From gagsl-py2 at yahoo.com.ar Sat Aug 1 00:04:27 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 01 Aug 2009 01:04:27 -0300 Subject: problem on socket programming References: <3de0863c-15ef-4153-8d0f-6b7a438b98f5@c2g2000yqi.googlegroups.com> <67ec3e6d-0995-459a-a7a5-3bc296729664@b15g2000yqd.googlegroups.com> <7dg2niF2bue0tU2@mid.uni-berlin.de> <5dbf451d-a289-40d1-83db-ce655d47f698@r38g2000yqn.googlegroups.com> <7dg55pF2bfubpU1@mid.uni-berlin.de> <72f851f9-a2d4-4448-900d-3fe20e4ebeb0@w41g2000yqb.googlegroups.com> Message-ID: En Fri, 31 Jul 2009 10:43:49 -0300, MalC0de escribi?: > none of you can't interpret it ? do you have errors like me !? Have you tried Diez B. Roggisch suggestion? : >> Can you ping and telnet to the port on the desired server? >> Firewalls can be an issue here. The official doc page for the socket module contains a working example of an echo client/server program like yours: http://docs.python.org/library/socket.html#example -- Gabriel Genellina From emmanuel.surleau at gmail.com Sat Aug 1 00:20:28 2009 From: emmanuel.surleau at gmail.com (Emmanuel Surleau) Date: Sat, 1 Aug 2009 06:20:28 +0200 Subject: Confessions of a Python fanboy In-Reply-To: <008f7990$0$9756$c3e8da3@news.astraweb.com> References: <008f7990$0$9756$c3e8da3@news.astraweb.com> Message-ID: <200908010620.28665.emmanuel.surleau@gmail.com> On Saturday 01 August 2009 03:46:12 Steven D'Aprano wrote: > On Fri, 31 Jul 2009 20:41:12 +0200, Emmanuel Surleau wrote: > >> We don't actually *declare* that something is constant and then have > >> that declaration ignored. Python doesn't lie to us, although (as in any > >> language) a programmer might. > > > > You could say that Ruby doesn't either, > > Well you could say a lot of things. Admittedly you don't need a separate > "constant" declaration, but creating a variable name with an initial > uppercase letter is sufficient to make it a (supposed) constant: *shrugs* I see it as a way to encourage (but not force) people to follow a coding convention. Is this such a bad thing? > irb(main):049:0* Thing = 5 > => 5 > irb(main):050:0> Thing = 7 > (irb):50: warning: already initialized constant Thing > => 7 > > As you can see, Ruby (well, irb at least) considers that Thing is a > constant, and then goes ahead and changes it anyway. I'm quite aware of how constants work in Ruby, yes :) > Apart from the use of an arbitrary naming convention instead of an > explicit "make this constant" declaration, and the feeble way Ruby > capitulates when you change it, I think having actual write-once > constants is actually a plus. Nothing wrong with naming conventions. This encourages a uniform coding style, something which Python could really use. > > you just need to read the > > documentation. Ruby's unwritten motto is "flexibility ?ber alles". In > > this regard, it is consistent (1). > > "It's consistent in its inconsistency" sort of thing perhaps? No, just consistent. > > Not much is really bolted down in > > Ruby. You get encapsulation, but it's so easy to break that it's mostly > > symbolic. > > Out of curiosity, can you read/write class and instance attributes from > outside the class without using a getter/setter? If you have an instance f class with a attribute @foo which doesn't have an accessor, you could do: f.instance_eval("@foo='bar'") And yes, instance_eval is evil. Cheers, Emm From gagsl-py2 at yahoo.com.ar Sat Aug 1 00:48:50 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 01 Aug 2009 01:48:50 -0300 Subject: Newbie Question regarding __init__() References: Message-ID: En Sat, 01 Aug 2009 00:13:05 -0300, Nat Williams escribi?: > One other thing. I'm a little confused by the first line of > dcObject.__init__: > > self.init_Pre() and self.init_Exec() > > I suspect this does not do what you think it does. init_Pre and > init_Exec > will both be called by this expression (unless init_Pre throws an > exception, > of course). You're not getting anything here that you wouldn't by just > calling each method on a separate line, except just making it harder to > read. Well, perhaps Simon didn't grasp Python's syntax and semantics very well yet, but his code would work as designed after fixing obvious errors: class dcObject(object): """Base Object""" def __init__(self): """default init method has the form of init_Pre() and init_Exec init_Post()""" self.init_Pre() and self.init_Exec() self.init_Post() def init_Pre(self): """Always called before init_Exec() if it returns false init_Exec is not executed""" return True def init_Exec(self): """Base __init__ code goes here and this is only executed if init_Pre() returns true""" return True def init_Post(self): """Always called after the init_Pre() and init_Exec()""" return True init_Pre might return False, in that case init_Exec would not be executed. init_Post is always called. And that's exactly what the docstrings say. I would use an `if` statement instead: if self.init_Pre(): self.init_Exec() and make init_Exec and init_Post not return anything if they have no intrinsic meaning. And probably use better names. But basically the structure is OK. -- Gabriel Genellina From nad at acm.org Sat Aug 1 00:55:34 2009 From: nad at acm.org (Ned Deily) Date: Fri, 31 Jul 2009 21:55:34 -0700 Subject: Python docs disappointing References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: In article , Terry Reedy wrote: > This is one area where Windows users seems to have an advantage. The > standard installer includes the doc set as a Windows help file. I often > keep that open in one window while programming in others. I only later > discovered that this was a copy of the online docs ;-), which I only use > to check the in-development version before submitting a doc bug. The python.org Mac OS X installers include the complete documentation set for that version in HTML; the IDLE Help menu will open the front page in a browser (from where you can bookmark it for later use). -- Ned Deily, nad at acm.org From riaz.ahmadskh at gmail.com Sat Aug 1 03:02:51 2009 From: riaz.ahmadskh at gmail.com (Riaz Ahmad) Date: Sat, 1 Aug 2009 00:02:51 -0700 (PDT) Subject: "ADMISSION IN FA FSC" "ADMISSION IN FA/FSC" "ADMISSION IN GC UNIVERSITY LAHORE" "ADMISSION IN SCIENCE COLLEGE LAHORE" "ADMISSION IN KIPS LAHORE" "ADMISSION IN LEADERSHIP COLLEGE LAHORE" "ADMISSION IN BAHAUDDIN ZAKARIYA UNIVERSITY MULTAN" Message-ID: <38954c7f-1af5-4739-8982-6193b280d4da@d36g2000prb.googlegroups.com> "ADMISSION IN FA FSC" www.admissionspk.blogspot.com "ADMISSION IN FA/FSC" www.admissionspk.blogspot.com "ADMISSION IN GC UNIVERSITY LAHORE" www.admissionspk.blogspot.com "ADMISSION IN SCIENCE COLLEGE LAHORE" www.admissionspk.blogspot.com "ADMISSION IN KIPS LAHORE" www.admissionspk.blogspot.com "ADMISSION IN LEADERSHIP COLLEGE LAHORE" www.admissionspk.blogspot.com "ADMISSION IN BAHAUDDIN ZAKARIYA UNIVERSITY MULTAN" www.admissionspk.blogspot.com www.admissionspk.blogspot.com From robertrobert93 at yahoo.com Sat Aug 1 03:34:58 2009 From: robertrobert93 at yahoo.com (Robert Robert) Date: Sat, 1 Aug 2009 00:34:58 -0700 (PDT) Subject: fil open close very slow Message-ID: <950181.91001.qm@web59306.mail.re1.yahoo.com> hiya all, I have a "large" script written in python. There is in that big script at a certain point a loop in which I create a lots of simple small text files. Each text file just contain I think 4 or 5 short lines. When I simply run it in IDLE, it runs fast. But when?I compile it to binary files, it becomes very slow. I turned on the profiler and discorvered it was slow at the open() and close() calls. I removed those calls to confirm this, and yes my program runs very fast then. Does anyone has an idea or suggestion why this can be possible. I only compile them to .pyc files, which as what I see, when I normally run in IDLe these files are created as well, so I really got no clue. rh. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Sat Aug 1 03:53:51 2009 From: rt8396 at gmail.com (r) Date: Sat, 1 Aug 2009 00:53:51 -0700 (PDT) Subject: possible to round number and convert to string? References: <24763821.post@talk.nabble.com> <4a737350$0$28514$4fafbaef@reader2.news.tin.it> Message-ID: <4e60ee41-44a2-4e23-b3dd-70a8549026e0@a13g2000yqc.googlegroups.com> On Jul 31, 7:42?pm, "Dr. Phillip M. Feldman" wrote: > This was very close to what I wanted. ?Thanks! ?My final code looks like > this: > > def num2str(x,f=4): > ? ?"""Convert x (int or float) to a string with f digits to right of > ? ?the decimal point. ?f may be zero or negative, in which case the decimal > ? ?point is suppressed.""" > ? ?s= str(round(x,f)) > ? ?if f<=0: > ? ? ? # Delete decimal point: > ? ? ? i= s.find('.') > ? ? ? if i>0: s= s[:i] > ? ?return s Is it *really* necessary to create a named function for something as trivial as this? >>> import math >>> '%0.3f' %math.pi '3.142' >>> '%d' %math.pi '3' Seems string formatting is more "pythonic" -- opps, now why did i have to go and say that... :) From dickinsm at gmail.com Sat Aug 1 04:36:11 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 1 Aug 2009 01:36:11 -0700 (PDT) Subject: possible to round number and convert to string? References: Message-ID: On Jul 31, 11:17?pm, "Dr. Phillip M. Feldman" wrote: > I'd like to be able to convert a float to a string representation in which > the number is rounded to a specified number of digits. ?If num2str is a > hypothetical function that does this, then num2str(pi,3) would be '3.142' > (not '3.141'). Python's string formatting does exactly this. Python 2.6.2 (r262:71600, Jul 8 2009, 09:56:31) [GCC 4.0.1 (Apple Inc. build 5490)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> num2str = '{0:.{1}f}'.format >>> num2str(3.14159, 3) '3.142' (In Python 3.1, num2str = '{:.{}f}'.format is enough.) Mark From john_re at fastmail.us Sat Aug 1 04:52:28 2009 From: john_re at fastmail.us (john_re) Date: Sat, 01 Aug 2009 01:52:28 -0700 Subject: Aug 1 & 16- Global VOIP Free SW HW Culture meeting, BerkeleyTIP, For Forwarding Message-ID: <1249116748.25769.1327808157@webmail.messagingengine.com> Interested in joining the friendly global Free SW HW & Culture communities in a global Voice meeting? You?re invited. :) You can join from your home, or better: get a local meeting together. Tip: a college WiFi cafe could be a great local meeting place. Make sure you have a VOIP headset! For all details, see the website (I?m leaving out many sublinks to make this email smaller). http://sites.google.com/site/berkeleytip Start by joining #berkeleytip on IRC freenode.net. We?ll help you get your VOIP connection working. :) ===== MARK YOUR CALENDARS: 1st Sat & 3rd Sunday each month. August 1 & 16. 10A - 6P Pacific US time (+7H GMT, IIRC) = 1P-9P Eastern US time = 5P - 1A GMT ? Or, come to the local meeting on the UC Berkeley campus. NOTE: SPECIAL LOCATION AUG 1: SEE BTIP WEBSITE FOR LOCATION, & RSVP TO ME OR THE BTIP LISTS. AUG 1 MEETING WILL BE 12N - 3P AT THE BTIP VOIP SERVER LOCATION ON THE UCB CAMPUS. SEE THE WEBSITE FOR ROOM LOCATION. We?ll hack on the new BTIP Asterisk VOIP server, in its presence. PLEASE RSVP TO ME (John) OR THE LIST IF YOU WANT TO MEET AT OUR USUAL LOCATION, THE FREE SPEECH CAFE, 10A-12n, 3-6PM, (otherwise i might not be there). ===== MEETING TOPICS FOR AUGUST: 1) Whatever _you_ want to work on - Email the BTIPGlobal list & let us know what your interests are. 2) Our VOIP conference server, using Asterisk. 3) Planning for year 2. ===== JOIN FOR THE START OF YEAR 2 GLOBAL MEETINGs: We had a great first year. We had local attendees from around the San Francisco Bay Area & Northern California. High School, College, Grad Students, & working & retired people attended. >From the US, people joined the meeting (IRC or VOIP) from Hawaii to Virgina, Washington to Michigan to Florida. (+ California & other states.) Globally, Sweden, Germany, England, Ireland, Iran & India (& maybe others I don?t recall right now.) :) In May Richard Stallman joined the global meeting for Q & A about free SW & HW. == YEAR 2 FOCUS: COLLEGE LOCAL MEETINGS, & AMERICAS? ANNOUNCEMENTS. Two main things I?ll focus on this year: 1) Inviting groups to join at colleges & universities - BTIP is educational. My hope: if more students learn about free SW hw & culture, some of them will then go on to become _contributors_. :) 2) I?ll try to get monthly announcements out to the biggest LUGs in the 10 largest countries in the Americas. == What would _YOU_ like to accomplish this year? Email the BTIP mail list, say ?hi?, tell us about your interests, projects & desires. ===== FOR FORWARDING - You are invited to forward this announcement wherever you think it might be appreciated. From hitechpundir at gmail.com Sat Aug 1 05:22:28 2009 From: hitechpundir at gmail.com (sirjee) Date: Sat, 1 Aug 2009 02:22:28 -0700 (PDT) Subject: problem in event handling on change of variable value. Message-ID: <9c0d7a31-0310-4499-9974-92afc588f315@d15g2000prc.googlegroups.com> hello; i m facing a problem in handling events on change of value of environment variable in a tool CANoe. class CANoeEvents: def OnChange(self,value): print "value of environment variable has changed" def OnOpen(self,App): print "opening Application" App_Event = DispatchWithEvents('CANoe.Application',CANoeEvents) time.sleep(2) App_Event.Open("C:\projectConfig.cfg") # printd "opening Application" and event handled properly. .......(now a code file runs in the canoe in which value of environment variable called dummy is changed during execution. Just like OnOpen; OnChange is defined in specification which should be called on change of environment variable.But it is not happening.) while (): myenvVar = App_Event.Environment.GetVariable("dummy") The VB does it very easily and defines a subroutine called : Sub myenvVar _OnChange(value) print "value of environment variable has changed" End Sub //////////////////////////////////////////////////however the alternative for subroutine for OnOpen in VB (defined below) works fine as shown above in python. Sub AppEvent_OnOpen(App) print "opening Application" End Sub for VB; all this stuff is cake work.... object_eventname subroutine and done.....what in python? From paul at subsignal.org Sat Aug 1 05:28:32 2009 From: paul at subsignal.org (paul) Date: Sat, 01 Aug 2009 11:28:32 +0200 Subject: socket policy flash help In-Reply-To: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> Message-ID: NighterNet schrieb: > I need help on the policy to able to let access to user to the server > once the policy access is finish. I been trying to find a good > example, but I got no luck. Using python version 3.1. > > Here the code I tested but it not working. > > if str(buff) == str("b\'\\x00\'"): > print ('policy FOUND >>> sending...') > rawinput = str(' access-from domain=\"*\" to-ports=\"*\" />') > print (rawinput) > b = bytes ( ord(c) for c in rawinput) > self.sockfd.send(b); And the error is? Doesn't Flash use http as transport? cheers Paul From davea at ieee.org Sat Aug 1 05:52:11 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 01 Aug 2009 05:52:11 -0400 Subject: Newbie Question regarding __init__() In-Reply-To: References: Message-ID: <4A74104B.7080403@ieee.org> Nat Williams wrote: > As MRAB described, ALL instance methods need to accept 'self' as a first > parameter, as that will be passed to them implicitly when they are called. > This includes __init__. The name 'self' is just a commonly accepted > convention for the name of the instance object passed to methods. You don't > have to call it that, but you really should. > > Take a look at http://docs.python.org/tutorial/classes.html#class-objects > It might help shed some light on how methods and instances work. > > One other thing. I'm a little confused by the first line of > dcObject.__init__: > > self.init_Pre() and self.init_Exec() > > I suspect this does not do what you think it does. init_Pre and init_Exec > will both be called by this expression (unless init_Pre throws an exception, > of course). You're not getting anything here that you wouldn't by just > calling each method on a separate line, except just making it harder to > read. > > Read the doc-string for init_Pre() and for init_Exec(). The final version of init_Pre() will return False in some circumstances, and in those circumstances Simon doesn't want init_Exec() to be called. He's deliberately using the short-circuit evaluation of 'and' to accomplish that. > > On Fri, Jul 31, 2009 at 8:53 PM, Simon wrote: > > >> Hi >> >> So should the dcObject class include the "self" as well since I have >> not defined an __init__ method in dcCursor? >> >> Simon >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > Every one of those methods in both of those classes need a "self" first argument. As others have said, all instance methods need a 'self.' From vinay_sajip at yahoo.co.uk Sat Aug 1 05:57:13 2009 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Sat, 1 Aug 2009 02:57:13 -0700 (PDT) Subject: Confused About Python Loggin References: <534A6695-37D9-4200-9872-9E844AE50681@cs.ucl.ac.uk> <14CCA71D-F575-4B8A-8C99-67BDAAC2C6E0@cs.ucl.ac.uk> Message-ID: On Jul 31, 2:04?pm, Jean-Michel Pichavant wrote: > Jannik Sund? wrote: > > Hi all. I think I fixed this problem by setting fileLogger.propagate = > > 0. Otherwise it will propagate up to the root logger, which outputs to > > stdout, as far as I can understand. > > > On 31 Jul 2009, at 01:17, Jannik Sund? wrote: > > >> Dear all, I am quite confused about the Pythonlogging. I have read > >> and re-read the Python documentation for the Pythonloggingmodule > >> and googled, but to no avail. I simply want one logger to log to a > >> file and another logger to log to the console. Neither should log the > >> other's messages. The code below causes fileLogger to log to BOTH a > >> file and the console, how come? It seems to me that a call such as > >> "consoleHandler =logging.StreamHandler()" affects other loggers, > >> which I do not want. Also, if I do not do > >>logging.basicConfig(level=logging.INFO) in one of the classes of my > >> application, theloggingdoes not work. Any ideas how come? > > >> Thanks a lot for any help! :) > > >> fileHandler =logging.FileHandler('../../logs/log.txt') > >> fileLogger =logging.getLogger('TESTHARNESSFILE') > >> fileLogger.addHandler(fileHandler) > >> fileLogger.setLevel(logging.INFO) > >> consoleHandler =logging.StreamHandler() > >> logger =logging.getLogger('TESTHARNESS') > >> logger.addHandler(consoleHandler) > >> logger.setLevel(logging.INFO) > > > --http://mail.python.org/mailman/listinfo/python-list > > Please do not top post :o) > > Are sure you have used the code provided above ? > Loggers only propagate events to its parent. > > fileLogger =logging.getLogger('TESTHARNESSFILE" > logger =logging.getLogger('TESTHARNESS') > Those one have no parent relationship. > > However these one have parent relationship: > fileLogger =logging.getLogger('TESTHARNESS.FILE") # note the dotted name > logger =logging.getLogger('TESTHARNESS') > > Or maybe you have added a handler to the root logger... > > Using the propagate attribute is correct only between 2 loggers that are > meant to be parents. > > JM What you say is true, Jean-Michel, but the OP might be meaning the parent-child relationship both his loggers have with the mother of all loggers - the root logger ;-) Regards, Vinay Sajip From piet at cs.uu.nl Sat Aug 1 07:52:16 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 01 Aug 2009 13:52:16 +0200 Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> Message-ID: >>>>> NighterNet (N) wrote: >N> I need help on the policy to able to let access to user to the server >N> once the policy access is finish. I been trying to find a good >N> example, but I got no luck. Using python version 3.1. >N> Here the code I tested but it not working. >N> if str(buff) == str("b\'\\x00\'"): What is buff supposed to contain here? I assume a byte sequence? Do you reaaly mean that buff[0] contains the byte 'b' and buff[1] contains a single quote? And the last byte also a single quote? And the four bytes with \ x 0 0 before that instead of a null byte? In total 29 bytes? Or did you mean just the 23 bytes long b'\x00'? Maybe it should be if buff == b'\x00': >N> print ('policy FOUND >>> sending...') >N> rawinput = str('') The str here is unnecessary as you have already a string. >N> print (rawinput) >N> b = bytes ( ord(c) for c in rawinput) Why not b = b'' ? >N> self.sockfd.send(b); -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From tarundevnani at gmail.com Sat Aug 1 09:32:53 2009 From: tarundevnani at gmail.com (tarun) Date: Sat, 1 Aug 2009 19:02:53 +0530 Subject: How to read webpage Message-ID: Dear All,I want to read a webpage and copy the contents of it in word file. I tried to write following code: import urllib2 urllib2.urlopen("http://www.rediff .com/") *Error:-* urllib2.urlopen("http://www.icicibank.com/") File "C:\Python25\lib\urllib2.py", line 121, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 374, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 392, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1100, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1075, in do_open raise URLError(err) urllib2.URLError: -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sat Aug 1 09:52:17 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 01 Aug 2009 14:52:17 +0100 Subject: How to read webpage In-Reply-To: References: Message-ID: <4A744891.7050808@mrabarnett.plus.com> tarun wrote: > Dear All, > I want to read a webpage and copy the contents of it in word file. I > tried to write following code: > > import urllib2 > urllib2.urlopen("http://www.rediff.com/") > > *Error:-* > > urllib2.urlopen("http://www.icicibank.com/") > File "C:\Python25\lib\urllib2.py", line 121, in urlopen > return _opener.open(url, data) > File "C:\Python25\lib\urllib2.py", line 374, in open > response = self._open(req, data) > File "C:\Python25\lib\urllib2.py", line 392, in _open > '_open', req) > File "C:\Python25\lib\urllib2.py", line 353, in _call_chain > result = func(*args) > File "C:\Python25\lib\urllib2.py", line 1100, in http_open > return self.do_open(httplib.HTTPConnection, req) > File "C:\Python25\lib\urllib2.py", line 1075, in do_open > raise URLError(err) > urllib2.URLError: > I've just tried it. I didn't get an exception, so your problem must be elsewhere. From koranthala at gmail.com Sat Aug 1 11:19:28 2009 From: koranthala at gmail.com (koranthala) Date: Sat, 1 Aug 2009 08:19:28 -0700 (PDT) Subject: How to read webpage References: Message-ID: <67de4ef0-0da7-47e6-8e2e-23be4a6b452c@t11g2000prh.googlegroups.com> On Aug 1, 6:52?pm, MRAB wrote: > tarun wrote: > > Dear All, > > I want to read a webpage and copy the contents of it in word file. I > > tried to write following code: > > > import urllib2 > > urllib2.urlopen("http://www.rediff.com/") > > > *Error:-* > > > ? ? urllib2.urlopen("http://www.icicibank.com/") > > ? File "C:\Python25\lib\urllib2.py", line 121, in urlopen > > ? ? return _opener.open(url, data) > > ? File "C:\Python25\lib\urllib2.py", line 374, in open > > ? ? response = self._open(req, data) > > ? File "C:\Python25\lib\urllib2.py", line 392, in _open > > ? ? '_open', req) > > ? File "C:\Python25\lib\urllib2.py", line 353, in _call_chain > > ? ? result = func(*args) > > ? File "C:\Python25\lib\urllib2.py", line 1100, in http_open > > ? ? return self.do_open(httplib.HTTPConnection, req) > > ? File "C:\Python25\lib\urllib2.py", line 1075, in do_open > > ? ? raise URLError(err) > > urllib2.URLError: > > I've just tried it. I didn't get an exception, so your problem must be > elsewhere. Is it that the website expects a valid browser? In that case, spoof a browser and try to get the site. From joncle at googlemail.com Sat Aug 1 11:31:09 2009 From: joncle at googlemail.com (Jon Clements) Date: Sat, 1 Aug 2009 08:31:09 -0700 (PDT) Subject: How to read webpage References: Message-ID: <7690d42e-ea99-4aec-9029-5cfae119ffcf@o32g2000yqm.googlegroups.com> On 1 Aug, 14:52, MRAB wrote: > tarun wrote: > > Dear All, > > I want to read a webpage and copy the contents of it in word file. I > > tried to write following code: > > > import urllib2 > > urllib2.urlopen("http://www.rediff.com/") > > > *Error:-* > > > ? ? urllib2.urlopen("http://www.icicibank.com/") > > ? File "C:\Python25\lib\urllib2.py", line 121, in urlopen > > ? ? return _opener.open(url, data) > > ? File "C:\Python25\lib\urllib2.py", line 374, in open > > ? ? response = self._open(req, data) > > ? File "C:\Python25\lib\urllib2.py", line 392, in _open > > ? ? '_open', req) > > ? File "C:\Python25\lib\urllib2.py", line 353, in _call_chain > > ? ? result = func(*args) > > ? File "C:\Python25\lib\urllib2.py", line 1100, in http_open > > ? ? return self.do_open(httplib.HTTPConnection, req) > > ? File "C:\Python25\lib\urllib2.py", line 1075, in do_open > > ? ? raise URLError(err) > > urllib2.URLError: > > I've just tried it. I didn't get an exception, so your problem must be > elsewhere. I'm hoping this adds to MRAB's reply; it is intended however for the OP. Jeeze -- been a while since I've had to deal with Sockets (directly anyway). If memory serves correctly, it's where the system can't name resolve the required address. So best guess is it's either a temporary glitch, or an issue with your routing. Jon. Jon. From darkneter at gmail.com Sat Aug 1 11:34:57 2009 From: darkneter at gmail.com (NighterNet) Date: Sat, 1 Aug 2009 08:34:57 -0700 (PDT) Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> Message-ID: <8bede581-f260-4c69-abf0-1e8071380b76@z4g2000prh.googlegroups.com> On Aug 1, 4:52?am, Piet van Oostrum wrote: > >>>>> NighterNet (N) wrote: > >N> I need help on the policy to able to let access to user to the server > >N> once the policy access is finish. I been trying to find a good > >N> example, but I got no luck. Using python version 3.1. > >N> Here the code I tested but it not working. > >N> if str(buff) == str("b\'\\x00\'"): > > What is buff supposed to contain here? I assume a byte sequence? > Do you reaaly mean that buff[0] contains the byte 'b' and buff[1] > contains a single quote? And the last byte also a single quote? And the > four bytes with \ x 0 0 before that instead of a null byte? In total 29 bytes? > > Or did you mean just the 23 bytes long b'\x00'? > > Maybe it should be if buff == b'\x00': > > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ('policy FOUND >>> sending...') > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? rawinput = str('') > > The str here is unnecessary as you have already a string. > > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print (rawinput) > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? b = bytes ( ord(c) for c in rawinput) > > Why not > b = b'' ? > > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.sockfd.send(b); > > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org I try that method and flash socket is not getting the policy. b = b'' self.sockfd.send(b); server = socket.socket( socket.AF_INET, socket.SOCK_STREAM) When it able to read the policy it send it but it fail to send to flash some reason and send it again and then d/c. From marcusw at cox.net Sat Aug 1 11:43:15 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sat, 01 Aug 2009 11:43:15 -0400 Subject: How to read webpage In-Reply-To: <7690d42e-ea99-4aec-9029-5cfae119ffcf@o32g2000yqm.googlegroups.com> References: <7690d42e-ea99-4aec-9029-5cfae119ffcf@o32g2000yqm.googlegroups.com> Message-ID: On 8/1/2009 11:31 AM, Jon Clements wrote: > On 1 Aug, 14:52, MRAB wrote: >> tarun wrote: >>> Dear All, >>> I want to read a webpage and copy the contents of it in word file. I >>> tried to write following code: >>> import urllib2 >>> urllib2.urlopen("http://www.rediff.com/") >>> *Error:-* >>> urllib2.urlopen("http://www.icicibank.com/") >>> File "C:\Python25\lib\urllib2.py", line 121, in urlopen >>> return _opener.open(url, data) >>> File "C:\Python25\lib\urllib2.py", line 374, in open >>> response = self._open(req, data) >>> File "C:\Python25\lib\urllib2.py", line 392, in _open >>> '_open', req) >>> File "C:\Python25\lib\urllib2.py", line 353, in _call_chain >>> result = func(*args) >>> File "C:\Python25\lib\urllib2.py", line 1100, in http_open >>> return self.do_open(httplib.HTTPConnection, req) >>> File "C:\Python25\lib\urllib2.py", line 1075, in do_open >>> raise URLError(err) >>> urllib2.URLError: >> I've just tried it. I didn't get an exception, so your problem must be >> elsewhere. > > I'm hoping this adds to MRAB's reply; it is intended however for the > OP. > > Jeeze -- been a while since I've had to deal with Sockets (directly > anyway). > If memory serves correctly, it's where the system can't name resolve > the required address. > So best guess is it's either a temporary glitch, or an issue with your > routing. > > Jon. > Jon. 'getaddrinfo failed' means that the nameserver can't be found, or that it has no records of that address (I'm 90% sure of that). Marcus From nobody at nowhere.com Sat Aug 1 13:11:18 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 01 Aug 2009 18:11:18 +0100 Subject: Python docs disappointing References: Message-ID: On Fri, 31 Jul 2009 20:10:45 +0000, kj wrote: > I'm pretty new to Python, and I like a lot overall, but I find the > documentation for Python rather poor, overall. FWIW, I find the module documentation to be mostly adequate. What's missing is a human-readable language *manual*. The tutorial omits too much; the language reference may be fine for language lawyering, but it's not much use otherwise. From MatzeGuentert at gmx.de Sat Aug 1 13:16:14 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Sat, 01 Aug 2009 19:16:14 +0200 Subject: M2Crypto: AttributeError: 'CSR' object has no attribute 'pkey' Message-ID: <1249146974.3330.1.camel@celsius> Hello python-guys I am trying to build a python based certificate authority using m2crypto. I am quite new to python and I am asking myself why my code snippets below throw the following Traceback: $ python csr.py ...++++++++++++ ...............++++++++++++ Traceback (most recent call last): File "csr.py", line 48, in csr.create_cert_signing_request(pubkey, cert_name) File "csr.py", line 17, in create_cert_signing_request cert_request.set_pubkey(keypair) File "/usr/lib64/python2.6/site-packages/M2Crypto/X509.py", line 926, in set_pubkey return m2.x509_req_set_pubkey( self.req, pkey.pkey ) AttributeError: 'CSR' object has no attribute 'pkey' Bellow are my modules containing two classes CSR and Keypair. There seems to be something wrong in the way I am calling csr.create_cert_signing_request(), because if I directly add the key generation part to the create_cert_singing_request function it works... http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.X509.Request-class.html#set_pubkey This link states out, that the instance function set_pubkey takes an EVP_KEY object as argument, and thats what I am passing to it, or not? I really would be happy if someone could give me a helping hand on this and maybe could comment every style / ... mistake I made to accelerate my learning experience. Thanks, Matthias $ cat csr.py from config import * from keypair import * from M2Crypto import X509, EVP class CSR(object): def __init__(self): pass def create_cert_signing_request(keypair, cert_name, cert_extension_stack=None): # create a certificate signing request object cert_request = X509.Request() # set certificate version to 3 cert_request.set_version(3) # which rsa public key should be used? cert_request.set_pubkey(keypair) # create an subject for the certificate request cert_request.set_subject_name(cert_name) if cert_extension_stack != None: # add the extensions to the request cert_request.add_extensions(cert_extension_stack) # sign the request using the RSA key pair cert_request.sign(keypair, 'sha1') return cert_request if __name__ == "__main__": csr = CSR() cert_name = X509.X509_Name() keyp = Keypair() keyp.create_keypair() keyp.save_keypair("host.key") pubkey = keyp.get_keypair() cert_name.C = "GB" cert_name.ST = "Greater Manchester" cert_name.L = "Salford" cert_name.O = "COMODO CA Limited" cert_name.CN = "COMODO Certification Authority" cert_name.OU = "Information Technology" cert_name.Email = "contact at comodo.com" csr.create_cert_signing_request(pubkey, cert_name) $ cat keypair.py from M2Crypto import X509, m2, RSA, EVP from config import * class Keypair(object): def __init__(self): self.config = Config() self.keypair = EVP.PKey() def create_keypair(self): # generate an RSA key pair # OpenSSL book page 232 # second argument should be a constant RSA_F4 or RSA_3 rsa_key_pair = RSA.gen_key(int(self.config.get_attribute('CA','key_size')), m2.RSA_F4) # check if RSA key pair is usable # OpenSSL book page 232 if rsa_key_pair.check_key() != 1: print 'error while generating key!' sys.exit() # EVP object which can hold either a DSA or an RSA object # OpenSSL book page 236 evp_key_container = EVP.PKey() evp_key_container.assign_rsa(rsa_key_pair) self.keypair = evp_key_container def save_keypair(self, filename): self.keypair.save_key(filename, None) def load_keypair(self, filename): self.keypair = EVP.load_key(filename) def get_keypair(self): return self.keypair def get_public_key(self): return self.keypair.pkey def print_keypair(self): print self.keypair.as_pem(None) if __name__ == "__main__": key = Keypair() key.create_keypair() key.save_keypair("test.key") print key.get_keypair() print key.get_public_key() From enleverLesX_XXmcX at XmclavXeauX.com Sat Aug 1 13:20:35 2009 From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP) Date: Sat, 01 Aug 2009 19:20:35 +0200 Subject: os.path.exists() and Samba shares References: Message-ID: <4a747965$0$23487$ba4acef3@news.orange.fr> Hi! > SAMBA is a Linux implementation of the SMB protocol, natively supported on Windows. Right. But, with Vista or Seven, only recents releases of Samba are supported. And, Samba know only NTLM release 2 (in register: HKLM\SYSTEM\CurrentControlSet\Control\Lsa value LMCompatibilityLevel ; set 1 or 0. ) @-salutations -- Michel Claveau From justindecell at gmail.com Sat Aug 1 14:07:15 2009 From: justindecell at gmail.com (Justin DeCell) Date: Sat, 1 Aug 2009 11:07:15 -0700 Subject: Queryable Daemon Message-ID: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Hi All, I was hoping for a little help with a project I'm working on. I'm writing a daemon in python that I want to be queryable (i.e. I should be able to run foo -s and it will report some internal information about the foo daemon if it's running) but I can't figure out a way get information from that process from an external process. I was thinking that there should be a way to open a file descriptor, have the daemon write to that every so often and then have the query process just read from that fd but it looks like on the process reading from an fd has to be a child of the daemon for this to work. The only other way I thought of would be to write to a file on disk every so often from the daemon and just read the from the query process but it seems like there should be a more elegant way to do this... By the way I'm writing this for unix only so there's no need to worry about compatibility with other os'. Thanks, -Justin -------------- next part -------------- An HTML attachment was scrubbed... URL: From luke.leighton at googlemail.com Sat Aug 1 14:07:51 2009 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 1 Aug 2009 11:07:51 -0700 (PDT) Subject: JavaScript toolkits (was Re: ANN: Porcupine Web Application Server 0.6 is released!) References: Message-ID: <01133210-f03b-4a71-aa9e-d69fe44ac9a5@r38g2000yqn.googlegroups.com> On Jul 20, 4:00 pm, a... at pythoncraft.com (Aahz) wrote: > Out of curiosity, are there anyJavaScripttoolkits or python-to-javascript compilers > that generate code > that degrades gracefully whenJavaScriptis disabled? http://advogato.org/article/981.html you'll need to do a little bit of work - use a state-machine-based framework (such as twisted, from what i can gather), or use fastcgi, or solve the problem of storing the state of the pyjamas application "in between" web requests - but yes, pyjamas-web is a port of pyjamas to the web server. so, by writing an app that conforms to the pyjamas API, you get to compile it to native javascript, to run in the web browser; you get to run it as pure python using pyjamas-desktop (python-hulahop underneath or pywebkitgtk) and then, if you want to finish off the experiment that i started, you get to run the _same_ python app server-side on behalf of the users. all quite quite mad, to be honest :) l. From luke.leighton at googlemail.com Sat Aug 1 14:11:02 2009 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 1 Aug 2009 11:11:02 -0700 (PDT) Subject: JavaScript toolkits (was Re: ANN: Porcupine Web Application Server 0.6 is released!) References: <1c994086-8c58-488f-b3b3-6161c4b2ba05@k30g2000yqf.googlegroups.com> Message-ID: <2a2f05af-a87e-44bf-8d36-774697dbd794@c29g2000yqd.googlegroups.com> On Jul 21, 12:55 pm, Paul Boddie wrote: > On 20 Jul, 18:00, a... at pythoncraft.com (Aahz) wrote: > > > > > Out of curiosity, are there anyJavaScripttoolkits that generate code > > that degrades gracefully whenJavaScriptis disabled? > > You mean "Web toolkits which useJavaScript", I presume. I have > written (and use myself) a toolkit/framework called XSLForms (part of > the XSLTools distribution) which supports in-page updates (AJAX, > effectively) that degrade to vanilla whole-page requests ifJavaScript > is switched off: yeahhh.... i remember doing something like that. each portion of the page i did as a separate AJAX load, and then there was some loader- infrastructure where you could, if javascript was switched off, do a tree-walk-reconstruction of the page. if anyone's interested i can provide source code. l. From hjtoi-better-remove-before-reply at comcast.net Sat Aug 1 14:19:13 2009 From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen) Date: Sat, 01 Aug 2009 11:19:13 -0700 Subject: M2Crypto: AttributeError: 'CSR' object has no attribute 'pkey' References: Message-ID: Matthias G?ntert wrote: > class CSR(object): > def __init__(self): > pass > > def create_cert_signing_request(keypair, cert_name, > cert_extension_stack=None): You missed self. Although this method does not seem to be using any instance data so there isn't actually much reason to have a CSR object unless you intend to expand it in ways that require it. > if cert_extension_stack != None: A word of advice: always check equality/inequality to None with 'is', because that way it is a straight pointer conversion which is faster and won't cause any surprises. In other words, write the above as: if cert_extension_stack is not None: -- Heikki Toivonen - http://heikkitoivonen.net From jkn_gg at nicorp.f9.co.uk Sat Aug 1 15:01:32 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Sat, 1 Aug 2009 12:01:32 -0700 (PDT) Subject: Python docs disappointing References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: On Aug 1, 4:18?am, Terry Reedy wrote: > This is one area where Windows users seems to have an advantage. The > standard installer includes the doc set as a Windows help file. I often > keep that open in one window while programming in others. I only later > discovered that this was a copy of the online docs ;-), which I only use > to check the in-development version before submitting a doc bug. The ActiveState distribution also includes the doc set as a CHM file (the canonical version didn't used to; one reason why I've used ActiveState in the past). I run a dual-boot system and have used a CHM (Windows Compiled help file format) viewer under Linux to read the Windows help file. This has been pretty handy in the past. Unfortunately, the combination of the python 2.6 CHM helpfile style, and the KChmViewer application gives me body text which is almost unreadable (black text on dark blue background). I'm not sure if this a bug in KChmViewer but it's pretty annoying. Anyone else see this? J^n From python at mrabarnett.plus.com Sat Aug 1 15:32:21 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 01 Aug 2009 20:32:21 +0100 Subject: Queryable Daemon In-Reply-To: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> References: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Message-ID: <4A749845.4020208@mrabarnett.plus.com> Justin DeCell wrote: > Hi All, > > I was hoping for a little help with a project I'm working on. I'm > writing a daemon in python that I want to be queryable (i.e. I should > be able to run foo -s and it will report some internal information about > the foo daemon if it's running) but I can't figure out a way get > information from that process from an external process. I was thinking > that there should be a way to open a file descriptor, have the daemon > write to that every so often and then have the query process just read > from that fd but it looks like on the process reading from an fd has to > be a child of the daemon for this to work. The only other way I thought > of would be to write to a file on disk every so often from the daemon > and just read the from the query process but it seems like there should > be a more elegant way to do this... > > By the way I'm writing this for unix only so there's no need to worry > about compatibility with other os'. > Instead of a file descriptor, how about a socket? A certain port at "127.0.0.1"? From mail at timgolden.me.uk Sat Aug 1 15:32:31 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 01 Aug 2009 20:32:31 +0100 Subject: Python docs disappointing In-Reply-To: References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: <4A74984F.9010805@timgolden.me.uk> jkn wrote: > The ActiveState distribution also includes the doc set as a CHM file > (the canonical version didn't used to; one reason why I've used > ActiveState in the past). It has done for quite some while now: Python 2.3 was the first and that was released, what, six years ago. Still, you're right; it used to use plain HTML. > Unfortunately, the combination of the python 2.6 CHM helpfile style, > and the KChmViewer application gives me body text which is almost > unreadable (black text on dark blue background). I'm not sure if this > a bug in KChmViewer but it's pretty annoying. Anyone else see this? This was noised about when the new-style docs were first released. Somehow (I don't run Linux usually) I had the impression it had been fixed; presumably not. However, rebuilding the docs is not at all hard: you just need a Python installation and the HTMLHelp Workshop. Then you can fiddle about with the CSS to your heart's content. TJG From geomajor56 at gmail.com Sat Aug 1 15:39:12 2009 From: geomajor56 at gmail.com (Michael Savarese) Date: Sat, 1 Aug 2009 15:39:12 -0400 Subject: iterate lines with regex Message-ID: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> I'm a python newbie and I'm trying to test several regular expressions on the same line before moving on to next line. it seems to move on to next line before trying all regular expressions which is my goal. it only returns true for first regular expression does the curser have to be rest to beginning of line? If so, how would I do that. remember I'm new thanks in advance to any advice Mike S. the following is part of my code, readThis=open('c:/9320.txt','r') for line in readThis: try: thisKey = key.search(line).group(1) thisMap = map.search(line).group(1) thisParcel = parcel.search(line).group(1) except: continue -------------- next part -------------- An HTML attachment was scrubbed... URL: From jkn_gg at nicorp.f9.co.uk Sat Aug 1 15:44:14 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Sat, 1 Aug 2009 12:44:14 -0700 (PDT) Subject: Python docs disappointing References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: Hi Tim On Aug 1, 8:32?pm, Tim Golden wrote: > > > Unfortunately, the combination of the python 2.6 CHM helpfile style, > > and the KChmViewer application gives me body text which is almost > > unreadable (black text on dark blue background). I'm not sure if this > > a bug in KChmViewer but it's pretty annoying. Anyone else see this? > > This was noised about when the new-style docs were first released. > Somehow (I don't run Linux usually) I had the impression it had > been fixed; presumably not. However, rebuilding the docs is not > at all hard: you just need a Python installation and the > HTMLHelp Workshop. Then you can fiddle about with the CSS to > your heart's content. > The HTML form of the documents (on python.org) seem fine (dark text on a light background, with a 'light blue on dark blue' sidebar). I was guessing that the .CHM was intended to have the same style, and therefore there was a problem with either my viwer, or with the conversion. Is this not the case then? I've just checked using xchm, and this displays OK - but I don't think it's taking any notice of any styles. FWIW I'm running 4.0-r1; there is a later release but it's not yet available for my Gentoo distribution. Can you point me at any references to this bug in the Python release world please? Thanks J^n From jkn_gg at nicorp.f9.co.uk Sat Aug 1 15:47:50 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Sat, 1 Aug 2009 12:47:50 -0700 (PDT) Subject: Python docs disappointing References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: <5cdcdc4a-5dd5-4c0a-a7cd-cdd078f8c262@a13g2000yqc.googlegroups.com> update: if I set 'use KHTMLPart-based widget' instead of 'QTextBrowser- based Widget' to display HTML content in the application settings of KchmViewer, all is readable. Hurrah! I wonder if it is picing up some QT stylesheet I have lying around in an over-clever way... J^n From ml at well-adjusted.de Sat Aug 1 15:55:31 2009 From: ml at well-adjusted.de (Jochen Schulz) Date: Sat, 1 Aug 2009 21:55:31 +0200 Subject: iterate lines with regex In-Reply-To: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> Message-ID: <20090801195531.GH15902@wasteland.homelinux.net> Michael Savarese: > > for line in readThis: > try: > thisKey = key.search(line).group(1) > thisMap = map.search(line).group(1) > thisParcel = parcel.search(line).group(1) > except: > continue Why do you catch all exceptions in that loop? Remove the try-except clause including the 'continue' and a stacktrace will probybably tell you why your loop appears to do nothing. J. -- A passionate argument means more to me than a blockbuster movie. [Agree] [Disagree] -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 204 bytes Desc: Digital signature URL: From breamoreboy at yahoo.co.uk Sat Aug 1 16:08:14 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Aug 2009 21:08:14 +0100 Subject: iterate lines with regex In-Reply-To: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> Message-ID: Michael Savarese wrote: > I'm a python newbie and I'm trying to test several regular expressions on > the same line before moving on to next line. > it seems to move on to next line before trying all regular expressions which > is my goal. > it only returns true for first regular expression > does the curser have to be rest to beginning of line? If so, how would I do > that. > remember I'm new > thanks in advance to any advice > Mike S. > > the following is part of my code, > readThis=open('c:/9320.txt','r') > > for line in readThis: > try: > thisKey = key.search(line).group(1) > thisMap = map.search(line).group(1) > thisParcel = parcel.search(line).group(1) > except: > continue > > The bare except will hide any errors in the lines above it. Either catch errors that you expect or take the try-except out. -- Kindest regards. Mark Lawrence. From workitharder at gmail.com Sat Aug 1 16:42:16 2009 From: workitharder at gmail.com (Buck) Date: Sat, 1 Aug 2009 13:42:16 -0700 (PDT) Subject: Module updating plans for Python 3.1: feedparser, MySQLdb References: <4a739a96$0$1615$742ec2ed@news.sonic.net> Message-ID: I use MySQLdb quite a bit in my work. I could volunteer to help update it. Are there any particular bugs we're talking about or just a straight port to 3.0? --Buck On Jul 31, 6:32?pm, John Nagle wrote: > ? ? Any progress on updating feedparser and MySQLdb for Python 3.x in the > foreseeable future? > > ? ? Feedparser shouldn't be that hard; it's just that nobody is working on it. > MySQLdb is known to be hard, and that may be a while. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle From garabik-news-2005-05 at kassiopeia.juls.savba.sk Sat Aug 1 17:14:59 2009 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Sat, 1 Aug 2009 21:14:59 +0000 (UTC) Subject: Queryable Daemon References: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Message-ID: MRAB wrote: > Justin DeCell wrote: >> Hi All, >> ... >> The only other way I thought >> of would be to write to a file on disk every so often from the daemon >> and just read the from the query process but it seems like there should >> be a more elegant way to do this... >> >> By the way I'm writing this for unix only so there's no need to worry >> about compatibility with other os'. >> > Instead of a file descriptor, how about a socket? A certain port at > "127.0.0.1"? Or a Unix domain socket. Or let the demon catch signal, say SIGUSR1 and dump its state to a file. A bit easier programming that a socket, a bit less elegant. -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From saimapk81 at gmail.com Sat Aug 1 17:29:25 2009 From: saimapk81 at gmail.com (saima81) Date: Sat, 1 Aug 2009 14:29:25 -0700 (PDT) Subject: "PAK WEB PAGES" "PAK WEB SITES" "PAK WEB PAGES" "PAK WEB SITES" "PAK WEB PAGES" "PAK WEB SITES" ON www.pak-web-pages.blogspot.com Message-ID: "PAK WEB PAGES" www.pak-web-pages.blogspot.com "PAK WEB SITES" www.pak-web-pages.blogspot.com "PAK WEB PAGES" www.pak-web-pages.blogspot.com "PAK WEB SITES" www.pak-web-pages.blogspot.com "PAK WEB PAGES" www.pak-web-pages.blogspot.com "PAK WEB SITES" www.pak-web-pages.blogspot.com ON www.pak-web-pages.blogspot.com www.pak-web-pages.blogspot.com From michael at altra-optics.co.uk Sat Aug 1 17:58:53 2009 From: michael at altra-optics.co.uk (Michael M Mason) Date: Sat, 1 Aug 2009 22:58:53 +0100 Subject: Newbie thwarted by sys.path on Vista Message-ID: <7djs50F2bsubuU1@mid.individual.net> I'm running Python 3.1 on Vista and I can't figure out how to add my own directory to sys.path. The docs suggest that I can either add it to the PYTHONPATH environment variable or to the PythonPath key in the registry. However, PYTHONPATH doesn't exist, and updating the registry key has no effect (and in any case the contents aren't the same as sys.path). So where does sys.path get its value from, and how do I change it? -- Michael From nytrokiss at gmail.com Sat Aug 1 19:01:45 2009 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 2 Aug 2009 02:01:45 +0300 Subject: How to read webpage In-Reply-To: References: <7690d42e-ea99-4aec-9029-5cfae119ffcf@o32g2000yqm.googlegroups.com> Message-ID: <8a6b8e350908011601v4d2ab86bp5618c6171cfb9a98@mail.gmail.com> Check your connection to the internet. On Sat, Aug 1, 2009 at 6:43 PM, Marcus Wanner wrote: > On 8/1/2009 11:31 AM, Jon Clements wrote: > >> On 1 Aug, 14:52, MRAB wrote: >> >>> tarun wrote: >>> >>>> Dear All, >>>> I want to read a webpage and copy the contents of it in word file. I >>>> tried to write following code: >>>> import urllib2 >>>> urllib2.urlopen("http://www.rediff.com/") >>>> *Error:-* >>>> urllib2.urlopen("http://www.icicibank.com/") >>>> File "C:\Python25\lib\urllib2.py", line 121, in urlopen >>>> return _opener.open(url, data) >>>> File "C:\Python25\lib\urllib2.py", line 374, in open >>>> response = self._open(req, data) >>>> File "C:\Python25\lib\urllib2.py", line 392, in _open >>>> '_open', req) >>>> File "C:\Python25\lib\urllib2.py", line 353, in _call_chain >>>> result = func(*args) >>>> File "C:\Python25\lib\urllib2.py", line 1100, in http_open >>>> return self.do_open(httplib.HTTPConnection, req) >>>> File "C:\Python25\lib\urllib2.py", line 1075, in do_open >>>> raise URLError(err) >>>> urllib2.URLError: >>>> >>> I've just tried it. I didn't get an exception, so your problem must be >>> elsewhere. >>> >> >> I'm hoping this adds to MRAB's reply; it is intended however for the >> OP. >> >> Jeeze -- been a while since I've had to deal with Sockets (directly >> anyway). >> If memory serves correctly, it's where the system can't name resolve >> the required address. >> So best guess is it's either a temporary glitch, or an issue with your >> routing. >> >> Jon. >> Jon. >> > > 'getaddrinfo failed' means that the nameserver can't be found, or that it > has no records of that address (I'm 90% sure of that). > > Marcus > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From luke.leighton at googlemail.com Sat Aug 1 19:19:55 2009 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 1 Aug 2009 16:19:55 -0700 (PDT) Subject: Calling functions: Why this complicated ? References: <89dd3da60907141340i46a6d913mb333788e85507128@mail.gmail.com> Message-ID: <5e089462-dbc1-4764-a57c-86c94cb0ae14@u16g2000yqe.googlegroups.com> On Jul 14, 11:31 pm, Chris Rebert wrote: > On Tue, Jul 14, 2009 at 1:40 PM, Mohan Parthasarathy wrote: > > Hi, > > I am a newbie. I am reading > >http://www.network-theory.co.uk/docs/pytut/KeywordArguments.html > > Defining a function with "N" arguments and calling them in "M" different > > ways. Why does it have to be this complicated ? I like the idea of calling > > the function by explicitly naming the arguments, but there are so many other > > ways here that is very confusing. Do people really use all these features ? > > Perhaps, there is a equivalent book to "Javascript: Good Parts" for Python ? > > Oh $DEITY, don't even compare Python toJavaScript. At least in > Python, when you try to access a non-existent attribute, a proper > NameError exception is thrown rather than silently getting back > "undefined"... (*has traumatic horror story flashback*) yehh, that's what i thought, originally, but after talking it over with the people doing the EMCAScript Harmony spec, they explained that nooo, there _are_ exceptions thrown (two if the browser implements it properly, which IE of course doesn't). you can try it by installing the spidermonkey js compiler, which is the exact same js engine that's in firefox. in the python-to-javascript compiler, http://pyjs.org, however, we've taken to adding a double-check (the equivalent of getattr) when you specify the --strict option, juuust to make sure. and yes, there was a talk at europython 2009, pretty much called "javascript, the good parts, for python programmers", you can look it up, the talk audio is online by now. http://europython.eu l. From joncle at googlemail.com Sat Aug 1 19:32:21 2009 From: joncle at googlemail.com (Jon Clements) Date: Sat, 1 Aug 2009 16:32:21 -0700 (PDT) Subject: Newbie thwarted by sys.path on Vista References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: <105eaa91-e751-4b25-a2c9-94cd075b60c7@s15g2000yqs.googlegroups.com> On 1 Aug, 22:58, "Michael M Mason" wrote: > I'm running Python 3.1 on Vista and I can't figure out how to add my own > directory to ?sys.path. > > The docs suggest that I can either add it to the PYTHONPATH environment > variable or to the PythonPath key in the registry. ?However, PYTHONPATH > doesn't exist, and updating the registry key has no effect (and in any case > the contents aren't the same as sys.path). > > So where does sys.path get its value from, and how do I change it? > > -- > Michael sys.path is just a list. So in your 'main' module where you do most of your imports, just append or prepend the path you desire (the search order is left to right). Although, I believe under Windows creating a system level or user level PYTHONPATH environment variable will enable Windows to pick it up. Not 100% sure as I don't have a Windows machine handy. From piet at cs.uu.nl Sat Aug 1 19:36:18 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 01:36:18 +0200 Subject: Newbie thwarted by sys.path on Vista References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: >>>>> "Michael M Mason" (MMM) wrote: >MMM> I'm running Python 3.1 on Vista and I can't figure out how to add my own >MMM> directory to sys.path. >MMM> The docs suggest that I can either add it to the PYTHONPATH environment >MMM> variable or to the PythonPath key in the registry. However, PYTHONPATH >MMM> doesn't exist, Then create it. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From aahz at pythoncraft.com Sat Aug 1 19:36:58 2009 From: aahz at pythoncraft.com (Aahz) Date: 1 Aug 2009 16:36:58 -0700 Subject: string.Template issue References: Message-ID: In article , Javier Collado wrote: > >In the string.Template documentation >(http://docs.python.org/library/string.html) it's explained that if a >custom regular expression for pattern substitution is needed, it's >possible to override idpattern class attribute (whose default value is >[_a-z][_a-z0-9]*). > >However, if the custom pattern that is needed is just uppercase >letters something like [A-Z]+ won't work because of the following line >in the _TemplateMetaclass class __init__ method: >cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) > >I would say that this is an error (IGNORECASE just shouldn't be there) Good point! I don't have an answer for you, but please file a report at bugs.python.org to make sure it doesn't get lost. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Many customs in this life persist because they ease friction and promote productivity as a result of universal agreement, and whether they are precisely the optimal choices is much less important." --Henry Spencer From david.lyon at preisshare.net Sat Aug 1 20:26:19 2009 From: david.lyon at preisshare.net (David Lyon) Date: Sat, 01 Aug 2009 20:26:19 -0400 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7djs50F2bsubuU1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: <73ddb9b5d0110a42e2831eb6c150d2a8@preisshare.net> On Sat, 1 Aug 2009 22:58:53 +0100, "Michael M Mason" wrote: > I'm running Python 3.1 on Vista and I can't figure out how to add my own > directory to sys.path. > > The docs suggest that I can either add it to the PYTHONPATH environment > variable or to the PythonPath key in the registry. However, PYTHONPATH > doesn't exist, and updating the registry key has no effect > > So where does sys.path get its value from, and how do I change it? The simplest hack (worst - but most direct) is that sys.path is a list and you can use it like any other list. (add, delete, change items in it) It gets loaded from site.py (in the standardard library) at startup. Anything else you'll have to ask somebody else. David From davea at ieee.org Sat Aug 1 20:29:12 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 01 Aug 2009 20:29:12 -0400 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7djs50F2bsubuU1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: <4A74DDD8.7020304@ieee.org> Michael M Mason wrote: >
I'm > running Python 3.1 on Vista and I can't figure out how to add my own > directory to sys.path. > > The docs suggest that I can either add it to the PYTHONPATH > environment variable or to the PythonPath key in the registry. > However, PYTHONPATH doesn't exist, and updating the registry key has > no effect (and in any case the contents aren't the same as sys.path). > > So where does sys.path get its value from, and how do I change it? > sys.path gets its values from several places. The ones I think I know of are: current directory (which uses "" rather than the expected ".") directories listed in PythonPath environment variable Windows-system directory relative to the executable (python.exe or pythonw.exe) that's actually running relative to the user directory (docs&settings/username/Application Data .... If there's no PythonPath variable, it just uses those other items. I have no idea what it gets from the registry entries. Anyway, I'd suggest adding it to PythonPath, and if it's empty, just create it with the directory you need. I'm hoping you know you can also add to sys.path directly during script initialization. It's just a list, and is writeable. From joongkoo.cho at gmail.com Sat Aug 1 20:43:57 2009 From: joongkoo.cho at gmail.com (Joongkoo Cho) Date: Sat, 1 Aug 2009 17:43:57 -0700 Subject: Shortest path code on real map Message-ID: Dear All, I'm trying to calculate shortest paths on US highway map. I understand how shortest path algorithms work in Python but I need helps to do it on real maps. How can I make link-node information? Best, John -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Aug 1 21:06:47 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 01:06:47 GMT Subject: Custom namespaces Message-ID: <0284d760$0$20667$c3e8da3@news.astraweb.com> I was playing around with a custom mapping type, and I wanted to use it as a namespace, so I tried to use it as my module __dict__: >>> import __main__ >>> __main__.__dict__ = MyNamespace() Traceback (most recent call last): File "", line 1, in TypeError: readonly attribute Why is __dict__ made read-only? I next thought I could change the type of the namespace to my class: >>> __main__.__dict__.__class__ = MyNamespace Traceback (most recent call last): File "", line 1, in TypeError: __class__ assignment: only for heap types Drat, foiled again!!! Okay, if I can't do this at the module level, can I at least install a custom namespace at the class level? >>> class MyNamespace(dict): ... def __getitem__(self, key): ... print "Looking up key '%s'" % key ... return super(MyNamespace, self).__getitem__(key) ... >>> namespace = MyNamespace(x=1, y=2, z=3) >>> namespace['x'] Looking up key 'x' 1 >>> C = new.classobj("C", (object,), namespace) >>> C.x 1 Apparently not. It looks like the namespace provided to the class constructor gets copied when the class is made. Interestingly enough, the namespace argument gets modified *before* it gets copied, which has an unwanted side-effect: >>> namespace {'y': 2, 'x': 1, '__module__': '__main__', 'z': 3, '__doc__': None} Is there any way to install a custom type as a namespace? -- Steven From redforks at gmail.com Sat Aug 1 21:11:45 2009 From: redforks at gmail.com (Red Forks) Date: Sun, 2 Aug 2009 09:11:45 +0800 Subject: string.Template issue In-Reply-To: References: Message-ID: <3f18b3f10908011811t6947fbf2t335370c676889062@mail.gmail.com> On Thu, Jul 30, 2009 at 4:17 PM, Javier Collado wrote: > Hello, > > In the string.Template documentation > (http://docs.python.org/library/string.html) it's explained that if a > custom regular expression for pattern substitution is needed, it's > possible to override idpattern class attribute (whose default value is > [_a-z][_a-z0-9]*). > > However, if the custom pattern that is needed is just uppercase > letters something like [A-Z]+ won't work because of the following line > in the _TemplateMetaclass class __init__ method: > cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) derive a new class, and replace __init__ method, or replace _TemplateMetaclass.__init__() method. > > > I would say that this is an error (IGNORECASE just shouldn't be there) > and that the line above should be: > cls.pattern = _re.compile(pattern, _re.VERBOSE) > and the default value for idpattern: > [_a-zA-Z][_a-zA-Z0-9]* > > Do you agree on this? Is there any reason for the IGNORECASE option to > be passed to re.compile? > > Best regards, > Javier > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From redforks at gmail.com Sat Aug 1 21:18:58 2009 From: redforks at gmail.com (Red Forks) Date: Sun, 2 Aug 2009 09:18:58 +0800 Subject: Custom namespaces In-Reply-To: <0284d760$0$20667$c3e8da3@news.astraweb.com> References: <0284d760$0$20667$c3e8da3@news.astraweb.com> Message-ID: <3f18b3f10908011818x711e49ccg575eb4eb7363f261@mail.gmail.com> On Sun, Aug 2, 2009 at 9:06 AM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > I was playing around with a custom mapping type, and I wanted to use it > as a namespace, so I tried to use it as my module __dict__: > > >>> import __main__ > >>> __main__.__dict__ = MyNamespace() > Traceback (most recent call last): > File "", line 1, in > TypeError: readonly attribute > > Why is __dict__ made read-only? to protect module type? Use .update() method: __main.__.__dict__.update(MyNamespace()) You can create your own Module instance: from types import ModuleType m = ModuleType('modulename') and make a sub class of ModuleType is also OK > > > I next thought I could change the type of the namespace to my class: > > >>> __main__.__dict__.__class__ = MyNamespace > Traceback (most recent call last): > File "", line 1, in > TypeError: __class__ assignment: only for heap types > > Drat, foiled again!!! > > Okay, if I can't do this at the module level, can I at least install a > custom namespace at the class level? > > >>> class MyNamespace(dict): > ... def __getitem__(self, key): > ... print "Looking up key '%s'" % key > ... return super(MyNamespace, self).__getitem__(key) > ... > >>> namespace = MyNamespace(x=1, y=2, z=3) > >>> namespace['x'] > Looking up key 'x' > 1 > >>> C = new.classobj("C", (object,), namespace) > >>> C.x > 1 > > Apparently not. It looks like the namespace provided to the class > constructor gets copied when the class is made. > > Interestingly enough, the namespace argument gets modified *before* it > gets copied, which has an unwanted side-effect: > > >>> namespace > {'y': 2, 'x': 1, '__module__': '__main__', 'z': 3, '__doc__': None} > > > Is there any way to install a custom type as a namespace? > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dciphercomputing at gmail.com Sat Aug 1 21:25:10 2009 From: dciphercomputing at gmail.com (Simon) Date: Sat, 1 Aug 2009 18:25:10 -0700 (PDT) Subject: Newbie Question regarding __init__() References: Message-ID: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> Okay I will fix my code and include "self" and see what happens. I know I tried that before and got another error which I suspect was another newbie error. The idea behind the init_Pre is that I can put custom code here to customize the __init__ instead of creating a new subclass. This kind of hook pattern allows you to flatten your inheritance hierarchy. I can choose in the init_Pre method to execute code before the init_exec (which contains the default __init__ code) and still execute the init_Exec method or I can completely customize the entire __init__ by returning False from init_Pre and prevent the init_Exec from being called. I use this type of pattern with almost all my methods. In this way I can create a less complicated inheritance chain but still have have custom code when needed without sub-classing. I am use to Visual FoxPro which where you can do =This.init_Pre().And.This.init_Exec() and the result is discarded so that is why it looks the way it does. In this form init_Exec has to return a value. However, If self.init_Pre(): self.init_Exec() would work the same and then I could avoid returning a value. Thanks, Simon On Aug 1, 5:52?am, Dave Angel wrote: > Nat Williams wrote: > > As MRAB described, ALL instance methods need to accept 'self' as a first > > parameter, as that will be passed to them implicitly when they are called. > > This includes __init__. ?The name 'self' is just a commonly accepted > > convention for the name of the instance object passed to methods. ?You don't > > have to call it that, but you really should. > > > Take a look athttp://docs.python.org/tutorial/classes.html#class-objects > > It might help shed some light on how methods and instances work. > > > One other thing. ?I'm a little confused by the first line of > > dcObject.__init__: > > > self.init_Pre() and self.init_Exec() > > > I suspect this does not do what you think it does. ?init_Pre and init_Exec > > will both be called by this expression (unless init_Pre throws an exception, > > of course). ?You're not getting anything here that you wouldn't by just > > calling each method on a separate line, except just making it harder to > > read. > > Read the doc-string for init_Pre() and for init_Exec(). ?The final > version of init_Pre() will return False in some circumstances, and in > those circumstances Simon doesn't want init_Exec() to be called. ?He's > deliberately using the short-circuit evaluation of ?'and' ?to accomplish > that. > > > > > > > > > On Fri, Jul 31, 2009 at 8:53 PM, Simon wrote: > > >> Hi > > >> So should the dcObject class include the "self" as well since I have > >> not defined an __init__ method in dcCursor? > > >> Simon > > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > Every one of those methods in both of those classes need a "self" first > argument. ?As others have said, all instance methods need a 'self.' From sturlamolden at yahoo.no Sat Aug 1 21:31:15 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 18:31:15 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: Message-ID: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> On 20 Jul, 18:27, Phillip B Oldham wrote: > We're not looking to start any arguments or religious wars and we're > not asking that python be changed into something its not. We'd simply > like to understand the decision behind the lists and tuple structures. > We feel that in not "getting" the difference between the two types we > may be missing out on using these data structures to their full > potential. A crude simplification would be: - A Python programmer will use a tuple where a C programmer will use a struct. - Python and C programmers use lists and arrays similarly. Tuples are used for passing arguments to and from a function. Common use of tuples include multiple return values and optional arguments (*args). It has already been mentioned that tuples are immutable and can be used as dictionary keys. From skip at pobox.com Sat Aug 1 21:38:46 2009 From: skip at pobox.com (Skip Montanaro) Date: Sun, 2 Aug 2009 01:38:46 +0000 (UTC) Subject: Wrapping prstat on Solaris References: <1bce2ffd-85cb-4860-8b3e-92d8e1619a46@k19g2000yqn.googlegroups.com> Message-ID: > You haven't told us how you are actually reading from prstat's output > pipe, which may be the cause. For instance, if you are doing > > for line in pipe: > print line > ... > > then this could cause your buffering issue. > > Instead try using readline(): > > while True: > line = pipe.readline() > ... Yes, I've been using for line in pipe. Switching to your construct seems to work like a charm. Thanks, Skip From fatkinson at mishmash.com Sat Aug 1 21:50:48 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sat, 01 Aug 2009 18:50:48 -0700 Subject: Get Cliet IP Address Message-ID: What is the function to obtain the client browser's IP address? Fred From fatkinson at mishmash.com Sat Aug 1 21:56:33 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sat, 01 Aug 2009 18:56:33 -0700 Subject: Predefined Variables References: <7cr6siF28oinaU2@mid.uni-berlin.de> Message-ID: <4gs9755f299j7ueitf422hh2vna32f358o@4ax.com> On Thu, 23 Jul 2009 15:28:50 +0200, "Diez B. Roggisch" wrote: >Fred Atkinson wrote: > >> Is there a pre-defined variable that returns the GET line >> (http://www.php.net/index.php?everythingafterthequestionmark) as a >> single variable (rather than individual variables)? > >Variables don't return things. Functions do. And additionally the answer >depends on what and with what you actually do. > >Diez I want to display the client browser's IP address on the Web page. I'd like to create a variable like this: ip = somefunction(). Then I can print the IP address on the Web page and/or log it in an error file. Fred From sturlamolden at yahoo.no Sat Aug 1 22:19:43 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 19:19:43 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: <86b332b3-2da0-44e0-b29f-d930136635df@u16g2000pru.googlegroups.com> <4677d753-364f-4d29-9091-e55008daec83@12g2000pri.googlegroups.com> Message-ID: <78d2801f-790c-475b-8953-23094482637f@h21g2000yqa.googlegroups.com> On 31 Jul, 23:43, Raymond Hettinger wrote: >?More than one person here has > observed that the time to learn to program Pythonically is inversely > proportional to their experience in Java. I believe it is opposite. The longer the Java experience, the longer it takes to program pythonically. The correlation is not inverse. In particular, programmers accustomed to Java or C++ seem to use for- loops awfully lot. And when they do, they always loop over a sequence of integers, and use these as array indices. They consequently use a class where a tuple would be more appropriate, never return multiple values from functions, etc. Due to their coding style, they produce programs that are notoriously inefficient, and blame this on 'Python being slow'. Unlearning the idioms from Java takes a while. Python is not Java and should not be programmed as such. On the other hand, I found that my experience with MATLAB helped me a lot on picking up a pythonical style quickly. From greg at cosc.canterbury.ac.nz Sat Aug 1 22:19:45 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 02 Aug 2009 14:19:45 +1200 Subject: Python processors? : WAS Re: Does python have the capability for driver development ? In-Reply-To: <2d8298b9-b857-4b3d-ae63-2056d80cdf7f@d4g2000yqa.googlegroups.com> References: <4a7151b2$0$17782$ba4acef3@news.orange.fr> <2d8298b9-b857-4b3d-ae63-2056d80cdf7f@d4g2000yqa.googlegroups.com> Message-ID: <7dkbcqF2c6aqgU1@mid.individual.net> Francesco Bochicchio wrote: > I wonder: has anybody thought of making a python-machine, or at least > a processor able to directly execute high-level bytecode (LLVM-like?). In some of my idle moments I've speculated on what such a machine might be like. One of my ideas for potential future projects is to flesh out the design and maybe even build an FPGA prototype. It would purely be for fun, though. It's unlikely that such a processor would be able to compete speed-wise with a general-purpose CPU running a Python interpreter with critical libraries written in C. That's what killed things like the Lisp machine. Their developers couldn't keep up with the huge resources that people like Intel and Motorola had to throw at CPU development, so eventually a general-purpose CPU could run Lisp faster than a Lisp machine. -- Greg From sturlamolden at yahoo.no Sat Aug 1 22:44:17 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 19:44:17 -0700 (PDT) Subject: fast video encoding References: <570097d0-2b2a-4705-892f-0d0154d69d63@b14g2000yqd.googlegroups.com> Message-ID: <0c8cfac7-0a70-4e1f-90ec-19e9c45cae89@h21g2000yqa.googlegroups.com> On 29 Jul, 10:14, gregorth wrote: > for a scientific application I need to save a video stream to disc for > further post processing. I have worked a bit on this as well. There are two things that make scientific applications different form common video encoding: First, a scientific video stream is often very different from a 'movie': There are usually very little 'movement'. For example, when I have filmed a mouse swimming in a water maze (a pool of milky white water), the only thing that moves is the rat. So I could achieve excellent compression just by saving the pixels that changed. Second, scientific data should be stored with lossless compression if possible. Common video codecs are aimed at films and home video, not scientific video streams. I don't know how your data are, but I would be very picky about the codec. And chances are you will be better off home-brewing your own domain specific compression. If you need to store large amounts of scientific data, consider using something like a HDF5 database for storage. There are two Python wrappers for HDF5 that I know of (h5py and PyTables). From nobody at nowhere.com Sat Aug 1 22:47:59 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 02 Aug 2009 03:47:59 +0100 Subject: Help understanding the decisions *behind* python? References: <86b332b3-2da0-44e0-b29f-d930136635df@u16g2000pru.googlegroups.com> <4677d753-364f-4d29-9091-e55008daec83@12g2000pri.googlegroups.com> <78d2801f-790c-475b-8953-23094482637f@h21g2000yqa.googlegroups.com> Message-ID: On Sat, 01 Aug 2009 19:19:43 -0700, sturlamolden wrote: >>?More than one person here has >> observed that the time to learn to program Pythonically is inversely >> proportional to their experience in Java. > > I believe it is opposite. The longer the Java experience, the longer > it takes to program pythonically. The correlation is not inverse. In > particular, programmers accustomed to Java or C++ seem to use for- > loops awfully lot. And when they do, they always loop over a sequence > of integers, and use these as array indices. It would be more accurate to say that of programmers who are *only* accustomed to Java or C++. I've been using C for 80-90% of my code for 25 years, and I wouldn't normally loop over the indices. But then the other 10-20% is Lisp, Tcl, Haskell, PostScript and, more recently, Python. OTOH, using a "for" loop when you could use a generator means less work when you need to make a minor change and a generator is no longer sufficient. From sturlamolden at yahoo.no Sat Aug 1 23:00:32 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 20:00:32 -0700 (PDT) Subject: Does python have the capability for driver development ? References: <87skgf83ua.fsf@rsw.digi.com.br> <94abbddc-dac7-4215-84d1-d4eb3f82724d@h21g2000yqa.googlegroups.com> Message-ID: On 30 Jul, 02:19, MalC0de wrote: > actually I mean driver programming under Windows operating system, if > you know, there's A kit name DDK available at microsoft's website for > developing device drivers under C / C++ environment, Actually, Microsoft has replaced DDK with a new kit called WDK for Vista. The funny thing about WDK is that there are a lot of illegal C and C++ in the headers, which even Microsoft's own compiler refuse to accept. So good luck on getting anything to compile. From darkneter at gmail.com Sat Aug 1 23:04:05 2009 From: darkneter at gmail.com (NighterNet) Date: Sat, 1 Aug 2009 20:04:05 -0700 (PDT) Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> <8bede581-f260-4c69-abf0-1e8071380b76@z4g2000prh.googlegroups.com> Message-ID: <7e6cdc26-bcc0-4503-b7b4-9ad80b1041f6@v37g2000prg.googlegroups.com> Here the full code. flashpolicy.xml [[[ ]]] flashpolicytest_server3x.py [[[ #!/usr/local/bin/python ''' Still under testing... python version 3.x.x ''' import socket import threading import sys import os file_name = 'flashpolicy.xml' fh = open(file_name, "r") policy = fh.read(10001) host = ''; #out side network port = 5555; print ("# ------------- Init... ------------- #"); class ClientThread (threading.Thread): global policy; allClients = []; vlock = threading.Lock(); id = 0 # next available thread number def __init__(self,clientSocket): threading.Thread.__init__(self) self.sockfd = clientSocket; #socket client self.name = ''; ClientThread.id += 1 self.id = ClientThread.id self.nickName = ''; self.allClients.append(self.sockfd); def sendAll(self,buff): for index,clientSock in enumerate(self.allClients): try: clientSock.send(buff); except (socket.error): print ('error socket %s\n',index,"| clean"); clientSock.close() del self.allClients[index] def run(self): while True: buff = self.sockfd.recv(1028); if not buff: print ("connect close...(client side)"); self.sockfd.close(); break #incase it loop infinite if str(buff) == str("b\'\\x00\'"): print ('policy FOUND >>> sending...') print(buff) b = b'' print (b) self.sockfd.send(b); self.sockfd.sendall(b); print(buff); self.sendAll(buff) self.sockfd.close() print ("# ------------- Init... Listen Client ------------- #\n"); try: server = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) except AttributeError: # AttributeError catches Python built without IPv6 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: # socket.error catches OS with IPv6 disabled server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind((host,port)) server.listen(5) print ("Server Up Listen!",host,":",port," Bind!"); while True: (clientSocket, address) = server.accept(); print("client connect from :",address); ct = ClientThread(clientSocket); print(ct.id); ct.start(); ]]] Some odd reason I can't send flash policy from python to flash socket to agrees with the connection. From fatkinson at mishmash.com Sat Aug 1 23:07:21 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sat, 01 Aug 2009 20:07:21 -0700 Subject: Predefined Variables References: <7cr6siF28oinaU2@mid.uni-berlin.de> <4gs9755f299j7ueitf422hh2vna32f358o@4ax.com> Message-ID: On Sat, 01 Aug 2009 18:56:33 -0700, Fred Atkinson wrote: >On Thu, 23 Jul 2009 15:28:50 +0200, "Diez B. Roggisch" > wrote: > >>Fred Atkinson wrote: >> >>> Is there a pre-defined variable that returns the GET line >>> (http://www.php.net/index.php?everythingafterthequestionmark) as a >>> single variable (rather than individual variables)? >> >>Variables don't return things. Functions do. And additionally the answer >>depends on what and with what you actually do. >> >>Diez > > I want to display the client browser's IP address on the Web >page. > > I'd like to create a variable like this: ip = somefunction(). > Then I can print the IP address on the Web page and/or log it >in an error file. > > > > Fred I replied to the wrong post. Sorry. I want to do something like this: string = os.environment('QUERY_STRING') If this is the string in the URL: http://www.someurl.com/cgi-bin/somescript.cgi?anythingafterthequestionmark 'string' should now contain the value 'everythingafterthequestionmark' When I use the os.environment('QUERY_STRING'), it doesn't work. Is there something I should import to make this function work? Or what else is wrong? Fred From sturlamolden at yahoo.no Sat Aug 1 23:10:00 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 20:10:00 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: <86b332b3-2da0-44e0-b29f-d930136635df@u16g2000pru.googlegroups.com> <4677d753-364f-4d29-9091-e55008daec83@12g2000pri.googlegroups.com> <78d2801f-790c-475b-8953-23094482637f@h21g2000yqa.googlegroups.com> Message-ID: <8a15492e-c9ab-47be-afea-cde3065413b1@e27g2000yqm.googlegroups.com> On 2 Aug, 04:47, Nobody wrote: > OTOH, using a "for" loop when you could use a generator means less work > when you need to make a minor change and a generator is no longer > sufficient. It's not just that. It is e.g. using a for loop and indexes instead of a slice. E.g. for i in range(10): # Java idiom a[i] = b[i+1] instead of a[:10] = b[1:11] # Pythonic From sturlamolden at yahoo.no Sat Aug 1 23:24:11 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 20:24:11 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: <86b332b3-2da0-44e0-b29f-d930136635df@u16g2000pru.googlegroups.com> <200907312048.03922.emmanuel.surleau@gmail.com> Message-ID: <2ff11bfc-9101-4b29-8b71-1627d85f799e@18g2000yqa.googlegroups.com> On 31 Jul, 21:31, Masklinn wrote: > It's intuitive if you come to Python knowing other languages with ? > tuples (which are mostly functional, and in which tuples are *never* ? > sequences/iterables). At the end of the day, and if Guido's intention ? > truly was what Raymond says, implementing tuples as immutable sequence ? > was a mistake. And the documentation is to blame as well: in it, ? > tuples are clearly described as a *sequence* type, not a *structure* ? > type. That depends on the readers' preconceptions: Only when the reader have knowledge of C structs, Pascal records, or Java classes should this matter. The na?ve reader will not have preconceptions about a difference between "structure types" and "sequence types". A more advanced C programmer will also know that a struct is a form of a sequence in C: you can e.g. memcpy any struct to a char array. From zooko at zooko.com Sun Aug 2 00:14:49 2009 From: zooko at zooko.com (Zooko Wilcox-O'Hearn) Date: Sat, 1 Aug 2009 22:14:49 -0600 Subject: ANNOUNCING Tahoe, the Lofty-Atmospheric Filesystem, v1.5 Message-ID: <9CE7ACE7-219C-4097-8543-928E05651387@zooko.com> Dear people of python-list: Python is our preferred programming language for the Tahoe-LAFS project. We use C/C++ extension modules for the CPU-intensive parts, and we interoperate with many languages through the RESTful web API, but the core code is 100% Python. Regards, Zooko --- The Tahoe-LAFS team is pleased to announce the immediate availability of version 1.5 of Tahoe, the Lofty Atmospheric File System. Tahoe-LAFS is the first cloud storage technology which offers security and privacy in the sense that the cloud storage service provider itself can't read or alter your data. Here is the one-page explanation of its unique security and fault-tolerance properties: http://allmydata.org/source/tahoe/trunk/docs/about.html This release is the successor to v1.4.1, which was released April 13, 2009 [1]. This is a major new release, improving the user interface and performance and fixing a few bugs, and adding ports to OpenBSD, NetBSD, ArchLinux, NixOS, and embedded systems built on ARM CPUs. See the NEWS file [2] for more information. In addition to the functionality of Tahoe-LAFS itself, a crop of related projects have sprung up to extend it and to integrate it into operating systems and applications. These include frontends for Windows, Macintosh, JavaScript, and iPhone, and plugins for duplicity, bzr, Hadoop, and TiddlyWiki, and more. See the Related Projects page on the wiki [3]. COMPATIBILITY Version 1.5 is fully compatible with the version 1 series of Tahoe-LAFS. Files written by v1.5 clients can be read by clients of all versions back to v1.0. v1.5 clients can read files produced by clients of all versions since v1.0. v1.5 servers can serve clients of all versions back to v1.0 and v1.5 clients can use servers of all versions back to v1.0. This is the sixth release in the version 1 series. The version 1 series of Tahoe-LAFS will be actively supported and maintained for the forseeable future, and future versions of Tahoe-LAFS will retain the ability to read and write files compatible with Tahoe-LAFS v1. The version 1 series of Tahoe-LAFS is the basis of the consumer backup product from Allmydata, Inc. -- http://allmydata.com . WHAT IS IT GOOD FOR? With Tahoe-LAFS, you can distribute your filesystem across a set of servers, such that if some of them fail or even turn out to be malicious, the entire filesystem continues to be available. You can share your files with other users, using a simple and flexible access control scheme. We believe that the combination of erasure coding, strong encryption, Free/Open Source Software and careful engineering make Tahoe-LAFS safer than RAID, removable drive, tape, on-line backup or other Cloud storage systems. This software comes with extensive tests, and there are no known security flaws which would compromise confidentiality or data integrity in typical use. (For all currently known issues please see the known_issues.txt file [4].) LICENCE You may use this package under the GNU General Public License, version 2 or, at your option, any later version. See the file "COPYING.GPL" [5] for the terms of the GNU General Public License, version 2. You may use this package under the Transitive Grace Period Public Licence, version 1 or, at your option, any later version. (The Transitive Grace Period Public Licence has requirements similar to the GPL except that it allows you to wait for up to twelve months after you redistribute a derived work before releasing the source code of your derived work.) See the file "COPYING.TGPPL.html" [6] for the terms of the Transitive Grace Period Public Licence, version 1. (You may choose to use this package under the terms of either licence, at your option.) INSTALLATION Tahoe-LAFS works on Linux, Mac OS X, Windows, Cygwin, Solaris, *BSD, and probably most other systems. Start with "docs/install.html" [7]. HACKING AND COMMUNITY Please join us on the mailing list [8]. Patches are gratefully accepted -- the RoadMap page [9] shows the next improvements that we plan to make and CREDITS [10] lists the names of people who've contributed to the project. The Dev page [11] contains resources for hackers. SPONSORSHIP Tahoe-LAFS was originally developed thanks to the sponsorship of Allmydata, Inc. [12], a provider of commercial backup services. Allmydata, Inc. created the Tahoe-LAFS project and contributed hardware, software, ideas, bug reports, suggestions, demands, and money (employing several Tahoe-LAFS hackers and instructing them to spend part of their work time on this Free Software project). Also they awarded customized t-shirts to hackers who found security flaws in Tahoe-LAFS (see http://hacktahoe.org ). After discontinuing funding of Tahoe-LAFS R&D in early 2009, Allmydata, Inc. has continued to provide servers, co-lo space and bandwidth to the open source project. Thank you to Allmydata, Inc. for their generous and public-spirited support. This is the second release of Tahoe-LAFS which was created solely as a labor of love by volunteers; developer time is no longer funded by allmydata.com (see [13] for details). Zooko Wilcox-O'Hearn on behalf of the Tahoe-LAFS team Special acknowledgment goes to Brian Warner, whose superb engineering skills and dedication are primarily responsible for the Tahoe implementation, and significantly responsible for the Tahoe design as well, not to mention most of the docs and tests. Tahoe-LAFS wouldn't exist without him. August 1, 2009 Boulder, Colorado, USA P.S. Just kidding about that acronym. "LAFS" actually stands for "Lightweight Authorization File System". Or possibly for "Least-Authority File System". There is no truth to the rumour that it actually stands for "Long-lived Axe-tolerant File System". [1] http://allmydata.org/trac/tahoe/browser/relnotes.txt?rev=3853 [2] http://allmydata.org/trac/tahoe/browser/NEWS?rev=4033 [3] http://allmydata.org/trac/tahoe/wiki/RelatedProjects [4] http://allmydata.org/trac/tahoe/browser/docs/known_issues.txt [5] http://allmydata.org/trac/tahoe/browser/COPYING.GPL [6] http://allmydata.org/source/tahoe/trunk/COPYING.TGPPL.html [7] http://allmydata.org/source/tahoe/trunk/docs/install.html [8] http://allmydata.org/cgi-bin/mailman/listinfo/tahoe-dev [9] http://allmydata.org/trac/tahoe/roadmap [10] http://allmydata.org/trac/tahoe/browser/CREDITS?rev=4035 [11] http://allmydata.org/trac/tahoe/wiki/Dev [12] http://allmydata.com [13] http://allmydata.org/pipermail/tahoe-dev/2009-March/001461.html From clp2 at rebertia.com Sun Aug 2 00:46:35 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 1 Aug 2009 21:46:35 -0700 Subject: Custom namespaces In-Reply-To: <0284d760$0$20667$c3e8da3@news.astraweb.com> References: <0284d760$0$20667$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0908012146p11c58419s7d33aa9a2a048f46@mail.gmail.com> On Sat, Aug 1, 2009 at 6:06 PM, Steven D'Aprano wrote: > I was playing around with a custom mapping type, and I wanted to use it > as a namespace, so I tried to use it as my module __dict__: > >>>> import __main__ >>>> __main__.__dict__ = MyNamespace() > Traceback (most recent call last): > ?File "", line 1, in > TypeError: readonly attribute > > Why is __dict__ made read-only? > > I next thought I could change the type of the namespace to my class: > >>>> __main__.__dict__.__class__ = MyNamespace > Traceback (most recent call last): > ?File "", line 1, in > TypeError: __class__ assignment: only for heap types > > Drat, foiled again!!! > > Okay, if I can't do this at the module level, can I at least install a > custom namespace at the class level? > Apparently not. It looks like the namespace provided to the class > constructor gets copied when the class is made. > Is there any way to install a custom type as a namespace? For classes/objects, yes, using metaclasses. See the __prepare__() method in PEP 3115: http://www.python.org/dev/peps/pep-3115/ Cheers, Chris -- http://blog.rebertia.com From bhardwajjayesh7 at gmail.com Sun Aug 2 02:11:43 2009 From: bhardwajjayesh7 at gmail.com (golu) Date: Sat, 1 Aug 2009 23:11:43 -0700 (PDT) Subject: cgi script Message-ID: Hi, i started learning cgi few days ago in python and everything went fine until i started getting the follwing error " The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script. If you think this is a server error, please contact the webmaster. " i am using apache on xampp. plz help From michael at altra-optics.co.uk Sun Aug 2 02:34:56 2009 From: michael at altra-optics.co.uk (Michael M Mason) Date: Sun, 2 Aug 2009 07:34:56 +0100 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: <7dks7jF2ccjstU1@mid.individual.net> "Dave Angel" wrote in message news:mailman.4120.1249172970.8015.python-list at python.org... > Michael M Mason wrote: >>
I'm running >> Python 3.1 on Vista and I can't figure out how to add my own directory to >> sys.path. Thanks to Jon, Piet, David and Dave for the responses. > sys.path gets its values from several places. Ah, I'd misunderstood the docs: I thought it came from just one place (which I couldn't find). > Anyway, I'd suggest adding it to PythonPath, and if it's empty, just > create it with the directory you need. Thanks--that worked! > I'm hoping you know you can also add to sys.path directly during script > initialization. It's just a list, and is writeable. Yes, but I'm mainly playing in IDLE and I was getting a bit fed up of repeatedly typing import sys sys.path.append('C:/Users/Michael/Code/Python') import mystuff -- Michael From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 02:47:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 06:47:41 GMT Subject: Python processors? : WAS Re: Does python have the capability for driver development ? References: <4a7151b2$0$17782$ba4acef3@news.orange.fr> <2d8298b9-b857-4b3d-ae63-2056d80cdf7f@d4g2000yqa.googlegroups.com> <7dkbcqF2c6aqgU1@mid.individual.net> Message-ID: <02852746$0$20667$c3e8da3@news.astraweb.com> On Sun, 02 Aug 2009 14:19:45 +1200, greg wrote: > That's what killed things like the Lisp machine. Their developers > couldn't keep up with the huge resources that people like Intel and > Motorola had to throw at CPU development, so eventually a > general-purpose CPU could run Lisp faster than a Lisp machine. When you say "eventually", I think you mean "decades ago". I recall a collaboration between Apple and Texas Instruments to build a Macintosh with a Lisp Machine in the late 1980s. From the one box, you could run two computers simultaneously, with two operating systems, one running the Motorola 68020 and the other a Lisp Machine processor. I don't think it sold very well -- by memory, benchmarks showed that for half (or less) of the price, you could run Lisp in software on a vanilla Mac and the software would be faster than running it on the Lisp Machine. TI also had at least one Nubus card for the Mac running a Lisp Machine: http://en.wikipedia.org/wiki/TI_Explorer On a similar note, there were Forth machines also available for the Apple Macintosh. Unlike Lisp, I think they suffered from the general lack of popularity of Forth rather than lack of speed. -- Steven From efotinis at oohay.com Sun Aug 2 02:59:41 2009 From: efotinis at oohay.com (eliasf) Date: Sun, 2 Aug 2009 09:59:41 +0300 Subject: Get Cliet IP Address In-Reply-To: References: Message-ID: <1249196395.629238@athprx04> "Fred Atkinson" wrote: > What is the function to obtain the client browser's IP > address? Do you mean the external public IP to the Internet? When I wanted to log the dynamic IP that my ADSL connection gets, I used whatismyip.com like this: import urllib2 QUERY_URL = 'http://www.whatismyip.com/automation/n09230945.asp' def query(): """Get IP as a string. As per the whatismyip.com automation rules, this function should not be called more ofter than every 5 minutes. """ return urllib2.urlopen(QUERY_URL).read() There's probably a better way, but I'm not very good with networking. :o) From pavlovevidence at gmail.com Sun Aug 2 03:14:41 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 Aug 2009 00:14:41 -0700 (PDT) Subject: cgi script References: Message-ID: <007247ae-53b8-4ce7-ad85-eb332b455f41@2g2000prl.googlegroups.com> On Aug 1, 11:11?pm, golu wrote: > Hi, > i started learning cgi few days ago in python and everything went > fine ?until i started getting the follwing error > " > The server encountered an internal error and was unable to complete > your request. Either the server is overloaded or there was an error in > a CGI script. Your script has a syntax error. (You forgot a colon or something like that.) If you can, try to run the file directly from a Python interpreter to see where the error is. Carl Banks From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 03:18:53 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 07:18:53 GMT Subject: Custom namespaces References: <0284d760$0$20667$c3e8da3@news.astraweb.com> Message-ID: <02852e95$0$20667$c3e8da3@news.astraweb.com> On Sat, 01 Aug 2009 21:46:35 -0700, Chris Rebert wrote: >> Is there any way to install a custom type as a namespace? > > For classes/objects, yes, using metaclasses. See the __prepare__() > method in PEP 3115: http://www.python.org/dev/peps/pep-3115/ Looks good, but that's Python 3 only, yes? At least, I can't get the metaclass to change the __dict__ in Python 2.6. There's obviously no __prepare__ before 3.0, but I tried the following, and still __dict__ ends up as a regular dict. Am I missing something? class VerboseDict(dict): def __getitem__(self, item): print ("Looking up key '%s'..." % item) return super(VerboseDict, self).__getitem__(item) class Meta(type): def __new__(cls, name, bases, namespace): namespace = VerboseDict(namespace) obj = super(Meta, cls).__new__(cls, name, bases, namespace) return obj MyClass = Meta('MyClass', (object,), dict(x=1, y=2)) -- Steven From clp2 at rebertia.com Sun Aug 2 03:31:05 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 Aug 2009 00:31:05 -0700 Subject: Custom namespaces In-Reply-To: <02852e95$0$20667$c3e8da3@news.astraweb.com> References: <0284d760$0$20667$c3e8da3@news.astraweb.com> <02852e95$0$20667$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0908020031h32fadb65ye7e306138205a751@mail.gmail.com> On Sun, Aug 2, 2009 at 12:18 AM, Steven D'Aprano wrote: > On Sat, 01 Aug 2009 21:46:35 -0700, Chris Rebert wrote: > >>> Is there any way to install a custom type as a namespace? >> >> For classes/objects, yes, using metaclasses. See the __prepare__() >> method in PEP 3115: http://www.python.org/dev/peps/pep-3115/ > > Looks good, but that's Python 3 only, yes? Correct. > At least, I can't get the metaclass to change the __dict__ in Python 2.6. > There's obviously no __prepare__ before 3.0, but I tried the following, > and still __dict__ ends up as a regular dict. Am I missing something? > > > class VerboseDict(dict): > ? ?def __getitem__(self, item): > ? ? ? ?print ("Looking up key '%s'..." % item) > ? ? ? ?return super(VerboseDict, self).__getitem__(item) > > class Meta(type): > ? ?def __new__(cls, name, bases, namespace): > ? ? ? ?namespace = VerboseDict(namespace) > ? ? ? ?obj = super(Meta, cls).__new__(cls, name, bases, namespace) > ? ? ? ?return obj I would /guess/ that type.__new__() is internally doing the equivalent of dict(namespace). Hence why the addition of __prepare__() was necessary; it's probably impossible to accomplish what you want in earlier Python versions. Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 03:35:08 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 07:35:08 GMT Subject: Generate a new object each time a name is imported Message-ID: <02853264$0$20667$c3e8da3@news.astraweb.com> I would like to generate a new object each time I import a name from a module, rather than getting the same object each time. For example, currently I might do something like this: # Module count = 0 def factory(): # Generate a unique object each time this is called global count count += 1 return "Object #%d" % count # Calling module from Module import factory a = factory() # a == "Object #1" b = factory() # b == "Object #2" del factory I'm looking for a way to hide the generation of objects from the caller, so I could do something like this: from Module import factory() as a # a == "Object #1" from Module import factory() as b # b == "Object #2" except of course that syntax is illegal. -- Steven From jgardner at jonathangardner.net Sun Aug 2 03:38:22 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Sun, 2 Aug 2009 00:38:22 -0700 (PDT) Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: On Aug 2, 12:35?am, Steven D'Aprano wrote: > > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a ?# a == "Object #1" > from Module import factory() as b ?# b == "Object #2" > Explicit is better than implicit. In other words, I don't see why you need to hide this. Just import the factory function and call it. from Module import factory a = factory() From hniksic at xemacs.org Sun Aug 2 04:23:51 2009 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 02 Aug 2009 10:23:51 +0200 Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <87tz0qei94.fsf@busola.homelinux.net> Steven D'Aprano writes: > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a # a == "Object #1" > from Module import factory() as b # b == "Object #2" > > except of course that syntax is illegal. That sounds reasonable (zen quotes aside), but it's just not possible in current Python. It would require for any use of "a" in subsequent code to not only refer to an object, but also to automagically call it. I know of no mechanism to do that. While Python allows intricate customization of access to objects, simply referring to a name remains fixed in meaning, probably intentionally. (The "cell" mechanism used to implement closures sounds like it could help, but a cell only stores a single value, not a factory, and it doesn't apply to global variables anyway.) From Ron.Barak at lsi.com Sun Aug 2 04:45:09 2009 From: Ron.Barak at lsi.com (Barak, Ron) Date: Sun, 2 Aug 2009 09:45:09 +0100 Subject: Run pyc file without specifying python path ? In-Reply-To: <4A71D35F.3090800@dejaviewphoto.com> References: <7F0503CD69378F49BE0DC30661C6CCF6701A26C4@enbmail01.lsi.com> <4A708F68.1010505@ieee.org> <7F0503CD69378F49BE0DC30661C6CCF6701A26C7@enbmail01.lsi.com> <4A7199FF.8010202@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF6701A26D2@enbmail01.lsi.com> <4A71D35F.3090800@dejaviewphoto.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF67D49D30E@enbmail01.lsi.com> > -----Original Message----- > From: Dave Angel [mailto:davea at dejaviewphoto.com] > Sent: Thursday, July 30, 2009 20:08 > To: Barak, Ron > Cc: 'python-list at python.org' > Subject: Re: Run pyc file without specifying python path ? > > Barak, Ron wrote: > > Hi Dave, > > > > On second thoughts, I may have a problem implementing the > wrapper solution, because my actual test_pyc.pyc, needs to > parse its command line. > > Namely, the actual call to test_pyc.pyc looks something like this: > > > > $ python test_pyc.py -U dave -PpasswoRD -C CreateMcGroupOnVolume > > --SVMs_IPs '10.1.1.1 , 10.1.1.2' -n "host1,host2" -g gn -j > jn -s svn > > -t tvn -p pool1 -l -c > > > > And I don't know of a way to add these parameters to the "import > > test_pyc" in wrapper > > > > Is there a way to pass information to an imported module ? > (Sorry if there's an obvious answer, I just cannot figure it out). > > > > Bye, > > Ron. > > > > > >> -----Original Message----- > >> From: Dave Angel [mailto:davea at dejaviewphoto.com] > >> Sent: Thursday, July 30, 2009 16:03 > >> To: Barak, Ron > >> Cc: 'Dave Angel'; 'python-list at python.org' > >> Subject: RE: Run pyc file without specifying python path ? > >> > >> Barak, Ron wrote: > >> > >>>> -----Original Message----- > >>>> From: Dave Angel [mailto:davea at ieee.org] > >>>> Sent: Wednesday, July 29, 2009 21:05 > >>>> To: Barak, Ron > >>>> Cc: 'python-list at python.org' > >>>> Subject: Re: Run pyc file without specifying python path ? > >>>> > >>>> Barak, Ron wrote: > >>>> > >>>> > >>>>> Hi, > >>>>> > >>>>> I wanted to make a python byte-code file executable, > >>>>> > >>>>> > >>>> expecting to be able to run it without specifying > "python" on the > >>>> (Linux bash) command line. > >>>> > >>>> > >>>>> So, I wrote the following: > >>>>> > >>>>> [root at VMLinux1 python]# cat test_pyc.py #!/usr/bin/env python > >>>>> > >>>>> print "hello" > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> and made its pyc file executable: > >>>>> > >>>>> [root at VMLinux1 python]# ls -ls test_pyc.pyc > >>>>> 4 -rwxr-xr-x 1 root root 106 Jul 29 14:22 test_pyc.pyc > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> So, I see: > >>>>> > >>>>> [root at VMLinux1 python]# file test_pyc.py* > >>>>> test_pyc.py: a python script text executable > >>>>> test_pyc.pyc: python 2.3 byte-compiled > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> If I try to do the following, no problem: > >>>>> > >>>>> [root at VMLinux1 python]# python test_pyc.pyc hello > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> However, the following fails: > >>>>> > >>>>> [root at VMLinux1 python]# ./test_pyc.pyc > >>>>> -bash: ./test_pyc.pyc: cannot execute binary file > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> Is there a way to run a pyc file without specifying the > >>>>> > >>>>> > >>>> python path ? > >>>> > >>>> > >>>>> Bye, > >>>>> Ron. > >>>>> > >>>>> > >>>>> > >>>>> > >>>> I don't currently run Unix, but I think I know the problem. > >>>> > >>>> In a text file, the shell examines the first line, and if > >>>> > >> it begins > >> > >>>> #! > >>>> it's assumed to point to the executable of an > interpreter for that > >>>> text file. Presumably the same trick doesn't work for a > .pyc file. > >>>> > >>>> Why not write a trivial wrapper.py file, don't compile > it, and let > >>>> that invoke the main code in the .pyc file? > >>>> > >>>> Then make wrapper.py executable, and you're ready to go. > >>>> > >>>> DaveA > >>>> > >>>> > >>>> > >>>> > >>> Hi Dave, > >>> Your solution sort of defeats my intended purpose (sorry > >>> > >> for not divulging my 'hidden agenda'). > >> > >>> I wanted my application to "hide" the fact that it's a > >>> > >> python script, and look as much as possible like it's a compiled > >> program. > >> > >>> The reason I don't just give my user a py file, is that I > >>> > >> don't want a cleaver user to change the innards of the script. > >> > >>> On the other hand, I don't want to make a compiled > >>> > >> (freezed?) version of the application, because it'll grow the > >> resulting file significantly, and I don't have the > experience to know > >> how it will run on different Linuxes. > >> > >>> Bye, > >>> Ron. > >>> > >>> > >> Most of the other answers basically paraphrased my suggestion of > >> making a wrapper file, not compiling it, and making it > executable. > >> With that > >> approach, the user just types "wrapper.py" on his command line. > >> > >> And wrapper.py only needs two lines, a shebang, and an > import, no big > >> deal if the user modifies it. The rest of your code can be .pyc > >> files. > >> > >> Steven makes some good points. You have to define what level of > >> clever you're protecting from. A determined hacker will get in no > >> matter what you do, unless you want to ship the program in a > >> proprietary embedded system, encased in epoxy. > >> Further, if you have an extension of .py or .pyc, a knowledgeable > >> hacker will know it's probably python. > >> > >> You imply you want it to run unmodifed on multiple unknown Linux > >> versions. I think that lets out binfmt solutions. > >> That means you need to test and support not only multiple Linux > >> implementations, but multiple Python versions, because who > knows what > >> the user may have installed. I think you need to rethink your > >> support strategy. And maybe concentrate on being able to detect > >> change, rather than prevent it. > >> > >> DaveA > >> > >> > >> > >> > (Please don't top-post. It puts responses out of order) > > You don't have to do anything special. Any module can import > sys, and parse sys.argv, as long as it wasn't yet modified. > > DaveA > Hi Dave, It seems like I don't understand your solution. I use the (appatched) soapAPI.py as the wrapper to parsing.pyc. However, if I do (for instance): $ python -u parsing.pyc -U aaa The last line of the output is (as expected): return_code: 12 ; params: {'username': 'aaa'} But, if I try the following: $ soapAPI.py -U aaa I don't get this line. Only the output to stderr gets printed to the screen. Bye, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: soapAPI.py Type: application/octet-stream Size: 65 bytes Desc: soapAPI.py URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: parsing.py Type: application/octet-stream Size: 9542 bytes Desc: parsing.py URL: From breamoreboy at yahoo.co.uk Sun Aug 2 04:55:04 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Aug 2009 09:55:04 +0100 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7dks7jF2ccjstU1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> <7dks7jF2ccjstU1@mid.individual.net> Message-ID: Michael M Mason wrote: > > "Dave Angel" wrote in message > news:mailman.4120.1249172970.8015.python-list at python.org... >> Michael M Mason wrote: >>>
I'm >>> running Python 3.1 on Vista and I can't figure out how to add my own >>> directory to sys.path. > > Thanks to Jon, Piet, David and Dave for the responses. > >> sys.path gets its values from several places. > > Ah, I'd misunderstood the docs: I thought it came from just one place > (which I couldn't find). > >> Anyway, I'd suggest adding it to PythonPath, and if it's empty, just >> create it with the directory you need. > > Thanks--that worked! Be careful, I'm screwed things up on several occasions by placing a file on PYTHONPATH that overrides a file in the standard library, test.py being my favourite! > >> I'm hoping you know you can also add to sys.path directly during >> script initialization. It's just a list, and is writeable. > > Yes, but I'm mainly playing in IDLE and I was getting a bit fed up of > repeatedly typing > import sys > sys.path.append('C:/Users/Michael/Code/Python') > import mystuff > -- Kindest regards. Mark Lawrence. From michael at altra-optics.co.uk Sun Aug 2 05:15:25 2009 From: michael at altra-optics.co.uk (Michael M Mason) Date: Sun, 2 Aug 2009 10:15:25 +0100 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: References: <7djs50F2bsubuU1@mid.individual.net> <7dks7jF2ccjstU1@mid.individual.net> Message-ID: <7dl3pkF2cnqf5U1@mid.individual.net> "Mark Lawrence" wrote in message news:mailman.4130.1249203322.8015.python-list at python.org... > Be careful, I'm screwed things up on several occasions by placing a file > on PYTHONPATH that overrides a file in the standard library, test.py being > my favourite! Thanks. Sure enough, I've already got my own test.py but I hadn't discovered it was a problem yet... -- Michael From davea at ieee.org Sun Aug 2 05:35:34 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 02 Aug 2009 05:35:34 -0400 Subject: Run pyc file without specifying python path ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF67D49D30E@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6701A26C4@enbmail01.lsi.com> <4A708F68.1010505@ieee.org> <7F0503CD69378F49BE0DC30661C6CCF6701A26C7@enbmail01.lsi.com> <4A7199FF.8010202@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF6701A26D2@enbmail01.lsi.com> <4A71D35F.3090800@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF67D49D30E@enbmail01.lsi.com> Message-ID: <4A755DE6.1000906@ieee.org> Barak, Ron wrote: > Hi Dave, > > It seems like I don't understand your solution. > I use the (appatched) soapAPI.py as the wrapper to parsing.pyc. > However, if I do (for instance): > > $ python -u parsing.pyc -U aaa > > The last line of the output is (as expected): > > return_code: 12 ; params: {'username': 'aaa'} > > But, if I try the following: > > $ soapAPI.py -U aaa > > I don't get this line. Only the output to stderr gets printed to the screen. > > Bye, > Ron. > > Hi Ron, To make it easier for anybody following this thread, let me post the minimum equivalent source files, inline. parsing.py: ------------------------------ #!/usr/bin/env python import sys def main(): print >> sys.stderr, "This is stderr output" return 5, sys.argv if __name__ == "__main__": return_code, params = main() print "return_code:",return_code,"; params:",params sys.exit(return_code) ------------------------------- soapapi.py: ------------------------------- #!/usr/bin/env python import sys import parsing parsing.main() ------------------------------ When I run soapapi.;py, it indeed prints only the stderr output. The solution is to move (most or all) of the top-level code of parsing.py into a main() function. Since you already have a main(), I'll rename that, and make a new one that calls it. new parsing.py: ------------------------------- #!/usr/bin/env python import sys def innermain(): print >> sys.stderr, "This is stderr output" return 5, sys.argv def main(): return_code, params = innermain() print "return_code:",return_code,"; params:",params sys.exit(return_code) if __name__ == "__main__": main() ------------------------------- The output is now two lines, one from innermain(), and one from main(). And it's the same whether the user runs parsing.py or soapAPI.py To clarify what happened, realize that when the user invokes parsing.py, the module is considered a script, and gets a pseudo-name of "__main__" When that same module is imported by another one, it is considered a library module, and gets its own name "parsing" So any logic that explicitly checks for "__main__" has to change, because we want identical behavior in the two cases. DaveA From davea at ieee.org Sun Aug 2 05:51:45 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 02 Aug 2009 05:51:45 -0400 Subject: Newbie Question regarding __init__() In-Reply-To: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> Message-ID: <4A7561B1.9060808@ieee.org> Simon wrote: > Okay I will fix my code and include "self" and see what happens. I > know I tried that before and got another error which I suspect was > another newbie error. > > The idea behind the init_Pre is that I can put custom code here to > customize the __init__ instead of creating a new subclass. This kind > of hook pattern allows you to flatten your inheritance hierarchy. I > can choose in the init_Pre method to execute code before the init_exec > (which contains the default __init__ code) and still execute the > init_Exec method or I can completely customize the entire __init__ by > returning False from init_Pre and prevent the init_Exec from being > called. I use this type of pattern with almost all my methods. In > this way I can create a less complicated inheritance chain but still > have have custom code when needed without sub-classing. > > I am use to Visual FoxPro which where you can do > > =is.init_Pre().And.This.init_Exec() and the result is discarded so > that is why it looks the way it does. In this form init_Exec has to > return a value. However, If self.init_Pre(): self.init_Exec() would > work the same and then I could avoid returning a value. > > Thanks, > Simon > > > On Aug 1, 5:52 am, Dave Angel wrote: > >> Nat Williams wrote: >> >>> As MRAB described, ALL instance methods need to accept 'self' as a first >>> parameter, as that will be passed to them implicitly when they are called. >>> This includes __init__. The name 'self' is just a commonly accepted >>> convention for the name of the instance object passed to methods. You don't >>> have to call it that, but you really should. >>> >>> Take a look athttp://docs.python.org/tutorial/classes.html#class-objects >>> It might help shed some light on how methods and instances work. >>> >>> One other thing. I'm a little confused by the first line of >>> dcObject.__init__: >>> >>> self.init_Pre() and self.init_Exec() >>> >>> I suspect this does not do what you think it does. init_Pre and init_Exec >>> will both be called by this expression (unless init_Pre throws an exception, >>> of course). You're not getting anything here that you wouldn't by just >>> calling each method on a separate line, except just making it harder to >>> read. >>> >> Read the doc-string for init_Pre() and for init_Exec(). The final >> version of init_Pre() will return False in some circumstances, and in >> those circumstances Simon doesn't want init_Exec() to be called. He's >> deliberately using the short-circuit evaluation of 'and' to accomplish >> that. >> >> >> >> >> >> >> >> >>> On Fri, Jul 31, 2009 at 8:53 PM, Simon wrote: >>> >>>> Hi >>>> >>>> So should the dcObject class include the "self" as well since I have >>>> not defined an __init__ method in dcCursor? >>>> >>>> Simon >>>> >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>>> >> Every one of those methods in both of those classes need a "self" first >> argument. As others have said, all instance methods need a 'self.' >> > > (Please don't top-post. You should put new responses at the end of quoted text, or sometimes inline if that's clearer.) I don't understand your comparison to Foxpro. read on. As your code was last posted, you don't need a return value from init_Exec() Every function that doesn't have an explicit return will return None. And None is interpreted as False in an "and" expression. If you had an "if" around the whole thing, then you'd care. DaveA From davea at ieee.org Sun Aug 2 06:00:28 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 02 Aug 2009 06:00:28 -0400 Subject: Help understanding the decisions *behind* python? In-Reply-To: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> Message-ID: <4A7563BC.2040406@ieee.org> sturlamolden wrote: > On 20 Jul, 18:27, Phillip B Oldham wrote: > > >> We're not looking to start any arguments or religious wars and we're >> not asking that python be changed into something its not. We'd simply >> like to understand the decision behind the lists and tuple structures. >> We feel that in not "getting" the difference between the two types we >> may be missing out on using these data structures to their full >> potential. >> > > A crude simplification would be: > > - A Python programmer will use a tuple where a C programmer will use a > struct. > > - Python and C programmers use lists and arrays similarly. > > Tuples are used for passing arguments to and from a function. Common > use of tuples include multiple return values and optional arguments > (*args). > > It has already been mentioned that tuples are immutable and can be > used as dictionary keys. > > > I think collections.namedtuple, introduced in Python 2.6, might help bridge the gap between a traditional tuple and a C struct. From __peter__ at web.de Sun Aug 2 06:33:03 2009 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Aug 2009 12:33:03 +0200 Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I would like to generate a new object each time I import a name from a > module, rather than getting the same object each time. For example, > currently I might do something like this: > > # Module > count = 0 > def factory(): > # Generate a unique object each time this is called > global count > count += 1 > return "Object #%d" % count > > > # Calling module > from Module import factory > a = factory() # a == "Object #1" > b = factory() # b == "Object #2" > del factory > > > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a # a == "Object #1" > from Module import factory() as b # b == "Object #2" > > except of course that syntax is illegal. How about >>> class A(object): ... def __init__(self): ... self._n = 0 ... @property ... def a(self): ... try: ... return self._n ... finally: ... self._n += 1 ... >>> import sys >>> sys.modules["yadda"] = A() >>> from yadda import a >>> from yadda import a as b >>> a, b (0, 1) Peter From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 06:49:33 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 10:49:33 GMT Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <02855ff5$0$20667$c3e8da3@news.astraweb.com> On Sun, 02 Aug 2009 12:33:03 +0200, Peter Otten wrote: > How about [snip] >>>> import sys >>>> sys.modules["yadda"] = A() Perfect! That's exactly the sort of thing I'm looking for. Thanks for everyone who answered. -- Steven From breamoreboy at yahoo.co.uk Sun Aug 2 07:04:25 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Aug 2009 12:04:25 +0100 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7dl3pkF2cnqf5U1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> <7dks7jF2ccjstU1@mid.individual.net> <7dl3pkF2cnqf5U1@mid.individual.net> Message-ID: Michael M Mason wrote: > "Mark Lawrence" wrote in message > news:mailman.4130.1249203322.8015.python-list at python.org... >> Be careful, I'm screwed things up on several occasions by placing a >> file on PYTHONPATH that overrides a file in the standard library, >> test.py being my favourite! > > Thanks. Sure enough, I've already got my own test.py but I hadn't > discovered it was a problem yet... > Typical, tried to reproduce it and can't! Still at least you've been warned. -- Kindest regards. Mark Lawrence. From http Sun Aug 2 07:18:34 2009 From: http (Paul Rubin) Date: 02 Aug 2009 04:18:34 -0700 Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <7x63d631md.fsf@ruckus.brouhaha.com> Peter Otten <__peter__ at web.de> writes: > >>> import sys > >>> sys.modules["yadda"] = A() OMG.... wow. I bow to you. But I'm not sure whether that's bowing in awe or in terror. From marcusw at cox.net Sun Aug 2 08:08:34 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sun, 02 Aug 2009 08:08:34 -0400 Subject: Help understanding the decisions *behind* python? In-Reply-To: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> Message-ID: On 8/1/2009 9:31 PM, sturlamolden wrote: > - Python and C programmers use lists and arrays similarly. I'm guessing that's because of the brackets... Marcus From __peter__ at web.de Sun Aug 2 08:19:01 2009 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Aug 2009 14:19:01 +0200 Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> <7x63d631md.fsf@ruckus.brouhaha.com> Message-ID: wrote: KNode cannot parse your From-string correctly. Strange. > Peter Otten <__peter__ at web.de> writes: >> >>> import sys >> >>> sys.modules["yadda"] = A() > > OMG.... wow. I bow to you. But I'm not sure whether that's bowing in > awe or in terror. I don't know who invented it, but it's an old trick. It even made it into the standard library (email.LazyImporter). For the record: I don't recommend it. Peter From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 08:36:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 12:36:41 GMT Subject: Skipping a superclass Message-ID: <02857910$0$20667$c3e8da3@news.astraweb.com> I have a series of subclasses like this: class A(object): def method(self, *args): print "Lots of work gets done here in the base class" class B(A): def method(self, *args): print "A little bit of work gets done in B" super(B, self).method(*args) class C(B): def method(self, *args): print "A little bit of work gets done in C" super(C, self).method(*args) However, the work done in C.method() makes the work done in B.method() obsolete: I want one to run, or the other, but not both. C does need to inherit from B, for the sake of the other methods, so I want C.method() *only* to skip B while still inheriting from A. (All other methods have to inherit from B as normal.) So what I have done is change the call to super in C to super(B, self) instead of super(C, self). It seems to work, but is this safe to do? Or are there strange side-effects I haven't seen yet? -- Steven From clp2 at rebertia.com Sun Aug 2 09:02:10 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 Aug 2009 06:02:10 -0700 Subject: Skipping a superclass In-Reply-To: <02857910$0$20667$c3e8da3@news.astraweb.com> References: <02857910$0$20667$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0908020602u37fee362i35019d16b857f755@mail.gmail.com> On Sun, Aug 2, 2009 at 5:36 AM, Steven D'Aprano wrote: > I have a series of subclasses like this: > > class A(object): > ? ?def method(self, *args): > ? ? ? ?print "Lots of work gets done here in the base class" > > class B(A): > ? ?def method(self, *args): > ? ? ? ?print "A little bit of work gets done in B" > ? ? ? ?super(B, self).method(*args) > > class C(B): > ? ?def method(self, *args): > ? ? ? ?print "A little bit of work gets done in C" > ? ? ? ?super(C, self).method(*args) > > > However, the work done in C.method() makes the work done in B.method() > obsolete: I want one to run, or the other, but not both. C does need to > inherit from B, for the sake of the other methods, so I want C.method() > *only* to skip B while still inheriting from A. (All other methods have > to inherit from B as normal.) > > So what I have done is change the call to super in C to super(B, self) > instead of super(C, self). It seems to work, but is this safe to do? Or > are there strange side-effects I haven't seen yet? Barring some true weirdness in super(), I don't /think/ so. It obviously works fine in the single-inheritance case, and (after some brute-force testing) the only permitted multiple inheritances involving C and (A or B) always have C ahead of B in the MRO (method resolution order). The fact that you're wanting to bypass a superclass method might suggest however, that your hierarchy could be structured better. Have you considered moving B.method() into another, new class (e.g. newB) which subclasses B? Then C can inherit from B without inheriting the unwanted method, while B's functionality still exists, just under a new name (newB). Cheers, Chris -- http://blog.rebertia.com From lists at cheimes.de Sun Aug 2 09:08:25 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 02 Aug 2009 15:08:25 +0200 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7djs50F2bsubuU1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: Michael M Mason wrote: > I'm running Python 3.1 on Vista and I can't figure out how to add my own > directory to sys.path. > > The docs suggest that I can either add it to the PYTHONPATH environment > variable or to the PythonPath key in the registry. However, PYTHONPATH > doesn't exist, and updating the registry key has no effect (and in any case > the contents aren't the same as sys.path). > > So where does sys.path get its value from, and how do I change it? You can use my PEP 370 (http://python.org/dev/peps/pep-0370/) and a .pth file to extend the search path for modules. >>> import os >>> import site >>> site.USER_SITE '/home/heimes/.local/lib/python2.6/site-packages' >>> if not os.path.isdir(site.USER_SITE): ... os.makedirs(site.USER_SITE) ... >>> pth = open(os.path.join(site.USER_SITE, "michal.pth"), "w") >>> pth.write("C:/Users/Michael/Code/Python\n") >>> pth.close() Restart Python, your custom search path should be in sys.path. Christian From ifl2009 at shu.edu Sun Aug 2 09:34:37 2009 From: ifl2009 at shu.edu (IFL 2009) Date: Sun, 2 Aug 2009 09:34:37 -0400 Subject: IFL 2009: Call for Papers and Participation Message-ID: An HTML attachment was scrubbed... URL: From fatkinson at mishmash.com Sun Aug 2 09:42:52 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sun, 02 Aug 2009 06:42:52 -0700 Subject: Seeding the rand() Generator Message-ID: How does one seed the rand() generator when retrieving random recordings in MySQL? Regards, Fred From jizzai at gmail.com Sun Aug 2 09:50:14 2009 From: jizzai at gmail.com (Jizzai) Date: Sun, 02 Aug 2009 13:50:14 GMT Subject: Is python buffer overflow proof? Message-ID: Is a _pure_ python program buffer overflow proof? For example in C++ you can declare a char[9] to hold user input. If the user inputs 10+ chars a buffer overflow occurs. In python, I cannot seem to find a way to define/restrict a string length. This is probably by design and raises the topic in question. Am curious to see the opinions of people who know. TIA. From albert at spenarnc.xs4all.nl Sun Aug 2 09:54:04 2009 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 02 Aug 2009 13:54:04 GMT Subject: Colour of output text References: <03c4ceed-c49b-4dd0-a585-e6169b02e0eb@26g2000yqk.googlegroups.com> Message-ID: In article , Jean-Michel Pichavant wrote: >Nobody wrote: >> On Fri, 10 Jul 2009 09:23:54 +0000, garabik-news-2005-05 wrote: >> >> >>>>> I would like to learn a way of changing the colour of a particular >>>>> part of the output text. I've tried the following >>>>> >>>> On Unix operating systems this would be done through the curses interface: >>>> >>>> http://docs.python.org/library/curses.html >>>> >>> Or using ANSI colour codes: >>> >>> colours = { >>> 'none' : "", >>> 'default' : "\033[0m", >>> 'bold' : "\033[1m", >>> >> >> [snip] >> >> >>> # non-standard attributes, supported by some terminals >>> >> >> This comment should have appeared immediately after "none" ;) >> >> Hard-coding control/escape sequences is just lame. Use the curses modules >> to obtain the correct sequences for the terminal. >> >> >As the OP I'm really interested in doing so. I currently have all my >colors hard-coded. >Now It may be lame but as soon as I call curses.initscr(), it's just >messing up with my terminal, moreover I didn't figure out how to "print >'hello'" using curses color codes. >Anyone has an example ? I'm pretty sure it may fit in one line. In general initscr() ought to work. It fails if it has no/a wrong idea of what your terminal is. In the same shell as you run run your program type set | grep -i term Now some entry should show up, e.g. TERM=xterm infocmp $TERM should fetch information about your terminal, from the same source as curses does. Possible problems are: - your operating system/configurations lies to curses about the terminal or your terminal is not specified at all - curses has not been properly installed and cannot find the database Groetjes Albert > >JM > > -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From lob8682 at gmail.com Sun Aug 2 09:58:47 2009 From: lob8682 at gmail.com (Kamal Kamal) Date: Sun, 2 Aug 2009 06:58:47 -0700 (PDT) Subject: "PAK WEB" "PAK WEB TV" "PAK WEBSITES" "PAK WEB DIRECTORY" "PAK WEB HOSTING" "PAK WEB HOST" "PAK WEB HOSTING" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" on www.pak-web-pages.blogspot.com Message-ID: "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB TV" www.pak-web-pages.blogspot.com "PAK WEBSITES" www.pak-web-pages.blogspot.com "PAK WEB DIRECTORY" www.pak-web-pages.blogspot.com "PAK WEB HOSTING" www.pak-web-pages.blogspot.com "PAK WEB HOST" www.pak-web-pages.blogspot.com "PAK WEB HOSTING" www.pak-web-pages.blogspot.com "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" "PAK WEB" "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" on www.pak-web-pages.blogspot.com From albert at spenarnc.xs4all.nl Sun Aug 2 10:14:53 2009 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 02 Aug 2009 14:14:53 GMT Subject: A Bug By Any Other Name ... References: Message-ID: In article , J. Cliff Dyer wrote: >On Fri, 2009-07-17 at 20:53 +0000, Albert van der Horst wrote: >> Because unlike in algol 68 in python whitespace is relevant, >> we could get by with requiring whitespace: >> x= -q # okay >> a> 8 ** -2 # okay > >This is actually quite thoroughly untrue. In python, *indentation* is >significant. Whitespace (internal to a line) is not. You can even call >methods like this if you want: You totally don't get it. You describe how python is now. I propose a change to be made to python. Small wonder that that is different from what it is now. > >>>> s = 'abc' >>>> s . upper() >ABC You prove nothing by giving examples. You can disprove by giving one counter example, here it goes. Whitespace (internal to a line) is significant. In Python you cannot change xleftgoing = 123000000 to x left going = 123 000 000 (You can in Algol68) >Obviously, that's A Bad Idea(tm), but python's parser won't stop you. What is a bad idea? Apparently you are not talking about my idea of changing the parser. ("Pythons parser won't stop you from changing the parser" doesn't make sense.) >The ++ operator gotcha is so minor that I can't remember anyone actually >asking about it on the list (who was actually facing it as a >problem--this thread was started by idle speculation). Can we not >change the language syntax to address non-issues? As other languages have an Eleventh Commandment against concatenating operators, the larger issue is hardly futile. > >Practicality beats purity, a.k.a. don't you have something better to do? I'm having a great time, thank you! >Cheers, >Cliff Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From marcusw at cox.net Sun Aug 2 10:32:39 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sun, 02 Aug 2009 10:32:39 -0400 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: On 8/2/2009 9:50 AM, Jizzai wrote: > Is a _pure_ python program buffer overflow proof? > > For example in C++ you can declare a char[9] to hold user input. > If the user inputs 10+ chars a buffer overflow occurs. > > In python, I cannot seem to find a way to define/restrict a string length. > This is probably by design and raises the topic in question. > > Am curious to see the opinions of people who know. > > TIA. I believe that python is buffer overflow proof. In fact, I think that even ctypes is overflow proof... Marcus From marcusw at cox.net Sun Aug 2 10:36:18 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sun, 02 Aug 2009 10:36:18 -0400 Subject: Seeding the rand() Generator In-Reply-To: References: Message-ID: On 8/2/2009 9:42 AM, Fred Atkinson wrote: > How does one seed the rand() generator when retrieving random > recordings in MySQL? > > Regards, > > > > Fred something like: import random, time random.seed(time.time()) #not actual record access code: sqlite3.recordaccessfuction(recordid = random.rand()) Marcus From lists at cheimes.de Sun Aug 2 10:43:25 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 02 Aug 2009 16:43:25 +0200 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: Marcus Wanner wrote: > I believe that python is buffer overflow proof. In fact, I think that > even ctypes is overflow proof... No, ctypes isn't buffer overflow proof. ctypes can break and crash a Python interpreter easily. Christian From matt.urry at googlemail.com Sun Aug 2 10:45:39 2009 From: matt.urry at googlemail.com (ma3mju) Date: Sun, 2 Aug 2009 07:45:39 -0700 (PDT) Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> Message-ID: <206a63e2-9159-44f0-ac5c-a14055448b47@h21g2000yqa.googlegroups.com> On 31 July, 11:27, Piet van Oostrum wrote: > >>>>> ma3mju (m) wrote: > >m> Hi all, > >m> I'm having trouble with multiprocessing I'm using it to speed up some > >m> simulations, I find for large queues when the process reaches the > >m> poison pill it does not exit whereas for smaller queues it works > >m> without any problems. Has anyone else had this trouble? Can anyone > >m> tell me a way around it? The code is in two files below. > > How do you know it doesn't exit. You haven't shown any of your output. > > I did discover a problem in your code, but it should cause an exception: > > >m> #set off some of the easy workers on the hard work (maybe double > >m> number of hard) > >m> for i in range(0,num_hard_workers): > >m> ? ? hard_work_queue.put(None) > >m> ? ? hard_workers.append(multiprocessing.Process > >m> (target=GP.RandomWalkGeneralizationErrorParallel,args= > >m> (hard_work_queue,result_queue,))) > >m> #wait for all hard workers to finish > >m> for worker in hard_workers: > >m> ? ? worker.join() > > Here you create new hard workers, but you never start them. The join > should then give an exception when it reaches these. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org Ok thanks I'll change that In a sec, It never reaches that bit of code because the easy_workers don't exit so it never gets past the join(). As far as running it goes I get the datapt and number of points printed to the list for everything in both queues. When it reaches the end of either queue I get "Poison" on the screen then "here" for each process but I don't get "worker joined" and as expected don't get "this should not appear". If I have a look at the processes running after all queues are supposed to have finished I see all of them running taking little or no resources. This is running on Ubuntu Jaunty at home and the same happens on the Debian machine at uni. The weird thing is that if I run them with less points the processes do manage to exit. Thanks Matt From matt.urry at googlemail.com Sun Aug 2 10:48:44 2009 From: matt.urry at googlemail.com (ma3mju) Date: Sun, 2 Aug 2009 07:48:44 -0700 (PDT) Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> Message-ID: <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> On 31 July, 11:34, MRAB wrote: > ma3mju wrote: > > Hi all, > > > I'm having trouble with multiprocessing I'm using it to speed up some > > simulations, I find for large queues when the process reaches the > > poison pill it does not exit whereas for smaller queues it works > > without any problems. Has anyone else had this trouble? Can anyone > > tell me a way around it? The code is in two files below. > > [snip] > > > #get number of cores and set the number on concurrent processes > > num_hard_workers = 2 > > num_workers = multiprocessing.cpu_count()*1.5 > > easy_workers = [] > > hard_workers = [] > > #add poison pill for each worker and create the worker > > for i in range(0,num_workers-num_hard_workers): > > ? ? easy_work_queue.put(None) > > ? ? easy_workers.append(multiprocessing.Process > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > (easy_work_queue,result_queue,))) > > for i in range(0,num_hard_workers): > > ? ? hard_work_queue.put(None) > > ? ? hard_workers.append(multiprocessing.Process > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > (hard_work_queue,result_queue,))) > > You have 2 hard workers and ceil(CPU_count * 1.5) - 2 easy workers. > What if the number of CPUs was 1? That would give 2 hard and 0 easy! > > Also, I recommend that you put only 1 'poison pill' in each queue and > have the workers put it back when they see it. I'll give that a go in a sec and see if it helps. The processes quit out for smaller queues though so it should in theory be alright. I'm not too fussed about the CPU's it's only there because I change between a uni PC and home one with a different number of cores in each but both greater than one. From Scott.Daniels at Acm.Org Sun Aug 2 11:11:22 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 02 Aug 2009 08:11:22 -0700 Subject: Predefined Variables In-Reply-To: References: Message-ID: Piet van Oostrum wrote: >>>>>> Scott David Daniels (SDD) wrote: >> SDD> Stephen Cuppett (should have written in this order): >>>> "Fred Atkinson" wrote ... >>>>> Is there a pre-defined variable that returns the GET line... >>>> os.environment('QUERY_STRING') >> SDD> Maybe you mean: >> SDD> os.environ['USER'] > Let's take the best of both: > os.environ['QUERY_STRING'] Sorry about that. I was testing expression before posting, and I don't do that much cgi stuff. I forgot to restore the variable name. --Scott David Daniels Scott.Daniels at Acm.Org From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 11:18:27 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 15:18:27 GMT Subject: Is python buffer overflow proof? References: Message-ID: <02859ef9$0$20667$c3e8da3@news.astraweb.com> On Sun, 02 Aug 2009 13:50:14 +0000, Jizzai wrote: > Is a _pure_ python program buffer overflow proof? It's supposed to be. > For example in C++ you can declare a char[9] to hold user input. If the > user inputs 10+ chars a buffer overflow occurs. > > In python, I cannot seem to find a way to define/restrict a string > length. This is probably by design and raises the topic in question. That's a separate issue from being buffer overflow proof. You can't specify that a string have a maximum of N characters except by slicing the string after it's formed: s = "x"*10000 # Make a big string. s = s[:100] # Limit it to 100 characters. But Python won't overflow any buffers even if you try to create a truly huge string: s = "x"*(1024**4) # Try to create a 1 TB string. Your PC will run slow while Python and the OS tries to allocate 1TB of memory, then it will safely raise MemoryError. Pure Python should never dump core. -- Steven From Scott.Daniels at Acm.Org Sun Aug 2 11:53:50 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 02 Aug 2009 08:53:50 -0700 Subject: Seeding the rand() Generator In-Reply-To: References: Message-ID: Fred Atkinson wrote: > How does one seed the rand() generator when retrieving random > recordings in MySQL? It is not entirely clear what you are asking. If you are talking about MySQL's random number generator, you are talking in the wrong newsgroup. If you are talking about Python's, does this work? import random random.seed(123542552) I'm not quite sure how you came to believe that Python controls MySQL, as opposed to using its services. --Scott David Daniels Scott.Daniels at Acm.Org From matt.urry at googlemail.com Sun Aug 2 12:57:44 2009 From: matt.urry at googlemail.com (ma3mju) Date: Sun, 2 Aug 2009 09:57:44 -0700 (PDT) Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> Message-ID: <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> On 2 Aug, 15:48, ma3mju wrote: > On 31 July, 11:34, MRAB wrote: > > > > > ma3mju wrote: > > > Hi all, > > > > I'm having trouble with multiprocessing I'm using it to speed up some > > > simulations, I find for large queues when the process reaches the > > > poison pill it does not exit whereas for smaller queues it works > > > without any problems. Has anyone else had this trouble? Can anyone > > > tell me a way around it? The code is in two files below. > > > [snip] > > > > #get number of cores and set the number on concurrent processes > > > num_hard_workers = 2 > > > num_workers = multiprocessing.cpu_count()*1.5 > > > easy_workers = [] > > > hard_workers = [] > > > #add poison pill for each worker and create the worker > > > for i in range(0,num_workers-num_hard_workers): > > > ? ? easy_work_queue.put(None) > > > ? ? easy_workers.append(multiprocessing.Process > > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > > (easy_work_queue,result_queue,))) > > > for i in range(0,num_hard_workers): > > > ? ? hard_work_queue.put(None) > > > ? ? hard_workers.append(multiprocessing.Process > > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > > (hard_work_queue,result_queue,))) > > > You have 2 hard workers and ceil(CPU_count * 1.5) - 2 easy workers. > > What if the number of CPUs was 1? That would give 2 hard and 0 easy! > > > Also, I recommend that you put only 1 'poison pill' in each queue and > > have the workers put it back when they see it. > > I'll give that a go in a sec and see if it helps. The processes quit > out for smaller queues though so it should in theory be alright. I'm > not too fussed about the CPU's it's only there because I change > between a uni PC and home one with a different number of cores in each > but both greater than one. Just tried changing the poison pill part to no avail sadly From tjreedy at udel.edu Sun Aug 2 14:07:44 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 02 Aug 2009 14:07:44 -0400 Subject: Generate a new object each time a name is imported In-Reply-To: References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: Peter Otten wrote: > Steven D'Aprano wrote: >> I'm looking for a way to hide the generation of objects from the caller, >> so I could do something like this: >> >> from Module import factory() as a # a == "Object #1" >> from Module import factory() as b # b == "Object #2" >> >> except of course that syntax is illegal. > > How about For newbies who do not get how the following works, but would like to know, I am adding some explanation. >>>> class A(object): > ... def __init__(self): > ... self._n = 0 > ... @property > ... def a(self): > ... try: > ... return self._n > ... finally: > ... self._n += 1 The @property decorator turns the 'a' function into the hidden getter function for what looks to the outside world like a simple instance attribute named 'a'. >>>> import sys >>>> sys.modules["yadda"] = A() sys.modules is a system namespace that normally associates names with modules. It is used by import statements to find existing modules. However, there is no requirement that the associated object actually be a module. A module is simply a collection of objects accessed as attributes. One can get and set attributes of a module, and but hardly anyhing else. Other attribute collection objects will do as well as far as imports are concerned. 'If it quack like a duck (module in this case)...' The above sets the 'module' to an *instance* of class A. >>>> from yadda import a This looks for the 'module' named 'yadda'. It finds one - the instance of A. It then requests attribute 'a' (of that instance). That request is routed to the getter function. This import statement could be in any module, not just the one that set A() as a module surrogate. >>>> from yadda import a as b >>>> a, b > (0, 1) As Peter mentioned in his followup, module surrogates were intended for lazy imports of expensive-to-compute attributes that might never be needed, so their creation could be delayed to whenever needed, if ever. Tricks like the above are not recommended for normal usage, but do illstrate some aspects of the language. Terry Jan Reedy From catalinfest at gmail.com Sun Aug 2 14:13:13 2009 From: catalinfest at gmail.com (catafest) Date: Sun, 2 Aug 2009 11:13:13 -0700 (PDT) Subject: How to read webpage References: Message-ID: <44c17767-e08e-4c8c-ae1f-0e11e54d3485@o6g2000yqj.googlegroups.com> Maybe your python2.5 not working good!? But, I use python 2.6 , and i use this for your problem: import urllib html = urllib.urlopen("http://www.rediff.com/").read() print html If you want use authenticate then... You make working urllib2 and use this >>>auth = urllib2.Request(auth_uri, authreq_data) On Aug 1, 4:52?pm, MRAB wrote: > tarun wrote: > > Dear All, > > I want to read a webpage and copy the contents of it in word file. I > > tried to write following code: > > > import urllib2 > > urllib2.urlopen("http://www.rediff.com/") > > > *Error:-* > > > ? ? urllib2.urlopen("http://www.icicibank.com/") > > ? File "C:\Python25\lib\urllib2.py", line 121, in urlopen > > ? ? return _opener.open(url, data) > > ? File "C:\Python25\lib\urllib2.py", line 374, in open > > ? ? response = self._open(req, data) > > ? File "C:\Python25\lib\urllib2.py", line 392, in _open > > ? ? '_open', req) > > ? File "C:\Python25\lib\urllib2.py", line 353, in _call_chain > > ? ? result = func(*args) > > ? File "C:\Python25\lib\urllib2.py", line 1100, in http_open > > ? ? return self.do_open(httplib.HTTPConnection, req) > > ? File "C:\Python25\lib\urllib2.py", line 1075, in do_open > > ? ? raise URLError(err) > > urllib2.URLError: > > I've just tried it. I didn't get an exception, so your problem must be > elsewhere. From python at mrabarnett.plus.com Sun Aug 2 14:25:36 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 02 Aug 2009 19:25:36 +0100 Subject: Processes not exiting In-Reply-To: <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> Message-ID: <4A75DA20.7050209@mrabarnett.plus.com> ma3mju wrote: > On 2 Aug, 15:48, ma3mju wrote: >> On 31 July, 11:34, MRAB wrote: >> >> >> >>> ma3mju wrote: >>>> Hi all, >>>> I'm having trouble with multiprocessing I'm using it to speed up some >>>> simulations, I find for large queues when the process reaches the >>>> poison pill it does not exit whereas for smaller queues it works >>>> without any problems. Has anyone else had this trouble? Can anyone >>>> tell me a way around it? The code is in two files below. >>> [snip] >>>> #get number of cores and set the number on concurrent processes >>>> num_hard_workers = 2 >>>> num_workers = multiprocessing.cpu_count()*1.5 >>>> easy_workers = [] >>>> hard_workers = [] >>>> #add poison pill for each worker and create the worker >>>> for i in range(0,num_workers-num_hard_workers): >>>> easy_work_queue.put(None) >>>> easy_workers.append(multiprocessing.Process >>>> (target=GP.RandomWalkGeneralizationErrorParallel,args= >>>> (easy_work_queue,result_queue,))) >>>> for i in range(0,num_hard_workers): >>>> hard_work_queue.put(None) >>>> hard_workers.append(multiprocessing.Process >>>> (target=GP.RandomWalkGeneralizationErrorParallel,args= >>>> (hard_work_queue,result_queue,))) >>> You have 2 hard workers and ceil(CPU_count * 1.5) - 2 easy workers. >>> What if the number of CPUs was 1? That would give 2 hard and 0 easy! >>> Also, I recommend that you put only 1 'poison pill' in each queue and >>> have the workers put it back when they see it. >> I'll give that a go in a sec and see if it helps. The processes quit >> out for smaller queues though so it should in theory be alright. I'm >> not too fussed about the CPU's it's only there because I change >> between a uni PC and home one with a different number of cores in each >> but both greater than one. > > Just tried changing the poison pill part to no avail sadly I wonder whether one of the workers is raising an exception, perhaps due to lack of memory, when there are large number of jobs to process. Another question: why are you distinguishing between easy and hard jobs? Do you actually get a measurable improvement in performance from doing it this way instead of having just a single queue of jobs and a single pool of workers? From piet at cs.uu.nl Sun Aug 2 14:26:55 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 20:26:55 +0200 Subject: Get Cliet IP Address References: Message-ID: >>>>> Fred Atkinson (FA) wrote: >FA> What is the function to obtain the client browser's IP >FA> address? You mean in a web server? The following should work (and was posted by me not long ago): from os import getenv ip = (getenv("HTTP_CLIENT_IP") or getenv("HTTP_X_FORWARDED_FOR") or getenv("HTTP_X_FORWARDED_FOR") or getenv("REMOTE_ADDR") or "UNKNOWN") I use getenv() rather than environ[] to avoid exceptions. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From piet at cs.uu.nl Sun Aug 2 14:31:07 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 20:31:07 +0200 Subject: cgi script References: Message-ID: >>>>> golu (g) wrote: >g> Hi, >g> i started learning cgi few days ago in python and everything went >g> fine until i started getting the follwing error >g> " >g> The server encountered an internal error and was unable to complete >g> your request. Either the server is overloaded or there was an error in >g> a CGI script. >g> If you think this is a server error, please contact the webmaster. " >g> i am using apache on xampp. plz help Putting the following in your script might help as it will show the exception trace in your browser (if it gets that far, that is). import cgitb cgitb.enable() -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From REMpeteOVE at petezilla.co.uk Sun Aug 2 15:21:06 2009 From: REMpeteOVE at petezilla.co.uk (Peter Chant) Date: Sun, 02 Aug 2009 20:21:06 +0100 Subject: Building / making an application Message-ID: <2i5hk6-8gh.ln1@phoenix.fire> What is a good way to do this? There are instructions on making modules at: http://docs.python.org/distutils/setupscript.html however, what do you do if you don't want a module? I'm thinking of where I'd like to split the code into several files and have a build / setup script put it together and install it somewhere such as /usr/local/bin. I'm interested in what the standard way of doing this is. Thanks, Pete -- http://www.petezilla.co.uk From piet at cs.uu.nl Sun Aug 2 15:25:02 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 21:25:02 +0200 Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> <8bede581-f260-4c69-abf0-1e8071380b76@z4g2000prh.googlegroups.com> <7e6cdc26-bcc0-4503-b7b4-9ad80b1041f6@v37g2000prg.googlegroups.com> Message-ID: >>>>> NighterNet (N) wrote: >N> Here the full code. >N> flashpolicy.xml >N> [[[ >N> >N> >N> >N> >N> ]]] >N> flashpolicytest_server3x.py >N> [[[ >N> #!/usr/local/bin/python >N> ''' >N> Still under testing... >N> python version 3.x.x >N> ''' >N> import socket >N> import threading >N> import sys >N> import os >N> file_name = 'flashpolicy.xml' >N> fh = open(file_name, "r") >N> policy = fh.read(10001) You never use that variable. >N> host = ''; #out side network >N> port = 5555; >N> print ("# ------------- Init... ------------- #"); >N> class ClientThread (threading.Thread): >N> global policy; >N> allClients = []; >N> vlock = threading.Lock(); >N> id = 0 # next available thread number >N> def __init__(self,clientSocket): >N> threading.Thread.__init__(self) >N> self.sockfd = clientSocket; #socket client >N> self.name = ''; >N> ClientThread.id += 1 >N> self.id = ClientThread.id >N> self.nickName = ''; >N> self.allClients.append(self.sockfd); >N> def sendAll(self,buff): >N> for index,clientSock in enumerate(self.allClients): >N> try: >N> clientSock.send(buff); There is no guarantee that send will indeed transmit all of buff. It is better to use clientSock.sendall(buff). Or you should check the return value of send and check if it is equal to the length of buff. And repeat if not. (But sendall is easier). Also don't use ; at the end of the statement. It's not pythonic. >N> except (socket.error): >N> print ('error socket %s\n',index,"| clean"); >N> clientSock.close() >N> del self.allClients[index] >N> def run(self): >N> while True: >N> buff = self.sockfd.recv(1028); There is no guarantee that recv will get the whole message. It may even get as little as 1 byte. So you should check the return value of recv. The official way is to keep reading until you have enough input or until you hit end of file. >N> if not buff: >N> print ("connect close...(client side)"); >N> self.sockfd.close(); >N> break #incase it loop infinite >N> if str(buff) == str("b\'\\x00\'"): What you check here is whether buff contains the byte sequence that starts with a b, then a ' ... and ending with the 5 bytes \ x 0 0 ' which is wrong. Actually it should be: if buff == b\'\x00': or if buff == b\'\0': >N> print ('policy FOUND >>> sending...') >N> print(buff) >N> b = b'N> from domain=\"*\" to-ports=\"*\" />' >N> print (b) >N> self.sockfd.send(b); >N> self.sockfd.sendall(b); Only self.sockfd.sendall; delete the line with self.sockfd.send(b). And remove the semicolons for esthetical reasons. >N> Some odd reason I can't send flash policy from python to flash socket >N> to agrees with the connection. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From hackingkk at gmail.com Sun Aug 2 15:32:10 2009 From: hackingkk at gmail.com (Krishnakant) Date: Mon, 03 Aug 2009 01:02:10 +0530 Subject: Building / making an application In-Reply-To: <2i5hk6-8gh.ln1@phoenix.fire> References: <2i5hk6-8gh.ln1@phoenix.fire> Message-ID: <1249241530.4541.12.camel@krishna-laptop> On Sun, 2009-08-02 at 20:21 +0100, Peter Chant wrote: > What is a good way to do this? There are instructions on making modules at: > > http://docs.python.org/distutils/setupscript.html > > however, what do you do if you don't want a module? I'm thinking of where > I'd like to split the code into several files and have a build / setup > script put it together and install it somewhere such as /usr/local/bin. > I'm interested in what the standard way of doing this is. > Have you considered creating a deb or rpm package for your application? Most of the documentation for deb or rpm will talk about make files. But even a distutil based python package (with a setup.py) can be made into a deb package. Then the your requirement will be satisfied at least for most gnu/linux based distros. happy hacking. Krishnakant. From REMpeteOVE at petezilla.co.uk Sun Aug 2 16:00:15 2009 From: REMpeteOVE at petezilla.co.uk (Peter Chant) Date: Sun, 02 Aug 2009 21:00:15 +0100 Subject: Building / making an application References: <2i5hk6-8gh.ln1@phoenix.fire> Message-ID: Krishnakant wrote: > Have you considered creating a deb or rpm package for your application? > Most of the documentation for deb or rpm will talk about make files. > But even a distutil based python package (with a setup.py) can be made > into a deb package. > Then the your requirement will be satisfied at least for most gnu/linux > based distros. I'm a slacker, so what I would do would be to make a slack build, the slackbuild would take the source and build that. The stage I am at is the "how to build the source" stage. Don't really intend to get as far as distribution specific packages. What I could do is create a script in the source root directory (that sounds a bit overblown) that simply concatenates together all the python files in the right order and perhaps copies the result to /usr/local/bin or /usr/bin as appropriate. Is that the right way to go? It looks like distutils is appropriate only for modules. OTOH it might be appropriate to put the bulk of an application in a module and have a function calling it the only part of the main script. Pete -- http://www.petezilla.co.uk From deets at nospam.web.de Sun Aug 2 16:08:00 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 02 Aug 2009 22:08:00 +0200 Subject: Building / making an application In-Reply-To: References: <2i5hk6-8gh.ln1@phoenix.fire> Message-ID: <7dma10F2cd7tnU1@mid.uni-berlin.de> Peter Chant schrieb: > Krishnakant wrote: > > >> Have you considered creating a deb or rpm package for your application? >> Most of the documentation for deb or rpm will talk about make files. >> But even a distutil based python package (with a setup.py) can be made >> into a deb package. >> Then the your requirement will be satisfied at least for most gnu/linux >> based distros. > > I'm a slacker, so what I would do would be to make a slack build, the > slackbuild would take the source and build that. The stage I am at is > the "how to build the source" stage. Don't really intend to get as far as > distribution specific packages. > > What I could do is create a script in the source root directory (that sounds > a bit overblown) that simply concatenates together all the python files in > the right order and perhaps copies the result to /usr/local/bin or /usr/bin > as appropriate. Is that the right way to go? It looks like distutils is > appropriate only for modules. > > OTOH it might be appropriate to put the bulk of an application in a module > and have a function calling it the only part of the main script. You should consider using setuptools. Then you get an egg that people can install, and you can define "console_scripts"-entry-points which will be installed into /usr/local/bin or similar locations. Diez From aahz at pythoncraft.com Sun Aug 2 16:15:00 2009 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2009 13:15:00 -0700 Subject: Help with Regex for domain names References: <0422bf8f-ce59-4de2-a1a4-b16a32e5f152@o15g2000yqm.googlegroups.com> Message-ID: In article , MRAB wrote: >Nobody wrote: >> On Thu, 30 Jul 2009 10:29:09 -0700, rurpy wrote: >> >>>> regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)') >>> You might also want to consider that some country >>> codes such as "co" for Columbia might match more than >>> you want, for example: >>> >>> re.match(r'[\w\-\.]+\.(?:us|au|de|co)', 'foo.boo.com') >>> >>> will match. >> >> ... so put \b at the end, i.e.: >> >> regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)\b') >> >It would still match "www.bbc.co.uk", so you might need: > >regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)\b(?!\.\b)') If it's a string containing just the candidate domain, you can do regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)$') -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Many customs in this life persist because they ease friction and promote productivity as a result of universal agreement, and whether they are precisely the optimal choices is much less important." --Henry Spencer From piet at cs.uu.nl Sun Aug 2 16:49:05 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 22:49:05 +0200 Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> Message-ID: >>>>> MRAB (M) wrote: >M> I wonder whether one of the workers is raising an exception, perhaps due >M> to lack of memory, when there are large number of jobs to process. But that wouldn't prevent the join. And you would probably get an exception traceback printed. I wonder if something fishy is happening in the multiprocessing infrastructure. Or maybe the Fortran code goes wrong because it has no protection against buffer overruns and similar problems, I think. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From fatkinson at mishmash.com Sun Aug 2 17:18:28 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sun, 02 Aug 2009 14:18:28 -0700 Subject: Seeding the rand() Generator References: Message-ID: On Sun, 02 Aug 2009 08:53:50 -0700, Scott David Daniels wrote: >Fred Atkinson wrote: >> How does one seed the rand() generator when retrieving random >> recordings in MySQL? > >It is not entirely clear what you are asking. If you are talking about >MySQL's random number generator, you are talking in the wrong newsgroup. >If you are talking about Python's, does this work? > import random > random.seed(123542552) >I'm not quite sure how you came to believe that Python controls MySQL, >as opposed to using its services. > >--Scott David Daniels >Scott.Daniels at Acm.Org I am coding in Python. I am accessing a MySQL database. I have a string to instruct the MySQL database to use the 'rand()' function to randomly choose one of the records in the database. I know how to seed it in PHP. Does anyone know how to see it from with Python? Regards, Fred From fatkinson at mishmash.com Sun Aug 2 17:20:02 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sun, 02 Aug 2009 14:20:02 -0700 Subject: Predefined Variables References: Message-ID: On Sun, 02 Aug 2009 08:11:22 -0700, Scott David Daniels wrote: >Piet van Oostrum wrote: >>>>>>> Scott David Daniels (SDD) wrote: >>> SDD> Stephen Cuppett (should have written in this order): >>>>> "Fred Atkinson" wrote ... >>>>>> Is there a pre-defined variable that returns the GET line... >>>>> os.environment('QUERY_STRING') >>> SDD> Maybe you mean: >>> SDD> os.environ['USER'] >> Let's take the best of both: >> os.environ['QUERY_STRING'] > >Sorry about that. I was testing expression before posting, and I don't >do that much cgi stuff. I forgot to restore the variable name. > >--Scott David Daniels >Scott.Daniels at Acm.Org I finally got it to work with x =getenv('QUERY_STRING') Regards, Fred From victorsubervi at gmail.com Sun Aug 2 17:22:20 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 2 Aug 2009 16:22:20 -0500 Subject: RE Question Message-ID: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> Hi; How do I search and replace something like this: aLine = re.sub('[<]?[p]?[>]?[<]?[b]?[>]?', '', aLine) where RE *only* looks for the possibility of "

" at the beginning of the string; that is, not the individual components as I have it coded above, but the entire 3-character block? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcusw at cox.net Sun Aug 2 17:51:11 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sun, 02 Aug 2009 17:51:11 -0400 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: On 8/2/2009 10:43 AM, Christian Heimes wrote: > Marcus Wanner wrote: >> I believe that python is buffer overflow proof. In fact, I think that >> even ctypes is overflow proof... > > No, ctypes isn't buffer overflow proof. ctypes can break and crash a > Python interpreter easily. > > Christian > I see. I thought that it said "invalid array index" when you try to read/write outside of an array's bounds, though... Marcus From REMpeteOVE at petezilla.co.uk Sun Aug 2 18:26:08 2009 From: REMpeteOVE at petezilla.co.uk (Peter Chant) Date: Sun, 02 Aug 2009 23:26:08 +0100 Subject: Building / making an application References: <2i5hk6-8gh.ln1@phoenix.fire> <7dma10F2cd7tnU1@mid.uni-berlin.de> Message-ID: <0dghk6-12j.ln1@phoenix.fire> Diez B. Roggisch wrote: > You should consider using setuptools. Then you get an egg that people > can install, and you can define "console_scripts"-entry-points which > will be installed into /usr/local/bin or similar locations. Interesting, I think I need to have a play with that. The cross platform bit could be useful as well. Pete -- http://www.petezilla.co.uk From missive at hotmail.com Sun Aug 2 18:27:49 2009 From: missive at hotmail.com (Lee Harr) Date: Mon, 3 Aug 2009 02:57:49 +0430 Subject: [ANNC] pybotwar-0.3 Message-ID: pybotwar is a fun and educational game where players create computer programs to control simulated robots to compete in a battle arena. http://pybotwar.googlecode.com/ pybotwar uses pybox2d for the physical simulation, and uses pygame and pygsear for the visualization. pybotwar is released under GPLv3. Changes in pybotwar-0.3: - make tarball extract in to versioned directory _________________________________________________________________ With Windows Live, you can organize, edit, and share your photos. http://www.microsoft.com/middleeast/windows/windowslive/products/photo-gallery-edit.aspx From suruti94 at gmail.com Sun Aug 2 19:22:45 2009 From: suruti94 at gmail.com (Mohan Parthasarathy) Date: Sun, 2 Aug 2009 16:22:45 -0700 Subject: Python docs disappointing In-Reply-To: References: Message-ID: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> I am a newbie and about a month old with Python. There is a wealth of material about Python and I am really enjoying learning Python. One thing that could have helped Python documentation is that instead of the very "raw" doc string, it could have used something like PythonDoc (java doc style) so that the functions/classes are documented better. At least I am planning to use PythonDoc for the code that I am going to write. Let me know if there is a better one.. -mohan On Fri, Jul 31, 2009 at 1:10 PM, kj wrote: > > > > I'm pretty new to Python, and I like a lot overall, but I find the > documentation for Python rather poor, overall. > > I'm sure that Python experts don't have this problem: they have > internalized some good ways to access the documentation, are > productive with it, and therefore have lost the ability to see why > the Python documentations is deficient for beginners. This explains > why a suboptimal situation can persist like this: those who are > most able fix it are also the least able to perceive it. > > I've heard similar complaints from other experienced programmers > who are trying out Python for the first time: poor documentation. > > Here is an *entirely typical* example: on some Unix, try > > % pydoc urllib > > The displayed documentation mention the optional parameter "data" > in practically every function listed (a few dozen of them). This > parameter is not documented *anywhere* on that page. All that we > are told is that its default value is always None. > > I'm sure that I can find a full description of this parameter if > I fire up Google, and search online. In fact, more likely than > not, I'll find far more documentation than I want. But my point > is that a programmer should not need to do this. The full > documentation should be readily accessible directly through a few > keystrokes. > > I would love to know how experienced Python programmers quickly > zero in on the Python documentation they need. > > TIA! > > kynn > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Aug 2 19:40:20 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 Aug 2009 16:40:20 -0700 Subject: Python docs disappointing In-Reply-To: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> References: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> Message-ID: <50697b2c0908021640o38f1de9fnd778da4d985c4672@mail.gmail.com> > On Fri, Jul 31, 2009 at 1:10 PM, kj wrote: >> I'm pretty new to Python, and I like a lot overall, but I find the >> documentation for Python rather poor, overall. >> >> I'm sure that Python experts don't have this problem: they have >> internalized some good ways to access the documentation, are >> productive with it, and therefore have lost the ability to see why >> the Python documentations is deficient for beginners. ?This explains >> why a suboptimal situation can persist like this: those who are >> most able fix it are also the least able to perceive it. >> >> I've heard similar complaints from other experienced programmers >> who are trying out Python for the first time: poor documentation. >> >> Here is an *entirely typical* example: on some Unix, try >> >> % pydoc urllib >> >> The displayed documentation mention the optional parameter "data" >> in practically every function listed (a few dozen of them). ?This >> parameter is not documented *anywhere* on that page. ?All that we >> are told is that its default value is always None. >> >> I'm sure that I can find a full description of this parameter if >> I fire up Google, and search online. ?In fact, more likely than >> not, I'll find far more documentation than I want. ?But my point >> is that a programmer should not need to do this. ?The full >> documentation should be readily accessible directly through a few >> keystrokes. >> >> I would love to know how experienced Python programmers quickly >> zero in on the Python documentation they need. On Sun, Aug 2, 2009 at 4:22 PM, Mohan Parthasarathy wrote: > I am a newbie and about a month old with Python. There is a wealth of > material about Python and I am really enjoying learning Python. > > One thing that could have helped Python documentation is that instead of the > very "raw" doc string, it could have used something like PythonDoc (java doc > style) so that the functions/classes are documented better. At least I am > planning to use PythonDoc for the code that I am going to write. Let me know > if there is a better one.. If you use reStructuredText (http://docutils.sf.net/rst.html), you can leverage Sphinx (http://sphinx.pocoo.org/), which generates the superb-looking official Python docs. Cheers, Chris P.S. Please don't top-post (http://en.wikipedia.org/wiki/Top-post) in the future. -- http://blog.rebertia.com From pavlovevidence at gmail.com Sun Aug 2 20:00:40 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 Aug 2009 17:00:40 -0700 (PDT) Subject: Seeding the rand() Generator References: Message-ID: On Aug 2, 2:18?pm, Fred Atkinson wrote: > On Sun, 02 Aug 2009 08:53:50 -0700, Scott David Daniels > > wrote: > >Fred Atkinson wrote: > >> ? ? ? ?How does one seed the rand() generator when retrieving random > >> recordings in MySQL? ? > > >It is not entirely clear what you are asking. ?If you are talking about > >MySQL's random number generator, you are talking in the wrong newsgroup. > >If you are talking about Python's, does this work? > > ? ? import random > > ? ? random.seed(123542552) > >I'm not quite sure how you came to believe that Python controls MySQL, > >as opposed to using its services. > > >--Scott David Daniels > >Scott.Dani... at Acm.Org > > ? ? ? ? I am coding in Python. ? > > ? ? ? ? I am accessing a MySQL database. ? > > ? ? ? ? I have a string to instruct the MySQL database to use the > 'rand()' function to randomly choose one of the records in the > database. ? > > ? ? ? ? I know how to seed it in PHP. ?Does anyone know how to see it > from with Python? ? It sounds like you are using MySQL's rand() function, which means that whatever SQL command you used to seed it in PHP is the same command you would use to seed it in Python. You'll have to give us more information if you want a better answer than that. Carl Banks From lists at cheimes.de Sun Aug 2 20:39:34 2009 From: lists at cheimes.de (Christian Heimes) Date: Mon, 03 Aug 2009 02:39:34 +0200 Subject: Python docs disappointing In-Reply-To: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> References: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> Message-ID: Mohan Parthasarathy schrieb: > I am a newbie and about a month old with Python. There is a wealth of > material about Python and I am really enjoying learning Python. > > One thing that could have helped Python documentation is that instead of the > very "raw" doc string, it could have used something like PythonDoc (java doc > style) so that the functions/classes are documented better. At least I am > planning to use PythonDoc for the code that I am going to write. Let me know > if there is a better one.. Several projects are trying to improve the doc strings with an extended syntax. Personally I prefer the epytext syntax from epydoc [1]. It's a JavaDoc like markup language that extends the raw doc strings with useful information. Christian [1] http://epydoc.sourceforge.net/manual-epytext.html From r1chardj0n3s at gmail.com Sun Aug 2 21:07:55 2009 From: r1chardj0n3s at gmail.com (Richard Jones) Date: Mon, 3 Aug 2009 11:07:55 +1000 Subject: Registation is open for the 9th PyWeek game programming challenge! Message-ID: <3A356906-89BE-47A4-9ECE-4C87A7EA89BE@gmail.com> The ninth PyWeek challenge will run between: Sunday 30th August to Sunday 6th September (00:00UTC to 00:00UTC) The PyWeek challenge invites entrants to write a game in one week from scratch either as an individual or in a team. Entries must be developed in Python, during the challenge, and must incorporate some theme chosen at the start of the challenge. REGISTRATION IS NOW OPEN -- Visit the challenge website to sign up, join discussions in the message board or read the timetable and rules: http://www.pyweek.org/9/ PLANNING FOR THE CHALLENGE -- Make sure you have working versions of the libraries you're going to use. The rules page has a list of libraries and other resources. Make sure you can build packages to submit as your final submission (if you're going to use py2exe, make sure you know how to use it and that it works). If you don't have access to Linux, Windows or a Mac to test on, contact friends, family or other competitors to find someone who is able to test for you. From milesck at umich.edu Sun Aug 2 21:15:10 2009 From: milesck at umich.edu (Miles Kaufmann) Date: Sun, 2 Aug 2009 18:15:10 -0700 Subject: Skipping a superclass In-Reply-To: <02857910$0$20667$c3e8da3@news.astraweb.com> References: <02857910$0$20667$c3e8da3@news.astraweb.com> Message-ID: <3597BCD2-E6D1-4A76-85A2-6C1CA3D8B40B@umich.edu> On Aug 2, 2009, at 5:36 AM, Steven D'Aprano wrote: > I have a series of subclasses like this: > > class A(object): > def method(self, *args): > print "Lots of work gets done here in the base class" > > class B(A): > def method(self, *args): > print "A little bit of work gets done in B" > super(B, self).method(*args) > > class C(B): > def method(self, *args): > print "A little bit of work gets done in C" > super(C, self).method(*args) > > > However, the work done in C.method() makes the work done in B.method() > obsolete: I want one to run, or the other, but not both. C does need > to > inherit from B, for the sake of the other methods, so I want > C.method() > *only* to skip B while still inheriting from A. (All other methods > have > to inherit from B as normal.) This might not be applicable to the larger problem you're trying to solve, but for this sample, I would write it as: class A(object): def method(self, *args): self._method(*args) print "Lots of work gets done here in the base class" def _method(self, *args): pass # or perhaps raise NotImplemented class B(A): def _method(self, *args): print "A little bit of work gets done in B" class C(B): def _method(self, *args): print "A little bit of work gets done in C" > So what I have done is change the call to super in C to super(B, self) > instead of super(C, self). It seems to work, but is this safe to do? > Or > are there strange side-effects I haven't seen yet? In a diamond-inheritance situation, you may end up skipping methods besides just B.method(). -Miles From wuwei23 at gmail.com Sun Aug 2 21:23:39 2009 From: wuwei23 at gmail.com (alex23) Date: Sun, 2 Aug 2009 18:23:39 -0700 (PDT) Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <182b3193-d249-4887-ad23-b9c5a3b6dcd8@y4g2000prf.googlegroups.com> On Aug 3, 4:07?am, Terry Reedy wrote: > Peter Otten wrote: > > Steven D'Aprano wrote: [...] Fantastic question, answer & explanation, guys. Well done. From torriem at gmail.com Sun Aug 2 21:36:08 2009 From: torriem at gmail.com (Michael Torrie) Date: Sun, 02 Aug 2009 19:36:08 -0600 Subject: Queryable Daemon In-Reply-To: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> References: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Message-ID: <4A763F08.3000504@gmail.com> Justin DeCell wrote: > I was hoping for a little help with a project I'm working on. I'm > writing a daemon in python that I want to be queryable (i.e. I should > be able to run foo -s and it will report some internal information > about the foo daemon if it's running) but I can't figure out a way get > information from that process from an external process. I was thinking > that there should be a way to open a file descriptor, have the daemon > write to that every so often and then have the query process just read > from that fd but it looks like on the process reading from an fd has > to be a child of the daemon for this to work. The only other way I > thought of would be to write to a file on disk every so often from the > daemon and just read the from the query process but it seems like > there should be a more elegant way to do this... Most daemon programs I know of that do this use unix sockets. The socket is typically put in /tmp, or probably better in /var/run, or some other appropriate place. Often this is configurable in a config file that both the daemon and the program or instance that checks the daemon read. Another possibility is shared memory segments. I'm not sure how security is done in this case. Anyway, shared memory is a common IPC mechanism. From steve at nospam.au Sun Aug 2 22:27:22 2009 From: steve at nospam.au (steve) Date: Mon, 3 Aug 2009 12:27:22 +1000 Subject: Test for Pythonwin? References: <4a728aac$0$9744$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <4a764b0a$0$22840$5a62ac22@per-qv1-newsreader-01.iinet.net.au> "steve" wrote in message news:4a728aac$0$9744$5a62ac22 at per-qv1-newsreader-01.iinet.net.au... > Is there a good way to check if a script is running inside Pythonwin? > Perhaps a property or method that is exposed by that environment? > > or, alternatively, is there a better place to ask :-) > > Steven > > 'pywin' in sys.modules Didn't want to check for redirection because my redirection code is in a different thread, and I'd have to think about thread synchronization as well. Thanks guys, Steven From icebergwtf at gmail.com Sun Aug 2 22:33:53 2009 From: icebergwtf at gmail.com (tiefeng wu) Date: Mon, 3 Aug 2009 10:33:53 +0800 Subject: RE Question In-Reply-To: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> References: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> Message-ID: <4314c1f70908021933o68857e6fia8a99f039ea9f1d9@mail.gmail.com> 2009/8/3 Victor Subervi : -> Hi; -> How do I search and replace something like this: > aLine = re.sub('[<]?[p]?[>]? a-zA-Z0-9"\'=:]*>[<]?[b]?[>]?', '', aLine) > where RE *only* looks for the possibility of "

" at the beginning of the > string; that is, not the individual components as I have it coded above, but > the entire 3-character block? > TIA, > Victor I'm not sure I totally understand your problem, try this: aLine = re.sub(r'(?:

)?]*>(?:)'.format(str(x)), '', aLine) tiefeng wu 2009-08-03 From aahz at pythoncraft.com Sun Aug 2 22:52:14 2009 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2009 19:52:14 -0700 Subject: Printing with colors in a portable way References: <33e19169-19b4-497a-b262-2bcf7b5637d5@r38g2000yqn.googlegroups.com> Message-ID: In article <33e19169-19b4-497a-b262-2bcf7b5637d5 at r38g2000yqn.googlegroups.com>, Robert Dailey wrote: > >Anyone know of a way to print text in Python 3.1 with colors in a >portable way? In other words, I should be able to do something like >this: > >print_color( "This is my text", COLOR_BLUE ) > >And this should be portable (i.e. it should work on Linux, Mac, >Windows). Much as I hate to say, use a cross-platform GUI -- Tkinter comes with Python, and you can also use SDL via PyGame, wxWindows, pyQT, PyOpenGL, and so on. If that's not an option, you should have said "command-line program". ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From joshua at azariah.com Sun Aug 2 23:18:43 2009 From: joshua at azariah.com (Joshua J. Kugler) Date: Sun, 2 Aug 2009 19:18:43 -0800 Subject: ANNOUNCE: AwstatsReader 0.01 Message-ID: <200908021918.44365.joshua@azariah.com> ABOUT THE MODULE ================ AwstatsReader is an attempt at a pythonic interface to AWStats data cache files. ?Using it, you can access year, month, and individual data points via dictionary-like accessors. Download here: http://azariah.com/open_source.html ABOUT THE AUTHOR ================ Joshua Kugler (joshua at azariah.com) is a programmer and system administrator with over 10 years of industry experience. ?He is currently looking for a job. ?Happen to have one you could offer him? :) Resume at: http://jjncj.com/papers/KuglerAll.pdf DISCLAIMER ========== This is a "release early, release often" release, codnamed Joshua-hopes- somebody-downloads-this-and-likes-code-quality-and-hires-him. This is an early release...probably pre-alpha. ?There are no tests yet (haven't generated cache files I can release publically), not much documentation, and the interface may change (but I hope not too much). And I haven't even put this in a public repository, as the name might (but probably won't) change. I wrote this via examples from an AWStats cache file, so I'm sure there are sections for which I do not have definitions. ?If you would send me those sections, I'll be sure to add them. The error handling is probably a little light. ?Certainly could be improved. Right now, this will parse and display cache files from AWStats 6.5. I've not tested other versions yet, as 6.5 is the only version I've had access to so far. INSTALLATION ============ See INSTALL LICENSE ======= See COPYING EXAMPLE ======= import AwstatsReader obj ?= AwstatsReader.AwstatsReader('/path/to/awstats_logs', 'example.com') print obj[2007] print obj[2008][6] m = obj[2009][7] print m['general'] # Access like a dictionary... print m['general']['LastLine'] #...or like an object attribute print m['general'].LastLine print m.general.LastLine FEEDBACK ======== Please send questions/comments/suggestions to awstatsreader at azariah.com For now, you can find the latest version here: http://azariah.com/open_source.html From gagsl-py2 at yahoo.com.ar Mon Aug 3 00:13:17 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 01:13:17 -0300 Subject: RE Question References: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> Message-ID: En Sun, 02 Aug 2009 18:22:20 -0300, Victor Subervi escribi?: > How do I search and replace something like this: > aLine = re.sub('[<]?[p]?[>]? a-zA-Z0-9"\'=:]*>[<]?[b]?[>]?', '', aLine) > where RE *only* looks for the possibility of "

" at the beginning of > the > string; that is, not the individual components as I have it coded above, > but > the entire 3-character block? An example would make it more clear; I think you want to match either "

" is optional. Use a normal group or a non-capturing group: r'(

)? Message-ID: <19e16923-b200-498b-9ab2-f7d316b568a6@d32g2000yqh.googlegroups.com> On Aug 2, 9:52?pm, a... at pythoncraft.com (Aahz) wrote: [snip] > Much as I hate to say, use a cross-platform GUI -- Tkinter comes with > Python, [snip] Why is Tkinter such a whipping boy of the Python community? I know it's very simple and does not have all the bells and whistles of wx, but i think the gentle learning curve is very important for those struggling to learn GUI's. Even today I always use Tkinter first, and then only reach for wx when absolutely necessary. Seems to me the relativity small footprint(GUI wise) compared to the payoffs are worth the inclusion. I think if Tkinter where ever removed from Python it would be not only a disservice to the language but also a detriment to the *new* users of the language. Just my humble opinion From anthra.norell at bluewin.ch Mon Aug 3 03:40:00 2009 From: anthra.norell at bluewin.ch (Anthra Norell) Date: Mon, 03 Aug 2009 09:40:00 +0200 Subject: Compiling regex inside function? Message-ID: <4A769450.5080702@bluewin.ch> Hi all, I have a regex that has no use outside of a particular function. From an encapsulation point of view it should be scoped as restrictively as possible. Defining it inside the function certainly works, but if re.compile () is run every time the function is called, it isn't such a good idea after all. E.g. def entries (l): r = re.compile ('([0-9]+) entr(y|ies)') match = r.search (l) if match: return match.group (1) So the question is: does "r" get regex-compiled once at py-compile time or repeatedly at entries() run time? Frederic From greg.ewing at canterbury.ac.nz Mon Aug 3 03:40:41 2009 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Mon, 03 Aug 2009 19:40:41 +1200 Subject: Registation is open for the 9th PyWeek game programming challenge! In-Reply-To: <3A356906-89BE-47A4-9ECE-4C87A7EA89BE@gmail.com> References: <3A356906-89BE-47A4-9ECE-4C87A7EA89BE@gmail.com> Message-ID: <4A769479.9080707@canterbury.ac.nz> Richard Jones wrote: > The ninth PyWeek challenge will run between: > > Sunday 30th August to Sunday 6th September (00:00UTC to 00:00UTC) Yow, hard on the heels of Pyggy! I'd hoped there might be a bit more breathing room, sorry about that! Hope the Pyggy entrants aren't feeling too burned out to participate. -- Greg From deets at nospam.web.de Mon Aug 3 03:45:32 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Aug 2009 09:45:32 +0200 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: <7dnissF2bthr0U1@mid.uni-berlin.de> Marcus Wanner schrieb: > On 8/2/2009 10:43 AM, Christian Heimes wrote: >> Marcus Wanner wrote: >>> I believe that python is buffer overflow proof. In fact, I think that >>> even ctypes is overflow proof... >> >> No, ctypes isn't buffer overflow proof. ctypes can break and crash a >> Python interpreter easily. >> >> Christian >> > I see. I thought that it said "invalid array index" when you try to > read/write outside of an array's bounds, though... But you can cast the resulting pointer to an array of larger size, and there you are. Diez From davea at ieee.org Mon Aug 3 04:04:04 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Aug 2009 04:04:04 -0400 Subject: Run pyc file without specifying python path ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF67D49D318@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6701A26C4@enbmail01.lsi.com> <4A708F68.1010505@ieee.org> <7F0503CD69378F49BE0DC30661C6CCF6701A26C7@enbmail01.lsi.com> <4A7199FF.8010202@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF6701A26D2@enbmail01.lsi.com> <4A71D35F.3090800@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF67D49D30E@enbmail01.lsi.com> <4A755DE6.1000906@ieee.org> <7F0503CD69378F49BE0DC30661C6CCF67D49D318@enbmail01.lsi.com> Message-ID: <4A7699F4.1050400@ieee.org> Barak, Ron wrote: > >> -----Original Message----- >> From: Dave Angel [mailto:davea at ieee.org] >> Sent: Sunday, August 02, 2009 12:36 >> To: Barak, Ron >> Cc: 'python-list at python.org' >> Subject: Re: Run pyc file without specifying python path ? >> >> Barak, Ron wrote: >> >>> Hi Dave, >>> >>> It seems like I don't understand your solution. >>> I use the (attached) soapAPI.py as the wrapper to parsing.pyc. >>> However, if I do (for instance): >>> >>> $ python -u parsing.pyc -U aaa >>> >>> The last line of the output is (as expected): >>> >>> return_code: 12 ; params: {'username': 'aaa'} >>> >>> But, if I try the following: >>> >>> $ soapAPI.py -U aaa >>> >>> I don't get this line. Only the output to stderr gets >>> >> printed to the screen. >> >>> Bye, >>> Ron. >>> >>> >>> >> Hi Ron, >> >> To make it easier for anybody following this thread, let me >> post the minimum equivalent source files, inline. >> >> parsing.py: >> ------------------------------ >> #!/usr/bin/env python >> >> import sys >> >> def main(): >> print >> sys.stderr, "This is stderr output" >> return 5, sys.argv >> >> if __name__ == "__main__": >> return_code, params = main() >> print "return_code:",return_code,"; params:",params >> sys.exit(return_code) >> ------------------------------- >> soapapi.py: >> ------------------------------- >> #!/usr/bin/env python >> >> import sys >> import parsing >> >> parsing.main() >> ------------------------------ >> >> >> When I run soapapi.;py, it indeed prints only the stderr output. >> >> The solution is to move (most or all) of the top-level code >> of parsing.py into a main() function. Since you already have >> a main(), I'll rename that, and make a new one that calls it. >> >> new parsing.py: >> ------------------------------- >> #!/usr/bin/env python >> >> import sys >> >> def innermain(): >> print >> sys.stderr, "This is stderr output" >> return 5, sys.argv >> >> def main(): >> return_code, params = innermain() >> print "return_code:",return_code,"; params:",params >> sys.exit(return_code) >> >> if __name__ == "__main__": >> main() >> ------------------------------- >> >> The output is now two lines, one from innermain(), and one >> from main(). >> And it's the same whether the user runs parsing.py or soapAPI.py >> >> To clarify what happened, realize that when the user invokes >> parsing.py, the module is considered a script, and gets a >> pseudo-name of >> "__main__" When that same module is imported by another one, it is >> considered a library module, and gets its own name "parsing" >> >> So any logic that explicitly checks for "__main__" has to >> change, because we want identical behavior in the two cases. >> >> DaveA >> >> >> > > Hi Dave, > > Trying your above scripts, I get other results than you do. E.g.: > > $ python parsing.py --help > return_code: 5 ; params: ['parsing.py', '--help'] > This is stderr output > > $ python soapapi.py --help > This is stderr output > > $ > > So, in my environment (cygwin on win xp, python Python 2.5.2) I'm getting different results than you get, namely - soapapi.py on my environment does not show the stdout output. > On which environment did you get identical results from your parsing.py and soapapi.py ? > > Bye, > Ron. > > $ cat parsing.py > #!/usr/bin/env python > > import sys > > def main(): > print >> sys.stderr, "This is stderr output" > return 5, sys.argv > > if __name__ == "__main__": > return_code, params = main() > print "return_code:",return_code,"; params:",params > sys.exit(return_code) > > $ cat soapapi.py > #!/usr/bin/env python > > import sys > import parsing > > parsing.main() > > > > Please read my message again, especially starting with the words "the solution is." I showed two versions of parsing.py, and you're still using the broken version. I posted both versions, with descriptions of what I changed and why, so that you could see why the change was important. I'm using sys.version == 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] Running on XP Sp3. And 2.5 will give identical results, though I don't have it installed any more. DaveA From matt.urry at googlemail.com Mon Aug 3 04:36:41 2009 From: matt.urry at googlemail.com (ma3mju) Date: Mon, 3 Aug 2009 01:36:41 -0700 (PDT) Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> Message-ID: <996e50f5-c126-4ac2-ae8d-458d22a26ee1@v20g2000yqm.googlegroups.com> On 2 Aug, 21:49, Piet van Oostrum wrote: > >>>>> MRAB (M) wrote: > >M> I wonder whether one of the workers is raising an exception, perhaps due > >M> to lack of memory, when there are large number of jobs to process. > > But that wouldn't prevent the join. And you would probably get an > exception traceback printed. > > I wonder if something fishy is happening in the multiprocessing > infrastructure. Or maybe the Fortran code goes wrong because it has no > protection against buffer overruns and similar problems, I think. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org I don't think it's a memory problem, the reason for the hard and easy queue is because for larger examples it uses far more RAM. If I run all of workers with harder problems I do begin to run out of RAM and end up spending all my time switching in and out of swap so I limit the number of harder problems I run at the same time. I've watched it run to the end (a very boring couple of hours) and it stays out of my swap space and everything appears to be staying in RAM. Just hangs after all "poison" has been printed for each process. The other thing is that I get the message "here" telling me I broke out of the loop after seeing the poison pill in the process and I get all the things queued listed as output surely if I were to run out of memory I wouldn't expect all of the jobs to be listed as output. I have a serial script that works fine so I know individually for each example the fortran code works. Thanks Matt From MatzeGuentert at gmx.de Mon Aug 3 04:46:29 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Mon, 03 Aug 2009 08:46:29 +0000 Subject: M2Crypto: X509.X509_Extension_Stack() throws AssertionError Message-ID: <1249289189.3205.5.camel@celsius> Hello python-list members Why is the following code snippet throwing an AssertionError? Is that behavior a bug within X509.X509_Extension_Stack()? How would you suggest popping every element from the stack? Regards, Matthias G?ntert ------------------------------------------------- from M2Crypto import X509 if __name__ == '__main__': cert_extension_stack = X509.X509_Extension_Stack() cert_extension_1 = X509.new_extension("basicConstraints", "CA:FALSE") cert_extension_1.set_critical() cert_extension_2 = X509.new_extension("keyUsage", "101000000") cert_extension_2.set_critical() cert_extension_3 = X509.new_extension("subjectAlternativeName", "DNS:www.mydomain.tld") print cert_extension_stack.push(cert_extension_1) print cert_extension_stack.push(cert_extension_2) print cert_extension_stack.push(cert_extension_3) print cert_extension_stack.pop() ------------------------------------------------- ------------------------------------------------- Traceback (most recent call last): File "test.py", line 18, in print cert_extension_stack.pop() File "/usr/lib64/python2.6/site-packages/M2Crypto/X509.py", line 159, in pop assert len(self.pystack) == 0 AssertionError 1 2 3 ------------------------------------------------- From zdenekmaxa at yahoo.co.uk Mon Aug 3 05:19:11 2009 From: zdenekmaxa at yahoo.co.uk (Zdenek Maxa) Date: Mon, 03 Aug 2009 11:19:11 +0200 Subject: urllib2.urlopen timeout Message-ID: <4A76AB8F.5090403@yahoo.co.uk> Hi, I would like to ask how I should set timeout for a call: f = urllib2.urlopen(url) I am using Python 2.5. I have already tried socket.setdefaulttimeout(3). However, this adversely affects other connections the application makes, since it seems to affect all socket connections. I know that Python 2.6 offers urllib2.urlopen(url[, data][, timeout]) which would elegantly solved my problem, but I have to stick to Python 2.5. I am doing urlopen in a thread so I want to avoid really long hanging on this call, which happens at times, until some default timeout ticks out. All hints appreciated. Thanks, Zdenek From jeanmichel at sequans.com Mon Aug 3 06:46:45 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 03 Aug 2009 12:46:45 +0200 Subject: Printing with colors in a portable way In-Reply-To: References: <33e19169-19b4-497a-b262-2bcf7b5637d5@r38g2000yqn.googlegroups.com> Message-ID: <4A76C015.5010600@sequans.com> Nobody wrote: > On Thu, 30 Jul 2009 15:40:37 -0700, Robert Dailey wrote: > > >> Anyone know of a way to print text in Python 3.1 with colors in a >> portable way? In other words, I should be able to do something like >> this: >> >> print_color( "This is my text", COLOR_BLUE ) >> >> And this should be portable (i.e. it should work on Linux, Mac, >> Windows). >> > > The way that terminals (and emulators) handle colour is fundamentally > different from the DOS/Windows console. If you want something which will > work on both, you will have write separate implementations for terminals > and the DOS/Windows console. > > For terminals, you can use the "curses" package, e.g.: > > import curses > > curses.setupterm() > setaf = curses.tigetstr('setaf') > setab = curses.tigetstr('setab') > > def foreground(num): > if setaf: > sys.stdout.write(curses.tparm(setaf, num)) > > def background(num): > if setab: > sys.stdout.write(curses.tparm(setab, num)) > > For the Windows console, you'll need to use ctypes to interface to the > SetConsoleTextAttribute() function from Kernel32.dll. > > FYI http://github.com/jbowes/markymark/blob/59511b36a752b40243cc18fb0fb9800c74549ac1/markymark.py If the URL ever becomes invalid, then google for markymark.py You can use it either to color your Linux/Unix terms, or you can just look at the python code to see how to set colors and attributes. JM From hitechpundir at gmail.com Mon Aug 3 07:12:15 2009 From: hitechpundir at gmail.com (sirjee) Date: Mon, 3 Aug 2009 04:12:15 -0700 (PDT) Subject: problem in event handling on change of variable value. References: <9c0d7a31-0310-4499-9974-92afc588f315@d15g2000prc.googlegroups.com> Message-ID: <27a8e24c-7f58-4952-b45a-439601223199@13g2000prl.googlegroups.com> On Aug 1, 2:22?pm, sirjee wrote: > hello; > > i m facing a problem in handling events on change of value of > environment variable in a toolCANoe. > > class CANoeEvents: > ? ? def OnChange(self,value): > ? ? ? ? print "value of environment variable has changed" > ? ? def OnOpen(self,App): > ? ? ? ? print "opening Application" > > App_Event = DispatchWithEvents('CANoe.Application',CANoeEvents) > time.sleep(2) > App_Event.Open("C:\projectConfig.cfg") ?# printd "opening Application" > and event handled properly. > .......(now a code file runs in thecanoein which value of > environment variable called dummy is changed during execution. Just > like OnOpen; OnChange is defined in specification which should be > called on change of environment variable.But it is not happening.) > while (): > ? ? ? ? ? ? ? ? myenvVar = App_Event.Environment.GetVariable("dummy") > > The VB does it very easily and defines a subroutine called : > Sub myenvVar _OnChange(value) > ? ?print "value of environment variable has changed" > End Sub > //////////////////////////////////////////////////however the > alternative for subroutine for OnOpen in VB (defined below) works fine > as shown above in python. > Sub AppEvent_OnOpen(App) > ? ? ? ? print "opening Application" > End Sub > > for VB; all this stuff is cake work.... object_eventname subroutine > and done.....what in python? hi all; strange !!!! i got answer to the problem posted by me only. now I have very good control of CANoe tool from python.... if anybody faces any problem wrt automation of CANoe tool using python; do contact me. here actual problem lied in analysing and implementing com heirarchy. ( which is really bit cumbersome) onChange event is associated with App_Event.Environment.GetVariable ("dummy") object. So we need to associate separate class with this object and then write onChange function: class evtClass: def __init__(self): print "initializing event class" def OnChange(self,value): print "value of environment variable changing" print "changed value of environment variable is" print value see = App_Event.Environment.GetVariable("dummy") see_temp=DispatchWithEvents(see,evtClass) this will solve problem. So we need to create separate classes for events associated with separate objects. regards sirjee From marcusw at cox.net Mon Aug 3 08:01:00 2009 From: marcusw at cox.net (Marcus Wanner) Date: Mon, 03 Aug 2009 08:01:00 -0400 Subject: Is python buffer overflow proof? In-Reply-To: <7dnissF2bthr0U1@mid.uni-berlin.de> References: <7dnissF2bthr0U1@mid.uni-berlin.de> Message-ID: On 8/3/2009 3:45 AM, Diez B. Roggisch wrote: > Marcus Wanner schrieb: >> On 8/2/2009 10:43 AM, Christian Heimes wrote: >>> Marcus Wanner wrote: >>>> I believe that python is buffer overflow proof. In fact, I think >>>> that even ctypes is overflow proof... >>> >>> No, ctypes isn't buffer overflow proof. ctypes can break and crash a >>> Python interpreter easily. >>> >>> Christian >>> >> I see. I thought that it said "invalid array index" when you try to >> read/write outside of an array's bounds, though... > > > But you can cast the resulting pointer to an array of larger size, and > there you are. > > Diez Ah, that makes sense. I had forgotten about ctypes.cast(). Marcus From riaz.ahmadskh at gmail.com Mon Aug 3 08:03:46 2009 From: riaz.ahmadskh at gmail.com (Riaz Ahmad) Date: Mon, 3 Aug 2009 05:03:46 -0700 (PDT) Subject: "PAKISTAN NEWS" "PAKISTANI NEWSPAPERS" "MAGAZINES ON LINE" "URDU LANGUAGE SOFTWARES" "URDU POETRY PAKISTAN" "PAKISTANI WEB SITE DIRECTOR" "PAKISTANI NEWSPAPERS" "PAKISTAN" "PAKISTAN" on www.pak-web-pages.blogspot.com Message-ID: "PAKISTAN NEWS" www.pak-web-pages.blogspot.com "PAKISTANI NEWSPAPERS" www.pak-web-pages.blogspot.com "MAGAZINES ON LINE" www.pak-web-pages.blogspot.com "URDU LANGUAGE SOFTWARES" www.pak-web-pages.blogspot.com "URDU POETRY PAKISTAN" www.pak-web-pages.blogspot.com "PAKISTANI WEB SITE DIRECTOR" www.pak-web-pages.blogspot.com "PAKISTANI NEWSPAPERS" www.pak-web-pages.blogspot.com "PAKISTAN" www.pak-web-pages.blogspot.com "PAKISTAN" www.pak-web-pages.blogspot.com on www.pak-web-pages.blogspot.com From hubaghdadi at gmail.com Mon Aug 3 08:14:35 2009 From: hubaghdadi at gmail.com (Hussein B) Date: Mon, 3 Aug 2009 05:14:35 -0700 (PDT) Subject: Executing remote command with paramiko Message-ID: Hey, I'm trying to run a sudo guarded command over SSH using paramiko +++++++++++++++++++ s = paramiko.SSHClient() s.load_system_host_keys() s.connect(hostname, port, username, passwd) stdin, stdout, stderr = s.exec_command('sudo -s') stdin.write('password\n') stdin.flush() print 'Flushing' stdin, stdout, stderr = s.exec_command('harvester') print stdout.read() s.close() +++++++++++++++++++ It seems to me that the sudo -s isn't getting executed at all. I commented the sudo -s code lines and no error is shown. Thanks for help and time. From duncan.booth at invalid.invalid Mon Aug 3 08:34:28 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Aug 2009 12:34:28 GMT Subject: heapq "key" arguments References: <97932d10-8601-401f-bb69-a98db9036929@p15g2000vbl.googlegroups.com> <1582f82e-34aa-4b66-b989-c9f8351a5f1c@o9g2000prg.googlegroups.com> <4f096546-36a1-4633-9a24-1265ce0929ce@q14g2000vbi.googlegroups.com> Message-ID: "Gabriel Genellina" wrote: > Ok, it's not strictly the same, but usually it doesn't hurt. The heaqp > module doesn't promise anything about equal elements: it may keep the > original order, rearrange them at will, reverse them, whatever. The documentation doesn't say anything directly about stability, but the implementation is actually stable. You can probably assume it must be at least for nlargest and nsmallest otherwise the stated equivalence wouldn't hold: e.g. nsmallest documentation says: Equivalent to: sorted(iterable, key=key)[:n] -- Duncan Booth http://kupuguy.blogspot.com From sjmachin at lexicon.net Mon Aug 3 09:00:33 2009 From: sjmachin at lexicon.net (John Machin) Date: Mon, 3 Aug 2009 06:00:33 -0700 (PDT) Subject: New implementation of re module References: Message-ID: On Jul 28, 2:34?am, MRAB wrote: > Hi all, > > I've been working on a new implementation of the re module. The details > are athttp://bugs.python.org/issue2636, specifically fromhttp://bugs.python.org/issue2636#msg90954. I've included a .pyd file for > Python 2.6 on Windows if you want to try it out. > Where/how should we report perceived bugs: On that bugs.python.org issue? Here? Private e-mail? From ram.rachum at gmail.com Mon Aug 3 09:18:29 2009 From: ram.rachum at gmail.com (cool-RR) Date: Mon, 3 Aug 2009 06:18:29 -0700 (PDT) Subject: Announcing PythonTurtle Message-ID: Hello, I wanted to announce that I have just released my little side project, PythonTurtle. Here is its website: http://pythonturtle.com Its goal is to be the lowest-threshold way to learn (or teach) Python. You can read more about it and download it on the website. Ram. From mydevforums at gmail.com Mon Aug 3 10:04:07 2009 From: mydevforums at gmail.com (IronyOfLife) Date: Mon, 3 Aug 2009 07:04:07 -0700 (PDT) Subject: Python configuration question when python scripts are executed using Appweb as web server. Message-ID: Hi All I have installed python 2.6.2 in windows xp professional machine. I have set the following environment variables -- PYTHONPATH. It points to following windows folders: python root folder, the lib folder and lib-tk folder. I have configured IIS to execute python scripts. I do not have any issues executing python scripts from the python interpreter window or from the browser using IIS as the web server. However, when I use the open source Appweb web browser to execute python scripts. It is able to execute only simple script without issues. For example, hello.py executes fine. hello.py -------------------------------------------------------- #!/usr/bin/env python print "Content-type: text/html\n\n" print "Hello world!" However I am not able to execute python scripts that contain import statements. I need to point out here that i do not have issue with using os or sys packages. When I tried to execute the sample client script that came with the gnutls wrapper for python, I got error. I narrowed it down to the "from ... import" line in the example. from gnutls.crypto import * from gnutls.connection import * Next I modified it to the functions used in the client python scripts (NOTE: I have added some additional functions to connection and crypto python scripts). from gnutls.crypto import X509Certificate, X509PrivateKey, X509CRL from gnutls.connection import AnonClientCred Next step, in order to debug, I used the module finder to see what is happening. To being with I used the module finder to find out the modules loaded for the simple script hello.py. hello2.py -------------------------------------------------------- #!/usr/bin/env python import modulefinder import pdb pdb.set_trace() finder = modulefinder.ModuleFinder() finder.run_script('hello.py') print "Content-type: text/html\n\n" print "" print sys.exc_info() print 'Loaded modules:' for name, mod in finder.modules.iteritems(): print '%s: ' % name, print ','.join(mod.globalnames.keys()[:3]) print '-'*50 print 'Modules not imported:' print '\n'.join(finder.badmodules.iterkeys()) print "" I got the error. Please see below for error as captured from Appweb logs. See lines 3 to 5. cgi:5 main 356: CGI Response: read 89 bytes cgi:6 main 356: Data is: > c:\appweb\web\hello2.py(9)() -> finder = modulefinder.ModuleFinder() (Pdb) cgi:5 main 356: CGI Response: read 0 bytes cmd:7 main getExitCode: process 0, code 1 default:1 main Error: 503 "Service Unavailable" for "/hello2.py", file "c:/appweb/web/hello2.py": CGI process /hello2.py: exited abnormally with exit code: 1 request:5 main 356: flushOutput: background 0 Once again, let me stress that this issue is happening only when I use appweb as the web server. Some details on Appweb that I found out: Appweb opens up a new console process and executes the python scripts. See sample below: cmd:5 pool.0 Running: C:\Dev\Ironic\Tools\Python26\python.exe c:/ appweb/web/hello2.py When python scripts are executed in this fashion, should there be additional command line arguments be passed? Am I missing any additional settings. Also can you help with improving the debugging lines in hello2.py so that I can identify the issue. Please help. Thanks. Ram G. From jeanmichel at sequans.com Mon Aug 3 10:38:43 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 03 Aug 2009 16:38:43 +0200 Subject: Generate a new object each time a name is imported In-Reply-To: <02853264$0$20667$c3e8da3@news.astraweb.com> References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <4A76F673.9010701@sequans.com> Steven D'Aprano wrote: > I would like to generate a new object each time I import a name from a > module, rather than getting the same object each time. For example, > currently I might do something like this: > > # Module > count = 0 > def factory(): > # Generate a unique object each time this is called > global count > count += 1 > return "Object #%d" % count > > > # Calling module > from Module import factory > a = factory() # a == "Object #1" > b = factory() # b == "Object #2" > del factory > > > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a # a == "Object #1" > from Module import factory() as b # b == "Object #2" > > except of course that syntax is illegal. > > > Why making standard statements do what they're not meant to do ? You could write >import Module > >a = factory() >b = factory() But you already know that. So what's the purpose of making >from Module import factory as a >from Module import factory as b return 2 different objects ? If I had to write this code I would expect 'a is b' to return 'True'. This is no "don't do that" answer, it's a sincere question: what is the benefit of your /new/ syntax ? JM From andre.roberge at gmail.com Mon Aug 3 10:53:43 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 3 Aug 2009 07:53:43 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: <44a7457e-4dc7-4ad4-be80-3585ce693bc9@f37g2000yqn.googlegroups.com> On Aug 3, 10:18?am, cool-RR wrote: > Hello, > > I wanted to announce that I have just released my little side project, > PythonTurtle. > Here is its website:http://pythonturtle.com > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > You can read more about it and download it on the website. > > Ram. Why not make the source available? At the very least, people that do not run windows could try it too. Andr? From jcd at sdf.lonestar.org Mon Aug 3 10:54:05 2009 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 03 Aug 2009 10:54:05 -0400 Subject: A Bug By Any Other Name ... In-Reply-To: References: Message-ID: <1249311245.8865.11.camel@aalcdl07> On Sun, 2009-08-02 at 14:14 +0000, Albert van der Horst wrote: > >This is actually quite thoroughly untrue. In python, *indentation* > is > >significant. Whitespace (internal to a line) is not. You can even > call > >methods like this if you want: > > You totally don't get it. You describe how python is now. > I propose a change to be made to python. Small wonder that that is > different from what it is now. > > > > >>>> s = 'abc' > >>>> s . upper() > >ABC > > You prove nothing by giving examples. > You can disprove by giving one counter example, > here it goes. > > Whitespace (internal to a line) is significant. > In Python you cannot change > xleftgoing = 123000000 > to > x left going = 123 000 000 > > (You can in Algol68) I had a feeling that counterexample would be coming sooner or later. However, it doesn't really address the change you're looking for. Internal whitespace *is* irrelevant, except insofar as it can be used to delimit different tokens in parsing. If tokens are separate, they are separate, and no more or less whitespace is going to make any difference. Again, I'm describing how python is now. Which is not to say it couldn't be changed, I just want to make sure you understand how deep into the heart of python you are trying to cut. You make it sound like a small change, but it is not. You are proposing changing the parsing rules, which completely changes the scope of what is possible and what isn't with python syntax. All to solve a problem that, so far, hasn't been proven to exist in anything other than a speculative way. You're trying to turn an ocean liner around because you left your sunscreen on the dock. Cheers, Cliff From newsgroup at silveraxe.de Mon Aug 3 10:56:17 2009 From: newsgroup at silveraxe.de (Hilmar Bunjes) Date: Mon, 03 Aug 2009 16:56:17 +0200 Subject: Announcing PythonTurtle In-Reply-To: <44a7457e-4dc7-4ad4-be80-3585ce693bc9@f37g2000yqn.googlegroups.com> References: <44a7457e-4dc7-4ad4-be80-3585ce693bc9@f37g2000yqn.googlegroups.com> Message-ID: <4a76fa98$0$31327$9b4e6d93@newsspool4.arcor-online.net> Andr? schrieb: >> I wanted to announce that I have just released my little side project, >> PythonTurtle. >> Here is its website:http://pythonturtle.com >> >> Its goal is to be the lowest-threshold way to learn (or teach) Python. >> You can read more about it and download it on the website. >> >> Ram. > > Why not make the source available? At the very least, people that do > not run windows could try it too. Isn't this the source: http://github.com/cool-RR/PythonTurtle/tree/master ? Linked at the bottom of the page. Best, Hilmar From sandhyaprabhakaran at gmail.com Mon Aug 3 11:17:53 2009 From: sandhyaprabhakaran at gmail.com (Sandhya Prabhakaran) Date: Mon, 3 Aug 2009 08:17:53 -0700 (PDT) Subject: Extract the numeric and alphabetic part from an alphanumeric string Message-ID: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Hi, I have a string as str='123ACTGAAC'. I need to extract the numeric part from the alphabetic part which I did using >>>numer=re.findall(r'\d+',str) >>>numer 123 To get the alphabetic part, I could do >>>alpha=str.replace('123','') >>>alpha ACTGAAC But when I give >>>alpha=str.replace(numer,'') Traceback (most recent call last): File "", line 1, in TypeError: expected a character buffer object How do I blank out the initial numeric part so as to get just the alphabetic part. The string is always in the same format. Please help. Regards, Sandhya From ram.rachum at gmail.com Mon Aug 3 11:22:50 2009 From: ram.rachum at gmail.com (cool-RR) Date: Mon, 3 Aug 2009 08:22:50 -0700 (PDT) Subject: Announcing PythonTurtle References: <44a7457e-4dc7-4ad4-be80-3585ce693bc9@f37g2000yqn.googlegroups.com> Message-ID: On Aug 3, 5:53?pm, Andr? wrote: > On Aug 3, 10:18?am, cool-RR wrote: > > > Hello, > > > I wanted to announce that I have just released my little side project, > > PythonTurtle. > > Here is its website:http://pythonturtle.com > > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > > You can read more about it and download it on the website. > > > Ram. > > Why not make the source available? ?At the very least, people that do > not run windows could try it too. > > Andr? Sorry that the link is obscure like that. I'll change it so it's easier to see. From peter at peter-b.co.uk Mon Aug 3 11:31:09 2009 From: peter at peter-b.co.uk (Peter Brett) Date: Mon, 03 Aug 2009 16:31:09 +0100 Subject: Extract the numeric and alphabetic part from an alphanumeric string References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: Sandhya Prabhakaran writes: > Hi, > > I have a string as str='123ACTGAAC'. > > I need to extract the numeric part from the alphabetic part which I > did using >>>>numer=re.findall(r'\d+',str) >>>>numer > 123 > > To get the alphabetic part, I could do >>>>alpha=str.replace('123','') >>>>alpha > ACTGAAC > But when I give >>>>alpha=str.replace(numer,'') > Traceback (most recent call last): > File "", line 1, in > TypeError: expected a character buffer object > > How do I blank out the initial numeric part so as to get just the > alphabetic part. The string is always in the same format. Firstly, you really should read the Regular Expression HOWTO: http://docs.python.org/howto/regex.html#regex-howto Secondly, is this what you wanted to do? >>> p = re.compile(r'^\d+') >>> p.sub('', '123ACTGAAC') 'ACTGAAC' Regards, Peter -- Peter Brett Remote Sensing Research Group Surrey Space Centre From andreas.tawn at ubisoft.com Mon Aug 3 11:33:00 2009 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Mon, 3 Aug 2009 17:33:00 +0200 Subject: Extract the numeric and alphabetic part from an alphanumeric string In-Reply-To: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C758007C8ACF4@PDC-MAIL3.ubisoft.org> > Hi, > > I have a string as str='123ACTGAAC'. > > I need to extract the numeric part from the alphabetic part which I > did using > >>>numer=re.findall(r'\d+',str) > >>>numer > 123 > > To get the alphabetic part, I could do > >>>alpha=str.replace('123','') > >>>alpha > ACTGAAC > But when I give > >>>alpha=str.replace(numer,'') > Traceback (most recent call last): > File "", line 1, in > TypeError: expected a character buffer object > > How do I blank out the initial numeric part so as to get just the > alphabetic part. The string is always in the same format. > > Please help. > > Regards, > Sandhya If the format's always the same, you could use slicing instead. >>> s = '123ACTGAAC' >>> s[:3] '123' >>> s[3:] 'ACTGAAC' BTW, you should avoid using built-ins like str for variable names. Bad things will happen. Cheers, Drea From python at mrabarnett.plus.com Mon Aug 3 11:43:30 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 03 Aug 2009 16:43:30 +0100 Subject: Extract the numeric and alphabetic part from an alphanumeric string In-Reply-To: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: <4A7705A2.2010301@mrabarnett.plus.com> Sandhya Prabhakaran wrote: > Hi, > > I have a string as str='123ACTGAAC'. > > I need to extract the numeric part from the alphabetic part which I > did using >>>> numer=re.findall(r'\d+',str) >>>> numer > 123 > [snip] I get: ['123'] which is a _list_ of the strings found. From kushal.kumaran+python at gmail.com Mon Aug 3 11:49:15 2009 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Mon, 3 Aug 2009 21:19:15 +0530 Subject: Extract the numeric and alphabetic part from an alphanumeric string In-Reply-To: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: <1e364c4e0908030849u7583637h9c8d688f8520b904@mail.gmail.com> On Mon, Aug 3, 2009 at 8:47 PM, Sandhya Prabhakaran wrote: > Hi, > > I have a string as str='123ACTGAAC'. > > I need to extract the numeric part from the alphabetic part which I > did using >>>>numer=re.findall(r'\d+',str) >>>>numer > 123 > The docs for re.findall say that it returns a list of matches. So '123' will be numer[0]. > To get the alphabetic part, I could do >>>>alpha=str.replace('123','') >>>>alpha > ACTGAAC > But when I give >>>>alpha=str.replace(numer,'') > Traceback (most recent call last): > ?File "", line 1, in > TypeError: expected a character buffer object > That's what would happen if you pass in a list instead of a string to replace. > How do I blank out the initial numeric part so as to get just the > alphabetic part. The string is always in the same format. > > Please help. > -- kushal From python at mrabarnett.plus.com Mon Aug 3 12:00:05 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 03 Aug 2009 17:00:05 +0100 Subject: New implementation of re module In-Reply-To: References: Message-ID: <4A770985.5020900@mrabarnett.plus.com> John Machin wrote: > On Jul 28, 2:34 am, MRAB wrote: >> Hi all, >> >> I've been working on a new implementation of the re module. The details >> are athttp://bugs.python.org/issue2636, specifically fromhttp://bugs.python.org/issue2636#msg90954. I've included a .pyd file for >> Python 2.6 on Windows if you want to try it out. >> > > Where/how should we report perceived bugs: On that bugs.python.org > issue? Here? Private e-mail? > Probably on http://bugs.python.org/issue2636. From ethan at stoneleaf.us Mon Aug 3 12:00:43 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 03 Aug 2009 09:00:43 -0700 Subject: Python docs disappointing In-Reply-To: <7bb4df03-f09a-40b0-83f8-1c6d0c9800a8@j21g2000vbn.googlegroups.com> References: <7bb4df03-f09a-40b0-83f8-1c6d0c9800a8@j21g2000vbn.googlegroups.com> Message-ID: <4A7709AB.4060105@stoneleaf.us> Carl Banks wrote: > On Jul 31, 1:55 pm, Mark Lawrence wrote: > >>Apart from that what have the Pythonistas ever done for us? Nothing!:) > > > > Please don't feed the trolls. > > And if you do feed the trolls don't smile at them. > > > Carl Banks And if you do smile at them, don't show your teeth! ~Ethan~ From deets at nospam.web.de Mon Aug 3 12:01:14 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Aug 2009 18:01:14 +0200 Subject: Compiling regex inside function? References: Message-ID: <7dofubF2crctpU1@mid.uni-berlin.de> Anthra Norell wrote: > Hi all, > > I have a regex that has no use outside of a particular function. From > an encapsulation point of view it should be scoped as restrictively as > possible. Defining it inside the function certainly works, but if > re.compile () is run every time the function is called, it isn't such a > good idea after all. E.g. > > def entries (l): > r = re.compile ('([0-9]+) entr(y|ies)') > match = r.search (l) > if match: return match.group (1) > > So the question is: does "r" get regex-compiled once at py-compile time > or repeatedly at entries() run time? This can't be answered as simple yes/no-question. While the statement is executed each time, the resulting pattern-object isn't re-created, instead there is a caching-mechanism inside the module - so unless you create a situation where that cache's limits are exceeded and pattern objects are removed from it, you are essentially having the overhead of one function-call & a dict-lookup. Certainly worth it. As an additional note: r"" has *nothing* todo with this, that's just so-called raw string literals which have a different escaping-behavior - thus it's easier to write regexes in them. Diez From cjw at ncf.ca Mon Aug 3 12:04:50 2009 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 03 Aug 2009 12:04:50 -0400 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: cool-RR wrote: > Hello, > > I wanted to announce that I have just released my little side project, > PythonTurtle. > Here is its website: > http://pythonturtle.com > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > You can read more about it and download it on the website. > > Ram. It looks neat but it's not yet ready for prime time. Colin W. From robert.kern at gmail.com Mon Aug 3 12:24:19 2009 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Aug 2009 11:24:19 -0500 Subject: iterate lines with regex In-Reply-To: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> Message-ID: On 2009-08-01 14:39, Michael Savarese wrote: > > I'm a python newbie and I'm trying to test several regular expressions > on the same line before moving on to next line. > it seems to move on to next line before trying all regular expressions > which is my goal. > it only returns true for first regular expression > does the curser have to be rest to beginning of line? If so, how would I > do that. > remember I'm new > thanks in advance to any advice > Mike S. > > the following is part of my code, > readThis=open('c:/9320.txt','r') > > for line in readThis: > try: > thisKey = key.search(line).group(1) > thisMap = map.search(line).group(1) > thisParcel = parcel.search(line).group(1) > except: > continue What is happening is that either key or map fails to match and trying to get a group raises an exception. This is caught, and the "continue" statement tells the for-loop to go to the next line in readThis. The "continue" statement does not mean "go back to where the error was raised and continue executing as if no error happened". The key to using try: except: properly is to surround as little code as possible. Also, to explicitly state which exceptions you are going to catch. In this case, though, you don't want to use exceptions. You should deal with the match objects that are the result of the .search() method. for line in readThis: key_match = key.search(line) if key_match is not None: this_key = key_match.group(1) # ... do something with this_key map_match = map.search(line) if map_match is not None: this_map = map_match.group(1) # ... do something with this_map parcel_match = parcel.search(line) if parcel_match is not None: this_parcel = parcel_match.group(1) # ... do something with this_parcel -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From wuwei23 at gmail.com Mon Aug 3 12:40:02 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 09:40:02 -0700 (PDT) Subject: Extract the numeric and alphabetic part from an alphanumeric string References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: <3fc2ad25-8af7-452e-aab5-5716064d758f@y28g2000prd.googlegroups.com> Sandhya Prabhakaran wrote: > I have a string as str='123ACTGAAC'. You shouldn't use 'str' as a label like that, it prevents you from using the str() function in the same body of code. > How do I blank out the initial numeric part so as to get just the > alphabetic part. The string is always in the same format. >>> sample = '123ACTGAAC' >>> numer = ''.join(s for s in sample if s.isdigit()) >>> alpha = ''.join(s for s in sample if s.isalpha()) >>> numer, alpha ('123', 'ACTGAAC') If by 'always in the same format' you mean the positions of the numbers & alphas, you could slightly abuse the struct module: >>> import struct >>> sample = '123ACTGAAC' >>> format = '3s7s' # a string of 3 + a string of 7 >>> struct.unpack(format, sample) ('123', 'ACTGAAC') But seriously, you should use slicing: >>> sample = '123ACTGAAC' >>> sample[0:3], sample[3:] ('123', 'CTGAAC') You can also label the slices, which can be handy for self-documenting your code: >>> num = slice(3) >>> alp = slice(4,10) >>> sample[num], sample[alp] ('123', 'CTGAAC') From ram.rachum at gmail.com Mon Aug 3 12:47:43 2009 From: ram.rachum at gmail.com (cool-RR) Date: Mon, 3 Aug 2009 09:47:43 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> On Aug 3, 7:04?pm, "Colin J. Williams" wrote: > cool-RR wrote: > > Hello, > > > I wanted to announce that I have just released my little side project, > > PythonTurtle. > > Here is its website: > >http://pythonturtle.com > > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > > You can read more about it and download it on the website. > > > Ram. > > It looks neat but it's not yet ready for prime time. > > Colin W. I agree there's a lot that can be improved - I wanted to put it out there so I could get feedback and fix the important things first. So I'd appreciate you telling me what you think needs improvement. Ram. From sandhyaprabhakaran at gmail.com Mon Aug 3 12:52:48 2009 From: sandhyaprabhakaran at gmail.com (Sandhya Prabhakaran) Date: Mon, 3 Aug 2009 18:52:48 +0200 Subject: Extract the numeric and alphabetic part from an alphanumeric string In-Reply-To: <1e364c4e0908030849u7583637h9c8d688f8520b904@mail.gmail.com> References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> <1e364c4e0908030849u7583637h9c8d688f8520b904@mail.gmail.com> Message-ID: Oh yes indeed........! Now that works :D Thanks a lot !! 2009/8/3 Kushal Kumaran > > On Mon, Aug 3, 2009 at 8:47 PM, Sandhya > Prabhakaran wrote: > > Hi, > > > > I have a string as str='123ACTGAAC'. > > > > I need to extract the numeric part from the alphabetic part which I > > did using > >>>>numer=re.findall(r'\d+',str) > >>>>numer > > 123 > > > > The docs for re.findall say that it returns a list of matches. So > '123' will be numer[0]. > > > To get the alphabetic part, I could do > >>>>alpha=str.replace('123','') > >>>>alpha > > ACTGAAC > > But when I give > >>>>alpha=str.replace(numer,'') > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: expected a character buffer object > > > > That's what would happen if you pass in a list instead of a string to > replace. > > > How do I blank out the initial numeric part so as to get just the > > alphabetic part. The string is always in the same format. > > > > Please help. > > > > -- > kushal > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Mon Aug 3 12:55:06 2009 From: python at rcn.com (Raymond Hettinger) Date: Mon, 3 Aug 2009 09:55:06 -0700 (PDT) Subject: heapq "key" arguments References: <97932d10-8601-401f-bb69-a98db9036929@p15g2000vbl.googlegroups.com> <1582f82e-34aa-4b66-b989-c9f8351a5f1c@o9g2000prg.googlegroups.com> <4f096546-36a1-4633-9a24-1265ce0929ce@q14g2000vbi.googlegroups.com> Message-ID: <3d2f5ff5-201e-4451-b9e7-fb33652b44a7@d9g2000prh.googlegroups.com> [Duncan Booth] > The documentation doesn't say anything directly about stability, but the > implementation is actually stable. You can probably assume it must be at > least for nlargest and nsmallest otherwise the stated equivalence wouldn't > hold: > > e.g. nsmallest documentation says: > > ? ? ? ? Equivalent to: sorted(iterable, key=key)[:n] Yes. The code for nsmallest and nlargest preserves stability so that the equivalence is maintained. Raymond From wuwei23 at gmail.com Mon Aug 3 12:56:02 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 09:56:02 -0700 (PDT) Subject: Compiling regex inside function? References: Message-ID: Anthra Norell wrote: > def entries (l): > ? ? ? ? r = re.compile ('([0-9]+) entr(y|ies)') > ? ? ? ? match = r.search (l) > ? ? ? ? if match: return match.group (1) > > So the question is: does "r" get regex-compiled once at py-compile time > or repeatedly at entries() run time? The docs say: The compiled versions of the most recent patterns passed to re.match (), re.search() or re.compile() are cached, so programs that use only a few regular expressions at a time needn?t worry about compiling regular expressions. (But they don't say how few is 'only a few'...) If you're concerned about it, you could always set the compiled pattern to a default value in the function's argspec, as that _is_ only executed the once: def entries(line, regex = re.compile('([0-9]+) entr(y|ies)'): match = regex.search(line) ... From nagle at animats.com Mon Aug 3 12:57:08 2009 From: nagle at animats.com (John Nagle) Date: Mon, 03 Aug 2009 09:57:08 -0700 Subject: Help understanding the decisions *behind* python? In-Reply-To: References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> Message-ID: <4a7715ff$0$1641$742ec2ed@news.sonic.net> Dave Angel wrote: > sturlamolden wrote: >> On 20 Jul, 18:27, Phillip B Oldham wrote: >> Tuples are used for passing arguments to and from a function. Common >> use of tuples include multiple return values and optional arguments >> (*args). That's from Mesa, the Xerox PARC language of the 1970s. Mesa used tuples for subroutine arguments in a very straightforward way. Every function took one tuple as an argument, written as parameters in parentheses separated by commas. Every function returned a tuple as an argument. This had a nice symmetry; function outputs and function inputs had the same form. Mesa was the first language to break through the "single return value" syntax problem. Python doesn't go that far. John Nagle From wuwei23 at gmail.com Mon Aug 3 13:02:57 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 10:02:57 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> <4a7715ff$0$1641$742ec2ed@news.sonic.net> Message-ID: <686a0fac-b746-488f-9514-a1849fbda94d@g1g2000pra.googlegroups.com> John Nagle wrote: > Every function returned a tuple as an argument. This had a nice > symmetry; function outputs and function inputs had the same form. ? > Mesa was the first language to break through the "single return > value" syntax problem. > > ? ? Python doesn't go that far. I assume here you're referring to the former point and not the latter? From nobody at nowhere.com Mon Aug 3 13:23:06 2009 From: nobody at nowhere.com (Nobody) Date: Mon, 03 Aug 2009 18:23:06 +0100 Subject: Queryable Daemon References: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Message-ID: On Sun, 02 Aug 2009 19:36:08 -0600, Michael Torrie wrote: > Another possibility is shared memory segments. I'm not sure how > security is done in this case. Shared memory segments have an owner, group, and the standard ugo=rwx permissions (execute permission is present but ignored); see the shmget(2) and shmctl(2) manpages. But Unix-domain sockets are supported by the standard library, while shared memory would require a separate library, e.g.: http://semanchuk.com/philip/PythonIpc/ Also, there is unlikely to be an advantage to using shared memory in Python. In most cases, you would have to explicitly serialise Python objects into the shared memory region. It's more useful in C, where you can treat the region as a struct which is accessed directly from the program. From python at mrabarnett.plus.com Mon Aug 3 13:29:56 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 03 Aug 2009 18:29:56 +0100 Subject: iterate lines with regex In-Reply-To: References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> Message-ID: <4A771E94.70805@mrabarnett.plus.com> Robert Kern wrote: [snip] > > for line in readThis: > key_match = key.search(line) > if key_match is not None: > this_key = key_match.group(1) > # ... do something with this_key > map_match = map.search(line) > if map_match is not None: > this_map = map_match.group(1) > # ... do something with this_map > parcel_match = parcel.search(line) > if parcel_match is not None: > this_parcel = parcel_match.group(1) > # ... do something with this_parcel > re.search and re.match will return a MatchObject if successful or None if unsuccessful. A MatchObject is always true, so you can simplify to: ... if key_match: this_key = key_match.group(1) # ... do something with this_key ... From python at rcn.com Mon Aug 3 13:36:28 2009 From: python at rcn.com (Raymond Hettinger) Date: Mon, 3 Aug 2009 10:36:28 -0700 (PDT) Subject: heapq "key" arguments References: <97932d10-8601-401f-bb69-a98db9036929@p15g2000vbl.googlegroups.com> Message-ID: [Joshua Bronson]: > According tohttp://docs.python.org/library/heapq.html, Python 2.5 > added an optional "key" argument to heapq.nsmallest and > heapq.nlargest. I could never understand why they didn't also add a > "key" argument to the other relevant functions (heapify, heappush, > etc). The problem is that heapq acts on regular lists, so it does not have exclusive access to the structure. So, there is no reliable way for it to maintain a separate list of keys. Since the keys can't be saved in the structure (without possibly breaking other code), the fine grained heapq functions (like heappop and heappush) would need to call key functions every time they are invoked. This is at odds with the implicit guarantee of the key function that it will be called no more than once per key. The overall problem is one of granularity. A key function should be applied once in an initial pass, not on every call to a push/pop function. The everyday solution that most people use is to operate on a list of (key, record) tuples and let tuple comparison do the work for you. Another solution is to build a Heap class that does have exclusive access to the structure, but the API sugar often isn't worth the slightly weaker performance. One other thought. Heaps are a lazy evaluation structure, so their fined-grained mutation functions only work well with just a single ordering function, so there is not need to have (and every reason to avoid) changing key functions in mid-stream. IOW, the key function needs to be constant across all accesses. Contrast this with other uses of key functions where it makes perfect sense to run minage=min(data, key=attrgetter('age')) and then running minsal=min(data, key=attrgetter('salary')). The flexibility to change key functions just doesn't make sense in the context of the fine-grained heap functions. Accordingly, this is why I put key functions in nlargest() and nsmallest() but not in heappush() and friends. The former can guarantee no more than one key function call per entry and they evaluate immediately instead of lazily. Raymond From duncan.booth at invalid.invalid Mon Aug 3 13:47:05 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Aug 2009 17:47:05 GMT Subject: Compiling regex inside function? References: Message-ID: alex23 wrote: > The docs say: > The compiled versions of the most recent patterns passed to re.match > (), re.search() or re.compile() are cached, so programs that use only > a few regular expressions at a time needn?t worry about compiling > regular expressions. > > (But they don't say how few is 'only a few'...) If you're interested then it isn't all that hard to open up re.py in an editor and see that the cache holds up to 100 items. Of course that's just an implementation detail so other versions might have a different size cache. Also implementation dependant, but it might be worth knowing that when you hit that limit the cache is simply cleared: there's no gradual clearing of the oldest or least used entries. From bcharrow at csail.mit.edu Mon Aug 3 14:26:38 2009 From: bcharrow at csail.mit.edu (Ben Charrow) Date: Mon, 03 Aug 2009 14:26:38 -0400 Subject: urllib2.urlopen timeout In-Reply-To: <4A76AB8F.5090403@yahoo.co.uk> References: <4A76AB8F.5090403@yahoo.co.uk> Message-ID: <4A772BDE.4020602@csail.mit.edu> Zdenek Maxa wrote: > Hi, > > I would like to ask how I should set timeout for a call: > > f = urllib2.urlopen(url) > > > I know that Python 2.6 offers > urllib2.urlopen(url[, data][, timeout]) > which would elegantly solved my problem, but I have to stick to Python 2.5. > There are three solutions that I know about: 1) Make your own little HTTP library and set timeouts for each of your sockets. 2) The same as the above, except use asynchronous sockets and the the select module. 3) If you're on a Unix style system, use the signal module (the example is helpful http://docs.python.org/library/signal.html#example) Here's some code: import urllib2 import signal class TimeoutException(Exception): """SIGALARM was sent to the process""" pass def raise_timeout(signum, frame): raise TimeoutException("Timeout!") signal.signal(signal.SIGALRM, raise_timeout) try: signal.alarm(5) # raise alarm in 5 seconds data = urllib2.urlopen("http://www.google.com").readlines() except TimeoutException, ex: data = None finally: signal.alarm(0) # disable alarm HTH, Ben From sakradevanamindra at gmail.com Mon Aug 3 14:39:24 2009 From: sakradevanamindra at gmail.com (Leo Brugud) Date: Mon, 3 Aug 2009 11:39:24 -0700 (PDT) Subject: Can python do something like the onclick events in javascript ? Message-ID: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> I'm trying to use python to build a simple web page that make use of the onclick behavior, instead of requiring users to click the 'submit' button. I realize in javascript there are onclick, onchange events. Is python capable of doing the same? Thanks in Advance From robert.kern at gmail.com Mon Aug 3 14:44:07 2009 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Aug 2009 13:44:07 -0500 Subject: iterate lines with regex In-Reply-To: <4A771E94.70805@mrabarnett.plus.com> References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> <4A771E94.70805@mrabarnett.plus.com> Message-ID: On 2009-08-03 12:29, MRAB wrote: > Robert Kern wrote: > [snip] >> >> for line in readThis: >> key_match = key.search(line) >> if key_match is not None: >> this_key = key_match.group(1) >> # ... do something with this_key >> map_match = map.search(line) >> if map_match is not None: >> this_map = map_match.group(1) >> # ... do something with this_map >> parcel_match = parcel.search(line) >> if parcel_match is not None: >> this_parcel = parcel_match.group(1) >> # ... do something with this_parcel >> > re.search and re.match will return a MatchObject if successful or None > if unsuccessful. A MatchObject is always true, so you can simplify to: > > ... > if key_match: > this_key = key_match.group(1) > # ... do something with this_key > ... True, but I prefer to maintain a consistent style for None-testing regardless of whether or not I am sure the not-None type will have a suitable __nonzero__ implementation. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From deets at nospam.web.de Mon Aug 3 14:45:14 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Aug 2009 20:45:14 +0200 Subject: Can python do something like the onclick events in javascript ? In-Reply-To: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> References: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> Message-ID: <7dophqF2crpcqU1@mid.uni-berlin.de> Leo Brugud schrieb: > I'm trying to use python to build a simple web page that make use of > the onclick behavior, instead of requiring users > to click the 'submit' button. If that's the only reason, don't use JS for that, it's annoying. > I realize in javascript there are onclick, onchange events. Is python > capable of doing the same? Somewhat, through a python-2-javascript-translation: http://pyjs.org/ Diez From benjamin.kaplan at case.edu Mon Aug 3 14:54:58 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 3 Aug 2009 14:54:58 -0400 Subject: Can python do something like the onclick events in javascript ? In-Reply-To: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> References: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> Message-ID: On Mon, Aug 3, 2009 at 2:39 PM, Leo Brugud wrote: > I'm trying to use python to build a simple web page that make use of > the onclick behavior, instead of requiring users > to click the 'submit' button. > > I realize in javascript there are onclick, onchange events. Is python > capable of doing the same? > It depends. Python is usually used as a server-side language while Javascript is client-side. The client's web browser requests a web page, your program processes that request and sends the client a web page. That web page can contain anything you want, including Javascript. Your python program never hears from that client again until the *client* initiates contact, be it through a submit button or a javascript event that submits an HTTP request. You'll have to add the onclick and onchange code to the resulting web page, using Javascript, because Python never handles sending the request, jsut receiving it. Of course, this isn't the case if you are using something like pyjs, which compiles Python code to Javascript, your code will be running as Javascript code and not Python code. > > Thanks in Advance > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From saimapk81 at gmail.com Mon Aug 3 15:01:51 2009 From: saimapk81 at gmail.com (saima81) Date: Mon, 3 Aug 2009 12:01:51 -0700 (PDT) Subject: "MAGZINES IN URDU" "PAKISTANI MAGZINES" PAKISTAN" "PAKISTAN" "PAKISTANI NEWSPAPERS" "tHE eXPRTESS" "JANG NEWS" "WAQT" "DAWN" ON www.pak-web-pages.blogspot.com Message-ID: <054ce11f-597a-4c6e-b130-68a3bee4ad1b@i18g2000pro.googlegroups.com> "MAGZINES IN URDU" "PAKISTANI MAGZINES" PAKISTAN" "PAKISTAN" "PAKISTANI NEWSPAPERS" "tHE eXPRTESS" "JANG NEWS" "WAQT" "DAWN" ON www.pak-web-pages.blogspot.com From sam at tregar.com Mon Aug 3 15:11:38 2009 From: sam at tregar.com (Sam Tregar) Date: Mon, 3 Aug 2009 15:11:38 -0400 Subject: Online payment module Message-ID: Hello all. I'm considering building a module to provide a cross-payment-gatewat API for making online payments. In the Perl world we have a module like this called Business::OnlinePayment ( http://search.cpan.org/~jasonk/Business-OnlinePayment-2.01/OnlinePayment.pm). Is there anything like this in Python? My searches so far haven't turned up anything. If I don't find one I'll probably build one, covering PayPal and Authorize.net to start. If anyone is interested in discussing the project and/or getting involved shoot me an email. Thanks, -sam -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Mon Aug 3 15:21:57 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 03 Aug 2009 12:21:57 -0700 Subject: .dbf tables and Null In-Reply-To: <2f4d5719-6ca8-4ef2-8734-420b3044b1dc@l35g2000pra.googlegroups.com> References: <2f4d5719-6ca8-4ef2-8734-420b3044b1dc@l35g2000pra.googlegroups.com> Message-ID: <4A7738D5.3010009@stoneleaf.us> John Machin wrote: > On Aug 1, 3:41 am, Ethan Furman wrote: > >>Mornin'! and a good one, too, I hope. >> >>Question for you... >> >>First part of the question: What is the general value in having Null >>capability for fields? > > > In general, in any database system, so that one can distinguish > between "the customer has no 'middle name'" ('') and "the customer's > 'middle name' is unknown" (NULL). > > >>Second part: Is there a tangible difference between Null, and the >>nothing of 0, '', False, etc, in python? > > > 0 is the zero thing, it is not nothing. False is not nothing. > > > >>Third part: If there is a tangible difference, do those of us who use >>python and these old, refuse-to-die, .dbf files actually have need of, >>or have tables including, Null values? >> >>P.S. part (for John Machin, if he sees this ;) >>Will the dbf package you are working on support Null values? > > > My philosophy when digging stuff out of arcane storages is to expose > what is found and leave any kludging/sanitising to the next layer. > > For example, None is returned for an N (Number) field that's all > spaces; it's up to the caller to decide whether to treat None as zero, > raise an exception, pop up a data-collection dialogue box, ... > > If you mean specifically the Visual Foxpro v3 _NullFlags hack, yes, it > already supports that, as well as the VFP9 abuse of that hack for > Varchar and Varbinary fields :-) Thank you. It's been an interesting journey learning Python. Probably the two most difficult concepts for me to really internalize have been "batteries included" (thank you for the pointer to struct!) (I finally 'found' and incorporated array into my dbf module), and "everything is an object, even functions!". The unittest module worked wonderfully in making sure everything still worked after switching over to array as well, and the 30+% speed-up is also nice! :) All in all, I *love* Python! ~Ethan~ From no.email at please.post Mon Aug 3 15:59:23 2009 From: no.email at please.post (kj) Date: Mon, 3 Aug 2009 19:59:23 +0000 (UTC) Subject: kw param question Message-ID: I want to write a decorator that, among other things, returns a function that has one additional keyword parameter, say foo=None. When I try def my_decorator(f): # blah, blah def wrapper(*p, foo=None, **kw): x = f(*p, **kw) if (foo): # blah, blah else # blah blah return wrapper ...i get a syntax error where it says "foo=None". I get similar errors with everything else I've tried. Is is possible to do this in Python? TIA! kynn From hjtoi-better-remove-before-reply at comcast.net Mon Aug 3 16:08:37 2009 From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen) Date: Mon, 03 Aug 2009 13:08:37 -0700 Subject: M2Crypto: X509.X509_Extension_Stack() throws AssertionError References: Message-ID: Matthias G?ntert wrote: > Why is the following code snippet throwing an AssertionError? Is that > behavior a bug within X509.X509_Extension_Stack()? How would you suggest > popping every element from the stack? > > cert_extension_2 = X509.new_extension("keyUsage", "101000000") Maybe your OpenSSL is too old. keyUsage needs to be defined in OpenSSL obj_dat.h file for this to work. > cert_extension_3 = X509.new_extension("subjectAlternativeName", > "DNS:www.mydomain.tld") And I believe you mispelled this, try subjectAltName. With the change in spelling for subjectAltName your test passes for me using OpenSSL 1.0.0beta3 and M2Crypto 0.20beta with the (still incomplete) patch to make M2Crypto work with OpenSSL 1.0: https://bugzilla.osafoundation.org/show_bug.cgi?id=12855 -- Heikki Toivonen - http://heikkitoivonen.net From marduk at letterboxes.org Mon Aug 3 16:27:34 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Mon, 03 Aug 2009 16:27:34 -0400 Subject: kw param question In-Reply-To: References: Message-ID: <1249331254.1179.7.camel@brotherus.corp.redhat.com> On Mon, 2009-08-03 at 19:59 +0000, kj wrote: > > I want to write a decorator that, among other things, returns a > function that has one additional keyword parameter, say foo=None. > > When I try > > def my_decorator(f): > # blah, blah > def wrapper(*p, foo=None, **kw): > x = f(*p, **kw) > if (foo): > # blah, blah > else > # blah blah > return wrapper > > ...i get a syntax error where it says "foo=None". I get similar > errors with everything else I've tried. > Not exactly sure what you're trying to do.. but, regular arguments must be used *before* positional and keyword arguments so the definition: def wrapper(*p, foo=None, **kw): is syntactically incorrect whereby the following is correct: def wrapper(foo=None, *p, **kw): But if what you are wanting is to actually add 'foo' to kw then I would do this: def my_decorator(f): # blah, blah def wrapper(*p, **kw): if 'foo' not in kw: kw['foo'] = None x = f(*p, **kw) if kw['foo']: # blah blah else: # blah blah return wrapper From rt8396 at gmail.com Mon Aug 3 16:35:51 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 13:35:51 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> Message-ID: Hello, I wanted to announce that I have just released my little side project, PythonTurtle. [snip] I think it looks great --haven't download the source yet-- but i really like the screenshot. This will be more "inviting" to the new, inexperianced users. I like the idea of packaging up the command prompt and the canvas into one very friendly interface. I especially like that you are using a "real" turtle. I can remember the first time i used turtle (in python stdlib) and i kept saying to myself... "Were the heck is this damn turtle?!?!" (>_<) :-) From bartsmeets86 at gmail.com Mon Aug 3 16:39:44 2009 From: bartsmeets86 at gmail.com (Bart Smeets) Date: Mon, 3 Aug 2009 22:39:44 +0200 Subject: easy_install: unresolved external symbol Message-ID: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> Hello, I keep getting errors when trying to use easy_install to install bbfreeze or cxfreeze (same errors). This is the output: http://pastebin.com/m65ba474d The error message unresolved external symbol keeps popping up. I have no idea how to solve this. Can anyone give me a hint? Thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From wells at submute.net Mon Aug 3 16:47:23 2009 From: wells at submute.net (Wells Oliver) Date: Mon, 3 Aug 2009 15:47:23 -0500 Subject: Ordering of dict keys & values Message-ID: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> I understand that the keys in a dictionary are ordered not randomly but something practically close to it, but if I create a SQL query like so: query = 'INSERT INTO Batting (%s) VALUES(%s)' % (','.join(stats.keys()), ','.join(stats.values())) Can I at least rely on the value being in the same index as its corresponding key? -- Wells Oliver wells at submute.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From dciphercomputing at gmail.com Mon Aug 3 16:55:13 2009 From: dciphercomputing at gmail.com (Simon) Date: Mon, 3 Aug 2009 13:55:13 -0700 (PDT) Subject: Newbie Question regarding __init__() References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> Message-ID: <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> On Aug 2, 5:51?am, Dave Angel wrote: > Simon wrote: > > Okay I will fix my code and include "self" and see what happens. ?I > > know I tried that before and got another error which I suspect was > > another newbie error. > > > The idea behind the init_Pre is that I can put custom code here to > > customize the __init__ instead of creating a new subclass. ?This kind > > of hook pattern allows you to flatten your inheritance hierarchy. ?I > > can choose in the init_Pre method to execute code before the init_exec > > (which contains the default __init__ code) and still execute the > > init_Exec method or I can completely customize the entire __init__ by > > returning False from init_Pre and prevent the init_Exec from being > > called. ?I use this type of pattern with almost all my methods. ?In > > this way I can create a less complicated inheritance chain but still > > have have custom code when needed without sub-classing. > > > I am use to Visual FoxPro which where you can do > > > =is.init_Pre().And.This.init_Exec() and the result is discarded so > > that is why it looks the way it does. ?In this form init_Exec has to > > return a value. ?However, If self.init_Pre(): self.init_Exec() would > > work the same and then I could avoid returning a value. > > > Thanks, > > Simon > > > On Aug 1, 5:52 am, Dave Angel wrote: > > >> Nat Williams wrote: > > >>> As MRAB described, ALL instance methods need to accept 'self' as a first > >>> parameter, as that will be passed to them implicitly when they are called. > >>> This includes __init__. ?The name 'self' is just a commonly accepted > >>> convention for the name of the instance object passed to methods. ?You don't > >>> have to call it that, but you really should. > > >>> Take a look athttp://docs.python.org/tutorial/classes.html#class-objects > >>> It might help shed some light on how methods and instances work. > > >>> One other thing. ?I'm a little confused by the first line of > >>> dcObject.__init__: > > >>> self.init_Pre() and self.init_Exec() > > >>> I suspect this does not do what you think it does. ?init_Pre and init_Exec > >>> will both be called by this expression (unless init_Pre throws an exception, > >>> of course). ?You're not getting anything here that you wouldn't by just > >>> calling each method on a separate line, except just making it harder to > >>> read. > > >> Read the doc-string for init_Pre() and for init_Exec(). ?The final > >> version of init_Pre() will return False in some circumstances, and in > >> those circumstances Simon doesn't want init_Exec() to be called. ?He's > >> deliberately using the short-circuit evaluation of ?'and' ?to accomplish > >> that. > > >>> On Fri, Jul 31, 2009 at 8:53 PM, Simon wrote: > > >>>> Hi > > >>>> So should the dcObject class include the "self" as well since I have > >>>> not defined an __init__ method in dcCursor? > > >>>> Simon > > >>>> -- > >>>>http://mail.python.org/mailman/listinfo/python-list > > >> Every one of those methods in both of those classes need a "self" first > >> argument. ?As others have said, all instance methods need a 'self.' > > (Please don't top-post. ?You should put new responses at the end of > quoted text, or sometimes inline if that's clearer.) > > I don't understand your comparison to Foxpro. ?read on. > > As your code was last posted, you don't need a return value from > init_Exec() ?Every function that doesn't have an explicit return will > return None. ?And None is interpreted as False in an "and" expression. ? > If you had an "if" around the whole thing, then you'd care. > > DaveA All I meant by the FoxPro comment was the idea of using the equal sign without a variable to throw away the result. Also in FoxPro there is no such thing as automatically returning None. If there is no explicit return then True is returned. Thanks I did not know that None is interpreted as False. Simon From no.email at please.post Mon Aug 3 16:58:46 2009 From: no.email at please.post (kj) Date: Mon, 3 Aug 2009 20:58:46 +0000 (UTC) Subject: kw param question References: Message-ID: In Albert Hopkins writes: >On Mon, 2009-08-03 at 19:59 +0000, kj wrote: >> >> I want to write a decorator that, among other things, returns a >> function that has one additional keyword parameter, say foo=None. >> >> When I try >> >> def my_decorator(f): >> # blah, blah >> def wrapper(*p, foo=None, **kw): >> x = f(*p, **kw) >> if (foo): >> # blah, blah >> else >> # blah blah >> return wrapper >> >> ...i get a syntax error where it says "foo=None". I get similar >> errors with everything else I've tried. >> >Not exactly sure what you're trying to do.. Yeah, I wasn't too clear. I figured out how to do what I wanted to do: def my_decorator(f): # blah, blah def wrapper(*p, **kw): foo = kw.pop('force', None) x = f(*p, **kw) if (foo): # blah, blah else # blah blah return wrapper Now the definitions of the original functions do not include the foo=None argument, but "actual" functions (i.e. the ones generated by the decorator) all accept the optional foo parameter. The only remaining problem is how to document this... I don't see how pydoc could possibly figure this one out. I guess this is sufficient argument to abandon this idea. Bummer. kynn From pavlovevidence at gmail.com Mon Aug 3 17:04:12 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Aug 2009 14:04:12 -0700 (PDT) Subject: iterate lines with regex References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> <4A771E94.70805@mrabarnett.plus.com> Message-ID: <463f3ea4-c8a4-405b-9eab-95a878684db0@a13g2000yqc.googlegroups.com> On Aug 3, 11:44?am, Robert Kern wrote: > On 2009-08-03 12:29, MRAB wrote: > > > > > > > Robert Kern wrote: > > [snip] > > >> for line in readThis: > >> key_match = key.search(line) > >> if key_match is not None: > >> this_key = key_match.group(1) > >> # ... do something with this_key > >> map_match = map.search(line) > >> if map_match is not None: > >> this_map = map_match.group(1) > >> # ... do something with this_map > >> parcel_match = parcel.search(line) > >> if parcel_match is not None: > >> this_parcel = parcel_match.group(1) > >> # ... do something with this_parcel > > > re.search and re.match will return a MatchObject if successful or None > > if unsuccessful. A MatchObject is always true, so you can simplify to: > > > ... > > if key_match: > > this_key = key_match.group(1) > > # ... do something with this_key > > ... > > True, but I prefer to maintain a consistent style for None-testing regardless of > whether or not I am sure the not-None type will have a suitable __nonzero__ > implementation. There's one thing to keep in mind. In the unknown future, it's possible that re.match could be changed to return an object with a false value that contains some information about the reason for failure, or partial match information, or something like that. If that happens, code like: if m: will continue to work, while code like if m is not None: will suddenly fail. Granted, it's not likely to happen for regexps but it could happen in similar situations in other places. I am one of the biggest critics of implicit boolean values, but given that Python has it, I think it is best to adhere strongly idiomatic uses like regexps. Carl Banks From sturlamolden at yahoo.no Mon Aug 3 17:04:53 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 3 Aug 2009 14:04:53 -0700 (PDT) Subject: Is python buffer overflow proof? References: Message-ID: On 2 Aug, 15:50, Jizzai wrote: > Is a _pure_ python program buffer overflow proof? > > For example in C++ you can declare a char[9] to hold user input. > If the user inputs 10+ chars a buffer overflow occurs. Short answer: NO Bounds checking on sequence types is a protection against buffer overflow, but is certainly not sufficient. The Python interpreter is written in C. Python extension modules are written in C (or something similar). If you find an unprotected buffer in this C code, you can possibly overflow this buffer. This can be used for nasty things like corrupting the stack and injecting malicious code. There is a reason why the Python sandbox (rexec and Bastion modules) was disabled in Python 2.3. IronPython and Jython provides better protection against buffer overflow than CPython, as these interpreters are written in safer languages (C# and Java). You thus get an extra layer of protection between the Python code and the unsafe C (used in JVM and .NET runtimes). From no.email at please.post Mon Aug 3 17:07:32 2009 From: no.email at please.post (kj) Date: Mon, 3 Aug 2009 21:07:32 +0000 (UTC) Subject: no-clobber dicts? Message-ID: I use the term "no-clobber dict" to refer to a dictionary D with the especial property that if K is in D, then D[K] = V will raise an exception unless V == D[K]. In other words, D[K] can be set if K doesn't exist already among D's keys, or if the assigned value is equal to the current value of D[K]. All other assignments to D[K] trigger an exception. The idea here is to detect inconsistencies in the data. This is a data structure I often need. Before I re-invent the wheel, I thought I'd ask: is it already available? TIA! kynn From aurele.tux at gmail.com Mon Aug 3 17:11:20 2009 From: aurele.tux at gmail.com (aurelien) Date: Mon, 03 Aug 2009 23:11:20 +0200 Subject: Hello to the community Message-ID: <1249333880.7712.20.camel@r2d2> Hello to the Python community ! I'm a totaly newbbie in this langage. I hope i will learn a lot with you. Thanks. aurelien From boris.arloff at yahoo.com Mon Aug 3 17:25:06 2009 From: boris.arloff at yahoo.com (Boris Arloff) Date: Mon, 3 Aug 2009 14:25:06 -0700 (PDT) Subject: Trying to get ABC to work Message-ID: <358094.5069.qm@web65302.mail.ac2.yahoo.com> Hi, ? Looking for ideas on getting Abstract Base Classes to work as intended within a metaclass. ? I was wondering if I could use an abc method within a metaclass to force a reimplementation when a class is instantiated from the metaclass.? It seems like I cannot do so.? I implemented the following test case: ? import abc class MetaExample(type): ? def __init__(cls, name, bases, ns): ??? setattr(cls, 'cls_meth', cls.cls_meth)??? # cls method as instance method ??? setattr(cls, 'cls_abc', cls.cls_abc)????????# abc cls method as instance method ? ? def cls_meth(cls): ??? print('Class method defined stub') ? ? @abc.abstractmethod ? def cls_abc(cls): ??? try: ????? print('Class-Abstract method defined stub') ??? except NotImplementedError, err: ????? print('Must implement cls_abc.') ??? except: ????? print('General exception at cls_abc method.') ? Then I create class MyKlass from the metaclass and instantiate it as myklass: MyKlass(object): __metaclass__ = MetaExample myklass = MyKlass() myklass.cls_meth()?? --> prints "Class method defined stub" myklass.cls_abc()???? --> prints "Class-Abstract method defined stub" ? I was hopping for myklass.cls_abc() to print "Must implement cls_abc." ? However, this makes sense since?MyKlass implements from the metaclass the cls_abc method and?there will never be an abstraction?of this method. ? Any ideas on how to get this done?? Any way I could define an abstract method within a metaclass and have it behave?with abstraction when the class is created off the metaclass? ? I other words, I want to force an implementation of cls_abc() method when MyKlass(object): __metaclass__ = MetaExample is declared, or else get NotImplementedError exception. ? Thanks, Boris Arloff ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Mon Aug 3 17:25:18 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 Aug 2009 14:25:18 -0700 Subject: Ordering of dict keys & values In-Reply-To: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> References: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> Message-ID: <50697b2c0908031425i22fd02ffjde3e41a697eb1c30@mail.gmail.com> On Mon, Aug 3, 2009 at 1:47 PM, Wells Oliver wrote: > I understand that the keys in a dictionary are ordered not randomly but > something practically close to it, but if I create a SQL query like so: > > query = 'INSERT INTO Batting (%s) VALUES(%s)' % (','.join(stats.keys()), > ','.join(stats.values())) > > Can I at least rely on the value being in the same index as its > corresponding key? Yes. Per http://docs.python.org/library/stdtypes.html#dict.items : """ Note: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary?s history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). """ Cheers, Chris -- http://blog.rebertia.com From Samnsparky at gmail.com Mon Aug 3 17:29:05 2009 From: Samnsparky at gmail.com (Sparky) Date: Mon, 3 Aug 2009 14:29:05 -0700 (PDT) Subject: WindowsError: exception: access violation writing 0x00000000 Message-ID: <73c6c4f5-a00b-4f95-a85d-0f257b2f001a@c2g2000yqi.googlegroups.com> Hello! I am using cTypes on Windows to interface with a dll and I keep getting an error when I execute this method: def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0): """ Name: U12.eAnalogIn(channel, idNum = None, demo = 0, readD=0) Args: See section 4.4 of the User's Guide Desc: This is a simplified version of Counter. Reads & resets the counter (CNT). """ if idNum is None: idNum = self.id ljid = ctypes.c_long(idNum) state = ctypes.c_long(999) ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, readD, ctypes.byref(state)) if ecode != 0: raise LabJackException(ecode) if ljid == -1: raise LabJackException(-1, "LabJack not found.") return {"idnum":ljid.value, "state":state.value} Here is the error message: Traceback (most recent call last): File "", line 1, in device.eDigitalIn(0) File "C:\Documents and Settings\All Users\Documents\Python \LabJackPython_new\u12.py", line 118, in eDigitalIn ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, readD, ctypes.byref(state)) WindowsError: exception: access violation writing 0x00000000 Here is the signature of the method (which is known to work with C++ programs): long _stdcall EDigitalIn(long *idnum, long demo, long channel, long readD, long *state); staticLib is declared with staticLib = ctypes.windll.LoadLibrary ("ljackuw"). Any ideas? Thanks, Sam From rt8396 at gmail.com Mon Aug 3 17:47:54 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 14:47:54 -0700 (PDT) Subject: no-clobber dicts? References: Message-ID: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> On Aug 3, 4:07?pm, kj wrote: > I use the term "no-clobber dict" to refer to a dictionary D with > the especial property that if K is in D, then > > ? D[K] = V > > will raise an exception unless V == D[K]. ?In other words, D[K] > can be set if K doesn't exist already among D's keys, or if the > assigned value is equal to the current value of D[K]. ?All other > assignments to D[K] trigger an exception. > > The idea here is to detect inconsistencies in the data. > > This is a data structure I often need. ?Before I re-invent the > wheel, I thought I'd ask: is it already available? > > TIA! > > kynn Not sure if something like this already exists, but it would be trivial to implement by overriding dict.__setitem__() badda-bing baby! From clp2 at rebertia.com Mon Aug 3 18:00:14 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 Aug 2009 15:00:14 -0700 Subject: no-clobber dicts? In-Reply-To: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: <50697b2c0908031500w23af3271y49ef3aab49a67695@mail.gmail.com> On Mon, Aug 3, 2009 at 2:47 PM, r wrote: > On Aug 3, 4:07?pm, kj wrote: >> I use the term "no-clobber dict" to refer to a dictionary D with >> the especial property that if K is in D, then >> >> ? D[K] = V >> >> will raise an exception unless V == D[K]. ?In other words, D[K] >> can be set if K doesn't exist already among D's keys, or if the >> assigned value is equal to the current value of D[K]. ?All other >> assignments to D[K] trigger an exception. >> >> The idea here is to detect inconsistencies in the data. >> >> This is a data structure I often need. ?Before I re-invent the >> wheel, I thought I'd ask: is it already available? >> >> TIA! >> >> kynn > > Not sure if something like this already exists, but it would be > trivial to implement by overriding dict.__setitem__() That is, if you don't care about .update() not preserving the invariant. Otherwise, one will need to look at the UserDict module. Cheers, Chris -- http://blog.rebertia.com From ram.rachum at gmail.com Mon Aug 3 18:03:31 2009 From: ram.rachum at gmail.com (cool-RR) Date: Mon, 3 Aug 2009 15:03:31 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> Message-ID: On Aug 3, 11:35?pm, r wrote: > Hello, > I wanted to announce that I have just released my little side > project, > PythonTurtle. > [snip] > > I think it looks great --haven't download the source yet-- but i > really like the screenshot. This will be more "inviting" to the new, > inexperianced users. I like the idea of packaging up the command > prompt and the canvas into one very friendly interface. ?I especially > like that you are using a "real" turtle. > > I can remember the first time i used turtle (in python stdlib) and i > kept saying to myself... > > ? ? "Were the heck is this damn turtle?!?!" (>_<) > > :-) Thanks for the compliments; The things you mentioned you liked are all things that I was specifically thinking about when I decided to make PythonTurtle. Well, maybe minus the screenshot :) From victorsubervi at gmail.com Mon Aug 3 18:05:13 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 3 Aug 2009 18:05:13 -0400 Subject: RE Question In-Reply-To: References: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> Message-ID: <4dc0cfea0908031505t571b8d4cqa28579ae14c9209a@mail.gmail.com> That worked. Thank you again :) Victor On Mon, Aug 3, 2009 at 12:13 AM, Gabriel Genellina wrote: > En Sun, 02 Aug 2009 18:22:20 -0300, Victor Subervi < > victorsubervi at gmail.com> escribi?: > > > How do I search and replace something like this: >> aLine = re.sub('[<]?[p]?[>]?> a-zA-Z0-9"\'=:]*>[<]?[b]?[>]?', '', aLine) >> where RE *only* looks for the possibility of "

" at the beginning of the >> string; that is, not the individual components as I have it coded above, >> but >> the entire 3-character block? >> > > An example would make it more clear; I think you want to match either > "

" is > optional. Use a normal group or a non-capturing group: > r'(

)? > That said, using regular expressions to parse HTML or XML is terribly > fragile; I'd use a specific tool (like BeautifulSoup, ElementTree, or lxml) > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From darkneter at gmail.com Mon Aug 3 18:14:41 2009 From: darkneter at gmail.com (NighterNet) Date: Mon, 3 Aug 2009 15:14:41 -0700 (PDT) Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> <8bede581-f260-4c69-abf0-1e8071380b76@z4g2000prh.googlegroups.com> <7e6cdc26-bcc0-4503-b7b4-9ad80b1041f6@v37g2000prg.googlegroups.com> Message-ID: On Aug 2, 12:25?pm, Piet van Oostrum wrote: > >>>>> NighterNet (N) wrote: > >N> Here the full code. > >N> flashpolicy.xml > >N> [[[ > >N> > >N> > >N> ? ? > >N> > >N> ]]] > >N> flashpolicytest_server3x.py > >N> [[[ > >N> #!/usr/local/bin/python > >N> ''' > >N> Still under testing... > >N> python version 3.x.x > >N> ''' > >N> importsocket > >N> import threading > >N> import sys > >N> import os > >N> file_name = 'flashpolicy.xml' > >N> fh = open(file_name, "r") > >N> policy = fh.read(10001) > > You never use that variable. > > > > >N> host = ''; #out side network > >N> port = 5555; > >N> print ("# ?------------- Init... ------------- ?#"); > >N> class ClientThread (threading.Thread): > >N> ? ? ? global policy; > >N> ? ? ? allClients = []; > >N> ? ? ? vlock = threading.Lock(); > >N> ? ? ? id = 0 # next available thread number > >N> ? ? ? def __init__(self,clientSocket): > >N> ? ? ? ? ? ? ? threading.Thread.__init__(self) > >N> ? ? ? ? ? ? ? self.sockfd = clientSocket; #socketclient > >N> ? ? ? ? ? ? ? self.name = ''; > >N> ? ? ? ? ? ? ? ClientThread.id += 1 > >N> ? ? ? ? ? ? ? self.id = ClientThread.id > >N> ? ? ? ? ? ? ? self.nickName = ''; > >N> ? ? ? ? ? ? ? self.allClients.append(self.sockfd); > >N> ? ? ? def sendAll(self,buff): > >N> ? ? ? ? ? ? ? for index,clientSock in enumerate(self.allClients): > >N> ? ? ? ? ? ? ? ? ? ? ? try: > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? clientSock.send(buff); > > There is no guarantee that send will indeed transmit all of buff. It is > better to use clientSock.sendall(buff). Or you should check the return > value of send and check if it is equal to the length of buff. And repeat > if not. (But sendall is easier). > > Also don't use ; at the end of the statement. It's not pythonic. > > >N> ? ? ? ? ? ? ? ? ? ? ? except (socket.error): > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ('errorsocket%s\n',index,"| clean"); > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? clientSock.close() > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? del self.allClients[index] > >N> ? ? ? def run(self): > >N> ? ? ? ? ? ? ? while True: > >N> ? ? ? ? ? ? ? ? ? ? ? buff = self.sockfd.recv(1028); > > There is no guarantee that recv will get the whole message. It may even > get as little as 1 byte. So you should check the return value of recv. > The official way is to keep reading until you have enough input or until > you hit end of file. > > >N> ? ? ? ? ? ? ? ? ? ? ? if not buff: > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ("connect close...(client side)"); > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.sockfd.close(); > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? break #incase it loop infinite > >N> ? ? ? ? ? ? ? ? ? ? ? if str(buff) == str("b\'\\x00\'"): > > What you check here is whether buff contains the byte sequence that starts with a > b, then a ' ... and ending with the 5 bytes \ x 0 0 ' which is wrong. > > Actually it should be: > > if buff == b\'\x00': > or > if buff == b\'\0': > > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ('policy FOUND >>> sending...') > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print(buff) > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? b = b' >N> from domain=\"*\" to-ports=\"*\" />' > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print (b) > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.sockfd.send(b); > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.sockfd.sendall(b); > > Only self.sockfd.sendall; delete the line with self.sockfd.send(b). And > remove the semicolons for esthetical reasons. > > >N> Some odd reason I can't send flash policy from python to flashsocket > >N> to agrees with the connection. > > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org thanks it help. I was not sure about the format most the time. From nagle at animats.com Mon Aug 3 18:19:22 2009 From: nagle at animats.com (John Nagle) Date: Mon, 03 Aug 2009 15:19:22 -0700 Subject: Obtaining Python version Message-ID: <4a776184$0$1611$742ec2ed@news.sonic.net> This works, but it seems too cute: >>> pyver = map(int,sys.version.split()[0].split('.')) >>> print(pyver) [2, 6, 1] Is it guaranteed that the Python version string will be in a form suitable for that? In other words, does "sys.version" begin N.N.N other stuff in all versions, and will it stay that way? Are there ever non-numeric versions, like "3.2.rc1"? John Nagle From rhodri at wildebst.demon.co.uk Mon Aug 3 18:24:04 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 03 Aug 2009 23:24:04 +0100 Subject: fast video encoding In-Reply-To: <0c8cfac7-0a70-4e1f-90ec-19e9c45cae89@h21g2000yqa.googlegroups.com> References: <570097d0-2b2a-4705-892f-0d0154d69d63@b14g2000yqd.googlegroups.com> <0c8cfac7-0a70-4e1f-90ec-19e9c45cae89@h21g2000yqa.googlegroups.com> Message-ID: On Sun, 02 Aug 2009 03:44:17 +0100, sturlamolden wrote: > On 29 Jul, 10:14, gregorth wrote: > >> for a scientific application I need to save a video stream to disc for >> further post processing. > > I have worked a bit on this as well. There are two things that make > scientific applications different form common video encoding: > > First, a scientific video stream is often very different from a > 'movie': There are usually very little 'movement'. For example, when I > have filmed a mouse swimming in a water maze (a pool of milky white > water), the only thing that moves is the rat. So I could achieve > excellent compression just by saving the pixels that changed. These are referred to as P-frames; any encoder that gets further than the most basic version of any video protocol will do this for you. Unfortunately, water pixels change a lot from frame to frame, even when the camera is static, so it doesn't gain you as much as you might hope in cases like you mention. > Second, scientific data should be stored with lossless compression if > possible. If data storage is no object, be my guest. Of course, you're going to have to write your own codecs for this, since pretty much every video protocol in existence is lossy. In reality, lossless compression isn't necessary. As long as your quantisation isn't completely up the spout, the added precision isn't actually going to gain you anything unless you're working in very specialised situations; even then, if it does make a significant difference then you needed greater resolution anyway. -- Rhodri James *-* Wildebeest Herder to the Masses From andre.roberge at gmail.com Mon Aug 3 18:32:10 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 3 Aug 2009 15:32:10 -0700 (PDT) Subject: Obtaining Python version References: <4a776184$0$1611$742ec2ed@news.sonic.net> Message-ID: <680573fa-6d5a-46eb-b48e-461841b8d887@c1g2000yqi.googlegroups.com> On Aug 3, 7:19?pm, John Nagle wrote: > This works, but it seems too cute: > > ?>>> pyver = map(int,sys.version.split()[0].split('.')) > ?>>> print(pyver) > [2, 6, 1] > You can also do: >>> import sys >>> sys.version_info (2, 5, 2, 'final', 0) or >>> sys.version_info[:3] (2, 5, 2) > Is it guaranteed that the Python version string will be in a form > suitable for that? ?In other words, does "sys.version" begin > > N.N.N other stuff > > in all versions, and will it stay that way? ?Are there ever > non-numeric versions, like "3.2.rc1"? > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle I strongly suspect that sys.version_info would never change... Andr? From rt8396 at gmail.com Mon Aug 3 18:34:53 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 15:34:53 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> Message-ID: <491ed6e7-08dd-4b26-acb8-38da475491ed@b14g2000yqd.googlegroups.com> On Aug 3, 5:03?pm, cool-RR wrote: [snip] > Thanks for the compliments; The things you mentioned you liked are all > things that I was specifically thinking about when I decided to make > PythonTurtle. Well, maybe minus the screenshot :) I *may* get roasted for this comment, but i think a turtle module along the lines of what you have here would better serve the stdlib. The current implementation is great, but the whole purpose of turtle is to help children or non-programmers get a feel of the language in a very, very, simple and fun way. Your app is presented in much the same way as any over-the-counter windows app any non-programmer has seen before making them *feel* a little more comfortable. [warning wild speculations ahead!!] I just guessing here, but i'll bet many of these *noobs* have found the current turtle just a wee-bit more advanced than they can handle, and *some* have been scared off. I would also venture to say a key-map of sorts that is available thru the help menu where one could push an "Up" button, or a "rotate" button, and have the proper command inserted in the prompt, and then have the command execute, may also help make the connections here, a sort of *real* Visual Basic programming -- sorry Microsoft :P From zuo at chopin.edu.pl Mon Aug 3 18:35:50 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 04 Aug 2009 00:35:50 +0200 Subject: Obtaining Python version In-Reply-To: <4a776184$0$1611$742ec2ed@news.sonic.net> References: <4a776184$0$1611$742ec2ed@news.sonic.net> Message-ID: 04-08-2009 o 00:19:22 John Nagle wrote: > This works, but it seems too cute: > > >>> pyver = map(int,sys.version.split()[0].split('.')) > >>> print(pyver) > [2, 6, 1] > > Is it guaranteed that the Python version string will be in a form > suitable for that? In other words, does "sys.version" begin > > N.N.N other stuff > > in all versions, and will it stay that way? Are there ever > non-numeric versions, like "3.2.rc1"? Why not to use: sys.version_info "A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial. All values except releaselevel are integers; the release level is 'alpha', 'beta', 'candidate', or 'final'. The version_info value corresponding to the Python version 2.0 is (2, 0, 0, 'final', 0)." http://docs.python.org/library/sys.html#sys.version_info Cheers, *j -- Jan Kaliszewski (zuo) From keith at nekotaku.com Mon Aug 3 18:54:15 2009 From: keith at nekotaku.com (KB) Date: Mon, 3 Aug 2009 15:54:15 -0700 (PDT) Subject: Problem with reading CSV file from URL, last record truncated. Message-ID: <0996356d-ee7d-4a5e-9c0c-9f9502c01892@l5g2000pra.googlegroups.com> Hi, I am trying to download from a URL, a CSV using the following: import re import urllib, urllib2, cookielib import mechanize import csv import numpy import os def return_ranking(): cj = mechanize.MSIECookieJar(delayload=True) cj.load_from_registry() # finds cookie index file from registry # set things up for cookies opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) reply = opener.open('http://ichart.finance.yahoo.com/table.csv? s=CSCO&a=00&b=01&c=2009&d=01&e=2&f=2010&g=d&ignore=.csv').read() fout=open('csco.csv','wb') fout.write(reply) fout.close fin=open('csco.csv','rb') table = csv.reader(fin) fin.close for row in table: print row return_ranking() I need to use cookies etc (mechanize/urllib2) for a different, more complex URL but since it wasn't working, I went back to a simple Yahoo example (above) which I have working with urllib (not urllib2). The behaviour I am seeing is that the last record is being truncated: (sample output) ['2009-04-08', '17.29', '17.33', '16.94', '17.13', '45389100', '17.13'] ['2009-04-07', '17.20', '17.25', '16.58', '16.85', '59902600', '16.85'] ['200'] A friend said I should do the above writing out to a file and have csvreader read in the file, but as you can see, to no avail! Any help greatly appreciated! Note that urllib.urlretrieve works perfectly but I give up the ability to import cookies from my registry which is all important (AFAIK anyway mechanize requires urllib2). Any help greatly appreciated. From keith at nekotaku.com Mon Aug 3 19:21:02 2009 From: keith at nekotaku.com (KB) Date: Mon, 3 Aug 2009 16:21:02 -0700 (PDT) Subject: Problem with reading CSV file from URL, last record truncated. References: <0996356d-ee7d-4a5e-9c0c-9f9502c01892@l5g2000pra.googlegroups.com> Message-ID: On Aug 3, 3:54?pm, KB wrote: > Hi, > > I am trying to download from a URL, a CSV using the following: > > import re > import urllib, urllib2, cookielib > import mechanize > import csv > import numpy > import os > > def return_ranking(): > > ? ? ? ? cj = mechanize.MSIECookieJar(delayload=True) > ? ? ? ? cj.load_from_registry() ?# finds cookie index file from registry > > ? ? ? ? # set things up for cookies > > ? ? ? ? opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > > ? ? ? ? urllib2.install_opener(opener) > > ? ? ? ? reply = opener.open('http://ichart.finance.yahoo.com/table.csv? > s=CSCO&a=00&b=01&c=2009&d=01&e=2&f=2010&g=d&ignore=.csv').read() > > ? ? ? ? fout=open('csco.csv','wb') > ? ? ? ? fout.write(reply) > ? ? ? ? fout.close > > > return_ranking() > > I need to use cookies etc (mechanize/urllib2) for a different, more > complex URL but since it wasn't working, I went back to a simple Yahoo > example (above) which I have working with urllib (not urllib2). > > The behaviour I am seeing is that the last record is being truncated: > > (sample output) > ['2009-04-08', '17.29', '17.33', '16.94', '17.13', '45389100', > '17.13'] > ['2009-04-07', '17.20', '17.25', '16.58', '16.85', '59902600', > '16.85'] > ['200'] > > A friend said I should do the above writing out to a file and have > csvreader read in the file, but as you can see, to no avail! > > Any help greatly appreciated! Note that urllib.urlretrieve works > perfectly but I give up the ability to import cookies from my registry > which is all important (AFAIK anyway mechanize requires urllib2). > > Any help greatly appreciated. By moving: > fin=open('csco.csv','rb') > table = csv.reader(fin) > fin.close > > for row in table: > print row outside of the routine and into the mainline, it works like a charm. Would like to know why though, so would love to hear any clues! From piet at cs.uu.nl Mon Aug 3 19:26:58 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 04 Aug 2009 01:26:58 +0200 Subject: Executing remote command with paramiko References: Message-ID: >>>>> Hussein B (HB) wrote: >HB> Hey, >HB> I'm trying to run a sudo guarded command over SSH using paramiko >HB> +++++++++++++++++++ >HB> s = paramiko.SSHClient() >HB> s.load_system_host_keys() >HB> s.connect(hostname, port, username, passwd) >HB> stdin, stdout, stderr = s.exec_command('sudo -s') >HB> stdin.write('password\n') >HB> stdin.flush() >HB> print 'Flushing' >HB> stdin, stdout, stderr = s.exec_command('harvester') >HB> print stdout.read() >HB> s.close() >HB> +++++++++++++++++++ >HB> It seems to me that the sudo -s isn't getting executed at all. >HB> I commented the sudo -s code lines and no error is shown. >HB> Thanks for help and time. Your command 'harvester' is not run in the sudo shell, but separately in a new session. so it will run under 'username', not under 'root'. You could use stdin, stdout, stderr = s.exec_command('sudo harvester') instead. Or use the lower-level constructs: s = paramiko.SSHClient() s.load_system_host_keys() s.connect(hostname, port, username, password) t = s.get_transport() chan = t.open_session() chan.exec_command('sudo -s') print 'writing password' chan.send(password + '\n') print 'write command' chan.send('whoami\n') print "try to read" print chan.recv(9999) For more control you can use chan.recv_ready() to see if output is available. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From greg at cosc.canterbury.ac.nz Mon Aug 3 19:35:12 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 04 Aug 2009 11:35:12 +1200 Subject: Help understanding the decisions *behind* python? In-Reply-To: <4a7715ff$0$1641$742ec2ed@news.sonic.net> References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> <4a7715ff$0$1641$742ec2ed@news.sonic.net> Message-ID: <7dpagaF2cu16mU1@mid.individual.net> John Nagle wrote: > Mesa used tuples for subroutine arguments in a very straightforward > way. Every function took one tuple as an argument > > Python doesn't go that far. I believe that a very early version of Python did do something like that, but it was found to be a bad idea, because there was an ambiguity between multiple args and a single arg that happened to be a tuple. This was before keyword arguments existed -- they would have been hard to incorporate into the old scheme. -- Greg From rt8396 at gmail.com Mon Aug 3 19:39:25 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 16:39:25 -0700 (PDT) Subject: no-clobber dicts? References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: <1d95f706-71f4-487e-a920-a31643b76c10@w6g2000yqw.googlegroups.com> On Aug 3, 5:00?pm, Chris Rebert wrote: > On Mon, Aug 3, 2009 at 2:47 PM, r wrote: [snip] > > Not sure if something like this already exists, but it would be > > trivial to implement by overriding dict.__setitem__() > > That is, if you don't care about .update() not preserving the > invariant. Otherwise, one will need to look at the UserDict module. > > Cheers, > Chris > --http://blog.rebertia.com Good catch Chris. However since the OP said this was for testing purposes, i just *assumed* he would be smart enough *not* to call update() on the dict at hand ;-). But sometimes i need to be protected from myself too -- at least thats what my therapist keeps telling me :-) From greg at cosc.canterbury.ac.nz Mon Aug 3 19:40:06 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 04 Aug 2009 11:40:06 +1200 Subject: fast video encoding In-Reply-To: References: <570097d0-2b2a-4705-892f-0d0154d69d63@b14g2000yqd.googlegroups.com> <0c8cfac7-0a70-4e1f-90ec-19e9c45cae89@h21g2000yqa.googlegroups.com> Message-ID: <7dpapgF2ckro4U1@mid.individual.net> Rhodri James wrote: > Unfortunately, water pixels change a lot from frame to frame, even > when the camera is static, so it doesn't gain you as much as you might > hope in cases like you mention. In the case mentioned, the water is of no interest, so it could be removed altogether by a suitable custom compressor. -- Greg From python at mrabarnett.plus.com Mon Aug 3 19:47:23 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Aug 2009 00:47:23 +0100 Subject: Problem with reading CSV file from URL, last record truncated. In-Reply-To: References: <0996356d-ee7d-4a5e-9c0c-9f9502c01892@l5g2000pra.googlegroups.com> Message-ID: <4A77770B.2070008@mrabarnett.plus.com> KB wrote: > On Aug 3, 3:54 pm, KB wrote: >> Hi, >> >> I am trying to download from a URL, a CSV using the following: >> >> import re >> import urllib, urllib2, cookielib >> import mechanize >> import csv >> import numpy >> import os >> >> def return_ranking(): >> >> cj = mechanize.MSIECookieJar(delayload=True) >> cj.load_from_registry() # finds cookie index file from registry >> >> # set things up for cookies >> >> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) >> >> urllib2.install_opener(opener) >> >> reply = opener.open('http://ichart.finance.yahoo.com/table.csv? >> s=CSCO&a=00&b=01&c=2009&d=01&e=2&f=2010&g=d&ignore=.csv').read() >> >> fout=open('csco.csv','wb') >> fout.write(reply) >> fout.close This should be: fout.close() >> > >> return_ranking() >> [snip] > By moving: >> fin=open('csco.csv','rb') >> table = csv.reader(fin) >> fin.close This should be: fin.close() >> >> for row in table: >> print row > > outside of the routine and into the mainline, it works like a charm. > > Would like to know why though, so would love to hear any clues! > The parentheses aren't optional; without them you're just referring to the method, not calling it. Because you weren't closing the file the text wasn't all written to disk. When it returns from return_ranking() there's no longer any reference to 'fout', so the file object is available for collection by the garbage collector. When the file object is collected it writes the remaining text to disk. In CPython the file object is collected as soon as there's no reference to it, but in other implementations that might not be the case. From mensanator at aol.com Mon Aug 3 20:32:03 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Aug 2009 17:32:03 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: On Aug 3, 8:18?am, cool-RR wrote: > Hello, > > I wanted to announce that I have just released my little side project, > PythonTurtle. > Here is its website:http://pythonturtle.com > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > You can read more about it and download it on the website. I dunno, looks kind of worthless to me. http://www.mensanator.com/mensanator/PythonTurtle/PythonTurtle.htm > > Ram. From van.lindberg at gmail.com Mon Aug 3 20:42:14 2009 From: van.lindberg at gmail.com (VanL) Date: Mon, 03 Aug 2009 19:42:14 -0500 Subject: Extracting text from html Message-ID: Hello all, Does anyone know of a good tool to get a minimally-formatted text document out of an html document? Something along the lines of what you would get with a lynx -dump, but in Python. I have lxml installed, so I can roll my own if I need to. However, this seemed like the sort of thing that someone would have solved already. Thanks, Van From gagsl-py2 at yahoo.com.ar Mon Aug 3 20:42:47 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 21:42:47 -0300 Subject: Python configuration question when python scripts are executed using Appweb as web server. References: Message-ID: En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife escribi?: > I have installed python 2.6.2 in windows xp professional machine. I > have set the following environment variables -- PYTHONPATH. It points > to following windows folders: python root folder, the lib folder and > lib-tk folder. Why? Did you read it somewhere? Usually there is no need to set the PYTHONPATH variable at all; remove it. > I have configured IIS to execute python scripts. > > I do not have any issues executing python scripts from the python > interpreter window or from the browser using IIS as the web server. Try again after PYTHONPATH is removed, and make sure you can import all the required modules from the Python console. Only then try to run the cgi scripts. > However, when I use the open source Appweb web browser to execute > python scripts. It is able to execute only simple script without > issues. [...]However I am not able to execute python scripts that > contain import > statements. I need to point out here that i do not have issue with > using os or sys packages. When I tried to execute the sample client > script that came with the gnutls wrapper for python, I got error. I > narrowed it down to the "from ... import" line in the example. > > from gnutls.crypto import * > from gnutls.connection import * Check that the above lines work fine from inside the Python console. If not, something went wrong when you installed the gnutls Python package. > Next step, in order to debug, I used the module finder to see what is > happening. To being with I used the module finder to find out the > modules loaded for the simple script hello.py. Debugging cgi scripts isn't easy sometimes; try adding this line at the start of your script: import cgitb;cgitb.enable() You should get a nicely formatted stack trace whenever an exception is raised. If you get an HTTP error instead (like 500 Internal Server Error) it's likely a syntax error, you must fix it before continuing. Then, you may find that modulefinder is no more needed. > import pdb > pdb.set_trace() pdb cannot work inside a CGI script; remove that. > Once again, let me stress that this issue is happening only when I use > appweb as the web server. I don't know appweb, but if you first make sure the script works from the command line, it should be much easier to make it work in the web server. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Aug 3 21:10:57 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 22:10:57 -0300 Subject: easy_install: unresolved external symbol References: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> Message-ID: En Mon, 03 Aug 2009 17:39:44 -0300, Bart Smeets escribi?: > I keep getting errors when trying to use easy_install to install > bbfreeze or > cxfreeze (same errors). > This is the output: > http://pastebin.com/m65ba474d Can't you use the binary packages? -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Aug 3 21:18:08 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 22:18:08 -0300 Subject: Ordering of dict keys & values References: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> Message-ID: En Mon, 03 Aug 2009 17:47:23 -0300, Wells Oliver escribi?: > I understand that the keys in a dictionary are ordered not randomly but > something practically close to it, but if I create a SQL query like so: > > query = 'INSERT INTO Batting (%s) VALUES(%s)' % (','.join(stats.keys()), > ','.join(stats.values())) > > Can I at least rely on the value being in the same index as its > corresponding key? You already got the answer you wanted, but note that building a SQL statement that way is unsafe [1]. I prefer this way: query= 'INSERT INTO Batting (%s) VALUES(%s)' % ( ','.join(stats.keys()), ','.join(['?']*len(stats))) cursor.execute(query, stats.values()) [1] If you don't know what "SQL injection" means, see http://xkcd.com/327/ -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Aug 3 21:39:50 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 22:39:50 -0300 Subject: Is python buffer overflow proof? References: Message-ID: En Mon, 03 Aug 2009 18:04:53 -0300, sturlamolden escribi?: > On 2 Aug, 15:50, Jizzai wrote: > >> Is a _pure_ python program buffer overflow proof? >> >> For example in C++ you can declare a char[9] to hold user input. >> If the user inputs 10+ chars a buffer overflow occurs. > > Short answer: NO > > Bounds checking on sequence types is a protection against buffer > overflow, but is certainly not sufficient. > > The Python interpreter is written in C. Python extension modules are > written in C (or something similar). If you find an unprotected buffer > in this C code, you can possibly overflow this buffer. This can be > used for nasty things like corrupting the stack and injecting > malicious code. There is a reason why the Python sandbox (rexec and > Bastion modules) was disabled in Python 2.3. (I think the reason rexec and bastion were disabled has nothing to do with the possibility of buffer overflows in extension modules) > IronPython and Jython provides better protection against buffer > overflow than CPython, as these interpreters are written in safer > languages (C# and Java). You thus get an extra layer of protection > between the Python code and the unsafe C (used in JVM and .NET > runtimes). I disagree. You've just translated the responsability to check for buffer overflows, from the Python VM, to the Java VM or the .Net runtime (and all three suffered from buffer overruns and other problems in some way or another). Also, Python extensions written in C are equivalent to using JNI in Java or unmanaged code in C#: all three are likely to have hidden problems. It's always the same story: a *language* may declare that such things are impossible, but a particular *implementation* may have bugs and fail to comply with the specification. -- Gabriel Genellina From cocobear.cn at gmail.com Mon Aug 3 21:44:49 2009 From: cocobear.cn at gmail.com (cocobear) Date: Mon, 3 Aug 2009 18:44:49 -0700 (PDT) Subject: merge two png pic References: Message-ID: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> On Jul 31, 2:52?pm, Peter Otten <__pete... at web.de> wrote: > cocobear wrote: > > On Jul 29, 9:20 am, cocobear wrote: > >> Thistwopngfile has their own palette > > >> >>> im1.mode > >> 'P' > >> >>> im.mode > >> 'P' > >> >>> im.getpalette == im1.getpalette > > >> False > > >> I can use this code tomergetwopngpictogether: > > >> Map = Image.new("RGB", (x,y)) > >> Map.paste(im, box) > >> Map.paste(im1,box) > > >> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE) > > >> But if thetwopngpicis too big , or if I have tomergemorepic > >> together, I will get MemoryError: > > >> >>> Image.new("RGB",(44544,38656)) > > As a workaround you could split the image into tiles that fit into your > machine's RAM. Or you could try to do the rendering on a 64-bit system. > You'll need at least > > >>> 3*44544*38656./(2**30) > > 4.8109130859375 > > 5 gigabytes for the target image plus memory for the biggest source image. > Alternatively there are probably tools that can keep parts of the image on > disk (imagemagick, maybe? you'll have to check yourself or ask in a > specialized forum). As a last resort you should be able to write such a tool > yourself. I don't know how hard it would be to generate the PNG, but the RGB > pasting should be trivial. > Thanks for you reply. Map = Image.new("RGB", ((x2-x1+1)*256, (y2-y1+1)*256)) for x in range(x1,x2+1): for y in range(y1,y2+1): #print x,y filename = "v=cn1.11&hl=zh-CN&x=%d&y=%d&z=%d&s=Galile" % (x,y,z) # box = ((x-x1)*256, (y-y1)*256, (x-x1)*256+256, (y-y1) *256+256) #print box im = Image.open(filename+".png") Map.paste(im, box) temp = "temp_map.png" Map.save(temp) del Map print "converting" Map = Image.open(temp) Map = Map.convert("P", palette=Image.ADAPTIVE) Now I use code above, the problem is when I create a RGB image, I need four times spaces then a 'P' mode image. Can I directly create a 'P' mode image, and paste those images on? (NOTICE: this small image has different palette) > >> Traceback (most recent call last): > >> File "", line 1, in > >> File "/usr/lib/python2.5/site-packages/PIL/Image.py", line 1710, in > >> new > >> return Image()._new(core.fill(mode, size, color)) > >> MemoryError > > >> How can I directlymergetwopicto a ?P' modepngwith palette. > > > Nobody replied. > > What do you want to do with such a big image? You will run into the same > limitation when you are trying to display it. > I want to download a map from google map with high precision > Peter From afriere at yahoo.co.uk Mon Aug 3 21:53:02 2009 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 3 Aug 2009 18:53:02 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> Message-ID: <1d144bd0-8829-4449-8935-60bf6f66a5d6@l5g2000pra.googlegroups.com> On Aug 4, 6:35?am, r wrote: [snip] > > I can remember the first time i used turtle (in python stdlib) and i > kept saying to myself... > > ? ? "Were the heck is this damn turtle?!?!" (>_<) > > :-) In Python2.6, try this: >>> turtle.shape('turtle') From benjamin.kaplan at case.edu Mon Aug 3 22:15:03 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 3 Aug 2009 22:15:03 -0400 Subject: [OT] Re: Ordering of dict keys & values In-Reply-To: References: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> Message-ID: On Mon, Aug 3, 2009 at 9:18 PM, Gabriel Genellina wrote: > > [1] If you don't know what "SQL injection" means, see http://xkcd.com/327/ I love how XKCD is one of the preferred learning tools (along with Wikipeida) for people on this list. I think Randall Munroe should make a comic about it. :) From justin.mailinglists at gmail.com Mon Aug 3 22:32:22 2009 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Mon, 3 Aug 2009 19:32:22 -0700 (PDT) Subject: Extracting text from html References: Message-ID: <44201d0e-87fe-457e-a7e2-26b2c5027d76@b25g2000prb.googlegroups.com> http://tinyurl.com/kpoweq From fft1976 at gmail.com Mon Aug 3 22:51:36 2009 From: fft1976 at gmail.com (fft1976) Date: Mon, 3 Aug 2009 19:51:36 -0700 (PDT) Subject: RUBY vs COMMON LISP References: <389503e4-eb6a-48c2-af76-cebe1dc7141c@h30g2000vbr.googlegroups.com> <87my6ic1k5.fsf@galatea.local> <1a40c8fe-83e4-4c50-90e2-b72ef86a6ac4@m7g2000prd.googlegroups.com> <87hbwp9umw.fsf@galatea.local> Message-ID: <04aef600-150d-44fa-a0cd-d88a4b17e836@m7g2000prd.googlegroups.com> On Aug 3, 1:19?am, p... at informatimago.com (Pascal J. Bourguignon) wrote: > fft1976 writes: > > By the way, here is in 1 line of BF, a complete BF reader that is able > > to > > read all the BF syntax needed to write it: > > > ,+[-.,+] > > > Here's how to try it: > > > $ sudo apt-get install bf > > $ cat > reader.bf > > ,+[-.,+] > > $ bf reader.bf < reader.bf > > > Your 150 lines don't look very impressive now, do they? > > > Ruby < Lisp <<< BF! > > I specified a syntactic reader. ?Not just a reader. It is a syntactic reader. BF's syntax is just a sequence of characters. If you throw in illegal characters, the behavior is "undefined". Lisp's syntax is more complicated: it's a tree of identifiers (in its idealized form; of course, Common Lisp had to fuck it up). Ruby's and Python's syntaxes are even more complicated. The above was to illustrate the wrongness of your argument that the length of a self-parser determines the usefulness of the language. Hell, I know that BF can be a little *too* awesome. By the way, Python's syntax is much better than Ruby's. Dollar signs in front of variables? WTF were the designers smoking? That's like Perl! Haven't you learned your lesson? Python's syntax might even be better than Lisp's, but it's certainly harder to parse. From pavlovevidence at gmail.com Mon Aug 3 23:00:08 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Aug 2009 20:00:08 -0700 (PDT) Subject: Seeding the rand() Generator References: Message-ID: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> On Aug 3, 8:12?pm, Fred Atkinson wrote: > On Sun, 2 Aug 2009 17:00:40 -0700 (PDT), Carl Banks > > wrote: > > ? ? ? ? I appreciate the response. ? > > ? ? ? ? I am executing a statement to retrieve one record at random. ? > > ? ? ? ? An example would be: SELECT first, second, third, fourth, > fifth, sixth from sometable order by rand() limit 1 > > ? ? ? ? It would be contained as: stmt = "SELECT first, second, third, > fourth, fifth, sixth from sometable order by rand() limit 1" > > ? ? ? ? Then I would execute it with the command: cursor.execute(stmt) > > ? ? ? ? How would I correctly seed the random generator in the MySQL > statement from within Python? ? You apparently know how to run MySQL statements from Python, correct? You also apparently know how to run a particular MySQL statement from PHP that seeds the random number generator, correct? Given those two apparent facts, you should be able run whatever statement you ran in PHP to seed the RNG in Python. So I don't see what the problem is. Your question is a MySQL question, not a Python question. I don't know off hand how to seed the RNG in MySQL, and, since this is a Python group and not a MySQL group, I don't care to look it up. But if you were able to produce the MySQL statement in PHP that does it you shouldn't need to ask. If you don't "get" why this is a MySQL question and not a Python question, then you need to learn more about what you are doing. Carl Banks From davea at ieee.org Mon Aug 3 23:00:13 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Aug 2009 23:00:13 -0400 Subject: Newbie Question regarding __init__() In-Reply-To: <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> Message-ID: <4A77A43D.4000709@ieee.org> Simon wrote: > On Aug 2, 5:51 am, Dave Angel wrote: > >> >> I don't understand your comparison to Foxpro. read on. >> >> As your code was last posted, you don't need a return value from >> init_Exec() Every function that doesn't have an explicit return will >> return None. And None is interpreted as False in an "and" expression. >> If you had an "if" around the whole thing, then you'd care. >> >> DaveA >> > > All I meant by the FoxPro comment was the idea of using the equal sign > without a variable to throw away the result. Also in FoxPro there is > no such thing as automatically returning None. If there is no > explicit return then True is returned. > > Thanks I did not know that None is interpreted as False. > > Simon > > > To throw away the result of an expression in Python is even easier. Just don't use it. func1() and func2() is a valid expression whose result is not used. And func2()'s result is therefore irrelevant. But shortcircuiting means that func2() is only called if func1() returned False (or something equivalent to it, like 0 or an empty list) From pavlovevidence at gmail.com Mon Aug 3 23:02:26 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Aug 2009 20:02:26 -0700 (PDT) Subject: RUBY vs COMMON LISP References: <389503e4-eb6a-48c2-af76-cebe1dc7141c@h30g2000vbr.googlegroups.com> <87my6ic1k5.fsf@galatea.local> <1a40c8fe-83e4-4c50-90e2-b72ef86a6ac4@m7g2000prd.googlegroups.com> <87hbwp9umw.fsf@galatea.local> <04aef600-150d-44fa-a0cd-d88a4b17e836@m7g2000prd.googlegroups.com> Message-ID: <3755ae21-b7b0-4f82-99d4-1095ec953c39@s6g2000vbp.googlegroups.com> On Aug 3, 7:51?pm, fft1976 wrote: > On Aug 3, 1:19?am, p... at informatimago.com (Pascal J. Bourguignon) > wrote: > > > > > > > fft1976 writes: > > > By the way, here is in 1 line of BF, a complete BF reader that is able > > > to > > > read all the BF syntax needed to write it: > > > > ,+[-.,+] > > > > Here's how to try it: > > > > $ sudo apt-get install bf > > > $ cat > reader.bf > > > ,+[-.,+] > > > $ bf reader.bf < reader.bf > > > > Your 150 lines don't look very impressive now, do they? > > > > Ruby < Lisp <<< BF! > > > I specified a syntactic reader. ?Not just a reader. > > It is a syntactic reader. BF's syntax is just a sequence of > characters. If you throw in illegal characters, the behavior is > "undefined". Lisp's syntax is more complicated: it's a tree of > identifiers (in its idealized form; of course, Common Lisp had to fuck > it up). Ruby's and Python's syntaxes are even more complicated. > > The above was to illustrate the wrongness of your argument that the > length of a self-parser determines the usefulness of the language. > Hell, I know that BF can be a little *too* awesome. > > By the way, Python's syntax is much better than Ruby's. Dollar signs > in front of variables? WTF were the designers smoking? That's like > Perl! Haven't you learned your lesson? > > Python's syntax might even be better than Lisp's, but it's certainly > harder to parse.- Hide quoted text - Go away, troll. [This is cross-posted; I recommend that no one else follow up.] Carl Banks From fft1976 at gmail.com Mon Aug 3 23:06:58 2009 From: fft1976 at gmail.com (fft1976) Date: Mon, 3 Aug 2009 20:06:58 -0700 (PDT) Subject: RUBY vs COMMON LISP References: <389503e4-eb6a-48c2-af76-cebe1dc7141c@h30g2000vbr.googlegroups.com> <87my6ic1k5.fsf@galatea.local> <1a40c8fe-83e4-4c50-90e2-b72ef86a6ac4@m7g2000prd.googlegroups.com> <87hbwp9umw.fsf@galatea.local> <04aef600-150d-44fa-a0cd-d88a4b17e836@m7g2000prd.googlegroups.com> <3755ae21-b7b0-4f82-99d4-1095ec953c39@s6g2000vbp.googlegroups.com> Message-ID: On Aug 3, 8:02?pm, Carl Banks wrote: > On Aug 3, 7:51?pm, fft1976 wrote: > > > > > On Aug 3, 1:19?am, p... at informatimago.com (Pascal J. Bourguignon) > > wrote: > > > > fft1976 writes: > > > > By the way, here is in 1 line of BF, a complete BF reader that is able > > > > to > > > > read all the BF syntax needed to write it: > > > > > ,+[-.,+] > > > > > Here's how to try it: > > > > > $ sudo apt-get install bf > > > > $ cat > reader.bf > > > > ,+[-.,+] > > > > $ bf reader.bf < reader.bf > > > > > Your 150 lines don't look very impressive now, do they? > > > > > Ruby < Lisp <<< BF! > > > > I specified a syntactic reader. ?Not just a reader. > > > It is a syntactic reader. BF's syntax is just a sequence of > > characters. If you throw in illegal characters, the behavior is > > "undefined". Lisp's syntax is more complicated: it's a tree of > > identifiers (in its idealized form; of course, Common Lisp had to fuck > > it up). Ruby's and Python's syntaxes are even more complicated. > > > The above was to illustrate the wrongness of your argument that the > > length of a self-parser determines the usefulness of the language. > > Hell, I know that BF can be a little *too* awesome. > > > By the way, Python's syntax is much better than Ruby's. Dollar signs > > in front of variables? WTF were the designers smoking? That's like > > Perl! Haven't you learned your lesson? > > > Python's syntax might even be better than Lisp's, but it's certainly > > harder to parse.- Hide quoted text - > > Go away, troll. > > [This is cross-posted; I recommend that no one else follow up.] > > Carl Banks Lispers were having fun badmouthing other languages for no good reason: """ Don't you realize how ugly Ruby syntax is? Here is in 150 lines of lisp, a simplified lisp reader that is able to read all the lisp syntax needed to write it. Try to parse Ruby syntax in Ruby and see how useless a language it is. """ http://groups.google.com/group/comp.lang.lisp/msg/52dde974d504ad54 Of course you don't like it when I point out just how wrong you are. From fatkinson at mishmash.com Mon Aug 3 23:12:49 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Mon, 03 Aug 2009 20:12:49 -0700 Subject: Seeding the rand() Generator References: Message-ID: On Sun, 2 Aug 2009 17:00:40 -0700 (PDT), Carl Banks wrote: I appreciate the response. I am executing a statement to retrieve one record at random. An example would be: SELECT first, second, third, fourth, fifth, sixth from sometable order by rand() limit 1 It would be contained as: stmt = "SELECT first, second, third, fourth, fifth, sixth from sometable order by rand() limit 1" Then I would execute it with the command: cursor.execute(stmt) How would I correctly seed the random generator in the MySQL statement from within Python? Regards, Fred From steven at REMOVE.THIS.cybersource.com.au Mon Aug 3 23:23:20 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 03:23:20 GMT Subject: no-clobber dicts? References: Message-ID: On Mon, 03 Aug 2009 21:07:32 +0000, kj wrote: > I use the term "no-clobber dict" to refer to a dictionary D with the > especial property that if K is in D, then > > D[K] = V > > will raise an exception unless V == D[K]. In other words, D[K] can be > set if K doesn't exist already among D's keys, or if the assigned value > is equal to the current value of D[K]. All other assignments to D[K] > trigger an exception. Coincidentally, I just built something very close to what you ask. Here it is: class ConstantNamespace(dict): """Dictionary with write-once keys.""" def __delitem__(self, key): raise TypeError("can't unbind constants") def __setitem__(self, key, value): if key in self: raise TypeError("can't rebind constants") super(ConstantNamespace, self).__setitem__(key, value) def clear(self): raise TypeError('cannot unbind constants') def pop(self, key, *args): raise TypeError("cannot pop constants") def popitem(self): raise TypeError("cannot pop constants") def update(self, other): for key in other: if key in self: raise TypeError('cannot update constants') # If we get here, then we're not modifying anything, # so okay to proceed. super(ConstantNamespace, self).update(other) def copy(self): c = self.__class__(**self) return c I also have a series of unit tests for it if you're interested in them. -- Steven From davea at ieee.org Mon Aug 3 23:23:38 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Aug 2009 23:23:38 -0400 Subject: file comparison In-Reply-To: <29a34bc20908031748j11280ab0mb4303da4156db54b@mail.gmail.com> References: <29a34bc20907310225n50b35fe2m322872af2058a465@mail.gmail.com> <200907311247.30793.hendrik@microcorp.co.za> <4A72E9BF.3080808@ieee.org> <29a34bc20908031748j11280ab0mb4303da4156db54b@mail.gmail.com> Message-ID: <4A77A9BA.4090104@ieee.org> learner learner wrote: > Firstly thanks for showing the interest. I shall elobarate more on the > problem: > > file-1.txt > -------------- > hai > how > r > u > > file-2.txt > --------------- > r > hai > u > > > The two files have some lines in common. > > For eg: File-1.txt-first line-"hai" does not match with File-2.txt-first > line-"r" but surely matches with File-2.txt -second > > line -"hai". On having an iterative search the file-1.txt should finally be > left out with mismatched string "how", which is > > to be dumped into a third file say file3.txt or rewritten to > file-1.txt/file-2.txt with this single word "how" in line 1. > > some facts to remember: > ------------------------ > > the srings in the files will be same including case sentiveness if at all > present, else will be pronounced as a mismatch. > > this is bascically an iterative string search amongst the files and > isolating the mismatched strings into a text file > > (By replying off-list, you are ignoring the intent of public mailing lists. So I'm copying your message to the list, along with my response.) As I said before: If the text files are each a list of items, with order and duplication irrelevant, then your best bet is probably to build a set from each, and difference the sets. Sets are case-sensitive, and your example above indicates that order is at least partially irrelevant to you. So read each file, converting the lines into a set. Then do a set difference of those two sets. Then build a list from the result, and write that to a file. If it doesn't work, post the code you tried, along with sample data and expected output for that sample data. DaveA From steven at REMOVE.THIS.cybersource.com.au Mon Aug 3 23:30:35 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 03:30:35 GMT Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: On Mon, 03 Aug 2009 16:38:43 +0200, Jean-Michel Pichavant wrote: > So what's the purpose of making > >>from Module import factory as a >>from Module import factory as b > > return 2 different objects ? If I had to write this code I would expect > 'a is b' to return 'True'. > > This is no "don't do that" answer, it's a sincere question: what is the > benefit of your /new/ syntax ? Consider it "properties for modules": a = obj.factory b = obj.factory doesn't promise that a is b, because factory might be a property that returns a new object each time. Actually, this behaviour pre-dates properties. If obj has a __getattr__ or __getattribute__ method, then it could do the same thing. -- Steven From steven at REMOVE.THIS.cybersource.com.au Mon Aug 3 23:44:54 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 03:44:54 GMT Subject: Is python buffer overflow proof? References: Message-ID: On Mon, 03 Aug 2009 14:04:53 -0700, sturlamolden wrote: > On 2 Aug, 15:50, Jizzai wrote: > >> Is a _pure_ python program buffer overflow proof? >> >> For example in C++ you can declare a char[9] to hold user input. If the >> user inputs 10+ chars a buffer overflow occurs. > > Short answer: NO > > Bounds checking on sequence types is a protection against buffer > overflow, but is certainly not sufficient. > > The Python interpreter is written in C. Python extension modules are > written in C (or something similar). If you find an unprotected buffer > in this C code, you can possibly overflow this buffer. How are C extension modules "_pure_ python"? -- Steven From thangappan143 at gmail.com Mon Aug 3 23:45:47 2009 From: thangappan143 at gmail.com (Thangappan.M) Date: Tue, 4 Aug 2009 09:15:47 +0530 Subject: Problem in installing PyGreSQL Message-ID: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> Dear all, I want to access the database related stuffs in python.So I found the PyGreSQL module in net. Then I tried to download the module.But I am not able to download it. I am not a super user. I am using Linux debian machine Python version is 2.4.4 -- Regards, Thangappan.M -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Tue Aug 4 00:06:15 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 04:06:15 GMT Subject: kw param question References: Message-ID: On Mon, 03 Aug 2009 19:59:23 +0000, kj wrote: > I want to write a decorator that, among other things, returns a function > that has one additional keyword parameter, say foo=None. > > When I try > > def my_decorator(f): > # blah, blah > def wrapper(*p, foo=None, **kw): > x = f(*p, **kw) > if (foo): > # blah, blah > else > # blah blah > return wrapper > > ...i get a syntax error where it says "foo=None". I get similar errors > with everything else I've tried. > > Is is possible to do this in Python? Have you tried this under Python 2.6 or 3.0? I've run into similar issues, because you can't have keyword-only arguments in Python 2.5 :( My solution was to create a decorator that faked them. The docstring is longer than the decorator itself. from functools import wraps def keywords(**defaults): """Return a decorator which decorates a function to accept keyword arguments. Python 2.5 and earlier don't allow keyword-only arguments for non-builtin functions. The obvious syntax: def func(x, *args, key=None, word='parrot'): is not permitted. As a work-around, write your function something like the following example: >>> @keywords(key=None, word='parrot') ... def func(x, y=0, *args, **kwargs): ... # Inside the function, we can guarantee that kwargs['key'] and ... # kwargs['word'] both exist, and no other keys. ... print "x=%s, y=%s, args=%s" % (x, y, args) ... if kwargs['key'] is None: msg = "kwargs['key'] is None" ... else: msg = "kwargs['key'] is something else" ... msg += " and kwargs['word'] is %r" % kwargs['word'] ... print msg ... When you call func, if you don't provide a keyword-only argument, the default will be substituted: >>> func(1, 2, 3, 4) x=1, y=2, args=(3, 4) kwargs['key'] is None and kwargs['word'] is 'parrot' >>> func(1) x=1, y=0, args=() kwargs['key'] is None and kwargs['word'] is 'parrot' Naturally you can provide your own values for keyword-only arguments: >>> func(1, 2, 3, word='spam') x=1, y=2, args=(3,) kwargs['key'] is None and kwargs['word'] is 'spam' >>> func(1, 2, 3, word='spam', key=len) x=1, y=2, args=(3,) kwargs['key'] is something else and kwargs['word'] is 'spam' If you pass an unexpected keyword argument, TypeError is raised: >>> #doctest:+IGNORE_EXCEPTION_DETAIL ... func(1, 2, 3, 4, keyword='something') Traceback (most recent call last): ... TypeError: ... """ def decorator(func): """Decorate func to allow keyword-only arguments.""" @wraps(func) def f(*args, **kwargs): for key in kwargs: if key not in defaults: raise TypeError( "'%s' is an invalid keyword argument for " \ "this function" % key ) d = defaults.copy() d.update(kwargs) return func(*args, **d) return f return decorator (Copy and pasted from working code, but I make no guarantee that it will have survived the process in working order!) -- Steven From rt8396 at gmail.com Tue Aug 4 00:08:52 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 21:08:52 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> <1d144bd0-8829-4449-8935-60bf6f66a5d6@l5g2000pra.googlegroups.com> Message-ID: <02ad1097-bf09-4980-8d1d-18cdbf50cb5a@24g2000yqm.googlegroups.com> On Aug 3, 8:53?pm, Asun Friere wrote: > On Aug 4, 6:35?am, r wrote: > > [snip] > > > > > I can remember the first time i used turtle (in python stdlib) and i > > kept saying to myself... > > > ? ? "Were the heck is this damn turtle?!?!" (>_<) > > > :-) > > In Python2.6, try this: > > > > >>> turtle.shape('turtle') Thanks Asun, now i don't have anything to complain about! :-# From koranthala at gmail.com Tue Aug 4 00:09:05 2009 From: koranthala at gmail.com (koranthala) Date: Mon, 3 Aug 2009 21:09:05 -0700 (PDT) Subject: Which GUI framework to use? Message-ID: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> Hi, I am creating a very minimal application (a networking app). I have written the application using Twisted. Now, I need to put a GUI wrapper on the application. The application needs a login screen and also it needs to be minimized to system tray. If I right click the image on system tray, I should be able to close it. It uses some legacy code, so the whole app is written in Python 2.4. Also, my company requires that I use permissive licenses (no GPL - MIT, BSD, LGPL etc ok) Which GUI framework is best for this? I tried using Tkinter, but it does not support minimize to system tray (or I couldnt find it). This is my first foray to GUI programming, so other issues that I am worried about - 1. GUI needs a loop, Twisted needs a loop. How can both go ahead without messing each other? Thank You very much K From jjposner at optimum.net Tue Aug 4 00:12:34 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 04 Aug 2009 00:12:34 -0400 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: <4A77B532.5020906@optimum.net> > ... I would also venture to say a key-map > of sorts that is available thru the help menu where one could push an > "Up" button, or a "rotate" button, and have the proper command > inserted in the prompt, and then have the command execute, may also > help make the connections here, a sort of *real* Visual Basic > programming -- sorry Microsoft :P > Along these lines, see my "ClixTur" application at www.jjposner.net. It's a point-and-click front end to the standard Python turtle module, implementing only a very small subset of the turtle commands. As you click, the "real turtle commands" appear in a transcript window. You can then save (and maybe edit) and replay the transcript. Ram, I like a lot of what you've done. Could you talk about your decision to embed the standard turtle module (which is implemented in Tkinter) in a wxPython application? -John From philip at semanchuk.com Tue Aug 4 00:34:10 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 Aug 2009 00:34:10 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> Message-ID: <4B1B10B5-24D5-44D0-B16F-6308D8D8FAD2@semanchuk.com> On Aug 3, 2009, at 11:45 PM, Thangappan.M wrote: > Dear all, > > I want to access the database related stuffs in python.So I found the > PyGreSQL module in net. > Then I tried to download the module.But I am not able to download it. > > I am not a super user. > I am using Linux debian machine > Python version is 2.4.4 Hi Thangappan, If you want us to be able to help you, you'll need to give more information. For instance, why are you not able to download PyGreSQL? You might want to try psycopg2 which also gives you access to PostgreSQL from Python. You can download it from this site: http://initd.org/ Hope this helps Philip From http Tue Aug 4 00:34:15 2009 From: http (Paul Rubin) Date: 03 Aug 2009 21:34:15 -0700 Subject: Is python buffer overflow proof? References: Message-ID: <7x1vnsmc3c.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > The Python interpreter is written in C. Python extension modules are > > written in C (or something similar). If you find an unprotected buffer > > in this C code, you can possibly overflow this buffer. > > How are C extension modules "_pure_ python"? A lot of basic Python constructs (like numbers and dictionaries) are implemented as C extension modules. It is reasonable to consider "pure Python" to include the contents of the Python standard library. From david.lyon at preisshare.net Tue Aug 4 00:42:25 2009 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 04 Aug 2009 00:42:25 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> Message-ID: <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> On Tue, 4 Aug 2009 09:15:47 +0530, "Thangappan.M" wrote: > I want to access the database related stuffs in python.So I found the > PyGreSQL module in net. > Then I tried to download the module.But I am not able to download it. Did none of the links here work? http://www.pygresql.org/readme.html#where-to-get > I am not a super user. > I am using Linux debian machine > Python version is 2.4.4 Try building it from source. Otherwise try getting it from pypi http://pypi.python.org/pypi/PyGreSQL/ David From nagle at animats.com Tue Aug 4 01:06:06 2009 From: nagle at animats.com (John Nagle) Date: Mon, 03 Aug 2009 22:06:06 -0700 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: <4a77c0d9$0$1584$742ec2ed@news.sonic.net> Gabriel Genellina wrote: > En Mon, 03 Aug 2009 18:04:53 -0300, sturlamolden > escribi?: > >> On 2 Aug, 15:50, Jizzai wrote: >> >>> Is a _pure_ python program buffer overflow proof? >>> >>> For example in C++ you can declare a char[9] to hold user input. >>> If the user inputs 10+ chars a buffer overflow occurs. >> >> Short answer: NO > I disagree. You've just translated the responsability to check for > buffer overflows, from the Python VM, to the Java VM or the .Net runtime > (and all three suffered from buffer overruns and other problems in some > way or another). A more useful question is whether the standard libraries are being run through any of the commercial static checkers for possible buffer overflows. John Nagle From wuwei23 at gmail.com Tue Aug 4 01:33:33 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 22:33:33 -0700 (PDT) Subject: no-clobber dicts? References: Message-ID: Steven D'Aprano wrote: > I also have a series of unit tests for it if you're interested in them. That's several times today that kj has asked a question and you've responded with ready-to-go code. If this was Stackoverflow, I'd accuse you of reputation-whoring... You _can_ just post your cool code without the double act, y'know! :) From david.lyon at preisshare.net Tue Aug 4 01:55:20 2009 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 04 Aug 2009 01:55:20 -0400 Subject: Python docs disappointing - group effort to hire =?UTF-8?Q?writers=3F?= In-Reply-To: <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> References: <09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com> <109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com> <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> Message-ID: It isn't totally about the writers... Peoples egos are also at stake - it seems. If "Fred X wrote Doc Y".. they don't want their name taken off.. So they generally speaking don't want the docs changed. If you talk too much about docs.. you can be told you're OT.. even in a thread about docs... On Fri, 31 Jul 2009 17:12:43 -0700, Kee Nethery wrote: > I too find the Python docs not very useful and it really slows down my > learning curve. > > I wonder if it would make sense to find good tech writers, get a > quotes, and get some professionally written documentation WITH LOTS OF > EXAMPLES added to the standard Python documentation tree. > > I'd chip in money for that task. I've certainly spent enough buying > Python books to where it would be very reasonable to chip in the cost > of one book towards this project. Get enough people ... could be a > great thing. > > Even though it is not the version I use, I would suggest that the > really detailed docs with lots of examples be written against the > latest python version. > > Just a thought. > > Kee Nethery From steven at REMOVE.THIS.cybersource.com.au Tue Aug 4 02:09:52 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 06:09:52 GMT Subject: Is python buffer overflow proof? References: <7x1vnsmc3c.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 03 Aug 2009 21:34:15 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> > The Python interpreter is written in C. Python extension modules are >> > written in C (or something similar). If you find an unprotected >> > buffer in this C code, you can possibly overflow this buffer. >> >> How are C extension modules "_pure_ python"? > > A lot of basic Python constructs (like numbers and dictionaries) are > implemented as C extension modules. It is reasonable to consider "pure > Python" to include the contents of the Python standard library. Well, yes, but we're not saying that Python is bug-free. There could be bugs in the Python VM for that matter. The point is that code you write yourself can rely on "pure Python" to be free of buffer-overflows (for some definition of "rely") rather than having to worry about managing memory yourself. If you do this: buffer = [0]*1024 buffer[:] = [1]*1025 you don't over-write some random piece of memory, the list object resizes to accommodate, or fails with an exception instead. No special action is needed to avoid buffer overflows. You can't make that claim about C extensions. It's interesting to contrast that with DoS vulnerabilities in pure Python code. Python won't stop you from trying to calculate a googolplex: googol = 10**100 googolplex = 10**googol and doing so will be a moderately effective denial of service against your Python application. If you're concerned with that, you need to code defensively in the Python layer. Protecting against time-consuming operations is not part of Python's design. -- Steven From wuwei23 at gmail.com Tue Aug 4 02:21:20 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 23:21:20 -0700 (PDT) Subject: Python docs disappointing - group effort to hire writers? References: <09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com> <109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com> <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> Message-ID: <95ea30c4-a5e5-458e-a8e4-4398c376e52d@13g2000prl.googlegroups.com> On Aug 4, 3:55?pm, David Lyon wrote: > It isn't totally about the writers... > Peoples egos are also at stake - it seems. Citation please. > If "Fred X wrote Doc Y".. they don't want their name taken off.. So > they generally speaking don't want the docs changed. Ditto. > If you talk too much about docs.. you can be told you're OT.. > even in a thread about docs... And again. All I've _ever_ seen (on this group at least) is the much repeated phrase "All patches to the docs are welcomed". If you'd like to cast aspersions on the characters of those doing the work over actually contributing yourself, you're certainly free to do so, just don't expect your claims to be taken seriously. Other people's refusal to do the work that _you_ consider to be necessary isn't "ego". From deets at nospam.web.de Tue Aug 4 02:48:31 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 04 Aug 2009 08:48:31 +0200 Subject: Which GUI framework to use? In-Reply-To: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> References: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> Message-ID: <7dq3tvF2d74reU1@mid.uni-berlin.de> koranthala schrieb: > Hi, > I am creating a very minimal application (a networking app). > I have written the application using Twisted. > Now, I need to put a GUI wrapper on the application. > The application needs a login screen and also it needs to be > minimized to system tray. If I right click the image on system tray, I > should be able to close it. > It uses some legacy code, so the whole app is written in Python > 2.4. Also, my company requires that I use permissive licenses (no GPL > - MIT, BSD, LGPL etc ok) Google this group. The discussions are abundant about this. Keep in mind that while Qt changed licenses to LGPL, PyQt didn't and thus you can't use it. > Which GUI framework is best for this? I tried using Tkinter, but it > does not support minimize to system tray (or I couldnt find it). > > This is my first foray to GUI programming, so other issues that I > am worried about - > 1. GUI needs a loop, Twisted needs a loop. How can both go ahead > without messing each other? Google is your friend here, too: http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html Diez From contact at xavierho.com Tue Aug 4 02:59:50 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 4 Aug 2009 16:59:50 +1000 Subject: Seeding the rand() Generator In-Reply-To: References: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> Message-ID: <2d56febf0908032359k4d3abf63i97bb4883a75b2a15@mail.gmail.com> On Tue, Aug 4, 2009 at 5:48 PM, Fred Atkinson wrote: > I tried using the same command I used when I did this in PHP. > That command was: mt_srand(date("w")) > > It was a PHP command that seeds the MySQL random function, > according to the folks on the PHP newsgroup. Well, some people have suggested to use that inside Python. That would work, right? Although, if you're just trying to find the Python-equivalent, fair enough. Regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From torppa at staff.megabaud.fi Tue Aug 4 03:12:30 2009 From: torppa at staff.megabaud.fi (Jarkko Torppa) Date: Tue, 04 Aug 2009 07:12:30 GMT Subject: Seeding the rand() Generator References: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> Message-ID: On 2009-08-04, Fred Atkinson wrote: > On Mon, 3 Aug 2009 20:00:08 -0700 (PDT), Carl Banks > wrote: >> >>If you don't "get" why this is a MySQL question and not a Python >>question, then you need to learn more about what you are doing. > > I wouldn't agree. > > I tried using the same command I used when I did this in PHP. > That command was: mt_srand(date("w")) > > It was a PHP command that seeds the MySQL random function, > according to the folks on the PHP newsgroup. It seems that they lied to you. Did you actually try that ? > I'm trying to figure out what the Python equivalent of that > is. Python equivalent of that is random.seed(x), if PHP docs are to be believed. > Now do you see? What you acutally want is "select *,rand(3) as rand from table order by rand" or something like that. That 3 is the seed in there. -- Jarkko Torppa From news123 at free.fr Tue Aug 4 03:24:57 2009 From: news123 at free.fr (News123) Date: Tue, 04 Aug 2009 09:24:57 +0200 Subject: merge two png pic In-Reply-To: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> References: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> Message-ID: <4a77e249$0$2449$426a74cc@news.free.fr> Hi, cocobear wrote: >> > >> Map = Image.new("RGB", (x,y)) >> > >> Map.paste(im, box) >> > >> Map.paste(im1,box) > >> > >> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE) > >> > >> But if thetwopngpicis too big , or if I have tomergemorepic >> > >> together, I will get MemoryError: > >>>>> > >> >>> Image.new("RGB",(44544,38656)) >> >> What do you want to do with such a big image? You will run into the same >> limitation when you are trying to display it. >> > > I want to download a map from google map with high precision > For me it sounds strange to handle such big files. Is the map you download from Google really that big? Mostly Google maps uses normally tiles of sizes 256x256 pixel, wich you have to compose to get the big image. If your problem is to combine tiles with different palettes, then you should pobably look at a way to 'unify' the palette of all tiles befor combining them. Being no expert of PIL I don't know whether this is easily possible though? bye N From contact at xavierho.com Tue Aug 4 03:31:29 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 4 Aug 2009 17:31:29 +1000 Subject: merge two png pic In-Reply-To: <4a77e249$0$2449$426a74cc@news.free.fr> References: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> <4a77e249$0$2449$426a74cc@news.free.fr> Message-ID: <2d56febf0908040031j2aabe2f8xa5c69be943030783@mail.gmail.com> Strange, I did reply but you didn't see it? >>>>> > >> >>> Image.new("RGB",(44544,38656)) > >> > >> What do you want to do with such a big image? You will run into the same > >> limitation when you are trying to display it. > >> > > > > I want to download a map from google map with high precision > Download several maps instead. Streaming if you have to. I'm not sure how you're going to avoid that MemoryError by trying to aggregate everything at once. Might have to make it a dynamic loader, and only load pictures as relevant (i.e: visible, and next to visible) Think how Google Maps do it. They can't possibly upload 5GB of pictures every time you access Maps - that wouldn't have worked. They work with the only visible areas. If you could tell us exactly what your program is trying to achieve, maybe we'll have a better solution for you. Best regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From lkrzysiak at gmail.com Tue Aug 4 03:33:49 2009 From: lkrzysiak at gmail.com (=?UTF-8?Q?=C5=81ukasz?=) Date: Tue, 4 Aug 2009 00:33:49 -0700 (PDT) Subject: Strange python script behaviour Message-ID: Hi, I have a problem with one of my python scripts. When I run this script from command line it works correctly, but if I set up cron to run this script on specified hour it works for a while and then "[Errno 32] Broken pipe" error occures (always). The strangest thing is that if I change command in CRON from python /home/xxx/script.py to python /home/xxx/script.py > /tmp/script.log 2>&1 the script always works correctly!!! The question is WHY? Any ideas? From electronixtar at gmail.com Tue Aug 4 03:38:27 2009 From: electronixtar at gmail.com (est) Date: Tue, 4 Aug 2009 00:38:27 -0700 (PDT) Subject: modify a exe's RT_ACCELERATOR table using pefile module Message-ID: Hi list, I need to modify a exe's RT_ACCELERATOR table, rename F1 to Ctrl+F1, and assign hotkey F1 to another function Is there a way to do it with pefile/python? A sample code is appreciated. Thanks! From ram.rachum at gmail.com Tue Aug 4 03:44:59 2009 From: ram.rachum at gmail.com (cool-RR) Date: Tue, 4 Aug 2009 00:44:59 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: <9e3b0c86-3a2a-4bc4-91f3-1b01a05d6b86@f37g2000yqn.googlegroups.com> On Aug 4, 7:12?am, John Posner wrote: > > ... I would also venture to say a key-map > > of sorts that is available thru the help menu where one could push an > > "Up" button, or a "rotate" button, and have the proper command > > inserted in the prompt, and then have the command execute, may also > > help make the connections here, a sort of *real* Visual Basic > > programming -- sorry Microsoft :P > > Along these lines, see my "ClixTur" application atwww.jjposner.net. > It's a point-and-click front end to the standard Python turtle module, > implementing only a very small subset of the turtle commands. As you > click, the "real turtle commands" appear in a transcript window. You can > then save (and maybe edit) and replay the transcript. > > Ram, I like a lot of what you've done. Could you talk about your > decision to embed the standard turtle module (which is implemented in > Tkinter) in a wxPython application? > > -John Certainly John- although I have not embedded the turtle module at all, I just wrote my own. This was actually quite a short process - What took the most time was developing the shell, which is a fork of PyShell. The original PyShell controls the same process it is run on, but my fork controls a different process (created by the multiprocessing package.) That took a lot of time. I actually created an independent package for it, called "shelltoprocess", which is a subfolder in PythonTurtle's source, so now anyone can use it for their own project. I am proud to say that this shell has some features that IDLE should envy. If you're asking WHY I put it in a wxPython application, the answer is pretty much what "r" said: To make it like any other "over the counter" Windows application, making people feel more comfortable with it. Also, not requiring them to install Python+packages, but just PythonTurtle. Ram. From fatkinson at mishmash.com Tue Aug 4 03:48:42 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Tue, 04 Aug 2009 00:48:42 -0700 Subject: Seeding the rand() Generator References: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> Message-ID: On Mon, 3 Aug 2009 20:00:08 -0700 (PDT), Carl Banks wrote: >Your question is a MySQL question, not a Python question. I don't >know off hand how to seed the RNG in MySQL, and, since this is a >Python group and not a MySQL group, I don't care to look it up. But >if you were able to produce the MySQL statement in PHP that does it >you shouldn't need to ask. > >If you don't "get" why this is a MySQL question and not a Python >question, then you need to learn more about what you are doing. I wouldn't agree. I tried using the same command I used when I did this in PHP. That command was: mt_srand(date("w")) It was a PHP command that seeds the MySQL random function, according to the folks on the PHP newsgroup. I'm trying to figure out what the Python equivalent of that is. Now do you see? Fred From http Tue Aug 4 03:56:05 2009 From: http (Paul Rubin) Date: 04 Aug 2009 00:56:05 -0700 Subject: Is python buffer overflow proof? References: <7x1vnsmc3c.fsf@ruckus.brouhaha.com> Message-ID: <7x4osoypuy.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > The point is that code you write yourself can rely on "pure Python" to be > free of buffer-overflows (for some definition of "rely") rather than > having to worry about managing memory yourself. Right. Basically the Python interpreter protects you reasonably well from silly errors. The interpreter hasn't had anywhere near the level of hardening required to claim to protect you from diabolically clever malicious code running in the same interpreter as your sensitive application. The Rexec/Bastion modules were basically swiss cheese. From loic.domaigne at googlemail.com Tue Aug 4 04:02:04 2009 From: loic.domaigne at googlemail.com (=?ISO-8859-1?Q?Lo=EFc_Domaign=E9?=) Date: Tue, 4 Aug 2009 01:02:04 -0700 (PDT) Subject: Strange python script behaviour References: Message-ID: Hi, > I have a problem with one of my python scripts. When I run this script > from command line it works correctly, but if I set up cron to run this > script on specified hour it works for a while and then "[Errno 32] > Broken pipe" error occures (always). > > The strangest thing is that if I change command in CRON > > from > python /home/xxx/script.py > to > python /home/xxx/script.py ?> /tmp/script.log 2>&1 > > the script always works correctly!!! > > The question is WHY? Any ideas? This is a cron issue, and has little with python to do. By default, cron will email the output produced by your script, unless you redirect. It does so by pipe to a "mail" program. Your error seems to indicate a problem with the latter (perhaps you don't have any "mail" program installed). HTH, Lo?c -- My Blog: http://www.domaigne.com/blog "To err is human, but to really foul things up you need a computer." -- Paul Ehrlich From anthra.norell at bluewin.ch Tue Aug 4 04:02:31 2009 From: anthra.norell at bluewin.ch (Anthra Norell) Date: Tue, 04 Aug 2009 10:02:31 +0200 Subject: Compiling regex inside function? In-Reply-To: References: Message-ID: <4A77EB17.2050308@bluewin.ch> alex23 wrote: > Anthra Norell wrote: > >> def entries (l): >> r = re.compile ('([0-9]+) entr(y|ies)') >> match = r.search (l) >> if match: return match.group (1) >> >> So the question is: does "r" get regex-compiled once at py-compile time >> or repeatedly at entries() run time? >> > The docs say: > The compiled versions of the most recent patterns passed to re.match > (), re.search() or re.compile() are cached, so programs that use only > a few regular expressions at a time needn?t worry about compiling > regular expressions. > > (But they don't say how few is 'only a few'...) > > If you're concerned about it, you could always set the compiled > pattern to a default value in the function's argspec, as that _is_ > only executed the once: > > def entries(line, regex = re.compile('([0-9]+) entr(y|ies)'): > match = regex.search(line) > ... > Excellent idea! Thank you all for the tips. Frederic From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 4 04:03:53 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 04 Aug 2009 10:03:53 +0200 Subject: Confessions of a Python fanboy In-Reply-To: <008eef29$0$9756$c3e8da3@news.astraweb.com> References: <008e82e8$0$9756$c3e8da3@news.astraweb.com> <4a72d7cf$0$25239$426a34cc@news.free.fr> <008eef29$0$9756$c3e8da3@news.astraweb.com> Message-ID: <4a77eb69$0$22600$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Fri, 31 Jul 2009 13:38:56 +0200, Bruno Desthuilliers wrote: > >>> On the other hand, we don't have to prefix names with @ and @@, >> Nope, we have to prefix them with 'self' or 'cls' (or even >> 'self.__class__'). > > Incorrect. Correct for all relevant cases, except this one: >>>> class K: > ... class_attribute = 'No @@ required.' > ... >>>> K().class_attribute > 'No @@ required.' Once again: Ruby's attributes are *private*, so you can't access an attribute (class or instance) from outside a method. IOW, the above example is irrelevant. (snip) > Disadvantages: your code is filled with line noise. It's an arbitrary > choice between @@ meaning instance attribute and @@ meaning class > attribute -- there's no logical reason for choosing one over the other, > so you have to memorise which is which. It's easy to get it wrong. So far that's something I have no difficulty living with. >>> and we >>> don't have the compiler trying to *guess* whether we're calling a >>> function or referring to a variable. >> Please re-read a bit more carefully - it's *all* method call. > > What did I misread from here? Nowhere - it's me that got it wrong here, sorry. (snip) >>> Somebody who knows more Ruby than me should try writing the Zen of >>> Ruby. Something like: >> (snip childish parody of Python Zen) >> >> Steven, is that any useful ? > > It made me feel good. Why ??? You don't like Ruby ? Fine, don't use it. Period. I can't see the point of all these pissing contests. > But seriously, while I admit that I have very little Ruby experience, and > so aren't in a great position to judge, it seems to me that Ruby doesn't > have anything like Python's over-riding design principles (the Zen). If > there is a design principle to Ruby, I can't see what it is. Fullfill the tastes of Matz ?-) (snip) >>> Although I'm sure Ruby has its good points. I'm not convinced anonymous >>> code blocks are one of them though. >> Ruby's code blocks come from Smalltalk, where they are an absolute >> necessity since message passing (which code blocks are part of) is the >> *only* builtin control flow in Smalltalk - so you just *need* this >> construction to provide branching and iterations. > > Just because Smalltalk had a particular (mis?)feature You can drop the 'mis' part IMHO. The point of code blocks in Smalltalk is that once you have something as powerful as the message+code blocks combo, you just don't need any other 'special form' for control flow. > doesn't mean that > other languages should copy it. Nope. But OTHO, Python is famous for all the features it copied from other languages !-) From spam.buster at web.de Tue Aug 4 04:08:23 2009 From: spam.buster at web.de (Lars Behrens) Date: Tue, 04 Aug 2009 10:08:23 +0200 Subject: Strange python script behaviour References: Message-ID: ?ukasz wrote: > The strangest thing is that if I change command in CRON > > from > python /home/xxx/script.py > to > python /home/xxx/script.py > /tmp/script.log 2>&1 > > the script always works correctly!!! > > The question is WHY? Any ideas? Seems to me that this is more of a shell thing... First of all, it is always a good idea to call applications with their full path from cronjobs: /usr/bin/python /home/xxx/script.py or whatever the output of your "which python" may be. How did you create the cronjob? Dependending on the editor you used, maybe there is a missing newline... -- Cheerz Lars From lkrzysiak at gmail.com Tue Aug 4 04:30:29 2009 From: lkrzysiak at gmail.com (=?UTF-8?Q?=C5=81ukasz?=) Date: Tue, 4 Aug 2009 01:30:29 -0700 (PDT) Subject: Strange python script behaviour References: Message-ID: <4cfffc2c-1923-4fc6-be0b-07ee4c4aae2b@h21g2000yqa.googlegroups.com> On 4 Sie, 10:02, Lo?c Domaign? wrote: > Hi, > > > I have a problem with one of my python scripts. When I run this script > > from command line it works correctly, but if I set up cron to run this > > script on specified hour it works for a while and then "[Errno 32] > > Broken pipe" error occures (always). > > > The strangest thing is that if I change command in CRON > > > from > > python /home/xxx/script.py > > to > > python /home/xxx/script.py ?> /tmp/script.log 2>&1 > > > the script always works correctly!!! > > > The question is WHY? Any ideas? > > This is a cron issue, and has little with python to do. > > By default, cron will email the output produced by your script, unless > you redirect. It does so by pipe to a "mail" program. Your error seems > to indicate a problem with the latter (perhaps you don't have any > "mail" program installed). > Hmm... interesting, but logical explanation. Cron has its weird issues. I guess I have to redirect outputs of all my scripts to /dev/ null in order to prevent them from this kind of error. Thanks for help :) From lkrzysiak at gmail.com Tue Aug 4 04:33:17 2009 From: lkrzysiak at gmail.com (=?UTF-8?Q?=C5=81ukasz?=) Date: Tue, 4 Aug 2009 01:33:17 -0700 (PDT) Subject: Strange python script behaviour References: Message-ID: <7e430558-f029-450e-bb06-2b273a7a2fe1@s31g2000yqs.googlegroups.com> On 4 Sie, 10:08, Lars Behrens wrote: > ?ukasz wrote: > > The strangest thing is that if I change command in CRON > > > from > > python /home/xxx/script.py > > to > > python /home/xxx/script.py ?> /tmp/script.log 2>&1 > > > the script always works correctly!!! > > > The question is WHY? Any ideas? > > Seems to me that this is more of a shell thing... > > First of all, it is always a good idea to call applications with their full > path from cronjobs: > > /usr/bin/python /home/xxx/script.py or whatever the output of your "which > python" may be. > > How did you create the cronjob? Dependending on the editor you used, maybe > there is a missing newline... > No, I've just simplified cron entries to not mess the example :) The key thing was redirecting stdin & stderr to file. But thanks anyway... :) From gagsl-py2 at yahoo.com.ar Tue Aug 4 04:48:15 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 04 Aug 2009 05:48:15 -0300 Subject: Is python buffer overflow proof? References: <4a77c0d9$0$1584$742ec2ed@news.sonic.net> Message-ID: En Tue, 04 Aug 2009 02:06:06 -0300, John Nagle escribi?: > Gabriel Genellina wrote: >> En Mon, 03 Aug 2009 18:04:53 -0300, sturlamolden >> escribi?: >> >>> On 2 Aug, 15:50, Jizzai wrote: >>> >>>> Is a _pure_ python program buffer overflow proof? >>>> For example in C++ you can declare a char[9] to hold user input. >>>> If the user inputs 10+ chars a buffer overflow occurs. > A more useful question is whether the standard libraries are being > run through any of the commercial static checkers for possible buffer > overflows. In the past the Python source code was checked with valgrind and some coverity tools; I don't know the current status. -- Gabriel Genellina From bartsmeets86 at gmail.com Tue Aug 4 04:52:20 2009 From: bartsmeets86 at gmail.com (Bart Smeets) Date: Tue, 4 Aug 2009 10:52:20 +0200 Subject: easy_install: unresolved external symbol In-Reply-To: References: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> Message-ID: <2119ee90908040152k5a744f98l7d5bc7da755948a2@mail.gmail.com> I could ofcourse use cxfreeze's binary package. But bbfreeze is not available as a binary. I would love to get easy_install to work. But I have no idea what's going wrong here. 2009/8/4 Gabriel Genellina > En Mon, 03 Aug 2009 17:39:44 -0300, Bart Smeets > escribi?: > > I keep getting errors when trying to use easy_install to install bbfreeze >> or >> cxfreeze (same errors). >> This is the output: >> http://pastebin.com/m65ba474d >> > > Can't you use the binary packages? > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From loic.domaigne at googlemail.com Tue Aug 4 05:11:21 2009 From: loic.domaigne at googlemail.com (=?ISO-8859-1?Q?Lo=EFc_Domaign=E9?=) Date: Tue, 4 Aug 2009 02:11:21 -0700 (PDT) Subject: Strange python script behaviour References: <4cfffc2c-1923-4fc6-be0b-07ee4c4aae2b@h21g2000yqa.googlegroups.com> Message-ID: <328af145-daaa-4239-bb42-dbf0a379540e@f37g2000yqn.googlegroups.com> > > > I have a problem with one of my python scripts. When I run this script > > > from command line it works correctly, but if I set up cron to run this > > > script on specified hour it works for a while and then "[Errno 32] > > > Broken pipe" error occures (always). > > > > The strangest thing is that if I change command in CRON > > > > from > > > python /home/xxx/script.py > > > to > > > python /home/xxx/script.py ?> /tmp/script.log 2>&1 > > > > the script always works correctly!!! > > > > The question is WHY? Any ideas? > > > This is a cron issue, and has little with python to do. > > > By default, cron will email the output produced by your script, unless > > you redirect. It does so by pipe to a "mail" program. Your error seems > > to indicate a problem with the latter (perhaps you don't have any > > "mail" program installed). > > Hmm... interesting, but logical explanation. Cron has its weird > issues. I guess I have to redirect outputs of all my scripts to /dev/ > null in order to prevent them from this kind of error. You could also set the MAILTO variable to "". HTH, Lo?c -- My Blog: http://www.domaigne.com/blog "Hardware: The parts of a computer system that can be kicked." -- Jeff Pesis. From david.lyon at preisshare.net Tue Aug 4 05:12:07 2009 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 04 Aug 2009 05:12:07 -0400 Subject: =?UTF-8?Q?easy=5Finstall=3A=20unresolved=20external=20symbol?= In-Reply-To: <2119ee90908040152k5a744f98l7d5bc7da755948a2@mail.gmail.com> References: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> <2119ee90908040152k5a744f98l7d5bc7da755948a2@mail.gmail.com> Message-ID: <87f2eede5ce0f1391994db66153e3c96@preisshare.net> On Tue, 4 Aug 2009 10:52:20 +0200, Bart Smeets wrote: > I could ofcourse use cxfreeze's binary package. But bbfreeze is not > available as a binary. I would love to get easy_install to work. But I have > no idea what's going wrong here. What is going on is that setuptools does some very 'advanced' things. The best you can do is give the option to link to the ez_setup.py install script and let the users install it them themselves... David From steven at REMOVE.THIS.cybersource.com.au Tue Aug 4 05:28:50 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 09:28:50 GMT Subject: Confessions of a Python fanboy References: <008e82e8$0$9756$c3e8da3@news.astraweb.com> <4a72d7cf$0$25239$426a34cc@news.free.fr> <008eef29$0$9756$c3e8da3@news.astraweb.com> <4a77eb69$0$22600$426a74cc@news.free.fr> Message-ID: On Tue, 04 Aug 2009 10:03:53 +0200, Bruno Desthuilliers wrote: >> Disadvantages: your code is filled with line noise. It's an arbitrary >> choice between @@ meaning instance attribute and @@ meaning class >> attribute -- there's no logical reason for choosing one over the other, >> so you have to memorise which is which. It's easy to get it wrong. > > So far that's something I have no difficulty living with. I don't like arbitrary symbols. Most people don't -- that's why "line noise" is unpopular. It's hard to read, hard to write, hard to maintain, and hard to talk about. The more line-noise, the worse the language. Of course, *ultimately* every symbol is arbitrary. There's no reason why "2" should mean the integer two, or "list" should mean a sequence type, but some symbols have such a long history, or have some other connection (say, with human languages), that the arbitrariness is lost. For instance, "+" is the obvious, non-arbitrary choice for the addition operator in any programming language using Latin symbols, and probably any programming language on Earth. (Not the *only* choice, but the obvious one.) I have a similar dislike for decorator syntax, because "@" ("at" in English) has nothing to do with decorations. It's an arbitrary symbol. One might argue that "$" would have been a more logical choice, because we turn numerals into currency by decorating it with a $ sign. (At least in the US, Canada, Australia, and a few other countries.) I use decorators all the time, and they are a fantastic invention, but the arbitrariness of the @ syntax is a negative. Oh well, one negative out of a whole lot of positives isn't too bad. At least I only have to deal with *one* such arbitrary symbol that needs memorizing. There's no need to distinguish between @@function_decorator and @class_decorator (or should it be the other way around?). Similarly, Python's choice of syntax for attributes is consistent: object.attribute works for everything, whether object is a class, an instance, a module, and whether attribute is callable or not. You can even use it on ints, provided you are clever about it: >>> 42 .__class__ >>>> Somebody who knows more Ruby than me should try writing the Zen of >>>> Ruby. Something like: >>> (snip childish parody of Python Zen) >>> >>> Steven, is that any useful ? >> >> It made me feel good. > > Why ??? > > You don't like Ruby ? Fine, don't use it. Period. I can't see the point > of all these pissing contests. Criticism of a language is a pissing contest? Yeah, okay, I was a tad dismissive. I un-apologetically jump to strong impressions about languages based on minimal use -- but I'm also willing to change my mind. Ruby certainly looks to me like it has some nice features. Syntax that looks like Perl isn't one of them though. >> Just because Smalltalk had a particular (mis?)feature > > You can drop the 'mis' part IMHO. The point of code blocks in Smalltalk > is that once you have something as powerful as the message+code blocks > combo, you just don't need any other 'special form' for control flow. Well, maybe, but remember, programming languages are only partly for communication to the compiler. They also have the requirement to communicate with human programmers as well, and that's even more important, because (1) humans spent a lot more time working with code than compilers do; (2) human programmers charge much more money than compilers do; (3) and you can modify the compiler to suit human needs much more easily than you can modify programmers to suit the compiler's needs. So I'd ask, does Smalltalk's message passing model match the way human beings think? If not, then that's a good sign it might be a misfeature. >> doesn't mean that >> other languages should copy it. > > Nope. But OTHO, Python is famous for all the features it copied from > other languages !-) Absolutely! There's nothing wrong with copying *good* features :) -- Steven From gregor.lingl at aon.at Tue Aug 4 05:30:23 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 11:30:23 +0200 Subject: ANN: Python's turtle module: collection of examples + demoViewer Message-ID: <4a77ffb2$0$1552$91cee783@newsreader04.highway.telekom.at> Hi all, A few days ago I've created a repository of turtle graphics demos/applications, that use Python's new turtle module. You can find it at at google code: http://python-turtle-demo.googlecode.com There are two versions of the collection: one for use with Python 3.1 and one for use with Python 2.5 / 2.6. The latter contains a *** backport of version 1.1 of the turtle module *** *** (from Python 3.1) to Python 2.5 / 2.6 *** Among others it contains all the examples I have demonstrated at Pycon 2009 and at EuroPython 2009. Moreover it contains the demoViewer (which is also in the source distribution of CPython) that lets you select the examples via a menu, display their source code and execute them in parallel. If you are interested to amend some of these examples, add some explanatory material or contribute additional examples, please tell me so I could add you as a committer to the project. I'd be glad to expand the repository whith interesting examples and applications using the turtle module. If you have questions concerning the examples, feel free to ask here or ask me directly via my email-address. I hope this collection will prove to be useful. Best regards, Gregor P.S.: I tried to announce it at comp.lang.python.announce but for some unknown reason it was not accepted there From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 4 06:01:06 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 04 Aug 2009 12:01:06 +0200 Subject: Confessions of a Python fanboy In-Reply-To: References: <008e82e8$0$9756$c3e8da3@news.astraweb.com> <4a72d7cf$0$25239$426a34cc@news.free.fr> <008eef29$0$9756$c3e8da3@news.astraweb.com> <4a77eb69$0$22600$426a74cc@news.free.fr> Message-ID: <4a7806e2$0$438$426a34cc@news.free.fr> Steven D'Aprano a ?crit : > On Tue, 04 Aug 2009 10:03:53 +0200, Bruno Desthuilliers wrote: > >>> Disadvantages: your code is filled with line noise. It's an arbitrary >>> choice between @@ meaning instance attribute and @@ meaning class >>> attribute -- there's no logical reason for choosing one over the other, >>> so you have to memorise which is which. It's easy to get it wrong. >> So far that's something I have no difficulty living with. > > I don't like arbitrary symbols. Neither do I - when there are too many at least. But I can certainly live with a couple ones. Now the point wasn't about my personal tastes, but about the fact that this particular pair of "arbitrary symbols" was IMHO still usable - IOW, I wouldn't dismiss Ruby on this sole point. > Most people don't -- that's why "line > noise" is unpopular. It's hard to read, hard to write, hard to maintain, > and hard to talk about. The more line-noise, the worse the language. OTHO, too much verbosity is a pain too. Ever programmed in AppleScript ? "set the attribute XXX of object YYY of collection ZZZ to SomeValue"... Yuck. I bet you prefer "zzz[yyy].xxx = SomeValue" - which uses three arbitrary symbols. (snip) > Oh well, one negative out of > a whole lot of positives isn't too bad. Indeed. You could perhaps learn a bit more about Ruby's positives if you don't block on what you perceive (rightfully or not) as negative points ?-) (snip) >>>>> Somebody who knows more Ruby than me should try writing the Zen of >>>>> Ruby. Something like: >>>> (snip childish parody of Python Zen) >>>> >>>> Steven, is that any useful ? >>> It made me feel good. >> Why ??? >> >> You don't like Ruby ? Fine, don't use it. Period. I can't see the point >> of all these pissing contests. > > Criticism of a language is a pissing contest? Not necessarily. But: > Yeah, okay, I was a tad dismissive. I un-apologetically jump to strong > impressions about languages based on minimal use Possibly, yes. > -- but I'm also willing > to change my mind. Ruby certainly looks to me like it has some nice > features. Syntax that looks like Perl isn't one of them though. Not my cup of tea neither FWIW. But Ruby is nowhere near Perl in terms of "line noise". > >>> Just because Smalltalk had a particular (mis?)feature >> You can drop the 'mis' part IMHO. The point of code blocks in Smalltalk >> is that once you have something as powerful as the message+code blocks >> combo, you just don't need any other 'special form' for control flow. > > Well, maybe, but remember, programming languages are only partly for > communication to the compiler. They also have the requirement to > communicate with human programmers as well, and that's even more > important, because > > (1) humans spent a lot more time working with code than compilers do; > > (2) human programmers charge much more money than compilers do; > > (3) and you can modify the compiler to suit human needs much more easily > than you can modify programmers to suit the compiler's needs. > > So I'd ask, does Smalltalk's message passing model match the way human > beings think? Does all human beings think the same way ? And aren't human beings able to learn new ways ? Smalltalk's only control flow construct might seem a bit weird at first when all you've been exposed to so far are more "traditional" special constructs, but it's not hard to learn and is way more uniform and flexible than having special constructs for each and any possible situation. One could ask if functional programming or OO "matches the way human beings think". From experience, some of us just find FP and / or OO just obvious, and some won't never get it. FWIW, there are quite a few features and idioms in Python that I _now_ find readable and obvious, but that would have puzzled me ten years ago. This reminds me of a shop where the CTO had forbidden using any OO feature of the main language used there because "nobody would understand it" (needless to say, I only stayed there a couple weeks...). > >>> doesn't mean that >>> other languages should copy it. >> Nope. But OTHO, Python is famous for all the features it copied from >> other languages !-) > > Absolutely! There's nothing wrong with copying *good* features :) Well... at least when they make sense and integrate smoothly into the target language. From masklinn at masklinn.net Tue Aug 4 06:15:19 2009 From: masklinn at masklinn.net (Masklinn) Date: Tue, 4 Aug 2009 12:15:19 +0200 Subject: Help understanding the decisions *behind* python? In-Reply-To: <4a7715ff$0$1641$742ec2ed@news.sonic.net> References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> <4a7715ff$0$1641$742ec2ed@news.sonic.net> Message-ID: <80C5CBFA-5547-4675-B60E-033C5C60DEDB@masklinn.net> On 3 Aug 2009, at 18:57 , John Nagle wrote: > Dave Angel wrote: >> sturlamolden wrote: >>> On 20 Jul, 18:27, Phillip B Oldham wrote: >>> Tuples are used for passing arguments to and from a function. Common >>> use of tuples include multiple return values and optional arguments >>> (*args). > > That's from Mesa, the Xerox PARC language of the 1970s. > > Mesa used tuples for subroutine arguments in a very straightforward > way. Every function took one tuple as an argument, written as > parameters > in parentheses separated by commas. Most statically typed functional languages seem to do pretty much the same: uncurried functions really take a tuple as single argument rather than multiple arguments, using pattern matching to make it look like multiple arguments. Then again, most of them seem to default to curried functions these days, which is nice. From masklinn at masklinn.net Tue Aug 4 06:21:01 2009 From: masklinn at masklinn.net (Masklinn) Date: Tue, 4 Aug 2009 12:21:01 +0200 Subject: Confessions of a Python fanboy In-Reply-To: References: <008e82e8$0$9756$c3e8da3@news.astraweb.com> <4a72d7cf$0$25239$426a34cc@news.free.fr> <008eef29$0$9756$c3e8da3@news.astraweb.com> <4a77eb69$0$22600$426a74cc@news.free.fr> Message-ID: <6FE460F1-7484-4234-9D41-72AAE26AB06E@masklinn.net> On 4 Aug 2009, at 11:28 , Steven D'Aprano wrote: > So I'd ask, does Smalltalk's message passing model match the way human > beings think? Yes. From yinon.me at gmail.com Tue Aug 4 06:30:52 2009 From: yinon.me at gmail.com (Yinon Ehrlich) Date: Tue, 4 Aug 2009 03:30:52 -0700 (PDT) Subject: Obtaining Python version References: <4a776184$0$1611$742ec2ed@news.sonic.net> Message-ID: <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> On Aug 4, 1:19?am, John Nagle wrote: > This works, but it seems too cute: > > ?>>> pyver = map(int,sys.version.split()[0].split('.')) > ?>>> print(pyver) > [2, 6, 1] > > Is it guaranteed that the Python version string will be in a form > suitable for that? ?In other words, does "sys.version" begin > > N.N.N other stuff > > in all versions, and will it stay that way? ?Are there ever > non-numeric versions, like "3.2.rc1"? > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle Hi, Easy way to test for Python version: if sys.hexversion >= 0x2060100: pass -- Yinon From koranthala at gmail.com Tue Aug 4 06:32:51 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 03:32:51 -0700 (PDT) Subject: Which GUI framework to use? References: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> <7dq3tvF2d74reU1@mid.uni-berlin.de> Message-ID: On Aug 4, 11:48?am, "Diez B. Roggisch" wrote: > koranthala schrieb: > > > Hi, > > ? ?I am creating a very minimal application (a networking app). > > ? ?I have written the application using Twisted. > > ? ?Now, I need to put a GUI wrapper on the application. > > ? ?The application needs a login screen and also it needs to be > > minimized to system tray. If I right click the image on system tray, I > > should be able to close it. > > ? ?It uses some legacy code, so the whole app is written in Python > > 2.4. Also, my company requires that I use permissive licenses (no GPL > > - MIT, BSD, LGPL etc ok) > > Google this group. The discussions are abundant about this. Keep in mind > that while Qt changed licenses to LGPL, PyQt didn't and thus you can't > use it. > > > ? ?Which GUI framework is best for this? I tried using Tkinter, but it > > does not support minimize to system tray (or I couldnt find it). > > > ? ?This is my first foray to GUI programming, so other issues that I > > am worried about - > > ? ?1. GUI needs a loop, Twisted needs a loop. How can both go ahead > > without messing each other? > > Google is your friend here, too: > > http://twistedmatrix.com/projects/core/documentation/howto/choosing-r... > > Diez Sorry about it. I should have done the homework better. From lists at cheimes.de Tue Aug 4 06:58:03 2009 From: lists at cheimes.de (Christian Heimes) Date: Tue, 04 Aug 2009 12:58:03 +0200 Subject: Is python buffer overflow proof? In-Reply-To: <4a77c0d9$0$1584$742ec2ed@news.sonic.net> References: <4a77c0d9$0$1584$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > A more useful question is whether the standard libraries are being > run through any of the commercial static checkers for possible buffer > overflows. The CPython interpreter is constantly checked with http://www.coverity.com/. Although Python is used for critical stuff at large companies like Apple, Google and NASA, only a few critical bugs in the C code have been found in the last couple of years. From gregor.lingl at aon.at Tue Aug 4 07:19:48 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 13:19:48 +0200 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: <4a781958$0$1552$91cee783@newsreader04.highway.telekom.at> cool-RR schrieb: > Hello, > > I wanted to announce that I have just released my little side project, > PythonTurtle. > Here is its website: > http://pythonturtle.com > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > You can read more about it and download it on the website. > > Ram. Hi Ram, that's indeed a nice starting point for kids to doing turtle graphics, although currently it seems to implement only a very small subset of Python's turtle module's capabilities, even less than those of the old turtle module (that shipped with Python upto 2.5). Moreover I have to complain that you decided to use different commands for the turtle's actions - go instead of forward, turn instead of left and right etc. First I think left and right are more intuitive than turn as they do not need negative angles as arguments, which might matter for young children. Also I cannot see the advantage of cammands like visible() or invisible() over showturtle() and hideturtle() But second even kids - when learning how to program - will arrive at a point where it's no more problem to use an editor like IDLE so they could easily switch to Python's turtle module. That would be even easier if they had not to learn a new command set. Moreover a learning environment like PythonTurtle needs something like an editor - at least a simple one - in order to create programs that can be run repeatedly. Coding, that's creating programs - not only issuing a sequence of cammands interactively. It would be certainly a good thing if one had a similar environment using Tkinter, preferably also as part of the standard distribution of Python accompanying the turtle module. I think it should not be that difficult to create a GUI of this sort combining IDLE's shell window, its editor and turtle.py. Alas, at the moment I'm too busy with some othr work to start a project like this. Perhaps someone else might be interested? I'd enjoy to join a team doing it. Finally I'd like to stress, that the aims of PythonTurtle and Python's turtle module are quite different - as one could grasp easily by trying out the collection of examples at python-turtle-demo.googlecode.com that I posted in another posting. Anyway they could very well complement one another in some more mature state of development. Best regards, Gregor From thorsten at thorstenkampe.de Tue Aug 4 07:23:12 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 4 Aug 2009 13:23:12 +0200 Subject: Is python buffer overflow proof? References: Message-ID: * Jizzai (Sun, 02 Aug 2009 13:50:14 GMT) > Is a _pure_ python program buffer overflow proof? You cannot create "your own" buffer overflow in Python as you can in C and C++ but your code could still be vulnerable if the underlying Python construct is written in C. See [1] for instance. Thorsten [1] http://www.gentoo.org/security/en/glsa/glsa-200610-07.xml From IDOL at il.ibm.com Tue Aug 4 07:25:17 2009 From: IDOL at il.ibm.com (Ido Levy) Date: Tue, 4 Aug 2009 14:25:17 +0300 Subject: How to fetch an XML file using an HTTPS query Message-ID: Hello All I am quite new to Python and I would appreciate your advice on the following issue. I am trying to fetch an XML file from a remote server using an HTTPS query. When testing the HTTPS query from the browser after I entered the URL I got a pop-up box asking me if I want to "save a file" or "open with". >From a Python script I tried using urllib but it fails. I validated that my Python release support https request by using the following code and a different URL: import urllib print urllib.urlopen('https://...').read() and got the expected result. When I tried the above code or the following one with the URL that should return an XML file import sys import urllib import urllib2 headers = {'User-Agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.12) Gecko/20050923 Firefox/1.0.7', 'Cookie': 'JSESSIONID=000000000000000000000000000:111111111;Path=/',} url = "https://..." req = urllib2.Request(url, None, headers) urlFH = urllib2.urlopen(req) headers = urlFH.info() page_content = urlFH.readlines() urlFH.close() for line in page_content: print 'line: %s' % line I got the following result in both cases: Invalid filter passed. Thanks in Advance Ido Levy -------------- next part -------------- An HTML attachment was scrubbed... URL: From sibtey.mehndi at genpact.com Tue Aug 4 07:31:42 2009 From: sibtey.mehndi at genpact.com (Mehndi, Sibtey) Date: Tue, 4 Aug 2009 04:31:42 -0700 Subject: how to create a Com object of Picalo Module Message-ID: <1A343A98C8DAE44A8D9D1BF310F90D5E0140E41E62@GCPWINGGN2EVS11.IND.CORP.AD> Hi I want to use the picalo module in to VB.NET so I have tried to create the COM object of picalo module but I am unable to create. Anyone can help me out to create the picalo com object. Thanks, Sibtey This e-mail (and any attachments), is confidential and may be privileged. It may be read, copied and used only by intended recipients. Unauthorized access to this e-mail (or attachments) and disclosure or copying of its contents or any action taken in reliance on it is unlawful. Unintended recipients must notify the sender immediately by e-mail/phone & delete it from their system without making any copies or disclosing it to a third person. -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Tue Aug 4 07:34:44 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 4 Aug 2009 21:34:44 +1000 Subject: Obtaining Python version In-Reply-To: <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> Message-ID: <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> On Tue, Aug 4, 2009 at 8:30 PM, Yinon Ehrlich wrote: > Hi, > Easy way to test for Python version: > if sys.hexversion >= 0x2060100: > pass > Great suggestion. I just tested it on my newly installed Python 3.1 (as of 3.1r31) >>> import sys >>> "%X" % sys.hexversion '30100F0' That's genius - '301' for Python 3.1, and '00F0' is r31! I'm definitely going to use this more often in the future. Cheers, Xavier -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Tue Aug 4 07:37:11 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 4 Aug 2009 21:37:11 +1000 Subject: Obtaining Python version In-Reply-To: <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> Message-ID: <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> On Tue, Aug 4, 2009 at 9:34 PM, Xavier Ho wrote: > ... and '00F0' is r31! > Actually, 00F0 is 576 in decimal. Maybe it's the subversion? Anyhow, it's still good! -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregor.lingl at aon.at Tue Aug 4 07:37:23 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 13:37:23 +0200 Subject: Announcing PythonTurtle In-Reply-To: <9e3b0c86-3a2a-4bc4-91f3-1b01a05d6b86@f37g2000yqn.googlegroups.com> References: <9e3b0c86-3a2a-4bc4-91f3-1b01a05d6b86@f37g2000yqn.googlegroups.com> Message-ID: <4a781d85$0$2311$91cee783@newsreader02.highway.telekom.at> cool-RR schrieb: > On Aug 4, 7:12 am, John Posner wrote: >>> ... I would also venture to say a key-map >>> ... > If you're asking WHY I put it in a wxPython application, the answer is > pretty much what "r" said: To make it like any other "over the > counter" Windows application, making people feel more comfortable with > it. > Also, not requiring them to install Python+packages, but just > PythonTurtle. Fortunately it's not necessary to install 'packages' to use Python's turtle module as it is one of it's 'batteries included'. And I think it's not so a bad idea to install Python if one want's to learn it, anyway. Regards, Gregor > > Ram. From cocobear.cn at gmail.com Tue Aug 4 08:01:47 2009 From: cocobear.cn at gmail.com (cocobear) Date: Tue, 4 Aug 2009 05:01:47 -0700 (PDT) Subject: merge two png pic References: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> <4a77e249$0$2449$426a74cc@news.free.fr> Message-ID: <72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com> On Aug 4, 3:24?pm, News123 wrote: > Hi, > > > > > > cocobear wrote: > >> > >> Map = Image.new("RGB", (x,y)) > >> > >> Map.paste(im, box) > >> > >> Map.paste(im1,box) > > >> > >> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE) > > >> > >> But if thetwopngpicis too big , or if I have tomergemorepic > >> > >> together, I will get MemoryError: > > >>>>> > >> >>> Image.new("RGB",(44544,38656)) > > >> What do you want to do with such a big image? You will run into the same > >> limitation when you are trying to display it. > > > I want to download a map from google map with high precision > > For me it sounds strange to handle such big files. > > Is the map you download from Google really that big? > Mostly Google maps uses normally tiles of sizes 256x256 pixel, wich you > have to compose to get the ?big image. > The map I downloaded from Google is small(256x256). These small maps will compose a big image. > If your problem is to combine tiles with different palettes, then you > should pobably look at a way to ?'unify' the palette of all tiles befor > combining them. > I think it is impossible to 'unify' all this tiles. > Being no expert of PIL I don't know whether this is easily possible though? > > bye > > N From hendrik at microcorp.co.za Tue Aug 4 08:14:40 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 4 Aug 2009 14:14:40 +0200 Subject: Which GUI framework to use? In-Reply-To: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> References: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> Message-ID: <200908041414.41026.hendrik@microcorp.co.za> On Tuesday 04 August 2009 06:09:05 koranthala wrote: > Hi, > I am creating a very minimal application (a networking app). > I have written the application using Twisted. > Now, I need to put a GUI wrapper on the application. > The application needs a login screen and also it needs to be > minimized to system tray. If I right click the image on system tray, I > should be able to close it. > It uses some legacy code, so the whole app is written in Python > 2.4. Also, my company requires that I use permissive licenses (no GPL > - MIT, BSD, LGPL etc ok) > > Which GUI framework is best for this? I tried using Tkinter, but it > does not support minimize to system tray (or I couldnt find it). look at iconify, and at withdraw - Hendrik From ram.rachum at gmail.com Tue Aug 4 08:19:48 2009 From: ram.rachum at gmail.com (cool-RR) Date: Tue, 4 Aug 2009 05:19:48 -0700 (PDT) Subject: Announcing PythonTurtle References: <4a781958$0$1552$91cee783@newsreader04.highway.telekom.at> Message-ID: <766a3973-6960-4500-9c7c-88d5261b823c@24g2000yqm.googlegroups.com> > Hi Ram, > > that's indeed a nice starting point for kids to doing turtle graphics, > although currently it seems to implement only a very small subset of > Python's turtle module's capabilities, even less than those of the old > turtle module (that shipped with Python upto 2.5). > I agree - an undo feature for example would be nice and it's something I would like to do in a future version. Other than that though, I don't think having many turtle-functions is so important. I think the important thing is for the student to build complex things from simple building blocks. > Moreover I have to complain that you decided to use different commands > for the turtle's actions - go instead of forward, turn instead of left > and right etc. First I think left and right are more intuitive than turn > as they do not need negative angles as arguments, which might matter for > young children. Also I cannot see the advantage of cammands like > visible() or invisible() over showturtle() and hideturtle() > But second even kids - when learning how to program - will arrive at a > point where it's no more problem to use an editor like IDLE so they > could easily switch to Python's turtle module. That would be even easier > if they had not to learn a new command set. > Moreover a learning environment like PythonTurtle needs something like > an editor - at least a simple one - in order to create programs that can > be run repeatedly. Coding, that's creating programs - not only issuing > a sequence of cammands interactively. > A text editor would be a good feature for future versions. Regarding the naming of functions: I named them in the way that seemed best to me. You seem not to agree, you like the way your functions are named better, and there's little point in arguing over which convention is truly better. The convention I chose is the one that seemed ideal to me. I did consider naming the functions the same way you did for consistency, but I decided not to compromise the quality of PythonTurtle just to be compatible with a module that my users may not even use. > It would be certainly a good thing if one had a similar environment > using Tkinter, preferably also as part of the standard distribution of > Python accompanying the turtle module. I think it should not be that > difficult to create a GUI of this sort combining IDLE's shell window, > its editor and turtle.py. Alas, at the moment I'm too busy with some > othr work to start a project like this. Perhaps someone else might be > interested? I'd enjoy to join a team doing it. I agree that it shouldn't be difficult; The question is whether someone will step up and do it. > Finally I'd like to stress, that the aims of PythonTurtle and Python's > turtle module are quite different - as one could grasp easily by trying > out the collection of examples at python-turtle-demo.googlecode.com that > I posted in another posting. Anyway they could very well complement one > another in some more mature state of development. > > Best regards, > Gregor Thank you for your feedback Gregor. Ram Rachum. From thangappan143 at gmail.com Tue Aug 4 08:25:30 2009 From: thangappan143 at gmail.com (Thangappan.M) Date: Tue, 4 Aug 2009 17:55:30 +0530 Subject: Problem in Installing PyGreSQL Message-ID: <7aa29e790908040525p562245c8v95d5a5d875fe606f@mail.gmail.com> Dear all, While installing PyGreSQl module in my machine I got the error as pg_config command not found. I am not a super user. how can I install this pg_config tool. -- Regards, Thangappan.M -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Tue Aug 4 08:27:27 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 04 Aug 2009 07:27:27 -0500 Subject: Is python buffer overflow proof? In-Reply-To: References: <7dnissF2bthr0U1@mid.uni-berlin.de> Message-ID: <4A78292F.8040907@tim.thechases.com> Marcus Wanner wrote: > On 8/3/2009 3:45 AM, Diez B. Roggisch wrote: >> But you can cast the resulting pointer to an array of larger size, and >> there you are. > > Ah, that makes sense. I had forgotten about ctypes.cast(). You *can* shoot yourself in the foot with Python, you just have to aim much more carefully than you do with C/C++. -tkc From gregor.lingl at aon.at Tue Aug 4 08:45:47 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 14:45:47 +0200 Subject: Announcing PythonTurtle In-Reply-To: <766a3973-6960-4500-9c7c-88d5261b823c@24g2000yqm.googlegroups.com> References: <4a781958$0$1552$91cee783@newsreader04.highway.telekom.at> <766a3973-6960-4500-9c7c-88d5261b823c@24g2000yqm.googlegroups.com> Message-ID: <4a782d7b$0$1549$91cee783@newsreader04.highway.telekom.at> cool-RR schrieb: >> Hi Ram, >> >> that's indeed a nice starting point for kids to doing turtle graphics, >> although currently it seems to implement only a very small subset of >> Python's turtle module's capabilities, even less than those of the old >> turtle module (that shipped with Python upto 2.5). ... > A text editor would be a good feature for future versions. > Regarding the naming of functions: I named them in the way that seemed > best to me. You seem not to agree, you like the way your functions are > named better, and there's little point in arguing over which > convention is truly better. The convention I chose is the one that > seemed ideal to me. > I did consider naming the functions the same way you did for > consistency, but I decided not to compromise the quality of > PythonTurtle just to be compatible with a module that my users may not > even use. That's the advantage of not developing for the standard library. In fact those elementary commands you use were present already in the old turtle module. When I decided to extend the old turtle module a primary requirement was that it remains 100% compatible to the old one. New versions of a module in the standard library must not break code of previous users of that module. In short: I did not name these functions but I had to use the names that already were there. Nevertheless I'd prefer left and right over turn even today, especially for kids as I argued before. Regards, Gregor > >> It would be certainly a good thing if one had a similar environment >> using Tkinter, preferably also as part of the standard distribution of >> Python accompanying the turtle module. I think it should not be that >> difficult to create a GUI of this sort combining IDLE's shell window, >> its editor and turtle.py. Alas, at the moment I'm too busy with some >> othr work to start a project like this. Perhaps someone else might be >> interested? I'd enjoy to join a team doing it. > > I agree that it shouldn't be difficult; The question is whether > someone will step up and do it. > >> Finally I'd like to stress, that the aims of PythonTurtle and Python's >> turtle module are quite different - as one could grasp easily by trying >> out the collection of examples at python-turtle-demo.googlecode.com that >> I posted in another posting. Anyway they could very well complement one >> another in some more mature state of development. >> >> Best regards, >> Gregor > > Thank you for your feedback Gregor. > > Ram Rachum. From darcy at druid.net Tue Aug 4 08:48:56 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 08:48:56 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> Message-ID: <20090804084856.b825967a.darcy@druid.net> On Tue, 04 Aug 2009 00:42:25 -0400 David Lyon wrote: > > Then I tried to download the module.But I am not able to download it. > > Did none of the links here work? > > http://www.pygresql.org/readme.html#where-to-get The RPM seems to be missing. I am currently trying to find one. I don't run Linux myself and sometimes forget to check that we have a working RPM. > > I am not a super user. > > I am using Linux debian machine > > Python version is 2.4.4 > > Try building it from source. That will work of course and it is a small enough package that it should build painlessly. There is a working setup.py. > Otherwise try getting it from pypi It is also missing the RPM. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From fatkinson at mishmash.com Tue Aug 4 08:58:46 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Tue, 04 Aug 2009 05:58:46 -0700 Subject: Seeding the rand() Generator References: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> Message-ID: <52cg759c3kg732ikns1emlgb5c3joom4md@4ax.com> On Tue, 04 Aug 2009 07:12:30 GMT, Jarkko Torppa wrote: >On 2009-08-04, Fred Atkinson wrote: >> On Mon, 3 Aug 2009 20:00:08 -0700 (PDT), Carl Banks >> wrote: >>> >>>If you don't "get" why this is a MySQL question and not a Python >>>question, then you need to learn more about what you are doing. >> >> I wouldn't agree. >> >> I tried using the same command I used when I did this in PHP. >> That command was: mt_srand(date("w")) >> >> It was a PHP command that seeds the MySQL random function, >> according to the folks on the PHP newsgroup. > >It seems that they lied to you. Did you actually try that ? > >> I'm trying to figure out what the Python equivalent of that >> is. > >Python equivalent of that is random.seed(x), if PHP docs are to be believed. > >> Now do you see? > >What you acutally want is "select *,rand(3) as rand from table >order by rand" or something like that. That 3 is the seed in there. Yes, I actually tried that and it worked. Things got much more random after I started using it. Regards, Fred From benjamin.kaplan at case.edu Tue Aug 4 09:03:55 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 4 Aug 2009 09:03:55 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <20090804084856.b825967a.darcy@druid.net> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> Message-ID: On Tue, Aug 4, 2009 at 8:48 AM, D'Arcy J.M. Cain wrote: > On Tue, 04 Aug 2009 00:42:25 -0400 > David Lyon wrote: >> > Then I tried to download the module.But I am not able to download it. >> >> Did none of the links here work? >> >> http://www.pygresql.org/readme.html#where-to-get > > The RPM seems to be missing. ?I am currently trying to find one. ?I > don't run Linux myself and sometimes forget to check that we have a > working RPM. > >> > I am not a super user. >> > I am using Linux debian machine >> > Python version is 2.4.4 >> >> Try building it from source. > > That will work of course and it is a small enough package that it > should build painlessly. ?There is a working setup.py. > >> Otherwise try getting it from pypi > > It is also missing the RPM. Doesn't matter here. Debians use DEBs (DEBian packages), not RPMs (for the Red Hat Package Manager). Either way, the OP can't install system level packages. That's what the comment about not being a super user meant. > > -- > D'Arcy J.M. Cain ? ? ? ? | ?Democracy is three wolves > http://www.druid.net/darcy/ ? ? ? ? ? ? ? ?| ?and a sheep voting on > +1 416 425 1212 ? ? (DoD#0082) ? ?(eNTP) ? | ?what's for dinner. > -- > http://mail.python.org/mailman/listinfo/python-list > From mydevforums at gmail.com Tue Aug 4 09:15:24 2009 From: mydevforums at gmail.com (IronyOfLife) Date: Tue, 4 Aug 2009 06:15:24 -0700 (PDT) Subject: Python configuration question when python scripts are executed using Appweb as web server. References: Message-ID: On Aug 3, 8:42?pm, "Gabriel Genellina" wrote: > En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife ? > escribi?: > > > I have installed python 2.6.2 in windows xp professional machine. I > > have set the following environment variables -- PYTHONPATH. It points > > to following windows folders: python root folder, the lib folder and > > lib-tk folder. > > Why? Did you read it somewhere? Usually there is no need to set the ? > PYTHONPATH variable at all; remove it. > > > I have configured IIS to execute python scripts. > > > I do not have any issues executing python scripts from the python > > interpreter window or from the browser using IIS as the web server. > > Try again after PYTHONPATH is removed, and make sure you can import all ? > the required modules from the Python console. Only then try to run the cgi ? > scripts. > > > However, when I use the open source Appweb web browser to execute > > python scripts. It is able to execute only simple script without > > issues. [...]However I am not able to execute python scripts that ? > > contain import > > statements. I need to point out here that i do not have issue with > > using os or sys packages. When I tried to execute the sample client > > script that came with the gnutls wrapper for python, I got error. I > > narrowed it down to the "from ... import" line in the example. > > > from gnutls.crypto import * > > from gnutls.connection import * > > Check that the above lines work fine from inside the Python console. > If not, something went wrong when you installed the gnutls Python package. > > > Next step, in order to debug, I used the module finder to see what is > > happening. To being with I used the module finder to find out the > > modules loaded for the simple script hello.py. > > Debugging cgi scripts isn't easy sometimes; try adding this line at the ? > start of your script: > > import cgitb;cgitb.enable() > > You should get a nicely formatted stack trace whenever an exception is ? > raised. If you get an HTTP error instead (like 500 Internal Server Error) ? > it's likely a syntax error, you must fix it before continuing. > Then, you may find that modulefinder is no more needed. > > > import pdb > > pdb.set_trace() > > pdb cannot work inside a CGI script; remove that. > > > Once again, let me stress that this issue is happening only when I use > > appweb as the web server. > > I don't know appweb, but if you first make sure the script works from the ? > command line, it should be much easier to make it work in the web server. > > -- > Gabriel Genellina Hi Gabriel Thanks for your reply. As I had mentioned in my original post, I am able to successfully execute gnutls client python script while using python interpreter and from the web browser while using IIS as web server. The scripts were not executing successfully only when I used AppWeb as web server. Setting PYTHONPATH environment variables is mentioned in Python docs. I figured out how to get the debug statements to write to Appweb logs and from there I found out the issue to be ImportError. Python does provide a very cryptic error message. "(, ImportError('DLL load failed: The specified module could not be found.',), )" I then downloaded filemon (as suggested in another forum) utility tool for windows environment. Using the tool I found that python.exe is trying to load gnutls related dlls from system path and a list of folders (I dont know why it didnt try to pick up the dlls from all the path provided in PATH environment variable) none of which contain the gnutls related dlls. I solved the issue temporarily by copying the gnutls related dlls to the path searched by python.exe Now my gnutls client python script executes successfully when i use Appweb as the web server, NOTE: When I use python interpreter or IIS as webserver the path where python.exe looks for gnutls related dll's are different. In this scenario python.exe is able to successfully load the required dlls. From davea at ieee.org Tue Aug 4 09:29:35 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 04 Aug 2009 09:29:35 -0400 Subject: Newbie Question regarding __init__() In-Reply-To: References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> <4A77A43D.4000709@ieee.org> Message-ID: <4A7837BF.6070903@ieee.org> Dennis Lee Bieber wrote: > On Mon, 03 Aug 2009 23:00:13 -0400, Dave Angel > declaimed the following in gmane.comp.python.general: > > >> To throw away the result of an expression in Python is even easier. >> Just don't use it. >> func1() and func2() >> is a valid expression whose result is not used. And func2()'s result is >> therefore irrelevant. But shortcircuiting means that func2() is only >> called if func1() returned False (or something equivalent to it, like 0 >> or an empty list) >> > > Backwards... > > When using "and", the RHS is only evaluated if the LHS evaluates to > TRUE (if the LHS is FALSE, why go further, since False and anything -> > False). > > Conversely, when using "or", the RHS is only evaluated if the LHS is > FALSE. > You're right of course. Slip of the keyboard. DaveA From nyamatongwe+thunder at gmail.com Tue Aug 4 09:32:55 2009 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 04 Aug 2009 13:32:55 GMT Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: Thorsten Kampe: > You cannot create "your own" buffer overflow in Python as you can in C > and C++ but your code could still be vulnerable if the underlying Python > construct is written in C. Python's standard library does now include unsafe constructs. import ctypes x = '1234' # Munging byte 1 OK ctypes.memset(x, 1, 1) print(x) # Next line writes beyond end of variable and crashes ctypes.memset(x, 1, 20000) print(x) Neil From philip at semanchuk.com Tue Aug 4 09:34:17 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 Aug 2009 09:34:17 -0400 Subject: Problem in Installing PyGreSQL In-Reply-To: <7aa29e790908040525p562245c8v95d5a5d875fe606f@mail.gmail.com> References: <7aa29e790908040525p562245c8v95d5a5d875fe606f@mail.gmail.com> Message-ID: On Aug 4, 2009, at 8:25 AM, Thangappan.M wrote: > Dear all, > > While installing PyGreSQl module in my machine I got the error as > pg_config > command not found. > I am not a super user. > how can I install this pg_config tool. Thangappan, pg_config is part of PostgreSQL. It reports various pieces of information about the Postgres installation, like the BINDIR, INCLUDEDIR, compile flags, version etc. If PostgreSQL is installed on your machine, then I'll bet that pg_config is also installed, but it isn't on your path so the PyGreSQl installer can't find it. When you're having trouble installing a specific package like PyGreSQl, you'll probably get better answers by posting your questions to a specific mailing list: http://mailman.vex.net/mailman/listinfo/pygresql By searching the archives you might even find that your question has been answered already. Good luck Philip From tycho at tycho.ws Tue Aug 4 09:41:30 2009 From: tycho at tycho.ws (Tycho Andersen) Date: Tue, 4 Aug 2009 08:41:30 -0500 Subject: How to fetch an XML file using an HTTPS query In-Reply-To: <49b3a7400908040638h46d4e4dcxe5cd4120e9c2c7a1@mail.gmail.com> References: <49b3a7400908040638h46d4e4dcxe5cd4120e9c2c7a1@mail.gmail.com> Message-ID: <49b3a7400908040641l5f5daaa8v374041b7fbac442a@mail.gmail.com> Blah, forgot to include the list. When is python-list going to get Reply-To? \t On Tue, Aug 4, 2009 at 8:38 AM, Tycho Andersen wrote: > Hi Ido, > > On Tue, Aug 4, 2009 at 6:25 AM, Ido Levy wrote: >> [snip] >> I got the following result in both cases: >> ? ? ? ? >> ? ? ? ? >> ? ? ? ? Invalid filter passed. >> ? ? ? ? > > To me, this doesn't look like a python problem: the application was > successfully connected to and returned a result. The problem you're > experiencing is that it wasn't the result you expected. Are you sure > you're setting the right headers, posting the right form values, etc. > and giving the app exactly what it wants? > > \t > From darcy at druid.net Tue Aug 4 09:53:40 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 09:53:40 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> Message-ID: <20090804095340.67e2de0f.darcy@druid.net> On Tue, 4 Aug 2009 09:03:55 -0400 Benjamin Kaplan wrote: > Doesn't matter here. Debians use DEBs (DEBian packages), not RPMs (for > the Red Hat Package Manager). Either way, the OP can't install system > level packages. That's what the comment about not being a super user > meant. Urk! I thought that all the Linux distros used RPMs. Maybe I should just remove that link and let each distro provide their own package. As long as it was just one I could take some steps to make sure that I wasn't distributing malware but the more packages I supply that I can't personally test, the more uncomfortable I get. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From darcy at druid.net Tue Aug 4 09:55:47 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 09:55:47 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> Message-ID: <20090804095547.a5274e22.darcy@druid.net> On Tue, 4 Aug 2009 09:03:55 -0400 Benjamin Kaplan wrote: > Doesn't matter here. Debians use DEBs (DEBian packages), not RPMs (for > the Red Hat Package Manager). Either way, the OP can't install system > level packages. That's what the comment about not being a super user > meant. By the way, you don't have to be super user to install PyGreSQL. You just need SU if you want to install it system wide. PyGreSQL doesn't require any special privileges to run. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From benjamin.kaplan at case.edu Tue Aug 4 10:02:23 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 4 Aug 2009 10:02:23 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <20090804095547.a5274e22.darcy@druid.net> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> <20090804095547.a5274e22.darcy@druid.net> Message-ID: On Tue, Aug 4, 2009 at 9:55 AM, D'Arcy J.M. Cain wrote: > On Tue, 4 Aug 2009 09:03:55 -0400 > Benjamin Kaplan wrote: >> Doesn't matter here. Debians use DEBs (DEBian packages), not RPMs (for >> the Red Hat Package Manager). Either way, the OP can't install system >> level packages. That's what the comment about not being a super user >> meant. > > By the way, you don't have to be super user to install PyGreSQL. ?You > just need SU if you want to install it system wide. ?PyGreSQL doesn't > require any special privileges to run. Right, but the packages install system-wide. That's why he could compile it himself but not use the package. > > -- > D'Arcy J.M. Cain ? ? ? ? | ?Democracy is three wolves > http://www.druid.net/darcy/ ? ? ? ? ? ? ? ?| ?and a sheep voting on > +1 416 425 1212 ? ? (DoD#0082) ? ?(eNTP) ? | ?what's for dinner. > -- > http://mail.python.org/mailman/listinfo/python-list > From darcy at druid.net Tue Aug 4 10:14:49 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 10:14:49 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> <20090804095547.a5274e22.darcy@druid.net> Message-ID: <20090804101449.79cd4522.darcy@druid.net> On Tue, 4 Aug 2009 10:02:23 -0400 Benjamin Kaplan wrote: > > By the way, you don't have to be super user to install PyGreSQL. ?You > > just need SU if you want to install it system wide. ?PyGreSQL doesn't > > require any special privileges to run. > > Right, but the packages install system-wide. That's why he could > compile it himself but not use the package. Exactly so don't install the package. Do "python setup.py build" and put the three files that are built (_pg.so, pg.py and pgdb.py) into any directory and point PYTHONPATH to it. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From python at mrabarnett.plus.com Tue Aug 4 10:17:39 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Aug 2009 15:17:39 +0100 Subject: Obtaining Python version In-Reply-To: <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> Message-ID: <4A784303.2070804@mrabarnett.plus.com> Xavier Ho wrote: > On Tue, Aug 4, 2009 at 9:34 PM, Xavier Ho > wrote: > > ... > and '00F0' is r31! > > > Actually, 00F0 is 576 in decimal. Maybe it's the subversion? > 0x00F0 is 240. > Anyhow, it's still good! > From contact at xavierho.com Tue Aug 4 10:39:56 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 5 Aug 2009 00:39:56 +1000 Subject: Obtaining Python version In-Reply-To: <4A784303.2070804@mrabarnett.plus.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> <4A784303.2070804@mrabarnett.plus.com> Message-ID: <2d56febf0908040739i79d4bcc9o461d6641c68f5fb9@mail.gmail.com> On Wed, Aug 5, 2009 at 12:17 AM, MRAB wrote: > 0x00F0 is 240. ... Right. I wonder where my brain is. *searches pocket* So, what am I doing wrong here? >>> int(str(0x00F0), 16) 576 Cheers, -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From darcy at druid.net Tue Aug 4 10:44:43 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 10:44:43 -0400 Subject: Obtaining Python version In-Reply-To: <2d56febf0908040739i79d4bcc9o461d6641c68f5fb9@mail.gmail.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> <4A784303.2070804@mrabarnett.plus.com> <2d56febf0908040739i79d4bcc9o461d6641c68f5fb9@mail.gmail.com> Message-ID: <20090804104443.72ebffba.darcy@druid.net> On Wed, 5 Aug 2009 00:39:56 +1000 Xavier Ho wrote: > So, what am I doing wrong here? > > >>> int(str(0x00F0), 16) Look at the output of str(0x00F0) for a clue. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From jjposner at optimum.net Tue Aug 4 10:45:24 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 04 Aug 2009 10:45:24 -0400 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: <4A784984.6000903@optimum.net> > Certainly John- although I have not embedded the turtle module at all, > I just wrote my own. OK, then why the statements "from turtle import *" in the modules turtleprocess.py and turtlewidget.py? Tx, John From contact at xavierho.com Tue Aug 4 10:48:39 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 5 Aug 2009 00:48:39 +1000 Subject: Obtaining Python version In-Reply-To: <2d56febf0908040747s1a02f975ke383323e68732e6e@mail.gmail.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> <4A784303.2070804@mrabarnett.plus.com> <2d56febf0908040739i79d4bcc9o461d6641c68f5fb9@mail.gmail.com> <20090804104443.72ebffba.darcy@druid.net> <2d56febf0908040747s1a02f975ke383323e68732e6e@mail.gmail.com> Message-ID: <2d56febf0908040748y41c977c3k96d4437ed35edad@mail.gmail.com> On Wed, Aug 5, 2009 at 12:44 AM, D'Arcy J.M. Cain wrote: > On Wed, 5 Aug 2009 00:39:56 +1000 >> Xavier Ho wrote: >> > So, what am I doing wrong here? >> > >> > >>> int(str(0x00F0), 16) >> >> Look at the output of str(0x00F0) for a clue. >> > > ... Wow. I *am* slow tonight. Thanks. > > >>> int('00F0', 16) > 240 > (oops.) I was mixing the hex literals and the string literals. Thanks a bunch. -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From Samnsparky at gmail.com Tue Aug 4 11:25:28 2009 From: Samnsparky at gmail.com (Sparky) Date: Tue, 4 Aug 2009 08:25:28 -0700 (PDT) Subject: WindowsError: exception: access violation writing 0x00000000 References: <73c6c4f5-a00b-4f95-a85d-0f257b2f001a@c2g2000yqi.googlegroups.com> Message-ID: On Aug 3, 3:29?pm, Sparky wrote: > Hello! I am using cTypes on Windows to interface with a dll and I keep > getting an error when I execute this method: > > def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0): > ? ? ? ? """ > ? ? ? ? Name: U12.eAnalogIn(channel, idNum = None, demo = 0, readD=0) > ? ? ? ? Args: See section 4.4 of the User's Guide > ? ? ? ? Desc: This is a simplified version of Counter. Reads & resets > the counter (CNT). > ? ? ? ? """ > > ? ? ? ? if idNum is None: > ? ? ? ? ? ? idNum = self.id > > ? ? ? ? ljid = ctypes.c_long(idNum) > ? ? ? ? state = ctypes.c_long(999) > > ? ? ? ? ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, > readD, ctypes.byref(state)) > > ? ? ? ? if ecode != 0: raise LabJackException(ecode) > ? ? ? ? if ljid == -1: raise LabJackException(-1, "LabJack not > found.") > > ? ? ? ? return {"idnum":ljid.value, "state":state.value} > > Here is the error message: > Traceback (most recent call last): > ? File "", line 1, in > ? ? device.eDigitalIn(0) > ? File "C:\Documents and Settings\All Users\Documents\Python > \LabJackPython_new\u12.py", line 118, in eDigitalIn > ? ? ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, readD, > ctypes.byref(state)) > WindowsError: exception: access violation writing 0x00000000 > > Here is the signature of the method (which is known to work with C++ > programs): > > long _stdcall EDigitalIn(long *idnum, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long demo, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long channel, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long readD, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long *state); > > staticLib is declared with staticLib = ctypes.windll.LoadLibrary > ("ljackuw"). > > Any ideas? > > Thanks, > Sam One more thing, I seem to be getting back incorrect values for doubles passed by reference. Any suggestions? I am on a 64-bit machine but I should think that should not make a difference. Thanks again, Sam From philip at semanchuk.com Tue Aug 4 11:47:31 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 Aug 2009 11:47:31 -0400 Subject: WindowsError: exception: access violation writing 0x00000000 In-Reply-To: References: <73c6c4f5-a00b-4f95-a85d-0f257b2f001a@c2g2000yqi.googlegroups.com> Message-ID: <2231CCC9-1EDA-4923-8110-20015F3BDA6E@semanchuk.com> On Aug 4, 2009, at 11:25 AM, Sparky wrote: > On Aug 3, 3:29 pm, Sparky wrote: >> Hello! I am using cTypes on Windows to interface with a dll and I >> keep >> getting an error when I execute this method: >> >> def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0): >> """ >> Name: U12.eAnalogIn(channel, idNum = None, demo = 0, readD=0) >> Args: See section 4.4 of the User's Guide >> Desc: This is a simplified version of Counter. Reads & resets >> the counter (CNT). >> """ >> >> if idNum is None: >> idNum = self.id >> >> ljid = ctypes.c_long(idNum) >> state = ctypes.c_long(999) >> >> ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, >> readD, ctypes.byref(state)) >> >> if ecode != 0: raise LabJackException(ecode) >> if ljid == -1: raise LabJackException(-1, "LabJack not >> found.") >> >> return {"idnum":ljid.value, "state":state.value} >> >> Here is the error message: >> Traceback (most recent call last): >> File "", line 1, in >> device.eDigitalIn(0) >> File "C:\Documents and Settings\All Users\Documents\Python >> \LabJackPython_new\u12.py", line 118, in eDigitalIn >> ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, >> readD, >> ctypes.byref(state)) >> WindowsError: exception: access violation writing 0x00000000 >> >> Here is the signature of the method (which is known to work with C++ >> programs): >> >> long _stdcall EDigitalIn(long *idnum, >> long demo, >> long channel, >> long readD, >> long *state); >> >> staticLib is declared with staticLib = ctypes.windll.LoadLibrary >> ("ljackuw"). >> >> Any ideas? >> >> Thanks, >> Sam > > One more thing, I seem to be getting back incorrect values for doubles > passed by reference. Any suggestions? I am on a 64-bit machine but I > should think that should not make a difference. Hi Sam, ctypes is pretty straightforward, and I wouldn't expect it to break on something simple. I looked over your code (warning -- I am a ctypes novice) and it looks OK to me. If you're getting null pointer writes I'd suspect that the call signature isn't what you think it is, perhaps due to a lack of an extern "C" declaration or something like that. In short, I don't think this is a problem in your Python code or in ctypes. But since your Python code is the easiest to change, why not do a quick test of a minimal example? def eDigitalIn_test_version(self, channel, idNum = None, demo = 0, readD=0): ljid = ctypes.c_long(42) state = ctypes.c_long(999) ecode = staticLib.ECount(ctypes.byref(ljid), 0, 0, 0, ctypes.byref(state)) print ecode Does that work any better? You could also try replacing the byref() calls with pointers created by ctypes.pointer(). But I suspect that all this will do is give you confidence that it isn't your Python code that's wrong. You might want to write a minimal C program that invokes ECount. That would help you to prove whether or not you have a working C (not C++!) interface for your function. HTH Philip From cool-rr at cool-rr.com Tue Aug 4 12:04:17 2009 From: cool-rr at cool-rr.com (cool-RR) Date: Tue, 4 Aug 2009 19:04:17 +0300 Subject: Announcing PythonTurtle In-Reply-To: <4A784984.6000903@optimum.net> References: <4A784984.6000903@optimum.net> Message-ID: On Tue, Aug 4, 2009 at 5:45 PM, John Posner wrote: > > Certainly John- although I have not embedded the turtle module at all, >> I just wrote my own. >> > > OK, then why the statements "from turtle import *" in the modules > turtleprocess.py and turtlewidget.py? > > Tx, > John > > It's from a module turtle.py in my own PythonTurtle package. -- Sincerely, Ram Rachum -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at please.post Tue Aug 4 12:07:34 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 16:07:34 +0000 (UTC) Subject: kw param question References: Message-ID: In Steven D'Aprano writes: >On Mon, 03 Aug 2009 19:59:23 +0000, kj wrote: >> I want to write a decorator that, among other things, returns a function >> that has one additional keyword parameter, say foo=None. >> >> When I try >> >> def my_decorator(f): >> # blah, blah >> def wrapper(*p, foo=None, **kw): >> x = f(*p, **kw) >> if (foo): >> # blah, blah >> else >> # blah blah >> return wrapper >> >> ...i get a syntax error where it says "foo=None". I get similar errors >> with everything else I've tried. >> >> Is is possible to do this in Python? >Have you tried this under Python 2.6 or 3.0? >I've run into similar issues, because you can't have keyword-only >arguments in Python 2.5 :( >My solution was to create a decorator that faked them. The docstring is >longer than the decorator itself. >from functools import wraps >def keywords(**defaults): > """Return a decorator which decorates a function to accept keyword > arguments. > Python 2.5 and earlier don't allow keyword-only arguments for > non-builtin functions. The obvious syntax: > def func(x, *args, key=None, word='parrot'): > is not permitted. As a work-around, write your function something > like the following example: > >>> @keywords(key=None, word='parrot') > ... def func(x, y=0, *args, **kwargs): > ... # Inside the function, we can guarantee that kwargs['key'] and > ... # kwargs['word'] both exist, and no other keys. > ... print "x=%s, y=%s, args=%s" % (x, y, args) > ... if kwargs['key'] is None: msg = "kwargs['key'] is None" > ... else: msg = "kwargs['key'] is something else" > ... msg += " and kwargs['word'] is %r" % kwargs['word'] > ... print msg > ... > When you call func, if you don't provide a keyword-only argument, the > default will be substituted: > >>> func(1, 2, 3, 4) > x=1, y=2, args=(3, 4) > kwargs['key'] is None and kwargs['word'] is 'parrot' > >>> func(1) > x=1, y=0, args=() > kwargs['key'] is None and kwargs['word'] is 'parrot' > Naturally you can provide your own values for keyword-only arguments: > >>> func(1, 2, 3, word='spam') > x=1, y=2, args=(3,) > kwargs['key'] is None and kwargs['word'] is 'spam' > >>> func(1, 2, 3, word='spam', key=len) > x=1, y=2, args=(3,) > kwargs['key'] is something else and kwargs['word'] is 'spam' > If you pass an unexpected keyword argument, TypeError is raised: > >>> #doctest:+IGNORE_EXCEPTION_DETAIL > ... func(1, 2, 3, 4, keyword='something') > Traceback (most recent call last): > ... > TypeError: ... > """ > def decorator(func): > """Decorate func to allow keyword-only arguments.""" > @wraps(func) > def f(*args, **kwargs): > for key in kwargs: > if key not in defaults: > raise TypeError( > "'%s' is an invalid keyword argument for " \ > "this function" % key > ) > d = defaults.copy() > d.update(kwargs) > return func(*args, **d) > return f > return decorator Thanks for this. It's very useful. A lot of stuff for me to chew on. kynn From MatzeGuentert at gmx.de Tue Aug 4 12:27:40 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Tue, 04 Aug 2009 18:27:40 +0200 Subject: M2Crypto: X509.X509_Extension_Stack() throws AssertionError In-Reply-To: References: Message-ID: <1249403260.3396.6.camel@celsius> > > cert_extension_2 = X509.new_extension("keyUsage", "101000000") > > Maybe your OpenSSL is too old. keyUsage needs to be defined in OpenSSL > obj_dat.h file for this to work. I am using OpenSSL version 0.9.8k-fips which is the latest version. I replaced: cert_extension_2 = X509.new_extension("keyUsage", "101000000") with: cert_extension_2 = X509.new_extension("keyUsage", "keyCertSign, cRLSign") which worked for me. Also I found an easy way to iterate through the extension stack using: cert = X509.X509() for e in cert_extension_stack: cert.add_ext(e) > > cert_extension_3 = X509.new_extension("subjectAlternativeName", > > "DNS:www.mydomain.tld") > And I believe you mispelled this, try subjectAltName. Changing "subjectAlternativeName" to "subjectAltName" did the trick. Thank you! From MatzeGuentert at gmx.de Tue Aug 4 12:51:39 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Tue, 04 Aug 2009 18:51:39 +0200 Subject: M2Crypto: How to generate subjectKeyIdentifier / authorityKeyIdentifier Message-ID: <1249404699.3396.30.camel@celsius> Hello I am trying to add the extensions "subjectKeyIdentifier" and "authorityKeyIdentifier" to a x509v3 certificate. Regarding rfc5280, section 4.2.1.2 the key identifier is composed of the 160-bit SHA-1 hash of the BIT STRING subjectPublicKey http://tools.ietf.org/html/rfc5280#section-4.2.1.2 I don't know how or which function to use from EVP.PKey() to compose a fingerprint from the public key, as you can see below I was playing around with some functions, which simply returned nonsense (at least for me) I would be happy if someone could provide some example code on how to generate a fingerprint from the public key. "print keyp.final()" nor "print keyp.sign_final() on the last line does return anything... -------------------------------------------------------- from M2Crypto import X509, m2, RSA, EVP from config import * import os.path class Keypair(object): def __init__(self): self.config = Config() self.keypair = EVP.PKey() def create_keypair(self, key_size=1024): # generate an RSA key pair # OpenSSL book page 232 # second argument should be a constant RSA_F4 or RSA_3 rsa_key_pair = RSA.gen_key(key_size, m2.RSA_F4) # check if RSA key pair is usable # OpenSSL book page 232 if rsa_key_pair.check_key() != 1: print 'error while generating key!' sys.exit() # EVP object which can hold either a DSA or an RSA object # OpenSSL book page 236 evp_key_container = EVP.PKey() evp_key_container.assign_rsa(rsa_key_pair) self.keypair = evp_key_container def save_keypair(self, filename): if not os.path.exists(filename): self.keypair.save_key(filename, None) else: print "error in save_keypair(): cannot save key, it already exists" def load_keypair(self, filename): try: self.keypair = EVP.load_key(filename) except TypeError: print "error in load_keypair(): maybe file does not exist?" def get_keypair(self): return self.keypair def get_public_key(self): return self.keypair.pkey def print_keypair(self): print self.keypair.as_pem(None) if __name__ == "__main__": keypair = Keypair() keypair.create_keypair() # keypair.save_keypair("test.keys") keyp = keypair.get_keypair() print keyp.final() print keyp.sign_final() --------------------------------------------------------- And this maybe some OT question but how can I use OpenSSL to generate some fingerprint for testing and comparison purpose? For example I have got a certificate client.crt and the keys client.key $ openssl x509 -noout -text -in client.crt [...] X509v3 Subject Key Identifier: D2:C0:39:37:45:F6:A3:BF:D8:91:A2:F5:C7:43:42:80:6A:3C:38:AF X509v3 Authority Key Identifier: A7:E2:2E:59:F8:53:1F:68:F2:59:34:32:42:F6:21:20:C0:D1:3A:89 [...] But openssl provides me different fingerprint... so whats wrong here? $ openssl rsa -pubout -in client_1.key | openssl sha1 -c writing RSA key cc:d2:ab:16:1f:a1:23:3e:fe:45:03:ab:4f:86:57:65:52:16:b2:1a From bartsmeets86 at gmail.com Tue Aug 4 12:52:05 2009 From: bartsmeets86 at gmail.com (Bart Smeets) Date: Tue, 4 Aug 2009 18:52:05 +0200 Subject: easy_install: unresolved external symbol In-Reply-To: <87f2eede5ce0f1391994db66153e3c96@preisshare.net> References: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> <2119ee90908040152k5a744f98l7d5bc7da755948a2@mail.gmail.com> <87f2eede5ce0f1391994db66153e3c96@preisshare.net> Message-ID: <2119ee90908040952p6233d28ek99584bcd4f5f6f42@mail.gmail.com> How do I give the option to link to the ez_setup.py? 2009/8/4 David Lyon > On Tue, 4 Aug 2009 10:52:20 +0200, Bart Smeets > wrote: > > I could ofcourse use cxfreeze's binary package. But bbfreeze is not > > available as a binary. I would love to get easy_install to work. But I > have > > no idea what's going wrong here. > > What is going on is that setuptools does some very 'advanced' things. > > The best you can do is give the option to link to the ez_setup.py > install script and let the users install it them themselves... > > David > -------------- next part -------------- An HTML attachment was scrubbed... URL: From r.a.teterin at gmail.com Tue Aug 4 13:08:45 2009 From: r.a.teterin at gmail.com (Roman) Date: Tue, 4 Aug 2009 21:08:45 +0400 Subject: Trying to get ABC to work In-Reply-To: <358094.5069.qm@web65302.mail.ac2.yahoo.com> References: <358094.5069.qm@web65302.mail.ac2.yahoo.com> Message-ID: <20090804170845.GA3092@localhost> Following code works, although I'm not sure that it's exactly what you want: import abc class MetaExample(abc.ABCMeta): def __new__(mcs, name, bases, ns): ns['cls_meth'] = mcs.cls_meth if not 'cls_abc' in ns: ns['cls_abc'] = mcs.cls_abc return super().__new__(mcs, name, bases, ns) def cls_meth(cls): print('Class method defined stub') @abc.abstractmethod def cls_abc(cls): try: print('Class-Abstract method defined stub') except NotImplementedError as err: print('Must implement cls_abc') except: print('General exception at cls_abc method') That's how I've tested it: class Test1(object, metaclass=MetaExample): def cls_abc(self): print("method of", self) class Test2(object, metaclass=MetaExample): pass test1 = Test1() test1.cls_meth() test1.cls_abc() test2 = Test2() Output: Class method defined stub method of <__main__.Test1 object at 0xb7b5f52c> Traceback (most recent call last): File "/tmp/test.py", line 32, in test2 = Test2() TypeError: Can't instantiate abstract class Test2 with abstract methods cls_abc According to the documentation, @abstractmethod "requires that the metaclass is ABCMeta or derived from it", so I've changed base class from type to ABCMeta. Also I don't think that using try/except inside the abstract method will work, maybe it would be better to check presence of all required methods directly inside the metaclass, without @abstractmethod decorator. From holger at merlinux.eu Tue Aug 4 13:19:16 2009 From: holger at merlinux.eu (holger krekel) Date: Tue, 4 Aug 2009 19:19:16 +0200 Subject: pylib/py.test 1.0.0 released Message-ID: <20090804171915.GS31589@trillke.net> Hello everyone, i am happy to announce pylib/py.test 1.0.0, a MIT-licensed library geared towards advanced testing and elastic distributed programming with Python. It features the mature cross-project py.test automated testing tool with many new features, aiming to: * allow writing zero-boilerplate automated tests in Python * offer strong debugging and reporting of test failures * rapidly run and ad-hoc distribute tests to multiple CPUs/platforms * support unit-, functional and integration testing * be easy to extend and tackle growing testing needs, (current prime example oejskit, a live-browser javascript unittesting 3rd party plugin) Please check things out at: http://pytest.org or read the blogged release announcement: http://tetamap.wordpress.com/2009/08/04/pylib-1-0-0 or read on for some ... Distinctive new features shipping with py.test 1.0.0 ------------------------------------------------------ For those already knowing about the older 0.9.2 release or being experienced with other testing approaches i'll try to give a summary of the distinctive testing features shipping with 1.0.0: * test function arguments ("funcargs"): With this, python test functions can name arguments and one writes factory functions to provide instances for such "fixture" arguments. This page http://codespeak.net/py/dist/test/funcargs.html contains reference info and tutorial examples. Test function arguments also allow for natural test parametrization - one provides several different argument values, no changes to the test function needed, no magic "yield" for generating tests anymore - although 1.0 still allows them and of course still supports traditional xUnit-style setup_module/class/function or (new) direct runs of unittest.TestCase style tests. * distributed testing: distributing test runs among Linux/OSX/Windows hosts and across python-2.4 till python-2.6 interpreters works reasonably stable now. This means that you can easily iron out test-module/function specific problems across a variety of platforms, accelerating the change & test feedback cycle. * xfail: a new way to mark tests as "expected to fail" which means they run normally but are reported/counted specially. This "xfail" mark is meant to mark missing / wrong implementation rather than missing dependencies / wrong platforms for which one uses "skip". Especially for larger test suites making this distinction is very helpful. * IO-capturing: output of test functions is captured per-test, by default including any output from sub processes. This works on all platforms and also (now) interacts well with the logging module without importing/using it itself so there are no interferences. * pastebin: new command line option "--pastebin" to send your test session output or individual test failures to the Pocoo pastebin service and prints out URLs. Convenient for quick IRC/messaging communication. * plugins: it is now easy to write plugins by implementing one or more of the 37 hooks which py.test calls to implement the testing process. There are many examples, among them the "oejskit" plugin which integrates testing of javascript code in real-life browsers into a regular test run. Apart from such separately distributed "cross-project" plugins you can also write per-project plugins/extensions that lives with your testing code. cheers & have fun, holger -- Metaprogramming, Python, Testing: http://tetamap.wordpress.com Python, PyPy, pytest contracting: http://merlinux.eu From Samnsparky at gmail.com Tue Aug 4 13:23:10 2009 From: Samnsparky at gmail.com (Sparky) Date: Tue, 4 Aug 2009 10:23:10 -0700 (PDT) Subject: WindowsError: exception: access violation writing 0x00000000 References: <73c6c4f5-a00b-4f95-a85d-0f257b2f001a@c2g2000yqi.googlegroups.com> Message-ID: <26927cc2-2134-46b6-873a-02be9cf829f2@h21g2000yqa.googlegroups.com> On Aug 4, 9:47?am, Philip Semanchuk wrote: > On Aug 4, 2009, at 11:25 AM, Sparky wrote: > > > > > > > On Aug 3, 3:29 pm, Sparky wrote: > >> Hello! I am using cTypes on Windows to interface with a dll and I ? > >> keep > >> getting an error when I execute this method: > > >> def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0): > >> ? ? ? ? """ > >> ? ? ? ? Name: U12.eAnalogIn(channel, idNum = None, demo = 0, readD=0) > >> ? ? ? ? Args: See section 4.4 of the User's Guide > >> ? ? ? ? Desc: This is a simplified version of Counter. Reads & resets > >> the counter (CNT). > >> ? ? ? ? """ > > >> ? ? ? ? if idNum is None: > >> ? ? ? ? ? ? idNum = self.id > > >> ? ? ? ? ljid = ctypes.c_long(idNum) > >> ? ? ? ? state = ctypes.c_long(999) > > >> ? ? ? ? ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, > >> readD, ctypes.byref(state)) > > >> ? ? ? ? if ecode != 0: raise LabJackException(ecode) > >> ? ? ? ? if ljid == -1: raise LabJackException(-1, "LabJack not > >> found.") > > >> ? ? ? ? return {"idnum":ljid.value, "state":state.value} > > >> Here is the error message: > >> Traceback (most recent call last): > >> ? File "", line 1, in > >> ? ? device.eDigitalIn(0) > >> ? File "C:\Documents and Settings\All Users\Documents\Python > >> \LabJackPython_new\u12.py", line 118, in eDigitalIn > >> ? ? ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, ? > >> readD, > >> ctypes.byref(state)) > >> WindowsError: exception: access violation writing 0x00000000 > > >> Here is the signature of the method (which is known to work with C++ > >> programs): > > >> long _stdcall EDigitalIn(long *idnum, > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long demo, > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long channel, > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long readD, > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long *state); > > >> staticLib is declared with staticLib = ctypes.windll.LoadLibrary > >> ("ljackuw"). > > >> Any ideas? > > >> Thanks, > >> Sam > > > One more thing, I seem to be getting back incorrect values for doubles > > passed by reference. Any suggestions? I am on a 64-bit machine but I > > should think that should not make a difference. > > Hi Sam, > ctypes is pretty straightforward, and I wouldn't expect it to break on ? > something simple. I looked over your code (warning -- I am a ctypes ? > novice) and it looks OK to me. If you're getting null pointer writes ? > I'd suspect that the call signature isn't what you think it is, ? > perhaps due to a lack of an extern "C" declaration or something like ? > that. In short, I don't think this is a problem in your Python code or ? > in ctypes. > > But since your Python code is the easiest to change, why not do a ? > quick test of a minimal example? > > def eDigitalIn_test_version(self, channel, idNum = None, demo = 0, ? > readD=0): > ? ? ? ? ?ljid = ctypes.c_long(42) > ? ? ? ? ?state = ctypes.c_long(999) > > ? ? ? ? ?ecode = staticLib.ECount(ctypes.byref(ljid), 0, 0, 0, ? > ctypes.byref(state)) > > ? ? ? ? ?print ecode > > Does that work any better? > > You could also try replacing the byref() calls with pointers created ? > by ctypes.pointer(). But I suspect that all this will do is give you ? > confidence that it isn't your Python code that's wrong. > > You might want to write a minimal C program that invokes ECount. That ? > would help you to prove whether or not you have a working C (not C++!) ? > interface for your function. > > HTH > Philip Hey Philip, Thank you for your response. It turns out I was calling a function that I was not intending on calling, so it was not a Python problem. Thanks, Sam From jay.bird0804 at gmail.com Tue Aug 4 14:15:47 2009 From: jay.bird0804 at gmail.com (Jay Bird) Date: Tue, 4 Aug 2009 11:15:47 -0700 (PDT) Subject: Overlap in python Message-ID: Hi everyone, I've been trying to figure out a simple algorithm on how to combine a list of parts that have 1D locations that overlap into a non- overlapping list. For example, here would be my input: part name location a 5-9 b 7-10 c 3-6 d 15-20 e 18-23 And here is what I need for an output: part name location c.a.b 3-10 d.e 15-23 I've tried various methods, which all fail. Does anyone have an idea how to do this? Thank you very much! Jay From marcusw at cox.net Tue Aug 4 14:31:49 2009 From: marcusw at cox.net (Marcus Wanner) Date: Tue, 4 Aug 2009 11:31:49 -0700 (PDT) Subject: Overlap in python References: Message-ID: <3f11f316-5e9e-4786-8757-edf9ab234bb7@j32g2000yqh.googlegroups.com> On Aug 4, 2:15?pm, Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. ?For example, here would be my input: > > part name ? location > a ? ? ? ? ? ? ? ? ?5-9 > b ? ? ? ? ? ? ? ? ?7-10 > c ? ? ? ? ? ? ? ? ?3-6 > d ? ? ? ? ? ? ? ? ?15-20 > e ? ? ? ? ? ? ? ? ?18-23 > > And here is what I need for an output: > part name ? location > c.a.b ? ? ? ? ? ?3-10 > d.e ? ? ? ? ? ? ? 15-23 > > I've tried various methods, which all fail. ?Does anyone have an idea > how to do this? > > Thank you very much! > Jay Just take all the values, put them in a list, and use min() and max(). For example: import string def makelist(values): values = string.replace(values, ' ', '') listofvaluepairs = string.split(values, ',') listofvalues = [] for pair in listofvaluepairs: twovalues = string.split(pair, '-') listofvalues.append(int(twovalues[0])) listofvalues.append(int(twovalues[1])) return listofvalues values = '5-9, 7-10, 3-6' values = makelist(values) print('Values: %d-%d' %(min(values), max(values)) ) Marcus From anna.konstorum at gmail.com Tue Aug 4 14:46:14 2009 From: anna.konstorum at gmail.com (Ann) Date: Tue, 4 Aug 2009 11:46:14 -0700 (PDT) Subject: Overlap in python References: <3f11f316-5e9e-4786-8757-edf9ab234bb7@j32g2000yqh.googlegroups.com> Message-ID: On Aug 4, 11:31?am, Marcus Wanner wrote: > On Aug 4, 2:15?pm, Jay Bird wrote: > > > > > Hi everyone, > > > I've been trying to figure out a simple algorithm on how to combine a > > list of parts that have 1D locations that overlap into a non- > > overlapping list. ?For example, here would be my input: > > > part name ? location > > a ? ? ? ? ? ? ? ? ?5-9 > > b ? ? ? ? ? ? ? ? ?7-10 > > c ? ? ? ? ? ? ? ? ?3-6 > > d ? ? ? ? ? ? ? ? ?15-20 > > e ? ? ? ? ? ? ? ? ?18-23 > > > And here is what I need for an output: > > part name ? location > > c.a.b ? ? ? ? ? ?3-10 > > d.e ? ? ? ? ? ? ? 15-23 > > > I've tried various methods, which all fail. ?Does anyone have an idea > > how to do this? > > > Thank you very much! > > Jay > > Just take all the values, put them in a list, and use min() and max(). > For example: > > import string > > def makelist(values): > ? ? values = string.replace(values, ' ', '') > ? ? listofvaluepairs = string.split(values, ',') > ? ? listofvalues = [] > ? ? for pair in listofvaluepairs: > ? ? ? ? twovalues = string.split(pair, '-') > ? ? ? ? listofvalues.append(int(twovalues[0])) > ? ? ? ? listofvalues.append(int(twovalues[1])) > ? ? return listofvalues > > values = '5-9, 7-10, 3-6' > values = makelist(values) > print('Values: %d-%d' %(min(values), max(values)) ) > > Marcus Thank you for your help, this is a very nice program but it does not address the issue that I have values that do not overlap, for example 'c' and 'd' do not overlap in the above example and thus I would not want to output 3-20 but the individual positions instead. In addition, my inputs are not ordered from smallest to largest, thus I could have a situation where a=5-9, b=15-20, c=7-10, etc., and I would still want an output of: a.c = 5-10, b=15-20. I apologize for the complication. Thank you again! Jay From aurele.tux at gmail.com Tue Aug 4 14:53:56 2009 From: aurele.tux at gmail.com (aurelien) Date: Tue, 04 Aug 2009 20:53:56 +0200 Subject: Is it possible to have the python color in the terminal ? Message-ID: <1249412036.5765.20.camel@r2d2> Hello, I am under gNewSense, i am a newbbie on Python, i look for how change the color terminal when python run. at the step >>> all is in black and white. Is it possible to have the python color in the terminal ? Thanks for your help. aurelien From marcusw at cox.net Tue Aug 4 14:55:22 2009 From: marcusw at cox.net (Marcus Wanner) Date: Tue, 04 Aug 2009 14:55:22 -0400 Subject: Overlap in python In-Reply-To: References: <3f11f316-5e9e-4786-8757-edf9ab234bb7@j32g2000yqh.googlegroups.com> Message-ID: On 8/4/2009 2:46 PM, Ann wrote: > On Aug 4, 11:31 am, Marcus Wanner wrote: >> On Aug 4, 2:15 pm, Jay Bird wrote: >> >> >> >>> Hi everyone, >>> I've been trying to figure out a simple algorithm on how to combine a >>> list of parts that have 1D locations that overlap into a non- >>> overlapping list. For example, here would be my input: >>> part name location >>> a 5-9 >>> b 7-10 >>> c 3-6 >>> d 15-20 >>> e 18-23 >>> And here is what I need for an output: >>> part name location >>> c.a.b 3-10 >>> d.e 15-23 >>> I've tried various methods, which all fail. Does anyone have an idea >>> how to do this? >>> Thank you very much! >>> Jay >> Just take all the values, put them in a list, and use min() and max(). >> For example: >> >> import string >> >> def makelist(values): >> values = string.replace(values, ' ', '') >> listofvaluepairs = string.split(values, ',') >> listofvalues = [] >> for pair in listofvaluepairs: >> twovalues = string.split(pair, '-') >> listofvalues.append(int(twovalues[0])) >> listofvalues.append(int(twovalues[1])) >> return listofvalues >> >> values = '5-9, 7-10, 3-6' >> values = makelist(values) >> print('Values: %d-%d' %(min(values), max(values)) ) >> >> Marcus > > Thank you for your help, this is a very nice program but it does not > address the issue that I have values that do not overlap, for example > 'c' and 'd' do not overlap in the above example and thus I would not > want to output 3-20 but the individual positions instead. In > addition, my inputs are not ordered from smallest to largest, thus I > could have a situation where a=5-9, b=15-20, c=7-10, etc., and I would > still want an output of: a.c = 5-10, b=15-20. I apologize for the > complication. > > Thank you again! > > Jay That would be a bit more complicated...you might try using tuples of values in a list, or writing your own class for the data handling. Unfortunately that's not something I can just sit down and code in 5 minutes, it would take some careful thought and planning. Marcus From marcusw at cox.net Tue Aug 4 15:00:32 2009 From: marcusw at cox.net (Marcus Wanner) Date: Tue, 04 Aug 2009 15:00:32 -0400 Subject: Is it possible to have the python color in the terminal ? In-Reply-To: <1249412036.5765.20.camel@r2d2> References: <1249412036.5765.20.camel@r2d2> Message-ID: On 8/4/2009 2:53 PM, aurelien wrote: > Hello, > > I am under gNewSense, i am a newbbie on Python, i look for how change > the color terminal when python run. > at the step >>> all is in black and white. > Is it possible to have the python color in the terminal ? > > Thanks for your help. > > aurelien > You might try posting to this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/58df7b77394e4666/f4c13766a1e09380 I don't know much about the question myself, though. Marcus From breamoreboy at yahoo.co.uk Tue Aug 4 15:10:52 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 04 Aug 2009 20:10:52 +0100 Subject: Overlap in python In-Reply-To: References: Message-ID: Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 > > I've tried various methods, which all fail. Does anyone have an idea > how to do this? > > Thank you very much! > Jay I haven't tried but could you adapt this:- data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] for k, g in groupby(enumerate(data), lambda (i,x):i-x): print map(itemgetter(1), g) found here http://www.python.org/doc/2.6.2/library/itertools.html#module-itertools -- Kindest regards. Mark Lawrence. From kosta.koeman at gmail.com Tue Aug 4 15:13:10 2009 From: kosta.koeman at gmail.com (Kosta) Date: Tue, 4 Aug 2009 12:13:10 -0700 (PDT) Subject: Using Python to automate builds Message-ID: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> I am a Python newbie, tasked with automating (researching) building Windows drivers using the WDK build environment. I've been looking into Python for this (instead of writing a bunch of batch files). What I would like to do, is to open a cmd window, and start a Python script. This script would then (based upon input arguments), build different flavors of the driver (fre, chk, x86, x64) and do some post processing (create cat files, sign, etc.). I was hoping to take advantage as much as possible of exisiting infrastructure from the WDK. I am able to call setenv.bat and provide all the input parameters. One of the things setenv.bat does is change the path environment variable. However, this is not captured by Python. I could duplicate the functionality, but I'd rather not. Is there a way to capture all enviroment variable changes being made by a batch file from Python? Thanks! From aurele.tux at gmail.com Tue Aug 4 15:20:03 2009 From: aurele.tux at gmail.com (aurelien) Date: Tue, 4 Aug 2009 12:20:03 -0700 (PDT) Subject: Is it possible to have the python color in the terminal ? Message-ID: Hello, I am under gNewSense, i am a newbbie on Python, i look for how change the color terminal when python run. at the step >>> all is in black and white. Is it possible to have the python color in the terminal ? Thanks for your help aurelien From aurele.tux at gmail.com Tue Aug 4 15:23:24 2009 From: aurele.tux at gmail.com (aurelien) Date: Tue, 04 Aug 2009 21:23:24 +0200 Subject: Is it possible to have the python color in the terminal ? In-Reply-To: References: <1249412036.5765.20.camel@r2d2> Message-ID: <1249413804.5765.24.camel@r2d2> > You might try posting to this thread: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/58df7b77394e4666/f4c13766a1e09380 > I don't know much about the question myself, though. > > Marcus Thanks for your help ! aurelien From no.email at please.post Tue Aug 4 15:29:00 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 19:29:00 +0000 (UTC) Subject: no-clobber dicts? References: Message-ID: In Steven D'Aprano writes: >On Mon, 03 Aug 2009 21:07:32 +0000, kj wrote: >> I use the term "no-clobber dict" to refer to a dictionary D with the >> especial property that if K is in D, then >> >> D[K] = V >> >> will raise an exception unless V == D[K]. In other words, D[K] can be >> set if K doesn't exist already among D's keys, or if the assigned value >> is equal to the current value of D[K]. All other assignments to D[K] >> trigger an exception. >Coincidentally, I just built something very close to what you ask. Here >it is: >class ConstantNamespace(dict): > """Dictionary with write-once keys.""" > def __delitem__(self, key): > raise TypeError("can't unbind constants") > def __setitem__(self, key, value): > if key in self: > raise TypeError("can't rebind constants") > super(ConstantNamespace, self).__setitem__(key, value) > def clear(self): > raise TypeError('cannot unbind constants') > def pop(self, key, *args): > raise TypeError("cannot pop constants") > def popitem(self): > raise TypeError("cannot pop constants") > def update(self, other): > for key in other: > if key in self: > raise TypeError('cannot update constants') > # If we get here, then we're not modifying anything, > # so okay to proceed. > super(ConstantNamespace, self).update(other) > def copy(self): > c = self.__class__(**self) > return c Thanks. As you note this not quite what I'm looking for, but it's a good template for it. kynn From no.email at please.post Tue Aug 4 15:30:51 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 19:30:51 +0000 (UTC) Subject: no-clobber dicts? References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: In Chris Rebert writes: >On Mon, Aug 3, 2009 at 2:47 PM, r wrote: >> On Aug 3, 4:07=C2=A0pm, kj wrote: >>> I use the term "no-clobber dict" to refer to a dictionary D with >>> the especial property that if K is in D, then >>> >>> =C2=A0 D[K] =3D V >>> >>> will raise an exception unless V =3D=3D D[K]. =C2=A0In other words, D[K] >>> can be set if K doesn't exist already among D's keys, or if the >>> assigned value is equal to the current value of D[K]. =C2=A0All other >>> assignments to D[K] trigger an exception. >>> >>> The idea here is to detect inconsistencies in the data. >>> >>> This is a data structure I often need. =C2=A0Before I re-invent the >>> wheel, I thought I'd ask: is it already available? >>> >>> TIA! >>> >>> kynn >> >> Not sure if something like this already exists, but it would be >> trivial to implement by overriding dict.__setitem__() >That is, if you don't care about .update() not preserving the >invariant. The implication here is that .update() does not in turn use .__setitem__(), which I find a bit surprising. kynn From r.a.teterin at gmail.com Tue Aug 4 15:54:10 2009 From: r.a.teterin at gmail.com (Roman) Date: Tue, 4 Aug 2009 23:54:10 +0400 Subject: Is it possible to have the python color in the terminal ? In-Reply-To: References: Message-ID: <20090804195410.GA3247@localhost> On 04/08/09 12:20, aurelien wrote: > Hello, > > I am under gNewSense, i am a newbbie on Python, i look for how change > the color terminal when python run. > at the step >>> all is in black and white. > Is it possible to have the python color in the terminal ? > > Thanks for your help > > aurelien > -- > http://mail.python.org/mailman/listinfo/python-list > If you want to get colourful output, you can use IPython (http://ipython.scipy.org/moin/FrontPage), it is an enhanced Python shell. You may also change colour of text by printing appropriate escape sequences (e.g. executing print("\033[0;32m") in Python interpreter should change foreground colour to green. From gregor.lingl at aon.at Tue Aug 4 15:57:40 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 21:57:40 +0200 Subject: Overlap in python In-Reply-To: References: Message-ID: <4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> Jay Bird schrieb: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 > Suppose you have your data given as a dictionary: data = {'a':(5,9), 'b':(7,10), 'c':(3,6), 'd':(15,20), 'e':(18,23)} Then the following not particularly elegant but very simple and straight forward algorithm will solve your problem: def values(key): return set(range(data[key][0], data[key][1]+1)) keys = list(data.keys()) result = [] while keys: k = [keys[0]] keys = keys[1:] v = values(k[0]) for l in keys[:]: if v.intersection(values(l)): v.update(values(l)) k.append(l) keys.remove(l) result.append((k,v)) # print(result) ## if you like for k, v in result: print(".".join(sorted(k)), "%d-%d" % (min(v), max(v))) Regards, Gregor > I've tried various methods, which all fail. Does anyone have an idea > how to do this? > > Thank you very much! > Jay From info at egenix.com Tue Aug 4 15:58:40 2009 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Tue, 04 Aug 2009 21:58:40 +0200 Subject: ANN: eGenix pyOpenSSL Distribution 0.9.0-0.9.8k now also in .egg format Message-ID: <4A7892F0.3080805@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com pyOpenSSL Distribution Version 0.9.0-0.9.8k An easy to install and use repackaged distribution of the pyOpenSSL Python interface for OpenSSL - available on Windows, Mac OS X and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.9.0-0.9.8k-1-Update.html ________________________________________________________________________ INTRODUCTION The eGenix.com pyOpenSSL Distribution includes everything you need to get started with SSL in Python. It comes with an easy to use installer that includes the most recent OpenSSL library versions in pre-compiled form. pyOpenSSL is an open-source Python add-on (http://pyopenssl.sf.net/) that allows writing SSL aware networking applications as well as certificate management tools. OpenSSL is an open-source implementation of the SSL protocol (http://www.openssl.org/). For more information, please see the product page: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ NEWS Due to popular demand, we've added .egg file versions for Windows and Linux to the available download options. This should make things easier for people using e.g. zc.buildout and other egg-file based installers. As always, binaries include both pyOpenSSL and the necessary OpenSSL libraries. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ UPGRADING Before installing this version of pyOpenSSL, please make sure that you uninstall any previously installed pyOpenSSL version. Otherwise, you could end up not using the included OpenSSL libs. _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Aug 04 2009) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From no.email at please.post Tue Aug 4 16:01:12 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 20:01:12 +0000 (UTC) Subject: no-clobber dicts? References: Message-ID: In Steven D'Aprano writes: >class ConstantNamespace(dict): >I also have a series of unit tests for it if you're interested in them. Actually, come to think of it, I think I'll take you up on this. I'd love to see those tests. Unit testing in Python is in area I need to work on. TIA! kynn From dickinsm at gmail.com Tue Aug 4 16:03:00 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 4 Aug 2009 13:03:00 -0700 (PDT) Subject: Overlap in python References: Message-ID: <78d86d92-d373-4163-a418-600a3eb36ab3@o15g2000yqm.googlegroups.com> On Aug 4, 7:15?pm, Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. ?For example, here would be my input: > > part name ? location > a ? ? ? ? ? ? ? ? ?5-9 > b ? ? ? ? ? ? ? ? ?7-10 > c ? ? ? ? ? ? ? ? ?3-6 > d ? ? ? ? ? ? ? ? ?15-20 > e ? ? ? ? ? ? ? ? ?18-23 > > And here is what I need for an output: > part name ? location > c.a.b ? ? ? ? ? ?3-10 > d.e ? ? ? ? ? ? ? 15-23 > > I've tried various methods, which all fail. ?Does anyone have an idea > how to do this? Here's an approach that might work. Turning it into a sensible function and parsing input/massaging output properly are left as an exercise. Blocks that just touch (e.g. (3, 6) then (6, 9)) are amalgamated; if this isn't what you want, and they should be treated as separate instead, then replace 'Stop' with 'Finish' (or any other string that sorts before 'Start'). input = [ ('a', (5, 9)), ('b', (7, 10)), ('c', (3, 6)), ('d', (15, 20)), ('e', (18, 23)), ] # create sorted list of points where an interval is entered or left transitions = [] for name, (start, stop) in input: transitions.extend([(start, 'Start', name), (stop, 'Stop', name)]) transitions.sort() # scan list, accumulating blocks along the way. count = 0 for i, (pt, startend, name) in enumerate(transitions): if startend == 'Start': if not count: start = pt names = [] count += 1 names.append(name) else: count -= 1 if not count: print '.'.join(names), "%s--%s" % (start, pt) The output that I get from this under Python 2.6 is: c.a.b 3--10 d.e 15--23 -- Mark From clp2 at rebertia.com Tue Aug 4 16:03:08 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 Aug 2009 13:03:08 -0700 Subject: no-clobber dicts? In-Reply-To: References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: <50697b2c0908041303ycf7a2f2g47b2b2eebf723d32@mail.gmail.com> On Tue, Aug 4, 2009 at 12:30 PM, kj wrote: > In Chris Rebert writes: > >>On Mon, Aug 3, 2009 at 2:47 PM, r wrote: >>> On Aug 3, 4:07=C2=A0pm, kj wrote: >>>> I use the term "no-clobber dict" to refer to a dictionary D with >>>> the especial property that if K is in D, then >>>> >>>> =C2=A0 D[K] =3D V >>>> >>>> will raise an exception unless V =3D=3D D[K]. =C2=A0In other words, D[K] >>>> can be set if K doesn't exist already among D's keys, or if the >>>> assigned value is equal to the current value of D[K]. =C2=A0All other >>>> assignments to D[K] trigger an exception. >>>> >>>> The idea here is to detect inconsistencies in the data. >>>> >>>> This is a data structure I often need. =C2=A0Before I re-invent the >>>> wheel, I thought I'd ask: is it already available? >>>> >>>> TIA! >>>> >>>> kynn >>> >>> Not sure if something like this already exists, but it would be >>> trivial to implement by overriding dict.__setitem__() > >>That is, if you don't care about .update() not preserving the >>invariant. > > The implication here is that .update() does not in turn use > .__setitem__(), which I find a bit surprising. The builtin types are allowed to take such shortcuts for performance reasons. Cheers, Chris -- http://blog.rebertia.com From dciphercomputing at gmail.com Tue Aug 4 16:05:10 2009 From: dciphercomputing at gmail.com (Simon) Date: Tue, 4 Aug 2009 13:05:10 -0700 (PDT) Subject: Newbie Question regarding __init__() References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> Message-ID: <20295b74-b630-47bd-b48d-9881bc6453a7@g6g2000vbr.googlegroups.com> On Aug 3, 11:00?pm, Dave Angel wrote: > Simon wrote: > > On Aug 2, 5:51 am, Dave Angel wrote: > > >> > >> I don't understand your comparison to Foxpro. ?read on. > > >> As your code was last posted, you don't need a return value from > >> init_Exec() ?Every function that doesn't have an explicit return will > >> return None. ?And None is interpreted as False in an "and" expression. ? > >> If you had an "if" around the whole thing, then you'd care. > > >> DaveA > > > All I meant by the FoxPro comment was the idea of using the equal sign > > without a variable to throw away the result. ?Also in FoxPro there is > > no such thing as automatically returning None. ?If there is no > > explicit return then True is returned. > > > Thanks I did not know that None is interpreted as False. > > > Simon > > To throw away the result of an expression in Python is even easier. ? > Just don't use it. > ? ? ? ?func1() and func2() > is a valid expression whose result is not used. ?And func2()'s result is > therefore irrelevant. ?But shortcircuiting means that func2() is only > called if func1() returned False (or something equivalent to it, like 0 > or an empty list) Thanks for telling me how Python throws away the result. Secondly my code works perfectly now that I am properly defining my methods using "self". From 1x7y2z9 at gmail.com Tue Aug 4 16:11:18 2009 From: 1x7y2z9 at gmail.com (1x7y2z9) Date: Tue, 4 Aug 2009 13:11:18 -0700 (PDT) Subject: boolean OR gotcha Message-ID: >>> 0 or None is None True >>> None or 0 is None False >>> None or 0 is 0 True Yes, this is explained in the docs: The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned. Another one (also explainable): >>> 0 or None == None or 0 True # Above is same as (operator precedence): >>> 0 or (None == None) or 0 True # Here is something different: >>> (0 or None) == (None or 0) False From python at rcn.com Tue Aug 4 16:14:29 2009 From: python at rcn.com (Raymond Hettinger) Date: Tue, 4 Aug 2009 13:14:29 -0700 (PDT) Subject: no-clobber dicts? References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: <435e2e2c-6f83-48e0-870e-febdc37c4c5c@x6g2000prc.googlegroups.com> [kj] > The implication here is that .update() does not in turn use > .__setitem__(), which I find a bit surprising. It's never wise to make assumptions about this sort of thing. Every method in a class or type is allowed to directly access or modify its private, internal data. The implementation is free to choose whether to limit that access to a few accessors (i.e. getitem, setitem, delitem, len) or to let all of the methods have direct access to the underlying data structure. Even if accessors were used, the choice would be arbitrary (perhaps delitem() gets implemented in terms of pop() or somesuch). This is a basic for OO programming. Unless the class documentation promises to use particular hooks, the implementation is free to change in any way that doesn't violate the published API (this is one of the benefits of encapsulation and abstract data types). In general, if a subclass is overriding, rather than extending, then it should override *every* method that could be affected. Raymond From mensanator at aol.com Tue Aug 4 16:21:30 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Aug 2009 13:21:30 -0700 (PDT) Subject: Is it possible to have the python color in the terminal ? References: Message-ID: On Aug 4, 1:53?pm, aurelien wrote: > Hello, > > I am under gNewSense, i am a newbbie on Python, i look for how change > the color terminal when python run. > at the step >>> all is in black and white. > Is it possible to have the python color in the terminal ? Depends on whether your terminal supports ANSI codes. For example, Windows does not, but the Cygwin terminal does. So, from Cygwin I can do >>> a = "\x1b[32m" >>> a '\x1b[32m' >>> print a >>> >>> >>> print b Traceback (most recent call last): File "", line 1, in NameError: name 'b' is not defined >>> And everything from the "print a" statement onwards is green. An ANSI code: an escape character (ESC, ASCII value 27, \x1b in hex) followed by the appropriate code sequence: Code: Meaning: \x1b[0m reset; clears all colors and styles (to white on black) \x1b[1m bold on (see below) \x1b[3m italics on \x1b[4m underline on \x1b[7m inverse on; reverses foreground & background colors \x1b[9m strikethrough on \x1b[22m bold off (see below) \x1b[23m italics off \x1b[24m underline off \x1b[27m inverse off \x1b[29m strikethrough off \x1b[30m set foreground color to black \x1b[31m set foreground color to red \x1b[32m set foreground color to green \x1b[33m set foreground color to yellow \x1b[34m set foreground color to blue \x1b[35m set foreground color to magenta (purple) \x1b[36m set foreground color to cyan \x1b[37m set foreground color to white \x1b[39m set foreground color to default (white) \x1b[40m set background color to black \x1b[41m set background color to red \x1b[42m set background color to green \x1b[43m set background color to yellow \x1b[44m set background color to blue \x1b[45m set background color to magenta (purple) \x1b[46m set background color to cyan \x1b[47m set background color to white \x1b[49m set background color to default (black) > > Thanks for your help. > > aurelien From apt.shansen at gmail.com Tue Aug 4 16:24:46 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Tue, 4 Aug 2009 13:24:46 -0700 Subject: boolean OR gotcha In-Reply-To: References: Message-ID: <7a9c25c20908041324l1a589c54q2f0f9666ab4ddd67@mail.gmail.com> > > > # Here is something different: > >>> (0 or None) == (None or 0) > False What is the actual problem? You quoted the docs, it seems very clear. (0 or None) would return None. (None or 0) would return 0. None is not equal to 0, of course. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From zuo at chopin.edu.pl Tue Aug 4 16:25:09 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 04 Aug 2009 22:25:09 +0200 Subject: boolean OR gotcha In-Reply-To: References: Message-ID: 04-08-2009 o 22:11:18 1x7y2z9 <1x7y2z9 at gmail.com> wrote: > Another one (also explainable): >>>> 0 or None == None or 0 > True > # Above is same as (operator precedence): >>>> 0 or (None == None) or 0 > True > # Here is something different: >>>> (0 or None) == (None or 0) > False I don't see any problem here. The last is ok: None != 0. *j -- Jan Kaliszewski (zuo) From kushal.kumaran+python at gmail.com Tue Aug 4 16:25:55 2009 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Wed, 5 Aug 2009 01:55:55 +0530 Subject: Online payment module In-Reply-To: References: Message-ID: <1e364c4e0908041325h5be577dq2363fba4c39af05b@mail.gmail.com> On Tue, Aug 4, 2009 at 12:41 AM, Sam Tregar wrote: > Hello all.? I'm considering building a module to provide a > cross-payment-gatewat API for making online payments.? In the Perl world we > have a module like this called Business::OnlinePayment > (http://search.cpan.org/~jasonk/Business-OnlinePayment-2.01/OnlinePayment.pm). > > Is there anything like this in Python?? My searches so far haven't turned up > anything.? If I don't find one I'll probably build one, covering PayPal and > Authorize.net to start.? If anyone is interested in discussing the project > and/or getting involved shoot me an email. > Not really familiar with this area, but have you seen these? http://code.google.com/p/pypaypal/ http://www.geteasyshop.com/front-page -- kushal From duane.kaufman at gmail.com Tue Aug 4 16:32:32 2009 From: duane.kaufman at gmail.com (DuaneKaufman) Date: Tue, 4 Aug 2009 13:32:32 -0700 (PDT) Subject: Overlap in python References: Message-ID: <2e475887-0e8d-4b34-a918-1af720c166bf@r38g2000yqn.googlegroups.com> On Aug 4, 1:15?pm, Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. ?For example, here would be my input: > > part name ? location > a ? ? ? ? ? ? ? ? ?5-9 > b ? ? ? ? ? ? ? ? ?7-10 > c ? ? ? ? ? ? ? ? ?3-6 > d ? ? ? ? ? ? ? ? ?15-20 > e ? ? ? ? ? ? ? ? ?18-23 > > And here is what I need for an output: > part name ? location > c.a.b ? ? ? ? ? ?3-10 > d.e ? ? ? ? ? ? ? 15-23 > > I've tried various methods, which all fail. ?Does anyone have an idea > how to do this? > > Thank you very much! > Jay Hi, You have gotten some excellent feedback (all without installing anything extra to your Python install), but might I suggest the use of an interval arithmetic package to aid in this? For instance the interval module found at: http://members.cox.net/apoco/interval/ can be put to use: Given your data above: > part name location > a 5-9 > b 7-10 > c 3-6 from interval import Interval >>> a_int=Interval(5,9) >>> b_int=Interval(7,10) >>> c_int=Interval(3,6) >>> a_int.overlaps(b_int) True >>> a_int.overlaps(c_int) True >>> b_int.overlaps(c_int) False Duane From 1x7y2z9 at gmail.com Tue Aug 4 16:35:02 2009 From: 1x7y2z9 at gmail.com (1x7y2z9) Date: Tue, 4 Aug 2009 13:35:02 -0700 (PDT) Subject: boolean OR gotcha References: Message-ID: Did not intend that there was a problem. Just a gotcha or a fun little titbit ... maybe. :) On Aug 4, 1:25?pm, "Jan Kaliszewski" wrote: > 04-08-2009 o 22:11:18 1x7y2z9 <1x7y... at gmail.com> wrote: > > > Another one (also explainable): > >>>> 0 or None == None or 0 > > True > > # Above is same as (operator precedence): > >>>> 0 or (None == None) or 0 > > True > > # Here is something different: > >>>> (0 or None) == (None or 0) > > False > > I don't see any problem here. > > The last is ok: None != 0. > > *j > -- > Jan Kaliszewski (zuo) From maxkhesin at gmail.com Tue Aug 4 16:45:10 2009 From: maxkhesin at gmail.com (xamdam) Date: Tue, 4 Aug 2009 13:45:10 -0700 (PDT) Subject: SDMX format Message-ID: Does anyone know of python libs for writing SDMX XML format? http://www.SDMX.org/resources/SDMXML/schemas/v2_0/common thanks, max. From bearophileHUGS at lycos.com Tue Aug 4 16:54:16 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Tue, 4 Aug 2009 13:54:16 -0700 (PDT) Subject: Overlap in python References: Message-ID: Jay Bird: > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 That's sometimes known as "The Set Union Problem on Intervals". Knowing the name of a problem is sometimes half the work :-) People have written papers on this. This is a O(N^2) force-brute algorithm, you can try it on your data: data = """part name location a 5-9 b 7-10 c 3-6 d 15-20 e 18-23""" pairs = map(str.split, data.splitlines()[1:]) triples = [map(int, i.split("-")) + [name] for (name, i) in pairs] overlap = lambda x1,y1, x2,y2: y1 >= x2 and x1 <= y2 results = [] for (x1,y1,name) in triples: for i, res in enumerate(results): if overlap(x1,y1, res[0],res[1]): results[i].append(name) results[i][0] = min(x1, res[0]) results[i][1] = max(y1, res[1]) break else: results.append([x1, y1, name]) print results # Output: [[3, 10, 'a', 'b', 'c'], [15, 23, 'd', 'e']] If you have have a lot of data then it will be too much slow, and you have to use a more complex algorithm. If your intervals are many, they are small, and they are spread in a not too much large range of possible values, you can create an integer array of indexes, and you can "paint" intervals on it. Bye, bearophile From gregor.lingl at aon.at Tue Aug 4 16:54:16 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 22:54:16 +0200 Subject: Overlap in python In-Reply-To: <2e475887-0e8d-4b34-a918-1af720c166bf@r38g2000yqn.googlegroups.com> References: <2e475887-0e8d-4b34-a918-1af720c166bf@r38g2000yqn.googlegroups.com> Message-ID: <4a78a005$0$2301$91cee783@newsreader02.highway.telekom.at> DuaneKaufman schrieb: > On Aug 4, 1:15 pm, Jay Bird wrote: ... > For instance the interval module found at: http://members.cox.net/apoco/interval/ > can be put to use: > > Given your data above: >> part name location >> a 5-9 >> b 7-10 >> c 3-6 > > from interval import Interval >>>> a_int=Interval(5,9) >>>> b_int=Interval(7,10) >>>> c_int=Interval(3,6) >>>> a_int.overlaps(b_int) > True >>>> a_int.overlaps(c_int) > True >>>> b_int.overlaps(c_int) > False As my proposed solution shows this approach can be done with on board means of Python (namely the set type). This would be quite different though, if you had floating point boundaries of the intervals. Regards, Gregor > > Duane From gregor.lingl at aon.at Tue Aug 4 16:57:59 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 22:57:59 +0200 Subject: Overlap in python In-Reply-To: <4a78a005$0$2301$91cee783@newsreader02.highway.telekom.at> References: <2e475887-0e8d-4b34-a918-1af720c166bf@r38g2000yqn.googlegroups.com> <4a78a005$0$2301$91cee783@newsreader02.highway.telekom.at> Message-ID: <4a78a0e5$0$2301$91cee783@newsreader02.highway.telekom.at> Gregor Lingl schrieb: > > As my proposed solution shows this approach can > be done with on board means of Python (namely > the set type). This would be quite different though, > if you had floating point boundaries of the intervals. > ... or if the intgers involved were very big :-( > Regards, > Gregor > >> >> Duane From bearophileHUGS at lycos.com Tue Aug 4 17:00:37 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Tue, 4 Aug 2009 14:00:37 -0700 (PDT) Subject: Overlap in python References: <78d86d92-d373-4163-a418-600a3eb36ab3@o15g2000yqm.googlegroups.com> Message-ID: <1f284d33-256e-4a61-a59a-3c84a2cf00e6@18g2000yqa.googlegroups.com> Mark Dickinson: > # create sorted list of points where an interval is entered or left > transitions = [] > for name, (start, stop) in input: > ? ? transitions.extend([(start, 'Start', name), (stop, 'Stop', name)]) > transitions.sort() > > # scan list, accumulating blocks along the way. Oh, right, that's the usual simple solution. Silly me for showing the dumb quadratic solution :-) The "pixelmap" approach may be faster if you have tons of small intervals in a not too much large range. Bye, bearophile From dickinsm at gmail.com Tue Aug 4 17:22:01 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 4 Aug 2009 14:22:01 -0700 (PDT) Subject: Overlap in python References: <78d86d92-d373-4163-a418-600a3eb36ab3@o15g2000yqm.googlegroups.com> Message-ID: <0bf0707a-d053-4481-af26-b2a524ab0964@k19g2000yqn.googlegroups.com> On Aug 4, 9:03?pm, Mark Dickinson wrote: > for i, (pt, startend, name) in enumerate(transitions): Whoops. That line should just be: for pt, startend, name in transitions: The enumerate was accidentally left-over from a more complicated version. -- Mark From davea at ieee.org Tue Aug 4 17:34:23 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 04 Aug 2009 17:34:23 -0400 Subject: Using Python to automate builds In-Reply-To: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> Message-ID: <4A78A95F.9080209@ieee.org> Kosta wrote: > I am a Python newbie, tasked with automating (researching) building > Windows drivers using the WDK build environment. I've been looking > into Python for this (instead of writing a bunch of batch files). > > What I would like to do, is to open a cmd window, and start a Python > script. This script would then (based upon input arguments), build > different flavors of the driver (fre, chk, x86, x64) and do some post > processing (create cat files, sign, etc.). > > I was hoping to take advantage as much as possible of exisiting > infrastructure from the WDK. I am able to call setenv.bat and provide > all the input parameters. One of the things setenv.bat does is change > the path environment variable. However, this is not captured by > Python. I could duplicate the functionality, but I'd rather not. Is > there a way to capture all enviroment variable changes being made by a > batch file from Python? > > Thanks! > > An excellent question. It's been a few years, but last time I remember looking, setenv.bat only changed environment variables, and didn't change current directory, or run any external programs.. If that's still true, I figure you have three options. I don't know of any way to capture them explicitly. So here are the three choices I can come up with: 1) have the first python program invoke a new shell which runs setenv, then runs another python program. This second python program would be where all the work is done, invoking compilers, linkers etc. So the first python program invokes a batch file which looks something like: call setenv.bat arg1 python second.py arg2 arg3 arg4 arg5 This batch file could even be generated on the fly, just to simplify complex argument passing. 2) Have the python program invoke a batch file something like the following, and then analyze the resulting text file call setenv.bat arg1 set > tempfile.txt The contents of that tempfile could then be loaded into a dict similar to the usual environment. Now the Python script can continue, and just use these environment variable instead of the original set 3) Have the python program parse the setenv.bat instead of running it. There was a post on this newsgroup announcing pyKook. It's still in early form, but you might get ideas from it. I haven't looked, I just pasted the announcement to look at later. + I have released pyKook 0.0.2. + http://pypi.python.org/pypi/Kook/0.0.2 + http://www.kuwata-lab.com/kook/ + http://www.kuwata-lab.com/kook/pykook-users-guide.html Other possibilities: + http://pypi.python.org/pypi/vellum/ flexible small 'make' alternative + http://code.google.com/p/waf/ + http://code.google.com/p/fabricate/ DaveA From gdamjan at gmail.com Tue Aug 4 17:40:17 2009 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Tue, 04 Aug 2009 23:40:17 +0200 Subject: Problem in installing PyGreSQL References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> <20090804095547.a5274e22.darcy@druid.net> Message-ID: <1fmmk6-htc.ln1@archaeopteryx.softver.org.mk> >> > By the way, you don't have to be super user to install PyGreSQL. >> > You just need SU if you want to install it system wide. PyGreSQL >> > doesn't require any special privileges to run. >> >> Right, but the packages install system-wide. That's why he could >> compile it himself but not use the package. > > Exactly so don't install the package. Do "python setup.py build" and > put the three files that are built (_pg.so, pg.py and pgdb.py) into > any directory and point PYTHONPATH to it. Or.. with Python 2.6 and up, you can do: python setup.py install --user and it will install the package in users own ~/.local/lib/python2.6/site-packages/ BTW that path is configurable with the PYTHONUSERBASE environment variable. see: http://www.python.org/dev/peps/pep-0370/ -- ?????? ( http://softver.org.mk/damjan/ ) Spammers scratch here with a diamond to find my address: ||||||||||||||||||||||||||||||||||||||||||||||| From kosta.koeman at gmail.com Tue Aug 4 17:40:46 2009 From: kosta.koeman at gmail.com (Kosta) Date: Tue, 4 Aug 2009 14:40:46 -0700 (PDT) Subject: Using Python to automate builds References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> Message-ID: <48e9dcba-5309-4de6-b833-7abec18120e1@d9g2000prh.googlegroups.com> On Aug 4, 2:34?pm, Dave Angel wrote: > Kosta wrote: > > I am a Python newbie, tasked with automating (researching) building > > Windows drivers using the WDK build environment. ?I've been looking > > into Python for this (instead of writing a bunch of batch files). > > > What I would like to do, is to open a cmd window, and start a Python > > script. ?This script would then (based upon input arguments), build > > different flavors of the driver (fre, chk, x86, x64) and do some post > > processing (create cat files, sign, etc.). > > > I was hoping to take advantage as much as possible of exisiting > > infrastructure from the WDK. ?I am able to call setenv.bat and provide > > all the input parameters. ?One of the things setenv.bat does is change > > the path environment variable. ?However, this is not captured by > > Python. ?I could duplicate the functionality, but I'd rather not. ?Is > > there a way to capture all enviroment variable changes being made by a > > batch file from Python? > > > Thanks! > > An excellent question. ?It's been a few years, but last time I remember > looking, setenv.bat only changed environment variables, and didn't > change current directory, or run any external programs.. ?If that's > still true, I figure you have three options. > > I don't know of any way to capture them explicitly. ?So here are the > three choices I can come up with: > > 1) have the first python program invoke a new shell which runs setenv, > then runs another python program. ?This second python program would be > where all the work is done, invoking compilers, linkers etc. ?So the > first python program invokes a batch file which looks something like: > ? ? ? ? ? call setenv.bat ?arg1 > ? ? ? ? ? python second.py ? ?arg2 arg3 ?arg4 ?arg5 > > ?This batch file could even be generated on the fly, just to simplify > complex argument passing. > > 2) Have the python program invoke a batch file something like the > following, and then analyze the resulting text file > ? ? ? ? ? ?call setenv.bat ? arg1 > ? ? ? ? ? ?set > tempfile.txt > > The contents of that tempfile could then be loaded into a dict similar > to the usual environment. ?Now the Python script can continue, and just > use these environment variable instead of the original set > > 3) Have the python program parse the setenv.bat instead of running it. > > There was a post on this newsgroup announcing pyKook. ?It's still in > early form, but you might get ideas from it. ?I haven't looked, I just > pasted the announcement to look at later. > > + I have released pyKook 0.0.2. > +http://pypi.python.org/pypi/Kook/0.0.2 > +http://www.kuwata-lab.com/kook/ > +http://www.kuwata-lab.com/kook/pykook-users-guide.html > > Other possibilities: > + ?http://pypi.python.org/pypi/vellum/? ? ? flexible small 'make' > alternative > > + ?http://code.google.com/p/waf/ > > + ?http://code.google.com/p/fabricate/ > > DaveA- Hide quoted text - > > - Show quoted text - Thanks Dave. I had thought about those three options, and was honestly hoping for a foruth (I know, some people are never satisfied ;). I'll look into pyKook. Thank you for your help. From philip at semanchuk.com Tue Aug 4 17:52:48 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 Aug 2009 17:52:48 -0400 Subject: Using Python to automate builds In-Reply-To: <48e9dcba-5309-4de6-b833-7abec18120e1@d9g2000prh.googlegroups.com> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <48e9dcba-5309-4de6-b833-7abec18120e1@d9g2000prh.googlegroups.com> Message-ID: On Aug 4, 2009, at 5:40 PM, Kosta wrote: > On Aug 4, 2:34 pm, Dave Angel wrote: >> >> + I have released pyKook 0.0.2. >> +http://pypi.python.org/pypi/Kook/0.0.2 >> +http://www.kuwata-lab.com/kook/ >> +http://www.kuwata-lab.com/kook/pykook-users-guide.html >> >> Other possibilities: >> + http://pypi.python.org/pypi/vellum/ flexible small 'make' >> alternative >> >> + http://code.google.com/p/waf/ >> >> + http://code.google.com/p/fabricate/ >> >> DaveA- Hide quoted text - >> >> - Show quoted text - > > Thanks Dave. I had thought about those three options, and was > honestly hoping for a foruth (I know, some people are never > satisfied ;). I'll look into pyKook. Thank you for your help. Poof! Your wish is granted! =) http://www.scons.org/ Dunno if you'll find it better, worse or different than the alternatives, but there it is. have fun P From no.email at please.post Tue Aug 4 17:57:25 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 21:57:25 +0000 (UTC) Subject: Overlap in python References: Message-ID: In Jay Bird writes: >Hi everyone, >I've been trying to figure out a simple algorithm on how to combine a >list of parts that have 1D locations that overlap into a non- >overlapping list. For example, here would be my input: >part name location >a 5-9 >b 7-10 >c 3-6 >d 15-20 >e 18-23 >And here is what I need for an output: >part name location >c.a.b 3-10 >d.e 15-23 >I've tried various methods, which all fail. Does anyone have an idea >how to do this? This problem is basically isomorphic to the problem of finding connected components in an undirected graph. If your parts are nodes in a graph, there's an edge between them if they overlap. The following is probably overkill, but it works. It uses the module pygraph, which you can download from http://code.google.com/p/python-graph/ The real work is done by its connected_components function. import pygraph from pygraph.algorithms.accessibility import connected_components class Part(object): def __init__(self, name, start, finish): self.name = name if start >= finish: raise ValueError("start must be strictly less than finish") self.start = start self.finish = finish def __str__(self): return self.name def combine_parts(parts): gr = pygraph.graph() gr.add_nodes(parts) # connect the nodes for i in range(len(parts) - 1): part_i = parts[i] for j in range(i + 1, len(parts)): part_j = parts[j] if (part_j.start <= part_i.finish <= part_j.finish or part_i.start <= part_j.finish <= part_i.finish): gr.add_edge(part_i, part_j) cc = connected_components(gr) c2n = {} # build connected components as lists for k, v in cc.items(): c2n.setdefault(v, []).append(k) ret = [] for nodes in c2n.values(): nodes.sort(key=lambda x: x.start) name = '.'.join(x.name for x in nodes) start = min(x.start for x in nodes) finish = max(x.finish for x in nodes) ret.append((name, start, finish)) return ret if __name__ == '__main__': data = [Part('a', 5, 9), Part('b', 7, 10), Part('c', 3, 6), Part('d', 15, 20), Part('e', 18, 23)] print combine_parts(data) When you run the script above, the output is [('c.a.b', 3, 10), ('d.e', 15, 23)] HTH, kynn From python at mrabarnett.plus.com Tue Aug 4 18:09:33 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Aug 2009 23:09:33 +0100 Subject: Overlap in python In-Reply-To: References: Message-ID: <4A78B19D.4020306@mrabarnett.plus.com> Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 > > I've tried various methods, which all fail. Does anyone have an idea > how to do this? > >>> parts = [(5, 9, "a"), (7, 10, "b"), (3, 6, "c"), (15, 20, "d"), (18, 23, "e")] >>> parts.sort() >>> parts [(3, 6, 'c'), (5, 9, 'a'), (7, 10, 'b'), (15, 20, 'd'), (18, 23, 'e')] >>> # Merge overlapping intervals. >>> pos = 1 >>> while pos < len(parts): # Merge the pair in parts[pos - 1 : pos + 1] if they overlap. p, q = parts[pos - 1 : pos + 1] if p[1] >= q[0]: parts[pos - 1 : pos + 1] = [(p[0], max(p[1], q[1]), p[2] + "." + q[2])] else: # They don't overlap, so try the next pair. pos += 1 >>> parts [(3, 10, 'c.a.b'), (15, 23, 'd.e')] From no.email at please.post Tue Aug 4 18:10:18 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 22:10:18 +0000 (UTC) Subject: Overlap in python References: <78d86d92-d373-4163-a418-600a3eb36ab3@o15g2000yqm.googlegroups.com> Message-ID: In <78d86d92-d373-4163-a418-600a3eb36ab3 at o15g2000yqm.googlegroups.com> Mark Dickinson writes: >On Aug 4, 7:15=A0pm, Jay Bird wrote: >> Hi everyone, >> >> I've been trying to figure out a simple algorithm on how to combine a >> list of parts that have 1D locations that overlap into a non- >> overlapping list. =A0For example, here would be my input: >> >> part name =A0 location >> a =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A05-9 >> b =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A07-10 >> c =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A03-6 >> d =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A015-20 >> e =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A018-23 >> >> And here is what I need for an output: >> part name =A0 location >> c.a.b =A0 =A0 =A0 =A0 =A0 =A03-10 >> d.e =A0 =A0 =A0 =A0 =A0 =A0 =A0 15-23 >> >> I've tried various methods, which all fail. =A0Does anyone have an idea >> how to do this? >Here's an approach that might work. Turning it into a sensible >function and parsing input/massaging output properly are left >as an exercise. Blocks that just touch (e.g. (3, 6) then (6, 9)) >are amalgamated; if this isn't what you want, and they should >be treated as separate instead, then replace 'Stop' with 'Finish' >(or any other string that sorts before 'Start'). >input =3D [ > ('a', (5, 9)), > ('b', (7, 10)), > ('c', (3, 6)), > ('d', (15, 20)), > ('e', (18, 23)), > ] ># create sorted list of points where an interval is entered or left >transitions =3D [] >for name, (start, stop) in input: > transitions.extend([(start, 'Start', name), (stop, 'Stop', name)]) >transitions.sort() ># scan list, accumulating blocks along the way. >count =3D 0 >for i, (pt, startend, name) in enumerate(transitions): > if startend =3D=3D 'Start': > if not count: > start =3D pt > names =3D [] > count +=3D 1 > names.append(name) > else: > count -=3D 1 > if not count: > print '.'.join(names), "%s--%s" % (start, pt) Very cool. kynn From bearophileHUGS at lycos.com Tue Aug 4 18:10:33 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Tue, 4 Aug 2009 15:10:33 -0700 (PDT) Subject: Overlap in python References: Message-ID: kj: > ? ? # connect the nodes > ? ? for i in range(len(parts) - 1): > ? ? ? ? part_i = parts[i] > ? ? ? ? for j in range(i + 1, len(parts)): Note that's O(N^2), see the O(sort) standard solution by Mark Dickinson. Bye, bearophile From ryniek90 at gmail.com Tue Aug 4 18:20:21 2009 From: ryniek90 at gmail.com (ryniek90) Date: Wed, 05 Aug 2009 00:20:21 +0200 Subject: How to write replace string for object which will be substituted? [regexp] In-Reply-To: References: Message-ID: <4A78B425.2010604@gmail.com> Hi. I started learning regexp, and some things goes well, but most of them still not. I've got problem with some regexp. Better post code here: " >>> import re >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> mail '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> print mail name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = re.sub('^\n|$\n', '', mail) >>> print maail name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = re.sub(' ', '', maail) >>> print maail name at mail.com name1[at]mail[dot]com name2[$at$]mail[$dot$]com >>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) >>> print maail name at mail.com name1 at mail[dot]com name2 at mail[$dot$]com >>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) >>> print maail name at mail.com name1 at mail.com name2 at mail.com >>> #How must i write the replace string to replace all this regexp's with just ONE command, in string 'mail' ? >>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', *?*, mail) " How must i write that replace pattern (look at question mark), to maek that substituion work? I didn't saw anything helpful while reading Re doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but something gone wrong - didn't wrote it right. Is there more user friendly HowTo for Python Re, than this? I'm new to programming an regexp, sorry for inconvenience. From jay.bird0804 at gmail.com Tue Aug 4 18:21:13 2009 From: jay.bird0804 at gmail.com (Jay Bird) Date: Tue, 4 Aug 2009 15:21:13 -0700 (PDT) Subject: Overlap in python References: <4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> Message-ID: Hi everyone, I wanted to thank you all for your help and *excellent* discussion. I was able to utilize and embed the script by Grigor Lingl in the 6th post of this discussion to get my program to work very quickly (I had to do about 20 comparisons per data bin, with over 40K bins in total). I am involved in genomic analysis research and this problem comes up a lot and I was surprised to not have been able to find a clear way to solve it. I will also look through all the tips in this thread, I have a feeling they may come in handy for future use! Thank you again, Jay From mensanator at aol.com Tue Aug 4 18:47:16 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Aug 2009 15:47:16 -0700 (PDT) Subject: Overlap in python References: <4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> Message-ID: <99c721fe-57fa-4508-9acb-2399ac81b9bf@k19g2000yqn.googlegroups.com> On Aug 4, 2:57?pm, Gregor Lingl wrote: > Jay Bird schrieb: > > > > > > > Hi everyone, > > > I've been trying to figure out a simple algorithm on how to combine a > > list of parts that have 1D locations that overlap into a non- > > overlapping list. ?For example, here would be my input: > > > part name ? location > > a ? ? ? ? ? ? ? ? ?5-9 > > b ? ? ? ? ? ? ? ? ?7-10 > > c ? ? ? ? ? ? ? ? ?3-6 > > d ? ? ? ? ? ? ? ? ?15-20 > > e ? ? ? ? ? ? ? ? ?18-23 > > > And here is what I need for an output: > > part name ? location > > c.a.b ? ? ? ? ? ?3-10 > > d.e ? ? ? ? ? ? ? 15-23 > > Suppose you have your data given as a dictionary: > > data = {'a':(5,9), > ? ? ? ? ?'b':(7,10), > ? ? ? ? ?'c':(3,6), > ? ? ? ? ?'d':(15,20), > ? ? ? ? ?'e':(18,23)} > > Then the following not particularly elegant > but very simple and straight forward > algorithm will solve your problem: > > def values(key): > ? ? ?return set(range(data[key][0], data[key][1]+1)) > > keys = list(data.keys()) > result = [] > while keys: > ? ? ?k = [keys[0]] > ? ? ?keys = keys[1:] > ? ? ?v = values(k[0]) > ? ? ?for l in keys[:]: > ? ? ? ? ?if v.intersection(values(l)): > ? ? ? ? ? ? ?v.update(values(l)) > ? ? ? ? ? ? ?k.append(l) > ? ? ? ? ? ? ?keys.remove(l) > ? ? ?result.append((k,v)) > > # print(result) ## if you like > > for k, v in result: > ? ? ?print(".".join(sorted(k)), "%d-%d" % (min(v), max(v))) > > Regards, > Gregor > > > > > I've tried various methods, which all fail. ?Does anyone have an idea > > how to do this? > > > Thank you very much! > > Jay I was thinking sets, too. import random def overlap(): merge_count = 0 datam.append(data.pop(0)) while len(data)>0: d0 = data.pop(0) dmi = 0 dmtemp = datam[:] while d0: dmtest = d0[1].intersection(dmtemp[dmi][1]) #print(d0,dmtemp[dmi],dmtest) if len(dmtest)>0: # overlap dmtest = d0[1].union(dmtemp[dmi][1]) datam[dmi] = (d0[0]+dmtemp[dmi][0],dmtest) d0 = None dmi = 0 merge_count += 1 else: dmi += 1 if dmi == len(dmtemp): datam.append(d0) d0 = None return merge_count # repeat until 0 returned ## OP data ##data=[] ##data.append(('a',set([i for i in range(5,9+1)]))) ##data.append(('b',set([i for i in range(7,10+1)]))) ##data.append(('c',set([i for i in range(3,6+1)]))) ##data.append(('d',set([i for i in range(15,20+1)]))) ##data.append(('e',set([i for i in range(18,23+1)]))) ##datam = [] ## ##print() ##for j in data: print(j) ##print() ## ## ##overlap() ## ##for i in datam: ## print(i[0],min(i[1]),max(i[1])) ## ## ('a', {8, 9, 5, 6, 7}) ## ('b', {8, 9, 10, 7}) ## ('c', {3, 4, 5, 6}) ## ('d', {15, 16, 17, 18, 19, 20}) ## ('e', {18, 19, 20, 21, 22, 23}) ## ## cba 3 10 ## ed 15 23 ## special case - repeat overlap test until no merges data = [('A', {79, 80, 81, 82, 83, 84, 85, 86}), ('B', {96, 89, 90, 91, 92, 93, 94, 95}), ('C', {21, 22, 23, 24, 25, 26, 27, 28}), ('D', {64, 65, 66, 67, 68, 69, 62, 63}), ('E', {72, 73, 74, 75, 76, 77, 78, 79}), ('F', {65, 66, 67, 68, 69, 70, 71, 72}), ('G', {11, 12, 13, 14, 15, 16, 17, 18}), ('H', {24, 25, 26, 27, 28, 29, 30, 31}), ('I', {32, 33, 34, 35, 36, 37, 38, 31}), ('J', {81, 82, 83, 84, 85, 86, 87, 88})] datam = [] ## ('A', {55, 56, 57, 58, 59, 60, 61, 62}) ## ('B', {64, 57, 58, 59, 60, 61, 62, 63}) ## ('C', {10, 11, 12, 13, 14, 15, 16, 17}) ## ('D', {32, 25, 26, 27, 28, 29, 30, 31}) ## ('E', {54, 55, 56, 57, 58, 59, 60, 61}) ## ('F', {64, 65, 66, 59, 60, 61, 62, 63}) ## ('G', {41, 42, 43, 44, 45, 46, 47, 48}) ## ('H', {67, 68, 69, 70, 71, 72, 73, 74}) ## ('I', {55, 56, 57, 58, 59, 60, 61, 62}) ## ('J', {64, 65, 66, 67, 68, 69, 62, 63}) ## ## JIFEBA 54 69 ## C 10 17 ## D 25 32 ## G 41 48 ## H 67 74 <--- NFG overlaps JIFEBA print() for j in data: print(j) print() merges = 1 # corrects above while merges > 0: merges = overlap() print(merges) if merges>0: data = datam[:] datam = [] for i in datam: print(i[0],min(i[1]),max(i[1])) ## corrected ## ## ('A', {79, 80, 81, 82, 83, 84, 85, 86}) ## ('B', {96, 89, 90, 91, 92, 93, 94, 95}) ## ('C', {21, 22, 23, 24, 25, 26, 27, 28}) ## ('D', {64, 65, 66, 67, 68, 69, 62, 63}) ## ('E', {72, 73, 74, 75, 76, 77, 78, 79}) ## ('F', {65, 66, 67, 68, 69, 70, 71, 72}) ## ('G', {11, 12, 13, 14, 15, 16, 17, 18}) ## ('H', {24, 25, 26, 27, 28, 29, 30, 31}) ## ('I', {32, 33, 34, 35, 36, 37, 38, 31}) ## ('J', {81, 82, 83, 84, 85, 86, 87, 88}) ## ## 5 ## 1 ## 0 ## DJFEA 62 88 ## B 89 96 ## IHC 21 38 ## G 11 18 # random sequences data = [] for j in range(12): q = random.randint(0,90) r = q+12 data.append((chr(j+65),set([x for x in range(q,r)]))) datam = [] print() for j in data: print(j) print() merges = 1 # corrects above while merges > 0: merges = overlap() print(merges) if merges>0: data = datam[:] datam = [] for i in datam: print(i[0],min(i[1]),max(i[1])) ## ('A', {3, 4, 5, 6, 7, 8, 9, 10}) ## ('B', {76, 77, 78, 79, 80, 81, 82, 83}) ## ('C', {43, 44, 45, 46, 47, 48, 49, 50}) ## ('D', {42, 43, 44, 45, 46, 47, 48, 49}) ## ('E', {23, 24, 25, 26, 27, 28, 29, 30}) ## ('F', {49, 50, 51, 52, 53, 54, 55, 56}) ## ('G', {76, 77, 78, 79, 80, 81, 82, 83}) ## ('H', {1, 2, 3, 4, 5, 6, 7, 8}) ## ('I', {37, 38, 39, 40, 41, 42, 43, 44}) ## ('J', {83, 84, 85, 86, 87, 88, 89, 90}) ## ## 6 ## 0 ## HA 1 10 ## JGB 76 90 ## IFDC 37 56 ## E 23 30 ## ('A', {64, 65, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63}) ## ('B', {34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45}) ## ('C', {16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27}) ## ('D', {70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81}) ## ('E', {64, 65, 66, 67, 56, 57, 58, 59, 60, 61, 62, 63}) ## ('F', {34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45}) ## ('G', {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}) ## ('H', {64, 65, 66, 55, 56, 57, 58, 59, 60, 61, 62, 63}) ## ('I', {44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55}) ## ('J', {64, 65, 66, 67, 68, 57, 58, 59, 60, 61, 62, 63}) ## ('K', {96, 97, 98, 99, 88, 89, 90, 91, 92, 93, 94, 95}) ## ('L', {96, 97, 98, 99, 100, 89, 90, 91, 92, 93, 94, 95}) ## ## 6 ## 1 ## 0 ## FBJIHEA 34 68 ## C 16 27 ## D 70 81 ## G 0 11 ## LK 88 100 From python at mrabarnett.plus.com Tue Aug 4 18:55:36 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Aug 2009 23:55:36 +0100 Subject: How to write replace string for object which will be substituted? [regexp] In-Reply-To: <4A78B425.2010604@gmail.com> References: <4A78B425.2010604@gmail.com> Message-ID: <4A78BC68.2020601@mrabarnett.plus.com> ryniek90 wrote: > Hi. > I started learning regexp, and some things goes well, but most of them > still not. > > I've got problem with some regexp. Better post code here: > > " > >>> import re > >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > mail [$dot$] com\n' > >>> mail > '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > >>> print mail > > name at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > >>> maail = re.sub('^\n|$\n', '', mail) > >>> print maail > name at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > >>> maail = re.sub(' ', '', maail) > >>> print maail > name at mail.com > name1[at]mail[dot]com > name2[$at$]mail[$dot$]com > >>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > >>> print maail > name at mail.com > name1 at mail[dot]com > name2 at mail[$dot$]com > >>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > >>> print maail > name at mail.com > name1 at mail.com > name2 at mail.com > >>> #How must i write the replace string to replace all this regexp's > with just ONE command, in string 'mail' ? > >>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', > *?*, mail) > " > > How must i write that replace pattern (look at question mark), to maek > that substituion work? I didn't saw anything helpful while reading Re > doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but > something gone wrong - didn't wrote it right. > Is there more user friendly HowTo for Python Re, than this? > > I'm new to programming an regexp, sorry for inconvenience. > I don't think you can do it in one regex, nor would I want to. Just use the string's replace() method. >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> mail '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> print mail name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = mail.strip() name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = maail.replace(' ', '') >>> print maail name at mail.com name1[at]mail[dot]com name2[$at$]mail[$dot$]com >>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') >>> print maail name at mail.com name1 at mail[dot]com name2 at mail[$dot$]com >>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') >>> print maail name at mail.com name1 at mail.com name2 at mail.com From sam at tregar.com Tue Aug 4 19:50:29 2009 From: sam at tregar.com (Sam Tregar) Date: Tue, 4 Aug 2009 19:50:29 -0400 Subject: Online payment module In-Reply-To: <1e364c4e0908041325h5be577dq2363fba4c39af05b@mail.gmail.com> References: <1e364c4e0908041325h5be577dq2363fba4c39af05b@mail.gmail.com> Message-ID: On Tue, Aug 4, 2009 at 4:25 PM, Kushal Kumaran < kushal.kumaran+python at gmail.com > wrote: > > Not really familiar with this area, but have you seen these? > > http://code.google.com/p/pypaypal/ > http://www.geteasyshop.com/front-page > Thanks, but neither of these are remotely what I'm looking for! The first is an API for accessing PayPal, but not the one I'll be using - this one has only one release and hasn't been updated in over a year, looks basically useless. The other is a full-fledged e-commerce application, not a code library. -sam -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex at moreati.org.uk Tue Aug 4 20:30:05 2009 From: alex at moreati.org.uk (Alex Willmer) Date: Tue, 4 Aug 2009 17:30:05 -0700 (PDT) Subject: New implementation of re module References: Message-ID: <380ee69c-b498-4f99-8bca-2f680dd0171b@b14g2000yqd.googlegroups.com> On Jul 27, 5:34?pm, MRAB wrote: > Hi all, > > I've been working on a new implementation of the re module. The details > are athttp://bugs.python.org/issue2636, specifically fromhttp://bugs.python.org/issue2636#msg90954. I've included a .pyd file for > Python 2.6 on Windows if you want to try it out. Firstly Matthew, thank you for all your work on this. It brings some very nice regex features to Python. I've used Christopher Arndt's post as a basis and created a package from you latest upload (issue2636-20090804.zip), which builds for Python 2.5 and 2.6. I'd like to see this on PyPI, so it's easier to install the module and your work gets wider exposure. Would this be alright and would you prefer to have control of the upload, as this is your work? Below is the setup.py, the unicodedata_db.h files are taken from the appropriate branches on svn.python.org #!/usr/bin/env python import shutil import sys from distutils.core import setup, Extension MAJOR, MINOR = sys.version_info[:2] # Copy appropriate unicodedata_db.h, not found in published includes if (MAJOR, MINOR) == (2, 6): shutil.copy('Python26/unicodedata_db.h', './') elif (MAJOR, MINOR) == (2, 5): shutil.copy('Python25/unicodedata_db.h', './') else: print "WARNING: No unicodedata_db.h prepared." setup( name='regex', version='20080804', description='Alternate regular expression module, to replace re.', author='Matthew Barnett', author_email='python at mrabarnett.nospam.plus.com', # Obsfucated url='http://bugs.python.org/issue2636', py_modules = ['regex'], ext_modules=[Extension('_regex', ['_regex.c'])], ) Sincerely, Alex Willmer From missive at hotmail.com Tue Aug 4 21:01:14 2009 From: missive at hotmail.com (Lee Harr) Date: Wed, 5 Aug 2009 05:31:14 +0430 Subject: [ANNC] pybotwar-0.4 Message-ID: pybotwar is a fun and educational game where players create computer programs to control simulated robots to compete in a battle arena. http://pybotwar.googlecode.com/ pybotwar uses pybox2d for the physical simulation, and uses pygame and pygsear for the visualization. pybotwar is released under GPLv3. Changes in pybotwar-0.4: - added display of robot status - added configuration file for easier testing of various options - remove / don't remove dead robots - robot max health - physics values (force, torque, mass, bullet speed) - add non graphics mode (for much faster resolution of battles) - fixed cannon heating going below zero _________________________________________________________________ Drag n? drop?Get easy photo sharing with Windows Live? Photos. http://www.microsoft.com/windows/windowslive/products/photos.aspx From koranthala at gmail.com Tue Aug 4 21:29:17 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 18:29:17 -0700 (PDT) Subject: My first wxPython App with Twisted Message-ID: Hi, I am creating the first GUI app (wxPython based) using Twisted. I am facing an issue which I cannot seem to solve/understand due to lack of trace or anything. I had a big app written on twisted and now I am creating a login screen to the app. The app used to work without any issues. I added the login screen and the login screen comes up. But then everything freezes up. I have to force quit the python application to get anything back. Can anyone help me solve it? The code is as follows: import wx import os import logging from twisted.internet import wxreactor wxreactor.install() from twisted.internet import reactor #Called only after wxreactor.install() from twisted.internet.task import LoopingCall import clientapp def opj(path): """ Convert paths to the platform-specific separator """ st = apply(os.path.join, tuple(path.split('/'))) if path.startswith('/'): st = '/' + st return st class APPApp(wx.App): def OnInit(self): self.frame = APPFrame(None, -1, " APP Login", size=(200, 150)) self.panel = APPPanel(self.frame,-1) #client.run method does the verification etc along with other items client = clientapp.setup_app() call = LoopingCall(client.run) call.start(.51) return True def main(): app = APPApp(0) reactor.registerWxApp(app) try: reactor.run() except StandardError: raise class APPPanel(wx.Panel): """ APP GUI PANEL The panel in which the user name and password is typed. @var ID_LOGIN: Login buttons id. When this button is clicked, the data is stored for logging. """ ID_LOGIN = wx.NewId() def __init__(self, parent, id): self.parent = parent wx.Panel.__init__(self, parent, id, size=(200,150)) self.quote = wx.StaticText(self, -1, "APP Login",wx.Point(60, 10)) wx.StaticText(self, wx.ID_ANY, "User Name ", wx.Point(20, 33)) wx.StaticText(self, wx.ID_ANY, "Password ", wx.Point(20, 58)) self.usernameBox = wx.TextCtrl(self, wx.ID_ANY, "", wx.Point(80, 31), wx.Size(100, wx.ID_ANY)) self.usernameBox.SetFocus() self.passwordBox = wx.TextCtrl(self, wx.ID_ANY, "", wx.Point(80, 56), wx.Size(100, wx.ID_ANY), style=wx.TE_PASSWORD) self.button =wx.Button(self, self.ID_LOGIN, "Login", wx.Point (60, 88)) wx.EVT_BUTTON(parent, self.ID_LOGIN, self.on_login) def on_login(self, event): username = self.usernameBox.GetString(0, 128) password = self.passwordBox.GetString(0, 128) if username and password: self.parent.on_login_click(username, password) class APPTaskBarIcon(wx.TaskBarIcon): ''' TaskBar Icon So that the application is always alive on the taskbar. 3 operations are possible, DoubleClick on the taskbar would bring up the window, right click will bring up options to restore or exit the tool. ''' TBMENU_RESTORE = wx.NewId() TBMENU_CLOSE = wx.NewId() def __init__(self, frame): wx.TaskBarIcon.__init__(self) self.frame = frame # Set the image icon = self.MakeIcon(self.frame.get_image()) self.SetIcon(icon, "APP") self.imgidx = 1 # bind some events self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarActivate) self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=self.TBMENU_RESTORE) self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=self.TBMENU_CLOSE) def CreatePopupMenu(self): """ Right Click Popup Menu This method is called by the base class when it needs to popup the menu for the default EVT_RIGHT_DOWN event. """ menu = wx.Menu() menu.Append(self.TBMENU_RESTORE, "Restore Window") menu.Append(self.TBMENU_CLOSE, "Exit APP") return menu def MakeIcon(self, img): """ Return the generated Icon. This function is required because various platforms have different requirements for the icon size. """ if "wxMSW" in wx.PlatformInfo: img = img.Scale(16, 16) elif "wxGTK" in wx.PlatformInfo: img = img.Scale(22, 22) icon = wx.IconFromBitmap(img.ConvertToBitmap() ) return icon def OnTaskBarActivate(self, evt): ''' Activation code - say DoubleClick etc. It raises the window ''' if self.frame.IsIconized(): self.frame.Iconize(False) if not self.frame.IsShown(): self.frame.Show(True) self.frame.Raise() def OnTaskBarClose(self, evt): ''' On right click and close, the frame itself is closed ''' wx.CallAfter(self.frame.Close) class APPFrame(wx.Frame): def __init__(self, parent, id, title, size=None): wx.Frame.__init__(self, parent, id, title, size=size, pos=wx.Point(400, 300)) icon = self.get_icon() self.SetIcon(icon) self.tbicon = APPTaskBarIcon(self) self.Show(True) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.Bind(wx.EVT_ICONIZE, self.OnIconify) def on_login_click(self, username, password): self.Hide() def OnCloseWindow(self, event): if self.tbicon is not None: self.tbicon.Destroy() event.Skip() def OnIconify(self, event): self.Hide() def get_image(self): img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO) return img def get_icon(self): img = self.get_image() icon = wx.IconFromBitmap(img.ConvertToBitmap() ) return icon if __name__ == '__main__': main() -------------- If somebody can help me out, I would be much obliged. From koranthala at gmail.com Tue Aug 4 21:39:49 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 18:39:49 -0700 (PDT) Subject: My first wxPython App with Twisted References: Message-ID: <15ec22f4-7bcf-4a7f-81e0-ad98004adde4@p36g2000prn.googlegroups.com> On Aug 5, 6:29?am, koranthala wrote: > Hi, > ? ?I am creating the first GUI app (wxPython based) using Twisted. > ? ?I am facing an issue which I cannot seem to solve/understand due > to lack of trace or anything. > > ? ?I had a big app written on twisted and now I am creating a login > screen to the app. > ? ?The app used to work without any issues. I added the login screen > and the login screen comes up. > ? ? But then everything freezes up. I have to force quit the python > application to get anything back. Can anyone help me solve it? > > ? ?The code is as follows: > > import wx > import os > import logging > > from twisted.internet import wxreactor > wxreactor.install() > from twisted.internet import reactor #Called only after > wxreactor.install() > from twisted.internet.task import LoopingCall > > import clientapp > > def opj(path): > ? ?""" Convert paths to the platform-specific separator """ > ? ?st = apply(os.path.join, tuple(path.split('/'))) > ? ?if path.startswith('/'): > ? ? ? ?st = '/' + st > ? ?return st > > class APPApp(wx.App): > ? ?def OnInit(self): > ? ? ? ?self.frame = APPFrame(None, -1, " APP Login", size=(200, 150)) > ? ? ? ?self.panel = APPPanel(self.frame,-1) > ? ? ? ?#client.run method does the verification etc along with other > items > ? ? ? ?client = clientapp.setup_app() > ? ? ? ?call = LoopingCall(client.run) > ? ? ? ?call.start(.51) > ? ? ? ?return True > > def main(): > ? ?app = APPApp(0) > ? ?reactor.registerWxApp(app) > ? ?try: > ? ? ? ?reactor.run() > ? ?except StandardError: > ? ? ? ?raise > > class APPPanel(wx.Panel): > ? ?""" APP GUI PANEL > > ? ?The panel in which the user name and password is typed. > ? ?@var ID_LOGIN: Login buttons id. When this button is clicked, the > data > ? ? ? ?is stored for logging. > > ? ?""" > ? ?ID_LOGIN = wx.NewId() > > ? ?def __init__(self, parent, id): > ? ? ? ?self.parent = parent > ? ? ? ?wx.Panel.__init__(self, parent, id, size=(200,150)) > ? ? ? ?self.quote = wx.StaticText(self, -1, "APP Login",wx.Point(60, > 10)) > ? ? ? ?wx.StaticText(self, wx.ID_ANY, "User Name ", wx.Point(20, 33)) > ? ? ? ?wx.StaticText(self, wx.ID_ANY, "Password ", wx.Point(20, 58)) > ? ? ? ?self.usernameBox = wx.TextCtrl(self, wx.ID_ANY, "", > wx.Point(80, 31), wx.Size(100, wx.ID_ANY)) > ? ? ? ?self.usernameBox.SetFocus() > ? ? ? ?self.passwordBox = wx.TextCtrl(self, wx.ID_ANY, "", > wx.Point(80, 56), wx.Size(100, wx.ID_ANY), style=wx.TE_PASSWORD) > ? ? ? ?self.button =wx.Button(self, self.ID_LOGIN, "Login", wx.Point > (60, 88)) > ? ? ? ?wx.EVT_BUTTON(parent, self.ID_LOGIN, self.on_login) > > ? ?def on_login(self, event): > ? ? ? ?username = self.usernameBox.GetString(0, 128) > ? ? ? ?password = self.passwordBox.GetString(0, 128) > ? ? ? ?if username and password: > ? ? ? ? ? ?self.parent.on_login_click(username, password) > > class APPTaskBarIcon(wx.TaskBarIcon): > ? ?''' TaskBar Icon > > ? ?So that the application is always alive on the taskbar. > ? ?3 operations are possible, DoubleClick on the taskbar would bring > up the > ? ?window, right click will bring up options to restore or exit the > tool. > > ? ?''' > ? ?TBMENU_RESTORE = wx.NewId() > ? ?TBMENU_CLOSE ? = wx.NewId() > > ? ?def __init__(self, frame): > ? ? ? ?wx.TaskBarIcon.__init__(self) > ? ? ? ?self.frame = frame > ? ? ? ?# Set the image > ? ? ? ?icon = self.MakeIcon(self.frame.get_image()) > ? ? ? ?self.SetIcon(icon, "APP") > ? ? ? ?self.imgidx = 1 > ? ? ? ?# bind some events > ? ? ? ?self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarActivate) > ? ? ? ?self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, > id=self.TBMENU_RESTORE) > ? ? ? ?self.Bind(wx.EVT_MENU, self.OnTaskBarClose, > id=self.TBMENU_CLOSE) > > ? ?def CreatePopupMenu(self): > ? ? ? ?""" Right Click Popup Menu > > ? ? ? ?This method is called by the base class when it needs to popup > ? ? ? ?the menu for the default EVT_RIGHT_DOWN event. > > ? ? ? ?""" > ? ? ? ?menu = wx.Menu() > ? ? ? ?menu.Append(self.TBMENU_RESTORE, "Restore Window") > ? ? ? ?menu.Append(self.TBMENU_CLOSE, "Exit APP") > ? ? ? ?return menu > > ? ?def MakeIcon(self, img): > ? ? ? ?""" Return the generated Icon. > > ? ? ? ?This function is required because various platforms have > different > ? ? ? ?requirements for the icon size. > > ? ? ? ?""" > ? ? ? ?if "wxMSW" in wx.PlatformInfo: > ? ? ? ? ? ?img = img.Scale(16, 16) > ? ? ? ?elif "wxGTK" in wx.PlatformInfo: > ? ? ? ? ? ?img = img.Scale(22, 22) > ? ? ? ?icon = wx.IconFromBitmap(img.ConvertToBitmap() ) > ? ? ? ?return icon > > ? ?def OnTaskBarActivate(self, evt): > ? ? ? ?''' Activation code - say DoubleClick etc. It raises the window > ''' > ? ? ? ?if self.frame.IsIconized(): > ? ? ? ? ? ?self.frame.Iconize(False) > ? ? ? ?if not self.frame.IsShown(): > ? ? ? ? ? ?self.frame.Show(True) > ? ? ? ?self.frame.Raise() > > ? ?def OnTaskBarClose(self, evt): > ? ? ? ?''' On right click and close, the frame itself is closed ''' > ? ? ? ?wx.CallAfter(self.frame.Close) > > class APPFrame(wx.Frame): > ? ?def __init__(self, parent, id, title, size=None): > ? ? ? ?wx.Frame.__init__(self, parent, id, title, > ? ? ? ? ? ? ? ? ? ? ? ? ?size=size, pos=wx.Point(400, 300)) > ? ? ? ?icon = self.get_icon() > ? ? ? ?self.SetIcon(icon) > ? ? ? ?self.tbicon = APPTaskBarIcon(self) > ? ? ? ?self.Show(True) > ? ? ? ?self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) > ? ? ? ?self.Bind(wx.EVT_ICONIZE, self.OnIconify) > > ? ?def on_login_click(self, username, password): > ? ? ? ?self.Hide() > > ? ?def OnCloseWindow(self, event): > ? ? ? ?if self.tbicon is not None: > ? ? ? ? ? ?self.tbicon.Destroy() > ? ? ? ?event.Skip() > > ? ?def OnIconify(self, event): > ? ? ? ?self.Hide() > > ? ?def get_image(self): > ? ? ? ?img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO) > ? ? ? ?return img > > ? ?def get_icon(self): > ? ? ? ?img = self.get_image() > ? ? ? ?icon = wx.IconFromBitmap(img.ConvertToBitmap() ) > ? ? ? ?return icon > > if __name__ == '__main__': > ? ?main() > > -------------- > If somebody can help me out, I would be much obliged. Please disregard this mail. I will post a barebones version separately. From koranthala at gmail.com Tue Aug 4 21:41:40 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 18:41:40 -0700 (PDT) Subject: My first wxPython App with Twisted - barebones version Message-ID: <735ece44-08f5-4120-966f-28489299c443@o9g2000prg.googlegroups.com> Hi, I am creating the first GUI app (wxPython based) using Twisted. I am facing an issue which I cannot seem to solve/understand due to lack of trace or anything. I had a big app written on twisted and now I am creating a login screen to the app. The app used to work without any issues. I added the login screen and the login screen comes up. But then everything freezes up. I have to force quit the python application to get anything back. Can anyone help me solve it? The code is as follows: import wx import os import logging from twisted.internet import wxreactor wxreactor.install() from twisted.internet import reactor #Called only after wxreactor.install() from twisted.internet.task import LoopingCall import clientapp def opj(path): """ Convert paths to the platform-specific separator """ st = apply(os.path.join, tuple(path.split('/'))) if path.startswith('/'): st = '/' + st return st class APPApp(wx.App): def OnInit(self): self.frame = APPFrame(None, -1, " APP Login", size=(200, 150)) self.panel = APPPanel(self.frame,-1) client = clientapp.setup_app() call = LoopingCall(client.run) call.start(.51) return True def main(): app = APPApp(0) reactor.registerWxApp(app) try: reactor.run() except StandardError: raise class APPFrame(wx.Frame): def __init__(self, parent, id, title, size=None): wx.Frame.__init__(self, parent, id, title, size=size, pos=wx.Point(400, 300)) icon = self.get_icon() self.SetIcon(icon) self.Show(True) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.Bind(wx.EVT_ICONIZE, self.OnIconify) def on_login_click(self, username, password): self.Hide() def OnCloseWindow(self, event): event.Skip() def OnIconify(self, event): self.Hide() def get_image(self): img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO) return img def get_icon(self): img = self.get_image() icon = wx.IconFromBitmap(img.ConvertToBitmap() ) return icon if __name__ == '__main__': main() From geomajor56 at gmail.com Tue Aug 4 22:06:27 2009 From: geomajor56 at gmail.com (Michael Savarese) Date: Tue, 4 Aug 2009 22:06:27 -0400 Subject: os.walk() Message-ID: <75c8645a0908041906s138c1499k59cd57d569a5c83e@mail.gmail.com> Greetings Python newbie here, and thanks to all who have helped me previously. Is there a way of grabbing file attributes while traversing with os.walk()? It would be advantageous to have date modified and file size along with the file name. If anyone can point me in the right direction, I'd appreciate it. Thanks in advance Mike S -------------- next part -------------- An HTML attachment was scrubbed... URL: From erikwickstrom at gmail.com Tue Aug 4 22:37:32 2009 From: erikwickstrom at gmail.com (erikcw) Date: Tue, 4 Aug 2009 19:37:32 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? Message-ID: Hi, I'm trying to get multiprocessing to working consistently with my script. I keep getting random tracebacks with no helpful information. Sometimes it works, sometimes it doesn't. Traceback (most recent call last): File "scraper.py", line 144, in print pool.map(scrape, range(10)) File "/usr/lib/python2.6/multiprocessing/pool.py", line 148, in map return self.map_async(func, iterable, chunksize).get() File "/usr/lib/python2.6/multiprocessing/pool.py", line 422, in get raise self._value TypeError: expected string or buffer It's not always the same traceback, but they are always short like this. I'm running Python 2.6.2 on Ubuntu 9.04. Any idea how I can debug this? Thanks! Erik From clp2 at rebertia.com Tue Aug 4 22:48:45 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 Aug 2009 19:48:45 -0700 Subject: os.walk() In-Reply-To: <75c8645a0908041906s138c1499k59cd57d569a5c83e@mail.gmail.com> References: <75c8645a0908041906s138c1499k59cd57d569a5c83e@mail.gmail.com> Message-ID: <50697b2c0908041948q31a30819g29e3d7f196e94074@mail.gmail.com> On Tue, Aug 4, 2009 at 7:06 PM, Michael Savarese wrote: > Greetings > Python newbie here, and thanks to all who have helped me previously. > Is there a way of grabbing file attributes while traversing with os.walk()? > It would be advantageous to have date modified and file size along with the > file name. > If anyone can point me in the right direction, I'd appreciate it. Feed the path to os.stat(), and then use the `stat` module on the result: http://docs.python.org/library/os.html#os.stat http://docs.python.org/library/stat.html#module-stat Cheers, Chris -- http://blog.rebertia.com From koranthala at gmail.com Tue Aug 4 22:51:55 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 19:51:55 -0700 (PDT) Subject: My first wxPython App with Twisted - barebones version References: <735ece44-08f5-4120-966f-28489299c443@o9g2000prg.googlegroups.com> Message-ID: <6b487c43-814f-4130-b104-2b80795ed389@t11g2000prh.googlegroups.com> On Aug 5, 6:41?am, koranthala wrote: > Hi, > ? ?I am creating the first GUI app (wxPython based) using Twisted. > ? ?I am facing an issue which I cannot seem to solve/understand due > to lack of trace or anything. > ? ?I had a big app written on twisted and now I am creating a login > screen to the app. > ? ?The app used to work without any issues. I added the login screen > and the login screen comes up. > ? ? But then everything freezes up. I have to force quit the python > application to get anything back. Can anyone help me solve it? > ? ?The code is as follows: > > import wx > import os > import logging > > from twisted.internet import wxreactor > wxreactor.install() > from twisted.internet import reactor #Called only after > wxreactor.install() > from twisted.internet.task import LoopingCall > > import clientapp > > def opj(path): > ? ? """ Convert paths to the platform-specific separator """ > ? ? st = apply(os.path.join, tuple(path.split('/'))) > ? ? if path.startswith('/'): > ? ? ? ? st = '/' + st > ? ? return st > > class APPApp(wx.App): > ? ? def OnInit(self): > ? ? ? ? self.frame = APPFrame(None, -1, " APP Login", size=(200, 150)) > ? ? ? ? self.panel = APPPanel(self.frame,-1) > ? ? ? ? client = clientapp.setup_app() > ? ? ? ? call = LoopingCall(client.run) > ? ? ? ? call.start(.51) > ? ? ? ? return True > > def main(): > ? ? app = APPApp(0) > ? ? reactor.registerWxApp(app) > ? ? try: > ? ? ? ? reactor.run() > ? ? except StandardError: > ? ? ? ? raise > > class APPFrame(wx.Frame): > ? ? def __init__(self, parent, id, title, size=None): > ? ? ? ? wx.Frame.__init__(self, parent, id, title, > ? ? ? ? ? ? ? ? ? ? ? ? ? size=size, pos=wx.Point(400, 300)) > ? ? ? ? icon = self.get_icon() > ? ? ? ? self.SetIcon(icon) > ? ? ? ? self.Show(True) > ? ? ? ? self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) > ? ? ? ? self.Bind(wx.EVT_ICONIZE, self.OnIconify) > > ? ? def on_login_click(self, username, password): > ? ? ? ? self.Hide() > > ? ? def OnCloseWindow(self, event): > ? ? ? ? event.Skip() > > ? ? def OnIconify(self, event): > ? ? ? ? self.Hide() > > ? ? def get_image(self): > ? ? ? ? img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO) > ? ? ? ? return img > > ? ? def get_icon(self): > ? ? ? ? img = self.get_image() > ? ? ? ? icon = wx.IconFromBitmap(img.ConvertToBitmap() ) > ? ? ? ? return icon > > if __name__ == '__main__': > ? ? main() Sorry for spamming this group. I found that this was due to a interaction with pyHook and the wxPython GUI. I havent solved it, but atleast it is not due to twisted and wxPython. From steve at REMOVE-THIS-cybersource.com.au Tue Aug 4 23:07:26 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Aug 2009 13:07:26 +1000 Subject: no-clobber dicts? References: Message-ID: <00027aa9$0$2969$c3e8da3@news.astraweb.com> On Wed, 5 Aug 2009 06:01 am kj wrote: > In Steven > D'Aprano writes: > >>class ConstantNamespace(dict): > > >>I also have a series of unit tests for it if you're interested in them. > > Actually, come to think of it, I think I'll take you up on this. > I'd love to see those tests. Unit testing in Python is in area I > need to work on. No problem. Here you go: http://www.cybersource.com.au/users/steve/python/constants.py Comments welcome. -- Steven From sturlamolden at yahoo.no Tue Aug 4 23:46:30 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 4 Aug 2009 20:46:30 -0700 (PDT) Subject: Is python buffer overflow proof? References: <7dnissF2bthr0U1@mid.uni-berlin.de> Message-ID: On Aug 4, 2:27?pm, Tim Chase wrote: > You *can* shoot yourself in the foot with Python, you just have > to aim much more carefully than you do with C/C++. You can e.g. define a class with a __del__ method and make some circular references. That should give you a nice memory leak. From IDOL at il.ibm.com Wed Aug 5 00:24:48 2009 From: IDOL at il.ibm.com (Ido Levy) Date: Wed, 5 Aug 2009 07:24:48 +0300 Subject: How to fetch an XML file using an HTTPS query In-Reply-To: <49b3a7400908040641l5f5daaa8v374041b7fbac442a@mail.gmail.com> References: <49b3a7400908040638h46d4e4dcxe5cd4120e9c2c7a1@mail.gmail.com> <49b3a7400908040641l5f5daaa8v374041b7fbac442a@mail.gmail.com> Message-ID: Hi Tycho, Thank you for your advice. My problem was in the query itself, I replaced every space character with '%20' and it works. You are right, the Python code below does do the work. Ido From: Tycho Andersen To: python-list at python.org Date: 04/08/2009 04:42 PM Subject: Re: How to fetch an XML file using an HTTPS query Blah, forgot to include the list. When is python-list going to get Reply-To? \t On Tue, Aug 4, 2009 at 8:38 AM, Tycho Andersen wrote: > Hi Ido, > > On Tue, Aug 4, 2009 at 6:25 AM, Ido Levy wrote: >> [snip] >> I got the following result in both cases: >> >> >> Invalid filter passed. >> > > To me, this doesn't look like a python problem: the application was > successfully connected to and returned a result. The problem you're > experiencing is that it wasn't the result you expected. Are you sure > you're setting the right headers, posting the right form values, etc. > and giving the app exactly what it wants? > > \t > -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From hjtoi-better-remove-before-reply at comcast.net Wed Aug 5 00:50:31 2009 From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen) Date: Tue, 04 Aug 2009 21:50:31 -0700 Subject: M2Crypto: How to generate subjectKeyIdentifier / authorityKeyIdentifier References: Message-ID: Matthias G?ntert wrote: > I am trying to add the extensions "subjectKeyIdentifier" and > "authorityKeyIdentifier" to a x509v3 certificate. M2Crypto has a couple of bugs open related that, with potential workarounds that I haven't yet deemed polished enough to checkin, but which might help you out: https://bugzilla.osafoundation.org/show_bug.cgi?id=7530 https://bugzilla.osafoundation.org/show_bug.cgi?id=12151 -- Heikki Toivonen - http://heikkitoivonen.net From nick.m.daly at gmail.com Wed Aug 5 01:06:45 2009 From: nick.m.daly at gmail.com (Nick Daly) Date: Wed, 05 Aug 2009 00:06:45 -0500 Subject: The Perils of PyContract (and Generators) Message-ID: <4A791365.50905@gmail.com> So, just in case any body else runs into this strange, strange happening, I thought I might as well document it somewhere Google can find it. Contracts for Python[0] and generators don't necessarily play well together. This mail comes in three parts, first, the example code that didn't work at all, second, a more in-depth view of the situation while you mull over the solution, and third, the answer. The trouble with this example is that even with all the (2 lines of) boilerplate code required to make PyContract work, the entire example is all of about a dozen lines long. The lines after the "post:" directive are executed every time the function returns, and if any one of them is false, PyContract raises an exception, preventing the calling code from acting on bad data: import os def find_files(name, directory="."): """Finds files with the sub-string name in the name. post: forall(__return__, lambda filename: name in filename) """ for root, dirs, files in os.walk(directory): for the_file in files: if name in the_file: yield the_file import contract contract.checkmod(__name__) That's it. We're just walking the directory and returning the next matching item in the generator when it's called. However, if we try executing this simple function in ipy (Interactive Python, not Iron Python), nothing works as you'd expect: In a directory containing 4 files: ["one fish", "two fish", "red fish", "blue fish"] >>> find_files("fish") >>> z = find_files("fish") >>> z.next() StopIteration: ... Apparently our generator object is empty whenever it's returned. When adding a print statement right before the yield, we see: >>> z = find_files("o") "one fish" "two fish" >>> z.next() StopIteration: ... Why are they printing during the function? Why is everything printing before the function even returns?? Has my python croaked? (How actors and serpents could both behave like amphibians is beyond me) The trouble is that when the yield statement is replaced with a return statement, everything works exactly as you might expect. It's perfect. Unit tests don't fail, doctests are happy, and dependent code works exactly as advertised. When you turn it back into a generator though, well, generating empty lists for everything isn't helpful. Getting irritated at it, I eventually just decided to comment out and remove as many lines as possible (11) without actually breaking the example, at which point it started working... What? The problem actually lies in the contract. Generally, the PyContract shouldn't affect the return values or in any way modify the code, which it doesn't, as long as the function returns a list values (the way the code had in fact originally been written). However, the contract mentioned above is actually quite wrong for a generator. PyContract's forall function checks every value in the list (exhausting the list) before returning it, and actually operates on the actual return value, and not a copy. Thus, when the forall function verifies all the values in the list, it's generating every value in the list, emptying the generator before it's returned. Correcting the above example involves doing nothing more than simplifying the contract: post: name in __return__ So, in conclusion, generators and PyContract's forall() function don't mix, and PyContract doesn't operate off of a copy of your parameters unless you explicitly tell it so (I don't think it ever operates off a copy of your return value). Nick 0: http://www.wayforward.net/pycontract/ From sturlamolden at yahoo.no Wed Aug 5 01:21:20 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 4 Aug 2009 22:21:20 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: Message-ID: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> On Aug 5, 4:37 am, erikcw wrote: > It's not always the same traceback, but they are always short like > this. I'm running Python 2.6.2 on Ubuntu 9.04. > > Any idea how I can debug this? In my experience, multiprocessing is fragile. Scripts tend fo fail for no obvious reason, case processes to be orphaned and linger, system- wide resource leaks, etc. For example, multiprocessing uses os._exit to stop a spawned process, even though it inevitably results in resource leaks on Linux (it should use sys.exit). Ga?l Varoquaux and I noticed this when we implemented shared memory ndarrays for numpy; we consistently got memory leaks with System V IPC for no obvious reason. Even after Jesse Noller was informed of the problem (about half a year ago), the bug still lingers. It is easy edit multiprocessing's forking.py file on you own, but bugs like this is a pain in the ass, and I suspect multiprocessing has many of them. Of course unless you show us you whole script, identifying the source of your bug will be impossible. But it may very likely be in multiprocessing as well. The quality of this module is not impressing. I am beginning to think that multiprocessing should never have made it into the Python standard library. The GIL cannot be that bad! If you can't stand the GIL, get a Unix (or Mac, Linux, Cygwin) and use os.fork. Or simply switch to a non-GIL Python: IronPython or Jython. Allow me to show you something better. With os.fork we can write code like this: class parallel(object): def __enter__(self): # call os.fork def __exit__(self, exc_type, exc_value, traceback): # call sys.exit in the child processes and # os.waitpid in the parent def __call__(self, iterable): # return different sub-subsequences depending on # child or parent status with parallel() as p: # parallel block starts here for item in p(iterable): # whatever # parallel block ends here This makes parallel code a lot cleaner than anything you can do with multiprocessing, allowing you to use constructs similar to OpenMP. Further, if you make 'parallel' a dummy context manager, you can develop and test the algorithms serially. The only drawback is that you have to use Cygwin to get os.fork on Windows, and forking will be less efficient (no copy-on-write optimization). Well, this is just one example of why Windows sucks from the perspective of the programmer. But it also shows that you can do much better by not using multiprocessing at all. The only case I can think of where multiprocessing would be usesful, is I/O bound code on Windows. But here you will almost always resort to C extension modules. For I/O bound code, Python tends to give you a 200x speed penalty over C. If you are resorting to C anyway, you can just use OpenMP in C for your parallel processing. We can thus forget about multiprocessing here as well, given that we have access to the C code. If we don't, it is still very likely that the C code releases the GIL, and we can get away with using Python threads instead of multiprocessing. IMHO, if you are using multiprocessing, you are very likely to have a design problem. Regards, Sturla From wuwei23 at gmail.com Wed Aug 5 01:45:50 2009 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 Aug 2009 22:45:50 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: <80f475f8-e6ea-4960-bdb8-86a90c60d656@y10g2000prf.googlegroups.com> John Posner wrote: > OK, then why the statements "from turtle import *" in the modules > turtleprocess.py and turtlewidget.py? Looking in the source I'd say it's because there's a local turtle.py. From mensanator at aol.com Wed Aug 5 01:49:16 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Aug 2009 22:49:16 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy Message-ID: I hadn't noticed this before, but the overhaul of Turtle Graphics dating back to 2.6 has been broken as far as gmpy is concerned. I hadn't noticed because I usually have tracing turned off (tracing off takes 3-4 seconds, tracing on takes 6-7 minutes). In 3.1, tracing is now a screen attribute, not a turtle atribute. I have no idea why tooter = turtle.Turtle() tooter.tracer(False) doesn't give me an error (I thought silent errors were a bad thing). Had to change to tooter = turtle.Turtle() tooter.screen.tracer(False) # tracer now a screen attribute to turn tracing off in 3.1. Naturally, having tracing on caused my program to crash. The 2.6 version seemed to work, but only because turning off tracing as a turtle attribute works in 2.6. So I turned it back on and it crashed too. 2.5 worked okay. The reason is that code in turtle.py was chabged from v2.5 if self._drawing: if self._tracing: dx = float(x1 - x0) dy = float(y1 - y0) distance = hypot(dx, dy) nhops = int(distance) to v3.1 if self._speed and screen._tracing == 1: diff = (end-start) diffsq = (diff[0]*screen.xscale)**2 + (diff[1] *screen.yscale)**2 nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed) *self._speed)) Unfortunately, that calculation of nhops is illegal if diffsq is an .mpf (gmpy floating point). Otherwise, you get Traceback (most recent call last): File "K:\user_python26\turtle\turtle_xy_Py3.py", line 95, in tooter.goto(the_coord) File "C:\Python31\lib\turtle.py", line 1771, in goto self._goto(Vec2D(*x)) File "C:\Python31\lib\turtle.py", line 3165, in _goto nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed)) ValueError: mpq.pow fractional exponent, inexact-root So when using gmpy, you have to convert the .mpz to int before calling turtle functions. (if tracing is on). demo code (fixed code commented out) import gmpy ## (even) hi----| ## | ## lo (odd) ## or ## ## (even) lo ## | ## | ## ----hi (odd) ## ## ## ## import turtle tooter = turtle.Turtle() tooter.hideturtle() tooter.speed('fast') turtle.update() # make tracer false and it works #tooter.screen.tracer(False) # tracer now a screen attribute tooter.penup() tooter.color('black') s = ['1','0'] while len(s[0])<10000: s = [''.join(s), s[0]] origin = [0,0] if s[0] == '0': tooter.goto(origin) tooter.dot(1) if s[1] == '0': tooter.goto([1,0]) tooter.dot(1) print(len(s[0])) for i,j in enumerate(s[0]): the_coord=[] cur_root = gmpy.sqrt(i) lo__root = gmpy.sqrt(i)**2 hi__root = ((gmpy.sqrt(i)+1)**2) ## cur_root = int(gmpy.sqrt(i)) ## lo__root = int(gmpy.sqrt(i)**2) ## hi__root = int(((gmpy.sqrt(i)+1)**2)) if hi__root%2==0: side = 'northeast' else: side = 'southwest' elbow = (hi__root - lo__root)//2 + lo__root + 1 if i>= elbow: side_len = i - elbow elbow_plus = True else: side_len = elbow - i elbow_plus = False if side == 'northeast': elbow_offset = [(gmpy.sqrt(elbow)-1)//2 +1,-((gmpy.sqrt(elbow)-1)// 2) +1] else: elbow_offset = [-((gmpy.sqrt(elbow)-1)//2 +1),((gmpy.sqrt (elbow)-1)//2 +1)] ## if side == 'northeast': ## elbow_offset = [int((gmpy.sqrt(elbow)-1)//2 +1),-int(((gmpy.sqrt (elbow)-1)//2) +1)] ## else: ## elbow_offset = [-int(((gmpy.sqrt(elbow)-1)//2 +1)),int (((gmpy.sqrt(elbow)-1)//2 +1))] elbow_coord = [origin[0]+elbow_offset[0],origin[1]+elbow_offset[1]] if i != hi__root and i != lo__root: if i == elbow: the_coord = elbow_coord else: if elbow_plus: if side == 'northeast': the_coord = [elbow_coord[0]-side_len,elbow_coord[1]] else: the_coord = [elbow_coord[0]+side_len,elbow_coord[1]] else: if side == 'northeast': the_coord = [elbow_coord[0],elbow_coord[1]+side_len] else: the_coord = [elbow_coord[0],elbow_coord[1]-side_len] else: if i % 2 == 0: # even square n = gmpy.sqrt(i)//2 - 1 ## n = int(gmpy.sqrt(i)//2) - 1 the_coord = [-n, -n-1] else: n = (gmpy.sqrt(i)-1)//2 - 1 ## n = int((gmpy.sqrt(i)-1)//2) - 1 the_coord = [1+n, 1+n] if j == '0': tooter.goto(the_coord) tooter.dot(2) print('done') turtle.update() turtle.done() print('done') From pfeldman at verizon.net Wed Aug 5 02:28:29 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Tue, 4 Aug 2009 23:28:29 -0700 (PDT) Subject: trouble with complex numbers Message-ID: <24821423.post@talk.nabble.com> When I try to compute the phase of a complex number, I get an error message: In [3]: from cmath import * In [4]: x=1+1J In [5]: phase(x) NameError: name 'phase' is not defined AttributeError: 'complex' object has no attribute 'phase' Any advice will be appreciated. -- View this message in context: http://www.nabble.com/trouble-with-complex-numbers-tp24821423p24821423.html Sent from the Python - python-list mailing list archive at Nabble.com. From ryniek90 at gmail.com Wed Aug 5 02:50:08 2009 From: ryniek90 at gmail.com (ryniek) Date: Tue, 4 Aug 2009 23:50:08 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> Message-ID: <581a0c92-3117-4712-bfac-a3b9c4f6eb97@26g2000yqk.googlegroups.com> On 5 Sie, 00:55, MRAB wrote: > ryniek90 wrote: > > Hi. > > I started learning regexp, and some things goes well, but most of them > > still not. > > > I've got problem with some regexp. Better post code here: > > > " > > ?>>> import re > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > ?>>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > ?>>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = re.sub('^\n|$\n', '', mail) > > ?>>> print maail > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > ?>>> maail = re.sub(' ', '', maail) > > ?>>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > > ?>>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > > ?>>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > ?>>> #How must i write the replace string to replace all this regexp's > > with just ONE command, in string 'mail' ? > > ?>>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', > > *?*, mail) > > " > > > How must i write that replace pattern (look at question mark), to maek > > that substituion work? I didn't saw anything helpful while reading Re > > doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but > > something gone wrong - didn't wrote it right. > > Is there more user friendly HowTo for Python Re, than this? > > > I'm new to programming an regexp, sorry for inconvenience. > > I don't think you can do it in one regex, nor would I want to. Just use > the string's replace() method. > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > mail [$dot$] com\n' > ?>>> mail > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > ?>>> print mail > > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > ?>>> maail = mail.strip() > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > ?>>> maail = maail.replace(' ', '') > ?>>> print maail > n... at mail.com > name1[at]mail[dot]com > name2[$at$]mail[$dot$]com > ?>>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > ?>>> print maail > n... at mail.com > name1 at mail[dot]com > name2 at mail[$dot$]com > ?>>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > ?>>> print maail > n... at mail.com > na... at mail.com > na... at mail.com Too bad, I thought that the almighty re module could do anything, but it failed with this (or maybe re can do what i want, but only few people knows how to force him to that? :P). But with help of MRAB, i choose The 3rd Point of Python's Zen - "Simple is better than complex." " >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> mail '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> print mail name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = mail.lstrip().rstrip().replace(' ', '').replace('[dot]', '.').replace('[$dot$]', '.').replace('[at]', '@').replace('[$at$]', '@') >>> print maail name at mail.com name1 at mail.com name2 at mail.com >>> #Did it :) " Thanks again :) From ryniek90 at gmail.com Wed Aug 5 02:53:56 2009 From: ryniek90 at gmail.com (ryniek) Date: Tue, 4 Aug 2009 23:53:56 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> Message-ID: <45b7bc73-9c60-4da5-beda-1c2536add738@c1g2000yqi.googlegroups.com> On 5 Sie, 00:55, MRAB wrote: > ryniek90 wrote: > > Hi. > > I started learning regexp, and some things goes well, but most of them > > still not. > > > I've got problem with some regexp. Better post code here: > > > " > > ?>>> import re > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > ?>>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > ?>>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = re.sub('^\n|$\n', '', mail) > > ?>>> print maail > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > ?>>> maail = re.sub(' ', '', maail) > > ?>>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > > ?>>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > > ?>>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > ?>>> #How must i write the replace string to replace all this regexp's > > with just ONE command, in string 'mail' ? > > ?>>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', > > *?*, mail) > > " > > > How must i write that replace pattern (look at question mark), to maek > > that substituion work? I didn't saw anything helpful while reading Re > > doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but > > something gone wrong - didn't wrote it right. > > Is there more user friendly HowTo for Python Re, than this? > > > I'm new to programming an regexp, sorry for inconvenience. > > I don't think you can do it in one regex, nor would I want to. Just use > the string's replace() method. > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > mail [$dot$] com\n' > ?>>> mail > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > ?>>> print mail > > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > ?>>> maail = mail.strip() > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > ?>>> maail = maail.replace(' ', '') > ?>>> print maail > n... at mail.com > name1[at]mail[dot]com > name2[$at$]mail[$dot$]com > ?>>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > ?>>> print maail > n... at mail.com > name1 at mail[dot]com > name2 at mail[$dot$]com > ?>>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > ?>>> print maail > n... at mail.com > na... at mail.com > na... at mail.com Too bad, I thought that the almighty re module could do anything, but it failed with this (or maybe re can do what i want, but only few people knows how to force him to that? :P). But with help of MRAB, i choose The 3rd Point of Python's Zen - "Simple is better than complex." " >>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> mail '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> print mail n... at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = mail.lstrip().rstrip().replace(' ', '').replace('[dot]', '.').replace('[$dot$]', '.').replace('[at]', '@').replace('[$at$]', '@') >>> print maail n... at mail.com na... at mail.com na... at mail.com >>> #Did it :) " Thanks again :) From casevh at gmail.com Wed Aug 5 02:54:12 2009 From: casevh at gmail.com (casevh) Date: Tue, 4 Aug 2009 23:54:12 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: Message-ID: On Aug 4, 10:49?pm, Mensanator wrote: > I hadn't noticed this before, but the overhaul of Turtle Graphics > dating > back to 2.6 has been broken as far as gmpy is concerned. > The reason is that code in turtle.py was chabged from > > v2.5 > ? ? ? ? if self._drawing: > ? ? ? ? ? ? if self._tracing: > ? ? ? ? ? ? ? ? dx = float(x1 - x0) > ? ? ? ? ? ? ? ? dy = float(y1 - y0) > ? ? ? ? ? ? ? ? distance = hypot(dx, dy) > ? ? ? ? ? ? ? ? nhops = int(distance) > > to > > v3.1 > ? ? ? ?if self._speed and screen._tracing == 1: > ? ? ? ? ? ? diff = (end-start) > ? ? ? ? ? ? diffsq = (diff[0]*screen.xscale)**2 + (diff[1] > *screen.yscale)**2 > ? ? ? ? ? ? nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed) > *self._speed)) > > Unfortunately, that calculation of nhops is illegal if diffsq is > an .mpf (gmpy > floating point). Otherwise, you get > > Traceback (most recent call last): > ? File "K:\user_python26\turtle\turtle_xy_Py3.py", line 95, in > > ? ? tooter.goto(the_coord) > ? File "C:\Python31\lib\turtle.py", line 1771, in goto > ? ? self._goto(Vec2D(*x)) > ? File "C:\Python31\lib\turtle.py", line 3165, in _goto > ? ? nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed)) > ValueError: mpq.pow fractional exponent, inexact-root > Warning: Completely untested fix ahead! What happens if you change turtle.py to use nhops=1+int((math.sqrt(diffsq)/(3*math.pow(1.1, self._speed) *self._speed)) casevh From steve at REMOVE-THIS-cybersource.com.au Wed Aug 5 03:19:52 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Aug 2009 17:19:52 +1000 Subject: Turtle Graphics are incompatible with gmpy References: Message-ID: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> On Wed, 5 Aug 2009 03:49 pm Mensanator wrote: > In 3.1, tracing is now a screen attribute, not a turtle atribute. > I have no idea why > > tooter = turtle.Turtle() > tooter.tracer(False) > > doesn't give me an error (I thought silent errors were a bad thing). What makes it an error? Do you consider the following an error? >>> class Test: ... pass ... >>> t = Test() >>> t.tracer = 5 >>> Perhaps you mean, it's an API change you didn't know about, and you wish to protest that Turtle Graphics made an incompatible API change without telling you? > Naturally, having tracing on caused my program to crash. It seg faulted or raised an exception? [...] > Unfortunately, that calculation of nhops is illegal if diffsq is > an .mpf (gmpy floating point). Otherwise, you get How does diffsq get to be a mpf? Are gmpy floats supposed to be supported? -- Steven From gregor.lingl at aon.at Wed Aug 5 03:21:44 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Wed, 05 Aug 2009 09:21:44 +0200 Subject: Turtle Graphics are incompatible with gmpy In-Reply-To: References: Message-ID: <4a793315$0$2305$91cee783@newsreader02.highway.telekom.at> Mensanator schrieb: > I hadn't noticed this before, but the overhaul of Turtle Graphics > dating > back to 2.6 has been broken as far as gmpy is concerned. > > I hadn't noticed because I usually have tracing turned off (tracing > off > takes 3-4 seconds, tracing on takes 6-7 minutes). > > In 3.1, tracing is now a screen attribute, not a turtle atribute. > I have no idea why > > tooter = turtle.Turtle() > tooter.tracer(False) > > doesn't give me an error (I thought silent errors were a bad thing). > Hi, on my machine I get: Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import turtle >>> tooter = turtle.Turtle() >>> tooter.tracer(False) Traceback (most recent call last): File "", line 1, in tooter.tracer(False) AttributeError: 'Turtle' object has no attribute 'tracer' >>> I'd like to help with your problem but I'd much better be able to analyze it, if I had a version of your script, which works as you intended with Python 2.5 and the old turtle module. Could you please post it? (The one you posted below uses some commands of the turtle 2.6 module which are not present in 2.5, so it doesn't run with Python 2.5) Regards, Gregor > Had to change to > > tooter = turtle.Turtle() > tooter.screen.tracer(False) # tracer now a screen attribute > > to turn tracing off in 3.1. > > Naturally, having tracing on caused my program to crash. The 2.6 > version > seemed to work, but only because turning off tracing as a turtle > attribute > works in 2.6. > > So I turned it back on and it crashed too. > > 2.5 worked okay. > > The reason is that code in turtle.py was chabged from > > v2.5 > if self._drawing: > if self._tracing: > dx = float(x1 - x0) > dy = float(y1 - y0) > distance = hypot(dx, dy) > nhops = int(distance) > > to > > v3.1 > if self._speed and screen._tracing == 1: > diff = (end-start) > diffsq = (diff[0]*screen.xscale)**2 + (diff[1] > *screen.yscale)**2 > nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed) > *self._speed)) > > Unfortunately, that calculation of nhops is illegal if diffsq is > an .mpf (gmpy > floating point). Otherwise, you get > > Traceback (most recent call last): > File "K:\user_python26\turtle\turtle_xy_Py3.py", line 95, in > > tooter.goto(the_coord) > File "C:\Python31\lib\turtle.py", line 1771, in goto > self._goto(Vec2D(*x)) > File "C:\Python31\lib\turtle.py", line 3165, in _goto > nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed)) > ValueError: mpq.pow fractional exponent, inexact-root > > So when using gmpy, you have to convert the .mpz to int before calling > turtle > functions. (if tracing is on). > > demo code (fixed code commented out) > > import gmpy > > ## (even) hi----| > ## | > ## lo (odd) > ## or > ## > ## (even) lo > ## | > ## | > ## ----hi (odd) > ## > ## > ## > ## > > import turtle > > tooter = turtle.Turtle() > > tooter.hideturtle() > tooter.speed('fast') > turtle.update() > # make tracer false and it works > #tooter.screen.tracer(False) # tracer now a screen attribute > tooter.penup() > tooter.color('black') > > s = ['1','0'] > while len(s[0])<10000: > s = [''.join(s), s[0]] > > > origin = [0,0] > if s[0] == '0': > tooter.goto(origin) > tooter.dot(1) > if s[1] == '0': > tooter.goto([1,0]) > tooter.dot(1) > > print(len(s[0])) > > for i,j in enumerate(s[0]): > the_coord=[] > cur_root = gmpy.sqrt(i) > lo__root = gmpy.sqrt(i)**2 > hi__root = ((gmpy.sqrt(i)+1)**2) > ## cur_root = int(gmpy.sqrt(i)) > ## lo__root = int(gmpy.sqrt(i)**2) > ## hi__root = int(((gmpy.sqrt(i)+1)**2)) > > if hi__root%2==0: > side = 'northeast' > else: > side = 'southwest' > > elbow = (hi__root - lo__root)//2 + lo__root + 1 > > if i>= elbow: > > side_len = i - elbow > elbow_plus = True > else: > side_len = elbow - i > elbow_plus = False > > if side == 'northeast': > elbow_offset = [(gmpy.sqrt(elbow)-1)//2 +1,-((gmpy.sqrt(elbow)-1)// > 2) +1] > else: > elbow_offset = [-((gmpy.sqrt(elbow)-1)//2 +1),((gmpy.sqrt > (elbow)-1)//2 +1)] > ## if side == 'northeast': > ## elbow_offset = [int((gmpy.sqrt(elbow)-1)//2 +1),-int(((gmpy.sqrt > (elbow)-1)//2) +1)] > ## else: > ## elbow_offset = [-int(((gmpy.sqrt(elbow)-1)//2 +1)),int > (((gmpy.sqrt(elbow)-1)//2 +1))] > > elbow_coord = [origin[0]+elbow_offset[0],origin[1]+elbow_offset[1]] > > if i != hi__root and i != lo__root: > if i == elbow: > the_coord = elbow_coord > else: > if elbow_plus: > if side == 'northeast': > the_coord = [elbow_coord[0]-side_len,elbow_coord[1]] > else: > the_coord = [elbow_coord[0]+side_len,elbow_coord[1]] > else: > if side == 'northeast': > the_coord = [elbow_coord[0],elbow_coord[1]+side_len] > else: > the_coord = [elbow_coord[0],elbow_coord[1]-side_len] > else: > if i % 2 == 0: # even square > n = gmpy.sqrt(i)//2 - 1 > ## n = int(gmpy.sqrt(i)//2) - 1 > the_coord = [-n, -n-1] > else: > n = (gmpy.sqrt(i)-1)//2 - 1 > ## n = int((gmpy.sqrt(i)-1)//2) - 1 > the_coord = [1+n, 1+n] > if j == '0': > tooter.goto(the_coord) > tooter.dot(2) > print('done') > > turtle.update() > turtle.done() > print('done') From steve at REMOVE-THIS-cybersource.com.au Wed Aug 5 03:23:29 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Aug 2009 17:23:29 +1000 Subject: The Perils of PyContract (and Generators) References: Message-ID: <0002b6ac$0$2970$c3e8da3@news.astraweb.com> On Wed, 5 Aug 2009 03:06 pm Nick Daly wrote: > The problem actually lies in the contract. Generally, the PyContract > shouldn't affect the return values or in any way modify the code, which > it doesn't, as long as the function returns a list values (the way the > code had in fact originally been written). However, the contract > mentioned above is actually quite wrong for a generator. Yes, because you are conflating the items yielded from the generator with the generator object returned from the generator function "find_files". You can't look inside the generator object without using up whichever items you look at. [...] > Correcting the above example involves doing nothing more than > simplifying the contract: > > post: > name in __return__ That can't be right, not unless PyContract is doing something I don't expect. I expect that would be equivalent of: 'fish' in which should fail: >>> __return__ = find_files('fish') # a generator object >>> 'fish' in __return__ False >>> >>> __return__ = find_files('fish') >>> __return__ = list(__return__) >>> 'fish' in __return__ False >>> __return__ ['one fish', 'two fish', 'red fish', 'blue fish'] Of course, I may be mistaking what PyContract is doing. -- Steven From rays at blue-cove.com Wed Aug 5 03:25:03 2009 From: rays at blue-cove.com (RayS) Date: Wed, 05 Aug 2009 00:25:03 -0700 Subject: Cypress FX2 - py libusb code? Message-ID: <5.2.1.1.2.20090804224315.01c22b60@pop-server.san.rr.com> An HTML attachment was scrubbed... URL: From gregor.lingl at aon.at Wed Aug 5 03:37:08 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Wed, 05 Aug 2009 09:37:08 +0200 Subject: Turtle Graphics are incompatible with gmpy In-Reply-To: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: <4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> Steven D'Aprano schrieb: > On Wed, 5 Aug 2009 03:49 pm Mensanator wrote: > >> In 3.1, tracing is now a screen attribute, not a turtle atribute. >> I have no idea why >> >> tooter = turtle.Turtle() >> tooter.tracer(False) >> >> doesn't give me an error (I thought silent errors were a bad thing). > > What makes it an error? Do you consider the following an error? > >>>> class Test: > ... pass > ... >>>> t = Test() >>>> t.tracer = 5 >>>> > > Perhaps you mean, it's an API change you didn't know about, and you wish to > protest that Turtle Graphics made an incompatible API change without > telling you? > It didn't form 2.5 to 2.6 (at least not intentionally). But with the indroduction of the TurtleScreen class and the Screen class/object (singleton) a few of the turtle methods were also implemented as screen methods and as turtle methods declared deprecated (see docs of Python 2.6). These deprecated turtle methods do not occur as turtle methods any more in Python 3.x. Among them is the tracer method, which in fact does not control single turtle objects but all the turtles on a given screen. So there is an icompatibility beween 2.6 and 3.x But as far as I have understood, this doesn't concern the problem reported by mensator. Regards, Gregor > >> Naturally, having tracing on caused my program to crash. > > It seg faulted or raised an exception? > > > [...] >> Unfortunately, that calculation of nhops is illegal if diffsq is >> an .mpf (gmpy floating point). Otherwise, you get > > How does diffsq get to be a mpf? Are gmpy floats supposed to be supported? > > > From news123 at free.fr Wed Aug 5 03:44:18 2009 From: news123 at free.fr (News123) Date: Wed, 05 Aug 2009 09:44:18 +0200 Subject: merge two png pic In-Reply-To: <72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com> References: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> <4a77e249$0$2449$426a74cc@news.free.fr> <72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com> Message-ID: <4a793852$0$19598$426a74cc@news.free.fr> You didn't really tell us why you need one big file, which contains more pixel, than you can probably store in RAM Is it for printing? Not knwoing your goal makes it difficult to suggest solutions. Can't you use other image formats like raw RGB or What other image formats are supported? tiff? Raw? PPM ( http://en.wikipedia.org/wiki/Portable_pixmap )? concatenating raw/ppm files with the same width would be really trivial. so you could use python to create horizontal raw/ppm stripes. then you could concatenate them without having to have the whole image in RAM. Perhaps there's even converters from ppm to png, that don't need the whole image in RAM. cocobear wrote: > On Aug 4, 3:24 pm, News123 wrote: >> Hi, >> >> >> >> >> >> cocobear wrote: >>>>>>> Map = Image.new("RGB", (x,y)) >>>>>>> Map.paste(im, box) >>>>>>> Map.paste(im1,box) >>>>>>> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE) >>>>>>> But if thetwopngpicis too big , or if I have tomergemorepic >>>>>>> together, I will get MemoryError: >>>>>>>>>>>>> Image.new("RGB",(44544,38656)) >>>> What do you want to do with such a big image? You will run into the same >>>> limitation when you are trying to display it. >>> I want to download a map from google map with high precision >> For me it sounds strange to handle such big files. >> >> Is the map you download from Google really that big? >> Mostly Google maps uses normally tiles of sizes 256x256 pixel, wich you >> have to compose to get the big image. >> > > The map I downloaded from Google is small(256x256). These small maps > will compose a big image. > > > >> If your problem is to combine tiles with different palettes, then you >> should pobably look at a way to 'unify' the palette of all tiles befor >> combining them. >> > > I think it is impossible to 'unify' all this tiles. > > >> Being no expert of PIL I don't know whether this is easily possible though? >> >> bye >> >> N > From hendrik at microcorp.co.za Wed Aug 5 03:56:33 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 5 Aug 2009 09:56:33 +0200 Subject: Using Python to automate builds In-Reply-To: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> Message-ID: <200908050956.33995.hendrik@microcorp.co.za> On Tuesday 04 August 2009 21:13:10 Kosta wrote: > I am a Python newbie, tasked with automating (researching) building > Windows drivers using the WDK build environment. I've been looking > into Python for this (instead of writing a bunch of batch files). > Why do you not use make and a makefile - it was designed to do exactly this. - Hendrik From fafounet at gmail.com Wed Aug 5 04:08:14 2009 From: fafounet at gmail.com (Fafounet) Date: Wed, 5 Aug 2009 01:08:14 -0700 (PDT) Subject: Special chars with HTMLParser Message-ID: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com> Hello, I am parsing a web page with special chars such as é (which stands for ?). I know I can have the unicode character ? from unicode ("\xe9","iso-8859-1") but with those extra characters I don' t know. I tried to implement handle_charref within HTMLParser without success. Furthermore, if I have the data abécd, handle_data will get "ab", handle_charref will get xe9 and then handle_data doesn't have the end of the string ("cd"). Thank you for your help, Fabien From clp2 at rebertia.com Wed Aug 5 04:40:59 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 5 Aug 2009 01:40:59 -0700 Subject: trouble with complex numbers In-Reply-To: <24821423.post@talk.nabble.com> References: <24821423.post@talk.nabble.com> Message-ID: <50697b2c0908050140g3acd8a8cx9fc87af12ea77c31@mail.gmail.com> On Tue, Aug 4, 2009 at 11:28 PM, Dr. Phillip M. Feldman wrote: > > When I try to compute the phase of a complex number, I get an error message: > > In [3]: from cmath import * > In [4]: x=1+1J > In [5]: phase(x) > > NameError: name 'phase' is not defined > > AttributeError: 'complex' object has no attribute 'phase' I suspect the problem lies in what you snipped away: In [1]: from cmath import phase In [2]: x=1+1J In [3]: phase(x) Out[3]: 0.78539816339744828 Cheers, Chris -- http://blog.rebertia.com From wuwei23 at gmail.com Wed Aug 5 04:43:13 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Aug 2009 01:43:13 -0700 (PDT) Subject: trouble with complex numbers References: Message-ID: On Aug 5, 4:28?pm, "Dr. Phillip M. Feldman" wrote: > When I try to compute the phase of a complex number, I get an error message: > [...] > Any advice will be appreciated. 1. What version of Python are you using, and on what platform? 2. What you snipped is necessary to help debug your problem. 3. Do you have a cmath.py in the folder you're running the interpreter in? From sanu1267 at gmail.com Wed Aug 5 05:03:51 2009 From: sanu1267 at gmail.com (sanju ps) Date: Wed, 5 Aug 2009 14:33:51 +0530 Subject: Launch my application if its not running Message-ID: <2b76be80908050203o5d002a8draf4c8bed564eef2b@mail.gmail.com> How to check whether my gui application is running or not.If its already running i have to quit my program other wise i need to launch my program. Can anybody suggest a solution to this Regards Sanju -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Aug 5 05:07:14 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 5 Aug 2009 02:07:14 -0700 Subject: Launch my application if its not running In-Reply-To: <2b76be80908050203o5d002a8draf4c8bed564eef2b@mail.gmail.com> References: <2b76be80908050203o5d002a8draf4c8bed564eef2b@mail.gmail.com> Message-ID: <50697b2c0908050207h7f2a866fuf63e843a66a7030d@mail.gmail.com> On Wed, Aug 5, 2009 at 2:03 AM, sanju ps wrote: > How to check whether my gui application is running or not.If its already > running i have to quit my program other wise i need to launch my program. > Can anybody suggest a solution to this Use a lock file? http://en.wikipedia.org/wiki/Lock_file#Lock_files Cheers, Chris -- http://blog.rebertia.com From smpoojary at gmail.com Wed Aug 5 05:11:38 2009 From: smpoojary at gmail.com (Mahesh Poojary S) Date: Wed, 5 Aug 2009 02:11:38 -0700 (PDT) Subject: socket.inet_ntop, and pton question In-Reply-To: <12rpns1tkp0e34@corp.supernews.com> References: <12rpns1tkp0e34@corp.supernews.com> Message-ID: <24823395.post@talk.nabble.com> Martin-298 wrote: > > Hi > > Are these functions (inet_ntop(), inet_pton()) from the socket library > supported on Windows. > > If not is there an equivalent for them using Windows > > Ive seen mention of people creating their own in order to use them > > Appreciate the help > > ty > -- > http://mail.python.org/mailman/listinfo/python-list > > You can use the below code: def inet_ntop(address_family, packed_ip): if address_family != AF_INET: raise socket.error, (97, 'Address family not supported by protocol') lIP = [] for ch in packed_ip: lIP.append(str(ord(ch))) strIP = string.join(lIP,'.') return strIP def inet_pton(address_family, ip_string): if address_family != AF_INET: raise socket.error, (97, 'Address family not supported by protocol') lIP = ip_string.split('.') strHexIP = "" for i in lIP: if i == '': continue strHex = "%x" % int(i) strHex = strHex.zfill(2) strHexIP += "\\x"+strHex return strHexIP -- View this message in context: http://www.nabble.com/socket.inet_ntop%2C-and-pton-question-tp8677935p24823395.html Sent from the Python - python-list mailing list archive at Nabble.com. From lists at cheimes.de Wed Aug 5 05:21:18 2009 From: lists at cheimes.de (Christian Heimes) Date: Wed, 05 Aug 2009 11:21:18 +0200 Subject: trouble with complex numbers In-Reply-To: <24821423.post@talk.nabble.com> References: <24821423.post@talk.nabble.com> Message-ID: Dr. Phillip M. Feldman wrote: > When I try to compute the phase of a complex number, I get an error message: > > In [3]: from cmath import * > In [4]: x=1+1J > In [5]: phase(x) > > NameError: name 'phase' is not defined > > AttributeError: 'complex' object has no attribute 'phase' > > Any advice will be appreciated. phase() has been added to Python 2.6 and 3.0. It's not available in Python 2.5 and earlier. If you'd used cmath.phase() instead of the ugly "from cmath import *" statement you'd have seen the correct error message. You can write your own phase() function. This function is mostly correct unless either the real and/or the imag part is NaN or INF. from math import atan2 def phase(z): z += 1j # convert int, long, float to complex return atan2(z.imag, z.real) From Tribulations at Paralleles.invalid Wed Aug 5 06:13:00 2009 From: Tribulations at Paralleles.invalid (TP) Date: Wed, 05 Aug 2009 12:13:00 +0200 Subject: intricated functions: how to share a variable Message-ID: Hi everybody, See the following example: ######### def tutu(): def toto(): print a a = 4 print a a=2 toto() tutu() ########## I obtain the following error: "UnboundLocalError: local variable 'a' referenced before assignment" This is because Python looks in the local context before looking in the global context. The use of "global a" in toto() does not help because global allows to force Python to look for the variable at the module level. So, how to share a variable between intricated functions? Thanks a lot Julien -- python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\ 9&1+,\'Z4(55l4('])" "When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong." (first law of AC Clarke) From albert at spenarnc.xs4all.nl Wed Aug 5 06:35:18 2009 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 05 Aug 2009 10:35:18 GMT Subject: Overlap in python References: Message-ID: In article , Jay Bird wrote: >Hi everyone, > >I've been trying to figure out a simple algorithm on how to combine a >list of parts that have 1D locations that overlap into a non- >overlapping list. For example, here would be my input: > >part name location >a 5-9 >b 7-10 >c 3-6 >d 15-20 >e 18-23 > >And here is what I need for an output: >part name location >c.a.b 3-10 >d.e 15-23 > >I've tried various methods, which all fail. Does anyone have an idea >how to do this? That is an algorithmic question and has little to do with Python. You could proceed as follows: - Order your data by the lower limit - Combine everything with the same lower limit. - Then combine every pair of consecutive entries that overlap. (In you case the second step is not needed.) > >Thank you very much! >Jay -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From deets at nospam.web.de Wed Aug 5 06:39:54 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Aug 2009 12:39:54 +0200 Subject: intricated functions: how to share a variable References: Message-ID: <7dt5rqF2crv46U1@mid.uni-berlin.de> TP wrote: > Hi everybody, > > See the following example: > > ######### > def tutu(): > > def toto(): > > print a > a = 4 > print a > > a=2 > toto() > > tutu() > ########## > > I obtain the following error: > "UnboundLocalError: local variable 'a' referenced before assignment" > > This is because Python looks in the local context before looking in the > global context. > > The use of "global a" in toto() does not help because global allows to > force Python to look for the variable at the module level. > > So, how to share a variable between intricated functions? You could use a class :) Another often used trick is to have a mutable container-object, like this: def tutu(): a = [2] def toto(): a[0] = 4 toto() Diez From clp2 at rebertia.com Wed Aug 5 06:42:23 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 5 Aug 2009 03:42:23 -0700 Subject: intricated functions: how to share a variable In-Reply-To: References: Message-ID: <50697b2c0908050342t5ae6feaauc757021a71521b2a@mail.gmail.com> On Wed, Aug 5, 2009 at 3:13 AM, TP wrote: > Hi everybody, > > See the following example: > > ######### > def tutu(): > > ? ?def toto(): > nonlocal a #note: this requires a rather recent version of python > ? ? ? ?print a > ? ? ? ?a = 4 > ? ? ? ?print a > > ? ?a=2 > ? ?toto() > > tutu() > ########## > > I obtain the following error: > "UnboundLocalError: local variable 'a' referenced before assignment" > > This is because Python looks in the local context before looking in the > global context. > > The use of "global a" in toto() does not help because global allows to force > Python to look for the variable at the module level. > > So, how to share a variable between intricated functions? Details: http://www.python.org/dev/peps/pep-3104/ Cheers, Chris -- http://blog.rebertia.com From bearophileHUGS at lycos.com Wed Aug 5 06:42:58 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Wed, 5 Aug 2009 03:42:58 -0700 (PDT) Subject: Overlap in python References: Message-ID: <4f5f1301-d160-4b61-926d-782277b064e9@r38g2000yqn.googlegroups.com> Albert van der Horst: >That is an algorithmic question and has little to do with Python.< Yes, but comp.lang.python isn't comp.lang.c, that kind of questions are perfectly fine here. They help keep this place from becoming boring. Bye, bearophile From __peter__ at web.de Wed Aug 5 06:46:28 2009 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Aug 2009 12:46:28 +0200 Subject: intricated functions: how to share a variable References: Message-ID: TP wrote: > Hi everybody, > > See the following example: > > ######### > def tutu(): > > def toto(): > > print a > a = 4 > print a > > a=2 > toto() > > tutu() > ########## > > I obtain the following error: > "UnboundLocalError: local variable 'a' referenced before assignment" > > This is because Python looks in the local context before looking in the > global context. > > The use of "global a" in toto() does not help because global allows to > force Python to look for the variable at the module level. > > So, how to share a variable between intricated functions? This limitation is removed in Python 3 with the 'nonlocal' statement: >>> def outer(): ... def inner(): ... nonlocal a ... print(a) ... a = 4 ... print(a) ... a = 2 ... inner() ... print(a) ... >>> outer() 2 4 4 Peter From bearophileHUGS at lycos.com Wed Aug 5 06:47:19 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Wed, 5 Aug 2009 03:47:19 -0700 (PDT) Subject: intricated functions: how to share a variable References: Message-ID: <9a937d26-2375-4836-9824-d34d9f92d284@o15g2000yqm.googlegroups.com> TP: > def tutu(): > > ? ? def toto(): > > ? ? ? ? print a > ? ? ? ? a = 4 > ? ? ? ? print a > > ? ? a=2 > ? ? toto() > > tutu() > ########## > > I obtain the following error: > "UnboundLocalError: local variable 'a' referenced before assignment" > > This is because Python looks in the local context before looking in the > global context. > > The use of "global a" in toto() does not help because global allows to force > Python to look for the variable at the module level. > > So, how to share a variable between intricated functions? Generally your purpose as a programmer is to write the least intricate code. Because the less tricky it is, the more readable it becomes and also the bug count decreases. So probably a better solution is to just use the normal function semantics: you pass them an argument and you take an argument as return value. Such return value will be the new version of the value you talk about. Python3+ has the "nonlocal" statement that may do what you ask for. But as many other things in Python it must be used with judgment, to avoid writing intricate code. Bye, bearophile From marcusw at cox.net Wed Aug 5 07:13:23 2009 From: marcusw at cox.net (Marcus Wanner) Date: Wed, 05 Aug 2009 07:13:23 -0400 Subject: Overlap in python In-Reply-To: <4A78B19D.4020306@mrabarnett.plus.com> References: <4A78B19D.4020306@mrabarnett.plus.com> Message-ID: On 8/4/2009 6:09 PM, MRAB wrote: > >>> parts = [(5, 9, "a"), (7, 10, "b"), (3, 6, "c"), (15, 20, "d"), > (18, 23, "e")] > >>> parts.sort() > >>> parts > [(3, 6, 'c'), (5, 9, 'a'), (7, 10, 'b'), (15, 20, 'd'), (18, 23, 'e')] > >>> # Merge overlapping intervals. > >>> pos = 1 > >>> while pos < len(parts): > # Merge the pair in parts[pos - 1 : pos + 1] if they overlap. > p, q = parts[pos - 1 : pos + 1] > if p[1] >= q[0]: > parts[pos - 1 : pos + 1] = [(p[0], max(p[1], q[1]), p[2] > + "." + q[2])] > else: > # They don't overlap, so try the next pair. > pos += 1 > > > >>> parts > [(3, 10, 'c.a.b'), (15, 23, 'd.e')] > That's the best solution I've seen so far. It even has input/output formatted as close as is reasonably possible to the format specified. As we would say in googlecode, +1. Marcus From marcusw at cox.net Wed Aug 5 07:21:55 2009 From: marcusw at cox.net (Marcus Wanner) Date: Wed, 05 Aug 2009 07:21:55 -0400 Subject: Using Python to automate builds In-Reply-To: References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <48e9dcba-5309-4de6-b833-7abec18120e1@d9g2000prh.googlegroups.com> Message-ID: On 8/4/2009 5:52 PM, Philip Semanchuk wrote: > > On Aug 4, 2009, at 5:40 PM, Kosta wrote: > >> On Aug 4, 2:34 pm, Dave Angel wrote: >>> >>> + I have released pyKook 0.0.2. >>> +http://pypi.python.org/pypi/Kook/0.0.2 >>> +http://www.kuwata-lab.com/kook/ >>> +http://www.kuwata-lab.com/kook/pykook-users-guide.html >>> >>> Other possibilities: >>> + http://pypi.python.org/pypi/vellum/ flexible small 'make' >>> alternative >>> >>> + http://code.google.com/p/waf/ >>> >>> + http://code.google.com/p/fabricate/ >>> >>> DaveA- Hide quoted text - >>> >>> - Show quoted text - >> >> Thanks Dave. I had thought about those three options, and was >> honestly hoping for a foruth (I know, some people are never >> satisfied ;). I'll look into pyKook. Thank you for your help. > > Poof! Your wish is granted! =) > > http://www.scons.org/ > > Dunno if you'll find it better, worse or different than the > alternatives, but there it is. > > have fun > P > > I can highly recommend scons. At dolphin-emu, we use it to daily compile a project containing over 500,000 lines of c/c++ code, which is modified very frequently. It works like a charm, and is seamlessly cross- platform (in my experience). However, it might not be exactly the thing you're looking for. Marcus From anthra.norell at bluewin.ch Wed Aug 5 07:28:18 2009 From: anthra.norell at bluewin.ch (Anthra Norell) Date: Wed, 05 Aug 2009 13:28:18 +0200 Subject: How to write replace string for object which will be substituted? [regexp] In-Reply-To: <4A78BC68.2020601@mrabarnett.plus.com> References: <4A78B425.2010604@gmail.com> <4A78BC68.2020601@mrabarnett.plus.com> Message-ID: <4A796CD2.7050009@bluewin.ch> MRAB wrote: > ryniek90 wrote: >> Hi. >> I started learning regexp, and some things goes well, but most of >> them still not. >> >> I've got problem with some regexp. Better post code here: >> >> " >> >>> import re >> >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] >> mail [$dot$] com\n' >> >>> mail >> '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail >> [$dot$] com\n' >> >>> print mail >> >> name at mail.com >> name1 [at] mail [dot] com >> name2 [$at$] mail [$dot$] com >> >> >>> maail = re.sub('^\n|$\n', '', mail) >> >>> print maail >> name at mail.com >> name1 [at] mail [dot] com >> name2 [$at$] mail [$dot$] com >> >>> maail = re.sub(' ', '', maail) >> >>> print maail >> name at mail.com >> name1[at]mail[dot]com >> name2[$at$]mail[$dot$]com >> >>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) >> >>> print maail >> name at mail.com >> name1 at mail[dot]com >> name2 at mail[$dot$]com >> >>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) >> >>> print maail >> name at mail.com >> name1 at mail.com >> name2 at mail.com >> >>> #How must i write the replace string to replace all this >> regexp's with just ONE command, in string 'mail' ? >> >>> maail = re.sub('^\n|$\n| >> |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', *?*, mail) >> " >> >> How must i write that replace pattern (look at question mark), to >> maek that substituion work? I didn't saw anything helpful while >> reading Re doc and HowTo (from Python Doc). I tried with >> 'MatchObject.group()' but something gone wrong - didn't wrote it right. >> Is there more user friendly HowTo for Python Re, than this? >> >> I'm new to programming an regexp, sorry for inconvenience. >> > I don't think you can do it in one regex, nor would I want to. Just use > the string's replace() method. > > >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > mail [$dot$] com\n' > >>> mail > '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > >>> print mail > > name at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > >>> maail = mail.strip() > name at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > >>> maail = maail.replace(' ', '') > >>> print maail > name at mail.com > name1[at]mail[dot]com > name2[$at$]mail[$dot$]com > >>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > >>> print maail > name at mail.com > name1 at mail[dot]com > name2 at mail[$dot$]com > >>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > >>> print maail > name at mail.com > name1 at mail.com > name2 at mail.com This is a good learning exercise demonstrating the impracticality of regular expressions in a given situation. In the light of the fascination regular expressions seem to exert in general, one might conclude that knowing regular expressions in essence is knowing when not to use them. There is nothing wrong with cascading substitutions through multiple expressions. The OP's solution wrapped up in a function and streamlined for needless regex overkill might look something like this: def translate (s): s1 = s.strip () # Instead of: s1 = re.sub ('^\n|$\n', '', s) s2 = s1.replace (' ', '') # Instead of: s2 = re.sub (' ', '', s1) s3 = re.sub ('\[at\]|\[\$at\$\]', '@', s2) s4 = re.sub ('\[dot\]|\[\$dot\$\]', '.', s3) return s4 print translate (mail) # Tested MRAB's solution using replace () avoids needless regex complexity, but doesn't simplify tedious coding if the number of substitutions is significant. Some time ago I proposed a little module I made to alleviate the tedium. It would handle this case like this: import SE Translator = SE.SE ( ' (32)= [at]=@ [$at$]=@ [dot]=. [$dot$]=. ' ) print Translator (mail.strip ()) # Tested So SE.SE compiles a string composed of any number of substitution definitions into an object that translates anything given it. In a running speed contest it would surely come in last, although in most cases the disadvantage would be imperceptible. Another matter is coding speed. Here the advantage is obvious, even with a set of substitutions as small as this one, let alone with sets in the tens or even hundreds. One inconspicuous but significant feature of SE is that it handles precedence correctly if targets overlap (upstream over downstream and long over short). As far as I know there's nothing in the Python system handling substitution precedence. It always needs to be hand-coded from one case to the next and that isn't exactly trivial. SE can be downloaded from http://pypi.python.org/pypi/SE/2.3. Frederic From joncle at googlemail.com Wed Aug 5 07:40:05 2009 From: joncle at googlemail.com (Jon Clements) Date: Wed, 5 Aug 2009 04:40:05 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> <45b7bc73-9c60-4da5-beda-1c2536add738@c1g2000yqi.googlegroups.com> Message-ID: On 5 Aug, 07:53, ryniek wrote: > On 5 Sie, 00:55, MRAB wrote: > > > > > ryniek90 wrote: > > > Hi. > > > I started learning regexp, and some things goes well, but most of them > > > still not. > > > > I've got problem with some regexp. Better post code here: > > > > " > > > ?>>> import re > > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > > mail [$dot$] com\n' > > > ?>>> mail > > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > > com\n' > > > ?>>> print mail > > > > n... at mail.com > > > name1 [at] mail [dot] com > > > name2 [$at$] mail [$dot$] com > > > > ?>>> maail = re.sub('^\n|$\n', '', mail) > > > ?>>> print maail > > > n... at mail.com > > > name1 [at] mail [dot] com > > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = re.sub(' ', '', maail) > > > ?>>> print maail > > > n... at mail.com > > > name1[at]mail[dot]com > > > name2[$at$]mail[$dot$]com > > > ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > > > ?>>> print maail > > > n... at mail.com > > > name1 at mail[dot]com > > > name2 at mail[$dot$]com > > > ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > > > ?>>> print maail > > > n... at mail.com > > > na... at mail.com > > > na... at mail.com > > > ?>>> #How must i write the replace string to replace all this regexp's > > > with just ONE command, in string 'mail' ? > > > ?>>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', > > > *?*, mail) > > > " > > > > How must i write that replace pattern (look at question mark), to maek > > > that substituion work? I didn't saw anything helpful while reading Re > > > doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but > > > something gone wrong - didn't wrote it right. > > > Is there more user friendly HowTo for Python Re, than this? > > > > I'm new to programming an regexp, sorry for inconvenience. > > > I don't think you can do it in one regex, nor would I want to. Just use > > the string's replace() method. > > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > ?>>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > ?>>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = mail.strip() > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = maail.replace(' ', '') > > ?>>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > ?>>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > > ?>>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > ?>>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > > ?>>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > Too bad, I thought that the almighty re module could do anything, but > it failed with this (or maybe re can do what i want, but only few > people knows how to force him to that? ?:P). > But with help of MRAB, i choose The 3rd Point of Python's Zen - > "Simple is better than complex." > > " > > >>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' > >>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > > >>> print mail > > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > >>> maail = mail.lstrip().rstrip().replace(' ', '').replace('[dot]', '.').replace('[$dot$]', '.').replace('[at]', '@').replace('[$at$]', '@') > >>> print maail > > n... at mail.com > na... at mail.com > na... at mail.com > > >>> #Did it ?:) > > " > > Thanks again ? :) Short of writing a dedicated function I might be tempted to write this as: EMAIL_REPLACEMENTS = ( ('[at]', '@'), ('[dot]', '.'), ... ) for src, dest in EMAIL_REPLACEMENTS: mail = mail.replace(src, dest) Apart from taste reasons, it keeps the replaces more obvious (and accessible via a variable rather than embedded in the code), enables swapping the order or adding/removing easier. Jon From cournape at gmail.com Wed Aug 5 08:08:18 2009 From: cournape at gmail.com (David Cournapeau) Date: Wed, 5 Aug 2009 21:08:18 +0900 Subject: Using Python to automate builds In-Reply-To: <200908050956.33995.hendrik@microcorp.co.za> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <200908050956.33995.hendrik@microcorp.co.za> Message-ID: <5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> On Wed, Aug 5, 2009 at 4:56 PM, Hendrik van Rooyen wrote: > On Tuesday 04 August 2009 21:13:10 Kosta wrote: >> I am a Python newbie, tasked with automating (researching) building >> Windows drivers using the WDK build environment. ?I've been looking >> into Python for this (instead of writing a bunch of batch files). >> > Why do you not use make and a makefile - it was designed to > do exactly this. Because make is a pain on windows (lack of a proper shell) ? cheers, David From jfine at pytex.org Wed Aug 5 08:17:44 2009 From: jfine at pytex.org (Jonathan Fine) Date: Wed, 05 Aug 2009 13:17:44 +0100 Subject: Do anyone here use Python *embedded* in a database? Message-ID: Hi I'm writing a talk that compares embed and extend, and wondered if anyone here ever used the Python *embedded* in a database server. http://twistedmatrix.com/users/glyph/rant/extendit.html Web frameworks (such as Django) use extend, to import an extension module that makes a connection to a database. If you have used embed, you might have consulted a page such as: http://www.postgresql.org/docs/8.3/interactive/plpython-funcs.html -- Jonathan From ryniek90 at gmail.com Wed Aug 5 08:21:43 2009 From: ryniek90 at gmail.com (ryniek) Date: Wed, 5 Aug 2009 05:21:43 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> <4A78BC68.2020601@mrabarnett.plus.com> Message-ID: <0cde7cf6-0365-44da-b044-9066d522fa2d@w41g2000yqb.googlegroups.com> On 5 Sie, 13:28, Anthra Norell wrote: > MRAB wrote: > > ryniek90 wrote: > >> Hi. > >> I started learning regexp, and some things goes well, but most of > >> them still not. > > >> I've got problem with some regexp. Better post code here: > > >> " > >> ?>>> import re > >> ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > >> mail [$dot$] com\n' > >> ?>>> mail > >> '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail > >> [$dot$] com\n' > >> ?>>> print mail > > >> n... at mail.com > >> name1 [at] mail [dot] com > >> name2 [$at$] mail [$dot$] com > > >> ?>>> maail = re.sub('^\n|$\n', '', mail) > >> ?>>> print maail > >> n... at mail.com > >> name1 [at] mail [dot] com > >> name2 [$at$] mail [$dot$] com > >> ?>>> maail = re.sub(' ', '', maail) > >> ?>>> print maail > >> n... at mail.com > >> name1[at]mail[dot]com > >> name2[$at$]mail[$dot$]com > >> ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > >> ?>>> print maail > >> n... at mail.com > >> name1 at mail[dot]com > >> name2 at mail[$dot$]com > >> ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > >> ?>>> print maail > >> n... at mail.com > >> na... at mail.com > >> na... at mail.com > >> ?>>> #How must i write the replace string to replace all this > >> regexp's with just ONE command, in string 'mail' ? > >> ?>>> maail = re.sub('^\n|$\n| > >> |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', *?*, mail) > >> " > > >> How must i write that replace pattern (look at question mark), to > >> maek that substituion work? I didn't saw anything helpful while > >> reading Re doc and HowTo (from Python Doc). I tried with > >> 'MatchObject.group()' but something gone wrong - didn't wrote it right. > >> Is there more user friendly HowTo for Python Re, than this? > > >> I'm new to programming an regexp, sorry for inconvenience. > > > I don't think you can do it in one regex, nor would I want to. Just use > > the string's replace() method. > > > >>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > >>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > >>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > >>> maail = mail.strip() > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > >>> maail = maail.replace(' ', '') > > >>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > >>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > > >>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > >>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > > >>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > This is a good learning exercise demonstrating the impracticality of > regular expressions in a given situation. In the light of the > fascination regular expressions seem to exert in general, one might > conclude that knowing regular expressions in essence is knowing when not > to use them. > > There is nothing wrong with cascading substitutions through multiple > expressions. The OP's solution wrapped up in a function and streamlined > for needless regex overkill might look something like this: > > def translate (s): > ? ?s1 = s.strip () ? ? # Instead of: s1 = re.sub ('^\n|$\n', '', s) > ? ?s2 = s1.replace (' ', '') ? ?# Instead of: s2 = re.sub (' ', '', s1) > ? ?s3 = re.sub ('\[at\]|\[\$at\$\]', '@', s2) > ? ?s4 = re.sub ('\[dot\]|\[\$dot\$\]', '.', s3) > ? ?return s4 > > print translate (mail) ? # Tested > > MRAB's solution using replace () avoids needless regex complexity, but > doesn't simplify tedious coding if the number of substitutions is > significant. Some time ago I proposed a little module I made to > alleviate the tedium. It would handle this case like this: > > import SE > Translator = SE.SE ( ' (32)= [at]=@ [$at$]=@ [dot]=. [$dot$]=. ' ) > print Translator (mail.strip ()) ? # Tested > > So SE.SE compiles a string composed of any number of substitution > definitions into an object that translates anything given it. In a > running speed contest it would surely come in last, although in most > cases the disadvantage would be imperceptible. Another matter is coding > speed. Here the advantage is obvious, even with a set of substitutions > as small as this one, let alone with sets in the tens or even hundreds. > One inconspicuous but significant feature of SE is that it handles > precedence correctly if targets overlap (upstream over downstream and > long over short). As far as I know there's nothing in the Python system > handling substitution precedence. It always needs to be hand-coded from > one case to the next and that isn't exactly trivial. > > SE can be downloaded fromhttp://pypi.python.org/pypi/SE/2.3. > > Frederic Thanks again. :) I saw that MRAB is actively developing new implementation of re module. MRAB: You think it'd be good idea adding to Your project some best features of SE module? I didn't seen yet features of Your re module but will try to find time even today, to see what's going on. Greets From ryniek90 at gmail.com Wed Aug 5 08:21:56 2009 From: ryniek90 at gmail.com (ryniek) Date: Wed, 5 Aug 2009 05:21:56 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> <4A78BC68.2020601@mrabarnett.plus.com> Message-ID: On 5 Sie, 13:28, Anthra Norell wrote: > MRAB wrote: > > ryniek90 wrote: > >> Hi. > >> I started learning regexp, and some things goes well, but most of > >> them still not. > > >> I've got problem with some regexp. Better post code here: > > >> " > >> ?>>> import re > >> ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > >> mail [$dot$] com\n' > >> ?>>> mail > >> '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail > >> [$dot$] com\n' > >> ?>>> print mail > > >> n... at mail.com > >> name1 [at] mail [dot] com > >> name2 [$at$] mail [$dot$] com > > >> ?>>> maail = re.sub('^\n|$\n', '', mail) > >> ?>>> print maail > >> n... at mail.com > >> name1 [at] mail [dot] com > >> name2 [$at$] mail [$dot$] com > >> ?>>> maail = re.sub(' ', '', maail) > >> ?>>> print maail > >> n... at mail.com > >> name1[at]mail[dot]com > >> name2[$at$]mail[$dot$]com > >> ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > >> ?>>> print maail > >> n... at mail.com > >> name1 at mail[dot]com > >> name2 at mail[$dot$]com > >> ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > >> ?>>> print maail > >> n... at mail.com > >> na... at mail.com > >> na... at mail.com > >> ?>>> #How must i write the replace string to replace all this > >> regexp's with just ONE command, in string 'mail' ? > >> ?>>> maail = re.sub('^\n|$\n| > >> |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', *?*, mail) > >> " > > >> How must i write that replace pattern (look at question mark), to > >> maek that substituion work? I didn't saw anything helpful while > >> reading Re doc and HowTo (from Python Doc). I tried with > >> 'MatchObject.group()' but something gone wrong - didn't wrote it right. > >> Is there more user friendly HowTo for Python Re, than this? > > >> I'm new to programming an regexp, sorry for inconvenience. > > > I don't think you can do it in one regex, nor would I want to. Just use > > the string's replace() method. > > > >>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > >>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > >>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > >>> maail = mail.strip() > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > >>> maail = maail.replace(' ', '') > > >>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > >>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > > >>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > >>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > > >>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > This is a good learning exercise demonstrating the impracticality of > regular expressions in a given situation. In the light of the > fascination regular expressions seem to exert in general, one might > conclude that knowing regular expressions in essence is knowing when not > to use them. > > There is nothing wrong with cascading substitutions through multiple > expressions. The OP's solution wrapped up in a function and streamlined > for needless regex overkill might look something like this: > > def translate (s): > ? ?s1 = s.strip () ? ? # Instead of: s1 = re.sub ('^\n|$\n', '', s) > ? ?s2 = s1.replace (' ', '') ? ?# Instead of: s2 = re.sub (' ', '', s1) > ? ?s3 = re.sub ('\[at\]|\[\$at\$\]', '@', s2) > ? ?s4 = re.sub ('\[dot\]|\[\$dot\$\]', '.', s3) > ? ?return s4 > > print translate (mail) ? # Tested > > MRAB's solution using replace () avoids needless regex complexity, but > doesn't simplify tedious coding if the number of substitutions is > significant. Some time ago I proposed a little module I made to > alleviate the tedium. It would handle this case like this: > > import SE > Translator = SE.SE ( ' (32)= [at]=@ [$at$]=@ [dot]=. [$dot$]=. ' ) > print Translator (mail.strip ()) ? # Tested > > So SE.SE compiles a string composed of any number of substitution > definitions into an object that translates anything given it. In a > running speed contest it would surely come in last, although in most > cases the disadvantage would be imperceptible. Another matter is coding > speed. Here the advantage is obvious, even with a set of substitutions > as small as this one, let alone with sets in the tens or even hundreds. > One inconspicuous but significant feature of SE is that it handles > precedence correctly if targets overlap (upstream over downstream and > long over short). As far as I know there's nothing in the Python system > handling substitution precedence. It always needs to be hand-coded from > one case to the next and that isn't exactly trivial. > > SE can be downloaded fromhttp://pypi.python.org/pypi/SE/2.3. > > Frederic Thanks again. :) I saw that MRAB is actively developing new implementation of re module. MRAB: You think it'd be good idea adding to Your project some best features of SE module? I didn't seen yet features of Your re module but will try to find time even today, to see what's going on. Greets From piet at cs.uu.nl Wed Aug 5 08:28:15 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 14:28:15 +0200 Subject: Special chars with HTMLParser References: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com> Message-ID: >>>>> Fafounet (F) wrote: >F> Hello, >F> I am parsing a web page with special chars such as é (which >F> stands for ?). >F> I know I can have the unicode character ? from unicode >F> ("\xe9","iso-8859-1") >F> but with those extra characters I don' t know. >F> I tried to implement handle_charref within HTMLParser without success. >F> Furthermore, if I have the data abécd, handle_data will get "ab", >F> handle_charref will get xe9 and then handle_data doesn't have the end >F> of the string ("cd"). The character references indicate Unicode ordinals, not iso-8859-1 characters. In your example it will give the proper character because iso-8859-1 coincides with the first part of the Unicode ordinals, but for character outside of iso-8859-1 it will fail. This should give you an idea: from htmlentitydefs import name2codepoint ... def handle_charref(self, name): if name.startswith('x'): num = int(name[1:], 16) else: num = int(name, 10) print 'char:', repr(unichr(num)) def handle_entityref(self, name): print 'char:', unichr(name2codepoint[name]) If your HTML may be illegal you should add some exception handling. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From Tribulations at Paralleles.invalid Wed Aug 5 08:33:03 2009 From: Tribulations at Paralleles.invalid (TP) Date: Wed, 05 Aug 2009 14:33:03 +0200 Subject: intricated functions: how to share a variable References: <9a937d26-2375-4836-9824-d34d9f92d284@o15g2000yqm.googlegroups.com> Message-ID: Bearophile wrote: > So probably a better solution is to just use the normal function > semantics: you pass them an argument and you take an argument as > return value. Such return value will be the new version of the value > you talk about. Thanks for your answer. Yes, it is better like this. My problem is that I cannot get the return values of the function and affect it to some variable, because the function is called via a "signal-slot" connection of PyQt4, not by an explicit inline function call. For example: ######### def tutu(): def toto(): print a a = 4 print a a=2 # ... # definition of some graphical QPushButton "button" # ... # ... self.connect( button, SIGNAL( "clicked" ), toto ) tutu() ########## Then, as advised Diez, perhaps the best solution is to have "true" global variables by using a class and defining the variable a as a member self.a of the class. By doing like this, a will be known everywhere. Julien -- python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\ 9&1+,\'Z4(55l4('])" "When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong." (first law of AC Clarke) From piet at cs.uu.nl Wed Aug 5 08:34:31 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 14:34:31 +0200 Subject: trouble with complex numbers References: <24821423.post@talk.nabble.com> Message-ID: >>>>> Christian Heimes (CH) wrote: >CH> You can write your own phase() function. This function is mostly correct >CH> unless either the real and/or the imag part is NaN or INF. >CH> from math import atan2 >CH> def phase(z): >CH> z += 1j # convert int, long, float to complex That should be z += 0j >CH> return atan2(z.imag, z.real) -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From kpalamartchouk at gmail.com Wed Aug 5 08:50:04 2009 From: kpalamartchouk at gmail.com (kpal) Date: Wed, 5 Aug 2009 05:50:04 -0700 (PDT) Subject: Datetime with float seconds Message-ID: Hello Everybody, The standard datetime has 1 microsecond granularity. My application needs finer time resolution, preferably float seconds. Is there an alternative to the out-of-the-box datetime? Timezone support is not essential. Thanks, From nick.m.daly at gmail.com Wed Aug 5 08:56:14 2009 From: nick.m.daly at gmail.com (Nick Daly) Date: Wed, 05 Aug 2009 07:56:14 -0500 Subject: The Perils of PyContract (and Generators) Message-ID: <4A79816E.5050106@gmail.com> On Wed, 5 Aug 2009 03:06 pm Nick Daly wrote: > The problem actually lies in the contract. Generally, the PyContract > shouldn't affect the return values or in any way modify the code, which > it doesn't, as long as the function returns a list values (the way the > code had in fact originally been written). However, the contract > mentioned above is actually quite wrong for a generator. Yes, because you are conflating the items yielded from the generator with the generator object returned from the generator function "find_files". You can't look inside the generator object without using up whichever items you look at. [...] > Correcting the above example involves doing nothing more than > simplifying the contract: > > post: > name in __return__ That can't be right, not unless PyContract is doing something I don't expect. I expect that would be equivalent of: 'fish' in which should fail: >>> __return__ = find_files('fish') # a generator object >>> 'fish' in __return__ False >>> >>> __return__ = find_files('fish') >>> __return__ = list(__return__) >>> 'fish' in __return__ False >>> __return__ ['one fish', 'two fish', 'red fish', 'blue fish'] Of course, I may be mistaking what PyContract is doing. ----- No, you're absolutely right, I realized the error in my email moments after sending it, I was just hoping no one was paying enough attention to notice. I'm essentially asking PyContract to operate outside of the generator (it needs to check the return value of a generator, without changing its internal state), which doesn't seem to have an easy solution unless generators have some fantastic reverse_states function that I haven't heard about. I suppose one could be built, saving off the values of all local variables for later restoration, but that would still be dependent on the state of the rest of the machine and could not guarantee giving the same answer twice in a row. So, the moral of the story seems to be that PyContract's post-return value checking doesn't mix with generators at all. Sort of sad, because they're two neat flavors that would go great together but are instead technically incompatible. A decent set of unit-tests would accomplish the same thing much less destructively anyway. Nick From fafounet at gmail.com Wed Aug 5 09:03:46 2009 From: fafounet at gmail.com (Fafounet) Date: Wed, 5 Aug 2009 06:03:46 -0700 (PDT) Subject: Special chars with HTMLParser References: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com> Message-ID: <69835fa3-c6a0-44d3-bba2-5e3117102590@k30g2000yqf.googlegroups.com> Thank you, now I can get the correct character. Now when I have the string abécd I can get ab then ? thanks to your function and then cd. But how is it possible to know that cd is still the same word ? Fabien > The character references indicate Unicode ordinals, not iso-8859-1 > characters. In your example it will give the proper character because > iso-8859-1 coincides with the first part of the Unicode ordinals, but > for character outside of iso-8859-1 it will fail. > > This should give you an idea: > > from htmlentitydefs import name2codepoint > ... > ? ? def handle_charref(self, name): > ? ? ? ? if name.startswith('x'): > ? ? ? ? ? ? num = int(name[1:], 16) > ? ? ? ? else: > ? ? ? ? ? ? num = int(name, 10) > ? ? ? ? print 'char:', repr(unichr(num)) > > ? ? def handle_entityref(self, name): > ? ? ? ? print 'char:', unichr(name2codepoint[name]) > > If your HTML may be illegal you should add some exception handling. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org From contact at xavierho.com Wed Aug 5 09:15:53 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 5 Aug 2009 23:15:53 +1000 Subject: Datetime with float seconds In-Reply-To: References: Message-ID: <2d56febf0908050615i1d8f5137v3295c1ab574067c5@mail.gmail.com> On Wed, Aug 5, 2009 at 10:50 PM, kpal wrote: > Hello Everybody, > > The standard datetime has 1 microsecond granularity. My application > needs finer time resolution, preferably float seconds. Is there an > alternative to the out-of-the-box datetime? Timezone support is not > essential. This is a little outdated, but: >>>from time import time Usually gets me things like #output Run time: 0.0279998779297 seconds. So... that might be what you want. - Xavier -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Wed Aug 5 09:35:19 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Aug 2009 06:35:19 -0700 (PDT) Subject: intricated functions: how to share a variable References: <9a937d26-2375-4836-9824-d34d9f92d284@o15g2000yqm.googlegroups.com> Message-ID: TP wrote: > Then, as advised Diez, perhaps the best solution is to have "true" global > variables by using a class and defining the variable a as a member self.a > of the class. By doing like this, a will be known everywhere. Or, as Bearophile suggested, you could use the standard way of passing arguments into a function: >>> def tutu(): ... a = 2 ... def toto(a=a): ... print 'toto', a ... a = 4 ... print 'toto', a ... print 'tutu', a ... toto() ... print 'tutu', a ... >>> tutu() tutu 2 toto 2 toto 4 tutu 2 You could also just do 'toto(a)', but as you're trying to create a closure here, binding the external scope 'a' to toto via the default argument will (probably) do what you need. From jnoller at gmail.com Wed Aug 5 09:40:57 2009 From: jnoller at gmail.com (Jesse Noller) Date: Wed, 5 Aug 2009 06:40:57 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> Message-ID: <74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> On Aug 5, 1:21?am, sturlamolden wrote: > On Aug 5, 4:37 am, erikcw wrote: > > > It's not always the same traceback, but they are always short like > > this. ?I'm running Python 2.6.2 on Ubuntu 9.04. > > > Any idea how I can debug this? > > In my experience,multiprocessingis fragile. Scripts tend fo fail for > no obvious reason, case processes to be orphaned and linger, system- > wide resource leaks, etc. For example,multiprocessinguses os._exit > to stop a spawned process, even though it inevitably results in > resource leaks on Linux (it should use sys.exit). Ga?l Varoquaux and I > noticed this when we implemented shared memory ndarrays for numpy; we > consistently got memory leaks with System V IPC for no obvious reason. > Even after Jesse Noller was informed of the problem (about half a year > ago), the bug still lingers. It is easy editmultiprocessing's > forking.py file on you own, but bugs like this is a pain in the ass, > and I suspectmultiprocessinghas many of them. Of course unless you > show us you whole script, identifying the source of your bug will be > impossible. But it may very likely be inmultiprocessingas well. The > quality of this module is not impressing. I am beginning to think thatmultiprocessingshould never have made it into the Python standard > library. The GIL cannot be that bad! If you can't stand the GIL, get a > Unix (or Mac, Linux, Cygwin) and use os.fork. Or simply switch to a > non-GIL Python: IronPython or Jython. > > Allow me to show you something better. With os.fork we can write code > like this: > > class parallel(object): > > ? ?def __enter__(self): > ? ? ? ?# call os.fork > > ? ?def __exit__(self, exc_type, exc_value, traceback): > ? ? ? ?# call sys.exit in the child processes and > ? ? ? ?# os.waitpid in the parent > > ? ?def __call__(self, iterable): > ? ? ? ?# return different sub-subsequences depending on > ? ? ? ?# child or parent status > > with parallel() as p: > ? ? # parallel block starts here > > ? ? for item in p(iterable): > ? ? ? ? # whatever > > ? ? # parallel block ends here > > This makes parallel code a lot cleaner than anything you can do withmultiprocessing, allowing you to use constructs similar to OpenMP. > Further, if you make 'parallel' a dummy context manager, you can > develop and test the algorithms serially. The only drawback is that > you have to use Cygwin to get os.fork on Windows, and forking will be > less efficient (no copy-on-write optimization). Well, this is just one > example of why Windows sucks from the perspective of the programmer. > But it also shows that you can do much better by notusingmultiprocessingat all. > > The only case I can think of wheremultiprocessingwould be usesful, > is I/O bound code on Windows. But here you will almost always resort > to C extension modules. For I/O bound code, Python tends to give you a > 200x speed penalty over C. If you are resorting to C anyway, you can > just use OpenMP in C for your parallel processing. We can thus forget > aboutmultiprocessinghere as well, given that we have access to the C > code. If we don't, it is still very likely that the C code releases > the GIL, and we can get away withusingPython threads instead ofmultiprocessing. > > IMHO, if you areusingmultiprocessing, you are very likely to have a > design problem. > > Regards, > Sturla Sturla; That bug was fixed unless I'm missing something. Also, patches and continued bug reports are welcome. jesse From wuwei23 at gmail.com Wed Aug 5 09:41:56 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Aug 2009 06:41:56 -0700 (PDT) Subject: trouble with complex numbers References: <24821423.post@talk.nabble.com> Message-ID: Piet van Oostrum wrote: > That should be z += 0j Pardon my ignorance, but could anyone explain the rationale behind using 'j' to indicate the imaginary number (as opposed to the more intuitive 'i')? (Not that I've had much call to use complex numbers but I'm curious....) From jjposner at optimum.net Wed Aug 5 09:46:16 2009 From: jjposner at optimum.net (John Posner) Date: Wed, 05 Aug 2009 09:46:16 -0400 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: <4A798D28.5060004@optimum.net> >> OK, then why the statements "from turtle import *" in the modules >> turtleprocess.py and turtlewidget.py? >> Yes, I see that now (he said meekly, too sheepish to complain about being misled by an unfortunate naming choice). Tx, John From casevh at gmail.com Wed Aug 5 09:50:17 2009 From: casevh at gmail.com (casevh) Date: Wed, 5 Aug 2009 06:50:17 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: <5a4ab236-4cbf-4895-935a-5fdc712f0d08@u38g2000pro.googlegroups.com> On Aug 5, 12:19?am, Steven D'Aprano wrote: > On Wed, 5 Aug 2009 03:49 pm Mensanator wrote: > > > In 3.1, tracing is now a screen attribute, not a turtle atribute. > > I have no idea why > > > ? tooter = turtle.Turtle() > > ? tooter.tracer(False) > > > doesn't give me an error (I thought silent errors were a bad thing). > > What makes it an error? Do you consider the following an error? > > >>> class Test: > > ... ? ? pass > ... > > >>> t = Test() > >>> t.tracer = 5 > > Perhaps you mean, it's an API change you didn't know about, and you wish to > protest that Turtle Graphics made an incompatible API change without > telling you? > > > Naturally, having tracing on caused my program to crash. > > It seg faulted or raised an exception? > > [...] > > > Unfortunately, that calculation of nhops is illegal if diffsq is > > an .mpf (gmpy floating point). Otherwise, you get > > How does diffsq get to be a mpf? Are gmpy floats supposed to be supported? > > -- > Steven The root cause of the error is that GMP, the underlying library for gmpy, provides only the basic floating point operations. gmpy implements a very limited exponentiation function. Python's math library will convert an mpf to a float automatically so I think the revised calculation for nhops should work with either any numerical type that supports __float__. casevh From hendrik at microcorp.co.za Wed Aug 5 10:29:39 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 5 Aug 2009 16:29:39 +0200 Subject: Using Python to automate builds In-Reply-To: <5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <200908050956.33995.hendrik@microcorp.co.za> <5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> Message-ID: <200908051629.39417.hendrik@microcorp.co.za> On Wednesday 05 August 2009 14:08:18 David Cournapeau wrote: > On Wed, Aug 5, 2009 at 4:56 PM, Hendrik van > > Rooyen wrote: > > On Tuesday 04 August 2009 21:13:10 Kosta wrote: > >> I am a Python newbie, tasked with automating (researching) building > >> Windows drivers using the WDK build environment. ?I've been looking > >> into Python for this (instead of writing a bunch of batch files). > > > > Why do you not use make and a makefile - it was designed to > > do exactly this. > > Because make is a pain on windows (lack of a proper shell) ? Well, you could always use Dosbox - I am doing exactly that on Linux to be able to run some old DOS based assembler tools. It will run on windows too, they claim. And it is very simple to use too - no fancy fidgeting, all you have to do is to point it at a directory that becomes your "C" drive. Bit slow - but hey, nobody's perfect. - Hendrik From contact at xavierho.com Wed Aug 5 10:32:15 2009 From: contact at xavierho.com (Xavier Ho) Date: Thu, 6 Aug 2009 00:32:15 +1000 Subject: Subclassing Python's dict In-Reply-To: References: Message-ID: <2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com> On Thu, Aug 6, 2009 at 11:51 AM, Sergey Simonenko wrote: > I subclass builtin 'dict' in my application and experience some problems > with it. > You should subclass collections.UserDict, and not the default dict class. Refer to the collections module. Also, the ABC MutableMapping might be of your interest. > Another guy have reported me that he experiences similar problems with > subclassing builtin 'list'. Similarly, UserList is what you should subclass. HTH, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From joncle at googlemail.com Wed Aug 5 10:32:37 2009 From: joncle at googlemail.com (Jon Clements) Date: Wed, 5 Aug 2009 07:32:37 -0700 (PDT) Subject: Do anyone here use Python *embedded* in a database? References: Message-ID: <767b6862-065f-480a-82f5-ed3aa35bf84d@n11g2000yqb.googlegroups.com> On 5 Aug, 13:17, Jonathan Fine wrote: > Hi > > I'm writing a talk that compares embed and extend, and wondered if > anyone here ever used the Python *embedded* in a database server. > ? ? ?http://twistedmatrix.com/users/glyph/rant/extendit.html > > Web frameworks (such as Django) use extend, to import an extension > module that makes a connection to a database. > > If you have used embed, you might have consulted a page such as: > ? ? ?http://www.postgresql.org/docs/8.3/interactive/plpython-funcs.html > > -- > Jonathan Yup, have used plpythonu within postgres without too many problems. Although I do recall once that using the CSV module to load and filter external data, did consume a massive amount of memory. Even though the entire procedure was iterator based -- never did work out if it was postgres caching, or some other weird stuff. [That was about 2 years ago though] Jon. From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 5 10:39:52 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 05 Aug 2009 16:39:52 +0200 Subject: Subclassing Python's dict In-Reply-To: References: Message-ID: <4a7999b1$0$306$426a74cc@news.free.fr> Sergey Simonenko a ?crit : > Hi, > > I subclass builtin 'dict' in my application and experience some problems > with it. > > The whole issue is that I should redefine 'setdefault' and 'update' > methods after redefining '__setitem__' or/and '__delitem__', > otherwise 'update' and 'setdefault' ignore redefined '__setitem__' and > use builtin dict's one so dict looks kinda like a black box. > > Another guy have reported me that he experiences similar problems with > subclassing builtin 'list'. I indeed notice this behaviour here (Python 2.6.2). I'm afraid it has to do with some optimization tricks (dict being the very fundamental data structure in Python, it has to be higly optimized). From af1ing at seznam.cz Wed Aug 5 10:41:05 2009 From: af1ing at seznam.cz (Rog) Date: Wed, 5 Aug 2009 07:41:05 -0700 (PDT) Subject: http access produces 503 Message-ID: <3b5ab07c-7b0b-4d23-965b-192dc86cf6ff@a26g2000yqn.googlegroups.com> I am porting a simple code from Perl, the website asks for usr/pwd and the server's side Perl script makes atemp ftp dir for file upload. The original Perl script connects okay, does its job. The same URL stuffed into FF3 performs the same way. My Python script I am sweating out for past four days (noob!) gets consistently "503", even with user agen set to: Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11. Snippets of relevant code below. Please, help me understand how this same code lets me log in into my router usr/pwd running .asp, but this !@#$% perl script returns to me w/503 c*ap? Thank you. Do I need to set any proxy? The server is on intranet and the FF3 is set to proxy. The original Perl script did not use any proxy setting.


url = http://example.com/ftpsetup.pl?username=boofa&nodeid=42
#########################################################
# create a password manager
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
    password_mgr.add_password(None, url, uid, pcode)
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
    class Mopener(URLopener): version = "Mozilla/5.0 (Windows; U;
Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

    opener = Mopener()

# create "opener" (OpenerDirector instance)

    opener = urllib2.build_opener(handler)
    opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U;
Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11')]

    opener.version = "Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:
1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

    print opener.version
# timeout in seconds
    timeout = 10
    socket.setdefaulttimeout(timeout)

# Install the opener all calls to urllib2.urlopen use our opener.
    urllib2.install_opener(opener)

    try:
        response = opener.open(url)
        # "http://www.useragent.org/" tested okay!!!
        print"ok = 1"
    except:
        print "error 1"
#####################################################################################

output from the above:

Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/
20071127 Firefox/2.0.0.11
error 1
Error code:  503
('Service Unavailable', 'The server cannot process the request due to
a high load')
From michael at stroeder.com Wed Aug 5 10:43:09 2009 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 05 Aug 2009 16:43:09 +0200 Subject: unicode() vs. s.decode() Message-ID: HI! These both expressions are equivalent but which is faster or should be used for any reason? u = unicode(s,'utf-8') u = s.decode('utf-8') # looks nicer Ciao, Michael. From martin.hellwig at dcuktec.org Wed Aug 5 10:46:13 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 Aug 2009 15:46:13 +0100 Subject: Parsing Binary Structures; Is there a better way / What is your way? Message-ID: Hi List, On several occasions I have needed (and build) a parser that reads a binary piece of data with custom structure. For example (bogus one): BE +---------+---------+-------------+-------------+------+--------+ | Version | Command | Instruction | Data Length | Data | Filler | +---------+---------+-------------+-------------+------+--------+ Version: 6 bits Command: 4 bits Instruction: 5 bits Data Length: 5 bits Data: 0-31 bits Filler: filling 0 bits to make the packet dividable by 8 what I usually do is read the packet in binary mode, convert the output to a concatenated 'binary string'(i.e. '0101011000110') and then use slice indeces to get the right data portions. Depending on what I need to do with these portions I convert them to whatever is handy (usually an integer). This works out fine for me. Most of the time I also put the ASCII art diagram of this 'protocol' as a comment in the code, making it more readable/understandable. Though there are a couple of things that bothers me with my approach: - This seems such a general problem that I think that there must be already a general pythonic solution. - Using a string for binary representation takes at least 8 times more memory for the packet than strictly necessary. - Seems to need a lot of prep work before doing the actual parsing. Any suggestion is greatly appreciated. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From dp_pearce at hotmail.com Wed Aug 5 10:51:44 2009 From: dp_pearce at hotmail.com (dp_pearce) Date: Wed, 5 Aug 2009 07:51:44 -0700 (PDT) Subject: Is it possible to produce spider plots? Message-ID: I want to be able to use Python to produce Spider plots (perhaps you know them as radar plots or star plots). Does anyone know how to achieve this? Are there existing libraries? Direction to any examples, especially those with tutorials, would be greatly appreciated. Cheers, Dan http://www.answers.com/topic/spider-plot From pruebauno at latinmail.com Wed Aug 5 10:56:35 2009 From: pruebauno at latinmail.com (nn) Date: Wed, 5 Aug 2009 07:56:35 -0700 (PDT) Subject: Overlap in python References: <4A78B19D.4020306@mrabarnett.plus.com> Message-ID: <4c9f81a5-51b9-4487-9df9-d458b327d286@s15g2000yqs.googlegroups.com> On Aug 5, 7:13?am, Marcus Wanner wrote: > On 8/4/2009 6:09 PM, MRAB wrote: > > > ?>>> parts = [(5, 9, "a"), (7, 10, "b"), (3, 6, "c"), (15, 20, "d"), > > (18, 23, "e")] > > ?>>> parts.sort() > > ?>>> parts > > [(3, 6, 'c'), (5, 9, 'a'), (7, 10, 'b'), (15, 20, 'd'), (18, 23, 'e')] > > ?>>> # Merge overlapping intervals. > > ?>>> pos = 1 > > ?>>> while pos < len(parts): > > ? ? ? ? # Merge the pair in parts[pos - 1 : pos + 1] if they overlap. > > ? ? ? ? p, q = parts[pos - 1 : pos + 1] > > ? ? ? ? if p[1] >= q[0]: > > ? ? ? ? ? ? ? ? parts[pos - 1 : pos + 1] = [(p[0], max(p[1], q[1]), p[2] > > + "." + q[2])] > > ? ? ? ? else: > > ? ? ? ? ? ? ? ? # They don't overlap, so try the next pair. > > ? ? ? ? ? ? ? ? pos += 1 > > > ?>>> parts > > [(3, 10, 'c.a.b'), (15, 23, 'd.e')] > > That's the best solution I've seen so far. It even has input/output > formatted as close as is reasonably possible to the format specified. > > As we would say in googlecode, +1. > > Marcus How does it compare to this one? http://groups.google.com/group/comp.lang.python/browse_frm/thread/1a1d2ed9d05d11d0/56684b795fc527cc#56684b795fc527cc From roger_lynx at yahoo.com Wed Aug 5 11:05:38 2009 From: roger_lynx at yahoo.com (roger_lynx) Date: Wed, 05 Aug 2009 15:05:38 -0000 Subject: web access yields "503" Message-ID: Hi, I am porting a simple code from Perl, the website asks for usr/pwd and the server's side Perl script makes a temp ftp dir for a file upload. The original Perl script connects okay, does its job. The same URL stuffed into FF3 performs the same way. My Python script I am sweating over for past four days (noob!) gets consistently "503", even with user agent set to: Mozilla/5.0 (Windows;U; Windows NT 5.1; it; rv:1.8.1.11)Gecko/20071127 Firefox/2.0.0.11. Snippets of relevant code below, heavily copied from this author: http://www.voidspace.org.uk/python/articles/urllib2.shtml Please, help me understand how this same code lets me log in into my router usr/pwd running .asp, but this !@#$% perl script returns to me w/503 c*ap? Thank you. Do I need to set any proxy? The server is on intranet and the FF3 is set to proxy. The original Perl script did not use any proxy setting! LWP::

url = http://bad_example.com/ftpsetup.pl?username=boofa&nodeid=42
#########################################################
# create a password manager
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
    password_mgr.add_password(None, url, uid, pcode)
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
    class Mopener(URLopener): version = "Mozilla/5.0 (Windows; U;
Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

    opener = Mopener()

# create "opener" (OpenerDirector instance)

    opener = urllib2.build_opener(handler)
    opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U;
Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11')]

    opener.version = "Mozilla/5.0 (Windows; U; 
Windows NT 5.1; it; rv:
1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

    print opener.version
# timeout in seconds
    timeout = 10
    socket.setdefaulttimeout(timeout)

# Install the opener all calls to urllib2.urlopen use our opener.
    urllib2.install_opener(opener)

    try:
        response = opener.open(url)
        # "http://www.useragent.org/" tested okay!!!
        print"ok = 1"
    except:
        print "error 1"
#####################################################################################

output from the above:

Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/
20071127 Firefox/2.0.0.11
error 1
Error code: 503
('Service Unavailable', 'The server cannot process the request due to
a high load')
From Scott.Daniels at Acm.Org Wed Aug 5 11:12:48 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 05 Aug 2009 08:12:48 -0700 Subject: Overlap in python In-Reply-To: References: Message-ID: Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 > > I've tried various methods, which all fail. Does anyone have an idea > how to do this? > > Thank you very much! > Jay I once had to do this for finding nested block structure. The key for me was a sort order: start, -final. Having not seen it here (though I looked a bit), here's one: class Entry(object): '''An entry is a name and range''' def __init__(self, line): self.name, startstop = line.split() start, stop = startstop.split('-') self.start, self.stop = int(start), int(stop) def combined_ranges(lines): '''Create Entries in "magic order", and produce ranges. The "magic order" makes least element with longest range first, so overlaps show up in head order, with final tail first among equals. ''' # Fill in our table (ignoring blank lines), then sort by magic order elements = [Entry(line) for line in lines if line.strip()] elements.sort(key=lambda e: (e.start, -e.stop)) # Now produce resolved ranges. Grab the start gen = iter(elements) first = gen.next() # For the remainder, combine or produce for v in gen: if v.start <= first.stop: # on overlap, merge in new element (may update stop) first.name += '.' + v.name if first.stop < v.stop: first.stop = v.stop else: yield first first = v # And now produce the last element we covered yield first # Demo: sample = '''part name location a 5-9 b 7-10 c 3-6 d 15-20 e 18-23 ''' source = iter(sample.split('\n')) # source of lines, opened file? ignored = source.next() # discard heading for interval in combined_range(source): print '%s %s-%s' % (interval.name, interval.start, interval.stop) Prints: c.a.b 3-10 d.e 15-23 --Scott David Daniels Scott.Daniels at Acm.Org From wuwei23 at gmail.com Wed Aug 5 11:17:34 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Aug 2009 08:17:34 -0700 (PDT) Subject: trouble with complex numbers References: <24821423.post@talk.nabble.com> Message-ID: <37b97967-ec2e-4c37-a4b9-46e56a6de7bd@p36g2000prn.googlegroups.com> On Aug 6, 1:18?am, Scott David Daniels wrote: > I think it explained in the complex math area, but basically EE types > use j, math types use i for exactly the same thing. ?Since i is so > frequently and index in CS, and there is another strong convention, > why not let the EE types win? That 'i' tends to be used as index did occur to me, I just wasn't aware of what conventions were used in other contexts. Thanks, Scott, much appreciated. From rustompmody at gmail.com Wed Aug 5 11:18:05 2009 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 5 Aug 2009 20:48:05 +0530 Subject: error return from urlopen Message-ID: When I direct urlopen to a non-existent server process I get IOError: [Errno socket error] (10061, 'Connection refused') The connection refused is as expected but whats the 10061? strerror(10061) says 'unknown error' So its like an errno but not quite an errno? Can I find out more about this number like I can about errno? From Scott.Daniels at Acm.Org Wed Aug 5 11:18:55 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 05 Aug 2009 08:18:55 -0700 Subject: trouble with complex numbers In-Reply-To: References: <24821423.post@talk.nabble.com> Message-ID: alex23 wrote: > Piet van Oostrum wrote: >> That should be z += 0j > > Pardon my ignorance, but could anyone explain the rationale behind > using 'j' to indicate the imaginary number (as opposed to the more > intuitive 'i')? > > (Not that I've had much call to use complex numbers but I'm > curious....) I think it explained in the complex math area, but basically EE types use j, math types use i for exactly the same thing. Since i is so frequently and index in CS, and there is another strong convention, why not let the EE types win? --Scott David Daniels Scott.Daniels at Acm.Org From robin at reportlab.com Wed Aug 5 11:18:55 2009 From: robin at reportlab.com (Robin Becker) Date: Wed, 05 Aug 2009 16:18:55 +0100 Subject: Is it possible to produce spider plots? In-Reply-To: References: Message-ID: <4A79A2DF.5010908@chamonix.reportlab.co.uk> dp_pearce wrote: > I want to be able to use Python to produce Spider plots (perhaps you > know them as radar plots or star plots). Does anyone know how to > achieve this? Are there existing libraries? > > Direction to any examples, especially those with tutorials, would be > greatly appreciated. > > Cheers, ...... reportlab has a spider chart in reportlab/graphics/charts/spider.py -- Robin Becker From marduk at letterboxes.org Wed Aug 5 11:28:22 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Wed, 05 Aug 2009 11:28:22 -0400 Subject: error return from urlopen In-Reply-To: References: Message-ID: <1249486102.23428.3.camel@brotherus.corp.redhat.com> On Wed, 2009-08-05 at 20:48 +0530, Rustom Mody wrote: > When I direct urlopen to a non-existent server process I get > > IOError: [Errno socket error] (10061, 'Connection refused') > The connection refused is as expected but whats the 10061? > strerror(10061) says 'unknown error' > > So its like an errno but not quite an errno? > Can I find out more about this number like I can about errno? http://msdn.microsoft.com/en-us/library/ms740668(VS.85).aspx From tim.arnold at sas.com Wed Aug 5 11:30:07 2009 From: tim.arnold at sas.com (Tim Arnold) Date: Wed, 5 Aug 2009 11:30:07 -0400 Subject: oNVDL validation docbook 5 Message-ID: Hi, I'm using the oNVDL java validator for my DocBook 5.0 documents. Otherwise, my doc system is python. I wonder if there is any work going on (or perhaps something I'm missing) to use python to validate DocBook 5 (using the rng files bundled with the DocBook5 distribution) I think the catch with DocBook 5 rng is that it has embedded Schematron rules, which makes lxml not able to validate. I'm out of my depth here, but that's what I've heard. Anyway, I'd sure like to streamline this using python rather than a subprocess call out to that java validator. Any suggestions or pointers welcome. thanks, --Tim Arnold From jkn_gg at nicorp.f9.co.uk Wed Aug 5 11:33:48 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Wed, 5 Aug 2009 08:33:48 -0700 (PDT) Subject: Is it possible to produce spider plots? References: Message-ID: On Aug 5, 3:51?pm, dp_pearce wrote: > I want to be able to use Python to produce Spider plots (perhaps you > know them as radar plots or star plots). Does anyone know how to > achieve this? Are there existing libraries? > The 'wxPython in Action' book has some simple example code which produces this sort of graphic. If you are after a GUI application rather than creating a paper copy it might be worth checking this out. HTH J^n From tack at urandom.ca Wed Aug 5 11:38:13 2009 From: tack at urandom.ca (Jason Tackaberry) Date: Wed, 05 Aug 2009 11:38:13 -0400 Subject: intricated functions: how to share a variable In-Reply-To: <7dt5rqF2crv46U1@mid.uni-berlin.de> References: <7dt5rqF2crv46U1@mid.uni-berlin.de> Message-ID: <1249486693.7120.789.camel@arrakis> On Wed, 2009-08-05 at 12:39 +0200, Diez B. Roggisch wrote: > Another often used trick is to have a mutable container-object, like this: > > def tutu(): > a = [2] > > def toto(): > a[0] = 4 > > toto() When you need a writable bound variable inside a closure, I prefer this idiom: def foo(): def bar(): print bar.a bar.a = 4 print bar.a bar.a = 2 bar() Python 3's nonlocal is obviously much more elegant. Cheers, Jason. From joncle at googlemail.com Wed Aug 5 11:39:07 2009 From: joncle at googlemail.com (Jon Clements) Date: Wed, 5 Aug 2009 08:39:07 -0700 (PDT) Subject: Parsing Binary Structures; Is there a better way / What is your way? References: Message-ID: <9bca27b8-e71d-4b71-a792-d9ca7be18ab3@24g2000yqm.googlegroups.com> On 5 Aug, 15:46, "Martin P. Hellwig" wrote: > Hi List, > > On several occasions I have needed (and build) a parser that reads a > binary piece of data with custom structure. For example (bogus one): > > BE > +---------+---------+-------------+-------------+------+--------+ > | Version | Command | Instruction | Data Length | Data | Filler | > +---------+---------+-------------+-------------+------+--------+ > Version: 6 bits > Command: 4 bits > Instruction: 5 bits > Data Length: 5 bits > Data: 0-31 bits > Filler: filling 0 bits to make the packet dividable by 8 > > what I usually do is read the packet in binary mode, convert the output > to a concatenated 'binary string'(i.e. '0101011000110') and then use > slice indeces to get the right data portions. > Depending on what I need to do with these portions I convert them to > whatever is handy (usually an integer). > > This works out fine for me. Most of the time I also put the ASCII art > diagram of this 'protocol' as a comment in the code, making it more > readable/understandable. > > Though there are a couple of things that bothers me with my approach: > - This seems such a general problem that I think that there must be > already a general pythonic solution. > - Using a string for binary representation takes at least 8 times more > memory for the packet than strictly necessary. > - Seems to need a lot of prep work before doing the actual parsing. > > Any suggestion is greatly appreciated. > > -- > MPHhttp://blog.dcuktec.com > 'If consumed, best digested with added seasoning to own preference.' IIRC (and I have my doubts) the BitVector module may be of use, but it's been about 3 years since I had to look at it. I think it used the C equiv. of short ints to do its work. Otherwise, maybe the array module, the struct module or even possibly ctypes. Not much use, but might give a few pointers. Jon. From kosta.koeman at gmail.com Wed Aug 5 11:39:15 2009 From: kosta.koeman at gmail.com (Kosta) Date: Wed, 5 Aug 2009 08:39:15 -0700 (PDT) Subject: Using Python to automate builds References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <200908050956.33995.hendrik@microcorp.co.za> <5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> Message-ID: On Aug 5, 7:29?am, Hendrik van Rooyen wrote: > On Wednesday 05 August 2009 14:08:18 David Cournapeau wrote: > > > On Wed, Aug 5, 2009 at 4:56 PM, Hendrik van > > > Rooyen wrote: > > > On Tuesday 04 August 2009 21:13:10 Kosta wrote: > > >> I am a Python newbie, tasked with automating (researching) building > > >> Windows drivers using the WDK build environment. ?I've been looking > > >> into Python for this (instead of writing a bunch of batch files). > > > > Why do you not use make and a makefile - it was designed to > > > do exactly this. > > > Because make is a pain on windows (lack of a proper shell) ? > > Well, you could always use Dosbox - I am doing exactly that > on Linux to be able to run some old DOS based assembler > tools. ?It will run on windows too, they claim. > > And it is very simple to use too - no fancy fidgeting, all you have > to do is to point it at a directory that becomes your "C" drive. > > Bit slow - but hey, nobody's perfect. > > - Hendrik Sorry for not being more clear. The WDK provides build.exe, a utility that calls the compiler & linker with the approprite switches. In essence, it manages all the nmake details away from the developer. For some, this is a bad thing in terms of loss of control. But in reality, this is a great thing, as this is the way Microsoft builds Windows. As far as I can tell, the WDK build environment is dervied from the Microsoft Windows build environment, which is great for developing kernel components in the similar enviornment in which Microsoft builds its OS. It is a requirement to use the WDK. Setenv.bat sets up the path and other environment variables build.exe needs to compile and link (and even binplace) its utilities. So building itself is not the issue. The problem is that if I call setenv.bat from Python and then build.exe, but the modifications to the path (and other environment settings) are not seen by Python, so the attempt to build without a specified path fails. Now I can open up a build window that targets a build type (check or release), an architecture target (x86 or x64) and an OS target (which will be Windows Xp except if in the future, the driver(s) uses some infrastructure introduced in later versions of WDM. However, what I was hoping to do was to have a python script that would allow me to build 4 versions of the driver: x86 check, x86 release, x64 check, and x64 release. I may have to resort to using batch files, but I was hoping as much as possible to use Python. Thanks, Kosta From breamoreboy at yahoo.co.uk Wed Aug 5 11:52:08 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 05 Aug 2009 16:52:08 +0100 Subject: Overlap in python In-Reply-To: References: <4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> Message-ID: Jay Bird wrote: > Hi everyone, > > I wanted to thank you all for your help and *excellent* discussion. I > was able to utilize and embed the script by Grigor Lingl in the 6th > post of this discussion to get my program to work very quickly (I had > to do about 20 comparisons per data bin, with over 40K bins in > total). I am involved in genomic analysis research and this problem > comes up a lot and I was surprised to not have been able to find a > clear way to solve it. I will also look through all the tips in this > thread, I have a feeling they may come in handy for future use! > > Thank you again, > Jay I don't know if this is relevant, but http://planet.python.org/ has an entry dated this morning which points here http://www.logarithmic.net/pfh/blog/01249470842. HTH. -- Kindest regards. Mark Lawrence. From tack at urandom.ca Wed Aug 5 11:53:56 2009 From: tack at urandom.ca (Jason Tackaberry) Date: Wed, 05 Aug 2009 11:53:56 -0400 Subject: unicode() vs. s.decode() In-Reply-To: References: Message-ID: <1249487636.7120.798.camel@arrakis> On Wed, 2009-08-05 at 16:43 +0200, Michael Str?der wrote: > These both expressions are equivalent but which is faster or should be used > for any reason? > > u = unicode(s,'utf-8') > > u = s.decode('utf-8') # looks nicer It is sometimes non-obvious which constructs are faster than others in Python. I also regularly have these questions, but it's pretty easy to run quick (albeit naive) benchmarks to see. The first thing to try is to have a look at the bytecode for each: >>> import dis >>> dis.dis(lambda s: s.decode('utf-8')) 1 0 LOAD_FAST 0 (s) 3 LOAD_ATTR 0 (decode) 6 LOAD_CONST 0 ('utf-8') 9 CALL_FUNCTION 1 12 RETURN_VALUE >>> dis.dis(lambda s: unicode(s, 'utf-8')) 1 0 LOAD_GLOBAL 0 (unicode) 3 LOAD_FAST 0 (s) 6 LOAD_CONST 0 ('utf-8') 9 CALL_FUNCTION 2 12 RETURN_VALUE The presence of LOAD_ATTR in the first form hints that this is probably going to be slower. Next, actually try it: >>> import timeit >>> timeit.timeit('"foobarbaz".decode("utf-8")') 1.698289155960083 >>> timeit.timeit('unicode("foobarbaz", "utf-8")') 0.53305888175964355 So indeed, uncode(s, 'utf-8') is faster by a fair margin. On the other hand, unless you need to do this in a tight loop several tens of thousands of times, I'd prefer the slower form s.decode('utf-8') because it's, as you pointed out, cleaner and more readable code. Cheers, Jason. From J.Fine at open.ac.uk Wed Aug 5 12:03:13 2009 From: J.Fine at open.ac.uk (Jonathan Fine) Date: Wed, 05 Aug 2009 17:03:13 +0100 Subject: Do anyone here use Python *embedded* in a database? In-Reply-To: <767b6862-065f-480a-82f5-ed3aa35bf84d@n11g2000yqb.googlegroups.com> References: <767b6862-065f-480a-82f5-ed3aa35bf84d@n11g2000yqb.googlegroups.com> Message-ID: Jon Clements wrote: > On 5 Aug, 13:17, Jonathan Fine wrote: >> Hi >> >> I'm writing a talk that compares embed and extend, and wondered if >> anyone here ever used the Python *embedded* in a database server. >> http://twistedmatrix.com/users/glyph/rant/extendit.html >> >> Web frameworks (such as Django) use extend, to import an extension >> module that makes a connection to a database. >> >> If you have used embed, you might have consulted a page such as: >> http://www.postgresql.org/docs/8.3/interactive/plpython-funcs.html >> >> -- >> Jonathan > > Yup, have used plpythonu within postgres without too many problems. > Although I do recall once that using the CSV module to load and filter > external data, did consume a massive amount of memory. Even though the > entire procedure was iterator based -- never did work out if it was > postgres caching, or some other weird stuff. [That was about 2 years > ago though] Thanks, Jon, for that. -- Jonathan From lawrencew00 at hotmail.com Wed Aug 5 12:07:39 2009 From: lawrencew00 at hotmail.com (Lawrence Wong) Date: Wed, 5 Aug 2009 16:07:39 +0000 Subject: os.system in a service Message-ID: Hi, I wrote a program which runs a .bat file using os.system like: 'os.system(pathToBatFile)' and everything was good. Then I decided to turn my program into a service as opposed to being run with the command prompt showing. When my program became a service, I noticed that the os.system command to run my .bat file was no longer working. By 'not working' I mean no exception is thrown, but it was as if the line with os.system(pathToBatFile) did not exist. I was wondering why this is and if there is a way to fix this or what an alternative to using os.system to run my .bat file was? LW . . . Lawrence _________________________________________________________________ Send and receive email from all of your webmail accounts. http://go.microsoft.com/?linkid=9671356 -------------- next part -------------- An HTML attachment was scrubbed... URL: From rays at blue-cove.com Wed Aug 5 12:21:35 2009 From: rays at blue-cove.com (RayS) Date: Wed, 05 Aug 2009 09:21:35 -0700 Subject: Cypress FX2 - py libusb code? In-Reply-To: <5.2.1.1.2.20090804224315.01c22b60@pop-server.san.rr.com> Message-ID: <5.2.1.1.2.20090805091843.01c76cc8@blue-cove.com> An HTML attachment was scrubbed... URL: -------------- next part -------------- """ To run the single C file USB bulk read program properly, you must provide a source of data to the CY7C68013 FIFO bus, like the Simple dual channel A/D system, otherwise the reading call will time out in one second, you will get a bunch of zeros, and the ninth status number will be something negative instead of 512. """ import sys import os import time import usb def PrintDevInfo(dev): """Print device information.""" print "Device:", dev.filename print " Device class:",dev.deviceClass print " Device sub class:",dev.deviceSubClass print " Device protocol:",dev.deviceProtocol print " Max packet size:",dev.maxPacketSize print " idVendor:",dev.idVendor print " idProduct:",dev.idProduct print " Device Version:",dev.deviceVersion print " Device SerialNumber:",dev.iSerialNumber for config in dev.configurations: print " Configuration:", config.value print " Total length:", config.totalLength print " selfPowered:", config.selfPowered print " remoteWakeup:", config.remoteWakeup print " maxPower:", config.maxPower for intf in config.interfaces: print " Interface:",intf[0].interfaceNumber for alt in intf: print " Alternate Setting:",alt.alternateSetting print " Interface class:",alt.interfaceClass print " Interface sub class:",alt.interfaceSubClass print " Interface protocol:",alt.interfaceProtocol for ep in alt.endpoints: print " Endpoint:",hex(ep.address) print " Type:",ep.type print " Max packet size:",ep.maxPacketSize print " Interval:",ep.interval firmware = [0x90, 0xE6, 0x0B, 0x74, 0x03, 0xF0, ##REVCTL = 0x03 0x90, 0xE6, 0x04, 0x74, 0x80, 0xF0, ##FIFORESET = 0x80 0x74, 0x08, 0xF0, ##FIFORESET = 0x08 0xE4, 0xF0, ##FIFORESET = 0x00 0x90, 0xE6, 0x01, 0x74, 0xCB, 0xF0, ##IFCONFIG = 0xCB 0x90, 0xE6, 0x1B, 0x74, 0x0D, 0xF0, ##EP8FIFOCFG = 0x0D #0x90, 0xE6, 0x09, 0x74, 0x10, 0xF0, ##FIFOPINPOLAR = 0x10 TRUST!!! 0x80, 0xFE] ##while (1) {} reset = 0x01 er = [] endpoint = 8 # find all of the USB busses busses = usb.busses() #print busses # Find one device rdev = None for bus in busses: for dev in bus.devices: if dev.idVendor == 0x04B4 and dev.idProduct == 0x8613: rdev = dev if rdev==None: print "Could not find a CY7C68013\ndev.idVendor == 0x04B4 and dev.idProduct == 0x8613" sys.exit() else: dev = rdev #PrintDevInfo(dev) endpoint=8 current_handle = dev.open() requestType = 0x40 request = 0xa0 #buffer = ''.zfill(4096) value=0 index=0 timeout=1000 er.append(('RESET', current_handle.controlMsg(requestType, request, reset, value, index, timeout) ))##RESET time.sleep(0.1) for i in range(len(firmware)): #er.append(('ctrlMsg', i, current_handle.controlMsg(0x40, 0xa0, firmware[i], value=i, index=0))) er.append(('ctrlMsg', i, len(current_handle.controlMsg(0x40, 0xa0, firmware[i], value=i, index=0)))) er.append(('UNRESET', current_handle.controlMsg(requestType, request, reset+1, value, index, timeout))) ##UNRESET time.sleep(0.1) # we know that there's one config, one interface, and one endpoint conf = dev.configurations[0] er.append(( "confs", len(dev.configurations))) er.append(conf.interfaces.count(0))#, conf.interfaces.index(1) iface = conf.interfaces[0][1] er.append( ("ifaces[0]", len(conf.interfaces[0]))) endpoint = iface.endpoints[1] er.append(( "endpoints", len(iface.endpoints))) er.append(( "iin", iface.interfaceNumber)) er.append( current_handle.setConfiguration(conf)) er.append( current_handle.claimInterface(iface)) er.append( current_handle.setAltInterface(iface)) try: er.append( current_handle.bulkRead(endpoint.address, 512, 1000)) except usb.USBError, e: print ' bulkRead error: ', e.args print ' return data:' for e in er: print ' ', e PrintDevInfo(dev) sys.exit() for i in range(512): print " %02x " % buffer[i], current_handle.releaseInterface(0) dev.close() print "\n status: ", er[-1] From breamoreboy at yahoo.co.uk Wed Aug 5 12:30:24 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 05 Aug 2009 17:30:24 +0100 Subject: Is it possible to produce spider plots? In-Reply-To: References: Message-ID: dp_pearce wrote: > I want to be able to use Python to produce Spider plots (perhaps you > know them as radar plots or star plots). Does anyone know how to > achieve this? Are there existing libraries? > > Direction to any examples, especially those with tutorials, would be > greatly appreciated. > > Cheers, > Dan > > http://www.answers.com/topic/spider-plot How about http://matplotlib.sourceforge.net/examples/api/radar_chart.html?highlight=spider -- Kindest regards. Mark Lawrence. From tim.arnold at sas.com Wed Aug 5 12:34:18 2009 From: tim.arnold at sas.com (Tim Arnold) Date: Wed, 5 Aug 2009 12:34:18 -0400 Subject: Using Python to automate builds References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> Message-ID: "Kosta" wrote in message news:84d9ae10-3aee-40a8-97ac-05799da0de64 at f18g2000prf.googlegroups.com... >I am a Python newbie, tasked with automating (researching) building > Windows drivers using the WDK build environment. I've been looking > into Python for this (instead of writing a bunch of batch files). > > What I would like to do, is to open a cmd window, and start a Python > script. This script would then (based upon input arguments), build > different flavors of the driver (fre, chk, x86, x64) and do some post > processing (create cat files, sign, etc.). > > I was hoping to take advantage as much as possible of exisiting > infrastructure from the WDK. I am able to call setenv.bat and provide > all the input parameters. One of the things setenv.bat does is change > the path environment variable. However, this is not captured by > Python. I could duplicate the functionality, but I'd rather not. Is > there a way to capture all enviroment variable changes being made by a > batch file from Python? > > Thanks! It sounds like you know what you're doing. I just wanted to point out that you can specify environment dictionaries in the subprocess.Popen module. You can set a different dictionary for each call you make to the system. Not sure if that helps, --Tim From martin.hellwig at dcuktec.org Wed Aug 5 13:05:08 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 Aug 2009 18:05:08 +0100 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: <9bca27b8-e71d-4b71-a792-d9ca7be18ab3@24g2000yqm.googlegroups.com> References: <9bca27b8-e71d-4b71-a792-d9ca7be18ab3@24g2000yqm.googlegroups.com> Message-ID: Jon Clements wrote: > IIRC (and I have my doubts) the BitVector module may be of use, but > it's been about 3 years since I had to look at it. I think it used the > C equiv. of short ints to do its work. Otherwise, maybe the array > module, the struct module or even possibly ctypes. > > Not much use, but might give a few pointers. > > Jon. I tried struct before (it seemed logical) but it didn't really do what I expected: >>> import struct >>> struct.unpack('?','x') (True,) I expected a list like (False, True, True, True, True, False, False, False). But it is (actually I hope) just an error of my side, so if somebody knows how to achieve what I want, with this module, please enlighten me :-) The array module doesn't seem to have an option for boolean values. BitVector does look very promising, but after peeking in the source it does more or less the same as what I do with converting back and forth of 'bitstrings'. I haven't thought about using ctypes for this, excellent suggestion! Thank you for your feedback. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From deets at nospam.web.de Wed Aug 5 13:16:54 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Aug 2009 19:16:54 +0200 Subject: access string data from within cython Message-ID: <7dtt46F2e5osvU1@mid.uni-berlin.de> Hi, I'm trying to wrap a C-API which has a call that takes a void* and a size_t as arguments. void foo(void *data, size_t length) The wrapper is supposed to be called with a python (byte)string instance, which might contain more than one '\0'-character. So how do I access the raw data of a string? I tried looking into the buffer-protocol, but to be honest - that's beyond me, I don't see where that is actually giving me access to the real data. Diez From bearophileHUGS at lycos.com Wed Aug 5 13:17:29 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Wed, 5 Aug 2009 10:17:29 -0700 (PDT) Subject: Parsing Binary Structures; Is there a better way / What is your way? References: Message-ID: <50e27473-926b-458a-84f2-927ad02a0ed8@c14g2000yqm.googlegroups.com> Martin P. Hellwig: > On several occasions I have needed (and build) a parser that reads a > binary piece of data with custom structure. For example (bogus one): > > BE > +---------+---------+-------------+-------------+------+--------+ > | Version | Command | Instruction | Data Length | Data | Filler | > +---------+---------+-------------+-------------+------+--------+ > Version: 6 bits > Command: 4 bits > Instruction: 5 bits > Data Length: 5 bits > Data: 0-31 bits > Filler: filling 0 bits to make the packet dividable by 8 Have you tried Hachoir? (I think its name may be changed to Fusil, I don't know). Bye, bearophile From masklinn at masklinn.net Wed Aug 5 13:22:42 2009 From: masklinn at masklinn.net (Masklinn) Date: Wed, 5 Aug 2009 19:22:42 +0200 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: References: Message-ID: <934952CA-AC59-415C-A5D8-AEF74A0033FD@masklinn.net> On 5 Aug 2009, at 16:46 , Martin P. Hellwig wrote: > Hi List, > > On several occasions I have needed (and build) a parser that reads a > binary piece of data with custom structure. For example (bogus one): > > BE > +---------+---------+-------------+-------------+------+--------+ > | Version | Command | Instruction | Data Length | Data | Filler | > +---------+---------+-------------+-------------+------+--------+ > Version: 6 bits > Command: 4 bits > Instruction: 5 bits > Data Length: 5 bits > Data: 0-31 bits > Filler: filling 0 bits to make the packet dividable by 8 > > what I usually do is read the packet in binary mode, convert the > output to a concatenated 'binary string'(i.e. '0101011000110') and > then use slice indeces to get the right data portions. > Depending on what I need to do with these portions I convert them to > whatever is handy (usually an integer). > > This works out fine for me. Most of the time I also put the ASCII > art diagram of this 'protocol' as a comment in the code, making it > more readable/understandable. > > Though there are a couple of things that bothers me with my approach: > - This seems such a general problem that I think that there must be > already a general pythonic solution. > - Using a string for binary representation takes at least 8 times > more memory for the packet than strictly necessary. > - Seems to need a lot of prep work before doing the actual parsing. > > Any suggestion is greatly appreciated. The gold standard for binary parsing (and serialization) is probably Erlang's bit syntax, but as far as Python goes you might be interested by Hachoir (http://hachoir.org/ but it seems down right now). It's not going to match your second point, but it can probably help with the rest (caveat: I haven't used hachoir personally). From masklinn at masklinn.net Wed Aug 5 13:26:53 2009 From: masklinn at masklinn.net (Masklinn) Date: Wed, 5 Aug 2009 19:26:53 +0200 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: <50e27473-926b-458a-84f2-927ad02a0ed8@c14g2000yqm.googlegroups.com> References: <50e27473-926b-458a-84f2-927ad02a0ed8@c14g2000yqm.googlegroups.com> Message-ID: <7120B941-0C12-47ED-9505-08914EBD9CFB@masklinn.net> On 5 Aug 2009, at 19:17 , Bearophile wrote: > Have you tried Hachoir? (I think its name may be changed to Fusil, I > don't know). Name hasn't been changed (I think fusil is a subproject, something like that) on the other hand the hachoir.org site is dead. But apparently Hachoir was moved to bitbucket (http://bitbucket.org/haypo/hachoir/wiki/Home ) just in time so? From mensanator at aol.com Wed Aug 5 13:33:07 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 5 Aug 2009 10:33:07 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> <4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> Message-ID: > It didn't form 2.5 to 2.6 (at least not intentionally). But with the > indroduction of the TurtleScreen class and the Screen class/object > (singleton) a few of the turtle methods were also implemented as screen > methods and as turtle methods declared deprecated (see docs of Python > 2.6). These deprecated turtle methods do not occur as turtle methods any > more in Python 3.x. More info. Yes, there is no tracer attribute...when the object is created. But watch this (Python 3.1): >>> import turtle >>> tooter = turtle.Turtle() >>> tooter.tracer Traceback (most recent call last): File "", line 1, in tooter.tracer AttributeError: 'Turtle' object has no attribute 'tracer' >>> tooter.hideturtle() >>> tooter.speed('fast') >>> turtle.update() >>> turtle.tracer Now, after setting hide, speed, update, a tracer exists. Is that supposed to happen? That explains why there was no error when I set the turtle attribute instead of the screen attribute. And, of course, setting the turtle attribute accomplishes nothing, as actual tracing is controlled by the screen attribute as you say. > > Among them is the tracer method, which in fact does not control single > turtle objects but all the turtles on a given screen. > > So there is an icompatibility beween 2.6 and 3.x > > But as far as I have understood, this doesn't concern the problem > reported by mensator. Only that the problem is hidden when tracing is off, as the nhops variable is never evaluated when trace is off. > > Regards, > Gregor From gregor.lingl at aon.at Wed Aug 5 13:56:50 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Wed, 05 Aug 2009 19:56:50 +0200 Subject: Turtle Graphics are incompatible with gmpy In-Reply-To: References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> <4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> Message-ID: <4A79C7E2.3000406@aon.at> Mensanator schrieb: >> It didn't form 2.5 to 2.6 (at least not intentionally). But with the >> indroduction of the TurtleScreen class and the Screen class/object >> (singleton) a few of the turtle methods were also implemented as screen >> methods and as turtle methods declared deprecated (see docs of Python >> 2.6). These deprecated turtle methods do not occur as turtle methods any >> more in Python 3.x. > > More info. > > Yes, there is no tracer attribute...when the object is created. > > But watch this (Python 3.1): > >>>> import turtle >>>> tooter = turtle.Turtle() >>>> tooter.tracer > Traceback (most recent call last): > File "", line 1, in > tooter.tracer > AttributeError: 'Turtle' object has no attribute 'tracer' >>>> tooter.hideturtle() >>>> tooter.speed('fast') >>>> turtle.update() >>>> turtle.tracer > > > Now, after setting hide, speed, update, a tracer exists. No, >>> import turtle >>> turtle.tracer >>> help(turtle.tracer) Help on function tracer in module turtle: tracer(n=None, delay=None) Turns turtle animation on/off and set delay for update drawings. Optional arguments: n -- nonnegative integer delay -- nonnegative integer If n is given, only each n-th regular screen update is really performed. (Can be used to accelerate the drawing of complex graphics.) Second arguments sets delay value.) Example: >>> tracer(8, 25) >>> dist = 2 >>> for i in range(200): fd(dist) rt(90) dist += 2 >>> The reason for this is, that the turtle module (the new one as well as the old one) has a vers special design: The methods of class Turtle are also available as functions (which are in fact methods calls of an anonymous turtle). The same holds for the methods of TurtleScreen. The intention behind this design is that you can use the module in an OOP way as well as with procedural programming (especially for beginners). When using objects I normally use from turtle import Turtle, Screen screen = Screen() # that creates singleton object, the screen the turtle acts on and I create as many turtles as I need from the Turtle class So turtle.tracer() doesn't make sense anymore > Is that supposed to happen? That explains why there was no error > when I set the turtle attribute instead of the screen attribute. You do not 'set the turtle attribute', you call the tracer function of the turtle module > And, of course, setting the turtle attribute accomplishes nothing, > as actual tracing is controlled by the screen attribute as you say. > >> Among them is the tracer method, which in fact does not control single >> turtle objects but all the turtles on a given screen. >> >> So there is an icompatibility beween 2.6 and 3.x >> >> But as far as I have understood, this doesn't concern the problem >> reported by mensator. > > Only that the problem is hidden when tracing is off, as the nhops > variable is never evaluated when trace is off. Nevertheless I'd like to see a working Python 2.5 version of your script. Regards, Gregor From http Wed Aug 5 14:12:05 2009 From: http (Paul Rubin) Date: 05 Aug 2009 11:12:05 -0700 Subject: Parsing Binary Structures; Is there a better way / What is your way? References: Message-ID: <7x3a86gmfe.fsf@ruckus.brouhaha.com> "Martin P. Hellwig" writes: > what I usually do is read the packet in binary mode, convert the > output to a concatenated 'binary string'(i.e. '0101011000110') and Something wrong with reading the data words as an integer and using old fashioned shifts and masks to get at the bit fields? From 1x7y2z9 at gmail.com Wed Aug 5 14:12:45 2009 From: 1x7y2z9 at gmail.com (1x7y2z9) Date: Wed, 5 Aug 2009 11:12:45 -0700 (PDT) Subject: unicode() vs. s.decode() References: Message-ID: unicode() has LOAD_GLOBAL which s.decode() does not. Is it generally the case that LOAD_ATTR is slower than LOAD_GLOBAL that lead to your intuition that the former would probably be slower? Or some other intuition? Of course, the results from timeit are a different thing - I ask about the intuition in the disassembler output. Thanks. > > The presence of LOAD_ATTR in the first form hints that this is probably > going to be slower. ? Next, actually try it: > From piet at cs.uu.nl Wed Aug 5 14:20:47 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 20:20:47 +0200 Subject: Special chars with HTMLParser References: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com> <69835fa3-c6a0-44d3-bba2-5e3117102590@k30g2000yqf.googlegroups.com> Message-ID: >>>>> Fafounet (F) wrote: >F> Thank you, now I can get the correct character. >F> Now when I have the string abécd I can get ab then ? thanks to >F> your function and then cd. But how is it possible to know that cd is >F> still the same word ? That depends on your definition of `word'. And that is language-dependent. What you normally do is collect the text in a (unicode) string variable. This happens in handle_data, handle_charref and handle_entityref. Then you check that the previously collected stuff was a word (e.g. consisting of Unicode letters), and that the new stuff also consists of letters. If your language has additional word constituents like - or ' you have to add this. You can do this with unicodedata.category or with a regular expression. If your locale is correct \w in a regular expression may be helpful. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From dp_pearce at hotmail.com Wed Aug 5 14:21:50 2009 From: dp_pearce at hotmail.com (Devon_Dan) Date: Wed, 5 Aug 2009 11:21:50 -0700 (PDT) Subject: Is it possible to produce spider plots? References: Message-ID: <2481d12e-6af9-4dbb-991d-fb636c3b6831@k6g2000yqn.googlegroups.com> > reportlab has a spider chart in reportlab/graphics/charts/spider.py > How about > http://matplotlib.sourceforge.net/examples/api/radar_chart.html?highl... Both exactly what I was after. Thanks very much. > The 'wxPython in Action' book has some simple example code which > produces this sort of graphic. If you are after a GUI application > rather than creating a paper copy it might be worth checking this out. Thanks for this one jkn. I actually have this book and went through it looking to see if it had an answer before posting. Completely missed it! Clearly I need to RTFM more closely next time. From philip at semanchuk.com Wed Aug 5 14:25:27 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 5 Aug 2009 14:25:27 -0400 Subject: access string data from within cython In-Reply-To: <7dtt46F2e5osvU1@mid.uni-berlin.de> References: <7dtt46F2e5osvU1@mid.uni-berlin.de> Message-ID: On Aug 5, 2009, at 1:16 PM, Diez B. Roggisch wrote: > Hi, > > I'm trying to wrap a C-API which has a call that takes a void* and a > size_t > as arguments. > > void foo(void *data, size_t length) > > > The wrapper is supposed to be called with a python (byte)string > instance, > which might contain more than one '\0'-character. > > So how do I access the raw data of a string? I tried looking into the > buffer-protocol, but to be honest - that's beyond me, I don't see > where > that is actually giving me access to the real data. Hi Diez, Would ctypes.create_string_buffer() work for you? bye P From jeremy.cowles at gmail.com Wed Aug 5 14:31:38 2009 From: jeremy.cowles at gmail.com (Jeremy Cowles) Date: Wed, 5 Aug 2009 11:31:38 -0700 Subject: Install setup tools for 2.6 Message-ID: <373cf0740908051131gacaf77apba48fa40e929f491@mail.gmail.com> Ok, I feel like this is a really stupid question, but how do you install setup tools for Python 2.6 under windows? The only format is .egg which requires setup tools to install, doesn't it? Thanks, Jeremy -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.hellwig at dcuktec.org Wed Aug 5 14:46:12 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 Aug 2009 19:46:12 +0100 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: <7x3a86gmfe.fsf@ruckus.brouhaha.com> References: <7x3a86gmfe.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Martin P. Hellwig" writes: >> what I usually do is read the packet in binary mode, convert the >> output to a concatenated 'binary string'(i.e. '0101011000110') and > > Something wrong with reading the data words as an integer and using > old fashioned shifts and masks to get at the bit fields? No not at all of course, I just found it more readable to slice it instead of shifting and masking; i.e. if the ASCII art schematics of the protocol are included as a comment it is almost an 1 to 1 implementation. Is there an advantage using shifts and masks over my kitchen type solution? -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From ihatespam at hotmail.com Wed Aug 5 14:47:58 2009 From: ihatespam at hotmail.com (Just Another Victim of the Ambient Morality) Date: Wed, 5 Aug 2009 14:47:58 -0400 Subject: Confessions of a Python fanboy References: <008e82e8$0$9756$c3e8da3@news.astraweb.com><4a72d7cf$0$25239$426a34cc@news.free.fr><008eef29$0$9756$c3e8da3@news.astraweb.com><4a77eb69$0$22600$426a74cc@news.free.fr> Message-ID: "Steven D'Aprano" wrote in message news:pan.2009.08.04.09.28.49 at REMOVE.THIS.cybersource.com.au... > On Tue, 04 Aug 2009 10:03:53 +0200, Bruno Desthuilliers wrote: > >>> Disadvantages: your code is filled with line noise. It's an arbitrary >>> choice between @@ meaning instance attribute and @@ meaning class >>> attribute -- there's no logical reason for choosing one over the other, >>> so you have to memorise which is which. It's easy to get it wrong. >> >> So far that's something I have no difficulty living with. > > I don't like arbitrary symbols. Most people don't -- that's why "line > noise" is unpopular. It's hard to read, hard to write, hard to maintain, > and hard to talk about. The more line-noise, the worse the language. It's not "line noise" if it conveys information... > Of course, *ultimately* every symbol is arbitrary. There's no reason why > "2" should mean the integer two, or "list" should mean a sequence type, > but some symbols have such a long history, or have some other connection > (say, with human languages), that the arbitrariness is lost. For > instance, "+" is the obvious, non-arbitrary choice for the addition > operator in any programming language using Latin symbols, and probably > any programming language on Earth. (Not the *only* choice, but the > obvious one.) > > I have a similar dislike for decorator syntax, because "@" ("at" in > English) has nothing to do with decorations. It's an arbitrary symbol. > One might argue that "$" would have been a more logical choice, because > we turn numerals into currency by decorating it with a $ sign. (At least > in the US, Canada, Australia, and a few other countries.) I use > decorators all the time, and they are a fantastic invention, but the > arbitrariness of the @ syntax is a negative. Oh well, one negative out of > a whole lot of positives isn't too bad. You can think of "@" as describing something being "at" the instance or the class. "$" is totally arbitrary to me 'cause I don't thnk of my code as currency... > At least I only have to deal with *one* such arbitrary symbol that needs > memorizing. There's no need to distinguish between @@function_decorator > and @class_decorator (or should it be the other way around?). Similarly, > Python's choice of syntax for attributes is consistent: object.attribute > works for everything, whether object is a class, an instance, a module, > and whether attribute is callable or not. You can even use it on ints, > provided you are clever about it: You can think of "@" as being at an instance or "@@" to be more emphatically (as the Japanese do in their language) integrated with a class, being available to all instances... or you can simply understand that instance vairables are more common than class variables so the shorter notation is used for the more common case... You want to talk about arbitrariness? Why is len() a function you pass objects into while objects can have methods that describe themselves to you? At least Ruby defines operators using the actual name of the operator instead of you having to remember an arbitrary magic incantation that corresponds to the operator... class Test attr_reader :data def initialize(data) @data = data end # This is the operator part... def + right Test.new @data + right.data end end >>>>> Somebody who knows more Ruby than me should try writing the Zen of >>>>> Ruby. Something like: >>>> (snip childish parody of Python Zen) >>>> >>>> Steven, is that any useful ? >>> >>> It made me feel good. >> >> Why ??? >> >> You don't like Ruby ? Fine, don't use it. Period. I can't see the point >> of all these pissing contests. > > Criticism of a language is a pissing contest? > > Yeah, okay, I was a tad dismissive. I un-apologetically jump to strong > impressions about languages based on minimal use -- but I'm also willing > to change my mind. Ruby certainly looks to me like it has some nice > features. Syntax that looks like Perl isn't one of them though. Yeah, that would be the "pissing contest" part. You could simply have gone to the Ruby newsgroup and posted some criticisms to see what was behind those decisions. However, that would have avoided the pissing contest and perhaps you wanted one... >>> Just because Smalltalk had a particular (mis?)feature >> >> You can drop the 'mis' part IMHO. The point of code blocks in Smalltalk >> is that once you have something as powerful as the message+code blocks >> combo, you just don't need any other 'special form' for control flow. > > Well, maybe, but remember, programming languages are only partly for > communication to the compiler. They also have the requirement to > communicate with human programmers as well, and that's even more > important, because > > (1) humans spent a lot more time working with code than compilers do; > > (2) human programmers charge much more money than compilers do; > > (3) and you can modify the compiler to suit human needs much more easily > than you can modify programmers to suit the compiler's needs. > > So I'd ask, does Smalltalk's message passing model match the way human > beings think? If not, then that's a good sign it might be a misfeature. I think this is overstated. Not all humans think in exactly the same way so it's very presumptuous. It also ignores our intellect. We can change the way we think and we can use this versatility to our advantage. We can increase our productivity in certain tasks by changing the way we think to some other paradigm that better serves a given purpose... >>> doesn't mean that >>> other languages should copy it. >> >> Nope. But OTHO, Python is famous for all the features it copied from >> other languages !-) > > Absolutely! There's nothing wrong with copying *good* features :) The trick, of course, is figuring out which features are good! From http Wed Aug 5 14:51:06 2009 From: http (Paul Rubin) Date: 05 Aug 2009 11:51:06 -0700 Subject: Parsing Binary Structures; Is there a better way / What is your way? References: <7x3a86gmfe.fsf@ruckus.brouhaha.com> Message-ID: <7xr5vqw0v9.fsf@ruckus.brouhaha.com> "Martin P. Hellwig" writes: > Is there an advantage using shifts and masks over my kitchen type solution? Weren't you complaining about the 8-to-1 expansion from turning each bit to an ascii char? From gdamjan at gmail.com Wed Aug 5 15:05:30 2009 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Wed, 05 Aug 2009 21:05:30 +0200 Subject: String to valid Python identifier Message-ID: Is there any easy function in the stdlib to convert any random string in a valid Python identifier .. possibly by replacing non-valid characters with _ ? Python 2.x only, so no need to do Unicode. -- ?????? ( http://softver.org.mk/damjan/ ) Religion ends and philosophy begins, just as alchemy ends and chemistry begins and astrology ends, and astronomy begins. From pdlemper at earthlink.net Wed Aug 5 15:18:26 2009 From: pdlemper at earthlink.net (pdlemper at earthlink.net) Date: Wed, 05 Aug 2009 14:18:26 -0500 Subject: trouble with complex numbers References: <24821423.post@talk.nabble.com> Message-ID: <7gmj75lbijq2k8d8lk6kff7itt76n8ij13@4ax.com> On Wed, 05 Aug 2009 08:18:55 -0700, Scott David Daniels wrote: >I think it explained in the complex math area, but basically EE types >use j, math types use i for exactly the same thing. Since i is so >frequently and index in CS, and there is another strong convention, >why not let the EE types win? > >--Scott David Daniels >Scott.Daniels at Acm.Org i represents current Dave WB3DWE From sturlamolden at yahoo.no Wed Aug 5 15:23:16 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 5 Aug 2009 12:23:16 -0700 (PDT) Subject: access string data from within cython References: <7dtt46F2e5osvU1@mid.uni-berlin.de> Message-ID: <88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com> On 5 Aug, 19:16, "Diez B. Roggisch" wrote: > void foo(void *data, size_t length) > > The wrapper is supposed to be called with a python (byte)string instance, > which might contain more than one '\0'-character. > > So how do I access the raw data of a string? cdef extern void foo(void *data, int length) cdef char *data cdef int length bytestring = ... #whatever rawdata = bytestring length = len(bytestring) foo(data, length) From joshua at joshuakugler.com Wed Aug 5 15:23:31 2009 From: joshua at joshuakugler.com (Joshua Kugler) Date: Wed, 05 Aug 2009 11:23:31 -0800 Subject: Subclassing Python's dict References: <2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com> Message-ID: Xavier Ho wrote: > On Thu, Aug 6, 2009 at 11:51 AM, Sergey Simonenko > wrote: > >> I subclass builtin 'dict' in my application and experience some problems >> with it. >> > > You should subclass collections.UserDict, and not the default dict class. > Refer to the collections module. Are you referring to Python 3.0? Python 2.6 does not have collections.UserDict j From sturlamolden at yahoo.no Wed Aug 5 15:25:42 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 5 Aug 2009 12:25:42 -0700 (PDT) Subject: access string data from within cython References: <7dtt46F2e5osvU1@mid.uni-berlin.de> <88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com> Message-ID: <99c677b4-75eb-4a33-a1be-eecbc61c14fc@k19g2000yqn.googlegroups.com> On 5 Aug, 21:23, sturlamolden wrote: > foo(data, length) Oops, that would be foo( data, length) From joshua at joshuakugler.com Wed Aug 5 15:26:48 2009 From: joshua at joshuakugler.com (Joshua Kugler) Date: Wed, 05 Aug 2009 11:26:48 -0800 Subject: Do anyone here use Python *embedded* in a database? References: Message-ID: Jonathan Fine wrote: > Hi > > I'm writing a talk that compares embed and extend, and wondered if > anyone here ever used the Python *embedded* in a database server. > http://twistedmatrix.com/users/glyph/rant/extendit.html > > Web frameworks (such as Django) use extend, to import an extension > module that makes a connection to a database. > > If you have used embed, you might have consulted a page such as: > http://www.postgresql.org/docs/8.3/interactive/plpython-funcs.html > Yes, I've used plpython. We had a web application that had account creation logic with salting, encryption, etc, on the passwords. We then wanted to use the same accounts to log in to a Drupal site. Instead of trying to replicate the logic in PHP, I just created a stored procedure with plpython, and we overrode the drupal login check to call something like "SELECT check_account(user, pass)" which would return 1 or 0 on success or failure, respectively. Worked great. j From mensanator at aol.com Wed Aug 5 15:31:05 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 5 Aug 2009 12:31:05 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: On Aug 5, 2:19?am, Steven D'Aprano wrote: > On Wed, 5 Aug 2009 03:49 pm Mensanator wrote: > > > In 3.1, tracing is now a screen attribute, not a turtle atribute. > > I have no idea why > > > ? tooter = turtle.Turtle() > > ? tooter.tracer(False) > > > doesn't give me an error (I thought silent errors were a bad thing). > > What makes it an error? Do you consider the following an error? > > >>> class Test: > > ... ? ? pass > ... > > >>> t = Test() > >>> t.tracer = 5 Come on, even _I_ know this: >>> class Test: pass >>> t = Test() >>> t.tracer Traceback (most recent call last): File "", line 1, in t.tracer AttributeError: 'Test' object has no attribute 'tracer' >>> t.tracer = False >>> t.tracer False > > Perhaps you mean, it's an API change you didn't know about, and you wish to > protest that Turtle Graphics made an incompatible API change without > telling you? What does this mean? >>> import turtle >>> tooter = turtle.Turtle() >>> tooter.tracer Traceback (most recent call last): File "", line 1, in tooter.tracer AttributeError: 'Turtle' object has no attribute 'tracer' >>> tooter.hideturtle() >>> tooter.speed('fast') >>> turtle.update() >>> turtle.tracer How did the tracer attribute appear out of thin air? And more importantly, why, if has been deprecated and dropped from 3.x? > > > Naturally, having tracing on caused my program to crash. > > It seg faulted or raised an exception? Why did you snip it? Should I not refer to this as a crash? Traceback (most recent call last): File "K:\user_python26\turtle\turtle_xy_Py3.py", line 95, in tooter.goto(the_coord) File "C:\Python31\lib\turtle.py", line 1771, in goto self._goto(Vec2D(*x)) File "C:\Python31\lib\turtle.py", line 3165, in _goto nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed)) ValueError: mpq.pow fractional exponent, inexact-root > > [...] > > > Unfortunately, that calculation of nhops is illegal if diffsq is > > an .mpf (gmpy floating point). Otherwise, you get > > How does diffsq get to be a mpf? No idea. I neglected to mention I'm using the new gmpy 1.10. Don't know if that has any bearing. > Are gmpy floats supposed to be supported? Apparently not, as gmpy has only limited exponential capability. Looks like I need to change turtle.py to use math.sqrt(diffsq) or float(diffsq)**0.5. Or not pass turtle.py any .mpz since it can't handle them. > > -- > Steven From sturlamolden at yahoo.no Wed Aug 5 15:36:11 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 5 Aug 2009 12:36:11 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> <74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> Message-ID: <6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> On 5 Aug, 15:40, Jesse Noller wrote: > Sturla; > > That bug was fixed unless I'm missing something. It is still in SVN. Change every call to os._exit to sys.exit please. :) http://svn.python.org/view/python/branches/release26-maint/Lib/multiprocessing/forking.py?revision=66717&view=markup http://svn.python.org/view/python/branches/release31-maint/Lib/multiprocessing/forking.py?revision=73579&view=markup From sturlamolden at yahoo.no Wed Aug 5 15:40:40 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 5 Aug 2009 12:40:40 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> <74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> <6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> Message-ID: On 5 Aug, 21:36, sturlamolden wrote: > http://svn.python.org/view/python/branches/release26-maint/Lib/multip... > > http://svn.python.org/view/python/branches/release31-maint/Lib/multip... http://svn.python.org/view/python/trunk/Lib/multiprocessing/forking.py?revision=65864&view=markup From martin.hellwig at dcuktec.org Wed Aug 5 15:41:26 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 Aug 2009 20:41:26 +0100 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: <7xr5vqw0v9.fsf@ruckus.brouhaha.com> References: <7x3a86gmfe.fsf@ruckus.brouhaha.com> <7xr5vqw0v9.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Martin P. Hellwig" writes: >> Is there an advantage using shifts and masks over my kitchen type solution? > > Weren't you complaining about the 8-to-1 expansion from turning each bit > to an ascii char? Yes you are (of course) right, my 'dream' solution would be something that accepts slice indeces on bit level. Your reasoning did reveal some flaws in my approach though ;-) -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From rylesny at gmail.com Wed Aug 5 15:48:24 2009 From: rylesny at gmail.com (ryles) Date: Wed, 5 Aug 2009 12:48:24 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: Message-ID: On Aug 4, 10:37?pm, erikcw wrote: > Traceback (most recent call last): > ? File "scraper.py", line 144, in > ? ? print pool.map(scrape, range(10)) > ? File "/usr/lib/python2.6/multiprocessing/pool.py", line 148, in map > ? ? return self.map_async(func, iterable, chunksize).get() > ? File "/usr/lib/python2.6/multiprocessing/pool.py", line 422, in get > ? ? raise self._value > TypeError: expected string or buffer This is almost certainly due to your scrape call raising an exception. In the parent process, multiprocessing will detect if one of its workers have terminated with an exception and then re-raise it. However, only the exception and not the original traceback is made available, which is making debugging more difficult for you. Here's a simple example which demonstrates this behavior: *** from multiprocessing import Pool *** def evil_on_8(x): ... if x == 8: raise ValueError("I DONT LIKE THE NUMBER 8") ... return x + 1 ... *** pool = Pool(processes=4) >>> pool.map(evil_on_8, range(5)) [1, 2, 3, 4, 5] *** pool.map(evil_on_8, range(10)) # 8 will cause evilness. Traceback (most recent call last): File "", line 1, in File "/bb/real/3ps/lib/python2.6/multiprocessing/pool.py", line 148, in map return self.map_async(func, iterable, chunksize).get() File "/bb/real/3ps/lib/python2.6/multiprocessing/pool.py", line 422, in get raise self._value ValueError: I DONT LIKE THE NUMBER 8 *** My recommendation is that you wrap your scrape code inside a try/ except and log any exception. I usually do this with logging.exception (), or if logging is not in use, the traceback module. After that you can simply re-raise it. From no.email at please.post Wed Aug 5 15:58:39 2009 From: no.email at please.post (kj) Date: Wed, 5 Aug 2009 19:58:39 +0000 (UTC) Subject: no-clobber dicts? References: <00027aa9$0$2969$c3e8da3@news.astraweb.com> Message-ID: In <00027aa9$0$2969$c3e8da3 at news.astraweb.com> Steven D'Aprano writes: >No problem. Here you go: >http://www.cybersource.com.au/users/steve/python/constants.py Extremely helpful. Thanks! kynn From wolfram.hinderer at googlemail.com Wed Aug 5 16:00:07 2009 From: wolfram.hinderer at googlemail.com (Wolfram Hinderer) Date: Wed, 5 Aug 2009 13:00:07 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: <214e2b0a-15c9-4d2b-a836-9ad75a13fc6c@r38g2000yqn.googlegroups.com> On 5 Aug., 21:31, Mensanator wrote: > > >>> import turtle > >>> tooter = turtle.Turtle() > >>> tooter.tracer > > Traceback (most recent call last): > ? File "", line 1, in > ? ? tooter.tracer > AttributeError: 'Turtle' object has no attribute 'tracer'>>> tooter.hideturtle() > >>> tooter.speed('fast') > >>> turtle.update() > >>> turtle.tracer > > > > How did the tracer attribute appear out of thin air? You seem to confuse the "tooter" Turtle object and the "turtle" module when talking about "the tracer attribute". From piet at cs.uu.nl Wed Aug 5 16:07:29 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 22:07:29 +0200 Subject: Is this a bug in multiprocessing or in my script? References: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> <74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> <6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> Message-ID: >>>>> sturlamolden (s) wrote: >s> On 5 Aug, 15:40, Jesse Noller wrote: >>> Sturla; >>> >>> That bug was fixed unless I'm missing something. >s> It is still in SVN. Change every call to os._exit to sys.exit >s> please. :) Calling os.exit in a child process may be dangerous. It can cause unflushed buffers to be flushed twice: once in the parent and once in the child. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From ethan at stoneleaf.us Wed Aug 5 16:08:00 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 05 Aug 2009 13:08:00 -0700 Subject: Turtle Graphics are incompatible with gmpy In-Reply-To: References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: <4A79E6A0.5040404@stoneleaf.us> Mensanator wrote: > > What does this mean? > > >>>>import turtle >>>>tooter = turtle.Turtle() >>>>*tooter*.tracer > > Traceback (most recent call last): > File "", line 1, in > tooter.tracer > AttributeError: 'Turtle' object has no attribute 'tracer' > >>>>tooter.hideturtle() >>>>tooter.speed('fast') >>>>turtle.update() >>>>*turtle*.tracer > > > > How did the tracer attribute appear out of thin air? Perhaps I am missing something (wouldn't surprise me!) but it seems that the first time you are looking for a tracer on 'tooter', and the second time you are looking for a tracer on 'turtle'. After *turtle.tracer* succeeds, does *tooter.tracer*? ~Ethan~ From no.email at please.post Wed Aug 5 16:09:25 2009 From: no.email at please.post (kj) Date: Wed, 5 Aug 2009 20:09:25 +0000 (UTC) Subject: How to combine regexps? Message-ID: One of the nice things one can do with Perl's regexp's is illustrated in the following example: my $gly = qr/gg[ucag]/i my $ala = qr/gc[ucag]/i; my $val = qr/gu[ucag]/i; my $leu = qr/uu[ag]|cu[ucag]/i; my $ile = qr/au[uca]/i; my $aliphatic = qr/$gly|$ala|$val|$leu|$ile/; In other words, one can build regular expressions by re-combining other regular expressions. Is there a way to do this with Python's regexps? TIA! kynn From aahz at pythoncraft.com Wed Aug 5 16:11:37 2009 From: aahz at pythoncraft.com (Aahz) Date: 5 Aug 2009 13:11:37 -0700 Subject: Printing with colors in a portable way References: <33e19169-19b4-497a-b262-2bcf7b5637d5@r38g2000yqn.googlegroups.com> <19e16923-b200-498b-9ab2-f7d316b568a6@d32g2000yqh.googlegroups.com> Message-ID: In article <19e16923-b200-498b-9ab2-f7d316b568a6 at d32g2000yqh.googlegroups.com>, r wrote: >On Aug 2, 9:52=A0pm, a... at pythoncraft.com (Aahz) wrote: > >> Much as I hate to say, use a cross-platform GUI -- Tkinter comes with >> Python, > >Why is Tkinter such a whipping boy of the Python community? Can you explain what the connection is between my post and yours? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From piet at cs.uu.nl Wed Aug 5 16:14:04 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 22:14:04 +0200 Subject: http access produces 503 References: <3b5ab07c-7b0b-4d23-965b-192dc86cf6ff@a26g2000yqn.googlegroups.com> Message-ID: >>>>> Rog (R) wrote: >R> I am porting a simple code from Perl, the website asks for usr/pwd and >R> the server's side Perl script makes atemp ftp dir for file upload. >R> The original Perl script connects okay, does its job. The same URL >R> stuffed into FF3 performs the same way. >R> My Python script I am sweating out for past four days (noob!) gets >R> consistently "503", even with user agen set to: Mozilla/5.0 (Windows; >R> U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11. >R> Snippets of relevant code below. >R> Please, help me understand how this same code lets me log in into my >R> router usr/pwd running .asp, but this !@#$% perl script returns to me >R> w/503 c*ap? >R> Thank you. Which perl script? >R> Do I need to set any proxy? The server is on intranet and the FF3 is >R> set to proxy. The original Perl script did not use any proxy setting. >R>

>R> url = http://example.com/ftpsetup.pl?username=boofa&nodeid=42
>R> #########################################################
>R> # create a password manager
>R>     password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
>R> # Add the username and password.
>R> # If we knew the realm, we could use it instead of ``None``.
>R>     password_mgr.add_password(None, url, uid, pcode)
>R>     handler = urllib2.HTTPBasicAuthHandler(password_mgr)
>R>     class Mopener(URLopener): version = "Mozilla/5.0 (Windows; U;
>R> Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

>R>     opener = Mopener()

>R> # create "opener" (OpenerDirector instance)

>R>     opener = urllib2.build_opener(handler)
>R>     opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U;
>R> Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11')]

>R>     opener.version = "Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:
>R> 1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

>R>     print opener.version
>R> # timeout in seconds
>R>     timeout = 10
>R>     socket.setdefaulttimeout(timeout)

>R> # Install the opener all calls to urllib2.urlopen use our opener.
>R>     urllib2.install_opener(opener)

>R>     try:
>R>         response = opener.open(url)
>R>         # "http://www.useragent.org/" tested okay!!!
>R>         print"ok = 1"
>R>     except:
>R>         print "error 1"
>R> #####################################################################################

This code is a mess. The indentation is wrong so it can't be your real
code. Imports are missing. And there is a lot of garbage that doen't do
anything. E.g. The Mopener business is not used. install_opener is not
used.

Please make a minimal examples and check if that fails to. Like:

import urllib2
import socket

url = 'http://example.com/ftpsetup.pl?username=boofa&nodeid=42'
uid = ...
pcode = ...

# create a password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
password_mgr.add_password(None, url, uid, pcode)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)

# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)

try:
    response = opener.open(url)
    print response.read()
    print"ok = 1"
except:
    print "error 1"



>R> output from the above:

>R> Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/
>R> 20071127 Firefox/2.0.0.11
>R> error 1
>R> Error code:  503
>R> ('Service Unavailable', 'The server cannot process the request due to
>R> a high load')

That suggests that there is a real problem in the server. Or that your
url causes some problems.

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From pfeldman at verizon.net  Wed Aug  5 16:16:31 2009
From: pfeldman at verizon.net (Dr. Phillip M. Feldman)
Date: Wed, 5 Aug 2009 13:16:31 -0700 (PDT)
Subject: trouble with complex numbers
In-Reply-To: 
References: <24821423.post@talk.nabble.com> 
Message-ID: <24835436.post@talk.nabble.com>


I am using Python 2.5, and most of the cmath functions are not yet available
in this version.  Thanks!

Phillip

P.S. In your code, that should be x+= 0J

P.P.S. I wish that the documentation indicated anything that is new.


Christian Heimes-2 wrote:
> 
> 
> 
> phase() has been added to Python 2.6 and 3.0. It's not available in 
> Python 2.5 and earlier. If you'd used cmath.phase() instead of the ugly 
> "from cmath import *" statement you'd have seen the correct error message.
> 
> You can write your own phase() function. This function is mostly correct 
> unless either the real and/or the imag part is NaN or INF.
> 
> from math import atan2
> 
> def phase(z):
>      z += 1j # convert int, long, float to complex
>      return atan2(z.imag, z.real)
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

-- 
View this message in context: http://www.nabble.com/trouble-with-complex-numbers-tp24821423p24835436.html
Sent from the Python - python-list mailing list archive at Nabble.com.



From gagsl-py2 at yahoo.com.ar  Wed Aug  5 16:18:02 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 05 Aug 2009 17:18:02 -0300
Subject: Python configuration question when python scripts are executed
	using Appweb as web server.
References: 
	
	
Message-ID: 

En Tue, 04 Aug 2009 10:15:24 -0300, IronyOfLife 
escribi?:
> On Aug 3, 8:42?pm, "Gabriel Genellina"  wrote:
>> En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife   
>> escribi?:
>>
>> > I have installed python 2.6.2 in windows xp professional machine. I
>> > have set the following environment variables -- PYTHONPATH. It points
>> > to following windows folders: python root folder, the lib folder and
>> > lib-tk folder.
>>
>> Why? Did you read it somewhere? Usually there is no need to set the ?
>> PYTHONPATH variable at all; remove it.
>
> Setting PYTHONPATH environment variables is mentioned in Python docs.

Could you provide a link please? Setting PYTHONPATH should not be
necesary, and in fact it's a very bad idea. Environment variables are
global, but Python modules may depend on the Python version, architecture,
install location... By example, you may install a 64 bits Python 3.1
version *and* a 32 bits Python 2.5 version and they both can coexist
peacefully - but an extension module compiled for the former cannot be
used in the later version. You must build a separate library for each
version, and install them in two separate directories. But since the
PYTHONPATH variable is shared by all installations, which directory should
contain?
It's best not to use PYTHONPATH at all and rely on other alternatives
(like .pth files, that are searched relative to the current Python
executable, so different versions use different configuration files)

> I solved the issue temporarily by copying the gnutls related dlls to
> the path searched by python.exe

Glad to see you could finally fix it!

-- 
Gabriel Genellina



From robert.kern at gmail.com  Wed Aug  5 16:27:51 2009
From: robert.kern at gmail.com (Robert Kern)
Date: Wed, 05 Aug 2009 15:27:51 -0500
Subject: trouble with complex numbers
In-Reply-To: <24835436.post@talk.nabble.com>
References: <24821423.post@talk.nabble.com> 
	<24835436.post@talk.nabble.com>
Message-ID: 

On 2009-08-05 15:16, Dr. Phillip M. Feldman wrote:
> I am using Python 2.5, and most of the cmath functions are not yet available
> in this version.  Thanks!
>
> Phillip
>
> P.S. In your code, that should be x+= 0J
>
> P.P.S. I wish that the documentation indicated anything that is new.

It does.

http://docs.python.org/library/cmath#cmath.phase

"New in version 2.6."

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From malc0de.encrypt at gmail.com  Wed Aug  5 16:28:30 2009
From: malc0de.encrypt at gmail.com (MalC0de)
Date: Wed, 5 Aug 2009 13:28:30 -0700 (PDT)
Subject: Error on Attaching to the process while debugging
Message-ID: <21dbc649-2f82-4e4c-9777-c8a58c25a9e0@r2g2000yqm.googlegroups.com>

Hello there, I'm writting a debugger,
the problem is there no good interpretation ...

here's the codes:

my_debugger.py :

#!/usr/bin/env python
from ctypes import *
from my_debugger_defines import *
kernel32 = windll.kernel32
class debugger():
    def __init__(self):
	  self.h_process = None
	  self.pid = None
	  self.debugger_active = False
          pass
    def load(self,path_to_exe):
        creation_flags = DEBUG_PROCESS
        startupinfo = STARTUPINFO()
        process_information = PROCESSINFORMATION()
        startupinfo.dwFlags = 0x1
        startupinfo.wShowWindow = 0x0
        startupinfo.cb = sizeof(startupinfo)
        if kernel32.CreateProcessA(path_to_exe,
                                    None,
                                    None,
                                    None,
                                    None,
                                    creation_flags,
                                    None,
                                    None,
                                    byref(startupinfo),
                                    byref(process_information)):
                  print "[*]we have sucessfully launched the process"
                  print "[*]PID %d" % process_information.dwProcessId
                  self.h_process = self.open_process
(process_information.dwProcessId)
        else:
            print"[*]Error 0x%08x." % kernel32.GetLastError()

def Open_process(self,pid):
    h_process = kernel32.OpenProcess(PROCESS_ALL_ACCESS,pid,False)
    return h_process
def attach(self,pid):
        self.h_process = self.open_process(pid)
        # We attempt to attach to the process
        # if this fails we exit the call
        if kernel32.DebugActiveProcess(pid):
            self.debugger_active = True
            self.pid             = int(pid)

        else:
            print "[*] Unable to attach to the process."

def run(self):
    while self.debugger_active == True:
        self.get_debug_event()
def get_debug_event(self):
    debug_event = DEBUG_EVENT()
    continue_status = DBG_CONTINUE
    if kernel32.WaitForDebugEvent(byref(debug_event),INFINITE):
        raw_input("Press a key to continue ...")
    self.debugger_active = False
    kernel32.ContinueDebugEvent
(debug_event.dwProdcessid,debug_event.dwThreadId,continue_status)
    def detach(self):
        if kernel32.DeugActiveProcessStop(self.pid):
            print "[*]Finished debugging. exiting ..."
            return True
        else:
            print "there was an error"
            return false

it's already have a method named : Attach ...

ok, the next source ,
my_test.py which lead python to launching the calc.exe for testing
purpose .

my_test.py :

#!/usr/bin/python
import my_debugger
debugger = my_debugger.debugger()
pid = raw_input("Enter the PID of the process to attach to :")
debugger.attach(int(pid))
debugger.detach()

and finally the essential definitions into my_debugger_defines.py

#!/usr/bin/env python
from ctypes import *
WORD = c_ushort
DWORD = c_ulong
LPBYTE = POINTER(c_ubyte)
LPTSTR = POINTER(c_char)
HANDLE = c_void_p
DEBUG_PROCESS = 0x00000001
CREATE_NEW_CONSOLE = 0x00000010
class STARTUPINFO(Structure):
    _fielnds_ = [
        ("cb",                                  DWORD),
        ("lpReserved",                          LPTSTR),
        ("lpDesktop",                           LPTSTR),
        ("lpTitle",                             LPTSTR),
        ("dwX",                                 DWORD),
        ("dwY",                                 DWORD),
        ("dwXSize",                             DWORD),
        ("dwYSize",                             DWORD),
        ("dwXCountChars",                       DWORD),
        ("dwFillAttribute",                     DWORD),
        ("dwFlags",                             DWORD),
        ("wShowWindow",                          WORD),
        ("cbReserved2",                          WORD),
        ("lpReserved2",                        LPBYTE),
        ("hStdInput",                          HANDLE),
        ("hStdOutput",                         HANDLE),
        ("hStdError",                          HANDLE),
    ]
class PROCESSINFORMATION(Structure):
    _fields_ = [
        ("hProcess",                           HANDLE),
        ("hThread",                            HANDLE),
        ("dwProcessId",                         DWORD),
        ("dwThreadId",                          DWORD),
    ]

when you type : python my_test.py it must run without any problem, but
seems errors occures while interpretation :

Enter the PID of the process to attach to :212
Traceback (most recent call last):
  File "C:\python25\2\my_Test.py", line 5, in 
    debugger.attach(int(pid))
AttributeError: debugger instance has no attribute 'attach'

it's nasty shit !
the my_debugger is already has a definition for attach() ,

please help me up,

thanks ...


From jnoller at gmail.com  Wed Aug  5 16:28:45 2009
From: jnoller at gmail.com (Jesse Noller)
Date: Wed, 5 Aug 2009 13:28:45 -0700 (PDT)
Subject: Is this a bug in multiprocessing or in my script?
References: 
	<2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> 
	<74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> 
	<6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> 
	
Message-ID: <4a238650-45b0-4478-884f-257fa2d3e9ba@o32g2000yqm.googlegroups.com>

On Aug 5, 3:40?pm, sturlamolden  wrote:
> On 5 Aug, 21:36, sturlamolden  wrote:
>
> >http://svn.python.org/view/python/branches/release26-maint/Lib/multip...
>
> >http://svn.python.org/view/python/branches/release31-maint/Lib/multip...
>
> http://svn.python.org/view/python/trunk/Lib/multiprocessing/forking.p...

Since the bug was never filed in the tracker (it was sent to my
personal mail box, and I dropped it - sorry), I've filed a new one:

http://bugs.python.org/issue6653

In the future please use the bug tracker to file and track bugs with,
so things are not as lossy.

jesse


From massi_srb at msn.com  Wed Aug  5 16:30:27 2009
From: massi_srb at msn.com (Massi)
Date: Wed, 5 Aug 2009 13:30:27 -0700 (PDT)
Subject: Web page data and urllib2.urlopen
Message-ID: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>

Hi everyone, I'm using the urllib2 library to get the html source code
of web pages. In general it works great, but I'm having to do with a
financial web site which does not provide the souce code I expect. As
a matter of fact if you try:

import urllib2
res = urllib2.urlopen("http://www.marketwatch.com/story/mondays-
biggest-gaining-and-declining-stocks-2009-07-27")
page = res.read()
print page

you will see that the printed code is very different from the one
given, for example, by mozilla. Since I have really little knowledge
in html I can't even understand if this is a python or html problem.
Can anyone give me some help?
Thanks in advance.


From sturlamolden at yahoo.no  Wed Aug  5 16:35:02 2009
From: sturlamolden at yahoo.no (sturlamolden)
Date: Wed, 5 Aug 2009 13:35:02 -0700 (PDT)
Subject: Is this a bug in multiprocessing or in my script?
References: 
	<2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> 
	<74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> 
	<6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> 
	
Message-ID: <8d19bdd2-ac70-4fd0-bea3-56ab520048de@z31g2000yqd.googlegroups.com>

On 5 Aug, 22:07, Piet van Oostrum  wrote:

> Calling os.exit in a child process may be dangerous. It can cause
> unflushed buffers to be flushed twice: once in the parent and once in
> the child.

I assume you mean sys.exit. If this is the case, multiprocessing needs
a mechanism to chose between os._exit and sys.exit for child
processes. Calling os._exit might also be dangerous because it could
prevent necessary clean-up code from executing  (e.g. in C
extensions). I had a case where shared memory on Linux (System V IPC)
leaked due to os._exit. The deallocator for my extension type never
got to execute in child processes. The deallocator was needed to
release the shared segment when its reference count dropped to 0.
Changing to sys.exit solved the problem. On Windows there was no leak,
because the kernel did the reference counting.




From pavlovevidence at gmail.com  Wed Aug  5 16:35:23 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Wed, 5 Aug 2009 13:35:23 -0700 (PDT)
Subject: How to combine regexps?
References: 
Message-ID: 

On Aug 5, 1:09?pm, kj  wrote:
> One of the nice things one can do with Perl's regexp's is illustrated
> in the following example:
>
> my $gly = qr/gg[ucag]/i
> my $ala = qr/gc[ucag]/i;
> my $val = qr/gu[ucag]/i;
> my $leu = qr/uu[ag]|cu[ucag]/i;
> my $ile = qr/au[uca]/i;
>
> my $aliphatic = qr/$gly|$ala|$val|$leu|$ile/;
>
> In other words, one can build regular expressions by re-combining
> other regular expressions.
>
> Is there a way to do this with Python's regexps?

Your example is just string manipulation.

You're not combining regexps here, you are combining strings which you
(evidently) will soon use to create a regexp.

Yes, you can do that in Python as well, in exactly the same way, using
Python's string manipulation capabilities.


Carl Banks


From no.email at please.post  Wed Aug  5 16:36:07 2009
From: no.email at please.post (kj)
Date: Wed, 5 Aug 2009 20:36:07 +0000 (UTC)
Subject: How to combine regexps?
References: 
Message-ID: 

In  kj  writes:



>One of the nice things one can do with Perl's regexp's is illustrated
>in the following example:

>my $gly = qr/gg[ucag]/i
>my $ala = qr/gc[ucag]/i;
>my $val = qr/gu[ucag]/i;
>my $leu = qr/uu[ag]|cu[ucag]/i;
>my $ile = qr/au[uca]/i;

>my $aliphatic = qr/$gly|$ala|$val|$leu|$ile/;


>In other words, one can build regular expressions by re-combining
>other regular expressions.

>Is there a way to do this with Python's regexps?


OK, answering my own question here, it looks like the only way to
do this is to leave the "component" expressions as regular strings,
and combine those, before compiling them into regexps.

Easy enough.

kynn


From joncle at googlemail.com  Wed Aug  5 16:39:33 2009
From: joncle at googlemail.com (Jon Clements)
Date: Wed, 5 Aug 2009 13:39:33 -0700 (PDT)
Subject: Parsing Binary Structures; Is there a better way / What is your 
	way?
References: 
	<7x3a86gmfe.fsf@ruckus.brouhaha.com> 
	
	<7xr5vqw0v9.fsf@ruckus.brouhaha.com> 
	
Message-ID: <1211ccf7-1147-42de-ab62-3e5b33b09011@k19g2000yqn.googlegroups.com>

On 5 Aug, 20:41, "Martin P. Hellwig" 
wrote:
> Paul Rubin wrote:
> > "Martin P. Hellwig"  writes:
> >> Is there an advantage using shifts and masks over my kitchen type solution?
>
> > Weren't you complaining about the 8-to-1 expansion from turning each bit
> > to an ascii char?
>
> Yes you are (of course) right, my 'dream' solution would be something
> that accepts slice indeces on bit level. Your reasoning did reveal some
> flaws in my approach though ;-)
>
> --
> MPHhttp://blog.dcuktec.com
> 'If consumed, best digested with added seasoning to own preference.'

Ahh huh -- found it...

ID: DLT119
Desc: datasyzygy misc. development, production and accounts.
Date: 2008-12-09
File: pybits.py
"""
Implements a python level interface to reading bit fields with an
associated type. Fields are accessed via __getitem__ and must be a
valid python name. eg:

class MyStructure:
    a = BitField(4, int)
    b = BitField(6, int)
    c = BitField(2, int)
    d = BitField(36, str)
"""

Ummm, seems I left the rest pretty vague, but I'm guessing that's what
you're after, and I'm fairly curious to see what I wrote... mind you,
not too hard to write again now that's jogged my memory! (although
after a couple at the pub, not going to do it tonight!)

Cheers,

Jon.



From mensanator at aol.com  Wed Aug  5 16:40:28 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 13:40:28 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	
	
Message-ID: <87b655e8-937b-4f62-ad1e-5165d547a7bd@v20g2000yqm.googlegroups.com>

On Aug 5, 3:08?pm, Ethan Furman  wrote:
> Mensanator wrote:
>
> 
>
>
>
>
>
>
>
> > What does this mean?
>
> >>>>import turtle
> >>>>tooter = turtle.Turtle()
> >>>>*tooter*.tracer
>
> > Traceback (most recent call last):
> > ? File "", line 1, in 
> > ? ? tooter.tracer
> > AttributeError: 'Turtle' object has no attribute 'tracer'
>
> >>>>tooter.hideturtle()
> >>>>tooter.speed('fast')
> >>>>turtle.update()
> >>>>*turtle*.tracer
>
> > 
>
> > How did the tracer attribute appear out of thin air?
>
> Perhaps I am missing something (wouldn't surprise me!) but it seems that
> the first time you are looking for a tracer on 'tooter', and the second
> time you are looking for a tracer on 'turtle'. ?

Duh. I could have looked at that from now til the sun don't shine and
not seen it. And I even retyped it, no cut/paste.

> After *turtle.tracer*
> succeeds, does *tooter.tracer*?

No, that was my mistake. Too late now as the record is gone, but I
could have sworn I had the math exception first. That's what made
me go realize the tracing wasn't off which led me to add .screen.

Sounds like I should have gotten the attribute error first.

Maybe I did and am mis-remembering it. Usually, I don't start keeping
notes at first because I'm not expecting failure.

>
> ~Ethan~



From sturlamolden at yahoo.no  Wed Aug  5 16:41:53 2009
From: sturlamolden at yahoo.no (sturlamolden)
Date: Wed, 5 Aug 2009 13:41:53 -0700 (PDT)
Subject: Is this a bug in multiprocessing or in my script?
References: 
	<2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> 
	<74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> 
	<6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> 
	 
	<4a238650-45b0-4478-884f-257fa2d3e9ba@o32g2000yqm.googlegroups.com>
Message-ID: <54cdf823-7b2c-4ff8-b1f2-b8091a7daeb8@d32g2000yqh.googlegroups.com>

On 5 Aug, 22:28, Jesse Noller  wrote:

> http://bugs.python.org/issue6653
>
> In the future please use the bug tracker to file and track bugs with,
> so things are not as lossy.

Ok, sorry :)

Also see Piet's comment here. He has a valid case against sys.exit in
some cases. Thus it appears that both ways of shutting down child
processes might be dangerous: If we don't want buffers to flush we
have to use os._exit. If we want clean-up code to execute we have to
use sys.exit. If we want both we are screwed. :(






From netgraviton at gmail.com  Wed Aug  5 16:42:40 2009
From: netgraviton at gmail.com (WordStream)
Date: Wed, 5 Aug 2009 13:42:40 -0700 (PDT)
Subject: [ATTN] Sr. Software Development Engineer
Message-ID: 

Postion Title - Sr. Software Development Engineer

Job Responsibilities
The Sr. Software Development Engineer will be responsible for the
design, development and implementation of the award-winning WordStream
suite of products.

Development is presently done primarily using Python on the server and
Adobe Flex/HTML/AJAX as a Rich Internet Application (RIA) frontend.
However, like everything in the computing industry, we're constantly
evolving how we work.  We're always on the lookout for newer and
better technologies, and as a result, the technologies we use tomorrow
are likely to be different.

This is a full-time telecommute position.  The Sr. Software
Development Engineer can choose to work in our Boston office, or they
can choose to work from at home or from any location in the world.

Qualifications
The Sr. Software Development Engineer will be an individual who has
top-notch coding skills, and can demonstrate an aptitude to learn new
technologies.

Prior experience with any specific technologies (e.g., Python or Adobe
Flex) is not a requirement; we're looking for people with a history of
leveraging any technology to create masterpieces.

Prior experience working on web analytics applications, search
engines, content management systems or other Web publishing systems is
a plus.

Please note, only candidates with a bachelor's degree in computer
science or engineering, or, a very substantial amount of related
technical coursework and work experience in a related field will be
considered.

Related Skills
Python, Adobe Flex, Structured Query Language (SQL), Object-Oriented
Programming, SQLite, Open-Source software development, Git, Object-
Relational Mapping (ORM), Postgres SQL, AJAX, HTML, Search Engine
Optimization (SEO) or Search Engine Marketing (SEM)

Compensation
?	Full-time salaried position, with competitive salary.
?	Position includes equity participation and comprehensive benefits
(healthcare, vision and dental).
?	Flexibility to work from any location, worldwide.

About WordStream
Founded in August 2008 by experienced search marketers and software
experts, WordStream has developed the first database-driven Keyword
Management Software solution for pay-per-click advertisers and
agencies. With the decline in print and traditional media, companies
of every size are flocking to the Internet, search engine marketing
and, specifically, Google AdWords to advertise their products and
services. But mastering even the basics of search engine marketing
isn?t easy ? until now! From keyword discovery to ad group creation,
WordStream helps pay-per-click advertisers build the solid keyword
foundation required for PPC success. WordStream is backed by Sigma +
Partners. For more information please visit: http://www.wordstream.com

How To Apply
To apply for the Sr. Software Development Engineer position, send a
resume to jobs at WordStream dot com.


From rogerb at rogerbinns.com  Wed Aug  5 16:45:09 2009
From: rogerb at rogerbinns.com (Roger Binns)
Date: Wed, 05 Aug 2009 13:45:09 -0700
Subject: Do anyone here use Python *embedded* in a database?
In-Reply-To: 
References: 
Message-ID: 

Jonathan Fine wrote:
> anyone here ever used the Python *embedded* in a database server.

There is also the case of using SQLite where it shares the same process as
your Python code (and nothing else) and is a standard part of the Python
library.

You can add your own functions and collations and if using APSW then you can
also go way further than a regular database and add virtual tables and
virtual storage.

SQLite generally outperforms database servers since there is no cross
process or network communication until you get to larger workloads and/or
concurrent database access which database servers are more tuned for.

Roger



From jnoller at gmail.com  Wed Aug  5 16:50:03 2009
From: jnoller at gmail.com (Jesse Noller)
Date: Wed, 5 Aug 2009 13:50:03 -0700 (PDT)
Subject: Is this a bug in multiprocessing or in my script?
References: 
	<2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> 
	<74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> 
	<6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> 
	 
	<4a238650-45b0-4478-884f-257fa2d3e9ba@o32g2000yqm.googlegroups.com> 
	<54cdf823-7b2c-4ff8-b1f2-b8091a7daeb8@d32g2000yqh.googlegroups.com>
Message-ID: 

On Aug 5, 4:41?pm, sturlamolden  wrote:
> On 5 Aug, 22:28, Jesse Noller  wrote:
>
> >http://bugs.python.org/issue6653
>
> > In the future please use the bug tracker to file and track bugs with,
> > so things are not as lossy.
>
> Ok, sorry :)
>
> Also see Piet's comment here. He has a valid case against sys.exit in
> some cases. Thus it appears that both ways of shutting down child
> processes might be dangerous: If we don't want buffers to flush we
> have to use os._exit. If we want clean-up code to execute we have to
> use sys.exit. If we want both we are screwed. :(

Comments around this bug should go in the bug report - again, so we
don't loose them. I do not personally subscribe to this group , so
it's very easy to miss things.

jesse


From mensanator at aol.com  Wed Aug  5 17:03:05 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 14:03:05 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
Message-ID: 

On Aug 5, 12:56?pm, Gregor Lingl  wrote:
> Mensanator schrieb:
>
>
>
>
>
> >> It didn't form 2.5 to 2.6 (at least not intentionally). But with the
> >> indroduction of the TurtleScreen class and the Screen class/object
> >> (singleton) a few of the turtle methods were also implemented as screen
> >> methods and as turtle methods declared deprecated (see docs of Python
> >> 2.6). These deprecated turtle methods do not occur as turtle methods any
> >> more in Python 3.x.
>
> > More info.
>
> > Yes, there is no tracer attribute...when the object is created.
>
> > But watch this (Python 3.1):
>
> >>>> import turtle
> >>>> tooter = turtle.Turtle()
> >>>> tooter.tracer
> > Traceback (most recent call last):
> > ? File "", line 1, in 
> > ? ? tooter.tracer
> > AttributeError: 'Turtle' object has no attribute 'tracer'
> >>>> tooter.hideturtle()
> >>>> tooter.speed('fast')
> >>>> turtle.update()
> >>>> turtle.tracer
> > 
>
> > Now, after setting hide, speed, update, a tracer exists.
>
> No,

Yeah, I mistyped my example, sorry about that. I thought sure
it was the math error that lead me to the tracer issue, but that
might have been a mistake.

>
> Nevertheless I'd like to see a working Python 2.5 version of your script.

I've commented out the parts that v2.5 doesn't have.
So the pen is still down and I have no .dot function,
but the gotos appear to still work as evidenced by
the large black square it now draws.

With tracing on in 2.5, I see the turtle move around
the square. With tracing off, I still the the square
outined, but without a turtle and much faster.

With 3.1, the screen is completely blank for 3-4 seconds and appears
all at once when it's done.

import gmpy

##   (even) hi----|
##                |
##                lo (odd)
## or
##
##   (even) lo
##           |
##           |
##           ----hi (odd)
##
##
##
##

import turtle

tooter = turtle.Turtle()

#tooter.hideturtle()
tooter.speed('fast')
#turtle.update()
tooter.tracer(False)
#tooter.penup()
tooter.color('black')

s = ['1','0']
while len(s[0])<10000:
    s = [''.join(s), s[0]]


origin = [0,0]
if s[0] == '0':
  tooter.goto(origin)
  #tooter.dot(1)
if s[1] == '0':
  tooter.goto([1,0])
  #tooter.dot(1)

print len(s[0])

for i,j in enumerate(s[0]):
  the_coord=[]
  cur_root = gmpy.sqrt(i)
  lo__root = gmpy.sqrt(i)**2
  hi__root = (gmpy.sqrt(i)+1)**2

  if hi__root%2==0:
    side = 'northeast'
  else:
    side = 'southwest'

  elbow = (hi__root - lo__root)/2 + lo__root + 1

  if i>= elbow:
    side_len = i - elbow
    elbow_plus = True
  else:
    side_len = elbow - i
    elbow_plus = False

  if side == 'northeast':
    elbow_offset = [(gmpy.sqrt(elbow)-1)/2 +1,-((gmpy.sqrt(elbow)-1)/2
+1)]
  else:
    elbow_offset = [-((gmpy.sqrt(elbow)-1)/2 +1),((gmpy.sqrt(elbow)-1)/
2 +1)]

  elbow_coord = [origin[0]+elbow_offset[0],origin[1]+elbow_offset[1]]

  if i != hi__root and i != lo__root:
    if i == elbow:
      the_coord = elbow_coord
    else:
      if elbow_plus:
        if side == 'northeast':
          the_coord = [elbow_coord[0]-side_len,elbow_coord[1]]
        else:
          the_coord = [elbow_coord[0]+side_len,elbow_coord[1]]
      else:
        if side == 'northeast':
          the_coord = [elbow_coord[0],elbow_coord[1]+side_len]
        else:
          the_coord = [elbow_coord[0],elbow_coord[1]-side_len]
  else:
    if i % 2 == 0:  # even square
      n = gmpy.sqrt(i)/2 - 1
      the_coord = [-n, -n-1]
    else:
      n = (gmpy.sqrt(i)-1)/2 - 1
      the_coord = [1+n, 1+n]
  if j == '0':
    tooter.goto(the_coord)
    #tooter.dot(2)
print 'done'

#turtle.update()
turtle.done()
print 'done'


>
> Regards,
> Gregor


From deets at nospam.web.de  Wed Aug  5 17:19:20 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Wed, 05 Aug 2009 23:19:20 +0200
Subject: access string data from within cython
In-Reply-To: 
References: <7dtt46F2e5osvU1@mid.uni-berlin.de>
	
Message-ID: <7dubaoF2e96rfU2@mid.uni-berlin.de>

Philip Semanchuk schrieb:
> 
> On Aug 5, 2009, at 1:16 PM, Diez B. Roggisch wrote:
> 
>> Hi,
>>
>> I'm trying to wrap a C-API which has a call that takes a void* and a 
>> size_t
>> as arguments.
>>
>> void foo(void *data, size_t length)
>>
>>
>> The wrapper is supposed to be called with a python (byte)string instance,
>> which might contain more than one '\0'-character.
>>
>> So how do I access the raw data of a string? I tried looking into the
>> buffer-protocol, but to be honest - that's beyond me, I don't see where
>> that is actually giving me access to the real data.
> 
> Hi Diez,
> Would ctypes.create_string_buffer() work for you?

I'm not using ctypes because I want a distributable egg with static 
linkage. ctypes can't help there afaik.

Diez


From contact at xavierho.com  Wed Aug  5 17:22:44 2009
From: contact at xavierho.com (Xavier Ho)
Date: Thu, 6 Aug 2009 07:22:44 +1000
Subject: Subclassing Python's dict
In-Reply-To: 
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com>
	
Message-ID: <2d56febf0908051422h2cd0e58p1afce376895d5d1e@mail.gmail.com>

On Thu, Aug 6, 2009 at 5:23 AM, Joshua Kugler wrote:

> Are you referring to Python 3.0?  Python 2.6 does not have
> collections.UserDict
>
> j
>

Yes, I was.... sometimes it's hard to keep track what's not in 2.6 and in
3.1 for me, sorry. And thanks.

The ABC MutableMapping is still valid, though. I hope he gets it sorted out.


With a morning yawn,
Xavier
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From deets at nospam.web.de  Wed Aug  5 17:22:56 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Wed, 05 Aug 2009 23:22:56 +0200
Subject: access string data from within cython
In-Reply-To: <88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com>
References: <7dtt46F2e5osvU1@mid.uni-berlin.de>
	<88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com>
Message-ID: <7dubhgF2e96rfU3@mid.uni-berlin.de>

sturlamolden schrieb:
> On 5 Aug, 19:16, "Diez B. Roggisch"  wrote:
> 
>> void foo(void *data, size_t length)
>>
>> The wrapper is supposed to be called with a python (byte)string instance,
>> which might contain more than one '\0'-character.
>>
>> So how do I access the raw data of a string?
> 
> cdef extern void foo(void *data, int length)
> cdef char *data
> cdef int length
> bytestring = ... #whatever
> 
> rawdata =  bytestring
> length =  len(bytestring)

And that gives me the *full* bytestring, not only until the first zero? 
I can't try that right now (not at work anymore), but if it's that easy, 
that would be great.

Diez


From philip at semanchuk.com  Wed Aug  5 17:30:22 2009
From: philip at semanchuk.com (Philip Semanchuk)
Date: Wed, 5 Aug 2009 17:30:22 -0400
Subject: access string data from within cython
In-Reply-To: <7dubaoF2e96rfU2@mid.uni-berlin.de>
References: <7dtt46F2e5osvU1@mid.uni-berlin.de>
	
	<7dubaoF2e96rfU2@mid.uni-berlin.de>
Message-ID: <84411DCB-CD09-4EE1-B50E-51D005748BE1@semanchuk.com>


On Aug 5, 2009, at 5:19 PM, Diez B. Roggisch wrote:

> Philip Semanchuk schrieb:
>> On Aug 5, 2009, at 1:16 PM, Diez B. Roggisch wrote:
>>> Hi,
>>>
>>> I'm trying to wrap a C-API which has a call that takes a void* and  
>>> a size_t
>>> as arguments.
>>>
>>> void foo(void *data, size_t length)
>>>
>>>
>>> The wrapper is supposed to be called with a python (byte)string  
>>> instance,
>>> which might contain more than one '\0'-character.
>>>
>>> So how do I access the raw data of a string? I tried looking into  
>>> the
>>> buffer-protocol, but to be honest - that's beyond me, I don't see  
>>> where
>>> that is actually giving me access to the real data.
>> Hi Diez,
>> Would ctypes.create_string_buffer() work for you?
>
> I'm not using ctypes because I want a distributable egg with static  
> linkage. ctypes can't help there afaik.

Sorry, I read cython as CPython.




From xahlee at gmail.com  Wed Aug  5 17:44:49 2009
From: xahlee at gmail.com (Xah Lee)
Date: Wed, 5 Aug 2009 14:44:49 -0700 (PDT)
Subject: Google sitemap generator in python gone?
Message-ID: <5982ba4d-668c-460f-a666-5d7cbe697883@x25g2000prf.googlegroups.com>

google used to have a sitemap generator written in python, at:
 https://www.google.com/webmasters/tools/docs/en/sitemap-generator.html

but the url is gone. It seems the current version is moved here:
http://code.google.com/p/googlesitemapgenerator/
and is written in JavaScript.

is the old python version still available? or is there some official
doc about this change?

thanks.

  Xah
? http://xahlee.org/

?


From sturlamolden at yahoo.no  Wed Aug  5 17:51:12 2009
From: sturlamolden at yahoo.no (sturlamolden)
Date: Wed, 5 Aug 2009 14:51:12 -0700 (PDT)
Subject: access string data from within cython
References: <7dtt46F2e5osvU1@mid.uni-berlin.de>
	<88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com>
	<7dubhgF2e96rfU3@mid.uni-berlin.de>
Message-ID: <71adfa33-faee-48d7-adb0-1403d8af4fd5@c14g2000yqm.googlegroups.com>

On 5 Aug, 23:22, "Diez B. Roggisch"  wrote:

> And that gives me the *full* bytestring, not only until the first zero?
> I can't try that right now (not at work anymore), but if it's that easy,
> that would be great.

It should, and if it does not it is a bug in Cython. The len()
function should work similarly in Python and Cython: It should just
call the object's __len__ method. Cython has no idea that your Python
object bytestring is a byte string, nor does Cython care.

>>> bs = '\x00'*10 # bytes string with 10 zeros
>>> len(bs)
10
>>> bs.__len__()
10



From joncle at googlemail.com  Wed Aug  5 17:55:02 2009
From: joncle at googlemail.com (Jon Clements)
Date: Wed, 5 Aug 2009 14:55:02 -0700 (PDT)
Subject: Google sitemap generator in python gone?
References: <5982ba4d-668c-460f-a666-5d7cbe697883@x25g2000prf.googlegroups.com>
Message-ID: <631e148d-9e26-4779-b76a-bd405f4525c8@c34g2000yqi.googlegroups.com>

On 5 Aug, 22:44, Xah Lee  wrote:
> google used to have a sitemap generator written in python, at:
> ?https://www.google.com/webmasters/tools/docs/en/sitemap-generator.html
>
> but the url is gone. It seems the current version is moved here:http://code.google.com/p/googlesitemapgenerator/
> and is written in JavaScript.
>
> is the old python version still available? or is there some official
> doc about this change?
>
> thanks.
>
> ? Xah
> ?http://xahlee.org/
>
> ?

How about asking Google, and not this list?

It's always good to see a funny troll on this list though...

Now please piddle off...


From martin.hellwig at dcuktec.org  Wed Aug  5 17:59:18 2009
From: martin.hellwig at dcuktec.org (Martin P. Hellwig)
Date: Wed, 05 Aug 2009 22:59:18 +0100
Subject: Google sitemap generator in python gone?
In-Reply-To: <631e148d-9e26-4779-b76a-bd405f4525c8@c34g2000yqi.googlegroups.com>
References: <5982ba4d-668c-460f-a666-5d7cbe697883@x25g2000prf.googlegroups.com>
	<631e148d-9e26-4779-b76a-bd405f4525c8@c34g2000yqi.googlegroups.com>
Message-ID: 

Jon Clements wrote:

> Now please piddle off...

I am guessing west-midlands? :-)

-- 
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'


From python at mrabarnett.plus.com  Wed Aug  5 18:03:11 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Wed, 05 Aug 2009 23:03:11 +0100
Subject: How to combine regexps?
In-Reply-To: 
References:  
Message-ID: <4A7A019F.3070205@mrabarnett.plus.com>

kj wrote:
> In  kj  writes:
> 
> 
> 
>> One of the nice things one can do with Perl's regexp's is illustrated
>> in the following example:
> 
>> my $gly = qr/gg[ucag]/i
>> my $ala = qr/gc[ucag]/i;
>> my $val = qr/gu[ucag]/i;
>> my $leu = qr/uu[ag]|cu[ucag]/i;
>> my $ile = qr/au[uca]/i;
> 
>> my $aliphatic = qr/$gly|$ala|$val|$leu|$ile/;
> 
> 
>> In other words, one can build regular expressions by re-combining
>> other regular expressions.
> 
>> Is there a way to do this with Python's regexps?
> 
> 
> OK, answering my own question here, it looks like the only way to
> do this is to leave the "component" expressions as regular strings,
> and combine those, before compiling them into regexps.
> 
> Easy enough.
> 
A compiled regular expression has 'pattern' and 'flags' attributes, so
you can get the original parameters which were used to create it if a
function is given just the compiled regular expression. Might be useful.


From mensanator at aol.com  Wed Aug  5 18:31:17 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 15:31:17 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
	
Message-ID: 

I fixed this to produce the actual image I'm looking
for instead of that stupid black square. All I did was
use up() & dowm() in place of penup(), pendown() and
replace dot(2) with forward(1).

I'll be posting a followup report later.


import gmpy

##   (even) hi----|
##                |
##                lo (odd)
## or
##
##   (even) lo
##           |
##           |
##           ----hi (odd)
##
##
##
##

import turtle

tooter = turtle.Turtle()

#tooter.hideturtle()
tooter.speed('fast')
#turtle.update()
tooter.tracer(False)
#tooter.penup()
tooter.up()
tooter.color('black')

s = ['1','0']
while len(s[0])<10000:
    s = [''.join(s), s[0]]


origin = [0,0]
if s[0] == '0':
  tooter.goto(origin)
  #tooter.dot(1)
  tooter.down()
  tooter.forward(1)
  tooter.up()
if s[1] == '0':
  tooter.goto([1,0])
  #tooter.dot(1)
  tooter.down()
  tooter.forward(1)
  tooter.up()

print len(s[0])

for i,j in enumerate(s[0]):
  the_coord=[]
  cur_root = gmpy.sqrt(i)
  lo__root = gmpy.sqrt(i)**2
  hi__root = (gmpy.sqrt(i)+1)**2

  if hi__root%2==0:
    side = 'northeast'
  else:
    side = 'southwest'

  elbow = (hi__root - lo__root)/2 + lo__root + 1

  if i>= elbow:
    side_len = i - elbow
    elbow_plus = True
  else:
    side_len = elbow - i
    elbow_plus = False

  if side == 'northeast':
    elbow_offset = [(gmpy.sqrt(elbow)-1)/2 +1,-((gmpy.sqrt(elbow)-1)/2
+1)]
  else:
    elbow_offset = [-((gmpy.sqrt(elbow)-1)/2 +1),((gmpy.sqrt(elbow)-1)/
2 +1)]

  elbow_coord = [origin[0]+elbow_offset[0],origin[1]+elbow_offset[1]]

  if i != hi__root and i != lo__root:
    if i == elbow:
      the_coord = elbow_coord
    else:
      if elbow_plus:
        if side == 'northeast':
          the_coord = [elbow_coord[0]-side_len,elbow_coord[1]]
        else:
          the_coord = [elbow_coord[0]+side_len,elbow_coord[1]]
      else:
        if side == 'northeast':
          the_coord = [elbow_coord[0],elbow_coord[1]+side_len]
        else:
          the_coord = [elbow_coord[0],elbow_coord[1]-side_len]
  else:
    if i % 2 == 0:  # even square
      n = gmpy.sqrt(i)/2 - 1
      the_coord = [-n, -n-1]
    else:
      n = (gmpy.sqrt(i)-1)/2 - 1
      the_coord = [1+n, 1+n]
  if j == '0':
    tooter.goto(the_coord)
    #tooter.dot(2)
    tooter.down()
    tooter.forward(1)
    tooter.up()
print 'done'

#turtle.update()
turtle.done()
print 'done'


From ryan at rfk.id.au  Wed Aug  5 18:33:14 2009
From: ryan at rfk.id.au (Ryan Kelly)
Date: Thu, 06 Aug 2009 08:33:14 +1000
Subject: ANN:  extprot 0.1.1
Message-ID: <1249511594.4180.9.camel@durian>


Hi All,


Sorry if you get this twice, it seems to have gotten lost on its way
through python-announce.

I'm pleased to announce the first release of the "extprot" python
module.  Extprot implements a compact, efficient, extensible and
language-neutral object serialisation protocol.

License:      MIT
Downloads:    http://pypi.python.org/pypi/extprot/
Source code:  http://github.com/rfk/extprot/tree/master


You can think of extprot as something akin to Google's protocol buffers,
with a few extra bytes of serialisation overhead and a Python binding
that doesn't have nearly as many rough edges.  For example:

      * It's a stand-alone python module, packaged and distributed in
        the standard fashion.
      * It's friendly to dynamic package management tools like pip.
      * It works exclusively with standard Python objects. Declared a
        list field? It's a native list object.
      * You don't need to compile your protocol definitions.


More on the extprot format itself is here:

   http://eigenclass.org/R2/writings/extprot-extensible-protocols-intro

More on my motivations for this package here, if you're interested:

    http://www.rfk.id.au/blog/entry/new-python-module-extprot


Enjoy!


    Ryan

-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
ryan at rfk.id.au        |  http://www.rfk.id.au/ramblings/gpg/ for details

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 204 bytes
Desc: This is a digitally signed message part
URL: 

From steve at REMOVE-THIS-cybersource.com.au  Wed Aug  5 19:04:55 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 05 Aug 2009 23:04:55 GMT
Subject: trouble with complex numbers
References: <24821423.post@talk.nabble.com> 
	<24835436.post@talk.nabble.com>
	
Message-ID: <028a00b4$0$5185$c3e8da3@news.astraweb.com>

On Wed, 05 Aug 2009 15:27:51 -0500, Robert Kern wrote:

> On 2009-08-05 15:16, Dr. Phillip M. Feldman wrote:
>> I am using Python 2.5, and most of the cmath functions are not yet
>> available in this version.  Thanks!
>>
>> Phillip
>>
>> P.S. In your code, that should be x+= 0J
>>
>> P.P.S. I wish that the documentation indicated anything that is new.
> 
> It does.
> 
> http://docs.python.org/library/cmath#cmath.phase
> 
> "New in version 2.6."


Furthermore, every release comes with a What's New document:

http://docs.python.org/whatsnew/index.html




-- 
Steven


From lanyjie at yahoo.com  Wed Aug  5 19:05:41 2009
From: lanyjie at yahoo.com (Yingjie Lan)
Date: Wed, 5 Aug 2009 16:05:41 -0700 (PDT)
Subject: using expy to extend python
Message-ID: <871540.68601.qm@web54204.mail.re2.yahoo.com>


Hi,

The expy project provides an express way to extend Python. After some careful considerations, I came up with some reasons for expy (this is not an exhaustive list):

(I). WYSIWYG. The expy project enables you to write your module in Python the way your extension would be (WYSIWYG), and meanwhile write your implementation in pure C. You specify your modules, functions, methods, classes, and even their documentations the usual way of writing your Python correspondences. Then your provide your implementation to the functions/methods by returning a multi-line string. By such an arrangement, everything falls in its right place, and your extension code becomes easy to read and maintain. Also, the generated code is very human-friendly.

(II). You only provide minimal information to indicate your intension of how your module/class would function in Python. So your extension is largely independent from the Python extension API. As your interaction with the Python extension API is reduced to minimal (you only care about the functionality and logic), it is then possible that your module written in expy can be independent of changes in the extension API.

(III). The building and setup of your project can be automatically done with the distutil tool. In the tutorial, there are ample examples on how easily this is achieved.

(IV). Very light weight. The expy tool is surprisingly light weight dispite of its powerful ability, as it is written in pure Python. There is no parser or compiler for code generation, but rather the powerful reflexion mechanism of Python is exploited in a clever way to generate human-friendly codes. Currently, generating code in C is supported, however, the implementation is well modularized and code generation in other languages such as Java and C++ should be easy.

While there are already a couple of other projects trying to simply this task with different strategies, such as Cython, Pyrex and modulator, this project is unique and charming in its own way. All you need is the WYSIWYG Python file for your module extension, then expy takes care of everything else. What follows in this documentation is on how to extend Python in C using expy-cxpy: the module expy helps define your module, while module cxpy helps generate C codes for your defined module.

For more information about expy, please visit its homepage at: http://expy.sf.net/

Cheers,

Yingjie



      


From Samnsparky at gmail.com  Wed Aug  5 19:12:09 2009
From: Samnsparky at gmail.com (Sparky)
Date: Wed, 5 Aug 2009 16:12:09 -0700 (PDT)
Subject: Two Dimensional Array + ctypes
Message-ID: <79d2b3e3-b049-4d70-a56b-6e7f3ea2fa86@e27g2000yqm.googlegroups.com>

Hello! I am trying to call this method:

long _stdcall AIBurst(long *idnum,
			 long demo,
			 long stateIOin,
			 long updateIO,
			 long ledOn,
			 long numChannels,
			 long *channels,
			 long *gains,
			 float *scanRate,
			 long disableCal,
			 long triggerIO,
			 long triggerState,
			 long numScans,
			 long timeout,
			 float (*voltages)[4],
			 long *stateIOout,
			 long *overVoltage,
			 long transferMode);

I am having some problems with that  float (*voltages)[4]. Here is
what I tried:

def aiBurst(self, channels, scanRate, numScans, idNum=None, demo=0,
stateIOin=[0, 0, 0, 0], updateIO=0, ledOn=0, gains=[0, 0, 0, 0],
disableCal=0, triggerIO=0, triggerState=0, timeout=1, transferMode=0):

        if idNum is None:
            idNum = self.id

        idNum = ctypes.c_long(idNum)

        numChannels = len(channels)

        stateIOArray = listToCArray(stateIOin, ctypes.c_long)
        channelsArray = listToCArray(channels, ctypes.c_long)
        gainsArray = listToCArray(gains, ctypes.c_long)
        scanRate = ctypes.c_float(scanRate)
        pointerArray = (ctypes.c_void_p * 4)
        voltages = pointerArray(ctypes.cast(ctypes.pointer
((ctypes.c_long * 4096)()), ctypes.c_void_p), ctypes.cast
(ctypes.pointer((ctypes.c_long * 4096)()), ctypes.c_void_p),
ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)()),
ctypes.c_void_p), ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)
()), ctypes.c_void_p))
        stateIOout = (ctypes.c_long * 4096)()
        overVoltage = ctypes.c_long(999)

        staticLib.AIBurst(ctypes.byref(idNum), demo, stateIOArray,
updateIO, ledOn, numChannels, ctypes.byref(channelsArray), ctypes.byref
(gainsArray), ctypes.byref(scanRate), disableCal, triggerIO,
triggerState, numScans, timeout, ctypes.byref(voltages), ctypes.byref
(stateIOout), ctypes.byref(overVoltage), transferMode)

The program runs but the values that come back in the array are not
right. However, I am not sure if I am passing the array or if I am
just not reading them well afterwards. What is the best way to put
this in and what is the best way to cast it and read it back?

Thanks,
Sam


From nad at acm.org  Wed Aug  5 19:12:10 2009
From: nad at acm.org (Ned Deily)
Date: Wed, 05 Aug 2009 16:12:10 -0700
Subject: Install setup tools for 2.6
References: <373cf0740908051131gacaf77apba48fa40e929f491@mail.gmail.com>
Message-ID: 

In article 
<373cf0740908051131gacaf77apba48fa40e929f491 at mail.gmail.com>,
 Jeremy Cowles  wrote:
> Ok, I feel like this is a really stupid question, but how do you install
> setup tools for Python 2.6 under windows?
> The only format is .egg which requires setup tools to install, doesn't it?

http://pypi.python.org/pypi/setuptools#id1

-- 
 Ned Deily,
 nad at acm.org



From mensanator at aol.com  Wed Aug  5 19:16:10 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 16:16:10 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
	
	
Message-ID: <49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com>

On Aug 5, 5:31?pm, Mensanator  wrote:
> I fixed this to produce the actual image I'm looking
> for instead of that stupid black square. All I did was
> use up() & dowm() in place of penup(), pendown() and
> replace dot(2) with forward(1).
>
> I'll be posting a followup report later.
>

http://www.mensanator.com/mensanator/PythonTurtle/turtle.htm


From ethan at stoneleaf.us  Wed Aug  5 19:29:17 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Wed, 05 Aug 2009 16:29:17 -0700
Subject: Programming by Contract
Message-ID: <4A7A15CD.9090306@stoneleaf.us>

Greetings!

I have seen posts about the assert statement and PbC (or maybe it was 
DbC), and I just took a very brief look at pycontract 
(http://www.wayforward.net/pycontract/) and now I have at least one 
question:  Is this basically another way of thinking about unit testing, 
or is the idea of PbC more along the lines of *always* checking the 
input/output of functions to ensure they are correct?  (*Contstant 
vigilance!* as Prof Moody would say ;)

I know asserts can be turned off, so they obviously won't work for the 
latter case, and having seen the sample of pycontract it seems it only 
does its thing during debugging.

So is Design (Programming) by Contract a fancy way of saying "Document 
your inputs/outputs!" or is there more to it?

~Ethan~


From wolfgang at rohdewald.de  Wed Aug  5 19:48:36 2009
From: wolfgang at rohdewald.de (Wolfgang Rohdewald)
Date: Thu, 6 Aug 2009 01:48:36 +0200
Subject: using expy to extend python
In-Reply-To: <871540.68601.qm@web54204.mail.re2.yahoo.com>
References: <871540.68601.qm@web54204.mail.re2.yahoo.com>
Message-ID: <200908060148.36696.wolfgang@rohdewald.de>

On Thursday 06 August 2009, Yingjie Lan wrote:
> For more information about expy, please visit its homepage at:
> http://expy.sf.net/

looks very interesting, bookmarked.

In your example class mate, def rename looks wrong:
if malloc fails, the previous name should probably not
be replaced by an empty string?

-- 
Wolfgang


From macmanes at gmail.com  Wed Aug  5 19:54:46 2009
From: macmanes at gmail.com (PeroMHC)
Date: Wed, 5 Aug 2009 16:54:46 -0700 (PDT)
Subject: remove last 76 letters from string
Message-ID: 

Hi All, So here is the problem... I have a FASTA file (used for DNA
analyses) that looks like this:

...
>gnl|SRA|SRR019045.10.1 SL-XAY_956090708:2:1:0:1028.1 length=152
NCTTTTTTTATTTTTTGTATAAATGAAGTTTCACTATATCGGACGAGCGGTTCAGCAGTCATTCCGAGAC
CGATATAGTGAAACTTCATTTCTACAAAAANTACCAAACGTCGCTCGGCAGAGCGTCGTGTTGGGCAAGA
GAGTAGCACTCG
>gnl|SRA|SRR019045.11.1 SL-XAY_956090708:2:1:0:1151.1 length=152
NGGTNTGGNNNNCNCCNTNCTNCNNCNTCANCCTCCNGTCNCANNCCNCNTNNNNNCNNNNNCNNTNCTT
CTNCNNTCTCCATTCCTTCTTNATAGCCTGCTCCANCGCACGTTGAACCTTCTGCACCACGAACGCACTC
ACACCACTCATC
>gnl|SRA|SRR019045.12.1 SL-XAY_956090708:2:1:0:1197.1 length=152
NGTCGGGTCTTCGCTATCACTGGACTGCTCCCATCAGCTATAGGTCCTCCCCGCCACACCCCATGCCCAC
CGCCTATCCACGTCTGTCACAACCTCATACATCAGACAGTCACACTTACCAACATATCCAAGCACCTCAA
GCAACACATCAT
...

This snippet represents 3 individual DNA sequences. Each sequences is
identified by the line starting with >
The complete file has about 10 million individual sequences.

A simple enough problem, I want to read in this data, and cut out the
last 76 letters (nucleotides) from each individual sequence and send
them to a new txt file with a similar format.

Any help on how to do this would be appreciated.
Thanks!


From zuo at chopin.edu.pl  Wed Aug  5 20:23:06 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Thu, 06 Aug 2009 02:23:06 +0200
Subject: remove last 76 letters from string
In-Reply-To: 
References: 
Message-ID: 

Dnia 06-08-2009 o 01:54:46 PeroMHC  wrote:

> This snippet represents 3 individual DNA sequences. Each sequences is
> identified by the line starting with >
> The complete file has about 10 million individual sequences.
>
> A simple enough problem, I want to read in this data, and cut out the
> last 76 letters (nucleotides) from each individual sequence and send
> them to a new txt file with a similar format.

If I understand correctly you want sth like this:


with open(path_to_the_input_file) as fasta:
     with open(path_to_the_input_file) as nucleotides:
	for seq in fasta:
             print >>nucleotides, '> foo bar length=76'
             print >>nucleotides, seq[-76]


Cheers,
*j

-- 
Jan Kaliszewski (zuo) 


From zuo at chopin.edu.pl  Wed Aug  5 20:24:22 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Thu, 06 Aug 2009 02:24:22 +0200
Subject: remove last 76 letters from string [sorry, errata]
In-Reply-To: 
References: 
Message-ID: 

Dnia 06-08-2009 o 01:54:46 PeroMHC  wrote:

> This snippet represents 3 individual DNA sequences. Each sequences is
> identified by the line starting with >
> The complete file has about 10 million individual sequences.
>
> A simple enough problem, I want to read in this data, and cut out the
> last 76 letters (nucleotides) from each individual sequence and send
> them to a new txt file with a similar format.

If I understand correctly you want sth like this:


with open(path_to_the_input_file) as fasta:
       with open(path_to_the_output_file) as nucleotides:
	for seq in fasta:
               print >>nucleotides, '> foo bar length=76'
               print >>nucleotides, seq[-76]


Cheers,
*j

-- 
Jan Kaliszewski (zuo) 


From python at mrabarnett.plus.com  Wed Aug  5 20:26:22 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 01:26:22 +0100
Subject: String to valid Python identifier
In-Reply-To: 
References: 
Message-ID: <4A7A232E.1060402@mrabarnett.plus.com>

?????? ??????????? wrote:
> Is there any easy function in the stdlib to convert any random string in 
> a valid Python identifier .. possibly by replacing non-valid characters 
> with _ ?
> 
> Python 2.x only, so no need to do Unicode.
> 
Lookup the 'maketrans' function in the 'string' module and the
'translate' method of the 'str' class.


From python at mrabarnett.plus.com  Wed Aug  5 20:32:22 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 01:32:22 +0100
Subject: remove last 76 letters from string
In-Reply-To: 
References: 
Message-ID: <4A7A2496.4080808@mrabarnett.plus.com>

PeroMHC wrote:
> Hi All, So here is the problem... I have a FASTA file (used for DNA
> analyses) that looks like this:
> 
> ...
>> gnl|SRA|SRR019045.10.1 SL-XAY_956090708:2:1:0:1028.1 length=152
> NCTTTTTTTATTTTTTGTATAAATGAAGTTTCACTATATCGGACGAGCGGTTCAGCAGTCATTCCGAGAC
> CGATATAGTGAAACTTCATTTCTACAAAAANTACCAAACGTCGCTCGGCAGAGCGTCGTGTTGGGCAAGA
> GAGTAGCACTCG
>> gnl|SRA|SRR019045.11.1 SL-XAY_956090708:2:1:0:1151.1 length=152
> NGGTNTGGNNNNCNCCNTNCTNCNNCNTCANCCTCCNGTCNCANNCCNCNTNNNNNCNNNNNCNNTNCTT
> CTNCNNTCTCCATTCCTTCTTNATAGCCTGCTCCANCGCACGTTGAACCTTCTGCACCACGAACGCACTC
> ACACCACTCATC
>> gnl|SRA|SRR019045.12.1 SL-XAY_956090708:2:1:0:1197.1 length=152
> NGTCGGGTCTTCGCTATCACTGGACTGCTCCCATCAGCTATAGGTCCTCCCCGCCACACCCCATGCCCAC
> CGCCTATCCACGTCTGTCACAACCTCATACATCAGACAGTCACACTTACCAACATATCCAAGCACCTCAA
> GCAACACATCAT
> ...
> 
> This snippet represents 3 individual DNA sequences. Each sequences is
> identified by the line starting with >
> The complete file has about 10 million individual sequences.
> 
> A simple enough problem, I want to read in this data, and cut out the
> last 76 letters (nucleotides) from each individual sequence and send
> them to a new txt file with a similar format.
> 
> Any help on how to do this would be appreciated.
> Thanks!

If the input file is large then you can reduce the amount of memory
needed by reading the input file a line at a time by iterating over the
file object:

     input_file = open(input_path)
     for line in input_file:
         ...
     input_file.close()

Each line will end with '\n', so use the 'rstrip' method to remove it,
and then slice the last 76 characters:

     last_part = line.rstrip()[-76 : ]


From darkneter at gmail.com  Wed Aug  5 20:39:52 2009
From: darkneter at gmail.com (NighterNet)
Date: Wed, 5 Aug 2009 17:39:52 -0700 (PDT)
Subject: sqlite3 gui
Message-ID: <3d2c4f7a-9d9b-4aff-9de1-141ecf4327de@x6g2000prc.googlegroups.com>

This took a while to get a gui working. I am new at this coding.

This work with sqlite3 Python Version: 3.1.0. The older version
doesn't work.

#!/usr/local/bin/python
'''
    This is for basic database access to view the information.
Python version: 3.1.0

Features:
-view database.
-run script
-update row
-delete row
-insert row

To do list:
-delete table
-create table
-export database
-import database
-primary id need to able to insert to the table
-delete table row
-refresh data

Note:
-It doesn't remove the GUI
-It bit buggy.
-Python version: 3.0.1 -Doesn't support the gui

execute script without '"' ->  INSERT INTO member (user, password)
VALUES( "admin", "admin")
'''

from tkinter import *
from tkinter import ttk
from tkinter import tix
import sqlite3 as sqlite
import re

DATABASE = 'nameofdatabasefile.db'
title = "Sqlite3 Database";

db = sqlite.connect(DATABASE);
cur = db.cursor();

print("#==============================#")
print("# Python Version: 3.1.0        #")
print("# sqlite3                      #")
print("#==============================#")

class Application(Frame):
    #label_serverstatus = Label()
    table = []
    tablename = ''
    tablerowid = ''
    tablecolid = '0'
    tablerowname = ''
    tablevarinput = []
    tablevartext = []
    tableentrywidgetrow = []
    tablelabelwidgetrow = []

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master.grid_columnconfigure(0, weight=1)
        self.master.grid_rowconfigure(0, weight=1)
        self.master.title(title)
        self.listtable()#Make a list table
        self.createWidgets()
        self.master.geometry("800x600")
        self.pack()
    def listtable(self):
        self.table = []
        cur.execute("select * from sqlite_master WHERE type='table'");
        for t in cur:
            #print (t[1])
            self.table.append(t[1])

    #Create Widgets
    def createWidgets(self):
        #Schema
        self.Schemaframe = ttk.Labelframe(self, text='Schema',
width=600, height=100)
        self.Schemaframe.grid(column=1, row=1, sticky=W)
        self.text_database = Label(self.Schemaframe)
        self.text_database["text"] = "Schema Database:" + DATABASE
        self.text_database.grid(column=1, row=1, sticky=W)

        #Table
        self.tableframe = ttk.Labelframe(self, text='Schema Table',
width=600, height=100)
        self.tableframe.grid(column=1, row=2, sticky=W)
        self.text_table = Label(self.tableframe)
        self.text_table["text"] = "table:"
        self.text_table.grid(column=1, row=1, sticky=W)

        self.combobox = ttk.Combobox(self.tableframe)
        self.combobox.grid(column=2, row=1, sticky=W)
        self.combobox["values"] = self.table
        self.combobox.bind('<>', self.table_click)
        self.combobox.current(1)

        self.button_deletetable = Button(self.tableframe)
        self.button_deletetable["text"] = "Delete Table"
        self.button_deletetable.grid(column=3, row=1, sticky=W)

        self.button_createtable = Button(self.tableframe)
        self.button_createtable["text"] = "Create Table"
        self.button_createtable.grid(column=4, row=1, sticky=W)

        #Table
        self.scriptframe = ttk.Labelframe(self, text='Schema Script',
width=600, height=100)
        self.scriptframe.grid(column=1, row=3, sticky=W)

        self.button_script = Button(self.scriptframe)
        self.button_script["text"] = "Exeute script"
        self.button_script["command"] = self.executescript
        self.button_script.grid(column=1, row=1, sticky=W)

        self.button_commit = Button(self.scriptframe)
        self.button_commit["text"] = "Commit"
        self.button_commit["command"] = self.commit_save
        self.button_commit.grid(column=2, row=1, sticky=W)

        #TEXT BOX
        self.textbox = Text(self.scriptframe, width=40, height=10)
        self.textbox.grid(column=1, row=2, sticky=W,columnspan=6)

        #TABLE FRAME LIST
        self.tablerowframe = ttk.Labelframe(self, text='Table Rows',
width=600, height=100)
        self.tablerowframe.grid(column=2, row=1, sticky=W,rowspan=3)

        #TABLE ROW LIST
        self.listbox = Listbox(self.tablerowframe, exportselection=0,
background="white")
        self.listbox.bind("<>",self.listselect_click)
        self.listbox.grid(column=1, row=1, sticky=W)

        #vbar
        self.vbar = Scrollbar(self.tablerowframe, name="vbar")
        self.vbar.grid(column=1, row=1, sticky=E)
        self.vbar.configure(orient=VERTICAL,
command=self.listbox.yview)
        self.listbox.configure(yscrollcommand=self.vbar.set)

        self.button_createrow = Button(self.tablerowframe)
        self.button_createrow["text"] = "Create Table Row"
        self.button_createrow["command"] = self.commit_save
        self.button_createrow.grid(column=1, row=2, sticky=W)

        #TABLE FRAME ROW EDIT
        self.tablerowframe = ttk.Labelframe(self, text='Table Rows
EDIT', width=256, height=480)
        self.tablerowframe.grid(column=1, row=4, sticky=W)

    #SELECT TABLE FROM COMBOBOX
    def table_click(self,event):
        #print("click")
        self.tablename = str(self.combobox.selection_get())
        print(self.tablename)
        self.tableselected(self.tablename);
        return "break"

    #SHOW TABLE ROWS IN THE LIST BOX
    def tableselected(self,name):
        #print("TABLE SELECT ->" + str(name))
        cur.execute("select * from " + name);
        self.listbox.delete(0, "end")
        for t in cur:
            #print (t)
            #print (t[1])#table
            #spreadsheet.append(t[1])
            self.listbox.insert("end", str(t[0]))
        #self.listbox["listvariable"] = spreadsheet

    #CLICK TABLE ROW SELECTED ID OR ROW NAME
    def listselect_click(self,event):
        rowid = self.listbox.curselection()
        rowid = self.listbox.index(rowid)
        #print(self.listbox.get(rowid))
        self.tablerowid = rowid
        self.tablerowname = self.listbox.get(rowid)
        self.selecttablerow()
        return "break"

    #TABLE ROW INFORMATION
    def selecttablerow(self):
        #print ("TABLE ROW ->")
        self.tablevartext = []
        self.tablevarinput = []

        cur.execute("select * from sqlite_master WHERE type='table'");
        for t in cur:
            if self.tablename == t[1]:
                #print (t)
                tablestr = t[4].replace("CREATE TABLE "
+self.tablename + " ",'')
                tablestr = tablestr.replace("(","")
                tablestr = tablestr.replace(")","")
                comumndata = tablestr.split(',')

                for col in comumndata:
                    col = col.strip()
                    m = re.match(r"(^(\w+))",col)
                    #print (m.group(0))#column name of the table
current selected.
                    self.tablevartext.append(m.group(0))
                break

        query = str('SELECT * FROM ' + self.tablename + " WHERE id=\'"
+ self.tablerowname + "\'")
        #print(query)
        cur.execute(query);
        #table row out put
        for t in cur:
            #print (t)
            for vardata in t:
                #print(vardata)
                self.tablevarinput.append(vardata)
        self.deletetablerowinput
        self.createtablerowinput()

    def createtablerowinput(self):
        self.deletetablerowinput()
        rowcount = 0
        #self.button_destroy = Button(self.tablerowframe)
        #self.button_destroy["text"] = "delete rows"
        #self.button_destroy["command"] = self.deletetablerowinput
        #self.button_destroy.grid(column=1, row=1, sticky=W)

        self.button_deleterowtable = Button(self.tablerowframe)
        self.button_deleterowtable["text"] = "Delete Table Row"
        self.button_deleterowtable["command"] = self.deletetablerow
        self.button_deleterowtable.grid(column=1, row=1, sticky=W)

        self.button_updatetablerow = Button(self.tablerowframe)
        self.button_updatetablerow["text"] = "Update Table Row"
        self.button_updatetablerow["command"] = self.updatetablerow
        self.button_updatetablerow.grid(column=2, row=1, sticky=W)

        self.button_inserttablerow = Button(self.tablerowframe)
        self.button_inserttablerow["text"] = "Insert Table Row"
        self.button_inserttablerow["command"] = self.inserttablerow
        self.button_inserttablerow.grid(column=3, row=1, sticky=W)

        for columnname in self.tablevartext:
            #print(columnname)
            self.entry_tablevarrow = Entry(self.tablerowframe,
width=30, textvariable=columnname)
            self.entry_tablevarrow.delete(0,"end")
            self.entry_tablevarrow.insert(0,str(self.tablevarinput
[rowcount]))
            self.entry_tablevarrow.grid(column=2, row=rowcount+2,
sticky=W)
            self.tableentrywidgetrow.append(self.entry_tablevarrow)

            self.label_var = Label(self.tablerowframe, width=16)
            self.label_var['text'] = columnname
            self.label_var.grid(column=1, row=rowcount+2, sticky=W)
            self.tablelabelwidgetrow.append(self.label_var)
            #print(rowcount)
            rowcount += 1
    def updatetablerow(self):
        count = 0;
        #mysql_query("UPDATE  $db_table SET imageid='{$hashname}'
WHERE idhash='{$IDIMAGE}'")
        query = "UPDATE " + self.tablename
        set = " SET "
        where = "WHERE"
        for x in self.tableentrywidgetrow:
            if count == 0:
                where = where + " " + x["textvariable"] + "=\'" + x.get
() + "\' "
            else:
                if count == len(self.tableentrywidgetrow)-1:
                    set = set + "" + x["textvariable"] + "=\'" + x.get
() + "\' "
                else:
                    set = set + "" + x["textvariable"] + "=\'" + x.get
() + "\', "

            print ( x["textvariable"] + "->" +  x.get())
            count += 1
        print (query + set + where)
        querystring = query + set + where
        self.applydata(querystring)
        #print (len(self.tableentrywidgetrow))
    def deletetablerow(self):
        count = 0;
        query = "DELETE FROM " + self.tablename + " WHERE "
        delete = ""
        for x in self.tableentrywidgetrow:
            if count == len(self.tableentrywidgetrow)-1:
                delete = delete + "" + x["textvariable"] + "=\'" +
x.get() + "\' "
            else:
                delete = delete + "" + x["textvariable"] + "=\'" +
x.get() + "\' AND "
            count += 1
        print (query + delete)
        querystring = query + delete
        self.applydata(querystring)
        #print (len(self.tableentrywidgetrow))
    def inserttablerow(self):
        #cur.execute('INSERT INTO member (user, password) VALUES
( "admin", "admin")')
        count = 0;
        query = "INSERT INTO " + self.tablename + "("
        values = ""
        insert = ""
        #be sure it not the primary key else it will give error
        for x in self.tableentrywidgetrow:
            if count == len(self.tableentrywidgetrow)-1:
                values = values + x["textvariable"] + ''
                insert = insert + '\"' + x.get() + '\"'
            else:
                if count == 0:
                    print ("PRIMARY KEY")
                else:
                    values = values + x["textvariable"] + ','
                    insert = insert + '\"' + x.get() + '\",'

            count += 1

        querystring = query + values + ") VALUES(" + insert + ")"
        print (querystring)
        self.applydata(querystring)
        #print (len(self.tableentrywidgetrow))

    def deletetablerowinput(self):
        for x in self.tableentrywidgetrow:
            x.destroy()
        self.tableentrywidgetrow = []
        for y in self.tablelabelwidgetrow:
            x.destroy()
        self.tablelabelwidgetrow = []

    #SCRIPTS ++++++
    def executescript(self):
        print("Execute Script...")
        scripttext = self.textbox.get('1.0', 'end')
        self.applydata(scripttext)
        print(scripttext)
    #COMMIT +++++++
    def commit_save(self):
        print("Sqlite3 Commit")
        db.commit()
    def applydata(self,querystr):
        print("Sqlite3 Commit")
        db = sqlite.connect(DATABASE);
        cur = db.cursor()
        cur.execute(querystr)
        db.commit()

root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()

Not sure what you guys think about this. Still working on it. I can't
hard code this well. Still learning it. >.<


From lanyjie at yahoo.com  Wed Aug  5 20:40:18 2009
From: lanyjie at yahoo.com (Yingjie Lan)
Date: Wed, 5 Aug 2009 17:40:18 -0700 (PDT)
Subject: using expy to extend python
In-Reply-To: <200908060148.36696.wolfgang@rohdewald.de>
Message-ID: <870509.8482.qm@web54208.mail.re2.yahoo.com>


> From: Wolfgang Rohdewald 
> Subject: Re: using expy to extend python
> To: python-list at python.org
> Date: Thursday, August 6, 2009, 3:48 AM
> On Thursday 06 August 2009, Yingjie
> Lan wrote:
> > For more information about expy, please visit its
> homepage at:
> > http://expy.sf.net/
> 
> looks very interesting, bookmarked.
> 

Glad to hear that! Thanks.

> In your example class mate, def rename looks wrong:
> if malloc fails, the previous name should probably not
> be replaced by an empty string?
> 

Thanks for pointing that out. Probably should throw an exception if malloc fails. 

Yingjie


      


From gregor.lingl at aon.at  Wed Aug  5 20:49:44 2009
From: gregor.lingl at aon.at (Gregor Lingl)
Date: Thu, 06 Aug 2009 02:49:44 +0200
Subject: Turtle Graphics are incompatible with gmpy
In-Reply-To: <49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com>
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at>
	
	<4A79C7E2.3000406@aon.at>
	
	
	<49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com>
Message-ID: <4a7a28b3$0$2303$91cee783@newsreader01.highway.telekom.at>

Mensanator schrieb:
> On Aug 5, 5:31 pm, Mensanator  wrote:
>> I fixed this to produce the actual image I'm looking
>> for instead of that stupid black square. All I did was
>> use up() & dowm() in place of penup(), pendown() and
>> replace dot(2) with forward(1).
>>
>> I'll be posting a followup report later.
>>
> 
> http://www.mensanator.com/mensanator/PythonTurtle/turtle.htm

Hi Mansanator,

Thanks for that thorough investigations.
I hope I'll soon find time to study it in detail.

I've just one idea, but I don't know if you might
be intersted in it or if it's rewarding at all:

What would be the results when using the old turtle
module with Python 3.1 (it will certainly not run
out of the box, but perhaps 2to3 might do it?)

That would clarify the question if there is some
impact of new division or some changes in Tkinter.

Best regards,
Gregor


From gagsl-py2 at yahoo.com.ar  Wed Aug  5 20:54:07 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 05 Aug 2009 21:54:07 -0300
Subject: Datetime with float seconds
References: 
Message-ID: 

En Wed, 05 Aug 2009 09:50:04 -0300, kpal 
escribi?:

> The standard datetime has 1 microsecond granularity.

Note that this is the finest granularity a datetime object can store, NOT
the precision of datetime.now() by example.

> My application
> needs finer time resolution, preferably float seconds.

"float seconds" doesn't mean much. time.time returns float seconds, but
its precision is around 15ms on Windows.

> Is there an
> alternative to the out-of-the-box datetime? Timezone support is not
> essential.

On Windows, use time.clock(), which internally uses
QueryPerformanceCounter. The resolution depends on your hardware, but it's
typically better than 1 microsecond. If you want to know the actual value:

py> from ctypes import *
py> kernel32=windll.kernel32
py> QueryPerformanceCounter=kernel32.QueryPerformanceCounter
py> QueryPerformanceFrequency=kernel32.QueryPerformanceFrequency
py> plonglong = POINTER(c_longlong)
py> QueryPerformanceFrequency.argtypes = [plonglong]
py> freq = c_longlong()
py> QueryPerformanceFrequency(byref(freq))
1
py> freq
c_longlong(3579545L)

That is, on my system the resolution is 1/3579545s, or better than 300ns

-- 
Gabriel Genellina



From gagsl-py2 at yahoo.com.ar  Wed Aug  5 20:54:16 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 05 Aug 2009 21:54:16 -0300
Subject: Install setup tools for 2.6
References: <373cf0740908051131gacaf77apba48fa40e929f491@mail.gmail.com>
Message-ID: 

En Wed, 05 Aug 2009 15:31:38 -0300, Jeremy Cowles
 escribi?:

> Ok, I feel like this is a really stupid question, but how do you install
> setup tools for Python 2.6 under windows?
> The only format is .egg which requires setup tools to install, doesn't  
> it?

I have no idea, and I try to stay as far away from setuptools/ez_setup as
I can. I think they solve some kind of problems for some kind of people
(else the tool would be defunct by now), but haven't worked for me.
Perhaps you don't need setuptools either?

-- 
Gabriel Genellina



From mensanator at aol.com  Wed Aug  5 21:31:00 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 18:31:00 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
	
	 
	<49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com> 
	<4a7a28b3$0$2303$91cee783@newsreader01.highway.telekom.at>
Message-ID: 

On Aug 5, 7:49?pm, Gregor Lingl  wrote:
> Mensanator schrieb:
>
> > On Aug 5, 5:31 pm, Mensanator  wrote:
> >> I fixed this to produce the actual image I'm looking
> >> for instead of that stupid black square. All I did was
> >> use up() & dowm() in place of penup(), pendown() and
> >> replace dot(2) with forward(1).
>
> >> I'll be posting a followup report later.
>
> >http://www.mensanator.com/mensanator/PythonTurtle/turtle.htm
>
> Hi Mansanator,
>
> Thanks for that thorough investigations.
> I hope I'll soon find time to study it in detail.
>
> I've just one idea, but I don't know if you might
> be intersted in it or if it's rewarding at all:

Sure, not tonight, of course, but I can give it try.

>
> What would be the results when using the old turtle
> module with Python 3.1 (it will certainly not run
> out of the box, but perhaps 2to3 might do it?)

I would just need to copy turtle.py to 3.1 Lib (renamed,
of course)?

>
> That would clarify the question if there is some
> impact of new division or some changes in Tkinter.

I had a quick glance through the code. Not too many divisions
and most of them seemd to already be forcing float division
by constructs such as mutiplying by 1.0 (which I assume isn't
strictly neccessary as long as / and // are used correctly.

It seemed a lot of floats were used in the 2.5 code as I saw
such stuff as int(difference), so I really don't know why
.mpz would be a problem since they are integers also and a
Python int ought to be the same thing when coerced to a float
(at least in the range used by Turtle graphics.

>
> Best regards,
> Gregor



From sjmachin at lexicon.net  Wed Aug  5 21:31:56 2009
From: sjmachin at lexicon.net (John Machin)
Date: Thu, 6 Aug 2009 01:31:56 +0000 (UTC)
Subject: unicode() vs. s.decode()
References: 
	<1249487636.7120.798.camel@arrakis>
Message-ID: 

Jason Tackaberry  urandom.ca> writes:
> On Wed, 2009-08-05 at 16:43 +0200, Michael Str?der wrote:
> > These both expressions are equivalent but which is faster or should be used
> > for any reason?
> > u = unicode(s,'utf-8')
> > u = s.decode('utf-8') # looks nicer
> 
> It is sometimes non-obvious which constructs are faster than others in
> Python.  I also regularly have these questions, but it's pretty easy to
> run quick (albeit naive) benchmarks to see.
> 
> The first thing to try is to have a look at the bytecode for each:
[snip] 
> The presence of LOAD_ATTR in the first form hints that this is probably
> going to be slower.   Next, actually try it:
> 
>         >>> import timeit
>         >>> timeit.timeit('"foobarbaz".decode("utf-8")')
>         1.698289155960083
>         >>> timeit.timeit('unicode("foobarbaz", "utf-8")')
>         0.53305888175964355
> 
> So indeed, uncode(s, 'utf-8') is faster by a fair margin.

Faster by an enormous margin; attributing this to the cost of attribute lookup
seems implausible.

Suggested further avenues of investigation:

(1) Try the timing again with "cp1252" and "utf8" and "utf_8"

(2) grep "utf-8" /Objects/unicodeobject.c

HTH,
John



From digitalhillbilly at hotmail.com  Wed Aug  5 21:40:57 2009
From: digitalhillbilly at hotmail.com (DH)
Date: Wed, 5 Aug 2009 18:40:57 -0700 (PDT)
Subject: access read / write violation with ctypes
Message-ID: 

Hi all,

I'm quite new to cytpes and am having some troubles I was hoping I
could get a little help with. Before I get into the details this is
what I'm trying to accomplish - I would like to read a dng with python
pass it through either libraw.dll or dcraw.dll (notes on dcraw.dll
version at the end) for initial processing then to MagickWand for some
light enhancement and final jpeg output. After I get these working I
will see how I can add LittleCMS into the fray. I'm not doing
something correctly but don't know what. I've read a lot of documents
over the past couple days and though I've learned quite a lot I just
can't get past this access violation error.

I very grateful for anything that can be offered.

dh

...

I am currently working out MagickWand and dcraw separately but am
having similar troubles with both resulting in either 'Windows Error:
exception: access violation reading 0x00000000' or alternatively
'Windows Error: ... writing'

1 - MagickWand (read violation):

I'm using popen to capture dcraw stdout and want to pass it to
magickwand. If I instead write the dcraw output to a file then read it
with magickwand I get the same error. But if I comment out the dcraw
protion and read the dcraw output file from the previous attempt,
MagickWand opens the file fine and I can manipulate it to my hearts
content. The basics:

proc = subprocess.Popen("dcraw -c -4 -T image.dng", shell=True,
close_fds=False, stdout=subprocess.PIPE).communicate()[0]

magickWandLib = 'C:\\Program Files (x86)\\ImageMagick-6.5.3-Q16\
\CORE_RL_wand_.dll'
Magick = cdll.LoadLibrary(magickWandLib)

Magick.MagickWandGenesis()
wand = Magick.NewMagickWand()

Magick.MagickReadImageFile(proc)
-> access violation reading

2 - DCRaw (write violation):

I've been bouncing between libraw.dll and dcraw.dll. The dcraw version
I'm using is found at
http://translate.google.com/translate?hl=en&sl=es&tl=en&u=http://www.ojodigital.com/foro/perfectraw-perfectblend/206898-perfectraw-0-5-a.html
. Libraw is limited in the sence that it is mainly suited to loading
and unpacking raw images. Actual processing is done only in emulation
mode which I have not yet been able to access throught the library.
PerfectRaw uses a tweaked and librarised version of dcraw with thier
GUI + some enhanced functions. I'm only interesed in the dll though

2.1 - libraw.dll

I won't go into great detail as I can get it to work but only open,
unpack and write out a tiff or ppm. No process settings

2.2 - dcraw.dll

I can load the library but cannot initialise an instance. Each attempt
in a variety or methods always returns an 'access violation writing
0x00000000'. The parameters I use to initialise are taken from a test
program provided by the authors.

test app:
	int w,h;
	printf("Resultado de leer el RAW: %i\n",DCRAW_Init("c:\\test\
\IMG_4118.CR2",&w,&h)

python:
	dcraw_lib = 'C:\\programs\\PerfectRaw\\dcraw.dll'
	dcraw = ctypes.cdll.LoadLibrary(dcraw_lib)

	img = 'C:\\programs\\PerfectRaw\\image.dng'
	dcraw.DCRAW_Init(img,4000,3000) # canon G9 converted to dng
	-> access violation writing



From gforgx at lavabit.com  Wed Aug  5 21:51:52 2009
From: gforgx at lavabit.com (Sergey Simonenko)
Date: Wed, 05 Aug 2009 19:51:52 -0600
Subject: Subclassing Python's dict
Message-ID: 

Hi,

I subclass builtin 'dict' in my application and experience some problems  
with it.

The whole issue is that I should redefine 'setdefault' and 'update'  
methods after redefining '__setitem__' or/and '__delitem__',
otherwise 'update' and 'setdefault' ignore redefined '__setitem__' and use  
builtin dict's one so dict looks kinda like a black box.

Another guy have reported me that he experiences similar problems with  
subclassing builtin 'list'.

Kind regards, Sergey.

-- 
???????? ? ???????? ??????? ???????? Opera: http://www.opera.com/mail/



From cocobear.cn at gmail.com  Wed Aug  5 22:17:53 2009
From: cocobear.cn at gmail.com (cocobear)
Date: Wed, 5 Aug 2009 19:17:53 -0700 (PDT)
Subject: merge two png pic
References: 
	 
	
	<006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com>
	<4a77e249$0$2449$426a74cc@news.free.fr>
	<72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com>
	<4a793852$0$19598$426a74cc@news.free.fr>
Message-ID: <69579cfc-9151-43df-a5ef-a6b05f1bd718@13g2000prl.googlegroups.com>

On Aug 5, 3:44?pm, News123  wrote:
> You didn't really tell us why you need one big file, which contains more
> pixel, than you can probably store in RAM
>

In fact I do not need such a big image.
I just want to know the solution.


> Is it for printing?
> Not knwoing your goal makes it difficult to suggest solutions.
>
> Can't you use other image formats like raw RGB or
> What other image formats are supported?
> tiff? Raw? PPM (http://en.wikipedia.org/wiki/Portable_pixmap)?
>

I want to view image use Windows Pic View.

I don't familiar with PPM? photoshop don't support PPM, does PIL
support this format?


> concatenating raw/ppm files with the same width would be really trivial.
>
> so you could use python to create horizontal raw/ppm stripes.
>
> then you could concatenate them without having to have the whole image
> in RAM.
>
> Perhaps there's even converters from ppm to png, that don't need the
> whole image in RAM.
>
>
>
> cocobear wrote:
> > On Aug 4, 3:24 pm, News123  wrote:
> >> Hi,
>
> >> cocobear wrote:
> >>>>>>> Map = Image.new("RGB", (x,y))
> >>>>>>> Map.paste(im, box)
> >>>>>>> Map.paste(im1,box)
> >>>>>>> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE)
> >>>>>>> But if thetwopngpicis too big , or if I have tomergemorepic
> >>>>>>> together, I will get MemoryError:
> >>>>>>>>>>>>> Image.new("RGB",(44544,38656))
> >>>> What do you want to do with such a big image? You will run into the same
> >>>> limitation when you are trying to display it.
> >>> I want to download a map from google map with high precision
> >> For me it sounds strange to handle such big files.
>
> >> Is the map you download from Google really that big?
> >> Mostly Google maps uses normally tiles of sizes 256x256 pixel, wich you
> >> have to compose to get the ?big image.
>
> > The map I downloaded from Google is small(256x256). These small maps
> > will compose a big image.
>
> >> If your problem is to combine tiles with different palettes, then you
> >> should pobably look at a way to ?'unify' the palette of all tiles befor
> >> combining them.
>
> > I think it is impossible to 'unify' all this tiles.
>
> >> Being no expert of PIL I don't know whether this is easily possible though?
>
> >> bye
>
> >> N



From wuwei23 at gmail.com  Wed Aug  5 23:19:37 2009
From: wuwei23 at gmail.com (alex23)
Date: Wed, 5 Aug 2009 20:19:37 -0700 (PDT)
Subject: Subclassing Python's dict
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com> 
	
Message-ID: 

Xavier Ho wrote:
> You should subclass collections.UserDict, and not the default dict class.
> Refer to the collections module.

Xavier, why do you think that is the correct approach? The docs say
"The need for this class has been largely supplanted by the ability to
subclass directly from dict (a feature that became available starting
with Python version 2.2)."

If you mean that Sergey should subclass _in this instance_ could you
please explain why? (Sorry if you already have, I never saw your
original post...)




From rt8396 at gmail.com  Wed Aug  5 23:35:43 2009
From: rt8396 at gmail.com (r)
Date: Wed, 5 Aug 2009 20:35:43 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
Message-ID: <93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegroups.com>

On Aug 4, 12:55?am, David Lyon  wrote:
> It isn't totally about the writers...
> Peoples egos are also at stake - it seems.
> If "Fred X wrote Doc Y".. they don't want their name taken off.. So
> they generally speaking don't want the docs changed.
> If you talk too much about docs.. you can be told you're OT..
> even in a thread about docs...

This is the most honest post within this thread. Yes i believe --
although it does not make me happy-- that many within this community
are hostile, vulgar, and viscous towards any notion of change if it
comes from outside the "insiders" group (and even sometimes from the
inside). Which is very sad.

Yes sometimes people are just trolling, but this tread has nothing to
do with trolling. kj has a legitimate complaint. Do i believe the docs
are a complete waste of bytes, No! Many people have invested tons of
hard work into them (and i thank them for their hard work). But i do
believe --like all things in this word-- perfection is always just out
of hands reach, we must constantly seek perfection because we can
never attain it. Like any group effort, eventually it will adopt the
idioms of self indulgence. Python dev needs the input of those who are
not experts in the language --especially in the realm of docs.

It is so easy to forget the struggles we face when learning something
new. The accessibility and appeal of Python to new users is in the
best interest of this community. If you don't believe that, you are
pissing on all the years of hard work that has been put in here. You
might as well just tell Guido to "close up shop"

I have posted this once before but i will post it again. Please read
Christopher's words carefully because they apply to this community in
a big way...Don't fall into the trap of narcissism.

Christopher Lasch referring to the pitfalls of Narcissistic societies:

"""In such a society of constant competition, there can be no allies,
and little transparency. The threats to
acquisitions of social symbols are so numerous, varied and frequently
incomprehensible, that defensiveness, as well as competitiveness,
becomes a way of life. Any real sense of community is undermined -- or
even destroyed -- to be replaced by virtual equivalents that strive,
unsuccessfully, to synthesize a sense of community."""

While I agree that some narcissism is vital to an individuals ego in
competitive atmospheres, I do not believe the Python community
warrants this need.


From rays at blue-cove.com  Thu Aug  6 00:21:13 2009
From: rays at blue-cove.com (RayS)
Date: Wed, 05 Aug 2009 21:21:13 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com>
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
Message-ID: <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>

An HTML attachment was scrubbed...
URL: 

From davea at ieee.org  Thu Aug  6 00:51:19 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 00:51:19 -0400
Subject: Error on Attaching to the process while debugging
In-Reply-To: <21dbc649-2f82-4e4c-9777-c8a58c25a9e0@r2g2000yqm.googlegroups.com>
References: <21dbc649-2f82-4e4c-9777-c8a58c25a9e0@r2g2000yqm.googlegroups.com>
Message-ID: <4A7A6147.5030901@ieee.org>


MalC0de wrote:
> Hello there, I'm writting a debugger,
> the problem is there no good interpretation ...
>
> here's the codes:
>
> my_debugger.py :
>
> #!/usr/bin/env python
> from ctypes import *
> from my_debugger_defines import *
> kernel32 = windll.kernel32
> class debugger():
>     def __init__(self):
> 	  self.h_process = None
> 	  self.pid = None
> 	  self.debugger_active = False
>           pass
>     def load(self,path_to_exe):
>         creation_flags = DEBUG_PROCESS
>         startupinfo = STARTUPINFO()
>         process_information = PROCESSINFORMATION()
>         startupinfo.dwFlags = 0x1
>         startupinfo.wShowWindow = 0x0
>         startupinfo.cb = sizeof(startupinfo)
>         if kernel32.CreateProcessA(path_to_exe,
>                                     None,
>                                     None,
>                                     None,
>                                     None,
>                                     creation_flags,
>                                     None,
>                                     None,
>                                     byref(startupinfo),
>                                     byref(process_information)):
>                   print "[*]we have sucessfully launched the process"
>                   print "[*]PID %d" % process_information.dwProcessId
>                   self.h_process = self.open_process
> (process_information.dwProcessId)
>         else:
>             print"[*]Error 0x%08x." % kernel32.GetLastError()
>
> def Open_process(self,pid):
>     h_process = kernel32.OpenProcess(PROCESS_ALL_ACCESS,pid,False)
>     return h_process
> def attach(self,pid):
>         self.h_process = self.open_process(pid)
>         # We attempt to attach to the process
>         # if this fails we exit the call
>         if kernel32.DebugActiveProcess(pid):
>             self.debugger_active = True
>             self.pid             = int(pid)
>
>         else:
>             print "[*] Unable to attach to the process."
>
> def run(self):
>     while self.debugger_active == True:
>         self.get_debug_event()
> def get_debug_event(self):
>     debug_event = DEBUG_EVENT()
>     continue_status = DBG_CONTINUE
>     if kernel32.WaitForDebugEvent(byref(debug_event),INFINITE):
>         raw_input("Press a key to continue ...")
>     self.debugger_active = False
>     kernel32.ContinueDebugEvent
> (debug_event.dwProdcessid,debug_event.dwThreadId,continue_status)
>     def detach(self):
>         if kernel32.DeugActiveProcessStop(self.pid):
>             print "[*]Finished debugging. exiting ..."
>             return True
>         else:
>             print "there was an error"
>             return false
>
> it's already have a method named : Attach ...
> 
>   
Indentation is critical.  You have defined functions ( Open_process() 
attach(), run(), etc. ) that have formal parameters named self, but are 
indented outside of the class definition.  Indentation trumps, so these 
are not attributes of the class.  They're functions, not methods.

It looks like you have other indentation problems, but I'll let you run 
with this much.

Incidentally, following naming conventions could also help here.  
debugger is a class, but it's not capitalized.  Open_process() is 
intended to be a method, but it is capitalized.  And your comments refer 
to attach() as Attach...  Another convention you're breaking is using    
"from ctypes import * "   That's a dangerous way to do imports, as it 
mixes those names with the ones in this module.  I prefer a simple 
import, and use the module name as a prefix when you reference those 
symbols.  If there are a few symbols you do want to have directly 
included, then import them one at a time, without the * notation.  (just 
my opinion)

DaveA



From gagsl-py2 at yahoo.com.ar  Thu Aug  6 01:19:24 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 02:19:24 -0300
Subject: Two Dimensional Array + ctypes
References: <79d2b3e3-b049-4d70-a56b-6e7f3ea2fa86@e27g2000yqm.googlegroups.com>
Message-ID: 

En Wed, 05 Aug 2009 20:12:09 -0300, Sparky  escribi?:

> Hello! I am trying to call this method:
>
> long _stdcall AIBurst(long *idnum, [...]
> 			 long timeout,
> 			 float (*voltages)[4],
> 			 long *stateIOout,
> 			 long *overVoltage,
> 			 long transferMode);
>
> I am having some problems with that  float (*voltages)[4].

>         pointerArray = (ctypes.c_void_p * 4)
>         voltages = pointerArray(ctypes.cast(ctypes.pointer
> ((ctypes.c_long * 4096)()), ctypes.c_void_p), ctypes.cast
> (ctypes.pointer((ctypes.c_long * 4096)()), ctypes.c_void_p),
> ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)()),
> ctypes.c_void_p), ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)

Why c_long and not c_float?
Anyway, this way looks much more clear to me (and doesn't require a cast):

arr4096_type = ctypes.c_float * 4096
voltages_type = arr4096_type * 4
voltages = voltages_type()

> The program runs but the values that come back in the array are not
> right.

Thay might be due to the long/float confusion.

-- 
Gabriel Genellina



From davea at ieee.org  Thu Aug  6 01:25:48 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 01:25:48 -0400
Subject: Web page data and urllib2.urlopen
In-Reply-To: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
Message-ID: <4A7A695C.4010403@ieee.org>

Massi wrote:
> Hi everyone, I'm using the urllib2 library to get the html source code
> of web pages. In general it works great, but I'm having to do with a
> financial web site which does not provide the souce code I expect. As
> a matter of fact if you try:
>
> import urllib2
> res = urllib2.urlopen("http://www.marketwatch.com/story/mondays-
> biggest-gaining-and-declining-stocks-2009-07-27")
> page = res.read()
> print page
>
> you will see that the printed code is very different from the one
> given, for example, by mozilla. Since I have really little knowledge
> in html I can't even understand if this is a python or html problem.
> Can anyone give me some help?
> Thanks in advance.
>
>   
I don't think this is a Python issue, but a "raw read" versus an 
interactive interpretation of a page.  The browser does lots more than a 
single roundtrip defined by urlopen/read.

I also would love to see some explanation of what happens here, or a 
pointer to a reference that would help me understand it.

I took the output of the read(), and formatted it, roughly, as html.  I 
expected to find a refresh, which is the simplest way that one page can 
cause a very different one to be loaded.
      

If Mozilla had seen a page with this line in an appropriate place, it'd 
immediately begin loading the other page, at "someotherurl"  But there's 
no such line.

Next, I looked for javascript.  The Mozilla page contains lots of 
javascript, but there's none in the raw page.  So I can't explain 
Mozilla's differences that way.

I did notice the link to /m/Content/mobile2.css, but I don' t know any 
way a CSS file could cause the content to change, just the display.

All I can guess is that it has something to do with "browser type" or 
cookies.  And that would make lots of sense if this was a cgi page.  But 
the URL doesn't look like that, as it doesn't end in pl, py, asp, or any 
of another dozen special suffixes.

Any hints, anybody???

DaveA



From MatzeGuentert at gmx.de  Thu Aug  6 01:26:31 2009
From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=)
Date: Thu, 06 Aug 2009 07:26:31 +0200
Subject: M2Crypto: How to generate subjectKeyIdentifier /
	authorityKeyIdentifier
In-Reply-To: 
References: 
	
Message-ID: <1249536391.3348.35.camel@celsius>

> M2Crypto has a couple of bugs open related that, with potential
> workarounds that I haven't yet deemed polished enough to checkin, but
> which might help you out:
> 
> https://bugzilla.osafoundation.org/show_bug.cgi?id=7530
> https://bugzilla.osafoundation.org/show_bug.cgi?id=12151

Thanks, that helped me a lot. Generating the 'subjectKeyIdentifier' now
works for me using the following procedure:

----------------------------------------------------------
import hashlib 

def get_public_key_fingerprint(self):
	h = hashlib.new('sha1')
    	h.update(self.keypair.as_der())
    	client_serial = h.hexdigest().upper()
    	client_serial_hex = ''
    	
    	for byte in xrange(20):
    	 client_serial_hex += client_serial[byte*2] + client_serial[byte*2
+1]
    		if byte < 19:
    			client_serial_hex += ':'
    
        return client_serial_hex 

[...]
cert_extension_4 = X509.new_extension("subjectKeyIdentifier",
keys_ca.get_public_key_fingerprint()) 
----------------------------------------------------------

However I don't understand the way the hash gets build. Comparing the
output from a given keypair and certificate build via OpenVPNs easy-rsa
scripts shows different subjectKeyIdentifiers. As stated out by rfc5280
there is no right or wrong way in creating the unique hash, so this
should be fine. 

But setting the 'authorityKeyIdentifier' extension gives me some
headache here. The following code snippet produces a segmentation fault
on my python interpreter (version 2.6)  

----------------------------------------------------------
cert_extension = X509.new_extension("authorityKeyIdentifier",
keys_ca.get_public_key_fingerprint())

cert_extension_stack.push(cert_extension)
----------------------------------------------------------

Same on this:
----------------------------------------------------------
cert_extension = 

X509.new_extension("authorityKeyIdentifier",
"keyid:1C:88:E1:8E:F1:5F:9D:1C:2B:6C:41:D4:3D:BB:79:0D:33:4A:E3:9A,
DirName:/C=US/ST=CA/L=SanFrancisco/O=Fort-Funston/CN=Fort-Funston
CA/emailAddress=me at myhost.mydomain, serial:B1:82:B1:E4:23:78:F1:12")

cert_extension_stack.push(cert_extension)
----------------------------------------------------------

So the question is: Is there another workaround to set this extension?
How can I provide more information to get this fixed? Working with the
latest SVN version is no option for me at the moment. 

Thanks in advance,
Matthias 




From gagsl-py2 at yahoo.com.ar  Thu Aug  6 01:30:58 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 02:30:58 -0300
Subject: os.system in a service
References: 
Message-ID: 

En Wed, 05 Aug 2009 13:07:39 -0300, Lawrence Wong  
 escribi?:

> I wrote a program which runs a .bat file using os.system like:  
> 'os.system(pathToBatFile)' and everything was good.  Then I decided to  
> turn my program into a service as opposed to being run with the command  
> prompt showing.  When my program became a service, I noticed that the  
> os.system command to run my .bat file was no longer working.  By 'not  
> working' I mean no exception is thrown, but it was as if the line with  
> os.system(pathToBatFile) did not exist.  I was wondering why this is and  
> if there is a way to fix this or what an alternative to using os.system  
> to run my .bat file was?

Capture stdout and stderr and you'll probably see the error message:

some_command >logfile.txt 2>&1

-- 
Gabriel Genellina



From pfeldman at verizon.net  Thu Aug  6 01:42:26 2009
From: pfeldman at verizon.net (Dr. Phillip M. Feldman)
Date: Wed, 5 Aug 2009 22:42:26 -0700 (PDT)
Subject: How to comment on a Python PEP?
Message-ID: <24840417.post@talk.nabble.com>


Is there a mechanism for submitting comments on a Python PEP?
-- 
View this message in context: http://www.nabble.com/How-to-comment-on-a-Python-PEP--tp24840417p24840417.html
Sent from the Python - python-list mailing list archive at Nabble.com.



From mlm2winnet at gmail.com  Thu Aug  6 01:49:42 2009
From: mlm2winnet at gmail.com (Chris Harris)
Date: Wed, 5 Aug 2009 22:49:42 -0700 (PDT)
Subject: Hi everyone
Message-ID: <150d41dd-018a-48a0-8dda-43e7832d6434@r38g2000yqn.googlegroups.com>

I'm happy to be a part of this group, i'd liek to say hi and invite
everyone to join my group =D Have a great night i look forward to
being an active member of this group

http://groups.google.com/group/mlm-2-win


From gagsl-py2 at yahoo.com.ar  Thu Aug  6 01:50:01 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 02:50:01 -0300
Subject: Parsing Binary Structures; Is there a better way / What is your
	way?
References: 
Message-ID: 

En Wed, 05 Aug 2009 11:46:13 -0300, Martin P. Hellwig  
 escribi?:

> On several occasions I have needed (and build) a parser that reads a  
> binary piece of data with custom structure. For example (bogus one):
>
> BE
> +---------+---------+-------------+-------------+------+--------+
> | Version | Command | Instruction | Data Length | Data | Filler |
> +---------+---------+-------------+-------------+------+--------+
> Version: 6 bits
> Command: 4 bits
> Instruction: 5 bits
> Data Length: 5 bits
> Data: 0-31 bits
> Filler: filling 0 bits to make the packet dividable by 8

> - Using a string for binary representation takes at least 8 times more  
> memory for the packet than strictly necessary.

The size difference isn't so big; an integer takes 12 bytes and a string  
takes 24+len bytes. "Data" above would take 56 bytes max when stored as a  
string '0110001...' vs. 12 bytes when using a plain integer (sizes  
computed on Windows 32bits). Plus, doing bitwise operations in Python  
isn't a fast operation as it is in C, by example -- so your current  
implementation might be a quite good one (in pure Python, I mean).

-- 
Gabriel Genellina



From davea at ieee.org  Thu Aug  6 02:30:47 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 02:30:47 -0400
Subject: access read / write violation with ctypes
In-Reply-To: 
References: 
Message-ID: <4A7A7897.1030207@ieee.org>

DH wrote:
> 
>
> I'm using popen to capture dcraw stdout and want to pass it to
> magickwand. If I instead write the dcraw output to a file then read it
> with magickwand I get the same error. But if I comment out the dcraw
> protion and read the dcraw output file from the previous attempt,
> MagickWand opens the file fine and I can manipulate it to my hearts
> content. The basics:
>
> 
>   
Just a quick guess, based only on this paragraph.  But I'd guess the 
dcraw output file is buffered, and is not fully written when you're 
trying to read it back.

You could do some checking by comparing sizes, when you get it from the 
pipe, and when you see it finally written in the directory.

DaveA


From hendrik at microcorp.co.za  Thu Aug  6 02:43:58 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Thu, 6 Aug 2009 08:43:58 +0200
Subject: Datetime with float seconds
In-Reply-To: 
References: 
Message-ID: <200908060843.58925.hendrik@microcorp.co.za>

On Wednesday 05 August 2009 14:50:04 kpal wrote:
> Hello Everybody,
>
> The standard datetime has 1 microsecond granularity. My application
> needs finer time resolution, preferably float seconds. Is there an
> alternative to the out-of-the-box datetime? Timezone support is not
> essential.

I am curious as to what would require less than microsecond
timing - about the only thing I can think of would be something
involving measuring the speed of light, where nanoseconds
or better would be nice.

- Hendrik



From davea at ieee.org  Thu Aug  6 02:45:01 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 02:45:01 -0400
Subject: Parsing Binary Structures;	Is there a better way / What is
	your way?
In-Reply-To: <7xr5vqw0v9.fsf@ruckus.brouhaha.com>
References: 	<7x3a86gmfe.fsf@ruckus.brouhaha.com>	
	<7xr5vqw0v9.fsf@ruckus.brouhaha.com>
Message-ID: <4A7A7BED.4030105@ieee.org>

Paul Rubin wrote:
> "Martin P. Hellwig"  writes:
>   
>> Is there an advantage using shifts and masks over my kitchen type solution?
>>     
>
> Weren't you complaining about the 8-to-1 expansion from turning each bit
> to an ascii char?
>
>   
One warning to Martin:

If you want your code portable across systems, watch out for 
big-endian/little-endian  issues, as well as alignment ones.  Shift & 
mask code tends to be highly specific to a particular endian-ness, 
especially if trying to get multiple bits that cross a byte or word 
boundary.

Over the years, I know I've seen at least three endian versions for the 
same 32bit word.  Something like abcd, dcba, and cdab.

One advantage of converting first to bitstrings, is that there's just 
the two places to fix, for portability, the conversion from byte array 
to bitstring, and the conversion back.

DaveA



From deets at nospam.web.de  Thu Aug  6 02:59:13 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Thu, 06 Aug 2009 08:59:13 +0200
Subject: os.system in a service
In-Reply-To: 
References: 
	
Message-ID: <7dvda1F2c4s7kU1@mid.uni-berlin.de>

Gabriel Genellina schrieb:
> En Wed, 05 Aug 2009 13:07:39 -0300, Lawrence Wong 
>  escribi?:
> 
>> I wrote a program which runs a .bat file using os.system like: 
>> 'os.system(pathToBatFile)' and everything was good.  Then I decided to 
>> turn my program into a service as opposed to being run with the 
>> command prompt showing.  When my program became a service, I noticed 
>> that the os.system command to run my .bat file was no longer working.  
>> By 'not working' I mean no exception is thrown, but it was as if the 
>> line with os.system(pathToBatFile) did not exist.  I was wondering why 
>> this is and if there is a way to fix this or what an alternative to 
>> using os.system to run my .bat file was?
> 
> Capture stdout and stderr and you'll probably see the error message:
> 
> some_command >logfile.txt 2>&1

Which isn't possible as a service.

The OP might consider using suprocess istead of os.system, and establish 
pipes to read the output of the command into a file he can analyze.

Diez


From hendrik at microcorp.co.za  Thu Aug  6 03:39:33 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Thu, 6 Aug 2009 09:39:33 +0200
Subject: Parsing Binary Structures;
	Is there a better way / What is your way?
In-Reply-To: 
References: 
Message-ID: <200908060939.33365.hendrik@microcorp.co.za>

On Wednesday 05 August 2009 16:46:13 Martin P. Hellwig wrote:
> Hi List,
>
> On several occasions I have needed (and build) a parser that reads a
> binary piece of data with custom structure. For example (bogus one):
>
> BE
> +---------+---------+-------------+-------------+------+--------+
>
> | Version | Command | Instruction | Data Length | Data | Filler |
>
> +---------+---------+-------------+-------------+------+--------+
> Version: 6 bits
> Command: 4 bits
> Instruction: 5 bits
> Data Length: 5 bits
> Data: 0-31 bits
> Filler: filling 0 bits to make the packet dividable by 8
>
> what I usually do is read the packet in binary mode, convert the output
> to a concatenated 'binary string'(i.e. '0101011000110') and then use
> slice indeces to get the right data portions.
> Depending on what I need to do with these portions I convert them to
> whatever is handy (usually an integer).

This bit banging stuff is a PITA, no matter what you do.
Python does not have bit fields like C.
And C bit fields are implementation dependent.
Write an extension?

Some time ago I asked a similar question, and
Castironpi came up with what was essentially an
indexed integer, with named bits.

It stores the bits natively, but I suspect that the
price paid is access time.

I enclose a module that you can adapt.
It talks about bytes but they are integers really.
It is different from what you are doing, as it
was aimed at reading and writing bits in 
a hardware context.

If you get your head around the concept,
then it may give you some ideas.  It should
be possible to extend the concept to
pass name,length tuples at construction time
instead of just a name with an implied length 
of one bit, and it may make sense to change
the underlying type from an integer to an 
array of one byte integers.

It is nice to be able to say:
val = bitname() 
to read, and 
bitname(1)
or
bitname(0)
to write.

I can also write:
outputbits[3] = 1
or
val = inputbits[5]

If you can successfully generalise it
to field names It should be very useful.

I cannot think of a way though, to not
have the "in" and "out" split, but you can
program your way around that - you do not
have to update "in place".

- Hendrik

-------------- next part --------------
A non-text attachment was scrubbed...
Name: bits.py
Type: application/x-python
Size: 4379 bytes
Desc: not available
URL: 

From kpalamartchouk at gmail.com  Thu Aug  6 03:46:58 2009
From: kpalamartchouk at gmail.com (kpal)
Date: Thu, 6 Aug 2009 00:46:58 -0700 (PDT)
Subject: Datetime with float seconds
References: 
	
Message-ID: <0819ae46-767f-4256-81d9-f265b7552cd8@h31g2000yqd.googlegroups.com>

On Aug 6, 7:43?am, Hendrik van Rooyen  wrote:

> I am curious as to what would require less than microsecond
> timing - about the only thing I can think of would be something
> involving measuring the speed of light, where nanoseconds
> or better would be nice.

You are right :-) I am trying to write a scientific software that does
some satellite geodesy computations (involving the speed of light),
and I would prefer to keep all the times float, while retaining the
time and time interval arithmetics and format transformation
capabilities of datetime. The system time granularity, that is of
cause limited, is not a problem at all, as the data are to be
initialized by constructing instances from external data.

Thanks


From hendrik at microcorp.co.za  Thu Aug  6 03:58:30 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Thu, 6 Aug 2009 09:58:30 +0200
Subject: Parsing Binary Structures;
	Is there a better way / What is your way?
In-Reply-To: <7x3a86gmfe.fsf@ruckus.brouhaha.com>
References: 
	<7x3a86gmfe.fsf@ruckus.brouhaha.com>
Message-ID: <200908060958.30882.hendrik@microcorp.co.za>

On Wednesday 05 August 2009 20:12:05 Paul Rubin wrote:
> "Martin P. Hellwig"  writes:
> > what I usually do is read the packet in binary mode, convert the
> > output to a concatenated 'binary string'(i.e. '0101011000110') and
>
> Something wrong with reading the data words as an integer and using
> old fashioned shifts and masks to get at the bit fields?

There is nothing wrong with that, and in the final analysis, it is what
is used - however, I can sympathize with the OP, as it is much nicer
to just call a named thing than to juggle a bunch of hard coded
shifts and masks.

I think the real point here is sort of meta programming - what
is needed is a way to describe and name the elements of the
structure so that useful python objects are created.

The code I posted for bits does that, and I use it all the
time - it is almost as good as being back in 8031 assembler
with direct named bit access.

- Hendrik


From contact at xavierho.com  Thu Aug  6 04:05:52 2009
From: contact at xavierho.com (Xavier Ho)
Date: Thu, 6 Aug 2009 18:05:52 +1000
Subject: merge two png pic
In-Reply-To: <69579cfc-9151-43df-a5ef-a6b05f1bd718@13g2000prl.googlegroups.com>
References: 
	
	
	<006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com>
	<4a77e249$0$2449$426a74cc@news.free.fr>
	<72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com>
	<4a793852$0$19598$426a74cc@news.free.fr>
	<69579cfc-9151-43df-a5ef-a6b05f1bd718@13g2000prl.googlegroups.com>
Message-ID: <2d56febf0908060105p1604f02u57128d23172b3d67@mail.gmail.com>

On Thu, Aug 6, 2009 at 12:17 PM, cocobear  wrote:

>
> I want to view image use Windows Pic View.
>
> If you run out of memory trying to combining those images into a 30k by 40k
pixels image, the Windows Pic View isn't going to be able to display it
either.

Regards,

Ching-Yun "Xavier" Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: contact at xavierho.com
Website: http://xavierho.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From hendrik at microcorp.co.za  Thu Aug  6 04:06:04 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Thu, 6 Aug 2009 10:06:04 +0200
Subject: Parsing Binary Structures;
	Is there a better way / What is your way?
In-Reply-To: 
References: 
	<7xr5vqw0v9.fsf@ruckus.brouhaha.com>
	
Message-ID: <200908061006.04437.hendrik@microcorp.co.za>

On Wednesday 05 August 2009 21:41:26 Martin P. Hellwig wrote:

> Yes you are (of course) right, my 'dream' solution would be something
> that accepts slice indeces on bit level. Your reasoning did reveal some
> flaws in my approach though ;-)

This is the first time I have been compared to the sandman...

:-)

- Hendrik



From martin at v.loewis.de  Thu Aug  6 04:24:08 2009
From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=)
Date: Thu, 06 Aug 2009 10:24:08 +0200
Subject: String to valid Python identifier
In-Reply-To: 
References: 
Message-ID: <4a7a9328$0$2355$9b622d9e@news.freenet.de>

> Is there any easy function in the stdlib to convert any random string in 
> a valid Python identifier .. possibly by replacing non-valid characters 
> with _ ?

I think this is fairly underspecified as a problem statement. A solution
that would meet your specification would be

def mkident(s):
    return "foo"

It returns a valid Python identifier for any random string.

If you now complain that this gives too many collisions, I propose

def mkident(s):
    return "foo%d" % (hash(s) & 0x7fffffff)

Regards,
Martin


From contact at xavierho.com  Thu Aug  6 04:26:22 2009
From: contact at xavierho.com (Xavier Ho)
Date: Thu, 6 Aug 2009 18:26:22 +1000
Subject: Subclassing Python's dict
In-Reply-To: 
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com>
	
	
Message-ID: <2d56febf0908060126i323d499fla4b7a22c934c5e7@mail.gmail.com>

On Thu, Aug 6, 2009 at 1:19 PM, alex23  wrote:

> Xavier Ho wrote:
> > You should subclass collections.UserDict, and not the default dict class.
> > Refer to the collections module.
>
> Xavier, why do you think that is the correct approach?


I'll be honest first and say that I do not completely understand how dict is
implemented in the underlying C structure. But as Bruno had already
mentioned, dict has a slightly different behaviour then we'd expect. For
example, the __getitem__() function isn't actually used by the interpreter
(which, you know, *can* be a problem.)

http://www.python.org/download/releases/2.2.3/descrintro/#subclassing
(I don't know if 2.6.2 changed anything since 2.2.3, but there are some
references you can look at, and sample code.)

To answer your question, it's really not "the correct approach", but I think
(meaning: untested) UserDict doesn't have the same implementation, which
might free up some restrictions Sergey encountered.

The docs say
> "The need for this class has been largely supplanted by the ability to
> subclass directly from dict (a feature that became available starting
> with Python version 2.2)."


I didn't realise they took UserDict out in later versions (2.6, for
example), and put it back in Python 3.0. Does anyone know why?

So, I do not actually know.

> If you mean that Sergey should subclass _in this instance_ could you
> please explain why? (Sorry if you already have, I never saw your
> original post...)
>

It was really more or less an educated guess. He didn't tell us what he is
trying to achieve, so _in this instance_ I can't give more advice than
saying "well, if this doesn't work, here are you other options that I know
of/just found. Try these and let us know if you got it to work." *winks*

-

Sometimes I do answer a little too quickly, I apologise for that.

- Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From iainking at gmail.com  Thu Aug  6 04:28:29 2009
From: iainking at gmail.com (Iain King)
Date: Thu, 6 Aug 2009 01:28:29 -0700 (PDT)
Subject: remove last 76 letters from string
References: 
	
Message-ID: 

>      print >>nucleotides, seq[-76]

> ? ? ?last_part = line.rstrip()[-76 : ]

You all mean:   seq[:-76]   , right? (assuming you've already stripped
any junk off the end of the string)

Iain


From gagsl-py2 at yahoo.com.ar  Thu Aug  6 04:35:57 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 05:35:57 -0300
Subject: os.system in a service
References: 
	
	<7dvda1F2c4s7kU1@mid.uni-berlin.de>
Message-ID: 

En Thu, 06 Aug 2009 03:59:13 -0300, Diez B. Roggisch   
escribi?:
> Gabriel Genellina schrieb:
>> En Wed, 05 Aug 2009 13:07:39 -0300, Lawrence Wong  
>>  escribi?:

>>> I wrote a program which runs a .bat file using os.system like:  
>>> 'os.system(pathToBatFile)' and everything was good.  Then I decided to  
>>> turn my program into a service as opposed to being run with the  
>>> command prompt showing.  When my program became a service, I noticed  
>>> that the os.system command to run my .bat file was no longer working.  
>>> [...]

>>  Capture stdout and stderr and you'll probably see the error message:
>>  some_command >logfile.txt 2>&1
>
> Which isn't possible as a service.

Why you say so? One should avoid using mapped drive letters and network  
shares -- that probably aren't defined for the account under which the  
service runs. And always use absolute paths. And ensure the account has  
write permissions for the output file... But other than that, os.system  
should work fine. Do I miss something?

> The OP might consider using suprocess istead of os.system, and establish  
> pipes to read the output of the command into a file he can analyze.

That's a good idea, although overkill for simple cases I'd say.

-- 
Gabriel Genellina



From martin at v.loewis.de  Thu Aug  6 04:42:33 2009
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Thu, 06 Aug 2009 10:42:33 +0200
Subject: How to comment on a Python PEP?
In-Reply-To: 
References: 
Message-ID: <4a7a9779$0$2384$9b622d9e@news.freenet.de>

> Is there a mechanism for submitting comments on a Python PEP?

You post to python-dev or comp.lang.python, and you CC the author.

Regards,
Martin


From dr.scottgriffiths at gmail.com  Thu Aug  6 04:44:19 2009
From: dr.scottgriffiths at gmail.com (sgriffiths)
Date: Thu, 6 Aug 2009 01:44:19 -0700 (PDT)
Subject: Parsing Binary Structures; Is there a better way / What is your 
	way?
References: 
Message-ID: 

On Aug 5, 3:46?pm, "Martin P. Hellwig" 
wrote:
> Hi List,
>
> On several occasions I have needed (and build) a parser that reads a
> binary piece of data with custom structure. For example (bogus one):
>
> BE
> +---------+---------+-------------+-------------+------+--------+
> | Version | Command | Instruction | Data Length | Data | Filler |
> +---------+---------+-------------+-------------+------+--------+
> Version: 6 bits
> Command: 4 bits
> Instruction: 5 bits
> Data Length: 5 bits
> Data: 0-31 bits
> Filler: filling 0 bits to make the packet dividable by 8
>
> what I usually do is read the packet in binary mode, convert the output
> to a concatenated 'binary string'(i.e. '0101011000110') and then use
> slice indeces to get the right data portions.
> Depending on what I need to do with these portions I convert them to
> whatever is handy (usually an integer).
>
> This works out fine for me. Most of the time I also put the ASCII art
> diagram of this 'protocol' as a comment in the code, making it more
> readable/understandable.
>
> Though there are a couple of things that bothers me with my approach:
> - This seems such a general problem that I think that there must be
> already a general pythonic solution.
> - Using a string for binary representation takes at least 8 times more
> memory for the packet than strictly necessary.
> - Seems to need a lot of prep work before doing the actual parsing.
>
> Any suggestion is greatly appreciated.
>
> --
> MPHhttp://blog.dcuktec.com
> 'If consumed, best digested with added seasoning to own preference.'

Take a look at the bitstring module (in pypi or google code). It's
designed to help make this sort of thing easy and it's more fully
featured than BitVector or BitSet. Internally the data is stored as a
byte array, so memory isn't wasted. It will also do all the dirty work
of bit masking and shifting so that you can concentrate on the real
problems. For example:

>>> s = BitString('0x1232432312')  # just to give us some data to play with
>>> ver, comm, instr, bitlen = s.read('uint6, bin4, bin5, uint5')
>>> data = s.readbits(bitlen)

Different interpretations of the binary data are given using Python
properties (e.g. s.hex, s.oct, s.uint, etc.) and it supports bit-wise
slicing, modification, finding, replacing and more. It is also still
in active development (full disclosure: I'm the author :-)).



From contact at xavierho.com  Thu Aug  6 04:44:45 2009
From: contact at xavierho.com (Xavier Ho)
Date: Thu, 6 Aug 2009 18:44:45 +1000
Subject: remove last 76 letters from string
In-Reply-To: 
References: 
	
	
Message-ID: <2d56febf0908060144g4201d152mbf981c9273d5915f@mail.gmail.com>

On Thu, Aug 6, 2009 at 6:28 PM, Iain King  wrote:

> >      print >>nucleotides, seq[-76]
>
> >      last_part = line.rstrip()[-76 : ]
>
> You all mean:   seq[:-76]   , right? (assuming you've already stripped
> any junk off the end of the string)
>

I think so, probably both of them typo'd. (What are the probabilities of
that?)

It looks to me like you have two lines per DNA sequence. What you could do
instead, is to alternate the line reading with a with statement, as
suggested by Jan. Although I don't know why he's nesting two of them.
(explanation would be neat.)

Here's my version of approach, given the sample data the OP posted:

with open('NodeList.txt', 'r') as file:
    for line in file.readlines():
        line = line.rstrip()
        if line[0] == '>':
            # Do for New DNA Sequence
            # ...
        else:
            line = line[:-76]
            # ...

Should do what you need.

Best regards,

Ching-Yun "Xavier" Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: contact at xavierho.com
Website: http://xavierho.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From sanu1267 at gmail.com  Thu Aug  6 05:25:58 2009
From: sanu1267 at gmail.com (sanju ps)
Date: Thu, 6 Aug 2009 14:55:58 +0530
Subject: handling kill signal
Message-ID: <2b76be80908060225n674cbea5x6511d768c2828be6@mail.gmail.com>

I want to handle a kill signal..In my program i wrote like this

def handler(signum, frame):
    print "Signal",signum
    delete_temp_file()
    exit(1)
signal.signal(signal.SIGTERM, handler)

And when i tried pkill processid .program is exited but not deleting the
temp file
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From thangappan143 at gmail.com  Thu Aug  6 06:30:15 2009
From: thangappan143 at gmail.com (Thangappan.M)
Date: Thu, 6 Aug 2009 16:00:15 +0530
Subject: Problem in installing PyGreSQL
In-Reply-To: 
References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com>
	<7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net>
	<20090804084856.b825967a.darcy@druid.net>
	
	<20090804095547.a5274e22.darcy@druid.net> 
Message-ID: <7aa29e790908060330x67d900a9rfb4677eaf0eddeb@mail.gmail.com>

I have downloaded the  psycopg2 tar file from the following link.
http://initd.org/tracker/psycopg

I have done the following things.
         * Extracting the files from the tar file
         * tried to execute python ./setup.py build

It gives the following error.

#python ./setup.py build

running build
running build_py
running build_ext
Traceback (most recent call last):
  File "./setup.py", line 410, in ?
    ext_modules=ext)
  File "distutils/core.py", line 149, in setup
  File "distutils/dist.py", line 946, in run_commands
  File "distutils/dist.py", line 966, in run_command
  File "distutils/command/build.py", line 112, in run
  File "/usr/lib/python2.4/cmd.py", line 333, in run_command
    del help[cmd]
  File "distutils/dist.py", line 965, in run_command
  File "/usr/lib/python2.4/cmd.py", line 117, in ensure_finalized
    pass
  File "./setup.py", line 219, in finalize_options
    except (Warning, w):
NameError: global name 'w' is not defined

What would be the solution?
Otherwise can you tell how to install DB-API in debian machine.

On Wed, Aug 5, 2009 at 10:43 AM, Dennis Lee Bieber wrote:

> On Tue, 4 Aug 2009 09:55:47 -0400, "D'Arcy J.M. Cain" 
> declaimed the following in gmane.comp.python.general:
>
> >
> > By the way, you don't have to be super user to install PyGreSQL.  You
> > just need SU if you want to install it system wide.  PyGreSQL doesn't
> > require any special privileges to run.
> >
>         Potentially silly question:
>
>        While the DB-API module may be installable in a user mode... Do we
> know if the original querant even has PostgreSQL running and accessible?
>
> The statement
>
> OP> I want to access the database related stuffs in python.So I found
> the
> OP> PyGreSQL module in net.
>
> doesn't leave me with any confidence that they realize this is just an
> access module for one specific server -- and that they still need a
> server to which they can connect.
>
>        If they don't have a PostgreSQL server, it may be better just to
> direct them to SQLite3...
> --
>        Wulfraed        Dennis Lee Bieber               KD6MOG
>        wlfraed at ix.netcom.com           wulfraed at bestiaria.com
>                HTTP://wlfraed.home.netcom.com/
>        (Bestiaria Support Staff:               web-asst at bestiaria.com)
>                HTTP://www.bestiaria.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Regards,
Thangappan.M
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From python at mrabarnett.plus.com  Thu Aug  6 06:34:24 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 11:34:24 +0100
Subject: remove last 76 letters from string
In-Reply-To: 
References: 	
	
Message-ID: <4A7AB1B0.7090606@mrabarnett.plus.com>

Iain King wrote:
>>      print >>nucleotides, seq[-76]
> 
>>      last_part = line.rstrip()[-76 : ]
> 
> You all mean:   seq[:-76]   , right? (assuming you've already stripped
> any junk off the end of the string)
> 
The OP said "cut out the last 76 letters (nucleotides) from each
individual sequence and send them to a new txt file with a similar 
format.", ie extract the last 76 letters (in the same format) to a file.


From deets at nospam.web.de  Thu Aug  6 06:38:39 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Thu, 06 Aug 2009 12:38:39 +0200
Subject: Cython + setuptools not working with .pyx,only with .c-files
Message-ID: <7dvq5fF2e21b7U1@mid.uni-berlin.de>

Hi,


I'm trying to build a Cython-extension as Egg.

However, this doesn't work - I can either use distutils to build the
extension, creating a myextension.c-file on the way.

If that's there, I can use setuptools to build the egg.

But when I remove the .c-file, the .pyx-file isn't used to re-generate it.

This is my setup.py:

----
import os
import glob
from setuptools import setup, Extension
#from distutils.core import setup
#from distutils.extension import Extension

from Cython.Distutils import build_ext


objs = [...] # a static lib I want to wrap

setup(
    name='MyExtension',
    version="0.1",
    description='',
    author='Diez B. Roggisch',
    author_email='...',
    cmdclass = {'build_ext': build_ext},
    ext_modules = [Extension("myextension", ["myextension.pyx"],
                             libraries=["crypto"],
                             extra_objects = objs)],

-----


I can of course check in the myextension.c-file , and then when actually
working on the extension create it new by uncommenting the above lines.

But I guess that's not really the way things should work...

Diez


From pavlovevidence at gmail.com  Thu Aug  6 06:38:53 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Thu, 6 Aug 2009 03:38:53 -0700 (PDT)
Subject: Subclassing Python's dict
References:  
	<4a7999b1$0$306$426a74cc@news.free.fr>
Message-ID: <2c161a54-fade-4753-aa3f-3fee67632056@l5g2000pra.googlegroups.com>

On Aug 5, 7:39?am, Bruno Desthuilliers  wrote:
> Sergey Simonenko a ?crit :
>
> > Hi,
>
> > I subclass builtin 'dict' in my application and experience some problems
> > with it.
>
> > The whole issue is that I should redefine 'setdefault' and 'update'
> > methods after redefining '__setitem__' or/and '__delitem__',
> > otherwise 'update' and 'setdefault' ignore redefined '__setitem__' and
> > use builtin dict's one so dict looks kinda like a black box.
>
> > Another guy have reported me that he experiences similar problems with
> > subclassing builtin 'list'.
>
> I indeed notice this behaviour here (Python 2.6.2). I'm afraid it has to
> do with some optimization tricks (dict being the very fundamental data
> structure in Python, it has to be higly optimized).

You can ultimately blame it on optimization in this case, but in
general there isn't any way (in Python) to require that __setitem__ be
the common point for all modifications.

In fact this is an example of a general condition of OOP.  A "high-
level" method may or may not call a "low-level" method to do its dirty
work, and there is no way to know this simply from the class's
interface.  You need to have knowledge of the implementation to know
whether you need to override "high-level" or "low-level" methods.  In
general you can't safely subclass based on the interface alone; you
have to know what you're subclassing.

(As an aside: this intuitively is the reason why I never cared much
for some of the arguments against inheritance.  Many arguments against
inheritance go like this: "Inheritance is bad because X can happen if
you're not careful".  Doesn't mean anything to me because you have be
careful anyway.)

Because of the care required when subclassing, I tend to use
inheritance only when the intended base class is A. also under my
control, or B. specifically designed to be subclassed.  Examples of B
in the standard Python library are Queue and Thread.  list and dict
are allowed to be subclassed but aren't specifically designed for it,
so I tend not to subclass those.  (It is occasionally indispensible,
though.)


Carl Banks


From cournape at gmail.com  Thu Aug  6 06:57:11 2009
From: cournape at gmail.com (David Cournapeau)
Date: Thu, 6 Aug 2009 19:57:11 +0900
Subject: Using Python to automate builds
In-Reply-To: 
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com>
	
	
Message-ID: <5b8d13220908060357rb2fa7bp519809ce73455c28@mail.gmail.com>

On Thu, Aug 6, 2009 at 12:39 AM, Kosta wrote:

>
> Setenv.bat sets up the path and other environment variables build.exe
> needs to compile and link (and even binplace) its utilities. ?So
> building itself is not the issue. ?The problem is that if I call
> setenv.bat from Python and then build.exe, but the modifications to
> the path (and other environment settings) are not seen by Python, so
> the attempt to build without a specified path fails.

It sounds like you do not propagate the environment when calling
setenv.bat from python. There is an option to do so in
subprocess.Popen init method, or you can define your own environment
if you do not want to propagate the whole environment (but this is
often difficult to avoid for build environment in my experience,
expecially if you don't have access to the sources of the whole system
to check which variables are necessary).

David


From lawrencew00 at hotmail.com  Thu Aug  6 06:58:03 2009
From: lawrencew00 at hotmail.com (Lawrence Wong)
Date: Thu, 6 Aug 2009 10:58:03 +0000
Subject: os.system in a service
In-Reply-To: 
References: 
	
	<7dvda1F2c4s7kU1@mid.uni-berlin.de> 
	
Message-ID: 


I actually found the solution.  I was trying to copy a file from another computer to the current one.  My 'access was denied'.  So I had to go to my service at Admin Tools --> Services and 'Log on as' the Administrator.  Was ok after that.  Thanks for your responses everyone.  

> To: python-list at python.org
> From: gagsl-py2 at yahoo.com.ar
> Subject: Re: os.system in a service
> Date: Thu, 6 Aug 2009 05:35:57 -0300
> 
> En Thu, 06 Aug 2009 03:59:13 -0300, Diez B. Roggisch   
> escribi?:
> > Gabriel Genellina schrieb:
> >> En Wed, 05 Aug 2009 13:07:39 -0300, Lawrence Wong  
> >>  escribi?:
> 
> >>> I wrote a program which runs a .bat file using os.system like:  
> >>> 'os.system(pathToBatFile)' and everything was good.  Then I decided to  
> >>> turn my program into a service as opposed to being run with the  
> >>> command prompt showing.  When my program became a service, I noticed  
> >>> that the os.system command to run my .bat file was no longer working.  
> >>> [...]
> 
> >>  Capture stdout and stderr and you'll probably see the error message:
> >>  some_command >logfile.txt 2>&1
> >
> > Which isn't possible as a service.
> 
> Why you say so? One should avoid using mapped drive letters and network  
> shares -- that probably aren't defined for the account under which the  
> service runs. And always use absolute paths. And ensure the account has  
> write permissions for the output file... But other than that, os.system  
> should work fine. Do I miss something?
> 
> > The OP might consider using suprocess istead of os.system, and establish  
> > pipes to read the output of the command into a file he can analyze.
> 
> That's a good idea, although overkill for simple cases I'd say.
> 
> -- 
> Gabriel Genellina
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

_________________________________________________________________
More storage. Better anti-spam and antivirus protection. Hotmail makes it simple.
http://go.microsoft.com/?linkid=9671357
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From cournape at gmail.com  Thu Aug  6 07:00:09 2009
From: cournape at gmail.com (David Cournapeau)
Date: Thu, 6 Aug 2009 20:00:09 +0900
Subject: Cython + setuptools not working with .pyx,only with .c-files
In-Reply-To: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
References: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
Message-ID: <5b8d13220908060400m4d096726i6d929fb0e32a0327@mail.gmail.com>

On Thu, Aug 6, 2009 at 7:38 PM, Diez B. Roggisch wrote:
> Hi,
>
>
> I'm trying to build a Cython-extension as Egg.
>
> However, this doesn't work - I can either use distutils to build the
> extension, creating a myextension.c-file on the way.
>
> If that's there, I can use setuptools to build the egg.
>
> But when I remove the .c-file, the .pyx-file isn't used to re-generate it.
>
> This is my setup.py:
>
> ----
> import os
> import glob
> from setuptools import setup, Extension
> #from distutils.core import setup
> #from distutils.extension import Extension
>
> from Cython.Distutils import build_ext

What happens if you import setuptools *after* Cython.distutils ? My
guess - I could be wrong - is that both Cython.distutils and
setuptools monkey-patch distutils, and that setuptools does not "see"
Cython.Distutils. It could also be an incompatibility between
Cython.Distutils and setuptools (the design of distutils forces you to
take into account the details of things modified by every distutils
extension).

cheers,

David


From doron.tal.list at gmail.com  Thu Aug  6 08:00:45 2009
From: doron.tal.list at gmail.com (Doron Tal)
Date: Thu, 6 Aug 2009 15:00:45 +0300
Subject: inspect.stack() performance
Message-ID: <2a8674c60908060500k1c77b556la70d06d5feaaef0e@mail.gmail.com>

I use inspect.stack() to extract some info, such as file name, function name
and line number, for the sake of logging (home brew logger).
I tested to see how much time it takes to execute the command:

Python 2.4.3 (#1, Jan 21 2009, 01:11:33)
[GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> t = timeit.Timer('inspect.stack()', 'import inspect')
>>> t.repeat(3,1000)
[0.28500604629516602, 0.28315305709838867, 0.29169297218322754]
>>>

About 280uSec per call.

If I log 1000 times per seconds than I get to spend 28% of the process time
on inspect.stack()
Is there a better/quicker way of retrieving the same info?

Thanks,
--doron
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From Michalek.Jan at uhul.cz  Thu Aug  6 08:37:55 2009
From: Michalek.Jan at uhul.cz (=?iso-8859-2?Q?MICH=C1LEK_Jan_Mgr=2E?=)
Date: Thu, 6 Aug 2009 14:37:55 +0200
Subject: one method of COM object needs a variant type variable
Message-ID: <913F77222E913C49A057FDD7BBDEAAA30192B846@br-dc.uhul.wan>

How i can use this type in win32.com? One method of com object (geomedia storage service) needs this variable for storage geometry of geometry object (this variable will be writen into blob in DB). Is possible make this variable in py??
Thanks Jelen/Stack
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From marcusw at cox.net  Thu Aug  6 09:24:33 2009
From: marcusw at cox.net (Marcus Wanner)
Date: Thu, 06 Aug 2009 09:24:33 -0400
Subject: Overlap in python
In-Reply-To: <4c9f81a5-51b9-4487-9df9-d458b327d286@s15g2000yqs.googlegroups.com>
References: 	<4A78B19D.4020306@mrabarnett.plus.com>	
	<4c9f81a5-51b9-4487-9df9-d458b327d286@s15g2000yqs.googlegroups.com>
Message-ID: 

On 8/5/2009 10:56 AM, nn wrote:
> On Aug 5, 7:13 am, Marcus Wanner  wrote:
>> On 8/4/2009 6:09 PM, MRAB wrote:
>>
>>>  >>> parts = [(5, 9, "a"), (7, 10, "b"), (3, 6, "c"), (15, 20, "d"),
>>> (18, 23, "e")]
>>>  >>> parts.sort()
>>>  >>> parts
>>> [(3, 6, 'c'), (5, 9, 'a'), (7, 10, 'b'), (15, 20, 'd'), (18, 23, 'e')]
>>>  >>> # Merge overlapping intervals.
>>>  >>> pos = 1
>>>  >>> while pos < len(parts):
>>>         # Merge the pair in parts[pos - 1 : pos + 1] if they overlap.
>>>         p, q = parts[pos - 1 : pos + 1]
>>>         if p[1] >= q[0]:
>>>                 parts[pos - 1 : pos + 1] = [(p[0], max(p[1], q[1]), p[2]
>>> + "." + q[2])]
>>>         else:
>>>                 # They don't overlap, so try the next pair.
>>>                 pos += 1
>>>  >>> parts
>>> [(3, 10, 'c.a.b'), (15, 23, 'd.e')]
>> That's the best solution I've seen so far. It even has input/output
>> formatted as close as is reasonably possible to the format specified.
>>
>> As we would say in googlecode, +1.
>>
>> Marcus
> 
> How does it compare to this one?
> 
> http://groups.google.com/group/comp.lang.python/browse_frm/thread/1a1d2ed9d05d11d0/56684b795fc527cc#56684b795fc527cc
That is a different problem, and the solution is more complex.
I am not going to try to judge which is better.

Marcus

-- 
print ''.join([chr(((ord(z)+(ord("I'M/THE"[3])+sum(
     [ord(x)for x in 'CRYPTOR'])))%(4*ord('8')+ord(
     ' ')))) for z in ''.join(([(('\xca\x10\x03\t'+
     '\x01\xff\xe6\xbe\x0c\r\x06\x12\x17\xee\xbe'+
     '\x10\x03\x06\x12\r\x0c\xdf\xbe\x12\x11\x13'+
     '\xe8')[13*2-y]) for y in range(int(6.5*4)+1)]
     ))])



From tjreedy at udel.edu  Thu Aug  6 09:55:04 2009
From: tjreedy at udel.edu (Terry Reedy)
Date: Thu, 06 Aug 2009 22:55:04 +0900
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
Message-ID: 

RayS wrote:
> At 08:35 PM 8/5/2009 -0700, r wrote:
>> """... Any real sense of community is undermined -- or
>> even destroyed -- to be replaced by virtual equivalents that strive,
>> unsuccessfully, to synthesize a sense of community."""
> 
> I've brought up the idea of the quasi-community doc that PHP uses to 
> good effect.

And what have you done about setting up such a project?

> http://www.php.net/manual/en/language.types.array.php is a prime example 
> where 2/3 of the "doc" is user-contributed comments and code.

I consider consider this to an unreadable mishmash. If you and others 
want something like that, do it.  And quite bitching about the work of 
those of us who have done something compact and readable. We are all 
volunteers here.

tjr



From iainking at gmail.com  Thu Aug  6 09:58:13 2009
From: iainking at gmail.com (Iain King)
Date: Thu, 6 Aug 2009 06:58:13 -0700 (PDT)
Subject: remove last 76 letters from string
References: 
	
	
	
Message-ID: <938fdab5-65c5-47a0-8386-95edc470da9e@a26g2000yqn.googlegroups.com>

On Aug 6, 11:34?am, MRAB  wrote:
> Iain King wrote:
> >> ? ? ?print >>nucleotides, seq[-76]
>
> >> ? ? ?last_part = line.rstrip()[-76 : ]
>
> > You all mean: ? seq[:-76] ? , right? (assuming you've already stripped
> > any junk off the end of the string)
>
> The OP said "cut out the last 76 letters (nucleotides) from each
> individual sequence and send them to a new txt file with a similar
> format.", ie extract the last 76 letters (in the same format) to a file.

So he did.  Excuse me while I go eat my other foot.


From tack at urandom.ca  Thu Aug  6 10:15:41 2009
From: tack at urandom.ca (Jason Tackaberry)
Date: Thu, 06 Aug 2009 10:15:41 -0400
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 
	<1249487636.7120.798.camel@arrakis>
	
Message-ID: <1249568141.10840.37.camel@arrakis>

On Thu, 2009-08-06 at 01:31 +0000, John Machin wrote:
> Faster by an enormous margin; attributing this to the cost of attribute lookup
> seems implausible.

Ok, fair point.  I don't think the time difference fully registered when
I composed that message.

Testing a global access (LOAD_GLOBAL) versus an attribute access on a
global object (LOAD_GLOBAL + LOAD_ATTR) shows that the latter is about
40% slower than the former.  So that certainly doesn't account for the
difference.


> Suggested further avenues of investigation:
> 
> (1) Try the timing again with "cp1252" and "utf8" and "utf_8"
> 
> (2) grep "utf-8" /Objects/unicodeobject.c

Very pedagogical of you. :)  Indeed, it looks like bigger player in the
performance difference is the fact that the code path for unicode(s,
enc) short-circuits the codec registry for common encodings (which
includes 'utf-8' specifically), whereas s.decode('utf-8') necessarily
consults the codec registry.

Cheers,
Jason.



From thorsten at thorstenkampe.de  Thu Aug  6 10:32:34 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Thu, 6 Aug 2009 16:32:34 +0200
Subject: unicode() vs. s.decode()
References: 
Message-ID: 

* Michael Str?der (Wed, 05 Aug 2009 16:43:09 +0200)
> These both expressions are equivalent but which is faster or should be
> used for any reason?
> 
> u = unicode(s,'utf-8')
> 
> u = s.decode('utf-8') # looks nicer

"decode" was added in Python 2.2 for the sake of symmetry to encode(). 
It's essentially the same as unicode() and I wouldn't be surprised if it 
is exactly the same. I don't think any measurable speed increase will be 
noticeable between those two.

Thorsten


From sbassi at clubdelarazon.org  Thu Aug  6 10:35:36 2009
From: sbassi at clubdelarazon.org (Sebastian Bassi)
Date: Thu, 6 Aug 2009 11:35:36 -0300
Subject: ANN: Python for Bioinformatics book
Message-ID: <9e2f512b0908060735w7d270238y773275d45c46a954@mail.gmail.com>

"Python for Bioinformatics"
ISBN 1584889292
Amazon: http://www.tinyurl.com/biopython
Publisher: http://www.crcpress.com/product/isbn/9781584889298

This book introduces programming concepts to life science researchers,
bioinformaticians, support staff, students, and everyone who is
interested in applying programming to solve biologically-related
problems. Python is the chosen programming language for this task
because it is both powerful and easy-to-use.

It begins with the basic aspects of the language (like data types and
control structures) up to essential skills on today's bioinformatics
tasks like building web applications, using relational database
management systems, XML and version control. There is a chapter
devoted to Biopython (www.biopython.org) since it can be used for most
of the tasks related to bioinformatics data processing.

There is a section with applications with source code, featuring
sequence manipulation, filtering vector contamination, calculating DNA
melting temperature, parsing a genbank file, inferring splicing sites,
and more.

There are questions at the end of every chapter and odd numbered
questiona are answered in an appendix making this text suitable for
classroom use.

This book can be used also as a reference material as it includes
Richard Gruet's Python Quick Reference, and the Python Style Guide.

DVD: The included DVD features a virtual machine with a special
edition of DNALinux, with all the programs and complementary files
required to run the scripts commented in the book. All scripts can be
tweaked to fit a particular configuration. By using a pre-configured
virtual machine the reader has access to the same development
environment than the author, so he can focus on learning Python. All
code is also available at the http://py3.us/## where ## is the code
number, for example: http://py3.us/57

I've been working on this book for more than two years testing the
examples under different setups and working to make the code
compatible for most versions of Python, Biopython and operating
systems. Where there is code that only works with a particular
dependency, this is clearly noted.

Finally, I want to highlight that non-bioinformaticians out there can
use this book as an introduction to bioinformatics by starting with
the included "Diving into the Gene Pool with BioPython" (by Zachary
Voase and published originally in Python Magazine).


-- 
Sebasti?n Bassi. Diplomado en Ciencia y Tecnolog?a.

Non standard disclaimer: READ CAREFULLY. By reading this email,
you agree, on behalf of your employer, to release me from all
obligations and waivers arising from any and all NON-NEGOTIATED
agreements, licenses, terms-of-service, shrinkwrap, clickwrap,
browsewrap, confidentiality, non-disclosure, non-compete and
acceptable use policies ("BOGUS AGREEMENTS") that I have
entered into with your employer, its partners, licensors, agents and
assigns, in perpetuity, without prejudice to my ongoing rights and
privileges. You further represent that you have the authority to release
me from any BOGUS AGREEMENTS on behalf of your employer.


From kee at kagi.com  Thu Aug  6 10:39:10 2009
From: kee at kagi.com (Kee Nethery)
Date: Thu, 6 Aug 2009 07:39:10 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
Message-ID: <701EC8AD-A151-46F9-A393-31B3960CE2FC@kagi.com>


On Aug 6, 2009, at 6:55 AM, Terry Reedy wrote:

> RayS wrote:
>> At 08:35 PM 8/5/2009 -0700, r wrote:
>>> """... Any real sense of community is undermined -- or
>>> even destroyed -- to be replaced by virtual equivalents that strive,
>>> unsuccessfully, to synthesize a sense of community."""
>> I've brought up the idea of the quasi-community doc that PHP uses  
>> to good effect.
>
> And what have you done about setting up such a project?
>
>> http://www.php.net/manual/en/language.types.array.php is a prime  
>> example where 2/3 of the "doc" is user-contributed comments and code.
>
> I consider consider this to an unreadable mishmash. If you and  
> others want something like that, do it.  And quite bitching about  
> the work of those of us who have done something compact and  
> readable. We are all volunteers here.

As I struggle through trying to figure out how to make python do  
simple stuff for me, I frequently generate samples. If some volunteer  
here would point me towards the documentation that would tell me how I  
can alter the existing Python docs to include sample code, I'd be more  
than happy to do so.

I would like to "do it". Please point me to the docs that tell me how  
to "do it" so that we people with newbie questions and a need for  
examples can get out of your way and "do it" ourselves.

Thanks,
Kee Nethery





From jakecjacobson at gmail.com  Thu Aug  6 10:50:07 2009
From: jakecjacobson at gmail.com (jakecjacobson)
Date: Thu, 6 Aug 2009 07:50:07 -0700 (PDT)
Subject: Help making this script better
Message-ID: <2f8e34ec-01aa-4ec4-9636-a8ec1f87c68c@o6g2000yqj.googlegroups.com>

Hi,

After much Google searching and trial & error, I was able to write a
Python script that posts XML files to a REST API using HTTPS and
passing PEM cert & key file.  It seems to be working but would like
some pointers on how to handle errors.  I am using Python 2.4, I don't
have the capability to upgrade even though I would like to.  I am very
new to Python so help will be greatly appreciated and I hope others
can use this script.

#!/usr/bin/python
#################################################################
# catalog_feeder.py
#################################################################
# This sciript will process a directory of XML files and push them to
the Enterprise Catalog.
#  You configure this script by using a configuration file that
describes the required variables.
#  The path to this file is either passed into the script as a command
line argument or hard coded
#  in the script.  The script will terminate with an error if it can't
process the XML file.
#################################################################

# IMPORT STATEMENTS
import httplib
import mimetypes
import os
import sys
import shutil
import time
from urllib import *
from time import strftime
from xml.dom import minidom

def main(c):
	start_time = time.time()
	# Set configuration parameters
	try:
		# Process the XML conf file ....
		xmldoc = minidom.parse(c)
		catalog_host = readConfFile(xmldoc, 'catalog_host')
		catalog_port = int(readConfFile(xmldoc, 'catalog_port'))
		catalog_path = readConfFile(xmldoc, 'catalog_path')
		collection_name = readConfFile(xmldoc, 'collection_name')
		cert_file = readConfFile(xmldoc, 'cert_file')
		key_file = readConfFile(xmldoc, 'key_file')
		log_file = readConfFile(xmldoc, 'log_file')
		input_dir = readConfFile(xmldoc, 'input_dir')
		archive_dir = readConfFile(xmldoc, 'archive_dir')
		hold_dir = readConfFile(xmldoc, 'hold_dir')
	except Exception, inst:
		# I had an error so report it and exit script
		print "Unexpected error opening %s: %s" % (c, inst)
		sys.exit(1)
	# Log Starting
	logOut = verifyLogging(log_file)
	if logOut:
		log(logOut, "Processing Started ...")
	# Get list of XML files to process
	if os.path.exists(input_dir):
		files = getFiles2Post(input_dir)
	else:
		if logOut:
			log(logOut, "WARNING!!! Couldn't find input directory: " +
input_dir)
			cleanup(logOut)
		else:
			print "Dir doen't exist: " + input_dir
			sys.exit(1)
	try:
		# Process each file to the catalog
		connection = httplib.HTTPSConnection(catalog_host, catalog_port,
key_file, cert_file)
		for file in files:
			log(logOut, "Processing " + file + " ...")
			try:
				response = post2Catalog(connection, catalog_path, os.path.join
(input_dir, file), collection_name)
				if response.status == 200:
					msg = "Succesfully posted " +  file + " to cataloge ..."
					print msg
					log(logOut, msg)
					# Move file to done directory
					shutil.move(os.path.join(input_dir, file), os.path.join
(archive_dir, file))
				else:
					msg = "Error posting " +  file + " to cataloge [" + response.read
() + "] ..."
					print msg
					log(logOut, response.read())
					# Move file to error dir
					shutil.move(os.path.join(input_dir, file), os.path.join(hold_dir,
file))
			except IOError, (errno):
				print "%s" % (errno)

	except httplib.HTTPException, (e):
		print "Unexpected error %s " % (e)

	run_time = time.time() - start_time
	print 'Run time: %f seconds' % run_time

	# Clean up
	connection.close()
	cleanup(logOut)

# Get an arry of files from the input_dir
def getFiles2Post(d):
	return (os.listdir(d))

# Read out the conf file and set the needed global variable
def readConfFile(xmldoc, tag):
	return (xmldoc.getElementsByTagName(tag)[0].firstChild.data)

# Write out the message to log file
def log(f, m):
	f.write(strftime("%Y-%m-%d %H:%M:%S") + " : " + m + '\n')

# Clean up and exit
def cleanup(logOut):
	if logOut:
		log(logOut, "Processing Ended ...\n")
		logOut.close()
	sys.exit(0)

# Verify if we can write to the log file and return a file handle if
we can
def verifyLogging(l):
	fh=''  # No logging default behavior
	if os.path.exists(os.path.dirname(l)):
		fh = open(l, 'a')
	return(fh)

# Print out the usage of this script
def printusage():
	print""
	print
"**************************************************************************************************"
	print " Must provide the path to the configuration file when calling
this script ..."
	print " Example: " + sys.argv[0] + " /path_2_configuration_file/
conf.xml"
	print
"**************************************************************************************************"
	print ""
	sys.exit(1)

#############################
# Posting XML file to the Catelog Service
#############################
def post2Catalog(connection, path, file, collection):
	head = {"Content-Type" : "application/x-www-form-urlencoded",
"Accept" : "text/plain"}
	parameters = urlencode({"collection" : collection, "entryxml" : open
(file,'r').read()})
	connection.request('POST', path, parameters, head)
	response = connection.getresponse()
	# To reuse the connection, I have to read the response.  I really
don't care about it so I do nothing with it.
	body = response.read()
	return response

# Main
if __name__ == "__main__":
	_pathname = os.path.dirname(sys.argv[0])
	total=len(sys.argv)
	if len(sys.argv) > 1:
		main(sys.argv[1])
	else:
		printusage()


From bearophileHUGS at lycos.com  Thu Aug  6 10:52:44 2009
From: bearophileHUGS at lycos.com (Bearophile)
Date: Thu, 6 Aug 2009 07:52:44 -0700 (PDT)
Subject: ANN: Python for Bioinformatics book
References: 
Message-ID: 

Sebastian Bassi:

> All code is also available at thehttp://py3.us/##where ## is the code number, for example:http://py3.us/57<

The book looks interesting, but that doesn't look like a good way to
show/offer the code. I suggest to also put it into a zip that can be
downloaded.

Bye,
bearophile


From josepharmbruster at gmail.com  Thu Aug  6 11:05:20 2009
From: josepharmbruster at gmail.com (joseph armbruster)
Date: Thu, 6 Aug 2009 08:05:20 -0700 (PDT)
Subject: FCC Amateur Radio database -> SQLite
Message-ID: <1b304bef-150f-405d-a66a-6ec2979a1f2c@a1g2000yqn.googlegroups.com>

Here is a quick way to get the amateur radio database from the FCC put
into sqlite.  If anyone has insight into a pure-python import, please
comment.

http://libjoe.blogspot.com/2009/08/loading-up-fcc-license-database.html

Joseph Armbruster
http://www.joevial.com


From kuchunwah01 at yahoo.com  Thu Aug  6 11:19:20 2009
From: kuchunwah01 at yahoo.com (John)
Date: Thu, 6 Aug 2009 08:19:20 -0700 (PDT)
Subject: convert non-delimited to delimited
Message-ID: <768586.94351.qm@web65602.mail.ac4.yahoo.com>

I am not really a CS person, but I have a task to import a non-delimited text to an access database.? After some research, I *think* the best way to do this is by first converting the non-delimited text to delimited text, and then import it to the database.? Is this the best way to approach this?? Or is there easier way?

Example:
---------------------------------------------------------------------------
Test , BTS
0800000532
05/MAY/1945 00:00
Female
858327
AB Pos
�

CMV Neg Req'd
IgA Deficient




Wr(a+)
S-


>> OCT/23/07 08:18:00 TRETHEWEYD >>>>>>>>>>>>>>>>> Please fax to:
>> OCT/22/07 09:37:00 [COMBINE] [Combine from person_id 924598 to person_id 858327]
[Following comments for to person_id 924598]
>> OCT/18/07 15:53:00 TRETHEWEYD 2007/10/18 15:52

-----------------------------------------------------------------------------------
Basically there are 2 portions to this.? The first portion consist of 7 lines (Full Name, Medical record number, birth date, gender, internal ID, blood group, phenotype).? The second portion list the different list of requirements, denote by  and .? In the sample shown above, the patient do not have information on phenotype, thus there is the � symbol.? 
?
I am really stump on where to go from here.? Any help would be appreciated it.? I have also include a text file which gives several more examples.
?
Thanks so much!


      __________________________________________________________________
Looking for the perfect gift? Give the gift of Flickr! 

http://www.flickr.com/gift/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: samplepatient.txt
Type: application/octet-stream
Size: 48996 bytes
Desc: not available
URL: 

From sbassi at clubdelarazon.org  Thu Aug  6 11:34:35 2009
From: sbassi at clubdelarazon.org (Sebastian Bassi)
Date: Thu, 6 Aug 2009 12:34:35 -0300
Subject: ANN: Python for Bioinformatics book
In-Reply-To: 
References: 
	
Message-ID: <9e2f512b0908060834g5ad2ce34vbc2df78d16a24f69@mail.gmail.com>

On Thu, Aug 6, 2009 at 11:52 AM, Bearophile wrote:
> The book looks interesting, but that doesn't look like a good way to
> show/offer the code. I suggest to also put it into a zip that can be
> downloaded.

Code is also in a directory in the DVD and also inside the virtual
machine. Anyway I think it wouldn't hurt to make a zip and put it
online, so i will do it. Thanks.
Best,
SB.


From rcdailey at gmail.com  Thu Aug  6 11:35:57 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 08:35:57 -0700 (PDT)
Subject: Help with regex
Message-ID: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>

Hey guys,

I'm creating a python script that is going to try to search a text
file for any text that matches my regular expression. The thing it is
looking for is:

FILEVERSION #,#,#,#

The # symbol represents any number that can be any length 1 or
greater. Example:

FILEVERSION 1,45,10082,3

The regex should only match the exact above. So far here's what I have
come up with:

re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )

This works, but I was hoping for something a bit cleaner. I'm having
to create a special case portion of the regex for the last of the 4
numbers simply because it doesn't end with a comma like the first 3.
Is there a better, more compact, way to write this regex?


From mydevforums at gmail.com  Thu Aug  6 11:49:30 2009
From: mydevforums at gmail.com (IronyOfLife)
Date: Thu, 6 Aug 2009 08:49:30 -0700 (PDT)
Subject: Python configuration question when python scripts are executed 
	using Appweb as web server.
References: 
	
	
	
Message-ID: 

Hi Gabriel

On Aug 5, 4:18?pm, "Gabriel Genellina"  wrote:
> En Tue, 04 Aug 2009 10:15:24 -0300, IronyOfLife 
> escribi?:
>
> > On Aug 3, 8:42?pm, "Gabriel Genellina"  wrote:
> >> En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife  ?
> >> escribi?:
>
> >> > I have installed python 2.6.2 in windows xp professional machine. I
> >> > have set the following environment variables -- PYTHONPATH. It points
> >> > to following windows folders: python root folder, the lib folder and
> >> > lib-tk folder.
>
> >> Why? Did you read it somewhere? Usually there is no need to set the ?
> >> PYTHONPATH variable at all; remove it.
>
> > Setting PYTHONPATH environment variables is mentioned in Python docs.
>
> Could you provide a link please? Setting PYTHONPATH should not be

Here are couple of links that discusses setting PYTHONPATH environment
variable.
http://docs.python.org/using/windows.html
http://www.daimi.au.dk/~chili/PBI/pythonpath.html

> necesary, and in fact it's a very bad idea. Environment variables are
> global, but Python modules may depend on the Python version, architecture,
> install location... By example, you may install a 64 bits Python 3.1
> version *and* a 32 bits Python 2.5 version and they both can coexist
> peacefully - but an extension module compiled for the former cannot be
> used in the later version. You must build a separate library for each
> version, and install them in two separate directories. But since the
> PYTHONPATH variable is shared by all installations, which directory should
> contain?
> It's best not to use PYTHONPATH at all and rely on other alternatives
> (like .pth files, that are searched relative to the current Python
> executable, so different versions use different configuration files)

I understand your concerns regarding setting of PYTHONPATH while
multiple versions of Python are installed on the same machine. My fix
however does not use PYTHONPATH. The GNUTLS wrapper module for PYTHON
loads the GNUTLS dll's and it was not able to find them. Using FileMon
(win tool) I found out the paths that are scanned and I copied the
dlls to one of such paths. I still do not like this fix. This is a
temporary solution.

Can you explain maybe with some sample how to set .pth files? Maybe
this will resolve my issue.
>
> > I solved the issue temporarily by copying the gnutls related dlls to
> > the path searched by python.exe
>
> Glad to see you could finally fix it!
>
> --
> Gabriel Genellina

Thanks very much for your reply.


From wuwei23 at gmail.com  Thu Aug  6 11:52:51 2009
From: wuwei23 at gmail.com (alex23)
Date: Thu, 6 Aug 2009 08:52:51 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
Message-ID: <96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>

Kee Nethery wrote:
> As I struggle through trying to figure out how to make python do ?
> simple stuff for me, I frequently generate samples. If some volunteer ?
> here would point me towards the documentation that would tell me how I ?
> can alter the existing Python docs to include sample code, I'd be more ?
> than happy to do so.

No offence, but the last thing the official documentation needs is
example code written by people learning how to code. Suggest changes,
request clarifications, submit samples for review, sure, but direct
modification by users? I've seen the PHP docs; thanks but no thanks.

> I would like to "do it". Please point me to the docs that tell me how ?
> to "do it" so that we people with newbie questions and a need for ?
> examples can get out of your way and "do it" ourselves.

You start by reading this: http://docs.python.org/documenting/index.html
And this: http://www.python.org/dev/contributing/
And this: http://wiki.python.org/moin/WikiGuidelines

The first link, which directly answers your question, is clearly
listed on the doc contents page as "Documenting Python". I'm uncertain
how the docs could be made any _more_ helpful if people aren't
prepared to put effort into reading them. We're a long way away from
direct upload to the brain, unfortunately.

If you're learning the language, you should also consider using more
appropriate resources:
http://mail.python.org/mailman/listinfo/tutor
http://www.doughellmann.com/PyMOTW/
http://diveintopython.org/

The documentation cannot be all things to all people, and it most
certainly can't be a guide to general programming, which is what often
seems to be the issue with novice users. Python's a great language to
learn how to program in, sure, but I would hate to see that become the
focus of the docs.


From python at mrabarnett.plus.com  Thu Aug  6 12:02:44 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 17:02:44 +0100
Subject: Help with regex
In-Reply-To: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
Message-ID: <4A7AFEA4.4050800@mrabarnett.plus.com>

Robert Dailey wrote:
> Hey guys,
> 
> I'm creating a python script that is going to try to search a text
> file for any text that matches my regular expression. The thing it is
> looking for is:
> 
> FILEVERSION #,#,#,#
> 
> The # symbol represents any number that can be any length 1 or
> greater. Example:
> 
> FILEVERSION 1,45,10082,3
> 
> The regex should only match the exact above. So far here's what I have
> come up with:
> 
> re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
> 
> This works, but I was hoping for something a bit cleaner. I'm having
> to create a special case portion of the regex for the last of the 4
> numbers simply because it doesn't end with a comma like the first 3.
> Is there a better, more compact, way to write this regex?

The character class \d is equivalent to [0-9], and ',' isn't a special
character so it doesn't need to be escaped:

     re.compile(r'FILEVERSION (?:\d+,){3}\d+')


From wuwei23 at gmail.com  Thu Aug  6 12:07:51 2009
From: wuwei23 at gmail.com (alex23)
Date: Thu, 6 Aug 2009 09:07:51 -0700 (PDT)
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
Message-ID: <2b20f8fe-86e7-452e-ae94-e9179627fc74@y4g2000prf.googlegroups.com>

On Aug 7, 1:35?am, Robert Dailey  wrote:
> I'm creating a python script that is going to try to search a text
> file for any text that matches my regular expression. The thing it is
> looking for is:
>
> FILEVERSION 1,45,10082,3

Would it be easier to do it without regex? The following is untested
but I would probably do it more like this:

TOKEN = 'FILEVERSION '
for line in file:
  if line.startswith(TOKEN):
    version = line[len(TOKEN):]
    maj, min, rev, other = version.split(',')
    break # if there's only one occurance, otherwise do stuff here


From sion at viridian.paintbox  Thu Aug  6 12:11:24 2009
From: sion at viridian.paintbox (Sion Arrowsmith)
Date: Thu, 06 Aug 2009 16:11:24 GMT
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
Message-ID: 

Terry Reedy   wrote:
>RayS wrote:
>> http://www.php.net/manual/en/language.types.array.php is a prime example 
>> [ ... ]
>I consider consider this to an unreadable mishmash.
[compared to]
> something compact and readable.

Are you talking about the language or the documentation? 9-)

(Actually, that might be a serious point: does the approach to
documentation reflect language design?)

-- 
\S

   under construction



From atragor at gmail.com  Thu Aug  6 12:12:53 2009
From: atragor at gmail.com (Roman)
Date: Thu, 6 Aug 2009 20:12:53 +0400
Subject: Help with regex
In-Reply-To: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
Message-ID: <20090806161253.GA6789@localhost>

On 06/08/09 08:35, Robert Dailey wrote:
> Hey guys,
> 
> I'm creating a python script that is going to try to search a text
> file for any text that matches my regular expression. The thing it is
> looking for is:
> 
> FILEVERSION #,#,#,#
> 
> The # symbol represents any number that can be any length 1 or
> greater. Example:
> 
> FILEVERSION 1,45,10082,3
> 
> The regex should only match the exact above. So far here's what I have
> come up with:
> 
> re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
> 
> This works, but I was hoping for something a bit cleaner. I'm having
> to create a special case portion of the regex for the last of the 4
> numbers simply because it doesn't end with a comma like the first 3.
> Is there a better, more compact, way to write this regex?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Since there cannot be more than one "end of string" you can try this
expression:
re.compile( r'FILEVERSION (?:[0-9]+(,|$)){4}' )


From rcdailey at gmail.com  Thu Aug  6 12:14:08 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 09:14:08 -0700 (PDT)
Subject: Character encoding & the copyright symbol
Message-ID: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>

Hello,

I'm loading a file via open() in Python 3.1 and I'm getting the
following error when I try to print the contents of the file that I
obtained through a call to read():

UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
position 1650: character maps to 

The file is defined as ASCII and the copyright symbol shows up just
fine in Notepad++. However, Python will not print this symbol. How can
I get this to work? And no, I won't replace it with "(c)". Thanks!


From robert.kern at gmail.com  Thu Aug  6 12:14:51 2009
From: robert.kern at gmail.com (Robert Kern)
Date: Thu, 06 Aug 2009 11:14:51 -0500
Subject: How to comment on a Python PEP?
In-Reply-To: <4a7a9779$0$2384$9b622d9e@news.freenet.de>
References: 
	<4a7a9779$0$2384$9b622d9e@news.freenet.de>
Message-ID: 

On 2009-08-06 03:42, "Martin v. L?wis" wrote:
>> Is there a mechanism for submitting comments on a Python PEP?
>
> You post to python-dev or comp.lang.python, and you CC the author.

And be sure to put the PEP number in the Subject: line.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From rcdailey at gmail.com  Thu Aug  6 12:17:10 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 09:17:10 -0700 (PDT)
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
Message-ID: <64c96ebc-ce6f-4657-968e-4cbe77a8303d@t13g2000yqt.googlegroups.com>

On Aug 6, 11:02?am, MRAB  wrote:
> Robert Dailey wrote:
> > Hey guys,
>
> > I'm creating a python script that is going to try to search a text
> > file for any text that matches my regular expression. The thing it is
> > looking for is:
>
> > FILEVERSION #,#,#,#
>
> > The # symbol represents any number that can be any length 1 or
> > greater. Example:
>
> > FILEVERSION 1,45,10082,3
>
> > The regex should only match the exact above. So far here's what I have
> > come up with:
>
> > re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
>
> > This works, but I was hoping for something a bit cleaner. I'm having
> > to create a special case portion of the regex for the last of the 4
> > numbers simply because it doesn't end with a comma like the first 3.
> > Is there a better, more compact, way to write this regex?
>
> The character class \d is equivalent to [0-9], and ',' isn't a special
> character so it doesn't need to be escaped:
>
> ? ? ?re.compile(r'FILEVERSION (?:\d+,){3}\d+')

But ',' is a special symbol It's used in this way:
{0,3}

This will match the previous regex 0-3 times. Are you sure commas need
not be escaped?

In any case, your suggestions help to clean it up a bit!


From rylesny at gmail.com  Thu Aug  6 12:20:28 2009
From: rylesny at gmail.com (ryles)
Date: Thu, 6 Aug 2009 09:20:28 -0700 (PDT)
Subject: Web page data and urllib2.urlopen
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
Message-ID: <923ea664-5da0-480b-a114-e83c831a44c8@f10g2000vbf.googlegroups.com>

On Aug 5, 4:30?pm, Massi  wrote:
> Hi everyone, I'm using the urllib2 library to get the html source code
> of web pages. In general it works great, but I'm having to do with a
> financial web site which does not provide the souce code I expect. As
> a matter of fact if you try:
>
> import urllib2
> res = urllib2.urlopen("http://www.marketwatch.com/story/mondays-
> biggest-gaining-and-declining-stocks-2009-07-27")
> page = res.read()
> print page
>
> you will see that the printed code is very different from the one
> given, for example, by mozilla. Since I have really little knowledge
> in html I can't even understand if this is a python or html problem.
> Can anyone give me some help?
> Thanks in advance.

Check if setting your user agent to Mozilla results in a different
page:

http://diveintopython.org/http_web_services/user_agent.html


From http  Thu Aug  6 12:20:33 2009
From: http (Paul Rubin)
Date: 06 Aug 2009 09:20:33 -0700
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
Message-ID: <7xab2c52y6.fsf@ruckus.brouhaha.com>

alex23  writes:
> No offence, but the last thing the official documentation needs is
> example code written by people learning how to code. Suggest changes,
> request clarifications, submit samples for review, sure, but direct
> modification by users? I've seen the PHP docs; thanks but no thanks.

The PHP docs as I remember are sort of regular (non-publically
editable) doc pages, each of which has a public discussion thread
where people can post questions and answers about the topic of that
doc page.  I thought it worked really well.  The main thing is that
the good stuff from the comment section gets folded into the actual
doc now and then.

There is something similar with the PostgreSQL docs.  There is also
Real World Haskell (http://book.realworld.haskell.org) which has a lot
of interspersed user comments.  It would be cool if Python's doc site
did something like it too.


From michael at stroeder.com  Thu Aug  6 12:26:09 2009
From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=)
Date: Thu, 06 Aug 2009 18:26:09 +0200
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 
	
Message-ID: <2qcrk6-doj.ln1@nb2.stroeder.com>

Thorsten Kampe wrote:
> * Michael Str?der (Wed, 05 Aug 2009 16:43:09 +0200)
>> These both expressions are equivalent but which is faster or should be
>> used for any reason?
>>
>> u = unicode(s,'utf-8')
>>
>> u = s.decode('utf-8') # looks nicer
> 
> "decode" was added in Python 2.2 for the sake of symmetry to encode(). 

Yes, and I like the style. But...

> It's essentially the same as unicode() and I wouldn't be surprised if it 
> is exactly the same.

Did you try?

> I don't think any measurable speed increase will be noticeable between
> those two.

Well, seems not to be true. Try yourself. I did (my console has UTF-8 as charset):

Python 2.6 (r26:66714, Feb  3 2009, 20:52:03)
[GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer("'???????'.decode('utf-8')").timeit(1000000)
7.2721178531646729
>>> timeit.Timer("'???????'.decode('utf8')").timeit(1000000)
7.1302499771118164
>>> timeit.Timer("unicode('???????','utf8')").timeit(1000000)
8.3726329803466797
>>> timeit.Timer("unicode('???????','utf-8')").timeit(1000000)
1.8622009754180908
>>> timeit.Timer("unicode('???????','utf8')").timeit(1000000)
8.651669979095459
>>>

Comparing again the two best combinations:

>>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
17.23644495010376
>>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
72.087096929550171

That is significant! So the winner is:

unicode('???????','utf-8')

Ciao, Michael.


From philip at semanchuk.com  Thu Aug  6 12:31:27 2009
From: philip at semanchuk.com (Philip Semanchuk)
Date: Thu, 6 Aug 2009 12:31:27 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: 


On Aug 6, 2009, at 12:14 PM, Robert Dailey wrote:

> Hello,
>
> I'm loading a file via open() in Python 3.1 and I'm getting the
> following error when I try to print the contents of the file that I
> obtained through a call to read():
>
> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
>
> The file is defined as ASCII and the copyright symbol shows up just
> fine in Notepad++. However, Python will not print this symbol. How can
> I get this to work? And no, I won't replace it with "(c)". Thanks!

If the file is defined as ASCII and it contains 0xa9, then the file  
was written incorrectly or you were told the wrong encoding. There is  
no such character in ASCII which runs from 0x00 - 0x7f.

The copyright symbol == 0xa9 if the encoding is ISO-8859-1 or  
windows-1252, and since you're on Windows the latter is a likely bet.

http://en.wikipedia.org/wiki/Ascii
http://en.wikipedia.org/wiki/Iso-8859-1
http://en.wikipedia.org/wiki/Windows-1252


Bottom line is that your file is not in ASCII. Try specifying  
windows-1252 as the encoding. Without seeing your code I can't tell  
you where you need to specify the encoding, but the Python docs should  
help you out.


HTH
Philip



From R.Brodie at rl.ac.uk  Thu Aug  6 12:31:58 2009
From: R.Brodie at rl.ac.uk (Richard Brodie)
Date: Thu, 6 Aug 2009 17:31:58 +0100
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: 


"Robert Dailey"  wrote in message 
news:29ab0981-b95d-4435-91bd-a7a520419ada at b15g2000yqd.googlegroups.com...

> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
>
> The file is defined as ASCII.

That's the problem: ASCII is a seven bit code. What you have is
actually ISO-8859-1 (or possibly Windows-1252).

The different ISO-8859-n variants assign various characters to
to '\xa9'. Rather than being Western-European centric and assuming
ISO-8859-1 by default, Python throws an error when you stray
outside of strict ASCII. 




From python at mrabarnett.plus.com  Thu Aug  6 12:34:59 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 17:34:59 +0100
Subject: Help with regex
In-Reply-To: <64c96ebc-ce6f-4657-968e-4cbe77a8303d@t13g2000yqt.googlegroups.com>
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>	
	<64c96ebc-ce6f-4657-968e-4cbe77a8303d@t13g2000yqt.googlegroups.com>
Message-ID: <4A7B0633.2030106@mrabarnett.plus.com>

Robert Dailey wrote:
> On Aug 6, 11:02 am, MRAB  wrote:
>> Robert Dailey wrote:
>>> Hey guys,
>>> I'm creating a python script that is going to try to search a text
>>> file for any text that matches my regular expression. The thing it is
>>> looking for is:
>>> FILEVERSION #,#,#,#
>>> The # symbol represents any number that can be any length 1 or
>>> greater. Example:
>>> FILEVERSION 1,45,10082,3
>>> The regex should only match the exact above. So far here's what I have
>>> come up with:
>>> re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
>>> This works, but I was hoping for something a bit cleaner. I'm having
>>> to create a special case portion of the regex for the last of the 4
>>> numbers simply because it doesn't end with a comma like the first 3.
>>> Is there a better, more compact, way to write this regex?
>> The character class \d is equivalent to [0-9], and ',' isn't a special
>> character so it doesn't need to be escaped:
>>
>>      re.compile(r'FILEVERSION (?:\d+,){3}\d+')
> 
> But ',' is a special symbol It's used in this way:
> {0,3}
> 
> This will match the previous regex 0-3 times. Are you sure commas need
> not be escaped?
> 
> In any case, your suggestions help to clean it up a bit!

By 'special' I mean ones like '?', '*', '(', etc. ',' isn't special in
that sense.

In fact, the {...} quantifier is special only if it's syntactically
correct, otherwise it's just a literal, eg "a{," and a{} are just
literals.


From Samnsparky at gmail.com  Thu Aug  6 12:40:23 2009
From: Samnsparky at gmail.com (Sparky)
Date: Thu, 6 Aug 2009 09:40:23 -0700 (PDT)
Subject: Two Dimensional Array + ctypes
References: <79d2b3e3-b049-4d70-a56b-6e7f3ea2fa86@e27g2000yqm.googlegroups.com>
	
Message-ID: <6a218894-54d3-48d4-8a91-74e02ceefecb@g23g2000vbr.googlegroups.com>

On Aug 5, 11:19?pm, "Gabriel Genellina" 
wrote:
> En Wed, 05 Aug 2009 20:12:09 -0300, Sparky  escribi?:
>
>
>
>
>
> > Hello! I am trying to call this method:
>
> > long _stdcall AIBurst(long *idnum, [...]
> > ? ? ? ? ? ? ? ? ? ? long timeout,
> > ? ? ? ? ? ? ? ? ? ? float (*voltages)[4],
> > ? ? ? ? ? ? ? ? ? ? long *stateIOout,
> > ? ? ? ? ? ? ? ? ? ? long *overVoltage,
> > ? ? ? ? ? ? ? ? ? ? long transferMode);
>
> > I am having some problems with that ?float (*voltages)[4].
> > ? ? ? ? pointerArray = (ctypes.c_void_p * 4)
> > ? ? ? ? voltages = pointerArray(ctypes.cast(ctypes.pointer
> > ((ctypes.c_long * 4096)()), ctypes.c_void_p), ctypes.cast
> > (ctypes.pointer((ctypes.c_long * 4096)()), ctypes.c_void_p),
> > ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)()),
> > ctypes.c_void_p), ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)
>
> Why c_long and not c_float?
> Anyway, this way looks much more clear to me (and doesn't require a cast):
>
> arr4096_type = ctypes.c_float * 4096
> voltages_type = arr4096_type * 4
> voltages = voltages_type()
>
> > The program runs but the values that come back in the array are not
> > right.
>
> Thay might be due to the long/float confusion.
>
> --
> Gabriel Genellina

Brilliant! Your code is much cleaner and the problem must have been
float vs long.

Thanks,
Sam


From arockinit at gmail.com  Thu Aug  6 12:41:06 2009
From: arockinit at gmail.com (Adam N)
Date: Thu, 6 Aug 2009 09:41:06 -0700 (PDT)
Subject: Using easy_install, reduncant?
References:  
	
Message-ID: <671c5d83-650b-4a20-9504-b430b1ee8318@d4g2000vbm.googlegroups.com>

On Jul 27, 7:53?pm, David Lyon  wrote:
> On Mon, 27 Jul 2009 09:42:06 -0700 (PDT), ray 
> wrote:
>
> > I am working on a Trac installation. ?I am new to Python. ?To install
> > packages, it is suggested to use setuptools. ?I have not understood
> > the directions.
>
> > I execute ez_install.py.
>
> > Then I attempt to execute easy_install.py setuptools-0.6c9-py2.6.egg.
> > There response that setuptools is already the active version in easy-
> > install.pth. ?Then:
> > Installing easy_install.exe script to C:\Python26\Scripts error: ?C:
> > \Python26\Scripts\Easy_install.exe: Permission denied.
>
> > I have compared the file entries before and after this attempt and
> > there are no new files. ?Is there any problems here? ?What did I miss?
>
> Try using python package manager :http://sourceforge.net/projects/pythonpkgmgr/
>
> You might find it a lot simpler. It will download and install setuptools
> for you if you are still having problems.
>
> David

Is there any solution within the easy_install world?  I'm trying to
run a script (pinax) that calls it specifically so I'd have to do all
sorts of hacking to use pythonpkgmgr.


From rcdailey at gmail.com  Thu Aug  6 12:41:07 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 09:41:07 -0700 (PDT)
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
Message-ID: 

On Aug 6, 11:31?am, "Richard Brodie"  wrote:
> "Robert Dailey"  wrote in message
>
> news:29ab0981-b95d-4435-91bd-a7a520419ada at b15g2000yqd.googlegroups.com...
>
> > UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> > position 1650: character maps to 
>
> > The file is defined as ASCII.
>
> That's the problem: ASCII is a seven bit code. What you have is
> actually ISO-8859-1 (or possibly Windows-1252).
>
> The different ISO-8859-n variants assign various characters to
> to '\xa9'. Rather than being Western-European centric and assuming
> ISO-8859-1 by default, Python throws an error when you stray
> outside of strict ASCII.

Thanks for the help guys. Sorry I left out code, I wasn't sure at the
time if it would be helpful. Below is my code:


#========================================================
def GetFileContentsAsString( file ):
   f = open( file, mode='r', encoding='cp1252' )
   contents = f.read()
   f.close()
   return contents

#========================================================
def ReplaceVersion( file, version, regExps ):
   #match = regExps[0].search( 'FILEVERSION 1,45332,2100,32,' )
   #print( match.group() )
   text = GetFileContentsAsString( file )
   print( text )


As you can see, I am trying to load the file with encoding 'cp1252'
which, according to the python 3.1 docs, translates to windows-1252. I
also tried 'latin_1', which translates to ISO-8859-1, but this did not
work either. Am I doing something else wrong?


From rcdailey at gmail.com  Thu Aug  6 12:43:42 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 09:43:42 -0700 (PDT)
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
Message-ID: <35f72d0f-d659-423a-bea0-955092e02d15@d34g2000vbm.googlegroups.com>

On Aug 6, 11:12?am, Roman  wrote:
> On 06/08/09 08:35, Robert Dailey wrote:
>
>
>
>
>
> > Hey guys,
>
> > I'm creating a python script that is going to try to search a text
> > file for any text that matches my regular expression. The thing it is
> > looking for is:
>
> > FILEVERSION #,#,#,#
>
> > The # symbol represents any number that can be any length 1 or
> > greater. Example:
>
> > FILEVERSION 1,45,10082,3
>
> > The regex should only match the exact above. So far here's what I have
> > come up with:
>
> > re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
>
> > This works, but I was hoping for something a bit cleaner. I'm having
> > to create a special case portion of the regex for the last of the 4
> > numbers simply because it doesn't end with a comma like the first 3.
> > Is there a better, more compact, way to write this regex?
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Since there cannot be more than one "end of string" you can try this
> expression:
> re.compile( r'FILEVERSION (?:[0-9]+(,|$)){4}' )

I had thought of this but I can't use that either. I have to assume
that someone was silly and put text at the end somewhere, perhaps a
comment. Like so:

FILEVERSION 1,2,3,4     // This is the file version

It would be nice if there was a type of counter for regex. So you
could say 'match only 1 [^,]' or something like that...


From marduk at letterboxes.org  Thu Aug  6 12:45:43 2009
From: marduk at letterboxes.org (Albert Hopkins)
Date: Thu, 06 Aug 2009 12:45:43 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: <1249577143.6168.14.camel@centar>

On Thu, 2009-08-06 at 09:14 -0700, Robert Dailey wrote:
> Hello,
> 
> I'm loading a file via open() in Python 3.1 and I'm getting the
> following error when I try to print the contents of the file that I
> obtained through a call to read():
> 
> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
> 
> The file is defined as ASCII and the copyright symbol shows up just
> fine in Notepad++. However, Python will not print this symbol. How can
> I get this to work? And no, I won't replace it with "(c)". Thanks!

It's not actually ASCII but Windows-1252 extended ASCII-like.  So with
that information you can do either of 2 things: You can open it in text
mode and specify the encoding:

>>> fp = open(filename, 'r', encoding='windows-1252')
>>> s = fp.read()
>>> print(s)

or you can open it in binary mode and decode it later:

>>> fp = open(filename, 'rb')
>>> b = fp.read()
>>> print(str(b, encoding='windows-1252'))

Or you may be able to set the default encoding to windows-1252 but I
don't know how to do that (in Windows).

p.s.

Next time it might be helpful to paste a code snippet else we have to
make assumptions about what you are actually doing.



From R.Brodie at rl.ac.uk  Thu Aug  6 13:02:01 2009
From: R.Brodie at rl.ac.uk (Richard Brodie)
Date: Thu, 6 Aug 2009 18:02:01 +0100
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
	
Message-ID: 


"Robert Dailey"  wrote in message 
news:f64f9830-c416-41b1-a510-c1e486271b4e at g19g2000vbi.googlegroups.com...

> As you can see, I am trying to load the file with encoding 'cp1252'
> which, according to the python 3.1 docs, translates to windows-1252. I
> also tried 'latin_1', which translates to ISO-8859-1, but this did not
> work either. Am I doing something else wrong?

Probably it's just the debugging print that has a problem, and if you
opened an output file with an encoding specified it would be fine.
When you get a UnicodeEncodingError, it's conversion _from_
Unicode that has failed. 




From philip at semanchuk.com  Thu Aug  6 13:02:14 2009
From: philip at semanchuk.com (Philip Semanchuk)
Date: Thu, 6 Aug 2009 13:02:14 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: 
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
	
Message-ID: <1886EEEC-CFDA-40BD-8BAC-64015C4D3672@semanchuk.com>


On Aug 6, 2009, at 12:41 PM, Robert Dailey wrote:

> On Aug 6, 11:31 am, "Richard Brodie"  wrote:
>> "Robert Dailey"  wrote in message
>>
>> news:29ab0981-b95d-4435-91bd-a7a520419ada at b15g2000yqd.googlegroups.com 
>> ...
>>
>>> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
>>> position 1650: character maps to 
>>
>>> The file is defined as ASCII.
>>
>> That's the problem: ASCII is a seven bit code. What you have is
>> actually ISO-8859-1 (or possibly Windows-1252).
>>
>> The different ISO-8859-n variants assign various characters to
>> to '\xa9'. Rather than being Western-European centric and assuming
>> ISO-8859-1 by default, Python throws an error when you stray
>> outside of strict ASCII.
>
> Thanks for the help guys. Sorry I left out code, I wasn't sure at the
> time if it would be helpful. Below is my code:
>
>
> #========================================================
> def GetFileContentsAsString( file ):
>   f = open( file, mode='r', encoding='cp1252' )
>   contents = f.read()
>   f.close()
>   return contents
>
> #========================================================
> def ReplaceVersion( file, version, regExps ):
>   #match = regExps[0].search( 'FILEVERSION 1,45332,2100,32,' )
>   #print( match.group() )
>   text = GetFileContentsAsString( file )
>   print( text )
>
>
> As you can see, I am trying to load the file with encoding 'cp1252'
> which, according to the python 3.1 docs, translates to windows-1252. I
> also tried 'latin_1', which translates to ISO-8859-1, but this did not
> work either. Am I doing something else wrong?


Are you getting the error when you read the file or when you  
print(text)?

As a side note, you should probably use something other than "file"  
for the parameter name in GetFileContentsAsString() since file() is a  
Python function.






From kosta.koeman at gmail.com  Thu Aug  6 13:27:56 2009
From: kosta.koeman at gmail.com (Kosta)
Date: Thu, 6 Aug 2009 10:27:56 -0700 (PDT)
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> 
	
	
	
Message-ID: <1a236d86-72de-4b43-bc7b-cf0c9bdab615@u38g2000pro.googlegroups.com>

On Aug 6, 3:57?am, David Cournapeau  wrote:
> On Thu, Aug 6, 2009 at 12:39 AM, Kosta wrote:
>
> > Setenv.bat sets up the path and other environment variables build.exe
> > needs to compile and link (and even binplace) its utilities. ?So
> > building itself is not the issue. ?The problem is that if I call
> > setenv.bat from Python and then build.exe, but the modifications to
> > the path (and other environment settings) are not seen by Python, so
> > the attempt to build without a specified path fails.
>
> It sounds like you do not propagate the environment when calling
> setenv.bat from python. There is an option to do so in
> subprocess.Popen init method, or you can define your own environment
> if you do not want to propagate the whole environment (but this is
> often difficult to avoid for build environment in my experience,
> expecially if you don't have access to the sources of the whole system
> to check which variables are necessary).
>
> David

David,

Thanks you.  I looked up the docs on Popen (http://docs.python.org/
library/subprocess.html) where I read:

On Windows: the Popen class uses CreateProcess() to execute the child
program, which operates on strings. If args is a sequence, it will be
converted to a string using the list2cmdline() method. Please note
that not all MS Windows applications interpret the command line the
same way: list2cmdline() is designed for applications using the same
rules as the MS C runtime.

My interpretation of the above (and your email) is that using Popen
allows one to pass the Python environment to a child processs (in my
case, setenv.bat).   I need the reverse, to propagate from the child
to the parent.

Thanks,
Kosta



From ladasky at my-deja.com  Thu Aug  6 13:36:40 2009
From: ladasky at my-deja.com (John Ladasky)
Date: Thu, 6 Aug 2009 10:36:40 -0700 (PDT)
Subject: Overlap in python
References: 
	<4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> 
	
Message-ID: <900c8420-fc28-41d2-8720-518fc48763db@v15g2000prn.googlegroups.com>

On Aug 4, 3:21?pm, Jay Bird  wrote:
> Hi everyone,
>
> I wanted to thank you all for your help and *excellent* discussion. ?I
> was able to utilize and embed the script by Grigor Lingl in the 6th
> post of this discussion to get my program to work very quickly (I had
> to do about 20 comparisons per data bin, with over 40K bins in
> total). ?I am involved in genomic analysis research and this problem
> comes up a lot and I was surprised to not have been able to find a
> clear way to solve it. ?I will also look through all the tips in this
> thread, I have a feeling they may come in handy for future use!
>
> Thank you again,
> Jay

Hi Jay,

I know this is a bit off-topic, but how does this pertain to genomic
analysis?  Are you counting the lengths of microsatellite repeats or
something?


From steve at REMOVE-THIS-cybersource.com.au  Thu Aug  6 13:39:10 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 06 Aug 2009 17:39:10 GMT
Subject: Unexpected side-effects of assigning to sys.modules[__name__]
Message-ID: <028b05d5$0$5185$c3e8da3@news.astraweb.com>

Given this module:

#funny.py
import sys
print "Before:"
print "  __name__ =", __name__
print "  sys.modules[__name__] =", sys.modules[__name__]
sys.modules[__name__] = 123
print "After:"
print "  __name__ =", __name__
print "  sys =", sys


when I run it I get these results:


[steve at sylar python]$ python2.6 funny.py
Before:
  __name__ = __main__
  sys.modules[__name__] = 
After:
  __name__ = None
  sys = None



I'm completely perplexed by this behaviour. sys.modules() seems to be a 
regular dict, at least according to type(), and yet assigning to an item 
of it seems to have unexpected, and rather weird, side-effects.

What am I missing?



-- 
Steven


From nobody at nowhere.com  Thu Aug  6 13:50:23 2009
From: nobody at nowhere.com (Nobody)
Date: Thu, 06 Aug 2009 18:50:23 +0100
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
Message-ID: 

On Thu, 06 Aug 2009 17:02:44 +0100, MRAB wrote:

> The character class \d is equivalent to [0-9]

Not for Unicode, which is the default in 3.x.



From nobody at nowhere.com  Thu Aug  6 13:58:10 2009
From: nobody at nowhere.com (Nobody)
Date: Thu, 06 Aug 2009 18:58:10 +0100
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
Message-ID: 

On Thu, 06 Aug 2009 08:35:57 -0700, Robert Dailey wrote:

> I'm creating a python script that is going to try to search a text
> file for any text that matches my regular expression. The thing it is
> looking for is:
> 
> FILEVERSION #,#,#,#
> 
> The # symbol represents any number that can be any length 1 or
> greater. Example:
> 
> FILEVERSION 1,45,10082,3
> 
> The regex should only match the exact above. So far here's what I have
> come up with:
> 
> re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )

[0-9]+ allows any number of leading zeros, which is sometimes undesirable.
Using:

	(0|[1-9][0-9]*)

is more robust.



From jeanmichel at sequans.com  Thu Aug  6 14:01:42 2009
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Thu, 06 Aug 2009 20:01:42 +0200
Subject: Unexpected side-effects of assigning to sys.modules[__name__]
In-Reply-To: <028b05d5$0$5185$c3e8da3@news.astraweb.com>
References: <028b05d5$0$5185$c3e8da3@news.astraweb.com>
Message-ID: <4A7B1A86.8040609@sequans.com>

Steven D'Aprano wrote:
> Given this module:
>
> #funny.py
> import sys
> print "Before:"
> print "  __name__ =", __name__
> print "  sys.modules[__name__] =", sys.modules[__name__]
> sys.modules[__name__] = 123
> print "After:"
> print "  __name__ =", __name__
> print "  sys =", sys
>
>
> when I run it I get these results:
>
>
> [steve at sylar python]$ python2.6 funny.py
> Before:
>   __name__ = __main__
>   sys.modules[__name__] = 
> After:
>   __name__ = None
>   sys = None
>
>
>
> I'm completely perplexed by this behaviour. sys.modules() seems to be a 
> regular dict, at least according to type(), and yet assigning to an item 
> of it seems to have unexpected, and rather weird, side-effects.
>
> What am I missing?
>
>
>
>   
Maybe when you assign 123 to sys.modules[__name__], you've removed the 
last reference on  and it is 
garbaged. You are then loosing all your initial namespace.


try this one:
#funny.py
import sys
print "Before:"
print "  __name__ =", __name__
print "  sys.modules[__name__] =", sys.modules[__name__]
foo = sys.modules[__name__] # backup ref for the garbage collector
sys.modules[__name__] = 123
print "After:"
print "  __name__ =", __name__
print "  sys =", sys

Jean-Michel




From thorsten at thorstenkampe.de  Thu Aug  6 14:05:52 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Thu, 6 Aug 2009 20:05:52 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
Message-ID: 

* Michael Str?der (Thu, 06 Aug 2009 18:26:09 +0200)
> Thorsten Kampe wrote:
> > * Michael Str?der (Wed, 05 Aug 2009 16:43:09 +0200)
> > I don't think any measurable speed increase will be noticeable
> > between those two.
> 
> Well, seems not to be true. Try yourself. I did (my console has UTF-8 as charset):
> 
> Python 2.6 (r26:66714, Feb  3 2009, 20:52:03)
> [GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import timeit
> >>> timeit.Timer("'???????'.decode('utf-8')").timeit(1000000)
> 7.2721178531646729
> >>> timeit.Timer("'???????'.decode('utf8')").timeit(1000000)
> 7.1302499771118164
> >>> timeit.Timer("unicode('???????','utf8')").timeit(1000000)
> 8.3726329803466797
> >>> timeit.Timer("unicode('???????','utf-8')").timeit(1000000)
> 1.8622009754180908
> >>> timeit.Timer("unicode('???????','utf8')").timeit(1000000)
> 8.651669979095459
> >>>
> 
> Comparing again the two best combinations:
> 
> >>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
> 17.23644495010376
> >>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
> 72.087096929550171
> 
> That is significant! So the winner is:
> 
> unicode('???????','utf-8')

Unless you are planning to write a loop that decodes "???????" one 
million times, these benchmarks are meaningless.

Thorsten


From nobody at nowhere.com  Thu Aug  6 14:08:26 2009
From: nobody at nowhere.com (Nobody)
Date: Thu, 06 Aug 2009 19:08:26 +0100
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: 

On Thu, 06 Aug 2009 09:14:08 -0700, Robert Dailey wrote:

> I'm loading a file via open() in Python 3.1 and I'm getting the
> following error when I try to print the contents of the file that I
> obtained through a call to read():
> 
> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
> 
> The file is defined as ASCII and the copyright symbol shows up just
> fine in Notepad++. However, Python will not print this symbol. How can
> I get this to work? And no, I won't replace it with "(c)". Thanks!

1. As others have said, your file *isn't* ASCII, but that isn't the
problem.

2. The problem is that the encoding which your standard output
stream uses doesn't have the copyright symbol. You need to use something
like:

sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'iso-8859-1')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'iso-8859-1')

to fix the encoding of the stdout and stderr streams.



From python-url at phaseit.net  Thu Aug  6 14:21:58 2009
From: python-url at phaseit.net (Gabriel Genellina)
Date: Thu, 6 Aug 2009 18:21:58 +0000 (UTC)
Subject: Python-URL! - weekly Python news and links (Aug  6)
Message-ID: 

QOTW:  "The economy rises and falls, money comes and goes, but a great
conference has permanent good effects.  Well, a lot more permanent than
government fiscal policy, anyway." - Python Software Foundation Director
"bitter-in-victory-gracious-in-defeat-ly y'rs" timbot

    
    Is python free of "buffer overflow" errors?
        http://groups.google.com/group/comp.lang.python/t/a31faac6feced289/

    Lessons learned in implementation of a write-once dict:
        http://groups.google.com/group/comp.lang.python/t/bc8b91669257e246/

    Methods, attributes, iterators, lambdas, and how Ruby handles them:
        http://groups.google.com/group/comp.lang.python/t/6e4fc61946513405/

    Python 3 allows for custom types to be used as a class namespace 
    not just dicts):
        http://groups.google.com/group/comp.lang.python/t/50caadd10d2cca16/

    Could Python be used to write a device driver?
        http://groups.google.com/group/comp.lang.python/t/4efc28f9fe45b69e/

    The various meanings of the underscore character '_' in identifiers:
        http://groups.google.com/group/comp.lang.python/t/e32d577ad3d5a208/

    Generate a new object each time a name is imported:
        http://groups.google.com/group/comp.lang.python/t/b7112f74e2efa8bd/

    heapq.nlargest takes a "key" argument - why not the other functions in
    the same module?
        http://groups.google.com/group/comp.lang.python/t/a5095d3f4b54f79b/

    Immutable objects and how they could improve concurrency [old thread,
    still alive]:
        http://groups.google.com/group/comp.lang.python/t/cb0cf56c52321ccc/5c82cd09767ba85a?#5c82cd09767ba85a

    How to modify a variable in an outer (non global) scope:
        http://groups.google.com/group/comp.lang.python/t/e0e64250bd82825f/

    Best way to add "private" directories to sys.path:
        http://groups.google.com/group/comp.lang.python/t/cb43cf90d72f6833/

    Interval arithmetic:
        http://groups.google.com/group/comp.lang.python/t/71f050d8f5987244/

    Ensure that no more than three instances of the same program are
    running at the same time:
        http://groups.google.com/group/comp.lang.python/t/af7ae6429c2bda1e/

    Some people don't like the way Python documentation is managed/presented:
        http://groups.google.com/group/comp.lang.python/t/a52b22cd90b15ef8/
    
    
========================================================================
Everything Python-related you want is probably one or two clicks away in
these pages:

    Python.org's Python Language Website is the traditional
    center of Pythonia
        http://www.python.org
    Notice especially the master FAQ
        http://www.python.org/doc/FAQ.html

    PythonWare complements the digest you're reading with the
    marvelous daily python url
         http://www.pythonware.com/daily

    Just beginning with Python?  This page is a great place to start:
	http://wiki.python.org/moin/BeginnersGuide/Programmers

    The Python Papers aims to publish "the efforts of Python enthusiasts":
	http://pythonpapers.org/
    The Python Magazine is a technical monthly devoted to Python:
	http://pythonmagazine.com

    Readers have recommended the "Planet" sites:
	http://planetpython.org
	http://planet.python.org

    comp.lang.python.announce announces new Python software.  Be
    sure to scan this newsgroup weekly.
        http://groups.google.com/group/comp.lang.python.announce/topics

    Python411 indexes "podcasts ... to help people learn Python ..."
    Updates appear more-than-weekly:
        http://www.awaretek.com/python/index.html

    The Python Package Index catalogues packages.
        http://www.python.org/pypi/

    Much of Python's real work takes place on Special-Interest Group
    mailing lists
        http://www.python.org/sigs/

    Python Success Stories--from air-traffic control to on-line
    match-making--can inspire you or decision-makers to whom you're
    subject with a vision of what the language makes practical.
        http://www.pythonology.com/success

    The Python Software Foundation (PSF) has replaced the Python
    Consortium as an independent nexus of activity.  It has official
    responsibility for Python's development and maintenance.
        http://www.python.org/psf/
    Among the ways you can support PSF is with a donation.
        http://www.python.org/psf/donations/

    The Summary of Python Tracker Issues is an automatically generated
    report summarizing new bugs, closed ones, and patch submissions. 
        http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date

    Although unmaintained since 2002, the Cetus collection of Python
    hyperlinks retains a few gems.
        http://www.cetus-links.org/oo_python.html

    Python FAQTS
        http://python.faqts.com/

    The Cookbook is a collaborative effort to capture useful and
    interesting recipes.
	http://code.activestate.com/recipes/langs/python/

    Many Python conferences around the world are in preparation.
    Watch this space for links to them.

    Among several Python-oriented RSS/RDF feeds available, see:
        http://www.python.org/channews.rdf
    For more, see:
        http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all
    The old Python "To-Do List" now lives principally in a
    SourceForge reincarnation.
        http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse
	http://www.python.org/dev/peps/pep-0042/

    del.icio.us presents an intriguing approach to reference commentary.
    It already aggregates quite a bit of Python intelligence.
        http://del.icio.us/tag/python

    Enjoy the *Python Magazine*.
	http://pymag.phparch.com/

    *Py: the Journal of the Python Language*
        http://www.pyzine.com

    Dr.Dobb's Portal is another source of Python news and articles:
        http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python
    and Python articles regularly appear at IBM DeveloperWorks:
        http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8

Previous - (U)se the (R)esource, (L)uke! - messages are listed here:
  http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date
  http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d&
  http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes

There is *not* an RSS for "Python-URL!"--at least not yet.  Arguments
for and against are occasionally entertained.


Suggestions/corrections for next week's posting are always welcome.
E-mail to  should get through.

To receive a new issue of this posting in e-mail each Monday morning
(approximately), ask  to subscribe.  Mention
"Python-URL!".  Write to the same address to unsubscribe.


-- The Python-URL! Team--

Phaseit, Inc. (http://phaseit.net) is pleased to participate in and
sponsor the "Python-URL!" project.  Watch this space for upcoming
news about posting archives.


From rt8396 at gmail.com  Thu Aug  6 14:33:06 2009
From: rt8396 at gmail.com (r)
Date: Thu, 6 Aug 2009 11:33:06 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
Message-ID: <2eaf5b79-dc0a-4762-9f06-5de7e22381a2@r38g2000yqn.googlegroups.com>

On Aug 6, 11:20?am, Paul Rubin  wrote:
...(snip)
> There is something similar with the PostgreSQL docs. ?There is also
> Real World Haskell (http://book.realworld.haskell.org) which has a lot
> of interspersed user comments. ?It would be cool if Python's doc site
> did something like it too.

hear! hear!


From kee at kagi.com  Thu Aug  6 14:36:31 2009
From: kee at kagi.com (Kee Nethery)
Date: Thu, 6 Aug 2009 11:36:31 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
Message-ID: 

As someone trying to learn the language I want to say that the tone on  
this list towards people who are trying to learn Python  feels like it  
has become anti-newbies.

Learning a new language is difficult enough without seeing other  
newbies getting shamed for not knowing everything there is to know  
about Python before asking their questions.

For example, the guy who was looking for Python sample code for the  
Google Map API, calling him a troll was harsh. Suggesting he broach  
the question to Google was a reasonable answer. By the same token, his  
asking this list about the missing Python examples seems reasonable  
also. Seems to me that people on a Python list might have some  
background knowledge or even samples of the Google Python code that  
was no longer on the Google web site.

There seems to be a general consensus among the newbies that other  
languages have a user contributions resource tied to the main official  
docs to allow newbies to teach each other what they have learned. The  
desire is for python.org to have the same kind of support resource so  
that us newbies can self support each other.

Kee Nethery


From dioxide.software at gmail.com  Thu Aug  6 14:49:26 2009
From: dioxide.software at gmail.com (KK)
Date: Thu, 6 Aug 2009 11:49:26 -0700 (PDT)
Subject: pylucene installation problem on Ubuntu 9.04
Message-ID: 

hi all,
I've trying to install pylucene on my linux box from last 2 days but
not able to do so. first i tried to install it using apt-get like
this,
kk-laptop$ sudo apt-get install pylucene
and it did install python2.5, python2.5-minimal and pylucene. I must
mention one thing that I already had python2.6 on my box as the
default python i.e /usr/bin/python is linked to python2.6. Anyway s,
now i started the python interpreter using "python" command from cli
and then to make sure pylucene has been installed i tried to import
the module and to my surprise it said "module pylucene not found".
I thought I should enter the python2.6 env and do the same , so i
tried starting the python2.6 interpreter using "python2.6" as the
command and tried importing the same module and again it failed giving
the same irritating message.
 As a final try i pulled the source code of pylucene and as per the
comments given there in the README file, copied the mentioned files to
site-packages directory of python2.6 and then tried importing the
module and then got the same error message saying no module name
pylucene is present. I'm sick of this error !
Can someone point me what is the issue? If it is due to multiple
version of python running on box, can someone tell me which one to
remove or someone tell me how to get the whole thing running? I'll
very much thankful to you guys.

Thanks,
KK.


From martin.hellwig at dcuktec.org  Thu Aug  6 14:50:30 2009
From: martin.hellwig at dcuktec.org (Martin P. Hellwig)
Date: Thu, 06 Aug 2009 19:50:30 +0100
Subject: Parsing Binary Structures; Is there a better way / What is your
	way?
In-Reply-To: 
References: 
Message-ID: 

Thanks all for your insights and suggestions.
It seems to me that there are a couple of ways to this bit manipulation 
and a couple of foreign modules to assist you with that.

Would it be worth the while to do a PEP on this?
Personally I think that it would be nice to have a standard module in 
Python for this but perhaps there is a good reason that there isn't 
already one.

-- 
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'


From piet at cs.uu.nl  Thu Aug  6 14:58:13 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Thu, 06 Aug 2009 20:58:13 +0200
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com>
	
	
	
	<1a236d86-72de-4b43-bc7b-cf0c9bdab615@u38g2000pro.googlegroups.com>
Message-ID: 

>>>>> Kosta  (K) wrote:

>K> My interpretation of the above (and your email) is that using Popen
>K> allows one to pass the Python environment to a child processs (in my
>K> case, setenv.bat).   I need the reverse, to propagate from the child
>K> to the parent.

I don't think there is any modern OS that allows that. Unless you use
your own protocol of course, like letting the child write the
environment to its stdout and reading and interpreting it in the parent.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From wescpy at gmail.com  Thu Aug  6 15:14:21 2009
From: wescpy at gmail.com (Wesley Chun)
Date: Thu, 6 Aug 2009 12:14:21 -0700 (PDT)
Subject: Python docs disappointing
References: 
Message-ID: <1fcc79a2-692a-4744-a3e4-122394e3dad9@a39g2000pre.googlegroups.com>

On Jul 31, 1:10?pm, kj  wrote:
> I'm pretty new to Python, and I like a lot overall, but I find the
> documentation for Python rather poor, overall.
>
> I'm sure that Python experts don't have this problem:


kj,

welcome to Python! i'm sorry that you find the documentation lacking.
the one thing about the docs is that they're just pointers to get you
started and aren't very comprehensive. there are plenty of good online
tutorials out there as well as books. in fact, one of my main
motivations for writing "Core Python Programming" was because when i
learned Python 13 years ago, the online docs were enough to get me
started but did not have enough info to help me become an intermediate
Python programmer. there were only *2*(!) Python books out there, and
they were special-topic oriented, not ones to learn the language from.
it took almost a year and a half to write, but from what i hear from
readers and what has been said in reviews, it's pretty comprehensive,
and is a good book to learn Python from. i only wish that *i* had it
when i was learning!

Most "Python experts" do not have the entire language memorized, so
everyone has to look at the docs from time-to-time, not just
beginners. i'll either hit up http://docs.python.org/library/MODULE.html
or flip open my Nutshell or PER references, and finally, i'll google
if i have to (rare). the Python docs are the language manuals and not
necessarily full reference texts, so you have to just take them for
what they are.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


From martin at v.loewis.de  Thu Aug  6 15:14:41 2009
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Thu, 06 Aug 2009 21:14:41 +0200
Subject: Character encoding & the copyright symbol
In-Reply-To: 
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>		
	
Message-ID: <4A7B2BA1.2020002@v.loewis.de>

> As a side note, you should probably use something other than "file" for
> the parameter name in GetFileContentsAsString() since file() is a Python
> function.

Python 3.1.1a0 (py3k:74094, Jul 19 2009, 13:39:42)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
py> file
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'file' is not defined

Regards,
Martin



From piet at cs.uu.nl  Thu Aug  6 15:17:16 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Thu, 06 Aug 2009 21:17:16 +0200
Subject: Web page data and urllib2.urlopen
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
	
Message-ID: 

>>>>> Dave Angel  (DA) wrote:

>DA> Massi wrote:
>>> Hi everyone, I'm using the urllib2 library to get the html source code
>>> of web pages. In general it works great, but I'm having to do with a
>>> financial web site which does not provide the souce code I expect. As
>>> a matter of fact if you try:
>>> 
>>> import urllib2
>>> res = urllib2.urlopen("http://www.marketwatch.com/story/mondays-
>>> biggest-gaining-and-declining-stocks-2009-07-27")
>>> page = res.read()
>>> print page
>>> 
>>> you will see that the printed code is very different from the one
>>> given, for example, by mozilla. Since I have really little knowledge
>>> in html I can't even understand if this is a python or html problem.
>>> Can anyone give me some help?
>>> Thanks in advance.
>>> 
>>> 
>DA> I don't think this is a Python issue, but a "raw read" versus an
>DA> interactive interpretation of a page.  The browser does lots more than a
>DA> single roundtrip defined by urlopen/read.

>DA> I also would love to see some explanation of what happens here, or a
>DA> pointer to a reference that would help me understand it.

>DA> I took the output of the read(), and formatted it, roughly, as html.  I
>DA> expected to find a refresh, which is the simplest way that one page can
>DA> cause a very different one to be loaded.
>DA>      

>DA> If Mozilla had seen a page with this line in an appropriate place, it'd
>DA> immediately begin loading the other page, at "someotherurl"  But there's no
>DA> such line.

>DA> Next, I looked for javascript.  The Mozilla page contains lots of
>DA> javascript, but there's none in the raw page.  So I can't explain Mozilla's
>DA> differences that way.

>DA> I did notice the link to /m/Content/mobile2.css, but I don' t know any way
>DA> a CSS file could cause the content to change, just the display.

>DA> All I can guess is that it has something to do with "browser type" or
>DA> cookies.  And that would make lots of sense if this was a cgi page.  But
>DA> the URL doesn't look like that, as it doesn't end in pl, py, asp, or any of
>DA> another dozen special suffixes.

>DA> Any hints, anybody???

If you look into the HTML that Firefox gets, there is a lot of
javascript in it.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From steve at REMOVE-THIS-cybersource.com.au  Thu Aug  6 15:17:30 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 06 Aug 2009 19:17:30 GMT
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
Message-ID: <028b1ce0$0$5185$c3e8da3@news.astraweb.com>

On Thu, 06 Aug 2009 20:05:52 +0200, Thorsten Kampe wrote:

> > That is significant! So the winner is:
> > 
> > unicode('???????','utf-8')
> 
> Unless you are planning to write a loop that decodes "???????" one
> million times, these benchmarks are meaningless.

What if you're writing a loop which takes one million different lines of 
text and decodes them once each?


>>> setup = 'L = ["abc"*(n%100) for n in xrange(1000000)]'
>>> t1 = timeit.Timer('for line in L: line.decode("utf-8")', setup)
>>> t2 = timeit.Timer('for line in L: unicode(line, "utf-8")', setup)
>>> t1.timeit(number=1)
5.6751680374145508
>>> t2.timeit(number=1)
2.6822888851165771


Seems like a pretty meaningful difference to me.



-- 
Steven


From philip at semanchuk.com  Thu Aug  6 15:20:48 2009
From: philip at semanchuk.com (Philip Semanchuk)
Date: Thu, 6 Aug 2009 15:20:48 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: <4A7B2BA1.2020002@v.loewis.de>
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>		
	
	<4A7B2BA1.2020002@v.loewis.de>
Message-ID: <45B3614D-01A3-4CC2-BB78-5B488BC74841@semanchuk.com>


On Aug 6, 2009, at 3:14 PM, Martin v. L?wis wrote:

>> As a side note, you should probably use something other than "file"  
>> for
>> the parameter name in GetFileContentsAsString() since file() is a  
>> Python
>> function.
>
> Python 3.1.1a0 (py3k:74094, Jul 19 2009, 13:39:42)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> py> file
> Traceback (most recent call last):
>  File "", line 1, in 
> NameError: name 'file' is not defined


Whooops, didn't know about that change from 2.x to 3.x. Thanks.



From joncle at googlemail.com  Thu Aug  6 15:38:48 2009
From: joncle at googlemail.com (Jon Clements)
Date: Thu, 6 Aug 2009 12:38:48 -0700 (PDT)
Subject: pylucene installation problem on Ubuntu 9.04
References: 
Message-ID: 

On 6 Aug, 19:49, KK  wrote:
> hi all,
> I've trying to install pylucene on my linux box from last 2 days but
> not able to do so. first i tried to install it using apt-get like
> this,
> kk-laptop$ sudo apt-get install pylucene
> and it did install python2.5, python2.5-minimal and pylucene. I must
> mention one thing that I already had python2.6 on my box as the
> default python i.e /usr/bin/python is linked to python2.6. Anyway s,
> now i started the python interpreter using "python" command from cli
> and then to make sure pylucene has been installed i tried to import
> the module and to my surprise it said "module pylucene not found".
> I thought I should enter the python2.6 env and do the same , so i
> tried starting the python2.6 interpreter using "python2.6" as the
> command and tried importing the same module and again it failed giving
> the same irritating message.
> ?As a final try i pulled the source code of pylucene and as per the
> comments given there in the README file, copied the mentioned files to
> site-packages directory of python2.6 and then tried importing the
> module and then got the same error message saying no module name
> pylucene is present. I'm sick of this error !
> Can someone point me what is the issue? If it is due to multiple
> version of python running on box, can someone tell me which one to
> remove or someone tell me how to get the whole thing running? I'll
> very much thankful to you guys.
>
> Thanks,
> KK.

If you installed using apt, have you a pylucene directory under /usr/
local/lib/python2.6/dist-packages/?

Also, if you run python, and import sys; print sys.path
whats it show?

Jon.


From benjamin.kaplan at case.edu  Thu Aug  6 15:48:27 2009
From: benjamin.kaplan at case.edu (Benjamin Kaplan)
Date: Thu, 6 Aug 2009 15:48:27 -0400
Subject: pylucene installation problem on Ubuntu 9.04
In-Reply-To: 
References: 
Message-ID: 

On Thu, Aug 6, 2009 at 2:49 PM, KK wrote:
>
> kk-laptop$ sudo apt-get install pylucene
> and it did install python2.5, python2.5-minimal and pylucene. I must
> mention one thing that I already had python2.6 on my box as the
> default python i.e /usr/bin/python is linked to python2.6. Anyway s,
> now i started the python interpreter using "python" command from cli
> and then to make sure pylucene has been installed i tried to import
> the module and to my surprise it said "module pylucene not found".
> I thought I should enter the python2.6 env and do the same , so i
> tried starting the python2.6 interpreter using "python2.6" as the
> command and tried importing the same module and again it failed giving
> the same irritating message.

Pylucene seems to have installed under Python 2.5. Python extensions
are only installed for one version of python and extensions that use C
may only work under one particular version. If you want to use that
package, run python2.5 from the command line and try importing it.


From benjamin.kaplan at case.edu  Thu Aug  6 15:54:26 2009
From: benjamin.kaplan at case.edu (Benjamin Kaplan)
Date: Thu, 6 Aug 2009 15:54:26 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: 
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
	
Message-ID: 

On Thu, Aug 6, 2009 at 12:41 PM, Robert Dailey wrote:
> On Aug 6, 11:31?am, "Richard Brodie"  wrote:
>> "Robert Dailey"  wrote in message
>>
>> news:29ab0981-b95d-4435-91bd-a7a520419ada at b15g2000yqd.googlegroups.com...
>>
>> > UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
>> > position 1650: character maps to 
>>
>> > The file is defined as ASCII.
>>
>> That's the problem: ASCII is a seven bit code. What you have is
>> actually ISO-8859-1 (or possibly Windows-1252).
>>
>> The different ISO-8859-n variants assign various characters to
>> to '\xa9'. Rather than being Western-European centric and assuming
>> ISO-8859-1 by default, Python throws an error when you stray
>> outside of strict ASCII.
>
> Thanks for the help guys. Sorry I left out code, I wasn't sure at the
> time if it would be helpful. Below is my code:
>
>
> #========================================================
> def GetFileContentsAsString( file ):
> ? f = open( file, mode='r', encoding='cp1252' )
> ? contents = f.read()
> ? f.close()
> ? return contents
>
> #========================================================
> def ReplaceVersion( file, version, regExps ):
> ? #match = regExps[0].search( 'FILEVERSION 1,45332,2100,32,' )
> ? #print( match.group() )
> ? text = GetFileContentsAsString( file )
> ? print( text )
>
>
> As you can see, I am trying to load the file with encoding 'cp1252'
> which, according to the python 3.1 docs, translates to windows-1252. I
> also tried 'latin_1', which translates to ISO-8859-1, but this did not
> work either. Am I doing something else wrong?

This is why we need code and full tracebacks. There's a good chance
that your error is on the print(text) line. That's because sys.stdout
is probably a byte stream without an encoding defined. When you try to
print your unicode string, Python has to convert it to a stream of
bytes. Python refuses to guess on the console encoding and just falls
back to ascii, the conversion fails, and you get your error. Try using
print( text.encode( 'cp1252' ) ) instead.
> --
> http://mail.python.org/mailman/listinfo/python-list
>


From aahz at pythoncraft.com  Thu Aug  6 15:55:57 2009
From: aahz at pythoncraft.com (Aahz)
Date: 6 Aug 2009 12:55:57 -0700
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com>
	
Message-ID: 

In article ,
Hendrik van Rooyen   wrote:
>
>Bit slow - but hey, nobody's perfect.

YM "pobody's nerfect" HTH HAND
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz


From aahz at pythoncraft.com  Thu Aug  6 16:16:33 2009
From: aahz at pythoncraft.com (Aahz)
Date: 6 Aug 2009 13:16:33 -0700
Subject: How to write replace string for object which will be substituted?
	[regexp]
References: 
	
Message-ID: 

In article ,
ryniek90   wrote:
>
>I started learning regexp, and some things goes well, but most of them 
>still not.

1) 'Some people, when confronted with a problem, think "I know, I'll use
regular expressions."  Now they have two problems.'
--Jamie Zawinski, comp.emacs.xemacs, 8/1997

2) If you really want to learn regexes, get a copy of _Mastering Regular
Expressions_ by Friedl (either 2nd or 3rd edition)
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz


From kosta.koeman at gmail.com  Thu Aug  6 16:19:31 2009
From: kosta.koeman at gmail.com (Kosta)
Date: Thu, 6 Aug 2009 13:19:31 -0700 (PDT)
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> 
	
	
	
	<1a236d86-72de-4b43-bc7b-cf0c9bdab615@u38g2000pro.googlegroups.com>
	
Message-ID: <4703dc01-a41a-4bcd-b225-9ef819105144@a39g2000pre.googlegroups.com>

On Aug 6, 11:58?am, Piet van Oostrum  wrote:
> >>>>> Kosta  (K) wrote:
> >K> My interpretation of the above (and your email) is that using Popen
> >K> allows one to pass the Python environment to a child processs (in my
> >K> case, setenv.bat). ? I need the reverse, to propagate from the child
> >K> to the parent.
>
> I don't think there is any modern OS that allows that. Unless you use
> your own protocol of course, like letting the child write the
> environment to its stdout and reading and interpreting it in the parent.
> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: p... at vanoostrum.org

Piet,

Yes you are correct.  Thinking more about parent/child processes and
what I am doing: opening a cmd window (its own process), starting up
Python (a child process), and then attempting to run setenv.bat (a
child process to Python), and yes I'm out of luck.


From davea at ieee.org  Thu Aug  6 16:26:11 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 16:26:11 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: <4A7B3C63.2050307@ieee.org>

Robert Dailey wrote:
> Hello,
>
> I'm loading a file via open() in Python 3.1 and I'm getting the
> following error when I try to print the contents of the file that I
> obtained through a call to read():
>
> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
>
> The file is defined as ASCII and the copyright symbol shows up just
> fine in Notepad++. However, Python will not print this symbol. How can
> I get this to work? And no, I won't replace it with "(c)". Thanks!
>
>   
I see others have alerted you to changes needed in stdout, which is 
ASCII coded by default.

But I wanted to comment on the (c) remark.  If you're in the US, that's 
the wrong abbreviation for copyright.  The only recognized abbreviation 
is (copr).

DaveA


From python at rcn.com  Thu Aug  6 16:47:13 2009
From: python at rcn.com (Raymond Hettinger)
Date: Thu, 6 Aug 2009 13:47:13 -0700 (PDT)
Subject: Subclassing Python's dict
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com> 
	
Message-ID: 

> Are you referring to Python 3.0? ?Python 2.6 does not have
> collections.UserDict

In Python2.6, it is in its own module.

    >>> from UserDict import UserDict


Raymond


From ryniek90 at gmail.com  Thu Aug  6 17:03:54 2009
From: ryniek90 at gmail.com (Ryniek90)
Date: Thu, 06 Aug 2009 23:03:54 +0200
Subject: How to write replace string for object which will be substituted?
	[regexp]
In-Reply-To: 
References: 
Message-ID: <4A7B453A.4050501@gmail.com>


> 2) If you really want to learn regexes, get a copy of _Mastering Regular
> Expressions_ by Friedl (either 2nd or 3rd edition)
>   

I made preview of that book, but some pages are disabled from preview. 
Has that book topics about Python regexp's?
If so, i must buy it.


From clp2 at rebertia.com  Thu Aug  6 17:08:15 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Thu, 6 Aug 2009 14:08:15 -0700
Subject: os.walk()
In-Reply-To: <75c8645a0908050849ua654ec1q6e9c8c83f412d7aa@mail.gmail.com>
References: <75c8645a0908041906s138c1499k59cd57d569a5c83e@mail.gmail.com>
	<50697b2c0908041948q31a30819g29e3d7f196e94074@mail.gmail.com>
	<75c8645a0908050849ua654ec1q6e9c8c83f412d7aa@mail.gmail.com>
Message-ID: <50697b2c0908061408p79316e22mc5a93f4b1ef17f04@mail.gmail.com>

> On Tue, Aug 4, 2009 at 10:48 PM, Chris Rebert  wrote:
>> On Tue, Aug 4, 2009 at 7:06 PM, Michael Savarese wrote:
>> > Greetings
>> > Python newbie here, and thanks to all who have helped me previously.
>> > Is there a way of grabbing file attributes while traversing with os.walk()?
>> > It would be advantageous to have date modified and file size along with the
>> > file name.
>> > If anyone can point me in the right direction, I'd appreciate it.
>>
>> Feed the path to os.stat(), and then use the `stat` module on the result:
>> http://docs.python.org/library/os.html#os.stat
>> http://docs.python.org/library/stat.html#module-stat

2009/8/5 Michael Savarese :
> Chris, thanks for the info.
> I'm a bit stuck here.
>
> am i close?

Yes, you just need to plug some more bricks together (as it were).

> import os, sys
> import os.path
>
> for root, dirs, files in os.walk('c:/Temp'):
>     for name in files:
>         statinfo=os.stat(name)
#see http://docs.python.org/library/os.path.html#os.path.join
        filepath = os.path.join(root, name)
        statinfo = os.stat(filepath)
>
>           print root,dirs,name,statinfo.st_size ; it gets stuck here, i guess it needs the full path.
>                                                                  is this where i use the join function to bring root, dirs, and filename together?
>                                                                  I kinda suck at that too, can you point me in the right direction?
>
> also:
>>>> statinfo.st_mtime
> 1247778166.6563497  can i have a hint on how to convert this?

That is the time represented in seconds since the (UNIX) epoch.
Use the functions in the `time` module to convert it to something more
palatable:
http://docs.python.org/library/time.html

Cheers,
Chris
-- 
http://blog.rebertia.com


From clp2 at rebertia.com  Thu Aug  6 17:09:28 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Thu, 6 Aug 2009 14:09:28 -0700
Subject: How to write replace string for object which will be substituted?
	[regexp]
In-Reply-To: <4A7B453A.4050501@gmail.com>
References: 
	<4A7B453A.4050501@gmail.com>
Message-ID: <50697b2c0908061409u2295f111l808f1eafc9142668@mail.gmail.com>

On Thu, Aug 6, 2009 at 2:03 PM, Ryniek90 wrote:
>> 2) If you really want to learn regexes, get a copy of _Mastering Regular
>> Expressions_ by Friedl (either 2nd or 3rd edition)
>>
>
> I made preview of that book, but some pages are disabled from preview. Has
> that book topics about Python regexp's?
> If so, i must buy it.

Yes, Python is among the language APIs covered.

Cheers,
Chris
-- 
http://blog.rebertia.com


From python at rcn.com  Thu Aug  6 17:18:14 2009
From: python at rcn.com (Raymond Hettinger)
Date: Thu, 6 Aug 2009 14:18:14 -0700 (PDT)
Subject: Subclassing Python's dict
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com> 
	
	
Message-ID: <3fadb25e-6457-4c2e-96a0-6d917ebba08b@2g2000prl.googlegroups.com>

> Xavier Ho wrote:
> > You should subclass collections.UserDict, and not the default dict class.
> > Refer to the collections module.
>
> Xavier, why do you think that is the correct approach? The docs say
> "The need for this class has been largely supplanted by the ability to
> subclass directly from dict (a feature that became available starting
> with Python version 2.2)."

UserDict can be a good choice because the pure python source makes
it clear exactly what needs to be overridden (you can see which
methods are implemented in terms of lower level methods and which
ones access the underlying dict directly.

Another choice is to use DictMixin or MutableMapping and fill-in just
the required abstract methods.  This approach is simple and
flexible.
It allows you to wrap a mapping interface around many different
classes
(a dbm for example).  The disadvantage is that it can be slow.

Subclassing a dict is typically done when the new class has to be
substitutable for real dicts (perhaps an API enforces a check
for instance(x, dict) or somesuch).  As the OP found out, the
dict methods all access the underlying structure directly, so
you will need to override *all* methods that need to have a new
behavior.  The remaining methods are inherited and run at C speed,
so performance may dictate this approach.

So, there you have three ways to do it.  In Py3.1, we used the latter
approach for collections.Counter() -- that gives a high speed on the
inherited methods.  For collections.OrderedDict, a hybrid approach
was used (subclassing from both dict and MutableMapping).  Most of
the work is done by MutableMapping and the dict is inherited so that
the OrderedDict objects would be substitutable anywhere regular
dicts are expected.  And IIRC, there are still some cases of UserDict
being used in the python source (situations where subclassing from
dict wouldn't work as well).


Raymond



From ethan at stoneleaf.us  Thu Aug  6 17:23:47 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Thu, 06 Aug 2009 14:23:47 -0700
Subject: Help with regex
In-Reply-To: 
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
Message-ID: <4A7B49E3.3000908@stoneleaf.us>

Nobody wrote:
> On Thu, 06 Aug 2009 08:35:57 -0700, Robert Dailey wrote:
> 
> 
>>I'm creating a python script that is going to try to search a text
>>file for any text that matches my regular expression. The thing it is
>>looking for is:
>>
>>FILEVERSION #,#,#,#
>>
>>The # symbol represents any number that can be any length 1 or
>>greater. Example:
>>
>>FILEVERSION 1,45,10082,3
>>
>>The regex should only match the exact above. So far here's what I have
>>come up with:
>>
>>re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
> 
> 
> [0-9]+ allows any number of leading zeros, which is sometimes undesirable.
> Using:
> 
> 	(0|[1-9][0-9]*)
> 
> is more robust.

You make a good point about possibly being undesirable, but I question 
the assertion that your solution is /more robust/.  If the OP 
wants/needs to match numbers even with leading zeroes your /more robust/ 
version fails.

~Ethan~



From nils at ccsg.de  Thu Aug  6 17:28:29 2009
From: nils at ccsg.de (Nils Ruettershoff)
Date: Thu, 06 Aug 2009 23:28:29 +0200
Subject: Seeding the rand() Generator
In-Reply-To: 
References: 			
	
Message-ID: <4A7B4AFD.9030808@ccsg.de>

Hi Fred,

I just saw your SQL Statement
> 	An example would be: SELECT first, second, third, fourth,
> fifth, sixth from sometable order by rand() limit 1
>
>   
and I feel  me  constrained to give you an advice. Don't use this SQL 
statement to pick up a random row, your user and maybe DBA would much 
appreciate it.
You are certainly asking why. Lets have a brief look what you are asking 
your mysql DB:

Fetch all rows from 'sometable', but only with attribute 'first, 
second,...' sort them all starting at 'random row' and afterward through 
anything away you did before, but the first line

If you have a table with 100000 rows you would fetch and sort up to 
100000 rows, pick up one row and discard up to 99999 rows. That sounds 
not very clever, right?

So please take a look at this site to get a better alternate way for 
that approach:

http://jan.kneschke.de/projects/mysql/order-by-rand/

if you want to know more please check this article too:

http://jan.kneschke.de/2007/2/22/analyzing-complex-queries

regards,

Nils



From bdezonia at wisc.edu  Thu Aug  6 17:57:00 2009
From: bdezonia at wisc.edu (BDZ)
Date: Thu, 6 Aug 2009 14:57:00 -0700 (PDT)
Subject: os.path.exists() and Samba shares
References: <42f0c423-657f-45fb-bec5-67dcdda9f4ad@a13g2000yqc.googlegroups.com>
	<3fdc924a-75ad-477a-be2e-6e42ce7bff0c@s15g2000yqs.googlegroups.com> 
	<337482f9-8ad9-4600-9cf4-39911f5368ac@h31g2000yqd.googlegroups.com> 
	
Message-ID: 

On Jul 31, 10:56?pm, "Gabriel Genellina" 
wrote:
> En Fri, 31 Jul 2009 13:33:45 -0300, BDZ  escribi?:
>
>
>
> > On Jul 30, 4:41?pm, Lo?c Domaign? 
> > wrote:
> >> > Hello. I have written a Python 3.1 script running on Windows that uses
> >> > os.path.exists() to connect to network shares. If the various network
> >> > shares require different user account and password combos than the
> >> > account the script is running under the routine returns false. I need
> >> > something like os.samba.path.exists(username,password,path). Does
> >> > anyone have a suggestion on how I can accomplish what I need to do in
> >> > Python?
>
> >> Could the Python Samba module PySamba be interesting for ?
> >> you?http://sourceforge.net/projects/pysamba/
>
> > Unfortunately, although it has the calls I'd want, pysamba appears to
> > be *nix only. I need something that will work under Windows. Is there
> > a set of Python Windows functions (official or contributed) that might
> > do what I need? (I'm new to Python)
>
> SAMBA is a Linux implementation of the SMB protocol, natively supported on
> Windows. You may use the pywin32 package (available on sourceforge.net) to
> call the WNetAddConnection2 Windows function:http://msdn.microsoft.com/en-us/library/aa385413(VS.85).aspx
>
> --
> Gabriel Genellina

The WNetAddConnection2 function under pywin32 seems to work. I am able
to make connections to various SMB network resources hosted by
Windows, Mac, and Linux boxes. It has the annoying side effect of
opening a connection.

There is a Win32 function called NetShareCheck. It sounds perfect. It
just checks that the share exists (no connection left open) and does
not require username or password. Unfortunately it fails for Mac and
Linux SMB resources. Just FYI.

I understand Samba and Windows SMB are not the same thing. What I was
hoping for when I investigated pySamba was to find a python module/
extension that supported a simple SMB interface and would run from any
host platform.


From python at mrabarnett.plus.com  Thu Aug  6 18:05:24 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 23:05:24 +0100
Subject: XML flaw
Message-ID: <4A7B53A4.2000508@mrabarnett.plus.com>

Hi all,

I've just read this article, which mentions Python:

XML flaw threatens millions of apps with DoS attacks
http://infoworld.com/print/86340

Something to worry about?


From steve at REMOVE-THIS-cybersource.com.au  Thu Aug  6 18:09:14 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 06 Aug 2009 22:09:14 GMT
Subject: Unexpected side-effects of assigning to sys.modules[__name__]
References: <028b05d5$0$5185$c3e8da3@news.astraweb.com>
	
Message-ID: <0004d7c9$0$2895$c3e8da3@news.astraweb.com>

On Thu, 06 Aug 2009 20:01:42 +0200, Jean-Michel Pichavant wrote:


> > I'm completely perplexed by this behaviour. sys.modules() seems to be
> > a regular dict, at least according to type(), and yet assigning to an
> > item of it seems to have unexpected, and rather weird, side-effects.
> >
> > What am I missing?
> >
> >
> >
> >
> Maybe when you assign 123 to sys.modules[__name__], you've removed the
> last reference on  and it is
> garbaged. You are then loosing all your initial namespace.

By Jove, I think you've got it! How obvious in hindsight. Thank you.





-- 
Steven


From davea at ieee.org  Thu Aug  6 18:17:02 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 18:17:02 -0400
Subject: Web page data and urllib2.urlopen
In-Reply-To: 
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>	
	
Message-ID: <4A7B565E.9000508@ieee.org>



Piet van Oostrum wrote:
> 
>> DA> If Mozilla had seen a page with this line in an appropriate place, it'd
>> DA> immediately begin loading the other page, at "someotherurl"  But there's no
>> DA> such line.
>>     
>
>   
>> DA> Next, I looked for javascript.  The Mozilla page contains lots of
>> DA> javascript, but there's none in the raw page.  So I can't explain Mozilla's
>> DA> differences that way.
>>     
>
>   
>> DA> I did notice the link to /m/Content/mobile2.css, but I don' t know any way
>> DA> a CSS file could cause the content to change, just the display.
>>     
>
>   
>> DA> All I can guess is that it has something to do with "browser type" or
>> DA> cookies.  And that would make lots of sense if this was a cgi page.  But
>> DA> the URL doesn't look like that, as it doesn't end in pl, py, asp, or any of
>> DA> another dozen special suffixes.
>>     
>
>   
>> DA> Any hints, anybody???
>>     
>
> If you look into the HTML that Firefox gets, there is a lot of
> javascript in it.
>   

But the raw page didn't have any javascript.  So what about that 
original raw page triggered additional stuff to be loaded?
Is it "user agent", as someone else brought out?  And is there somewhere 
I can read more about that aspect of things?  I've mostly built very 
static html pages, where the server yields the same page to everybody.  
And some form stuff, where the  user clicks on a 'submit" button to 
trigger a script that's not shown on the URL line.





From clp2 at rebertia.com  Thu Aug  6 18:23:16 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Thu, 6 Aug 2009 15:23:16 -0700
Subject: XML flaw
In-Reply-To: <4A7B53A4.2000508@mrabarnett.plus.com>
References: <4A7B53A4.2000508@mrabarnett.plus.com>
Message-ID: <50697b2c0908061523k5ce10b8eldccd4089e6f70e63@mail.gmail.com>

On Thu, Aug 6, 2009 at 3:05 PM, MRAB wrote:
> Hi all,
>
> I've just read this article, which mentions Python:
>
> XML flaw threatens millions of apps with DoS attacks
> http://infoworld.com/print/86340
>
> Something to worry about?

More detailed article:
http://blogs.zdnet.com/open-source/?p=4609

Quote:
"If you own any of the following libraries you need to be alert and
ready to patch:
    * Python libexpat"
AKA xml.parsers.expat AKA pyexpat

The good news: "[a patch] is in process for Python."

Cheers,
Chris
-- 
http://blog.rebertia.com


From breamoreboy at yahoo.co.uk  Thu Aug  6 18:23:16 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Thu, 06 Aug 2009 23:23:16 +0100
Subject: XML flaw
In-Reply-To: <4A7B53A4.2000508@mrabarnett.plus.com>
References: <4A7B53A4.2000508@mrabarnett.plus.com>
Message-ID: 

MRAB wrote:
> Hi all,
> 
> I've just read this article, which mentions Python:
> 
> XML flaw threatens millions of apps with DoS attacks
> http://infoworld.com/print/86340
> 
> Something to worry about?
No.  Discussing letting Tom, Dick and Harriet loose on the Python 
documentaion is far more important than trivial issues like Denial of 
Service atacks via XML.

Sorry, just couldn't resist.

-- 
Kindest regards.

Mark Lawrence.



From REMpeteOVE at petezilla.co.uk  Thu Aug  6 19:04:46 2009
From: REMpeteOVE at petezilla.co.uk (Peter Chant)
Date: Fri, 07 Aug 2009 00:04:46 +0100
Subject: Setuptools - help!
Message-ID: 

Chaps,

any ideas, I'm floundering - I don't quite get it.  I have the following
files, setup.py and main.py in a directory pphoto:

# more setup.py
from setuptools import setup, find_packages
setup(
    name = "Pphoto",
    version = "0.1",
    packages = find_packages(),

    # other arguments here...
    entry_points = {'console_scripts': ['foo = pphoto.main:HelloWorld',]}


)

bash-3.1# more main.py


def HelloWorld():
    print "Hello World!"

print "Odd world"


>From various websites that should produce a script foo that runs HelloWorld. 
It does produce a script that simply crashes.

bash-3.1# foo
Traceback (most recent call last):
  File "/usr/bin/foo", line 8, in 
    load_entry_point('Pphoto==0.1', 'console_scripts', 'foo')()
  File "build/bdist.linux-i686/egg/pkg_resources.py", line 277, in
load_entry_point
  File "build/bdist.linux-i686/egg/pkg_resources.py", line 2098, in
load_entry_point
  File "build/bdist.linux-i686/egg/pkg_resources.py", line 1831, in load
ImportError: No module named pphoto.main
bash-3.1#            


Note, doing this as root as it seems not to do anything usefull at all if I
run python setup develop as a user. 

Any ideas?  I must be missing something fundamental?

Pete


-- 
http://www.petezilla.co.uk


From robert.kern at gmail.com  Thu Aug  6 19:17:26 2009
From: robert.kern at gmail.com (Robert Kern)
Date: Thu, 06 Aug 2009 18:17:26 -0500
Subject: Setuptools - help!
In-Reply-To: 
References: 
Message-ID: 

On 2009-08-06 18:04, Peter Chant wrote:
> Chaps,
>
> any ideas, I'm floundering - I don't quite get it.  I have the following
> files, setup.py and main.py in a directory pphoto:
>
> # more setup.py
> from setuptools import setup, find_packages
> setup(
>      name = "Pphoto",
>      version = "0.1",
>      packages = find_packages(),
>
>      # other arguments here...
>      entry_points = {'console_scripts': ['foo = pphoto.main:HelloWorld',]}
>
>
> )
>
> bash-3.1# more main.py
>
>
> def HelloWorld():
>      print "Hello World!"
>
> print "Odd world"
>
>
>> From various websites that should produce a script foo that runs HelloWorld.
> It does produce a script that simply crashes.
>
> bash-3.1# foo
> Traceback (most recent call last):
>    File "/usr/bin/foo", line 8, in
>      load_entry_point('Pphoto==0.1', 'console_scripts', 'foo')()
>    File "build/bdist.linux-i686/egg/pkg_resources.py", line 277, in
> load_entry_point
>    File "build/bdist.linux-i686/egg/pkg_resources.py", line 2098, in
> load_entry_point
>    File "build/bdist.linux-i686/egg/pkg_resources.py", line 1831, in load
> ImportError: No module named pphoto.main
> bash-3.1#
>
>
> Note, doing this as root as it seems not to do anything usefull at all if I
> run python setup develop as a user.
>
> Any ideas?  I must be missing something fundamental?

You need to put main.py into the pphoto package.

$ mkdir pphoto/
$ mv main.py pphoto/
$ touch pphoto/__init__.py

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From dfnsonfsduifb at gmx.de  Thu Aug  6 20:55:27 2009
From: dfnsonfsduifb at gmx.de (Johannes Bauer)
Date: Fri, 07 Aug 2009 02:55:27 +0200
Subject: Python3: Using sorted(key=...)
Message-ID: <7e1cbuF2dfhtoU1@mid.dfncis.de>

Hello list,

I'm having trouble with a incredibly simple sort of a list containing
ints and tuples:

def myorder(x):
	if type(x) == int:
		return x
	else:
		return x[0]

odata = sorted([ (a, b) for (a, b) in data["description"].items() ],
key=myorder)

still says:

Traceback (most recent call last):
  File "./genproto.py", line 81, in 
    odata = sorted([ (a, b) for (a, b) in data["description"].items() ],
key=myorder)
TypeError: unorderable types: tuple() < int()

Why is that? Am I missing something very obvious?

Kind regards,
Johannes

-- 
"Du bist einfach nur l?cherlich! Mit solchen albernen und hohlen S?tzen
kannst du mir nicht impr?gnieren."
-- Hobbycholeriker Jens Fittig aka Wolfgang Gerber in de.sci.electronics
                             <4a6f44d0$0$12481$9b622d9e at news.freenet.de>


From jabronson at gmail.com  Thu Aug  6 21:10:39 2009
From: jabronson at gmail.com (Joshua Bronson)
Date: Thu, 6 Aug 2009 18:10:39 -0700 (PDT)
Subject: heapq "key" arguments
References: <97932d10-8601-401f-bb69-a98db9036929@p15g2000vbl.googlegroups.com>
	
Message-ID: 

On Aug 3, 1:36?pm, Raymond Hettinger  wrote:
> [Joshua Bronson]:
>
> > According tohttp://docs.python.org/library/heapq.html, Python 2.5
> > added an optional "key" argument to heapq.nsmallest and
> > heapq.nlargest. I could never understand why they didn't also add a
> > "key" argument to the other relevant functions (heapify, heappush,
> > etc).
>
> The problem is that heapq acts on regular lists, so it does not
> have exclusive access to the structure. ?So, there is no reliable
> way for it to maintain a separate list of keys. ?Since the keys
> can't be saved in the structure (without possibly breaking other
> code), the fine grained heapq functions (like heappop and heappush)
> would need to call key functions every time they are invoked.
> This is at odds with the implicit guarantee of the key function
> that it will be called no more than once per key.
>
> The overall problem is one of granularity. ?A key function should
> be applied once in an initial pass, not on every call to a push/pop
> function. ?The everyday solution that most people use is to operate
> on a list of (key, record) tuples and let tuple comparison do the
> work for you. ?Another solution is to build a Heap class that does
> have exclusive access to the structure, but the API sugar often
> isn't worth the slightly weaker performance.
>
> One other thought. ?Heaps are a lazy evaluation structure, so their
> fined-grained mutation functions only work well with just a single
> ordering function, so there is not need to have (and every reason
> to avoid) changing key functions in mid-stream. ?IOW, the key
> function needs to be constant across all accesses. ?Contrast this
> with other uses of key functions where it makes perfect sense
> to run minage=min(data, key=attrgetter('age')) and then running
> minsal=min(data, key=attrgetter('salary')). ?The flexibility to
> change key functions just doesn't make sense in the context of
> the fine-grained heap functions.
>
> Accordingly, this is why I put key functions in nlargest() and
> nsmallest() but not in heappush() and friends. ?The former can
> guarantee no more than one key function call per entry and they
> evaluate immediately instead of lazily.
>
> Raymond


I see, that makes sense. Thanks for the great explanation.

Josh


From gagsl-py2 at yahoo.com.ar  Thu Aug  6 21:24:22 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 22:24:22 -0300
Subject: Help making this script better
References: <2f8e34ec-01aa-4ec4-9636-a8ec1f87c68c@o6g2000yqj.googlegroups.com>
Message-ID: 

En Thu, 06 Aug 2009 11:50:07 -0300, jakecjacobson  
 escribi?:

> After much Google searching and trial & error, I was able to write a
> Python script that posts XML files to a REST API using HTTPS and
> passing PEM cert & key file.  It seems to be working but would like
> some pointers on how to handle errors.  I am using Python 2.4, I don't
> have the capability to upgrade even though I would like to.  I am very
> new to Python so help will be greatly appreciated and I hope others
> can use this script.

Just a few remarks, mostly on style rather than functionality:

> #!/usr/bin/python
> #################################################################
> # catalog_feeder.py
> #################################################################
> # This sciript will process a directory of XML files and push them to
> the Enterprise Catalog.
> #  You configure this script by using a configuration file that
> describes the required variables.
> #  The path to this file is either passed into the script as a command
> line argument or hard coded
> #  in the script.  The script will terminate with an error if it can't
> process the XML file.
> #################################################################

Note that Python has "docstrings" - the __doc__ attribute attached to  
every module, class and function. The very first string in the  
module/function/class becomes its docstring. The interactive help system  
-and other tools like pydoc- can inspect and show such info.
The above comment could serve perfectly as this module's docstring - just  
remove all the #'s and enclose the whole text in """triple quotes"""  
(required as it spawns many lines).
By example, in that case you could print the text in your usage() function  
like this:
print __doc__

> 	try:
> 		# Process the XML conf file ....
> 		xmldoc = minidom.parse(c)
> 		catalog_host = readConfFile(xmldoc, 'catalog_host')
> 		catalog_port = int(readConfFile(xmldoc, 'catalog_port'))
> 		catalog_path = readConfFile(xmldoc, 'catalog_path')
> 		collection_name = readConfFile(xmldoc, 'collection_name')
> 		cert_file = readConfFile(xmldoc, 'cert_file')
> 		key_file = readConfFile(xmldoc, 'key_file')
> 		log_file = readConfFile(xmldoc, 'log_file')
> 		input_dir = readConfFile(xmldoc, 'input_dir')
> 		archive_dir = readConfFile(xmldoc, 'archive_dir')
> 		hold_dir = readConfFile(xmldoc, 'hold_dir')
> 	except Exception, inst:
> 		# I had an error so report it and exit script
> 		print "Unexpected error opening %s: %s" % (c, inst)
> 		sys.exit(1)

Ok, an unexpected error: but *which* one? doing exactly *what*? You're  
hiding important information (the error type, the full traceback, the  
source line that raised the error...) that's very valuable when something  
goes wrong and you have to determine what happened.
In this case, you're adding a bit of information: the name of the file  
being processed. That's good. But at the same time, hiding all the other  
info, and that's not so good. What about this:

	except Exception:
		print >>sys.stderr, "Unexpected error opening %s" % c
		raise

The final raise will propagate the exception; by default, Python will  
print the exception type, the exception value, the full traceback  
including source lines, and exit the script with a status code of 1. The  
same effect that you intended, but more complete.

In other cases, where you don't have anything to add to the default  
exception handling, the best thing to do is: nothing. That is, don't catch  
an exception unless you have something good to do with it. (Exceptions  
aren't Pok?mon: you don't have to "catch 'em all!")

> 	# Log Starting
> 	logOut = verifyLogging(log_file)
> 	if logOut:
> 		log(logOut, "Processing Started ...")

I would move the decision into the log function (that is, just write  
log("something") and make the log function decide whether to write to file  
or not). For your next script, look at the logging module:  
http://docs.python.org/library/logging.html

> # Get an arry of files from the input_dir
> def getFiles2Post(d):
> 	return (os.listdir(d))

Note that return isn't a function but a statement. You don't need the  
outer (). Also, using a docstring instead of a comment:

def getFiles2Post(input_dir):
     "Return the list of files in input_dir to process"
     return os.listdir(input_dir)

> # Read out the conf file and set the needed global variable
> def readConfFile(xmldoc, tag):
> 	return (xmldoc.getElementsByTagName(tag)[0].firstChild.data)

Same as above. Which "needed global variable"?

> def cleanup(logOut):
>       [...]	sys.exit(0)

Exiting the script from everywhere makes it harder to reuse some of its  
functions later. Just return the desired status code to the caller, which  
in turn will return to main(), until it gets to the outermost level, which  
is the only place I'd use sys.exit()

-- 
Gabriel Genellina



From michael at stroeder.com  Thu Aug  6 21:25:03 2009
From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=)
Date: Fri, 07 Aug 2009 03:25:03 +0200
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
Message-ID: 

Thorsten Kampe wrote:
> * Michael Str?der (Thu, 06 Aug 2009 18:26:09 +0200)
>>>>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
>> 17.23644495010376
>>>>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
>> 72.087096929550171
>>
>> That is significant! So the winner is:
>>
>> unicode('???????','utf-8')
> 
> Unless you are planning to write a loop that decodes "???????" one 
> million times, these benchmarks are meaningless.

Well, I can tell you I would not have posted this here and checked it if it
would be meaningless for me. You don't have to read and answer this thread if
it's meaningless to you.

Ciao, Michael.


From sjmachin at lexicon.net  Thu Aug  6 21:27:51 2009
From: sjmachin at lexicon.net (John Machin)
Date: Thu, 6 Aug 2009 18:27:51 -0700 (PDT)
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
	
Message-ID: 

On Aug 7, 7:23?am, Ethan Furman  wrote:
> Nobody wrote:
> > On Thu, 06 Aug 2009 08:35:57 -0700, Robert Dailey wrote:
>
> >>I'm creating a python script that is going to try to search a text
> >>file for any text that matches my regular expression. The thing it is
> >>looking for is:
>
> >>FILEVERSION #,#,#,#
>
> >>The # symbol represents any number that can be any length 1 or
> >>greater. Example:
>
> >>FILEVERSION 1,45,10082,3
>
> >>The regex should only match the exact above. So far here's what I have
> >>come up with:
>
> >>re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
>
> > [0-9]+ allows any number of leading zeros, which is sometimes undesirable.
> > Using:
>
> > ? ?(0|[1-9][0-9]*)
>
> > is more robust.
>
> You make a good point about possibly being undesirable, but I question
> the assertion that your solution is /more robust/. ?If the OP
> wants/needs to match numbers even with leading zeroes your /more robust/
> version fails.

I'd go further: the OP would probably be better off matching anything
that looked vaguely like an attempt to produce what he wanted e.g.
r"FILEVERSION\s*[0-9,]{3,}" and then taking appropriate action based
on whether that matched a "strictly correct" regex.



From gagsl-py2 at yahoo.com.ar  Thu Aug  6 21:29:19 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 22:29:19 -0300
Subject: Subclassing Python's dict
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com>
	
	
	<2d56febf0908060126i323d499fla4b7a22c934c5e7@mail.gmail.com>
Message-ID: 

En Thu, 06 Aug 2009 05:26:22 -0300, Xavier Ho 
escribi?:
> On Thu, Aug 6, 2009 at 1:19 PM, alex23  wrote:
>> Xavier Ho wrote:
>> > You should subclass collections.UserDict, and not the default dict  
>> class.
>>
>> Xavier, why do you think that is the correct approach?
>
> I'll be honest first and say that I do not completely understand how  
> dict is
> implemented in the underlying C structure. But as Bruno had already
> mentioned, dict has a slightly different behaviour then we'd expect. For
> example, the __getitem__() function isn't actually used by the  
> interpreter
> (which, you know, *can* be a problem.)

Thinks have evolved...
Before Python 2.2, builtin types were not subclassable. You could not
inherit from dict. In order to write another mapping class, you had to
write the complete interface - or inherit from UserDict, that was a
concrete class implementing the mapping protocol.

Later, DictMixin was added (in 2.3) and it made easier to write other
mapping classes: one had to write the most basic methods (__getitem__ /
__setitem__ / __delitem__ / keys) and the DictMixin provided the remaining
functionality (e.g. values() is built from keys() plus __getitem__). Later
releases allowed an even more modular approach, and until 2.5 DictMixin
was the recommended approach.

Then came 3.0/2.6 and PEP3119 defining a rich hierarchy of abstract base
classes; a normal dictionary implements the MutableMapping ABC and this is
the preferred approach now (the MutableMapping implementation is very
similar to the original DictMixin, but builds on the other base classes
like Sized, Iterable...)

> I didn't realise they took UserDict out in later versions (2.6, for
> example), and put it back in Python 3.0. Does anyone know why?

UserDict still exists on both releases (collections.UserDict on 3.x), but
it's not the preferred approach to implement a new mapping class anymore.

-- 
Gabriel Genellina



From python at mrabarnett.plus.com  Thu Aug  6 21:33:27 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Fri, 07 Aug 2009 02:33:27 +0100
Subject: Python3: Using sorted(key=...)
In-Reply-To: <7e1cbuF2dfhtoU1@mid.dfncis.de>
References: <7e1cbuF2dfhtoU1@mid.dfncis.de>
Message-ID: <4A7B8467.8060101@mrabarnett.plus.com>

Johannes Bauer wrote:
> Hello list,
> 
> I'm having trouble with a incredibly simple sort of a list containing
> ints and tuples:
> 
> def myorder(x):
> 	if type(x) == int:
> 		return x
> 	else:
> 		return x[0]
> 
> odata = sorted([ (a, b) for (a, b) in data["description"].items() ],
> key=myorder)
> 
You're sorting a list of tuples (key/value pairs), so 'myorder' is
always given a tuple.

> still says:
> 
> Traceback (most recent call last):
>   File "./genproto.py", line 81, in 
>     odata = sorted([ (a, b) for (a, b) in data["description"].items() ],
> key=myorder)
> TypeError: unorderable types: tuple() < int()
> 
> Why is that? Am I missing something very obvious?
> 
Are some keys 'int' and others 'tuple'? In Python 3.x you can't compare
them except for equality:


Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> (1, ) < 1
False


Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> (1, ) < 1
Traceback (most recent call last):
   File "", line 1, in 
TypeError: unorderable types: tuple() < int()


From sjmachin at lexicon.net  Thu Aug  6 22:01:24 2009
From: sjmachin at lexicon.net (John Machin)
Date: Fri, 7 Aug 2009 02:01:24 +0000 (UTC)
Subject: unicode() vs. s.decode()
References: 
	<1249487636.7120.798.camel@arrakis>
	
	<1249568141.10840.37.camel@arrakis>
Message-ID: 

Jason Tackaberry  urandom.ca> writes:

> On Thu, 2009-08-06 at 01:31 +0000, John Machin wrote:

> > Suggested further avenues of investigation:
> > 
> > (1) Try the timing again with "cp1252" and "utf8" and "utf_8"
> > 
> > (2) grep "utf-8" /Objects/unicodeobject.c
> 
> Very pedagogical of you. :)  Indeed, it looks like bigger player in the
> performance difference is the fact that the code path for unicode(s,
> enc) short-circuits the codec registry for common encodings (which
> includes 'utf-8' specifically), whereas s.decode('utf-8') necessarily
> consults the codec registry.

So the next question (the answer to which may benefit all users
of .encode() and .decode()) is:

    Why does consulting the codec registry take so long,
    and can this be improved?





From dfnsonfsduifb at gmx.de  Thu Aug  6 22:15:52 2009
From: dfnsonfsduifb at gmx.de (Johannes Bauer)
Date: Fri, 07 Aug 2009 04:15:52 +0200
Subject: Python3: Using sorted(key=...)
In-Reply-To: 
References: <7e1cbuF2dfhtoU1@mid.dfncis.de>
	
Message-ID: <7e1h2oF2dlhvjU1@mid.dfncis.de>

MRAB schrieb:
> Johannes Bauer wrote:
>> Hello list,
>>
>> I'm having trouble with a incredibly simple sort of a list containing
>> ints and tuples:
>>
>> def myorder(x):
>>     if type(x) == int:
>>         return x
>>     else:
>>         return x[0]
>>
>> odata = sorted([ (a, b) for (a, b) in data["description"].items() ],
>> key=myorder)
>>
> You're sorting a list of tuples (key/value pairs), so 'myorder' is
> always given a tuple.

Oh good lord! You're right... I meant

def myorder(x):
     if type(x[0]) == int:
         return x[0]
     else:
         return x[0][0]

Thanks for your help,
Kind regards,
Johannes

-- 
"Du bist einfach nur l?cherlich! Mit solchen albernen und hohlen S?tzen
kannst du mir nicht impr?gnieren."
-- Hobbycholeriker Jens Fittig aka Wolfgang Gerber in de.sci.electronics
                             <4a6f44d0$0$12481$9b622d9e at news.freenet.de>


From michaelmossey at gmail.com  Thu Aug  6 23:02:10 2009
From: michaelmossey at gmail.com (Michael Mossey)
Date: Thu, 6 Aug 2009 20:02:10 -0700 (PDT)
Subject: help with threads
Message-ID: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>

Hello,

I have a simple application that needs one thread to manage networking
in addition to the main "thread" that does the main job. It's not
working right. I know hardly anything about threads, so I was hoping
someone could point me in the right direction to research this.

Basically, I have a program that does some computational work, and
also conveys its status to a monitor program elsewhere on the network
via sockets. I wanted to use a thread to manage the networking so that
the main program can run without regard to networking (i.e. they would
be asynchronous). So the network thread loops and calls select.

My problem is that in some cases, the network thread appears to stop,
while the main thread is doing a long computation.

I'm hoping someone can give me a general idea what to read about. For
example, under what conditions does a thread stop running? Can other
threads "take priority"? Are there certain operations that block other
threads (such as disk access)?

Thanks,
Mike


From jsrat10 at gmail.com  Thu Aug  6 23:13:01 2009
From: jsrat10 at gmail.com (jo)
Date: Thu, 6 Aug 2009 20:13:01 -0700 (PDT)
Subject: need help with an egg
Message-ID: <4d881767-ebe3-432c-bc9b-683b80626c97@y4g2000prf.googlegroups.com>

Hi,

I am very new to python....

I created an egg on a machine.  The Python version on that  is 2.5.
Copied that egg to a machine which has Python 2.6.

unzip -t Myproj-0.1-py2.5.egg
The above command shows all the files I need

When I run the easy_install, I get the foll. error.  Is it because of
the version?  Or am I doing something wrong?  Or the way I understand
the egg works is wrong.  Can anyone please help?
If it's the version issue, does that mean I cannot use that egg on my
machine with 2.6 version?

Installed /usr/local/lib/python2.6/dist-packages/Myproj-0.1-py2.5.egg
Processing dependencies for Myproj==0.1
Searching for Myproj==0.1
Reading http://pypi.python.org/simple/Myproj/
Couldn't find index page for 'Myproj' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
No local packages or download links found for Myproj==0.1
error: Could not find suitable distribution for Requirement.parse
('Myproj==0.1')

Thank you
Jo


From nate at binkert.org  Thu Aug  6 23:19:24 2009
From: nate at binkert.org (nathan binkert)
Date: Thu, 6 Aug 2009 20:19:24 -0700
Subject: Pure python implementation of string.format?
Message-ID: <217accd40908062019hb57a3d1n711316c21f9436bf@mail.gmail.com>

I was wondering if there was a pure python version of string.format
anywhere that could be used with python 2.4 and python 2.5.  Searching
has only turned up an early implementation done for pep 3101, but it
seems that it didn't get that far.

Thanks,

  Nate


From sgeorge at coe.neu.edu  Thu Aug  6 23:21:34 2009
From: sgeorge at coe.neu.edu (Sarmad George)
Date: Thu,  6 Aug 2009 23:21:34 -0400
Subject: SMTP
Message-ID: <1249615294.4a7b9dbe3a900@www.coe.neu.edu>

Good day all
I am new to the Python list
My question is here not Python as much as it is in servers

I have a code to send an email through my SMTP server - comcast Boston
fromaddrs = "******"
toaddrs = "sgeorge at coe.neu.edu"
msg = "Hello World"

server = smtplib.SMTP ('76.96.30.117', '25') #COMCAST BOSTON
server.set_debuglevel(1)
try:
    server.sendmail(fromaddrs, toaddrs, msg)
finally:
    server.quit()

Which basically sends a hello world message
Debugging gives me an indication of acceptance as seen below (and I as googled
it)
I tried the same from the University server, and I got the same results almost!
However, no emails in my Inbox when I log in - PLS can you explain the trouble?
Is it a firewall blocker?
Thanks alot


send: 'ehlo [127.0.1.1]\r\n'
reply: '250-OMTA03.emeryville.ca.mail.comcast.net hello [98.216.11.39], pleased
to meet you\r\n'
reply: '250-HELP\r\n'
reply: '250-AUTH LOGIN PLAIN CRAM-MD5\r\n'
reply: '250-SIZE 15728640\r\n'
reply: '250-ENHANCEDSTATUSCODES\r\n'
reply: '250-8BITMIME\r\n'
reply: '250-STARTTLS\r\n'
reply: '250 OK\r\n'
reply: retcode (250); Msg: OMTA03.emeryville.ca.mail.comcast.net hello
[98.216.11.39], pleased to meet you
HELP
AUTH LOGIN PLAIN CRAM-MD5
SIZE 15728640
ENHANCEDSTATUSCODES
8BITMIME
STARTTLS
OK
send: 'mail FROM: size=11\r\n'
reply: '250 2.1.0  sender ok\r\n'
reply: retcode (250); Msg: 2.1.0  sender ok
send: 'rcpt TO:\r\n'
reply: '250 2.1.5  recipient ok\r\n'
reply: retcode (250); Msg: 2.1.5  recipient ok
send: 'data\r\n'
reply: '354 enter mail, end with "." on a line by itself\r\n'
reply: retcode (354); Msg: enter mail, end with "." on a line by itself
data: (354, 'enter mail, end with "." on a line by itself')
send: 'Hello World\r\n.\r\n'
reply: '250 2.0.0 REQK1c0070qYooa8PEQKQA mail accepted for delivery\r\n'
reply: retcode (250); Msg: 2.0.0 REQK1c0070qYooa8PEQKQA mail accepted for
delivery
data: (250, '2.0.0 REQK1c0070qYooa8PEQKQA mail accepted for delivery')
send: 'quit\r\n'
reply: '221 2.0.0 OMTA03.emeryville.ca.mail.comcast.net comcast closing
connection\r\n'
reply: retcode (221); Msg: 2.0.0 OMTA03.emeryville.ca.mail.comcast.net comcast
closing connection

Sarmad Edward George
Electrical Computer Eng
Northeastern Uni
Boston MA - USA



From gagsl-py2 at yahoo.com.ar  Thu Aug  6 23:21:38 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 00:21:38 -0300
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com>
	
	
	
	<1a236d86-72de-4b43-bc7b-cf0c9bdab615@u38g2000pro.googlegroups.com>
Message-ID: 

En Thu, 06 Aug 2009 14:27:56 -0300, Kosta   
escribi?:
> On Aug 6, 3:57?am, David Cournapeau  wrote:
>> On Thu, Aug 6, 2009 at 12:39 AM, Kosta wrote:
>>
>> > Setenv.bat sets up the path and other environment variables build.exe
>> > needs to compile and link (and even binplace) its utilities. ?So
>> > building itself is not the issue. ?The problem is that if I call
>> > setenv.bat from Python and then build.exe, but the modifications to
>> > the path (and other environment settings) are not seen by Python, so
>> > the attempt to build without a specified path fails.
>>
>> It sounds like you do not propagate the environment when calling
>> setenv.bat from python. There is an option to do so in
>> subprocess.Popen init method, or you can define your own environment
>
> My interpretation of the above (and your email) is that using Popen
> allows one to pass the Python environment to a child processs (in my
> case, setenv.bat).   I need the reverse, to propagate from the child
> to the parent.

In addition to just calling setenv, dump the modified environment. Parse  
the output into a dictionary that you can use as the env argument to later  
subprocess calls:

py> import subprocess
py> cmdline = '(call setenv >nul 2>&1 & set)'
py> p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, shell=True)
py> env = dict(line.rstrip().split("=",1) for line in p.stdout)
py> p.wait()
0
py> env
{'TMP': 'D:\\USERDATA\\Gabriel\\CONFIG~1\\Temp', 'COMPUTERNAME': 'LEPTON',  
'HOMEDRIVE': 'D:', ...
py> env['FOO']='Salta Violeta!'
py> subprocess.call("echo %FOO%", shell=True, env=env)
Salta Violeta!
0

-- 
Gabriel Genellina



From dioxide.software at gmail.com  Thu Aug  6 23:22:57 2009
From: dioxide.software at gmail.com (KK)
Date: Thu, 6 Aug 2009 20:22:57 -0700 (PDT)
Subject: pylucene installation problem on Ubuntu 9.04
References: 
	
Message-ID: 

On Aug 7, 12:38?am, Jon Clements  wrote:
> On 6 Aug, 19:49, KK  wrote:
>
>
>
> > hi all,
> > I've trying to install pylucene on my linux box from last 2 days but
> > not able to do so. first i tried to install it using apt-get like
> > this,
> > kk-laptop$ sudo apt-get install pylucene
> > and it did install python2.5, python2.5-minimal and pylucene. I must
> > mention one thing that I already had python2.6 on my box as the
> > default python i.e /usr/bin/python is linked to python2.6. Anyway s,
> > now i started the python interpreter using "python" command from cli
> > and then to make sure pylucene has been installed i tried to import
> > the module and to my surprise it said "module pylucene not found".
> > I thought I should enter the python2.6 env and do the same , so i
> > tried starting the python2.6 interpreter using "python2.6" as the
> > command and tried importing the same module and again it failed giving
> > the same irritating message.
> > ?As a final try i pulled the source code of pylucene and as per the
> > comments given there in the README file, copied the mentioned files to
> > site-packages directory of python2.6 and then tried importing the
> > module and then got the same error message saying no module name
> > pylucene is present. I'm sick of this error !
> > Can someone point me what is the issue? If it is due to multiple
> > version of python running on box, can someone tell me which one to
> > remove or someone tell me how to get the whole thing running? I'll
> > very much thankful to you guys.
>
> > Thanks,
> > KK.
>
> If you installed using apt, have you a pylucene directory under /usr/
> local/lib/python2.6/dist-packages/?
>
> Also, if you run python, and import sys; print sys.path
> whats it show?
>
> Jon.

Yes I've a dirctory called dist-packages under python2.6 but that
doesn't contain anything on pylucene [it has lupyne, which i installed
day before yesterday and importing lupyne doesn't give any error msg,
but again it is dependent on pylucene]
# for python the output is :
------------------------------
kk-laptop$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print sys.path
['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/
python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/
lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/
dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/var/
lib/python-support/python2.6', '/usr/lib/python2.6/dist-packages/
gtk-2.0', '/var/lib/python-support/python2.6/gtk-2.0', '/usr/local/lib/
python2.6/dist-packages']
>>>
-------------------------------

for python2.5 this is the output:
kk-laptop$ python2.5
Python 2.5.4 (r254:67916, Apr  4 2009, 17:55:16)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print sys.path
['', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/
python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/
python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/
lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/
gst-0.10', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/
site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0']
>>>
--------------------------------

and for python2.6 the output is this:
kk-laptop$ python2.6
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print sys.path
['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/
python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/
lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/
dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/var/
lib/python-support/python2.6', '/usr/lib/python2.6/dist-packages/
gtk-2.0', '/var/lib/python-support/python2.6/gtk-2.0', '/usr/local/lib/
python2.6/dist-packages']


>From all of the above what I can see is we don't have any directory
named dist-packages under python2.5 but we've one under 2.6, then
where did all those pylucene files got installed to after i installed
it using apt-get? Any ideas?

Thanks
KK


From michele.simionato at gmail.com  Thu Aug  6 23:29:35 2009
From: michele.simionato at gmail.com (Michele Simionato)
Date: Thu, 6 Aug 2009 20:29:35 -0700 (PDT)
Subject: Custom namespaces
References: <0284d760$0$20667$c3e8da3@news.astraweb.com>
	
Message-ID: <271ecd46-b684-49a0-b7ce-a0c0a4be519f@z28g2000vbl.googlegroups.com>

On Aug 2, 6:46?am, Chris Rebert  wrote:
> > Is there any way to install a custom type as a namespace?
>
> For classes/objects, yes, using metaclasses.
> See the __prepare__() method in PEP 3115:http://www.python.org/dev/peps/pep-3115/

Here is an example of usage:

http://www.artima.com/weblogs/viewpost.jsp?thread=236234
http://www.artima.com/weblogs/viewpost.jsp?thread=236260
(yes, it only works for Python 3+)


From loic.domaigne at googlemail.com  Fri Aug  7 00:04:40 2009
From: loic.domaigne at googlemail.com (=?ISO-8859-1?Q?Lo=EFc_Domaign=E9?=)
Date: Thu, 6 Aug 2009 21:04:40 -0700 (PDT)
Subject: help with threads
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
Message-ID: <949b87d5-8cff-444a-b6ba-23d49610d130@p36g2000vbn.googlegroups.com>

Hallo Michael,

> I have a simple application that needs one thread to manage networking
> in addition to the main "thread" that does the main job. It's not
> working right. I know hardly anything about threads, so I was hoping
> someone could point me in the right direction to research this.
>
> Basically, I have a program that does some computational work, and
> also conveys its status to a monitor program elsewhere on the network
> via sockets. I wanted to use a thread to manage the networking so that
> the main program can run without regard to networking (i.e. they would
> be asynchronous). So the network thread loops and calls select.
>
> My problem is that in some cases, the network thread appears to stop,
> while the main thread is doing a long computation.
>
> I'm hoping someone can give me a general idea what to read about. For
> example, under what conditions does a thread stop running? Can other
> threads "take priority"? Are there certain operations that block other
> threads (such as disk access)?

May I suggest:
http://www.dabeaz.com/python/GIL.pdf

HTH,
Lo?c
--
My Blog: http://www.domaigne.com/blog

"There is only one problem with common sense; it?s not very common."
-- Milt Bryce


From gagsl-py2 at yahoo.com.ar  Fri Aug  7 00:21:23 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 01:21:23 -0300
Subject: SMTP
References: <1249615294.4a7b9dbe3a900@www.coe.neu.edu>
Message-ID: 

En Fri, 07 Aug 2009 00:21:34 -0300, Sarmad George   
escribi?:

> Good day all
> I am new to the Python list

Welcome!

> My question is here not Python as much as it is in servers
>
> I have a code to send an email through my SMTP server - comcast Boston
> fromaddrs = "******"
> toaddrs = "sgeorge at coe.neu.edu"
> msg = "Hello World"
>
> server = smtplib.SMTP ('76.96.30.117', '25') #COMCAST BOSTON
> server.set_debuglevel(1)
> try:
>     server.sendmail(fromaddrs, toaddrs, msg)
> finally:
>     server.quit()
>
> Which basically sends a hello world message
> Debugging gives me an indication of acceptance as seen below (and I as  
> googled
> it)
> I tried the same from the University server, and I got the same results  
> almost!
> However, no emails in my Inbox when I log in - PLS can you explain the  
> trouble?
> Is it a firewall blocker?

It's probably a spam filter in action: you claim to be someone at Yahoo  
but you're not using a Yahoo server to send mail. Try using the Yahoo smtp  
mail servers to deliver your message, or use your ISP address as the  
sender if you use their SMTP. In any case, you should log in first with  
the adequate username+password.

-- 
Gabriel Genellina



From http  Fri Aug  7 00:42:04 2009
From: http (Paul Rubin)
Date: 06 Aug 2009 21:42:04 -0700
Subject: Python3: Using sorted(key=...)
References: <7e1cbuF2dfhtoU1@mid.dfncis.de>
	
	<7e1h2oF2dlhvjU1@mid.dfncis.de>
Message-ID: <7xvdl0xmjn.fsf@ruckus.brouhaha.com>

Johannes Bauer  writes:
> def myorder(x):
>      if type(x[0]) == int:
>          return x[0]
>      else:
>          return x[0][0]

I used to write code like that pretty regularly, but over time I found
that it's better to stay consistent and use the same container format
(in this case, tuples) for everything, rather than having special
cases for the singleton and non-singleton case.


From michele.simionato at gmail.com  Fri Aug  7 00:54:25 2009
From: michele.simionato at gmail.com (Michele Simionato)
Date: Thu, 6 Aug 2009 21:54:25 -0700 (PDT)
Subject: Generate a new object each time a name is imported
References: <02853264$0$20667$c3e8da3@news.astraweb.com>
	 
	<7x63d631md.fsf@ruckus.brouhaha.com>
Message-ID: 

On Aug 2, 1:18?pm, Paul Rubin  wrote:
> Peter Otten <__pete... at web.de> writes:
> > >>> import sys
> > >>> sys.modules["yadda"] = A()
>
> OMG.... wow. ?I bow to you. ?But I'm not sure whether that's bowing in
> awe or in terror.

I had to play this kind of tricks on our production code, not so long
ago. Not that I am pride of it, but it was the lesser evil to cope
with a wrong design. The scenario: a large legacy code base
based on the idea of using a Python module to keep configuration
parameters. The idea is fine as long as the parameters are
immutable, but in our case the parameters could be changed.
In theory the parameters should have been set only once,
however in practice this was not guaranteed: every piece
of code could change the parameters at some moment, and things
could get "interesting" to debug.
Throwing away the configuration system was not an option, because
it would have involved changing hundreds of modules, so I set out
for a compromise: the parameters are still mutable, but they
can be changed only once. This was implemented by replacing
the module with a configuration object using custom
descriptors. Here is the code:

$ echo config.py
import sys

class WriteOnce(object):
    "WriteOnce descriptor"
    def __init__(self, default):
        self.default = self.value = default
        self.already_set = False
    def __get__(self, obj, objcls):
        return self.value
    def __set__(self, obj, value):
        if value != self.value and self.already_set:
            raise TypeError('You cannot set twice a write-once
attribute!')
        self.value = value
        self.already_set = True

class Config(object):
    "A singleton to be used as a module"
    parameter = WriteOnce(0)

sys.modules['config'] = Config()

The usage is

>>> import config
>>> config.parameter = 42
>>> config.parameter = 43
Traceback (most recent call last):
   ...
TypeError: You cannot set twice a write-once attribute!

Just to say that there are use cases where replacing modules with
objects may have sense.
Still, a better design would just have passed immutable configuration
objects around
(changing the configuration would mean to create a new object).
Unfortunately there are still a lot a people without a functional
mindset :-(


From gagsl-py2 at yahoo.com.ar  Fri Aug  7 01:37:13 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 02:37:13 -0300
Subject: Python configuration question when python scripts are executed
	using Appweb as web server.
References: 
	
	
	
	
Message-ID: 

En Thu, 06 Aug 2009 12:49:30 -0300, IronyOfLife   
escribi?:
> On Aug 5, 4:18?pm, "Gabriel Genellina"  wrote:
>> En Tue, 04 Aug 2009 10:15:24 -0300, IronyOfLife 
>> escribi?:
>> > On Aug 3, 8:42?pm, "Gabriel Genellina"  wrote:
>> >> En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife  
>>  ?
>> >> escribi?:
>>
>> >> > I have installed python 2.6.2 in windows xp professional machine. I
>> >> > have set the following environment variables -- PYTHONPATH. It  
>> points
>> >> > to following windows folders: python root folder, the lib folder  
>> and
>> >> > lib-tk folder.
>>
>> >> Why? Did you read it somewhere? Usually there is no need to set the ?
>> >> PYTHONPATH variable at all; remove it.
>>
>> > Setting PYTHONPATH environment variables is mentioned in Python docs.
>>
>> Could you provide a link please? Setting PYTHONPATH should not be
>
> Here are couple of links that discusses setting PYTHONPATH environment
> variable.
> http://docs.python.org/using/windows.html

Ouch, that document should be reworked and updated!

> http://www.daimi.au.dk/~chili/PBI/pythonpath.html

That's mostly obsolete for current versions. Since PEP370 [0] was  
implemented, a per-user private directory is already in sys.path now, so  
there is no need to play with PYTHONPATH.

> I understand your concerns regarding setting of PYTHONPATH while
> multiple versions of Python are installed on the same machine. My fix
> however does not use PYTHONPATH. The GNUTLS wrapper module for PYTHON
> loads the GNUTLS dll's and it was not able to find them. Using FileMon
> (win tool) I found out the paths that are scanned and I copied the
> dlls to one of such paths. I still do not like this fix. This is a
> temporary solution.

Note that this cannot be fixed from inside Python. When you import a  
module, the interpreter scans the directories in ITS search path  
(sys.path) looking for a matching module. Once the module is found:
- if it is a Python file, it's executed
- if it is an extension module (a .pyd file, in fact a .dll renamed) it's  
loaded using LoadLibraryEx (a Windows function), and finally its  
initialization routine is executed.

For LoadLibrary to successfully load the module, all its external  
references must be resolved. That is, Windows must locate and load all  
other DLLs that this module depends on, using its own search strategy [1],  
taking into account the PATH environment variable and many other places.

It is at this stage that you get the error: when the gnutls wrapper  
attempts to load the gnutls DLL. That search is done by Windows, not by  
Python, and PYTHONPATH has nothing to do with it.

Why different results in IIS and appweb? Note that there exist several  
search strategies, they depend on the application home directory, the  
location of the .exe, whether SetDllDirectory was called or not, whether  
the application has a manifest or not, a .local file or not... Hard to  
tell with so many variables.

> Can you explain maybe with some sample how to set .pth files? Maybe
> this will resolve my issue.

Yes, but I don't think this will actually help with your issue.

pth files are described here [2]. Suppose you want to add c:\foo\bar to  
sys.path, then write a file whatever.pth containing this single line:

c:\foo\bar

and place it on c:\your_python_installation\lib\site-packages
When the interpreter starts, it will find the .pth file, read it, and add  
any directory it finds (that actually exists) to sys.path

Note that another Python installation will use a diferent site-packages  
directory and won't find this particular .pth file, so different Python  
versions don't interfere.

---

[0] http://python.org/dev/peps/pep-0370/
[1] http://msdn.microsoft.com/en-us/library/ms682586(VS.85).aspx
[2] http://docs.python.org/library/site.html

-- 
Gabriel Genellina



From wuwei23 at gmail.com  Fri Aug  7 01:41:17 2009
From: wuwei23 at gmail.com (alex23)
Date: Thu, 6 Aug 2009 22:41:17 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
Message-ID: <3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>

Paul Rubin  wrote:
> The PHP docs as I remember are sort of regular (non-publically
> editable) doc pages, each of which has a public discussion thread
> where people can post questions and answers about the topic of that
> doc page. ?I thought it worked really well. ?The main thing is that
> the good stuff from the comment section gets folded into the actual
> doc now and then.

I'd still like to see this kept out of the official docs as much as
possible, mostly for reasons of brevity & clarity. I think the
official docs should be considered definitive and not require a
hermeneutic evaluation against user comments to ensure they're still
correct...

How about a secondary site that embeds the docs and provides
commenting functionality around it? That's certainly a finitely scoped
project that those with issues about the docs could establish and
contribute to, with the possibility of it gaining official support
later once it gains traction.





From nobody at nowhere.com  Fri Aug  7 01:42:29 2009
From: nobody at nowhere.com (Nobody)
Date: Fri, 07 Aug 2009 06:42:29 +0100
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
	
Message-ID: 

On Thu, 06 Aug 2009 14:23:47 -0700, Ethan Furman wrote:

>> [0-9]+ allows any number of leading zeros, which is sometimes undesirable.
>> Using:
>> 
>> 	(0|[1-9][0-9]*)
>> 
>> is more robust.
> 
> You make a good point about possibly being undesirable, but I question 
> the assertion that your solution is /more robust/.  If the OP 
> wants/needs to match numbers even with leading zeroes your /more robust/ 
> version fails.

Well, the OP did say:

> The regex should only match the exact above.

I suppose that it depends upon the definition of "exact" ;)

More seriously: failing to produce an error when one is called for is also
a bug.

Personally, unless I knew for certain that the rest of the program would
handle leading zeros correctly (e.g. *not* interpreting the number as
octal), I would try to reject it in the parser. It's usually much easier
to determine the cause of an error raised by the parser than if you allow
bogus data to propagate deep into the program.



From mark.v.weber at gmail.com  Fri Aug  7 01:42:42 2009
From: mark.v.weber at gmail.com (mark.v.weber at gmail.com)
Date: Thu, 6 Aug 2009 22:42:42 -0700 (PDT)
Subject: how to kill subprocess when Python process is killed?
Message-ID: <0feaa2a3-5b73-43e4-9b24-11f157ff6d18@l34g2000vba.googlegroups.com>

I am writing a Python program that launches a subprocess (using
Popen).
I am reading stdout of the subprocess, doing some filtering, and
writing to
stdout of the main process.

When I kill the main process (cntl-C) the subprocess keeps running.
How do I kill the subprocess too? The subprocess is likey to run a
long time.

Context:
I'm launching only one subprocess at a time, I'm filtering its stdout.
The user might decide to interrupt to try something else; the user
wants the process and all subprocesses to go away in response
to a cntl-C

I'm new to python; solution must be for Python 2.5 (windows) to help
me.

Any help and/or pointers appreciated.




From gagsl-py2 at yahoo.com.ar  Fri Aug  7 01:49:59 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 02:49:59 -0300
Subject: one method of COM object needs a variant type variable
References: <913F77222E913C49A057FDD7BBDEAAA30192B846@br-dc.uhul.wan>
Message-ID: 

En Thu, 06 Aug 2009 09:37:55 -0300, MICH?LEK Jan Mgr.  
 escribi?:

> How i can use this type in win32.com? One method of com object (geomedia  
> storage service) needs this variable for storage geometry of geometry  
> object (this variable will be writen into blob in DB). Is possible make  
> this variable in py??

Any compatible object may be used on the Python side, the pywin32 library  
manages the conversion automatically.

See  
http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/PythonCOM.html

-- 
Gabriel Genellina



From wuwei23 at gmail.com  Fri Aug  7 01:57:34 2009
From: wuwei23 at gmail.com (alex23)
Date: Thu, 6 Aug 2009 22:57:34 -0700 (PDT)
Subject: how to kill subprocess when Python process is killed?
References: <0feaa2a3-5b73-43e4-9b24-11f157ff6d18@l34g2000vba.googlegroups.com>
Message-ID: <3733148e-c03d-42ef-88f7-855c516e6564@d9g2000prh.googlegroups.com>

On Aug 7, 3:42?pm, "mark.v.we... at gmail.com" 
wrote:
> When I kill the main process (cntl-C) the subprocess keeps running.
> How do I kill the subprocess too? The subprocess is likey to run a
> long time.

You can register functions to run when the Python process ends by
using the atexit[1] module.

The following has been tested & works under Python 2.6 on Windows XP:

    import atexit

    def cleanup():
        print 'stop the subprocess in here'

    atexit.register(cleanup)

    while True:
        pass


[1]: http://docs.python.org/library/atexit.html


From stefan_ml at behnel.de  Fri Aug  7 02:07:37 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 07 Aug 2009 08:07:37 +0200
Subject: SDMX format
In-Reply-To: 
References: 
Message-ID: <4a7bc4a8$0$31337$9b4e6d93@newsspool4.arcor-online.net>

xamdam wrote:
> Does anyone know of python libs for writing SDMX XML format?
> http://www.SDMX.org/resources/SDMXML/schemas/v2_0/common

Looks like the page behind that link is broken, but in general, working
with XML formats in Python isn't hard at all when you use ElementTree or
lxml. The latter also has support for XML-Schema validation, and you might
be interested in lxml.objectify for handling data centric XML formats
(assuming that's the case here).

Stefan


From stefan_ml at behnel.de  Fri Aug  7 02:23:32 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 07 Aug 2009 08:23:32 +0200
Subject: How to fetch an XML file using an HTTPS query
In-Reply-To: 
References: 	<49b3a7400908040638h46d4e4dcxe5cd4120e9c2c7a1@mail.gmail.com>
	
Message-ID: <4a7bc863$0$31334$9b4e6d93@newsspool4.arcor-online.net>

Tycho Andersen wrote:
> Blah, forgot to include the list. When is python-list going to get Reply-To?

Hopefully never.

Stefan


From stefan_ml at behnel.de  Fri Aug  7 02:40:35 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 07 Aug 2009 08:40:35 +0200
Subject: How to force SAX parser to ignore encoding problems
In-Reply-To: <89c214a4-e846-4101-b0b3-8078eec15114@w41g2000yqb.googlegroups.com>
References: <89c214a4-e846-4101-b0b3-8078eec15114@w41g2000yqb.googlegroups.com>
Message-ID: <4a7bcc64$0$31330$9b4e6d93@newsspool4.arcor-online.net>

?ukasz wrote:
> I have a problem with my XML parser (created with libraries from
> xml.sax package). When parser finds a invalid character (in CDATA
> section) for example ?, throws an exception SAXParseException.
> 
> Is there any way to just ignore this kind of problem. Maybe there is a
> way to set up parser in less strict mode?
> 
> I know that I can catch this exception and determine if this is this
> kind of problem and then ignore this, but I am asking about any global
> setting.

The parser from libxml2 that lxml provides has a recovery option, i.e. it
can keep parsing regardless of errors and will drop the broken content.

However, it is *always* better to fix the input, if you get any hand on it.
Broken XML is *not* XML at all. If you can't fix the source, you can never
be sure that the data you received is in any way complete or even usable.

Stefan


From michaelmossey at gmail.com  Fri Aug  7 02:40:53 2009
From: michaelmossey at gmail.com (Michael Mossey)
Date: Thu, 6 Aug 2009 23:40:53 -0700 (PDT)
Subject: help with threads
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
	<949b87d5-8cff-444a-b6ba-23d49610d130@p36g2000vbn.googlegroups.com>
Message-ID: 

Ah yes, that explains it. Some of these long computations are done in
pure C, so I'm sure the GIL is not being released.
Thanks.


From stefan_ml at behnel.de  Fri Aug  7 02:46:38 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 07 Aug 2009 08:46:38 +0200
Subject: Generators through the C API
In-Reply-To: 
References: 
	
Message-ID: <4a7bcdce$0$31330$9b4e6d93@newsspool4.arcor-online.net>

Duncan Booth schrieb:
> Lucas P Melo  wrote:
> 
>> Hello, I'm a total noob about the C API. Is there any way to create a 
>> generator function using the C API? I couldn't find anything like the 
>> 'yield' keyword in it.
>>
>> Thanks in advance.
> 
> You define a new type with tp_flags including Py_TPFLAGS_HAVE_ITER. 
> Anything that would be a local variable in your generator needs to become 
> an attribute in the type.
> 
> The tp_init initialization function should contain all the code up to the 
> first yield, tp_iter should return self and tp_iternext should execute code 
> up to the next yield.

This is pretty easy to do in Cython (or Pyrex), BTW. Just write a class
with an __iter__ and __next__ method, and Cython will generate the C-API
code as expected.

http://docs.cython.org/docs/special_methods.html#iterators

Note that Cython doesn't currently support the "yield" statement, but
that's certainly on the ToDo list.

http://trac.cython.org/cython_trac/ticket/83

Stefan


From kushal.kumaran+python at gmail.com  Fri Aug  7 02:52:31 2009
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Fri, 7 Aug 2009 12:22:31 +0530
Subject: Web page data and urllib2.urlopen
In-Reply-To: <4A7B565E.9000508@ieee.org>
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
	
	 <4A7B565E.9000508@ieee.org>
Message-ID: <1e364c4e0908062352w33ae8914q7436743d3256e1d5@mail.gmail.com>

On Fri, Aug 7, 2009 at 3:47 AM, Dave Angel wrote:
>
>
> Piet van Oostrum wrote:
>>
>> 
>>>
>>> DA> All I can guess is that it has something to do with "browser type" or
>>> DA> cookies. ?And that would make lots of sense if this was a cgi page.
>>> ?But
>>> DA> the URL doesn't look like that, as it doesn't end in pl, py, asp, or
>>> any of
>>> DA> another dozen special suffixes.
>>>

Note that the URL does not have to have any special suffix for it to
be dynamically generated.  See any page at wikipedia, for example.
Mediawiki, the software running the site, is a php application.

>>
>>
>>>
>>> DA> Any hints, anybody???
>>>
>>
>> If you look into the HTML that Firefox gets, there is a lot of
>> javascript in it.
>>
>
> But the raw page didn't have any javascript. ?So what about that original
> raw page triggered additional stuff to be loaded?

FWIW, I'm getting a ton of javascript in the page downloaded using
your code fragment.

> Is it "user agent", as someone else brought out? ?And is there somewhere I
> can read more about that aspect of things? ?I've mostly built very static
> html pages, where the server yields the same page to everybody. ?And some
> form stuff, where the ?user clicks on a 'submit" button to trigger a script
> that's not shown on the URL line.
>

-- 
kushal


From stefan_ml at behnel.de  Fri Aug  7 02:53:38 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 07 Aug 2009 08:53:38 +0200
Subject: Special chars with HTMLParser
In-Reply-To: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com>
References: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com>
Message-ID: <4a7bcf71$0$31330$9b4e6d93@newsspool4.arcor-online.net>

Fafounet wrote:
> I am parsing a web page with special chars such as é (which
> stands for ?).
> I know I can have the unicode character ? from unicode
> ("\xe9","iso-8859-1")
> but with those extra characters I don' t know.
> 
> I tried to implement handle_charref within HTMLParser without success.
> Furthermore, if I have the data abécd, handle_data will get "ab",
> handle_charref will get xe9 and then handle_data doesn't have the end
> of the string ("cd").

Any reason you can't use a tree based HTML parser like the one in
lxml.html? That would eliminate this kind of problem altogether, as you'd
always get a well-decoded unicode string from the tree content.

Stefan


From breamoreboy at yahoo.co.uk  Fri Aug  7 03:04:51 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Fri, 07 Aug 2009 08:04:51 +0100
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 		<2qcrk6-doj.ln1@nb2.stroeder.com>	
	
Message-ID: 

Michael Str?der wrote:
> Thorsten Kampe wrote:
>> * Michael Str?der (Thu, 06 Aug 2009 18:26:09 +0200)
>>>>>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
>>> 17.23644495010376
>>>>>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
>>> 72.087096929550171
>>>
>>> That is significant! So the winner is:
>>>
>>> unicode('???????','utf-8')
>> Unless you are planning to write a loop that decodes "???????" one 
>> million times, these benchmarks are meaningless.
> 
> Well, I can tell you I would not have posted this here and checked it if it
> would be meaningless for me. You don't have to read and answer this thread if
> it's meaningless to you.
> 
> Ciao, Michael.
I believe that the comment "these benchmarks are meaningless" refers to 
the length of the strings being used in the tests.  Surely something 
involving thousands or millions of characters is more meaningful? Or to 
go the other way, you are unlikely to write
for c in '???????':
     u = unicode(c, 'utf-8')
     ...
Yes?

-- 
Kindest regards.

Mark Lawrence.



From python at lists.wgwh.ch  Fri Aug  7 03:13:04 2009
From: python at lists.wgwh.ch (Oli Schacher)
Date: Fri, 07 Aug 2009 09:13:04 +0200
Subject: SMTP
In-Reply-To: <1249615294.4a7b9dbe3a900@www.coe.neu.edu>
References: <1249615294.4a7b9dbe3a900@www.coe.neu.edu>
Message-ID: <4A7BD400.1020404@lists.wgwh.ch>

Sarmad George schrieb:

> msg = "Hello World"

Your sending your message without any headers (no subject etc). So
probably your message lands in the recipients spam folder.

Try:
msg = """To: recipient at example.com
Subject: hello world

Hello there"""


The blank line between the headers and the body is important!

Also make sure to use a sender address that is allowed to send through
your smtp relay. yahoo.com sender is probably a bad idea. Check your
Yahoo Inbox, you might even have a bounce message there telling you that
the final mail server didn't accept your message.



From hendrik at microcorp.co.za  Fri Aug  7 03:15:34 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Fri, 7 Aug 2009 09:15:34 +0200
Subject: Parsing Binary Structures;
	Is there a better way / What is your way?
In-Reply-To: 
References: 
	
Message-ID: <200908070915.34564.hendrik@microcorp.co.za>

On Thursday 06 August 2009 20:50:30 Martin P. Hellwig wrote:
> Thanks all for your insights and suggestions.
> It seems to me that there are a couple of ways to this bit manipulation
> and a couple of foreign modules to assist you with that.
>
> Would it be worth the while to do a PEP on this?
> Personally I think that it would be nice to have a standard module in
> Python for this but perhaps there is a good reason that there isn't
> already one.

I agree that it would be nice - I think it would be nice if something
like this is added to the struct module to give a "this is the obvious
way that python handles foreign data" module

- Hendrik




From Michalek.Jan at uhul.cz  Fri Aug  7 03:21:03 2009
From: Michalek.Jan at uhul.cz (=?iso-8859-2?Q?MICH=C1LEK_Jan_Mgr=2E?=)
Date: Fri, 7 Aug 2009 09:21:03 +0200
Subject: one method of COM object needs a variant type variable
Message-ID: <913F77222E913C49A057FDD7BBDEAAA30192B8A0@br-dc.uhul.wan>

Thanks Gabriel,
I seen this before, but I don't know, what's mean 'compatible object'. I need create object who will like as an variant type.
Je.
it looks lieke this:
...
obj=win32com.client.Dispatch('Geomedia.PointGeometry') #geometry object
gss=win32com.client.Dispatch('Geomedia.GeometryStorageService')#geometry strorage object
....
gss.GeometryToStorage(obj, out) #out must be a variant type variable
.....
oRS.Fields("Geometry").Value = out # writing blob into recordset via ADO
 
 
En Thu, 06 Aug 2009 09:37:55 -0300, MICH?LEK Jan Mgr.  

 > escribi?:



> How i can use this type in win32.com? One method of com object (geomedia  

> storage service) needs this variable for storage geometry of geometry  

> object (this variable will be writen into blob in DB). Is possible make  

> this variable in py??



Any compatible object may be used on the Python side, the pywin32 library  

manages the conversion automatically.



See  

http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/PythonCOM.html



-- 

Gabriel Genellina
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at REMOVE-THIS-cybersource.com.au  Fri Aug  7 03:25:44 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 07 Aug 2009 07:25:44 GMT
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	
	
Message-ID: <00055a38$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 08:04:51 +0100, Mark Lawrence wrote:

> I believe that the comment "these benchmarks are meaningless" refers to
> the length of the strings being used in the tests.  Surely something
> involving thousands or millions of characters is more meaningful? Or to
> go the other way, you are unlikely to write for c in '???????':
>      u = unicode(c, 'utf-8')
>      ...
> Yes?

There are all sorts of potential use-cases. A day or two ago, somebody 
posted a question involving tens of thousands of lines of tens of 
thousands of characters each (don't quote me, I'm going by memory). On 
the other hand, it doesn't require much imagination to think of a use-
case where there are millions of lines each of a dozen or so characters, 
and you want to process it line by line:


noun: cat
noun: dog
verb: caf?
...


As always, before optimizing, you should profile to be sure you are 
actually optimizing and not wasting your time.



-- 
Steven


From hendrik at microcorp.co.za  Fri Aug  7 03:38:54 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Fri, 7 Aug 2009 09:38:54 +0200
Subject: help with threads
In-Reply-To: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
Message-ID: <200908070938.54928.hendrik@microcorp.co.za>

On Friday 07 August 2009 05:02:10 Michael Mossey wrote:
> Hello,

> My problem is that in some cases, the network thread appears to stop,
> while the main thread is doing a long computation.

Is this computation done in pure python or are you calling some
underlying thing in C?

I would be surprised if a pure python computation thread were to hog
the cpu  - have you been able to figure out what the computation thread is
actually doing when the hogging occurs?

> I'm hoping someone can give me a general idea what to read about. For
> example, under what conditions does a thread stop running? Can other
> threads "take priority"? Are there certain operations that block other
> threads (such as disk access)?

AFAIK python threads are all at the same level of priority, and the running
thread is interrupted every N python bytecode instructions, so what you are
experiencing should not happen.

Try to figure out, if you can, where the computation thread is spending
its time.

- Hendrik


From lists at digital.ktu.lt  Fri Aug  7 03:46:20 2009
From: lists at digital.ktu.lt (Algirdas Brazas)
Date: Fri, 7 Aug 2009 10:46:20 +0300
Subject: Pywin32 @ windows 7
Message-ID: <004a01ca1733$a9768c10$4605a8c0@btsc1>

Hi all,

Did anyone manage to get windows extensions installet on windows 7 64 bit? As 
far as I try I get only "Setup program invalid or damaged".

Al. 




From sumit.jha50 at gmail.com  Fri Aug  7 04:22:14 2009
From: sumit.jha50 at gmail.com (sumit)
Date: Fri, 7 Aug 2009 01:22:14 -0700 (PDT)
Subject: problem
Message-ID: <207a84d7-fb45-46c5-a2fb-e34c564c09f8@v37g2000prg.googlegroups.com>

i want 2 hav the header files for regular expression to non
deterministin autometa
so whr should i find it?plz help


From jeanmichel at sequans.com  Fri Aug  7 04:47:55 2009
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Fri, 07 Aug 2009 10:47:55 +0200
Subject: help with threads
In-Reply-To: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
Message-ID: <4A7BEA3B.4090000@sequans.com>

Michael Mossey wrote:
> Hello,
>
> I have a simple application that needs one thread to manage networking
> in addition to the main "thread" that does the main job. It's not
> working right. I know hardly anything about threads, so I was hoping
> someone could point me in the right direction to research this.
>
> Basically, I have a program that does some computational work, and
> also conveys its status to a monitor program elsewhere on the network
> via sockets. I wanted to use a thread to manage the networking so that
> the main program can run without regard to networking (i.e. they would
> be asynchronous). So the network thread loops and calls select.
>
> My problem is that in some cases, the network thread appears to stop,
> while the main thread is doing a long computation.
>
> I'm hoping someone can give me a general idea what to read about. For
> example, under what conditions does a thread stop running? Can other
> threads "take priority"? Are there certain operations that block other
> threads (such as disk access)?
>
> Thanks,
> Mike
>   
I may be a little out of subject, anyway *if* you are writing also the 
server side program, you should really take a look at
http://docs.python.org/library/xmlrpclib.html
or
http://pyro.sourceforge.net/

... and forget about network coding :o)

To help you for your initial question, exceptions in thread are not 
propagated to the main thread, so when an unhanded exception occurs in 
your thread, it will just stop. Maybe this is what is happening.

A quick workaround is to embed all you threaded code in a try except 
clause and log the exception before re-raising it. You should only do 
that for debugging purpose.

JM


From jeanmichel at sequans.com  Fri Aug  7 04:55:51 2009
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Fri, 07 Aug 2009 10:55:51 +0200
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>	
		<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
Message-ID: <4A7BEC17.6040602@sequans.com>

alex23 wrote:
> Paul Rubin  wrote:
>   
>> The PHP docs as I remember are sort of regular (non-publically
>> editable) doc pages, each of which has a public discussion thread
>> where people can post questions and answers about the topic of that
>> doc page.  I thought it worked really well.  The main thing is that
>> the good stuff from the comment section gets folded into the actual
>> doc now and then.
>>     
>
> I'd still like to see this kept out of the official docs as much as
> possible, mostly for reasons of brevity & clarity. I think the
> official docs should be considered definitive and not require a
> hermeneutic evaluation against user comments to ensure they're still
> correct...
>
> How about a secondary site that embeds the docs and provides
> commenting functionality around it? That's certainly a finitely scoped
> project that those with issues about the docs could establish and
> contribute to, with the possibility of it gaining official support
> later once it gains traction.
>
>
>
>   
Very good Idea. I'd like to get a commented/user improved python 
documentation site with examples and I also love the current python 
documentation.

JM


From piet at cs.uu.nl  Fri Aug  7 05:14:30 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Fri, 07 Aug 2009 11:14:30 +0200
Subject: Web page data and urllib2.urlopen
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
	
	
	
Message-ID: 

>>>>> Dave Angel  (DA) wrote:

>DA> Piet van Oostrum wrote:
>>> 
>DA> If Mozilla had seen a page with this line in an appropriate place, it'd
>DA> immediately begin loading the other page, at "someotherurl"  But there's no
>DA> such line.
>>>> 
>>> 
>>> 
>DA> Next, I looked for javascript.  The Mozilla page contains lots of
>DA> javascript, but there's none in the raw page.  So I can't explain Mozilla's
>DA> differences that way.
>>>> 
>>> 
>>> 
>DA> I did notice the link to /m/Content/mobile2.css, but I don' t know any way
>DA> a CSS file could cause the content to change, just the display.
>>>> 
>>> 
>>> 
>DA> All I can guess is that it has something to do with "browser type" or
>DA> cookies.  And that would make lots of sense if this was a cgi page.  But
>DA> the URL doesn't look like that, as it doesn't end in pl, py, asp, or any of
>DA> another dozen special suffixes.
>>>> 
>>> 
>>> 
>DA> Any hints, anybody???
>>>> 
>>> 
>>> If you look into the HTML that Firefox gets, there is a lot of
>>> javascript in it.
>>> 

>DA> But the raw page didn't have any javascript.  So what about that original
>DA> raw page triggered additional stuff to be loaded?
>DA> Is it "user agent", as someone else brought out?  And is there somewhere I
>DA> can read more about that aspect of things?  I've mostly built very static
>DA> html pages, where the server yields the same page to everybody.  And some
>DA> form stuff, where the  user clicks on a 'submit" button to trigger a script
>DA> that's not shown on the URL line.

Yes, if you specify a 'normal' web browser as user agent you do get the
Javascript:

import urllib2

request = urllib2.Request('http://www.marketwatch.com/story/mondays-biggest-gaining-and-declining-stocks-2009-07-27')
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13')

opener = urllib2.build_opener() 
page = opener.open(request).read()
print page

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From rt8396 at gmail.com  Fri Aug  7 05:22:50 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 02:22:50 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
Message-ID: <0067d0ed-95b7-4a97-b2f8-7f35f13c6304@f10g2000vbf.googlegroups.com>

On Aug 7, 12:41?am, alex23  wrote:
...(snip)
> How about a secondary site that embeds the docs and provides
> commenting functionality around it? That's certainly a finitely scoped
> project that those with issues about the docs could establish and
> contribute to, with the possibility of it gaining official support
> later once it gains traction.

This is by far the most helpful and honest post i have ever seen by
our friend alex23. I have a new found respect for you sir, thanks

-R


From piet at cs.uu.nl  Fri Aug  7 05:33:24 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Fri, 07 Aug 2009 11:33:24 +0200
Subject: problem
References: <207a84d7-fb45-46c5-a2fb-e34c564c09f8@v37g2000prg.googlegroups.com>
Message-ID: 

>>>>> sumit  (s) wrote:

>s> i want 2 hav the header files for regular expression to non
>s> deterministin autometa
>s> so whr should i find it?plz help

What header files? C? You can find lots of header files by googling. But
the header files contain only the interface, not the implementation. And
conversion from regular expression to non-deterministic automaton is an
implementation matter, so the header file will not help you there. You
will need the C or C++ file.

And then, do you want Python's implementation or any implementation.
Please be specific when you ask something.

Start by googling for regex.h for general software.
Python header file is in
http://svn.python.org/view/python/trunk/Modules/sre.h and the
implementation in http://svn.python.org/view/python/trunk/Modules/_sre.c
but I don't think it goes non deterministic. For that you can better
look into the general 'grep'-like software. For example start here:
http://arglist.com/regex/ 
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From anand at esi-india.com  Fri Aug  7 05:54:06 2009
From: anand at esi-india.com (Anand K Rayudu)
Date: Fri, 07 Aug 2009 15:24:06 +0530
Subject: How to reset document  string
Message-ID: <4A7BF9BE.2080702@esi-india.com>

Dear All,

We have extended and embedded python into my our application.
We exposed few APIs to python using

 Py_InitModule("myModuleName", myMethods);
where my methods are

static PyMethodDef VistaDbMethods[] = {
   { (char *)"myAPI",_myAPICFunctionPtr ,METH_VARARGS,"usage: MyHelp)" }


Now problem is ml_doc (Document string). Most of the time the strings 
given by development team is not descriptive enough, so support team 
want to enhance these docstring on need basis and supply to customer
The idea is we will provide get latest help option from application, 
which will contact our webserver or allow user to pick new help 
document,  which will re apply the help on fly.
 From then on our script editors will show the new enhanced help.
How do I achieve this.

I tried to change ..__doc__ = "My new doc"

This failles as it is read only attribute.

Another approach could be calling  Py_InitModule("myModuleName", 
myMethods); with new help string. But It is not working,
So I am not sure what is the right way to do it

Thanks in advance for  all your kind help

Regards,
Anand





From thorsten at thorstenkampe.de  Fri Aug  7 06:00:42 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Fri, 7 Aug 2009 12:00:42 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
Message-ID: 

* Steven D'Aprano (06 Aug 2009 19:17:30 GMT)
> On Thu, 06 Aug 2009 20:05:52 +0200, Thorsten Kampe wrote:
> > > That is significant! So the winner is:
> > > 
> > > unicode('???????','utf-8')
> > 
> > Unless you are planning to write a loop that decodes "???????" one
> > million times, these benchmarks are meaningless.
> 
> What if you're writing a loop which takes one million different lines of 
> text and decodes them once each?
> 
> >>> setup = 'L = ["abc"*(n%100) for n in xrange(1000000)]'
> >>> t1 = timeit.Timer('for line in L: line.decode("utf-8")', setup)
> >>> t2 = timeit.Timer('for line in L: unicode(line, "utf-8")', setup)
> >>> t1.timeit(number=1)
> 5.6751680374145508
> >>> t2.timeit(number=1)
> 2.6822888851165771
> 
> Seems like a pretty meaningful difference to me.

Bollocks. No one will even notice whether a code sequence runs 2.7 or 
5.7 seconds. That's completely artificial benchmarking.

Thorsten


From deets at nospam.web.de  Fri Aug  7 06:09:34 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 07 Aug 2009 12:09:34 +0200
Subject: Cython + setuptools not working with .pyx,only with .c-files
In-Reply-To: 
References: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
	
Message-ID: <7e2cquF2c8kj0U1@mid.uni-berlin.de>

David Cournapeau schrieb:
> On Thu, Aug 6, 2009 at 7:38 PM, Diez B. Roggisch wrote:
>> Hi,
>>
>>
>> I'm trying to build a Cython-extension as Egg.
>>
>> However, this doesn't work - I can either use distutils to build the
>> extension, creating a myextension.c-file on the way.
>>
>> If that's there, I can use setuptools to build the egg.
>>
>> But when I remove the .c-file, the .pyx-file isn't used to re-generate it.
>>
>> This is my setup.py:
>>
>> ----
>> import os
>> import glob
>> from setuptools import setup, Extension
>> #from distutils.core import setup
>> #from distutils.extension import Extension
>>
>> from Cython.Distutils import build_ext
> 
> What happens if you import setuptools *after* Cython.distutils ? My
> guess - I could be wrong - is that both Cython.distutils and
> setuptools monkey-patch distutils, and that setuptools does not "see"
> Cython.Distutils. It could also be an incompatibility between
> Cython.Distutils and setuptools (the design of distutils forces you to
> take into account the details of things modified by every distutils
> extension).

Tried that, nothing changed :(

Diez


From deets at nospam.web.de  Fri Aug  7 06:12:23 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 07 Aug 2009 12:12:23 +0200
Subject: need help with an egg
In-Reply-To: <4d881767-ebe3-432c-bc9b-683b80626c97@y4g2000prf.googlegroups.com>
References: <4d881767-ebe3-432c-bc9b-683b80626c97@y4g2000prf.googlegroups.com>
Message-ID: <7e2d07F2c8kj0U2@mid.uni-berlin.de>

jo schrieb:
> Hi,
> 
> I am very new to python....
> 
> I created an egg on a machine.  The Python version on that  is 2.5.
> Copied that egg to a machine which has Python 2.6.
> 
> unzip -t Myproj-0.1-py2.5.egg
> The above command shows all the files I need
> 
> When I run the easy_install, I get the foll. error.  Is it because of
> the version?  Or am I doing something wrong?  Or the way I understand
> the egg works is wrong.  Can anyone please help?
> If it's the version issue, does that mean I cannot use that egg on my
> machine with 2.6 version?
> 
> Installed /usr/local/lib/python2.6/dist-packages/Myproj-0.1-py2.5.egg
> Processing dependencies for Myproj==0.1
> Searching for Myproj==0.1
> Reading http://pypi.python.org/simple/Myproj/
> Couldn't find index page for 'Myproj' (maybe misspelled?)
> Scanning index of all packages (this may take a while)
> Reading http://pypi.python.org/simple/
> No local packages or download links found for Myproj==0.1
> error: Could not find suitable distribution for Requirement.parse
> ('Myproj==0.1')

Yes, eggs are (at least) python version specific. They can even be 
OS-specific.


Diez


From thorsten at thorstenkampe.de  Fri Aug  7 06:12:32 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Fri, 7 Aug 2009 12:12:32 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	
Message-ID: 

* Michael Str?der (Fri, 07 Aug 2009 03:25:03 +0200)
> Thorsten Kampe wrote:
> > * Michael Str?der (Thu, 06 Aug 2009 18:26:09 +0200)
> >>>>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
> >> 17.23644495010376
> >>>>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
> >> 72.087096929550171
> >>
> >> That is significant! So the winner is:
> >>
> >> unicode('???????','utf-8')
> > 
> > Unless you are planning to write a loop that decodes "???????" one 
> > million times, these benchmarks are meaningless.
> 
> Well, I can tell you I would not have posted this here and checked it if it
> would be meaningless for me. You don't have to read and answer this thread if
> it's meaningless to you.

Again: if you think decoding "???????" one million times is a real world 
use case for your module then go for unicode(). Otherwise the time you 
spent benchmarking artificial cases like this is just wasted time. In 
real life people won't even notice whether an application takes one or 
two minutes to complete.

Use whatever you prefer (decode() or unicode()). If you experience 
performance bottlenecks when you're done, test whether changing decode() 
to unicode() makes a difference. /That/ is relevant.

Thorsten


From deets at nospam.web.de  Fri Aug  7 06:17:50 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 07 Aug 2009 12:17:50 +0200
Subject: How to reset document  string
In-Reply-To: 
References: 
Message-ID: <7e2daiF2da4u8U1@mid.uni-berlin.de>

Anand K Rayudu schrieb:
> Dear All,
> 
> We have extended and embedded python into my our application.
> We exposed few APIs to python using
> 
> Py_InitModule("myModuleName", myMethods);
> where my methods are
> 
> static PyMethodDef VistaDbMethods[] = {
>   { (char *)"myAPI",_myAPICFunctionPtr ,METH_VARARGS,"usage: MyHelp)" }
> 
> 
> Now problem is ml_doc (Document string). Most of the time the strings 
> given by development team is not descriptive enough, so support team 
> want to enhance these docstring on need basis and supply to customer
> The idea is we will provide get latest help option from application, 
> which will contact our webserver or allow user to pick new help 
> document,  which will re apply the help on fly.
>  From then on our script editors will show the new enhanced help.
> How do I achieve this.
> 
> I tried to change ..__doc__ = "My new doc"
> 
> This failles as it is read only attribute.
> 
> Another approach could be calling  Py_InitModule("myModuleName", 
> myMethods); with new help string. But It is not working,
> So I am not sure what is the right way to do it

To put the right docstrings into the embedded interpreter. I don't know 
about your processes, but either the support just suggests better 
strings & developers put them in there, or maybe some sort of shared 
header-file could be used that the developers use & support enhances. 
Something like this:


--- docstrings.h ---

#define VistaDbMethods__doc__ "usage: MyHelp"


And if that's enhanced over time by the support-staff, docs will get 
better. Hopefully.

Alternatives are:

  - beating your developers with a clue-stick into submission that good 
docs are important
  - write a usage-guide using e.g. sphinx and release that as add-on-docs.

Diez


From http  Fri Aug  7 06:43:48 2009
From: http (Paul Rubin)
Date: 07 Aug 2009 03:43:48 -0700
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
Message-ID: <7xk51fgazf.fsf@ruckus.brouhaha.com>

alex23  writes:
> I'd still like to see this kept out of the official docs as much as
> possible, mostly for reasons of brevity & clarity. I think the
> official docs should be considered definitive and not require a
> hermeneutic evaluation against user comments to ensure they're still
> correct...

Such evaluation would only do them good.  The official docs are full
of errors and omissions, which is why we have this thread going on
here in the newsgroup.


From dioxide.software at gmail.com  Fri Aug  7 07:09:25 2009
From: dioxide.software at gmail.com (KK)
Date: Fri, 7 Aug 2009 04:09:25 -0700 (PDT)
Subject: pylucene installation problem on Ubuntu 9.04
References: 
	 
	
Message-ID: 

I tried doing something silly.
I went to the directory "/usr/local/lib/python2.6/site-packages" and
then tried to compile/run the file called PyLucene.py the way we
compile/run python scripts, then from there i started the python
interpreter by typing python ( which is actually python2.6), then i
tried to import that module, [un]fortunately it din't give that error
message but something else, you can see below:

kk-laptop:/usr/local/lib/python2.6/site-packages$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> indexDir = '/opt/lucene/index'
>>> import PyLucene
WARNING: could not properly read security provider files:
         file:///usr/local/gcc-3.4.6/lib/security/libgcj.security
         file:///usr/local/gcc-3.4.6/lib/security/classpath.security
         Falling back to standard GNU security provider
>>>

then tried to copy and paste my sample code for indexing data to
lucene, this way:


>>> writer = IndexWriter(indexDir, StandardAnalyzer(), True)
>>> title = "this is sample page title"
>>> content = "This is sample page content for testing pylucene tool"
>>>
>>> doc = Document()
>>> doc.add(Field("title", title, Field.Store.YES, Field.Index.TOKENIZED))
>>> doc.add(Field("content", content, Field.Store.YES, Field.Index.TOKENIZED))
>>> writer.addDocument(doc)
>>> writer.optimize()
>>>

----------------------------
and surprisingly it din't give any other error. to crosscheck things i
went to the lucene index directory and fired LUKE and luckily found
that doc being indexed by lucene, even i tried searching for some
words and found they are working fine. So Pylucene seems to be working
partially, in my case. But I think python is not able to load the
PyLucene module (btw, i din't see any __init__ scripts which, i guess,
are used for bootstrapping external modules, right?). Then what is the
fix for this? do we have to add some __init__ scripts to make python
load PyLucene module when it starts? do i sound silly? What is the
best/easiest way to get this working? I've spend quite a lot of time
jsut to make PyLucene running but to no avail.
BTW, I tried to start the python interpreter from other locations and
tried imporitn this PyLucene module but got the same irritating error
message saying "module not found".
Also trying to run my sample indexer from cli using the normal way[kk-
laptop$ python indexer.py] gave the same error message.

Any help/advice is highly appreciated.
Thanks,
KK

On Aug 7, 8:22?am, KK  wrote:
> On Aug 7, 12:38?am, Jon Clements  wrote:
>
>
>
> > On 6 Aug, 19:49, KK  wrote:
>
> > > hi all,
> > > I've trying to install pylucene on my linux box from last 2 days but
> > > not able to do so. first i tried to install it using apt-get like
> > > this,
> > > kk-laptop$ sudo apt-get install pylucene
> > > and it did install python2.5, python2.5-minimal and pylucene. I must
> > > mention one thing that I already had python2.6 on my box as the
> > > default python i.e /usr/bin/python is linked to python2.6. Anyway s,
> > > now i started the python interpreter using "python" command from cli
> > > and then to make sure pylucene has been installed i tried to import
> > > the module and to my surprise it said "module pylucene not found".
> > > I thought I should enter the python2.6 env and do the same , so i
> > > tried starting the python2.6 interpreter using "python2.6" as the
> > > command and tried importing the same module and again it failed giving
> > > the same irritating message.
> > > ?As a final try i pulled the source code of pylucene and as per the
> > > comments given there in the README file, copied the mentioned files to
> > > site-packages directory of python2.6 and then tried importing the
> > > module and then got the same error message saying no module name
> > > pylucene is present. I'm sick of this error !
> > > Can someone point me what is the issue? If it is due to multiple
> > > version of python running on box, can someone tell me which one to
> > > remove or someone tell me how to get the whole thing running? I'll
> > > very much thankful to you guys.
>
> > > Thanks,
> > > KK.
>
> > If you installed using apt, have you a pylucene directory under /usr/
> > local/lib/python2.6/dist-packages/?
>
> > Also, if you run python, and import sys; print sys.path
> > whats it show?
>
> > Jon.
>
> Yes I've a dirctory called dist-packages under python2.6 but that
> doesn't contain anything on pylucene [it has lupyne, which i installed
> day before yesterday and importing lupyne doesn't give any error msg,
> but again it is dependent on pylucene]
> # for python the output is :
> ------------------------------
> kk-laptop$ python
> Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> import sys
> >>> print sys.path
>
> ['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/
> python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/
> lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/
> dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/var/
> lib/python-support/python2.6', '/usr/lib/python2.6/dist-packages/
> gtk-2.0', '/var/lib/python-support/python2.6/gtk-2.0', '/usr/local/lib/
> python2.6/dist-packages']
>
> -------------------------------
>
> for python2.5 this is the output:
> kk-laptop$ python2.5
> Python 2.5.4 (r254:67916, Apr ?4 2009, 17:55:16)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> import sys
> >>> print sys.path
>
> ['', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/
> python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/
> python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/
> lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/
> gst-0.10', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/
> site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0']
>
> --------------------------------
>
> and for python2.6 the output is this:
> kk-laptop$ python2.6
> Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> import sys
> >>> print sys.path
>
> ['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/
> python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/
> lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/
> dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/var/
> lib/python-support/python2.6', '/usr/lib/python2.6/dist-packages/
> gtk-2.0', '/var/lib/python-support/python2.6/gtk-2.0', '/usr/local/lib/
> python2.6/dist-packages']
>
> From all of the above what I can see is we don't have any directory
> named dist-packages under python2.5 but we've one under 2.6, then
> where did all those pylucene files got installed to after i installed
> it using apt-get? Any ideas?
>
> Thanks
> KK



From andrew at acooke.org  Fri Aug  7 07:29:13 2009
From: andrew at acooke.org (andrew cooke)
Date: Fri, 7 Aug 2009 04:29:13 -0700 (PDT)
Subject: Parsing Binary Structures; Is there a better way / What is your 
	way?
References: 
Message-ID: <4c436221-7f6e-43ca-9ece-6b05afac540a@g1g2000vbr.googlegroups.com>

On Aug 5, 10:46?am, "Martin P. Hellwig" 
wrote:
> Hi List,
>
> On several occasions I have needed (and build) a parser that reads a
> binary piece of data with custom structure. For example (bogus one):
>
> BE
> +---------+---------+-------------+-------------+------+--------+
> | Version | Command | Instruction | Data Length | Data | Filler |
> +---------+---------+-------------+-------------+------+--------+
> Version: 6 bits
> Command: 4 bits
> Instruction: 5 bits
> Data Length: 5 bits
> Data: 0-31 bits
> Filler: filling 0 bits to make the packet dividable by 8

hi,

sorry i'm a bit late here, but lepl does exactly this.  also, as you
asked for in another post, the BitString class allows arbitrary
indexing into a sequence of bits.  and because it's part of a
recursive descent parser you can match "anything" (lepl will handle -
although less efficiently - left recursive and ambiguous grammars).

see the example at http://www.acooke.org/lepl/binary.html#matching
which constructs an ethernet frame and then parses it, extracting the
source and destination addresses.

feel free to email me with more questions.

disclaimer: this is quite new and i don't know of anyone that actually
uses it; it is also Python3 only (because it uses bytes()).

andrew




From cournape at gmail.com  Fri Aug  7 07:35:24 2009
From: cournape at gmail.com (David Cournapeau)
Date: Fri, 7 Aug 2009 20:35:24 +0900
Subject: Cython + setuptools not working with .pyx,only with .c-files
In-Reply-To: <7e2cquF2c8kj0U1@mid.uni-berlin.de>
References: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
	
	<7e2cquF2c8kj0U1@mid.uni-berlin.de>
Message-ID: <5b8d13220908070435i2ee17e9cgb183ee11791d401b@mail.gmail.com>

On Fri, Aug 7, 2009 at 7:09 PM, Diez B. Roggisch wrote:

>
> Tried that, nothing changed :(

Then you will have to modify Cython.Distutils to be aware of
setuptools, I think (and soon Distribute... ).

David


From garabik-news-2005-05 at kassiopeia.juls.savba.sk  Fri Aug  7 07:49:05 2009
From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk)
Date: Fri, 7 Aug 2009 11:49:05 +0000 (UTC)
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
Message-ID: 

Thorsten Kampe  wrote:
> * Steven D'Aprano (06 Aug 2009 19:17:30 GMT)
>> What if you're writing a loop which takes one million different lines of 
>> text and decodes them once each?
>> 
>> >>> setup = 'L = ["abc"*(n%100) for n in xrange(1000000)]'
>> >>> t1 = timeit.Timer('for line in L: line.decode("utf-8")', setup)
>> >>> t2 = timeit.Timer('for line in L: unicode(line, "utf-8")', setup)
>> >>> t1.timeit(number=1)
>> 5.6751680374145508
>> >>> t2.timeit(number=1)
>> 2.6822888851165771
>> 
>> Seems like a pretty meaningful difference to me.
> 
> Bollocks. No one will even notice whether a code sequence runs 2.7 or 
> 5.7 seconds. That's completely artificial benchmarking.
>

For a real-life example, I have often a file with one word per line, and
I run python scripts to apply some (sometimes fairy trivial)
transformation over it. REAL example, reading lines with word, lemma,
tag separated by tabs from stdin and writing word into stdout, unless it
starts with '<' (~6e5 lines, python2.5, user times, warm cache, I hope
the comments are self-explanatory)

no unicode
user    0m2.380s

decode('utf-8'), encode('utf-8')
user    0m3.560s

sys.stdout = codecs.getwriter('utf-8')(sys.stdout);sys.stdin = codecs.getreader('utf-8')(sys.stdin)
user    0m6.180s

unicode(line, 'utf8'), encode('utf-8')
user    0m3.820s

unicode(line, 'utf-8'), encode('utf-8')
user    0m2.880sa

python3.1
user    0m1.560s

Since I have something like 18 million words in my currenct project (and
 > 600 million overall) and I often tweak some parameters and re-run the
 > transformations, the differences are pretty significant.

Personally, I have been surprised by:
1) bad performance of the codecs wrapper (I expected it to be on par with 
   unicode(x,'utf-8'), mayble slightly better due to less function calls
2) good performance of python3.1 (utf-8 locale)


-- 
 -----------------------------------------------------------
| Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__    garabik @ kassiopeia.juls.savba.sk     |
 -----------------------------------------------------------
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!


From dmitrey.kroshko at scipy.org  Fri Aug  7 08:00:40 2009
From: dmitrey.kroshko at scipy.org (dmitrey)
Date: Fri, 7 Aug 2009 05:00:40 -0700 (PDT)
Subject: how to overload operator "<  <" (a < x < b)?
Message-ID: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>

hi all,
is it possible to overload operator "<  <"? (And other like this one,
eg "<=  <=", ">  >", ">=  >=")
Any URL/example?
Thank you in advance, D.


From davea at ieee.org  Fri Aug  7 08:15:11 2009
From: davea at ieee.org (Dave Angel)
Date: Fri, 07 Aug 2009 08:15:11 -0400
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>	
		<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
Message-ID: <4A7C1ACF.80505@ieee.org>

alex23 wrote:
> Paul Rubin  wrote:
>   
>> The PHP docs as I remember are sort of regular (non-publically
>> editable) doc pages, each of which has a public discussion thread
>> where people can post questions and answers about the topic of that
>> doc page.  I thought it worked really well.  The main thing is that
>> the good stuff from the comment section gets folded into the actual
>> doc now and then.
>>     
>
> I'd still like to see this kept out of the official docs as much as
> possible, mostly for reasons of brevity & clarity. I think the
> official docs should be considered definitive and not require a
> hermeneutic evaluation against user comments to ensure they're still
> correct...
>
> How about a secondary site that embeds the docs and provides
> commenting functionality around it? That's certainly a finitely scoped
> project that those with issues about the docs could establish and
> contribute to, with the possibility of it gaining official support
> later once it gains traction.
>
>
>   
I share your concern about unmonitored comments.  However, it seems a 
useful possibility would be for the "official" pages to each have 
specially-marked links that possibly lead to such user comments.  
Clearly they'd have to marked carefully, so that naive users don't 
confuse the two.  But otherwise, it feels like a good idea.

In my case, I usually access the docs via the Windows help file.  So 
it'd be quite easy for me to recognize that once I've gotten to a 
browser page, I'm not in Kansas any more.  But that could be also 
accomplished by having a very different stylesheet for the user comments 
page.

DaveA



From deets at nospam.web.de  Fri Aug  7 08:16:22 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 07 Aug 2009 14:16:22 +0200
Subject: how to overload operator "<  <" (a < x < b)?
In-Reply-To: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
Message-ID: <7e2k8mF2djd57U1@mid.uni-berlin.de>

dmitrey schrieb:
> hi all,
> is it possible to overload operator "<  <"? (And other like this one,
> eg "<=  <=", ">  >", ">=  >=")
> Any URL/example?
> Thank you in advance, D.

http://docs.python.org/reference/datamodel.html#object.__lt__

Diez


From __peter__ at web.de  Fri Aug  7 08:21:31 2009
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Aug 2009 14:21:31 +0200
Subject: how to overload operator "<  <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
Message-ID: 

dmitrey wrote:

> is it possible to overload operator "<  <"? (And other like this one,
> eg "<=  <=", ">  >", ">=  >=")

No. 

a < x < b 

is a shortcut for 

a < x and x < b

where x is of course evaluated only once.

Peter




From durumdara at gmail.com  Fri Aug  7 08:31:10 2009
From: durumdara at gmail.com (durumdara)
Date: Fri, 7 Aug 2009 05:31:10 -0700 (PDT)
Subject: Bug or feature: double strings as one
Message-ID: 

Hi!

I found an interesting thing in Python.
Today one of my "def"s got wrong result.

When I checked the code I saw that I miss a "," from the list.

l = ['?' '?']

Interesting, that Python handle them as one string.

print ['?' '?']
['\xf3\xd3']

I wanna ask that is a bug or is it a feature?

In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
must concatenate the strings with some sign, like "+" or "||".

This technic is avoid the mistyping, like today. But in python I can
miss the concat sign, and I got wrong result...

Thanks for your help and for your answer:
   dd




From pavlovevidence at gmail.com  Fri Aug  7 08:33:25 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 7 Aug 2009 05:33:25 -0700 (PDT)
Subject: How to reset document string
References: 
Message-ID: 

On Aug 7, 2:54?am, Anand K Rayudu  wrote:
> Dear All,
>
> We have extended and embedded python into my our application.
> We exposed few APIs to python using
>
> ?Py_InitModule("myModuleName", myMethods);
> where my methods are
>
> static PyMethodDef VistaDbMethods[] = {
> ? ?{ (char *)"myAPI",_myAPICFunctionPtr ,METH_VARARGS,"usage: MyHelp)" }
>
> Now problem is ml_doc (Document string). Most of the time the strings
> given by development team is not descriptive enough, so support team
> want to enhance these docstring on need basis and supply to customer
> The idea is we will provide get latest help option from application,
> which will contact our webserver or allow user to pick new help
> document, ?which will re apply the help on fly.
> ?From then on our script editors will show the new enhanced help.
> How do I achieve this.

Sounds very cool.  I have a few ideas.

1. Since you say you are embedding Python in your application, the
most direct way might be to modify the Python interpreter to allow the
__doc__ attribute to be changed.  You'd have to modify the PyCFunction
type (defined in methodobject.h and methodobject.c) to allow
overriding the compiled-in doc field.

2. Instead of replacing the __doc__ attribute of the function, just
replace the whole function with a wrapper.  So, for instance, if your
application decides to update the docstring for myModuleName.myAPI(),
instead of running code like this:

    myModuleName.myAPI.__doc__ = 'new docstring'

run code like this:

    def create_wrapper(func,docstring):
        def wrapper(*args):
            return func(*args)
        wrapper.__doc__ = doc
        return wrapper
    myModuleName.myAPI = create_wrapper(
                 myModuleName.myAPI,'new docstring')

So now myApi is a Python function with the new docstring that calls
the old function.  (Note: if you are concerned with efficiency, it's
possible to write a wrapper in C that has very little overhead.)

This approach has minor disadvantages (such as if any code write from
myModuleName import myAPI--it won't see the new version) but it may be
the easiest approach.

3. Instead of customizing the __doc__ attribute, store any custom
docstrings in a dictionary keyed by the function.

    custom_doc[myModuleName.myApi] = 'new docstring'

Your script editor, when looking for documentation, will first search
in this custom area to see if the docstring has been overridden; if
so, use that; if not, use the docstring.  Something like this:

    def documentation_to_use_in_script_editor(func):
        try:
            return custom_doc[func]
        except KeyError:
            return func.__doc__

That has the negative of the special docstring not being visible at an
interactive prompt.


I have given you some fairly vague answers, hopefully that'll give you
some idea.  It sounds like you have an ambitious project, suggesting
that you are probably good enough to implement the suggestions.


Carl Banks


From davea at ieee.org  Fri Aug  7 08:34:00 2009
From: davea at ieee.org (Dave Angel)
Date: Fri, 07 Aug 2009 08:34:00 -0400
Subject: Web page data and urllib2.urlopen
In-Reply-To: 
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>			
	
Message-ID: <4A7C1F38.8010701@ieee.org>


Piet van Oostrum wrote:
>>>>>> 
>>>>>>             
> 
>> DA> But the raw page didn't have any javascript.  So what about that original
>> DA> raw page triggered additional stuff to be loaded?
>> DA> Is it "user agent", as someone else brought out?  And is there somewhere I
>> DA> can read more about that aspect of things?  I've mostly built very static
>> DA> html pages, where the server yields the same page to everybody.  And some
>> DA> form stuff, where the  user clicks on a 'submit" button to trigger a script
>> DA> that's not shown on the URL line.
>>     
>
> Yes, if you specify a 'normal' web browser as user agent you do get the
> Javascript:
>
> import urllib2
>
> request = urllib2.Request('http://www.marketwatch.com/story/mondays-biggest-gaining-and-declining-stocks-2009-07-27')
> request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13')
>
> opener = urllib2.build_opener() 
> page = opener.open(request).read()
> print page
>
>   
Thanks much.  That's a key I didn't understand.

DaveA


From deets at nospam.web.de  Fri Aug  7 08:37:48 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 07 Aug 2009 14:37:48 +0200
Subject: Bug or feature: double strings as one
In-Reply-To: 
References: 
Message-ID: <7e2lgtF2bpusmU1@mid.uni-berlin.de>

durumdara schrieb:
> Hi!
> 
> I found an interesting thing in Python.
> Today one of my "def"s got wrong result.
> 
> When I checked the code I saw that I miss a "," from the list.
> 
> l = ['?' '?']
> 
> Interesting, that Python handle them as one string.
> 
> print ['?' '?']
> ['\xf3\xd3']
> 
> I wanna ask that is a bug or is it a feature?
> 
> In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
> must concatenate the strings with some sign, like "+" or "||".
> 
> This technic is avoid the mistyping, like today. But in python I can
> miss the concat sign, and I got wrong result...

It's a feature. It is sometimes used in cases where you want to split a 
longer text into several lines, but without introducing newlines.

like this (the parentheses are there for the parser not to puke):


foo = ("foobarbaz"
        "padamm")

It has the potential to produce errors as you have seen them, though.

Diez


From s.selvamsiva at gmail.com  Fri Aug  7 08:40:49 2009
From: s.selvamsiva at gmail.com (S.Selvam)
Date: Fri, 7 Aug 2009 18:10:49 +0530
Subject: pulldom extracting records from recordset
Message-ID: 

Hi all,

I am using pulldom to handle large xml files.It works fine, but i do not
know how to store a particular set of  records(as xml) out of the recordset.
-----------------code---------
from xml.dom import pulldom
hamlet_file = open("input_xml/inp_test.xml")
events = pulldom.parse(hamlet_file)
for (event, node) in events:
  if event == pulldom.START_ELEMENT:
    if node.tagName == "Record":
     events.expandNode(node)
     print node  #this does not work as it is a object
------------------------------

Whenever the node name is a Record,i process it. I want to store the all the
nodes meeting my requirement.
  For eg,i need output as below,

         
            
                 hi
           
           
            ---
           
        

         
            
                 hello
           .
           .
Where input xml might contain 'n' number of Records.
I have been struggling to figure it out.I would be happy to get a solution
for this.

-- 
Yours,
S.Selvam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From __peter__ at web.de  Fri Aug  7 08:41:36 2009
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Aug 2009 14:41:36 +0200
Subject: Bug or feature: double strings as one
References: 
Message-ID: 

durumdara wrote:

> I found an interesting thing in Python.
> Today one of my "def"s got wrong result.
> 
> When I checked the code I saw that I miss a "," from the list.
> 
> l = ['?' '?']
> 
> Interesting, that Python handle them as one string.
> 
> print ['?' '?']
> ['\xf3\xd3']
> 
> I wanna ask that is a bug or is it a feature?

Feature:

http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation

Peter



From benjamin.kaplan at case.edu  Fri Aug  7 08:50:52 2009
From: benjamin.kaplan at case.edu (Benjamin Kaplan)
Date: Fri, 7 Aug 2009 08:50:52 -0400
Subject: how to overload operator "< <" (a < x < b)?
In-Reply-To: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
Message-ID: 

On Fri, Aug 7, 2009 at 8:00 AM, dmitrey wrote:
> hi all,
> is it possible to overload operator "< ?<"? (And other like this one,
> eg "<= ?<=", "> ?>", ">= ?>=")
> Any URL/example?
> Thank you in advance, D.

That isn't an operator at all. Python does not support compound
comparisons like that. You have to do "a > b and b > c".
> --
> http://mail.python.org/mailman/listinfo/python-list
>


From piet at cs.uu.nl  Fri Aug  7 08:54:31 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Fri, 07 Aug 2009 14:54:31 +0200
Subject: Web page data and urllib2.urlopen
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
	
	
	
	
	
Message-ID: 

>>>>> Dave Angel  (DA) wrote:

>DA> Piet van Oostrum wrote:
>>>>>>>> 
>>>>>>>> 
>>> 
>DA> But the raw page didn't have any javascript.  So what about that original
>DA> raw page triggered additional stuff to be loaded?
>DA> Is it "user agent", as someone else brought out?  And is there somewhere I
>DA> can read more about that aspect of things?  I've mostly built very static
>DA> html pages, where the server yields the same page to everybody.  And some
>DA> form stuff, where the  user clicks on a 'submit" button to trigger a script
>DA> that's not shown on the URL line.
>>>> 
>>> 
>>> Yes, if you specify a 'normal' web browser as user agent you do get the
>>> Javascript:
>>> 
>>> import urllib2
>>> 
>>> request = urllib2.Request('http://www.marketwatch.com/story/mondays-biggest-gaining-and-declining-stocks-2009-07-27')
>>> request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13')
>>> 
>>> opener = urllib2.build_opener() page = opener.open(request).read()
>>> print page
>>> 
>>> 
>DA> Thanks much.  That's a key I didn't understand.

You can even specify the headers in the Request constructor:


url = 'http://www.marketwatch.com/story/mondays-biggest-gaining-and-declining-stocks-2009-07-27'
hdr = {'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13'}
request = urllib2.Request(url = url, headers = hdr)

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From s.selvamsiva at gmail.com  Fri Aug  7 09:04:01 2009
From: s.selvamsiva at gmail.com (S.Selvam)
Date: Fri, 7 Aug 2009 18:34:01 +0530
Subject: pulldom extracting records from recordset
In-Reply-To: 
References: 
Message-ID: 

On Fri, Aug 7, 2009 at 6:10 PM, S.Selvam  wrote:

> Hi all,
>
> I am using pulldom to handle large xml files.It works fine, but i do not
> know how to store a particular set of  records(as xml) out of the recordset.
> -----------------code---------
> from xml.dom import pulldom
> hamlet_file = open("input_xml/inp_test.xml")
> events = pulldom.parse(hamlet_file)
> for (event, node) in events:
>   if event == pulldom.START_ELEMENT:
>     if node.tagName == "Record":
>      events.expandNode(node)
>      print node  #this does not work as it is a object
> ------------------------------
>
> Whenever the node name is a Record,i process it. I want to store the all
> the nodes meeting my requirement.
>   For eg,i need output as below,
>
>          
>             
>                  hi
>            
>            
>             ---
>            
>         
>
>          
>             
>                  hello
>            .
>            .
> Where input xml might contain 'n' number of Records.
> I have been struggling to figure it out.I would be happy to get a solution
> for this.
>
> --
> Yours,
> S.Selvam
>

Hi all,
   I just found the solution,
         *node.toprettyxml()*
     has done it.



-- 
Yours,
S.Selvam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From piet at cs.uu.nl  Fri Aug  7 09:09:29 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Fri, 07 Aug 2009 15:09:29 +0200
Subject: how to kill subprocess when Python process is killed?
References: <0feaa2a3-5b73-43e4-9b24-11f157ff6d18@l34g2000vba.googlegroups.com>
Message-ID: 

>>>>> "mark.v.weber at gmail.com"  (M) wrote:

>M> I am writing a Python program that launches a subprocess (using
>M> Popen).
>M> I am reading stdout of the subprocess, doing some filtering, and
>M> writing to
>M> stdout of the main process.

>M> When I kill the main process (cntl-C) the subprocess keeps running.
>M> How do I kill the subprocess too? The subprocess is likey to run a
>M> long time.

>M> Context:
>M> I'm launching only one subprocess at a time, I'm filtering its stdout.
>M> The user might decide to interrupt to try something else; the user
>M> wants the process and all subprocesses to go away in response
>M> to a cntl-C

>M> I'm new to python; solution must be for Python 2.5 (windows) to help
>M> me.

>M> Any help and/or pointers appreciated.

When the parent dies, the child should die when it's writing on the
broken pipe. At least that's how it works in Unix systems. I don't know
about Windows, however.

To let the dying be fast you should make sure that stdout in the child
is unbuffered.

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From thorsten at thorstenkampe.de  Fri Aug  7 09:10:29 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Fri, 7 Aug 2009 15:10:29 +0200
Subject: Is python buffer overflow proof?
References: 
	
	
Message-ID: 

* Neil Hodgson (Tue, 04 Aug 2009 13:32:55 GMT)
> Thorsten Kampe:
> > You cannot create "your own" buffer overflow in Python as you can in 
C 
> > and C++ but your code could still be vulnerable if the underlying Python 
> > construct is written in C.
> 
>    Python's standard library does now include unsafe constructs.

I don't doubt that. If Python contains a buffer overflow vulnerability 
your code will also be susceptible to that. Please read the link I 
provided as an example.

Thorsten


From wuwei23 at gmail.com  Fri Aug  7 09:48:20 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 06:48:20 -0700 (PDT)
Subject: how to overload operator "< <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
Message-ID: 

On Aug 7, 10:50?pm, Benjamin Kaplan  wrote:
> That isn't an operator at all. Python does not support compound
> comparisons like that. You have to do "a > b and b > c".

You know, it costs nothing to open up a python interpreter and check
your certainty:

>>> x = 10
>>> 1 < x < 20
True

This is a _very_ common pattern.

>>> class X(object):
...   def __lt__(self, other):
...     print 'in lt'
...     return True
...   def __gt__(self, other):
...     print 'in gt'
...     return True
...
>>> x = X()
>>> 1 < x < 20
in gt
in lt
True
>>> 20 < x < 1
in gt
in lt
True

dmitrey: Diez' advice was the best you received.


From kdawg44 at gmail.com  Fri Aug  7 09:52:16 2009
From: kdawg44 at gmail.com (Kevin Holleran)
Date: Fri, 7 Aug 2009 09:52:16 -0400
Subject: Changing Remote Registry
Message-ID: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>

Good morning,

I fear the answer to this is that I just cannot do this....

I wrote a python script that goes out to a bunch of remote machines and
queries the registry for some values.  Effectively, there have been some
software upgrades that have been done as the need arose but we need to do
them across the organization now.  There are three, and the script checks
all three and returns the values.  One of these just needs to be a registry
change as it is a client server application that the server was upgraded and
the clients need a change to a registry value to work.

Long story short, I am using _winreg to do this.

hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
value,type = _winreg.QueryValueEx(hKey, item)
if (value == wrongValue):
       _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)


When I do this I receive the error:

_winreg.SetValue WindowsError: [Error 5] Access Denied


I am running this from my machine as a domain admin, connecting to the
remote machine which is also on the domain.
I am connecting to the remote registry with:

keyPath = _winreg.ConnectRegistry(r"\\" +
ipAddress,_winreg.HKEY_LOCAL_MACHINE)


Thanks for any help.

--
Kevin Holleran
Master of Science, Computer Information Systems
Grand Valley State University
Master of Business Administration
Western Michigan University
Completion December 2009
CCNA, ISA, MCSA, MCDST, MCP

"We are what we repeatedly do. Excellence, then, is not an act, but a
habit." - Aristotle

"A man flattened by an opponent can get up again. A man flattened by
conformity stays down for good. " - Thomas J. Watson
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From wuwei23 at gmail.com  Fri Aug  7 09:53:22 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 06:53:22 -0700 (PDT)
Subject: unicode() vs. s.decode()
References: 
	 
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	 
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
Message-ID: <556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>

Thorsten Kampe  wrote:
> Bollocks. No one will even notice whether a code sequence runs 2.7 or
> 5.7 seconds. That's completely artificial benchmarking.

But that's not what you first claimed:

> I don't think any measurable speed increase will be
> noticeable between those two.

But please, keep changing your argument so you don't have to admit you
were wrong.


From stargaming at gmail.com  Fri Aug  7 09:59:45 2009
From: stargaming at gmail.com (Robert Lehmann)
Date: Fri, 7 Aug 2009 13:59:45 +0000 (UTC)
Subject: how to overload operator "< <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
Message-ID: 

On Fri, 07 Aug 2009 08:50:52 -0400, Benjamin Kaplan wrote:

> On Fri, Aug 7, 2009 at 8:00 AM, dmitrey
> wrote:
>> hi all,
>> is it possible to overload operator "< ?<"? (And other like this one,
>> eg "<= ?<=", "> ?>", ">= ?>=")
>> Any URL/example?
>> Thank you in advance, D.
> 
> That isn't an operator at all. Python does not support compound
> comparisons like that. You have to do "a > b and b > c".

Python actually allows you to chain comparison operators, automatically 
unpacking ``a > b > c`` to ``a > b and b > c``::

>>> class C(object):
...   def __lt__(self, other):
...     print self, "LESS-THAN", other
...     return True
... 
>>> a = C(); b = C(); x = C()
>>> a < x < b
<__main__.C object...> LESS-THAN <__main__.C object...>
<__main__.C object...> LESS-THAN <__main__.C object...>
True

>>> x = 42
>>> 40 < x < 50 # between 40 and 50
True
>>> 50 < x < 60 # between 50 and 60
False
>>> 1 == True < 2 == 2.0 < 3 < 4 != 5 > 0 # yikes, unreadable! but legal.
True
>>> # same as: (1 == True) and (True < 2) and (2 == 2.0) ...

HTH,

-- 
Robert "Stargaming" Lehmann



From wuwei23 at gmail.com  Fri Aug  7 10:05:20 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 07:05:20 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
Message-ID: 

Paul Rubin  wrote:
> Such evaluation would only do them good. ?The official docs are full
> of errors and omissions, which is why we have this thread going on
> here in the newsgroup.

And there is a process for reporting and correcting such errors and
omissions, which is what I pointed out in my post.


From Scott.Daniels at Acm.Org  Fri Aug  7 10:08:59 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Fri, 07 Aug 2009 07:08:59 -0700
Subject: Problem in installing PyGreSQL
In-Reply-To: 
References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com>	<7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net>	<20090804084856.b825967a.darcy@druid.net>		<20090804095547.a5274e22.darcy@druid.net>		<7aa29e790908060330x67d900a9rfb4677eaf0eddeb@mail.gmail.com>
	
Message-ID: 

Dennis Lee Bieber wrote:
> On Thu, 6 Aug 2009 16:00:15 +0530, "Thangappan.M"
>  declaimed the following in
> gmane.comp.python.general:
>>   File "./setup.py", line 219, in finalize_options
>>     except (Warning, w):
>> NameError: global name 'w' is not defined
>>
>> What would be the solution?
>> Otherwise can you tell how to install DB-API in debian machine.
> 	Sorry... 1) I run on WinXP; 2) I don't build packages, relying on
> pre-built binaries; 3) I run MySQL.
> 
> 	However, based upon the examples in the Tutorial, that line should
> not have the (, ). A parenthesised (tuple) is suppose to contain a list
> of exceptions, and the parameter to catch the exception specifics has to
> be outside the list.
> 
> 	Best I can suggest is editing that particular line and removing the
> (, ) -- then try rebuilding.
> 
> 	I'll also re-ask: All you are installing is the Python adapter to
> the database. DO YOU HAVE A RUNNING PostgreSQL server that you can
> connect to?

Just to be a bit more explict:
Change file setup.py's line 219 from:
 >>     except (Warning, w):
to either (OK in Python 2.6 and greater):
        except Warning as w:
or (works for Python 2.X):
        except Warning, w:


--Scott David Daniels
Scott.Daniels at Acm.Org


From python at mrabarnett.plus.com  Fri Aug  7 10:11:47 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Fri, 07 Aug 2009 15:11:47 +0100
Subject: Changing Remote Registry
In-Reply-To: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
Message-ID: <4A7C3623.5020702@mrabarnett.plus.com>

Kevin Holleran wrote:
> Good morning,
> 
> I fear the answer to this is that I just cannot do this....
> 
> I wrote a python script that goes out to a bunch of remote machines and 
> queries the registry for some values.  Effectively, there have been some 
> software upgrades that have been done as the need arose but we need to 
> do them across the organization now.  There are three, and the script 
> checks all three and returns the values.  One of these just needs to be 
> a registry change as it is a client server application that the server 
> was upgraded and the clients need a change to a registry value to work.
> 
> Long story short, I am using _winreg to do this.
> 
> hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
> value,type = _winreg.QueryValueEx(hKey, item)
> if (value == wrongValue):
>        _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
>                
> 
> When I do this I receive the error:
> 
> _winreg.SetValue WindowsError: [Error 5] Access Denied
> 
> 
> I am running this from my machine as a domain admin, connecting to the 
> remote machine which is also on the domain.
> I am connecting to the remote registry with:
> 
> keyPath = _winreg.ConnectRegistry(r"\\" + 
> ipAddress,_winreg.HKEY_LOCAL_MACHINE)
> 
> 
> Thanks for any help. 
> 
What is 'ipAddress'? Is it an actual IP address? The documentation says
it should be the computer name.


From invalid at invalid  Fri Aug  7 10:13:33 2009
From: invalid at invalid (Grant Edwards)
Date: Fri, 07 Aug 2009 09:13:33 -0500
Subject: Bug or feature: double strings as one
References: 
Message-ID: 

On 2009-08-07, durumdara  wrote:
> Hi!
>
> I found an interesting thing in Python.
> Today one of my "def"s got wrong result.
>
> When I checked the code I saw that I miss a "," from the list.
>
> l = ['?' '?']
>
> Interesting, that Python handle them as one string.
>
> print ['?' '?']
> ['\xf3\xd3']
>
> I wanna ask that is a bug or is it a feature?

You "wanna"?

> In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
> must concatenate the strings with some sign, like "+" or "||".

In other languages like Ruby, awk, C, C++, etc. adjacent string
constants are concatenated.

-- 
Grant Edwards                   grante             Yow! Is it clean in other
                                  at               dimensions?
                               visi.com            


From deets at nospam.web.de  Fri Aug  7 10:18:55 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 07 Aug 2009 16:18:55 +0200
Subject: how to overload operator "< <" (a < x < b)?
In-Reply-To: 
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
	
Message-ID: <7e2regF2eqbabU1@mid.uni-berlin.de>

alex23 schrieb:
> On Aug 7, 10:50 pm, Benjamin Kaplan  wrote:
>> That isn't an operator at all. Python does not support compound
>> comparisons like that. You have to do "a > b and b > c".
> 
> You know, it costs nothing to open up a python interpreter and check
> your certainty:
> 
>>>> x = 10
>>>> 1 < x < 20
> True
> 
> This is a _very_ common pattern.
> 
>>>> class X(object):
> ...   def __lt__(self, other):
> ...     print 'in lt'
> ...     return True
> ...   def __gt__(self, other):
> ...     print 'in gt'
> ...     return True
> ...
>>>> x = X()
>>>> 1 < x < 20
> in gt
> in lt
> True
>>>> 20 < x < 1
> in gt
> in lt
> True
> 
> dmitrey: Diez' advice was the best you received.

Not really. I didn't get the chaining, and Peter is right that for that 
there is no real overloading.

Diez


From matt.urry at googlemail.com  Fri Aug  7 10:29:46 2009
From: matt.urry at googlemail.com (ma3mju)
Date: Fri, 7 Aug 2009 07:29:46 -0700 (PDT)
Subject: Processes not exiting
References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com>
	
	<61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com>
	<01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> 
	
	 
	<996e50f5-c126-4ac2-ae8d-458d22a26ee1@v20g2000yqm.googlegroups.com>
Message-ID: <4b564f49-712c-408a-b8bd-9cff5af4a4fe@h30g2000vbr.googlegroups.com>

On 3 Aug, 09:36, ma3mju  wrote:
> On 2 Aug, 21:49, Piet van Oostrum  wrote:
>
> > >>>>> MRAB  (M) wrote:
> > >M> I wonder whether one of the workers is raising an exception, perhaps due
> > >M> to lack of memory, when there are large number of jobs to process.
>
> > But that wouldn't prevent the join. And you would probably get an
> > exception traceback printed.
>
> > I wonder if something fishy is happening in the multiprocessing
> > infrastructure. Or maybe the Fortran code goes wrong because it has no
> > protection against buffer overruns and similar problems, I think.
> > --
> > Piet van Oostrum 
> > URL:http://pietvanoostrum.com[PGP8DAE142BE17999C4]
> > Private email: p... at vanoostrum.org
>
> I don't think it's a memory problem, the reason for the hard and easy
> queue is because for larger examples it uses far more RAM. If I run
> all of workers with harder problems I do begin to run out of RAM and
> end up spending all my time switching in and out of swap so I limit
> the number of harder problems I run at the same time. I've watched it
> run to the end (a very boring couple of hours) and it stays out of my
> swap space and everything appears to be staying in RAM. Just hangs
> after all "poison" has been printed for each process.
>
> The other thing is that I get the message "here" telling me I broke
> out of the loop after seeing the poison pill in the process and I get
> all the things queued listed as output surely if I were to run out of
> memory I wouldn't expect all of the jobs to be listed as output.
>
> I have a serial script that works fine so I know individually for each
> example the fortran code works.
>
> Thanks
>
> Matt

Any ideas for a solution?


From kdawg44 at gmail.com  Fri Aug  7 10:30:37 2009
From: kdawg44 at gmail.com (Kevin Holleran)
Date: Fri, 7 Aug 2009 10:30:37 -0400
Subject: Changing Remote Registry
In-Reply-To: <5caea3690908070730g620e4fe5j90219702c5cf5a90@mail.gmail.com>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
	<4A7C3623.5020702@mrabarnett.plus.com>
	<5caea3690908070730g620e4fe5j90219702c5cf5a90@mail.gmail.com>
Message-ID: <5caea3690908070730i1030e8fdgdb108e88588c043c@mail.gmail.com>

>
>  Good morning,
>>
>> I fear the answer to this is that I just cannot do this....
>>
>> I wrote a python script that goes out to a bunch of remote machines and
>> queries the registry for some values.  Effectively, there have been some
>> software upgrades that have been done as the need arose but we need to do
>> them across the organization now.  There are three, and the script checks
>> all three and returns the values.  One of these just needs to be a registry
>> change as it is a client server application that the server was upgraded and
>> the clients need a change to a registry value to work.
>>
>> Long story short, I am using _winreg to do this.
>>
>> hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
>> value,type = _winreg.QueryValueEx(hKey, item)
>> if (value == wrongValue):
>>       _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
>>
>> When I do this I receive the error:
>>
>> _winreg.SetValue WindowsError: [Error 5] Access Denied
>>
>>
>> I am running this from my machine as a domain admin, connecting to the
>> remote machine which is also on the domain.
>> I am connecting to the remote registry with:
>>
>> keyPath = _winreg.ConnectRegistry(r"\\" +
>> ipAddress,_winreg.HKEY_LOCAL_MACHINE)
>>
>>
>> Thanks for any help.
>>
> What is 'ipAddress'? Is it an actual IP address? The documentation says
> it should be the computer name.
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Thanks for the response.  From my experience that does not matter.  It is an
actual IP address.  I can connect to the registry fine, its just the
writing.  I read that value and other values.  It errors on the
_winreg.KEY_SET_VALUE.  I am wondering if Windows just will not let the
registry be changed remotely in this way or if there is something else I
have to do.

Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From matt.urry at googlemail.com  Fri Aug  7 10:31:48 2009
From: matt.urry at googlemail.com (ma3mju)
Date: Fri, 7 Aug 2009 07:31:48 -0700 (PDT)
Subject: Processes not exiting
References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com>
	
	<61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com>
	<01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> 
	
	 
	<996e50f5-c126-4ac2-ae8d-458d22a26ee1@v20g2000yqm.googlegroups.com>
Message-ID: <1a890fc6-e014-45e7-9eee-2595202b9571@e4g2000vbe.googlegroups.com>

On 3 Aug, 09:36, ma3mju  wrote:
> On 2 Aug, 21:49, Piet van Oostrum  wrote:
>
> > >>>>> MRAB  (M) wrote:
> > >M> I wonder whether one of the workers is raising an exception, perhaps due
> > >M> to lack of memory, when there are large number of jobs to process.
>
> > But that wouldn't prevent the join. And you would probably get an
> > exception traceback printed.
>
> > I wonder if something fishy is happening in the multiprocessing
> > infrastructure. Or maybe the Fortran code goes wrong because it has no
> > protection against buffer overruns and similar problems, I think.
> > --
> > Piet van Oostrum 
> > URL:http://pietvanoostrum.com[PGP8DAE142BE17999C4]
> > Private email: p... at vanoostrum.org
>
> I don't think it's a memory problem, the reason for the hard and easy
> queue is because for larger examples it uses far more RAM. If I run
> all of workers with harder problems I do begin to run out of RAM and
> end up spending all my time switching in and out of swap so I limit
> the number of harder problems I run at the same time. I've watched it
> run to the end (a very boring couple of hours) and it stays out of my
> swap space and everything appears to be staying in RAM. Just hangs
> after all "poison" has been printed for each process.
>
> The other thing is that I get the message "here" telling me I broke
> out of the loop after seeing the poison pill in the process and I get
> all the things queued listed as output surely if I were to run out of
> memory I wouldn't expect all of the jobs to be listed as output.
>
> I have a serial script that works fine so I know individually for each
> example the fortran code works.
>
> Thanks
>
> Matt

Any ideas?


From wuwei23 at gmail.com  Fri Aug  7 10:32:10 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 07:32:10 -0700 (PDT)
Subject: how to overload operator "< <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
	
	<7e2regF2eqbabU1@mid.uni-berlin.de>
Message-ID: <90f46cdb-84cc-47aa-90f4-da0e09472eda@o9g2000prg.googlegroups.com>

"Diez B. Roggisch"  wrote:
> Not really. I didn't get the chaining, and Peter is right that for that
> there is no real overloading.

I'm sorry, I don't really get why overloading lt & gt isn't an answer
to the OP's question... His terminology may not have been correct but
I'm not sure why it's not a sufficient response.

(then again it is a Friday night and I have been out drinking...)


From Scott.Daniels at Acm.Org  Fri Aug  7 10:37:37 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Fri, 07 Aug 2009 07:37:37 -0700
Subject: M2Crypto: How to generate subjectKeyIdentifier /
	authorityKeyIdentifier
In-Reply-To: 
References: 	
	
Message-ID: 

Matthias G?ntert wrote:
>> M2Crypto has a couple of bugs open related that, with potential
>> workarounds that I haven't yet deemed polished enough to checkin, but
>> which might help you out:
>>
>> https://bugzilla.osafoundation.org/show_bug.cgi?id=7530
>> https://bugzilla.osafoundation.org/show_bug.cgi?id=12151
> 
> ... Generating the 'subjectKeyIdentifier':
 > ...
> def get_public_key_fingerprint(self):
> 	h = hashlib.new('sha1')
>     	h.update(self.keypair.as_der())
>     	client_serial = h.hexdigest().upper()
>     	client_serial_hex = ''
>     	for byte in xrange(20):
>     	 client_serial_hex += client_serial[byte*2] + client_serial[byte*2
> +1]
>     		if byte < 19:
>     			client_serial_hex += ':'
>         return client_serial_hex 
> ...

More tersely (code golf?):

     def get_public_key_fingerprint(self):
	digest = hashlib.sha1(self.keypair.as_der()).hexdigest().upper()
	return ':'.join(digest[pos : pos+2] for pos in range(0, 40, 2))

--Scott David Daniels
Scott.Daniels at Acm.Org


--Scott David Daniels
Scott.Daniels at Acm.Org


From python at mrabarnett.plus.com  Fri Aug  7 10:46:56 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Fri, 07 Aug 2009 15:46:56 +0100
Subject: Changing Remote Registry
In-Reply-To: <5caea3690908070730g620e4fe5j90219702c5cf5a90@mail.gmail.com>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>	
	<4A7C3623.5020702@mrabarnett.plus.com>
	<5caea3690908070730g620e4fe5j90219702c5cf5a90@mail.gmail.com>
Message-ID: <4A7C3E60.3060809@mrabarnett.plus.com>

Kevin Holleran wrote:
> 
> On Fri, Aug 7, 2009 at 10:11 AM, MRAB  > wrote:
> 
>     Kevin Holleran wrote:
> 
>         Good morning,
> 
>         I fear the answer to this is that I just cannot do this....
> 
>         I wrote a python script that goes out to a bunch of remote
>         machines and queries the registry for some values.  Effectively,
>         there have been some software upgrades that have been done as
>         the need arose but we need to do them across the organization
>         now.  There are three, and the script checks all three and
>         returns the values.  One of these just needs to be a registry
>         change as it is a client server application that the server was
>         upgraded and the clients need a change to a registry value to work.
> 
>         Long story short, I am using _winreg to do this.
> 
>         hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
>         value,type = _winreg.QueryValueEx(hKey, item)
>         if (value == wrongValue):
>               _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
>            
Hmm. If you're querying with (hKey, item), shouldn't you also be setting
with (hKey, item), not (hKey,'')?

>         When I do this I receive the error:
> 
>         _winreg.SetValue WindowsError: [Error 5] Access Denied
> 
> 
>         I am running this from my machine as a domain admin, connecting
>         to the remote machine which is also on the domain.
>         I am connecting to the remote registry with:
> 
>         keyPath = _winreg.ConnectRegistry(r"\\" +
>         ipAddress,_winreg.HKEY_LOCAL_MACHINE)
> 
> 
>         Thanks for any help.
> 
>     What is 'ipAddress'? Is it an actual IP address? The documentation says
>     it should be the computer name.
>     -- 
>     http://mail.python.org/mailman/listinfo/python-list
> 
> 
> 
> Thanks for the response.  From my experience that does not matter.  It 
> is an actual IP address.  I can connect to the registry fine, its just 
> the writing.  I read that value and other values.  It errors on the 
> _winreg.KEY_SET_VALUE.  I am wondering if Windows just will not let the 
> registry be changed remotely in this way or if there is something else I 
> have to do.
> 


From python at mrabarnett.plus.com  Fri Aug  7 11:02:09 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Fri, 07 Aug 2009 16:02:09 +0100
Subject: Processes not exiting
In-Reply-To: <4b564f49-712c-408a-b8bd-9cff5af4a4fe@h30g2000vbr.googlegroups.com>
References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com>		<61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com>	<01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com>
		
	<996e50f5-c126-4ac2-ae8d-458d22a26ee1@v20g2000yqm.googlegroups.com>
	<4b564f49-712c-408a-b8bd-9cff5af4a4fe@h30g2000vbr.googlegroups.com>
Message-ID: <4A7C41F1.3080303@mrabarnett.plus.com>

ma3mju wrote:
> On 3 Aug, 09:36, ma3mju  wrote:
>> On 2 Aug, 21:49, Piet van Oostrum  wrote:
>>
>>>>>>>> MRAB  (M) wrote:
>>>> M> I wonder whether one of the workers is raising an exception, perhaps due
>>>> M> to lack of memory, when there are large number of jobs to process.
>>> But that wouldn't prevent the join. And you would probably get an
>>> exception traceback printed.
>>> I wonder if something fishy is happening in the multiprocessing
>>> infrastructure. Or maybe the Fortran code goes wrong because it has no
>>> protection against buffer overruns and similar problems, I think.
>>> --
>>> Piet van Oostrum 
>>> URL:http://pietvanoostrum.com[PGP8DAE142BE17999C4]
>>> Private email: p... at vanoostrum.org
>> I don't think it's a memory problem, the reason for the hard and easy
>> queue is because for larger examples it uses far more RAM. If I run
>> all of workers with harder problems I do begin to run out of RAM and
>> end up spending all my time switching in and out of swap so I limit
>> the number of harder problems I run at the same time. I've watched it
>> run to the end (a very boring couple of hours) and it stays out of my
>> swap space and everything appears to be staying in RAM. Just hangs
>> after all "poison" has been printed for each process.
>>
>> The other thing is that I get the message "here" telling me I broke
>> out of the loop after seeing the poison pill in the process and I get
>> all the things queued listed as output surely if I were to run out of
>> memory I wouldn't expect all of the jobs to be listed as output.
>>
>> I have a serial script that works fine so I know individually for each
>> example the fortran code works.
>>
>> Thanks
>>
>> Matt
> 
> Any ideas for a solution?

A workaround is to do them in small batches.

You could put each job in a queue with a flag to say whether it's hard 
or easy, then:

     while have more jobs:
         move up to BATCH_SIZE jobs into worker queues
         create and start workers
         wait for workers to finish
         discard workers


From exarkun at twistedmatrix.com  Fri Aug  7 11:02:13 2009
From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com)
Date: Fri, 07 Aug 2009 15:02:13 -0000
Subject: how to overload operator "< <" (a < x < b)?
In-Reply-To: 
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
Message-ID: <20090807150213.13038.275088682.divmod.xquotient.2@localhost.localdomain>

On 12:50 pm, benjamin.kaplan at case.edu wrote:
>On Fri, Aug 7, 2009 at 8:00 AM, dmitrey 
>wrote:
>>hi all,
>>is it possible to overload operator "< ?<"? (And other like this one,
>>eg "<= ?<=", "> ?>", ">= ?>=")
>>Any URL/example?
>>Thank you in advance, D.
>
>That isn't an operator at all. Python does not support compound
>comparisons like that. You have to do "a > b and b > c".

That's partially correct.  There is no "compound less than operator", or
whatever you want to call that.  However, Python does support "compound
comparisons" like that:

  >>> 1 < 2 < 3
  True
  >>> 1 < 3 < 2
  False
  >>> 1 == 2 == 3
  False
  >>> 2 == 2 == 2
  True
  >>>
Jean-Paul


From Scott.Daniels at Acm.Org  Fri Aug  7 11:04:22 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Fri, 07 Aug 2009 08:04:22 -0700
Subject: how to overload operator "< <" (a < x < b)?
In-Reply-To: 
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
Message-ID: 

Benjamin Kaplan wrote:
> .... Python does not support compound
> comparisons like that. You have to do "a > b and b > c".

Funny, my python does.  This has been around a long time.
I am not certain whether 1.5.2 did it, but "chained comparisons"
have been around for a long time.

     >>> 'a'< 'd' <'z'
     True
     >>> 'a'< 'D' <'z'
     False

--Scott David Daniels
Scott.Daniels at Acm.Org


From kdawg44 at gmail.com  Fri Aug  7 11:05:01 2009
From: kdawg44 at gmail.com (Kevin Holleran)
Date: Fri, 7 Aug 2009 11:05:01 -0400
Subject: Changing Remote Registry
In-Reply-To: <4A7C3E60.3060809@mrabarnett.plus.com>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
	<4A7C3623.5020702@mrabarnett.plus.com>
	<5caea3690908070730g620e4fe5j90219702c5cf5a90@mail.gmail.com>
	<4A7C3E60.3060809@mrabarnett.plus.com>
Message-ID: <5caea3690908070805q3ff8f208r37a50a670c9f1bc9@mail.gmail.com>

 On Fri, Aug 7, 2009 at 10:46 AM, MRAB  wrote:

> Kevin Holleran wrote:
>
>>
>> On Fri, Aug 7, 2009 at 10:11 AM, MRAB > python at mrabarnett.plus.com>> wrote:
>>
>>    Kevin Holleran wrote:
>>
>>        Good morning,
>>
>>        I fear the answer to this is that I just cannot do this....
>>
>>        I wrote a python script that goes out to a bunch of remote
>>        machines and queries the registry for some values.  Effectively,
>>        there have been some software upgrades that have been done as
>>        the need arose but we need to do them across the organization
>>        now.  There are three, and the script checks all three and
>>        returns the values.  One of these just needs to be a registry
>>        change as it is a client server application that the server was
>>        upgraded and the clients need a change to a registry value to work.
>>
>>        Long story short, I am using _winreg to do this.
>>
>>        hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
>>        value,type = _winreg.QueryValueEx(hKey, item)
>>        if (value == wrongValue):
>>              _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
>>
>>
> Hmm. If you're querying with (hKey, item), shouldn't you also be setting
> with (hKey, item), not (hKey,'')?
>
>
>         When I do this I receive the error:
>>
>>        _winreg.SetValue WindowsError: [Error 5] Access Denied
>>
>>
>>        I am running this from my machine as a domain admin, connecting
>>        to the remote machine which is also on the domain.
>>        I am connecting to the remote registry with:
>>
>>        keyPath = _winreg.ConnectRegistry(r"\\" +
>>        ipAddress,_winreg.HKEY_LOCAL_MACHINE)
>>
>>
>>        Thanks for any help.
>>
>>    What is 'ipAddress'? Is it an actual IP address? The documentation says
>>    it should be the computer name.
>>    --    http://mail.python.org/mailman/listinfo/python-list
>>
>>
>>
>> Thanks for the response.  From my experience that does not matter.  It is
>> an actual IP address.  I can connect to the registry fine, its just the
>> writing.  I read that value and other values.  It errors on the
>> _winreg.KEY_SET_VALUE.  I am wondering if Windows just will not let the
>> registry be changed remotely in this way or if there is something else I
>> have to do.
>>
>>  --
> http://mail.python.org/mailman/listinfo/python-list
>

Sorry, that line is correct, I was removing specific information relevant to
our infrastructure.  That is the valuename.  The error I am getting is:


Traceback (most recent call last):
  File "script.py", line 53, in 
    value,type = _winreg.QueryValueEx(hKey,item)
WindowsError: [Error 5] Access is denied

But the real error is here I believe:

       hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)

When I just do a:

       hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_READ)

I receive no errors.

Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From thorsten at thorstenkampe.de  Fri Aug  7 11:13:07 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Fri, 7 Aug 2009 17:13:07 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
Message-ID: 

* alex23 (Fri, 7 Aug 2009 06:53:22 -0700 (PDT))
> Thorsten Kampe  wrote:
> > Bollocks. No one will even notice whether a code sequence runs 2.7 or
> > 5.7 seconds. That's completely artificial benchmarking.
> 
> But that's not what you first claimed:
> 
> > I don't think any measurable speed increase will be
> > noticeable between those two.
> 
> But please, keep changing your argument so you don't have to admit you
> were wrong.

Bollocks. Please note the word "noticeable". "noticeable" as in 
recognisable as in reasonably experiencable or as in whatever.

One guy claims he has times between 2.7 and 5.7 seconds when 
benchmarking more or less randomly generated "one million different 
lines". That *is* *exactly* nothing.

Another guy claims he gets times between 2.9 and 6.2 seconds when 
running decode/unicode in various manifestations over "18 million 
words" (or is it 600 million?) and says "the differences are pretty 
significant". I think I don't have to comment on that.

If you increase the number of loops to one million or one billion or 
whatever even the slightest completely negligible difference will occur. 
The same thing will happen if you just increase the corpus of words to a 
million, trillion or whatever. The performance implications of that are 
exactly none.

Thorsten


From manu3d at gmail.com  Fri Aug  7 11:15:08 2009
From: manu3d at gmail.com (Emanuele D'Arrigo)
Date: Fri, 7 Aug 2009 08:15:08 -0700 (PDT)
Subject: Executing untrusted code
Message-ID: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com>

Greetings everybody,

I've been reading and mulling about python and security, specifically
in terms of executing code that may or may not be trustworthy. I
understand that libraries such as Rexec and Bastion are now deprecated
because they have known vulnerabilities that may be exploited to
circumvent the restrictions imposed.

So, am I right in understanding that is not possible to execute a
piece of code in a way that limits the objects and attributes that it
can access or that limits its access to file system and sockets? Are
there best practices to at least minimize some of the risks associated
with untrusted code execution?

And whatever happened to this:

http://sayspy.blogspot.com/2007/05/i-have-finished-securing-python.html

seemed to be a step forward in the right direction!

Manu


From gert.cuykens at gmail.com  Fri Aug  7 11:23:52 2009
From: gert.cuykens at gmail.com (gert)
Date: Fri, 7 Aug 2009 08:23:52 -0700 (PDT)
Subject: HTTP_RANGE
Message-ID: <72a8588f-ea26-489a-936d-29462e57c917@p28g2000vbn.googlegroups.com>

def application(environ, response):
    range=environ.get('HTTP_RANGE','bytes=0-').replace
('bytes=','').split(',')
    offset=[]
    for r in range: offset.append(r.split('-'))
    out='0123456789'
    lengthF=len(out)
    lengthC=str(lengthF-int(offset[0][0]))
    bitS=int(offset[0][0])
    bitE=lengthF-1
    bytes='bytes '+str(bitS)+'-'+str(bitE)+'/'+str(lengthF)
    response('200 OK', [('Content-Length', lengthC), ('Content-
Range',bytes)])
    return [out[bitS:]]

C:\Users\gert\Desktop>curl http://127.0.0.1/appwsgi/wsgi/download.wsgi
-v
* About to connect() to 127.0.0.1 port 80 (#0)
*   Trying 127.0.0.1... connected
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)
> GET /appwsgi/wsgi/download.wsgi HTTP/1.1
> User-Agent: curl/7.19.4 (amd64-pc-win32) libcurl/7.19.4 OpenSSL/0.9.8j zlib/1.2.3
> Host: 127.0.0.1
> Accept: */*

* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Date: Thu, 06 Aug 2009 19:05:09 GMT
< Server: WSGIServer/0.1 Python/3.1
< Content-Length: 10
< Content-Range: bytes 0-9/10
<
0123456789* Closing connection #0

C:\Users\gert\Desktop>curl -C 2 http://127.0.0.1/appwsgi/wsgi/download.wsgi
-v
* About to connect() to 127.0.0.1 port 80 (#0)
*   Trying 127.0.0.1... connected
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)
> GET /appwsgi/wsgi/download.wsgi HTTP/1.1
> Range: bytes=2-
> User-Agent: curl/7.19.4 (amd64-pc-win32) libcurl/7.19.4 OpenSSL/0.9.8j zlib/1.2.3
> Host: 127.0.0.1
> Accept: */*

* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Date: Thu, 06 Aug 2009 19:06:52 GMT
< Server: WSGIServer/0.1 Python/3.1
< Content-Length: 8
< Content-Range: bytes 2-9/10
<
23456789* Closing connection #0

Why does it use HTTP 1.0 ? Can I force it to use HTTP 1.1 ?


From python at mrabarnett.plus.com  Fri Aug  7 11:28:24 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Fri, 07 Aug 2009 16:28:24 +0100
Subject: Changing Remote Registry
In-Reply-To: <5caea3690908070805q3ff8f208r37a50a670c9f1bc9@mail.gmail.com>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>	<4A7C3623.5020702@mrabarnett.plus.com>	<5caea3690908070730g620e4fe5j90219702c5cf5a90@mail.gmail.com>	<4A7C3E60.3060809@mrabarnett.plus.com>
	<5caea3690908070805q3ff8f208r37a50a670c9f1bc9@mail.gmail.com>
Message-ID: <4A7C4818.10709@mrabarnett.plus.com>

Kevin Holleran wrote:
> On Fri, Aug 7, 2009 at 10:46 AM, MRAB  > wrote:
> 
>     Kevin Holleran wrote:
> 
> 
>         On Fri, Aug 7, 2009 at 10:11 AM, MRAB
>         
>                  >> wrote:
> 
>            Kevin Holleran wrote:
> 
>                Good morning,
> 
>                I fear the answer to this is that I just cannot do this....
> 
>                I wrote a python script that goes out to a bunch of remote
>                machines and queries the registry for some values.
>          Effectively,
>                there have been some software upgrades that have been done as
>                the need arose but we need to do them across the organization
>                now.  There are three, and the script checks all three and
>                returns the values.  One of these just needs to be a registry
>                change as it is a client server application that the
>         server was
>                upgraded and the clients need a change to a registry
>         value to work.
> 
>                Long story short, I am using _winreg to do this.
> 
>                hKey = _winreg.OpenKey (keyPath, path, 0,
>         _winreg.KEY_SET_VALUE)
>                value,type = _winreg.QueryValueEx(hKey, item)
>                if (value == wrongValue):
>                      _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
>                  
> 
>     Hmm. If you're querying with (hKey, item), shouldn't you also be setting
>     with (hKey, item), not (hKey,'')?
> 
> 
>                When I do this I receive the error:
> 
>                _winreg.SetValue WindowsError: [Error 5] Access Denied
> 
> 
>                I am running this from my machine as a domain admin,
>         connecting
>                to the remote machine which is also on the domain.
>                I am connecting to the remote registry with:
> 
>                keyPath = _winreg.ConnectRegistry(r"\\" +
>                ipAddress,_winreg.HKEY_LOCAL_MACHINE)
> 
> 
>                Thanks for any help.
> 
>            What is 'ipAddress'? Is it an actual IP address? The
>         documentation says
>            it should be the computer name.
>            --    http://mail.python.org/mailman/listinfo/python-list
> 
> 
> 
>         Thanks for the response.  From my experience that does not
>         matter.  It is an actual IP address.  I can connect to the
>         registry fine, its just the writing.  I read that value and
>         other values.  It errors on the _winreg.KEY_SET_VALUE.  I am
>         wondering if Windows just will not let the registry be changed
>         remotely in this way or if there is something else I have to do.
> 
>     -- 
>     http://mail.python.org/mailman/listinfo/python-list
> 
> 
> Sorry, that line is correct, I was removing specific information 
> relevant to our infrastructure.  That is the valuename.  The error I am 
> getting is:
> 
> 
> Traceback (most recent call last):
>   File "script.py", line 53, in 
>     value,type = _winreg.QueryValueEx(hKey,item)
> WindowsError: [Error 5] Access is denied
> 
> But the real error is here I believe:
> 
>        hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
> 
> When I just do a:
> 
>        hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_READ)
> 
> I receive no errors.
> 
> Thanks.
> 
If it's complaining _as soon as_ you request write permission then I'd
say that was a permissions problem, not an error! :-)


From mark.v.weber at gmail.com  Fri Aug  7 11:51:48 2009
From: mark.v.weber at gmail.com (mark.v.weber at gmail.com)
Date: Fri, 7 Aug 2009 08:51:48 -0700 (PDT)
Subject: how to kill subprocess when Python process is killed?
References: <0feaa2a3-5b73-43e4-9b24-11f157ff6d18@l34g2000vba.googlegroups.com>
	<3733148e-c03d-42ef-88f7-855c516e6564@d9g2000prh.googlegroups.com>
Message-ID: <63d1512c-4018-467d-a439-25dd76975e5e@g19g2000vbi.googlegroups.com>

On Aug 7, 12:57?am, alex23  wrote:
> On Aug 7, 3:42?pm, "mark.v.we... at gmail.com" 
> wrote:
>
> > When I kill the main process (cntl-C) the subprocess keeps running.
> > How do I kill the subprocess too? The subprocess is likely to run a
> > long time.
>
> You can register functions to run when the Python process ends by
> using the atexit[1] module.
>
> The following has been tested & works under Python 2.6 on Windows XP:
>
> ? ? import atexit
>
> ? ? def cleanup():
> ? ? ? ? print 'stop thesubprocessin here'
>
> ? ? atexit.register(cleanup)
>
> ? ? while True:
> ? ? ? ? pass
>
> [1]:http://docs.python.org/library/atexit.html

Works perfectly. Thanks!


From kee at kagi.com  Fri Aug  7 12:03:37 2009
From: kee at kagi.com (Kee Nethery)
Date: Fri, 7 Aug 2009 09:03:37 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
Message-ID: <690C5186-1666-4EF4-B223-AF8880B0C21C@kagi.com>

During all this conversation there was a ticket posted in the bug  
tracking system with the suggestion of each section in the official  
docs linking to a fixed wiki page that can contain user contributions.

The ticket has been closed because this addition to the official docs  
is already in the works.

So ... to everyone who thinks there needs to be a place for user  
comments to augment the official docs, it's supposed to happen. Same  
with corrections to the docs, there is supposed to be a place per  
section where people can post corrections to the docs.

I'm looking forward to the acceleration of improvements to the  
official docs based upon easy to provide user feedback. Glad to see  
that the bug tracking system is going to not be the primary means for  
documentation changes.

Kee



From Scott.Daniels at Acm.Org  Fri Aug  7 12:05:00 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Fri, 07 Aug 2009 09:05:00 -0700
Subject: Bug or feature: double strings as one
In-Reply-To: 
References: 
	
Message-ID: <5Y2dnfnYAdsl0-HXnZ2dnUVZ_j9i4p2d@pdx.net>

Grant Edwards wrote:
> On 2009-08-07, durumdara  wrote:
>> In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
>> must concatenate the strings with some sign, like "+" or "||".
> 
> In other languages like Ruby, awk, C, C++, etc. adjacent string
> constants are concatenated.

I must learn this "etc." language, I hear it mentioned all the time :-)

--Scott David Daniels
Scott.Daniels at Acm.Org



From rickbking at comcast.net  Fri Aug  7 12:19:21 2009
From: rickbking at comcast.net (Rick King)
Date: Fri, 07 Aug 2009 12:19:21 -0400
Subject: py2exe-created exe results in "application failed to initialize"
Message-ID: <4A7C5409.5020807@comcast.net>

Hi everyone,
I want to package up an application into an exe using py2exe but the 
result produces the dreaded

"application failed to initialize 0x....142" error.

I'm using wxPython and basically just took the sample for wxpython GUI 
that came with py2exe and changed the name. My setup is python 2.6, 
wxpython 2.8. My setup.py looks like the following.

from distutils.core import setup
import py2exe
import sys

class Target:
    def __init__(self, **kw):
        self.__dict__.update(kw)
        # for the versioninfo resources
        self.version = "0.1"
        self.company_name = "OWDC"
        self.copyright = "no copyright"
        self.name = "FileTool"

manifest_template = '''

.... etc.
'''

RT_MANIFEST = 24

FileTool = Target(
    description = "FileTool",
    script = "filetoolGUI.py",
    other_resources = [(RT_MANIFEST, 1, manifest_template % 
dict(prog="FileTool"))],
    dest_base = "FileTool")

setup(
    options = {"py2exe": {"compressed": 1,"optimize": 2,"ascii": 
1,"bundle_files": 1}},
    zipfile = None,
    windows = [FileTool],
    )

Any help will be greatly appreciated!

Rick King
Southfield MI USA



From bbarbero at inescporto.pt  Fri Aug  7 12:19:28 2009
From: bbarbero at inescporto.pt (bbarbero at inescporto.pt)
Date: Fri, 07 Aug 2009 18:19:28 +0200
Subject: Extracting matrix from a text file
Message-ID: <20090807181928.10784usha588i2a8@horde.inescporto.pt>

Hello to all!!

I am new in python, and I am running it on Mac with Smultron editor. I  
need to read a textfile that includes numbers (in a matrix form),  
indexes, and strings, like this:

Marsyas-kea distance matrix for MIREX 2007 Audio Similarity Exchange
Q/R	1	2	3	4	5
1	0	4.54592	4.36685	5.29463	3.85728
2	4.54592	0	3.97667	5.02151	4.64284
3	4.36685	3.97667	0	4.98743	4.83683
4	5.29463	5.02151	4.98743	0	6.04393
5	3.85728	4.64284	4.83683	6.04393	0



So I just want to keep the matrix in the "middle" for math computations.

	0       4.54592	4.36685	5.29463	3.85728
	4.54592	0	3.97667	5.02151	4.64284
	4.36685	3.97667	0	4.98743	4.83683
	5.29463	5.02151	4.98743	0	6.04393
	3.85728	4.64284	4.83683	6.04393	0

I've seen and tried a lot of ways, like split or isinstance.. but  
never get the wanted result.... does anyone have an idea, or hint?  
Thank you once more for your help!

Best Regards,
Bea

----------------------------------------------------------------
This message was sent using IMP, the Internet Messaging Program.


From stefan_ml at behnel.de  Fri Aug  7 12:31:27 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 07 Aug 2009 18:31:27 +0200
Subject: Cython + setuptools not working with .pyx,only with .c-files
In-Reply-To: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
References: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
Message-ID: <4a7c56e0$0$31871$9b4e6d93@newsspool3.arcor-online.net>

Diez B. Roggisch wrote:
> I'm trying to build a Cython-extension as Egg.
> 
> However, this doesn't work - I can either use distutils to build the
> extension, creating a myextension.c-file on the way.
> 
> If that's there, I can use setuptools to build the egg.
> 
> But when I remove the .c-file, the .pyx-file isn't used to re-generate it.

setuptools monkeypatch into distutils to support Pyrex if it's installed,
but most non-bleeding-edge versions do not know about Cython and thus break
the Cython distutils support when Pyrex isn't there as well.

What helps is to put a fake Pyrex installation into your sys.path, like

http://codespeak.net/svn/lxml/trunk/fake_pyrex/

as done at the top of

http://codespeak.net/svn/lxml/trunk/setup.py

I haven't tried if newer setuptools versions have been fixed yet.

Stefan


From sandorl at gmail.com  Fri Aug  7 12:32:53 2009
From: sandorl at gmail.com (=?UTF-8?B?TMOhc3psw7MgU8OhbmRvcg==?=)
Date: Fri, 7 Aug 2009 12:32:53 -0400
Subject: question: why isn't a byte of a hash more uniform? how could I 
	improve my code to cure that?
Message-ID: 

Hi all,
I am a Python novice, and right now I would be happy to simply get my job
done with it, but I could appreciate some thoughts on the issue below.

I need to assign one of four numbers to names in a list. The assignment
should be pseudo-random: no pattern whatsoever, but deterministic,
reproducible, and close to uniform. My understanding was that hash functions
would do the job. As I only needed 2 bits of treatment, I picked a byte of
the hashes generated, and even taken mod 4 of it. See the code below.

After I have written a short Python script that hashes my textfile line by
line and collects the numbers next to the original, I checked what I got.
Instead of getting around 25% in each treatment, the range is 17.8%-31.3%. I
understand that the pseudo-randomness means that the treatments should not
be neat and symmetric. Still, this variation is unacceptable for my purpose.
My understanding was that good hash functions generate numbers that look
completely random, and picking only a byte should not change that. I thought
the promise was also to get close to uniformity:
http://en.wikipedia.org/wiki/Hash_function#Uniformity. I tried all the
hashes in the hashlib module, and picked bytes from the beginning and the
end of the hashes, but treatments never were close to uniform (curiously,
always the last treatment seems to be too rare).

Maybe it is an obvious CS puzzle, I'm looking forward to standing corrected.

Thanks!

Laszlo

The script:

#! /usr/bin/python

f = open('names.txt', 'r')
g = open('nameshashed.txt', 'a')

import hashlib

for line in f:
    line = line.rstrip()
    h = str(hashlib.sha512(line).hexdigest())
    s = line + ',' + str(ord(h[64])%4) + '\n'
    g.write(s),
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From wuwei23 at gmail.com  Fri Aug  7 12:39:15 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 09:39:15 -0700 (PDT)
Subject: Extracting matrix from a text file
References: 
Message-ID: 

On Aug 8, 2:19?am, bbarb... at inescporto.pt wrote:
> I am new in python, and I am running it on Mac with Smultron editor. I ?
> need to read a textfile that includes numbers (in a matrix form), ?
> indexes, and strings, like this:
>
> Marsyas-kea distance matrix for MIREX 2007 Audio Similarity Exchange
> Q/R ? ? 1 ? ? ? 2 ? ? ? 3 ? ? ? 4 ? ? ? 5
> 1 ? ? ? 0 ? ? ? 4.54592 4.36685 5.29463 3.85728
> 2 ? ? ? 4.54592 0 ? ? ? 3.97667 5.02151 4.64284
> 3 ? ? ? 4.36685 3.97667 0 ? ? ? 4.98743 4.83683
> 4 ? ? ? 5.29463 5.02151 4.98743 0 ? ? ? 6.04393
> 5 ? ? ? 3.85728 4.64284 4.83683 6.04393 0
>
> So I just want to keep the matrix in the "middle" for math computations.
>
> ? ? ? ? 0 ? ? ? 4.54592 4.36685 5.29463 3.85728
> ? ? ? ? 4.54592 0 ? ? ? 3.97667 5.02151 4.64284
> ? ? ? ? 4.36685 3.97667 0 ? ? ? 4.98743 4.83683
> ? ? ? ? 5.29463 5.02151 4.98743 0 ? ? ? 6.04393
> ? ? ? ? 3.85728 4.64284 4.83683 6.04393 0
>
> I've seen and tried a lot of ways, like split or isinstance.. but ?
> never get the wanted result.... does anyone have an idea, or hint? ?
> Thank you once more for your help!


isinstance? Are you just randomly trying functions hoping they'll
work? :)

Untested code follows:

with open(,'r') as textfile:
    header = textfile.next() # skip the header
    col_0_size = 8 # cos it does
    for line in textfile:
        newline = line[col_0_size:] # strip off the index column
        columns = newline.split(' ') # will give you a tuple of
strings
        one, two, three, four, five = map(float, columns) # turns the
strings into floats
        # do whatever you want to those values here

This is fairly standard text handling with Python, if you haven't
already you should really work through the Python tutorial[1],
especially the section on strings [2], and if you have, perhaps David
Mertz's 'Text Processing in Python'[3] may be of use.

1: http://docs.python.org/tutorial/
2: http://docs.python.org/tutorial/introduction.html#strings
3: http://gnosis.cx/TPiP/


From no.email at please.post  Fri Aug  7 12:50:12 2009
From: no.email at please.post (kj)
Date: Fri, 7 Aug 2009 16:50:12 +0000 (UTC)
Subject: PEP 8 exegetics: conditional imports?
Message-ID: 



Conditional imports make sense to me, as in the following example:

def foobar(filename):
    if os.path.splitext(filename)[1] == '.gz':
        import gzip
        f = gzip.open(filename)
    else:
        f = file(filename)
    # etc.

And yet, quoth PEP 8:

    - Imports are always put at the top of the file, just after any module
      comments and docstrings, and before module globals and constants.

...which seems to condemn conditional imports unequivocally. 

Then again, the PEP 8 scriptures do not explicitly mention conditional
imports at all, as far as I can tell, which leaves open the
possibility that they are still righteous. 

In fact, venerable passages in the Python standard library source
code, if properly interpreted, can be seen to carry out conditional
imports, such as this fragment recovered from random.py:

        if a is None:
            try:
                a = long(_hexlify(_urandom(16)), 16)
            except NotImplementedError:
                import time
                a = long(time.time() * 256) # use fractional seconds

Or even more clearly, this one from test/pystone.py:

if __name__ == '__main__':
    import sys



I seek the wisdom of the elders.  Is there a consensus on the matter
of conditional imports?  Are they righteous?  Or are they the way
of the wicked?

kynn


From invalid at invalid  Fri Aug  7 13:00:47 2009
From: invalid at invalid (Grant Edwards)
Date: Fri, 07 Aug 2009 12:00:47 -0500
Subject: Bug or feature: double strings as one
References: 
	
	<5Y2dnfnYAdsl0-HXnZ2dnUVZ_j9i4p2d@pdx.net>
Message-ID: 

On 2009-08-07, Scott David Daniels  wrote:
> Grant Edwards wrote:
>> On 2009-08-07, durumdara  wrote:
>>> In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
>>> must concatenate the strings with some sign, like "+" or "||".
>> 
>> In other languages like Ruby, awk, C, C++, etc. adjacent string
>> constants are concatenated.
>
> I must learn this "etc." language, I hear it mentioned all the time :-)

Definitely.  Not only does it have _all_ the features, it even
manages to simultaneously have several mutually-exclusive
features.

-- 
Grant Edwards                   grante             Yow! I'm meditating on
                                  at               the FORMALDEHYDE and the
                               visi.com            ASBESTOS leaking into my
                                                   PERSONAL SPACE!!


From python.list at tim.thechases.com  Fri Aug  7 13:19:47 2009
From: python.list at tim.thechases.com (Tim Chase)
Date: Fri, 07 Aug 2009 12:19:47 -0500
Subject: question: why isn't a byte of a hash more uniform? how could
	I    improve my code to cure that?
In-Reply-To: 
References: 
Message-ID: <4A7C6233.4050105@tim.thechases.com>

> After I have written a short Python script that hashes my textfile line by
> line and collects the numbers next to the original, I checked what I got.
> Instead of getting around 25% in each treatment, the range is 17.8%-31.3%.

That sounds suspiciously like 25% with a +/- 7% fluctuation one 
might expect to see from non-random source data.

Remember that your outputs are driven purely by your inputs in a 
deterministic fashion -- if your inputs are purely random, then 
your outputs should more closely match your expected bin'ing.  If 
your inputs aren't random, you get a taste of your own medicine 
("my file has just the number 42 on every line...why isn't my 
output random?").  And randomness-of-hash-output is a red herring 
since hashing is *not* random.

Your input is also finite -- an aspect which leaves you a far cry 
from the full hash-space.  If an md5 has 32 bytes (256 bits) of 
data, your input would have to cover 2**256 possible inputs to 
see the full profile of your outputs.  That's a lot of input :)

-tkc






From python at mrabarnett.plus.com  Fri Aug  7 13:29:23 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Fri, 07 Aug 2009 18:29:23 +0100
Subject: Extracting matrix from a text file
In-Reply-To: 
References: 
	
Message-ID: <4A7C6473.8050602@mrabarnett.plus.com>

alex23 wrote:
> On Aug 8, 2:19 am, bbarb... at inescporto.pt wrote:
>> I am new in python, and I am running it on Mac with Smultron editor. I  
>> need to read a textfile that includes numbers (in a matrix form),  
>> indexes, and strings, like this:
>>
>> Marsyas-kea distance matrix for MIREX 2007 Audio Similarity Exchange
>> Q/R     1       2       3       4       5
>> 1       0       4.54592 4.36685 5.29463 3.85728
>> 2       4.54592 0       3.97667 5.02151 4.64284
>> 3       4.36685 3.97667 0       4.98743 4.83683
>> 4       5.29463 5.02151 4.98743 0       6.04393
>> 5       3.85728 4.64284 4.83683 6.04393 0
>>
>> So I just want to keep the matrix in the "middle" for math computations.
>>
>>         0       4.54592 4.36685 5.29463 3.85728
>>         4.54592 0       3.97667 5.02151 4.64284
>>         4.36685 3.97667 0       4.98743 4.83683
>>         5.29463 5.02151 4.98743 0       6.04393
>>         3.85728 4.64284 4.83683 6.04393 0
>>
>> I've seen and tried a lot of ways, like split or isinstance.. but  
>> never get the wanted result.... does anyone have an idea, or hint?  
>> Thank you once more for your help!
> 
> 
> isinstance? Are you just randomly trying functions hoping they'll
> work? :)
> 
> Untested code follows:
> 
> with open(,'r') as textfile:
>     header = textfile.next() # skip the header
>     col_0_size = 8 # cos it does
>     for line in textfile:
>         newline = line[col_0_size:] # strip off the index column
>         columns = newline.split(' ') # will give you a tuple of
> strings
[snip]
Or:
         columns = line.split(' ')[1 : ]


From wuwei23 at gmail.com  Fri Aug  7 13:29:55 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 10:29:55 -0700 (PDT)
Subject: PEP 8 exegetics: conditional imports?
References: 
Message-ID: <3d84c940-faea-4b3b-af3c-73059b3eaf96@v23g2000pro.googlegroups.com>

On Aug 8, 2:50?am, kj  wrote:
> Conditional imports make sense to me, as in the following example[...]
> And yet, quoth PEP 8:
>
> ? ? - Imports are always put at the top of the file, just after any module
> ? ? ? comments and docstrings, and before module globals and constants.
>
> ...which seems to condemn conditional imports unequivocally.

Really? It doesn't mention conditionals at all, it simply says that
imports should occur before globals and constants, not before
conditions. If you want to put conditions around your imports, then
that's the place to do it.

> I seek the wisdom of the elders. ?Is there a consensus on the matter
> of conditional imports? ?Are they righteous? ?Or are they the way
> of the wicked?

Bear in mind that PEP 8 primarily applies to submissions to the
standard library, in order to provide a standard that aids in
understanding them. If a module is used throughout a body of code,
it's helpful to list these modules at the top of the code, for
clarity. However, if a module is only required under exceptional
conditions, you'll often see it imported at the point which it's
required: as the import occurs near the code, this mitigates the
initial requirement somewhat, and reduces the startup time of the
code.

The style guide also states:
    But most importantly: know when to be inconsistent -- sometimes
the style
    guide just doesn't apply.  When in doubt, use your best judgment.
Look
    at other examples and decide what looks best.  And don't hesitate
to ask!

Checks around imports are often used to provide cross-version
compatibility. Embedded imports are often used when the code relying
on them is barely used. These are all very common uses.

pystone is a good example. Nothing within the modular code of pystone
requires sys, it's only imported if the module is executed, primarily
for error reporting & argument handling.


From no.email at please.post  Fri Aug  7 13:35:28 2009
From: no.email at please.post (kj)
Date: Fri, 7 Aug 2009 17:35:28 +0000 (UTC)
Subject: Bug or feature: double strings as one
References: 
	
Message-ID: 

In  Peter Otten <__peter__ at web.de> writes:

>durumdara wrote:

>> I found an interesting thing in Python.
>> Today one of my "def"s got wrong result.
>> 
>> When I checked the code I saw that I miss a "," from the list.
>> 
>> l = ['??' '??']
>> 
>> Interesting, that Python handle them as one string.
>> 
>> print ['??' '??']
>> ['\xf3\xd3']
>> 
>> I wanna ask that is a bug or is it a feature?

Feature, as others have pointed out, though I fail to see the need
for it, given that Python's general syntax for string (as opposed
to string literal) concatenation is already so convenient.  I.e.,
I fail to see why

x = ("first part of a very long string "
     "second part of a very long string")

is so much better than

x = ("first part of a very long string " +
     "second part of a very long string")

FWIW, C has the same concatenation feature for string literals.
E.g., the following is valid C:

printf("first part of a very long string "
       "second part of a very long string\n");

kynn



From wuwei23 at gmail.com  Fri Aug  7 13:37:02 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 10:37:02 -0700 (PDT)
Subject: Extracting matrix from a text file
References:  
	 
	
Message-ID: 

MRAB  wrote:
> Or:
> ? ? ? ? ?columns = line.split(' ')[1 : ]

Even better, well spotted.


From garabik-news-2005-05 at kassiopeia.juls.savba.sk  Fri Aug  7 13:41:38 2009
From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk)
Date: Fri, 7 Aug 2009 17:41:38 +0000 (UTC)
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
Message-ID: 

Thorsten Kampe  wrote:
 
> lines". That *is* *exactly* nothing.
> 
> Another guy claims he gets times between 2.9 and 6.2 seconds when 
> running decode/unicode in various manifestations over "18 million 


over a sample of 600000 words (sorry for not being able to explain
myself clear enough so that everyone understands)
while my current project is 18e6 words, that is the overall running time
will be 87 vs. 186 seconds, which is fairly noticeable.

> words" (or is it 600 million?) and says "the differences are pretty 
> significant". 

600 million is the size of the whole corpus, that translates to
48 minutes vs. 1h43min. That already is a huge difference (going to
lunch during noon or waiting another hour until it runs over - and 
you can bet it is _very_ noticeable when I am hungry :-)).

With 9 different versions of the corpus (that is, what we are really
using now) that goes to 7.2 hours (or even less with python3.1!) vs. 15
hours. Being able to re-run the whole corpus generation in one working
day (and then go on with the next issues) vs. working overtime or
delivering the corpus one day later is a huge difference. Like, being
one day behind the schedule.

> I think I don't have to comment on that.

Indeed, the numbers are self-explanatory.

> 
> If you increase the number of loops to one million or one billion or 
> whatever even the slightest completely negligible difference will occur. 
> The same thing will happen if you just increase the corpus of words to a 
> million, trillion or whatever. The performance implications of that are 
> exactly none.
> 

I am not sure I understood that. Must be my English :-)

-- 
 -----------------------------------------------------------
| Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__    garabik @ kassiopeia.juls.savba.sk     |
 -----------------------------------------------------------
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!


From rt8396 at gmail.com  Fri Aug  7 13:43:05 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 10:43:05 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
Message-ID: 

On Aug 7, 11:03?am, Kee Nethery  wrote:
...(snip)
> I'm looking forward to the acceleration of improvements to the ?
> official docs based upon easy to provide user feedback. Glad to see ?
> that the bug tracking system is going to not be the primary means for ?
> documentation changes.

+1



From wuwei23 at gmail.com  Fri Aug  7 13:43:13 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 10:43:13 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	 
Message-ID: <1de1eadf-6a2a-414c-a7cf-cf235edadcfb@a39g2000pre.googlegroups.com>

kj  wrote:
> Feature, as others have pointed out, though I fail to see the need
> for it, given that Python's general syntax for string (as opposed
> to string literal) concatenation is already so convenient. ?I.e.,
> I fail to see why
>
> x = ("first part of a very long string "
> ? ? ?"second part of a very long string")
>
> is so much better than
>
> x = ("first part of a very long string " +
> ? ? ?"second part of a very long string")

My impression is it's mostly for one of clarity. It's especially
useful with regular expressions, as it allows for comments to document
each element of the regex (following example shamelessly taken from
the docs (albeit with personal preferences on formatting))):

re.compile(
    "[A-Za-z_]"       # letter or underscore
    "[A-Za-z0-9_]*"   # letter, digit or underscore
)

Not having the plus sign present does assist (IMO) in the ease of
parsing the regex.
re.compile(


From wuwei23 at gmail.com  Fri Aug  7 13:45:29 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 10:45:29 -0700 (PDT)
Subject: unicode() vs. s.decode()
References: 
	 
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	 
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	 
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com> 
	 
Message-ID: <006e7808-74e7-4d29-a7bc-01492d14de65@v15g2000prn.googlegroups.com>

garabik-news-2005... at kassiopeia.juls.savba.sk wrote:
> I am not sure I understood that. Must be my English :-)

I just parsed it as "blah blah blah I won't admit I'm wrong" and
didn't miss anything substantive.




From wuwei23 at gmail.com  Fri Aug  7 13:48:22 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 10:48:22 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
Message-ID: 

Kee Nethery  wrote:
> I'm looking forward to the acceleration of improvements to the ?
> official docs based upon easy to provide user feedback. Glad to see ?
> that the bug tracking system is going to not be the primary means for ?
> documentation changes.

I'm not sure what you see as being fundamentally different between
open access to a bug tracker & open access to a wiki, other than it
being a lot more difficult to have threaded discussion on a wiki.

Why exactly is posting an open comment on a bug tracker somehow
inferior to posting an open comment on a wiki?


From abecedarian314159 at yahoo.com  Fri Aug  7 13:51:17 2009
From: abecedarian314159 at yahoo.com (William)
Date: Fri, 7 Aug 2009 10:51:17 -0700 (PDT)
Subject: questions about object references
Message-ID: <786181.46665.qm@web110610.mail.gq1.yahoo.com>

I have a question.? Suppose I do the following:

def myfunc(a,b):
? return a+b

myfunc2=myfunc

is there anyway to find all of the references to myfunc?? That is, can I find out all of the functions that may be aliased to myfunc?

second question:



class MyClass(object):
?def __init__(a,b):
?? self.a=a
?? self.b=b
? def myfunc(self):
??? return self.a+self.b

myclass=MyClass(3,4)
myclass.myfunc2=myclass.myfunc

Is there any way to find all the references to myclass.myfunc--in this case,
myclass.myfunc2?

Thanks,
William

is there a way to 





      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From drobinow at gmail.com  Fri Aug  7 14:05:35 2009
From: drobinow at gmail.com (David Robinow)
Date: Fri, 7 Aug 2009 14:05:35 -0400
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References:  
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
Message-ID: <4eb0089f0908071105i5180b861rea513c70bf8f9655@mail.gmail.com>

On Fri, Aug 7, 2009 at 1:48 PM, alex23 wrote:
> Why exactly is posting an open comment on a bug tracker somehow
> inferior to posting an open comment on a wiki?
 When one believes that development is controlled by a cabal which is
jealous of outsiders and actively prevents improvements to the docs,
any change, even if only in perception, helps to weaken the hold of
the evil forces holding back the success of Python.


From mail at timgolden.me.uk  Fri Aug  7 14:08:22 2009
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 07 Aug 2009 19:08:22 +0100
Subject: Changing Remote Registry
In-Reply-To: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
Message-ID: <4A7C6D96.3000201@timgolden.me.uk>

Kevin Holleran wrote:
> Long story short, I am using _winreg to do this.
> 
> hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
> value,type = _winreg.QueryValueEx(hKey, item)
> if (value == wrongValue):
>        _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
> 
> 
> When I do this I receive the error:
> 
> _winreg.SetValue WindowsError: [Error 5] Access Denied

As an alternative, try using WMI instead. You'll have to look up the docs
a bit, but to get you started:


import wmi

reg = wmi.WMI ("remote-machine", namespace="default").StdRegProv

print reg.methods.keys ()



TJG


From vorticitywolfe at gmail.com  Fri Aug  7 14:17:28 2009
From: vorticitywolfe at gmail.com (J Wolfe)
Date: Fri, 7 Aug 2009 11:17:28 -0700 (PDT)
Subject: passing menu label to function
Message-ID: <44f84fe8-0dce-463f-b37f-b02f241bf93a@e34g2000vbm.googlegroups.com>

Hi,

I would like to pass the label name of a menu to the command it is
calling, is that possible?

self.menuitem.menu.add_command(label="pass this",command = lambda i =
self.self.menuitem.menu.cget("label"): self.function(i))

def function(self, i)
     print i   # print the label name


Any help would be appreciated!
Thanks!
Jonathan


From marduk at letterboxes.org  Fri Aug  7 14:18:51 2009
From: marduk at letterboxes.org (Albert Hopkins)
Date: Fri, 07 Aug 2009 14:18:51 -0400
Subject: PEP 8 exegetics: conditional imports?
In-Reply-To: 
References: 
Message-ID: <1249669131.8286.32.camel@centar>

On Fri, 2009-08-07 at 16:50 +0000, kj wrote:
> 
> Conditional imports make sense to me, as in the following example:
> 
> def foobar(filename):
>     if os.path.splitext(filename)[1] == '.gz':
>         import gzip
>         f = gzip.open(filename)
>     else:
>         f = file(filename)
>     # etc.
> 
> And yet, quoth PEP 8:
> 
>     - Imports are always put at the top of the file, just after any module
>       comments and docstrings, and before module globals and constants.
> 
> ...which seems to condemn conditional imports unequivocally. 
> 
> Then again, the PEP 8 scriptures do not explicitly mention conditional
> imports at all, as far as I can tell, which leaves open the
> possibility that they are still righteous. 
> 
> In fact, venerable passages in the Python standard library source
> code, if properly interpreted, can be seen to carry out conditional
> imports, such as this fragment recovered from random.py:
> 
>         if a is None:
>             try:
>                 a = long(_hexlify(_urandom(16)), 16)
>             except NotImplementedError:
>                 import time
>                 a = long(time.time() * 256) # use fractional seconds
> 
> Or even more clearly, this one from test/pystone.py:
> 
> if __name__ == '__main__':
>     import sys
> 
> 

I can't speak for others... but generally you can "tell" when an import
belongs at the top of a module and when you need to make exceptions.  I
would say that, as a general rule, they go up top (easier to identify
what external dependencies a module have).  There are, of course,
exceptions:

      * Exceptions and other not-often-executed blocks
      * Inside test functions (where the imported modules are only used
        by tests
      * Inside main() functions where the imported modules are only used
        if the module is run as a script
      * When startup-time is important. Often it's necessary to have you
        module up and running in an instant and import "expensive"
        modules as-needed.
      * "Dynamic" import such as plugins, etc.

Of course, like everything else in PEP 8, it's meant as a "guide" and
not as an "order".  YMMV.

-a




From wuwei23 at gmail.com  Fri Aug  7 14:30:41 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 11:30:41 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References:   
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
Message-ID: <56e513e5-63cd-479d-94b2-0f10f617d4a0@d4g2000prc.googlegroups.com>

David Robinow  wrote:
> ?When one believes that development is controlled by a cabal which is
> jealous of outsiders and actively prevents improvements to the docs,
> any change, even if only in perception, helps to weaken the hold of
> the evil forces holding back the success of Python.

Yeah, it's clearly all ego and assholes that's preventing Python from
being the enochian equivalent of programming languages :)


From marduk at letterboxes.org  Fri Aug  7 14:35:52 2009
From: marduk at letterboxes.org (Albert Hopkins)
Date: Fri, 07 Aug 2009 14:35:52 -0400
Subject: PEP 8 exegetics: conditional imports?
In-Reply-To: 
References: 
Message-ID: <1249670152.8286.43.camel@centar>

On Fri, 2009-08-07 at 16:50 +0000, kj wrote:
> 
> Conditional imports make sense to me, as in the following example:
> 
> def foobar(filename):
>     if os.path.splitext(filename)[1] == '.gz':
>         import gzip
>         f = gzip.open(filename)
>     else:
>         f = file(filename)
>     # etc.
> 

I should add that in your example I would probably still put the import
at the top, e.g.:

import gzip
[...]

def foobar(filename):
    if os.path.splitext(filename)[1] == '.gz':
        f = gzip.open(filename)
    else:
        f = open(filename)

Reason being is that if later on I decide I want to write another
function inside my module that does the same thing I don't have to do
the same conditional import.

Even better, if this is something you find yourself doing often you can
create your own "smart" open and put it in a library:

# file anyfile

import __builtin__
import gzip

def open(filename, ...):
    if filename.endswith('.gz'):
        f = gzip.open(filename, ...)
    else:
        f = __builtin__.open(f, ...)

    return f

Then:

>>> import anyfile
>>> f = anyfile.open(filename, ...)

-a




From keith.hughitt at gmail.com  Fri Aug  7 14:42:42 2009
From: keith.hughitt at gmail.com (pwnedd)
Date: Fri, 7 Aug 2009 11:42:42 -0700 (PDT)
Subject: Database query execution times in Python?
Message-ID: <24870050.post@talk.nabble.com>


Hi all,

I've been writing some code using libraries based on the Python Database API
2.0 (MySQLdb & pg), and so far things are working really well. There is one
thing that I have not been able to figure out how to do, however: 

Retrieve the time is took a given query to execute.

Does anyone know if this is possible?

Any help would be greatly appreciated.

Thanks!
Keith


-- 
View this message in context: http://www.nabble.com/Database-query-execution-times-in-Python--tp24870050p24870050.html
Sent from the Python - python-list mailing list archive at Nabble.com.



From SandorL at gmail.com  Fri Aug  7 14:48:16 2009
From: SandorL at gmail.com (=?ISO-8859-1?Q?L=E1szl=F3_S=E1ndor?=)
Date: Fri, 7 Aug 2009 14:48:16 -0400
Subject: question: why isn't a byte of a hash more uniform? how could I
	improve my code to cure that?
References: 
Message-ID: 

Thank you, Tim. My comments are below.

On 2009-08-07 13:19:47 -0400, Tim Chase  said:

>> After I have written a short Python script that hashes my textfile line by
>> line and collects the numbers next to the original, I checked what I got.
>> Instead of getting around 25% in each treatment, the range is 17.8%-31.3%.
> 
> That sounds suspiciously like 25% with a +/- 7% fluctuation one might 
> expect to see from non-random source data.

Could you help me where this range comes from? (If all my lines were 
"42", I wouldn't hit this range. So it cannot be a rule. Right?)

> 
> Remember that your outputs are driven purely by your inputs in a 
> deterministic fashion -- if your inputs are purely random, then your 
> outputs should more closely match your expected bin'ing.  If your 
> inputs aren't random, you get a taste of your own medicine ("my file 
> has just the number 42 on every line...why isn't my output random?").  
> And randomness-of-hash-output is a red herring since hashing is *not* 
> random.

Thanks, I tried to be correct with "pseudo-random". I understand that 
everything is dependent on input. I want it to be the case. However, I 
hoped that good hashes produce random-looking output from input with 
very little variation. It would be strange if I could not get more than 
18% of lines with a remainder of 3 (after division by 4), whatever hash 
I try just because these are names of people.

> 
> Your input is also finite -- an aspect which leaves you a far cry from 
> the full hash-space.  If an md5 has 32 bytes (256 bits) of data, your 
> input would have to cover 2**256 possible inputs to see the full 
> profile of your outputs.  That's a lot of input :)
> 
> -tkc

OK, I understand. Could anyone suggest a better way to do this, then?

(Recap: random-looking, close-to uniform assignment of one number out 
of four possibilities to strings.)

Thanks, everyone.

Laszlo



From REMpeteOVE at petezilla.co.uk  Fri Aug  7 15:04:41 2009
From: REMpeteOVE at petezilla.co.uk (Peter Chant)
Date: Fri, 07 Aug 2009 20:04:41 +0100
Subject: Setuptools - help!
References: 
	
Message-ID: <9fauk6-t24.ln1@phoenix.fire>

Robert Kern wrote:

> You need to put main.py into the pphoto package.
> 
> $ mkdir pphoto/
> $ mv main.py pphoto/
> $ touch pphoto/__init__.py
> 

Thanks, it worked.  Any ideas how to run the resulting scripts without
installing or running as root?

Pete


-- 
http://www.petezilla.co.uk


From nagle at animats.com  Fri Aug  7 15:06:47 2009
From: nagle at animats.com (John Nagle)
Date: Fri, 07 Aug 2009 12:06:47 -0700
Subject: Module updating plans for Python 3.1: feedparser, MySQLdb
In-Reply-To: 
References: <4a739a96$0$1615$742ec2ed@news.sonic.net>
	
Message-ID: <4a7c7a50$0$1586$742ec2ed@news.sonic.net>

Buck wrote:
> I use MySQLdb quite a bit in my work. I could volunteer to help update
> it. Are there any particular bugs we're talking about or just a
> straight port to 3.0?

    It's a non-trivial port.  There's a release candidate for Python 2.6;
see

https://sourceforge.net/project/shownotes.php?release_id=672239

but that was back in March and hasn't advanced since then.

There's an unofficial port of MySQLdb to
Python 2.6 for Windows.  See

https://sourceforge.net/forum/forum.php?thread_id=3108914&forum_id=70460

The MySQLdb developer says that conversion to 3.0 is hard, and he's busy
doing other things.

					John Nagle


From nagle at animats.com  Fri Aug  7 15:07:48 2009
From: nagle at animats.com (John Nagle)
Date: Fri, 07 Aug 2009 12:07:48 -0700
Subject: Is "feedparser" deprecated?
Message-ID: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>

   Feedparser requires SGMLlib, which has been removed from Python 3.0.
Feedparser hasn't been updated since 2007. Does this mean Feedparser
is dead?

				John Nagle


From van.lindberg at gmail.com  Fri Aug  7 15:15:55 2009
From: van.lindberg at gmail.com (VanL)
Date: Fri, 07 Aug 2009 14:15:55 -0500
Subject: Survey: Does your company use Python? Do you know a company that
	uses Python?
Message-ID: 

This is a survey to find as many companies using Python as we can. You 
can see the survey below:



You don't need to work at the company to add it to this list! We will 
filter for duplicates.

The answers to this survey will be kept private. If you still don't want 
to identify yourself, no problem! We just want to know where Python is 
being used.




From ethan at stoneleaf.us  Fri Aug  7 15:15:56 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Fri, 07 Aug 2009 12:15:56 -0700
Subject: question: why isn't a byte of a hash more uniform? how could
	I	improve my code to cure that?
In-Reply-To: 
References: 
	
Message-ID: <4A7C7D6C.4020904@stoneleaf.us>

L?szl? S?ndor wrote:
> Thank you, Tim. My comments are below.
> 
> On 2009-08-07 13:19:47 -0400, Tim Chase  
> said:
> 
>>> After I have written a short Python script that hashes my textfile 
>>> line by
>>> line and collects the numbers next to the original, I checked what I 
>>> got.
>>> Instead of getting around 25% in each treatment, the range is 
>>> 17.8%-31.3%.
>>
>>
>> That sounds suspiciously like 25% with a +/- 7% fluctuation one might 
>> expect to see from non-random source data.
> 
> 
> Could you help me where this range comes from? (If all my lines were 
> "42", I wouldn't hit this range. So it cannot be a rule. Right?)
> 
>>
>> Remember that your outputs are driven purely by your inputs in a 
>> deterministic fashion -- if your inputs are purely random, then your 
>> outputs should more closely match your expected bin'ing.  If your 
>> inputs aren't random, you get a taste of your own medicine ("my file 
>> has just the number 42 on every line...why isn't my output random?").  
>> And randomness-of-hash-output is a red herring since hashing is *not* 
>> random.
> 
> 
> Thanks, I tried to be correct with "pseudo-random". I understand that 
> everything is dependent on input. I want it to be the case. However, I 
> hoped that good hashes produce random-looking output from input with 
> very little variation. It would be strange if I could not get more than 
> 18% of lines with a remainder of 3 (after division by 4), whatever hash 
> I try just because these are names of people.
> 
>>
>> Your input is also finite -- an aspect which leaves you a far cry from 
>> the full hash-space.  If an md5 has 32 bytes (256 bits) of data, your 
>> input would have to cover 2**256 possible inputs to see the full 
>> profile of your outputs.  That's a lot of input :)
>>
>> -tkc
> 
> 
> OK, I understand. Could anyone suggest a better way to do this, then?
> 
> (Recap: random-looking, close-to uniform assignment of one number out of 
> four possibilities to strings.)
> 
> Thanks, everyone.
> 
> Laszlo
> 

Well,  a very simplistic method is to use the length of the input string 
modulus four.  If the names have decently "random" lengths, that may work.

~Ethan~


From __peter__ at web.de  Fri Aug  7 15:26:13 2009
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Aug 2009 21:26:13 +0200
Subject: passing menu label to function
References: <44f84fe8-0dce-463f-b37f-b02f241bf93a@e34g2000vbm.googlegroups.com>
Message-ID: 

J Wolfe wrote:

> I would like to pass the label name of a menu to the command it is
> calling, is that possible?
> 
> self.menuitem.menu.add_command(label="pass this",command = lambda i =
> self.self.menuitem.menu.cget("label"): self.function(i))
> 
> def function(self, i)
>      print i   # print the label name

A simple pure-python approach:

def add_command_with_label(menu, label, command):
    menu.add_command(label=label, command=lambda: command(label))

# ...

function = self.function
menu = self.menuitem.menu
add_command_with_label(menu, "pass this", function)

Alternatively, if you plan to change the labels during runtime:

index = 1 # indices start at 1, not 0
menu.add_command(label="whatever", command=lambda index=index, menu=menu: 
function(menu.entrycget(index, "label")))

(all untested, likely to contain typos)

Peter



From __peter__ at web.de  Fri Aug  7 15:42:16 2009
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Aug 2009 21:42:16 +0200
Subject: PEP 8 exegetics: conditional imports?
References: 
Message-ID: 

kj wrote:

> Conditional imports make sense to me, as in the following example:
> 
> def foobar(filename):
>     if os.path.splitext(filename)[1] == '.gz':
>         import gzip
>         f = gzip.open(filename)
>     else:
>         f = file(filename)
>     # etc.
> 
> And yet, quoth PEP 8:
> 
>     - Imports are always put at the top of the file, just after any module
>       comments and docstrings, and before module globals and constants.
> 
> ...which seems to condemn conditional imports unequivocally.
> 
> Then again, the PEP 8 scriptures do not explicitly mention conditional
> imports at all, as far as I can tell, which leaves open the
> possibility that they are still righteous.
> 
> In fact, venerable passages in the Python standard library source
> code, if properly interpreted, can be seen to carry out conditional
> imports, such as this fragment recovered from random.py:
> 
>         if a is None:
>             try:
>                 a = long(_hexlify(_urandom(16)), 16)
>             except NotImplementedError:
>                 import time
>                 a = long(time.time() * 256) # use fractional seconds
> 
> Or even more clearly, this one from test/pystone.py:
> 
> if __name__ == '__main__':
>     import sys
> 
> 
> 
> I seek the wisdom of the elders.  Is there a consensus on the matter
> of conditional imports?  Are they righteous?  Or are they the way
> of the wicked?

If you want to take a rational approach measure speed and memory footprint 
of your program both with the conditional and unconditional imports. Then go 
with the conditional imports only if you can demonstrate a noticeable 
benefit.

This criterion is unlikely to be met for the examples you give above. time 
is a built-in module, and gzip a thin wrapper around zlib which is also 
built-in.

Peter



From lists at cheimes.de  Fri Aug  7 15:44:57 2009
From: lists at cheimes.de (Christian Heimes)
Date: Fri, 07 Aug 2009 21:44:57 +0200
Subject: PEP 8 exegetics: conditional imports?
In-Reply-To: 
References: 
Message-ID: 

kj wrote:
> I seek the wisdom of the elders.  Is there a consensus on the matter
> of conditional imports?  Are they righteous?  Or are they the way
> of the wicked?

imports in functions are dangerous and may lead to dead locks if they 
are mixed with threads. An import should never start a thread and you 
should avoid to import code in threads.

Christian



From wuwei23 at gmail.com  Fri Aug  7 15:57:11 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 12:57:11 -0700 (PDT)
Subject: Is "feedparser" deprecated?
References: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
Message-ID: <61d0b767-144b-4e3b-96dd-afe71904d619@t11g2000prh.googlegroups.com>

John Nagle  wrote:
> ? ?Feedparser requires SGMLlib, which has been removed from Python 3.0.
> Feedparser hasn't been updated since 2007. Does this mean Feedparser
> is dead?

Wouldn't you be better served asking this on the feedparser bug
tracker?

http://code.google.com/p/feedparser/issues/list


From vorticitywolfe at gmail.com  Fri Aug  7 16:00:11 2009
From: vorticitywolfe at gmail.com (J Wolfe)
Date: Fri, 7 Aug 2009 13:00:11 -0700 (PDT)
Subject: passing menu label to function
References: <44f84fe8-0dce-463f-b37f-b02f241bf93a@e34g2000vbm.googlegroups.com>
	
Message-ID: <0ac769de-3a7c-4973-a333-d06b7b14d540@q35g2000vbi.googlegroups.com>

Thanks Peter,

I figured out an alternative just as you posted your response,

I just looped through the buttons I wanted to add and used the loop
variable to label the item and then passed it to the function, though
your way seems much more robust.

Thanks a lot!


From wuwei23 at gmail.com  Fri Aug  7 16:00:17 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 13:00:17 -0700 (PDT)
Subject: PEP 8 exegetics: conditional imports?
References: 
	
Message-ID: 

Peter Otten <__pete... at web.de> wrote:
> This criterion is unlikely to be met for the examples you give above. time
> is a built-in module, and gzip a thin wrapper around zlib which is also
> built-in.

This is something I was _utterly_ unaware of. Is there a list of what
modules are built-in readily available?

The only reference[1] I could find via Google doesn't list zlib at
all.

[1]: http://www.vldb.informatik.hu-berlin.de/Themen/manuals/python/python-texinfo/built-in_modules.html


From davea at ieee.org  Fri Aug  7 16:00:59 2009
From: davea at ieee.org (Dave Angel)
Date: Fri, 07 Aug 2009 16:00:59 -0400
Subject: question: why isn't a byte of a hash more uniform? how could
	I 	improve my code to cure that?
In-Reply-To: 
References: 
Message-ID: <4A7C87FB.40106@ieee.org>

L???????????????????????????????? wrote:
> Hi all,
> I am a Python novice, and right now I would be happy to simply get my job
> done with it, but I could appreciate some thoughts on the issue below.
>
> I need to assign one of four numbers to names in a list. The assignment
> should be pseudo-random: no pattern whatsoever, but deterministic,
> reproducible, and close to uniform. My understanding was that hash functions
> would do the job. As I only needed 2 bits of treatment, I picked a byte of
> the hashes generated, and even taken mod 4 of it. See the code below.
>
> After I have written a short Python script that hashes my textfile line by
> line and collects the numbers next to the original, I checked what I got.
> Instead of getting around 25% in each treatment, the range is 17.8%-31.3%. I
> understand that the pseudo-randomness means that the treatments should not
> be neat and symmetric. Still, this variation is unacceptable for my purpose.
> My understanding was that good hash functions generate numbers that look
> completely random, and picking only a byte should not change that. I thought
> the promise was also to get close to uniformity:
> http://en.wikipedia.org/wiki/Hash_function#Uniformity. I tried all the
> hashes in the hashlib module, and picked bytes from the beginning and the
> end of the hashes, but treatments never were close to uniform (curiously,
> always the last treatment seems to be too rare).
>
> Maybe it is an obvious CS puzzle, I'm looking forward to standing corrected.
>
> Thanks!
>
> Laszlo
>
> The script:
>
> #! /usr/bin/python
>
> f = open('names.txt', 'r')
> g = open('nameshashed.txt', 'a')
>
> import hashlib
>
> for line in f:
>     line = line.rstrip()
>     h = str(hashlib.sha512(line).hexdigest())
>     s = line + ',' + str(ord(h[64])%4) + '\n'
>     g.write(s),
>
>   
The problem is indeed simple, but really nothing to do with Python.  
You're using a single character from a hexdigest, so the only 
possibilities are 0,1,2,...9,A,B, C, D,E, and F

Taking the ords of each of those, and moduloing with 4, you get
     4 - 0
     5 - 1
     4 - 2
     3 - 3

In other words, there's a greater than expected likelihood of 1, and 
less than expected likelihood of 3.  I'd figure the distribution ought 
to be:
     25%,  31%, 25%, and 19%

I'd use digest() instead of hexdigest(), and of course reduce the 
subscript  to 63 or less.

DaveA


From davea at ieee.org  Fri Aug  7 16:16:01 2009
From: davea at ieee.org (Dave Angel)
Date: Fri, 07 Aug 2009 16:16:01 -0400
Subject: PEP 8 exegetics: conditional imports?
In-Reply-To: <1249669131.8286.32.camel@centar>
References:  <1249669131.8286.32.camel@centar>
Message-ID: <4A7C8B81.1010901@ieee.org>

Albert Hopkins wrote:
> On Fri, 2009-08-07 at 16:50 +0000, kj wrote:
>   
>> Conditional imports make sense to me, as in the following example:
>>
>> def foobar(filename):
>>     if os.path.splitext(filename)[1] == '.gz':
>>         import gzip
>>         f = gzip.open(filename)
>>     else:
>>         f = file(filename)
>>     # etc.
>>
>> And yet, quoth PEP 8:
>>
>>     - Imports are always put at the top of the file, just after any module
>>       comments and docstrings, and before module globals and constants.
>>
>> ...which seems to condemn conditional imports unequivocally. 
>>
>> Then again, the PEP 8 scriptures do not explicitly mention conditional
>> imports at all, as far as I can tell, which leaves open the
>> possibility that they are still righteous. 
>>
>> In fact, venerable passages in the Python standard library source
>> code, if properly interpreted, can be seen to carry out conditional
>> imports, such as this fragment recovered from random.py:
>>
>>         if a is None:
>>             try:
>>                 a = long(_hexlify(_urandom(16)), 16)
>>             except NotImplementedError:
>>                 import time
>>                 a = long(time.time() * 256) # use fractional seconds
>>
>> Or even more clearly, this one from test/pystone.py:
>>
>> if __name__ == '__main__':
>>     import sys
>>
>>
>>     
>
> I can't speak for others... but generally you can "tell" when an import
> belongs at the top of a module and when you need to make exceptions.  I
> would say that, as a general rule, they go up top (easier to identify
> what external dependencies a module have).  There are, of course,
> exceptions:
>
>       * Exceptions and other not-often-executed blocks
>       * Inside test functions (where the imported modules are only used
>         by tests
>       * Inside main() functions where the imported modules are only used
>         if the module is run as a script
>       * When startup-time is important. Often it's necessary to have you
>         module up and running in an instant and import "expensive"
>         modules as-needed.
>       * "Dynamic" import such as plugins, etc.
>
> Of course, like everything else in PEP 8, it's meant as a "guide" and
> not as an "order".  YMMV.
>
> -a
>
>
>   
Excellent points.  I'd add a couple more, one pro, and two con:

You need conditionals when you're doing things that are 
environment-specific.  For example, you might use Win32 stuff when on 
Windows, and something else when on Linux.  So you might have a pair of 
modules which encapsulate the non-portable aspects, and conditionally 
import one of those.

You usually want any imports to be complete before starting 
multithreading.  As somebody else has recently pointed out, there's an 
import-lock that's active during imports,

If two modules do mutual imports (not a good idea, but it is sometimes 
practically unavoidable), the earlier in the file that the import 
happens, the less likely for a problem to crop up.  So try to put them 
at the top.




From gnewsg at gmail.com  Fri Aug  7 16:22:58 2009
From: gnewsg at gmail.com (Giampaolo Rodola')
Date: Fri, 7 Aug 2009 13:22:58 -0700 (PDT)
Subject: Survey: Does your company use Python? Do you know a company that 
	uses Python?
References: 
Message-ID: 

On 7 Ago, 21:15, VanL  wrote:
> This is a survey to find as many companies using Python as we can. You
> can see the survey below:
>
> 
>
> You don't need to work at the company to add it to this list! We will
> filter for duplicates.
>
> The answers to this survey will be kept private. If you still don't want
> to identify yourself, no problem! We just want to know where Python is
> being used.

...you accidentally forgot to mention the *reason*.


--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil


From __peter__ at web.de  Fri Aug  7 16:27:26 2009
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Aug 2009 22:27:26 +0200
Subject: question: why isn't a byte of a hash more uniform? how could I
	improve my code to cure that?
References: 
	
Message-ID: 

Dave Angel wrote:

[clever analysis snipped]

> I'd use digest() instead of hexdigest(), and of course reduce the
> subscript  to 63 or less.

OP: You could also try

hash(line) % 4

While AFAIK it doesn't make promises about randomness it might still be good 
enough in practice.

Peter




From horos11 at gmail.com  Fri Aug  7 16:29:28 2009
From: horos11 at gmail.com (horos11)
Date: Fri, 7 Aug 2009 13:29:28 -0700 (PDT)
Subject: importing fully qualified scripts to check syntax
Message-ID: 

hey all,

I'm trying to make a syntax checker, where I say:

python -c "import /path/to/script"

to check the syntax of the script named '/path/to/script' (note: no py
extension needed). Of course this doesn't work because the
functionality for import is bundled up with the environment..

So - is there any simple, generic way in python to import a python
file without worrying about naming convention or environment? Sort of
like require in perl?

Ed



From __peter__ at web.de  Fri Aug  7 16:33:08 2009
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Aug 2009 22:33:08 +0200
Subject: PEP 8 exegetics: conditional imports?
References: 
	
	
Message-ID: 

alex23 wrote:

> This is something I was _utterly_ unaware of. Is there a list of what
> modules are built-in readily available?

>> sys.builtin_module_names
('__builtin__', '__main__', '_ast', '_bisect', '_codecs', '_collections', 
'_functools', '_locale', '_random', '_socket', '_sre', '_struct', 
'_symtable', '_warnings', '_weakref', 'array', 'binascii', 'cPickle', 
'cStringIO', 'errno', 'exceptions', 'fcntl', 'gc', 'grp', 'imp', 
'itertools', 'marshal', 'math', 'operator', 'posix', 'pwd', 'select', 
'signal', 'spwd', 'strop', 'sys', 'syslog', 'thread', 'time', 'unicodedata', 
'xxsubtype', 'zipimport', 'zlib')

Peter




From kee at kagi.com  Fri Aug  7 16:35:26 2009
From: kee at kagi.com (Kee Nethery)
Date: Fri, 7 Aug 2009 13:35:26 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References: 
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
Message-ID: <93DD1DF1-1614-47A6-A512-F7EFEE6B0642@kagi.com>


On Aug 7, 2009, at 10:48 AM, alex23 wrote:

> Kee Nethery  wrote:
>> I'm looking forward to the acceleration of improvements to the
>> official docs based upon easy to provide user feedback. Glad to see
>> that the bug tracking system is going to not be the primary means for
>> documentation changes.
>
> I'm not sure what you see as being fundamentally different between
> open access to a bug tracker & open access to a wiki, other than it
> being a lot more difficult to have threaded discussion on a wiki.
>
> Why exactly is posting an open comment on a bug tracker somehow
> inferior to posting an open comment on a wiki?

It's a good question and deserves a good answer.

* Fewer Steps
* Immediate
* Does not need to be formally reviewed
* Easier to search

For all these comments, assume the starting point is the section in a  
web page that documents a specific python function. Assume the user is  
using the documentation for the first time in attempt to convert to  
Python. Thus, this is the only official Python page they have ever  
seen, they found it via Google and went directly to it. For example  
purposes, I'll use the following page:
http://docs.python.org/reference/lexical_analysis.html
Lets say the user is in section 2.1.3 Comments

Here's the scenario: The user wanted to include "#" in one of their  
strings and the IDE kept interpreting it as a comment. But they really  
need to use that character in the string. Eventually they find out  
that they can escape the character in their string so that Python  
stops thinking it is the beginning of a comment. They want other users  
to not suffer through the same thing, and they want to contribute to  
the betterment of Python, so they want this information saved so that  
others can avoid the mistake they were making.

* Fewer Steps:

With the bug tracking system, their only option is to lobby to get the  
documentation changed. Lets assume that Python experts all agree that  
the docs should get updated with this gotcha (which as a newbie, they  
are not sure that is a valid assumption and would probably just halt  
in their quest to get the docs updated). But assuming everyone agrees  
this is a valuable addition to the docs so that others can avoid the  
same error, where on this page dues the user submit this bug? There is  
no link on this page to the bug tracking system.

Lets assume they find the bug tracking system through determined  
efforts because they believe there has to be such a thing and they are  
absolutely sure the powers that be want their input. When they find  
the bug tracking system ... they have to create a user account. Then  
they have to wait for the confirming email. Finally they get access to  
the bug tracking system and being a good citizen, they want to make  
sure that they are not duplicating a previously entered bug. What do  
they search on? Do they search for 2.1.3? Do they search for "#"?  
Chances are, even if they do a whole set of searches, and if there  
really is already another bug entered for the exact same issue, they  
are unlikely to find it.

So they create a bug and now they need to go back and reference the  
link (find the page from their browser history) and type up why they  
think their modification to the documentation is worthy. Then once the  
bug is submitted ... you get the picture, there are a gazillion steps  
just to submit a bug. Most people do not bother to submit little  
helpful hints to the docs because it is too much of a pain to do so  
and there is zero confidence that as a newbie, anyone cares about what  
they found confusing, after all, they are just a newbie and not worthy  
of altering the documentation. (Certainly that opinion has been  
expressed several times on this mailing list).

With a wiki article tied to each section in the docs, they click on  
the link and are taken directly to the wiki page of user contributions  
for this specific  2.1.3 section of the docs. They scan the user  
comments and see that no one else entered a note about this gotcha.  
They click on the edit button, enter their gotcha, save, and they are  
done.

* Immediate:

With the bug tracking system, they struggle to find a place to  
contribute and then once they make their contribution, they have no  
idea whether anyone will ever see it and whether they have just wasted  
a bunch of time.

With the wiki link for that section, in less than a minute, they can  
see the comments they have left attached to that specific section so  
that others can see them too and perhaps avoid the same mistake they  
made. A wiki link encourages new users to be contributors. New users  
are the absolute best source of what is confusing to a new user.

* Does not need to be formally reviewed:

With the bug tracking system, each bug has to be reviewed by a  
volunteer, analyzed, commented on, dealt with.

With a wiki, no one has to look at user comments. They can just leave  
them there and ignore them. Other users can police the content and add  
additional comments or examples. All the while none of the official  
volunteers have to get in the loop. If some official volunteer wants  
to improve the docs, they can scan the wiki contributions and use that  
as the source for official changes to the docs.

* Easier to search:

Very few people would think to search the bug tracking system for help  
with some specific function. If someone is having trouble with the #  
sign in their strings, the bug tracking system is not going to be at  
the top of their list for search locations, especially when the bug  
tracking system is not mentioned and when found requires a confirmed  
login.

With a wiki link, the first thing someone will do is click on that to  
see if anyone else left notes about the specific problem. If there was  
no answer there, they'd search Google and try bunches of different  
wordings looking for some clue as to what is happening. I doubt most  
users (except for expert users) would ever search the bug tracking  
system for hints on why their code is not doing what they expect.

My 2 cents,
Kee



From horos11 at gmail.com  Fri Aug  7 16:39:22 2009
From: horos11 at gmail.com (horos11)
Date: Fri, 7 Aug 2009 13:39:22 -0700 (PDT)
Subject: syntax checker in python
Message-ID: 

ps - I just realized that it isn't enough to do:

python -c 'import /path/to/script'

since that actually executes any statement inside of the script
(wheras all I want to do is check syntax)

So - let me reprhase that - exactly how can you do a syntax check in
python? Something like perl's -c:

     perl -c script_name.p

Ed


From nad at acm.org  Fri Aug  7 16:41:53 2009
From: nad at acm.org (Ned Deily)
Date: Fri, 07 Aug 2009 13:41:53 -0700
Subject: questions about object references
References: <786181.46665.qm@web110610.mail.gq1.yahoo.com>
Message-ID: 

In article <786181.46665.qm at web110610.mail.gq1.yahoo.com>,
 William  wrote:

> I have a question.? Suppose I do the following:
> 
> def myfunc(a,b):
> ? return a+b
> 
> myfunc2=myfunc
> 
> is there anyway to find all of the references to myfunc?? That is, can I find 
> out all of the functions that may be aliased to myfunc?

The general idea is to search the appropriate namespaces and check for 
object identity, so something like:

>>> def myfunc(a,b):
...     return a+b
... 
>>> myfunc2 = myfunc
>>> 
>>> name = None
>>> namespace = globals()
>>> 
>>> for name in namespace:
...     if namespace[name] is myfunc:
...         print " %s = %s" % (name, namespace[name])
... 
 myfunc = 
 myfunc2 = 

> second question:
> 
> class MyClass(object):
> ?def __init__(a,b):
> ?? self.a=a
> ?? self.b=b
> ? def myfunc(self):
> ??? return self.a+self.b
> 
> myclass=MyClass(3,4)
> myclass.myfunc2=myclass.myfunc
> 
> Is there any way to find all the references to myclass.myfunc--in this case,
> myclass.myfunc2?

This is a little trickier since the object you are searching for is a 
bound method; while it might seem like it should, testing for object 
identity doesn't work.  (You'd could test for identity of the function 
objects pointed to by the bound methods' __func__ attributes.)  However, 
plain old test for equality works, so, for example, to search the 
instance object's attribute space:

>>> class MyClass(object):
...     def __init__(self,a,b):
...         self.a=a
...         self.b=b
...     def myfunc(self):
...         return self.a+self.b
... 
>>> myclass = MyClass(3,4)
>>> myclass.myfunc2 = myclass.myfunc
>>> 
>>> for name in dir(myclass):
...     obj = getattr(myclass, name)  
...     if obj == myclass.myfunc:
...         print " %s is %s" % (name, obj)
... 
 myfunc is >
 myfunc2 is >

-- 
 Ned Deily,
 nad at acm.org



From ivlenin at gmail.com  Fri Aug  7 16:42:42 2009
From: ivlenin at gmail.com (I V)
Date: 7 Aug 2009 22:42:42 +0200
Subject: Is "feedparser" deprecated?
References: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
	<61d0b767-144b-4e3b-96dd-afe71904d619@t11g2000prh.googlegroups.com>
Message-ID: <4a7c91c2$1@news.x-privat.org>

On Fri, 07 Aug 2009 12:57:11 -0700, alex23 wrote:
> John Nagle  wrote:
>> Feedparser hasn't been updated since 2007. Does this mean Feedparser is
>> dead?
> 
> Wouldn't you be better served asking this on the feedparser bug tracker?
> 
> http://code.google.com/p/feedparser/issues/list

But if the project _is_ dead, one would be unlikely to get a response on 
the bug tracker; as seems, in fact, to have happened already:

http://code.google.com/p/feedparser/issues/detail?id=160&start=100

I take it that the lack of response to this issue means the answer is 
"yes."


From gagsl-py2 at yahoo.com.ar  Fri Aug  7 16:42:51 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 17:42:51 -0300
Subject: one method of COM object needs a variant type variable
References: <913F77222E913C49A057FDD7BBDEAAA30192B8A0@br-dc.uhul.wan>
Message-ID: 

En Fri, 07 Aug 2009 04:21:03 -0300, MICH?LEK Jan Mgr.
 escribi?:

> Thanks Gabriel,
> I seen this before, but I don't know, what's mean 'compatible object'. I  
> need create object who will like as an variant type.

A variant is like a giant union contaning almost every basic type. See
http://msdn.microsoft.com/en-us/library/ms221627.aspx
A variant can hold simple Python objects as integer, float, string... but
not complex ones as, say, DocXMLRPCServer. The conversion to/from variant
types is done automatically.
I think you'll get more help in the python-win32 at python.org list.

-- 
Gabriel Genellina



From fuzzyman at gmail.com  Fri Aug  7 16:52:03 2009
From: fuzzyman at gmail.com (Fuzzyman)
Date: Fri, 7 Aug 2009 13:52:03 -0700 (PDT)
Subject: Is python buffer overflow proof?
References:  
	
Message-ID: 

On Aug 3, 10:04?pm, sturlamolden  wrote:
> On 2 Aug, 15:50, Jizzai  wrote:
>
> > Is a _pure_ python program buffer overflow proof?
>
> > For example in C++ you can declare a char[9] to hold user input.
> > If the user inputs 10+ chars a buffer overflow occurs.
>
> Short answer: NO
>
> Bounds checking on sequence types is a protection against buffer
> overflow, but is certainly not sufficient.
>
> The Python interpreter is written in C. Python extension modules are
> written in C (or something similar). If you find an unprotected buffer
> in this C code, you can possibly overflow this buffer. This can be
> used for nasty things like corrupting the stack and injecting
> malicious code. There is a reason why the Python sandbox (rexec and
> Bastion modules) was disabled in Python 2.3.
>
> IronPython and Jython provides better protection against buffer
> overflow than CPython, as these interpreters are written in safer
> languages (C# and Java). You thus get an extra layer of protection
> between the Python code and the unsafe C (used in JVM and .NET
> runtimes).

Well, both Java and .NET both have their own FFI that let you do
whatever you want (more or less).

Michael Foord
--
http://www.ironpythoninaction.com/


From no.email at please.post  Fri Aug  7 16:53:10 2009
From: no.email at please.post (kj)
Date: Fri, 7 Aug 2009 20:53:10 +0000 (UTC)
Subject: unique-ifying a list
Message-ID: 



Suppose that x is some list.  To produce a version of the list with
duplicate elements removed one could, I suppose, do this:

    x = list(set(x))

but I expect that this will not preserve the original order of
elements.

I suppose that I could write something like

def uniquify(items):
    seen = set()
    ret = []
    for i in items:
        if not i in seen:
            ret.append(i)
            seen.add(i)
    return ret

But this seems to me like such a commonly needed operation that I
find it hard to believe one would need to resort to such self-rolled
solutions.  Isn't there some more standard (and hopefully more
efficient, as in "C-coded"/built-in) approach?

TIA!

kynn


From fuzzyman at gmail.com  Fri Aug  7 16:54:05 2009
From: fuzzyman at gmail.com (Fuzzyman)
Date: Fri, 7 Aug 2009 13:54:05 -0700 (PDT)
Subject: Is python buffer overflow proof?
References:  
	 
	
	<4a77c0d9$0$1584$742ec2ed@news.sonic.net>
Message-ID: <95f33050-4f3b-42e8-97f3-9caf3e36292f@g19g2000vbi.googlegroups.com>

On Aug 4, 6:06?am, John Nagle  wrote:
> Gabriel Genellina wrote:
> > En Mon, 03 Aug 2009 18:04:53 -0300, sturlamolden 
> > escribi?:
>
> >> On 2 Aug, 15:50, Jizzai  wrote:
>
> >>> Is a _pure_ python program buffer overflow proof?
>
> >>> For example in C++ you can declare a char[9] to hold user input.
> >>> If the user inputs 10+ chars a buffer overflow occurs.
>
> >> Short answer: NO
> > I disagree. You've just translated the responsability to check for
> > buffer overflows, from the Python VM, to the Java VM or the .Net runtime
> > (and all three suffered from buffer overruns and other problems in some
> > way or another).
>
> ? ? A more useful question is whether the standard libraries are being
> run through any of the commercial static checkers for possible buffer
> overflows.
>
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle

Python has been run through valgrind which did expose (and result in
the fixing) of several theoretical problems.

Pure Python can be crashed (cause segfaults) in various ways - there
is even a directory of tests that do this in the test suite. I don't
think any are due to buffer overflows.

Michael Foord
--
http://www.ironpythoninaction.com/


From mensanator at aol.com  Fri Aug  7 17:01:06 2009
From: mensanator at aol.com (Mensanator)
Date: Fri, 7 Aug 2009 14:01:06 -0700 (PDT)
Subject: Good news & bad news (was: Turtle Graphics are incompatible with 
	gmpy)
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
	
	 
	<49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com> 
	<4a7a28b3$0$2303$91cee783@newsreader01.highway.telekom.at> 
	
Message-ID: 

Bad news:

I ran the 2.5 turtle.py through the 2to3 refactorer but the
result would not run in 3.1, some kind of type mismatch between
ints and NoneType. So I set it aside.

Good news:

I tracked down the actual cause of the image discrepencies in my
report.

http://www.mensanator.com/mensanator/PythonTurtle/turtle.htm

These are completely bogus as it turns out. I had thought I was
essentially executing the same code (aside from changing 3.1
turtle functions that don't exist in 2.5 to their equivalent).

But in my mucking about tracking down the gmpy problem, a bug
crept in when I converted back from Python ints

  if side == 'northeast':
    elbow_offset = [int((gmpy.sqrt(elbow)-1)//2 +1),
                    -int(((gmpy.sqrt(elbow)-1)//2) +1)]
  else:
    elbow_offset = [-int(((gmpy.sqrt(elbow)-1)//2 +1)),
                    int(((gmpy.sqrt(elbow)-1)//2 +1))]

to gmpy ints.

  if side == 'northeast':
    elbow_offset = [(gmpy.sqrt(elbow)-1)//2 +1,
                    -((gmpy.sqrt(elbow)-1)//2) +1]
  else:
    elbow_offset = [-((gmpy.sqrt(elbow)-1)//2 +1),
                    ((gmpy.sqrt(elbow)-1)//2 +1)]

A ")" is mislocated in -((gmpy.sqrt(elbow)-1)//2) +1], the one
after "//2" should have been placed after the "+1". There were
still three matching sets, but the +1 was now happening after
the negation instead or prior to it. And, of course, this lead
to discrepencies in the calls to the turtle goto function.
And, luckily, the code chain for 2.5 originated from the version
prior to the introduction of this error, otherwise, if the same
error was in both, the images would have been identicle albeit
wrong.

So it looks like there is NO practical difference between the
2.5 algorithm and the 3.1 algorithm. I'm no longer going to try
to get the 2.5 turtle.py to work in 3.1.

And with the nhops calculation changed to

 nhops = 1+int((float(diffsq)**0.5)/(3*(1.1**self._speed)
*self._speed))

it no longer crashes in trace mode.

This was probably originally provoked by gmpy 1.10 and probably
isn't a problem in 2.6 with gmpy 1.04. I had upgraded my 2.6 gmpy
to 1.10 where it also crashed. I may have run the test code in
2.6 when I had 1.04 installed but it's unlikely I would have done
so with tracing on since it's 100 times slower. But I expect it
would not have failed due to this:


Changes in gmpy 1.10

Number conversion rules have changed.
-------------------------------------
The arguments in operations involving mixed types are converted
using the following rules:

   Integer --> Rational   --> Floating-point
    'int'       'Fraction'     'float'
    'long'      'mpq'          'Decimal'
    'mpz'                      'mpf'

   Old behavior:
     mpz(1) + float(1.2)     --> float(2.2)
     mpz(1) + Decimal('1.2') --> mpz(2)

   New behavior:
     mpz(1) + float(1.2)     --> mpf(2.2)
     mpz(1) + Decimal('1.2') --> mpf(2.2)


Apparently, as I painfully found out, that rule change can cause
applications to fail due to an mpf result from a mixed type function
instead of a float when they subsequently use fractional
exponentiation.



From duncan.booth at invalid.invalid  Fri Aug  7 17:04:15 2009
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 7 Aug 2009 21:04:15 GMT
Subject: Bug or feature: double strings as one
References: 
	
	<5Y2dnfnYAdsl0-HXnZ2dnUVZ_j9i4p2d@pdx.net>
	
Message-ID: 

Grant Edwards  wrote:

> Definitely.  Not only does it have _all_ the features, it even
> manages to simultaneously have several mutually-exclusive
> features.

Sounds a bit like Perl.


From jgardner at jonathangardner.net  Fri Aug  7 17:41:07 2009
From: jgardner at jonathangardner.net (Jonathan Gardner)
Date: Fri, 7 Aug 2009 14:41:07 -0700 (PDT)
Subject: unique-ifying a list
References: 
Message-ID: 

On Aug 7, 1:53?pm, kj  wrote:
> Suppose that x is some list. ?To produce a version of the list with
> duplicate elements removed one could, I suppose, do this:
>
> ? ? x = list(set(x))
>
> but I expect that this will not preserve the original order of
> elements.
>
> I suppose that I could write something like
>
> def uniquify(items):
> ? ? seen = set()
> ? ? ret = []
> ? ? for i in items:
> ? ? ? ? if not i in seen:
> ? ? ? ? ? ? ret.append(i)
> ? ? ? ? ? ? seen.add(i)
> ? ? return ret
>
> But this seems to me like such a commonly needed operation that I
> find it hard to believe one would need to resort to such self-rolled
> solutions. ?Isn't there some more standard (and hopefully more
> efficient, as in "C-coded"/built-in) approach?
>

Honestly, doing unique operations is pretty rare in the application
level. Unless you're writing some kind of database, I don't see why
you'd do it. (My recommendation is not to write databases.)

If you want unique elements, use a set. If you want to order them,
sort a list of the items in the set.

If you want to preserve the order, then using a dict may be even
better.

    orig_order = dict(reversed([reversed(i) for i in enumerate
(items)])
    unique_ordered = sorted(orig_order.keys(), key=lambda k: orig_order
[k])

Hints to understanding:
* enumerate generates (index, item) pairs.
* We reverse each pair so that we get an item -> index mapping.
* We reverse it so that the first ones appear last. Later pairs
override earlier ones in dict().


From jgardner at jonathangardner.net  Fri Aug  7 17:48:51 2009
From: jgardner at jonathangardner.net (Jonathan Gardner)
Date: Fri, 7 Aug 2009 14:48:51 -0700 (PDT)
Subject: syntax checker in python
References: 
Message-ID: <675fb1c7-1747-4a22-8d74-42affc1929bc@i4g2000prm.googlegroups.com>

On Aug 7, 1:39?pm, horos11  wrote:
> ps - I just realized that it isn't enough to do:
>
> python -c 'import /path/to/script'
>
> since that actually executes any statement inside of the script
> (wheras all I want to do is check syntax)
>
> So - let me reprhase that - exactly how can you do a syntax check in
> python? Something like perl's -c:
>
> ? ? ?perl -c script_name.p
>

You may want to read the sections under "Python Language Services" in
the Python Library Reference. There may be something you are looking
for there.


From no.email at please.post  Fri Aug  7 17:51:39 2009
From: no.email at please.post (kj)
Date: Fri, 7 Aug 2009 21:51:39 +0000 (UTC)
Subject: Why all the __double_underscored_vars__?
Message-ID: 



Python is chock-full of identifiers beginning and ending with double
underscores, such as __builtin__, __contains__, and __coerce__.

Using underscores to signal that an identifier is somehow "private"
to an implementation is pretty common in languages other than
Python.  But in these cases the understanding is that the use of
these variables in external code amounts to "going behind the API",
and is therefore unwise.

But as far as I can tell, Python's double-underscore variables are
very much part of Python's API.  E.g., programmers are specifically
instructed to override "double-underscore methods" to achieve
certain functionalities.

In this case, I wonder: what justifiies the double-underscore
convention?  For example, what would be the problem with changing
the name of the complex.__gt__ method to complex.gt?

TIA!

kynn


From hjtoi-better-remove-before-reply at comcast.net  Fri Aug  7 18:02:15 2009
From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen)
Date: Fri, 07 Aug 2009 15:02:15 -0700
Subject: Setuptools - help!
References: 
	
	<9fauk6-t24.ln1@phoenix.fire>
Message-ID: 

Peter Chant wrote:
> Thanks, it worked.  Any ideas how to run the resulting scripts without
> installing or running as root?

If you install as root, you should be able to run the scripts as normal
user. However, I don't recommend this approach since it could conflict
with your system Python packages.

I like using virtualenv to create isolated Python environments. I can
easily install whatever Python packages I want into each environment,
delete them when I am done with them or messed up etc.

http://pypi.python.org/pypi/virtualenv

-- 
  Heikki Toivonen - http://heikkitoivonen.net


From clp2 at rebertia.com  Fri Aug  7 18:13:41 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Fri, 7 Aug 2009 18:13:41 -0400
Subject: Why all the __double_underscored_vars__?
In-Reply-To: 
References: 
Message-ID: <50697b2c0908071513m2e25009dv7bd61e7b20a9094a@mail.gmail.com>

On Fri, Aug 7, 2009 at 5:51 PM, kj wrote:
> Python is chock-full of identifiers beginning and ending with double
> underscores, such as __builtin__, __contains__, and __coerce__.
>
> Using underscores to signal that an identifier is somehow "private"
> to an implementation is pretty common in languages other than
> Python. ?But in these cases the understanding is that the use of
> these variables in external code amounts to "going behind the API",
> and is therefore unwise.
>
> But as far as I can tell, Python's double-underscore variables are
> very much part of Python's API. ?E.g., programmers are specifically
> instructed to override "double-underscore methods" to achieve
> certain functionalities.

Right, but the *users* of the functionality provided by __methods__
typically should not invoke such methods directly.
For example, one should write `a > b`, not `a.__gt__(b)`. The lack of
underscores in just plain `gt` would suggest that it's a normal method
that could/should be called directly. Also, if the underscore
requirement were removed, then people might unknowingly overload an
operator without knowing it.
The double-underscores indicate that the Python interpreter itself
usually is the caller of the method, and as such some level of "magic"
may be associated with it. Other languages have you do the equivalent
of `def +():` or `def operator +()` to override an operator, the
keyword or symbol serving a similar warning that "here be magic". To
avoid adding another keyword and the confusion of having punctuation
as method names, Python uses a different convention, double leading
and trailing underscores.

Cheers,
Chris
-- 
http://blog.rebertia.com


From labjacksupport at gmail.com  Fri Aug  7 18:16:57 2009
From: labjacksupport at gmail.com (LabJack Support)
Date: Fri, 7 Aug 2009 15:16:57 -0700 (PDT)
Subject: ValueError: Procedure probably called with not enough arguments (8 
	bytes missing)
Message-ID: 

Hello! I am chasing around a problem that I am having with ctypes and
I am hoping someone can help out. Here is the Python code:

    def asynch(self, baudrate, data, idNum=None, demo=0, portB=0,
enableTE=0, enableTO=0, enableDel=0, numWrite=0, numRead=0):
        """
        Name: U12.asynchConfig(fullA, fullB, fullC, halfA, halfB,
halfC, idNum=None, demo=None, timeoutMult=1, configA=0, configB=0,
configTE=0)
        Args: See section 4.12 of the User's Guide
        Desc: Requires firmware V1.1 or higher. This function writes
to the asynch registers and sets the direction of the D lines (input/
output) as needed.

        >>> dev = U12()
        >>> dev.asynchConfig(96,1,1,22,2,1)
        >>> {'idNum': 1}
        """

        #Check id number
        if idNum is None:
            idNum = self.id
        idNum = ctypes.c_long(idNum)

        # Check size of data
        if len(data) > 18: raise ValueError("data can not be larger
than 18 elements")

        # Make data 18 elements large
        dataArray = [0] * 18
        for i in range(0, len(data)):
            dataArray[i] = data[i]
        print dataArray
        dataArray = listToCArray(dataArray, ctypes.c_long)

        ecode = staticLib.AsynchConfig(ctypes.byref(idNum), demo,
portB, enableTE, enableTO, enableDel, baudrate, numWrite, numRead,
ctypes.byref(dataArray))

        if ecode != 0:print ecode # TODO: Switch this out for
exception

        return {"idnum":long, "data":dataArray}

Here is the method signature of the c function:

long Asynch(	long *idnum,
				long demo,
				long portB,
				long enableTE,
				long enableTO,
				long enableDel,
				long baudrate,
				long numWrite,
				long numRead,
				long *data)

Thank you in advance,
Sam


From labjacksupport at gmail.com  Fri Aug  7 18:17:52 2009
From: labjacksupport at gmail.com (LabJack Support)
Date: Fri, 7 Aug 2009 15:17:52 -0700 (PDT)
Subject: ValueError: Procedure probably called with not enough arguments 
	(8 bytes missing)
References: eb8393e4-d923-4c27-a98c-1c370522c510@p28g2000vbn.googlegroups.com
Message-ID: <38bd8e73-77cb-49e2-8014-42dad28fc987@d21g2000vbm.googlegroups.com>

On Aug 7, 4:16?pm, LabJack Support  wrote:
> Hello! I am chasing around a problem that I am having with ctypes and
> I am hoping someone can help out. Here is the Python code:
>
> ? ? def asynch(self, baudrate, data, idNum=None, demo=0, portB=0,
> enableTE=0, enableTO=0, enableDel=0, numWrite=0, numRead=0):
> ? ? ? ? """
> ? ? ? ? Name: U12.asynchConfig(fullA, fullB, fullC, halfA, halfB,
> halfC, idNum=None, demo=None, timeoutMult=1, configA=0, configB=0,
> configTE=0)
> ? ? ? ? Args: See section 4.12 of the User's Guide
> ? ? ? ? Desc: Requires firmware V1.1 or higher. This function writes
> to the asynch registers and sets the direction of the D lines (input/
> output) as needed.
>
> ? ? ? ? >>> dev = U12()
> ? ? ? ? >>> dev.asynchConfig(96,1,1,22,2,1)
> ? ? ? ? >>> {'idNum': 1}
> ? ? ? ? """
>
> ? ? ? ? #Check id number
> ? ? ? ? if idNum is None:
> ? ? ? ? ? ? idNum = self.id
> ? ? ? ? idNum = ctypes.c_long(idNum)
>
> ? ? ? ? # Check size of data
> ? ? ? ? if len(data) > 18: raise ValueError("data can not be larger
> than 18 elements")
>
> ? ? ? ? # Make data 18 elements large
> ? ? ? ? dataArray = [0] * 18
> ? ? ? ? for i in range(0, len(data)):
> ? ? ? ? ? ? dataArray[i] = data[i]
> ? ? ? ? print dataArray
> ? ? ? ? dataArray = listToCArray(dataArray, ctypes.c_long)
>
> ? ? ? ? ecode = staticLib.AsynchConfig(ctypes.byref(idNum), demo,
> portB, enableTE, enableTO, enableDel, baudrate, numWrite, numRead,
> ctypes.byref(dataArray))
>
> ? ? ? ? if ecode != 0:print ecode # TODO: Switch this out for
> exception
>
> ? ? ? ? return {"idnum":long, "data":dataArray}
>
> Here is the method signature of the c function:
>
> long Asynch( ? ?long *idnum,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long demo,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long portB,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long enableTE,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long enableTO,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long enableDel,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long baudrate,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long numWrite,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long numRead,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long *data)
>
> Thank you in advance,
> Sam

Whoops I am sorry. The problem was due to a typo.


From bearophileHUGS at lycos.com  Fri Aug  7 19:04:19 2009
From: bearophileHUGS at lycos.com (Bearophile)
Date: Fri, 7 Aug 2009 16:04:19 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
Message-ID: 

durumdara:
> I wanna ask that is a bug or is it a feature?

For me it's a bug-prone antifeature.

Bye,
bearophile


From rt8396 at gmail.com  Fri Aug  7 19:40:14 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 16:40:14 -0700 (PDT)
Subject: Why all the __double_underscored_vars__?
References: 
	
Message-ID: 

On Aug 7, 5:13?pm, Chris Rebert  wrote:
> On Fri, Aug 7, 2009 at 5:51 PM, kj wrote:
> > Python is chock-full of identifiers beginning and ending with double
> > underscores, such as __builtin__, __contains__, and __coerce__.
...(snip)
> Right, but the *users* of the functionality provided by __methods__
...(snip)
> Cheers,
> Chris

Yes and Python's way is by-far the proper way to handle such
functionailty. Don't thank god, thank Guido


From sjmachin at lexicon.net  Fri Aug  7 19:46:03 2009
From: sjmachin at lexicon.net (John Machin)
Date: Fri, 7 Aug 2009 16:46:03 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	  
	<1de1eadf-6a2a-414c-a7cf-cf235edadcfb@a39g2000pre.googlegroups.com>
Message-ID: 

On Aug 8, 3:43?am, alex23  wrote:
> kj  wrote:
> > Feature, as others have pointed out, though I fail to see the need
> > for it, given that Python's general syntax for string (as opposed
> > to string literal) concatenation is already so convenient. ?I.e.,
> > I fail to see why
>
> > x = ("first part of a very long string "
> > ? ? ?"second part of a very long string")
>
> > is so much better than
>
> > x = ("first part of a very long string " +
> > ? ? ?"second part of a very long string")
>
> My impression is it's mostly for one of clarity. It's especially
> useful with regular expressions, as it allows for comments to document
> each element of the regex (following example shamelessly taken from
> the docs (albeit with personal preferences on formatting))):
>
> re.compile(
> ? ? "[A-Za-z_]" ? ? ? # letter or underscore
> ? ? "[A-Za-z0-9_]*" ? # letter, digit or underscore
> )
>
> Not having the plus sign present does assist (IMO) in the ease of
> parsing the regex.
> re.compile(

re.VERBOSE?


From piet at cs.uu.nl  Fri Aug  7 20:03:54 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Sat, 08 Aug 2009 02:03:54 +0200
Subject: help with threads
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
	<949b87d5-8cff-444a-b6ba-23d49610d130@p36g2000vbn.googlegroups.com>
	
Message-ID: 

>>>>> Michael Mossey  (MM) wrote:

>MM> Ah yes, that explains it. Some of these long computations are done in
>MM> pure C, so I'm sure the GIL is not being released.

Is that C code under your own control? Or at least the glue from Python
to C? In that case, and if the C code is not manipulating Python objects
or something in the Python interpreter, it could be changed to release
the GIL during the computation. That's also how Numpy does it, IIRC.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From rt8396 at gmail.com  Fri Aug  7 20:11:01 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 17:11:01 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
Message-ID: <5ba3a8f0-bdff-4ae7-bff4-abacf559d3a6@p23g2000vbl.googlegroups.com>

On Aug 7, 7:31?am, durumdara  wrote:
> Hi!
>
> I found an interesting thing in Python.
> Today one of my "def"s got wrong result.
...(snip)

I think it's a completely useless feature and i have never used it
even once! This so-called "feature" seems a direct  contridiction to
the zen...

"""There should be one-- and preferably only one --obvious way to do
it. """


From deets at nospam.web.de  Fri Aug  7 20:31:48 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sat, 08 Aug 2009 02:31:48 +0200
Subject: syntax checker in python
In-Reply-To: 
References: 
Message-ID: <7e3vblF2ea3orU1@mid.uni-berlin.de>

horos11 schrieb:
> ps - I just realized that it isn't enough to do:
> 
> python -c 'import /path/to/script'
> 
> since that actually executes any statement inside of the script
> (wheras all I want to do is check syntax)
> 
> So - let me reprhase that - exactly how can you do a syntax check in
> python? Something like perl's -c:

See pylint & pychecker.

Diez



From rt8396 at gmail.com  Fri Aug  7 20:33:09 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 17:33:09 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> 
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro 
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com> 
	
	 
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com> 
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
Message-ID: <0242fc66-2b78-4494-a133-43aff6a86353@p9g2000vbl.googlegroups.com>

On Aug 7, 3:35?pm, Kee Nethery  wrote:
(snip)

Kee,
that was an eloquent and enlighting post and i think it speaks volumes
to the lack of inclusion of all Pythoneers in this community. Not to
mention the viscous attitudes and self indulgence we have around here.

For those of you with ADD, Kee was speaking to the hurdles one must
overcome to change even the most minor things within this community.
Change around here almost parallels an act-of-congress with it's de-
motivating burdens that beset a new python user who may wish to add
his or her 2 pennies to the Python wishing well. And i believe like
Kee, most of them just give up and say
   """Oh Well, F### it!"""

Not to mention the never ending droves of naysayers, bullies, smart-
arses, and egomaniacs with their minions and sock-puppets ready at
moments notice to pounce on (and utterly destroy) any feeble noob who
dares to try and enhance the user experience in Python for all of us.



From nobody at nowhere.com  Fri Aug  7 20:40:51 2009
From: nobody at nowhere.com (Nobody)
Date: Sat, 08 Aug 2009 01:40:51 +0100
Subject: Executing untrusted code
References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com>
Message-ID: 

On Fri, 07 Aug 2009 08:15:08 -0700, Emanuele D'Arrigo wrote:

> Are
> there best practices to at least minimize some of the risks associated
> with untrusted code execution?

Yes: don't execute it. Failing that, run the Python interpreter within a
sandbox.

If you want to support restricted execution within a language, it has to
be built into the language from day one. Trying to bolt it on later is a
fool's errand.



From rt8396 at gmail.com  Fri Aug  7 20:54:40 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 17:54:40 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	<5ba3a8f0-bdff-4ae7-bff4-abacf559d3a6@p23g2000vbl.googlegroups.com>
Message-ID: 

It sure doesn't get any more obivous than...
  "string1" + "string2"

Although i much prefer string formatting to concatenation for almost
all cases except the most simple. This auto-magic conacatenation of
strings is unintuitive and completely moronic if you ask my opinion. I
blow chunks when i see this type of code, and the result from it, and
so should my interpretor!
  "string1" "string2" --> syntax error you moron!

If you are wanting to create shortcuts, do them where they make sense
and can serve a useful purpose...

t = ('1' "word" 33.3)
l = [1 2 3 (4 5)]
d = {keyname:value keyname:value etc...}

KISS people!


From gagsl-py2 at yahoo.com.ar  Fri Aug  7 21:10:33 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 22:10:33 -0300
Subject: unique-ifying a list
References: 
Message-ID: 

En Fri, 07 Aug 2009 17:53:10 -0300, kj  escribi?:

> Suppose that x is some list.  To produce a version of the list with
> duplicate elements removed one could, I suppose, do this:
>
>     x = list(set(x))
>
> but I expect that this will not preserve the original order of
> elements.
>
> I suppose that I could write something like
>
> def uniquify(items):
>     seen = set()
>     ret = []
>     for i in items:
>         if not i in seen:
>             ret.append(i)
>             seen.add(i)
>     return ret

Assuming the elements are hashable, yes, that's the fastest way (minus
some microoptimizations like using local names for ret.append and
seen.add, or the 'not in' operator).

See bearophile's recipe [1], another one [2] by Tim Peters (quite old but
worths reading the comment section), and this thread [3]

[1] http://code.activestate.com/recipes/438599/
[2] http://code.activestate.com/recipes/52560/
[3] http://groups.google.com/group/comp.lang.python/t/40c6c455f4fd5154/

-- 
Gabriel Genellina



From gagsl-py2 at yahoo.com.ar  Fri Aug  7 21:10:39 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 22:10:39 -0300
Subject: Is "feedparser" deprecated?
References: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
Message-ID: 

En Fri, 07 Aug 2009 16:07:48 -0300, John Nagle 
escribi?:

>    Feedparser requires SGMLlib, which has been removed from Python 3.0.
> Feedparser hasn't been updated since 2007. Does this mean Feedparser
> is dead?

Since we have generic and easy of use XML parsers like ElementTree and
lxml,  specialized rss parsers like feedparser are not so much required.
I've used ElementTree when I had to parse an rss feed in the past (not so
many times).

-- 
Gabriel Genellina



From gagsl-py2 at yahoo.com.ar  Fri Aug  7 21:16:06 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 22:16:06 -0300
Subject: importing fully qualified scripts to check syntax
References: 
Message-ID: 

En Fri, 07 Aug 2009 17:29:28 -0300, horos11  escribi?:

> I'm trying to make a syntax checker, where I say:
>
> python -c "import /path/to/script"
>
> to check the syntax of the script named '/path/to/script' (note: no py
> extension needed). Of course this doesn't work because the
> functionality for import is bundled up with the environment..

Try the py_compile module in the standard library:
http://docs.python.org/library/

The import statement does more than just checking syntax. You may want to  
start the interpreter with the -tt option also.

-- 
Gabriel Genellina



From steve at REMOVE-THIS-cybersource.com.au  Fri Aug  7 22:04:58 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 08 Aug 2009 02:04:58 GMT
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
Message-ID: <0006608d$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 12:00:42 +0200, Thorsten Kampe wrote:

> Bollocks. No one will even notice whether a code sequence runs 2.7 or
> 5.7 seconds. That's completely artificial benchmarking.

You think users won't notice a doubling of execution time? Well, that 
explains some of the apps I'm forced to use...

A two-second running time for (say) a command-line tool is already 
noticeable. A five-second one is *very* noticeable -- long enough to be a 
drag, short enough that you aren't tempted to go off and do something 
else while you're waiting for it to finish.


-- 
Steven


From Dave  Fri Aug  7 23:05:20 2009
From: Dave (Dave)
Date: Fri, 07 Aug 2009 22:05:20 -0500
Subject: Windows 7 : any problems installing or running Python ?
Message-ID: 

Anybody tried it ? 
Is anything broken, ie is the whole shootin' match good to go ?
I'm esp interested in WConio for 3.0/3.1 which I use heavily.
Thanks                              Dave     pdlemper at earthlink.net

                               " I saw the number 4 in silver "  Guido
                                   ( apologies to Wm Carlos Williams )


From n179911 at gmail.com  Fri Aug  7 23:29:06 2009
From: n179911 at gmail.com (n179911)
Date: Fri, 7 Aug 2009 20:29:06 -0700 (PDT)
Subject: How to address a global variable in a function
Message-ID: <82c2f2e7-ed3e-482b-9318-d5539a2a9da8@y10g2000prg.googlegroups.com>

HI,

I have a global variable

// line 8
tx  = 0

and then I have this function (start in line 12):
def handleTranslate(result):
	print line
	txStr, tyStr = result.group(1), result.group(2)
	print txStr, tyStr

	tx += int(txStr)
	ty += int(tyStr)

	return

But I am getting this error:
    handleTranslate(result)
  File "buildsvg.py", line 22, in handleTranslate
    tx += int(txStr)
UnboundLocalError: local variable 'tx' referenced before assignment

How can I fix it?
I have assigned 'tx' to 0 in line 8. I don't understand why i get this
error.

Thank you for any help.



From steve at REMOVE-THIS-cybersource.com.au  Fri Aug  7 23:29:43 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 08 Aug 2009 03:29:43 GMT
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
Message-ID: <0006746a$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 17:13:07 +0200, Thorsten Kampe wrote:

> One guy claims he has times between 2.7 and 5.7 seconds when
> benchmarking more or less randomly generated "one million different
> lines". That *is* *exactly* nothing.


We agree that in the grand scheme of things, a difference of 2.7 seconds 
versus 5.7 seconds is a trivial difference if your entire program takes 
(say) 8 minutes to run. You won't even notice it.

But why assume that the program takes 8 minutes to run? Perhaps it takes 
8 seconds to run, and 6 seconds of that is the decoding. Then halving 
that reduces the total runtime from 8 seconds to 5, which is a noticeable 
speed increase to the user, and significant if you then run that program 
tens of thousands of times.

The Python dev team spend significant time and effort to get improvements 
of the order of 10%, and you're pooh-poohing an improvement of the order 
of 100%. By all means, reminding people that pre-mature optimization is a 
waste of time, but it's possible to take that attitude too far to Planet 
Bizarro. At the point that you start insisting, and emphasising, that a 
three second time difference is "*exactly*" zero, it seems to me that 
this is about you winning rather than you giving good advice.



-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Fri Aug  7 23:29:59 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 08 Aug 2009 03:29:59 GMT
Subject: PEP 8 exegetics: conditional imports?
References: 
Message-ID: <0006747a$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 16:50:12 +0000, kj wrote:

> I seek the wisdom of the elders.  Is there a consensus on the matter of
> conditional imports?  Are they righteous?  Or are they the way of the
> wicked?

Being an elder doesn't grant you wisdom. It just might mean you've been 
stupid and ignorant for a long time.

For what it's worth, you can take my conditional imports when you've 
pried them from my cold, dead hands.



-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Fri Aug  7 23:31:31 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 08 Aug 2009 03:31:31 GMT
Subject: Bug or feature: double strings as one
References: 
	 
Message-ID: <000674d6$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 17:35:28 +0000, kj wrote:

> I fail to see why
> 
> x = ("first part of a very long string "
>      "second part of a very long string")

That's done by the compiler at compile time and is fast.

> is so much better than
> 
> x = ("first part of a very long string " +
>      "second part of a very long string")

That's done by the Python virtual machine at runtime and creates two 
strings, then passes them to a method, which creates a third string, then 
(usually) disposes of the first two strings.

Except for some versions of the CPython implementation, which has a 
keyhole compiler which folds constants at runtime. But it's a simple 
optimizer, easy to defeat:

>>> import dis
>>> dis.dis(compile("s = ''; s + 'a' + 'b'", '', 'exec'))
  1           0 LOAD_CONST               0 ('')
              3 STORE_NAME               0 (s)
              6 LOAD_NAME                0 (s)
              9 LOAD_CONST               1 ('a')
             12 BINARY_ADD
             13 LOAD_CONST               2 ('b')
             16 BINARY_ADD
             17 POP_TOP
             18 LOAD_CONST               3 (None)
             21 RETURN_VALUE
>>>
>>> dis.dis(compile("s = ''; s + 'a' 'b'", '', 'exec'))
  1           0 LOAD_CONST               0 ('')
              3 STORE_NAME               0 (s)
              6 LOAD_NAME                0 (s)
              9 LOAD_CONST               1 ('ab')
             12 BINARY_ADD
             13 POP_TOP
             14 LOAD_CONST               2 (None)
             17 RETURN_VALUE



-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Fri Aug  7 23:31:46 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 08 Aug 2009 03:31:46 GMT
Subject: how to overload operator "< <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
	
Message-ID: <000674e5$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 08:04:22 -0700, Scott David Daniels wrote:

> Benjamin Kaplan wrote:
>> .... Python does not support compound comparisons like that. You have
>> to do "a > b and b > c".
> 
> Funny, my python does.  This has been around a long time. I am not
> certain whether 1.5.2 did it, but "chained comparisons" have been around
> for a long time.

Yes it does:

$ python1.5
Python 1.5.2 (#1, Apr  1 2009, 22:55:54)  [GCC 4.1.2 20070925 (Red Hat 
4.1.2-27)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>
>>> 2 < 3 < 4
1


Remembering that back then, 0 and 1 were used instead of False and True.


-- 
Steven


From pavlovevidence at gmail.com  Sat Aug  8 00:01:47 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 7 Aug 2009 21:01:47 -0700 (PDT)
Subject: how to overload operator "< <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
	
	<7e2regF2eqbabU1@mid.uni-berlin.de>
Message-ID: <429efe93-afd0-4d46-973c-0df0d4f42c0c@p9g2000vbl.googlegroups.com>

On Aug 7, 7:18?am, "Diez B. Roggisch"  wrote:
> alex23 schrieb:
>
>
>
>
>
> > On Aug 7, 10:50 pm, Benjamin Kaplan  wrote:
> >> That isn't an operator at all. Python does not support compound
> >> comparisons like that. You have to do "a > b and b > c".
>
> > You know, it costs nothing to open up a python interpreter and check
> > your certainty:
>
> >>>> x = 10
> >>>> 1 < x < 20
> > True
>
> > This is a _very_ common pattern.
>
> >>>> class X(object):
> > ... ? def __lt__(self, other):
> > ... ? ? print 'in lt'
> > ... ? ? return True
> > ... ? def __gt__(self, other):
> > ... ? ? print 'in gt'
> > ... ? ? return True
> > ...
> >>>> x = X()
> >>>> 1 < x < 20
> > in gt
> > in lt
> > True
> >>>> 20 < x < 1
> > in gt
> > in lt
> > True
>
> > dmitrey: Diez' advice was the best you received.
>
> Not really. I didn't get the chaining, and Peter is right that for that
> there is no real overloading.

You can program __lt__, __gt__, and friends to return a closure with a
boolean value.  See my upcoming reply to the author.


Carl Banks


From pavlovevidence at gmail.com  Sat Aug  8 00:10:35 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 7 Aug 2009 21:10:35 -0700 (PDT)
Subject: how to overload operator "< <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
	
	<7e2regF2eqbabU1@mid.uni-berlin.de>
	<429efe93-afd0-4d46-973c-0df0d4f42c0c@p9g2000vbl.googlegroups.com>
Message-ID: <241f44f0-cd5c-48cd-a5ac-7a51954809fe@p23g2000vbl.googlegroups.com>

On Aug 7, 9:01?pm, Carl Banks  wrote:
> On Aug 7, 7:18?am, "Diez B. Roggisch"  wrote:
>
>
>
>
>
> > alex23 schrieb:
>
> > > On Aug 7, 10:50 pm, Benjamin Kaplan  wrote:
> > >> That isn't an operator at all. Python does not support compound
> > >> comparisons like that. You have to do "a > b and b > c".
>
> > > You know, it costs nothing to open up a python interpreter and check
> > > your certainty:
>
> > >>>> x = 10
> > >>>> 1 < x < 20
> > > True
>
> > > This is a _very_ common pattern.
>
> > >>>> class X(object):
> > > ... ? def __lt__(self, other):
> > > ... ? ? print 'in lt'
> > > ... ? ? return True
> > > ... ? def __gt__(self, other):
> > > ... ? ? print 'in gt'
> > > ... ? ? return True
> > > ...
> > >>>> x = X()
> > >>>> 1 < x < 20
> > > in gt
> > > in lt
> > > True
> > >>>> 20 < x < 1
> > > in gt
> > > in lt
> > > True
>
> > > dmitrey: Diez' advice was the best you received.
>
> > Not really. I didn't get the chaining, and Peter is right that for that
> > there is no real overloading.
>
> You can program __lt__, __gt__, and friends to return a closure with a
> boolean value. ?See my upcoming reply to the author.

Actually, scratch that.  It won't work because the chained comparison
short-circuits.  If you have __lt__ return a closure then a < b won't
work unless a < b is always true, which means it'll cause ordinary
binary comparison to fail.  Oh well.


Carl Banks


From n179911 at gmail.com  Sat Aug  8 00:14:37 2009
From: n179911 at gmail.com (n179911)
Date: Fri, 7 Aug 2009 21:14:37 -0700 (PDT)
Subject: How to address a global variable in a function
References: <82c2f2e7-ed3e-482b-9318-d5539a2a9da8@y10g2000prg.googlegroups.com>
Message-ID: 

On Aug 7, 8:29?pm, n179911  wrote:
> HI,
>
> I have a global variable
>
> // line 8
> tx ?= 0
>
> and then I have this function (start in line 12):
> def handleTranslate(result):
> ? ? ? ? print line
> ? ? ? ? txStr, tyStr = result.group(1), result.group(2)
> ? ? ? ? print txStr, tyStr
>
> ? ? ? ? tx += int(txStr)
> ? ? ? ? ty += int(tyStr)
>
> ? ? ? ? return
>
> But I am getting this error:
> ? ? handleTranslate(result)
> ? File "buildsvg.py", line 22, in handleTranslate
> ? ? tx += int(txStr)
> UnboundLocalError: local variable 'tx' referenced before assignment
>
> How can I fix it?
> I have assigned 'tx' to 0 in line 8. I don't understand why i get this
> error.
>
> Thank you for any help.

I figure out my problem

put this in my function:
global tx


From clp2 at rebertia.com  Sat Aug  8 00:14:58 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Sat, 8 Aug 2009 00:14:58 -0400
Subject: How to address a global variable in a function
In-Reply-To: <82c2f2e7-ed3e-482b-9318-d5539a2a9da8@y10g2000prg.googlegroups.com>
References: <82c2f2e7-ed3e-482b-9318-d5539a2a9da8@y10g2000prg.googlegroups.com>
Message-ID: <50697b2c0908072114y2676738fm48461973a03e472b@mail.gmail.com>

On Fri, Aug 7, 2009 at 11:29 PM, n179911 wrote:
> HI,
>
> I have a global variable
>
> // line 8
> tx ?= 0
>
> and then I have this function (start in line 12):
> def handleTranslate(result):
> ? ? ? ?print line
> ? ? ? ?txStr, tyStr = result.group(1), result.group(2)
> ? ? ? ?print txStr, tyStr
>
> ? ? ? ?tx += int(txStr)
> ? ? ? ?ty += int(tyStr)
>
> ? ? ? ?return
>
> But I am getting this error:
> ? ?handleTranslate(result)
> ?File "buildsvg.py", line 22, in handleTranslate
> ? ?tx += int(txStr)
> UnboundLocalError: local variable 'tx' referenced before assignment
>
> How can I fix it?
> I have assigned 'tx' to 0 in line 8. I don't understand why i get this
> error.

By default, Python assumes that any variables assigned to in a
function are local variables. To change this assumption, you need to
declare that you want to reference a global variable. This is done by
putting a `global` statement at the start of the function (i.e.
`global tx`).

In the future, you might STFW (in this case, for "UnboundLocalError")
before posting to the newsgroup, as you would have found several
explanations of this common newbie-biter.

Cheers,
Chris
-- 
http://blog.rebertia.com


From steve at REMOVE-THIS-cybersource.com.au  Sat Aug  8 00:25:31 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 08 Aug 2009 04:25:31 GMT
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
Message-ID: <0006817d$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 13:35:26 -0700, Kee Nethery wrote:


> > Why exactly is posting an open comment on a bug tracker somehow
> > inferior to posting an open comment on a wiki?
> 
> It's a good question and deserves a good answer.
> 
> * Fewer Steps
> * Immediate
> * Does not need to be formally reviewed
> * Easier to search

The last one is actually wrong, because the Python bug tracker is indexed 
by Google.

As for the rest, you're right that the current bug-tracker puts up 
barriers to people submitting comments and bugs. That's actually a good 
thing. The only thing worse than not enough information is too much 
information, and the current situation does a good job of discouraging 
the sorts of people who submit bad bug reports (e.g. duplicates of bug 
reports, bug reports for things fixed years ago, bug reports that are due 
to mistakes in their code, etc.).


> For example  
> purposes, I'll use the following page:
> http://docs.python.org/reference/lexical_analysis.html
> Lets say the user is in section 2.1.3 Comments

Disclaimer: python.org is down at the moment, so I can't check that page 
to see precisely what you're talking about.


> Here's the scenario: The user wanted to include "#" in one of their
> strings and the IDE kept interpreting it as a comment. But they really
> need to use that character in the string. Eventually they find out that
> they can escape the character in their string so that Python stops
> thinking it is the beginning of a comment.

Er, that would be a bug in the IDE, surely? Inside strings, # is an 
ordinary character with no special meaning.


>>> s = "this is a string with an unescaped # in it"
>>> s
'this is a string with an unescaped # in it'


The Python docs are supposed to be about Python the language, not work-
arounds for IDE bugs.


[...]
> Lets assume that Python experts all agree that  
> the docs should get updated with this gotcha (which as a newbie, they  
> are not sure that is a valid assumption and would probably just halt  
> in their quest to get the docs updated).

Good.

As a newbie, you SHOULD assume that anything you think is a bug is 
probably a bug in YOUR code, not Python, and the same goes for 
documentation bugs. If you don't understand something in the docs, 
chances are that it's a problem with you, not the docs. Your first port 
of call should be the tutor list, or here, and not to "fix" the docs by 
putting in noise that just gets in the way of the intended audience, 
namely experienced developers.


> and there is zero confidence that as a newbie, anyone cares about what  
> they found confusing, after all, they are just a newbie and not worthy  
> of altering the documentation. (Certainly that opinion has been  
> expressed several times on this mailing list).

No, we care. We just don't want to have the docs filled with all the hand-
holding and introductory stuff which the newbie needs. As a developer, 
you will outgrow the need for training wheels. Why force training wheels 
on the docs that you will be referring to for your entire career as a 
programmer, when you only need them for the first few months? There are 
plenty of docs aimed at newbies, and mailing lists where you can ask 
questions.

Putting user-comments on a separate page separates the noisy, low-value 
comments from the good stuff, but it increases the efforts needed by the 
webpage admin (who is going to deal with the comment spam? who is going 
to go through the user-comments stripping out the total nonsense put in 
by helpful ignoramuses?). It works for Wikipedia, because there are tens 
of thousands of users contributing small amounts of effort, and hundreds 
putting in a lot of effort, but even there there is a major problem with 
vandalism. We don't have those resources.

By the way, if a person wants to contribute, and can demonstrate 
competence, reliability, good-sense and trustworthiness, there's no 
reason why he or she couldn't get a check-in account for the Python docs. 
(All the Python docs are written by volunteers.) A good way to 
demonstrate these things is by submitting good-quality doc improvements 
to the bug-tracker. If a person can't be bothered to do so, because it 
requires effort to get an account, that goes a long way to demonstrating 
the *lack* of reliability which will disqualify them from the job.


> Very few people would think to search the bug tracking system for help  
> with some specific function. If someone is having trouble with the #  
> sign in their strings, the bug tracking system is not going to be at  
> the top of their list for search locations, especially when the bug  
> tracking system is not mentioned and when found requires a confirmed  
> login.

You don't need a login to view bug reports, only to modify them.

If you want an open-access documentation system go right ahead and build 
one. There are plenty of wikis available to use, and the Python docs are 
freely available as your starting point. I might even contribute myself. 
I just don't want it mixed in with the official docs: I want a clear 
separation between what's officially sanctioned and what's not.


-- 
Steven


From pavlovevidence at gmail.com  Sat Aug  8 00:46:51 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 7 Aug 2009 21:46:51 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> 
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro 
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com> 
	
	 
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com> 
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com>
Message-ID: 

On Aug 7, 9:25?pm, Steven D'Aprano  wrote:
> If you want an open-access documentation system go right ahead and build
> one. There are plenty of wikis available to use, and the Python docs are
> freely available as your starting point. I might even contribute myself.
> I just don't want it mixed in with the official docs: I want a clear
> separation between what's officially sanctioned and what's not.

The PyGame documentation has a "Click to view comments" box.  That
would be A. low profile, and B. distinct from official documentation
enough for me.

It'd probably be useful, but might also attract spam and lots of
useless fluff, because it's likely to be much higher volume than
documentation on other projects.


Carl Banks


From http  Sat Aug  8 01:06:23 2009
From: http (Paul Rubin)
Date: 07 Aug 2009 22:06:23 -0700
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com>
Message-ID: <7xd476rj1s.fsf@ruckus.brouhaha.com>

Steven D'Aprano  writes:
> As for the rest, you're right that the current bug-tracker puts up 
> barriers to people submitting comments and bugs. That's actually a good 
> thing. The only thing worse than not enough information is too much 
> information, and the current situation does a good job of discouraging 
> the sorts of people who submit bad bug reports (e.g. duplicates of bug 
> reports, bug reports for things fixed years ago, bug reports that are due 
> to mistakes in their code, etc.).

Stephen, Alex, etc.: have you actually used the php.net doc system?
Don't knock it til you've tried it.  IMO it is superior to Python's
system.  I don't use PHP much these days.


From http  Sat Aug  8 01:09:23 2009
From: http (Paul Rubin)
Date: 07 Aug 2009 22:09:23 -0700
Subject: question: why isn't a byte of a hash more uniform? how could I
	improve my code to cure that?
References: 
	
Message-ID: <7x8whuriws.fsf@ruckus.brouhaha.com>

L?szl? S?ndor  writes:
> OK, I understand. Could anyone suggest a better way to do this, then?
> 
> (Recap: random-looking, close-to uniform assignment of one number out
> of four possibilities to strings.)

Use a cryptographic hash function like md5 (deprecated for security
purposes but should be ok for this application).  The built-in Python
hash function is made for hashing symbols and is designed to avoid
collisions when you have a bunch of sequential identifiers (a,b,c...).
That is, it deliberately does NOT resemble a random function, which
would have a certain number of collisions by chance.


From rt8396 at gmail.com  Sat Aug  8 01:10:32 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 22:10:32 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	  
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
Message-ID: <14b5efce-e0b8-4455-ba9e-43b4b0df5e20@g6g2000vbr.googlegroups.com>

On Aug 7, 10:31?pm, Steven D'Aprano  wrote:
...(snip excessive showmanship) :-)

Ah Steven thats a real nice "snappy comeback" and some may get blinded
by the "black magic" but basically all you are saying is that "version
a" takes less overhead than "version b", compilation wise... but let's
dig a little deeper shall we?

First of all, i don't know about you but i don't set around all day
hard coding string data into my programs so the nano second difference
gained between auto-magic-string-concatination and "s1"+"s2"+"sN"
really doesn't justify a feature(bug??) like this that breaks the Zen
wide open. Sadly all it serves is to confuse new comers and contribute
line noise to the tutorial -- of which there is too much already!

Sure it's a nice parlor trick, but not much more...

Q: Steven, how often do you actually use this feature, i mean *really*
use it?


From pavlovevidence at gmail.com  Sat Aug  8 01:50:24 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 7 Aug 2009 22:50:24 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	
	<5Y2dnfnYAdsl0-HXnZ2dnUVZ_j9i4p2d@pdx.net> 
	
Message-ID: <8723453a-2836-4e9b-ac98-1fc4886da074@f10g2000vbf.googlegroups.com>

On Aug 7, 10:00?am, Grant Edwards  wrote:
> On 2009-08-07, Scott David Daniels  wrote:
>
> > Grant Edwards wrote:
> >> On 2009-08-07, durumdara  wrote:
> >>> In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
> >>> must concatenate the strings with some sign, like "+" or "||".
>
> >> In other languages like Ruby, awk, C, C++, etc. adjacent string
> >> constants are concatenated.
>
> > I must learn this "etc." language, I hear it mentioned all the time :-)
>
> Definitely. ?Not only does it have _all_ the features, it even
> manages to simultaneously have several mutually-exclusive
> features.

http://www.geocities.com/connorbd/tarpit/magentaaarm.html


(It's on Geocities, yikes, someone better archive that....)

Carl Banks


From rt8396 at gmail.com  Sat Aug  8 01:52:19 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 22:52:19 -0700 (PDT)
Subject: Windows 7 : any problems installing or running Python ?
References: 
Message-ID: 

On Aug 7, 10:05?pm, Dave WB3DWE wrote:
...(snip)

Oh God, windows 7 is here :(.  What great functionality has M$
bestowed on the weary peasants now? More importantly why the heck am i
still using windows in 2009? i think i will dump my winders os for
good this year and go linux from here on out (can i get a hell yea?).
Sorry Dave i don't think i'll ever try windows 7 but i hope you find a
solution because i do want you to use Python.

Oh and Google, the masses are ready for the windows replacement....
Google? ....Goooooooogle!!!



From rschroev_nospam_ml at fastmail.fm  Sat Aug  8 02:39:49 2009
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Sat, 08 Aug 2009 08:39:49 +0200
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <7xd476rj1s.fsf@ruckus.brouhaha.com>
References: 
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com>
	<7xd476rj1s.fsf@ruckus.brouhaha.com>
Message-ID: 

Paul Rubin schreef:
> Steven D'Aprano  writes:
>> As for the rest, you're right that the current bug-tracker puts up 
>> barriers to people submitting comments and bugs. That's actually a good 
>> thing. The only thing worse than not enough information is too much 
>> information, and the current situation does a good job of discouraging 
>> the sorts of people who submit bad bug reports (e.g. duplicates of bug 
>> reports, bug reports for things fixed years ago, bug reports that are due 
>> to mistakes in their code, etc.).
> 
> Stephen, Alex, etc.: have you actually used the php.net doc system?
> Don't knock it til you've tried it.  IMO it is superior to Python's
> system.  I don't use PHP much these days.

I have to use PHP from time to time, in which cases I often have to use
the manual on php.net. I don't like it at all.

The official documentation is often incomplete, leaving out the details
I need and forcing me to read the comments.

Which I don't want to do, since many comments show a lack of
understanding of the subject matter. I have to read all of them, trying
to find out which ones are correct and which ones are wrong (or
misleading) to get the complete picture.


I like Python's documentation, where I can be confident that the
documentation is correct (except in the case of the very exceptional
bug) and mostly clear, much better.

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

Roel Schroeven


From koranthala at gmail.com  Sat Aug  8 03:26:50 2009
From: koranthala at gmail.com (koranthala)
Date: Sat, 8 Aug 2009 00:26:50 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	
Message-ID: <40ed2690-3c6d-4413-a8a9-6bce7a304077@m7g2000prd.googlegroups.com>

On Aug 7, 5:15?pm, Dave Angel  wrote:
> alex23 wrote:
> > Paul Rubin  wrote:
>
> >> The PHP docs as I remember are sort of regular (non-publically
> >> editable) doc pages, each of which has a public discussion thread
> >> where people can post questions and answers about the topic of that
> >> doc page. ?I thought it worked really well. ?The main thing is that
> >> the good stuff from the comment section gets folded into the actual
> >> doc now and then.
>
> > I'd still like to see this kept out of the official docs as much as
> > possible, mostly for reasons of brevity & clarity. I think the
> > official docs should be considered definitive and not require a
> > hermeneutic evaluation against user comments to ensure they're still
> > correct...
>
> > How about a secondary site that embeds the docs and provides
> > commenting functionality around it? That's certainly a finitely scoped
> > project that those with issues about the docs could establish and
> > contribute to, with the possibility of it gaining official support
> > later once it gains traction.
>
> I share your concern about unmonitored comments. ?However, it seems a
> useful possibility would be for the "official" pages to each have
> specially-marked links that possibly lead to such user comments. ?
> Clearly they'd have to marked carefully, so that naive users don't
> confuse the two. ?But otherwise, it feels like a good idea.
>
> In my case, I usually access the docs via the Windows help file. ?So
> it'd be quite easy for me to recognize that once I've gotten to a
> browser page, I'm not in Kansas any more. ?But that could be also
> accomplished by having a very different stylesheet for the user comments
> page.
>
> DaveA

The best example that I have seen is djangobook.
The comment system in it is quite exquisite.
It would be good for the Python docs to have such a mechanism.


From pavlovevidence at gmail.com  Sat Aug  8 03:30:06 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sat, 8 Aug 2009 00:30:06 -0700 (PDT)
Subject: syntax checker in python
References: 
Message-ID: 

On Aug 7, 1:39?pm, horos11  wrote:
> ps - I just realized that it isn't enough to do:
>
> python -c 'import /path/to/script'
>
> since that actually executes any statement inside of the script
> (wheras all I want to do is check syntax)
>
> So - let me reprhase that - exactly how can you do a syntax check in
> python? Something like perl's -c:
>
> ? ? ?perl -c script_name.p

A quick and dirty way would be to use the py_compile:

python -m py_compile /path/to/script

Warning: this simply appends "c" to the filename and writes out the
compiled file (kind of dumb behavior, actually), so if it's a script
you probably want to delete it afterwards:

python -m py_compile /path/to/script ; rm -f /path/to/scriptc


A little better might be to write a little Python helper script that
directs output to nowhere (something like this, feel free to
embellish):

import py_compile
py_compile.compile(sys.argv[1],'/dev/null',None,False)



Carl Banks


From dmitrey.kroshko at scipy.org  Sat Aug  8 04:50:27 2009
From: dmitrey.kroshko at scipy.org (dmitrey)
Date: Sat, 8 Aug 2009 01:50:27 -0700 (PDT)
Subject: is it possible to overload operator "^"?
Message-ID: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>

hi all,
is it possible to overload operator "^"? (AFAIK __pow__ overloads **
instead of ^)
Thank you in advance, D.


From efotinis at y  Sat Aug  8 04:53:28 2009
From: efotinis at y (Elias Fotinis (eliasf))
Date: Sat, 8 Aug 2009 11:53:28 +0300
Subject: unique-ifying a list
In-Reply-To: 
References: 
Message-ID: <1249721637.162236@athprx03>

"kj" wrote:
> I suppose that I could write something like
>
> def uniquify(items):
>    seen = set()
>    ret = []
>    for i in items:
>        if not i in seen:
>            ret.append(i)
>            seen.add(i)
>    return ret
>
> But this seems to me like such a commonly needed operation that I
> find it hard to believe one would need to resort to such self-rolled
> solutions.  Isn't there some more standard (and hopefully more
> efficient, as in "C-coded"/built-in) approach?

The most "standard" way is a recipe from the itertools docs (I'd give a 
link, but python.org is down at the moment):

    def unique_everseen(iterable, key=None):
        "List unique elements, preserving order. Remember all elements ever 
seen."
        # unique_everseen('AAAABBBCCDAABBB') --> A B C D
        # unique_everseen('ABBCcAD', str.lower) --> A B C D
        seen = set()
        seen_add = seen.add
        if key is None:
            for element in iterable:
                if element not in seen:
                    seen_add(element)
                    yield element
        else:
            for element in iterable:
                k = key(element)
                if k not in seen:
                    seen_add(k)
                    yield element

All the recipes mentioned there are pretty handy, so I've made a module 
(iterutil.py) out of them.



From gherron at islandtraining.com  Sat Aug  8 05:02:19 2009
From: gherron at islandtraining.com (Gary Herron)
Date: Sat, 08 Aug 2009 02:02:19 -0700
Subject: is it possible to overload operator "^"?
In-Reply-To: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
References: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
Message-ID: <4A7D3F1B.5070100@islandtraining.com>

dmitrey wrote:
> hi all,
> is it possible to overload operator "^"? (AFAIK __pow__ overloads **
> instead of ^)
> Thank you in advance, D.
>   

The ^ operator is not an exponentiation, but rather the xor operator.  
Thus you can override it with the __xor__ method.

Beware, if you are thinking of ^ as an exponentiation like operator, the 
operator precedence will seem wrong.



From deets at nospam.web.de  Sat Aug  8 05:06:13 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sat, 08 Aug 2009 11:06:13 +0200
Subject: is it possible to overload operator "^"?
In-Reply-To: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
References: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
Message-ID: <7e4tg5F2eirarU1@mid.uni-berlin.de>

dmitrey schrieb:
> hi all,
> is it possible to overload operator "^"? (AFAIK __pow__ overloads **
> instead of ^)
> Thank you in advance, D.

Did you read the link I gave you for your last question?

It shows __xor__ as special method.

Diez


From efotinis at y  Sat Aug  8 05:44:16 2009
From: efotinis at y (Elias Fotinis (eliasf))
Date: Sat, 8 Aug 2009 12:44:16 +0300
Subject: Pywin32 @ windows 7
In-Reply-To: 
References: <004a01ca1733$a9768c10$4605a8c0@btsc1>
	
Message-ID: <1249724885.215365@athprx03>

"Dennis Lee Bieber" wrote:
> Ever consider that the name has WIN32 in, and not WIN64, for a
> reason?

Win32 is a misnomer; it just means "non-Win16". The same API exists in 
Windows x64 (with pointers expanded to 64-bit, of course). 



From efotinis at y  Sat Aug  8 05:46:59 2009
From: efotinis at y (Elias Fotinis (eliasf))
Date: Sat, 8 Aug 2009 12:46:59 +0300
Subject: Pywin32 @ windows 7
In-Reply-To: 
References: 
Message-ID: <1249724885.744992@athprx03>

"Algirdas Brazas" wrote:
> Did anyone manage to get windows extensions installet on windows 7 64 bit?
> As far as I try I get only "Setup program invalid or damaged".

Try downloading the installer again. It should work then.

I haven't tested it on Win7, but my Vista machine has Python and pywin32 
x64. 



From breamoreboy at yahoo.co.uk  Sat Aug  8 06:01:55 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 08 Aug 2009 11:01:55 +0100
Subject: Bug or feature: double strings as one
In-Reply-To: 
References: 		<5Y2dnfnYAdsl0-HXnZ2dnUVZ_j9i4p2d@pdx.net>
	
Message-ID: 

Unknown wrote:
> On 2009-08-07, Scott David Daniels  wrote:
>> Grant Edwards wrote:
>>> On 2009-08-07, durumdara  wrote:
>>>> In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
>>>> must concatenate the strings with some sign, like "+" or "||".
>>> In other languages like Ruby, awk, C, C++, etc. adjacent string
>>> constants are concatenated.
>> I must learn this "etc." language, I hear it mentioned all the time :-)
> 
> Definitely.  Not only does it have _all_ the features, it even
> manages to simultaneously have several mutually-exclusive
> features.
> 
I have tried google for this "etc." language but failed dismally.  Does 
it belong here? http://www.thefreecountry.com/compilers/esoteric.shtml

-- 
Kindest regards.

Mark Lawrence.



From efotinis at y  Sat Aug  8 06:02:45 2009
From: efotinis at y (Elias Fotinis (eliasf))
Date: Sat, 8 Aug 2009 13:02:45 +0300
Subject: Bug or feature: double strings as one
In-Reply-To: <8723453a-2836-4e9b-ac98-1fc4886da074@f10g2000vbf.googlegroups.com>
References: 
	
	<5Y2dnfnYAdsl0-HXnZ2dnUVZ_j9i4p2d@pdx.net>
	
	<8723453a-2836-4e9b-ac98-1fc4886da074@f10g2000vbf.googlegroups.com>
Message-ID: <1249725805.853806@athprx03>

"Carl Banks" wrote:
> http://www.geocities.com/connorbd/tarpit/magentaaarm.html
> (It's on Geocities, yikes, someone better archive that....)

http://web.archive.org/web/*/http://www.geocities.com/connorbd/tarpit/magentaaarm.html

:)



From dmitrey.kroshko at scipy.org  Sat Aug  8 06:04:11 2009
From: dmitrey.kroshko at scipy.org (dmitrey)
Date: Sat, 8 Aug 2009 03:04:11 -0700 (PDT)
Subject: is it possible to overload operator "^"?
References: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
	<7e4tg5F2eirarU1@mid.uni-berlin.de>
Message-ID: 

> the operator precedence will seem wrong
So, are there any ways to change operator precedence (for my class)?

To Diez:
yes, but I haven't paid attention to xor. BTW the url is currently
unavailable (Network Timeout. The server at docs.python.org is taking
too long to respond.).

On Aug 8, 12:06 pm, "Diez B. Roggisch"  wrote:
> Did you read the link I gave you for your last question?
> It shows __xor__ as special method.
> Diez


From deets at nospam.web.de  Sat Aug  8 06:08:20 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sat, 08 Aug 2009 12:08:20 +0200
Subject: is it possible to overload operator "^"?
In-Reply-To: 
References: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
	<7e4tg5F2eirarU1@mid.uni-berlin.de>
	
Message-ID: <7e514kF2ekgqfU1@mid.uni-berlin.de>

dmitrey schrieb:
>> the operator precedence will seem wrong
> So, are there any ways to change operator precedence (for my class)?

No. Those are built-in.

Diez 
 
 


From enleverLesX_XXmcX at XmclavXeauX.com  Sat Aug  8 06:39:14 2009
From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP)
Date: Sat, 08 Aug 2009 12:39:14 +0200
Subject: Windows 7 : any problems installing or running Python ?
References: 
Message-ID: <4a7d55d4$0$12642$ba4acef3@news.orange.fr>

Hi! 

I use, all days, Python 2.6 + Pywin32 on Win-7-64 bits. Without problem
(I confirm : pywin 32 on 64 bits).

@-salutations
-- 
Michel Claveau 


From rylesny at gmail.com  Sat Aug  8 06:58:03 2009
From: rylesny at gmail.com (ryles)
Date: Sat, 8 Aug 2009 03:58:03 -0700 (PDT)
Subject: unique-ifying a list
References: 
Message-ID: 

On Aug 7, 4:53?pm, kj  wrote:
> Suppose that x is some list. ?To produce a version of the list with
> duplicate elements removed one could, I suppose, do this:
>
> ? ? x = list(set(x))
>
> but I expect that this will not preserve the original order of
> elements.
>

OrderedSet is most likely on the way, but for now Python 3.1 and 2.7
have OrderedDict. For 3.0 and 2.6 the recipe is here:

http://code.activestate.com/recipes/576669

With OrderedDict you can do:

OrderedDict.fromkeys(x).keys()  # Returns an iterator in 3.x, a list
in 2.x.


From thorsten at thorstenkampe.de  Sat Aug  8 07:16:12 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Sat, 8 Aug 2009 13:16:12 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	<0006746a$0$2895$c3e8da3@news.astraweb.com>
Message-ID: 

* Steven D'Aprano (08 Aug 2009 03:29:43 GMT)
> On Fri, 07 Aug 2009 17:13:07 +0200, Thorsten Kampe wrote:
> > One guy claims he has times between 2.7 and 5.7 seconds when
> > benchmarking more or less randomly generated "one million different
> > lines". That *is* *exactly* nothing.
> 
> We agree that in the grand scheme of things, a difference of 2.7 seconds 
> versus 5.7 seconds is a trivial difference if your entire program takes 
> (say) 8 minutes to run. You won't even notice it.

Exactly.

> But why assume that the program takes 8 minutes to run? Perhaps it takes 
> 8 seconds to run, and 6 seconds of that is the decoding. Then halving 
> that reduces the total runtime from 8 seconds to 5, which is a noticeable 
> speed increase to the user, and significant if you then run that program 
> tens of thousands of times.

Exactly. That's why it doesn't make sense to benchmark decode()/unicode
() isolated - meaning out of the context of your actual program.

> By all means, reminding people that pre-mature optimization is a 
> waste of time, but it's possible to take that attitude too far to Planet 
> Bizarro. At the point that you start insisting, and emphasising, that a 
> three second time difference is "*exactly*" zero,

Exactly. Because it was not generated in a real world use case but by 
running a simple loop one millions times. Why one million times? Because 
by running it "only" one hundred thousand times the difference would 
have seen even less relevant.

> it seems to me that this is about you winning rather than you giving
> good advice.

I already gave good advice:
1. don't benchmark
2. don't benchmark until you have an actual performance issue
3. if you benchmark then the whole application and not single commands

It's really easy: Michael has working code. With that he can easily 
write two versions - one that uses decode() and one that uses unicode(). 
He can benchmark these with some real world input he often uses by 
running it a hundred or a thousand times (even a million if he likes). 
Then he can compare the results. I doubt that there will be any 
noticeable difference.

Thorsten


From vinay_sajip at yahoo.co.uk  Sat Aug  8 07:38:13 2009
From: vinay_sajip at yahoo.co.uk (Vinay Sajip)
Date: Sat, 8 Aug 2009 04:38:13 -0700 (PDT)
Subject: ANN: gnupg v0.2.1 released
Message-ID: 

A new version of the Python module which wraps GnuPG has been
released.

What Changed?
=============
This is a minor bug-fix release. See the project website (
http://code.google.com/p/python-gnupg/ ) for more information.

The current version passes all tests on Windows (Python 2.4, 2.5, 2.6,
3.1, Jython 2.5.0) and Ubuntu (Python 2.4, 2.5, 2.6, 3.0, Jython
2.5.0).

What Does It Do?
================
The gnupg module allows Python programs to make use of the
functionality provided by the Gnu Privacy Guard (abbreviated GPG or
GnuPG). Using this module, Python programs can encrypt and decrypt
data, digitally sign documents and verify digital signatures, manage
(generate, list and delete) encryption keys, using proven Public Key
Infrastructure (PKI) encryption technology based on OpenPGP.

This module is expected to be used with Python versions >= 2.4, as it
makes use of the subprocess module which appeared in that version of
Python. This module is a newer version derived from earlier work by
Andrew Kuchling, Richard Jones and Steve Traugott.

A test suite using unittest is included with the source distribution.

Simple usage:

>>> import gnupg
>>> gpg = gnupg.GPG(gnupghome='/path/to/keyring/directory')
>>> gpg.list_keys()
[{
  ...
  'fingerprint': 'F819EE7705497D73E3CCEE65197D5DAC68F1AAB2',
  'keyid': '197D5DAC68F1AAB2',
  'length': '1024',
  'type': 'pub',
  'uids': ['', 'Gary Gross (A test user) ']},
 {
  ...
  'fingerprint': '37F24DD4B918CC264D4F31D60C5FEFA7A921FC4A',
  'keyid': '0C5FEFA7A921FC4A',
  'length': '1024',
  ...
  'uids': ['', 'Danny Davis (A test user) ']}]
>>> encrypted = gpg.encrypt("Hello, world!", ['0C5FEFA7A921FC4A'])
>>> str(encrypted)
'-----BEGIN PGP MESSAGE-----\nVersion: GnuPG v1.4.9 (GNU/Linux)\n
\nhQIOA/6NHMDTXUwcEAf
...
-----END PGP MESSAGE-----\n'
>>> decrypted = gpg.decrypt(str(encrypted), passphrase='secret')
>>> str(decrypted)
'Hello, world!'
>>> signed = gpg.sign("Goodbye, world!", passphrase='secret')
>>> verified = verified = gpg.verify(str(signed))
>>> print "Verified" if verified else "Not verified"
'Verified'

For more information, visit http://code.google.com/p/python-gnupg/ -
as always, your feedback is most welcome (especially bug reports,
patches and suggestions for improvement). Enjoy!

Cheers

Vinay Sajip
Red Dove Consultants Ltd.


From kushal.kumaran+python at gmail.com  Sat Aug  8 07:47:50 2009
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Sat, 8 Aug 2009 17:17:50 +0530
Subject: Database query execution times in Python?
In-Reply-To: <24870050.post@talk.nabble.com>
References: <24870050.post@talk.nabble.com>
Message-ID: <1e364c4e0908080447s1496e40bkbf60f80020be863b@mail.gmail.com>

On Sat, Aug 8, 2009 at 12:12 AM, pwnedd wrote:
>
> Hi all,
>
> I've been writing some code using libraries based on the Python Database API
> 2.0 (MySQLdb & pg), and so far things are working really well. There is one
> thing that I have not been able to figure out how to do, however:
>
> Retrieve the time is took a given query to execute.
>
> Does anyone know if this is possible?
>

If nothing else, you could always use the time.time() function for
timing sections of code.  This will also include the time it took to
transport the result from the database to your application, though.

-- 
kushal


From no.email at please.post  Sat Aug  8 08:11:19 2009
From: no.email at please.post (kj)
Date: Sat, 8 Aug 2009 12:11:19 +0000 (UTC)
Subject: Why all the __double_underscored_vars__?
References: 
	
Message-ID: 

In  Chris Rebert  writes:

>The double-underscores indicate that the Python interpreter itself
>usually is the caller of the method, and as such some level of "magic"
>may be associated with it. Other languages have you do the equivalent
>of `def +():` or `def operator +()` to override an operator, the
>keyword or symbol serving a similar warning that "here be magic".

In this case, then I hope that some of these __items__ get demoted
to a more mundane level, so that the notion of "magic" doesn't get
trivialized by everyday idioms like:

if __name__ == '__main__':
    # etc

There are a few in this category...  I figure that they are cases
of "atavistic magic".

I bring this up because I find it quite difficult to explain to my
students (who are complete newcomers to programming) all the
__underscored__ stuff that even rank noobs like them have to deal
with.  (Trust me, to most of them your reply to my post would be
as clear as mud.)  This suggests to me that there's something a
bit unnatural about some of these __items__.

Anyway, thanks for your post.  I see your point.

kynn


From thorsten at thorstenkampe.de  Sat Aug  8 08:19:44 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Sat, 8 Aug 2009 14:19:44 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	
	<006e7808-74e7-4d29-a7bc-01492d14de65@v15g2000prn.googlegroups.com>
Message-ID: 

* alex23 (Fri, 7 Aug 2009 10:45:29 -0700 (PDT))
> garabik-news-2005... at kassiopeia.juls.savba.sk wrote:
> > I am not sure I understood that. Must be my English :-)
> 
> I just parsed it as "blah blah blah I won't admit I'm wrong" and
> didn't miss anything substantive.

Alex, there are still a number of performance optimizations that require 
a thorough optimizer like you. Like using short identifiers instead of 
long ones. I guess you could easily prove that by comparing "a = 0" to 
"a_long_identifier = 0" and running it one hundred trillion times. The 
performance gain could easily add up to *days*. Keep us updated.

Thorsten


From gdamjan at gmail.com  Sat Aug  8 08:25:40 2009
From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=)
Date: Sat, 08 Aug 2009 14:25:40 +0200
Subject: String to valid Python identifier
References: 
	<4a7a9328$0$2355$9b622d9e@news.freenet.de>
Message-ID: <5f70l6-70h.ln1@archaeopteryx.softver.org.mk>



>> Is there any easy function in the stdlib to convert any random string
>> in a valid Python identifier .. possibly by replacing non-valid
>> characters with _ ?
> 
> I think this is fairly underspecified as a problem statement. A
> solution that would meet your specification would be

True, I was thinking that if there was an obvious solution I'd get the 
answer right away.. so it seems there's not.

I did try the string.maketrans way... it was a bit ugly so I decided to 
ask here if I'm missing something... maybe I'll try maketrans again.


ps.
by "convert" I didn't mean a full transformation... I was more hoping 
for the least intrusive transformation that would still leave 
discernible resemblance of the original string. 



-- 
?????? ( http://softver.org.mk/damjan/ )

When you do things right, people won't be sure if you did anything at 
all.


From thorsten at thorstenkampe.de  Sat Aug  8 08:28:54 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Sat, 8 Aug 2009 14:28:54 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	
Message-ID: 

* garabik-news-2005-05 at kassiopeia.juls.savba.sk (Fri, 7 Aug 2009 
17:41:38 +0000 (UTC))
> Thorsten Kampe  wrote:
> > If you increase the number of loops to one million or one billion or
> > whatever even the slightest completely negligible difference will
> > occur. The same thing will happen if you just increase the corpus of
> > words to a million, trillion or whatever. The performance
> > implications of that are exactly none.
> 
> I am not sure I understood that. Must be my English :-)

I guess you understand me very well and I understand you very well. If 
the performance gain you want to prove doesn't show with 600,000 words, 
you test again with 18,000,000 words and if that is not impressive 
enough with 600,000,000 words. Great.

Or if a million repetitions of your "improved" code don't show the 
expected "performance advantage" you run it a billion times. Even 
greater. Keep on optimzing.

Thorsten


From cournape at gmail.com  Sat Aug  8 09:02:37 2009
From: cournape at gmail.com (David Cournapeau)
Date: Sat, 8 Aug 2009 22:02:37 +0900
Subject: Why all the __double_underscored_vars__?
In-Reply-To: 
References: 
	
	
Message-ID: <5b8d13220908080602y65815858yda25ddbfd3a05031@mail.gmail.com>

On Sat, Aug 8, 2009 at 9:11 PM, kj wrote:
> In  Chris Rebert  writes:
>
>>The double-underscores indicate that the Python interpreter itself
>>usually is the caller of the method, and as such some level of "magic"
>>may be associated with it. Other languages have you do the equivalent
>>of `def +():` or `def operator +()` to override an operator, the
>>keyword or symbol serving a similar warning that "here be magic".
>
> In this case, then I hope that some of these __items__ get demoted
> to a more mundane level, so that the notion of "magic" doesn't get
> trivialized by everyday idioms like:
>
> if __name__ == '__main__':
> ? ?# etc
>
> There are a few in this category... ?I figure that they are cases
> of "atavistic magic".
>
> I bring this up because I find it quite difficult to explain to my
> students (who are complete newcomers to programming) all the
> __underscored__ stuff that even rank noobs like them have to deal
> with. ?(Trust me, to most of them your reply to my post would be
> as clear as mud.)

Maybe your students do not need to know about it, at least at the
beginning ? I heavily use python, and do not use the underscore
methods so much most of the time, except for __init__,

cheers,

David


From michael at stroeder.com  Sat Aug  8 09:09:23 2009
From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=)
Date: Sat, 08 Aug 2009 15:09:23 +0200
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	<0006746a$0$2895$c3e8da3@news.astraweb.com>
	
Message-ID: <41a0l6-2u4.ln1@nb2.stroeder.com>

Thorsten Kampe wrote:
> * Steven D'Aprano (08 Aug 2009 03:29:43 GMT)
>> But why assume that the program takes 8 minutes to run? Perhaps it takes 
>> 8 seconds to run, and 6 seconds of that is the decoding. Then halving 
>> that reduces the total runtime from 8 seconds to 5, which is a noticeable 
>> speed increase to the user, and significant if you then run that program 
>> tens of thousands of times.
> 
> Exactly. That's why it doesn't make sense to benchmark decode()/unicode
> () isolated - meaning out of the context of your actual program.

Thorsten, the point is you're too arrogant to admit that making such a general
statement like you did without knowing *anything* about the context is simply
false. So this is not a technial matter. It's mainly an issue with your attitude.

>> By all means, reminding people that pre-mature optimization is a 
>> waste of time, but it's possible to take that attitude too far to Planet 
>> Bizarro. At the point that you start insisting, and emphasising, that a 
>> three second time difference is "*exactly*" zero,
> 
> Exactly. Because it was not generated in a real world use case but by 
> running a simple loop one millions times. Why one million times? Because 
> by running it "only" one hundred thousand times the difference would 
> have seen even less relevant.

I was running it one million times to mitigate influences on the timing by
other background processes which is a common technique when benchmarking. I
was mainly interested in the percentage which is indeed significant. The
absolute times also strongly depend on the hardware where the software is
running. So your comment about the absolute times are complete nonsense. I'm
eager that this software should also run with acceptable response times on
hardware much slower than my development machine.

> I already gave good advice:
> 1. don't benchmark
> 2. don't benchmark until you have an actual performance issue
> 3. if you benchmark then the whole application and not single commands

You don't know anything about what I'm doing and what my aim is. So your
general rules don't apply.

> It's really easy: Michael has working code. With that he can easily 
> write two versions - one that uses decode() and one that uses unicode().

Yes, I have working code which was originally written before .decode() being
added in Python 2.2. Therefore I wondered whether it would be nice for
readability to replace unicode() by s.decode() since the software does not
support Python versions prior 2.3 anymore anyway. But one aspect is also
performance and hence my question and testing.

Ciao, Michael.


From vlastimil.brom at gmail.com  Sat Aug  8 09:21:38 2009
From: vlastimil.brom at gmail.com (Vlastimil Brom)
Date: Sat, 8 Aug 2009 15:21:38 +0200
Subject: String to valid Python identifier
In-Reply-To: <5f70l6-70h.ln1@archaeopteryx.softver.org.mk>
References: 
	<4a7a9328$0$2355$9b622d9e@news.freenet.de>
	<5f70l6-70h.ln1@archaeopteryx.softver.org.mk>
Message-ID: <9fdb569a0908080621w116dd3e7qbdb4019bbb0f691a@mail.gmail.com>

2009/8/8 ?????? ??????????? :
>
>
>>> Is there any easy function in the stdlib to convert any random string
>>> in a valid Python identifier .. possibly by replacing non-valid
>>> characters with _ ?
...
>
> ps.
> by "convert" I didn't mean a full transformation... I was more hoping
> for the least intrusive transformation that would still leave
> discernible resemblance of the original string.
>
>
>
> --
> ?????? ( http://softver.org.mk/damjan/ )
>
> When you do things right, people won't be sure if you did anything at
> all.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Depending on the needs (speed, readability ...), the regular
expression replacement might be viable too:
>>> import re
>>> print re.sub(r"[^a-zA-Z0-9_]", r"_", u"a?bc d:e?_123's - foo?!var")
a_bc_d_e__123_s___foo__var
>>> print re.sub(r"\W", r"_", u"a?bc d:e?_123's - foo?!var") # equivalent
a_bc_d_e__123_s___foo__var
>>>

Additionally, as with the other approaches, you also have to check for
the (illegal) starting digit and replace it or prepend some valid
prefix.
hth
 vbr


From lcazarre at gmail.com  Sat Aug  8 09:31:02 2009
From: lcazarre at gmail.com (Caezar)
Date: Sat, 8 Aug 2009 06:31:02 -0700 (PDT)
Subject: www.python.org website is down?
Message-ID: 

I cannot connect to the official Python website. I get the following
error message:

"Connection Interrupted
The connection to the server was reset while the page was loading.
The network link was interrupted while negotiating a connection.
Please try again."

Are you experiencing the same problem?


From breamoreboy at yahoo.co.uk  Sat Aug  8 09:41:57 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 08 Aug 2009 14:41:57 +0100
Subject: www.python.org website is down?
In-Reply-To: 
References: 
Message-ID: 

Caezar wrote:
> I cannot connect to the official Python website. I get the following
> error message:
> 
> "Connection Interrupted
> The connection to the server was reset while the page was loading.
> The network link was interrupted while negotiating a connection.
> Please try again."
> 
> Are you experiencing the same problem?
Yes, it's been down for several hours.

-- 
Kindest regards.

Mark Lawrence.



From fasteliteprogrammer at yahoo.com  Sat Aug  8 09:48:04 2009
From: fasteliteprogrammer at yahoo.com (Craig)
Date: Sat, 8 Aug 2009 06:48:04 -0700 (PDT)
Subject: www.python.org website is down?
In-Reply-To: 
Message-ID: <314905.49987.qm@web36501.mail.mud.yahoo.com>

Yes the same prob.

--- On Sat, 8/8/09, Mark Lawrence  wrote:

> From: Mark Lawrence 
> Subject: Re: www.python.org website is down?
> To: python-list at python.org
> Date: Saturday, August 8, 2009, 8:41 AM
> Caezar wrote:
> > I cannot connect to the official Python website. I get
> the following
> > error message:
> > 
> > "Connection Interrupted
> > The connection to the server was reset while the page
> was loading.
> > The network link was interrupted while negotiating a
> connection.
> > Please try again."
> > 
> > Are you experiencing the same problem?
> Yes, it's been down for several hours.
> 
> -- Kindest regards.
> 
> Mark Lawrence.
> 
> -- http://mail.python.org/mailman/listinfo/python-list
> 


      


From python at mrabarnett.plus.com  Sat Aug  8 09:48:16 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Sat, 08 Aug 2009 14:48:16 +0100
Subject: www.python.org website is down?
In-Reply-To: 
References: 
Message-ID: <4A7D8220.90806@mrabarnett.plus.com>

Caezar wrote:
> I cannot connect to the official Python website. I get the following
> error message:
> 
> "Connection Interrupted
> The connection to the server was reset while the page was loading.
> The network link was interrupted while negotiating a connection.
> Please try again."
> 
> Are you experiencing the same problem?

A.M. Kuchling said:

"""
Both www.python.org and svn.python.org are down.  They're hosted on
the same machine, and it seems to have run into disk problems and
hasn't rebooted even after power-cycling.  Thomas Wouters will be
visiting the machine physically tomorrow to try to diagnose the
problem.

(The machine also hosts planet.python.org and hg.python.org.)
"""


From bh at izb.knu.ac.kr  Sat Aug  8 10:26:53 2009
From: bh at izb.knu.ac.kr (Byung-Hee HWANG)
Date: Sat, 08 Aug 2009 23:26:53 +0900
Subject: www.python.org website is down?
References: 
Message-ID: <86ab2a4c0i.fsf@betla.izb.knu.ac.kr>

Caezar  writes:

> I cannot connect to the official Python website. I get the following
> error message:
>
> "Connection Interrupted
> The connection to the server was reset while the page was loading.
> The network link was interrupted while negotiating a connection.
> Please try again."
>
> Are you experiencing the same problem?

Yes, me, too. Now i can't open the URL www.python.org ;;

-- 
"But there's a little more. Don Corleone is too modest."
		-- Emilio Barzini, "Chapter 20", page 286


From danielwong at berkeley.edu  Sat Aug  8 11:15:24 2009
From: danielwong at berkeley.edu (Daniel Wong)
Date: Sat, 8 Aug 2009 08:15:24 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
Message-ID: 

>
> A.M. Kuchling said:
>
> """
> Bothwww.python.organd svn.python.org are down. ?They're hosted on
> the same machine, and it seems to have run into disk problems and
> hasn't rebooted even after power-cycling. ?Thomas Wouters will be
> visiting the machine physically tomorrow to try to diagnose the
> problem.
>
> (The machine also hosts planet.python.org and hg.python.org.)
> """

This is probably a stupid question, but Is there going to be any data
loss if it turns out that the disk has died completely? I assume there
are backups of the repo that are geographically distributed.


From efotinis at y  Sat Aug  8 11:43:34 2009
From: efotinis at y (Elias Fotinis (eliasf))
Date: Sat, 8 Aug 2009 18:43:34 +0300
Subject: www.python.org website is down?
In-Reply-To: 
References: 
Message-ID: <1249746242.50676@athprx03>

"Caezar" wrote:
> I cannot connect to the official Python website.
[snip]
> Are you experiencing the same problem?

Yes, it's been down for a while.

A useful site to check in such occasions is 
http://downforeveryoneorjustme.com/. 



From foetsch at yahoo.com  Sat Aug  8 12:02:48 2009
From: foetsch at yahoo.com (=?UTF-8?B?TWljaGFlbCBGw7Z0c2No?=)
Date: Sat, 08 Aug 2009 18:02:48 +0200
Subject: unicode() vs. s.decode()
In-Reply-To: <2qcrk6-doj.ln1@nb2.stroeder.com>
References: 	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
Message-ID: <4A7DA1A8.4020603@yahoo.com>

Michael Str?der wrote:
 > >>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
 > 17.23644495010376
 > >>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
 > 72.087096929550171
 >
 > That is significant! So the winner is:
 >
 > unicode('???????','utf-8')

Which proves that benchmark results can be misleading sometimes. :-)

unicode() becomes *slower* when you try "UTF-8" in uppercase, or an 
entirely different codec, say "cp1252":

   >>> timeit.Timer("unicode('???????','UTF-8')").timeit(1000000)
   2.5777881145477295
   >>> timeit.Timer("'???????'.decode('UTF-8')").timeit(1000000)
   1.8430399894714355
   >>> timeit.Timer("unicode('???????','cp1252')").timeit(1000000)
   2.3622498512268066
   >>> timeit.Timer("'???????'.decode('cp1252')").timeit(1000000)
   1.7812771797180176

The reason seems to be that unicode() bypasses codecs.lookup() if the 
encoding is one of "utf-8", "latin-1", "mbcs", or "ascii". OTOH, 
str.decode() always calls codecs.lookup().

If speed is your primary concern, this will give you even better 
performance than unicode():

   decoder = codecs.lookup("utf-8").decode
   for i in xrange(1000000):
       decoder("???????")[0]


However, there's also a functional difference between unicode() and 
str.decode():

unicode() always raises an exception when you try to decode a unicode 
object. str.decode() will first try to encode a unicode object using the 
default encoding (usually "ascii"), which might or might not work.

Kind Regards,
M.F.



From garabik-news-2005-05 at kassiopeia.juls.savba.sk  Sat Aug  8 12:16:49 2009
From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk)
Date: Sat, 8 Aug 2009 16:16:49 +0000 (UTC)
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	
	
Message-ID: 

Thorsten Kampe  wrote:
> * garabik-news-2005-05 at kassiopeia.juls.savba.sk (Fri, 7 Aug 2009 
> 17:41:38 +0000 (UTC))
>> Thorsten Kampe  wrote:
>> > If you increase the number of loops to one million or one billion or
>> > whatever even the slightest completely negligible difference will
>> > occur. The same thing will happen if you just increase the corpus of
>> > words to a million, trillion or whatever. The performance
>> > implications of that are exactly none.
>> 
>> I am not sure I understood that. Must be my English :-)
> 
> I guess you understand me very well and I understand you very well. If 

I did not. Really. But then it has been explained to me, so I think I do
now :-)

> the performance gain you want to prove doesn't show with 600,000 words, 
> you test again with 18,000,000 words and if that is not impressive 
> enough with 600,000,000 words. Great.
> 

Huh? 
18e6 words is what I am working with _now_. Most of the data is already
collected, there are going to be few more books, but that's all. And the
optimization I was talking about means going home from work one hour
later or earlier. Quite noticeable for me.
600e6 words is the main corpus. Data is already there and wait to be
processed in some time. Once we finih our current project. That is 
real life, no thought experiment.


> Or if a million repetitions of your "improved" code don't show the 
> expected "performance advantage" you run it a billion times. Even 
> greater. Keep on optimzing.

No, we do not have one billion words (yet - I assume you are talking
about American billion - if you are talking about European billion, we
would be masters of the world with a billion word corpus!).
However, that might change once we start collecting www data (which is a
separate project, to be started in a year or two)
Then, we'll do some more optimiation because the time differences will
be more noticeable. Easy as that.


-- 
 -----------------------------------------------------------
| Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__    garabik @ kassiopeia.juls.savba.sk     |
 -----------------------------------------------------------
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!


From nipunreddevil at gmail.com  Sat Aug  8 12:34:02 2009
From: nipunreddevil at gmail.com (nipun batra)
Date: Sat, 8 Aug 2009 12:34:02 -0400
Subject: Serial port access
Message-ID: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>

Hi,
How can we access serial port using usb-serial converters,using python in
linux.I want to further use pyGTK for Gui development after accessing serial
data.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rogerpack2005 at gmail.com  Sat Aug  8 12:34:05 2009
From: rogerpack2005 at gmail.com (rogerdpack)
Date: Sat, 8 Aug 2009 09:34:05 -0700 (PDT)
Subject: .h files?
Message-ID: <50c453d9-d455-4f08-959c-e225149495fb@i18g2000pro.googlegroups.com>

Question.  Seems that with python distributions you have the option to
include either "external facing, public" *.h files, and make them
available, or include the whole kit and kaboodle [all *.h files].  Any
word on how python does this currently?  Just wondering as ruby runs
into the same question.
Thanks!
-roger


From jimxu at google.com  Sat Aug  8 12:47:14 2009
From: jimxu at google.com (Yongjian Xu)
Date: Sat, 8 Aug 2009 09:47:14 -0700
Subject: Why all the __double_underscored_vars__?
In-Reply-To: 
References: 
	 
	
Message-ID: <9c09a1210908080947t6d955beaxa495502b95ce9c1@mail.gmail.com>

These "special" methods are not meant to be used or known to beginners. They
aren't even meant to be called directly (in most cases). They are either
operator overloading methods or behavior customization methods. In my
opinion, in the meta programming realm. Should probably in advanced topic or
something.


On Sat, Aug 8, 2009 at 5:11 AM, kj  wrote:

> In  Chris Rebert <
> clp2 at rebertia.com> writes:
>
> >The double-underscores indicate that the Python interpreter itself
> >usually is the caller of the method, and as such some level of "magic"
> >may be associated with it. Other languages have you do the equivalent
> >of `def +():` or `def operator +()` to override an operator, the
> >keyword or symbol serving a similar warning that "here be magic".
>
> In this case, then I hope that some of these __items__ get demoted
> to a more mundane level, so that the notion of "magic" doesn't get
> trivialized by everyday idioms like:
>
> if __name__ == '__main__':
>    # etc
>
> There are a few in this category...  I figure that they are cases
> of "atavistic magic".
>
> I bring this up because I find it quite difficult to explain to my
> students (who are complete newcomers to programming) all the
> __underscored__ stuff that even rank noobs like them have to deal
> with.  (Trust me, to most of them your reply to my post would be
> as clear as mud.)  This suggests to me that there's something a
> bit unnatural about some of these __items__.
>
> Anyway, thanks for your post.  I see your point.
>
> kynn
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From n179911 at gmail.com  Sat Aug  8 12:47:38 2009
From: n179911 at gmail.com (n179911)
Date: Sat, 8 Aug 2009 09:47:38 -0700 (PDT)
Subject: Need help in refactoring my python script
Message-ID: <10d392bc-0a41-4a12-a863-f5fcb296d40c@a37g2000prf.googlegroups.com>

I have a python script which process a file line by line, if the line
matches a regex, it calls a function to handle it.

My question is is there a better write to refactor my script. The
script works, but as it is, i need to keep indent to the right of the
editor as I add more and more regex for my file.

Thank you for any idea.
Now my code end up like this:

for line in fi.readlines():

	result= reg1.match(line)

	if result:
		handleReg1(result)

	else:
		result = reg2.match(line)

		if result:
			handleReg2(result)
		else:
			result = reg3.match(line)

			if result:
				handleReg3(result)
			else:
				result = reg4.match(line)

				if result:
					handleReg4(result)
				else:
					result = reg5.match(line)

					if result:
                                               handleReg5(result)


From exarkun at twistedmatrix.com  Sat Aug  8 12:54:51 2009
From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com)
Date: Sat, 08 Aug 2009 16:54:51 -0000
Subject: Serial port access
In-Reply-To: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
References: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
Message-ID: <20090808165451.7171.1497184396.divmod.xquotient.112@localhost.localdomain>

On 04:34 pm, nipunreddevil at gmail.com wrote:
>Hi,
>How can we access serial port using usb-serial converters,using python 
>in
>linux.I want to further use pyGTK for Gui development after accessing 
>serial
>data.

Twisted supports serial ports and has good Gtk integration.

http://twistedmatrix.com/projects/core/documentation/examples/ has some
examples of each of these things (take a look at mouse.py for the serial
port example).

Jean-Paul


From hatbabe at gmail.com  Sat Aug  8 12:57:32 2009
From: hatbabe at gmail.com (the hatter)
Date: Sat, 8 Aug 2009 09:57:32 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
Message-ID: 

> A.M. Kuchling said:
>
> """
> Bothwww.python.organd svn.python.org are down. ?They're hosted on
> the same machine, and it seems to have run into disk problems and
> hasn't rebooted even after power-cycling. ?Thomas Wouters will be
> visiting the machine physically tomorrow to try to diagnose the
> problem.
>
> (The machine also hosts planet.python.org and hg.python.org.)
> """

I was hoping to find an official mirror to grab source from when I
couldn't connect, but all i found were notices saying the python board
had decided they didn't want any ?  Seems a bit short-sighted if the
main site isn't some kind of fairly bulletproof, diverse/redundant/
intrinsically mirroring setup.


the hatter


From thorsten at thorstenkampe.de  Sat Aug  8 13:00:11 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Sat, 8 Aug 2009 19:00:11 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	<0006746a$0$2895$c3e8da3@news.astraweb.com>
	
	<41a0l6-2u4.ln1@nb2.stroeder.com>
Message-ID: 

* Michael Str?der (Sat, 08 Aug 2009 15:09:23 +0200)
> Thorsten Kampe wrote:
> > * Steven D'Aprano (08 Aug 2009 03:29:43 GMT)
> >> But why assume that the program takes 8 minutes to run? Perhaps it takes 
> >> 8 seconds to run, and 6 seconds of that is the decoding. Then halving 
> >> that reduces the total runtime from 8 seconds to 5, which is a noticeable 
> >> speed increase to the user, and significant if you then run that program 
> >> tens of thousands of times.
> > 
> > Exactly. That's why it doesn't make sense to benchmark decode()/unicode
> > () isolated - meaning out of the context of your actual program.
> 
> Thorsten, the point is you're too arrogant to admit that making such a general
> statement like you did without knowing *anything* about the context is simply
> false.

I made a general statement to a very general question ("These both 
expressions are equivalent but which is faster or should be used for any 
reason?"). If you have specific needs or reasons then you obviously 
failed to provide that specific "context" in your question.
 
> >> By all means, reminding people that pre-mature optimization is a 
> >> waste of time, but it's possible to take that attitude too far to Planet 
> >> Bizarro. At the point that you start insisting, and emphasising, that a 
> >> three second time difference is "*exactly*" zero,
> > 
> > Exactly. Because it was not generated in a real world use case but by 
> > running a simple loop one millions times. Why one million times? Because 
> > by running it "only" one hundred thousand times the difference would 
> > have seen even less relevant.
> 
> I was running it one million times to mitigate influences on the timing by
> other background processes which is a common technique when benchmarking.

Err, no. That is what "repeat" is for and it defaults to 3 ("This means 
that other processes running on the same computer may interfere with the 
timing. The best thing to do when accurate timing is necessary is to 
repeat the timing a few times and use the best time. [...] the default 
of 3 repetitions is probably enough in most cases.")

Three times - not one million times. You choose one million times (for 
the loop) when the thing you're testing is very fast (like decoding) and 
you don't want results in the 0.00000n range. Which is what you asked 
for and what you got.

> > I already gave good advice:
> > 1. don't benchmark
> > 2. don't benchmark until you have an actual performance issue
> > 3. if you benchmark then the whole application and not single commands
> 
> You don't know anything about what I'm doing and what my aim is. So your
> general rules don't apply.

See above. You asked a general question, you got a general answer.
 
> > It's really easy: Michael has working code. With that he can easily 
> > write two versions - one that uses decode() and one that uses unicode().
> 
> Yes, I have working code which was originally written before .decode() being
> added in Python 2.2. Therefore I wondered whether it would be nice for
> readability to replace unicode() by s.decode() since the software does not
> support Python versions prior 2.3 anymore anyway. But one aspect is also
> performance and hence my question and testing.

You haven't done any testing yet. Running decode/unicode one million 
times in a loop is not testing. If you don't believe me then read at 
least Martelli's Optimization chapter in Python in a nutshell (the 
chapter is available via Google books).

Thorsten


From __peter__ at web.de  Sat Aug  8 13:02:09 2009
From: __peter__ at web.de (Peter Otten)
Date: Sat, 08 Aug 2009 19:02:09 +0200
Subject: Need help in refactoring my python script
References: <10d392bc-0a41-4a12-a863-f5fcb296d40c@a37g2000prf.googlegroups.com>
Message-ID: 

n179911 wrote:

> I have a python script which process a file line by line, if the line
> matches a regex, it calls a function to handle it.
> 
> My question is is there a better write to refactor my script. The
> script works, but as it is, i need to keep indent to the right of the
> editor as I add more and more regex for my file.
> 
> Thank you for any idea.
> Now my code end up like this:
> 
> for line in fi.readlines():
> 
>         result= reg1.match(line)
> 
>         if result:
>                 handleReg1(result)
> 
>         else:
>                 result = reg2.match(line)
> 
>                 if result:
>                         handleReg2(result)
>                 else:
>                         result = reg3.match(line)
> 
>                         if result:
>                                 handleReg3(result)
>                         else:
>                                 result = reg4.match(line)
> 
>                                 if result:
>                                         handleReg4(result)
>                                 else:
>                                         result = reg5.match(line)
> 
>                                         if result:
>                                                handleReg5(result)
> 

If the handlers are indeed functions you can put them into a list:

match_handler_pairs = [
    (reg1.match, handleReg1),
    (reg2.match, handleReg2),
    ...
    ]

for line in fi: # look Ma, no readlines()
    for match, handler in match_handler_pairs:
        result = match(line)
        if result:
            handler(result)
            break
        
 Peter



From python at mrabarnett.plus.com  Sat Aug  8 13:09:47 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Sat, 08 Aug 2009 18:09:47 +0100
Subject: Need help in refactoring my python script
In-Reply-To: <10d392bc-0a41-4a12-a863-f5fcb296d40c@a37g2000prf.googlegroups.com>
References: <10d392bc-0a41-4a12-a863-f5fcb296d40c@a37g2000prf.googlegroups.com>
Message-ID: <4A7DB15B.3090804@mrabarnett.plus.com>

n179911 wrote:
> I have a python script which process a file line by line, if the line
> matches a regex, it calls a function to handle it.
> 
> My question is is there a better write to refactor my script. The
> script works, but as it is, i need to keep indent to the right of the
> editor as I add more and more regex for my file.
> 
> Thank you for any idea.
> Now my code end up like this:
> 
> for line in fi.readlines():

This will read all the lines and then iterate through them. You can 
iterate through the file line by line directly with:

     for line in fi:
         ...

> 	result= reg1.match(line)
> 	if result:
> 		handleReg1(result)
> 	else:
> 		result = reg2.match(line)
> 		if result:
> 			handleReg2(result)
> 		else:
> 			result = reg3.match(line)
> 			if result:
> 				handleReg3(result)
> 			else:
> 				result = reg4.match(line)
> 				if result:
> 					handleReg4(result)
> 				else:
> 					result = reg5.match(line)
> 					if result:
>                                                handleReg5(result)

Build a list of the regexes and their functions:

actions = []
actions.append((reg1, handleReg1))
actions.append((reg2, handleReg2))
actions.append((reg3, handleReg3))
actions.append((reg4, handleReg4))
actions.append((reg5, handleReg5))

for line in fi:
     for reg, func in actions:
         result = reg.match(line)
         if result:
             func(result)
             break


From rcdailey at gmail.com  Sat Aug  8 13:12:30 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Sat, 8 Aug 2009 10:12:30 -0700 (PDT)
Subject: Subclass dynamically
Message-ID: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com>

Hey,

I have a class that I want to have a different base class depending on
a parameter that I pass to its __init__method. For example
(pseudocode):

class MyDerived( self.base ):
  def __init__( self, base ):
    self.base = base


Something like that... and then I would do this:

foo = MyDerived( MyBase() )

Note I'm using Python 3.1 on Windows. Thanks in advance.


From gherron at islandtraining.com  Sat Aug  8 13:31:41 2009
From: gherron at islandtraining.com (Gary Herron)
Date: Sat, 08 Aug 2009 10:31:41 -0700
Subject: Subclass dynamically
In-Reply-To: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com>
References: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com>
Message-ID: <4A7DB67D.9070208@islandtraining.com>

Robert Dailey wrote:
> Hey,
>
> I have a class that I want to have a different base class depending on
> a parameter that I pass to its __init__method. For example
> (pseudocode):
>
> class MyDerived( self.base ):
>   def __init__( self, base ):
>     self.base = base
>
>
> Something like that... and then I would do this:
>
> foo = MyDerived( MyBase() )
>
> Note I'm using Python 3.1 on Windows. Thanks in advance.
>   
Python makes it possible to change base classes, but that doesn't mean 
it ever a good idea.

Moreover, the assignment is at the class level, not the instance level:

    MyDerived.__bases__ = (base,) #A tuple of bases

would change the base class for the class MyDerived, and all instances 
past, present, or future.

Better (but still not good) might be a factory function that derives a 
class with the desired base class:

def Derive(base):
    class Derived(base):
        pass
    return Derived

DerivedClass = Derive(MyBase)
foo = DerivedClass(...)

I believe that will produce what you were looking for.

Gary Herron



From zuo at chopin.edu.pl  Sat Aug  8 13:43:30 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Sat, 08 Aug 2009 19:43:30 +0200
Subject: Bug or feature: double strings as one
In-Reply-To: <000674d6$0$2895$c3e8da3@news.astraweb.com>
References: 
	
	
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
Message-ID: 

08-08-2009 Steven D'Aprano  wrote:

> On Fri, 07 Aug 2009 17:35:28 +0000, kj wrote:
>
>> I fail to see why
>>
>> x = ("first part of a very long string "
>>      "second part of a very long string")
>
> That's done by the compiler at compile time and is fast.

Moreover, it's also more readable, when you use str calling its
methods or using formatting on it.

I use it very often, e.g.:

         afunction('quite long string %s quite long string '
                   'quite long string quite long string %s '
                   'quite %s long string quite long string'
                   % (variable1, variable2, variable3))

It seems nicer to me than:

         afunction(('quite long string %s quite long string '
                    + 'quite long string quite long string %s '
                    + 'quite %s long string quite long string')
                   % (variable1, variable2, variable3))

(Note that multiline-'''-strings are usless in such cases).

*j

-- 
Jan Kaliszewski (zuo) 


From python at mrabarnett.plus.com  Sat Aug  8 14:14:40 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Sat, 08 Aug 2009 19:14:40 +0100
Subject: convert non-delimited to delimited
In-Reply-To: <768586.94351.qm@web65602.mail.ac4.yahoo.com>
References: <768586.94351.qm@web65602.mail.ac4.yahoo.com>
Message-ID: <4A7DC090.8020109@mrabarnett.plus.com>

John wrote:
> I am not really a CS person, but I have a task to import a non-delimited 
> text to an access database.  After some research, I *think* the best way 
> to do this is by first converting the non-delimited text to delimited 
> text, and then import it to the database.  Is this the best way to 
> approach this?  Or is there easier way?
>  
[snip]
> 
> I am really stump on where to go from here.  Any help would be 
> appreciated it.  I have also include a text file which gives several 
> more examples.
> 
You'll need to see what types of file the database can import. A brief
search of the web says that it can import tab-separated text files (a
line is a record and the fields are separated by tab characters).

Be sure to test it first before trying it on the real database! :-)


From rami.chowdhury at gmail.com  Sat Aug  8 14:15:20 2009
From: rami.chowdhury at gmail.com (Rami Chowdhury)
Date: Sat, 8 Aug 2009 11:15:20 -0700
Subject: [Diversity] Language note
In-Reply-To: <12470af00908080943g1e559273sdd5e4fc92336a5eb@mail.gmail.com>
References: <20090807143826.GA19246@panix.com>
	<7528bcdd0908070753t7533d6ddw2321a462ed7036e3@mail.gmail.com>
	
	
	<12470af00908080755y717036b2j3d2ac7bf98838fc@mail.gmail.com>
	
	<12470af00908080943g1e559273sdd5e4fc92336a5eb@mail.gmail.com>
Message-ID: 


> Most indian languages have a different
> grammer (compared to English). So i'm curious to see how that would be
> implemented in a parser

+1 -- I'd be interested in seeing this too, although we have drifted  
OT here and perhaps this conversation would be better had on Python- 
list. The closest I've seen to a language being able to support  
different grammatical structures is Perligata (http:// 
www.csse.monash.edu.au/~damian/papers/HTML/Perligata.html), does  
Python have anything similar?

-------------
Rami Chowdhury
"Never assume malice when stupidity will suffice." -- Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)




On Aug 8, 2009, at 09:43 , vid wrote:

> On Sat, Aug 8, 2009 at 21:19, Rami  
> Chowdhury wrote:
>> I suppose the Chinese Python project that Brianna linked to
>> (http://www.chinesepython.org/cgi_bin/cgb.cgi/english/ 
>> english.html) must
>> take Unicode input...
>
> That was interesting but i dont know chinese and IIUC my requirement
> is slightly different -- Most indian languages have a different
> grammer (compared to English). So i'm curious to see how that would be
> implemented in a parser, especially because it brings in a lot more
> ambiguity.
>
> -- 
> thanks
> || vid || http://www.svaksha.com ||
> _______________________________________________
> Diversity mailing list
> Diversity at python.org
> http://mail.python.org/mailman/listinfo/diversity



From martin at v.loewis.de  Sat Aug  8 14:17:37 2009
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Sat, 08 Aug 2009 20:17:37 +0200
Subject: www.python.org website is down?
In-Reply-To: 
References: 
	
	
Message-ID: <4A7DC141.9070207@v.loewis.de>

> This is probably a stupid question, but Is there going to be any data
> loss if it turns out that the disk has died completely? I assume there
> are backups of the repo that are geographically distributed.

Yes, we have backups, and are restoring them at the moment. However,
we still haven't given up on the original disks: they are (probably)
fine; it's just the RAID controller that has failed (and we can't buy a
replacement before Monday).

Regards,
Martin


From kpouya at gmail.com  Sat Aug  8 14:33:57 2009
From: kpouya at gmail.com (Pouya Khankhanian)
Date: Sat, 8 Aug 2009 11:33:57 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
	
	<4A7DC141.9070207@v.loewis.de>
Message-ID: <54581bf3-c9a1-4bbf-945c-28d436ffda2a@k13g2000prh.googlegroups.com>

On Aug 8, 11:17?am, "Martin v. L?wis"  wrote:
> > This is probably a stupid question, but Is there going to be any data
> > loss if it turns out that the disk has died completely? I assume there
> > are backups of the repo that are geographically distributed.
>
> Yes, we have backups, and are restoring them at the moment. However,
> we still haven't given up on the original disks: they are (probably)
> fine; it's just the RAID controller that has failed (and we can't buy a
> replacement before Monday).
>
> Regards,
> Martin

Is there a mirror site to download the latest python installer? Every
mirror I have found on the web redirects me to python.org.
Best
Peter


From sharath20284 at gmail.com  Sat Aug  8 14:49:13 2009
From: sharath20284 at gmail.com (Sharath)
Date: Sat, 8 Aug 2009 11:49:13 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
	
	<4A7DC141.9070207@v.loewis.de>
	<54581bf3-c9a1-4bbf-945c-28d436ffda2a@k13g2000prh.googlegroups.com>
Message-ID: <4cea29ee-cc89-4494-aef9-0f46f8dd11b9@2g2000prl.googlegroups.com>

On Aug 8, 11:33?am, Pouya Khankhanian  wrote:
> On Aug 8, 11:17?am, "Martin v. L?wis"  wrote:
>
> > > This is probably a stupid question, but Is there going to be any data
> > > loss if it turns out that the disk has died completely? I assume there
> > > are backups of the repo that are geographically distributed.
>
> > Yes, we have backups, and are restoring them at the moment. However,
> > we still haven't given up on the original disks: they are (probably)
> > fine; it's just the RAID controller that has failed (and we can't buy a
> > replacement before Monday).
>
> > Regards,
> > Martin
>
> Is there a mirror site to download the latest python installer? Every
> mirror I have found on the web redirects me to python.org.
> Best
> Peter


Python FTP mirror sites also have the same problem. They are not being
mirrored for some require a password. Is there any other way to get a
copy?

Sharath Venkatesha


From no.email at please.post  Sat Aug  8 14:49:28 2009
From: no.email at please.post (kj)
Date: Sat, 8 Aug 2009 18:49:28 +0000 (UTC)
Subject: Why all the __double_underscored_vars__?
References: 
	
	
	
Message-ID: 

In  David Cournapeau  writes:

>On Sat, Aug 8, 2009 at 9:11 PM, kj wrote:
>> In  Chris Rebert p2 at rebertia.com> writes:
>>
>>>The double-underscores indicate that the Python interpreter itself
>>>usually is the caller of the method, and as such some level of "magic"
>>>may be associated with it. Other languages have you do the equivalent
>>>of `def +():` or `def operator +()` to override an operator, the
>>>keyword or symbol serving a similar warning that "here be magic".
>>
>> In this case, then I hope that some of these __items__ get demoted
>> to a more mundane level, so that the notion of "magic" doesn't get
>> trivialized by everyday idioms like:
>>
>> if __name__ =3D=3D '__main__':
>> =C2=A0 =C2=A0# etc
>>
>> There are a few in this category... =C2=A0I figure that they are cases
>> of "atavistic magic".
>>
>> I bring this up because I find it quite difficult to explain to my
>> students (who are complete newcomers to programming) all the
>> __underscored__ stuff that even rank noobs like them have to deal
>> with. =C2=A0(Trust me, to most of them your reply to my post would be
>> as clear as mud.)

>Maybe your students do not need to know about it, at least at the
>beginning ? I heavily use python, and do not use the underscore
>methods so much most of the time, except for __init__,

Believe me, it's not me who's bringing this stuff up: *they*
specifically ask.  That's precisely my point: it is *they* who
somehow feel they can't avoid finding out about this stuff; they
must run into such __arcana__ often enough to cause them to wonder.
If at least some rank beginners (i.e. some of my students) feel
this way, I suggest that some of this alleged __arcana__ should be
demoted to a more mundane everyday status, without the scare-underscores.
E.g. maybe there should be a built-in is_main(), or some such, so
that beginners don't have to venture into the dark underworld of
__name__ and "__main__".

kynn


From kyrie at uh.cu  Sat Aug  8 15:13:04 2009
From: kyrie at uh.cu (Luis Alberto Zarrabeitia Gomez)
Date: Sat, 08 Aug 2009 15:13:04 -0400
Subject: Subclass dynamically
In-Reply-To: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com>
References: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com>
Message-ID: <1249758784.4a7dce40af627@mail.uh.cu>


Quoting Robert Dailey :

> Hey,
> 
> I have a class that I want to have a different base class depending on
> a parameter that I pass to its __init__method. For example
> (pseudocode):

1- Are you sure that you want that behavior? Given that in python, a class is
just a particular case of invocable object, you could just write a function
instead, and the code may be more robust.

2- If you are /sure/ that is the behavior you want, take a look at the __new__
method. The __new__ can decide which instance to return (you could even define a
new class inside of it, instantiate it, and return the instance).

3- You may want to take a look at metaclasses. But without more details about
why you want it, I can't give you more precise answers.

Regards,

-- 
Luis Zarrabeitia
Facultad de Matem?tica y Computaci?n, UH
http://profesores.matcom.uh.cu/~kyrie



-- 
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba 
http://www.universidad2010.cu



From breamoreboy at yahoo.co.uk  Sat Aug  8 15:27:49 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 08 Aug 2009 20:27:49 +0100
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>		<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>			<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
Message-ID: 

Kee Nethery wrote:
> As someone trying to learn the language I want to say that the tone on 
> this list towards people who are trying to learn Python  feels like it 
> has become anti-newbies.
> 
[snip]
> 
> Kee Nethery
My gut feeling (which could of course be wrong) is that many hard core 
Pythonistas are cheesed off with newbies who refuse to help themselves.
No evidence that that they've tried any Python tutorial.  No evidence 
that that they've searched anywhere in an attempt to resolve the problem 
before posting.  "This code doesn't work, please fix it".  Response 
often "Please post your actual code, or a snippet that gives the same 
exception, and give the complete exception details".

Show that you have made an attempt to help yourself, and the response 
here is almost certainly 100% helpful.

Further, I have seen many requests here which are nothing really to do 
with Python, say a query about which algorithm to use.  Response "Not 
really a Python question, but try ...".  Put the same question on (say) 
the C ng and you'd be told in no uncertain terms to Foxtrot Oscar.

-- 
Kindest regards.

Mark Lawrence.



From http  Sat Aug  8 15:37:01 2009
From: http (Paul Rubin)
Date: 08 Aug 2009 12:37:01 -0700
Subject: unique-ifying a list
References: 
	
Message-ID: <7x8whum71e.fsf@ruckus.brouhaha.com>

Dennis Lee Bieber  writes:
> 	Why bother with	seen	?

The version with seen runs in linear time because of the O(1) set
lookup.  Your version runs in quadratic time.


From contact at xavierho.com  Sat Aug  8 16:35:42 2009
From: contact at xavierho.com (Xavier Ho)
Date: Sun, 9 Aug 2009 06:35:42 +1000
Subject: www.python.org website is down?
In-Reply-To: <4cea29ee-cc89-4494-aef9-0f46f8dd11b9@2g2000prl.googlegroups.com>
References: 
	
	
	<4A7DC141.9070207@v.loewis.de>
	<54581bf3-c9a1-4bbf-945c-28d436ffda2a@k13g2000prh.googlegroups.com>
	<4cea29ee-cc89-4494-aef9-0f46f8dd11b9@2g2000prl.googlegroups.com>
Message-ID: <2d56febf0908081335r23a03895i16bf3b5551a7823a@mail.gmail.com>

Well, it's back up now.

At least for me. ;)

Ching-Yun "Xavier" Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: contact at xavierho.com
Website: http://xavierho.com/


On Sun, Aug 9, 2009 at 4:49 AM, Sharath  wrote:

> On Aug 8, 11:33 am, Pouya Khankhanian  wrote:
> > On Aug 8, 11:17 am, "Martin v. L?wis"  wrote:
> >
> > > > This is probably a stupid question, but Is there going to be any data
> > > > loss if it turns out that the disk has died completely? I assume
> there
> > > > are backups of the repo that are geographically distributed.
> >
> > > Yes, we have backups, and are restoring them at the moment. However,
> > > we still haven't given up on the original disks: they are (probably)
> > > fine; it's just the RAID controller that has failed (and we can't buy a
> > > replacement before Monday).
> >
> > > Regards,
> > > Martin
> >
> > Is there a mirror site to download the latest python installer? Every
> > mirror I have found on the web redirects me to python.org.
> > Best
> > Peter
>
>
> Python FTP mirror sites also have the same problem. They are not being
> mirrored for some require a password. Is there any other way to get a
> copy?
>
> Sharath Venkatesha
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From aahz at pythoncraft.com  Sat Aug  8 16:37:21 2009
From: aahz at pythoncraft.com (Aahz)
Date: 8 Aug 2009 13:37:21 -0700
Subject: python.org downtime (was Re: is it possible to overload operator "^"?)
References: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
	<7e4tg5F2eirarU1@mid.uni-berlin.de>
	
Message-ID: 

In article ,
dmitrey   wrote:
>
>To Diez:
>yes, but I haven't paid attention to xor. BTW the url is currently
>unavailable (Network Timeout. The server at docs.python.org is taking
>too long to respond.).

www.python.org is currently having hardware problems
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz


From clp2 at rebertia.com  Sat Aug  8 16:41:42 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Sat, 8 Aug 2009 16:41:42 -0400
Subject: Serial port access
In-Reply-To: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
References: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
Message-ID: <50697b2c0908081341o63636f36i99b5971fdb0bbb57@mail.gmail.com>

On Sat, Aug 8, 2009 at 12:34 PM, nipun batra wrote:
> Hi,
> How can we access serial port using usb-serial converters,using python in
> linux.

PySerial might also be an option:
http://pyserial.sourceforge.net/index.html

Cheers,
Chris
-- 
http://blog.rebertia.com


From contact at xavierho.com  Sat Aug  8 16:44:09 2009
From: contact at xavierho.com (Xavier Ho)
Date: Sun, 9 Aug 2009 06:44:09 +1000
Subject: python.org downtime (was Re: is it possible to overload operator 
	"^"?)
In-Reply-To: 
References: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
	<7e4tg5F2eirarU1@mid.uni-berlin.de>
	
	
Message-ID: <2d56febf0908081344n10fb56eo1fe108cbb824901f@mail.gmail.com>

On Sun, Aug 9, 2009 at 6:37 AM, Aahz  wrote:

> www.python.org is currently having hardware problems
>

So what I'm seeing is an illusion? It works as of now.

- Xavier
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From Scott.Daniels at Acm.Org  Sat Aug  8 17:50:32 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Sat, 08 Aug 2009 14:50:32 -0700
Subject: Why all the __double_underscored_vars__?
In-Reply-To: 
References: 
	
	
	
	
Message-ID: 

kj wrote:
>>> ... I find it quite difficult to explain to my
>>> students (who are complete newcomers to programming) all the
>>> __underscored__ stuff that even rank noobs like them have to deal
>>> with. =C2=A0(Trust me, to most of them your reply to my post would be
>>> as clear as mud.)
> Believe me, it's not me who's bringing this stuff up: *they*
> specifically ask.  That's precisely my point: it is *they* who
> somehow feel they can't avoid finding out about this stuff; they
> must run into such __arcana__ often enough to cause them to wonder.
> If at least some rank beginners (i.e. some of my students) feel
> this way, I suggest that some of this alleged __arcana__ should be
> demoted to a more mundane everyday status, without the scare-underscores.
> E.g. maybe there should be a built-in is_main(), or some such, so
> that beginners don't have to venture into the dark underworld of
> __name__ and "__main__".

Do you know about Kirby Urner's technique of calling such symbols,
"ribs," -- the access to the "stuff" Python is built from?  One nice
thing about Python is that you can experiment with what these
"__ribs__" do without having to learn yet another language.

It seems nice to me that you can use a rule that says, "stick to
normal names and you don't have to worry about mucking with the
way Python itself works, but if you are curious, looks for those
things and fiddle with them."

--Scott David Daniels
Scott.Daniels at Acm.Org


From kpouya at gmail.com  Sat Aug  8 17:50:34 2009
From: kpouya at gmail.com (Pouya Khankhanian)
Date: Sat, 8 Aug 2009 14:50:34 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
	
	<4A7DC141.9070207@v.loewis.de>
	<54581bf3-c9a1-4bbf-945c-28d436ffda2a@k13g2000prh.googlegroups.com>
	<4cea29ee-cc89-4494-aef9-0f46f8dd11b9@2g2000prl.googlegroups.com>
Message-ID: <80c46b94-9df2-43f5-9182-37c2413db783@b25g2000prb.googlegroups.com>

On Aug 8, 11:49?am, Sharath  wrote:
> On Aug 8, 11:33?am, Pouya Khankhanian  wrote:
>
>
>
> > On Aug 8, 11:17?am, "Martin v. L?wis"  wrote:
>
> > > > This is probably a stupid question, but Is there going to be any data
> > > > loss if it turns out that the disk has died completely? I assume there
> > > > are backups of the repo that are geographically distributed.
>
> > > Yes, we have backups, and are restoring them at the moment. However,
> > > we still haven't given up on the original disks: they are (probably)
> > > fine; it's just the RAID controller that has failed (and we can't buy a
> > > replacement before Monday).
>
> > > Regards,
> > > Martin
>
> > Is there a mirror site to download the latest python installer? Every
> > mirror I have found on the web redirects me to python.org.
> > Best
> > Peter
>
> Python FTP mirror sites also have the same problem. They are not being
> mirrored for some require a password. Is there any other way to get a
> copy?
>
> Sharath Venkatesha

Website is back up! Thanks for all the hard work


From efotinis at y  Sat Aug  8 18:05:01 2009
From: efotinis at y (Elias Fotinis (eliasf))
Date: Sun, 9 Aug 2009 01:05:01 +0300
Subject: Pywin32 @ windows 7
In-Reply-To: 
References: <004a01ca1733$a9768c10$4605a8c0@btsc1><1249724885.215365@athprx03>
	
Message-ID: <1249769137.332546@athprx03>

"Dennis Lee Bieber" wrote:
> Has it been built under a 64-bit OS though? (I'll confess I've not
> looked -- I always install the ActiveState binary for my WinXP (32bit)
> system, and that library is part of the install)

Yes, both Python x64 and pywin32 x64 are native 64-bit applications -- they 
can't even be installed on a 32-bit system. 



From pavlovevidence at gmail.com  Sat Aug  8 18:39:16 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sat, 8 Aug 2009 15:39:16 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
Message-ID: <47b58ea9-d199-41f7-8d7b-8de382f85396@m7g2000prd.googlegroups.com>

On Aug 6, 11:36?am, Kee Nethery  wrote:
> As someone trying to learn the language I want to say that the tone on ?
> this list towards people who are trying to learn Python ?feels like it ?
> has become anti-newbies.

I don't think this NG is anti-newbie so much as anti-whining-loser.

Unfortunately, some newbies might see this and perceive it to be abuse
of newbies in general.  It is not so.  People who have chips on their
shoulder, who make loaded, emotionally-provocative comments, who make
no effort on their own, who expect us to do their homework and/or job
for them, etc., there are the people who going to get an unfavorable
tone.

Newbies who ask respectable questions without having an attitude will
generally get respectable answers.


> For example, the guy who was looking for Python sample code for the ?
> Google Map API, calling him a troll was harsh.

No it wasn't, that guy is Xah Lee, a person who's been trolling Usenet
for a long time.  He is best ignored, but I don't blame someone for
snapping at him.


Carl Banks


From pavlovevidence at gmail.com  Sat Aug  8 19:10:20 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sat, 8 Aug 2009 16:10:20 -0700 (PDT)
Subject: Subclass dynamically
References: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com>
	
Message-ID: <478f321d-3d88-4074-af17-1bc3d509e6b3@x25g2000prf.googlegroups.com>

On Aug 8, 12:13?pm, Luis Alberto Zarrabeitia Gomez 
wrote:
> Quoting Robert Dailey :
>
> > Hey,
>
> > I have a class that I want to have a different base class depending on
> > a parameter that I pass to its __init__method. For example
> > (pseudocode):
>
> 1- Are you sure that you want that behavior? Given that in python, a class is
> just a particular case of invocable object, you could just write a function
> instead, and the code may be more robust.
>
> 2- If you are /sure/ that is the behavior you want, take a look at the __new__
> method. The __new__ can decide which instance to return (you could even define a
> new class inside of it, instantiate it, and return the instance).
>
> 3- You may want to take a look at metaclasses. But without more details about
> why you want it, I can't give you more precise answers.

One could accomplish this using methods 2 and 3, but it would go
against so many common expectations I have to recommend never doing
it.  If you call a type, it should return an object of that type (or,
at worst, a subtype or "null" type) or raise an exception.

The factory function is the way to do this.

Another alternative is to forego inheritance and simply call method on
the passed "base" object.  Given that the OP posted code that almost
literally works in that case, this might be the best way to go for his
case.

So instead of this hypothetical code:

class MyDerived(self.base):
    def __init__(self,base)
        self.base = base
    # MyDerived inherits a_method() from self.base

He could go with this real code:

class MyClass(object):
    def __init__(self,base)
        self.base = base
    def a_method(self):
        return self.base.a_method()

where, instead of inheriting self.base's a_method, it simply defines
a_method() to call self.base.a_method() directly.


Carl Banks


From michael at stroeder.com  Sat Aug  8 19:42:14 2009
From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=)
Date: Sun, 09 Aug 2009 01:42:14 +0200
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 		<2qcrk6-doj.ln1@nb2.stroeder.com>
	
Message-ID: 

Michael F?tsch wrote:
> If speed is your primary concern, this will give you even better
> performance than unicode():
> 
>   decoder = codecs.lookup("utf-8").decode
>   for i in xrange(1000000):
>       decoder("???????")[0]

Hmm, that could be interesting. I will give it a try.

> However, there's also a functional difference between unicode() and
> str.decode():
> 
> unicode() always raises an exception when you try to decode a unicode
> object. str.decode() will first try to encode a unicode object using the
> default encoding (usually "ascii"), which might or might not work.

Thanks for pointing that out. So in my case I'd consider that also a plus for
using unicode().

Ciao, Michael.


From BrianVanderburg2 at aim.com  Sat Aug  8 21:08:38 2009
From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II)
Date: Sat, 08 Aug 2009 21:08:38 -0400
Subject: How to do relpath implementation on 2.5
Message-ID: <4A7E2196.2080403@aim.com>

I've coded my own 'relpath' implementation for 2.5 (shown below) and I 
want to make sure it follows as closely as it should to 2.6 and later.  
I've got a question regarding that.  When attempting to convert to a 
relative path and it is not possible for some reason (different drive or 
UNC share), should that be an error or should it return the absolute 
path of the target?  I'm using Debian so I don't have 2.6 available 
right now for testing.

This is what I've got so far

import os
from os import path


def relpath(target, origin=os.curdir):
    """
    Determine relative path of target to origin or
    """

    target = path.normcase(path.abspath(path.normpath(target)))
    origin = path.normcase(path.abspath(path.normpath(origin)))

    # Same?
    if target == origin:
        return '.'

    original_target = target

    # Check drive (for Windows)
    (tdrive, target) = path.splitdrive(target)
    (odrive, origin) = path.splitdrive(origin)
    if tdrive != odrive:
        return original_target

    # Check UNC path (for Windows)
    # If they are on different shares, we want an absolute path
    if not tdrive and not odrive and hasattr(path, 'splitunc'):
        (tunc, target) = path.splitunc(target)
        (ounc, origin) = path.splitunc(origin)
        if tunc != ounc:
            return original_target

    # Split into lists
    target_list = target.split(os.sep)
    origin_list = origin.split(os.sep)

    # Remove beginning empty parts
    # Helps to handle when one item may be in the root
    while target_list and not target_list[0]:
        del target_list[0]
    while origin_list and not origin_list[0]:
        del origin_list[0]

    # Remove common items
    while origin_list and target_list:
        if origin_list[0] == target_list[0]:
            del origin_list[0]
            del target_list[0]
        else:
            break

    # Combine and return the result
    relative_list = [os.pardir] * len(origin_list) + target_list
    if not relative_list:
        return os.curdir
    return os.sep.join(relative_list)


Currently I just return the target if it can not be made relative.

Brian A. Vanderburg II


From nipunreddevil at gmail.com  Sat Aug  8 21:20:12 2009
From: nipunreddevil at gmail.com (nipun batra)
Date: Sun, 9 Aug 2009 06:50:12 +0530
Subject: Serial port access
In-Reply-To: <50697b2c0908081341o63636f36i99b5971fdb0bbb57@mail.gmail.com>
References: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
	<50697b2c0908081341o63636f36i99b5971fdb0bbb57@mail.gmail.com>
Message-ID: <1e61b3260908081820r702a4e24s6599fa724c97344a@mail.gmail.com>

On Sun, Aug 9, 2009 at 2:11 AM, Chris Rebert  wrote:

> On Sat, Aug 8, 2009 at 12:34 PM, nipun batra
> wrote:
> > Hi,
> > How can we access serial port using usb-serial converters,using python in
> > linux.
>
> PySerial might also be an option:
> http://pyserial.sourceforge.net/index.html
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>


pySerial mentions about serial ports but not about usb-serial.Can i do
something like convert my usb-serial to act as serial port and then use
pySerial
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From thudfoo at opensuse.us  Sat Aug  8 21:41:23 2009
From: thudfoo at opensuse.us (member thudfoo)
Date: Sat, 8 Aug 2009 18:41:23 -0700
Subject: Is "feedparser" deprecated?
In-Reply-To: 
References: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
	
Message-ID: <3d881a310908081841x17235cf1rd38418b119dd7b4d@mail.gmail.com>

On Fri, Aug 7, 2009 at 6:10 PM, Gabriel Genellina wrote:

> En Fri, 07 Aug 2009 16:07:48 -0300, John Nagle 
> escribi?:
>
>    Feedparser requires SGMLlib, which has been removed from Python 3.0.
>> Feedparser hasn't been updated since 2007. Does this mean Feedparser
>> is dead?
>>
>
> Since we have generic and easy of use XML parsers like ElementTree and
> lxml,  specialized rss parsers like feedparser are not so much required.
> I've used ElementTree when I had to parse an rss feed in the past (not so
> many times).
>
> --
> Gabriel Genellina
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

feedparser is much more than than an just  another xml
 parser.

Read its documetion.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From zac256 at gmail.com  Sat Aug  8 21:52:17 2009
From: zac256 at gmail.com (Zac Burns)
Date: Sat, 8 Aug 2009 18:52:17 -0700
Subject: Why all the __double_underscored_vars__?
In-Reply-To: 
References: 
	
	
	
	
	
Message-ID: <333edbe80908081852i4fd753er5656216cbb1b06e2@mail.gmail.com>

As I understand it, the double underscores is to create a namespace
"reserved for python's internal use". That way python can add more
variables and methods in the future and as long as people respect the
namespace their code will not break with future revisions.

--
Zachary Burns
(407)590-4814
Aim - Zac256FL
Production Engineer (Digital Overlord)
Zindagi Games


From dstanek at dstanek.com  Sat Aug  8 23:15:36 2009
From: dstanek at dstanek.com (David Stanek)
Date: Sat, 8 Aug 2009 23:15:36 -0400
Subject: Is "feedparser" deprecated?
In-Reply-To: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
References: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
Message-ID: 

On Fri, Aug 7, 2009 at 3:07 PM, John Nagle wrote:
> ?Feedparser requires SGMLlib, which has been removed from Python 3.0.
> Feedparser hasn't been updated since 2007. Does this mean Feedparser
> is dead?
>

The release is from 2007, but there are several recent commits.

http://code.google.com/p/feedparser/source/list


-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek


From michaelmossey at gmail.com  Sun Aug  9 00:43:32 2009
From: michaelmossey at gmail.com (Michael Mossey)
Date: Sat, 8 Aug 2009 21:43:32 -0700 (PDT)
Subject: help with threads
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
	<949b87d5-8cff-444a-b6ba-23d49610d130@p36g2000vbn.googlegroups.com> 
	 
	
Message-ID: 

On Aug 7, 5:03?pm, Piet van Oostrum  wrote:
> >>>>> Michael Mossey  (MM) wrote:
> >MM> Ah yes, that explains it. Some of these long computations are done in
> >MM> pure C, so I'm sure the GIL is not being released.
>
> Is that C code under your own control? Or at least the glue from Python
> to C? In that case, and if the C code is not manipulating Python objects
> or something in the Python interpreter, it could be changed to release
> the GIL during the computation. That's also how Numpy does it, IIRC.
> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: p... at vanoostrum.org

I don't have any control over this code, and it's easier to solve my
problem in other ways. I just put a sleep() call between calls to the
C library, and that gives the network thread enough responsiveness for
my particular task. I am grateful, anyway, to understand why this kind
of thing happens.


From martin at v.loewis.de  Sun Aug  9 00:49:08 2009
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Sun, 09 Aug 2009 06:49:08 +0200
Subject: .h files?
In-Reply-To: <50c453d9-d455-4f08-959c-e225149495fb@i18g2000pro.googlegroups.com>
References: <50c453d9-d455-4f08-959c-e225149495fb@i18g2000pro.googlegroups.com>
Message-ID: <4a7e5544$0$2550$9b622d9e@news.freenet.de>

> Question.  Seems that with python distributions you have the option to
> include either "external facing, public" *.h files, and make them
> available, or include the whole kit and kaboodle [all *.h files].

What python distributions are you referring to? The ones I know don't
make this distinction; there is only a single set of header files that
you can choose to install.

Regards,
Martin


From nipunreddevil at gmail.com  Sun Aug  9 00:51:20 2009
From: nipunreddevil at gmail.com (nipun batra)
Date: Sun, 9 Aug 2009 10:21:20 +0530
Subject: Serial port access
In-Reply-To: <1e61b3260908081820r702a4e24s6599fa724c97344a@mail.gmail.com>
References: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
	<50697b2c0908081341o63636f36i99b5971fdb0bbb57@mail.gmail.com>
	<1e61b3260908081820r702a4e24s6599fa724c97344a@mail.gmail.com>
Message-ID: <1e61b3260908082151l1fed2afena6db9bc239da5c6a@mail.gmail.com>

Ok i managed to comunicate serially using pySerial,but only using Idle. but
when i use it within Geany or Gedit,i get following errors
Traceback most recent call last
File "serial.py",line 3,in module
import serial
File"/home/nipun/serial.py",line 5,in module
ser=serial.Serial()
Attribute error:module object has no attribute Serial

how can i make it work?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From wuwei23 at gmail.com  Sun Aug  9 01:16:53 2009
From: wuwei23 at gmail.com (alex23)
Date: Sat, 8 Aug 2009 22:16:53 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com> 
	<7xd476rj1s.fsf@ruckus.brouhaha.com>
Message-ID: 

Paul Rubin  wrote:
> Stephen, Alex, etc.: have you actually used the php.net doc system?
> Don't knock it til you've tried it. ?IMO it is superior to Python's
> system. ?

I've tried it, a lot. Is it okay for me to keep criticising it now, or
would you like some time to find some other allusion to ignorance with
which to wave away my opinion?


From kwatch at gmail.com  Sun Aug  9 01:37:03 2009
From: kwatch at gmail.com (kwatch)
Date: Sat, 8 Aug 2009 22:37:03 -0700 (PDT)
Subject: [ANN] pyKook 0.0.3 - a smart build tool similar to Make, Rake, or Ant
Message-ID: <06fbfe63-2ee2-4669-91cc-2df12ea4bd86@i4g2000prm.googlegroups.com>

Hi,

I have released pyKook 0.0.3.
http://pypi.python.org/pypi/Kook/0.0.3
http://www.kuwata-lab.com/kook/
http://www.kuwata-lab.com/kook/pykook-users-guide.html

In this release, recipe syntax is changed (see below).


Overview
========

pyKook is a smart build tool similar to Make, Rake, Ant, or Cook.
pyKook regards software project as cooking.
Terms used in pyKook are cooking terms.
For example:

    cookbook    -  Makefile
    product     -  target file
    ingredient  -  source file
    recipe      -  how to create target from source
    spices      -  command-line options for recipe


Cookbook (= Makefile) is written in pure Python.
You can write any statements or expressions in cookbook.

NOTICE: pyKook is under alpha release. Spec and features may be
changed
in the future without previous announcement.


Example
=======

Example of cookbook (Kookbook.py):

    --------------------------------------------------
    ##
    ## properties
    ##
    cc     = prop('cc',     'gcc')
    cflags = prop('cflags', '-g -Wall')


    ##
    ## recipes
    ##
    @recipe
    @ingreds("hello")
    def all(c):        # or task_all(c)
        pass

    @recipe
    @product("hello")
    @ingreds("hello.o")
    def file_command(c):
        """generates hello command"""
        system(c%"$(cc) $(cflags) -o $(product) $(ingred)")

    @recipe
    @product("*.o")
    @ingreds("$(1).c", if_exists("$(1).h"))
    def file_ext_o(c):
        """compile '*.c' and '*.h'"""
        system(c%"$(cc) $(cflags) -c $(1).c")

    @recipe
    def clean(c):
        rm_f("*.o")
    --------------------------------------------------


Exampe of result:

    --------------------------------------------------
    bash> ls
    Kookbook.py   hello.c    hello.h

    bash> pykook -l
    Properties:
      cc                  : 'gcc'
      cflags              : '-g -Wall'

    Task recipes:
      all                 : cook all products
      clean               : remove by-products

    File recipes:
      hello               : generates hello command
      *.o                 : compile '*.c' and '*.h'

    (Tips: you can set 'kook_default_product' variable in your
kookbook.)

    bash> pykook all           # or, pykook --cc=gcc4 all
    ### *** hello.o (func=file_ext_o)
    $ gcc -g -Wall -c hello.c
    ### ** hello (func=file_command)
    $ gcc -g -Wall -o hello hello.o
    ### * all (func=task_all)
    --------------------------------------------------


See users-guide for more details.
http://www.kuwata-lab.com/kook/pykook-users-guide.html


Enhancements, Changes, Bug fixes sice 0.0.2
===========================================


Changes
-------

  - IMPORTANT!!
    New '@recipe' decorator is required for each recipe function.
    If function is decorated by '@recipe', 'task_' prefix is not
necessary.

    ex:
      ## previous version
  	  def task_clean(c):    # 'task_' prefix is required
  	    rm_rf("*.o")

      ## since this release
  	  @release              # @release decorator is required
  	  def clean(c):         # 'task_' prefix is not necessary
  	    rm_rf("*.o")

    See http://www.kuwata-lab.com/kook/pykook-users-guide.html#cookbook-recipekind
  	for details.

  - Library codes are much refactored.


Enhancements
------------

  - IMPORTANT!!
    New feature to support command-line script framework.
    You can convert Kookbook.py into command-line script.
	See http://www.kuwata-lab.com/kook/pykook-users-guide.html#topic-framework
	for details.

  - New command-line option '-n' (no exec) supported.
    If you specify '-n', commands such as 'cp()' or 'rm()' are not
executed.
	In other words, '-n' means 'dry-run'.

  - Add a lot of test scripts.


Bug fixes
---------

  - A bug related timestamp detection is now fixed.
    There was a case that product file was not updated even when
    ingredient files were updated.

  - A bug about recipe tree is fixed. There was a case that the same
recipe
    can be invoke more than once when an intermediate recipe was
required
    from several recipes.



Have fun!

--
regards,
makoto kuwata


From rylesny at gmail.com  Sun Aug  9 03:49:42 2009
From: rylesny at gmail.com (ryles)
Date: Sun, 9 Aug 2009 00:49:42 -0700 (PDT)
Subject: How to do relpath implementation on 2.5
References: 
Message-ID: 

On Aug 8, 9:08?pm, Brian Allen Vanderburg II
 wrote:
> I've coded my own 'relpath' implementation for 2.5 (shown below) and I
> want to make sure it follows as closely as it should to 2.6 and later. ?
> I've got a question regarding that. ?When attempting to convert to a
> relative path and it is not possible for some reason (different drive or
> UNC share), should that be an error or should it return the absolute
> path of the target? ?I'm using Debian so I don't have 2.6 available
> right now for testing.

Usually Python source code is easily browsed at:

http://svn.python.org/view/

Unfortunately the server is down right now.

The implementation in 2.6 raises a ValueError exception. Here is the
function from ntpath.py:

def relpath(path, start=curdir):
    """Return a relative version of a path"""

    if not path:
        raise ValueError("no path specified")
    start_list = abspath(start).split(sep)
    path_list = abspath(path).split(sep)
    if start_list[0].lower() != path_list[0].lower():
        unc_path, rest = splitunc(path)
        unc_start, rest = splitunc(start)
        if bool(unc_path) ^ bool(unc_start):
            raise ValueError("Cannot mix UNC and non-UNC paths (%s and
%s)"
                                                                %
(path, start))
        else:
            raise ValueError("path is on drive %s, start on drive %s"
                                                % (path_list[0],
start_list[0]))
    # Work out how much of the filepath is shared by start and path.
    for i in range(min(len(start_list), len(path_list))):
        if start_list[i].lower() != path_list[i].lower():
            break
    else:
        i += 1

    rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
    if not rel_list:
        return curdir
    return join(*rel_list)


From asmodai at in-nomine.org  Sun Aug  9 04:41:11 2009
From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven)
Date: Sun, 9 Aug 2009 10:41:11 +0200
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	
	
Message-ID: <20090809084111.GB30241@nexus.in-nomine.org>

-On [20090808 20:07], Thorsten Kampe (thorsten at thorstenkampe.de) wrote:
>In real life people won't even notice whether an application takes one or
>two minutes to complete.

I think you are quite wrong here.

I have worked with optical engineers who needed to calculate grating numbers
for their lenses. If they can have a calculation program that runs in 1
minute instead of 2 they can effectively double their output during the day
(since they run calculations hundreds to thousand times a day to get the
most optimal results with minor tweaks).

I think you are being a bit too easy on hand waving here that mere minute
runtimes are not noticeable.

-- 
Jeroen Ruigrok van der Werven  / asmodai
????? ?????? ??? ?? ??????
http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B
When we have not what we like, we must like what we have...


From steve at REMOVE-THIS-cybersource.com.au  Sun Aug  9 04:48:16 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 09 Aug 2009 08:48:16 GMT
Subject: Why all the __double_underscored_vars__?
References: 
	
	
Message-ID: <00081096$0$2954$c3e8da3@news.astraweb.com>

On Sat, 08 Aug 2009 12:11:19 +0000, kj wrote:

> In  Chris Rebert
>  writes:
> 
>>The double-underscores indicate that the Python interpreter itself
>>usually is the caller of the method, and as such some level of "magic"
>>may be associated with it. Other languages have you do the equivalent of
>>`def +():` or `def operator +()` to override an operator, the keyword or
>>symbol serving a similar warning that "here be magic".
> 
> In this case, then I hope that some of these __items__ get demoted to a
> more mundane level, so that the notion of "magic" doesn't get
> trivialized by everyday idioms like:
> 
> if __name__ == '__main__':
>     # etc

But that is magic, and just because it's magic doesn't mean it's not 
useful every day.

I don't see what's so difficult about telling your students that double 
underscore names have special meaning to the Python interpreter. That 
doesn't mean you're forbidden from using them, or that you have to use 
them, it just means that they have a special meaning to the interpreter, 
and you usually don't call them directly.



-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Sun Aug  9 05:07:31 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 09 Aug 2009 09:07:31 GMT
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	
Message-ID: <00081519$0$2954$c3e8da3@news.astraweb.com>

On Sat, 08 Aug 2009 20:27:49 +0100, Mark Lawrence wrote:

> Further, I have seen many requests here which are nothing really to do
> with Python, say a query about which algorithm to use.  Response "Not
> really a Python question, but try ...".  Put the same question on (say)
> the C ng and you'd be told in no uncertain terms to Foxtrot Oscar.

We're a lot friendlier than the C newsgroup.

Personally, I think knowing the right algorithm to use is as much a part 
of Python programming as knowing whether to call mystring.upper() or 
string.upper(mystring).


-- 
Steven


From mh at pixar.com  Sun Aug  9 05:37:52 2009
From: mh at pixar.com (mh at pixar.com)
Date: 09 Aug 2009 09:37:52 GMT
Subject: tracing openurl input and output?
Message-ID: <4a7e98f0$0$9288$386e9d2@news.usenetserver.com>

How can I watch the messages being sent back and for on urllib shttp
requests?  If it were simple http I would just watch the socket traffic
but of course that won't work for https.  Is there a debug flag I can
set that will do this?

context:  I am dealing with a web service bug and I want to tell
the provider exactly what is going back and forth to his server,
eliminating the "maybe there's a bug in your library" chat.

    import urllib
    params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
    f = urllib.urlopen("https://example.com/cgi-bin/query", params)

Many TIA!

-- 
Mark Harrison
Pixar Animation Studios


From steve at REMOVE-THIS-cybersource.com.au  Sun Aug  9 06:01:25 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 09 Aug 2009 10:01:25 GMT
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	<0006746a$0$2895$c3e8da3@news.astraweb.com>
	
	<41a0l6-2u4.ln1@nb2.stroeder.com>
	
Message-ID: <000821ba$0$2954$c3e8da3@news.astraweb.com>

On Sat, 08 Aug 2009 19:00:11 +0200, Thorsten Kampe wrote:

>> I was running it one million times to mitigate influences on the timing
>> by other background processes which is a common technique when
>> benchmarking.
> 
> Err, no. That is what "repeat" is for and it defaults to 3 ("This means
> that other processes running on the same computer may interfere with the
> timing. The best thing to do when accurate timing is necessary is to
> repeat the timing a few times and use the best time. [...] the default
> of 3 repetitions is probably enough in most cases.")


It's useful to look at the timeit module to see what the author(s) think.

Let's start with the repeat() method. In the Timer docstring:

"The repeat() method is a convenience to call timeit() multiple times and 
return a list of results."

and the repeat() method's own docstring:

"This is a convenience function that calls the timeit() repeatedly, 
returning a list of results.  The first argument specifies how many times 
to call timeit(), defaulting to 3; the second argument specifies the 
timer argument, defaulting to one million."

So it's quite obvious that the module author(s), and possibly even Tim 
Peters himself, consider repeat() to be a mere convenience method. 
There's nothing you can do with repeat() that can't be done with the 
timeit() method itself.

Notice that both repeat() and timeit() methods take an argument to 
specify how many times to execute the code snippet. Why not just execute 
it once? The module doesn't say, but the answer is a basic measurement 
technique: if your clock is accurate to (say) a millisecond, and you 
measure a single event as taking a millisecond, then your relative error 
is roughly 100%. But if you time 1000 events, and measure the total time 
as 1 second, the relative error is now 0.1%.

The authors of the timeit module obvious considered this an important 
factor: not only did they allow you to specify the number of times to 
execute the code snippet (defaulting to one million, not to one) but they 
had this to say:

[quote]
Command line usage:
    python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement]

Options:
  -n/--number N: how many times to execute 'statement'
 [...]

If -n is not given, a suitable number of loops is calculated by trying
successive powers of 10 until the total time is at least 0.2 seconds.
[end quote]

In other words, when calling the timeit module from the command line, by 
default it will choose a value for n that gives a sufficiently small 
relative error.

It's not an accident that timeit gives you two "count" parameters: the 
number of times to execute the code snippet per timing, and the number of 
timings. They control (partly) for different sources of error.



-- 
Steven


From duncan.booth at invalid.invalid  Sun Aug  9 06:47:15 2009
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 9 Aug 2009 10:47:15 GMT
Subject: tracing openurl input and output?
References: <4a7e98f0$0$9288$386e9d2@news.usenetserver.com>
Message-ID: 

mh at pixar.com wrote:

> How can I watch the messages being sent back and for on urllib shttp
> requests?  If it were simple http I would just watch the socket traffic
> but of course that won't work for https.  Is there a debug flag I can
> set that will do this?
> 
> context:  I am dealing with a web service bug and I want to tell
> the provider exactly what is going back and forth to his server,
> eliminating the "maybe there's a bug in your library" chat.
> 
>     import urllib
>     params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>     f = urllib.urlopen("https://example.com/cgi-bin/query", params)
> 
> Many TIA!
> 
If you are running on Windows then I'd say get hold of a copy of fiddler2 
(http://www.fiddler2.com/fiddler2/) and tell your code to use it as a 
proxy. It does an excellent job of capturing and decoding web traffic and 
even lets you modify packets as they go past. The only thing to watch for 
with https is that your code will see an invalid certificate as of course 
it sees fiddler's own self signed certificate instead of the original.

I'm not sure what Linux or Mac equivalents there might be (though in a 
pinch you can always run your code on one system and Fiddler on a different 
one).


From nipunreddevil at gmail.com  Sun Aug  9 07:03:04 2009
From: nipunreddevil at gmail.com (nipun batra)
Date: Sun, 9 Aug 2009 16:33:04 +0530
Subject: String algo
Message-ID: <1e61b3260908090403o1b6c5a66w7c59a2bd29e193a1@mail.gmail.com>

I will be receiving data serially from another pc,.i can use any sort of
marker between two packets,i will be the person sending data as well after
reading it from some devices.But packet length is not constant.
each packet has this format:
201.535a56.65b4.56c89.565d
another packet could be :
4a5b6c7d
What i need is a program to store variables such as:var_a has value 4,var_b
has value 5,for second string.
I have to read and write data continuosly using serial port.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From lokeshmaremalla at gmail.com  Sun Aug  9 07:43:33 2009
From: lokeshmaremalla at gmail.com (Lokesh)
Date: Sun, 9 Aug 2009 04:43:33 -0700 (PDT)
Subject: Need help in configuration for TimedRotatingFileHandler
Message-ID: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>

Hi,

Need help in configure the TimedRotatingFileHandler from configuration
file

I have tried with the below code and ended up with the error, code is
pasted below
Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
\logs\rotate_test'
[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler,timedRotatingFileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=timedRotatingFileHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[handler_timedRotatingFileHandler]
class=handlers.TimedRotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt='%Y-%m-%d %H:%M:%S'


Thanks or your time
Regards,
Lokesh


From gert.cuykens at gmail.com  Sun Aug  9 08:14:33 2009
From: gert.cuykens at gmail.com (gert)
Date: Sun, 9 Aug 2009 05:14:33 -0700 (PDT)
Subject: resume upload wsgi script
Message-ID: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>

I working on a resume upload script and encountered the following
problems

sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
'\ufffd\ufff
d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
Content-Disposition: form-data; name="Filename"

DSC00013.JPG
------------Ef1

when I dont use SUBSTR or  COALESCE and || it works

def application(environ, response):
    range=environ.get('HTTP_RANGE','bytes=0-').replace
('bytes=','').split(',')
    offset=[]
    for r in range: offset.append(r.split('-'))
    db.execute('UPDATE users SET picture=SUBSTR(picture,?) WHERE
uid=?', (offset[0][0],s.UID))

    chunk=environ['wsgi.input'].read(int(environ
['CONTENT_LENGTH'])).decode('latin1')
    db.execute('UPDATE users SET picture=COALESCE(picture,?)||? WHERE
uid=?', (''.encode('latin1'),chunk.encode('latin1'), s.UID))

    #while True:
    #      chunk=environ['wsgi.input'].read(8192).decode('latin1')
    #      if not chunk: break
    #      db.execute("UPDATE users SET picture=COALESCE
(picture,'')||? WHERE uid=?", (chunk, s.UID))

the following is the POST clean up when PUT is not used, does anyone
know how to do this without loading the complete blob into memory ?

    db.execute('SELECT picture FROM users WHERE uid=?',(s.UID,))
    f=db.fetch()
    b=environ['CONTENT_TYPE'].split('boundary=')[1]
    p=search(b+r'.*?Content-Type: application/octet-stream\r\n\r\n(.*?)
\r\n--'+b,f[0][0].decode('latin1'),DOTALL).group(1)
    db.execute('UPDATE users SET picture=? WHERE uid=?', (p.encode
('latin1'), s.UID))



From manu3d at gmail.com  Sun Aug  9 08:32:46 2009
From: manu3d at gmail.com (Emanuele D'Arrigo)
Date: Sun, 9 Aug 2009 05:32:46 -0700 (PDT)
Subject: exec("dir()",d)
Message-ID: <9adbf402-3e7e-44a4-adb3-afc36d5d88ba@33g2000vbe.googlegroups.com>

Greetings everybody,

I don't quite understand why if I do this:

>>> d = {}
>>> exec("dir()", d)

1) d is no longer empty
2) the content of d now looks like __builtins__.__dict__ but isn't
quite it d == __builtins__.__dict__ returns false.

Can anybody shed some light?

Manu


From mwilson at the-wire.com  Sun Aug  9 08:50:41 2009
From: mwilson at the-wire.com (Mel)
Date: Sun, 09 Aug 2009 08:50:41 -0400
Subject: exec("dir()",d)
References: <9adbf402-3e7e-44a4-adb3-afc36d5d88ba@33g2000vbe.googlegroups.com>
Message-ID: 

Emanuele D'Arrigo wrote:

> Greetings everybody,
> 
> I don't quite understand why if I do this:
> 
>>>> d = {}
>>>> exec("dir()", d)
> 
> 1) d is no longer empty
> 2) the content of d now looks like __builtins__.__dict__ but isn't
> quite it d == __builtins__.__dict__ returns false.
> 
> Can anybody shed some light?

You should check up on what exec does.  In this case it runs a string 
containing code using dictionary `d` as its global namespace, and so `d` has 
to contain the usual global namespace symbols -- otherwise `dict` can't 
work.  `__builtins__.__dict__ is one of the elements in the global 
namespace, not the namespace itself.  Another example:


Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=7
>>> d={'b':a}
>>> exec ("print b", d)
7
>>> d
{'__builtins__': {'bytearray': , 'IndexError': , 'all': , 'help': Type 
help() for interactive help, or help(object) for help about object., 'vars': 
, 'SyntaxError': , 
'unicode': , 'UnicodeDecodeError': , 'isinstance': , 'copyright': Copyright (c) 2001-2009 Python Software 
Foundation.
[ ... ]
'AssertionError': , 'classmethod': , 'UnboundLocalError': , 
'NotImplementedError': , 
'AttributeError': , 'OverflowError': }, 'b': 7}
>>> 

To get rid of the name error, you'd need
d={}
d['d'] = d
exec ("dir (d)", d)


	Mel.



From lists at cheimes.de  Sun Aug  9 09:01:48 2009
From: lists at cheimes.de (Christian Heimes)
Date: Sun, 09 Aug 2009 15:01:48 +0200
Subject: exec("dir()",d)
In-Reply-To: <9adbf402-3e7e-44a4-adb3-afc36d5d88ba@33g2000vbe.googlegroups.com>
References: <9adbf402-3e7e-44a4-adb3-afc36d5d88ba@33g2000vbe.googlegroups.com>
Message-ID: 

Emanuele D'Arrigo schrieb:
> Greetings everybody,
> 
> I don't quite understand why if I do this:
> 
>>>> d = {}
>>>> exec("dir()", d)
> 
> 1) d is no longer empty
> 2) the content of d now looks like __builtins__.__dict__ but isn't
> quite it d == __builtins__.__dict__ returns false.
> 
> Can anybody shed some light?

RTFM helps ;) http://docs.python.org/reference/simple_stmts.html#exec

As a side effect, an implementation may insert additional keys into the 
dictionaries given besides those corresponding to variable names set by 
the executed code. For example, the current implementation may add a 
reference to the dictionary of the built-in module __builtin__ under the 
key __builtins__ (!).

Christian



From samwyse at gmail.com  Sun Aug  9 09:13:38 2009
From: samwyse at gmail.com (samwyse)
Date: Sun, 9 Aug 2009 06:13:38 -0700 (PDT)
Subject: setting Referer for urllib.urlretrieve
Message-ID: <1668f798-0a73-47a5-9f87-34312109c67c@v2g2000vbb.googlegroups.com>

Here's what I have so far:

import urllib

class AppURLopener(urllib.FancyURLopener):
    version = "App/1.7"
    referrer = None
    def __init__(self, *args):
        urllib.FancyURLopener.__init__(self, *args)
        if self.referrer:
            addheader('Referer', self.referrer)

urllib._urlopener = AppURLopener()

Unfortunately, the 'Referer' header potentially varies for each url
that I retrieve, and the way the module is written, I can't change the
calls to __init__ or open. The best idea I've had is to assign a new
value to my class variable just before calling urllib.urlretrieve(),
but that just seems ugly.  Any ideas?  Thanks.

PS for anyone not familiar with the RFCs:  Yes, I'm spelling
"referrer" correctly everywhere in my code.


From hendrik at microcorp.co.za  Sun Aug  9 09:14:20 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Sun, 9 Aug 2009 15:14:20 +0200
Subject: Serial port access
In-Reply-To: <1e61b3260908081820r702a4e24s6599fa724c97344a@mail.gmail.com>
References: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
	<50697b2c0908081341o63636f36i99b5971fdb0bbb57@mail.gmail.com>
	<1e61b3260908081820r702a4e24s6599fa724c97344a@mail.gmail.com>
Message-ID: <200908091514.20684.hendrik@microcorp.co.za>

On Sunday 09 August 2009 03:20:12 nipun batra wrote:
> On Sun, Aug 9, 2009 at 2:11 AM, Chris Rebert  wrote:
> > On Sat, Aug 8, 2009 at 12:34 PM, nipun batra
> >
> > wrote:
> > > Hi,
> > > How can we access serial port using usb-serial converters,using python
> > > in linux.
> >
> > PySerial might also be an option:
> > http://pyserial.sourceforge.net/index.html
> >
> > Cheers,
> > Chris
> > --
> > http://blog.rebertia.com
>
> pySerial mentions about serial ports but not about usb-serial.Can i do
> something like convert my usb-serial to act as serial port and then use
> pySerial

You can also look in the /dev directory to see which tty is created when you
plug in the usb to serial converter, and use that /dev/ttySx as a file, 
reading and writing to it directly.

You will need this information whatever you do, as you will need to specify
which port to use, to whatever software you choose to use.

- Hendrik


From deets at nospam.web.de  Sun Aug  9 09:17:39 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sun, 09 Aug 2009 15:17:39 +0200
Subject: resume upload wsgi script
In-Reply-To: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
Message-ID: <7e80jlF2etv0kU1@mid.uni-berlin.de>

gert schrieb:
> I working on a resume upload script and encountered the following
> problems
> 
> sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
> '\ufffd\ufff
> d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
> Content-Disposition: form-data; name="Filename"

You are treating a binary data column as if it were a string. That's 
bogus, you need to use a blob column.

Also I wouldn't combine the uplodaded chunks until the full upload is 
finished - and even then only if I actually need the data.

Diez


From gert.cuykens at gmail.com  Sun Aug  9 09:31:12 2009
From: gert.cuykens at gmail.com (gert)
Date: Sun, 9 Aug 2009 06:31:12 -0700 (PDT)
Subject: resume upload wsgi script
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
Message-ID: 

On Aug 9, 3:17?pm, "Diez B. Roggisch"  wrote:
> gert schrieb:
>
> > I working on a resume upload script and encountered the following
> > problems
>
> > sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
> > '\ufffd\ufff
> > d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
> > Content-Disposition: form-data; name="Filename"
>
> You are treating a binary data column as if it were a string. That's
> bogus, you need to use a blob column.
>
> Also I wouldn't combine the uplodaded chunks until the full upload is
> finished - and even then only if I actually need the data.
>
> Diez

And the best solution would be to use TEXT instead or some sort of
SUBBIN that i do not know of in sqlite ?



From steve at REMOVE-THIS-cybersource.com.au  Sun Aug  9 10:41:05 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 09 Aug 2009 14:41:05 GMT
Subject: setting Referer for urllib.urlretrieve
References: <1668f798-0a73-47a5-9f87-34312109c67c@v2g2000vbb.googlegroups.com>
Message-ID: <028ed082$0$20617$c3e8da3@news.astraweb.com>

On Sun, 09 Aug 2009 06:13:38 -0700, samwyse wrote:

> Here's what I have so far:
> 
> import urllib
> 
> class AppURLopener(urllib.FancyURLopener):
>     version = "App/1.7"
>     referrer = None
>     def __init__(self, *args):
>         urllib.FancyURLopener.__init__(self, *args)
>         if self.referrer:
>             addheader('Referer', self.referrer)
> 
> urllib._urlopener = AppURLopener()
> 
> Unfortunately, the 'Referer' header potentially varies for each url that
> I retrieve, and the way the module is written, I can't change the calls
> to __init__ or open. The best idea I've had is to assign a new value to
> my class variable just before calling urllib.urlretrieve(), but that
> just seems ugly.  Any ideas?  Thanks.

[Aside: an int variable is an int. A str variable is a str. A list 
variable is a list. A class variable is a class. You probably mean a 
class attribute, not a variable. If other languages want to call it a 
variable, or a sausage, that's their problem.]

If you're prepared for a bit of extra work, you could take over all the 
URL handling instead of relying on automatic openers. This will give you 
much finer control, but it will also require more effort on your part. 
The basic idea is, instead of installing openers, and then ask the urllib 
module to handle the connection, you handle the connection yourself:

make a Request object using urllib2.Request
make an Opener object using urllib2.build_opener
call opener.open(request) to connect to the server
deal with the connection (retry, fail or read)

Essentially, you use the Request object instead of a URL, and you would 
add the appropriate referer header to the Request object.

Another approach, perhaps a more minimal change than the above, would be 
something like this:

# untested
class AppURLopener(urllib.FancyURLopener):
    version = "App/1.7"
    def __init__(self, *args):
        urllib.FancyURLopener.__init__(self, *args)
    def add_referrer(self, url=None):
        if url:
            addheader('Referer', url)

urllib._urlopener = AppURLopener()
urllib._urlopener.add_referrer("http://example.com/")



-- 
Steven


From deets at nospam.web.de  Sun Aug  9 10:42:11 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sun, 09 Aug 2009 16:42:11 +0200
Subject: resume upload wsgi script
In-Reply-To: 
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
	
Message-ID: <7e85i3F2fdc1eU1@mid.uni-berlin.de>

gert schrieb:
> On Aug 9, 3:17 pm, "Diez B. Roggisch"  wrote:
>> gert schrieb:
>>
>>> I working on a resume upload script and encountered the following
>>> problems
>>> sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
>>> '\ufffd\ufff
>>> d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
>>> Content-Disposition: form-data; name="Filename"
>> You are treating a binary data column as if it were a string. That's
>> bogus, you need to use a blob column.
>>
>> Also I wouldn't combine the uplodaded chunks until the full upload is
>> finished - and even then only if I actually need the data.
>>
>> Diez
> 
> And the best solution would be to use TEXT instead or some sort of
> SUBBIN that i do not know of in sqlite ?
> 

No, the best solution would be to use "BLOB", and no SUB*-stuff, but 
instead a 1:n-relation of chunks, that when the upload is finished you 
can easily combine in python to one large blob, storing that in the DB 
again.

Diez


From kushal.kumaran+python at gmail.com  Sun Aug  9 10:58:14 2009
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Sun, 9 Aug 2009 20:28:14 +0530
Subject: Need help in configuration for TimedRotatingFileHandler
In-Reply-To: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
Message-ID: <1e364c4e0908090758m5daa8ec2td7109498d96569b7@mail.gmail.com>

On Sun, Aug 9, 2009 at 5:13 PM, Lokesh wrote:
> Hi,
>
> Need help in configure the TimedRotatingFileHandler from configuration
> file
>
> I have tried with the below code and ended up with the error, code is
> pasted below
> Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
> \logs\rotate_test'

Does the directory G:\\lok_sib\\logs exist?

> 

-- 
kushal


From zuo at chopin.edu.pl  Sun Aug  9 11:15:32 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Sun, 09 Aug 2009 17:15:32 +0200
Subject: Need help in configuration for TimedRotatingFileHandler
In-Reply-To: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
Message-ID: 

09-08-2009 Lokesh  wrote:

> I have tried with the below code and ended up with the error, code is
> pasted below
> Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
> \logs\rotate_test'

Note that: '\r' is listed (interpreted by Python as 'carriage return'
special character) and not '\\r' (which would mean '\' char + 'r' char).

Regards,
*j

-- 
Jan Kaliszewski (zuo) 


From koranthala at gmail.com  Sun Aug  9 11:35:55 2009
From: koranthala at gmail.com (koranthala)
Date: Sun, 9 Aug 2009 08:35:55 -0700 (PDT)
Subject: Twisted - how to get text for HTTP error responses
Message-ID: <3ae722aa-4e65-475c-b345-73b394779db8@13g2000prl.googlegroups.com>

Hi,
   I am writing a HTTP client in Twisted. The client contacts the
server, and any errors in the sent messages will be returned back to
the client in 400 message. The reason for failure at the server is
sent as the text in the 400 message. I tried the same using the
browser, and I can see the error text (the text might be like - 'Item
X not found in DB').
   The client is supposed to use this text and calculate the next
messages to be sent to the server. But, I cannot seem to find a
mechanism to get the response text from the errback. I went through
failure.py, but I couldnt find a way to do it.
   Ex:
I send a data to the server as so
d = defer.waitForDeferred(getPage(url, method='POST', headers=hdr,
postdata=form))
yield d
try:
   reply = d.getResult()
   success(reply)
except Error, failure:
   failure(failure)

Now, inside failure method, I was unable to print the text out - say
'Item X not found in DB'.
Is it possible using Twisted? If so, how can it be done?

Thanks in Advance
K



From rt8396 at gmail.com  Sun Aug  9 12:04:48 2009
From: rt8396 at gmail.com (r)
Date: Sun, 9 Aug 2009 09:04:48 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	  
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
	
Message-ID: <7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com>

On Aug 8, 12:43?pm, "Jan Kaliszewski"  wrote:
> 08-08-2009 Steven D'Aprano  wrote:
...(snip)
> I use it very often, e.g.:
>
> ? ? ? ? ?afunction('quite long string %s quite long string '
> ? ? ? ? ? ? ? ? ? ?'quite long string quite long string %s '
> ? ? ? ? ? ? ? ? ? ?'quite %s long string quite long string'
> ? ? ? ? ? ? ? ? ? ?% (variable1, variable2, variable3))
>
> It seems nicer to me than:
>
> ? ? ? ? ?afunction(('quite long string %s quite long string '
> ? ? ? ? ? ? ? ? ? ? + 'quite long string quite long string %s '
> ? ? ? ? ? ? ? ? ? ? + 'quite %s long string quite long string')
> ? ? ? ? ? ? ? ? ? ?% (variable1, variable2, variable3))
>
> (Note that multiline-'''-strings are usless in such cases).
>

uhh? A much better way to handle such a problem is like this...

prompt1 = '''
Some people like to use %s
ways of doing things just
so they can support their %s
way of coding
'''

afunction(prompt1 %(var1, var2))

WOW!, that just somehow looks more professional to me? I hate to long
strings in the middle of a code block. Please be smart when writing
code people!!



From julien.chevalier at gmail.com  Sun Aug  9 12:22:40 2009
From: julien.chevalier at gmail.com (Kiki)
Date: Sun, 9 Aug 2009 09:22:40 -0700 (PDT)
Subject: Client/Server based on SocketServer and Windows
Message-ID: 

Hello list,

I've written a small Client/server system.
Basically, i'm expecting something like : The client sends every once
and a while a small data chunk (not more than 50 bytes) the server
receive it and print it.

Here is the server request handler :

class ThreadedTCPRequestHandlerFoo(SocketServer.BaseRequestHandler):

    def handle(self):
	    data = self.request.recv(1024)
	    cur_thread = threading.currentThread()
            response = "%s: %s from Foo" % (cur_thread.getName(),
data)
            print response

and this is the client :

def clientPrompt(ip, port, message):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((ip, port))
	while(1):
		k=raw_input('#>')
		sock.send(k)
		print "%s\n" % k
		if k == 'quit': break
        sock.close()

My problem comes from that I can't send data from client more than
once without having the following Winsock error : 10053 Software
caused connection abort.
I have to restart the client each time I want to send a new message.

Could anyboy explain me why ?

Regards


From exarkun at twistedmatrix.com  Sun Aug  9 12:23:34 2009
From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com)
Date: Sun, 09 Aug 2009 16:23:34 -0000
Subject: Twisted - how to get text for HTTP error responses
In-Reply-To: <3ae722aa-4e65-475c-b345-73b394779db8@13g2000prl.googlegroups.com>
References: <3ae722aa-4e65-475c-b345-73b394779db8@13g2000prl.googlegroups.com>
Message-ID: <20090809162334.7171.12739707.divmod.xquotient.199@localhost.localdomain>

On 03:35 pm, koranthala at gmail.com wrote:
>Hi,
>   I am writing a HTTP client in Twisted. The client contacts the
>server, and any errors in the sent messages will be returned back to
>the client in 400 message. The reason for failure at the server is
>sent as the text in the 400 message. I tried the same using the
>browser, and I can see the error text (the text might be like - 'Item
>X not found in DB').
>   The client is supposed to use this text and calculate the next
>messages to be sent to the server. But, I cannot seem to find a
>mechanism to get the response text from the errback. I went through
>failure.py, but I couldnt find a way to do it.
>   Ex:
>I send a data to the server as so
>d = defer.waitForDeferred(getPage(url, method='POST', headers=hdr,
>postdata=form))
>yield d
>try:
>   reply = d.getResult()
>   success(reply)
>except Error, failure:
>   failure(failure)
>
>Now, inside failure method, I was unable to print the text out - say
>'Item X not found in DB'.
>Is it possible using Twisted? If so, how can it be done?

The Error instance which the local "failure" is bound to in your example 
above has a number of attributes, one of which is "status" which may be 
what you're looking for.  If not, take a look at its other attributes.

Jean-Paul


From python.list at tim.thechases.com  Sun Aug  9 12:47:26 2009
From: python.list at tim.thechases.com (Tim Chase)
Date: Sun, 09 Aug 2009 11:47:26 -0500
Subject: String algo
In-Reply-To: <1e61b3260908090403o1b6c5a66w7c59a2bd29e193a1@mail.gmail.com>
References: <1e61b3260908090403o1b6c5a66w7c59a2bd29e193a1@mail.gmail.com>
Message-ID: <4A7EFD9E.50805@tim.thechases.com>

nipun batra wrote:
> I will be receiving data serially from another pc,.i can use any sort of
> marker between two packets,i will be the person sending data as well after
> reading it from some devices.But packet length is not constant.
> each packet has this format:
> 201.535a56.65b4.56c89.565d
> another packet could be :
> 4a5b6c7d
> What i need is a program to store variables such as:var_a has value 4,var_b
> has value 5,for second string.
> I have to read and write data continuosly using serial port.

Sounds like you want to break apart your string at the 
non-numeric bits, and then create a mapping from them:

 >>> import re
 >>> s = "201.535a56.65b4.56c89.565d"
 >>> r = re.compile(r"(\d+(?:\.\d+)?)([a-z]+)", re.I)
 >>> r.findall(s)
[('201.535', 'a'), ('56.65', 'b'), ('4.56', 'c'), ('89.565', 'd')]
 >>> d = dict((k,float(v)) for v,k in r.findall(s))
 >>> print d['a']
201.535
 >>> print d['c']
4.56
 >>> print 'z' in d
False
 >>> print 'b' in d
True

Adjust the regexp accordingly if there are +/- signs, 
exponentiation, limits on the splitting-characters, etc.


-tkc









From b1540457 at tyldd.com  Sun Aug  9 13:02:03 2009
From: b1540457 at tyldd.com (Anny Mous)
Date: Mon, 10 Aug 2009 03:02:03 +1000
Subject: Bug or feature: double strings as one
References: 
	
	
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
	
	<7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com>
Message-ID: 

r wrote:

> On Aug 8, 12:43?pm, "Jan Kaliszewski"  wrote:

>> (Note that multiline-'''-strings are usless in such cases).
>>
> 
> uhh? A much better way to handle such a problem is like this...
> 
> prompt1 = '''
> Some people like to use %s
> ways of doing things just
> so they can support their %s
> way of coding
> '''

Oh wow, you so need to work on your reading comprehension skills! Didn't you
notice Jan's comment that multiline ''' strings are useless??? They add
extra newlines into the string which aren't wanted.

> WOW!, that just somehow looks more professional to me? I hate to long
> strings in the middle of a code block. Please be smart when writing
> code people!!

Because totally failing to pay attention to the requirements is "smart".





From zuo at chopin.edu.pl  Sun Aug  9 13:10:52 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Sun, 09 Aug 2009 19:10:52 +0200
Subject: Bug or feature: double strings as one
In-Reply-To: <7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com>
References: 
	
	
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
	
	<7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com>
Message-ID: 

09-08-2009 r  wrote:

> On Aug 8, 12:43?pm, "Jan Kaliszewski"  wrote:
>> 08-08-2009 Steven D'Aprano  wrote:
> ...(snip)
>> I use it very often, e.g.:
>>
>> ? ? ? ? ?afunction('quite long string %s quite long string '
>> ? ? ? ? ? ? ? ? ? ?'quite long string quite long string %s '
>> ? ? ? ? ? ? ? ? ? ?'quite %s long string quite long string'
>> ? ? ? ? ? ? ? ? ? ?% (variable1, variable2, variable3))
>>
>> It seems nicer to me than:
>>
>> ? ? ? ? ?afunction(('quite long string %s quite long string '
>> ? ? ? ? ? ? ? ? ? ? + 'quite long string quite long string %s '
>> ? ? ? ? ? ? ? ? ? ? + 'quite %s long string quite long string')
>> ? ? ? ? ? ? ? ? ? ?% (variable1, variable2, variable3))
>>
>> (Note that multiline-'''-strings are usless in such cases).
>>
>
> uhh? A much better way to handle such a problem is like this...
>
> prompt1 = '''
> Some people like to use %s
> ways of doing things just
> so they can support their %s
> way of coding
> '''

Sorry, you are wrong, '''-way would be usefull only if:

     * you want to have '\n' in each place where you wrap the
       literal in your code,

and

     * you use '''-literal at a module (non-indented) level

       or you need not only '\n'-s but also indentations
          (dependent on indentation of your code),

       or such ugly indentation is ok for you:

           some indentated code...
  ? ? ? ? ?prompt = '''quite long string %s quite long string
''' quite long string quite long string %s
''' quite %s long string quite long string
'''
           some indentated code...


That's why I wrote it's "useless in such cases."

Regards,
*j

-- 
Jan Kaliszewski (zuo) 


From no.i.dont at want.mail.from.spammers.com  Sun Aug  9 13:16:50 2009
From: no.i.dont at want.mail.from.spammers.com (Fencer)
Date: Sun, 09 Aug 2009 19:16:50 +0200
Subject: Problem with join in__str__() in class (newbie)
Message-ID: <7e8ek2F2dre5lU1@mid.individual.net>

Hello, I've written two classes. One class describes experts: experts 
has a unique ID and a name. An expert knows topics and other experts. A 
topic is described by my other class and includes a unique ID and a 
name. Now I have a problem with the __str__ method in my Expert class:

def __str__(self):
     output = '%s:%s' % (self.expert_id, self.name)
     output += '\nKnown topics: %s' % (', '.join(str(self.topics)))
#   print 'Known experts: '
#   for e in self.known_experts:
#       print '%s:%s' % (e.expert_id, e.name)
     return output

self.topics is a list of objects of type Topic.
self.known_experts is a list of objects of type Expert, specifically the 
experts known by the given expert.

When I print an object of type Expert, the output is not what I want. If 
the expert knows only one topic, say polemics, the output is:
e2:Carla
Known topics: t, 5, :, P, o, l, e, m, i, c, s
If the expert knows two topics, say Polemics and The Parthenon, then the 
  output is:
e2:Carla
Known topics: [, <, _, _, m, a, i, n, _, _, ., T, o, p, i, c,  , i, n, 
s, t, a, n, c, e,  , a, t,  , 0, x, 0, 2, 2, 2, D, 0, 8, 0, >, ]

This is not what I want. :) I want the output like this:
e2:Carla
Known topics: t5:Polemics, t6:The Parthenon

Also, notice the code I've commented out. If I can get the join above to 
work (with your help) my next question is how to present the known 
experts in a comma separated list with only expert_id and name? I can't 
use the normal __str__() method (the one I'm writing here) because it 
prints too much information. Does that mean a join is out of the question?

Thanks for any replies!

- Fencer


From jonrascal at gmail.com  Sun Aug  9 13:28:13 2009
From: jonrascal at gmail.com (jon rascal)
Date: Sun, 9 Aug 2009 10:28:13 -0700 (PDT)
Subject: Problem with join in__str__() in class (newbie)
References: <7e8ek2F2dre5lU1@mid.individual.net>
Message-ID: 


> def __str__(self):
> ? ? ?output = '%s:%s' % (self.expert_id, self.name)
> ? ? ?output += '\nKnown topics: %s' % (', '.join(str(self.topics)))

You're turning your list into a string -- try this:
', '.join([str(x) for x in self.topics])


From apt.shansen at gmail.com  Sun Aug  9 13:37:08 2009
From: apt.shansen at gmail.com (Stephen Hansen)
Date: Sun, 9 Aug 2009 10:37:08 -0700
Subject: Problem with join in__str__() in class (newbie)
In-Reply-To: <7e8ek2F2dre5lU1@mid.individual.net>
References: <7e8ek2F2dre5lU1@mid.individual.net>
Message-ID: <7a9c25c20908091037l2db51049v74b2e18efc927c25@mail.gmail.com>

   output += '\nKnown topics: %s' % (', '.join(str(self.topics)))


Your problem is here.

self.topics is a list of topic instances: but you're calling str() on the
list itself to turn the LIST itself into a string. Compare:

>>> x = [1,2,3]
>>> x
[1, 2, 3]
>>> str(x)
'[1, 2, 3]'

Now, after str(self.topics) is done, you have one big string. A string is a
sequence of characters (mostly). Calling ",".join(string) will do just what
you see there-- return a string with a comma between each character.

What you want to do, I assume, is call str() on each item in self.topics,
and join them.

That would be:

output += '\nKnown topics: %s' % ( ','.join(str(item) for item in
self.topics) )

That's a generator expression which will do what you want, I believe.
Provided your topic instances have a __str__ method that returns a string of
the form "t:".

Also, notice the code I've commented out. If I can get the join above to
> work (with your help) my next question is how to present the known experts
> in a comma separated list with only expert_id and name? I can't use the
> normal __str__() method (the one I'm writing here) because it prints too
> much information. Does that mean a join is out of the question?


Honestly, I think you are putting too much into the Expert class's __str__
method. I would make it do basically:

return "%s:%s" % (self.expert_id, self.name)

And then put the __str__ you're working on above in a different method which
does -- more. Call it 'dump' or something. That way you CAN just use the
normal str/__str__ from within this 'dump' and get what you want. str()
should return that object in its stringified form. Another method is a
better way to dump 'that object' and things 'around' it and that it 'knows'.

But if you really must have just str(expert) and have it return the big
chunk of information, your commented code looks about right. You'll have to
use your knowledge of how the internal expert class works instead of relying
on the experts just returning a str() of themselves. That's slightly bad.
But not horrible.

HTH,

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From no.i.dont at want.mail.from.spammers.com  Sun Aug  9 13:42:23 2009
From: no.i.dont at want.mail.from.spammers.com (Fencer)
Date: Sun, 09 Aug 2009 19:42:23 +0200
Subject: Problem with join in__str__() in class (newbie)
In-Reply-To: 
References: <7e8ek2F2dre5lU1@mid.individual.net>
	
Message-ID: <7e8g3vF2etertU1@mid.individual.net>

jon rascal wrote:
> 
> You're turning your list into a string -- try this:
> ', '.join([str(x) for x in self.topics])

Thanks for your quick reply, unfortunately it didn't quite work for me.
Say topics contain two topics: polemics, and the parthenon I get this 
output:
e2:Carla
Known topics: t5:Polemics

only the first topic is printed. If topics only contain a single topic I 
get this error:
Traceback (most recent call last):
   File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 
57, in 
     print experts[1]
   File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 
21, in __str__
     output += '\nKnown topics: %s' % (', '.join([str(x) for x in 
self.topics]))
TypeError: iteration over non-sequence

What did I do wrong?

- Fencer


From gert.cuykens at gmail.com  Sun Aug  9 13:51:25 2009
From: gert.cuykens at gmail.com (gert)
Date: Sun, 9 Aug 2009 10:51:25 -0700 (PDT)
Subject: resume upload wsgi script
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
	
	<7e85i3F2fdc1eU1@mid.uni-berlin.de>
Message-ID: <9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com>

On Aug 9, 4:42?pm, "Diez B. Roggisch"  wrote:
> gert schrieb:
>
>
>
> > On Aug 9, 3:17 pm, "Diez B. Roggisch"  wrote:
> >> gert schrieb:
>
> >>> I working on a resume upload script and encountered the following
> >>> problems
> >>> sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
> >>> '\ufffd\ufff
> >>> d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
> >>> Content-Disposition: form-data; name="Filename"
> >> You are treating a binary data column as if it were a string. That's
> >> bogus, you need to use a blob column.
>
> >> Also I wouldn't combine the uplodaded chunks until the full upload is
> >> finished - and even then only if I actually need the data.
>
> >> Diez
>
> > And the best solution would be to use TEXT instead or some sort of
> > SUBBIN that i do not know of in sqlite ?
>
> No, the best solution would be to use "BLOB", and no SUB*-stuff, but
> instead a 1:n-relation of chunks, that when the upload is finished you
> can easily combine in python to one large blob, storing that in the DB
> again.
>
> Diez

so one table of chunks

CREATE TABLE temp (
    file_id  VARCHAR(64),
    chunK_id  INTEGER,
    chunk BLOB,
    PRIMARY KEY(file_id,chunk_id)
);

SELECT chunk FROM temp WHERE file_id = 'file'
concatenating result in python
update blob
delete temp

How do I concatenate results that do not fit into memory ?


From apt.shansen at gmail.com  Sun Aug  9 14:06:44 2009
From: apt.shansen at gmail.com (Stephen Hansen)
Date: Sun, 9 Aug 2009 11:06:44 -0700
Subject: Problem with join in__str__() in class (newbie)
In-Reply-To: <7e8g3vF2etertU1@mid.individual.net>
References: <7e8ek2F2dre5lU1@mid.individual.net>
	
	<7e8g3vF2etertU1@mid.individual.net>
Message-ID: <7a9c25c20908091106u7a5464dey625220f211e69d58@mail.gmail.com>

>
> only the first topic is printed. If topics only contain a single topic I
> get this error:
> Traceback (most recent call last):
>  File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 57,
> in 
>    print experts[1]
>  File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 21,
> in __str__
>    output += '\nKnown topics: %s' % (', '.join([str(x) for x in
> self.topics]))
> TypeError: iteration over non-sequence
>
> What did I do wrong?
>

It looks like, "if topics contains only a single topic", means:

    self.topics = MyTopic

was done at some point. What you should do is make self.topics ALWAYS be a
list: even if it's only a list of one item.

So you do

    self.topics.append(MyTopic)

when you add that one topic. That way self.topics is always a list.
Sometimes empty, sometimes containing one element, sometimes containing
many.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From python at mrabarnett.plus.com  Sun Aug  9 14:10:08 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Sun, 09 Aug 2009 19:10:08 +0100
Subject: Problem with join in__str__() in class (newbie)
In-Reply-To: <7e8g3vF2etertU1@mid.individual.net>
References: <7e8ek2F2dre5lU1@mid.individual.net>	
	<7e8g3vF2etertU1@mid.individual.net>
Message-ID: <4A7F1100.5040203@mrabarnett.plus.com>

Fencer wrote:
> jon rascal wrote:
>>
>> You're turning your list into a string -- try this:
>> ', '.join([str(x) for x in self.topics])
> 
> Thanks for your quick reply, unfortunately it didn't quite work for me.
> Say topics contain two topics: polemics, and the parthenon I get this 
> output:
> e2:Carla
> Known topics: t5:Polemics
> 
> only the first topic is printed. If topics only contain a single topic I 
> get this error:
> Traceback (most recent call last):
>   File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 
> 57, in 
>     print experts[1]
>   File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 
> 21, in __str__
>     output += '\nKnown topics: %s' % (', '.join([str(x) for x in 
> self.topics]))
> TypeError: iteration over non-sequence
> 
> What did I do wrong?
> 
Try printing self.topics. It should always be a list of topics.


From deets at nospam.web.de  Sun Aug  9 14:25:47 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sun, 09 Aug 2009 20:25:47 +0200
Subject: resume upload wsgi script
In-Reply-To: <9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com>
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
	
	<7e85i3F2fdc1eU1@mid.uni-berlin.de>
	<9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com>
Message-ID: <7e8ildF2f1hcpU1@mid.uni-berlin.de>

gert schrieb:
> On Aug 9, 4:42 pm, "Diez B. Roggisch"  wrote:
>> gert schrieb:
>>
>>
>>
>>> On Aug 9, 3:17 pm, "Diez B. Roggisch"  wrote:
>>>> gert schrieb:
>>>>> I working on a resume upload script and encountered the following
>>>>> problems
>>>>> sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
>>>>> '\ufffd\ufff
>>>>> d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
>>>>> Content-Disposition: form-data; name="Filename"
>>>> You are treating a binary data column as if it were a string. That's
>>>> bogus, you need to use a blob column.
>>>> Also I wouldn't combine the uplodaded chunks until the full upload is
>>>> finished - and even then only if I actually need the data.
>>>> Diez
>>> And the best solution would be to use TEXT instead or some sort of
>>> SUBBIN that i do not know of in sqlite ?
>> No, the best solution would be to use "BLOB", and no SUB*-stuff, but
>> instead a 1:n-relation of chunks, that when the upload is finished you
>> can easily combine in python to one large blob, storing that in the DB
>> again.
>>
>> Diez
> 
> so one table of chunks
> 
> CREATE TABLE temp (
>     file_id  VARCHAR(64),
>     chunK_id  INTEGER,
>     chunk BLOB,
>     PRIMARY KEY(file_id,chunk_id)
> );
> 
> SELECT chunk FROM temp WHERE file_id = 'file'
> concatenating result in python
> update blob
> delete temp
> 
> How do I concatenate results that do not fit into memory ?

By writing them into one file? If files were to large for your memory, 
all the substring-stuff wouldn't help either - the sqlite works in the 
same memory as your program...

But how many gigabytes of uploads do you expect?

Diez


From no.i.dont at want.mail.from.spammers.com  Sun Aug  9 14:56:26 2009
From: no.i.dont at want.mail.from.spammers.com (Fencer)
Date: Sun, 09 Aug 2009 20:56:26 +0200
Subject: Problem with join in__str__() in class (newbie)
In-Reply-To: 
References: <7e8ek2F2dre5lU1@mid.individual.net>		<7e8g3vF2etertU1@mid.individual.net>
	
Message-ID: <7e8keqF2eib0lU1@mid.individual.net>

MRAB wrote:
> Try printing self.topics. It should always be a list of topics.

Ah, yes, that made me find a bug when I was creating the Expert objects: 
the lists of known topics were not created properly. I should have 
posted more code I suppose! Thanks for the help, this problem has now 
been solved. I guess I can't use a join to print the known experts as I 
described in my first post.

- Fencer


From Nikolaus at rath.org  Sun Aug  9 15:02:57 2009
From: Nikolaus at rath.org (Nikolaus Rath)
Date: Sun, 09 Aug 2009 15:02:57 -0400
Subject: Monkeypatching an object to become callable
Message-ID: <87hbwgu7xa.fsf@vostro.rath.org>

Hi,

I want to monkeypatch an object so that it becomes callable, although
originally it is not meant to be. (Yes, I think I do have a good reason
to do so).

But simply adding a __call__ attribute to the object apparently isn't
enough, and I do not want to touch the class object (since it would
modify all the instances):

>>> class foo(object):
...   pass
... 
>>> t = foo()
>>> def test():
...   print 'bar'
... 
>>> t()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'foo' object is not callable
>>> t.__call__ = test
>>> t()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'foo' object is not callable
>>> t.__call__()
bar


Is there an additional trick to get it to work?


Best,

   -Nikolaus

-- 
 ?Time flies like an arrow, fruit flies like a Banana.?

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C


From darkwater42 at gmail.com  Sun Aug  9 15:26:54 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Sun, 9 Aug 2009 12:26:54 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
Message-ID: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>

A friend of mine is just learning Python, and he's a bit tweaked about
how unrecognized escape sequences are treated in Python. This is from
the Python 3.0 reference manual:

     Unlike Standard C, all unrecognized escape sequences are left in
the string unchanged, i.e.,
     the backslash is left in the string. (This behavior is useful
when debugging: if an escape
     sequence is mistyped, the resulting output is more easily
recognized as broken.) It is also
     important to note that the escape sequences only recognized in
string literals fall into the
     category of unrecognized escapes for bytes literals.

My friend begs to differ with the above. It would be much better for
debugging if Python generated a parsing error for unrecognized escape
sequences, rather than leaving them unchanged. g++ outputs a warning
for such escape sequences, for instance. This is what I would consider
to be the correct behavior. (Actually, I think it should just generate
a fatal parsing error, but a warning is okay too.)

In any case, I think my friend should mellow out a bit, but we both
consider this something of a wart. He's just more wart-phobic than I
am. Is there any way that this behavior can be considered anything
other than a wart? Other than the unconvincing claim that you can use
this "feature" to save you a bit of typing sometimes when you actually
want a backslash to be in your string?

|>ouglas


From piet at cs.uu.nl  Sun Aug  9 16:15:22 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Sun, 09 Aug 2009 22:15:22 +0200
Subject: Problem with join in__str__() in class (newbie)
References: <7e8ek2F2dre5lU1@mid.individual.net>
	
	<7e8g3vF2etertU1@mid.individual.net>
	
	<7e8keqF2eib0lU1@mid.individual.net>
Message-ID: 

>>>>> Fencer  (F) wrote:

>F> Also, notice the code I've commented out. If I can get the join above to
>F> work (with your help) my next question is how to present the known experts
>F> in a comma separated list with only expert_id and name? I can't use the
>F> normal __str__() method (the one I'm writing here) because it prints too
>F> much information. Does that mean a join is out of the question?

>F> MRAB wrote:
>>> Try printing self.topics. It should always be a list of topics.

>F> Ah, yes, that made me find a bug when I was creating the Expert objects:
>F> the lists of known topics were not created properly. I should have posted
>F> more code I suppose! Thanks for the help, this problem has now been solved.
>F> I guess I can't use a join to print the known experts as I described in my
>F> first post.

Yes, you can. But you need an additional method that gives only the id
and name. Like this:

------------------------------------------------------------------------
class Expert:
    '''An expert'''
    def __init__(self, id, name, topics):
        self.expert_id = id
        self.name = name
        self.topics = topics
        self.known_experts = []
        
    def add_expert(self, expert):
        self.known_experts.append(expert)

    def __str__(self):
        output = (self.brief_str() +
                  '\nKnown topics: %s' % (', '.join(map(str, self.topics))) +
                  ('\nKnown experts: %s' %
                   (', '.join(exp.brief_str() for exp in self.known_experts))))
        return output

    def brief_str(self):
        '''Gives a brief description of the expert: just the id and name.'''
        return '%s:%s' % (self.expert_id, self.name)
    
class Topic:
    '''A topic'''
    def __init__(self, id, name):
        self.topic_id = id
        self.name = name

    def __str__(self):
        return '%s:%s' % (self.topic_id, self.name)

topic1 = Topic('t1', 'Relativity')
topic2 = Topic('t2', 'Math')
topic5 = Topic('t5', 'Polemics')
topic6 = Topic('t6', 'The Parthenon')

expert1 = Expert('e1', 'Albert', [topic1])
expert2 = Expert('e2', 'Leonhard', [topic2])

expert1.add_expert(expert2)

expert5 = Expert('e5', 'Carla', [topic5, topic6])
expert5.add_expert(expert1)
expert5.add_expert(expert2)

for ex in expert1, expert2, expert5:
    print ex
------------------------------------------------------------------------

(I prefer to use map instead of a list/iterator comprehension in this
particular case. With the known_experts that isn't possible, unless
brief_str is made into a static method)
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From victorsubervi at gmail.com  Sun Aug  9 16:21:43 2009
From: victorsubervi at gmail.com (Victor Subervi)
Date: Sun, 9 Aug 2009 15:21:43 -0500
Subject: Surpressing Warnings
Message-ID: <4dc0cfea0908091321y54156d30sc0c4dc3a564eecab@mail.gmail.com>

Hi:
I get a ton of warnings like this from a program I run:

Warning (from warnings module):
  File "C:\Python25\read.py", line 67
    cursor.execute(sqlKWDrop)
Warning: Unknown table 'judaism_128'

How do I surpress them?
TIA,
Victor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From missive at hotmail.com  Sun Aug  9 16:26:31 2009
From: missive at hotmail.com (Lee Harr)
Date: Mon, 10 Aug 2009 00:56:31 +0430
Subject: [ANNC] pybotwar-0.5
Message-ID: 


pybotwar is a fun and educational game where players
create computer programs to control simulated robots
to compete in a battle arena.

http://pybotwar.googlecode.com/


pybotwar uses pybox2d for the physical simulation,
and uses pygame and pygsear for the visualization.

pybotwar is released under GPLv3.


Changes in pybotwar-0.5:
    - added tournament mode
    - added explosive shells
    - robots are now damaged by colliding with walls or other robots
    - added damage sensor
    - added gyro sensor
    - added configurable cannon reload time
    - added robot statistics database
    - added time limit for robot startup/ initialization
    - health bar changes color below 30% health
    - fixed force/ torque possibly going over 100%
    - fixed problem with non-integer force/ torque values
    - each robot gets its own log file in test mode
    - send robot errors to log file
    - use optparse for cmd line options


_________________________________________________________________
More than messages?check out the rest of the Windows Live?.
http://www.microsoft.com/windows/windowslive/


From deets at nospam.web.de  Sun Aug  9 16:28:29 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sun, 09 Aug 2009 22:28:29 +0200
Subject: Monkeypatching an object to become callable
In-Reply-To: <87hbwgu7xa.fsf@vostro.rath.org>
References: <87hbwgu7xa.fsf@vostro.rath.org>
Message-ID: <7e8preF2d6adsU1@mid.uni-berlin.de>

Nikolaus Rath schrieb:
> Hi,
> 
> I want to monkeypatch an object so that it becomes callable, although
> originally it is not meant to be. (Yes, I think I do have a good reason
> to do so).
> 
> But simply adding a __call__ attribute to the object apparently isn't
> enough, and I do not want to touch the class object (since it would
> modify all the instances):
> 
>>>> class foo(object):
> ...   pass
> ... 
>>>> t = foo()
>>>> def test():
> ...   print 'bar'
> ... 
>>>> t()
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'foo' object is not callable
>>>> t.__call__ = test
>>>> t()
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'foo' object is not callable
>>>> t.__call__()
> bar
> 
> 
> Is there an additional trick to get it to work?

AFAIK special methods are always only evaluated on the class. But this 
works:

class Foo(object):

     pass

f = Foo()

def make_callable(f):
     class Callable(f.__class__):

         def __call__(self):
             print "foobar"

     f.__class__ = Callable

make_callable(f)
f()

Diez


From rt8396 at gmail.com  Sun Aug  9 16:34:12 2009
From: rt8396 at gmail.com (r)
Date: Sun, 9 Aug 2009 13:34:12 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	  
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
	 
	<7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com> 
	
Message-ID: <21131b4b-67d3-4ddf-b061-60327d670ca7@l31g2000vbp.googlegroups.com>

On Aug 9, 12:10?pm, "Jan Kaliszewski"  wrote:
..(snip)
> Sorry, you are wrong, '''-way would be usefull only if:
>
> ? ? ?* you want to have '\n' in each place where you wrap the
> ? ? ? ?literal in your code,
>
> and
>
> ? ? ?* you use '''-literal at a module (non-indented) level
>
> ? ? ? ?or you need not only '\n'-s but also indentations
> ? ? ? ? ? (dependent on indentation of your code),
>
> ? ? ? ?or such ugly indentation is ok for you:
>
> ? ? ? ? ? ?some indentated code...
> ? ? ? ? ? ?prompt = '''quite long string %s quite long string
> ''' quite long string quite long string %s
> ''' quite %s long string quite long string
> '''
> ? ? ? ? ? ?some indentated code...
>
> That's why I wrote it's "useless in such cases."

@ Jan & Anny

No, of course putting a multi-line string inside a block does not
solve anything. What i meant for you to do is to declare the string
outside the block or as a module level Constant. i typically declare
all multi-line strings (ig for dialog prompts etc..) right after my
globals at the top of my modules or within an imported module like...

from thisModuleConstants import *




From sajmikins at gmail.com  Sun Aug  9 17:02:51 2009
From: sajmikins at gmail.com (Simon Forman)
Date: Sun, 9 Aug 2009 14:02:51 -0700 (PDT)
Subject: unique-ifying a list
References: 
Message-ID: 

On Aug 7, 4:53?pm, kj  wrote:
> Suppose that x is some list. ?To produce a version of the list with
> duplicate elements removed one could, I suppose, do this:
>
> ? ? x = list(set(x))
>
> but I expect that this will not preserve the original order of
> elements.
>
> I suppose that I could write something like
>
> def uniquify(items):
> ? ? seen = set()
> ? ? ret = []
> ? ? for i in items:
> ? ? ? ? if not i in seen:
> ? ? ? ? ? ? ret.append(i)
> ? ? ? ? ? ? seen.add(i)
> ? ? return ret
>
> But this seems to me like such a commonly needed operation that I
> find it hard to believe one would need to resort to such self-rolled
> solutions. ?Isn't there some more standard (and hopefully more
> efficient, as in "C-coded"/built-in) approach?
>
> TIA!
>
> kynn


Unique items in a list, in the same order as in the list:

x = sorted(set(x), key=x.index)

;]


From davea at ieee.org  Sun Aug  9 17:15:47 2009
From: davea at ieee.org (Dave Angel)
Date: Sun, 09 Aug 2009 17:15:47 -0400
Subject: Need help in configuration for TimedRotatingFileHandler
In-Reply-To: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
Message-ID: <4A7F3C83.1040607@ieee.org>

Lokesh wrote:
> Hi,
>
> Need help in configure the TimedRotatingFileHandler from configuration
> file
>
> I have tried with the below code and ended up with the error, code is
> pasted below
> Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
> \logs\rotate_test'
> [loggers]
> keys=root,simpleExample
>
> [handlers]
> keys=consoleHandler,timedRotatingFileHandler
>
> [formatters]
> keys=simpleFormatter
>
> [logger_root]
> level=DEBUG
> handlers=consoleHandler
>
> [logger_simpleExample]
> level=DEBUG
> handlers=timedRotatingFileHandler
> qualname=simpleExample
> propagate=0
>
> [handler_consoleHandler]
> class=StreamHandler
> level=DEBUG
> formatter=simpleFormatter
> args=(sys.stdout,)
>
> [handler_timedRotatingFileHandler]
> class=handlers.TimedRotatingFileHandler
> level=DEBUG
> formatter=simpleFormatter
> args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)
>
> [formatter_simpleFormatter]
> format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
> datefmt='%Y-%m-%d %H:%M:%S'
>
>
> Thanks or your time
> Regards,
> Lokesh
>
>   
I don't see code there, I see lots of config data, presumably in an .ini 
file.   So I don't know how you're reading it in, and converting it to 
Python variables, but I know where I'd look, based on your error message.

The following line:

args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)

seems to contain a Python string.  But there are unescaped backslashes 
within it.  You can get away with it in two cases, because \l  isn't a 
valid escape sequence.  But in the case of \r, it looks like a newline 
character.

Anyway, all three of those backslashes probably need to be doubled.

args=("G:\\lok_sib\\logs\\rotate_test", 'midnight', 1)

Two other cures that may work, depending on context:   change the backslashes to forward slashes, or use a raw string.

But as I said earlier, you don't show in any way what code is interpreting this line, so it's all just guesswork.

DaveA



From rt8396 at gmail.com  Sun Aug  9 17:43:14 2009
From: rt8396 at gmail.com (r)
Date: Sun, 9 Aug 2009 14:43:14 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	  
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
	 
	<7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com> 
	
	<21131b4b-67d3-4ddf-b061-60327d670ca7@l31g2000vbp.googlegroups.com>
Message-ID: <6cdaacf6-a560-483e-a14d-26396173e3bd@o35g2000vbi.googlegroups.com>


#-- el bueno --#
"hello i am a very long string that\
does not like newlines so please \
escape me, Thank you!"

#-- el malo --#
"hello i am a very long string that"+
"does not like newlines but i have no"+
"idea what to do with myself"

#-- el feo --#
"hello i am a very long string that"
"does not like newlines but i have no"
"idea what to do with myself"


just ideas people!


From mail at johannes-janssen.de  Sun Aug  9 18:06:44 2009
From: mail at johannes-janssen.de (Johannes Janssen)
Date: Mon, 10 Aug 2009 00:06:44 +0200
Subject: How to find out in which module an instance of a class is created?
Message-ID: <4A7F4874.8030008@johannes-janssen.de>

Hi
I like to know in which module an instance of a class was initialized. 
Using __module__ or __name__ within a class only gives me the module in 
which the class was defined not the instance of the class. Is there some 
(simple) way to do this?
For better understanding I'll give an example how I want to use this. 
Okay let's say I've got a module *foo,* in which class A is defined as 
the following:

 > class A(object):
 >     def __init__(self, mod):
 >         self.mod = mod

In a module called *bar* I do the following:

 > import foo
 > a = A(__name__)

Then a.mod should be "bar". But I don't like to pass the value of a.mod 
manually rather than having it default to the module the instance a of A 
was created in (here "bar").
Unfortunately something like this ...

 > class A(object):
 >     def __init__(self, mod=__name__):
 >         self.mod = mod

... won't work. In this case mod would always be "foo".

Kind regards
johannes


From gert.cuykens at gmail.com  Sun Aug  9 18:22:17 2009
From: gert.cuykens at gmail.com (gert)
Date: Sun, 9 Aug 2009 15:22:17 -0700 (PDT)
Subject: resume upload wsgi script
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
	
	<7e85i3F2fdc1eU1@mid.uni-berlin.de>
	<9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com>
	<7e8ildF2f1hcpU1@mid.uni-berlin.de>
Message-ID: <49e41062-9e0d-4c5e-beca-edb02d3ce6e8@e34g2000vbm.googlegroups.com>

On Aug 9, 8:25?pm, "Diez B. Roggisch"  wrote:
> gert schrieb:
>
>
>
> > On Aug 9, 4:42 pm, "Diez B. Roggisch"  wrote:
> >> gert schrieb:
>
> >>> On Aug 9, 3:17 pm, "Diez B. Roggisch"  wrote:
> >>>> gert schrieb:
> >>>>> I working on a resume upload script and encountered the following
> >>>>> problems
> >>>>> sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
> >>>>> '\ufffd\ufff
> >>>>> d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
> >>>>> Content-Disposition: form-data; name="Filename"
> >>>> You are treating a binary data column as if it were a string. That's
> >>>> bogus, you need to use a blob column.
> >>>> Also I wouldn't combine the uplodaded chunks until the full upload is
> >>>> finished - and even then only if I actually need the data.
> >>>> Diez
> >>> And the best solution would be to use TEXT instead or some sort of
> >>> SUBBIN that i do not know of in sqlite ?
> >> No, the best solution would be to use "BLOB", and no SUB*-stuff, but
> >> instead a 1:n-relation of chunks, that when the upload is finished you
> >> can easily combine in python to one large blob, storing that in the DB
> >> again.
>
> >> Diez
>
> > so one table of chunks
>
> > CREATE TABLE temp (
> > ? ? file_id ?VARCHAR(64),
> > ? ? chunK_id ?INTEGER,
> > ? ? chunk BLOB,
> > ? ? PRIMARY KEY(file_id,chunk_id)
> > );
>
> > SELECT chunk FROM temp WHERE file_id = 'file'
> > concatenating result in python
> > update blob
> > delete temp
>
> > How do I concatenate results that do not fit into memory ?
>
> By writing them into one file? If files were to large for your memory,
> all the substring-stuff wouldn't help either - the sqlite works in the
> same memory as your program...
>
> But how many gigabytes of uploads do you expect?
>

250KB :)
Its just HTTP1.1 has everything for making ftp like file transfers
possible.
When I write it to a file then I am back at square one because I still
need to load it completely to get it into a blob.
So there is no way to concatenate BLOB's without loading it completely
into memory ?


From pavlovevidence at gmail.com  Sun Aug  9 18:24:53 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sun, 9 Aug 2009 15:24:53 -0700 (PDT)
Subject: Monkeypatching an object to become callable
References: <87hbwgu7xa.fsf@vostro.rath.org>
Message-ID: 

On Aug 9, 12:02?pm, Nikolaus Rath  wrote:
> Hi,
>
> I want to monkeypatch an object so that it becomes callable, although
> originally it is not meant to be. (Yes, I think I do have a good reason
> to do so).
>
> But simply adding a __call__ attribute to the object apparently isn't
> enough, and I do not want to touch the class object (since it would
> modify all the instances):


Override the class's __call__, and program it to call a certain method
(say _instancecall) on the object.  Catch AttributeError and raise
TypeError so that it matches the behavior when no __call__ is defined.


def __call__(self,*args,**kwargs):
    try:
        func = self._instancecall
    except AttributeError:
        raise TypeError("'%s' object not callable" % self.__class__)
    return func(*args,**kwargs)


Note: don't call _instancecall inside the try clause; you don't want
to catch attribute errors raised inside the _instancecall method.

Then set _instancecall on any objects you want to be callable.


Carl Banks


From clp2 at rebertia.com  Sun Aug  9 18:47:58 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Sun, 9 Aug 2009 18:47:58 -0400
Subject: Surpressing Warnings
In-Reply-To: <4dc0cfea0908091321y54156d30sc0c4dc3a564eecab@mail.gmail.com>
References: <4dc0cfea0908091321y54156d30sc0c4dc3a564eecab@mail.gmail.com>
Message-ID: <50697b2c0908091547q6f63b0d1v2b70ffa0a9352b24@mail.gmail.com>

On Sun, Aug 9, 2009 at 4:21 PM, Victor Subervi wrote:
> Hi:
> I get a ton of warnings like this from a program I run:
>
> Warning (from warnings module):
> ? File "C:\Python25\read.py", line 67
> ??? cursor.execute(sqlKWDrop)
> Warning: Unknown table 'judaism_128'
>
> How do I surpress them?

import warnings
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    cursor.execute(sqlKWDrop)
#repeat for every call that's causing warnings

or to just silence all warnings from anywhere:

import warnings
warnings.simplefilter("ignore")

Cheers,
Chris
-- 
http://blog.rebertia.com


From zuo at chopin.edu.pl  Sun Aug  9 19:26:00 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Mon, 10 Aug 2009 01:26:00 +0200
Subject: Bug or feature: double strings as one
In-Reply-To: <6cdaacf6-a560-483e-a14d-26396173e3bd@o35g2000vbi.googlegroups.com>
References: 
	
	
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
	
	<7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com>
	
	<21131b4b-67d3-4ddf-b061-60327d670ca7@l31g2000vbp.googlegroups.com>
	<6cdaacf6-a560-483e-a14d-26396173e3bd@o35g2000vbi.googlegroups.com>
Message-ID: 

09-08-2009 o 23:43:14 r  wrote:

> #-- el bueno --#
> "hello i am a very long string that\
> does not like newlines so please \
> escape me, Thank you!"

You probably ment: """hello i am... [etc.]

Anyway... You're right that generally it's good idea to define
dialog prompts and such stuff separately rather that to hardcode
it, especially in big projects. Then certainly multiline
string literals are useful (though, if you need to get rid of
newlines, IMHO "el feo" method is more elegant and less error
prone than your "el bueno" [possible invisible space after '\']).

But there are plenty of other situations when it's better
(in practice) to have strings (even long) together with your
code, e.g. log information for debugging, or

Cheers,

*j


From lists at cheimes.de  Sun Aug  9 19:47:34 2009
From: lists at cheimes.de (Christian Heimes)
Date: Mon, 10 Aug 2009 01:47:34 +0200
Subject: How to find out in which module an instance of a class is created?
In-Reply-To: <4A7F4874.8030008@johannes-janssen.de>
References: <4A7F4874.8030008@johannes-janssen.de>
Message-ID: <4A7F6016.2060408@cheimes.de>

Johannes Janssen wrote:
>  > class A(object):
>  >     def __init__(self, mod=__name__):
>  >         self.mod = mod
> 
> .... won't work. In this case mod would always be "foo".

You have to inspect the stack in order to get the module of the caller. 
The implementation of warnings.warn() gives you some examples how to get 
the module name.

Christian


From nagle at animats.com  Sun Aug  9 19:51:41 2009
From: nagle at animats.com (John Nagle)
Date: Sun, 09 Aug 2009 16:51:41 -0700
Subject: Does python have the capability for driver development ? Maybe
	with ShedSkin
In-Reply-To: 
References: 
Message-ID: <4a7f6018$0$1642$742ec2ed@news.sonic.net>

MalC0de wrote:
> hello there, I've a question :
> I want to know does python have any capability for using Ring0 and
> kernel functions for driver and device development stuff .
> if there's such a feature it is very good, and if there something for
> this kind that you know please refer me to some reference and show me
> some snippet .
> 
> thanks
> 
> - Malc0de

     With the CPython interpretive system, it's not likely to work. But
using ShedSkin, which generates hard machine code, it might be possible.
The main problem is that Shed Skin uses a garbage-collected environment,
which few kernels have.

     Under QNX, which is a a real message-passing operating system with
all drivers in user space, it should be possible to write a driver in
Python.  There's Python for QNX.  It would probably be too slow to
be useful, though.

     I've actually written a handler for Baudot Teletype machines in
Python.  See

     https://sourceforge.net/projects/baudotrss/

Those machines are so slow (45.45 baud) that Python isn't the bottleneck.

					John Nagle


From python at mrabarnett.plus.com  Sun Aug  9 19:51:48 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Mon, 10 Aug 2009 00:51:48 +0100
Subject: Bug or feature: double strings as one
In-Reply-To: 
References: 			<000674d6$0$2895$c3e8da3@news.astraweb.com>		<7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com>		<21131b4b-67d3-4ddf-b061-60327d670ca7@l31g2000vbp.googlegroups.com>	<6cdaacf6-a560-483e-a14d-26396173e3bd@o35g2000vbi.googlegroups.com>
	
Message-ID: <4A7F6114.9020402@mrabarnett.plus.com>

Jan Kaliszewski wrote:
> 09-08-2009 o 23:43:14 r  wrote:
> 
>> #-- el bueno --#
>> "hello i am a very long string that\
>> does not like newlines so please \
>> escape me, Thank you!"
> 
> You probably ment: """hello i am... [etc.]
> 
> Anyway... You're right that generally it's good idea to define
> dialog prompts and such stuff separately rather that to hardcode
> it, especially in big projects. Then certainly multiline
> string literals are useful (though, if you need to get rid of
> newlines, IMHO "el feo" method is more elegant and less error
> prone than your "el bueno" [possible invisible space after '\']).
> 
> But there are plenty of other situations when it's better
> (in practice) to have strings (even long) together with your
> code, e.g. log information for debugging, or
> 
Here's an idea that you're probably going to hate: indented strings. :-)

A string prefixed with 'i' would be an 'indented' string. Leading space
and tab characters at the start of the string (just after the quote) or
the start of each line within a multiline string would be ignored.

 >>> """Line 1
        Line 2
"""
'Line 1\n       Line 2\n'
 >>> i"""Line 1
        Line 2
"""
'Line 1\nLine 2\n'

An additional feature could be to make '\ ' == ' ', perhaps only for
indented strings if you're worried that it could breaking existing code:

 >>> i"""Line 1
\       Line 2
"""
'Line 1\n       Line 2\n'

This would save you having to write '\x20'.


From steve at REMOVE-THIS-cybersource.com.au  Sun Aug  9 20:06:18 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 00:06:18 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
Message-ID: <0008e7c1$0$2880$c3e8da3@news.astraweb.com>

On Sun, 09 Aug 2009 12:26:54 -0700, Douglas Alan wrote:

> A friend of mine is just learning Python, and he's a bit tweaked about
> how unrecognized escape sequences are treated in Python.
...
> In any case, I think my friend should mellow out a bit, but we both
> consider this something of a wart. He's just more wart-phobic than I am.
> Is there any way that this behavior can be considered anything other
> than a wart? Other than the unconvincing claim that you can use this
> "feature" to save you a bit of typing sometimes when you actually want a
> backslash to be in your string?

I'd put it this way: a backslash is just an ordinary character, except 
when it needs to be special. So Python's behaviour is "treat backslash as 
a normal character, except for these exceptions" while the behaviour your 
friend wants is "treat a backslash as an error, except for these 
exceptions".

Why should a backslash in a string literal be an error?



-- 
Steven


From bouncyinc at gmail.com  Sun Aug  9 20:42:26 2009
From: bouncyinc at gmail.com (John Haggerty)
Date: Sun, 9 Aug 2009 18:42:26 -0600
Subject: getting a "simple" program to work
Message-ID: 

ok so I know this is one of those "weird" requests but here me out.
So far I have an issue with a package for python called "libgmail" which is
basically a gmail interface for python to send messages remoetly.

Works ok except that the 'sendMessage' routine is bad.

This is included in the above attachment

it's used in a program called "ogss" which is an sms interface to gmail to
basically read gmail and then have a command done on a remote machine and
then spat out on the local machine to a log file that's opened and then
emailed back

problem is that the sending back routine fails.

Now I've found a program that will more or less do what is requied but it's
not really exactly what would be used in that it doesn't use the libgmail
routine.

So far the maintainer of both packages seem to be afk or not having their
routines fixed and so far debian/Unbuntu claim that the last version of the
package has been fixed :(

Is there a recommendatin of how to combine/alter so that ogss can transmit?
My main issue is that python is lesser known to me than Chinese (which I
also don't know).

My idea of this is to have a remote email timeclock program which could then
be scripted with any language or just "echo >>blah" if necessary.

Thanks in advance :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: libgmail.py
Type: text/x-python
Size: 54655 bytes
Desc: not available
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: ogss.py
Type: text/x-python
Size: 6241 bytes
Desc: not available
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: send2.py
Type: text/x-python
Size: 2088 bytes
Desc: not available
URL: 

From bbxx789_05ss at yahoo.com  Sun Aug  9 20:55:26 2009
From: bbxx789_05ss at yahoo.com (7stud)
Date: Sun, 9 Aug 2009 17:55:26 -0700 (PDT)
Subject: Monkeypatching an object to become callable
References: <87hbwgu7xa.fsf@vostro.rath.org>
Message-ID: <0aa46ece-64b9-4c28-b690-5ac5937ce3f2@f20g2000prn.googlegroups.com>

On Aug 9, 1:02?pm, Nikolaus Rath  wrote:
> Hi,
>
> I want to monkeypatch an object so that it becomes callable, although
> originally it is not meant to be. (Yes, I think I do have a good reason
> to do so).
>
> But simply adding a __call__ attribute to the object apparently isn't
> enough, and I do not want to touch the class object (since it would
> modify all the instances):
>
> >>> class foo(object):
>
> ... ? pass
> ...>>> t = foo()
> >>> def test():
>
> ... ? print 'bar'
> ...>>> t()
>
> Traceback (most recent call last):
> ? File "", line 1, in 
> TypeError: 'foo' object is not callable>>> t.__call__ = test
> >>> t()
>
> Traceback (most recent call last):
> ? File "", line 1, in 
> TypeError: 'foo' object is not callable>>> t.__call__()
>
> bar
>
> Is there an additional trick to get it to work?
>
> Best,
>
> ? ?-Nikolaus
>
> --
> ??Time flies like an arrow, fruit flies like a Banana.?
>
> ? PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 ?02CF A9AD B7F8 AE4E 425C


With an old-style class your code will work:

class A:
    pass

def test():
    print "test"

a = A()
a.__call__ = test

a()

--output:--
test


a2 = A()
a2()

--output:--

    a2()
AttributeError: A instance has no __call__ method



Another option is to use the *decorator pattern*.  The decorator
pattern can be used when you want to add additional methods and
attributes to an object, and you don't want to disturb the original
class:

class A(object):
    def __init__(self, x):
        self.x = x

    def sayhi(self):
        print "hi"


class Wrapper(object):
    def __init__(self, obj, func):
        self.obj = obj
        self.func = func

    def __call__(self, *args):
        return self.func(*args)

    def __getattr__(self, name):
        return object.__getattribute__(self.obj, name)


def test():
    print "test"

a = A(10)
w = Wrapper(a, test)
w()
print w.x
w.sayhi()

--output:--
test
10
hi



From darkwater42 at gmail.com  Sun Aug  9 20:56:55 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Sun, 9 Aug 2009 17:56:55 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
Message-ID: 

Steven D'Aprano wrote:

> Why should a backslash in a string literal be an error?

Because in Python, if my friend sees the string "foo\xbar\n", he has
no idea whether the "\x" is an escape sequence, or if it is just the
characters "\x", unless he looks it up in the manual, or tries it out
in the REPL, or what have you. My friend is adamant that it would be
better if he could just look at the string literal and know. He
doesn't want to be bothered to have to store stuff like that in his
head. He wants to be able to figure out programs just by looking at
them, to the maximum degree that that is feasible.

In comparison to Python, in C++, he can just look "foo\xbar\n" and
know that "\x" is a special character. (As long as it compiles without
warnings under g++.)

He's particularly annoyed too, that if he types "foo\xbar" at the
REPL, it echoes back as "foo\\xbar". He finds that to be some sort of
annoying DWIM feature, and if Python is going to have DWIM features,
then it should, for example, figure out what he means by "\" and not
bother him with a syntax error in that case.

Another reason that Python should not behave the way that it does, is
that it pegs Python into a corner where it can't add new escape
sequences in the future, as doing so will break existing code.
Generating a syntax error instead for unknown escape sequences would
allow for future extensions.

Now not to pick on Python unfairly, most other languages have similar
issues with escape sequences. (Except for the Bourne Shell and bash,
where "\x" always just means "x", no matter what character "x" happens
to be.) But I've been telling my friend for years to switch to Python
because of how wonderful and consistent Python is in comparison to
most other languages, and now he seems disappointed and seems to think
that Python is just more of the same.

Of course I think that he's overreacting a bit. My point of view is
that every language has *some* warts; Python just has a bit fewer than
most. It would have been nice, I should think, if this wart had been
"fixed" in Python 3, as I do consider it to be a minor wart.

|>ouglas



From pavlovevidence at gmail.com  Sun Aug  9 21:34:14 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sun, 9 Aug 2009 18:34:14 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
Message-ID: 

On Aug 9, 5:06?pm, Steven D'Aprano  wrote:
> On Sun, 09 Aug 2009 12:26:54 -0700, Douglas Alan wrote:
> > A friend of mine is just learning Python, and he's a bit tweaked about
> > how unrecognized escape sequences are treated in Python.
> ...
> > In any case, I think my friend should mellow out a bit, but we both
> > consider this something of a wart. He's just more wart-phobic than I am.
> > Is there any way that this behavior can be considered anything other
> > than a wart? Other than the unconvincing claim that you can use this
> > "feature" to save you a bit of typing sometimes when you actually want a
> > backslash to be in your string?
>
> I'd put it this way: a backslash is just an ordinary character, except
> when it needs to be special. So Python's behaviour is "treat backslash as
> a normal character, except for these exceptions" while the behaviour your
> friend wants is "treat a backslash as an error, except for these
> exceptions".
>
> Why should a backslash in a string literal be an error?

Because the behavior of \ in a string is context-dependent, which
means a reader can't know if \ is a literal character or escape
character without knowing the context, and it means an innocuous
change in context can cause a rather significant change in \.

IOW it's an error-prone mess.  It would be better if Python (like C)
treated \ consistently as an escape character.  (And in raw strings,
consistently as a literal.)

It's kind of a minor issue in terms of overall real-world importance,
but in terms of raw unPythonicness this might be the worst offense the
language makes.


Carl Banks


From darkwater42 at gmail.com  Sun Aug  9 22:42:56 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Sun, 9 Aug 2009 19:42:56 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
Message-ID: <1cf80e77-416b-43be-8491-0b7b7494aa92@s6g2000vbp.googlegroups.com>

On Aug 9, 8:06?pm, Steven D'Aprano wrote:

> while the behaviour your
> friend wants is "treat a backslash as an error, except for these
> exceptions".

Besides, can't all error situations be described as, "treat the error
situation as an error, except for the exception of when the situation
isn't an error"???

The behavior my friend wants isn't any more exceptional than that!

|>ouglas


From mensanator at aol.com  Sun Aug  9 22:46:52 2009
From: mensanator at aol.com (Mensanator)
Date: Sun, 9 Aug 2009 19:46:52 -0700 (PDT)
Subject: pybotwar-0.5
References: 
Message-ID: <3e9c5fcd-4047-4edd-b2ec-d892c77e3a69@f33g2000vbm.googlegroups.com>

On Aug 9, 3:26?pm, Lee Harr  wrote:
> pybotwar is a fun and educational game where players
> create computer programs to control simulated robots
> to compete in a battle arena.
>
> http://pybotwar.googlecode.com/

Why is the doc folder empty?

Shouldn't you supply some hint on how the games works
and at least a rudimentary guide to robot design?

What version to you expect that will be in? 1.0? 10.0?

Could you inform us when you have something worth looking
at and not before so we don't have to waste our time?


>
> pybotwar uses pybox2d for the physical simulation,
> and uses pygame and pygsear for the visualization.
>
> pybotwar is released under GPLv3.
>
> Changes in pybotwar-0.5:
> ? ? - added tournament mode
> ? ? - added explosive shells
> ? ? - robots are now damaged by colliding with walls or other robots
> ? ? - added damage sensor
> ? ? - added gyro sensor
> ? ? - added configurable cannon reload time
> ? ? - added robot statistics database
> ? ? - added time limit for robot startup/ initialization
> ? ? - health bar changes color below 30% health
> ? ? - fixed force/ torque possibly going over 100%
> ? ? - fixed problem with non-integer force/ torque values
> ? ? - each robot gets its own log file in test mode
> ? ? - send robot errors to log file
> ? ? - use optparse for cmd line options
>
> _________________________________________________________________
> More than messages?check out the rest of the Windows Live?.http://www.microsoft.com/windows/windowslive/



From xahlee at gmail.com  Sun Aug  9 23:04:43 2009
From: xahlee at gmail.com (Xah Lee)
Date: Sun, 9 Aug 2009 20:04:43 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
Message-ID: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>

The prob with python docs is with the python priests.

there are frequent posts about python doc's poor quality, and some
efforts to improve the doc (such as wiki or seggestions), about few
times a year (in so much as i've seen), the typical response is
pissing fight, with python priests to tell them not to start another
wiki, or ?you should apply in our church first and formulate a PEP
proposal first or kindly donate or otherwise fuckoff?, and so on.

i've wrote several articles about this issue, total time spend on this
is probably more than 2 months full-time work. See:

? Python Documentation Problems
  http://xahlee.org/perl-python/python_doc_index.html

just about each article above generates a thread of flames.

I also have re-wrote the entire python regex doc in 2005:

? Pyhton Regex Documentation: String Pattern Matching
  http://xahlee.org/perl-python/python_re-write/lib/module-re.html

there are some positive reviews, but most are drawn out by nay-sayers.

I often receive thank you emails for 2 particular articles, which are
most frequently google searched as indicated by my weblog:

? Python Doc Problem Example: gzip
  http://xahlee.org/perl-python/python_doc_gzip.html

? Python Doc Problem Example: sort()
  http://xahlee.org/perl-python/python_doc_sort.html

? Sorting in Python and Perl
  http://xahlee.org/perl-python/sort_list.html

See also:

? Language, Purity, Cult, and Deception
  http://xahlee.org/UnixResource_dir/writ/lang_purity_cult_deception.html

  Xah
? http://xahlee.org/

?

On Jul 31, 1:10 pm, kj  wrote:
> I'm pretty new to Python, and I like a lot overall, but I find the
> documentation for Python rather poor, overall.
>
> I'm sure that Python experts don't have this problem: they have
> internalized some good ways to access the documentation, are
> productive with it, and therefore have lost the ability to see why
> the Python documentations is deficient for beginners.  This explains
> why a suboptimal situation can persist like this: those who are
> most able fix it are also the least able to perceive it.
>
> I've heard similar complaints from other experienced programmers
> who are trying out Python for the first time: poor documentation.
>
> Here is an *entirely typical* example: on some Unix, try
>
> % pydoc urllib
>
> The displayed documentation mention the optional parameter "data"
> in practically every function listed (a few dozen of them).  This
> parameter is not documented *anywhere* on that page.  All that we
> are told is that its default value is always None.
>
> I'm sure that I can find a full description of this parameter if
> I fire up Google, and search online.  In fact, more likely than
> not, I'll find far more documentation than I want.  But my point
> is that a programmer should not need to do this.  The full
> documentation should be readily accessible directly through a few
> keystrokes.
>
> I would love to know how experienced Python programmers quickly
> zero in on the Python documentation they need.
>
> TIA!
>
> kynn



From spamgrinder.trylater at ggmail.com  Sun Aug  9 23:43:41 2009
From: spamgrinder.trylater at ggmail.com (AlF)
Date: Sun, 09 Aug 2009 20:43:41 -0700
Subject: reloading the module imported as 'from ... import ...'
Message-ID: <4A7F976D.7090600@ggmail.com>

Hi,

what is the best way to reload the module imported using 'from ... 
import ...'

Is following a way to do so?


 >>> from email.charset import Charset
 >>> reload(email.charset)
Traceback (most recent call last):
   File "", line 1, in 
NameError: name 'email' is not defined
 >>>
 >>>
 >>> import email.charset
 >>> reload(email.charset)

References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
Message-ID: <1bcfbcd867677baf95b4ab8d685dbe44@preisshare.net>


Since you're talking about documentation, which is a part of python,
don't you think you should be discussing it on python-dev ?

That's where discussions about the documentation should be held.

haha - I'm just curious to see how long it will for them to
shut the discussion down. 

Before you do that, you should clearly work out in your own mind
how you think things need to improve. It's not good enough just
saying this or that is bad without having specific ideas on what
needs to change.

Good luck fellow sinner and blasphemer...

How dare you suggest that things could be improved...


On Sun, 9 Aug 2009 20:04:43 -0700 (PDT), Xah Lee  wrote:
> The prob with python docs is with the python priests.
> 
> there are frequent posts about python doc's poor quality, and some
> efforts to improve the doc (such as wiki or seggestions), about few
> times a year (in so much as i've seen), the typical response is
> pissing fight, with python priests to tell them not to start another
> wiki, or ?you should apply in our church first and formulate a PEP
> proposal first or kindly donate or otherwise fuckoff?, and so on.
> 
> i've wrote several articles about this issue, total time spend on this
> is probably more than 2 months full-time work. See:
> 
> ? Python Documentation Problems
>   http://xahlee.org/perl-python/python_doc_index.html
> 
> just about each article above generates a thread of flames.
> 
> I also have re-wrote the entire python regex doc in 2005:
> 
> ? Pyhton Regex Documentation: String Pattern Matching
>   http://xahlee.org/perl-python/python_re-write/lib/module-re.html
> 
> there are some positive reviews, but most are drawn out by nay-sayers.
> 
> I often receive thank you emails for 2 particular articles, which are
> most frequently google searched as indicated by my weblog:
> 
> ? Python Doc Problem Example: gzip
>   http://xahlee.org/perl-python/python_doc_gzip.html
> 
> ? Python Doc Problem Example: sort()
>   http://xahlee.org/perl-python/python_doc_sort.html
> 
> ? Sorting in Python and Perl
>   http://xahlee.org/perl-python/sort_list.html
> 
> See also:
> 
> ? Language, Purity, Cult, and Deception
>   http://xahlee.org/UnixResource_dir/writ/lang_purity_cult_deception.html
> 
>   Xah
> ? http://xahlee.org/
> 
> ?
> 
> On Jul 31, 1:10 pm, kj  wrote:
>> I'm pretty new to Python, and I like a lot overall, but I find the
>> documentation for Python rather poor, overall.
>>
>> I'm sure that Python experts don't have this problem: they have
>> internalized some good ways to access the documentation, are
>> productive with it, and therefore have lost the ability to see why
>> the Python documentations is deficient for beginners.  This explains
>> why a suboptimal situation can persist like this: those who are
>> most able fix it are also the least able to perceive it.
>>
>> I've heard similar complaints from other experienced programmers
>> who are trying out Python for the first time: poor documentation.
>>
>> Here is an *entirely typical* example: on some Unix, try
>>
>> % pydoc urllib
>>
>> The displayed documentation mention the optional parameter "data"
>> in practically every function listed (a few dozen of them).  This
>> parameter is not documented *anywhere* on that page.  All that we
>> are told is that its default value is always None.
>>
>> I'm sure that I can find a full description of this parameter if
>> I fire up Google, and search online.  In fact, more likely than
>> not, I'll find far more documentation than I want.  But my point
>> is that a programmer should not need to do this.  The full
>> documentation should be readily accessible directly through a few
>> keystrokes.
>>
>> I would love to know how experienced Python programmers quickly
>> zero in on the Python documentation they need.
>>
>> TIA!
>>
>> kynn


From lokeshmaremalla at gmail.com  Mon Aug 10 01:07:37 2009
From: lokeshmaremalla at gmail.com (Lokesh Maremalla)
Date: Mon, 10 Aug 2009 10:37:37 +0530
Subject: Need help in configuration for TimedRotatingFileHandler
In-Reply-To: <4A7F3C83.1040607@ieee.org>
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
	<4A7F3C83.1040607@ieee.org>
Message-ID: 

Hi Dave,

I have modified the code as mentioned in reply and is working fine. But
still i am facing an issue and the issue is described below.

In configuration file i have coded the TimedRotatingFileHandler like
args=("G:\\lok_sib\\logs\\rotate_test", 'D', 1)

step1: Executed the code and got the log file with the information
step2: Modified the system time from current day to next day
step3: End up with the error and the error is pasted below

Traceback (most recent call last):
  File "c:\Python25\lib\logging\handlers.py", line 74, in emit
    self.doRollover()
  File "c:\Python25\lib\logging\handlers.py", line 274, in doRollover
    os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is
being used by another process

Python version - 2.5.4

Thanks for your time.

Regards,
Lokesh


On Mon, Aug 10, 2009 at 2:45 AM, Dave Angel  wrote:

> Lokesh wrote:
>
>> Hi,
>>
>> Need help in configure the TimedRotatingFileHandler from configuration
>> file
>>
>> I have tried with the below code and ended up with the error, code is
>> pasted below
>> Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
>> \logs\rotate_test'
>> [loggers]
>> keys=root,simpleExample
>>
>> [handlers]
>> keys=consoleHandler,timedRotatingFileHandler
>>
>> [formatters]
>> keys=simpleFormatter
>>
>> [logger_root]
>> level=DEBUG
>> handlers=consoleHandler
>>
>> [logger_simpleExample]
>> level=DEBUG
>> handlers=timedRotatingFileHandler
>> qualname=simpleExample
>> propagate=0
>>
>> [handler_consoleHandler]
>> class=StreamHandler
>> level=DEBUG
>> formatter=simpleFormatter
>> args=(sys.stdout,)
>>
>> [handler_timedRotatingFileHandler]
>> class=handlers.TimedRotatingFileHandler
>> level=DEBUG
>> formatter=simpleFormatter
>> args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)
>>
>> [formatter_simpleFormatter]
>> format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
>> datefmt='%Y-%m-%d %H:%M:%S'
>>
>>
>> Thanks or your time
>> Regards,
>> Lokesh
>>
>>
>>
> I don't see code there, I see lots of config data, presumably in an .ini
> file.   So I don't know how you're reading it in, and converting it to
> Python variables, but I know where I'd look, based on your error message.
>
> The following line:
>
> args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)
>
> seems to contain a Python string.  But there are unescaped backslashes
> within it.  You can get away with it in two cases, because \l  isn't a valid
> escape sequence.  But in the case of \r, it looks like a newline character.
>
> Anyway, all three of those backslashes probably need to be doubled.
>
> args=("G:\\lok_sib\\logs\\rotate_test", 'midnight', 1)
>
> Two other cures that may work, depending on context:   change the
> backslashes to forward slashes, or use a raw string.
>
> But as I said earlier, you don't show in any way what code is interpreting
> this line, so it's all just guesswork.
>
> DaveA
>
>


-- 
Thanks & Regards,
Lokesh.
lokeshmaremalla at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From lokeshmaremalla at gmail.com  Mon Aug 10 01:21:09 2009
From: lokeshmaremalla at gmail.com (Lokesh Maremalla)
Date: Mon, 10 Aug 2009 10:51:09 +0530
Subject: Need help in configuration for TimedRotatingFileHandler
In-Reply-To: 
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
	<4A7F3C83.1040607@ieee.org>
	
Message-ID: 

Hi Dave,

I forgot to provide the information about the code how I am using logger
Here is the complete scenario

I have modified the code as mentioned in reply and is working fine. But
still I am facing an issue and the issue is described below.

In configuration file i have coded the TimedRotatingFileHandler like
args=("G:\\lok_sib\\logs\\rotate_test", 'D', 1)

Code:
mlogger = logging.getLogger("simpleExample")
def a_view(request):
    mlogger.debug("a_view called")
    if request.method== "POST" :
        mlogger.debug("post function")
    else:
        mlogger.debug("serve function")

Execution:
step1: Executed the code and got the log file with the information
step2: Modified the system time from current day to next day
step3: End up with the error and the error is pasted below

Traceback (most recent call last):
  File "c:\Python25\lib\logging\handlers.py", line 74, in emit
    self.doRollover()
  File "c:\Python25\lib\logging\handlers.py", line 274, in doRollover
    os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is
being used by another process

Python version - 2.5.4

I guess my output should be like this for the next day
-a new log file rotate_test. should generate in the respective
location

Please correct me if I am wrong.


Thanks for your time.

Regards,
Lokesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From timr at probo.com  Mon Aug 10 01:31:27 2009
From: timr at probo.com (Tim Roberts)
Date: Sun, 09 Aug 2009 22:31:27 -0700
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
Message-ID: 

Kosta  wrote:
>
>
>What I would like to do, is to open a cmd window, and start a Python
>script.  This script would then (based upon input arguments), build
>different flavors of the driver (fre, chk, x86, x64) and do some post
>processing (create cat files, sign, etc.).
>
>I was hoping to take advantage as much as possible of exisiting
>infrastructure from the WDK.  I am able to call setenv.bat and provide
>all the input parameters.  One of the things setenv.bat does is change
>the path environment variable.  However, this is not captured by
>Python.  I could duplicate the functionality, but I'd rather not.  Is
>there a way to capture all enviroment variable changes being made by a
>batch file from Python?

My suggestion is that you just call "setenv" again every time you start a
new process.  My "build everything" batch file has a series of sections
something like this:

  setlocal
  set LAST=%CD%
  call %DDK%\bin\setenv %DDK% chk WXP no_oacr
  @echo on
  set USERNAME=timr
  cd %LAST%
  build %BLD%
  endlocal

  setlocal
  set LAST=%CD%
  call %DDK%\bin\setenv %DDK% fre WXP no_oacr
  @echo on
  set USERNAME=timr
  cd %LAST%
  build %BLD%
  endlocal

  setlocal
  set LAST=%CD%
  call %DDK%\bin\setenv %DDK% chk WLH x64 no_oacr
  @echo on
  set USERNAME=timr
  cd %LAST%
  build %BLD%
  endlocal
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 01:32:36 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 05:32:36 GMT
Subject: reloading the module imported as 'from ... import ...'
References: <4A7F976D.7090600@ggmail.com>
Message-ID: 

On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:

> Hi,
> 
> what is the best way to reload the module imported using 'from ...
> import ...'


Have you tried "from ... import ..." again?



-- 
Steven


From timr at probo.com  Mon Aug 10 01:34:41 2009
From: timr at probo.com (Tim Roberts)
Date: Sun, 09 Aug 2009 22:34:41 -0700
Subject: Pywin32 @ windows 7
References: 
Message-ID: 

"Algirdas Brazas"  wrote:
>
>Did anyone manage to get windows extensions installet on windows 7 64 bit? As 
>far as I try I get only "Setup program invalid or damaged".

I've been running 32-bit Python 2.5 and the 32-bit versions of PyWin32 and
wxPython on Windows 7 64-bit for many months.  No problems.

I have not tried the 64-bit Python and PyWin32 builds yet.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.


From timr at probo.com  Mon Aug 10 01:42:45 2009
From: timr at probo.com (Tim Roberts)
Date: Sun, 09 Aug 2009 22:42:45 -0700
Subject: Windows 7 : any problems installing or running Python ?
References: 
Message-ID: 

Dave WB3DWE wrote:
>
>Anybody tried it ? 
>Is anything broken, ie is the whole shootin' match good to go ?
>I'm esp interested in WConio for 3.0/3.1 which I use heavily.

I've been running the 32-bit builds of Python 2.5, PyWin32, and wxPython on
Windows 7 64-bit for many months.  No problems at all.

I hated Vista; I would only run it if my clients insisted on having their
drivers tested on it.  Vista SP1 was somewhat better, but I don't mind
Windows 7 at all.  I might even upgrade my primary development machine from
XP.  A number of the usually cranky driver developers have expressed the
same opinion.  Microsoft might actually have a winner here.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.


From spamgrinder.trylater at ggmail.com  Mon Aug 10 01:48:31 2009
From: spamgrinder.trylater at ggmail.com (AlF)
Date: Sun, 09 Aug 2009 22:48:31 -0700
Subject: reloading the module imported as 'from ... import ...'
In-Reply-To: 
References: <4A7F976D.7090600@ggmail.com>
	
Message-ID: <4A7FB4AF.7060107@ggmail.com>

Steven D'Aprano wrote:
> On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:
> 
>> Hi,
>>
>> what is the best way to reload the module imported using 'from ...
>> import ...'
> 
> 
> Have you tried "from ... import ..." again?
> 

I have not because of an assumption that "import" imports the module 
just once. In fact this still works that way:

here is a terminal 1:

$ cat > a.py
a=1
$ cat > a.py
a=2
$


and terminal 2:

 >>> from a import a
 >>> a
1
 >>> a
1
 >>> from a import a
 >>> a
1
 >>>

In spite of changing a.py in fly, the imported a is still 1




From julien.chevalier at gmail.com  Mon Aug 10 01:58:31 2009
From: julien.chevalier at gmail.com (Kiki)
Date: Sun, 9 Aug 2009 22:58:31 -0700 (PDT)
Subject: Client/Server based on SocketServer and Windows
References: 
	
Message-ID: <979ad93c-0257-4add-8fb7-b56e253e3fb7@h30g2000vbr.googlegroups.com>

Thank you Dennis

I'm using 2 differents editor, which may be the cause of such a mess
in the indentation.

I must admitt that I lazily rely on those (not so bad indeed) editors.

"If indentation whas bad they would have tell me"

Too bad am i

Won't post misindeted code anymore.


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 02:03:05 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 06:03:05 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
Message-ID: 

On Sun, 09 Aug 2009 17:56:55 -0700, Douglas Alan wrote:

> Steven D'Aprano wrote:
> 
>> Why should a backslash in a string literal be an error?
> 
> Because in Python, if my friend sees the string "foo\xbar\n", he has no
> idea whether the "\x" is an escape sequence, or if it is just the
> characters "\x", unless he looks it up in the manual, or tries it out in
> the REPL, or what have you. 

Fair enough, but isn't that just another way of saying that if you look 
at a piece of code and don't know what it does, you don't know what it 
does unless you look it up or try it out?


> My friend is adamant that it would be better
> if he could just look at the string literal and know. He doesn't want to
> be bothered to have to store stuff like that in his head. He wants to be
> able to figure out programs just by looking at them, to the maximum
> degree that that is feasible.

I actually sympathize strongly with that attitude. But, honestly, your 
friend is a programmer (or at least pretends to be one *wink*). You can't 
be a programmer without memorizing stuff: syntax, function calls, modules 
to import, quoting rules, blah blah blah. Take C as an example -- there's 
absolutely nothing about () that says "group expressions or call a 
function" and {} that says "group a code block". You just have to 
memorize it. If you don't know what a backslash escape is going to do, 
why would you use it? I'm sure your friend isn't in the habit of randomly 
adding backslashes to strings just to see whether it will still compile.

This is especially important when reading (as opposed to writing) code. 
You read somebody else's code, and see "foo\xbar\n". Let's say you know 
it compiles without warning. Big deal -- you don't know what the escape 
codes do unless you've memorized them. What does \n resolve to? chr(13) 
or chr(97) or chr(0)? Who knows? 

Unless you know the rules, you have no idea what is in the string. 
Allowing \y to resolve to a literal backslash followed by y doesn't 
change that. All it means is that some \c combinations return a single 
character, and some return two.



> In comparison to Python, in C++, he can just look "foo\xbar\n" and know
> that "\x" is a special character. (As long as it compiles without
> warnings under g++.)

So what you mean is, he can just look at "foo\xbar\n" AND COMPILE IT 
USING g++, and know whether or not \x is a special character.

[sarcasm] Gosh. That's an enormous difference from Python, where you have 
to print the string at the REPL to know what it does. [/sarcasm]

Aside:
\x isn't a special character:

>>> "\x"
ValueError: invalid \x escape

However, \xba is:

>>> "\xba"
'\xba'
>>> len("\xba")
1
>>> ord("\xba")
186



> He's particularly annoyed too, that if he types "foo\xbar" at the REPL,
> it echoes back as "foo\\xbar". He finds that to be some sort of annoying
> DWIM feature, and if Python is going to have DWIM features, then it
> should, for example, figure out what he means by "\" and not bother him
> with a syntax error in that case.

Now your friend is confused. This is a good thing. Any backslash you see 
in Python's default string output is *always* an escape:

>>> "a string with a 'proper' escape \t (tab)"
"a string with a 'proper' escape \t (tab)"
>>> "a string with an 'improper' escape \y (backslash-y)"
"a string with an 'improper' escape \\y (backslash-y)"

The REPL is actually doing him a favour. It always escapes backslashes, 
so there is no ambiguity. A backslash is displayed as \\, any other \c is 
a special character.


> Of course I think that he's overreacting a bit. 

:)


> My point of view is that
> every language has *some* warts; Python just has a bit fewer than most.
> It would have been nice, I should think, if this wart had been "fixed"
> in Python 3, as I do consider it to be a minor wart.

And if anyone had cared enough to raise it a couple of years back, it 
possibly might have been.


-- 
Steven


From nagle at animats.com  Mon Aug 10 02:03:14 2009
From: nagle at animats.com (John Nagle)
Date: Sun, 09 Aug 2009 23:03:14 -0700
Subject: Unrecognized escape sequences in string literals
In-Reply-To: 
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
Message-ID: <4a7fb72d$0$1589$742ec2ed@news.sonic.net>

Carl Banks wrote:
> IOW it's an error-prone mess.  It would be better if Python (like C)
> treated \ consistently as an escape character.  (And in raw strings,
> consistently as a literal.)

    Agreed.  For one thing, if another escape character ever has to be
added to the language, that may change the semantics of previously
correct strings.  If "\" followed by a non-special character is treated
as an error, that doesn't happen.

					John Nagle


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 02:10:53 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 06:10:53 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
Message-ID: 

On Sun, 09 Aug 2009 18:34:14 -0700, Carl Banks wrote:

>> Why should a backslash in a string literal be an error?
> 
> Because the behavior of \ in a string is context-dependent, which means
> a reader can't know if \ is a literal character or escape character
> without knowing the context, and it means an innocuous change in context
> can cause a rather significant change in \.

*Any* change in context is significant with escapes.

"this \nhas two lines"

If you change the \n to a \t you get a significant difference. If you 
change the \n to a \y you get a significant difference. Why is the first 
one acceptable but the second not?


> IOW it's an error-prone mess.

I've never had any errors caused by this. I've never seen anyone write to 
this newsgroup confused over escape behaviour, or asking for help with an 
error caused by it, and until this thread, never seen anyone complain 
about it either.

Excuse my cynicism, but I believe that you are using "error-prone" to 
mean "I don't like this behaviour" rather than "it causes lots of errors".



-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 02:21:36 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 06:21:36 GMT
Subject: reloading the module imported as 'from ... import ...'
References: <4A7F976D.7090600@ggmail.com>
	
	<4A7FB4AF.7060107@ggmail.com>
Message-ID: 

On Sun, 09 Aug 2009 22:48:31 -0700, AlF wrote:

> Steven D'Aprano wrote:
>> On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:
>> 
>>> Hi,
>>>
>>> what is the best way to reload the module imported using 'from ...
>>> import ...'
>> 
>> 
>> Have you tried "from ... import ..." again?
>> 
>> 
> I have not because of an assumption that "import" imports the module
> just once. 

Ah, of course the cached module will still reflect the older version. 
Sorry, I was thinking about solving a different problem:

- In module "main" call "from A import a"
- Some other part of your code modifies A.a
- You want to have the imported a be refreshed with the value of A.a


No, my suggestion won't help in this situation.

Instead, you can:

(1) Delete the module from sys.modules, forcing Python to re-read it from 
disk:

import sys
del sys.modules['A']
from A import a

or

(2) Recognize that Python doesn't specifically support what you're trying 
to do. reload() is a convenience function, and you probably should stick 
to the "import A; A.a" form.


-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 02:23:20 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 06:23:20 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	<4a7fb72d$0$1589$742ec2ed@news.sonic.net>
Message-ID: 

On Sun, 09 Aug 2009 23:03:14 -0700, John Nagle wrote:

> if another escape character ever has to be
> added to the language, that may change the semantics of previously
> correct strings.

And that's the only argument in favour of prohibiting non-special 
backslash sequences I've seen yet that is even close to convincing.


-- 
Steven


From darkwater42 at gmail.com  Mon Aug 10 03:32:30 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Mon, 10 Aug 2009 00:32:30 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
Message-ID: <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>

On Aug 10, 2:03 am, Steven D'Aprano
 wrote:

> On Sun, 09 Aug 2009 17:56:55 -0700, Douglas Alan wrote:

> > Because in Python, if my friend sees the string "foo\xbar\n", he has no
> > idea whether the "\x" is an escape sequence, or if it is just the
> > characters "\x", unless he looks it up in the manual, or tries it out in
> > the REPL, or what have you.
>
> Fair enough, but isn't that just another way of saying that if you look
> at a piece of code and don't know what it does, you don't know what it
> does unless you look it up or try it out?

Not really. It's more like saying that easy things should be easy, and
hard things should possible. But in this case, Python is making
something that should be really easy, a bit harder and more error
prone than it should be.

In C++, if I know that the code I'm looking at compiles, then I never
need worry that I've misinterpreted what a string literal means. At
least not if it doesn't have any escape characters in it that I'm not
familiar with. But in Python, if I see, "\f\o\o\b\a\z", I'm not really
sure what I'm seeing, as I surely don't have committed to memory some
of the more obscure escape sequences. If I saw this in C++, and I knew
that it was in code that compiled, then I'd at least know that there
are some strange escape codes that I have to look up. Unlike with
Python, it would never be the case in C++ code that the programmer who
wrote the code was just too lazy to type in "\\f\\o\\o\\b\\a\\z"
instead.

> > My friend is adamant that it would be better
> > if he could just look at the string literal and know. He doesn't want to
> > be bothered to have to store stuff like that in his head. He wants to be
> > able to figure out programs just by looking at them, to the maximum
> > degree that that is feasible.
>
> I actually sympathize strongly with that attitude. But, honestly, your
> friend is a programmer (or at least pretends to be one *wink*).

Actually, he's probably written more code than you, me, and ten other
random decent programmers put together. As he can slap out massive
amounts of code very quickly, he'd prefer not to have crap getting in
his way. In the time it takes him to look something up, he might have
written another page of code.

He's perfectly capable of dealing with crap, as years of writing large
programs in Perl and PHP quickly proves, but his whole reason for
learning Python, I take it, is so that he will be bothered with less
crap and therefore write code even faster.

> You can't be a programmer without memorizing stuff: syntax, function
> calls, modules to import, quoting rules, blah blah blah. Take C as
> an example -- there's absolutely nothing about () that says "group
> expressions or call a function" and {} that says "group a code
> block".

I don't really think that this is a good analogy. It's like the
difference between remembering rules of grammar and remembering
English spelling. As a kid, I was the best in my school at grammar,
and one of the worst at speling.

> You just have to memorize it. If you don't know what a backslash
> escape is going to do, why would you use it?

(1) You're looking at code that someone else wrote, or (2) you forget
to type "\\" instead of "\" in your code (or get lazy sometimes), as
that is okay most of the time, and you inadvertently get a subtle bug.

> This is especially important when reading (as opposed to writing) code.
> You read somebody else's code, and see "foo\xbar\n". Let's say you know
> it compiles without warning. Big deal -- you don't know what the escape
> codes do unless you've memorized them. What does \n resolve to? chr(13)
> or chr(97) or chr(0)? Who knows?

It *is* a big deal. Or at least a non-trivial deal. It means that you
can tell just by looking at the code that there are funny characters
in the string, and not just a backslashes. You don't have to go
running for the manual every time you see code with backslashes, where
the upshot might be that the programmer was merely saving themselves
some typing.

> > In comparison to Python, in C++, he can just look "foo\xbar\n" and know
> > that "\x" is a special character. (As long as it compiles without
> > warnings under g++.)
>
> So what you mean is, he can just look at "foo\xbar\n" AND COMPILE IT
> USING g++, and know whether or not \x is a special character.

I'm not sure that your comments are paying due diligence to full
life-cycle software development issues that involve multiple
programmers (or even just your own program that you wrote a year ago,
and you don't remember all the details of what you did) combined with
maintaining and modifying existing code, etc.

> Aside:
> \x isn't a special character:
>
> >>> "\x"
>
> ValueError: invalid \x escape

I think that this all just goes to prove my friend's point! Here I've
been programming in Python for more than a decade (not full time, mind
you, as I also program in other languages, like C++), and even I
didn't know that "\xba" was an escape sequence, and I inadvertently
introduced a subtle bug into my argument because it just so happens
that the first two characters of "bar" are legal hexadecimal! If I did
the very same thing in a real program, it might take me a lot of time
to track down the bug.

Also, it seems that Python is being inconsistent here. Python knows
that
the string "\x" doesn't contain a full escape sequence, so why doesn't
it
treat the string "\x" the same way that it treats the string "\z"?
After all, if you're a Python programmer, you should know that "\x"
doesn't contain a complete escape sequence, and therefore, you would
not be surprised if Python were so kind as to just leave it alone,
rather than raising a ValueError.

I.e., "\z" is not a legal escape sequence, so it gets left as
"\\z". "\x" is not a legal escape sequence. Shouldn't it also get left
as "\\x"?

> > He's particularly annoyed too, that if he types "foo\xbar" at the REPL,
> > it echoes back as "foo\\xbar". He finds that to be some sort of annoying
> > DWIM feature, and if Python is going to have DWIM features, then it
> > should, for example, figure out what he means by "\" and not bother him
> > with a syntax error in that case.
>
> Now your friend is confused. This is a good thing. Any backslash you see
> in Python's default string output is *always* an escape:

Well, I think he's more annoyed that if Python is going to be so
helpful as to put in the missing "\" for you in "foo\zbar", then it
should put in the missing "\" for you in "\". He considers this to be
an
inconsistency.

Me, I'd never, ever, EVER want a language to special-case something at
the end of a string, but I can see that from his new-to-Python
perspective, Python seems to be DWIMing in one place and not the
other, and he thinks that it should either do no DWIMing at all, or
consistently DWIM. To not be consistent in this regard is "inelegant",
says he.

And I can see his point that allowing "foo\zbar" and "foo\\zbar" to be
synonymous is a form of DWIMing.

> > My point of view is that every language has *some* warts; Python
> > just has a bit fewer than most.  It would have been nice, I should
> > think, if this wart had been "fixed" in Python 3, as I do consider
> > it to be a minor wart.

> And if anyone had cared enough to raise it a couple of years back, it
> possibly might have been.

So, now if only my friend had learned Python years ago, when I told
him to, he possibly might be happy with Python by now!

|>ouglas


From pavlovevidence at gmail.com  Mon Aug 10 03:37:33 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Mon, 10 Aug 2009 00:37:33 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
Message-ID: 

On Aug 9, 11:10?pm, Steven D'Aprano
 wrote:
> On Sun, 09 Aug 2009 18:34:14 -0700, Carl Banks wrote:
> >> Why should a backslash in a string literal be an error?
>
> > Because the behavior of \ in a string is context-dependent, which means
> > a reader can't know if \ is a literal character or escape character
> > without knowing the context, and it means an innocuous change in context
> > can cause a rather significant change in \.
>
> *Any* change in context is significant with escapes.
>
> "this \nhas two lines"
>
> If you change the \n to a \t you get a significant difference. If you
> change the \n to a \y you get a significant difference. Why is the first
> one acceptable but the second not?

Because when you change \n to \t, you've haven't changed the meaning
of the \ character; but when you change \n to \y, you have, and you
did so without even touching the backslash.


> > IOW it's an error-prone mess.
>
> I've never had any errors caused by this.

Thank you for your anecdotal evidence.  Here's mine: This has gotten
me at least twice, and a compiler complaint would have reduced my bug-
hunting time from tens of minutes to ones of seconds.  [Aside: it was
when I was using Python on Windows for the first time]


> I've never seen anyone write to
> this newsgroup confused over escape behaviour, or asking for help with an
> error caused by it, and until this thread, never seen anyone complain
> about it either.

More anecdotal evidence.  Here's mine: I have.


> Excuse my cynicism, but I believe that you are using "error-prone" to
> mean "I don't like this behaviour" rather than "it causes lots of errors".

No, I'm using error-prone to mean error-prone.

Someone (obviously not you because you're have perfect knowledge of
the language and 100% situation awareness at all times) might have a
string like "abcd\stuv"  and change it to "abcd\tuvw" without even
thinking about the fact that the s comes after the backslash.

Worst of all: they might not even notice the error, because the repr
of this string is:

'abcd\tuwv'

They might not notice that the backslash is single, because (unlike
you) mortal fallible human beings don't always register tiny details
like a backslash being single when it should be double.

Point is, this is a very bad inconsistency.  It makes the behavior of
\ impossible to learn by analogy, now you have to memorize a list of
situations where it behaves one way or another.


Carl Banks


From darkwater42 at gmail.com  Mon Aug 10 03:57:18 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Mon, 10 Aug 2009 00:57:18 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
Message-ID: <246b6a1d-7e83-4ad3-9978-c2a55b884a6c@o13g2000vbl.googlegroups.com>

On Aug 10, 2:10?am, Steven D'Aprano

> I've never had any errors caused by this.

But you've seen an error caused by this, in this very discussion.
I.e., "foo\xbar".

"\xba" isn't an escape sequence in any other language that I've used,
which is one reason I made this error... Oh, wait a minute -- it *is*
an escape sequence in JavaScript. But in JavaScript, while "\xba" is a
special character, "\xb" is synonymous with "xb".

The fact that every language seems to treat these things similarly but
differently, is yet another reason why they should just be treated
utterly consistently by all of the languages: I.e., escape sequences
that don't have a special meaning should be an error!

> I've never seen anyone write to
> this newsgroup confused over escape behaviour,

My friend objects strongly the claim that he is "confused" by it, so I
guess you are right that no one is confused. He just thinks that it
violates the beautiful sense of aesthetics that he was sworn over and
over again Python to have.

But aesthetics is a non-negligible issue with practical ramifications.
(Not that anything can be done about this wart at this point,
however.)

> or asking for help with an error caused by it, and until
> this thread, never seen anyone complain about it either.

Oh, this bothered me too when I first learned Python, and I thought it
was stupid. It just didn't bother me enough to complain publicly.

Besides, the vast majority of Python noobs don't come here, despite
appearance sometimes, and by the time most people get here, they've
probably got bigger fish to fry.

|>ouglas




From bruno.42.desthuilliers at websiteburo.invalid  Mon Aug 10 04:08:32 2009
From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers)
Date: Mon, 10 Aug 2009 10:08:32 +0200
Subject: Monkeypatching an object to become callable
In-Reply-To: <0aa46ece-64b9-4c28-b690-5ac5937ce3f2@f20g2000prn.googlegroups.com>
References: <87hbwgu7xa.fsf@vostro.rath.org>
	<0aa46ece-64b9-4c28-b690-5ac5937ce3f2@f20g2000prn.googlegroups.com>
Message-ID: <4a7fd55e$0$32765$426a74cc@news.free.fr>

7stud a ?crit :
(snip)
> class Wrapper(object):
>     def __init__(self, obj, func):
>         self.obj = obj
>         self.func = func
> 
>     def __call__(self, *args):
>         return self.func(*args)
> 
>     def __getattr__(self, name):
>         return object.__getattribute__(self.obj, name)

This should be

           return getattr(self.obj, name)

directly calling object.__getattribute__ might skip redefinition of 
__getattribute__ in self.obj.__class__ or it's mro.



From frederic.leger at contactoffice.net  Mon Aug 10 04:35:54 2009
From: frederic.leger at contactoffice.net (=?iso-8859-1?Q?Fr=E9d=E9ric_L=E9ger?=)
Date: Mon, 10 Aug 2009 10:35:54 +0200 (CEST)
Subject: install tarball package Python on Debian, necessary modules not found
Message-ID: <16266394.6699.1249893354154.JavaMail.root@orville>

I use Debian Lenny and I tried to install the tarball packaging of the lastest python realease (http://www.python.org/download/, release 3.1). After read README file I launch standard Makefile commands. But at the end of "make" command, I have got this message:

"...
Python build finished, but the necessary bits to build these modules were not found:
_curses            _curses_panel      _dbm
_gdbm              _hashlib           _sqlite3
_ssl               _tkinter           bz2
readline
To find the necessary bits, look in setup.py in detect_modules() for the module's name.
..."

Solution:

So I installed these Debian packages to correct the problem:

_curses, _curses_panel = libncurses-dev
zlib = libbz2-dev
bz2 = libzip-dev
_dbm, _gdbm = libgdbm-dev 
_hashlib, _ssl = libssl-dev 
_sqlite3 = libsqlite3-dev 
_tkinter = tk8.4-dev 
readline = libreadline5-dev 

I use on command line "apt-get install libncurses-dev libbz2-dev ..."
After that, I retry to compile python "make clean ; make ...". And all modules are good.

Good work with Python 3.1 ;)


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 04:37:48 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 08:37:48 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
Message-ID: 

On Mon, 10 Aug 2009 00:37:33 -0700, Carl Banks wrote:

> On Aug 9, 11:10?pm, Steven D'Aprano
>  wrote:
>> On Sun, 09 Aug 2009 18:34:14 -0700, Carl Banks wrote:
>> >> Why should a backslash in a string literal be an error?
>>
>> > Because the behavior of \ in a string is context-dependent, which
>> > means a reader can't know if \ is a literal character or escape
>> > character without knowing the context, and it means an innocuous
>> > change in context can cause a rather significant change in \.
>>
>> *Any* change in context is significant with escapes.
>>
>> "this \nhas two lines"
>>
>> If you change the \n to a \t you get a significant difference. If you
>> change the \n to a \y you get a significant difference. Why is the
>> first one acceptable but the second not?
> 
> Because when you change \n to \t, you've haven't changed the meaning of
> the \ character; 

I assume you mean the \ character in the literal, not the (non-existent) 
\ character in the string.


> but when you change \n to \y, you have, and you did so
> without even touching the backslash.

Not at all.

'\n' maps to the string chr(10).
'\y' maps to the string chr(92) + chr(121).

In both cases the backslash in the literal have the same meaning: grab 
the next token (usually a single character, but not always), look it up 
in a mapping somewhere, and insert the result in the string object being 
built.

(I don't know if the *implementation* is precisely as described, but 
that's irrelevant. It's still functionally a mapping.) 



>> > IOW it's an error-prone mess.
>>
>> I've never had any errors caused by this.
> 
> Thank you for your anecdotal evidence.  Here's mine: This has gotten me
> at least twice, and a compiler complaint would have reduced my bug-
> hunting time from tens of minutes to ones of seconds.  [Aside: it was
> when I was using Python on Windows for the first time]

Okay, that's twice in, how many years have you been programming?

I've mistyped "xrange" as "xrnage" two or three times. Does that make 
xrange() "an error-prone mess" too? Probably not. Why is my mistake my 
mistake, but your mistake the language's fault?


[...]

Oh, wait, no, I tell I lie -- I *have* seen people reporting "bugs" here 
caused by backslashes. They're invariably Windows programmers writing 
pathnames using backslashes, so I'll give you that one: if you don't know 
that Python treats backslashes as special in string literals, you will 
screw up your Windows pathnames.

Interestingly, the problem there is not that \y resolves to literal 
backslash followed by y, but that \t DOESN'T resolve to the expected 
backslash-t. So it seems to me that the problem for Windows coders is not 
that \y doesn't raise an error, but the mere existence of backslash 
escapes.



> Someone (obviously not you because you're have perfect knowledge of the
> language and 100% situation awareness at all times) might have a string
> like "abcd\stuv"  and change it to "abcd\tuvw" without even thinking
> about the fact that the s comes after the backslash.

Deary me. And they might type "4+15" instead of "4*51", and now 
arithmetic is an "error-prone mess" too. If you know of a programming 
language which can prevent you making semantic errors, please let us all 
know what it is.

If you edit code without thinking, you will be burnt, and you get *zero* 
sympathy from me.


> Worst of all: they might not even notice the error, because the repr of
> this string is:
> 
> 'abcd\tuwv'
> 
> They might not notice that the backslash is single, because (unlike you)
> mortal fallible human beings don't always register tiny details like a
> backslash being single when it should be double.

"Help help, 123145 looks too similar to 1231145, and now I calculated my 
taxes wrong and will go to jail!!!"


> Point is, this is a very bad inconsistency.  It makes the behavior of \
> impossible to learn by analogy, now you have to memorize a list of
> situations where it behaves one way or another.

No, you don't "have" to memorize anything, you can go right ahead and 
escape every backslash, as I did for years. Your code will still work 
fine.

You already have to memorize what escape codes return special characters. 
The only difference is whether you learn "...and everything else raises 
an exception" or "...and everything else is returned unchanged". 

There is at least one good reason for preferring an error, namely that it 
allows Python to introduce new escape codes without going through a long, 
slow process. But the rest of these complaints are terribly unconvincing.



-- 
Steven


From deets at nospam.web.de  Mon Aug 10 04:39:19 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Mon, 10 Aug 2009 10:39:19 +0200
Subject: resume upload wsgi script
In-Reply-To: <49e41062-9e0d-4c5e-beca-edb02d3ce6e8@e34g2000vbm.googlegroups.com>
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
	
	<7e85i3F2fdc1eU1@mid.uni-berlin.de>
	<9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com>
	<7e8ildF2f1hcpU1@mid.uni-berlin.de>
	<49e41062-9e0d-4c5e-beca-edb02d3ce6e8@e34g2000vbm.googlegroups.com>
Message-ID: <7ea4lpF2dvr5cU1@mid.uni-berlin.de>

> 
> 250KB :)

So why do you bother?

> Its just HTTP1.1 has everything for making ftp like file transfers
> possible.
> When I write it to a file then I am back at square one because I still
> need to load it completely to get it into a blob.

Well, the blob is nothing but datat in the file-system. If you are 
*really* concerned about that, then don't use the db, but use the 
filesystem, appending to the file until it's finished - and storing a 
reference to it to the DB. We do that as well, because otherwise the db 
will become unmanagable anyway (dumping, backups).

> So there is no way to concatenate BLOB's without loading it completely
> into memory ?

In theory, the DB might offer special stream-based methods for these 
kinds of tasks, but the db-api lacks them. Some DB-adapters might offer 
some non-standard-extensions, but I don't think sqlite does.

Diez


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 04:49:20 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 08:49:20 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<246b6a1d-7e83-4ad3-9978-c2a55b884a6c@o13g2000vbl.googlegroups.com>
Message-ID: 

On Mon, 10 Aug 2009 00:57:18 -0700, Douglas Alan wrote:

> On Aug 10, 2:10?am, Steven D'Aprano
> 
>> I've never had any errors caused by this.
> 
> But you've seen an error caused by this, in this very discussion. I.e.,
> "foo\xbar".


Your complaint is that "invalid" escapes like \y resolve to a literal 
backslash-y instead of raising an error. But \xbar doesn't contain an 
invalid escape, it contains a valid hex escape. Your ignorance that \xHH 
is a valid hex escape (for suitable hex digits) isn't an example of an 
error caused by "invalid" escapes like \y.



> "\xba" isn't an escape sequence in any other language that I've used,
> which is one reason I made this error... Oh, wait a minute -- it *is* an
> escape sequence in JavaScript. But in JavaScript, while "\xba" is a
> special character, "\xb" is synonymous with "xb".
> 
> The fact that every language seems to treat these things similarly but
> differently, is yet another reason why they should just be treated
> utterly consistently by all of the languages: I.e., escape sequences
> that don't have a special meaning should be an error!

Perhaps all the other languages should follow Python's lead instead?

Or perhaps they should follow bash's lead, and map \C to C for every 
character. If there were no special escapes at all, Windows programmers 
wouldn't keep getting burnt when they write "C:\\Documents\today\foo" and 
end up with something completely unexpected.

Oh wait, no, that still wouldn't work, because they'd end up with 
C:\Documentstodayfoo. So copying bash doesn't work.

But copying C will upset the bash coders, because they'll write 
"some\ file\ with\ spaces" and suddenly their code won't even compile!!!

Seems like no matter what you do, you're going to upset *somebody*.



>> I've never seen anyone write to
>> this newsgroup confused over escape behaviour,
> 
> My friend objects strongly the claim that he is "confused" by it, so I
> guess you are right that no one is confused. He just thinks that it
> violates the beautiful sense of aesthetics that he was sworn over and
> over again Python to have.

Fair enough.



-- 
Steven


From no.i.dont at want.mail.from.spammers.com  Mon Aug 10 05:23:57 2009
From: no.i.dont at want.mail.from.spammers.com (Fencer)
Date: Mon, 10 Aug 2009 11:23:57 +0200
Subject: Problem with join in__str__() in class (newbie)
In-Reply-To: 
References: <7e8ek2F2dre5lU1@mid.individual.net>
	
	<7e8g3vF2etertU1@mid.individual.net>
	
	<7e8keqF2eib0lU1@mid.individual.net> 
Message-ID: <7ea79eF2esi87U1@mid.individual.net>

Piet van Oostrum wrote:
[snip]

Thanks for your detailed reply!

- Fencer


From duncan.booth at invalid.invalid  Mon Aug 10 05:34:38 2009
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 10 Aug 2009 09:34:38 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<246b6a1d-7e83-4ad3-9978-c2a55b884a6c@o13g2000vbl.googlegroups.com>
Message-ID: 

Douglas Alan  wrote:

> "\xba" isn't an escape sequence in any other language that I've used,
> which is one reason I made this error... Oh, wait a minute -- it *is*
> an escape sequence in JavaScript. But in JavaScript, while "\xba" is a
> special character, "\xb" is synonymous with "xb".
> 

"\xba" is an escape sequence in c, c++, c#, python, javascript, perl and 
probably many others.

"\xb" is an escape sequence in c, c++, c# but not in Python, Javascript, or 
Perl. Python will throw ValueError if you try to use "\xb" in a string, 
Javascript simply ignores the backslash.

> The fact that every language seems to treat these things similarly but
> differently, is yet another reason why they should just be treated
> utterly consistently by all of the languages: I.e., escape sequences
> that don't have a special meaning should be an error!

It would be nice if these things were treated consistently, but they aren't 
and it seems unlikely to change.



-- 
Duncan Booth http://kupuguy.blogspot.com


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 05:40:24 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 09:40:24 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
Message-ID: 

On Mon, 10 Aug 2009 00:32:30 -0700, Douglas Alan wrote:

> In C++, if I know that the code I'm looking at compiles, then I never
> need worry that I've misinterpreted what a string literal means.

If you don't know what your string literals are, you don't know what your 
program does. You can't expect the compiler to save you from semantic 
errors. Adding escape codes into the string literal doesn't change this 
basic truth.

Semantics matters, and unlike syntax, the compiler can't check it. 
There's a difference between a program that does the equivalent of:

    os.system("cp myfile myfile~")

and one which does this

    os.system("rm myfile myfile~")


The compiler can't save you from typing 1234 instead of 11234, or 31.45 
instead of 3.145, or "My darling Ho" instead of "My darling Jo", so why 
do you expect it to save you from typing "abc\d" instead of "abc\\d"?

Perhaps it can catch *some* errors of that type, but only at the cost of 
extra effort required to defeat the compiler (forcing the programmer to 
type \\d to prevent the compiler complaining about \d). I don't think the 
benefit is worth the cost. You and your friend do. Who is to say you're 
right?



> At
> least not if it doesn't have any escape characters in it that I'm not
> familiar with. But in Python, if I see, "\f\o\o\b\a\z", I'm not really
> sure what I'm seeing, as I surely don't have committed to memory some of
> the more obscure escape sequences. If I saw this in C++, and I knew that
> it was in code that compiled, then I'd at least know that there are some
> strange escape codes that I have to look up. 

And if you saw that in Python, you'd also know that there are some 
strange escape codes that you have to look up. Fortunately, in Python, 
that's really simple:

>>> "\f\o\o\b\a\z"
'\x0c\\o\\o\x08\x07\\z'

Immediately you can see that the \o and \z sequences resolve to 
themselves, and the \f \b and \a don't.



> Unlike with Python, it
> would never be the case in C++ code that the programmer who wrote the
> code was just too lazy to type in "\\f\\o\\o\\b\\a\\z" instead.

But if you see "abc\n", you can't be sure whether the lazy programmer 
intended "abc"+newline, or "abc"+backslash+"n". Either way, the compiler 
won't complain.


 
>> You just have to memorize it. If you don't know what a backslash escape
>> is going to do, why would you use it?
> 
> (1) You're looking at code that someone else wrote, or (2) you forget to
> type "\\" instead of "\" in your code (or get lazy sometimes), as that
> is okay most of the time, and you inadvertently get a subtle bug.

The same error can occur in C++, if you intend \\n but type \n by 
mistake. Or vice versa. The compiler won't save you from that.



>> This is especially important when reading (as opposed to writing) code.
>> You read somebody else's code, and see "foo\xbar\n". Let's say you know
>> it compiles without warning. Big deal -- you don't know what the escape
>> codes do unless you've memorized them. What does \n resolve to? chr(13)
>> or chr(97) or chr(0)? Who knows?
> 
> It *is* a big deal. Or at least a non-trivial deal. It means that you
> can tell just by looking at the code that there are funny characters in
> the string, and not just a backslashes. 

I'm not entirely sure why you think that's a big deal. Strictly speaking, 
there are no "funny characters", not even \0, in Python. They're all just 
characters. Perhaps the closest is newline (which is pretty obvious).



> You don't have to go running for
> the manual every time you see code with backslashes, where the upshot
> might be that the programmer was merely saving themselves some typing.

Why do you care if there are "funny characters"?

In C++, if you see an escape you don't recognize, do you care? Do you go 
running for the manual? If the answer is No, then why do it in Python?

And if the answer is Yes, then how is Python worse than C++?


[...]
> Also, it seems that Python is being inconsistent here. Python knows that
> the string "\x" doesn't contain a full escape sequence, so why doesn't
> it
> treat the string "\x" the same way that it treats the string "\z"?
[...]
> I.e., "\z" is not a legal escape sequence, so it gets left as "\\z".

No. \z *is* a legal escape sequence, it just happens to map to \z.

If you stop thinking of \z as an illegal escape sequence that Python 
refuses to raise an error for, the problem goes away. It's a legal escape 
sequence that maps to backslash + z.



> "\x" is not a legal escape sequence. Shouldn't it also get left as
> "\\x"?

No, because it actually is an illegal escape sequence.



>> > He's particularly annoyed too, that if he types "foo\xbar" at the
>> > REPL, it echoes back as "foo\\xbar". He finds that to be some sort of
>> > annoying DWIM feature, and if Python is going to have DWIM features,
>> > then it should, for example, figure out what he means by "\" and not
>> > bother him with a syntax error in that case.
>>
>> Now your friend is confused. This is a good thing. Any backslash you
>> see in Python's default string output is *always* an escape:
> 
> Well, I think he's more annoyed that if Python is going to be so helpful
> as to put in the missing "\" for you in "foo\zbar", then it should put
> in the missing "\" for you in "\". He considers this to be an
> inconsistency.

(1) There is no missing \ in "foo\zbar".

(2) The problem with "\" isn't a missing backslash, but a missing end-
quote.





> Me, I'd never, ever, EVER want a language to special-case something at
> the end of a string, but I can see that from his new-to-Python
> perspective, Python seems to be DWIMing in one place and not the other,
> and he thinks that it should either do no DWIMing at all, or
> consistently DWIM. To not be consistent in this regard is "inelegant",
> says he.

Python isn't DWIMing here. The rules are simple and straightforward, 
there's no mind-reading or guessing required. There is no heuristic 
trying to predict what the user intends. It's a simple rule:

When parsing a string literal (apart from raw strings), if you see a 
backslash, then grab the next token (usually a single character, but for 
\x and \0 it could be multiple characters). If there is a mapping 
available for that token, insert that in the string being built, and if 
not, insert the backslash and the token.

(As I said earlier, this may not be precisely how it is implemented, but 
functionally, it is what Python does.)


> And I can see his point that allowing "foo\zbar" and "foo\\zbar" to be
> synonymous is a form of DWIMing.

Is it "a form of DWIMing" to consider 1.234e1 and 12.34  synonymous?

What about 86 and 0x44? Is that DWIMing?

I'm sure both you and your friend are excellent programmers, but you're 
tossing around DWIM as a meaningless term of opprobrium without any 
apparent understand of what DWIM actually is.




-- 
Steven



From duncan.booth at invalid.invalid  Mon Aug 10 05:41:52 2009
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 10 Aug 2009 09:41:52 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<246b6a1d-7e83-4ad3-9978-c2a55b884a6c@o13g2000vbl.googlegroups.com>
	
Message-ID: 

Steven D'Aprano  wrote:

> Or perhaps they should follow bash's lead, and map \C to C for every 
> character. If there were no special escapes at all, Windows
> programmers wouldn't keep getting burnt when they write
> "C:\\Documents\today\foo" and end up with something completely
> unexpected. 
> 
> Oh wait, no, that still wouldn't work, because they'd end up with 
> C:\Documentstodayfoo. So copying bash doesn't work.
> 

There is of course no problem at all so long as you stick to writing your 
paths as MS intended them to be written: 8.3 and UPPERCASE

>>> "C:\DOCUME~1\TODAY\FOO"
'C:\\DOCUME~1\\TODAY\\FOO'

:^)


-- 
Duncan Booth http://kupuguy.blogspot.com


From garabik-news-2005-05 at kassiopeia.juls.savba.sk  Mon Aug 10 05:43:08 2009
From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk)
Date: Mon, 10 Aug 2009 09:43:08 +0000 (UTC)
Subject: install tarball package Python on Debian,
	necessary modules not found
References: 
Message-ID: 

Fr?d?ric L?ger  wrote:

> I use Debian Lenny and I tried to install the tarball packaging of the
> lastest python realease (http://www.python.org/download/, release
> 3.1). After read README file I launch standard Makefile commands. But
> at the end of "make" command, I have got this message:
> 

Maybe you know, but there is python3.1 deb in experimental. Works with
testing like a charm. It is also possible to install ubuntu's 3.X into
debian.

-- 
 -----------------------------------------------------------
| Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__    garabik @ kassiopeia.juls.savba.sk     |
 -----------------------------------------------------------
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!


From thangappan143 at gmail.com  Mon Aug 10 05:45:07 2009
From: thangappan143 at gmail.com (Thangappan.M)
Date: Mon, 10 Aug 2009 15:15:07 +0530
Subject: Problem in installing PyGreSQL
In-Reply-To: 
References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com>
	<7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net>
	<20090804084856.b825967a.darcy@druid.net>
	
	<20090804095547.a5274e22.darcy@druid.net> 
	<7aa29e790908060330x67d900a9rfb4677eaf0eddeb@mail.gmail.com>
	
	
Message-ID: <7aa29e790908100245k3c08dc36mcebbfa48a0d6bdc4@mail.gmail.com>

Here I attached the setup.py and setup.cfg file.This is for your reference.
I have changed the exception line.
Even though I got the following error while running the python setup.py
build
running build
running build_py
running build_ext
error: No such file or directory

===========================================

On Fri, Aug 7, 2009 at 7:38 PM, Scott David Daniels
wrote:

> Dennis Lee Bieber wrote:
>
>> On Thu, 6 Aug 2009 16:00:15 +0530, "Thangappan.M"
>>  declaimed the following in
>> gmane.comp.python.general:
>>
>>>  File "./setup.py", line 219, in finalize_options
>>>    except (Warning, w):
>>> NameError: global name 'w' is not defined
>>>
>>> What would be the solution?
>>> Otherwise can you tell how to install DB-API in debian machine.
>>>
>>        Sorry... 1) I run on WinXP; 2) I don't build packages, relying on
>> pre-built binaries; 3) I run MySQL.
>>
>>        However, based upon the examples in the Tutorial, that line should
>> not have the (, ). A parenthesised (tuple) is suppose to contain a list
>> of exceptions, and the parameter to catch the exception specifics has to
>> be outside the list.
>>
>>        Best I can suggest is editing that particular line and removing the
>> (, ) -- then try rebuilding.
>>
>>        I'll also re-ask: All you are installing is the Python adapter to
>> the database. DO YOU HAVE A RUNNING PostgreSQL server that you can
>> connect to?
>>
>
> Just to be a bit more explict:
> Change file setup.py's line 219 from:
> >>     except (Warning, w):
> to either (OK in Python 2.6 and greater):
>       except Warning as w:
> or (works for Python 2.X):
>       except Warning, w:
>
>
> --Scott David Daniels
> Scott.Daniels at Acm.Org
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Regards,
Thangappan.M
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: setup.cfg
Type: application/octet-stream
Size: 2041 bytes
Desc: not available
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: setup.py
Type: text/x-python
Size: 15479 bytes
Desc: not available
URL: 

From manu3d at gmail.com  Mon Aug 10 06:01:30 2009
From: manu3d at gmail.com (Emanuele D'Arrigo)
Date: Mon, 10 Aug 2009 03:01:30 -0700 (PDT)
Subject: exec("dir()",d)
References: <9adbf402-3e7e-44a4-adb3-afc36d5d88ba@33g2000vbe.googlegroups.com>
	
Message-ID: <138a15c5-a39b-427a-91c6-47ce7dd52a78@f33g2000vbm.googlegroups.com>

Thank you both for the explanation.

As a matter of fact RTFM doesn't -always- help. Sometimes I'm just
thick and I can read the manual 10 times and still not understand, as
it happened on this particular matter. Your contribution focused my
attention on the right bit of the manual which I somehow didn't manage
to ingest before. Now I understand.

Thank you.

Manu


From deets at nospam.web.de  Mon Aug 10 06:52:26 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Mon, 10 Aug 2009 12:52:26 +0200
Subject: Cython + setuptools not working with .pyx,only with .c-files
References: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
	<4a7c56e0$0$31871$9b4e6d93@newsspool3.arcor-online.net>
Message-ID: <7eacfaF2fi1s2U1@mid.uni-berlin.de>

Stefan Behnel wrote:

> Diez B. Roggisch wrote:
>> I'm trying to build a Cython-extension as Egg.
>> 
>> However, this doesn't work - I can either use distutils to build the
>> extension, creating a myextension.c-file on the way.
>> 
>> If that's there, I can use setuptools to build the egg.
>> 
>> But when I remove the .c-file, the .pyx-file isn't used to re-generate
>> it.
> 
> setuptools monkeypatch into distutils to support Pyrex if it's installed,
> but most non-bleeding-edge versions do not know about Cython and thus
> break the Cython distutils support when Pyrex isn't there as well.
> 
> What helps is to put a fake Pyrex installation into your sys.path, like
> 
> http://codespeak.net/svn/lxml/trunk/fake_pyrex/
> 
> as done at the top of
> 
> http://codespeak.net/svn/lxml/trunk/setup.py

Thanks, that did the trick for us.

Diez


From subhakolkata1234 at gmail.com  Mon Aug 10 07:26:57 2009
From: subhakolkata1234 at gmail.com (joy99)
Date: Mon, 10 Aug 2009 04:26:57 -0700 (PDT)
Subject: Problem Regarding Handling of Unicode string
Message-ID: <9ac0e194-9e25-468a-9807-957ef3142dd3@i18g2000pro.googlegroups.com>

Dear Group,

I am using Python26 on WindowsXP with service pack2. My GUI is IDLE.
I am using Hindi resources and get nice output like:
??
where I can use all the re functions and other functions without doing
any transliteration,etc.
I was trying to use Bengali but it is giving me output like:
'\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95'
I wanted to see Bengali output as
????
and I like to use all functions including re.
If any one can help me on that.
Best Regards,
Subhabrata.


From nair.jitendra at gmail.com  Mon Aug 10 07:39:03 2009
From: nair.jitendra at gmail.com (jitu)
Date: Mon, 10 Aug 2009 04:39:03 -0700 (PDT)
Subject: Problem when fetching page using urllib2.urlopen
Message-ID: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>

Hi,

A html page  contains 'anchor' elements with 'href' attribute  having
a semicolon  in the url , while fetching the page using
urllib2.urlopen, all such href's  containing  'semicolons' are
truncated.


For example the href http://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt=AlWSqpkpqhICp1lMgChtJkCdGWoL
get truncated to http://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i

The page I am talking about can be fetched from
http://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_ylc=X3oDMTFka28zOGNuBF9TAzI3NjY2NzkEX3MDOTY5NTUzMjUEc2VjA3NzcC1kZXN0BHNsawN0aXRsZQ--

Thanks a Lot
Regards
jitu



From eckhardt at satorlaser.com  Mon Aug 10 07:41:01 2009
From: eckhardt at satorlaser.com (Ulrich Eckhardt)
Date: Mon, 10 Aug 2009 13:41:01 +0200
Subject: Problem Regarding Handling of Unicode string
References: <9ac0e194-9e25-468a-9807-957ef3142dd3@i18g2000pro.googlegroups.com>
Message-ID: 

joy99 wrote:
> [...] it is giving me output like:
> '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95'
   ^^^^^^^^^^^^

These three bytes encode the byte-order marker (BOM, Unicode uFEFF) as
UTF-8, followed by codepoint u09a8 (look it up on unicode.org what that
is).

In any case, if this is produced as output, there is some missing
encoding/decoding going on. You mentioned that it works in one case but
doesn't in another. Since you didn't provide any information how to
reproduce what you saw, any further help is at most guesswork.

Uli

-- 
Sator Laser GmbH
Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932



From python at mrabarnett.plus.com  Mon Aug 10 07:41:08 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Mon, 10 Aug 2009 12:41:08 +0100
Subject: Unrecognized escape sequences in string literals
In-Reply-To: 
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>	
	
Message-ID: <4A800754.20907@mrabarnett.plus.com>

Steven D'Aprano wrote:
> On Sun, 09 Aug 2009 17:56:55 -0700, Douglas Alan wrote:
> 
[snip]
>> My point of view is that
>> every language has *some* warts; Python just has a bit fewer than most.
>> It would have been nice, I should think, if this wart had been "fixed"
>> in Python 3, as I do consider it to be a minor wart.
> 
> And if anyone had cared enough to raise it a couple of years back, it 
> possibly might have been.
> 
My preference would've been that a backslash followed by A-Z, a-z, or
0-9 is special, but a backslash followed by any other character is just
the character, except for backslash followed by a newline, which
suppresses the newline.

I would also have preferred a backslash in a raw string to always be a
literal.

Ah well, something for Python 4.x. :-)


From nair.jitendra at gmail.com  Mon Aug 10 07:43:12 2009
From: nair.jitendra at gmail.com (jitu)
Date: Mon, 10 Aug 2009 04:43:12 -0700 (PDT)
Subject: Problem when fetching page using urllib2.urlopen
References: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>
Message-ID: <0579ebc0-2542-4f96-af3e-9861ad646b13@d9g2000prh.googlegroups.com>

On Aug 10, 4:39?pm, jitu  wrote:
> Hi,
>
> A html page ?contains 'anchor' elements with 'href' attribute ?having
> a semicolon ?in the url , while fetching the page using
> urllib2.urlopen, all such href's ?containing ?'semicolons' are
> truncated.
>
> For example the hrefhttp://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt...
> get truncated tohttp://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i
>
> The page I am talking about can be fetched fromhttp://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_...
>
> Thanks a Lot
> Regards
> jitu

Hi

   Sorry, the question what I wanted to ask was, whether is this the
correct behaviour or a bug ?


Thanks A Lot.
Regards
jitu


From sibtey.mehndi at genpact.com  Mon Aug 10 08:23:56 2009
From: sibtey.mehndi at genpact.com (Mehndi, Sibtey)
Date: Mon, 10 Aug 2009 17:53:56 +0530
Subject: [Errno 9] Bad file descriptor
Message-ID: <1A343A98C8DAE44A8D9D1BF310F90D5E0141163674@GCPWINGGN2EVS11.IND.CORP.AD>

Hi
I am trying to create a COM object of picalo functionalities so that I can use it into my VB application but I am getting the following error "[Errno 9] bad file descriptor".
Can you please suggest me what is supposed to do to avoid this problem?

This is my code

class Test(object):
    _reg_progid_ = "test"
    _reg_clsid_ = "{D2EFAAC0-797A-471A-AA07-ECEACFE33A08}"
    _public_methods_ = ['dbconnect']


    def dbconnect(self, dbName, dbUserName, dbPWD, dbHost, dbPort):
        try:
            self.conn = Database.MySQLConnection(dbName, username=dbUserName, password=dbPWD, host=dbHost, port=dbPort)
            self.table = self.conn.table( "SELECT * FROM test_flag_data")
            return  "connected"
        except Exception,e:
            return str(e)

Thanks,
Sibty



This e-mail (and any attachments), is confidential and may be privileged. It may be read, copied and used only
by intended recipients. Unauthorized access to this e-mail (or attachments) and disclosure or copying of its 
contents or any action taken in reliance on it is unlawful. Unintended recipients must notify the sender immediately 
by e-mail/phone & delete it from their system without making any copies or disclosing it to a third person.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nadiasvertex at gmail.com  Mon Aug 10 08:41:28 2009
From: nadiasvertex at gmail.com (Christopher)
Date: Mon, 10 Aug 2009 05:41:28 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
	
	<4A7DC141.9070207@v.loewis.de>
	<54581bf3-c9a1-4bbf-945c-28d436ffda2a@k13g2000prh.googlegroups.com>
	<4cea29ee-cc89-4494-aef9-0f46f8dd11b9@2g2000prl.googlegroups.com> 
	<80c46b94-9df2-43f5-9182-37c2413db783@b25g2000prb.googlegroups.com>
Message-ID: 

On Aug 8, 5:50?pm, Pouya Khankhanian  wrote:
> On Aug 8, 11:49?am, Sharath  wrote:
>
>
>
> > On Aug 8, 11:33?am, Pouya Khankhanian  wrote:
>
> > > On Aug 8, 11:17?am, "Martin v. L?wis"  wrote:
>
> > > > > This is probably a stupid question, but Is there going to be any data
> > > > > loss if it turns out that the disk has died completely? I assume there
> > > > > are backups of the repo that are geographically distributed.
>
> > > > Yes, we have backups, and are restoring them at the moment. However,
> > > > we still haven't given up on the original disks: they are (probably)
> > > > fine; it's just the RAID controller that has failed (and we can't buy a
> > > > replacement before Monday).
>
> > > > Regards,
> > > > Martin
>
> > > Is there a mirror site to download the latest python installer? Every
> > > mirror I have found on the web redirects me to python.org.
> > > Best
> > > Peter
>
> > Python FTP mirror sites also have the same problem. They are not being
> > mirrored for some require a password. Is there any other way to get a
> > copy?
>
> > Sharath Venkatesha
>
> Website is back up! Thanks for all the hard work

Actually, it appears to be down again.


From kdawg44 at gmail.com  Mon Aug 10 08:47:19 2009
From: kdawg44 at gmail.com (Kevin Holleran)
Date: Mon, 10 Aug 2009 08:47:19 -0400
Subject: Changing Remote Registry
In-Reply-To: <4A7C6D96.3000201@timgolden.me.uk>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
	<4A7C6D96.3000201@timgolden.me.uk>
Message-ID: <5caea3690908100547l65394e65le111d8f3dda9e903@mail.gmail.com>

On Fri, Aug 7, 2009 at 2:08 PM, Tim Golden  wrote:

> Kevin Holleran wrote:
>
>> Long story short, I am using _winreg to do this.
>>
>> hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
>> value,type = _winreg.QueryValueEx(hKey, item)
>> if (value == wrongValue):
>>       _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
>>
>>
>> When I do this I receive the error:
>>
>> _winreg.SetValue WindowsError: [Error 5] Access Denied
>>
>
> As an alternative, try using WMI instead. You'll have to look up the docs
> a bit, but to get you started:
>
> 
> import wmi
>
> reg = wmi.WMI ("remote-machine", namespace="default").StdRegProv
>
> print reg.methods.keys ()
>
> 
>
> TJG
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Thank you for your response.

I actually started with the WMI wrapper but isn't that just a wrapper that
utilizes (in this case) the _winreg module?

I guess my question is will Windows let me change the registry remotely?
The error is a Windows permission error on the KEY_SET_VALUE.  I am running
this as a domain admin on a machine on the domain.  Does the connection
inherit the credentials I am running it under or will I need to pass those
in?  Or does Windows simply not let me change the registry?

To me its not worth too much trouble.  If I can change it in place it saves
me just a little bit of work because I have to touch each machine anyway for
other reasons.  The big difference is that I can change all the machines I
have to touch right now and get them fixed up or these folks are just going
to have to wait until I get to each one.

Thanks for all your help and support.

Kevin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From ebonak at hotmail.com  Mon Aug 10 08:50:21 2009
From: ebonak at hotmail.com (Esmail)
Date: Mon, 10 Aug 2009 08:50:21 -0400
Subject: compression level with tarfile (w:gz) ?
Message-ID: 

Hello,

I was wondering if it possible to specify a compression level when I
tar/gzip a file in Python using the tarfile module. I would like to
specify the highest (9) compression level for gzip.

Ideally:

    t = tarfile.open(tar_file_name+'.tar.gz', mode='w:gz:9')

When I create a simple tar and then gzip it 'manually' with compression
level 9, I get a smaller archive than when I have this code execute with
the w:gz option.

Is the only way to accomplish the higher rate to create a tar file
and then use a different module to gzip it (assuming I can specify
the compression level there)?

Thanks,
Esmail

-----------------
My current code:
-----------------

def tar_it_up(target_dir_name, tar_file_name=None):
     '''
     tar up target_dir_name directory and create a
     tar/zip file with base name tar_file_name

     appends a date/timestamp to tar_file_name
     '''

     time_string = time.strftime("_%b_%d_%Y_%a_%H_%M")

     if tar_file_name is None:
         tar_file_name = target_dir_name

     tar_file_name += time_string

     print ('Creating archive of %s ...' % target_dir_name),

     t = tarfile.open(tar_file_name+'.tar.gz', mode='w:gz')
#   t = tarfile.open(tar_file_name+'.tar', mode='w')
     t.add(target_dir_name)
     t.close()

     print ('saved to %s.tar.gz' % tar_file_name)



From contact at xavierho.com  Mon Aug 10 08:51:21 2009
From: contact at xavierho.com (Xavier Ho)
Date: Mon, 10 Aug 2009 22:51:21 +1000
Subject: www.python.org website is down?
In-Reply-To: 
References: 
	
	
	<4A7DC141.9070207@v.loewis.de>
	<54581bf3-c9a1-4bbf-945c-28d436ffda2a@k13g2000prh.googlegroups.com>
	<4cea29ee-cc89-4494-aef9-0f46f8dd11b9@2g2000prl.googlegroups.com>
	<80c46b94-9df2-43f5-9182-37c2413db783@b25g2000prb.googlegroups.com>
	
Message-ID: <2d56febf0908100551v6ad45fb3u5b77adc0149051d8@mail.gmail.com>

On Mon, Aug 10, 2009 at 10:41 PM, Christopher wrote:

>
> Actually, it appears to be down again.
>

Nope, works for me, just a little slow.

-Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From benjamin.kaplan at case.edu  Mon Aug 10 09:19:43 2009
From: benjamin.kaplan at case.edu (Benjamin Kaplan)
Date: Mon, 10 Aug 2009 09:19:43 -0400
Subject: compression level with tarfile (w:gz) ?
In-Reply-To: 
References: 
Message-ID: 

On Mon, Aug 10, 2009 at 8:50 AM, Esmail wrote:
> Hello,
>
> I was wondering if it possible to specify a compression level when I
> tar/gzip a file in Python using the tarfile module. I would like to
> specify the highest (9) compression level for gzip.
>
> Ideally:
>
> ? t = tarfile.open(tar_file_name+'.tar.gz', mode='w:gz:9')
>
> When I create a simple tar and then gzip it 'manually' with compression
> level 9, I get a smaller archive than when I have this code execute with
> the w:gz option.
>

Looking at the tarfile docs, it seems that there are tarfile.gzopen
and tarfile.bz2open functions that have a compresslevel parameter that
defaults to 9. You can't append using those functions but you can read
and write.

> Is the only way to accomplish the higher rate to create a tar file
> and then use a different module to gzip it (assuming I can specify
> the compression level there)?
>
> Thanks,
> Esmail
>
> -----------------
> My current code:
> -----------------
>
> def tar_it_up(target_dir_name, tar_file_name=None):
> ? ?'''
> ? ?tar up target_dir_name directory and create a
> ? ?tar/zip file with base name tar_file_name
>
> ? ?appends a date/timestamp to tar_file_name
> ? ?'''
>
> ? ?time_string = time.strftime("_%b_%d_%Y_%a_%H_%M")
>
> ? ?if tar_file_name is None:
> ? ? ? ?tar_file_name = target_dir_name
>
> ? ?tar_file_name += time_string
>
> ? ?print ('Creating archive of %s ...' % target_dir_name),
>
> ? ?t = tarfile.open(tar_file_name+'.tar.gz', mode='w:gz')
> # ? t = tarfile.open(tar_file_name+'.tar', mode='w')
> ? ?t.add(target_dir_name)
> ? ?t.close()
>
> ? ?print ('saved to %s.tar.gz' % tar_file_name)
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


From ebonak at hotmail.com  Mon Aug 10 09:37:14 2009
From: ebonak at hotmail.com (Esmail)
Date: Mon, 10 Aug 2009 09:37:14 -0400
Subject: compression level with tarfile (w:gz) ?
In-Reply-To: 
References: 
	
Message-ID: 

Benjamin Kaplan wrote:
> On Mon, Aug 10, 2009 at 8:50 AM, Esmail wrote:
>>
>> I was wondering if it possible to specify a compression level when I
>> tar/gzip a file in Python using the tarfile module. I would like to
>> specify the highest (9) compression level for gzip.
>>
>> Ideally:
>>
>>   t = tarfile.open(tar_file_name+'.tar.gz', mode='w:gz:9')
<..>
> 
> Looking at the tarfile docs, it seems that there are tarfile.gzopen
> and tarfile.bz2open functions that have a compresslevel parameter that
> defaults to 9. You can't append using those functions but you can read
> and write.

Hi Benjamin,

I can't find tarfile.gzopen  in the tarfile docs, I'm looking here:

     http://docs.python.org/library/tarfile.html

Am I looking at the wrong page?

Thanks,

Esmail



From lars at gustaebel.de  Mon Aug 10 09:41:08 2009
From: lars at gustaebel.de (Lars =?iso-8859-1?Q?Gust=E4bel?=)
Date: Mon, 10 Aug 2009 15:41:08 +0200
Subject: compression level with tarfile (w:gz) ?
In-Reply-To: 
References: 
Message-ID: <20090810134108.GA7790@axis.g33x.de>

On Mon, Aug 10, 2009 at 08:50:21AM -0400, Esmail wrote:
> I was wondering if it possible to specify a compression level when I
> tar/gzip a file in Python using the tarfile module. I would like to
> specify the highest (9) compression level for gzip.

tarfile uses gzip.GzipFile() internally, GzipFile()'s default compression level
is 9.

> When I create a simple tar and then gzip it 'manually' with compression
> level 9, I get a smaller archive than when I have this code execute with
> the w:gz option.

How much smaller is it? I did a test with a recent Linux kernel source tree
which made an archive of 337MB. Command-line gzip was ahead of Python's
GzipFile() by just 20200 bytes(!) with an archive of about 74MB.

> Is the only way to accomplish the higher rate to create a tar file
> and then use a different module to gzip it (assuming I can specify
> the compression level there)?

If you need the disk space that badly, the alternative would be to pipe
tarfile's output to command-line gzip somehow:

fobj = open("result.tar.gz", "w")
proc = subprocess.Popen(["gzip", "-9"], stdin=subprocess.PIPE, stdout=fobj)
tar = tarfile.open(fileobj=proc.stdin, mode="w|")
tar.add(...)
tar.close()
proc.stdin.close()
fobj.close()

Cheers,

-- 
Lars Gust?bel
lars at gustaebel.de

A physicist is an atom's way of knowing about atoms.
(George Wald)


From benjamin.kaplan at case.edu  Mon Aug 10 09:55:06 2009
From: benjamin.kaplan at case.edu (Benjamin Kaplan)
Date: Mon, 10 Aug 2009 09:55:06 -0400
Subject: compression level with tarfile (w:gz) ?
In-Reply-To: 
References: 
	
	
Message-ID: 

On Mon, Aug 10, 2009 at 9:37 AM, Esmail wrote:
> Benjamin Kaplan wrote:
>>
>> On Mon, Aug 10, 2009 at 8:50 AM, Esmail wrote:
>>>
>>> I was wondering if it possible to specify a compression level when I
>>> tar/gzip a file in Python using the tarfile module. I would like to
>>> specify the highest (9) compression level for gzip.
>>>
>>> Ideally:
>>>
>>> ?t = tarfile.open(tar_file_name+'.tar.gz', mode='w:gz:9')
>
> <..>
>>
>> Looking at the tarfile docs, it seems that there are tarfile.gzopen
>> and tarfile.bz2open functions that have a compresslevel parameter that
>> defaults to 9. You can't append using those functions but you can read
>> and write.
>
> Hi Benjamin,
>
> I can't find tarfile.gzopen ?in the tarfile docs, I'm looking here:
>
> ? ?http://docs.python.org/library/tarfile.html
>
> Am I looking at the wrong page?
>

My mistake. It isn't a function of the tarfile module, it's a class
method of tarfile.TarFile. I was looking at the help in the
interactive interpreter. It doesn't seem to be in the official docs,
but you can use pydoc to view the docstrings.

> Thanks,
>
> Esmail
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


From rt8396 at gmail.com  Mon Aug 10 09:57:43 2009
From: rt8396 at gmail.com (r)
Date: Mon, 10 Aug 2009 06:57:43 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
Message-ID: <1d952f0b-9552-48ef-ad2e-a7b8e06ea8eb@n2g2000vba.googlegroups.com>

On Aug 8, 8:48?am, MRAB  wrote:
...(snip)
> Bothwww.python.organd svn.python.org are down. ?They're hosted on
> the same machine, and it seems to have run into disk problems and
> hasn't rebooted even after power-cycling. ?Thomas Wouters will be
> visiting the machine physically tomorrow to try to diagnose the
> problem.

Oh stop lying MRAB, everybody knows Guido hosts Python.org from his
attic on an old Linux box :-)


From rurpy at yahoo.com  Mon Aug 10 10:01:04 2009
From: rurpy at yahoo.com (rurpy at yahoo.com)
Date: Mon, 10 Aug 2009 07:01:04 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
Message-ID: <616c058c-2595-42fc-b80d-e599d5d6ad66@o36g2000vbl.googlegroups.com>

On Aug 9, 10:02?pm, David Lyon  wrote:
...
> Before you do that, you should clearly work out in your own mind
> how you think things need to improve. It's not good enough just
> saying this or that is bad without having specific ideas on what
> needs to change.
'''

He did.  Did you read, for example, the critique of the gzip
docs for which he gave the url

   http://xahlee.org/perl-python/python_doc_gzip.html

There were some things I might not completely agree with
there, but basically, I thought it was right on, including
his suggestions on how to improve it.


From darkwater42 at gmail.com  Mon Aug 10 10:11:33 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Mon, 10 Aug 2009 07:11:33 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
Message-ID: 

On Aug 10, 4:37?am, Steven D'Aprano

> There is at least one good reason for preferring an error, namely that it
> allows Python to introduce new escape codes without going through a long,
> slow process. But the rest of these complaints are terribly unconvincing.


What about:

   o Beautiful is better than ugly
   o Explicit is better than implicit
   o Simple is better than complex
   o Readability counts
   o Special cases aren't special enough to break the rules
   o Errors should never pass silently

?

And most importantly:

   o In the face of ambiguity, refuse the temptation to guess.
   o There should be one -- and preferably only one -- obvious way to
do it.

?

So, what's the one obvious right way to express "foo\zbar"? Is it

   "foo\zbar"

or

   "foo\\zbar"

And if it's the latter, what possible benefit is there in allowing the
former?  And if it's the former, why does Python echo the latter?

|>ouglas


From python at mrabarnett.plus.com  Mon Aug 10 10:13:12 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Mon, 10 Aug 2009 15:13:12 +0100
Subject: www.python.org website is down?
In-Reply-To: <1d952f0b-9552-48ef-ad2e-a7b8e06ea8eb@n2g2000vba.googlegroups.com>
References: 	
	<1d952f0b-9552-48ef-ad2e-a7b8e06ea8eb@n2g2000vba.googlegroups.com>
Message-ID: <4A802AF8.1000407@mrabarnett.plus.com>

r wrote:
> On Aug 8, 8:48 am, MRAB  wrote:
> ...(snip)
>> Bothwww.python.organd svn.python.org are down.  They're hosted on
>> the same machine, and it seems to have run into disk problems and
>> hasn't rebooted even after power-cycling.  Thomas Wouters will be
>> visiting the machine physically tomorrow to try to diagnose the
>> problem.
> 
> Oh stop lying MRAB, everybody knows Guido hosts Python.org from his
> attic on an old Linux box :-)

That was a quote from A.M. Kuchling.

It's actually hosted on a matchbox-sized multi-core multi-terabyte
wifi-enabled Linux machine that Guido brought back from 2050.
Unfortunately, the dog ate it, so he's had to go and buy another one!
:-)


From pruebauno at latinmail.com  Mon Aug 10 10:17:22 2009
From: pruebauno at latinmail.com (nn)
Date: Mon, 10 Aug 2009 07:17:22 -0700 (PDT)
Subject: syntax checker in python
References: 
Message-ID: <8bcca8f4-673c-4478-a2ad-fc292c761062@m20g2000vbp.googlegroups.com>

On Aug 7, 4:39?pm, horos11  wrote:
> ps - I just realized that it isn't enough to do:
>
> python -c 'import /path/to/script'
>
> since that actually executes any statement inside of the script
> (wheras all I want to do is check syntax)
>
> So - let me reprhase that - exactly how can you do a syntax check in
> python? Something like perl's -c:
>
> ? ? ?perl -c script_name.p
>
> Ed

You might want to check PyFlakes; it doesn't execute scripts unlike
the others.

http://www.divmod.org/trac/wiki/DivmodPyflakes


From eckhardt at satorlaser.com  Mon Aug 10 10:37:25 2009
From: eckhardt at satorlaser.com (Ulrich Eckhardt)
Date: Mon, 10 Aug 2009 16:37:25 +0200
Subject: With or without leading underscore...
Message-ID: <5un5l6-fvn.ln1@satorlaser.homedns.org>

...that is the question!

I have a module which exports a type. It also exports a function that
returns instances of that type. Now, the reason for my question is that
while users will directly use instances of the type, they will not create
instances of the type themselves.

So, the type is a part of the public API, but its constructor is not. Should
I mark the type as private (with a leading underscore) or not?

Thanks!

Uli

-- 
Sator Laser GmbH
Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932



From mydevforums at gmail.com  Mon Aug 10 10:48:31 2009
From: mydevforums at gmail.com (IronyOfLife)
Date: Mon, 10 Aug 2009 07:48:31 -0700 (PDT)
Subject: Python configuration question when python scripts are executed 
	using Appweb as web server.
References: 
	
	
	
	
	
Message-ID: 

Hi Gabriel

Thanks for the detailed and useful reply.


On Aug 7, 1:37?am, "Gabriel Genellina"  wrote:
> En Thu, 06 Aug 2009 12:49:30 -0300, IronyOfLife  ?
> escribi?:
>
>
>
>
>
> > On Aug 5, 4:18?pm, "Gabriel Genellina"  wrote:
> >> En Tue, 04 Aug 2009 10:15:24 -0300, IronyOfLife 
> >> escribi?:
> >> > On Aug 3, 8:42?pm, "Gabriel Genellina"  wrote:
> >> >> En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife ?
> >>  ?
> >> >> escribi?:
>
> >> >> > I have installed python 2.6.2 in windows xp professional machine. I
> >> >> > have set the following environment variables -- PYTHONPATH. It ?
> >> points
> >> >> > to following windows folders: python root folder, the lib folder ?
> >> and
> >> >> > lib-tk folder.
>
> >> >> Why? Did you read it somewhere? Usually there is no need to set the ?
> >> >> PYTHONPATH variable at all; remove it.
>
> >> > Setting PYTHONPATH environment variables is mentioned in Python docs.
>
> >> Could you provide a link please? Setting PYTHONPATH should not be
>
> > Here are couple of links that discusses setting PYTHONPATH environment
> > variable.
> >http://docs.python.org/using/windows.html
>
> Ouch, that document should be reworked and updated!
>
> >http://www.daimi.au.dk/~chili/PBI/pythonpath.html
>
> That's mostly obsolete for current versions. Since PEP370 [0] was ?
> implemented, a per-user private directory is already in sys.path now, so ?
> there is no need to play with PYTHONPATH.

Thanks for the clarification on PYTHONPATH.
>
> > I understand your concerns regarding setting of PYTHONPATH while
> > multiple versions of Python are installed on the same machine. My fix
> > however does not use PYTHONPATH. The GNUTLS wrapper module for PYTHON
> > loads the GNUTLS dll's and it was not able to find them. Using FileMon
> > (win tool) I found out the paths that are scanned and I copied the
> > dlls to one of such paths. I still do not like this fix. This is a
> > temporary solution.
>
> Note that this cannot be fixed from inside Python. When you import a ?
> module, the interpreter scans the directories in ITS search path ?
> (sys.path) looking for a matching module. Once the module is found:
> - if it is a Python file, it's executed
> - if it is an extension module (a .pyd file, in fact a .dll renamed) it's ?
> loaded using LoadLibraryEx (a Windows function), and finally its ?
> initialization routine is executed.
>
> For LoadLibrary to successfully load the module, all its external ?
> references must be resolved. That is, Windows must locate and load all ?
> other DLLs that this module depends on, using its own search strategy [1], ?
> taking into account the PATH environment variable and many other places.
>
> It is at this stage that you get the error: when the gnutls wrapper ?
> attempts to load the gnutls DLL. That search is done by Windows, not by ?
> Python, and PYTHONPATH has nothing to do with it.
>
> Why different results in IIS and appweb? Note that there exist several ?
> search strategies, they depend on the application home directory, the ?
> location of the .exe, whether SetDllDirectory was called or not, whether ?
> the application has a manifest or not, a .local file or not... Hard to ?
> tell with so many variables.

This is fairly easy to explain. When I configured IIS to execute
python scripts, as per the documentation I pass two command line
arguments. Appweb works this way. It opens up a new command process
and in the function parameter for environment it sets only SYSTEMROOT.
It does not set the PATH variable (A BUG IN APPWEB which I have passed
on to them. They have not commented or provided any work around) for
Windows platform.

So while loading the gnutls client script is loaded, the following
path is searched
1. gnutls\library
2. C:\windows
3. C:\WIndows\system
4. C:\WIndows\system32
5. Folder where pyhton.exe is present.

And when I use IIS, the PATH variable is also set. So in this case all
the folders in the PATH are also searched and LoadLibrary is able to
successfully find the GNUTLS related Dlls without any issues.

You were mentioning about .local file or manifest file to specify the
path. I used the python's build command to build the wrapper. Is there
a way to mention in setup.py to generate the .manifest file? I wold
very much appreciate if you can help me with that.

I will also look for answers for how to modify setup.py to generate
manifest file or .local file etc..

>
> > Can you explain maybe with some sample how to set .pth files? Maybe
> > this will resolve my issue.
>
> Yes, but I don't think this will actually help with your issue.
>
> pth files are described here [2]. Suppose you want to add c:\foo\bar to ?
> sys.path, then write a file whatever.pth containing this single line:
>
> c:\foo\bar
>
> and place it on c:\your_python_installation\lib\site-packages
> When the interpreter starts, it will find the .pth file, read it, and add ?
> any directory it finds (that actually exists) to sys.path
>
> Note that another Python installation will use a diferent site-packages ?
> directory and won't find this particular .pth file, so different Python ?
> versions don't interfere.
>
> ---
>
> [0]http://python.org/dev/peps/pep-0370/
> [1]http://msdn.microsoft.com/en-us/library/ms682586(VS.85).aspx
> [2]http://docs.python.org/library/site.html
>
> --
> Gabriel Genellina



From ebonak at hotmail.com  Mon Aug 10 10:52:35 2009
From: ebonak at hotmail.com (Esmail)
Date: Mon, 10 Aug 2009 10:52:35 -0400
Subject: compression level with tarfile (w:gz) ?
In-Reply-To: 
References: 		
	
Message-ID: 

Benjamin Kaplan wrote:
> 
>> I can't find tarfile.gzopen  in the tarfile docs, I'm looking here:
>>
>>    http://docs.python.org/library/tarfile.html
>>
>> Am I looking at the wrong page?
>>
> 
> My mistake. It isn't a function of the tarfile module, it's a class
> method of tarfile.TarFile. I was looking at the help in the
> interactive interpreter. It doesn't seem to be in the official docs,
> but you can use pydoc to view the docstrings.

Thanks for the additional information,

Esmail



From davea at ieee.org  Mon Aug 10 10:52:55 2009
From: davea at ieee.org (Dave Angel)
Date: Mon, 10 Aug 2009 10:52:55 -0400
Subject: Need help in configuration for TimedRotatingFileHandler
In-Reply-To: 
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>	<4A7F3C83.1040607@ieee.org>	
	
Message-ID: <4A803447.70607@ieee.org>

Lokesh Maremalla wrote:
> 
> Code:
> mlogger = logging.getLogger("simpleExample")
> def a_view(request):
>     mlogger.debug("a_view called")
>     if request.method== "POST" :
>         mlogger.debug("post function")
>     else:
>         mlogger.debug("serve function")
>
> Execution:
> step1: Executed the code and got the log file with the information
> step2: Modified the system time from current day to next day
> step3: End up with the error and the error is pasted below
>
> Traceback (most recent call last):
>   File "c:\Python25\lib\logging\handlers.py", line 74, in emit
>     self.doRollover()
>   File "c:\Python25\lib\logging\handlers.py", line 274, in doRollover
>     os.rename(self.baseFilename, dfn)
> WindowsError: [Error 32] The process cannot access the file because it is
> being used by another process
>
> Python version - 2.5.4
>
> I guess my output should be like this for the next day
> -a new log file rotate_test. should generate in the respective
> location
>
> Please correct me if I am wrong.
>
>
> Thanks for your time.
>
> Regards,
> Lokesh
>
>   
Generally speaking, this error on os.rename() will occur if you haven't 
properly closed the file first, and if I recall correctly, Unix would 
have permitted a rename on an open file.  You're on Windows.  However, I 
don't know how that works with the logging package.  If the program has 
terminated, and you run it a second time on the following day (or after 
changing the system time), then I'd expect no trouble.  But I'm guessing 
your program is still running, and you just want to change from logging 
to yesterday's file to logging to today's file.

If I had to guess, I'd say that you have two instances of the logger 
running, and the second one is still holding the handle open.  But 
that's just a wild guess.

Could someone else who is familiar with logging, and with 
TimedRotatingFileHandler in particular, jump in here?  Preferably a 
Windows person?

DaveA


From matt.urry at googlemail.com  Mon Aug 10 10:54:38 2009
From: matt.urry at googlemail.com (ma3mju)
Date: Mon, 10 Aug 2009 07:54:38 -0700 (PDT)
Subject: Processes not exiting
References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com>
	
	<61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com>
	<01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> 
	
	 
	<996e50f5-c126-4ac2-ae8d-458d22a26ee1@v20g2000yqm.googlegroups.com> 
	<4b564f49-712c-408a-b8bd-9cff5af4a4fe@h30g2000vbr.googlegroups.com> 
	
Message-ID: <049e9160-5a92-47b9-9ac6-8e01573d5689@p15g2000vbl.googlegroups.com>

On 7 Aug, 16:02, MRAB  wrote:
> ma3mju wrote:
> > On 3 Aug, 09:36, ma3mju  wrote:
> >> On 2 Aug, 21:49, Piet van Oostrum  wrote:
>
> >>>>>>>> MRAB  (M) wrote:
> >>>> M> I wonder whether one of the workers is raising an exception, perhaps due
> >>>> M> to lack of memory, when there are large number of jobs to process.
> >>> But that wouldn't prevent the join. And you would probably get an
> >>> exception traceback printed.
> >>> I wonder if something fishy is happening in the multiprocessing
> >>> infrastructure. Or maybe the Fortran code goes wrong because it has no
> >>> protection against buffer overruns and similar problems, I think.
> >>> --
> >>> Piet van Oostrum 
> >>> URL:http://pietvanoostrum.com[PGP8DAE142BE17999C4]
> >>> Private email: p... at vanoostrum.org
> >> I don't think it's a memory problem, the reason for the hard and easy
> >> queue is because for larger examples it uses far more RAM. If I run
> >> all of workers with harder problems I do begin to run out of RAM and
> >> end up spending all my time switching in and out of swap so I limit
> >> the number of harder problems I run at the same time. I've watched it
> >> run to the end (a very boring couple of hours) and it stays out of my
> >> swap space and everything appears to be staying in RAM. Just hangs
> >> after all "poison" has been printed for each process.
>
> >> The other thing is that I get the message "here" telling me I broke
> >> out of the loop after seeing the poison pill in the process and I get
> >> all the things queued listed as output surely if I were to run out of
> >> memory I wouldn't expect all of the jobs to be listed as output.
>
> >> I have a serial script that works fine so I know individually for each
> >> example the fortran code works.
>
> >> Thanks
>
> >> Matt
>
> > Any ideas for a solution?
>
> A workaround is to do them in small batches.
>
> You could put each job in a queue with a flag to say whether it's hard
> or easy, then:
>
> ? ? ?while have more jobs:
> ? ? ? ? ?move up to BATCH_SIZE jobs into worker queues
> ? ? ? ? ?create and start workers
> ? ? ? ? ?wait for workers to finish
> ? ? ? ? ?discard workers

Yeah, I was hoping for something with a bit more finesse. In the end I
used pool instead with a callback function and that has solved the
problem. I did today find this snippet;

Joining processes that use queues

    Bear in mind that a process that has put items in a queue will
wait before terminating until all the buffered items are fed by the
?feeder? thread to the underlying pipe. (The child process can call
the Queue.cancel_join_thread() method of the queue to avoid this
behaviour.)

    This means that whenever you use a queue you need to make sure
that all items which have been put on the queue will eventually be
removed before the process is joined. Otherwise you cannot be sure
that processes which have put items on the queue will terminate.
Remember also that non-daemonic processes will be automatically be
joined.


I don't know (not a computer scientist) but could it have been the
pipe getting full?

In case anyway else is effected by this I've attached the new code to
see the changes I made to fix it.

Thanks for all your help

Matt

============================================================================================================================
parallel.py
============================================================================================================================
import GaussianProcessRegression as GP
import numpy as np
import networkx as nx
import pickle
from multiprocessing import Pool

global result

def cb(r):
    global result
    print r
    result[r[0]] = r[1]


############################################################################################
# Things You Can Change
############################################################################################
#savefiles
savefile = "powerlaw"
graphfile = "powerlawgraph"
#sample sizes
num_graphs = 5
num_sets_of_data = 10
#other things...
intervals = np.ceil(np.logspace(-2,1,50)*500)
noise = [np.sqrt(0.1),np.sqrt(0.01),np.sqrt(0.001),np.sqrt(0.0001)]
num_hard_workers = 5
hard_work_threshold = 4000
############################################################################################
#generate graphs
graphs  = []
for i in range(0,num_graphs):
    graphs.append(nx.powerlaw_cluster_graph(500,0.1,0.05))
#save them for later reference
filehandler = open(graphfile,'w')
pickle.dump(graphs,filehandler,-1)
filehandler.close()

#queues
easy_work = []
hard_work = []

#construct the items in the hard queue
l=0
for j in range(0,len(intervals)):
    for i in range(0,len(noise)):
        for k in range(0,num_graphs):
            if int(intervals[j]) <=hard_work_threshold:
                easy_work.append({'datapt': l,'graph': graphs
[k],'noise': noise[i],'number_of_sets_of_data':
num_sets_of_data,'number_of_data_points':int(intervals[j])})
            else:
                hard_work.append({'datapt': l,'graph': graphs
[k],'noise': noise[i],'number_of_sets_of_data':
num_sets_of_data,'number_of_data_points':int(intervals[j])})
            l+=1

result = np.zeros(l)

#create pool with all cores possible
worker_pool = Pool()

for i in xrange(0,len(easy_work)):
    worker_pool.apply_async(GP.RandomWalkGeneralizationErrorParallel,
(easy_work[i],),callback=cb)

worker_pool.close()
worker_pool.join()

#create hard work queue
worker_pool = Pool(processes = num_hard_workers)

for i in xrange(0,len(hard_work)):
    worker_pool.apply_async(GP.RandomWalkGeneralizationErrorParallel,
(hard_work[i],),callback=cb)

worker_pool.close()
worker_pool.join()


finaldata = result.reshape((len(intervals),len(noise),num_graphs))
np.save(savefile,finaldata)

================================================================================================================================================
GaussianProcessRegression.py
================================================================================================================================================
import CovarianceFunction as CF
import networkx as nx
import numpy as np
import scipy.linalg as sp
#fortran code from lapack-blas (hopefully when scipy updated this wont
be needed)
import dtrsv

#Currently we assume Gaussian noise TODO change to general noise
#Assume 0 mean TODO change to general mean Gaussian Process
class GaussianProcessRegression:
    def __init__(self,covariance_function,sigma):
        #a covariance function object defined in CovarianceFunction
class
        #note this uses the parent class but any children can be used
        self.C = covariance_function
        #a list of pts that are known and their values
        self.pts = []
        self.vals = []
        #the inverse of K as defined in
        #@book{coolen05:theoryofneural,
	    #ISBN = {0-19-853024-2},
	    #publisher = {Oxford University Press, USA},
	    #author = {Coolen, A. C. C. and K{\"{u}}hn, R. and Sollich, P.},
	    #title = {Theory of neural information processing systems},
	    #year = {2005},
        #}
        self.K = np.array([])
        #gaussian noise variable
        self.sigma = float(sigma)
        self.cholL = np.array([])


    def add_data_points(self,points,vals):
       #add all points to list
       self.pts += points
       self.vals += vals
       arraysize = len(self.pts)
       #construct K
       K = np.zeros((arraysize,arraysize))
       #for speed
       pts = self.pts
       between_points = self.C.between_points
       if len(self.K):
            K[:-1,:-1] = self.K
       for i in xrange(0,arraysize):
           for j in xrange(arraysize-len(points),arraysize):
                 K[i,j] = between_points(pts[i],pts[j])
                 K[j,i] = K[i,j]
       K[arraysize-len(points):arraysize,arraysize-len
(points):arraysize] =  K[arraysize-len(points):arraysize,arraysize-len
(points):arraysize] + self.sigma**2 * np.eye(len(points))
       self.K = K

    #calculate the prediction of a point based on data previously
given
    def point_prediction(self,points):
        mean = []
        variance =[]
        arraysize = len(self.pts)
        #cholesky
        #if self.cholL.shape[0] < arraysize:
        L=np.linalg.cholesky(self.K)
        #    self.cholL = L
        #else:
        #    L = self.cholL

        alpha = sp.cho_solve((L,1),self.vals)
        #create L in banded form
        k=np.zeros((arraysize,len(points)))
 
##################################################################
        #for speed get ref to functions im going to use and save them
        between_points = self.C.between_points
        pts = self.pts
        dot = np.dot
 
##################################################################
        for j in xrange(0,len(points)):
            #create k
            for i in xrange(0,arraysize):
                k[i,j] = between_points(pts[i],points[j])

        #calculate mean and variance
        #call the command for forward substitution
        ###############fortran
call#######################################
        v = dtrsv.dtrsv('L','N',arraysize,L,k)
 
##################################################################

        #result
        mean=dot(alpha,k)
        for i in xrange(0,len(points)):
            variance.append(between_points(points[i],points[i]) - dot(v
[:,i],v[:,i]))
        #return it in dictionary form
        return {'mean':mean,'variance':variance}


    # calculate the error for data given, where function is a vector
    # of the function evaluated at a sufficiently large number of
points
    # that the GPregression has been trying to learn
    def error(self,function):
        total = 0
        #sum up variances
        result = self.point_prediction(function[::2])
        total = np.sum(result['variance'])
        total = (1/float(len(function)/2))*total
        return total

    #clear what has been learnt so far
    def clear(self):
        self.pts = []
        self.vals = []
        self.K = np.array([])

    #calculate the average error for a function defined in function
when give
    #number_of_examples examples
    def average_error_over_samples(self,function, sample_size,
number_of_examples):
        avg = 0
        numberofpoints = len(function)/2
        for i in range(0,sample_size):
            self.clear()
            #generate points of the function
            permpts = np.random.randint
(0,numberofpoints,number_of_examples)
            #create the vectors
            pts = []
            vals = []
            for j in range(0,number_of_examples):
                pts.append(function[permpts[j]*2])
                vals.append(function[permpts[j]*2+1])

            #learn these points
            self.add_data_points(pts,vals)
            #print("points added")
            avg = avg + self.error(function)
        avg = avg/sample_size
        return avg





From jura.grozni at gmail.com  Mon Aug 10 10:55:42 2009
From: jura.grozni at gmail.com (azrael)
Date: Mon, 10 Aug 2009 07:55:42 -0700 (PDT)
Subject: wxpython question
Message-ID: <11f24035-bd42-4df8-879a-2e2558ee45ee@d23g2000vbm.googlegroups.com>

Is there maybe a method bounded to the class SpinCtrl() that could
hide the widget. One that is maybe also implemented in any other
control.

self.spcKvadDo = wx.SpinCtrl(id=-1, initial=0, max=1000000, min=0,
name='spcKvadDo', parent=self.pnlFilteri, pos=wx.Point(10, 10),
size=wx.Size(118, 21), style=wx.SP_ARROW_KEYS)

self.spcKvadOd.XXX()

I tried it with the SetTransparent() method but it did not work. Has
anyone any Idea?


From ebonak at hotmail.com  Mon Aug 10 10:55:42 2009
From: ebonak at hotmail.com (Esmail)
Date: Mon, 10 Aug 2009 10:55:42 -0400
Subject: compression level with tarfile (w:gz) ?
In-Reply-To: <20090810134108.GA7790@axis.g33x.de>
References:  <20090810134108.GA7790@axis.g33x.de>
Message-ID: 

Hi Lars,

Lars Gust?bel wrote:
> 
> How much smaller is it? I did a test with a recent Linux kernel source tree
> which made an archive of 337MB. Command-line gzip was ahead of Python's
> GzipFile() by just 20200 bytes(!) with an archive of about 74MB.
> 
>> Is the only way to accomplish the higher rate to create a tar file
>> and then use a different module to gzip it (assuming I can specify
>> the compression level there)?
> 
> If you need the disk space that badly, the alternative would be to pipe
> tarfile's output to command-line gzip somehow:

Thanks for the additional info and the workaround. I was mostly just
curious if there was a way to specify the compression level, so far
I'm ok with the generated file sizes, but it's good to know that there
are other options to specify my own compression level.

Thanks again,

Esmail



From zuo at chopin.edu.pl  Mon Aug 10 10:55:51 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Mon, 10 Aug 2009 16:55:51 +0200
Subject: With or without leading underscore...
In-Reply-To: <5un5l6-fvn.ln1@satorlaser.homedns.org>
References: <5un5l6-fvn.ln1@satorlaser.homedns.org>
Message-ID: 

10-08-2009 Ulrich Eckhardt  wrote:

> So, the type is a part of the public API, but its constructor is not.  
> Should
> I mark the type as private (with a leading underscore) or not?

IMHO you shouldn't (i.e. name should be marked "public") because of
possible usage of e.g. "isinstance(foo, YourType)".

Cheers,
*j

-- 
Jan Kaliszewski (zuo) 


From lutz at rmi.net  Mon Aug 10 10:58:11 2009
From: lutz at rmi.net (Mark Lutz)
Date: Mon, 10 Aug 2009 07:58:11 -0700 (PDT)
Subject: Florida Python training in October
Message-ID: 

We're pleased to announce a new venue for our Python classes.
Python author and trainer Mark Lutz will be teaching a 3-day
Python class on October 20-22, in Sarasota, Florida.  Come
spend 3 days mastering Python, and enjoy all that Florida and
its Gulf Coast have to offer while you're here.

This is a public training session open to individual enrollments,
and covers the same topics and hands-on lab work as the over 200
onsite sessions that Mark has taught.  The class provides an
in-depth introduction to both Python and its common applications,
and parallels the instructor's best-selling Python books.

This class is also newly retooled to cover recent changes in
both Python 2.6 and 3.1.  Whether you're using 2.X, using 3.X,
or stuck somewhere between them, you'll find that our class is
aimed at your needs.  For more information on this session,
please visit its web page:

http://home.earthlink.net/~python-training/2009-public-classes.htm

For additional background on the class itself, as well as a
preview of our 2010 Florida class schedule, see our home page:

http://home.earthlink.net/~python-training

Thanks for your interest,
--Mark Lutz's Python Training Services


From Scott.Daniels at Acm.Org  Mon Aug 10 10:58:47 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Mon, 10 Aug 2009 07:58:47 -0700
Subject: Unrecognized escape sequences in string literals
In-Reply-To: 
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
	
Message-ID: 

Douglas Alan wrote:
> So, what's the one obvious right way to express "foo\zbar"? Is it
>    "foo\zbar"
> or
>    "foo\\zbar"
> And if it's the latter, what possible benefit is there in allowing the
> former?  And if it's the former, why does Python echo the latter?

Actually, if we were designing from fresh (with no C behind us), I might
advocate for "\s" to be the escape sequence for a backslash.  I don't
particularly like that it is hard to see if the following string
contains a tab:   "abc\\\\\\\\\table".  The string rules reflect C's
rules, and I see little excuse for trying to change them now.

--Scott David Daniels
Scott.Daniels at Acm.Org


From piet at cs.uu.nl  Mon Aug 10 11:00:34 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Mon, 10 Aug 2009 17:00:34 +0200
Subject: reloading the module imported as 'from ... import ...'
References: <4A7F976D.7090600@ggmail.com>
	
	<4A7FB4AF.7060107@ggmail.com>
	
Message-ID: 

>>>>> Steven D'Aprano  (SD) wrote:

>SD> On Sun, 09 Aug 2009 22:48:31 -0700, AlF wrote:
>>> Steven D'Aprano wrote:
>>>> On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:
>>>> 
>>>>> Hi,
>>>>> 
>>>>> what is the best way to reload the module imported using 'from ...
>>>>> import ...'
>>>> 
>>>> 
>>>> Have you tried "from ... import ..." again?
>>>> 
>>>> 
>>> I have not because of an assumption that "import" imports the module
>>> just once. 

>SD> Ah, of course the cached module will still reflect the older version. 
>SD> Sorry, I was thinking about solving a different problem:

If you do a reload in between the cached version is replaced by the new
version. However, objects from the old module that have references
before the reload will still lie around. This could cause very subtle
bugs.

Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) 
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import testmod
>>> from testmod import TestClass
>>> a = TestClass()
>>> b = TestClass()
>>> a.__class__ is b.__class__
True
>>> reload(testmod)

>>> c = TestClass()
>>> c.__class__ is a.__class__
True
>>> from testmod import TestClass
>>> d = TestClass()
>>> d.__class__ is a.__class__
False

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From cornelius.keller at googlemail.com  Mon Aug 10 11:07:28 2009
From: cornelius.keller at googlemail.com (Cornelius Keller)
Date: Mon, 10 Aug 2009 08:07:28 -0700 (PDT)
Subject: variable & scoping question.
Message-ID: 

Hi,

I'm a quite fresh python programmer, (6 Month python experience).
Today I found something I absolotly don'nt understand:

given the following function:

def test_effect(class_id=None,class_ids=[]):
    if class_id is not None:
        if class_id not in class_ids:
            class_ids.append(int(class_id))

    print class_ids

I observe that the class_ids array is growing when it is called with
different class id's.

I expected class_ids to be [] if the keyword argument is not set, but
it seems to beahve like a static variable if not set.

example:


In [3]: test.test_effect(class_id=1)
[1]

In [4]: test.test_effect(class_id=1)
[1]

In [5]: test.test_effect(class_id=2)
[1, 2]

In [6]: test.test_effect(class_id=2)
[1, 2]

In [7]: test.test_effect(class_id=3)
[1, 2, 3]

Is this an intended python beahviour?

sincerly
- Cornelius






From deets at nospam.web.de  Mon Aug 10 11:12:29 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Mon, 10 Aug 2009 17:12:29 +0200
Subject: variable & scoping question.
References: 
Message-ID: <7earmtF2f4tvnU1@mid.uni-berlin.de>

Cornelius Keller wrote:

> Hi,
> 
> I'm a quite fresh python programmer, (6 Month python experience).
> Today I found something I absolotly don'nt understand:
> 
> given the following function:
> 
> def test_effect(class_id=None,class_ids=[]):
> ? ? if class_id is not None:
> ? ? ? ? if class_id not in class_ids:
> ? ? ? ? ? ? class_ids.append(int(class_id))
> 
> ? ? print class_ids
> 
> I observe that the class_ids array is growing when it is called with
> different class id's.
> 
> I expected class_ids to be [] if the keyword argument is not set, but
> it seems to beahve like a static variable if not set.

http://effbot.org/zone/default-values.htm

Diez


From rt8396 at gmail.com  Mon Aug 10 11:13:05 2009
From: rt8396 at gmail.com (r)
Date: Mon, 10 Aug 2009 08:13:05 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
Message-ID: <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>

On Aug 9, 11:02?pm, David Lyon  wrote:
> Since you're talking about documentation, which is a part of python,
> don't you think you should be discussing it on python-dev ?

Yea, them's be a friendly bunch to noob ideas ;). Hey i got a better
idea, lets go to the IRS and see if we can persuade them to stop
taxing us...

> That's where discussions about the documentation should be held.
> haha - I'm just curious to see how long it will for them to
> shut the discussion down.

Yea, probably not long at all, of course not before the troll calling,
bulling, defamation of character, etc, has lost it's fun.

> Before you do that, you should clearly work out in your own mind
> how you think things need to improve. It's not good enough just
> saying this or that is bad without having specific ideas on what
> needs to change.

see links that xah posted, and there is more he did not post.

> Good luck fellow sinner and blasphemer...
> How dare you suggest that things could be improved...

how dare YOU suggest they NOT be improved!!!


From darkwater42 at gmail.com  Mon Aug 10 11:21:03 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Mon, 10 Aug 2009 08:21:03 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
	
	
Message-ID: <86e09602-7eb1-4397-a77f-fb1e3c5b34b9@k26g2000vbp.googlegroups.com>

On Aug 10, 10:58?am, Scott David Daniels 
wrote:

>?The string rules reflect C's rules, and I see little
> excuse for trying to change them now.

No they don't. Or at least not C++'s rules. C++ behaves exactly as I
should like.

(Or at least g++ does. Or rather *almost* as I would like, as by
default it generates a warning for "foo\zbar", while I think that an
error would be somewhat preferable.)

But you're right, it's too late to change this now.

|>ouglas



From samwyse at gmail.com  Mon Aug 10 11:21:49 2009
From: samwyse at gmail.com (samwyse)
Date: Mon, 10 Aug 2009 08:21:49 -0700 (PDT)
Subject: setting Referer for urllib.urlretrieve
References: <1668f798-0a73-47a5-9f87-34312109c67c@v2g2000vbb.googlegroups.com>
	<028ed082$0$20617$c3e8da3@news.astraweb.com>
Message-ID: <73d9e384-30a0-4927-ac73-722d11c06d15@g6g2000vbr.googlegroups.com>

On Aug 9, 9:41?am, Steven D'Aprano  wrote:
> On Sun, 09 Aug 2009 06:13:38 -0700,samwysewrote:
> > Here's what I have so far:
>
> > import urllib
>
> > class AppURLopener(urllib.FancyURLopener):
> > ? ? version = "App/1.7"
> > ? ? referrer = None
> > ? ? def __init__(self, *args):
> > ? ? ? ? urllib.FancyURLopener.__init__(self, *args)
> > ? ? ? ? if self.referrer:
> > ? ? ? ? ? ? addheader('Referer', self.referrer)
>
> > urllib._urlopener = AppURLopener()
>
> > Unfortunately, the 'Referer' header potentially varies for each url that
> > I retrieve, and the way the module is written, I can't change the calls
> > to __init__ or open. The best idea I've had is to assign a new value to
> > my class variable just before calling urllib.urlretrieve(), but that
> > just seems ugly. ?Any ideas? ?Thanks.
>
> [Aside: an int variable is an int. A str variable is a str. A list
> variable is a list. A class variable is a class. You probably mean a
> class attribute, not a variable. If other languages want to call it a
> variable, or a sausage, that's their problem.]
>
> If you're prepared for a bit of extra work, you could take over all the
> URL handling instead of relying on automatic openers. This will give you
> much finer control, but it will also require more effort on your part.
> The basic idea is, instead of installing openers, and then ask the urllib
> module to handle the connection, you handle the connection yourself:
>
> make a Request object using urllib2.Request
> make an Opener object using urllib2.build_opener
> call opener.open(request) to connect to the server
> deal with the connection (retry, fail or read)
>
> Essentially, you use the Request object instead of a URL, and you would
> add the appropriate referer header to the Request object.
>
> Another approach, perhaps a more minimal change than the above, would be
> something like this:
>
> # untested
> class AppURLopener(urllib.FancyURLopener):
> ? ? version = "App/1.7"
> ? ? def __init__(self, *args):
> ? ? ? ? urllib.FancyURLopener.__init__(self, *args)
> ? ? def add_referrer(self, url=None):
> ? ? ? ? if url:
> ? ? ? ? ? ? addheader('Referer', url)
>
> urllib._urlopener = AppURLopener()
> urllib._urlopener.add_referrer("http://example.com/")

Thanks for the ideas.  I'd briefly considered something similar to
your first idea, implementing my own version of urlretrieve to accept
a Request object, but it does seem like a good bit of work.  Maybe
over Labor Day.  :)

The second idea is pretty much what I'm going to go with for now.  The
program that I'm writing is almost a clone of wget, but it fixes some
personal dislikes with the way recursive retrievals are done.  (Or
maybe I just don't understand wget's full array of options well
enough.)  This means that my referrer changes as I bounce up and down
the hierarchy, which makes this less convenient.  Still, it does seem
more convenient that re-writing the module from scratch.


From python at mrabarnett.plus.com  Mon Aug 10 11:25:20 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Mon, 10 Aug 2009 16:25:20 +0100
Subject: Processes not exiting
In-Reply-To: <049e9160-5a92-47b9-9ac6-8e01573d5689@p15g2000vbl.googlegroups.com>
References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com>		<61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com>	<01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com>
		
	<996e50f5-c126-4ac2-ae8d-458d22a26ee1@v20g2000yqm.googlegroups.com>
	<4b564f49-712c-408a-b8bd-9cff5af4a4fe@h30g2000vbr.googlegroups.com>
	
	<049e9160-5a92-47b9-9ac6-8e01573d5689@p15g2000vbl.googlegroups.com>
Message-ID: <4A803BE0.3090902@mrabarnett.plus.com>

ma3mju wrote:
> On 7 Aug, 16:02, MRAB  wrote:
>> ma3mju wrote:
>>> On 3 Aug, 09:36, ma3mju  wrote:
>>>> On 2 Aug, 21:49, Piet van Oostrum  wrote:
>>>>>>>>>> MRAB  (M) wrote:
>>>>>> M> I wonder whether one of the workers is raising an exception, perhaps due
>>>>>> M> to lack of memory, when there are large number of jobs to process.
>>>>> But that wouldn't prevent the join. And you would probably get an
>>>>> exception traceback printed.
>>>>> I wonder if something fishy is happening in the multiprocessing
>>>>> infrastructure. Or maybe the Fortran code goes wrong because it has no
>>>>> protection against buffer overruns and similar problems, I think.
>>>>> --
>>>>> Piet van Oostrum 
>>>>> URL:http://pietvanoostrum.com[PGP8DAE142BE17999C4]
>>>>> Private email: p... at vanoostrum.org
>>>> I don't think it's a memory problem, the reason for the hard and easy
>>>> queue is because for larger examples it uses far more RAM. If I run
>>>> all of workers with harder problems I do begin to run out of RAM and
>>>> end up spending all my time switching in and out of swap so I limit
>>>> the number of harder problems I run at the same time. I've watched it
>>>> run to the end (a very boring couple of hours) and it stays out of my
>>>> swap space and everything appears to be staying in RAM. Just hangs
>>>> after all "poison" has been printed for each process.
>>>> The other thing is that I get the message "here" telling me I broke
>>>> out of the loop after seeing the poison pill in the process and I get
>>>> all the things queued listed as output surely if I were to run out of
>>>> memory I wouldn't expect all of the jobs to be listed as output.
>>>> I have a serial script that works fine so I know individually for each
>>>> example the fortran code works.
>>>> Thanks
>>>> Matt
>>> Any ideas for a solution?
>> A workaround is to do them in small batches.
>>
>> You could put each job in a queue with a flag to say whether it's hard
>> or easy, then:
>>
>>      while have more jobs:
>>          move up to BATCH_SIZE jobs into worker queues
>>          create and start workers
>>          wait for workers to finish
>>          discard workers
> 
> Yeah, I was hoping for something with a bit more finesse. In the end I
> used pool instead with a callback function and that has solved the
> problem. I did today find this snippet;
> 
> Joining processes that use queues
> 
>     Bear in mind that a process that has put items in a queue will
> wait before terminating until all the buffered items are fed by the
> ?feeder? thread to the underlying pipe. (The child process can call
> the Queue.cancel_join_thread() method of the queue to avoid this
> behaviour.)
> 
>     This means that whenever you use a queue you need to make sure
> that all items which have been put on the queue will eventually be
> removed before the process is joined. Otherwise you cannot be sure
> that processes which have put items on the queue will terminate.
> Remember also that non-daemonic processes will be automatically be
> joined.
> 
> 
> I don't know (not a computer scientist) but could it have been the
> pipe getting full?
> 
> In case anyway else is effected by this I've attached the new code to
> see the changes I made to fix it.
> 
[snip]
Maybe the reason is this:

Threads share an address space, so putting data into a queue simply
involves putting a reference there, but processes don't share an address
space, so a sender must continue to exist until the data itself has been
copied into the pipe that connects the processes. This pipe has a
limited capacity.

In your code you were waiting for the easy workers to terminate and you
weren't reading from the queue, and maybe, therefore, the pipe either,
so with a large number of jobs the pipe was becoming full.

In summary: the worker didn't terminate because the pipe was full; the
pipe was full because you weren't reading the results; you weren't
reading the results because the worker hadn't terminated.


From bieffe62 at gmail.com  Mon Aug 10 11:36:52 2009
From: bieffe62 at gmail.com (Francesco Bochicchio)
Date: Mon, 10 Aug 2009 08:36:52 -0700 (PDT)
Subject: variable & scoping question.
References: 
	<7earmtF2f4tvnU1@mid.uni-berlin.de>
Message-ID: 

On Aug 10, 5:12?pm, "Diez B. Roggisch"  wrote:
> Cornelius Keller wrote:
> > Hi,
>
> > I'm a quite fresh python programmer, (6 Month python experience).
> > Today I found something I absolotly don'nt understand:
>
> > given the following function:
>
> > def test_effect(class_id=None,class_ids=[]):
> > ? ? if class_id is not None:
> > ? ? ? ? if class_id not in class_ids:
> > ? ? ? ? ? ? class_ids.append(int(class_id))
>
> > ? ? print class_ids
>
> > I observe that the class_ids array is growing when it is called with
> > different class id's.
>
> > I expected class_ids to be [] if the keyword argument is not set, but
> > it seems to beahve like a static variable if not set.
>
> http://effbot.org/zone/default-values.htm
>
> Diez

Maybe on the first page of python.org there should be a 'python
gotchas' link to a page listing these few
non-intuituive peculiarities of our beloved snake ... same goes for
the official python tutorial ...

Ciao
-----
FB



From cornelius.keller at googlemail.com  Mon Aug 10 11:46:17 2009
From: cornelius.keller at googlemail.com (Cornelius Keller)
Date: Mon, 10 Aug 2009 08:46:17 -0700 (PDT)
Subject: variable & scoping question.
References: 
	<7earmtF2f4tvnU1@mid.uni-berlin.de>
Message-ID: <93c50fc3-2cf9-4fc6-9919-cde7cfd273e6@o35g2000vbi.googlegroups.com>

On 10 Aug., 17:12, "Diez B. Roggisch"  wrote:
> Cornelius Keller wrote:
[snip]
>
> http://effbot.org/zone/default-values.htm
>
> Diez

Ok thank you.
I' understand now why.
I still think this is very confusing, because default values don't
behave like most people would expect without reading the docs.

- Cornelius


From MatzeGuentert at gmx.de  Mon Aug 10 11:55:06 2009
From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=)
Date: Mon, 10 Aug 2009 17:55:06 +0200
Subject: M2Crypto: How to generate subjectKeyIdentifier /
	authorityKeyIdentifier
In-Reply-To: 
References: 
	
	
	
Message-ID: <1249919706.3267.239.camel@celsius>

Now I have this patch applied to the M2Crypto SVN branch 




From piet at cs.uu.nl  Mon Aug 10 11:58:27 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Mon, 10 Aug 2009 17:58:27 +0200
Subject: Problem Regarding Handling of Unicode string
References: <9ac0e194-9e25-468a-9807-957ef3142dd3@i18g2000pro.googlegroups.com>
Message-ID: 

>>>>> joy99  (j) wrote:

>j> Dear Group,
>j> I am using Python26 on WindowsXP with service pack2. My GUI is IDLE.
>j> I am using Hindi resources and get nice output like:
>j> ??
>j> where I can use all the re functions and other functions without doing
>j> any transliteration,etc.
>j> I was trying to use Bengali but it is giving me output like:
>j> '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95'
>j> I wanted to see Bengali output as
>j> ????
>j> and I like to use all functions including re.
>j> If any one can help me on that.
>j> Best Regards,
>j> Subhabrata.

Make sure your stdout (in case you use print) has utf-8 encoding. This
might be problematic on Windows, however.

>>> print '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95'
????

Or if you write to a file, open it with utf-8 encoding.

I take utf-8 because in general this is the preferred encoding for
non-ASCII text. It could be that Bengali has a different preferred encoding.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From davea at ieee.org  Mon Aug 10 12:03:19 2009
From: davea at ieee.org (Dave Angel)
Date: Mon, 10 Aug 2009 12:03:19 -0400
Subject: Client/Server based on SocketServer and Windows
In-Reply-To: <979ad93c-0257-4add-8fb7-b56e253e3fb7@h30g2000vbr.googlegroups.com>
References: 	
	<979ad93c-0257-4add-8fb7-b56e253e3fb7@h30g2000vbr.googlegroups.com>
Message-ID: <4A8044C7.1080203@ieee.org>

Kiki wrote:
> Thank you Dennis
>
> I'm using 2 differents editor, which may be the cause of such a mess
> in the indentation.
>
> I must admitt that I lazily rely on those (not so bad indeed) editors.
>
> "If indentation whas bad they would have tell me"
>
> Too bad am i
>
> Won't post misindeted code anymore.
>
>   
No problem using multiple editors.  But you need to configure each one 
to *never* put tabs in the file (it should use spaces exclusively).  If 
you can't do that in one of the editors, then use the other editor 
exclusively.

Other useful but not mandatory features -
    - when tab is pressed, it should indent using spaces, to a multiple 
of 4 columns.
    - by default, indent a new line the same as the previous, or even 
based on the previous plus some syntax rules.
    - make tabs and/or spaces visible, so you can tell if the file has a 
mixture.

DaveA
  


From rt8396 at gmail.com  Mon Aug 10 12:09:17 2009
From: rt8396 at gmail.com (r)
Date: Mon, 10 Aug 2009 09:09:17 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
	<1d952f0b-9552-48ef-ad2e-a7b8e06ea8eb@n2g2000vba.googlegroups.com>
	
Message-ID: <6f54e63f-9f98-46a6-aff2-7b93a78b683b@e18g2000vbe.googlegroups.com>

On Aug 10, 9:13?am, MRAB  wrote:
> r wrote:
> > On Aug 8, 8:48 am, MRAB  wrote:
> > ...(snip)
> >> Bothwww.python.organdsvn.python.org are down. ?They're hosted on
> >> the same machine, and it seems to have run into disk problems and
> >> hasn't rebooted even after power-cycling. ?Thomas Wouters will be
> >> visiting the machine physically tomorrow to try to diagnose the
> >> problem.
>
> > Oh stop lying MRAB, everybody knows Guido hosts Python.org from his
> > attic on an old Linux box :-)
>
> That was a quote from A.M. Kuchling.
>
> It's actually hosted on a matchbox-sized multi-core multi-terabyte
> wifi-enabled Linux machine that Guido brought back from 2050.
> Unfortunately, the dog ate it, so he's had to go and buy another one!
> :-)

i just hope he gets one that has supported wifi drivers available! :-)


From ethan at stoneleaf.us  Mon Aug 10 12:13:34 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Mon, 10 Aug 2009 09:13:34 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>		<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>			<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
Message-ID: <4A80472E.4090108@stoneleaf.us>

Kee Nethery wrote:
> As someone trying to learn the language I want to say that the tone on  
> this list towards people who are trying to learn Python  feels like it  
> has become anti-newbies.
> 
> Learning a new language is difficult enough without seeing other  
> newbies getting shamed for not knowing everything there is to know  
> about Python before asking their questions.
> 
> For example, the guy who was looking for Python sample code for the  
> Google Map API, calling him a troll was harsh. Suggesting he broach  the 
> question to Google was a reasonable answer. By the same token, his  
> asking this list about the missing Python examples seems reasonable  
> also. Seems to me that people on a Python list might have some  
> background knowledge or even samples of the Google Python code that  was 
> no longer on the Google web site.
> 
> There seems to be a general consensus among the newbies that other  
> languages have a user contributions resource tied to the main official  
> docs to allow newbies to teach each other what they have learned. The  
> desire is for python.org to have the same kind of support resource so  
> that us newbies can self support each other.
> 
> Kee Nethery

As someone who is (hopefully!) leaving newbieness I can say I have had 
no problem with the helpfullness of this list.  I will also say that 
before I ever posted any questions I had devoured Dive Into Python and 
How To Think Like a Computer Scientist Using Python (both excellent), 
and I try to put as much detail into my questions as I can so nobody has 
to guess what I'm trying to do.

As someone who relies heavily on the docs I will also say that the idea 
of giving the ability to modify the official documentation to somebody 
who is /learning/ the language is, quite frankly, terrifying.  I have no 
issues with a seperate system, some of which have been suggested, but 
good reference documentation is crucial.  If you find examples lacking, 
there are plenty of web-sites, or even (dare I say it?) actual hard-copy 
books!  ;)  My bookshelf currently has Learning Python, Programming 
Python, Python Cookbook, Python Programming on Win32, and Regular 
Expressions.  All great books, and not too pricey if you can get them used.

My $0.02.

~Ethan~


From dorzey at googlemail.com  Mon Aug 10 12:15:07 2009
From: dorzey at googlemail.com (dorzey)
Date: Mon, 10 Aug 2009 09:15:07 -0700 (PDT)
Subject: Problem when fetching page using urllib2.urlopen
References: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>
	<0579ebc0-2542-4f96-af3e-9861ad646b13@d9g2000prh.googlegroups.com>
Message-ID: 

"geturl - this returns the real URL of the page fetched. This is
useful because urlopen (or the opener object used) may have followed a
redirect. The URL of the page fetched may not be the same as the URL
requested." from http://www.voidspace.org.uk/python/articles/urllib2.shtml#info-and-geturl

It might be worth checking that you are actually getting the page you
want; I seem to remember that semicolons need to be encoded, similar
to '&'.

Dorzey

On Aug 10, 12:43?pm, jitu  wrote:
> On Aug 10, 4:39?pm, jitu  wrote:
>
> > Hi,
>
> > A html page ?contains 'anchor' elements with 'href' attribute ?having
> > a semicolon ?in the url , while fetching the page using
> > urllib2.urlopen, all such href's ?containing ?'semicolons' are
> > truncated.
>
> > For example the hrefhttp://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt...
> > get truncated tohttp://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i
>
> > The page I am talking about can be fetched fromhttp://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_...
>
> > Thanks a Lot
> > Regards
> > jitu
>
> Hi
>
> ? ?Sorry, the question what I wanted to ask was, whether is this the
> correct behaviour or a bug ?
>
> Thanks A Lot.
> Regards
> jitu



From MatzeGuentert at gmx.de  Mon Aug 10 12:19:17 2009
From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=)
Date: Mon, 10 Aug 2009 16:19:17 +0000
Subject: M2Crypto: How to generate subjectKeyIdentifier /
	authorityKeyIdentifier
In-Reply-To: 
References: 
	
	
	
Message-ID: <1249921157.3267.263.camel@celsius>

Hello once again

Now I have the extension-patch [0] applied to the M2Crypto SVN branch
(revision 704). Creating a root and an subRoot CA certificate now works
great including the SKID/AKID extensions. 

I am also able to verify those created certificates using:

$ openssl verify -CAfile rootCA.crt rootCA.crt 
rootCA.crt: OK

$ openssl verify -CAfile rootCA.crt subRootCA.crt 
subRootCA.crt: OK

But having a closer look onto the generated key ID's shows that there is
either something wrong in the way I am adding the subjectKeyIdentifier
extension or the way the hash gets calculated in the background. 

This are the hashes:

__rootCA__			
SKID F4:EF:64:5F:7A:A2:2A:14:14:F9:AE:6E:DB:04:78:0A:8C:6E:02:9F -: A
--> OKAY
AKID F4:EF:64:5F:7A:A2:2A:14:14:F9:AE:6E:DB:04:78:0A:8C:6E:02:9F -: A
--> OKAY

__subRootCA (signed by rootCA)__ 	
SKID DA:39:A3:EE:5E:6B:4B:0D:32:55:BF:EF:95:60:18:90:AF:D8:07:09 -: B
--> OKAY
AKID F4:EF:64:5F:7A:A2:2A:14:14:F9:AE:6E:DB:04:78:0A:8C:6E:02:9F -: A
--> OKAY

__client (signed by rootCA)__
SKID DA:39:A3:EE:5E:6B:4B:0D:32:55:BF:EF:95:60:18:90:AF:D8:07:09 -: B
--> NOT OKAY, should be different from RootCA
AKID F4:EF:64:5F:7A:A2:2A:14:14:F9:AE:6E:DB:04:78:0A:8C:6E:02:9F -: A
--> OKAY

__client (signed by subRootCA)__
SKID DA:39:A3:EE:5E:6B:4B:0D:32:55:BF:EF:95:60:18:90:AF:D8:07:09 -: B
--> NOT OKAY, should be different from subRootCA
AKID DA:39:A3:EE:5E:6B:4B:0D:32:55:BF:EF:95:60:18:90:AF:D8:07:09 -: B
--> OKAY

I really would be happy if someone could have a look at my code [1] as
this extensions are important for verifying the trust chain. Please let
me know if there is anything I can do with my limited knowledge about
OpenSSL to get this working... 

Regards, Matthias 

[0] https://bugzilla.osafoundation.org/attachment.cgi?id=5106
[1] http://code.google.com/p/webca/source/browse/trunk/src/ca.py




From gert.cuykens at gmail.com  Mon Aug 10 12:41:19 2009
From: gert.cuykens at gmail.com (gert)
Date: Mon, 10 Aug 2009 09:41:19 -0700 (PDT)
Subject: resume upload wsgi script
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
	
	<7e85i3F2fdc1eU1@mid.uni-berlin.de>
	<9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com>
	<7e8ildF2f1hcpU1@mid.uni-berlin.de>
	<49e41062-9e0d-4c5e-beca-edb02d3ce6e8@e34g2000vbm.googlegroups.com>
	<7ea4lpF2dvr5cU1@mid.uni-berlin.de>
Message-ID: 

On Aug 10, 10:39?am, "Diez B. Roggisch"  wrote:
> > 250KB :)
>
> So why do you bother?
>
> > Its just HTTP1.1 has everything for making ftp like file transfers
> > possible.
> > When I write it to a file then I am back at square one because I still
> > need to load it completely to get it into a blob.
>
> Well, the blob is nothing but datat in the file-system. If you are
> *really* concerned about that, then don't use the db, but use the
> filesystem, appending to the file until it's finished - and storing a
> reference to it to the DB. We do that as well, because otherwise the db
> will become unmanagable anyway (dumping, backups).
>

I also hate debugging sql that contains blob data. So if using files
how do you clean the http post stuff?
(b+r'.*?Content-Type: application/octet-stream\r\n\r\n(.*?)\r
\n--'+b,file,DOTALL)
using as litlle memory as possible ?
I can not use PUT upload only because flash does not support PUT.


From python at mrabarnett.plus.com  Mon Aug 10 12:42:50 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Mon, 10 Aug 2009 17:42:50 +0100
Subject: variable & scoping question.
In-Reply-To: 
References: 	<7earmtF2f4tvnU1@mid.uni-berlin.de>
	
Message-ID: <4A804E0A.2090202@mrabarnett.plus.com>

Francesco Bochicchio wrote:
> On Aug 10, 5:12 pm, "Diez B. Roggisch"  wrote:
>> Cornelius Keller wrote:
>>> Hi,
>>> I'm a quite fresh python programmer, (6 Month python experience).
>>> Today I found something I absolotly don'nt understand:
>>> given the following function:
>>> def test_effect(class_id=None,class_ids=[]):
>>>     if class_id is not None:
>>>         if class_id not in class_ids:
>>>             class_ids.append(int(class_id))
>>>     print class_ids
>>> I observe that the class_ids array is growing when it is called with
>>> different class id's.
>>> I expected class_ids to be [] if the keyword argument is not set, but
>>> it seems to beahve like a static variable if not set.
>> http://effbot.org/zone/default-values.htm
>>
>> Diez
> 
> Maybe on the first page of python.org there should be a 'python
> gotchas' link to a page listing these few
> non-intuituive peculiarities of our beloved snake ... same goes for
> the official python tutorial ...
> 
Should they be called 'snake bites'? Well, pythons are constrictors, not
biters, but if Python is being non-intuitive... :-)


From ethan at stoneleaf.us  Mon Aug 10 12:55:46 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Mon, 10 Aug 2009 09:55:46 -0700
Subject: variable & scoping question.
In-Reply-To: <93c50fc3-2cf9-4fc6-9919-cde7cfd273e6@o35g2000vbi.googlegroups.com>
References: 	<7earmtF2f4tvnU1@mid.uni-berlin.de>
	<93c50fc3-2cf9-4fc6-9919-cde7cfd273e6@o35g2000vbi.googlegroups.com>
Message-ID: <4A805112.8020308@stoneleaf.us>

Cornelius Keller wrote:
[snip]

> I still think this is very confusing, because default values don't
> behave like most people would expect without reading the docs.
> 
> - Cornelius

Why would you expect to become a good programmer of _any_ language 
without reading its docs?

~Ethan~


From deets at nospam.web.de  Mon Aug 10 13:11:12 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Mon, 10 Aug 2009 19:11:12 +0200
Subject: Problem when fetching page using urllib2.urlopen
References: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>
	<0579ebc0-2542-4f96-af3e-9861ad646b13@d9g2000prh.googlegroups.com>
	
Message-ID: <7eb2lgF2ec7u9U1@mid.uni-berlin.de>

dorzey wrote:

> "geturl - this returns the real URL of the page fetched. This is
> useful because urlopen (or the opener object used) may have followed a
> redirect. The URL of the page fetched may not be the same as the URL
> requested." from
> http://www.voidspace.org.uk/python/articles/urllib2.shtml#info-and-geturl
> 
> It might be worth checking that you are actually getting the page you
> want; I seem to remember that semicolons need to be encoded, similar
> to '&'.

You remember wrong.

http://www.faqs.org/rfcs/rfc2396.html

See Section 3.3, path-components.

Diez


From abecedarian314159 at yahoo.com  Mon Aug 10 13:19:31 2009
From: abecedarian314159 at yahoo.com (William)
Date: Mon, 10 Aug 2009 10:19:31 -0700 (PDT)
Subject: reloading the module imported as 'from ... import ...'
In-Reply-To: <4A7FB4AF.7060107@ggmail.com>
References: <4A7F976D.7090600@ggmail.com>
	
	<4A7FB4AF.7060107@ggmail.com>
Message-ID: <208933.60826.qm@web110606.mail.gq1.yahoo.com>

What about using the reimport library?

http://code.google.com/p/reimport/

Cheers,
William



________________________________
From: AlF 
To: python-list at python.org
Sent: Monday, August 10, 2009 1:48:31 AM
Subject: Re: reloading the module imported as 'from ... import ...'

Steven D'Aprano wrote:
> On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:
> 
>> Hi,
>> 
>> what is the best way to reload the module imported using 'from ...
>> import ...'
> 
> 
> Have you tried "from ... import ..." again?
> 

I have not because of an assumption that "import" imports the module just once. In fact this still works that way:

here is a terminal 1:

$ cat > a.py
a=1
$ cat > a.py
a=2
$


and terminal 2:

>>> from a import a
>>> a
1
>>> a
1
>>> from a import a
>>> a
1
>>>

In spite of changing a.py in fly, the imported a is still 1


-- http://mail.python.org/mailman/listinfo/python-list



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From pavlovevidence at gmail.com  Mon Aug 10 13:28:25 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Mon, 10 Aug 2009 10:28:25 -0700 (PDT)
Subject: With or without leading underscore...
References: <5un5l6-fvn.ln1@satorlaser.homedns.org>
Message-ID: <4d6719e4-217a-4921-bd26-228fd4944eb7@r24g2000vbn.googlegroups.com>

On Aug 10, 7:37?am, Ulrich Eckhardt  wrote:
> ...that is the question!
>
> I have a module which exports a type. It also exports a function that
> returns instances of that type. Now, the reason for my question is that
> while users will directly use instances of the type, they will not create
> instances of the type themselves.
>
> So, the type is a part of the public API, but its constructor is not. Should
> I mark the type as private (with a leading underscore) or not?


I would not use the underscore.

If the initializer is private you might consider dispensing with
__init__ (have it raise TypeError), and initialize it from a "private"
method or classmethod, or even directly from the factory function.
And if you're wondering how the hell you're going to create the object
of type A when you've disabled __init__, see the example classmethod
below.


class A(object):
    def __init__(self,*args,**kwargs):
        raise TypeError('Type not callable; use factory function
instead')

    @classmethod
    def _create_object(cls,initial_value):
        self = object.__new__(cls) # avoid __init__
        self.value = initial_value



Carl Banks


From dorzey at googlemail.com  Mon Aug 10 13:28:51 2009
From: dorzey at googlemail.com (dorzey)
Date: Mon, 10 Aug 2009 10:28:51 -0700 (PDT)
Subject: Problem when fetching page using urllib2.urlopen
References: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>
	<0579ebc0-2542-4f96-af3e-9861ad646b13@d9g2000prh.googlegroups.com> 
	 
	<7eb2lgF2ec7u9U1@mid.uni-berlin.de>
Message-ID: <474e7cc0-f563-4e62-ab9e-61b16451a9bf@q14g2000vbi.googlegroups.com>

On 10 Aug, 18:11, "Diez B. Roggisch"  wrote:
> dorzey wrote:
> > "geturl - this returns the real URL of the page fetched. This is
> > useful because urlopen (or the opener object used) may have followed a
> > redirect. The URL of the page fetched may not be the same as the URL
> > requested." from
> >http://www.voidspace.org.uk/python/articles/urllib2.shtml#info-and-ge...
>
> > It might be worth checking that you are actually getting the page you
> > want; I seem to remember that semicolons need to be encoded, similar
> > to '&'.
>
> You remember wrong.
>
> http://www.faqs.org/rfcs/rfc2396.html
>
> See Section 3.3, path-components.
>
> Diez

My memory has been known to let me down on occasions ;) Thank you for
correcting my mistake.


From pavlovevidence at gmail.com  Mon Aug 10 13:29:27 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Mon, 10 Aug 2009 10:29:27 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
Message-ID: 

On Aug 10, 4:41?am, MRAB  wrote:
> Steven D'Aprano wrote:
> > On Sun, 09 Aug 2009 17:56:55 -0700, Douglas Alan wrote:
>
> [snip]
> >> My point of view is that
> >> every language has *some* warts; Python just has a bit fewer than most.
> >> It would have been nice, I should think, if this wart had been "fixed"
> >> in Python 3, as I do consider it to be a minor wart.
>
> > And if anyone had cared enough to raise it a couple of years back, it
> > possibly might have been.
>
> My preference would've been that a backslash followed by A-Z, a-z, or
> 0-9 is special, but a backslash followed by any other character is just
> the character, except for backslash followed by a newline, which
> suppresses the newline.

That would be reasonable; it'd match the behavior of regexps.


Carl Banks



From pavlovevidence at gmail.com  Mon Aug 10 13:43:08 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Mon, 10 Aug 2009 10:43:08 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
Message-ID: <0702d438-253e-4c8c-a26f-9247d824010a@e4g2000vbe.googlegroups.com>

On Aug 10, 1:37?am, Steven D'Aprano
 wrote:
> On Mon, 10 Aug 2009 00:37:33 -0700, Carl Banks wrote:
> > On Aug 9, 11:10?pm, Steven D'Aprano
> >  wrote:
> >> On Sun, 09 Aug 2009 18:34:14 -0700, Carl Banks wrote:
> >> >> Why should a backslash in a string literal be an error?
>
> >> > Because the behavior of \ in a string is context-dependent, which
> >> > means a reader can't know if \ is a literal character or escape
> >> > character without knowing the context, and it means an innocuous
> >> > change in context can cause a rather significant change in \.
>
> >> *Any* change in context is significant with escapes.
>
> >> "this \nhas two lines"
>
> >> If you change the \n to a \t you get a significant difference. If you
> >> change the \n to a \y you get a significant difference. Why is the
> >> first one acceptable but the second not?
>
> > Because when you change \n to \t, you've haven't changed the meaning of
> > the \ character;
>
> I assume you mean the \ character in the literal, not the (non-existent)
> \ character in the string.
>
> > but when you change \n to \y, you have, and you did so
> > without even touching the backslash.
>
> Not at all.
>
> '\n' maps to the string chr(10).
> '\y' maps to the string chr(92) + chr(121).
>
> In both cases the backslash in the literal have the same meaning: grab
> the next token (usually a single character, but not always), look it up
> in a mapping somewhere, and insert the result in the string object being
> built.

That is a ridiculous rationalization.  Nobody sees "\y" in a string
and thinks "it's an escape sequence that returns the bytes '\y'".


[snip rest, because an argument in favor inconsistent, context-
dependent behavior doesn't need any further refutation than to point
out that it is an argument in favor of inconsistent, context-dependent
behavior]


Carl Banks


From rickbking at comcast.net  Mon Aug 10 13:44:17 2009
From: rickbking at comcast.net (Rick King)
Date: Mon, 10 Aug 2009 13:44:17 -0400
Subject: how to use "exec" stmt to get input from user 
Message-ID: <4A805C71.4010809@comcast.net>

I have a cmd.py-derived program (with a wxPython GUI) and want to 
execute python statements for lines that are not my own special commands.

So basically it's either:

    def do_somecommand(self,arg):
        ...

or

    def default(self,arg):
        exec arg in globals(),self.cmdlocals

(where cmdlocals is a my local dictionary)

in default() I'd like to be able to execute any python statement 
including something like

    "x = raw_input('>')"

when I do this though it goes to the command window and so any user of 
the program would be confused, which also means I have to have a command 
window.

If I add this:

    self.stdin = self.edt_console_input   (where self.edt_console_input 
is a wxPython text control)

it just gets an EOF right away.

Is there any way to do what I want to do? This might be better posted on 
the wxpython list.

Thanks for any help!

Rick King
Southfield MI




From darkwater42 at gmail.com  Mon Aug 10 13:52:05 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Mon, 10 Aug 2009 10:52:05 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
	
	
	<86e09602-7eb1-4397-a77f-fb1e3c5b34b9@k26g2000vbp.googlegroups.com>
Message-ID: <274a2d6a-a154-4d22-a093-c1c29457f71f@z34g2000vbl.googlegroups.com>

I wrote:

> But you're right, it's too late to change this now.

P.S. But if it weren't too late, I think that your idea to have "\s"
be the escape sequence for a backslash instead of "\\" might be a good
one.

|>ouglas


From starsareblueandfaraway at gmail.com  Mon Aug 10 13:53:13 2009
From: starsareblueandfaraway at gmail.com (Roy Hyunjin Han)
Date: Mon, 10 Aug 2009 13:53:13 -0400
Subject: Python documentation servers
Message-ID: <6a5569ec0908101053x53e8070escae5e6535325afb@mail.gmail.com>

Are there issues with the python documentation servers?
http://docs.python.org/
The site has been really slow to respond all weekend.


From 71david at libero.it  Mon Aug 10 14:00:06 2009
From: 71david at libero.it (David)
Date: Mon, 10 Aug 2009 20:00:06 +0200
Subject: wxpython question
References: <11f24035-bd42-4df8-879a-2e2558ee45ee@d23g2000vbm.googlegroups.com>
Message-ID: 

Il Mon, 10 Aug 2009 07:55:42 -0700 (PDT), azrael ha scritto:

> Is there maybe a method bounded to the class SpinCtrl() that could
> hide the widget. One that is maybe also implemented in any other
> control.

AFAIK, any widget can be made invisibile calling the .Show(False) method of
the container sizer.
http://docs.wxwidgets.org/stable/wx_wxsizer.html#wxsizershow

David


From dullrich at sprynet.com  Mon Aug 10 14:10:14 2009
From: dullrich at sprynet.com (David C Ullrich)
Date: Mon, 10 Aug 2009 13:10:14 -0500
Subject: how to use "exec" stmt to get input from user
References: 
Message-ID: 

What you're trying to do and what's not working isn't 
entirely clear to me.

But if I had a wxPython application and I wanted to
execute user input (note the _if_) I'd just pop up a window
(I forget how "ShowModal" is spelled in wx right now)
with a text box and an Execute button and a Cancel
button - if the user hits the Execute button I'd
attempt to execute what he'd typed in the box.

There are reasons you want to be very careful about
this...

On Mon, 10 Aug 2009 13:44:17 -0400, Rick King wrote:

> I have a cmd.py-derived program (with a wxPython GUI) and want to
> execute python statements for lines that are not my own special
> commands.
> 
> So basically it's either:
> 
>     def do_somecommand(self,arg):
>         ...
> 
> or
> 
>     def default(self,arg):
>         exec arg in globals(),self.cmdlocals
> 
> (where cmdlocals is a my local dictionary)
> 
> in default() I'd like to be able to execute any python statement
> including something like
> 
>     "x = raw_input('>')"
> 
> when I do this though it goes to the command window and so any user of
> the program would be confused, which also means I have to have a command
> window.
> 
> If I add this:
> 
>     self.stdin = self.edt_console_input   (where self.edt_console_input
> is a wxPython text control)
> 
> it just gets an EOF right away.
> 
> Is there any way to do what I want to do? This might be better posted on
> the wxpython list.
> 
> Thanks for any help!
> 
> Rick King
> Southfield MI



From rt8396 at gmail.com  Mon Aug 10 14:35:39 2009
From: rt8396 at gmail.com (r)
Date: Mon, 10 Aug 2009 11:35:39 -0700 (PDT)
Subject: pybotwar-0.5
References:  
	<3e9c5fcd-4047-4edd-b2ec-d892c77e3a69@f33g2000vbm.googlegroups.com>
Message-ID: 

On Aug 9, 9:46?pm, Mensanator  wrote:
> On Aug 9, 3:26?pm, Lee Harr  wrote:
>
> > pybotwar is a fun and educational game where players
> > create computer programs to control simulated robots
> > to compete in a battle arena.
>
> >http://pybotwar.googlecode.com/
>
> Why is the doc folder empty?
>
> Shouldn't you supply some hint on how the games works
> and at least a rudimentary guide to robot design?
>
> What version to you expect that will be in? 1.0? 10.0?
>
> Could you inform us when you have something worth looking
> at and not before so we don't have to waste our time?

What a bombastically stupid thing to say even for you "Menstrual
cycle". Sure, there is no documentation but maybe the creator meant
for this module to be used only by experienced Python programmers and
not script kiddies like yourself who need a four page tut just to code
up a hello world.py. If you are anything more than an amateur the
source code should be all the documentation you need to use this
module. If not, get on with your pathetic life!

Next time before you open your mouth, try to use those two brain cells
you have left up there and put together a reasonable and responsible
response that is more than just a cowardly put down. Now run along
little spam bot, i am sure one of the other thousands of groups you
post to can't wait for your triumphant return!

r "slayer of the galactic-ly stupid!"


From jcd at sdf.lonestar.org  Mon Aug 10 14:47:19 2009
From: jcd at sdf.lonestar.org (J. Cliff Dyer)
Date: Mon, 10 Aug 2009 14:47:19 -0400
Subject: variable & scoping question.
In-Reply-To: <93c50fc3-2cf9-4fc6-9919-cde7cfd273e6@o35g2000vbi.googlegroups.com>
References: 
	<7earmtF2f4tvnU1@mid.uni-berlin.de>
	<93c50fc3-2cf9-4fc6-9919-cde7cfd273e6@o35g2000vbi.googlegroups.com>
Message-ID: <1249930039.17682.5.camel@aalcdl07>

On Mon, 2009-08-10 at 08:46 -0700, Cornelius Keller wrote:
> On 10 Aug., 17:12, "Diez B. Roggisch"  wrote:
> > Cornelius Keller wrote:
> [snip]
> >
> > http://effbot.org/zone/default-values.htm
> >
> > Diez
> 
> Ok thank you.
> I' understand now why.
> I still think this is very confusing, because default values don't
> behave like most people would expect without reading the docs.
> 
> - Cornelius

You are correct.  This is confusing at first blush.  The important thing
to remember is: *don't do that.*  Learn the pythonic workaround of using
None in your parameters whenever you want a default empty list, and
don't let it bother you too much.  Overall, python is a remarkably well
designed language.  This is one of the relatively rare warts that crept
in because it enables a broader cleanliness of design.

Cheers,
Cliff




From rt8396 at gmail.com  Mon Aug 10 15:10:08 2009
From: rt8396 at gmail.com (r)
Date: Mon, 10 Aug 2009 12:10:08 -0700 (PDT)
Subject: Python documentation servers
References: 
Message-ID: 

On Aug 10, 12:53?pm, Roy Hyunjin Han
 wrote:
> Are there issues with the python documentation servers?http://docs.python.org/
> The site has been really slow to respond all weekend.

try this thread
http://groups.google.com/group/comp.lang.python/browse_thread/thread/052368a71f2a8ad2/929bd74bd203c6e8?hl=en&lnk=raot8

PS Just ignore the OT humor near the bottom ;)


From breamoreboy at yahoo.co.uk  Mon Aug 10 15:11:53 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Mon, 10 Aug 2009 20:11:53 +0100
Subject: pybotwar-0.5
In-Reply-To: 
References: 
	<3e9c5fcd-4047-4edd-b2ec-d892c77e3a69@f33g2000vbm.googlegroups.com>
	
Message-ID: 

[snip]
> r "slayer of the galactic-ly stupid!"
Can I assume from this that you intend killing yourself, on the grounds 
that some 10 days ago you couldn't successfully use a windows compiled 
help file?
-- 
Kindest regards.

Mark Lawrence.



From piet at cs.uu.nl  Mon Aug 10 15:36:55 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Mon, 10 Aug 2009 21:36:55 +0200
Subject: Problem when fetching page using urllib2.urlopen
References: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>
Message-ID: 

>>>>> jitu  (j) wrote:

>j> Hi,
>j> A html page  contains 'anchor' elements with 'href' attribute  having
>j> a semicolon  in the url , while fetching the page using
>j> urllib2.urlopen, all such href's  containing  'semicolons' are
>j> truncated.


>j> For example the href http://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt=AlWSqpkpqhICp1lMgChtJkCdGWoL
>j> get truncated to http://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i

>j> The page I am talking about can be fetched from
>j> http://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_ylc=X3oDMTFka28zOGNuBF9TAzI3NjY2NzkEX3MDOTY5NTUzMjUEc2VjA3NzcC1kZXN0BHNsawN0aXRsZQ--

It's not python that causes this. It is the server that sends you the
URLs without these parameters (that's what they are).

To get them you have to tell the server that you are a respectable
browser. E.g.

import urllib2

url = 'http://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt=AlWSqpkpqhICp1lMgChtJkCdGWoL'

url = 'http://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_ylc=X3oDMTFka28zOGNuBF9TAzI3NjY2NzkEX3MDOTY5NTUzMjUEc2VjA3NzcC1kZXN0BHNsawN0aXRsZQ--'

hdrs = {'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13',
       'Accept': 'image/*'}

request = urllib2.Request(url = url, headers = hdrs)
page = urllib2.urlopen(request).read()

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From piet at cs.uu.nl  Mon Aug 10 15:38:39 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Mon, 10 Aug 2009 21:38:39 +0200
Subject: www.python.org website is down?
References: 
	
	<1d952f0b-9552-48ef-ad2e-a7b8e06ea8eb@n2g2000vba.googlegroups.com>
	
Message-ID: 

>>>>> MRAB  (M) wrote:

>M> r wrote:
>>> On Aug 8, 8:48 am, MRAB  wrote:
>>> ...(snip)
>>>> Bothwww.python.organd svn.python.org are down.  They're hosted on
>>>> the same machine, and it seems to have run into disk problems and
>>>> hasn't rebooted even after power-cycling.  Thomas Wouters will be
>>>> visiting the machine physically tomorrow to try to diagnose the
>>>> problem.
>>> 
>>> Oh stop lying MRAB, everybody knows Guido hosts Python.org from his
>>> attic on an old Linux box :-)

>M> That was a quote from A.M. Kuchling.

>M> It's actually hosted on a matchbox-sized multi-core multi-terabyte
>M> wifi-enabled Linux machine that Guido brought back from 2050.
>M> Unfortunately, the dog ate it, so he's had to go and buy another one!

The 2050 models can run on the internal heat of a dog !!
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From rt8396 at gmail.com  Mon Aug 10 16:56:57 2009
From: rt8396 at gmail.com (r)
Date: Mon, 10 Aug 2009 13:56:57 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	
Message-ID: <081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com>

On Aug 10, 11:13?am, Ethan Furman  wrote:
(snip)
> As someone who relies heavily on the docs I will also say that the idea
> of giving the ability to modify the official documentation to somebody
> who is /learning/ the language is, quite frankly, terrifying.
(snip)

Ethan,
I think what you and a few others seem to miss is ... Of course nobody
wants Joe-Noob writing the Python docs -- thats lunacy, would you give
your 12 year old the keys to a shiny new corvette? -- No! What people
are asking for is the ability for a noobs input on the official docs,
and for that input to be taken seriously. Sure some of the suggestions
will be nothing more than "helpful ignoramuses" with unhelpful
suggestions as some have said, but the input channels need to be
there. Currently Python dev seems to be more output than input,
however i could be wrong? We some real I/O going on here.

Also the Python tut is full of fluff (sorry Guido) and it contributes
to late learning of the language. Luckily however Python has many
users who really love the language and have taken the time to write
beautiful tutorials that start at various levels of entry. Read xah's
take on the official tutorial, it's spot on baby!

A little note for tutorial writers:
==================================

Dear Expert,
Whilst writing any tutorial on any subject matter please remember, you
may be an expert, but mostly *non-experts* will be reading your
material... pssft, this may come as a surprise, but tutorials are
meant for *NON-EXPERTS*!

Please refrain from stroking your own ego by obstrufcation of the very
ideas you wish to convey to these influential minds. Sure exposing
your huge intelligence to the world may give you warm-fuzzies-in-your-
tummy, but believe me your poor students will be rendered as helpless
as Paris Hilton at a "panties required" spelling bee.

Please try, and i know this is a lot to ask, to use the most simple
explanation to convey the point -- and *only* the point at hand! Take
for example the introduction of functions. You could go with your gut
instinct, "shoot from the hip" and pop off something like this that
prints a Fibonacci series up to n...

def fib(n):
    a, b = 0, 1
    while b < n:
        print b,
        a, b = b, a+b

>>> fib(2000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

And all you would have accomplished was to blow holes thru the
students mind! Now like the next guy, i love calculating series of
numbers all day, but this is a piss poor example of functions for the
new student, or anybody for that matter!  While your student is
racking his brain trying to figure out what "a" and "b" stand for,
much less n, and not to mention what the heck a "Fibonacci" series is
in the first place (Google can help though) , he (the student) has
forgotten that this example is simply how to write and call a
function. A much better example would be the following...

def add(x, y):
    print x+y

>>> add(1, 2)
3

WOW,  with that small piece of code you have just transported three
main principals of a function in a very simple and strait forward way
smack-dab into the cerebral cortex of the student, and your fingers
did not even break a sweat!

 1. function names should describe exactly what they do
 2. functions take arguments
 3. functions do something with those arguments(like mini programs!)

You could followup with this fine example that extents on the
first...

def add(x, y=2)
    return x+y

>>> add(1,2)

>>> print add(1, 2)
3
>>> print add(1)
3
>>> print add(100, 5.5)
100.5
>>> print add()
error...


However Ethan (and Co.),  not everybody who downloads Python the first
time knows about this. Also the Python website is filled to the brim
with a hodgepodge of "links-here" "links-there", "links-every-freaking-
where" (are we getting paid by the link people?) causing most noobs
brain to start blowing chunks just while tring to find a good
alternative to the official tut!

Really, it's bloat on a proportion that only elephant sized bloat
wares like M$, M$-Office, Adobe-PDF, and the like, can hold a candle
to. Python really needs and enema, and thats no joke!


From mensanator at aol.com  Mon Aug 10 17:01:58 2009
From: mensanator at aol.com (Mensanator)
Date: Mon, 10 Aug 2009 14:01:58 -0700 (PDT)
Subject: pybotwar-0.5
References:  
	<3e9c5fcd-4047-4edd-b2ec-d892c77e3a69@f33g2000vbm.googlegroups.com> 
	
Message-ID: 

On Aug 10, 1:35?pm, r  wrote:
>
> Sure, there is no documentation

http://www.mensanator.com/mensanator/PythonTurtle/paper.htm



From rickbking at comcast.net  Mon Aug 10 17:36:27 2009
From: rickbking at comcast.net (Rick King)
Date: Mon, 10 Aug 2009 17:36:27 -0400
Subject: how to use "exec" stmt to get input from user
In-Reply-To: 
References: 
	
Message-ID: <4A8092DB.3090703@comcast.net>

Thanks for your comment.

The purpose of the application is to automate the manipulation of large 
numbers of files. For automation I want to be able to have scripts that 
I can use for various purposes.

On input, cmd.py handles calling "do_...." methods for known commands; 
for the rest I want to "exec" the lines with my own dictionary. This 
allows me to use python statements, so I can do things like 
concatenating variables to form directory names, and so on. I'd like to 
be able to use any python statement, including "x=raw_input('>')", but 
this currently brings everything to a halt.

One thing this app does is execute processes using wxPythons wx.Process 
object and wx.Execute function. wxPython makes it easy to redirect stdin 
and stdout. I'm trying to do a similar thing for individual python 
statements. I'm not sure that makes sense.

I hope that's clear.

Rick


David C Ullrich wrote:
> What you're trying to do and what's not working isn't 
> entirely clear to me.
>
> But if I had a wxPython application and I wanted to
> execute user input (note the _if_) I'd just pop up a window
> (I forget how "ShowModal" is spelled in wx right now)
> with a text box and an Execute button and a Cancel
> button - if the user hits the Execute button I'd
> attempt to execute what he'd typed in the box.
>
> There are reasons you want to be very careful about
> this...
>
> On Mon, 10 Aug 2009 13:44:17 -0400, Rick King wrote:
>
>   
>> I have a cmd.py-derived program (with a wxPython GUI) and want to
>> execute python statements for lines that are not my own special
>> commands.
>>
>> So basically it's either:
>>
>>     def do_somecommand(self,arg):
>>         ...
>>
>> or
>>
>>     def default(self,arg):
>>         exec arg in globals(),self.cmdlocals
>>
>> (where cmdlocals is a my local dictionary)
>>
>> in default() I'd like to be able to execute any python statement
>> including something like
>>
>>     "x = raw_input('>')"
>>
>> when I do this though it goes to the command window and so any user of
>> the program would be confused, which also means I have to have a command
>> window.
>>
>> If I add this:
>>
>>     self.stdin = self.edt_console_input   (where self.edt_console_input
>> is a wxPython text control)
>>
>> it just gets an EOF right away.
>>
>> Is there any way to do what I want to do? This might be better posted on
>> the wxpython list.
>>
>> Thanks for any help!
>>
>> Rick King
>> Southfield MI
>>     
>
>   
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From longbotham at gmail.com  Mon Aug 10 17:38:08 2009
From: longbotham at gmail.com (Nathan)
Date: Mon, 10 Aug 2009 14:38:08 -0700 (PDT)
Subject: numpy array merge
Message-ID: <427654ff-5455-4198-bc86-d810ef3fafd6@t11g2000prh.googlegroups.com>

Is there an easy way to merge two numpy arrays with different rank
sizes (terminology?).  I want to make a single array by concatenating
two arrays along a given direction and filling the excess cells with a
dummy variable.  numpy concatenate works well as long as the two
arrays have the same dimension, but I want to do this on two array
with a matching dimension size.  An example:

import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = np.array([[1,2],[3,4],[5,6]])
np.concatenate((a,a),axis=1)  #This works fine, but isn't what I need.
Out:  array([[1, 2, 3, 1, 2, 3],
       [4, 5, 6, 4, 5, 6]])
np.concatenate((a,b),axis=1)  #This doesn't work, but this is what I
need.

I want to fill the third row of array "a" with a dummy variable (99999
or NaN) and concatenate with "b" to make:
[1,2,3,1,2]
[4,5,6,4,5]
[99999,99999,99999,5,6]

This just seems like it would be relatively common.  So I thought I'd
check if I'm missing something before I go write the logic.  Thanks!


From mail at johannes-janssen.de  Mon Aug 10 17:51:59 2009
From: mail at johannes-janssen.de (Johannes Janssen)
Date: Mon, 10 Aug 2009 23:51:59 +0200
Subject: How to find out in which module an instance of a class is created?
In-Reply-To: <4A7F6016.2060408@cheimes.de>
References: <4A7F4874.8030008@johannes-janssen.de>
	<4A7F6016.2060408@cheimes.de>
Message-ID: <4A80967F.9030604@johannes-janssen.de>

Christian Heimes schrieb:
> Johannes Janssen wrote:
>>  > class A(object):
>>  >     def __init__(self, mod=__name__):
>>  >         self.mod = mod
>>
>> .... won't work. In this case mod would always be "foo".
>
> You have to inspect the stack in order to get the module of the 
> caller. The implementation of warnings.warn() gives you some examples 
> how to get the module name.
>
> Christian
>
Thanks for the quick and very helpful reply. Basically just copying from 
warnings.warn(), I came up with this:

import sys

class A(object):
    def __init__(self, mod=None):
        if mod is None:
            self.mod = sys._getframe(1).f_globals['__name__']
        else:
            self.mod = mod

In warnings.warn() they used try around sys._getframe(1). As far as I 
understand what is done in warnings, there it is not sure what object 
caused the warning and therefore it is not sure whether you can or 
cannot use sys._getframe(1). Though in my case it should be quite clear. 
Can I be sure that my code will always work?

Johannes


From aahz at pythoncraft.com  Mon Aug 10 18:02:00 2009
From: aahz at pythoncraft.com (Aahz)
Date: 10 Aug 2009 15:02:00 -0700
Subject: help with threads
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
Message-ID: 

In article <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c at l5g2000pra.googlegroups.com>,
Michael Mossey   wrote:
>
>I have a simple application that needs one thread to manage networking
>in addition to the main "thread" that does the main job. It's not
>working right. I know hardly anything about threads, so I was hoping
>someone could point me in the right direction to research this.

You might also consider the multiprocessing module.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz


From patx44 at gmail.com  Mon Aug 10 18:12:43 2009
From: patx44 at gmail.com (patx)
Date: Mon, 10 Aug 2009 18:12:43 -0400
Subject: fastPATX (a new and simple web browser)
Message-ID: <699f51260908101512n42fa053bj41646f816f8c3f9b@mail.gmail.com>

There was a new release of fastPATX today. However the code and the program
itself will not be available to the public untill Tuesday the 11th. This is
due to me not having the proper tools I need to publish it (I am not at my
"main comp."). This is a bit of an over statement it will probably be
published near midnight Florida time. There are many different places you
can get fastPATX. I will cover them below:
http://bitbucket.org/patx/fastpatx/
http://patx44.appspot.com/
http://www.hawkee.com/snippet/6429/

More places may be out there (mirrors) but I do not know, they are NOT
official but I do 100% support them, and encourage many to mirror fastPATX.

fastPATX official wiki - http://bitbucket.org/patx/fastpatx

JJTComputing have given a great review of fastPATX and it has been linked to
on many site (Tuxmachines). I strongly wish that if you use fastPATX to blog
or tweet (include an @h_erd ???) about, even if you did not like it! Also if
you do like it please follow the project on bitbucket.org >>
http://bitbucket.org/patx/fastpatx/follow/

If you have any questions or suggestions please email me.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From darkwater42 at gmail.com  Mon Aug 10 18:17:24 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Mon, 10 Aug 2009 15:17:24 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
Message-ID: <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>

From: Steven D'Aprano  wrote:

> On Mon, 10 Aug 2009 00:32:30 -0700, Douglas Alan wrote:

> > In C++, if I know that the code I'm looking at compiles,
> > then I never need worry that I've misinterpreted what a
> > string literal means.

> If you don't know what your string literals are, you don't
> know what your program does. You can't expect the compiler
> to save you from semantic errors. Adding escape codes into
> the string literal doesn't change this basic truth.

I grow weary of these semantic debates. The bottom line is
that C++'s strategy here catches bugs early on that Python's
approach doesn't. It does so at no additional cost.

>From a purely practical point of view, why would any
language not want to adopt a zero-cost approach to catching
bugs, even if they are relatively rare, as early as
possible?

(Other than the reason that adopting it *now* is sadly too
late.)

Furthermore, Python's strategy here is SPECIFICALLY
DESIGNED, according to the reference manual to catch bugs.
I.e., from the original posting on this issue:

     Unlike Standard C, all unrecognized escape sequences
     are left in the string unchanged, i.e., the backslash
     is left in the string. (This behavior is useful when
     debugging: if an escape sequence is mistyped, the
     resulting output is more easily recognized as broken.)

If this "feature" is designed to catch bugs, why be
half-assed about it? Especially since there seems to be
little valid use case for allowing programmers to be lazy in
their typing here.

> The compiler can't save you from typing 1234 instead of
> 11234, or 31.45 instead of 3.145, or "My darling Ho"
> instead of "My darling Jo", so why do you expect it to
> save you from typing "abc\d" instead of "abc\\d"?

Because in the former cases it can't catch the the bug, and
in the latter case, it can.

> Perhaps it can catch *some* errors of that type, but only
> at the cost of extra effort required to defeat the
> compiler (forcing the programmer to type \\d to prevent
> the compiler complaining about \d). I don't think the
> benefit is worth the cost. You and your friend do. Who is
> to say you're right?

Well, Bjarne Stroustrup, for one.

All of these are value judgments, of course, but I truly
doubt that anyone would have been bothered if Python from
day one had behaved the way that C++ does. Additionally, I
expect that if Python had always behaved the way that C++
does, and then today someone came along and proposed the
behavior that Python currently implements, so that the
programmer could sometimes get away with typing a bit less,
such a person would be chided for not understanding the Zen
of Python.

> > You don't have to go running for the manual every time
> > you see code with backslashes, where the upshot might be
> > that the programmer was merely saving themselves some
> > typing.

> Why do you care if there are "funny characters"?

Because, of course, "funny characters" often have
interesting consequences when output. Furthermore, their
consequences aren't always immediately obvious from looking
at the source code, unless you are intimately familiar with
the function of the special characters in question.

For instance, sometimes in the wrong combination, they wedge
your xterm. Etc.

I'm surprised that this needs to be spelled out.

> In C++, if you see an escape you don't recognize, do you
> care?

Yes, of course I do. If I need to know what the program
does.

> Do you go running for the manual? If the answer is No,
> then why do it in Python?

The answer is that I do in both cases.

> No. \z *is* a legal escape sequence, it just happens to map to \z.

> If you stop thinking of \z as an illegal escape sequence
> that Python refuses to raise an error for, the problem
> goes away. It's a legal escape sequence that maps to
> backslash + z.

(1) I already used that argument on my friend, and he wasn't
buying it. (Personally, I find the argument technically
valid, but commonsensically invalid. It's a language-lawyer
kind of argument, rather than one that appeals to any notion
of real aesthetics.)

(2) That argument disagrees with the Python reference
manual, which explicitly states that "unrecognized escape
sequences are left in the string unchanged", and that the
purpose for doing so is because it "is useful when
debugging".

> > "\x" is not a legal escape sequence. Shouldn't it also
> > get left as "\\x"?
>
> No, because it actually is an illegal escape sequence.

What makes it "illegal". As far as I can tell, it's just
another "unrecognized escape sequence". JavaScript treats it
that way. Are you going to be the one to tell all the
JavaScript programmers that their language can't tell a
legal escape sequence from an illegal one?

> > Well, I think he's more annoyed that if Python is going
> > to be so helpful as to put in the missing "\" for you in
> > "foo\zbar", then it should put in the missing "\" for
> > you in "\". He considers this to be an inconsistency.
>
> (1) There is no missing \ in "foo\zbar".
>
> (2) The problem with "\" isn't a missing backslash, but a
> missing end- quote.

Says who? All of this really depends on your point of
view. The whole morass goes away completely if one adopts
C++'s approach here.

> Python isn't DWIMing here. The rules are simple and straightforward,
> there's no mind-reading or guessing required.

It may not be a complex form of DWIMing, but it's still
DWIMing a bit. Python is figuring that if I typed "\z", then
either I must have really meant to type "\\z", or that I
want to see the backslash when I'm debugging because I made
a mistake, or that I'm just too lazy to type "\\z".

> Is it "a form of DWIMing" to consider 1.234e1 and 12.34
> synonymous?

That's a very different issue, as (1) there are very
significant use cases for both kinds of numerical
representations, and (2) there's often only one obvious way
way that the number should be entered, depending on the
coding situation.

> What about 86 and 0x44? Is that DWIMing?

See previous comment.

> I'm sure both you and your friend are excellent
> programmers, but you're tossing around DWIM as a
> meaningless term of opprobrium without any apparent
> understand of what DWIM actually is.

I don't know if my friend even knows the term DWIM, other
than me paraphrasing him, but I certainly understand all
about the term. It comes from InterLisp. When DWIM was
enabled, your program would run until it hit an error, and
for certain kinds of errors, it would wait a few seconds for
the user to notice the error message, and if the user didn't
tell the program to stop, it would try to figure out what
the user most likely meant, and then continue running using
the computer-generated "fix".

I.e., more or less like continuing on in the face of what
the Python Reference manual refers to as an "unrecognized
escape sequence".

|>ouglas


From 7of77 at web.de  Mon Aug 10 18:24:21 2009
From: 7of77 at web.de (bernd)
Date: Mon, 10 Aug 2009 15:24:21 -0700 (PDT)
Subject: illegal geld machen , schnell geld verdienen in , schnell geld im 
	internet , geld 2.0 geld verdienen im web 2.0 ,
	novoline american poker 
	online spielen , sofort geld im internet , mehr geld verdienen ,
	roulette geld machen ,
References: <692f7f6b-2235-429f-be42-c3d04cdcb134@r37g2000yqd.googlegroups.com>
	<7350a4df-0ba2-4cb4-ab39-f7fda00bc729@t13g2000yqt.googlegroups.com>
Message-ID: 

On 25 Jul., 00:50, entr... at web.de wrote:
> On 7 Jun., 19:48, swirler... at googlemail.com wrote:
> , schnell geld verdienenwww.novocasinos.de
> http://www.novocasinos.de
> http://casino-pirat.de
> www.casino-pirat.de
> www.novocasinos.de
> http://www.novocasinos.de
> > *www.novocasinos.de
> > *http://www.novocasinos.de
> > *
> > +++ SOFORT GEWINN +++ REICH WERDEN +++
> > *http://WWW.novolinecasinos.de
> > *http://www.novocasinos.de
> > *www.casino-pirat.de
> > *www.novocasinos.de
>
> > geld im internet verdienen mit geld verdienen mit online umfragen
> > damit geld machen blog geld verdienen
> > schnell geld verdiehnen geld sparen leicht
> > jetzt sofort schnelles geld drakensang geld verdienen
> > www schnell geld im internet verdienen forum
> > geld sparen leicht gemacht ebook geld verdienen im internet
> > wie kann ich online geld verdienen man schnell geld machen
> > gewinn24 jetzt sofort reunion schnell geld
> > wo kann ich geld gewinn online spielen und geld
> > schnell geld zu verdienen einfach und schnell geld
> > viel geld verdienen im internet online poker echtes geld
> > geld seite geld verdienen mit internet
> > ich schnelles geld machen geld im internet verdienen ohne
> > internet geld vedienen geld machen von
> > internet geld verdient geld online gewinnen
> > schnell zu geld man online geld verdienen
> > geld machen wenn geld verdienen mit web
> > http://novocasinos.de
> > geld verdienen mit homepage geld verdienen durch online- Zitierten Text ausblenden -
>
> - Zitierten Text anzeigen -



From david.lyon at preisshare.net  Mon Aug 10 19:56:21 2009
From: david.lyon at preisshare.net (David Lyon)
Date: Mon, 10 Aug 2009 19:56:21 -0400
Subject: wxpython question
In-Reply-To: <11f24035-bd42-4df8-879a-2e2558ee45ee@d23g2000vbm.googlegroups.com>
References: <11f24035-bd42-4df8-879a-2e2558ee45ee@d23g2000vbm.googlegroups.com>
Message-ID: 


is there a method/property called Show/Shown ?

On Mon, 10 Aug 2009 07:55:42 -0700 (PDT), azrael 
wrote:
> Is there maybe a method bounded to the class SpinCtrl() that could
> hide the widget. One that is maybe also implemented in any other
> control.
> 
> self.spcKvadDo = wx.SpinCtrl(id=-1, initial=0, max=1000000, min=0,
> name='spcKvadDo', parent=self.pnlFilteri, pos=wx.Point(10, 10),
> size=wx.Size(118, 21), style=wx.SP_ARROW_KEYS)
> 
> self.spcKvadOd.XXX()
> 
> I tried it with the SetTransparent() method but it did not work. Has
> anyone any Idea?


From david.lyon at preisshare.net  Mon Aug 10 20:05:00 2009
From: david.lyon at preisshare.net (David Lyon)
Date: Mon, 10 Aug 2009 20:05:00 -0400
Subject: Python docs disappointing - group effort to hire
	=?UTF-8?Q?writers=3F?=
In-Reply-To: <4A80472E.4090108@stoneleaf.us>
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>		<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>			<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	<4A80472E.4090108@stoneleaf.us>
Message-ID: <0985e0fe54bf41fa3736cd6697d42bf4@preisshare.net>

On Mon, 10 Aug 2009 09:13:34 -0700, Ethan Furman 
wrote:
> As someone who relies heavily on the docs I will also say that the idea 
> of giving the ability to modify the official documentation to somebody 
> who is /learning/ the language is, quite frankly, terrifying.  

What is more terrifying is the way feedback from newbies is handled.

Your statement implies that the only way feedback can be handled is
to throw the keys down in discust and walk away. That's primative
behaviour. And misleading, because that isn't going to happen.

> My bookshelf currently has Learning Python, Programming 
> Python, Python Cookbook, Python Programming on Win32, and Regular 
> Expressions.  All great books, and not too pricey if you can get them
used.

So, what you're advocating is let things stay how they are...

Ignore feedback... tell people to freak off...




From http  Mon Aug 10 21:28:47 2009
From: http (Paul Rubin)
Date: 10 Aug 2009 18:28:47 -0700
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	
	<081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com>
Message-ID: <7xr5vj9m0g.fsf@ruckus.brouhaha.com>

r  writes:
> Whilst writing any tutorial on any subject matter please remember, you
> may be an expert, but mostly *non-experts* will be reading your
> material... pssft, this may come as a surprise, but tutorials are
> meant for *NON-EXPERTS*!

I think the Python tutorial is aimed at users who are newbies to
Python but not newbies to programming.  Writing a tutorial for total
newbies is a completely different problem, that would result in a much
different document that's less useful to the existing tutorial's
intended audience.


From pacificik at warnell.uga.edu  Mon Aug 10 22:11:04 2009
From: pacificik at warnell.uga.edu (Krishna Pacifici)
Date: Mon, 10 Aug 2009 22:11:04 -0400
Subject: dictionary help
Message-ID: <4A809AF80200008C000149EC@redhorse.forestry.uga.edu>

Hi,
kind of a newbie here, but I have two questions that are probably pretty simple.

1.  I need to get rid of duplicate values that are associated with different keys in a dictionary.  For example I have the following code.
s={}
s[0]=[10,2,3]
 s[10]=[22,23,24]
 s[20]=[45,5]
s[30]=[2,4]
s[40]=[6,7,8]

Now I want to be able to loop through the primary keys and get rid of duplicates (both in keys and values) so that I would have either a new dictionary or the same dictionary but with the following values:

s[0]=[3]
 s[10]=[22,23,24]
 s[20]=[45,5]
s[30]=[2,4]
s[40]=[6,7,8]

It doesn't matter which value gets removed as long as there is only one remaining, so in this example it doesn't matter that 2 got removed from s[0] or from s[30] as long as there is only one 2 in the dictionary.

2.  I need to be able to loop over the values in the dictionary when there are multiple values assigned to each key like above and assign new values to those values.  Taking the above example I would want to assign a new value so that when you called s[0] it would equal [3,4] say if 4 was the new value.  I think this should be as simple as adding a value, but I kept on having difficulty.

Any suggestions would be greatly appreciated.

Thank you very much,
Krishna

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From gagsl-py2 at yahoo.com.ar  Mon Aug 10 22:15:03 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Mon, 10 Aug 2009 23:15:03 -0300
Subject: Python configuration question when python scripts are executed
	using Appweb as web server.
References: 
	
	
	
	
	
	
Message-ID: 

En Mon, 10 Aug 2009 11:48:31 -0300, IronyOfLife 
escribi?:

>> Why different results in IIS and appweb? [...]
> This is fairly easy to explain. When I configured IIS to execute
> python scripts, as per the documentation I pass two command line
> arguments. Appweb works this way. It opens up a new command process
> and in the function parameter for environment it sets only SYSTEMROOT.
> It does not set the PATH variable (A BUG IN APPWEB which I have passed
> on to them. They have not commented or provided any work around) for
> Windows platform.

Perhaps you could configure appweb to call a .bat file like this, instead
of directly invoking python?

set path=%path%;other;directories;added
c:\path\to\python.exe %*

(this is slightly off topic now...)

> You were mentioning about .local file or manifest file to specify the
> path. I used the python's build command to build the wrapper. Is there
> a way to mention in setup.py to generate the .manifest file? I wold
> very much appreciate if you can help me with that.
>
> I will also look for answers for how to modify setup.py to generate
> manifest file or .local file etc..

The last part is easy: foo.exe.local is just an empty file in the same
directory as foo.exe - when it exists, DLLs are searched first on the
directory containing the application [1]

With manifest files I can't help. I suggest you create a new thread with
that question, perhaps in the distutils-SIG mailing list [2]

[1] http://msdn.microsoft.com/en-us/library/ms682600(VS.85).aspx
[2] http://mail.python.org/mailman/listinfo/distutils-sig

-- 
Gabriel Genellina



From jcd at sdf.lonestar.org  Mon Aug 10 23:07:49 2009
From: jcd at sdf.lonestar.org (J. Cliff Dyer)
Date: Mon, 10 Aug 2009 23:07:49 -0400
Subject: dictionary help
In-Reply-To: <4A809AF80200008C000149EC@redhorse.forestry.uga.edu>
References: <4A809AF80200008C000149EC@redhorse.forestry.uga.edu>
Message-ID: <1249960069.5675.8.camel@webb>

On Mon, 2009-08-10 at 22:11 -0400, Krishna Pacifici wrote:
> Hi,
> kind of a newbie here, but I have two questions that are probably
> pretty simple.
> 
> 1.  I need to get rid of duplicate values that are associated with
> different keys in a dictionary.  For example I have the following
> code.
> s={}
> s[0]=[10,2,3]
> s[10]=[22,23,24]
> s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
> 
> Now I want to be able to loop through the primary keys and get rid of
> duplicates (both in keys and values) so that I would have either a new
> dictionary or the same dictionary but with the following values:
> 
> s[0]=[3]
> s[10]=[22,23,24]
> s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
> 
> It doesn't matter which value gets removed as long as there is only
> one remaining, so in this example it doesn't matter that 2 got removed
> from s[0] or from s[30] as long as there is only one 2 in the
> dictionary.
> 
So if the number is a key, you want to keep the key, and delete all
matching values, and if the number is not a key, you want to keep one
(any one) instance of that number?  I'm not sure that what you are
looking for is best represented by a dict.  You might want to consider
creating your own class and overriding __getitem__.


> 2.  I need to be able to loop over the values in the dictionary when
> there are multiple values assigned to each key like above and assign
> new values to those values.  Taking the above example I would want to
> assign a new value so that when you called s[0] it would equal [3,4]
> say if 4 was the new value.  I think this should be as simple as
> adding a value, but I kept on having difficulty.
> 
Here you might want to either use the append() method on the lists of
each entry.

> Any suggestions would be greatly appreciated.
> 
I'm not sure what you are doing maps cleanly to currently existing
datastructures, which means that there might not be a quick shortcut for
you.  Hammer out the specs of what you want your class to be able to do,
and what the API will be for performing each of those functions.  Then
you should be able to begin implementing it, or at least come up with
some more specific questions.



> Thank you very much,
> Krishna

Cheers,
Cliff




From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 23:27:59 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 03:27:59 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
	
	
	<86e09602-7eb1-4397-a77f-fb1e3c5b34b9@k26g2000vbp.googlegroups.com>
Message-ID: 

On Mon, 10 Aug 2009 08:21:03 -0700, Douglas Alan wrote:

> But you're right, it's too late to change this now.

Not really. There is a procedure for making non-backwards compatible 
changes. If you care deeply enough about this, you could agitate for 
Python 3.2 to raise a PendingDepreciation warning for "unexpected" escape 
sequences like \z, Python 3.3 to raise a Depreciation warning, and Python 
3.4 to treat it as an error.

It may even be possible to skip the PendingDepreciation warning and go 
straight for Depreciation warning in 3.2.


-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 23:29:20 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 03:29:20 GMT
Subject: With or without leading underscore...
References: <5un5l6-fvn.ln1@satorlaser.homedns.org>
Message-ID: 

On Mon, 10 Aug 2009 16:37:25 +0200, Ulrich Eckhardt wrote:

> ...that is the question!
> 
> I have a module which exports a type. It also exports a function that
> returns instances of that type. Now, the reason for my question is that
> while users will directly use instances of the type, they will not
> create instances of the type themselves.
> 
> So, the type is a part of the public API, but its constructor is not.
> Should I mark the type as private (with a leading underscore) or not?

My opinion is that if you have to ask the question "Should this class be 
private?", then the answer is No.

Only make objects private if you have specific reasons for doing so. I 
know this goes against the advice given by other languages (namely, make 
everything private unless you need it to be public) but Python encourages 
openness and transparency.



-- 
Steven


From hjtoi-better-remove-before-reply at comcast.net  Tue Aug 11 00:25:21 2009
From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen)
Date: Mon, 10 Aug 2009 21:25:21 -0700
Subject: ANN: M2Crypto 0.20
Message-ID: 

I am please to announce the M2Crypto 0.20 release, which was in
development for over nine months. Over 30 bugs fixed by more than ten
people. Download links and bug filing instructions on the homepage at
http://chandlerproject.org/Projects/MeTooCrypto.

M2Crypto is the most complete Python wrapper for OpenSSL featuring RSA,
DSA, DH, HMACs, message digests, symmetric ciphers (including AES); SSL
functionality to implement clients and servers; HTTPS extensions to
Python's httplib, urllib, and xmlrpclib; unforgeable HMAC'ing
AuthCookies for web session management; FTP/TLS client and server;
S/MIME; ZServerSSL: A HTTPS server for Zope and ZSmime: An S/MIME
messenger for Zope. Smartcards supported with the Engine interface.

Changelog:

- Deprecated M2Crypto.PGP subpackage since nobody seems to be using it
nor is it being maintained (if you do use it, please let me know)
- Added fedora_setup.sh to help work around differences on Fedora Core
-based distributions (RedHat, CentOS, ...); thanks to Miloslav Trmac
- Added X509.load_request_bio and load_request_string, by Hartmut Goebel
and Pavel Shramov
- Added alias X509.Request.set_subject for set_subject_name to match
X509.X509, by Pavel Shramov
- OBJ_* wrappers did not work properly with OpenSSL 0.9.8a and earlier,
fix by Pavel Shramov
- Added ASN1_UTCTIME.get_datetime and set_datetime, by Pavel Shramov
- Fixed obj_obj2txt, which returned nonsense, fix by Barney Stratford
- m2urllib did not close sockets properly, fix by Miloslav Trmac
- Allow SSL peer certificate to have subjectAltName without dNSName and
use commonName for hostname check, fix by Miloslav Trmac
- threading_locking_callback did not block on a lock when the lock
  was held by another thread, by Miloslav Trmac
- Allow more blocking OpenSSL functions to run without GIL, by Miloslav
Trmac
- Fixed httpslib to send only the path+query+fragment part of the URL
when using CONNECT proxy, by James Bowes
- SSLServer.__init__ now takes optional bind_and_activate parameter and
  initializes by calling SocketServer.BaseServer.__init__, which
  are Python 2.6 compatibility fixes, by Christian
- ftpslib now works with Python 2.6, by Theodore A. Roth
- httpslib.ProxyHTTPSConnection needs to cast port into integer,
  by John M. Schanck
- Added support for RSASSA-PSS signing and verifying, by Chris Collis
- Added support for disabling padding when using RSA encryption,
  by Chris Collis
- ASN1_INTEGERs can now be larger than fits in an int, for example to
support X509 certificates with large serial numbers, patch by Mikhail
Vorozhtsov and testcase by Barry G.
- Reverted a change done in 0.17 to m2urllib2 which changed urls to
include host when it should stay as it was
- httpslib no longer uses urllib; instead it uses urlparse for url parsing
- SMIME.text_crlf and text_crlf_bio were always raising TypeError; fixed
- EVP.load_key and load_key_bio fixed to raise EVP.EVPError and
BIO.BIOError instead of str (str exceptions not allowed in Python 2.6
and later)
- SSL.Session.load_session fixed to raise SSL.SSLError instead of str
- SMIME.load_pkcs7, load_pkcs7_bio, smime_load_pkcs7,
smime_load_pkcs7_bio, text_crlf, text_crlf_bio fixed to raise
BIO.BIOError, SMIME.PKCS7_Error and SMIME.SMIME_Error as appropriate
instead of str
- Added FIPS mode to unit tests, and used FIPS-compliant key sizes in
other tests, by Miloslav Trmac. Note that tests run much slower because
of this!
- Unit tests cover 80% of the code

-- 
  Heikki Toivonen - http://heikkitoivonen.net


From robert.kern at gmail.com  Tue Aug 11 00:33:03 2009
From: robert.kern at gmail.com (Robert Kern)
Date: Tue, 11 Aug 2009 00:33:03 -0400
Subject: numpy array merge
In-Reply-To: <427654ff-5455-4198-bc86-d810ef3fafd6@t11g2000prh.googlegroups.com>
References: <427654ff-5455-4198-bc86-d810ef3fafd6@t11g2000prh.googlegroups.com>
Message-ID: 

On 2009-08-10 17:38, Nathan wrote:
> Is there an easy way to merge two numpy arrays with different rank
> sizes (terminology?).

You will want to ask numpy questions on the numpy mailing list.

   http://www.scipy.org/Mailing_Lists

I believe that "shape" is the term you are looking for.

> I want to make a single array by concatenating
> two arrays along a given direction and filling the excess cells with a
> dummy variable.  numpy concatenate works well as long as the two
> arrays have the same dimension, but I want to do this on two array
> with a matching dimension size.  An example:
>
> import numpy as np
> a = np.array([[1,2,3],[4,5,6]])
> b = np.array([[1,2],[3,4],[5,6]])
> np.concatenate((a,a),axis=1)  #This works fine, but isn't what I need.
> Out:  array([[1, 2, 3, 1, 2, 3],
>         [4, 5, 6, 4, 5, 6]])
> np.concatenate((a,b),axis=1)  #This doesn't work, but this is what I
> need.
>
> I want to fill the third row of array "a" with a dummy variable (99999
> or NaN) and concatenate with "b" to make:
> [1,2,3,1,2]
> [4,5,6,4,5]
> [99999,99999,99999,5,6]
>
> This just seems like it would be relatively common.  So I thought I'd
> check if I'm missing something before I go write the logic.  Thanks!

I don't believe there is anything that does what you want out-of-box. You will 
probably want to determine the appropriate shape for the final array, use 
empty() to create it, use .fill(nan) (or whatever) to supply the default value, 
then assign the input arrays into the appropriate locations.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From nair.jitendra at gmail.com  Tue Aug 11 01:15:31 2009
From: nair.jitendra at gmail.com (jitu)
Date: Mon, 10 Aug 2009 22:15:31 -0700 (PDT)
Subject: Problem when fetching page using urllib2.urlopen
References: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>
	
Message-ID: <1002806e-cab7-4e9b-80e4-ab46dff20cdf@b25g2000prb.googlegroups.com>


Yes Piet you were right this works. But seems does not work on google
app engine, since  it appends it own agent info as seen below

'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US;
rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13 AppEngine-Google;
(+http://code.google.com/appengine)'

Any way Thanks . Good to know about the User-Agent field.

Jitu


On Aug 11, 12:36?am, Piet van Oostrum  wrote:
> >>>>> jitu  (j) wrote:
> >j> Hi,
> >j> A html page ?contains 'anchor' elements with 'href' attribute ?having
> >j> a semicolon ?in the url , while fetching the page using
> >j> urllib2.urlopen, all such href's ?containing ?'semicolons' are
> >j> truncated.
> >j> For example the hrefhttp://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt...
> >j> get truncated tohttp://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i
> >j> The page I am talking about can be fetched from
> >j>http://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_...
>
> It's not python that causes this. It is the server that sends you the
> URLs without these parameters (that's what they are).
>
> To get them you have to tell the server that you are a respectable
> browser. E.g.
>
> import urllib2
>
> url = 'http://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt...
>
> url = 'http://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_...
>
> hdrs = {'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13',
> ? ? ? ?'Accept': 'image/*'}
>
> request = urllib2.Request(url = url, headers = hdrs)
> page = urllib2.urlopen(request).read()
>
> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: p... at vanoostrum.org



From arshakrishnamtech at gmail.com  Tue Aug 11 01:29:29 2009
From: arshakrishnamtech at gmail.com (ArshaKrishna)
Date: Mon, 10 Aug 2009 22:29:29 -0700 (PDT)
Subject: Nltk with python
Message-ID: <82c9f923-1098-4b7e-8f9d-9504c1a8962c@12g2000pri.googlegroups.com>

How can I resolve scope ambiguity using nltk toolkit with python


From cmalmqui at gmail.com  Tue Aug 11 01:54:38 2009
From: cmalmqui at gmail.com (cmalmqui)
Date: Mon, 10 Aug 2009 22:54:38 -0700 (PDT)
Subject: ElementTree - Howto access text within XML tag element...
Message-ID: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>

Hi,

I am writing on a small XML parser and are currently stuck as I am not
able to get the whole element name in ElementTree.

Please see the below example where "print root[0][0]" returns
""

Is there a way to get hold of the "Running" string in the tag using
elementTree?


    
      2009-07-10T14:48:00Z
      
      .........

For those of you that know how to program XML I have another
question:
I am currently "hardcoding" my XML parser using brackets, is this a
good approach or should I build it using a "search on tag" approach.

Thank you for any answers!


From terry.yinzhe at gmail.com  Tue Aug 11 01:59:13 2009
From: terry.yinzhe at gmail.com (Terry)
Date: Mon, 10 Aug 2009 22:59:13 -0700 (PDT)
Subject: How to pickle a lambda function?
Message-ID: <37c55108-083f-4d60-b8a3-9b2b10833ac3@r18g2000yqd.googlegroups.com>

Hi,

I'm trying to implement something like:

remote_map(fun, list)

to execute the function on a remove machine. But the problem is I
cannot pickle a lambda function and send it to the remote machine.

Is there any possible way to pickle (or other method) any functions
including lambda?

br, Terry


From steven at REMOVE.THIS.cybersource.com.au  Tue Aug 11 02:47:32 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 06:47:32 GMT
Subject: Python docs disappointing - group effort to hire	writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	<4A80472E.4090108@stoneleaf.us>
	
Message-ID: 

On Mon, 10 Aug 2009 20:05:00 -0400, David Lyon wrote:

> So, what you're advocating is let things stay how they are...

If it's not broken, don't fix it.


> Ignore feedback... tell people to freak off...

Only useless feedback.


-- 
Steven




From steven at REMOVE.THIS.cybersource.com.au  Tue Aug 11 02:51:28 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 06:51:28 GMT
Subject: variable & scoping question.
References: 
	<7earmtF2f4tvnU1@mid.uni-berlin.de>
	<93c50fc3-2cf9-4fc6-9919-cde7cfd273e6@o35g2000vbi.googlegroups.com>
Message-ID: 

On Mon, 10 Aug 2009 08:46:17 -0700, Cornelius Keller wrote:

> On 10 Aug., 17:12, "Diez B. Roggisch"  wrote:
>> Cornelius Keller wrote:
> [snip]
>>
>> http://effbot.org/zone/default-values.htm
>>
>> Diez
> 
> Ok thank you.
> I' understand now why.
> I still think this is very confusing, because default values don't
> behave like most people would expect without reading the docs.


Really? How do you expect the default value to behave in this example?

>>> import time
>>> def test(x=time.time()):
...     print x
...
>>>
>>> test()
1249972984.33
>>> time.sleep(30)
>>> test()
1249972984.33

You get the same default object each time you call the function, NOT a 
fresh one created. I'm sure I'd be terribly confused if Python re-
evaluated the default value each time I called the function.

There's no difference between this and the case x=[], except that lists 
are mutable and floats aren't. You get the same default list each time, 
it just has different stuff in it. The alternative would be to get a 
different list each time, and that would require re-evaluating the 
default each time the function was called, which is horrible.




-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Tue Aug 11 03:07:13 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 07:07:13 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
Message-ID: 

On Mon, 10 Aug 2009 15:17:24 -0700, Douglas Alan wrote:

> From: Steven D'Aprano  wrote:
> 
>> On Mon, 10 Aug 2009 00:32:30 -0700, Douglas Alan wrote:
> 
>> > In C++, if I know that the code I'm looking at compiles, then I never
>> > need worry that I've misinterpreted what a string literal means.
> 
>> If you don't know what your string literals are, you don't know what
>> your program does. You can't expect the compiler to save you from
>> semantic errors. Adding escape codes into the string literal doesn't
>> change this basic truth.
> 
> I grow weary of these semantic debates. The bottom line is that C++'s
> strategy here catches bugs early on that Python's approach doesn't. It
> does so at no additional cost.
>
> From a purely practical point of view, why would any language not want
> to adopt a zero-cost approach to catching bugs, even if they are
> relatively rare, as early as possible?

Because the cost isn't zero. Needing to write \\ in a string literal when 
you want \ is a cost, and having to read \\ in source code and mentally 
translate that to \ is also a cost. By all means argue that it's a cost 
that is worth paying, but please stop pretending that it's not a cost.

Having to remember that \n is a "special" escape and \y isn't is also a 
cost, but that's a cost you pay in C++ too, if you want your code to 
compile.


By the way, you've stated repeatedly that \y will compile with a warning 
in g++. So what precisely do you get if you ignore the warning? What do 
other C++ compilers do? Apart from the lack of warning, what actually is 
the difference between Python's behaviour and C++'s behaviour?



> (Other than the reason that adopting it *now* is sadly too late.)
> 
> Furthermore, Python's strategy here is SPECIFICALLY DESIGNED, according
> to the reference manual to catch bugs. I.e., from the original posting
> on this issue:
> 
>      Unlike Standard C, all unrecognized escape sequences are left in
>      the string unchanged, i.e., the backslash is left in the string.
>      (This behavior is useful when debugging: if an escape sequence is
>      mistyped, the resulting output is more easily recognized as
>      broken.)

You need to work on your reading comprehension. It doesn't say anything 
about the motivation for this behaviour, let alone that it was 
"SPECIFICALLY DESIGNED" to catch bugs. It says it is useful for 
debugging. My shoe is useful for squashing poisonous spiders, but it 
wasn't designed as a poisonous-spider squashing device.



>> The compiler can't save you from typing 1234 instead of 11234, or 31.45
>> instead of 3.145, or "My darling Ho" instead of "My darling Jo", so why
>> do you expect it to save you from typing "abc\d" instead of "abc\\d"?
> 
> Because in the former cases it can't catch the the bug, and in the
> latter case, it can.

I'm not convinced this is a bug that needs catching, but if you think it 
is, then that's a reasonable argument.



>> Perhaps it can catch *some* errors of that type, but only at the cost
>> of extra effort required to defeat the compiler (forcing the programmer
>> to type \\d to prevent the compiler complaining about \d). I don't
>> think the benefit is worth the cost. You and your friend do. Who is to
>> say you're right?
> 
> Well, Bjarne Stroustrup, for one.

Then let him design his own language *wink*


> All of these are value judgments, of course, but I truly doubt that
> anyone would have been bothered if Python from day one had behaved the
> way that C++ does. 

If I'm reading this page correctly, Python does behave as C++ does. Or at 
least as Larch/C++ does:

http://www.cs.ucf.edu/~leavens/larchc++manual/lcpp_47.html




>> In C++, if you see an escape you don't recognize, do you care?
> 
> Yes, of course I do. If I need to know what the program does.

Precisely the same as in Python.


>> Do you go running for the manual? If the answer is No, then why do it
>> in Python?
> 
> The answer is that I do in both cases.

You deleted without answer my next question:

"And if the answer is Yes, then how is Python worse than C++?"

Seems to me that the answer is "It's not worse than C++, it's the same" 
-- in both cases, you have to memorize the "special" escape sequences, 
and in both cases, if you see an escape you don't recognize, you need to 
look it up.



>> No. \z *is* a legal escape sequence, it just happens to map to \z.
> 
>> If you stop thinking of \z as an illegal escape sequence that Python
>> refuses to raise an error for, the problem goes away. It's a legal
>> escape sequence that maps to backslash + z.
> 
> (1) I already used that argument on my friend, and he wasn't buying it.
> (Personally, I find the argument technically valid, but commonsensically
> invalid. It's a language-lawyer kind of argument, rather than one that
> appeals to any notion of real aesthetics.)

I disagree with your sense of aesthetics. I think that having to write 
\\y when I want \y just to satisfy a bondage-and-discipline compiler is 
ugly. That's not to deny that B&D isn't useful on occasion, but in this 
case I believe the benefit is negligible, and so even a tiny cost is not 
worth the pain.

The sweet sweet pain... oh wait, sorry, wrong newsgroup...



> (2) That argument disagrees with the Python reference manual, which
> explicitly states that "unrecognized escape sequences are left in the
> string unchanged", and that the purpose for doing so is because it "is
> useful when debugging".

How does it disagree? \y in the source code mapping to \y in the string 
object is the sequence being left unchanged. And the usefulness of doing 
so is hardly a disagreement over the fact that it does so.



>> > "\x" is not a legal escape sequence. Shouldn't it also get left as
>> > "\\x"?
>>
>> No, because it actually is an illegal escape sequence.
> 
> What makes it "illegal". As far as I can tell, it's just another
> "unrecognized escape sequence". 

No, it's recognized, because \x is the prefix for an hexadecimal escape 
code. And it's illegal, because it's missing the actual hexadecimal 
digits.


> JavaScript treats it that way. Are you
> going to be the one to tell all the JavaScript programmers that their
> language can't tell a legal escape sequence from an illegal one?

Well, it is Javascript... 

All joking aside, syntax varies from one language to another. What counts 
as a legal escape sequence in Javascript and what counts as a legal 
escape sequence in Python are different. What makes you think I'm talking 
about Javascript?


>> > Well, I think he's more annoyed that if Python is going to be so
>> > helpful as to put in the missing "\" for you in "foo\zbar", then it
>> > should put in the missing "\" for you in "\". He considers this to be
>> > an inconsistency.
>>
>> (1) There is no missing \ in "foo\zbar".
>>
>> (2) The problem with "\" isn't a missing backslash, but a missing end-
>> quote.
> 
> Says who? All of this really depends on your point of view. The whole
> morass goes away completely if one adopts C++'s approach here.

But the morass only exists in the first place because you have adopted 
C++'s approach instead of Python's approach -- and (possibly) not even a 
standard part of the C++ approach, but a non-standard warning provided by 
one compiler out of many.


Even if you disagree about (1), it's easy enough to prove that (2) is 
correct:

>>> "\"
  File "", line 1
    "\"
      ^
SyntaxError: EOL while scanning single-quoted string


This is the exact same error you get here:


>>> "a
  File "", line 1
    "a
     ^
SyntaxError: EOL while scanning single-quoted string



>> Python isn't DWIMing here. The rules are simple and straightforward,
>> there's no mind-reading or guessing required.
> 
> It may not be a complex form of DWIMing, but it's still DWIMing a bit.
> Python is figuring that if I typed "\z", then either I must have really
> meant to type "\\z", 

Nope, not in the least. Python NEVER EVER EVER tries to guess what you 
mean.

If you type "xyz", it assumes you want "xyz".

If you type "xyz\n", it assumes you want "xyz\n".

If you type "xyz\\n", it assumes you want "xyz\\n".

If you type "xyz\y", it assumes you want "xyz\y".

If you type "xyz\\y", it assumes you want "xyz\\y".

This is *exactly* like C++, except that in Python the semantics of \y and 
\\y are identical. Python doesn't guess what you mean, it *imposes* a 
meaning on the escape sequence. You just don't like that meaning.



> or that I want to see the backslash when I'm
> debugging because I made a mistake, or that I'm just too lazy to type
> "\\z".

Oh jeez, if you're going to define DWIM so broadly, then *everything* is 
DWIM. "If I type '1+2', then the C++ compiler figures out that I must 
have wanted to add 1 and 2..."


> I don't know if my friend even knows the term DWIM, other than me
> paraphrasing him, but I certainly understand all about the term. It
> comes from InterLisp. When DWIM was enabled, your program would run
> until it hit an error, and for certain kinds of errors, it would wait a
> few seconds for the user to notice the error message, and if the user
> didn't tell the program to stop, it would try to figure out what the
> user most likely meant, and then continue running using the
> computer-generated "fix".

Right. And Python isn't doing anything even remotely similar to that.



> I.e., more or less like continuing on in the face of what the Python
> Reference manual refers to as an "unrecognized escape sequence".

The wording could be better, I accept. It would be better to talk about 
"special escapes" (e.g. \n) and "any non-special escape" (e.g. \y).




-- 
Steven


From nad at acm.org  Tue Aug 11 03:13:07 2009
From: nad at acm.org (Ned Deily)
Date: Tue, 11 Aug 2009 00:13:07 -0700
Subject: ElementTree - Howto access text within XML tag element...
References: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
Message-ID: 

In article 
<1ad8dac1-8fff-493a-a197-d847e7b6a761 at c2g2000yqi.googlegroups.com>,
 cmalmqui  wrote:
> I am writing on a small XML parser and are currently stuck as I am not
> able to get the whole element name in ElementTree.
> 
> Please see the below example where "print root[0][0]" returns
> ""
> 
> Is there a way to get hold of the "Running" string in the tag using
> elementTree?
> 
> 
>     
>       2009-07-10T14:48:00Z
>       
>       .........

"Running" is the value of the "Sport" attribute of the "Activity" 
element.  The documentation for the Element interface lists several ways 
to access element attributes; in your example,

>>> elem = root[0][0]
>>> elem.get("Sport")
'Running'
>>> elem.attrib
{'Sport': 'Running'}
>>> elem.items()
[('Sport', 'Running')]

See http://docs.python.org/library/xml.etree.elementtree.html

-- 
 Ned Deily,
 nad at acm.org



From duncan.booth at invalid.invalid  Tue Aug 11 03:42:06 2009
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 11 Aug 2009 07:42:06 GMT
Subject: How to pickle a lambda function?
References: <37c55108-083f-4d60-b8a3-9b2b10833ac3@r18g2000yqd.googlegroups.com>
Message-ID: 

Terry  wrote:

> I'm trying to implement something like:
> 
> remote_map(fun, list)
> 
> to execute the function on a remove machine. But the problem is I
> cannot pickle a lambda function and send it to the remote machine.
> 
> Is there any possible way to pickle (or other method) any functions
> including lambda?
> 

You can pickle any named functions that are declared at module scope.

You cannot pickle anonymous functions, methods, or functions declared 
nested inside other functions. The function must be present in the same 
module when you unpickle it, and if the definition has changed between 
pickling and unpickling the new definition will be used (just as other 
instances will use the current class definition not the one they were 
pickled with).

You probably could pickle some of the components needed to create your 
lambda and construct a new function from it when unpickling: try the code 
object, the name of the module to be used for the globals, and default 
arguments. I don't think you can pickle the closure so better make sure 
your lambda doesn't need one, and be very careful to ensure that you 
restore the pickle in the same version of Python otherwise the code object 
might break. Best just avoid this and use named functions for anything that 
needs pickling.

-- 
Duncan Booth http://kupuguy.blogspot.com


From solipsis at pitrou.net  Tue Aug 11 03:47:39 2009
From: solipsis at pitrou.net (Antoine Pitrou)
Date: Tue, 11 Aug 2009 07:47:39 +0000 (UTC)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
Message-ID: 

r  gmail.com> writes:
> 
> On Aug 9, 11:02?pm, David Lyon  wrote:
> > Since you're talking about documentation, which is a part of python,
> > don't you think you should be discussing it on python-dev ?
> 
> Yea, them's be a friendly bunch to noob ideas ;). Hey i got a better
> idea, lets go to the IRS and see if we can persuade them to stop
> taxing us...

You know, the most interesting thing in this thread is certainly its title :
? Social problems of Python doc ?

Yes, the little social problem here should be clear: if you have complaints to
voice or improvements to suggest to the Python docs, you should do so on the
issue tracker (*). For most topics, this is the only reasonable way to signal
problems to the Python developers community, and so it is in most free software
/ open source projects.

Just because you are able to write tongue-in-cheek (**) comments on python-list
or, even worse, on a third party website, and generate a long thread about how
Python doc (supposedly) s*cks
1) doesn't mean there is a legitimate issue (we all know how people can quickly
inflame about empty subjects)
2) even though there can be a legitimate issue, doesn't mean Python developers
will go out of their way and parse the entirety of the messages to find
potentially useful data in them. The bug tracker is the place for this, and it's
your task, if you want to help, to submit suggestions in it.

FYI, the Python doc is very actively maintained nowadays, and bug reports /are/
taken into account. If you think you've got a lot of time for ranting about how
the doc sucks, but don't want to spend the couple of minutes needed to post
issues on the bug tracker, it speaks a lot about your motivation. Admittedly, in
every successful community, there are attention seekers who are not interested
in actual participation.

(*) http://bugs.python.org

(**) yes, humour is fine, but it doesn't replace actual, informational content


Antoine.




From deets at nospam.web.de  Tue Aug 11 03:51:02 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Tue, 11 Aug 2009 09:51:02 +0200
Subject: ElementTree - Howto access text within XML tag element...
In-Reply-To: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
References: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
Message-ID: <7ecm77F2fbf71U1@mid.uni-berlin.de>

cmalmqui schrieb:
> Hi,
> 
> I am writing on a small XML parser and are currently stuck as I am not
> able to get the whole element name in ElementTree.
> 
> Please see the below example where "print root[0][0]" returns
> ""
> 
> Is there a way to get hold of the "Running" string in the tag using
> elementTree?
> 
> 
>     
>       2009-07-10T14:48:00Z
>       
>       .........
> 
> For those of you that know how to program XML I have another
> question:
> I am currently "hardcoding" my XML parser using brackets, is this a
> good approach or should I build it using a "search on tag" approach.

What do you mean by that - hardcoding by brackets?

Diez


From breamoreboy at yahoo.co.uk  Tue Aug 11 03:56:39 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 08:56:39 +0100
Subject: Social problems of Python doc [was Re: Python docs disappointing]
In-Reply-To: 
References: 	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>		<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
Message-ID: 

Antoine Pitrou wrote:
> r  gmail.com> writes:
>> On Aug 9, 11:02 pm, David Lyon  wrote:
>>> Since you're talking about documentation, which is a part of python,
>>> don't you think you should be discussing it on python-dev ?
>> Yea, them's be a friendly bunch to noob ideas ;). Hey i got a better
>> idea, lets go to the IRS and see if we can persuade them to stop
>> taxing us...
> 
> You know, the most interesting thing in this thread is certainly its title :
> ? Social problems of Python doc ?
> 
> Yes, the little social problem here should be clear: if you have complaints to
> voice or improvements to suggest to the Python docs, you should do so on the
> issue tracker (*). For most topics, this is the only reasonable way to signal
> problems to the Python developers community, and so it is in most free software
> / open source projects.
> 
> Just because you are able to write tongue-in-cheek (**) comments on python-list
> or, even worse, on a third party website, and generate a long thread about how
> Python doc (supposedly) s*cks
> 1) doesn't mean there is a legitimate issue (we all know how people can quickly
> inflame about empty subjects)
> 2) even though there can be a legitimate issue, doesn't mean Python developers
> will go out of their way and parse the entirety of the messages to find
> potentially useful data in them. The bug tracker is the place for this, and it's
> your task, if you want to help, to submit suggestions in it.
> 
> FYI, the Python doc is very actively maintained nowadays, and bug reports /are/
> taken into account. If you think you've got a lot of time for ranting about how
> the doc sucks, but don't want to spend the couple of minutes needed to post
> issues on the bug tracker, it speaks a lot about your motivation. Admittedly, in
> every successful community, there are attention seekers who are not interested
> in actual participation.
> 
> (*) http://bugs.python.org
> 
> (**) yes, humour is fine, but it doesn't replace actual, informational content
> 
> 
> Antoine.
> 
> 
Thank you for this fine, cultured, reasonable response.  Seriously!!!

-- 
Kindest regards.

Mark Lawrence.



From terry.yinzhe at gmail.com  Tue Aug 11 04:16:14 2009
From: terry.yinzhe at gmail.com (Terry)
Date: Tue, 11 Aug 2009 01:16:14 -0700 (PDT)
Subject: How to pickle a lambda function?
References: <37c55108-083f-4d60-b8a3-9b2b10833ac3@r18g2000yqd.googlegroups.com>
	
Message-ID: 

On Aug 11, 3:42?pm, Duncan Booth  wrote:
> Terry  wrote:
> > I'm trying to implement something like:
>
> > remote_map(fun, list)
>
> > to execute the function on a remove machine. But the problem is I
> > cannot pickle a lambda function and send it to the remote machine.
>
> > Is there any possible way to pickle (or other method) any functions
> > including lambda?
>
> You can pickle any named functions that are declared at module scope.
>
> You cannot pickle anonymous functions, methods, or functions declared
> nested inside other functions. The function must be present in the same
> module when you unpickle it, and if the definition has changed between
> pickling and unpickling the new definition will be used (just as other
> instances will use the current class definition not the one they were
> pickled with).
>
> You probably could pickle some of the components needed to create your
> lambda and construct a new function from it when unpickling: try the code
> object, the name of the module to be used for the globals, and default
> arguments. I don't think you can pickle the closure so better make sure
> your lambda doesn't need one, and be very careful to ensure that you
> restore the pickle in the same version of Python otherwise the code object
> might break. Best just avoid this and use named functions for anything that
> needs pickling.
>
> --
> Duncan Boothhttp://kupuguy.blogspot.com

Yes, I'm think of pickle (actually marshal) the code object. Otherwise
I have to use string and eval:-(

The reason I need to be able to pickle any function is because I want
my remote machine knows nothing about the function before receiving
it, so I don't need to update the source code in the remote machine
very often.

br, terry


From sjmachin at lexicon.net  Tue Aug 11 04:17:00 2009
From: sjmachin at lexicon.net (John Machin)
Date: Tue, 11 Aug 2009 01:17:00 -0700 (PDT)
Subject: Problem Regarding Handling of Unicode string
References: <9ac0e194-9e25-468a-9807-957ef3142dd3@i18g2000pro.googlegroups.com>
Message-ID: <47b265c5-e71f-4018-815a-0bfbea927a4a@y28g2000prd.googlegroups.com>

On Aug 10, 9:26?pm, joy99  wrote:
> Dear Group,
>
> I am using Python26 on WindowsXP with service pack2. My GUI is IDLE.
> I am using Hindi resources and get nice output like:
> ??
> where I can use all the re functions and other functions without doing
> any transliteration,etc.
> I was trying to use Bengali but it is giving me output like:

WHAT is giving you this output?

> '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95'

In a very ordinary IDLE session (Win XP SP3, Python 2.6.2, locale:
Australia/English, no "Hindi resources"):

>>> x = '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95'
>>> ux = x.decode('utf-8')
>>> ux
u'\ufeff\u0985\u09a8\u09c7\u0995'
>>> print ux
????? # looks like what you wanted; please confirm
>>> import unicodedata
>>> for c in ux:
	print unicodedata.name(c)


ZERO WIDTH NO-BREAK SPACE # this is a BOM
BENGALI LETTER A
BENGALI LETTER NA
BENGALI VOWEL SIGN E
BENGALI LETTER KA
>>>

> I wanted to see Bengali output as
> ????
> and I like to use all functions including re.
> If any one can help me on that.

"I am using Hindi resources" doesn't tell us much ... except to prompt
the comment that perhaps if you want to display Bengali script, you
may need Bengali resources. However it looks like I can display your
Bengali data without any special resources.

It seems like you are not doing the same with Bengali as you are doing
with Hindi. We can't help you very much if you don't show exactly what
you are doing.

Have you considered asking in an Indian Python forum? Note: you will
still need to say what you are doing that works with Hindi but not
with Bengali.

Cheers,
John


From bruno.42.desthuilliers at websiteburo.invalid  Tue Aug 11 04:41:25 2009
From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers)
Date: Tue, 11 Aug 2009 10:41:25 +0200
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com>
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	
	<081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com>
Message-ID: <4a812e8d$0$27778$426a74cc@news.free.fr>

r a ?crit :
(snip)
> 
> A little note for tutorial writers:
> ==================================
> 
> Dear Expert,
> Whilst writing any tutorial on any subject matter please remember, you
> may be an expert, but mostly *non-experts* will be reading your
> material... 

I can only second Paul on this : just like the K&R, Python's official 
tutorial targets experienced programmers, not total noobies.



From bruno.42.desthuilliers at websiteburo.invalid  Tue Aug 11 04:46:19 2009
From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers)
Date: Tue, 11 Aug 2009 10:46:19 +0200
Subject: With or without leading underscore...
In-Reply-To: <4d6719e4-217a-4921-bd26-228fd4944eb7@r24g2000vbn.googlegroups.com>
References: <5un5l6-fvn.ln1@satorlaser.homedns.org>
	<4d6719e4-217a-4921-bd26-228fd4944eb7@r24g2000vbn.googlegroups.com>
Message-ID: <4a812fb2$0$27778$426a74cc@news.free.fr>

Carl Banks a ?crit :
(snip)


> class A(object):
>     def __init__(self,*args,**kwargs):
>         raise TypeError('Type not callable; use factory function
> instead')
> 
>     @classmethod
>     def _create_object(cls,initial_value):
>         self = object.__new__(cls) # avoid __init__
>         self.value = initial_value

I assume there's a missing "return self" line here ?-)


From Brian.Mingus at colorado.edu  Tue Aug 11 04:49:01 2009
From: Brian.Mingus at colorado.edu (Brian)
Date: Tue, 11 Aug 2009 02:49:01 -0600
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
Message-ID: <9839a05c0908110149paa2eddbue3880037e0fded3f@mail.gmail.com>

On Fri, Jul 31, 2009 at 6:12 PM, Kee Nethery  wrote:

> I too find the Python docs not very useful and it really slows down my
> learning curve.
>
> I wonder if it would make sense to find good tech writers, get a quotes,
> and get some professionally written documentation WITH LOTS OF EXAMPLES
> added to the standard Python documentation tree.
>
> I'd chip in money for that task. I've certainly spent enough buying Python
> books to where it would be very reasonable to chip in the cost of one book
> towards this project. Get enough people ... could be a great thing.
>
> Even though it is not the version I use, I would suggest that the really
> detailed docs with lots of examples be written against the latest python
> version.
>
> Just a thought.
>
> Kee Nethery
> --
> http://mail.python.org/mailman/listinfo/python-list
>

One thing I really like about the PHP docs is the built in forums. User
feedback on documentation is invaluable.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From zhongshq at gmail.com  Tue Aug 11 04:49:40 2009
From: zhongshq at gmail.com (zhongshq)
Date: Tue, 11 Aug 2009 01:49:40 -0700 (PDT)
Subject: Is there any package implanation the following arithmetics?
Message-ID: 

Hi,

I wonder if there has any package can check whether two rectangles are
overlap, is a dot inside or outside a polygon, etc.

Thanks a lot!


From vinay_sajip at yahoo.co.uk  Tue Aug 11 06:23:00 2009
From: vinay_sajip at yahoo.co.uk (Vinay Sajip)
Date: Tue, 11 Aug 2009 03:23:00 -0700 (PDT)
Subject: Need help in configuration for TimedRotatingFileHandler
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
	<4A7F3C83.1040607@ieee.org>
	 
	 
	
Message-ID: 

On Aug 10, 3:52?pm, Dave Angel  wrote:
> Lokesh Maremalla wrote:
> > Traceback (most recent call last):
> > ? File "c:\Python25\lib\logging\handlers.py", line 74, in emit
> > ? ? self.doRollover()
> > ? File "c:\Python25\lib\logging\handlers.py", line 274, in doRollover
> > ? ? os.rename(self.baseFilename, dfn)
> > WindowsError: [Error 32] The process cannot access the file because it is
> > being used by another process
>
> Generally speaking, this error on os.rename() will occur if you haven't
> properly closed the file first, and if I recall correctly, Unix would
> have permitted a rename on an open file. ?You're on Windows. ?However, I
> don't know how that works with theloggingpackage. ?If the program has
> terminated, and you run it a second time on the following day (or after
> changing the system time), then I'd expect no trouble. ?But I'm guessing
> your program is still running, and you just want to change fromlogging
> to yesterday's file tologgingto today's file.
>
> If I had to guess, I'd say that you have two instances of the logger
> running, and the second one is still holding the handle open. ?But
> that's just a wild guess.
>

It's certainly possible that there are two instances of the handler,
which would cause this problem. Other things which might cause this
problem are the file handle inherited by a child process, an anti-
virus scanner having the file open for scanning (anti-virus scanners
often scan files which have just been written, like log files) and
indexing software such as Google Desktop or Windows' own indexing
service.

I would advise using sysinternals tools such as FileMon and Handle to
see what's holding the file open.

Regards,


Vinay Sajip


From scholz.lothar at gmail.com  Tue Aug 11 06:45:10 2009
From: scholz.lothar at gmail.com (llothar)
Date: Tue, 11 Aug 2009 03:45:10 -0700 (PDT)
Subject: UML for Python or some other Graphical Notation Language
Message-ID: <2eabd7a9-2517-41b3-a3be-183171c04372@2g2000prl.googlegroups.com>

This is more an academic question right now but was there ever some
work in progress how UML could be made better for Python or script
languages in general.

It is so extremely deep interwoven with Java/C++ language
implementations that there are a lot of modified notiations necessary.

Or is there anything else then UML?
Eiffel still has BON for example.


From helvinlui at gmail.com  Tue Aug 11 07:22:13 2009
From: helvinlui at gmail.com (Helvin)
Date: Tue, 11 Aug 2009 04:22:13 -0700 (PDT)
Subject: Search and write to .txt file
Message-ID: 

Hi everyone,

I am writing some python script that should find a line which contains
'1' in the data.txt file, then be able to move a certain number of
lines down, before replacing a line. At the moment, I am able to find
the line '1', but when I use f.seek to move, and then rewrite, what I
write goes to the end of the .txt file, instead of being adjusted by
my f.seek.

Do you know what way I should take?

Data.txt is a file of 3 lines:
   line1
   line2
   line3

Code:

   with open('data.txt', 'r+') as f:
       firstread = f.readlines()   # Take a snapshot of initial file

       f.seek(0,0)    # Go back to beginning and search
       for line in f:
           print line
           if line.find('1'):
               print 'line matched'
               f.seek(1,1)       # Move one space along
               f.write('house\n')     # f.write overwrites the exact
number of bytes.
               break                    # leave loop once '1' is found

       f.seek(0,0)              # Go back to beginning, and read
data.txt again
       lastread = f.readlines()

       print 'firstread is', firstread
       print 'lastread is', lastread

This shouldn't be too difficult, but I don't know how. > <
Help appreciated!


From lujan at ceam.es  Tue Aug 11 07:26:42 2009
From: lujan at ceam.es (=?ISO-8859-1?Q?Alonso_Luj=E1n_Torres_Ta=F1o?=)
Date: Tue, 11 Aug 2009 13:26:42 +0200
Subject: add fields in a existing dbf
Message-ID: <4A815572.1020905@ceam.es>

Hi!

I'm trying to modify a dbf adding a new field in a python script, but I 
can't.

Just I can add a field in new dbf created in the same script.

I tryed with:

    db = dbf.Dbf("../filesource.dbf",new =False, readOnly=False)
    ...
    db.addField(("PESO","N",32,8))

and return error:

    Traceback (most recent call last):
      File "script.py", line 34, in 
        db.addField(("PESO","N",32,8))
      File "/usr/lib/python2.5/site-packages/dbfpy/dbf.py", line 229, in
    addField
        "structure can't be changed")
    TypeError: ('At least one record was added, ', "structure can't be
    changed")


I have not idea of what error I make.

If someone can help me, I'll so gratefull.

Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From kushal.kumaran+python at gmail.com  Tue Aug 11 07:34:35 2009
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Tue, 11 Aug 2009 17:04:35 +0530
Subject: Search and write to .txt file
In-Reply-To: 
References: 
Message-ID: <1e364c4e0908110434m52701b64vebca82dbbec8d300@mail.gmail.com>

On Tue, Aug 11, 2009 at 4:52 PM, Helvin wrote:
> Hi everyone,
>
> I am writing some python script that should find a line which contains
> '1' in the data.txt file, then be able to move a certain number of
> lines down, before replacing a line. At the moment, I am able to find
> the line '1', but when I use f.seek to move, and then rewrite, what I
> write goes to the end of the .txt file, instead of being adjusted by
> my f.seek.
>
> Do you know what way I should take?
>

It might be easier to read the file into a list of lines (using
readlines, as you do in your code already), make your change there and
write it back to a file.  If your file is indeed as small as you
indicate below, that should be significantly easier.

> Data.txt is a file of 3 lines:
> ? line1
> ? line2
> ? line3
>
> Code:
>
> ? with open('data.txt', 'r+') as f:
> ? ? ? firstread = f.readlines() ? # Take a snapshot of initial file
>
> ? ? ? f.seek(0,0) ? ?# Go back to beginning and search
> ? ? ? for line in f:
> ? ? ? ? ? print line
> ? ? ? ? ? if line.find('1'):
> ? ? ? ? ? ? ? print 'line matched'
> ? ? ? ? ? ? ? f.seek(1,1) ? ? ? # Move one space along
> ? ? ? ? ? ? ? f.write('house\n') ? ? # f.write overwrites the exact
> number of bytes.
> ? ? ? ? ? ? ? break ? ? ? ? ? ? ? ? ? ?# leave loop once '1' is found
>
> ? ? ? f.seek(0,0) ? ? ? ? ? ? ?# Go back to beginning, and read
> data.txt again
> ? ? ? lastread = f.readlines()
>
> ? ? ? print 'firstread is', firstread
> ? ? ? print 'lastread is', lastread
>
> This shouldn't be too difficult, but I don't know how. > <
> Help appreciated!


From davea at ieee.org  Tue Aug 11 07:37:25 2009
From: davea at ieee.org (Dave Angel)
Date: Tue, 11 Aug 2009 07:37:25 -0400
Subject: dictionary help
In-Reply-To: <4A809AF80200008C000149EC@redhorse.forestry.uga.edu>
References: <4A809AF80200008C000149EC@redhorse.forestry.uga.edu>
Message-ID: <4A8157F5.1010103@ieee.org>

Krishna Pacifici wrote:
> Hi,
> kind of a newbie here, but I have two questions that are probably pretty simple.
>
> 1.  I need to get rid of duplicate values that are associated with different keys in a dictionary.  For example I have the following code.
> s={}
> s[0]=[10,2,3]
>  s[10]=[22,23,24]
>  s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
>
> Now I want to be able to loop through the primary keys and get rid of duplicates (both in keys and values) so that I would have either a new dictionary or the same dictionary but with the following values:
>
> s[0]=[3]
>  s[10]=[22,23,24]
>  s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
>
> It doesn't matter which value gets removed as long as there is only one remaining, so in this example it doesn't matter that 2 got removed from s[0] or from s[30] as long as there is only one 2 in the dictionary.
>
> 2.  I need to be able to loop over the values in the dictionary when there are multiple values assigned to each key like above and assign new values to those values.  Taking the above example I would want to assign a new value so that when you called s[0] it would equal [3,4] say if 4 was the new value.  I think this should be as simple as adding a value, but I kept on having difficulty.
>
> Any suggestions would be greatly appreciated.
>
> Thank you very much,
> Krishna
>
>
>   
Sounds like homework.  If it was for an unconstrained project, I'd 
design a different data structure, one that directly enforced the data 
constraints.  So far, I can't imagine a useful reason for this 
particular set of constraints.

Let's break the problems down.

1a)   Do you know how to write a loop that visits all the keys of a 
dictionary?
1b)  Do you know how to safely check if a particular key exists?     
e.g.      if   key in s:
1c)  Do you know how to collect a set of values, so that when a 
duplicate is found, it can be recognized as such?
1d) Do you know how to remove an item from a list?

2a)  Like 1a)
2b) Do you know how to append a value to the end of a list?  Is s[key] a 
list?


DaveA



From deets at nospam.web.de  Tue Aug 11 07:49:04 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Tue, 11 Aug 2009 13:49:04 +0200
Subject: UML for Python or some other Graphical Notation Language
References: <2eabd7a9-2517-41b3-a3be-183171c04372@2g2000prl.googlegroups.com>
Message-ID: <7ed45gF2evk04U1@mid.uni-berlin.de>

llothar wrote:

> This is more an academic question right now but was there ever some
> work in progress how UML could be made better for Python or script
> languages in general.
> 
> It is so extremely deep interwoven with Java/C++ language
> implementations that there are a lot of modified notiations necessary.
> 
> Or is there anything else then UML?
> Eiffel still has BON for example.

http://fptiny.blogspot.com/2008/03/rad-with-tiny-erp.html

Diez


From skip at pobox.com  Tue Aug 11 08:40:31 2009
From: skip at pobox.com (skip at pobox.com)
Date: Tue, 11 Aug 2009 07:40:31 -0500 (CDT)
Subject: test message
Message-ID: <20090811124031.4B11911ACFB4@montanaro.dyndns.org>

Sorry for the low content email.  Testing the mail-to-news gateway on
mail.python.org.  Don't flame me for not using a test newsgroup. ;-)

-- 
Skip Montanaro - skip at pobox.com - http://www.smontanaro.net/
    Getting old sucks, but it beats dying young


From skip.montanaro at gmail.com  Tue Aug 11 09:00:54 2009
From: skip.montanaro at gmail.com (Skip Montanaro)
Date: Tue, 11 Aug 2009 06:00:54 -0700 (PDT)
Subject: test message
References: 
Message-ID: <7e0b6c26-b95d-48a5-a16e-bbbc7361f240@c34g2000yqi.googlegroups.com>

On Aug 11, 7:40?am, s... at pobox.com wrote:
> Sorry for the low content email. ?Testing the mail-to-news gateway on
> mail.python.org. ?Don't flame me for not using a test newsgroup. ;-)

Posting a followup to test the return path (news-to-mail).

S


From piet at cs.uu.nl  Tue Aug 11 09:30:12 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Tue, 11 Aug 2009 15:30:12 +0200
Subject: Search and write to .txt file
References: 
Message-ID: 

>>>>> Helvin  (H) wrote:

>H> Hi everyone,
>H> I am writing some python script that should find a line which contains
>H> '1' in the data.txt file, then be able to move a certain number of
>H> lines down, before replacing a line. At the moment, I am able to find
>H> the line '1', but when I use f.seek to move, and then rewrite, what I
>H> write goes to the end of the .txt file, instead of being adjusted by
>H> my f.seek.

>H> Do you know what way I should take?

>H> Data.txt is a file of 3 lines:
>H>    line1
>H>    line2
>H>    line3

>H> Code:

>H>    with open('data.txt', 'r+') as f:
>H>        firstread = f.readlines()   # Take a snapshot of initial file

>H>        f.seek(0,0)    # Go back to beginning and search
>H>        for line in f:
>H>            print line
>H>            if line.find('1'):
>H>                print 'line matched'
>H>                f.seek(1,1)       # Move one space along
>H>                f.write('house\n')     # f.write overwrites the exact
>H> number of bytes.
>H>                break                    # leave loop once '1' is found

Mixing an iterator on the file with direct calls (seek/write) isn't
going to work. The iterator does read ahead which causes the file
position not to be what you think it is.

See:

>>> with open('data.txt', 'r+') as f:
...   for line in f:
...       print line, f.tell()
... 
line1
18
line2
18
line3
18

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From bmorab at gmail.com  Tue Aug 11 09:49:58 2009
From: bmorab at gmail.com (telekab1@hotmail.com)
Date: Tue, 11 Aug 2009 06:49:58 -0700 (PDT)
Subject: Extracting matrix from a text file
Message-ID: 

Hello to all!!

I am new in python, and I am running it on Mac with Smultron editor. I
need to read a textfile that includes numbers (in a matrix form),
indexes, and strings, like this:

Marsyas-kea distance matrix for MIREX 2007 Audio Similarity Exchange
Q/R        1                   2                   3
4                5
1        0                  4.54592        4.36685
5.29463        3.85728
2        4.54592        0                  3.97667
5.02151        4.64284
3        4.36685        3.97667        0
4.98743        4.83683
4        5.29463        5.02151        4.98743
0                  6.04393
5        3.85728        4.64284        4.83683        6.04393        0

My code to get this information is:

matrix = open("dmatrix_5.txt");

while 1:
    mat = matrix.readline()
    if not mat:
    	break
    pass # do something
    print mat



So I just want to keep the matrix in the "middle" for math
computations.

        0                  4.54592        4.36685
5.29463        3.85728
        4.54592        0                  3.97667
5.02151        4.64284
        4.36685        3.97667        0
4.98743        4.83683
        5.29463        5.02151        4.98743
0                  6.04393
        3.85728        4.64284        4.83683        6.04393        0


I've seen and tried a lot of ways, like split or isinstance.. but
never get the wanted result.... does anyone have an idea, or hint?
Thank you once more for your help!

Best Regards,
Bea


From piet at cs.uu.nl  Tue Aug 11 09:50:01 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Tue, 11 Aug 2009 15:50:01 +0200
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
Message-ID: 

>>>>> Steven D'Aprano  (SD) wrote:

>SD> If I'm reading this page correctly, Python does behave as C++ does. Or at 
>SD> least as Larch/C++ does:

>SD> http://www.cs.ucf.edu/~leavens/larchc++manual/lcpp_47.html

They call them `non-standard escape sequences' for a reason: that they
are not in standard C++.

test.cpp:
char* temp = "abc\yz";

TEMP> g++ -c test.cpp
test.cpp:1:1: warning: unknown escape sequence '\y'

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From breamoreboy at yahoo.co.uk  Tue Aug 11 09:52:29 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 14:52:29 +0100
Subject: Search and write to .txt file
In-Reply-To: 
References: 
Message-ID: 

Helvin wrote:
> Hi everyone,
> 
> I am writing some python script that should find a line which contains
> '1' in the data.txt file, then be able to move a certain number of
> lines down, before replacing a line. At the moment, I am able to find
> the line '1', but when I use f.seek to move, and then rewrite, what I
> write goes to the end of the .txt file, instead of being adjusted by
> my f.seek.
> 
> Do you know what way I should take?
> 
> Data.txt is a file of 3 lines:
>    line1
>    line2
>    line3
> 
> Code:
> 
>    with open('data.txt', 'r+') as f:
>        firstread = f.readlines()   # Take a snapshot of initial file
> 
>        f.seek(0,0)    # Go back to beginning and search
>        for line in f:
>            print line
>            if line.find('1'):
>                print 'line matched'
>                f.seek(1,1)       # Move one space along
>                f.write('house\n')     # f.write overwrites the exact
> number of bytes.
>                break                    # leave loop once '1' is found
> 
>        f.seek(0,0)              # Go back to beginning, and read
> data.txt again
>        lastread = f.readlines()
> 
>        print 'firstread is', firstread
>        print 'lastread is', lastread
> 
> This shouldn't be too difficult, but I don't know how. > <
> Help appreciated!
You can't mix and match the file iterator "for line in f" with the seek 
method.  You already have the data in firstread, why not process it from 
there, i.e. "for line in firstread".  Also look at the docs for the find 
method, it doesn't return what you think it does.

-- 
Kindest regards.

Mark Lawrence.



From breamoreboy at yahoo.co.uk  Tue Aug 11 10:04:31 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 15:04:31 +0100
Subject: Extracting matrix from a text file
In-Reply-To: 
References: 
Message-ID: 

telekab1 at hotmail.com wrote:
> Hello to all!!
> 
> I am new in python, and I am running it on Mac with Smultron editor. I
> need to read a textfile that includes numbers (in a matrix form),
> indexes, and strings, like this:
> 
> Marsyas-kea distance matrix for MIREX 2007 Audio Similarity Exchange
> Q/R        1                   2                   3
> 4                5
> 1        0                  4.54592        4.36685
> 5.29463        3.85728
> 2        4.54592        0                  3.97667
> 5.02151        4.64284
> 3        4.36685        3.97667        0
> 4.98743        4.83683
> 4        5.29463        5.02151        4.98743
> 0                  6.04393
> 5        3.85728        4.64284        4.83683        6.04393        0
> 
> My code to get this information is:
> 
> matrix = open("dmatrix_5.txt");
> 
> while 1:
>     mat = matrix.readline()
>     if not mat:
>     	break
>     pass # do something
>     print mat
> 
> 
> 
> So I just want to keep the matrix in the "middle" for math
> computations.
> 
>         0                  4.54592        4.36685
> 5.29463        3.85728
>         4.54592        0                  3.97667
> 5.02151        4.64284
>         4.36685        3.97667        0
> 4.98743        4.83683
>         5.29463        5.02151        4.98743
> 0                  6.04393
>         3.85728        4.64284        4.83683        6.04393        0
> 
> 
> I've seen and tried a lot of ways, like split or isinstance.. but
> never get the wanted result.... does anyone have an idea, or hint?
> Thank you once more for your help!
> 
> Best Regards,
> Bea
I think your best bet is to read and action the responses you got to 
your original email from three days ago.  If these have got lost in the 
post simply search online, they're bound to be archived somewhere.

-- 
Kindest regards.

Mark Lawrence.



From ethan at stoneleaf.us  Tue Aug 11 10:12:17 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Tue, 11 Aug 2009 07:12:17 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <0985e0fe54bf41fa3736cd6697d42bf4@preisshare.net>
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>		<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>			<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	<4A80472E.4090108@stoneleaf.us>
	<0985e0fe54bf41fa3736cd6697d42bf4@preisshare.net>
Message-ID: <4A817C41.2050607@stoneleaf.us>

David Lyon wrote:
> On Mon, 10 Aug 2009 09:13:34 -0700, Ethan Furman 
> wrote:
> 
>>As someone who relies heavily on the docs I will also say that the idea 
>>of giving the ability to modify the official documentation to somebody 
>>who is /learning/ the language is, quite frankly, terrifying.  
> 
> 
> What is more terrifying is the way feedback from newbies is handled.
> 
> Your statement implies that the only way feedback can be handled is
> to throw the keys down in discust and walk away. That's primative
> behaviour. And misleading, because that isn't going to happen.
> 

Allow me to put back the sentence you unfairly snipped:
> I have no issues with a seperate system, some of which have been 
> suggested, but good reference documentation is crucial.  If you find 
> examples lacking, there are plenty of web-sites, or even (dare I say
> it?) actual hard-copy books!  ;)

To be clear, what I am advocating is that *official documentation not be 
opened up to everybody,* _especially not people who don't yet grok the 
language_.

> 
>>My bookshelf currently has Learning Python, Programming 
>>Python, Python Cookbook, Python Programming on Win32, and Regular 
>>Expressions.  All great books, and not too pricey if you can get them
> 
> used.
> 
> So, what you're advocating is let things stay how they are...
> 
> Ignore feedback... tell people to freak off...
> 
> 

I had not addressed feedback before, but I shall do so now:  Discuss 
concern on the Python list first to make sure it is not a lack of 
understanding, then, if a legitimate issue with the docs exists, use the 
bug tracker.  If one can't be bothered to take the time to be a 
Responsible Citizen, I am not going to be bothered by lacking that one's 
comments/concerns/feed-back.

~Ethan~


From davea at ieee.org  Tue Aug 11 10:22:49 2009
From: davea at ieee.org (Dave Angel)
Date: Tue, 11 Aug 2009 10:22:49 -0400
Subject: Search and write to .txt file
In-Reply-To: 
References: 
	
Message-ID: <4A817EB9.9040807@ieee.org>

Piet van Oostrum wrote:
>>>>>> Helvin  (H) wrote:
>>>>>>             
>
>   
>> H> Hi everyone,
>> H> I am writing some python script that should find a line which contains
>> H> '1' in the data.txt file, then be able to move a certain number of
>> H> lines down, before replacing a line. At the moment, I am able to find
>> H> the line '1', but when I use f.seek to move, and then rewrite, what I
>> H> write goes to the end of the .txt file, instead of being adjusted by
>> H> my f.seek.
>>     
>
>   
>> H> Do you know what way I should take?
>>     
>
>   
>> H> Data.txt is a file of 3 lines:
>> H>    line1
>> H>    line2
>> H>    line3
>>     
>
>   
>> H> Code:
>>     
>
>   
>> H>    with open('data.txt', 'r+') as f:
>> H>        firstread = f.readlines()   # Take a snapshot of initial file
>>     
>
>   
>> H>        f.seek(0,0)    # Go back to beginning and search
>> H>        for line in f:
>> H>            print line
>> H>            if line.find('1'):
>> H>                print 'line matched'
>> H>                f.seek(1,1)       # Move one space along
>> H>                f.write('house\n')     # f.write overwrites the exact
>> H> number of bytes.
>> H>                break                    # leave loop once '1' is found
>>     
>
> Mixing an iterator on the file with direct calls (seek/write) isn't
> going to work. The iterator does read ahead which causes the file
> position not to be what you think it is.
>
> See:
>
>   
>>>> with open('data.txt', 'r+') as f:
>>>>         
> ...   for line in f:
> ...       print line, f.tell()
> ... 
> line1
> 18
> line2
> 18
> line3
> 18
>
>   
In addition to the buffering involved in the read loop, trying to 
position ahead some number of lines would be rather error prone, since 
this is a text file, with varying length lines, and the \n character 
might occupy one byte on some OS, and two bytes on others (Windows).  If 
you feel you must do it in-place, then switch the file mode to binary, 
and use read(), not readline(), keeping track of your own position at 
all times.

As was already suggested by Kushal, if the file is small enough to just 
use readlines() and manipulate that list, I'd do that.  If not, I'd scan 
through the file, creating a new one, creating a new one as you go, then 
rename the new one back when finished.  Actually, I'd create a new one 
even in the first case, in case of a crash while rewriting the file.


DaveA


From ethan at stoneleaf.us  Tue Aug 11 10:35:54 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Tue, 11 Aug 2009 07:35:54 -0700
Subject: Unrecognized escape sequences in string literals
In-Reply-To: 
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>							<86e09602-7eb1-4397-a77f-fb1e3c5b34b9@k26g2000vbp.googlegroups.com>
	
Message-ID: <4A8181CA.9050200@stoneleaf.us>

Steven D'Aprano wrote:
> On Mon, 10 Aug 2009 08:21:03 -0700, Douglas Alan wrote:
> 
> 
>>But you're right, it's too late to change this now.
> 
> 
> Not really. There is a procedure for making non-backwards compatible 
> changes. If you care deeply enough about this, you could agitate for 
> Python 3.2 to raise a PendingDepreciation warning for "unexpected" escape 
> sequences like \z, Python 3.3 to raise a Depreciation warning, and Python 
> 3.4 to treat it as an error.
> 
> It may even be possible to skip the PendingDepreciation warning and go 
> straight for Depreciation warning in 3.2.
> 
> 

And once it's fully depreciated you have to stop writing it off on your 
taxes.  *wink*

~Ethan~


From Nikolaus at rath.org  Tue Aug 11 10:44:11 2009
From: Nikolaus at rath.org (Nikolaus Rath)
Date: Tue, 11 Aug 2009 10:44:11 -0400
Subject: Profiling a Callback Function
Message-ID: <1250001851.3970.15.camel@inspiron.ap.columbia.edu>

Hello,

I am trying to profile a Python program that primarily calls a C
extension. From within the C extension, a callback Python function is
then called concurrently in several threads.

When I tried to profile this application with

  import c_extension
  def callback_fn(args):
      # Do all sorts of complicated, time consuming stuff
      pass

  def main():
      c_extension.call_me_back(callback_fn, some_random_args)

  cProfile.run('main', 'profile.dat')

I only got results for main(), but no information at all about
callback_fn.


What is the proper way to profile such an application? 


I already thought about this:

  import c_extension

  def callback_fn(args):
      # Do all sorts of complicated, time consuming stuff
      pass
  
  def callback_wrapper(args):
       def doit():
           callback_fn(args)

       cProfile.run('doit', 'profile.dat')

  c_extension.call_me_back(callback_wrapper, some_random_args)


but that probably overwrites the profiling information whenever
callback_wrapper is called, instead of accumulating them over several
calls (with different arguments).


Best,


   -Nikolaus

-- 
 ?Time flies like an arrow, fruit flies like a Banana.?

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C




From cjw at ncf.ca  Tue Aug 11 10:45:28 2009
From: cjw at ncf.ca (Colin J. Williams)
Date: Tue, 11 Aug 2009 10:45:28 -0400
Subject: Extracting matrix from a text file
In-Reply-To: 
References: 
Message-ID: <4A818408.6080506@ncf.ca>

telekab1 at hotmail.com wrote:
> Hello to all!!
> 
> I am new in python, and I am running it on Mac with Smultron editor. I
> need to read a textfile that includes numbers (in a matrix form),
> indexes, and strings, like this:
> 
> Marsyas-kea distance matrix for MIREX 2007 Audio Similarity Exchange
> Q/R        1                   2                   3
> 4                5
> 1        0                  4.54592        4.36685
> 5.29463        3.85728
> 2        4.54592        0                  3.97667
> 5.02151        4.64284
> 3        4.36685        3.97667        0
> 4.98743        4.83683
> 4        5.29463        5.02151        4.98743
> 0                  6.04393
> 5        3.85728        4.64284        4.83683        6.04393        0
> 
> My code to get this information is:
> 
> matrix = open("dmatrix_5.txt");
> 
> while 1:
>     mat = matrix.readline()
>     if not mat:
>     	break
>     pass # do something
>     print mat
> 
> 
> 
> So I just want to keep the matrix in the "middle" for math
> computations.
> 
>         0                  4.54592        4.36685
> 5.29463        3.85728
>         4.54592        0                  3.97667
> 5.02151        4.64284
>         4.36685        3.97667        0
> 4.98743        4.83683
>         5.29463        5.02151        4.98743
> 0                  6.04393
>         3.85728        4.64284        4.83683        6.04393        0
> 
> 
> I've seen and tried a lot of ways, like split or isinstance.. but
> never get the wanted result.... does anyone have an idea, or hint?
> Thank you once more for your help!
> 
> Best Regards,
> Bea

numpy provides an answer.  See the little script below:

import numpy as _n
import string as _s
a=  "0       4.54592 4.36685 5.29463 3.85728 " + \
   "4.54592 0       3.97667 5.02151 4.64284 "   + \
   '4.36685 3.97667 0       4.98743 4.83683 '   + \
   '5.29463 5.02151 4.98743 0       6.04393 '   + \
   '3.85728 4.64284 4.83683 6.04393 0'

d= _n.mat(_n.reshape(_n.array(a.split(), dtype= _n.float), (5, 5)))
print repr(d)
print 'Default printoptions:', _n.get_printoptions()

for p in range(9):
   _n.set_printoptions(precision= p)
   print 'precision= ', p, '\n', d

When you run this, you'll see that there is a numpy glitch for precisions > 5.

Colin W.


From rurpy at yahoo.com  Tue Aug 11 10:57:28 2009
From: rurpy at yahoo.com (rurpy at yahoo.com)
Date: Tue, 11 Aug 2009 07:57:28 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
Message-ID: <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>

On 08/11/2009 01:47 AM, Antoine Pitrou wrote:
> r  gmail.com>  writes:
>> On Aug 9, 11:02 pm, David Lyon  wrote:
>>> Since you're talking about documentation, which is a part of python,
>>> don't you think you should be discussing it on python-dev ?
>> Yea, them's be a friendly bunch to noob ideas ;). Hey i got a better
>> idea, lets go to the IRS and see if we can persuade them to stop
>> taxing us...
>
> You know, the most interesting thing in this thread is certainly its title :
> ? Social problems of Python doc ?
>
> Yes, the little social problem here should be clear: if you have complaints to
> voice or improvements to suggest to the Python docs, you should do so on the
> issue tracker (*). For most topics, this is the only reasonable way to signal
> problems to the Python developers community, and so it is in most free software
> / open source projects.

"the *only* reasonable way"?  That's clearly wrong (unless you
want to wiggle in the room provided by "reasonable" or "most").
There is discussion on the dev list, there is discussion here.

The issue tracker is fine for many things, but the process it
provides is equivalent to peep-hole optimization.  How does one
submit a tracker issue for something like the overall organization
of the docs (for example, the mis-placement of things like data-
types in the library manual rather than the language manual)?

The big problem with the docs is poor writing (this includes
not using examples when they can help explain something more
clearly than verbiage alone).  It is understandable why this
should be so -- most programmers are good at and enjoy
programming, not writing and the python community is, say,
about 99.9% programmers.

This is why all the attempts (at least that I've noticed) are
programming focused -- build a wiki, write a new doc processing
framework, etc.  Unfortunately none of those addresses the real
problem -- the need for clear, well written, well organized
*content*.  I don't see how telling people to submit tracker
issues will solve this problem.  I can rewrite some section so
it sounds good to me, but likely it will be just as bad (perhaps
in different ways) that what is there.

The post that started this thread proposed something like paying
professional writers to improve the docs.  This may or may not
be a practical suggestion.  But the immediate response it
engendered was an auto-immune-like group response: the docs
are great already, don't complain, fix them yourself, yada, yada;
the same response that any criticism of free software produces.

It's really too bad the the python community can't seriously
discuss ways to improves the docs.  There are other possibilities
for instance the Fedora Docs project (can't say I'm impressed
by what they've produced but that doesn't mean their model
is useless).  There is a need for an approval process managed
by someone who actually understands what good technical writing
is.  And perhaps editors who can polish or work with programmers
who provide the raw technical description of some module.

Some kind of higher level more global process is the only
way I can see that the docs will be improved to any sort
or professional standard.  I don't see how issues like this
will be addressed by submitting tracker items.

Personally, I have given up on this issue.  The social factors
involved really pretty much determine that the Python docs
will never reach a very high quality -- that's just the way
it is and I've come to accept that.


From pacificik at warnell.uga.edu  Tue Aug 11 11:13:28 2009
From: pacificik at warnell.uga.edu (Krishna Pacifici)
Date: Tue, 11 Aug 2009 11:13:28 -0400
Subject: dictionary help
Message-ID: <4A8152580200008C00014A44@redhorse.forestry.uga.edu>

Thanks for the help.

Actually this is part of a much larger project, but I have unfortunately pigeon-holed myself into needing to do these things without a whole lot of flexibility.

To give a specific example I have the following dictionary where I need to remove values that are duplicated with other values and remove values that are duplicates of the keys, but still retain it as a dictionary.  Each value is itself a class with many attributes that I need to call later on in the program, but I cannot have duplicates because it would mess up some estimation part of my model.

d =
{36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11, 31], 22: [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}

So I want a new dictionary that would get rid of the duplicate values of 21, 22, 36 and 20 and give me back a dictionary that looked like this:

new_d=
{36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23, 12, 32], 26: [25, 27, 16], 30: [40]}

I understand that a dictionary may not be the best approach, but like I said I have sort of pigeon-holed myself by the way that I am simulating my data and the estimation model that I am using.  Any suggestions or comments about the above problem would be greatly appreciated.

Thanks again,
Krishna



>>> Dave Angel  08/11/09 7:38 AM >>>
Krishna Pacifici wrote:
> Hi,
> kind of a newbie here, but I have two questions that are probably pretty simple.
>
> 1.  I need to get rid of duplicate values that are associated with different keys in a dictionary.  For example I have the following code.
> s={}
> s[0]=[10,2,3]
>  s[10]=[22,23,24]
>  s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
>
> Now I want to be able to loop through the primary keys and get rid of duplicates (both in keys and values) so that I would have either a new dictionary or the same dictionary but with the following values:
>
> s[0]=[3]
>  s[10]=[22,23,24]
>  s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
>
> It doesn't matter which value gets removed as long as there is only one remaining, so in this example it doesn't matter that 2 got removed from s[0] or from s[30] as long as there is only one 2 in the dictionary.
>
> 2.  I need to be able to loop over the values in the dictionary when there are multiple values assigned to each key like above and assign new values to those values.  Taking the above example I would want to assign a new value so that when you called s[0] it would equal [3,4] say if 4 was the new value.  I think this should be as simple as adding a value, but I kept on having difficulty.
>
> Any suggestions would be greatly appreciated.
>
> Thank you very much,
> Krishna
>
>
>   
Sounds like homework.  If it was for an unconstrained project, I'd 
design a different data structure, one that directly enforced the data 
constraints.  So far, I can't imagine a useful reason for this 
particular set of constraints.

Let's break the problems down.

1a)   Do you know how to write a loop that visits all the keys of a 
dictionary?
1b)  Do you know how to safely check if a particular key exists?     
e.g.      if   key in s:
1c)  Do you know how to collect a set of values, so that when a 
duplicate is found, it can be recognized as such?
1d) Do you know how to remove an item from a list?

2a)  Like 1a)
2b) Do you know how to append a value to the end of a list?  Is s[key] a 
list?


DaveA


-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From sajmikins at gmail.com  Tue Aug 11 11:44:04 2009
From: sajmikins at gmail.com (Simon Forman)
Date: Tue, 11 Aug 2009 08:44:04 -0700 (PDT)
Subject: Search and write to .txt file
References: 
Message-ID: 

On Aug 11, 7:22?am, Helvin  wrote:
> Hi everyone,
>
> I am writing some python script that should find a line which contains
> '1' in the data.txt file, then be able to move a certain number of
> lines down, before replacing a line. At the moment, I am able to find
> the line '1', but when I use f.seek to move, and then rewrite, what I
> write goes to the end of the .txt file, instead of being adjusted by
> my f.seek.
>
> Do you know what way I should take?
>
> Data.txt is a file of 3 lines:
> ? ?line1
> ? ?line2
> ? ?line3
>
> Code:
>
> ? ?with open('data.txt', 'r+') as f:
> ? ? ? ?firstread = f.readlines() ? # Take a snapshot of initial file
>
> ? ? ? ?f.seek(0,0) ? ?# Go back to beginning and search
> ? ? ? ?for line in f:
> ? ? ? ? ? ?print line
> ? ? ? ? ? ?if line.find('1'):
> ? ? ? ? ? ? ? ?print 'line matched'
> ? ? ? ? ? ? ? ?f.seek(1,1) ? ? ? # Move one space along
> ? ? ? ? ? ? ? ?f.write('house\n') ? ? # f.write overwrites the exact
> number of bytes.
> ? ? ? ? ? ? ? ?break ? ? ? ? ? ? ? ? ? ?# leave loop once '1' is found
>
> ? ? ? ?f.seek(0,0) ? ? ? ? ? ? ?# Go back to beginning, and read
> data.txt again
> ? ? ? ?lastread = f.readlines()
>
> ? ? ? ?print 'firstread is', firstread
> ? ? ? ?print 'lastread is', lastread
>
> This shouldn't be too difficult, but I don't know how. > <
> Help appreciated!

There's a bug in this line:

if line.find('1'):

the string find() method returns an integer, which will be -1 if the
substring is not found. In python -1 is treated as True (only 0 is
False) so your if statement will always succeed unless '1' is the
first character on the line.

HTH,
~Simon


P.S. you can use the help() command in the python interpreter to get
docs on most things:

>>> help(str.find)

Help on method_descriptor:

find(...)
    S.find(sub [,start [,end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within s[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.



From python at mrabarnett.plus.com  Tue Aug 11 11:51:42 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Tue, 11 Aug 2009 16:51:42 +0100
Subject: dictionary help
In-Reply-To: <4A8152580200008C00014A44@redhorse.forestry.uga.edu>
References: <4A8152580200008C00014A44@redhorse.forestry.uga.edu>
Message-ID: <4A81938E.3070509@mrabarnett.plus.com>

Krishna Pacifici wrote:
> Thanks for the help.
> 
> Actually this is part of a much larger project, but I have unfortunately 
> pigeon-holed myself into needing to do these things without a whole lot 
> of flexibility.
> 
> To give a specific example I have the following dictionary where I need 
> to remove values that are duplicated with other values and remove values 
> that are duplicates of the keys, but still retain it as a dictionary.  
> Each value is itself a class with many attributes that I need to call 
> later on in the program, but I cannot have duplicates because it would 
> mess up some estimation part of my model.
> 
> d =
> {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11, 31], 22: 
> [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}
> 
> So I want a new dictionary that would get rid of the duplicate values of 
> 21, 22, 36 and 20 and give me back a dictionary that looked like this:
> 
> new_d=
> {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23, 
> 12, 32], 26: [25, 27, 16], 30: [40]}
> 
> I understand that a dictionary may not be the best approach, but like I 
> said I have sort of pigeon-holed myself by the way that I am simulating 
> my data and the estimation model that I am using.  Any suggestions or 
> comments about the above problem would be greatly appreciated.
> 
 >>> d = {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11,
31], 22: [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}
 >>> new_d = {}
 >>> seen = set(d.keys())
 >>> for k, v in d.items():
...     new_d[k] = [x for x in v if x not in seen]
...     seen |= set(new_d[k])
...
 >>> new_d
{36: [35, 37, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23, 12,
32], 26: [25, 27, 16], 30: [40]}



From sajmikins at gmail.com  Tue Aug 11 12:10:10 2009
From: sajmikins at gmail.com (Simon Forman)
Date: Tue, 11 Aug 2009 09:10:10 -0700 (PDT)
Subject: dictionary help
References: <4A8152580200008C00014A44@redhorse.forestry.uga.edu> 
	
Message-ID: 

On Aug 11, 11:51?am, MRAB  wrote:
> Krishna Pacifici wrote:
> > Thanks for the help.
>
> > Actually this is part of a much larger project, but I have unfortunately
> > pigeon-holed myself into needing to do these things without a whole lot
> > of flexibility.
>
> > To give a specific example I have the following dictionary where I need
> > to remove values that are duplicated with other values and remove values
> > that are duplicates of the keys, but still retain it as a dictionary. ?
> > Each value is itself a class with many attributes that I need to call
> > later on in the program, but I cannot have duplicates because it would
> > mess up some estimation part of my model.
>
> > d =
> > {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11, 31], 22:
> > [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}
>
> > So I want a new dictionary that would get rid of the duplicate values of
> > 21, 22, 36 and 20 and give me back a dictionary that looked like this:
>
> > new_d=
> > {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23,
> > 12, 32], 26: [25, 27, 16], 30: [40]}
>
> > I understand that a dictionary may not be the best approach, but like I
> > said I have sort of pigeon-holed myself by the way that I am simulating
> > my data and the estimation model that I am using. ?Any suggestions or
> > comments about the above problem would be greatly appreciated.
>
> ?>>> d = {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11,
> 31], 22: [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}
> ?>>> new_d = {}
> ?>>> seen = set(d.keys())
> ?>>> for k, v in d.items():
> ... ? ? new_d[k] = [x for x in v if x not in seen]
> ... ? ? seen |= set(new_d[k])
> ...
> ?>>> new_d
> {36: [35, 37, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23, 12,
> 32], 26: [25, 27, 16], 30: [40]}

Ha ha, MRAB beat me to it:

d = {
    36: [35, 37, 26, 46],
    75: [74, 76, 65, 85],
    21: [20, 22, 11, 31],
    22: [21, 23, 12, 32],
    26: [25, 27, 16, 36],
    30: [20, 31, 40],
    }


new_d = { # Given, and apparently incorrect.
    36: [35, 37, 26, 46], # 26 is a key and should be gone.
    75: [74, 76, 65, 85],
    21: [20, 11, 31],
    22: [23, 12, 32],
    26: [25, 27, 16],
    30: [40],
    }


expected = {
    36: [35, 37, 46],
    75: [74, 76, 65, 85],
    21: [20, 11, 31],
    22: [23, 12, 32],
    26: [25, 27, 16],
    30: [40],
    }


def removeDuplicates(D):
    '''
    Remove values that are duplicated with other values
    and remove values that are duplicates of the keys.

    Assumes that values in the lists are already unique within
    each list.  I.e. duplicates are only in the keys or in other
    lists.

    This function works "in place" on D, so it doesn't return
    anything.  Caller must keep a reference to D.
    '''

    seen = set(D) # Get a set of the keys.

    for key, values_list in D.iteritems():

        # Filter out values that have already been seen.
        filtered_values = [
            value
            for value in values_list
            if not value in seen
            ]

        # Remember newly seen values.
        seen.update(filtered_values)

        D[key] = filtered_values


## Example:
##
##    >>> d == expected
##    False
##    >>> removeDuplicates(d)
##    >>> d == expected
##    True


From ethan at stoneleaf.us  Tue Aug 11 12:12:44 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Tue, 11 Aug 2009 09:12:44 -0700
Subject: add fields in a existing dbf
In-Reply-To: <4A815572.1020905@ceam.es>
References: <4A815572.1020905@ceam.es>
Message-ID: <4A81987C.4080800@stoneleaf.us>

Alonso Luj?n Torres Ta?o wrote:
> Hi!
> 
> I'm trying to modify a dbf adding a new field in a python script, but I 
> can't.
> 
> Just I can add a field in new dbf created in the same script.
> 
> I tryed with:
> 
>     db = dbf.Dbf("../filesource.dbf",new =False, readOnly=False)
>     ...
>     db.addField(("PESO","N",32,8))
> 
> and return error:
> 
>     Traceback (most recent call last):
>       File "script.py", line 34, in 
>         db.addField(("PESO","N",32,8))
>       File "/usr/lib/python2.5/site-packages/dbfpy/dbf.py", line 229, in
>     addField
>         "structure can't be changed")
>     TypeError: ('At least one record was added, ', "structure can't be
>     changed")
> 
> 
> I have not idea of what error I make.
> 
> If someone can help me, I'll so gratefull.
> 
> Thanks!
> 

I am not familiar with dbfpy, but the dbf files I am familiar with do 
not support 32 digit Numerics.  Did you mean 12?

At any rate, if you use http://groups.google.com/group/python-dbase

the commands would be:

import dbf
db = dbf.Table("../filesource.dbf")
db.add_fields("peso N(12.8)")
db.close()

and you'll have your field -- assuming, of course, you have write 
priveleges, etc.

Hope this helps!

~Ethan~

Disclaimer:  I am the author of python-dbase.


From petshmidt at googlemail.com  Tue Aug 11 12:33:52 2009
From: petshmidt at googlemail.com (someone)
Date: Tue, 11 Aug 2009 09:33:52 -0700 (PDT)
Subject: better way?
Message-ID: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>

Hello,

I'd like to make insert into db if record not exist otherwise update.
to save typing list of columns in both statements I do following

query = "SELECT location FROM table WHERE location = %s AND id = %s;"
result = self._getResult(db, query, [location,id])

fields = ['id', 'location', 'wl', 'modified', 'counter', 'name']
if result:
    t = map(lambda s: s + ' = %s', fields)
    temp = ", ".join(t)
    query = "UPDATE table SET " + temp + " WHERE location = %s AND id
= %s;"
    self._execQuery(db, query, [id, location, self.wl, 'NOW()', 1,
name, location, id])
else:
    f = ", ".join(fields)
    query = """
        INSERT INTO table
        (""" + f + """)
        VALUES
        (%s,%s,%s,NOW()- interval '1 day', 1, %s)
    """
    self._execQuery(db, query, [id, location, self.wl, name])



is there better or more readable way to do it?

Pet


From bthate at gmail.com  Tue Aug 11 12:41:37 2009
From: bthate at gmail.com (Bart Thate)
Date: Tue, 11 Aug 2009 09:41:37 -0700 (PDT)
Subject: GOZERBOT 0.9.1 released
Message-ID: <0fefbd87-efa2-4eaa-afe1-9e5b7ec5ad86@z31g2000yqd.googlegroups.com>

here it is .. GOZERBOT 0.9.1 !!

Main change this time is the distribution method, we now provide a
tar.gz with all the dependencies included. This means that you can run
the bot locally without any root required. Python 2.5 or higher
needed, see http://gozerbot.org

Enjoy !

about GOZERBOT:

GOZERBOT is a channel bot that aids with conversation in irc channels
and
jabber conference rooms. its mainly used to serve rss feeds and to
have
custom commands made for the channel. More then just a channel bot
GOZERBOT
aims to provide a platform for the user to program his own bot and
make it
into something thats usefull. This is done with a plugin structure
that
makes it easy to program your own. But GOZERBOT comes with some
batteries
included, there are now over 100 plugins already written and ready for
use.


From emile at fenx.com  Tue Aug 11 12:49:19 2009
From: emile at fenx.com (Emile van Sebille)
Date: Tue, 11 Aug 2009 09:49:19 -0700
Subject: Is there any package implanation the following arithmetics?
In-Reply-To: 
References: 
Message-ID: 

On 8/11/2009 1:49 AM zhongshq said...
> Hi,
> 
> I wonder if there has any package can check whether two rectangles are
> overlap, is a dot inside or outside a polygon, etc.

PythonCad at http://sourceforge.net/projects/pythoncad/ has 
intersections built in.

Emile



From rt8396 at gmail.com  Tue Aug 11 12:49:31 2009
From: rt8396 at gmail.com (r)
Date: Tue, 11 Aug 2009 09:49:31 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References:   
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	<4A80472E.4090108@stoneleaf.us> 
	
	
Message-ID: <63f2b657-c646-4a69-9a05-1da5975bb6d2@z31g2000yqd.googlegroups.com>

On Aug 11, 1:47?am, Steven D'Aprano
 wrote:
> On Mon, 10 Aug 2009 20:05:00 -0400, David Lyon wrote:
> > Ignore feedback... tell people to freak off...
>
> Only useless feedback.

And who decides what is useless and what isn't Steven?. You?, alex23?,
Bruno?, Paul? Carl? Who makes these decisions and do *they* make them
without pride or prejudice? Do they approve an idea by someone they
hate because it it good, or do they toss it in the trash just to spite
them, because they have the power to do so? As we can see much
resistace exists against even the ideas of change. How will change
ever take place with such defiance!

I am sorry but i feel many here would not judge fairly based on the
merits of an idea without allowing "buddy-systems" or "pecking-orders"
to get in the way. Sad really, only Python suffers in the end.

Some say the tutorial is not meant for non-programmers, but for
programmers with no Python experience. So! How does that justify
obstruction of the tut? Why not present the same information in a way
both can easily understand? I thought Pythons original vision was to
allow easy entry into programming for anybody -- experienced or not!
Anybody remember "CP4E"?

Is this an ivory tower thing? i dunno, but it seems to be...???



From pacificik at warnell.uga.edu  Tue Aug 11 12:55:28 2009
From: pacificik at warnell.uga.edu (Krishna Pacifici)
Date: Tue, 11 Aug 2009 12:55:28 -0400
Subject: dictionary help
Message-ID: <4A816A400200008C00014A70@redhorse.forestry.uga.edu>

Wow, thanks MRAB and Simon, you guys are good.

I guess I will go ahead and ask the next question that has also stumped me for awhile now.

So basically I need to loop through the values in the new dictionary and append attributes of a class object.  Each of the values (and keys) represent a block in a grid with a specific location (e.g. 35 is the block in row 3 col 5) and each block is an object with several attributes associated with it.  I want to call that block and append two separate attributes to the dictionary within that same key.

So again it would look something like this:

block 35 has 2 attributes, say a and b, a=2, b=5 
block 37 has a=1, b=3
block 46 has a=3, b=8

the two attributes come from two different definitions within the class statement, 
def detections
...
return a

def abundance
...
return b

so I would want to append to key 36 those two attributes for each block so that the resulting dictionary item would look like this:
                         a           b   
{36:[35,37,46], [2,1,3], [5,3,8] ...}

Any help with this would be greatly appreciated.  And thank you so much for all of your help thus far, I'm still pretty new to python and am enjoying all of the flexibility associated with a scripting and programming language.

Thanks again,
Krishna

>>> Simon Forman  08/11/09 12:15 PM >>>
On Aug 11, 11:51 am, MRAB  wrote:
> Krishna Pacifici wrote:
> > Thanks for the help.
>
> > Actually this is part of a much larger project, but I have unfortunately
> > pigeon-holed myself into needing to do these things without a whole lot
> > of flexibility.
>
> > To give a specific example I have the following dictionary where I need
> > to remove values that are duplicated with other values and remove values
> > that are duplicates of the keys, but still retain it as a dictionary.  
> > Each value is itself a class with many attributes that I need to call
> > later on in the program, but I cannot have duplicates because it would
> > mess up some estimation part of my model.
>
> > d =
> > {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11, 31], 22:
> > [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}
>
> > So I want a new dictionary that would get rid of the duplicate values of
> > 21, 22, 36 and 20 and give me back a dictionary that looked like this:
>
> > new_d=
> > {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23,
> > 12, 32], 26: [25, 27, 16], 30: [40]}
>
> > I understand that a dictionary may not be the best approach, but like I
> > said I have sort of pigeon-holed myself by the way that I am simulating
> > my data and the estimation model that I am using.  Any suggestions or
> > comments about the above problem would be greatly appreciated.
>
>  >>> d = {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11,
> 31], 22: [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}
>  >>> new_d = {}
>  >>> seen = set(d.keys())
>  >>> for k, v in d.items():
> ...     new_d[k] = [x for x in v if x not in seen]
> ...     seen |= set(new_d[k])
> ...
>  >>> new_d
> {36: [35, 37, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23, 12,
> 32], 26: [25, 27, 16], 30: [40]}

Ha ha, MRAB beat me to it:

d = {
    36: [35, 37, 26, 46],
    75: [74, 76, 65, 85],
    21: [20, 22, 11, 31],
    22: [21, 23, 12, 32],
    26: [25, 27, 16, 36],
    30: [20, 31, 40],
    }


new_d = { # Given, and apparently incorrect.
    36: [35, 37, 26, 46], # 26 is a key and should be gone.
    75: [74, 76, 65, 85],
    21: [20, 11, 31],
    22: [23, 12, 32],
    26: [25, 27, 16],
    30: [40],
    }


expected = {
    36: [35, 37, 46],
    75: [74, 76, 65, 85],
    21: [20, 11, 31],
    22: [23, 12, 32],
    26: [25, 27, 16],
    30: [40],
    }


def removeDuplicates(D):
    '''
    Remove values that are duplicated with other values
    and remove values that are duplicates of the keys.

    Assumes that values in the lists are already unique within
    each list.  I.e. duplicates are only in the keys or in other
    lists.

    This function works "in place" on D, so it doesn't return
    anything.  Caller must keep a reference to D.
    '''

    seen = set(D) # Get a set of the keys.

    for key, values_list in D.iteritems():

        # Filter out values that have already been seen.
        filtered_values = [
            value
            for value in values_list
            if not value in seen
            ]

        # Remember newly seen values.
        seen.update(filtered_values)

        D[key] = filtered_values


## Example:
##
##    >>> d == expected
##    False
##    >>> removeDuplicates(d)
##    >>> d == expected
##    True
-- 
http://mail.python.org/mailman/listinfo/python-list

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From liukis at usc.edu  Tue Aug 11 13:29:42 2009
From: liukis at usc.edu (Maria Liukis)
Date: Tue, 11 Aug 2009 10:29:42 -0700
Subject: Any built-in function for smallest positive floating point number?
Message-ID: 

Hello everybody,

Is somebody aware of built-in Python's function that would return a  
value for smallest positive double precision floating point number  
(analogous to 'realmin' in Matlab). Python has built-in sys.maxint  
but I could not find anything for float.

Any help would be greatly appreciated.

Thanks,
Masha
--------------------
liukis at usc.edu



-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From dotancohen at gmail.com  Tue Aug 11 13:33:39 2009
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 11 Aug 2009 20:33:39 +0300
Subject: Scraping Wikipedia with Python
Message-ID: <880dece00908111033n2a9f8e5et937d1f4bbcb2df89@mail.gmail.com>

I plan on making a geography-learning Anki [1] deck, and Wikipedia has
the information that I need in nicely formatted tables on the side of
each country's page. Has someone already invented a wheel to parse and
store that data (scrape)? It is probably not difficult to code, and
within the Wikipedia license, but if that wheel has already been
invented then I don't want to redo it. I tried googling for a
Wikipedia-specific solution but found none, is there a general purpose
solution that I could use?

Note that I am a regular Wikipedia contributor and plan on staying
within the realm of Wikipedia's rules.


[1] http://ichi2.net/anki/

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il


From Francis.Brissette at autodesk.com  Tue Aug 11 13:39:49 2009
From: Francis.Brissette at autodesk.com (Francis Brissette)
Date: Tue, 11 Aug 2009 10:39:49 -0700
Subject: Unsigned char array to an unsigned longlong array
Message-ID: 

Hello,

I'm using Python 2.6.2.
Is there a way to have an Array of unsigned longlong (C Type: unsigned longlong, Minimum size if bytes: 8) ?
I found a page on the internet (http://mail.python.org/pipermail/patches/2005-April/017430.html), but I'm not quite sure if it is available.


What I want to do is to store an array of bytes in an array of longlongs.
To workaround this issue, I have tried to use the double array (TypeCode 'd'), since the size in bytes is the same (8 for instance).
But it gives me strange result. Please look at the example:

import array
myByteArray = array.array('B', [1,2,3,4,5,6,7,8])
>> myByteArray = array('B', [1, 2, 3, 4, 5, 6, 7, 8])

myLongArray = array.array('L', myByteArray.tostring() )
myLongArray = array('L', [67305985L, 134678021L])

myDoubleArray = array.array('d', myByteArray.tostring() )
myDoubleArray = array('d', [5.447603722011605e-270])

If we convert the byte array to an hex form, we will get for the long array: [04030201, 08070605].
If we convert this hex array to decimal, we then get the Long Array: [67305985, 134678021].

Now, if we do the same exercise for the double array, the hex form will look like: [0807060504030201].
And the decimal value would be: [5.784376957523072e+17].

Where does the 5.447603722011605e-270 value comes from ?


Thanks for your help,
Francis
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From breamoreboy at yahoo.co.uk  Tue Aug 11 13:41:48 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 18:41:48 +0100
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <63f2b657-c646-4a69-9a05-1da5975bb6d2@z31g2000yqd.googlegroups.com>
References:  
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>	
		<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>		<4A80472E.4090108@stoneleaf.us>
		
	<63f2b657-c646-4a69-9a05-1da5975bb6d2@z31g2000yqd.googlegroups.com>
Message-ID: 

r wrote:
> On Aug 11, 1:47 am, Steven D'Aprano
>  wrote:
>> On Mon, 10 Aug 2009 20:05:00 -0400, David Lyon wrote:
>>> Ignore feedback... tell people to freak off...
>> Only useless feedback.
> 
[snip]
> 
> I am sorry but i feel many here would not judge fairly based on the
> merits of an idea without allowing "buddy-systems" or "pecking-orders"
> to get in the way. Sad really, only Python suffers in the end.
I disagree with these comments.  I do not believe that Python has a 
buddy system or a pecking order getting in the way of anything.  As you 
are making thsse accusations, either provide hard evidence that can 
persuade me that your perspective on this is correct or shut up.
> 
[snip]
> 

-- 
Kindest regards.

Mark Lawrence.



From nagle at animats.com  Tue Aug 11 13:48:17 2009
From: nagle at animats.com (John Nagle)
Date: Tue, 11 Aug 2009 10:48:17 -0700
Subject: Is "feedparser" deprecated?
In-Reply-To: 
References: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
	
Message-ID: <4a81adee$0$1654$742ec2ed@news.sonic.net>

Gabriel Genellina wrote:
> En Fri, 07 Aug 2009 16:07:48 -0300, John Nagle 
> escribi?:
> 
>>    Feedparser requires SGMLlib, which has been removed from Python 3.0.
>> Feedparser hasn't been updated since 2007. Does this mean Feedparser
>> is dead?
> 
> Since we have generic and easy of use XML parsers like ElementTree and
> lxml,  specialized rss parsers like feedparser are not so much required.
> I've used ElementTree when I had to parse an rss feed in the past (not so
> many times).

    Take a look at what Feedparser has to do to deal with real-world RSS
feeds.  There are several hundred lines of code just to figure out the
source encoding.  There's gzip support, Atom support, base 64 encoding
support... Then there's the RSS polling protocol, which also requires
some support.  A basic XML parser only does part of the job.

					John Nagle


From liukis at usc.edu  Tue Aug 11 13:48:55 2009
From: liukis at usc.edu (Maria Liukis)
Date: Tue, 11 Aug 2009 10:48:55 -0700
Subject: Any built-in function for smallest positive floating point number?
In-Reply-To: 
References: 
Message-ID: <3E85703A-28AF-4626-8BFB-786C85810BCD@usc.edu>

A bit more of googling gave me an answer:

 >>> import numpy as np
 >>> np.finfo(np.double).tiny
array(2.2250738585072014e-308)
 >>>

Thanks,
Masha
--------------------
liukis at usc.edu



On Aug 11, 2009, at 10:29 AM, Maria Liukis wrote:

> Hello everybody,
>
> Is somebody aware of built-in Python's function that would return a  
> value for smallest positive double precision floating point number  
> (analogous to 'realmin' in Matlab). Python has built-in sys.maxint  
> but I could not find anything for float.
>
> Any help would be greatly appreciated.
>
> Thanks,
> Masha
> --------------------
> liukis at usc.edu
>
>
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at REMOVE-THIS-cybersource.com.au  Tue Aug 11 13:53:16 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 17:53:16 GMT
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
Message-ID: <0291a07d$0$20639$c3e8da3@news.astraweb.com>

On Tue, 11 Aug 2009 07:57:28 -0700, rurpy wrote:

> On 08/11/2009 01:47 AM, Antoine Pitrou wrote:
>> r  gmail.com>  writes:
>>> On Aug 9, 11:02 pm, David Lyon  wrote:
>>>> Since you're talking about documentation, which is a part of python,
>>>> don't you think you should be discussing it on python-dev ?
>>> Yea, them's be a friendly bunch to noob ideas ;). Hey i got a better
>>> idea, lets go to the IRS and see if we can persuade them to stop
>>> taxing us...
>>
>> You know, the most interesting thing in this thread is certainly its
>> title : ? Social problems of Python doc ?
>>
>> Yes, the little social problem here should be clear: if you have
>> complaints to voice or improvements to suggest to the Python docs, you
>> should do so on the issue tracker (*). For most topics, this is the
>> only reasonable way to signal problems to the Python developers
>> community, and so it is in most free software / open source projects.
> 
> "the *only* reasonable way"?  That's clearly wrong (unless you want to
> wiggle in the room provided by "reasonable" or "most"). There is
> discussion on the dev list, there is discussion here.

Discussion here is spitting into the wind. The noise-to-signal ratio is 
high enough that the people who can fix an issue aren't likely to see it 
here. Unless somebody raises a report in the bug tracker, it will go 
nowhere, fast.

The same happens for issues on the dev list: I can't count how many times 
people there have said "put it in the bug tracker, or it will be 
forgotten".


> The issue tracker is fine for many things, but the process it provides
> is equivalent to peep-hole optimization.  How does one submit a tracker
> issue for something like the overall organization of the docs (for
> example, the mis-placement of things like data- types in the library
> manual rather than the language manual)?

The same way you would submit a tracker issue for anything.

"Documentation bug: Data types are misplaced in the library manual 
instead of the language manual.

Suggested alternative: move page docs.python.org/xyz.html to abc.html"



> The big problem with the docs is poor writing (this includes not using
> examples when they can help explain something more clearly than verbiage
> alone).

There's a difference between insufficiently good writing and poor 
writing: think of grading the docs, where 100 is "perfect in every way" 
and -100 is "perfectly awful in every possible way". (It's not a linear 
scale.) A score of 0 is "mediocre, just barely acceptable". Poor writing 
has a negative score. In my opinion, Python's docs are perhaps a 40 or 
50, significantly better than most technical docs I've seen.


[...]
>  I can rewrite some section so it sounds good to me, but likely it will
> be just as bad (perhaps in different ways) that what is there.

Bug reports are valuable even if you don't have the skills to provide a 
patch. Bug reports with patches are even more valuable, but that doesn't 
mean that the failure to provide a patch *necessarily* dooms your report 
to oblivion.


> The post that started this thread proposed something like paying
> professional writers to improve the docs.  This may or may not be a
> practical suggestion.  But the immediate response it engendered was an
> auto-immune-like group response: the docs are great already, don't
> complain, fix them yourself, yada, yada; the same response that any
> criticism of free software produces.

I haven't seen any such knee-jerk responses. What I've seen is a set of 
sensible, *practical* advice:

- complaining on its own, especially here, is pointless;

- Python is a community effort, if you see something that needs fixing, 
do something about it;

- many of us DON'T want arbitrary people "correcting" the official docs 
without oversight, and believe that would be a disaster (arbitrary people 
aren't give check-in privileges to add code to Python's standard library, 
nor should they be given check-in privileges to add docs);

- if people are keen on a Python wiki, then by all means publish one, 
just don't expect the Python dev team to build and manage it for you;

- bug reports and patches to the docs are ALWAYS welcome, even if they 
are rejected;

- if you don't have the skills to fix a bug (including doc bugs), an 
alternative is to pay somebody else to do so instead.

 
> It's really too bad the the python community can't seriously discuss
> ways to improves the docs.  There are other possibilities for instance
> the Fedora Docs project (can't say I'm impressed by what they've
> produced but that doesn't mean their model is useless).  There is a need
> for an approval process managed by someone who actually understands what
> good technical writing is.  And perhaps editors who can polish or work
> with programmers who provide the raw technical description of some
> module.

Yes, you're correct. 

[sarcasm] Now that we've agreed on what needs to be done, the problem is 
solved!!! [end sarcasm]



> Some kind of higher level more global process is the only way I can see
> that the docs will be improved to any sort or professional standard.  I
> don't see how issues like this will be addressed by submitting tracker
> items.

You want community input into the docs, but you're not willing to give 
that input except to bitch and moan and sook that the tracker is no good.

Even if the PSF had a full-time team of professional documentation 
writers and editors, guess what, you would STILL need to submit issues to 
the bug tracker, because otherwise THEY WON'T BE TRACKED.


> Personally, I have given up on this issue.  The social factors involved
> really pretty much determine that the Python docs will never reach a
> very high quality -- that's just the way it is and I've come to accept
> that.

Ultimately it boils down to two factors:

Money.

Effort.

If you won't put in the effort, and you won't put in the money, then it 
won't happen. Moaning that other people aren't putting in the money to 
hire team of professional writers isn't productive, and moaning that 
other people aren't putting in the effort to improve the docs isn't 
either.



-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Tue Aug 11 14:00:08 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 18:00:08 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
	
Message-ID: <0291a21a$0$20639$c3e8da3@news.astraweb.com>

On Tue, 11 Aug 2009 15:50:01 +0200, Piet van Oostrum wrote:

>>>>>> Steven D'Aprano  (SD) wrote:
> 
>>SD> If I'm reading this page correctly, Python does behave as C++ does.
>>Or at SD> least as Larch/C++ does:
> 
>>SD> http://www.cs.ucf.edu/~leavens/larchc++manual/lcpp_47.html
> 
> They call them `non-standard escape sequences' for a reason: that they
> are not in standard C++.
> 
> test.cpp:
> char* temp = "abc\yz";
> 
> TEMP> g++ -c test.cpp
> test.cpp:1:1: warning: unknown escape sequence '\y'


Isn't that a warning, not a fatal error? So what does temp contain?



-- 
Steven


From squishywaffle at gmail.com  Tue Aug 11 14:14:14 2009
From: squishywaffle at gmail.com (squishywaffle at gmail.com)
Date: Tue, 11 Aug 2009 11:14:14 -0700 (PDT)
Subject: Networked Broadcast Messaging
Message-ID: <37ea826b-708d-48f4-a64a-42f58fec5325@c2g2000yqi.googlegroups.com>

I'm not exactly sure what the term for this would be, but I was
wondering if there were any Python packages that supported some kind
of ad-hoc message broadcasting. What I'd like to do is something like
this:

* On a number of workhorse machines, a process listens for network
messages from our broadcast service. It subscribes to a certain sub-
set of them and will only respond to the messaging events that it is
subscribed to.
* Any machine can broadcast a message out to the network of machines
without specifying an IP address.
* Machines can come and go. Since messages are not directly sent to a
specific IP address from our Python script, the messages are simply
broadcasted to those who are there to listen. If nobody is subscribed
to the message type being sent, nothing happens.

I know XML-RPC and other friends are an option, but I'm looking for
something that doesn't require managing a set of IP addresses or
hostnames. I'm not sure what to Google for such a package/module, any
direction would be greatly appreciated.


From pacificik at warnell.uga.edu  Tue Aug 11 14:17:15 2009
From: pacificik at warnell.uga.edu (Krishna Pacifici)
Date: Tue, 11 Aug 2009 14:17:15 -0400
Subject: looping through values in a dictionary and appending to a
	 list
Message-ID: <4A817D6B0200008C00014A9B@redhorse.forestry.uga.edu>

Nevermind,
got it.

Sorry.

>>> Krishna Pacifici 08/11/09 2:12 PM >>>
Hi,
I want to append the values of a dictionary to a list.  I have a dictionary sec_dict_clean and I want to append the values to a list, but am having a hard time looping through the values in the dictionary.

I have tried something like this:
lista=[]
for i in sec_dict_clean.values():
    for j in sec_dict_clean.values()[i]:
        lista.append(sec_dict_clean.values()[i])

But I keep on getting an error:
TypeError: list indices must be integers

Any ideas on how to loop through values in a dictionary?

Thanks,
Krishna

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nagle at animats.com  Tue Aug 11 14:26:44 2009
From: nagle at animats.com (John Nagle)
Date: Tue, 11 Aug 2009 11:26:44 -0700
Subject: Scraping Wikipedia with Python
In-Reply-To: 
References: 
Message-ID: <4a81b6f0$0$1590$742ec2ed@news.sonic.net>

Dotan Cohen wrote:
> I plan on making a geography-learning Anki [1] deck, and Wikipedia has
> the information that I need in nicely formatted tables on the side of
> each country's page. Has someone already invented a wheel to parse and
> store that data (scrape)? 

     Wikipedia has an API for computer access.  See

	http://www.mediawiki.org/wiki/API

				John Nagle


From dotancohen at gmail.com  Tue Aug 11 14:29:40 2009
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 11 Aug 2009 21:29:40 +0300
Subject: Scraping Wikipedia with Python
In-Reply-To: <4a81b6f0$0$1590$742ec2ed@news.sonic.net>
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
Message-ID: <880dece00908111129k525a0614td4c59a7a9371a7ba@mail.gmail.com>

> ? ?Wikipedia has an API for computer access. ?See
>
> ? ? ? ?http://www.mediawiki.org/wiki/API
>

Yes, I am aware of this as well. Does anyone know of a python class
for easily interacting with it, or do I need to roll my own.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il


From greg.kujawa at gmail.com  Tue Aug 11 14:34:54 2009
From: greg.kujawa at gmail.com (gregarican)
Date: Tue, 11 Aug 2009 11:34:54 -0700 (PDT)
Subject: Networked Broadcast Messaging
References: <37ea826b-708d-48f4-a64a-42f58fec5325@c2g2000yqi.googlegroups.com>
Message-ID: <889a2a1d-e791-479e-8e41-4387e1b258fd@z31g2000yqd.googlegroups.com>

On Aug 11, 2:14?pm, "squishywaf... at gmail.com"
 wrote:
> I'm not exactly sure what the term for this would be, but I was
> wondering if there were any Python packages that supported some kind
> of ad-hoc message broadcasting. What I'd like to do is something like
> this:
>
> * On a number of workhorse machines, a process listens for network
> messages from our broadcast service. It subscribes to a certain sub-
> set of them and will only respond to the messaging events that it is
> subscribed to.
> * Any machine can broadcast a message out to the network of machines
> without specifying an IP address.
> * Machines can come and go. Since messages are not directly sent to a
> specific IP address from our Python script, the messages are simply
> broadcasted to those who are there to listen. If nobody is subscribed
> to the message type being sent, nothing happens.
>
> I know XML-RPC and other friends are an option, but I'm looking for
> something that doesn't require managing a set of IP addresses or
> hostnames. I'm not sure what to Google for such a package/module, any
> direction would be greatly appreciated.

Offhand I'd suggest binding a specific UDP port on the listening
workstations. Then the broadcasting workstation(s) could just pull a
standard list of IP's based on its own subnet. Then there'd be no hard-
coded machine names or IP addresses to manage. Just send the message
to all hosts on the same subnet as the broadcaster(s). Plus the UDP
connection would be stateless and not care if the receivers actually
got the message or not...


From kushal.kumaran+python at gmail.com  Tue Aug 11 14:39:30 2009
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Wed, 12 Aug 2009 00:09:30 +0530
Subject: better way?
In-Reply-To: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
Message-ID: <1e364c4e0908111139r5c4536d6s90be6cf5aef2d26a@mail.gmail.com>

On Tue, Aug 11, 2009 at 10:03 PM, someone wrote:
> Hello,
>
> I'd like to make insert into db if record not exist otherwise update.
> to save typing list of columns in both statements I do following
>
> 
>
>
> is there better or more readable way to do it?
>

Well, mysql, in particular, offers an "on duplicate key update" clause
that you can take a look at.  Don't know about about other databases.

-- 
kushal


From http  Tue Aug 11 14:40:46 2009
From: http (Paul Rubin)
Date: 11 Aug 2009 11:40:46 -0700
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
Message-ID: <7xk51anqhd.fsf@ruckus.brouhaha.com>

Steven D'Aprano  writes:
> - if people are keen on a Python wiki, then by all means publish one, 
> just don't expect the Python dev team to build and manage it for you;

There are already some nice ones at:

   http://en.wikibooks.org/wiki/Python


From python at rcn.com  Tue Aug 11 14:43:29 2009
From: python at rcn.com (Raymond Hettinger)
Date: Tue, 11 Aug 2009 11:43:29 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References:   
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	 
	<081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com> 
	<7xr5vj9m0g.fsf@ruckus.brouhaha.com>
Message-ID: <2fd432c7-00e2-4bb6-9192-e9f7aa96c4d7@m3g2000pri.googlegroups.com>

[Paul Rubin]
> I think the Python tutorial is aimed at users who are newbies to
> Python but not newbies to programming. ?Writing a tutorial for total
> newbies is a completely different problem, that would result in a much
> different document that's less useful to the existing tutorial's
> intended audience.

There is more than one right answer to "what is the best tutorial
for different people".  The www.python.org website lists a number
of tutorials.  Here is the page specifically marked for those
who are new to programming:

 http://wiki.python.org/moin/BeginnersGuide


Raymond





From petshmidt at googlemail.com  Tue Aug 11 14:45:50 2009
From: petshmidt at googlemail.com (Pet)
Date: Tue, 11 Aug 2009 11:45:50 -0700 (PDT)
Subject: better way?
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
Message-ID: <78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>

On 11 Aug., 20:39, Kushal Kumaran 
wrote:
> On Tue, Aug 11, 2009 at 10:03 PM, someone wrote:
> > Hello,
>
> > I'd like to make insert into db if record not exist otherwise update.
> > to save typing list of columns in both statements I do following
>
> > 
>
> > is there better or more readable way to do it?
>
> Well, mysql, in particular, offers an "on duplicate key update" clause
> that you can take a look at. ?Don't know about about other databases.
>
> --
> kushal

Oh, forgotten to mention. It's PostGres


From http  Tue Aug 11 14:52:46 2009
From: http (Paul Rubin)
Date: 11 Aug 2009 11:52:46 -0700
Subject: Python docs disappointing - group effort to hire writers?
References:  
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	<4A80472E.4090108@stoneleaf.us>
	
	
	<63f2b657-c646-4a69-9a05-1da5975bb6d2@z31g2000yqd.googlegroups.com>
Message-ID: <7xfxbynpxd.fsf@ruckus.brouhaha.com>

r  writes:
> Some say the tutorial is not meant for non-programmers, but for
> programmers with no Python experience. So! How does that justify
> obstruction of the tut? Why not present the same information in a way
> both can easily understand? 

I agree that a tutorial for non-programmers would be useful, but it's
better to have it as a separate document.  The existing tutorial helps
experienced programmers get started with Python very quickly, by
checking off familiar features from other languages and saying how
Python implements them.  Someone familiar with (say) Java or C++ can
read it in a few minutes and start contributing to a Python project.
Pitching it to complete beginners would require covering a lot of
ground that is already well known to someone who programs in other
languages, and would slow it down too much. 


From dullrich at sprynet.com  Tue Aug 11 14:53:03 2009
From: dullrich at sprynet.com (David C Ullrich)
Date: Tue, 11 Aug 2009 13:53:03 -0500
Subject: Scraping Wikipedia with Python
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	
Message-ID: <6YidncRAiJ6SIxzXRVn_vwA@giganews.com>

On Tue, 11 Aug 2009 21:29:40 +0300, Dotan Cohen wrote:

>> ? ?Wikipedia has an API for computer access. ?See
>>
>> ? ? ? ?http://www.mediawiki.org/wiki/API
>>
>>
> Yes, I am aware of this as well. Does anyone know of a python class for
> easily interacting with it, or do I need to roll my own.

Try reading a little there! Starting there I went to

http://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot

where I found a section on existing bots, comments on how the "scraping"
is not what you want, and even a Python section with a link to something 
labelled  PyWikipediaBot...






From http  Tue Aug 11 14:54:16 2009
From: http (Paul Rubin)
Date: 11 Aug 2009 11:54:16 -0700
Subject: Python docs disappointing - group effort to hire writers?
References:  
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	
	<081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com>
	<7xr5vj9m0g.fsf@ruckus.brouhaha.com>
	<2fd432c7-00e2-4bb6-9192-e9f7aa96c4d7@m3g2000pri.googlegroups.com>
Message-ID: <7xab266v1j.fsf@ruckus.brouhaha.com>

Raymond Hettinger  writes:
> Here is the page specifically marked for those who are new to programming:
>  http://wiki.python.org/moin/BeginnersGuide

Oh cool, I didn't know about that one.


From kushal.kumaran+python at gmail.com  Tue Aug 11 15:00:37 2009
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Wed, 12 Aug 2009 00:30:37 +0530
Subject: Networked Broadcast Messaging
In-Reply-To: <889a2a1d-e791-479e-8e41-4387e1b258fd@z31g2000yqd.googlegroups.com>
References: <37ea826b-708d-48f4-a64a-42f58fec5325@c2g2000yqi.googlegroups.com>
	<889a2a1d-e791-479e-8e41-4387e1b258fd@z31g2000yqd.googlegroups.com>
Message-ID: <1e364c4e0908111200j5d83b5d4o6ab950b82265189c@mail.gmail.com>

On Wed, Aug 12, 2009 at 12:04 AM, gregarican wrote:
> On Aug 11, 2:14?pm, "squishywaf... at gmail.com"
>  wrote:
>> I'm not exactly sure what the term for this would be, but I was
>> wondering if there were any Python packages that supported some kind
>> of ad-hoc message broadcasting. What I'd like to do is something like
>> this:
>>
>> * On a number of workhorse machines, a process listens for network
>> messages from our broadcast service. It subscribes to a certain sub-
>> set of them and will only respond to the messaging events that it is
>> subscribed to.
>> * Any machine can broadcast a message out to the network of machines
>> without specifying an IP address.
>> * Machines can come and go. Since messages are not directly sent to a
>> specific IP address from our Python script, the messages are simply
>> broadcasted to those who are there to listen. If nobody is subscribed
>> to the message type being sent, nothing happens.
>>
>> I know XML-RPC and other friends are an option, but I'm looking for
>> something that doesn't require managing a set of IP addresses or
>> hostnames. I'm not sure what to Google for such a package/module, any
>> direction would be greatly appreciated.
>
> Offhand I'd suggest binding a specific UDP port on the listening
> workstations. Then the broadcasting workstation(s) could just pull a
> standard list of IP's based on its own subnet. Then there'd be no hard-
> coded machine names or IP addresses to manage. Just send the message
> to all hosts on the same subnet as the broadcaster(s). Plus the UDP
> connection would be stateless and not care if the receivers actually
> got the message or not...

You could use the socket module to broadcast.  Using INADDR_BROADCAST
as the destination should do it.  I fail to recollect whether that
will need root privileges...

-- 
kushal


From maximilianbianco at gmail.com  Tue Aug 11 15:01:00 2009
From: maximilianbianco at gmail.com (max bianco)
Date: Tue, 11 Aug 2009 15:01:00 -0400
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <0006817d$0$2895$c3e8da3@news.astraweb.com>
References: 
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com>
Message-ID: 

On Sat, Aug 8, 2009 at 12:25 AM, Steven
D'Aprano wrote:
> On Fri, 07 Aug 2009 13:35:26 -0700, Kee Nethery wrote:
>
>
>> > Why exactly is posting an open comment on a bug tracker somehow
>> > inferior to posting an open comment on a wiki?
>>
>> It's a good question and deserves a good answer.
>>
>> * Fewer Steps
>> * Immediate
>> * Does not need to be formally reviewed
>> * Easier to search
>
> The last one is actually wrong, because the Python bug tracker is indexed
> by Google.
>
> As for the rest, you're right that the current bug-tracker puts up
> barriers to people submitting comments and bugs. That's actually a good
> thing. The only thing worse than not enough information is too much
> information, and the current situation does a good job of discouraging
> the sorts of people who submit bad bug reports (e.g. duplicates of bug
> reports, bug reports for things fixed years ago, bug reports that are due
> to mistakes in their code, etc.).
>
>
>> For example
>> purposes, I'll use the following page:
>> http://docs.python.org/reference/lexical_analysis.html
>> Lets say the user is in section 2.1.3 Comments
>
> Disclaimer: python.org is down at the moment, so I can't check that page
> to see precisely what you're talking about.
>
>
>> Here's the scenario: The user wanted to include "#" in one of their
>> strings and the IDE kept interpreting it as a comment. But they really
>> need to use that character in the string. Eventually they find out that
>> they can escape the character in their string so that Python stops
>> thinking it is the beginning of a comment.
>
> Er, that would be a bug in the IDE, surely? Inside strings, # is an
> ordinary character with no special meaning.
>
>
>>>> s = "this is a string with an unescaped # in it"
>>>> s
> 'this is a string with an unescaped # in it'
>
>
> The Python docs are supposed to be about Python the language, not work-
> arounds for IDE bugs.
>
>
> [...]
>> Lets assume that Python experts all agree that
>> the docs should get updated with this gotcha (which as a newbie, they
>> are not sure that is a valid assumption and would probably just halt
>> in their quest to get the docs updated).
>
> Good.
>
> As a newbie, you SHOULD assume that anything you think is a bug is
> probably a bug in YOUR code, not Python, and the same goes for
> documentation bugs. If you don't understand something in the docs,
> chances are that it's a problem with you, not the docs. Your first port
> of call should be the tutor list, or here, and not to "fix" the docs by
> putting in noise that just gets in the way of the intended audience,
> namely experienced developers.
>
I assume I am misunderstanding you here and you meant something else?
Python is paraded as a good language for beginners. Is this a false
statement or a secondary objective? Or are the docs only meant for
experienced developers? That just doesn't sound right.


From invalid at invalid  Tue Aug 11 15:01:35 2009
From: invalid at invalid (Grant Edwards)
Date: Tue, 11 Aug 2009 14:01:35 -0500
Subject: Python docs disappointing - group effort to hire writers?
References:  
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	<4A80472E.4090108@stoneleaf.us>
	
	
	<63f2b657-c646-4a69-9a05-1da5975bb6d2@z31g2000yqd.googlegroups.com>
	<7xfxbynpxd.fsf@ruckus.brouhaha.com>
Message-ID: 

On 2009-08-11, Paul Rubin  wrote:
> r  writes:
>> Some say the tutorial is not meant for non-programmers, but for
>> programmers with no Python experience. So! How does that justify
>> obstruction of the tut? Why not present the same information in a way
>> both can easily understand? 
>
> I agree that a tutorial for non-programmers would be useful, but it's
> better to have it as a separate document.

There are plenty of docs aimed at non-programmers.  I've heard
this one recommended many times:

http://www.greenteapress.com/thinkpython/

-- 
Grant Edwards                   grante             Yow! Am I having fun yet?
                                  at               
                               visi.com            


From maximilianbianco at gmail.com  Tue Aug 11 15:03:09 2009
From: maximilianbianco at gmail.com (max bianco)
Date: Tue, 11 Aug 2009 15:03:09 -0400
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References:  
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
Message-ID: 

On Thu, Aug 6, 2009 at 2:36 PM, Kee Nethery wrote:
> As someone trying to learn the language I want to say that the tone on this
> list towards people who are trying to learn Python ?feels like it has become
> anti-newbies.
>
> Learning a new language is difficult enough without seeing other newbies
> getting shamed for not knowing everything there is to know about Python
> before asking their questions.

Well I have to say your right about the tone but using google before
you ask is not an unreasonable expectation. I have of course broken
this golden rule myself on mailing lists myself , however a response
like use google is totally acceptable to me.


From squishywaffle at gmail.com  Tue Aug 11 15:06:41 2009
From: squishywaffle at gmail.com (Greg Taylor)
Date: Tue, 11 Aug 2009 12:06:41 -0700 (PDT)
Subject: Networked Broadcast Messaging
References: <37ea826b-708d-48f4-a64a-42f58fec5325@c2g2000yqi.googlegroups.com>
	<889a2a1d-e791-479e-8e41-4387e1b258fd@z31g2000yqd.googlegroups.com> 
	
Message-ID: <4dc5c63e-55d6-4758-b2e6-f405571347df@g31g2000yqc.googlegroups.com>

On Aug 11, 3:00?pm, Kushal Kumaran 
wrote:
> You could use the socket module to broadcast. ?Using INADDR_BROADCAST
> as the destination should do it. ?I fail to recollect whether that
> will need root privileges...

Awesome, I think this is exactly what I'm looking for. Much
appreciated!

Greg


From invalid at invalid  Tue Aug 11 15:11:37 2009
From: invalid at invalid (Grant Edwards)
Date: Tue, 11 Aug 2009 14:11:37 -0500
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com>
	
Message-ID: 

On 2009-08-11, max bianco  wrote:

> I assume I am misunderstanding you here and you meant something else?
> Python is paraded as a good language for beginners.

I believe it is a good language for beginners.

> Is this a false statement or a secondary objective?

Objective of what?

> Or are the docs only meant for experienced developers?

Some are, some aren't.  The "standard" docs (most of the docs
you can reach directly from http://www.python.org/doc/ --
including the tutorial) aren't intended to teach somebody how
to program and assume the reader has a basic grounding in
programming and language theory.

There are plenty of books and tutorials that are aimed at
teaching programming and Python at the same time.  You can find
some of via the links listed under "Additional documentation"
at http://www.python.org/doc/ -- particularly here:

 http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

> That just doesn't sound right.

-- 
Grant Edwards                   grante             Yow! My mind is making
                                  at               ashtrays in Dayton ...
                               visi.com            


From dotancohen at gmail.com  Tue Aug 11 15:14:07 2009
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 11 Aug 2009 22:14:07 +0300
Subject: Scraping Wikipedia with Python
In-Reply-To: <6YidncRAiJ6SIxzXRVn_vwA@giganews.com>
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	
	<6YidncRAiJ6SIxzXRVn_vwA@giganews.com>
Message-ID: <880dece00908111214y5def00afqe1e8849edd73d7e7@mail.gmail.com>

> Try reading a little there! Starting there I went to
>
> http://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot
>
> where I found a section on existing bots, comments on how the "scraping"
> is not what you want, and even a Python section with a link to something
> labelled ?PyWikipediaBot...
>

Thanks. I read the first bit of that page, but did not finish it.
Grepping it for Python led to to what I need.

Sorry for the noise.


-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il


From dmitrey.kroshko at scipy.org  Tue Aug 11 15:15:13 2009
From: dmitrey.kroshko at scipy.org (dmitrey)
Date: Tue, 11 Aug 2009 12:15:13 -0700 (PDT)
Subject: for key, value in dict.() - how to get? (which func)
Message-ID: 

hi all,
which method should I use to get iterator over (key, value) pairs for
Python dict, Python v 2.6 and above?

Of course I could use

for key in myDict.keys():
    value = myDict.values()
    # do something with the pair key, value

but searching each time for the value take some cputime that is
serious for the task involved

IIRC in python 2.5 I have something like keyvalues(), but I don't see
something like that in current dir(myDict).

Thank you in advance, D.


From rami.chowdhury at gmail.com  Tue Aug 11 15:23:46 2009
From: rami.chowdhury at gmail.com (Rami Chowdhury)
Date: Tue, 11 Aug 2009 12:23:46 -0700
Subject: better way?
In-Reply-To: <78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
Message-ID: 

IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than  
MySQL...

On Tue, 11 Aug 2009 11:45:50 -0700, Pet  wrote:

> On 11 Aug., 20:39, Kushal Kumaran 
> wrote:
>> On Tue, Aug 11, 2009 at 10:03 PM, someone  
>> wrote:
>> > Hello,
>>
>> > I'd like to make insert into db if record not exist otherwise update.
>> > to save typing list of columns in both statements I do following
>>
>> > 
>>
>> > is there better or more readable way to do it?
>>
>> Well, mysql, in particular, offers an "on duplicate key update" clause
>> that you can take a look at. ?Don't know about about other databases.
>>
>> --
>> kushal
>
> Oh, forgotten to mention. It's PostGres



-- 
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)


From rami.chowdhury at gmail.com  Tue Aug 11 15:26:05 2009
From: rami.chowdhury at gmail.com (Rami Chowdhury)
Date: Tue, 11 Aug 2009 12:26:05 -0700
Subject: for key, value in dict.() - how to get? (which func)
In-Reply-To: 
References: 
Message-ID: 

Hi Dmitrey,

I think what you're looking for is myDict.items(), or myDict.iteritems().

Cheers,
Rami

On Tue, 11 Aug 2009 12:15:13 -0700, dmitrey   
wrote:

> hi all,
> which method should I use to get iterator over (key, value) pairs for
> Python dict, Python v 2.6 and above?
>
> Of course I could use
>
> for key in myDict.keys():
>     value = myDict.values()
>     # do something with the pair key, value
>
> but searching each time for the value take some cputime that is
> serious for the task involved
>
> IIRC in python 2.5 I have something like keyvalues(), but I don't see
> something like that in current dir(myDict).
>
> Thank you in advance, D.



-- 
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)


From ethan at stoneleaf.us  Tue Aug 11 15:30:00 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Tue, 11 Aug 2009 12:30:00 -0700
Subject: Programming by Contract
In-Reply-To: <4A7A15CD.9090306@stoneleaf.us>
References: <4A7A15CD.9090306@stoneleaf.us>
Message-ID: <4A81C6B8.7010605@stoneleaf.us>

Ethan Furman wrote:
> Greetings!
> 
> I have seen posts about the assert statement and PbC (or maybe it was 
> DbC), and I just took a very brief look at pycontract 
> (http://www.wayforward.net/pycontract/) and now I have at least one 
> question:  Is this basically another way of thinking about unit testing, 
> or is the idea of PbC more along the lines of *always* checking the 
> input/output of functions to ensure they are correct?  (*Contstant 
> vigilance!* as Prof Moody would say ;)
> 
> I know asserts can be turned off, so they obviously won't work for the 
> latter case, and having seen the sample of pycontract it seems it only 
> does its thing during debugging.
> 
> So is Design (Programming) by Contract a fancy way of saying "Document 
> your inputs/outputs!" or is there more to it?
> 
> ~Ethan~

Hmmm...

Well, from the (apparently) complete lack of interest, I shall take away 
the (better?) documentation ideas and unit testing ideas, and not worry 
about the rest.  :)

~Ethan~


From dmitrey.kroshko at scipy.org  Tue Aug 11 15:31:27 2009
From: dmitrey.kroshko at scipy.org (dmitrey)
Date: Tue, 11 Aug 2009 12:31:27 -0700 (PDT)
Subject: for key, value in dict.() - how to get? (which func)
References: 
	
Message-ID: 

Yes, thank you, items() is the correct approach, on the other hand I
have already get rid of the cycle.
Regards, D.

On Aug 11, 10:26?pm, "Rami Chowdhury" 
wrote:
> Hi Dmitrey,
>
> I think what you're looking for is myDict.items(), or myDict.iteritems().
>
> Cheers,
> Rami
>
> On Tue, 11 Aug 2009 12:15:13 -0700, dmitrey  ?
> wrote:
>
>
>
> > hi all,
> > which method should I use to get iterator over (key, value) pairs for
> > Python dict, Python v 2.6 and above?
>
> > Of course I could use
>
> > for key in myDict.keys():
> > ? ? value = myDict.values()
> > ? ? # do something with the pair key, value
>
> > but searching each time for the value take some cputime that is
> > serious for the task involved
>
> > IIRC in python 2.5 I have something like keyvalues(), but I don't see
> > something like that in current dir(myDict).
>
> > Thank you in advance, D.
>
> --
> Rami Chowdhury
> "Never attribute to malice that which can be attributed to stupidity" -- ?
> Hanlon's Razor
> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)



From Brian.Mingus at colorado.edu  Tue Aug 11 15:39:50 2009
From: Brian.Mingus at colorado.edu (Brian)
Date: Tue, 11 Aug 2009 13:39:50 -0600
Subject: Scraping Wikipedia with Python
In-Reply-To: <880dece00908111129k525a0614td4c59a7a9371a7ba@mail.gmail.com>
References:  
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	<880dece00908111129k525a0614td4c59a7a9371a7ba@mail.gmail.com>
Message-ID: <9839a05c0908111239w64e507beud9492d58dee8f0a5@mail.gmail.com>

On Tue, Aug 11, 2009 at 12:29 PM, Dotan Cohen  wrote:

> >    Wikipedia has an API for computer access.  See
> >
> >        http://www.mediawiki.org/wiki/API
> >
>
> Yes, I am aware of this as well. Does anyone know of a python class
> for easily interacting with it, or do I need to roll my own.
>
> --
> Dotan Cohen
>

https://mwclient.svn.sourceforge.net/svnroot/mwclient/trunk/mwclient/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From petshmidt at googlemail.com  Tue Aug 11 15:40:22 2009
From: petshmidt at googlemail.com (Pet)
Date: Tue, 11 Aug 2009 12:40:22 -0700 (PDT)
Subject: better way?
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
Message-ID: <7b9a2a26-3b6a-48b9-bb63-da05e24c9b39@c1g2000yqi.googlegroups.com>

On 11 Aug., 21:23, "Rami Chowdhury"  wrote:
> IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than ?
> MySQL...
>

Ok, I've completely failed here :)

Thanks, man

>
>
>
>
> On Tue, 11 Aug 2009 11:45:50 -0700, Pet  wrote:
> > On 11 Aug., 20:39, Kushal Kumaran 
> > wrote:
> >> On Tue, Aug 11, 2009 at 10:03 PM, someone ?
> >> wrote:
> >> > Hello,
>
> >> > I'd like to make insert into db if record not exist otherwise update.
> >> > to save typing list of columns in both statements I do following
>
> >> > 
>
> >> > is there better or more readable way to do it?
>
> >> Well, mysql, in particular, offers an "on duplicate key update" clause
> >> that you can take a look at. ?Don't know about about other databases.
>
> >> --
> >> kushal
>
> > Oh, forgotten to mention. It's PostGres
>
> --
> Rami Chowdhury
> "Never attribute to malice that which can be attributed to stupidity" -- ?
> Hanlon's Razor
> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)



From mgi820 at motorola.com  Tue Aug 11 15:44:49 2009
From: mgi820 at motorola.com (Gary Duzan)
Date: Tue, 11 Aug 2009 19:44:49 +0000 (UTC)
Subject: for key, value in dict.() - how to get? (which func)
References: 
Message-ID: 

In article ,
dmitrey   wrote:
>hi all,
>which method should I use to get iterator over (key, value) pairs for
>Python dict, Python v 2.6 and above?

   dict.iteritems()

>>> import sys
>>> for (key, value) in sys.modules.iteritems(): print key, value

					Gary Duzan
					Motorola H&NM




From pacificik at warnell.uga.edu  Tue Aug 11 15:47:47 2009
From: pacificik at warnell.uga.edu (Krishna Pacifici)
Date: Tue, 11 Aug 2009 15:47:47 -0400
Subject: adding multiple new values to the same key in a dictionary
Message-ID: <4A8192A30200008C00014AB9@redhorse.forestry.uga.edu>

Hi,
I want to be able to add multiple new values to a key in a dictionary.

I have tried the following:

sec_dict_clean=
{88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85]}

for i in range(len(sec_dict_clean.values())):
    for j in range(len(sec_dict_clean.values()[i])):
        sec_dict_clean.setdefault(key,[]).append(blocks[sec_dict_clean.values()[i][j]].abundance)

where blocks[...].abundance gives me a single value from an object,

but this gives me the following:

sec_dict_clean=
{88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85, 4, 12, 11, 6, 9, 12, 11, 7, 10, 10, 12, 9, 6, 12, 15, 9, 8, 12, 15, 12, 12]}

instead I want each abundance (starts with 4, 12...) to be associated with each of the values so that it would look like this:

sec_dict_clean=
{88: ([87, 89, 78, 98], [4,12,11,6]), 58: ([57, 59, 48, 68], [9,12,11,7]), 69: ([79], [10])...}

You can see there are several errors here (I have more things being appended than there are values in the dictionary), but I really just want to know how to add multiple values to the same key in a dictionary.

Thanks for any help,
Krishna


-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rt8396 at gmail.com  Tue Aug 11 15:55:27 2009
From: rt8396 at gmail.com (r)
Date: Tue, 11 Aug 2009 12:55:27 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com> 
	
	
Message-ID: <6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com>

Ok people follow me here. Open your winders help file and click the
"Tutorial" link. What is this FLUFF doing here!?!?! Where is the damn
index? Where is the damn tutorial? I want to learn Python not read the
HISTORY OF THE WORLD.

Upon clicking the "Tutorial" link pre 2.6, a nice menu was placed
before your eyes, WHERE IS IT!?!??? Good thing i know the language or
i would have given up already!!!!


From rcdailey at gmail.com  Tue Aug 11 16:08:19 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Tue, 11 Aug 2009 13:08:19 -0700 (PDT)
Subject: Need cleanup advice for multiline string
Message-ID: 

Hey guys. Being a C++ programmer, I like to keep variable definitions
close to the location in which they will be used. This improves
readability in many ways. However, when I have a multi-line string
definition at function level scope, things get tricky because of the
indents. In this case indents are serving two purposes: For syntax and
actual text output. The tabs for function scope should not be included
in the contents of the string. Below is the code I am trying to
improve. Notice how it looks ugly/unreadable because of the way the
string contents are shifted all the way to the left edge of the
document. This breaks the flow of scope. Would you guys solve this
problem by moving failMsg into global scope? Perhaps through some
other type of syntax?

Help is appreciated!

def RunCommand( commandList ):
   commandString =
   print( 'Running Command:',  )
   cmd = subprocess.Popen( commandList )
   returnCode = cmd.wait()
   if returnCode:
      failMsg = '''\
*************************************************
The following command returned exit code [{:#x}].
This represents failure of some form. Please review
the command output for more details on the issue.
------------
{}
*************************************************
'''
      commandString = ' '.join( commandList )
      raise CommandFailure( failMsg.format( returnCode,
commandString ) )


From matthew at woodcraft.me.uk  Tue Aug 11 16:10:03 2009
From: matthew at woodcraft.me.uk (Matthew Woodcraft)
Date: Tue, 11 Aug 2009 20:10:03 GMT
Subject: better way?
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
Message-ID: <87skfyjen8.fsf@golux.woodcraft.me.uk>

"Rami Chowdhury"  writes:

> IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than
> MySQL...

PostgreSQL does not have ON DUPLICATE KEY UPDATE.

The SQL standard way to do what the OP wants is MERGE. PostgreSQL
doesn't have that either.

-M-


From breamoreboy at yahoo.co.uk  Tue Aug 11 16:12:29 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 21:12:29 +0100
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com>
References: 	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>	<7xab2c52y6.fsf@ruckus.brouhaha.com>	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>	<7xk51fgazf.fsf@ruckus.brouhaha.com>					<0006817d$0$2895$c3e8da3@news.astraweb.com>
		
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com>
Message-ID: 

r wrote:
> Ok people follow me here. Open your winders help file and click the
> "Tutorial" link. What is this FLUFF doing here!?!?! Where is the damn
> index? Where is the damn tutorial? I want to learn Python not read the
> HISTORY OF THE WORLD.
> 
> Upon clicking the "Tutorial" link pre 2.6, a nice menu was placed
> before your eyes, WHERE IS IT!?!??? Good thing i know the language or
> i would have given up already!!!!
As I keep on repeating, my version works perfectly.  Perhaps this is 
because I have a computing IQ of approximately 2**32, so realised that 
something was wrong, went here and downloaded the corrected version of 
the file, which has presumably been available for months!!!!!

http://www.python.org/download/releases/2.6.2/

And you want newbies let loose on the python docs.  As good ole Santa 
would say, ho, ho, ho!
-- 
Kindest regards.

Mark Lawrence.



From rcdailey at gmail.com  Tue Aug 11 16:16:58 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Tue, 11 Aug 2009 13:16:58 -0700 (PDT)
Subject: Need cleanup advice for multiline string
References: 
Message-ID: <30eb6e66-1d5c-4a76-b80d-54d11bafbdb3@h31g2000yqd.googlegroups.com>

On Aug 11, 3:08?pm, Robert Dailey  wrote:
> Hey guys. Being a C++ programmer, I like to keep variable definitions
> close to the location in which they will be used. This improves
> readability in many ways. However, when I have a multi-line string
> definition at function level scope, things get tricky because of the
> indents. In this case indents are serving two purposes: For syntax and
> actual text output. The tabs for function scope should not be included
> in the contents of the string. Below is the code I am trying to
> improve. Notice how it looks ugly/unreadable because of the way the
> string contents are shifted all the way to the left edge of the
> document. This breaks the flow of scope. Would you guys solve this
> problem by moving failMsg into global scope? Perhaps through some
> other type of syntax?
>
> Help is appreciated!
>
> def RunCommand( commandList ):
> ? ?commandString =
> ? ?print( 'Running Command:', ?)
> ? ?cmd = subprocess.Popen( commandList )
> ? ?returnCode = cmd.wait()
> ? ?if returnCode:
> ? ? ? failMsg = '''\
> *************************************************
> The following command returned exit code [{:#x}].
> This represents failure of some form. Please review
> the command output for more details on the issue.
> ------------
> {}
> *************************************************
> '''
> ? ? ? commandString = ' '.join( commandList )
> ? ? ? raise CommandFailure( failMsg.format( returnCode,
> commandString ) )

And yes, I recognize there are syntax errors. Ignore those for now.


From rami.chowdhury at gmail.com  Tue Aug 11 16:19:00 2009
From: rami.chowdhury at gmail.com (Rami Chowdhury)
Date: Tue, 11 Aug 2009 13:19:00 -0700
Subject: better way?
In-Reply-To: <87skfyjen8.fsf@golux.woodcraft.me.uk>
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
	<87skfyjen8.fsf@golux.woodcraft.me.uk>
Message-ID: 

Ah, my apologies, I must have been getting it confused with ON UPDATE  
[things]. Thanks for correcting me.

On Tue, 11 Aug 2009 13:10:03 -0700, Matthew Woodcraft  
 wrote:

> "Rami Chowdhury"  writes:
>
>> IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than
>> MySQL...
>
> PostgreSQL does not have ON DUPLICATE KEY UPDATE.
>
> The SQL standard way to do what the OP wants is MERGE. PostgreSQL
> doesn't have that either.
>
> -M-



-- 
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)


From cmalmqui at gmail.com  Tue Aug 11 16:20:35 2009
From: cmalmqui at gmail.com (cmalmqui)
Date: Tue, 11 Aug 2009 13:20:35 -0700 (PDT)
Subject: ElementTree - Howto access text within XML tag element...
References: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
	<7ecm77F2fbf71U1@mid.uni-berlin.de>
Message-ID: 

On Aug 11, 9:51?am, "Diez B. Roggisch"  wrote:
> cmalmqui schrieb:
> > Hi,
>
> > I am writing on a small XML parser and are currently stuck as I am not
> > able to get the whole element name in ElementTree.
>
> > Please see the below example where "print root[0][0]" returns
> > ""
>
> > Is there a way to get hold of the "Running" string in the tag using
> > elementTree?
>
> > 
> > ? ? 
> > ? ? ? 2009-07-10T14:48:00Z
> > ? ? ? 
> > ? ? ? .........
>
> > For those of you that know how to program XML I have another
> > question:
> > I am currently "hardcoding" my XML parser using brackets, is this a
> > good approach or should I build it using a "search on tag" approach.
>
> What do you mean by that - hardcoding by brackets?
>
> Diez

Indeed, my current approach has been to hardcode the XML parser using
brackets. Is there a more elegant way?

I am parsing a garmin xml file from a handheld GPS and as you can see
in the below script, I am hardcoding each node:

import xml.etree.cElementTree as etree

def gettext(elem):
    text = elem.text or ""
    for e in elem:
        text += gettext(e)
        if e.tail:
            text += e.tail
    return text

tree = etree.parse('10_07_2009 16_48_00_history.tcx')
root = tree.getroot()

elem = root[0][0]

# ID Tag
print "type of exercise    : " + elem.get("Sport")
print "excercise starttime : " + gettext(elem[0])

# iterate over all laps
for i in range(1, len(elem)-1):

    # LAP TAG
    print "\nlap number          : " + str(i)
    print "lap start time      : " + str(elem[i].get("StartTime"))
    print "lap duration (s)    : " + gettext(elem[i][0])
    print "lap length (m)      : " + gettext(elem[i][1])
    print "max speed (km/h)    : " + gettext(elem[i][2])
    print "number of calories  : " + gettext(elem[i][3])
    print "average heartbeat   : " + gettext(elem[i][4][0])
    print "max     heartbeat   : " + gettext(elem[i][5][0])
    print "number of records   : " + str(len(elem[i][8])-1)
    for j in range(1, len(elem[i][8])-1):
        time = gettext(elem[i][8][j][0])    #time
        lat  = gettext(elem[i][8][j][1][0]) #lat
        lon  = gettext(elem[i][8][j][1][1]) #lon
        alt  = gettext(elem[i][8][j][2])    #alt
        dist = gettext(elem[i][8][j][3])    #distance from start
        bpm  = gettext(elem[i][8][j][4][0]) #beats per minute
        #print time + " " + lat + " " + lon + " " + alt + " " + dist +
" " + bpm

print "\nReceiver Info       : " + gettext(elem[len(elem)-1][0])


From darkwater42 at gmail.com  Tue Aug 11 16:20:52 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Tue, 11 Aug 2009 13:20:52 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
	 
	<0291a21a$0$20639$c3e8da3@news.astraweb.com>
Message-ID: <8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com>

On Aug 11, 2:00?pm, Steven D'Aprano  wrote:

> > test.cpp:1:1: warning: unknown escape sequence '\y'
>
> Isn't that a warning, not a fatal error? So what does temp contain?

My "Annotated C++ Reference Manual" is packed, and surprisingly in
Stroustrup's Third Edition, there is no mention of the issue in the
entire 1,000 pages. But Microsoft to the rescue:

     If you want a backslash character to appear within a string,
     you must type two backslashes (\\)

(From http://msdn.microsoft.com/en-us/library/69ze775t.aspx)

The question of what any specific C++ does if you ignore the warning
is irrelevant, as such behavior in C++ is almost *always* undefined.
Hence the warning.

|>ouglas


From cmalmqui at gmail.com  Tue Aug 11 16:21:20 2009
From: cmalmqui at gmail.com (cmalmqui)
Date: Tue, 11 Aug 2009 13:21:20 -0700 (PDT)
Subject: ElementTree - Howto access text within XML tag element...
References: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
	
Message-ID: <512cde86-d758-48b7-b474-eac48ef56c54@26g2000yqk.googlegroups.com>

On Aug 11, 9:13?am, Ned Deily  wrote:
> In article
> <1ad8dac1-8fff-493a-a197-d847e7b6a... at c2g2000yqi.googlegroups.com>,
>
> ?cmalmqui  wrote:
> > I am writing on a small XML parser and are currently stuck as I am not
> > able to get the whole element name in ElementTree.
>
> > Please see the below example where "print root[0][0]" returns
> > ""
>
> > Is there a way to get hold of the "Running" string in the tag using
> > elementTree?
>
> > 
> > ? ? 
> > ? ? ? 2009-07-10T14:48:00Z
> > ? ? ? 
> > ? ? ? .........
>
> "Running" is the value of the "Sport" attribute of the "Activity"
> element. ?The documentation for the Element interface lists several ways
> to access element attributes; in your example,
>
> >>> elem = root[0][0]
> >>> elem.get("Sport")
> 'Running'
> >>> elem.attrib
>
> {'Sport': 'Running'}>>> elem.items()
>
> [('Sport', 'Running')]
>
> Seehttp://docs.python.org/library/xml.etree.elementtree.html
>
> --
> ?Ned Deily,
> ?n... at acm.org

Excellent!
Thanks!
The XML magic is getting there slowly...


From chris at simplistix.co.uk  Tue Aug 11 16:25:47 2009
From: chris at simplistix.co.uk (Chris Withers)
Date: Tue, 11 Aug 2009 21:25:47 +0100
Subject: httplib incredibly slow :-(
Message-ID: <4A81D3CB.7080209@simplistix.co.uk>

Hi All,

I'm using the following script to download a 150Mb file:

from base64 import encodestring
from httplib import HTTPConnection
from datetime import datetime

conn = HTTPSConnection('localhost')
headers = {}
auth = 'Basic '+encodestring('username:password').strip()
headers['Authorization']=auth
t = datetime.now()
print t
conn.request('GET','/somefile.zip',None,headers)
print 'request:',datetime.now()-t
response = conn.getresponse()
print 'response:',datetime.now()-t
data = response.read()
print 'read:',datetime.now()-t

The output shows it takes over 20 minutes to do this.
However, this is on a local network, and downloading the same file in IE 
takes under 3 seconds!

I saw this issue:

http://bugs.python.org/issue2576

I tried changing the buffer size to 4096 in a subclass as the issue 
suggested, but I didn't see the reported speed improvement.
I'm using Python 2.6.2.

Does anyone know of an alternative library for creating http requests 
and getting their responses that's faster but hopefully has a similar 
interface?

Chris

-- 
Simplistix - Content Management, Batch Processing & Python Consulting
            - http://www.simplistix.co.uk


From rcdailey at gmail.com  Tue Aug 11 16:28:57 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Tue, 11 Aug 2009 13:28:57 -0700 (PDT)
Subject: Bug in format specification in Python 3?
Message-ID: 

Hello,

According to the Python 3.1 documentation, I can have a format
specification like so:

print( 'This is a hex number: {:#08x}'.format( 4 ) )

This will print:

This is a hex number: 0x000004

I notice that the '0x' portion is counted in the width, which was
specified as 8. This seems wrong to me. Is this by design? If so, why?
I expect that the width portion to only apply to the input + padding
only. I don't consider the '0x' portion part of the padding. But maybe
it is...


From http  Tue Aug 11 16:31:34 2009
From: http (Paul Rubin)
Date: 11 Aug 2009 13:31:34 -0700
Subject: Scraping Wikipedia with Python
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	
	<6YidncRAiJ6SIxzXRVn_vwA@giganews.com>
	
Message-ID: <7xd472hz2x.fsf@ruckus.brouhaha.com>

Dotan Cohen  writes:
> Thanks. I read the first bit of that page, but did not finish it.
> Grepping it for Python led to to what I need.

maybe you want dbpedia.


From breamoreboy at yahoo.co.uk  Tue Aug 11 16:32:56 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 21:32:56 +0100
Subject: Need cleanup advice for multiline string
In-Reply-To: <30eb6e66-1d5c-4a76-b80d-54d11bafbdb3@h31g2000yqd.googlegroups.com>
References: 
	<30eb6e66-1d5c-4a76-b80d-54d11bafbdb3@h31g2000yqd.googlegroups.com>
Message-ID: 

Robert Dailey wrote:
> On Aug 11, 3:08 pm, Robert Dailey  wrote:
>> Hey guys. Being a C++ programmer, I like to keep variable definitions
>> close to the location in which they will be used. This improves
>> readability in many ways. However, when I have a multi-line string
>> definition at function level scope, things get tricky because of the
>> indents. In this case indents are serving two purposes: For syntax and
>> actual text output. The tabs for function scope should not be included
>> in the contents of the string. Below is the code I am trying to
>> improve. Notice how it looks ugly/unreadable because of the way the
>> string contents are shifted all the way to the left edge of the
>> document. This breaks the flow of scope. Would you guys solve this
>> problem by moving failMsg into global scope? Perhaps through some
>> other type of syntax?
>>
>> Help is appreciated!
>>
>> def RunCommand( commandList ):
>>    commandString =
>>    print( 'Running Command:',  )
>>    cmd = subprocess.Popen( commandList )
>>    returnCode = cmd.wait()
>>    if returnCode:
>>       failMsg = '''\
>> *************************************************
>> The following command returned exit code [{:#x}].
>> This represents failure of some form. Please review
>> the command output for more details on the issue.
>> ------------
>> {}
>> *************************************************
>> '''
>>       commandString = ' '.join( commandList )
>>       raise CommandFailure( failMsg.format( returnCode,
>> commandString ) )
> 
> And yes, I recognize there are syntax errors. Ignore those for now.
For starters take a look at http://tinyurl.com/o2o8r8 , just about every 
combination of string concatenation going there.  I assume that one of 
these will let you leave failMsg where it belongs.

-- 
Kindest regards.

Mark Lawrence.



From rt8396 at gmail.com  Tue Aug 11 16:36:18 2009
From: rt8396 at gmail.com (r)
Date: Tue, 11 Aug 2009 13:36:18 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com> 
	
	 
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com> 
	
Message-ID: <875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>

Ah Ha! the docs are broken and i was right all along! Are the good
folks at Python dev rolling a new installer as we speak, or we must
wait for new version?


From ethan at stoneleaf.us  Tue Aug 11 16:38:37 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Tue, 11 Aug 2009 13:38:37 -0700
Subject: Unrecognized escape sequences in string literals
In-Reply-To: <8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com>
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>			<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>		<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>		
	<0291a21a$0$20639$c3e8da3@news.astraweb.com>
	<8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com>
Message-ID: <4A81D6CD.1060903@stoneleaf.us>

Douglas Alan wrote:
> On Aug 11, 2:00 pm, Steven D'Aprano  cybersource.com.au> wrote:
> 
> 
>>>test.cpp:1:1: warning: unknown escape sequence '\y'
>>
>>Isn't that a warning, not a fatal error? So what does temp contain?
> 
> 
> My "Annotated C++ Reference Manual" is packed, and surprisingly in
> Stroustrup's Third Edition, there is no mention of the issue in the
> entire 1,000 pages. But Microsoft to the rescue:
> 
>      If you want a backslash character to appear within a string,
>      you must type two backslashes (\\)
> 
> (From http://msdn.microsoft.com/en-us/library/69ze775t.aspx)
> 
> The question of what any specific C++ does if you ignore the warning
> is irrelevant, as such behavior in C++ is almost *always* undefined.
> Hence the warning.
> 
> |>ouglas

Almost always undefined?  Whereas with Python, and some memorization or 
a small table/list nearby, you can easily *know* what you will get.

Mind you, I'm not really vested in how Python *should* handle 
backslashes one way or the other, but I am glad it has rules that it 
follows for consitent results, and I don't have to break out a byte-code 
editor to find out what's in my string literal.

~Ethan~


From bearophileHUGS at lycos.com  Tue Aug 11 16:40:24 2009
From: bearophileHUGS at lycos.com (Bearophile)
Date: Tue, 11 Aug 2009 13:40:24 -0700 (PDT)
Subject: Need cleanup advice for multiline string
References: 
Message-ID: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>

Robert Dailey:
> This breaks the flow of scope. Would you guys solve this
> problem by moving failMsg into global scope?
> Perhaps through some other type of syntax?

There are gals too here.
This may help:
http://docs.python.org/library/textwrap.html#textwrap.dedent

Bye,
bearophile


From breamoreboy at yahoo.co.uk  Tue Aug 11 16:46:12 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 21:46:12 +0100
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>
References: 	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>	<7xab2c52y6.fsf@ruckus.brouhaha.com>	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>	<7xk51fgazf.fsf@ruckus.brouhaha.com>					<0006817d$0$2895$c3e8da3@news.astraweb.com>
		
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com>
	
	<875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>
Message-ID: 

r wrote:
> Ah Ha! the docs are broken and i was right all along! Are the good
> folks at Python dev rolling a new installer as we speak, or we must
> wait for new version?
As I pointed out a few minutes ago thicko, the new version has been 
available for months.

-- 
Kindest regards.

Mark Lawrence.



From rays at blue-cove.com  Tue Aug 11 16:52:04 2009
From: rays at blue-cove.com (RJ)
Date: Tue, 11 Aug 2009 13:52:04 -0700
Subject: New 2.6 and wx install => DLL load failed: The specified
	procedure could not be found
Message-ID: <6.2.3.4.2.20090811134337.04a210d8@blue-cove.com>

I just installed python-2.6.2.msi from Python.org and 
wxPython2.8-win32-ansi-2.8.10.1-py26.exe and now can't import this 
wx. (I had 2.4, but uninstalled)
This reminds me of a basic question I had before: what are the 
compilers used for the Win32 binaries? Is this a compiler 
compatibility issue? a wx bug?

C:\projects>python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> import wx
Traceback (most recent call last):
   File "", line 1, in 
   File 
"C:\Python26\lib\site-packages\wx-2.8-msw-ansi\wx\__init__.py", line 45,
in 
     from wx._core import *
   File "C:\Python26\lib\site-packages\wx-2.8-msw-ansi\wx\_core.py", 
line 4, in <
module>
     import _core_
ImportError: DLL load failed: The specified procedure could not be found.
 >>> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rcdailey at gmail.com  Tue Aug 11 16:52:34 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Tue, 11 Aug 2009 13:52:34 -0700 (PDT)
Subject: Need cleanup advice for multiline string
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>
Message-ID: <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>

On Aug 11, 3:40?pm, Bearophile  wrote:
> Robert Dailey:
>
> > This breaks the flow of scope. Would you guys solve this
> > problem by moving failMsg into global scope?
> > Perhaps through some other type of syntax?
>
> There are gals too here.
> This may help:http://docs.python.org/library/textwrap.html#textwrap.dedent
>
> Bye,
> bearophile

It's a figure of speech. And besides, why would I want programming
advice from a woman? lol. Thanks for the help.


From charles at declareSub.com  Tue Aug 11 16:53:41 2009
From: charles at declareSub.com (Charles Yeomans)
Date: Tue, 11 Aug 2009 16:53:41 -0400
Subject: Programming by Contract
In-Reply-To: <4A81C6B8.7010605@stoneleaf.us>
References: <4A7A15CD.9090306@stoneleaf.us> <4A81C6B8.7010605@stoneleaf.us>
Message-ID: <18F0FD2E-7C01-4B1C-85DF-28433C23D886@declareSub.com>


On Aug 11, 2009, at 3:30 PM, Ethan Furman wrote:

> Ethan Furman wrote:
>> Greetings!
>> I have seen posts about the assert statement and PbC (or maybe it  
>> was DbC), and I just took a very brief look at pycontract (http://www.wayforward.net/pycontract/ 
>> ) and now I have at least one question:  Is this basically another  
>> way of thinking about unit testing, or is the idea of PbC more  
>> along the lines of *always* checking the input/output of functions  
>> to ensure they are correct?  (*Contstant vigilance!* as Prof Moody  
>> would say ;)
>> I know asserts can be turned off, so they obviously won't work for  
>> the latter case, and having seen the sample of pycontract it seems  
>> it only does its thing during debugging.
>> So is Design (Programming) by Contract a fancy way of saying  
>> "Document your inputs/outputs!" or is there more to it?
>> ~Ethan~
>
> Hmmm...
>
> Well, from the (apparently) complete lack of interest, I shall take  
> away the (better?) documentation ideas and unit testing ideas, and  
> not worry about the rest.  :)
>
>




Design by contract is complementary to unit testing (I notice that the  
author of PEP 316 appears confused about this).  DbC is, roughly  
speaking, about explicit allocation of responsibility.  Consider this  
contrived example.

def foo(s):
     require(s is not None)
     //code
     ensure(hasattr(returnValue, '__iter__'))


The require condition tells you that it's the caller's responsibility  
to pass a non-nil argument to foo.  The ensure condition is a  
guarantee that foo will return something suitable for iteration, if  
the precondition in the require condition is satisfied.  These  
conditions can be enforced at runtime, but may not be, for reasons of  
performance.

DbC is in fact about not *always* checking the input/output of  
functions; on the contrary, Bertrand Meyer, the inventor of DbC,  
claims that DbC allows one to eliminate such redundancy, and the  
resulting overhead.

Charles Yeomans


From python at mrabarnett.plus.com  Tue Aug 11 17:04:43 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Tue, 11 Aug 2009 22:04:43 +0100
Subject: Bug in format specification in Python 3?
In-Reply-To: 
References: 
Message-ID: <4A81DCEB.8020805@mrabarnett.plus.com>

Robert Dailey wrote:
> Hello,
> 
> According to the Python 3.1 documentation, I can have a format
> specification like so:
> 
> print( 'This is a hex number: {:#08x}'.format( 4 ) )
> 
> This will print:
> 
> This is a hex number: 0x000004
> 
> I notice that the '0x' portion is counted in the width, which was
> specified as 8. This seems wrong to me. Is this by design? If so, why?
> I expect that the width portion to only apply to the input + padding
> only. I don't consider the '0x' portion part of the padding. But maybe
> it is...

The width portion is the width of what is produced by the specification.
The '#' tells it to add '0x', so that's part of what's produced. If you
don't want the '0x' to be counted then don't include '#' in the
specification. It makes perfect sense! :-)


From python at mrabarnett.plus.com  Tue Aug 11 17:11:57 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Tue, 11 Aug 2009 22:11:57 +0100
Subject: dictionary help
In-Reply-To: <4A816A400200008C00014A70@redhorse.forestry.uga.edu>
References: <4A816A400200008C00014A70@redhorse.forestry.uga.edu>
Message-ID: <4A81DE9D.1000505@mrabarnett.plus.com>

Krishna Pacifici wrote:
> Wow, thanks MRAB and Simon, you guys are good.
> 
> I guess I will go ahead and ask the next question that has also stumped 
> me for awhile now.
> 
> So basically I need to loop through the values in the new dictionary and 
> append attributes of a class object.  Each of the values (and keys) 
> represent a block in a grid with a specific location (e.g. 35 is the 
> block in row 3 col 5) and each block is an object with several 
> attributes associated with it.  I want to call that block and append two 
> separate attributes to the dictionary within that same key.
> 
> So again it would look something like this:
> 
> block 35 has 2 attributes, say a and b, a=2, b=5
> block 37 has a=1, b=3
> block 46 has a=3, b=8
> 
> the two attributes come from two different definitions within the class 
> statement,
> def detections
> ...
> return a
> 
> def abundance
> ...
> return b
> 
> so I would want to append to key 36 those two attributes for each block 
> so that the resulting dictionary item would look like this:
>                          a           b  
> {36:[35,37,46], [2,1,3], [5,3,8] ...}
> 
That doesn't look like a dictionary. Perhaps want you want is for the
value to be a list of lists:

     {36: [[35,37,46], [2,1,3], [5,3,8]] ...}

although you'd have parallel lists, ie a list of blocks, a list of 'a',
and a list of 'b'. A better format might be to keep a block's attributes
with the block itself.

     {36: [[35,2,5], [37,1,3], [46,3,8]] ...}

> Any help with this would be greatly appreciated.  And thank you so much 
> for all of your help thus far, I'm still pretty new to python and am 
> enjoying all of the flexibility associated with a scripting and 
> programming language.
> 
[snip]



From guthrie at mum.edu  Tue Aug 11 17:12:01 2009
From: guthrie at mum.edu (guthrie)
Date: Tue, 11 Aug 2009 14:12:01 -0700 (PDT)
Subject: run all scripts in sub-directory as subroutines?
Message-ID: 

I want to have a program which will form a list of all *.py scripts in
a sub-directory, and then call some standard messages on them. So I
can add a new data source modularly by just dropping a new file into
the sources directory with the appropriate methods in it.

For example:

path = sys.path[0]
print "Starting Directory:: " + path

getDir=path + "\Sources"            # point to directory of data
sources
for name in os.listdir(getDir):     # run collection from each source
    src = imp.load_source("data",getDir,open(getDir+"\\"+name, 'rb'))
    src.getData()
    src.doGraph()

This works fine, but in the sub-modules the sys.path appropriately
returns the same as from the parent, I want them to know their own
file names. How?? I can pass it to them, but wondered if there is a
more self-sufficient way for a module to know from where it was
invoked.


From ethan at stoneleaf.us  Tue Aug 11 17:20:18 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Tue, 11 Aug 2009 14:20:18 -0700
Subject: Programming by Contract
In-Reply-To: <18F0FD2E-7C01-4B1C-85DF-28433C23D886@declareSub.com>
References: <4A7A15CD.9090306@stoneleaf.us> <4A81C6B8.7010605@stoneleaf.us>
	<18F0FD2E-7C01-4B1C-85DF-28433C23D886@declareSub.com>
Message-ID: <4A81E092.1070303@stoneleaf.us>

Charles Yeomans wrote:
> 
> On Aug 11, 2009, at 3:30 PM, Ethan Furman wrote:
> 
>> Ethan Furman wrote:
>>
>>> Greetings!
>>> I have seen posts about the assert statement and PbC (or maybe it  
>>> was DbC), and I just took a very brief look at pycontract 
>>> (http://www.wayforward.net/pycontract/ ) and now I have at least one 
>>> question:  Is this basically another  way of thinking about unit 
>>> testing, or is the idea of PbC more  along the lines of *always* 
>>> checking the input/output of functions  to ensure they are correct?  
>>> (*Contstant vigilance!* as Prof Moody  would say ;)
>>> I know asserts can be turned off, so they obviously won't work for  
>>> the latter case, and having seen the sample of pycontract it seems  
>>> it only does its thing during debugging.
>>> So is Design (Programming) by Contract a fancy way of saying  
>>> "Document your inputs/outputs!" or is there more to it?
>>> ~Ethan~
>>
>>
>> Hmmm...
>>
>> Well, from the (apparently) complete lack of interest, I shall take  
>> away the (better?) documentation ideas and unit testing ideas, and  
>> not worry about the rest.  :)
>>
>>
> 
> 
> 
> 
> Design by contract is complementary to unit testing (I notice that the  
> author of PEP 316 appears confused about this).  DbC is, roughly  
> speaking, about explicit allocation of responsibility.  Consider this  
> contrived example.
> 
> def foo(s):
>     require(s is not None)
>     //code
>     ensure(hasattr(returnValue, '__iter__'))
> 
> 
> The require condition tells you that it's the caller's responsibility  
> to pass a non-nil argument to foo.  The ensure condition is a  guarantee 
> that foo will return something suitable for iteration, if  the 
> precondition in the require condition is satisfied.  These  conditions 
> can be enforced at runtime, but may not be, for reasons of  performance.
> 
> DbC is in fact about not *always* checking the input/output of  
> functions; on the contrary, Bertrand Meyer, the inventor of DbC,  claims 
> that DbC allows one to eliminate such redundancy, and the  resulting 
> overhead.
> 
> Charles Yeomans

Many thanks!

So if I understand -- Python's EAFP fits well with DbC, as DbC seems 
well suited to say, "This is your responsibility, and this is mine," 
stated in programming terms (who needs comments? ;)  Combined with unit 
testing (which should be easier to design correctly given the DbC code), 
healthy code seems more attainable.

Interesting.  Thank you for the information.

~Ethan~


From darkwater42 at gmail.com  Tue Aug 11 17:29:43 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Tue, 11 Aug 2009 14:29:43 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
Message-ID: <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com>

Steven D'Aprano wrote:

> Because the cost isn't zero. Needing to write \\ in a string
> literal when you want \ is a cost,

I need to preface this entire post with the fact that I've
already used ALL of the arguments that you've provided on my
friend before I ever even came here with the topic, and my
own arguments on why Python can be considered to be doing
the right thing on this issue didn't even convince ME, much
less him. When I can't even convince myself with an argument
I'm making, then you know there's a problem with it!

Now back the our regularly scheduled debate:

I think that the total cost of all of that extra typing for
all the Python programmers in the entire world is now
significantly less than the time it took to have this
debate. Which would have never happened if Python did things
the right way on this issue to begin with. Meaning that
we're now at LESS than zero cost for doing things right!

And we haven't even yet included all the useless heat that
is going to be generated during code reviews and in-house coding
standard debates.

That's why I stand by Python's motto:

   THERE SHOULD BE ONE-- AND PREFERABLY ONLY ONE --OBVIOUS
   WAY TO DO IT.

> and having to read \\ in source code and mentally
> translate that to \ is also a cost.

For me that has no mental cost. What does have a mental cost
is remembering whether "\b" is an "unrecognized escape
sequence" or not.

> By all means argue that it's a cost that is worth paying,
> but please stop pretending that it's not a cost.

I'm not "pretending". I'm pwning you with logic and common
sense!

> Having to remember that \n is a "special" escape and \y
> isn't is also a cost, but that's a cost you pay in C++ too,
> if you want your code to compile.

Ummm, no I don't! I just always use "\\" when I want a
backslash to appear, and I only think about the more obscure
escape sequences if I actually need them, or some code that
I am reading has used them.

> By the way, you've stated repeatedly that \y will compile
> with a warning in g++. So what precisely do you get if you
> ignore the warning?

A program with undefined behavior. That's typically what a
warning means from a C++ compiler. (Sometimes it means
use of a deprecated feature, though.)

> What do other C++ compilers do?

The Microsoft compilers also consider it to be incorrect
code, as I documented in a different post.

> Apart from the lack of warning, what actually is the
> difference between Python's behavior and C++'s behavior?

That question makes just about as much sense as, "Apart
from the lack of a fatal error, what actually is the
difference between Python's behavior and C++'s?"

Sure, warnings aren't fatal errors, but if you ignore them,
then you are almost always doing something very
wrong. (Unless you're building legacy code.)

> > Furthermore, Python's strategy here is SPECIFICALLY
> > DESIGNED, according to the reference manual to catch
> > bugs. I.e., from the original posting on this issue:
>
> >      Unlike Standard C, all unrecognized escape sequences
> >      are left in the string unchanged, i.e., the backslash
> >      is left in the string.  (This behavior is useful when
> >      debugging: if an escape sequence is mistyped, the
> >      resulting output is more easily recognized as
> >      broken.)
>
> You need to work on your reading comprehension. It doesn't
> say anything about the motivation for this behaviour, let
> alone that it was "SPECIFICALLY DESIGNED" to catch bugs. It
> says it is useful for debugging. My shoe is useful for
> squashing poisonous spiders, but it wasn't designed as a
> poisonous-spider squashing device.

As I have a BS from MIT in BS-ology, I can readily set aside
your aspersions to my intellect, and point out the gross
errors of your ways: Natural language does not work the way
you claim. It is is much more practical, implicit, and
elliptical.

More specifically, if your shoe came with a reference manual
claiming that it was useful for squashing poisonous spiders,
then you may now validly assume poisonous spider squashing
was a design requirement of the shoe. (Or at least it has
become one, even if ipso facto.) Furthermore, if it turns out
that the shoe is deficient at poisonous spider squashing,
and consequently causes you to get bitten by a poisonous
spider, then you now have grounds for a lawsuit.

> > Because in the former cases it can't catch the the bug,
> > and in the latter case, it can.
>
> I'm not convinced this is a bug that needs catching, but if
> you think it is, then that's a reasonable argument.

All my arguments are reasonable.

> >> Perhaps it can catch *some* errors of that type, but
> >> only at the cost of extra effort required to defeat the
> >> compiler (forcing the programmer to type \\d to prevent
> >> the compiler complaining about \d). I don't think the
> >> benefit is worth the cost. You and your friend do. Who
> >> is to say you're right?
>
> > Well, Bjarne Stroustrup, for one.
>
> Then let him design his own language *wink*

Oh, I'm not sure that's such a good idea. He might come up
with a language as crazy as C++.

> >> In C++, if you see an escape you don't recognize, do you
> >> care?
>
> > Yes, of course I do. If I need to know what the program
> > does.
>
> Precisely the same as in Python.

Not so at all!

In C++ I only have to run for the manual only when someone
actually puts a *real* escape sequence in their code. With
Python, I have to run for the manual (or at least the REPL),
every time some lame-brained person who thinks they should be
allowed near a keyboard programs using "unrecognized escape
sequences" because they can't be bothered to hit the "\" key
twice.

> Seems to me that the answer is "It's not worse than C++,
> it's the same" -- in both cases, you have to memorize the
> "special" escape sequences, and in both cases, if you see
> an escape you don't recognize, you need to look it up.

The answer is that in this particular case, C++ causes me
far fewer woes! And if C++ is causing me fewer woes than
Language X, then you've got to know that Language X has a
problem.

> I disagree with your sense of aesthetics. I think that
> having to write \\y when I want \y just to satisfy a
> bondage-and-discipline compiler is ugly. That's not to deny
> that B&D isn't useful on occasion, but in this case I
> believe the benefit is negligible, and so even a tiny cost
> is not worth the pain.

EXPLICIT IS BETTER THAN IMPLICIT.

> > (2) That argument disagrees with the Python reference
> > manual, which explicitly states that "unrecognized escape
> > sequences are left in the string unchanged", and that the
> > purpose for doing so is because it "is useful when
> > debugging".
>
> How does it disagree? \y in the source code mapping to \y in
> the string object is the sequence being left unchanged. And
> the usefulness of doing so is hardly a disagreement over the
> fact that it does so.

Because you've stated that "\y" is a legal escape sequence,
while the Python Reference Manual explicitly states that it
is an "unrecognized escape sequence", and that such
"unrecognized escape sequences" are sources of bugs.

> > What makes it "illegal". As far as I can tell, it's just
> > another "unrecognized escape sequence".
>
> No, it's recognized, because \x is the prefix for an
> hexadecimal escape code. And it's illegal, because it's
> missing the actual hexadecimal digits.

So? Why does that make it "illegal" rather than merely
"unrecognized?"

SIMPLE IS BETTER THAN COMPLEX.

> All joking aside, syntax varies from one language to
> another. What counts as a legal escape sequence in
> Javascript and what counts as a legal escape sequence in
> Python are different. What makes you think I'm talking
> about Javascript?

Because anyone with common sense will agree that "\y" is an
illegal escape sequence. The only disagreement should then
be how illegal escape sequences should be handled. Python is
not currently handling them in a way that makes the most
sense.

ERRORS SHOULD NEVER PASS SILENTLY.

> But the morass only exists in the first place because you
> have adopted C++'s approach instead of Python's approach --
> and (possibly) not even a standard part of the C++ approach,
> but a non-standard warning provided by one compiler out of
> many.

Them's fighting words! I rarely adopt the C++ approach to
anything! In this case, (1) C++ just coincidentally happens
to be right, and (2) as far as I can tell, g++ implements
the C++ standard correctly here.

> > It may not be a complex form of DWIMing, but it's still
> > DWIMing a bit.  Python is figuring that if I typed "\z",
> > then either I must have really meant to type "\\z",
>
> Nope, not in the least. Python NEVER EVER EVER tries to
> guess what you mean.

Neither does Perl. That doesn't mean that Perl isn't often
DWIMy.

> This is *exactly* like C++, except that in Python the
> semantics of \y and \\y are identical. Python doesn't
> guess what you mean, it *imposes* a meaning on the escape
> sequence. You just don't like that meaning.

That's because I don't like things that are ill-conceived.

> > I.e., more or less like continuing on in the face of
> > what the Python Reference manual refers to as an
> > "unrecognized escape sequence".

> The wording could be better, I accept. It would be better
> to talk about "special escapes" (e.g. \n) and "any
> non-special escape" (e.g. \y).

Or maybe the wording is just fine, and it's the treatment of
unrecognized escape sequences that could be better.

|>ouglas




From no.email at please.post  Tue Aug 11 17:30:24 2009
From: no.email at please.post (kj)
Date: Tue, 11 Aug 2009 21:30:24 +0000 (UTC)
Subject: How to access a function's formal signature?
Message-ID: 



In the standard Python interactive interpreter, the string printed
by the help command when applied to a function includes the function's
formal signature.  E.g.:

>>> def foo(bar, *baz, **frobozz):
...   pass
... 
>>> help(foo)
Help on function foo in module __main__:

foo(bar, *baz, **frobozz)


Here by "signature" I'm referring to the substring "bar, *baz,
**frobozz" shown above (or, equivalently, any other object from
which this string could be deduced).  (I figured out that I can
retrieve this signature using methods in the inspect module.)

OK, now, is there a way to modify a function so that pydoc (and
presumably also the interactive interpreter's help function, etc.)
will print out a desired specific signature for this function?

For example, is there some way that I can modify foo above so that
help(foo) will print out

foo(x, y=None)

I tried mucking with foo.func_code's co_argcount, co_varnames, and
co_flags attributes, but as it turns out, they are read-only,
unfortunately.

The context here is the problem of writing a signature-changing
decorator in such a way that documentation facilities like help
and pydoc will print out the signature of the *original* undecorated
code (with some modifications), rather than the signature of the
decorated method.

TIA!

kynn


From darkwater42 at gmail.com  Tue Aug 11 17:39:30 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Tue, 11 Aug 2009 14:39:30 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
	
	
	<86e09602-7eb1-4397-a77f-fb1e3c5b34b9@k26g2000vbp.googlegroups.com>
	
Message-ID: <6cca7095-cd11-4961-a44c-78da1b4ddf6b@g10g2000yqh.googlegroups.com>

On Aug 10, 11:27?pm, Steven D'Aprano
 wrote:
> On Mon, 10 Aug 2009 08:21:03 -0700, Douglas Alan wrote:
> > But you're right, it's too late to change this now.
>
> Not really. There is a procedure for making non-backwards compatible
> changes. If you care deeply enough about this, you could agitate for
> Python 3.2 to raise a PendingDepreciation warning for "unexpected" escape
> sequences like \z,

How does one do this?

Not that I necessarily think that it is important enough a nit to
break a lot of existing code.

Also, if I "agitate for change", then in the future people might
actually accurately accuse me of agitating for change, when typically
I just come here for a good argument, and I provide a connected series
of statements intended to establish a proposition, but in return I
receive merely the automatic gainsaying of any statement I make.

|>ouglas



From pavlovevidence at gmail.com  Tue Aug 11 17:42:02 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Tue, 11 Aug 2009 14:42:02 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<7xab2c52y6.fsf@ruckus.brouhaha.com> 
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com> 
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com> 
	
	 
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com> 
	
	<875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>
	
Message-ID: 

On Aug 11, 1:46?pm, Mark Lawrence  wrote:
> r wrote:
> > Ah Ha! the docs are broken and i was right all along! Are the good
> > folks at Python dev rolling a new installer as we speak, or we must
> > wait for new version?
>
> As I pointed out a few minutes ago thicko, the new version has been
> available for months.


Hello,

I'm mailing you to kindly request, again, that you please stop
validating "r"'s disruptiveness by responding to him on
comp.lang.python.  Thank you.

Carl Banks


From deets at nospam.web.de  Tue Aug 11 17:42:42 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Tue, 11 Aug 2009 23:42:42 +0200
Subject: ElementTree - Howto access text within XML tag element...
In-Reply-To: 
References: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
	<7ecm77F2fbf71U1@mid.uni-berlin.de>
	
Message-ID: <7ee6ukF2fo0t8U1@mid.uni-berlin.de>

cmalmqui schrieb:
> On Aug 11, 9:51 am, "Diez B. Roggisch"  wrote:
>> cmalmqui schrieb:
>>> Hi,
>>> I am writing on a small XML parser and are currently stuck as I am not
>>> able to get the whole element name in ElementTree.
>>> Please see the below example where "print root[0][0]" returns
>>> ""
>>> Is there a way to get hold of the "Running" string in the tag using
>>> elementTree?
>>> 
>>>     
>>>       2009-07-10T14:48:00Z
>>>       
>>>       .........
>>> For those of you that know how to program XML I have another
>>> question:
>>> I am currently "hardcoding" my XML parser using brackets, is this a
>>> good approach or should I build it using a "search on tag" approach.
>> What do you mean by that - hardcoding by brackets?
>>
>> Diez
> 
> Indeed, my current approach has been to hardcode the XML parser using
> brackets. Is there a more elegant way?
> 
> I am parsing a garmin xml file from a handheld GPS and as you can see
> in the below script, I am hardcoding each node:

As you don't give an actual example of how the XML looks like, it's hard 
to tell. But under the assumption that the tag-names are not generic, 
I'd certainly go for

   root.find("tagname")

instead. That's much clearer, and you don't rely on an actual order of 
elements.

Diez


From darkwater42 at gmail.com  Tue Aug 11 17:48:24 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Tue, 11 Aug 2009 14:48:24 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
	 
	<0291a21a$0$20639$c3e8da3@news.astraweb.com>
	<8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com>
	
Message-ID: <1a0e1e6d-d902-4df7-8d35-850c4f62cc9c@e27g2000yqm.googlegroups.com>

On Aug 11, 4:38?pm, Ethan Furman  wrote:

> Mind you, I'm not really vested in how Python *should* handle
> backslashes one way or the other, but I am glad it has rules that it
> follows for consitent results, and I don't have to break out a byte-code
> editor to find out what's in my string literal.

I don't understand your comment. C++ generates a warning if you use an
undefined escape sequence, which indicates that your program should be
fixed. If the escape sequence isn't undefined, then C++ does the same
thing as Python.

It would be *even* better if C++ generated a fatal error in this
situation. (g++ probably has an option to make warnings fatal, but I
don't happen to know what that option is.) g++ might not generate an
error so that you can compile legacy C code with it.

In any case, my argument has consistently been that Python should have
treated undefined escape sequences consistently as fatal errors, not
as warnings.

|>ouglas



From rurpy at yahoo.com  Tue Aug 11 17:50:51 2009
From: rurpy at yahoo.com (rurpy at yahoo.com)
Date: Tue, 11 Aug 2009 14:50:51 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
Message-ID: <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>

On 08/11/2009 11:53 AM, Steven D'Aprano wrote:
> On Tue, 11 Aug 2009 07:57:28 -0700, rurpy wrote:
>
>> On 08/11/2009 01:47 AM, Antoine Pitrou wrote:
>>> r   gmail.com>   writes:
>>>> On Aug 9, 11:02 pm, David Lyon   wrote:
>>>>> Since you're talking about documentation, which is a part of python,
>>>>> don't you think you should be discussing it on python-dev ?
>>>> Yea, them's be a friendly bunch to noob ideas ;). Hey i got a better
>>>> idea, lets go to the IRS and see if we can persuade them to stop
>>>> taxing us...
>>> You know, the most interesting thing in this thread is certainly its
>>> title : ? Social problems of Python doc ?
>>>
>>> Yes, the little social problem here should be clear: if you have
>>> complaints to voice or improvements to suggest to the Python docs, you
>>> should do so on the issue tracker (*). For most topics, this is the
>>> only reasonable way to signal problems to the Python developers
>>> community, and so it is in most free software / open source projects.
>> "the *only* reasonable way"?  That's clearly wrong (unless you want to
>> wiggle in the room provided by "reasonable" or "most"). There is
>> discussion on the dev list, there is discussion here.
>
> Discussion here is spitting into the wind. The noise-to-signal ratio is
> high enough that the people who can fix an issue aren't likely to see it
> here. Unless somebody raises a report in the bug tracker, it will go
> nowhere, fast.

The point isn't always to gain a core developer's attention --
sometimes it is to figure out a good approach before proposing
something concrete.

> The same happens for issues on the dev list: I can't count how many times
> people there have said "put it in the bug tracker, or it will be
> forgotten".

On the contrary, there are many issues raised there that are
discussed there or result in the response, "take it to python-
ideas".  Not every issue to so well-baked that it is ready for
a tracker issue with patch.  There are some things that need
discussion before investing a lot of effort in them.

>> The issue tracker is fine for many things, but the process it provides
>> is equivalent to peep-hole optimization.  How does one submit a tracker
>> issue for something like the overall organization of the docs (for
>> example, the mis-placement of things like data- types in the library
>> manual rather than the language manual)?
>
> The same way you would submit a tracker issue for anything.
>
> "Documentation bug: Data types are misplaced in the library manual
> instead of the language manual.
>
> Suggested alternative: move page docs.python.org/xyz.html to abc.html"

But that's the problem.  Such a reorg is not a simple matter
of moving a file from here to there.  It will require a lot
moving about of sections and a lot of word-smithing to glue
them back together again in a coherent way.

A tracker issue, even one that was fairly specific about
how things should be reorganized but which did not provide
all the needed changes (a large patch) would almost certainly
be ignored or rejected.  But providing a large patch raises
two questions.  How likely is it to be be accepted?
(Something anyone would want to know before investing the time.)
And how to actually do the work needed to generate it (it could
be a very large amount of work for an individual and I don't
think it can be broken down into small independent issues.)
How is one to test the waters as to acceptability, or solicit
help, if one simply submits a tracker issue?

>> The big problem with the docs is poor writing (this includes not using
>> examples when they can help explain something more clearly than verbiage
>> alone).
>
> There's a difference between insufficiently good writing and poor
> writing: think of grading the docs, where 100 is "perfect in every way"
> and -100 is "perfectly awful in every possible way". (It's not a linear
> scale.) A score of 0 is "mediocre, just barely acceptable". Poor writing
> has a negative score. In my opinion, Python's docs are perhaps a 40 or
> 50, significantly better than most technical docs I've seen.

There is no objective way of rating docs.  My evaluation results
in part from the fact that I was able to learn Perl using only
the man pages.  I seriously attempted the same with the supposedly
easier-to-learn Python but was not able to and had to resort to
other web resources and buying Beazly's book.

Before you reply that tutorials are for learning, not reference
manuals, I will disagree.  A well written reference manual will
provide all the information needed to understand a language (albeit
arranged differently than the linear form of a tutorial), and I
have learned several languages in addition to Perl from their
reference materials.  Which is why I attribute my failure to do
so with Python to be the docs' fault.

> [...]
>>   I can rewrite some section so it sounds good to me, but likely it will
>> be just as bad (perhaps in different ways) that what is there.
>
> Bug reports are valuable even if you don't have the skills to provide a
> patch. Bug reports with patches are even more valuable, but that doesn't
> mean that the failure to provide a patch *necessarily* dooms your report
> to oblivion.
>
>
>> The post that started this thread proposed something like paying
>> professional writers to improve the docs.  This may or may not be a
>> practical suggestion.  But the immediate response it engendered was an
>> auto-immune-like group response: the docs are great already, don't
>> complain, fix them yourself, yada, yada; the same response that any
>> criticism of free software produces.
>
> I haven't seen any such knee-jerk responses. What I've seen is a set of
> sensible, *practical* advice:
>
> - complaining on its own, especially here, is pointless;

I don't think that is true.  (Or rather, the extent that it is true
is determined by the attitudes here.)

> - Python is a community effort, if you see something that needs fixing,
> do something about it;

Pointing out something that needs fixing *is* doing something
about it.  Maybe not as much as you'd like but from each according
to his ability...

> - many of us DON'T want arbitrary people "correcting" the official docs
> without oversight, and believe that would be a disaster (arbitrary people
> aren't give check-in privileges to add code to Python's standard library,
> nor should they be given check-in privileges to add docs);

Agreed.  I hope that was clear from my earlier post.

> - if people are keen on a Python wiki, then by all means publish one,
> just don't expect the Python dev team to build and manage it for you;

As luminous a Pythoneer as Fredrik Lundh set up a documentation
wiki to collect user contributions but it has faded away.  If
he couldn't pull it off then I'd say most other attempts without
the backing of python.org are almost certainly doomed to failure.
However, were the Python docs site to provide a wiki, along
with a mechanism to migrate suggestions developed on the wiki
into the docs, it might well be a viable (and easier because of
the wysiwyg effect) way of improving the docs.  As other have
pointed out, Postgresql, PHP, and Haskell have done so.
Now maybe there are good reasons not to do that.  But your hand-
waving is not one of them.

> - bug reports and patches to the docs are ALWAYS welcome, even if they
> are rejected;

Of course.  The cost for briefly looking at a report before
rejecting it is very low.  However the cost for producing it
can be much higher.  I'm not saying that that is what happens,
just that your statement considers only the pov of the issue
handlers, not the submitters.

> - if you don't have the skills to fix a bug (including doc bugs), an
> alternative is to pay somebody else to do so instead.

That there are alternatives was not my point.  My point was
that there are perhaps *other* alternatives too, but anyone
who tries to explore them here usually gets buried under a
mass of negativity.

>> It's really too bad the the python community can't seriously discuss
>> ways to improves the docs.  There are other possibilities for instance
>> the Fedora Docs project (can't say I'm impressed by what they've
>> produced but that doesn't mean their model is useless).  There is a need
>> for an approval process managed by someone who actually understands what
>> good technical writing is.  And perhaps editors who can polish or work
>> with programmers who provide the raw technical description of some
>> module.
>
> Yes, you're correct.
>
> [sarcasm] Now that we've agreed on what needs to be done, the problem is
> solved!!! [end sarcasm]

Anyone who's ever been to AA knows that the first step to
solving a problem is to acknowledge the problem exists.
As long as every "the docs sux" complaint is met here with
the standard responses that I've mentioned, rather than, "yes,
they do have some problems, what do you think we should do
about them?", the docs will continue to sux.  But as I said
maybe that's just the way it is.

>> Some kind of higher level more global process is the only way I can see
>> that the docs will be improved to any sort or professional standard.  I
>> don't see how issues like this will be addressed by submitting tracker
>> items.
>
> You want community input into the docs, but you're not willing to give
> that input except to bitch and moan and sook that the tracker is no good.

I have not done any "bitching and moaning".  I tried to
explain a group reaction that affects python negatively
(IMO) by rejecting any consideration of ways of improving
the docs other than submitting tracker issues.
That you pejoratively label it "bitching and moaning"
I count as evidence supporting my view.

> Even if the PSF had a full-time team of professional documentation
> writers and editors, guess what, you would STILL need to submit issues to
> the bug tracker, because otherwise THEY WON'T BE TRACKED.

Maybe, maybe not.  Depends on what development process the
(hypothetical) doc team chooses to use is.

>> Personally, I have given up on this issue.  The social factors involved
>> really pretty much determine that the Python docs will never reach a
>> very high quality -- that's just the way it is and I've come to accept
>> that.
>
> Ultimately it boils down to two factors:
>
> Money.
>
> Effort.
>
> If you won't put in the effort, and you won't put in the money, then it
> won't happen. Moaning that other people aren't putting in the money to
> hire team of professional writers isn't productive, and moaning that
> other people aren't putting in the effort to improve the docs isn't
> either.

Eh?  I have a computer filled with software that I put no
money or effort into, yet there it is.  So clearly you are
wrong in the general sense.  Before you call me a free-loading
ingratiate consider the software you use and how much of it you
have made substantive contributions to.  We all have limited
time and resources and we all have to choose where to invest that
time.  That some of us choose to invest it somewhere other than
Python does not deprive of of our right to point out problems
in Python when we note them.



From breamoreboy at yahoo.co.uk  Tue Aug 11 18:06:35 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 23:06:35 +0100
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References: 	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>					<0006817d$0$2895$c3e8da3@news.astraweb.com>
		
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com>
		<875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>	
	
Message-ID: 

Carl Banks wrote:
> On Aug 11, 1:46 pm, Mark Lawrence  wrote:
>> r wrote:
>>> Ah Ha! the docs are broken and i was right all along! Are the good
>>> folks at Python dev rolling a new installer as we speak, or we must
>>> wait for new version?
>> As I pointed out a few minutes ago thicko, the new version has been
>> available for months.
> 
> 
> Hello,
> 
> I'm mailing you to kindly request, again, that you please stop
> validating "r"'s disruptiveness by responding to him on
> comp.lang.python.  Thank you.
> 
> Carl Banks
I hereby apologise.  My only feeble excuse is that my mammary glands are 
getting crushed.

-- 
Kindest regards.

Mark Lawrence.



From paul at boddie.org.uk  Tue Aug 11 18:08:59 2009
From: paul at boddie.org.uk (Paul Boddie)
Date: Tue, 11 Aug 2009 15:08:59 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
Message-ID: <9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegroups.com>

On 11 Aug, 23:50, ru... at yahoo.com wrote:
>
> However, were the Python docs site to provide a wiki, along
> with a mechanism to migrate suggestions developed on the wiki
> into the docs, it might well be a viable (and easier because of
> the wysiwyg effect) way of improving the docs. ?As other have
> pointed out, Postgresql, PHP, and Haskell have done so.
> Now maybe there are good reasons not to do that. ?But your hand-
> waving is not one of them.

I think you make some good points, although I don't have time to
respond to all of them. Certainly, the documentation situation with
Python is not ideal; otherwise, people would not be complaining about
it so frequently.

I recommend going to the existing Wiki and looking at what there is
already:

http://wiki.python.org/moin/Documentation
http://wiki.python.org/moin/CategoryDocumentation

Sadly, I don't think you'll find much to work with, apart from the
occasional attempt to make an annotated version of the existing
documentation:

http://wiki.python.org/moin/PythonLibraryReference

So my next recommendation is to either use the existing Wiki
infrastructure or to ask for a separate Wiki for the purpose of
reworking the documentation. You could either take the existing
documentation, which I believe is now restructured text, and just drop
that into the Wiki with the appropriate format directives (for later
reworking in Wiki format, perhaps), or you could start afresh and
tackle some of the more serious issues head on.

I can see benefits to just starting from scratch. Perhaps the
licensing should be more explicit than the existing material on the
Wiki so that the documentation produced could be freely distributed
without uncertainty, but the outcome would hopefully be something that
stands on its own as an alternative or a replacement to the
conventional documentation.

Paul


From joelriv at gmail.com  Tue Aug 11 18:09:37 2009
From: joelriv at gmail.com (Joel Juvenal Rivera Rivera)
Date: Tue, 11 Aug 2009 17:09:37 -0500
Subject: create shell history with python
Message-ID: <1250028577.1453.46.camel@localhost>

I been thinking how to make a 'bash like history shell' in python,
i don't know if with stdin and stdout i can accomplish this or do i
need something like curses and stuff like that, anyway im start to
figure this out.
Does any body has try this? or have any interesting idea?

--Joel Rivera




From clp2 at rebertia.com  Tue Aug 11 18:15:02 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Tue, 11 Aug 2009 18:15:02 -0400
Subject: create shell history with python
In-Reply-To: <1250028577.1453.46.camel@localhost>
References: <1250028577.1453.46.camel@localhost>
Message-ID: <50697b2c0908111515t386f7ee7w6fcebd1326c77263@mail.gmail.com>

On Tue, Aug 11, 2009 at 6:09 PM, Joel Juvenal Rivera
Rivera wrote:
> I been thinking how to make a 'bash like history shell' in python,
> i don't know if with stdin and stdout i can accomplish this or do i
> need something like curses and stuff like that, anyway im start to
> figure this out.
> Does any body has try this? or have any interesting idea?

http://docs.python.org/library/readline.html

Cheers,
Chris
-- 
http://blog.rebertia.com


From deets at nospam.web.de  Tue Aug 11 18:15:38 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Wed, 12 Aug 2009 00:15:38 +0200
Subject: create shell history with python
In-Reply-To: 
References: 
Message-ID: <7ee8saF2e47vaU1@mid.uni-berlin.de>

Joel Juvenal Rivera Rivera schrieb:
> I been thinking how to make a 'bash like history shell' in python,
> i don't know if with stdin and stdout i can accomplish this or do i
> need something like curses and stuff like that, anyway im start to
> figure this out.
> Does any body has try this? or have any interesting idea?

Don't waste your time, use IPython :)

http://ipython.scipy.org/moin/

Diez


From joelriv at gmail.com  Tue Aug 11 18:18:55 2009
From: joelriv at gmail.com (Joel Juvenal Rivera Rivera)
Date: Tue, 11 Aug 2009 17:18:55 -0500
Subject: create shell history with python
In-Reply-To: <50697b2c0908111515t386f7ee7w6fcebd1326c77263@mail.gmail.com>
References: <1250028577.1453.46.camel@localhost>
	<50697b2c0908111515t386f7ee7w6fcebd1326c77263@mail.gmail.com>
Message-ID: <1250029135.1453.48.camel@localhost>

Wow i didn't  know that module this solves everything... i guess python
has a lot more  batteries than i thought .
Thank you Chris

El mar, 11-08-2009 a las 18:15 -0400, Chris Rebert escribi?:
> On Tue, Aug 11, 2009 at 6:09 PM, Joel Juvenal Rivera
> Rivera wrote:
> > I been thinking how to make a 'bash like history shell' in python,
> > i don't know if with stdin and stdout i can accomplish this or do i
> > need something like curses and stuff like that, anyway im start to
> > figure this out.
> > Does any body has try this? or have any interesting idea?
> 
> http://docs.python.org/library/readline.html
> 
> Cheers,
> Chris



From deets at nospam.web.de  Tue Aug 11 18:23:39 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Wed, 12 Aug 2009 00:23:39 +0200
Subject: for key, value in dict.() - how to get? (which func)
In-Reply-To: 
References: 
	
	
Message-ID: <7ee9beF2gr846U1@mid.uni-berlin.de>

dmitrey schrieb:
> Yes, thank you, items() is the correct approach, on the other hand I
> have already get rid of the cycle.

Most certainly items() is *not* the correct approach if you are 
concerned so much with performance, because items() first creates a list 
of key/value-pairs, where iteritems() will be an effective iterator.

so if you are (IMHO wrongly) concerned about performance of an O(1) 
lookup, items() certainly costs more.

And the following program proves it:

import time

d = dict(zip(xrange(100000), xrange(100000)))

start = time.time()
for loops in xrange(100):
     for key in d:
         value = d[key]

print "lookup: ", time.time() - start

start = time.time()

for loops in xrange(100):
     for key, value in d.items():
         value = d[key]


print "items: ", time.time() - start

start = time.time()

for loops in xrange(100):
     for key, value in d.iteritems():
         value = d[key]


print "items: ", time.time() - start


The result on my machine is:

deets$ python /tmp/test.py

lookup:  2.78633999825
items:  7.42830610275
items:  3.69960308075

So actually your condemed approach seems to be the fastest, where the 
items() call by far is the slowest approch.

"In the face of ambiguity, refuse the temptation to guess."


Diez


From aahz at pythoncraft.com  Tue Aug 11 18:25:27 2009
From: aahz at pythoncraft.com (Aahz)
Date: 11 Aug 2009 15:25:27 -0700
Subject: httplib incredibly slow :-(
References: 
Message-ID: 

In article ,
Chris Withers   wrote:
>
>Does anyone know of an alternative library for creating http requests 
>and getting their responses that's faster but hopefully has a similar 
>interface?

PyCurl
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz


From rt8396 at gmail.com  Tue Aug 11 19:12:42 2009
From: rt8396 at gmail.com (r)
Date: Tue, 11 Aug 2009 16:12:42 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<7xk51fgazf.fsf@ruckus.brouhaha.com> 
	 
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com> 
	
	 
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com> 
	
	<875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>
	
	
	
Message-ID: 

...(Carl Banks doing what he does best)
> > I'm mailing you to kindly request, again, that you please stop
> > validating "r"'s disruptiveness by responding to him on
> > comp.lang.python. ?Thank you.

Carl,
You have no right to tell people when where and how they should speak
to anyone. And how dare you think you can! If you spent even a
fraction of the time you spend manipulating the direction of this list
and instead, actually contributing to the problem at hand, (discussion
or otherwise) we would be much closer to solving this problem today.

You (and your conspirators) are the reason most people find the c.l.py
list so disturbing and wish not to participate. Get a life you moron
and stop trying to control the world.

PS: GET STUFFED!


From rays at blue-cove.com  Tue Aug 11 19:13:37 2009
From: rays at blue-cove.com (RJ)
Date: Tue, 11 Aug 2009 16:13:37 -0700
Subject: Social problems of Python doc [was Re: Python docs disappointing]
In-Reply-To: <9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegro
	ups.com>
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	<9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegroups.com>
Message-ID: <6.2.3.4.2.20090811160723.04a40580@blue-cove.com>

At 03:08 PM 8/11/2009, you wrote:
>I recommend going to the existing Wiki and looking at what there is
>already:
>
>http://wiki.python.org/moin/Documentation
>http://wiki.python.org/moin/CategoryDocumentation

I also can't see how to get 
from  http://wiki.python.org/moin/Documentation to 
http://wiki.python.org/moin/CategoryDocumentation, for one...

>Sadly, I don't think you'll find much to work with, apart from the
>occasional attempt to make an annotated version of the existing
>documentation:
>
>http://wiki.python.org/moin/PythonLibraryReference

The library reference above needs a link to Modules (and the link to 
Andrew's pages are now dead - 
http://pydoc.amk.ca/frame.html)

What I've always looked for and Google constantly for, is a main 
language version of the features of http://www.scipy.org/Cookbook and 
http://code.activestate.com/recipes/langs/python/, with module level 
organization. At least users can submit something at Activestate. The 
issue there (and at Scipy) is that I usually want an example 
illustrating some method, and that's not how it's organized (but is 
at those Other language sites), so I still need to search at Scipy, or do
http://www.google.com/search?q=site%3Ascipy.org+foo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From cjns1989 at gmail.com  Tue Aug 11 19:16:55 2009
From: cjns1989 at gmail.com (Chris Jones)
Date: Tue, 11 Aug 2009 19:16:55 -0400
Subject: [OT] From: header - WAS: Python docs disappointing - group effort	to
	hire writers?
In-Reply-To: <7xab266v1j.fsf@ruckus.brouhaha.com>
References: <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	
	<081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com>
	<7xr5vj9m0g.fsf@ruckus.brouhaha.com>
	<2fd432c7-00e2-4bb6-9192-e9f7aa96c4d7@m3g2000pri.googlegroups.com>
	<7xab266v1j.fsf@ruckus.brouhaha.com>
Message-ID: <20090811231655.GA3491@turki.gavron.org>

Hello Paul,

This is strictly OT, but when you get a chance, could you contact me off
list at the above address?

I need your help with the From: email address specified in your posts to
the list. 

Thanks,

CJ


From Nikolaus at rath.org  Tue Aug 11 19:21:16 2009
From: Nikolaus at rath.org (Nikolaus Rath)
Date: Tue, 11 Aug 2009 19:21:16 -0400
Subject: Monkeypatching an object to become callable
References: <87hbwgu7xa.fsf@vostro.rath.org>
	<0aa46ece-64b9-4c28-b690-5ac5937ce3f2@f20g2000prn.googlegroups.com>
	<4a7fd55e$0$32765$426a74cc@news.free.fr>
Message-ID: <87iqguey37.fsf@vostro.rath.org>

Bruno Desthuilliers  writes:
> 7stud a ?crit :
> (snip)
>> class Wrapper(object):
>>     def __init__(self, obj, func):
>>         self.obj = obj
>>         self.func = func
>>
>>     def __call__(self, *args):
>>         return self.func(*args)
>>
>>     def __getattr__(self, name):
>>         return object.__getattribute__(self.obj, name)
>
> This should be
>
>           return getattr(self.obj, name)
>
> directly calling object.__getattribute__ might skip redefinition of
> __getattribute__ in self.obj.__class__ or it's mro.

Works nicely, thanks. I came up with the following shorter version which
modifies the object in-place:

class Modifier(obj.__class__):
     def __call__(self):
         return fn()

obj.__class__ = Modifier


To me this seems a bit more elegant (less code, less underscores). Or
are there some cases where the above would fail?


Best,

   -Nikolaus

-- 
 ?Time flies like an arrow, fruit flies like a Banana.?

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C


From chris at simplistix.co.uk  Tue Aug 11 19:25:41 2009
From: chris at simplistix.co.uk (Chris Withers)
Date: Wed, 12 Aug 2009 00:25:41 +0100
Subject: httplib incredibly slow :-(
In-Reply-To: 
References: 
	
Message-ID: <4A81FDF5.6010508@simplistix.co.uk>

Aahz wrote:
> In article ,
> Chris Withers   wrote:
>> Does anyone know of an alternative library for creating http requests 
>> and getting their responses that's faster but hopefully has a similar 
>> interface?
> 
> PyCurl

This seems to be a wrapper around libcurl.

Does it work on Windows?
If so, where can I find some decent examples?
(the ones listed on the pycurl website are not what I'd call decent :-S)

Chris


-- 
Simplistix - Content Management, Batch Processing & Python Consulting
            - http://www.simplistix.co.uk


From pavlovevidence at gmail.com  Tue Aug 11 19:37:51 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Tue, 11 Aug 2009 16:37:51 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	<9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegroups.com>
Message-ID: 

On Aug 11, 3:08?pm, Paul Boddie  wrote:
> Certainly, the documentation situation with
> Python is not ideal; otherwise, people would not be complaining about
> it so frequently.

I will not take an opinion on whether Python's documentation is ideal
(more on why below) but I will opine that the conclusion doesn't
follow from your premise.  People's expectations of what documentation
should be are too different, there will always be people who aren't
pleased.  IOW, there is no "ideal".

For example, kj (who started this mess of thread) complained that
pydoc didn't give exhaustive usage documentation.  In contrast, I
think pydoc gives too much information.  I would rather have only the
bare minimum; I don't want to pan through ten paragraphs just to see
what the fifth argument is.

So who's right?

No one, there is no "right".  Unfortunately some people can't or won't
respect that opinions differ; they have to take perceived defects in
the docs personally.


Carl Banks


From pavlovevidence at gmail.com  Tue Aug 11 19:47:38 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Tue, 11 Aug 2009 16:47:38 -0700 (PDT)
Subject: How to access a function's formal signature?
References: 
Message-ID: <9c025b8e-9602-48cf-be77-f67e9ed3953c@26g2000yqk.googlegroups.com>

On Aug 11, 2:30?pm, kj  wrote:
> In the standard Python interactive interpreter, the string printed
> by the help command when applied to a function includes the function's
> formal signature. ?E.g.:
>
> >>> def foo(bar, *baz, **frobozz):
>
> ... ? pass
> ...>>> help(foo)
>
> Help on function foo in module __main__:
>
> foo(bar, *baz, **frobozz)
>
> Here by "signature" I'm referring to the substring "bar, *baz,
> **frobozz" shown above (or, equivalently, any other object from
> which this string could be deduced). ?(I figured out that I can
> retrieve this signature using methods in the inspect module.)
>
> OK, now, is there a way to modify a function so that pydoc (and
> presumably also the interactive interpreter's help function, etc.)
> will print out a desired specific signature for this function?

I think you'd have to modify pydoc.  pydoc pulls this information out
from the function's attributes (and maybe also it's underlying code
object) which are read-only.


Carl Banks


From danb_83 at yahoo.com  Tue Aug 11 20:08:01 2009
From: danb_83 at yahoo.com (AggieDan04)
Date: Tue, 11 Aug 2009 17:08:01 -0700 (PDT)
Subject: Bug in format specification in Python 3?
References: 
Message-ID: <8ae626c7-1f21-4ab6-b299-2e5633755fbf@g31g2000yqc.googlegroups.com>

On Aug 11, 3:28?pm, Robert Dailey  wrote:
> Hello,
>
> According to the Python 3.1 documentation, I can have a format
> specification like so:
>
> print( 'This is a hex number: {:#08x}'.format( 4 ) )
>
> This will print:
>
> This is a hex number: 0x000004
>
> I notice that the '0x' portion is counted in the width, which was
> specified as 8. This seems wrong to me. Is this by design? If so, why?
> I expect that the width portion to only apply to the input + padding
> only. I don't consider the '0x' portion part of the padding. But maybe
> it is...

It's unintuitive to me, too, but it's the same thing that Python 2.x
did:

>>> print '%#08x' % 4
0x000004



From skippy.hammond at gmail.com  Tue Aug 11 20:10:18 2009
From: skippy.hammond at gmail.com (Mark Hammond)
Date: Tue, 11 Aug 2009 17:10:18 -0700
Subject: Windows 7 : any problems installing or running Python ?
In-Reply-To: 
References: 
	
Message-ID: <4A82086A.4060606@gmail.com>

On 9/08/2009 10:42 PM, Tim Roberts wrote:
> Dave WB3DWE wrote:
>>
>> Anybody tried it ?
>> Is anything broken, ie is the whole shootin' match good to go ?
>> I'm esp interested in WConio for 3.0/3.1 which I use heavily.
>
> I've been running the 32-bit builds of Python 2.5, PyWin32, and wxPython on
> Windows 7 64-bit for many months.  No problems at all.
>
> I hated Vista; I would only run it if my clients insisted on having their
> drivers tested on it.  Vista SP1 was somewhat better, but I don't mind
> Windows 7 at all.  I might even upgrade my primary development machine from
> XP.  A number of the usually cranky driver developers have expressed the
> same opinion.  Microsoft might actually have a winner here.

"Me too" :)

Mark


From exarkun at twistedmatrix.com  Tue Aug 11 20:19:28 2009
From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com)
Date: Wed, 12 Aug 2009 00:19:28 -0000
Subject: Social problems of Python doc [was Re: Python docs disappointing]
In-Reply-To: 
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	<9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegroups.com>
	
Message-ID: <20090812001928.10431.2043769776.divmod.xquotient.0@localhost.localdomain>

On 11 Aug, 11:37 pm, pavlovevidence at gmail.com wrote:
>
>I will not take an opinion on whether Python's documentation is ideal
>(more on why below) but I will opine that the conclusion doesn't
>follow from your premise.  People's expectations of what documentation
>should be are too different, there will always be people who aren't
>pleased.  IOW, there is no "ideal".
>
>For example, kj (who started this mess of thread) complained that
>pydoc didn't give exhaustive usage documentation.  In contrast, I
>think pydoc gives too much information.  I would rather have only the
>bare minimum; I don't want to pan through ten paragraphs just to see
>what the fifth argument is.
>
>So who's right?
>
>No one, there is no "right".  Unfortunately some people can't or won't
>respect that opinions differ; they have to take perceived defects in
>the docs personally.

This is right on.  Excellent point, Carl.

Jean-Paul


From rurpy at yahoo.com  Tue Aug 11 20:46:39 2009
From: rurpy at yahoo.com (rurpy at yahoo.com)
Date: Tue, 11 Aug 2009 17:46:39 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<7xab2c52y6.fsf@ruckus.brouhaha.com> 
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com> 
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com> 
	
	 
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com> 
	
	<875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>
	
Message-ID: 

On Aug 11, 2:46 pm, Mark Lawrence  wrote:
> r wrote:
> > Ah Ha! the docs are broken and i was right all along! Are the good
> > folks at Python dev rolling a new installer as we speak, or we must
> > wait for new version?
>
> As I pointed out a few minutes ago thicko, the new version has been
> available for months.

Now hold on here...

I too was bitten by this.  I thought the chm docs were so unusable
that I went to the issue tracker, extremely annoyed, to submit a
rather caustic bug report.  Only after looking through the doc bugs
did I find that it was already recognised, that a corrected chm
file was available, and that there were no plans to do any more
than that.  (This is from memory since the python tracker is down).

On the main download page is a link to the 2.6.2 msi file with not
a word about the help file.  Only if you follow the "python-2.6.2"
link to a second page, is there a link to the corrected help file,
and even that says only, "Updated Windows help file" with no
indication that it is supposed to replace a broken one in the
distribution.

If "r" is a "thicko", I'd say the handling of this issue was done
by some who are considerably thicker.

It may also be yet another example of how documentation (using
the word loosely) is produced without sufficient attention to its
usefulness to its intended audience.


From jstroud at mbi.ucla.edu  Tue Aug 11 20:54:36 2009
From: jstroud at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 17:54:36 -0700
Subject: hashability
Message-ID: 

Hello All,

I wrote the function to test hashability of arbitrary objects. My reason 
is that the built-in python (2.5) hashing is too permissive for some 
uses. A symptom of this permissiveness comes from the ability to 
successfully hash() arbitrary objects:

   py> class C(object): pass
   ...
   py> {C():4}[C()]
   ------------------------------------------------------------
   Traceback (most recent call last):
     File "", line 1, in 
   : <__main__.C object at 0xe21610>

The basis for the exception is that the two instances do not have the 
same hash() although conceptually they might seem equal to the 
unitiated. Were I to re-design python, I'd throw an exception in this 
case because of the ill-defined behavior one might expect if a C() 
serves as a key for a dict.

To prevent users of one of my libraries from falling into this and 
similar traps (which have potentially problematic consequences), I came 
up with this test for hashability:

def hashable(k):
   try:
     hash(k)
   except TypeError:
     good = False
   else:
     good = (hasattr(k, '__hash__') and
             (hasattr(k, '__eq__') or hasattr(k, '__cmp__')))
   return good

It works as I would like for most of the cases I can invent:

   py> all(map(hashable, [1,1.0,"",(1,2,3)]))
   True
   py> any(map(hashable, [None, [1,2], {}, C(), __import__('sys')]))
   False

Can anyone think of boundary cases I might be missing with this approach?


James


From db3l.net at gmail.com  Tue Aug 11 21:18:43 2009
From: db3l.net at gmail.com (David Bolen)
Date: Tue, 11 Aug 2009 21:18:43 -0400
Subject: Networked Broadcast Messaging
References: <37ea826b-708d-48f4-a64a-42f58fec5325@c2g2000yqi.googlegroups.com>
Message-ID: 

"squishywaffle at gmail.com"  writes:

> * Machines can come and go. Since messages are not directly sent to a
> specific IP address from our Python script, the messages are simply
> broadcasted to those who are there to listen. If nobody is subscribed
> to the message type being sent, nothing happens.

What sort of delivery guarantees are you looking for if there is in
fact a machine that is trying to listen to a particular message or
message group?  Is it ok if someone is listening for a certain type of
message, is it ok if it misses one that is sent?

If you do simple direct broadcasting (e.g., UDP), you'd need your own
reliability layer above that if you cared if the message actually got
to an intended destination if that destination was present.

If you want better guarantees, you might look into a distributed
message bus like Spread (http://www.spread.org/) or perhaps a
messaging protocol like XMPP (http://xmpp.org/) through its PubSub
extension.  Both have Python interfaces, though I have no personal
experience with either.  But perhaps that will also give you some
terms or starting points for searching for other options.

-- David


From contact at xavierho.com  Tue Aug 11 21:38:08 2009
From: contact at xavierho.com (Xavier Ho)
Date: Wed, 12 Aug 2009 11:38:08 +1000
Subject: Any built-in function for smallest positive floating point 
	number?
In-Reply-To: 
References: 
Message-ID: <2d56febf0908111838n602c52fbu2d7754733b6246@mail.gmail.com>

On Wed, Aug 12, 2009 at 3:29 AM, Maria Liukis  wrote:

> Hello everybody,
> Is somebody aware of built-in Python's function that would return
> a value for smallest positive double precision floating point number
> (analogous to 'realmin' in Matlab). Python has built-in sys.maxint but I
> could not find anything for float.
>

I'm not sure if this helps, but here you go:
http://drj11.wordpress.com/2007/07/05/the-smallest-number/

I couldn't get it to work on Python 2.6.2 or 3.1 myself, however it seems
pretty small.

- Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From pavlovevidence at gmail.com  Tue Aug 11 21:40:15 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Tue, 11 Aug 2009 18:40:15 -0700 (PDT)
Subject: hashability
References: 
Message-ID: <3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>

On Aug 11, 5:54?pm, James Stroud  wrote:
> Hello All,
>
> I wrote the function to test hashability of arbitrary objects. My reason
> is that the built-in python (2.5) hashing is too permissive for some
> uses. A symptom of this permissiveness comes from the ability to
> successfully hash() arbitrary objects:
>
> ? ?py> class C(object): pass
> ? ?...
> ? ?py> {C():4}[C()]
> ? ?------------------------------------------------------------
> ? ?Traceback (most recent call last):
> ? ? ?File "", line 1, in 
> ? ?: <__main__.C object at 0xe21610>
>
> The basis for the exception is that the two instances do not have the
> same hash() although conceptually they might seem equal to the
> unitiated. Were I to re-design python, I'd throw an exception in this
> case because of the ill-defined behavior one might expect if a C()
> serves as a key for a dict.

That's arguably the right thing to do.

Personally I've found that being able to use class instances as
hashable objects to be terribly useful (these objects are hashed and
compared by identity, of course), so I don't mind it.  But I can
definitely see how this straddles the line between "practicality" and
"face of ambiguity".  And if Python didn't do it by default, it would
be little trouble to add the appropriate __eq__ and __hash__ methods.


> To prevent users of one of my libraries from falling into this and
> similar traps (which have potentially problematic consequences),

Even so, I would consider whether some of your users might, like me,
also find this terribly useful, and if so (probably a few will unless
they are all novices), allow them to disable or disregard this check.

> I came
> up with this test for hashability:
>
> def hashable(k):
> ? ?try:
> ? ? ?hash(k)
> ? ?except TypeError:
> ? ? ?good = False
> ? ?else:
> ? ? ?good = (hasattr(k, '__hash__') and
> ? ? ? ? ? ? ?(hasattr(k, '__eq__') or hasattr(k, '__cmp__')))
> ? ?return good

I wouldn't call the function "hashable".  Class instances like C() are
hashable whether you approve or not.  Something like
"deliberately_hashable" would be a better name.


> It works as I would like for most of the cases I can invent:
>
> ? ?py> all(map(hashable, [1,1.0,"",(1,2,3)]))
> ? ?True
> ? ?py> any(map(hashable, [None, [1,2], {}, C(), __import__('sys')]))
> ? ?False
>
> Can anyone think of boundary cases I might be missing with this approach?

It is possible to redefine == operator by defining __ne__ instead of
__eq__, at least on Python 2.5, so you should keep that in mind.


Carl Banks


From contact at xavierho.com  Tue Aug 11 21:42:36 2009
From: contact at xavierho.com (Xavier Ho)
Date: Wed, 12 Aug 2009 11:42:36 +1000
Subject: Any built-in function for smallest positive floating point 
	number?
In-Reply-To: <2d56febf0908111838n602c52fbu2d7754733b6246@mail.gmail.com>
References: 
	<2d56febf0908111838n602c52fbu2d7754733b6246@mail.gmail.com>
Message-ID: <2d56febf0908111842g11ff8f49w7c96a8bbbb929d83@mail.gmail.com>

I got it to work with Python 2.6.2.

>>> import struct
>>> struct.unpack('d', struct.pack('Q', 1))[0]
4.9406564584124654e-324

Python 3.1 will print 5e-324, which is fair enough.

Cheers,
Xavier
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From contact at xavierho.com  Tue Aug 11 21:49:00 2009
From: contact at xavierho.com (Xavier Ho)
Date: Wed, 12 Aug 2009 11:49:00 +1000
Subject: Any built-in function for smallest positive floating point 
	number?
In-Reply-To: <2d56febf0908111842g11ff8f49w7c96a8bbbb929d83@mail.gmail.com>
References: 
	<2d56febf0908111838n602c52fbu2d7754733b6246@mail.gmail.com>
	<2d56febf0908111842g11ff8f49w7c96a8bbbb929d83@mail.gmail.com>
Message-ID: <2d56febf0908111849y393a65fk609e787eee9bd6f3@mail.gmail.com>

Actually, that was double precision. You asked for float precision.

>>> struct.unpack('f', struct.pack('L', 1))[0]
1.4012984643248171e-45

which is the same as:
>>> 2**-149
1.4012984643248171e-45

I think that's it. Sorry for posting to the list three times in a row.
corrections welcome.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rurpy at yahoo.com  Tue Aug 11 21:50:39 2009
From: rurpy at yahoo.com (rurpy at yahoo.com)
Date: Tue, 11 Aug 2009 18:50:39 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	<9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegroups.com>
Message-ID: <56a1d77e-0379-49e4-99c1-2d0de1378bc2@v36g2000yqv.googlegroups.com>

On Aug 11, 4:08?pm, Paul Boddie  wrote:
> On 11 Aug, 23:50, ru... at yahoo.com wrote:
> > However, were the Python docs site to provide a wiki, along
> > with a mechanism to migrate suggestions developed on the wiki
> > into the docs, it might well be a viable (and easier because of
> > the wysiwyg effect) way of improving the docs. ?As other have
> > pointed out, Postgresql, PHP, and Haskell have done so.
> > Now maybe there are good reasons not to do that. ?But your hand-
> > waving is not one of them.
>[...]
> I can see benefits to just starting from scratch. Perhaps the
> licensing should be more explicit than the existing material on the
> Wiki so that the documentation produced could be freely distributed
> without uncertainty, but the outcome would hopefully be something that
> stands on its own as an alternative or a replacement to the
> conventional documentation.

A couple years ago I actually did give a half-assed try to rewriting
the doc.  I got the doc source downloaded and buildable with the
intent
of rewriting in bits and pieces as I had occasion to use (and find
problems with) various parts.  Not knowing latex, I stupidly got side-
tracked trying to convert it to docbook which I was more interested
in.
After I gave up on that and went back to latex, I found merging
changes
from Python into my source (a little of which was heavily modified by
this time) to be very time consuming.  And eventually the Python side
was changed to REST putting an end to my effort which by that time
were already pretty minimal.  I concluded that the rewrite I was
trying
to do was comparable to writing a Python book, and too ambitious for
one person working on it <5 hrs/week.

And of course I am not any better writer (probably worse) than the
average Python programmer.  Which is the problem with using a wiki --
unless good writers contribute, I see no reason to expect much
better results than already exist.  But maybe I am too pessimistic...



From http  Tue Aug 11 21:51:03 2009
From: http (Paul Rubin)
Date: 11 Aug 2009 18:51:03 -0700
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	<9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegroups.com>
	
Message-ID: <7xocqler5k.fsf@ruckus.brouhaha.com>

Carl Banks  writes:
> On> For example, kj (who started this mess of thread) complained that
> pydoc didn't give exhaustive usage documentation.  In contrast, I
> think pydoc gives too much information.  I would rather have only the
> bare minimum; I don't want to pan through ten paragraphs just to see
> what the fifth argument is.

The problem is that it doesn't sufficiently separate the carefully
written useful stuff from the automatically generated useless stuff.


From afriere at yahoo.co.uk  Tue Aug 11 22:06:54 2009
From: afriere at yahoo.co.uk (Asun Friere)
Date: Tue, 11 Aug 2009 19:06:54 -0700 (PDT)
Subject: hashability
References: 
Message-ID: <77eda964-a6ee-496b-9c5f-5391663099e0@b14g2000yqd.googlegroups.com>

On Aug 12, 10:54?am, James Stroud  wrote:

> I wrote the function to test hashability of arbitrary objects. My reason
> is that the built-in python (2.5) hashing is too permissive for some
> uses. A symptom of this permissiveness comes from the ability to
> successfully hash() arbitrary objects:

Arbitrary, or anonymous objects and some uses or some users?  I'm
can't see why anyone would expect different instance of a class to be
equivalent keys.

> The basis for the exception is that the two instances do not have the
> same hash() although conceptually they might seem equal to the
> unitiated.

Perhaps the best solution would be for the unitiated to correct their
misaprehensions?  If you don't understand that you are instantiating a
number of anonymous instances of a class you are missing something
very fundamental.

> Were I to re-design python, I'd throw an exception in this
> case because of the ill-defined behavior one might expect if a C()
> serves as a key for a dict.

Then you couldn't to this:

d = {C():1, C():2, C():3}
a,b,c = d.keys()
d[c]

Anonymous instances are a GoodThing(tm) and they can usually be de-
anonymised if need be.


From andrew at acooke.org  Tue Aug 11 22:13:39 2009
From: andrew at acooke.org (andrew cooke)
Date: Tue, 11 Aug 2009 19:13:39 -0700 (PDT)
Subject: Frustrated with scopes
Message-ID: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>


Is there a way to make this work (currently scope and join are
undefined at runtime when the inner class attributes are defined):

class _StreamFactory(object):

    @staticmethod
    def __call__(lines, source, join=''.join):

        class Line(object):

            __source = source
            __join = join
[...]

I can get something working by bouncing through global values, but it
looks awful and I think it's a source of a bug due too values being
redefined.

Thanks,
Andrew


From andrew at acooke.org  Tue Aug 11 22:14:27 2009
From: andrew at acooke.org (andrew cooke)
Date: Tue, 11 Aug 2009 19:14:27 -0700 (PDT)
Subject: Frustrated with scopes
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
Message-ID: 

correction: "source" and "join" are undefined.  Sorry, Andrew



From jstroud at mbi.ucla.edu  Tue Aug 11 22:15:07 2009
From: jstroud at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 19:15:07 -0700
Subject: hashability
In-Reply-To: <3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
Message-ID: 

Carl Banks wrote:
> On Aug 11, 5:54 pm, James Stroud  wrote:
> 
>> To prevent users of one of my libraries from falling into this and
>> similar traps (which have potentially problematic consequences),
> 
> Even so, I would consider whether some of your users might, like me,
> also find this terribly useful, and if so (probably a few will unless
> they are all novices), allow them to disable or disregard this check.

I realize I left out my use. The intent of the function is to flag 
objects that will make useful keys for a persistent dictionary. The 
{C():4}[C()] example demonstrates why I want to avoid certain types of 
keys--I don't want users to do things like {C():4, C():4}, which python 
happily allows but falls apart at the level of persistence.

However, I also want to avoid isinstance() and/or type checking in order 
to allow maximal flexibility so that users don't have to work too hard 
to make their keys.

> I wouldn't call the function "hashable".  Class instances like C() are
> hashable whether you approve or not.  Something like
> "deliberately_hashable" would be a better name.

I chose "keyable".

>> Can anyone think of boundary cases I might be missing with this approach?
> 
> It is possible to redefine == operator by defining __ne__ instead of
> __eq__, at least on Python 2.5, so you should keep that in mind.

Thanks for this hint. I've already put it in.

James


From jus__ at hotmail.com  Tue Aug 11 22:22:27 2009
From: jus__ at hotmail.com (Jus)
Date: Tue, 11 Aug 2009 22:22:27 -0400
Subject: Unsigned char array to an unsigned longlong array
Message-ID: 

Hello,

 

I'm using Python 2.6.2.

Is there a way to have an Array of unsigned longlong (C Type: unsigned
longlong, Minimum size if bytes: 8) ?

I found a page on the internet
(http://mail.python.org/pipermail/patches/2005-April/017430.html
 ), but I'm not quite sure if it is available.

 

 

What I want to do is to store an array of bytes in an array of longlongs.

To workaround this issue, I have tried to use the double array (TypeCode
'd'), since the size in bytes is the same (8 for instance).

But it gives me strange result. Please look at the example:

 

import array

myByteArray = array.array('B', [1,2,3,4,5,6,7,8])

>> myByteArray = array('B', [1, 2, 3, 4, 5, 6, 7, 8])

 

myLongArray = array.array('L', myByteArray.tostring() )

>> myLongArray = array('L', [67305985L, 134678021L])

 

myDoubleArray = array.array('d', myByteArray.tostring() )

>> myDoubleArray = array('d', [5.447603722011605e-270])

 

If we convert the byte array to an hex form, we will get for the long array:
[04030201, 08070605].

If we convert this hex array to decimal, we then get the Long Array:
[67305985, 134678021].

 

Now, if we do the same exercise for the double array, the hex form will look
like: [0807060504030201].

And the decimal value would be: [5.784376957523072e+17].

 

Where does the 5.447603722011605e-270 value comes from ?

 

 

Thanks for your help,

Francis

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From afriere at yahoo.co.uk  Tue Aug 11 22:24:39 2009
From: afriere at yahoo.co.uk (Asun Friere)
Date: Tue, 11 Aug 2009 19:24:39 -0700 (PDT)
Subject: hashability
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
Message-ID: <62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>

On Aug 12, 12:15?pm, James Stroud  wrote:

> I realize I left out my use. The intent of the function is to flag
> objects that will make useful keys for a persistent dictionary. The
> {C():4}[C()] example demonstrates why I want to avoid certain types of
> keys--I don't want users to do things like {C():4, C():4}, which python
> happily allows but falls apart at the level of persistence.

What am I missing here?  How, in terms of persistence, is {C():4, C():
4} conceptually different from {'spam':4, 'ham':4}?


From davea at ieee.org  Tue Aug 11 22:29:20 2009
From: davea at ieee.org (Dave Angel)
Date: Tue, 11 Aug 2009 22:29:20 -0400
Subject: adding multiple new values to the same key in a dictionary
In-Reply-To: <4A8192A30200008C00014AB9@redhorse.forestry.uga.edu>
References: <4A8192A30200008C00014AB9@redhorse.forestry.uga.edu>
Message-ID: <4A822900.7030008@ieee.org>

Krishna Pacifici wrote:
> Hi,
> I want to be able to add multiple new values to a key in a dictionary.
>
> I have tried the following:
>
> sec_dict_clean=
> {88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85]}
>
> for i in range(len(sec_dict_clean.values())):
>     for j in range(len(sec_dict_clean.values()[i])):
>         sec_dict_clean.setdefault(key,[]).append(blocks[sec_dict_clean.values()[i][j]].abundance)
>
> where blocks[...].abundance gives me a single value from an object,
>
> but this gives me the following:
>
> sec_dict_clean=
> {88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85, 4, 12, 11, 6, 9, 12, 11, 7, 10, 10, 12, 9, 6, 12, 15, 9, 8, 12, 15, 12, 12]}
>
> instead I want each abundance (starts with 4, 12...) to be associated with each of the values so that it would look like this:
>
> sec_dict_clean=
> {88: ([87, 89, 78, 98], [4,12,11,6]), 58: ([57, 59, 48, 68], [9,12,11,7]), 69: ([79], [10])...}
>
> You can see there are several errors here (I have more things being appended than there are values in the dictionary), but I really just want to know how to add multiple values to the same key in a dictionary.
>
> Thanks for any help,
> Krishna
>
>
>
>   
You're really distorting the purposes of both dictionary and list here.  
It makes your code totally unreadable, which makes it hard to write, and 
hard to debug.

A dictionary is a mapping between key and value, where each key has 
exactly one value.  You cannot add another one to it.   All you can do 
is make the value something which is itself a collection.  Now, your 
desired dictionary looks achievable, almost.  If you change the parens 
(tuple) to square brackets (list), then it'll work.
    So key 88 has a single value, which is a list of two items.  Each of 
those items is itself a list with 4 items.  And each of those items are 
integers.

But then I got bogged down in your sample code.  I tried to simplify it, 
replacing the first two lines with these three:

for i, key in enumerate(sec_dict_clean):
    val = sec_dict_clean[key]
    for j, xxx in enumerate(val):
        
???sec_dict_clean.setdefault(key,[]).append(blocks[sec_dict_clean.values()[i][j]].abundance)

But I can't make head nor tail of the third line.  You didn't have a 
variable key, so I don't know if I'm using the same one..  Since I can't 
figure out what you were trying to do, I can't see how to fix it.

I think the problem here is you're trying to reorganize the data as well 
as adding to it, in a single pass.  So is some previous code generating 
the dictionary incorrectly, and instead of fixing that, you're trying to 
reorganize it here?

To make each dictionary value a list of lists:

sec_dict_clean=
{88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85]}

for key in sec_dict_clean:
    sec_dict_clean[key] = [sec_dict_clean[key]]

now,  the dict looks like:
{88: [[87, 89, 78, 98, 3]], 58: [[57, 59, 48, 68]], 69: [[79]], 95: 
[[94, 96, 85]]}

At this point, if you have some interesting data to add to it, you can 
just append a new list to
     dict[key]

In an earlier message, you mentioned fields a and b, and assuming this 
is a similar problem, it would seem that 87 is somehow associated with 
4, and 89 with 12, and so on.  If that's the case, perhaps your desired 
final structure might look more like:

{88: [[87,4], [89,12], [78, 11],[98, 6],   58: [[57, 9], [59, 12], [48, 11], [68, 7]],   69: ...}


In this case, the structure is entirely different.  But the approach is 
the same.  And at least you'd be getting closer to the object approach 
where  [87,4] is replaced by an object of some type.

BTW, please don't top-post.  When you reply to this one, put your reply 
at the end, or sometimes interspersed.  But if you put it at the 
beginning, it's out of order.

DaveA



From davea at ieee.org  Tue Aug 11 22:54:49 2009
From: davea at ieee.org (Dave Angel)
Date: Tue, 11 Aug 2009 22:54:49 -0400
Subject: Need cleanup advice for multiline string
In-Reply-To: 
References: 
Message-ID: <4A822EF9.2090907@ieee.org>

Robert Dailey wrote:
> Hey guys. Being a C++ programmer, I like to keep variable definitions
> close to the location in which they will be used. This improves
> readability in many ways. However, when I have a multi-line string
> definition at function level scope, things get tricky because of the
> indents. In this case indents are serving two purposes: For syntax and
> actual text output. The tabs for function scope should not be included
> in the contents of the string. Below is the code I am trying to
> improve. Notice how it looks ugly/unreadable because of the way the
> string contents are shifted all the way to the left edge of the
> document. This breaks the flow of scope. Would you guys solve this
> problem by moving failMsg into global scope? Perhaps through some
> other type of syntax?
>
> Help is appreciated!
>
> def RunCommand( commandList ):
>    commandString =
>    print( 'Running Command:',  )
>    cmd = subprocess.Popen( commandList )
>    returnCode = cmd.wait()
>    if returnCode:
>       failMsg = '''\
> *************************************************
> The following command returned exit code [{:#x}].
> This represents failure of some form. Please review
> the command output for more details on the issue.
> ------------
> {}
> *************************************************
> '''
>       commandString = ' '.join( commandList )
>       raise CommandFailure( failMsg.format( returnCode,
> commandString ) )
>
>   
No, don't put it in global scope.  Put it externally, so it can be 
readily localized for international markets.

DaveA


From abecedarian314159 at yahoo.com  Tue Aug 11 23:22:56 2009
From: abecedarian314159 at yahoo.com (William)
Date: Tue, 11 Aug 2009 20:22:56 -0700 (PDT)
Subject: Is there any package implanation the following arithmetics?
In-Reply-To: 
References: 
	
Message-ID: <904309.72680.qm@web110602.mail.gq1.yahoo.com>

What you want is:
http://www.cgal.org/

I believe it has python bindings.

Cheers,
William



________________________________
From: Emile van Sebille 
To: python-list at python.org
Sent: Tuesday, August 11, 2009 12:49:19 PM
Subject: Re: Is there any package implanation the following arithmetics?

On 8/11/2009 1:49 AM zhongshq said...
> Hi,
> 
> I wonder if there has any package can check whether two rectangles are
> overlap, is a dot inside or outside a polygon, etc.

PythonCad at http://sourceforge.net/projects/pythoncad/ has intersections built in.

Emile

-- http://mail.python.org/mailman/listinfo/python-list



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From lanyjie at yahoo.com  Wed Aug 12 00:15:39 2009
From: lanyjie at yahoo.com (Yingjie Lan)
Date: Tue, 11 Aug 2009 21:15:39 -0700 (PDT)
Subject: releasing expy 0.1.1
Message-ID: <932447.5519.qm@web54201.mail.re2.yahoo.com>


Hi all,

This is to announce the release of expy 0.1.1 for those who are interested. Thanks a lot for the interest from this list. For more information, please see 

http://expy.sf.net/

Note: expy is an express way to extend Python. Why consider expy? Here are some good reasons:

(I). WYSIWYG. The expy project enables you to write your module in Python the way your extension would be (WYSIWYG), and meanwhile write your implementation in pure C. You specify your modules, functions, methods, classes, and even their documentations the usual way of writing your Python correspondences. Then your provide your implementation to the functions/methods by returning a multi-line string. By such an arrangement, everything falls in its right place, and your extension code becomes easy to read and maintain. Also, the generated code is very human-friendly.

(II). You only provide minimal information to indicate your intension of how your module/class would function in Python. So your extension is largely independent from the Python extension API. As your interaction with the Python extension API is reduced to minimal (you only care about the functionality and logic), it is then possible that your module written in expy can be independent of changes in the extension API.

(III). The building and setup of your project can be automatically done with the distutil tool. In the tutorial, there are ample examples on how easily this is achieved.

(IV). Very light weight. The expy tool is surprisingly light weight dispite of its powerful ability, as it is written in pure Python. There is no parser or compiler for code generation, but rather the powerful reflexion mechanism of Python is exploited in a clever way to generate human-friendly codes. Currently, generating code in C is supported, however, the implementation is well modularized and code generation in other languages such as Java and C++ should be easy.

While there are already a couple of other projects trying to simply this task with different strategies, such as Cython, Pyrex and modulator, this project is unique and charming in its own way. All you need is the WYSIWYG Python file for your module extension, then expy takes care of everything else. What follows in this documentation is on how to extend Python in C using expy-cxpy: the module expy helps define your module, while module cxpy helps generate C codes for your defined module.

regards,

Yingjie


      


From arphaksad at gmail.com  Wed Aug 12 00:27:47 2009
From: arphaksad at gmail.com (naaman)
Date: Tue, 11 Aug 2009 21:27:47 -0700 (PDT)
Subject: fileinput
Message-ID: 

I'm writing my first Python script and
I want to use fileinput to open a file in r+ mode.
Tried fileinput.input(sys.argv[1:],"r+") but that didn't work.
ANy ideas?

Need to find and overwrite a line in a file several times.
I can do it using open and seek() etc. but was wondering if I can use
fileinput.

thanks;



From bouncyinc at gmail.com  Wed Aug 12 00:28:22 2009
From: bouncyinc at gmail.com (John Haggerty)
Date: Tue, 11 Aug 2009 22:28:22 -0600
Subject: getting a "simple" program to work
In-Reply-To: 
References: 
Message-ID: 

just checking to see if there is any input that may have been misdirected to
a spam filter.
Would love to see some feedback if I may

On Sun, Aug 9, 2009 at 6:42 PM, John Haggerty  wrote:

> ok so I know this is one of those "weird" requests but here me out.
> So far I have an issue with a package for python called "libgmail" which is
> basically a gmail interface for python to send messages remoetly.
>
> Works ok except that the 'sendMessage' routine is bad.
>
> This is included in the above attachment
>
> it's used in a program called "ogss" which is an sms interface to gmail to
> basically read gmail and then have a command done on a remote machine and
> then spat out on the local machine to a log file that's opened and then
> emailed back
>
> problem is that the sending back routine fails.
>
> Now I've found a program that will more or less do what is requied but it's
> not really exactly what would be used in that it doesn't use the libgmail
> routine.
>
> So far the maintainer of both packages seem to be afk or not having their
> routines fixed and so far debian/Unbuntu claim that the last version of the
> package has been fixed :(
>
> Is there a recommendatin of how to combine/alter so that ogss can transmit?
> My main issue is that python is lesser known to me than Chinese (which I
> also don't know).
>
> My idea of this is to have a remote email timeclock program which could
> then be scripted with any language or just "echo >>blah" if necessary.
>
> Thanks in advance :)
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From clp2 at rebertia.com  Wed Aug 12 00:46:49 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Wed, 12 Aug 2009 00:46:49 -0400
Subject: getting a "simple" program to work
In-Reply-To: 
References: 
Message-ID: <50697b2c0908112146q6e12650dt914518166b4fae72@mail.gmail.com>

On Sun, Aug 9, 2009 at 8:42 PM, John Haggerty wrote:
> ok so I know this is one of those "weird" requests but here me out.
> So far I have an issue with a package for python called "libgmail" which is
> basically a gmail interface for python to send messages remoetly.
> Works ok except that the 'sendMessage' routine is bad.

How is it "bad" precisely? Be specific (e.g. error message(s),
description of observed incorrect behavior).

> This is included in the above attachment
> it's used in a program called "ogss" which is an sms interface to gmail to
> basically read gmail and then have a command done on a remote machine and
> then spat out on the local machine to a log file that's opened and then
> emailed back
> problem is that the sending back routine fails.

Which routine is that exactly? Please also specify exactly how it is
failing (e.g. error message(s), description of observed incorrect
behavior).

I apologize if these questions are answered in comments in the
attachments, but to be honest, the fact that you didn't (or couldn't)
put the specific problematic sections of code (and/or error messages)
inline in your message makes it less likely that people (such as
myself) will try to help you due to the volume of code you're making
people wade through (i.e. people tend not to read large code dumps,
/especially/ in attachments).

Cheers,
Chris
-- 
http://blog.rebertia.com


From bouncyinc at gmail.com  Wed Aug 12 01:02:57 2009
From: bouncyinc at gmail.com (John Haggerty)
Date: Tue, 11 Aug 2009 23:02:57 -0600
Subject: getting a "simple" program to work
In-Reply-To: <50697b2c0908112146q6e12650dt914518166b4fae72@mail.gmail.com>
References: 
	<50697b2c0908112146q6e12650dt914518166b4fae72@mail.gmail.com>
Message-ID: 

On Tue, Aug 11, 2009 at 10:46 PM, Chris Rebert  wrote:

> On Sun, Aug 9, 2009 at 8:42 PM, John Haggerty wrote:
> > ok so I know this is one of those "weird" requests but here me out.
> > So far I have an issue with a package for python called "libgmail" which
> is
> > basically a gmail interface for python to send messages remoetly.
> > Works ok except that the 'sendMessage' routine is bad.
>
> How is it "bad" precisely? Be specific (e.g. error message(s),
> description of observed incorrect behavior).
>

In regards to bad would be failing to transmit claiming that the submittal
is wrong for the transmit string.

(where username is my gmail username and "password" is my gmail password to
the test account, 6666666969 is the mobile number in question '00' is my
"carrier id" from the ogss code example which is just an array location from
a preformatted part of the string [probably from wikipedia on mobile carrier
email addresses to cell phones], I actually got desperate and commented out
the first attempt to transmit which I located in the code as just the
"instructions" the code fails on re-transmission, I later on looked at the
file and located that it was a zero byte file of no content. The program
itself looks for a command from the user's cell phone directly from mms sent
to the target gmail account prefaced by "Ogss" and anything else is treated
as a command but since the command failed on the first transmit I don't
think it's the command per se).

owner at bouncyinc:~/Desktop/OGSS$ python ogss.py username password 6666666969
00
Starting ogss
Logfile at:/home/owner/ogss.log
Opening log file for reading
Parsing user input
Connecting to Gmail
Logging into Gmail
Opening log file for writing
Listening for commands
Processing Command
ls: unrecognized option `---------------------------------------------'
Try `ls --help' for more information.
Seding back results
Traceback (most recent call last):
  File "ogss.py", line 127, in 
    main(sys.argv)
  File "ogss.py", line 110, in main
    account.sendMessage(tosend)
  File "/usr/lib/python2.5/site-packages/libgmail.py", line 615, in
sendMessage
    raise GmailSendError, resultInfo[SM_MSG]
libgmail.GmailSendError: Please try again.

I traced the result to the sendMessage routine and noted that anytime it
tries to send anything it fails this also fails with the standard "docs"
package for libgmail 0.30 docs from the maintainer's site.

Now the part where it *does* fail is where it has an issue with looking at
the trailing info but then it would have logged the info to the file and
emailed me back junk (which it didn't)

I assume this could be done on any system just replace 'ls' with 'dir' or
the equivalent.


>
> > This is included in the above attachment
> > it's used in a program called "ogss" which is an sms interface to gmail
> to
> > basically read gmail and then have a command done on a remote machine and
> > then spat out on the local machine to a log file that's opened and then
> > emailed back
> > problem is that the sending back routine fails.
>
> Which routine is that exactly? Please also specify exactly how it is
> failing (e.g. error message(s), description of observed incorrect
> behavior).
>
> I apologize if these questions are answered in comments in the
> attachments, but to be honest, the fact that you didn't (or couldn't)
> put the specific problematic sections of code (and/or error messages)
> inline in your message makes it less likely that people (such as
> myself) will try to help you due to the volume of code you're making
> people wade through (i.e. people tend not to read large code dumps,
> /especially/ in attachments).
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>
That's ok I understand I hope that helps at least in part.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From ben+python at benfinney.id.au  Wed Aug 12 01:11:22 2009
From: ben+python at benfinney.id.au (Ben Finney)
Date: Wed, 12 Aug 2009 15:11:22 +1000
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
Message-ID: <87skfxehvp.fsf@benfinney.id.au>

Dave Angel  writes:

> But I wanted to comment on the (c) remark.  If you're in the US,
> that's the wrong abbreviation for copyright.  The only recognized
> abbreviation is (copr).

More reading on this:

    
    

In brief: To be a legally-recognised copyright notice under US law, it
must begin with ?Copyright?, or one of the abbreviations ?Copr.? or the
exact symbol ???. As you rightly point out, neither ?(c)? nor ?(C)? have
any legal status as a copyright marker.

The Berne Convention, by making copyright active on *every* creative
work of expression, even in the total *absence* of a copyright notice,
essentially undermines the force of this and makes it exceedingly
difficult to divest a work of copyright. But that's a whole 'nother
depressing mess.

-- 
 \         ?A politician is an animal which can sit on a fence and yet |
  `\                  keep both ears to the ground.? ?Henry L. Mencken |
_o__)                                                                  |
Ben Finney


From nospamjstroudmapson at mbi.ucla.edu  Wed Aug 12 01:32:50 2009
From: nospamjstroudmapson at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 22:32:50 -0700
Subject: hashability
In-Reply-To: <62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
Message-ID: 

Asun Friere wrote:
> On Aug 12, 12:15 pm, James Stroud  wrote:
> 
>> I realize I left out my use. The intent of the function is to flag
>> objects that will make useful keys for a persistent dictionary. The
>> {C():4}[C()] example demonstrates why I want to avoid certain types of
>> keys--I don't want users to do things like {C():4, C():4}, which python
>> happily allows but falls apart at the level of persistence.
> 
> What am I missing here?  How, in terms of persistence, is {C():4, C():
> 4} conceptually different from {'spam':4, 'ham':4}?

You should be more imaginative.


From nospamjstroudmapson at mbi.ucla.edu  Wed Aug 12 01:33:50 2009
From: nospamjstroudmapson at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 22:33:50 -0700
Subject: hashability
In-Reply-To: <77eda964-a6ee-496b-9c5f-5391663099e0@b14g2000yqd.googlegroups.com>
References: 
	<77eda964-a6ee-496b-9c5f-5391663099e0@b14g2000yqd.googlegroups.com>
Message-ID: 

Asun Friere wrote:
> Perhaps the best solution would be for the unitiated to correct their
> misaprehensions

Can you come give a class to my users?


From nospamjstroudmapson at mbi.ucla.edu  Wed Aug 12 01:51:12 2009
From: nospamjstroudmapson at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 22:51:12 -0700
Subject: Frustrated with scopes
In-Reply-To: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
Message-ID: 

andrew cooke wrote:
> Is there a way to make this work (currently scope and join are
> undefined at runtime when the inner class attributes are defined):
> 
> class _StreamFactory(object):
> 
>     @staticmethod
>     def __call__(lines, source, join=''.join):
> 
>         class Line(object):
> 
>             __source = source
>             __join = join
> [...]


It would be helpful if you were to describe the type of behavior you expect.

I assume you will return the newly created Line class when you call an 
instance of _StreamFactory? There may be some things about the above 
that you might be overlooking:

1. __call__ does not supersede the __init__ constructor of _StreamFactory.
2. __source and __join are name-mangled in later versions of python. 
They will be attributes of the returned Line class named _Line_source 
and _Line_join respectively.

Rather than make _StreamFactory a class, you will probably get the 
behavior you desire if you simply make it a function:

def stream_factory:
   class Line(object):
     __source = source
     __join = join
   # etc.
   return Line

And then don't forget that double underscores produce name mangling and 
you'll be set.

James




From petshmidt at googlemail.com  Wed Aug 12 01:52:50 2009
From: petshmidt at googlemail.com (Pet)
Date: Tue, 11 Aug 2009 22:52:50 -0700 (PDT)
Subject: better way?
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
	<87skfyjen8.fsf@golux.woodcraft.me.uk> 
	
Message-ID: <6733c8fe-9ef8-4010-9b23-27538e19d8ff@c29g2000yqd.googlegroups.com>

On 11 Aug., 22:19, "Rami Chowdhury"  wrote:
> Ah, my apologies, I must have been getting it confused with ON UPDATE ?
> [things]. Thanks for correcting me.
>
> On Tue, 11 Aug 2009 13:10:03 -0700, Matthew Woodcraft ?
>
>  wrote:
> > "Rami Chowdhury"  writes:
>
> >> IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than
> >> MySQL...
>
> > PostgreSQL does not have ON DUPLICATE KEY UPDATE.
>
> > The SQL standard way to do what the OP wants is MERGE. PostgreSQL
> > doesn't have that either.
>
> > -M-
>
> --
> Rami Chowdhury
> "Never attribute to malice that which can be attributed to stupidity" -- ?
> Hanlon's Razor
> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)

So, I'm doing it in right way?
What about building columns? map(lambda s: s + ' = %s', fields)
Is that o.k.?

thanks


From chris at rebertia.com  Wed Aug 12 01:52:51 2009
From: chris at rebertia.com (Chris Rebert)
Date: Wed, 12 Aug 2009 01:52:51 -0400
Subject: hashability
In-Reply-To: <62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
Message-ID: <50697b2c0908112252l758c32b9u701daf09a7810a09@mail.gmail.com>

2009/8/11 Asun Friere :
> On Aug 12, 12:15?pm, James Stroud  wrote:
>
>> I realize I left out my use. The intent of the function is to flag
>> objects that will make useful keys for a persistent dictionary. The
>> {C():4}[C()] example demonstrates why I want to avoid certain types of
>> keys--I don't want users to do things like {C():4, C():4}, which python
>> happily allows but falls apart at the level of persistence.
>
> What am I missing here? ?How, in terms of persistence, is {C():4, C():
> 4} conceptually different from {'spam':4, 'ham':4}?

Thought Experiment:
Consider, for each dict, the case of pickling it twice to 2 separate files.
When loaded from both files into the same program, the spam-ham dicts
will work as expected between each other.
The dicts with C()s will not. For example, assuming the unpickled
dicts are `cs1` and `cs2`, cs1[cs2.keys()[0]] will raise KeyError.

Cheers,
Chris
-- 
http://blog.rebertia.com


From greg at cosc.canterbury.ac.nz  Wed Aug 12 02:06:13 2009
From: greg at cosc.canterbury.ac.nz (greg)
Date: Wed, 12 Aug 2009 18:06:13 +1200
Subject: Bug in format specification in Python 3?
In-Reply-To: 
References: 
Message-ID: <7ef4dkF26f4duU1@mid.individual.net>

Robert Dailey wrote:

> I notice that the '0x' portion is counted in the width, which was
> specified as 8. This seems wrong to me. Is this by design? If so, why?

Yes, it's the total field width. This is consistent with
the other formats, in which it includes decimal points,
signs, etc.

If you don't want that, then write the format string as

   'This is a hex number: 0x{:08x}'

-- 
Greg


From greg at cosc.canterbury.ac.nz  Wed Aug 12 02:17:06 2009
From: greg at cosc.canterbury.ac.nz (greg)
Date: Wed, 12 Aug 2009 18:17:06 +1200
Subject: Social problems of Python doc [was Re: Python docs disappointing]
In-Reply-To: <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
Message-ID: <7ef51uF2g36t5U1@mid.individual.net>

rurpy at yahoo.com wrote:
> Such a reorg is not a simple matter
> of moving a file from here to there.  It will require a lot
> moving about of sections and a lot of word-smithing to glue
> them back together again in a coherent way.

Concerning this particular issue, not everyone would
agree that the doc sections in question are misplaced.

In Python the distinction between builtin and library
types is fairly blurry. There are advantages to having
them all documented in one place -- when looking for
info about a type, you don't have to try to guess
whether it's considered built-in or not to know which
manual to look in.

-- 
Greg


From nospamjstroudmapson at mbi.ucla.edu  Wed Aug 12 02:17:08 2009
From: nospamjstroudmapson at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 23:17:08 -0700
Subject: Frustrated with scopes
In-Reply-To: 
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
	
Message-ID: 

James Stroud wrote:
 > def stream_factory:
 >   class Line(object):
 >     __source = source
 >     __join = join
 >   # etc.
 >   return Line
 >

of course I meant "def stream_factory(lines, source, join=''.join):"

James



From afriere at yahoo.co.uk  Wed Aug 12 02:18:59 2009
From: afriere at yahoo.co.uk (Asun Friere)
Date: Tue, 11 Aug 2009 23:18:59 -0700 (PDT)
Subject: hashability
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
	
Message-ID: 

On Aug 12, 3:32?pm, James Stroud 
wrote:

> You should be more imaginative.

I'm by no means discounting that there might be some actual problem
you're trying to solve here, but I honestly can't see it.

There really is no need to get personal about this, so rather than
asking for a level of imagination from me, (which I apparently lack),
please just explain to me how {one_instance_of_a_hashable_class : val,
another_instance_of_a_hashable_class :val} is conceptually different
{one_instance_of_class_str: val, another_instance_of_class_str: val},
in terms of persistence.

If I am missing something here, I would actually like to know.  If on
the other hand, I'm not, then rather at taking umbrage, you might want
instead to save yourself the effort of solving a non-existent problem?

> Can you come give a class to my users?

No.

However, I think it's fairly central to the notion of a class that it
is a template for creating different instances which themselves have a
unique identity.  And that subsequent calls to a class' constructor
ought to create unique instances of that class (subject perhaps to
implementation tricks such as interning).  If it is not obvious that {C
():4}[C()] invovles subsequent calls to C's constructor, then that
very example is itself didactic.


From clp2 at rebertia.com  Wed Aug 12 02:25:04 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Wed, 12 Aug 2009 02:25:04 -0400
Subject: hashability
In-Reply-To: <62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
Message-ID: <50697b2c0908112325h2610d261x487dd62caed57172@mail.gmail.com>

2009/8/11 Asun Friere :
> On Aug 12, 12:15?pm, James Stroud  wrote:
>
>> I realize I left out my use. The intent of the function is to flag
>> objects that will make useful keys for a persistent dictionary. The
>> {C():4}[C()] example demonstrates why I want to avoid certain types of
>> keys--I don't want users to do things like {C():4, C():4}, which python
>> happily allows but falls apart at the level of persistence.
>
> What am I missing here? ?How, in terms of persistence, is {C():4, C():
> 4} conceptually different from {'spam':4, 'ham':4}?

Consider the case of pickling the data twice to 2 separate files.
When loaded from both files into the same program, the spam-ham dicts
will work as expected.
The C()s will not. For cs1[cs2.keys()[0]] will raise KeyError.

Cheers,
Chris
-- 
http://blog.rebertia.com


From clp2 at rebertia.com  Wed Aug 12 02:26:31 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Wed, 12 Aug 2009 02:26:31 -0400
Subject: hashability
In-Reply-To: <50697b2c0908112325h2610d261x487dd62caed57172@mail.gmail.com>
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
	<50697b2c0908112325h2610d261x487dd62caed57172@mail.gmail.com>
Message-ID: <50697b2c0908112326q7908190btff3352979a02dc4f@mail.gmail.com>

On Wed, Aug 12, 2009 at 2:25 AM, Chris Rebert wrote:
> 2009/8/11 Asun Friere :
>> On Aug 12, 12:15?pm, James Stroud  wrote:

Apologies for the possible repeated post. Gmail failed to mark the
draft as sent for some reason.

- Chris


From afriere at yahoo.co.uk  Wed Aug 12 02:29:41 2009
From: afriere at yahoo.co.uk (Asun Friere)
Date: Tue, 11 Aug 2009 23:29:41 -0700 (PDT)
Subject: hashability
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
	
Message-ID: <3a07642d-7876-4939-9c05-f09545afd41a@b15g2000yqd.googlegroups.com>

On Aug 12, 3:52?pm, Chris Rebert  wrote:

> Thought Experiment:
> Consider, for each dict, the case of pickling it twice to 2 separate files.
> When loaded from both files into the same program, the spam-ham dicts
> will work as expected between each other.
> The dicts with C()s will not. For example, assuming the unpickled
> dicts are `cs1` and `cs2`, cs1[cs2.keys()[0]] will raise KeyError.
>

Aha!

cheers.



From dstanek at dstanek.com  Wed Aug 12 02:31:55 2009
From: dstanek at dstanek.com (David Stanek)
Date: Wed, 12 Aug 2009 02:31:55 -0400
Subject: hashability
In-Reply-To: 
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
	
	
Message-ID: 

On Wed, Aug 12, 2009 at 2:18 AM, Asun Friere wrote:
> On Aug 12, 3:32?pm, James Stroud 
> wrote:
>
>> You should be more imaginative.
>
> I'm by no means discounting that there might be some actual problem
> you're trying to solve here, but I honestly can't see it.

How about a cache? Hashing by id means nothing across machines or even
process runs on the same machine.

-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek


From nospamjstroudmapson at mbi.ucla.edu  Wed Aug 12 02:52:17 2009
From: nospamjstroudmapson at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 23:52:17 -0700
Subject: hashability
In-Reply-To: 
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
	
	
Message-ID: 

Asun Friere wrote:
> On Aug 12, 3:32 pm, James Stroud 
> wrote:
> 
>> You should be more imaginative.
> 
> I'm by no means discounting that there might be some actual problem
> you're trying to solve here, but I honestly can't see it.
> 
> There really is no need to get personal about this, so rather than
> asking for a level of imagination from me, (which I apparently lack),
> please just explain to me how {one_instance_of_a_hashable_class : val,
> another_instance_of_a_hashable_class :val} is conceptually different
> {one_instance_of_class_str: val, another_instance_of_class_str: val},
> in terms of persistence.

Sorry for being a twit. This list used to be quite nice but some people 
on this list got pretty abrasive. I couldn't tell you weren't one of 
these abrasive people from your post. I stopped giving the benefit of 
the doubt many moons ago and promptly enter attack mode at the slightest 
hint of abrasiveness. My attitude probably exacerbates the problem--but 
it sure does make me feel better.


Anyway, I think the problem has been described better than I'm able, but 
once an object goes to the file system, one can not take its hash value 
for granted. It is not possible to rely on the ability to recreate any 
arbitrary object de-novo and use the recreation as a key in proxy for 
the original object. I'm after this "je ne sais pas que l'appeler" 
quality of objects to use as keys (or to generate keys) for persistent 
dictionaries. Carl Banks suggested that this quality should not be 
called "hashable", so I'm calling it "keyable".


From garabik-news-2005-05 at kassiopeia.juls.savba.sk  Wed Aug 12 02:58:43 2009
From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk)
Date: Wed, 12 Aug 2009 06:58:43 +0000 (UTC)
Subject: create shell history with python
References: 
	<7ee8saF2e47vaU1@mid.uni-berlin.de>
Message-ID: 

Diez B. Roggisch  wrote:
> Joel Juvenal Rivera Rivera schrieb:
>> I been thinking how to make a 'bash like history shell' in python,
>> i don't know if with stdin and stdout i can accomplish this or do i
>> need something like curses and stuff like that, anyway im start to
>> figure this out.
>> Does any body has try this? or have any interesting idea?
> 
> Don't waste your time, use IPython :)
> 
> http://ipython.scipy.org/moin/
> 

for python 2.x only, unfortunately

-- 
 -----------------------------------------------------------
| Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__    garabik @ kassiopeia.juls.savba.sk     |
 -----------------------------------------------------------
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!


From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 03:08:06 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 07:08:06 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
	 <0291a21a$0$20639$c3e8da3@news.astraweb.com>
	<8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com>
	
	<1a0e1e6d-d902-4df7-8d35-850c4f62cc9c@e27g2000yqm.googlegroups.com>
Message-ID: 

On Tue, 11 Aug 2009 14:48:24 -0700, Douglas Alan wrote:

> In any case, my argument has consistently been that Python should have
> treated undefined escape sequences consistently as fatal errors, 

A reasonable position to take. I disagree with it, but it is certainly 
reasonable.


> not as warnings.

I don't know what language you're talking about here, because non-special 
escape sequences in Python aren't either errors or warnings:

>>> print "ab\cd"
ab\cd

No warning is made, because it's not considered an error that requires a 
warning. This matches the behaviour of other languages, including C and 
bash.



-- 
Steven


From afriere at yahoo.co.uk  Wed Aug 12 03:13:50 2009
From: afriere at yahoo.co.uk (Asun Friere)
Date: Wed, 12 Aug 2009 00:13:50 -0700 (PDT)
Subject: hashability
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
	
	
	
Message-ID: <108fe8d0-ec3c-49f4-b825-9303ac6aa8a9@32g2000yqj.googlegroups.com>

On Aug 12, 4:52?pm, James Stroud 
wrote:

> Sorry for being a twit.

Don't be ridiculous.  You haven't been a twit, I have!

I've just had a complete "blonde" moment here (with apologies to any
real blondes out there.  My only excuse is that I've been up to 02:30
for the last three nights running (or maybe it's the ageing process, a
cerebrovascular accident or something).

I just checked a class I recently wrote specifically for the purposes
of hashing a dict (in case I had made this error IRL).  Wouldn't you
know it, it's subclassed to tuple, and defines both __eq__ and
__cmp__.  Luckily when I write production code the guy who knows what
he's doing takes over.  And this in an app which compares keys from
different pickled files (representing DB holdings)?!  Of all things.

I can't believe how unfathomably stupid I've been.  I'm extremely
embarassed.  I think I'll just go out and shoot myself now.  Or get
some sleep.


From stefan_ml at behnel.de  Wed Aug 12 03:18:03 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Wed, 12 Aug 2009 09:18:03 +0200
Subject: ElementTree - Howto access text within XML tag element...
In-Reply-To: 
References: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
	<7ecm77F2fbf71U1@mid.uni-berlin.de>
	
Message-ID: <4a826cac$0$31870$9b4e6d93@newsspool3.arcor-online.net>

cmalmqui wrote:
> tree = etree.parse('10_07_2009 16_48_00_history.tcx')
> root = tree.getroot()
> 
> elem = root[0][0]
> 
> # iterate over all laps
> for i in range(1, len(elem)-1):

Note that you can iterate over elements as in

	for lap_element in elem:
	    # ...

Then use

	record = lap.find("recordtagname")

to find things inside the subtree. You can also use XPath-like expressions
such as

	all_intersting_elements =
		lap.findall("sometag/somechild//somedescendant")

Stefan


From afriere at yahoo.co.uk  Wed Aug 12 03:25:06 2009
From: afriere at yahoo.co.uk (Asun Friere)
Date: Wed, 12 Aug 2009 00:25:06 -0700 (PDT)
Subject: hashability
References: 
	
Message-ID: <25e7ee06-233d-4c8d-b5a9-384a4f5f1694@s15g2000yqs.googlegroups.com>

On Aug 12, 5:14?pm, Dennis Lee Bieber  wrote:

> c1 = C()
> c2 = C()
>
> {c1:4}[c2]
>
> to behave? That IS the equivalent of your statement -- two instances are
> two distinctly different entities...
>

Thankyou, that is EXACTLY the mistake I made that sent me off into
lunacy.

At the risk of further embarassment, the answer is that one would
expect it to behave analogously to:

c1 = int(x)
c2 = int(x)

{c1:4}[c2]

Or is my brain still on vacation?


From nospamjstroudmapson at mbi.ucla.edu  Wed Aug 12 03:33:01 2009
From: nospamjstroudmapson at mbi.ucla.edu (James Stroud)
Date: Wed, 12 Aug 2009 00:33:01 -0700
Subject: hashability
In-Reply-To: 
References: 
	
Message-ID: 

Dennis Lee Bieber wrote:
> On Tue, 11 Aug 2009 17:54:36 -0700, James Stroud 
> declaimed the following in gmane.comp.python.general:
> 
>>    ...
>>    py> {C():4}[C()]
>>    ------------------------------------------------------------
>>    Traceback (most recent call last):
>>      File "", line 1, in 
>>    : <__main__.C object at 0xe21610>
>>
>> The basis for the exception is that the two instances do not have the 
>> same hash() although conceptually they might seem equal to the 
>> unitiated. Were I to re-design python, I'd throw an exception in this 
>> case because of the ill-defined behavior one might expect if a C() 
>> serves as a key for a dict.
>>
> 	"A" C()... How would you expect
> 
> c1 = C()
> c2 = C()
> 
> {c1:4}[c2] 
> 
> to behave?


This seems like a subjective question. I think I demonstrated how it 
*does* behave, which is purely objective--and I know I can't do anything 
about that. But the subjective answer to the subjective question is that 
I would like an exception to be raised when the dictionary is 
constructed. I know an exception doesn't get thrown in the current 
incarnation of the python language. That is the objective reality of the 
situation which affronts my subjective notions of how reality should be.

That IS the equivalent of your statement -- two instances are
> two distinctly different entities...

Tell that to two different machines on two different days. Then bet the 
life of yourself and your nearest and dearest family on that fact and 
see whether you really want to take a hash value for granted. If a 
property of the python language fails the "bet the lives of your nearest 
and dearest on a consistent result" test, I call it "ill defined" and, 
subjectively speaking, I prefer exceptions to be thrown--And, by damned, 
I'll throw them myself if I have to.

"If it saves one life, it's worth it all."

James




From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 03:34:33 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 07:34:33 GMT
Subject: hashability
References: 
Message-ID: 

On Tue, 11 Aug 2009 17:54:36 -0700, James Stroud wrote:

> Hello All,
> 
> I wrote the function to test hashability of arbitrary objects. My reason
> is that the built-in python (2.5) hashing is too permissive for some
> uses. A symptom of this permissiveness comes from the ability to
> successfully hash() arbitrary objects:

No it doesn't.


>>> hash([])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: list objects are unhashable

Python successfully hashes *non*-arbitrary objects, including those that 
inherit from object.



>    py> class C(object): pass
>    ...
>    py> {C():4}[C()]
>    ------------------------------------------------------------
>    Traceback (most recent call last):
>      File "", line 1, in 
>    : <__main__.C object at 0xe21610>

Why would you expect that to succeed? The object you are using as the key 
is a different instance than the object you are looking up. Since your 
instances don't even compare equal, why would you expect them to hash 
equal?

>>> C() == C()
False



> The basis for the exception is that the two instances do not have the
> same hash() although conceptually they might seem equal to the
> unitiated. 

Yes, well, the ignorant and uninitiated frequently make mistakes. I feel 
your pain.



> Were I to re-design python, I'd throw an exception in this
> case because of the ill-defined behavior one might expect if a C()
> serves as a key for a dict.

It's not ill-defined, it's a perfectly reasonable design you just don't 
happen to like. It's quite useful for some.


> To prevent users of one of my libraries from falling into this and
> similar traps (which have potentially problematic consequences), I came
> up with this test for hashability:

That's not a test for hashability. That's a test for hashability and 
equality testing together.


> def hashable(k):
>    try:
>      hash(k)
>    except TypeError:
>      good = False
>    else:
>      good = (hasattr(k, '__hash__') and
>              (hasattr(k, '__eq__') or hasattr(k, '__cmp__')))
>    return good

The test for __hash__ is redundant, given that hash() has already 
succeeded.

It will wrongly reject classes that deliberately don't define equality, 
for whatever reason, and that *expect* the behaviour you are treating as 
an error.



> It works as I would like for most of the cases I can invent:
> 
>    py> all(map(hashable, [1,1.0,"",(1,2,3)])) True
>    py> any(map(hashable, [None, [1,2], {}, C(), __import__('sys')]))
>    False

Well there you go -- why on earth would you prohibit None as a dictionary 
key??? That's a serious failure.



-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 03:36:56 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 07:36:56 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
	 <0291a21a$0$20639$c3e8da3@news.astraweb.com>
	<8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com>
Message-ID: 

On Tue, 11 Aug 2009 13:20:52 -0700, Douglas Alan wrote:

> On Aug 11, 2:00?pm, Steven D'Aprano  cybersource.com.au> wrote:
> 
>> > test.cpp:1:1: warning: unknown escape sequence '\y'
>>
>> Isn't that a warning, not a fatal error? So what does temp contain?
> 
> My "Annotated C++ Reference Manual" is packed, and surprisingly in
> Stroustrup's Third Edition, there is no mention of the issue in the
> entire 1,000 pages. But Microsoft to the rescue:
> 
>      If you want a backslash character to appear within a string, you
>      must type two backslashes (\\)
> 
> (From http://msdn.microsoft.com/en-us/library/69ze775t.aspx)

Should I assume that Microsoft's C++ compiler treats it as an error, not 
a warning? Or is is this *still* undefined behaviour, and MS C++ compiler 
will happily compile "ab\cd" whatever it feels like?

 
> The question of what any specific C++ does if you ignore the warning is
> irrelevant, as such behavior in C++ is almost *always* undefined. Hence
> the warning.

So a C++ compiler which follows Python's behaviour would be behaving 
within the language specifications.

I note that the bash shell, which claims to follow C semantics, also does 
what Python does:

$ echo $'a s\trin\g with escapes'
a s     rin\g with escapes


Explain to me again why we're treating underspecified C++ semantics, 
which may or may not do *exactly* what Python does, as if it were the One 
True Way of treating escape sequences?


-- 
Steven


From petshmidt at googlemail.com  Wed Aug 12 03:49:50 2009
From: petshmidt at googlemail.com (Pet)
Date: Wed, 12 Aug 2009 00:49:50 -0700 (PDT)
Subject: better way?
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
Message-ID: <6126d193-5715-492f-8054-d9212bc6b87f@o32g2000yqm.googlegroups.com>

On 12 Aug., 09:14, Dennis Lee Bieber  wrote:
> On Tue, 11 Aug 2009 11:45:50 -0700 (PDT), Pet 
> declaimed the following in gmane.comp.python.general:
>
> > Oh, forgotten to mention. It's PostGres
>
> ? ? ? ? Really? There are still installations of an RDBMS that predates the
> commonalization of SQL?
>
> ? ? ? ? I suspect you mean PostgreSQL -- it IS a different beast from the
> older Postgres.

O, yeah. Of course it is PostgreSQL

>
> ? ? ? ? In either event -- my old books don't show an "all in one" solution.
>
> ? ? ? ? Best answer is probably to create some stored procedures which you
> call instead of plain INSERT; the stored procedure could then do
> whatever is needed to check for a duplicate (actually the easiest, I'd
> think, would be: if primary key is supplied, it is an UPDATE; if primary
> key is NULL or not supplied, it is an insert and the primary key will be
> auto-generated).

I don't really like the idea of stored procedure, because query would
depend on existence of it then. On the other side, it looks like best
option.

>
> --
> ? ? ? ? Wulfraed ? ? ? ? Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG
> ? ? ? ? wlfr... at ix.netcom.com ? ? HTTP://wlfraed.home.netcom.com/



From chris at simplistix.co.uk  Wed Aug 12 03:52:09 2009
From: chris at simplistix.co.uk (Chris Withers)
Date: Wed, 12 Aug 2009 08:52:09 +0100
Subject: httplib incredibly slow :-(
In-Reply-To: <4A81FDF5.6010508@simplistix.co.uk>
References: 	
	<4A81FDF5.6010508@simplistix.co.uk>
Message-ID: <4A8274A9.7000905@simplistix.co.uk>

Answering myself...

Chris Withers wrote:
>> In article ,
>> Chris Withers   wrote:
>>> Does anyone know of an alternative library for creating http requests 
>>> and getting their responses that's faster but hopefully has a similar 
>>> interface?
>>
>> PyCurl
> 
> This seems to be a wrapper around libcurl.
> 
> Does it work on Windows?

Not by my definition of work:

- there are no windows binaries for libcurl

- getting https support on windows seems pretty hit'n'miss:
http://stackoverflow.com/questions/197444/building-libcurl-with-ssl-support-on-windows

I'm still reeling from what seems to be such a huge problem with httplib 
that seem to be largely ignored :-(

Chris

-- 
Simplistix - Content Management, Batch Processing & Python Consulting
            - http://www.simplistix.co.uk


From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 03:58:59 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 07:58:59 GMT
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
Message-ID: 

On Tue, 11 Aug 2009 14:50:51 -0700, rurpy wrote:

>>> The issue tracker is fine for many things, but the process it provides
>>> is equivalent to peep-hole optimization.  How does one submit a
>>> tracker issue for something like the overall organization of the docs
>>> (for example, the mis-placement of things like data- types in the
>>> library manual rather than the language manual)?
>>
>> The same way you would submit a tracker issue for anything.
>>
>> "Documentation bug: Data types are misplaced in the library manual
>> instead of the language manual.
>>
>> Suggested alternative: move page docs.python.org/xyz.html to abc.html"
> 
> But that's the problem.  Such a reorg is not a simple matter of moving a
> file from here to there.  It will require a lot moving about of sections
> and a lot of word-smithing to glue them back together again in a
> coherent way.

That's no different from *any* major refactoring. The exact same problem 
exists for code as well as documentation. It's a solved problem for code, 
and it's a solved problem for documentation.

In some order:

Consensus that there is a problem that needs solving;
Volunteer(s) to do the work;
Somebody to take responsibility to check the changes in.


Sometimes, in the face of apathy or disagreement (which may very well be 
justified), you have to at least partly solve the problem *before* people 
will agree that it needed to be solved. Welcome to the real world.



> A tracker issue, even one that was fairly specific about how things
> should be reorganized but which did not provide all the needed changes
> (a large patch) would almost certainly be ignored or rejected.

Yes it would. Most patches are ignored, because the dev team are 
overworked, and if they don't see the need for a patch, they won't 
approve it.



> But
> providing a large patch raises two questions.  How likely is it to be be
> accepted? (Something anyone would want to know before investing the
> time.) And how to actually do the work needed to generate it (it could
> be a very large amount of work for an individual and I don't think it
> can be broken down into small independent issues.) How is one to test
> the waters as to acceptability, or solicit help, if one simply submits a
> tracker issue?

No, submitting a tracker issue is a necessary but not sufficient step. 
Without a tracker issue, you're very unlikely to have people agree to 
replace the existing docs with your docs, although a PEP would probably 
do it. (A PEP is significantly more effort than raising a tracker issue.)

You also have to get attention from those with check-in privileges. If 
they approve your patches, you're done. If they don't approve them, or 
fail to respond, you can try convincing them, or taking it to the Python-
Dev list and request somebody review your patches.

If you have no patches, perhaps because you're unwilling to invest the 
effort without a guarantee that it will be treated seriously, then you 
need to get some sort of consensus among the relevant people that the 
problem is worth solving.

Guess what? Sometimes others will disagree with you. What you see as the 
Worst. Docs. EVAR. may be seen as perfectly adequate, even excellent, by 
others. If this is the case, remember, Python isn't your product, you 
don't have veto over what goes into it. Feel free to publish your 
alternatives. Write a book. Go home and cry into your beer over it. 
Whatever. Sometimes you win, and sometimes you don't.

This is the same process whether dealing with code or documentation.


>> - if people are keen on a Python wiki, then by all means publish one,
>> just don't expect the Python dev team to build and manage it for you;
> 
> As luminous a Pythoneer as Fredrik Lundh set up a documentation wiki to
> collect user contributions but it has faded away.  If he couldn't pull
> it off then I'd say most other attempts without the backing of
> python.org are almost certainly doomed to failure.

Perhaps that's a good indication that a Python wiki *doesn't* fulfill a 
need in the community, and that despite what a few squeaky wheels think, 
the docs *are* doing a good job?



> As long as every "the docs
> sux" complaint is met here with the standard responses that I've
> mentioned, 

But they aren't met with such a so-called "standard response".


> rather than, "yes, they do have some problems, what do you
> think we should do about them?", 

We know that there are problems. We've said repeatedly that corrections 
and patches are welcome. We've repeatedly told you how to communicate 
your answer to the question of what should be done. None of this is good 
enough for you. I don't know what else you expect.


>> If you won't put in the effort, and you won't put in the money, then it
>> won't happen. Moaning that other people aren't putting in the money to
>> hire team of professional writers isn't productive, and moaning that
>> other people aren't putting in the effort to improve the docs isn't
>> either.
> 
> Eh?  I have a computer filled with software that I put no money or
> effort into, yet there it is.  

Ah yes, I'm sorry, I missed one other alternative: sit around and wait 
for somebody else to put in the money and/or effort.

> That some of us choose to
> invest it somewhere other than Python does not deprive of of our right
> to point out problems in Python when we note them.

Of course not. But it does mean that you won't be taken seriously, and 
you have no right to be taken seriously.



-- 
Steven


From jai_dgl at yahoo.co.in  Wed Aug 12 04:15:01 2009
From: jai_dgl at yahoo.co.in (Jey Simhan)
Date: Wed, 12 Aug 2009 01:15:01 -0700 (PDT)
Subject: Invitation to connect on LinkedIn
Message-ID: <1144938511.2842753.1250064901163.JavaMail.app@ech3-cdn13.prod>

LinkedIn
------------



   
I'd like to add you to my professional network on LinkedIn.

- Jey

Learn more:
https://www.linkedin.com/e/isd/682391381/2q9uIjvU/


 
------
(c) 2009, LinkedIn Corporation

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From simon at brunningonline.net  Wed Aug 12 04:21:24 2009
From: simon at brunningonline.net (Simon Brunning)
Date: Wed, 12 Aug 2009 09:21:24 +0100
Subject: Need cleanup advice for multiline string
In-Reply-To: <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> 
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
Message-ID: <8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com>

2009/8/11 Robert Dailey :
> On Aug 11, 3:40?pm, Bearophile  wrote:
>> There are gals too here.
>
> It's a figure of speech. And besides, why would I want programming
> advice from a woman? lol. Thanks for the help.

Give the attitudes still prevalent in our industry (cf
 and many more), I'm sorry to say that I
don't think this is funny.

-- 
Cheers,
Simon B.


From thorsten at thorstenkampe.de  Wed Aug 12 04:43:09 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Wed, 12 Aug 2009 10:43:09 +0200
Subject: Scraping Wikipedia with Python
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	
Message-ID: 

* Dotan Cohen (Tue, 11 Aug 2009 21:29:40 +0300)
> > ? ?Wikipedia has an API for computer access. ?See
> >
> > ? ? ? ?http://www.mediawiki.org/wiki/API
> >
> 
> Yes, I am aware of this as well. Does anyone know of a python class
> for easily interacting with it, or do I need to roll my own.

http://pypi.python.org/pypi?%3Aaction=search&term=wikipedia ?

Thorsten 


From hendrik at microcorp.co.za  Wed Aug 12 04:45:51 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Wed, 12 Aug 2009 10:45:51 +0200
Subject: Social problems of Python doc [was Re: Python docs disappointing]
In-Reply-To: <0291a07d$0$20639$c3e8da3@news.astraweb.com>
References: 
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
Message-ID: <200908121045.51808.hendrik@microcorp.co.za>

On Tuesday 11 August 2009 19:53:16 Steven D'Aprano wrote:

> You want community input into the docs, but you're not willing to give
> that input except to bitch and moan and sook that the tracker is no good.

wtf does the verb  "sook" mean?

I find:

sook
??/s?k/ Show Spelled Pronunciation [sook] Show IPA
Use sook in a Sentence
?noun
1. 	Australia and New Zealand. a timid, cowardly person, esp. a young person; 
crybaby.
?interjection
2. 	Midland U.S. (used to summon cows from the pasture).
Origin:
1890?95; prob. from earlier sense ?calf reared by hand,? perh. suck(-calf), 
with sp. repr. N England, Scots pron. of suck (but earliest cited pron. of 
sook is (so?o?k))

Sometimes English drives me crazy.

- Hendrik


From andreengels at gmail.com  Wed Aug 12 04:54:05 2009
From: andreengels at gmail.com (Andre Engels)
Date: Wed, 12 Aug 2009 10:54:05 +0200
Subject: looping through values in a dictionary and appending to a list
In-Reply-To: <4A817D6B0200008C00014A9B@redhorse.forestry.uga.edu>
References: <4A817D6B0200008C00014A9B@redhorse.forestry.uga.edu>
Message-ID: <6faf39c90908120154p41ac5211p64d7378d7e908190@mail.gmail.com>

On Tue, Aug 11, 2009 at 8:17 PM, Krishna
Pacifici wrote:
> Nevermind,
> got it.
>
> Sorry.
>
>>>> Krishna Pacifici 08/11/09 2:12 PM >>>
> Hi,
> I want to append the values of a dictionary to a list.? I have a dictionary
> sec_dict_clean and I want to append the values to a list, but am having a
> hard time looping through the values in the dictionary.
>
> I have tried something like this:
> lista=[]
> for i in sec_dict_clean.values():
> ??? for j in sec_dict_clean.values()[i]:
> ??? ??? lista.append(sec_dict_clean.values()[i])
>
> But I keep on getting an error:
> TypeError: list indices must be integers
>
> Any ideas on how to loop through values in a dictionary?

lista=[]
for value in sec_dict_clean.values():
    lista.append(value)

but even simpler would be:

lista = sec_dict_clean.values()


-- 
Andr? Engels, andreengels at gmail.com


From hendrik at microcorp.co.za  Wed Aug 12 05:04:35 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Wed, 12 Aug 2009 11:04:35 +0200
Subject: Need cleanup advice for multiline string
In-Reply-To: <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
Message-ID: <200908121104.35744.hendrik@microcorp.co.za>

On Tuesday 11 August 2009 22:52:34 Robert Dailey wrote:
> On Aug 11, 3:40?pm, Bearophile  wrote:
> > Robert Dailey:
> > > This breaks the flow of scope. Would you guys solve this
> > > problem by moving failMsg into global scope?
> > > Perhaps through some other type of syntax?
> >
> > There are gals too here.
> > This may
> > help:http://docs.python.org/library/textwrap.html#textwrap.dedent
> >
> > Bye,
> > bearophile
>
> It's a figure of speech. And besides, why would I want programming
> advice from a woman? lol. Thanks for the help.

Well it may come as a surprise to you, but it was a woman who
wrote one of the first compilers.

She became an Admiral in the US navy as a result.

If I recall correctly, her name was Grace Hooper.

How many compilers have you written from scratch,
without a compiler to help you?

:-)

- Hendrik



From fzgillani at live.com  Wed Aug 12 05:29:58 2009
From: fzgillani at live.com (fakhar Gillani)
Date: Wed, 12 Aug 2009 11:29:58 +0200
Subject: loops for ffmpeg CLI in python
Message-ID: 


 

Hi,

 

I am a begineer in Python. Actually I am encoding video files with different bitrates using ffmpeg CLI. I wanted to ask you that how can I make loops so that I can vary the bitrates in the CLI of ffmpeg??

 

I want to bulid a loop for the command below where i just want to vary the -vb parameter i.e. 10M. 

 

ffmpeg.exe -i sample.avi -y -f h264 -vb 10M -r 25 encoded_1000_0-05.h264

 

I have tried to make simple loops but it doest work:(

 

Can anyone here help me out?

 

Regards,

Gillani

 

 

_________________________________________________________________
Share your memories online with anyone you want.
http://www.microsoft.com/middleeast/windows/windowslive/products/photos-share.aspx?tab=1
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 05:32:01 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 09:32:01 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
	<494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com>
Message-ID: 

On Tue, 11 Aug 2009 14:29:43 -0700, Douglas Alan wrote:

> I need to preface this entire post with the fact that I've already used
> ALL of the arguments that you've provided on my friend before I ever
> even came here with the topic, and my own arguments on why Python can be
> considered to be doing the right thing on this issue didn't even
> convince ME, much less him. When I can't even convince myself with an
> argument I'm making, then you know there's a problem with it!


I hear all your arguments, and to play Devil's Advocate I repeat them, 
and they don't convince me either. So by your logic, there's obviously a 
problem with your arguments as well!

That problem basically boils down to a deep-seated philosophical 
disagreement over which philosophy a language should follow in regard to 
backslash escapes:

"Anything not explicitly permitted is forbidden"

versus  

"Anything not explicitly forbidden is permitted"

Python explicitly permits all escape sequences, with well-defined 
behaviour, with the only ones forbidden being those explicitly forbidden:

* hex escapes with invalid hex digits;

* oct escapes with invalid oct digits;

* Unicode named escapes with unknown names;

* 16- and 32-bit Unicode escapes with invalid hex digits.

C++ apparently forbids all escape sequences, with unspecified behaviour 
if you use a forbidden sequence, except for a handful of explicitly 
permitted sequences.

That's not better, it's merely different.

Actually, that's not true -- that the C++ standard forbids a thing, but 
leaves the consequences of doing that thing unspecified, is clearly a Bad 
Thing.



[...]

>> Apart from the lack of warning, what actually is the difference between
>> Python's behavior and C++'s behavior?
> 
> That question makes just about as much sense as, "Apart from the lack of
> a fatal error, what actually is the difference between Python's behavior
> and C++'s?"

This is what I get:

[steve ~]$ cat test.cc
#include 
int main(int argc, char* argv[])
{
std::cout << "x\yz" << std::endl;
return 0;
}
[steve ~]$ g++ test.cc -o test
test.cc:4:14: warning: unknown escape sequence '\y'
[steve at soy ~]$ ./test
xyz


So on at least one machine in the world, C++ simply strips out 
backslashes that it doesn't recognise, leaving the suffix. Unfortunately, 
we can't rely on that, because C++ is underspecified. Fortunately this is 
not a problem with Python, which does completely specify the behaviour of 
escape sequences so there are no surprises. 



[...]

>> I disagree with your sense of aesthetics. I think that having to write
>> \\y when I want \y just to satisfy a bondage-and-discipline compiler is
>> ugly. That's not to deny that B&D isn't useful on occasion, but in this
>> case I believe the benefit is negligible, and so even a tiny cost is
>> not worth the pain.
> 
> EXPLICIT IS BETTER THAN IMPLICIT.

Quoting the Zen without understanding (especially shouting) doesn't 
impress anyone. There's nothing implicit about escape sequences. \y is 
perfectly explicit. Look Ma, there's a backslash, and a y, it gives a 
backslash and a y!

Implicit has an actual meaning. You shouldn't use it as a mere term of 
opprobrium for anything you don't like.



>> > (2) That argument disagrees with the Python reference manual, which
>> > explicitly states that "unrecognized escape sequences are left in the
>> > string unchanged", and that the purpose for doing so is because it
>> > "is useful when debugging".
>>
>> How does it disagree? \y in the source code mapping to \y in the string
>> object is the sequence being left unchanged. And the usefulness of
>> doing so is hardly a disagreement over the fact that it does so.
> 
> Because you've stated that "\y" is a legal escape sequence, while the
> Python Reference Manual explicitly states that it is an "unrecognized
> escape sequence", and that such "unrecognized escape sequences" are
> sources of bugs.

There's that reading comprehension problem again.

Unrecognised != illegal.

"Useful for debugging" != "source of bugs". If they were equal, we could 
fix an awful lot of bugs by throwing away our debugging tools.

Here's the URL to the relevant page:
http://www.python.org/doc/2.5.2/ref/strings.html

It seems to me that the behaviour the Python designers were looking to 
avoid was the case where the coder accidentally inserted a backslash in 
the wrong place, and the language stripped the backslash out, e.g.:

Wanted "a\bcd" but accidentally typed "ab\cd" instead, and got "abcd".

(This is what Bash does by design, and at least some C/C++ compilers do, 
perhaps by accident, perhaps by design.)

In that case, with no obvious backslash, the user may not even be aware 
that there was a problem:

s = "ab\cd"  # assume the backslash is silently discarded
assert len(s) == 4
assert s[3] == 'c'
assert '\\' not in s

All of these tests would wrongly pass, but with Python's behaviour of 
leaving the backslash in, they would all fail, and the string is visually 
distinctive (it has an obvious backslash in it).

Now, if you consider that \c should be an error, then obviously it would 
be even better if "ab\cd" would raise a SyntaxError. But why consider \c 
to be an error?



[invalid hex escape sequences]

>> > What makes it "illegal". As far as I can tell, it's just another
>> > "unrecognized escape sequence".
>>
>> No, it's recognized, because \x is the prefix for an hexadecimal escape
>> code. And it's illegal, because it's missing the actual hexadecimal
>> digits.
> 
> So? Why does that make it "illegal" rather than merely "unrecognized?"

Because the empty string is not a legal pair of hex digits.

In '\y', the suffix y is a legal character, but it isn't recognized as a 
"special" character.

In '\x', the suffix '' is not a pair of hex digits. Since hex-escapes are 
documented as requiring a pair of hex digits, this is an error.


[...]
> Because anyone with common sense will agree that "\y" is an illegal
> escape sequence. 

"No True Scotsman would design a language that behaves like that!!!!"

Why should it be illegal? It seems like a perfectly valid escape sequence 
to me, so long as the semantics are specified explicitly.



[...]

>> > It may not be a complex form of DWIMing, but it's still DWIMing a
>> > bit.  Python is figuring that if I typed "\z", then either I must
>> > have really meant to type "\\z",
>>
>> Nope, not in the least. Python NEVER EVER EVER tries to guess what you
>> mean.
> 
> Neither does Perl. That doesn't mean that Perl isn't often DWIMy.

Fine, but we're not discussing Perl, we're discussing Python. Perl's DWIM-
iness is irrelevant.



>> This is *exactly* like C++, except that in Python the semantics of \y
>> and \\y are identical. Python doesn't guess what you mean, it *imposes*
>> a meaning on the escape sequence. You just don't like that meaning.
> 
> That's because I don't like things that are ill-conceived.

And yet you like C++... go figure *wink*


-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 05:39:16 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 09:39:16 GMT
Subject: hashability
References: 
	
	
Message-ID: 

On Wed, 12 Aug 2009 00:33:01 -0700, James Stroud wrote:

> Tell that to two different machines on two different days. Then bet the
> life of yourself and your nearest and dearest family on that fact and
> see whether you really want to take a hash value for granted. 

As far as I know, Python doesn't make any guarantees about hashes being 
repeatable on different machines, different versions, or even different 
runs of the interpreter.


> If a
> property of the python language fails the "bet the lives of your nearest
> and dearest on a consistent result" test, I call it "ill defined" and,
> subjectively speaking, I prefer exceptions to be thrown--And, by damned,
> I'll throw them myself if I have to.
> 
> "If it saves one life, it's worth it all."

Depends on the life, and the cost. Would you pay a million dollars from 
your own pocket to save the life of a 119 year old with advanced lung 
cancer, a bad heart, and a raging infection of Ebola, from choking on a 
fish bone?

What if the effort of saving that one life kills two lives? Opportunity 
costs are costs too.




-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 05:40:25 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 09:40:25 GMT
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	
Message-ID: 

On Wed, 12 Aug 2009 10:45:51 +0200, Hendrik van Rooyen wrote:

> On Tuesday 11 August 2009 19:53:16 Steven D'Aprano wrote:
> 
>> You want community input into the docs, but you're not willing to give
>> that input except to bitch and moan and sook that the tracker is no
>> good.
> 
> wtf does the verb  "sook" mean?
> 
> I find:
> 
> sook
> ??/s?k/ Show Spelled Pronunciation [sook] Show IPA
> Use sook in a Sentence
> ?noun
> 1. 	Australia and New Zealand. a timid, cowardly person, esp. a young
> person; crybaby.


That's the one. It's also used as a verb.




-- 
Steven


From python at mrabarnett.plus.com  Wed Aug 12 06:01:55 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Wed, 12 Aug 2009 11:01:55 +0100
Subject: Need cleanup advice for multiline string
In-Reply-To: <200908121104.35744.hendrik@microcorp.co.za>
References: 	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
	<200908121104.35744.hendrik@microcorp.co.za>
Message-ID: <4A829313.5010709@mrabarnett.plus.com>

Hendrik van Rooyen wrote:
> On Tuesday 11 August 2009 22:52:34 Robert Dailey wrote:
>> On Aug 11, 3:40 pm, Bearophile  wrote:
>>> Robert Dailey:
>>>> This breaks the flow of scope. Would you guys solve this
>>>> problem by moving failMsg into global scope?
>>>> Perhaps through some other type of syntax?
>>> There are gals too here.
>>> This may
>>> help:http://docs.python.org/library/textwrap.html#textwrap.dedent
>>>
>>> Bye,
>>> bearophile
>> It's a figure of speech. And besides, why would I want programming
>> advice from a woman? lol. Thanks for the help.
> 
> Well it may come as a surprise to you, but it was a woman who
> wrote one of the first compilers.
> 
> She became an Admiral in the US navy as a result.
> 
> If I recall correctly, her name was Grace Hooper.
> 
Grace Hopper. The saying "It's easier to ask forgiveness than it is to
get permission" is attributed to her.

> How many compilers have you written from scratch,
> without a compiler to help you?
> 
> :-)
> 



From mdekauwe at gmail.com  Wed Aug 12 06:15:30 2009
From: mdekauwe at gmail.com (Martin)
Date: Wed, 12 Aug 2009 03:15:30 -0700 (PDT)
Subject: matching patterns after regex?
Message-ID: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com>

Hi,

I have a string (see below) and ideally I would like to pull out the
decimal number which follows the bounding coordinate information. For
example ideal from this string I would return...

s = '\nGROUP                  = ARCHIVEDMETADATA\n
GROUPTYPE            = MASTERGROUP\n\n  GROUP                  =
BOUNDINGRECTANGLE\n\n    OBJECT                 =
NORTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
VALUE                = 19.9999999982039\n    END_OBJECT             =
NORTHBOUNDINGCOORDINATE\n\n    OBJECT                 =
SOUTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
VALUE                = 9.99999999910197\n    END_OBJECT             =
SOUTHBOUNDINGCOORDINATE\n\n    OBJECT                 =
EASTBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
VALUE                = 10.6506458717851\n    END_OBJECT             =
EASTBOUNDINGCOORDINATE\n\n    OBJECT                 =
WESTBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
VALUE                = 4.3188348375893e-15\n    END_OBJECT
= WESTBOUNDINGCOORDINATE\n\n  END_GROUP


NORTHBOUNDINGCOORDINATE = 19.9999999982039
SOUTHBOUNDINGCOORDINATE = 9.99999999910197
EASTBOUNDINGCOORDINATE = 10.6506458717851
WESTBOUNDINGCOORDINATE = 4.3188348375893e-15

so far I have only managed to extract the numbers by doing re.findall
("[\d.]*\d", s), which returns

['1',
 '19.9999999982039',
 '1',
 '9.99999999910197',
 '1',
 '10.6506458717851',
 '1',
 '4.3188348375893',
 '15',
etc.

Now the first problem that I can see is that my string match chops off
the "e-15" part and I am not sure how to incorporate the potential for
that in my pattern match. Does anyone have any suggestions as to how I
could also match this? Ideally I would have a statement which printed
the number between the two bounding coordinate strings for example

NORTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
VALUE                = 19.9999999982039\n    END_OBJECT             =
NORTHBOUNDINGCOORDINATE\n\n

Something that matched "NORTHBOUNDINGCOORDINATE" and printed the
decimal number before it hit the next string
"NORTHBOUNDINGCOORDINATE". But I am not sure how to do this. any
suggestions would be appreciated.

Many thanks

Martin


From phd at phd.pp.ru  Wed Aug 12 06:24:53 2009
From: phd at phd.pp.ru (Oleg Broytmann)
Date: Wed, 12 Aug 2009 14:24:53 +0400
Subject: SQLObject 0.11.0
Message-ID: <20090812102452.GE5602@phd.pp.ru>

Hello!

I'm pleased to announce version 0.11.0, the first stable release of 0.11 branch
of SQLObject.


What is SQLObject
=================

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite,
Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB).


Where is SQLObject
==================

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.11.0

News and changes:
http://sqlobject.org/News.html


What's New
==========

News since 0.10
-----------------

Features & Interface
~~~~~~~~~~~~~~~~~~~~

* Dropped support for Python 2.3. The minimal version of Python for
  SQLObject is 2.4 now.

* Dropped support for PostgreSQL 7.2. The minimal supported version of
  PostgreSQL is 7.3 now.

* New magic attribute 'j' similar to 'q' was added that automagically does
  join with the other table in MultipleJoin or RelatedJoin.

* SQLObject can now create and drop a database in MySQL, PostgreSQL, SQLite
  and Firebird/Interbase.

* Added some support for schemas in PostgreSQL.

* Added DecimalStringCol - similar to DecimalCol but stores data as strings
  to work around problems in some drivers and type affinity problem in
  SQLite.

* Added sqlobject.include.hashcol.HashCol - a column type that automatically
  hashes anything going into it, and returns out an object that hashes
  anything being compared to itself. Basically, it's good for really simple
  one-way password fields, and it even supports the assignment of None to
  indicate no password set. By default, it uses the md5 library for
  hashing, but this can be changed in a HashCol definition.

* RowDestroyedSignal and RowUpdatedSignal were added.

Minor features
~~~~~~~~~~~~~~

* Use reversed() in manager/command.py instead of .__reversed__().

* Minor change in logging to console - logger no longer stores the output
  file, it gets the file from module sys every time by name; this means
  logging will use new sys.stdout (or stderr) in case the user changed
  them.

* Changed the order of testing of SQLite modules - look for external
  PySQLite2 before sqlite3.

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
     Oleg Broytmann            http://phd.pp.ru/            phd at phd.pp.ru
           Programmers don't die, they just GOSUB without RETURN.


From paul at boddie.org.uk  Wed Aug 12 06:32:08 2009
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 Aug 2009 03:32:08 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	
Message-ID: <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>

On 12 Aug, 09:58, Steven D'Aprano
 wrote:
>
> We know that there are problems. We've said repeatedly that corrections
> and patches are welcome. We've repeatedly told you how to communicate
> your answer to the question of what should be done. None of this is good
> enough for you. I don't know what else you expect.

Maybe the problem is that although everyone welcomes contributions and
changes (or says that they do), the mechanisms remain largely beyond
criticism. Consequently, one sees occasional laments about there not
being enough people contributing to Python core development and soul-
searching about the reasons this might be so. If it were insisted that
changes to, say, Wikipedia were to be proposed by submitting a patch
or report for perusal by the editors and for future inclusion in some
version of the project, the whole project would most likely be a
shadow of its current self, and ambitions of large-scale collaborative
editing in general would still be ridiculed.

A free-for-all isn't likely to be the best solution for more actively
edited Python documentation, but Wiki solutions undeniably provide a
superior "fast path" for edits by trusted users to be incorporated and
published in accessible end-user documentation. Almost every analysis
of the current (and previous) documentation mechanisms has identified
the editorial workflow as a bottleneck and then proceeded to replicate
such a bottleneck in any proposed solution. I'm starting to believe
that there's a certain snobbery about Wiki solutions which lead many
people to develop all sorts of short-term, arcane solutions under the
illusion that something super-special and customised is necessary and
that they have to start virtually from scratch in order to cater to
the ultra-special needs of the target audience; by the time they're
done, no-one's interested any more, except to propose the next legacy
system in the making.

[...]

> > That some of us choose to
> > invest it somewhere other than Python does not deprive of of our right
> > to point out problems in Python when we note them.
>
> Of course not. But it does mean that you won't be taken seriously, and
> you have no right to be taken seriously.

That's an absurd position that has soured the reputation of numerous
projects. When someone spends the time to write a bug report, they are
often investing as much time and effort in something that they are
able to in any productive sense. I make a habit of submitting bug
reports to software distributions, typically so that the people who
are responsible for the components involved can investigate the
problem effectively. When the maintainers just close such reports or
mark them with a number of different labels which mostly indicate that
they consider those reports not worth their time, it sends the message
that they consider their time to be vastly more important than their
users, even though their users might have set aside an hour of their
potentially busy schedule which might have meant sacrificing something
else that should have taken higher priority (like time for sleeping,
in my own personal experience). Thus, I've had the impression with
some projects that I should be maintaining all sorts of stuff - the
bootloader, the kernel, various desktop applications, Mozilla - all so
that stuff actually gets fixed and that I'm not perceived as just
another user whose bug reports aren't welcome. I don't find this
reasonable at all when in many cases there *are* people getting paid
to do these jobs.

The Python core developers seem more attentive than in various other
projects, but please let us not establish the "delicate genius"
mentality that has infested other projects to the point that any
criticism is automatically labelled as ungrateful whining by people
who supposedly don't use the software, have an axe to grind, and who
are apparent simpletons who don't understand the revolutionary vision
of the project leadership. If you think throwing away goodwill is an
acceptable way of silencing complaints, please take a look at just
about any article about KDE 4 that permits reader comments to see how
much goodwill can be lost and what effect that has on a project's
reputation.

Paul


From davea at ieee.org  Wed Aug 12 07:05:39 2009
From: davea at ieee.org (Dave Angel)
Date: Wed, 12 Aug 2009 07:05:39 -0400
Subject: adding multiple new values to the same key in a dictionary
In-Reply-To: <4A822900.7030008@ieee.org>
References: <4A8192A30200008C00014AB9@redhorse.forestry.uga.edu>
	<4A822900.7030008@ieee.org>
Message-ID: <4A82A203.6030408@ieee.org>

Dave Angel wrote:
> Krishna Pacifici wrote:
>> Hi,
>> I want to be able to add multiple new values to a key in a dictionary.
>>
>> I have tried the following:
>>
>> sec_dict_clean=
>> {88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85]}
>>
>> for i in range(len(sec_dict_clean.values())):
>>     for j in range(len(sec_dict_clean.values()[i])):
>>         
>> sec_dict_clean.setdefault(key,[]).append(blocks[sec_dict_clean.values()[i][j]].abundance) 
>>
>>
>> where blocks[...].abundance gives me a single value from an object,
>>
>> but this gives me the following:
>>
>> sec_dict_clean=
>> {88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 
>> 85, 4, 12, 11, 6, 9, 12, 11, 7, 10, 10, 12, 9, 6, 12, 15, 9, 8, 12, 
>> 15, 12, 12]}
>>
>> instead I want each abundance (starts with 4, 12...) to be associated 
>> with each of the values so that it would look like this:
>>
>> sec_dict_clean=
>> {88: ([87, 89, 78, 98], [4,12,11,6]), 58: ([57, 59, 48, 68], 
>> [9,12,11,7]), 69: ([79], [10])...}
>>
>> You can see there are several errors here (I have more things being 
>> appended than there are values in the dictionary), but I really just 
>> want to know how to add multiple values to the same key in a dictionary.
>>
>> Thanks for any help,
>> Krishna
>>
>>
>>
>>   
> You're really distorting the purposes of both dictionary and list 
> here.  It makes your code totally unreadable, which makes it hard to 
> write, and hard to debug.
>
> A dictionary is a mapping between key and value, where each key has 
> exactly one value.  You cannot add another one to it.   All you can do 
> is make the value something which is itself a collection.  Now, your 
> desired dictionary looks achievable, almost.  If you change the parens 
> (tuple) to square brackets (list), then it'll work.
>    So key 88 has a single value, which is a list of two items.  Each 
> of those items is itself a list with 4 items.  And each of those items 
> are integers.
>
> But then I got bogged down in your sample code.  I tried to simplify 
> it, replacing the first two lines with these three:
>
> for i, key in enumerate(sec_dict_clean):
>    val = sec_dict_clean[key]
>    for j, xxx in enumerate(val):
>        
> ???sec_dict_clean.setdefault(key,[]).append(blocks[sec_dict_clean.values()[i][j]].abundance) 
>
>
> But I can't make head nor tail of the third line.  You didn't have a 
> variable key, so I don't know if I'm using the same one..  Since I 
> can't figure out what you were trying to do, I can't see how to fix it.
>
> I think the problem here is you're trying to reorganize the data as 
> well as adding to it, in a single pass.  So is some previous code 
> generating the dictionary incorrectly, and instead of fixing that, 
> you're trying to reorganize it here?
>
> To make each dictionary value a list of lists:
>
> sec_dict_clean=
> {88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85]}
>
> for key in sec_dict_clean:
>    sec_dict_clean[key] = [sec_dict_clean[key]]
>
> now,  the dict looks like:
> {88: [[87, 89, 78, 98, 3]], 58: [[57, 59, 48, 68]], 69: [[79]], 95: 
> [[94, 96, 85]]}
>
> At this point, if you have some interesting data to add to it, you can 
> just append a new list to
>     dict[key]
>
> In an earlier message, you mentioned fields a and b, and assuming this 
> is a similar problem, it would seem that 87 is somehow associated with 
> 4, and 89 with 12, and so on.  If that's the case, perhaps your 
> desired final structure might look more like:
>
> {88: [[87,4], [89,12], [78, 11],[98, 6],   58: [[57, 9], [59, 12], 
> [48, 11], [68, 7]],   69: ...}
>
>
> In this case, the structure is entirely different.  But the approach 
> is the same.  And at least you'd be getting closer to the object 
> approach where  [87,4] is replaced by an object of some type.
>
> BTW, please don't top-post.  When you reply to this one, put your 
> reply at the end, or sometimes interspersed.  But if you put it at the 
> beginning, it's out of order.
>
> DaveA
>
>
>
>
Look at the following (tested in Python 2.6.2).,  There are a number of 
things that could be cleaner, mainly the names of things.  I should 
never be calling something "value" unless it's a very generic routine.


class Sample(object):
    def __init__(self, mainval):
        self.mainval = mainval
        self.a = self.b = None
    def set_tags(self, a, b):
        self.a = a
        self.b = b
    def __repr__(self):
        return "<" + str(self.mainval) + " a=" + str(self.a) + " b=" + 
str(self.b) + ">"


diction2 = {88: [Sample(87), Sample(89), Sample(98), Sample(3)],
            58: [Sample(57), Sample(59), Sample(48), Sample(68)],
            69: [Sample(79)]
                 }

print diction2

for key, valuelist in diction2.iteritems():
    for item in valuelist:
        item.set_tags(12, 106)             #here's where you'd be using 
that mysterious blocks dictionary

print diction2



DaveA


From andrew at acooke.org  Wed Aug 12 07:49:06 2009
From: andrew at acooke.org (andrew cooke)
Date: Wed, 12 Aug 2009 04:49:06 -0700 (PDT)
Subject: Frustrated with scopes
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
	
Message-ID: 

On Aug 12, 1:51?am, James Stroud 
wrote:
> andrew cooke wrote:
> > Is there a way to make this work (currently scope and join are
> > undefined at runtime when the inner class attributes are defined):
>
> > class _StreamFactory(object):
>
> > ? ? @staticmethod
> > ? ? def __call__(lines, source, join=''.join):
>
> > ? ? ? ? class Line(object):
>
> > ? ? ? ? ? ? __source = source
> > ? ? ? ? ? ? __join = join
> > [...]
>
> It would be helpful if you were to describe the type of behavior you expect.

Sorry, I didn't make myself clear.  When run the code gives
 NameError: name 'source' is not defined
because the class namespace blocks the function namespace (or
something...).

Andrew


From andrew at acooke.org  Wed Aug 12 07:51:37 2009
From: andrew at acooke.org (andrew cooke)
Date: Wed, 12 Aug 2009 04:51:37 -0700 (PDT)
Subject: Frustrated with scopes
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
	
	
Message-ID: <4288a429-c7be-47a5-be06-7a53879d1767@w6g2000yqw.googlegroups.com>

On Aug 12, 7:49?am, andrew cooke  wrote:
> On Aug 12, 1:51?am, James Stroud 
> wrote:
>
>
>
> > andrew cooke wrote:
> > > Is there a way to make this work (currently scope and join are
> > > undefined at runtime when the inner class attributes are defined):
>
> > > class _StreamFactory(object):
>
> > > ? ? @staticmethod
> > > ? ? def __call__(lines, source, join=''.join):
>
> > > ? ? ? ? class Line(object):
>
> > > ? ? ? ? ? ? __source = source
> > > ? ? ? ? ? ? __join = join
> > > [...]
>
> > It would be helpful if you were to describe the type of behavior you expect.
>
> Sorry, I didn't make myself clear. ?When run the code gives
> ?NameError: name 'source' is not defined
> because the class namespace blocks the function namespace (or
> something...).

ie when the __call__ method is invoked on an instance of
_StreamFactory.

> Andrew



From bernard.chhun at gmail.com  Wed Aug 12 07:53:19 2009
From: bernard.chhun at gmail.com (Bernard)
Date: Wed, 12 Aug 2009 04:53:19 -0700 (PDT)
Subject: matching patterns after regex?
References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com>
Message-ID: <2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com>

On 12 ao?t, 06:15, Martin  wrote:
> Hi,
>
> I have a string (see below) and ideally I would like to pull out the
> decimal number which follows the bounding coordinate information. For
> example ideal from this string I would return...
>
> s = '\nGROUP ? ? ? ? ? ? ? ? ?= ARCHIVEDMETADATA\n
> GROUPTYPE ? ? ? ? ? ?= MASTERGROUP\n\n ?GROUP ? ? ? ? ? ? ? ? ?=
> BOUNDINGRECTANGLE\n\n ? ?OBJECT ? ? ? ? ? ? ? ? =
> NORTHBOUNDINGCOORDINATE\n ? ? ?NUM_VAL ? ? ? ? ? ? ?= 1\n
> VALUE ? ? ? ? ? ? ? ?= 19.9999999982039\n ? ?END_OBJECT ? ? ? ? ? ? =
> NORTHBOUNDINGCOORDINATE\n\n ? ?OBJECT ? ? ? ? ? ? ? ? =
> SOUTHBOUNDINGCOORDINATE\n ? ? ?NUM_VAL ? ? ? ? ? ? ?= 1\n
> VALUE ? ? ? ? ? ? ? ?= 9.99999999910197\n ? ?END_OBJECT ? ? ? ? ? ? =
> SOUTHBOUNDINGCOORDINATE\n\n ? ?OBJECT ? ? ? ? ? ? ? ? =
> EASTBOUNDINGCOORDINATE\n ? ? ?NUM_VAL ? ? ? ? ? ? ?= 1\n
> VALUE ? ? ? ? ? ? ? ?= 10.6506458717851\n ? ?END_OBJECT ? ? ? ? ? ? =
> EASTBOUNDINGCOORDINATE\n\n ? ?OBJECT ? ? ? ? ? ? ? ? =
> WESTBOUNDINGCOORDINATE\n ? ? ?NUM_VAL ? ? ? ? ? ? ?= 1\n
> VALUE ? ? ? ? ? ? ? ?= 4.3188348375893e-15\n ? ?END_OBJECT
> = WESTBOUNDINGCOORDINATE\n\n ?END_GROUP
>
> NORTHBOUNDINGCOORDINATE = 19.9999999982039
> SOUTHBOUNDINGCOORDINATE = 9.99999999910197
> EASTBOUNDINGCOORDINATE = 10.6506458717851
> WESTBOUNDINGCOORDINATE = 4.3188348375893e-15
>
> so far I have only managed to extract the numbers by doing re.findall
> ("[\d.]*\d", s), which returns
>
> ['1',
> ?'19.9999999982039',
> ?'1',
> ?'9.99999999910197',
> ?'1',
> ?'10.6506458717851',
> ?'1',
> ?'4.3188348375893',
> ?'15',
> etc.
>
> Now the first problem that I can see is that my string match chops off
> the "e-15" part and I am not sure how to incorporate the potential for
> that in my pattern match. Does anyone have any suggestions as to how I
> could also match this? Ideally I would have a statement which printed
> the number between the two bounding coordinate strings for example
>
> NORTHBOUNDINGCOORDINATE\n ? ? ?NUM_VAL ? ? ? ? ? ? ?= 1\n
> VALUE ? ? ? ? ? ? ? ?= 19.9999999982039\n ? ?END_OBJECT ? ? ? ? ? ? =
> NORTHBOUNDINGCOORDINATE\n\n
>
> Something that matched "NORTHBOUNDINGCOORDINATE" and printed the
> decimal number before it hit the next string
> "NORTHBOUNDINGCOORDINATE". But I am not sure how to do this. any
> suggestions would be appreciated.
>
> Many thanks
>
> Martin

Hey Martin,

here's a regex I've just tested : (\w+COORDINATE).*\s+VALUE\s+=\s([\d\.
\w-]+)

the first match corresponds to the whateverBOUNDINGCOORDINATE and the
second match is the value.

please provide some more entries if you'd like me to test my regex
some more :)

cheers

Bernard


From steve at REMOVE-THIS-cybersource.com.au  Wed Aug 12 08:08:40 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 12:08:40 GMT
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	
	<7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>
Message-ID: <0292a134$0$20647$c3e8da3@news.astraweb.com>

On Wed, 12 Aug 2009 03:32:08 -0700, Paul Boddie wrote:

> On 12 Aug, 09:58, Steven D'Aprano
>  wrote:
>>
>> We know that there are problems. We've said repeatedly that corrections
>> and patches are welcome. We've repeatedly told you how to communicate
>> your answer to the question of what should be done. None of this is
>> good enough for you. I don't know what else you expect.
> 
> Maybe the problem is that although everyone welcomes contributions and
> changes (or says that they do), the mechanisms remain largely beyond
> criticism. Consequently, one sees occasional laments about there not
> being enough people contributing to Python core development and soul-
> searching about the reasons this might be so. If it were insisted that
> changes to, say, Wikipedia were to be proposed by submitting a patch or
> report for perusal by the editors and for future inclusion in some
> version of the project, the whole project would most likely be a shadow
> of its current self, and ambitions of large-scale collaborative editing
> in general would still be ridiculed.

If Python had the tens of thousands of users, and hundreds of trusted 
(for some definition of trusted) editors, then Python could run using the 
same model as Wikipedia. The Wikipedia model is great, and I contribute 
to it myself.

But Wikipedia gets its users from the entire population of web-users, 
because there's something of interest to everyone in Wikipedia. 
Interested in movies? There are Wikipedia pages for you to contribute to. 
Interested in medicine? There are pages you can help with. Interested in 
the history and development of the mechanical pencil? There's probably 
even a page for you. And if there isn't, you can create one.

With tens of millions of web users, it's no surprise that Wikipedia can 
attract thousands of editors. But this does not apply to Python, which 
starts from a comparatively tiny population, primarily those interested 
in Python. Have a look at the Wikipedia page for Python. The Talk Page 
has comments from no more than *eight* people. The History stats suggest 
that, over seven years, only sixty-nine people have made more than a 
single edit to the page, most of them having made just two edits. Just 36 
people have made more than two edits, and some of those are bots. Only 
one user, Lulu of the Lotus-Eaters (David Mertz), has made more than 100 
edits.


> A free-for-all isn't likely to be the best solution for more actively
> edited Python documentation, but Wiki solutions undeniably provide a
> superior "fast path" for edits by trusted users to be incorporated and
> published in accessible end-user documentation. 

And the Python time-machine strikes again:

http://wiki.python.org/moin/


>> > That some of us choose to
>> > invest it somewhere other than Python does not deprive of of our
>> > right to point out problems in Python when we note them.
>>
>> Of course not. But it does mean that you won't be taken seriously, and
>> you have no right to be taken seriously.
> 
> That's an absurd position that has soured the reputation of numerous
> projects. When someone spends the time to write a bug report, they are
> often investing as much time and effort in something that they are able
> to in any productive sense. 

Firstly, in context, I wasn't talking to somebody who had made bug 
reports. I was talking to somebody whose only contribution, as near as I 
can tell, was to loudly complain that there are flaws in the Python 
documentation and insist that somebody else should fix them just the way 
he wants them fixed -- without being willing to even explain how he wants 
them fixed. Possibly the developers are expected to intuit from first 
principles what he wants.

Secondly, the world is full of complainers who won't lift a finger to 
help but demand others help them. It may be unfair to tar everybody with 
the same brush, but life is to short and time to valuable to avoid making 
judgements as to who to pay attention to. Those who invest a lot of 
effort into providing patches get listened to closely; so do those who 
make good quality detailed bug reports. Those who just say "It's broken, 
fix it" don't. Sometimes that will mean that someone with genuinely good 
ideas will be ignored, but that's the price one pays for avoiding being 
drowned by a chorus of trivial, contradictory, vague and insubstantial 
complaints.

If the Python Dev team paid attention to every post here claiming that 
Python "has a bug" when the bug was actually in the complainant's own 
code, we'd probably still be running Python 1.5.


> I make a habit of submitting bug reports to
> software distributions, typically so that the people who are responsible
> for the components involved can investigate the problem effectively.
> When the maintainers just close such reports or mark them with a number
> of different labels which mostly indicate that they consider those
> reports not worth their time, it sends the message that they consider
> their time to be vastly more important than their users, even though
> their users might have set aside an hour of their potentially busy
> schedule which might have meant sacrificing something else that should
> have taken higher priority (like time for sleeping, in my own personal
> experience).

Oh dear me. You mean that they don't agree that YOUR time is more 
important than theirs??? What horrible people they must be, to expect you 
to sacrifice some of your sleep time just so *they* can get some sleep 
themselves!!! Who do they think they are???



-- 
Steven


From deets at nospam.web.de  Wed Aug 12 08:12:14 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Wed, 12 Aug 2009 14:12:14 +0200
Subject: Frustrated with scopes
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
	
	
	<4288a429-c7be-47a5-be06-7a53879d1767@w6g2000yqw.googlegroups.com>
Message-ID: <7efpsuF2fvcq5U1@mid.uni-berlin.de>

andrew cooke wrote:

> On Aug 12, 7:49?am, andrew cooke  wrote:
>> On Aug 12, 1:51?am, James Stroud 
>> wrote:
>>
>>
>>
>> > andrew cooke wrote:
>> > > Is there a way to make this work (currently scope and join are
>> > > undefined at runtime when the inner class attributes are defined):
>>
>> > > class _StreamFactory(object):
>>
>> > > @staticmethod
>> > > def __call__(lines, source, join=''.join):
>>
>> > > class Line(object):
>>
>> > > __source = source
>> > > __join = join
>> > > [...]
>>
>> > It would be helpful if you were to describe the type of behavior you
>> > expect.
>>
>> Sorry, I didn't make myself clear. ?When run the code gives
>> NameError: name 'source' is not defined
>> because the class namespace blocks the function namespace (or
>> something...).
> 
> ie when the __call__ method is invoked on an instance of
> _StreamFactory.

But you can refer to the arguments if you don't insist on setting them as
class-attributes:




def factory(foo, bar):

    class A(object):

        def do_something(self):
            print foo, bar

    return A()

a = factory(10, 20)
a.do_something()



Diez


From mdekauwe at gmail.com  Wed Aug 12 08:12:22 2009
From: mdekauwe at gmail.com (Martin)
Date: Wed, 12 Aug 2009 05:12:22 -0700 (PDT)
Subject: matching patterns after regex?
References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com>
	<2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com>
Message-ID: 

On Aug 12, 12:53 pm, Bernard  wrote:
> On 12 ao?t, 06:15, Martin  wrote:
>
>
>
> > Hi,
>
> > I have a string (see below) and ideally I would like to pull out the
> > decimal number which follows the bounding coordinate information. For
> > example ideal from this string I would return...
>
> > s = '\nGROUP                  = ARCHIVEDMETADATA\n
> > GROUPTYPE            = MASTERGROUP\n\n  GROUP                  =
> > BOUNDINGRECTANGLE\n\n    OBJECT                 =
> > NORTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> > VALUE                = 19.9999999982039\n    END_OBJECT             =
> > NORTHBOUNDINGCOORDINATE\n\n    OBJECT                 =
> > SOUTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> > VALUE                = 9.99999999910197\n    END_OBJECT             =
> > SOUTHBOUNDINGCOORDINATE\n\n    OBJECT                 =
> > EASTBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> > VALUE                = 10.6506458717851\n    END_OBJECT             =
> > EASTBOUNDINGCOORDINATE\n\n    OBJECT                 =
> > WESTBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> > VALUE                = 4.3188348375893e-15\n    END_OBJECT
> > = WESTBOUNDINGCOORDINATE\n\n  END_GROUP
>
> > NORTHBOUNDINGCOORDINATE = 19.9999999982039
> > SOUTHBOUNDINGCOORDINATE = 9.99999999910197
> > EASTBOUNDINGCOORDINATE = 10.6506458717851
> > WESTBOUNDINGCOORDINATE = 4.3188348375893e-15
>
> > so far I have only managed to extract the numbers by doing re.findall
> > ("[\d.]*\d", s), which returns
>
> > ['1',
> >  '19.9999999982039',
> >  '1',
> >  '9.99999999910197',
> >  '1',
> >  '10.6506458717851',
> >  '1',
> >  '4.3188348375893',
> >  '15',
> > etc.
>
> > Now the first problem that I can see is that my string match chops off
> > the "e-15" part and I am not sure how to incorporate the potential for
> > that in my pattern match. Does anyone have any suggestions as to how I
> > could also match this? Ideally I would have a statement which printed
> > the number between the two bounding coordinate strings for example
>
> > NORTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> > VALUE                = 19.9999999982039\n    END_OBJECT             =
> > NORTHBOUNDINGCOORDINATE\n\n
>
> > Something that matched "NORTHBOUNDINGCOORDINATE" and printed the
> > decimal number before it hit the next string
> > "NORTHBOUNDINGCOORDINATE". But I am not sure how to do this. any
> > suggestions would be appreciated.
>
> > Many thanks
>
> > Martin
>
> Hey Martin,
>
> here's a regex I've just tested : (\w+COORDINATE).*\s+VALUE\s+=\s([\d\.
> \w-]+)
>
> the first match corresponds to the whateverBOUNDINGCOORDINATE and the
> second match is the value.
>
> please provide some more entries if you'd like me to test my regex
> some more :)
>
> cheers
>
> Bernard

Thanks Bernard it doesn't seem to be working for me...

I tried

re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)

is that what you meant? Apologies if not, that results in a syntax
error:

In [557]: re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)
------------------------------------------------------------
   File "", line 1
     re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)
                                                              ^
SyntaxError: unexpected character after line continuation character

Thanks





From steve at REMOVE-THIS-cybersource.com.au  Wed Aug 12 08:20:26 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 12:20:26 GMT
Subject: Frustrated with scopes
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
	
	
Message-ID: <0292a3f6$0$20647$c3e8da3@news.astraweb.com>

On Wed, 12 Aug 2009 04:49:06 -0700, andrew cooke wrote:

>> It would be helpful if you were to describe the type of behavior you
>> expect.
> 
> Sorry, I didn't make myself clear.  When run the code gives
>  NameError: name 'source' is not defined
> because the class namespace blocks the function namespace (or
> something...).

James asked you to describe the behaviour you expect. Please explain what 
you expect, and what you actually get. Post the ACTUAL error message, not 
a summary, not a paraphrase, but an actual copy and paste.


In any case, your code snippet works for me:


>>> class _StreamFactory(object):
...     @staticmethod
...     def __call__(lines, source, join=''.join):
...         class Line(object):
...             __source = source
...             __join = join
...
>>> obj = _StreamFactory()
>>> obj(['a', 'b'], "ab")
>>>

No errors. Of course it doesn't return anything, because your code 
snippet doesn't return anything either. Here's a modified version which 
returns the inner class:

>>> class _StreamFactory2(object):
...     @staticmethod
...     def __call__(lines, source, join=''.join):
...         class Line(object):
...             __source = source
...             __join = join
...         return Line
...
>>> obj = _StreamFactory2()
>>> K = obj(['a', 'b'], "ab")
>>> K

>>> K._Line__source
'ab'


Works perfectly. I suspect your error is probably something like you have 
misspelled "source" somewhere.


-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Wed Aug 12 08:23:25 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 12:23:25 GMT
Subject: matching patterns after regex?
References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com>
	<2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com>
	
Message-ID: <0292a4a9$0$20647$c3e8da3@news.astraweb.com>

On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote:

> I tried
> 
> re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)

You need to put quotes around strings.

In this case, because you're using regular expressions, you should use a 
raw string:

re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)

will probably work.





-- 
Steven


From solipsis at pitrou.net  Wed Aug 12 08:37:15 2009
From: solipsis at pitrou.net (Antoine Pitrou)
Date: Wed, 12 Aug 2009 12:37:15 +0000 (UTC)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	
	<7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>
Message-ID: 

Paul Boddie  boddie.org.uk> writes:
> 
> A free-for-all isn't likely to be the best solution for more actively
> edited Python documentation, but Wiki solutions undeniably provide a
> superior "fast path" for edits by trusted users to be incorporated and
> published in accessible end-user documentation.

Agreed.

> I'm starting to believe
> that there's a certain snobbery about Wiki solutions which lead many
> people to develop all sorts of short-term, arcane solutions under the
> illusion that something super-special and customised is necessary and
> that they have to start virtually from scratch in order to cater to
> the ultra-special needs of the target audience; by the time they're
> done, no-one's interested any more, except to propose the next legacy
> system in the making.

Not sure why you think it's snobbery... There are certain tacit expectations
regarding the docs:
- that they are versioned with the source tree (because, often, changes in
documentation will be synchronized with changes in behaviour / functionality, 
because we must maintain documentation for several versions at once, because you
want to use the same kind of merging that is used between different branches)
- that they can be used offline, rebuilt in different formats, etc.
- that you don't need a Web server (even locally) to navigate through them
- that proposed changes are to be reviewed by maintainers (core developers)
before they get actually committed

I'm not sure of any existing wiki system which fits the bill. So, while I agree
that the current situation can present a high threshold for occasional doc-only
contributions, there doesn't seem to be a simple solution to improve things.




From mdekauwe at gmail.com  Wed Aug 12 08:42:52 2009
From: mdekauwe at gmail.com (Martin)
Date: Wed, 12 Aug 2009 05:42:52 -0700 (PDT)
Subject: matching patterns after regex?
References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com>
	<2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com> 
	 
	<0292a4a9$0$20647$c3e8da3@news.astraweb.com>
Message-ID: <18d5d342-b678-4101-a284-24d6176ac856@v20g2000yqm.googlegroups.com>

On Aug 12, 1:23 pm, Steven D'Aprano  wrote:
> On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote:
> > I tried
>
> > re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)
>
> You need to put quotes around strings.
>
> In this case, because you're using regular expressions, you should use a
> raw string:
>
> re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)
>
> will probably work.
>
> --
> Steven

Thanks I see.

so I tried it and if I use it as it is, it matches the first instance:
I
n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)
Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')]

So I adjusted the first part of the regex, on the basis I could sub
NORTH for SOUTH etc.

In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\.
\w-]+)",s)
Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')]

But in both cases it doesn't return the decimal value rather the value
that comes after NUM_VAL = , rather than VALUE = ?




From davea at ieee.org  Wed Aug 12 08:52:50 2009
From: davea at ieee.org (Dave Angel)
Date: Wed, 12 Aug 2009 08:52:50 -0400
Subject: Frustrated with scopes
In-Reply-To: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
Message-ID: <4A82BB22.3080709@ieee.org>

andrew cooke wrote:
> Is there a way to make this work (currently scope and join are
> undefined at runtime when the inner class attributes are defined):
>
> class _StreamFactory(object):
>
>     @staticmethod
>     def __call__(lines, source, join=''.join):
>
>         class Line(object):
>
>             __source = source
>             __join = join
> [...]
>
> I can get something working by bouncing through global values, but it
> looks awful and I think it's a source of a bug due too values being
> redefined.
>
> Thanks,
> Andrew
>
>   
Supply us with just enough source code to actually try it, give the full 
error message including traceback, and tell us what you expected to 
see.  Also tell us Python version   (sys.version)

So far you've done none of these.  When I try the following, I get no 
errors, using Python 2.6.2


class _StreamFactory(object):

    @staticmethod
    def __call__(lines, source, join=''.join):

        class Line(object):

            __source = source
            __join = join
        return Line()


fact = _StreamFactory()
obj = fact(43, "name.txt")
print obj




From davea at ieee.org  Wed Aug 12 08:52:50 2009
From: davea at ieee.org (Dave Angel)
Date: Wed, 12 Aug 2009 08:52:50 -0400
Subject: Frustrated with scopes
In-Reply-To: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
Message-ID: <4A82BB22.3080709@ieee.org>

andrew cooke wrote:
> Is there a way to make this work (currently scope and join are
> undefined at runtime when the inner class attributes are defined):
>
> class _StreamFactory(object):
>
>     @staticmethod
>     def __call__(lines, source, join=''.join):
>
>         class Line(object):
>
>             __source = source
>             __join = join
> [...]
>
> I can get something working by bouncing through global values, but it
> looks awful and I think it's a source of a bug due too values being
> redefined.
>
> Thanks,
> Andrew
>
>   
Supply us with just enough source code to actually try it, give the full 
error message including traceback, and tell us what you expected to 
see.  Also tell us Python version   (sys.version)

So far you've done none of these.  When I try the following, I get no 
errors, using Python 2.6.2


class _StreamFactory(object):

    @staticmethod
    def __call__(lines, source, join=''.join):

        class Line(object):

            __source = source
            __join = join
        return Line()


fact = _StreamFactory()
obj = fact(43, "name.txt")
print obj




From paul at boddie.org.uk  Wed Aug 12 09:24:18 2009
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 Aug 2009 06:24:18 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	
	<7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>
	<0292a134$0$20647$c3e8da3@news.astraweb.com>
Message-ID: <3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com>

On 12 Aug, 14:08, Steven D'Aprano  wrote:
>
> With tens of millions of web users, it's no surprise that Wikipedia can
> attract thousands of editors. But this does not apply to Python, which
> starts from a comparatively tiny population, primarily those interested
> in Python. Have a look at the Wikipedia page for Python.

What does the Python entry on Wikipedia have to do with editing the
Python documentation in a Wiki? Once everyone has agreed that the
description of Python on Wikipedia is reasonable, there's not much
point in editing it, is there? In contrast, there's a continuous
stream of people who don't think Python's documentation is that great.

[...]

> > A free-for-all isn't likely to be the best solution for more actively
> > edited Python documentation, but Wiki solutions undeniably provide a
> > superior "fast path" for edits by trusted users to be incorporated and
> > published in accessible end-user documentation.
>
> And the Python time-machine strikes again:
>
> http://wiki.python.org/moin/

And I suggested that the complainants use it as a starting point.

[...]

> Oh dear me. You mean that they don't agree that YOUR time is more
> important than theirs??? What horrible people they must be, to expect you
> to sacrifice some of your sleep time just so *they* can get some sleep
> themselves!!! Who do they think they are???

That's quite an attempt to make my position more extreme than it
actually is. I get people asking me to improve my own software, you
know, and even if I don't have the time or inclination to do what they
ask, I do spend time discussing it with them. Such people, including
myself when I'm on the other side of the fence, appreciate more than
just a brush-off and no: they don't insist that their own time be
valued above anyone else's (as you would have me misrepresented); they
just ask that their own efforts aren't treated as having no value
because they're not part of the "elite" development team. You get
various projects doing soul-searching about embracing the efforts of
non-programmers, and the first port of call on that particular voyage
is to not treat them like idiot consumers whose remarks can only be
considered as mere heckling while the visionaries act out their
flawless production.

Paul

P.S. The mention of "social problems" ties in with other remarks made
recently, and I've increasingly found it more trouble than has been
worthwhile to pursue Python-related matters of late. When one tries to
encourage people to participate in improving various things, which
usually means the community having to accept a degree of criticism,
people claim that it's encouraging "undesirable" influences to point
such critics in the right direction instead of showing them the door.
When one tries to pursue such improvement matters oneself, people
always have something to say about the choice of technology or whether
they like the particular background colour being used or indeed have
an opinion, typically shallow and negative, about anything but the
task at hand, and there'll always be someone queuing up to dismantle
anything that does get done at the first opportunity. In contrast,
I've found other groups of people to be grateful for even modest
technical assistance, and I know that such people are much more likely
to get my support and input in the future than those who think that
it's some kind of advantage to have potential contributors run the
gauntlet of denial (that there are structural problems in their
project), skepticism (that newcomers can have anything to contribute),
discouragement (because any solution which doesn't validate someone's
technology preferences must be criticised) and, indeed, outright
hostility.

One can always spend one's time doing something which isn't 100%
enjoyable or 100% rewarding if one feels that the time is still being
spent on something worthwhile. I'm getting the feeling that lots of
Python-related stuff doesn't quite satisfy such criteria any more.


From jeanmichel at sequans.com  Wed Aug 12 09:27:49 2009
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Wed, 12 Aug 2009 15:27:49 +0200
Subject: Need cleanup advice for multiline string
In-Reply-To: <8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com>
References: 	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com>
Message-ID: <4A82C355.8080304@sequans.com>

Simon Brunning wrote:
> 2009/8/11 Robert Dailey :
>   
>> On Aug 11, 3:40 pm, Bearophile  wrote:
>>     
>>> There are gals too here.
>>>       
>> It's a figure of speech. And besides, why would I want programming
>> advice from a woman? lol. Thanks for the help.
>>     
>
> Give the attitudes still prevalent in our industry (cf
>  and many more), I'm sorry to say that I
> don't think this is funny.
>
>   
Having someone present technical informations with porn content cannot 
be qualified as "prevalent in our industry". I would even dare to say 
this is the opposite, it is almost unique.
I would also add that Robert was very far from this attitude, I consider 
his joke as a friendly tickle, not a male chauvinist aggression. I'm no 
women, but I'm sure they are as capable as me, not to say more, of 
making the distinction.

It has been said this list is not very friendly to newbies, let's not 
make it hostile to gentle jokes (even those not funny) when thanking 
helpers.

JM




From andrew at acooke.org  Wed Aug 12 09:47:38 2009
From: andrew at acooke.org (andrew cooke)
Date: Wed, 12 Aug 2009 06:47:38 -0700 (PDT)
Subject: Frustrated with scopes
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
	
Message-ID: <3bf15201-afc3-4fb4-9a99-ee2966c4da61@g31g2000yqc.googlegroups.com>

On Aug 12, 8:52?am, Dave Angel  wrote:
> Supply us with just enough source code to actually try it, give the full
> error message including traceback, and tell us what you expected to
> see. ?Also tell us Python version ? (sys.version)
>
> So far you've done none of these. ?When I try the following, I get no
> errors, using Python 2.6.2
>
> class _StreamFactory(object):
>
> ? ? @staticmethod
> ? ? def __call__(lines, source, join=''.join):
>
> ? ? ? ? class Line(object):
>
> ? ? ? ? ? ? __source = source
> ? ? ? ? ? ? __join = join
> ? ? ? ? return Line()
>
> fact = _StreamFactory()
> obj = fact(43, "name.txt")
> print obj

Ah!  OK, thanks for that.  I need to look at this again.  I'll post
again if necessary, but if it works for you then I clearly don't
understand what the issue is myself.

Andrew


From ebonak at hotmail.com  Wed Aug 12 09:58:09 2009
From: ebonak at hotmail.com (Esmail)
Date: Wed, 12 Aug 2009 09:58:09 -0400
Subject: best practice for documenting a project? pydoc?
Message-ID: 

Hello,

A project that I have been working on is getting larger
and more complex, and I would like to unload some of the
information from my memory/head to some other media (a
set of web pages?). I am primarily interested in documenting
the classes/methods.

This documentation is primarily for my use only - as I can't
continuously work on this project and have to come back to it
after some time, it would be nice to have some documentation
available to help jog my memory.

What is the best way to do this in an automated way? I have
been documenting my code as I've gone along.

Is pydoc still the way to go, or should I use something else?

Thanks,
Esmail



From exarkun at twistedmatrix.com  Wed Aug 12 10:09:56 2009
From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com)
Date: Wed, 12 Aug 2009 14:09:56 -0000
Subject: Need cleanup advice for multiline string
In-Reply-To: <4A82C355.8080304@sequans.com>
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com>
	<4A82C355.8080304@sequans.com>
Message-ID: <20090812140956.10431.1919444081.divmod.xquotient.60@localhost.localdomain>

On 01:27 pm, jeanmichel at sequans.com wrote:
>Simon Brunning wrote:
>>2009/8/11 Robert Dailey :
>>>On Aug 11, 3:40 pm, Bearophile  wrote:
>>>>There are gals too here.
>>>It's a figure of speech. And besides, why would I want programming
>>>advice from a woman? lol. Thanks for the help.
>>
>>Give the attitudes still prevalent in our industry (cf
>> and many more), I'm sorry to say that I
>>don't think this is funny.
>Having someone present technical informations with porn content cannot 
>be qualified as "prevalent in our industry". I would even dare to say 
>this is the opposite, it is almost unique.
>I would also add that Robert was very far from this attitude, I 
>consider his joke as a friendly tickle, not a male chauvinist 
>aggression. I'm no women, but I'm sure they are as capable as me, not 
>to say more, of making the distinction.
>
>It has been said this list is not very friendly to newbies, let's not 
>make it hostile to gentle jokes (even those not funny) when thanking 
>helpers.

It's lots of little things like this which combine to create an 
environment which is less friendly towards women than it is towards 
others.  You might read it as a joke, others might not.  Even if it is a 
joke, it's in poor taste and doesn't really belong on python-list.

There's a difference between pointing out inappropriate behavior and 
being unfriendly.  Hopefully Robert got help with his problem.  That's 
what the list is here for.  Having accomplished that, it is not 
unfriendly to ask him not to make disparaging comments, "jokes" or 
otherwise, about groups of people.

Jean-Paul


From breamoreboy at yahoo.co.uk  Wed Aug 12 10:10:47 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Wed, 12 Aug 2009 15:10:47 +0100
Subject: Social problems of Python doc [was Re: Python docs disappointing]
In-Reply-To: <3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com>
References: 	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>		<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>		<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>	<0291a07d$0$20639$c3e8da3@news.astraweb.com>	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>		<7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>	<0292a134$0$20647$c3e8da3@news.astraweb.com>
	<3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com>
Message-ID: 

Paul Boddie wrote:
[snip]
> One can always spend one's time doing something which isn't 100%
> enjoyable or 100% rewarding if one feels that the time is still being
> spent on something worthwhile. I'm getting the feeling that lots of
> Python-related stuff doesn't quite satisfy such criteria any more.

I've been strongly considering volunteering to do Python work but this 
thread has put me off completely.  I've time to spare as I only work 
part time due to long term health problems. However I don't feel that 
the time would be well spent on Python work, as I get the impression 
that a lot of it would go on cleaning some people's snotty noses, and on 
wiping other people's bottoms.

I'll just wait until my normal voluntary work starts again next month 
after the summer break.  Working with an extremely pleasant bunch of 
people hacking foreigners to death, that's more like it.  See the 
following links should anyone be interested.

http://www.dorsetforyou.com/index.jsp?articleid=386553
http://www.dorsetforyou.com/index.jsp?articleid=386598

-- 
Kindest regards.

Mark Lawrence.



From maxerickson at gmail.com  Wed Aug 12 10:14:46 2009
From: maxerickson at gmail.com (Max Erickson)
Date: Wed, 12 Aug 2009 14:14:46 +0000 (UTC)
Subject: httplib incredibly slow :-(
References: <4A81FDF5.6010508@simplistix.co.uk>
	<4A8274A9.7000905@simplistix.co.uk>
Message-ID: 

Chris Withers  wrote:
> 
> I'm still reeling from what seems to be such a huge problem with
> httplib that seem to be largely ignored :-(
> 
> Chris
> 

There is an httplib2 (but I don't know anything further about it...):

http://code.google.com/p/httplib2/

Calling wget or curl using a subprocess is probably as easy as it is 
ugly, I use the wget build from here:

http://gnuwin32.sourceforge.net/packages/wget.htm


max



From Scott.Daniels at Acm.Org  Wed Aug 12 10:29:37 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Wed, 12 Aug 2009 07:29:37 -0700
Subject: better way?
In-Reply-To: <6733c8fe-9ef8-4010-9b23-27538e19d8ff@c29g2000yqd.googlegroups.com>
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
	<87skfyjen8.fsf@golux.woodcraft.me.uk>
	
	<6733c8fe-9ef8-4010-9b23-27538e19d8ff@c29g2000yqd.googlegroups.com>
Message-ID: <3tSdnTBlOchPUh_XnZ2dnUVZ_oGdnZ2d@pdx.net>

Pet wrote:
> On 11 Aug., 22:19, "Rami Chowdhury"  wrote:
>> Ah, my apologies, I must have been getting it confused with ON UPDATE  
>> [things]. Thanks for correcting me.
>>
>> On Tue, 11 Aug 2009 13:10:03 -0700, Matthew Woodcraft  
>>
>>  wrote:
>>> "Rami Chowdhury"  writes:
>>>> IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than
>>>> MySQL...
>>> PostgreSQL does not have ON DUPLICATE KEY UPDATE.
>>> The SQL standard way to do what the OP wants is MERGE. PostgreSQL
>>> doesn't have that either.
> 
> So, I'm doing it in right way?
> What about building columns? map(lambda s: s + ' = %s', fields)
> Is that o.k.?
Isn't
     t = [field + ' = %s' for field in fields]
clearer than
     t = map(lambda s: s + ' = %s', fields)
? your call of course.

I don't quite understand why you are building the SQL from data
but constructing the arguments in source.  I'd actually set the
SQL up directly as a string, making both the SQL and Python more
readable. To the original question, you could unconditionally
perform a queries vaguely like:

UPDATE_SQL = '''UPDATE table ...
      WHERE id = %s AND location = %s;'''
INSERT_SQL = '''INSERT INTO table(...
      WHERE NOT EXISTS(SELECT * FROM table
                       WHERE id = %s AND location = %s;);'''
I'd put the NOW() and constant args (like the 1) in the SQL itself.
then your code might become:
     row = (self.wl, name, location, id)
     self._execQuery(db, UPDATE_SQL, [row])
     self._execQuery(db, INSERT_SQL, [row + (location, id)])
if _execQuery is like the standard Python DB interfaces.  Having
the SQL do the checking means you allows the DB to check its
index and use that result to control the operation, simplifying
the Python code without significantly affecting the the DB work
needed.  The "SELECT *" form in the EXIST test is something DB
optimizers look for, so don't fret about wasted data movement.



--Scott David Daniels
Scott.Daniels at Acm.Org


From rcdailey at gmail.com  Wed Aug 12 10:41:52 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Wed, 12 Aug 2009 07:41:52 -0700 (PDT)
Subject: Need cleanup advice for multiline string
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> 
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> 
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com> 
	<4A82C355.8080304@sequans.com>
	
Message-ID: <77a10bad-e0fe-4d50-95b2-f2f92a665001@h21g2000yqa.googlegroups.com>

On Aug 12, 9:09?am, exar... at twistedmatrix.com wrote:
> On 01:27 pm, jeanmic... at sequans.com wrote:
>
>
>
>
>
> >Simon Brunning wrote:
> >>2009/8/11 Robert Dailey :
> >>>On Aug 11, 3:40 pm, Bearophile  wrote:
> >>>>There are gals too here.
> >>>It's a figure of speech. And besides, why would I want programming
> >>>advice from a woman? lol. Thanks for the help.
>
> >>Give the attitudes still prevalent in our industry (cf
> >> and many more), I'm sorry to say that I
> >>don't think this is funny.
> >Having someone present technical informations with porn content cannot
> >be qualified as "prevalent in our industry". I would even dare to say
> >this is the opposite, it is almost unique.
> >I would also add that Robert was very far from this attitude, I
> >consider his joke as a friendly tickle, not a male chauvinist
> >aggression. I'm no women, but I'm sure they are as capable as me, not
> >to say more, of making the distinction.
>
> >It has been said this list is not very friendly to newbies, let's not
> >make it hostile to gentle jokes (even those not funny) when thanking
> >helpers.
>
> It's lots of little things like this which combine to create an
> environment which is less friendly towards women than it is towards
> others. ?You might read it as a joke, others might not. ?Even if it is a
> joke, it's in poor taste and doesn't really belong on python-list.
>
> There's a difference between pointing out inappropriate behavior and
> being unfriendly. ?Hopefully Robert got help with his problem. ?That's
> what the list is here for. ?Having accomplished that, it is not
> unfriendly to ask him not to make disparaging comments, "jokes" or
> otherwise, about groups of people.
>
> Jean-Paul

Hey everyone,

I was actually joking about my remark, I was making fun of the fact
that Bearophile took my figure of speech literally. I have worked with
a lot of women in the past and they even use "guys" to refer to
everyone in a room (When there were obviously other females in that
room as well).

On a more serious note, I do apologize to those offended by my remark.
I realize that these things can be a touchy subject for some people. I
expected more of a laid-back attitude from everyone. No need to be so
serious all the time. I cannot completely doubt that there are logical
women out there. I just haven't seen one yet. But that doesn't mean
I'm a sexist.

With my apology presented, I would like to propose that we end the
discussion here. As I said, this is a very sensitive subject and this
thread could spin way out of control if we don't just ignore the
issue. For those that took it as a friendly, harmless joke, hopefully
you had a laugh. For those that took it seriously or as an offense,
please take my apology to heart. Thanks once again to everyone for
your help. I've long been a member of this community and I really
appreciate the continuous support I've been receiving!

Take care everyone!


From rcdailey at gmail.com  Wed Aug 12 10:47:58 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Wed, 12 Aug 2009 07:47:58 -0700 (PDT)
Subject: Need cleanup advice for multiline string
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> 
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> 
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com> 
	<4A82C355.8080304@sequans.com>
	 
	<77a10bad-e0fe-4d50-95b2-f2f92a665001@h21g2000yqa.googlegroups.com>
Message-ID: <1b527b08-8b49-4bff-a192-215565feacf3@s15g2000yqs.googlegroups.com>

On Aug 12, 9:41?am, Robert Dailey  wrote:
> On Aug 12, 9:09?am, exar... at twistedmatrix.com wrote:
>
>
>
>
>
> > On 01:27 pm, jeanmic... at sequans.com wrote:
>
> > >Simon Brunning wrote:
> > >>2009/8/11 Robert Dailey :
> > >>>On Aug 11, 3:40 pm, Bearophile  wrote:
> > >>>>There are gals too here.
> > >>>It's a figure of speech. And besides, why would I want programming
> > >>>advice from a woman? lol. Thanks for the help.
>
> > >>Give the attitudes still prevalent in our industry (cf
> > >> and many more), I'm sorry to say that I
> > >>don't think this is funny.
> > >Having someone present technical informations with porn content cannot
> > >be qualified as "prevalent in our industry". I would even dare to say
> > >this is the opposite, it is almost unique.
> > >I would also add that Robert was very far from this attitude, I
> > >consider his joke as a friendly tickle, not a male chauvinist
> > >aggression. I'm no women, but I'm sure they are as capable as me, not
> > >to say more, of making the distinction.
>
> > >It has been said this list is not very friendly to newbies, let's not
> > >make it hostile to gentle jokes (even those not funny) when thanking
> > >helpers.
>
> > It's lots of little things like this which combine to create an
> > environment which is less friendly towards women than it is towards
> > others. ?You might read it as a joke, others might not. ?Even if it is a
> > joke, it's in poor taste and doesn't really belong on python-list.
>
> > There's a difference between pointing out inappropriate behavior and
> > being unfriendly. ?Hopefully Robert got help with his problem. ?That's
> > what the list is here for. ?Having accomplished that, it is not
> > unfriendly to ask him not to make disparaging comments, "jokes" or
> > otherwise, about groups of people.
>
> > Jean-Paul
>
> Hey everyone,
>
> I was actually joking about my remark, I was making fun of the fact
> that Bearophile took my figure of speech literally. I have worked with
> a lot of women in the past and they even use "guys" to refer to
> everyone in a room (When there were obviously other females in that
> room as well).
>
> On a more serious note, I do apologize to those offended by my remark.
> I realize that these things can be a touchy subject for some people. I
> expected more of a laid-back attitude from everyone. No need to be so
> serious all the time. I cannot completely doubt that there are logical
> women out there. I just haven't seen one yet. But that doesn't mean
> I'm a sexist.
>
> With my apology presented, I would like to propose that we end the
> discussion here. As I said, this is a very sensitive subject and this
> thread could spin way out of control if we don't just ignore the
> issue. For those that took it as a friendly, harmless joke, hopefully
> you had a laugh. For those that took it seriously or as an offense,
> please take my apology to heart. Thanks once again to everyone for
> your help. I've long been a member of this community and I really
> appreciate the continuous support I've been receiving!
>
> Take care everyone!

Oh, one last thing... So everyone knows, I chose the following
formatting solution to multiline strings:

def MyFunction():
   multilineString = (
      'This is a string that spans '
      'multiple lines.'
      )
   print( multilineString )

I think this is as good as it is going to get for my personal needs.
However, I do not like having to put a space at the end of each
string. I've also done this in the past, which is slightly more ugly:

  multilineString = (
     'This is a string that spans',
     'multiple lines.'
     )
  print( ' '.join( multilineString ) )

This will add the spaces between lines for you. However, in a
production quality application I would always have strings external to
the scripts and have an advanced localization system. However this is
useful for quick little scripts that I want to keep tidy.


From breamoreboy at yahoo.co.uk  Wed Aug 12 10:49:51 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Wed, 12 Aug 2009 15:49:51 +0100
Subject: best practice for documenting a project? pydoc?
In-Reply-To: 
References: 
Message-ID: 

Esmail wrote:
> Hello,
> 
> A project that I have been working on is getting larger
> and more complex, and I would like to unload some of the
> information from my memory/head to some other media (a
> set of web pages?). I am primarily interested in documenting
> the classes/methods.
> 
> This documentation is primarily for my use only - as I can't
> continuously work on this project and have to come back to it
> after some time, it would be nice to have some documentation
> available to help jog my memory.
> 
> What is the best way to do this in an automated way? I have
> been documenting my code as I've gone along.
> 
> Is pydoc still the way to go, or should I use something else?
> 
> Thanks,
> Esmail
> 
The docs for the constraint package look good, see
http://labix.org/python-constraint and http://labix.org/doc/constraint.
I think they've been produced with epydoc see http://epydoc.sourceforge.net/

-- 
Kindest regards.

Mark Lawrence.



From steve at REMOVE-THIS-cybersource.com.au  Wed Aug 12 11:08:32 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 15:08:32 GMT
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	
	<7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>
	<0292a134$0$20647$c3e8da3@news.astraweb.com>
	<3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com>
Message-ID: <0292cb5a$0$20647$c3e8da3@news.astraweb.com>

On Wed, 12 Aug 2009 06:24:18 -0700, Paul Boddie wrote:

> On 12 Aug, 14:08, Steven D'Aprano  cybersource.com.au> wrote:
>>
>> With tens of millions of web users, it's no surprise that Wikipedia can
>> attract thousands of editors. But this does not apply to Python, which
>> starts from a comparatively tiny population, primarily those interested
>> in Python. Have a look at the Wikipedia page for Python.
> 
> What does the Python entry on Wikipedia have to do with editing the
> Python documentation in a Wiki? 

Good question. I was responding to you mentioning Wikipedia as a possible 
role model for the Python docs.


> Once everyone has agreed that the
> description of Python on Wikipedia is reasonable, there's not much point
> in editing it, is there? 

And once we're all fabulously wealthy, there won't be any point in anyone 
working any more either!

The problem for your argument is, even if it were correct, not everyone 
agrees the Python article is "reasonable" -- there were three edits made 
since the 7th of this month. And before that, there was a stream of 22 
edits on the 5th, and another 25 edits since the  8th of July. Obviously 
the Python article is still in active development.

Some of those edits were, apparently, vandalism, which gives yet another 
reason why the Wikipedia model is not necessarily the right model to 
follow.


> In contrast, there's a continuous stream of
> people who don't think Python's documentation is that great.

And a great flood of those who think it's pretty good and gets the job 
done adequately, and a trickle of those who think it's perfect just the 
way it is.

It's not the people who suggest improvements to the docs that are the 
problem, but the ones who insist that the docs are terrible, but aren't 
willing to do anything but complain. Oh, and trolls like ... I hesitate 
to mention his name in case he has a bot monitoring the list ... first 
name starts with "X" followed by "ah", second name sounds like "Mee" ... 
who even if they make a few good points, they're lost in a sea of insults 
to others, arrogance and self-aggrandisement.


>> And the Python time-machine strikes again:
>>
>> http://wiki.python.org/moin/
> 
> And I suggested that the complainants use it as a starting point.

Sorry, I seem to have missed that.


> [...]
> 
>> Oh dear me. You mean that they don't agree that YOUR time is more
>> important than theirs??? What horrible people they must be, to expect
>> you to sacrifice some of your sleep time just so *they* can get some
>> sleep themselves!!! Who do they think they are???
> 
> That's quite an attempt to make my position more extreme than it
> actually is. 

Well, you did raise the issue of the sacrifices you were making to report 
these bugs. All I did was exaggerate the attitude a tad.


> I get people asking me to improve my own software, you
> know, and even if I don't have the time or inclination to do what they
> ask, I do spend time discussing it with them. Such people, including
> myself when I'm on the other side of the fence, appreciate more than
> just a brush-off and no: they don't insist that their own time be valued
> above anyone else's 

Then you're incredibly lucky to attract a better class of end-users. In 
my experience, most end-users won't even spend the effort to describe the 
problem they're having beyond "it doesn't work". And they usually 
misspell that.



> (as you would have me misrepresented); they just ask
> that their own efforts aren't treated as having no value because they're
> not part of the "elite" development team. You get various projects doing
> soul-searching about embracing the efforts of non-programmers, and the
> first port of call on that particular voyage is to not treat them like
> idiot consumers whose remarks can only be considered as mere heckling
> while the visionaries act out their flawless production.

A noble vision, but wait until the idiot heckling consumers discover your 
software, then we'll see how much time you're prepared to give them.



> 
> Paul
> 
> P.S. The mention of "social problems" ties in with other remarks made
> recently, and I've increasingly found it more trouble than has been
> worthwhile to pursue Python-related matters of late. When one tries to
> encourage people to participate in improving various things, which
> usually means the community having to accept a degree of criticism,
> people claim that it's encouraging "undesirable" influences to point
> such critics in the right direction instead of showing them the door.

Can you point me to a discussion where this has happened?


> When one tries to pursue such improvement matters oneself, people always
> have something to say about the choice of technology or whether they
> like the particular background colour being used 

You've discovered bike-shedding.

> or indeed have an
> opinion, typically shallow and negative, about anything but the task at
> hand, 

When you're agitating for change, anyone defending the status quo has 
opinions which are shallow and negative. When you're happy with the 
status quo, possibly even for good, rational reasons and not just because 
you're a shallow-minded, ignorant, know-nothing nay-sayer, it's those 
agitating for change who have shallow and negative opinions. It's such a 
bother trying to determine who is right, so I prefer to just accuse the 
other guy of being shallow and negative rather than try to understand his 
point of view. I find it saves time in the long run.


> and there'll always be someone queuing up to dismantle anything
> that does get done at the first opportunity. In contrast, I've found
> other groups of people to be grateful for even modest technical
> assistance, and I know that such people are much more likely to get my
> support and input in the future than those who think that it's some kind
> of advantage to have potential contributors run the gauntlet of denial
> (that there are structural problems in their project), skepticism (that
> newcomers can have anything to contribute), discouragement (because any
> solution which doesn't validate someone's technology preferences must be
> criticised) and, indeed, outright hostility.

I'm having trouble parsing the semantics of that sentence, so please 
excuse me for any misunderstandings.

There seems to be a hidden assumption in your sentence that there *are* 
structural problems in the project. Now obviously no project is 
"perfect", and we all know of cases where a group of people immersed in a 
project will become so close to it that they can't see the rotten trees 
for the wood, so to speak. But generally, the people in the project have 
a very good understanding of the project's strengths and weaknesses, 
because they've been living with it for a long, long time, and it's new-
comers, who don't know the tools, don't know the libraries, aren't 
familiar with the conventions, and don't know the reasons for the 
decisions made, who can't see the trees for the wood.

It's not experienced Python developers who write really slow Java code in 
Python, it's Java developers. And I'm sure the opposite occurs too: 
Python developers learning Java for the first time will struggle to write 
idiomatic Java code, and will criticise *the wrong things* because 
they're thinking like Python developers.

You're expecting outsiders to bring in fresh insights that the jaded, 
stuck-in-a-rut locals can't see. Well, it happens. But for every time it 
happens, there's a hundred outsiders who come along and say the 
equivalent of "What, no GOTO? Well this sucks."




-- 
Steven


From petshmidt at googlemail.com  Wed Aug 12 11:09:02 2009
From: petshmidt at googlemail.com (Pet)
Date: Wed, 12 Aug 2009 08:09:02 -0700 (PDT)
Subject: better way?
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
	<87skfyjen8.fsf@golux.woodcraft.me.uk> 
	
	<6733c8fe-9ef8-4010-9b23-27538e19d8ff@c29g2000yqd.googlegroups.com>
	<3tSdnTBlOchPUh_XnZ2dnUVZ_oGdnZ2d@pdx.net>
Message-ID: 

On Aug 12, 4:29?pm, Scott David Daniels  wrote:
> Pet wrote:
> > On 11 Aug., 22:19, "Rami Chowdhury"  wrote:
> >> Ah, my apologies, I must have been getting it confused with ON UPDATE ?
> >> [things]. Thanks for correcting me.
>
> >> On Tue, 11 Aug 2009 13:10:03 -0700, Matthew Woodcraft ?
>
> >>  wrote:
> >>> "Rami Chowdhury"  writes:
> >>>> IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than
> >>>> MySQL...
> >>> PostgreSQL does not have ON DUPLICATE KEY UPDATE.
> >>> The SQL standard way to do what the OP wants is MERGE. PostgreSQL
> >>> doesn't have that either.
>
> > So, I'm doing it in right way?
> > What about building columns? map(lambda s: s + ' = %s', fields)
> > Is that o.k.?
>
> Isn't
> ? ? ?t = [field + ' = %s' for field in fields]
> clearer than
> ? ? ?t = map(lambda s: s + ' = %s', fields)
> ? your call of course.

Yes, I think so

> I don't quite understand why you are building the SQL from data
> but constructing the arguments in source. ?I'd actually set the
> SQL up directly as a string, making both the SQL and Python more

Sometimes, column list could be long, besides I keep column list in
sync for both update and insert query

> readable. To the original question, you could unconditionally
> perform a queries vaguely like:
>
> UPDATE_SQL = '''UPDATE table ...
> ? ? ? WHERE id = %s AND location = %s;'''
> INSERT_SQL = '''INSERT INTO table(...
> ? ? ? WHERE NOT EXISTS(SELECT * FROM table
> ? ? ? ? ? ? ? ? ? ? ? ?WHERE id = %s AND location = %s;);'''
> I'd put the NOW() and constant args (like the 1) in the SQL itself.

yes, but I'm building both UPDATE in INSERT from same list of columns,
so I didn't found better way as this one


> then your code might become:
> ? ? ?row = (self.wl, name, location, id)
> ? ? ?self._execQuery(db, UPDATE_SQL, [row])
> ? ? ?self._execQuery(db, INSERT_SQL, [row + (location, id)])

I'm going to rebuild my queries like that.

Thank you very much!


> if _execQuery is like the standard Python DB interfaces. ?Having
> the SQL do the checking means you allows the DB to check its
> index and use that result to control the operation, simplifying
> the Python code without significantly affecting the the DB work
> needed. ?The "SELECT *" form in the EXIST test is something DB
> optimizers look for, so don't fret about wasted data movement.
>
> --Scott David Daniels
> Scott.Dani... at Acm.Org



From sajmikins at gmail.com  Wed Aug 12 11:11:43 2009
From: sajmikins at gmail.com (Simon Forman)
Date: Wed, 12 Aug 2009 08:11:43 -0700 (PDT)
Subject: Need cleanup advice for multiline string
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> 
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> 
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com> 
	<4A82C355.8080304@sequans.com>
	 
	<77a10bad-e0fe-4d50-95b2-f2f92a665001@h21g2000yqa.googlegroups.com>
Message-ID: 

On Aug 12, 10:41?am, Robert Dailey  wrote:
> On Aug 12, 9:09?am, exar... at twistedmatrix.com wrote:
>
>
>
> > On 01:27 pm, jeanmic... at sequans.com wrote:
>
> > >Simon Brunning wrote:
> > >>2009/8/11 Robert Dailey :
> > >>>On Aug 11, 3:40 pm, Bearophile  wrote:
> > >>>>There are gals too here.
> > >>>It's a figure of speech. And besides, why would I want programming
> > >>>advice from a woman? lol. Thanks for the help.
>
> > >>Give the attitudes still prevalent in our industry (cf
> > >> and many more), I'm sorry to say that I
> > >>don't think this is funny.
> > >Having someone present technical informations with porn content cannot
> > >be qualified as "prevalent in our industry". I would even dare to say
> > >this is the opposite, it is almost unique.
> > >I would also add that Robert was very far from this attitude, I
> > >consider his joke as a friendly tickle, not a male chauvinist
> > >aggression. I'm no women, but I'm sure they are as capable as me, not
> > >to say more, of making the distinction.
>
> > >It has been said this list is not very friendly to newbies, let's not
> > >make it hostile to gentle jokes (even those not funny) when thanking
> > >helpers.
>
> > It's lots of little things like this which combine to create an
> > environment which is less friendly towards women than it is towards
> > others. ?You might read it as a joke, others might not. ?Even if it is a
> > joke, it's in poor taste and doesn't really belong on python-list.
>
> > There's a difference between pointing out inappropriate behavior and
> > being unfriendly. ?Hopefully Robert got help with his problem. ?That's
> > what the list is here for. ?Having accomplished that, it is not
> > unfriendly to ask him not to make disparaging comments, "jokes" or
> > otherwise, about groups of people.
>
> > Jean-Paul
>
> Hey everyone,
>
> I was actually joking about my remark, I was making fun of the fact
> that Bearophile took my figure of speech literally. I have worked with
> a lot of women in the past and they even use "guys" to refer to
> everyone in a room (When there were obviously other females in that
> room as well).
>
> On a more serious note, I do apologize to those offended by my remark.
> I realize that these things can be a touchy subject for some people. I
> expected more of a laid-back attitude from everyone. No need to be so
> serious all the time. I cannot completely doubt that there are logical
> women out there. I just haven't seen one yet. But that doesn't mean
> I'm a sexist.

Oh my.  And you were doing so well.  You haven't seen a logical
woman?  Perhaps you're blind because your eyes were torn out by a
raging marmoset?

Guess what?  Thinking (or just saying) that /does/ mean you're a
sexist.  (Even if it was just another "friendly, harmless joke".)




> With my apology presented, I would like to propose that we end the
> discussion here. As I said, this is a very sensitive subject and this
> thread could spin way out of control if we don't just ignore the
> issue. For those that took it as a friendly, harmless joke, hopefully
> you had a laugh. For those that took it seriously or as an offense,
> please take my apology to heart. Thanks once again to everyone for
> your help. I've long been a member of this community and I really
> appreciate the continuous support I've been receiving!
>
> Take care everyone!



From steve at REMOVE-THIS-cybersource.com.au  Wed Aug 12 11:26:12 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 15:26:12 GMT
Subject: Need cleanup advice for multiline string
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com>
	<4A82C355.8080304@sequans.com>
	
	<77a10bad-e0fe-4d50-95b2-f2f92a665001@h21g2000yqa.googlegroups.com>
	<1b527b08-8b49-4bff-a192-215565feacf3@s15g2000yqs.googlegroups.com>
Message-ID: <0292cf7e$0$20647$c3e8da3@news.astraweb.com>

On Wed, 12 Aug 2009 07:47:58 -0700, Robert Dailey wrote:

> On Aug 12, 9:41?am, Robert Dailey  wrote:
... 
> > I was actually joking about my remark, I was making fun of the fact
> > that Bearophile took my figure of speech literally. 

Keep in mind that the Internet is a global forum, and not everyone here 
speaks English as a first language. I believe Bearophile is one of those. 
Although his, or possibly her, English is excellent, it wouldn't surprise 
me that (s)he would misinterpret "guys" as just referring to men. I'm a 
native English speaker, and I would have done the same.


> > I have worked with
> > a lot of women in the past and they even use "guys" to refer to
> > everyone in a room (When there were obviously other females in that
> > room as well).

Yes, I've seen this myself, but it's still uncommon enough to surprise me 
every time I see it.


> > On a more serious note, I do apologize to those offended by my remark.
> > I realize that these things can be a touchy subject for some people. I
> > expected more of a laid-back attitude from everyone. No need to be so
> > serious all the time. I cannot completely doubt that there are logical
> > women out there. I just haven't seen one yet. 

That's okay, I haven't seen terribly many logical men out there either.


> Oh, one last thing... So everyone knows, I chose the following
> formatting solution to multiline strings:
> 
> def MyFunction():
>    multilineString = (
>       'This is a string that spans '
>       'multiple lines.'
>       )
>    print( multilineString )
> 
> I think this is as good as it is going to get for my personal needs.
> However, I do not like having to put a space at the end of each
> string. 

So put them at the beginning of the next line. It makes the space more 
obvious, so it's clearer what you have done. That's what I sometimes do.


> I've also done this in the past, which is slightly more ugly:
> 
>   multilineString = (
>      'This is a string that spans',
>      'multiple lines.'
>      )
>   print( ' '.join( multilineString ) )


It's also less efficient, as it does the concatenation at runtime instead 
of compile time. But for a small script, that's not likely to be a 
problem worth worrying about.
 


-- 
Steven


From shaileshk at gmail.com  Wed Aug 12 11:33:55 2009
From: shaileshk at gmail.com (shaileshkumar)
Date: Wed, 12 Aug 2009 08:33:55 -0700 (PDT)
Subject: best practice for documenting a project? pydoc?
References: 
	
Message-ID: 

Hello,

EPYDOC is very good for automatic generation of documentation from
source code.

You may also consider Sphinx http://sphinx.pocoo.org/ which is used
for many
projects including the official Python documentation, documentation of
Zope (http://docs.zope.org/).
See the full list of projects using Sphinx at http://sphinx.pocoo.org/examples.html

- Shailesh


On Aug 12, 7:49?pm, Mark Lawrence  wrote:
> Esmail wrote:
> > Hello,
>
> > A project that I have been working on is getting larger
> > and more complex, and I would like to unload some of the
> > information from my memory/head to some other media (a
> > set of web pages?). I am primarily interested in documenting
> > the classes/methods.
>
> > This documentation is primarily for my use only - as I can't
> > continuously work on this project and have to come back to it
> > after some time, it would be nice to have some documentation
> > available to help jog my memory.
>
> > What is the best way to do this in an automated way? I have
> > been documenting my code as I've gone along.
>
> > Is pydoc still the way to go, or should I use something else?
>
> > Thanks,
> > Esmail
>
> The docs for the constraint package look good, seehttp://labix.org/python-constraintandhttp://labix.org/doc/constraint.
> I think they've been produced with epydoc seehttp://epydoc.sourceforge.net/
>
> --
> Kindest regards.
>
> Mark Lawrence.



From shaileshk at gmail.com  Wed Aug 12 11:50:14 2009
From: shaileshk at gmail.com (shaileshkumar)
Date: Wed, 12 Aug 2009 08:50:14 -0700 (PDT)
Subject: httplib incredibly slow :-(
References: <4A81FDF5.6010508@simplistix.co.uk>
	<4A8274A9.7000905@simplistix.co.uk> 
	
Message-ID: 

We use PyCURL on Windows. http://pycurl.sourceforge.net/ provides pre-
built versions for Windows and it works out of the box.

- Shailesh



On Aug 12, 7:14?pm, Max Erickson  wrote:
> Chris Withers  wrote:
>
> > I'm still reeling from what seems to be such a huge problem with
> > httplib that seem to be largely ignored :-(
>
> > Chris
>
> There is an httplib2 (but I don't know anything further about it...):
>
> http://code.google.com/p/httplib2/
>
> Calling wget or curl using a subprocess is probably as easy as it is
> ugly, I use the wget build from here:
>
> http://gnuwin32.sourceforge.net/packages/wget.htm
>
> max



From shaileshk at gmail.com  Wed Aug 12 11:56:03 2009
From: shaileshk at gmail.com (shaileshkumar)
Date: Wed, 12 Aug 2009 08:56:03 -0700 (PDT)
Subject: Programming by Contract
References: <4A7A15CD.9090306@stoneleaf.us> <4A81C6B8.7010605@stoneleaf.us> 
	<18F0FD2E-7C01-4B1C-85DF-28433C23D886@declareSub.com>
	
Message-ID: <78b17cf4-1e7b-4134-8626-2c352107ac27@f20g2000prn.googlegroups.com>

zope.interface provides extensive support for design by contract.
http://pypi.python.org/pypi/zope.interface.
This package can be used independently of zope in other projects.
- Shailesh

On Aug 12, 2:20?am, Ethan Furman  wrote:
> Charles Yeomans wrote:
>
> > On Aug 11, 2009, at 3:30 PM, Ethan Furman wrote:
>
> >> Ethan Furman wrote:
>
> >>> Greetings!
> >>> I have seen posts about the assert statement and PbC (or maybe it ?
> >>> was DbC), and I just took a very brief look at pycontract
> >>> (http://www.wayforward.net/pycontract/) and now I have at least one
> >>> question: ?Is this basically another ?way of thinking about unit
> >>> testing, or is the idea of PbC more ?along the lines of *always*
> >>> checking the input/output of functions ?to ensure they are correct? ?
> >>> (*Contstant vigilance!* as Prof Moody ?would say ;)
> >>> I know asserts can be turned off, so they obviously won't work for ?
> >>> the latter case, and having seen the sample of pycontract it seems ?
> >>> it only does its thing during debugging.
> >>> So is Design (Programming) by Contract a fancy way of saying ?
> >>> "Document your inputs/outputs!" or is there more to it?
> >>> ~Ethan~
>
> >> Hmmm...
>
> >> Well, from the (apparently) complete lack of interest, I shall take ?
> >> away the (better?) documentation ideas and unit testing ideas, and ?
> >> not worry about the rest. ?:)
>
> > Design by contract is complementary to unit testing (I notice that the ?
> > author of PEP 316 appears confused about this). ?DbC is, roughly ?
> > speaking, about explicit allocation of responsibility. ?Consider this ?
> > contrived example.
>
> > def foo(s):
> > ? ? require(s is not None)
> > ? ? //code
> > ? ? ensure(hasattr(returnValue, '__iter__'))
>
> > The require condition tells you that it's the caller's responsibility ?
> > to pass a non-nil argument to foo. ?The ensure condition is a ?guarantee
> > that foo will return something suitable for iteration, if ?the
> > precondition in the require condition is satisfied. ?These ?conditions
> > can be enforced at runtime, but may not be, for reasons of ?performance.
>
> > DbC is in fact about not *always* checking the input/output of ?
> > functions; on the contrary, Bertrand Meyer, the inventor of DbC, ?claims
> > that DbC allows one to eliminate such redundancy, and the ?resulting
> > overhead.
>
> > Charles Yeomans
>
> Many thanks!
>
> So if I understand -- Python's EAFP fits well with DbC, as DbC seems
> well suited to say, "This is your responsibility, and this is mine,"
> stated in programming terms (who needs comments? ;) ?Combined with unit
> testing (which should be easier to design correctly given the DbC code),
> healthy code seems more attainable.
>
> Interesting. ?Thank you for the information.
>
> ~Ethan~



From steve at REMOVE-THIS-cybersource.com.au  Wed Aug 12 11:58:28 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 15:58:28 GMT
Subject: Need cleanup advice for multiline string
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com>
	<4A82C355.8080304@sequans.com>
	
	<77a10bad-e0fe-4d50-95b2-f2f92a665001@h21g2000yqa.googlegroups.com>
	
Message-ID: <0292d70e$0$20647$c3e8da3@news.astraweb.com>

On Wed, 12 Aug 2009 08:11:43 -0700, Simon Forman wrote:

[quoting Robert Dailey]
>> I cannot completely doubt that there are logical
>> women out there. I just haven't seen one yet. But that doesn't mean I'm
>> a sexist.
> 
> Oh my.  And you were doing so well.  You haven't seen a logical woman? 
> Perhaps you're blind because your eyes were torn out by a raging
> marmoset?
> 
> Guess what?  Thinking (or just saying) that /does/ mean you're a sexist.
>  (Even if it was just another "friendly, harmless joke".)

It was an incredibly insensitive thing for Robert to say, having just 
been slapped for a previous insensitive "joke" about women. But still, 
most people, male or female, *aren't* logical. I know I've never met 
somebody who is entirely logical, of either sex, and I'm pretty sure I've 
not met very many people who are even mostly logical. Vulcans we are not. 
Does this mean I'm equally sexist against men *and* women? ("I'm not 
biased, I hate everyone equally!" *wink*)

Hell, here I am, at 2am, defending somebody I don't know, for saying 
something I don't approve of, against somebody who is saying something I 
agree with, out of some sort of misguided sense of fairness. Logic? Ha, 
what's logic got to do with it?



-- 
Steven


From db3l.net at gmail.com  Wed Aug 12 12:04:45 2009
From: db3l.net at gmail.com (David Bolen)
Date: Wed, 12 Aug 2009 12:04:45 -0400
Subject: Need cleanup advice for multiline string
References: 
Message-ID: 

Robert Dailey  writes:

> Hey guys. Being a C++ programmer, I like to keep variable definitions
> close to the location in which they will be used. This improves
> readability in many ways. However, when I have a multi-line string
> definition at function level scope, things get tricky because of the
> indents. In this case indents are serving two purposes: For syntax and
> actual text output. The tabs for function scope should not be included
> in the contents of the string. (...)

Personally I'm in the camp that something like this should be hoisted
out of the code path (whether to global scope, a dedicated message
module or configuration file is a design choice).

But if it's going to stay inline, one approach that can maintain some
of the attractive qualities of a triple quoted string is to make use
of the textwrap module:

    import textwrap

    def RunCommand( commandList ):
       # ...
       if returnCode:
           failMsg = textwrap.dedent('''\
                     *************************************************
                     The following command returned exit code [{:#x}].
                     This represents failure of some form. Please review
                     the command output for more details on the issue.
                     ------------
                     {}
                     *************************************************
                     ''')

which removes any common leading whitespace (must be identical in terms
of any tabs/spaces).

This is still additional run-time processing, and most likely less
efficient than the joining of individual strings, but it does permit a
clean triple-quoted string so IMO is easier to read/maintain in the
source - providing the code indentation level doesn't get in the way
of the desired line length of the string.  You can also choose to
dedent the string a bit (say to the level of "failMsg") if needed
without being forced all the way back to the left margin.

You can also combine textwrap.dedent with some of the other options if
where the strings are defined makes it nicer if they still have some
indentation (say in a global Python module).  In that case, you'd most
likely just process them once when the module was imported, so any
inefficiency in textwrap.dedent is far less important.

-- David


From paul at boddie.org.uk  Wed Aug 12 12:06:30 2009
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 Aug 2009 09:06:30 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	
	<7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>
	<0292a134$0$20647$c3e8da3@news.astraweb.com>
	<3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com>
	<0292cb5a$0$20647$c3e8da3@news.astraweb.com>
Message-ID: 

On 12 Aug, 17:08, Steven D'Aprano  wrote:
> On Wed, 12 Aug 2009 06:24:18 -0700, Paul Boddie wrote:
>
> > What does the Python entry on Wikipedia have to do with editing the
> > Python documentation in a Wiki?
>
> Good question. I was responding to you mentioning Wikipedia as a possible
> role model for the Python docs.

Yes, but claiming that only a few people want to edit a single entry
on one site (admittedly a popular one) isn't the same as saying that
few people would edit a documentation Wiki covering numerous different
things. A bunch of people edit the existing Python Wiki now, although
there's not that much direction behind it.

[...]

> It's not the people who suggest improvements to the docs that are the
> problem, but the ones who insist that the docs are terrible, but aren't
> willing to do anything but complain. Oh, and trolls like ... I hesitate
> to mention his name in case he has a bot monitoring the list ... first
> name starts with "X" followed by "ah", second name sounds like "Mee" ...
> who even if they make a few good points, they're lost in a sea of insults
> to others, arrogance and self-aggrandisement.

Right, but those good points are still worth taking on board. There
have been Xah Lee posts which have been relatively constructive, but
when the only responses are from people who see the name and can't be
bothered reading the message before issuing a stock "he's a troll"
response, the tone is likely to remain vulgar from that point onwards.
Xah Lee can be quite coherent and rational on comp.lang.lisp, which is
more than can be said for a number of regulars on that group.

[...]

> > P.S. The mention of "social problems" ties in with other remarks made
> > recently, and I've increasingly found it more trouble than has been
> > worthwhile to pursue Python-related matters of late. When one tries to
> > encourage people to participate in improving various things, which
> > usually means the community having to accept a degree of criticism,
> > people claim that it's encouraging "undesirable" influences to point
> > such critics in the right direction instead of showing them the door.
>
> Can you point me to a discussion where this has happened?

I won't name names as in some cases I've corresponded privately with
various people who have been perceived to be "trolls" (as you put it
above) and who have had the "don't talk to them" responses from
various regulars. Some people criticise in apparently unacceptable
ways for their own amusement, but most critics do so because they are
unaware of any better way and aren't aware of the most effective
methods to fix the issues that bother them, and this latter group is
clearly invested in finding solutions because they could quite easily
go and use something else. Certainly, I wouldn't spend my time
repeatedly enumerating the problems with a piece of technology if no-
one were interested in helping me do something about them.

> > When one tries to pursue such improvement matters oneself, people always
> > have something to say about the choice of technology or whether they
> > like the particular background colour being used
>
> You've discovered bike-shedding.
>
> > or indeed have an
> > opinion, typically shallow and negative, about anything but the task at
> > hand,
>
> When you're agitating for change, anyone defending the status quo has
> opinions which are shallow and negative. When you're happy with the
> status quo, possibly even for good, rational reasons and not just because
> you're a shallow-minded, ignorant, know-nothing nay-sayer, it's those
> agitating for change who have shallow and negative opinions. It's such a
> bother trying to determine who is right, so I prefer to just accuse the
> other guy of being shallow and negative rather than try to understand his
> point of view. I find it saves time in the long run.

I can expand what I've written to just about any project,
"improvement" or otherwise, where there may not be an existing
solution that anyone actually supports or is willing to use. And
still, if you give people something they could use (which is better
than effectively nothing), my experience is that in some communities
your work, however trivial, will be appreciated. But I get the
impression that in Python-related communities, it's all "Why didn't
you use XYZ?" or "What a toy!" instead.

[...]

> There seems to be a hidden assumption in your sentence that there *are*
> structural problems in the project.

Let me assume that maybe the barriers aren't really that bad for
Python documentation; that anyone who is really going to care about
submitting something will jump through the hoops and deliver something
that can be merged by the core developers. Even then, there's going to
be a whole class of improvements that won't get made by outsiders and
will fall on the editors to make. Now, more often than not, the people
who are already the most overworked are precisely those in the
position of reviewing and merging changes (as well as making their
own), and surely they will want to delegate some of that work, but
it's the classic pitfall of "delegation failure": they don't have the
capacity to delegate because that just means even more work for them
as a result. Shower such people with trivial change requests or bug
reports about documentation errors, and it's clear that the processes
aren't helping the editors to do more or for an increased number of
people to usefully collaborate.

I'm almost past caring about the documentation - it's useful for most
of what I want it for - because the bulk of the documentation that I
do use concerns the standard library which looks more and more
antiquated and disorganised every time I look at its contents. I don't
see any top-down remedy for this situation - Python 3 didn't even
bother with it properly - and maybe the solution will ultimately
involve a completely independent standard library developed by people
under their own steam who will then be criticised for not choosing the
most permissive licence possible and/or being technologically
backwards in some aspect of what they've done. That would, after all,
be the "Pythonic" response I'd most expect to see.

Paul


From rcdailey at gmail.com  Wed Aug 12 12:13:21 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Wed, 12 Aug 2009 09:13:21 -0700 (PDT)
Subject: Multithreaded library for Python?
Message-ID: 

Hey guys,

I realize the python library has multithreading support in it, but not
the kind I'm really looking for. I want something like Intel's TBB,
but for Python 3.1. I need to be able to spawn off "Tasks" that
operate until completed and then end by themselves. I could create my
own framework for this, but why bother if a solution already exists?
Anyone know of any libraries out there that would work?


From dotancohen at gmail.com  Wed Aug 12 12:18:43 2009
From: dotancohen at gmail.com (Dotan Cohen)
Date: Wed, 12 Aug 2009 19:18:43 +0300
Subject: Scraping Wikipedia with Python
In-Reply-To: <7xd472hz2x.fsf@ruckus.brouhaha.com>
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	
	<6YidncRAiJ6SIxzXRVn_vwA@giganews.com>
	
	<7xd472hz2x.fsf@ruckus.brouhaha.com>
Message-ID: <880dece00908120918u37b30c46w62a6edc850c644a9@mail.gmail.com>

> maybe you want dbpedia.

I did not know about this. Thanks!

That is the reason why I ask. This list has an unbelievable collective
knowledge and I am certain that asking "how much is 2+2" would net an
insightful answer that would teach me something.

Thank you, Paul, and thank you to the entire Python list!

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il


From dotancohen at gmail.com  Wed Aug 12 12:19:59 2009
From: dotancohen at gmail.com (Dotan Cohen)
Date: Wed, 12 Aug 2009 19:19:59 +0300
Subject: Scraping Wikipedia with Python
In-Reply-To: 
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	
	
Message-ID: <880dece00908120919n1fb8a74cj55641eae6654040f@mail.gmail.com>

> http://pypi.python.org/pypi?%3Aaction=search&term=wikipedia ?
>

Thanks, Thorsten, I will go through those. I did not know about that
resource, I am not a regular coder. One more resource to add to the
toolbox!


-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il


From dstanek at dstanek.com  Wed Aug 12 12:28:25 2009
From: dstanek at dstanek.com (David Stanek)
Date: Wed, 12 Aug 2009 12:28:25 -0400
Subject: httplib incredibly slow :-(
In-Reply-To: <4A81D3CB.7080209@simplistix.co.uk>
References: <4A81D3CB.7080209@simplistix.co.uk>
Message-ID: 

On Tue, Aug 11, 2009 at 4:25 PM, Chris Withers wrote:
> Hi All,
>
> I'm using the following script to download a 150Mb file:
>
> from base64 import encodestring
> from httplib import HTTPConnection
> from datetime import datetime
>
> conn = HTTPSConnection('localhost')
> headers = {}
> auth = 'Basic '+encodestring('username:password').strip()
> headers['Authorization']=auth
> t = datetime.now()
> print t
> conn.request('GET','/somefile.zip',None,headers)
> print 'request:',datetime.now()-t
> response = conn.getresponse()
> print 'response:',datetime.now()-t
> data = response.read()
> print 'read:',datetime.now()-t
>
> The output shows it takes over 20 minutes to do this.
> However, this is on a local network, and downloading the same file in IE
> takes under 3 seconds!
>
> I saw this issue:
>
> http://bugs.python.org/issue2576
>
> I tried changing the buffer size to 4096 in a subclass as the issue
> suggested, but I didn't see the reported speed improvement.
> I'm using Python 2.6.2.
>
> Does anyone know of an alternative library for creating http requests and
> getting their responses that's faster but hopefully has a similar interface?
>

I tried to reproduce this, but I could not. Could you paste in the
output of your script? Also on the same box where you run this script
can you test with curl or wget?

-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek


From hobesh at gmail.com  Wed Aug 12 12:30:48 2009
From: hobesh at gmail.com (Zach Hobesh)
Date: Wed, 12 Aug 2009 09:30:48 -0700
Subject: Mimicing an HTML form
Message-ID: 

Hi all,
I'm having alot of trouble automating the submitting of form.  I have an
HTML page that works and it looks like this:




When I put valid values for the handling script an app ID, this page works. Now I'm trying to turn this same functionality into a script. Here's my code: import urllib import os import urllib2 appID = *value here* video = os.path.normpath(os.getcwd() + '/news.wmv') title = 'News' desc = 'Here is a sample News video' uploader = *script here* print "Encoding url..." data = urllib.urlencode({"FileUploadedVideo": video, "hdnADCID" : appID, "txtTitle" : title, "txtDescription": desc}) user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = { 'User-Agent' : user_agent } print "Calling url..." req = urllib2.Request(uploader, data, headers) response = urllib2.urlopen(req) s = response.read() response.close() print "Writing results..." result = open('result.html','w') result.write(s) result.close() Does anybody have any suggestions? I keep on getting bad request, so I'm assuming that the html page is passing something that my script is not. Is there some way to scrape the POST request from the html form? Thanks, Zach -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at simplistix.co.uk Wed Aug 12 12:37:48 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Wed, 12 Aug 2009 17:37:48 +0100 Subject: httplib incredibly slow :-( In-Reply-To: References: <4A81D3CB.7080209@simplistix.co.uk> Message-ID: <4A82EFDC.70502@simplistix.co.uk> David Stanek wrote: > I tried to reproduce this, but I could not. Could you paste in the > output of your script? Not sure how that'll help, but sure: 2009-08-11 21:27:59.153000 request: 0:00:00.109000 response: 0:00:00.109000 read: 0:24:31.266000 > Also on the same box where you run this script > can you test with curl or wget? It's a Windows box, so no :-( But it really does download in a few seconds with IE, and 20min+ using the script I included... Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From ebonak at hotmail.com Wed Aug 12 12:42:17 2009 From: ebonak at hotmail.com (Esmail) Date: Wed, 12 Aug 2009 12:42:17 -0400 Subject: best practice for documenting a project? pydoc? In-Reply-To: References: Message-ID: shaileshkumar wrote: > Hello, > > EPYDOC is very good for automatic generation of documentation from > source code. > > You may also consider Sphinx http://sphinx.pocoo.org/ which is used > for many > projects including the official Python documentation, documentation of > Zope (http://docs.zope.org/). > See the full list of projects using Sphinx at http://sphinx.pocoo.org/examples.html > > - Shailesh Hi, Thanks for the links. Have you heard of something called HappyDoc? I just came across it by looking for info on epydoc. Thanks, Esmail From ebonak at hotmail.com Wed Aug 12 12:43:04 2009 From: ebonak at hotmail.com (Esmail) Date: Wed, 12 Aug 2009 12:43:04 -0400 Subject: best practice for documenting a project? pydoc? In-Reply-To: References: Message-ID: Mark Lawrence wrote: Hi Mark, > The docs for the constraint package look good, see > http://labix.org/python-constraint and http://labix.org/doc/constraint. > I think they've been produced with epydoc see > http://epydoc.sourceforge.net/ Thanks for the links, I'll take a look. Any experience with something called HappyDoc? Just came across it. Esmail From mdekauwe at gmail.com Wed Aug 12 12:43:11 2009 From: mdekauwe at gmail.com (Martin) Date: Wed, 12 Aug 2009 09:43:11 -0700 (PDT) Subject: matching patterns after regex? References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com> <2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com> <0292a4a9$0$20647$c3e8da3@news.astraweb.com> <18d5d342-b678-4101-a284-24d6176ac856@v20g2000yqm.googlegroups.com> Message-ID: On Aug 12, 1:42 pm, Martin wrote: > On Aug 12, 1:23 pm, Steven D'Aprano > > > cybersource.com.au> wrote: > > On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote: > > > I tried > > > > re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s) > > > You need to put quotes around strings. > > > In this case, because you're using regular expressions, you should use a > > raw string: > > > re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) > > > will probably work. > > > -- > > Steven > > Thanks I see. > > so I tried it and if I use it as it is, it matches the first instance: > I > n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) > Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')] > > So I adjusted the first part of the regex, on the basis I could sub > NORTH for SOUTH etc. > > In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\. > \w-]+)",s) > Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')] > > But in both cases it doesn't return the decimal value rather the value > that comes after NUM_VAL = , rather than VALUE = ? I think I kind of got that to work...but I am clearly not quite understanding how it works as I tried to use it again to match something else. In this case I want to print the values 0.000000 and 2223901.039333 from a string like this... YDim=1200\n\t\tUpperLeftPointMtrs=(0.000000,2223901.039333)\n\t\t I tried which I though was matching the statement and printing the decimal number after the equals sign?? re.findall(r"(\w+UpperLeftPointMtrs)*=\s([\d\.\w-]+)", s) where s is the string Many thanks for the help From ethan at stoneleaf.us Wed Aug 12 12:46:32 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 12 Aug 2009 09:46:32 -0700 Subject: Social problems of Python doc [was Re: Python docs disappointing] In-Reply-To: References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <0292a134$0$20647$c3e8da3@news.astraweb.com> <3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com> <0292cb5a$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A82F1E8.3090105@stoneleaf.us> Paul Boddie wrote: > On 12 Aug, 17:08, Steven D'Aprano cybersource.com.au> wrote: >>It's not the people who suggest improvements to the docs that are the >>problem, but the ones who insist that the docs are terrible, but aren't >>willing to do anything but complain. Oh, and trolls like ... I hesitate >>to mention his name in case he has a bot monitoring the list ... first >>name starts with "X" followed by "ah", second name sounds like "Mee" ... >>who even if they make a few good points, they're lost in a sea of insults >>to others, arrogance and self-aggrandisement. > > > Right, but those good points are still worth taking on board. The responsibility for communication is shared. How much to each party varies by circumstance (employer/employee, rank, volunteer, etc.). For myself, his posts are automatically deleted -- my time is precious to me. ~Ethan~ From chris at simplistix.co.uk Wed Aug 12 12:53:56 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Wed, 12 Aug 2009 17:53:56 +0100 Subject: httplib incredibly slow :-( In-Reply-To: References: <4A81FDF5.6010508@simplistix.co.uk> <4A8274A9.7000905@simplistix.co.uk> Message-ID: <4A82F3A4.8020903@simplistix.co.uk> shaileshkumar wrote: > We use PyCURL on Windows. http://pycurl.sourceforge.net/ provides pre- > built versions for Windows and it works out of the box. Does it include libcurl? Are these builds available for Python 2.6? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From chris at simplistix.co.uk Wed Aug 12 12:57:16 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Wed, 12 Aug 2009 17:57:16 +0100 Subject: httplib incredibly slow :-( In-Reply-To: References: <4A81FDF5.6010508@simplistix.co.uk> <4A8274A9.7000905@simplistix.co.uk> Message-ID: <4A82F46C.4080105@simplistix.co.uk> Max Erickson wrote: > There is an httplib2 (but I don't know anything further about it...): > > http://code.google.com/p/httplib2/ I had a look, it uses httplib, so will likely suffer from the same problems... > Calling wget or curl using a subprocess is probably as easy as it is > ugly, I use the wget build from here: > > http://gnuwin32.sourceforge.net/packages/wget.htm Yeah, no ;-) Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From shaileshk at gmail.com Wed Aug 12 13:00:08 2009 From: shaileshk at gmail.com (Shailesh Kumar) Date: Wed, 12 Aug 2009 22:30:08 +0530 Subject: httplib incredibly slow :-( In-Reply-To: <4A82F3A4.8020903@simplistix.co.uk> References: <4A81FDF5.6010508@simplistix.co.uk> <4A8274A9.7000905@simplistix.co.uk> <4A82F3A4.8020903@simplistix.co.uk> Message-ID: <92e4c3710908121000y3bcc8de6w56f767d78aa34ba6@mail.gmail.com> Yes it includes libcurl. I didn't have to install it separately. I still continue to use Python 2.4. So cannot say about Python 2.6. - Shailesh On Wed, Aug 12, 2009 at 10:23 PM, Chris Withers wrote: > shaileshkumar wrote: > >> We use PyCURL on Windows. http://pycurl.sourceforge.net/ provides pre- >> built versions for Windows and it works out of the box. >> > > Does it include libcurl? Are these builds available for Python 2.6? > > Chris > > -- > Simplistix - Content Management, Batch Processing & Python Consulting > - http://www.simplistix.co.uk > -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at please.post Wed Aug 12 13:01:01 2009 From: no.email at please.post (kj) Date: Wed, 12 Aug 2009 17:01:01 +0000 (UTC) Subject: How to find all possibly overlapping matches? Message-ID: re.findall finds all non-overlapping matches, but what if one wants all (maximal) matches, even those that overlap? All the solutions I can come up involve calling re.search iteratively, each time giving it a pos parameter starting just after the start of the previous match. Is there a built-in solution to such a task? TIA! kynn From python at mrabarnett.plus.com Wed Aug 12 13:23:21 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 12 Aug 2009 18:23:21 +0100 Subject: How to find all possibly overlapping matches? In-Reply-To: References: Message-ID: <4A82FA89.1040503@mrabarnett.plus.com> kj wrote: > > re.findall finds all non-overlapping matches, but what if one wants > all (maximal) matches, even those that overlap? > > All the solutions I can come up involve calling re.search iteratively, > each time giving it a pos parameter starting just after the start > of the previous match. > > Is there a built-in solution to such a task? > Not in the re module. It has been requested and is in my regex implementation at http://bugs.python.org/issue2636 if you want to try that. From darkwater42 at gmail.com Wed Aug 12 13:23:50 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Wed, 12 Aug 2009 10:23:50 -0700 (PDT) Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <0291a21a$0$20639$c3e8da3@news.astraweb.com> <8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com> <1a0e1e6d-d902-4df7-8d35-850c4f62cc9c@e27g2000yqm.googlegroups.com> Message-ID: On Aug 12, 3:08?am, Steven D'Aprano wrote: > On Tue, 11 Aug 2009 14:48:24 -0700, Douglas Alan wrote: > > In any case, my argument has consistently been that Python should have > > treated undefined escape sequences consistently as fatal errors, > > A reasonable position to take. I disagree with it, but it is certainly > reasonable. > > > not as warnings. > > I don't know what language you're talking about here, because non-special > escape sequences in Python aren't either errors or warnings: > > >>> print "ab\cd" > > ab\cd I was talking about C++, whose compilers tend to generate warnings for this usage. I think that the C++ compilers I've used take the right approach, only ideally they should be *even* more emphatic, and elevate the problem from a warning to an error. I assume, however, that the warning is a middle ground between doing the completely right thing, and, I assume, maintaining backward compatibility with common C implementations. As Python never had to worry about backward compatibility with C, Python didn't have to walk such a middle ground. On the other hand, *now* it has to worry about backward compatibility with itself. |>ouglas From breamoreboy at yahoo.co.uk Wed Aug 12 13:31:12 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Aug 2009 18:31:12 +0100 Subject: best practice for documenting a project? pydoc? In-Reply-To: References: Message-ID: Esmail wrote: > Mark Lawrence wrote: > Hi Mark, > >> The docs for the constraint package look good, see >> http://labix.org/python-constraint and http://labix.org/doc/constraint. >> I think they've been produced with epydoc see >> http://epydoc.sourceforge.net/ > > Thanks for the links, I'll take a look. > > Any experience with something called HappyDoc? Just came across it. > > Esmail > > Sorry never heard of it, or if I had I've forgotten it. -- Kindest regards. Mark Lawrence. From davea at ieee.org Wed Aug 12 13:35:45 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 12 Aug 2009 13:35:45 -0400 Subject: fileinput In-Reply-To: References: Message-ID: <4A82FD71.70501@ieee.org> naaman wrote: > I'm writing my first Python script and > I want to use fileinput to open a file in r+ mode. > Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > ANy ideas? > > Need to find and overwrite a line in a file several times. > I can do it using open and seek() etc. but was wondering if I can use > fileinput. > > thanks; > > > I haven't used it, but check out the 'inplace' keyword parameter. DaveA From jstroud at mbi.ucla.edu Wed Aug 12 13:37:45 2009 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 12 Aug 2009 10:37:45 -0700 Subject: hashability In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > Well there you go -- why on earth would you prohibit None as a dictionary > key??? That's a serious failure. roentgen 1% python Python 2.5 (r25:51908, Sep 20 2006, 17:36:21) [GCC 3.4.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. py> hash(None) 135543872 mbi136-176 98% /usr/bin/python Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. py> hash(None) 2030240 That's why. Read the whole thread. You are one of the abrasive ones. From darkwater42 at gmail.com Wed Aug 12 13:47:55 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Wed, 12 Aug 2009 10:47:55 -0700 (PDT) Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <0291a21a$0$20639$c3e8da3@news.astraweb.com> <8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com> Message-ID: On Aug 12, 3:36?am, Steven D'Aprano wrote: > On Tue, 11 Aug 2009 13:20:52 -0700, Douglas Alan wrote: > > My "Annotated C++ Reference Manual" is packed, and surprisingly in > > Stroustrup's Third Edition, there is no mention of the issue in the > > entire 1,000 pages. But Microsoft to the rescue: > > > ? ? ?If you want a backslash character to appear within a string, you > > ? ? ?must type two backslashes (\\) > > > (From http://msdn.microsoft.com/en-us/library/69ze775t.aspx) > > Should I assume that Microsoft's C++ compiler treats it as an error, not > a warning? In my experience, C++ compilers generally generate warnings for such situations, where they can. (Clearly, they often can't generate warnings for running off the end of an array, which is also undefined, though a really smart C++ compiler might be able to generate a warning in certain such circumstances.) > Or is is this *still* undefined behaviour, and MS C++ compiler > will happily compile "ab\cd" whatever it feels like? If it's a decent compiler, it will generate a warning. Who can say with Microsoft, however. It's clearly documented as illegal code, however. > > The question of what any specific C++ does if you ignore the warning is > > irrelevant, as such behavior in C++ is almost *always* undefined. Hence > > the warning. > > So a C++ compiler which follows Python's behaviour would be behaving > within the language specifications. It might be, but there are also *recommendations* in the C++ standard about what to do in such situations, and the recommendations say, I am pretty sure, not to do that, unless the particular compiler in question has to meet some very specific backward compatibility needs. > I note that the bash shell, which claims to follow C semantics, also does > what Python does: > > $ echo $'a s\trin\g with escapes' > a s ? ? rin\g with escapes Really? Not on my computers. (One is a Mac, and the other is a Fedora Core Linux box.) On my computers, bash doesn't seem to have *any* escape sequences, other than \\, \", \$, and \`. It seems to treat unknown escape sequences the same as Python does, but as there are only four known escape sequences, and they are all meant merely to guard against string interpolation, and the like, it's pretty darn easy to keep straight. > Explain to me again why we're treating underspecified C++ semantics, > which may or may not do *exactly* what Python does, as if it were the One > True Way of treating escape sequences? I'm not saying that C++ does it right for Python. The right thing for Python to do is to generate an error, as Python doesn't have to deal with all the crazy complexities that C++ has to. |>ouglas From clp2 at rebertia.com Wed Aug 12 13:50:33 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 12 Aug 2009 13:50:33 -0400 Subject: hashability In-Reply-To: References: Message-ID: <50697b2c0908121050w6fe89277n9f9b76b28f937f83@mail.gmail.com> On Wed, Aug 12, 2009 at 1:37 PM, James Stroud wrote: > Steven D'Aprano wrote: >> >> Well there you go -- why on earth would you prohibit None as a dictionary >> key??? That's a serious failure. > > > roentgen 1% python > Python 2.5 (r25:51908, Sep 20 2006, 17:36:21) [GCC 3.4.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > py> hash(None) > 135543872 > > > mbi136-176 98% /usr/bin/python > Python 2.5.1 (r251:54863, Feb ?6 2009, 19:02:12) [GCC 4.0.1 (Apple Inc. > build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > py> hash(None) > 2030240 Actually, None is a special-case as a built-in singleton value -- there's only ever *exactly one* instance of it in a given interpreter session. And I'm reasonably sure dict pickles don't store the hash code of items (the dict gets recreated from scratch), so there's no problem. Cheers, Chris -- http://blog.rebertia.com From no.email at please.post Wed Aug 12 14:00:16 2009 From: no.email at please.post (kj) Date: Wed, 12 Aug 2009 18:00:16 +0000 (UTC) Subject: How to find all possibly overlapping matches? References: Message-ID: In MRAB writes: >kj wrote: >> >> re.findall finds all non-overlapping matches, but what if one wants >> all (maximal) matches, even those that overlap? >> >> All the solutions I can come up involve calling re.search iteratively, >> each time giving it a pos parameter starting just after the start >> of the previous match. >> >> Is there a built-in solution to such a task? >> >Not in the re module. >It has been requested and is in my regex implementation at >http://bugs.python.org/issue2636 if you want to try that. Cool. Thanks! kynn From abecedarian314159 at yahoo.com Wed Aug 12 14:08:17 2009 From: abecedarian314159 at yahoo.com (William) Date: Wed, 12 Aug 2009 11:08:17 -0700 (PDT) Subject: SQLObject 0.11.0 In-Reply-To: <20090812102452.GE5602@phd.pp.ru> References: <20090812102452.GE5602@phd.pp.ru> Message-ID: <630942.37631.qm@web110607.mail.gq1.yahoo.com> I don't want to start a flame war and would just like some information before diving in-- What are some the advantages and disadvantages of SQLObject compared to SQLAlchemy? Thanks, William ________________________________ From: Oleg Broytmann To: Python Mailing List ; Python Announce Mailing List Sent: Wednesday, August 12, 2009 6:24:53 AM Subject: SQLObject 0.11.0 Hello! I'm pleased to announce version 0.11.0, the first stable release of 0.11 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.11.0 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.10 ----------------- Features & Interface ~~~~~~~~~~~~~~~~~~~~ * Dropped support for Python 2.3. The minimal version of Python for SQLObject is 2.4 now. * Dropped support for PostgreSQL 7.2. The minimal supported version of PostgreSQL is 7.3 now. * New magic attribute 'j' similar to 'q' was added that automagically does join with the other table in MultipleJoin or RelatedJoin. * SQLObject can now create and drop a database in MySQL, PostgreSQL, SQLite and Firebird/Interbase. * Added some support for schemas in PostgreSQL. * Added DecimalStringCol - similar to DecimalCol but stores data as strings to work around problems in some drivers and type affinity problem in SQLite. * Added sqlobject.include.hashcol.HashCol - a column type that automatically hashes anything going into it, and returns out an object that hashes anything being compared to itself. Basically, it's good for really simple one-way password fields, and it even supports the assignment of None to indicate no password set. By default, it uses the md5 library for hashing, but this can be changed in a HashCol definition. * RowDestroyedSignal and RowUpdatedSignal were added. Minor features ~~~~~~~~~~~~~~ * Use reversed() in manager/command.py instead of .__reversed__(). * Minor change in logging to console - logger no longer stores the output file, it gets the file from module sys every time by name; this means logging will use new sys.stdout (or stderr) in case the user changed them. * Changed the order of testing of SQLite modules - look for external PySQLite2 before sqlite3. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Wed Aug 12 14:11:40 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Aug 2009 18:11:40 GMT Subject: hashability References: Message-ID: <0292f646$0$20647$c3e8da3@news.astraweb.com> On Wed, 12 Aug 2009 10:37:45 -0700, James Stroud wrote: > Steven D'Aprano wrote: >> Well there you go -- why on earth would you prohibit None as a >> dictionary key??? That's a serious failure. > > > roentgen 1% python > Python 2.5 (r25:51908, Sep 20 2006, 17:36:21) [GCC 3.4.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > py> hash(None) > 135543872 > > > mbi136-176 98% /usr/bin/python > Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) [GCC 4.0.1 (Apple Inc. > build 5465)] on darwin Type "help", "copyright", "credits" or "license" > for more information. py> hash(None) > 2030240 > > > > That's why. Read the whole thread. You are one of the abrasive ones. I've read the whole thread. Pay close attention: [steve at ando ~]$ python Python 2.4.3 (#1, Mar 14 2007, 18:51:08) [GCC 4.1.1 20070105 (Red Hat 4.1.1-52)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pickle >>> d = {None: 42} >>> f = open('pickled_dict', 'w') >>> pickle.dump(d, f) >>> f.close() >>> [steve at ando ~]$ ssh sylar steve at sylar's password: Last login: Wed Aug 12 21:44:47 2009 [steve at sylar ~]$ python2.6 Python 2.6.1 (r261:67515, Dec 24 2008, 00:33:13) [GCC 4.1.2 20070502 (Red Hat 4.1.2-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pickle >>> f = open('pickled_dict', 'r') >>> d = pickle.load(f) >>> d {None: 42} I have successfully pickled a dict using None as a key on one machine using Python 2.4, and unpickled it on a completely different machine running Python 2.6. Still think that pickling None is a problem? -- Steven From schwehr at gmail.com Wed Aug 12 14:11:49 2009 From: schwehr at gmail.com (Kurt Schwehr) Date: Wed, 12 Aug 2009 11:11:49 -0700 (PDT) Subject: Pulling arrays from database for plotting Message-ID: <64fa9d35-a08b-4112-ba84-131f0f29c0f4@o15g2000yqm.googlegroups.com> Hi all, What's the best way to pull arrays from a database for plotting? Right now, this is what I do, but can it be done simpler / more efficiently? ipython -pylab import sqlite3 cx = sqlite3.connect('20080407.decimated.db3') a = array( [tuple(row) for row in cx.execute('SELECT cg_offset, delta_t_sec FROM bs_time WHERE recvr=2;')] ) x = a[:,0] y = a[:,1] plot(x,y) However, if I try to plot it directly using transpose, it hangs: import sqlite3 cx = sqlite3.connect('20080407.decimated.db3') plot(array( [tuple(row) for row in cx.execute('SELECT cg_offset, delta_t_sec FROM bs_time WHERE recvr=2;')] ).transpose()) It is that plot just doesn't know what to do with a 2D array? Then I tried this and it works, but is long and confusing to the uninitiated. plot(*array( [tuple(row) for row in cx.execute('SELECT cg_offset, delta_t_sec FROM bs_time WHERE recvr=2;')] ).T) In [4]: a Out[4]: array([[ 2.40000000e+01, 0.00000000e+00], [ 2.50000000e+01, -1.00000000e+00], [ 3.40000000e+01, 0.00000000e+00], ..., [ 8.63840000e+04, 2.00000000e+01], [ 8.63940000e+04, 2.00000000e+01], [ 8.64040000e+04, 2.00000000e+01]]) In [5]: a.transpose() Out[5]: array([[ 2.40000000e+01, 2.50000000e+01, 3.40000000e+01, ..., 8.63840000e+04, 8.63940000e+04, 8.64040000e+04], [ 0.00000000e+00, -1.00000000e+00, 0.00000000e+00, ..., 2.00000000e+01, 2.00000000e+01, 2.00000000e+01]]) From python at rcn.com Wed Aug 12 14:27:42 2009 From: python at rcn.com (Raymond Hettinger) Date: Wed, 12 Aug 2009 11:27:42 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> Message-ID: <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> On Aug 12, 3:32?am, Paul Boddie wrote: > Maybe the problem is that although everyone welcomes contributions and > changes (or says that they do), the mechanisms remain largely beyond > criticism. FWIW, I support the idea the regular docs incorporating links to freely editable wiki pages. That will at least make it easier for people to make changes or add notes. That being said, I would like to add a few thoughts about the current process. ISTM that important corrections (when the docs are clearly in error) tend to get made right away. What is more interesting are the doc requests that get rejected and why: * Many doc requests come from people just learning the language (that makes sense because the learning process involves reading the docs). Unfortunately, a fair number of those requests are flat-out wrong or represent a profound misunderstanding of the feature in question. That may be an indicator that the docs need to be improved, but the specific suggestion can be inane. * Some doc requests come from people who simply do not like the feature in question. It is natural for tastes, styles, and preferences to vary; however, we do have a firm rule that Guido's tastes, styles, and preferences are the ones that go into the language. So the doc writers need to try to channel Guido instead of fighting him. So, if you think eval() is evil (I don't but many do), we're not going to document that eval() should *never* be used. If you hate super(), that's too bad -- the docs need to describe what it does and how it was intended to be used -- the docs are no place for diatribes on why inheritance is over-used and why you think the world would be a better place without mixins or multiple inheritance. * Then, there is a matter of where to put a particular piece of documentation (how many times do you repeat a concept that pervades the language). Hashing is a good example. The docs can discuss how some objects hash to their object id and that object ids can change from run-to-run, but if someone gets tripped-up by the idea (hey, my set reprs changed between runs, wtf!), they want the docs updated in the specific place that tripped them up (i.e. you must put big red warnings in the set documentation, and the dict documentation, and everywhere else a hash gets used ...). The core problem is that the docs are interrelated -- the one place you're looking for documentation of a specific builtin or function can't contain every concept in the language. * Some behaviors are intentionally left unspecified. For the longest time, Tim did not want to guarantee sort stability. This left him free to continue to search for algorithmic improvements that did not have stability. Later, the property was deemed so important that it did become a guaranteed behavior. Also, some things are unspecified to make things easier for other implementations (IronPython, PyPy, Jython, etc.) We need to make sure that some one doesn't casually go through the docs making doc promises that are hard to keep. * Some things are just plain difficult to fully explain in English and not misrepresent that actual behavior. For example, the str.split () docs have been continuously tweaked over the years. Even now, I think there are corner cases that are not fully captured by the docs. Casual edits to str.split() docs are more likely than not to take them farther away from the truth. * Then, there is the problem of talking too much. A book could be written about super(), but that shouldn't all go into the docs for the super builtin. Beginners often want to master all the builtins and they try to read the doc page on builtin functions. It used to be that you could read through the builtin descriptions in a few minutes. Now, it takes a concerted effort to get through. It is hard to take a sip of water from a firehose. Too much information has make a function harder to understand. * My biggest pet peeve are requests to fill the docs with big red warnings. I do not want the docs to look like a mine field. The warnings should be reserved for a handful of security or data corruption risks. For the most part, the docs should be matter-of-fact, explaining what a function or method does and how it was intended to be used. Preferred: "The value str.letters is locale dependent" Not preferred: "Caution, the str.letters value can be adversely affected by the locale setting (it could even change length!); use this only when you are certain the locale setting will not violate any of your program invariants; consider using a string literal instead; I hate string.letters and think Guido was smoking crack when it was introduced." * Another category of rejected doc requests come from people looking for absolution from one of their programming bugs. It typically takes the form of, "I made an assumption that the language did X, but it did Y and my program didn't do what I wanted; therefore, the docs must be to blame and they must change ...". The suggestion is "I was suprised" implies "the docs are hosed". The fact is that people with diffferent backgrounds are going to have different expectations and someone is going to get "surprised". The docs need to say what functions do, but they don't need to be changed everytime someone writes a buggy program. In short, most doc requests that get rejected are requests that didn't actually improve the documentation. I do support links from the regular docs to an external wiki but the main docs should continue to go through the regular process using the tracker. Raymond From fetchinson at googlemail.com Wed Aug 12 14:40:01 2009 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 12 Aug 2009 11:40:01 -0700 Subject: SQLObject 0.11.0 In-Reply-To: <630942.37631.qm@web110607.mail.gq1.yahoo.com> References: <20090812102452.GE5602@phd.pp.ru> <630942.37631.qm@web110607.mail.gq1.yahoo.com> Message-ID: > I don't want to start a flame war and would just like some information > before diving in-- > What are some the advantages and disadvantages of SQLObject compared to > SQLAlchemy? In short: sqlobject is much simpler (to use, to understand, etc) than sqlalchemy and so I prefer it in small projects. This advantage is also a disadvantage when you have large and complex projects in mind. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From pavlovevidence at gmail.com Wed Aug 12 14:41:51 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Aug 2009 11:41:51 -0700 (PDT) Subject: hashability References: Message-ID: <1797a24d-7437-4a5c-bb67-9a81abb095c0@p10g2000prm.googlegroups.com> On Aug 12, 10:37?am, James Stroud wrote: > Steven D'Aprano wrote: > > Well there you go -- why on earth would you prohibit None as a dictionary > > key??? That's a serious failure. > > roentgen 1% python > Python 2.5 (r25:51908, Sep 20 2006, 17:36:21) > [GCC 3.4.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > py> hash(None) > 135543872 > > mbi136-176 98% /usr/bin/python > Python 2.5.1 (r251:54863, Feb ?6 2009, 19:02:12) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > py> hash(None) > 2030240 > > That's why. Read the whole thread. You are one of the abrasive ones. FYI: If you need the actual hash value to be consistent across versions of Python the built hash function won't suffice. The language doesn't guanrantee they will persist across versions. (IIRC, there was a change to the hash value of longs at one point related to int/long unification issues.) Now, when I saw your explanation I assumed that your persistence mechanism merely doesn't preserve identity (unlike, say, simple pickling, which does), meaning that objects that were once identical might be reconstituted as non-identical (or vice versa), which would be an issue if these objects are stored in dicts or sets. Equality must be preserved for dict keys and set members to continue to work property. However, the actual hash code doesn't need to be preserved. As was mentioned already, None is guaranteed by the language to be equal to itself, so equality is preserved and there should be no issue with it, even if the hash code changes across invocations. Now, if you are doing something weird with the hash value itself-- which I highly discourage--then all bets are off. Carl Banks From python at rcn.com Wed Aug 12 15:15:07 2009 From: python at rcn.com (Raymond Hettinger) Date: Wed, 12 Aug 2009 12:15:07 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> Message-ID: <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> [Xah Lee] > i've wrote several articles about this issue, total time spend on this > is probably more than 2 months full-time work. See: > > ? Python Documentation Problems > ?http://xahlee.org/perl-python/python_doc_index.html I just read you post. You did devote a substantial amount of time to the project. Some of your criticisms are valid. Wish you had posted patches, I think many of them would have been accepted. Since you wrote this a few years ago, many examples have been added to the docs and more are forthcoming. > I often receive thank you emails for 2 particular articles, which are > most frequently google searched as indicated by my weblog: > > ? Python Doc Problem Example: gzip > ?http://xahlee.org/perl-python/python_doc_gzip.html > > ? Python Doc Problem Example: sort() > ?http://xahlee.org/perl-python/python_doc_sort.html > > ? Sorting in Python and Perl > ?http://xahlee.org/perl-python/sort_list.html Some are the criticisms are valid; others seem off-base. Here are a few thoughts on list.sort() for those who are interested: * The key= and reversed= parameters are not intended for special cases, leaving cmp= for the general case. They were intended to be full replacements. In Python3.x, the cmp function is gone. * The interaction of the key= and cmp= functions can be made to interact (the key function is first applied to every element and the cmp function then gets applied to the results of the key function). This isn't a normal or intended use case, so the docs don't delve into the subject. * The reversed parameter does more than list.sort() followed by list.reverse(). It also preserves stability in the event of equal keys: >>> sorted([(1,2), (1,3)], key=itemgetter(0), reverse=True) [(1,2), (1,3)] So it was not correct to say that the following are equivalent: li.sort(lambda x, y: cmp(x[1],y[1]), reverse=True) li.sort(lambda x, y: cmp(y[1],x[1])) * We should link the sorted() and list.sort() docs to the sorting how-to (with a fuller discussion on the art of sorting including a discussion of operator.itemgetter() and operator.attrgetter() which were designed to work with the key= parameter. Raymond From mwkohout at gmail.com Wed Aug 12 15:44:51 2009 From: mwkohout at gmail.com (Michael Kohout) Date: Wed, 12 Aug 2009 12:44:51 -0700 (PDT) Subject: Extending embedded python-can extensions be local to a dictionary? Message-ID: <9d65250a-d4fa-440d-83ac-b22430284dab@24g2000yqm.googlegroups.com> Hello all- I've got a multithreaded server-based application that I'd like to use python to provide plugin support for. At execution time I would like each call to the plugin/plugins to have their own implementation of these extension methods. Looking at http://docs.python.org/extending/embedding.html#extending-embedded-python, I see how to add functions, but it looks like they are added at a global scope-not in a particular environment. Is there any way to add an extension to a local environment but not pollute the global env? FYI, I'm embedding python 2.6, but I'm more than open to embedding something newer. thanks Mike Kohout From rt8396 at gmail.com Wed Aug 12 16:14:51 2009 From: rt8396 at gmail.com (r) Date: Wed, 12 Aug 2009 13:14:51 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> Message-ID: <2fe731f6-8640-4e5c-bf39-62b22d635003@32g2000yqj.googlegroups.com> On Aug 12, 1:27?pm, Raymond Hettinger wrote: (snip) > * Many doc requests come from people just learning the language > (that makes sense because the learning process involves reading > the docs). ?Unfortunately, a fair number of those requests are > flat-out wrong or represent a profound misunderstanding of the > feature in question. ?That may be an indicator that the docs > need to be improved... Yes, if many people have problems with the docs then that must be a *clue* to some underling problem in the way the docs are presented. Whether its from misinfomation, misguidance, or just plain misunderstanding on the reader's part that does not matter. There are problems and we need the feedback from everybody noob-to-pro on how to fix this conundrum. One thing that some naysayers may forget is the fact that these noobs most likely have no idea *how*, *when*, or *where* to voice a complaint so they just move on to the next language or suffer with an incomplete understanding of the language and/or proper python idioms. I would say the complaints that this list has seen concerning docs only scratches the surface of the huge underling issues that face us here! > So, if you think eval() is evil (I don't but many > do), we're not going to document that eval() should *never* be used. > If you hate super(), that's too bad -- the docs need to describe > what it does and how it was intended to be used -- the docs are no > place for diatribes on why inheritance is over-used and why you > think the world would be a better place without mixins or > multiple inheritance. Eloquent and beautiful a paragraph that was Raymond. Why, because common sense is just so damn beautiful. Keep the docs clean of personal opinions and just give us the facts people. Who cares about the history of OOP --Google it!-- i want to read about using Python. Give me the nitty-gritty-down-and-dirty-facts that relate to Python syntax and structure, and only the facts, in the most strait forward and common sense way so i can get on to actually writing some code! If you seek self gratification visit c.l.py and vent away, everyone else seems to. From jschwab at gmail.com Wed Aug 12 16:34:19 2009 From: jschwab at gmail.com (jschwab) Date: Wed, 12 Aug 2009 13:34:19 -0700 (PDT) Subject: Format Code Repeat Counts? Message-ID: Are repeat counts supported Python's str.format() in some fashion? In Fortran my format strings can have repeat counts. write(*, fmt="3F8.3") [1, 2, 3] 1.000 2.000 3.000 I don't think printf-style format codes, which is what'd I'd previously used in Python, allow for repeat counts. As a more concrete example, say I have several sets of letters in a list of strings letters = ["aeiou", "hnopty", "egs", "amsp"] and I wanted to build a regular expression string out of them like re_str <==> "[aeiou][hnopty][egs][amsp]" Right now, the best I've got that doesn't require an explicit string like "[{1}][{2}][{3}][{4}]" is re_str = "".join(map(lambda x: "[{0}]".format(x), letters)) Is there a better way? Thanks, Josiah From alan.isaac at gmail.com Wed Aug 12 16:45:43 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Wed, 12 Aug 2009 20:45:43 GMT Subject: csv.DictWriter.write_header() Message-ID: Given a csv.DictWriter instance `dw` I think it would be nice to be able to say dw.write_header() instead of dw.writer.writerow(dw.fieldnames) Good idea? Alan Isaac From bernard.chhun at gmail.com Wed Aug 12 16:53:41 2009 From: bernard.chhun at gmail.com (Bernard) Date: Wed, 12 Aug 2009 13:53:41 -0700 (PDT) Subject: matching patterns after regex? References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com> <2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com> <0292a4a9$0$20647$c3e8da3@news.astraweb.com> <18d5d342-b678-4101-a284-24d6176ac856@v20g2000yqm.googlegroups.com> Message-ID: <85652297-16e7-489f-9e36-5092941df002@c34g2000yqi.googlegroups.com> On 12 ao?t, 12:43, Martin wrote: > On Aug 12, 1:42 pm, Martin wrote: > > > > > > > On Aug 12, 1:23 pm, Steven D'Aprano > > cybersource.com.au> wrote: > > > On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote: > > > > I tried > > > > > re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s) > > > > You need to put quotes around strings. > > > > In this case, because you're using regular expressions, you should use a > > > raw string: > > > > re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) > > > > will probably work. > > > > -- > > > Steven > > > Thanks I see. > > > so I tried it and if I use it as it is, it matches the first instance: > > I > > n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) > > Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')] > > > So I adjusted the first part of the regex, on the basis I could sub > > NORTH for SOUTH etc. > > > In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\. > > \w-]+)",s) > > Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')] > > > But in both cases it doesn't return the decimal value rather the value > > that comes after NUM_VAL = , rather than VALUE = ? > > I think I kind of got that to work...but I am clearly not quite > understanding how it works as I tried to use it again to match > something else. > > In this case I want to print the values 0.000000 and 2223901.039333 > from a string like this... > > YDim=1200\n\t\tUpperLeftPointMtrs=(0.000000,2223901.039333)\n\t\t > > I tried which I though was matching the statement and printing the > decimal number after the equals sign?? > > re.findall(r"(\w+UpperLeftPointMtrs)*=\s([\d\.\w-]+)", s) > > where s is the string > > Many thanks for the help You have to do it with 2 matches in the same regex: regex = r"UpperLeftPointMtrs=\(([\d\.]+),([\d\.]+)" The first match is before the , and the second one is after the , :) You should probably learn how to play with regexes. I personnaly use a visual tool called RX Toolkit[1] that comes with Komodo IDE. [1] http://docs.activestate.com/komodo/4.4/regex.html From pavlovevidence at gmail.com Wed Aug 12 16:57:53 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Aug 2009 13:57:53 -0700 (PDT) Subject: Extending embedded python-can extensions be local to a dictionary? References: <9d65250a-d4fa-440d-83ac-b22430284dab@24g2000yqm.googlegroups.com> Message-ID: <56b8b9d3-9166-4dc3-8166-1e60861d00b0@k26g2000vbp.googlegroups.com> On Aug 12, 12:44?pm, Michael Kohout wrote: > Hello all- > > I've got a multithreaded server-based application that I'd like to use > python to provide plugin support for. ?At execution time I would like > each call to the plugin/plugins to have their own implementation of > these extension methods. I am guessing that what you really want is each call to have its own data. There isn't much reason for each call to have its own methods. If that's not correct you will have to elaborate. > Looking athttp://docs.python.org/extending/embedding.html#extending-embedded-py..., > I see how to add functions, but it looks like they are added at a > global scope-not in a particular environment. ?Is there any way to add > an extension to a local environment but not pollute the global env? A couple things. They're not in a global scope, "globals" in Python have a scope local to a module (global is a misnomer, at best it means "globally accessible"). So you don't have to worry about a function defined on one module clashing with a function defined in another modules. However, even if name-clashes aren't an issue there isn't much point to defining the same function mulitple times for multiple calls. What you probably want is to define a new type that contains all the data extension code would need. For each call to the plugin, you would create an object of this type, then pass it to the appropriate plugin function. I have given you a vague answer because your question was vague; if you want a better answer please rephrase to be more specific. Include details like what you would like the code of a Python plugin to look like. Carl Banks From davigier at googlemail.com Wed Aug 12 17:09:29 2009 From: davigier at googlemail.com (David) Date: Wed, 12 Aug 2009 14:09:29 -0700 (PDT) Subject: How to launch a function at regular time intervals ? Message-ID: Hi all, I'm trying to launch a function at regular time intervals but cannot find the way to do it. Here is the code I wrote (time_interval is a user defined variable in seconds): while(1) timestamp=datetime.now() timestamp_seconds=timestamp.hour*3600+timestamp.minute*60+timestamp.second if timestamp_seconds % time_interval == 0: ****Call Function**** This does not work because during the second at which the condition holds true, there is time to call the function several times. Since I want to have this function called only once every x seconds, I tried to add the following condition: if timestamp_seconds % time_interval ==0 & timestamp.microsecond == 0 But it seems this second condition hardly ever happens (i.e. the timestamp variable is not updated every microsecond, therefore it can be 9998 then jump directly to 0003 for instance). Has anyone run into a similar problem (and solved it) ? Thanks for your help From darkwater42 at gmail.com Wed Aug 12 17:21:34 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Wed, 12 Aug 2009 14:21:34 -0700 (PDT) Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com> Message-ID: <7877b03a-09da-4836-804c-502b6f78003c@h21g2000yqa.googlegroups.com> On Aug 12, 5:32 am, Steven D'Aprano wrote: > That problem basically boils down to a deep-seated > philosophical disagreement over which philosophy a > language should follow in regard to backslash escapes: > > "Anything not explicitly permitted is forbidden" > > versus > > "Anything not explicitly forbidden is permitted" No, it doesn't. It boils down to whether a language should: (1) Try it's best to detect errors as early as possible, especially when the cost of doing so is low. (2) Make code as readable as possible, in part by making code as self-evident as possible by mere inspection and by reducing the amount of stuff that you have to memorize. Perl fails miserably in this regard, for instance. (3) To quote Einstein, make everything as simple as possible, and no simpler. (4) Take innately ambiguous things and not force them to be unambiguous by mere fiat. Allowing a programmer to program using a completely arbitrary resolution of "unrecognized escape sequences" violates all of the above principles. The fact that the meanings of unrecognized escape sequences are ambiguous is proved by the fact that every language seems to treat them somewhat differently, demonstrating that there is no natural intuitive meaning for them. Furthermore, allowing programmers to use "unrecognized escape sequences" without raising an error violates: (1) Explicit is better than implicit: Python provides a way to explicitly specify that you want a backslash. Every programmer should be encouraged to use Python's explicit mechanism here. (2) Simple is better than complex: Python currently has two classes of ambiguously interpretable escape sequences: "unrecognized ones", and "illegal" ones. Making a single class (i.e. just illegal ones) is simpler. Also, not having to memorize escape sequences that you rarely have need to use is simpler. (3) Readability counts: See above comments on readability. (4) Errors should never pass silently: Even the Python Reference Manual indicates that unrecognized escape sequences are a source of bugs. (See more comments on this below.) (5) In the face of ambiguity, refuse the temptation to guess. Every language, other than C++, is taking a guess at what the programmer would find to be most useful expansion for unrecognized escape sequences, and each of the languages is guessing differently. This temptation should be refused! You can argue that once it is in the Reference Manual it is no longer a guess, but that is patently specious, as Perl proves. For instance, the fact that Perl will quietly convert an array into a scalar for you, if you assign the array to a scalar variable is certainly a "guess" of the sort that this Python koan is referring to. Likewise for an arbitrary interpretation of unrecognized escape sequences. (6) There should be one-- and preferably only one --obvious way to do it. What is the one obvious way to express "\\y"? It is "\\y" or "\y"? Python can easily make one of these ways the "one obvious way" by making the other one raise an error. (7) Namespaces are one honking great idea -- let's do more of those! Allowing "\y" to self-expand is intruding into the namespace for special characters that require an escape sequence. > C++ apparently forbids all escape sequences, with > unspecified behaviour if you use a forbidden sequence, > except for a handful of explicitly permitted sequences. > > That's not better, it's merely different. It *is* better, as it catches errors early on at little cost, and for all the other reasons listed above. > Actually, that's not true -- that the C++ standard forbids > a thing, but leaves the consequences of doing that thing > unspecified, is clearly a Bad Thing. Indeed. But C++ has backward compatibly issues that make any that Python has to deal with, pale in comparison. The recommended behavior for a C++ compiler, however, is to flag the problem as an error or as a warning. > So on at least one machine in the world, C++ simply strips > out backslashes that it doesn't recognize, leaving the > suffix. Unfortunately, we can't rely on that, because C++ > is underspecified. No, *fortunately* you can't rely on it, forcing you to go fix your code. > Fortunately this is not a problem with > Python, which does completely specify the behaviour of > escape sequences so there are no surprises. It's not a surprise when the C++ compiler issues a warning to you. If you ignore the warning, then you have no one to blame but yourself. > Implicit has an actual meaning. You shouldn't use it as a > mere term of opprobrium for anything you don't like. Pardon me, but I'm using "implicit" to mean "implicit", and nothing more. Python's behavior here is "implicit" in the very same way that Perl implicitly converts an array into a scalar for you. (Though that particular Perl behavior is a far bigger wart than Python's behavior is here!) > > Because you've stated that "\y" is a legal escape > > sequence, while the Python Reference Manual explicitly > > states that it is an "unrecognized escape sequence", and > > that such "unrecognized escape sequences" are sources of > > bugs. > > There's that reading comprehension problem again. > > Unrecognised != illegal. This is reasoning that only a lawyer could love. The right thing for a programming language to do, when handed something that is syntactically "unrecognized" is to raise an error. > It seems to me that the behaviour the Python designers > were looking to avoid was the case where the coder > accidentally inserted a backslash in the wrong place, and > the language stripped the backslash out, e.g.: > > Wanted "a\bcd" but accidentally typed "ab\cd" instead, and > got "abcd". The moral of the story is that *any* arbitrary interpretation of unrecognized escape sequences is a potential source of bugs. In Python, you just end up with a converse issue, where one might understandably assume that "foo\bar" has a backslash in it, because "foo\yar" and *most* other similar strings do. But then it doesn't. > >> This is *exactly* like C++, except that in Python the > >> semantics of \y and \\y are identical. Python doesn't > >> guess what you mean, it *imposes* a meaning on the > >> escape sequence. You just don't like that meaning. > > That's because I don't like things that are > > ill-conceived. > And yet you like C++... go figure *wink* Now that's a bold assertion! I think that "tolerate C++" is more like it. But C++ does have its moments. |>ouglas From python at rcn.com Wed Aug 12 17:24:29 2009 From: python at rcn.com (Raymond Hettinger) Date: Wed, 12 Aug 2009 14:24:29 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> Message-ID: <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> [Raymond Hettinger] > Here are a few thoughts on list.sort() for those who are interested: After one more reading of Xah Lee's posts on the documentation for sort, here are couple more thoughts: * The reason that list.sort() allows None for the cmp parameter is not so that you can write list.sort(None). It was put there to make it easier for people writing function definitions where the cmp function is a possible argument: def sort_and_chop(seq, maxlen, cmp=None): s = seq[:] s.sort(cmp) # needs to accept None as a possible argument return s[:maxlen] * The reason for implementing the key= parameter had nothing to do with limitations of Python's compiler. Instead, it was inspired by the decorate-sort-undecorate pattern. Raymond From senad.ibraimoski at gmail.com Wed Aug 12 17:27:54 2009 From: senad.ibraimoski at gmail.com (Senad Ibraimoski -student-Mathematical Institute Belgrade) Date: Wed, 12 Aug 2009 14:27:54 -0700 (PDT) Subject: Plotting Quadratic Functions, pygame Message-ID: Hello, I'm a new guy to this group, my professor recommend this group to me, because I was boring him with questions.I'm new to python, and I have problem plotting Quadratic Functions. Using module pygame. Here is the code: #!/usr/bin/env python import pygame def main(): import sys import math from math import sqrt #Input equation coefficients screen=pygame.display.set_mode((400,400)) pygame.display.set_caption( ' Ploting ' ) screen.fill((255,255,255)) pen=((0,0,255)) dark=(0,0,0) ox=200 oy=200 a= int(raw_input('Input coefficient a ' )) b= int(raw_input('Input coefficient b ' )) c= int(raw_input('Input coefficient c ' )) pygame.draw.aaline(screen,((255,0,0)),((200,0)) ,((200,400))) pygame.draw.aaline(screen,((255,0,0)),((0,200)), ((400,200))) if a==0: if b==0: print 'No solutions' else: x= -c/b print x else: d=b*b-4*a*c if d<0: num=complex(-b/(2*a),sqrt(-d)/(2*a)) print num else: x1=(-b+sqrt(d))/(2*a) x2=(-b-sqrt(d))/(2*a) print 'x1= ' ,x1 print 'x2= ' ,x2 while 1: for event in pygame.event.get(): if event ==pygame.QUIT: print ' Quitting' pygame.quit() sys.exit(1) x=-50; while x<=50: y=(a*(x**2) + b*x + c) *(-1) screen.set_at(((x+ox),(y+oy)),dark) pygame.display.flip() x=x+1; return 0 if __name__ == '__main__': main() For now I'm plotting function only when Determinant >0. Or in other words, when equation has two solutions, x1,x2 e R... Now if you start my program you will see where problem is. It's with function, It so bad drawn. When I try to increment x in loop by 0.1 for every pass, I get problems because method set_at() Which sets pixel requires integer... Also I see I have problems with event handling here: while 1: for event in pygame.event.get(): if event ==pygame.QUIT: print ' Quitting' pygame.quit() sys.exit(1) When I click X, or exit on windows it doesn't exit. What do you suggest I do...? I don't have in this year Computer Graphics on my faculty. So this are my first steps in this area of CS. Regards, S.I From breamoreboy at yahoo.co.uk Wed Aug 12 17:29:11 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Aug 2009 22:29:11 +0100 Subject: matching patterns after regex? In-Reply-To: <85652297-16e7-489f-9e36-5092941df002@c34g2000yqi.googlegroups.com> References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com> <2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com> <0292a4a9$0$20647$c3e8da3@news.astraweb.com> <18d5d342-b678-4101-a284-24d6176ac856@v20g2000yqm.googlegroups.com> <85652297-16e7-489f-9e36-5092941df002@c34g2000yqi.googlegroups.com> Message-ID: Bernard wrote: > On 12 ao?t, 12:43, Martin wrote: >> On Aug 12, 1:42 pm, Martin wrote: >> >> >> >> >> >>> On Aug 12, 1:23 pm, Steven D'Aprano >> cybersource.com.au> wrote: >>>> On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote: >>>>> I tried >>>>> re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s) >>>> You need to put quotes around strings. >>>> In this case, because you're using regular expressions, you should use a >>>> raw string: >>>> re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) >>>> will probably work. >>>> -- >>>> Steven >>> Thanks I see. >>> so I tried it and if I use it as it is, it matches the first instance: >>> I >>> n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) >>> Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')] >>> So I adjusted the first part of the regex, on the basis I could sub >>> NORTH for SOUTH etc. >>> In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\. >>> \w-]+)",s) >>> Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')] >>> But in both cases it doesn't return the decimal value rather the value >>> that comes after NUM_VAL = , rather than VALUE = ? >> I think I kind of got that to work...but I am clearly not quite >> understanding how it works as I tried to use it again to match >> something else. >> >> In this case I want to print the values 0.000000 and 2223901.039333 >> from a string like this... >> >> YDim=1200\n\t\tUpperLeftPointMtrs=(0.000000,2223901.039333)\n\t\t >> >> I tried which I though was matching the statement and printing the >> decimal number after the equals sign?? >> >> re.findall(r"(\w+UpperLeftPointMtrs)*=\s([\d\.\w-]+)", s) >> >> where s is the string >> >> Many thanks for the help > > You have to do it with 2 matches in the same regex: > > regex = r"UpperLeftPointMtrs=\(([\d\.]+),([\d\.]+)" > > The first match is before the , and the second one is after the , :) > > You should probably learn how to play with regexes. > I personnaly use a visual tool called RX Toolkit[1] that comes with > Komodo IDE. > > [1] http://docs.activestate.com/komodo/4.4/regex.html Haven't tried it myself but how about this? http://re-try.appspot.com/ -- Kindest regards. Mark Lawrence. From no.email at please.post Wed Aug 12 17:41:38 2009 From: no.email at please.post (kj) Date: Wed, 12 Aug 2009 21:41:38 +0000 (UTC) Subject: How to page output in >>> ? Message-ID: How does one tell the python interactive interpreter to run the next output to stdout through the default pager? Basically, I'm looking for Python's equivalent of Perl's debugger's "|" prefix, as in DB<1> |print $long_output TIA! kynn From i3dmaster at gmail.com Wed Aug 12 17:56:27 2009 From: i3dmaster at gmail.com (i3dmaster) Date: Wed, 12 Aug 2009 14:56:27 -0700 (PDT) Subject: httplib incredibly slow :-( References: <4A81D3CB.7080209@simplistix.co.uk> Message-ID: On Aug 12, 9:37?am, Chris Withers wrote: > David Stanek wrote: > > I tried to reproduce this, but I could not. Could you paste in the > > output of your script? > > Not sure how that'll help, but sure: > > 2009-08-11 21:27:59.153000 > request: 0:00:00.109000 > response: 0:00:00.109000 > read: 0:24:31.266000 > > ?> Also on the same box where you run this script > > > can you test with curl or wget? > > It's a Windows box, so no :-( > But it really does download in a few seconds with IE, and 20min+ using > the script I included... > > Chris > > -- > Simplistix - Content Management, Batch Processing & Python Consulting > ? ? ? ? ? ? -http://www.simplistix.co.uk Just wanted to check if you can try turning on the debug mode for httplib and see if you can read a bit more debug info on where the calls get hung. In your example, it would be conn.set_debuglevel(1) From lists at cheimes.de Wed Aug 12 18:01:44 2009 From: lists at cheimes.de (Christian Heimes) Date: Thu, 13 Aug 2009 00:01:44 +0200 Subject: How to launch a function at regular time intervals ? In-Reply-To: References: Message-ID: <4A833BC8.1000801@cheimes.de> David wrote: > Has anyone run into a similar problem (and solved it) ? Yeah, here is my implementation as a perpetual timer based some cherrypy code and threading timer. import threading class PerpetualTimer(threading._Timer): """A subclass of threading._Timer whose run() method repeats. Based on cherrpy.process.plugins.PerpetualTimer """ def __init__(self, interval, function, name=None, daemon=False, args=(), kwargs={}): super(PerpetualTimer, self).__init__(interval, function, args, kwargs) self.setName(name) self.setDaemon(daemon) def run(self): while True: self.finished.wait(self.interval) if self.finished.isSet(): return self.function(*self.args, **self.kwargs) def stop(self, timeout=None): self.cancel() self.join(timeout) def callback(egg): egg.cook() timer = PerpetualTimer(100, callback, name="EggTimer", args=(somegg,)) timer.start() ... timer.stop() Christian From user at tld.invalid Wed Aug 12 18:07:23 2009 From: user at tld.invalid (Bartosz Wroblewski) Date: 12 Aug 2009 22:07:23 GMT Subject: How to launch a function at regular time intervals ? References: Message-ID: On Wed, 12 Aug 2009 14:09:29 -0700, David wrote: > > Hi all, I'm trying to launch a function at regular time intervals but > cannot find the way to do it. > For what it's worth, here's how I do it: ---------------8<--------------- #!/usr/bin/env python from time import sleep interval = 25 #seconds while not sleep(interval): f(spam, eggs, knight) ---------------8<--------------- You might want to put the sleep inside an *obviously* infinite loop. Note that this works best (most accurately) for longer periods. If you need to account for the time spent in the actual f() calls, plug in a time.time() call where appropriate. -- | <")-, | ''The good-enough is the enemy of the excellent.'' - John Miles | (_==/ |-----------,----------------------------------------------------- | ='- | Bartosz Wroblewski | bawr from holyhandgrenade.info or int8.org From python at mrabarnett.plus.com Wed Aug 12 18:19:18 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 12 Aug 2009 23:19:18 +0100 Subject: Format Code Repeat Counts? In-Reply-To: References: Message-ID: <4A833FE6.5030700@mrabarnett.plus.com> jschwab wrote: > Are repeat counts supported Python's str.format() in some fashion? > > In Fortran my format strings can have repeat counts. > > > write(*, fmt="3F8.3") [1, 2, 3] > 1.000 2.000 3.000 > > > I don't think printf-style format codes, which is what'd I'd > previously used in Python, allow for repeat counts. > > As a more concrete example, say I have several sets of letters in a > list of strings > letters = ["aeiou", "hnopty", "egs", "amsp"] > and I wanted to build a regular expression string out of them like > re_str <==> "[aeiou][hnopty][egs][amsp]" > Right now, the best I've got that doesn't require an explicit string > like "[{1}][{2}][{3}][{4}]" is > re_str = "".join(map(lambda x: "[{0}]".format(x), letters)) > > Is there a better way? > The shortest I can come up with is: "[" + "][".join(letters) + "]" From clp2 at rebertia.com Wed Aug 12 18:23:32 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 12 Aug 2009 18:23:32 -0400 Subject: Format Code Repeat Counts? In-Reply-To: References: Message-ID: <50697b2c0908121523jc495a65y1957a503b4f10566@mail.gmail.com> On Wed, Aug 12, 2009 at 4:34 PM, jschwab wrote: > As a more concrete example, say I have several sets of letters in a > list of strings > ? ? letters = ["aeiou", "hnopty", "egs", "amsp"] > and I wanted to build a regular expression string out of them like > ? ? re_str <==> "[aeiou][hnopty][egs][amsp]" > Right now, the best I've got that doesn't require an explicit string > like "[{1}][{2}][{3}][{4}]" is > ? ? re_str = "".join(map(lambda x: "[{0}]".format(x), letters)) > > Is there a better way? Slightly better, by using a generator expression instead of map() and lambda: re_str = "".join("[{0}]".format(x) for x in letters) Though obviously MRAB's is shorter (and a good show of lateral thinking). Cheers, Chris -- http://blog.rebertia.com From jgardner at jonathangardner.net Wed Aug 12 18:34:34 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Wed, 12 Aug 2009 15:34:34 -0700 (PDT) Subject: Plotting Quadratic Functions, pygame References: Message-ID: <14363c28-482a-40fe-bbdf-e727fb68dce6@i18g2000pro.googlegroups.com> Before we get into fixing your code, let's talk about style. A lot of bugs are solved when you fix the style, and the remaining bugs are much easier to find and fix. (Comments inline) On Aug 12, 2:27?pm, Senad Ibraimoski -student-Mathematical Institute Belgrade wrote: > Hello, I'm a new guy to this group, my professor recommend this group > to me, because I was boring him with questions.I'm new to python, and > I have problem plotting Quadratic Functions. Using module pygame. > Here is the code: > > #!/usr/bin/env python Vertical whitespace is very useful for separating different parts of your code, just like you do when you write paragraphs. > import pygame vertical whitespeace. > def main(): Throwing everything into one function is rarely a good idea. I'll identify ways you can separate out the code below into functions. For now, your code can share data between functions with global variables. Down the road, you may want to encapsulate the shared data in objects. > ? ? ? ? import sys > ? ? ? ? import math > ? ? ? ? from math import sqrt Put all the import statements at the top, as much as you can. > ? ? ? ? #Input equation coefficients > ? ? ? ? screen=pygame.display.set_mode((400,400)) > ? ? ? ? pygame.display.set_caption( ' Ploting ' ) > ? ? ? ? screen.fill((255,255,255)) > ? ? ? ? pen=((0,0,255)) > ? ? ? ? dark=(0,0,0) > ? ? ? ? ox=200 > ? ? ? ? oy=200 There are really two parts here: Getting the screen setup and drawing. Both should be separated into two functions. > ? ? ? ? a= int(raw_input('Input coefficient a ' )) > ? ? ? ? b= int(raw_input('Input coefficient b ' )) > ? ? ? ? c= int(raw_input('Input coefficient c ' )) Another part deals with collecting user input. Note that you shouldn't be collecting ints but floats. (Ideally, you would collect real numbers, but representing that in a computer is difficult.) > ? ? ? ? pygame.draw.aaline(screen,((255,0,0)),((200,0)) ,((200,400))) > ? ? ? ? pygame.draw.aaline(screen,((255,0,0)),((0,200)), ((400,200))) This draws the coordinate axes. This belongs in another function. > ? ? ? ? if a==0: > ? ? ? ? ? ? ? ? if b==0: > ? ? ? ? ? ? ? ? ? ? ? ? print 'No solutions' > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? x= -c/b > ? ? ? ? ? ? ? ? ? ? ? ? print x > ? ? ? ? else: > ? ? ? ? ? ? ? ? d=b*b-4*a*c > ? ? ? ? ? ? ? ? if d<0: > ? ? ? ? ? ? ? ? ? ? ? ? num=complex(-b/(2*a),sqrt(-d)/(2*a)) > ? ? ? ? ? ? ? ? ? ? ? ? print num > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? x1=(-b+sqrt(d))/(2*a) > ? ? ? ? ? ? ? ? ? ? ? ? x2=(-b-sqrt(d))/(2*a) > ? ? ? ? ? ? ? ? ? ? ? ? print 'x1= ' ,x1 > ? ? ? ? ? ? ? ? ? ? ? ? print 'x2= ' ,x2 The solver belongs in another function. I would have the solver take a representation of the equation (simply a tuple of (a, b, c)) and return a list of solutions. If there are no solutions, then return an empty list. > ? ? ? ? ? ? ? ? ? ? ? ? while 1: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? for event in pygame.event.get(): > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if event ==pygame.QUIT: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ' Quitting' > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? pygame.quit() > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? sys.exit(1) > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? x=-50; > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? while x<=50: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? y=(a*(x**2) + b*x + c) *(-1) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? screen.set_at(((x+ox),(y+oy)),dark) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? pygame.display.flip() > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? x=x+1; The main loop belongs in another function. The drawing bit belongs in another function. > > ? ? ? ? return 0 > > if __name__ == '__main__': main() > > For now I'm plotting function only when Determinant >0. Or in other > words, when equation has two solutions, > x1,x2 e R... Now if you start my program you will see where problem > is. It's with function, It so bad drawn. > When I try to increment x in loop by 0.1 for every pass, I get > problems because method set_at() Which sets pixel requires integer... > Your drawing function that you write should take a scaling factor in addition to the equation it is trying to draw. You'll have to round the floats to the nearest integer. This is pretty easy to do: number_as_int = int(number_as_float + 0.5) Rather than step between arbitrary numbers, step through every point on the graph. For this equation, y = a x^2 + b x + c, right? So walk from left-to-right over all visible values of x (0 to 400, or rather -200 to 200) and find y. > I don't have in this year Computer Graphics on my faculty. So this are > my first steps in this area of CS. > This is a very good first step. You have a bright future in programming and perhaps in computer graphics. From python at mrabarnett.plus.com Wed Aug 12 18:38:44 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 12 Aug 2009 23:38:44 +0100 Subject: Format Code Repeat Counts? In-Reply-To: <50697b2c0908121523jc495a65y1957a503b4f10566@mail.gmail.com> References: <50697b2c0908121523jc495a65y1957a503b4f10566@mail.gmail.com> Message-ID: <4A834474.9000304@mrabarnett.plus.com> Chris Rebert wrote: > On Wed, Aug 12, 2009 at 4:34 PM, jschwab wrote: > >> As a more concrete example, say I have several sets of letters in a >> list of strings >> letters = ["aeiou", "hnopty", "egs", "amsp"] >> and I wanted to build a regular expression string out of them like >> re_str <==> "[aeiou][hnopty][egs][amsp]" >> Right now, the best I've got that doesn't require an explicit string >> like "[{1}][{2}][{3}][{4}]" is >> re_str = "".join(map(lambda x: "[{0}]".format(x), letters)) >> >> Is there a better way? > > Slightly better, by using a generator expression instead of map() and lambda: > re_str = "".join("[{0}]".format(x) for x in letters) > > Though obviously MRAB's is shorter (and a good show of lateral thinking). > Python 3.1 supports auto-numbered placeholders "[{}]", so: re_str = ("[{}]" * len(letters)).format(*letters) From emile at fenx.com Wed Aug 12 18:45:00 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 12 Aug 2009 15:45:00 -0700 Subject: Format Code Repeat Counts? In-Reply-To: References: Message-ID: On 8/12/2009 1:34 PM jschwab said... > Are repeat counts supported Python's str.format() in some fashion? > > In Fortran my format strings can have repeat counts. > > > write(*, fmt="3F8.3") [1, 2, 3] > 1.000 2.000 3.000 > > > I don't think printf-style format codes, which is what'd I'd > previously used in Python, allow for repeat counts. > > As a more concrete example, say I have several sets of letters in a > list of strings > letters = ["aeiou", "hnopty", "egs", "amsp"] > and I wanted to build a regular expression string out of them like > re_str <==> "[aeiou][hnopty][egs][amsp]" > Right now, the best I've got that doesn't require an explicit string > like "[{1}][{2}][{3}][{4}]" is > re_str = "".join(map(lambda x: "[{0}]".format(x), letters)) > > Is there a better way? > I don't know. I often end up at something like: "[%s]"*len(letters) % tuple(letters) Emile From gb345 at invalid.com Wed Aug 12 18:57:33 2009 From: gb345 at invalid.com (gb345) Date: Wed, 12 Aug 2009 22:57:33 +0000 (UTC) Subject: Need feedback on ORF-extracting code Message-ID: Hi everyone. I'm relatively new to Python, and could use your feedback on the code below. First some nomenclature. A "nucleotide" is one of A, C, G, T, or U. (In practice, a sequence of such nucleotides never contains both T and U, but this fact is not important in what follows.) A "codon" is a sequence of 3 of these. A "stop codon" is any one of UAA, UAG, UGA, TAA, TAG, or TGA. Two codons are said to be "in frame" in a containing sequence of nucleotides if their positions differ by a multiple of 3. An "open reading frame," or ORF, is defined as a maximal subsequence of nucleotides whose length is a multiple of 3, begins with either AUG or ATG, terminates right before a stop codon in the original sequence, and contains no stop codons that are in frame with the initial codon (AUG or ATG). The fact that ORFs have lengths that are multiples of 3 means that there are three possible "registers" for ORFs (depending the modulo 3 of their starting positions), and that ORFs in different registers can overlap. I'll refer to these registers as 0, 1, and 2, because they contain ORFs that are in frame with the codons at positions 0, 1, and 2 of the original sequence, respectively. In the code below, routine extract_orfs takes as input a string, assumed to be a sequence of nucleotides, and returns a tuple of tuples, describing ORFs. These ORFs can overlap. The helper routine _xo takes as input a string (a sequence of nucleotides), and an offset, and returns a tuple of tuples, again representing ORFs, but this time all in the same register, since they are all in frame with the position passed as the second argument to the function. I would appreciate your comments on this code. I feel that it is not as clear as it could be, but I don't know how to make it any clearer. (NOTE: I realize that, in all likelihood, publicly available Python code already exists for this. At the moment I'm more interested in improving my Python skills.) Many thanks in advance! Gabe # BEGINNING OF CODE import sys import re _start = r'A[TU]G' _stop = r'(?:[TU]A[AG]|[TU]GA)' _nonstop = r'(?:[CAG][TUCAG]{2}|[TU](?:[TUC][TUCAG]|[AG][TUC])|[TU]GG)' _codon = r'(?:[TUCAG]{3})' _orf_re = re.compile('(' + _codon + r'*?)(A[TU]G' + _nonstop + '*)(' + _stop + ')', flags=re.I) _lead_re = re.compile(r'[TUCAG]*?A[TU]G', flags=re.I) def _xo(seq, pos): """ Helper routine that finds all the non-overlapping in-frame orfs starting from a specific position in the input sequence. input: a string of letters in the set 'tucagTUCAG', and a starting position; output: a tuple of tuples; each internal tuple consists of a starting position, an orf, and the stop codon that terminates it. """ ret = [] while True: m = _orf_re.match(seq, pos) if not m: break orf = m.group(2) stop = m.group(3) assert len(orf) % 3 == 0 ret.append((m.start() + len(m.group(1)), orf, stop)) pos = m.end() return ret def extract_orfs(seq): """ Extracts all (possibly overlapping) maximal open reading frames, defined as sequences beginning with AUG (or ATG), ending with an in-frame stop codon, and containing no in-frame stop codons in-between. input: a string of letters in the set 'tucagTUCAG'; output: a tuple of tuples; each internal tuple consists of a starting position, an orf, and the stop codon that terminates it. """ m = _lead_re.match(seq) if not m: return () pos = m.start() ret = [] for i in range(min(3, len(seq))): ret.extend(_xo(seq, pos + i)) ret.sort() return tuple(ret) # END OF CODE From steve at REMOVE-THIS-cybersource.com.au Wed Aug 12 19:19:20 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Aug 2009 23:19:20 GMT Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com> <7877b03a-09da-4836-804c-502b6f78003c@h21g2000yqa.googlegroups.com> Message-ID: <02933e60$0$20647$c3e8da3@news.astraweb.com> On Wed, 12 Aug 2009 14:21:34 -0700, Douglas Alan wrote: > On Aug 12, 5:32 am, Steven D'Aprano > wrote: > >> That problem basically boils down to a deep-seated philosophical >> disagreement over which philosophy a language should follow in regard >> to backslash escapes: >> >> "Anything not explicitly permitted is forbidden" >> >> versus >> >> "Anything not explicitly forbidden is permitted" > > No, it doesn't. It boils down to whether a language should: > > (1) Try it's best to detect errors as early as possible, especially when > the cost of doing so is low. You are making an unjustified assumption: \y is not an error. It is only an error if you think that anything not explicitly permitted is forbidden. While I'm amused that you've made my own point for me, I'm less amused that you seem to be totally incapable of seeing past your parochial language assumptions, even when those assumptions are explicitly pointed out to you. Am I wasting my time engaging you in discussion? There's a lot more I could say, but time is short, so let me just summarise: I disagree with nearly everything you say in this post. I think that a few points you make have some validity, but the vast majority are based on a superficial and confused understanding of language design principles. (I won't justify that claim now, perhaps later, time permitting.) Nevertheless, I think that your ultimate wish -- for \y etc to be considered an error -- is a reasonable design choice, given your assumptions. But it's not the only reasonable design choice, and Bash has made a different choice, and Python has made yet a third reasonable choice, and Pascal made yet a fourth reasonable choice. These are all reasonable choices, all have some good points and some bad points, but ultimately the differences between them are mostly arbitrary personal preference, like the colour of a car. Disagreements over preferences I can live with. One party insisting that red is the only logical colour for a car, and that anybody who prefers white or black or blue is illogical, is unacceptable. -- Steven From nobody at nowhere.com Wed Aug 12 19:23:10 2009 From: nobody at nowhere.com (Nobody) Date: Thu, 13 Aug 2009 00:23:10 +0100 Subject: How to page output in >>> ? References: Message-ID: On Wed, 12 Aug 2009 21:41:38 +0000, kj wrote: > How does one tell the python interactive interpreter to run the > next output to stdout through the default pager? Basically, I'm > looking for Python's equivalent of Perl's debugger's "|" prefix, > as in > > DB<1> |print $long_output Something like: sys.stdout.flush() p = subprocess.Popen([os.environ['PAGER']], stdin = subprocess.PIPE) sys.stdout = p.stdin ... sys.stdout.flush() sys.stdout = sys.__stdout__ p.stdin.close() p.wait() but with error and exception handling. But personally, I'd write the data to the child process explicitly if that's possible. From mdekauwe at gmail.com Wed Aug 12 19:29:38 2009 From: mdekauwe at gmail.com (Martin) Date: Wed, 12 Aug 2009 16:29:38 -0700 (PDT) Subject: matching patterns after regex? References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com> <2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com> <0292a4a9$0$20647$c3e8da3@news.astraweb.com> <18d5d342-b678-4101-a284-24d6176ac856@v20g2000yqm.googlegroups.com> <85652297-16e7-489f-9e36-5092941df002@c34g2000yqi.googlegroups.com> Message-ID: On Aug 12, 10:29?pm, Mark Lawrence wrote: > Bernard wrote: > > On 12 ao?t, 12:43, Martin wrote: > >> On Aug 12, 1:42 pm, Martin wrote: > > >>> On Aug 12, 1:23 pm, Steven D'Aprano >>> cybersource.com.au> wrote: > >>>> On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote: > >>>>> I tried > >>>>> re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s) > >>>> You need to put quotes around strings. > >>>> In this case, because you're using regular expressions, you should use a > >>>> raw string: > >>>> re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) > >>>> will probably work. > >>>> -- > >>>> Steven > >>> Thanks I see. > >>> so I tried it and if I use it as it is, it matches the first instance: > >>> I > >>> n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) > >>> Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')] > >>> So I adjusted the first part of the regex, on the basis I could sub > >>> NORTH for SOUTH etc. > >>> In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\. > >>> \w-]+)",s) > >>> Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')] > >>> But in both cases it doesn't return the decimal value rather the value > >>> that comes after NUM_VAL = , rather than VALUE = ? > >> I think I kind of got that to work...but I am clearly not quite > >> understanding how it works as I tried to use it again to match > >> something else. > > >> In this case I want to print the values 0.000000 and 2223901.039333 > >> from a string like this... > > >> YDim=1200\n\t\tUpperLeftPointMtrs=(0.000000,2223901.039333)\n\t\t > > >> I tried which I though was matching the statement and printing the > >> decimal number after the equals sign?? > > >> re.findall(r"(\w+UpperLeftPointMtrs)*=\s([\d\.\w-]+)", s) > > >> where s is the string > > >> Many thanks for the help > > > You have to do it with 2 matches in the same regex: > > > regex = r"UpperLeftPointMtrs=\(([\d\.]+),([\d\.]+)" > > > The first match ?is before the , and the second one is after the , :) > > > You should probably learn how to play with regexes. > > I personnaly use a visual tool called RX Toolkit[1] that comes with > > Komodo IDE. > > > [1]http://docs.activestate.com/komodo/4.4/regex.html > > Haven't tried it myself but how about this?http://re-try.appspot.com/ > > -- > Kindest regards. > > Mark Lawrence. Thanks Mark and Bernard. I have managed to get it working and I appreciate the help with understanding the syntax. The web links are also very useful, I'll give them a go. Martin From python at mrabarnett.plus.com Wed Aug 12 19:40:03 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 13 Aug 2009 00:40:03 +0100 Subject: Unrecognized escape sequences in string literals In-Reply-To: <02933e60$0$20647$c3e8da3@news.astraweb.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com> <7877b03a-09da-4836-804c-502b6f78003c@h21g2000yqa.googlegroups.com> <02933e60$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A8352D3.3070003@mrabarnett.plus.com> Steven D'Aprano wrote: > On Wed, 12 Aug 2009 14:21:34 -0700, Douglas Alan wrote: > >> On Aug 12, 5:32 am, Steven D'Aprano >> wrote: >> >>> That problem basically boils down to a deep-seated philosophical >>> disagreement over which philosophy a language should follow in regard >>> to backslash escapes: >>> >>> "Anything not explicitly permitted is forbidden" >>> >>> versus >>> >>> "Anything not explicitly forbidden is permitted" >> No, it doesn't. It boils down to whether a language should: >> >> (1) Try it's best to detect errors as early as possible, especially when >> the cost of doing so is low. > > You are making an unjustified assumption: \y is not an error. It is only > an error if you think that anything not explicitly permitted is forbidden. > > While I'm amused that you've made my own point for me, I'm less amused > that you seem to be totally incapable of seeing past your parochial > language assumptions, even when those assumptions are explicitly pointed > out to you. Am I wasting my time engaging you in discussion? > > There's a lot more I could say, but time is short, so let me just > summarise: > > I disagree with nearly everything you say in this post. I think that a > few points you make have some validity, but the vast majority are based > on a superficial and confused understanding of language design > principles. (I won't justify that claim now, perhaps later, time > permitting.) Nevertheless, I think that your ultimate wish -- for \y etc > to be considered an error -- is a reasonable design choice, given your > assumptions. But it's not the only reasonable design choice, and Bash has > made a different choice, and Python has made yet a third reasonable > choice, and Pascal made yet a fourth reasonable choice. > IHMO, it would've been simpler in the long run to say that backslash followed by one of [0-9A-Za-z] is an escape sequence, backslash followed by newline is ignored, and backslash followed by anything else is that something. That way there would be a way to introduce additional escape sequences without breaking existing code. From davea at ieee.org Wed Aug 12 20:30:16 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 12 Aug 2009 20:30:16 -0400 Subject: How to launch a function at regular time intervals ? In-Reply-To: References: Message-ID: <4A835E98.2070507@ieee.org> David wrote: > Hi all, I'm trying to launch a function at regular time intervals but > cannot find the way to do it. Here is the code I wrote (time_interval > is a user defined variable in seconds): > > while(1) > timestamp=datetime.now() > > timestamp_seconds=timestamp.hour*3600+timestamp.minute*60+timestamp.second > if timestamp_seconds % time_interval == 0: ****Call Function**** > > This does not work because during the second at which the condition > holds true, there is time to call the function several times. Since I > want to have this function called only once every x seconds, I tried > to add the following condition: > > if timestamp_seconds % time_interval ==0 & timestamp.microsecond == 0 > > But it seems this second condition hardly ever happens (i.e. the > timestamp variable is not updated every microsecond, therefore it can > be 9998 then jump directly to 0003 for instance). > > Has anyone run into a similar problem (and solved it) ? > > Thanks for your help > > I'm assuming you want to call it every time_interval seconds, on average, with a little jitter allowed on each call, but keeping correct long term. In other words, if one call is a little late, you want the next one to still happen as close to on-time as possible. The general outline is something like (untested): times_called = 0 #number of times function has been called start_time = now while True: elapsed = now - start_time int_elapsed = int(elapsed/time_interval) for times_called in range(times_called, int_elapsed): call_the_function() sleep(time_interval/10) #this might give us 10% jitter, which is usually fine DaveA From drobinow at gmail.com Wed Aug 12 20:53:43 2009 From: drobinow at gmail.com (David Robinow) Date: Wed, 12 Aug 2009 20:53:43 -0400 Subject: httplib incredibly slow :-( In-Reply-To: <4A82EFDC.70502@simplistix.co.uk> References: <4A81D3CB.7080209@simplistix.co.uk> <4A82EFDC.70502@simplistix.co.uk> Message-ID: <4eb0089f0908121753o5ecf141dj304b21c3df0d3d6b@mail.gmail.com> On Wed, Aug 12, 2009 at 12:37 PM, Chris Withers wrote: > David Stanek wrote: >> Also on the same box where you run this script >> can you test with curl or wget? > It's a Windows box, so no :-( Why not? http://users.ugent.be/~bpuype/wget/ http://curl.haxx.se/download.html From arphaksad at gmail.com Wed Aug 12 21:15:42 2009 From: arphaksad at gmail.com (naaman) Date: Wed, 12 Aug 2009 18:15:42 -0700 (PDT) Subject: fileinput References: Message-ID: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> On Aug 12, 1:35?pm, Dave Angel wrote: > naaman wrote: > > I'm writing my first Python script and > > I want to use fileinput to open a file in r+ mode. > > Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > > ANy ideas? > > > Need to find and overwrite a line in a file several times. > > I can do it using open and seek() etc. but was wondering if I can use > > fileinput. > > > thanks; > > I haven't used it, but check out the 'inplace' keyword parameter. > > DaveA I've only Python for a week so I'm not sure what inplace does From rylesny at gmail.com Wed Aug 12 21:25:40 2009 From: rylesny at gmail.com (ryles) Date: Wed, 12 Aug 2009 18:25:40 -0700 (PDT) Subject: run all scripts in sub-directory as subroutines? References: Message-ID: <0639e183-5c38-42b6-8411-3fd53e5ec01d@r34g2000vba.googlegroups.com> On Aug 11, 5:12?pm, guthrie wrote: > This works fine, but in the sub-modules the sys.path appropriately > returns the same as from the parent, I want them to know their own > file names. How?? I can pass it to them, but wondered if there is a > more self-sufficient way for a module to know from where it was > invoked. Instead of sys.path, you may be interested in the __file__ attribute will give you a module's filename: http://docs.python.org/reference/simple_stmts.html#index-1031 You could also be more explicit in matching *.py files in your subdirectory by using glob: http://docs.python.org/library/glob.html From cousinstanley at gmail.com Wed Aug 12 22:21:25 2009 From: cousinstanley at gmail.com (Cousin Stanley) Date: Thu, 13 Aug 2009 02:21:25 +0000 (UTC) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> Message-ID: > FWIW, I support the idea the regular docs incorporating links > to freely editable wiki pages. That will at least make it > easier for people to make changes or add notes. > > That being said, I would like to add a few thoughts about the > current process. ISTM that important corrections (when the > docs are clearly in error) tend to get made right away. What > is more interesting are the doc requests that get rejected > and why: > .... > In short, most doc requests that get rejected are requests > that didn't actually improve the documentation. > .... Raymond .... Thanks for your very eloquent and cohernt response that in my opinion helps to explain many of the problems, either real or perceived, with the Python documentation .... -- Stanley C. Kitching Human Being Phoenix, Arizona From sjmachin at lexicon.net Wed Aug 12 22:24:19 2009 From: sjmachin at lexicon.net (John Machin) Date: Wed, 12 Aug 2009 19:24:19 -0700 (PDT) Subject: csv.DictWriter.write_header() References: Message-ID: On Aug 13, 6:45?am, Alan G Isaac wrote: > Given a csv.DictWriter instance `dw` > I think it would be nice to be able to > say dw.write_header() > instead of > dw.writer.writerow(dw.fieldnames) > > Good idea? Yes, it's a brilliant idea. All you have to do is insert the following lines in your code after importing csv: csv.DictWriter.write_header = ( lambda dw: dw.writer.writerow(dw.fieldnames) ) From saptarshi.guha at gmail.com Wed Aug 12 22:32:26 2009 From: saptarshi.guha at gmail.com (sapsi) Date: Wed, 12 Aug 2009 19:32:26 -0700 (PDT) Subject: Write binary data to standard error? Message-ID: <9514cb7a-2962-484a-9669-c39533de138b@w41g2000yqb.googlegroups.com> Hello, This is probably a basic question, but how does one write binary data to standard error e.g int as network order (4 bytes)? Much thanks Saptarshi From saptarshi.guha at gmail.com Wed Aug 12 22:44:38 2009 From: saptarshi.guha at gmail.com (Saptarshi) Date: Wed, 12 Aug 2009 19:44:38 -0700 (PDT) Subject: Write binary data to standard error? References: <9514cb7a-2962-484a-9669-c39533de138b@w41g2000yqb.googlegroups.com> Message-ID: <765589c3-98da-45b9-ab35-475ca5c76250@g10g2000yqh.googlegroups.com> On Aug 12, 10:32?pm, sapsi wrote: > Hello, > This is probably a basic question, but how does one write binary data > to standard error e.g int as network order (4 bytes)? > > Much thanks > Saptarshi Solved: import sys import os from struct import * d=os.fdopen(sys.stderr.fileno(),"wb") d.write("\x00") d.write(pack(">i",5)) From alan.isaac at gmail.com Wed Aug 12 23:15:51 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Thu, 13 Aug 2009 03:15:51 GMT Subject: csv.DictWriter.write_header() In-Reply-To: References: Message-ID: > On Aug 13, 6:45 am, Alan G Isaac wrote: >> Given a csv.DictWriter instance `dw` >> I think it would be nice to be able to >> say dw.write_header() >> instead of >> dw.writer.writerow(dw.fieldnames) >> >> Good idea? On 8/12/2009 10:24 PM John Machin apparently wrote: > Yes, it's a brilliant idea. All you have to do is insert the following > lines in your code after importing csv: > > csv.DictWriter.write_header = ( > lambda dw: dw.writer.writerow(dw.fieldnames) > ) I do not understand the reason for your silly, sarcastic response. I already showed you how to achieve the result, so obviously I am not just asking for my own personal gain. I take it you do not realize that many users do not see a simple way to get this often needed functionality. (For example, see the gymnatics suggested by Shai Vaingast in his otherwise excellent and useful book.) And indeed, there is no reason to expect them to. So my question was, would this improve the class from a usability perspective? Do you have a useful response? Alan Isaac From rurpy at yahoo.com Wed Aug 12 23:23:27 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Wed, 12 Aug 2009 20:23:27 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> Message-ID: <65053f02-0e64-4070-90c8-e04394be90ad@d32g2000yqh.googlegroups.com> On 08/12/2009 01:58 AM, Steven D'Aprano wrote: > On Tue, 11 Aug 2009 14:50:51 -0700, rurpy wrote: > >>>> The issue tracker is fine for many things, but the process it provides >>>> is equivalent to peep-hole optimization. How does one submit a >>>> tracker issue for something like the overall organization of the docs >>>> (for example, the mis-placement of things like data- types in the >>>> library manual rather than the language manual)? >>> The same way you would submit a tracker issue for anything. >>> >>> "Documentation bug: Data types are misplaced in the library manual >>> instead of the language manual. >>> >>> Suggested alternative: move page docs.python.org/xyz.html to abc.html" >> But that's the problem. Such a reorg is not a simple matter of moving a >> file from here to there. It will require a lot moving about of sections >> and a lot of word-smithing to glue them back together again in a >> coherent way. > > That's no different from *any* major refactoring. The exact same problem > exists for code as well as documentation. It's a solved problem for code, > and it's a solved problem for documentation. Huh? I don't buy this at all. Code refactoring doesn't change the semantics of the program at all -- it simplifies the code that implements behavior without changing behavior. How does this apply to revising documentation? It may be true that some of the same techniques applicable to maintaining code are applicable to documentation but I need a lot more than your assertion to believe they are as equivalent as you seem to be claiming. > In some order: > > Consensus that there is a problem that needs solving; > Volunteer(s) to do the work; > Somebody to take responsibility to check the changes in. That's not refactoring as I understand it -- that is making a large change. I don't see that that addresses the problem of getting a large patch approved or the other issues I mentioned. > Sometimes, in the face of apathy or disagreement (which may very well be > justified), you have to at least partly solve the problem *before* people > will agree that it needed to be solved. Welcome to the real world. > >> A tracker issue, even one that was fairly specific about how things >> should be reorganized but which did not provide all the needed changes >> (a large patch) would almost certainly be ignored or rejected. > > Yes it would. Most patches are ignored, because the dev team are > overworked, and if they don't see the need for a patch, they won't > approve it. I'm confused. If they weren't overworked, then they would approve patches they didn't see a need for? Or are you saying because they are overworked they fail to approve patches that should be approved? I am not sure how either supports the argument that the tracker is the best method of improving the docs. >> But >> providing a large patch raises two questions. How likely is it to be be >> accepted? (Something anyone would want to know before investing the >> time.) And how to actually do the work needed to generate it (it could >> be a very large amount of work for an individual and I don't think it >> can be broken down into small independent issues.) How is one to test >> the waters as to acceptability, or solicit help, if one simply submits a >> tracker issue? > > No, submitting a tracker issue is a necessary but not sufficient step. > Without a tracker issue, you're very unlikely to have people agree to > replace the existing docs with your docs, although a PEP would probably > do it. (A PEP is significantly more effort than raising a tracker issue.) Has there ever been a PEP for a doc change? Are you making a serious suggestion? > You also have to get attention from those with check-in privileges. If > they approve your patches, you're done. If they don't approve them, or > fail to respond, you can try convincing them, or taking it to the Python- > Dev list and request somebody review your patches. > > If you have no patches, perhaps because you're unwilling to invest the > effort without a guarantee that it will be treated seriously, then you > need to get some sort of consensus among the relevant people that the > problem is worth solving. You are again describing the current process, not the issue of whether the current process is the optimal one or not. And while I would never expect a guarantee that a particular submission would be accepted, I think I would need, if not a guarantee, at least a high expectation that a submission would be treated seriously before I invested a large amount of work in it. > Guess what? Sometimes others will disagree with you. What you see as the > Worst. Docs. EVAR. may be seen as perfectly adequate, even excellent, by > others. If this is the case, remember, Python isn't your product, you > don't have veto over what goes into it. Feel free to publish your > alternatives. Write a book. Go home and cry into your beer over it. > Whatever. Sometimes you win, and sometimes you don't. Right, this is obvious. But the other side of that coin is that if people who see problems with the docs perceive that those who control access to the docs have no interest in changing them, then the first group will likely post their complaints on this newsgroup. If you don't like that then you have the same choices you listed above. Of course if the docs really are that good, there will relatively few complaints and the vast majority of readers will recognize the few complaints as invalid and ignore them, so if you are right that the docs are good enough, there should be no problem. > This is the same process whether dealing with code or documentation. > >>> - if people are keen on a Python wiki, then by all means publish one, >>> just don't expect the Python dev team to build and manage it for you; >> As luminous a Pythoneer as Fredrik Lundh set up a documentation wiki to >> collect user contributions but it has faded away. If he couldn't pull >> it off then I'd say most other attempts without the backing of >> python.org are almost certainly doomed to failure. > > Perhaps that's a good indication that a Python wiki *doesn't* fulfill a > need in the community, and that despite what a few squeaky wheels think, > the docs *are* doing a good job? That fails to explain the repeated criticisms of the docs here and in blogs. Of course this argument is not likely to convince you since there is no reliable quantitative support for the claim that there are more complaints about the docs than other aspects of Python -- it relies on each individual's powers of observation. But you also have to explain away very specific criticisms of the docs such as Xah Lee's as invalid or exceptions. >> As long as every "the docs >> sux" complaint is met here with the standard responses that I've >> mentioned, > > But they aren't met with such a so-called "standard response". I just looked through the first 70 or so messages in this thread and in this case I have agree with you, most of the responses were not what I called "standard responses". There was one guy, a Steven D'Aprano early on that trotted out the, "it's free software, fix it if you don't like it" line, and the troll epithet was used a time or two, but the vast majority were in fact reasonable and thoughtful responses. I will try to find some examples from other past threads. >> rather than, "yes, they do have some problems, what do you >> think we should do about them?", > > We know that there are problems. We've said repeatedly that corrections > and patches are welcome. We've repeatedly told you how to communicate > your answer to the question of what should be done. None of this is good > enough for you. I don't know what else you expect. You have been told repeatedly why your insistence that the tracker must be the only channel, is wrong. I don't understand why you can't understand that. (Generally only those in authority, bosses, parents, police, and the like, "tell" others what a situation is and have a right to demand that the subject accept it without question. I think you could find a more respectful and less authoritarian way of phrasing what you said above since you are not in a position of authority over me.) And who exactly is this "we" that you are a member of? >>> If you won't put in the effort, and you won't put in the money, then it >>> won't happen. Moaning that other people aren't putting in the money to >>> hire team of professional writers isn't productive, and moaning that >>> other people aren't putting in the effort to improve the docs isn't >>> either. >> Eh? I have a computer filled with software that I put no money or >> effort into, yet there it is. > > Ah yes, I'm sorry, I missed one other alternative: sit around and wait > for somebody else to put in the money and/or effort. > >> That some of us choose to >> invest it somewhere other than Python does not deprive of of our right >> to point out problems in Python when we note them. > > Of course not. But it does mean that you won't be taken seriously, and > you have no right to be taken seriously. On usenet no one has a right to anything. You can take my posts however you wish. I've tried to make reasonable arguments to support my view (with the understanding that these are usenet posts, not a doctoral thesis). But you (and the unnamed "we" above) seem to feel that public complaints or discussion about better alternatives to the current doc improvement process are somehow out-of-bounds. I'm sorry, I disagree. From http Thu Aug 13 00:11:12 2009 From: http (Paul Rubin) Date: 12 Aug 2009 21:11:12 -0700 Subject: Scraping Wikipedia with Python References: <4a81b6f0$0$1590$742ec2ed@news.sonic.net> <6YidncRAiJ6SIxzXRVn_vwA@giganews.com> <7xd472hz2x.fsf@ruckus.brouhaha.com> Message-ID: <7xtz0c8ian.fsf@ruckus.brouhaha.com> Dotan Cohen writes: > > maybe you want dbpedia. > I did not know about this. Thanks! You might also like freebase/metaweb. From walkraft at gmail.com Thu Aug 13 00:15:02 2009 From: walkraft at gmail.com (casebash) Date: Wed, 12 Aug 2009 21:15:02 -0700 (PDT) Subject: Nice copy in interactive terminal Message-ID: Hello fellow Python Users, I've been wondering for a while if there exists an interactive terminal which has nice copy feature (ie. I can copy code without getting the >>> in front of every line). Thanks, Chris PS. apologies if I am posting this in the wrong group. I am unsure of the exact scope of this group. From frank at chagford.com Thu Aug 13 00:20:05 2009 From: frank at chagford.com (Frank Millman) Date: Thu, 13 Aug 2009 06:20:05 +0200 Subject: How to launch a function at regular time intervals ? References: Message-ID: On Aug 12, 11:09 pm, David wrote: > Hi all, I'm trying to launch a function at regular time intervals but > cannot find the way to do it. I assume you want your main program to continue running, while launching the function to run in the background. If you need this as a general capability, Christian's approach is probably the way to go. In my case I had one specific requirement, and found it easier to write a dedicated solution, as follows - import threading class MyFunction(threading.Thread): """Perform function every 30 seconds in separate thread""" def __init__(self): threading.Thread.__init__(self) self.event = threading.Event() def run(self): while not self.event.is_set(): # either call your function here, # or put the body of the function here self.event.wait(30) # wait for 30 seconds def stop(self): self.event.set() At the start of the main program, I have the following - func = MyFunction() func.start() When closing the main program, I have - func.stop() func.join() It is trivial to modify this to pass the interval, plus any other parameters required, as arguments. HTH Frank Millman From gagsl-py2 at yahoo.com.ar Thu Aug 13 00:39:40 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 01:39:40 -0300 Subject: Changing Remote Registry References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com> <4A7C6D96.3000201@timgolden.me.uk> <5caea3690908100547l65394e65le111d8f3dda9e903@mail.gmail.com> Message-ID: En Mon, 10 Aug 2009 09:47:19 -0300, Kevin Holleran escribi?: > On Fri, Aug 7, 2009 at 2:08 PM, Tim Golden wrote: >> Kevin Holleran wrote: >> >>> hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE) >>> value,type = _winreg.QueryValueEx(hKey, item) >>> if (value == wrongValue): >>> _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue) >>> >>> >>> When I do this I receive the error: >>> >>> _winreg.SetValue WindowsError: [Error 5] Access Denied >>> > I guess my question is will Windows let me change the registry remotely? > The error is a Windows permission error on the KEY_SET_VALUE. I am > running > this as a domain admin on a machine on the domain. Does the connection > inherit the credentials I am running it under or will I need to pass > those > in? Or does Windows simply not let me change the registry? Try doing the same interactively with regedt32.exe (logged as the same user). You can check your actual permissions under the Edit menu. Also, try using KEY_WRITE instead of KEY_SET_VALUE. -- Gabriel Genellina From bouncyinc at gmail.com Thu Aug 13 00:41:47 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Wed, 12 Aug 2009 22:41:47 -0600 Subject: getting a "simple" program to work In-Reply-To: References: <50697b2c0908112146q6e12650dt914518166b4fae72@mail.gmail.com> Message-ID: Just checking to see if this is more adequate to what you would have wanted to see I didn't get any feedback so I wasn't quite sure of this at the present time. On Tue, Aug 11, 2009 at 11:02 PM, John Haggerty wrote: > > > On Tue, Aug 11, 2009 at 10:46 PM, Chris Rebert wrote: > >> On Sun, Aug 9, 2009 at 8:42 PM, John Haggerty wrote: >> > ok so I know this is one of those "weird" requests but here me out. >> > So far I have an issue with a package for python called "libgmail" which >> is >> > basically a gmail interface for python to send messages remoetly. >> > Works ok except that the 'sendMessage' routine is bad. >> >> How is it "bad" precisely? Be specific (e.g. error message(s), >> description of observed incorrect behavior). >> > > In regards to bad would be failing to transmit claiming that the submittal > is wrong for the transmit string. > > (where username is my gmail username and "password" is my gmail password to > the test account, 6666666969 is the mobile number in question '00' is my > "carrier id" from the ogss code example which is just an array location from > a preformatted part of the string [probably from wikipedia on mobile carrier > email addresses to cell phones], I actually got desperate and commented out > the first attempt to transmit which I located in the code as just the > "instructions" the code fails on re-transmission, I later on looked at the > file and located that it was a zero byte file of no content. The program > itself looks for a command from the user's cell phone directly from mms sent > to the target gmail account prefaced by "Ogss" and anything else is treated > as a command but since the command failed on the first transmit I don't > think it's the command per se). > > owner at bouncyinc:~/Desktop/OGSS$ python ogss.py username password > 6666666969 00 > Starting ogss > Logfile at:/home/owner/ogss.log > Opening log file for reading > Parsing user input > Connecting to Gmail > Logging into Gmail > Opening log file for writing > Listening for commands > Processing Command > ls: unrecognized option `---------------------------------------------' > Try `ls --help' for more information. > Seding back results > Traceback (most recent call last): > File "ogss.py", line 127, in > main(sys.argv) > File "ogss.py", line 110, in main > account.sendMessage(tosend) > File "/usr/lib/python2.5/site-packages/libgmail.py", line 615, in > sendMessage > raise GmailSendError, resultInfo[SM_MSG] > libgmail.GmailSendError: Please try again. > > I traced the result to the sendMessage routine and noted that anytime it > tries to send anything it fails this also fails with the standard "docs" > package for libgmail 0.30 docs from the maintainer's site. > > Now the part where it *does* fail is where it has an issue with looking at > the trailing info but then it would have logged the info to the file and > emailed me back junk (which it didn't) > > I assume this could be done on any system just replace 'ls' with 'dir' or > the equivalent. > > >> >> > This is included in the above attachment >> > it's used in a program called "ogss" which is an sms interface to gmail >> to >> > basically read gmail and then have a command done on a remote machine >> and >> > then spat out on the local machine to a log file that's opened and then >> > emailed back >> > problem is that the sending back routine fails. >> >> Which routine is that exactly? Please also specify exactly how it is >> failing (e.g. error message(s), description of observed incorrect >> behavior). >> >> I apologize if these questions are answered in comments in the >> attachments, but to be honest, the fact that you didn't (or couldn't) >> put the specific problematic sections of code (and/or error messages) >> inline in your message makes it less likely that people (such as >> myself) will try to help you due to the volume of code you're making >> people wade through (i.e. people tend not to read large code dumps, >> /especially/ in attachments). >> >> Cheers, >> Chris >> -- >> http://blog.rebertia.com >> > That's ok I understand I hope that helps at least in part. -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Thu Aug 13 00:42:15 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 13 Aug 2009 00:42:15 -0400 Subject: Nice copy in interactive terminal In-Reply-To: References: Message-ID: <50697b2c0908122142r34f9c386hf8292f59ffa9edf2@mail.gmail.com> On Thu, Aug 13, 2009 at 12:15 AM, casebash wrote: > Hello fellow Python Users, > > I've been wondering for a while if there exists an interactive > terminal which has nice copy feature (ie. I can copy code without > getting the >>> in front of every line). Not quite answering your exact question, but: - You can control the text of the prompt by modifying sys.ps1 - IPython (http://ipython.scipy.org/moin/) has powerful history features that are handy if you want a transcript of a REPL session Cheers, Chris -- http://blog.rebertia.com From gagsl-py2 at yahoo.com.ar Thu Aug 13 01:20:00 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 02:20:00 -0300 Subject: fileinput References: Message-ID: En Wed, 12 Aug 2009 01:27:47 -0300, naaman escribi?: > I'm writing my first Python script and > I want to use fileinput to open a file in r+ mode. > Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > ANy ideas? Don't use fileinput, it can't handle r+, only sequencial access. Even if you could use it, the documentation says [1]: fileinput.input([files[, inplace[, backup[, mode[, openhook]]]]]) "r+" corresponds to the `inplace` parameter (behaving like inplace=True) instead of `mode`. You could write fileinput.input(sys.argv[1:], mode="r+") instead - but again from the docs: "mode... must be one of 'r', 'rU', 'U' and 'rb'" > Need to find and overwrite a line in a file several times. > I can do it using open and seek() etc. but was wondering if I can use > fileinput. open+seek is the way to do that (assuming you don't alter the line length) [1] http://docs.python.org/library/fileinput.html#fileinput.input -- Gabriel Genellina From tjreedy at udel.edu Thu Aug 13 01:34:14 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Aug 2009 14:34:14 +0900 Subject: Social problems of Python doc [was Re: Python docs disappointing] In-Reply-To: <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> Message-ID: Raymond Hettinger wrote: > On Aug 12, 3:32 am, Paul Boddie wrote: >> Maybe the problem is that although everyone welcomes contributions and >> changes (or says that they do), the mechanisms remain largely beyond >> criticism. > > FWIW, I support the idea the regular docs incorporating links to > freely editable wiki pages. That will at least make it easier for > people to make changes or add notes. > > That being said, I would like to add a few thoughts about the > current process. The summary that follows accords with my experiences and observations. Perhaps you could add it to the Wiki. ISTM that important corrections (when the > docs are clearly in error) tend to get made right away. Many within a day. I have seen this with both some of my suggestions and others. What > is more interesting are the doc requests that get rejected > and why: One of my suggestions was postponed pending discussion on PyDev of the underlying issue, which I have not initiated yet. Another Georg accepted in principle but awaits me taking the time to write a fleshed out replacement text. > * Many doc requests come from people just learning the language > (that makes sense because the learning process involves reading > the docs). Unfortunately, a fair number of those requests are > flat-out wrong or represent a profound misunderstanding of the > feature in question. That may be an indicator that the docs > need to be improved, but the specific suggestion can be inane. > > * Some doc requests come from people who simply do not like the > feature in question. It is natural for tastes, styles, and > preferences to vary; however, we do have a firm rule that Guido's > tastes, styles, and preferences are the ones that go into the > language. So the doc writers need to try to channel Guido instead > of fighting him. So, if you think eval() is evil (I don't but many > do), we're not going to document that eval() should *never* be used. > If you hate super(), that's too bad -- the docs need to describe > what it does and how it was intended to be used -- the docs are no > place for diatribes on why inheritance is over-used and why you > think the world would be a better place without mixins or > multiple inheritance. > > * Then, there is a matter of where to put a particular piece of > documentation (how many times do you repeat a concept that pervades > the language). I doubt anyone can *really* understand the problem of organizing a book's worth in technical information into coherent order until they have actually tried to do so. > Hashing is a good example. The docs can discuss how > some objects hash to their object id and that object ids can change > from run-to-run, but if someone gets tripped-up by the idea (hey, > my set reprs changed between runs, wtf!), they want the docs updated > in the specific place that tripped them up (i.e. you must put big > red warnings in the set documentation, and the dict documentation, > and everywhere else a hash gets used ...). The core problem is that > the docs are interrelated -- the one place you're looking for > documentation of a specific builtin or function can't contain > every concept in the language. > > * Some behaviors are intentionally left unspecified. For the longest > time, Tim did not want to guarantee sort stability. This left him > free to continue to search for algorithmic improvements that did not > have stability. Later, the property was deemed so important that it > did become a guaranteed behavior. Also, some things are unspecified > to make things easier for other implementations (IronPython, PyPy, > Jython, etc.) We need to make sure that some one doesn't casually > go through the docs making doc promises that are hard to keep. > > * Some things are just plain difficult to fully explain in English > and not misrepresent that actual behavior. For example, the str.split > () > docs have been continuously tweaked over the years. Even now, I think > there are corner cases that are not fully captured by the docs. > Casual > edits to str.split() docs are more likely than not to take them > farther > away from the truth. > > * Then, there is the problem of talking too much. A book could be > written about super(), but that shouldn't all go into the docs for > the super builtin. Beginners often want to master all the builtins > and they try to read the doc page on builtin functions. It used to be > that you could read through the builtin descriptions in a few minutes. > Now, it takes a concerted effort to get through. It is hard to take > a sip of water from a firehose. Too much information has make a > function harder to understand. > > * My biggest pet peeve are requests to fill the docs with big red > warnings. I do not want the docs to look like a mine field. The > warnings > should be reserved for a handful of security or data corruption risks. > For the most part, the docs should be matter-of-fact, explaining what > a function or method does and how it was intended to be used. > > Preferred: "The value str.letters is locale dependent" > > Not preferred: "Caution, the str.letters value can be adversely > affected by the locale setting (it could even change length!); use > this > only when you are certain the locale setting will not violate any of > your program invariants; consider using a string literal instead; I > hate > string.letters and think Guido was smoking crack when it was > introduced." > > * Another category of rejected doc requests come from people looking > for > absolution from one of their programming bugs. It typically takes the > form of, "I made an assumption that the language did X, but it did Y > and my program didn't do what I wanted; therefore, the docs must be > to blame and they must change ...". The suggestion is "I was > suprised" > implies "the docs are hosed". The fact is that people with diffferent > backgrounds are going to have different expectations and someone is > going to get "surprised". The docs need to say what functions do, but > they don't need to be changed everytime someone writes a buggy > program. > > In short, most doc requests that get rejected are requests that didn't > actually improve the documentation. > > I do support links from the regular docs to an external wiki but the > main docs should continue to go through the regular process using the > tracker. Agreed Terry Jan Reedy From gagsl-py2 at yahoo.com.ar Thu Aug 13 01:36:07 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 02:36:07 -0300 Subject: Format Code Repeat Counts? References: <50697b2c0908121523jc495a65y1957a503b4f10566@mail.gmail.com> Message-ID: En Wed, 12 Aug 2009 19:23:32 -0300, Chris Rebert escribi?: > On Wed, Aug 12, 2009 at 4:34 PM, jschwab wrote: > >> As a more concrete example, say I have several sets of letters in a >> list of strings >> ? ? letters = ["aeiou", "hnopty", "egs", "amsp"] >> and I wanted to build a regular expression string out of them like >> ? ? re_str <==> "[aeiou][hnopty][egs][amsp]" >> Right now, the best I've got that doesn't require an explicit string >> like "[{1}][{2}][{3}][{4}]" is >> ? ? re_str = "".join(map(lambda x: "[{0}]".format(x), letters)) >> >> Is there a better way? > > Slightly better, by using a generator expression instead of map() and > lambda: > re_str = "".join("[{0}]".format(x) for x in letters) > > Though obviously MRAB's is shorter (and a good show of lateral thinking). Another way, using {} auto-numbering (requires Python 3.1 or the future 2.7) p3> letters = ["aeiou", "hnopty", "egs", "amsp"] p3> ("[{}]"*len(letters)).format(*letters) '[aeiou][hnopty][egs][amsp]' -- Gabriel Genellina From tjreedy at udel.edu Thu Aug 13 01:49:51 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Aug 2009 14:49:51 +0900 Subject: Social problems of Python doc [was Re: Python docs disappointing] In-Reply-To: References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <0292a134$0$20647$c3e8da3@news.astraweb.com> <3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com> <0292cb5a$0$20647$c3e8da3@news.astraweb.com> Message-ID: Paul Boddie wrote: > Right, but those good points are still worth taking on board. There > have been Xah Lee posts which have been relatively constructive, The last time that he did do so that I read, I responded rationally like I would with any other normal post. He responded with foul insults. End of discussion. > when the only responses are from people who see the name and can't be > bothered reading the message before issuing a stock "he's a troll" False premise. > response, the tone is likely to remain vulgar from that point onwards. He was vulgar even when I did ignore the name and did bother to read and write (not 'issue') a specific response. He has also 'blown' opportunities on the py-dev list. tjr From tjreedy at udel.edu Thu Aug 13 02:02:45 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Aug 2009 15:02:45 +0900 Subject: Need feedback on ORF-extracting code In-Reply-To: References: Message-ID: gb345 wrote: > > Hi everyone. I'm relatively new to Python, and could use your > feedback on the code below. > > First some nomenclature. A "nucleotide" is one of A, C, G, T, or > U. (In practice, a sequence of such nucleotides never contains > both T and U, but this fact is not important in what follows.) A > "codon" is a sequence of 3 of these. A "stop codon" is any one of > UAA, UAG, UGA, TAA, TAG, or TGA. Two codons are said to be "in > frame" in a containing sequence of nucleotides if their positions > differ by a multiple of 3. An "open reading frame," or ORF, is > defined as a maximal subsequence of nucleotides whose length is a > multiple of 3, begins with either AUG or ATG, terminates right > before a stop codon in the original sequence, and contains no stop > codons that are in frame with the initial codon (AUG or ATG). > > The fact that ORFs have lengths that are multiples of 3 means that > there are three possible "registers" for ORFs (depending the modulo > 3 of their starting positions), and that ORFs in different registers > can overlap. I'll refer to these registers as 0, 1, and 2, because > they contain ORFs that are in frame with the codons at positions > 0, 1, and 2 of the original sequence, respectively. > > In the code below, routine extract_orfs takes as input a string, > assumed to be a sequence of nucleotides, and returns a tuple of > tuples, describing ORFs. These ORFs can overlap. > > The helper routine _xo takes as input a string (a sequence of > nucleotides), and an offset, and returns a tuple of tuples, again > representing ORFs, but this time all in the same register, since > they are all in frame with the position passed as the second argument > to the function. > > I would appreciate your comments on this code. I feel that it is > not as clear as it could be, but I don't know how to make it any > clearer. > > (NOTE: I realize that, in all likelihood, publicly available Python > code already exists for this. At the moment I'm more interested > in improving my Python skills.) > > > Many thanks in advance! > > Gabe > > > > # BEGINNING OF CODE > import sys > import re > > _start = r'A[TU]G' > _stop = r'(?:[TU]A[AG]|[TU]GA)' > _nonstop = r'(?:[CAG][TUCAG]{2}|[TU](?:[TUC][TUCAG]|[AG][TUC])|[TU]GG)' > _codon = r'(?:[TUCAG]{3})' > _orf_re = re.compile('(' + _codon + r'*?)(A[TU]G' + > _nonstop + '*)(' + _stop + ')', flags=re.I) > _lead_re = re.compile(r'[TUCAG]*?A[TU]G', flags=re.I) > > def _xo(seq, pos): > """ > Helper routine that finds all the non-overlapping in-frame orfs > starting from a specific position in the input sequence. > > input: a string of letters in the set 'tucagTUCAG', and a starting > position; > output: a tuple of tuples; each internal tuple consists of a > starting position, an orf, and the stop codon that > terminates it. > """ > > ret = [] > while True: > m = _orf_re.match(seq, pos) > if not m: > break > orf = m.group(2) > stop = m.group(3) > assert len(orf) % 3 == 0 I am not currently familiar with the re module so I cannot comment in detail. The assert should be a claim that the re should *never* match anything other than a multiple of 3, so that it is a program bug if it ever do so. If this is not true, you should use an if statement. tjr > ret.append((m.start() + len(m.group(1)), orf, stop)) > pos = m.end() > return ret > > def extract_orfs(seq): > """ > Extracts all (possibly overlapping) maximal open reading frames, > defined as sequences beginning with AUG (or ATG), ending with an > in-frame stop codon, and containing no in-frame stop codons > in-between. > > input: a string of letters in the set 'tucagTUCAG'; > output: a tuple of tuples; each internal tuple consists of a > starting position, an orf, and the stop codon that > terminates it. > """ > > m = _lead_re.match(seq) > if not m: > return () > pos = m.start() > ret = [] > > for i in range(min(3, len(seq))): > ret.extend(_xo(seq, pos + i)) > ret.sort() > return tuple(ret) > > # END OF CODE From gagsl-py2 at yahoo.com.ar Thu Aug 13 02:16:15 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 03:16:15 -0300 Subject: How to find out in which module an instance of a class is created? References: <4A7F4874.8030008@johannes-janssen.de> <4A7F6016.2060408@cheimes.de> <4A80967F.9030604@johannes-janssen.de> Message-ID: En Mon, 10 Aug 2009 18:51:59 -0300, Johannes Janssen escribi?: > class A(object): > def __init__(self, mod=None): > if mod is None: > self.mod = sys._getframe(1).f_globals['__name__'] > else: > self.mod = mod > > In warnings.warn() they used try around sys._getframe(1). As far as I > understand what is done in warnings, there it is not sure what object > caused the warning and therefore it is not sure whether you can or > cannot use sys._getframe(1). Though in my case it should be quite clear. > Can I be sure that my code will always work? The try/except around sys._getframe(1) is because that function is not mandatory/available on all Python implementations (that's the case for jython which doesn't provide it). -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Thu Aug 13 02:28:53 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 03:28:53 -0300 Subject: How to page output in >>> ? References: Message-ID: En Wed, 12 Aug 2009 18:41:38 -0300, kj escribi?: > How does one tell the python interactive interpreter to run the > next output to stdout through the default pager? Basically, I'm > looking for Python's equivalent of Perl's debugger's "|" prefix, > as in > > DB<1> |print $long_output Try using pydoc.pager - read the source -- Gabriel Genellina From jeanmichel at sequans.com Thu Aug 13 02:36:59 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 13 Aug 2009 08:36:59 +0200 Subject: best practice for documenting a project? pydoc? In-Reply-To: References: Message-ID: <4A83B48B.1080307@sequans.com> Esmail wrote: > shaileshkumar wrote: >> Hello, >> >> EPYDOC is very good for automatic generation of documentation from >> source code. >> >> You may also consider Sphinx http://sphinx.pocoo.org/ which is used >> for many >> projects including the official Python documentation, documentation of >> Zope (http://docs.zope.org/). >> See the full list of projects using Sphinx at >> http://sphinx.pocoo.org/examples.html >> >> - Shailesh > > Hi, > > Thanks for the links. Have you heard of something called HappyDoc? I just > came across it by looking for info on epydoc. > > Thanks, > Esmail > I've never used Happydoc. I am using Epydoc, which is very efficient. Sphinx is very good as well, but its scope is much larger than documenting python code and will not provide the "click and run" effect of epydoc, for which you don't have to write any additional documentation. Epydoc supports restructured text, so you'll be able to switch to Sphinx later on without additional work. But if I remember well, your documentation is for personal use, so I guess you'll stick with epydoc. JM From gagsl-py2 at yahoo.com.ar Thu Aug 13 02:53:12 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 03:53:12 -0300 Subject: inspect.stack() performance References: <2a8674c60908060500k1c77b556la70d06d5feaaef0e@mail.gmail.com> Message-ID: En Thu, 06 Aug 2009 09:00:45 -0300, Doron Tal escribi?: > I use inspect.stack() to extract some info, such as file name, function > name > and line number, for the sake of logging (home brew logger). > I tested to see how much time it takes to execute the command: > > Python 2.4.3 (#1, Jan 21 2009, 01:11:33) > [GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import timeit >>>> t = timeit.Timer('inspect.stack()', 'import inspect') >>>> t.repeat(3,1000) > [0.28500604629516602, 0.28315305709838867, 0.29169297218322754] >>>> > > About 280uSec per call. > > If I log 1000 times per seconds than I get to spend 28% of the process > time > on inspect.stack() > Is there a better/quicker way of retrieving the same info? inspect loads the whole source code of every module in the stack (using linecache). If all you want is module name + line number, use this: f = sys._getframe() print f.f_globals['__name__'], f.f_lineno (see a recent post about warnings.warn too) -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Thu Aug 13 03:19:05 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 04:19:05 -0300 Subject: Monkeypatching an object to become callable References: <87hbwgu7xa.fsf@vostro.rath.org> <0aa46ece-64b9-4c28-b690-5ac5937ce3f2@f20g2000prn.googlegroups.com> <4a7fd55e$0$32765$426a74cc@news.free.fr> <87iqguey37.fsf@vostro.rath.org> Message-ID: En Tue, 11 Aug 2009 20:21:16 -0300, Nikolaus Rath escribi?: > Bruno Desthuilliers writes: >> 7stud a ?crit : >> (snip) >>> class Wrapper(object): >>> def __init__(self, obj, func): >>> self.obj = obj >>> self.func = func >>> >>> def __call__(self, *args): >>> return self.func(*args) >>> >>> def __getattr__(self, name): >>> return object.__getattribute__(self.obj, name) >> >> This should be >> >> return getattr(self.obj, name) >> >> directly calling object.__getattribute__ might skip redefinition of >> __getattribute__ in self.obj.__class__ or it's mro. > > Works nicely, thanks. I came up with the following shorter version which > modifies the object in-place: > > class Modifier(obj.__class__): > def __call__(self): > return fn() > > obj.__class__ = Modifier > > > To me this seems a bit more elegant (less code, less underscores). Or > are there some cases where the above would fail? I assume the above code is inside a function like make_callable(obj, fn) Then, a new class is created for every instance you make callable; you may want to cache all those classes (classes aren't cheap). Might fail: when obj is not a new-style class, or its __class__ isn't writable (e.g. builtin types). -- Gabriel Genellina From chris at simplistix.co.uk Thu Aug 13 03:20:37 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 13 Aug 2009 08:20:37 +0100 Subject: httplib incredibly slow :-( In-Reply-To: <4eb0089f0908121753o5ecf141dj304b21c3df0d3d6b@mail.gmail.com> References: <4A81D3CB.7080209@simplistix.co.uk> <4A82EFDC.70502@simplistix.co.uk> <4eb0089f0908121753o5ecf141dj304b21c3df0d3d6b@mail.gmail.com> Message-ID: <4A83BEC5.40101@simplistix.co.uk> David Robinow wrote: > On Wed, Aug 12, 2009 at 12:37 PM, Chris Withers wrote: >> David Stanek wrote: >>> Also on the same box where you run this script >>> can you test with curl or wget? >> It's a Windows box, so no :-( > > Why not? > > http://users.ugent.be/~bpuype/wget/ > http://curl.haxx.se/download.html Fair point, but I don't see what this will achieve... I've already established that the file downloads in seconds with [something else], so I'd like to understand why python isn't doing the same and fix the problem... Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From darkwater42 at gmail.com Thu Aug 13 03:37:42 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Thu, 13 Aug 2009 00:37:42 -0700 (PDT) Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com> <7877b03a-09da-4836-804c-502b6f78003c@h21g2000yqa.googlegroups.com> <02933e60$0$20647$c3e8da3@news.astraweb.com> Message-ID: <2cdc3f88-1952-4ca2-9754-5b7583fb5fd8@z31g2000yqd.googlegroups.com> On Aug 12, 7:19?pm, Steven D'Aprano wrote: > You are making an unjustified assumption: \y is not an error. You are making in an unjustified assumption that I ever made such an assumption! My claim is and has always been NOT that \y is inately an error, but rather that treating unrecognized escape sequences as legal escape sequences is error PRONE. > While I'm amused that you've made my own point for me, I'm less > amused that you seem to be totally incapable of seeing past your > parochial language assumptions, Where do you get the notion that my assumptions are in any sense "parochial"? They come from (1) a great deal of experience programming very reliable software, and (2) having learned at least two dozen different programming languages in my life. > I disagree with nearly everything you say in this post. I think > that a few points you make have some validity, but the vast > majority are based on a superficial and confused understanding > of language design principles. Whatever. I've taken two graduate level classes at MIT on programming languages design, and got an A in both classes, and designed my own programming language as a final project, and received an A+. But I guess I don't really know anything about the topic at all. > But it's not the only reasonable design choice, and Bash has > made a different choice, and Python has made yet a third > reasonable choice, and Pascal made yet a fourth reasonable choice. And so did Perl and PHP, and whatever other programming language you happen to mention. In fact, all programming languages are equally good, so we might as well just freeze all language design as it is now. Clearly we can do no better. > One party insisting that red is the only logical colour for a > car, and that anybody who prefers white or black or blue is > illogical, is unacceptable. If having all cars be red saved a lot of lives, or increased gas mileage significantly, then it might very well be the best color for a car. But of course, that is not the case. With programming languages, there is much more likely to be an actual fact of the matter on which sorts of language design decisions make programmers more productive on average, and which ones result in more reliable software. I will certainly admit that obtaining objective data on such things is very difficult, but it's a completely different thing that one's color preference for their car. |>ouglas From deets at nospam.web.de Thu Aug 13 04:01:53 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Aug 2009 10:01:53 +0200 Subject: resume upload wsgi script In-Reply-To: References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com> <7e80jlF2etv0kU1@mid.uni-berlin.de> <7e85i3F2fdc1eU1@mid.uni-berlin.de> <9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com> <7e8ildF2f1hcpU1@mid.uni-berlin.de> <49e41062-9e0d-4c5e-beca-edb02d3ce6e8@e34g2000vbm.googlegroups.com> <7ea4lpF2dvr5cU1@mid.uni-berlin.de> Message-ID: <7ehvjhF2ghuo2U1@mid.uni-berlin.de> gert schrieb: > On Aug 10, 10:39 am, "Diez B. Roggisch" wrote: >>> 250KB :) >> So why do you bother? >> >>> Its just HTTP1.1 has everything for making ftp like file transfers >>> possible. >>> When I write it to a file then I am back at square one because I still >>> need to load it completely to get it into a blob. >> Well, the blob is nothing but datat in the file-system. If you are >> *really* concerned about that, then don't use the db, but use the >> filesystem, appending to the file until it's finished - and storing a >> reference to it to the DB. We do that as well, because otherwise the db >> will become unmanagable anyway (dumping, backups). >> > > I also hate debugging sql that contains blob data. So if using files > how do you clean the http post stuff? > (b+r'.*?Content-Type: application/octet-stream\r\n\r\n(.*?)\r > \n--'+b,file,DOTALL) > using as litlle memory as possible ? > I can not use PUT upload only because flash does not support PUT. PUT or POST has nothing todo with that. It's the question if you need formencoded data or not. If not, you can simply upload the data directly, no nead to cleanup anything. For decoding formencoded data, you will need to write your own parser if you insist on these very debatable memory-constraints of yours. Diez From efotinis at y Thu Aug 13 04:56:04 2009 From: efotinis at y (Elias Fotinis (eliasf)) Date: Thu, 13 Aug 2009 11:56:04 +0300 Subject: Nice copy in interactive terminal In-Reply-To: References: Message-ID: <1250153823.228153@athprx03> "casebash" wrote: > I've been wondering for a while if there exists an interactive > terminal which has nice copy feature (ie. I can copy code without > getting the >>> in front of every line). It would help if we knew what platform you're interested in -- your User-Agent is G2/1.0, but I don't know what that is. :o) On Windows, PythonWin can copy from the interactive window without the prompts. From gagsl-py2 at yahoo.com.ar Thu Aug 13 05:28:25 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 06:28:25 -0300 Subject: Unsigned char array to an unsigned longlong array References: Message-ID: En Tue, 11 Aug 2009 23:22:27 -0300, Jus escribi?: > Is there a way to have an Array of unsigned longlong (C Type: unsigned > longlong, Minimum size if bytes: 8) ? > > What I want to do is to store an array of bytes in an array of longlongs. > > To workaround this issue, I have tried to use the double array (TypeCode > 'd'), since the size in bytes is the same (8 for instance). Do you want to operate on it from inside Python, or manage it in some way? If not, use whatever format you like, even bytes. It's just a contiguous memory block with a known size. > But it gives me strange result. Please look at the example: > > > import array > > myByteArray = array.array('B', [1,2,3,4,5,6,7,8]) > myLongArray = array.array('L', myByteArray.tostring() ) >>> myLongArray = array('L', [67305985L, 134678021L]) > myDoubleArray = array.array('d', myByteArray.tostring() ) >>> myDoubleArray = array('d', [5.447603722011605e-270]) > > If we convert the byte array to an hex form, we will get for the long > array: > [04030201, 08070605]. What do you mean "convert the byte array to an hex form"? > If we convert this hex array to decimal, we then get the Long Array: > [67305985, 134678021]. > > > Now, if we do the same exercise for the double array, the hex form will > look > like: [0807060504030201]. > > And the decimal value would be: [5.784376957523072e+17]. How did you got that? > Where does the 5.447603722011605e-270 value comes from ? The struct module agrees: py> s=struct.pack('q', 0x0807060504030201) py> struct.unpack('d', s) (5.447603722011605e-270,) And looking at the hex representation: py> (5.447603722011605e-270).hex() '0x1.7060504030201p-895' The 1. is implied, 7060504030201 are visible (52 bits), and the exponent is: py> hex(-895+1023) '0x80' So that value seems OK to me, at least with IEEE 754 hardware... -- Gabriel Genellina From erik.bernoth at googlemail.com Thu Aug 13 05:32:53 2009 From: erik.bernoth at googlemail.com (Erik Bernoth) Date: Thu, 13 Aug 2009 11:32:53 +0200 Subject: what is it, that I don't understand about python and lazy evaluation? Message-ID: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Hi List, look at the following code: def evens(): # iterator returning even numbers i = 0 while True: yield i i += 2 # now get all the even numbers up to 15 L = [n for n in evens() if n < 15] Isn't it strange, that this code runs (in a lazy language) for eternity? I would expect python to to spit out (in no time): >> L [0, 2, 4, 6, 8, 10, 12, 14] after 14 it is not nessesary to evaluate evens() any further. I really started to ask myself if python really is lazy, but everything else I wrote in lazy style still worked. Example: >> def test(txt, retval): .. print(txt) .. return retval .. >>> test(1, True) or test(2, True) 1 True >>> test(1, True) and test(2, True) 1 2 True Can anybody explain what happens with evens()? best regards Erik Bernoth PS: The code comes from a list post from 2006. You find it here: http://mail.python.org/pipermail/python-list/2006-November/585783.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu Aug 13 05:58:15 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 13 Aug 2009 11:58:15 +0200 Subject: Scraping Wikipedia with Python In-Reply-To: <6YidncRAiJ6SIxzXRVn_vwA@giganews.com> References: <4a81b6f0$0$1590$742ec2ed@news.sonic.net> <6YidncRAiJ6SIxzXRVn_vwA@giganews.com> Message-ID: <6faf39c90908130258q21f9c45cqca0c0a0db0a55b6e@mail.gmail.com> On Tue, Aug 11, 2009 at 8:53 PM, David C Ullrich wrote: > Try reading a little there! Starting there I went to > > http://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot > > where I found a section on existing bots, comments on how the "scraping" > is not what you want, and even a Python section with a link to something > labelled ?PyWikipediaBot... Some information on using the PyWikipediaBot for scraping from someone who used to program on the bot (and occasionally still does): To make the framework work, you need to add a file user-config.py with the following contents: family = 'wikipedia' mylang = 'en' If you want to use the bot to also edit pages on wikipedia, you will have to add: usernames['wikipedia']['en'] = If you work on another language of course you use that language's abbreviation instead of en. The heart of the framework is the file wikipedia.py, you need to import that one. It contains two important classes: Page and Site, which represent a wikipedia page and the site as a whole, respectively. It is best to put your code in a try like this: try: mysite = wikipedia.getSite() finally: wikipedia.stopme() The stopme() functionality has to do with the bot's behaviour to avoid over-feeding the server with requests. It has a certain time (default is 10 seconds) between two requests, but if you have several bots running, it will lengthen this time. stopme() tells that the bot is not running any more, so other runs are not delayed by it. wikipedia.getSite() gets the site object for your default site (if the settings above are chosen it is the English language Wikipedia). Still with me? Good, because now we get into the real programming. The Page class has as its __init__: def __init__(self, site, title, insite=None, defaultNamespace=0): site is here the wiki on which the page exists (usually this will be mysite, which is why I defined it above), title the title of the page. The optional parameters are for special usage. The Page class has a number of methods, which you can find in the file, but some of the most important are: page.title() - the title of the page page.site() - the wiki the page is on page.get() - the (wiki) text of the page page.put(text) - saves the page with 'text' as its new content. An important optional parameter is 'comment', which specifies the summary that is given with the change page.exists() - a boolean, true if the page exists, false otherwise page.linkedPages() - a list of Page objects, being the pages the page links to However, instead of page.get() it is advisable to use: wikipedia.getall(site,pages) with 'site' being a Site object (e.g. mysite) and pages a list (or more generally, iterable) of Page objects. It will get all pages in the list using a single call to the wiki, thus speeding up your bot and at the same time reducing its load on the wiki. Once a page has been loaded (either through get or through getall), subsequent calls to page.get() will not reload it. Thus, the normal way of working is to create a list of pages one is interested in, use getall (in groups of 60 or so) to load them, then use get to work with them. Another useful file in the framework is pagegenerators. It provides a number of generators that yield Page objects. Some interesting ones (check the code for the exact parameters): AllpagesPageGenerator: generates all pages of the wiki, alphabetically from a specified begin ReferringPageGenerator: all pages linking to a given page CategorizedPageGenerator: all pages in a given directory LinkedPageGenerator: all pages linked to from a given page Other generators are used by 'wrapping them around' a given generator. The most important of these is the PreloadingGenerator, which ensures that the page are preloaded (using wikipedia.getall) in groups. A simple way to use the bot framework to scrape all pages of the English Wikipedia (warning: This takes a few days!) would be: import wikipedia import pagegenerators basicgen = pagegenerators.AllpagesPageGenerator(includeredirects = False) generator = pagegenerators.PreloadingGenerator(basicgen, 200) for page in generator: title = page.title() text = page.get() -- Andr? Engels, andreengels at gmail.com From ben+python at benfinney.id.au Thu Aug 13 06:00:17 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 13 Aug 2009 20:00:17 +1000 Subject: subprocess + python-daemon - bug/problem? References: <699d22bd-e912-4ea3-92b0-c352a64611fb@n11g2000yqb.googlegroups.com> <828acd8d-a9bd-4506-b695-e537af4587d8@l31g2000yqb.googlegroups.com> <873a94ojvi.fsf@benfinney.id.au> Message-ID: <87hbwc58zy.fsf@benfinney.id.au> Ben Finney writes: > My first thought was perhaps it's related to the fact that the process > has no stdout? But setting ?stdout? and ?stderr? to the same file:: > > #! /usr/bin/python > > import daemon > import subprocess > > fake_console = open("fake_console.txt", "w+") > daemon.DaemonContext(stdout=fake_console, stderr=fake_console).open() > subprocess.Popen(['echo', '1']).wait() For newcomers to this thread: the ?daemon? module is provided by the ?python-daemon? distribution, of which I am the maintainer. > still gives the same error:: > > 1 > Traceback (most recent call last): > File "/home/bignose/Projects/python/python-daemon/bin/andy-clegg-test", line 8, in > subprocess.Popen(['echo', '1']).wait() > File "/usr/lib/python2.5/subprocess.py", line 1184, in wait > pid, sts = self._waitpid_no_intr(self.pid, 0) > File "/usr/lib/python2.5/subprocess.py", line 1014, in _waitpid_no_intr > return os.waitpid(pid, options) > OSError: [Errno 10] No child processes > > I'm not familiar enough with the nuances of the ?subprocess? module to > know what might be going wrong here. I'd like to know whether it might > be a problem in the ?python-daemon? library. I am no closer to a solution on this one. I don't have enough experience or knowledge of the ?subprocess? module to know whether it's a bug in ?subprocess?, a bug in ?python-daemon?, or a hard-to-track interaction between the two. Any narrowing of the problem would be appreciated. -- \ ?I bought a dog the other day. I named him Stay. It's fun to | `\ call him. ?Come here, Stay! Come here, Stay!? He went insane. | _o__) Now he just ignores me and keeps typing.? ?Steven Wright | Ben Finney From BrianVanderburg2 at aim.com Thu Aug 13 06:07:11 2009 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Thu, 13 Aug 2009 06:07:11 -0400 Subject: what is it, that I don't understand about python and lazy evaluation? In-Reply-To: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Message-ID: <4A83E5CF.7080208@aim.com> Erik Bernoth wrote: > Hi List, > > look at the following code: > > def evens(): > # iterator returning even numbers > i = 0 > while True: > yield i > i += 2 > > # now get all the even numbers up to 15 > L = [n for n in evens() if n < 15] > > Isn't it strange, that this code runs (in a lazy language) for > eternity? I would expect python to to spit out (in no time): > >> L > [0, 2, 4, 6, 8, 10, 12, 14] > > after 14 it is not nessesary to evaluate evens() any further. > > I really started to ask myself if python really is lazy, but > everything else I wrote in lazy style still worked. Example: > >> def test(txt, retval): > .. print(txt) > .. return retval > .. > >>> test(1, True) or test(2, True) > 1 > True > >>> test(1, True) and test(2, True) > 1 > 2 > True > > > Can anybody explain what happens with evens()? > > best regards > Erik Bernoth > > PS: The code comes from a list post from 2006. You find it here: > http://mail.python.org/pipermail/python-list/2006-November/585783.html In the list comprehension, it goes over all the items from the generator until the generator is done, and any item that is less than 15 becomes part of the list. The "if n < 15" does not control when the generator terminates, only which results from it are selected to be part of the list. You can pass the maximum desired value to make it terminate: def evens(max): i = 0 while i <= max: yield i i += 2 L = list(evens(15)) L: [0, 2, 4, 6, 8, 10, 12, 14] L = [n for n in evens(15)] L: [0, 2, 4, 6, 8, 10, 12, 14] Brian Vanderburg II From dmhouse at gmail.com Thu Aug 13 07:11:18 2009 From: dmhouse at gmail.com (David House) Date: Thu, 13 Aug 2009 12:11:18 +0100 Subject: what is it, that I don't understand about python and lazy evaluation? In-Reply-To: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Message-ID: 2009/8/13 Erik Bernoth : > after 14 it is not nessesary to evaluate evens() any further. How does Python know this? I.e. how does it know that evens() will always yield things in ascending order? For example, I could write an iterator like this: def my_iter(): for i in [0,2,4,6,8,10,12,14,16,18,1,3,5]: yield i Now, imagine I do [i for i in my_iter() if i < 15]. If you quit iterating after `i' becomes 16, you'll miss the valid numbers 1, 3, 5 at the end of the list! -- -David From python at mrabarnett.plus.com Thu Aug 13 07:23:50 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 13 Aug 2009 12:23:50 +0100 Subject: what is it, that I don't understand about python and lazy evaluation? In-Reply-To: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Message-ID: <4A83F7C6.2060301@mrabarnett.plus.com> Erik Bernoth wrote: > Hi List, > > look at the following code: > > def evens(): > # iterator returning even numbers > i = 0 > while True: > yield i > i += 2 > > # now get all the even numbers up to 15 > L = [n for n in evens() if n < 15] > > Isn't it strange, that this code runs (in a lazy language) for eternity? > I would expect python to to spit out (in no time): > >> L > [0, 2, 4, 6, 8, 10, 12, 14] > > after 14 it is not nessesary to evaluate evens() any further. > It's equivalent to: L = [] for n in evens(): if n < 15 L.append(n) From davea at ieee.org Thu Aug 13 07:50:30 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 07:50:30 -0400 Subject: fileinput In-Reply-To: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> References: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> Message-ID: <4A83FE06.90305@ieee.org> naaman wrote: > On Aug 12, 1:35 pm, Dave Angel wrote: > >> naaman wrote: >> >>> I'm writing my first Python script and >>> I want to use fileinput to open a file in r+ mode. >>> Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. >>> ANy ideas? >>> >>> Need to find and overwrite a line in a file several times. >>> I can do it using open and seek() etc. but was wondering if I can use >>> fileinput. >>> >>> thanks; >>> >> I haven't used it, but check out the 'inplace' keyword parameter. >> >> DaveA >> > > I've only Python for a week so I'm not sure what inplace does > > You should read the docs for it ( http://www.python.org/doc/2.6.2/library/fileinput.html ), but it's not very clear to me either So I dug up an example on the web: (ref: http://effbot.org/librarybook/fileinput.htm ) import fileinput, sys for line in fileinput.input(inplace=1): # /convert Windows/DOS text files to Unix files/ if line[-2:] == "\r\n": line = line[:-2] + "\n" sys.stdout.write(line) The inplace argument tells it to create a new file with the same name as the original (doing all the necessary nonsense with using a scratch file, and renaming/deleting) for each file processed. Stdout is pointed to that new version of the file. Notice that you have to explicitly write everything you want to wind up in the file -- if a given line is to remain unchanged, you just write "line" directly. If you're new to Python, I do not recommend trying to do open/seek to update a text file in place, especially if you're in DOS. There are lots of traps. the inplace method of fileinput avoids these by implicitly creating temp files and handling the details for you, which probably works great if you're dealing with text, in order. DaveA From sjmachin at lexicon.net Thu Aug 13 07:58:33 2009 From: sjmachin at lexicon.net (John Machin) Date: Thu, 13 Aug 2009 04:58:33 -0700 (PDT) Subject: csv.DictWriter.write_header() References: Message-ID: <68b9136d-fa0b-42dc-addf-02d338da34cd@z4g2000prh.googlegroups.com> On Aug 13, 1:15?pm, Alan G Isaac wrote: > > On Aug 13, 6:45 am, Alan G Isaac wrote: > >> Given a csv.DictWriter instance `dw` > >> I think it would be nice to be able to > >> say dw.write_header() > >> instead of > >> dw.writer.writerow(dw.fieldnames) > > >> Good idea? > > On 8/12/2009 10:24 PM John Machin apparently wrote: > > > Yes, it's a brilliant idea. All you have to do is insert the following > > lines in your code after importing csv: > > > csv.DictWriter.write_header = ( > > ? ? lambda dw: dw.writer.writerow(dw.fieldnames) > > ? ? ) > > I do not understand the reason for your silly, sarcastic response. Duck typing: ask a silly question, get a silly answer. > I already showed you how to achieve the result, What result? You said (in effect) "I think it would be nice to be able to write A instead of B". You didn't show any way of setting things up so that one could write A instead of B. I showed one way. Other possibilities are a 2-line patch to the users own csv.py, and submitting a patch to the dev team. The second is kludgy, and there could be a wait until e.g. 2.7 before the third happens. So back to the first way; everybody should have a utility module that they import to do little fixes like that ... here is a slightly more robust version: import csv try: csv.DictWriter.write_header except AttributeError: csv.DictWriter.write_header = ( lambda dw: dw.writer.writerow(dw.fieldnames) ) > so obviously > I am not just asking for my own personal gain. ??? > I take it you do not realize that many users do not see > a simple way to get this often needed functionality. No, I don't. How did you come to that realisation? AFAICT they don't ask in this forum or on StackOverflow. > (For example, see the gymnatics suggested by Shai Vaingast > in his otherwise excellent and useful book.) I can imagine that one might (without reading the source) make do with the published APIs: dw = csv.DictWriter(open(...), my_field_names dw.writerow(dict((fn, fn) for fn in my_field_names)) > And indeed, > there is no reason to expect them to. Indeed not, as for somebody who otherwise sees utility in the DictWriter class not having a writer_headers method is a glaring deficiency. Note that there is a difference between "expecting C to do X" and "expecting C to be able to do X". I really hope you don't mean that people should not be encouraged to be able to write a trivial class like csv.DictWriter and add trivial functionality themselves ... or to be able to just write the required functionality inline: wtr = csv.writer(open(...), ...) wtr.writerow(my_field_names) for adict in source_of_dicts(): wtr.writerow(adict[fn] for fn in my_field_names) or even: for obj in source_of_objects(): wtr.writerow(getattr(obj, fn) for fn in my_field_names) > So my question was, would this improve the class from > a usability perspective? Of course. > ?Do you have a useful response? See above. Also, the csv module appears to be in two minds about underscores in attribute names (field_size_limit, skipinitialspace, writerow, writerows) -- it may cause less confusion if it were called writeheader (consistent with writerow). From ebonak at hotmail.com Thu Aug 13 08:29:48 2009 From: ebonak at hotmail.com (Esmail) Date: Thu, 13 Aug 2009 08:29:48 -0400 Subject: best practice for documenting a project? pydoc? In-Reply-To: <4A83B48B.1080307@sequans.com> References: <4A83B48B.1080307@sequans.com> Message-ID: Hello Jean-Michel, Thanks for your post. Based on it, and the ones received so far I will give epydoc a closer look. I don't need something superfancy (at least at the moment), just something that helps me document my code more in an organized way and helps me sift through the various classes/methods more easily once I come back to the project after some lengthy interruptions. Best, Esmail Jean-Michel Pichavant wrote: > > > I've never used Happydoc. I am using Epydoc, which is very efficient. > Sphinx is very good as well, but its scope is much larger than > documenting python code and will not provide the "click and run" > effect of epydoc, for which you don't have to write any additional > documentation. Epydoc supports restructured text, so you'll be able to > switch to Sphinx later on without additional work. > But if I remember well, your documentation is for personal use, so I > guess you'll stick with epydoc. From drobinow at gmail.com Thu Aug 13 08:44:12 2009 From: drobinow at gmail.com (David Robinow) Date: Thu, 13 Aug 2009 08:44:12 -0400 Subject: httplib incredibly slow :-( In-Reply-To: <4A83BEC5.40101@simplistix.co.uk> References: <4A81D3CB.7080209@simplistix.co.uk> <4A82EFDC.70502@simplistix.co.uk> <4eb0089f0908121753o5ecf141dj304b21c3df0d3d6b@mail.gmail.com> <4A83BEC5.40101@simplistix.co.uk> Message-ID: <4eb0089f0908130544t72affa8ep7aa364806a94f9bb@mail.gmail.com> On Thu, Aug 13, 2009 at 3:20 AM, Chris Withers wrote: > David Robinow wrote: >> >> On Wed, Aug 12, 2009 at 12:37 PM, Chris Withers >> wrote: >>> >>> David Stanek wrote: >>>> >>>> Also on the same box where you run this script >>>> can you test with curl or wget? >>> >>> It's a Windows box, so no :-( >> >> Why not? >> >> http://users.ugent.be/~bpuype/wget/ >> http://curl.haxx.se/download.html > > Fair point, but I don't see what this will achieve... > > I've already established that the file downloads in seconds with [something > else], so I'd like to understand why python isn't doing the same and fix the > problem... My post was simply to correct the implication that curl and wget can not be used on Windows. It's up to you whether you want to use one or the other. I'm not the OP, and this is not my area of expertise, but ... You've got two data points. You've jumped to the conclusion that there's something wrong with Python or your code. You're probably right. However, if you try wget, for example, and it's as slow as your code, you cqn look elsewhere. If, on the other hand, wget is as fast as IE, you'll have more proof that your code is the problem. Then, since wget is open source you can look at the source code and see what wget is doing right that you (or httplib) is doing wrong. From catalinfest at gmail.com Thu Aug 13 08:55:56 2009 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Thu, 13 Aug 2009 05:55:56 -0700 (PDT) Subject: PIL and Python Message-ID: Hello ! I want use python to change the "note" from .jpeg files . What is the functions on PIL how make this ? Thank you ! From invalid at invalid Thu Aug 13 09:24:07 2009 From: invalid at invalid (Grant Edwards) Date: Thu, 13 Aug 2009 08:24:07 -0500 Subject: How to launch a function at regular time intervals ? References: Message-ID: On 2009-08-13, Dave Angel wrote: > I'm assuming you want to call it every time_interval seconds, on > average, with a little jitter allowed on each call, but keeping correct > long term. In other words, if one call is a little late, you want the > next one to still happen as close to on-time as possible. > > The general outline is something like (untested): > > times_called = 0 #number of times function has been called > start_time = now > while True: > elapsed = now - start_time > int_elapsed = int(elapsed/time_interval) > for times_called in range(times_called, int_elapsed): > call_the_function() > sleep(time_interval/10) #this might give us 10% jitter, which is usually fine I don't understand the reasoning behind the above loop -- specifically the sleeping of smaller intervals than needed. Why not something like this: interval = 5.0 # interval in seconds next = time.time() while True: now = time.time() if now < next: time.sleep(now-next) print "call_the_function()" next += interval That will be accurate over the long term with minimal jitter. From squishywaffle at gmail.com Thu Aug 13 09:31:25 2009 From: squishywaffle at gmail.com (Greg Taylor) Date: Thu, 13 Aug 2009 06:31:25 -0700 (PDT) Subject: Networked Broadcast Messaging References: <37ea826b-708d-48f4-a64a-42f58fec5325@c2g2000yqi.googlegroups.com> Message-ID: <859b8238-a730-4699-a94f-618f7311f58f@a13g2000yqc.googlegroups.com> On Aug 11, 9:18?pm, David Bolen wrote: > > If you want better guarantees, you might look into a distributed > message bus like Spread (http://www.spread.org/) or perhaps a > messaging protocol like XMPP (http://xmpp.org/) through its PubSub > extension. ?Both have Python interfaces, though I have no personal > experience with either. ?But perhaps that will also give you some > terms or starting points for searching for other options. This is also very helpful. In particular Spread, looks very attractive. Thanks for the tip, Greg From solipsis at pitrou.net Thu Aug 13 09:32:29 2009 From: solipsis at pitrou.net (Antoine Pitrou) Date: Thu, 13 Aug 2009 13:32:29 +0000 (UTC) Subject: what is it, that I don't understand about python and lazy evaluation? References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Message-ID: Erik Bernoth googlemail.com> writes: > > Isn't it strange, that this code runs (in a lazy language) for eternity? Python is a not a lazy language. `and` and `or` are particular, they are language constructs (*), not operators, that's why they can decide whether or not to evaluate their second term. It's a feature, but this feature is not general to Python. (*) by this I mean they have similar status as, for example, `if` and `else` From ebonak at hotmail.com Thu Aug 13 09:43:12 2009 From: ebonak at hotmail.com (Esmail) Date: Thu, 13 Aug 2009 09:43:12 -0400 Subject: Plotting Quadratic Functions, pygame In-Reply-To: References: Message-ID: Hello Senad, You might find this style guide useful too in your toolbox of Python skills & tricks. http://www.python.org/dev/peps/pep-0008/ This is a great and helpful group of people here, we are lucky to have access to groups like this. Best, Esmail From rurpy at yahoo.com Thu Aug 13 10:05:18 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Thu, 13 Aug 2009 07:05:18 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> Message-ID: <3d808272-6e56-4cf1-90df-8e5201df02df@c34g2000yqi.googlegroups.com> On 08/12/2009 12:27 PM, Raymond Hettinger wrote: > On Aug 12, 3:32 am, Paul Boddie wrote: >> Maybe the problem is that although everyone welcomes contributions and >> changes (or says that they do), the mechanisms remain largely beyond >> criticism. > > FWIW, I support the idea the regular docs incorporating links to > freely editable wiki pages. That will at least make it easier for > people to make changes or add notes. > > That being said, I would like to add a few thoughts about the > current process. ISTM that important corrections (when the > docs are clearly in error) tend to get made right away. What > is more interesting are the doc requests that get rejected > and why: [...snip interesting categorization of "bad" doc enhancement suggestions...] > In short, most doc requests that get rejected are requests that didn't > actually improve the documentation. > > I do support links from the regular docs to an external wiki but the > main docs should continue to go through the regular process using the > tracker. What is the purpose of such a wiki? 1. To provide hopefully useful adjunct information for each doc page? 2. To provide a source of input for improving the next version of the docs? In general I have a low opinion of wikis. Nearly all the ones I've seen are trash heaps of out-dated and wrong information, atrocious writing, and comments that look like the middle of some arcane usenet thread. They lack organization making it very difficult to find the needles of good information in the haystack of junk. The only one that seems to work is Wikipedia and it "works" because it has a very heavy-weight process controlling contributions. (And even then, my biggest complaint with Wikipedia is the poor writing quality in a lot of articles.) I'm not trying to be negative, only pointing out that to serve either of the goals I asked about above, a wiki will probably require a considerable management effort that should be faced up front. To simply set up a wiki and "wait for it to self-organize" (as I here read once) is a pipe-dream. How will it be managed? Anything written stays? If not what standards are used to remove junk entries? Wrong entries? Questionable entries? Who will do this? Will they act based on their own judgment or some documented formal standards? What happens to comments when a new doc version is released? What happens when entries become obsolete? What happens when comments are disputed? If the goal is (2) what kind of wiki contributions are being solicited ("I don't understand what this sentence means"? a complete rewrite of a section?) and how is that communicated? Who will take a long string of wiki comments constituting a discussion and condense them into something that can be submitted as a doc patch? (This I suspect is where the work is, where someone with good writing skills is needed.) Will this process be sufficient to raise the quality of the docs significantly, or are other steps also needed such as an attitude shift in what the core committers consider acceptable? If the goal is (1) above, it could potentially have a deleterious effect on the docs in that it will be easier to respond to requests to expand some description with, "there's no need since that is covered in (or belongs in) the wiki comments". All the above not withstanding, I too think a wiki is worth trying. But without doing a lot more than just "setting up a wiki", I sadly believe even a python.org supported wiki is doomed to failure. From ifl2009 at shu.edu Thu Aug 13 10:16:45 2009 From: ifl2009 at shu.edu (IFL 2009) Date: Thu, 13 Aug 2009 10:16:45 -0400 Subject: IFL 2009: Final Call for Papers and Participation Message-ID: An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Thu Aug 13 10:46:15 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 13 Aug 2009 07:46:15 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> <3d808272-6e56-4cf1-90df-8e5201df02df@c34g2000yqi.googlegroups.com> Message-ID: <13be5a11-612b-4fc5-a220-cc9aba2e4f8c@z31g2000yqd.googlegroups.com> On 13 Aug, 16:05, ru... at yahoo.com wrote: > > All the above not withstanding, I too think a wiki is worth > trying. ?But without doing a lot more than just "setting up > a wiki", I sadly believe even a python.org supported wiki > is doomed to failure. The ones on python.org seem to function reasonably well. I accept that they could be more aggressively edited, but this isn't done because there's a compromise between letting people contribute and keeping things moderately coherent, with the former being favoured. For other purposes, it would be quite acceptable to favour editorial control. I won't argue that providing infrastructure solves a problem - that's precisely the kind of thing I was criticising when I noted that some people will readily criticise the choice of tools to do a job instead of focusing on the job that has to be done - and you need people who are reasonably competent editors, but Wiki solutions remove a lot of technical barriers. I'm not arguing for the flavour of Wiki which implies unfettered, anonymous access from everyone on the Internet, either: the kind of Wiki that detractors portray all Wiki solutions as being in order to further their super-special "it has to fit like a glove or it's totally unusable" software agenda. It's quite possible to have people with somewhat more privileges than others in order to keep the peace, and they don't all need to have an entrenched editorial interest: on the current python.org Wiki sites, most of the administrators don't have an active interest in most of the content, but they are able to exercise control when it's clear that some contributors aren't particularly interested in actually improving the content. As well as having an active community effort around the existing python.org Wiki sites, there are also people who are interested in improving these offerings. What worries me is that despite such activity and such interest, many people will continue to lament the lack of vitality (or whatever other metric) of the general python.org offering, whilst retaining a blind spot for the obvious contribution that the Wikis can make to such improvement efforts. I encourage people to use wiki.python.org a lot more, should they be looking to improve the wealth of information provided by the community. Paul From ethan at stoneleaf.us Thu Aug 13 10:47:56 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Aug 2009 07:47:56 -0700 Subject: what is it, that I don't understand about python and lazy evaluation? In-Reply-To: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Message-ID: <4A84279C.2030504@stoneleaf.us> Erik Bernoth wrote: > Hi List, > > look at the following code: > > def evens(): > # iterator returning even numbers > i = 0 > while True: > yield i > i += 2 > > # now get all the even numbers up to 15 > L = [n for n in evens() if n < 15] > > Isn't it strange, that this code runs (in a lazy language) for eternity? > I would expect python to to spit out (in no time): > >> L > [0, 2, 4, 6, 8, 10, 12, 14] > > after 14 it is not nessesary to evaluate evens() any further. > > I really started to ask myself if python really is lazy, but everything > else I wrote in lazy style still worked. Example: > >> def test(txt, retval): > .. print(txt) > .. return retval > .. > >>> test(1, True) or test(2, True) > 1 > True > >>> test(1, True) and test(2, True) > 1 > 2 > True > > > Can anybody explain what happens with evens()? > > best regards > Erik Bernoth > > PS: The code comes from a list post from 2006. You find it here: > http://mail.python.org/pipermail/python-list/2006-November/585783.html > As MRAB pointed out, the issue is not with evens, it's with the list comprehension. The list comprehension doesn't know when to stop, only which numbers to include. ~Ethan~ From jschwab at gmail.com Thu Aug 13 11:01:20 2009 From: jschwab at gmail.com (jschwab) Date: Thu, 13 Aug 2009 08:01:20 -0700 (PDT) Subject: Format Code Repeat Counts? References: Message-ID: Thanks all! That was most helpful and informative. Best, Josiah From Samnsparky at gmail.com Thu Aug 13 11:30:55 2009 From: Samnsparky at gmail.com (Sparky) Date: Thu, 13 Aug 2009 08:30:55 -0700 (PDT) Subject: Tkinter Menu in Frame Message-ID: <37d94fb6-5afd-4a9e-a45b-49c08776cd82@r18g2000yqd.googlegroups.com> Hello! I am trying to figure out if it is possible to place a Tkinter menu within a frame. This would be instead of having the menu-bar at the top of the window. Thanks, Sam From davea at ieee.org Thu Aug 13 11:34:23 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 11:34:23 -0400 Subject: what is it, that I don't understand about python and lazy evaluation? In-Reply-To: References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Message-ID: <4A84327F.6040006@ieee.org> Antoine Pitrou wrote: > Erik Bernoth googlemail.com> writes: > >> Isn't it strange, that this code runs (in a lazy language) for eternity? >> > > Python is a not a lazy language. > `and` and `or` are particular, they are language constructs (*), not operators, > that's why they can decide whether or not to evaluate their second term. It's a > feature, but this feature is not general to Python. > > (*) by this I mean they have similar status as, for example, `if` and `else` > > > > Agreed. In fact, I don't know of any aspect of Python which I'd call lazy, although the word appears in the docs in a few places. I've seen, but not used, languages which had lazy evaluations. Simplest example would be an infinite precision math package, where the actual precision is not actually used till something external to the program got visibility to the value. So the constant PI might really be a generator, which would generate enough precision for whatever the value was being used for. If you did a free-form print of PI, the console would never terminate (in principle), but in practice, it'd get slower and slower printing out the digits till the machine ran out of memory, or the user lost patience. Python, on the other hand has at least three short-circuit operations, in which parts of the expression are defined not to be evaluated at all, if other parts meet certain conditions. These are the 'and' and 'or' keywords mentioned above, the chained comparison construct, and the conditional expression, added recently. In each of these, the semantics of the language require that those parts not be evaluated. val = (42 < x < function()) val = 19 if i<12 else function() val = x or function() In each example, the function() may or may not be actually called, depending on the other values of the expression. DaveA From marduk at letterboxes.org Thu Aug 13 11:42:42 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Thu, 13 Aug 2009 11:42:42 -0400 Subject: loops for ffmpeg CLI in python In-Reply-To: References: Message-ID: <1250178162.16478.0.camel@brotherus.corp.redhat.com> On Wed, 2009-08-12 at 11:29 +0200, fakhar Gillani wrote: > > Hi, > > I am a begineer in Python. Actually I am encoding video files with > different bitrates using ffmpeg CLI. I wanted to ask you that how can > I make loops so that I can vary the bitrates in the CLI of ffmpeg?? > > I want to bulid a loop for the command below where i just want to vary > the -vb parameter i.e. 10M. > > ffmpeg.exe -i sample.avi -y -f h264 -vb 10M -r 25 > encoded_1000_0-05.h264 > > I have tried to make simple loops but it doest work:( > > Can anyone here help me out? It might help if you specify what you tried and why it didn't work (for you). -a From breamoreboy at yahoo.co.uk Thu Aug 13 11:45:31 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 13 Aug 2009 16:45:31 +0100 Subject: Python configuration question when python scripts are executed using Appweb as web server. In-Reply-To: References: Message-ID: Gabriel Genellina wrote: [snip] >> Here are couple of links that discusses setting PYTHONPATH environment >> variable. >> http://docs.python.org/using/windows.html > > Ouch, that document should be reworked and updated! I don't understand this comment, given that the PEP370 Implementation section 2nd paragraph quite specifically refers to the use of PYTHONPATH, I quote. "The user site directory is added before the system site directories but after Python's search paths and PYTHONPATH. This setup allows the user to install a different version of a package than the system administrator but it prevents the user from accidently overwriting a stdlib module. Stdlib modules can still be overwritten with PYTHONPATH." What am I missing? > >> http://www.daimi.au.dk/~chili/PBI/pythonpath.html > [snip] -- Kindest regards. Mark Lawrence. From e.kroske at gmail.com Thu Aug 13 11:50:47 2009 From: e.kroske at gmail.com (Evan Kroske) Date: Thu, 13 Aug 2009 11:50:47 -0400 Subject: Delegate attribute requests to object Message-ID: <1a78d23f0908130850v3f013b37rd1a7bce23041eedc@mail.gmail.com> I'm trying to use the decorator pattern in a program I'm developing. I want to create a decorator object that works like the object it's decorating except for a few functions. However, I'd rather not hard-code all the identical functionality from the decorated object into the decorator object. Is there a way I can intercept all the attribute and function requests for the decorator and delegate them to the decorated object? Here's some example code: class Decorator: > def __init__(): > self.decorated = Decorated() > > def newFunction(): > # Do something > pass > > def interceptRequests(request): > return self.decorated.request() > > class Decorated: > def __init__(): > self.variable = 10 > > def oldFunction(): > # Do something > pass I want to be able to do something like this: objectA = Decorator() > objectB = Decorated() > assert objectA.oldFunction() == objectB.oldFunction() # No error > Is it possible (without inheritance)? -- Evan Kroske http://welcome2obscurity.blogspot.com/ The code, comments, and challenges of a novice software developer desperate for attention. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Aug 13 11:52:45 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 11:52:45 -0400 Subject: How to launch a function at regular time intervals ? In-Reply-To: References: Message-ID: <4A8436CD.9040308@ieee.org> Grant Edwards wrote: > On 2009-08-13, Dave Angel wrote: > > >> I'm assuming you want to call it every time_interval seconds, on >> average, with a little jitter allowed on each call, but keeping correct >> long term. In other words, if one call is a little late, you want the >> next one to still happen as close to on-time as possible. >> >> The general outline is something like (untested): >> >> times_called = 0 #number of times function has been called >> start_time = now >> while True: >> elapsed = now - start_time >> int_elapsed = int(elapsed/time_interval) >> for times_called in range(times_called, int_elapsed): >> call_the_function() >> sleep(time_interval/10) #this might give us 10% jitter, which is usually fine >> > > I don't understand the reasoning behind the above loop -- > specifically the sleeping of smaller intervals than needed. > > Why not something like this: > > interval = 5.0 # interval in seconds > next = time.time() > > while True: > now = time.time() > if now < next: > time.sleep(now-next) > print "call_the_function()" > next += interval > > That will be accurate over the long term with minimal jitter. > > > > Two reasons I didn't take an approach like that one. 1) I frequently need to do something else while waiting, so I tend to do multiple smaller sleeps. As long as each sleep is at least 100ms, the overhead cost is pretty small. 2) If (occasionally) the function takes longer than the specified interval time, my approach does catch-up calls so the average remains the same. My loop was only a rough outline, and if neither of these considerations applies, yours is much nicer. DaveA From gordon at panix.com Thu Aug 13 12:00:40 2009 From: gordon at panix.com (John Gordon) Date: Thu, 13 Aug 2009 16:00:40 +0000 (UTC) Subject: Interface to Exchange Calendar via web services Message-ID: I have a python app that needs to look up a person's Exchage Calendar entries to see if they are currently available. Does anyone have any code examples for communicating with EWS (Exchange Web Services)? I've found some code in Java and CSharp to do this, but none in python so far. Thanks! -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From rami.chowdhury at gmail.com Thu Aug 13 12:07:41 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 13 Aug 2009 09:07:41 -0700 Subject: Delegate attribute requests to object In-Reply-To: <1a78d23f0908130850v3f013b37rd1a7bce23041eedc@mail.gmail.com> References: <1a78d23f0908130850v3f013b37rd1a7bce23041eedc@mail.gmail.com> Message-ID: Perhaps I'm misunderstanding something, but I don't think that's really typical decorator behavior? Typically decorators, as I understand them, take an instance argument -- so you wouldn't be saying def __init__(self): self.decorated = Decorated() you'd be saying def __init__(self, decorated): self.decorated = decorated As for the attribute access, I believe you can override __getattr__ to do what you want: > class Decorator: > [snip] > def __getattr__(self, request): > return self.decorated.__getattr__(request) The same thing should work for methods, although you may want to pass arguments through as well. Is there a reason why, for this use, just making Decorator a subclass of Decorated (and only overriding the methods you need to be different) wouldn't work? On Thu, 13 Aug 2009 08:50:47 -0700, Evan Kroske wrote: > I'm trying to use the decorator pattern in a program I'm developing. I > want > to create a decorator object that works like the object it's decorating > except for a few functions. However, I'd rather not hard-code all the > identical functionality from the decorated object into the decorator > object. > Is there a way I can intercept all the attribute and function requests > for > the decorator and delegate them to the decorated object? Here's some > example > code: > > class Decorator: >> def __init__(): >> self.decorated = Decorated() >> >> def newFunction(): >> # Do something >> pass >> >> def interceptRequests(request): >> return self.decorated.request() >> >> class Decorated: >> def __init__(): >> self.variable = 10 >> >> def oldFunction(): >> # Do something >> pass > > > I want to be able to do something like this: > > objectA = Decorator() >> objectB = Decorated() >> assert objectA.oldFunction() == objectB.oldFunction() # No error >> > > Is it possible (without inheritance)? > > -- > Evan Kroske > http://welcome2obscurity.blogspot.com/ > The code, comments, and challenges of a novice > software developer desperate for attention. -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From ethan at stoneleaf.us Thu Aug 13 12:22:23 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Aug 2009 09:22:23 -0700 Subject: what is it, that I don't understand about python and lazy evaluation? In-Reply-To: <4A84279C.2030504@stoneleaf.us> References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> <4A84279C.2030504@stoneleaf.us> Message-ID: <4A843DBF.6050808@stoneleaf.us> Ethan Furman wrote: > Erik Bernoth wrote: > >> Hi List, >> >> look at the following code: >> >> def evens(): >> # iterator returning even numbers >> i = 0 >> while True: >> yield i >> i += 2 >> >> # now get all the even numbers up to 15 >> L = [n for n in evens() if n < 15] >> >> Isn't it strange, that this code runs (in a lazy language) for >> eternity? I would expect python to to spit out (in no time): >> >> L >> [0, 2, 4, 6, 8, 10, 12, 14] >> >> after 14 it is not nessesary to evaluate evens() any further. >> >> I really started to ask myself if python really is lazy, but >> everything else I wrote in lazy style still worked. Example: >> >> def test(txt, retval): >> .. print(txt) >> .. return retval >> .. >> >>> test(1, True) or test(2, True) >> 1 >> True >> >>> test(1, True) and test(2, True) >> 1 >> 2 >> True >> >> >> Can anybody explain what happens with evens()? >> >> best regards >> Erik Bernoth >> >> PS: The code comes from a list post from 2006. You find it here: >> http://mail.python.org/pipermail/python-list/2006-November/585783.html >> > > As MRAB pointed out, the issue is not with evens, it's with the list > comprehension. The list comprehension doesn't know when to stop, only > which numbers to include. > > ~Ethan~ > Actually, I am mistaken (gasp! shock! ;). A list comprehension will run until the iterator(s) it's based on end, and even() runs forever. ~Ethan~ From davigier at googlemail.com Thu Aug 13 12:25:58 2009 From: davigier at googlemail.com (David) Date: Thu, 13 Aug 2009 09:25:58 -0700 (PDT) Subject: How to launch a function at regular time intervals ? References: Message-ID: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> Thanks all for your answers. As suggested by Dave and Frank, I am indeed looking for the main program to continue running in the background (I have several functions I want to launch, each at a predefined time interval). I like Frank's solution, on the paper it seems it would do what I am looking for, but I cannot succeed in having it working. I guess I've been stuck with this problem for too long and can't succeed in using my brain accurately anymore... ;-) I defined the class as defined by Frank, and I then inserted the following code in a While True loop, without any other code (the idea is just to test Frank's solution before really using it in my program): func = MyFunction() func.start() func.stop() func.join() However I'm not getting the expected behavior. It's not taking into account the 30 sec wait, the function is called again and again without any time interval... Any idea ? Again, thanks a lot. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 13 12:33:55 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2009 16:33:55 GMT Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <65053f02-0e64-4070-90c8-e04394be90ad@d32g2000yqh.googlegroups.com> Message-ID: <029430d5$0$20647$c3e8da3@news.astraweb.com> On Wed, 12 Aug 2009 20:23:27 -0700, rurpy wrote: >> That's no different from *any* major refactoring. The exact same >> problem exists for code as well as documentation. It's a solved problem >> for code, and it's a solved problem for documentation. > > Huh? I don't buy this at all. Code refactoring doesn't change the > semantics of the program at all -- it simplifies the code that > implements behavior without changing behavior. How does this apply to > revising documentation? My apologies, I mis-wrote. Of course refactoring is inappropriate in this context. What I meant was a major redesign where the API may change. Except of course that documentation changes don't need to be concerned with backwards compatibility, except possibly to avoid breaking old links. [...] >> Yes it would. Most patches are ignored, because the dev team are >> overworked, and if they don't see the need for a patch, they won't >> approve it. > > I'm confused. If they weren't overworked, then they would approve > patches they didn't see a need for? No. If they're overworked, they're less likely to spend time investigating patches which aren't immediately obvious that they're needed. And additionally, if the patch doesn't appear to be useful, it's unlikely to be approved. Why would it be? > Or are you saying because they are > overworked they fail to approve patches that should be approved? Invariably there will be good patches missed because they haven't been noticed. > I am > not sure how either supports the argument that the tracker is the best > method of improving the docs. These are not arguments in favour of the tracker, these are realistic issues that any project of non-trivial size have to deal with. Virtually every project (not just software projects either) have to deal with the fact that there will be more things to do than resources to do them with. [...] >> No, submitting a tracker issue is a necessary but not sufficient step. >> Without a tracker issue, you're very unlikely to have people agree to >> replace the existing docs with your docs, although a PEP would probably >> do it. (A PEP is significantly more effort than raising a tracker >> issue.) > > Has there ever been a PEP for a doc change? Are you making a serious > suggestion? I don't know if there ever has been, but as far as I know, there are two ways to get changes approved to Python: informal approval by somebody with check-in privileges, or formal approval on the basis of a PEP. If you can't get the first, then the second is an option, albeit unlikely. >>> As long as every "the docs >>> sux" complaint is met here with the standard responses that I've >>> mentioned, >> >> But they aren't met with such a so-called "standard response". > > I just looked through the first 70 or so messages in this thread and in > this case I have agree with you, most of the responses were not what I > called "standard responses". There was one guy, a Steven D'Aprano early > on that trotted out the, "it's free software, fix it if you don't like > it" line, And I stand by it. If you're not helping to solve the problem, then what exactly are you doing? Even if you can't provide a patch, provide a bug report. What specifically is wrong with the docs? Be specific. Give examples. Explain why it is wrong. State your assumptions, e.g. what audience do you represent? If you do these things, you're helping. If you're just complaining, then you're not. >> We know that there are problems. We've said repeatedly that corrections >> and patches are welcome. We've repeatedly told you how to communicate >> your answer to the question of what should be done. None of this is >> good enough for you. I don't know what else you expect. > > You have been told repeatedly why your insistence that the tracker must > be the only channel, is wrong. I don't understand why you can't > understand that. > > (Generally only those in authority, bosses, parents, police, and the > like, "tell" others what a situation is and have a right to demand that > the subject accept it without question. I think you could find a more > respectful and less authoritarian way of phrasing what you said above > since you are not in a position of authority over me.) "You're not my real dad!!!" In the words of Jesse "The Body" Venture, I'm just telling it like it is. The tracker is the only practical way of getting doc changes accepted, for those without check-in privileges or the ear of someone with them. Me telling you this is no more an expression of authority than me telling you that the USA has 50 states. Of course I could be wrong. My understanding of the facts might be wrong, or I may not be in full possession of all the relevant facts. If so, I welcome correction. So please tell me, what other practical ways are there for an unprivileged person to get the official Python docs modified? -- Steven From invalid at invalid Thu Aug 13 12:40:06 2009 From: invalid at invalid (Grant Edwards) Date: Thu, 13 Aug 2009 11:40:06 -0500 Subject: How to launch a function at regular time intervals ? References: Message-ID: On 2009-08-13, Dave Angel wrote: > Grant Edwards wrote: >> On 2009-08-13, Dave Angel wrote: >>> The general outline is something like (untested): >>> >>> times_called = 0 #number of times function has been called >>> start_time = now >>> while True: >>> elapsed = now - start_time >>> int_elapsed = int(elapsed/time_interval) >>> for times_called in range(times_called, int_elapsed): >>> call_the_function() >>> sleep(time_interval/10) #this might give us 10% jitter, which is usually fine >> >> I don't understand the reasoning behind the above loop -- >> specifically the sleeping of smaller intervals than needed. >> >> Why not something like this: >> >> interval = 5.0 # interval in seconds >> next = time.time() >> >> while True: >> now = time.time() >> if now < next: >> time.sleep(now-next) >> print "call_the_function()" >> next += interval >> >> That will be accurate over the long term with minimal jitter. >> > Two reasons I didn't take an approach like that one. > > 1) I frequently need to do something else while waiting, so I > tend to do multiple smaller sleeps. As long as each sleep > is at least 100ms, the overhead cost is pretty small. I guess I always use a separate thread for cases like that. > 2) If (occasionally) the function takes longer than the > specified interval time, my approach does catch-up calls so > the average remains the same. I'm still confused -- doesn't mine do that as well? -- Grant Edwards grante Yow! Are you the at self-frying president? visi.com From tim.arnold at sas.com Thu Aug 13 12:57:17 2009 From: tim.arnold at sas.com (Tim Arnold) Date: Thu, 13 Aug 2009 12:57:17 -0400 Subject: coding for multiple versions of python Message-ID: Hi, I've got a python based system that has to run on hp unix and red hat linux. The Python version on the HP is 2.4 and the version on the Linux box is 2.6. There's nothing I can do about that. I think that means I must have two different libraries since the pyc files are not cross-version compatible. No problem for the libs like PIL or lxml. But for the part of the system I actually code every day, I'd rather not do dual maintenance, having two copies of my code for each platform/version. I'm guessing I need to configure cvs to copy files to both locations whenever I commit. Does that sound right? Is there a better way I'm not thinking of? thanks, --Tim From aahz at pythoncraft.com Thu Aug 13 12:58:52 2009 From: aahz at pythoncraft.com (Aahz) Date: 13 Aug 2009 09:58:52 -0700 Subject: Database query execution times in Python? References: Message-ID: In article , pwnedd wrote: > >I've been writing some code using libraries based on the Python Database API >2.0 (MySQLdb & pg), and so far things are working really well. There is one >thing that I have not been able to figure out how to do, however: > >Retrieve the time is took a given query to execute. Look up EXPLAIN -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From aahz at pythoncraft.com Thu Aug 13 13:04:54 2009 From: aahz at pythoncraft.com (Aahz) Date: 13 Aug 2009 10:04:54 -0700 Subject: httplib incredibly slow :-( References: Message-ID: In article , Chris Withers wrote: >Aahz wrote: >> In article , >> Chris Withers wrote: >>> >>> Does anyone know of an alternative library for creating http requests >>> and getting their responses that's faster but hopefully has a similar >>> interface? >> >> PyCurl > >This seems to be a wrapper around libcurl. >Does it work on Windows? Yes. >If so, where can I find some decent examples? >(the ones listed on the pycurl website are not what I'd call decent :-S) Sorry, I mostly have been working on our Mac port, so I'm not sure what's needed to make this work on Windows. Did you try downloading the PyCurl binary? Maybe it statically links libcurl on Windows. What do you need to know for a decent example? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From rays at blue-cove.com Thu Aug 13 13:13:54 2009 From: rays at blue-cove.com (RJ) Date: Thu, 13 Aug 2009 10:13:54 -0700 Subject: Social problems of Python doc [was Re: Python docs disappointing] In-Reply-To: <029430d5$0$20647$c3e8da3@news.astraweb.com> References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <65053f02-0e64-4070-90c8-e04394be90ad@d32g2000yqh.googlegroups.com> <029430d5$0$20647$c3e8da3@news.astraweb.com> Message-ID: <6.2.3.4.2.20090813100638.04a00478@blue-cove.com> A basic question in this thread is: Who will host the doc-wiki/whatever and how will it be linked to? If not hosted at python.org it can still be linked to from their docs, if allowed, possibly with 3rd level domain and re-direct. I host a number of commercial servers but I don't expect Guido to bless them with said links. If hosted at python.org it will require resources from the existing admins. If elsewhere then trusted admins and organization. If not linked to from python.org then it may well expire from lack of interest, as other seemingly nice attempts did. Ray Schumacher From python at mrabarnett.plus.com Thu Aug 13 13:16:21 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 13 Aug 2009 18:16:21 +0100 Subject: How to launch a function at regular time intervals ? In-Reply-To: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> Message-ID: <4A844A65.7080906@mrabarnett.plus.com> David wrote: > Thanks all for your answers. As suggested by Dave and Frank, I am > indeed looking for the main program to continue running in the > background (I have several functions I want to launch, each at a > predefined time interval). I like Frank's solution, on the paper it > seems it would do what I am looking for, but I cannot succeed in > having it working. I guess I've been stuck with this problem for too > long and can't succeed in using my brain accurately anymore... ;-) > > I defined the class as defined by Frank, and I then inserted the > following code in a While True loop, without any other code (the idea > is just to test Frank's solution before really using it in my > program): > > func = MyFunction() > func.start() > > func.stop() > func.join() > > However I'm not getting the expected behavior. It's not taking into > account the 30 sec wait, the function is called again and again > without any time interval... Any idea ? > > Again, thanks a lot. > What exactly do you mean by "I then inserted the following code in a While True loop"? Do you mean you put all four lines in it? If yes, then you're repeatedly starting then stopping the function. From rami.chowdhury at gmail.com Thu Aug 13 13:18:05 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 13 Aug 2009 10:18:05 -0700 Subject: Delegate attribute requests to object In-Reply-To: <1a78d23f0908131013x25feee2fwe6b907045e87b6f5@mail.gmail.com> References: <1a78d23f0908130850v3f013b37rd1a7bce23041eedc@mail.gmail.com> <1a78d23f0908131013x25feee2fwe6b907045e87b6f5@mail.gmail.com> Message-ID: More information at http://www.python.org/doc/2.5.2/ref/attribute-access.html if you need it :-) On Thu, 13 Aug 2009 10:13:47 -0700, Evan Kroske wrote: > I don't want to inherit from the classes I'm decorating because they > have a > common superclass. I can make a generic decorator that I can use on all > its > sibling classes. I'll try your getattr method to see if it works. > > On Thu, Aug 13, 2009 at 12:07 PM, Rami Chowdhury > wrote: > >> Perhaps I'm misunderstanding something, but I don't think that's really >> typical decorator behavior? Typically decorators, as I understand them, >> take >> an instance argument -- so you wouldn't be saying >> >> def __init__(self): >> self.decorated = Decorated() >> >> you'd be saying >> >> def __init__(self, decorated): >> self.decorated = decorated >> >> As for the attribute access, I believe you can override __getattr__ to >> do >> what you want: >> >> class Decorator: >>> [snip] >>> def __getattr__(self, request): >>> return self.decorated.__getattr__(request) >>> >> >> The same thing should work for methods, although you may want to pass >> arguments through as well. >> >> Is there a reason why, for this use, just making Decorator a subclass of >> Decorated (and only overriding the methods you need to be different) >> wouldn't work? >> >> >> On Thu, 13 Aug 2009 08:50:47 -0700, Evan Kroske >> wrote: >> >> I'm trying to use the decorator pattern in a program I'm developing. I >>> want >>> to create a decorator object that works like the object it's decorating >>> except for a few functions. However, I'd rather not hard-code all the >>> identical functionality from the decorated object into the decorator >>> object. >>> Is there a way I can intercept all the attribute and function requests >>> for >>> the decorator and delegate them to the decorated object? Here's some >>> example >>> code: >>> >>> class Decorator: >>> >>>> def __init__(): >>>> self.decorated = Decorated() >>>> >>>> def newFunction(): >>>> # Do something >>>> pass >>>> >>>> def interceptRequests(request): >>>> return self.decorated.request() >>>> >>>> class Decorated: >>>> def __init__(): >>>> self.variable = 10 >>>> >>>> def oldFunction(): >>>> # Do something >>>> pass >>>> >>> >>> >>> I want to be able to do something like this: >>> >>> objectA = Decorator() >>> >>>> objectB = Decorated() >>>> assert objectA.oldFunction() == objectB.oldFunction() # No error >>>> >>>> >>> Is it possible (without inheritance)? >>> >>> -- >>> Evan Kroske >>> http://welcome2obscurity.blogspot.com/ >>> The code, comments, and challenges of a novice >>> software developer desperate for attention. >>> >> >> >> >> -- >> Rami Chowdhury >> "Never attribute to malice that which can be attributed to stupidity" -- >> Hanlon's Razor >> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) >> > > > -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From webcokies at yahoo.com Thu Aug 13 13:52:46 2009 From: webcokies at yahoo.com (Joni Lee) Date: Thu, 13 Aug 2009 10:52:46 -0700 (PDT) Subject: Help newbie with how to call a source command Message-ID: <901009.79843.qm@web36903.mail.mud.yahoo.com> Hi all, ? I'm landing here because I need some help that I couldn't get through it. Question 1. I want to call a source command from python script. It will source some?variables enviroment for further commands. I tried the following which did not work os.sys('source '+source_text) call(['source',source_text], shell=True) commands.getoutput('source '+source_text) ? Anyone have experiences with this? Because I'm very new to this world so a details reply is really appreciated!!! thank you very much ? Question 2. I call a shell command from python, this time it runs a script which runs some ruby scripts. And the error returns: "ruby: command not found" ? Thank you again -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Thu Aug 13 14:12:07 2009 From: aahz at pythoncraft.com (Aahz) Date: 13 Aug 2009 11:12:07 -0700 Subject: How to address a global variable in a function References: <82c2f2e7-ed3e-482b-9318-d5539a2a9da8@y10g2000prg.googlegroups.com> Message-ID: In article <82c2f2e7-ed3e-482b-9318-d5539a2a9da8 at y10g2000prg.googlegroups.com>, n179911 wrote: > >I have a global variable > >// line 8 >tx = 0 > >and then I have this function (start in line 12): >def handleTranslate(result): > print line > txStr, tyStr = result.group(1), result.group(2) > print txStr, tyStr > > tx += int(txStr) > ty += int(tyStr) > > return BTW, you probably want to learn why global names are a bad idea, I don't have time to explain that here (or point you at references). Going through some of the online tutorials should address this. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From rami.chowdhury at gmail.com Thu Aug 13 14:29:04 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 13 Aug 2009 11:29:04 -0700 Subject: Delegate attribute requests to object In-Reply-To: <1a78d23f0908131100p75520be4oe7572aae00bf2f13@mail.gmail.com> References: <1a78d23f0908130850v3f013b37rd1a7bce23041eedc@mail.gmail.com> <1a78d23f0908131013x25feee2fwe6b907045e87b6f5@mail.gmail.com> <1a78d23f0908131100p75520be4oe7572aae00bf2f13@mail.gmail.com> Message-ID: Oops, my apologies, it's the __getattribute__ method you want to call on self.decorated (because __getattr__ won't be there unless you define it specifically) So it should go: def __getattr__(self, request): return self.decorated.__getattribute__(request) On Thu, 13 Aug 2009 11:00:28 -0700, Evan Kroske wrote: > Unfortunately, __getattr__ didn't work. When I try to use your code > > class Decorator: >> [snip] >> def __getattr__(self, request): >> return self.decorated.__getattr__(request) >> > > I get this error: > > AttributeError: 'Decorated' object has no attribute '__getattr__' >> > > Is that a private method, or am I simply using it wrong? Thanks for the > help. > > On Thu, Aug 13, 2009 at 1:18 PM, Rami Chowdhury > wrote: > >> More information at >> http://www.python.org/doc/2.5.2/ref/attribute-access.html if you need it >> :-) >> >> >> On Thu, 13 Aug 2009 10:13:47 -0700, Evan Kroske >> wrote: >> >> I don't want to inherit from the classes I'm decorating because they >> have >>> a >>> common superclass. I can make a generic decorator that I can use on all >>> its >>> sibling classes. I'll try your getattr method to see if it works. >>> >>> On Thu, Aug 13, 2009 at 12:07 PM, Rami Chowdhury >>> wrote: >>> >>> Perhaps I'm misunderstanding something, but I don't think that's >>> really >>>> typical decorator behavior? Typically decorators, as I understand >>>> them, >>>> take >>>> an instance argument -- so you wouldn't be saying >>>> >>>> def __init__(self): >>>> self.decorated = Decorated() >>>> >>>> you'd be saying >>>> >>>> def __init__(self, decorated): >>>> self.decorated = decorated >>>> >>>> As for the attribute access, I believe you can override __getattr__ >>>> to do >>>> what you want: >>>> >>>> class Decorator: >>>> >>>>> [snip] >>>>> def __getattr__(self, request): >>>>> return self.decorated.__getattr__(request) >>>>> >>>>> >>>> The same thing should work for methods, although you may want to pass >>>> arguments through as well. >>>> >>>> Is there a reason why, for this use, just making Decorator a subclass >>>> of >>>> Decorated (and only overriding the methods you need to be different) >>>> wouldn't work? >>>> >>>> >>>> On Thu, 13 Aug 2009 08:50:47 -0700, Evan Kroske >>>> wrote: >>>> >>>> I'm trying to use the decorator pattern in a program I'm developing. >>>> I >>>> >>>>> want >>>>> to create a decorator object that works like the object it's >>>>> decorating >>>>> except for a few functions. However, I'd rather not hard-code all the >>>>> identical functionality from the decorated object into the decorator >>>>> object. >>>>> Is there a way I can intercept all the attribute and function >>>>> requests >>>>> for >>>>> the decorator and delegate them to the decorated object? Here's some >>>>> example >>>>> code: >>>>> >>>>> class Decorator: >>>>> >>>>> def __init__(): >>>>>> self.decorated = Decorated() >>>>>> >>>>>> def newFunction(): >>>>>> # Do something >>>>>> pass >>>>>> >>>>>> def interceptRequests(request): >>>>>> return self.decorated.request() >>>>>> >>>>>> class Decorated: >>>>>> def __init__(): >>>>>> self.variable = 10 >>>>>> >>>>>> def oldFunction(): >>>>>> # Do something >>>>>> pass >>>>>> >>>>>> >>>>> >>>>> I want to be able to do something like this: >>>>> >>>>> objectA = Decorator() >>>>> >>>>> objectB = Decorated() >>>>>> assert objectA.oldFunction() == objectB.oldFunction() # No error >>>>>> >>>>>> >>>>>> Is it possible (without inheritance)? >>>>> >>>>> -- >>>>> Evan Kroske >>>>> http://welcome2obscurity.blogspot.com/ >>>>> The code, comments, and challenges of a novice >>>>> software developer desperate for attention. >>>>> >>>>> >>>> >>>> >>>> -- >>>> Rami Chowdhury >>>> "Never attribute to malice that which can be attributed to stupidity" >>>> -- >>>> Hanlon's Razor >>>> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) >>>> >>>> >>> >>> >>> >> >> >> -- >> Rami Chowdhury >> "Never attribute to malice that which can be attributed to stupidity" -- >> Hanlon's Razor >> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) >> > > > -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From jura.grozni at gmail.com Thu Aug 13 14:56:49 2009 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Aug 2009 11:56:49 -0700 (PDT) Subject: i Don't get why it makes trouble Message-ID: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> >>> j [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] >>> len(j) 5 >>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s'""" % (j) Traceback (most recent call last): File "", line 1, in TypeError: not enough arguments for format string I want to format the string. the list has five elements and the string has five placeholder but it wont format the string From lkcl at lkcl.net Thu Aug 13 15:01:41 2009 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Thu, 13 Aug 2009 19:01:41 +0000 Subject: [ANN] pyjamas 0.6pre3 released Message-ID: much as we'd very much like to declare a 0.6 stable release, really really soon and move forward, the ChangeLog just keeps growing (133 and counting) with the bugfixes, testing and contributions since 0.5p1. pyjamas is a port of GWT to python, and includes a python-to-javascript compiler and a widget UI toolkit that is similar to pyqt4, pygtk2 etc. applications can either be run as javascript (in a web browser) or on the desktop (using pyjamas-desktop) as python. conceptually therefore, pyjamas is similar to adobe AIR - except that it's python, not ActionScript, and it's entirely free software. hurrah! key changes: * the python-to-javascript has been significantly reworked, and now includes a --strict option which adds "python strict" features at the expense of speed. to disable these, and obtain speed instead, use "-O" * pyjamas-desktop has been merged into the pyjamas distribution, which includes support for one stable browser engine (XULrunner, the same engine behind firefox); pywebkitgtk (the engine behind safari and the iphone) and MSHTML (IE's engine). pywebkitgtk is useable (but unfriendly - no DOM exception handling); MSHTML is even less friendly - COM gets in the way at present, and eats even python exceptions). there's a lot more that could be said, but you've probably noticed all the other prerelease notices so 'nuff said, other than: thank you to the people who've been helping and contributing with testing, patches and more. downloads and more information: http://pypi.python.org/pypi/Pyjamas http://sf.net/projects/pyjamas http://code.google.com/p/pyjamas http://pyjs.org From pfeldman at verizon.net Thu Aug 13 15:05:26 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Thu, 13 Aug 2009 12:05:26 -0700 (PDT) Subject: trouble with reload Message-ID: <24956946.post@talk.nabble.com> According to the Python documentation, 'reload' reloads a previously imported module (so that changes made via an external editor will be effective). But, when I try to use this command, I get the following error message: TypeError: reload() argument must be module Any suggestions will be appreciated. -- View this message in context: http://www.nabble.com/trouble-with-reload-tp24956946p24956946.html Sent from the Python - python-list mailing list archive at Nabble.com. From zuo at chopin.edu.pl Thu Aug 13 15:06:47 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 13 Aug 2009 21:06:47 +0200 Subject: i Don't get why it makes trouble In-Reply-To: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: 13-08-2009 azrael wrote: >>>> j > [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] >>>> len(j) > 5 >>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, >>>> d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as >>>> z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' >>>> AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s'""" % (j) > Traceback (most recent call last): > File "", line 1, in > TypeError: not enough arguments for format string > > > I want to format the string. the list has five elements and the string > has five placeholder but it wont format the string j must be a tuple -- so either define it as (u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna') or when using it, wrap it with tuple() constructor: h = """...........""" % tuple(j) -- Jan Kaliszewski (zuo) From rami.chowdhury at gmail.com Thu Aug 13 15:07:36 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 13 Aug 2009 12:07:36 -0700 Subject: trouble with reload In-Reply-To: <24956946.post@talk.nabble.com> References: <24956946.post@talk.nabble.com> Message-ID: Could you please clarify how you're calling it? E.g. reload('foo') or reload(foo) ? On Thu, 13 Aug 2009 12:05:26 -0700, Dr. Phillip M. Feldman wrote: > According to the Python documentation, 'reload' reloads a previously > imported > module (so that changes made via an external editor will be effective). > But, when I try to use this command, I get the following error message: > > TypeError: reload() argument must be module > > Any suggestions will be appreciated. -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From zuo at chopin.edu.pl Thu Aug 13 15:12:50 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 13 Aug 2009 21:12:50 +0200 Subject: i Don't get why it makes trouble In-Reply-To: References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: Me wrote: > 13-08-2009 azrael wrote: > >>>>> j >> [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] >>>>> len(j) >> 5 >>>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, >>>>> d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as >>>>> z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = >>>>> '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s'""" % >>>>> (j) >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: not enough arguments for format string >> >> >> I want to format the string. the list has five elements and the string >> has five placeholder but it wont format the string > > j must be a tuple -- so either define it as [snip] PS. If you use Python 2.6 or newer, better use .format() method (then you can use also a list): >>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, \ ... d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as \ ... z, drzava as d, valuta as v WHERE u.naziv = '{0}' AND o.naziv = \ ... '{1}' AND z.naziv = '{2}' AND d.naziv = '{3}' AND v.naziv = '{4}'\ ... """.format(*j) Cheers, *j -- Jan Kaliszewski (zuo) From davea at ieee.org Thu Aug 13 15:17:00 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 15:17:00 -0400 Subject: How to launch a function at regular time intervals ? In-Reply-To: References: Message-ID: <4A8466AC.6080509@ieee.org> Grant Edwards wrote: > On 2009-08-13, Dave Angel wrote: > >> Grant Edwards wrote: >> >>> >>> interval = 5.0 # interval in seconds >>> next = time.time() >>> >>> while True: >>> now = time.time() >>> if now < next: >>> time.sleep(now-next) >>> print "call_the_function()" >>> next += interval >>> >>> That will be accurate over the long term with minimal jitter. >>> >>> >> >> 2) If (occasionally) the function takes longer than the >> specified interval time, my approach does catch-up calls so >> the average remains the same. >> > > I'm still confused -- doesn't mine do that as well? > > Yep. I missed it again. Clearly it does the catchup the next time around the while loop. DaveA From dullrich at sprynet.com Thu Aug 13 15:20:13 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Thu, 13 Aug 2009 14:20:13 -0500 Subject: trouble with reload References: Message-ID: On Thu, 13 Aug 2009 12:05:26 -0700, Dr. Phillip M. Feldman wrote: > According to the Python documentation, 'reload' reloads a previously > imported module (so that changes made via an external editor will be > effective). But, when I try to use this command, I get the following > error message: > > TypeError: reload() argument must be module That would mean that you're trying to reload something other than a module. Of course you think you're reloading a module. The problem is that... oops, since you don't show the code that leads to this error it's hard to say what the problem is. > Any suggestions will be appreciated. From garrickp at gmail.com Thu Aug 13 15:21:13 2009 From: garrickp at gmail.com (Falcolas) Date: Thu, 13 Aug 2009 12:21:13 -0700 (PDT) Subject: How to launch a function at regular time intervals ? References: Message-ID: On Aug 12, 3:09?pm, David wrote: > Hi all, I'm trying to launch a function at regular time intervals but > cannot find the way to do it. Here is the code I wrote (time_interval > is a user defined variable in seconds): > [snip] > Has anyone run into a similar problem (and solved it) ? > > Thanks for your help I did - as part of a script where I needed to send load into a system at a steady rate. I ended up using threading to do the function calls, since they were not guaranteed to complete before the next interval. duration_start = time.time() interval_counter = 0 while time.time() - duration_start < duration: for thread_count in xrange(numthreads): threading.Thread(target=exec_thread, kwargs={#snip unimportant#}).start() interval_counter += 1 time.sleep((duration_start + (interval * interval_counter)) - time.time()) Executing this loop with a simple echo and time print showed that there was no creep over time, and the deviation between intervals was around 1/100th of a second. I'm fairly sure I'm creating some gnarly memory leaks and such by not joining spent threads, but it's been a non-issue in my usage. Adding a list to keep track of the threads and join on complete threads would be fairly trivial to implement. I think for simpler applications, using threading.Timer to kick off the function would work just as well. ~G From jura.grozni at gmail.com Thu Aug 13 15:26:07 2009 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Aug 2009 12:26:07 -0700 (PDT) Subject: i Don't get why it makes trouble References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: <189e10f1-771a-4631-a907-56d450b5e493@c2g2000yqi.googlegroups.com> On 13 kol, 21:12, "Jan Kaliszewski" wrote: > Me wrote: > > 13-08-2009 azrael wrote: > > >>>>> j > >> [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] > >>>>> len(j) > >> 5 > >>>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, ? > >>>>> d.id_drzava, v.id_valuta FROM ? ulica as u, opcina as o, zupanija as ? > >>>>> z, drzava as d, valuta as v ?WHERE ?u.naziv = '%s' AND o.naziv = ? > >>>>> '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s'""" % ? > >>>>> (j) > >> Traceback (most recent call last): > >> ? File "", line 1, in > >> TypeError: not enough arguments for format string > > >> I want to format the string. the list has five elements and the string > >> has five placeholder but it wont format the string > > > j must be a tuple -- so either define it as > > [snip] > > PS. If you use Python 2.6 or newer, better use .format() method > (then you can use also a list): > > >>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, \ > > ... d.id_drzava, v.id_valuta FROM ? ulica as u, opcina as o, zupanija as \ > ... z, drzava as d, valuta as v ?WHERE ?u.naziv = '{0}' AND o.naziv = \ > ... '{1}' AND z.naziv = '{2}' AND d.naziv = '{3}' AND v.naziv = '{4}'\ > ... """.format(*j) > > Cheers, > *j > > -- > Jan Kaliszewski (zuo) Thanks Worked fine for me. I was a freakin idiot. I forgot about using a tuple. damn lists :D Thanks for the debuginig of my thoughts and actions. thnx From davea at ieee.org Thu Aug 13 15:28:02 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 15:28:02 -0400 Subject: How to launch a function at regular time intervals ? In-Reply-To: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> Message-ID: <4A846942.3020708@ieee.org> David wrote: > Thanks all for your answers. As suggested by Dave and Frank, I am > indeed looking for the main program to continue running in the > background (I have several functions I want to launch, each at a > predefined time interval). I like Frank's solution, on the paper it > seems it would do what I am looking for, but I cannot succeed in > having it working. I guess I've been stuck with this problem for too > long and can't succeed in using my brain accurately anymore... ;-) > > I defined the class as defined by Frank, and I then inserted the > following code in a While True loop, without any other code (the idea > is just to test Frank's solution before really using it in my > program): > > func = MyFunction() > func.start() > > func.stop() > func.join() > > However I'm not getting the expected behavior. It's not taking into > account the 30 sec wait, the function is called again and again > without any time interval... Any idea ? > > Again, thanks a lot. > > > Why don't you include the code you're actually trying, instead of just trying to describe it. Frank's class didn't call any function, it just had a place to do it. So we really don't know what you're running, nor what about it is wrong. Perhaps a few well placed print statements? DaveA From ebonak at hotmail.com Thu Aug 13 15:28:44 2009 From: ebonak at hotmail.com (Esmail) Date: Thu, 13 Aug 2009 15:28:44 -0400 Subject: get output of du / ls command - currently ugly code ... Message-ID: Hi all, Essentially all I want to know the size of a directory, and the size of a zipped tarball so that I can compute/report the compression ratio. The code I have seems hideous, but it seems to work. Surely there is an easier,more elegant way to do this? dir_size = os.popen('du -sk somename') data = dir_size.readlines() dir_size = int(data[0].split()[0]) print 'dir size: ', dir_size tar_size = os.popen('ls -s somename.tar.gz') data = tar_size.readlines() tar_size = int(data[0].split()[0]) print 'tar size: ', tar_size Thanks Esmail From rebfj at yahoo.co.uk Thu Aug 13 15:48:18 2009 From: rebfj at yahoo.co.uk (rebfj at yahoo.co.uk) Date: Thu, 13 Aug 2009 12:48:18 -0700 (PDT) Subject: get output of du / ls command - currently ugly code ... References: Message-ID: <6d501dbf-bbed-4b38-afc1-f956c9ff3ab6@h21g2000yqa.googlegroups.com> On Aug 13, 8:28?pm, Esmail wrote: > Hi all, > > Essentially all I want to know the size of a directory, and the size > of a zipped tarball so that I can compute/report the compression ratio. > > The code I have seems hideous, but it seems to work. Surely there is an > easier,more elegant way to do this? > > ? ? ?dir_size = os.popen('du -sk somename') > ? ? ?data = dir_size.readlines() > ? ? ?dir_size = int(data[0].split()[0]) > ? ? ?print 'dir size: ', dir_size > > ? ? ?tar_size = os.popen('ls -s somename.tar.gz') > ? ? ?data = tar_size.readlines() > ? ? ?tar_size = int(data[0].split()[0]) > ? ? ?print 'tar size: ', tar_size > > Thanks > Esmail Try using os.path.getsize(somename.tar.gz) From davea at ieee.org Thu Aug 13 15:48:55 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 15:48:55 -0400 Subject: Help newbie with how to call a source command In-Reply-To: <901009.79843.qm@web36903.mail.mud.yahoo.com> References: <901009.79843.qm@web36903.mail.mud.yahoo.com> Message-ID: <4A846E27.9090502@ieee.org> Joni Lee wrote: > Hi all, > > I'm landing here because I need some help that I couldn't get through it. > Question 1. > I want to call a source command from python script. It will source some variables enviroment for further commands. I tried the following which did not work > os.sys('source '+source_text) > call(['source',source_text], shell=True) > commands.getoutput('source '+source_text) > > Anyone have experiences with this? Because I'm very new to this world so a details reply is really appreciated!!! thank you very much > > Question 2. > I call a shell command from python, this time it runs a script which runs some ruby scripts. And the error returns: "ruby: command not found" > > Thank you again > > > 1) You cannot do "source" from Python. It's a shell command whose very nature is to remember some environment variables for the duration of that particular shell. So once it returns to your python program, they're lost. However, if you just need those variables for invocations of the same shell, you have a couple of choices. You can parse the file yourself, and set up an environment dictionary, and pass that when you invoke subsequent shells. Or you can build a script on the fly, prepending whatever script you're planning to run with that source_text file. 2) In this question, and in general, you need to specify the Python version, the OS environment, the particular Python code you used to launch the shell, the contents of the script, and the results you saw. Use copy and paste, don't just paraphrase. And in a case like this one, somebody familiar with the environment (Ruby on Unix?) will probably have other questions: environment dictionary passed to the shell, did you get a Ruby startup prompt? Or whatever. DaveA From philip at semanchuk.com Thu Aug 13 16:09:04 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 13 Aug 2009 16:09:04 -0400 Subject: i Don't get why it makes trouble In-Reply-To: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: On Aug 13, 2009, at 2:56 PM, azrael wrote: >>>> j > [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] >>>> len(j) > 5 >>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, >>>> d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija >>>> as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv >>>> = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = >>>> '%s'""" % (j) > Traceback (most recent call last): > File "", line 1, in > TypeError: not enough arguments for format string Hi azrael, You already have an answer to your question so I won't address that. I want to point out that this is a dangerous way to build SQL statements. For instance, what happens if someone enters a city name of L'viv? Your SQL will break due to mismatched single quotes. This kind of code is vulnerable to SQL injection attacks: http://en.wikipedia.org/wiki/SQL_injection Parameterized SQL is safer. Googling for 'parameterized SQL Python' should find some examples for you. Good luck Philip From ebonak at hotmail.com Thu Aug 13 16:13:51 2009 From: ebonak at hotmail.com (Esmail) Date: Thu, 13 Aug 2009 16:13:51 -0400 Subject: get output of du / ls command - currently ugly code ... In-Reply-To: <6d501dbf-bbed-4b38-afc1-f956c9ff3ab6@h21g2000yqa.googlegroups.com> References: <6d501dbf-bbed-4b38-afc1-f956c9ff3ab6@h21g2000yqa.googlegroups.com> Message-ID: <4A8473FF.7050701@hotmail.com> rebfj at yahoo.co.uk wrote: > On Aug 13, 8:28 pm, Esmail wrote: >> Hi all, >> >> Essentially all I want to know the size of a directory, and the size >> of a zipped tarball so that I can compute/report the compression ratio. >> >> dir_size = os.popen('du -sk somename') >> data = dir_size.readlines() >> dir_size = int(data[0].split()[0]) >> print 'dir size: ', dir_size >> Hi, > Try using os.path.getsize(somename.tar.gz) Beautiful! .. that takes care of the tarball .. but it doesn't seem to work for reporting the total size of the directory. Any suggestions how to do that in a nicer way? I just looked through os.path.* and there doesn't seem to be a function to report what "du -sb" would. Thanks for your help, Esmail From marduk at letterboxes.org Thu Aug 13 16:16:29 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Thu, 13 Aug 2009 16:16:29 -0400 Subject: get output of du / ls command - currently ugly code ... In-Reply-To: References: Message-ID: <1250194589.19760.4.camel@brotherus.corp.redhat.com> On Thu, 2009-08-13 at 15:28 -0400, Esmail wrote: > Hi all, > > Essentially all I want to know the size of a directory, and the size > of a zipped tarball so that I can compute/report the compression ratio. > > The code I have seems hideous, but it seems to work. Surely there is an > easier,more elegant way to do this? > > dir_size = os.popen('du -sk somename') > data = dir_size.readlines() > dir_size = int(data[0].split()[0]) > print 'dir size: ', dir_size > > tar_size = os.popen('ls -s somename.tar.gz') > data = tar_size.readlines() > tar_size = int(data[0].split()[0]) > print 'tar size: ', tar_size > I don't know about "easier", but a more elegant way is to not use os.popen() and to use Python's functions os.path.getsize (or os.stat) and os.walk (or os.path.walk) to achieve this. In fact if you look at the docstring for os.walk there is an example that almost does what you're doing with du, but is cross-platform and not dependent on shelling a process and scraping its stdout. -a From benjamin.kaplan at case.edu Thu Aug 13 17:05:37 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 13 Aug 2009 17:05:37 -0400 Subject: i Don't get why it makes trouble In-Reply-To: References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: On Thu, Aug 13, 2009 at 4:09 PM, Philip Semanchuk wrote: > > On Aug 13, 2009, at 2:56 PM, azrael wrote: > > j >>>>> >>>> [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] >> >>> len(j) >>>>> >>>> 5 >> >>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, >>>>> d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as z, >>>>> drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' AND >>>>> z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s'""" % (j) >>>>> >>>> Traceback (most recent call last): >> File "", line 1, in >> TypeError: not enough arguments for format string >> > > Hi azrael, > You already have an answer to your question so I won't address that. I want > to point out that this is a dangerous way to build SQL statements. > > For instance, what happens if someone enters a city name of L'viv? Your > SQL will break due to mismatched single quotes. This kind of code is > vulnerable to SQL injection attacks: > http://en.wikipedia.org/wiki/SQL_injection > No explanation of SQL injection is complete without a link to the relevant XKCD. http://xkcd.com/327/ > > Parameterized SQL is safer. Googling for 'parameterized SQL Python' should > find some examples for you. > > Good luck > Philip > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin at python.org Thu Aug 13 17:12:50 2009 From: benjamin at python.org (Benjamin Peterson) Date: Thu, 13 Aug 2009 16:12:50 -0500 Subject: [RELEASED] Python 3.1.1 Release Candidate Message-ID: <1afaf6160908131412i3b6f6636wc3fc166db0b9d5ce@mail.gmail.com> On behalf of the Python development team, I'm pleased to announce the first release candidate of Python 3.1.1. This bug fix release fixes many normal bugs and several critical ones including potential data corruption in the io library. The final version should be out within the next week. Python 3.1 focuses on the stabilization and optimization of the features and changes that Python 3.0 introduced. For example, the new I/O system has been rewritten in C for speed. File system APIs that use unicode strings now handle paths with undecodable bytes in them. Other features include an ordered dictionary implementation, a condensed syntax for nested with statements, and support for ttk Tile in Tkinter. For a more extensive list of changes in 3.1, see http://doc.python.org/3.1/whatsnew/3.1.html or Misc/NEWS in the Python distribution. To download Python 3.1.1 visit: http://www.python.org/download/releases/3.1/ The 3.1 documentation can be found at: http://docs.python.org/3.1 Bugs can always be reported to: http://bugs.python.org Enjoy! -- Benjamin Peterson Release Manager benjamin at python.org (on behalf of the entire python-dev team and 3.1.1's contributors) From petermoeller at gmail.com Thu Aug 13 17:26:54 2009 From: petermoeller at gmail.com (PeteDK) Date: Thu, 13 Aug 2009 14:26:54 -0700 (PDT) Subject: need help calculating point between two coordinates. Message-ID: <2d059a29-933e-4e2c-8730-f1f2688af26c@24g2000yqm.googlegroups.com> Hi there I'am working on a route comparison tool for carpools. The route comparison is based on 'steps' retrieved from google maps GDirection. These steps vary in length and i use the coordinates at the beginning of each "step". However, sometimes the distance of these steps is too long(ex. driving 30-40 km. on the freeway). Therefore i would like to calculate/find the coordinate located in between two given coordinates. Lets say one step starts at: 56.043185,9.922714 and ends at: 56.234287,9.864521 I would then like to calculate the point right in the middle of these coordinates. I use the haversine form to calculate the distance between coordinates, but im not sure whether or not this can be used for the same purpose. http://www.mpi.nl/world/persons/private ... versine.py I apologize if this thread has been posted the wrong place:) any help is greatly appreciated! kind regards. Pete From ebonak at hotmail.com Thu Aug 13 17:31:55 2009 From: ebonak at hotmail.com (Esmail) Date: Thu, 13 Aug 2009 17:31:55 -0400 Subject: Plotting Quadratic Functions, pygame In-Reply-To: References: Message-ID: Hello Senad, You might find this style guide useful too in your toolbox of Python skills & tricks. http://www.python.org/dev/peps/pep-0008/ This is a great and helpful group of people here, we are lucky to have access to groups like this. Best, Esmail From ebonak at hotmail.com Thu Aug 13 17:32:34 2009 From: ebonak at hotmail.com (Esmail) Date: Thu, 13 Aug 2009 17:32:34 -0400 Subject: get output of du / ls command - currently ugly code ... In-Reply-To: <1250194589.19760.4.camel@brotherus.corp.redhat.com> References: <1250194589.19760.4.camel@brotherus.corp.redhat.com> Message-ID: Albert Hopkins wrote: > > I don't know about "easier", but a more elegant way is to not use > os.popen() and to use Python's functions os.path.getsize (or os.stat) > and os.walk (or os.path.walk) to achieve this. > > In fact if you look at the docstring for os.walk there is an example > that almost does what you're doing with du, but is cross-platform and > not dependent on shelling a process and scraping its stdout. Thanks Albert, I'll take a look, Esmail From jura.grozni at gmail.com Thu Aug 13 18:00:19 2009 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Aug 2009 15:00:19 -0700 (PDT) Subject: i Don't get why it makes trouble References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: On 13 kol, 22:09, Philip Semanchuk wrote: > On Aug 13, 2009, at 2:56 PM, azrael wrote: > > >>>> j > > [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] > >>>> len(j) > > 5 > >>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, ? > >>>> d.id_drzava, v.id_valuta FROM ? ulica as u, opcina as o, zupanija ? > >>>> as z, drzava as d, valuta as v ?WHERE ?u.naziv = '%s' AND o.naziv ? > >>>> = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = ? > >>>> '%s'""" % (j) > > Traceback (most recent call last): > > ?File "", line 1, in > > TypeError: not enough arguments for format string > > Hi azrael, > You already have an answer to your question so I won't address that. I ? > want to point out that this is a dangerous way to build SQL statements. > > For instance, what happens if someone enters a city name of L'viv? ? > Your SQL will break due to mismatched single quotes. This kind of code ? > is vulnerable to SQL injection attacks:http://en.wikipedia.org/wiki/SQL_injection > > Parameterized SQL is safer. Googling for 'parameterized SQL Python' ? > should find some examples for you. > > Good luck > Philip I know Already. This is sopussed to be a small office application connecting on a LAN mysql server with no web connection. Thank you anyway From goldtech at worldpost.com Thu Aug 13 18:04:35 2009 From: goldtech at worldpost.com (goldtech) Date: Thu, 13 Aug 2009 15:04:35 -0700 (PDT) Subject: Idle text wrap Message-ID: <4e59f80c-e812-4273-9ebf-2c711ae35663@b25g2000prb.googlegroups.com> Hi, I'm using Idle interactive shell. Actually Idle-Spoon which has a few nice extensions and Python 2.6 on Linux. When I print str_value + "\n" Where str_value is for example a string of 120 chars. I notice that the lines seem to get hard wrapped at around 80. Is there a way I can config it to either wrap to the window, or for a higher amount before wrapping? Thanks. From philip at semanchuk.com Thu Aug 13 18:14:02 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 13 Aug 2009 18:14:02 -0400 Subject: i Don't get why it makes trouble In-Reply-To: References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: <59821D8E-7130-421E-84E4-72B55E339702@semanchuk.com> On Aug 13, 2009, at 6:00 PM, azrael wrote: > On 13 kol, 22:09, Philip Semanchuk wrote: >> On Aug 13, 2009, at 2:56 PM, azrael wrote: >> >>>>>> j >>> [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] >>>>>> len(j) >>> 5 >>>>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, >>>>>> d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija >>>>>> as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv >>>>>> = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = >>>>>> '%s'""" % (j) >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: not enough arguments for format string >> >> Hi azrael, >> You already have an answer to your question so I won't address >> that. I >> want to point out that this is a dangerous way to build SQL >> statements. >> >> For instance, what happens if someone enters a city name of L'viv? >> Your SQL will break due to mismatched single quotes. This kind of >> code >> is vulnerable to SQL injection attacks:http://en.wikipedia.org/wiki/SQL_injection >> >> Parameterized SQL is safer. Googling for 'parameterized SQL Python' >> should find some examples for you. >> >> Good luck >> Philip > > I know Already. This is sopussed to be a small office application > connecting on a LAN mysql server with no web connection. Thank you > anyway You're welcome. I'm glad you are aware. You're ahead of a lot of developers out there. I encourage you to at least think about using parameterized SQL anyway because you never know when someone (maybe even you!) will copy & paste your code, or use your library without realizing that it was "internal use only". It's usually just as easy as building SQL strings anyway. And besides, what about L'viv? =) Good luck with whatever choice you make Philip From david.mcwright at usbfmi.com Thu Aug 13 18:17:56 2009 From: david.mcwright at usbfmi.com (dippim) Date: Thu, 13 Aug 2009 15:17:56 -0700 (PDT) Subject: implementing descriptors Message-ID: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> I am new to Python and I have a question about descriptors. If I have a class as written below, is there a way to use descriptors to be certain that the datetime in start is always before the one in end? class foo(object): def __init__(self,a = None,b = None) self.start = a self.end = b from datetime import datetime c = datetime(2009,8,13,6,15,0) d = datetime(2009,8,14,12,0,0) afoo = foo(c,d) For instance, if the following code were run, I would like to instance of foo to switch the start and end times. afoo.start = datetime(2010,8,13,6,15,0) I was thinking of using the __set__ descriptor to catch the assignment and reverse the values if necessary, but I can't figure out how to determine which values is being set. Thanks for the help! David From davigier at googlemail.com Thu Aug 13 18:52:52 2009 From: davigier at googlemail.com (David) Date: Thu, 13 Aug 2009 15:52:52 -0700 (PDT) Subject: How to launch a function at regular time intervals ? References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> Message-ID: <18ac9f9a-0cf2-409c-82b3-ea068f21dbf7@k19g2000yqn.googlegroups.com> On 13 ao?t, 21:28, Dave Angel wrote: > David wrote: > > Thanks all for your answers. As suggested by Dave and Frank, I am > > indeed looking for the main program to continue running in the > > background (I have several functions I want to launch, each at a > > predefined time interval). I like Frank's solution, on the paper it > > seems it would do what I am looking for, but I cannot succeed in > > having it working. I guess I've been stuck with this problem for too > > long and can't succeed in using my brain accurately anymore... ;-) > > > I defined the class as defined by Frank, and I then inserted the > > following code in a While True loop, without any other code (the idea > > is just to test Frank's solution before really using it in my > > program): > > > ? ? func = MyFunction() > > ? ? func.start() > > > ? ? func.stop() > > ? ? func.join() > > > However I'm not getting the expected behavior. It's not taking into > > account the 30 sec wait, the function is called again and again > > without any time interval... Any idea ? > > > Again, thanks a lot. > > Why don't you include the code you're actually trying, instead of just > trying to describe it. ?Frank's class didn't call any function, it just > had a place to do it. ?So we really don't know what you're running, nor > what about it is wrong. > > Perhaps a few well placed print statements? > > DaveA Yes, I guess it would be more simple. Here is really what I am trying to do. I simplified the functions, but the purpose is to write some text in a local file every x seconds (here, I'm just writing the timestamp, i.e. a string representing the date & time, every 10 seconds) and to transfer this file to a distant server via FTP every y seconds (20 seconds in the example below). My code is a little bit more complicated because each time I transfer the file, I delete the local file which is then recreated when data is written, but for simplicity I left this out in the code below. So, here is the code I've been using to test Frank's code. I've been struggling with using or not a While True loop or not, and everything I try seems to run into issues. import threading from datetime import datetime import ftplib class CFtpConnection: """FTP Connection parameters""" def __init__(self, host, port, timeout, user, passwd): self.host = "" self.port = 21 self.timeout = 60 self.user = "" self.passwd = "" class CStoreData(threading.Thread): """Write timestamp in a file every 10 seconds in separate thread""" def __init__(self, timestamp): threading.Thread.__init__(self) self.event = threading.Event() self.timestamp = timestamp def run(self): while not self.event.is_set(): file_handler = open("Test.txt", 'a') file_handler.write(self.timestamp.strftime("%y%m%d%H%M%S \n")) file_handler.close() self.event.wait(10) def stop(self): self.event.set() class CTransferData(threading.Thread): """Transfer timestamp file every 20 seconds in separate thread""" def __init__(self, ftp_connection): threading.Thread.__init__(self) self.event = threading.Event() self.ftp_connection = ftp_connection def run(self): while not self.event.is_set(): file_handler = open("Test.txt", 'r') Ftp_handler = ftplib.FTP('') Ftp_handler.connect(self.ftp_connection.host, self.ftp_connection.port, self.ftp_connection.timeout) Ftp_handler.login(self.ftp_connection.user, self.ftp_connection.passwd) Ftp_handler.storbinary("STOR Test.txt", file_handler) file_handler.close() Ftp_handler.close() self.event.wait(20) def stop(self): self.event.set() ftp_connection = CFtpConnection("", 21, 60, "", "") ftp_connection.host = '127.0.0.1' ftp_connection.user = "admin" ftp_connection.passwd = "admin" while(1): timestamp = datetime.now() func_store_data = CStoreData(timestamp) func_store_data.start() func_transfer_data = CTransferData(ftp_connection) func_transfer_data.start() func_store_data.stop() func_store_data.join() func_transfer_data.stop() func_transfer_data.join() From breamoreboy at yahoo.co.uk Thu Aug 13 19:19:29 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 14 Aug 2009 00:19:29 +0100 Subject: implementing descriptors In-Reply-To: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: dippim wrote: > I am new to Python and I have a question about descriptors. If I have > a class as written below, is there a way to use descriptors to be > certain that the datetime in start is always before the one in end? > > class foo(object): > def __init__(self,a = None,b = None) > self.start = a > self.end = b > > from datetime import datetime > c = datetime(2009,8,13,6,15,0) > d = datetime(2009,8,14,12,0,0) > afoo = foo(c,d) > > For instance, if the following code were run, I would like to instance > of foo to switch the start and end times. > > afoo.start = datetime(2010,8,13,6,15,0) > > I was thinking of using the __set__ descriptor to catch the assignment > and reverse the values if necessary, but I can't figure out how to > determine which values is being set. > > Thanks for the help! > > David Take a look at the example given here. http://users.rcn.com/python/download/Descriptor.htm -- Kindest regards. Mark Lawrence. From mdekauwe at gmail.com Thu Aug 13 19:38:07 2009 From: mdekauwe at gmail.com (Martin) Date: Thu, 13 Aug 2009 16:38:07 -0700 (PDT) Subject: PIL and Python References: Message-ID: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> On Aug 13, 1:55?pm, "catalinf... at gmail.com" wrote: > Hello ! > I want use python to change the "note" from .jpeg files . > What is the functions on PIL how make this ? > Thank you ! What do u mean by the note? From emile at fenx.com Thu Aug 13 19:57:21 2009 From: emile at fenx.com (Emile van Sebille) Date: Thu, 13 Aug 2009 16:57:21 -0700 Subject: implementing descriptors In-Reply-To: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: On 8/13/2009 3:17 PM dippim said... > I am new to Python and I have a question about descriptors. If I have > a class as written below, is there a way to use descriptors to be > certain that the datetime in start is always before the one in end? > > class foo(object): > def __init__(self,a = None,b = None) > self.start = a > self.end = b > > from datetime import datetime > c = datetime(2009,8,13,6,15,0) > d = datetime(2009,8,14,12,0,0) > afoo = foo(c,d) > > For instance, if the following code were run, I would like to instance > of foo to switch the start and end times. > > afoo.start = datetime(2010,8,13,6,15,0) > > I was thinking of using the __set__ descriptor to catch the assignment > and reverse the values if necessary, why not... class foo(object): def __init__(self,a = None,b = None) self.start = min(a,b) self.end = max(a,b) Emile From davea at ieee.org Thu Aug 13 20:06:56 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 20:06:56 -0400 Subject: need help calculating point between two coordinates. In-Reply-To: <2d059a29-933e-4e2c-8730-f1f2688af26c@24g2000yqm.googlegroups.com> References: <2d059a29-933e-4e2c-8730-f1f2688af26c@24g2000yqm.googlegroups.com> Message-ID: <4A84AAA0.6060105@ieee.org> PeteDK wrote: > Hi there > > I'am working on a route comparison tool for carpools. > > The route comparison is based on 'steps' retrieved from google maps > GDirection. These steps vary in length and i use the coordinates at > the beginning of each "step". However, sometimes the distance of these > steps is too long(ex. driving 30-40 km. on the freeway). Therefore i > would like to calculate/find the coordinate located in between two > given coordinates. > Lets say one step starts at: > 56.043185,9.922714 > and ends at: > 56.234287,9.864521 > > I would then like to calculate the point right in the middle of these > coordinates. > > I use the haversine form to calculate the distance between > coordinates, but im not sure whether or not this can be used for the > same purpose. > http://www.mpi.nl/world/persons/private ... versine.py > > I apologize if this thread has been posted the wrong place:) > > any help is greatly appreciated! > > kind regards. > > Pete > > For the distances you're talking about, those coordinates are very close to linear. So to find the midpoint, just average the coordinates. You might be off by half a km, but roads bend more than that. DaveA From goldtech at worldpost.com Thu Aug 13 20:36:59 2009 From: goldtech at worldpost.com (goldtech) Date: Thu, 13 Aug 2009 17:36:59 -0700 (PDT) Subject: Python "and" behavior Message-ID: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> Could you explain or link me to an explanation of this? Been using Python for a while but not sure I understand what's happening below. Thanks. >>> ss=1 and "fffff" >>> ss 'fffff' >>> ss=0 and "fffff" >>> ss 0 >>> From gherron at islandtraining.com Thu Aug 13 20:50:42 2009 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 13 Aug 2009 17:50:42 -0700 Subject: Python "and" behavior In-Reply-To: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> Message-ID: <4A84B4E2.9080300@islandtraining.com> goldtech wrote: > Could you explain or link me to an explanation of this? Been using > Python for a while but not sure I understand what's happening below. > Thanks. > > > >>>> ss=1 and "fffff" >>>> ss >>>> > 'fffff' > >>>> ss=0 and "fffff" >>>> ss >>>> > 0 > Python's Boolean operators don't turn arbitrary values into True and False values. If you use it in any conditional, you'll get the same result as if it did, but it is occasionally it's nice to get the actual values used in the "and" instead of having the value distilled down to a True/False. From the Python manual: These are the Boolean operations, ordered by ascending priority: Operation Result Notes |x or y| if x is false, then y, else x (1) |x and y| if x is false, then x, else y (1) |not x| if x is false, then |True|, else |False| (2) Notes: *(1)* These only evaluate their second argument if needed for their outcome. *(2)* "not" has a lower priority than non-Boolean operators, so |not a == b| is interpreted as |not (a == b)|, and |a == not b| is a syntax error. ------------------------------------------------------------------------ -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Thu Aug 13 20:52:40 2009 From: mensanator at aol.com (Mensanator) Date: Thu, 13 Aug 2009 17:52:40 -0700 (PDT) Subject: Python "and" behavior References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> Message-ID: <44940d04-6378-4a32-b470-d4709aab1ada@b14g2000yqd.googlegroups.com> On Aug 13, 7:36?pm, goldtech wrote: > Could you explain or link me to an explanation of this? Been using > Python for a while but not sure I understand what's happening below. > Thanks. > > > > > > >>> ss=1 and "fffff" > >>> ss > 'fffff' > >>> ss=0 and "fffff" > >>> ss > 0 Does this help? >>> ss = True and 'fffff' >>> ss 'fffff' >>> ss = False and 'eeeee' >>> ss False From apt.shansen at gmail.com Thu Aug 13 21:02:38 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Thu, 13 Aug 2009 18:02:38 -0700 Subject: Python "and" behavior In-Reply-To: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> Message-ID: <7a9c25c20908131802v2295b18ev12af2ac830c24669@mail.gmail.com> > > Could you explain or link me to an explanation of this? Been using > Python for a while but not sure I understand what's happening below. > Thanks. > > >>> ss=1 and "fffff" > >>> ss > 'fffff' > >>> ss=0 and "fffff" > >>> ss > 0 > >>> The "and" and "or" operators in Python are actually not true boolean operators: they operate on the more fundamental interpretation of Truth that Python uses (and that 'if' for example uses) that goes back before Python got actual boolean True/False values. "x and y" evaluates first x; if it is false, its value is returned. Otherwise, the value of y is returned. "x or y" evaluates first x; if it is true, its value is returned. Otherwise, the value of y is returned. Python's idea of "true" verses "false" isn't the same as True and False. It's been described as "something" verses "nothing", as in Python the following are considered false: False, None, numeric 0 (in all types of numbers), empty strings, empty containers (lists, tuples, dictionaries, sets). Everything else is True. Instances of any class are True by default, but they can have a __nonzero__ operation on them to override that. So, every value has an innate 'truthfulness' about it: the 'if' statement bases its decision on that truthfulness. In the context of truthfulness, the string "hello" is just as true as the singleton True. So, if you do "x and y", if 'x' is a false value... then 'x' is returned-- as 'x' is just as false as the singleton False. Both are different ways of saying 'false' in logical operations. Lots of people don't like this. Lots of people do. Some people want it to be pure-true boolean algebra, have them return True/False always-- some people have even argued for "if" only branching on True/False values. The fact of the matter is, this is all just a fundamental part of Python that pre-dates it ever having true boolean values, and is never gonna go away. There's some useful properties to it, like: value = opt or "default" In this case, if opt was set to a something, it'll end up in value. Otherwise, "default" will. Of course that's only useful where a opt would never have a blank string or 0 or such in it naturally. The poor-man's ternary operator was commonly used before Python got a proper one: value = x and "Yes" or "No" The construct had some limits(namely, the value in the "Yes" part of the expression must be truthy), but is still useful in a lot of situations. If "x" would evaluate true, then value would be set to "Yes". Otherwise, it'd be set to "No". HTH, --Stephen -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Thu Aug 13 21:09:09 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 02:09:09 +0100 Subject: Python "and" behavior In-Reply-To: <4A84B4E2.9080300@islandtraining.com> References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> <4A84B4E2.9080300@islandtraining.com> Message-ID: <4A84B935.8080809@mrabarnett.plus.com> Gary Herron wrote: > goldtech wrote: >> Could you explain or link me to an explanation of this? Been using >> Python for a while but not sure I understand what's happening below. >> Thanks. >> >> >> >>>>> ss=1 and "fffff" >>>>> ss >>>>> >> 'fffff' >> >>>>> ss=0 and "fffff" >>>>> ss >>>>> >> 0 >> > > Python's Boolean operators don't turn arbitrary values into True and > False values. If you use it in any conditional, you'll get the same > result as if it did, but it is occasionally it's nice to get the actual > values used in the "and" instead of having the value distilled down to a > True/False. > > > >From the Python manual: > > These are the Boolean operations, ordered by ascending priority: > > Operation Result Notes > |x or y| if x is false, then y, else x (1) > |x and y| if x is false, then x, else y (1) > |not x| if x is false, then |True|, else |False| (2) > The Pythonic table would be: Operation Result |x or y| x if x else y |x and y| y if x else x |not x| False if x else False :-) From arphaksad at gmail.com Thu Aug 13 21:21:39 2009 From: arphaksad at gmail.com (naaman) Date: Thu, 13 Aug 2009 18:21:39 -0700 (PDT) Subject: fileinput References: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> Message-ID: <31f257a9-8949-47d7-a0ae-0b4ab7822eb6@q23g2000yqn.googlegroups.com> On Aug 13, 7:50?am, Dave Angel wrote: > naaman wrote: > > On Aug 12, 1:35 pm, Dave Angel wrote: > > >> naaman wrote: > > >>> I'm writing my first Python script and > >>> I want to use fileinput to open a file in r+ mode. > >>> Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > >>> ANy ideas? > > >>> Need to find and overwrite a line in a file several times. > >>> I can do it using open and seek() etc. but was wondering if I can use > >>> fileinput. > > >>> thanks; > > >> I haven't used it, but check out the 'inplace' keyword parameter. > > >> DaveA > > > I've only Python for a week so I'm not sure what inplace does > > You should read the docs for it > ? ? (http://www.python.org/doc/2.6.2/library/fileinput.html?), > but it's not very clear to me either ?So I dug up an example on the web: > ? ? ?(ref: ?http://effbot.org/librarybook/fileinput.htm) > > import fileinput, sys > > for line in fileinput.input(inplace=1): > ? ? # /convert Windows/DOS text files to Unix files/ > ? ? if line[-2:] == "\r\n": > ? ? ? ? line = line[:-2] + "\n" > ? ? sys.stdout.write(line) > > The inplace argument tells it to create a new file with the same name as > the original (doing all the necessary nonsense with using a scratch > file, and renaming/deleting) for each file processed. ?Stdout is pointed > to that new version of the file. ?Notice that you have to explicitly > write everything you want to wind up in the file -- if a given line is > to remain unchanged, you just write "line" directly. > > If you're new to Python, I do not recommend trying to do open/seek to > update a text file in place, especially if you're in DOS. ?There are > lots of traps. ?the inplace method of fileinput avoids these by > implicitly creating temp files and handling the details for you, which > probably works great if you're dealing with text, in order. > > DaveA Thanks Dave. I'll check that out From xahlee at gmail.com Thu Aug 13 21:36:04 2009 From: xahlee at gmail.com (Xah Lee) Date: Thu, 13 Aug 2009 18:36:04 -0700 (PDT) Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode Message-ID: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> ? A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode http://xahlee.org/UnixResource_dir/writ/emacs_whitespace-mode_problems.html plane text version follows: -------------------------------------------------- A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode Xah Lee, 2009-08-13 Just wanted to express some frustration with whitespace-mode. Emacs 23, just released, has this whitespace-mode feature. It renders spaces, tabs, newlines characters with a visible glyph. This feature, is in Microsoft Word since about 1992. This feature is important in practical ways. For example, when you work with ?tab separated line? files (CSV) that's a common format for importing/exporting address books or spreadsheets. It's also important in whitespace-significant langs such as Python. Or, in text processing when placement of space and tabs matters in the output. All i wanted, is to make Space and Tab and Newline chars visible. However, the emacs whitespace-mode does much more than that. It is designed for tech geeking control freaks to tune every aspect of white space in his source code. The mode is filled with bells and whistles. It distinguishes tabs mixed with spaces, EOLs mixed with spaces, EOLs at beginning of file, EOLs at end of file, run on spaces at end of line, lines that has nothing to do with white spaces but is simply longer than 80 chars, etc. Each of these is rendered with different foreground, background, colors, so that they cannot possibly escape the notices of control freaks. By default, most of these are on, so that, when you turn on the mode, most reasonable clean source code become this colorful rainbow unreadable fuck. I tried to tune it, with my 10 years of emacs of fucking 16 hours of using per day, and 3 years of elisp coding experience. But, after a hour, it's confusion hell sans avail. O, that Alex idiot with his emacswiki, refused to lead emacswiki into any readable state. All he can think about is my social skills. (See: Problems of Emacswiki.) What the fuck motherfuck. Hi tech geekers, coding freaks, social science ignoramus fucks, basic economics illiterate FSF fucks, freedom abusing selfish ideologists fucks, Richard Stallman propagandist fuck, we-try-to-be-easy-to-use linuxer idioting fucks, FUCK U. Xah ? http://xahlee.org/ ? From timinganalyzer at gmail.com Thu Aug 13 21:43:27 2009 From: timinganalyzer at gmail.com (timinganalyzer) Date: Thu, 13 Aug 2009 18:43:27 -0700 (PDT) Subject: new version TimingAnalyzer Message-ID: <55314c4f-24e0-4c2c-8016-3d004b622d21@j9g2000vbp.googlegroups.com> Hi All, 1.Added a new User Delay and Constraint Editor panel. You can add, delete, or update User Delays or Constraints. 2 .These User Delays and User Constraints are saved at the top of the .tim file. 3.Changing a User Delay or User Constraint updates every one of the same type in the diagram. 4.Files created with previous versions are converted to this new format when saved. 5.Added Python Interpreter, Jython 2.5. Now you can write scripts in Python. 6.Execute Python scripts using the same script dialog for the beanshell scripts or from Jython command line window. 7.Included start_app.py script in the install directory that will start the TimingAnalyzer from a Jython command line window. 8.Updated spice_pwl.bsh. This beanshell script generates spice piece wise linear test vectors for DigitalBus. 9.Included dff.py. This Python script shows how to generate a timing diagram for a D Flip Flop. Anyone interested in helping convert the Java scripts (in the scripts dir) to Python should let me know. Dan Fabrizio www.timing-diagrams.com From jura.grozni at gmail.com Thu Aug 13 21:51:10 2009 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Aug 2009 18:51:10 -0700 (PDT) Subject: i Don't get why it makes trouble References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: On 14 kol, 00:14, Philip Semanchuk wrote: > On Aug 13, 2009, at 6:00 PM, azrael wrote: > > > > > > > On 13 kol, 22:09, Philip Semanchuk wrote: > >> On Aug 13, 2009, at 2:56 PM, azrael wrote: > > >>>>>> j > >>> [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] > >>>>>> len(j) > >>> 5 > >>>>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, > >>>>>> d.id_drzava, v.id_valuta FROM ? ulica as u, opcina as o, zupanija > >>>>>> as z, drzava as d, valuta as v ?WHERE ?u.naziv = '%s' AND o.naziv > >>>>>> = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = > >>>>>> '%s'""" % (j) > >>> Traceback (most recent call last): > >>> ?File "", line 1, in > >>> TypeError: not enough arguments for format string > > >> Hi azrael, > >> You already have an answer to your question so I won't address ? > >> that. I > >> want to point out that this is a dangerous way to build SQL ? > >> statements. > > >> For instance, what happens if someone enters a city name of L'viv? > >> Your SQL will break due to mismatched single quotes. This kind of ? > >> code > >> is vulnerable to SQL injection attacks:http://en.wikipedia.org/wiki/SQL_injection > > >> Parameterized SQL is safer. Googling for 'parameterized SQL Python' > >> should find some examples for you. > > >> Good luck > >> Philip > > > I know Already. This is sopussed to be a small office application > > connecting on a LAN mysql server with no web connection. Thank you > > anyway > > You're welcome. I'm glad you are aware. You're ahead of a lot of ? > developers out there. > > I encourage you to at least think about using parameterized SQL anyway ? > because you never know when someone (maybe even you!) will copy & ? > paste your code, or use your library without realizing that it was ? > "internal use only". It's usually just as easy as building SQL strings ? > anyway. > > And besides, what about L'viv? =) > > Good luck with whatever choice you make > Philip Currently I am working on just a prototype to show what is possible to be done to get me some fundings for my future work. after that I will get over to an SQL Alchemy. It's ORM will take over this business for me. A lot of people a not aware of SQL injection. My friend from college asked me and a couple of other guys for Pen testing of an website. His SQL injection mistake made him an epic fail. Thanks From clp2 at rebertia.com Thu Aug 13 22:20:18 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 13 Aug 2009 22:20:18 -0400 Subject: csv.DictWriter.write_header() In-Reply-To: References: Message-ID: <50697b2c0908131920r14862573j6bdbfc7a486d5b26@mail.gmail.com> On Wed, Aug 12, 2009 at 4:45 PM, Alan G Isaac wrote: > Given a csv.DictWriter instance `dw` > I think it would be nice to be able to > say dw.write_header() > instead of > dw.writer.writerow(dw.fieldnames) > > Good idea? Maybe. You could file a bug: http://bugs.python.org/ Cheers, Chris -- http://blog.rebertia.com From akonsu at gmail.com Thu Aug 13 22:32:03 2009 From: akonsu at gmail.com (akonsu) Date: Thu, 13 Aug 2009 19:32:03 -0700 (PDT) Subject: something like perl's Mail::GPG ? Message-ID: <4365602b-e174-4419-a1f7-44dde1b66b0c@w41g2000yqb.googlegroups.com> hello, i am looking for a module with functionality similar to that of the Perl's Mail::GPG package. I need to verify multipart emails that are PGP-signed. thanks for any advice konstantin From arphaksad at gmail.com Thu Aug 13 22:33:32 2009 From: arphaksad at gmail.com (naaman) Date: Thu, 13 Aug 2009 19:33:32 -0700 (PDT) Subject: fileinput References: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> Message-ID: <5d11458b-322d-4851-98a8-13c4cee4f5aa@o13g2000vbl.googlegroups.com> On Aug 13, 7:50?am, Dave Angel wrote: > naaman wrote: > > On Aug 12, 1:35 pm, Dave Angel wrote: > > >> naaman wrote: > > >>> I'm writing my first Python script and > >>> I want to use fileinput to open a file in r+ mode. > >>> Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > >>> ANy ideas? > > >>> Need to find and overwrite a line in a file several times. > >>> I can do it using open and seek() etc. but was wondering if I can use > >>> fileinput. > > >>> thanks; > > >> I haven't used it, but check out the 'inplace' keyword parameter. > > >> DaveA > > > I've only Python for a week so I'm not sure what inplace does > > You should read the docs for it > ? ? (http://www.python.org/doc/2.6.2/library/fileinput.html?), > but it's not very clear to me either ?So I dug up an example on the web: > ? ? ?(ref: ?http://effbot.org/librarybook/fileinput.htm) > > import fileinput, sys > > for line in fileinput.input(inplace=1): > ? ? # /convert Windows/DOS text files to Unix files/ > ? ? if line[-2:] == "\r\n": > ? ? ? ? line = line[:-2] + "\n" > ? ? sys.stdout.write(line) > > The inplace argument tells it to create a new file with the same name as > the original (doing all the necessary nonsense with using a scratch > file, and renaming/deleting) for each file processed. ?Stdout is pointed > to that new version of the file. ?Notice that you have to explicitly > write everything you want to wind up in the file -- if a given line is > to remain unchanged, you just write "line" directly. > > If you're new to Python, I do not recommend trying to do open/seek to > update a text file in place, especially if you're in DOS. ?There are > lots of traps. ?the inplace method of fileinput avoids these by > implicitly creating temp files and handling the details for you, which > probably works great if you're dealing with text, in order. > > DaveA I wonder if inline creates an empty file and then the text from the processed file gets written to it. If that's what is going on then it's perfect solution. It will eliminate all the tell() and seek() and overwriting a shorter line with a longer one. I'll try it over the weekend. thanks From gagsl-py2 at yahoo.com.ar Thu Aug 13 23:15:14 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Aug 2009 00:15:14 -0300 Subject: Delegate attribute requests to object References: <1a78d23f0908130850v3f013b37rd1a7bce23041eedc@mail.gmail.com> <1a78d23f0908131013x25feee2fwe6b907045e87b6f5@mail.gmail.com> <1a78d23f0908131100p75520be4oe7572aae00bf2f13@mail.gmail.com> Message-ID: En Thu, 13 Aug 2009 12:50:47 -0300, Evan Kroske escribi?: > I'm trying to use the decorator pattern in a program I'm developing. I > want > to create a decorator object that works like the object it's decorating > except for a few functions. However, I'd rather not hard-code all the > identical functionality from the decorated object into the decorator > object. > Is there a way I can intercept all the attribute and function requests > for > the decorator and delegate them to the decorated object? You may search the list archives for references to "proxy" and "delegation". The term "decorator" has a very specific meaning in Python (as a syntax construct), don't use it in the search. > Is it possible (without inheritance)? Yes, using delegation. See below. En Thu, 13 Aug 2009 15:29:04 -0300, Rami Chowdhury escribi?: > Oops, my apologies, it's the __getattribute__ method you want to call on > self.decorated (because __getattr__ won't be there unless you define it > specifically) > So it should go: > > def __getattr__(self, request): > return self.decorated.__getattribute__(request) __getattribute__ doesn't exist on old-style classes either. Also, note that very rarely one has to *call* __special__ methods; the code should read: def __getattr__(self, request): return getattr(self.decorated, request) but that works *only* for old-style classes, as discussed here [1]. [3] is another approach for new-style classes (maybe not production-ready yet). And this recipe [2] shows how to make the decorated object keep calling methods on the decorator itself. [1] http://code.activestate.com/recipes/252151/ [2] http://code.activestate.com/recipes/519639/ [3] http://code.activestate.com/recipes/496741/ -- Gabriel Genellina From nirvana117 at gmail.com Thu Aug 13 23:16:18 2009 From: nirvana117 at gmail.com (dou dou) Date: Fri, 14 Aug 2009 11:16:18 +0800 Subject: problem with interface of operator.itemgetter Message-ID: <19b355330908132016y49f2679u631c3123fcfc920a@mail.gmail.com> I have a function to do some thing like LEFT JOIN in SQL, the function use the itemgetter to get the "ON" and "SELECT" parameters of the two table(list of list), the problem is that itemgetter may return a value or a tuple of values, because of the inconsistent return type of itemgetter, I have to do 2^3 IF check, the function like this: def left_join(table1, on_index1, table2, on_index2, getter1, getter2): """do thing like: SELECT on1(table1), g1(table1), g2(table2) FROM table1 LEFT JOIN table2 ON on1(table1) == on2(table2) """ on1 = itemgetter(*on_index1) on2 = itemgetter(*on_index2) g1 = itemgetter(*getter1) g2 = itemgetter(*getter2) d2 = {} d2 = dict((on2(r2), r2) for r2 in table2) #if itemgetter always return tuple, below could simple as one line #return [ list(on1(r1) + g1(r1) + g2(d2.get(on1(r1)))) for r1 in table1 ] len_on = len(on_index1) len_g1 = len(getter1) len_g2 = len(getter2) if len_on == 1: if len_g1 == 1 and len_g2 == 1: return [ [on1(r1), g1(r1), g2(d2.get(on1(r1)))] for r1 in table1 ] elif len_g1 == 1 and len_g2 > 1: return [ list((on1(r1),g1(r1))+g2(d2.get(on1(r1)))) for r1 in table1 ] elif len_g1 > 1 and len_g2 == 1: return [ list((on1(r1),)+g1(r1)+(g2(d2.get(on1(r1))),)) for r1 in table1 ] else: #len_g1 > 1 and len_g2 > 1: return [ list((on1(r1),)+g1(r1)+g2(d2.get(on1(r1)))) for r1 in table1 ] else: # len_on > 1 if len_g1 == 1 and len_g2 == 1: return [ list(on1(r1))+[g1(r1),g2(d2.get(on1(r1)))] for r1 in table1 ] elif len_g1 == 1 and len_g2 > 1: return [ list(on1(r1)+(g1(r1),)+g2(d2.get(on1(r1)))) for r1 in table1 ] elif len_g1 > 1 and len_g2 == 1: return [ list(on1(r1)+g1(r1)+(g2(d2.get(on1(r1))),)) for r1 in table1 ] else: #len_g1 > 1 and len_g2 > 1: return [ list(on1(r1)+g1(r1)+g2(d2.get(on1(r1)))) for r1 in table1 ] so is there a way to force itemgetter to return tuple even when itemgetter(only_have_one_argument)? or some other function to do this? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From arphaksad at gmail.com Thu Aug 13 23:25:02 2009 From: arphaksad at gmail.com (naaman) Date: Thu, 13 Aug 2009 20:25:02 -0700 (PDT) Subject: fileinput References: Message-ID: <88cecdd5-4a7f-40ee-ad2d-1b481d5db03d@g1g2000vbr.googlegroups.com> On Aug 13, 1:20?am, "Gabriel Genellina" wrote: > En Wed, 12 Aug 2009 01:27:47 -0300, naaman escribi?: > > > I'm writing my first Python script and > > I want to use fileinput to open a file in r+ mode. > > Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > > ANy ideas? > > Don't use fileinput, it can't handle r+, only sequencial access. > Even if you could use it, the documentation says [1]: > fileinput.input([files[, inplace[, backup[, mode[, openhook]]]]]) > > "r+" corresponds to the `inplace` parameter (behaving like inplace=True) ? > instead of `mode`. You could write fileinput.input(sys.argv[1:], ? > mode="r+") instead - but again from the docs: "mode... must be one of 'r', ? > 'rU', 'U' and 'rb'" > > > Need to find and overwrite a line in a file several times. > > I can do it using open and seek() etc. but was wondering if I can use > > fileinput. > > open+seek is the way to do that (assuming you don't alter the line length) > > [1]http://docs.python.org/library/fileinput.html#fileinput.input > > -- > Gabriel Genellina unfortunately, I am overwriting shorter with longer From arphaksad at gmail.com Thu Aug 13 23:41:41 2009 From: arphaksad at gmail.com (naaman) Date: Thu, 13 Aug 2009 20:41:41 -0700 (PDT) Subject: fileinput References: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> Message-ID: On Aug 13, 7:50?am, Dave Angel wrote: > naaman wrote: > > On Aug 12, 1:35 pm, Dave Angel wrote: > > >> naaman wrote: > > >>> I'm writing my first Python script and > >>> I want to use fileinput to open a file in r+ mode. > >>> Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > >>> ANy ideas? > > >>> Need to find and overwrite a line in a file several times. > >>> I can do it using open and seek() etc. but was wondering if I can use > >>> fileinput. > > >>> thanks; > > >> I haven't used it, but check out the 'inplace' keyword parameter. > > >> DaveA > > > I've only Python for a week so I'm not sure what inplace does > > You should read the docs for it > ? ? (http://www.python.org/doc/2.6.2/library/fileinput.html?), > but it's not very clear to me either ?So I dug up an example on the web: > ? ? ?(ref: ?http://effbot.org/librarybook/fileinput.htm) > > import fileinput, sys > > for line in fileinput.input(inplace=1): > ? ? # /convert Windows/DOS text files to Unix files/ > ? ? if line[-2:] == "\r\n": > ? ? ? ? line = line[:-2] + "\n" > ? ? sys.stdout.write(line) > > The inplace argument tells it to create a new file with the same name as > the original (doing all the necessary nonsense with using a scratch > file, and renaming/deleting) for each file processed. ?Stdout is pointed > to that new version of the file. ?Notice that you have to explicitly > write everything you want to wind up in the file -- if a given line is > to remain unchanged, you just write "line" directly. > > If you're new to Python, I do not recommend trying to do open/seek to > update a text file in place, especially if you're in DOS. ?There are > lots of traps. ?the inplace method of fileinput avoids these by > implicitly creating temp files and handling the details for you, which > probably works great if you're dealing with text, in order. > > DaveA here's the solution import fileinput, sys for line in fileinput.input(sys.argv[1],inplace=1): if (line[:-1]==r'drew'): line=line.replace(line,"fancy dog") sys.stdout.write(line) I want to replace drew in my input file with fancy dog. Tested with this input file angel heaven flying monkees lazy dogs drew blue sky veritas and got this angel heaven flying monkees lazy dogs fancy dog blue sky veritas So drew was replaced with fancy dog. Thanks to your inputs I got this solved. :-)) From Scott.Daniels at Acm.Org Fri Aug 14 00:09:45 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 13 Aug 2009 21:09:45 -0700 Subject: Programming by Contract In-Reply-To: References: <4A7A15CD.9090306@stoneleaf.us> <4A81C6B8.7010605@stoneleaf.us> Message-ID: Charles Yeomans wrote: > > On Aug 11, 2009, at 3:30 PM, Ethan Furman wrote: > >> Ethan Furman wrote: >>> Greetings! >>> I have seen posts about the assert statement and PbC (or maybe it was >>> DbC), and I just took a very brief look at pycontract >>> (http://www.wayforward.net/pycontract/) and now I have at least one >>> question: Is this basically another way of thinking about unit >>> testing, or is the idea of PbC more along the lines of *always* >>> checking the input/output of functions to ensure they are correct? >>> (*Contstant vigilance!* as Prof Moody would say ;) >>> I know asserts can be turned off, so they obviously won't work for >>> the latter case, and having seen the sample of pycontract it seems it >>> only does its thing during debugging. >>> So is Design (Programming) by Contract a fancy way of saying >>> "Document your inputs/outputs!" or is there more to it? >>> ~Ethan~ >> >> Hmmm... >> >> Well, from the (apparently) complete lack of interest, I shall take >> away the (better?) documentation ideas and unit testing ideas, and not >> worry about the rest. :) >> >> > > > > > Design by contract is complementary to unit testing (I notice that the > author of PEP 316 appears confused about this). DbC is, roughly > speaking, about explicit allocation of responsibility. Consider this > contrived example. > > def foo(s): > require(s is not None) > //code > ensure(hasattr(returnValue, '__iter__')) yo might want two flags, REQUIRE_OFF, and ENSURE_ON that control testing, and change the code above to: require(REQUIRE_OFF or s is not None) //code ensure(ENSURE_OFF or hasattr(returnValue, '__iter__')) Python has no good way to turn off argument calculation by manipulating function definition (at least that I know of). --Scott David Daniels Scott.Daniels at Acm.Org From akonsu at gmail.com Fri Aug 14 00:22:45 2009 From: akonsu at gmail.com (akonsu) Date: Thu, 13 Aug 2009 21:22:45 -0700 (PDT) Subject: coding for multiple versions of python References: Message-ID: <57f07ff6-282c-4ac1-b03a-b26321a02f70@g31g2000yqc.googlegroups.com> On Aug 13, 12:57?pm, "Tim Arnold" wrote: > Hi, > I've got a python based system that has to run on hp unix and red hat linux. > The Python version on the HP is 2.4 and the version on the Linux box is 2.6. > There's nothing I can do about that. > > I think that means I must have two different libraries since the pyc files > are not cross-version compatible. No problem for the libs like PIL or lxml. > But for the part of the system I actually code every day, I'd rather not do > dual maintenance, having two copies of my code for each platform/version. > > I'm guessing I need to configure cvs to copy files to both locations > whenever I commit. Does that sound right? Is there a better way I'm not > thinking of? > > thanks, > --Tim hello, why would you need to maintain pyc files at all? is having just source files enough? or am i missing something? konstantin From clp2 at rebertia.com Fri Aug 14 00:29:58 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 14 Aug 2009 00:29:58 -0400 Subject: coding for multiple versions of python In-Reply-To: References: Message-ID: <50697b2c0908132129p24b1f5e2y586d8d30648e0cd8@mail.gmail.com> On Thu, Aug 13, 2009 at 12:57 PM, Tim Arnold wrote: > Hi, > I've got a python based system that has to run on hp unix and red hat linux. > The Python version on the HP is 2.4 and the version on the Linux box is 2.6. > There's nothing I can do about that. > > I think that means I must have two different libraries since the pyc files > are not cross-version compatible. Why would the .pyc-s matter? They're just an optimization, which fall back to the .py files. It only matters if the .py sourcecode files are compatible with both versions. > But for the part of the system I actually code every day, I'd rather not do > dual maintenance, having two copies of my code for each platform/version. > > I'm guessing I need to configure cvs to copy files to both locations > whenever I commit. Does that sound right? Is there a better way I'm not > thinking of? Put your code's directory in the PYTHONPATH / sys.path of both Python versions. You will still have to write code that works in both versions though. Essentially, don't use any new syntax that's not present in the older version, and you'll have to work around any new/changed functions you use. Cheers, Chris -- http://blog.rebertia.com From tjreedy at udel.edu Fri Aug 14 00:45:23 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Aug 2009 13:45:23 +0900 Subject: i Don't get why it makes trouble In-Reply-To: <189e10f1-771a-4631-a907-56d450b5e493@c2g2000yqi.googlegroups.com> References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> <189e10f1-771a-4631-a907-56d450b5e493@c2g2000yqi.googlegroups.com> Message-ID: azrael wrote: > Thanks Worked fine for me. I was a freakin idiot. I forgot about using > a tuple. damn lists :D The special casing of tuples versus other sequence objects with % formatting, and the forgetting and mistake making of multiple people is one of the reasons for the new .format system. Any sequence can either be passed and printed as a single object or *unrolled as multiple objects. tjr From tjreedy at udel.edu Fri Aug 14 00:49:19 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Aug 2009 13:49:19 +0900 Subject: trouble with reload In-Reply-To: <24956946.post@talk.nabble.com> References: <24956946.post@talk.nabble.com> Message-ID: Dr. Phillip M. Feldman wrote: > According to the Python documentation, 'reload' reloads a previously imported > module (so that changes made via an external editor will be effective). > But, when I try to use this command, I get the following error message: > > TypeError: reload() argument must be module > > Any suggestions will be appreciated. Besides the other answers, do not use reload. It is removed in Py3 because it cannot be made to work as people reasonably expect. tjr From nobody at nowhere.com Fri Aug 14 00:52:24 2009 From: nobody at nowhere.com (Nobody) Date: Fri, 14 Aug 2009 05:52:24 +0100 Subject: PIL and Python References: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> Message-ID: On Thu, 13 Aug 2009 16:38:07 -0700, Martin wrote: >> I want use python to change the "note" from .jpeg files . >> What is the functions on PIL how make this ? > > What do u mean by the note? I think he means the EXIF data. From apt.shansen at gmail.com Fri Aug 14 00:59:19 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Thu, 13 Aug 2009 21:59:19 -0700 Subject: i Don't get why it makes trouble In-Reply-To: References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: <7a9c25c20908132159t113e339x2bd27b333c8f5f19@mail.gmail.com> > > Currently I am working on just a prototype to show what is possible to > be done to get me some fundings for my future work. after that I will > get over to an SQL Alchemy. It's ORM will take over this business for > me. > > A lot of people a not aware of SQL injection. My friend from college > asked me and a couple of other guys for Pen testing of an website. His > SQL injection mistake made him an epic fail. > You don't really need to go the full ORM route to do this safely -- constructing SQL from user input is not only wrong from a security point of view, but it's actually just harder to do it that way then use the mechanisms provided in PEP-249 compliant DB-API modules. Life's easier if you use parameterized queries, really :) You're probably connecting to your database via a DB-API compatible library, I assume? Most are. If so, it's simply a matter of: cur = con.cursor() cur.execute("SELECT name FROM blah WHERE id = ? AND zone = ?", (my_id, my_zone)) All DB-API compliant modules support this, though some mark the parameters differently. That's qmark, some alternates are numeric (:1, :2, etc), some named (:id, :zone), some format (%s, %d, etc), some pyformat, (%(id)d, %(zone)s). The module should provide a 'paramstyle' stating what is supported. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Fri Aug 14 01:17:57 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 13 Aug 2009 22:17:57 -0700 Subject: Format Code Repeat Counts? In-Reply-To: References: Message-ID: MRAB wrote: > The shortest I can come up with is: > "[" + "][".join(letters) + "]" Maybe a golf shot: "][".join(letters).join("[]") --Scott David Daniels Scott.Daniels at Acm.Org From Scott.Daniels at Acm.Org Fri Aug 14 01:36:12 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 13 Aug 2009 22:36:12 -0700 Subject: i Don't get why it makes trouble In-Reply-To: References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: azrael wrote: > ... A lot of people a not aware of SQL injection. My friend from college > asked me and a couple of other guys for Pen testing of an website. His > SQL injection mistake made him an epic fail. And some people are unaware of the unofficial official Python citation for SQL injection explanations: http://xkcd.com/327/ --Scott David Daniels Scott.Daniels at Acm.Org From pfeldman at verizon.net Fri Aug 14 01:36:37 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Thu, 13 Aug 2009 22:36:37 -0700 (PDT) Subject: trouble with reload In-Reply-To: References: <24956946.post@talk.nabble.com> Message-ID: <24965811.post@talk.nabble.com> Actually, I've tried both of these, and I get (different) errors in both cases: In [1]: from mymath import * In [2]: reload(mymath) NameError: name 'mymath' is not defined In [3]: reload('mymath') TypeError: reload() argument must be module Rami Chowdhury wrote: > > Could you please clarify how you're calling it? E.g. > reload('foo') > or > reload(foo) > > ? > > On Thu, 13 Aug 2009 12:05:26 -0700, Dr. Phillip M. Feldman > wrote: > >> According to the Python documentation, 'reload' reloads a previously >> imported >> module (so that changes made via an external editor will be effective). >> But, when I try to use this command, I get the following error message: >> >> TypeError: reload() argument must be module >> >> Any suggestions will be appreciated. > > > > -- > Rami Chowdhury > "Never attribute to malice that which can be attributed to stupidity" -- > Hanlon's Razor > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/trouble-with-reload-tp24956946p24965811.html Sent from the Python - python-list mailing list archive at Nabble.com. From martin at v.loewis.de Fri Aug 14 01:41:39 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 14 Aug 2009 07:41:39 +0200 Subject: coding for multiple versions of python In-Reply-To: References: Message-ID: <4A84F913.9090901@v.loewis.de> > I'm guessing I need to configure cvs to copy files to both locations > whenever I commit. Does that sound right? Is there a better way I'm not > thinking of? If the set of files doesn't change too often, you can use symlinks. That's how Debian currently installs Python packages for multiple versions on a single system. Specifically, put the source code into /net/source/python/foo/*.py. Then, on each system, put symlinks to all .py files into lib/site-packages/foo. Then Python will place the .pyc files next to the symlinks, not next to the actual .py files. HTH, Martin From narkewoody at gmail.com Fri Aug 14 02:22:49 2009 From: narkewoody at gmail.com (Steven Woody) Date: Fri, 14 Aug 2009 14:22:49 +0800 Subject: OptionParser How to: prog [options] [arguments] Message-ID: Hi, I am using OptionParser, but I've not managed figure out a way to support what I wanted command line format "prog [options] [arguments]". E.g., "svn ls -r123 http://hello.world". Can I do this using OptionParser? Thanks. -- Life is the only flaw in an otherwise perfect nonexistence -- Schopenhauer narke public key at http://subkeys.pgp.net:11371 (narkewoody at gmail.com) -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Fri Aug 14 02:31:19 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Aug 2009 23:31:19 -0700 (PDT) Subject: trouble with reload References: <24956946.post@talk.nabble.com> Message-ID: On Aug 13, 10:36?pm, "Dr. Phillip M. Feldman" wrote: > Actually, I've tried both of these, and I get (different) errors in both > cases: > > In [1]: from mymath import * > > In [2]: reload(mymath) > NameError: name 'mymath' is not defined > > In [3]: reload('mymath') > TypeError: reload() argument must be module Two problems here. 1. You have to call reload on an actual module object. When you write "from mymath import *" you are not actually binding the mytmath module to the mymath symbol. So, if you were to then write "print mymath" Python would raise a NameError exception. OTOH, if you were to write "import mymath", then the symbol mymath would bound to the mymath module. If you then write "print mymath", Python would output , the module object. Only then can you pass it to reload. 2. If you use "from mymath import *", even if you were to reload the mymath module (say, by importing it directly and calling reload on that), you will find that the functions you had originally imported will not be updated. They will still refer to the old functions. Why? Because when you reload a module, it only affects that's module's namespace. When you import a function from a module, you are now referencing the function from your own namespace. Even if the function in the module is replaced, the reference to that function in your own namespace hasn't been replaced. So, what do you do? My advice is to dispense with importing functions altogether; only import modules. It's more typing and a bit less efficient, but it makes everything more straightforward and consistent. Carl Banks From python at rcn.com Fri Aug 14 02:34:16 2009 From: python at rcn.com (Raymond Hettinger) Date: Thu, 13 Aug 2009 23:34:16 -0700 (PDT) Subject: implementing descriptors References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: [David] > I am new to Python and I have a question about descriptors. ?If I have > a class as written below, is there a way to use descriptors to be > certain that the datetime in start is always before the one in end? > > class foo(object): > ? ?def __init__(self,a = None,b = None) > ? ? ? self.start = a > ? ? ? self.end = b > > from datetime import datetime > c = datetime(2009,8,13,6,15,0) > d = datetime(2009,8,14,12,0,0) > afoo = foo(c,d) > > For instance, if the following code were run, I would like to instance > of foo to switch the start and end times. > > afoo.start = datetime(2010,8,13,6,15,0) > > I was thinking of using the __set__ descriptor to catch the assignment > and reverse the values if necessary, but I can't figure out how to > determine which values is being set. You're on the right track, but it is easier to use property() than to write your own custom descriptor with __get__ and __set__. class foo(object): def __init__(self,a = None,b = None): self._start = a self._end = b def get_start(self): return self._start def set_start(self, value): if self._end is None or value < self._end: self._start = value else: self._end = value start = property(get_start, set_start) def get_end(self): return self._end def set_end(self, value): if self._start is None or value > self._start: self._end = value else: self._start = value end = property(get_end, set_end) Raymond From frank at chagford.com Fri Aug 14 03:04:37 2009 From: frank at chagford.com (Frank Millman) Date: Fri, 14 Aug 2009 09:04:37 +0200 Subject: How to launch a function at regular time intervals ? References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> <18ac9f9a-0cf2-409c-82b3-ea068f21dbf7@k19g2000yqn.googlegroups.com> Message-ID: On Aug 14, 12:52 am, David wrote: > > Yes, I guess it would be more simple. Here is really what I am trying > to do. I simplified the functions, but the purpose is to write some > text in a local file every x seconds (here, I'm just writing the > timestamp, i.e. a string representing the date & time, every 10 > seconds) and to transfer this file to a distant server via FTP every y > seconds (20 seconds in the example below). My code is a little bit > more complicated because each time I transfer the file, I delete the > local file which is then recreated when data is written, but for > simplicity I left this out in the code below. So, here is the code > I've been using to test Frank's code. I've been struggling with using > or not a While True loop or not, and everything I try seems to run > into issues. > > import threading > from datetime import datetime > import ftplib > > class CFtpConnection: > """FTP Connection parameters""" > def __init__(self, host, port, timeout, user, passwd): > self.host = "" > self.port = 21 > self.timeout = 60 > self.user = "" > self.passwd = "" > > class CStoreData(threading.Thread): > """Write timestamp in a file every 10 seconds in separate > thread""" > > def __init__(self, timestamp): > threading.Thread.__init__(self) > self.event = threading.Event() > self.timestamp = timestamp > > def run(self): > while not self.event.is_set(): > file_handler = open("Test.txt", 'a') > file_handler.write(self.timestamp.strftime("%y%m%d%H%M%S > \n")) > file_handler.close() > self.event.wait(10) > > def stop(self): > self.event.set() > > class CTransferData(threading.Thread): > """Transfer timestamp file every 20 seconds in separate thread""" > > def __init__(self, ftp_connection): > threading.Thread.__init__(self) > self.event = threading.Event() > self.ftp_connection = ftp_connection > > def run(self): > while not self.event.is_set(): > file_handler = open("Test.txt", 'r') > Ftp_handler = ftplib.FTP('') > Ftp_handler.connect(self.ftp_connection.host, > self.ftp_connection.port, self.ftp_connection.timeout) > Ftp_handler.login(self.ftp_connection.user, > self.ftp_connection.passwd) > Ftp_handler.storbinary("STOR Test.txt", file_handler) > file_handler.close() > Ftp_handler.close() > self.event.wait(20) > > def stop(self): > self.event.set() > > ftp_connection = CFtpConnection("", 21, 60, "", "") > ftp_connection.host = '127.0.0.1' > ftp_connection.user = "admin" > ftp_connection.passwd = "admin" > > while(1): > timestamp = datetime.now() > func_store_data = CStoreData(timestamp) > func_store_data.start() > > func_transfer_data = CTransferData(ftp_connection) > func_transfer_data.start() > > func_store_data.stop() > func_store_data.join() > > func_transfer_data.stop() > func_transfer_data.join() Hi David I think that the main problem is your use of while(1) (usually written as 'while 1' BTW). The effect is that you create multiple copies of CStoreData and CTransferData, each running simultaneously. As you bind them to the same name each time, the previous one presumably gets garbage collected. I don't know if this effectively kills the running thread or not. Either way, this is not what you want to happen. Here are some initial thoughts - 1. You say that you want the main program to continue running in the background. Personally I find it easier to think of the main program running in the foreground, and each of the functions running in the background. 2. As you speak of launching several functions, you may want to keep a list of them to make it easier to stop them at the end. 3. Instead of passing 'timestamp' as an argument to each function, it is probably better to call datatime.now() within the function itself. Based on these thoughts, maybe your program should look something like this - running_functions = [] while 1: if some_condition: # start function to store data func = CStoreData() func.start() running_functions.append(func) if some_other_condition: # start function to transfer data func = CTransferData() func.start() running_functions.append(func) if end_condition: # terminate program break # break out of while loop time.sleep(0.1) # to avoid hogging the cpu # stop all running functions at end for func in running_functions: func.stop() func.join() I hope this gives you some ideas. Frank From walkraft at gmail.com Fri Aug 14 03:05:18 2009 From: walkraft at gmail.com (casebash) Date: Fri, 14 Aug 2009 00:05:18 -0700 (PDT) Subject: Nice copy in interactive terminal References: <1250153823.228153@athprx03> Message-ID: <0dac8bc9-8f00-4f4e-bc29-b475bade7685@y10g2000prg.googlegroups.com> I mainly develop on Linux these days, but if I ever end up doing anything on windows I'll make sure to look at that. On Aug 13, 6:56?pm, "Elias Fotinis \(eliasf\)" wrote: > "casebash" wrote: > > I've been wondering for a while if there exists an interactive > > terminal which has nice copy feature (ie. I can copy code without > > getting the >>> in front of every line). > > It would help if we knew what platform you're interested in -- your > User-Agent is G2/1.0, but I don't know what that is. ?:o) > > On Windows, PythonWin can copy from the interactive window without the > prompts. From gabriel.rossetti at arimaz.com Fri Aug 14 03:15:34 2009 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Fri, 14 Aug 2009 09:15:34 +0200 Subject: socket.send : (11, 'Resource temporarily unavailable') Message-ID: <4A850F16.4010309@arimaz.com> Hello everyone, I get a (11, 'Resource temporarily unavailable') error when I try to send a file using a socket. Is there s size limit? I tried sending a smaller file and ii poses no problem. Am I doing something wrong? Here is the code: def sendMessage(host, port, msg): if isinstance(msg, unicode): msg = msg.encode("utf-8") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.setblocking(0) totalsent = 0 while totalsent < len(msg): sent = sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent sock.close() Thank you, Gabriel From javier.collado at gmail.com Fri Aug 14 03:18:45 2009 From: javier.collado at gmail.com (Javier Collado) Date: Fri, 14 Aug 2009 09:18:45 +0200 Subject: OptionParser How to: prog [options] [arguments] In-Reply-To: References: Message-ID: Hello, I think that this isn't possible with optparse library. However, it's possible with argparse (http://code.google.com/p/argparse/): http://argparse.googlecode.com/svn/trunk/doc/other-methods.html#sub-commands It's not a standard library, but it's worth to take a look at it. Best regards, Javier 2009/8/14 Steven Woody : > Hi, > I am using OptionParser, but I've not managed figure out a way to support > what I wanted command line format "prog [options] [arguments]". > E.g., "svn ls -r123 http://hello.world".???Can?I?do?this?using?OptionParser? > Thanks. > -- > Life is the only flaw in an otherwise perfect nonexistence > ? ?-- Schopenhauer > > narke > public key at http://subkeys.pgp.net:11371 (narkewoody at gmail.com) > > -- > http://mail.python.org/mailman/listinfo/python-list > > From durumdara at gmail.com Fri Aug 14 03:43:02 2009 From: durumdara at gmail.com (durumdara) Date: Fri, 14 Aug 2009 00:43:02 -0700 (PDT) Subject: Pygresql, and query meta informations Message-ID: <55aceb1c-b3d9-4f9b-b8cf-d9833edb2660@c29g2000yqd.googlegroups.com> Hi! Pygresql, DB-API. I search for a solution to get meta information about last query, because I must export these infos to Delphi. Delphi have TDataSet, and it have meta structure that must be defined before I create it. For char/varchar fields I must define their sizes! Pygresql is not retreive the field sizes. Ok, it have solution that CHAR fields values have full size; but varchars are not. Ok, secondary I can calc all field lengths before I export, and I can set THIS CALCULATED size to the field, but this is data dependent. If I have NULL only, the field size = 0. Next query get 71 to the field len. Next query is 234... So I wanna ask that a.) have I some special way in Pygresql to retreive the char/varchar field's length? b.) if not, how to I realize this (other ways)? Thanks for your help: dd From gabriel.rossetti at arimaz.com Fri Aug 14 03:47:50 2009 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Fri, 14 Aug 2009 09:47:50 +0200 Subject: socket.send : (11, 'Resource temporarily unavailable') In-Reply-To: <4A850F16.4010309@arimaz.com> References: <4A850F16.4010309@arimaz.com> Message-ID: <4A8516A6.7010309@arimaz.com> Gabriel Rossetti wrote: > Hello everyone, > > I get a (11, 'Resource temporarily unavailable') error when I try to > send a file using a socket. Is there s size limit? I tried sending a > smaller file and ii poses no problem. Am I doing something wrong? Here > is the code: > > def sendMessage(host, port, msg): > > if isinstance(msg, unicode): > msg = msg.encode("utf-8") > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.connect((host, port)) > sock.setblocking(0) > totalsent = 0 > while totalsent < len(msg): > sent = sock.send(msg[totalsent:]) > if sent == 0: > raise RuntimeError, "socket connection broken" > totalsent = totalsent + sent > sock.close() > > Thank you, > Gabriel Actually, the original code didn't have the sock.setblocking(0), the problem I am trying to find is that the server does have sock.setblocking(0) (I can't change that) and it is getting the same error as my client has with the sock.setblocking(0), except it gets it on the accept() call. I tried modifying my code to be like this : def sendMessage(host, port, msg): if isinstance(msg, unicode): msg = msg.encode("utf-8") burstSize = 4096 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) while msg: sent = sock.send(msg[:burstSize]) print "Sending %d bytes..." % sent if sent == 0: raise RuntimeError, "socket connection broken" msg = msg[burstSize:] sock.close() thinking maybe if I send small parts it would work better but this does not seem to change anything. How are large msgs sent w/ a socket in python to a non-blocking server? The msg I'm trying to send is 175213 bytes long. Thank, Gabriel From hendrik at microcorp.co.za Fri Aug 14 04:11:34 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 14 Aug 2009 10:11:34 +0200 Subject: socket.send : (11, 'Resource temporarily unavailable') In-Reply-To: <4A850F16.4010309@arimaz.com> References: <4A850F16.4010309@arimaz.com> Message-ID: <200908141011.34272.hendrik@microcorp.co.za> On Friday 14 August 2009 09:15:34 Gabriel Rossetti wrote: > Hello everyone, > > I get a (11, 'Resource temporarily unavailable') error when I try to > send a file using a socket. Is there s size limit? I tried sending a > smaller file and ii poses no problem. Am I doing something wrong? Here > is the code: > > def sendMessage(host, port, msg): > > if isinstance(msg, unicode): > msg = msg.encode("utf-8") > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.connect((host, port)) > sock.setblocking(0) This is the problem - if the socket does not block, it will return the " temporarily unavailable" error when it is busy. If you want to use it non blocking then you have to handle the error in a try except, and loop. - Hendrik From hendrik at microcorp.co.za Fri Aug 14 04:16:21 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 14 Aug 2009 10:16:21 +0200 Subject: socket.send : (11, 'Resource temporarily unavailable') In-Reply-To: <4A8516A6.7010309@arimaz.com> References: <4A850F16.4010309@arimaz.com> <4A8516A6.7010309@arimaz.com> Message-ID: <200908141016.21579.hendrik@microcorp.co.za> On Friday 14 August 2009 09:47:50 Gabriel Rossetti wrote: > Gabriel Rossetti wrote: 8< ------------------------------------------ > > Actually, the original code didn't have the sock.setblocking(0), the > problem I am trying to find is that the server does have > sock.setblocking(0) (I can't change that) and it is getting the same > error as my client has with the sock.setblocking(0), except it gets it > on the accept() call. I tried modifying my code to be like this : > > def sendMessage(host, port, msg): > > if isinstance(msg, unicode): > msg = msg.encode("utf-8") > > burstSize = 4096 > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.connect((host, port)) > while msg: > sent = sock.send(msg[:burstSize]) > print "Sending %d bytes..." % sent > if sent == 0: > raise RuntimeError, "socket connection broken" > msg = msg[burstSize:] > sock.close() > > thinking maybe if I send small parts it would work better but this does > not seem to change anything. > How are large msgs sent w/ a socket in python to a non-blocking server? > The msg I'm trying to send is 175213 bytes long. Google for netstring, and also look at sock.sendall instead of send. - Hendrik From bearophileHUGS at lycos.com Fri Aug 14 04:24:20 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Fri, 14 Aug 2009 01:24:20 -0700 (PDT) Subject: Plotting Quadratic Functions, pygame References: Message-ID: Senad Ibraimoski Of Belgrade: > Hello, I'm a new guy to this group, my professor recommend this group > to me, because I was boring him with questions.I'm new to python, and > I have problem plotting Quadratic Functions. Using module pygame. Python is a tool you use to learn something else, but tools are important, they also help shape the way you think. So tell your teacher that questions about tools are important enough. If your purpose is to learn something then using Pygame to plot functions is OK. If your purpose is just to plot them, and you don't have strange needs, then MatPlotLib can be better. Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 04:34:52 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 08:34:52 GMT Subject: trouble with reload References: <24956946.post@talk.nabble.com> Message-ID: <0295120a$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 13:49:19 +0900, Terry Reedy wrote: > Dr. Phillip M. Feldman wrote: >> According to the Python documentation, 'reload' reloads a previously >> imported module (so that changes made via an external editor will be >> effective). But, when I try to use this command, I get the following >> error message: >> >> TypeError: reload() argument must be module >> >> Any suggestions will be appreciated. > > Besides the other answers, do not use reload. It is removed in Py3 > because it cannot be made to work as people reasonably expect. That's a damn shame, because it is very useful for interactive use once you get it's quirks. Is it gone-gone or just removed from built-ins? If the former, would the following be a reasonable replacement? def reload(module): if type(module) is not type(__builtins__): raise TypeError("reload() argument must be module") name = module.__name__ del globals()[name] del sys.modules[name] globals()[name] = __import__(name) It seems to work for me, but I'm not sure if I've missed something. -- Steven From rylesny at gmail.com Fri Aug 14 04:38:57 2009 From: rylesny at gmail.com (ryles) Date: Fri, 14 Aug 2009 01:38:57 -0700 (PDT) Subject: Python "and" behavior References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> Message-ID: <55453c36-d789-4710-8a9a-ce5dd306c7c1@h31g2000yqd.googlegroups.com> On Aug 13, 8:36?pm, goldtech wrote: > Could you explain or link me to an explanation of this? http://docs.python.org/tutorial/datastructures.html#more-on-conditions Give the whole tutorial a good read. From hendrik at microcorp.co.za Fri Aug 14 05:04:07 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 14 Aug 2009 11:04:07 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? Message-ID: <200908141104.07641.hendrik@microcorp.co.za> In the past, on this group, I have made statements that said that on Linux, the serial port handling somehow does not allow transmitting and receiving at the same time, and nobody contradicted me. I am running into the self same issue again. What I normally do is to open the port like this: port = open("/dev/ttyS0","r+b",0) and then I unblock it with: def unblock(f): """Given file 'f', sets its unblock flag to true.""" fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) Then I can write a loop that uses a try-except to see if there are characters available, and that examines a queue to see if there is something to transmit, to give the appearance of full duplex functionality. What I would really like is to have two threads - one that does blocking input waiting for a character, and one that examines an output queue and transmits the stuff it finds. When I try to do this, it does not seem to work - as far as I can see, it is as if the underlying implementation is somehow single threaded - if it is waiting for a received character, it waits until something comes in before it will transmit anything. So if you are talking to a device that does not respond, the whole thing freezes up waiting for a character that never comes, and nothing is transmitted either, despite the call to port.write(somestring). The write blocks, and everything stops, waiting for the receipt to finish. Is there a way to get full duplex, so that the transmit and receive are independent of each other? Or are we stuck with a disk-like model that forces a sequence on reads and writes? - Hendrik From jeanmichel at sequans.com Fri Aug 14 05:27:39 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 11:27:39 +0200 Subject: trouble with reload In-Reply-To: <24965811.post@talk.nabble.com> References: <24956946.post@talk.nabble.com> <24965811.post@talk.nabble.com> Message-ID: <4A852E0B.4070309@sequans.com> Dr. Phillip M. Feldman wrote: > Actually, I've tried both of these, and I get (different) errors in both > cases: > > In [1]: from mymath import * > > In [2]: reload(mymath) > NameError: name 'mymath' is not defined > > In [3]: reload('mymath') > TypeError: reload() argument must be module > > Please don't top post :o) 1/ Do not use the 'from import *' form, unless you don't have any other choice, it will set in your namespace an undefined number of symbols, you may get some name collisions which usually lead to very nasty bugs. import mymath reload(mymath) will do the trick. If you are of those lazy coders you can write import mymath as mm reload(mm) mm.aFunction() If you are using a few functions and don't what to prefix them with the module name you can also write import mymath from mymath import func1, func2, func3 # reload the functions reload(mymath) func1 = mymath.func1 func2 = mymath.func2 func3 = mymath.func3 JM From gagsl-py2 at yahoo.com.ar Fri Aug 14 05:32:25 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Aug 2009 06:32:25 -0300 Subject: trouble with reload References: <24956946.post@talk.nabble.com> <0295120a$0$20647$c3e8da3@news.astraweb.com> Message-ID: En Fri, 14 Aug 2009 05:34:52 -0300, Steven D'Aprano escribi?: > On Fri, 14 Aug 2009 13:49:19 +0900, Terry Reedy wrote: >> Besides the other answers, do not use reload. It is removed in Py3 >> because it cannot be made to work as people reasonably expect. > > That's a damn shame, because it is very useful for interactive use once > you get it's quirks. Is it gone-gone or just removed from built-ins? Just relocated: p3> import imp p3> imp.reload -- Gabriel Genellina From pavlovevidence at gmail.com Fri Aug 14 05:38:28 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 14 Aug 2009 02:38:28 -0700 (PDT) Subject: OptionParser How to: prog [options] [arguments] References: Message-ID: On Aug 14, 12:18?am, Javier Collado wrote: > 2009/8/14 Steven Woody : > > > Hi, > > I am using OptionParser, but I've not managed figure out a way to support > > what I wanted command line format "prog [options] [arguments]". > > E.g., "svn ls -r123http://hello.world". Can I do this using OptionParser? > > Thanks. > > Hello, > > I think that this isn't possible with optparse library. It's possible if you remove sys.argv[1] before invoking optparse. But... > However, it's possible with argparse (http://code.google.com/p/argparse/): > ?http://argparse.googlecode.com/svn/trunk/doc/other-methods.html#sub-c... > > It's not a standard library, but it's worth to take a look at it. It's more than worth looking at, it's a slam dunk. It's superior to optparse in every way I can think of. Unless you don't want the third- party dependency there is no reason to use optparse instead of argparse. Carl Banks From gagsl-py2 at yahoo.com.ar Fri Aug 14 05:45:57 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Aug 2009 06:45:57 -0300 Subject: OptionParser How to: prog [options] [arguments] References: Message-ID: En Fri, 14 Aug 2009 03:22:49 -0300, Steven Woody escribi?: > I am using OptionParser, but I've not managed figure out a way to support > what I wanted command line format "prog [options] [arguments]". > E.g., "svn ls -r123 http://hello.world". Can I do this using > OptionParser? Extract the yourself, and pass the remaining arguments (that is, sys.argv[2:]) to parser.parse_args() -- Gabriel Genellina From jeanmichel at sequans.com Fri Aug 14 05:45:58 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 11:45:58 +0200 Subject: implementing descriptors In-Reply-To: References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: <4A853256.9070806@sequans.com> Emile van Sebille wrote: > On 8/13/2009 3:17 PM dippim said... >> I am new to Python and I have a question about descriptors. If I have >> a class as written below, is there a way to use descriptors to be >> certain that the datetime in start is always before the one in end? >> >> class foo(object): >> def __init__(self,a = None,b = None) >> self.start = a >> self.end = b >> >> from datetime import datetime >> c = datetime(2009,8,13,6,15,0) >> d = datetime(2009,8,14,12,0,0) >> afoo = foo(c,d) >> >> For instance, if the following code were run, I would like to instance >> of foo to switch the start and end times. >> >> afoo.start = datetime(2010,8,13,6,15,0) >> >> I was thinking of using the __set__ descriptor to catch the assignment >> and reverse the values if necessary, > > why not... > > > class foo(object): > def __init__(self,a = None,b = None) > self.start = min(a,b) > self.end = max(a,b) > > > Emile > or class foo(object): def __init__(self, start, end) self.start = start self.end = end Problem solved by design :o) JM From sleepy at cabbage.co.uk Fri Aug 14 05:48:34 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Fri, 14 Aug 2009 09:48:34 GMT Subject: get the pause status from amarok 2.1 Message-ID: As the title says, I'm trying to find a way to get the pause status from amarok 2.1. I'm running kubuntu 9.04 with kde 4.2.2, python 2.6.2. Thanks in advance. From martin.hellwig at dcuktec.org Fri Aug 14 05:51:52 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 14 Aug 2009 10:51:52 +0100 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode In-Reply-To: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: Sounds like a bad case of STRIS http://blog.dcuktec.com/2009/08/stris.html From duncan.booth at invalid.invalid Fri Aug 14 06:26:55 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Aug 2009 10:26:55 GMT Subject: Python "and" behavior References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> <4A84B4E2.9080300@islandtraining.com> Message-ID: MRAB wrote: > Operation Result >|x or y| x if x else y >|x and y| y if x else x >|not x| False if x else False > >:-) > That's not a terribly good definition for the 'not' operator. Try: |not x| False if x else True -- Duncan Booth http://kupuguy.blogspot.com From deets at nospam.web.de Fri Aug 14 06:54:32 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 12:54:32 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <7eku38F2gtku3U1@mid.uni-berlin.de> Hendrik van Rooyen schrieb: > In the past, on this group, I have made statements that said that on Linux, > the serial port handling somehow does not allow transmitting and receiving at > the same time, and nobody contradicted me. > > I am running into the self same issue again. > > What I normally do is to open the port like this: > > port = open("/dev/ttyS0","r+b",0) How about using pyserial? With that, I never had any problems accessing the the serial ports, and AFAIK no duplex-problems as well. And I seriously doubt that these are a python-related problem - python only has a very thin, direct layer above the posix-calls, and doesn't do anything that would explain your observed behavior. The GIL is not the issue here either - it won't interfer with blocking IO. Diez From deets at nospam.web.de Fri Aug 14 06:55:07 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 12:55:07 +0200 Subject: get the pause status from amarok 2.1 In-Reply-To: References: Message-ID: <7eku4bF2gtku3U2@mid.uni-berlin.de> Sleepy Cabbage schrieb: > As the title says, I'm trying to find a way to get the pause status from > amarok 2.1. > > I'm running kubuntu 9.04 with kde 4.2.2, python 2.6.2. > > Thanks in advance. Not at my linux-system right now, but dcop and the respective python-module should help. Diez From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 06:58:30 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 10:58:30 GMT Subject: need help calculating point between two coordinates. References: <2d059a29-933e-4e2c-8730-f1f2688af26c@24g2000yqm.googlegroups.com> Message-ID: <029533b3$0$20647$c3e8da3@news.astraweb.com> On Thu, 13 Aug 2009 14:26:54 -0700, PeteDK wrote: > Hi there > > I'am working on a route comparison tool for carpools. > > The route comparison is based on 'steps' retrieved from google maps > GDirection. These steps vary in length and i use the coordinates at the > beginning of each "step". However, sometimes the distance of these steps > is too long(ex. driving 30-40 km. on the freeway). Therefore i would > like to calculate/find the coordinate located in between two given > coordinates. > Lets say one step starts at: > 56.043185,9.922714 > and ends at: > 56.234287,9.864521 > > I would then like to calculate the point right in the middle of these > coordinates. Can you assume that the coordinate system is virtually flat between those points? That is, are the distances small enough that the curvature of the earth isn't relevant? If so, the following should be close enough: def midpoint(a, b): """Return the two-dimensional point midway between points a and b.""" x = (a[0] + b[0])/2.0 y = (a[1] + b[1])/2.0 return (x, y) Otherwise, you can probably start here: http://www.geomidpoint.com/methods.html http://mathforum.org/library/drmath/results.html?contexts=drmath&levels=college&passed_id=51416&passed_title=College+Physics&search_cats=no&textsearch=spherical&textsearch_bool_type=and&topics=physics -- Steven From keith.hughitt at gmail.com Fri Aug 14 07:01:09 2009 From: keith.hughitt at gmail.com (pwnedd) Date: Fri, 14 Aug 2009 04:01:09 -0700 (PDT) Subject: Database query execution times in Python? In-Reply-To: References: <24870050.post@talk.nabble.com> Message-ID: <24969867.post@talk.nabble.com> > Look up EXPLAIN Thanks for the suggestion. I don't see any option to have EXPLAIN display the query time though? -- View this message in context: http://www.nabble.com/Database-query-execution-times-in-Python--tp24870050p24969867.html Sent from the Python - python-list mailing list archive at Nabble.com. From anand at esi-india.com Fri Aug 14 07:01:21 2009 From: anand at esi-india.com (Anand K Rayudu) Date: Fri, 14 Aug 2009 16:31:21 +0530 Subject: How to reset document string In-Reply-To: References: Message-ID: <4A854401.9070500@esi-india.com> Dear Carl, Your ideas are extremely good, and I liked idea 2 especially, based on that I am considering following approach. Eg: let us say I have module named myModule and exposing myModule.myAPI So I will now rename myModule as _myModule and write a python layer with myModule So my python layer will look like this file name myModule.py import _myModule def myAPI(arg1, arg2): """ @param arg1 help string @param arg2 help string """" _myModule.myAPI(arg1,arg2) # actual API So I will provide mechanism which reads the help files and generates this binding python file and reload the module, So now my python editor has the new python strings. Also another advantages of this approach is if customer choses his own IDE he will still get the documentation of our APIs, by just ensuring these python files are in PYTHON_PATH I think this is better approach, kindly please let me know your comments Regards, Anand > On Aug 7, 2:54 am, Anand K Rayudu wrote: > >> Dear All, >> >> We have extended and embedded python into my our application. >> We exposed few APIs to python using >> >> Py_InitModule("myModuleName", myMethods); >> where my methods are >> >> static PyMethodDef VistaDbMethods[] = { >> { (char *)"myAPI",_myAPICFunctionPtr ,METH_VARARGS,"usage: MyHelp)" } >> >> Now problem is ml_doc (Document string). Most of the time the strings >> given by development team is not descriptive enough, so support team >> want to enhance these docstring on need basis and supply to customer >> The idea is we will provide get latest help option from application, >> which will contact our webserver or allow user to pick new help >> document, which will re apply the help on fly. >> From then on our script editors will show the new enhanced help. >> How do I achieve this. >> > > Sounds very cool. I have a few ideas. > > 1. Since you say you are embedding Python in your application, the > most direct way might be to modify the Python interpreter to allow the > __doc__ attribute to be changed. You'd have to modify the PyCFunction > type (defined in methodobject.h and methodobject.c) to allow > overriding the compiled-in doc field. > > 2. Instead of replacing the __doc__ attribute of the function, just > replace the whole function with a wrapper. So, for instance, if your > application decides to update the docstring for myModuleName.myAPI(), > instead of running code like this: > > myModuleName.myAPI.__doc__ = 'new docstring' > > run code like this: > > def create_wrapper(func,docstring): > def wrapper(*args): > return func(*args) > wrapper.__doc__ = doc > return wrapper > myModuleName.myAPI = create_wrapper( > myModuleName.myAPI,'new docstring') > > So now myApi is a Python function with the new docstring that calls > the old function. (Note: if you are concerned with efficiency, it's > possible to write a wrapper in C that has very little overhead.) > > This approach has minor disadvantages (such as if any code write from > myModuleName import myAPI--it won't see the new version) but it may be > the easiest approach. > > 3. Instead of customizing the __doc__ attribute, store any custom > docstrings in a dictionary keyed by the function. > > custom_doc[myModuleName.myApi] = 'new docstring' > > Your script editor, when looking for documentation, will first search > in this custom area to see if the docstring has been overridden; if > so, use that; if not, use the docstring. Something like this: > > def documentation_to_use_in_script_editor(func): > try: > return custom_doc[func] > except KeyError: > return func.__doc__ > > That has the negative of the special docstring not being visible at an > interactive prompt. > > > I have given you some fairly vague answers, hopefully that'll give you > some idea. It sounds like you have an ambitious project, suggesting > that you are probably good enough to implement the suggestions. > > > Carl Banks > -------------- next part -------------- An HTML attachment was scrubbed... URL: From matiassurdi at gmail.com Fri Aug 14 07:30:39 2009 From: matiassurdi at gmail.com (Matias) Date: Fri, 14 Aug 2009 13:30:39 +0200 Subject: python-ldap and encodings Message-ID: Hi! I'm using python-ldap to create some entries on my openldap server. The problem is that some of those entries have accented characters and unicode text in general. I'm wondering if there is any example or documentation on how to add or modify ldap objects whose values contains non-ascii characters, such as accents, and so on. As far as I understand, those values should be encoded using base64, but if I do that, I don't know how to indicate in the modlist that this is the encoded value and not the value itself. Any help will be bery appreciated. Matias. From python at mrabarnett.plus.com Fri Aug 14 07:39:50 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 12:39:50 +0100 Subject: Format Code Repeat Counts? In-Reply-To: References: Message-ID: <4A854D06.1010503@mrabarnett.plus.com> Scott David Daniels wrote: > MRAB wrote: >> The shortest I can come up with is: >> "[" + "][".join(letters) + "]" > > Maybe a golf shot: > "][".join(letters).join("[]") > Even shorter: "["+"][".join(letters)+"]" :-) From matiassurdi at gmail.com Fri Aug 14 07:45:09 2009 From: matiassurdi at gmail.com (Matias) Date: Fri, 14 Aug 2009 13:45:09 +0200 Subject: python-ldap and encodings In-Reply-To: References: Message-ID: Matias wrote: > Hi! > > I'm using python-ldap to create some entries on my openldap server. > > The problem is that some of those entries have accented characters and > unicode text in general. > > I'm wondering if there is any example or documentation on how to add > or modify ldap objects whose values contains non-ascii characters, > such as accents, and so on. As far as I understand, those values > should be encoded using base64, but if I do that, I don't know how to > indicate in the modlist that this is the encoded value and not the > value itself. > > Any help will be bery appreciated. > > > Matias. > Nevermind.... I was doing something really stupid.Don't ask please :-) From greg at cosc.canterbury.ac.nz Fri Aug 14 08:13:46 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 15 Aug 2009 00:13:46 +1200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <7el2mqF2gi53eU1@mid.individual.net> Hendrik van Rooyen wrote: > port = open("/dev/ttyS0","r+b",0) > > What I would really like is to have two threads - one that does blocking input > waiting for a character, and one that examines an output queue and transmits > the stuff it finds. You can't read and write with the same stdio file object at the same time. Odd things tend to happen if you try. You need to open *two* file objects, one for reading and one for writing: fr = open("/dev/ttyS0","rb",0) fw = open("/dev/ttyS0","wb",0) and give fr to the reading thread and fw to the writing thread. You could also try avoiding file objects altogether and use the raw system calls in the os module. Since you're not using any buffering, there's little reason to use the stdio layer. If you do that, you should be able to use the same file descriptor for reading and writing without any trouble. -- Greg From t.gkikopoulos at dundee.ac.uk Fri Aug 14 08:52:11 2009 From: t.gkikopoulos at dundee.ac.uk (trias) Date: Fri, 14 Aug 2009 05:52:11 -0700 (PDT) Subject: anyone with genomewide microarray analysis experience ? Message-ID: <24971224.post@talk.nabble.com> Hi, I am trying to analyse some biological data from microarray experiments. Different experiments have been stored in a SQL database. One of the things I would like to do is to fetch all data from a certain distance from gene ATGs say 100+/- bp and calculate the bp average over all genes over this region. The microarray data has been normalised over each bp Does anyone have some scripts I could use for this purpose. I work with S.cerevisiae Thank you -- View this message in context: http://www.nabble.com/anyone-with-genomewide-microarray-analysis-experience---tp24971224p24971224.html Sent from the Python - python-list mailing list archive at Nabble.com. From istvan.albert at gmail.com Fri Aug 14 09:13:38 2009 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 14 Aug 2009 06:13:38 -0700 (PDT) Subject: anyone with genomewide microarray analysis experience ? References: Message-ID: <10e21ef1-0c13-4810-bbe2-79349099c85b@c29g2000yqd.googlegroups.com> On Aug 14, 8:52?am, trias wrote: > Does anyone have some scripts I could use for this purpose. I work with > S.cerevisiae Since the largest chromosome on the yeast genome is around 4 million bp, the easiest way to accomplish your goal is to create a list of the same size as the chromosome, then populate this list by mapping the genomic index to the list index. After doing this your problem simplifies to slicing the list around the coordinates of interest. You'll be done in minutes. i. From ml at well-adjusted.de Fri Aug 14 09:17:22 2009 From: ml at well-adjusted.de (Jochen Schulz) Date: Fri, 14 Aug 2009 15:17:22 +0200 Subject: anyone with genomewide microarray analysis experience ? In-Reply-To: <24971224.post@talk.nabble.com> References: <24971224.post@talk.nabble.com> Message-ID: <20090814131721.GM19479@wasteland.homelinux.net> trias: > > One of the things I would like to do is to fetch all data from a certain > distance from gene ATGs say 100+/- bp and calculate the bp average over all > genes over this region. I know absolutely nothing about your problem domain, but if your distance function is metric, you can use this: http://well-adjusted.de/mspace.py or that: http://code.activestate.com/recipes/572156/ The latter (by Baerophile) is fast, the former (by me) has more features. Baerophile has even faster implementations (non-Python) as well. J. -- I am worried that my dreams pale in comparison beside TV docu-soaps. [Agree] [Disagree] -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 204 bytes Desc: Digital signature URL: From cjw at ncf.ca Fri Aug 14 09:23:17 2009 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 14 Aug 2009 09:23:17 -0400 Subject: trouble with reload In-Reply-To: References: <24956946.post@talk.nabble.com> Message-ID: Terry Reedy wrote: > Dr. Phillip M. Feldman wrote: >> According to the Python documentation, 'reload' reloads a previously >> imported >> module (so that changes made via an external editor will be >> effective). But, when I try to use this command, I get the following >> error message: >> >> TypeError: reload() argument must be module >> >> Any suggestions will be appreciated. > > Besides the other answers, do not use reload. It is removed in Py3 > because it cannot be made to work as people reasonably expect. > > tjr > It's typically a user module that needs to be reloaded. It seems that del sys.modules['moduleName'] has no effect. Is there some other way of ensuring that any import goes to moduleName.py, instead of moduleName.pyc? Colin W. From alan.isaac at gmail.com Fri Aug 14 09:26:02 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Fri, 14 Aug 2009 13:26:02 GMT Subject: csv.DictWriter.write_header() In-Reply-To: <68b9136d-fa0b-42dc-addf-02d338da34cd@z4g2000prh.googlegroups.com> References: <68b9136d-fa0b-42dc-addf-02d338da34cd@z4g2000prh.googlegroups.com> Message-ID: > On Aug 13, 1:15 pm, Alan G Isaac wrote: >> I do not understand the reason for your silly, sarcastic response. On 8/13/2009 7:58 AM John Machin apparently wrote: > Duck typing: ask a silly question, get a silly answer. Maybe if you learned to be a more generous reader, fewer questions would look "silly" to you. On 8/13/2009 7:58 AM John Machin apparently wrote: > I can imagine that one might (without reading the source) make do with > the published APIs: Now you get it. > On Aug 13, 1:15 pm, Alan G Isaac wrote: >> So my question was, would this improve the class from >> a usability perspective? On 8/13/2009 7:58 AM John Machin apparently wrote: > Of course. Thank you, Alan From david.mcwright at usbfmi.com Fri Aug 14 09:29:22 2009 From: david.mcwright at usbfmi.com (dippim) Date: Fri, 14 Aug 2009 06:29:22 -0700 (PDT) Subject: implementing descriptors References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: <564bdae4-8b2c-440b-bc18-f76a5fdc60c2@r27g2000vbn.googlegroups.com> On Aug 14, 5:45?am, Jean-Michel Pichavant wrote: > Emile van Sebille wrote: > > On 8/13/2009 3:17 PM dippim said... > >> I am new to Python and I have a question about descriptors. ?If I have > >> a class as written below, is there a way to use descriptors to be > >> certain that the datetime in start is always before the one in end? > > >> class foo(object): > >> ? ?def __init__(self,a = None,b = None) > >> ? ? ? self.start = a > >> ? ? ? self.end = b > > >> from datetime import datetime > >> c = datetime(2009,8,13,6,15,0) > >> d = datetime(2009,8,14,12,0,0) > >> afoo = foo(c,d) > > >> For instance, if the following code were run, I would like to instance > >> of foo to switch the start and end times. > > >> afoo.start = datetime(2010,8,13,6,15,0) > > >> I was thinking of using the __set__ descriptor to catch the assignment > >> and reverse the values if necessary, > > > why not... > > > class foo(object): > > ? ?def __init__(self,a = None,b = None) > > ? ? ? self.start = min(a,b) > > ? ? ? self.end = max(a,b) > > > Emile > > or > > class foo(object): > ? ? def __init__(self, start, end) > ? ? ? ?self.start = start > ? ? ? ?self.end = end > > Problem solved by design :o) > > JM Emile and JM, Thanks for the response. However, these solution only work at instantiation. If I change the value of start or end after instantiation, then I can make start or end whatever I like without regard to order. From hendrik at microcorp.co.za Fri Aug 14 09:38:15 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 14 Aug 2009 15:38:15 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <7eku38F2gtku3U1@mid.uni-berlin.de> References: <7eku38F2gtku3U1@mid.uni-berlin.de> Message-ID: <200908141538.15798.hendrik@microcorp.co.za> On Friday 14 August 2009 12:54:32 Diez B. Roggisch wrote: > > How about using pyserial? With that, I never had any problems accessing > the the serial ports, and AFAIK no duplex-problems as well. And I > seriously doubt that these are a python-related problem - python only > has a very thin, direct layer above the posix-calls, and doesn't do > anything that would explain your observed behavior. The GIL is not the > issue here either - it won't interfer with blocking IO. I will have a look at pyserial - have never used it before. I agree that it is probably not a Python issue, and that the GIL is irelevant - I was hoping that someone had already travelled the road and could give me a signpost. In the meantime I have had another idea which I have also not tried yet, namely to do independent opens for reading and writing, to give me two file instances instead of one, and to try with that. I have no idea if it would make any difference, or even work at all. My normal stuff works, but I do not like it as it is essentially busy looping with short sleeps in between. In the eBox, it uses most of the processor just to move a few bytes of I/O in and out between the serial port and the TCP/IP, and struggles to do that better than five times a second, while the message time on the 115200 baud port is only about 2 milliseconds. - Hendrik From deets at nospam.web.de Fri Aug 14 09:39:31 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 15:39:31 +0200 Subject: implementing descriptors In-Reply-To: <564bdae4-8b2c-440b-bc18-f76a5fdc60c2@r27g2000vbn.googlegroups.com> References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> <564bdae4-8b2c-440b-bc18-f76a5fdc60c2@r27g2000vbn.googlegroups.com> Message-ID: <7el7ojF2gggrvU1@mid.uni-berlin.de> dippim schrieb: > On Aug 14, 5:45 am, Jean-Michel Pichavant > wrote: >> Emile van Sebille wrote: >>> On 8/13/2009 3:17 PM dippim said... >>>> I am new to Python and I have a question about descriptors. If I have >>>> a class as written below, is there a way to use descriptors to be >>>> certain that the datetime in start is always before the one in end? >>>> class foo(object): >>>> def __init__(self,a = None,b = None) >>>> self.start = a >>>> self.end = b >>>> from datetime import datetime >>>> c = datetime(2009,8,13,6,15,0) >>>> d = datetime(2009,8,14,12,0,0) >>>> afoo = foo(c,d) >>>> For instance, if the following code were run, I would like to instance >>>> of foo to switch the start and end times. >>>> afoo.start = datetime(2010,8,13,6,15,0) >>>> I was thinking of using the __set__ descriptor to catch the assignment >>>> and reverse the values if necessary, >>> why not... >>> class foo(object): >>> def __init__(self,a = None,b = None) >>> self.start = min(a,b) >>> self.end = max(a,b) >>> Emile >> or >> >> class foo(object): >> def __init__(self, start, end) >> self.start = start >> self.end = end >> >> Problem solved by design :o) >> >> JM > > Emile and JM, > > Thanks for the response. However, these solution only work at > instantiation. If I change the value of start or end after > instantiation, then I can make start or end whatever I like without > regard to order. > But for that, you don't need descriptors. All you need is a property: class Foo(object): def __init__(self, start, end): self._start = start self._end = end @property def start(self): return start @start.setter def start(self, value): if value >= self._end: raise ValueError, "Tried to set a value greater than end!" self._start = value # repeat for end, switch relational op Diez From hendrik at microcorp.co.za Fri Aug 14 09:48:08 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 14 Aug 2009 15:48:08 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <7el2mqF2gi53eU1@mid.individual.net> References: <7el2mqF2gi53eU1@mid.individual.net> Message-ID: <200908141548.08235.hendrik@microcorp.co.za> On Friday 14 August 2009 14:13:46 greg wrote: > You can't read and write with the same stdio file object > at the same time. Odd things tend to happen if you try. > > You need to open *two* file objects, one for reading > and one for writing: > > fr = open("/dev/ttyS0","rb",0) > fw = open("/dev/ttyS0","wb",0) > > and give fr to the reading thread and fw to the > writing thread. Does this actually work without somehow falling foul of the fact that the /dev/ttyS0 is only one thing? - I know that there is no physical reason for not being able to go in and out at the same time - in my embedded stuff I do that routinely - but that is all assembler running on bare metal so it is under my own control. > > You could also try avoiding file objects altogether > and use the raw system calls in the os module. Since > you're not using any buffering, there's little reason > to use the stdio layer. If you do that, you should be > able to use the same file descriptor for reading and > writing without any trouble. Thanks for this - I now have my weekend cut out for me... - Hendrik From david.mcwright at usbfmi.com Fri Aug 14 09:48:11 2009 From: david.mcwright at usbfmi.com (dippim) Date: Fri, 14 Aug 2009 06:48:11 -0700 (PDT) Subject: implementing descriptors References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: On Aug 14, 2:34?am, Raymond Hettinger wrote: > [David] > > > > > I am new to Python and I have a question about descriptors. ?If I have > > a class as written below, is there a way to use descriptors to be > > certain that the datetime in start is always before the one in end? > > > class foo(object): > > ? ?def __init__(self,a = None,b = None) > > ? ? ? self.start = a > > ? ? ? self.end = b > > > from datetime import datetime > > c = datetime(2009,8,13,6,15,0) > > d = datetime(2009,8,14,12,0,0) > > afoo = foo(c,d) > > > For instance, if the following code were run, I would like to instance > > of foo to switch the start and end times. > > > afoo.start = datetime(2010,8,13,6,15,0) > > > I was thinking of using the __set__ descriptor to catch the assignment > > and reverse the values if necessary, but I can't figure out how to > > determine which values is being set. > > You're on the right track, but it is easier to use property() than to > write your own custom descriptor with __get__ and __set__. > > class foo(object): > ? ? def __init__(self,a = None,b = None): > ? ? ? ? self._start = a > ? ? ? ? self._end = b > ? ? def get_start(self): > ? ? ? ? return self._start > ? ? def set_start(self, value): > ? ? ? ? if self._end is None or value < self._end: > ? ? ? ? ? ? self._start = value > ? ? ? ? else: > ? ? ? ? ? ? self._end = value > ? ? start = property(get_start, set_start) > ? ? def get_end(self): > ? ? ? ? return self._end > ? ? def set_end(self, value): > ? ? ? ? if self._start is None or value > self._start: > ? ? ? ? ? ? self._end = value > ? ? ? ? else: > ? ? ? ? ? ? self._start = value > ? ? end = property(get_end, set_end) > > Raymond Raymond, This functionality is exactly what I was looking for. Thanks! I'll be using this to solve my problem. Now that I'm on the right track, I'm still a bit confused about how __get__ and __set__ are useful. Admittedly, I don't need to understand them to solve this problem, but perhaps they may be useful in the future. If I wanted to solve this problem using __get__ and __set__ could it be done? Thanks Again! From exarkun at twistedmatrix.com Fri Aug 14 09:58:37 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Fri, 14 Aug 2009 13:58:37 -0000 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <200908141538.15798.hendrik@microcorp.co.za> References: <7eku38F2gtku3U1@mid.uni-berlin.de> <200908141538.15798.hendrik@microcorp.co.za> Message-ID: <20090814135837.11286.700809778.divmod.xquotient.174@localhost.localdomain> On 01:38 pm, hendrik at microcorp.co.za wrote: >On Friday 14 August 2009 12:54:32 Diez B. Roggisch wrote: >> >>How about using pyserial? With that, I never had any problems >>accessing >>the the serial ports, and AFAIK no duplex-problems as well. And I >>seriously doubt that these are a python-related problem - python only >>has a very thin, direct layer above the posix-calls, and doesn't do >>anything that would explain your observed behavior. The GIL is not the >>issue here either - it won't interfer with blocking IO. > >I will have a look at pyserial - have never used it before. > >I agree that it is probably not a Python issue, and that the GIL is >irelevant - I was hoping that someone had already travelled the road >and >could give me a signpost. > >In the meantime I have had another idea which I have also not tried >yet, >namely to do independent opens for reading and writing, to give me two >file >instances instead of one, and to try with that. I have no idea if it >would >make any difference, or even work at all. > >My normal stuff works, but I do not like it as it is essentially busy >looping >with short sleeps in between. In the eBox, it uses most of the >processor just >to move a few bytes of I/O in and out between the serial port and the >TCP/IP, >and struggles to do that better than five times a second, while the >message >time on the 115200 baud port is only about 2 milliseconds. One strategy you might employ to get rid of the busy looping is to use Twisted and its serial port support. This also addresses the full- duplex issue you've raised. Jean-Paul From deets at nospam.web.de Fri Aug 14 10:03:22 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 16:03:22 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: <7el2mqF2gi53eU1@mid.individual.net> Message-ID: <7el95aF2h0d12U1@mid.uni-berlin.de> Hendrik van Rooyen schrieb: > On Friday 14 August 2009 14:13:46 greg wrote: > >> You can't read and write with the same stdio file object >> at the same time. Odd things tend to happen if you try. >> >> You need to open *two* file objects, one for reading >> and one for writing: >> >> fr = open("/dev/ttyS0","rb",0) >> fw = open("/dev/ttyS0","wb",0) >> >> and give fr to the reading thread and fw to the >> writing thread. > > Does this actually work without somehow falling foul of the fact that > the /dev/ttyS0 is only one thing? - I know that there is no physical reason > for not being able to go in and out at the same time - in my embedded stuff I > do that routinely - but that is all assembler running on bare metal so it is > under my own control. > >> You could also try avoiding file objects altogether >> and use the raw system calls in the os module. Since >> you're not using any buffering, there's little reason >> to use the stdio layer. If you do that, you should be >> able to use the same file descriptor for reading and >> writing without any trouble. > > Thanks for this - I now have my weekend cut out for me... You should *really* just use pyserial. No hassle, instant satisfaction. Diez From ethan at stoneleaf.us Fri Aug 14 10:04:14 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Aug 2009 07:04:14 -0700 Subject: Python "and" behavior In-Reply-To: <4A84B935.8080809@mrabarnett.plus.com> References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> <4A84B4E2.9080300@islandtraining.com> <4A84B935.8080809@mrabarnett.plus.com> Message-ID: <4A856EDE.6010205@stoneleaf.us> MRAB wrote: > Gary Herron wrote: > >> goldtech wrote: >> >>> Could you explain or link me to an explanation of this? Been using >>> Python for a while but not sure I understand what's happening below. >>> Thanks. >>> >>> >>> >>> >>>>>> ss=1 and "fffff" >>>>>> ss >>>>>> >>> >>> 'fffff' >>> >>> >>>>>> ss=0 and "fffff" >>>>>> ss >>>>>> >>> >>> 0 >>> >> >> >> Python's Boolean operators don't turn arbitrary values into True and >> False values. If you use it in any conditional, you'll get the same >> result as if it did, but it is occasionally it's nice to get the >> actual values used in the "and" instead of having the value distilled >> down to a True/False. >> >> >> >From the Python manual: >> These are the Boolean operations, ordered by ascending priority: >> >> Operation Result Notes >> |x or y| if x is false, then y, else x (1) >> |x and y| if x is false, then x, else y (1) >> |not x| if x is false, then |True|, else |False| (2) >> > The Pythonic table would be: > > Operation Result > |x or y| x if x else y > |x and y| y if x else x > |not x| False if x else False > > :-) That last should be |not x| False if x else True ~Ethan~ From aahz at pythoncraft.com Fri Aug 14 10:07:31 2009 From: aahz at pythoncraft.com (Aahz) Date: 14 Aug 2009 07:07:31 -0700 Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> Message-ID: In article <6e13754c-1fa6-4d1b-8861-146bffec8656 at h30g2000vbr.googlegroups.com>, Douglas Alan wrote: > >My friend begs to differ with the above. It would be much better for >debugging if Python generated a parsing error for unrecognized escape >sequences, rather than leaving them unchanged. g++ outputs a warning >for such escape sequences, for instance. This is what I would consider >to be the correct behavior. (Actually, I think it should just generate >a fatal parsing error, but a warning is okay too.) Well, then, the usual response applies: create a patch, discuss it on python-ideas, and see what happens. (That is, nobody has previously complained so vociferously IIRC, and adding a warning is certainly within the bounds of what's theoretically acceptable.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From invalid at invalid Fri Aug 14 10:09:35 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 09:09:35 -0500 Subject: coding for multiple versions of python References: <4A84F913.9090901@v.loewis.de> Message-ID: On 2009-08-14, Martin v. L?wis wrote: >> I'm guessing I need to configure cvs to copy files to both >> locations whenever I commit. Does that sound right? Is there a >> better way I'm not thinking of? Just use one set of source files. > If the set of files doesn't change too often, you can use symlinks. > That's how Debian currently installs Python packages for multiple > versions on a single system. > > Specifically, put the source code into /net/source/python/foo/*.py. > Then, on each system, put symlinks to all .py files into > lib/site-packages/foo. Then Python will place the .pyc files next > to the symlinks, not next to the actual .py files. Why would he need two sets of .py files? -- Grant Edwards grante Yow! I'm EMOTIONAL at now because I have visi.com MERCHANDISING CLOUT!! From invalid at invalid Fri Aug 14 10:12:20 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 09:12:20 -0500 Subject: socket.send : (11, 'Resource temporarily unavailable') References: Message-ID: On 2009-08-14, Gabriel Rossetti wrote: > I get a (11, 'Resource temporarily unavailable') error when I > try to send a file using a socket. Is there s size limit? No, there's no size limit. However, there is a bandwidth limit. You can't shove bytes into the pipe faster than they come out the other end (at least not over the long term). > I tried sending a smaller file and ii poses no problem. Am I > doing something wrong? Yes. If you want to have the socket in non-blocking mode, then you have to catch EAGAIN and retry the operation. > def sendMessage(host, port, msg): > > if isinstance(msg, unicode): > msg = msg.encode("utf-8") > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.connect((host, port)) > sock.setblocking(0) > totalsent = 0 > while totalsent < len(msg): > sent = sock.send(msg[totalsent:]) > if sent == 0: > raise RuntimeError, "socket connection broken" > totalsent = totalsent + sent > sock.close() -- Grant Edwards grante Yow! I didn't order any at WOO-WOO ... Maybe a YUBBA visi.com ... But no WOO-WOO! From invalid at invalid Fri Aug 14 10:17:35 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 09:17:35 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: Message-ID: On 2009-08-14, Hendrik van Rooyen wrote: > In the past, on this group, I have made statements that said > that on Linux, the serial port handling somehow does not allow > transmitting and receiving at the same time, That's not true. Linux/Unix does and always has supported full-duplex communications on serial ports. > and nobody contradicted me. Um, sorry, I guess. > What I would really like is to have two threads - one that > does blocking input waiting for a character, and one that > examines an output queue and transmits the stuff it finds. That's the traditional way of doing full-duplex serial IO on Unix back in the day before the select/poll system calls were available. > When I try to do this, it does not seem to work - as far as I > can see, it is as if the underlying implementation is somehow > single threaded - if it is waiting for a received character, > it waits until something comes in before it will transmit > anything. Nope. I'll try to dig up an example, but that approach has always worked for me. > So if you are talking to a device that does not respond, the > whole thing freezes up waiting for a character that never > comes, and nothing is transmitted either, despite the call to > port.write(somestring). The write blocks, and everything > stops, waiting for the receipt to finish. I've never observed that behavior. > Is there a way to get full duplex, so that the transmit and > receive are independent of each other? That's the way serial ports work on Unix. > Or are we stuck with a disk-like model that forces a sequence > on reads and writes? No. -- Grant Edwards grante Yow! Like I always say at -- nothing can beat visi.com the BRATWURST here in DUSSELDORF!! From invalid at invalid Fri Aug 14 10:19:04 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 09:19:04 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: <7eku38F2gtku3U1@mid.uni-berlin.de> Message-ID: On 2009-08-14, Hendrik van Rooyen wrote: > In the meantime I have had another idea which I have also not tried yet, > namely to do independent opens for reading and writing, to give me two file > instances instead of one, and to try with that. I have no idea if it would > make any difference, or even work at all. That should work (and shouldn't make any difference) > My normal stuff works, but I do not like it as it is > essentially busy looping with short sleeps in between. In the > eBox, it uses most of the processor just to move a few bytes > of I/O in and out between the serial port and the TCP/IP, and > struggles to do that better than five times a second, while > the message time on the 115200 baud port is only about 2 > milliseconds. What platform are you using? I suppose it's possible that there's something broken in the serial driver for that particular hardware. -- Grant Edwards grante Yow! I feel ... JUGULAR ... at visi.com From invalid at invalid Fri Aug 14 10:19:36 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 09:19:36 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: <7eku38F2gtku3U1@mid.uni-berlin.de> <200908141538.15798.hendrik@microcorp.co.za> Message-ID: On 2009-08-14, exarkun at twistedmatrix.com wrote: > One strategy you might employ to get rid of the busy looping > is to use Twisted and its serial port support. This also > addresses the full- duplex issue you've raised. There are no such full-dulex issues. -- Grant Edwards grante Yow! The PINK SOCKS were at ORIGINALLY from 1952!! visi.com But they went to MARS around 1953!! From despen at verizon.net Fri Aug 14 10:20:12 2009 From: despen at verizon.net (despen at verizon.net) Date: Fri, 14 Aug 2009 14:20:12 GMT Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: "Martin P. Hellwig" writes: > Sounds like a bad case of STRIS > http://blog.dcuktec.com/2009/08/stris.html I believe the correct technical term for it is potty mouth. From invalid at invalid Fri Aug 14 10:28:26 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 09:28:26 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: <7el2mqF2gi53eU1@mid.individual.net> Message-ID: <1aGdnessDpUX6RjXnZ2dnUVZ_gCdnZ2d@posted.visi> On 2009-08-14, greg wrote: > Hendrik van Rooyen wrote: > >> port = open("/dev/ttyS0","r+b",0) >> >> What I would really like is to have two threads - one that >> does blocking input waiting for a character, and one that >> examines an output queue and transmits the stuff it finds. > > You can't read and write with the same stdio file object at > the same time. Odd things tend to happen if you try. > > You need to open *two* file objects, one for reading and one > for writing: > > fr = open("/dev/ttyS0","rb",0) > fw = open("/dev/ttyS0","wb",0) Doh! It didn't even occur to me that somebody would use python "file" objects for serial ports, and I completely overlooked the fact that the OP was doing that. In short: don't do that -- it just messes things up. > and give fr to the reading thread and fw to the writing > thread. > > You could also try avoiding file objects altogether and use > the raw system calls in the os module. That's definitely the way you should do serial port I/O. > Since you're not using any buffering, there's little reason to > use the stdio layer. If you do that, you should be able to use > the same file descriptor for reading and writing without any > trouble. Do not use Python file objects. Use the underlying file descriptors: os.open(), os.read(), os.write(). That will almost certainly solve your problems. If you want examples of os.xxxxx() usage, below is the PosixSerial.py module that I use for Linux-only applications. For cross-platform work, use pyserial (whose Posix support is based on the code below). ---------------------------------PosixSerial.py------------------------------ # Posix serial port class # Copyright 2001-2009 Grant B. Edwards # You may use this code in any way you like so long as you # leave this copyright notice. # Though you are not required to, it would be nice if you send # me a copy of bufixes or enhancements and allowed me to # incorporate and distribute them. import sys import fcntl import os import struct import termios import string import select if string.split(sys.version)[0] > '2': TERMIOS = termios else: import TERMIOS # construct dictionaries for baud rate lookups baudEnumToInt = {} baudIntToEnum = {} for rate in (0,50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200,230400,460800,500000,576000,921600,1000000,1152000,1500000,2000000,2500000,3000000,3500000,4000000): try: i = eval('TERMIOS.B'+str(rate)) baudEnumToInt[i]=rate baudIntToEnum[rate] = i except: pass # Do not know if these are right for anything except Linux if sys.platform[:5] == 'linux': TIOCMGET = 0x5415 TIOCMBIS = 0x5416 TIOCMBIC = 0x5417 TIOCMSET = 0x5418 TIOCM_LE = 0x001 TIOCM_DTR = 0x002 TIOCM_RTS = 0x004 TIOCM_ST = 0x008 TIOCM_SR = 0x010 TIOCM_CTS = 0x020 TIOCM_CAR = 0x040 TIOCM_RNG = 0x080 TIOCM_DSR = 0x100 TIOCM_CD = TIOCM_CAR TIOCM_RI = TIOCM_RNG TIOCM_OUT1 = 0x2000 TIOCM_OUT2 = 0x4000 TIOCM_zero_str = struct.pack('I',0) TIOCM_one_str = struct.pack('I',1) TIOCM_RTS_str = struct.pack('I',TIOCM_RTS) TIOCM_DTR_str = struct.pack('I',TIOCM_DTR) portNotOpenError = ValueError('port not open') class Port: """ An object wrapper for Posix serial ports """ def __init__(self,path=None,noinit=False): self.fd = None if path: self.open(path,noinit) def __tcsetattr(self): termios.tcsetattr(self.fd,TERMIOS.TCSANOW,[self.iflag,self.oflag,self.cflag,self.lflag,self.ispeed,self.ospeed,self.cc]) def __tcgetattr(self): self.iflag,self.oflag,self.cflag,self.lflag,self.ispeed,self.ospeed,self.cc = termios.tcgetattr(self.fd) def open(self,path,noinit): if self.fd: self.close() self.path = path self.fd = os.open(path,os.O_RDWR) self.__tcgetattr() if not noinit: self.iflag = 0 self.oflag = 0 self.lflag = 0 self.__tcsetattr() def close(self): if self.fd: os.close(self.fd) self.fd = None def fileno(self): return self.fd; def _write(self,data): if not self.fd: raise portNotOpenError return os.write(self.fd,data) def write(self,data): if not self.fd: raise portNotOpenError t = len(data) d = data while t>0: n = os.write(self.fd,d) d = d[n:] t = t - n def read(self,size=1024,timeout=None): if not self.fd: raise portNotOpenError if timeout is None: return os.read(self.fd,size) else: r,w,e = select.select([self.fd],[],[self.fd],timeout) if r: return os.read(self.fd,size) else: raise "timeout" def baud(self,rate=None): if not self.fd: raise portNotOpenError if not (rate is None): try: b = baudIntToEnum[rate] except: raise ValueError,'invalid baud rate: '+str(rate) self.ispeed = b self.ospeed = b self.__tcsetattr() return baudEnumToInt[self.ispeed] def charLen(self,clen=None): if not self.fd: raise portNotOpenError if not clen is None: self.cflag = self.cflag & ~TERMIOS.CSIZE if clen == 8: self.cflag = self.cflag | TERMIOS.CS8 elif clen == 7: self.cflag = self.cflag | TERMIOS.CS7 elif clen == 6: self.cflag = self.cflag | TERMIOS.CS6 elif clen == 5: self.cflag = self.cflag | TERMIOS.CS5 else: raise ValueError,'invalid char len: '+str(clen) self.__tcsetattr() cs = self.cflag & TERMIOS.CSIZE if cs == TERMIOS.CS8: return 8 elif cs == TERMIOS.CS7: return 7 elif cs == TERMIOS.CS6: return 6 elif cs == TERMIOS.CS5: return 5 else: raise ValueError,'char len invalid' def parity(self,par=None): if not self.fd: raise portNotOpenError if not par is None: self.cflag = self.cflag & ~(TERMIOS.PARENB|TERMIOS.PARODD) if par == 'none': pass elif par == 'even': self.cflag = self.cflag | (TERMIOS.PARENB) elif par == 'odd': self.cflag = self.cflag | (TERMIOS.PARENB|TERMIOS.PARODD) else: raise ValueError,'invalid parity: '+str(par) self.__tcsetattr() if (self.cflag & TERMIOS.PARENB) == 0: return 'none' elif self.cflag & TERMIOS.PARODD: return 'odd' else: return 'even' def xonxoff(self,enable=None): if not self.fd: raise portNotOpenError if not enable is None: if enable: self.iflag = self.iflag | (TERMIOS.IXON|TERMIOS.IXOFF) else: self.iflag = self.iflag & ~(TERMIOS.IXON|TERMIOS.IXOFF) self.__tcsetattr() return (self.iflag & (TERMIOS.IXON|TERMIOS.IXOFF)) == (TERMIOS.IXON|TERMIOS.IXOFF) def rtscts(self,enable=None): if not self.fd: raise portNotOpenError if not enable is None: if enable: self.cflag = self.cflag | TERMIOS.CRTSCTS else: self.cflag = self.cflag & ~TERMIOS.CRTSCTS self.__tcsetattr() return (self.cflag & TERMIOS.CRTSCTS) != 0 def cook(self,enable=None): if not self.fd: raise portNotOpenError if not enable is None: self.iflag = 0 self.oflag = 0 if enable: self.lflag = self.lflag | TERMIOS.ICANON else: self.lflag = self.lflag & ~TERMIOS.ICANON self.__tcsetattr() return (self.lflag & TERMIOS.ICANON) != 0 def echo(self,enable=None): if not self.fd: raise portNotOpenError if not enable is None: self.iflag = 0 self.oflag = 0 if enable: self.lflag = self.lflag | TERMIOS.ECHO else: self.lflag = self.lflag & ~TERMIOS.ECHO self.__tcsetattr() return (self.lflag & TERMIOS.ECHO) != 0 def __handleiflag(self,enable,mask): if not self.fd: raise portNotOpenError if not enable is None: if enable: self.iflag |= mask else: self.iflag &= ~mask self.__tcsetattr() return (self.iflag & mask) != 0 def ignbrk(self,enable=None): return self.__handleiflag(enable,TERMIOS.IGNBRK) def parmrk(self,enable=None): return self.__handleiflag(enable,TERMIOS.PARMRK) def ignpar(self,enable=None): return self.__handleiflag(enable,TERMIOS.IGNPAR) def brkint(self,enable=None): return self.__handleiflag(enable,TERMIOS.BRKINT) def flushInput(self): if not self.fd: raise portNotOpenError termios.tcflush(self.fd,TERMIOS.TCIFLUSH) def flushOutput(self): if not self.fd: raise portNotOpenError termios.tcflush(self.fd,TERMIOS.TCOFLUSH) def flushAll(self): self.flushInput() self.flushOutput() def sendBreak(self,howlong=0): if not self.fd: raise portNotOpenError termios.tcsendbreak(self.fd,howlong) def drainOutput(self): if not self.fd: raise portNotOpenError termios.tcdrain(self.fd) def vmin(self,vm=None): if not self.fd: raise portNotOpenError if not vm is None: if vm<0 or vm>255: raise ValueError,'invalid vmin: '+str(vm) self.cc[TERMIOS.VMIN] = vm self.__tcsetattr() return self.cc[TERMIOS.VMIN] def vtime(self,vt=None): if not self.fd: raise portNotOpenError if not vt is None: if vt<0 or vt>255: raise ValueError,'invalid vtime: '+str(vt) self.cc[TERMIOS.VTIME] = vt self.__tcsetattr() return self.cc[TERMIOS.VTIME] def nonblocking(self): if not self.fd: raise portNotOpenError fcntl.fcntl(self.fd,fcntl.F_SETFL,os.O_NONBLOCK) def txCount(self): s = fcntl.ioctl(self.fd,termios.TIOCOUTQ,TIOCM_zero_str) return struct.unpack('I',s)[0] def rxCount(self): s = fcntl.ioctl(self.fd,termios.TIOCINQ,TIOCM_zero_str) return struct.unpack('I',s)[0] def resetRM(self,value): if value: v = TIOCM_one_str else: v = TIOCM_zero_str fcntl.ioctl(self.fd,0x525005,v) if sys.platform[:5] == 'linux': def DSR(self): if not self.fd: raise portNotOpenError s = fcntl.ioctl(self.fd,TIOCMGET,TIOCM_zero_str) return bool(struct.unpack('I',s)[0] & TIOCM_DSR) def CD(self): if not self.fd: raise portNotOpenError s = fcntl.ioctl(self.fd,TIOCMGET,TIOCM_zero_str) return bool(struct.unpack('I',s)[0] & TIOCM_CD) def RI(self): if not self.fd: raise portNotOpenError s = fcntl.ioctl(self.fd,TIOCMGET,TIOCM_zero_str) return bool(struct.unpack('I',s)[0] & TIOCM_RI) def CTS(self): if not self.fd: raise portNotOpenError s = fcntl.ioctl(self.fd,TIOCMGET,TIOCM_zero_str) return bool(struct.unpack('I',s)[0] & TIOCM_CTS) def DTR(self,on=None): if not self.fd: raise portNotOpenError if not on is None: if on: fcntl.ioctl(self.fd,TIOCMBIS,TIOCM_DTR_str) else: fcntl.ioctl(self.fd,TIOCMBIC,TIOCM_DTR_str) s = fcntl.ioctl(self.fd,TIOCMGET,TIOCM_zero_str) return bool(struct.unpack('I',s)[0] & TIOCM_DTR) def RTS(self,on=None): if not self.fd: raise portNotOpenError if not on is None: if on: fcntl.ioctl(self.fd,TIOCMBIS,TIOCM_RTS_str) else: fcntl.ioctl(self.fd,TIOCMBIC,TIOCM_RTS_str) s = fcntl.ioctl(self.fd,TIOCMGET,TIOCM_zero_str) return bool(struct.unpack('I',s)[0] & TIOCM_RTS) ----------------------------------------------------------------------------- -- Grant Edwards grante Yow! Maybe I should have at asked for my Neutron Bomb visi.com in PAISLEY -- From exarkun at twistedmatrix.com Fri Aug 14 10:40:06 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Fri, 14 Aug 2009 14:40:06 -0000 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: <7eku38F2gtku3U1@mid.uni-berlin.de> <200908141538.15798.hendrik@microcorp.co.za> Message-ID: <20090814144006.11286.1931874476.divmod.xquotient.178@localhost.localdomain> On 02:19 pm, invalid at invalid wrote: >On 2009-08-14, exarkun at twistedmatrix.com >wrote: >>One strategy you might employ to get rid of the busy looping >>is to use Twisted and its serial port support. This also >>addresses the full- duplex issue you've raised. > >There are no such full-dulex issues. There was a perceived issues. Obviously it's possible to do full-duplex with Linux's serial port support (and all the other major platforms too, as far as I know), as long as you know how. :) Twisted makes the how a lot simpler. Jean-Paul From davea at ieee.org Fri Aug 14 10:48:00 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 10:48:00 -0400 Subject: implementing descriptors In-Reply-To: References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: <4A857920.1000008@ieee.org> dippim wrote: > On Aug 14, 2:34 am, Raymond Hettinger wrote: > >> [David] >> >> >> >> >>> I am new to Python and I have a question about descriptors. If I have >>> a class as written below, is there a way to use descriptors to be >>> certain that the datetime in start is always before the one in end? >>> >>> class foo(object): >>> def __init__(self,a =one,b = None) >>> self.start = >>> self.end = >>> >>> from datetime import datetime >>> c =atetime(2009,8,13,6,15,0) >>> d =atetime(2009,8,14,12,0,0) >>> afoo =oo(c,d) >>> >>> For instance, if the following code were run, I would like to instance >>> of foo to switch the start and end times. >>> >>> afoo.start =atetime(2010,8,13,6,15,0) >>> >>> I was thinking of using the __set__ descriptor to catch the assignment >>> and reverse the values if necessary, but I can't figure out how to >>> determine which values is being set. >>> >> You're on the right track, but it is easier to use property() than to >> write your own custom descriptor with __get__ and __set__. >> >> class foo(object): >> def __init__(self,a =one,b = None): >> self._start = >> self._end = >> def get_start(self): >> return self._start >> def set_start(self, value): >> if self._end is None or value < self._end: >> self._start =alue >> else: >> self._end =alue >> start =roperty(get_start, set_start) >> def get_end(self): >> return self._end >> def set_end(self, value): >> if self._start is None or value > self._start: >> self._end =alue >> else: >> self._start =alue >> end =roperty(get_end, set_end) >> >> Raymond >> > > Raymond, > This functionality is exactly what I was looking for. Thanks! I'll > be using this to solve my problem. > > Now that I'm on the right track, I'm still a bit confused about how > __get__ and __set__ are useful. Admittedly, I don't need to > understand them to solve this problem, but perhaps they may be useful > in the future. If I wanted to solve this problem using __get__ and > __set__ could it be done? > > Thanks Again! > > DANGER- WILL ROBINSON! Don't use this code as-is. There is a nasty surprise waiting for the caller when he sets start and end, and discovers that one of them gets thrown out, and an old value still remains. obj= foo(3, 5) obj.start = 8 obj.end = 12 print obj.start, obj.end will print out 3, 12. Not what the caller expected. Four fixes, in order of preference: 0) Trust your user to read and obey your docstrings. This was what JM was implying, by changing the names of the formal parameters. 1) make a new method that sets both values, making these two properties readonly. That new method would make sure the two parameters are self-consistent. Making the actual values readonly can be done with a descriptor as well, or even a decorator. 2) Raise an exception in the getter methods if they're out of order 3) do the min/max logic on the getter methods, but I don't like that one at all. DaveA From jeanmichel at sequans.com Fri Aug 14 10:49:47 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 16:49:47 +0200 Subject: callable virtual method Message-ID: <4A85798B.6020501@sequans.com> Hi fellows, Does anyone know a way to write virtual methods (in one virtual class) that will raise an exception only if called without being overridden ? Currently in the virtual method I'm checking that the class of the instance calling the method has defined that method as well. Example: class Stream(object): """Interface of all stream objects""" def resetStats(self): """Reset the stream statistics. All values a zeroed except the date.""" _log.info('Reset statistics of %s' % self) if self.__class__.resetStats == Stream.resetStats: raise NotImplementedError() It works but it's tedious, I have to add these 2 lines to every virtual method, changing the content of the 2 lines. Maybe there is a nice/builtin way to do so (python 2.4) JM From davea at ieee.org Fri Aug 14 10:53:35 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 10:53:35 -0400 Subject: coding for multiple versions of python In-Reply-To: References: <4A84F913.9090901@v.loewis.de> Message-ID: <4A857A6F.5010401@ieee.org> Grant Edwards wrote: > On 2009-08-14, Martin v. L?wis wrote: > > >>> I'm guessing I need to configure cvs to copy files to both >>> locations whenever I commit. Does that sound right? Is there a >>> better way I'm not thinking of? >>> > > Just use one set of source files. > > >> If the set of files doesn't change too often, you can use symlinks. >> That's how Debian currently installs Python packages for multiple >> versions on a single system. >> >> Specifically, put the source code into /net/source/python/foo/*.py. >> Then, on each system, put symlinks to all .py files into >> lib/site-packages/foo. Then Python will place the .pyc files next >> to the symlinks, not next to the actual .py files. >> > > Why would he need two sets of .py files? > > I can't speak for Martin, but his description doesn't have two sets of .py files, but two sets of symlinks pointing to the same .py files. It's the .pyc files that exist in two forms, since those are version dependent. He's assuming: 1) an OS that supports symlinks 2) two versions of Python on same system 3) one set of pure-python sources that want to stay in synch for both versions. From Scott.Daniels at Acm.Org Fri Aug 14 11:04:26 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 14 Aug 2009 08:04:26 -0700 Subject: Format Code Repeat Counts? In-Reply-To: References: Message-ID: <8YGdnWA4YPxq5xjXnZ2dnUVZ_hti4p2d@pdx.net> MRAB wrote: > Scott David Daniels wrote: >> MRAB wrote: >>> The shortest I can come up with is: >>> "[" + "][".join(letters) + "]" >> >> Maybe a golf shot: >> "][".join(letters).join("[]") >> > Even shorter: > > "["+"][".join(letters)+"]" > > :-) I was going by PEP8 rules. ;-) --Scott David Daniels Scott David Daniels at Acm.Org From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 11:24:42 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 15:24:42 GMT Subject: trouble with reload References: <24956946.post@talk.nabble.com> Message-ID: <02957215$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 09:23:17 -0400, Colin J. Williams wrote: > It's typically a user module that needs to be reloaded. What's a user module? > It seems that del sys.modules['moduleName'] has no effect. sys.modules is just a dictionary, I find it hard to believe that deleting from it has no effect. It works for me: >>> import sys >>> import math >>> 'math' in sys.modules True >>> del sys.modules['math'] >>> 'math' in sys.modules False What behaviour do you get? Of course deleting the math module from the cache doesn't do anything to the math module in your namespace: >>> math >>> del math >>> math Traceback (most recent call last): File "", line 1, in NameError: name 'math' is not defined Of course deleting the module (or reloading it) doesn't have any effect on any objects you already have: >>> import math >>> func = math.sin >>> del sys.modules['math'] >>> del math >>> math.sin(1.2) Traceback (most recent call last): File "", line 1, in NameError: name 'math' is not defined >>> func(1.2) 0.93203908596722629 > Is there some other way of ensuring that any import goes to > moduleName.py, instead of moduleName.pyc? Delete moduleName.pyc. Make sure the .pyc file doesn't exist in the first place. Make sure the last modification date of the .py file is newer than the modification date of the .pyc file. -- Steven From charles at declareSub.com Fri Aug 14 11:26:09 2009 From: charles at declareSub.com (Charles Yeomans) Date: Fri, 14 Aug 2009 11:26:09 -0400 Subject: Programming by Contract In-Reply-To: References: <4A7A15CD.9090306@stoneleaf.us> <4A81C6B8.7010605@stoneleaf.us> Message-ID: On Aug 14, 2009, at 12:09 AM, Scott David Daniels wrote: > Charles Yeomans wrote: >> On Aug 11, 2009, at 3:30 PM, Ethan Furman wrote: >>> Ethan Furman wrote: >>>> Greetings! >>>> I have seen posts about the assert statement and PbC (or maybe it >>>> was DbC), and I just took a very brief look at pycontract (http://www.wayforward.net/pycontract/ >>>> ) and now I have at least one question: Is this basically >>>> another way of thinking about unit testing, or is the idea of PbC >>>> more along the lines of *always* checking the input/output of >>>> functions to ensure they are correct? (*Contstant vigilance!* as >>>> Prof Moody would say ;) >>>> I know asserts can be turned off, so they obviously won't work >>>> for the latter case, and having seen the sample of pycontract it >>>> seems it only does its thing during debugging. >>>> So is Design (Programming) by Contract a fancy way of saying >>>> "Document your inputs/outputs!" or is there more to it? >>>> ~Ethan~ >>> >>> Hmmm... >>> >>> Well, from the (apparently) complete lack of interest, I shall >>> take away the (better?) documentation ideas and unit testing >>> ideas, and not worry about the rest. :) >>> >>> >> Design by contract is complementary to unit testing (I notice that >> the author of PEP 316 appears confused about this). DbC is, >> roughly speaking, about explicit allocation of responsibility. >> Consider this contrived example. >> def foo(s): >> require(s is not None) >> //code >> ensure(hasattr(returnValue, '__iter__')) > > yo might want two flags, REQUIRE_OFF, and ENSURE_ON that control > testing, and change the code above to: > require(REQUIRE_OFF or s is not None) > //code > ensure(ENSURE_OFF or hasattr(returnValue, '__iter__')) > > Python has no good way to turn off argument calculation by > manipulating function definition (at least that I know of). > For this purpose, it had occurred to me to do something like the following. def require(condition): if condition: return True else: raise PreconditionFailure def foo(s): assert require(s is not None) Then it occurred to me to actually read the assert documentation, where I learned that one can pass a second expression to assert. So instead one might write assert precondition, "PreconditionFailure" though I think I prefer the former. Charles Yeomans -------------- next part -------------- An HTML attachment was scrubbed... URL: From david.mcwright at usbfmi.com Fri Aug 14 11:39:25 2009 From: david.mcwright at usbfmi.com (dippim) Date: Fri, 14 Aug 2009 08:39:25 -0700 (PDT) Subject: implementing descriptors References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: On Aug 14, 10:48?am, Dave Angel wrote: > dippim wrote: > > On Aug 14, 2:34 am, Raymond Hettinger wrote: > > >> [David] > > >>> I am new to Python and I have a question about descriptors. ?If I have > >>> a class as written below, is there a way to use descriptors to be > >>> certain that the datetime in start is always before the one in end? > > >>> class foo(object): > >>> ? ?def __init__(self,a =one,b = None) > >>> ? ? ? self.start = > >>> ? ? ? self.end = > > >>> from datetime import datetime > >>> c =atetime(2009,8,13,6,15,0) > >>> d =atetime(2009,8,14,12,0,0) > >>> afoo =oo(c,d) > > >>> For instance, if the following code were run, I would like to instance > >>> of foo to switch the start and end times. > > >>> afoo.start =atetime(2010,8,13,6,15,0) > > >>> I was thinking of using the __set__ descriptor to catch the assignment > >>> and reverse the values if necessary, but I can't figure out how to > >>> determine which values is being set. > > >> You're on the right track, but it is easier to use property() than to > >> write your own custom descriptor with __get__ and __set__. > > >> class foo(object): > >> ? ? def __init__(self,a =one,b = None): > >> ? ? ? ? self._start = > >> ? ? ? ? self._end = > >> ? ? def get_start(self): > >> ? ? ? ? return self._start > >> ? ? def set_start(self, value): > >> ? ? ? ? if self._end is None or value < self._end: > >> ? ? ? ? ? ? self._start =alue > >> ? ? ? ? else: > >> ? ? ? ? ? ? self._end =alue > >> ? ? start =roperty(get_start, set_start) > >> ? ? def get_end(self): > >> ? ? ? ? return self._end > >> ? ? def set_end(self, value): > >> ? ? ? ? if self._start is None or value > self._start: > >> ? ? ? ? ? ? self._end =alue > >> ? ? ? ? else: > >> ? ? ? ? ? ? self._start =alue > >> ? ? end =roperty(get_end, set_end) > > >> Raymond > > > Raymond, > > ? ?This functionality is exactly what I was looking for. Thanks! ?I'll > > be using this to solve my problem. > > > ? ?Now that I'm on the right track, I'm still a bit confused about how > > __get__ and __set__ are useful. ?Admittedly, I don't need to > > understand them to solve this problem, but perhaps they may be useful > > in the future. ?If I wanted to solve this problem using __get__ and > > __set__ could it be done? > > > Thanks Again! > > DANGER- WILL ROBINSON! > > Don't use this code as-is. ?There is a nasty surprise waiting for the > caller when he sets start and end, and discovers that one of them gets > thrown out, and an old value still remains. > > obj= foo(3, 5) > obj.start = 8 > obj.end = 12 > print obj.start, obj.end > > will print out ?3, 12. ? ?Not what the caller expected. You're right about this and I appreciate the warning, but I think what Raymond was going for was directional accuracy without a great deal of his time wasted on details. The explanation served the purpose of moving me forward using property() and I'm thankful for it. > > Four fixes, in order of preference: > 0) Trust your user to read and obey your docstrings. ?This was what JM > was implying, by changing the names of the formal parameters. Considering I am not the sharpest knife in the drawer, I don't wish to start a philosophical discussion about the relative aptitude and capabilities of the people who might use a class I build. However, I will say that as this particular requirement is imposed on this class by the writer, shouldn't it be the writer's responsibility to enforce it, especially, when the cost of enforcement is so low? > 1) ?make a new method that sets both values, making these two properties > readonly. ?That new method would make sure the two parameters are > self-consistent. ?Making the actual values readonly can be done with a > descriptor as well, or even a decorator. > 2) Raise an exception in the getter methods if they're out of order > 3) do the min/max logic on the getter methods, but I don't like that one > at all. > > DaveA From david.mcwright at usbfmi.com Fri Aug 14 11:41:28 2009 From: david.mcwright at usbfmi.com (dippim) Date: Fri, 14 Aug 2009 08:41:28 -0700 (PDT) Subject: implementing descriptors References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> On Aug 14, 10:48?am, Dave Angel wrote: > dippim wrote: > > On Aug 14, 2:34 am, Raymond Hettinger wrote: > > >> [David] > > >>> I am new to Python and I have a question about descriptors. ?If I have > >>> a class as written below, is there a way to use descriptors to be > >>> certain that the datetime in start is always before the one in end? > > >>> class foo(object): > >>> ? ?def __init__(self,a =one,b = None) > >>> ? ? ? self.start = > >>> ? ? ? self.end = > > >>> from datetime import datetime > >>> c =atetime(2009,8,13,6,15,0) > >>> d =atetime(2009,8,14,12,0,0) > >>> afoo =oo(c,d) > > >>> For instance, if the following code were run, I would like to instance > >>> of foo to switch the start and end times. > > >>> afoo.start =atetime(2010,8,13,6,15,0) > > >>> I was thinking of using the __set__ descriptor to catch the assignment > >>> and reverse the values if necessary, but I can't figure out how to > >>> determine which values is being set. > > >> You're on the right track, but it is easier to use property() than to > >> write your own custom descriptor with __get__ and __set__. > > >> class foo(object): > >> ? ? def __init__(self,a =one,b = None): > >> ? ? ? ? self._start = > >> ? ? ? ? self._end = > >> ? ? def get_start(self): > >> ? ? ? ? return self._start > >> ? ? def set_start(self, value): > >> ? ? ? ? if self._end is None or value < self._end: > >> ? ? ? ? ? ? self._start =alue > >> ? ? ? ? else: > >> ? ? ? ? ? ? self._end =alue > >> ? ? start =roperty(get_start, set_start) > >> ? ? def get_end(self): > >> ? ? ? ? return self._end > >> ? ? def set_end(self, value): > >> ? ? ? ? if self._start is None or value > self._start: > >> ? ? ? ? ? ? self._end =alue > >> ? ? ? ? else: > >> ? ? ? ? ? ? self._start =alue > >> ? ? end =roperty(get_end, set_end) > > >> Raymond > > > Raymond, > > ? ?This functionality is exactly what I was looking for. Thanks! ?I'll > > be using this to solve my problem. > > > ? ?Now that I'm on the right track, I'm still a bit confused about how > > __get__ and __set__ are useful. ?Admittedly, I don't need to > > understand them to solve this problem, but perhaps they may be useful > > in the future. ?If I wanted to solve this problem using __get__ and > > __set__ could it be done? > > > Thanks Again! > > DANGER- WILL ROBINSON! > > Don't use this code as-is. ?There is a nasty surprise waiting for the > caller when he sets start and end, and discovers that one of them gets > thrown out, and an old value still remains. > > obj= foo(3, 5) > obj.start = 8 > obj.end = 12 > print obj.start, obj.end > > will print out ?3, 12. ? ?Not what the caller expected. You're right about this and I appreciate the warning, but I think what Raymond was going for was directional accuracy without a great deal of his time wasted on details. The explanation served the purpose of moving me forward using property() and I'm thankful for it. > > Four fixes, in order of preference: > 0) Trust your user to read and obey your docstrings. ?This was what JM > was implying, by changing the names of the formal parameters. Considering I am not the sharpest knife in the drawer, I don't wish to start a philosophical discussion about the relative aptitude and capabilities of the people who might use a class I build. However, I will say that as this particular requirement is imposed on this class by the writer, shouldn't it be the writer's responsibility to enforce it, especially, when the cost of enforcement is so low? > 1) ?make a new method that sets both values, making these two properties > readonly. ?That new method would make sure the two parameters are > self-consistent. ?Making the actual values readonly can be done with a > descriptor as well, or even a decorator. > 2) Raise an exception in the getter methods if they're out of order > 3) do the min/max logic on the getter methods, but I don't like that one > at all. > > DaveA From python at mrabarnett.plus.com Fri Aug 14 11:49:52 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 16:49:52 +0100 Subject: callable virtual method In-Reply-To: <4A85798B.6020501@sequans.com> References: <4A85798B.6020501@sequans.com> Message-ID: <4A8587A0.6040008@mrabarnett.plus.com> Jean-Michel Pichavant wrote: > Hi fellows, > > Does anyone know a way to write virtual methods (in one virtual class) > that will raise an exception only if called without being overridden ? > Currently in the virtual method I'm checking that the class of the > instance calling the method has defined that method as well. > > Example: > > class Stream(object): > """Interface of all stream objects""" > def resetStats(self): > """Reset the stream statistics. All values a zeroed except the > date.""" > _log.info('Reset statistics of %s' % self) > if self.__class__.resetStats == Stream.resetStats: > raise NotImplementedError() > > It works but it's tedious, I have to add these 2 lines to every virtual > method, changing the content of the 2 lines. > > Maybe there is a nice/builtin way to do so (python 2.4) > Why are you checking which class it's in? The method in the base class will be called only if it hasn't been overridden in the subclass. From deets at nospam.web.de Fri Aug 14 11:50:47 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 17:50:47 +0200 Subject: callable virtual method In-Reply-To: References: Message-ID: <7elfenF2gmdggU1@mid.uni-berlin.de> Jean-Michel Pichavant schrieb: > Hi fellows, > > Does anyone know a way to write virtual methods (in one virtual class) > that will raise an exception only if called without being overridden ? > Currently in the virtual method I'm checking that the class of the > instance calling the method has defined that method as well. > > Example: > > class Stream(object): > """Interface of all stream objects""" > def resetStats(self): > """Reset the stream statistics. All values a zeroed except the > date.""" > _log.info('Reset statistics of %s' % self) > if self.__class__.resetStats == Stream.resetStats: > raise NotImplementedError() > > It works but it's tedious, I have to add these 2 lines to every virtual > method, changing the content of the 2 lines. > > Maybe there is a nice/builtin way to do so (python 2.4) Python has no concept of "virtual" methods. A simple class Stream(object): def resetStats(self): raise NotImplemented is all you need. Once a subclass overrides resetStats, that implementatino is used. Additionally, there are modules such as zope.interface out there, that let you define more formally what an interface is, and declare who's implementing it. I don't used this myself though, so I can't really comment to which extend it e.g. warns you if you subclass *without* implementing. Diez From alan.isaac at gmail.com Fri Aug 14 11:54:54 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Fri, 14 Aug 2009 15:54:54 GMT Subject: retrieve item from nested list given index tuple Message-ID: `lst` is a nested list `tpl` is the indexes for an item in the list What is the nice way to retrieve the item? (Speedy access is nice.) I don't want to use NumPy, but I'd like somehow to avoid an explicit loop. I did consider using eval. E.g., eval('lst' + '[%d]'*len(tpl)%tpl). It works but seems rather ugly. I kind of like reduce(list.__getitem__, tpl, lst) but the reliance on reduce remains controversial enough to see i removed from the Python 3 built-ins ... Thanks, Alan Isaac From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 11:56:27 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 15:56:27 GMT Subject: callable virtual method References: Message-ID: <02957986$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 16:49:47 +0200, Jean-Michel Pichavant wrote: > Hi fellows, > > Does anyone know a way to write virtual methods (in one virtual class) > that will raise an exception only if called without being overridden ? > Currently in the virtual method I'm checking that the class of the > instance calling the method has defined that method as well. I'm not entirely sure of the terminology -- is this the same as an abstract base class? Googling has not enlightened me. Given your example, it seems to be. > Example: > > class Stream(object): > """Interface of all stream objects""" > def resetStats(self): > """Reset the stream statistics. All values a zeroed except the > date.""" > _log.info('Reset statistics of %s' % self) > if self.__class__.resetStats == Stream.resetStats: > raise NotImplementedError() The usual idiom I've seen for abstract methods is to simplify the check, and to put it *before* any work is done: class Stream(object): """Interface of all stream objects""" def resetStats(self): if self.__class__ is Stream: raise NotImplementedError() _log.info('Reset statistics of %s' % self) Even simpler is to just put the check in __init__, so to prevent the caller from creating an instance of the class: class AbstractStream(object): def __init__(self): if self.__class__ is Stream: raise NotImplementedError('abstract class') def resetStats(self): # This does not need to be over-ridden. _log.info('Reset statistics of %s' % self) def whatever(self): # This *must* be over-ridden, and *cannot* be called raise NotImplementedError('abstract method') If you have a lot of methods, you can probably reduce the boilerplate with decorators: # Untested from functools import wraps def abstract(func): # Abstract methods don't have to be over-ridden, so long as they # are called from a subclass of the abstract class. @functools.wraps(func) def inner(self, *args, **kwargs): if self.__class__ is Stream: raise NotImplementedError() return func(self, *args, **kwargs) return inner def virtual(func): # Virtual methods must be over-ridden, and must not be called by # inheritance. @functools.wraps(func) def inner(self, *args, **kwargs): raise NotImplementedError() return inner class Stream(object): @abstract def __init__(self): pass def resetStats(self): _log.info('Reset statistics of %s' % self) @virtual def whatever(self): pass -- Steven From maymunbeyin at gmail.com Fri Aug 14 12:03:27 2009 From: maymunbeyin at gmail.com (kk) Date: Fri, 14 Aug 2009 09:03:27 -0700 (PDT) Subject: Why does my ftp script quit after couple of hours? Message-ID: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> Hi This way the first time I did something with ftp stuff. I think that generally it works but it stops working(quits or disappears) after couple of hours of running. This was a personal test-trial script for my own needs which was to get my dynamic ip and broadcast to a client(I have a client script on another computer). I sure could use something like DynDns for the same purpose with easier management but I just wanted to give it a try to see if i could even make it work . Basically this script parses my ip from DynDns ip check page and uploads it to the given ftp site. It works fine initially, it does upload, it updates the Ip every hour but the problem is that after couple of hours the Python console window disappears, I assume it crashes. I know it does upload at least couple times(works for couple hours). it might be something to do with ftp connection. I will investigate that but I just wanted to see if I have any logic or some kind of contextual problem in the script. Here is the link to Pastie page http://pastie.org/584152 Thanks From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 12:11:52 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 16:11:52 GMT Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> Message-ID: <02957d23$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: > "I saw `cout' being shifted "Hello world" times to the left and stopped > right there." --Steve Gonedes Assuming that's something real, and not invented for humour, I presume that's describing something possible in C++. Am I correct? What the hell would it actually do??? -- Steven From invalid at invalid Fri Aug 14 12:17:36 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 11:17:36 -0500 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: On 2009-08-14, Steven D'Aprano wrote: > On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: > >> "I saw `cout' being shifted "Hello world" times to the left and stopped >> right there." --Steve Gonedes > > Assuming that's something real, and not invented for humour, I presume > that's describing something possible in C++. Am I correct? Yes. In C++, the "<<" operator is overloaded. Judging by the context in which I've seen it used, it does something like write strings to a stream. > What the hell > would it actually do??? IIRC in C++, cout << "Hello world"; is equivalent to this in C: printf("Hellow world"); or this in Python: print "hellow world" -- Grant Edwards grante Yow! Bo Derek ruined at my life! visi.com From deets at nospam.web.de Fri Aug 14 12:17:57 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 18:17:57 +0200 Subject: Why does my ftp script quit after couple of hours? In-Reply-To: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> References: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> Message-ID: <7elh1lF2h1rl0U1@mid.uni-berlin.de> kk schrieb: > Hi > This way the first time I did something with ftp stuff. I think that > generally it works but it stops working(quits or disappears) after > couple of hours of running. > > This was a personal test-trial script for my own needs which was to > get my dynamic ip and broadcast to a client(I have a client script on > another computer). I sure could use something like DynDns for the same > purpose with easier management but I just wanted to give it a try to > see if i could even make it work . > > Basically this script parses my ip from DynDns ip check page and > uploads it to the given ftp site. It works fine initially, it does > upload, it updates the Ip every hour but the problem is that after > couple of hours the Python console window disappears, I assume it > crashes. I know it does upload at least couple times(works for couple > hours). it might be something to do with ftp connection. I will > investigate that but I just wanted to see if I have any logic or some > kind of contextual problem in the script. > > > Here is the link to Pastie page > http://pastie.org/584152 The code isn't very robust if anything happens retrieving the IP-website - if for some reason the connection is broken, it won't catch any ensuing IO-exception. Also your way of extracing the IP is rather awkward, a simple re (often not the right tool, but here certainl yes) would help: >>> m = re.search(r"(([0-9]+\.){3}[0-9]+)", body) >>> m.group(1) '85.177.92.101' >>> Diez From maymunbeyin at gmail.com Fri Aug 14 12:25:50 2009 From: maymunbeyin at gmail.com (kk) Date: Fri, 14 Aug 2009 09:25:50 -0700 (PDT) Subject: Why does my ftp script quit after couple of hours? References: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> <7elh1lF2h1rl0U1@mid.uni-berlin.de> Message-ID: <337951bf-4d0d-4dde-95de-8e6d7d68a7f5@a13g2000yqc.googlegroups.com> Hi Diez Thanks for your insight. The reason I chose the awkward method to parse the ip digits is that I was not familiar with the regex module and the Dyndns Ip page is pretty simple page. I guess it is time to learn more about the Re module. As far as robustness, I agree with your assestment. I guess my main confusion with my result is that the console window just disappears. I wonder if I can make the window stay even if it crashesor if there are connection issues? I will createa seperate log file to see if I can catch any issues in a log file. From bieffe62 at gmail.com Fri Aug 14 12:27:30 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Fri, 14 Aug 2009 09:27:30 -0700 (PDT) Subject: Why does my ftp script quit after couple of hours? References: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> Message-ID: <84991768-4ab5-45fa-8e99-c8910280c81f@d32g2000yqh.googlegroups.com> On 14 Ago, 18:03, kk wrote: > Hi > This way the first time I did something with ftp stuff. I think that > generally it works but it stops working(quits or disappears) after > couple of hours of running. > > This was a personal test-trial script for my own needs which was to > get my dynamic ip and broadcast to a client(I have a client script on > another computer). I sure could use something like DynDns for the same > purpose with easier management but I just wanted to give it a try to > see if i could even make it work . > > Basically this script parses my ip from DynDns ip check page and > uploads it to the given ftp site. It works fine initially, it does > upload, it updates the Ip every hour but the problem is that after > couple of hours the Python console window disappears, I assume it > crashes. ?I know it does upload at least couple times(works for couple > hours). it might be something to do with ftp connection. I will > investigate that but I just wanted to see if I have any logic or some > kind of contextual problem in the script. > > Here is the link to Pastie pagehttp://pastie.org/584152 > > Thanks Try catching the exception inside the main loop, to prevent your program to exit in case of failure: if __name__=='__main__': while True: try: writeExtFile(FILE_PATH,FILE_NAME) uploadFile (FTP_NAME,FTP_USER_NAME,FTP_PASSWD,FTP_FOLDER,FILE_NAME) time.sleep(TIME_DELAY) except: err, det, tb = sys.exc_info() print "ERROR =>", err, det # gives you a description of the occurred failure traceback.print_tb(tb) # this might be needed only for debug Ciao ---- FB From wasala at gmail.com Fri Aug 14 12:28:34 2009 From: wasala at gmail.com (Asanka Wasala) Date: Fri, 14 Aug 2009 09:28:34 -0700 (PDT) Subject: Python Permutations Problem Message-ID: Hi I am developing a spell checker for my language, and I came across solving an interesing problem. It would be great if you can suggest me an optimized solution for the problem described below: I have certain group of letters like these: Group #1: c,r,b Group #2: a,z,k Group #3: h,t . . Letters within the same group can be substituted/replaced with the rest of the letters in that group. (ie. Group #1 means letter 'c' can be replaced with either 'r' or 'b', and letter r can be replaced with either c or b, and letter b can be replaced with either r or c) A group can have upto 3 letters, and letters do not overlap between groups. There can be upto 25 such groups. Given a word containing above letters, (e.g. 'cat'.) I want to generate all possible words by subsituting letters in the groups. eg. expected output: cat rat bat czt rzt bzt ckt rkt bkt cah rah bah czh rzh bzh ckh rkh bkh My code is given below. But for complex words like 'cccccccccczzk' it thows the 'maximum recursion depth exceeded' error. Therefore, can you suggest me an optimized solution to achive the above task? Thanks in advance. -------------------------- CODE------------------------------------------- #-*- coding: UTF-8 -*- import re def getPermutations(word): def getSimilarLetters(letter): pattern=u"|c,r,b|a,z,k|h,t|" list=[] ptrn=re.compile("(?P\|(.?,)*?"+letter+"(,.)*?\|)") k=ptrn.search(pattern) if k: letterlist=k.group("grp")[1:-1] list=letterlist.split(",") list.remove(letter) return list else: return letter list=[] def perm(word): posi=0 wrd=word for w in word: posi=posi+1 lst=getSimilarLetters(w) if len(lst)>0: for l in lst: newwrd=wrd[:posi-1]+l+wrd[posi:] if not (newwrd in list): list.append(newwrd) perm(newwrd) try: perm(word) except RuntimeError: list=[] list.append("error") return list list=getPermutations(u"cat") for i in list: print i.encode('utf-8') --------------------------------------------END of CODE----------------------------------------------------------------------------- From prateekkakirwar at gmail.com Fri Aug 14 12:31:43 2009 From: prateekkakirwar at gmail.com (Prateek) Date: Fri, 14 Aug 2009 09:31:43 -0700 (PDT) Subject: Natural Language Processing in Python Message-ID: Hi, Can somebody please provide me link to a good online resource or e- book for doing natural language processing programming in Python. Thanks, Prateek From deets at nospam.web.de Fri Aug 14 12:38:12 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 18:38:12 +0200 Subject: Why does my ftp script quit after couple of hours? In-Reply-To: <337951bf-4d0d-4dde-95de-8e6d7d68a7f5@a13g2000yqc.googlegroups.com> References: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> <7elh1lF2h1rl0U1@mid.uni-berlin.de> <337951bf-4d0d-4dde-95de-8e6d7d68a7f5@a13g2000yqc.googlegroups.com> Message-ID: <7eli7kF2gdbanU2@mid.uni-berlin.de> kk schrieb: > Hi Diez > > Thanks for your insight. The reason I chose the awkward method to > parse the ip digits is that I was not familiar with the regex module > and the Dyndns Ip page is pretty simple page. I guess it is time to > learn more about the Re module. > > As far as robustness, I agree with your assestment. I guess my main > confusion with my result is that the console window just disappears. I > wonder if I can make the window stay even if it crashesor if there are > connection issues? I will createa seperate log file to see if I can > catch any issues in a log file. I'm not a Windows-user, but even there it should be possible to *first* open the console, and then start the script in it. That will keep it open & you can see the stacktrace. Diez From tim.arnold at sas.com Fri Aug 14 12:39:10 2009 From: tim.arnold at sas.com (Tim Arnold) Date: Fri, 14 Aug 2009 12:39:10 -0400 Subject: coding for multiple versions of python References: Message-ID: "Tim Arnold" wrote in message news:h61gld$it2$1 at foggy.unx.sas.com... > Hi, > I've got a python based system that has to run on hp unix and red hat > linux. The Python version on the HP is 2.4 and the version on the Linux > box is 2.6. There's nothing I can do about that. > > I think that means I must have two different libraries since the pyc files > are not cross-version compatible. No problem for the libs like PIL or > lxml. But for the part of the system I actually code every day, I'd rather > not do dual maintenance, having two copies of my code for each > platform/version. > > I'm guessing I need to configure cvs to copy files to both locations > whenever I commit. Does that sound right? Is there a better way I'm not > thinking of? > > thanks, > --Tim > Thanks everyone. I assumed wrongly that I would run into problems if a pyc file generated for 2.4 was available when 2.6 was running the code. I see now that if the pyc is incompatible, python falls back to the py file. Makes sense, I was trying to solve a problem I didn't actually have. On the other hand, Martin's solution looks great for this situation. I'll keep my single set of python files and link to them from the different platform/python version dirs, so I can still get the optimization of the pyc files. I really love this group. thanks again, --Tim Arnold From python at mrabarnett.plus.com Fri Aug 14 12:40:04 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 17:40:04 +0100 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A859364.3060203@mrabarnett.plus.com> Grant Edwards wrote: > On 2009-08-14, Steven D'Aprano wrote: >> On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: >> >>> "I saw `cout' being shifted "Hello world" times to the left and stopped >>> right there." --Steve Gonedes >> Assuming that's something real, and not invented for humour, I presume >> that's describing something possible in C++. Am I correct? > > Yes. In C++, the "<<" operator is overloaded. Judging by the > context in which I've seen it used, it does something like > write strings to a stream. > >> What the hell >> would it actually do??? > > IIRC in C++, > > cout << "Hello world"; > It also returns cout, so you can chain them: cout << "Hello, " << name << '\n'; > is equivalent to this in C: > > printf("Hellow world"); > > or this in Python: > > print "hellow world" > From maymunbeyin at gmail.com Fri Aug 14 12:40:08 2009 From: maymunbeyin at gmail.com (kk) Date: Fri, 14 Aug 2009 09:40:08 -0700 (PDT) Subject: Why does my ftp script quit after couple of hours? References: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> <7elh1lF2h1rl0U1@mid.uni-berlin.de> <337951bf-4d0d-4dde-95de-8e6d7d68a7f5@a13g2000yqc.googlegroups.com> <7eli7kF2gdbanU2@mid.uni-berlin.de> Message-ID: <0b60c6a7-d950-4c3c-890d-908bb25b239b@w41g2000yqb.googlegroups.com> Awesome stuff, thank you so much for all the help. The Pcomp.lang.python is the most helpful list I have encountered so far :) From a0046088 at airmail.net Fri Aug 14 12:41:36 2009 From: a0046088 at airmail.net (wwwayne) Date: Fri, 14 Aug 2009 10:41:36 -0600 Subject: Natural Language Processing in Python References: Message-ID: On Fri, 14 Aug 2009 09:31:43 -0700 (PDT), Prateek wrote: >Hi, > >Can somebody please provide me link to a good online resource or e- >book for doing natural language processing programming in Python. > >Thanks, >Prateek http://www.nltk.org/book From darkwater42 at gmail.com Fri Aug 14 12:42:15 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Fri, 14 Aug 2009 09:42:15 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: On Aug 14, 12:17?pm, Grant Edwards wrote: > On 2009-08-14, Steven D'Aprano wrote: > > On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: > >> "I saw `cout' being shifted "Hello world" times to the left and stopped > >> right there." ?--Steve Gonedes > > > Assuming that's something real, and not invented for humour, I presume > > that's describing something possible in C++. Am I correct? > > Yes. ?In C++, the "<<" operator is overloaded. ?Judging by the > context in which I've seen it used, it does something like > write strings to a stream. There's a persistent rumor that it is *this* very "abuse" of overloading that caused Java to avoid operator overloading all together. But then then Java went and used "+" as the string concatenation operator. Go figure! |>ouglas P.S. Overloading "left shift" to mean "output" does indeed seem a bit sketchy, but in 15 years of C++ programming, I've never seen it cause any confusion or bugs. From skiaec04 at gmail.com Fri Aug 14 12:49:21 2009 From: skiaec04 at gmail.com (Alejandro E. Ciniglio) Date: Fri, 14 Aug 2009 12:49:21 -0400 Subject: Natural Language Processing in Python References: Message-ID: nltk is a good start, we used it in my Computational Linguistics course in school. www.nltk.org --Alejandro From jeanmichel at sequans.com Fri Aug 14 12:49:26 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 18:49:26 +0200 Subject: callable virtual method In-Reply-To: <4A8587A0.6040008@mrabarnett.plus.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> Message-ID: <4A859596.50808@sequans.com> MRAB wrote: > Jean-Michel Pichavant wrote: >> Hi fellows, >> >> Does anyone know a way to write virtual methods (in one virtual >> class) that will raise an exception only if called without being >> overridden ? >> Currently in the virtual method I'm checking that the class of the >> instance calling the method has defined that method as well. >> >> Example: >> >> class Stream(object): >> """Interface of all stream objects""" >> def resetStats(self): >> """Reset the stream statistics. All values a zeroed except the >> date.""" >> _log.info('Reset statistics of %s' % self) >> if self.__class__.resetStats == Stream.resetStats: >> raise NotImplementedError() >> >> It works but it's tedious, I have to add these 2 lines to every >> virtual method, changing the content of the 2 lines. >> >> Maybe there is a nice/builtin way to do so (python 2.4) >> > Why are you checking which class it's in? The method in the base class > will be called only if it hasn't been overridden in the subclass. Sorry guys (means guys *and* gals :op ), I realized I've not been able to describe precisely what I want to do. I'd like the base class to be virtual (aka abstract). However it may be abstract but it does not mean it cannot do some usefull stuff. Here is the schema of my abstract methods : class Interface(object): def method(self): # --------------------- # some common stuff executed here # --------------------- print 'hello world' # --------------------- # here shall stand child specific stuff (empty in the interface method) # --------------------- if self.__class__.method == Interface.method: raise NotImplementedError('You should have read the f****** manual ! You must override this method.') class GoodChild(Interface): def method(self): Interface.method(self) # I want to process the cool stuff done my the base Interface # ------------------------ # Specific GoodChild stuff here # ------------------------ print 'I am a good' return 'perfect' class BadChild(Interface): pass #I'm too lazy good = GoodChild() bad = BadChild() good.method() ...hello world ...I am a good bad.method() ...NotImplementedError: You should have read the f****** manual ! You must override this method. The reason I'd like to do so: I'll be providing the Interface, but child classes will be overridden by others. Having a reliable error RTFM feedback is a time saver, for me and the users. I hope I clarified my issue. JM From deets at nospam.web.de Fri Aug 14 12:56:53 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 18:56:53 +0200 Subject: callable virtual method In-Reply-To: References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> Message-ID: <7eljaoF2fnkqgU1@mid.uni-berlin.de> Jean-Michel Pichavant schrieb: > MRAB wrote: >> Jean-Michel Pichavant wrote: >>> Hi fellows, >>> >>> Does anyone know a way to write virtual methods (in one virtual >>> class) that will raise an exception only if called without being >>> overridden ? >>> Currently in the virtual method I'm checking that the class of the >>> instance calling the method has defined that method as well. >>> >>> Example: >>> >>> class Stream(object): >>> """Interface of all stream objects""" >>> def resetStats(self): >>> """Reset the stream statistics. All values a zeroed except the >>> date.""" >>> _log.info('Reset statistics of %s' % self) >>> if self.__class__.resetStats == Stream.resetStats: >>> raise NotImplementedError() >>> >>> It works but it's tedious, I have to add these 2 lines to every >>> virtual method, changing the content of the 2 lines. >>> >>> Maybe there is a nice/builtin way to do so (python 2.4) >>> >> Why are you checking which class it's in? The method in the base class >> will be called only if it hasn't been overridden in the subclass. > > Sorry guys (means guys *and* gals :op ), I realized I've not been able > to describe precisely what I want to do. > I'd like the base class to be virtual (aka abstract). However it may be > abstract but it does not mean it cannot do some usefull stuff. > > > Here is the schema of my abstract methods : > > class Interface(object): > def method(self): > # --------------------- > # some common stuff executed here > # --------------------- > print 'hello world' > # --------------------- > # here shall stand child specific stuff (empty in the interface > method) > # --------------------- > if self.__class__.method == Interface.method: > raise NotImplementedError('You should have read the f****** > manual ! You must override this method.') > > class GoodChild(Interface): > def method(self): > Interface.method(self) # I want to process the cool stuff done my > the base Interface > # ------------------------ > # Specific GoodChild stuff here > # ------------------------ > print 'I am a good' > return 'perfect' > > class BadChild(Interface): > pass #I'm too lazy > > > good = GoodChild() > bad = BadChild() > > good.method() > ...hello world > ...I am a good > > bad.method() > ...NotImplementedError: You should have read the f****** manual ! You > must override this method. > > > The reason I'd like to do so: I'll be providing the Interface, but child > classes will be overridden by others. Having a reliable error RTFM > feedback is a time saver, for me and the users. > I hope I clarified my issue. First of all, I doubt the above code really yields that output. You are missing a super-call there in GoodChild And the whole problem goes magically away if you start using OO a bit: class Base(object): def method(self): self._do_some_work_for_method() print "some more work" def _do_some_work_for_method(self): raise NotImplemented So your subclasses must implement something else instead of method - and voila, without any hassle things work as expected. Diez From python at mrabarnett.plus.com Fri Aug 14 12:58:33 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 17:58:33 +0100 Subject: Python Permutations Problem In-Reply-To: References: Message-ID: <4A8597B9.2000002@mrabarnett.plus.com> Asanka Wasala wrote: > Hi > I am developing a spell checker for my language, and I came across > solving an interesing problem. It would be great if you can suggest > me an optimized solution for the problem described below: > > I have certain group of letters like these: > > Group #1: c,r,b > Group #2: a,z,k > Group #3: h,t > . > . > > Letters within the same group can be substituted/replaced with the > rest of the letters in that group. > > (ie. Group #1 means letter 'c' can be replaced with either 'r' or 'b', > and letter r can be replaced with either c or b, and letter b can be > replaced with either r or c) > > A group can have upto 3 letters, and letters do not overlap between > groups. There can be upto 25 such groups. > Given a word containing above letters, (e.g. 'cat'.) I want to > generate all possible words by subsituting letters in the groups. > > eg. expected output: > > cat rat bat > czt rzt bzt > ckt rkt bkt > cah rah bah > czh rzh bzh > ckh rkh bkh > > My code is given below. But for complex words like 'cccccccccczzk' it > thows the 'maximum recursion depth exceeded' error. Therefore, can you > suggest me an optimized solution to achive the above task? Thanks in > advance. > -------------------------- [snip] This uses a generator in order: def get_permutations(word, group_dict): if word: for first in group_dict[word[0]]: for rest in get_permutations(word[1 : ], group_dict): yield first + rest else: yield "" def count_permutations(word, group_dict): if word: total = 1 for letter in word: total *= len(group_dict[letter]) return total else: return 0 group_def = u"crb azk ht" group_dict = {} for group in group_def.split(): for letter in group: group_dict[letter] = group word = u"cat" print "There are %d permutations." % count_permutations(word, group_dict) print for perm in get_permutations(word, group_dict): print perm From lanyjie at yahoo.com Fri Aug 14 13:00:49 2009 From: lanyjie at yahoo.com (Yingjie Lan) Date: Fri, 14 Aug 2009 10:00:49 -0700 (PDT) Subject: [Python-Dev] expy: an expressway to extend Python In-Reply-To: Message-ID: <637900.988.qm@web54204.mail.re2.yahoo.com> --- On Sat, 8/8/09, Stefan Behnel wrote: > From: Stefan Behnel > Subject: Re: [Python-Dev] expy: an expressway to extend Python > To: python-dev at python.org > Date: Saturday, August 8, 2009, 4:55 PM > > More details at http://expy.sourceforge.net/ > > I'm clearly biased, but my main concern here is that expy > requires C code > to be written inside of strings. There isn't any good > editor support for > that, so I doubt that expy is good for anything but very > thin wrappers (as > in the examples you presented). Thanks a lot for the input -- I sort of recaptured the advantages of expy and listed four points in the new introduction at http://expy.sf.net/ homepage. Lacking of editor highlight support is quite a problem, but it is possible to create a support. For example, you can use this to indicate the start of embedded code highlight: return """ and then the end mark is of course the enclosing """ > > That said, you might want to look at the argument unpacking > code generated > by Cython. It's highly optimised through specialisation and > has been > benchmarked quite a bit faster than the generic Python > C-API functions for > tuple/keyword extracting. Since argument conversion seems > to be more or > less all that expy really does, maybe you want to reuse > that code. > > Stefan Oh sure, that's nice if that part can be adopted by expy-cxpy. Any help out on this would be very welcomed. Yingjie From vippstar at gmail.com Fri Aug 14 13:01:57 2009 From: vippstar at gmail.com (vippstar) Date: Fri, 14 Aug 2009 10:01:57 -0700 (PDT) Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: On Aug 14, 4:36?am, Xah Lee wrote: > ? A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode > ?http://xahlee.org/UnixResource_dir/writ/emacs_whitespace-mode_problem... Instead of writing a completely useless article you could had asked for help in an emacs newsgroup, or wait until someone else does that for you too (creating and publishing such configuration you desire). Your article, except for the brief description of that mode, is completely useless. Why would you fill your website with junk? Perhaps because you like to write but you're too lazy to write something of value. From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 13:09:42 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 17:09:42 GMT Subject: retrieve item from nested list given index tuple References: Message-ID: <02958ab2$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 15:54:54 +0000, Alan G Isaac wrote: > `lst` is a nested list > > `tpl` is the indexes for an item in the list > What is the nice way to retrieve the item? (Speedy access is nice.) Assuming you want to do this frequently, write a helper function, then use it: # Untested def extract(nested, indexes): for index in indexes: nested = nested[index] return nested > I don't want to use NumPy, but I'd like somehow to avoid an explicit > loop. I did consider using eval. E.g., eval('lst' + > '[%d]'*len(tpl)%tpl). It works but seems rather ugly. And slow. > I kind of like > reduce(list.__getitem__, tpl, lst) but the reliance on reduce remains > controversial enough to see i removed from the Python 3 built-ins ... It's just moved into functools. >>> lst = ['a', 'b', ['aa', ['aaa', 'bbb', 'ccc'], 'cc']] >>> from functools import reduce >>> lst = ['a', 'b', ['aa', ['aaa', 'bbb', 'ccc'], 'cc']] >>> reduce(list.__getitem__, (2, 1, 0), lst) 'aaa' However, it doesn't work too well as soon as you mix sequence types: >>> reduce(list.__getitem__, (2, 1, 0, 0), lst) Traceback (most recent call last): File "", line 1, in TypeError: descriptor '__getitem__' requires a 'list' object but received a 'str' Try this instead: >>> from operator import getitem >>> reduce(getitem, (2, 1, 0), lst) 'aaa' >>> reduce(getitem, (2, 1, 0, 0), lst) 'a' operator.getitem is less ugly too. -- Steven From chris at simplistix.co.uk Fri Aug 14 13:13:05 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 14 Aug 2009 18:13:05 +0100 Subject: csv.DictWriter.write_header() In-Reply-To: References: <68b9136d-fa0b-42dc-addf-02d338da34cd@z4g2000prh.googlegroups.com> Message-ID: <4A859B21.7020603@simplistix.co.uk> Alan G Isaac wrote: > On 8/13/2009 7:58 AM John Machin apparently wrote: >> Duck typing: ask a silly question, get a silly answer. > > Maybe if you learned to be a more generous reader, > fewer questions would look "silly" to you. If you take a look at the crap that John very patiently wades through on the python-excel group, you might consider that a little light hearted sarcasm isn't much to put up with ;-) FWIW, if you're using csv because you think .xls is too hard to generate, try xlwt :-) cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From cjw at ncf.ca Fri Aug 14 13:14:16 2009 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 14 Aug 2009 13:14:16 -0400 Subject: trouble with reload In-Reply-To: <02957215$0$20647$c3e8da3@news.astraweb.com> References: <24956946.post@talk.nabble.com> <02957215$0$20647$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Fri, 14 Aug 2009 09:23:17 -0400, Colin J. Williams wrote: > >> It's typically a user module that needs to be reloaded. > > What's a user module? A module written by a user, as distinguished from a libary > > >> It seems that del sys.modules['moduleName'] has no effect. > > sys.modules is just a dictionary, I find it hard to believe that deleting > from it has no effect. It works for me: > >>>> import sys >>>> import math >>>> 'math' in sys.modules > True >>>> del sys.modules['math'] >>>> 'math' in sys.modules > False > > What behaviour do you get? > > > Of course deleting the math module from the cache doesn't do anything to > the math module in your namespace: > >>>> math > >>>> del math >>>> math > Traceback (most recent call last): > File "", line 1, in > NameError: name 'math' is not defined > > Of course deleting the module (or reloading it) doesn't have any effect > on any objects you already have: > > >>>> import math >>>> func = math.sin >>>> del sys.modules['math'] >>>> del math >>>> math.sin(1.2) > Traceback (most recent call last): > File "", line 1, in > NameError: name 'math' is not defined >>>> func(1.2) > 0.93203908596722629 > > > > >> Is there some other way of ensuring that any import goes to >> moduleName.py, instead of moduleName.pyc? > > Delete moduleName.pyc. > > Make sure the .pyc file doesn't exist in the first place. > > Make sure the last modification date of the .py file is newer than the > modification date of the .pyc file. That's easier said than done, when one is working with an IDE. The cached .pyc file might be different from that in the file. Colin W. > > > From chris at simplistix.co.uk Fri Aug 14 13:16:26 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 14 Aug 2009 18:16:26 +0100 Subject: httplib incredibly slow :-( In-Reply-To: References: Message-ID: <4A859BEA.9070701@simplistix.co.uk> Aahz wrote: > Sorry, I mostly have been working on our Mac port, so I'm not sure what's > needed to make this work on Windows. Did you try downloading the PyCurl > binary? Maybe it statically links libcurl on Windows. Shame it's not available as a bdist_egg, that's what I'm really after... > What do you need to know for a decent example? Simple download of a file from a url with some auth headers added would do me. Other than that, nice to haves would be how to build a http post with fields in a multi-part body, some of which might be files. cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From nad at acm.org Fri Aug 14 13:21:16 2009 From: nad at acm.org (Ned Deily) Date: Fri, 14 Aug 2009 10:21:16 -0700 Subject: Natural Language Processing in Python References: Message-ID: In article , Prateek wrote: > Can somebody please provide me link to a good online resource or e- > book for doing natural language processing programming in Python. Check out the Natural Language Toolkit: http://www.nltk.org/ -- Ned Deily, nad at acm.org From daniel.eliason at excite.com Fri Aug 14 13:25:17 2009 From: daniel.eliason at excite.com (fortunatus) Date: Fri, 14 Aug 2009 10:25:17 -0700 (PDT) Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: On Aug 14, 1:01?pm, vippstar wrote: > Why would you fill your website with junk? The OP made it clear: >Just wanted to express some frustration with whitespace-mode. From vippstar at gmail.com Fri Aug 14 13:31:39 2009 From: vippstar at gmail.com (vippstar) Date: Fri, 14 Aug 2009 10:31:39 -0700 (PDT) Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: On Aug 14, 8:25?pm, fortunatus wrote: > On Aug 14, 1:01?pm, vippstar wrote: > > > Why would you fill your website with junk? > > The OP made it clear: > > >Just wanted to express some frustration with whitespace-mode. You took my question out of context and answered it. I read the article, it's not like I missed any of it. Plus, it's not a real answer. "Because I wanted to". Why did you? Why would you? From jeanmichel at sequans.com Fri Aug 14 13:43:15 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 19:43:15 +0200 Subject: callable virtual method In-Reply-To: <7eljaoF2fnkqgU1@mid.uni-berlin.de> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> Message-ID: <4A85A233.9030905@sequans.com> Diez B. Roggisch wrote: > Jean-Michel Pichavant schrieb: >> MRAB wrote: >>> Jean-Michel Pichavant wrote: >>>> Hi fellows, >>>> >>>> Does anyone know a way to write virtual methods (in one virtual >>>> class) that will raise an exception only if called without being >>>> overridden ? >>>> Currently in the virtual method I'm checking that the class of the >>>> instance calling the method has defined that method as well. >>>> >>>> Example: >>>> >>>> class Stream(object): >>>> """Interface of all stream objects""" >>>> def resetStats(self): >>>> """Reset the stream statistics. All values a zeroed except >>>> the date.""" >>>> _log.info('Reset statistics of %s' % self) >>>> if self.__class__.resetStats == Stream.resetStats: >>>> raise NotImplementedError() >>>> >>>> It works but it's tedious, I have to add these 2 lines to every >>>> virtual method, changing the content of the 2 lines. >>>> >>>> Maybe there is a nice/builtin way to do so (python 2.4) >>>> >>> Why are you checking which class it's in? The method in the base class >>> will be called only if it hasn't been overridden in the subclass. >> >> Sorry guys (means guys *and* gals :op ), I realized I've not been >> able to describe precisely what I want to do. >> I'd like the base class to be virtual (aka abstract). However it may >> be abstract but it does not mean it cannot do some usefull stuff. >> >> >> Here is the schema of my abstract methods : >> >> class Interface(object): >> def method(self): >> # --------------------- >> # some common stuff executed here >> # --------------------- >> print 'hello world' >> # --------------------- >> # here shall stand child specific stuff (empty in the >> interface method) >> # --------------------- >> if self.__class__.method == Interface.method: >> raise NotImplementedError('You should have read the >> f****** manual ! You must override this method.') >> >> class GoodChild(Interface): >> def method(self): >> Interface.method(self) # I want to process the cool stuff done >> my the base Interface >> # ------------------------ >> # Specific GoodChild stuff here >> # ------------------------ >> print 'I am a good' >> return 'perfect' >> >> class BadChild(Interface): >> pass #I'm too lazy >> >> >> good = GoodChild() >> bad = BadChild() >> >> good.method() >> ...hello world >> ...I am a good >> >> bad.method() >> ...NotImplementedError: You should have read the f****** manual ! You >> must override this method. >> >> >> The reason I'd like to do so: I'll be providing the Interface, but >> child classes will be overridden by others. Having a reliable error >> RTFM feedback is a time saver, for me and the users. >> I hope I clarified my issue. > > First of all, I doubt the above code really yields that output. You > are missing a super-call there in GoodChild > > And the whole problem goes magically away if you start using OO a bit: > > > class Base(object): > > > def method(self): > self._do_some_work_for_method() > print "some more work" > > def _do_some_work_for_method(self): > raise NotImplemented > > > So your subclasses must implement something else instead of method - > and voila, without any hassle things work as expected. > > Diez It does yield that output, there's an unbound call to Interface.method. Your solution will work, for sure. The problem is that it will dumb down the Base class interface, multiplying the number of methods by 2. This would not be an issue in many cases, in mine there's already too much meaningful methods in my class for me to add artificial ones. Thanks for the tip anyway. JM From wiggly at wiggly.org Fri Aug 14 13:53:02 2009 From: wiggly at wiggly.org (Nigel Rantor) Date: Fri, 14 Aug 2009 18:53:02 +0100 Subject: callable virtual method In-Reply-To: <4A85A233.9030905@sequans.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> Message-ID: <4A85A47E.308@wiggly.org> Jean-Michel Pichavant wrote: > > Your solution will work, for sure. The problem is that it will dumb down > the Base class interface, multiplying the number of methods by 2. This > would not be an issue in many cases, in mine there's already too much > meaningful methods in my class for me to add artificial ones. > > Thanks for the tip anyway. I suggest you reconsider. You asked a question and have been given a standard way of achieving the desired outcome. It's common in OO to use a Template pattern like this. If you're not interested in finding out how loads of people have already solved the problem then why ask? The methods that require overriding can be prefixed with an underscore so that people get a hint that they are an implementation detail rather than part of the public interface. I don't see your problem, other than a vague aesthetic unease. Regards, n From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 13:55:59 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 17:55:59 GMT Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com> <7877b03a-09da-4836-804c-502b6f78003c@h21g2000yqa.googlegroups.com> <02933e60$0$20647$c3e8da3@news.astraweb.com> <2cdc3f88-1952-4ca2-9754-5b7583fb5fd8@z31g2000yqd.googlegroups.com> Message-ID: <0295958b$0$20647$c3e8da3@news.astraweb.com> I think I've spent enough time on this discussion, so I won't be directly responding to any of your recent points -- it's clear that I'm not persuading you that there's any justification for any behaviour for escape sequences other than the way C++ deals with them. That's your prerogative, of course, but I've done enough tilting at windmills for this week, so I'll just make one final comment and then withdraw from an unproductive argument. (I will make an effort to read any final comments you wish to make, so feel free to reply. Just don't expect an answer to any questions.) Douglas, you and I clearly have a difference of opinion on this. Neither of us have provided even the tiniest amount of objective, replicable, reliable data on the error-proneness of the C++ approach versus that of Python. The supposed superiority of the C++ approach is entirely subjective and based on personal opinion instead of quantitative facts. I prefer languages that permit anything that isn't explicitly forbidden, so I'm happy that Python treats non-special escape sequences as valid, and your attempts to convince me that this goes against the Zen have entirely failed to convince me. As I've done before, I will admit that one consequence of this design is that it makes it hard to introduce new escape sequences to Python. Given that it's vanishingly rare to want to do so, and that wanting to add backslashes to strings is common, I think that's a reasonable tradeoff. Other languages may make different tradeoffs, and that's fine by me. -- Steven From jeanmichel at sequans.com Fri Aug 14 13:57:17 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 19:57:17 +0200 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode In-Reply-To: References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: <4A85A57D.8030908@sequans.com> vippstar wrote: > On Aug 14, 8:25 pm, fortunatus wrote: > >> On Aug 14, 1:01 pm, vippstar wrote: >> >> >>> Why would you fill your website with junk? >>> >> The OP made it clear: >> >> >>> Just wanted to express some frustration with whitespace-mode. >>> > > You took my question out of context and answered it. I read the > article, it's not like I missed any of it. Plus, it's not a real > answer. "Because I wanted to". Why did you? Why would you? > FYI, Xah Lee is a well known BTFL (Benevolent Troller For Life), you shouldn't argue about one of his post. From cjw at ncf.ca Fri Aug 14 13:57:18 2009 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 14 Aug 2009 13:57:18 -0400 Subject: retrieve item from nested list given index tuple In-Reply-To: <02958ab2$0$20647$c3e8da3@news.astraweb.com> References: <02958ab2$0$20647$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Fri, 14 Aug 2009 15:54:54 +0000, Alan G Isaac wrote: > >> `lst` is a nested list >> >> `tpl` is the indexes for an item in the list > >> What is the nice way to retrieve the item? (Speedy access is nice.) > > Assuming you want to do this frequently, write a helper function, then > use it: > > # Untested > def extract(nested, indexes): > for index in indexes: > nested = nested[index] > return nested This looks OK for the first level of nesting. We are not told much about tpl but suppose that: lst= [a, [b, [c, d]], [e, f]] and that we wish to retrieve d and f from lst. tpl would need to be something like [[1, 1, 1], [2, 1]]. If that is the requirement, then Untested is only a step along the road, extract could be made recursive. Colin W. > > >> I don't want to use NumPy, but I'd like somehow to avoid an explicit >> loop. I did consider using eval. E.g., eval('lst' + >> '[%d]'*len(tpl)%tpl). It works but seems rather ugly. > > And slow. > > >> I kind of like >> reduce(list.__getitem__, tpl, lst) but the reliance on reduce remains >> controversial enough to see i removed from the Python 3 built-ins ... > > It's just moved into functools. > > >>>> lst = ['a', 'b', ['aa', ['aaa', 'bbb', 'ccc'], 'cc']] >>>> from functools import reduce >>>> lst = ['a', 'b', ['aa', ['aaa', 'bbb', 'ccc'], 'cc']] >>>> reduce(list.__getitem__, (2, 1, 0), lst) > 'aaa' > > > However, it doesn't work too well as soon as you mix sequence types: > >>>> reduce(list.__getitem__, (2, 1, 0, 0), lst) > Traceback (most recent call last): > File "", line 1, in > TypeError: descriptor '__getitem__' requires a 'list' object but received > a 'str' > > Try this instead: > >>>> from operator import getitem >>>> reduce(getitem, (2, 1, 0), lst) > 'aaa' >>>> reduce(getitem, (2, 1, 0, 0), lst) > 'a' > > operator.getitem is less ugly too. > > Colin W. From alan.isaac at gmail.com Fri Aug 14 14:02:58 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Fri, 14 Aug 2009 18:02:58 GMT Subject: retrieve item from nested list given index tuple In-Reply-To: <02958ab2$0$20647$c3e8da3@news.astraweb.com> References: <02958ab2$0$20647$c3e8da3@news.astraweb.com> Message-ID: On 8/14/2009 1:09 PM Steven D'Aprano apparently wrote: > Try this instead: > >>>> from operator import getitem >>>> reduce(getitem, (2, 1, 0), lst) > 'aaa' >>>> reduce(getitem, (2, 1, 0, 0), lst) > 'a' > > operator.getitem is less ugly too. Yes, that's better. Thanks, Alan From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 14:03:27 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 18:03:27 GMT Subject: trouble with reload References: <24956946.post@talk.nabble.com> <02957215$0$20647$c3e8da3@news.astraweb.com> Message-ID: <0295974b$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 13:14:16 -0400, Colin J. Williams wrote: > Steven D'Aprano wrote: >> On Fri, 14 Aug 2009 09:23:17 -0400, Colin J. Williams wrote: >> >>> It's typically a user module that needs to be reloaded. >> >> What's a user module? > A module written by a user, as distinguished from a libary You mean an end-user of the application? Or you mean the application programmer? I'm not sure there is any difference between "user modules" and "library modules" apart from what they do. Perhaps it would help if you could explain the circumstances of when you would reload a module. During application development, for an incremental edit/reload/test cycle? Or while the completed application is being executed? >>> Is there some other way of ensuring that any import goes to >>> moduleName.py, instead of moduleName.pyc? >> >> Delete moduleName.pyc. >> >> Make sure the .pyc file doesn't exist in the first place. >> >> Make sure the last modification date of the .py file is newer than the >> modification date of the .pyc file. > > That's easier said than done, when one is working with an IDE. The > cached .pyc file might be different from that in the file. If the IDE is getting in your way, then don't use it. Or if you tell us what IDE you're using, and precisely what it is doing, somebody can tell you how to defeat the IDE's cache. (That won't be me -- I don't use IDEs.) Or perhaps you're entire approach is wrong, and you shouldn't be using reload() at all. Don't know. -- Steven From dullrich at sprynet.com Fri Aug 14 14:18:35 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Fri, 14 Aug 2009 13:18:35 -0500 Subject: Komodo(!) Message-ID: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> Probably this isn't news to anyone but me, but just in case: Last I heard Komodo was a very highly regarded IDE that unfortunately cost money. Yesterday I discovered that they now have an editor available for free. Doesn't contain all the features of the IDE, but just having glanced at it it seems to contain more than I'll ever use. What I really like about it is that one can write Komodo scripts in Python (using an extensive API allowing various manipulations of the current document). From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 14:20:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 18:20:41 GMT Subject: callable virtual method References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> Message-ID: <02959b54$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 18:49:26 +0200, Jean-Michel Pichavant wrote: > Sorry guys (means guys *and* gals :op ), I realized I've not been able > to describe precisely what I want to do. I'd like the base class to be > virtual (aka abstract). However it may be abstract but it does not mean > it cannot do some usefull stuff. > > > Here is the schema of my abstract methods : > > class Interface(object): > def method(self): > # --------------------- > # some common stuff executed here > # --------------------- > print 'hello world' > # --------------------- > # here shall stand child specific stuff (empty in the interface > method) > # --------------------- > if self.__class__.method == Interface.method: > raise NotImplementedError('You should have read the f****** > manual ! You must override this method.') Okay, so I want to sub-class your Interface class. As you said, the methods in the abstract class are still useful, so in my class, I don't need any extra functionality for some methods -- I'm happy with just the "common stuff". So I use normal OO techniques and over-ride just the methods I need to over-ride: class GoodChild(Interface): # no need to over-ride method, because it does everything I want # but over-ride other methods that don't def whatever(self): print "Whatever..." return Interface.whatever() But now my class fails, with an insulting error message *wink*, and you force me to write a whole lot of crappy stupid boilerplate code: class VerboseGoodChild(Interface): # forced to over-ride methods for no good reason def method(self): return Interface.method(self) def another_method(self): return Interface.another_method(self) def yet_another_method(self): return Interface.yet_another_method(self) def still_more_methods(self): return Interface.still_more_methods(self) # Whew! That was a waste of effort. Now at last over-ride the # methods I need to: def whatever(self): print "Whatever..." return Interface.whatever() After the fourth such class, I say "Bugger this for a game of soldiers" and dump your Interface class for something else. > The reason I'd like to do so: I'll be providing the Interface, but child > classes will be overridden by others. Having a reliable error RTFM > feedback is a time saver, for me and the users. I hope I clarified my > issue. The usual way of implementing abstract base classes is to simply prohibit instantiation of the class, but allow all other inheritance. Putting useful functionality in methods, but then prohibiting subclasses from using them without jumping through hoops first, seems rather perverse to me. -- Steven From vlastimil.brom at gmail.com Fri Aug 14 14:26:00 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 14 Aug 2009 20:26:00 +0200 Subject: Natural Language Processing in Python In-Reply-To: References: Message-ID: <9fdb569a0908141126x19d2d4c5q6abc99de7e390f94@mail.gmail.com> 2009/8/14 Prateek : > Hi, > > Can somebody please provide me link to a good online resource or e- > book for doing natural language processing programming in Python. > > Thanks, > Prateek > -- > http://mail.python.org/mailman/listinfo/python-list > Maybe you could start with NLTK http://www.nltk.org/ Check the toolkit as well as the documentation. hth vbr From jeanmichel at sequans.com Fri Aug 14 14:29:03 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 20:29:03 +0200 Subject: callable virtual method In-Reply-To: <4A85A47E.308@wiggly.org> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> <4A85A47E.308@wiggly.org> Message-ID: <4A85ACEF.4090901@sequans.com> Nigel Rantor wrote: > Jean-Michel Pichavant wrote: >> >> Your solution will work, for sure. The problem is that it will dumb >> down the Base class interface, multiplying the number of methods by >> 2. This would not be an issue in many cases, in mine there's already >> too much meaningful methods in my class for me to add artificial ones. >> >> Thanks for the tip anyway. > > I suggest you reconsider. > > You asked a question and have been given a standard way of achieving > the desired outcome. > > It's common in OO to use a Template pattern like this. > > If you're not interested in finding out how loads of people have > already solved the problem then why ask? > > The methods that require overriding can be prefixed with an underscore > so that people get a hint that they are an implementation detail > rather than part of the public interface. > > I don't see your problem, other than a vague aesthetic unease. > > Regards, > > n I understand how refuting some obvious solution may look just stupid. You're right, I shouldn't have asked. By the way I'd like to know if I am I alone to find that class Stream: def start def stop def reset is better than class Stream: def start def _start def stop def _stop def reset def _reset (try to figure out with 20+ methods) What you call aesthetic may sometimes fall into readability. JM From invalid at invalid Fri Aug 14 14:38:27 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 13:38:27 -0500 Subject: Any way to adjust difflib algorithm? Message-ID: I'm trying to use difflib to compare two files, and it's not producing very useful results. When comparing two lines where only a few characters have changed, it usually seems to decide that a line was deleted/inserted/replaced rather than changed. Here's how I'm using it: #!/usr/bin/python import sys,difflib fromlines = [l.rstrip('\n') for l in open(sys.argv[1]).readlines()] tolines = [l.rstrip('\n') for l in open(sys.argv[2]).readlines()] print difflib.HtmlDiff().make_file(fromlines,tolines) In my particular usage, no lines have ever been inserted/deleted, so perhaps I should be running diffs on individual lines instead? If I do that, I can't figure out how to generate HTML output. Is there a way to tell the differ to try harder to match lines? -- Grant Edwards grante Yow! I hope something GOOD at came in the mail today so visi.com I have a REASON to live!! From davea at ieee.org Fri Aug 14 14:50:10 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 14:50:10 -0400 Subject: implementing descriptors In-Reply-To: <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> Message-ID: <4A85B1E2.10209@ieee.org> dippim wrote: > On Aug 14, 10:48 am, Dave Angel wrote: > >> dippim wrote: >> >>> On Aug 14, 2:34 am, Raymond Hettinger wrote: >>> >>>> [David] >>>> >>>>> I am new to Python and I have a question about descriptors. If I have >>>>> a class as written below, is there a way to use descriptors to be >>>>> certain that the datetime in start is always before the one in end? >>>>> >>>>> class foo(object): >>>>> def __init__(self,a =e,b = None) >>>>> self.start > >>> self.end > >>>>> from datetime import datetime >>>>> c =etime(2009,8,13,6,15,0) >>>>> d =etime(2009,8,14,12,0,0) >>>>> afoo =(c,d) >>>>> >>>>> For instance, if the following code were run, I would like to instance >>>>> of foo to switch the start and end times. >>>>> >>>>> afoo.start =etime(2010,8,13,6,15,0) >>>>> >>>>> I was thinking of using the __set__ descriptor to catch the assignment >>>>> and reverse the values if necessary, but I can't figure out how to >>>>> determine which values is being set. >>>>> >>>> You're on the right track, but it is easier to use property() than to >>>> write your own custom descriptor with __get__ and __set__. >>>> >>>> class foo(object): >>>> def __init__(self,a =e,b = None): >>>> self._start > >> self._end > >> def get_start(self): >>>> return self._start >>>> def set_start(self, value): >>>> if self._end is None or value < self._end: >>>> self._start =ue >>>> else: >>>> self._end =ue >>>> start =perty(get_start, set_start) >>>> def get_end(self): >>>> return self._end >>>> def set_end(self, value): >>>> if self._start is None or value > self._start: >>>> self._end =ue >>>> else: >>>> self._start =ue >>>> end =perty(get_end, set_end) >>>> >>>> Raymond >>>> >>> Raymond, >>> This functionality is exactly what I was looking for. Thanks! I'll >>> be using this to solve my problem. >>> >>> Now that I'm on the right track, I'm still a bit confused about how >>> __get__ and __set__ are useful. Admittedly, I don't need to >>> understand them to solve this problem, but perhaps they may be useful >>> in the future. If I wanted to solve this problem using __get__ and >>> __set__ could it be done? >>> >>> Thanks Again! >>> >> DANGER- WILL ROBINSON! >> >> Don't use this code as-is. There is a nasty surprise waiting for the >> caller when he sets start and end, and discovers that one of them gets >> thrown out, and an old value still remains. >> >> obj=oo(3, 5) >> obj.start = 8 >> obj.end = 12 >> print obj.start, obj.end >> >> will print out 3, 12. Not what the caller expected. >> > > You're right about this and I appreciate the warning, but I think what > Raymond was going for was directional accuracy without a great deal of > his time wasted on details. The explanation served the purpose of > moving me forward using property() and I'm thankful for it. > > >> Four fixes, in order of preference: >> 0) Trust your user to read and obey your docstrings. This was what JM >> was implying, by changing the names of the formal parameters. >> > > Considering I am not the sharpest knife in the drawer, I don't wish to > start a philosophical discussion about the relative aptitude and > capabilities of the people who might use a class I build. However, I > will say that as this particular requirement is imposed on this class > by the writer, shouldn't it be the writer's responsibility to enforce > it, especially, when the cost of enforcement is so low? > > >> 1) make a new method that sets both values, making these two properties >> readonly. That new method would make sure the two parameters are >> self-consistent. Making the actual values readonly can be done with a >> descriptor as well, or even a decorator. >> > > >> 2) Raise an exception in the getter methods if they're out of order >> 3) do the min/max logic on the getter methods, but I don't like that one >> at all. >> >> DaveA >> > > > I'm going to assume by "writer" you mean yourself? In other words, the interface isn't being forced upon you by someone else? So I'll continue to push for a cleaner/clearer interface. I'm not going to make any judgment about the relative abilities of you and the caller of your class. You make the final judgment call on how much you want to bulletproof your interface. But occasionally the "automatic fix" causes more problems than it solves. Now, this time you use the word "enforce," which is much different than the original implied "fix up." So I'll assume you mean it literally, that you want to detect when the caller has broken the rules, and raise an exception in that case. In either case, you need to define what "the rules" are. And normally this is done by specifying invariants. I think you're declaring an invariant that, at all times, the object has two datetime attributes, and that obj.start is no greater than obj.end. If the attributes are individually writable, and you do the swap at that time, you get into the trouble I described above. On the other hand, if you just do a raise, then your caller would still get into trouble for the same sequence of calls. So the cure is to either make a new method that explicitly changes both, or don't do the actual check for order till he tries to read the values. In that latter case, you're changing the invariant subtly, to say that if the object is temporarily in an invalid state, one cannot call any other methods or fetch values till the state has been corrected. A real pain to describe, but occasionally useful. This problem of an object temporarily being in an invalid state is not an uncommon one. But most of us have fallen into one of the pitfalls at one time or another. DaveA From wiggly at wiggly.org Fri Aug 14 14:53:37 2009 From: wiggly at wiggly.org (Nigel Rantor) Date: Fri, 14 Aug 2009 19:53:37 +0100 Subject: callable virtual method In-Reply-To: <4A85ACEF.4090901@sequans.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> <4A85A47E.308@wiggly.org> <4A85ACEF.4090901@sequans.com> Message-ID: <4A85B2B1.6090906@wiggly.org> Jean-Michel Pichavant wrote: > Nigel Rantor wrote: >> Jean-Michel Pichavant wrote: >>> >>> Your solution will work, for sure. The problem is that it will dumb >>> down the Base class interface, multiplying the number of methods by >>> 2. This would not be an issue in many cases, in mine there's already >>> too much meaningful methods in my class for me to add artificial ones. >>> >>> Thanks for the tip anyway. >> >> I suggest you reconsider. >> >> You asked a question and have been given a standard way of achieving >> the desired outcome. >> >> It's common in OO to use a Template pattern like this. >> >> If you're not interested in finding out how loads of people have >> already solved the problem then why ask? >> >> The methods that require overriding can be prefixed with an underscore >> so that people get a hint that they are an implementation detail >> rather than part of the public interface. >> >> I don't see your problem, other than a vague aesthetic unease. >> >> Regards, >> >> n > I understand how refuting some obvious solution may look just stupid. > You're right, I shouldn't have asked. I never said it seemed stupid. I was merely curious as to why you'd ask a question and ignore solutions. > By the way I'd like to know if I am I alone to find that > > class Stream: > def start > def stop > def reset > > is better than > > class Stream: > def start > def _start > def stop > def _stop > def reset > def _reset > > (try to figure out with 20+ methods) > What you call aesthetic may sometimes fall into readability. Depends on what you mean by "better". Do you mean pleasing to your eye or performs the task you want it to? Assuming you are taking the aesthetic viewpoint I think that in this case it will depend on how you set out your code. Realise that all of the underscore methods for your class are boilerplate, they simply raise an exception. They can all be at the end of the file, commented as an entire block to be left alone. Editing the main body of code is then fairly easy, and uncluttered... e.g. # # Stream class blah blah blah # class Stream: def start def stop def reset # # stubs to be over-ridden in sub-classes, add one for each # method that requires overriding. # def _start def _stop def _reset Regards, Nigel p.s. Please take this in the spirit it is offered. I'm trying to stop you from ignoring a good suggestion, not make you feel like a fool. From clp2 at rebertia.com Fri Aug 14 14:56:58 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 14 Aug 2009 14:56:58 -0400 Subject: Any way to adjust difflib algorithm? In-Reply-To: References: Message-ID: <50697b2c0908141156y2567464aod75aaf1a668c1d33@mail.gmail.com> On Fri, Aug 14, 2009 at 2:38 PM, Grant Edwards wrote: > I'm trying to use difflib to compare two files, and it's not > producing very useful results. ?When comparing two lines where > only a few characters have changed, it usually seems to decide > that a line was deleted/inserted/replaced rather than changed. > Is there a way to tell the differ to try harder to match lines? You could use a wordwise diff instead: http://www.gnu.org/software/wdiff/ Obviously that's not a pure Python solution though. Cheers, Chris -- http://blog.rebertia.com From invalid at invalid Fri Aug 14 15:18:59 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 14:18:59 -0500 Subject: Any way to adjust difflib algorithm? References: Message-ID: On 2009-08-14, Grant Edwards wrote: > I'm trying to use difflib to compare two files, and it's not > producing very useful results. When comparing two lines where > only a few characters have changed, it usually seems to decide > that a line was deleted/inserted/replaced rather than changed. [...] > In my particular usage, no lines have ever been > inserted/deleted, so perhaps I should be running diffs on > individual lines instead? If I do that, I can't figure out > how to generate HTML output. I ended up using the SequenceMatcher on individual pairs of lines and generating my own HTML based on the results of get_matching_blocks(). That produced the desired results. -- Grant Edwards grante Yow! I have a very good at DENTAL PLAN. Thank you. visi.com From davea at ieee.org Fri Aug 14 15:24:39 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 15:24:39 -0400 Subject: callable virtual method In-Reply-To: <4A85ACEF.4090901@sequans.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> <4A85A47E.308@wiggly.org> <4A85ACEF.4090901@sequans.com> Message-ID: <4A85B9F7.4010201@ieee.org> Jean-Michel Pichavant wrote: >
Nigel > Rantor wrote: >> Jean-Michel Pichavant wrote: >>> >>> Your solution will work, for sure. The problem is that it will dumb >>> down the Base class interface, multiplying the number of methods by >>> 2. This would not be an issue in many cases, in mine there's already >>> too much meaningful methods in my class for me to add artificial ones. >>> >>> Thanks for the tip anyway. >> >> I suggest you reconsider. >> >> You asked a question and have been given a standard way of achieving >> the desired outcome. >> >> It's common in OO to use a Template pattern like this. >> >> If you're not interested in finding out how loads of people have >> already solved the problem then why ask? >> >> The methods that require overriding can be prefixed with an >> underscore so that people get a hint that they are an implementation >> detail rather than part of the public interface. >> >> I don't see your problem, other than a vague aesthetic unease. >> >> Regards, >> >> n > I understand how refuting some obvious solution may look just stupid. > You're right, I shouldn't have asked. > > By the way I'd like to know if I am I alone to find that > > class Stream: > def start > def stop > def reset > > is better than > > class Stream: > def start > def _start > def stop > def _stop > def reset > def _reset > > (try to figure out with 20+ methods) > What you call aesthetic may sometimes fall into readability. > > > JM > > >
> Usually when one defines an abstract base class, one expects many people will derive from it, as opposed to only one having to write it. So if the base must be "ugly" according to some definition, so be it. Aesthetics are quite subjective. Nigel's approach has another benefit not stated, which is to keep the child class code simpler. They avoid the need to call any base class method to access the common logic. The downside is it assumes that the common logic will always be either at the beginning or always at the end of the child classes implementation. That's because the base class has hardcoded where in its implementation to call the child class method. Anyway, without arguing for or against either approach, I'd point out that you could have an extra formal parameter in the base method, which is a private signal from the child class that this is the internal call. Missing such a formal parameter would then trigger the "missing method in derived class" error message. You'd check such a parameter the same place as you're now checking the object's type. DaveA From kee at kagi.com Fri Aug 14 15:28:54 2009 From: kee at kagi.com (Kee Nethery) Date: Fri, 14 Aug 2009 12:28:54 -0700 Subject: Komodo(!) In-Reply-To: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> References: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> Message-ID: From the web site it looks like the free version does not include the debugging stuff. I've been using the paid version with the debugger functionality and I find it easy to use and incredibly nice for trying to understand what the code is doing. The built-in debugger has saved me tons of time, especially when troubleshooting CGIs. I'm using a Mac and of the Python IDEs I looked at, Komodo had the easiest to use user interface, in my opinion. Kee From kennyken747 at gmail.com Fri Aug 14 15:29:12 2009 From: kennyken747 at gmail.com (kennyken747) Date: Fri, 14 Aug 2009 12:29:12 -0700 (PDT) Subject: Something like wibiya? Message-ID: <78de82ac-72d2-472f-92ba-d0d3cb2e0b99@s31g2000yqs.googlegroups.com> Would Python be an efficient language to go about coding something like the toolbar from http://www.wibiya.com/index.php ? And then, how would I implement it? -Kenny Ledet Owner of Hotontheblock.com, Urban News Blog From davea at ieee.org Fri Aug 14 15:32:40 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 15:32:40 -0400 Subject: retrieve item from nested list given index tuple In-Reply-To: References: <02958ab2$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A85BBD8.7000409@ieee.org> Colin J. Williams wrote: >
Steven > D'Aprano wrote: >> On Fri, 14 Aug 2009 15:54:54 +0000, Alan G Isaac wrote: >> >>> `lst` is a nested list >>> >>> `tpl` is the indexes for an item in the list >> >>> What is the nice way to retrieve the item? (Speedy access is nice.) >> >> Assuming you want to do this frequently, write a helper function, >> then use it: >> >> # Untested >> def extract(nested, indexes): >> for index in indexes: >> nested = nested[index] >> return nested > > This looks OK for the first level of nesting. We are not told much > about tpl but suppose that: > > lst= [a, [b, [c, d]], [e, f]] and that we wish to retrieve d and f > from lst. tpl would need to be something like [[1, 1, 1], [2, 1]]. > > If that is the requirement, then Untested is only a step along the > road, extract could be made recursive. > > Colin W. > You missed the point: he's retrieving *an* item from a list that's nested arbitrarily. Each item in the tpl (tuple) is a simple integer. DaveA From cjwilliams43 at gmail.com Fri Aug 14 15:55:29 2009 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Fri, 14 Aug 2009 15:55:29 -0400 Subject: retrieve item from nested list given index tuple In-Reply-To: <4A85BBD8.7000409@ieee.org> References: <02958ab2$0$20647$c3e8da3@news.astraweb.com> <4A85BBD8.7000409@ieee.org> Message-ID: <4A85C131.60905@ncf.ca> Dave Angel wrote: > Colin J. Williams wrote: >>
Steven >> D'Aprano wrote: >>> On Fri, 14 Aug 2009 15:54:54 +0000, Alan G Isaac wrote: >>> >>>> `lst` is a nested list >>>> >>>> `tpl` is the indexes for an item in the list >>> >>>> What is the nice way to retrieve the item? (Speedy access is nice.) >>> >>> Assuming you want to do this frequently, write a helper function, >>> then use it: >>> >>> # Untested >>> def extract(nested, indexes): >>> for index in indexes: >>> nested = nested[index] >>> return nested >> >> This looks OK for the first level of nesting. We are not told much >> about tpl but suppose that: >> >> lst= [a, [b, [c, d]], [e, f]] and that we wish to retrieve d and f >> from lst. tpl would need to be something like [[1, 1, 1], [2, 1]]. >> >> If that is the requirement, then Untested is only a step along the >> road, extract could be made recursive. >> >> Colin W. >> > > You missed the point: he's retrieving *an* item from a list that's > nested arbitrarily. Each item in the tpl (tuple) is a simple integer. > > > DaveA Yes, you are right. Colin W. > > From mensanator at aol.com Fri Aug 14 16:07:40 2009 From: mensanator at aol.com (Mensanator) Date: Fri, 14 Aug 2009 13:07:40 -0700 (PDT) Subject: Python Permutations Problem References: Message-ID: <3ba39961-aec4-4034-beac-9552bb8a7ee6@w6g2000yqw.googlegroups.com> On Aug 14, 11:28?am, Asanka Wasala wrote: > Hi > I am developing a spell checker for my language, and I came across > solving an interesing problem. It would be great if you can suggest > me ?an optimized solution for the problem described below: > > I have certain group of letters like these: > > Group #1: c,r,b > Group #2: a,z,k > Group #3: h,t > . > . > > Letters within the same group can be substituted/replaced with the > rest of the letters in that group. > > (ie. Group #1 means letter 'c' can be replaced with either 'r' or 'b', > and letter r can be replaced with either c or b, and letter b can be > replaced with either r or c) > > A group can have upto 3 letters, and letters do not overlap between > groups. There can be upto 25 such groups. > Given a word containing above letters, (e.g. 'cat'.) I want to > generate all possible words by subsituting letters in the groups. > > eg. expected output: > > cat ? ? rat ? ? bat > czt ? ? rzt ? ? bzt > ckt ? ? rkt ? ? bkt > cah ? ? rah ? ? bah > czh ? ? rzh ? ? bzh > ckh ? ? rkh ? ? bkh > > My code is given below. But for complex words like 'cccccccccczzk' it > thows the 'maximum recursion depth exceeded' error. Therefore, can you > suggest me an optimized solution to achive the above task? Thanks in > advance. > -------------------------- > CODE------------------------------------------- > #-*- coding: UTF-8 -*- > import re > def getPermutations(word): > ? ? def getSimilarLetters(letter): > ? ? ? ? pattern=u"|c,r,b|a,z,k|h,t|" > ? ? ? ? list=[] > ? ? ? ? ptrn=re.compile("(?P\|(.?,)*?"+letter+"(,.)*?\|)") > ? ? ? ? k=ptrn.search(pattern) > ? ? ? ? if k: > ? ? ? ? ? ? letterlist=k.group("grp")[1:-1] > ? ? ? ? ? ? list=letterlist.split(",") > ? ? ? ? ? ? list.remove(letter) > ? ? ? ? ? ? return list > ? ? ? ? else: > ? ? ? ? ? ? return letter > > ? ? list=[] > > ? ? def perm(word): > ? ? ? ? posi=0 > ? ? ? ? wrd=word > ? ? ? ? for w in word: > ? ? ? ? ? ? posi=posi+1 > ? ? ? ? ? ? lst=getSimilarLetters(w) > ? ? ? ? ? ? if len(lst)>0: > ? ? ? ? ? ? ? ? for l in lst: > ? ? ? ? ? ? ? ? ? ? newwrd=wrd[:posi-1]+l+wrd[posi:] > ? ? ? ? ? ? ? ? ? ? if not (newwrd in list): > ? ? ? ? ? ? ? ? ? ? ? ? list.append(newwrd) > ? ? ? ? ? ? ? ? ? ? ? ? perm(newwrd) > > ? ? try: > ? ? ? ? perm(word) > ? ? except RuntimeError: > ? ? ? ? list=[] > ? ? ? ? list.append("error") > ? ? return list > > list=getPermutations(u"cat") > > for i in list: > ? ? print i.encode('utf-8') > --------------------------------------------END of > CODE-----------------------------------------------------------------------?------ IDLE 2.6.1 >>> import itertools as it >>> for i in it.product('crb','azk','ht'): print ''.join(i), cah cat czh czt ckh ckt rah rat rzh rzt rkh rkt bah bat bzh bzt bkh bkt From max at alcyone.com Fri Aug 14 16:10:57 2009 From: max at alcyone.com (Erik Max Francis) Date: Fri, 14 Aug 2009 13:10:57 -0700 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: Grant Edwards wrote: > On 2009-08-14, Steven D'Aprano wrote: >> What the hell >> would it actually do??? > > IIRC in C++, > > cout << "Hello world"; > > is equivalent to this in C: > > printf("Hellow world"); > > or this in Python: > > print "hellow world" Well, plus or minus newlines. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis It's hard to say what I want my legacy to be when I'm long gone. -- Aaliyah From invalid at invalid Fri Aug 14 16:13:31 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 15:13:31 -0500 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: <68-dnWijX7T2WBjXnZ2dnUVZ_t6dnZ2d@posted.visi> On 2009-08-14, Erik Max Francis wrote: > Grant Edwards wrote: >> On 2009-08-14, Steven D'Aprano wrote: >>> What the hell >>> would it actually do??? >> >> IIRC in C++, >> >> cout << "Hello world"; >> >> is equivalent to this in C: >> >> printf("Hellow world"); >> >> or this in Python: >> >> print "hellow world" > > Well, plus or minus newlines. And a few miscellaneous typos... -- Grant Edwards grante Yow! I don't understand at the HUMOUR of the THREE visi.com STOOGES!! From max at alcyone.com Fri Aug 14 16:18:04 2009 From: max at alcyone.com (Erik Max Francis) Date: Fri, 14 Aug 2009 13:18:04 -0700 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <68-dnWijX7T2WBjXnZ2dnUVZ_t6dnZ2d@posted.visi> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <68-dnWijX7T2WBjXnZ2dnUVZ_t6dnZ2d@posted.visi> Message-ID: Grant Edwards wrote: > On 2009-08-14, Erik Max Francis wrote: >> Grant Edwards wrote: >>> On 2009-08-14, Steven D'Aprano wrote: >>>> What the hell >>>> would it actually do??? >>> IIRC in C++, >>> >>> cout << "Hello world"; >>> >>> is equivalent to this in C: >>> >>> printf("Hellow world"); >>> >>> or this in Python: >>> >>> print "hellow world" >> Well, plus or minus newlines. > > And a few miscellaneous typos... ... and includes and namespaces :-). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis It's hard to say what I want my legacy to be when I'm long gone. -- Aaliyah From jeanmichel at sequans.com Fri Aug 14 16:22:10 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 22:22:10 +0200 Subject: callable virtual method In-Reply-To: <02959b54$0$20647$c3e8da3@news.astraweb.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A85C772.504@sequans.com> Steven D'Aprano wrote: > On Fri, 14 Aug 2009 18:49:26 +0200, Jean-Michel Pichavant wrote: > > >> Sorry guys (means guys *and* gals :op ), I realized I've not been able >> to describe precisely what I want to do. I'd like the base class to be >> virtual (aka abstract). However it may be abstract but it does not mean >> it cannot do some usefull stuff. >> >> >> Here is the schema of my abstract methods : >> >> class Interface(object): >> def method(self): >> # --------------------- >> # some common stuff executed here >> # --------------------- >> print 'hello world' >> # --------------------- >> # here shall stand child specific stuff (empty in the interface >> method) >> # --------------------- >> if self.__class__.method == Interface.method: >> raise NotImplementedError('You should have read the f****** >> manual ! You must override this method.') >> > > > Okay, so I want to sub-class your Interface class. As you said, the > methods in the abstract class are still useful, so in my class, I don't > need any extra functionality for some methods -- I'm happy with just the > "common stuff". So I use normal OO techniques and over-ride just the > methods I need to over-ride: > > Sometimes the base is doing cool stuff but incomplete stuff which requires knowledge only hold by the sub class. In my case the interface is a high level interface for a software that can run on multiple hardware platforms. Only the sub class has knowledge on how to operate the hardware, but no matter the hardware it still produces the same effect. Let's say I have 50 different hardwares, I'll have 50 sub classes of Interface with the 'start' method to define. It wouldn't be appropriate (OO programming)to write 50 times '_log.debug('Starting %s' % self)' in each child start method when the simple task of logging the call can be nicely handled by the base class. In the meantime, I must make sure the user, who is not a python guru in this case, has implemented the start method for his hardware, because only him knows how to effectively start this hardware. I don't want him to come to me saying, "I got no error, still my hardware does not start". You can then blame him for not reading the docs, but it will still be less expensive to throw a nice exception with an accurate feedback. [snip] > class VerboseGoodChild(Interface): > # forced to over-ride methods for no good reason > Definitely no !! This is the purpose of an interface class: to force people to write these methods. They *are* required, if they were not, they would not belong to the Interface. JM From no.email at please.post Fri Aug 14 16:23:20 2009 From: no.email at please.post (kj) Date: Fri, 14 Aug 2009 20:23:20 +0000 (UTC) Subject: Splitting on '^' ? Message-ID: Sometimes I want to split a string into lines, preserving the end-of-line markers. In Perl this is really easy to do, by splitting on the beginning-of-line anchor: @lines = split /^/, $string; But I can't figure out how to do the same thing with Python. E.g.: >>> import re >>> re.split('^', 'spam\nham\neggs\n') ['spam\nham\neggs\n'] >>> re.split('(?m)^', 'spam\nham\neggs\n') ['spam\nham\neggs\n'] >>> bol_re = re.compile('^', re.M) >>> bol_re.split('spam\nham\neggs\n') ['spam\nham\neggs\n'] Am I doing something wrong? kynn From guthrie at mum.edu Fri Aug 14 16:25:02 2009 From: guthrie at mum.edu (guthrie) Date: Fri, 14 Aug 2009 13:25:02 -0700 (PDT) Subject: py-rrdTool - install fails Message-ID: I want to do some rrd in a python cgi script, but am having trouble getting an easy install module. py-rrdTool looks good, but is distributed in c source, and is missing a header file in the distribution. Thus the install fails when it tries to reference rrd.h which is not there. Are there better rrd modules to use, or a compiled version of this, or other suggestions? -------------------------------------------------------------------------------------- building 'rrdtool._rrdtool' extension C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo / Ox /MD /W3 /GS- /DNDEBUG -I/usr/local\include "-IE:\PLang\Active Python \include" "-IE:\PLang\Active Python\PC" /Tcsrc/_rrdtoolmodule.c / Fobuild\temp.win32-2.6\Release\src/_rrdtoolmodule.obj _rrdtoolmodule.c src/_rrdtoolmodule.c(34) : fatal error C1083: Cannot open include file: 'rrd.h': No such file or directory error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN \cl.exe"' failed with exit status 2 C:\Documents and Settings\guthrie\Desktop\py-rrdtool-0.2.1> From gherron at islandtraining.com Fri Aug 14 16:36:20 2009 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 14 Aug 2009 13:36:20 -0700 Subject: Splitting on '^' ? In-Reply-To: References: Message-ID: <4A85CAC4.2000401@islandtraining.com> kj wrote: > Sometimes I want to split a string into lines, preserving the > end-of-line markers. In Perl this is really easy to do, by splitting > on the beginning-of-line anchor: > > @lines = split /^/, $string; > > But I can't figure out how to do the same thing with Python. E.g.: > > >>>> import re >>>> re.split('^', 'spam\nham\neggs\n') >>>> > ['spam\nham\neggs\n'] > >>>> re.split('(?m)^', 'spam\nham\neggs\n') >>>> > ['spam\nham\neggs\n'] > >>>> bol_re = re.compile('^', re.M) >>>> bol_re.split('spam\nham\neggs\n') >>>> > ['spam\nham\neggs\n'] > > Am I doing something wrong? > Just split on the EOL character: the "\n": re.split('\n', 'spam\nham\neggs\n') ['spam', 'ham', 'eggs', ''] The "^" and "$" characters do not match END-OF-LINE, but rather the END-OF-STRING, which was doing you no good. Gary Herron > kynn > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tycho at tycho.ws Fri Aug 14 16:38:49 2009 From: tycho at tycho.ws (Tycho Andersen) Date: Fri, 14 Aug 2009 15:38:49 -0500 Subject: Splitting on '^' ? In-Reply-To: References: Message-ID: <49b3a7400908141338v7ef43e19y9b8b813b747dc897@mail.gmail.com> On Fri, Aug 14, 2009 at 3:23 PM, kj wrote: > [snip] >>>> import re >>>> re.split('^', 'spam\nham\neggs\n') > ['spam\nham\neggs\n'] >>>> re.split('(?m)^', 'spam\nham\neggs\n') > ['spam\nham\neggs\n'] >>>> bol_re = re.compile('^', re.M) >>>> bol_re.split('spam\nham\neggs\n') > ['spam\nham\neggs\n'] > > Am I doing something wrong? Why not just: >>> re.split(r'\n', 'spam\nham\neggs') \t From lists at cheimes.de Fri Aug 14 16:39:56 2009 From: lists at cheimes.de (Christian Heimes) Date: Fri, 14 Aug 2009 22:39:56 +0200 Subject: py-rrdTool - install fails In-Reply-To: References: Message-ID: <4A85CB9C.5060305@cheimes.de> guthrie schrieb: > I want to do some rrd in a python cgi script, but am having trouble > getting an easy install module. > > py-rrdTool looks good, but is distributed in c source, and is missing > a header file in the distribution. Thus the install fails when it > tries to reference rrd.h which is not there. > > Are there better rrd modules to use, or a compiled version of this, or > other suggestions? > -------------------------------------------------------------------------------------- > building 'rrdtool._rrdtool' extension > C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo / > Ox /MD /W3 /GS- /DNDEBUG -I/usr/local\include "-IE:\PLang\Active Python > \include" "-IE:\PLang\Active Python\PC" /Tcsrc/_rrdtoolmodule.c / > Fobuild\temp.win32-2.6\Release\src/_rrdtoolmodule.obj > _rrdtoolmodule.c > src/_rrdtoolmodule.c(34) : fatal error C1083: Cannot open include > file: 'rrd.h': No such file or directory > error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN > \cl.exe"' failed with exit status 2 > > C:\Documents and Settings\guthrie\Desktop\py-rrdtool-0.2.1> rrd.h is part of the rrdtools. You need to install rrdtools plus all its dependencies. Have a lot of fun ;) Christian From lists at cheimes.de Fri Aug 14 16:39:56 2009 From: lists at cheimes.de (Christian Heimes) Date: Fri, 14 Aug 2009 22:39:56 +0200 Subject: py-rrdTool - install fails In-Reply-To: References: Message-ID: <4A85CB9C.5060305@cheimes.de> guthrie schrieb: > I want to do some rrd in a python cgi script, but am having trouble > getting an easy install module. > > py-rrdTool looks good, but is distributed in c source, and is missing > a header file in the distribution. Thus the install fails when it > tries to reference rrd.h which is not there. > > Are there better rrd modules to use, or a compiled version of this, or > other suggestions? > -------------------------------------------------------------------------------------- > building 'rrdtool._rrdtool' extension > C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo / > Ox /MD /W3 /GS- /DNDEBUG -I/usr/local\include "-IE:\PLang\Active Python > \include" "-IE:\PLang\Active Python\PC" /Tcsrc/_rrdtoolmodule.c / > Fobuild\temp.win32-2.6\Release\src/_rrdtoolmodule.obj > _rrdtoolmodule.c > src/_rrdtoolmodule.c(34) : fatal error C1083: Cannot open include > file: 'rrd.h': No such file or directory > error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN > \cl.exe"' failed with exit status 2 > > C:\Documents and Settings\guthrie\Desktop\py-rrdtool-0.2.1> rrd.h is part of the rrdtools. You need to install rrdtools plus all its dependencies. Have a lot of fun ;) Christian From gabriel at opensuse.org Fri Aug 14 16:41:36 2009 From: gabriel at opensuse.org (Gabriel) Date: Fri, 14 Aug 2009 17:41:36 -0300 Subject: Splitting on '^' ? In-Reply-To: References: Message-ID: <1adde6890908141341r29644770pc8b57a83369d4546@mail.gmail.com> On Fri, Aug 14, 2009 at 5:23 PM, kj wrote: > >>>> import re >>>> re.split('^', 'spam\nham\neggs\n') > ['spam\nham\neggs\n'] >>>> re.split('(?m)^', 'spam\nham\neggs\n') > ['spam\nham\neggs\n'] >>>> bol_re = re.compile('^', re.M) >>>> bol_re.split('spam\nham\neggs\n') > ['spam\nham\neggs\n'] > > Am I doing something wrong? > Maybe this: >>> import re >>> te = 'spam\nham\neggs\n' >>> pat = '\n' >>> re.split(pat,te) ['spam', 'ham', 'eggs', ''] -- Kind Regards From Brian.Mingus at colorado.edu Fri Aug 14 16:43:45 2009 From: Brian.Mingus at colorado.edu (Brian) Date: Fri, 14 Aug 2009 14:43:45 -0600 Subject: Splitting on '^' ? In-Reply-To: References: Message-ID: <9839a05c0908141343v37520d39i2833470f69528d95@mail.gmail.com> On Fri, Aug 14, 2009 at 2:23 PM, kj wrote: > > > Sometimes I want to split a string into lines, preserving the > end-of-line markers. In Perl this is really easy to do, by splitting > on the beginning-of-line anchor: > > @lines = split /^/, $string; > > But I can't figure out how to do the same thing with Python. E.g.: > > >>> import re > >>> re.split('^', 'spam\nham\neggs\n') > ['spam\nham\neggs\n'] > >>> re.split('(?m)^', 'spam\nham\neggs\n') > ['spam\nham\neggs\n'] > >>> bol_re = re.compile('^', re.M) > >>> bol_re.split('spam\nham\neggs\n') > ['spam\nham\neggs\n'] > > Am I doing something wrong? > > kynn > -- > http://mail.python.org/mailman/listinfo/python-list > You shouldn't use a regular expression for that. >>> from time import time >>> start=time();'spam\nham\neggs\n'.split('\n');print time()-start; ['spam', 'ham', 'eggs', ''] 4.6968460083e-05 >>> import re >>> start=time();re.split(r'\n', 'spam\nham\neggs');print time()-start; ['spam', 'ham', 'eggs'] 0.000284910202026 -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Fri Aug 14 16:44:27 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 14 Aug 2009 16:44:27 -0400 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: On Fri, Aug 14, 2009 at 12:42 PM, Douglas Alan wrote: > > P.S. Overloading "left shift" to mean "output" does indeed seem a bit > sketchy, but in 15 years of C++ programming, I've never seen it cause > any confusion or bugs. The only reason it hasn't is because people use it in "Hello World". I bet some newbie C++ programmers get confused the first time they see << used to shift. -------------- next part -------------- An HTML attachment was scrubbed... URL: From abecedarian314159 at yahoo.com Fri Aug 14 16:55:16 2009 From: abecedarian314159 at yahoo.com (William) Date: Fri, 14 Aug 2009 13:55:16 -0700 (PDT) Subject: Komodo(!) In-Reply-To: References: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> Message-ID: <553649.43098.qm@web110605.mail.gq1.yahoo.com> Personally, I rather like Wing ________________________________ From: Kee Nethery To: python-list at python.org Sent: Friday, August 14, 2009 3:28:54 PM Subject: Re: Komodo(!) >From the web site it looks like the free version does not include the debugging stuff. I've been using the paid version with the debugger functionality and I find it easy to use and incredibly nice for trying to understand what the code is doing. The built-in debugger has saved me tons of time, especially when troubleshooting CGIs. I'm using a Mac and of the Python IDEs I looked at, Komodo had the easiest to use user interface, in my opinion. Kee --http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Fri Aug 14 17:00:01 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 23:00:01 +0200 Subject: callable virtual method In-Reply-To: <4A85B9F7.4010201@ieee.org> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> <4A85A47E.308@wiggly.org> <4A85ACEF.4090901@sequans.com> <4A85B9F7.4010201@ieee.org> Message-ID: <4A85D051.2080004@sequans.com> Dave Angel wrote: > Jean-Michel Pichavant wrote: >>
Nigel >> Rantor wrote: >>> Jean-Michel Pichavant wrote: >>>> >>>> Your solution will work, for sure. The problem is that it will dumb >>>> down the Base class interface, multiplying the number of methods by >>>> 2. This would not be an issue in many cases, in mine there's >>>> already too much meaningful methods in my class for me to add >>>> artificial ones. >>>> >>>> Thanks for the tip anyway. >>> >>> I suggest you reconsider. >>> >>> You asked a question and have been given a standard way of achieving >>> the desired outcome. >>> >>> It's common in OO to use a Template pattern like this. >>> >>> If you're not interested in finding out how loads of people have >>> already solved the problem then why ask? >>> >>> The methods that require overriding can be prefixed with an >>> underscore so that people get a hint that they are an implementation >>> detail rather than part of the public interface. >>> >>> I don't see your problem, other than a vague aesthetic unease. >>> >>> Regards, >>> >>> n >> I understand how refuting some obvious solution may look just stupid. >> You're right, I shouldn't have asked. >> >> By the way I'd like to know if I am I alone to find that >> >> class Stream: >> def start >> def stop >> def reset >> >> is better than >> >> class Stream: >> def start >> def _start >> def stop >> def _stop >> def reset >> def _reset >> >> (try to figure out with 20+ methods) >> What you call aesthetic may sometimes fall into readability. >> >> >> JM >> >> >>
>> > Usually when one defines an abstract base class, one expects many > people will derive from it, as opposed to only one having to write > it. So if the base must be "ugly" according to some definition, so be > it. Aesthetics are quite subjective. > > Nigel's approach has another benefit not stated, which is to keep the > child class code simpler. They avoid the need to call any base class > method to access the common logic. The downside is it assumes that > the common logic will always be either at the beginning or always at > the end of the child classes implementation. That's because the base > class has hardcoded where in its implementation to call the child > class method. > I think this is a severe issue. You prevent the sub class from writing def foo(self): pre() Base.foo(self) post() > Anyway, without arguing for or against either approach, I'd point out > that you could have an extra formal parameter in the base method, > which is a private signal from the child class that this is the > internal call. Missing such a formal parameter would then trigger the > "missing method in derived class" error message. You'd check such a > parameter the same place as you're now checking the object's type. > > DaveA > > talking about approaches: 1/ class Interface: def foo(self): if self.__class__.foo == Interface.foo: raise NotImplementedError 2/ class Interface: def foo(self): self._foo() def _foo(sef): raise NotImplementedError Are they so different ? They both require about the same amount of extra characters, they're both readable. The second is a very classic OO layout, the first is more flexible for the sub classes and spare some method definition. This thread may live again, I cannot say but I'd like to thanks all who gave me their valuable idea on the subject, I mean it. Please don't take my skepticism as a lack of consideration. JM From lists at sourceillustrated.com Fri Aug 14 17:04:17 2009 From: lists at sourceillustrated.com (John Wells) Date: Fri, 14 Aug 2009 17:04:17 -0400 Subject: Komodo(!) In-Reply-To: References: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> Message-ID: <44dddf400908141404v2ec276bepd6399d3672ed7f49@mail.gmail.com> On Fri, Aug 14, 2009 at 3:28 PM, Kee Nethery wrote: > From the web site it looks like the free version does not include the > debugging stuff. > > I've been using the paid version with the debugger functionality and I find > it easy to use and incredibly nice for trying to understand what the code is > doing. The built-in debugger has saved me tons of time, especially when > troubleshooting CGIs. > > I'm using a Mac and of the Python IDEs I looked at, Komodo had the easiest > to use user interface, in my opinion. I've been using Netbeans with Python support and have enjoyed it. Have you tried it? It has integrated debugging, etc as well, and the price (free) is right. I'm curious how it compares to Komodo.... Thanks, John From ethan at stoneleaf.us Fri Aug 14 17:20:06 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Aug 2009 14:20:06 -0700 Subject: Splitting on '^' ? In-Reply-To: References: Message-ID: <4A85D506.7060104@stoneleaf.us> kj wrote: > > Sometimes I want to split a string into lines, preserving the > end-of-line markers. In Perl this is really easy to do, by splitting > on the beginning-of-line anchor: > > @lines = split /^/, $string; > > But I can't figure out how to do the same thing with Python. E.g.: > > >>>>import re >>>>re.split('^', 'spam\nham\neggs\n') > > ['spam\nham\neggs\n'] > >>>>re.split('(?m)^', 'spam\nham\neggs\n') > > ['spam\nham\neggs\n'] > >>>>bol_re = re.compile('^', re.M) >>>>bol_re.split('spam\nham\neggs\n') > > ['spam\nham\neggs\n'] > > Am I doing something wrong? > > kynn As you probably noticed from the other responses: No, you can't split on _and_ keep the splitby text. Looks like you'll have to roll your own. def splitat(text, sep): result = [line + sep for line in text.split(sep)] if result[-1] == sep: # either remove extra element result.pop() else: # or extra sep from last element result[-1] = result[-1][:-len(sep)] return result From python at mrabarnett.plus.com Fri Aug 14 17:22:05 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 22:22:05 +0100 Subject: Splitting on '^' ? In-Reply-To: <4A85CAC4.2000401@islandtraining.com> References: <4A85CAC4.2000401@islandtraining.com> Message-ID: <4A85D57D.40602@mrabarnett.plus.com> Gary Herron wrote: > kj wrote: >> Sometimes I want to split a string into lines, preserving the >> end-of-line markers. In Perl this is really easy to do, by splitting >> on the beginning-of-line anchor: >> >> @lines = split /^/, $string; >> >> But I can't figure out how to do the same thing with Python. E.g.: >> >> >>>>> import re >>>>> re.split('^', 'spam\nham\neggs\n') >>>>> >> ['spam\nham\neggs\n'] >> >>>>> re.split('(?m)^', 'spam\nham\neggs\n') >>>>> >> ['spam\nham\neggs\n'] >> >>>>> bol_re = re.compile('^', re.M) >>>>> bol_re.split('spam\nham\neggs\n') >>>>> >> ['spam\nham\neggs\n'] >> >> Am I doing something wrong? >> > Just split on the EOL character: the "\n": > re.split('\n', 'spam\nham\neggs\n') > ['spam', 'ham', 'eggs', ''] > > The "^" and "$" characters do not match END-OF-LINE, but rather the > END-OF-STRING, which was doing you no good. > With the MULTLINE flag "^" matches START-OF-LINE and "$" matches END-OF-LINE or END-OF-STRING. The current re module won't split on a zero-width match. From joseph.h.garvin at gmail.com Fri Aug 14 17:22:12 2009 From: joseph.h.garvin at gmail.com (Joseph Garvin) Date: Fri, 14 Aug 2009 16:22:12 -0500 Subject: bug?: python-config --ldflags gives incorrect output Message-ID: On the latest stable ubuntu: $ python-config --ldflags -L/usr/lib/python2.6/config -lpthread -ldl -lutil -lm -lpython2.6 In case the user is statically linking, I believe the -lpython2.6 should go before the other -l's. Also, -lz is missing so whenever you try to link against python you get tons of errors about missing PyZlib references. Am I right in thinking these are bugs? From piet at cs.uu.nl Fri Aug 14 17:30:45 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 14 Aug 2009 23:30:45 +0200 Subject: something like perl's Mail::GPG ? References: <4365602b-e174-4419-a1f7-44dde1b66b0c@w41g2000yqb.googlegroups.com> Message-ID: >>>>> akonsu (a) wrote: >a> hello, >a> i am looking for a module with functionality similar to that of the >a> Perl's Mail::GPG package. I need to verify multipart emails that are >a> PGP-signed. I don't know Perl's GPG package, but to verify PGP-signed stuff you can use gnupg. It doesn't have special code for mail messages, however. It is just a Pythonic wrapper facade around the gpg program. However, it doesn't do the PGP/MIME stuff, so you will have to transform the MIME messages into something that GPG understands. This isn't hard and you can find a short python script that does it on http://domnit.org/2008/03/clearmime. It describes how you can use it as a program and pipe the message through it into gpg --verify. You can also use it as a module if you rename it to clearmime.py, and use it with the recently released gnupg module. It is released under GPL. However it wouldn't be hard to write something similar yourself, for example if you want to feed it existing Message objects rather than strings. Example: import os from gnupg import GPG from clearmime import clarify msgtxt = open('testgpg.msg').read() cl = clarify(msgtxt) gpg=GPG(gnupghome = os.path.join(os.environ['HOME'], '.gnupg')) if gpg.verify(cl): print "Signature correct" else: print "Signature incorrect" -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From asmodai at in-nomine.org Fri Aug 14 17:41:50 2009 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 14 Aug 2009 23:41:50 +0200 Subject: Natural Language Processing in Python In-Reply-To: References: Message-ID: <20090814214150.GM30241@nexus.in-nomine.org> -On [20090814 18:39], Prateek (prateekkakirwar at gmail.com) wrote: >Can somebody please provide me link to a good online resource or e- >book for doing natural language processing programming in Python. http://www.nltk.org/ comes to mind. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Death comes for us all, we can only choose how to face it when it comes. From piet at cs.uu.nl Fri Aug 14 17:48:43 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 14 Aug 2009 23:48:43 +0200 Subject: Splitting on '^' ? References: Message-ID: >>>>> kj (k) wrote: >k> Sometimes I want to split a string into lines, preserving the >k> end-of-line markers. In Perl this is really easy to do, by splitting >k> on the beginning-of-line anchor: >k> @lines = split /^/, $string; >k> But I can't figure out how to do the same thing with Python. E.g.: >>>>> import re >>>>> re.split('^', 'spam\nham\neggs\n') >k> ['spam\nham\neggs\n'] >>>>> re.split('(?m)^', 'spam\nham\neggs\n') >k> ['spam\nham\neggs\n'] >>>>> bol_re = re.compile('^', re.M) >>>>> bol_re.split('spam\nham\neggs\n') >k> ['spam\nham\neggs\n'] >k> Am I doing something wrong? It says that in the doc of 're': Note that split will never split a string on an empty pattern match. For example: >>> re.split('x*', 'foo') ['foo'] >>> re.split("(?m)^$", "foo\n\nbar\n") ['foo\n\nbar\n'] -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From rurpy at yahoo.com Fri Aug 14 18:01:29 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Fri, 14 Aug 2009 15:01:29 -0700 (PDT) Subject: Splitting on '^' ? References: Message-ID: On Aug 14, 2:23?pm, kj wrote: > Sometimes I want to split a string into lines, preserving the > end-of-line markers. ?In Perl this is really easy to do, by splitting > on the beginning-of-line anchor: > > ? @lines = split /^/, $string; > > But I can't figure out how to do the same thing with Python. ?E.g.: Why not this? >>> lines = 'spam\nham\neggs\n'.splitlines (True) >>> lines ['spam\n', 'ham\n', 'eggs\n'] From pinkisntwell at gmail.com Fri Aug 14 18:24:26 2009 From: pinkisntwell at gmail.com (pinkisntwell) Date: Fri, 14 Aug 2009 15:24:26 -0700 (PDT) Subject: Calling parent constructor with different argument list Message-ID: <174a97e2-5ef4-47dc-9a60-ad7598f276cb@h21g2000yqa.googlegroups.com> class Vertex(tuple): pass class Positioned_Vertex(Vertex): def __init__(self, a, b): Vertex.__init__(a) a=Positioned_Vertex((0,0,0), 1) This gives: TypeError: tuple() takes at most 1 argument (2 given) It looks like the explicit call to Vertex.__init__ is never made and Vertex.__init__ is implicitly called when a Positioned_Vertex is created. Is there a way to work around this and call the constructor with the intended argument list? From lists at cheimes.de Fri Aug 14 18:25:00 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 15 Aug 2009 00:25:00 +0200 Subject: callable virtual method In-Reply-To: <4A85D051.2080004@sequans.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> <4A85A47E.308@wiggly.org> <4A85ACEF.4090901@sequans.com> <4A85B9F7.4010201@ieee.org> <4A85D051.2080004@sequans.com> Message-ID: Jean-Michel Pichavant wrote: > talking about approaches: > > 1/ > class Interface: > def foo(self): > if self.__class__.foo == Interface.foo: > raise NotImplementedError > > 2/ > class Interface: > def foo(self): > self._foo() > > def _foo(sef): > raise NotImplementedError Please don't call it an interface when it's really an abstract base class. And abstract base classes are probably the solution the OP is looking for, http://docs.python.org/library/abc.html Christian From davigier at googlemail.com Fri Aug 14 18:27:40 2009 From: davigier at googlemail.com (David) Date: Fri, 14 Aug 2009 15:27:40 -0700 (PDT) Subject: How to launch a function at regular time intervals ? References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> <18ac9f9a-0cf2-409c-82b3-ea068f21dbf7@k19g2000yqn.googlegroups.com> Message-ID: With your help, Franck, I think I finally got it to work. This is how I did it: # In the main program, launch the 2 threads CStoreData and CTransferData, which will run indefinitely until they are stopped (if the threads were launched inside the while loop, there would be an infinitely growing number of threads CStoreData all doing the same thing, same for CTransferData) func_store_data = CStoreData() func_store_data.start() func_transfer_data = CTransferData() func_transfer_data.start() # While loop, just to keep the threads running until they are stopped at the end of the program. If there wasn't a while loop, the threads would be stopped right after they are launched. The while loop separates the "start" of the threads from the "stop" of the threads while 1 if end_condition: # terminate program break # break out of while loop # Stop all running threads at end func_store_data.stop() func_store_data.join() func_transfer_data.stop() func_transfer_data.join() Again thanks a lot to all of you for your precious help. David From davigier at googlemail.com Fri Aug 14 18:27:55 2009 From: davigier at googlemail.com (David) Date: Fri, 14 Aug 2009 15:27:55 -0700 (PDT) Subject: How to launch a function at regular time intervals ? References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> <18ac9f9a-0cf2-409c-82b3-ea068f21dbf7@k19g2000yqn.googlegroups.com> Message-ID: <7e7f762d-6727-4756-9e5e-72b894f9a9fb@o32g2000yqm.googlegroups.com> With your help, Franck, I think I finally got it to work. This is how I did it: # In the main program, launch the 2 threads CStoreData and CTransferData, which will run indefinitely until they are stopped (if the threads were launched inside the while loop, there would be an infinitely growing number of threads CStoreData all doing the same thing, same for CTransferData) func_store_data = CStoreData() func_store_data.start() func_transfer_data = CTransferData() func_transfer_data.start() # While loop, just to keep the threads running until they are stopped at the end of the program. If there wasn't a while loop, the threads would be stopped right after they are launched. The while loop separates the "start" of the threads from the "stop" of the threads while 1 if end_condition: # terminate program break # break out of while loop # Stop all running threads at end func_store_data.stop() func_store_data.join() func_transfer_data.stop() func_transfer_data.join() Again thanks a lot to all of you for your precious help. David From davigier at googlemail.com Fri Aug 14 18:28:06 2009 From: davigier at googlemail.com (David) Date: Fri, 14 Aug 2009 15:28:06 -0700 (PDT) Subject: How to launch a function at regular time intervals ? References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> <18ac9f9a-0cf2-409c-82b3-ea068f21dbf7@k19g2000yqn.googlegroups.com> Message-ID: <97ddbf4b-0a80-4ef3-88e6-73b02208ef13@w41g2000yqb.googlegroups.com> With your help, Franck, I think I finally got it to work. This is how I did it: # In the main program, launch the 2 threads CStoreData and CTransferData, which will run indefinitely until they are stopped (if the threads were launched inside the while loop, there would be an infinitely growing number of threads CStoreData all doing the same thing, same for CTransferData) func_store_data = CStoreData() func_store_data.start() func_transfer_data = CTransferData() func_transfer_data.start() # While loop, just to keep the threads running until they are stopped at the end of the program. If there wasn't a while loop, the threads would be stopped right after they are launched. The while loop separates the "start" of the threads from the "stop" of the threads while 1 if end_condition: # terminate program break # break out of while loop # Stop all running threads at end func_store_data.stop() func_store_data.join() func_transfer_data.stop() func_transfer_data.join() Again thanks a lot to all of you for your precious help. David From python at mrabarnett.plus.com Fri Aug 14 18:30:52 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 23:30:52 +0100 Subject: Splitting on '^' ? In-Reply-To: <4A85D506.7060104@stoneleaf.us> References: <4A85D506.7060104@stoneleaf.us> Message-ID: <4A85E59C.6020001@mrabarnett.plus.com> Ethan Furman wrote: > kj wrote: >> >> Sometimes I want to split a string into lines, preserving the >> end-of-line markers. In Perl this is really easy to do, by splitting >> on the beginning-of-line anchor: >> >> @lines = split /^/, $string; >> >> But I can't figure out how to do the same thing with Python. E.g.: >> >> >>>>> import re >>>>> re.split('^', 'spam\nham\neggs\n') >> >> ['spam\nham\neggs\n'] >> >>>>> re.split('(?m)^', 'spam\nham\neggs\n') >> >> ['spam\nham\neggs\n'] >> >>>>> bol_re = re.compile('^', re.M) >>>>> bol_re.split('spam\nham\neggs\n') >> >> ['spam\nham\neggs\n'] >> >> Am I doing something wrong? >> >> kynn > > As you probably noticed from the other responses: No, you can't split > on _and_ keep the splitby text. > You _can_ split and keep what you split on: >>> re.split("(x)", "abxcd") ['ab', 'x', 'cd'] You _can't_ split on a zero-width match: >>> re.split("(x*)", "abxcd") ['ab', 'x', 'cd'] but you can use re.sub to replace zero-width matches with something that's not zero-width and then split on that (best with str.split): >>> re.sub("(x*)", "@", "abxcd") '@a at b@c at d@' >>> re.sub("(x*)", "@", "abxcd").split("@") ['', 'a', 'b', 'c', 'd', ''] From martin at v.loewis.de Fri Aug 14 18:40:56 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 15 Aug 2009 00:40:56 +0200 Subject: coding for multiple versions of python In-Reply-To: References: <4A84F913.9090901@v.loewis.de> Message-ID: <4a85e7f8$0$2427$9b622d9e@news.freenet.de> >> Specifically, put the source code into /net/source/python/foo/*.py. >> Then, on each system, put symlinks to all .py files into >> lib/site-packages/foo. Then Python will place the .pyc files next >> to the symlinks, not next to the actual .py files. > > Why would he need two sets of .py files? As Dave explains: So that the Python 2.4 installation on HP can write its own .pyc files on disk next to the source files, and Python 2.6 can write its .pyc files next to the sources on Linux. Regards, Martin From python at mrabarnett.plus.com Fri Aug 14 18:40:59 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 23:40:59 +0100 Subject: How to launch a function at regular time intervals ? In-Reply-To: References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> <18ac9f9a-0cf2-409c-82b3-ea068f21dbf7@k19g2000yqn.googlegroups.com> Message-ID: <4A85E7FB.4040507@mrabarnett.plus.com> David wrote: > With your help, Franck, I think I finally got it to work. This is how > I did it: > > # In the main program, launch the 2 threads CStoreData and > CTransferData, which will run indefinitely until they are stopped (if > the threads were launched inside the while loop, there would be an > infinitely growing number of threads CStoreData all doing the same > thing, same for CTransferData) > > func_store_data = CStoreData() > func_store_data.start() > > func_transfer_data = CTransferData() > func_transfer_data.start() > > # While loop, just to keep the threads running until they are stopped > at the end of the program. If there wasn't a while loop, the threads > would be stopped right after they are launched. The while loop > separates the "start" of the threads from the "stop" of the threads > > while 1 > if end_condition: # terminate program > break # break out of while loop > You might want to insert a sleep or something in there, otherwise you'll be it'll consume a lot of CPU time doing nothing (a 'busy wait'). > # Stop all running threads at end > > func_store_data.stop() > func_store_data.join() > > func_transfer_data.stop() > func_transfer_data.join() > > > Again thanks a lot to all of you for your precious help. > From martin at v.loewis.de Fri Aug 14 18:42:54 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 15 Aug 2009 00:42:54 +0200 Subject: coding for multiple versions of python In-Reply-To: References: <4A84F913.9090901@v.loewis.de> Message-ID: <4A85E86E.6070805@v.loewis.de> > He's assuming: > 1) an OS that supports symlinks > 2) two versions of Python on same system > 3) one set of pure-python sources that want to stay in synch for both > versions. Actually, the OP said he has HP(-UX, I assume), and Linux, so it would be two versions of Python on different systems - I also assume that he has an NFS server that both can mount (or that one machine can NFS mount the other). Regards, Martin From REMOVEmagicus23THIS at gmail.com Fri Aug 14 18:46:46 2009 From: REMOVEmagicus23THIS at gmail.com (magicus) Date: Fri, 14 Aug 2009 22:46:46 +0000 (UTC) Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: On Fri, 14 Aug 2009 19:57:17 +0200, Jean-Michel Pichavant wrote: > vippstar wrote: >> On Aug 14, 8:25 pm, fortunatus wrote: >> >>> On Aug 14, 1:01 pm, vippstar wrote: >>> >>> >>>> Why would you fill your website with junk? >>>> >>> The OP made it clear: >>> >>> >>>> Just wanted to express some frustration with whitespace-mode. >>>> >>>> >> You took my question out of context and answered it. I read the >> article, it's not like I missed any of it. Plus, it's not a real >> answer. "Because I wanted to". Why did you? Why would you? >> > FYI, Xah Lee is a well known BTFL (Benevolent Troller For Life), you > shouldn't argue about one of his post. Argue??? He is kill filed here wherever I find him. Life is too short to deal w/ idiots. ciao, f -- "Properly read, the Bible is the most potent force for atheism ever conceived." -- Isaac Asimov From Brian.Mingus at colorado.edu Fri Aug 14 18:57:13 2009 From: Brian.Mingus at colorado.edu (Brian) Date: Fri, 14 Aug 2009 16:57:13 -0600 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode In-Reply-To: References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: <9839a05c0908141557s4008e896nc5ddece003469596@mail.gmail.com> On Fri, Aug 14, 2009 at 4:46 PM, magicus wrote: > On Fri, 14 Aug 2009 19:57:17 +0200, Jean-Michel Pichavant > wrote: > > > vippstar wrote: > >> On Aug 14, 8:25 pm, fortunatus wrote: > >> > >>> On Aug 14, 1:01 pm, vippstar wrote: > >>> > >>> > >>>> Why would you fill your website with junk? > >>>> > >>> The OP made it clear: > >>> > >>> > >>>> Just wanted to express some frustration with whitespace-mode. > >>>> > >>>> > >> You took my question out of context and answered it. I read the > >> article, it's not like I missed any of it. Plus, it's not a real > >> answer. "Because I wanted to". Why did you? Why would you? > >> > > FYI, Xah Lee is a well known BTFL (Benevolent Troller For Life), you > > shouldn't argue about one of his post. > > Argue??? He is kill filed here wherever I find him. > > Life is too short to deal w/ idiots. > > ciao, > f > The funny thing about his rant (ie - that it is irrelevant) is that emacs python mode has always notified me that my indentations were inconsistent by highlighting the errant ones in blue. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Fri Aug 14 19:13:56 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Aug 2009 16:13:56 -0700 Subject: Splitting on '^' ? In-Reply-To: <4A85E59C.6020001@mrabarnett.plus.com> References: <4A85D506.7060104@stoneleaf.us> <4A85E59C.6020001@mrabarnett.plus.com> Message-ID: <4A85EFB4.3020008@stoneleaf.us> MRAB wrote: > Ethan Furman wrote: > >> kj wrote: >> >>> >>> Sometimes I want to split a string into lines, preserving the >>> end-of-line markers. In Perl this is really easy to do, by splitting >>> on the beginning-of-line anchor: >>> >>> @lines = split /^/, $string; >>> >>> But I can't figure out how to do the same thing with Python. E.g.: >>> >>> >>>>>> import re >>>>>> re.split('^', 'spam\nham\neggs\n') >>> >>> >>> ['spam\nham\neggs\n'] >>> >>>>>> re.split('(?m)^', 'spam\nham\neggs\n') >>> >>> >>> ['spam\nham\neggs\n'] >>> >>>>>> bol_re = re.compile('^', re.M) >>>>>> bol_re.split('spam\nham\neggs\n') >>> >>> >>> ['spam\nham\neggs\n'] >>> >>> Am I doing something wrong? >>> >>> kynn >> >> >> As you probably noticed from the other responses: No, you can't split >> on _and_ keep the splitby text. >> > You _can_ split and keep what you split on: > > >>> re.split("(x)", "abxcd") > ['ab', 'x', 'cd'] > > You _can't_ split on a zero-width match: > > >>> re.split("(x*)", "abxcd") > ['ab', 'x', 'cd'] > > but you can use re.sub to replace zero-width matches with something > that's not zero-width and then split on that (best with str.split): > > >>> re.sub("(x*)", "@", "abxcd") > '@a at b@c at d@' > >>> re.sub("(x*)", "@", "abxcd").split("@") > ['', 'a', 'b', 'c', 'd', ''] Wow! I stand corrected, although I'm in danger of falling over from the dizziness! :) As impressive as that is, I don't think it does what the OP is looking for. rurpy reminded us (or at least me ;) of .splitlines(), which seems to do exactly what the OP is looking for. I do take some comfort that my little snippet works for more than newlines alone, although I'm not aware of any other use-cases. :( ~Ethan~ Oh, hey, how about this? re.compile('(^[^\n]*\n?)', re.M).findall('text\ntext\ntext) Although this does give me an extra blank segment at the end... oh well. From breamoreboy at yahoo.co.uk Fri Aug 14 19:19:40 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Aug 2009 00:19:40 +0100 Subject: Calling parent constructor with different argument list In-Reply-To: <174a97e2-5ef4-47dc-9a60-ad7598f276cb@h21g2000yqa.googlegroups.com> References: <174a97e2-5ef4-47dc-9a60-ad7598f276cb@h21g2000yqa.googlegroups.com> Message-ID: pinkisntwell wrote: > class Vertex(tuple): > pass > > class Positioned_Vertex(Vertex): > > def __init__(self, a, b): def __init__(self, a): # just take out b > Vertex.__init__(a) > > a=Positioned_Vertex((0,0,0), 1) a=Positioned_Vertex( ( (0,0,0), 1) ) # and add a pair of brackets print a > > This gives: > > TypeError: tuple() takes at most 1 argument (2 given) > > It looks like the explicit call to Vertex.__init__ is never made and > Vertex.__init__ is implicitly called when a Positioned_Vertex is > created. Is there a way to work around this and call the constructor > with the intended argument list? Simplest way to get it to work is above using Python 2.6.2 on Windows. I'm sure there are variations depending on your use case, but I'll leave that to the experts. -- Kindest regards. Mark Lawrence. From arphaksad at gmail.com Fri Aug 14 20:05:40 2009 From: arphaksad at gmail.com (naaman) Date: Fri, 14 Aug 2009 17:05:40 -0700 (PDT) Subject: fileinput References: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> Message-ID: <4a237015-1b6d-418c-9bce-2f8e144e50d1@s15g2000yqs.googlegroups.com> On Aug 13, 11:41?pm, naaman wrote: > On Aug 13, 7:50?am, Dave Angel wrote: > > > > > naaman wrote: > > > On Aug 12, 1:35 pm, Dave Angel wrote: > > > >> naaman wrote: > > > >>> I'm writing my first Python script and > > >>> I want to use fileinput to open a file in r+ mode. > > >>> Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > > >>> ANy ideas? > > > >>> Need to find and overwrite a line in a file several times. > > >>> I can do it using open and seek() etc. but was wondering if I can use > > >>> fileinput. > > > >>> thanks; > > > >> I haven't used it, but check out the 'inplace' keyword parameter. > > > >> DaveA > > > > I've only Python for a week so I'm not sure what inplace does > > > You should read the docs for it > > ? ? (http://www.python.org/doc/2.6.2/library/fileinput.html?), > > but it's not very clear to me either ?So I dug up an example on the web: > > ? ? ?(ref: ?http://effbot.org/librarybook/fileinput.htm) > > > import fileinput, sys > > > for line in fileinput.input(inplace=1): > > ? ? # /convert Windows/DOS text files to Unix files/ > > ? ? if line[-2:] == "\r\n": > > ? ? ? ? line = line[:-2] + "\n" > > ? ? sys.stdout.write(line) > > > The inplace argument tells it to create a new file with the same name as > > the original (doing all the necessary nonsense with using a scratch > > file, and renaming/deleting) for each file processed. ?Stdout is pointed > > to that new version of the file. ?Notice that you have to explicitly > > write everything you want to wind up in the file -- if a given line is > > to remain unchanged, you just write "line" directly. > > > If you're new to Python, I do not recommend trying to do open/seek to > > update a text file in place, especially if you're in DOS. ?There are > > lots of traps. ?the inplace method of fileinput avoids these by > > implicitly creating temp files and handling the details for you, which > > probably works great if you're dealing with text, in order. > > > DaveA > > here's the solution > > import fileinput, sys > > for line in fileinput.input(sys.argv[1],inplace=1): > ? ? if (line[:-1]==r'drew'): > ? ? ? ? line=line.replace(line,"fancy dog") > ? ? sys.stdout.write(line) > > I want to replace drew in my input file with fancy dog. > Tested with this input file > angel > heaven > flying monkees > lazy dogs > drew > blue sky > veritas > > and got this > angel > heaven > flying monkees > lazy dogs > fancy dog > blue sky > veritas > > So drew was replaced with fancy dog. > Thanks to your inputs I got this solved. :-)) oops there should be a +"\n" after "fancy dog" line=line.replace(line,"fancy dog"+"\n") From gagsl-py2 at yahoo.com.ar Fri Aug 14 20:15:52 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Aug 2009 21:15:52 -0300 Subject: Calling parent constructor with different argument list References: <174a97e2-5ef4-47dc-9a60-ad7598f276cb@h21g2000yqa.googlegroups.com> Message-ID: En Fri, 14 Aug 2009 19:24:26 -0300, pinkisntwell escribi?: > class Vertex(tuple): > pass > > class Positioned_Vertex(Vertex): > > def __init__(self, a, b): > Vertex.__init__(a) > > a=Positioned_Vertex((0,0,0), 1) > > This gives: > > TypeError: tuple() takes at most 1 argument (2 given) > > It looks like the explicit call to Vertex.__init__ is never made and > Vertex.__init__ is implicitly called when a Positioned_Vertex is > created. Is there a way to work around this and call the constructor > with the intended argument list? The tuple constructor (like numbers, strings, and other immutable objects) never calls __init__. You have to override __new__ instead: py> class Point3D(tuple): ... def __new__(cls, x, y, z): ... obj = super(Point3D, cls).__new__(cls, (x,y,z)) ... return obj ... py> a = Point3D(10, 20, 30) py> a (10, 20, 30) py> type(a) See http://docs.python.org/reference/datamodel.html#basic-customization -- Gabriel Genellina From candide at free.invalid Fri Aug 14 20:22:57 2009 From: candide at free.invalid (candide) Date: Sat, 15 Aug 2009 02:22:57 +0200 Subject: Splitting a string into substrings of equal size Message-ID: <4a85ffe2$0$24643$426a34cc@news.free.fr> Suppose you need to split a string into substrings of a given size (except possibly the last substring). I make the hypothesis the first slice is at the end of the string. A typical example is provided by formatting a decimal string with thousands separator. What is the pythonic way to do this ? For my part, i reach to this rather complicated code: # ---------------------- def comaSep(z,k=3, sep=','): z=z[::-1] x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] return sep.join(x) # Test for z in ["75096042068045", "509", "12024", "7", "2009"]: print z+" --> ", comaSep(z) # ---------------------- outputting : 75096042068045 --> 75,096,042,068,045 509 --> 509 12024 --> 12,024 7 --> 7 2009 --> 2,009 Thanks From gagsl-py2 at yahoo.com.ar Fri Aug 14 21:00:52 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Aug 2009 22:00:52 -0300 Subject: Splitting a string into substrings of equal size References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: En Fri, 14 Aug 2009 21:22:57 -0300, candide escribi?: > Suppose you need to split a string into substrings of a given size > (except > possibly the last substring). I make the hypothesis the first slice is > at the > end of the string. > A typical example is provided by formatting a decimal string with > thousands > separator. > > > What is the pythonic way to do this ? py> import locale py> locale.setlocale(locale.LC_ALL, '') 'Spanish_Argentina.1252' py> locale.format("%d", 75096042068045, True) '75.096.042.068.045' :) > For my part, i reach to this rather complicated code: Mine isn't very simple either: py> def genparts(z): ... n = len(z) ... i = n%3 ... if i: yield z[:i] ... for i in xrange(i, n, 3): ... yield z[i:i+3] ... py> ','.join(genparts("75096042068045")) '75,096,042,068,045' -- Gabriel Genellina From pfeldman at verizon.net Fri Aug 14 21:25:45 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Fri, 14 Aug 2009 18:25:45 -0700 (PDT) Subject: Python 'for' loop is memory inefficient Message-ID: <24980842.post@talk.nabble.com> I wrote the following correct but inefficient test of primality for purposes of demonstrating that the simplest algorithm is often not the most efficient. But, when I try to run the following code with a value of n that is large enough to produce a significant amount of running time, I get an out-of-memory error! def is_prime(n): for j in range(2,n): if (n % j) == 0: return False return True It seems as though Python is actually expanding range(2,n) into a list of numbers, even though this is incredibly wasteful of memory. There should be a looping mechanism that generates the index variable values incrementally as they are needed. -- View this message in context: http://www.nabble.com/Python-%27for%27-loop-is-memory-inefficient-tp24980842p24980842.html Sent from the Python - python-list mailing list archive at Nabble.com. From ethan at stoneleaf.us Fri Aug 14 21:30:39 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Aug 2009 18:30:39 -0700 Subject: implementing descriptors In-Reply-To: <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> Message-ID: <4A860FBF.6070709@stoneleaf.us> dippim wrote: > On Aug 14, 10:48 am, Dave Angel wrote: > >>dippim wrote: >> >>>On Aug 14, 2:34 am, Raymond Hettinger wrote: >> >>>>[David] >> >>>>>I am new to Python and I have a question about descriptors. If I have >>>>>a class as written below, is there a way to use descriptors to be >>>>>certain that the datetime in start is always before the one in end? >> >>>>>class foo(object): >>>>> def __init__(self,a =one,b = None) >>>>> self.start = >>>>> self.end = >> >>>>>from datetime import datetime >>>>>c =atetime(2009,8,13,6,15,0) >>>>>d =atetime(2009,8,14,12,0,0) >>>>>afoo =oo(c,d) >> >>>>>For instance, if the following code were run, I would like to instance >>>>>of foo to switch the start and end times. >> >>>>>afoo.start =atetime(2010,8,13,6,15,0) >> >>>>>I was thinking of using the __set__ descriptor to catch the assignment >>>>>and reverse the values if necessary, but I can't figure out how to >>>>>determine which values is being set. >> >>>>You're on the right track, but it is easier to use property() than to >>>>write your own custom descriptor with __get__ and __set__. >> >>>>class foo(object): >>>> def __init__(self,a =one,b = None): >>>> self._start = >>>> self._end = >>>> def get_start(self): >>>> return self._start >>>> def set_start(self, value): >>>> if self._end is None or value < self._end: >>>> self._start =alue >>>> else: >>>> self._end =alue >>>> start =roperty(get_start, set_start) >>>> def get_end(self): >>>> return self._end >>>> def set_end(self, value): >>>> if self._start is None or value > self._start: >>>> self._end =alue >>>> else: >>>> self._start =alue >>>> end =roperty(get_end, set_end) >> >>>>Raymond >> >>>Raymond, >>> This functionality is exactly what I was looking for. Thanks! I'll >>>be using this to solve my problem. >> >>> Now that I'm on the right track, I'm still a bit confused about how >>>__get__ and __set__ are useful. Admittedly, I don't need to >>>understand them to solve this problem, but perhaps they may be useful >>>in the future. If I wanted to solve this problem using __get__ and >>>__set__ could it be done? >> >>>Thanks Again! >> >>DANGER- WILL ROBINSON! >> >>Don't use this code as-is. There is a nasty surprise waiting for the >>caller when he sets start and end, and discovers that one of them gets >>thrown out, and an old value still remains. >> >>obj= foo(3, 5) >>obj.start = 8 >>obj.end = 12 >>print obj.start, obj.end >> >>will print out 3, 12. Not what the caller expected. > > > You're right about this and I appreciate the warning, but I think what > Raymond was going for was directional accuracy without a great deal of > his time wasted on details. The explanation served the purpose of > moving me forward using property() and I'm thankful for it. > > >>Four fixes, in order of preference: >>0) Trust your user to read and obey your docstrings. This was what JM >>was implying, by changing the names of the formal parameters. > > > Considering I am not the sharpest knife in the drawer, I don't wish to > start a philosophical discussion about the relative aptitude and > capabilities of the people who might use a class I build. However, I > will say that as this particular requirement is imposed on this class > by the writer, shouldn't it be the writer's responsibility to enforce > it, especially, when the cost of enforcement is so low? > > >>1) make a new method that sets both values, making these two properties >>readonly. That new method would make sure the two parameters are >>self-consistent. Making the actual values readonly can be done with a >>descriptor as well, or even a decorator. > > >>2) Raise an exception in the getter methods if they're out of order >>3) do the min/max logic on the getter methods, but I don't like that one >>at all. >> >>DaveA > I am in complete agreement with DaveA on this issue -- if you want the invariant, then have a routine that set's both at once. The head-aches it would cause me, at least, to have to gyrate around whether I was making the object later or earlier in time (having to swap the order I assign stand and end, assuming I even know whether I'm going forward or backward without further checking... argh!) would quite possibly cause me to choose some other routine instead. How about something like (untested): def set(self, start=None, end=None): if start is None: start = self.start if end is None: end = self.end if start > end: raise ValueError('blah blah') self.start = start self.end = end This way you could still set only one, but have bounds checking in place. ~Ethan~ From apt.shansen at gmail.com Fri Aug 14 21:30:43 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Fri, 14 Aug 2009 18:30:43 -0700 Subject: Python 'for' loop is memory inefficient In-Reply-To: <24980842.post@talk.nabble.com> References: <24980842.post@talk.nabble.com> Message-ID: <7a9c25c20908141830i5c72e0c1i66343c0e9017f0ca@mail.gmail.com> > > It seems as though Python is actually expanding range(2,n) into a list of > numbers, even though this is incredibly wasteful of memory. There should be > a looping mechanism that generates the index variable values incrementally > as they are needed. This has nothing to do with Python's for loop (and saying the loop construct itself is memory inefficient makes me blink in confusion): but you've isolated the problem precisely all on your own. range() is defined as returning a list. Thus, it constructs the list all at once. xrange() returns an iterator, and generates the values on the fly. In Python 3, this was changed so range returns an iterator, and to get a list you do list(range(2,n)). --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Fri Aug 14 21:36:14 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Aug 2009 18:36:14 -0700 Subject: Programming by Contract In-Reply-To: References: <4A7A15CD.9090306@stoneleaf.us> <4A81C6B8.7010605@stoneleaf.us> Message-ID: <4A86110E.5050201@stoneleaf.us> Charles Yeomans wrote: > > On Aug 14, 2009, at 12:09 AM, Scott David Daniels wrote: > >> Charles Yeomans wrote: >> >>> On Aug 11, 2009, at 3:30 PM, Ethan Furman wrote: >> >>>> Ethan Furman wrote: >> >>>>> Greetings! >> >>>>> I have seen posts about the assert statement and PbC (or maybe it >>>>> was DbC), and I just took a very brief look at pycontract >>>>> (http://www.wayforward.net/pycontract/) and now I have at least one >>>>> question: Is this basically another way of thinking about unit >>>>> testing, or is the idea of PbC more along the lines of *always* >>>>> checking the input/output of functions to ensure they are correct? >>>>> (*Contstant vigilance!* as Prof Moody would say ;) >> >>>>> I know asserts can be turned off, so they obviously won't work for >>>>> the latter case, and having seen the sample of pycontract it seems >>>>> it only does its thing during debugging. >> >>>>> So is Design (Programming) by Contract a fancy way of saying >>>>> "Document your inputs/outputs!" or is there more to it? >> >>>>> ~Ethan~ >> >>>> >>>> Hmmm... >> >>>> >>>> Well, from the (apparently) complete lack of interest, I shall take >>>> away the (better?) documentation ideas and unit testing ideas, and >>>> not worry about the rest. :) >> >>>> >>>> >>> Design by contract is complementary to unit testing (I notice that >>> the author of PEP 316 appears confused about this). DbC is, roughly >>> speaking, about explicit allocation of responsibility. Consider this >>> contrived example. >> >>> def foo(s): >> >>> require(s is not None) >> >>> //code >> >>> ensure(hasattr(returnValue, '__iter__')) >> >> >> yo might want two flags, REQUIRE_OFF, and ENSURE_ON that control >> testing, and change the code above to: >> require(REQUIRE_OFF or s is not None) >> //code >> ensure(ENSURE_OFF or hasattr(returnValue, '__iter__')) >> >> Python has no good way to turn off argument calculation by >> manipulating function definition (at least that I know of). >> > > For this purpose, it had occurred to me to do something like the following. > > def require(condition): > if condition: > return True > else: > raise PreconditionFailure > > > def foo(s): > assert require(s is not None) > > > Then it occurred to me to actually read the assert documentation, where > I learned that one can pass a second expression to assert. So instead > one might write > > assert precondition, "PreconditionFailure" > > though I think I prefer the former. > > > Charles Yeomans > And in either case, since such checks can have a *huge* impact on performance, it is good that asserts can be disabled with the -O optimize switch. So it's also good that the original design for DbC was an _understanding_ of who is responsible for what, as opposed to _code_ to actually enforce it. ~Ethan~ From breamoreboy at yahoo.co.uk Fri Aug 14 21:38:18 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Aug 2009 02:38:18 +0100 Subject: Python 'for' loop is memory inefficient In-Reply-To: <24980842.post@talk.nabble.com> References: <24980842.post@talk.nabble.com> Message-ID: Dr. Phillip M. Feldman wrote: > I wrote the following correct but inefficient test of primality for purposes > of demonstrating that the simplest algorithm is often not the most > efficient. But, when I try to run the following code with a value of n that > is large enough to produce a significant amount of running time, I get an > out-of-memory error! > > def is_prime(n): > for j in range(2,n): > if (n % j) == 0: return False > return True > > It seems as though Python is actually expanding range(2,n) into a list of > numbers, even though this is incredibly wasteful of memory. There should be > a looping mechanism that generates the index variable values incrementally > as they are needed. I have a strong suspicion that you will find hints in the Python documentation that this has already been addressed. Perhaps you could try reading before posting? -- Kindest regards. Mark Lawrence. From ethan at stoneleaf.us Fri Aug 14 21:43:42 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Aug 2009 18:43:42 -0700 Subject: Python 'for' loop is memory inefficient In-Reply-To: <24980842.post@talk.nabble.com> References: <24980842.post@talk.nabble.com> Message-ID: <4A8612CE.7080700@stoneleaf.us> Dr. Phillip M. Feldman wrote: > I wrote the following correct but inefficient test of primality for purposes > of demonstrating that the simplest algorithm is often not the most > efficient. But, when I try to run the following code with a value of n that > is large enough to produce a significant amount of running time, I get an > out-of-memory error! > > def is_prime(n): > for j in range(2,n): > if (n % j) == 0: return False > return True > > It seems as though Python is actually expanding range(2,n) into a list of > numbers, even though this is incredibly wasteful of memory. There should be > a looping mechanism that generates the index variable values incrementally > as they are needed. You already have an answer to the range issue, so I will only add that putting a loop inside another loop is a decent way to expand the time taken. I will also observe that if you were to stop programming whatever language you are more familiar with in Python, and start programming Python in Python, you'll have an easier time of it. The Dive Into Python is an excellent start for that. ~Ethan~ From tjreedy at udel.edu Fri Aug 14 21:53:13 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 15 Aug 2009 10:53:13 +0900 Subject: implementing descriptors In-Reply-To: <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> Message-ID: dippim wrote: > will say that as this particular requirement is imposed on this class > by the writer, shouldn't it be the writer's responsibility to enforce > it, especially, when the cost of enforcement is so low? I would say that it is the writer's responsibility to set the requirement and be clear as to what it is and define the contract with respect to the requirement. The latter could either be user responsibility -- behavior explicitly undefined if violated -- or writer responsibility -- with either fix or raise exception upon violation detection. Python's duck-typing style tends to put responsibility on callers. Consider def minmidmax(seq): seq.sort() n = len(seq) return seq[0], seq[n//2], seq[n-1] This requires that seq have sane .sort, .__len__, and .__getitem__ methods. Checks could be added, but most Python programs would simply say the the input must be an in-place sortable sequence. Terry Jan Reedy From rt8396 at gmail.com Fri Aug 14 22:01:26 2009 From: rt8396 at gmail.com (r) Date: Fri, 14 Aug 2009 19:01:26 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: Message-ID: On Aug 14, 8:25?pm, "Dr. Phillip M. Feldman" wrote: > I wrote the following correct but inefficient test of primality for purposes > of demonstrating that the simplest algorithm is often not the most > efficient. ?But, when I try to run the following code with a value of n that > is large enough to produce a significant amount of running time, I get an > out-of-memory error! I don't think Python was created to keep mathematician's happy. Although strangely enough, the creator holds a masters degree in mathematics *and* computer science. Just another one of life's little ironies ;) From tjreedy at udel.edu Fri Aug 14 22:03:42 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 15 Aug 2009 11:03:42 +0900 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <7el2mqF2gi53eU1@mid.individual.net> References: <7el2mqF2gi53eU1@mid.individual.net> Message-ID: greg wrote: > You can't read and write with the same stdio file object > at the same time. Odd things tend to happen if you try. I believe the C standard specifies that the behavior of mixed reads and writes is undefined without intervening seek and/or flush, even if the seek is ignored (as it is on some Unix systems). With two threads, the timing is undetermined. From zuo at chopin.edu.pl Fri Aug 14 22:17:35 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 15 Aug 2009 04:17:35 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: <4a85ffe2$0$24643$426a34cc@news.free.fr> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: 15-08-2009 candide wrote: > Suppose you need to split a string into substrings of a given size > (except > possibly the last substring). I make the hypothesis the first slice is > at the end of the string. > A typical example is provided by formatting a decimal string with > thousands separator. I'd use iterators, especially for longer strings... import itertools def separate(text, grouplen=3, sep=','): "separate('12345678') -> '123,456,78'" repeated_iterator = [iter(text)] * grouplen groups = itertools.izip_longest(fillvalue='', *repeated_iterator) strings = (''.join(group) for group in groups) # gen. expr. return sep.join(strings) def back_separate(text, grouplen=3, sep=','): "back_separate('12345678') -> '12,345,678'" repeated_iterator = [reversed(text)] * grouplen groups = itertools.izip_longest(fillvalue='', *repeated_iterator) strings = [''.join(reversed(group)) for group in groups] # list compr. return sep.join(reversed(strings)) print separate('12345678') print back_separate('12345678') # alternate implementation # (without "materializing" 'strings' as a list in back_separate): def separate(text, grouplen=3, sep=','): "separate('12345678') -> '12,345,678'" textlen = len(text) end = textlen - (textlen % grouplen) repeated_iterator = [iter(itertools.islice(text, 0, end))] * grouplen strings = itertools.imap(lambda *chars: ''.join(chars), *repeated_iterator) return sep.join(itertools.chain(strings, (text[end:],))) def back_separate(text, grouplen=3, sep=','): "back_separate('12345678') -> '12,345,678'" beg = len(text) % grouplen repeated_iterator = [iter(itertools.islice(text, beg, None))] * grouplen strings = itertools.imap(lambda *chars: ''.join(chars), *repeated_iterator) return sep.join(itertools.chain((text[:beg],), strings)) print separate('12345678') print back_separate('12345678') http://docs.python.org/library/itertools.html#recipes was the inspiration for me (especially grouper). Cheers, *j -- Jan Kaliszewski (zuo) From davea at ieee.org Fri Aug 14 22:25:18 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 22:25:18 -0400 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A861C8E.4030602@ieee.org> Benjamin Kaplan wrote: > On Fri, Aug 14, 2009 at 12:42 PM, Douglas Alan wrote: > > >> P.S. Overloading "left shift" to mean "output" does indeed seem a bit >> sketchy, but in 15 years of C++ programming, I've never seen it cause >> any confusion or bugs. >> > > > > The only reason it hasn't is because people use it in "Hello World". I bet > some newbie C++ programmers get confused the first time they see << used to > shift. > > Actually, I've seen it cause confusion, because of operator precedence. The logical shift operators have a fairly high level priority, so sometimes you need parentheses that aren't obvious. Fortunately, most of those cases make compile errors. C++ has about 17 levels of precedence, plus some confusing associative rules. And operator overloading does *NOT* change precedence. DaveA From zuo at chopin.edu.pl Fri Aug 14 22:40:05 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 15 Aug 2009 04:40:05 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: 15-08-2009 Jan Kaliszewski wrote: > 15-08-2009 candide wrote: > >> Suppose you need to split a string into substrings of a given size >> (except >> possibly the last substring). I make the hypothesis the first slice is >> at the end of the string. >> A typical example is provided by formatting a decimal string with >> thousands separator. > > I'd use iterators, especially for longer strings... > > > import itertools [snip] Err... It's too late for coding... Now I see obvious and simpler variant: def separate(text, grouplen=3, sep=','): "separate('12345678') -> '123,456,78'" textlen = len(text) end = textlen - (textlen % grouplen) strings = (text[i:i+grouplen] for i in xrange(0, end, grouplen)) return sep.join(itertools.chain(strings, (text[end:],))) def back_separate(text, grouplen=3, sep=','): "back_separate('12345678') -> '12,345,678'" textlen = len(text) beg = textlen % grouplen strings = (text[i:i+grouplen] for i in xrange(beg, textlen, grouplen)) return sep.join(itertools.chain((text[:beg],), strings)) print separate('12345678') print back_separate('12345678') -- Jan Kaliszewski (zuo) From guthrie at mum.edu Fri Aug 14 23:20:34 2009 From: guthrie at mum.edu (guthrie) Date: Fri, 14 Aug 2009 20:20:34 -0700 (PDT) Subject: py-rrdTool - install fails References: Message-ID: On Aug 14, 3:39?pm, Christian Heimes wrote: > guthrie schrieb: > > > > > I want to do some rrd in a python cgi script, but am having trouble > > getting an easy install module. > > > py-rrdTool looks good, but is distributed in c source, and is missing > > a header file in the distribution. Thus the install fails when it > > tries to reference rrd.h which is not there. > > > Are there better rrd modules to use, or a compiled version of this, or > > other suggestions? > > -------------------------------------------------------------------------------------- > > building 'rrdtool._rrdtool' extension > > C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo / > > Ox /MD /W3 /GS- /DNDEBUG -I/usr/local\include "-IE:\PLang\Active Python > > \include" "-IE:\PLang\Active Python\PC" /Tcsrc/_rrdtoolmodule.c / > > Fobuild\temp.win32-2.6\Release\src/_rrdtoolmodule.obj > > _rrdtoolmodule.c > > src/_rrdtoolmodule.c(34) : fatal error C1083: Cannot open include > > file: 'rrd.h': No such file or directory > > error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN > > \cl.exe"' failed with exit status 2 > > > C:\Documents and Settings\guthrie\Desktop\py-rrdtool-0.2.1> > > rrd.h is part of the rrdtools. You need to install rrdtools plus all its > dependencies. Have a lot of fun ;) > > Christian Thanks; I got py-rrttool-0.2.1 from sourceforge, but in its src directory it has only 3 files, _rrdtoolmodule.c, rrd_extra.h, and rrd_format.h http://sourceforge.net/projects/py-rrdtool/files/py-rrdtool/0.2.1/ (same for site: http://www.nongnu.org/py-rrdtool/ ) Where should I be looking for other dependencies? I installed rrdtools.exe, and don't see any rrd.h file in that hierarchy. From magawake at gmail.com Fri Aug 14 23:28:32 2009 From: magawake at gmail.com (Mag Gam) Date: Fri, 14 Aug 2009 23:28:32 -0400 Subject: unittest Message-ID: <1cbd6f830908142028v638a4c06jf0f859be712e724c@mail.gmail.com> I am writing an application which has many command line arguments. For example: foo.py -args "bar bee" I would like to create a test suit using unittest so when I add features to "foo.py" I don't want to break other things. I just heard about unittest and would love to use it for this type of thing. so my question is, when I do these tests do I have to code them into foo.py? I prefer having a footest.py which will run the regression tests. Any thoughts about this? TIA From dieter at handshake.de Sat Aug 15 00:41:20 2009 From: dieter at handshake.de (Dieter Maurer) Date: 15 Aug 2009 06:41:20 +0200 Subject: httplib incredibly slow :-( In-Reply-To: References: <4A81D3CB.7080209@simplistix.co.uk> <4A82EFDC.70502@simplistix.co.uk> <4eb0089f0908121753o5ecf141dj304b21c3df0d3d6b@mail.gmail.com> Message-ID: Chris Withers writes on Thu, 13 Aug 2009 08:20:37 +0100: > ... > I've already established that the file downloads in seconds with > [something else], so I'd like to understand why python isn't doing the > same and fix the problem... A profile might help to understand what the time is used for. As almost all operations are not done in Python itself ("httplib" is really a very tiny wrapper above a socket), a C level profile may be necessary to understand the behaviour. Dieter From bouncyinc at gmail.com Sat Aug 15 00:46:19 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Fri, 14 Aug 2009 22:46:19 -0600 Subject: getting a "simple" program to work In-Reply-To: References: <50697b2c0908112146q6e12650dt914518166b4fae72@mail.gmail.com> Message-ID: I'm checking back with some new info. Apparently the maintainer of the ogss package indicated that this is definately an issue with the libgmail package. Now I have already submtted help to the maintainer of libgmail to get some help it making his project work again. I am also interesetd in how roundabout smtp support could be added to that program specifically print "Seding back results" account.sendMessage(tosend) print "Logging..." execd.append(int(maxmessage.id,16)) towrite = str(int(maxmessage.id,16))+"~ " for arg in command: towrite += arg+" " w.write(towrite+"\n") print "Listening for commands" in the code sample from ogss.py to take that subroutine and turn it around to allow the same arguments basically take the above and add ----------------------------------------- gmail_user = "" #Username gmail_pwd = "" #Password gmail_alt = " " #Alias ID gmail_alias = ""+gmail_alt #nickname mailing_list = "" class mailz: def __init__(self): self.files=[""] self.mail = MIMEMultipart() def attach(self,fil): self.files.append(fil) def mailprep(self,to, subject, text): self.to = to self.mail['From'] = gmail_alias self.mail['To'] = to self.mail['Subject'] = subject if (mailtoBcc !="") : self.mail['BCC'] = mailtoBcc text+="\n\n\n_________________________\nMail generated By PyGmS "+ver+"\n - Made By Djays\n http://djsh.net" self.mail.attach(MIMEText(text)) print self.files for attach in self.files: if (attach != "") : part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attach)) self.mail.attach(part) def sendmail(self): self.mailServer = smtplib.SMTP("smtp.gmail.com", 587) self.mailServer.ehlo() self.mailServer.starttls() self.mailServer.ehlo() self.mailServer.login(gmail_user, gmail_pwd) self.mailServer.sendmail(gmail_user, self.to, self.mail.as_string()) self.mailServer.close() ---------------------------------------------------------------------------- I hate to sound like a newb but the problem is that I'm running into apathetic maintainers of the software in question which has yet to be redacted as "working" and at the present time I have to deal with multi-server conglomerates like "Request Tracker" or "Roundup" both of which are simply not authenticating into gmail at all. At first I thought this was an issue of the ssl certificates not working but hen how come it's possible to have any of the code working when it's just the sending? And how is it possible that generic but different code can be working when it's all broken? Not to sound in any way belligerent but when this would be my 5th program language to solve a simple problem I think this is solveable w/o having to resort to the equivalent to a half semester of CS I in python imho. On Wed, Aug 12, 2009 at 10:41 PM, John Haggerty wrote: > Just checking to see if this is more adequate to what you would have wanted > to see I didn't get any feedback so I wasn't quite sure of this at the > present time. > > > On Tue, Aug 11, 2009 at 11:02 PM, John Haggerty wrote: > >> >> >> On Tue, Aug 11, 2009 at 10:46 PM, Chris Rebert wrote: >> >>> On Sun, Aug 9, 2009 at 8:42 PM, John Haggerty >>> wrote: >>> > ok so I know this is one of those "weird" requests but here me out. >>> > So far I have an issue with a package for python called "libgmail" >>> which is >>> > basically a gmail interface for python to send messages remoetly. >>> > Works ok except that the 'sendMessage' routine is bad. >>> >>> How is it "bad" precisely? Be specific (e.g. error message(s), >>> description of observed incorrect behavior). >>> >> >> In regards to bad would be failing to transmit claiming that the submittal >> is wrong for the transmit string. >> >> (where username is my gmail username and "password" is my gmail password >> to the test account, 6666666969 is the mobile number in question '00' is my >> "carrier id" from the ogss code example which is just an array location from >> a preformatted part of the string [probably from wikipedia on mobile carrier >> email addresses to cell phones], I actually got desperate and commented out >> the first attempt to transmit which I located in the code as just the >> "instructions" the code fails on re-transmission, I later on looked at the >> file and located that it was a zero byte file of no content. The program >> itself looks for a command from the user's cell phone directly from mms sent >> to the target gmail account prefaced by "Ogss" and anything else is treated >> as a command but since the command failed on the first transmit I don't >> think it's the command per se). >> >> owner at bouncyinc:~/Desktop/OGSS$ python ogss.py username password >> 6666666969 00 >> Starting ogss >> Logfile at:/home/owner/ogss.log >> Opening log file for reading >> Parsing user input >> Connecting to Gmail >> Logging into Gmail >> Opening log file for writing >> Listening for commands >> Processing Command >> ls: unrecognized option `---------------------------------------------' >> Try `ls --help' for more information. >> Seding back results >> Traceback (most recent call last): >> File "ogss.py", line 127, in >> main(sys.argv) >> File "ogss.py", line 110, in main >> account.sendMessage(tosend) >> File "/usr/lib/python2.5/site-packages/libgmail.py", line 615, in >> sendMessage >> raise GmailSendError, resultInfo[SM_MSG] >> libgmail.GmailSendError: Please try again. >> >> I traced the result to the sendMessage routine and noted that anytime it >> tries to send anything it fails this also fails with the standard "docs" >> package for libgmail 0.30 docs from the maintainer's site. >> >> Now the part where it *does* fail is where it has an issue with looking at >> the trailing info but then it would have logged the info to the file and >> emailed me back junk (which it didn't) >> >> I assume this could be done on any system just replace 'ls' with 'dir' or >> the equivalent. >> >> >>> >>> > This is included in the above attachment >>> > it's used in a program called "ogss" which is an sms interface to gmail >>> to >>> > basically read gmail and then have a command done on a remote machine >>> and >>> > then spat out on the local machine to a log file that's opened and then >>> > emailed back >>> > problem is that the sending back routine fails. >>> >>> Which routine is that exactly? Please also specify exactly how it is >>> failing (e.g. error message(s), description of observed incorrect >>> behavior). >>> >>> I apologize if these questions are answered in comments in the >>> attachments, but to be honest, the fact that you didn't (or couldn't) >>> put the specific problematic sections of code (and/or error messages) >>> inline in your message makes it less likely that people (such as >>> myself) will try to help you due to the volume of code you're making >>> people wade through (i.e. people tend not to read large code dumps, >>> /especially/ in attachments). >>> >>> Cheers, >>> Chris >>> -- >>> http://blog.rebertia.com >>> >> That's ok I understand I hope that helps at least in part. > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From oraclebill at gmail.com Sat Aug 15 01:15:36 2009 From: oraclebill at gmail.com (Bill Jones) Date: Fri, 14 Aug 2009 22:15:36 -0700 (PDT) Subject: Python docs disappointing - group effort to hire writers? References: <09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com> <109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com> <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> <93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com> <96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com> Message-ID: On Aug 8, 3:27?pm, Mark Lawrence wrote: > Kee Nethery wrote: > > As someone trying to learn the language I want to say that the tone on > > this list towards people who are trying to learn Python ?feels like it > > has become anti-newbies. > > [snip] > > > Kee Nethery > > My gut feeling (which could of course be wrong) is that many hard core > Pythonistas are cheesed off with newbies who refuse to help themselves. The funny thing is that their response is to shutdown changes that are intended to *help* newbies help themselves. It seems self-defeating to me. From jonrascal at gmail.com Sat Aug 15 01:39:08 2009 From: jonrascal at gmail.com (Rascal) Date: Fri, 14 Aug 2009 22:39:08 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: Message-ID: <04359a4b-9336-4936-8a15-a845ecebe4ba@m7g2000prd.googlegroups.com> look at xrange -- http://docs.python.org/library/functions.html#xrange From jonrascal at gmail.com Sat Aug 15 02:08:14 2009 From: jonrascal at gmail.com (Rascal) Date: Fri, 14 Aug 2009 23:08:14 -0700 (PDT) Subject: Splitting a string into substrings of equal size References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <3842c750-9633-4e8e-84da-4853784bce64@v37g2000prg.googlegroups.com> I'm bored for posting this, but here it is: def add_commas(str): str_list = list(str) str_len = len(str) for i in range(3, str_len, 3): str_list.insert(str_len - i, ',') return ''.join(str_list) From chardster at gmail.com Sat Aug 15 02:24:00 2009 From: chardster at gmail.com (Richard Thomas) Date: Fri, 14 Aug 2009 23:24:00 -0700 (PDT) Subject: unittest References: Message-ID: <75330ab0-329c-4842-a5b0-ddf0ccefe8ea@r18g2000yqd.googlegroups.com> On Aug 15, 4:28?am, Mag Gam wrote: > I am writing an application which has many command line arguments. > For example: foo.py -args "bar bee" > > I would like to create a test suit using unittest so when I add > features to "foo.py" I don't want to break other things. I just heard > about unittest and would love to use it for this type of thing. > > so my question is, when I do these tests do I have to code them into > foo.py? I prefer having a footest.py which will run the regression > tests. Any thoughts about this? > > TIA You should certainly keep your test suite separate. There's a quick example of how to write unit tests in the unittest documentation: http://docs.python.org/library/unittest.html#basic-example Richard. From python at rcn.com Sat Aug 15 03:10:36 2009 From: python at rcn.com (Raymond Hettinger) Date: Sat, 15 Aug 2009 00:10:36 -0700 (PDT) Subject: implementing descriptors References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: <8e92d272-ddf8-44ef-9bc9-86b60a5855e5@t11g2000prh.googlegroups.com> > Raymond, > ? ?This functionality is exactly what I was looking for. Thanks! ?I'll > be using this to solve my problem. > > ? ?Now that I'm on the right track, I'm still a bit confused about how > __get__ and __set__ are useful. ?Admittedly, I don't need to > understand them to solve this problem, but perhaps they may be useful > in the future. ?If I wanted to solve this problem using __get__ and > __set__ could it be done? The __get__ and __set__ methods are used to implement property() itself. So, if you didn't have property, you could roll your own version: class MyProperty(object): def __init__(self, fget, fset): self.fget = fget self.fset = fset def __get__(self, obj, objtype=None): return self.fget(obj) def __set__(self, obj, value): self.fset(obj, value) class foo(object): def __init__(self,a = None,b = None): self._start = a self._end = b def get_start(self): return self._start def set_start(self, value): if self._end is None or value < self._end: self._start = value else: self._end = value start = MyProperty(get_start, set_start) def get_end(self): return self._end def set_end(self, value): if self._start is None or value > self._start: self._end = value else: self._start = value end = MyProperty(get_end, set_end) Raymond From mobiledreamers at gmail.com Sat Aug 15 03:12:56 2009 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Sat, 15 Aug 2009 00:12:56 -0700 Subject: Natural Language Processing in Python In-Reply-To: <9fdb569a0908141126x19d2d4c5q6abc99de7e390f94@mail.gmail.com> References: <9fdb569a0908141126x19d2d4c5q6abc99de7e390f94@mail.gmail.com> Message-ID: Try this out Fotoroll does term extraction http://bit.ly/HCPDi So to get json output of list of terms post to http://fotoroll.com/findterms?json=true&text=Content+to+extract terms from Hope this helps Fotoroll Term extraction No limit on number of queries per day Yahoo 5000 queries a day Zemanta 1000 queries a day with regn On Fri, Aug 14, 2009 at 11:26 AM, Vlastimil Brom wrote: > 2009/8/14 Prateek : > > Hi, > > > > Can somebody please provide me link to a good online resource or e- > > book for doing natural language processing programming in Python. > > > > Thanks, > > Prateek > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > Maybe you could start with NLTK > http://www.nltk.org/ > Check the toolkit as well as the documentation. > > hth > vbr > -- > http://mail.python.org/mailman/listinfo/python-list > -- Bidegg worlds best auction site http://bidegg.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From dmitrey.kroshko at scipy.org Sat Aug 15 03:17:04 2009 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sat, 15 Aug 2009 00:17:04 -0700 (PDT) Subject: "for" cycle with assigning index Message-ID: <4149f0b2-603d-4c59-aa34-bd0fd826303c@b14g2000yqd.googlegroups.com> Hi all, could you inform me how to do it properly? I have the cycle for i in xrange(len(Funcs2)): # Funcs2 is Python dict Funcs.append(lambda *args, **kwargs: (Funcs2[i](*args, **kwargs) [IndDict[left_arr_indexes[i]]])) So, all the Funcs are initialized with i = last index = len(Funcs2) When I involve for i in xrange(len(Funcs2)): Funcs.append(lambda i=i,*args, **kwargs: (Funcs2[i](*args, **kwargs)[IndDict[left_arr_indexes[i]]])) I get "list indices must be integers, not dict" (and i is equal to Python dictionary, that is Funcs2) So, how to do it correctly? Thank you in advance, D. From hendrik at microcorp.co.za Sat Aug 15 03:29:13 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 09:29:13 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <20090814135837.11286.700809778.divmod.xquotient.174@localhost.localdomain> References: <200908141538.15798.hendrik@microcorp.co.za> <20090814135837.11286.700809778.divmod.xquotient.174@localhost.localdomain> Message-ID: <200908150929.13885.hendrik@microcorp.co.za> On Friday 14 August 2009 15:58:37 exarkun at twistedmatrix.com wrote: > One strategy you might employ to get rid of the busy looping is to use > Twisted and its serial port support. This also addresses the full- > duplex issue you've raised. I know - vaguely - about twisted and I have been dancing around the fire, not really ready to put the time in to understand it properly. Looks like the time has come though - my weekend is really going to hell. I am now going to make a loopback connector and start playing. Thanks to everybody for the feedback. - Hendrik From pavlovevidence at gmail.com Sat Aug 15 03:39:59 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Aug 2009 00:39:59 -0700 (PDT) Subject: "for" cycle with assigning index References: <4149f0b2-603d-4c59-aa34-bd0fd826303c@b14g2000yqd.googlegroups.com> Message-ID: <6a5fd53a-1c29-48d3-b3cc-c48350acc736@a37g2000prf.googlegroups.com> On Aug 15, 12:17?am, dmitrey wrote: > Hi all, > could you inform me how to do it properly? > > I have the cycle > > for i in xrange(len(Funcs2)): # Funcs2 is Python dict > ? ? ?Funcs.append(lambda *args, **kwargs: (Funcs2[i](*args, **kwargs) > [IndDict[left_arr_indexes[i]]])) > > So, all the Funcs are initialized with i = last index = len(Funcs2) > > When I involve > > for i in xrange(len(Funcs2)): > ? ? ?Funcs.append(lambda i=i,*args, **kwargs: (Funcs2[i](*args, > **kwargs)[IndDict[left_arr_indexes[i]]])) > > I get "list indices must be integers, not dict" (and i is equal to > Python dictionary, that is Funcs2) > > So, how to do it correctly? > Thank you in advance, D. Define a helper function to do it: def create_funcs_caller(i): def func(*args,**kwargs): return(Funcs2[i](*args,**kwargs)[IndDict[left_arr_indexes [i]]])) retirm func for i in xrange(len(Funcs2)): Funcs.append(create_funcs_caller(i)) (I prefer to do it this way in any case; never liked the keyword argument hack way of doing it.) Carl Banks From hendrik at microcorp.co.za Sat Aug 15 03:52:21 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 09:52:21 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <200908150952.21825.hendrik@microcorp.co.za> On Friday 14 August 2009 16:19:04 Grant Edwards wrote: > On 2009-08-14, Hendrik van Rooyen wrote: > > In the meantime I have had another idea which I have also not tried yet, > > namely to do independent opens for reading and writing, to give me two > > file instances instead of one, and to try with that. I have no idea if > > it would make any difference, or even work at all. > > That should work (and shouldn't make any difference) > > > My normal stuff works, but I do not like it as it is > > essentially busy looping with short sleeps in between. In the > > eBox, it uses most of the processor just to move a few bytes > > of I/O in and out between the serial port and the TCP/IP, and > > struggles to do that better than five times a second, while > > the message time on the 115200 baud port is only about 2 > > milliseconds. > > What platform are you using? I suppose it's possible that > there's something broken in the serial driver for that > particular hardware. Your experience seems to be exactly the opposite to mine - you are saying it should "just work" and I am seeing half duplex functionality. I have seen this on my development machine which is a dual processor of some gigs running SuSe Linux 10.3, as well as on the other end of a the scale - the eBox (a 400MHz 486 without floating point with 128 Mb of memory) running Slackware. Maybe it is in the way I set the port up, because that is the common thing. What I do is this: reterror = os.system('stty -F /dev/ttyS0 sane 115200 cread clocal raw -echo') It does not seem to make a difference if I do this before or after opening the port. Any comments from a Linux Guru? - Hendrik From hendrik at microcorp.co.za Sat Aug 15 04:09:02 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 10:09:02 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <7el95aF2h0d12U1@mid.uni-berlin.de> References: <7el95aF2h0d12U1@mid.uni-berlin.de> Message-ID: <200908151009.02540.hendrik@microcorp.co.za> On Friday 14 August 2009 16:03:22 Diez B. Roggisch wrote: > You should *really* just use pyserial. No hassle, instant satisfaction. :-) I have downloaded and had a quick look, and I see it is based on the standard library's serial.Serial class - another battery that I have not used before. And I see that serial.Serial looks like it uses os. calls, which is one of the things Greg mentioned. Curioser and Curioser. There was one thing I saw in a quick read of pyserial that I did not like as I cannot understand why it is done - if a timeout is set to less than a tenth of a second, then it is changed to be a tenth. - In a polling protocol that will limit you to poll only ten terminals a second, or less, and is a very long time if a message takes only a couple of millis to send. I am getting there - this time around I want to kill this problem dead because I seem to keep doing something wrong somewhere and I want to understand what it is and stop doing it. - Hendrik From hendrik at microcorp.co.za Sat Aug 15 04:14:39 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 10:14:39 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <200908151014.39683.hendrik@microcorp.co.za> On Friday 14 August 2009 16:19:36 Grant Edwards wrote: > On 2009-08-14, exarkun at twistedmatrix.com wrote: > > One strategy you might employ to get rid of the busy looping > > is to use Twisted and its serial port support. This also > > addresses the full- duplex issue you've raised. > > There are no such full-dulex issues. I will put an example together as soon as I have finished reading and answering the mail - maybe I am crazy and chasing angels. - Hendrik From http Sat Aug 15 04:15:13 2009 From: http (Paul Rubin) Date: 15 Aug 2009 01:15:13 -0700 Subject: "for" cycle with assigning index References: <4149f0b2-603d-4c59-aa34-bd0fd826303c@b14g2000yqd.googlegroups.com> <6a5fd53a-1c29-48d3-b3cc-c48350acc736@a37g2000prf.googlegroups.com> Message-ID: <7x1vndbii6.fsf@ruckus.brouhaha.com> Carl Banks writes: > def create_funcs_caller(i): > def func(*args,**kwargs): > return(Funcs2[i](*args,**kwargs)[IndDict[left_arr_indexes[i]]]) > retirm func > > for i in xrange(len(Funcs2)): > Funcs.append(create_funcs_caller(i)) I prefer to get rid of the index variable: def create_funcs_caller(f,ix): return lambda *args, **kw: f(*args,**kw)[ix] Funcs = list(create_funcs_caller(f,ix) for f,ix in zip(Funcs2, left_arr_indexes)) Or in point-free style: from itertools import starmap Funcs = starmap(create_funcs_caller, zip(Funcs2,left_arr_indexes)) From xahlee at gmail.com Sat Aug 15 04:18:39 2009 From: xahlee at gmail.com (Xah Lee) Date: Sat, 15 Aug 2009 01:18:39 -0700 (PDT) Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: Fresh out of the oven: ? How to use and setup Emacs's whitespace-mode http://xahlee.org/emacs/whitespace-mode.html Xah ? http://xahlee.org/ ? On Aug 13, 6:36 pm, Xah Lee wrote: > ? A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode > http://xahlee.org/UnixResource_dir/writ/emacs_whitespace-mode_problems.html > > plane text version follows: > -------------------------------------------------- > > A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode > > Xah Lee, 2009-08-13 > > Just wanted to express some frustration with whitespace-mode. > > Emacs 23, just released, has this whitespace-mode feature. It renders > spaces, tabs, newlines characters with a visible glyph. This feature, > is in Microsoft Word since about 1992. > > This feature is important in practical ways. For example, when you > work with ?tab separated line? files (CSV) that's a common format for > importing/exporting address books or spreadsheets. It's also important > in whitespace-significant langs such as Python. Or, in text processing > when placement of space and tabs matters in the output. > > All i wanted, is to make Space and Tab and Newline chars visible. > > However, the emacs whitespace-mode does much more than that. It is > designed for tech geeking control freaks to tune every aspect of white > space in his source code. The mode is filled with bells and whistles. > It distinguishes tabs mixed with spaces, EOLs mixed with spaces, EOLs > at beginning of file, EOLs at end of file, run on spaces at end of > line, lines that has nothing to do with white spaces but is simply > longer than 80 chars, etc. Each of these is rendered with different > foreground, background, colors, so that they cannot possibly escape > the notices of control freaks. > > By default, most of these are on, so that, when you turn on the mode, > most reasonable clean source code become this colorful rainbow > unreadable fuck. > > I tried to tune it, with my 10 years of emacs of fucking 16 hours of > using per day, and 3 years of elisp coding experience. But, after a > hour, it's confusion hell sans avail. > > O, that Alex idiot with his emacswiki, refused to lead emacswiki into > any readable state. All he can think about is my social skills. (See: > Problems of Emacswiki.) > > What the fuck motherfuck. Hi tech geekers, coding freaks, social > science ignoramus fucks, basic economics illiterate FSF fucks, freedom > abusing selfish ideologists fucks, Richard Stallman propagandist fuck, > we-try-to-be-easy-to-use linuxer idioting fucks, FUCK U. > > Xah > ? http://xahlee.org/ > > ? From hendrik at microcorp.co.za Sat Aug 15 04:32:17 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 10:32:17 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <1aGdnessDpUX6RjXnZ2dnUVZ_gCdnZ2d@posted.visi> References: <7el2mqF2gi53eU1@mid.individual.net> <1aGdnessDpUX6RjXnZ2dnUVZ_gCdnZ2d@posted.visi> Message-ID: <200908151032.17185.hendrik@microcorp.co.za> On Friday 14 August 2009 16:28:26 Grant Edwards wrote: > On 2009-08-14, greg wrote: > > Hendrik van Rooyen wrote: 8<--------------------------------------------------------------- > Doh! It didn't even occur to me that somebody would use python > "file" objects for serial ports, and I completely overlooked > the fact that the OP was doing that. > > In short: don't do that -- it just messes things up *grin* All right that makes me feel better - you were so adamant that there is no problem that I was starting to doubt my sanity. - So I hereby cancel the promise I have just made to put an example together. - It is no longer needed. > > Do not use Python file objects. Use the underlying file > descriptors: os.open(), os.read(), os.write(). That will > almost certainly solve your problems. > > If you want examples of os.xxxxx() usage, below is the > PosixSerial.py module that I use for Linux-only applications. > For cross-platform work, use pyserial (whose Posix support is > based on the code below). > 8< ---------------------------------PosixSerial.py---------------------------- Thanks that looks, on first inspection, similar to the serialposix.py module in the stdlib, but less cluttered. - Hendrik From pavlovevidence at gmail.com Sat Aug 15 04:41:53 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Aug 2009 01:41:53 -0700 (PDT) Subject: Python docs disappointing - group effort to hire writers? References: <09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com> <109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com> <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> <93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com> <96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com> Message-ID: <9e93859d-cfca-43ff-8bae-65308a8e1c4d@a39g2000pre.googlegroups.com> On Aug 14, 10:15?pm, Bill Jones wrote: > On Aug 8, 3:27?pm, Mark Lawrence wrote: > > My gut feeling (which could of course be wrong) is that many hard core > > Pythonistas are cheesed off with newbies who refuse to help themselves. > > The funny thing is that their response is to shutdown changes that are > intended > to *help* newbies help themselves. It seems self-defeating to me. Intended to help newbies doesn't necessarily mean it actually will help newbies. (Just sayin'.) Carl Banks From hendrik at microcorp.co.za Sat Aug 15 04:47:22 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 10:47:22 +0200 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <02957d23$0$20647$c3e8da3@news.astraweb.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: <200908151047.22231.hendrik@microcorp.co.za> On Friday 14 August 2009 18:11:52 Steven D'Aprano wrote: > On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: > > "I saw `cout' being shifted "Hello world" times to the left and stopped > > right there." --Steve Gonedes > > Assuming that's something real, and not invented for humour, I presume > that's describing something possible in C++. Am I correct? What the hell > would it actually do??? It would shift "cout" left "Hello World" times. It is unclear if the shift wraps around or not. It is similar to a banana *holding his hands apart about a foot* this colour. - Hendrik From clp2 at rebertia.com Sat Aug 15 04:48:30 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 15 Aug 2009 04:48:30 -0400 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <200908151047.22231.hendrik@microcorp.co.za> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <200908151047.22231.hendrik@microcorp.co.za> Message-ID: <50697b2c0908150148o1532b656od0582acf261311ad@mail.gmail.com> On Sat, Aug 15, 2009 at 4:47 AM, Hendrik van Rooyen wrote: > On Friday 14 August 2009 18:11:52 Steven D'Aprano wrote: >> On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: >> > "I saw `cout' being shifted "Hello world" times to the left and stopped >> > right there." ?--Steve Gonedes >> >> Assuming that's something real, and not invented for humour, I presume >> that's describing something possible in C++. Am I correct? What the hell >> would it actually do??? > > It would shift "cout" left "Hello World" times. > It is unclear if the shift wraps around or not. > > It is similar to a banana *holding his hands apart about a foot* this colour. > > - Hendrik I think you managed to successfully dereference the null pointer there... Cheers, Chris From hendrik at microcorp.co.za Sat Aug 15 04:50:43 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 10:50:43 +0200 Subject: Why does my ftp script quit after couple of hours? In-Reply-To: <337951bf-4d0d-4dde-95de-8e6d7d68a7f5@a13g2000yqc.googlegroups.com> References: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> <7elh1lF2h1rl0U1@mid.uni-berlin.de> <337951bf-4d0d-4dde-95de-8e6d7d68a7f5@a13g2000yqc.googlegroups.com> Message-ID: <200908151050.43954.hendrik@microcorp.co.za> On Friday 14 August 2009 18:25:50 kk wrote: > As far as robustness, I agree with your assestment. I guess my main > confusion with my result is that the console window just disappears. I > wonder if I can make the window stay even if it crashesor if there are > connection issues? I will createa seperate log file to see if I can > catch any issues in a log file. try opening python with the -i flag - then the console window hangs around after the script exits and you can examine variables and stuff. - Hendrik From sjmachin at lexicon.net Sat Aug 15 05:20:12 2009 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Aug 2009 02:20:12 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <24980842.post@talk.nabble.com> Message-ID: On Aug 15, 11:38?am, Mark Lawrence wrote: > Dr. Phillip M. Feldman wrote:> I wrote the following correct but inefficient test of primality for purposes > > of demonstrating that the simplest algorithm is often not the most > > efficient. ?But, when I try to run the following code with a value of n that > > is large enough to produce a significant amount of running time, I get an > > out-of-memory error! > > > def is_prime(n): > > ? ?for j in range(2,n): > > ? ? ? if (n % j) == 0: return False > > ? ?return True > > > It seems as though Python is actually expanding range(2,n) into a list of > > numbers, even though this is incredibly wasteful of memory. There should be > > a looping mechanism that generates the index variable values incrementally > > as they are needed. > > I have a strong suspicion that you will find hints in the Python > documentation that this has already been addressed. ?Perhaps you could > try reading before posting? Alternative hypothesis: the good doctor read the Python 3.x documentation but absent-mindedly ran Python 2.x From hendrik at microcorp.co.za Sat Aug 15 05:21:12 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 11:21:12 +0200 Subject: Python 'for' loop is memory inefficient In-Reply-To: <24980842.post@talk.nabble.com> References: <24980842.post@talk.nabble.com> Message-ID: <200908151121.12542.hendrik@microcorp.co.za> On Saturday 15 August 2009 03:25:45 Dr. Phillip M. Feldman wrote: > It seems as though Python is actually expanding range(2,n) into a list of > numbers, even though this is incredibly wasteful of memory. There should be > a looping mechanism that generates the index variable values incrementally > as they are needed. There is. Use xrange instead of range, and try again. And while you are about it, you may as well teach them that it is much better to do a multiplication than a division. -Hendrik From sleepy at cabbage.co.uk Sat Aug 15 05:25:19 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Sat, 15 Aug 2009 09:25:19 GMT Subject: get the pause status from amarok 2.1 References: <7eku4bF2gtku3U2@mid.uni-berlin.de> Message-ID: <3avhm.248709$bA.165466@newsfe16.ams2> On Fri, 14 Aug 2009 12:55:07 +0200, Diez B. Roggisch wrote: > Sleepy Cabbage schrieb: >> As the title says, I'm trying to find a way to get the pause status >> from amarok 2.1. >> >> I'm running kubuntu 9.04 with kde 4.2.2, python 2.6.2. >> >> Thanks in advance. > > Not at my linux-system right now, but dcop and the respective > python-module should help. > > Diez Thanks for you reply Diez. i'm sure that kde4.2 now uses qdbus instead of dcop and not sure whether amarok has the qdbus org.kde.amarok /Player GetStatus as it returns the following: qdbus: I don't know how to display an argument of type '(iiii)' From bh at izb.knu.ac.kr Sat Aug 15 05:34:38 2009 From: bh at izb.knu.ac.kr (Byung-Hee HWANG) Date: Sat, 15 Aug 2009 18:34:38 +0900 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: <861vnda09d.fsf@betla.izb.knu.ac.kr> Xah Lee writes: > ? A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode > http://xahlee.org/UnixResource_dir/writ/emacs_whitespace-mode_problems.html > [... snip 38 lines ...] OK, Xah, thanks for good writing, i'll read it 27 hours later. And i respect for your passion on Elisp, Python and text processing. BTW, i don't agree with your thought that you dislike FSF. FSF is not bad guy. Xah plz... Sincerely, -- "Don Michael." -- Peter Clemenza, "Chapter 31", page 435 From hendrik at microcorp.co.za Sat Aug 15 06:29:28 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 12:29:28 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: <7el2mqF2gi53eU1@mid.individual.net> Message-ID: <200908151229.29027.hendrik@microcorp.co.za> On Saturday 15 August 2009 04:03:42 Terry Reedy wrote: > greg wrote: > > You can't read and write with the same stdio file object > > at the same time. Odd things tend to happen if you try. > > I believe the C standard specifies that the behavior of mixed reads and > writes is undefined without intervening seek and/or flush, even if the > seek is ignored (as it is on some Unix systems). With two threads, the > timing is undetermined. For a serial port, flush on write makes some sense, but seek is complete nonsense because it is undefined, and besides- the point you try to seek to may never come around. So the message I am getting loud and clear is that the basic thing I am doing wrong is to use the ordinary python open() instead of os.open(). As for the timing in two threads - Yes you are right, but there is not a lot one can do about it - The right solution depends to a large extent on what you are doing - for instance, if you are writing a polling protocol (such as Burroughs poll-select, or Uniscope), then you want a loop that transmits something, and waits for an answer or time out. This is essentially half duplex, and in a high level language the natural structure to write this is in one thread. On the other hand, if you are writing a sliding window type protocol that is capable of pouring stuff into a link asynchronously from both ends, then the natural way to do it is to use two threads - one to handle incoming stuff, and the other to squirt out the data that must go out. If, as is true in my case, the source of outgoing data and the sink for incoming data is a TCP/IP socket, then one can accomplish this with blocking I/O quite efficiently, provided you have a third thread looking after overall timing Issues. For such a case, the timing is essentially determined by the flow of the data (provided of course that you can keep up with the link speed). When one introduces another variable into the equation, namely the requirement to do a transmission at least every n milliseconds, (a feel-good keepalive) then you need a time out on the sources, so that you can either do a transmission or raise an alarm because a reporting period was missed. So then you are back at a loop waiting for input or timeout, and doing a transmission afterwards. Only now there are two of them, facing in opposite directions. I think this sort of thing is better written at a lower level where one has access to the interrupts from the ports, as well as a timer interrupt to handle timing and timeout issues. But that is a lot of work, so I make do with python. - Hendrik From magawake at gmail.com Sat Aug 15 07:32:15 2009 From: magawake at gmail.com (Mag Gam) Date: Sat, 15 Aug 2009 07:32:15 -0400 Subject: unittest In-Reply-To: <75330ab0-329c-4842-a5b0-ddf0ccefe8ea@r18g2000yqd.googlegroups.com> References: <75330ab0-329c-4842-a5b0-ddf0ccefe8ea@r18g2000yqd.googlegroups.com> Message-ID: <1cbd6f830908150432v4a88ad86ge9a266b647088fca@mail.gmail.com> So, in this example: "import random" In my case I would do "import foo" ? is there anything I need to do for that? On Sat, Aug 15, 2009 at 2:24 AM, Richard Thomas wrote: > On Aug 15, 4:28?am, Mag Gam wrote: >> I am writing an application which has many command line arguments. >> For example: foo.py -args "bar bee" >> >> I would like to create a test suit using unittest so when I add >> features to "foo.py" I don't want to break other things. I just heard >> about unittest and would love to use it for this type of thing. >> >> so my question is, when I do these tests do I have to code them into >> foo.py? I prefer having a footest.py which will run the regression >> tests. Any thoughts about this? >> >> TIA > > You should certainly keep your test suite separate. There's a quick > example of how to write unit tests in the unittest documentation: > http://docs.python.org/library/unittest.html#basic-example > > Richard. > -- > http://mail.python.org/mailman/listinfo/python-list > From greg at cosc.canterbury.ac.nz Sat Aug 15 07:44:59 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 15 Aug 2009 23:44:59 +1200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: <7el2mqF2gi53eU1@mid.individual.net> Message-ID: <7enlcsF2fqpebU1@mid.individual.net> Terry Reedy wrote: > I believe the C standard specifies that the behavior of mixed reads and > writes is undefined without intervening seek and/or flush, even if the > seek is ignored (as it is on some Unix systems). With two threads, the > timing is undetermined. It's also possible that the stdio object is being locked while one of the threads is using it, which would also account for the observed half-duplex behaviour. Another good reason to steer clear of file objects! -- Greg From chris at simplistix.co.uk Sat Aug 15 07:55:37 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Sat, 15 Aug 2009 12:55:37 +0100 Subject: Python 2.6 still not giving memory back to the OS... Message-ID: <4A86A239.3030404@simplistix.co.uk> Hi All, I thought this was fixed back in Python 2.5, but I guess not? So, I'm playing in an interactive session: >>> from xlrd import open_workbook >>> b = open_workbook('some.xls',pickleable=0,formatting_info=1) At this point, top shows the process usage for python to be about 500Mb. That's okay, I'd expect that, b is big ;-) >>> del b However, it still does now, maybe the garbage collector needs a kick? >>> import gc >>> gc.collect() 702614 Nope, still 500Mb. What gives? How can I make Python give the memory its no longer using back to the OS? Okay, so maybe this is something to do with it being an interactive session? So I wrote this script: from xlrd import open_workbook import gc b = open_workbook('some.xls',pickleable=0,formatting_info=1) print 'opened' raw_input() del b print 'deleted' raw_input() gc.collect() print 'gc' raw_input() The raw inputs are there so I can check the memory usage in top. Even after the gc, Python still hasn't given the memory back to the OS :-( What am I doing wrong? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From contact at xavierho.com Sat Aug 15 08:09:50 2009 From: contact at xavierho.com (Xavier Ho) Date: Sat, 15 Aug 2009 22:09:50 +1000 Subject: What happened to __cmp__() in Python 3.x? Message-ID: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> Hey all, I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in the documentation. Is there a substitution for this special method in 3.1, or do I really have to define all six rich comparison methods to work it out? If this question has already been asked somewhere, I apologise in advance. Already googled around but I didn't find information on this. Any replies appreciated. Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Sat Aug 15 08:16:14 2009 From: contact at xavierho.com (Xavier Ho) Date: Sat, 15 Aug 2009 22:16:14 +1000 Subject: What's a good solution to implement rich comparison for user-defined classes? (was: What happened to __cmp__() in Python 3.x?) Message-ID: <2d56febf0908150516i7fb00b80ub3e9481c8bf3f3f9@mail.gmail.com> Never mind my last email. Google actually found me something at last. I also found this page: http://mail.python.org/pipermail/python-list/2008-November/688591.html That still uses a sloppy way of defining the special methods, and a little chunky. Is there a better way for the lazy me? Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Aug 15 08:25:00 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2009 12:25:00 GMT Subject: Python 'for' loop is memory inefficient References: Message-ID: <02969972$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 18:25:45 -0700, Dr. Phillip M. Feldman wrote: > It seems as though Python is actually expanding range(2,n) into a list > of numbers, even though this is incredibly wasteful of memory. There > should be a looping mechanism that generates the index variable values > incrementally as they are needed. Others have already pointed out to you that xrange() (for Python 2.x) does what you want. In Python 3.x, the old range() is gone for good, and xrange() renamed to just range(). However, I'd like to point out that your subject line is fundamentally incorrect. What you've discovered has *nothing* to do with for-loops: the for-loop will happily iterate over whatever object you pass to it (or at least try to, because not all objects are iterable). You might be thinking that Python requires you to write for-loops as for i in range(...): but that's not correct. The for-loop doesn't care what object comes after the "in" and before the ":", so long as it can iterate over it one item at a time: for i in [1, 3, 4, 5, 2, 0, -1, 8, 7, 6]: print i for c in "abcd": print c and many other variations will work perfectly fine. The memory-consumption you have discovered is a property of the range() function, not the for-loop: >>> L = range(2, 20) >>> L [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] Compare to xrange: >>> L = xrange(2, 20) >>> L xrange(2, 20) >>> list(L) # expand out into a list [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] By the way, both range() and xrange() take an optional 'stepsize' argument, defaulting to 1: >>> range(3, 20, 2) [3, 5, 7, 9, 11, 13, 15, 17, 19] help(range) and help(xrange) in the interactive interpreter are your friends. -- Steven From candide at free.invalid Sat Aug 15 08:28:27 2009 From: candide at free.invalid (candide) Date: Sat, 15 Aug 2009 14:28:27 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: <4a85ffe2$0$24643$426a34cc@news.free.fr> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <4a86a9eb$0$1557$426a34cc@news.free.fr> Thanks to all for your response. I particularly appreciate Rascal's solution. From steve at REMOVE-THIS-cybersource.com.au Sat Aug 15 08:39:47 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2009 12:39:47 GMT Subject: unittest References: <75330ab0-329c-4842-a5b0-ddf0ccefe8ea@r18g2000yqd.googlegroups.com> Message-ID: <02969ce9$0$20647$c3e8da3@news.astraweb.com> On Sat, 15 Aug 2009 07:32:15 -0400, Mag Gam wrote: > So, in this example: > > "import random" > > In my case I would do "import foo" ? is there anything I need to do for > that? Suppose you have a file mymodule.py containing your code, and you want some unit tests. If you only have a few, you can probably put them inside mymodule.py, but let's say you have lots and want to keep them in a separate file. So create a new module mymoduletests.py, and start it like this: # mymoduletests.py import unittest import mymodule class MyTests(unittest.TestCase): # Inherit from the TestCase class. # Put your tests inside this class def test_module_has_docstring(self): """Fail if the module has no docstring, or if it is empty.""" docstring = mymodule.__doc__ self.assert_(docstring is not None) self.assert_(docstring.strip() != '') if __name__ == '__main__': # only execute this part when you run the module # not when you import it unittest.main() Now to actually run the tests, from command-line, type: python mymoduletests.py and hit enter. (You do this from the operating system shell, not the Python interactive interpreter.) You should see something like this: . ---------------------------------------------------------------------- Ran 1 tests in 0.001s OK -- Steven From michael at stroeder.com Sat Aug 15 08:40:35 2009 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Sat, 15 Aug 2009 14:40:35 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <4vmil6-ait.ln1@nb2.stroeder.com> Hendrik van Rooyen wrote: > In the past, on this group, I have made statements that said that on Linux, > the serial port handling somehow does not allow transmitting and receiving at > the same time, and nobody contradicted me. Despite all the good comments here by other skilled people I'd recommend to determine whether the transmission line to the devices accessed support full duplex. My knowledge is a bit rusty on this topic. But I vaguely remember having to deal with symmetric two-wire connections (RS-485) which were definitely limited to half-duplex by the wire. So the PC hardware was a normal serial port with the usual UART hardware device but the transmission protocols were limited to half-duplex. Ciao, Michael. From zuo at chopin.edu.pl Sat Aug 15 09:38:53 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 15 Aug 2009 15:38:53 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: <3842c750-9633-4e8e-84da-4853784bce64@v37g2000prg.googlegroups.com> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> <3842c750-9633-4e8e-84da-4853784bce64@v37g2000prg.googlegroups.com> Message-ID: Dnia 15-08-2009 o 08:08:14 Rascal wrote: > I'm bored for posting this, but here it is: > > def add_commas(str): > str_list = list(str) > str_len = len(str) > for i in range(3, str_len, 3): > str_list.insert(str_len - i, ',') > return ''.join(str_list) For short strings (for sure most common case) it's ok: simple and clear. But for huge ones, it's better not to materialize additional list for the string -- then pure-iterator-sollutions would be better (like Gabriel's or mine). Cheers, *j -- Jan Kaliszewski (zuo) From davea at ieee.org Sat Aug 15 09:44:25 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 15 Aug 2009 09:44:25 -0400 Subject: Python 2.6 still not giving memory back to the OS... In-Reply-To: <4A86A239.3030404@simplistix.co.uk> References: <4A86A239.3030404@simplistix.co.uk> Message-ID: <4A86BBB9.5010705@ieee.org> Chris Withers wrote: >
Hi All, > > I thought this was fixed back in Python 2.5, but I guess not? > > So, I'm playing in an interactive session: > > >>> from xlrd import open_workbook > >>> b = open_workbook('some.xls',pickleable=0,formatting_info=1) > > At this point, top shows the process usage for python to be about 500Mb. > That's okay, I'd expect that, b is big ;-) > > >>> del b > > However, it still does now, maybe the garbage collector needs a kick? > > >>> import gc > >>> gc.collect() > 702614 > > Nope, still 500Mb. What gives? How can I make Python give the memory > its no longer using back to the OS? > > Okay, so maybe this is something to do with it being an interactive > session? So I wrote this script: > > from xlrd import open_workbook > import gc > b = open_workbook('some.xls',pickleable=0,formatting_info=1) > print 'opened' > raw_input() > del b > print 'deleted' > raw_input() > gc.collect() > print 'gc' > raw_input() > > The raw inputs are there so I can check the memory usage in top. > Even after the gc, Python still hasn't given the memory back to the OS > :-( > > What am I doing wrong? > > Chris > You're not doing anything wrong. I don't know of any other environment that "gives the memory back" to the OS. I don't know Unix/Linux memory management, but I do know Windows, and I suspect the others are quite similar. There are a few memory allocators within Windows itself, and some more within the MSC runtime library. They work similarly enough that I can safely just choose one to explain. I'll pick on malloc(). When malloc() is called for the first time (long before your module is loaded), it asks the operating system's low-level mapping allocator for a multiple of 64k. The 64k will always be aligned on a 64k boundary, and is in turn divided into 4k pages. The 64k could come from one of three places - the swapfile, an executable (or DLL), or a data file, but there's not much real difference between those. malloc() itself will always use the swapfile. Anyway, at this point my memory is a little bit fuzzy. I think only 4k of the swapfile is actually mapped in, the rest being reserved. But malloc() will then build some data structures for that 64k block, and as memory is requested, get more and more pieces of that 64k, till the whole thing is mapped in. Then, additional multiples of 64k are allocated in the same way, and of course the data structures are chained together. If an application "frees" a block, the data structure is updated, but the memory is not unmapped. Theoretically, if all the blocks within one 64k were freed, malloc() could release the 64k block to the OS, but to the best of my knowledge, malloc() never does. Incidentally, there's a different scheme for large blocks, but that's changed several times, and I have no idea how it's done now. Now, C programmers sometimes write a custom allocator, and in C++, it's not hard to have a custom allocator manage all instances of a particular class. This can be convenient for applications that know how their memory usage patterns are likely to work. Photoshop for example can be configured to use "user swap space" (I forget what they call it) from files that Photoshop explicitly allocates. And space from that allocator is not from the swapfile, so it's not constrained by other running applications, and wouldn't be counted by the Windows equivalent of 'top' (eg. the Windows Task Manager). A custom allocator can also be designed to know when a particular set of allocations are all freed, and release the memory entirely back to the system. For instance, if all temp data for a particular transaction is put into an appropriate custom allocator, then at the end of the transaction, it can safely be released. I would guess that Python doesn't do any custom allocators, and therefore never releases the memory back to the system. It will however reuse it when you allocate more stuff. DaveA (author of the memory tracking subsystem of NuMega's BoundsChecker) From grante at visi.com Sat Aug 15 10:25:03 2009 From: grante at visi.com (Grant Edwards) Date: Sat, 15 Aug 2009 09:25:03 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: Message-ID: On 2009-08-15, Hendrik van Rooyen wrote: > On Friday 14 August 2009 16:19:04 Grant Edwards wrote: > >> What platform are you using? I suppose it's possible that >> there's something broken in the serial driver for that >> particular hardware. > > Your experience seems to be exactly the opposite to mine - you > are saying it should "just work" and I am seeing half duplex > functionality. If you're using Python's normal open()/read()/write() calls, then that introduces all sorts of issues. I always use direct OS calls os.open(), os.read(), os.write(). > Any comments from a Linux Guru? Are you using python file operations open/read/write or OS file-descriptor operations os.open/os.read/os.write? -- Grant From grante at visi.com Sat Aug 15 10:37:42 2009 From: grante at visi.com (Grant Edwards) Date: Sat, 15 Aug 2009 09:37:42 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: <7el95aF2h0d12U1@mid.uni-berlin.de> Message-ID: On 2009-08-15, Hendrik van Rooyen wrote: > On Friday 14 August 2009 16:03:22 Diez B. Roggisch wrote: > >> You should *really* just use pyserial. No hassle, instant satisfaction. > >:-) I have downloaded and had a quick look, and I see it is > based on the standard library's serial.Serial class - another > battery that I have not used before. There is no "serial" module in the standard library. The serial module is provided by pyserial. > And I see that serial.Serial looks like it uses os. calls, > which is one of the things Greg mentioned. Indeed. You shouldn't try to use normal open/read/write calls with serial ports. -- Grant From grante at visi.com Sat Aug 15 10:40:09 2009 From: grante at visi.com (Grant Edwards) Date: Sat, 15 Aug 2009 09:40:09 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: <7el2mqF2gi53eU1@mid.individual.net> <1aGdnessDpUX6RjXnZ2dnUVZ_gCdnZ2d@posted.visi> Message-ID: On 2009-08-15, Hendrik van Rooyen wrote: > 8< ---------------------------------PosixSerial.py---------------------------- > > Thanks that looks, on first inspection, similar to the > serialposix.py module in the stdlib, but less cluttered. pyserial is a bit more complex because it is cross-platform and supports Windows, as well as RFC2272 telnet backends (and OS X?). The Posix support in pyserial is based on an earlier version of PosixSerial. -- Grant From Scott.Daniels at Acm.Org Sat Aug 15 12:11:49 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 15 Aug 2009 09:11:49 -0700 Subject: callable virtual method In-Reply-To: References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> Message-ID: Jean-Michel Pichavant wrote: > Steven D'Aprano wrote: >> On Fri, 14 Aug 2009 18:49:26 +0200, Jean-Michel Pichavant wrote: >> >> >>> Sorry guys (means guys *and* gals :op ), I realized I've not been able >>> to describe precisely what I want to do. I'd like the base class to be >>> virtual (aka abstract). However it may be abstract but it does not mean >>> it cannot do some usefull stuff. >>> >>> >>> Here is the schema of my abstract methods : >>> >>> class Interface(object): >>> def method(self): >>> # --------------------- >>> # some common stuff executed here >>> # --------------------- >>> print 'hello world' >>> # --------------------- >>> # here shall stand child specific stuff (empty in the interface >>> method) >>> # --------------------- >>> if self.__class__.method == Interface.method: >>> raise NotImplementedError('You should have read the f****** >>> manual ! You must override this method.') >>> >> >> >> Okay, so I want to sub-class your Interface class. As you said, the >> methods in the abstract class are still useful, so in my class, I >> don't need any extra functionality for some methods -- I'm happy with >> just the "common stuff". So I use normal OO techniques and over-ride >> just the methods I need to over-ride: >> >> > Sometimes the base is doing cool stuff but incomplete stuff which > requires knowledge only hold by the sub class. In my case the interface > is a high level interface for a software that can run on multiple > hardware platforms. Only the sub class has knowledge on how to operate > the hardware, but no matter the hardware it still produces the same effect. > > Let's say I have 50 different hardwares, I'll have 50 sub classes of > Interface with the 'start' method to define. It wouldn't be appropriate > (OO programming)to write 50 times '_log.debug('Starting %s' % self)' in > each child start method when the simple task of logging the call can be > nicely handled by the base class. > > In the meantime, I must make sure the user, who is not a python guru in > this case, has implemented the start method for his hardware, because > only him knows how to effectively start this hardware. I don't want him > to come to me saying, "I got no error, still my hardware does not > start". You can then blame him for not reading the docs, but it will > still be less expensive to throw a nice exception with an accurate > feedback. > > [snip] >> class VerboseGoodChild(Interface): >> # forced to over-ride methods for no good reason >> > > Definitely no !! This is the purpose of an interface class: to force > people to write these methods. They *are* required, if they were not, > they would not belong to the Interface. > > JM But there _is_ one moment when you can check those things, then avoid checking thereafter: object creation. So you can complicate your __init__ (or __new__) with those checks that make sure you instantiate only fully defined subclasses: # obviously not tested except in concept: class Base(object_or_whatever): def __init__(self, ...): class_ = self.__class__ if class_ is Base: raise TypeError('Attempt to instantiate Base class') for name in 'one two three four': if getattr(Base, name) is not getattr(Base, name): raise NotImplementedError( '%s implementation missing' % name) ... --Scott David Daniels Scott.Daniels at Acm.Org From dickinsm at gmail.com Sat Aug 15 12:41:44 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 15 Aug 2009 09:41:44 -0700 (PDT) Subject: Python 2.6 still not giving memory back to the OS... References: Message-ID: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> On Aug 15, 12:55?pm, Chris Withers wrote: > Hi All, > > I thought this was fixed back in Python 2.5, but I guess not? > > So, I'm playing in an interactive session: > > ?>>> from xlrd import open_workbook > ?>>> b = open_workbook('some.xls',pickleable=0,formatting_info=1) > > At this point, top shows the process usage for python to be about 500Mb. > That's okay, I'd expect that, b is big ;-) > > ?>>> del b > > However, it still does now, maybe the garbage collector needs a kick? > > ?>>> import gc > ?>>> gc.collect() > 702614 > > Nope, still 500Mb. What gives? How can I make Python give the memory its > no longer using back to the OS? > [...] Can you get the same effects without using the xlrd module? I don't have xlrd installed on my system (OS X 10.5/Intel), but I just tried the following: Python 2.6.2 (r262:71600, Jun 17 2009, 09:08:27) [GCC 4.0.1 (Apple Inc. build 5490)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> b = 'x'*(10**9) >>> f = open('testfile.txt', 'w') >>> f.write(b) >>> del b >>> f = open('testfile.txt') >>> b = f.read() >>> del b and got the expected memory usage for my Python process, as displayed by top: memory usage went up to nearly 1Gb after each assignment to b, then dropped down to 19 Mb or so after each 'del b'. I get similar results under Python 2.5. So maybe there's something in xlrd that's hanging on to all that memory? Mark From breamoreboy at yahoo.co.uk Sat Aug 15 12:47:07 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Aug 2009 17:47:07 +0100 Subject: Python docs disappointing - group effort to hire writers? In-Reply-To: References: <09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com> <109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com> <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> <93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com> <96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com> Message-ID: Bill Jones wrote: > On Aug 8, 3:27 pm, Mark Lawrence wrote: >> Kee Nethery wrote: >>> As someone trying to learn the language I want to say that the tone on >>> this list towards people who are trying to learn Python feels like it >>> has become anti-newbies. >> [snip] >> >>> Kee Nethery >> My gut feeling (which could of course be wrong) is that many hard core >> Pythonistas are cheesed off with newbies who refuse to help themselves. > > The funny thing is that their response is to shutdown changes that are > intended > to *help* newbies help themselves. It seems self-defeating to me. > And I still do not believe this to be true. Documents are being changed all the time. See the python-dev mailing list "Summary of python tracker issues" dated 17/24/31 July and 07/14 August 2009. The only request I recall being rejected is someone objecting to the use of "weapons" in a piece of sample code. Also see Issue6660 on the bug tracker, it is of particular interest to anyone who's interested in plans for python.org documentation links. -- Kindest regards. Mark Lawrence. From markstahler at gmail.com Sat Aug 15 13:01:15 2009 From: markstahler at gmail.com (kramed) Date: Sat, 15 Aug 2009 10:01:15 -0700 (PDT) Subject: Error: No SSL support included in this Python ? Message-ID: Hi there, I am running Windows on my dev machine and am running into the following error while running Django and my email routines. Exception Type: RuntimeError Exception Value: No SSL support included in this Python Exception Location: C:\Python26\lib\smtplib.py in starttls, line 615 This may sounds stupid but I thought SSL support was baked into Python? I am running Active State Python 2.6.2 and Django 1.1. The code works on my server but emails are not being sent properly so I need to debug the app. Can someone please point out what I am missing. Thanks From breamoreboy at yahoo.co.uk Sat Aug 15 13:06:04 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Aug 2009 18:06:04 +0100 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> Message-ID: Xavier Ho wrote: > Hey all, > > I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in the > documentation. > > Is there a substitution for this special method in 3.1, or do I really have > to define all six rich comparison methods to work it out? > > If this question has already been asked somewhere, I apologise in advance. > Already googled around but I didn't find information on this. > > Any replies appreciated. > > Ching-Yun "Xavier" Ho, Technical Artist > > Contact Information > Mobile: (+61) 04 3335 4748 > Skype ID: SpaXe85 > Email: contact at xavierho.com > Website: http://xavierho.com/ > > http://bytes.com/topic/python/answers/844614-python-3-sorting-comparison-function -- Kindest regards. Mark Lawrence. From Scott.Daniels at Acm.Org Sat Aug 15 13:11:29 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 15 Aug 2009 10:11:29 -0700 Subject: unittest In-Reply-To: References: Message-ID: Mag Gam wrote: > I am writing an application which has many command line arguments. > For example: foo.py -args "bar bee" > > I would like to create a test suit using unittest so when I add > features to "foo.py" I don't want to break other things. I just heard > about unittest and would love to use it for this type of thing. > > so my question is, when I do these tests do I have to code them into > foo.py? I prefer having a footest.py which will run the regression > tests. Any thoughts about this? > > TIA I avoid putting the tests in foo.py, simply because the bulk of my tests would make the code harder to read. So, no, unittest does not require that you code things into foo.py. You will find that you may bend your coding style within foo.py in order to make it more testable, but (if you do it right) that should also make the code clearer. --Scott David Daniels Scott.Daniels at Acm.Org From breamoreboy at yahoo.co.uk Sat Aug 15 13:12:33 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Aug 2009 18:12:33 +0100 Subject: What's a good solution to implement rich comparison for user-defined classes? (was: What happened to __cmp__() in Python 3.x?) In-Reply-To: <2d56febf0908150516i7fb00b80ub3e9481c8bf3f3f9@mail.gmail.com> References: <2d56febf0908150516i7fb00b80ub3e9481c8bf3f3f9@mail.gmail.com> Message-ID: Xavier Ho wrote: > Never mind my last email. Google actually found me something at last. > > I also found this page: > http://mail.python.org/pipermail/python-list/2008-November/688591.html > > That still uses a sloppy way of defining the special methods, and a little > chunky. > > Is there a better way for the lazy me? > > Ching-Yun "Xavier" Ho, Technical Artist > > Contact Information > Mobile: (+61) 04 3335 4748 > Skype ID: SpaXe85 > Email: contact at xavierho.com > Website: http://xavierho.com/ > > Did you follow on to this? http://mail.python.org/pipermail/python-list/2008-November/688661.html I think it's your call as to what to do next. -- Kindest regards. Mark Lawrence. From hendrik at microcorp.co.za Sat Aug 15 13:18:53 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 19:18:53 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <4vmil6-ait.ln1@nb2.stroeder.com> References: <4vmil6-ait.ln1@nb2.stroeder.com> Message-ID: <200908151918.54065.hendrik@microcorp.co.za> On Saturday 15 August 2009 14:40:35 Michael Str?der wrote: > Hendrik van Rooyen wrote: > > In the past, on this group, I have made statements that said that on > > Linux, the serial port handling somehow does not allow transmitting and > > receiving at the same time, and nobody contradicted me. > > Despite all the good comments here by other skilled people I'd recommend to > determine whether the transmission line to the devices accessed support > full duplex. > > My knowledge is a bit rusty on this topic. But I vaguely remember having to > deal with symmetric two-wire connections (RS-485) which were definitely > limited to half-duplex by the wire. So the PC hardware was a normal serial > port with the usual UART hardware device but the transmission protocols > were limited to half-duplex. You raise a good point, that is probably not well known amongst the youngsters here, as simple serial multidropping has gone out of fashion. There is nothing wrong with your memory as far as RS-485 goes - you have to "turn the line around", same as for *shudder* Burroughs TDI (Two Wire Direct Interface). Otherwise, if two or more parties talk at once you have cacophony. An RS-422 link is to some extent worse, as it is capable of full duplex, but the slaves cannot hear each other, so they have to listen and play very nicely with the master. This instance Is not one of those, thank heaven - I am on both sides of the link - once in the eBox in python, and on the other side there is just one Dallas chip - a fast (30 Mhz single cycle) 8051 lookalike that I programmed in assembler. It is a thing that does discrete I/O that we have made for a customer. The link in between is just RS-232 receive and transmit without hardware flow control or anything fancy. This is why I was so certain that there was something wrong in my python part, because I could use the second port on the Dallas to do monitoring, by spewing stuff out into Hyper Terminal. - Hendrik From python-url at phaseit.net Sat Aug 15 13:23:36 2009 From: python-url at phaseit.net (Gabriel Genellina) Date: Sat, 15 Aug 2009 17:23:36 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Aug 15) Message-ID: QOTW: "They questioned my competence and that made her very sad." - Roger Wallis,expert witness for Pirate Bay, on his wife http://torrentfreak.com/pirate-bay-witness-wife-overwhelmed-with-flowers-090227/ unicode(s) is, surprisingly, MUCH faster (for certain encodings) than s.decode(): http://groups.google.com/group/comp.lang.python/browse_thread/thread/314a3043ea63319f/ It is not possible to overload a compound "< <" operator (as in: a < x < b): http://groups.google.com/group/comp.lang.python/browse_thread/thread/5b931a6417b7829d/ Automatic join of "consecutive" " string " "literals": bug or feature? http://groups.google.com/group/comp.lang.python/browse_thread/thread/174d4e2b7c0203d/ Also, unrecognized escape sequences in string literals stay in the string: bug or feature? http://groups.google.com/group/comp.lang.python/browse_thread/thread/4e1ea6f550a8a1d1/ Restricting dictionary keys to those objects explicitely defining __eq__ / __hash__ may be useful in certain cases: http://groups.google.com/group/comp.lang.python/browse_thread/thread/d35856349110c18c/ How to find out in which module an instance was created? http://groups.google.com/group/comp.lang.python/browse_thread/thread/6acd71c326591325/ Monkey-patching an instance to make it callable (without altering other instances of the same class): http://groups.google.com/group/comp.lang.python/browse_thread/thread/6fdfc6458d82b581/ reload() and the 'from ... import ...' form of the import statement: http://groups.google.com/group/comp.lang.python/browse_thread/thread/994a6af36febabb5/ Several recipes to extract unique elements from a list: http://groups.google.com/group/comp.lang.python/t/e5015c12a57b46b8/ All those __double_underscored__ names are confusing - why do they exist? http://groups.google.com/group/comp.lang.python/t/e75ce772af98aaac/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiasts": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python Enjoy the *Python Magazine*. http://pymag.phparch.com/ *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From emile at fenx.com Sat Aug 15 13:28:00 2009 From: emile at fenx.com (Emile van Sebille) Date: Sat, 15 Aug 2009 10:28:00 -0700 Subject: Splitting a string into substrings of equal size In-Reply-To: <4a85ffe2$0$24643$426a34cc@news.free.fr> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: On 8/14/2009 5:22 PM candide said... > Suppose you need to split a string into substrings of a given size (except > possibly the last substring). I make the hypothesis the first slice is at the > end of the string. > A typical example is provided by formatting a decimal string with thousands > separator. > > > What is the pythonic way to do this ? I like list comps... >>> jj = '1234567890123456789' >>> ",".join([jj[ii:ii+3] for ii in range(0,len(jj),3)]) '123,456,789,012,345,678,9' >>> Emile From hendrik at microcorp.co.za Sat Aug 15 13:33:10 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 19:33:10 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <200908151933.10803.hendrik@microcorp.co.za> On Saturday 15 August 2009 16:25:03 Grant Edwards wrote: > > Are you using python file operations open/read/write or OS > file-descriptor operations os.open/os.read/os.write? The former - that seems to be the source of my trouble. I have now written a little test that uses serial.Serial and it works a treat. I am still confused about pyserial and serial - I found serial in my distribution library, (on the SuSe machine, not on the 2.5 in Slackware) but I had to download pyserial. I see that you were the the original author. Thank you for letting this stuff loose in the wild. - Hendrik From lists at cheimes.de Sat Aug 15 14:05:36 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 15 Aug 2009 20:05:36 +0200 Subject: Python 2.6 still not giving memory back to the OS... In-Reply-To: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> References: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> Message-ID: <4A86F8F0.5060101@cheimes.de> Mark Dickinson wrote: > and got the expected memory usage for my Python process, as > displayed by top: memory usage went up to nearly 1Gb after > each assignment to b, then dropped down to 19 Mb or so after > each 'del b'. I get similar results under Python 2.5. I get the same results on Linux: Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os, psutil >>> pi = psutil.Process(os.getpid()) >>> [mem/1024.**2 for mem in pi.get_memory_info()] [4.71875, 28.2578125] >>> s = 'x' * (10**9) >>> [mem/1024.**2 for mem in pi.get_memory_info()] [958.40234375, 981.93359375] >>> del s >>> [mem/1024.**2 for mem in pi.get_memory_info()] [11.62890625, 55.1875] Christian From lists at cheimes.de Sat Aug 15 14:05:36 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 15 Aug 2009 20:05:36 +0200 Subject: Python 2.6 still not giving memory back to the OS... In-Reply-To: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> References: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> Message-ID: <4A86F8F0.5060101@cheimes.de> Mark Dickinson wrote: > and got the expected memory usage for my Python process, as > displayed by top: memory usage went up to nearly 1Gb after > each assignment to b, then dropped down to 19 Mb or so after > each 'del b'. I get similar results under Python 2.5. I get the same results on Linux: Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os, psutil >>> pi = psutil.Process(os.getpid()) >>> [mem/1024.**2 for mem in pi.get_memory_info()] [4.71875, 28.2578125] >>> s = 'x' * (10**9) >>> [mem/1024.**2 for mem in pi.get_memory_info()] [958.40234375, 981.93359375] >>> del s >>> [mem/1024.**2 for mem in pi.get_memory_info()] [11.62890625, 55.1875] Christian From roy at panix.com Sat Aug 15 14:17:39 2009 From: roy at panix.com (Roy Smith) Date: Sat, 15 Aug 2009 14:17:39 -0400 Subject: getting the fractional part of a real? Message-ID: What's the best way to get the fractional part of a real? The two ways I can see are r % 1 and r = int(r), but both seem a bit hokey. Is there something more straight-forward that I'm missing, like fraction(r)? From lists at cheimes.de Sat Aug 15 14:40:54 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 15 Aug 2009 20:40:54 +0200 Subject: getting the fractional part of a real? In-Reply-To: References: Message-ID: <4A870136.70306@cheimes.de> Roy Smith schrieb: > What's the best way to get the fractional part of a real? The two ways I > can see are r % 1 and r = int(r), but both seem a bit hokey. Is there > something more straight-forward that I'm missing, like fraction(r)? >>> import math >>> math.modf(1.5) (0.5, 1.0) Christian From gregor.lingl at aon.at Sat Aug 15 14:48:51 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sat, 15 Aug 2009 20:48:51 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: <4a85ffe2$0$24643$426a34cc@news.free.fr> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <4A870313.4040702@aon.at> > What is the pythonic way to do this ? > > > For my part, i reach to this rather complicated code: > > > # ---------------------- > > def comaSep(z,k=3, sep=','): > z=z[::-1] > x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] > return sep.join(x) > > # Test > for z in ["75096042068045", "509", "12024", "7", "2009"]: > print z+" --> ", comaSep(z) > Just if you are interested, a recursive solution: >>> def comaSep(z,k=3,sep=","): return comaSep(z[:-3],k,sep)+sep+z[-3:] if len(z)>3 else z >>> comaSep("7") '7' >>> comaSep("2007") '2,007' >>> comaSep("12024") '12,024' >>> comaSep("509") '509' >>> comaSep("75096042068045") '75,096,042,068,045' >>> Gregor From gregor.lingl at aon.at Sat Aug 15 14:49:45 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sat, 15 Aug 2009 20:49:45 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: <4a85ffe2$0$24643$426a34cc@news.free.fr> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <4a870358$0$2292$91cee783@newsreader02.highway.telekom.at> > What is the pythonic way to do this ? > > > For my part, i reach to this rather complicated code: > > > # ---------------------- > > def comaSep(z,k=3, sep=','): > z=z[::-1] > x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] > return sep.join(x) > > # Test > for z in ["75096042068045", "509", "12024", "7", "2009"]: > print z+" --> ", comaSep(z) > Just if you are interested, a recursive solution: >>> def comaSep(z,k=3,sep=","): return comaSep(z[:-3],k,sep)+sep+z[-3:] if len(z)>3 else z >>> comaSep("7") '7' >>> comaSep("2007") '2,007' >>> comaSep("12024") '12,024' >>> comaSep("509") '509' >>> comaSep("75096042068045") '75,096,042,068,045' >>> Gregor From dickinsm at gmail.com Sat Aug 15 14:50:00 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 15 Aug 2009 11:50:00 -0700 (PDT) Subject: getting the fractional part of a real? References: Message-ID: <9e6ce7f2-deba-4538-88f3-2d44ab5ada4b@e27g2000yqm.googlegroups.com> On Aug 15, 7:40?pm, Christian Heimes wrote: > Roy Smith schrieb: > > > What's the best way to get the fractional part of a real? ?The two ways I > > can see are r % 1 and r = int(r), but both seem a bit hokey. ?Is there > > something more straight-forward that I'm missing, like fraction(r)? > >>> import math > >>> math.modf(1.5) > > (0.5, 1.0) What Christian said. math.fmod(r, 1.0) also works. Note that r % 1 and r - int(r) aren't the same thing for negative reals. What sign do you want the result to have when r is negative? Mark From gregor.lingl at aon.at Sat Aug 15 14:50:03 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sat, 15 Aug 2009 20:50:03 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <4a87036a$0$2292$91cee783@newsreader02.highway.telekom.at> Emile van Sebille schrieb: > On 8/14/2009 5:22 PM candide said... ... >> What is the pythonic way to do this ? > > I like list comps... > > >>> jj = '1234567890123456789' > >>> ",".join([jj[ii:ii+3] for ii in range(0,len(jj),3)]) > '123,456,789,012,345,678,9' > >>> > > Emile > Less beautiful but more correct: >>> ",".join([jj[max(ii-3,0):ii] for ii in range(len(jj)%3,len(jj)+3,3)]) '1,234,567,890,123,456,789' Gregor From gregor.lingl at aon.at Sat Aug 15 14:55:55 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sat, 15 Aug 2009 20:55:55 +0200 Subject: getting the fractional part of a real? In-Reply-To: References: Message-ID: <4a8704ca$0$2292$91cee783@newsreader02.highway.telekom.at> Christian Heimes schrieb: > Roy Smith schrieb: >> What's the best way to get the fractional part of a real? The two >> ways I can see are r % 1 and r = int(r), but both seem a bit hokey. >> Is there something more straight-forward that I'm missing, like >> fraction(r)? > >>>> import math >>>> math.modf(1.5) > (0.5, 1.0) > > Christian Or without the need to import something: >>> divmod(1.5, 1) (1.0, 0.5) >>> Gregor From nagle at animats.com Sat Aug 15 15:24:26 2009 From: nagle at animats.com (John Nagle) Date: Sat, 15 Aug 2009 12:24:26 -0700 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode In-Reply-To: References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: <4a870a7b$0$1674$742ec2ed@news.sonic.net> fortunatus wrote: > On Aug 14, 1:01 pm, vippstar wrote: >> Why would you fill your website with junk? > > The OP made it clear: > >> Just wanted to express some frustration with whitespace-mode. Well, it took until Python 3.0 until Python enforced rules that ensured that the indentation the user sees is the same indentation the compiler sees. We finally have a solution that allows both tabs and spaces but disallows the situations which are ambiguous. Until Python 3.0 is fully deployed, there are situations when you need an insane level of tab/space visibility. Blame Python, not EMACS. John Nagle From nagle at animats.com Sat Aug 15 15:34:15 2009 From: nagle at animats.com (John Nagle) Date: Sat, 15 Aug 2009 12:34:15 -0700 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <24980842.post@talk.nabble.com> Message-ID: <4a870cc7$0$1674$742ec2ed@news.sonic.net> Hendrik van Rooyen wrote: > On Saturday 15 August 2009 03:25:45 Dr. Phillip M. Feldman wrote: > And while you are about it, you may as well teach them that it is much better > to do a multiplication than a division. Actually, division speed hasn't been much of an issue in years. Arithmetic has been faster than memory access since CPUs went superscalar. In CPython, with all the interpreter overhead, you'll probably never notice the difference. I'd thought "xrange" had already been obsoleted, and hadn't realized the 2.3 - 2.6 versions of CPython were still doing "range" the hard way, not as a generator. John Nagle From alan.isaac at gmail.com Sat Aug 15 15:49:35 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Sat, 15 Aug 2009 19:49:35 GMT Subject: random.gauss vs. random.normalvariate Message-ID: Quoting http://docs.python.org/3.1/library/random.html#random.gauss: Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function defined below. So since both are offered and gauss is faster, I assume it must have some offsetting disadvantage. What is it? Thank you, Alan Isaac From roy at panix.com Sat Aug 15 16:01:25 2009 From: roy at panix.com (Roy Smith) Date: Sat, 15 Aug 2009 16:01:25 -0400 Subject: getting the fractional part of a real? References: <4a8704ca$0$2292$91cee783@newsreader02.highway.telekom.at> Message-ID: In article <4a8704ca$0$2292$91cee783 at newsreader02.highway.telekom.at>, Gregor Lingl wrote: > Christian Heimes schrieb: > > Roy Smith schrieb: > >> What's the best way to get the fractional part of a real? The two > >> ways I can see are r % 1 and r = int(r), but both seem a bit hokey. > >> Is there something more straight-forward that I'm missing, like > >> fraction(r)? > > > >>>> import math > >>>> math.modf(1.5) > > (0.5, 1.0) > > > > Christian > > Or without the need to import something: > > >>> divmod(1.5, 1) > (1.0, 0.5) > >>> > > Gregor Thanks. I knew I had to be missing something obvious. Regarding Mark Dickinson's question about what I want for negative reals, for the application I have in mind, r is guaranteed to be positive. From darkwater42 at gmail.com Sat Aug 15 16:01:43 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sat, 15 Aug 2009 13:01:43 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> On Aug 14, 10:25?pm, Dave Angel wrote: > Benjamin Kaplan wrote: > > On Fri, Aug 14, 2009 at 12:42 PM, Douglas Alan wrote: > >> P.S. Overloading "left shift" to mean "output" does indeed seem a bit > >> sketchy, but in 15 years of C++ programming, I've never seen it cause > >> any confusion or bugs. > > The only reason it hasn't is because people use it in "Hello World". I bet > > some newbie C++ programmers get confused the first time they see << used to > > shift. People typically get confused by a *lot* of things when they learn a new language. I think the better metric is how people fare with a language feature once they've grown accustomed to the language, and how long it takes them to acquire this familiarity. > Actually, I've seen it cause confusion, because of operator precedence. ? > The logical shift operators have a fairly high level priority, so > sometimes you need parentheses that aren't obvious. ?Fortunately, most > of those cases make compile errors. I've been programming in C++ so long that for me, if there's any confusion, it's the other way around. I see "<<" or ">>" and I think I/ O. I don't immediately think shifting. Fortunately, shifting is a pretty rare operation to actually use, which is perhaps why C++ reclaimed it for I/O. On the other hand, you are right that the precedence of "<<" is messed up for I/O. I've never seen a real-world case where this causes a bug in C++ code, because the static type-checker always seems to catch the error. In a dynamically typed language, this would be a much more serious problem. |>ouglas P.S. I find it strange, however, that anyone who is not okay with "abusing" operator overloading in this manner, wouldn't also take umbrage at Python's overloading of "+" to work with strings and lists, etc. Numerical addition and sequence concatenation have entirely different semantics. From bouncyinc at gmail.com Sat Aug 15 16:14:17 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 14:14:17 -0600 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <02957d23$0$20647$c3e8da3@news.astraweb.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: I guess the problem is---does it actually matter? On Fri, Aug 14, 2009 at 10:11 AM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: > > > "I saw `cout' being shifted "Hello world" times to the left and stopped > > right there." --Steve Gonedes > > Assuming that's something real, and not invented for humour, I presume > that's describing something possible in C++. Am I correct? What the hell > would it actually do??? > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wgwinder at gmail.com Sat Aug 15 16:17:02 2009 From: wgwinder at gmail.com (wgw) Date: Sat, 15 Aug 2009 13:17:02 -0700 (PDT) Subject: PyQt4.__file__ gives PyQt4/__init__.py as value Message-ID: <0b3b6163-3fb3-4b1b-9605-bf899f65b9e9@o6g2000yqj.googlegroups.com> I don't understand why the __file__ value in my installation of PyQt would not give a proper, full path. I'm guessing that I did not install pyqt properly (I'm on Ubuntu Hardy, trying to install QT4.5), but before redoing the install, I want to see if there is a quicker fix. Also, though PyQt4/ is in the site-packages directory, and loads properly into the interactive environment. Yolk does not list it. ??? Something strange here! Any suggestions? From metolone+gmane at gmail.com Sat Aug 15 16:22:39 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 15 Aug 2009 13:22:39 -0700 Subject: Splitting a string into substrings of equal size References: <4a85ffe2$0$24643$426a34cc@news.free.fr> <4a87036a$0$2292$91cee783@newsreader02.highway.telekom.at> Message-ID: "Gregor Lingl" wrote in message news:4a87036a$0$2292$91cee783 at newsreader02.highway.telekom.at... > Emile van Sebille schrieb: >> On 8/14/2009 5:22 PM candide said... > ... >>> What is the pythonic way to do this ? >> >> I like list comps... >> >> >>> jj = '1234567890123456789' >> >>> ",".join([jj[ii:ii+3] for ii in range(0,len(jj),3)]) >> '123,456,789,012,345,678,9' >> >>> >> >> Emile >> > > Less beautiful but more correct: > > >>> ",".join([jj[max(ii-3,0):ii] for ii in > range(len(jj)%3,len(jj)+3,3)]) > '1,234,567,890,123,456,789' > > Gregor Is it? >>> jj = '234567890123456789' >>> ",".join([jj[max(ii-3,0):ii] for ii in range(len(jj)%3,len(jj)+3,3)]) ',234,567,890,123,456,789' At least one other solution in this thread had the same problem. -Mark From bouncyinc at gmail.com Sat Aug 15 16:23:26 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 14:23:26 -0600 Subject: redoing libgmail interface to "smtplib" blah? Message-ID: The following program is theoretically supposed to use a supported library. Issues have come up where the library is not working and now another interface is being requierd to be used. At this point I'm looking at just changing the send commands but don't feel confident in doing so. Wondering specifically what would have to be changed to what. Thanks for your time :) #!/usr/bin/env python # # ogss -- SMS Shell through Gmail and libgmail # # Version 0.2 # # Author: btoews at mastahyeti.com # # License: GPL 2.0 # # NOTE: # You should ensure you are permitted to use this script before using it # to access Google's Gmail servers. # def main(argv): print "Starting ogss" logfile = os.path.join(os.environ["HOME"],"ogss.log") print "Logfile at:"+logfile execd = [] #Checking to see if the logfile already exists #if it doesn't we create it. if not os.path.exists(logfile): print "Creating log file" try: open(logfile,"w").close() except: print "Failed to open create log file. Check permissions" exit() #Opening log file for reading and parseing its contents into a list #Must do this to ensure that we dont execute old commands print "Opening log file for reading" try: r = open(logfile,"r") for line in r: eid = line.split("~") if len(eid)>=2: execd.append(int(eid[0])) r.close() except: print "Failed to open or read log file. Check permissions" exit() clist = [["3 River Wireless","@sms.3rivers.net"],["7-11 Speakout","@ cingularme.com"],["Airtel (Karnataka","India)Alaska Communications Systems"],["Alltel Wireless","@message.alltel.com"],["AT&T Wireless","@ txt.att.net"],["Bell Mobility (Canada)","@txt.bell.ca"],["Boost Mobile","@ myboostmobile.com"],["Cellular One (Dobson)","@mobile.celloneusa.com"],["Cingular (Postpaid)","@cingularme.com"],["Centennial Wireless","@cwemail.com"],["Cingular (GoPhone prepaid)","@cingularme.com"],["Claro (Nicaragua)","@ ideasclaro-ca.com"],["Comcel","@comcel.com.co"],["Cricket","@ sms.mycricket.com"],["CTI","@sms.ctimovil.com.ar"],["Emtel (Mauritius)","@ emtelworld.net"],["Fido (Canada)","@fido.ca"],["General Communications Inc.","@msg.gci.net"],["Globalstar","@msg.globalstarusa.com"],["Helio","@ myhelio.com"],["Illinois Valley Cellular","@ivctext.com"],["i wireless",". iws at iwspcs.net"],["Meteor (Ireland)","@sms.mymeteor.ie"],["Mero Mobile (Nepal)","@sms.spicenepal.com"],["MetroPCS","@mymetropcs.com"],["Movicom","@ movimensaje.com.ar"],["Mobitel (Sri Lanka)","@sms.mobitel.lk"],["Movistar (Colombia)","@movistar.com.co"],["MTN (South Africa)","@sms.co.za"],["MTS (Canada)","@text.mtsmobility.com"],["Nextel (Argentina)","@nextel.net.ar"],["Orange (Poland)","@orange.pl"],["Personal (Argentina)","@personal-net.com.ar"],["Plus GSM (Poland)","@text.plusgsm.pl"],["President\s Choice (Canada)","@ txt.bell.ca"],["Qwest","@qwestmp.com"],["Rogers (Canada)","@pcs.rogers.com"],["Sasktel (Canada)","@sms.sasktel.com"],["Setar Mobile email (Aruba)","@mas.aw"],["Solo Mobile","@txt.bell.ca"],["Sprint (PCS)","@messaging.sprintpcs.com"],["Sprint (Nextel)","@page.nextel.com"],["Suncom","@tms.suncom.com"],["T-Mobile","@ tmomail.net"],["T-Mobile (Austria)","@sms.t-mobile.at"],["Telus Mobility (Canada)","@msg.telus.com"],["Thumb Cellular","@sms.thumbcellular.com"],["Tigo (Formerly Ola)","@sms.tigo.com.co"],["Unicel","@utext.com"],["US Cellular","@email.uscc.net"],["Verizon","@vtext.com"],["Virgin Mobile (Canada)","@vmobile.ca"],["Virgin Mobile (USA)","@vmobl.com"],["YCC","@ sms.ycc.ru"],["Orange (UK)","@orange.net"],["Cincinnati Bell Wireless","@ gocbw.com"],["T-Mobile Germany","@t-mobile-sms.de"],["Vodafone Germany","@ vodafone-sms.de"],["E-Plus","@smsmail.eplus.de"]] print "Parsing user input" if len(argv)<4: if len(argv) == 2: if argv[1] == "-c": counter = 0 for car in clist: print str(counter) + "--" + car[0] counter += 1 exit() else: print "------Useage---------------------------------------------------------------\n\r------Start Service --- ogss.py USERNAME PASSWORD CELL-NUMBER CARRIER-NUMBER\n\r------List carriers --- ogss.py -c" print "------Useage from phone----------------------------------------------------\n\r------Ogss COMMAND" exit() username = argv[1] password = argv[2] number = argv[3] carrier = clist[int(argv[4])] cell_email = number+carrier[1] print "Connecting to Gmail" account = libgmail.GmailAccount(username,password) print "Logging into Gmail" account.login() print "Opening log file for writing" try: w = open(logfile,"a") except: print "Failed to open log file. Check permissions." exit() #If the logfile is empty (if this is the first use) we want to #send instructions to the users cell phone. #if len(execd) < 1: # instructions = libgmail.GmailComposedMessage(cell_email,"OGSS Instructions","To use OGSS reply to this message with an SMS starting with \"Ogss\". Whatever follows \"Ogss\" will be executed on your computer") # account.sendMessage(instructions) print "Listening for commands" while True: try: searchResult = account.getMessagesByQuery("from:"+cell_email,True) maxid = 0 if len(searchResult)>0: #Here we search through the inbox to find the most recent message sent #from the specified phone number for thread in searchResult: for message in thread: if cell_email == message.sender: if int(message.id,16)>maxid: maxid = int(message.id,16) maxmessage = message #Removeing all the garbage from the message to find the command #TODO find a neater way of parsing message ogsssplit = maxmessage.source.split("Ogss") spansplit = ogsssplit[len(ogsssplit)-1].split("") command = spansplit[0] command = command.split() #If the id of the most recent message does not already exist in #the log file, run the command if execd.count(int(maxmessage.id,16))==0: print "Processing Command" cresult = Popen(command,stdout=PIPE) body = cresult.stdout.read() tosend = libgmail.GmailComposedMessage(cell_email,"STDOUT","\n"+body) print "Seding back results" account.sendMessage(tosend) print "Logging..." execd.append(int(maxmessage.id,16)) towrite = str(int(maxmessage.id,16))+"~ " for arg in command: towrite += arg+" " w.write(towrite+"\n") print "Listening for commands" #TODO add ability to choose sleep time time.sleep(2) except (KeyboardInterrupt, SystemExit): w.close() print "Exiting..." exit() if __name__ == "__main__": import os,time,sys,libgmail from subprocess import Popen,PIPE main(sys.argv) -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sat Aug 15 16:26:06 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Aug 2009 13:26:06 -0700 (PDT) Subject: random.gauss vs. random.normalvariate References: Message-ID: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> On Aug 15, 12:49?pm, Alan G Isaac wrote: > Quotinghttp://docs.python.org/3.1/library/random.html#random.gauss: > ? ? Gaussian distribution. mu is the mean, and sigma is the > ? ? standard deviation. This is slightly faster than the > ? ? normalvariate() function defined below. > > So since both are offered and gauss is faster, I assume it > must have some offsetting disadvantage. ?What is it? random.gauss is not thread safe. I'm kind of surprised the html docs don't mention this; the docstring does. Carl Banks From bouncyinc at gmail.com Sat Aug 15 16:34:36 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 14:34:36 -0600 Subject: random.gauss vs. random.normalvariate In-Reply-To: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> Message-ID: What does the term "thread safe" mean exactly. I never had to program with "threads" before On Sat, Aug 15, 2009 at 2:26 PM, Carl Banks wrote: > On Aug 15, 12:49 pm, Alan G Isaac wrote: > > Quotinghttp://docs.python.org/3.1/library/random.html#random.gauss: > > Gaussian distribution. mu is the mean, and sigma is the > > standard deviation. This is slightly faster than the > > normalvariate() function defined below. > > > > So since both are offered and gauss is faster, I assume it > > must have some offsetting disadvantage. What is it? > > random.gauss is not thread safe. > > I'm kind of surprised the html docs don't mention this; the docstring > does. > > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Sat Aug 15 16:50:39 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 15 Aug 2009 22:50:39 +0200 Subject: Why is "unpacking" of tuples only allowed when there's 1 tupple ? Message-ID: <4A871F9F.3040904@gmail.com> hello, I'm not sure if "unpacking" is the right term but if I have a tuple of 2 arrays, I can either call a function with: Space_State = tf2ss ( filt[0], filt[1] ) or with Space_State = tf2ss ( *filt ) Now if I've to call a function with more parameters, why can't I use (Polynome is again a tuple of 2 arrays) : (which already gives an error in the IDE) Respons = signal.lfilter ( *Polynome, Signal ) and thus I've to use: Respons = signal.lfilter ( Polynome[0], Polynome[1], Signal ) I use Python 2.5.2 thanks, Stef Mientki From alan.isaac at gmail.com Sat Aug 15 16:54:37 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Sat, 15 Aug 2009 20:54:37 GMT Subject: random.gauss vs. random.normalvariate In-Reply-To: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> Message-ID: > On Aug 15, 12:49 pm, Alan G Isaac wrote: >> Quotinghttp://docs.python.org/3.1/library/random.html#random.gauss: >> Gaussian distribution. mu is the mean, and sigma is the >> standard deviation. This is slightly faster than the >> normalvariate() function defined below. >> >> So since both are offered and gauss is faster, I assume it >> must have some offsetting disadvantage. What is it? On 8/15/2009 4:26 PM Carl Banks apparently wrote: > random.gauss is not thread safe. > > I'm kind of surprised the html docs don't mention this; the docstring > does. Thank you, Alan Isaac From zuo at chopin.edu.pl Sat Aug 15 17:11:43 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 15 Aug 2009 23:11:43 +0200 Subject: Why is "unpacking" of tuples only allowed when there's 1 tupple ? In-Reply-To: <4A871F9F.3040904@gmail.com> References: <4A871F9F.3040904@gmail.com> Message-ID: Dnia 15-08-2009 o 22:50:39 Stef Mientki napisa?(a): > hello, > > I'm not sure if "unpacking" is the right term > but if I have a tuple of 2 arrays, > I can either call a function with: > > Space_State = tf2ss ( filt[0], filt[1] ) > > or with > Space_State = tf2ss ( *filt ) > > Now if I've to call a function with more parameters, > why can't I use (Polynome is again a tuple of 2 arrays) : > (which already gives an error in the IDE) > > Respons = signal.lfilter ( *Polynome, Signal ) > > and thus I've to use: > > Respons = signal.lfilter ( Polynome[0], Polynome[1], Signal ) The content of that tuple or list (filt/Polynome here) doesn't matter. Simply, when calling function, you can't put positional (non-keyword) argument after *something. >>> def nic(*args, **kwargs): pass ... >>> nic(*[1,2,3], 4) File "", line 1 SyntaxError: only named arguments may follow *expression That'd be ok: Respons = signal.lfilter(*Polynome, sig=Signal) # if this method can # receive argument # 'sig' after more # than len(Polynome) # of arguments -- Jan Kaliszewski (zuo) From python at mrabarnett.plus.com Sat Aug 15 17:18:24 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 15 Aug 2009 22:18:24 +0100 Subject: Python 'for' loop is memory inefficient In-Reply-To: <4a870cc7$0$1674$742ec2ed@news.sonic.net> References: <24980842.post@talk.nabble.com> <4a870cc7$0$1674$742ec2ed@news.sonic.net> Message-ID: <4A872620.1070808@mrabarnett.plus.com> John Nagle wrote: > Hendrik van Rooyen wrote: >> On Saturday 15 August 2009 03:25:45 Dr. Phillip M. Feldman wrote: > >> And while you are about it, you may as well teach them that it is much >> better to do a multiplication than a division. > > Actually, division speed hasn't been much of an issue in years. > Arithmetic > has been faster than memory access since CPUs went superscalar. In > CPython, > with all the interpreter overhead, you'll probably never notice the > difference. > > I'd thought "xrange" had already been obsoleted, and hadn't realized the > 2.3 - 2.6 versions of CPython were still doing "range" the hard way, not > as a generator. > It would've broken some existing code, hence it was left until Python 3. From lists at cheimes.de Sat Aug 15 17:19:42 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 15 Aug 2009 23:19:42 +0200 Subject: PyQt4.__file__ gives PyQt4/__init__.py as value In-Reply-To: <0b3b6163-3fb3-4b1b-9605-bf899f65b9e9@o6g2000yqj.googlegroups.com> References: <0b3b6163-3fb3-4b1b-9605-bf899f65b9e9@o6g2000yqj.googlegroups.com> Message-ID: <4A87266E.6080609@cheimes.de> wgw wrote: > I don't understand why the __file__ value in my installation of PyQt > would not give a proper, full path. > > I'm guessing that I did not install pyqt properly (I'm on Ubuntu > Hardy, trying to install QT4.5), but before redoing the install, I > want to see if there is a quicker fix. Some versions of Debian and Ubuntu used to compile Python files with a relative path. Try this: python2.5 /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 python2.5 -o /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 Christian From lists at cheimes.de Sat Aug 15 17:19:42 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 15 Aug 2009 23:19:42 +0200 Subject: PyQt4.__file__ gives PyQt4/__init__.py as value In-Reply-To: <0b3b6163-3fb3-4b1b-9605-bf899f65b9e9@o6g2000yqj.googlegroups.com> References: <0b3b6163-3fb3-4b1b-9605-bf899f65b9e9@o6g2000yqj.googlegroups.com> Message-ID: <4A87266E.6080609@cheimes.de> wgw wrote: > I don't understand why the __file__ value in my installation of PyQt > would not give a proper, full path. > > I'm guessing that I did not install pyqt properly (I'm on Ubuntu > Hardy, trying to install QT4.5), but before redoing the install, I > want to see if there is a quicker fix. Some versions of Debian and Ubuntu used to compile Python files with a relative path. Try this: python2.5 /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 python2.5 -o /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 Christian From stef.mientki at gmail.com Sat Aug 15 17:19:53 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 15 Aug 2009 23:19:53 +0200 Subject: Why is "unpacking" of tuples only allowed when there's 1 tupple ? In-Reply-To: References: <4A871F9F.3040904@gmail.com> Message-ID: <4A872679.4060300@gmail.com> thanks Jan, for the clear explanation. cheers, Stef Jan Kaliszewski wrote: > Dnia 15-08-2009 o 22:50:39 Stef Mientki > napisa?(a): > >> hello, >> >> I'm not sure if "unpacking" is the right term >> but if I have a tuple of 2 arrays, >> I can either call a function with: >> >> Space_State = tf2ss ( filt[0], filt[1] ) >> >> or with >> Space_State = tf2ss ( *filt ) >> >> Now if I've to call a function with more parameters, >> why can't I use (Polynome is again a tuple of 2 arrays) : >> (which already gives an error in the IDE) >> >> Respons = signal.lfilter ( *Polynome, Signal ) >> >> and thus I've to use: >> >> Respons = signal.lfilter ( Polynome[0], Polynome[1], Signal ) > > The content of that tuple or list (filt/Polynome here) doesn't matter. > Simply, when calling function, you can't put positional (non-keyword) > argument after *something. > > >>> def nic(*args, **kwargs): pass > ... > >>> nic(*[1,2,3], 4) > File "", line 1 > SyntaxError: only named arguments may follow *expression > > > That'd be ok: > > Respons = signal.lfilter(*Polynome, sig=Signal) # if this method can > # receive argument > # 'sig' after more > # than len(Polynome) > # of arguments > From jasevv at gmail.com Sat Aug 15 17:32:59 2009 From: jasevv at gmail.com (Jaseem) Date: Sat, 15 Aug 2009 14:32:59 -0700 (PDT) Subject: Python or ActionScript 3.0 Message-ID: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> Hi, Is python similar to actionscript 3.0 Which is better to create a rich gui internet application? Is it AS 3.0 with flex or python with its GUI libs? Is python in demand? Heard that python is similar to lisp. But both python and AS 3.0 is almost identical. Which is more similar to lisp are powerful? Thank You. From rylesny at gmail.com Sat Aug 15 17:54:27 2009 From: rylesny at gmail.com (ryles) Date: Sat, 15 Aug 2009 14:54:27 -0700 (PDT) Subject: Splitting a string into substrings of equal size References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <064c16a8-8a5a-4764-976f-1ee5a46d82bb@n2g2000vba.googlegroups.com> On Aug 14, 8:22?pm, candide wrote: > Suppose you need to split a string into substrings of a given size (except > possibly the last substring). I make the hypothesis the first slice is at the > end of the string. > A typical example is provided by formatting a decimal string with thousands > separator. > > What is the pythonic way to do this ? > > For my part, i reach to this rather complicated code: > > # ---------------------- > > def comaSep(z,k=3, sep=','): > ? ? z=z[::-1] > ? ? x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] > ? ? return sep.join(x) > > # Test > for z in ["75096042068045", "509", "12024", "7", "2009"]: > ? ? print z+" --> ", comaSep(z) > > # ---------------------- > > outputting : > > 75096042068045 --> ?75,096,042,068,045 > 509 --> ?509 > 12024 --> ?12,024 > 7 --> ?7 > 2009 --> ?2,009 > > Thanks py> s='1234567' py> ','.join(_[::-1] for _ in re.findall('.{1,3}',s[::-1])[::-1]) '1,234,567' py> # j/k ;) From wgwinder at gmail.com Sat Aug 15 17:58:48 2009 From: wgwinder at gmail.com (wgw) Date: Sat, 15 Aug 2009 14:58:48 -0700 (PDT) Subject: PyQt4.__file__ gives PyQt4/__init__.py as value References: <0b3b6163-3fb3-4b1b-9605-bf899f65b9e9@o6g2000yqj.googlegroups.com> Message-ID: <2d6a2d94-c1fb-4cd4-a21b-5fd8cf8ee484@g10g2000yqh.googlegroups.com> On Aug 15, 2:19?pm, Christian Heimes wrote: > wgw wrote: > > I don't understand why the __file__ value in my installation of PyQt > > would not give a proper, full path. > > > I'm guessing that I did not install pyqt properly (I'm on Ubuntu > > Hardy, trying to install QT4.5), but before redoing the install, I > > want to see if there is a quicker fix. > > Some versions of Debian and Ubuntu used to compile Python files with a > relative path. Try this: > > python2.5 /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 > python2.5 -o /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 > > Christian python2.5 /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 didn't change anything, and there is no -o option (-O exists, but would that be useful?) thanks! From python at mrabarnett.plus.com Sat Aug 15 18:06:22 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 15 Aug 2009 23:06:22 +0100 Subject: Splitting a string into substrings of equal size In-Reply-To: <064c16a8-8a5a-4764-976f-1ee5a46d82bb@n2g2000vba.googlegroups.com> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> <064c16a8-8a5a-4764-976f-1ee5a46d82bb@n2g2000vba.googlegroups.com> Message-ID: <4A87315E.7040603@mrabarnett.plus.com> ryles wrote: > On Aug 14, 8:22 pm, candide wrote: >> Suppose you need to split a string into substrings of a given size (except >> possibly the last substring). I make the hypothesis the first slice is at the >> end of the string. >> A typical example is provided by formatting a decimal string with thousands >> separator. >> >> What is the pythonic way to do this ? >> >> For my part, i reach to this rather complicated code: >> >> # ---------------------- >> >> def comaSep(z,k=3, sep=','): >> z=z[::-1] >> x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] >> return sep.join(x) >> >> # Test >> for z in ["75096042068045", "509", "12024", "7", "2009"]: >> print z+" --> ", comaSep(z) >> >> # ---------------------- >> >> outputting : >> >> 75096042068045 --> 75,096,042,068,045 >> 509 --> 509 >> 12024 --> 12,024 >> 7 --> 7 >> 2009 --> 2,009 >> >> Thanks > > py> s='1234567' > py> ','.join(_[::-1] for _ in re.findall('.{1,3}',s[::-1])[::-1]) > '1,234,567' > py> # j/k ;) If you're going to use re, then: >>> for z in ["75096042068045", "509", "12024", "7", "2009"]: print re.sub(r"(?<=.)(?=(?:...)+$)", ",", z) 75,096,042,068,045 509 12,024 7 2,009 From Brian.Mingus at colorado.edu Sat Aug 15 18:11:08 2009 From: Brian.Mingus at colorado.edu (Brian) Date: Sat, 15 Aug 2009 16:11:08 -0600 Subject: Splitting a string into substrings of equal size In-Reply-To: <4A87315E.7040603@mrabarnett.plus.com> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> <064c16a8-8a5a-4764-976f-1ee5a46d82bb@n2g2000vba.googlegroups.com> <4A87315E.7040603@mrabarnett.plus.com> Message-ID: <9839a05c0908151511w38fa4d7eu9926024e1472923f@mail.gmail.com> On Sat, Aug 15, 2009 at 4:06 PM, MRAB wrote: > ryles wrote: > >> On Aug 14, 8:22 pm, candide wrote: >> >>> Suppose you need to split a string into substrings of a given size >>> (except >>> possibly the last substring). I make the hypothesis the first slice is at >>> the >>> end of the string. >>> A typical example is provided by formatting a decimal string with >>> thousands >>> separator. >>> >>> What is the pythonic way to do this ? >>> >>> For my part, i reach to this rather complicated code: >>> >>> # ---------------------- >>> >>> def comaSep(z,k=3, sep=','): >>> z=z[::-1] >>> x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] >>> return sep.join(x) >>> >>> # Test >>> for z in ["75096042068045", "509", "12024", "7", "2009"]: >>> print z+" --> ", comaSep(z) >>> >>> # ---------------------- >>> >>> outputting : >>> >>> 75096042068045 --> 75,096,042,068,045 >>> 509 --> 509 >>> 12024 --> 12,024 >>> 7 --> 7 >>> 2009 --> 2,009 >>> >>> Thanks >>> >> >> py> s='1234567' >> py> ','.join(_[::-1] for _ in re.findall('.{1,3}',s[::-1])[::-1]) >> '1,234,567' >> py> # j/k ;) >> > > If you're going to use re, then: > > >>> for z in ["75096042068045", "509", "12024", "7", "2009"]: > print re.sub(r"(?<=.)(?=(?:...)+$)", ",", z) > > > 75,096,042,068,045 > 509 > 12,024 > 7 > 2,009 > Can you please break down this regex? -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sat Aug 15 18:28:09 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 15 Aug 2009 23:28:09 +0100 Subject: Splitting a string into substrings of equal size In-Reply-To: <9839a05c0908151511w38fa4d7eu9926024e1472923f@mail.gmail.com> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> <064c16a8-8a5a-4764-976f-1ee5a46d82bb@n2g2000vba.googlegroups.com> <4A87315E.7040603@mrabarnett.plus.com> <9839a05c0908151511w38fa4d7eu9926024e1472923f@mail.gmail.com> Message-ID: <4A873679.9010902@mrabarnett.plus.com> Brian wrote: > > > On Sat, Aug 15, 2009 at 4:06 PM, MRAB > wrote: > > ryles wrote: > > On Aug 14, 8:22 pm, candide wrote: > > Suppose you need to split a string into substrings of a > given size (except > possibly the last substring). I make the hypothesis the > first slice is at the > end of the string. > A typical example is provided by formatting a decimal string > with thousands > separator. > > What is the pythonic way to do this ? > > For my part, i reach to this rather complicated code: > > # ---------------------- > > def comaSep(z,k=3, sep=','): > z=z[::-1] > x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] > return sep.join(x) > > # Test > for z in ["75096042068045", "509", "12024", "7", "2009"]: > print z+" --> ", comaSep(z) > > # ---------------------- > > outputting : > > 75096042068045 --> 75,096,042,068,045 > 509 --> 509 > 12024 --> 12,024 > 7 --> 7 > 2009 --> 2,009 > > Thanks > > > py> s='1234567' > py> ','.join(_[::-1] for _ in re.findall('.{1,3}',s[::-1])[::-1]) > '1,234,567' > py> # j/k ;) > > > If you're going to use re, then: > > > >>> for z in ["75096042068045", "509", "12024", "7", "2009"]: > print re.sub(r"(?<=.)(?=(?:...)+$)", ",", z) > > > > 75,096,042,068,045 > 509 > 12,024 > 7 > 2,009 > > > Can you please break down this regex? > The call replaces a zero-width match with a comma, ie inserts a comma, if certain conditions are met: "(?<=.)" Look behind for 1 character. There must be at least one previous character. This ensures that a comma is never inserted at the start of the string. I could also have used "(? <064c16a8-8a5a-4764-976f-1ee5a46d82bb@n2g2000vba.googlegroups.com> <4A87315E.7040603@mrabarnett.plus.com> <9839a05c0908151511w38fa4d7eu9926024e1472923f@mail.gmail.com> Message-ID: On Aug 15, 6:28?pm, MRAB wrote: > > ? ? ?>>> for z in ["75096042068045", "509", "12024", "7", "2009"]: > > ? ? ? ? ? ?print re.sub(r"(?<=.)(?=(?:...)+$)", ",", z) > > > ? ? 75,096,042,068,045 > > ? ? 509 > > ? ? 12,024 > > ? ? 7 > > ? ? 2,009 > > The call replaces a zero-width match with a comma, ie inserts a comma, > if certain conditions are met: > > "(?<=.)" > ? ? ?Look behind for 1 character. There must be at least one previous > character. This ensures that a comma is never inserted at the start of > the string. I could also have used "(? whether the first character is a "-". That's left as an exercise for the > reader. :-) > > "(?=(?:...)+$)" > ? ? ?Look ahead for a multiple of 3 characters, followed by the end of > the string. Wow, well done. An exceptional recipe from Python's unofficial regex guru. And thanks for sharing the explanation. From paul.mike25 at gmail.com Sat Aug 15 20:02:36 2009 From: paul.mike25 at gmail.com (Mike Paul) Date: Sat, 15 Aug 2009 17:02:36 -0700 (PDT) Subject: Python- javascript Message-ID: <985d635f-5784-40a7-a2bb-b76900c200d9@b15g2000yqd.googlegroups.com> I'm trying to scrap a dynamic page with lot of javascript in it. Inorder to get all the data from the page i need to access the javascript. But i've no idea how to do it. Say I'm scraping some site htttp://www.xyz.com/xyz request=urllib2.Request("htttp://www.xyz.com/xyz") response=urllib2.urlopen(request) data=response.read() So i get all the data on the initial page. Now i need to access the javascript on this page to get additional details. I've heard someone telling me to use spidermonkey. But no idea on how to send javscript as request and get the response. How hsuld i be sending the javascript request as ? how can it be sent? This is the script I need to access. Click this to view more items Can anyone tell me how can i do it very clearly. I've been breaking my head into this for the past few days with no progress. Thanks From paul.mike25 at gmail.com Sat Aug 15 20:09:15 2009 From: paul.mike25 at gmail.com (Mike Paul) Date: Sat, 15 Aug 2009 19:09:15 -0500 Subject: Python - scraping - javascript Message-ID: <26ee78500908151709v6a159a95wde98b88f7d2e44bf@mail.gmail.com> I'm trying to scrap a dynamic page with lot of javascript in it. Inorder to get all the data from the page i need to access the javascript. But i've no idea how to do it. Say I'm scraping some site htttp://www.xyz.com/xyz request=urllib2.Request("htttp://www.xyz.com/xyz") response=urllib2.urlopen(request) data=response.read() So i get all the data on the initial page. Now i need to access the javascript on this page to get additional details. I've heard someone telling me to use spidermonkey. But no idea on how to send javscript as request and get the response. How hsuld i be sending the javascript request as ? how can it be sent? This is the script I need to access. Click this to view more items Can anyone tell me how can i do it very clearly. I've been breaking my head into this for the past few days with no progress. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From darkwater42 at gmail.com Sat Aug 15 20:57:28 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sat, 15 Aug 2009 17:57:28 -0700 (PDT) Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com> <7877b03a-09da-4836-804c-502b6f78003c@h21g2000yqa.googlegroups.com> <02933e60$0$20647$c3e8da3@news.astraweb.com> <2cdc3f88-1952-4ca2-9754-5b7583fb5fd8@z31g2000yqd.googlegroups.com> <0295958b$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4e15b3a9-b3ec-41f0-bb35-15ea5da7c9db@j21g2000yqe.googlegroups.com> On Aug 14, 1:55?pm, Steven D'Aprano wrote: > Douglas, you and I clearly have a difference of opinion on > this. Neither of us have provided even the tiniest amount > of objective, replicable, reliable data on the > error-proneness of the C++ approach versus that of > Python. The supposed superiority of the C++ approach is > entirely subjective and based on personal opinion instead > of quantitative facts. Alas, this is true for nearly any engineering methodology or philosophy, which is why, I suppose, Perl, for instance, still has its proponents. It's virtually impossible to prove any thesis, and these things only get decided by endless debate that rages across decades. > I prefer languages that permit anything that isn't > explicitly forbidden, so I'm happy that Python treats > non-special escape sequences as valid, I don't really understand what you mean by this. If Python were to declare that "unrecognized escape sequences" were forbidden, then they would be "explicitly forbidden". Would you then be happy? If not, why are you not upset that Python won't let me do [3, 4, 5] + 2 Some other programming languages I've used certainly do. > and your attempts to convince me that this goes against > the Zen have entirely failed to convince me. As I've done > before, I will admit that one consequence of this design > is that it makes it hard to introduce new escape sequences > to Python. Given that it's vanishingly rare to want to do > so, I'm not so convinced of that in the days of Unicode. If I see, backslash, and then some Kanji character, what am I supposed to make of that? For all I know, that Kanji character might mean newline, and I'm seeing code for a version of Python that was tweaked to be friendly to the Japanese. And in the days where smart hand-held devices are proliferating like crazy, there might be ever-more demand for easy-to-use i/o that lets you control various aspects of those devices. |>ouglas From sjmachin at lexicon.net Sat Aug 15 21:01:37 2009 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Aug 2009 18:01:37 -0700 (PDT) Subject: Python 2.6 still not giving memory back to the OS... References: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> Message-ID: <762603ba-0a4c-4504-94d9-34a8b1e3f9c3@s15g2000yqs.googlegroups.com> On Aug 16, 2:41?am, Mark Dickinson wrote: > and got the expected memory usage for my Python process, as > displayed by top: ?memory usage went up to nearly 1Gb after > each assignment to b, then dropped down to 19 Mb or so after > each 'del b'. ?I get similar results under Python 2.5. > > So maybe there's something in xlrd that's hanging on to all > that memory? News to me, and news to guppy/heapy v0.1.9 -- unless the new Windows support has some deficiencies -- after `del b` heapy can't find any trace of the Book object and its contents. As far as releasing memory back to the OS is concerned, I have dim memories of *x systems where free() would return space to the OS if the block was "large" and it was next to the "break" point ... this effect could be what you are seeing. From terry.yinzhe at gmail.com Sat Aug 15 21:04:29 2009 From: terry.yinzhe at gmail.com (Terry) Date: Sat, 15 Aug 2009 18:04:29 -0700 (PDT) Subject: ignored test cases in unittest Message-ID: Hi, I have some 100s unittest cases with my python program. And sometimes, I did quick-and-dirty work by ignoring some test cases by adding an 'x' (or something else) to the beginning of the case name. As time pass by, it's very hard for me to find which test cases are ignored. It seemed the to me that python unittest module does not support the counting of ignored test cases directly. Is there any ready solution for this? br, Terry From roy at panix.com Sat Aug 15 21:12:14 2009 From: roy at panix.com (Roy Smith) Date: Sat, 15 Aug 2009 21:12:14 -0400 Subject: ignored test cases in unittest References: Message-ID: In article , Terry wrote: > Hi, > > I have some 100s unittest cases with my python program. And sometimes, > I did quick-and-dirty work by ignoring some test cases by adding an > 'x' (or something else) to the beginning of the case name. > As time pass by, it's very hard for me to find which test cases are > ignored. If you are consistent in how you do this (i.e. always add an "x" to the beginning of the name), it should be trivial to find them all. I'm sure I could whip up some introspection based method, but it's easier and faster to just do "grep 'def.*xtest' *.py". From darkwater42 at gmail.com Sat Aug 15 21:29:13 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sat, 15 Aug 2009 18:29:13 -0700 (PDT) Subject: Python or ActionScript 3.0 References: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> Message-ID: <8a14e744-eb6c-4ae2-9bb4-2e32fcb987ae@v20g2000yqm.googlegroups.com> On Aug 15, 5:32?pm, Jaseem wrote: > Is python similar to actionscript 3.0 For some very rough sense of "similar" it might be, but not really. > Which is better to create a rich gui internet application? > Is it AS 3.0 with flex or python with its GUI libs? Python doesn't run in your typical web browser, but it is common to use Python for doing the server-side programming, along with a Python- based web development framework, such as Django. You could use Jython to make a JVM applet that would run in a browser, but JVM applets aren't very popular for a variety of reasons, and I doubt the performance would be very good. > Is python in demand? Yes, it's a popular language. > Heard that python is similar to lisp. Kind of. Not any more so that JavaScript is, though, for instance. > But both python and AS 3.0 is almost identical. No, Python and ActionScript are not "almost identical". > Which is more similar to lisp are powerful? They both have their similarities and differences from Lisp. I think it would be impossible to say which one is more similar to Lisp. In general, Python is in my opinion more pleasant to program in than ActionScript, but Python is not generally used for client-side browser code. I think the future of client-side browser programming is actually JavaScript, not ActionScript, though that future may morph into one that mostly uses JavaScript as a virtual machine. This is the approach that Google Web Toolkit takes. It lets you write your client-side code in Java, and that is then compiled into JavaScript. |>ouglas From narkewoody at gmail.com Sat Aug 15 21:52:47 2009 From: narkewoody at gmail.com (Steven Woody) Date: Sun, 16 Aug 2009 09:52:47 +0800 Subject: OptionParser How to: prog [options] [arguments] In-Reply-To: References: Message-ID: Thanks for all you suggestions! -------------- next part -------------- An HTML attachment was scrubbed... URL: From darkwater42 at gmail.com Sat Aug 15 22:12:06 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sat, 15 Aug 2009 19:12:06 -0700 (PDT) Subject: Python- javascript References: <985d635f-5784-40a7-a2bb-b76900c200d9@b15g2000yqd.googlegroups.com> Message-ID: <54684273-6de7-470e-899e-64e0a191c7e3@w6g2000yqw.googlegroups.com> On Aug 15, 8:02?pm, Mike Paul wrote: > I'm trying to scrap a dynamic page with lot of javascript in it. > Inorder to get all the data from the page i need to access the > javascript. But i've no idea how to do it. I'm not sure exactly what you are trying to do, but scraping websites that use a lot of JavaScript are often very problematic. The last time I did so, I had to write some pretty funky regular expressions to pick data out of the JavaScript. Fortunately, the data was directly in the JavaScript, rather than me having to reproduce the Ajax calling chain. If you need to do that, then you almost certainly want to use a package designed for doing such things. One such package is HtmlUnit. It is a "GUI-less browser" with a built-in JavaScript engine that is design for such scraping tasks. Unfortunately, you have to program it in Java, rather than Python. (You might be able to use Jython instead of Java, but I don't know for sure.) |>ouglas P.S. For scraping tasks, you probably want to use BeautifulSoup rather than urllib2. From ben+python at benfinney.id.au Sat Aug 15 22:15:04 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 16 Aug 2009 12:15:04 +1000 Subject: ignored test cases in unittest References: Message-ID: <873a7so66v.fsf@benfinney.id.au> Terry writes: > It seemed the to me that python unittest module does not support the > counting of ignored test cases directly. Is there any ready solution > for this? One solution I've seen involves: * a custom exception class, ?TestSkipped? * raising that exception at the top of test cases you want to temporarily skip * a custom ?TestResult? class that knows about a ?skipped? result * a custom reporter class that knows how you want to report that result -- \ ?A lot of people are afraid of heights. Not me, I'm afraid of | `\ widths.? ?Steven Wright | _o__) | Ben Finney From steve at REMOVE-THIS-cybersource.com.au Sat Aug 15 22:19:02 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 02:19:02 GMT Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> Message-ID: <02975ce6$0$20634$c3e8da3@news.astraweb.com> On Sat, 15 Aug 2009 13:01:43 -0700, Douglas Alan wrote: > P.S. I find it strange, however, that anyone who is not okay with > "abusing" operator overloading in this manner, wouldn't also take > umbrage at Python's overloading of "+" to work with strings and lists, > etc. Numerical addition and sequence concatenation have entirely > different semantics. Not to English speakers, where we frequently use 'add' to mean concatenate, append, insert, etc.: "add this to the end of the list" "add the prefix 'un-' to the beginning of the word to negate it" "add your voice to the list of those calling for change" "add your name and address to the visitor's book" and even in-place modifications: "after test audiences' luke-warm response, the studio added a completely different ending to the movie". Personally, I would have preferred & for string and list concatenation, but that's entirely for subjective reasons. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 15 22:22:38 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 02:22:38 GMT Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> <4a870a7b$0$1674$742ec2ed@news.sonic.net> Message-ID: <02975dbe$0$20634$c3e8da3@news.astraweb.com> On Sat, 15 Aug 2009 12:24:26 -0700, John Nagle wrote: > fortunatus wrote: >> On Aug 14, 1:01 pm, vippstar wrote: >>> Why would you fill your website with junk? >> >> The OP made it clear: >> >>> Just wanted to express some frustration with whitespace-mode. > > Well, it took until Python 3.0 until Python enforced rules that > ensured that the indentation the user sees is the same indentation the > compiler sees. We finally have a solution that allows both tabs and > spaces but disallows the situations which are ambiguous. Until Python > 3.0 is fully deployed, there are situations when you need an insane > level of tab/space visibility. Blame Python, not EMACS. You know, there are situations outside of Python where it is useful to see otherwise invisible characters. I was using Microsoft Word's "Show Invisibles" functionality years before Python even existed. Being able to see a visual glyph in place of whitespace (including line ending characters) is not just useful for editing indentation. -- Steven From bouncyinc at gmail.com Sat Aug 15 22:58:52 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 20:58:52 -0600 Subject: redoing libgmail interface to "smtplib" blah? In-Reply-To: References: Message-ID: On Sat, Aug 15, 2009 at 7:23 PM, Dennis Lee Bieber wrote: > On Sat, 15 Aug 2009 14:23:26 -0600, John Haggerty > declaimed the following in gmane.comp.python.general: > > > The following program is theoretically supposed to use a supported > library. > > Issues have come up where the library is not working and now another > > interface is being requierd to be used. > > > > At this point I'm looking at just changing the send commands but don't > feel > > confident in doing so. Wondering specifically what would have to be > changed > > to what. > > > > Thanks for your time :) > > Ugh... I'm afraid if I attacked this program I'd have to > restructure > the entire thing... There are no signs of any functional decomposition > in that -- if Python had an unstructured GOTO, I'd suspect this would > have been a spaghetti-code program... As it is, the best I can call it > is lasagna-code (interwoven but distinct layers in a linear form > from one end to the other). > > > > if __name__ == "__main__": > > import os,time,sys,libgmail > > from subprocess import Popen,PIPE > > main(sys.argv) > > Given the position of the import statements, this file can NOT be > used as an importable module for use by other programs, so the whole > breakdown of a main() is meaningless; might as well remove that if, the > def main(): line, move the imports to the top, and unindent the rest one > level. > > All those embedded calls to exit() also offend me; I'm from the "one > in, one out" school (though I'll use break and continue in a loop, I > still favor just one usage of them in such) > > Ideally, all the SMS related stuff would be isolated apart from the > email stuff. Would make changing email interface a lot more intuitive. > > Out of a fit of boredom, though it probably doesn't help your real > problem, and it has not been tested at all, this is my restructuring of > the code listing. > > -=-=-=-=-=-=-=- > import os > import time > import sys > import subprocess > > import libgmail > > > CARRIERLIST = [ ("3 River Wireless", "@sms.3rivers.net"), > ("7-11 Speakout","@cingularme.com"), > # ("Airtel (Karnataka","India) Alaska > Communications Systems"), > ("Alltel Wireless","@message.alltel.com"), > ("AT&T Wireless","@txt.att.net"), > ("Bell Mobility (Canada)","@txt.bell.ca"), > ("Boost Mobile","@myboostmobile.com"), > ("Cellular One (Dobson)","@mobile.celloneusa.com"), > ("Cingular (Postpaid)","@cingularme.com"), > ("Centennial Wireless","@cwemail.com"), > ("Cingular (GoPhone prepaid)","@cingularme.com"), > ("Claro (Nicaragua)","@ideasclaro-ca.com"), > ("Comcel","@comcel.com.co"), > ("Cricket","@sms.mycricket.com"), > ("CTI","@sms.ctimovil.com.ar"), > ("Emtel (Mauritius)","@emtelworld.net"), > ("Fido (Canada)","@fido.ca"), > ("General Communications Inc.","@msg.gci.net"), > ("Globalstar","@msg.globalstarusa.com"), > ("Helio","@myhelio.com"), > ("Illinois Valley Cellular","@ivctext.com"), > # ("i wireless",".iws at iwspcs.net"), > ("Meteor (Ireland)","@sms.mymeteor.ie"), > ("Mero Mobile (Nepal)","@sms.spicenepal.com"), > ("MetroPCS","@mymetropcs.com"), > ("Movicom","@movimensaje.com.ar"), > ("Mobitel (Sri Lanka)","@sms.mobitel.lk"), > ("Movistar (Colombia)","@movistar.com.co"), > ("MTN (South Africa)","@sms.co.za"), > ("MTS (Canada)","@text.mtsmobility.com"), > ("Nextel (Argentina)","@nextel.net.ar"), > ("Orange (Poland)","@orange.pl"), > ("Personal (Argentina)","@personal-net.com.ar"), > ("Plus GSM (Poland)","@text.plusgsm.pl"), > ("President's Choice (Canada)","@txt.bell.ca"), > ("Qwest","@qwestmp.com"), > ("Rogers (Canada)","@pcs.rogers.com"), > ("Sasktel (Canada)","@sms.sasktel.com"), > ("Setar Mobile email (Aruba)","@mas.aw"), > ("Solo Mobile","@txt.bell.ca"), > ("Sprint (PCS)","@messaging.sprintpcs.com"), > ("Sprint (Nextel)","@page.nextel.com"), > ("Suncom","@tms.suncom.com"), > ("T-Mobile","@tmomail.net"), > ("T-Mobile (Austria)","@sms.t-mobile.at"), > ("Telus Mobility (Canada)","@msg.telus.com"), > ("Thumb Cellular","@sms.thumbcellular.com"), > ("Tigo (Formerly Ola)","@sms.tigo.com.co"), > ("Unicel","@utext.com"), > ("US Cellular","@email.uscc.net"), > ("Verizon","@vtext.com"), > ("Virgin Mobile (Canada)","@vmobile.ca"), > ("Virgin Mobile (USA)","@vmobl.com"), > ("YCC","@sms.ycc.ru"), > ("Orange (UK)","@orange.net"), > ("Cincinnati Bell Wireless","@gocbw.com"), > ("T-Mobile Germany","@t-mobile-sms.de"), > ("Vodafone Germany","@vodafone-sms.de"), > ("E-Plus","@smsmail.eplus.de") ] > > INSTRUCTIONS = """ > ------Usage--------------------------------------------------------------- > ------Start Service --- > ogss.py USERNAME PASSWORD CELL-NUMBER CARRIER-NUMBER > ------List carriers --- > ogss.py -c > > ------Useage from > phone---------------------------------------------------- > ------Ogss COMMAND > """ > > #odd notation is to split by lines, then join lines with a space > PHONEINSTRUCTIONS = " ".join( > """To use OGSS reply to this message with an SMS starting with > "Ogss". Whatever follows "Ogss" will be executed on your computer > """.split()) > > class Logfile(object): > def __init__(self): > self.logname = os.path.join(os.environ["HOME"], "ogss.log") > if not os.path.exists(self.logname): > try: > self.log = open(logname, "w+") > except: > print "Failure to create log file; check permissions" > self.log = None > else: > try: > print "Opening log file: %s" % self.logname > self.log = open(logname, "r+") > except: > self.log = None > > def opened(self): > return self.log is not None > > def readParse(self): > if self.opened(): > self.log.seek(0, os.SEEK_SET) > retdata = [] > for line in self.log: > eid = line.split("~") > if len(eid) >= 2: > retdata.append(int(eid[0])) > return retdata > > def write(self, ID, commandLine): > if self.opened(): > self.log.seek(0, os.SEEK_END) > self.log.write("%s %s\n" % (ID, commandLine)) > > def close(self): > if self.opened(): > self.log.close() > > class MailConnection(object): > #might have been possible to subclass from libgmail.GmailAccount > #but by incorporating that as a component instead makes it > #a bit easier to replace with something else (SMTP?) > def __init__(self, uname, passwd): > self.uname = uname > self.passwd = passwd > self.account = libgmail.GmailAccount(self.uname, self.passwd) > > def login(self): > self.account.login() > > def sendMessage(self, message): > self.account.sendMessage(message) > > def getMessageByQuery(qstring, flag): #what does flag do? > return self.account.getMessagesByQuery(qstring, flag) > > def composeMessage(self, to, subject, body): > return libgmail.GmailComposedMessage(to, > subject, > body) > > > def parseCommandLine(args): > retdata = None > if len(args) == 1 and args[0] = "-c": > for i, car in enumerate(CARRIERLIST): > print "%5d -- %s" % (i, car[0]) > > elif len(args) > 3: > (username, password, number, carrierID) = tuple(args[:4]) > carrier = CARRIERLIST[int(carrierID)] > cell_email = number + carrier[1] > retdata = { "User" : username, > "Pass" : password, > "Number" : number, > "ID" : carrierID, > "Carrier" : carrier, > "Cell" : cell_email } > > else: > print INSTRUCTIONS > return retdata > > > def main(argv): > print "Starting ogss" > > print "Opening log file" > logfile = Logfile() > if logfile.opened(): > print "Parsing log file" > execd = logfile.readParse() > > print "Parsing command line input" > callee = parseCommandLine(argv[1:]) #strip program name > > if callee is not None: > print "Logging in to mail server" > account = MailConnection(callee["User"], > callee["Pass"]) > account.login() > > ## #if log file contents are empty, send instructions to > ## #user's phone > ## if not len(execd): > ## account.sendMessage( > ## account.composeMessage( > ## callee["Cell"], > ## "OGSS Instructions", > ## PHONEINSTRUCTIONS) ) > > > try: > while True: > print "Listening for commands" > print "Getting mailbox contents" > searchResult = account.getMessagesByQuery( > "from:" + callee["Cell"], > True ) > if searchResult: #presume empty if no messages > maxID = 0 > maxMessage = None > for thread in searchResult: > for message in thread: > if callee["Cell"] == message.sender: > mID = int(message.id, 16) > if mID > maxID: > maxID = mID > maxMessage = message > > if maxID and maxMessage: > if not maxID in execd: > print "Parsing command from message" > ogssSplit = > maxMessage.source.split("Ogss") > command = ogssSplit[-1].split( > "")[0].split() > > result = subprocess.Popen( > command, > stdout = subprocess.PIPE) > body = result.stdout.read() > account.sendMessage( > account.composeMessage( > callee["Cell"], > "STDOUT", > "\n" + body) ) > logfile.write(maxID, " ".join(command)) > > #TODO add ability to choose sleep time > time.sleep(2) > except (KeyboardInterrupt): > pass #exit WHILE loop with or equivalent > ## else: > ## pass #no login data supplied on startup > > logfile.close() > else: > print "Could not open log file, check permissions" > > > if __name__ == "__main__": > main(sys.argv) > -=-=-=-=-=-=-=- > > Everything that needs to be changed for SMTP should be in the class > MailConnection. Note: it appears that this program expects a > bidirectional mail connection -- similar to IMAP, where one connection > access both outgoing mail AND incoming mail that is stored on the remote > system. You'll probably need to use both SMTP to send the messages, and > POP3 to retrieve the mailbox contents -- and what you do about leaving > messages in a POP3 mailbox is up to you; most clients normally delete > them after fetching, but if the query has to fetch all messages just to > process one set, that may be a concern... Or you use something else to > retrieve messages and store them in a local mailbox for subsequent > usage. > > HMMM that does bring up the point -- where is your existing problem? > Reading GMAIL or sending to GMAIL? Sending actually reading worked which was what really surprised me. Especially since python had a ssl for pop and smtp as well. > > > Heh... with a bit of work, I could probably create a Eudora filter > to invoke a Python script on each new fetched email with the proper > subject/content, and then file it away is a different (local) mailbox -- > and do away with that whole log file search and message searching as > messages would be processed as received and never seen again. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From darkwater42 at gmail.com Sat Aug 15 23:00:23 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sat, 15 Aug 2009 20:00:23 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> Message-ID: On Aug 15, 10:19?pm, Steven D'Aprano wrote: > On Sat, 15 Aug 2009 13:01:43 -0700, Douglas Alan wrote: > > P.S. I find it strange, however, that anyone who is not okay with > > "abusing" operator overloading in this manner, wouldn't also take > > umbrage at Python's overloading of "+" to work with strings and lists, > > etc. Numerical addition and sequence concatenation have entirely > > different semantics. > > Not to English speakers, where we frequently use 'add' to mean > concatenate, append, insert, etc.: That is certainly true, but the "+" symbol (pronounced "plus" not "add") isn't exactly synonymous with the English word "add" and is usually used in, technical circles, to refer to a function that at least meets the properties of an abelian group operator. Also, programming languages (other than Perl) should be more precise than English. English words often have many, many meanings, but when we are talking about types and operations on types, the operations should generally have more specific semantics. In any case, let's say we grant that operators should be allowed to be as sloppy as English. Then we should have no problem with C++'s use of "<<" for i/o. Pseudo-code has a long heritage of using "<-" to indicate assignment, and there are a number of programming language (e.g., APL) that use assignment to the output terminal to indicate writing to the terminal. C++'s usage of "<<" for output is clearly designed to be reminiscent of this, and therefore intuitive. And intuitive it is, given the aforementioned background, at least. So, as far as I can tell, Python has no real authority to throw stones at C++ on this little tiny particular issue. |>ouglas From bouncyinc at gmail.com Sat Aug 15 23:18:14 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 21:18:14 -0600 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode In-Reply-To: <02975dbe$0$20634$c3e8da3@news.astraweb.com> References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> <4a870a7b$0$1674$742ec2ed@news.sonic.net> <02975dbe$0$20634$c3e8da3@news.astraweb.com> Message-ID: I would have to agree with that since I've had to work with Word 2007 issues with formatting from some...demanding people in the past. Took at least 1hour plus. On Sat, Aug 15, 2009 at 8:22 PM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > On Sat, 15 Aug 2009 12:24:26 -0700, John Nagle wrote: > > > fortunatus wrote: > >> On Aug 14, 1:01 pm, vippstar wrote: > >>> Why would you fill your website with junk? > >> > >> The OP made it clear: > >> > >>> Just wanted to express some frustration with whitespace-mode. > > > > Well, it took until Python 3.0 until Python enforced rules that > > ensured that the indentation the user sees is the same indentation the > > compiler sees. We finally have a solution that allows both tabs and > > spaces but disallows the situations which are ambiguous. Until Python > > 3.0 is fully deployed, there are situations when you need an insane > > level of tab/space visibility. Blame Python, not EMACS. > > You know, there are situations outside of Python where it is useful to > see otherwise invisible characters. I was using Microsoft Word's "Show > Invisibles" functionality years before Python even existed. Being able to > see a visual glyph in place of whitespace (including line ending > characters) is not just useful for editing indentation. > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bouncyinc at gmail.com Sat Aug 15 23:37:37 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 21:37:37 -0600 Subject: unittest In-Reply-To: <1cbd6f830908142028v638a4c06jf0f859be712e724c@mail.gmail.com> References: <1cbd6f830908142028v638a4c06jf0f859be712e724c@mail.gmail.com> Message-ID: This is an interesting question. I am just wondering: do you really have that many features that it would be impossible to just have a shell script run specific types of input or tests? When I did programming in the past for education they just had lists of input data and we ran the program against the test data. I just get slightly confused when "test suites" start to have to apply? On Fri, Aug 14, 2009 at 9:28 PM, Mag Gam wrote: > I am writing an application which has many command line arguments. > For example: foo.py -args "bar bee" > > I would like to create a test suit using unittest so when I add > features to "foo.py" I don't want to break other things. I just heard > about unittest and would love to use it for this type of thing. > > so my question is, when I do these tests do I have to code them into > foo.py? I prefer having a footest.py which will run the regression > tests. Any thoughts about this? > > TIA > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bouncyinc at gmail.com Sat Aug 15 23:40:23 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 21:40:23 -0600 Subject: ignored test cases in unittest In-Reply-To: References: Message-ID: So you are saying you have several hundred tests you have to do on your program? On Sat, Aug 15, 2009 at 7:04 PM, Terry wrote: > Hi, > > I have some 100s unittest cases with my python program. And sometimes, > I did quick-and-dirty work by ignoring some test cases by adding an > 'x' (or something else) to the beginning of the case name. > As time pass by, it's very hard for me to find which test cases are > ignored. > > It seemed the to me that python unittest module does not support the > counting of ignored test cases directly. Is there any ready solution > for this? > > br, Terry > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bouncyinc at gmail.com Sat Aug 15 23:44:03 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 21:44:03 -0600 Subject: Python or ActionScript 3.0 In-Reply-To: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> References: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> Message-ID: If it were me I'd go with python at least based on the fact that it's more supported and more popular, enough so that it has o'reiley soruces on it. On Sat, Aug 15, 2009 at 3:32 PM, Jaseem wrote: > Hi, > > Is python similar to actionscript 3.0 > Which is better to create a rich gui internet application? > Is it AS 3.0 with flex or python with its GUI libs? > > Is python in demand? > Heard that python is similar to lisp. But both python and AS 3.0 is > almost identical. Which is more similar to lisp are powerful? > > Thank You. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bouncyinc at gmail.com Sat Aug 15 23:59:09 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 21:59:09 -0600 Subject: random.gauss vs. random.normalvariate In-Reply-To: References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> Message-ID: On Sat, Aug 15, 2009 at 7:23 PM, Dennis Lee Bieber wrote: > On Sat, 15 Aug 2009 14:34:36 -0600, John Haggerty > declaimed the following in gmane.comp.python.general: > > > What does the term "thread safe" mean exactly. I never had to program > with > > "threads" before > > That, part way through the logic of the function, control could be > switched to a different thread which call the same function... This > second call would change some of the internal values and may then be > preempted and control returned to the first thread, which continues the > rest of the function with different values then it had when first > preempted. > > A very contrived example, untested of course, consider it > pseudo-code... > > startt = None > > def atimer(): > global startt > startt = time.time() > time.sleep(5) > print time.time() - startt > > t1 = threading.thread(atimer) > t2 = threading.thread(atimer) > t1.start() > t2.start() > > Say t1 gets all the way up to the sleep call, and (since sleep is a > releasing call), t2 then starts. t2 changes the value of startt; and > sleeps... both sleep and presuming the resolution is fine enough, t1 > resumes, and prints a delta time that is incorrect -- it is printing > the time difference from when t2 started to sleep, not from when t1 > started to sleep. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > Interesting so it seems that the compiler(c/c++)interpreter(perl, python)/vm(java) doesn't do this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From terry.yinzhe at gmail.com Sun Aug 16 00:09:45 2009 From: terry.yinzhe at gmail.com (Terry Yin) Date: Sun, 16 Aug 2009 12:09:45 +0800 Subject: ignored test cases in unittest In-Reply-To: References: Message-ID: Yes, should be more than 200. But now 187+ are running (some are 'ignored').It's a personal project, I just don't feel safe without all the testing as it grows bigger and bigger. On Sun, Aug 16, 2009 at 11:40 AM, John Haggerty wrote: > So you are saying you have several hundred tests you have to do on your > program? > > On Sat, Aug 15, 2009 at 7:04 PM, Terry wrote: > >> Hi, >> >> I have some 100s unittest cases with my python program. And sometimes, >> I did quick-and-dirty work by ignoring some test cases by adding an >> 'x' (or something else) to the beginning of the case name. >> As time pass by, it's very hard for me to find which test cases are >> ignored. >> >> It seemed the to me that python unittest module does not support the >> counting of ignored test cases directly. Is there any ready solution >> for this? >> >> br, Terry >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -- ------------------------- Blog: http://terry-yinzhe.spaces.live.com/ twitter: http://twitter.com/terryyin -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sun Aug 16 00:18:36 2009 From: http (Paul Rubin) Date: 15 Aug 2009 21:18:36 -0700 Subject: random.gauss vs. random.normalvariate References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> Message-ID: <7xd46ws86b.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > No language can guard against independent access of a shared/global > object by multiple threads... Erlang? From bouncyinc at gmail.com Sun Aug 16 00:23:33 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 22:23:33 -0600 Subject: random.gauss vs. random.normalvariate In-Reply-To: <7xd46ws86b.fsf@ruckus.brouhaha.com> References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> <7xd46ws86b.fsf@ruckus.brouhaha.com> Message-ID: Erlang I assume is a computer programming language? On Sat, Aug 15, 2009 at 10:18 PM, Paul Rubin wrote: > Dennis Lee Bieber writes: > > No language can guard against independent access of a shared/global > > object by multiple threads... > > Erlang? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sbassi at clubdelarazon.org Sun Aug 16 00:55:11 2009 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sun, 16 Aug 2009 01:55:11 -0300 Subject: Python or ActionScript 3.0 In-Reply-To: <8a14e744-eb6c-4ae2-9bb4-2e32fcb987ae@v20g2000yqm.googlegroups.com> References: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> <8a14e744-eb6c-4ae2-9bb4-2e32fcb987ae@v20g2000yqm.googlegroups.com> Message-ID: <9e2f512b0908152155w47318f81r866190ee8bcf1b4@mail.gmail.com> On Sat, Aug 15, 2009 at 10:29 PM, Douglas Alan wrote: > Python doesn't run in your typical web browser, but it is common to > use Python for doing the server-side programming, along with a Python- > based web development framework, such as Django. > You could use Jython to make a JVM applet that would run in a browser, > but JVM applets aren't very popular for a variety of reasons, and I > doubt the performance would be very good. There is another way to run Python in a browser: MS Silverlight, it runs IronPython on web browsers. http://www.trypython.org/ From kee at kagi.com Sun Aug 16 01:04:25 2009 From: kee at kagi.com (Kee Nethery) Date: Sat, 15 Aug 2009 22:04:25 -0700 Subject: Komodo(!) In-Reply-To: <553649.43098.qm@web110605.mail.gq1.yahoo.com> References: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> <553649.43098.qm@web110605.mail.gq1.yahoo.com> Message-ID: <5C409E92-2D78-4356-9ED0-34F418CEF2B4@kagi.com> On Aug 14, 2009, at 1:55 PM, William wrote: > Personally, I rather like Wing I tried Wing and basically as a newbie, there were too many setup parameters that I did not know how to set correctly and I could never get it to work for me. It runs under X11 and I guess that was just a bit too techie for me to get it to work properly. It's probably a very nice IDE and they were certainly helpful with their support but after a bunch of back and forths I decided to go back to Komodo. Have not looked at NetBeans. I'm a newbie and I need something that just works. Launch it and use it. Komodo meets that need for me. I've heard there is a nice add-on to Eclipse but Eclipse has even more setup variables than Wings and I've avoided it for that reason. Kee From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 01:05:01 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 05:05:01 GMT Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> Message-ID: <029783cd$0$20634$c3e8da3@news.astraweb.com> On Sat, 15 Aug 2009 20:00:23 -0700, Douglas Alan wrote: > So, as far as I can tell, Python has no real authority to throw stones > at C++ on this little tiny particular issue. I think you're being a tad over-defensive. I asked a genuine question about a quote in somebody's signature. That's a quote which can be found all over the Internet, and the poster using it has (as far as I know) no official capacity to speak for "Python" -- while Aahz is a high-profile, well-respected Pythonista, he's not Guido. Now that I understand what the semantics of cout << "Hello world" are, I don't have any problem with it either. It is a bit weird, "Hello world" >> cout would probably be better, but it's hardly the strangest design in any programming language, and it's probably influenced by input redirection using < in various shells. -- Steven From bouncyinc at gmail.com Sun Aug 16 01:14:39 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 23:14:39 -0600 Subject: redoing libgmail interface to "smtplib" blah? In-Reply-To: References: Message-ID: I did detect one problem thus far File "test.py", line 152 if len(args) == 1 and args[0] = "-c": On Sat, Aug 15, 2009 at 7:23 PM, Dennis Lee Bieber wrote: > On Sat, 15 Aug 2009 14:23:26 -0600, John Haggerty > declaimed the following in gmane.comp.python.general: > > > The following program is theoretically supposed to use a supported > library. > > Issues have come up where the library is not working and now another > > interface is being requierd to be used. > > > > At this point I'm looking at just changing the send commands but don't > feel > > confident in doing so. Wondering specifically what would have to be > changed > > to what. > > > > Thanks for your time :) > > Ugh... I'm afraid if I attacked this program I'd have to > restructure > the entire thing... There are no signs of any functional decomposition > in that -- if Python had an unstructured GOTO, I'd suspect this would > have been a spaghetti-code program... As it is, the best I can call it > is lasagna-code (interwoven but distinct layers in a linear form > from one end to the other). > > > > if __name__ == "__main__": > > import os,time,sys,libgmail > > from subprocess import Popen,PIPE > > main(sys.argv) > > Given the position of the import statements, this file can NOT be > used as an importable module for use by other programs, so the whole > breakdown of a main() is meaningless; might as well remove that if, the > def main(): line, move the imports to the top, and unindent the rest one > level. > > All those embedded calls to exit() also offend me; I'm from the "one > in, one out" school (though I'll use break and continue in a loop, I > still favor just one usage of them in such) > > Ideally, all the SMS related stuff would be isolated apart from the > email stuff. Would make changing email interface a lot more intuitive. > > Out of a fit of boredom, though it probably doesn't help your real > problem, and it has not been tested at all, this is my restructuring of > the code listing. > > -=-=-=-=-=-=-=- > import os > import time > import sys > import subprocess > > import libgmail > > > CARRIERLIST = [ ("3 River Wireless", "@sms.3rivers.net"), > ("7-11 Speakout","@cingularme.com"), > # ("Airtel (Karnataka","India) Alaska > Communications Systems"), > ("Alltel Wireless","@message.alltel.com"), > ("AT&T Wireless","@txt.att.net"), > ("Bell Mobility (Canada)","@txt.bell.ca"), > ("Boost Mobile","@myboostmobile.com"), > ("Cellular One (Dobson)","@mobile.celloneusa.com"), > ("Cingular (Postpaid)","@cingularme.com"), > ("Centennial Wireless","@cwemail.com"), > ("Cingular (GoPhone prepaid)","@cingularme.com"), > ("Claro (Nicaragua)","@ideasclaro-ca.com"), > ("Comcel","@comcel.com.co"), > ("Cricket","@sms.mycricket.com"), > ("CTI","@sms.ctimovil.com.ar"), > ("Emtel (Mauritius)","@emtelworld.net"), > ("Fido (Canada)","@fido.ca"), > ("General Communications Inc.","@msg.gci.net"), > ("Globalstar","@msg.globalstarusa.com"), > ("Helio","@myhelio.com"), > ("Illinois Valley Cellular","@ivctext.com"), > # ("i wireless",".iws at iwspcs.net"), > ("Meteor (Ireland)","@sms.mymeteor.ie"), > ("Mero Mobile (Nepal)","@sms.spicenepal.com"), > ("MetroPCS","@mymetropcs.com"), > ("Movicom","@movimensaje.com.ar"), > ("Mobitel (Sri Lanka)","@sms.mobitel.lk"), > ("Movistar (Colombia)","@movistar.com.co"), > ("MTN (South Africa)","@sms.co.za"), > ("MTS (Canada)","@text.mtsmobility.com"), > ("Nextel (Argentina)","@nextel.net.ar"), > ("Orange (Poland)","@orange.pl"), > ("Personal (Argentina)","@personal-net.com.ar"), > ("Plus GSM (Poland)","@text.plusgsm.pl"), > ("President's Choice (Canada)","@txt.bell.ca"), > ("Qwest","@qwestmp.com"), > ("Rogers (Canada)","@pcs.rogers.com"), > ("Sasktel (Canada)","@sms.sasktel.com"), > ("Setar Mobile email (Aruba)","@mas.aw"), > ("Solo Mobile","@txt.bell.ca"), > ("Sprint (PCS)","@messaging.sprintpcs.com"), > ("Sprint (Nextel)","@page.nextel.com"), > ("Suncom","@tms.suncom.com"), > ("T-Mobile","@tmomail.net"), > ("T-Mobile (Austria)","@sms.t-mobile.at"), > ("Telus Mobility (Canada)","@msg.telus.com"), > ("Thumb Cellular","@sms.thumbcellular.com"), > ("Tigo (Formerly Ola)","@sms.tigo.com.co"), > ("Unicel","@utext.com"), > ("US Cellular","@email.uscc.net"), > ("Verizon","@vtext.com"), > ("Virgin Mobile (Canada)","@vmobile.ca"), > ("Virgin Mobile (USA)","@vmobl.com"), > ("YCC","@sms.ycc.ru"), > ("Orange (UK)","@orange.net"), > ("Cincinnati Bell Wireless","@gocbw.com"), > ("T-Mobile Germany","@t-mobile-sms.de"), > ("Vodafone Germany","@vodafone-sms.de"), > ("E-Plus","@smsmail.eplus.de") ] > > INSTRUCTIONS = """ > ------Usage--------------------------------------------------------------- > ------Start Service --- > ogss.py USERNAME PASSWORD CELL-NUMBER CARRIER-NUMBER > ------List carriers --- > ogss.py -c > > ------Useage from > phone---------------------------------------------------- > ------Ogss COMMAND > """ > > #odd notation is to split by lines, then join lines with a space > PHONEINSTRUCTIONS = " ".join( > """To use OGSS reply to this message with an SMS starting with > "Ogss". Whatever follows "Ogss" will be executed on your computer > """.split()) > > class Logfile(object): > def __init__(self): > self.logname = os.path.join(os.environ["HOME"], "ogss.log") > if not os.path.exists(self.logname): > try: > self.log = open(logname, "w+") > except: > print "Failure to create log file; check permissions" > self.log = None > else: > try: > print "Opening log file: %s" % self.logname > self.log = open(logname, "r+") > except: > self.log = None > > def opened(self): > return self.log is not None > > def readParse(self): > if self.opened(): > self.log.seek(0, os.SEEK_SET) > retdata = [] > for line in self.log: > eid = line.split("~") > if len(eid) >= 2: > retdata.append(int(eid[0])) > return retdata > > def write(self, ID, commandLine): > if self.opened(): > self.log.seek(0, os.SEEK_END) > self.log.write("%s %s\n" % (ID, commandLine)) > > def close(self): > if self.opened(): > self.log.close() > > class MailConnection(object): > #might have been possible to subclass from libgmail.GmailAccount > #but by incorporating that as a component instead makes it > #a bit easier to replace with something else (SMTP?) > def __init__(self, uname, passwd): > self.uname = uname > self.passwd = passwd > self.account = libgmail.GmailAccount(self.uname, self.passwd) > > def login(self): > self.account.login() > > def sendMessage(self, message): > self.account.sendMessage(message) > > def getMessageByQuery(qstring, flag): #what does flag do? > return self.account.getMessagesByQuery(qstring, flag) > > def composeMessage(self, to, subject, body): > return libgmail.GmailComposedMessage(to, > subject, > body) > > > def parseCommandLine(args): > retdata = None > if len(args) == 1 and args[0] = "-c": > for i, car in enumerate(CARRIERLIST): > print "%5d -- %s" % (i, car[0]) > > elif len(args) > 3: > (username, password, number, carrierID) = tuple(args[:4]) > carrier = CARRIERLIST[int(carrierID)] > cell_email = number + carrier[1] > retdata = { "User" : username, > "Pass" : password, > "Number" : number, > "ID" : carrierID, > "Carrier" : carrier, > "Cell" : cell_email } > > else: > print INSTRUCTIONS > return retdata > > > def main(argv): > print "Starting ogss" > > print "Opening log file" > logfile = Logfile() > if logfile.opened(): > print "Parsing log file" > execd = logfile.readParse() > > print "Parsing command line input" > callee = parseCommandLine(argv[1:]) #strip program name > > if callee is not None: > print "Logging in to mail server" > account = MailConnection(callee["User"], > callee["Pass"]) > account.login() > > ## #if log file contents are empty, send instructions to > ## #user's phone > ## if not len(execd): > ## account.sendMessage( > ## account.composeMessage( > ## callee["Cell"], > ## "OGSS Instructions", > ## PHONEINSTRUCTIONS) ) > > > try: > while True: > print "Listening for commands" > print "Getting mailbox contents" > searchResult = account.getMessagesByQuery( > "from:" + callee["Cell"], > True ) > if searchResult: #presume empty if no messages > maxID = 0 > maxMessage = None > for thread in searchResult: > for message in thread: > if callee["Cell"] == message.sender: > mID = int(message.id, 16) > if mID > maxID: > maxID = mID > maxMessage = message > > if maxID and maxMessage: > if not maxID in execd: > print "Parsing command from message" > ogssSplit = > maxMessage.source.split("Ogss") > command = ogssSplit[-1].split( > "")[0].split() > > result = subprocess.Popen( > command, > stdout = subprocess.PIPE) > body = result.stdout.read() > account.sendMessage( > account.composeMessage( > callee["Cell"], > "STDOUT", > "\n" + body) ) > logfile.write(maxID, " ".join(command)) > > #TODO add ability to choose sleep time > time.sleep(2) > except (KeyboardInterrupt): > pass #exit WHILE loop with or equivalent > ## else: > ## pass #no login data supplied on startup > > logfile.close() > else: > print "Could not open log file, check permissions" > > > if __name__ == "__main__": > main(sys.argv) > -=-=-=-=-=-=-=- > > Everything that needs to be changed for SMTP should be in the class > MailConnection. Note: it appears that this program expects a > bidirectional mail connection -- similar to IMAP, where one connection > access both outgoing mail AND incoming mail that is stored on the remote > system. You'll probably need to use both SMTP to send the messages, and > POP3 to retrieve the mailbox contents -- and what you do about leaving > messages in a POP3 mailbox is up to you; most clients normally delete > them after fetching, but if the query has to fetch all messages just to > process one set, that may be a concern... Or you use something else to > retrieve messages and store them in a local mailbox for subsequent > usage. > > HMMM that does bring up the point -- where is your existing problem? > Reading GMAIL or sending to GMAIL? > > Heh... with a bit of work, I could probably create a Eudora filter > to invoke a Python script on each new fetched email with the proper > subject/content, and then file it away is a different (local) mailbox -- > and do away with that whole log file search and message searching as > messages would be processed as received and never seen again. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From enleverLesX_XXmcX at XmclavXeauX.com Sun Aug 16 01:43:29 2009 From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP) Date: Sun, 16 Aug 2009 07:43:29 +0200 Subject: Python or ActionScript 3.0 References: <8a14e744-eb6c-4ae2-9bb4-2e32fcb987ae@v20g2000yqm.googlegroups.com> Message-ID: <4a879c84$0$17754$ba4acef3@news.orange.fr> Hi! > Python doesn't run in your typical web browser Yes, Python can do it... on Windows. Two (examples) ways: - ActiveScripting (PythonScript), include in PyWin32 - Gestalt (who mix Python, Ruby & Javascript, via Silverlight) And alse, these two solutions run OK in HTA (HTml Application) for use HTML as GUI tool in local applications. @-salutations -- Michel Claveau From enleverLesX_XXmcX at XmclavXeauX.com Sun Aug 16 01:46:45 2009 From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP) Date: Sun, 16 Aug 2009 07:46:45 +0200 Subject: Python- javascript References: <985d635f-5784-40a7-a2bb-b76900c200d9@b15g2000yqd.googlegroups.com> Message-ID: <4a879d47$0$17765$ba4acef3@news.orange.fr> Hi! If you are under Windows, you can drive IE, for indirect drive the web-pages. In this case, you can then interact with pages & the javascript's scripts included. For more, see Pywin32, Pamie, Pxie, etc. @-salutations -- Michel Claveau From darkwater42 at gmail.com Sun Aug 16 01:51:07 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sat, 15 Aug 2009 22:51:07 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> Message-ID: <34dd6e0e-3b47-4761-ad7a-9038b0d36209@v36g2000yqv.googlegroups.com> On Aug 16, 1:05?am, Steven D'Aprano wrote: > On Sat, 15 Aug 2009 20:00:23 -0700, Douglas Alan wrote: > > So, as far as I can tell, Python has no real authority to throw stones > > at C++ on this little tiny particular issue. > I think you're being a tad over-defensive. Defensive? Personally, I prefer Python over C++ by about a factor of 100X. I just find it a bit amusing when someone claims that some programming language has a particular fatal flaw, when their own apparently favorite language has the very same issue in an only slightly different form. > the poster using it has (as far as I know) no official capacity to speak > for "Python" I never thought he did. I wasn't speaking literally, as I'm not under the opinion that any programming language has any literal authority or any literal ability to throw stones. > Now that I understand what the semantics of cout << "Hello world" are, I > don't have any problem with it either. It is a bit weird, "Hello world">> cout > would probably be better, but it's hardly the strangest design in > any programming language, and it's probably influenced by input > redirection using < in various shells. C++ also allows for reading from stdin like so: cin >> myVar; I think the direction of the arrows probably derives from languages like APL, which had notation something like so: myVar <- 3 [] <- myVar "<-" was really a little arrow symbol (APL didn't use ascii), and the first line above would assign the value 3 to myVar. In the second line, the "[]" was really a little box symbol and represented the terminal. Assigning to the box would cause the output to be printed on the terminal, so the above would output "3". If you did this: [] -> myVar It would read a value into myVar from the terminal. APL predates Unix by quite a few years. |>ouglas From xahlee at gmail.com Sun Aug 16 01:54:06 2009 From: xahlee at gmail.com (Xah Lee) Date: Sat, 15 Aug 2009 22:54:06 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. Message-ID: Xah's Edu Corner: The importance of syntax & notations. http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstract.html this article should teach the coding sophomorons and computer ?science? idiotic authors who harbor the notion that syntax is not important, picked up by all the elite i-reddit & twittering & hacker news am-hip dunces. Further readings: ? The TeX Pestilence http://xahlee.org/cmaci/notation/TeX_pestilence.html ? A Notation for Plane Geometry http://xahlee.org/cmaci/notation/plane_geometry_notation.html ? The Concepts and Confusions of Prefix, Infix, Postfix and Fully Nested Notations http://xahlee.org/UnixResource_dir/writ/notations.html ? The Problems of Traditional Math Notation http://xahlee.org/cmaci/notation/trad_math_notation.html Xah ? http://xahlee.org/ ? From timr at probo.com Sun Aug 16 02:07:07 2009 From: timr at probo.com (Tim Roberts) Date: Sat, 15 Aug 2009 23:07:07 -0700 Subject: Pygresql, and query meta informations References: <55aceb1c-b3d9-4f9b-b8cf-d9833edb2660@c29g2000yqd.googlegroups.com> Message-ID: <368f85prhp9d349trtooj5qsqmqmip0qqp@4ax.com> durumdara wrote: > >Pygresql, DB-API. > >I search for a solution to get meta information about last query, >because I must export these infos to Delphi. > >Delphi have TDataSet, and it have meta structure that must be defined >before I create it. >For char/varchar fields I must define their sizes! > >Pygresql is not retreive the field sizes. You should be able to get that information from the .description member of the cursor object. Have you checked it? If not, you will have to use fetch the information from the Postgres-specific tables, pg_class and pg_attribute. pg_class contains information about your tables; when you fetch the class number for your table, you can look up the columns in pg_attribute. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From nagle at animats.com Sun Aug 16 02:20:34 2009 From: nagle at animats.com (John Nagle) Date: Sat, 15 Aug 2009 23:20:34 -0700 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: <4vmil6-ait.ln1@nb2.stroeder.com> Message-ID: <4a87a444$0$1627$742ec2ed@news.sonic.net> Hendrik van Rooyen wrote: > On Saturday 15 August 2009 14:40:35 Michael Str?der wrote: >> Hendrik van Rooyen wrote: >>> In the past, on this group, I have made statements that said that on >>> Linux, the serial port handling somehow does not allow transmitting and >>> receiving at the same time, and nobody contradicted me. Absolutely false. >> Despite all the good comments here by other skilled people I'd recommend to >> determine whether the transmission line to the devices accessed support >> full duplex. All standard PC serial ports are full-duplex devices. Here's a program I wrote which uses "pyserial" to drive Baudot teletypes as full-duplex devices. https://sourceforge.net/projects/baudotrss/ This uses an input thread and an output thread. It reads RSS feeds and prints them on antique Teletype machines. (Reuters RSS feeds produce a classic news ticker. Twitter RSS feeds work but look silly when hammered out on yellow paper at 45.45 baud.) > > You raise a good point, that is probably not well known amongst the youngsters > here, as simple serial multidropping has gone out of fashion. Actually, no. Dynamixel servos as used on the latest Bioloid robots are multidrop serial RS-485. But outside the embedded world, nobody uses that stuff any more. (Embedded is going Ethernet; it's overkill but works fine and is now cheap.) John Nagle From emmanuel.surleau at gmail.com Sun Aug 16 02:30:54 2009 From: emmanuel.surleau at gmail.com (Emmanuel Surleau) Date: Sun, 16 Aug 2009 08:30:54 +0200 Subject: Python 'for' loop is memory inefficient In-Reply-To: <4A8612CE.7080700@stoneleaf.us> References: <24980842.post@talk.nabble.com> <4A8612CE.7080700@stoneleaf.us> Message-ID: <200908160830.55031.emmanuel.surleau@gmail.com> > Dr. Phillip M. Feldman wrote: [snip] > > def is_prime(n): > > for j in range(2,n): > > if (n % j) == 0: return False > > return True > > > > It seems as though Python is actually expanding range(2,n) into a list of > > numbers, even though this is incredibly wasteful of memory. There should > > be a looping mechanism that generates the index variable values > > incrementally as they are needed. > > You already have an answer to the range issue, so I will only add that > putting a loop inside another loop is a decent way to expand the time > taken. > > I will also observe that if you were to stop programming whatever > language you are more familiar with in Python, and start programming > Python in Python, you'll have an easier time of it. I don't see what's particularly un-Pythonic with this code. Not using xrange() is a mistake, certainly, but it remains clear, easily understandable code which correctly demonstrates the naive algorithm for detecting whether n is a prime. It doesn't call for condescension > The Dive Into Python is an excellent start for that. I never read it, but I was under the impression that the tutorial on python.org was geared toward programmers moving to Python from other languages. It was also my impression that Dive Into Python is rather outdated and occasionally inaccurate (based on comments on this mailing list). Cheers, Emm From dmitrey.kroshko at scipy.org Sun Aug 16 02:36:56 2009 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sat, 15 Aug 2009 23:36:56 -0700 (PDT) Subject: "for" cycle with assigning index References: <4149f0b2-603d-4c59-aa34-bd0fd826303c@b14g2000yqd.googlegroups.com> Message-ID: <7eac79f9-8b38-4aa6-8bd7-4dc042037b31@t13g2000yqt.googlegroups.com> Thanks all, especially Dennis for your detailed answer. left_arr_indexes is list of nonnegative integers, eg [0,0,0,1,1,4] IndDict is a dict like {0: [1,2], 3: [0,1], 10:[0,2,3]}, so that's why I don't use python list instead. The code is taken from OpenOpt framework that I develop. Currently I have implemented another workaround but the solution you proposed can be used in other parts of code. Regards, D. On Aug 16, 4:23?am, Dennis Lee Bieber wrote: > On Sat, 15 Aug 2009 13:22:08 -0700, Dennis Lee Bieber > declaimed the following in > gmane.comp.python.general: > > ? ? ? ? Okay -- my lack of experience with lambda shows... forgot to guard > the intermediates... > > > > for i in xrange(len(Funcs2)): > > > ? ? ?Funcs.append(lambda i=i,*args, **kwargs: (Funcs2[i](*args, > > > **kwargs)[IndDict[left_arr_indexes[i]]])) > > > > I get "list indices must be integers, not dict" (and i is equal to > > > Python dictionary, that is Funcs2) > > ? ? ? ? So... with the following assumptions (and ignoring all the other > respondents )... > > 1) ? ? ?Funcs2 IS a dictionary keyed by sequential integers starting at 0 > 2) ? ? ?Order in Funcs matters; that is, the first element of the list must > align with the element of the dictionary having key "0" > 3) ? ? ?IndDict and left_arr_indexes DO NOT CHANGE CONTENT after the loop > runs > 4) ? ? ?left_arr_indexes is at least as long as Funcs2 > > assert (min(Funcs2.keys()) == 0 > ? ? ? ? ? ? ? ? ? ? ? ? and > ? ? ? ? ? ? ? ? max(Funcs2.keys()) == (len(Funcs2) - 1)) ? ? ? ?#1 > assert len(left_arr_indexes) >= len(Funcs2) ? ? ? ? ?#4 > > Funcs = [None] * len(Funcs2) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?#2a > for ki, fv in Funcs2.items(): ? #ki->key as index; fv->function value > ? ? ? ? ritmp = IndDict[left_arr_indexes[ki]] ? ? ? ? ? ? ? ? ? ? ? ? ? #3 > ? ? ? ? Funcs[ki] = (lambda ri=ritmp, fn=fv, *args, **kwargs: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (fn(*args, **kwargs)[ri]) ? ? ? ? ? ? ? ? ? ? ? #2b > > ri and fn used to protect the intermediates, ritmp and fv, from changes > > 2a is needed as the order of .items() is undefined, so .append() can not > be used. This presets the result list size permitting direct indexing > (2b) to fill slots in order. > > #1 can still fail itself if a key is NOT an integer (what is the min() > of 0 and "a") > > ? ? ? ? I still don't know if IndDict is really a list or a dictionary, nor > what left_array_indexes contains (by name, it is a list of values to > index into another list -- but could be a list of keys to access a > dictionary) > > ? ? ? ? And I'll reiterate: if you are using dictionaries in which the keys > are sequential integers starting at 0... Replace them with simple > lists... > -- > ? ? ? ? Wulfraed ? ? ? ? Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ?HTTP://wlfraed.home.netcom.com/ From mail at microcorp.co.za Sun Aug 16 03:24:36 2009 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 16 Aug 2009 09:24:36 +0200 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com><02957d23$0$20647$c3e8da3@news.astraweb.com><5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com><02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> Message-ID: <009f01ca1e42$9c833600$0d00a8c0@Hendrik> >"Steven D'Aprano" wrote: >Now that I understand what the semantics of cout << "Hello world" are, I >don't have any problem with it either. It is a bit weird, "Hello world" >>> cout would probably be better, but it's hardly the strangest design in >any programming language, and it's probably influenced by input >redirection using < in various shells. I find it strange that you would prefer: "Hello world" >> cout over: cout << "Hello world" The latter seems to me to be more in line with normal assignment: - Take what is on the right and make the left the same. I suppose it is because we read from left to right that the first one seems better to you. Another instance of how different we all are. It goes down to the assembler - there are two schools: mov a,b - for Intel like languages, this means move b to a mov a,b - for Motorola like languages, this means move a to b Gets confusing sometimes. - Hendrik From jcm1981 at gmail.com Sun Aug 16 03:57:41 2009 From: jcm1981 at gmail.com (Chang Min Jeon) Date: Sun, 16 Aug 2009 16:57:41 +0900 Subject: my recursive function call is wrong? Message-ID: <22a413260908160057t2802d3cci70658278e7322eb8@mail.gmail.com> I'm trying to write program to translate define macro in 'C'. And start_parse has return condition that list's length is 0. At this time return statement invoke start_parse() function. I can't understand do that. I'm using Python 2.6.2 in Windows XP import re import sys comment = ''' #if defined (FEATURE_ONENESTED) # define PYTHON_POWERED # if defined(ANY_LANGUAGE) # error # endif #else # define FEATURE_NONE #endif ''' symbol_table = ['FEATURE_ONENESTED'] valid_area = False p_define = re.compile('^[\t ]*#[\t ]*define[\t ]+([a-zA-Z0-9_]+)[\t ]*') p_if = re.compile('^[\t ]*#[\t ]*if[\t ]+defined[\s]*[\(]*([a-zA-Z0-9_]+)[\)]*[\t ]*') p_elif = re.compile('^[\t ]*#[\t ]*elif[\t ]*') p_else = re.compile('^[\t ]*#[\t ]*else[\t ]*') p_endif = re.compile('^[\t ]*#[\t ]*endif[\t ]*') def start_parse(macro): global valid_area if len(macro) == 0: return if valid_area == True: if p_else.match(macro[0]): valid_area = False macro.pop(0) start_parse(macro) match = p_define.match(macro[0]) if match: symbol_table.append(match.group(1)) macro.pop(0) start_parse(macro) match = p_if.match(macro[0]) if match: for symbol in symbol_table:#print match.group(1) if match.group(1) == symbol: #print match.group(1) valid_area = True else: valid_area = False if p_else.match(macro[0]): macro.pop(0) start_parse(macro) match = p_endif.match(macro[0]) if match: valid_area = False macro.pop(0) start_parse(macro) if __name__ == '__main__': l = comment.splitlines() start_parse(l) print symbol_table -- CashFlow To be rich. -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Aug 16 04:04:59 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 04:04:59 -0400 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> Message-ID: <50697b2c0908160104k7d74ace9jda8f4b927402942@mail.gmail.com> On Sat, Aug 15, 2009 at 8:09 AM, Xavier Ho wrote: > Hey all, > > I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in the > documentation. > > Is there a substitution for this special method in 3.1, or do I really have > to define all six rich comparison methods to work it out? I don't think so. Quoting http://docs.python.org/dev/py3k/reference/datamodel.html "There are no swapped-argument versions of [the comparison] methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other?s reflection, __le__() and __ge__() are each other?s reflection, and __eq__() and __ne__() are their own reflection." I believe this means you only need to define one method from each of the following pairs to get all the operators working: * __eq__ or __ne__ * __lt__ or __gt__ * __ge__ or __le__ Cheers, Chris -- http://blog.rebertia.com From clp2 at rebertia.com Sun Aug 16 04:07:20 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 04:07:20 -0400 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> Message-ID: <50697b2c0908160107k6f31141dt5143071d0ff54c71@mail.gmail.com> On Sat, Aug 15, 2009 at 1:06 PM, Mark Lawrence wrote: > Xavier Ho wrote: >> >> Hey all, >> >> I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in >> the >> documentation. >> >> Is there a substitution for this special method in 3.1, or do I really >> have >> to define all six rich comparison methods to work it out? >> >> If this question has already been asked somewhere, I apologise in advance. >> Already googled around but I didn't find information on this. >> >> Any replies appreciated. >> > http://bytes.com/topic/python/answers/844614-python-3-sorting-comparison-function That seems to be about the built-in function cmp(). The OP was asking about the special method __cmp__ and the related rich comparison special methods (__eq__, __lt__, etc). Cheers, Chris -- http://blog.rebertia.com From clp2 at rebertia.com Sun Aug 16 04:15:43 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 04:15:43 -0400 Subject: random.gauss vs. random.normalvariate In-Reply-To: References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> <7xd46ws86b.fsf@ruckus.brouhaha.com> Message-ID: <50697b2c0908160115l2db5fe2eo4c665a3a83c4a8@mail.gmail.com> > On Sat, Aug 15, 2009 at 10:18 PM, Paul Rubin > wrote: >> >> Dennis Lee Bieber writes: >> > ? ? ? No language can guard against independent access of a >> > shared/global >> > object by multiple threads... >> >> Erlang? On Sun, Aug 16, 2009 at 12:23 AM, John Haggerty wrote: > Erlang I assume is a computer programming language? http://en.wikipedia.org/wiki/Erlang_(programming_language) There's a reason Wikipedia has a search function... :) Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 04:22:58 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 08:22:58 GMT Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> Message-ID: <0297b230$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 09:24:36 +0200, Hendrik van Rooyen wrote: >>"Steven D'Aprano" wrote: > >>Now that I understand what the semantics of cout << "Hello world" are, I >>don't have any problem with it either. It is a bit weird, "Hello world" >>>> cout would probably be better, but it's hardly the strangest design >>>> in >>any programming language, and it's probably influenced by input >>redirection using < in various shells. > > I find it strange that you would prefer: > > "Hello world" >> cout > over: > cout << "Hello world" > > The latter seems to me to be more in line with normal assignment: - Take > what is on the right and make the left the same. I don't like normal assignment. After nearly four decades of mathematics and programming, I'm used to it, but I don't think it is especially good. It confuses beginners to programming: they get one set of behaviour drilled into them in maths class, and then in programming class we use the same notation for something which is almost, but not quite, the same. Consider the difference between: y = 3 + x x = z as a pair of mathematics expressions versus as a pair of assignments. What conclusion can you draw about y and z? Even though it looks funny due to unfamiliarity, I'd love to see the results of a teaching language that used notation like: 3 + x -> y len(alist) -> n Widget(1, 2, 3).magic -> obj etc. for assignment. My prediction is that it would be easier to learn, and just as good for experienced coders. The only downside (apart from unfamiliarity) is that it would be a little bit harder to find the definition of a variable by visually skimming lines of code: your eyes have to zig-zag back and forth to find the end of the line, instead of running straight down the left margin looking for "myvar = ...". But it should be easy enough to search for "-> myvar". > I suppose it is because > we read from left to right that the first one seems better to you. Probably. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 04:32:35 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 08:32:35 GMT Subject: Python 'for' loop is memory inefficient References: <24980842.post@talk.nabble.com> <4A8612CE.7080700@stoneleaf.us> Message-ID: <0297b471$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 08:30:54 +0200, Emmanuel Surleau wrote: [...] >> I will also observe that if you were to stop programming whatever >> language you are more familiar with in Python, and start programming >> Python in Python, you'll have an easier time of it. > > I don't see what's particularly un-Pythonic with this code. Not using > xrange() is a mistake, certainly, but it remains clear, easily > understandable code which correctly demonstrates the naive algorithm for > detecting whether n is a prime. It doesn't call for condescension It's a particular unfair criticism because the critic (Ethan Furman) appears to have made a knee-jerk reaction. The "some language in Python" behaviour he's reacting to is the common idiom: for i in range(len(seq)): do_something_with(seq[i]) instead of the "Python in Python" idiom: for obj in seq: do_something_with(obj) That's a reasonable criticism, but *not in the case*. Ethan appears to have made the knee-jerk reaction "for i in range() is Bad" without stopping to think about what this specific piece of code is actually doing. (Replace 'obj' with 'j', 'seq' with 'range(2, n)', and 'do_something_with' with 'if (n % j) == 0: return False', and you have the exact same code pattern.) -- Steven From darkwater42 at gmail.com Sun Aug 16 04:41:41 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sun, 16 Aug 2009 01:41:41 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <0297b230$0$20634$c3e8da3@news.astraweb.com> Message-ID: <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> On Aug 16, 4:22?am, Steven D'Aprano wrote: > I don't like normal assignment. After nearly four decades of mathematics > and programming, I'm used to it, but I don't think it is especially good. > It confuses beginners to programming: they get one set of behaviour > drilled into them in maths class, and then in programming class we use > the same notation for something which is almost, but not quite, the same. > Consider the difference between: > > y = 3 + x > x = z > > as a pair of mathematics expressions versus as a pair of assignments. > What conclusion can you draw about y and z? Yeah, the syntax most commonly used for assignment today sucks. In the past, it was common to see languages with syntaxes like y <- y + 1 or y := y + 1 or let y = y + 1 But these languages have mostly fallen out of favor. The popular statistical programming language R still uses the y <- y + 1 syntax, though. Personally, my favorite is Lisp, which looks like (set! y (+ y 1)) or (let ((x 3) (y 4)) (foo x y)) I like to be able to read everything from left to right, and Lisp does that more than any other programming language. I would definitely not like a language that obscures assignment by moving it over to the right side of lines. |>ouglas From max at alcyone.com Sun Aug 16 04:46:11 2009 From: max at alcyone.com (Erik Max Francis) Date: Sun, 16 Aug 2009 01:46:11 -0700 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <0297b230$0$20634$c3e8da3@news.astraweb.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <0297b230$0$20634$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I don't like normal assignment. After nearly four decades of mathematics > and programming, I'm used to it, but I don't think it is especially good. > It confuses beginners to programming: they get one set of behaviour > drilled into them in maths class, and then in programming class we use > the same notation for something which is almost, but not quite, the same. > Consider the difference between: > > y = 3 + x > x = z > > as a pair of mathematics expressions versus as a pair of assignments. > What conclusion can you draw about y and z? What you're saying is true, but it's still a matter of terminology. The symbol "=" means different things in different contexts, and mathematics and programming are very different ones indeed. The problem is compounded with early languages which lazily confused the two in different context, such as (but not exclusive to) BASIC using = for both assignment and equality testing in what are in esssence totally unrelated contexts. > Even though it looks funny due to unfamiliarity, I'd love to see the > results of a teaching language that used notation like: > > 3 + x -> y > len(alist) -> n > Widget(1, 2, 3).magic -> obj > etc. > > for assignment. My prediction is that it would be easier to learn, and > just as good for experienced coders. This really isn't new at all. Reverse the arrow and the relationship to get:: y <- x + 3 (and use a real arrow rather than ASCII) and that's assignment in APL and a common representation in pseudocode ever since. Change it to := and that's what Pascal used, as well as quite a few mathematical papers dealing with iterative computations, I might add. Once you get past the point of realizing that you really need to make a distinction between assignment and equality testing, then it's just a matter of choosing two different operators for the job. Whether it's <-/= or :=/= or =/== or ->/= (with reversed behavior for assignment) is really academic and a matter of taste at that point. Given the history of programming languages, it doesn't really look like the to-be-assigned variable being at the end of expression is going to get much play, since not a single major one I'm familiar with does it that way, and a lot of them have come up with the same convention independently and haven't seen a need to change. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Get there first with the most men. -- Gen. Nathan Bedford Forrest, 1821-1877 From max at alcyone.com Sun Aug 16 04:48:15 2009 From: max at alcyone.com (Erik Max Francis) Date: Sun, 16 Aug 2009 01:48:15 -0700 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <0297b230$0$20634$c3e8da3@news.astraweb.com> <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> Message-ID: Douglas Alan wrote: > Personally, my favorite is Lisp, which looks like > > (set! y (+ y 1)) For varying values of "Lisp." `set!` is Scheme. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Get there first with the most men. -- Gen. Nathan Bedford Forrest, 1821-1877 From duncan.booth at invalid.invalid Sun Aug 16 05:25:02 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Aug 2009 09:25:02 GMT Subject: ignored test cases in unittest References: <873a7so66v.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Terry writes: > >> It seemed the to me that python unittest module does not support the >> counting of ignored test cases directly. Is there any ready solution >> for this? > > One solution I've seen involves: > > * a custom exception class, ???TestSkipped??? > > * raising that exception at the top of test cases you want to > temporarily skip > > * a custom ???TestResult??? class that knows about a ???skipped??? result > > * a custom reporter class that knows how you want to report that result > I'd add to that a decorator so you can quickly mark a test case as ignored without editing the test itself. Also you could include a reason why it is ignored: @ignore("This test takes too long to run") def test_foo(self): ... That also means you can redefine the decorator easily if you want to try running all the ignored tests. Another decorator useful here is one that asserts that the test will fail. If the test passes then maybe someone fixed whatever was making it fail and if so you want to consider re-enabling it. @fails("Needs the frobnozz module to be updated") def test_whotsit(self): ... From darkwater42 at gmail.com Sun Aug 16 05:31:55 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sun, 16 Aug 2009 02:31:55 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <0297b230$0$20634$c3e8da3@news.astraweb.com> <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> Message-ID: <523a62c0-2c5f-4027-944a-7edb0d4693d8@w41g2000yqb.googlegroups.com> On Aug 16, 4:48?am, Erik Max Francis wrote: > Douglas Alan wrote: > > Personally, my favorite is Lisp, which looks like > > > ? ?(set! y (+ y 1)) > > For varying values of "Lisp." ?`set!` is Scheme. Yes, I'm well aware! There are probably as many different dialects of Lisp as all other programming languages put together. |>ouglas From terry.yinzhe at gmail.com Sun Aug 16 05:38:20 2009 From: terry.yinzhe at gmail.com (Terry) Date: Sun, 16 Aug 2009 02:38:20 -0700 (PDT) Subject: ignored test cases in unittest References: <873a7so66v.fsf@benfinney.id.au> Message-ID: <56527679-4cec-49a1-9b46-c38de8f981c8@g10g2000yqh.googlegroups.com> On Aug 16, 5:25?pm, Duncan Booth wrote: > Ben Finney wrote: > > Terry writes: > > >> It seemed the to me that python unittest module does not support the > >> counting of ignored test cases directly. Is there any ready solution > >> for this? > > > One solution I've seen involves: > > > * a custom exception class, ?TestSkipped? > > > * raising that exception at the top of test cases you want to > > ? temporarily skip > > > * a custom ?TestResult? class that knows about a ?skipped? result > > > * a custom reporter class that knows how you want to report that result > > I'd add to that a decorator so you can quickly mark a test case as ignored > without editing the test itself. Also you could include a reason why it is > ignored: > > ?@ignore("This test takes too long to run") > ?def test_foo(self): > ? ? ... > > That also means you can redefine the decorator easily if you want to try > running all the ignored tests. > > Another decorator useful here is one that asserts that the test will fail. > If the test passes then maybe someone fixed whatever was making it fail and > if so you want to consider re-enabling it. > > ?@fails("Needs the frobnozz module to be updated") > ?def test_whotsit(self): > ? ? ... Thanks for the solutions. I think the decorator idea is what I'm look for:-) From breamoreboy at yahoo.co.uk Sun Aug 16 05:38:50 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 16 Aug 2009 10:38:50 +0100 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: <50697b2c0908160107k6f31141dt5143071d0ff54c71@mail.gmail.com> References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160107k6f31141dt5143071d0ff54c71@mail.gmail.com> Message-ID: Chris Rebert wrote: > On Sat, Aug 15, 2009 at 1:06 PM, Mark Lawrence wrote: >> Xavier Ho wrote: >>> Hey all, >>> >>> I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in >>> the >>> documentation. >>> >>> Is there a substitution for this special method in 3.1, or do I really >>> have >>> to define all six rich comparison methods to work it out? >>> >>> If this question has already been asked somewhere, I apologise in advance. >>> Already googled around but I didn't find information on this. >>> >>> Any replies appreciated. >>> >> http://bytes.com/topic/python/answers/844614-python-3-sorting-comparison-function > > That seems to be about the built-in function cmp(). The OP was asking > about the special method __cmp__ and the related rich comparison > special methods (__eq__, __lt__, etc). > > Cheers, > Chris Blast, I posted the wrong flaming link, sorry everybody. -- Kindest regards. Mark Lawrence. From contact at xavierho.com Sun Aug 16 05:45:42 2009 From: contact at xavierho.com (Xavier Ho) Date: Sun, 16 Aug 2009 19:45:42 +1000 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160107k6f31141dt5143071d0ff54c71@mail.gmail.com> Message-ID: <2d56febf0908160245i5fd0d9f2kba74d112f0826932@mail.gmail.com> On Sun, Aug 16, 2009 at 7:38 PM, Mark Lawrence wrote: > > Blast, I posted the wrong flaming link, sorry everybody. > No, don't be sorry. I found your link very informative, and while it's a little mixed, it could be useful. I'm really looking for a way to set up Python classes' natural ordering for sorting purposes. For example, every object of a class could own an attribute called 'Value'. If I could get Python to sort() a list of classes with that value, would the key=value parameter work, and is there a better way than to redefine 3 or more of the rich comparison special methods, etc. Also, I noticed heapq (the priority queue/heap queue module) doesn't use the natural sorting order like sorted() does. Just saying. Could someone give it a try? Regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregor.lingl at aon.at Sun Aug 16 05:46:19 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sun, 16 Aug 2009 11:46:19 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: References: <4a85ffe2$0$24643$426a34cc@news.free.fr> <4a87036a$0$2292$91cee783@newsreader02.highway.telekom.at> Message-ID: <4a87d56b$0$1540$91cee783@newsreader04.highway.telekom.at> Mark Tolonen schrieb: > > "Gregor Lingl" wrote in message > news:4a87036a$0$2292$91cee783 at newsreader02.highway.telekom.at... >> Emile van Sebille schrieb: >>> On 8/14/2009 5:22 PM candide said... >> ... >>>> What is the pythonic way to do this ? >>> >>> I like list comps... >>> >>> >>> jj = '1234567890123456789' >>> >>> ",".join([jj[ii:ii+3] for ii in range(0,len(jj),3)]) >>> '123,456,789,012,345,678,9' >>> >>> >>> >>> Emile >>> >> >> Less beautiful but more correct: >> >> >>> ",".join([jj[max(ii-3,0):ii] for ii in >> range(len(jj)%3,len(jj)+3,3)]) >> '1,234,567,890,123,456,789' >> >> Gregor > > Is it? > >>>> jj = '234567890123456789' >>>> ",".join([jj[max(ii-3,0):ii] for ii in range(len(jj)%3,len(jj)+3,3)]) > ',234,567,890,123,456,789' Schluck! Even more ugly: ",".join([jj[max(ii-3,0):ii] for ii in range(len(jj)%3,len(jj)+3,3)]).strip(",") '234,567,890,123,456,789' Gregor > > At least one other solution in this thread had the same problem. > > -Mark > > From terry.yinzhe at gmail.com Sun Aug 16 05:47:42 2009 From: terry.yinzhe at gmail.com (Terry) Date: Sun, 16 Aug 2009 02:47:42 -0700 (PDT) Subject: flatten a list of list Message-ID: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Hi, Is there a simple way (the pythonic way) to flatten a list of list? rather than my current solution: new_list=[] for l in list_of_list: new_list.extend(l) or, new_list=reduce(lambda x,y:x.extend(y), list_of_list) br, Terry From clp2 at rebertia.com Sun Aug 16 05:55:48 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 05:55:48 -0400 Subject: flatten a list of list In-Reply-To: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <50697b2c0908160255v10bfa290jd7ca1ea8635eadbb@mail.gmail.com> On Sun, Aug 16, 2009 at 5:47 AM, Terry wrote: > Hi, > > Is there a simple way (the pythonic way) to flatten a list of list? > rather than my current solution: > > new_list=[] > for l in list_of_list: > ? ?new_list.extend(l) > > or, > > new_list=reduce(lambda x,y:x.extend(y), list_of_list) #only marginally better: from operator import add new_list = reduce(add, list_of_list) #from the itertools recipes: from itertools import chain def flatten(listOfLists): return list(chain.from_iterable(listOfLists)) Cheers, Chris -- http://blog.rebertia.com From foetsch at yahoo.com Sun Aug 16 06:03:53 2009 From: foetsch at yahoo.com (=?ISO-8859-1?Q?Michael_F=F6tsch?=) Date: Sun, 16 Aug 2009 12:03:53 +0200 Subject: flatten a list of list In-Reply-To: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <4A87D989.2030508@yahoo.com> Terry wrote: > Is there a simple way (the pythonic way) to flatten a list of list? This is probably the shortest it can get: sum(list_of_lists, []) Kind Regards, M.F. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 06:18:11 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 10:18:11 GMT Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <0297b230$0$20634$c3e8da3@news.astraweb.com> <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> Message-ID: <0297cd31$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 01:41:41 -0700, Douglas Alan wrote: > I like to be able to read everything from left to right, and Lisp does > that more than any other programming language. > > I would definitely not like a language that obscures assignment by > moving it over to the right side of lines. One could argue that left-assigned-from-right assignment obscures the most important part of the assignment, namely *what* you're assigning, in favour of what you're assigning *to*. In any case, after half a century of left-from-right assignment, I think it's worth the experiment in a teaching language or three to try it the other way. The closest to this I know of is the family of languages derived from Apple's Hypertalk, where you do assignment with: put somevalue into name (Doesn't COBOL do something similar?) Beginners found that *very* easy to understand, and it didn't seem to make coding harder for experienced Hypercard developers. -- Steven From sturlamolden at yahoo.no Sun Aug 16 06:19:51 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Aug 2009 03:19:51 -0700 (PDT) Subject: wxFormBuilder finally supports wxPython Message-ID: Version 3.1 of wxFormBuilder can generate wxPython code. I have previously used wxFormBuilder to generate XRC files for my wxPython projects. Though still in beta, this might be even better. :-) http://wxformbuilder.org/ From mail at johannes-janssen.de Sun Aug 16 06:25:46 2009 From: mail at johannes-janssen.de (Johannes Janssen) Date: Sun, 16 Aug 2009 12:25:46 +0200 Subject: How to find out in which module an instance of a class is created? In-Reply-To: References: <4A7F4874.8030008@johannes-janssen.de> <4A7F6016.2060408@cheimes.de> <4A80967F.9030604@johannes-janssen.de> Message-ID: <4A87DEAA.3020309@johannes-janssen.de> Gabriel Genellina schrieb: > The try/except around sys._getframe(1) is because that function is not > mandatory/available on all Python implementations (that's the case for > jython which doesn't provide it). Thanks, shouldn't such information be part of the python documentation of sys._getframe() (http://docs.python.org/library/sys.html?highlight=sys._getframe#sys._getframe)? Johannes From clp2 at rebertia.com Sun Aug 16 06:30:54 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 06:30:54 -0400 Subject: How to find out in which module an instance of a class is created? In-Reply-To: <4A87DEAA.3020309@johannes-janssen.de> References: <4A7F4874.8030008@johannes-janssen.de> <4A7F6016.2060408@cheimes.de> <4A80967F.9030604@johannes-janssen.de> <4A87DEAA.3020309@johannes-janssen.de> Message-ID: <50697b2c0908160330p43397ac7g86d7e9010cb90d25@mail.gmail.com> On Sun, Aug 16, 2009 at 6:25 AM, Johannes Janssen wrote: > Gabriel Genellina schrieb: >> >> The try/except around sys._getframe(1) is because that function is not >> mandatory/available on all Python implementations (that's the case for >> jython which doesn't provide it). > > Thanks, shouldn't such information be part of the python documentation of > sys._getframe() > (http://docs.python.org/library/sys.html?highlight=sys._getframe#sys._getframe)? The leading underscore kinda indirectly implies it, but yeah, it's worth mentioning. File a bug in the docs: http://bugs.python.org/ Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 06:49:59 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 10:49:59 GMT Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <0297d4a6$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 05:55:48 -0400, Chris Rebert wrote: > On Sun, Aug 16, 2009 at 5:47 AM, Terry wrote: >> Hi, >> >> Is there a simple way (the pythonic way) to flatten a list of list? >> rather than my current solution: >> >> new_list=[] >> for l in list_of_list: >> ? ?new_list.extend(l) >> >> or, >> >> new_list=reduce(lambda x,y:x.extend(y), list_of_list) > > #only marginally better: > from operator import add > new_list = reduce(add, list_of_list) Surely that's going to be O(N**2)? I'd predict that would perform even worse than O(N**2) string concatenation, on account that a string of size N has to allocate space for N bytes, but a list of size N allocates space for N pointers (each 4 bytes, or 8 depending on the system), rounded up to the nearest power of two. Also CPython can optimize string concatenation to O(N) under some circumstances, but not lists. >>> from timeit import Timer >>> setup = """\\ ... L = [ ([None]*5000) for x in xrange(%d) ] ... from operator import add ... """ >>> Timer("reduce(add, L)", setup % 4).repeat(number=1000) [0.53808808326721191, 0.51404905319213867, 0.51157188415527344] >>> Timer("reduce(add, L)", setup % 8).repeat(number=1000) [2.1178171634674072, 3.8830602169036865, 4.72245192527771] >>> Timer("reduce(add, L)", setup % 16).repeat(number=1000) [17.190337896347046, 21.572744131088257, 21.584265947341919] Looks like O(N**2) behaviour to me. -- Steven From mail at johannes-janssen.de Sun Aug 16 06:50:27 2009 From: mail at johannes-janssen.de (Johannes Janssen) Date: Sun, 16 Aug 2009 12:50:27 +0200 Subject: How to find out in which module an instance of a class is created? In-Reply-To: <50697b2c0908160330p43397ac7g86d7e9010cb90d25@mail.gmail.com> References: <4A7F4874.8030008@johannes-janssen.de> <4A7F6016.2060408@cheimes.de> <4A80967F.9030604@johannes-janssen.de> <4A87DEAA.3020309@johannes-janssen.de> <50697b2c0908160330p43397ac7g86d7e9010cb90d25@mail.gmail.com> Message-ID: <4A87E473.7010606@johannes-janssen.de> Chris Rebert schrieb: > On Sun, Aug 16, 2009 at 6:25 AM, Johannes > Janssen wrote: > >> Gabriel Genellina schrieb: >> >>> The try/except around sys._getframe(1) is because that function is not >>> mandatory/available on all Python implementations (that's the case for >>> jython which doesn't provide it). >>> >> Thanks, shouldn't such information be part of the python documentation of >> sys._getframe() >> (http://docs.python.org/library/sys.html?highlight=sys._getframe#sys._getframe)? >> > > The leading underscore kinda indirectly implies it, but yeah, it's > worth mentioning. > File a bug in the docs: http://bugs.python.org/ > > Cheers, > Chris > I filed a bug: http://bugs.python.org/issue6712 . Johannes From clp2 at rebertia.com Sun Aug 16 06:59:52 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 06:59:52 -0400 Subject: flatten a list of list In-Reply-To: <0297d4a6$0$20634$c3e8da3@news.astraweb.com> References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297d4a6$0$20634$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0908160359u6c8cb593r627651a80017394e@mail.gmail.com> On Sun, Aug 16, 2009 at 6:49 AM, Steven D'Aprano wrote: > On Sun, 16 Aug 2009 05:55:48 -0400, Chris Rebert wrote: >> On Sun, Aug 16, 2009 at 5:47 AM, Terry wrote: >>> Hi, >>> >>> Is there a simple way (the pythonic way) to flatten a list of list? >>> rather than my current solution: >>> >>> new_list=[] >>> for l in list_of_list: >>> ? ?new_list.extend(l) >>> >>> or, >>> >>> new_list=reduce(lambda x,y:x.extend(y), list_of_list) >> >> #only marginally better: >> from operator import add >> new_list = reduce(add, list_of_list) > > Surely that's going to be O(N**2)? The OP asked for "simple", not "best", "most proper", or "fastest". My comment was intended to mean that the code was marginally *simpler*, not faster. Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 07:08:09 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 11:08:09 GMT Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <0297d8e8$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 12:03:53 +0200, Michael F?tsch wrote: > Terry wrote: >> Is there a simple way (the pythonic way) to flatten a list of list? > > This is probably the shortest it can get: > > sum(list_of_lists, []) That's also O(N**2). >>> from timeit import Timer >>> setup = "L = [ ([None]*5000) for x in xrange(%d) ]" >>> Timer("sum(L, [])", setup % 4).repeat(number=1000) [0.6070549488067627, 0.54354715347290039, 0.54686999320983887] >>> Timer("sum(L, [])", setup % 8).repeat(number=1000) [2.1285719871520996, 3.6722278594970703, 4.0785009860992432] >>> Timer("sum(L, [])", setup % 16).repeat(number=1000) [18.370341062545776, 20.40509295463562, 21.871708869934082] -- Steven From hendrik at microcorp.co.za Sun Aug 16 07:15:06 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 16 Aug 2009 13:15:06 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? - conclusions In-Reply-To: <4a87a444$0$1627$742ec2ed@news.sonic.net> References: <4a87a444$0$1627$742ec2ed@news.sonic.net> Message-ID: <200908161315.07229.hendrik@microcorp.co.za> On Sunday 16 August 2009 08:20:34 John Nagle wrote: > Hendrik van Rooyen wrote: > > On Saturday 15 August 2009 14:40:35 Michael Str?der wrote: > >> Hendrik van Rooyen wrote: > >>> In the past, on this group, I have made statements that said that on > >>> Linux, the serial port handling somehow does not allow transmitting and > >>> receiving at the same time, and nobody contradicted me. > > Absolutely false. No its true, if you open the serial port with the standard open() instead of os.open(). And it is also true that I was not contradicted in the past. :-) > > >> Despite all the good comments here by other skilled people I'd recommend > >> to determine whether the transmission line to the devices accessed > >> support full duplex. > > All standard PC serial ports are full-duplex devices. > I know this, and I started the thread because they would not work full duplex for me. 8< -------------------- pyserial baudot program link ----------------------- > > You raise a good point, that is probably not well known amongst the > > youngsters here, as simple serial multidropping has gone out of fashion. > > Actually, no. Dynamixel servos as used on the latest Bioloid robots > are multidrop serial RS-485. But outside the embedded world, nobody uses > that stuff any more. (Embedded is going Ethernet; it's overkill but > works fine and is now cheap.) Exactly - it is no longer part of mainstream fashion. We also still use RS-485 because it is cheaper, and we have better control over timing. I enclose two naive test implementations. To run them you will need a loopback connector. One can be made by shorting pin 2 and 3 together on the standard DB9. The results are illuminating - on my development machine, (dual 64 bit, some gigs), the last lines look like this: test.py: The quick brown fox jumps over the lazy dog 1023 That took 3.91238284111 seconds - 3.82068636827 Millisecs per record, 261.733077152 recs per sec hvr at Linuxbox:~/dos/JOBS/sms/lib> test1.py: The quick brown fox jumps over the lazy dog 1023 That took 3.90402388573 seconds - 3.81252332591 Millisecs per record, 262.293477185 recs per sec hvr at Linuxbox:~/dos/JOBS/sms/lib> Almost no difference between the two implementations. This is basically because there is enough processing power to keep the link running at full speed in both instances. On the eBox, (486, 400MHz, 128Mb, no FP), the difference is startling: test.py: The quick brown fox jumps over the lazy dog 1023 That took 69.2863521576 seconds - 67.6624532789 Millisecs per record, 14.7792453797 recs per sec root at ebox:/home/user/sms/lib# About eighteen times slower than the development machine. test1.py: The quick brown fox jumps over the lazy dog 1023 That took 10.391780138 seconds - 10.148222791 Millisecs per record, 98.5394211964 recs per sec root at ebox:/home/user/sms/lib# Less than three times slower than the development machine. The little processor + Slackware + python cannot keep the link busy. Python, as a character handler, well let us say that it is suboptimal, because saying that something sucks, sucks. An almost seven times ratio between the implementations is not to be sneezed at. So the conclusions I have come to are the following: 1) Thou shalt not use ordinary python files for serial ports, on pain of death. 2) Thou shalt strive mightily to minimize python calls, doing all in thy power to move away from character input to string input. 3) Thou shalt expend real treasure for real processing power as there is no such thing as a free lunch. I would like to thank everybody who took the trouble to respond to teach me the error of my ways. - Hendrik -------------- next part -------------- A non-text attachment was scrubbed... Name: test1.py Type: application/x-python Size: 1900 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: application/x-python Size: 1832 bytes Desc: not available URL: From subhakolkata1234 at gmail.com Sun Aug 16 07:19:06 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Sun, 16 Aug 2009 04:19:06 -0700 (PDT) Subject: Problem Regarding Handling of Unicode string References: <9ac0e194-9e25-468a-9807-957ef3142dd3@i18g2000pro.googlegroups.com> <47b265c5-e71f-4018-815a-0bfbea927a4a@y28g2000prd.googlegroups.com> Message-ID: On Aug 11, 1:17?pm, John Machin wrote: > On Aug 10, 9:26?pm, joy99 wrote: > > > Dear Group, > > > I am using Python26 on WindowsXP with service pack2. My GUI is IDLE. > > I am using Hindi resources and get nice output like: > > ?? > > where I can use all the re functions and other functions without doing > > any transliteration,etc. > > I was trying to use Bengali but it is giving me output like: > > WHAT is giving you this output? > > > '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95' > > In a very ordinary IDLE session (Win XP SP3, Python 2.6.2, locale: > Australia/English, no "Hindi resources"): > > >>> x = '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95' > >>> ux = x.decode('utf-8') > >>> ux > > u'\ufeff\u0985\u09a8\u09c7\u0995'>>> print ux > > ????? # looks like what you wanted; please confirm>>> import unicodedata > >>> for c in ux: > > ? ? ? ? print unicodedata.name(c) > > ZERO WIDTH NO-BREAK SPACE # this is a BOM > BENGALI LETTER A > BENGALI LETTER NA > BENGALI VOWEL SIGN E > BENGALI LETTER KA > > > > > I wanted to see Bengali output as > > ???? > > and I like to use all functions including re. > > If any one can help me on that. > > "I am using Hindi resources" doesn't tell us much ... except to prompt > the comment that perhaps if you want to display Bengali script, you > may need Bengali resources. However it looks like I can display your > Bengali data without any special resources. > > It seems like you are not doing the same with Bengali as you are doing > with Hindi. We can't help you very much if you don't show exactly what > you are doing. > > Have you considered asking in an Indian Python forum? Note: you will > still need to say what you are doing that works with Hindi but not > with Bengali. > > Cheers, > John Dear Group, I have already worked out my solution but everyone of yours' answers helped me to see different solutions from different angles. Thank you for the same. I am building some social network program in Bengali. I just gave the transliteration problem which was giving me problem, I thought as you are very expert pythoners so it would be minutes' matter. By your answers I saw I was not wrong. But as I solved the problem so I checked it bit late. Sorry for the same. Best Regards, Subhabrata. From terry.yinzhe at gmail.com Sun Aug 16 07:22:00 2009 From: terry.yinzhe at gmail.com (Terry) Date: Sun, 16 Aug 2009 04:22:00 -0700 (PDT) Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297d4a6$0$20634$c3e8da3@news.astraweb.com> Message-ID: On Aug 16, 6:59?pm, Chris Rebert wrote: > On Sun, Aug 16, 2009 at 6:49 AM, Steven > > > > > > D'Aprano wrote: > > On Sun, 16 Aug 2009 05:55:48 -0400, Chris Rebert wrote: > >> On Sun, Aug 16, 2009 at 5:47 AM, Terry wrote: > >>> Hi, > > >>> Is there a simple way (the pythonic way) to flatten a list of list? > >>> rather than my current solution: > > >>> new_list=[] > >>> for l in list_of_list: > >>> ? ?new_list.extend(l) > > >>> or, > > >>> new_list=reduce(lambda x,y:x.extend(y), list_of_list) > > >> #only marginally better: > >> from operator import add > >> new_list = reduce(add, list_of_list) > > > Surely that's going to be O(N**2)? > > The OP asked for "simple", not "best", "most proper", or "fastest". My > comment was intended to mean that the code was marginally *simpler*, > not faster. > > Cheers, > Chris > --http://blog.rebertia.com Well, if possible, I'd like not only to know a simple solution, but also the 'best', the 'most proper' and the 'fastest':-) If they are not the same. br, Terry From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 07:25:53 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 11:25:53 GMT Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <0297dd0f$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 02:47:42 -0700, Terry wrote: > Hi, > > Is there a simple way (the pythonic way) to flatten a list of list? > rather than my current solution: > > new_list=[] > for l in list_of_list: > new_list.extend(l) I don't think that scales terribly well. In my testing, it performs about as badly as the O(N**2) behaviours others have suggested (using sum or reduce with add) -- perhaps a bit worse for small N, but not quite as badly for large N. > new_list=reduce(lambda x,y:x.extend(y), list_of_list) That doesn't even work. >>> list_of_list = [ [1,2,3], [2, 4, 8] ] >>> new_list=reduce(lambda x,y:x.extend(y), list_of_list) >>> new_list is None True Chris' suggestion using itertools seems pretty good: >>> from timeit import Timer >>> setup = """\\ ... L = [ [None]*5000 for _ in xrange(%d) ] ... from itertools import chain ... """ >>> Timer("list(chain.from_iterable(L))", setup % 4).repeat(number=1000) [0.61839914321899414, 0.61799716949462891, 0.62065696716308594] >>> Timer("list(chain.from_iterable(L))", setup % 8).repeat(number=1000) [1.2618398666381836, 1.3385050296783447, 3.9113419055938721] >>> Timer("list(chain.from_iterable(L))", setup % 16).repeat(number=1000) [3.1349358558654785, 4.8554730415344238, 5.4319999217987061] -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 07:31:57 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 11:31:57 GMT Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297d4a6$0$20634$c3e8da3@news.astraweb.com> Message-ID: <0297de7c$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 06:59:52 -0400, Chris Rebert wrote: >> Surely that's going to be O(N**2)? > > The OP asked for "simple", not "best", "most proper", or "fastest". My > comment was intended to mean that the code was marginally *simpler*, not > faster. Fair enough, but he also asked for Pythonic, and while some people might argue that "terrible performance" is Pythonic, I hope you wouldn't be one of them! :) If it soothes your ruffled sense of honour *wink*, I think your solution with itertools.chain is probably the best so far. -- Steven From tjreedy at udel.edu Sun Aug 16 07:39:40 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 16 Aug 2009 20:39:40 +0900 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: <2d56febf0908160245i5fd0d9f2kba74d112f0826932@mail.gmail.com> References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160107k6f31141dt5143071d0ff54c71@mail.gmail.com> <2d56febf0908160245i5fd0d9f2kba74d112f0826932@mail.gmail.com> Message-ID: Xavier Ho wrote: > I'm really looking for a way to set up Python classes' natural ordering > for sorting purposes. I believe __lt__ (<) is the only method (operator) used by both .sort and heap module. From hendrik at microcorp.co.za Sun Aug 16 07:42:14 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 16 Aug 2009 13:42:14 +0200 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <0297cd31$0$20634$c3e8da3@news.astraweb.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> <0297cd31$0$20634$c3e8da3@news.astraweb.com> Message-ID: <200908161342.14612.hendrik@microcorp.co.za> On Sunday 16 August 2009 12:18:11 Steven D'Aprano wrote: > In any case, after half a century of left-from-right assignment, I think > it's worth the experiment in a teaching language or three to try it the > other way. The closest to this I know of is the family of languages > derived from Apple's Hypertalk, where you do assignment with: > > put somevalue into name > > (Doesn't COBOL do something similar?) Yup. move banana to pineapple. move accountnum in inrec to accountnum in outrec. move corresponding inrec to outrec. It should all be upper case of course... I cannot quite recall, but I have the feeling that in the second form, "of" was also allowed instead of "in", but it has been a while now so I am probably wrong. The move was powerful - it would do conversions for you based on the types of the operands - it all "just worked". - Hendrik From clp2 at rebertia.com Sun Aug 16 07:43:00 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 07:43:00 -0400 Subject: flatten a list of list In-Reply-To: <0297de7c$0$20634$c3e8da3@news.astraweb.com> References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297d4a6$0$20634$c3e8da3@news.astraweb.com> <0297de7c$0$20634$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0908160443j1608f14dsb9ec1b7f39bd6410@mail.gmail.com> On Sun, Aug 16, 2009 at 7:31 AM, Steven D'Aprano wrote: > On Sun, 16 Aug 2009 06:59:52 -0400, Chris Rebert wrote: >>> Surely that's going to be O(N**2)? >> >> The OP asked for "simple", not "best", "most proper", or "fastest". My >> comment was intended to mean that the code was marginally *simpler*, not >> faster. > > Fair enough, but he also asked for Pythonic, and while some people might > argue that "terrible performance" is Pythonic, I hope you wouldn't be one > of them! :) Indeed not. :) I expected it would be worse performance-wise than the OP's original due to all the intermediate lists that get produced; it shouldn't be used in optimized production code. > If it soothes your ruffled sense of honour *wink*, I think your solution > with itertools.chain is probably the best so far. Except it's not really my solution, it's whoever put it in the itertools docs's. :( But I'm glad to been able to help by pointing the recipe out. :-) Cheers, Chris -- http://blog.rebertia.com From breamoreboy at yahoo.co.uk Sun Aug 16 07:49:16 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 16 Aug 2009 12:49:16 +0100 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: <50697b2c0908160104k7d74ace9jda8f4b927402942@mail.gmail.com> References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160104k7d74ace9jda8f4b927402942@mail.gmail.com> Message-ID: Chris Rebert wrote: > On Sat, Aug 15, 2009 at 8:09 AM, Xavier Ho wrote: >> Hey all, >> >> I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in the >> documentation. >> >> Is there a substitution for this special method in 3.1, or do I really have >> to define all six rich comparison methods to work it out? > > I don't think so. Quoting > http://docs.python.org/dev/py3k/reference/datamodel.html > > "There are no swapped-argument versions of [the comparison] methods > (to be used when the left argument does not support the operation but > the right argument does); rather, __lt__() and __gt__() are each > other?s reflection, __le__() and __ge__() are each other?s reflection, > and __eq__() and __ne__() are their own reflection." > > I believe this means you only need to define one method from each of > the following pairs to get all the operators working: > * __eq__ or __ne__ > * __lt__ or __gt__ > * __ge__ or __le__ > > Cheers, > Chris Unfortunately I don't think it's that easy, see. http://mail.python.org/pipermail/python-list/2008-November/688761.html The issue referenced is still open. This of course assumes that I've posted the correct link this time! -- Kindest regards. Mark Lawrence. From contact at xavierho.com Sun Aug 16 07:58:35 2009 From: contact at xavierho.com (Xavier Ho) Date: Sun, 16 Aug 2009 21:58:35 +1000 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160104k7d74ace9jda8f4b927402942@mail.gmail.com> Message-ID: <2d56febf0908160458k3b5197d8tf1a69e3083ab3146@mail.gmail.com> On Sun, Aug 16, 2009 at 9:49 PM, Mark Lawrence wrote: > > Unfortunately I don't think it's that easy, see. > http://mail.python.org/pipermail/python-list/2008-November/688761.html > The issue referenced is still open. This of course assumes that I've > posted the correct link this time! > I'm not sure what you're referring to here. The link brought me to about __ne__ being automatically determined when __eq__ is defined. Although it is a rich comparison special method, it doesn't entirely cover the usefulness of __cmp__(). Terry: I'll give that a test tomorrow and see what I can come up with. Thanks for the quick info. Regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From luke.leighton at googlemail.com Sun Aug 16 08:08:39 2009 From: luke.leighton at googlemail.com (lkcl) Date: Sun, 16 Aug 2009 05:08:39 -0700 (PDT) Subject: platform-specific overrides of functions and class methods (expanding on imputils demo code) Message-ID: i've just had to put something together for pyjamas-desktop which may prove to be useful to other people, so i'm pointing people in its general direction, for archive purposes. the purpose behind the platform override system is to allow implementations of a common API, in python, to share the majority of their codebase (modules, classes, functions etc.) _but_, for _very_ specific platform implementation purposes, allow for "overrides". example: test.py def test(): print "hello" platform/testOverridingPlatformName.py: def test(): print "this is not kansas any more" code is here: http://pyjamas.svn.sourceforge.net/viewvc/pyjamas/trunk/pyjd/ modules to pay attention to: importers.py (a modified version of Demos/ imputils/importers.py) and modcompile.py. setup/init function is very simple - see __init__py.in last few lines. on reading modcompile.py you may be forgiven for going "wtf????" but basically PlatformParser loads the python source; turns it into an AST; then also the "platform-specific" version is loaded and turned into an AST; then, the two ASTs are handed to the "merge" function which does a top-level "replace" of functions and a top-level "replace" of class methods. _theen_ the resultant "merged" AST is handed to a module which was derived from compiler/pycodegen.py - none of the code in there can cope with being handed an already-compiled AST so it was necessary to make a class that did. looking around on the internet i find quite a few people asking about how to do this, so ... take a look at modcompile.Module, and how it's used. very simple. i've disabled saving and detection of .pyc files for now, because the job of loading code from .pyc should really be done by PlatformParser (which understands the concept of... duh, a platform). the _last_ thing that you want to happen is to run one platform's code, generate some .pyc files, then change a config file to run a different back-end platform, for example (which is possible with pyjamas-desktop) and end up running the _wrong_ platform-specific code. for those people wondering, "why in god's green earth would anyone want to _do_ such a thing???" it's quite simple: the alternative is a complete dog's dinner, in pyjamas: def do_some_DOM_manipulation(document): # heeeere we go... if platform == 'hulahop' # this is for XULrunner do_some_stuff() elif platform == 'pywebkitgtk': do_something_different() elif platform == 'mshtml' # for pywin32 and comtypes.... do_something_dreadful() else: do_the_default_here() now imagine that across an API with ... four hundred functions. i just... couldn't bring myself to do that. not when the pyjs (python- to-javascript) compiler _already_ solved this problem (thanks to james tauber) by deploying the AST merge concept. all i did was merge that with the imputils demo code so that, rather than at compile-time the pyjs compiler goes and generates five platform-specific versions of the same application, pyjamas-desktop at _run_ time can do exactly the same thing. but - it's a generic enough idea to be of value elsewhere - for example, all the loooovely code in e.g. the setup distutils? all those looovely "if os.platform == 'win32'", and "if sys.this = 'posix' " could be replaced with platform-specific overrides that got merged at run-time, thus _dramatically_ simplifying the look and the useability of the code. enjoy. l. From bearophileHUGS at lycos.com Sun Aug 16 08:24:36 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Sun, 16 Aug 2009 05:24:36 -0700 (PDT) Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297d4a6$0$20634$c3e8da3@news.astraweb.com> Message-ID: <218b0a2e-ed83-4675-9942-6297048a4676@c14g2000yqm.googlegroups.com> Chris Rebert: > The OP asked for "simple", not "best", "most proper", or "fastest". My > comment was intended to mean that the code was marginally *simpler*, > not faster. Yep, the OP has asked for simple code. But often this is not the right way to solve this situation. A better way is to create (or copy) a flatten that's efficient and well tested & debugged, put it into some library of utilities, and then use import&use it when it's needed. Bye, bearophile From breamoreboy at yahoo.co.uk Sun Aug 16 08:33:29 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 16 Aug 2009 13:33:29 +0100 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: <2d56febf0908160458k3b5197d8tf1a69e3083ab3146@mail.gmail.com> References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160104k7d74ace9jda8f4b927402942@mail.gmail.com> <2d56febf0908160458k3b5197d8tf1a69e3083ab3146@mail.gmail.com> Message-ID: Xavier Ho wrote: > On Sun, Aug 16, 2009 at 9:49 PM, Mark Lawrence wrote: > >> Unfortunately I don't think it's that easy, see. >> http://mail.python.org/pipermail/python-list/2008-November/688761.html >> The issue referenced is still open. This of course assumes that I've >> posted the correct link this time! >> > > I'm not sure what you're referring to here. The link brought me to about > __ne__ being automatically determined when __eq__ is defined. Although it is > a rich comparison special method, it doesn't entirely cover the usefulness > of __cmp__(). > > Terry: I'll give that a test tomorrow and see what I can come up with. > Thanks for the quick info. > > Regards, > > Ching-Yun "Xavier" Ho, Technical Artist > > Contact Information > Mobile: (+61) 04 3335 4748 > Skype ID: SpaXe85 > Email: contact at xavierho.com > Website: http://xavierho.com/ > > I wasn't discussing __cmp__, I was referring to the quote by Chris Rebert from the Python docs regarding the rich comparison methods, a discrepancy between the documentation and the implementation as noted in the link that I gave, and an indication that the issue raised on this discrepancy is still open. As Terry Reedy has mentioned __lt__ elsewhere, you should be aware of the discrepancy, otherwise you could go charging off down the wrong track. FWIW it was Terry who raised the issue 4395, I'm sure that he could explain the ramifications of it all far better than I ever could, so I'll sign out. -- Kindest regards. Mark Lawrence. From python at mrabarnett.plus.com Sun Aug 16 08:45:22 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 16 Aug 2009 13:45:22 +0100 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <34dd6e0e-3b47-4761-ad7a-9038b0d36209@v36g2000yqv.googlegroups.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <34dd6e0e-3b47-4761-ad7a-9038b0d36209@v36g2000yqv.googlegroups.com> Message-ID: <4A87FF62.2020508@mrabarnett.plus.com> Douglas Alan wrote: [snip] > C++ also allows for reading from stdin like so: > > cin >> myVar; > > I think the direction of the arrows probably derives from languages > like APL, which had notation something like so: > > myVar <- 3 > [] <- myVar > > "<-" was really a little arrow symbol (APL didn't use ascii), and the > first line above would assign the value 3 to myVar. In the second > line, the "[]" was really a little box symbol and represented the > terminal. Assigning to the box would cause the output to be printed > on the terminal, so the above would output "3". If you did this: > > [] -> myVar > > It would read a value into myVar from the terminal. > > APL predates Unix by quite a few years. > No, APL is strictly right-to-left. -> x means "goto x". Writing to the console is: [] <- myVar Reading from the console is: myVar <- [] From magawake at gmail.com Sun Aug 16 09:25:42 2009 From: magawake at gmail.com (Mag Gam) Date: Sun, 16 Aug 2009 09:25:42 -0400 Subject: unittest In-Reply-To: References: <1cbd6f830908142028v638a4c06jf0f859be712e724c@mail.gmail.com> Message-ID: <1cbd6f830908160625m5a8ffa9er7e34c203f30fca49@mail.gmail.com> John: Well, this is actually a script which wraps around another application. :-) My goal is when I introduce a new feature I don't want to break old stuff so instead of me testing manually I want to build a framework of tests. On Sat, Aug 15, 2009 at 11:37 PM, John Haggerty wrote: > This is an interesting question. I am just wondering: do you really have > that many features that it would be impossible to just have a shell script > run specific types of input or tests? > > When I did programming in the past for education they just had lists of > input data and we ran the program against the test data. > > I just get slightly confused when "test suites" start to have to apply? > > On Fri, Aug 14, 2009 at 9:28 PM, Mag Gam wrote: >> >> I am writing an application which has many command line arguments. >> For example: foo.py -args "bar bee" >> >> I would like to create a test suit using unittest so when I add >> features to "foo.py" I don't want to break other things. I just heard >> about unittest and would love to use it for this type of thing. >> >> so my question is, when I do these tests do I have to code them into >> foo.py? I prefer having a footest.py which will run the regression >> tests. Any thoughts about this? >> >> TIA >> -- >> http://mail.python.org/mailman/listinfo/python-list > > From kevin.p.dwyer at gmail.com Sun Aug 16 09:31:19 2009 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Sun, 16 Aug 2009 13:31:19 +0000 (UTC) Subject: my recursive function call is wrong? References: <22a413260908160057t2802d3cci70658278e7322eb8@mail.gmail.com> Message-ID: On Sun, 16 Aug 2009 16:57:41 +0900, Chang Min Jeon wrote: Hello, You have placed recursive calls to the function in a number of different locations; when len(macro) becomes zero control will return to the calling function, but this calling function may have more code to execute, including further calls to start_parse(), and further attempts to index macro. I like to keep recursive calls at the end of a function, so that there is a clean path back to the top level caller once the terminal condition is reached. You can do it differently, but you need to bear in mind the execution paths through your code. Cheers, Kev From emmanuel.surleau at gmail.com Sun Aug 16 09:34:06 2009 From: emmanuel.surleau at gmail.com (Emmanuel Surleau) Date: Sun, 16 Aug 2009 15:34:06 +0200 Subject: Python 'for' loop is memory inefficient In-Reply-To: <0297b471$0$20634$c3e8da3@news.astraweb.com> References: <24980842.post@talk.nabble.com> <0297b471$0$20634$c3e8da3@news.astraweb.com> Message-ID: <200908161534.06831.emmanuel.surleau@gmail.com> > It's a particular unfair criticism because the critic (Ethan Furman) > appears to have made a knee-jerk reaction. The "some language in Python" > behaviour he's reacting to is the common idiom: > > for i in range(len(seq)): > do_something_with(seq[i]) > > > instead of the "Python in Python" idiom: > > for obj in seq: > do_something_with(obj) > > > That's a reasonable criticism, but *not in the case*. Ethan appears to > have made the knee-jerk reaction "for i in range() is Bad" without > stopping to think about what this specific piece of code is actually > doing. > > (Replace 'obj' with 'j', 'seq' with 'range(2, n)', and > 'do_something_with' with 'if (n % j) == 0: return False', and you have > the exact same code pattern.) Fair enough. But as far as I know, for i in (x)range(num) is the canonical way to iterate over numbers in Python. Another case of lack of RTFM* before answering, I suppose. Cheers, Emm *Read The Fine Mail From grante at visi.com Sun Aug 16 09:55:31 2009 From: grante at visi.com (Grant Edwards) Date: Sun, 16 Aug 2009 08:55:31 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: Message-ID: On 2009-08-15, Hendrik van Rooyen wrote: > On Saturday 15 August 2009 16:25:03 Grant Edwards wrote: > >> Are you using python file operations open/read/write or OS >> file-descriptor operations os.open/os.read/os.write? > > The former - that seems to be the source of my trouble. > > I have now written a little test that uses serial.Serial and > it works a treat. Good to hear. > I am still confused about pyserial and serial - I found serial > in my distribution library, (on the SuSe machine, not on the > 2.5 in Slackware) but I had to download pyserial. That's very interesting. Is the pre-existing "serial" a version of pyserial that the packager had pre-installed or is it something else? I didn't know any distributions shipped Python with pyserial installed. In either case, "serial" isn't something that ships with the standard Python library. > I see that you were the the original author. Thank you for > letting this stuff loose in the wild. My pleasure. -- From jeanmichel at sequans.com Sun Aug 16 09:59:18 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Sun, 16 Aug 2009 15:59:18 +0200 Subject: callable virtual method In-Reply-To: References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A8810B6.8080204@sequans.com> Scott David Daniels wrote: > Jean-Michel Pichavant wrote: >> Steven D'Aprano wrote: >>> On Fri, 14 Aug 2009 18:49:26 +0200, Jean-Michel Pichavant wrote: >>> >>> >>>> Sorry guys (means guys *and* gals :op ), I realized I've not been able >>>> to describe precisely what I want to do. I'd like the base class to be >>>> virtual (aka abstract). However it may be abstract but it does not >>>> mean >>>> it cannot do some usefull stuff. >>>> >>>> >>>> Here is the schema of my abstract methods : >>>> >>>> class Interface(object): >>>> def method(self): >>>> # --------------------- >>>> # some common stuff executed here >>>> # --------------------- >>>> print 'hello world' >>>> # --------------------- >>>> # here shall stand child specific stuff (empty in the >>>> interface >>>> method) >>>> # --------------------- >>>> if self.__class__.method == Interface.method: >>>> raise NotImplementedError('You should have read the >>>> f****** >>>> manual ! You must override this method.') >>>> >>> >>> >>> Okay, so I want to sub-class your Interface class. As you said, the >>> methods in the abstract class are still useful, so in my class, I >>> don't need any extra functionality for some methods -- I'm happy >>> with just the "common stuff". So I use normal OO techniques and >>> over-ride just the methods I need to over-ride: >>> >>> >> Sometimes the base is doing cool stuff but incomplete stuff which >> requires knowledge only hold by the sub class. In my case the >> interface is a high level interface for a software that can run on >> multiple hardware platforms. Only the sub class has knowledge on how >> to operate the hardware, but no matter the hardware it still produces >> the same effect. >> >> Let's say I have 50 different hardwares, I'll have 50 sub classes of >> Interface with the 'start' method to define. It wouldn't be >> appropriate (OO programming)to write 50 times '_log.debug('Starting >> %s' % self)' in each child start method when the simple task of >> logging the call can be nicely handled by the base class. >> >> In the meantime, I must make sure the user, who is not a python guru >> in this case, has implemented the start method for his hardware, >> because only him knows how to effectively start this hardware. I >> don't want him to come to me saying, "I got no error, still my >> hardware does not start". You can then blame him for not reading the >> docs, but it will still be less expensive to throw a nice exception >> with an accurate feedback. >> >> [snip] >>> class VerboseGoodChild(Interface): >>> # forced to over-ride methods for no good reason >>> >> >> Definitely no !! This is the purpose of an interface class: to force >> people to write these methods. They *are* required, if they were not, >> they would not belong to the Interface. >> >> JM > > But there _is_ one moment when you can check those things, then avoid > checking thereafter: object creation. So you can complicate your > __init__ (or __new__) with those checks that make sure you instantiate > only fully defined subclasses: > > # obviously not tested except in concept: > > class Base(object_or_whatever): > def __init__(self, ...): > class_ = self.__class__ > if class_ is Base: > raise TypeError('Attempt to instantiate Base class') > for name in 'one two three four': > if getattr(Base, name) is not getattr(Base, name): > raise NotImplementedError( > '%s implementation missing' % name) > ... > > --Scott David Daniels > Scott.Daniels at Acm.Org That could do the trick, sparing me from writing additional code in each methods. Thanks. JM From lists at cheimes.de Sun Aug 16 10:07:13 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 16 Aug 2009 16:07:13 +0200 Subject: callable virtual method In-Reply-To: <4A8810B6.8080204@sequans.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> <4A8810B6.8080204@sequans.com> Message-ID: <4A881291.6030805@cheimes.de> Jean-Michel Pichavant wrote: >> Scott.Daniels at Acm.Org > That could do the trick, sparing me from writing additional code in each > methods. Thanks. Why are you trying to reinvent the wheel? Python's abc module already takes care of these details. Christian From jeanmichel at sequans.com Sun Aug 16 10:13:46 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Sun, 16 Aug 2009 16:13:46 +0200 Subject: callable virtual method In-Reply-To: References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> <4A85A47E.308@wiggly.org> <4A85ACEF.4090901@sequans.com> <4A85B9F7.4010201@ieee.org> <4A85D051.2080004@sequans.com> Message-ID: <4A88141A.1030201@sequans.com> Christian Heimes wrote: > Jean-Michel Pichavant wrote: >> talking about approaches: >> >> 1/ >> class Interface: >> def foo(self): >> if self.__class__.foo == Interface.foo: >> raise NotImplementedError >> >> 2/ >> class Interface: >> def foo(self): >> self._foo() >> >> def _foo(sef): >> raise NotImplementedError > > Please don't call it an interface when it's really an abstract base > class. And abstract base classes are probably the solution the OP is > looking for, http://docs.python.org/library/abc.html > > Christian > Sadly I'm working with python 2.4. Anyway it's good to hear they've added ABC support to python, didn't know that. I didn't know there was a difference between interface and abstract classes as well. With a little bit of googling, I found out that actually Interface classes do not provide any implementation. What I'm looking for is definitely an abstract class. JM From jeanmichel at sequans.com Sun Aug 16 10:17:39 2009 From: jeanmichel at sequans.com (jean-michel Pichavant) Date: Sun, 16 Aug 2009 16:17:39 +0200 Subject: callable virtual method In-Reply-To: <4A881291.6030805@cheimes.de> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> <4A8810B6.8080204@sequans.com> <4A881291.6030805@cheimes.de> Message-ID: <4A881503.7010202@sequans.com> Christian Heimes a ?crit : > Jean-Michel Pichavant wrote: >>> Scott.Daniels at Acm.Org >> That could do the trick, sparing me from writing additional code in >> each methods. Thanks. > > Why are you trying to reinvent the wheel? Python's abc module already > takes care of these details. > > Christian I'm working with python 2.4 and don't plan to change. The abc module would have been exactly what I was looking for. I'll keep it mind if I ever upgrade to python 2.6+ JM From victorsubervi at gmail.com Sun Aug 16 11:30:34 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 16 Aug 2009 10:30:34 -0500 Subject: Surpressing Warnings In-Reply-To: References: <4dc0cfea0908091321y54156d30sc0c4dc3a564eecab@mail.gmail.com> Message-ID: <4dc0cfea0908160830n33c4e511t7aa1662884596885@mail.gmail.com> This is strange because I actually had "if exists" in my code: sqlKWDrop = 'DROP TABLE IF EXISTS ' + kwTable + ';' where kwTable, in the instance cited below, becomes "judaism_128". What gives? Victor On Sun, Aug 9, 2009 at 7:57 PM, Dennis Lee Bieber wrote: > On Sun, 9 Aug 2009 15:21:43 -0500, Victor Subervi > declaimed the following in > gmane.comp.python.general: > > > Hi: > > I get a ton of warnings like this from a program I run: > > > > Warning (from warnings module): > > File "C:\Python25\read.py", line 67 > > cursor.execute(sqlKWDrop) > > Warning: Unknown table 'judaism_128' > > > Personally -- I'd suggest fixing the database so that the table > does > exist... > > Ah, but then -- it appears from the name, that the purpose of this > SQL statement is to delete the table... In which case use a database > that supports (for example, current versions of MySQL, SQLite, and > PostgreSQL) "drop table IF EXISTS tbl_name" which suppress the > warning/error message and update the SQL as appropriate. > > Appears that M$ SQL Server does NOT implement that syntax... Nor > could I find it for Firebird. > > If the application is specific for one database engine, it might be > worth it to find out what features permit discovering if a table exists > and bypassing the drop if it doesn't... > > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Sun Aug 16 11:41:21 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 16 Aug 2009 11:41:21 -0400 Subject: Python 'for' loop is memory inefficient In-Reply-To: <200908160830.55031.emmanuel.surleau@gmail.com> References: <24980842.post@talk.nabble.com> <4A8612CE.7080700@stoneleaf.us> <200908160830.55031.emmanuel.surleau@gmail.com> Message-ID: On Sun, Aug 16, 2009 at 2:30 AM, Emmanuel Surleau wrote: > > I don't see what's particularly un-Pythonic with this code. Not using xrange() > is a mistake, certainly, but it remains clear, easily understandable code > which correctly demonstrates the naive algorithm for detecting whether n is a > prime. It doesn't call for condescension It's not that the code is bad, but too many people coming from Java and C keep thinking of for loops like they're using Java or C and therefore that "for i in range(a,b)" is identical to "for(int i = a; i < b; i++)". It's not and, for the most part, you shouldn't code like that. Since you're using numbers, range/xrange is the appropriate idiom but you still have to remember that a for loop in python doesn't loop until a condition is met, it loops through an iterator until the interator says it's done. From psilord at merlin.cs.wisc.edu Sun Aug 16 12:05:01 2009 From: psilord at merlin.cs.wisc.edu (Peter Keller) Date: 16 Aug 2009 16:05:01 GMT Subject: Xah's Edu Corner: The importance of syntax & notations. References: Message-ID: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> In comp.lang.scheme Xah Lee wrote: > Xah's Edu Corner: The importance of syntax & notations. > > http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstract.html > > this article should teach the coding sophomorons and computer > ?science? idiotic authors who harbor the notion that syntax is not > important, picked up by all the elite i-reddit & twittering & hacker > news am-hip dunces. I must have really tweaked you with my "Syntax is not important, ideas are." statement. I read Wolfram's article carefully. He applies an intuitive sense onto why he does or doesn't like a particular notation, but yet can't really elucidate his feelings. I'm surprised that didn't tweak you worse. He also goes so far as to mention that: "But actually we still don't know a clean simple way to represent things like geometrical diagrams in a kind of language-like notation. And my guess is that actually of all the math-like stuff out there, only a comparatively small fraction can actually be represented well with language-like notation." It is simply that the method by which the right brain categorizes and processes visual information is not observable by the left brain. Therefore no language can EVER be constructed by the left brain to represent why the right brain "prefers" some visual layouts for languages over others. I've done enough classical art training in my life to understand the conflict between the powerful spatial/visual processor the right brain has and the (in the context of drawing) meaningless linguistics of trying to describe the process. Only when we as human beings build the observation channels needed (with physical connection between certain areas of the left and right sides of the brain) will any sort of meaningful left brain language be created for the visual understanding/gradation of the spatial relationship and the method by which our right brain performs its processing. If you want to design a better computer language, hire an artist. Most semantic objects in programs stand in some spatio-temporal relation to each other. If you deny that fact, then simply look at the directed acyclic form/SSA form/CPS transform of any of your favorite languages. Compiler go through *great* pains to transform left brain scribblings into large spatio-temporal "2d images" where lots of algorithms are done before converting them into assembly. This is because it is simply easier to visually understand how to do the processing of those elements than not. Thank you. -pete From jcm1981 at gmail.com Sun Aug 16 12:17:42 2009 From: jcm1981 at gmail.com (Chang Min Jeon) Date: Mon, 17 Aug 2009 01:17:42 +0900 Subject: my recursive function call is wrong? In-Reply-To: References: <22a413260908160057t2802d3cci70658278e7322eb8@mail.gmail.com> Message-ID: <22a413260908160917j46b93717hd57889ce26feae6d@mail.gmail.com> Dear Kev Thank you very much. I got it.:) 2009/8/16 Kev Dwyer > On Sun, 16 Aug 2009 16:57:41 +0900, Chang Min Jeon wrote: > > > Hello, > > You have placed recursive calls to the function in a number of different > locations; when len(macro) becomes zero control will return to the > calling function, but this calling function may have more code to > execute, including further calls to start_parse(), and further attempts > to index macro. > > I like to keep recursive calls at the end of a function, so that there is > a clean path back to the top level caller once the terminal condition is > reached. You can do it differently, but you need to bear in mind the > execution paths through your code. > > Cheers, > > Kev > > -- > http://mail.python.org/mailman/listinfo/python-list > -- CashFlow To be rich. -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at subsignal.org Sun Aug 16 12:30:48 2009 From: paul at subsignal.org (paul) Date: Sun, 16 Aug 2009 18:30:48 +0200 Subject: Python or ActionScript 3.0 In-Reply-To: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> References: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> Message-ID: Jaseem schrieb: > Hi, > > Is python similar to actionscript 3.0 Not really. > Which is better to create a rich gui internet application? > Is it AS 3.0 with flex or python with its GUI libs? Flex+AS3 definitely! (it's been designed for that, no surprise here) > > Is python in demand? Depends. It seems quite popular in the scientific community and for system administration these days. > Heard that python is similar to lisp. But both python and AS 3.0 is > almost identical. Which is more similar to lisp are powerful? If python is 100m away from lisp, than it's 102.32m for AS3. cheers Paul > > Thank You. From python at rcn.com Sun Aug 16 12:33:59 2009 From: python at rcn.com (Raymond Hettinger) Date: Sun, 16 Aug 2009 09:33:59 -0700 (PDT) Subject: What happened to __cmp__() in Python 3.x? References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> Message-ID: <561aa2a7-2cf8-4c30-b9a7-e22ad64655b5@g31g2000yqc.googlegroups.com> [Xavier Ho] > > I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in the > > documentation. > > > Is there a substitution for this special method in 3.1, or do I really have > > to define all six rich comparison methods to work it out? FWIW, there is a recipe for expanding the comparison operators: http://code.activestate.com/recipes/576685/ Raymond From jasevv at gmail.com Sun Aug 16 12:39:49 2009 From: jasevv at gmail.com (Jaseem) Date: Sun, 16 Aug 2009 09:39:49 -0700 (PDT) Subject: Python or ActionScript 3.0 References: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> Message-ID: <4a889173-f1bf-4661-ae1d-4b0c23c4d586@r18g2000yqd.googlegroups.com> On Aug 16, 9:30?pm, paul wrote: > Jaseem schrieb:> Hi, > > > Is python similar to actionscript 3.0 > > Not really. > > > Which is better to create a rich gui internet application? > > Is it AS 3.0 with flex or python with its GUI libs? > > Flex+AS3 definitely! (it's been designed for that, no surprise here) > > > > > Is python in demand? > > Depends. It seems quite popular in the scientific community and for > system administration these days. > > > Heard that python is similar to lisp. But both python and AS 3.0 is > > almost identical. Which is more similar to lisp are powerful? > > If python is 100m away from lisp, than it's 102.32m for AS3. > > cheers > ? Paul > > > > > Thank You. > > Alright! From Scott.Daniels at Acm.Org Sun Aug 16 12:40:57 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 16 Aug 2009 09:40:57 -0700 Subject: flatten a list of list In-Reply-To: <0297dd0f$0$20634$c3e8da3@news.astraweb.com> References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297dd0f$0$20634$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sun, 16 Aug 2009 02:47:42 -0700, Terry wrote: >> Is there a simple way (the pythonic way) to flatten a list of list? > Chris' suggestion using itertools seems pretty good: > >>>> from timeit import Timer >>>> setup = """\\ > ... L = [ [None]*5000 for _ in xrange(%d) ] > ... from itertools import chain > ... """ >>>> Timer("list(chain.from_iterable(L))", setup % 4).repeat(number=1000) > [0.61839914321899414, 0.61799716949462891, 0.62065696716308594] >>>> Timer("list(chain.from_iterable(L))", setup % 8).repeat(number=1000) > [1.2618398666381836, 1.3385050296783447, 3.9113419055938721] >>>> Timer("list(chain.from_iterable(L))", setup % 16).repeat(number=1000) > [3.1349358558654785, 4.8554730415344238, 5.4319999217987061] OK, it definitely helps to get a size estimate before building: >>> setup = """\\ L = [ [None]*5000 for _ in xrange(%d) ] import itertools class Holder(object): def __init__(self, list_of_lists): self._list = list_of_lists def __iter__(self): return itertools.chain.from_iterable(self._list) def __len__(self): return sum(len(x) for x in self._list) """ >>> timeit.Timer("list(Holder(L))", setup % 4).repeat(number=1000) [0.59912279353940789, 0.59505886921382967, 0.59474989139681611] >>> timeit.Timer("list(Holder(L))", setup % 8).repeat(number=1000) [1.1898235669617208, 1.194797383466323, 1.1945367358141823] >>> timeit.Timer("list(Holder(L))", setup % 16).repeat(number=1000) [2.4244464031043123, 2.4261885239604482, 2.4050011942858589] vs straight chain.from_iterable (on my machine): [0.7828263089303249, 0.79326171343005925, 0.80967664884783019] [1.499510971366476, 1.5263249938190455, 1.5599706107899181] [3.4427520816193109, 3.632409426337702, 3.5290488036887382] --Scott David Daniels Scott.Daniels at Acm.Org From no.email at please.post Sun Aug 16 13:09:32 2009 From: no.email at please.post (kj) Date: Sun, 16 Aug 2009 17:09:32 +0000 (UTC) Subject: Splitting on '^' ? References: Message-ID: In rurpy at yahoo.com writes: >On Aug 14, 2:23=A0pm, kj wrote: >> Sometimes I want to split a string into lines, preserving the >> end-of-line markers. =A0In Perl this is really easy to do, by splitting >> on the beginning-of-line anchor: >> >> =A0 @lines =3D split /^/, $string; >> >> But I can't figure out how to do the same thing with Python. =A0E.g.: >Why not this? >>>> lines =3D 'spam\nham\neggs\n'.splitlines (True) >>>> lines >['spam\n', 'ham\n', 'eggs\n'] That's perfect. And .splitlines seems to be able to handle all "standard" end-of-line markers without any special direction (which, ironically, strikes me as a *little* Perlish, somehow): >>> "spam\015\012ham\015eggs\012".splitlines(True) ['spam\r\n', 'ham\r', 'eggs\n'] Amazing. I'm not sure this is the *best* way to do this in general (I would have preferred it, and IMHO it would have been more Pythonic, if .splitlines accepted an additional optional argument where one could specify the end-of-line sequence to be used for the splitting, defaulting to the OS's conventional sequence, and then it split *strictly* on that sequence). But for now this .splitlines will do nicely. Thanks! kynn From bettini at dsi.unifi.it Sun Aug 16 13:12:11 2009 From: bettini at dsi.unifi.it (Lorenzo Bettini) Date: Sun, 16 Aug 2009 19:12:11 +0200 Subject: Komodo(!) In-Reply-To: References: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> <553649.43098.qm@web110605.mail.gq1.yahoo.com> Message-ID: <4a883df4@news.x-privat.org> Kee Nethery wrote: > I've heard there is a nice add-on to Eclipse but Eclipse has even more > setup variables than Wings and I've avoided it for that reason. > Hi I've just started using python and since I've been an eclipse user for many years I tried http://pydev.sourceforge.net/ and I really enjoyed that! :-) cheers Lorenzo -- Lorenzo Bettini, PhD in Computer Science, DI, Univ. Torino ICQ# lbetto, 16080134 (GNU/Linux User # 158233) HOME: http://www.lorenzobettini.it MUSIC: http://www.purplesucker.com http://www.myspace.com/supertrouperabba BLOGS: http://tronprog.blogspot.com http://longlivemusic.blogspot.com http://www.gnu.org/software/src-highlite http://www.gnu.org/software/gengetopt http://www.gnu.org/software/gengen http://doublecpp.sourceforge.net From bieffe62 at gmail.com Sun Aug 16 13:12:29 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Sun, 16 Aug 2009 10:12:29 -0700 (PDT) Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297dd0f$0$20634$c3e8da3@news.astraweb.com> Message-ID: <65abe4e8-dd82-47f9-b851-028babbcc247@c29g2000yqd.googlegroups.com> On Aug 16, 1:25?pm, Steven D'Aprano wrote: ... > Chris' suggestion using itertools seems pretty good: > > >>> from timeit import Timer > >>> setup = """\\ > > ... L = [ [None]*5000 for _ in xrange(%d) ] > ... from itertools import chain > ... """>>> Timer("list(chain.from_iterable(L))", setup % 4).repeat(number=1000) > > [0.61839914321899414, 0.61799716949462891, 0.62065696716308594]>>> Timer("list(chain.from_iterable(L))", setup % 8).repeat(number=1000) > > [1.2618398666381836, 1.3385050296783447, 3.9113419055938721]>>> Timer("list(chain.from_iterable(L))", setup % 16).repeat(number=1000) > > [3.1349358558654785, 4.8554730415344238, 5.4319999217987061] > > -- > Steven I had a peek at itertools ( which is a C module btw) and realized that chain solves the problem by creating a chain object, which is a sort of generator. Both creating the chain object and converting the chain object to a list seem to be O(N), so the whole is O(N) too ... Then I tried this pure python version: # ----- CODE from timeit import Timer setup = """\\ L = [ [None]*5000 for _ in range(%d) ] def pychain( list_of_list ): for l in list_of_list: for elem in l: yield elem """ print( Timer("list(pychain(L))", setup % 4).repeat(number=1000)) print( Timer("list(pychain(L))", setup % 8).repeat(number=1000)) print( Timer("list(pychain(L))", setup % 16).repeat(number=1000)) # ----- END CODE and got times that seem to confirm it : [2.818755865097046, 2.7880589962005615, 2.79232120513916] [5.588631868362427, 5.588244915008545, 5.587780952453613] [11.620548009872437, 11.39465618133545, 11.40834903717041] For reference, here are the times of the itertools.chain solution on my laptop: [0.6518809795379639, 0.6491332054138184, 0.6483590602874756] [1.3188841342926025, 1.3173959255218506, 1.3207998275756836] [2.7200729846954346, 2.5402050018310547, 2.543621063232422] All this with Python 3.1 compiled from source on Xubuntu 8.10. Ciao ----- FB From martin at v.loewis.de Sun Aug 16 13:22:52 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 16 Aug 2009 19:22:52 +0200 Subject: Python 2.6 still not giving memory back to the OS... In-Reply-To: <762603ba-0a4c-4504-94d9-34a8b1e3f9c3@s15g2000yqs.googlegroups.com> References: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> <762603ba-0a4c-4504-94d9-34a8b1e3f9c3@s15g2000yqs.googlegroups.com> Message-ID: <4A88406C.3060609@v.loewis.de> > As far as releasing memory back to the OS is concerned, I have dim > memories of *x systems where free() would return space to the OS if > the block was "large" and it was next to the "break" point ... this > effect could be what you are seeing. Today, there are two cases when malloc returns memory on a typical Unix system (in particular, in Linux malloc): a) if the malloc block block is small (below page size), it is allocated from the brk heap, where it can only be returned if the last page of that heap is completely free, and b) if the block is large (multiple pages), it gets returned to the system right away. Case b) can only happen if the C malloc uses mmap to allocate large blocks. For Python, case b) is realistic, in the sense that most allocations go to Python's obmalloc, and those allocate from C malloc in chunks of 256kiB (IIRC). So when such an arena is completely free (not a single Python object allocated on it anymore), it can get returned to the system. In some case, Python also allocates smaller blocks from C malloc; in this case, a) will trigger. So as long as something at the end of the heap stays allocated, C malloc will not return anything from the brk heap to the system. Regards, Martin From alan.isaac at gmail.com Sun Aug 16 13:37:04 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Sun, 16 Aug 2009 17:37:04 GMT Subject: flatten a list of list In-Reply-To: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <4A8843BF.1060203@gmail.com> On 8/16/2009 5:47 AM Terry apparently wrote: > Is there a simple way (the pythonic way) to flatten a list of list? > rather than my current solution: > new_list=[] > for l in list_of_list: > new_list.extend(l) new_list = list(xi for lst in list_of_list for xi in lst) hth, Alan Isaac From http Sun Aug 16 13:40:41 2009 From: http (Paul Rubin) Date: 16 Aug 2009 10:40:41 -0700 Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <7xocqfzmg6.fsf@ruckus.brouhaha.com> Terry writes: > Is there a simple way (the pythonic way) to flatten a list of list? > rather than my current solution: > > new_list=[] > for l in list_of_list: > new_list.extend(l) from itertools import chain new_list = list(chain(list_of_list)) From darkwater42 at gmail.com Sun Aug 16 13:46:37 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sun, 16 Aug 2009 10:46:37 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <34dd6e0e-3b47-4761-ad7a-9038b0d36209@v36g2000yqv.googlegroups.com> Message-ID: On Aug 16, 8:45?am, MRAB wrote: > No, APL is strictly right-to-left. > > ? ? ?-> x > > means "goto x". > > Writing to the console is: > > ? ? ?[] <- myVar > > Reading from the console is: > > ? ? ?myVar <- [] Ah, thanks for the correction. It's been 5,000 years since I used APL! |>ouglas From w_a_x_man at yahoo.com Sun Aug 16 14:03:18 2009 From: w_a_x_man at yahoo.com (w_a_x_man) Date: Sun, 16 Aug 2009 11:03:18 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> Message-ID: <5031edcc-c63e-4a3b-9f12-caba0cc34e92@r18g2000yqd.googlegroups.com> On Aug 16, 11:05?am, Petey Keller wrote: > Compiler go through *great* pains Compiler work real hard. Compiler have heap big trouble. From sajmikins at gmail.com Sun Aug 16 14:33:30 2009 From: sajmikins at gmail.com (Simon Forman) Date: Sun, 16 Aug 2009 14:33:30 -0400 Subject: problem with interface of operator.itemgetter In-Reply-To: <19b355330908132016y49f2679u631c3123fcfc920a@mail.gmail.com> References: <19b355330908132016y49f2679u631c3123fcfc920a@mail.gmail.com> Message-ID: <50f98a4c0908161133hd7587chf7368ab0014dabb2@mail.gmail.com> On Thu, Aug 13, 2009 at 11:16 PM, dou dou wrote: > I have a function to do some thing like LEFT JOIN in SQL, the function use > the itemgetter to get the "ON" and "SELECT" parameters of the two table(list > of list), the problem is that itemgetter may return a value or a tuple of > values, because of the inconsistent return type of itemgetter, I have to do > 2^3 IF check, > the function like this: > > def left_join(table1, on_index1, table2, on_index2, getter1, getter2): > ??? """do thing like: > ??? SELECT on1(table1), g1(table1), g2(table2) FROM table1 > ??? LEFT JOIN table2 > ??? ON on1(table1) == on2(table2) > ??? """ > ??? on1 = itemgetter(*on_index1) > ??? on2 = itemgetter(*on_index2) > ??? g1 = itemgetter(*getter1) > ??? g2 = itemgetter(*getter2) > > ??? d2 = {} > ??? d2 = dict((on2(r2), r2) for r2 in table2) > > ??? #if itemgetter always return tuple, below could simple as one line > ??? #return [ list(on1(r1) + g1(r1) + g2(d2.get(on1(r1)))) for r1 in table1 > ] > > ??? len_on = len(on_index1) > ??? len_g1 = len(getter1) > ??? len_g2 = len(getter2) > > ??? if len_on == 1: > ??????? if len_g1 == 1 and len_g2 == 1: > ??????????? return [ [on1(r1), g1(r1), g2(d2.get(on1(r1)))] for r1 in table1 > ] > ??????? elif len_g1 == 1 and len_g2 > 1: > ??????????? return [ list((on1(r1),g1(r1))+g2(d2.get(on1(r1)))) for r1 in > table1 ] > ??????? elif len_g1 > 1 and len_g2 == 1: > ??????????? return [ list((on1(r1),)+g1(r1)+(g2(d2.get(on1(r1))),))? for r1 > in table1 ] > ??????? else: #len_g1 > 1 and len_g2 > 1: > ??????????? return [ list((on1(r1),)+g1(r1)+g2(d2.get(on1(r1)))) for r1 in > table1 ] > ??? else: # len_on > 1 > ??????? if len_g1 == 1 and len_g2 == 1: > ??????????? return [ list(on1(r1))+[g1(r1),g2(d2.get(on1(r1)))] for r1 in > table1 ] > ??????? elif len_g1 == 1 and len_g2 > 1: > ??????????? return [ list(on1(r1)+(g1(r1),)+g2(d2.get(on1(r1)))) for r1 in > table1 ] > ??????? elif len_g1 > 1 and len_g2 == 1: > ??????????? return [ list(on1(r1)+g1(r1)+(g2(d2.get(on1(r1))),))? for r1 in > table1 ] > ??????? else: #len_g1 > 1 and len_g2 > 1: > ??????????? return [ list(on1(r1)+g1(r1)+g2(d2.get(on1(r1)))) for r1 in > table1 ] > > so is there a way to force itemgetter to return tuple even when > itemgetter(only_have_one_argument)? or some other function to do this? > > Thanks. > You can use a little helper function to create your itemgetter like this: def makeItemGetter(indexes): I = itemgetter(*indexes) if len(indexes) > 1: return I return lambda thing: (I(thing),) If indexes contains only one index the itemgetter is wrapped in a lambda that turns its output into a tuple. HTH, ~Simon From gallium.arsenide at gmail.com Sun Aug 16 14:35:52 2009 From: gallium.arsenide at gmail.com (John Yeung) Date: Sun, 16 Aug 2009 11:35:52 -0700 (PDT) Subject: Splitting on '^' ? References: Message-ID: <96ac83a3-adaf-4d22-ad9c-048a99b46927@o13g2000vbl.googlegroups.com> On Aug 16, 1:09?pm, kj wrote: > And .splitlines seems to be able to handle all > "standard" end-of-line markers without any special > direction (which, ironically, strikes > me as a *little* Perlish, somehow): It's Pythonic. Universal newline-handling for text has been a staple of Python for as long as I can remember (very possibly since the very beginning). > >>> "spam\015\012ham\015eggs\012".splitlines(True) > > ['spam\r\n', 'ham\r', 'eggs\n'] > > Amazing. ?I'm not sure this is the *best* way to do > this in general (I would have preferred it, and IMHO > it would have been more Pythonic, if .splitlines > accepted an additional optional argument [...]). I believe it's the best way. When you can use a string method instead of a regex, it's definitely most Pythonic to use the string method. I would argue that this particular string method is Pythonic in design. Remember, Python strives not only for explicitness, but simplicity and ease of use. When dealing with text, universal newlines are much more often than not simpler and easier for the programmer. John From bartc at freeuk.com Sun Aug 16 14:45:27 2009 From: bartc at freeuk.com (bartc) Date: Sun, 16 Aug 2009 18:45:27 GMT Subject: Python 'for' loop is memory inefficient In-Reply-To: <02969972$0$20647$c3e8da3@news.astraweb.com> References: <02969972$0$20647$c3e8da3@news.astraweb.com> Message-ID: "Steven D'Aprano" wrote in message news:02969972$0$20647$c3e8da3 at news.astraweb.com... > On Fri, 14 Aug 2009 18:25:45 -0700, Dr. Phillip M. Feldman wrote: > >> It seems as though Python is actually expanding range(2,n) into a list >> of numbers, even though this is incredibly wasteful of memory. There >> should be a looping mechanism that generates the index variable values >> incrementally as they are needed. > > > Others have already pointed out to you that xrange() (for Python 2.x) > does what you want. In Python 3.x, the old range() is gone for good, and > xrange() renamed to just range(). It does seem rather worrying that whoever originally thought up Python decided it would be a good idea to implement a simple 1 to N (or 0 to N-1) for-loop by first creating an array of N consecutive integers! They must have known Python was going to be slow anyway, but this wouldn't have helped the speed any. Nor the memory consumption. A for-loop, for iterating over a simple sequence, should be one of the fastest things in the language. [Presumably the internal code that created those consecutive integers used a more conventional looping method...] -- Bartc From apt.shansen at gmail.com Sun Aug 16 14:50:09 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 16 Aug 2009 11:50:09 -0700 Subject: Splitting on '^' ? In-Reply-To: References: Message-ID: <7a9c25c20908161150ma1267b9xecc86a222312c0af@mail.gmail.com> And .splitlines seems to be able to handle all "standard" end-of-line > markers without any special direction (which, ironically, strikes > me as a *little* Perlish, somehow): > > >>> "spam\015\012ham\015eggs\012".splitlines(True) > ['spam\r\n', 'ham\r', 'eggs\n'] > ... actually "working correctly" and robustly is "perlish"? :) The only reason I've ever actually used this method is this very feature of it, that you can't readily reproduce with other methods unless you start getting into regular expressions (and I really believe regular expressions should not be the default place one looks to solve a problem in Python) Then again, as soon as Python started allowing you to open files with mode "rU", I gleefully ran through my codebase and changed every operation to that and made sure to write out with platform-local newlines exclusively, thus finally flipping off those darn files that users kept producing with mixed line endings. > Amazing. I'm not sure this is the *best* way to do this in general > (I would have preferred it, and IMHO it would have been more > Pythonic, if .splitlines accepted an additional optional argument > where one could specify the end-of-line sequence to be used for > the splitting, defaulting to the OS's conventional sequence, and > then it split *strictly* on that sequence). > If you want strict and absolute splitting, you don't need another method; just do mystring.split(os.linesep); I mean sure, it doesn't have the 'keepends' feature -- but I don't actually understand why you want keepends with a strict definition of endings... If you /only/ want to split on \n, you know there's an \n on the end of each line in the returned list and can easily be sure to write it out (for example) :) In the modern world of mixed systems and the internet, and files being flung around willy-nilly, and editors being configured to varying degrees of correctness, and such.... It's Pythonic to be able to handle all these files that anyone made on any system and treat them as they are clearly *meant* to be treated. Since the intention *is* clear that these are all *end of line* markers-- it's explicitly stated, just slightly differently depending on the OS-- Python treats all of the line-endings as equal on read if you want it to. By using either str.splitlines() or opening a text file as "rU". Thank goodness for that :) In some cases you may need a more pedantic approach to line endings. In that case, just use str.split() :) --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sun Aug 16 14:53:08 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 16 Aug 2009 14:53:08 -0400 Subject: random.gauss vs. random.normalvariate In-Reply-To: References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> Message-ID: <4A885594.1080703@ieee.org> John Haggerty wrote: > On Sat, Aug 15, 2009 at 7:23 PM, Dennis Lee Bieber wrote: > > >> On Sat, 15 Aug 2009 14:34:36 -0600, John Haggerty >> declaimed the following in gmane.comp.python.general: >> >> >>> What does the term "thread safe" mean exactly. I never had to program >>> >> with >> >>> "threads" before >>> >> That, part way through the logic of the function, control could be >> switched to a different thread which call the same function... This >> second call would change some of the internal values and may then be >> preempted and control returned to the first thread, which continues the >> rest of the function with different values then it had when first >> preempted. >> >> A very contrived example, untested of course, consider it >> pseudo-code... >> >> startt = None >> >> def atimer(): >> global startt >> startt = time.time() >> time.sleep(5) >> print time.time() - startt >> >> t1 = threading.thread(atimer) >> t2 = threading.thread(atimer) >> t1.start() >> t2.start() >> >> Say t1 gets all the way up to the sleep call, and (since sleep is a >> releasing call), t2 then starts. t2 changes the value of startt; and >> sleeps... both sleep and presuming the resolution is fine enough, t1 >> resumes, and prints a delta time that is incorrect -- it is printing >> the time difference from when t2 started to sleep, not from when t1 >> started to sleep. >> -- >> Wulfraed Dennis Lee Bieber KD6MOG >> wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > Interesting so it seems that the compiler(c/c++)interpreter(perl, > python)/vm(java) doesn't do this? > > It is impossible for a language, vm, or operating system to avoid threading problems without the programmer's help, except by trivial means (eg. preventing you from having them at all). The power of threading is entirely tied up with the features the environment gives to the developer, and those features come with a risk. At one extreme is the CP/M model. You start a new program only when you finish the previous one. So the only communication between them is a file the first one leaves behind, that the second can look at. Next is separate processes. If you launch a second process, by default, they're independent, and not likely to get into trouble. But you can build pipes or shared memory, or sockets between them, and then you have to worry about race conditions. Next is threads, within a single process. At this point, you can share (global) variables between them, or you can have objects known to both when the thread is launched. The system cannot tell which ones are deliberate and which ones are accidental. So a language might give extra keywords to tell the compiler that certain things should be protected in certain ways. Or it might give a way to declare a "per-thread global" that acts like a global to each thread, but is actually two independent variables from the process point of view. The only real reason threads are singled out is it's easier to collide by mistake. But that's also what makes it efficient to "collide" on purpose. DaveA From darkwater42 at gmail.com Sun Aug 16 14:55:31 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sun, 16 Aug 2009 11:55:31 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <0297b230$0$20634$c3e8da3@news.astraweb.com> <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> <0297cd31$0$20634$c3e8da3@news.astraweb.com> Message-ID: <0ee729c3-22f0-450c-8fba-39ae74f7535d@d4g2000vbm.googlegroups.com> On Aug 16, 6:18?am, Steven D'Aprano wrote: > On Sun, 16 Aug 2009 01:41:41 -0700, Douglas Alan wrote: > > I would definitely not like a language that obscures assignment by > > moving it over to the right side of lines. > One could argue that left-assigned-from-right assignment obscures the > most important part of the assignment, namely *what* you're assigning, in > favour of what you're assigning *to*. The most important things are always the side-effects and the name- bindings. In a large program, it can be difficult to figure out where a name is defined, or which version of a name a particular line of code is seeing. Consequently languages should always go out of their way to make tracking this as easy as possible. Side effects are also a huge issue, and a source of many bugs. This is one of the reasons that that are many functional languages that prohibit or discourage side-effects. Side effects should be made as obvious as is feasible. This is why, for instance, in Scheme, variable assignment as an exclamation mark in it. E.g., (set! x (+ x 1)) The exclamation mark is to make the fact that a side effect is happening there stand out and be immediately apparent. And C++ provides the "const" declaration for similar reasons. > In any case, after half a century of left-from-right assignment, I think > it's worth the experiment in a teaching language or three to try it the > other way. The closest to this I know of is the family of languages > derived from Apple's Hypertalk, where you do assignment with: > > put somevalue into name That's okay with me, but only because the statement begins with "put", which lets you know at the very beginning of the line that something very important is happening. You don't have to scan all the way to the right before you notice. Still, I would prefer let name = somevalue as the "let" gives me the heads up right away, and then immediately after the "let" is the name that I might want to be able to scan for quickly. |>ouglas From psilord at merlin.cs.wisc.edu Sun Aug 16 15:17:02 2009 From: psilord at merlin.cs.wisc.edu (Peter Keller) Date: 16 Aug 2009 19:17:02 GMT Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> <5031edcc-c63e-4a3b-9f12-caba0cc34e92@r18g2000yqd.googlegroups.com> Message-ID: <4a885b2e$0$9897$80265adb@spool.cs.wisc.edu> In comp.lang.scheme w_a_x_man wrote: > On Aug 16, 11:05?am, Petey Keller wrote: >> Compiler go through *great* pains > > Compiler work real hard. > Compiler have heap big trouble. That's a funny observation in the context of this thread--which I appreciate, since syntax really is the cornerstone of meaning transferal between people. The unintended connotation brought in by what I mistakenly wrote underscores the value of syntax. However, what we don't have is a means of measuring the effectiveness and/or efficiency of expressing meaning for an arbitrary set of syntax rules. Computer Scientists can do this somewhat in that the expressive power of parsing is greater than regular expressions and both can use a syntax to represent them. But in a single complexity class, the "black art" of how to place a metric on a syntax is, at least at this time, relegated to the right brain and how it visually sees (and visually parses) the syntax and how our emotions relate to the syntax. The wolfram article, in fact, never does mention any metric other than "this is hard to understand, this is less hard to understand". In a sense, how is that useful at all? Instead of really trying to find a method by which understanding can be placed upon a metric (or discovering a method *can not* be found, he seems to anecdotally ascribe understanding difficulty upon various syntaxs. The real frustrations of Xah Lee might be explained by his denial of the right brain processing of syntax information. It is to be expected since most industrial cultures suppress right brain advancement (emotional understanding/social interaction, drawing, music, spatial relations) in lieu of left brain processing (language and syntax, symbolic manipulation (part, though not all of the skill set of math), object naming). In fact, his skills of communicating his ideas in a social setting which, in my opinion, are poor and stunted, is a red flag and the epitome of this type of cultural viewpoint. Thank you. -pete From sajmikins at gmail.com Sun Aug 16 15:36:20 2009 From: sajmikins at gmail.com (Simon Forman) Date: Sun, 16 Aug 2009 12:36:20 -0700 (PDT) Subject: Splitting a string into substrings of equal size References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: On Aug 14, 8:22?pm, candide wrote: > Suppose you need to split a string into substrings of a given size (except > possibly the last substring). I make the hypothesis the first slice is at the > end of the string. > A typical example is provided by formatting a decimal string with thousands > separator. > > What is the pythonic way to do this ? > > For my part, i reach to this rather complicated code: > > # ---------------------- > > def comaSep(z,k=3, sep=','): > ? ? z=z[::-1] > ? ? x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] > ? ? return sep.join(x) > > # Test > for z in ["75096042068045", "509", "12024", "7", "2009"]: > ? ? print z+" --> ", comaSep(z) > > # ---------------------- > > outputting : > > 75096042068045 --> ?75,096,042,068,045 > 509 --> ?509 > 12024 --> ?12,024 > 7 --> ?7 > 2009 --> ?2,009 > > Thanks FWIW: def chunks(s, length=3): stop = len(s) start = stop - length while start > 0: yield s[start:stop] stop, start = start, start - length yield s[:stop] s = '1234567890' print ','.join(reversed(list(chunks(s)))) # prints '1,234,567,890' From python at mrabarnett.plus.com Sun Aug 16 16:00:27 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 16 Aug 2009 21:00:27 +0100 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <02969972$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A88655B.2070108@mrabarnett.plus.com> bartc wrote: > > "Steven D'Aprano" wrote in > message news:02969972$0$20647$c3e8da3 at news.astraweb.com... >> On Fri, 14 Aug 2009 18:25:45 -0700, Dr. Phillip M. Feldman wrote: >> >>> It seems as though Python is actually expanding range(2,n) into a list >>> of numbers, even though this is incredibly wasteful of memory. There >>> should be a looping mechanism that generates the index variable values >>> incrementally as they are needed. >> >> >> Others have already pointed out to you that xrange() (for Python 2.x) >> does what you want. In Python 3.x, the old range() is gone for good, and >> xrange() renamed to just range(). > > It does seem rather worrying that whoever originally thought up Python > decided it would be a good idea to implement a simple 1 to N (or 0 to > N-1) for-loop by first creating an array of N consecutive integers! > Whoever? I am shocked! ;-) > They must have known Python was going to be slow anyway, but this > wouldn't have helped the speed any. Nor the memory consumption. > > A for-loop, for iterating over a simple sequence, should be one of the > fastest things in the language. > > [Presumably the internal code that created those consecutive integers > used a more conventional looping method...] > From shailen.tuli at gmail.com Sun Aug 16 16:13:32 2009 From: shailen.tuli at gmail.com (Shailen) Date: Sun, 16 Aug 2009 13:13:32 -0700 (PDT) Subject: zip codes Message-ID: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> Is there any Python module that helps with US and foreign zip-code lookups? I'm thinking of something that provides basic mappings of zip to cities, city to zips, etc. Since this kind of information is so often used for basic user-registration, I'm assuming functionality of this sort must be available for Python. Any suggestions will be much appreciated. - Shailen Tuli From no.email at please.post Sun Aug 16 16:29:15 2009 From: no.email at please.post (kj) Date: Sun, 16 Aug 2009 20:29:15 +0000 (UTC) Subject: XPath support? Message-ID: I'm looking for a XML parser that produces an object with full XPath support. What I've been using up to now, xml.etree.ElementTree, fails to support Xpath predicates, as in "spam[@eggs='3']/ham". What I'm trying to do is to read-in a large XML string, and parse it into an object from which I can extract nodes matching selectors that include such predicates. Any suggestions would be greatly appreciated. TIA! kynn From deets at nospam.web.de Sun Aug 16 16:31:24 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 16 Aug 2009 22:31:24 +0200 Subject: XPath support? In-Reply-To: References: Message-ID: <7er8ksF2hmnmqU1@mid.uni-berlin.de> kj schrieb: > I'm looking for a XML parser that produces an object with full > XPath support. What I've been using up to now, xml.etree.ElementTree, > fails to support Xpath predicates, as in "spam[@eggs='3']/ham". > > What I'm trying to do is to read-in a large XML string, and parse > it into an object from which I can extract nodes matching selectors > that include such predicates. > > Any suggestions would be greatly appreciated. Try lxml. It's element-tree compatible, and supports xpath. Diez From kevin.p.dwyer at gmail.com Sun Aug 16 16:37:16 2009 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Sun, 16 Aug 2009 20:37:16 +0000 (UTC) Subject: XPath support? References: Message-ID: On Sun, 16 Aug 2009 20:29:15 +0000, kj wrote: > I'm looking for a XML parser that produces an object with full XPath > support. What I've been using up to now, xml.etree.ElementTree, fails > to support Xpath predicates, as in "spam[@eggs='3']/ham". > > What I'm trying to do is to read-in a large XML string, and parse it > into an object from which I can extract nodes matching selectors that > include such predicates. > > Any suggestions would be greatly appreciated. > > TIA! > > kynn Have you tried lxml (http://codespeak.net/lxml/)? Kev From sturlamolden at yahoo.no Sun Aug 16 16:41:07 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Aug 2009 13:41:07 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> Message-ID: On 16 Aug, 11:45, "bartc" wrote: > A for-loop, for iterating over a simple sequence, should be one of the > fastest things in the language. Anyone experienced with interpreted high-level languages knows this is not true. Not because iterating a sequence is expensive, but because the interpreter is constantly executing the body of the loop. There is a reason why Matlab and Python/NumPy programmers rely heavily on vectorized array expressions for efficient numerics. The only thing more evil than a for-loop is recursive function calls. This does not mean Python is slow. It just means you have to program differently. From http Sun Aug 16 16:42:56 2009 From: http (Paul Rubin) Date: 16 Aug 2009 13:42:56 -0700 Subject: random.gauss vs. random.normalvariate References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> <7xd46ws86b.fsf@ruckus.brouhaha.com> Message-ID: <7xbpmfqylr.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > > > No language can guard against independent access of a shared/global > > > object by multiple threads... > http://en.wikipedia.org/wiki/Erlang_(programming_language) > """ > Like operating system processes (and unlike green threads and operating > system threads) they have NO SHARED STATE between them. > """ > which seems to reinforce my statement, not refute it. Id say Erlang guards against independent access of shared/global objects by not allowing them. > (The Amiga was heavily dependent upon message ports... Having to > copy data buffers between processes would have slowed the system > down drastically [8MHz processor, in those days], It's perfectly ok for Erlang implementation to just pass pointers around, when the processes are on the same machine. Erlang prohibits data mutation so there isn't an issue of a process modifying some structure while another process is using it. From toby at telegraphics.com.au Sun Aug 16 16:51:21 2009 From: toby at telegraphics.com.au (toby) Date: Sun, 16 Aug 2009 13:51:21 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> Message-ID: <4f0af709-527a-47db-8a8a-b0b42c6fe34d@d32g2000yqh.googlegroups.com> On Aug 16, 12:05?pm, Peter Keller wrote: > In comp.lang.scheme Xah Lee wrote: > > > Xah's Edu Corner: The importance of syntax & notations. > > >http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstr... > > > this article should teach the coding sophomorons and computer > > ?science? idiotic authors who harbor the notion that syntax is not > > important, picked up by all the elite i-reddit & twittering & ?hacker > > news am-hip dunces. > > I must have really tweaked you with my "Syntax is not important, ideas are." > statement. > > I read Wolfram's article carefully. He applies an intuitive sense onto > why he does or doesn't like a particular notation, but yet can't really > elucidate his feelings. Exactly; and as far as I can determine, Knuth does the same. He applies standards of *good taste* to his notation. (No surprise that he's also singled out for vituperation by the OP.) In my opinion Knuth believed in the value of literate programming for similar reasons: To try to exploit existing cognitive training. If your user base is familiar with English, or mathematical notation, or some other lexicography, try to exploit the pre-wired associations. Clearly this involves some intuition. > ... > Thank you. > > -pete From fateman at gmail.com Sun Aug 16 17:00:42 2009 From: fateman at gmail.com (rjf) Date: Sun, 16 Aug 2009 14:00:42 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> Message-ID: <75e1deb2-f879-4deb-bd50-56954dfefc64@o6g2000yqj.googlegroups.com> On Aug 16, 9:05?am, Peter Keller wrote: > In comp.lang.scheme Xah Lee wrote: > > > Xah's Edu Corner: The importance of syntax & notations. > > >http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstr... > > > this article should teach the coding sophomorons and computer > > ?science? idiotic authors who harbor the notion that syntax is not > > important, picked up by all the elite i-reddit & twittering & ?hacker > > news am-hip dunces. > > I must have really tweaked you with my "Syntax is not important, ideas are." > statement. > > I read Wolfram's article carefully. He applies an intuitive sense onto > why he does or doesn't like a particular notation, but yet can't really > elucidate his feelings. I'm surprised that didn't tweak you worse. He > also goes so far as to mention that: > > "But actually we still don't know a clean simple way to represent things > like geometrical diagrams in a kind of language-like notation. And > my guess is that actually of all the math-like stuff out there, only > a comparatively small fraction can actually be represented well with > language-like notation." > For someone talking about notation and language, it is amusing that Wolfram refuses to write grammatically correct sentences. Each of the pseudo-sentences quoted above is a dependent clause. Wolfram writes like that. He typically begins sentences with "but" or "and". In the article cited, he also claims to be more-or-less the only person alive to have thought about these issues, and that Mathematica is the solution. This is not surprising,and it is nevertheless clear that Wolfram has spent some time thinking about mathematical notation, and some money developing fonts and such. His self-praise is perhaps not deserved. It is unfortunate that most users of Mathematica labor under a misunderstanding of the meaning of the fundamental algorithmic notation of that system, namely "function definition". f[x_]:=x+1 is not a function definition, although most users think so. In fact, it is a pattern/replacement rule. If you want to write the equivalent of the lisp (defun f(x)(+ x 1)) you can do so in mathematica, but it looks like this: f=#1+1& or alternatively, f=Function[Plus[Slot[1],1]] or alternatively, f= Function[{x},x+1] How do those choices grab you for the Emmy in "Excellence in Notation"? By the way, what is wrong with f[x_]:=x+1? While you might think it maps x->x+1 for all x, it does so only in the absence of other rules involving f. Thus the presence of another definition (actually another rule) ... f[z_]:=z^2/;OddQ[z] changes the definition when the argument is an odd integer. An equivalent definition is f[z_?OddQ]:=z^2 now you could have 2 rules f[x_?Predicate1]:= 123 f[x_?Predicate2]:= 456 and it might not be clear which Predicate is a subset of the other. (It is clear that the blank pattern "_" is a superset of "_?OddQ" ). So how does Mathematica deal with this situation? The predicates are tested in some order until one returns True. What order is that? "Whenever the appropriate ordering is not clear, Mathematica stores rules in the order you give them. " Oh, when is the ordering not clear? Uh, "you should realize that this [ordering] is not always possible". (quotes from mathematica documentation , TheOrderingOfDefinitions.) While Wolfram has provided an admirable summary of the history of notation, his solution is less so. RJF From martin.hellwig at dcuktec.org Sun Aug 16 17:10:05 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sun, 16 Aug 2009 22:10:05 +0100 Subject: zip codes In-Reply-To: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> Message-ID: Shailen wrote: > Is there any Python module that helps with US and foreign zip-code > lookups? I'm thinking of something that provides basic mappings of zip > to cities, city to zips, etc. Since this kind of information is so > often used for basic user-registration, I'm assuming functionality of > this sort must be available for Python. Any suggestions will be much > appreciated. > There might be an associated can of worms here, for example in the Netherlands zip codes are actually copyrighted and require a license if you want to do something with them, on the other hand you get a nice SQL formatted db to use it. I don't know how this works in other countries but I imagine that it is likely to be generally the same. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From rylesny at gmail.com Sun Aug 16 17:10:25 2009 From: rylesny at gmail.com (ryles) Date: Sun, 16 Aug 2009 14:10:25 -0700 (PDT) Subject: Python 2.6 still not giving memory back to the OS... References: Message-ID: <79bbe86b-0d3b-4f03-b0df-be4b3308d4cd@f10g2000vbf.googlegroups.com> On Aug 15, 7:55?am, Chris Withers wrote: > Hi All, > > I thought this was fixed back in Python 2.5, but I guess not? > > So, I'm playing in an interactive session: > > ?>>> from xlrd import open_workbook > ?>>> b = open_workbook('some.xls',pickleable=0,formatting_info=1) > > At this point, top shows the process usage for python to be about 500Mb. > That's okay, I'd expect that, b is big ;-) > > ?>>> del b > > However, it still does now, maybe the garbage collector needs a kick? > > ?>>> import gc > ?>>> gc.collect() > 702614 > > Nope, still 500Mb. What gives? How can I make Python give the memory its > no longer using back to the OS? > > Okay, so maybe this is something to do with it being an interactive > session? So I wrote this script: > > from xlrd import open_workbook > import gc > b = open_workbook('some.xls',pickleable=0,formatting_info=1) > print 'opened' > raw_input() > del b > print 'deleted' > raw_input() > gc.collect() > print 'gc' > raw_input() > > The raw inputs are there so I can check the memory usage in top. > Even after the gc, Python still hasn't given the memory back to the OS :-( > > What am I doing wrong? > > Chris > > -- > Simplistix - Content Management, Batch Processing & Python Consulting > ? ? ? ? ? ? -http://www.simplistix.co.uk Repeat the 'b = open_workbook ...' line in the interpreter several times and track the memory usage after each execution. I noticed this behavior on linux, but saw that after repeating it a few times memory usage finally stop going up. Probably just the behavior of the allocator. From aahz at pythoncraft.com Sun Aug 16 17:24:17 2009 From: aahz at pythoncraft.com (Aahz) Date: 16 Aug 2009 14:24:17 -0700 Subject: Nltk with python References: <82c9f923-1098-4b7e-8f9d-9504c1a8962c@12g2000pri.googlegroups.com> Message-ID: In article <82c9f923-1098-4b7e-8f9d-9504c1a8962c at 12g2000pri.googlegroups.com>, ArshaKrishna wrote: > >How can I resolve scope ambiguity using nltk toolkit with python Question not clear, please provide more explanation -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From aahz at pythoncraft.com Sun Aug 16 17:25:12 2009 From: aahz at pythoncraft.com (Aahz) Date: 16 Aug 2009 14:25:12 -0700 Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> Message-ID: In article <35833d36-2fdc-4ed8-8142-604af3c88afe at k6g2000yqn.googlegroups.com>, Shailen wrote: > >Is there any Python module that helps with US and foreign zip-code >lookups? I'm thinking of something that provides basic mappings of zip >to cities, city to zips, etc. Since this kind of information is so >often used for basic user-registration, I'm assuming functionality of >this sort must be available for Python. Any suggestions will be much >appreciated. There's no module; you have to purchase the information and then massage it yourself. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From nagle at animats.com Sun Aug 16 17:58:40 2009 From: nagle at animats.com (John Nagle) Date: Sun, 16 Aug 2009 14:58:40 -0700 Subject: Xah's Edu Corner: The importance of syntax & notations. In-Reply-To: References: Message-ID: <4a888022$0$1637$742ec2ed@news.sonic.net> Xah Lee wrote: > Xah's Edu Corner: The importance of syntax & notations. > > http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstract.html > > this article should teach the coding sophomorons and computer > ?science? idiotic authors who harbor the notion that syntax is not > important, picked up by all the elite i-reddit & twittering & hacker > news am-hip dunces. Definitely read Wolfram's paper. He and his people actually had to solve the problem. Wolfram had to face up to the big problem - how do we input traditional mathematics into a computer unambiguously. Version 1 was Mathematica FullForm, which is very wordy but clear, like Ada. This worked, but was too clunky. After a few redesigns, they came up with what he calls StandardForm, which is Mathematica's variant on what he calls "TraditionalForm", or mathematics as currently written in textbooks. The differences are subtle; the main one is that precedence is more explicit, and a "double strike" convention is used to disambiguate certain meta-symbols, like the "d" used in derivatives and "i" used as sqrt(-1). StandardForm is unambiguous. TraditionalForm is not, as anyone who spends too much time reading other people's math publications realizes. Cleverly, the Mathematica people have been able to produce a set of heuristics which, Wolfram claims, allows converting traditional form into the unambiguous StandardForm, getting it right most of the time. (I've been struggling to read a paper on machine learning which has some non-standard operator precedence problems, and I wish the paper was in StandardForm.) Wolfram would, I think, like to make "StandardForm" the standard for publication, and in time, something like that will probably happen. It's useful to be able to get math in and out of symbolic manipulation systems. Anyway, read the paper. John Nagle From shailen.tuli at gmail.com Sun Aug 16 18:26:27 2009 From: shailen.tuli at gmail.com (Shailen) Date: Sun, 16 Aug 2009 15:26:27 -0700 (PDT) Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> Message-ID: <512e67d9-8733-4329-a7d9-c6e21d6a2165@r38g2000yqn.googlegroups.com> Thanks Martin and Aahz. Anyone know if zip code information is copyrighted for the US? Anyone can look up zip codes on usps.gov (and other locations),so the information is readily available. I need zip codes for a handful of cities and could map those myself (or write a script to scrape them for me), but am not sure if they *MUST* be purchased for copyright reasons. Anyone know? - Shailen Tuli From davea at ieee.org Sun Aug 16 18:27:47 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 16 Aug 2009 18:27:47 -0400 Subject: redoing libgmail interface to "smtplib" blah? In-Reply-To: References: Message-ID: <4A8887E3.3050000@ieee.org> Dennis Lee Bieber wrote: > On Sat, 15 Aug 2009 23:14:39 -0600, John Haggerty > declaimed the following in gmane.comp.python.general: > > >> I did detect one problem thus far >> >> File "test.py", line 152 >> if len(args) == 1 and args[0] = "-c": >> >> > Should have been fine, unless my memory of sys.argv contents was > wrong (as I recall, sys.argv, if it behaves like other languages, would > > You missed the actual problem: there's a single '=' in the second part of the if expression. Should be "==" DaveA From sturlamolden at yahoo.no Sun Aug 16 18:35:26 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Aug 2009 15:35:26 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> On 16 Aug, 14:57, Dennis Lee Bieber wrote: > ? ? ? ? Well, the alternative would be to have two keywords for looping: one > for your "simple" incrementing integer loop, and another for a loop that > operates over the elements of some collection type. A compiler could easily recognise a statement like for i in range(n): as a simple integer loop. In fact, Cython is able to do this. From http Sun Aug 16 19:17:59 2009 From: http (Paul Rubin) Date: 16 Aug 2009 16:17:59 -0700 Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> <512e67d9-8733-4329-a7d9-c6e21d6a2165@r38g2000yqn.googlegroups.com> Message-ID: <7x63cnbb6g.fsf@ruckus.brouhaha.com> Shailen writes: > Thanks Martin and Aahz. Anyone know if zip code information is > copyrighted for the US? Anyone can look up zip codes on usps.gov (and > other locations),so the information is readily available. I need zip > codes for a handful of cities and could map those myself (or write a > script to scrape them for me), but am not sure if they *MUST* be > purchased for copyright reasons. Anyone know? I don't think US zip code info is copyrighted. There is a lot of it in the TIGER database: http://www.census.gov/geo/www/tiger/tigerua/ua_tgr2k.html There are also some API's operated by usps.com if you want just a few lookups now and then. It was a long time ago, I don't remember specifics, and the contents are surely out of date by now, but I extracted a bunch of the TIGER geographic coordinates for zip codes here: http://www.nightsong.com/phr/chess/zipcodes.zip From http Sun Aug 16 19:32:31 2009 From: http (Paul Rubin) Date: 16 Aug 2009 16:32:31 -0700 Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> <512e67d9-8733-4329-a7d9-c6e21d6a2165@r38g2000yqn.googlegroups.com> <7x63cnbb6g.fsf@ruckus.brouhaha.com> Message-ID: <7xws539vxs.fsf@ruckus.brouhaha.com> > It was a long time ago, I don't remember specifics, and the contents > are surely out of date by now, but I extracted a bunch of the TIGER > geographic coordinates for zip codes here: > > http://www.nightsong.com/phr/chess/zipcodes.zip That file may have actually come from here: http://www.census.gov/geo/www/tiger/zip1999.html From invalid at invalid Sun Aug 16 20:07:18 2009 From: invalid at invalid (Grant Edwards) Date: Sun, 16 Aug 2009 19:07:18 -0500 Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> <512e67d9-8733-4329-a7d9-c6e21d6a2165@r38g2000yqn.googlegroups.com> Message-ID: On 2009-08-16, Shailen wrote: > Thanks Martin and Aahz. Anyone know if zip code information is > copyrighted for the US? You can't copyright "information" as such. Only concrete expressions of information. A particular publication containing zip code information can be copyrighted. The underlying facts themselve cannot be. -- Grant From benjamin.kaplan at case.edu Sun Aug 16 21:23:20 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 16 Aug 2009 21:23:20 -0400 Subject: Python 'for' loop is memory inefficient In-Reply-To: <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: On Sun, Aug 16, 2009 at 6:35 PM, sturlamolden wrote: > > A compiler could easily recognise a statement like > > ? for i in range(n): > > as a simple integer loop. In fact, Cython is able to do this. but special cases aren't special enough to break the rules. From sjmachin at lexicon.net Sun Aug 16 21:23:23 2009 From: sjmachin at lexicon.net (John Machin) Date: Sun, 16 Aug 2009 18:23:23 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: On Aug 17, 8:35?am, sturlamolden wrote: > A compiler could easily recognise a statement like > ? ?for i in range(n): > as a simple integer loop. In fact, Cython is able to do this. Extremely easy, once users relinquish the right to replace built-in "range" with their own concoctions ... From exarkun at twistedmatrix.com Sun Aug 16 21:28:40 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 17 Aug 2009 01:28:40 -0000 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: <20090817012840.8740.554583249.divmod.xquotient.17@localhost.localdomain> On 01:23 am, benjamin.kaplan at case.edu wrote: >On Sun, Aug 16, 2009 at 6:35 PM, sturlamolden >wrote: >> >>A compiler could easily recognise a statement like >> >>? for i in range(n): >> >>as a simple integer loop. In fact, Cython is able to do this. > >but special cases aren't special enough to break the rules. Although I think PyPy also recognizes this case and makes it as efficient as using xrange, and does so without breaking any rules. There *are* _some_ legitimate complaints to be made about the CPython runtime. :) Jean-Paul From http Sun Aug 16 21:44:33 2009 From: http (Paul Rubin) Date: 16 Aug 2009 18:44:33 -0700 Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: <7xtz079ptq.fsf@ruckus.brouhaha.com> exarkun at twistedmatrix.com writes: > Although I think PyPy also recognizes this case and makes it as > efficient as using xrange, and does so without breaking any rules. How can pypy possibly know that the user hasn't assigned some other value to "range"? From pavlovevidence at gmail.com Sun Aug 16 21:53:10 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 16 Aug 2009 18:53:10 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: <900c0d5e-a41a-4820-9844-816afa1a33c9@g10g2000yqh.googlegroups.com> On Aug 16, 6:28?pm, exar... at twistedmatrix.com wrote: > On 01:23 am, benjamin.kap... at case.edu wrote: > > >On Sun, Aug 16, 2009 at 6:35 PM, sturlamolden > >wrote: > > >>A compiler could easily recognise a statement like > > >>? for i in range(n): > > >>as a simple integer loop. In fact, Cython is able to do this. > > >but special cases aren't special enough to break the rules. > > Although I think PyPy also recognizes this case and makes it as > efficient as using xrange, and does so without breaking any rules. PyPy uses a JIT compiler (which is still slower than CPython, suggesting that perhaps they should have spent more time optimizing the general case than optimizing for an easily avoided special case). > There *are* _some_ legitimate complaints to be made about the CPython > runtime. :) This isn't one of them. xrange has been part of Python for 10 years. If there are any complaints to be made about this situation it's that there are any 2.x learning materials anythere that continue to use range() and not xrange() in this context. Carl Banks From pavlovevidence at gmail.com Sun Aug 16 22:12:20 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 16 Aug 2009 19:12:20 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> On Aug 16, 3:35?pm, sturlamolden wrote: > On 16 Aug, 14:57, Dennis Lee Bieber wrote: > > > ? ? ? ? Well, the alternative would be to have two keywords for looping: one > > for your "simple" incrementing integer loop, and another for a loop that > > operates over the elements of some collection type. > > A compiler could easily recognise a statement like > > ? ?for i in range(n): > > as a simple integer loop. It would be a simple to do if you were writing it for a different langauge was a lot less dynamic than Python is. It'd be quite a complex hack to add it to CPython's compiler while maintaing the current highly dynamic runtime semantics and backwards compatibility, which is a design constraint of Python whether you like it or not. And all this complaining about an issue that can be worked around by xrange instead of range. Sheesh. > In fact, Cython is able to do this. Cython can do this easily because it is a different language that is a lot less dynamic than Python. If you don't care about the dynamic stuff why don't you just use Cython? Or quit complaining and just use xrange. Carl Banks From nobody at nowhere.com Sun Aug 16 22:21:43 2009 From: nobody at nowhere.com (Nobody) Date: Mon, 17 Aug 2009 03:21:43 +0100 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> Message-ID: On Sun, 16 Aug 2009 05:05:01 +0000, Steven D'Aprano wrote: > Now that I understand what the semantics of cout << "Hello world" are, I > don't have any problem with it either. It is a bit weird, "Hello world" > >> cout would probably be better, Placing the stream on the LHS allows the main forms of << to be implemented as methods of the ostream class. C++ only considers the LHS operand when attempting to resolve an infix operator as a method. Also, << and >> are left-associative, and that cannot be changed by overloading. Having the ostream on the LHS allows the operators to be chained: cout << "Hello" << ", " << "world" << endl equivalent to: (((cout << "Hello") << ", ") << "world") << endl [operator<< returns the ostream as its result.] Even if you could make >> right-associative, the values would have to be written right-to-left: endl >> "world" >> ", " >> "Hello" >> cout i.e.: endl >> ("world" >> (", " >> ("Hello" >> cout))) From benjamin at python.org Sun Aug 16 22:55:14 2009 From: benjamin at python.org (Benjamin Peterson) Date: Sun, 16 Aug 2009 21:55:14 -0500 Subject: [RELEASED] Python 3.1.1 Message-ID: <1afaf6160908161955k6968c378md76ec37cba4865aa@mail.gmail.com> On behalf of the Python development team, I'm happy to announce the first bugfix release of the Python 3.1 series, Python 3.1.1. This bug fix release fixes many normal bugs and several critical ones including potential data corruption in the io library. Python 3.1 focuses on the stabilization and optimization of the features and changes that Python 3.0 introduced. For example, the new I/O system has been rewritten in C for speed. File system APIs that use unicode strings now handle paths with undecodable bytes in them. Other features include an ordered dictionary implementation, a condensed syntax for nested with statements, and support for ttk Tile in Tkinter. For a more extensive list of changes in 3.1, see http://doc.python.org/3.1/whatsnew/3.1.html or Misc/NEWS in the Python distribution. Please note the Windows and Mac binaries are not available yet but will be in the coming days. To download Python 3.1.1 visit: http://www.python.org/download/releases/3.1.1/ The 3.1 documentation can be found at: http://docs.python.org/3.1 Bugs can always be reported to: http://bugs.python.org Enjoy! -- Benjamin Peterson Release Manager benjamin at python.org (on behalf of the entire python-dev team and 3.1.1's contributors) From xahlee at gmail.com Sun Aug 16 23:00:23 2009 From: xahlee at gmail.com (Xah Lee) Date: Sun, 16 Aug 2009 20:00:23 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> Message-ID: Thanks Raymond. I've been out of python community for a couple of years. I've saved your messages and will study it later when next time i work in python. Possibly today and will reply in some of your points. But just wanted to say thanks for improving python. Also, sometimes ago out of the blue i noticed someone has posted a bug on python's gzip doc with acknowledgement. http://bugs.python.org/issue2406 Thank you M.-A. DARCHE (madarche). Also, i noticed python doc now and later has improved a lot since last i looked around python 2.4. For one thing, the html/xhtml is now valid html. Good riddence of the fucking TeX. Also, code examples have syntax coloring on. Xah ? http://xahlee.org/ ? On Aug 12, 12:15 pm, Raymond Hettinger wrote: > [Xah Lee] > > > i've wrote several articles about this issue, total time spend on this > > is probably more than 2 months full-time work. See: > > > ? Python Documentation Problems > > http://xahlee.org/perl-python/python_doc_index.html > > I just read you post. You did devote a substantial amount of time > to the project. Some of your criticisms are valid. Wish you had > posted patches, I think many of them would have been accepted. > > Since you wrote this a few years ago, many examples have > been added to the docs and more are forthcoming. > > > I often receive thank you emails for 2 particular articles, which are > > most frequently google searched as indicated by my weblog: > > > ? Python Doc Problem Example: gzip > > http://xahlee.org/perl-python/python_doc_gzip.html > > > ? Python Doc Problem Example: sort() > > http://xahlee.org/perl-python/python_doc_sort.html > > > ? Sorting in Python and Perl > > http://xahlee.org/perl-python/sort_list.html > > Some are the criticisms are valid; others seem off-base. > > Here are a few thoughts on list.sort() for those who are interested: > > * The key= and reversed= parameters are not intended for special > cases, leaving cmp= for the general case. They were intended to > be full replacements. In Python3.x, the cmp function is gone. > > * The interaction of the key= and cmp= functions can be made to > interact (the key function is first applied to every element and > the cmp function then gets applied to the results of the key > function). This isn't a normal or intended use case, so the docs > don't delve into the subject. > > * The reversed parameter does more than list.sort() followed by > list.reverse(). It also preserves stability in the event of equal > keys: > > >>> sorted([(1,2), (1,3)], key=itemgetter(0), reverse=True) > [(1,2), (1,3)] > > So it was not correct to say that the following are equivalent: > > li.sort(lambda x, y: cmp(x[1],y[1]), reverse=True) > li.sort(lambda x, y: cmp(y[1],x[1])) > > * We should link the sorted() and list.sort() docs to the > sorting how-to (with a fuller discussion on the art of sorting > including a discussion of operator.itemgetter() and > operator.attrgetter() which were designed to work with the key= > parameter. > > Raymond From nobody at nowhere.com Sun Aug 16 23:10:17 2009 From: nobody at nowhere.com (Nobody) Date: Mon, 17 Aug 2009 04:10:17 +0100 Subject: Python 'for' loop is memory inefficient References: <24980842.post@talk.nabble.com> <4A8612CE.7080700@stoneleaf.us> <200908160830.55031.emmanuel.surleau@gmail.com> Message-ID: On Sun, 16 Aug 2009 11:41:21 -0400, Benjamin Kaplan wrote: > It's not that the code is bad, but too many people coming from Java > and C keep thinking of for loops like they're using Java or C and > therefore that "for i in range(a,b)" is identical to "for(int i = a; i > < b; i++)". It's not and, for the most part, you shouldn't code like > that. Since you're using numbers, range/xrange is the appropriate > idiom but you still have to remember that a for loop in python doesn't > loop until a condition is met, it loops through an iterator until the > interator says it's done. Java also has iterators; it's more a case of people coming from C and BASIC. Although, some of those may have come *through* Java without abandoning old habits. You see the same thing with people coming from BASIC to C and writing: #define NUM_DATES 50 int day[NUM_DATES], month[NUM_DATES], year[NUM_DATES]; rather than defining a "struct". Sometimes referred to as "I know ten languages and can write in BASIC in all of them". From nobody at nowhere.com Sun Aug 16 23:32:07 2009 From: nobody at nowhere.com (Nobody) Date: Mon, 17 Aug 2009 04:32:07 +0100 Subject: wxFormBuilder finally supports wxPython References: Message-ID: On Sun, 16 Aug 2009 03:19:51 -0700, sturlamolden wrote: > Version 3.1 of wxFormBuilder can generate wxPython code. I have > previously used wxFormBuilder to generate XRC files for my wxPython > projects. Though still in beta, this might be even better. :-) Is there a reason to prefer code over XRC? From jon at ffconsultancy.com Mon Aug 17 00:05:46 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 17 Aug 2009 05:05:46 +0100 Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> <5031edcc-c63e-4a3b-9f12-caba0cc34e92@r18g2000yqd.googlegroups.com> Message-ID: w_a_x_man wrote: > On Aug 16, 11:05?am, Petey Keller wrote: >> Compiler go through *great* pains > > Compiler work real hard. > Compiler have heap big trouble. ROTFL. :-) -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From xahlee at gmail.com Mon Aug 17 00:43:48 2009 From: xahlee at gmail.com (Xah Lee) Date: Sun, 16 Aug 2009 21:43:48 -0700 (PDT) Subject: python doc available in emacs info format? Message-ID: btw, is there still info format for python doc? i feel kinda sad that emacs info format has pretty much been deprecated over the past decade. About a decade ago, you still will see now and then people asking for emacs info format of docs (was the days of perl). Today, one don't hear of it. Part of this is due to emacs cult problem. See: ? Emacs Modernization http://xahlee.org/emacs/emacs_modernization.html ? Emacs Should Adopt HTML To Replace Texinfo http://xahlee.org/emacs/modernization_html_vs_info.html ? Language, Purity, Cult, and Deception http://xahlee.org/UnixResource_dir/writ/lang_purity_cult_deception.html Xah ? http://xahlee.org/ ? On Dec 11 2008, 6:56 am, Matthias wrote: > Xah Lee writes: > > in programing elisp in emacs, i can press ?Ctrl+h f? to lookup > > the doc for the function under cursor. is there such facility > > when coding in perl, python, php? > > Yes, try C-h S (or similarly S): > > (info-lookup-symbol SYMBOL &optional MODE) Display the > definition of SYMBOL, as found in the relevant manual. When this > command is called interactively, it reads SYMBOL from the > minibuffer. > > Note that `the relevant manual' means an info file. With recent > emacsen on an Ubuntu distro, python arrives with info files and > everything is well configured. It also works with bash, latex, perl, > scheme, elisp, awk, texinfo, makefile, libc, or any info file with an > index. > -- > Matthias From psilord at merlin.cs.wisc.edu Mon Aug 17 01:22:44 2009 From: psilord at merlin.cs.wisc.edu (Peter Keller) Date: 17 Aug 2009 05:22:44 GMT Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> <4f0af709-527a-47db-8a8a-b0b42c6fe34d@d32g2000yqh.googlegroups.com> Message-ID: <4a88e924$0$9895$80265adb@spool.cs.wisc.edu> In comp.lang.scheme toby wrote: > In my opinion Knuth believed in the value of literate programming for > similar reasons: To try to exploit existing cognitive training. If > your user base is familiar with English, or mathematical notation, or > some other lexicography, try to exploit the pre-wired associations. > Clearly this involves some intuition. I've dabbled in the linguistics field a little bit and this thread made me remember a certain topic delineated in this paper: http://complex.upf.es/~ricard/SWPRS.pdf This paper uses a concept that I would say needs more investigation: The mapping of syntax onto metric spaces. In fact, the paper literally makes a statement about how physically close two words are when mapped onto a line of text and language networks build graph topologies based upon the distance of words from each other as they relate in syntactical form. It seems the foundations for being able to construct a metric to "measure" syntax is somewhat available. If you squint at the math in the above paper, you can see how it can apply to multidimensional metric spaces and syntax in different modalities (like the comparison between reading written words and hearing spoken words). For example, here the same semantic idea in a regex defined three ways: english-like: Match the letter "a" followed by one or more letter "p"s followed by the letter "l" then optionaly the letter "e". scheme-like: (regex (char-class \#a) (re+ (char-class \#p)) (char-class \#l) (re? (char-class \#e))) perl-like: /ap+le?/ The perl-like one would be the one chosen by most programmers, but the various reasons why it is chosen will fluctuate. Can we do better? Can we give a predictable measurement of some syntactic quantities that we can optimize and get a predictable answer? Most people would say the perl-like form has the least amount of "syntactic garbage" and is "short". How do we meaningfully define those two terms? One might say "syntactic garbage" is syntax which doesn't relate *at all* to the actual semantic objects, and "short" might mean elimination of redundant syntax and/or transformation of explicit syntax into implicit syntax already available in the metric space. What do I mean by explicit versus implicit? In the scheme-like form, we explicitly denote the evaluation and class of the various semantic objects of the regex before applying the "regex" function across the evaluated arguments. Whitespace is used to separate the morphemes of only the scheme syntax. The embedding metric space of the syntax (meaning the line of text indexed by character position) does nothing to help or hinder the expression of the semantic objects. In the perl-like form, we implicitly denote the evaluation of the regex by using a prototyping-based syntax, meaning the inherent qualities of the embedding metric space are utilized. This specifically means that evaluation happens left to right in reading order and semantic objects evaluate directly to themselves and take as arguments semantic objects as related directly in the embedding metric space. For example, the ? takes as an argument the semantic object at location index[?]-1. Grouping parenthsis act as a VERY simple tokenization system to group multiple objects into one syntactical datum. Given the analysis, it seems the perl-like regex generally auto-quote themselves as an advantageous use of the embeded metric space in which they reside (aka the line of text). The english-like form is the worst for explicit modeling because it abstracts the semantic objects into a meta-space that is then referenced by the syntax in the embedding space of the line itself. In human reasoning, that is what the quotes mean. Out of the three syntax models, only the perl one has no redundant syntax and takes up the smallest amount of the metric space into which it is embedded--clearly seen by observation. Consider if we have quantities "syntactic datums" versus "semantic objects", then one might make an equation like this: semantic objects expressiveness = ---------------- syntactic datums And of course, expressiveness rises as semantic objects begin to outweigh syntactic objects. This seems a very reasonable, although simplistic, model to me and would be a good start in my estimation. I say simplistic because the semantic objects are not taken in relation to themselves on the metric space the syntactic datums are embeded, I'll get to this in a bit. Now, what do we do with the above equation, well, we define what we can, and then optimize the hell out of it. "semantic objects" for a computer language is probably a fixed quantity, there are only so many operators and grouping constructs, and usually very few, meaning one, function description semantic objects. So, we are left with a free variable of "syntactic datums" that we should minimize to be as small as possible. If we don't take into consideration the topological mapping of the semantic objects into the syntactic datum space, then the number of semantic objects at least equals the number of syntactic datums. Expressiveness is simply one in the best case, and this would be pretty poor for sure. It could be worse--just add redundant syntactic datums, now it is worse! If we take into consideration the mapping of the semantic objects onto the metric space, then maybe this becomes the new equation: distance(index[obj1], index[obj2], ..., index[objn]) expressiveness = ---------------------------------------------------- syntactic datums The distance() function in this new model is the centroid of the syntactic datum which represent the semantic object. (Of course, there are other models of expressiveness which would need to be explored based upon this incremental idea I'm presenting.) Larger distances between semantic objects, or larger syntactic constructs, would mean less expressiveness. This is interesting, because it can give a rough number that sorts the three syntactic models I provided for the regex and it would follow conventional wisdom. This is a decriptivist model of syntax measurement. Obviously, the fun is can we search an optimization tree to try find an optimal set of syntactic datums to represent a known and finite set of semantic objects taking into consideration the features of the metric space into which the syntactic datums are embedded? Maybe for another day.... Later, -pete From xahlee at gmail.com Mon Aug 17 01:32:07 2009 From: xahlee at gmail.com (Xah Lee) Date: Sun, 16 Aug 2009 22:32:07 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. References: Message-ID: <25203724-bf60-484f-9ede-e61c45f15e33@s31g2000yqs.googlegroups.com> Personally, particular interesting info i've learned is that, for all my trouble in the past decade expressing problems of traditional math notation, i learned from his article this single-phrase summary: ?traditional math notation lacks a grammar?. The article is somewhat disappointing though. I was expecting he'd go into some details about the science of math notations, or, as he put it aptly: ?linguistics of math notations?. However, he didn't touch the subject, except saying that it haven't been studied. Xah On Aug 15, 10:54?pm, Xah Lee wrote: > Xah's Edu Corner: The importance of syntax & notations. > > http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstr... > > this article should teach the coding sophomorons and computer > ?science? idiotic authors who harbor the notion that syntax is not > important, picked up by all the elite i-reddit & twittering & ?hacker > news am-hip dunces. > > Further readings: > > ? The TeX Pestilence > ?http://xahlee.org/cmaci/notation/TeX_pestilence.html > > ? A Notation for Plane Geometry > ?http://xahlee.org/cmaci/notation/plane_geometry_notation.html > > ? The Concepts and Confusions of Prefix, Infix, Postfix and Fully > Nested Notations > ?http://xahlee.org/UnixResource_dir/writ/notations.html > > ? The Problems of Traditional Math Notation > ?http://xahlee.org/cmaci/notation/trad_math_notation.html > > ? Xah > ?http://xahlee.org/ > > ? From psilord at merlin.cs.wisc.edu Mon Aug 17 01:39:48 2009 From: psilord at merlin.cs.wisc.edu (Peter Keller) Date: 17 Aug 2009 05:39:48 GMT Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> <4f0af709-527a-47db-8a8a-b0b42c6fe34d@d32g2000yqh.googlegroups.com> <4a88e924$0$9895$80265adb@spool.cs.wisc.edu> Message-ID: <4a88ed24$0$9896$80265adb@spool.cs.wisc.edu> In comp.lang.scheme Peter Keller wrote: > The distance() function in this new model is the centroid of the syntactic > datum which represent the semantic object. Oops. I meant to say: "The distance() function in this new model uses the centroid of each individual syntactic datum (which represents the semantic object) as the location for each semantic object." Sorry. -pete From ranjithpmathew at gmail.com Mon Aug 17 01:59:02 2009 From: ranjithpmathew at gmail.com (L@D@n) Date: Sun, 16 Aug 2009 22:59:02 -0700 (PDT) Subject: GUI interface builder for python Message-ID: Which is the best GUI interface builder with drag and drop capabilities. I am using Ubuntu GNU/Linux. Please help me. Thank you. From jasevv at gmail.com Mon Aug 17 02:12:42 2009 From: jasevv at gmail.com (Jaseem) Date: Sun, 16 Aug 2009 23:12:42 -0700 (PDT) Subject: GUI interface builder for python References: Message-ID: <1960c134-b4a0-4b96-bd58-1cf00dab9d72@d32g2000yqh.googlegroups.com> On Aug 17, 10:59?am, "L at D@n" wrote: > Which is the best GUI interface builder with drag and drop > capabilities. > I am using Ubuntu GNU/Linux. > Please help me. > Thank you. There are many GUI builders for python. (Have to deal with the licensing issues.) Qt has a GUI builder. Glade (GTK+) for python is also good. Boa constructor is also nice. From kkylheku at gmail.com Mon Aug 17 02:42:01 2009 From: kkylheku at gmail.com (Kaz Kylheku) Date: Mon, 17 Aug 2009 06:42:01 +0000 (UTC) Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> <4f0af709-527a-47db-8a8a-b0b42c6fe34d@d32g2000yqh.googlegroups.com> <4a88e924$0$9895$80265adb@spool.cs.wisc.edu> <4a88ed24$0$9896$80265adb@spool.cs.wisc.edu> Message-ID: <20090826140229.540@gmail.com> ["Followup-To:" header set to comp.lang.lisp.] On 2009-08-17, Peter Keller wrote: > In comp.lang.scheme Peter Keller wrote: >> The distance() function in this new model is the centroid of the syntactic >> datum which represent the semantic object. > > Oops. > > I meant to say: > > "The distance() function in this new model uses the centroid of each > individual syntactic datum (which represents the semantic object) as > the location for each semantic object." Don't sweat it; either way it makes no sense. The rewrite does have a more journal-publishable feel to it, though: the centroid of the whole aromatic diffusion seems to hover more precisely above the site of the bovine waste from which it apparently emanates. From xahlee at gmail.com Mon Aug 17 02:50:27 2009 From: xahlee at gmail.com (Xah Lee) Date: Sun, 16 Aug 2009 23:50:27 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: On Aug 12, 12:15 pm, Raymond Hettinger wrote: > [Xah Lee] > > > i've wrote several articles about this issue, total time spend on this > > is probably more than 2 months full-time work. See: > > > ? Python Documentation Problems > > http://xahlee.org/perl-python/python_doc_index.html > > I just read you post. You did devote a substantial amount of time > to the project. Some of your criticisms are valid. Wish you had > posted patches, I think many of them would have been accepted. > > Since you wrote this a few years ago, many examples have > been added to the docs and more are forthcoming. > > > I often receive thank you emails for 2 particular articles, which are > > most frequently google searched as indicated by my weblog: > > > ? Python Doc Problem Example: gzip > > http://xahlee.org/perl-python/python_doc_gzip.html > > > ? Python Doc Problem Example: sort() > > http://xahlee.org/perl-python/python_doc_sort.html > > > ? Sorting in Python and Perl > > http://xahlee.org/perl-python/sort_list.html > > Some are the criticisms are valid; others seem off-base. > > Here are a few thoughts on list.sort() for those who are interested: > > * The key= and reversed= parameters are not intended for special > cases, leaving cmp= for the general case. They were intended to > be full replacements. In Python3.x, the cmp function is gone. > > * The interaction of the key= and cmp= functions can be made to > interact (the key function is first applied to every element and > the cmp function then gets applied to the results of the key > function). This isn't a normal or intended use case, so the docs > don't delve into the subject. > > * The reversed parameter does more than list.sort() followed by > list.reverse(). It also preserves stability in the event of equal > keys: > > >>> sorted([(1,2), (1,3)], key=itemgetter(0), reverse=True) > [(1,2), (1,3)] > > So it was not correct to say that the following are equivalent: > > li.sort(lambda x, y: cmp(x[1],y[1]), reverse=True) > li.sort(lambda x, y: cmp(y[1],x[1])) > > * We should link the sorted() and list.sort() docs to the > sorting how-to (with a fuller discussion on the art of sorting > including a discussion of operator.itemgetter() and > operator.attrgetter() which were designed to work with the key= > parameter. > > Here are a few thoughts on list.sort() for those who are interested: > > After one more reading of Xah Lee's posts on the documentation for > sort, > here are couple more thoughts: > > * The reason that list.sort() allows None for the cmp parameter is not > so that you can write list.sort(None). It was put there to make it > easier for people writing function definitions where the cmp function > is a possible argument: > > def sort_and_chop(seq, maxlen, cmp=None): > s = seq[:] > s.sort(cmp) # needs to accept None as a possible > argument > return s[:maxlen] > > * The reason for implementing the key= parameter had nothing to do > with limitations of Python's compiler. Instead, it was inspired by > the > decorate-sort-undecorate pattern. Hi Raymond, thanks for the many points. They are informative, some i disagree, but it's getting into detail. I don't know python 3.0, will have to look into its sort in the future. This part i don't particular agree: > * The reason for implementing the key= parameter had nothing to do > with limitations of Python's compiler. Instead, it was inspired by > the > decorate-sort-undecorate pattern. The decorate-sort-undecorate pattern is a compiler limitation, for most of today's langs. I'm not sure, but i think some of the fancy functional langs automatically detect such and optimize it away, to various degrees. ... my criticism is usually written in a style catered to irritate a particular class of coder i call tech geekers (they think of themselfs with their idiotic term ?hackers?). So, parts are exaggerated. It'd be more clear to say, that the reason for python's ?key?, and as a ?solution? or need of the decorate-sort-undecorate issue, can be attributed to the current state of the art of popular imperative language's compilers (induced by such lang's semantics). again, i haven't studied python 3.0 to see what it has changed with sort, and thanks for the informative post. I find it intriguing that it doesn't have ?cmp? anymore as you say.... maybe when i actually study it and i'll come away with rage and rants. LOL. Xah ? http://xahlee.org/ ? From contact at xavierho.com Mon Aug 17 03:09:14 2009 From: contact at xavierho.com (Xavier Ho) Date: Mon, 17 Aug 2009 17:09:14 +1000 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160104k7d74ace9jda8f4b927402942@mail.gmail.com> <2d56febf0908160458k3b5197d8tf1a69e3083ab3146@mail.gmail.com> Message-ID: <2d56febf0908170009i7ce4f53tb89ffde60d09a2bc@mail.gmail.com> On Sun, Aug 16, 2009 at 10:33 PM, Mark Lawrence wrote: > > I wasn't discussing __cmp__, I was referring to the quote by Chris Rebert > from the Python docs regarding the rich comparison methods, a discrepancy > between the documentation and the implementation as noted in the link that I > gave, and an indication that the issue raised on this discrepancy is still > open. As Terry Reedy has mentioned __lt__ elsewhere, you should be aware of > the discrepancy, otherwise you could go charging off down the wrong track. > FWIW it was Terry who raised the issue 4395, I'm sure that he could explain > the ramifications of it all far better than I ever could, so I'll sign out. Oh, I see. Thanks for informing then. =) Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From sleepy at cabbage.co.uk Mon Aug 17 03:23:55 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Mon, 17 Aug 2009 07:23:55 GMT Subject: get the pause status from amarok 2.1 References: <7eku4bF2gtku3U2@mid.uni-berlin.de> <3avhm.248709$bA.165466@newsfe16.ams2> Message-ID: On Sat, 15 Aug 2009 09:25:19 +0000, Sleepy Cabbage wrote: > On Fri, 14 Aug 2009 12:55:07 +0200, Diez B. Roggisch wrote: > >> Sleepy Cabbage schrieb: >>> As the title says, I'm trying to find a way to get the pause status >>> from amarok 2.1. >>> >>> I'm running kubuntu 9.04 with kde 4.2.2, python 2.6.2. >>> >>> Thanks in advance. >> >> Not at my linux-system right now, but dcop and the respective >> python-module should help. >> >> Diez > > Thanks for you reply Diez. i'm sure that kde4.2 now uses qdbus instead > of dcop and not sure whether amarok has the qdbus org.kde.amarok /Player > GetStatus as it returns the following: qdbus: I don't know how to > display an argument of type '(iiii)' 'dbus --literal org.kde.amarok /Player org.freedesktop.MediaPlayer.GetStatus' From sleepy at cabbage.co.uk Mon Aug 17 03:25:22 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Mon, 17 Aug 2009 07:25:22 GMT Subject: get the pause status from amarok 2.1 References: <7eku4bF2gtku3U2@mid.uni-berlin.de> <3avhm.248709$bA.165466@newsfe16.ams2> Message-ID: On Mon, 17 Aug 2009 07:23:55 +0000, Sleepy Cabbage wrote: > On Sat, 15 Aug 2009 09:25:19 +0000, Sleepy Cabbage wrote: > >> On Fri, 14 Aug 2009 12:55:07 +0200, Diez B. Roggisch wrote: >> >>> Sleepy Cabbage schrieb: >>>> As the title says, I'm trying to find a way to get the pause status >>>> from amarok 2.1. >>>> >>>> I'm running kubuntu 9.04 with kde 4.2.2, python 2.6.2. >>>> >>>> Thanks in advance. >>> >>> Not at my linux-system right now, but dcop and the respective >>> python-module should help. >>> >>> Diez >> >> Thanks for you reply Diez. i'm sure that kde4.2 now uses qdbus instead >> of dcop and not sure whether amarok has the qdbus org.kde.amarok >> /Player GetStatus as it returns the following: qdbus: I don't know how >> to display an argument of type '(iiii)' > > 'dbus --literal org.kde.amarok /Player > org.freedesktop.MediaPlayer.GetStatus' Ref my last post: This works!! From xahlee at gmail.com Mon Aug 17 03:25:24 2009 From: xahlee at gmail.com (Xah Lee) Date: Mon, 17 Aug 2009 00:25:24 -0700 (PDT) Subject: python doc available in emacs info format? References: Message-ID: <4aba0b60-0aff-419a-877a-cac1e0e448ee@j21g2000yqe.googlegroups.com> info format for Xah Lee writes: > in programing elisp in emacs, i can press ?Ctrl+h f? to lookup > the doc for the function under cursor. is there such facility > when coding in perl, python, php? On Dec 11 2008, 6:56 am, Matthias wrote: > Yes, try C-h S (or similarly S): > (info-lookup-symbol SYMBOL &optional MODE) Display the > definition of SYMBOL, as found in the relevant manual. When this > command is called interactively, it reads SYMBOL from the > minibuffer. > Note that `the relevant manual' means an info file. With recent > emacsen on an Ubuntu distro, python arrives with info files and > everything is well configured. It also works with bash, latex, perl, > scheme, elisp, awk, texinfo, makefile, libc, or any info file with an > index. I noticed that Matthias actually mentioned that info docs is available and bundled out of the box on Ubuntu linux for many popular langs, as of 2008-12. Is that true? Where can i download these info files? As far as i know, a little google search or official doc sites usually don't have a download for info format. I'm interested in getting current version doc for perl, python, php, and ruby. Thanks. Xah ? http://xahlee.org/ ? From sjoerd at acm.org Mon Aug 17 04:29:17 2009 From: sjoerd at acm.org (Sjoerd Mullender) Date: Mon, 17 Aug 2009 10:29:17 +0200 Subject: zip codes In-Reply-To: References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> Message-ID: <4A8914DD.4000307@acm.org> Martin P. Hellwig wrote: > Shailen wrote: >> Is there any Python module that helps with US and foreign zip-code >> lookups? I'm thinking of something that provides basic mappings of zip >> to cities, city to zips, etc. Since this kind of information is so >> often used for basic user-registration, I'm assuming functionality of >> this sort must be available for Python. Any suggestions will be much >> appreciated. >> > There might be an associated can of worms here, for example in the > Netherlands zip codes are actually copyrighted and require a license if > you want to do something with them, on the other hand you get a nice SQL > formatted db to use it. I don't know how this works in other countries > but I imagine that it is likely to be generally the same. > Also in The Netherlands, ZIP codes are much more fine-grained than in some other countries: ZIP code plus house number together are sufficient to uniquely identify an address. I.e. you don't need the street name. E.g., my work address has ZIP code 1098 XG and house number 123, so together they indicate that I work at Science Park 123, Amsterdam. In other words, a simple city <-> ZIP mapping is not sufficient. -- Sjoerd Mullender -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 379 bytes Desc: OpenPGP digital signature URL: From hendrik at microcorp.co.za Mon Aug 17 05:36:18 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 17 Aug 2009 11:36:18 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <200908171136.18188.hendrik@microcorp.co.za> On Sunday 16 August 2009 15:55:31 Grant Edwards wrote: > On 2009-08-15, Hendrik van Rooyen wrote: > > I am still confused about pyserial and serial - I found serial > > in my distribution library, (on the SuSe machine, not on the > > 2.5 in Slackware) but I had to download pyserial. > > That's very interesting. Is the pre-existing "serial" a > version of pyserial that the packager had pre-installed or is > it something else? I didn't know any distributions shipped I am not too sure now - when I looked in the packages directory over the weekend it was there. But I am really not sure how it got there - I cannot recall downloading it myself, but that means nothing as I have been using this machine for a while now, so it is possible that I did it some time ago and forgotten about it, without ever using it. Possible, but unlikely. I would like to think that if I downloaded it, I would have tried it, and then I would have remembered. Sorry to be so vague. Does this help? hvr at Linuxbox:~> python Python 2.5.1 (r251:54863, Dec 6 2008, 10:49:39) [GCC 4.2.1 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import serial >>> dir(serial) ['EIGHTBITS', 'FCNTL', 'FIVEBITS', 'FileLike', 'PARITY_EVEN', 'PARITY_NAMES', 'PARITY_NONE', 'PARITY_ODD', 'SEVENBITS', 'SIXBITS', 'STOPBITS_ONE', 'STOPBITS_TWO', 'Serial', 'SerialBase', 'SerialException', 'SerialTimeoutException', 'TERMIOS', 'TIOCINQ', 'TIOCMBIC', 'TIOCMBIS', 'TIOCMGET', 'TIOCMSET', 'TIOCM_CAR', 'TIOCM_CD', 'TIOCM_CTS', 'TIOCM_DSR', 'TIOCM_DTR', 'TIOCM_DTR_str', 'TIOCM_RI', 'TIOCM_RNG', 'TIOCM_RTS', 'TIOCM_RTS_str', 'TIOCM_zero_str', 'VERSION', 'XOFF', 'XON', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'device', 'errno', 'fcntl', 'os', 'plat', 'portNotOpenError', 'select', 'serialposix', 'serialutil', 'string', 'struct', 'sys', 'termios', 'writeTimeoutError'] >>> serial.VERSION '1.27' - Hendrik From fas at cs.stir.ac.uk Mon Aug 17 05:38:15 2009 From: fas at cs.stir.ac.uk (Farhan Sheikh) Date: Mon, 17 Aug 2009 10:38:15 +0100 Subject: Uninstalling mac python2.5 to install python2.6 Message-ID: <83423F73-83DA-436B-A3BA-E83CD61CD28D@cs.stir.ac.uk> Dear all, i originally had python2.5 on my mac at the univeristy and had to get 2.6 to get NEST and pyNN to work together. however now as those are now installed, i had to install numpy. As i installed numpy, it only installed its directories into the python2.5 folders and as i am new to to mac terminals i don't know how to change its directories to be installed into python2.6. my question is, do i have to uninstall python 2.5 so that only python2.6 is on the machine or is there a way to change the path so it saves into python2.5? Thanking You Farhan -- Academic Excellence at the Heart of Scotland. The University of Stirling is a charity registered in Scotland, number SC 011159. From xahlee at gmail.com Mon Aug 17 05:42:42 2009 From: xahlee at gmail.com (Xah Lee) Date: Mon, 17 Aug 2009 02:42:42 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. References: <25203724-bf60-484f-9ede-e61c45f15e33@s31g2000yqs.googlegroups.com> Message-ID: 2009-08-17 On Aug 16, 10:32 pm, Xah Lee wrote: > Personally, particular interesting info i've learned is that, for all > my trouble in the past decade expressing problems of traditional math > notation, i learned from his article this single-phrase summary: > ?traditional math notation lacks a grammar?. > The article is somewhat disappointing though. I was expecting he'd go > into some details about the science of math notations, or, as he put > it aptly: ?linguistics of math notations?. However, he didn't touch > the subject, except saying that it haven't been studied. upon a more detailed reading of Stephen's article, i discovered some errors. On this page: http://www.stephenwolfram.com/publications/recent/mathml/mathml2.html he mentions the Plimpton 322 tablet. It is widely taught in math history books, that this table is pythagorean triples. On reading his article, i wanted to refresh my understanding of the subject, so i looked up Wikipedia: http://en.wikipedia.org/wiki/Plimpton_322 and behold! apparantly, in recent academic publications, it is suggested that this is not pythagorean triples, but rather: ?a list of regular reciprocal pairs?. Xah ? http://xahlee.org/ ? On Aug 15, 10:54 pm, Xah Lee wrote: > Xah's Edu Corner: The importance of syntax & notations. >http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstr... > this article should teach the coding sophomorons and computer > ?science? idiotic authors who harbor the notion that syntax is not > important, picked up by all the elite i-reddit & twittering & hacker > news am-hip dunces. > Further readings: > ? The TeX Pestilence > http://xahlee.org/cmaci/notation/TeX_pestilence.html > ? A Notation for Plane Geometry > http://xahlee.org/cmaci/notation/plane_geometry_notation.html > ? The Concepts and Confusions of Prefix, Infix, Postfix and Fully > Nested Notations > http://xahlee.org/UnixResource_dir/writ/notations.html > ? The Problems of Traditional Math Notation > http://xahlee.org/cmaci/notation/trad_math_notation.html From pierre.gaillard at gmail.com Mon Aug 17 05:50:03 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Mon, 17 Aug 2009 02:50:03 -0700 (PDT) Subject: sub-list extraction, logical indexation Message-ID: Hello Everyone, I would like to know if it is possible to extract a sub-list from a list ? typically if : L =[[1, 2, 3],[4, 5, 6],[3] ] How to extract easily the elements 0 and 2 of L in order to get : L2 =[[1, 2, 3],[3] ] Moreover, I would like to know if it is possible to use logical indexation such that : index = [ True, False, True] L2 = L or usual indexation, something like index=[0, 2] L2 = L I tried, but failed... Thanks for your help Pierre From indermeet.gandhi at gmail.com Mon Aug 17 05:55:37 2009 From: indermeet.gandhi at gmail.com (inder) Date: Mon, 17 Aug 2009 02:55:37 -0700 (PDT) Subject: XML parsing with python Message-ID: Hi All, I am new to xml . I need to parse the xml file . After reading and browsing on the web , I could get much help . I guess SAX would be better suited for my requirement . Could some juct provide me a sample python code so that I can execute it and see how the parsing actually happens . Lets say my xml file - GLADE xwPython --> wxFormBuilder PyQt --> QtDesigner From exarkun at twistedmatrix.com Mon Aug 17 07:43:15 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 17 Aug 2009 11:43:15 -0000 Subject: Python 'for' loop is memory inefficient In-Reply-To: <900c0d5e-a41a-4820-9844-816afa1a33c9@g10g2000yqh.googlegroups.com> References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <900c0d5e-a41a-4820-9844-816afa1a33c9@g10g2000yqh.googlegroups.com> Message-ID: <20090817114315.8740.284099123.divmod.xquotient.27@localhost.localdomain> On 01:53 am, pavlovevidence at gmail.com wrote: >On Aug 16, 6:28?pm, exar... at twistedmatrix.com wrote: >>On 01:23 am, benjamin.kap... at case.edu wrote: >> >> >On Sun, Aug 16, 2009 at 6:35 PM, sturlamolden >> >wrote: >> >> >>A compiler could easily recognise a statement like >> >> >>? for i in range(n): >> >> >>as a simple integer loop. In fact, Cython is able to do this. >> >> >but special cases aren't special enough to break the rules. >> >>Although I think PyPy also recognizes this case and makes it as >>efficient as using xrange, and does so without breaking any rules. > >PyPy uses a JIT compiler (which is still slower than CPython, >suggesting that perhaps they should have spent more time optimizing >the general case than optimizing for an easily avoided special case). It's true that PyPy has a JIT compiler (which is still slower than CPython). However, this isn't where the range speedup comes from. The range optimization is handled specifically in the implementation of range (or possibly of list, or a combination of the two, I can't remember exactly). It's effective even when the JIT compiler is disabled. > >>There *are* _some_ legitimate complaints to be made about the CPython >>runtime. :) > >This isn't one of them. > >xrange has been part of Python for 10 years. > >If there are any complaints to be made about this situation it's that >there are any 2.x learning materials anythere that continue to use >range() and not xrange() in this context. Jean-Paul From exarkun at twistedmatrix.com Mon Aug 17 07:44:35 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 17 Aug 2009 11:44:35 -0000 Subject: Python 'for' loop is memory inefficient In-Reply-To: <7xtz079ptq.fsf@ruckus.brouhaha.com> References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <7xtz079ptq.fsf@ruckus.brouhaha.com> Message-ID: <20090817114435.8740.1376128107.divmod.xquotient.30@localhost.localdomain> On 01:44 am, http wrote: >exarkun at twistedmatrix.com writes: >>Although I think PyPy also recognizes this case and makes it as >>efficient as using xrange, and does so without breaking any rules. > >How can pypy possibly know that the user hasn't assigned some other >value to "range"? It doesn't really need to. The optimization isn't applied when the compiler sees the name "range" being called. It's applied after the object the default builtin name "range" is bound to is called. Jean-Paul From vlastimil.brom at gmail.com Mon Aug 17 07:58:40 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Mon, 17 Aug 2009 13:58:40 +0200 Subject: sub-list extraction, logical indexation In-Reply-To: <4A893263.2000706@mrabarnett.plus.com> References: <7esoqbF2gnhrcU1@mid.uni-berlin.de> <4A893263.2000706@mrabarnett.plus.com> Message-ID: <9fdb569a0908170458v167d57obf8517704f6e8dc@mail.gmail.com> 2009/8/17 MRAB : > Diez B. Roggisch wrote: >> >> Pierre wrote: >> >>> Hello Everyone, >>> >>> I would like to know if it is possible to extract a sub-list from a >>> list ? >>> >>> typically if : >>> >>> L =[[1, 2, 3],[4, 5, 6],[3] ] >>> >>> How to extract easily the elements 0 and 2 of L in order to get : >>> >>> L2 =[[1, 2, 3],[3] ] >>> >>> Moreover, I would like to know if it is possible to use logical >>> indexation such that : >>> >>> index = [ True, False, True] >>> L2 = L >>> >>> or usual indexation, something like >>> index=[0, 2] >>> L2 = L >>> >>> I tried, but failed... >>> Thanks for your help >> >> >> index = [ True, False, True] >> L2 = [v for i, v in enumerate(L) if index[i]] >> > Or: > > L =[[1, 2, 3],[4, 5, 6],[3] ] > index = [ True, False, True] > > from itertools import izip > L2 = [v for i, v in izip(index, L) if i] > Or in python 3.1 >>> import itertools >>> list(itertools.compress(data=[[1, 2, 3], [4, 5, 6], [3]], selectors=[True, False, True])) [[1, 2, 3], [3]] vbr From dmhouse at gmail.com Mon Aug 17 08:23:47 2009 From: dmhouse at gmail.com (David House) Date: Mon, 17 Aug 2009 13:23:47 +0100 Subject: ignored test cases in unittest In-Reply-To: <56527679-4cec-49a1-9b46-c38de8f981c8@g10g2000yqh.googlegroups.com> References: <873a7so66v.fsf@benfinney.id.au> <56527679-4cec-49a1-9b46-c38de8f981c8@g10g2000yqh.googlegroups.com> Message-ID: 2009/8/16 Terry : > Thanks for the solutions. I think the decorator idea is what I'm look > for:-) Note that the unittest module now supports the `skip' and `expectedFailure' decorators, which seem to describe some of the solutions here. See http://docs.python.org/3.1/library/unittest.html#skipping-tests-and-expected-failures -- -David From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 17 08:33:22 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 17 Aug 2009 14:33:22 +0200 Subject: callable virtual method In-Reply-To: References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4a894e11$0$22902$426a74cc@news.free.fr> Jean-Michel Pichavant a ?crit : (snip) > Sometimes the base is doing cool stuff but incomplete stuff which > requires knowledge only hold by the sub class. In my case the interface > is a high level interface for a software that can run on multiple > hardware platforms. Only the sub class has knowledge on how to operate > the hardware, but no matter the hardware it still produces the same effect. > > Let's say I have 50 different hardwares, I'll have 50 sub classes of > Interface with the 'start' method to define. It wouldn't be appropriate > (OO programming)to write 50 times '_log.debug('Starting %s' % self)' in > each child start method when the simple task of logging the call can be > nicely handled by the base class. Which is exactly one of the use cases for the Template Method pattern in traditional OO design. For the record, Python can offer other solutions to this kind of problem - like a combination of decorators and metaclasses. > In the meantime, I must make sure the user, who is not a python guru in > this case, has implemented the start method for his hardware, whether he has to implement the 'start' or '_start' method doesn't make any difference here. From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 17 08:35:19 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 17 Aug 2009 14:35:19 +0200 Subject: callable virtual method In-Reply-To: References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4a894e85$0$22902$426a74cc@news.free.fr> Jean-Michel Pichavant a ?crit : > Scott David Daniels wrote: (snip) >> But there _is_ one moment when you can check those things, then avoid >> checking thereafter: object creation. So you can complicate your >> __init__ (or __new__) with those checks that make sure you instantiate >> only fully defined subclasses: That's something I'd rather do in a custom metaclass. But YMMV, of course... From sturlamolden at yahoo.no Mon Aug 17 08:37:29 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 17 Aug 2009 05:37:29 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> Message-ID: <60535b0d-dac1-4f4b-a464-eb05a2b3c0a3@h31g2000yqd.googlegroups.com> On 16 Aug, 19:12, Carl Banks wrote: > If you don't care about the dynamic stuff why don't you just use > Cython? ?Or quit complaining and just use xrange. I think you are the only one complaining here. From python at mrabarnett.plus.com Mon Aug 17 09:01:19 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 17 Aug 2009 14:01:19 +0100 Subject: Python 'for' loop is memory inefficient In-Reply-To: <20090817114036.8740.394539460.divmod.xquotient.22@localhost.localdomain> References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> <20090817114036.8740.394539460.divmod.xquotient.22@localhost.localdomain> Message-ID: <4A89549F.6050004@mrabarnett.plus.com> exarkun at twistedmatrix.com wrote: > On 02:12 am, pavlovevidence at gmail.com wrote: >> On Aug 16, 3:35?pm, sturlamolden wrote: >>> On 16 Aug, 14:57, Dennis Lee Bieber wrote: >>> >>> > ? ? ? ? Well, the alternative would be to have two keywords for >>> looping: one >>> > for your "simple" incrementing integer loop, and another for a loop >>> that >>> > operates over the elements of some collection type. >>> >>> A compiler could easily recognise a statement like >>> >>> ? ?for i in range(n): >>> >>> as a simple integer loop. >> >> It would be a simple to do if you were writing it for a different >> langauge was a lot less dynamic than Python is. It'd be quite a >> complex hack to add it to CPython's compiler while maintaing the >> current highly dynamic runtime semantics and backwards compatibility, >> which is a design constraint of Python whether you like it or not. > > In your other message, you said this wasn't a legitimate CPython > complaint. Here, you say that it would be a "complex hack" to implement > this in CPython. "complex hack" has negative connotations in my mind. > This seems contradictory to me. >> >> And all this complaining about an issue that can be worked around by >> xrange instead of range. Sheesh. > > Sure. The specific issue of range vs xrange is quite a small one. There > is a slightly larger one regarding the flexibility (or relative lack > thereof) of the CPython runtime, though. > A possible solution would be to make 'range' return an instance of, say, 'RangeList', a subclass of list which would behave like 'list' externally but create the list of values internally only when needed. From steven.oldner at gmail.com Mon Aug 17 09:03:52 2009 From: steven.oldner at gmail.com (steven.oldner) Date: Mon, 17 Aug 2009 06:03:52 -0700 (PDT) Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> <4A8914DD.4000307@acm.org> Message-ID: <15819238-2a87-47e4-8d5f-1f1714d2dd8c@r38g2000yqn.googlegroups.com> On Aug 17, 5:21?am, MRAB wrote: > Sjoerd Mullender wrote: > > Martin P. Hellwig wrote: > >> Shailen wrote: > >>> Is there any Python module that helps with US and foreign zip-code > >>> lookups? I'm thinking of something that provides basic mappings of zip > >>> to cities, city to zips, etc. Since this kind of information is so > >>> often used for basic user-registration, I'm assuming functionality of > >>> this sort must be available for Python. Any suggestions will be much > >>> appreciated. > > >> There might be an associated can of worms here, for example in the > >> Netherlands zip codes are actually copyrighted and require a license if > >> you want to do something with them, on the other hand you get a nice SQL > >> formatted db to use it. I don't know how this works in other countries > >> but I imagine that it is likely to be generally the same. > > > Also in The Netherlands, ZIP codes are much more fine-grained than in > > some other countries: ZIP code plus house number together are sufficient > > to uniquely identify an address. ?I.e. you don't need the street name. > > E.g., my work address has ZIP code 1098 XG and house number 123, so > > together they indicate that I work at Science Park 123, Amsterdam. > > > In other words, a simple city <-> ZIP mapping is not sufficient. > > The same comment applies to UK postcodes, which are also alphanumeric. > My home postcode, for example, is shared with only 3 other houses, IIRC.- Hide quoted text - > > - Show quoted text - Google for Zip codes. There are some free databases of codes, but they are dated. USPS and 3 party vendors sell zip code databases and lists. The USPS APIs are a joke. They were going to charge me for using them. I ended up using a 2 year old database of ZIP codes for my needs. Hope this helps! From luke.leighton at googlemail.com Mon Aug 17 09:03:57 2009 From: luke.leighton at googlemail.com (lkcl) Date: Mon, 17 Aug 2009 06:03:57 -0700 (PDT) Subject: platform-specific overrides of functions and class methods (expanding on imputils demo code) References: Message-ID: <77715735-2668-43e7-95da-c91d175b35c9@z31g2000yqd.googlegroups.com> thought that people might like to know: i found also that imputil, the standard python module, was lacking the necessary complexity in being a substitute for the standard __import__ function. the additions required were very simple: # note the addition of level=-1 which is ignored def _import_hook(self, fqname, globals=None, locals=None, fromlist=None, level=-1): ..... # Grrr, some people "import os.path" or do "from os.path import ..." if len(parts) == 2 and hasattr(top_module, parts[1]): if fromlist: return getattr(top_module, parts[1]) else: return top_module # assume that the module has already been imported, # walk from top_module to find it. mod = top_module for k in parts[1:]: if not hasattr(mod, k): print "no mod", mod, k, parts mod = None break mod = getattr(mod, k) if mod: return mod # If the importer does not exist, then we have to bail. A missing # importer means that something else imported the module, and we have # no knowledge of how to get sub-modules out of the thing. raise ImportError, 'No module named ' + fqname it's the module-walking that's been added: going from the "top" module, looking for an attribute of the split-parts. this code makes the assumption that if top module already exists, and it has a sub- module, and that has a sub-sub-module, and that has a sub-sub-sub- module etc. then it is perfectly reasonable to return that pre- existing, already-imported [sub-]+ module as the return result. the reason why this had to be added is because comtypes.gen.{some module} auto-generator relies on it, and calls __import__ *direct*. if somebody would like to add this to the python bugtracker, as a contribution, that would be great. alternatively, you might like to have a word with the python developers to get them to remove the censorship on my contributions. l. From stefan_ml at behnel.de Mon Aug 17 09:20:31 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 17 Aug 2009 15:20:31 +0200 Subject: Python 'for' loop is memory inefficient In-Reply-To: <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> Message-ID: <4a895920$0$32674$9b4e6d93@newsspool2.arcor-online.net> Carl Banks wrote: > On Aug 16, 3:35 pm, sturlamolden wrote: >> On 16 Aug, 14:57, Dennis Lee Bieber wrote: >> >>> Well, the alternative would be to have two keywords for looping: one >>> for your "simple" incrementing integer loop, and another for a loop that >>> operates over the elements of some collection type. >> A compiler could easily recognise a statement like >> >> for i in range(n): >> >> as a simple integer loop. >> >> In fact, Cython is able to do this. > > Cython can do this easily because it is a different language that is a > lot less dynamic than Python. Actually, Cython is able to do this because it knows the global scope of a module. The only thing that this optimisation makes impossible when you compile your module using Cython is to inject builtins into the module namespace *after* the compilation, either by assigning module attributes or by importing the module into a custom namespace. Given that both use cases are extremely rare, it was decided that optimisations like this are more important than the ability to redefine the most common builtins (such as 'range' or 'enumerate'). So, in a way, Cython really makes them "builtins". Stefan From steve at REMOVE-THIS-cybersource.com.au Mon Aug 17 09:23:14 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Aug 2009 13:23:14 GMT Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: <0012dd1f$0$2904$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 15:35:26 -0700, sturlamolden wrote: > On 16 Aug, 14:57, Dennis Lee Bieber wrote: > >> ? ? ? ? Well, the alternative would be to have two keywords for >> ? ? ? ? looping: one >> for your "simple" incrementing integer loop, and another for a loop >> that operates over the elements of some collection type. > > A compiler could easily recognise a statement like > > for i in range(n): > > as a simple integer loop. "Easily" huh? Would you like to put a small wager on that? Here is an unedited copy-and-paste of the last few lines of an interactive Python session: >>> for i in range(5): ... print i ... 0 1 2 Surprise! 4 >>> __builtins__.range is range True Can you determine how I did this? How would the compiler avoid this? If you can find a method for the compiler to avoid surprises like this, why do you think it would be valuable to add all that extra complexity to the language? (As opposed to an external tool like Cython.) -- Steven From stefan_ml at behnel.de Mon Aug 17 09:24:17 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 17 Aug 2009 15:24:17 +0200 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: <4a895a01$0$32674$9b4e6d93@newsspool2.arcor-online.net> John Machin wrote: > On Aug 17, 8:35 am, sturlamolden wrote: > >> A compiler could easily recognise a statement like >> for i in range(n): >> as a simple integer loop. In fact, Cython is able to do this. > > Extremely easy, once users relinquish the right to replace built-in > "range" with their own concoctions ... Cython allows you to do that. You just have to do it inside the module. If Cython determines that "range" refers the global builtin name, it will enable the loop optimisation. If you assign anything to that global name inside your module (even the range function itself), this will disable the optimisation. Stefan From terry.yinzhe at gmail.com Mon Aug 17 09:38:48 2009 From: terry.yinzhe at gmail.com (Terry Yin) Date: Mon, 17 Aug 2009 21:38:48 +0800 Subject: ignored test cases in unittest In-Reply-To: References: <873a7so66v.fsf@benfinney.id.au> <56527679-4cec-49a1-9b46-c38de8f981c8@g10g2000yqh.googlegroups.com> Message-ID: On Aug 17, 8:23 pm, David House wrote: > > Note that the unittest module now supports the `skip' and > `expectedFailure' decorators, which seem to describe some of the > solutions here. > > Seehttp:// docs.python.org/3.1/library/unittest.html#skipping-tests-and-e... > > -- > -David Yes, indeed! I'm using 2.6 now. It seemed I need to copy untitest.py from 3.1. But the docs.python.org is hell slow from where I am (China), not even working except the title:-( br, Terry On Mon, Aug 17, 2009 at 8:23 PM, David House wrote: > 2009/8/16 Terry : > > Thanks for the solutions. I think the decorator idea is what I'm look > > for:-) > > Note that the unittest module now supports the `skip' and > `expectedFailure' decorators, which seem to describe some of the > solutions here. > > See > http://docs.python.org/3.1/library/unittest.html#skipping-tests-and-expected-failures > > -- > -David > -- ------------------------- Blog: http://terry-yinzhe.spaces.live.com/ twitter: http://twitter.com/terryyin -------------- next part -------------- An HTML attachment was scrubbed... URL: From drobinow at gmail.com Mon Aug 17 10:04:14 2009 From: drobinow at gmail.com (David Robinow) Date: Mon, 17 Aug 2009 10:04:14 -0400 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <24980842.post@talk.nabble.com> <4A8612CE.7080700@stoneleaf.us> <200908160830.55031.emmanuel.surleau@gmail.com> Message-ID: <4eb0089f0908170704y664a3031ufed176ada36cc2c@mail.gmail.com> On Sun, Aug 16, 2009 at 11:10 PM, Nobody wrote: > Java also has iterators; it's more a case of people coming from C and BASIC. > > Although, some of those may have come *through* Java without abandoning > old habits. You see the same thing with people coming from BASIC to C and > writing: > > ? ? ? ?#define NUM_DATES 50 > ? ? ? ?int day[NUM_DATES], month[NUM_DATES], year[NUM_DATES]; > > rather than defining a "struct". > > Sometimes referred to as "I know ten languages and can write in BASIC in > all of them". Ha, ha. I learned that pattern in Fortran. I confess to having written code like that in C. I think I've gotten over it. From invalid at invalid Mon Aug 17 10:04:42 2009 From: invalid at invalid (Grant Edwards) Date: Mon, 17 Aug 2009 09:04:42 -0500 Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> Message-ID: On 2009-08-17, Sjoerd Mullender wrote: > Also in The Netherlands, ZIP codes are much more fine-grained than in > some other countries: ZIP code plus house number together are sufficient > to uniquely identify an address. I.e. you don't need the street name. > E.g., my work address has ZIP code 1098 XG and house number 123, so > together they indicate that I work at Science Park 123, Amsterdam. > > In other words, a simple city <-> ZIP mapping is not sufficient. Same here in the US. A 5-digit zip code narrows it down to a neghborhood within a city, and a full 9-digit zip code is shared with perhaps 5-10 houses -- generally I believe it identifies one side of a one-block section of a street in a single-family-home residential area. In apartment or office buildings a 9-digit zip code generally identifies a specific floor in a specific building. Most companies of any size have their own zip code (or codes). My company only has ~40 employees, and we have our own unique zip code. -- Grant Edwards grante Yow! Here I am at the flea at market but nobody is buying visi.com my urine sample bottles ... From aaron.watters at gmail.com Mon Aug 17 10:05:21 2009 From: aaron.watters at gmail.com (Aaron Watters) Date: Mon, 17 Aug 2009 07:05:21 -0700 (PDT) Subject: off topic: google groups sucks? Message-ID: <087f64b6-0cc7-4a75-a2ba-9ca74d31f1fd@o32g2000yqm.googlegroups.com> Just a note. It seems that google groups is increasing the sucks coefficient. I search for things using "group search" for comp.lang.python and I get no results even though I know there are results from a few months or weeks ago. What is the best alternative for this kind of trawling? gmane? With all the smart people working at google how can they **** up like this? Inquiring minds want to know. -- Aaron Watters === Sisyphus got ripped. From jkn_gg at nicorp.f9.co.uk Mon Aug 17 10:46:14 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Mon, 17 Aug 2009 07:46:14 -0700 (PDT) Subject: off topic: google groups sucks? References: <087f64b6-0cc7-4a75-a2ba-9ca74d31f1fd@o32g2000yqm.googlegroups.com> Message-ID: On Aug 17, 3:05?pm, Aaron Watters wrote: > Just a note. ?It seems that google groups is increasing the > sucks coefficient. > > I search for things using "group search" for comp.lang.python > and I get no results even though I know there are results from > a few months or weeks ago. There seems to be a problem with Google Searching 'at the moment'. I have seen it with other groups, but not noticed it to date on c.l.p. http://groups.google.com/group/groupsknownissues/browse_thread/thread/d88d02f269a7d20d# J^n From chris at simplistix.co.uk Mon Aug 17 10:53:08 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 17 Aug 2009 15:53:08 +0100 Subject: httplib incredibly slow :-( In-Reply-To: References: <4A81D3CB.7080209@simplistix.co.uk> Message-ID: <4A896ED4.8000509@simplistix.co.uk> i3dmaster wrote: > Just wanted to check if you can try turning on the debug mode for > httplib and see if you can read a bit more debug info on where the > calls get hung. In your example, it would be conn.set_debuglevel(1) I had a look through the code this debug level controls and I don't see any information that this provides which would help here... Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From stefan_ml at behnel.de Mon Aug 17 11:11:10 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 17 Aug 2009 17:11:10 +0200 Subject: off topic: google groups sucks? In-Reply-To: References: <087f64b6-0cc7-4a75-a2ba-9ca74d31f1fd@o32g2000yqm.googlegroups.com> Message-ID: <4a89730e$0$32667$9b4e6d93@newsspool2.arcor-online.net> jkn wrote: > On Aug 17, 3:05 pm, Aaron Watters wrote: >> Just a note. It seems that google groups is increasing the >> sucks coefficient. >> >> I search for things using "group search" for comp.lang.python >> and I get no results even though I know there are results from >> a few months or weeks ago. > > There seems to be a problem with Google Searching 'at the moment'. I > have seen it with other groups, but not noticed it to date on c.l.p. > > http://groups.google.com/group/groupsknownissues/browse_thread/thread/d88d02f269a7d20d# I noticed a problem with Google in general this weekend, not even related to mailing lists. I can't remember getting similarly bad results from a web search for years. Even trivial queries that worked for months returned completely unrelated pages and lacked the "obvious" target page in the result set. Stefan From jjposner at optimum.net Mon Aug 17 11:31:30 2009 From: jjposner at optimum.net (John Posner) Date: Mon, 17 Aug 2009 11:31:30 -0400 Subject: XML parsing with python In-Reply-To: References: Message-ID: <4A8977D2.1020801@optimum.net> > Use the iterparse() function of the xml.etree.ElementTree package. > > http://effbot.org/zone/element-iterparse.htm > http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk > > Stefan > iterparse() is too big a hammer for this purpose, IMO. How about this: from xml.etree.ElementTree import ElementTree tree = ElementTree(None, "myfile.xml") for elem in tree.findall('//book/title'): print elem.text -John From wiggly at wiggly.org Mon Aug 17 11:42:40 2009 From: wiggly at wiggly.org (Nigel Rantor) Date: Mon, 17 Aug 2009 16:42:40 +0100 Subject: zip codes In-Reply-To: <4A892F2B.4020507@mrabarnett.plus.com> References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> <4A8914DD.4000307@acm.org> <4A892F2B.4020507@mrabarnett.plus.com> Message-ID: <4A897A70.3050100@wiggly.org> MRAB wrote: > Sjoerd Mullender wrote: >> Martin P. Hellwig wrote: >>> Shailen wrote: >>>> Is there any Python module that helps with US and foreign zip-code >>>> lookups? I'm thinking of something that provides basic mappings of zip >>>> to cities, city to zips, etc. Since this kind of information is so >>>> often used for basic user-registration, I'm assuming functionality of >>>> this sort must be available for Python. Any suggestions will be much >>>> appreciated. >>>> >>> There might be an associated can of worms here, for example in the >>> Netherlands zip codes are actually copyrighted and require a license if >>> you want to do something with them, on the other hand you get a nice SQL >>> formatted db to use it. I don't know how this works in other countries >>> but I imagine that it is likely to be generally the same. >>> >> >> Also in The Netherlands, ZIP codes are much more fine-grained than in >> some other countries: ZIP code plus house number together are sufficient >> to uniquely identify an address. I.e. you don't need the street name. >> E.g., my work address has ZIP code 1098 XG and house number 123, so >> together they indicate that I work at Science Park 123, Amsterdam. >> >> In other words, a simple city <-> ZIP mapping is not sufficient. >> > The same comment applies to UK postcodes, which are also alphanumeric. > My home postcode, for example, is shared with only 3 other houses, IIRC. Kind of off-topic...but nevertheless... Yes, the UK postcode database (PAF) can be bought from the Royal Mail for a fee. The data cannot be copyright, but the version they maintain and distribute is. As an aside, the PAF has finer grained information than simply the postal code, every letterbox in the UK has (or is meant to) a DPS (delivery point suffix), so that given a post code and DPS you can uniquely identify individual letterbox even when, for example, a house has been split into multiple flats. So, nastily, you *can* identify individual letterboxes, but the Royal Mail does not publicise the fact, so you cannot actually look at a post code on a letter and determine the letterbox it is intended for. Shame really. n From aahz at pythoncraft.com Mon Aug 17 11:44:27 2009 From: aahz at pythoncraft.com (Aahz) Date: 17 Aug 2009 08:44:27 -0700 Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: In article <461cc6f1-fc23-4bc7-a719-6f29babf8bcd at o15g2000yqm.googlegroups.com>, Robert Dailey wrote: > >It's a figure of speech. And besides, why would I want programming >advice from a woman? lol. Thanks for the help. Well, I'm sorry to see this, it means I was wrong about the lack of sexism in the Python community. I encourage anyone who wants to improve the situation to join the new diversity list: http://mail.python.org/mailman/listinfo/diversity -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From ethan at stoneleaf.us Mon Aug 17 12:24:26 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 17 Aug 2009 09:24:26 -0700 Subject: Python 'for' loop is memory inefficient In-Reply-To: <200908160830.55031.emmanuel.surleau@gmail.com> References: <24980842.post@talk.nabble.com> <4A8612CE.7080700@stoneleaf.us> <200908160830.55031.emmanuel.surleau@gmail.com> Message-ID: <4A89843A.6090308@stoneleaf.us> Emmanuel Surleau wrote: >>Dr. Phillip M. Feldman wrote: > > > [snip] > > >>>def is_prime(n): >>> for j in range(2,n): >>> if (n % j) == 0: return False >>> return True >>> >>>It seems as though Python is actually expanding range(2,n) into a list of >>>numbers, even though this is incredibly wasteful of memory. There should >>>be a looping mechanism that generates the index variable values >>>incrementally as they are needed. >> [snip] >> >>I will also observe that if you were to stop programming whatever >>language you are more familiar with in Python, and start programming >>Python in Python, you'll have an easier time of it. > > > I don't see what's particularly un-Pythonic with this code. Not using xrange() > is a mistake, certainly, but it remains clear, easily understandable code > which correctly demonstrates the naive algorithm for detecting whether n is a > prime. It doesn't call for condescension > [snip] > > Cheers, > > Emm My comment about programming Python in Python was geared more towards the subject line than the actual code, and the biases evident in his comments in both this thread and earlier ones. ~Ethan~ From invalid at invalid Mon Aug 17 12:32:08 2009 From: invalid at invalid (Grant Edwards) Date: Mon, 17 Aug 2009 11:32:08 -0500 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> Message-ID: On 2009-08-11, Bearophile wrote: > Robert Dailey: > >> This breaks the flow of scope. Would you guys solve this >> problem by moving failMsg into global scope? Perhaps through >> some other type of syntax? > > There are gals too here. Straying a bit OT, but I find this particular issue rather fascinating. At least in the US, "guys" is now pretty much gender-neutral according to my casual research (mostly just paying attention to informal speach). Oddly, it still seems to be masculine when singular. Though one commonly hears a group of females addressed as "you guys" or refered to as "those guys", one never hears a single female referred to as "a guy" or "that guy". It is a bit tricky, however, since a phrase like "a group of guys" still seems to refer to just males since the word "guys" in that case is being applied individually to a plurality of persons rather being applied collectivelly to a single group -- if that makes any sense. I've actually discussed this with a a number of female friends, and they almost all thought the term "gals" was condescending and actually preferred to be referred to collectively as "guys". -- Grant Edwards grante Yow! You can't hurt me!! at I have an ASSUMABLE visi.com MORTGAGE!! From aaron.watters at gmail.com Mon Aug 17 12:41:14 2009 From: aaron.watters at gmail.com (Aaron Watters) Date: Mon, 17 Aug 2009 09:41:14 -0700 (PDT) Subject: off topic: google groups sucks? References: <087f64b6-0cc7-4a75-a2ba-9ca74d31f1fd@o32g2000yqm.googlegroups.com> Message-ID: <082ae712-a55f-4bd6-aa07-71f6d4c2253b@j21g2000yqe.googlegroups.com> On Aug 17, 10:05?am, Aaron Watters wrote: > Just a note. ?It seems that google groups is increasing the > sucks coefficient. I'm having better luck now using the advanced search option with queries like gadfly group:comp.lang.python which become http://groups.google.com/groups/search?q=gadfly+group:comp.lang.python The "search this group" feature still needs fixing, however. -- Aaron Watters === if you lined up all economists end to end they'd still point in different directions. -- stolen from somewhere From jeanmichel at sequans.com Mon Aug 17 13:03:56 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 17 Aug 2009 19:03:56 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> Message-ID: <4A898D7C.2080709@sequans.com> Grant Edwards wrote: > On 2009-08-11, Bearophile wrote: > >> Robert Dailey: >> >> >>> This breaks the flow of scope. Would you guys solve this >>> problem by moving failMsg into global scope? Perhaps through >>> some other type of syntax? >>> >> There are gals too here. >> > > Straying a bit OT, but I find this particular issue rather > fascinating. > > At least in the US, "guys" is now pretty much gender-neutral > according to my casual research (mostly just paying attention > to informal speach). > > Oddly, it still seems to be masculine when singular. Though one > commonly hears a group of females addressed as "you guys" or > refered to as "those guys", one never hears a single female > referred to as "a guy" or "that guy". > > It is a bit tricky, however, since a phrase like "a group of > guys" still seems to refer to just males since the word "guys" > in that case is being applied individually to a plurality of > persons rather being applied collectivelly to a single group -- > if that makes any sense. > > I've actually discussed this with a a number of female friends, > and they almost all thought the term "gals" was condescending > and actually preferred to be referred to collectively as > "guys". > > I'm no English native, but I already heard women/men referring to a group as "guys", no matter that group gender configuration. It's even used for group composed exclusively of women. Moreover it looks like a *very* friendly form, so there is really nothing to worry about it. Forms like: "Hi guys", "You guys should do something...", "Come on guys..." are very friendly and gender-neutral. JM From piet at cs.uu.nl Mon Aug 17 13:14:42 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 17 Aug 2009 19:14:42 +0200 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: >>>>> Simon Brunning (SB) wrote: >SB> 2009/8/11 Robert Dailey : >>> On Aug 11, 3:40?pm, Bearophile wrote: >>>> There are gals too here. >>> >>> It's a figure of speech. And besides, why would I want programming >>> advice from a woman? lol. Thanks for the help. >SB> Give the attitudes still prevalent in our industry (cf >SB> and many more), I'm sorry to say that I >SB> don't think this is funny. seconded -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From jeanmichel at sequans.com Mon Aug 17 13:23:39 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 17 Aug 2009 19:23:39 +0200 Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <4A89921B.4000603@sequans.com> Aahz wrote: > In article <461cc6f1-fc23-4bc7-a719-6f29babf8bcd at o15g2000yqm.googlegroups.com>, > Robert Dailey wrote: > >> It's a figure of speech. And besides, why would I want programming >> advice from a woman? lol. Thanks for the help. >> > > Well, I'm sorry to see this, it means I was wrong about the lack of > sexism in the Python community. I encourage anyone who wants to improve > the situation to join the new diversity list: > > http://mail.python.org/mailman/listinfo/diversity > Are you suggesting this list reject part of the community regarding its sexual orientation, ethnicity, size, culture? If that was the case I'd like to know about it. I would really want to know how you'd guess my gender (could be some clue somewhere), my sexual orientation, my religion and so on. How can you reject someone regarding informations you don't have ? That's the beauty of this mailing list, it has diversity, by design. We even welcome people that mixes up joke with sexist aggression, not to mention how open minded we are :o) Beside, the day you'll meet a real act of sexism in this list, please know that people talk and act on their own, do not assign their attitude to the whole community. You'll know that Python is sexist the day you'll find the title 'No women allowed' on the python main document page. JM PS : Newbies are not welcome here ! From timothywayne.cook at gmail.com Mon Aug 17 13:30:44 2009 From: timothywayne.cook at gmail.com (Tim Cook) Date: Mon, 17 Aug 2009 10:30:44 -0700 (PDT) Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: On Aug 16, 6:47?am, Terry wrote: > Hi, > > Is there a simple way (the pythonic way) to flatten a list of list? > rather than my current solution: > > new_list=[] > for l in list_of_list: > ? ? new_list.extend(l) > > or, > > new_list=reduce(lambda x,y:x.extend(y), list_of_list) > > br, Terry Well, This is not simple but it is comprhensive in that it has to do several things. I am using it to decompose deeply nested lists from Pyparsing output that may have strings in a variety of languages. Performance wise I do not know how it stacks up against the other examples but it works for me. :-) def flatten(x): """flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). All strings are converted to unicode. """ result = [] for el in x: #if isinstance(el, (list, tuple)): if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) # all strings must be unicode rtnlist=[] for x in result: if isinstance(x,str): # replace any brackets so Python doesn't think it's a list and we still have a seperator. x=x.replace('[','_') x=x.replace(']','_') try: x=unicode(x, "utf8") # need more decode types here except UnicodeDecodeError: x=unicode(x, "latin1") except UnicodeDecodeError: x=unicode(x,"iso-8859-1") except UnicodeDecodeError: x=unicode(x,"eucJP") rtnlist.append(x) return rtnlist From rami.chowdhury at gmail.com Mon Aug 17 13:33:52 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Mon, 17 Aug 2009 10:33:52 -0700 Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) In-Reply-To: <4A89921B.4000603@sequans.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <4A89921B.4000603@sequans.com> Message-ID: > You'll know that Python is sexist the day you'll find the title 'No > women allowed' on the python main document page. Good God I hope you're being ironic. On Mon, 17 Aug 2009 10:23:39 -0700, Jean-Michel Pichavant wrote: > Aahz wrote: >> In article >> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd at o15g2000yqm.googlegroups.com>, >> Robert Dailey wrote: >> >>> It's a figure of speech. And besides, why would I want programming >>> advice from a woman? lol. Thanks for the help. >>> >> >> Well, I'm sorry to see this, it means I was wrong about the lack of >> sexism in the Python community. I encourage anyone who wants to improve >> the situation to join the new diversity list: >> >> http://mail.python.org/mailman/listinfo/diversity >> > Are you suggesting this list reject part of the community regarding its > sexual orientation, ethnicity, size, culture? If that was the case I'd > like to know about it. > I would really want to know how you'd guess my gender (could be some > clue somewhere), my sexual orientation, my religion and so on. > How can you reject someone regarding informations you don't have ? > > That's the beauty of this mailing list, it has diversity, by design. > We even welcome people that mixes up joke with sexist aggression, not to > mention how open minded we are :o) > > Beside, the day you'll meet a real act of sexism in this list, please > know that people talk and act on their own, do not assign their attitude > to the whole community. > You'll know that Python is sexist the day you'll find the title 'No > women allowed' on the python main document page. > > JM > > PS : Newbies are not welcome here ! > > -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From seldan24 at gmail.com Mon Aug 17 13:43:33 2009 From: seldan24 at gmail.com (seldan24) Date: Mon, 17 Aug 2009 10:43:33 -0700 (PDT) Subject: Using a Callback Function - ftplib Message-ID: <76875cdd-30c4-4a3b-8a16-d0e2061765d7@v2g2000vbb.googlegroups.com> Hello, I'm utterly confused by something which is most likely trivial. I'm attempting to connect to an FTP server, retrieve a list of files, and store than in an array. I.e.: import ftplib ftp = ftplib.FTP(server) ftp.login(user, pass) ftp.cwd(conf['testdir']) ftp.retrlines('NLST ' + "testfile*.txt") ftp.quit() The above example works fine... and would return a list of any files that match "testfile*.txt" to standard out. The issue is I don't want that to go to stdout, I'd rather capture them within an array so I can retrieve them later. If I try something like: my_files = ftp.retrlines('NLST ' + "testfile*.txt") Then, my_files, will just print out the return code of the FTP NLST command. I'm trying to get the file names themselves. Now, I've read through the ftplib module section of the Python documentation and it says that, by default, the output goes to sys.stdout unless a callback function is used. Here is where I get utterly lost. I can certainly see the files being outputted to sys.stdout, but don't know how to capture that output... i.e. testfile1.txt testfile2.txt testfile3.txt Will show to the screen, but I can't catch it! I'm sure this is trivial... any help would be greatly appreciated. From gallium.arsenide at gmail.com Mon Aug 17 13:44:49 2009 From: gallium.arsenide at gmail.com (John Yeung) Date: Mon, 17 Aug 2009 10:44:49 -0700 (PDT) Subject: off topic: google groups sucks? References: <087f64b6-0cc7-4a75-a2ba-9ca74d31f1fd@o32g2000yqm.googlegroups.com> <082ae712-a55f-4bd6-aa07-71f6d4c2253b@j21g2000yqe.googlegroups.com> Message-ID: <784a24a3-066e-45b9-81e7-bed187e9f012@f10g2000vbf.googlegroups.com> On Aug 17, 12:41?pm, Aaron Watters wrote: > I'm having better luck now using the advanced search option > with queries like > > ? ?gadfly group:comp.lang.python > > The "search this group" feature still needs fixing, however. Thanks, Aaron, for confirming that it's not just me! I've been noticing spotty or missing results searching groups for a while now, actually, to the point that I gave up trying. Can't remember exactly when it started, but I do remember that it used to work pretty well and then suddenly got significantly worse. Also, thanks for the tip of trying advanced searches. John From 71david at libero.it Mon Aug 17 13:51:33 2009 From: 71david at libero.it (David) Date: Mon, 17 Aug 2009 19:51:33 +0200 Subject: Using a Callback Function - ftplib References: <76875cdd-30c4-4a3b-8a16-d0e2061765d7@v2g2000vbb.googlegroups.com> Message-ID: <1euafoc8zeh0q.91hedjv5ueuh$.dlg@40tude.net> Il Mon, 17 Aug 2009 10:43:33 -0700 (PDT), seldan24 ha scritto: > Hello, > > I'm utterly confused by something which is most likely trivial. I'm > attempting to connect to an FTP server, retrieve a list of files, and > store than in an array. I.e.: > > import ftplib > > ftp = ftplib.FTP(server) > ftp.login(user, pass) > ftp.cwd(conf['testdir']) Why bother with retrlines? Use the provided higer level fuctions: remotefiles = [] ftp.dir(remotefiles.append) or, if you prefer nlst remotefiles = ftp.nlst() regards david From seldan24 at gmail.com Mon Aug 17 14:10:25 2009 From: seldan24 at gmail.com (seldan24) Date: Mon, 17 Aug 2009 11:10:25 -0700 (PDT) Subject: Using a Callback Function - ftplib References: <76875cdd-30c4-4a3b-8a16-d0e2061765d7@v2g2000vbb.googlegroups.com> <1euafoc8zeh0q.91hedjv5ueuh$.dlg@40tude.net> Message-ID: On Aug 17, 1:51?pm, David <71da... at libero.it> wrote: > Il Mon, 17 Aug 2009 10:43:33 -0700 (PDT), seldan24 ha scritto: > > > Hello, > > > I'm utterly confused by something which is most likely trivial. ?I'm > > attempting to connect to an FTP server, retrieve a list of files, and > > store than in an array. ?I.e.: > > > import ftplib > > > ftp = ftplib.FTP(server) > > ftp.login(user, pass) > > ftp.cwd(conf['testdir']) > > Why bother with retrlines? Use the provided higer level fuctions: > > remotefiles = [] > ftp.dir(remotefiles.append) > > or, if you prefer nlst > > remotefiles = ftp.nlst() > > regards > david I didn't even notice the higher level methods. I changed the retrieval line to: ftp.nlst("testfile*.txt") This works great. The result is even captured in an array. I really have no idea what the difference between a LIST and NLST is within FTP. Never delved that deep into it. I did notice that an NLST will return a specific FTP code if a file doesn't exist, whereas a LIST doesn't. So, I ended up using NLST as that'll generate an ftplib.error_perm exception. Based on if the job cares if a file is not available or not (some do, some don't), I'll either exit, or continue on with the file loop. Anyway, thanks again, works perfectly, next time I'll try to scroll down and read a bit more prior to posting! From nad at acm.org Mon Aug 17 14:25:30 2009 From: nad at acm.org (Ned Deily) Date: Mon, 17 Aug 2009 11:25:30 -0700 Subject: Uninstalling mac python2.5 to install python2.6 References: <83423F73-83DA-436B-A3BA-E83CD61CD28D@cs.stir.ac.uk> Message-ID: In article <83423F73-83DA-436B-A3BA-E83CD61CD28D at cs.stir.ac.uk>, Farhan Sheikh wrote: > i originally had python2.5 on my mac at the univeristy and had to get > 2.6 to get NEST and pyNN to work together. however now as those are > now installed, i had to install numpy. > > As i installed numpy, it only installed its directories into the > python2.5 folders and as i am new to to mac terminals i don't know how > to change its directories to be installed into python2.6. my question > is, do i have to uninstall python 2.5 so that only python2.6 is on the > machine or is there a way to change the path so it saves into python2.5? There appears to be a NumPy installer image for Python 2.6 and OX 10.5 here: http://sourceforge.net/projects/numpy/files/ Multiple versions of python can co-exist on OS X. You definitely should not remove the Apple-supplied python2.5 (linked to from /usr/bin/python) in 10.5. -- Ned Deily, nad at acm.org From fidellira.6 at gmail.com Mon Aug 17 14:26:05 2009 From: fidellira.6 at gmail.com (axl456) Date: Mon, 17 Aug 2009 11:26:05 -0700 (PDT) Subject: GUI interface builder for python References: Message-ID: <21bca3cf-b2c7-47d7-9142-26c9fd015f92@r27g2000vbn.googlegroups.com> On Aug 17, 1:59?am, "L at D@n" wrote: > Which is the best GUI interface builder with drag and drop > capabilities. > I am using Ubuntu GNU/Linux. > Please help me. > Thank you. boa is really nice.. From pavlovevidence at gmail.com Mon Aug 17 14:32:29 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 11:32:29 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> Message-ID: On Aug 17, 4:40?am, exar... at twistedmatrix.com wrote: > On 02:12 am, pavlovevide... at gmail.com wrote: > > > > >On Aug 16, 3:35?pm, sturlamolden wrote: > >>On 16 Aug, 14:57, Dennis Lee Bieber wrote: > > >> > ? ? ? ? Well, the alternative would be to have two keywords for > >>looping: one > >> > for your "simple" incrementing integer loop, and another for a loop > >>that > >> > operates over the elements of some collection type. > > >>A compiler could easily recognise a statement like > > >>? ?for i in range(n): > > >>as a simple integer loop. > > >It would be a simple to do if you were writing it for a different > >langauge was a lot less dynamic than Python is. ?It'd be quite a > >complex hack to add it to CPython's compiler while maintaing the > >current highly dynamic runtime semantics and backwards compatibility, > >which is a design constraint of Python whether you like it or not. > > In your other message, you said this wasn't a legitimate CPython > complaint. ?Here, you say that it would be a "complex hack" to implement > this in CPython. ?"complex hack" has negative connotations in my mind. > This seems contradictory to me. Well, you missed the point, chief. It's not a legitimate complaint because you can use xrange, you don't need compiler magic to recognize and optimize range. Carl Banks From zorigaman at gmail.com Mon Aug 17 14:46:21 2009 From: zorigaman at gmail.com (Zorigaman) Date: Mon, 17 Aug 2009 11:46:21 -0700 (PDT) Subject: Embedding a python console inside a python application Message-ID: Hi, I am starting an application in which I would like to have some scripting functionality. It will obviously be done in Python. The thing is that I would like my scripts to have access to the rest of the application as an object it could manipulate. I made some research and I found the code module, which allows to have a Python interpreter inside an application, but I am not sure if I can access to the "parent" which created this interpreter. A solution could be to launch my application through an interpreter, but the problem there is how to integrate it back into the GUI, redirecting streams ? Another option is the cmd module, but here, same problem, I am not sure if can have access to my application's objects. I am using PyQt with Python 2.6.1, I could switch to Python 3.0 if necessary. I am familiar with programming, but that's my first script-enabled application, tell me if I am missing something obvious. http://docs.python.org/library/code.html http://docs.python.org/library/cmd.html From jurgenex at hotmail.com Mon Aug 17 14:48:43 2009 From: jurgenex at hotmail.com (Jürgen Exner) Date: Mon, 17 Aug 2009 11:48:43 -0700 Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: Jon Harrop wrote: >Xah Lee wrote: [...] Please do not feed this well-known troll. He is known to spew some remotely on-topic junk into a bunch of unrelated NGs and to enjoy the ensuing confusion. jue From no.email at please.post Mon Aug 17 15:05:26 2009 From: no.email at please.post (kj) Date: Mon, 17 Aug 2009 19:05:26 +0000 (UTC) Subject: XPath support? References: Message-ID: In Kev Dwyer writes: >On Sun, 16 Aug 2009 20:29:15 +0000, kj wrote: >> I'm looking for a XML parser that produces an object with full XPath >> support. What I've been using up to now, xml.etree.ElementTree, fails >> to support Xpath predicates, as in "spam[@eggs='3']/ham". >> >> What I'm trying to do is to read-in a large XML string, and parse it >> into an object from which I can extract nodes matching selectors that >> include such predicates. >> >> Any suggestions would be greatly appreciated. >> >> TIA! >> >> kynn >Have you tried lxml (http://codespeak.net/lxml/)? Thanks! (To Diez too!) kynn From no.email at please.post Mon Aug 17 15:10:22 2009 From: no.email at please.post (kj) Date: Mon, 17 Aug 2009 19:10:22 +0000 (UTC) Subject: Data visualization in Python Message-ID: I'm looking for a good Python package for visualizing scientific/statistical data. (FWIW, the OS I'm interested in is Mac OS X). The users of this package will be experimental biologists with little programming experience (but currently learning Python). (I normally visualize data using R or Mathematica, but I don't want to saddle these novices with the task of learning yet another language.) TIA! kynn From bruce at cenderis.demon.co.uk Mon Aug 17 15:13:29 2009 From: bruce at cenderis.demon.co.uk (Bruce Stephens) Date: Mon, 17 Aug 2009 20:13:29 +0100 Subject: python doc available in emacs info format? References: <4a893f9a$0$307$14726298@news.sunsite.dk> Message-ID: <87d46u9rty.fsf@cenderis.demon.co.uk> "Colin S. Miller" writes: [...] > Ubuntu maintains a package search site, it is on > http://packages.ubuntu.com/ > > However, there seems to be no files named > python.*info (regexp) And yet there are info files in python2.5-doc: . [...] From paul at boddie.org.uk Mon Aug 17 15:22:16 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 17 Aug 2009 12:22:16 -0700 (PDT) Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <704d9cc8-fa9a-4e7e-8d7a-bb130935d10a@24g2000yqm.googlegroups.com> On 17 Aug, 19:23, Jean-Michel Pichavant wrote: > > Are you suggesting this list reject part of the community regarding its > sexual orientation, ethnicity, size, culture? If that was the case I'd > like to know about it. Careful: you probably meant to write "rejects", not "reject". That changes the meaning of what you've written somewhat. > I would really want to know how you'd guess my gender (could be some > clue somewhere), my sexual orientation, my religion and so on. > How can you reject someone regarding informations you don't have ? Well, everyone can of course hide their actual identity on the Internet, but when someone references a group of people with a juvenile remark (if we are being charitable about the matter), it has nothing to do with guessing the characteristics of individuals. The whole excuse that anonymity defends against insults and harassment is a bit like saying that slinging mud at everyone is acceptable as long as everyone is encouraged to do it and nobody is wearing their nicest clothes. And unless your idea of a Python-related conference is something close to a fancy-dress event with everyone "in character" - which would obviously limit the effectiveness of such an event - you presumably understand that there is a genuine need for continuity between interactions on and off the Internet. This somewhat undermines your argument. > That's the beauty of this mailing list, it has diversity, by design. An explanation is needed here for this not to sound like conversational padding. > We even welcome people that mixes up joke with sexist aggression, not to > mention how open minded we are :o) Well, jokes actually need an amusing side, regardless of how "edgy" ("juvenile" is typically the more accurate term) the joke- teller is trying to be, and that was completely absent from the remark in question. There's little room for error in communication over a medium like this one, as I pointed out with your opening sentence. And much as it probably upsets the "unfettered free speech" advocates, we should be able to assert that "sexist aggression" is not acceptable behaviour amongst those who seek to participate in our community. Paul From invalid at invalid Mon Aug 17 15:29:36 2009 From: invalid at invalid (Grant Edwards) Date: Mon, 17 Aug 2009 14:29:36 -0500 Subject: Data visualization in Python References: Message-ID: On 2009-08-17, kj wrote: > I'm looking for a good Python package for visualizing > scientific/statistical data. (FWIW, the OS I'm interested in > is Mac OS X). Both matplotlib and gnuplot-py can produce pretty good results with a minimum of effort: http://matplotlib.sourceforge.net/ http://gnuplot-py.sourceforge.net/ I lean more towards gnuplot, but that's probably just a bias from having used Gnuplot for 10+ years before learning Python. Both matplotlib and gnuplot are basically 2D packages with some 3D features. There's also a Python binding for VTK. I found it a bit harder to use for the stuff I did, but sophisticated 3D stuff it's probably the winner: http://www.vtk.org/ [It also has the only Delaunay triangulation module (of the 3 that I tried) that worked reliably, but you probably don't care about that.] -- Grant Edwards grante Yow! Let me do my TRIBUTE at to FISHNET STOCKINGS ... visi.com From invalid at invalid Mon Aug 17 15:36:18 2009 From: invalid at invalid (Grant Edwards) Date: Mon, 17 Aug 2009 14:36:18 -0500 Subject: Data visualization in Python References: Message-ID: On 2009-08-17, Grant Edwards wrote: > On 2009-08-17, kj wrote: > >> I'm looking for a good Python package for visualizing >> scientific/statistical data. (FWIW, the OS I'm interested in >> is Mac OS X). > > Both matplotlib and gnuplot-py can produce pretty good results > with a minimum of effort: Oh, just in case you haven't found them, you might also be interested in the SciPy and Scientific Python projects: http://www.scipy.org/ http://sourcesup.cru.fr/projects/scientific-py/ Though they have deceptively similar names, they're two separate projects. Unfortunately, some rather promenent documentation conflates the two. For example, http://docs.python.org/3.1/tutorial/whatnow.html refers to www.scipy.org as "the Scientific Python" project. -- Grant Edwards grante Yow! I hope the at ``Eurythmics'' practice visi.com birth control ... From exarkun at twistedmatrix.com Mon Aug 17 15:41:55 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 17 Aug 2009 19:41:55 -0000 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> Message-ID: <20090817194155.8740.902674574.divmod.xquotient.69@localhost.localdomain> On 06:32 pm, pavlovevidence at gmail.com wrote: >On Aug 17, 4:40?am, exar... at twistedmatrix.com wrote: >>On 02:12 am, pavlovevide... at gmail.com wrote: >> >> >> >> >On Aug 16, 3:35?pm, sturlamolden wrote: >> >>On 16 Aug, 14:57, Dennis Lee Bieber wrote: >> >> >> > ? ? ? ? Well, the alternative would be to have two keywords for >> >>looping: one >> >> > for your "simple" incrementing integer loop, and another for a >>loop >> >>that >> >> > operates over the elements of some collection type. >> >> >>A compiler could easily recognise a statement like >> >> >>? ?for i in range(n): >> >> >>as a simple integer loop. >> >> >It would be a simple to do if you were writing it for a different >> >langauge was a lot less dynamic than Python is. ?It'd be quite a >> >complex hack to add it to CPython's compiler while maintaing the >> >current highly dynamic runtime semantics and backwards compatibility, >> >which is a design constraint of Python whether you like it or not. >> >>In your other message, you said this wasn't a legitimate CPython >>complaint. ?Here, you say that it would be a "complex hack" to >>implement >>this in CPython. ?"complex hack" has negative connotations in my mind. >>This seems contradictory to me. > >Well, you missed the point, chief. > >It's not a legitimate complaint because you can use xrange, you don't >need compiler magic to recognize and optimize range. There's a lot of things in Python that I don't strictly *need*. That doesn't mean that they wouldn't be welcome if I could have them. Getting rid of the range/xrange dichotomy would improve things. Yes, I can work around it until the runtime is good enough to let me think about an *interesting* problem instead. That makes it a legitimate complaint in my eyes. You're welcome to disagree, of course, but do you have an argument more compelling than the one you give here? It seems to me one could use it to argue a lot of Python out of existence. Chief. (Seriously, "chief"? What are you going for? It sounds like condescension to me; what's the point of that? I hope I'm just misreading you.) Jean-Paul From jon at ffconsultancy.com Mon Aug 17 15:42:38 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 17 Aug 2009 20:42:38 +0100 Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: Xah Lee wrote: > On Aug 12, 12:15 pm, Raymond Hettinger wrote: >> * The reason for implementing the key= parameter had nothing to do >> with limitations of Python's compiler. Instead, it was inspired by >> the >> decorate-sort-undecorate pattern. > > The decorate-sort-undecorate pattern is a compiler limitation, for > most of today's langs. I'm not sure, but i think some of the fancy > functional langs automatically detect such and optimize it away, to > various degrees. You mean people use that pattern as a fast alternative in languages where user-defined functions are very slow, like Python and Mathematica? -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From brochu121 at gmail.com Mon Aug 17 15:51:19 2009 From: brochu121 at gmail.com (David Brochu) Date: Mon, 17 Aug 2009 15:51:19 -0400 Subject: comparing XML files to eachother Message-ID: <9583ed900908171251k50fafaefrd626439bf1bd9a3c@mail.gmail.com> I need to compare one xml document to another to see if the content matches. Unfortunately, the formatting (spacing) and order of elements may change between files from run to run. I have looked into xml dom minidom but can't seem to find how to accomplish this. Does anyone know how I can do a compare between two XML documents using the STL? -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Mon Aug 17 15:59:43 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 12:59:43 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> Message-ID: <6c86d734-61b8-48e2-aa28-a62dfbd2ee75@w6g2000yqw.googlegroups.com> On Aug 17, 12:41?pm, exar... at twistedmatrix.com wrote: > There's a lot of things in Python that I don't strictly *need*. ?That > doesn't mean that they wouldn't be welcome if I could have them. > Getting rid of the range/xrange dichotomy would improve things. ?Yes, I > can work around it until the runtime is good enough to let me think > about an *interesting* problem instead. You don't have to think about using xrange in a for loop, you just always use it. >?That makes it a legitimate > complaint in my eyes. ?You're welcome to disagree, of course, but do you > have an argument more compelling than the one you give here? I am not arguing in favor of range/xrange, I am saying that it's silly to complain that the compiler isn't a whole lot more complex than it is just so it can implemnent a semantically-diconnected special case just so that you can avoid typing an extra "x". The cost doesn't even remotely justify it. Carl Banks From pavlovevidence at gmail.com Mon Aug 17 16:00:44 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 13:00:44 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> <6c86d734-61b8-48e2-aa28-a62dfbd2ee75@w6g2000yqw.googlegroups.com> Message-ID: <15810fe6-604b-49e8-8bd6-b3766bf9f993@z31g2000yqd.googlegroups.com> On Aug 17, 12:59?pm, Carl Banks wrote: >?The cost doesn't even remotely justify it. I mean, it doesn't even remotely justify the cost. Carl Banks From piet at cs.uu.nl Mon Aug 17 16:05:13 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 17 Aug 2009 22:05:13 +0200 Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> <512e67d9-8733-4329-a7d9-c6e21d6a2165@r38g2000yqn.googlegroups.com> Message-ID: >>>>> Grant Edwards (GE) wrote: >GE> On 2009-08-16, Shailen wrote: >>> Thanks Martin and Aahz. Anyone know if zip code information is >>> copyrighted for the US? >GE> You can't copyright "information" as such. Only concrete >GE> expressions of information. A particular publication >GE> containing zip code information can be copyrighted. The >GE> underlying facts themselve cannot be. But that doesn't help you if you need that information and the only way to obtain it is from copyrighted sources. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From ronn.ross at gmail.com Mon Aug 17 16:18:17 2009 From: ronn.ross at gmail.com (Ronn Ross) Date: Mon, 17 Aug 2009 16:18:17 -0400 Subject: Barcodes Message-ID: <9c8c445f0908171318x2d9d862bi35ccb398376aceca@mail.gmail.com> My company needs a small inventory management app. Does python have any libraries to help with reading and writing bar codes? -------------- next part -------------- An HTML attachment was scrubbed... URL: From aaron.watters at gmail.com Mon Aug 17 16:35:02 2009 From: aaron.watters at gmail.com (Aaron Watters) Date: Mon, 17 Aug 2009 13:35:02 -0700 (PDT) Subject: off topic: google groups sucks? References: <087f64b6-0cc7-4a75-a2ba-9ca74d31f1fd@o32g2000yqm.googlegroups.com> <082ae712-a55f-4bd6-aa07-71f6d4c2253b@j21g2000yqe.googlegroups.com> <784a24a3-066e-45b9-81e7-bed187e9f012@f10g2000vbf.googlegroups.com> Message-ID: <51877a03-b6de-4131-90d8-13cd618236aa@v20g2000yqm.googlegroups.com> On Aug 17, 1:44?pm, John Yeung wrote: > Thanks, Aaron, for confirming that it's not just me! yea, unfortunately this kind of thing happens in monopolies that have no viable competition anymore... Sometimes I begin to suspect that I'm seeing the results that I should want rather than the results I want. (Lucene has this property too -- you get the results the algorithm wants you to get, rather than the results you want to get.) -- Aaron Watters === In communism the future is certain, but the past is ever changing. From jordilin at gmail.com Mon Aug 17 16:37:13 2009 From: jordilin at gmail.com (jordilin) Date: Mon, 17 Aug 2009 13:37:13 -0700 (PDT) Subject: Data visualization in Python References: Message-ID: On 17 ago, 21:10, kj wrote: > I'm looking for a good Python package for visualizing > scientific/statistical data. ?(FWIW, the OS I'm interested in is > Mac OS X). > > The users of this package will be experimental biologists with > little programming experience (but currently learning Python). > > (I normally visualize data using R or Mathematica, but I don't want > to saddle these novices with the task of learning yet another > language.) > > TIA! > > kynn Matplotlib is the one. There is Google Chart api which seems fairly easy to understand and use thanks to pygooglechart bindings. From emile at fenx.com Mon Aug 17 16:44:52 2009 From: emile at fenx.com (Emile van Sebille) Date: Mon, 17 Aug 2009 13:44:52 -0700 Subject: Barcodes In-Reply-To: <9c8c445f0908171318x2d9d862bi35ccb398376aceca@mail.gmail.com> References: <9c8c445f0908171318x2d9d862bi35ccb398376aceca@mail.gmail.com> Message-ID: On 8/17/2009 1:18 PM Ronn Ross said... > My company needs a small inventory management app. Does python have any > libraries to help with reading and writing bar codes? I've written bar code apps and python really doesn't enter into that part of things. Printers generally have bar code printing capabilities so you just send the right escape sequences and you get the bar codes. To read them, bar code readers scan and translate before sending the values through typically a keyboard wedge or serial port. Emile From hani.mousli at gmail.com Mon Aug 17 16:47:44 2009 From: hani.mousli at gmail.com (=?UTF-8?B?2YfYp9mG2Yog2KfZhNmF2YjYtdmE2Yo=?=) Date: Mon, 17 Aug 2009 13:47:44 -0700 (PDT) Subject: Strongly typed list Message-ID: Hello, I am using eclips for python and i am facing a problem. I have many classes with many properties and want a list of objects from one of my declared classes. The problem is:When i am accessing any item from the list, the IDE does not know it's type because in python we do not declare the variable with it's type, so there is no auto complete and i have to go to the class to copy the attribute name. To make idea more clear: class AutomataBranch(object): def __init__(selfparams): self.Name=""; self.nodes=[]; class LanguageAutomata(object): def __init__(selfparams): self.cfgAutomata=[];#This has AutomaBranch Type Now in any method in LanguageAutomata class if i wrote: cfgAutomata. Then it wont give me the Name attribute Is there any solution for that? Perhaps of there is some thing like C# List cfgAutomata such that the list wont accept items unless they are AutomataBranch will be good. From python.list at tim.thechases.com Mon Aug 17 16:55:23 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 17 Aug 2009 15:55:23 -0500 Subject: Barcodes In-Reply-To: References: <9c8c445f0908171318x2d9d862bi35ccb398376aceca@mail.gmail.com> Message-ID: <4A89C3BB.2030605@tim.thechases.com> >> My company needs a small inventory management app. Does >> python have any libraries to help with reading and writing >> bar codes? > > I've written bar code apps and python really doesn't enter > into that part of things. Printers generally have bar code > printing capabilities so you just send the right escape > sequences and you get the bar codes. To read them, bar code > readers scan and translate before sending the values through > typically a keyboard wedge or serial port. To add to what Emile mentions, most barcode readers present a keyboard-wedge interface, so that scanning a barcode merely appears as if you typed it at the keyboard (USB readers show up as a HID profile). Often they'll have configuration barcodes that you can scan to tweak the profile (such as pressing , or an arrow-key after sending the barcode; controlling beep tone & volume, etc). For printing barcodes, you can use any number of solutions -- the most popular usually just involves installing a "barcode font" and then rendering text in that font to your desired output canvas. I believe there are some native rendering solutions as well, but I've not investigated since the font method was more than sufficient for my wants. -tkc From http Mon Aug 17 16:56:13 2009 From: http (Paul Rubin) Date: 17 Aug 2009 13:56:13 -0700 Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: <7xtz06cg7m.fsf@ruckus.brouhaha.com> Jon Harrop writes: > You mean people use that pattern as a fast alternative in languages where > user-defined functions are very slow, like Python and Mathematica? It really doesn't matter whether the language is fast or slow--there are going to be applications where calling the comparison function multiple times per element is slower than calling it once per element and storing the result. Note the Haskell idiom (sortBy (compare`on`f) xs) is similar to DSU but calls the comparison function multiple times. Python 3.0 went overboard by actually removing the cmp argument and requiring use of the key argument. That requires various kludges if the key is, say, a tree structure that has to be recursively compared with another such structure. Maybe then can bring back cmp someday. From pavlovevidence at gmail.com Mon Aug 17 17:06:04 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 14:06:04 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> Message-ID: <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> On Aug 17, 10:03?am, Jean-Michel Pichavant wrote: > I'm no English native, but I already heard women/men referring to a > group as "guys", no matter that group gender configuration. It's even > used for group composed exclusively of women. Moreover it looks like a > *very* friendly form, so there is really nothing to worry about it. I like how being very friendly means calling people after a guy who tried to blow up the English Parliament. Carl Banks From xahlee at gmail.com Mon Aug 17 17:09:54 2009 From: xahlee at gmail.com (Xah Lee) Date: Mon, 17 Aug 2009 14:09:54 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. References: <25203724-bf60-484f-9ede-e61c45f15e33@s31g2000yqs.googlegroups.com> Message-ID: http://www.stephenwolfram.com/publications/recent/mathml/index.html i was trying to find the publication date and context, but didn't find it last time after a couple min. Yesterday, on rereading, i did. The article in question is: ? Mathematical Notation: Past and Future (2000) Stephen Wolfram October 20, 2000 Transcript of a keynote address presented at MathML and Math on the Web: MathML International Conference 2000 ? so, it's a speech for MathML conf in 2000. so, this explains the error on the plimpton 322. The latest discovery on that is published in 2002 and later. the date of this speech also explains parts of the writings about some mysterious ?fundamental science work?, which now we know is his controversial book A New Kind Of Science (2002). Xah ? http://xahlee.org/ ? ---------------------- Xah Lee wrote: Personally, particular interesting info i've learned is that, for all my trouble in the past decade expressing problems of traditional math notation, i learned from his article this single-phrase summary: ?traditional math notation lacks a grammar?. The article is somewhat disappointing though. I was expecting he'd go into some details about the science of math notations, or, as he put it aptly: ?linguistics of math notations?. However, he didn't touch the subject, except saying that it haven't been studied. upon a more detailed reading of Stephen's article, i discovered some errors. On this page:http://www.stephenwolfram.com/publications/recent/mathml/ mathml2.html he mentions the Plimpton 322 tablet. It is widely taught in math history books, that this table is pythagorean triples. On reading his article, i wanted to refresh my understanding of the subject, so i looked up Wikipedia: http://en.wikipedia.org/wiki/Plimpton_322 and behold! apparantly, in recent academic publications, it is suggested that this is not pythagorean triples, but rather: ?a list of regular reciprocal pairs?. Xah ?http://xahlee.org/ ? From pavlovevidence at gmail.com Mon Aug 17 17:12:51 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 14:12:51 -0700 (PDT) Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: On Aug 17, 8:44?am, a... at pythoncraft.com (Aahz) wrote: > In article <461cc6f1-fc23-4bc7-a719-6f29babf8... at o15g2000yqm.googlegroups.com>, > Robert Dailey ? wrote: > > > > >It's a figure of speech. And besides, why would I want programming > >advice from a woman? lol. Thanks for the help. > > Well, I'm sorry to see this, it means I was wrong about the lack of > sexism in the Python community. Oh come on, one newbie making an off-color joke is not any sort of reflection of the community as a whole. Anyway it's pretty naive to expect what is now a large community to avoid bad eggs altogether. Price you pay for popularity. Carl Banks From fabiofz at gmail.com Mon Aug 17 17:13:10 2009 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 17 Aug 2009 18:13:10 -0300 Subject: Strongly typed list In-Reply-To: References: Message-ID: > Hello, I am using eclips for python and i am facing a problem. I have > many classes with many properties and want a list of objects from one > of my declared classes. The problem is:When i am accessing any item > from the list, the IDE does not know it's type because in python we do > not declare the variable with it's type, so there is no auto complete > and i have to go to the class to copy the attribute name. To make idea > more clear: > > class AutomataBranch(object): > ? ?def __init__(selfparams): > ? ? ? ?self.Name=""; > ? ? ? ?self.nodes=[]; > > class LanguageAutomata(object): > ? ?def __init__(selfparams): > ? ? ? ?self.cfgAutomata=[];#This has AutomaBranch Type > Now in any method in LanguageAutomata class if i wrote: cfgAutomata. > Then it wont give me the Name attribute Is there any solution for > that? > Perhaps of there is some thing like C# List > cfgAutomata such that the list wont accept items unless they are > AutomataBranch will be good. Hello, Unfortunately, right now there is no way to gather that specific code completion in pydev -- because of the dynamic nature of python, that info is very hard to get. Best Regards, Fabio From hani.mousli at gmail.com Mon Aug 17 17:19:01 2009 From: hani.mousli at gmail.com (=?UTF-8?B?2YfYp9mG2Yog2KfZhNmF2YjYtdmE2Yo=?=) Date: Mon, 17 Aug 2009 14:19:01 -0700 (PDT) Subject: Strongly typed list References: Message-ID: <7718922b-c72c-4a7e-90a3-098318063013@n11g2000yqb.googlegroups.com> Please could you lead me to a way or a good IDE that makes developing huge projects in python more easier than what i found.Now i am using eclips. Actually it is very hard to remember all my classes methods and attributes or copy and paste them each time. Thanks very much for your interest Hani Almousli..... From xahlee at gmail.com Mon Aug 17 17:26:32 2009 From: xahlee at gmail.com (Xah Lee) Date: Mon, 17 Aug 2009 14:26:32 -0700 (PDT) Subject: python doc available in emacs info format? References: <4a893f9a$0$307$14726298@news.sunsite.dk> Message-ID: <03e865a3-5789-424c-9851-7567fcf00fa6@z31g2000yqd.googlegroups.com> > Please do not slag off a project if you want people to help; > it tends to put the goat up. a healthy community needs both positive comment as well as negative to grow. emacs's user base has been rotting off from i estimate more than 50% of programers to less that 1% today. the particular observation about info doc in this thread is a specific example. You can help FSF and emacs to improve, by, for example, trying to help it to evolve with the rapidly changing computing industry, In this case, document formats, provided if you see some of my points as valid. Or, at least consider this eroding awareness of the gnu info format among average programers worth discussing. No disrespect to you, but dismissing it as ?troll? or similiar sentiment is not helpful. emacs community is too much cult and pride. FSF and its product the GNU was highly successful in the 1980 and 1990s, with its gcc, emacs, and slew of gnu version of unix tools. A significant part of the reason is because these products at the time is truely better products in comparison to existing ones, that there are almost no substitute. Today, for many variety and complexity of reasons, almost none of this is true, except possiblly a few such as gcc and GPG. The unix shells ways and sed, awk, etc tools has largely been replaced by perl, python, ruby etc, partly due to the changing nature of computing. For GCC itself, and make, yacc, bison etc there are tens of competiting products either commercial or open source. Then there's Java, with its entire suite of tools and libs, and there are tens of truely quality languages out there today other then the ones that GCC can handle. emacs 23, although is fantastic to us emacs fans, but if you look carefully at its feature list, most of it is widely in commericial software about 10 years ago. Xah ? http://xahlee.org/ ? On Aug 17, 4:32 am, "Colin S. Miller" wrote: > Xah Lee wrote: > > btw, is there still info format for python doc? > > > i feel kinda sad that emacs info format has pretty much been > > deprecated over the past decade. About a decade ago, you still will > > see now and then people asking for emacs info format of docs (was the > > days of perl). Today, one don't hear of it. > > > Part of this is due to emacs cult problem. See: > > Xah, > > Please do not slag off a project if you want people to help; > it tends to put the goat up. > > It is not "Emacs Info" format, it is FSF Info format. > There is a stand-alone program to read the Info documentation. > The program is called "info". > > Ubuntu maintains a package search site, it is onhttp://packages.ubuntu.com/ > > However, there seems to be no files named > python.*info (regexp) > > There is a > python-docutils package > which does contain information in several > other formats. > > This package can be found either via the above site > or using "apt-cache search python-doc". > > As "info" is a FSF format, all FSF produced programs > will provide documentation in this format. However Python > is not under the auspices of the FSF, so does not need to use > this format. > > BTW, > HTML versions of INFO documentation can be generated by > info2html or info_to_html on them, or texi2html on the source. > > Have a nice day, > Colin S. Miller From clp2 at rebertia.com Mon Aug 17 17:31:51 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 17 Aug 2009 14:31:51 -0700 Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <50697b2c0908171431i36557d40wc5b85c67e0dc193d@mail.gmail.com> On Mon, Aug 17, 2009 at 2:12 PM, Carl Banks wrote: > On Aug 17, 8:44?am, a... at pythoncraft.com (Aahz) wrote: >> In article <461cc6f1-fc23-4bc7-a719-6f29babf8... at o15g2000yqm.googlegroups.com>, >> Robert Dailey ? wrote: >> >It's a figure of speech. And besides, why would I want programming >> >advice from a woman? lol. Thanks for the help. >> >> Well, I'm sorry to see this, it means I was wrong about the lack of >> sexism in the Python community. > > Oh come on, one newbie making an off-color joke is not any sort of > reflection of the community as a whole. > > Anyway it's pretty naive to expect what is now a large community to > avoid bad eggs altogether. ?Price you pay for popularity. Agreed on both points, but the lack of any reprimanding for making said inappropriate joke /would/ reflect badly on the community. Fortunately, said person's behavior has now been condemned by virtue of this thread; it's a step in the right direction. Cheers, Chris From python at mrabarnett.plus.com Mon Aug 17 17:41:54 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 17 Aug 2009 22:41:54 +0100 Subject: Need cleanup advice for multiline string In-Reply-To: <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> Message-ID: <4A89CEA2.10400@mrabarnett.plus.com> Carl Banks wrote: > On Aug 17, 10:03 am, Jean-Michel Pichavant > wrote: >> I'm no English native, but I already heard women/men referring to a >> group as "guys", no matter that group gender configuration. It's even >> used for group composed exclusively of women. Moreover it looks like a >> *very* friendly form, so there is really nothing to worry about it. > > I like how being very friendly means calling people after a guy who > tried to blow up the English Parliament. > Guy Fawkes adopted the name Guido while fighting for the Spanish in the Low Countries: http://en.wikipedia.org/wiki/Guy_Fawkes From nat.k at gm.ml Mon Aug 17 18:16:56 2009 From: nat.k at gm.ml (Nathan Keel) Date: Mon, 17 Aug 2009 15:16:56 -0700 Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: Jon Harrop wrote: > Xah Lee wrote: >> On Aug 12, 12:15 pm, Raymond Hettinger wrote: >>> * The reason for implementing the key= parameter had nothing to do >>> with limitations of Python's compiler. Instead, it was inspired by >>> the >>> decorate-sort-undecorate pattern. >> >> The decorate-sort-undecorate pattern is a compiler limitation, for >> most of today's langs. I'm not sure, but i think some of the fancy >> functional langs automatically detect such and optimize it away, to >> various degrees. > > You mean people use that pattern as a fast alternative in languages > where user-defined functions are very slow, like Python and > Mathematica? > Do not give this "Xah Lee" idiot any attention. This asshole posts only self-serving nonsense, because he thinks it makes him sound important (when in reality, he is absolutely clueless). This idiot always cross posts to 5 or more different groups that have nothing to do with his attempts to impress people (which always fail). He's incredibly arrogant, yet incredibly clueless. From zorigaman at gmail.com Mon Aug 17 18:26:23 2009 From: zorigaman at gmail.com (Zorigaman) Date: Mon, 17 Aug 2009 15:26:23 -0700 (PDT) Subject: Embedding a python console inside a python application References: Message-ID: <15807e7d-2b96-4f25-8998-7506743c5fea@a26g2000yqn.googlegroups.com> On 17 ao?t, 20:46, Zorigaman wrote: > Hi, > > I am starting an application in which I would like to have some > scripting functionality. It will obviously be done in Python. The > thing is that I would like my scripts to have access to the rest of > the application as an object it could manipulate. > I made some research and I found the code module, which allows to have > a Python interpreter inside an application, but I am not sure if I can > access to the "parent" which created this interpreter. A solution > could be to launch my application through an interpreter, but the > problem there is how to integrate it back into the GUI, redirecting > streams ? > Another option is the cmd module, but here, same problem, I am not > sure if can have access to my application's objects. > I am using PyQt with Python 2.6.1, I could switch to Python 3.0 if > necessary. > I am familiar with programming, but that's my first script-enabled > application, tell me if I am missing something obvious. > > http://docs.python.org/library/code.htmlhttp://docs.python.org/library/cmd.html D'oh. The code module offers exactly what I need, you can specify object in the interpreter's constructor. D'oh. From nospam at nospam.com Mon Aug 17 18:26:47 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 00:26:47 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? Message-ID: Hello, I need to convert DD MM YYYY dates into the MySQL-friendly YYYY-MM-DD, and translate the month name from literal French to its numeric equivalent (eg. "Janvier" into "01"). Here's an example: SELECT dateinscription, dateconnexion FROM membres LIMIT 1; 26 Mai 2007|17 Ao?t 2009 - 09h20 I'd like to update the row into "2007-05-26" and "2009-08-17 09:20", respectively. What is the best way to do this in Python? Thank you. From python at rcn.com Mon Aug 17 18:42:55 2009 From: python at rcn.com (Raymond Hettinger) Date: Mon, 17 Aug 2009 15:42:55 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: [Xah Lee] > This part i don't particular agree: > > > * The reason for implementing the key= parameter had nothing to do > > with limitations of Python's compiler. ?Instead, it was inspired by > > the > > decorate-sort-undecorate pattern. > > The decorate-sort-undecorate pattern is a compiler limitation, for > most of today's langs. I'm not sure, but i think some of the fancy > functional langs automatically detect such and optimize it away, to > various degrees. > > ... my criticism is usually written in a style catered to irritate a > particular class of coder i call tech geekers (they think of themselfs > with their idiotic term ?hackers?). So, parts are exaggerated. It'd be > more clear to say, that the reason for python's ?key?, and as a > ?solution? or need of the decorate-sort-undecorate issue, can be > attributed to the current state of the art of popular imperative > language's compilers (induced by such lang's semantics). I'm not following you here. If you're saying that it is possible for a compiler to automatically transform a cmp argument into a key argument, transforming O(n log n) calls into O(n) calls, then I don't see how that could be done (a cmp argument can be a C function that is not introspectable or an arbitrarily complex python function that may be difficult to analyze and transform programmatically). The key function was introduced as a simpler way for programmers to write the commonly used decorate-sort-undecorate pattern -- compiler limitations had nothing to do with it. In general, key functions are not a terribly new or inflexible concept. The SORT BY clauses in SQL are an example. That being said, it is a fair criticism of Python's compiler that it does not do much in the way of optimizations. It does a handful of basic peephole optimizations but that is about it. Other languages like Haskell fair better in this regard. Raymond From gregor.lingl at aon.at Mon Aug 17 19:14:57 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 18 Aug 2009 01:14:57 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <4a89e480$0$2302$91cee783@newsreader02.highway.telekom.at> Simon Forman schrieb: > On Aug 14, 8:22 pm, candide wrote: >> Suppose you need to split a string into substrings of a given size (except >> possibly the last substring). I make the hypothesis the first slice is at the >> end of the string. >> A typical example is provided by formatting a decimal string with thousands >> separator. >> >> What is the pythonic way to do this ? >> ... >> Thanks > > FWIW: > > def chunks(s, length=3): > stop = len(s) > start = stop - length > while start > 0: > yield s[start:stop] > stop, start = start, start - length > yield s[:stop] > > > s = '1234567890' > print ','.join(reversed(list(chunks(s)))) > # prints '1,234,567,890' or: >>> def chunks(s, length=3): i, j = 0, len(s) % length or length while i < len(s): yield s[i:j] i, j = j, j + length >>> print(','.join(list(chunks(s)))) 1,234,567,890 >>> print(','.join(list(chunks(s,2)))) 12,34,56,78,90 >>> print(','.join(list(chunks(s,4)))) 12,3456,7890 Regards, Gregor From ben+python at benfinney.id.au Mon Aug 17 19:30:39 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 09:30:39 +1000 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <87ab1ykogw.fsf@benfinney.id.au> Robert Dailey writes: > On Aug 11, 3:40?pm, Bearophile wrote: > > Robert Dailey: > > > This breaks the flow of scope. Would you guys solve this > > > problem by [?] > > There are gals too here. > > It's a figure of speech. Indeed. When I use the term ?guys? as a form of address, it's intended to be gender-neutral. > And besides, why would I want programming advice from a woman? lol. No, that's not worth any laughter, especially because there are still too many people who seriously think that way. It's totally unacceptable. Please don't promote sexist garbage like that here. -- \ ?With Lisp or Forth, a master programmer has unlimited power | `\ and expressiveness. With Python, even a regular guy can reach | _o__) for the stars.? ?Raymond Hettinger | Ben Finney From jearl at notengoamigos.org Mon Aug 17 19:30:59 2009 From: jearl at notengoamigos.org (Jason Earl) Date: Mon, 17 Aug 2009 17:30:59 -0600 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: <87ocqerpak.fsf@notengoamigos.org> Xah Lee writes: > Fresh out of the oven: > > ? How to use and setup Emacs's whitespace-mode > http://xahlee.org/emacs/whitespace-mode.html > > Xah > ? http://xahlee.org/ Xah, I disagree with you about the usefulness of whitespace-mode's defaults, and I certainly disagree with the need to use profanity on your usenet post on the subject, but it is hard to argue against your whitespace-mode.html page. Very well done. Thanks, Jason From jgardner at jonathangardner.net Mon Aug 17 19:55:49 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 17 Aug 2009 16:55:49 -0700 (PDT) Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: <4fa932a9-3f8e-4882-ba53-2715ba15c7cf@32g2000yqj.googlegroups.com> On Aug 17, 3:26?pm, Gilles Ganault wrote: > Hello, > > ? ? ? ? I need to convert DD MM YYYY dates into the MySQL-friendly > YYYY-MM-DD, and translate the month name from literal French to its > numeric equivalent (eg. "Janvier" into "01"). > > Here's an example: > > SELECT dateinscription, dateconnexion FROM membres LIMIT 1; > 26 Mai 2007|17 Ao?t 2009 - 09h20 > > I'd like to update the row into "2007-05-26" and "2009-08-17 09:20", > respectively. > > What is the best way to do this in Python? > > Thank you. From cmpython at gmail.com Mon Aug 17 19:58:28 2009 From: cmpython at gmail.com (Che M) Date: Mon, 17 Aug 2009 16:58:28 -0700 (PDT) Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: On Aug 17, 6:26?pm, Gilles Ganault wrote: > Hello, > > ? ? ? ? I need to convert DD MM YYYY dates into the MySQL-friendly > YYYY-MM-DD, and translate the month name from literal French to its > numeric equivalent (eg. "Janvier" into "01"). > > Here's an example: > > SELECT dateinscription, dateconnexion FROM membres LIMIT 1; > 26 Mai 2007|17 Ao?t 2009 - 09h20 > > I'd like to update the row into "2007-05-26" and "2009-08-17 09:20", > respectively. > > What is the best way to do this in Python? > > Thank you. Likely this is not the best way, but I would do, for the first one (and the same idea for the second): def convert(date): frenchdict = {'Mai':'May'} #etc... day = mystring[:2] month = frenchdict[ mystring[3:6] ] year = mystring[7:11] newdate = year+'-'+month+'-'+day print 'newdate is ', newdate From sjmachin at lexicon.net Mon Aug 17 19:59:21 2009 From: sjmachin at lexicon.net (John Machin) Date: Mon, 17 Aug 2009 16:59:21 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <56159dcf-b27d-418f-a8a4-0e4ebb71faa3@c14g2000yqm.googlegroups.com> On Aug 12, 6:52?am, Robert Dailey wrote: > On Aug 11, 3:40?pm, Bearophile wrote: > > > Robert Dailey: > > > > This breaks the flow of scope. Would you guys solve this > > > problem by moving failMsg into global scope? > > > Perhaps through some other type of syntax? > > > There are gals too here. > > This may help:http://docs.python.org/library/textwrap.html#textwrap.dedent > > > Bye, > > bearophile > > It's a figure of speech. And besides, why would I want programming > advice from a woman? lol. Thanks for the help. Please consider having an attitude transplant. From jgardner at jonathangardner.net Mon Aug 17 20:05:28 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 17 Aug 2009 17:05:28 -0700 (PDT) Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: On Aug 17, 3:26?pm, Gilles Ganault wrote: > ? ? ? ? I need to convert DD MM YYYY dates into the MySQL-friendly > YYYY-MM-DD, and translate the month name from literal French to its > numeric equivalent (eg. "Janvier" into "01"). > > Here's an example: > > SELECT dateinscription, dateconnexion FROM membres LIMIT 1; > 26 Mai 2007|17 Ao?t 2009 - 09h20 > > I'd like to update the row into "2007-05-26" and "2009-08-17 09:20", > respectively. > > What is the best way to do this in Python? > Unfortunately, there isn't any string to date parsers in the built- ins. Not to worry, though, since writing your own is easy, especially if you use regular expressions from the re module. I suggest using an RE such as: r"(?P\d+)\s+(?P\w+)\s+(?P\d+)" If you want to translate month names to month numbers, then you need some sort of dict to do so. Unfortunately, there isn't a terrific standard for this, so your best bet is to put it in some file somewhere, or even hard-code it in your code. (Month names won't change over the lifetime of your program, so it's reasonable to put them in your code somewhere.) month_names_to_numbers = { 'jan':1, ... } Once you have the year, month, and date, formatting it is trivial with the built-in formatter. "%04d-%02d%02d %02d:%02d" % (year, month, date, hour, minute) The variety of date formats out there have prevented a universal, clean solution to this problem. Until we all start sticking to the same conventions, we will always have to write code to translate dates from one format to another. From jgardner at jonathangardner.net Mon Aug 17 20:14:56 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 17 Aug 2009 17:14:56 -0700 (PDT) Subject: Strongly typed list References: <7718922b-c72c-4a7e-90a3-098318063013@n11g2000yqb.googlegroups.com> Message-ID: On Aug 17, 2:19?pm, ???? ??????? wrote: > Please could you lead me to a way or a good IDE that makes developing > huge projects in python more easier than what i found.Now i am using > eclips. Actually it is very hard to remember all my classes methods > and attributes or copy and paste them each time. > Thanks very much for your interest > Hani Almousli..... You're relying on your IDE too much. You should rely on the code and on your own notes. Your project should never get big because there is no reason to throw in a bunch of useless code. Think of the simplest way to get your job done. Then write that in pseudo-code. Finally, run it in Python to see if it actually works. You may be surprised with how far that will get you. If you are having problems remembering the attributes and methods of your instances, you are probably using too many attributes and methods, their names are too long, or you have too many arguments to each method. Keep the interfaces between parts as simple as possible. If you still have a big project, then break it up into several smaller, re-usable, and independent modules. Keep the interfaces as simple as possible, and never write code that does anything but Duck- Typing. From rami.chowdhury at gmail.com Mon Aug 17 20:18:33 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Mon, 17 Aug 2009 17:18:33 -0700 Subject: Converting DD MM YYYY into YYYY-MM-DD? In-Reply-To: References: Message-ID: Correct me if I'm wrong, but doesn't http://docs.python.org/library/datetime.html#datetime.datetime.strptime do this? >>> import locale >>> locale.setlocale(locale.LC_ALL, 'FR') 'French_France.1252' >>> date_str = '05 Mai 2009 - 18h25' >>> fmt = '%d %B %Y - %Hh%M' >>> date_obj = datetime.strptime(date_str, fmt) >>> date_obj datetime.datetime(2009, 5, 5, 18, 25) >>> date_obj.strftime('%Y-%m-%d %H:%M') '2009-05-05 18:25' If you're using a recent enough version of Python (2.5 and up) I'd imagine that's the best way to do it? On Mon, 17 Aug 2009 16:58:28 -0700, Che M wrote: > On Aug 17, 6:26?pm, Gilles Ganault wrote: >> Hello, >> >> ? ? ? ? I need to convert DD MM YYYY dates into the MySQL-friendly >> YYYY-MM-DD, and translate the month name from literal French to its >> numeric equivalent (eg. "Janvier" into "01"). >> >> Here's an example: >> >> SELECT dateinscription, dateconnexion FROM membres LIMIT 1; >> 26 Mai 2007|17 Ao?t 2009 - 09h20 >> >> I'd like to update the row into "2007-05-26" and "2009-08-17 09:20", >> respectively. >> >> What is the best way to do this in Python? >> >> Thank you. > > Likely this is not the best way, but I would do, for > the first one (and the same idea for the second): > > def convert(date): > frenchdict = {'Mai':'May'} #etc... > day = mystring[:2] > month = frenchdict[ mystring[3:6] ] > year = mystring[7:11] > newdate = year+'-'+month+'-'+day > print 'newdate is ', newdate > -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From cmpython at gmail.com Mon Aug 17 20:19:59 2009 From: cmpython at gmail.com (Che M) Date: Mon, 17 Aug 2009 17:19:59 -0700 (PDT) Subject: GUI interface builder for python References: <21bca3cf-b2c7-47d7-9142-26c9fd015f92@r27g2000vbn.googlegroups.com> Message-ID: <02ec7cd9-e749-46d3-8b25-75d85794f292@o35g2000vbi.googlegroups.com> On Aug 17, 2:26?pm, axl456 wrote: > On Aug 17, 1:59?am, "L at D@n" wrote: > > > Which is the best GUI interface builder with drag and drop > > capabilities. > > I am using Ubuntu GNU/Linux. > > Please help me. > > Thank you. > > boa is really nice.. Boa (Boa Constructor) is really nice for wxPython GUI work, but it has some bugs when using Linux that might be dealbreakers for the user. At least I have had problems on Ubuntu 8.10 64 bit (but none or very few with WinXP). For those that might care, they are (as of now, Boa 0.6.1-4) are: - The File -> New option is cut off in the menu. But that can be gotten around by using the Palette to choose the same options. - No gridlines in the Frame Designer (makes it harder to use) - Some problems with the height of the rows in the Inspector, at least with 64 bit Ubuntu, some of which can be fixed with this workaround: https://bugs.launchpad.net/ubuntu/+source/boa-constructor/+bug/313952 and there is a note there saying it has been patched in a 0.6.1-6 version in a Debian repository. Haven't tried. - I have had some random shutdowns, but not many. Che From ben+python at benfinney.id.au Mon Aug 17 20:20:05 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 10:20:05 +1000 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: <8763cmkm6i.fsf@benfinney.id.au> Gilles Ganault writes: > I need to convert DD MM YYYY dates into the MySQL-friendly > YYYY-MM-DD This is not specific to MySQL. It is the common international standard date representation format defined by ISO 8601. > and translate the month name from literal French to its numeric > equivalent (eg. "Janvier" into "01"). The simplest way to do this would be by a mapping from month-name to month-number. An obvious, and wrong, approach to this would be to hard-code the twelve month names into your program data. Instead, you should generate the map based on the standard library (in this case, the underlying C standard library) locale database : >>> import locale >>> locale.setlocale(locale.LC_TIME, "en_AU.UTF-8") >>> months = dict( ... (locale.nl_langinfo(getattr(locale, key)), i) ... for (key, i) in ( ... ('MON_%(i)d' % vars(), i) ... for i in range(1, 12+1))) >>> import pprint >>> pprint.pprint(months) {'April': 4, 'August': 8, 'December': 12, 'February': 2, 'January': 1, 'July': 7, 'June': 6, 'March': 3, 'May': 5, 'November': 11, 'October': 10, 'September': 9} Of course, if you can avoid having to generate this mapping at all in your program, that's best; see below. > Here's an example: > > SELECT dateinscription, dateconnexion FROM membres LIMIT 1; > 26 Mai 2007|17 Ao?t 2009 - 09h20 > > I'd like to update the row into "2007-05-26" and "2009-08-17 09:20", > respectively. Storing a timestamp as a text attribute in a database seems perverse and begging for trouble. Doesn't the database have a timestamp data type? Or perhaps that's what you're trying to achieve? > What is the best way to do this in Python? The ?datetime.strptime? function will create a Python ?datetime? object from a string, parsed according to a format . I don't know whether that function allows for month names in the current locale (as set by ?locale.setlocale(locale.LC_TIME, ?)?). If it does, that's the right way, since it doesn't involve explciitly generating the mapping as shown above. Use your preferred Python-to-database library to feed that ?datetime? object directly to the database and store it in an attribute of the native database timestamp type. Then, format the timestamp value at the point of outputting that value, instead of storing the text representation in the database. -- \ ?To succeed in the world it is not enough to be stupid, you | `\ must also be well-mannered.? ?Voltaire | _o__) | Ben Finney From mensanator at aol.com Mon Aug 17 20:40:42 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 17 Aug 2009 17:40:42 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> Message-ID: <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> On Aug 17, 4:06?pm, Carl Banks wrote: > On Aug 17, 10:03?am, Jean-Michel Pichavant > wrote: > > > I'm no English native, but I already heard women/men referring to a > > group as "guys", no matter that group gender configuration. It's even > > used for group composed exclusively of women. Moreover it looks like a > > *very* friendly form, so there is really nothing to worry about it. > > I like how being very friendly means calling people after a guy who > tried to blow up the English Parliament. So? > > Carl Banks From pavlovevidence at gmail.com Mon Aug 17 21:04:58 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 18:04:58 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> Message-ID: On Aug 17, 5:40?pm, Mensanator wrote: > On Aug 17, 4:06?pm, Carl Banks wrote: > > > On Aug 17, 10:03?am, Jean-Michel Pichavant > > wrote: > > > > I'm no English native, but I already heard women/men referring to a > > > group as "guys", no matter that group gender configuration. It's even > > > used for group composed exclusively of women. Moreover it looks like a > > > *very* friendly form, so there is really nothing to worry about it. > > > I like how being very friendly means calling people after a guy who > > tried to blow up the English Parliament. > > So? I also like how making an amusing pointless observation gets people all huffy. (BTW, lest anyone is not aware, that is the origin of the word "guy", this was not some random association.) Carl Banks From magawake at gmail.com Mon Aug 17 21:33:29 2009 From: magawake at gmail.com (Mag Gam) Date: Mon, 17 Aug 2009 21:33:29 -0400 Subject: unittest In-Reply-To: <1cbd6f830908160625m5a8ffa9er7e34c203f30fca49@mail.gmail.com> References: <1cbd6f830908142028v638a4c06jf0f859be712e724c@mail.gmail.com> <1cbd6f830908160625m5a8ffa9er7e34c203f30fca49@mail.gmail.com> Message-ID: <1cbd6f830908171833p73109091ga612b2ec719d28eb@mail.gmail.com> all, thank you very much!!! Now my question is, how do I simulate a argv? My program has take an argv, like "foo.py File" is necessary. How and where do I put it in my test? I suppose in the setUp(), but I am not sure how. any thoughts or ideas? TIA On Sun, Aug 16, 2009 at 9:25 AM, Mag Gam wrote: > John: > > Well, this is actually a script which wraps around another application. :-) > My goal is when I introduce a new feature I don't want to break old > stuff so instead of me testing manually I want to build a framework of > tests. > > > > On Sat, Aug 15, 2009 at 11:37 PM, John Haggerty wrote: >> This is an interesting question. I am just wondering: do you really have >> that many features that it would be impossible to just have a shell script >> run specific types of input or tests? >> >> When I did programming in the past for education they just had lists of >> input data and we ran the program against the test data. >> >> I just get slightly confused when "test suites" start to have to apply? >> >> On Fri, Aug 14, 2009 at 9:28 PM, Mag Gam wrote: >>> >>> I am writing an application which has many command line arguments. >>> For example: foo.py -args "bar bee" >>> >>> I would like to create a test suit using unittest so when I add >>> features to "foo.py" I don't want to break other things. I just heard >>> about unittest and would love to use it for this type of thing. >>> >>> so my question is, when I do these tests do I have to code them into >>> foo.py? I prefer having a footest.py which will run the regression >>> tests. Any thoughts about this? >>> >>> TIA >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> > From ben+python at benfinney.id.au Mon Aug 17 22:06:37 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 12:06:37 +1000 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: <87skfpkh8y.fsf@benfinney.id.au> Jonathan Gardner writes: > Unfortunately, there isn't any string to date parsers in the built- > ins. Fortunately, Python 2.5 or later has the ?datetime.strptime? function. -- \ ?You could augment an earwig to the point where it understood | `\ nuclear physics, but it would still be a very stupid thing to | _o__) do!? ?The Doctor, _The Two Doctors_ | Ben Finney From jgardner at jonathangardner.net Mon Aug 17 22:31:36 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 17 Aug 2009 19:31:36 -0700 (PDT) Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <8763cmkm6i.fsf@benfinney.id.au> Message-ID: <91da9c54-a152-469b-81b0-65b99a532a1a@d4g2000yqa.googlegroups.com> On Aug 17, 5:20?pm, Ben Finney wrote: > > Instead, you should generate the map based on the standard library (in > this case, the underlying C standard library) locale database > : > Does Windows support POSIX locales? From ben+python at benfinney.id.au Mon Aug 17 22:32:06 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 12:32:06 +1000 Subject: unittest References: <1cbd6f830908142028v638a4c06jf0f859be712e724c@mail.gmail.com> <1cbd6f830908160625m5a8ffa9er7e34c203f30fca49@mail.gmail.com> Message-ID: <87ocqdkg2h.fsf@benfinney.id.au> Mag Gam writes: > all, thank you very much!!! > > Now my question is You would do well to ask more about testing in Python on the focussed forum for that topic, the ?testing-in-python? mailing list . -- \ ?If it ain't bust don't fix it is a very sound principle and | `\ remains so despite the fact that I have slavishly ignored it | _o__) all my life.? ?Douglas Adams | Ben Finney From jgardner at jonathangardner.net Mon Aug 17 22:36:24 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 17 Aug 2009 19:36:24 -0700 (PDT) Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <87skfpkh8y.fsf@benfinney.id.au> Message-ID: On Aug 17, 7:06?pm, Ben Finney wrote: > Jonathan Gardner writes: > > Unfortunately, there isn't any string to date parsers in the built- > > ins. > > Fortunately, Python 2.5 or later has the ?datetime.strptime? function. > Hate to weasel out of this one, but the language that strptime provides is pretty limited. I don't find it useful except in the trivial cases. Same goes for strftime. Also, both of these are very Western European centric. Yes, Asian languages are supported but not naturally. From jgardner at jonathangardner.net Mon Aug 17 22:38:34 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 17 Aug 2009 19:38:34 -0700 (PDT) Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: On Aug 17, 5:18?pm, "Rami Chowdhury" wrote: > > >>> import locale > >>> locale.setlocale(locale.LC_ALL, 'FR') locale is nice when you only have a single thread. Webservers aren't single threaded. You can't serve up one page for one locale and then another in another locale without seeing very, very weird behavior. From ben+python at benfinney.id.au Mon Aug 17 22:46:24 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 12:46:24 +1000 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <8763cmkm6i.fsf@benfinney.id.au> <91da9c54-a152-469b-81b0-65b99a532a1a@d4g2000yqa.googlegroups.com> Message-ID: <87k511kfen.fsf@benfinney.id.au> Jonathan Gardner writes: > On Aug 17, 5:20?pm, Ben Finney wrote: > > Instead, you should generate the map based on the standard library (in > > this case, the underlying C standard library) locale database > > : > > Does Windows support POSIX locales? If it does not, it should :-) since it addresses the problem in one standard place. It would be foolish for Python to re-implement that functionality when presumably the operating system already knows how to map between dates and locale-specific text representations. You'll need to check the operating system documentation for what alternative it might provide. -- \ ?I got fired from my job the other day. They said my | `\ personality was weird. ? That's okay, I have four more.? | _o__) ?Bug-Eyed Earl, _Red Meat_ | Ben Finney From af2012 at gmail.com Mon Aug 17 22:49:31 2009 From: af2012 at gmail.com (Allan Fong) Date: Mon, 17 Aug 2009 22:49:31 -0400 Subject: New to python Message-ID: <62763f750908171949q2d9029ddo1df40b8850f945b6@mail.gmail.com> Hi! I'm fairly new to Python. I understand the basics basics but I'm been trying to write a simple python code that will let me read input data from my USB drive and write it in a text file and I am so lost. Can anyone help or direct me to some resources? Thank you! -------------- next part -------------- An HTML attachment was scrubbed... URL: From rurpy at yahoo.com Mon Aug 17 23:19:16 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 17 Aug 2009 20:19:16 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> <3d808272-6e56-4cf1-90df-8e5201df02df@c34g2000yqi.googlegroups.com> <13be5a11-612b-4fc5-a220-cc9aba2e4f8c@z31g2000yqd.googlegroups.com> Message-ID: <611687df-e755-4910-9042-5dab20de1a7e@c34g2000yqi.googlegroups.com> On 08/13/2009 08:46 AM, Paul Boddie wrote: > On 13 Aug, 16:05, ru... at yahoo.com wrote: >> All the above not withstanding, I too think a wiki is worth >> trying. But without doing a lot more than just "setting up >> a wiki", I sadly believe even a python.org supported wiki >> is doomed to failure. > > The ones on python.org seem to function reasonably well. I accept that > they could be more aggressively edited, but this isn't done because > there's a compromise between letting people contribute and keeping > things moderately coherent, with the former being favoured. For other > purposes, it would be quite acceptable to favour editorial control. Yes, I agree. I should have mentioned this as an exception in my "wikis suck" diatribe. Although it far better than most wiki's I've seen, it is still pretty easy to find signs of typical wiki-ness. On the Documentation page my first click was on AnnotableDocumentation: 404. Second try, DoumentationDiscussion: two very short paragraphs dated 2003. After that I found some useful (in general though not what I was looking for) information but not a good first impression. (Well not exactly first, in fairness I have used other wiki sections such as the Templating page and found them very useful.) > I won't argue that providing infrastructure solves a problem - that's > precisely the kind of thing I was criticising when I noted that some > people will readily criticise the choice of tools to do a job instead > of focusing on the job that has to be done - and you need people who > are reasonably competent editors, but Wiki solutions remove a lot of > technical barriers. I'm not arguing for the flavour of Wiki which > implies unfettered, anonymous access from everyone on the Internet, > either: the kind of Wiki that detractors portray all Wiki solutions as > being in order to further their super-special "it has to fit like a > glove or it's totally unusable" software agenda. It's quite possible > to have people with somewhat more privileges than others in order to > keep the peace, and they don't all need to have an entrenched > editorial interest: on the current python.org Wiki sites, most of the > administrators don't have an active interest in most of the content, > but they are able to exercise control when it's clear that some > contributors aren't particularly interested in actually improving the > content. > > As well as having an active community effort around the existing > python.org Wiki sites, there are also people who are interested in > improving these offerings. What worries me is that despite such > activity and such interest, many people will continue to lament the > lack of vitality (or whatever other metric) of the general python.org > offering, whilst retaining a blind spot for the obvious contribution > that the Wikis can make to such improvement efforts. I encourage > people to use wiki.python.org a lot more, should they be looking to > improve the wealth of information provided by the community. Again, I agree with all of that. But my main interest is in improving the standard docs that are distributed with Python and I question a wiki's role in that. I took a look at the PHP docs last night which seem pretty well done. The User Comments looked rather as I expected, there was useful info but most did not contain documentation quality writing. So if they are used as a source for improving the docs, there clearly must be a pretty large amount of editorial effort required, although much of it is probably just filtering out comments that don't provide any information appropriate for inclusion in the docs. They list 38 names under "User Note Maintainers" (http://www.php.net/manual/en/preface.php) Unfortunately I couldn't find a description of what these people actually do. I don't know how much work was involved in removing the comments that are no longer there. Again, I don't mean to sound like I am dissing the idea of annotatable docs -- I think it is a good idea and will provide useful supplementary information. But I continue to question whether this will result in improvements in the docs themselves (which is my main interest) unless: 1. The purpose of the wiki is clearly "marketed" as soliciting suggestions, rewrites, etc destined ultimately for inclusion in the docs. 2. There is a dedicated core of doc-competent volunteers focused on extracting, condensing and editing the user comments and getting them into the docs, either directly (if the volunteers are committers -- unlikely) or through the existing tracker system. And this still fails to address the problems with the docs that aren't amenable to fixing via the tracker system. At least two of those problems are: 1. Difficultly in making large organizational changes. 2. Prevalent opinion among doc approvers that the current excessively terse style is desirerable. From rami.chowdhury at gmail.com Mon Aug 17 23:22:05 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Mon, 17 Aug 2009 20:22:05 -0700 Subject: Converting DD MM YYYY into YYYY-MM-DD? In-Reply-To: <87k511kfen.fsf@benfinney.id.au> References: <91da9c54-a152-469b-81b0-65b99a532a1a@d4g2000yqa.googlegroups.com> <87k511kfen.fsf@benfinney.id.au> Message-ID: <200908172022.05517.rami.chowdhury@gmail.com> ---- My sample interactive session (locale.setlocale and all) was on a 32-bit Vista install of Python 2.5, so it works on that... --- Rami Chowdhury "A man with a watch knows what time it is. A man with two watches is never sure". -- Segal's Law 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Monday 17 August 2009 19:46:24 Ben Finney wrote: > Jonathan Gardner writes: > > On Aug 17, 5:20 pm, Ben Finney wrote: > > > Instead, you should generate the map based on the standard library (in > > > this case, the underlying C standard library) locale database > > > > >#lo...>: > > > > Does Windows support POSIX locales? > > If it does not, it should :-) since it addresses the problem in one > standard place. It would be foolish for Python to re-implement that > functionality when presumably the operating system already knows how to > map between dates and locale-specific text representations. > > You'll need to check the operating system documentation for what > alternative it might provide. > > -- > \ ?I got fired from my job the other day. They said my | > `\ personality was weird. ? That's okay, I have four more.? | > _o__) ?Bug-Eyed Earl, _Red Meat_ | > Ben Finney From clp2 at rebertia.com Mon Aug 17 23:22:50 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 17 Aug 2009 20:22:50 -0700 Subject: New to python In-Reply-To: <62763f750908171949q2d9029ddo1df40b8850f945b6@mail.gmail.com> References: <62763f750908171949q2d9029ddo1df40b8850f945b6@mail.gmail.com> Message-ID: <50697b2c0908172022ta35e948y8613e70463f28345@mail.gmail.com> On Mon, Aug 17, 2009 at 7:49 PM, Allan Fong wrote: > Hi! I'm fairly new to Python.? I understand the basics basics but I'm been > trying to write a simple python code that will let me read input data from > my USB drive and write it in a text file and I am so lost.? Can anyone help > or direct me to some resources?? Thank you! Working with files: http://docs.python.org/library/stdtypes.html#file-objects Reading+writing common file formats: JSON: http://docs.python.org/library/json.html CSV: http://docs.python.org/library/csv.html Cheers, Chris -- http://blog.rebertia.com From roykty at gmail.com Mon Aug 17 23:45:37 2009 From: roykty at gmail.com (roykty at gmail.com) Date: Mon, 17 Aug 2009 20:45:37 -0700 (PDT) Subject: Text lost when I write file Message-ID: Dear All, I try to write text into a file but some text lost when the size of the text content is over 32K. Is that relate to the buffer of the python and any setting can solve this problem??. Regards Roy From mensanator at aol.com Mon Aug 17 23:49:29 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 17 Aug 2009 20:49:29 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> Message-ID: On Aug 17, 8:04?pm, Carl Banks wrote: > On Aug 17, 5:40?pm, Mensanator wrote: > > > On Aug 17, 4:06?pm, Carl Banks wrote: > > > > On Aug 17, 10:03?am, Jean-Michel Pichavant > > > wrote: > > > > > I'm no English native, but I already heard women/men referring to a > > > > group as "guys", no matter that group gender configuration. It's even > > > > used for group composed exclusively of women. Moreover it looks like a > > > > *very* friendly form, so there is really nothing to worry about it. > > > > I like how being very friendly means calling people after a guy who > > > tried to blow up the English Parliament. > > > So? > > I also like how making an amusing pointless observation Pointless, yes, but what was amusing abot the observation? > gets people all huffy. That wasn't huffy. You want to see huffy, make a wisecrack comparing mothballs to Zyklon B, you'll REALLY get a load of huffy replies. > > (BTW, lest anyone is not aware, that is the origin of the word "guy", It most certainly is not. Maybe the origin of that word's useage as a genric reference to a male, but you didn't say that. > this was not some random association.) Penny for the guy? > > Carl Banks From tjreedy at udel.edu Mon Aug 17 23:56:58 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Aug 2009 12:56:58 +0900 Subject: Python 'for' loop is memory inefficient In-Reply-To: <20090817194155.8740.902674574.divmod.xquotient.69@localhost.localdomain> References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> <20090817194155.8740.902674574.divmod.xquotient.69@localhost.localdomain> Message-ID: exarkun at twistedmatrix.com wrote: > There's a lot of things in Python that I don't strictly *need*. That > doesn't mean that they wouldn't be welcome if I could have them. Getting > rid of the range/xrange dichotomy would improve things. The developers agreed a couple of years ago. Starting using 3.1 if you want this. Since 'range' could refer to a user-defined object, rather than the builtin function, there is no way the interpreter should substitute 'xrange'. tjr From tjreedy at udel.edu Tue Aug 18 00:06:50 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Aug 2009 13:06:50 +0900 Subject: Social problems of Python doc [was Re: Python docs disappointing] In-Reply-To: References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: Nathan Keel wrote: > idiot ... asshole > absolutely clueless ... idiot ...incredibly > arrogant, yet incredibly clueless. To me, such name-calling is as obnoxious as the intended target. tjr From clp2 at rebertia.com Tue Aug 18 00:09:34 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 17 Aug 2009 21:09:34 -0700 Subject: Text lost when I write file In-Reply-To: References: Message-ID: <50697b2c0908172109m906fb7ape3d02a8a0c4bba53@mail.gmail.com> On Mon, Aug 17, 2009 at 8:45 PM, roykty at gmail.com wrote: > Dear All, > > I try to write text into a file but some text lost when the size of > the text content is over 32K. > Is that relate to the buffer of the python and any setting can solve > this problem??. Please show us the code you're using. Cheers, Chris -- http://blog.rebertia.com From ben+python at benfinney.id.au Tue Aug 18 00:23:26 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 14:23:26 +1000 Subject: Text lost when I write file References: Message-ID: <87fxbpkawx.fsf@benfinney.id.au> Chris Rebert writes: > On Mon, Aug 17, 2009 at 8:45 PM, roykty at gmail.com wrote: > > I try to write text into a file but some text lost when the size of > > the text content is over 32K. > > Is that relate to the buffer of the python and any setting can solve > > this problem??. > > Please show us the code you're using. Not the whole danged thing, of course; please show a minimal executable example that demonstrates the behaviour. -- \ ?I do not believe in immortality of the individual, and I | `\ consider ethics to be an exclusively human concern with no | _o__) superhuman authority behind it.? ?Albert Einstein, letter, 1953 | Ben Finney From steven at REMOVE.THIS.cybersource.com.au Tue Aug 18 00:34:57 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 04:34:57 GMT Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: On Mon, 17 Aug 2009 14:31:51 -0700, Chris Rebert wrote: >> Oh come on, one newbie making an off-color joke is not any sort of >> reflection of the community as a whole. >> >> Anyway it's pretty naive to expect what is now a large community to >> avoid bad eggs altogether. ?Price you pay for popularity. > > Agreed on both points, but the lack of any reprimanding for making said > inappropriate joke /would/ reflect badly on the community. Fortunately, > said person's behavior has now been condemned by virtue of this thread; > it's a step in the right direction. Pardon me, but he has been slapped, a number of times. Check the original thread, you'll see that the OP was slapped for his stupid joke, then slapped again for another dismissive comment after the first reprimand. You might argue he wasn't slapped *enough*, but that's another story. Personally, I thought he was either trolling for a reaction, or he was an old-fuddy-duddy (regardless of biological age), and either way reacting to his comments would just draw attention to something which is best dealt with with a cold-shoulder. Reinforce the good behaviour, shun the bad. The comments were made a week ago -- why the sudden flurry of attention? -- Steven From pavlovevidence at gmail.com Tue Aug 18 00:35:48 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 21:35:48 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> Message-ID: <86bb893a-344a-4c7b-9fc6-67d9f42c7607@q14g2000vbi.googlegroups.com> On Aug 17, 8:49?pm, Mensanator wrote: > On Aug 17, 8:04 pm, Carl Banks wrote: > > > > > > > On Aug 17, 5:40 pm, Mensanator wrote: > > > > On Aug 17, 4:06 pm, Carl Banks wrote: > > > > > On Aug 17, 10:03 am, Jean-Michel Pichavant > > > > wrote: > > > > > > I'm no English native, but I already heard women/men referring to a > > > > > group as "guys", no matter that group gender configuration. It's even > > > > > used for group composed exclusively of women. Moreover it looks like a > > > > > *very* friendly form, so there is really nothing to worry about it. > > > > > I like how being very friendly means calling people after a guy who > > > > tried to blow up the English Parliament. > > > > So? > > > I also like how making an amusing pointless observation > > Pointless, yes, but what was amusing abot the observation? The irony that in being friendly that you're calling someone a terrorist. I guess I shouldn't have expected you to get it. > > gets people all huffy. > > That wasn't huffy. You want to see huffy, make a wisecrack > comparing mothballs to Zyklon B, you'll REALLY get a load > of huffy replies. > > > (BTW, lest anyone is not aware, that is the origin of the word "guy", > > It most certainly is not. My dictionary disagrees with you. > Maybe the origin of that > word's useage as a genric reference to a male, but > you didn't say that. > > > this was not some random association.) > > Penny for the guy? Probably that phrase was part of the word's gradual common adoption. Carl Banks From steven at REMOVE.THIS.cybersource.com.au Tue Aug 18 00:37:33 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 04:37:33 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> Message-ID: On Mon, 17 Aug 2009 18:04:58 -0700, Carl Banks wrote: > On Aug 17, 5:40?pm, Mensanator wrote: >> On Aug 17, 4:06?pm, Carl Banks wrote: >> >> > On Aug 17, 10:03?am, Jean-Michel Pichavant >> > wrote: >> >> > > I'm no English native, but I already heard women/men referring to a >> > > group as "guys", no matter that group gender configuration. It's >> > > even used for group composed exclusively of women. Moreover it >> > > looks like a *very* friendly form, so there is really nothing to >> > > worry about it. >> >> > I like how being very friendly means calling people after a guy who >> > tried to blow up the English Parliament. >> >> So? > > I also like how making an amusing pointless observation gets people all > huffy. > > (BTW, lest anyone is not aware, that is the origin of the word "guy", > this was not some random association.) Yes, apparently the slang term "guy" for "man" (and these days, "person") was derived from Guy Fawkes: http://www.worldwidewords.org/weirdwords/ww-guy1.htm but the name itself is much older, and comes from Old German for "wood" or "warrior". In old French, it was "Gy", and in Italian (and presumably Dutch) it is "Guido". http://www.thinkbabynames.com/meaning/1/Guy http://www.blurtit.com/q113276.html You'll also note that "guy" the noun has a number of meanings: http://wordnetweb.princeton.edu/perl/webwn?s=guy I don't know if there's any point to all this, but it's interesting, even if off-topic. -- Steven From steven at REMOVE.THIS.cybersource.com.au Tue Aug 18 00:37:46 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 04:37:46 GMT Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> <7xtz06cg7m.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 17 Aug 2009 13:56:13 -0700, Paul Rubin wrote: > Python 3.0 went overboard by actually removing the cmp argument and > requiring use of the key argument. That requires various kludges if the > key is, say, a tree structure that has to be recursively compared with > another such structure. Maybe then can bring back cmp someday. I'm having trouble understanding this, which may be my weakness rather than yours, but could you give an actual (simplified?) example I can run, where cmp would work but key wouldn't? -- Steven From aahz at pythoncraft.com Tue Aug 18 00:45:39 2009 From: aahz at pythoncraft.com (Aahz) Date: 17 Aug 2009 21:45:39 -0700 Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) References: Message-ID: In article , Steven D'Aprano wrote: > >The comments were made a week ago -- why the sudden flurry of attention? Mainly an opportunity to flog the new diversity list. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From naveen.garg at gmail.com Tue Aug 18 00:45:57 2009 From: naveen.garg at gmail.com (naveen) Date: Mon, 17 Aug 2009 21:45:57 -0700 (PDT) Subject: define class over 2 files Message-ID: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> Is it possible to split up a class definition over multiple files? From contact at xavierho.com Tue Aug 18 00:58:58 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 18 Aug 2009 14:58:58 +1000 Subject: define class over 2 files In-Reply-To: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> Message-ID: <2d56febf0908172158l760256rc703d7d87f04e509@mail.gmail.com> On Tue, Aug 18, 2009 at 2:45 PM, naveen wrote: > Is it possible to split up a class definition over multiple files? > - Answer in short, I don't think so. Now why would you want to do that? There is another solution - have a main class for shared methods, and have other classes [in different files, perhaps] inherit from it. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Tue Aug 18 01:07:14 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 15:07:14 +1000 Subject: Diversity in Python References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <87bpmdk8vx.fsf@benfinney.id.au> Steven D'Aprano writes: > The comments were made a week ago -- why the sudden flurry of > attention? In my case, it's because I was ignoring the thread in which they were made. The change of subject drew them to my attention, where I saw the community response was (IMO) insufficient at the time, so I acted to correct that. Now that the community response is (IMO) more appropriate, there's no further need to beat on those particular comments. Additional transgressions could warrant additional responses, of course. -- \ ?I got some new underwear the other day. Well, new to me.? ?Emo | `\ Philips | _o__) | Ben Finney From ariel.balter at gmail.com Tue Aug 18 01:27:57 2009 From: ariel.balter at gmail.com (abalter) Date: Mon, 17 Aug 2009 22:27:57 -0700 (PDT) Subject: Data visualization in Python References: Message-ID: <4121b29c-ebac-4f8f-b6af-e9789564cb4d@24g2000yqm.googlegroups.com> On Aug 17, 12:10?pm, kj wrote: > I'm looking for a good Python package for visualizing > scientific/statistical data. ?(FWIW, the OS I'm interested in is > Mac OS X). > > The users of this package will be experimental biologists with > little programming experience (but currently learning Python). > > (I normally visualize data using R or Mathematica, but I don't want > to saddle these novices with the task of learning yet another > language.) > > TIA! > > kynn You might also look into the pythonxy superpackage, http://www.pythonxy.com/foreword.php and http://enthought.com. From indermeet.gandhi at gmail.com Tue Aug 18 01:28:17 2009 From: indermeet.gandhi at gmail.com (inder) Date: Mon, 17 Aug 2009 22:28:17 -0700 (PDT) Subject: XML parsing with python References: Message-ID: On Aug 17, 8:31?pm, John Posner wrote: > > Use the iterparse() function of the xml.etree.ElementTree package. > > >http://effbot.org/zone/element-iterparse.htm > >http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk > > > Stefan > > iterparse() is too big a hammer for this purpose, IMO. How about this: > > ? from xml.etree.ElementTree import ElementTree > ? tree = ElementTree(None, "myfile.xml") > ? for elem in tree.findall('//book/title'): > ? ? ? print elem.text > > -John Thanks for the prompt reply . I feel let me try using iterparse. Will it be slower compared to SAX parsing ... ultimately I will have a huge xml file to parse ? Another question , I will also need to validate my xml against xsd . I would like to do this validation through the parsing tool itself . Does there exist an Unix utility which validates or even a python library call would be fine ? Thanks in advance From steven at REMOVE.THIS.cybersource.com.au Tue Aug 18 01:51:55 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 05:51:55 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> <86bb893a-344a-4c7b-9fc6-67d9f42c7607@q14g2000vbi.googlegroups.com> Message-ID: On Mon, 17 Aug 2009 21:35:48 -0700, Carl Banks wrote: >> > > > I like how being very friendly means calling people after a guy >> > > > who tried to blow up the English Parliament. >> >> > > So? >> >> > I also like how making an amusing pointless observation >> >> Pointless, yes, but what was amusing abot the observation? > > The irony that in being friendly that you're calling someone a > terrorist. Please, the term is Freedom Fighter. > I guess I shouldn't have expected you to get it. Ouch! Nasty! Is there something in the air today? People are short-tempered and grouchy all over the place... -- Steven From steven at REMOVE.THIS.cybersource.com.au Tue Aug 18 01:57:46 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 05:57:46 GMT Subject: define class over 2 files References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> Message-ID: On Mon, 17 Aug 2009 21:45:57 -0700, naveen wrote: > Is it possible to split up a class definition over multiple files? Not exactly, but you can do variations of this: In file A.py, create: class Parent: def method(self): return "Method" In file B.py, do this: import A class Child(B.parent): def another_method(self): return "Another Method" Now your class Child has two methods, method() and another_method(). Similarly, you can do this: # File A.py def function(x, y): return x+y # or something more complicated # File B.py import A def MyClass(object): def func(self, x, y): return A.function(x, y) -- Steven From stefan_ml at behnel.de Tue Aug 18 02:24:24 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 Aug 2009 08:24:24 +0200 Subject: XML parsing with python In-Reply-To: References: Message-ID: <4a8a4918$0$32672$9b4e6d93@newsspool2.arcor-online.net> inder wrote: > On Aug 17, 8:31 pm, John Posner wrote: >>> Use the iterparse() function of the xml.etree.ElementTree package. >>> http://effbot.org/zone/element-iterparse.htm >>> http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk >>> Stefan >> iterparse() is too big a hammer for this purpose, IMO. How about this: >> >> from xml.etree.ElementTree import ElementTree >> tree = ElementTree(None, "myfile.xml") >> for elem in tree.findall('//book/title'): >> print elem.text >> >> -John > > Thanks for the prompt reply . > > I feel let me try using iterparse. Will it be slower compared to SAX > parsing ... ultimately I will have a huge xml file to parse ? If you use the cElementTree module, it may even be faster. > Another question , I will also need to validate my xml against xsd . I > would like to do this validation through the parsing tool itself . In that case, you can use lxml instead of ElementTree. http://codespeak.net/lxml/ Stefan From stefan_ml at behnel.de Tue Aug 18 02:32:59 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 Aug 2009 08:32:59 +0200 Subject: XML parsing with python In-Reply-To: References: Message-ID: <4a8a4b1c$0$32679$9b4e6d93@newsspool2.arcor-online.net> John Posner wrote: >> Use the iterparse() function of the xml.etree.ElementTree package. > > iterparse() is too big a hammer for this purpose, IMO. How about this: > > from xml.etree.ElementTree import ElementTree > tree = ElementTree(None, "myfile.xml") > for elem in tree.findall('//book/title'): > print elem.text Is that really so much better than an iterparse() version? from xml.etree.ElementTree import ElementTree for _, elem in ElementTree.iterparse("myfile.xml"): if elem.tag == 'book': print elem.findtext('title') elem.clear() Stefan From deets at nospam.web.de Tue Aug 18 02:46:10 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 08:46:10 +0200 Subject: Strongly typed list In-Reply-To: <7718922b-c72c-4a7e-90a3-098318063013@n11g2000yqb.googlegroups.com> References: <7718922b-c72c-4a7e-90a3-098318063013@n11g2000yqb.googlegroups.com> Message-ID: <7ev11jF1jj25dU1@mid.uni-berlin.de> ???? ??????? schrieb: > Please could you lead me to a way or a good IDE that makes developing > huge projects in python more easier than what i found.Now i am using > eclips. Actually it is very hard to remember all my classes methods > and attributes or copy and paste them each time. > Thanks very much for your interest > Hani Almousli..... There are many really big projects written in Python - none of them with the aid of intelli-sense. What python lacks in that respect due to it's dynamic typing, it more than compensates by being faster to develop and having to write much less code. Diez From sreejithemk at gmail.com Tue Aug 18 02:46:28 2009 From: sreejithemk at gmail.com (Sreejith K) Date: Mon, 17 Aug 2009 23:46:28 -0700 (PDT) Subject: Changing Python Opcodes Message-ID: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> Hi, I know this is not the best way to do it. But I have to do it at least to make it *hard* to decompile the python bytecode. I want to distribute a software written in Python without the source. So I compiled Python from source changing some opcode values (Taking care of HAVE_ARGUMENT value) and distributed with the .pyc files. It did compile but when I'm installing additional python modules using easy_install, the import fails with a segmentation fault. It worked in a 32 bit Centos 5.2 but not on 64bit Centos 5.2. I am using python 2.5.4 source. I changed only the Include/opcode.py source with my jumbled opcode values. Was I correct here ? I would like to know what all changes to be made as to successfully compile a custom python with different opcode values ? From nospam at nospam.com Tue Aug 18 02:59:57 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 08:59:57 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: <3vjk85hapd0nuigp09qrihm6e7faliompd@4ax.com> Thanks everyone for the help. This script is just a one-shot thingie on my work host, not as a web script or anything professional. On Mon, 17 Aug 2009 17:05:28 -0700 (PDT), Jonathan Gardner wrote: >Unfortunately, there isn't any string to date parsers in the built- >ins. Not to worry, though, since writing your own is easy, especially >if you use regular expressions from the re module. I suggest using an >RE such as: > > r"(?P\d+)\s+(?P\w+)\s+(?P\d+)" I've never seen regexes like this. I'm curious to know what those mean: r = Unicode? (?P = ? means that it shouldn't be greedy, what about P? From naveen.garg at gmail.com Tue Aug 18 03:04:56 2009 From: naveen.garg at gmail.com (naveen) Date: Tue, 18 Aug 2009 00:04:56 -0700 (PDT) Subject: define class over 2 files References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> Message-ID: <6a490ec8-3536-4508-afd4-90a5cf9317b5@g10g2000yqh.googlegroups.com> > > Is it possible to split up a class definition over multiple files? > > Not exactly, but you can do variations of this: ... [subclass a class] > Steven Thanks Steven. I guess I will just preprocess the script: cat partA.py > class.py cat partB >> class.py python class.py From ben+python at benfinney.id.au Tue Aug 18 03:10:50 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 17:10:50 +1000 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <3vjk85hapd0nuigp09qrihm6e7faliompd@4ax.com> Message-ID: <874os5k35x.fsf@benfinney.id.au> Gilles Ganault writes: > Thanks everyone for the help. This script is just a one-shot thingie > on my work host, not as a web script or anything professional. > > On Mon, 17 Aug 2009 17:05:28 -0700 (PDT), Jonathan Gardner > wrote: > > r"(?P\d+)\s+(?P\w+)\s+(?P\d+)" > > I've never seen regexes like this. I'm curious to know what those > mean: Luckily, you have access to the documentation to find out. > r = Unicode? > (?P = ? means that it shouldn't be greedy, what about P? -- \ ?We reserve the right to serve refuse to anyone.? ?restaurant, | `\ Japan | _o__) | Ben Finney From ben+python at benfinney.id.au Tue Aug 18 03:13:17 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 17:13:17 +1000 Subject: define class over 2 files References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> <6a490ec8-3536-4508-afd4-90a5cf9317b5@g10g2000yqh.googlegroups.com> Message-ID: <87zl9xiohe.fsf@benfinney.id.au> naveen writes: > I guess I will just preprocess the script: > > cat partA.py > class.py > cat partB >> class.py > python class.py > This, to me, is a programming smell; not necessarily bad, but an indicator of bad practice. What is the problem you're trying to solve? I'll wager there are better ways to address it. -- \ ?Laugh and the world laughs with you; snore and you sleep | `\ alone.? ?anonymous | _o__) | Ben Finney From deets at nospam.web.de Tue Aug 18 03:19:31 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 09:19:31 +0200 Subject: Changing Python Opcodes In-Reply-To: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> References: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> Message-ID: <7ev303F2ib9r1U1@mid.uni-berlin.de> Sreejith K schrieb: > Hi, > > I know this is not the best way to do it. But I have to do it at least > to make it *hard* to decompile the python bytecode. > > I want to distribute a software written in Python without the source. > So I compiled Python from source changing some opcode values (Taking > care of HAVE_ARGUMENT value) and distributed with the .pyc files. It > did compile but when I'm installing additional python modules using > easy_install, the import fails with a segmentation fault. It worked in > a 32 bit Centos 5.2 but not on 64bit Centos 5.2. I am using python > 2.5.4 source. > > I changed only the Include/opcode.py source with my jumbled opcode > values. Was I correct here ? I would like to know what all changes to > be made as to successfully compile a custom python with different > opcode values ? As you are the one who modified your Python, you are the one responsible for debugging that - noone else can. Did you try installing the egg *without* pyc-files in there? Because naturally those shouldn't work. They shouldn't crash the interpreter either, but then again - you *did* modify it. Diez From sreejithemk at gmail.com Tue Aug 18 03:42:10 2009 From: sreejithemk at gmail.com (Sreejith K) Date: Tue, 18 Aug 2009 00:42:10 -0700 (PDT) Subject: Changing Python Opcodes References: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> <7ev303F2ib9r1U1@mid.uni-berlin.de> Message-ID: <7cfe9433-37a6-456e-8a77-b0a8f17e5f23@e27g2000yqm.googlegroups.com> On Aug 18, 12:19?pm, "Diez B. Roggisch" wrote: > Did you try installing the egg *without* pyc-files in there? Because > naturally those shouldn't work. They shouldn't crash the interpreter > either, but then again - you *did* modify it. Hi Diez, thanks for the immediate reply :) I installed the setuptools using ez_setup.py script. Then I used the easy_install to install additional modules. When importing the installed modules segfault occurs. The module I installed was TurboGears. Then I thought that it happened maybe because the easy_install script is downloading eggs for original python (I'm not sure if it is what easy_install is doing). So I also tried to install the module by downloading all the dependencies (tar.gz files) and building it. Even then segfault occured. Is there any problem in changing only the opcodes.py file ? I did something horribly wrong here. Hope someone will help... From nospam at nospam.com Tue Aug 18 03:49:41 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 09:49:41 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <3vjk85hapd0nuigp09qrihm6e7faliompd@4ax.com> <874os5k35x.fsf@benfinney.id.au> Message-ID: <10nk85le4ghbb22ogjuta10cneir6pcc8p@4ax.com> On Tue, 18 Aug 2009 17:10:50 +1000, Ben Finney wrote: >Luckily, you have access to the documentation to find out. I never used groups before. Thanks for showing me. At this point, the script is almost done, but the regex fails if the month contains accented characters (eg. "Ao?t", but fine if eg. "Jan"). Adding a line to load the French locale doesn't help :-/ Any idea what I could do to keep the regex happy? Thank you. ============== import re import apsw import locale #In case error due to accent in month name, but no soup 4 U locale.setlocale(locale.LC_ALL, 'FR') connection=apsw.Connection("test.sqlite") cursor=connection.cursor() re_inscription = re.compile(r"(?P\d+)\s+(?P\w+)\s+(?P\d+)") sql = 'SELECT id,dateinscription,dateconnexion FROM mytable' rows=list(cursor.execute(sql)) for row in rows: dateinscription = row[1] dateconnexion = row[2] #Prints OK print dateinscription m = re_inscription.search(dateinscription) if m: day = m.group("date") month = m.group("month") year = m.group("year") print "%s-%s-%s" % (year,month,day) else: print "No go" ============== From weinhand at unileoben.ac.at Tue Aug 18 03:59:20 2009 From: weinhand at unileoben.ac.at (Weinhandl Herbert) Date: Tue, 18 Aug 2009 09:59:20 +0200 Subject: Data visualization in Python In-Reply-To: References: Message-ID: <4a8a5f86$0$12126$3b214f66@aconews.univie.ac.at> Am 2009-08-17 21:10, schrieb kj: > I'm looking for a good Python package for visualizing > scientific/statistical data. (FWIW, the OS I'm interested in is > Mac OS X). > > The users of this package will be experimental biologists with > little programming experience (but currently learning Python). SciDAVis is a free application for Scientific Data Analysis and Visualization. http://scidavis.sourceforge.net/ Veusz is a scientific plotting and graphing package written in Python. http://home.gna.org/veusz/ Open source data visualization and analysis for novice and experts. Data mining through visual programming or Python scripting. Extensions for bioinformatics and text mining. Comprehensive, flexible and fast. http://www.ailab.si/orange/ > (I normally visualize data using R or Mathematica, but I don't want > to saddle these novices with the task of learning yet another > language.) hth Herbert From nitebirdz at sacredchaos.com Tue Aug 18 04:07:32 2009 From: nitebirdz at sacredchaos.com (nitebirdz at sacredchaos.com) Date: Tue, 18 Aug 2009 10:07:32 +0200 Subject: Using a Callback Function - ftplib In-Reply-To: References: <76875cdd-30c4-4a3b-8a16-d0e2061765d7@v2g2000vbb.googlegroups.com> <1euafoc8zeh0q.91hedjv5ueuh$.dlg@40tude.net> Message-ID: <20090818080731.GA12396@sevilla.sacredchaos.com> On Mon, Aug 17, 2009 at 11:10:25AM -0700, seldan24 wrote: > > I didn't even notice the higher level methods. I changed the > retrieval line to: > > ftp.nlst("testfile*.txt") > > This works great. The result is even captured in an array. I really > have no idea what the difference between a LIST and NLST is within > FTP. Never delved that deep into it. I did notice that an NLST will > return a specific FTP code if a file doesn't exist, whereas a LIST > doesn't. So, I ended up using NLST as that'll generate an > ftplib.error_perm exception. Based on if the job cares if a file is > not available or not (some do, some don't), I'll either exit, or > continue on with the file loop. > The following thread from a NetBSD mailing list may help clarify this issue: http://mail-index.netbsd.org/netbsd-users/2001/01/30/0016.html NLST returns a machine-readable list of names, while LIST returns a human-readable list. Hene the presence of the FTP code in the case of NLST. From rami.chowdhury at gmail.com Tue Aug 18 04:11:20 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 18 Aug 2009 01:11:20 -0700 Subject: Converting DD MM YYYY into YYYY-MM-DD? In-Reply-To: <10nk85le4ghbb22ogjuta10cneir6pcc8p@4ax.com> References: <874os5k35x.fsf@benfinney.id.au> <10nk85le4ghbb22ogjuta10cneir6pcc8p@4ax.com> Message-ID: <200908180111.20975.rami.chowdhury@gmail.com> Could you let me know which platform this is on (Windows, *nix)? It may be a locale encoding issue -- the locale.setlocale() function allows the second argument to be a tuple of (locale_code, encoding), as below: locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) Since this is for a one-shot (and presumably threading-agnostic) program, and a fairly trivially formatted date-string, I would suggest using datetime.strptime (http://docs.python.org/library/datetime.html#datetime.datetime.strptime) and not regular expressions (which IIRC have Issues with non-ASCII characters). ---- Rami Chowdhury "Ninety percent of everything is crap." -- Sturgeon's Law 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Tuesday 18 August 2009 00:49:41 Gilles Ganault wrote: > On Tue, 18 Aug 2009 17:10:50 +1000, Ben Finney > > wrote: > >Luckily, you have access to the documentation to find out. > > I never used groups before. Thanks for showing me. > > At this point, the script is almost done, but the regex fails if the > month contains accented characters (eg. "Ao?t", but fine if eg. > "Jan"). > > Adding a line to load the French locale doesn't help :-/ > > Any idea what I could do to keep the regex happy? > > Thank you. > > ============== > import re > import apsw > import locale > > #In case error due to accent in month name, but no soup 4 U > locale.setlocale(locale.LC_ALL, 'FR') > > connection=apsw.Connection("test.sqlite") > cursor=connection.cursor() > > re_inscription = > re.compile(r"(?P\d+)\s+(?P\w+)\s+(?P\d+)") > > sql = 'SELECT id,dateinscription,dateconnexion FROM mytable' > rows=list(cursor.execute(sql)) > for row in rows: > dateinscription = row[1] > dateconnexion = row[2] > > #Prints OK > print dateinscription > > m = re_inscription.search(dateinscription) > if m: > day = m.group("date") > month = m.group("month") > year = m.group("year") > print "%s-%s-%s" % (year,month,day) > else: > print "No go" > ============== From martin at v.loewis.de Tue Aug 18 04:12:06 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 18 Aug 2009 10:12:06 +0200 Subject: Mercurial migration: help needed Message-ID: <4A8A6256.1030009@v.loewis.de> This is a repost from two weeks ago. It didn't get much feedback last time. I still keep trying, reposting to python-list also this time. In this thread, I'd like to collect things that ought to be done but where Dirkjan has indicated that he would prefer if somebody else did it. Item 1 ------ The first item is build identification. If you want to work on this, please either provide a patch (for trunk and/or py3k), or (if you are a committer) create a subversion branch. It seems that Barry and I agree that for the maintenance branches, sys.subversion should be frozen, so we need actually two sets of patches: one that removes sys.subversion entirely, and the other that freezes the branch to the respective one, and freezes the subversion revision to None. The patch should consider what Dirkjan proposes as the branching strategy: clones to separate 2.x and 3.x, as well as for features, and branches with the clones for releases and maintenance (see the PEP for details). Anybody working on this should have good knowledge of the Python source code, Mercurial, and either autoconf or Visual Studio (preferably both). Item 2 ------ The second item is line conversion hooks. Dj Gilcrease has posted a solution which he considers a hack himself. Mark Hammond has also volunteered, but it seems some volunteer needs to be "in charge", keeping track of a proposed solution until everybody agrees that it is a good solution. It may be that two solutions are necessary: a short-term one, that operates as a hook and has limitations, and a long-term one, that improves the hook system of Mercurial to implement the proper functionality (which then might get shipped with Mercurial in a cross-platform manner). Regards, Martin From nospam at nospam.com Tue Aug 18 04:19:53 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 10:19:53 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <874os5k35x.fsf@benfinney.id.au> <10nk85le4ghbb22ogjuta10cneir6pcc8p@4ax.com> Message-ID: On Tue, 18 Aug 2009 01:11:20 -0700, Rami Chowdhury wrote: >Could you let me know which platform this is on (Windows, *nix)? It may be a >locale encoding issue -- the locale.setlocale() function allows the second >argument to be a tuple of (locale_code, encoding), as below: > >locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) It's on XP, and I'm using ActivePython 2.5.1.1. http://www.activestate.com/activepython/ Python doesn't like the above: #locale.Error: unsupported locale setting locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) Maybe it was introduced in more recent versions of Python? >Since this is for a one-shot (and presumably threading-agnostic) program, and >a fairly trivially formatted date-string, I would suggest using >datetime.strptime >(http://docs.python.org/library/datetime.html#datetime.datetime.strptime) and >not regular expressions (which IIRC have Issues with non-ASCII characters). If the regex library can only handle basic latin characters, I'll wait until a script I'm running is done, and I'll upgrade to the 2.6.2.2 to see how it goes. Thank you. From dirkjan at ochtman.nl Tue Aug 18 04:20:15 2009 From: dirkjan at ochtman.nl (Dirkjan Ochtman) Date: Tue, 18 Aug 2009 10:20:15 +0200 Subject: [Python-Dev] Mercurial migration: help needed In-Reply-To: <4A8A6256.1030009@v.loewis.de> References: <4A8A6256.1030009@v.loewis.de> Message-ID: On Tue, Aug 18, 2009 at 10:12, "Martin v. L?wis" wrote: > In this thread, I'd like to collect things that ought to be done > but where Dirkjan has indicated that he would prefer if somebody else > did it. I think the most important item here is currently the win32text stuff. Mark Hammond said he would work on this; Mark, when do you have time for this? Then I could set apart some time for it as well. Have stalled a bit on the fine-grained branch processing, hope to move that forward tomorrow. Cheers, Dirkjan From clp2 at rebertia.com Tue Aug 18 04:28:25 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 01:28:25 -0700 Subject: conversion of Python object to perl object In-Reply-To: <229114.26317.qm@web7901.mail.in.yahoo.com> References: <229114.26317.qm@web7901.mail.in.yahoo.com> Message-ID: <50697b2c0908180128i48ac0d77sa04db33a05ab2c7@mail.gmail.com> On Mon, Aug 17, 2009 at 3:47 AM, srinivasan srinivas wrote: > Hi, > I have to call a perl method which takes a hash as its?argument from a python module. Is there a way to convert python dictionary to perl hash ( not hash ref)? How are you calling the Perl method from Python in the first place? Cheers, Chris -- http://blog.rebertia.com From paul at boddie.org.uk Tue Aug 18 04:34:58 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 18 Aug 2009 01:34:58 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> <3d808272-6e56-4cf1-90df-8e5201df02df@c34g2000yqi.googlegroups.com> <13be5a11-612b-4fc5-a220-cc9aba2e4f8c@z31g2000yqd.googlegroups.com> <611687df-e755-4910-9042-5dab20de1a7e@c34g2000yqi.googlegroups.com> Message-ID: <2f09b257-98c1-432c-8643-3bf1c5bdc875@e27g2000yqm.googlegroups.com> On 18 Aug, 05:19, ru... at yahoo.com wrote: > > Yes, I agree. ?I should have mentioned this as an exception > in my "wikis suck" diatribe. ?Although it far better than > most wiki's I've seen, it is still pretty easy to find signs > of typical wiki-ness. ?On the Documentation page my first > click was on AnnotableDocumentation: 404. Well, "Annotatable Documentation" is an external link. All we can do in such cases is to tidy such stuff up, mark it as invalid, or remove it. >?Second try, DoumentationDiscussion: two very short paragraphs dated 2003. Right. There are parts of the Wiki which were used actively in the past but which have fallen into disrepair. Some pages lack focus - they've been created according to "old school" Wiki conventions which I regard as being somewhat obsolete (just creating new pages all over the place to cover whatever happens to be in the writer's head at the time) - and every now and again, I attempt to rationalise these pages and focus their content. > After that I found some useful (in general though not what I > was looking for) information but not a good first impression. > (Well not exactly first, in fairness I have used other wiki > sections such as the Templating page and found them very > useful.) It needs work, of course. [...] > I took a look at the PHP docs last night which seem > pretty well done. ?The User Comments looked rather as I > expected, there was useful info but most did not contain > documentation quality writing. ?So if they are used as > a source for improving the docs, there clearly must be a > pretty large amount of editorial effort required, although > much of it is probably just filtering out comments that > don't provide any information appropriate for inclusion > in the docs. ?They list 38 names under "User Note Maintainers" > (http://www.php.net/manual/en/preface.php) > Unfortunately I couldn't find a description of what these > people actually do. ?I don't know how much work was involved > in removing the comments that are no longer there. Indeed. There's always the editorial bottleneck unless it's a total free-for-all situation. I've remarked before about how user comments don't necessarily add significantly to documentation, which is an assertion that some people make, and there definitely does need to be a process of integrating the best feedback into the main work. The crucial difference between a Wiki and an annotation system is the combination of the contribution and editorial aspects in a Wiki - you edit the actual work, and people can decide whether it's a good edit or not - in contrast to their separation in most annotation systems. In some cases, strict annotation systems are probably better: the GPLv3 annotation system was oriented towards discussion of the text, and that's not so effectively done in a Wiki. > Again, I don't mean to sound like I am dissing the idea > of annotatable docs -- I think it is a good idea and will > provide useful supplementary information. Where there's a separation of annotation and editing, I worry about the editorial bottleneck. I also worry about "handprint" edits more generally, where people just want to leave their touch on the work without actually contributing anything of substance. > But I continue to question whether this will result in > improvements in the docs themselves (which is my main > interest) unless: > > ? ?1. The purpose of the wiki is clearly "marketed" as > soliciting suggestions, rewrites, etc destined ultimately > for inclusion in the docs. I'm happy to see tangential work rather than stuff which fills exactly the same role as the current documentation. For example, the Python module of the week articles (PyMOTW, [1]) are exactly the kind of tangential work that could be encouraged, even though that is not so much a collaborative work itself. Paul [1] http://www.doughellmann.com/PyMOTW/ From rami.chowdhury at gmail.com Tue Aug 18 04:42:26 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 18 Aug 2009 01:42:26 -0700 Subject: Converting DD MM YYYY into YYYY-MM-DD? In-Reply-To: References: Message-ID: <200908180142.26979.rami.chowdhury@gmail.com> > Python doesn't like the above: > > #locale.Error: unsupported locale setting > locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) > > Maybe it was introduced in more recent versions of Python? Hmm, that's odd. According to the docs (http://docs.python.org/library/locale.html#locale.setlocale) it's been that way since 2.0, but I've just checked this on my Windows (Vista) machine and you're right, it returns an error. This worked for me on 32-bit Vista: locale.setlocale(locale.LC_ALL, 'FR') It uses Windows-1252 for the encoding, but that seems to deal with the circonflexe in 'Ao?t' just fine, so it should work for this purpose. ---- Rami Chowdhury "Never attributed to malice that which can be attributed to stupidity." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Tuesday 18 August 2009 01:19:53 Gilles Ganault wrote: > On Tue, 18 Aug 2009 01:11:20 -0700, Rami Chowdhury > > wrote: > >Could you let me know which platform this is on (Windows, *nix)? It may be > > a locale encoding issue -- the locale.setlocale() function allows the > > second argument to be a tuple of (locale_code, encoding), as below: > > > >locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) > > It's on XP, and I'm using ActivePython 2.5.1.1. > http://www.activestate.com/activepython/ > > Python doesn't like the above: > > #locale.Error: unsupported locale setting > locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) > > Maybe it was introduced in more recent versions of Python? > > >Since this is for a one-shot (and presumably threading-agnostic) program, > > and a fairly trivially formatted date-string, I would suggest using > >datetime.strptime > >(http://docs.python.org/library/datetime.html#datetime.datetime.strptime) > > and not regular expressions (which IIRC have Issues with non-ASCII > > characters). > > If the regex library can only handle basic latin characters, I'll wait > until a script I'm running is done, and I'll upgrade to the 2.6.2.2 to > see how it goes. > > Thank you. From nospam at nospam.com Tue Aug 18 04:52:41 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 10:52:41 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: I find it odd that the regex library can't handle European characters :-/ From indermeet.gandhi at gmail.com Tue Aug 18 04:55:35 2009 From: indermeet.gandhi at gmail.com (inder) Date: Tue, 18 Aug 2009 01:55:35 -0700 (PDT) Subject: XML parsing with python References: <4a8a4918$0$32672$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <25838ee3-897a-4979-bd08-c2d0287d02c0@f37g2000yqn.googlegroups.com> On Aug 18, 11:24?am, Stefan Behnel wrote: > inder wrote: > > On Aug 17, 8:31 pm, John Posner wrote: > >>> Use the iterparse() function of the xml.etree.ElementTree package. > >>>http://effbot.org/zone/element-iterparse.htm > >>>http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk > >>> Stefan > >> iterparse() is too big a hammer for this purpose, IMO. How about this: > > >> ? from xml.etree.ElementTree import ElementTree > >> ? tree = ElementTree(None, "myfile.xml") > >> ? for elem in tree.findall('//book/title'): > >> ? ? ? print elem.text > > >> -John > > > Thanks for the prompt reply . > > > I feel let me try using iterparse. Will it be slower compared to SAX > > parsing ... ultimately I will have a huge xml file to parse ? > > If you use the cElementTree module, it may even be faster. > > > Another question , I will also need to validate my xml against xsd . I > > would like to do this validation through the parsing tool ?itself . > > In that case, you can use lxml instead of ElementTree. > > http://codespeak.net/lxml/ > > Stefan Hi , Is lxml part of standard python package ? I am having python 2.5 . I might not be able to use any additional package other than the standard python . Could you please suggest something part of standard python package ? Thanks From deets at nospam.web.de Tue Aug 18 04:57:58 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 10:57:58 +0200 Subject: Changing Python Opcodes References: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> <7ev303F2ib9r1U1@mid.uni-berlin.de> <7cfe9433-37a6-456e-8a77-b0a8f17e5f23@e27g2000yqm.googlegroups.com> Message-ID: <7ev8omF2ffh1jU1@mid.uni-berlin.de> Sreejith K wrote: > On Aug 18, 12:19?pm, "Diez B. Roggisch" wrote: > >> Did you try installing the egg *without* pyc-files in there? Because >> naturally those shouldn't work. They shouldn't crash the interpreter >> either, but then again - you *did* modify it. > > Hi Diez, thanks for the immediate reply :) > > I installed the setuptools using ez_setup.py script. Then I used the > easy_install to install additional modules. When importing the > installed modules segfault occurs. The module I installed was > TurboGears. > > Then I thought that it happened maybe because the easy_install script > is downloading eggs for original python (I'm not sure if it is what > easy_install is doing). Yep, that's actually it's main purpose. > So I also tried to install the module by > downloading all the dependencies (tar.gz files) and building it. Even > then segfault occured. Is there any problem in changing only the > opcodes.py file ? I did something horribly wrong here. Hope someone > will help... I don't know. You modified this yourself. If I were in your situation, what I would have done is to - modify the version-information stored in my PYC-files so that I'm sure I don't accidentally load any "normal" PYC-files. Python does check that through some magic number, make sure you use your own. - fire up the debugger and see where the segfault actually happens. Nobody can be helping you there, because it's *your* code, not Python anymore. And giving others access to it defies somewhat the purpose of the whole exercise.... Diez From nospam at nospam.com Tue Aug 18 05:07:21 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 11:07:21 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: On Tue, 18 Aug 2009 10:52:41 +0200, Gilles Ganault wrote: >I find it odd that the regex library can't handle European characters >:-/ Ha, found it! :-) http://www.regular-expressions.info/python.html ========= # -*- coding: latin-1 -*- import locale import re locale.setlocale(locale.LC_ALL, 'FR') re_inscription = re.compile(r"(?P\d+)\s+(?P\w+)\s+(?P\d+)",re.LOCALE) dateinscription = "11 Ao?t 2008" m = re_inscription.search(dateinscription) if m: day = m.group("date") month = m.group("month") year = m.group("year") print "%s-%s-%s" % (year,month,day) else: print "Yuck" ========= Thanks everyone! From http Tue Aug 18 05:15:51 2009 From: http (Paul Rubin) Date: 18 Aug 2009 02:15:51 -0700 Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> <3d808272-6e56-4cf1-90df-8e5201df02df@c34g2000yqi.googlegroups.com> <13be5a11-612b-4fc5-a220-cc9aba2e4f8c@z31g2000yqd.googlegroups.com> <611687df-e755-4910-9042-5dab20de1a7e@c34g2000yqi.googlegroups.com> Message-ID: <7xiqgl7a9k.fsf@ruckus.brouhaha.com> rurpy at yahoo.com writes: > I took a look at the PHP docs last night which seem pretty well > done. The User Comments looked rather as I expected, there was > useful info but most did not contain documentation quality writing. > So if they are used as a source for improving the docs, there > clearly must be a pretty large amount of editorial effort required, > although much of it is probably just filtering out comments that > don't provide any information appropriate for inclusion in the docs. The comments section contains questions from users and answers to those questions from other users. What you may be missing is the part of the comments useful to the doc maintainers is primarily the user questions, rather than the user answers. The questions show the doc writer exactly what parts of the official doc are unclear or incomplete. The user-written answers may be wrong or generally crap, but the doc writer now knows what to do to improve the doc. That's why it's such a win to have the comments on the same page as the official docs. See also the user-commented http://book.realworldhaskell.org/read/ where the comments really helped clarify the finished (dead tree) text. From stefan_ml at behnel.de Tue Aug 18 05:26:02 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 Aug 2009 11:26:02 +0200 Subject: XML parsing with python In-Reply-To: <25838ee3-897a-4979-bd08-c2d0287d02c0@f37g2000yqn.googlegroups.com> References: <4a8a4918$0$32672$9b4e6d93@newsspool2.arcor-online.net> <25838ee3-897a-4979-bd08-c2d0287d02c0@f37g2000yqn.googlegroups.com> Message-ID: <4a8a73aa$0$32676$9b4e6d93@newsspool2.arcor-online.net> inder wrote: > Is lxml part of standard python package ? I am having python 2.5 . No, that's why I suggested ElementTree first. > I might not be able to use any additional package other than the > standard python . Could you please suggest something part of standard > python package ? No, there isn't any XMLSchema support in the stdlib. However, you may still be able to use lxml locally for development and with validation enabled, and switch to non-validating ElementTree on distribution/pre-prod-testing/whatever. Just use a conditional import and write a bit of setup code. Stefan From hendrik at microcorp.co.za Tue Aug 18 05:49:12 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 18 Aug 2009 11:49:12 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> References: <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> Message-ID: <200908181149.12382.hendrik@microcorp.co.za> On Monday 17 August 2009 23:06:04 Carl Banks wrote: > On Aug 17, 10:03?am, Jean-Michel Pichavant > > wrote: > > I'm no English native, but I already heard women/men referring to a > > group as "guys", no matter that group gender configuration. It's even > > used for group composed exclusively of women. Moreover it looks like a > > *very* friendly form, so there is really nothing to worry about it. > > I like how being very friendly means calling people after a guy who > tried to blow up the English Parliament. +1 QOTW - Hendrik From __peter__ at web.de Tue Aug 18 05:55:57 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 18 Aug 2009 11:55:57 +0200 Subject: Changing Python Opcodes References: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> <7ev303F2ib9r1U1@mid.uni-berlin.de> <7cfe9433-37a6-456e-8a77-b0a8f17e5f23@e27g2000yqm.googlegroups.com> <7ev8omF2ffh1jU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Sreejith K wrote: >> So I compiled Python from source changing some opcode values > Nobody > can be helping you there, because it's *your* code, not Python anymore. > And giving others access to it defies somewhat the purpose of the whole > exercise.... ...and everyone with the expertise to decompile your application and do something useful with the result will also be able to find this thread. Basically you're trying the security through obscurity stunt without the obscurity... Peter From nitebirdz at sacredchaos.com Tue Aug 18 06:02:44 2009 From: nitebirdz at sacredchaos.com (Nitebirdz) Date: Tue, 18 Aug 2009 12:02:44 +0200 Subject: Using a Callback Function - ftplib In-Reply-To: References: <76875cdd-30c4-4a3b-8a16-d0e2061765d7@v2g2000vbb.googlegroups.com> <1euafoc8zeh0q.91hedjv5ueuh$.dlg@40tude.net> Message-ID: <20090818100243.GB16443@sevilla.sacredchaos.com> On Mon, Aug 17, 2009 at 11:10:25AM -0700, seldan24 wrote: > > I didn't even notice the higher level methods. I changed the > retrieval line to: > > ftp.nlst("testfile*.txt") > > This works great. The result is even captured in an array. I really > have no idea what the difference between a LIST and NLST is within > FTP. Never delved that deep into it. I did notice that an NLST will > return a specific FTP code if a file doesn't exist, whereas a LIST > doesn't. So, I ended up using NLST as that'll generate an > ftplib.error_perm exception. Based on if the job cares if a file is > not available or not (some do, some don't), I'll either exit, or > continue on with the file loop. > The following thread from a NetBSD mailing list may help clarify this issue: http://mail-index.netbsd.org/netbsd-users/2001/01/30/0016.html NLST returns a machine-readable list of names, while LIST returns a human-readable list. Hene the presence of the FTP code in the case of NLST. From ben+python at benfinney.id.au Tue Aug 18 06:03:47 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 20:03:47 +1000 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: <87iqgligl8.fsf@benfinney.id.au> Gilles Ganault writes: > dateinscription = "11 Ao?t 2008" For any text string that's not ASCII, you should specify it as Unicode. (Actually, you should specify text as Unicode anyway.) For a literal text string: dateinscription = u"11 Ao?t 2008" If you're using exclusively Python 3, you will get Unicode text literals by default; but I assume you're using Python 2 based on existing discussion. The principles of handling text in Python: Get it to internal Unicode objects as soon as possible, handle it as Unicode for as long as possible, and only encode it to some byte stream for output as late as possible. -- \ ?When a well-packaged web of lies has been sold to the masses | `\ over generations, the truth will seem utterly preposterous and | _o__) its speaker a raving lunatic.? ?Dresden James | Ben Finney From sleepy at cabbage.co.uk Tue Aug 18 06:05:18 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Tue, 18 Aug 2009 10:05:18 GMT Subject: urlopen errors in script Message-ID: I'm scripting a superkaramba theme using python and have intgrated output from amarok. I have also would like to show the artist and song title from a radio stream i've added to my playlist. If I open a python console and add the following: >>>import urllib2 >>>from urllib2 import urlopen >>>nowplaying = str.split(urlopen('http://www.hearteastmids.co.uk// jsfiles/NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% 2F6854.xml&l=6854&tzc=8&at=HeartEastMids').read(),'>') >>>print test[4][:-3] this works and displays the artist and song title. However, when I add this to my script I get the following errors: ---------------------------------------------------------------------------- superkaramba(28855) ThemesDlg::addThemeToList: addThemeToList() file: "/ home/sleepy/dev/MyTheme/ MyTheme.theme" superkaramba(28855) Karamba::startKaramba: Loading script module: "MyTheme.py" superkaramba(28855) KarambaInterface::initInterpreter: Using "python" script: "/home/sleepy/dev/MyTheme/ MyTheme.py" Kross: "Loading the interpreter library for python" Kross: "Successfully loaded Interpreter instance from library." Kross: "PythonScript::Constructor." Kross: "PythonScript::execute" Kross: "PythonInterpreter::extractException: File "/home/sleepy/dev/MyTheme/MyTheme.py", line 4, in #this import statement allows access to the karamba functions File "/home/sleepy/dev/MyTheme/MyTheme.py", line 9, in import urllib2 File "", line 18, in _import File "/usr/lib/python2.6/urllib2.py", line 92, in import httplib File "", line 18, in _import File "/usr/lib/python2.6/httplib.py", line 1054, in import ssl File "", line 18, in _import File "/usr/lib/python2.6/ssl.py", line 81, in class SSLSocket (socket): " Kross: "Error error=Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) lineno=81 trace= File "/home/sleepy/dev/MyTheme/MyTheme.py", line 4, in #this import statement allows access to the karamba functions File "/home/sleepy/dev/MyTheme/MyTheme.py", line 9, in import urllib2 File "", line 18, in _import File "/usr/lib/python2.6/urllib2.py", line 92, in import httplib File "", line 18, in _import File "/usr/lib/python2.6/httplib.py", line 1054, in import ssl File "", line 18, in _import File "/usr/lib/python2.6/ssl.py", line 81, in class SSLSocket (socket): " TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python2.6/dist-packages/apport_python_hook.py", line 38, in apport_excepthook from apport.packaging_impl import impl as packaging File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/__init__.py", line 1, in from apport.report import Report File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/report.py", line 21, in import fileutils File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/fileutils.py", line 16, in from packaging_impl import impl as packaging File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/packaging_impl.py", line 18, in import apt File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apt/__init__.py", line 7, in from apt.package import Package File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apt/package.py", line 23, in import httplib File "", line 18, in _import File "/usr/lib/python2.6/httplib.py", line 1054, in import ssl File "", line 18, in _import File "/usr/lib/python2.6/ssl.py", line 81, in class SSLSocket (socket): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Original exception was: TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Kross: "PythonScript::Destructor." ------------------------------------------------------------------------ Thanks in advance From sleepy at cabbage.co.uk Tue Aug 18 06:07:41 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Tue, 18 Aug 2009 10:07:41 GMT Subject: urlopen errors in script Message-ID: I'm scripting a superkaramba theme using python and have intgrated output from amarok. I have also would like to show the artist and song title from a radio stream i've added to my playlist. If I open a python console and add the following: ">>>import urllib2" ">>>from urllib2 import urlopen" ">>>nowplaying = str.split(urlopen('http://www.hearteastmids.co.uk// jsfiles/NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% 2F6854.xml&l=6854&tzc=8&at=HeartEastMids').read(),'>')" ">>>print test[4][:-3]" this works and displays the artist and song title. However, when I add this to my script I get the following errors: ---------------------------------------------------------------------------- superkaramba(28855) ThemesDlg::addThemeToList: addThemeToList() file: "/ home/sleepy/dev/MyTheme/ MyTheme.theme" superkaramba(28855) Karamba::startKaramba: Loading script module: "MyTheme.py" superkaramba(28855) KarambaInterface::initInterpreter: Using "python" script: "/home/sleepy/dev/MyTheme/ MyTheme.py" Kross: "Loading the interpreter library for python" Kross: "Successfully loaded Interpreter instance from library." Kross: "PythonScript::Constructor." Kross: "PythonScript::execute" Kross: "PythonInterpreter::extractException: File "/home/sleepy/dev/MyTheme/MyTheme.py", line 4, in #this import statement allows access to the karamba functions File "/home/sleepy/dev/MyTheme/MyTheme.py", line 9, in import urllib2 File "", line 18, in _import File "/usr/lib/python2.6/urllib2.py", line 92, in import httplib File "", line 18, in _import File "/usr/lib/python2.6/httplib.py", line 1054, in import ssl File "", line 18, in _import File "/usr/lib/python2.6/ssl.py", line 81, in class SSLSocket (socket): " Kross: "Error error=Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) lineno=81 trace= File "/home/sleepy/dev/MyTheme/MyTheme.py", line 4, in #this import statement allows access to the karamba functions File "/home/sleepy/dev/MyTheme/MyTheme.py", line 9, in import urllib2 File "", line 18, in _import File "/usr/lib/python2.6/urllib2.py", line 92, in import httplib File "", line 18, in _import File "/usr/lib/python2.6/httplib.py", line 1054, in import ssl File "", line 18, in _import File "/usr/lib/python2.6/ssl.py", line 81, in class SSLSocket (socket): " TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python2.6/dist-packages/apport_python_hook.py", line 38, in apport_excepthook from apport.packaging_impl import impl as packaging File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/__init__.py", line 1, in from apport.report import Report File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/report.py", line 21, in import fileutils File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/fileutils.py", line 16, in from packaging_impl import impl as packaging File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/packaging_impl.py", line 18, in import apt File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apt/__init__.py", line 7, in from apt.package import Package File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apt/package.py", line 23, in import httplib File "", line 18, in _import File "/usr/lib/python2.6/httplib.py", line 1054, in import ssl File "", line 18, in _import File "/usr/lib/python2.6/ssl.py", line 81, in class SSLSocket (socket): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Original exception was: TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Kross: "PythonScript::Destructor." ------------------------------------------------------------------------ Thanks in advance From hendrik at microcorp.co.za Tue Aug 18 06:12:14 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 18 Aug 2009 12:12:14 +0200 Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) In-Reply-To: References: Message-ID: <200908181212.14882.hendrik@microcorp.co.za> On Tuesday 18 August 2009 06:45:39 Aahz wrote: > In article , > > Steven D'Aprano wrote: > >The comments were made a week ago -- why the sudden flurry of attention? > > Mainly an opportunity to flog the new diversity list. Here my English fails me - flog as in "whip", or flog as in "sell"? - Hendrik From nospam at nospam.com Tue Aug 18 06:21:07 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 12:21:07 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <87iqgligl8.fsf@benfinney.id.au> Message-ID: On Tue, 18 Aug 2009 20:03:47 +1000, Ben Finney wrote: >The principles of handling text in Python: Get it to internal Unicode >objects as soon as possible, handle it as Unicode for as long as >possible, and only encode it to some byte stream for output as late as >possible. Thanks much for the tip. I'll keep that in mind when I have strings with accents. From marduk at letterboxes.org Tue Aug 18 06:26:02 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 18 Aug 2009 06:26:02 -0400 Subject: Strongly typed list In-Reply-To: <7ev11jF1jj25dU1@mid.uni-berlin.de> References: <7718922b-c72c-4a7e-90a3-098318063013@n11g2000yqb.googlegroups.com> <7ev11jF1jj25dU1@mid.uni-berlin.de> Message-ID: <1250591162.10348.3.camel@blackwidow.nbk> On Tue, 2009-08-18 at 08:46 +0200, Diez B. Roggisch wrote: > Please could you lead me to a way or a good IDE that makes developing > > huge projects in python more easier than what i found.Now i am using > > eclips. Actually it is very hard to remember all my classes methods > > and attributes or copy and paste them each time. > > Thanks very much for your interest > > Hani Almousli..... > > There are many really big projects written in Python - none of them with > the aid of intelli-sense. > > What python lacks in that respect due to it's dynamic typing, it more > than compensates by being faster to develop and having to write much > less code. But this class can do *anything*! It .slice()s.. It .dice()s... ... sorry, couldn't resist ;-) -a From ben+python at benfinney.id.au Tue Aug 18 06:37:47 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 20:37:47 +1000 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <87iqgligl8.fsf@benfinney.id.au> Message-ID: <87ab1xif0k.fsf@benfinney.id.au> Gilles Ganault writes: > On Tue, 18 Aug 2009 20:03:47 +1000, Ben Finney > wrote: > >The principles of handling text in Python: Get it to internal Unicode > >objects as soon as possible, handle it as Unicode for as long as > >possible, and only encode it to some byte stream for output as late as > >possible. > > Thanks much for the tip. I'll keep that in mind when I have strings > with accents. Again, note that these recommendations hold for *any* text in Python, with or without accents; once you accept that text is best handled in Unicode, there's little sense in making an exception for the limited subset that happens to be representable in ASCII. -- \ ?The Bermuda Triangle got tired of warm weather. It moved to | `\ Alaska. Now Santa Claus is missing.? ?Steven Wright | _o__) | Ben Finney From rui.maciel at gmail.com Tue Aug 18 06:38:30 2009 From: rui.maciel at gmail.com (Rui Maciel) Date: Tue, 18 Aug 2009 11:38:30 +0100 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: <4a8a84a3$0$27142$a729d347@news.telepac.pt> Xah Lee wrote: > This feature is important in practical ways. For example, when you > work with ?tab separated line? files (CSV) that's a common format for > importing/exporting address books or spreadsheets. CSV stands for "comma separated values" and the import facilities of any spreadsheet application lets the user define the field separator character. Rui Maciel From ben+python at benfinney.id.au Tue Aug 18 06:38:36 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 20:38:36 +1000 Subject: Diversity in Python References: Message-ID: <8763cliez7.fsf@benfinney.id.au> Hendrik van Rooyen writes: > On Tuesday 18 August 2009 06:45:39 Aahz wrote: > > Mainly an opportunity to flog the new diversity list. > > Here my English fails me - flog as in "whip", or flog as in "sell"? Yes :-) -- \ ?The most common of all follies is to believe passionately in | `\ the palpably not true. It is the chief occupation of mankind.? | _o__) ?Henry L. Mencken | Ben Finney From __peter__ at web.de Tue Aug 18 07:21:59 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 18 Aug 2009 13:21:59 +0200 Subject: urlopen errors in script References: Message-ID: Sleepy Cabbage wrote: > I'm scripting a superkaramba theme using python and have intgrated output > from amarok. I have also would like to show the artist and song title from > a radio stream i've added to my playlist. > > If I open a python console and add the following: > > ">>>import urllib2" > ">>>from urllib2 import urlopen" > > ">>>nowplaying = str.split(urlopen('http://www.hearteastmids.co.uk// > jsfiles/NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% > 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% > 2F6854.xml&l=6854&tzc=8&at=HeartEastMids').read(),'>')" > > ">>>print test[4][:-3]" > > this works and displays the artist and song title. > > However, when I add this to my script I get the following errors: Please give a minimal version of your script that produces the error, not some arbitrary excerpt that you ran successfully on the command line. If I were to guess: you are doing something like import socket socket.socket = socket somewhere, thus confusing the socket class with the module of the same name. Peter From mhammond at skippinet.com.au Tue Aug 18 07:32:23 2009 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 18 Aug 2009 21:32:23 +1000 Subject: [Python-Dev] Mercurial migration: help needed In-Reply-To: References: <4A8A6256.1030009@v.loewis.de> Message-ID: <4A8A9147.7070109@skippinet.com.au> On 18/08/2009 6:20 PM, Dirkjan Ochtman wrote: > On Tue, Aug 18, 2009 at 10:12, "Martin v. L?wis" wrote: >> In this thread, I'd like to collect things that ought to be done >> but where Dirkjan has indicated that he would prefer if somebody else >> did it. > > I think the most important item here is currently the win32text stuff. > Mark Hammond said he would work on this; Mark, when do you have time > for this? Then I could set apart some time for it as well. I can make time, somewhat spasmodically, starting fairly soon. Might I suggest that as a first task I can resurrect my old stale patch, and you can arrange to install win32text locally and start experimenting with how mixed line-endings can work for you. Once we are all playing in the same ballpark I think we should be able to make good progress. I-said-ballpark-yet-I-call-myself-an-aussie? ly, Mark From jeanmichel at sequans.com Tue Aug 18 07:36:49 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 18 Aug 2009 13:36:49 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <4A89CEA2.10400@mrabarnett.plus.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <4A89CEA2.10400@mrabarnett.plus.com> Message-ID: <4A8A9251.3080200@sequans.com> MRAB wrote: > Carl Banks wrote: >> On Aug 17, 10:03 am, Jean-Michel Pichavant >> wrote: >>> I'm no English native, but I already heard women/men referring to a >>> group as "guys", no matter that group gender configuration. It's even >>> used for group composed exclusively of women. Moreover it looks like a >>> *very* friendly form, so there is really nothing to worry about it. >> >> I like how being very friendly means calling people after a guy who >> tried to blow up the English Parliament. >> > Guy Fawkes adopted the name Guido while fighting for the Spanish in the > Low Countries: > > http://en.wikipedia.org/wiki/Guy_Fawkes > I didn't get Carl's reference. The only thing I know about blowing the parliament is from the movie V for Vendetta (no comment please !). Now thanks to your link: "In 18th-century England, the term "guy" was used to refer to an effigy of Fawkes, which would be paraded around town by children on the anniversary of the conspiracy" Well, my knowledge is much too low to get this kind of reference from the start. :-/ JM From hani.mousli at gmail.com Tue Aug 18 07:37:54 2009 From: hani.mousli at gmail.com (=?UTF-8?B?2YfYp9mG2Yog2KfZhNmF2YjYtdmE2Yo=?=) Date: Tue, 18 Aug 2009 04:37:54 -0700 (PDT) Subject: Strongly typed list References: Message-ID: <1513faa5-e199-400c-a567-1f7b33aeb547@t13g2000yqt.googlegroups.com> I think i found a good managable solution. Actually it is trivial but may help (I used it now). When i wnat to access the list then i assign the object which i want to access to a variable ex: 1)x=AutomataBranch() 2)x=self.cfgAutomata[i] The first line is used only to make the IDE knows that x is from AutomatBranch type.After that when i press x. then all methods and properties are visualized. I think it is some how good. From exarkun at twistedmatrix.com Tue Aug 18 07:45:18 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Tue, 18 Aug 2009 11:45:18 -0000 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> <20090817194155.8740.902674574.divmod.xquotient.69@localhost.localdomain> Message-ID: <20090818114518.7602.827840579.divmod.xquotient.0@localhost.localdomain> On 03:56 am, tjreedy at udel.edu wrote: >exarkun at twistedmatrix.com wrote: >>There's a lot of things in Python that I don't strictly *need*. That >>doesn't mean that they wouldn't be welcome if I could have them. >>Getting rid of the range/xrange dichotomy would improve things. > >The developers agreed a couple of years ago. Starting using 3.1 if you >want this. And there was much rejoicing, et cetera. >Since 'range' could refer to a user-defined object, rather than the >builtin function, there is no way the interpreter should substitute >'xrange'. See the earlier parts of this thread for the reasons this isn't true. :) Jean-Paul From dirkjan at ochtman.nl Tue Aug 18 07:46:36 2009 From: dirkjan at ochtman.nl (Dirkjan Ochtman) Date: Tue, 18 Aug 2009 13:46:36 +0200 Subject: [Python-Dev] Mercurial migration: help needed In-Reply-To: <4A8A9147.7070109@skippinet.com.au> References: <4A8A6256.1030009@v.loewis.de> <4A8A9147.7070109@skippinet.com.au> Message-ID: On Tue, Aug 18, 2009 at 13:32, Mark Hammond wrote: > I can make time, somewhat spasmodically, starting fairly soon. ?Might I > suggest that as a first task I can resurrect my old stale patch, and you can > arrange to install win32text locally and start experimenting with how mixed > line-endings can work for you. ?Once we are all playing in the same ballpark > I think we should be able to make good progress. Sounds good to me. Cheers, Dirkjan From sleepy at cabbage.co.uk Tue Aug 18 07:48:42 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Tue, 18 Aug 2009 11:48:42 GMT Subject: urlopen errors in script References: Message-ID: On Tue, 18 Aug 2009 13:21:59 +0200, Peter Otten wrote: > Sleepy Cabbage wrote: > >> I'm scripting a superkaramba theme using python and have intgrated >> output from amarok. I have also would like to show the artist and song >> title from a radio stream i've added to my playlist. >> >> If I open a python console and add the following: >> >> ">>>import urllib2" >> ">>>from urllib2 import urlopen" >> >> ">>>nowplaying = str.split(urlopen('http://www.hearteastmids.co.uk// >> jsfiles/NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net% 2Ffeeds% >> 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% >> 2F6854.xml&l=6854&tzc=8&at=HeartEastMids').read(),'>')" >> >> ">>>print test[4][:-3]" >> >> this works and displays the artist and song title. >> >> However, when I add this to my script I get the following errors: > > Please give a minimal version of your script that produces the error, > not some arbitrary excerpt that you ran successfully on the command > line. > > If I were to guess: you are doing something like > > import socket > socket.socket = socket > > somewhere, thus confusing the socket class with the module of the same > name. > > Peter Thanks Peter. This is the script up to where the error seems to fall: "#!/usr/bin/env superkaramba" "# -*- coding: iso-8859-1 -*-" "import karamba" "import subprocess" "from subprocess import Popen, PIPE, STDOUT, call" "import urllib" "from urllib import urlopen" "#this is called when your widget is initialized" "def initWidget(widget):" "clkPause = karamba.createClickArea(widget, 156, 470, 35, 35, "qdbus org.kde.amarok /Player Pause")" "nowplaying = urllib.urlopen('http://www.hearteastmids.co.uk//jsfiles/ NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% 2F6854.xml&l=6854&tzc=8&at=HeartEastMids').read()" Hope this can enlighten things From stefan_ml at behnel.de Tue Aug 18 07:55:06 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 Aug 2009 13:55:06 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? In-Reply-To: <87ab1xif0k.fsf@benfinney.id.au> References: <87iqgligl8.fsf@benfinney.id.au> <87ab1xif0k.fsf@benfinney.id.au> Message-ID: <4a8a969b$0$30229$9b4e6d93@newsspool1.arcor-online.net> Ben Finney wrote: >>> The principles of handling text in Python: Get it to internal Unicode >>> objects as soon as possible, handle it as Unicode for as long as >>> possible, and only encode it to some byte stream for output as late as >>> possible. > Again, note that these recommendations hold for *any* text in Python, > with or without accents; once you accept that text is best handled in > Unicode, there's little sense in making an exception for the limited > subset that happens to be representable in ASCII. If the QOTW wasn't meant for fun, I'd vote for this. This is very good advice. Stefan From __peter__ at web.de Tue Aug 18 08:19:52 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 18 Aug 2009 14:19:52 +0200 Subject: urlopen errors in script References: Message-ID: Sleepy Cabbage wrote: > This is the script up to where the error seems to fall: > > "#!/usr/bin/env superkaramba" > "# -*- coding: iso-8859-1 -*-" > > "import karamba" > "import subprocess" > "from subprocess import Popen, PIPE, STDOUT, call" > "import urllib" > "from urllib import urlopen" > > "#this is called when your widget is initialized" > "def initWidget(widget):" > "clkPause = karamba.createClickArea(widget, 156, 470, 35, 35, "qdbus > org.kde.amarok /Player Pause")" > "nowplaying = urllib.urlopen('http://www.hearteastmids.co.uk//jsfiles/ > NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% > 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% > 2F6854.xml&l=6854&tzc=8&at=HeartEastMids').read()" > > Hope this can enlighten things While there isn't any obvious blunder apart from the odd quotes that you wrap around every line there seem to be other files missing to run the script. I'm sorry, but I'm not prepared to invest much more than $ sudo aptitude install superkaramba into the problem. Perhaps an actual user of superkaramba can step in. Peter From steve at REMOVE-THIS-cybersource.com.au Tue Aug 18 08:59:43 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 12:59:43 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <4A89CEA2.10400@mrabarnett.plus.com> Message-ID: <0014291d$0$2963$c3e8da3@news.astraweb.com> On Tue, 18 Aug 2009 13:36:49 +0200, Jean-Michel Pichavant wrote: > MRAB wrote: >> Carl Banks wrote: >>> On Aug 17, 10:03 am, Jean-Michel Pichavant >>> wrote: >>>> I'm no English native, but I already heard women/men referring to a >>>> group as "guys", no matter that group gender configuration. It's even >>>> used for group composed exclusively of women. Moreover it looks like >>>> a *very* friendly form, so there is really nothing to worry about it. >>> >>> I like how being very friendly means calling people after a guy who >>> tried to blow up the English Parliament. >>> >> Guy Fawkes adopted the name Guido while fighting for the Spanish in the >> Low Countries: >> >> http://en.wikipedia.org/wiki/Guy_Fawkes >> > I didn't get Carl's reference. The only thing I know about blowing the > parliament is from the movie V for Vendetta (no comment please !). Now > thanks to your link: > "In 18th-century England, the term "guy" was used to refer to an effigy > of Fawkes, which would be paraded > around town by children on the anniversary of the conspiracy" > > Well, my knowledge is much too low to get this kind of reference from > the start. :-/ "Guy" is an old English name, related to the old French name "Gy" and Italian "Guido". It's originally derived from the Old German for "wood" or "warrior". After Guy Fawkes tried to blow up the English Parliament house, and was executed, the British government encouraged people to burn effigies of him. These became known as "guys", which eventually became slang for an ugly man, which later became slang for any man, and in recent years, any person. So the irony is that the friendly term "guys", referring to a group of people, is derived from the name of an 18th century religious terrorist. One can only wonder whether in 200 years time people will walk into the office and say "Hey you osamas, they're giving away free donuts down stairs, anyone want some?" -- Steven From steve at REMOVE-THIS-cybersource.com.au Tue Aug 18 09:01:53 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 13:01:53 GMT Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) References: Message-ID: <001429a0$0$2963$c3e8da3@news.astraweb.com> On Tue, 18 Aug 2009 12:12:14 +0200, Hendrik van Rooyen wrote: > On Tuesday 18 August 2009 06:45:39 Aahz wrote: >> In article , >> >> Steven D'Aprano wrote: >> >The comments were made a week ago -- why the sudden flurry of >> >attention? >> >> Mainly an opportunity to flog the new diversity list. > > Here my English fails me - flog as in "whip", or flog as in "sell"? Almost certainly "flog" as in sell. But not literally sell, for money, but sell in the sense of convincing others it is a good list to join. -- Steven From sleepy at cabbage.co.uk Tue Aug 18 09:05:03 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Tue, 18 Aug 2009 13:05:03 GMT Subject: urlopen errors in script References: Message-ID: <3Gxim.148238$XK2.30441@newsfe15.ams2> Thanks for the time you've spent anyway Peter. I have superkaramba installed and the rest of the script is running fine, it's only when I put the urlopen part in that it comes back with errors. The quotes are just to make it readable on here as my first attempt at posting muted the text. From deets at nospam.web.de Tue Aug 18 09:15:42 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 15:15:42 +0200 Subject: Strongly typed list References: <1513faa5-e199-400c-a567-1f7b33aeb547@t13g2000yqt.googlegroups.com> Message-ID: <7evnruF2i9sm7U1@mid.uni-berlin.de> ???? ??????? wrote: > I think i found a good managable solution. Actually it is trivial but > may help (I used it now). > When i wnat to access the list then i assign the object which i want > to access to a variable ex: > 1)x=AutomataBranch() > 2)x=self.cfgAutomata[i] > > The first line is used only to make the IDE knows that x is from > AutomatBranch type.After that when i press x. then all methods and > properties are visualized. > > I think it is some how good. Unless x=AutomataBranch() is something that is expensive. And to be honest: changing code (possibly introducing bugs!!!) to work around short-comings in either your IDE or your way you insist to work strikes me as odd. I understand the desire to have autocompletion. But it's not *that* important. Maybe fabrio (who's maintaining the PyDev-eclipse-plugin) could be asked to add something like this: #@x:AutomataBranch to the plugin - so that when pydev reads that comment, it has a hint on what to use for autocompletion. Diez From naveen.garg at gmail.com Tue Aug 18 09:50:56 2009 From: naveen.garg at gmail.com (naveen) Date: Tue, 18 Aug 2009 06:50:56 -0700 (PDT) Subject: define class over 2 files References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> <6a490ec8-3536-4508-afd4-90a5cf9317b5@g10g2000yqh.googlegroups.com> <87zl9xiohe.fsf@benfinney.id.au> Message-ID: > indicator of bad practice. What is the problem you're trying to solve? > Ben Finney No major problem. I was just trying to make some experimental changes to autokey. My repo: http://github.com/tinku99/autokey.git/ Didn't want to subclass or reorganize a class just yet. From brochu121 at gmail.com Tue Aug 18 09:51:45 2009 From: brochu121 at gmail.com (David Brochu) Date: Tue, 18 Aug 2009 09:51:45 -0400 Subject: Compare content of two XML files Message-ID: <9583ed900908180651h270a2218nc1a3c3bab383e897@mail.gmail.com> I need to compare a REST XML response with a 'gold standard' response (one that we have already verified is correct). The problem is, sometimes the REST response comes back and it is logically correct, but the order of attributes and elements is different than what is in the 'gold standard' file. For example: 'Gold Standard': REST Response: Notice how the attributes in and are in different order. The response is correct, but obviously doesn't match the 'gold standard'. Does anyone know how I would be able to compare these two files and verify they match, even though the order of attributes and elements may be different between the two? Is there a module I should be using for this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjposner at optimum.net Tue Aug 18 10:04:36 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 18 Aug 2009 10:04:36 -0400 Subject: Code formatting question: conditional expression Message-ID: <4A8AB4F4.3040805@optimum.net> While refactoring some code, I ran across an opportunity to use a conditional expression. Original: if total > P.BASE: excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) else: excessblk = None Is there any consensus on how to format a conditional expression that is too long for one line? How about this: excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None) The above format separates the values from the if-then-else machinery. Too many lines? Would it be better to line up "if" and "else" vertically? ... excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None) PEP 308 is silent on this topic. -John From lauromoura at gmail.com Tue Aug 18 10:06:47 2009 From: lauromoura at gmail.com (Lauro Moura) Date: Tue, 18 Aug 2009 11:06:47 -0300 Subject: ANN: PySide has been released Message-ID: Hi, The PySide team is pleased to announce the first public release of PySide: Python for Qt! PySide, its documentation, and developer resources are available at the project website, http://www.pyside.org . What is it? ----------- PySide is a project providing an LGPL'd set of Python bindings for the Qt framework. PySide already provides a full set of Qt bindings as well as automated binding generation tools. Since the whole toolset has been made available, the team expects PySide to be valuable not only to Qt software developers, but to people willing to create Python bindings to any Qt-based library, or to any C++ library in general. Although based on a different technical approach, PySide will initially be API-compatible with existing Python bindings for Qt. PySide is still a work in progress, and some work is still required to stabilize the codebase. This being said, the team believes it is already in a usable state, especially if an occasional rough edge and unpainted surface can be tolerated. Due to practical reasons, the initial development efforts have been focused on Linux, but the team hopes people to join in porting the code to other platforms and to further develop the bindings and tools. Regards, PySide team -- Lauro Moura ("lmoura" on Freenode) http://lauro.wordpress.com From tuomas.vesterinen at iki.fi Tue Aug 18 10:08:23 2009 From: tuomas.vesterinen at iki.fi (Tuomas Vesterinen) Date: Tue, 18 Aug 2009 17:08:23 +0300 Subject: ANNOUNCEMENT: Tinybooker accounting released Message-ID: <4a8ab5d7$0$24765$9b536df3@news.fv.fi> Tinybooker 0.2.2 released at http://tinybooker.org/ Tinybooker is an accounting program offering the dual accounting core functionality for moderate size accountings: * Assisted establishing new accountings * Localized scheme templates * Easy entering and saving new entries * Standard reports in plain text or HTML: Income Statement, Balance Sheet, Journal, Nominal Ledger, Final Statement and Scheme * Assisted opening the next financial year * Accounting example as a demo * Open for auditing, all files human readable plain text * All written in pure Python * License GPL3 This early release is for Linux only. Later Tinybooker will be ported to Windows. Developers, more translations wanted, join the project contacting me at https://sourceforge.net/sendmessage.php?touser=2524141. From deets at nospam.web.de Tue Aug 18 10:10:01 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 16:10:01 +0200 Subject: Code formatting question: conditional expression References: Message-ID: <7evr1pF2i4mouU1@mid.uni-berlin.de> John Posner wrote: > While refactoring some code, I ran across an opportunity to use a > conditional expression. Original: > > if total > P.BASE: > excessblk = Block(total - P.BASE, srccol, > carry_button_suppress=True) > else: > excessblk = None > > Is there any consensus on how to format a conditional expression that is > too long for one line? How about this: > > excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) > if total > P.BASE else > None) > > The above format separates the values from the if-then-else machinery. > Too many lines? Would it be better to line up "if" and "else" > vertically? ... > > excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) > if total > P.BASE > else None) My choice would be excessblk = None if total > P.BASE: excessblk = ... You don't lose any vertical space, and it's much more readable IMHO. Diez From vs at it.uu.se Tue Aug 18 10:28:08 2009 From: vs at it.uu.se (Virgil Stokes) Date: Tue, 18 Aug 2009 16:28:08 +0200 Subject: Start-up program Message-ID: <4A8ABA78.8050605@it.uu.se> How difficult is to create a program that will be executed when Windows Vista is started? As Windows Calendar does, for example. I am actually more interested in the Python tools that might be used for this task. I hope that this question is not inappropriate for the list. :-\ --V From jeanmichel at sequans.com Tue Aug 18 10:32:02 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 18 Aug 2009 16:32:02 +0200 Subject: Code formatting question: conditional expression In-Reply-To: <7evr1pF2i4mouU1@mid.uni-berlin.de> References: <7evr1pF2i4mouU1@mid.uni-berlin.de> Message-ID: <4A8ABB62.80702@sequans.com> Diez B. Roggisch wrote: > John Posner wrote: > > >> While refactoring some code, I ran across an opportunity to use a >> conditional expression. Original: >> >> if total > P.BASE: >> excessblk = Block(total - P.BASE, srccol, >> carry_button_suppress=True) >> else: >> excessblk = None >> >> Is there any consensus on how to format a conditional expression that is >> too long for one line? How about this: >> >> excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) >> if total > P.BASE else >> None) >> >> The above format separates the values from the if-then-else machinery. >> Too many lines? Would it be better to line up "if" and "else" >> vertically? ... >> >> excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) >> if total > P.BASE >> else None) >> > > My choice would be > > excessblk = None > if total > P.BASE: > excessblk = ... > > > You don't lose any vertical space, and it's much more readable IMHO. > > Diez > +1, I'm using such layout whenever possible. JM From invalid at invalid Tue Aug 18 10:36:03 2009 From: invalid at invalid (Grant Edwards) Date: Tue, 18 Aug 2009 09:36:03 -0500 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> Message-ID: On 2009-08-17, Carl Banks wrote: > On Aug 17, 10:03?am, Jean-Michel Pichavant > wrote: >> I'm no English native, but I already heard women/men referring to a >> group as "guys", no matter that group gender configuration. It's even >> used for group composed exclusively of women. Moreover it looks like a >> *very* friendly form, so there is really nothing to worry about it. > > I like how being very friendly means calling people after a guy who > tried to blow up the English Parliament. Everybody likes fireworks! -- Grant Edwards grante Yow! Where do your SOCKS at go when you lose them in visi.com th' WASHER? From jliu6302 at yahoo.com Tue Aug 18 10:38:05 2009 From: jliu6302 at yahoo.com (John Liu) Date: Tue, 18 Aug 2009 07:38:05 -0700 (PDT) Subject: listen and receive the stock price from a VPN Message-ID: <685566.50872.qm@web53801.mail.re2.yahoo.com> Hi, My friends ? I am trying a Pyhton script to connect a VPN with (IP address, user ID, and passwrod). ? suppose I need to use Socket to connect the VPN and compare to a list of stock tickers I want to receive. ? Is there any wasy way and fast way to do that? ? Thanks so much in advance. ? Kindly regards, ? John -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Tue Aug 18 10:54:34 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Aug 2009 07:54:34 -0700 (PDT) Subject: GUI interface builder for python References: <21bca3cf-b2c7-47d7-9142-26c9fd015f92@r27g2000vbn.googlegroups.com> <02ec7cd9-e749-46d3-8b25-75d85794f292@o35g2000vbi.googlegroups.com> Message-ID: On 17 Aug, 17:19, Che M wrote: > Boa (Boa Constructor) is really nice for wxPython GUI > work, but it has some bugs when using Linux that might > be dealbreakers for the user. ?At least I have had > problems on Ubuntu 8.10 64 bit (but none or very few > I prefer wxFormBuilder over Boa. From steve at REMOVE-THIS-cybersource.com.au Tue Aug 18 10:54:36 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 14:54:36 GMT Subject: Code formatting question: conditional expression References: Message-ID: <0014440c$0$2963$c3e8da3@news.astraweb.com> On Tue, 18 Aug 2009 10:04:36 -0400, John Posner wrote: > While refactoring some code, I ran across an opportunity to use a > conditional expression. Original: > > if total > P.BASE: > excessblk = Block(total - P.BASE, srccol, > carry_button_suppress=True) > else: > excessblk = None > > Is there any consensus on how to format a conditional expression that is > too long for one line? Er, that defeats the purpose of using a conditional expression. If it's too long for one line, leave it as an if...else statement. > How about this: > > excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) > if total > P.BASE else > None) If you insist on using the conditional expression, my preference would be: excessblk = ( Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None ) -- Steven From jjposner at optimum.net Tue Aug 18 10:58:05 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 18 Aug 2009 10:58:05 -0400 Subject: Code formatting question: conditional expression In-Reply-To: References: Message-ID: <4A8AC17D.5080602@optimum.net> > > My choice would be > > excessblk = None > if total > P.BASE: > excessblk = ... > Diez and Jean-Michel, Ha! Your suggestion above was my *original* coding. It looks like I'm evolving backwards! But doesn't it violate the DRY principle? The token "excessblk" appears twice instead of once. Thanks again, John From dmitrey.kroshko at scipy.org Tue Aug 18 11:19:12 2009 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Tue, 18 Aug 2009 08:19:12 -0700 (PDT) Subject: simplest way to visit 3 subdirectories with a command? Message-ID: <487d46f0-db01-4134-b9a8-8360f5dc82f6@w41g2000yqb.googlegroups.com> hi all, could you inform how to compose a py-file (for soft installation), that will visit 3 subdirectories (eg subdir1, subdir2, subdir3) and invoke a command "python setup.py install" in each subdirectory? I know there should be a simple solution available in Python documentation, but I have an awful lots of other things to be done, so could someone write these several lines of code? Thank you in advance, D. From R.Brodie at rl.ac.uk Tue Aug 18 11:27:52 2009 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 18 Aug 2009 16:27:52 +0100 Subject: Code formatting question: conditional expression References: Message-ID: "John Posner" wrote in message news:mailman.26.1250604346.2854.python-list at python.org... > if total > P.BASE: > excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) > else: > excessblk = None I wonder if it is appropriate to replace the None sentinel with one that is an instance of Block() e.g. size = total - P.BASE excessblk = Block(size, srccol, carry_button_suppress=True, empty_block=(size <= 0) ) From holdenweb at gmail.com Tue Aug 18 11:55:54 2009 From: holdenweb at gmail.com (Steve Holden) Date: Tue, 18 Aug 2009 08:55:54 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> > > Robert Dailey: [...] > > It's a figure of speech. And besides, why would I want programming > advice from a woman? lol. Thanks for the help. Sorry, Robert, simply not acceptable. Whether designed to be funny or not it's the kind of inane remark I would be really happy never to see again. The problem is that we can't just "let these things go by" all the time (even though we aren't discussing a major crime here). If we do that it encourages (at best) an atmosphere of complacency and a feeling that it's OK to demean people in Python forums. I'd really like to see those *not* get a hold. regards Steve From jeanmichel at sequans.com Tue Aug 18 11:57:01 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 18 Aug 2009 17:57:01 +0200 Subject: Code formatting question: conditional expression In-Reply-To: <4A8AC17D.5080602@optimum.net> References: <4A8AC17D.5080602@optimum.net> Message-ID: <4A8ACF4D.2080805@sequans.com> John Posner wrote: >> >> My choice would be >> >> excessblk = None >> if total > P.BASE: >> excessblk = ... >> > > Diez and Jean-Michel, > > Ha! Your suggestion above was my *original* coding. It looks like I'm > evolving backwards! > > But doesn't it violate the DRY principle? The token "excessblk" > appears twice instead of once. > > Thanks again, > John > I don't see any problem in that. You are hunting poor readability, not redundancy, it's up to you to decide of you priorities. I would still advise that readability should rule your world. JM From deets at nospam.web.de Tue Aug 18 11:57:28 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 17:57:28 +0200 Subject: Start-up program References: Message-ID: <7f01b8F2hfu8qU1@mid.uni-berlin.de> Virgil Stokes wrote: > How difficult is to create a program that will be executed when Windows > Vista is started? As Windows Calendar does, for example. > > I am actually more interested in the Python tools that might be used for > this task. I hope that this question is not inappropriate for the list. There are many discussions here about creating an exe (py2exe) that you could start in autostart, and how to run scripts as windows services, which is the other option. Just google a bit. Diez From jeanmichel at sequans.com Tue Aug 18 12:00:09 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 18 Aug 2009 18:00:09 +0200 Subject: Start-up program In-Reply-To: <4A8ABA78.8050605@it.uu.se> References: <4A8ABA78.8050605@it.uu.se> Message-ID: <4A8AD009.5050005@sequans.com> Virgil Stokes wrote: > How difficult is to create a program that will be executed when > Windows Vista is started? As Windows Calendar does, for example. > > I am actually more interested in the Python tools that might be used > for this task. I hope that this question is not inappropriate for the > list. :-\ > > --V > Well put your program in your startup folder or configure it as a service in the service manager of windows. Now your problem becomes "How difficult is to create a program" for which there is no easy answer as it really depends on the kind of program. JM From madzientist at gmail.com Tue Aug 18 12:04:54 2009 From: madzientist at gmail.com (madzientist) Date: Tue, 18 Aug 2009 09:04:54 -0700 (PDT) Subject: Mac OS 9.2 Message-ID: <96ab6db4-55c5-4142-8ef8-d7fbe97e4c4d@f37g2000yqn.googlegroups.com> hi, i have to work with mac OS 9.2 for legacy reasons...is there a compiled version of python for this os ? i need to get input about variable values from the user and then print out some text files that make use of this input. a gui would be nice, but keyboard based input would be ok too... thanks much, suresh ps. if there isn't a version of pythn that will work, perhaps you could suggest some other scripting language for 0S 9.2 ? From python at mrabarnett.plus.com Tue Aug 18 12:09:24 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 18 Aug 2009 17:09:24 +0100 Subject: Start-up program In-Reply-To: <4A8ABA78.8050605@it.uu.se> References: <4A8ABA78.8050605@it.uu.se> Message-ID: <4A8AD234.7050205@mrabarnett.plus.com> Virgil Stokes wrote: > How difficult is to create a program that will be executed when Windows > Vista is started? As Windows Calendar does, for example. > > I am actually more interested in the Python tools that might be used for > this task. I hope that this question is not inappropriate for the list. :-\ > Look for the Windows Startup folder. A quick search with Google found: http://www.bleepingcomputer.com/forums/topic85142.html From nirvana117 at gmail.com Tue Aug 18 12:49:55 2009 From: nirvana117 at gmail.com (dou dou) Date: Wed, 19 Aug 2009 00:49:55 +0800 Subject: problem with interface of operator.itemgetter In-Reply-To: <50f98a4c0908161132o4bf73e80lf306f89108c1e669@mail.gmail.com> References: <19b355330908132016y49f2679u631c3123fcfc920a@mail.gmail.com> <50f98a4c0908161132o4bf73e80lf306f89108c1e669@mail.gmail.com> Message-ID: <19b355330908180949x2f8635dfk39ae892a9f6943b2@mail.gmail.com> 2009/8/17 Simon Forman > You can use a little helper function to create your itemgetter like this: > > def makeItemGetter(indexes): > I = itemgetter(*indexes) > if len(indexes) > 1: > return I > return lambda thing: (I(thing),) > > If indexes contains only one index the itemgetter is wrapped in a > lambda that turns its output into a tuple. Thanks. I just thought if the stdlib could support some function like item*s *getter would be better, it always returns tuple instead of a item or a tuple of items. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Tue Aug 18 13:05:49 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 18 Aug 2009 19:05:49 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> Message-ID: <4A8ADF6D.2030405@sequans.com> Steve Holden wrote: >>> Robert Dailey: >>> > [...] > >> It's a figure of speech. And besides, why would I want programming >> advice from a woman? lol. Thanks for the help. >> > > Sorry, Robert, simply not acceptable. Whether designed to be funny or > not it's the kind of inane remark I would be really happy never to see > again. > > The problem is that we can't just "let these things go by" all the > time (even though we aren't discussing a major crime here). If we do > that it encourages (at best) an atmosphere of complacency and a > feeling that it's OK to demean people in Python forums. I'd really > like to see those *not* get a hold. > > regards > Steve > Did you read the original post (this is an old one) ? Because quoting a joke out of its context is totally unfair. Anyway the hysteria that is surrounding this thread is just amazing. I'm waiting for more. JM From james.harris.1 at googlemail.com Tue Aug 18 13:09:29 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Tue, 18 Aug 2009 10:09:29 -0700 (PDT) Subject: Identifying a class type - bad practice? Message-ID: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> I am writing some code to form a tree of nodes of different types. The idea is to define one class per node type such as class node_type_1(node): class node_type_2(node): etc (Class "node" would hold any common properties). When walking the tree I need to know what type of node I'm dealing with so polymorphism isn't generally useful. The action to be taken depends on the node type. Two options appear to be useful: __class__ and isinstance. I know the latter will match the instance against any superclass and the former will match one class only. My question is: is this the Pythonic way to deal with such a tree? Is there a better way? In C I would use structs where one field was a tag indicating the kind of struct. James From python.list at tim.thechases.com Tue Aug 18 13:11:54 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 18 Aug 2009 12:11:54 -0500 Subject: simplest way to visit 3 subdirectories with a command? In-Reply-To: <487d46f0-db01-4134-b9a8-8360f5dc82f6@w41g2000yqb.googlegroups.com> References: <487d46f0-db01-4134-b9a8-8360f5dc82f6@w41g2000yqb.googlegroups.com> Message-ID: <4A8AE0DA.1080909@tim.thechases.com> > could you inform how to compose a py-file (for soft installation), > that will visit 3 subdirectories (eg subdir1, subdir2, subdir3) and > invoke a command "python setup.py install" in each subdirectory? > I know there should be a simple solution available in Python If you're executing "python setup.py install", that sounds like you're operating at the shell level, not within python. In which case, I'd just use my shell's iteration capabilities: # running bash on a *nix-like OS bash$ for dir in subdir1 subdir2 subdir3; do pushd $dir; python setup.py install; popd; done # running within Win32's cmd.exe c:\temp\> for %f in (subdir1 subdir2 subdir3) do pushd %f & python setup.py install & popd or something of the sort. Remember in Win32 that the variables have to be escaped if you put them in a batch file ("%%f" instead of "%f") -tkc From seldan24 at gmail.com Tue Aug 18 13:18:42 2009 From: seldan24 at gmail.com (seldan24) Date: Tue, 18 Aug 2009 10:18:42 -0700 (PDT) Subject: Using a Callback Function - ftplib References: <76875cdd-30c4-4a3b-8a16-d0e2061765d7@v2g2000vbb.googlegroups.com> <1euafoc8zeh0q.91hedjv5ueuh$.dlg@40tude.net> Message-ID: On Aug 18, 6:02?am, Nitebirdz wrote: > On Mon, Aug 17, 2009 at 11:10:25AM -0700, seldan24 wrote: > > > I didn't even notice the higher level methods. ?I changed the > > retrieval line to: > > > ftp.nlst("testfile*.txt") > > > This works great. ?The result is even captured in an array. ?I really > > have no idea what the difference between a LIST and NLST is within > > FTP. ?Never delved that deep into it. ?I did notice that an NLST will > > return a specific FTP code if a file doesn't exist, whereas a LIST > > doesn't. ?So, I ended up using NLST as that'll generate an > > ftplib.error_perm exception. ?Based on if the job cares if a file is > > not available or not (some do, some don't), I'll either exit, or > > continue on with the file loop. > > The following thread from a NetBSD mailing list may help clarify this > issue: > > http://mail-index.netbsd.org/netbsd-users/2001/01/30/0016.html > > NLST returns a machine-readable list of names, while LIST returns a > human-readable list. ?Hene the presence of the FTP code in the case of > NLST. ? Nitebirdz, Thanks for the information. I knew it stood for 'named list' but had no idea how that differed from the standard. I appreciate the link. From madzientist at gmail.com Tue Aug 18 13:19:10 2009 From: madzientist at gmail.com (madzientist) Date: Tue, 18 Aug 2009 10:19:10 -0700 (PDT) Subject: Mac OS 9.2 References: <96ab6db4-55c5-4142-8ef8-d7fbe97e4c4d@f37g2000yqn.googlegroups.com> Message-ID: <5ed2205e-9542-44c3-a8b7-70f52b0d09cb@r38g2000yqn.googlegroups.com> ok, i found macpython 2.3 at this site: http://homepages.cwi.nl/~jack/macpython/macpython-older.html is this the best option for me in terms of using python on os 9.2 ? thanks much !! suresh On Aug 18, 6:04?pm, madzientist wrote: > hi, > > i have to work with mac OS 9.2 for legacy reasons...is there a > compiled version of python for this os ? i need to get input about > variable values from the user and then print out some text files that > make use of this input. a gui would be nice, but keyboard based input > would be ok too... > > thanks much, > > suresh > > ps. if there isn't a version of pythn that will work, perhaps you > could suggest some other scripting language for 0S 9.2 ? From jjposner at optimum.net Tue Aug 18 13:25:46 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 18 Aug 2009 13:25:46 -0400 Subject: Code formatting question: conditional expression In-Reply-To: References: Message-ID: <4A8AE41A.3060107@optimum.net> > I wonder if it is appropriate to replace the None sentinel with one that is an instance > of Block() e.g. > > size = total - P.BASE > excessblk = Block(size, srccol, carry_button_suppress=True, empty_block=(size <= 0) ) > In this particular case, Richard, I don't think so. The Block class is an application-level wrapper for a graphical object. I don't want to worry about zero-size objects. ("Is this column really empty, or does it contain one or more zero-size blocks?") If you're interested, take a look at "BlockHead" at www.jjposner.net. BTW, from the (admittedly few) responses to my original post, it seems there's some sentiment that "conditional expressions" are a non-Pythonic misfeature. Interesting ... -John From chris at simplistix.co.uk Tue Aug 18 13:39:10 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 18 Aug 2009 18:39:10 +0100 Subject: xlutils 1.4.0 released! Message-ID: <4A8AE73E.9030504@simplistix.co.uk> Hi All, I'm pleased to announce a new release of xlutils. This is a small collection of utilities that make use of both xlrd and xlwt to process Microsoft Excel files. The changes for this release are as follows: - Add sheet density information and onesheet option to xlutils.margins. - Reduced the memory footprint of xlutils.filter.ColumnTrimmer at the expense of speed. - Fixed incorrect warnings about boolean cells in xlutils.filter.ErrorFilter. xlwt has always supported boolean cells. - xlutils.filter.BaseReader now opens workbooks with on_demand = True - Added support for xlrd Books opened with on_demand as True passed to open_workbook. - Fixed bug when copying error cells. - Requires the latest versions of xlrd (0.7.1) and xlwt (0.7.2). To find out more, please read here: http://www.simplistix.co.uk/software/python/xlutils In case you're not aware, xlrd and xlwt are two excellent pure-python libraries for reading and writing Excel files. They run on any platform and, likely, any implementation of Python without the need for horrific things like binding to Excel via COM and so needing a Windows machine. If you use any of xlrd, xlwt or xlutils, the following google group will be of use: http://groups.google.com.au/group/python-excel Hope some of this is of interest, I'd love to hear from anyone who ends up using it! cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From rcdailey at gmail.com Tue Aug 18 14:19:28 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 11:19:28 -0700 (PDT) Subject: Parallelization in Python 2.6 Message-ID: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> I'm looking for a way to parallelize my python script without using typical threading primitives. For example, C++ has pthreads and TBB to break things into "tasks". I would like to see something like this for python. So, if I have a very linear script: doStuff1() doStuff2() I can parallelize it easily like so: create_task( doStuff1 ) create_task( doStuff2 ) Both of these functions would be called from new threads, and once execution ends the threads would die. I realize this is a simple example and I could create my own classes for this functionality, but I do not want to bother if a solution already exists. Thanks in advance. From stefan_ml at behnel.de Tue Aug 18 14:41:18 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 Aug 2009 20:41:18 +0200 Subject: Parallelization in Python 2.6 In-Reply-To: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> Message-ID: <4a8af5ce$0$30224$9b4e6d93@newsspool1.arcor-online.net> Robert Dailey wrote: > I'm looking for a way to parallelize my python script without using > typical threading primitives. For example, C++ has pthreads and TBB to > break things into "tasks". I would like to see something like this for > python. So, if I have a very linear script: > > doStuff1() > doStuff2() > > > I can parallelize it easily like so: > > create_task( doStuff1 ) > create_task( doStuff2 ) > > Both of these functions would be called from new threads, and once > execution ends the threads would die. I realize this is a simple > example and I could create my own classes for this functionality, but > I do not want to bother if a solution already exists. I think the canonical answer is to use the threading module or (preferably) the multiprocessing module, which is new in Py2.6. http://docs.python.org/library/threading.html http://docs.python.org/library/multiprocessing.html Both share a (mostly) common interface and are simple enough to use. They are pretty close to the above interface already. Stefan From ethan at stoneleaf.us Tue Aug 18 14:43:36 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 Aug 2009 11:43:36 -0700 Subject: Code formatting question: conditional expression In-Reply-To: <4A8AE41A.3060107@optimum.net> References: <4A8AE41A.3060107@optimum.net> Message-ID: <4A8AF658.4090400@stoneleaf.us> John Posner wrote: > > BTW, from the (admittedly few) responses to my original post, it seems > there's some sentiment that "conditional expressions" are a non-Pythonic > misfeature. Interesting ... > > -John > > > I didn't read it that way. One of the (to me) core points of Pythonic is readability. A conditional expression on one line is fine -- a conditional expression on more than one line is less readable than the standard if-else structure. ~Ethan~ From ethan at stoneleaf.us Tue Aug 18 15:08:42 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 Aug 2009 12:08:42 -0700 Subject: Identifying a class type - bad practice? In-Reply-To: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> References: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> Message-ID: <4A8AFC3A.4000608@stoneleaf.us> James Harris wrote: > I am writing some code to form a tree of nodes of different types. The > idea is to define one class per node type such as > > class node_type_1(node): > > class node_type_2(node): > > etc > > (Class "node" would hold any common properties). > > When walking the tree I need to know what type of node I'm dealing > with so polymorphism isn't generally useful. The action to be taken > depends on the node type. Two options appear to be useful: __class__ > and isinstance. I know the latter will match the instance against any > superclass and the former will match one class only. > > My question is: is this the Pythonic way to deal with such a tree? Is > there a better way? In C I would use structs where one field was a tag > indicating the kind of struct. > > James I would recommend going with isinstance. An instance of node_type_2 will not be an instance node_type_1, so no worries there, and it leaves open the option of subclassing further if you need to later on. ~Ethan~ From andre.roberge at gmail.com Tue Aug 18 15:24:18 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Tue, 18 Aug 2009 12:24:18 -0700 (PDT) Subject: Identifying a class type - bad practice? References: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> Message-ID: <0aab1195-8ae5-4550-993f-bec9aca7e27e@p23g2000vbl.googlegroups.com> On Aug 18, 2:09?pm, James Harris wrote: > I am writing some code to form a tree of nodes of different types. The > idea is to define one class per node type such as > > class node_type_1(node): > ? > class node_type_2(node): > ? > etc > > (Class "node" would hold any common properties). > > When walking the tree I need to know what type of node I'm dealing > with so polymorphism isn't generally useful. The action to be taken > depends on the node type. Two options appear to be useful: __class__ > and isinstance. I know the latter will match the instance against any > superclass and the former will match one class only. > > My question is: is this the Pythonic way to deal with such a tree? Is > there a better way? In C I would use structs where one field was a tag > indicating the kind of struct. > > James I would probably go with hasattr(instance, 'what_I_want') Andr? From sajmikins at gmail.com Tue Aug 18 15:42:10 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 15:42:10 -0400 Subject: comparing XML files to eachother In-Reply-To: <9583ed900908171251k50fafaefrd626439bf1bd9a3c@mail.gmail.com> References: <9583ed900908171251k50fafaefrd626439bf1bd9a3c@mail.gmail.com> Message-ID: <50f98a4c0908181242w734a3b64k68b8928bdef0c88d@mail.gmail.com> On Mon, Aug 17, 2009 at 3:51 PM, David Brochu wrote: > I need to compare one xml document to another to see if the content matches. > Unfortunately, the formatting (spacing) and order of elements may change > between files from run to run. I have looked into xml dom minidom but can't > seem to find how to accomplish this. Does anyone know how I can do a compare > between two XML documents using the STL? It seems to me that you're going to have to "normalize" the documents to be able to compare them. (I.e. strip or ignore spacing differences, sort the elements to be in the same order, etc..) From pavpanchekha at gmail.com Tue Aug 18 15:44:55 2009 From: pavpanchekha at gmail.com (Pavel Panchekha) Date: Tue, 18 Aug 2009 12:44:55 -0700 (PDT) Subject: Inheriting dictionary Message-ID: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> I want a dictionary that will transparently "inherit" from a parent dictionary. So, for example: """ a = InheritDict({1: "one", 2: "two", 4: "four"}) b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) a[1] # "one" a[4] # "four" b[1] # "one" b[3] # "three" b[4] # "foobar" """ I've written something like this in Python already, but I'm wondering if something like this already exists, preferably written in C, for speed. From zuo at chopin.edu.pl Tue Aug 18 15:48:58 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 21:48:58 +0200 Subject: Code formatting question: conditional expression In-Reply-To: <0014440c$0$2963$c3e8da3@news.astraweb.com> References: <0014440c$0$2963$c3e8da3@news.astraweb.com> Message-ID: 18-08-2009 Steven D'Aprano wrote: > On Tue, 18 Aug 2009 10:04:36 -0400, John Posner wrote: > [snip] >> How about this: >> >> excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) >> if total > P.BASE else >> None) > > If you insist on using the conditional expression, my preference would > be: > > excessblk = ( > Block(total - P.BASE, srccol, carry_button_suppress=True) > if total > P.BASE else None > ) Generally I'd prefer: excessblk = (Block(........) if total > P.BASE else None) But it this case first line would be too long, then I'd try using: excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None) or excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None) I'd use conditional expression only (rather) in situation when the first expression-part was 'common' and the other (after else) was 'rare'. Cheers, *j -- Jan Kaliszewski (zuo) From code at pizzashack.org Tue Aug 18 16:10:15 2009 From: code at pizzashack.org (Derek Martin) Date: Tue, 18 Aug 2009 15:10:15 -0500 Subject: basic thread question Message-ID: <20090818201015.GP20434@dragontoe.org> I have some simple threaded code... If I run this with an arg of 1 (start one thread), it pegs one cpu, as I would expect. If I run it with an arg of 2 (start 2 threads), it uses both CPUs, but utilization of both is less than 50%. Can anyone explain why? I do not pretend it's impeccable code, and I'm not looking for a critiqe of the code per se, excepting the case where what I've written is actually *wrong*. I hacked this together in a couple of minutes, with the intent of pegging my CPUs. Performance with two threads is actually *worse* than with one, which is highly unintuitive. I can accomplish my goal very easily with bash, but I still want to understand what's going on here... The OS is Linux 2.6.24, on a Ubuntu base. Here's the code: Thanks -=-=-=-=- #!/usr/bin/python import thread, sys, time def busy(thread): x=0 while True: x+=1 if __name__ == '__main__': try: cpus = int(sys.argv[1]) except ValueError: cpus = 1 print "cpus = %d, argv[1] = %s\n" % (cpus, sys.argv[1]) i=0 thread_list = [] while i < cpus: x = thread.start_new_thread(busy, (i,)) thread_list.append(x) i+=1 while True: pass -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From zuo at chopin.edu.pl Tue Aug 18 16:23:09 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 22:23:09 +0200 Subject: Inheriting dictionary In-Reply-To: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: 18-08-2009 o 21:44:55 Pavel Panchekha wrote: > I want a dictionary that will transparently "inherit" from a parent > dictionary. So, for example: > > """ > a = InheritDict({1: "one", 2: "two", 4: "four"}) > b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) > > a[1] # "one" > a[4] # "four" > b[1] # "one" > b[3] # "three" > b[4] # "foobar" > """ > > I've written something like this in Python already, but I'm wondering > if something like this already exists, preferably written in C, for > speed. AFAIN -- no. But you can easily implement it in Python with rather small loss of speed... class InheritDict(dict): class NoParent(object): def __getitem__(self, key): raise KeyError('There is no %r key in the hierarchy' % key) def __nonzero__(self): return False noparent = NoParent() def __init__(self, *args, **kwargs): parent = kwargs.pop('inherit_from', self.noparent) dict.__init__(self, *args, **kwargs) self.parent = parent def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return self.parent[key] Did you do it in similar way? (just curiosity) :-) Regards, *j -- Jan Kaliszewski (zuo) From nat.williams at gmail.com Tue Aug 18 16:27:41 2009 From: nat.williams at gmail.com (Nat Williams) Date: Tue, 18 Aug 2009 15:27:41 -0500 Subject: Inheriting dictionary In-Reply-To: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: On Tue, Aug 18, 2009 at 2:44 PM, Pavel Panchekha wrote: > I want a dictionary that will transparently "inherit" from a parent > dictionary. So, for example: > > """ > a = InheritDict({1: "one", 2: "two", 4: "four"}) > b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) > > a[1] # "one" > a[4] # "four" > b[1] # "one" > b[3] # "three" > b[4] # "foobar" > """ > > I've written something like this in Python already, but I'm wondering > if something like this already exists, preferably written in C, for > speed. Why complicate this with a custom object? Just use regular dicts and make b a copy of a. a = {1: 'one', 2: 'two', 4: 'four'} b = dict(a) b[3] = 'three' b[4] = 'foobar' -------------- next part -------------- An HTML attachment was scrubbed... URL: From rcdailey at gmail.com Tue Aug 18 16:27:49 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:27:49 -0700 (PDT) Subject: How to create functors? Message-ID: Hello, I want to simply wrap a function up into an object so it can be called with no parameters. The parameters that it would otherwise have taken are already filled in. Like so: print1 = lambda: print( "Foobar" ) print1() However, the above code fails with: File "C:\IT\work\distro_test\distribute_radix.py", line 286 print1 = lambda: print( "Foobar" ) ^ SyntaxError: invalid syntax How can I get this working? From duncan.booth at invalid.invalid Tue Aug 18 16:31:51 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Aug 2009 20:31:51 GMT Subject: How to create functors? References: Message-ID: Robert Dailey wrote: > Hello, > > I want to simply wrap a function up into an object so it can be called > with no parameters. The parameters that it would otherwise have taken > are already filled in. Like so: > > > print1 = lambda: print( "Foobar" ) > print1() > > However, the above code fails with: > > File "C:\IT\work\distro_test\distribute_radix.py", line 286 > print1 = lambda: print( "Foobar" ) > ^ > SyntaxError: invalid syntax > > How can I get this working? def print1(): print "Foobar" It looks like in your version of Python "print" isn't a function. It always helps if you say the exact version you are using in your question as the exact answer you need may vary. From rcdailey at gmail.com Tue Aug 18 16:32:55 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:32:55 -0700 (PDT) Subject: How to create functors? References: Message-ID: On Aug 18, 3:31?pm, Duncan Booth wrote: > Robert Dailey wrote: > > Hello, > > > I want to simply wrap a function up into an object so it can be called > > with no parameters. The parameters that it would otherwise have taken > > are already filled in. Like so: > > > ? ? ? print1 = lambda: print( "Foobar" ) > > ? ? ? print1() > > > However, the above code fails with: > > > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 > > ? ? print1 = lambda: print( "Foobar" ) > > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > > SyntaxError: invalid syntax > > > How can I get this working? > > def print1(): > ? ? print "Foobar" > > It looks like in your version of Python "print" isn't a function. It always > helps if you say the exact version you are using in your question as the > exact answer you need may vary. I'm using Python 2.6. And using the legacy syntax in the lambda does not work either. I want to avoid using a def if possible. Thanks. From pavpanchekha at gmail.com Tue Aug 18 16:32:58 2009 From: pavpanchekha at gmail.com (Pavel Panchekha) Date: Tue, 18 Aug 2009 13:32:58 -0700 (PDT) Subject: Inheriting dictionary References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: <54699ee8-9c14-4aea-be86-06ef49be86c5@d21g2000vbm.googlegroups.com> On Aug 18, 4:23?pm, "Jan Kaliszewski" wrote: > 18-08-2009 o 21:44:55 Pavel Panchekha wrote: > > > > > I want a dictionary that will transparently "inherit" from a parent > > dictionary. So, for example: > > > """ > > a = InheritDict({1: "one", 2: "two", 4: "four"}) > > b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) > > > a[1] # "one" > > a[4] # "four" > > b[1] # "one" > > b[3] # "three" > > b[4] # "foobar" > > """ > > > I've written something like this in Python already, but I'm wondering > > if something like this already exists, preferably written in C, for > > speed. > > AFAIN -- no. But you can easily implement it in Python with rather > small loss of speed... > > ? class InheritDict(dict): > > ? ? ? class NoParent(object): > ? ? ? ? ? def __getitem__(self, key): > ? ? ? ? ? ? ? raise KeyError('There is no %r key in the hierarchy' % key) > ? ? ? ? ? def __nonzero__(self): > ? ? ? ? ? ? ? return False > > ? ? ? noparent = NoParent() > > ? ? ? def __init__(self, *args, **kwargs): > ? ? ? ? ? parent = kwargs.pop('inherit_from', self.noparent) > ? ? ? ? ? dict.__init__(self, *args, **kwargs) > ? ? ? ? ? self.parent = parent > > ? ? ? def __getitem__(self, key): > ? ? ? ? ? try: > ? ? ? ? ? ? ? return dict.__getitem__(self, key) > ? ? ? ? ? except KeyError: > ? ? ? ? ? ? ? return self.parent[key] > > Did you do it in similar way? (just curiosity) :-) > > Regards, > *j > > -- > Jan Kaliszewski (zuo) I implemented it in a similar way (instead of a try block, an if block, which works a tiny bit faster; also have a multiple-parents case, but its rare, and I could do that in Python without much loss of speed). Pity that there's no C version; this InheritDict is kind of the core of my application (in a very basic test, I have 329901 calls to __getitem__). Oh well; I'll see if I can optimize the __getattr__ function with minor tweaking. Thanks for your help. From rcdailey at gmail.com Tue Aug 18 16:36:07 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:36:07 -0700 (PDT) Subject: How to create functors? References: Message-ID: On Aug 18, 3:31?pm, Duncan Booth wrote: > Robert Dailey wrote: > > Hello, > > > I want to simply wrap a function up into an object so it can be called > > with no parameters. The parameters that it would otherwise have taken > > are already filled in. Like so: > > > ? ? ? print1 = lambda: print( "Foobar" ) > > ? ? ? print1() > > > However, the above code fails with: > > > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 > > ? ? print1 = lambda: print( "Foobar" ) > > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > > SyntaxError: invalid syntax > > > How can I get this working? > > def print1(): > ? ? print "Foobar" > > It looks like in your version of Python "print" isn't a function. It always > helps if you say the exact version you are using in your question as the > exact answer you need may vary. Seems like it works fine on everything else except for print(). For example: print1 = lambda: MyFunction( "FooBar" ) The syntax above is accepted by the interpreter. From sajmikins at gmail.com Tue Aug 18 16:37:21 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 16:37:21 -0400 Subject: define class over 2 files In-Reply-To: References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> Message-ID: <50f98a4c0908181337q6295f977ubcf8edab02fef5cb@mail.gmail.com> On Tue, Aug 18, 2009 at 1:57 AM, Steven D'Aprano wrote: > On Mon, 17 Aug 2009 21:45:57 -0700, naveen wrote: > >> Is it possible to split up a class definition over multiple files? > > Not exactly, but you can do variations of this: > > > In file A.py, create: > > class Parent: > ? ?def method(self): > ? ? ? ?return "Method" > > > In file B.py, do this: > > import A > class Child(B.parent): class Child(A.Parent): From clp2 at rebertia.com Tue Aug 18 16:40:37 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 13:40:37 -0700 Subject: How to create functors? In-Reply-To: References: Message-ID: <50697b2c0908181340n48f510cdx79ee9ceeb416d4a5@mail.gmail.com> On Tue, Aug 18, 2009 at 1:32 PM, Robert Dailey wrote: > On Aug 18, 3:31?pm, Duncan Booth wrote: >> Robert Dailey wrote: >> > Hello, >> >> > I want to simply wrap a function up into an object so it can be called >> > with no parameters. The parameters that it would otherwise have taken >> > are already filled in. Like so: >> >> > ? ? ? print1 = lambda: print( "Foobar" ) >> > ? ? ? print1() >> >> > However, the above code fails with: >> >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 >> > ? ? print1 = lambda: print( "Foobar" ) >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ >> > SyntaxError: invalid syntax >> >> > How can I get this working? >> >> def print1(): >> ? ? print "Foobar" >> >> It looks like in your version of Python "print" isn't a function. It always >> helps if you say the exact version you are using in your question as the >> exact answer you need may vary. > > I'm using Python 2.6. And using the legacy syntax in the lambda does > not work either. I want to avoid using a def if possible. Thanks. chris at morpheus ~ $ python Python 2.6.2 (r262:71600, May 14 2009, 16:34:51) [GCC 4.0.1 (Apple Inc. build 5484)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print1 = lambda: print( "Foobar" ) File "", line 1 print1 = lambda: print( "Foobar" ) ^ SyntaxError: invalid syntax >>> from __future__ import print_function >>> print1 = lambda: print( "Foobar" ) >>> print1() Foobar Cheers, Chris -- http://blog.rebertia.com From jgardner at jonathangardner.net Tue Aug 18 16:41:16 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Tue, 18 Aug 2009 13:41:16 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> Message-ID: <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> On Aug 18, 11:19?am, Robert Dailey wrote: > I'm looking for a way to parallelize my python script without using > typical threading primitives. For example, C++ has pthreads and TBB to > break things into "tasks". I would like to see something like this for > python. So, if I have a very linear script: > > doStuff1() > doStuff2() > > I can parallelize it easily like so: > > create_task( doStuff1 ) > create_task( doStuff2 ) > > Both of these functions would be called from new threads, and once > execution ends the threads would die. I realize this is a simple > example and I could create my own classes for this functionality, but > I do not want to bother if a solution already exists. > If you haven't heard of the Python GIL, you'll want to find out sooner rather than later. Short summary: Python doesn't do threading very well. There are quite a few parallelization solutions out there for Python, however. (I don't know what they are off the top of my head, however.) The way they work is they have worker processes that can be spread across machines. When you want to parallelize a task, you send off a function to those worker threads. There are some serious caveats and problems, not the least of which is sharing code between the worker threads and the director, so this isn't a great solution. If you're looking for highly parallelized code, Python may not be the right answer. Try something like Erlang or Haskell. From zuo at chopin.edu.pl Tue Aug 18 16:42:46 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 22:42:46 +0200 Subject: define class over 2 files In-Reply-To: <2d56febf0908172158l760256rc703d7d87f04e509@mail.gmail.com> References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> <2d56febf0908172158l760256rc703d7d87f04e509@mail.gmail.com> Message-ID: 18-08-2009 o 06:58:58 Xavier Ho wrote: > On Tue, Aug 18, 2009 at 2:45 PM, naveen wrote: > >> Is it possible to split up a class definition over multiple files? >> - > Answer in short, I don't think so. Why not? --------- File a.py: class MyClass: def foo(self, x): return x * 6 --------- File b.py: import a def bar(self): print 'bar' def baz(self, a): print self.foooo(a) # adding methods by hand: a.MyClass.bar = bar a.MyClass.baz = baz --------- File c.py import a def foooo(self, a): return a * self.foo(4) def baaar(self): print self.baz('tralala') def bazzz(self): print 'bzzzzzzzzzz' # adding methods more automaticly: for name, obj in globals().values(): setattr(a.MyClass, name, obj) > Now why would you want to do that? It's a good question. As others said it's very probable that some other solution would be better (e.g. inheritance). Cheers, *j -- Jan Kaliszewski (zuo) From rcdailey at gmail.com Tue Aug 18 16:42:59 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:42:59 -0700 (PDT) Subject: How to create functors? References: Message-ID: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> On Aug 18, 3:40?pm, Chris Rebert wrote: > On Tue, Aug 18, 2009 at 1:32 PM, Robert Dailey wrote: > > On Aug 18, 3:31?pm, Duncan Booth wrote: > >> Robert Dailey wrote: > >> > Hello, > > >> > I want to simply wrap a function up into an object so it can be called > >> > with no parameters. The parameters that it would otherwise have taken > >> > are already filled in. Like so: > > >> > ? ? ? print1 = lambda: print( "Foobar" ) > >> > ? ? ? print1() > > >> > However, the above code fails with: > > >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 > >> > ? ? print1 = lambda: print( "Foobar" ) > >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > >> > SyntaxError: invalid syntax > > >> > How can I get this working? > > >> def print1(): > >> ? ? print "Foobar" > > >> It looks like in your version of Python "print" isn't a function. It always > >> helps if you say the exact version you are using in your question as the > >> exact answer you need may vary. > > > I'm using Python 2.6. And using the legacy syntax in the lambda does > > not work either. I want to avoid using a def if possible. Thanks. > > chris at morpheus ~ $ python > Python 2.6.2 (r262:71600, May 14 2009, 16:34:51) > [GCC 4.0.1 (Apple Inc. build 5484)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> print1 = lambda: print( "Foobar" ) > > ? File "", line 1 > ? ? print1 = lambda: print( "Foobar" ) > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > SyntaxError: invalid syntax>>> from __future__ import print_function > >>> print1 = lambda: print( "Foobar" ) > >>> print1() > > Foobar > > Cheers, > Chris > --http://blog.rebertia.com I see what you're saying now. However, why am I able to use print as a function in general-purpose code in my Python 2.6 script, like so: def SomeFunction(): print( "Hello World" ) But, I am not able to do this: SomeFunction = lambda: print( "Hello World" ) ?????? Doesn't make sense. From rcdailey at gmail.com Tue Aug 18 16:45:38 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:45:38 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> Message-ID: <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> On Aug 18, 3:41?pm, Jonathan Gardner wrote: > On Aug 18, 11:19?am, Robert Dailey wrote: > > > > > > > I'm looking for a way to parallelize my python script without using > > typical threading primitives. For example, C++ has pthreads and TBB to > > break things into "tasks". I would like to see something like this for > > python. So, if I have a very linear script: > > > doStuff1() > > doStuff2() > > > I can parallelize it easily like so: > > > create_task( doStuff1 ) > > create_task( doStuff2 ) > > > Both of these functions would be called from new threads, and once > > execution ends the threads would die. I realize this is a simple > > example and I could create my own classes for this functionality, but > > I do not want to bother if a solution already exists. > > If you haven't heard of the Python GIL, you'll want to find out sooner > rather than later. Short summary: Python doesn't do threading very > well. > > There are quite a few parallelization solutions out there for Python, > however. (I don't know what they are off the top of my head, however.) > The way they work is they have worker processes that can be spread > across machines. When you want to parallelize a task, you send off a > function to those worker threads. > > There are some serious caveats and problems, not the least of which is > sharing code between the worker threads and the director, so this > isn't a great solution. > > If you're looking for highly parallelized code, Python may not be the > right answer. Try something like Erlang or Haskell. Really, all I'm trying to do is the most trivial type of parallelization. Take two functions, execute them in parallel. This type of parallelization is called "embarrassingly parallel", and is the simplest form. There are no dependencies between the two functions. They do requires read-only access to shared data, though. And if they are being spawned as sub-processes this could cause problems, unless the multiprocess module creates pipelines or other means to handle this situation. From rami.chowdhury at gmail.com Tue Aug 18 16:45:50 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 18 Aug 2009 13:45:50 -0700 Subject: How to create functors? In-Reply-To: References: Message-ID: Lambda expressions are, I believe, syntactically limited to a single expression -- no statements, like 'print' is in Python 2.x. If you are strongly against just defining a function, you might have to use a trick to get around it -- this page (http://p-nand-q.com/python/stupid_lambda_tricks.html) has some suggestions. On Tue, 18 Aug 2009 13:32:55 -0700, Robert Dailey wrote: > On Aug 18, 3:31?pm, Duncan Booth wrote: >> Robert Dailey wrote: >> > Hello, >> >> > I want to simply wrap a function up into an object so it can be called >> > with no parameters. The parameters that it would otherwise have taken >> > are already filled in. Like so: >> >> > ? ? ? print1 = lambda: print( "Foobar" ) >> > ? ? ? print1() >> >> > However, the above code fails with: >> >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 >> > ? ? print1 = lambda: print( "Foobar" ) >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ >> > SyntaxError: invalid syntax >> >> > How can I get this working? >> >> def print1(): >> ? ? print "Foobar" >> >> It looks like in your version of Python "print" isn't a function. It >> always >> helps if you say the exact version you are using in your question as the >> exact answer you need may vary. > > I'm using Python 2.6. And using the legacy syntax in the lambda does > not work either. I want to avoid using a def if possible. Thanks. -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From nad at acm.org Tue Aug 18 16:46:57 2009 From: nad at acm.org (Ned Deily) Date: Tue, 18 Aug 2009 13:46:57 -0700 Subject: How to create functors? References: Message-ID: In article , Robert Dailey wrote: > On Aug 18, 3:31?pm, Duncan Booth wrote: > > Robert Dailey wrote: > > > Hello, > > > > > I want to simply wrap a function up into an object so it can be called > > > with no parameters. The parameters that it would otherwise have taken > > > are already filled in. Like so: > > > > > ? ? ? print1 = lambda: print( "Foobar" ) > > > ? ? ? print1() > > > > > However, the above code fails with: > > > > > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 > > > ? ? print1 = lambda: print( "Foobar" ) > > > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > > > SyntaxError: invalid syntax > > > > > How can I get this working? > > > > def print1(): > > ? ? print "Foobar" > > > > It looks like in your version of Python "print" isn't a function. It always > > helps if you say the exact version you are using in your question as the > > exact answer you need may vary. > > I'm using Python 2.6. And using the legacy syntax in the lambda does > not work either. I want to avoid using a def if possible. Thanks. The problem is that in Python 2 print is a statement, not a function. That should work fine in Python 3 where print *is* a function. In 2.x, you can wrap print in a function or use something like: >>> import sys >>> print1 = lambda: sys.stdout.write("Foobar\n") >>> print1() Foobar or the pprint library module or various other solutions. -- Ned Deily, nad at acm.org From malaclypse2 at gmail.com Tue Aug 18 16:49:34 2009 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 18 Aug 2009 16:49:34 -0400 Subject: How to create functors? In-Reply-To: References: Message-ID: <16651e80908181349l20efec3do7148c7ef1f2657cb@mail.gmail.com> On Tue, Aug 18, 2009 at 4:27 PM, Robert Dailey wrote: > Hello, > > I want to simply wrap a function up into an object so it can be called > with no parameters. The parameters that it would otherwise have taken > are already filled in. Like so: > > > ? ? ?print1 = lambda: print( "Foobar" ) > ? ? ?print1() > > However, the above code fails with: > > ?File "C:\IT\work\distro_test\distribute_radix.py", line 286 > ? ?print1 = lambda: print( "Foobar" ) > ? ? ? ? ? ? ? ? ? ? ? ? ^ > SyntaxError: invalid syntax > > How can I get this working? You can't, at least not with that example. Lambdas are restricted to a single expression[1]. Print is not an expression, it's a statement[2]. I'm guessing that your use case is not really in wrapping a print statement in an anonymous function. Given the first part of your message, you might find something of use in the functools module, particularly functools.partial [3]. 1: http://docs.python.org/tutorial/controlflow.html#lambda-forms 2: http://docs.python.org/reference/simple_stmts.html 3: http://docs.python.org/library/functools.html#functools.partial -- Jerry From clp2 at rebertia.com Tue Aug 18 16:50:27 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 13:50:27 -0700 Subject: Identifying a class type - bad practice? In-Reply-To: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> References: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> Message-ID: <50697b2c0908181350x5bbfd8e9qe1b7e1d3c13bf49e@mail.gmail.com> On Tue, Aug 18, 2009 at 10:09 AM, James Harris wrote: > I am writing some code to form a tree of nodes of different types. The > idea is to define one class per node type such as > > class node_type_1(node): > ? > class node_type_2(node): > ? > etc > > (Class "node" would hold any common properties). > > When walking the tree I need to know what type of node I'm dealing > with so polymorphism isn't generally useful. The action to be taken > depends on the node type. I'm sure it relates to the exact type of tree you're walking and the calculation you're doing on it, but what is the reason why your code, which in the abstract sounds like it will vaguely resemble this: def walk_tree(tree): if isinstance(tree, node_type_1): #code walk_tree(subtree) elif isinstance(tree, node_type_2): #code walk_tree(subtree) #etc... can't be written instead as: class node_type_1: def walk_tree(self): #code self.subtree.walk() class node_type_2: def walk_tree(self): #code self.subtree.walk() #etc ? Cheers, Chris -- http://blog.rebertia.com From rcdailey at gmail.com Tue Aug 18 16:51:19 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:51:19 -0700 (PDT) Subject: How to create functors? References: Message-ID: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> On Aug 18, 3:45?pm, "Rami Chowdhury" wrote: > Lambda expressions are, I believe, syntactically limited to a single ? > expression -- no statements, like 'print' is in Python 2.x. > > If you are strongly against just defining a function, you might have to ? > use a trick to get around it -- this page ? > (http://p-nand-q.com/python/stupid_lambda_tricks.html) has some ? > suggestions. > > On Tue, 18 Aug 2009 13:32:55 -0700, Robert Dailey ? > wrote: > > > > > > > On Aug 18, 3:31?pm, Duncan Booth wrote: > >> Robert Dailey wrote: > >> > Hello, > > >> > I want to simply wrap a function up into an object so it can be called > >> > with no parameters. The parameters that it would otherwise have taken > >> > are already filled in. Like so: > > >> > ? ? ? print1 = lambda: print( "Foobar" ) > >> > ? ? ? print1() > > >> > However, the above code fails with: > > >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 > >> > ? ? print1 = lambda: print( "Foobar" ) > >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > >> > SyntaxError: invalid syntax > > >> > How can I get this working? > > >> def print1(): > >> ? ? print "Foobar" > > >> It looks like in your version of Python "print" isn't a function. It ? > >> always > >> helps if you say the exact version you are using in your question as the > >> exact answer you need may vary. > > > I'm using Python 2.6. And using the legacy syntax in the lambda does > > not work either. I want to avoid using a def if possible. Thanks. > > -- > Rami Chowdhury > "Never attribute to malice that which can be attributed to stupidity" -- ? > Hanlon's Razor > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) The example I gave earlier is a bit contrived, the real example fundamentally requires a lambda since I am actually passing in local variables into the functions the lambda is wrapping. Example: def MyFunction(): localVariable = 20 CreateTask( lambda: SomeOtherFunction( localVariable ) ) # CreateTask () executes the functor internally This is more or less like the real scenario I'm working with. There are other (more personal) reasons why I prefer to avoid 'def' in this case. I want to keep the functor as central to the code that needs it as possible to improve code readability. Thanks for the help everyone. I guess in Python 3.0 the print() function will not require the import from __future__ to work in this particular case? From zuo at chopin.edu.pl Tue Aug 18 16:51:26 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 22:51:26 +0200 Subject: How to create functors? In-Reply-To: References: Message-ID: 18-08-2009 o 22:32:55 Robert Dailey wrote: > On Aug 18, 3:31?pm, Duncan Booth wrote: >> Robert Dailey wrote: >> > Hello, >> >> > I want to simply wrap a function up into an object so it can be called >> > with no parameters. The parameters that it would otherwise have taken >> > are already filled in. Like so: >> >> > ? ? ? print1 = lambda: print( "Foobar" ) >> > ? ? ? print1() >> >> > However, the above code fails with: >> >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 >> > ? ? print1 = lambda: print( "Foobar" ) >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ >> > SyntaxError: invalid syntax >> >> > How can I get this working? >> >> def print1(): >> ? ? print "Foobar" >> >> It looks like in your version of Python "print" isn't a function. It >> always >> helps if you say the exact version you are using in your question as the >> exact answer you need may vary. > > I'm using Python 2.6. And using the legacy syntax in the lambda does > not work either. In Python 1.x/2.x 'print' is a keyword-based statement, not a function -- then you cannot use it in lambda (which in Python is limited to single expressions, and statements are not allowed in it). You can try using sys.stdout.write() instead. > I want to avoid using a def if possible. But what for? Usualy def is more readable than lambda and it's not worth to lose readibility just to save a few keystrokes. Cheers, *j -- Jan Kaliszewski (zuo) From rcdailey at gmail.com Tue Aug 18 16:52:21 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:52:21 -0700 (PDT) Subject: How to create functors? References: Message-ID: <315f52d5-1e0c-48ab-85fb-e5857aedd3ce@s15g2000yqs.googlegroups.com> On Aug 18, 3:51?pm, "Jan Kaliszewski" wrote: > 18-08-2009 o 22:32:55 Robert Dailey wrote: > > > > > > > On Aug 18, 3:31?pm, Duncan Booth wrote: > >> Robert Dailey wrote: > >> > Hello, > > >> > I want to simply wrap a function up into an object so it can be called > >> > with no parameters. The parameters that it would otherwise have taken > >> > are already filled in. Like so: > > >> > ? ? ? print1 = lambda: print( "Foobar" ) > >> > ? ? ? print1() > > >> > However, the above code fails with: > > >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 > >> > ? ? print1 = lambda: print( "Foobar" ) > >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > >> > SyntaxError: invalid syntax > > >> > How can I get this working? > > >> def print1(): > >> ? ? print "Foobar" > > >> It looks like in your version of Python "print" isn't a function. It ? > >> always > >> helps if you say the exact version you are using in your question as the > >> exact answer you need may vary. > > > I'm using Python 2.6. And using the legacy syntax in the lambda does > > not work either. > > In Python 1.x/2.x 'print' is a keyword-based statement, not a function > -- then you cannot use it in lambda (which in Python is limited to > single expressions, and statements are not allowed in it). > > You can try using sys.stdout.write() instead. > > > I want to avoid using a def if possible. > > But what for? Usualy def is more readable than lambda and it's not worth > to lose readibility just to save a few keystrokes. > > Cheers, > *j > > -- > Jan Kaliszewski (zuo) I posted a bit earlier than you did. See my previous post. Thanks for the help. From invalid at invalid Tue Aug 18 16:55:19 2009 From: invalid at invalid (Grant Edwards) Date: Tue, 18 Aug 2009 15:55:19 -0500 Subject: How to create functors? References: Message-ID: On 2009-08-18, Robert Dailey wrote: > Hello, > > I want to simply wrap a function up into an object so it can be called > with no parameters. The parameters that it would otherwise have taken > are already filled in. Like so: > > > print1 = lambda: print( "Foobar" ) > print1() > > However, the above code fails with: > > File "C:\IT\work\distro_test\distribute_radix.py", line 286 > print1 = lambda: print( "Foobar" ) > ^ > SyntaxError: invalid syntax > > How can I get this working? Doesn't this do what you want? def print1(): return print(" Foobar" ) -- Grant Edwards grante Yow! I want my nose in at lights! visi.com From rami.chowdhury at gmail.com Tue Aug 18 16:57:54 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 18 Aug 2009 13:57:54 -0700 Subject: How to create functors? In-Reply-To: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> References: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> Message-ID: > why am I able to use print as a > function in general-purpose code in my Python 2.6 script I believe it's because that is parsed as the print statement followed by a parenthesized expression. On Tue, 18 Aug 2009 13:42:59 -0700, Robert Dailey wrote: > On Aug 18, 3:40?pm, Chris Rebert wrote: >> On Tue, Aug 18, 2009 at 1:32 PM, Robert Dailey >> wrote: >> > On Aug 18, 3:31?pm, Duncan Booth wrote: >> >> Robert Dailey wrote: >> >> > Hello, >> >> >> > I want to simply wrap a function up into an object so it can be >> called >> >> > with no parameters. The parameters that it would otherwise have >> taken >> >> > are already filled in. Like so: >> >> >> > ? ? ? print1 = lambda: print( "Foobar" ) >> >> > ? ? ? print1() >> >> >> > However, the above code fails with: >> >> >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 >> >> > ? ? print1 = lambda: print( "Foobar" ) >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ >> >> > SyntaxError: invalid syntax >> >> >> > How can I get this working? >> >> >> def print1(): >> >> ? ? print "Foobar" >> >> >> It looks like in your version of Python "print" isn't a function. It >> always >> >> helps if you say the exact version you are using in your question as >> the >> >> exact answer you need may vary. >> >> > I'm using Python 2.6. And using the legacy syntax in the lambda does >> > not work either. I want to avoid using a def if possible. Thanks. >> >> chris at morpheus ~ $ python >> Python 2.6.2 (r262:71600, May 14 2009, 16:34:51) >> [GCC 4.0.1 (Apple Inc. build 5484)] on darwin >> Type "help", "copyright", "credits" or "license" for more >> information.>>> print1 = lambda: print( "Foobar" ) >> >> ? File "", line 1 >> ? ? print1 = lambda: print( "Foobar" ) >> ? ? ? ? ? ? ? ? ? ? ? ? ?^ >> SyntaxError: invalid syntax>>> from __future__ import print_function >> >>> print1 = lambda: print( "Foobar" ) >> >>> print1() >> >> Foobar >> >> Cheers, >> Chris >> --http://blog.rebertia.com > > I see what you're saying now. However, why am I able to use print as a > function in general-purpose code in my Python 2.6 script, like so: > > def SomeFunction(): > print( "Hello World" ) > > But, I am not able to do this: > > SomeFunction = lambda: print( "Hello World" ) > > ?????? > > Doesn't make sense. -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From nad at acm.org Tue Aug 18 17:00:04 2009 From: nad at acm.org (Ned Deily) Date: Tue, 18 Aug 2009 14:00:04 -0700 Subject: How to create functors? References: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> Message-ID: In article <5834f36f-b172-4e76-ad90-7056e7097cdd at o6g2000yqj.googlegroups.com>, Robert Dailey wrote: > I see what you're saying now. However, why am I able to use print as a > function in general-purpose code in my Python 2.6 script, like so: > > def SomeFunction(): > print( "Hello World" ) For the same reason you can do this: >>> x = ( "Hello World" ) >>> type(x) -- Ned Deily, nad at acm.org From zuo at chopin.edu.pl Tue Aug 18 17:01:26 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 23:01:26 +0200 Subject: How to create functors? In-Reply-To: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> References: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> Message-ID: Dnia 18-08-2009 o 22:42:59 Robert Dailey napisa?(a): > I see what you're saying now. However, why am I able to use print as a > function in general-purpose code in my Python 2.6 script, like so: > > def SomeFunction(): > print( "Hello World" ) > > But, I am not able to do this: > > SomeFunction = lambda: print( "Hello World" ) > > ?????? Because (unless you do 'from __future__ import print_function' in Py2.6) it's statement, not a functions. In Python you can put any expression in parentheses -- it's useful for wraping long lines but changes nothing semantically (unless you add a comma -- then you create a tuple, even without parentheses, but it'a another story...). *j -- Jan Kaliszewski (zuo) From gu.yakahughes at gmail.com Tue Aug 18 17:02:16 2009 From: gu.yakahughes at gmail.com (KillSwitch) Date: Tue, 18 Aug 2009 14:02:16 -0700 (PDT) Subject: Editing a wiki Message-ID: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> Hey guys, Is it possible to edit a wiki page with python, including logging in to edit the page, and inserting text into the edit box, etc. I was thinking maybe python would be the language to do this in, because I have to iterate through every line in a text file and gather info about what to enter in the wiki that way, then put that text in a wiki page. It's sort of a program-documenting program. If it's possible to do this, I would make a special way of entering comments in the source files, like maybe --[[##title code here]] and then --[[@@code example here]] with the two symbols at the beginning of the comment dictating what to enter where. Thanks for any input. From rcdailey at gmail.com Tue Aug 18 17:03:51 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 14:03:51 -0700 (PDT) Subject: How to create functors? References: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> Message-ID: On Aug 18, 4:01?pm, "Jan Kaliszewski" wrote: > Dnia 18-08-2009 o 22:42:59 Robert Dailey napisa?(a): > > > I see what you're saying now. However, why am I able to use print as a > > function in general-purpose code in my Python 2.6 script, like so: > > > def SomeFunction(): > > ? ?print( "Hello World" ) > > > But, I am not able to do this: > > > SomeFunction = lambda: print( "Hello World" ) > > > ?????? > > Because (unless you do 'from __future__ import print_function' in Py2.6) > it's statement, not a functions. In Python you can put any expression > in parentheses -- it's useful for wraping long lines but changes nothing > semantically (unless you add a comma -- then you create a tuple, even > without parentheses, but it'a another story...). > > *j > > -- > Jan Kaliszewski (zuo) Ah, I see now. I completely fooled myself. This whole time I thought Python 2.6 was updated to work with both forms of print by default as a convenience, but still maintain the backwards compatibility. I understand the situation now. Thanks to everyone for the help. From lkcl at lkcl.net Tue Aug 18 17:05:54 2009 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Tue, 18 Aug 2009 21:05:54 +0000 Subject: [ANN] Pyjamas 0.6 Web Widget Set and python-to-javascript Compiler released Message-ID: Pyjamas 0.6 is finally out: many thanks to everyone who has contributed. Special thanks to Kees Bos; Bernd, Bernd and Jurgen from LovelySystems.com; the people who showed an interest in Pyjamas at EuroPython 2009; and especially to everyone who has helped during the pre-releases, with testing and bugreports over the past few weeks. For a full list of contributors, see CREDITS. Downloads: --------- http://code.google.com/p/pyjamas/downloads http://pypi.python.org/pypi/Pyjamas http://sf.net/projects/pyjamas Pyjamas ------- Pyjamas is a port of Google Web Toolkit to Python, and thus enables the development of Rich Media AJAX applications in Python, with no need for special browser plugins. Pyjamas contains a stand-alone python-to-javascript compiler, and also a Widget Set API that looks very similar to Desktop Widget Set APIs (such as PyQT4 or PyGTK2). For more information, see: http://pyjs.org http://pyjs.org/FAQ.html http://pyjs.org/features.html Known bugs: http://code.google.com/p/pyjamas/issues #227, #228, #229, #230 and #232 Pyjamas-Desktop --------------- Pyjamas runs your application in a Web Browser (as javascript); Pyjamas-Desktop runs exactly the same python application on the Desktop (as python) http://pyjd.org Release 0.6 of Pyjamas also incorporates Pyjamas-Desktop directly into the Pyjamas Distribution. To use Pyjamas-Desktop there are three choices, with more planned [MacOSX PyObjC; KDE's PyKHTML]. 1) - XULRunner install hulahop and python-xpcom. hulahop is distributed with both Debian and Ubuntu; python-xpcom is part of XULRunner and is also distributed with both Debian and Ubuntu. Other users should investigate the installation instructions for python-xpcom and hulahop for the operating system of their choice on the appropriate web sites. GNU/Linux, FreeBSD and other POSIX systems are strongly advised to use XULRunner for Pyjamas-Desktop: it is the most stable of the PyJD ports. 2) - PyWebKitGtk you will need a patched version of pywebkitgtk: http://code.google.com/p/pywebkitgtk/issues/detail?id=13 you will need a patched version of webkit: http://github.com/lkcl/webkit/16401.master Detailed build instructions are available here: http://wiki.github.com/lkcl/webkit/helping-with-16401master 3) - MSHTML (experimental!) For Windows users, all that's required, other than installing python and Internet Explorer, is one further package: Win32 "comtypes". Win32 "comtypes" can be downloaded here: * http://sourceforge.net/projects/comtypes/ The MSHTML version primarily works. Reports using IE8's MSHTML engine would be appreciated. Known bugs: the use of Tab to cycle through Keyboard Focus elements is ineffective; onkeyup and onkeydown events are unresponsive, but oddly onkeypress event handling works. From rami.chowdhury at gmail.com Tue Aug 18 17:11:23 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 18 Aug 2009 14:11:23 -0700 Subject: How to create functors? In-Reply-To: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> References: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> Message-ID: > The example I gave earlier is a bit contrived, the real example > fundamentally requires a lambda since I am actually passing in local > variables into the functions the lambda is wrapping. Example: > > def MyFunction(): > localVariable = 20 > CreateTask( lambda: SomeOtherFunction( localVariable ) ) # CreateTask > () executes the functor internally > > This is more or less like the real scenario I'm working with. You could define a local function ('closure') inside the function: def MyFunction(): localVariable = 20 def UseLocalVariable(): SomeOtherFunction(localVariable) CreateTask(UseLocalVariable) I would suggest this is much better for readability. On Tue, 18 Aug 2009 13:51:19 -0700, Robert Dailey wrote: > On Aug 18, 3:45?pm, "Rami Chowdhury" wrote: >> Lambda expressions are, I believe, syntactically limited to a single ? >> expression -- no statements, like 'print' is in Python 2.x. >> >> If you are strongly against just defining a function, you might have to >> ? >> use a trick to get around it -- this page ? >> (http://p-nand-q.com/python/stupid_lambda_tricks.html) has some ? >> suggestions. >> >> On Tue, 18 Aug 2009 13:32:55 -0700, Robert Dailey ? >> wrote: >> >> >> >> >> >> > On Aug 18, 3:31?pm, Duncan Booth wrote: >> >> Robert Dailey wrote: >> >> > Hello, >> >> >> > I want to simply wrap a function up into an object so it can be >> called >> >> > with no parameters. The parameters that it would otherwise have >> taken >> >> > are already filled in. Like so: >> >> >> > ? ? ? print1 = lambda: print( "Foobar" ) >> >> > ? ? ? print1() >> >> >> > However, the above code fails with: >> >> >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 >> >> > ? ? print1 = lambda: print( "Foobar" ) >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ >> >> > SyntaxError: invalid syntax >> >> >> > How can I get this working? >> >> >> def print1(): >> >> ? ? print "Foobar" >> >> >> It looks like in your version of Python "print" isn't a function. It >> ? >> >> always >> >> helps if you say the exact version you are using in your question as >> the >> >> exact answer you need may vary. >> >> > I'm using Python 2.6. And using the legacy syntax in the lambda does >> > not work either. I want to avoid using a def if possible. Thanks. >> >> -- >> Rami Chowdhury >> "Never attribute to malice that which can be attributed to stupidity" >> -- ? >> Hanlon's Razor >> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > > The example I gave earlier is a bit contrived, the real example > fundamentally requires a lambda since I am actually passing in local > variables into the functions the lambda is wrapping. Example: > > def MyFunction(): > localVariable = 20 > CreateTask( lambda: SomeOtherFunction( localVariable ) ) # CreateTask > () executes the functor internally > > This is more or less like the real scenario I'm working with. There > are other (more personal) reasons why I prefer to avoid 'def' in this > case. I want to keep the functor as central to the code that needs it > as possible to improve code readability. > > Thanks for the help everyone. I guess in Python 3.0 the print() > function will not require the import from __future__ to work in this > particular case? -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From david.birdsong at gmail.com Tue Aug 18 17:11:25 2009 From: david.birdsong at gmail.com (birdsong) Date: Tue, 18 Aug 2009 14:11:25 -0700 (PDT) Subject: basic thread question References: Message-ID: <07fb2a97-d720-4dcd-9155-9237c1802091@i8g2000pro.googlegroups.com> On Aug 18, 1:10?pm, Derek Martin wrote: > I have some simple threaded code... ?If I run this > with an arg of 1 (start one thread), it pegs one cpu, as I would > expect. ?If I run it with an arg of 2 (start 2 threads), it uses both > CPUs, but utilization of both is less than 50%. ?Can anyone explain > why? ? > > I do not pretend it's impeccable code, and I'm not looking for a > critiqe of the code per se, excepting the case where what I've written > is actually *wrong*. I hacked this together in a couple of minutes, > with the intent of pegging my CPUs. ?Performance with two threads is > actually *worse* than with one, which is highly unintuitive. ?I can > accomplish my goal very easily with bash, but I still want to > understand what's going on here... > > The OS is Linux 2.6.24, on a Ubuntu base. ?Here's the code: > > Thanks > > -=-=-=-=- > > #!/usr/bin/python > > import thread, sys, time > > def busy(thread): > ? ? x=0 > ? ? while True: > ? ? ? ? x+=1 > > if __name__ == '__main__': > ? ? try: > ? ? ? ? cpus = int(sys.argv[1]) > ? ? except ValueError: > ? ? ? ? cpus = 1 > ? ? print "cpus = %d, argv[1] = %s\n" % (cpus, sys.argv[1]) > ? ? i=0 > ? ? thread_list = [] > ? ? while i < cpus: > ? ? ? ? x = thread.start_new_thread(busy, (i,)) > ? ? ? ? thread_list.append(x) > ? ? ? ? i+=1 > ? ? while True: > ? ? ? ? pass > > -- > Derek D. Martinhttp://www.pizzashack.org/ > GPG Key ID: 0x81CFE75D > > ?application_pgp-signature_part > < 1KViewDownload watch this and all your findings will be explained: http://blip.tv/file/2232410 this talk marked a pivotal moment in my understanding of python threads and signal handling in threaded programs. From zuo at chopin.edu.pl Tue Aug 18 17:11:34 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 23:11:34 +0200 Subject: Inheriting dictionary In-Reply-To: References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: 18-08-2009 o 22:27:41 Nat Williams wrote: > On Tue, Aug 18, 2009 at 2:44 PM, Pavel Panchekha > wrote: > >> I want a dictionary that will transparently "inherit" from a parent >> dictionary. So, for example: >> >> """ >> a = InheritDict({1: "one", 2: "two", 4: "four"}) >> b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) >> >> a[1] # "one" >> a[4] # "four" >> b[1] # "one" >> b[3] # "three" >> b[4] # "foobar" >> """ >> >> I've written something like this in Python already, but I'm wondering >> if something like this already exists, preferably written in C, for >> speed. > > > Why complicate this with a custom object? Just use regular dicts and > make b a copy of a. > > a = {1: 'one', 2: 'two', 4: 'four'} > b = dict(a) > b[3] = 'three' > b[4] = 'foobar' Because, as I understand Pavel's intent, it has to work dynamically (e.g. changes in 'a' reflect in behaviour of 'b'), and obviously not only for such trivial examples like above. *j -- Jan Kaliszewski (zuo) From sajmikins at gmail.com Tue Aug 18 17:13:02 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 17:13:02 -0400 Subject: Need cleanup advice for multiline string In-Reply-To: <4A8ADF6D.2030405@sequans.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: <50f98a4c0908181413s69648332i6dea4f927e605f6@mail.gmail.com> On Tue, Aug 18, 2009 at 1:05 PM, Jean-Michel Pichavant wrote: > Steve Holden wrote: >>>> >>>> Robert Dailey: >>>> >> >> [...] >> >>> >>> It's a figure of speech. And besides, why would I want programming >>> advice from a woman? lol. Thanks for the help. >>> >> >> Sorry, Robert, simply not acceptable. Whether designed to be funny or >> not it's the kind of inane remark I would be really happy never to see >> again. >> >> The problem is that we can't just "let these things go by" all the >> time (even though we aren't discussing a major crime here). If we do >> that it encourages (at best) an atmosphere of complacency and a >> feeling that it's OK to demean people in Python forums. I'd really >> like to see those *not* get a hold. >> >> regards >> ?Steve >> > > Did you read the original post (this is an old one) ? Because quoting a joke > out of its context is totally unfair. Unfair to whom? In any event, the context here seems to be a mixture of Guy Fawkes trivia and general disapproval of sexist remarks on c.l.p, so I don't see this comment as "out of context". (For the record, I use "guys" to refer to groups of people regardless of their gender. I also use "dude" to refer to people regardless of their gender. The only person who has taken offense to this is my mom. "I am not a dude." But she means she's not a cowboy, not not a male.) (Uh, she is, in fact, female.) > Anyway the hysteria that is surrounding this thread is just amazing. I'm > waiting for more. I don't feel hysterical, only appalled. The OP used a common slang term, someone mentioned that the term implies a group of males when in fact the group being addressed is mixed gender, and the OP replied that it was "just a figure of speech". So far, so good. But then the OP made a sexist "joke". He was called on it and issued a rather gracious apology, but then he dropped another sexist turd right in the middle of his otherwise model apology. I won't speak for anyone else, but I was appalled. Sexism, racism, homophobia, religious intolerance, etc., all stem from a fundamental forgetfulness of our Unity in God (as I would put it) and this is perhaps the single greatest cause of human misery. We are one family. From deets at nospam.web.de Tue Aug 18 17:18:36 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 23:18:36 +0200 Subject: Editing a wiki In-Reply-To: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> References: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> Message-ID: <7f0k5cF2i58otU1@mid.uni-berlin.de> KillSwitch schrieb: > Hey guys, > Is it possible to edit a wiki page with python, including logging in > to edit the page, and inserting text into the edit box, etc. I was > thinking maybe python would be the language to do this in, because I > have to iterate through every line in a text file and gather info > about what to enter in the wiki that way, then put that text in a wiki > page. It's sort of a program-documenting program. If it's possible to > do this, I would make a special way of entering comments in the source > files, like maybe --[[##title code here]] and then --[[@@code example > here]] with the two symbols at the beginning of the comment dictating > what to enter where. Thanks for any input. Take a look at mechanize, which is a python web-client impostor thingy - it should be easy to use for this purpose. Diez From pavpanchekha at gmail.com Tue Aug 18 17:19:05 2009 From: pavpanchekha at gmail.com (Pavel Panchekha) Date: Tue, 18 Aug 2009 14:19:05 -0700 (PDT) Subject: Inheriting dictionary References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: <30490e9b-7f8d-4adc-afc6-0c1d5e04cbac@f33g2000vbm.googlegroups.com> On Aug 18, 5:11?pm, "Jan Kaliszewski" wrote: > 18-08-2009 o 22:27:41 Nat Williams wrote: > > > > > On Tue, Aug 18, 2009 at 2:44 PM, Pavel Panchekha ? > > wrote: > > >> I want a dictionary that will transparently "inherit" from a parent > >> dictionary. So, for example: > > >> """ > >> a = InheritDict({1: "one", 2: "two", 4: "four"}) > >> b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) > > >> a[1] # "one" > >> a[4] # "four" > >> b[1] # "one" > >> b[3] # "three" > >> b[4] # "foobar" > >> """ > > >> I've written something like this in Python already, but I'm wondering > >> if something like this already exists, preferably written in C, for > >> speed. > > > Why complicate this with a custom object? ?Just use regular dicts and ? > > make b a copy of a. > > > a = {1: 'one', 2: 'two', 4: 'four'} > > b = dict(a) > > b[3] = 'three' > > b[4] = 'foobar' > > Because, as I understand Pavel's intent, it has to work dynamically > (e.g. changes in 'a' reflect in behaviour of 'b'), and obviously not > only for such trivial examples like above. > > *j > > -- > Jan Kaliszewski (zuo) That is indeed the point. From leonhard.vogt at gmx.ch Tue Aug 18 17:19:26 2009 From: leonhard.vogt at gmx.ch (Leonhard Vogt) Date: Tue, 18 Aug 2009 23:19:26 +0200 Subject: How to create functors? In-Reply-To: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> References: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> Message-ID: <36b62$4a8b1adf$544b15b8$17140@news.hispeed.ch> > The example I gave earlier is a bit contrived, the real example > fundamentally requires a lambda since I am actually passing in local > variables into the functions the lambda is wrapping. Example: > > def MyFunction(): > localVariable = 20 > CreateTask( lambda: SomeOtherFunction( localVariable ) ) # CreateTask > () executes the functor internally > > This is more or less like the real scenario I'm working with. There > are other (more personal) reasons why I prefer to avoid 'def' in this > case. I want to keep the functor as central to the code that needs it > as possible to improve code readability. > what about def MyFunction(): localVariable = 20 def wrapper(): return SomeOtherFunction( localVariable ) CreateTask( wrapper ) the wrapper is only visible inside MyFunction. Leonhard From ben+python at benfinney.id.au Tue Aug 18 17:19:39 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 07:19:39 +1000 Subject: Code formatting question: conditional expression References: Message-ID: <87skfohlas.fsf@benfinney.id.au> John Posner writes: > Is there any consensus on how to format a conditional expression that > is too long for one line? How about this: > > excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) > if total > P.BASE else > None) > > The above format separates the values from the if-then-else machinery. > Too many lines? Too much indentation, and worse, indentation that changes based on a distractingly irrelevant quantity: the length of the first line. I prefer:: excessblk = ( Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None) > Would it be better to line up "if" and "else" vertically? ... If the expression assigned in the ?else? branch were also quite long, I'd say yes:: excessblk = ( Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else Block(total, srccol, carry_button_suppress=False)) -- \ ?Friendship is born at that moment when one person says to | `\ another, ?What! You too? I thought I was the only one!?? ?C.S. | _o__) Lewis | Ben Finney From ben+python at benfinney.id.au Tue Aug 18 17:24:35 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 07:24:35 +1000 Subject: Code formatting question: conditional expression References: <7evr1pF2i4mouU1@mid.uni-berlin.de> Message-ID: <87ocqchl2k.fsf@benfinney.id.au> "Diez B. Roggisch" writes: > excessblk = None > if total > P.BASE: > excessblk = ... > > You don't lose any vertical space, I don't see vertical space as such a scarce resource; we don't have an imminent newline shortage, to my knowledge. I value it far lower than, say, local readability. > and it's much more readable IMHO. On the basis of local readability, then, I agree that a multi-line conditional expression is far less quickly comprehensible than a normal multi-line ?if? statement. Assigning the default value of ?None? first (if that's the default) is also good style IMO. -- \ ?Pinky, are you pondering what I'm pondering?? ?Wuh, I think | `\ so, Brain, but wouldn't anything lose its flavor on the bedpost | _o__) overnight?? ?_Pinky and The Brain_ | Ben Finney From deets at nospam.web.de Tue Aug 18 17:24:38 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 23:24:38 +0200 Subject: How to create functors? In-Reply-To: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> References: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> Message-ID: <7f0kgmF2iioslU1@mid.uni-berlin.de> > The example I gave earlier is a bit contrived, the real example > fundamentally requires a lambda since I am actually passing in local > variables into the functions the lambda is wrapping. Example: funcs = [] for i in xrange(10): def f(i=i): print i funcs.append(f) for f in funcs: f() > This is more or less like the real scenario I'm working with. There > are other (more personal) reasons why I prefer to avoid 'def' in this > case. I want to keep the functor as central to the code that needs it > as possible to improve code readability. Didn't you say the other day you came from C++? Given the galactic amount of hoops to jump through that language has to offer, typing def f instead of the even longe lambda strikes me as rather peculiar. Diez From zuo at chopin.edu.pl Tue Aug 18 17:30:19 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 23:30:19 +0200 Subject: How to create functors? In-Reply-To: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> References: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> Message-ID: Dnia 18-08-2009 o 22:51:19 Robert Dailey napisa?(a): > The example I gave earlier is a bit contrived, the real example > fundamentally requires a lambda since I am actually passing in local > variables into the functions the lambda is wrapping. Example: > > def MyFunction(): > localVariable = 20 > CreateTask( lambda: SomeOtherFunction( localVariable ) ) # CreateTask > () executes the functor internally Lambda in Python is a sintactic sugar for some simple situations. But you *always* can replace it with def, e.g.: def MyFunction(): localVariable = 20 def TaskFunction(): SomeOtherFunction(localVariable) CreateTask(TaskFunction) If we say about You can also use functools.partial: import functools def MyFunction(): localVariable = 20 CreateTask(functools.partial(SomeOtherFunction, localVariable) ...which (especially) makes sense if passed function is supposed to be callend many times. > This is more or less like the real scenario I'm working with. There > are other (more personal) reasons why I prefer to avoid 'def' in this > case. I want to keep the functor as central to the code that needs it > as possible to improve code readability. IMHO def is mostly more readable (see my previous mail...). > Thanks for the help everyone. I guess in Python 3.0 the print() > function will not require the import from __future__ to work in this > particular case? Print as a function is a standard feature of Py 3.x so it doesn't require it (see: http://docs.python.org/3.1/whatsnew/3.0.html ). Regards, *j -- Jan Kaliszewski (zuo) From clp2 at rebertia.com Tue Aug 18 17:30:22 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 14:30:22 -0700 Subject: Editing a wiki In-Reply-To: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> References: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> Message-ID: <50697b2c0908181430k7b36ec3fv4248865dbd0ae954@mail.gmail.com> On Tue, Aug 18, 2009 at 2:02 PM, KillSwitch wrote: > Hey guys, > Is it possible to edit a wiki page with python, including logging in > to edit the page, and inserting text into the edit box, etc. Depends on the wiki. For Mediawiki, yes: http://pywikipediabot.sourceforge.net/ Cheers, Chris -- http://blog.rebertia.com From invalid at invalid Tue Aug 18 17:31:58 2009 From: invalid at invalid (Grant Edwards) Date: Tue, 18 Aug 2009 16:31:58 -0500 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: On 2009-08-18, Simon Forman wrote: > Sexism, racism, homophobia, religious intolerance, etc., all > stem from a fundamental forgetfulness of our Unity in God (as > I would put it) and this is perhaps the single greatest cause > of human misery. You mean the single greatest cause of human misery isn't Microsoft Windows? -- Grant Edwards grante Yow! What I want to find at out is -- do parrots know visi.com much about Astro-Turf? From paul at boddie.org.uk Tue Aug 18 17:32:11 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 18 Aug 2009 14:32:11 -0700 (PDT) Subject: Editing a wiki References: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> Message-ID: On 18 Aug, 23:02, KillSwitch wrote: > Hey guys, > Is it possible to edit a wiki page with python, including logging in > to edit the page, and inserting text into the edit box, etc. I was > thinking maybe python would be the language to do this in, because I > have to iterate through every line in a text file and gather info > about what to enter in the wiki that way, then put that text in a wiki > page. What you seem to want is a way of interacting with Web forms, and there are various Python client libraries which do this: http://wiki.python.org/moin/WebClientProgramming However, see below. > It's sort of a program-documenting program. If it's possible to > do this, I would make a special way of entering comments in the source > files, like maybe --[[##title code here]] and then --[[@@code example > here]] with the two symbols at the beginning of the comment dictating > what to enter where. Thanks for any input. Generally, you have to be careful interacting with Web sites in an automated fashion: Wiki sites in particular often have measures in place to deter "robots" and behaviour which looks like spamming. If the Wiki is under your control, you'd be better off uploading content via the data store (such as the filesystem for MoinMoin and some other Wiki solutions) or via specific mechanisms provided for administration of the Wiki. Paul From ben+python at benfinney.id.au Tue Aug 18 17:39:13 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 07:39:13 +1000 Subject: Code formatting question: conditional expression References: Message-ID: <87k510hke6.fsf@benfinney.id.au> John Posner writes: > > excessblk = None > > if total > P.BASE: > > excessblk = ... > > [?] > But doesn't it violate the DRY principle? The token "excessblk" > appears twice instead of once. No, the DRY principle doesn't speak against assigning two *different* values in two *different* circumstances. That's not duplication, and doesn't risk contradiction. DRY speaks against repeating the same *meaning* in two different places. Because this concept is expressed in natural language and not a programming language, and because we don't speak in a language under the same principles we espouse for programming, there are multiple terms used for this concept :-) Another term which makes the point slightly more sharply is SPOT: there should be a Single Point Of Truth for each fact in the overall system. -- \ ?What I have to do is see, at any rate, that I do not lend | `\ myself to the wrong which I condemn.? ?Henry Thoreau, _Civil | _o__) Disobedience_ | Ben Finney From zuo at chopin.edu.pl Tue Aug 18 17:41:02 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 23:41:02 +0200 Subject: basic thread question In-Reply-To: <20090818201015.GP20434@dragontoe.org> References: <20090818201015.GP20434@dragontoe.org> Message-ID: 18-08-2009 o 22:10:15 Derek Martin wrote: > I have some simple threaded code... If I run this > with an arg of 1 (start one thread), it pegs one cpu, as I would > expect. If I run it with an arg of 2 (start 2 threads), it uses both > CPUs, but utilization of both is less than 50%. Can anyone explain > why? > > I do not pretend it's impeccable code, and I'm not looking for a > critiqe of the code per se, excepting the case where what I've written > is actually *wrong*. I hacked this together in a couple of minutes, > with the intent of pegging my CPUs. Performance with two threads is > actually *worse* than with one, which is highly unintuitive. I can > accomplish my goal very easily with bash, but I still want to > understand what's going on here... > > The OS is Linux 2.6.24, on a Ubuntu base. Here's the code: Python threads can't benefit from multiple processors (because of GIL, see: http://docs.python.org/glossary.html#term-global-interpreter-lock). 'multiprocessing' module is what you need: http://docs.python.org/library/multiprocessing.html Cheers, *j -- Jan Kaliszewski (zuo) From ben+python at benfinney.id.au Tue Aug 18 17:42:40 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 07:42:40 +1000 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> Message-ID: <87fxbohk8f.fsf@benfinney.id.au> Jean-Michel Pichavant writes: > Anyway the hysteria that is surrounding this thread is just amazing. If the calm reproach that has been the maximum response so far seems like ?hysteria? to you, I can only conclude you have only been using the internet for a few hours. -- \ ?The fact that I have no remedy for all the sorrows of the | `\ world is no reason for my accepting yours. It simply supports | _o__) the strong probability that yours is a fake.? ?Henry L. Mencken | Ben Finney From rcdailey at gmail.com Tue Aug 18 17:50:22 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 14:50:22 -0700 (PDT) Subject: How to create functors? References: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> Message-ID: On Aug 18, 4:30?pm, "Jan Kaliszewski" wrote: > Lambda in Python is a sintactic sugar for some simple situations. But you > *always* can replace it with def, e.g.: > > ? def MyFunction(): > > ? ? ? localVariable = 20 > ? ? ? def TaskFunction(): > ? ? ? ? ? SomeOtherFunction(localVariable) > > ? ? ? CreateTask(TaskFunction) > > If we say about You can also use functools.partial: > > ? import functools > > ? def MyFunction(): > > ? ? ? localVariable = 20 > ? ? ? CreateTask(functools.partial(SomeOtherFunction, localVariable) > > ...which (especially) makes sense if passed function is supposed to be > callend many times. Good point, I'm too used to C++ (Can't define functions in local scope). I never thought of that. In C++ I use boost::bind() fairly extensively and I carry over those habits to python. > > IMHO def is mostly more readable (see my previous mail...). > > Print as a function is a standard feature of Py 3.x so it doesn't > require it (see:http://docs.python.org/3.1/whatsnew/3.0.html). Thanks for the info. From erik1vandamme at gmail.com Tue Aug 18 18:06:50 2009 From: erik1vandamme at gmail.com (Erik Vandamme) Date: Tue, 18 Aug 2009 15:06:50 -0700 (PDT) Subject: Setuptools - help! References: Message-ID: <77a95cac-a059-4501-917a-e87157511912@p36g2000prn.googlegroups.com> On Aug 7, 9:17?am, Robert Kern wrote: > On 2009-08-06 18:04, Peter Chant wrote: > > > > > Chaps, > > > any ideas, I'm floundering - I don't quite get it. ?I have the following > > files, setup.py and main.py in a directory pphoto: > > > # more setup.py > > from setuptools import setup, find_packages > > setup( > > ? ? ?name = "Pphoto", > > ? ? ?version = "0.1", > > ? ? ?packages = find_packages(), > > > ? ? ?# other arguments here... > > ? ? ?entry_points = {'console_scripts': ['foo = pphoto.main:HelloWorld',]} > > > ) > > > bash-3.1# more main.py > > > def HelloWorld(): > > ? ? ?print "Hello World!" > > > print "Odd world" > > >> From various websites that should produce a script foo that runs HelloWorld. > > It does produce a script that simply crashes. > > > bash-3.1# foo > > Traceback (most recent call last): > > ? ?File "/usr/bin/foo", line 8, in > > ? ? ?load_entry_point('Pphoto==0.1', 'console_scripts', 'foo')() > > ? ?File "build/bdist.linux-i686/egg/pkg_resources.py", line 277, in > > load_entry_point > > ? ?File "build/bdist.linux-i686/egg/pkg_resources.py", line 2098, in > > load_entry_point > > ? ?File "build/bdist.linux-i686/egg/pkg_resources.py", line 1831, in load > > ImportError: No module named pphoto.main > > bash-3.1# > > > Note, doing this as root as it seems not to do anything usefull at all if I > > run python setup develop as a user. > > > Any ideas? ?I must be missing something fundamental? > > You need to put main.py into the pphoto package. > > $ mkdir pphoto/ > $ mv main.py pphoto/ > $ touch pphoto/__init__.py > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco erik at erik-d2c:~/calibre-0.6.7$ mv main.py pphoto/ mv: cannot stat `main.py': No such file or directory ------------------------------------- there is no main.py in the main calibre folder and there is 5 of them in the subfolders????? From sajmikins at gmail.com Tue Aug 18 18:08:11 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 15:08:11 -0700 (PDT) Subject: Inheriting dictionary References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: <2fe6d216-1e8f-4de1-8c36-d4ee11bb7233@26g2000yqk.googlegroups.com> On Aug 18, 3:44?pm, Pavel Panchekha wrote: > I want a dictionary that will transparently "inherit" from a parent > dictionary. So, for example: > > """ > a = InheritDict({1: "one", 2: "two", 4: "four"}) > b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) > > a[1] # "one" > a[4] # "four" > b[1] # "one" > b[3] # "three" > b[4] # "foobar" > """ > > I've written something like this in Python already, but I'm wondering > if something like this already exists, preferably written in C, for > speed. I would consider something like the following: a = {1: "one", 2: "two", 4: "four"} b = {3: "three", 4: "foobar"} from functools import partial def getter(first, second, key): try: return first(key) except KeyError: return second(key) f = partial(getter, b.__getitem__, a.__getitem__) # Or, if you know you'll be getting a lot of KeyErrors, you # can use get() instead of __getitem__(). def getter1(first, second, key, sentinel=None): item = first(key, sentinel) if item is sentinel: item = second(key) return item g = partial(getter1, b.get, a.__getitem__) HTH, ~Simon From robert.kern at gmail.com Tue Aug 18 18:14:42 2009 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 18 Aug 2009 15:14:42 -0700 Subject: Setuptools - help! In-Reply-To: <77a95cac-a059-4501-917a-e87157511912@p36g2000prn.googlegroups.com> References: <77a95cac-a059-4501-917a-e87157511912@p36g2000prn.googlegroups.com> Message-ID: On 2009-08-18 15:06 PM, Erik Vandamme wrote: > On Aug 7, 9:17 am, Robert Kern wrote: >> On 2009-08-06 18:04, Peter Chant wrote: >> >> >> >>> Chaps, >> >>> any ideas, I'm floundering - I don't quite get it. I have the following >>> files, setup.py and main.py in a directory pphoto: >> >>> # more setup.py >>> from setuptools import setup, find_packages >>> setup( >>> name = "Pphoto", >>> version = "0.1", >>> packages = find_packages(), >> >>> # other arguments here... >>> entry_points = {'console_scripts': ['foo = pphoto.main:HelloWorld',]} >> >>> ) >> >>> bash-3.1# more main.py >> >>> def HelloWorld(): >>> print "Hello World!" >> >>> print "Odd world" >> >>>> From various websites that should produce a script foo that runs HelloWorld. >>> It does produce a script that simply crashes. >> >>> bash-3.1# foo >>> Traceback (most recent call last): >>> File "/usr/bin/foo", line 8, in >>> load_entry_point('Pphoto==0.1', 'console_scripts', 'foo')() >>> File "build/bdist.linux-i686/egg/pkg_resources.py", line 277, in >>> load_entry_point >>> File "build/bdist.linux-i686/egg/pkg_resources.py", line 2098, in >>> load_entry_point >>> File "build/bdist.linux-i686/egg/pkg_resources.py", line 1831, in load >>> ImportError: No module named pphoto.main >>> bash-3.1# >> >>> Note, doing this as root as it seems not to do anything usefull at all if I >>> run python setup develop as a user. >> >>> Any ideas? I must be missing something fundamental? >> >> You need to put main.py into the pphoto package. >> >> $ mkdir pphoto/ >> $ mv main.py pphoto/ >> $ touch pphoto/__init__.py >> >> -- >> Robert Kern >> >> "I have come to believe that the whole world is an enigma, a harmless enigma >> that is made terrible by our own mad attempt to interpret it as though it had >> an underlying truth." >> -- Umberto Eco > erik at erik-d2c:~/calibre-0.6.7$ mv main.py pphoto/ > mv: cannot stat `main.py': No such file or directory > ------------------------------------- > there is no main.py in the main calibre folder and there is 5 of them > in the subfolders????? I was helping Peter Chant with his problem. You have a different problem. Why are you trying to follow my advice verbatim for a completely different package? What problem are you seeing? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From code at pizzashack.org Tue Aug 18 18:18:54 2009 From: code at pizzashack.org (Derek Martin) Date: Tue, 18 Aug 2009 17:18:54 -0500 Subject: basic thread question In-Reply-To: <20090818201015.GP20434@dragontoe.org> References: <20090818201015.GP20434@dragontoe.org> Message-ID: <20090818221854.GQ20434@dragontoe.org> On Tue, Aug 18, 2009 at 03:10:15PM -0500, Derek Martin wrote: > I have some simple threaded code... If I run this > with an arg of 1 (start one thread), it pegs one cpu, as I would > expect. If I run it with an arg of 2 (start 2 threads), it uses both > CPUs, but utilization of both is less than 50%. Can anyone explain > why? Ah, searching while waiting for an answer (the e-mail gateway is a bit slow, it seems...) I discovered that the GIL is the culprate. Evidently this question comes up a lot. It would probably save a lot of time on the part of those who answer questions here, as well as those implementing solutions in Python, if whoever is maintaining the docs these days would put a blurb about this in the docs in big bold letters... Concurrency being perhaps the primary reason to use threading, essentially it means that Python is not useful for the sorts of problems that one would be inclined to solve they way my code works (or rather, was meant to). It would be very helpful to know that *before* one tried to implement a solution that way... especially for solutions significantly less trivial than mine. ;-) Thanks -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From digitalxero at gmail.com Tue Aug 18 18:21:26 2009 From: digitalxero at gmail.com (Dj Gilcrease) Date: Tue, 18 Aug 2009 16:21:26 -0600 Subject: [Python-Dev] Mercurial migration: help needed In-Reply-To: <4A8A6256.1030009@v.loewis.de> References: <4A8A6256.1030009@v.loewis.de> Message-ID: On Tue, Aug 18, 2009 at 2:12 AM, "Martin v. L?wis" wrote: > The second item is line conversion hooks. Dj Gilcrease has posted a > solution which he considers a hack himself. Mark Hammond has also > volunteered, but it seems some volunteer needs to be "in charge", > keeping track of a proposed solution until everybody agrees that it > is a good solution. It may be that two solutions are necessary: a > short-term one, that operates as a hook and has limitations, and > a long-term one, that improves the hook system of Mercurial to > implement the proper functionality (which then might get shipped > with Mercurial in a cross-platform manner). My solution is a hack because the hooks in Mercurial need to be modified to support it properly, I would be happy to help work on this as it is a situation I run into all the time in my own projects. I can never seem to get all the developers to enable the hooks, and one of them always commits with improper line endings =P From markscottwright at gmail.com Tue Aug 18 18:24:20 2009 From: markscottwright at gmail.com (markscottwright) Date: Tue, 18 Aug 2009 15:24:20 -0700 (PDT) Subject: How do I convert an iterator over bytes into a str? Message-ID: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> This does what I expected: In [6]: list(iter([1,2,3,4,5])) Out[6]: [1, 2, 3, 4, 5] But this appears to be doing a __repr__ rather than making me a nice string: In [7]: str(iter("four score and seven years ago")) Out[7]: '' What's the correct way to turn an iterator over bytes into a string? This works, but, ewww: In [8]: "".join(iter("four score and seven years ago")) Out[8]: 'four score and seven years ago' From emile at fenx.com Tue Aug 18 18:39:27 2009 From: emile at fenx.com (Emile van Sebille) Date: Tue, 18 Aug 2009 15:39:27 -0700 Subject: Need cleanup advice for multiline string In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: On 8/18/2009 2:31 PM Unknown said... > You mean the single greatest cause of human misery isn't > Microsoft Windows? Either that or users... Sick-of-both-today-ly y'rs, Emile From davidshais at googlemail.com Tue Aug 18 18:47:09 2009 From: davidshais at googlemail.com (David) Date: Tue, 18 Aug 2009 15:47:09 -0700 (PDT) Subject: Scope and classes Message-ID: Hi all, I'm trying to understand how scopes work within a class definition. I'll quickly illustrate with an example. Say I had the following class definition: class Abc: message = 'Hello World' def print_message(self): print message >>> instance = Abc() >>> instance.print_message() NameError: global name 'message' not defined My question is, why? message is not defined in print_message, but it is defined in the enclosing scope (the class)? Thanks! From breamoreboy at yahoo.co.uk Tue Aug 18 18:54:13 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 18 Aug 2009 23:54:13 +0100 Subject: How do I convert an iterator over bytes into a str? In-Reply-To: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> Message-ID: markscottwright wrote: > This does what I expected: > In [6]: list(iter([1,2,3,4,5])) > Out[6]: [1, 2, 3, 4, 5] > > But this appears to be doing a __repr__ rather than making me a nice > string: > In [7]: str(iter("four score and seven years ago")) > Out[7]: '' > > What's the correct way to turn an iterator over bytes into a string? > This works, but, ewww: > In [8]: "".join(iter("four score and seven years ago")) > Out[8]: 'four score and seven years ago' You've started with a string. >>> type("four score and seven years ago") -- Kindest regards. Mark Lawrence. From olivier.anospamrnospamnnospamanospamenospamz at affaires.net Tue Aug 18 19:03:30 2009 From: olivier.anospamrnospamnnospamanospamenospamz at affaires.net (Ludo) Date: Wed, 19 Aug 2009 01:03:30 +0200 Subject: Read C++ enum in python Message-ID: <4a8b3342$0$25403$426a34cc@news.free.fr> Hello, I work in a very large project where we have C++ packages and pieces of python code. I've been googleing for days but what I find seems really too complicated for what I want to do. My business is, in python, to read enum definitions provided by the header file of an c++ package. Of course I could open the .h file, read the enum and transcode it by hand into a .py file but the package is regularly updated and thus is the enum. My question is then simple : do we have : - either a simple way in python to read the .h file, retrieve the c++ enum and provide an access to it in my python script - either a simple tool (in a long-term it would be automatically run when the c++ package is compiled) generating from the .h file a .py file containing the python definition of the enums ? Thank you for any suggestion. From atulskulkarni at gmail.com Tue Aug 18 19:06:12 2009 From: atulskulkarni at gmail.com (Atul.) Date: Tue, 18 Aug 2009 16:06:12 -0700 (PDT) Subject: Python on the web, how to? Message-ID: Hello All, Needless to say I am new to python and web programming. I am looking for a quick Python-101 course / tutorial for "using python to implement dynamic content on web" under some web server. Any pointers what should I be reading? Regards, Atul. From clp2 at rebertia.com Tue Aug 18 19:16:07 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 16:16:07 -0700 Subject: Scope and classes In-Reply-To: References: Message-ID: <50697b2c0908181616y41cab4eah13769e75d59a505d@mail.gmail.com> On Tue, Aug 18, 2009 at 3:47 PM, David wrote: > Hi all, > > I'm trying to understand how scopes work within a class definition. > I'll quickly illustrate with an example. Say I had the following class > definition: > > class Abc: > ? ?message = 'Hello World' > > ? ?def print_message(self): > ? ? ? ?print message > >>>> instance = Abc() >>>> instance.print_message() > NameError: global name 'message' not defined > > My question is, why? message is not defined in print_message, but it > is defined in the enclosing scope (the class)? A class' scope is never consulted when resolving variable names in its methods. The scopes consulted are roughly (and in this order): 1. Local variable scope (i.e. of the current function/method) 2. Enclosing functions (if you have functions nested inside other functions) 3. Globals (i.e. module-level variables) 3. Builtins (i.e. the built-in functions and methods, such as len()) To access class-level variables from within instance methods of the class, you have 2 options: A. Use the class name, i.e. Abc.message B. Reference the class indirectly, i.e. self.__class__.message Cheers, Chris -- http://blog.rebertia.com From wwn1 at sfu.ca Tue Aug 18 19:16:33 2009 From: wwn1 at sfu.ca (WilsonOfCanada) Date: Tue, 18 Aug 2009 16:16:33 -0700 (PDT) Subject: Raw Strings with Variables Message-ID: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Hellos, I know that if you have: happy = r"C:\moo" print happy you get C:\moo instead of C:\\moo The thing is that I want to do this a variable instead. ex. testline = fileName.readline() rawtestline = r testline Thanks From clp2 at rebertia.com Tue Aug 18 19:18:57 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 16:18:57 -0700 Subject: Python on the web, how to? In-Reply-To: References: Message-ID: <50697b2c0908181618r6be34f68ma7702b8358788602@mail.gmail.com> On Tue, Aug 18, 2009 at 4:06 PM, Atul. wrote: > Hello All, > > Needless to say I am new to python and web programming. I am looking > for a quick Python-101 course / tutorial for "using python to > implement dynamic content on web" under some web server. Any pointers > what should I be reading? Google for "Python web framework" and take your pick. Some popular choices: - Django: http://www.djangoproject.com/ -- associated online book: http://djangobook.com/ - TurboGears: http://turbogears.org/ Cheers, Chris -- http://blog.rebertia.com From af2012 at gmail.com Tue Aug 18 19:33:00 2009 From: af2012 at gmail.com (Allan) Date: Tue, 18 Aug 2009 16:33:00 -0700 (PDT) Subject: recording input from USB port and write to text file Message-ID: Hi! I'm fairly new to Python. I understand the basics basics but I'm been trying to write a simple python code that will let me read input data (such as mouse movement) from my USB port and write it in a text file and I am so lost. Can anyone help or direct me to some resources? Thank you! From davidshais at googlemail.com Tue Aug 18 19:38:15 2009 From: davidshais at googlemail.com (David) Date: Tue, 18 Aug 2009 16:38:15 -0700 (PDT) Subject: Scope and classes References: Message-ID: <07746be7-368e-4222-82a1-fecb5c2c5da3@s31g2000yqs.googlegroups.com> On Aug 19, 12:16?am, Chris Rebert wrote: > On Tue, Aug 18, 2009 at 3:47 PM, David wrote: > > Hi all, > > > I'm trying to understand how scopes work within a class definition. > > I'll quickly illustrate with an example. Say I had the following class > > definition: > > > class Abc: > > ? ?message = 'Hello World' > > > ? ?def print_message(self): > > ? ? ? ?print message > > >>>> instance = Abc() > >>>> instance.print_message() > > NameError: global name 'message' not defined > > > My question is, why? message is not defined in print_message, but it > > is defined in the enclosing scope (the class)? > > A class' scope is never consulted when resolving variable names in its methods. > > The scopes consulted are roughly (and in this order): > 1. Local variable scope (i.e. of the current function/method) > 2. Enclosing functions (if you have functions nested inside other functions) > 3. Globals (i.e. module-level variables) > 3. Builtins (i.e. the built-in functions and methods, such as len()) > > To access class-level variables from within instance methods of the > class, you have 2 options: > A. Use the class name, i.e. Abc.message > B. Reference the class indirectly, i.e. self.__class__.message > > Cheers, > Chris > --http://blog.rebertia.com Ah, thanks! From steve at REMOVE-THIS-cybersource.com.au Tue Aug 18 19:39:38 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 23:39:38 GMT Subject: Scope and classes References: Message-ID: <0014bf1a$0$2963$c3e8da3@news.astraweb.com> On Tue, 18 Aug 2009 15:47:09 -0700, David wrote: > Hi all, > > I'm trying to understand how scopes work within a class definition. I'll > quickly illustrate with an example. Say I had the following class > definition: > > class Abc: > message = 'Hello World' > > def print_message(self): > print message > >>>> instance = Abc() >>>> instance.print_message() > NameError: global name 'message' not defined > > My question is, why? message is not defined in print_message, but it is > defined in the enclosing scope (the class)? It's a deliberate design decision. I don't recall the reasons for it, but the class namespace is deliberately excluded from the method scope. The correct way of writing the above is: class Abc: message = 'Hello World' def print_message(self): print self.message self.message will first search the instance namespace for an attribute `message`, then search the class, then any superclasses. If you specifically want the class attribute, even if the instance masks it with an instance attribute of the same name, you do this instead: print self.__class__.message -- Steven From marduk at letterboxes.org Tue Aug 18 19:39:54 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 18 Aug 2009 19:39:54 -0400 Subject: Raw Strings with Variables In-Reply-To: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: <1250638794.5388.3.camel@centar.nbk> On Tue, 2009-08-18 at 16:16 -0700, WilsonOfCanada wrote: > Hellos, > > I know that if you have: > > happy = r"C:\moo" > print happy > > you get C:\moo instead of C:\\moo > > The thing is that I want to do this a variable instead. > > ex. testline = fileName.readline() > rawtestline = r testline I'm not sure what you are hoping for... Raw strings apply to string literals. If you are reading from a file, as above, you need not worry about it: $ cat test.txt C:\moo $ python -c 'r = open("test.txt").readline() ; print r' C:\moo From python at mrabarnett.plus.com Tue Aug 18 19:50:05 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 19 Aug 2009 00:50:05 +0100 Subject: Read C++ enum in python In-Reply-To: <4a8b3342$0$25403$426a34cc@news.free.fr> References: <4a8b3342$0$25403$426a34cc@news.free.fr> Message-ID: <4A8B3E2D.7040702@mrabarnett.plus.com> Ludo wrote: > Hello, > > I work in a very large project where we have C++ packages and pieces of > python code. > > I've been googleing for days but what I find seems really too > complicated for what I want to do. > > My business is, in python, to read enum definitions provided by the > header file of an c++ package. > Of course I could open the .h file, read the enum and transcode it by > hand into a .py file but the package is regularly updated and thus is > the enum. > > My question is then simple : do we have : > - either a simple way in python to read the .h file, retrieve the > c++ enum and provide an access to it in my python script > - either a simple tool (in a long-term it would be automatically run > when the c++ package is compiled) generating from the .h file a .py file > containing the python definition of the enums ? > > Thank you for any suggestion. Speaking personally, I'd parse the .h file using a regular expression (re module) and generate a .py file. Compilers typically have a way of letting you run external scripts (eg batch files in Windows or, in this case, a Python script) when an application is compiled. From zuo at chopin.edu.pl Tue Aug 18 19:52:42 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 19 Aug 2009 01:52:42 +0200 Subject: How do I convert an iterator over bytes into a str? In-Reply-To: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> Message-ID: 19-08-2009 o 00:24:20 markscottwright wrote: > What's the correct way to turn an iterator over bytes into a string? > This works, but, ewww: > In [8]: "".join(iter("four score and seven years ago")) > Out[8]: 'four score and seven years ago' But it is the correct way (and even recommended over s=s+t or s+=t, when applicable -- see: http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange). Cheers, *j -- Jan Kaliszewski (zuo) From david.birdsong at gmail.com Tue Aug 18 19:58:28 2009 From: david.birdsong at gmail.com (birdsong) Date: Tue, 18 Aug 2009 16:58:28 -0700 (PDT) Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> Message-ID: <92338aa1-0913-483a-b950-c73f0fdb0b1f@v37g2000prg.googlegroups.com> On Aug 18, 3:18?pm, Derek Martin wrote: > On Tue, Aug 18, 2009 at 03:10:15PM -0500, Derek Martin wrote: > > I have some simple threaded code... ?If I run this > > with an arg of 1 (start one thread), it pegs one cpu, as I would > > expect. ?If I run it with an arg of 2 (start 2 threads), it uses both > > CPUs, but utilization of both is less than 50%. ?Can anyone explain > > why? ? > > Ah, searching while waiting for an answer (the e-mail gateway is a bit > slow, it seems...) I discovered that the GIL is the culprate. > Evidently this question comes up a lot. ?It would probably save a lot > of time on the part of those who answer questions here, as well as > those implementing solutions in Python, if whoever is maintaining the > docs these days would put a blurb about this in the docs in big bold > letters... ?Concurrency being perhaps the primary reason to use > threading, essentially it means that Python is not useful for the > sorts of problems that one would be inclined to solve they way my code > works (or rather, was meant to). ?It would be very helpful to know > that *before* one tried to implement a solution that way... especially > for solutions significantly less trivial than mine. ;-) > > Thanks > > -- > Derek D. Martinhttp://www.pizzashack.org/ > GPG Key ID: 0x81CFE75D > > ?application_pgp-signature_part > < 1KViewDownload I would still watch that video which will explain a bit more about the GIL. From steve at REMOVE-THIS-cybersource.com.au Tue Aug 18 20:03:44 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2009 00:03:44 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: <0014c4c0$0$2963$c3e8da3@news.astraweb.com> On Tue, 18 Aug 2009 17:13:02 -0400, Simon Forman wrote: > Sexism, racism, homophobia, religious intolerance, etc., all stem from a > fundamental forgetfulness of our Unity in God (as I would put it) and Of the tens of thousands of Gods that people have invented, which is the one we're supposed to believe in? I always forget which ones we're supposed to dismiss as nonsense, and which one we're not. > this is perhaps the single greatest cause of human misery. Okay, we're Unified in God. Great. What does that actually mean, really? In the struggle to survive in a world of shortages, disease, natural disasters and disputes between well-meaning but incompatible viewpoints (to say nothing of the selfish and greedy), what practical difference does it make? -- Steven From cmpython at gmail.com Tue Aug 18 20:04:08 2009 From: cmpython at gmail.com (Che M) Date: Tue, 18 Aug 2009 17:04:08 -0700 (PDT) Subject: GUI interface builder for python References: <21bca3cf-b2c7-47d7-9142-26c9fd015f92@r27g2000vbn.googlegroups.com> <02ec7cd9-e749-46d3-8b25-75d85794f292@o35g2000vbi.googlegroups.com> Message-ID: <02bf2081-4f4a-4219-8441-1d48f09af338@c14g2000yqm.googlegroups.com> On Aug 18, 10:54?am, sturlamolden wrote: > On 17 Aug, 17:19, Che M wrote: > > > Boa (Boa Constructor) is really nice for wxPython GUI > > work, but it has some bugs when using Linux that might > > be dealbreakers for the user. ?At least I have had > > problems on Ubuntu 8.10 64 bit (but none or very few > > I prefer wxFormBuilder over Boa. Why? From tjreedy at udel.edu Tue Aug 18 20:08:20 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Aug 2009 09:08:20 +0900 Subject: sub-list extraction, logical indexation In-Reply-To: References: Message-ID: Pierre wrote: > Hello Everyone, > > I would like to know if it is possible to extract a sub-list from a > list ? > > typically if : > > L =[[1, 2, 3],[4, 5, 6],[3] ] > > How to extract easily the elements 0 and 2 of L in order to get : > > L2 =[[1, 2, 3],[3] ] L2 = [L[0],L[2]] > > Moreover, I would like to know if it is possible to use logical > indexation such that : > > index = [ True, False, True] > L2 = L use zip(index,L) in a for loop > > or usual indexation, something like > index=[0, 2] > L2 = L #untried L2=[] for i in index L2.append(L[i]) tjr From wwn1 at sfu.ca Tue Aug 18 20:09:29 2009 From: wwn1 at sfu.ca (WilsonOfCanada) Date: Tue, 18 Aug 2009 17:09:29 -0700 (PDT) Subject: Raw Strings with Variables References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: You're right, but the moment I append it onto a list, it would become C:\\moo. arrPlaces = [] intPoint =0 while (len(testline)): testline = fileName.readline() print testline arrPlaces[intPoint].append(testline) intPoint += 1 print arrPlaces > C:\moo > C:\supermoo > ['C:\\moo', 'C:\\supermoo'] Is there a way to stop that when appending to the dictionary? Thanks From zuo at chopin.edu.pl Tue Aug 18 20:10:58 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 19 Aug 2009 02:10:58 +0200 Subject: Scope and classes In-Reply-To: References: Message-ID: 19-08-2009 o 00:47:09 David wrote: > Hi all, > > I'm trying to understand how scopes work within a class definition. > I'll quickly illustrate with an example. Say I had the following class > definition: > > class Abc: > message = 'Hello World' > > def print_message(self): > print message > >>>> instance = Abc() >>>> instance.print_message() > NameError: global name 'message' not defined > > My question is, why? message is not defined in print_message, but it > is defined in the enclosing scope (the class)? Note that when *running* the code that is *inside* print_message() method called within the global scope, the outer (enclosing) scope is indeed the global scope (the scope in which e.g. 'instance' name exists; note that e.g. 'print instance' in that method would be ok). As Chris wrote, class' scope (contrary to outer function scope) is not considered as the 'enclosing' scope. The only ways to reach Abc's attribute 'message' from that method are: * 'Abc.message' * 'self.__class__.message' * 'self.message' (unless there is an instance attribute 'message' which overrides the class attribute). Cheers, *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Tue Aug 18 20:17:22 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 19 Aug 2009 02:17:22 +0200 Subject: Scope and classes In-Reply-To: References: Message-ID: 19-08-2009 o 02:10:58 Jan Kaliszewski wrote: > The only ways to reach Abc's attribute 'message' from that method are: > * 'Abc.message' > * 'self.__class__.message' > * 'self.message' (unless there is an instance attribute 'message' which > overrides the class attribute). And of course getattr(Abc), getattr(self.__class__) etc. :-) -- Jan Kaliszewski (zuo) From clp2 at rebertia.com Tue Aug 18 20:18:13 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 17:18:13 -0700 Subject: Raw Strings with Variables In-Reply-To: References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: <50697b2c0908181718w6eb8befbp876e8cd831ec3c8e@mail.gmail.com> On Tue, Aug 18, 2009 at 5:09 PM, WilsonOfCanada wrote: > You're right, but the moment I append it onto a list, it would become > C:\\moo. > > arrPlaces = [] > intPoint =0 > > while (len(testline)): > ? ? ? ?testline = fileName.readline() > ? ? ? ?print testline > ? ? ? ?arrPlaces[intPoint].append(testline) > ? ? ? ?intPoint += 1 > > print arrPlaces > >> C:\moo >> C:\supermoo >> ['C:\\moo', 'C:\\supermoo'] That's because the list uses repr() rather than str() to stringify its items when it is output. repr() shows escape sequences rather than the literal characters and adds the surrounding quote marks, but the string is not modified upon placement in the container. Study this interpreter session: >>> a = r"C:\supermoo" >>> b = "\t" #a tab character >>> c = [a, b] >>> print a #note the lack of quotes in the output C:\supermoo >>> print repr(a) #note the quotes and \\ 'C:\\supermoo' >>> print b #we see the literal tab >>> print repr(b) #we see the escape sequence '\t' >>> print c #note how this matches the repr() output from earlier ['C:\\supermoo', '\t'] >>> print c[0], c[1], "end" #but the actual strings are the same as before C:\supermoo end Cheers, Chris -- http://blog.rebertia.com From zuo at chopin.edu.pl Tue Aug 18 20:30:36 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 19 Aug 2009 02:30:36 +0200 Subject: Raw Strings with Variables In-Reply-To: References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: Dnia 19-08-2009 o 02:09:29 WilsonOfCanada napisa?(a): > You're right, but the moment I append it onto a list, it would become > C:\\moo. No, it would not. Really! > C:\moo > C:\supermoo > ['C:\\moo', 'C:\\supermoo'] It is not the matter of content of the string but only of a way of *presentation* of it by print: print arrPlaces in the example is roughly equivalent to: print '[' + repr(a_list[0]) + ', ' + repr(a_list[1]) + ']' So try: print a_list[0] Output: C:\moo print a_list[1] Output: C:\supermoo print ', '.join(arrPlaces) Output: C:\moo, C:\supermoo print ', '.join("'%s'" % item for item in arrPlaces) Output: 'C:\moo', 'C:\supermoo' Cheers, *j -- Jan Kaliszewski (zuo) From ben+python at benfinney.id.au Tue Aug 18 20:42:13 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 10:42:13 +1000 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: <87hbw4fxcq.fsf@benfinney.id.au> Simon Forman writes: > Sexism, racism, homophobia, religious intolerance, etc., all stem from > a fundamental forgetfulness of our Unity in God (as I would put it) It seems odd, for someone who cites religious intolerance as a problem, to then assert an extremely divisive religious idea. We're all unified by our humanity. Bringing any god into the picture is surely counter to any goals of unity. > We are one family. Agreed. -- \ ?Are you thinking what I'm thinking, Pinky?? ?Uh... yeah, | `\ Brain, but where are we going to find rubber pants our size?? | _o__) ?_Pinky and The Brain_ | Ben Finney From mauriceling at gmail.com Tue Aug 18 20:49:56 2009 From: mauriceling at gmail.com (mauriceling@acm.org) Date: Tue, 18 Aug 2009 17:49:56 -0700 (PDT) Subject: Call for Papers - PyCon Asia Pacific 2010 Message-ID: <04687d05-2017-4002-ba11-6d50f684b2f3@y28g2000prd.googlegroups.com> Dear fellow friends and colleagues, I apologize if you had received multiple copies of this Call for Papers. Maurice ================================================================== ------------------------------------------------------------ Call for Papers - PyCon Asia Pacific 2010 ------------------------------------------------------------ PyCon Asia Pacific 2010 represents a major development for the Python community in the Asia Pacific region. In Asia Pacific, we are encouraged by the country-level initiatives of Python conferences in India and New Zealand. We fully expect that PyCon Asia Pacific will be hosted by different APAC countries as the momentum of Python develops in the region. Quote : ??Python development in the Asia Pacific region is proceeding rapidly? I would very much like to highlight the special nature of this conference?. I hope that my presence will help to further international cooperation on Python development? Steven Holden, Chairman, Python Software Foundation (PSF) Keynote, PyCon Asia Pacific 2010 PyCon Asia Pacific 2010?s is looking for proposals from the Python community to fill its formal presentation tracks. The Conference Days will be June 10-11, 2010 in Singapore, preceded by a Tutorial Day (June 9). (http://apac.pycon.org) Important Dates ----------------------- ? Call for Papers: August 15, 2009 ? Deadline for Paper Submissions: February 1, 2010 ? Notification of Paper Acceptance: March 15, 2010 ? Conference Registration Open: March 15, 2010 ? Submission of Camera-Ready Paper: April 15, 2010 ? Conference Days: June 10 - 11, 2010 (preceded by tutorials on the June 9, 2010) PyCon Topics -------------------- PyCon conferences worldwide have had a broad range of presentations, ranging from reports on academic and commercial projects to tutorials and case studies. We hope to continue that tradition here at PyCon Asia Pacific in Singapore. As long as the presentation is interesting and potentially useful to the Python community, it will be considered for inclusion in the program. We are especially interested in short presentations that will teach conference-goers something new and useful. Suitable topics for PyCon Asia Pacific 2010 presentations include, but are not limited to: ? Core Python and other implementations: IronPython, Jython, PyPy and Stackless. ? Python libraries and extensions ? Business Applications ? Databases ? Embedding and Extending Python ? Game Programming ? GUI Programming ? Network Programming ? Python in IT Security ? Open Source Python projects ? Packaging Issues ? Programming Tools ? Project Best Practices ? Python in Education, Science and Math ? System Administration ? Web Programming (Django, Zope, TurboGears, WSGI) Talk Format ----------------- The preferred length for talks is 30 minutes. Session lengths include time for audience questions. You should budget at least five minutes for questions; for example, a 30-minute talk will be 25 minutes of presentation and 5 minutes of questions. Open Space rooms will also be available for follow-up sessions. Proposal Submission ------------------------------- The primary author should submit a proposal, after which additional authors can be added. This is to help us make arrangements for reviewers and draft the conference programme. The proposal must include the following: ? Talk title. ? Choice of one or more category tag. ? Level. Indicate the intended audience difficulty level i.e. beginner, intermediate or advanced. ? Summary (max 100 words) for the website. ? Description : Detailed outline for review; notes for reviewers and permission for your talk to be recorded. Your proposal will be reviewed by the programme committee. If your proposal is accepted, you should thereafter include: ? a companion paper (up to 30 pages) OR ? an extended abstract (up to 3 pages) along with your presentation. Go to http://us.pycon.org/2008/conference/proposals/ example1/ for an example of a conference talk proposal. Please send your proposal (and any questions) to conference at pugs.org.sg. Companion Paper or Extended Abstract Submission ---------------------------------------------------------------------------- All presenters should submit a paper by the deadline above, with or without prior proposal submission. This submission is to be your full paper (companion paper or extended abstract), not a draft. It should contain all of the usual aspects of a paper such as an abstract, introduction, body and conclusion. Please ensure that this submission has had its grammar and spelling corrected and that code snippets work. Your paper will be peer-reviewed by the programme committee and a notice of paper acceptance with review comments will be sent to the author(s) on March 15, 2010. Accepted papers can be amended by the author(s), taking into account of reviewers' comments and submit for publication by April 15, 2010. ? All papers will be published in The Python Papers Monograph series (www.pythonpapers.org). We suggest, but do not require, all authors to place their papers under the Creative Commons license. ? Please see http://www.pythonpapers.org/instAuthor.html for the preferred formats of submission. ? Please submit your papers at http://ojs.pythonpapers.org/index.php/tppm/author. Your paper allows attendees who attended your talk a chance to refresh their memories about your presentation, and gives attendees who missed your talk a chance to learn from you anyway. Make sure your paper includes - at the very least - a brief introduction to your subject material and a list of further resources. Assistance ---------------- PyCon Asia Pacific 2010 in Singapore cannot offer payment or free registration to all conference speakers. However, financial aid will be available were possible, and giving a talk is a great rationale. If you require financial aid in order to attend PyCon Asia Pacific 2010 in Singapore, please note it in your proposal. If you have any questions, contact conference at pugs.org.sg. From wwn1 at sfu.ca Tue Aug 18 20:51:31 2009 From: wwn1 at sfu.ca (WilsonOfCanada) Date: Tue, 18 Aug 2009 17:51:31 -0700 (PDT) Subject: Raw Strings with Variables References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: However, when I send the list over as a dictionary for HTML: d["places"] = arrPlaces return render_to_response('rentSearch.html', d) the HTML using Django has: {{ places }} but returns ['C:\\moo', 'C:\\supermoo'] From clp2 at rebertia.com Tue Aug 18 21:00:56 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 18:00:56 -0700 Subject: Raw Strings with Variables In-Reply-To: References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: <50697b2c0908181800r62abeb00t9632b3f336e2e0c1@mail.gmail.com> On Tue, Aug 18, 2009 at 5:51 PM, WilsonOfCanada wrote: > However, when I send the list over as a dictionary for HTML: > > d["places"] = arrPlaces > > return render_to_response('rentSearch.html', d) > > the HTML using Django has: > > {{ places }} but returns ['C:\\moo', 'C:\\supermoo'] As we've explained already, containers (such as dictionaries and lists) use repr() to display their elements, and repr() for strings shows the escape sequences (e.g. \\ \t \n) and adds surrounding quotes. Hence the output you're getting. If you don't like the way it looks, then either send the list through a filter that outputs it like you want by accessing the elements individually, or iterate over the contents of the list in your template and output it like you want. Cheers, Chris -- http://blog.rebertia.com From http Tue Aug 18 21:07:25 2009 From: http (Paul Rubin) Date: 18 Aug 2009 18:07:25 -0700 Subject: Editing a wiki References: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> Message-ID: <7x1vn8har6.fsf@ruckus.brouhaha.com> KillSwitch writes: > Is it possible to edit a wiki page with python, including logging in > to edit the page, and inserting text into the edit box, etc. If you are talking about MediaWiki (the software behind Wikipedia), it already has an API for which there are several Python clients. See: http://www.mediawiki.org/wiki/API http://www.mediawiki.org/wiki/API:Client_Code If you are looking to use Python (or any other language) to automatically edit Wikipedia itself, you need approval for that. See: http://en.wikipedia.org/wiki/Wikipedia:Bot_policy From davea at ieee.org Tue Aug 18 21:07:27 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 18 Aug 2009 21:07:27 -0400 Subject: Start-up program In-Reply-To: <4A8ABA78.8050605@it.uu.se> References: <4A8ABA78.8050605@it.uu.se> Message-ID: <4A8B504F.8010307@ieee.org> Virgil Stokes wrote: >
How > difficult is to create a program that will be executed when Windows > Vista is started? As Windows Calendar does, for example. > > I am actually more interested in the Python tools that might be used > for this task. I hope that this question is not inappropriate for the > list. :-\ > > --V > > >
> The three responses I've seen probably aren't what you're asking. You have to make a distinction between when Windows starts, and when a user logs in. If you're interested in the point when the user logs in, all you need to do is make a shortcut for the script, no special executable is needed. Just put the shortcut in the Startup folder. But if you're really interested in the point when Windows starts, you have three options. Most painful is making a service. But that's unnecessary. Second way involves the system policy: HKLM\SOFTWARE\Policies\Microsoft|Windows\System\Scripts\ but anything started that way has a 10 minute time limit before it's automatically killed. Third, and easiest way is the task scheduler: Start Menu/All Programs/Accessories/System Tools/ScheduledTasks Add your program in with the scheduled task wizard. There are various scheduling choices, and one of them is called something like "boot". Again, you needn't make a separate EXE file, since Python.exe is already a perfectly valid one. It's likely that Vista has some security oddities, and I don't have any pointers for that. But even in XP, one thing you might need to do is "Fast Logon Optimization". It's enabled by default, but if somebody has turned it off, then logon might be blocked till your special script finishes. DaveA From davidshais at googlemail.com Tue Aug 18 21:12:39 2009 From: davidshais at googlemail.com (David) Date: Tue, 18 Aug 2009 18:12:39 -0700 (PDT) Subject: Scope and classes References: Message-ID: On Aug 19, 1:17?am, "Jan Kaliszewski" wrote: > 19-08-2009 o 02:10:58 Jan Kaliszewski wrote: > > > The only ways to reach Abc's attribute 'message' from that method are: > > * 'Abc.message' > > * 'self.__class__.message' > > * 'self.message' (unless there is an instance attribute 'message' which > > overrides the class attribute). > > And of course getattr(Abc), getattr(self.__class__) etc. :-) > > -- > Jan Kaliszewski (zuo) Out of 'Abc.message' and 'self.message', which is the favoured convention? It would be very easy to accidentally override 'self.messages' with an instance attribute! From ben+python at benfinney.id.au Tue Aug 18 21:22:32 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 11:22:32 +1000 Subject: Scope and classes References: Message-ID: <878whgfvhj.fsf@benfinney.id.au> David writes: > Out of 'Abc.message' and 'self.message', which is the favoured > convention? It's not a matter of convention. They mean different things, so you use each depending on what you mean. > It would be very easy to accidentally override 'self.messages' with an > instance attribute! Right. So you use ?Abc.message? when you specifically want a class independent of any instance, and you use ?self.message? when you want the attribute of this instance (with fallback to the usual resolution order). -- \ ?Any intelligent fool can make things bigger and more complex? | `\ It takes a touch of genius ? and a lot of courage ? to move in | _o__) the opposite direction.? ?Albert Einstein | Ben Finney From ben+python at benfinney.id.au Tue Aug 18 22:01:29 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 12:01:29 +1000 Subject: Scope and classes References: <878whgfvhj.fsf@benfinney.id.au> Message-ID: <874os4ftom.fsf@benfinney.id.au> Ben Finney writes: > Right. So you use ?Abc.message? when you specifically want a class > independent of any instance That's ?a class attribute independent of any instance?, of course. -- \ ?Humanity has advanced, when it has advanced, not because it | `\ has been sober, responsible, and cautious, but because it has | _o__) been playful, rebellious, and immature.? ?Tom Robbins | Ben Finney From gu.yakahughes at gmail.com Tue Aug 18 22:25:07 2009 From: gu.yakahughes at gmail.com (yaka) Date: Tue, 18 Aug 2009 19:25:07 -0700 (PDT) Subject: Editing a wiki References: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> <7x1vn8har6.fsf@ruckus.brouhaha.com> Message-ID: <85b24ce4-2cbb-402d-8027-f3025c795db0@r18g2000yqd.googlegroups.com> On Aug 18, 6:07?pm, Paul Rubin wrote: > KillSwitch writes: > > Is it possible to edit a wiki page with python, including logging in > > to edit the page, and inserting text into the edit box, etc. > > If you are talking about MediaWiki (the software behind Wikipedia), > it already has an API for which there are several Python clients. > See: > > ? ?http://www.mediawiki.org/wiki/API > ? ?http://www.mediawiki.org/wiki/API:Client_Code > > If you are looking to use Python (or any other language) to > automatically edit Wikipedia itself, you need approval for that. > See: > > ?http://en.wikipedia.org/wiki/Wikipedia:Bot_policy It's actually a wiki owned by a friend. From sjmachin at lexicon.net Tue Aug 18 22:32:14 2009 From: sjmachin at lexicon.net (John Machin) Date: Tue, 18 Aug 2009 19:32:14 -0700 (PDT) Subject: How do I convert an iterator over bytes into a str? References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> Message-ID: <9e60a01a-46e3-4aab-bbb0-845e4a08fb15@i8g2000pro.googlegroups.com> On Aug 19, 8:24?am, markscottwright wrote: > This does what I expected: > ? ? In [6]: list(iter([1,2,3,4,5])) > ? ? Out[6]: [1, 2, 3, 4, 5] > > But this appears to be doing a __repr__ rather than making me a nice > string: > ? ?In [7]: str(iter("four score and seven years ago")) > ? ?Out[7]: '' > > What's the correct way to turn an iterator over bytes into a string? > This works, but, ewww: > ? ? In [8]: "".join(iter("four score and seven years ago")) > ? ? Out[8]: 'four score and seven years ago' There is no such thing as an "iterator over bytes" in Python 2.x. There is no such concept as "convert an iterator over into a str" object. What you have is an iterator over str objects of length 1. To do what you appear to actually want to do (concatenate a bunch of strings), it is recomemnded to use ''.join(str_iterable). From pavlovevidence at gmail.com Tue Aug 18 23:02:34 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 18 Aug 2009 20:02:34 -0700 (PDT) Subject: How do I convert an iterator over bytes into a str? References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> Message-ID: On Aug 18, 3:24?pm, markscottwright wrote: > This does what I expected: > ? ? In [6]: list(iter([1,2,3,4,5])) > ? ? Out[6]: [1, 2, 3, 4, 5] > > But this appears to be doing a __repr__ rather than making me a nice > string: > ? ?In [7]: str(iter("four score and seven years ago")) > ? ?Out[7]: '' Unfortunately, str() is overloaded in that it tries to be both a sorta- pretty-printer and a constructor. You're trying to use it as a constructor, but it wants to be a sorta-pretty-printer here. Anyway, str is different from other container objects since, unlike other containers, strings can't contain arbitrary Python objects. > What's the correct way to turn an iterator over bytes into a string? > This works, but, ewww: > ? ? In [8]: "".join(iter("four score and seven years ago")) > ? ? Out[8]: 'four score and seven years ago' This is the correct way. If the syntax bothers you can always do this: str.join("",iter("four score")) I think "".join is ugly as hell but in this case convenience beats beauty for me. Carl Banks From grante at visi.com Tue Aug 18 23:23:34 2009 From: grante at visi.com (Grant Edwards) Date: Tue, 18 Aug 2009 22:23:34 -0500 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> Message-ID: On 2009-08-19, Ben Finney wrote: > Simon Forman writes: >> We are one family. > > Agreed. That's not much comfort if you've seen the way many families get along with each other. -- Grant From sajmikins at gmail.com Tue Aug 18 23:27:39 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 23:27:39 -0400 Subject: Inheriting dictionary In-Reply-To: <2fe6d216-1e8f-4de1-8c36-d4ee11bb7233@26g2000yqk.googlegroups.com> References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> <2fe6d216-1e8f-4de1-8c36-d4ee11bb7233@26g2000yqk.googlegroups.com> Message-ID: <50f98a4c0908182027j214c922dx3f82d6114c6eda3a@mail.gmail.com> On Tue, Aug 18, 2009 at 6:08 PM, Simon Forman wrote: > On Aug 18, 3:44?pm, Pavel Panchekha wrote: >> I want a dictionary that will transparently "inherit" from a parent >> dictionary. So, for example: >> >> """ >> a = InheritDict({1: "one", 2: "two", 4: "four"}) >> b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) >> >> a[1] # "one" >> a[4] # "four" >> b[1] # "one" >> b[3] # "three" >> b[4] # "foobar" >> """ >> >> I've written something like this in Python already, but I'm wondering >> if something like this already exists, preferably written in C, for >> speed. > > > I would consider something like the following: > > > a = {1: "one", 2: "two", 4: "four"} > b = {3: "three", 4: "foobar"} > > > from functools import partial > > > def getter(first, second, key): > ? ?try: > ? ? ? ?return first(key) > ? ?except KeyError: > ? ? ? ?return second(key) > > > f = partial(getter, b.__getitem__, a.__getitem__) > > > # Or, if you know you'll be getting a lot of KeyErrors, you > # can use get() instead of __getitem__(). > > def getter1(first, second, key, sentinel=None): > ? ?item = first(key, sentinel) > ? ?if item is sentinel: > ? ? ? ?item = second(key) > ? ?return item > > g = partial(getter1, b.get, a.__getitem__) > > > HTH, > ~Simon > -- > http://mail.python.org/mailman/listinfo/python-list > Since you're going for speed the overhead of using partial (which creates a wrapper object around the getter function) can be replaced by something like this: def makeGetter(first, second): def getter(key): try: return first(key) except KeyError: return second(key) return getter f = makeGetter(b.__getitem__, a.__getitem__) From sajmikins at gmail.com Tue Aug 18 23:43:48 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 23:43:48 -0400 Subject: Need cleanup advice for multiline string In-Reply-To: <0014c4c0$0$2963$c3e8da3@news.astraweb.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <0014c4c0$0$2963$c3e8da3@news.astraweb.com> Message-ID: <50f98a4c0908182043i8a619fdydb9311eadf7cef9@mail.gmail.com> On Tue, Aug 18, 2009 at 8:03 PM, Steven D'Aprano wrote: > On Tue, 18 Aug 2009 17:13:02 -0400, Simon Forman wrote: > >> Sexism, racism, homophobia, religious intolerance, etc., all stem from a >> fundamental forgetfulness of our Unity in God (as I would put it) and > > Of the tens of thousands of Gods that people have invented, which is the > one we're supposed to believe in? I always forget which ones we're > supposed to dismiss as nonsense, and which one we're not. Why the heck are you asking me? (I'd say "/you/ are the God you should believe in.") >> this is perhaps the single greatest cause of human misery. > > Okay, we're Unified in God. Great. What does that actually mean, really? > In the struggle to survive in a world of shortages, disease, natural > disasters and disputes between well-meaning but incompatible viewpoints > (to say nothing of the selfish and greedy), what practical difference > does it make? It means (to me, at least) that underlying all the BS and misery there's a reason to hope, a reality the transcends this squalid mud-ball Earth, and can overcome it completely if tapped. It's more than a symbol with meaning, Unity is a phenomenon that can be lived, experienced. It can be practiced and deepened. Done well, the practical difference it makes defies measurement. (That's why calling folks on sexist behavior is important enough to butt in on a thread on usenet with an OT reprimand. IMHO) Regards, ~Simon From ben+python at benfinney.id.au Tue Aug 18 23:49:12 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 13:49:12 +1000 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> Message-ID: <87vdkkea4n.fsf@benfinney.id.au> Grant Edwards writes: > On 2009-08-19, Ben Finney wrote: > > Simon Forman writes: > >> We are one family. > > > > Agreed. > > That's not much comfort if you've seen the way many families get along > with each other. Demonstrable facts, by nature of being independently verifiable, are a better point of unification than comforting illusions, however confidently asserted. -- \ ?Life does not cease to be funny when people die any more than | `\ it ceases to be serious when people laugh.? ?George Bernard Shaw | _o__) | Ben Finney From sajmikins at gmail.com Tue Aug 18 23:49:45 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 23:49:45 -0400 Subject: Need cleanup advice for multiline string In-Reply-To: <87hbw4fxcq.fsf@benfinney.id.au> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> Message-ID: <50f98a4c0908182049t63322bbiebf53065562cb2@mail.gmail.com> On Tue, Aug 18, 2009 at 8:42 PM, Ben Finney wrote: > Simon Forman writes: > >> Sexism, racism, homophobia, religious intolerance, etc., all stem from >> a fundamental forgetfulness of our Unity in God (as I would put it) > > It seems odd, for someone who cites religious intolerance as a problem, > to then assert an extremely divisive religious idea. Well, I did say, "(as I would put it)" to try to cushion the blow. > We're all unified by our humanity. Bringing any god into the picture is > surely counter to any goals of unity. Unity "in humanity" is, to my way of thinking, the same as Unity "in God". I think Unity, like None, is a built-in singleton, so to speak. >> We are one family. > > Agreed. <3 From ben+python at benfinney.id.au Wed Aug 19 00:05:53 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 14:05:53 +1000 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> Message-ID: <87r5v8e9cu.fsf@benfinney.id.au> Simon Forman writes: > On Tue, Aug 18, 2009 at 8:42 PM, Ben Finney wrote: > > We're all unified by our humanity. Bringing any god into the picture > > is surely counter to any goals of unity. > > Unity "in humanity" is, to my way of thinking, the same as Unity "in > God". Then you're playing Humpty-Dumpty games with words. You know very well that ?God? has established meanings entirely different from ?humanity?, and those meanings played a part in your choice of that word. I maintain that you can't consistently make a declaration in favour of human unity and unfounded religious assertions. > I think Unity, like None, is a built-in singleton, so to speak. This is white noise. > >> We are one family. > > > > Agreed. > > <3 I think we can peaceably leave it at that. -- \ ?Spam will be a thing of the past in two years' time.? ?Bill | `\ Gates, 2004-01-24 | _o__) | Ben Finney From pavlovevidence at gmail.com Wed Aug 19 00:14:05 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 18 Aug 2009 21:14:05 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> <87vdkkea4n.fsf@benfinney.id.au> Message-ID: On Aug 18, 8:49?pm, Ben Finney wrote: > Grant Edwards writes: > > On 2009-08-19, Ben Finney wrote: > > > Simon Forman writes: > > >> We are one family. > > > > Agreed. > > > That's not much comfort if you've seen the way many families get along > > with each other. > > Demonstrable facts, by nature of being independently verifiable, are a > better point of unification than comforting illusions, however > confidently asserted. You know, if you're going to escalate a budding flame war the least you could do is to choose to do it some other way than by following up to an obvious joke, probably one designed to diffuse the ill-feeling. Carl Banks From mensanator at aol.com Wed Aug 19 00:37:04 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 18 Aug 2009 21:37:04 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <4A89CEA2.10400@mrabarnett.plus.com> <0014291d$0$2963$c3e8da3@news.astraweb.com> Message-ID: <58ea46ae-0ad0-4d63-b3ba-7ed693a2b381@d32g2000yqh.googlegroups.com> On Aug 18, 7:59?am, Steven D'Aprano wrote: > On Tue, 18 Aug 2009 13:36:49 +0200, Jean-Michel Pichavant wrote: > > MRAB wrote: > >> Carl Banks wrote: > >>> On Aug 17, 10:03 am, Jean-Michel Pichavant > >>> wrote: > >>>> I'm no English native, but I already heard women/men referring to a > >>>> group as "guys", no matter that group gender configuration. It's even > >>>> used for group composed exclusively of women. Moreover it looks like > >>>> a *very* friendly form, so there is really nothing to worry about it. > > >>> I like how being very friendly means calling people after a guy who > >>> tried to blow up the English Parliament. > > >> Guy Fawkes adopted the name Guido while fighting for the Spanish in the > >> Low Countries: > > >>http://en.wikipedia.org/wiki/Guy_Fawkes > > > I didn't get Carl's reference. The only thing I know about blowing the > > parliament is from the movie V for Vendetta (no comment please !). Now > > thanks to your link: > > "In 18th-century England, the term "guy" was used to refer to an effigy > > of Fawkes, which would be paraded > > around town by children on the anniversary of the conspiracy" > > > Well, my knowledge is much too low to get this kind of reference from > > the start. :-/ > > "Guy" is an old English name, related to the old French name "Gy" and > Italian "Guido". It's originally derived from the Old German for "wood" > or "warrior". > > After Guy Fawkes tried to blow up the English Parliament house, and was > executed, the British government encouraged people to burn effigies of > him. These became known as "guys", which eventually became slang for an > ugly man, which later became slang for any man, and in recent years, any > person. > > So the irony is that the friendly term "guys", referring to a group of > people, is derived from the name of an 18th century You're off by at least a century. > religious terrorist. As were all members of parliament including the king. > > One can only wonder whether in 200 years time people will walk into the > office and say "Hey you osamas, they're giving away free donuts down > stairs, anyone want some?" Q: What's white and flies across the ocean? A: Lord Mountbatten's tennis shoes. Ain't so fuckin' funny, is it? (Unless you're Irish, in which case it's hysterical). > > -- > Steven From gallium.arsenide at gmail.com Wed Aug 19 00:44:01 2009 From: gallium.arsenide at gmail.com (John Yeung) Date: Tue, 18 Aug 2009 21:44:01 -0700 (PDT) Subject: Code formatting question: conditional expression References: Message-ID: On Aug 18, 1:25?pm, John Posner wrote: > BTW, from the (admittedly few) responses to my original > post, it seems there's some sentiment that "conditional > expressions" are a non-Pythonic misfeature. Interesting ... Well, it's not like Guido was especially eager to add it in the first place. I personally wouldn't call it a misfeature, but it shares with lambda the property that it's best used when what you need to say with it is very short. John Y. From mensanator at aol.com Wed Aug 19 00:52:43 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 18 Aug 2009 21:52:43 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> <86bb893a-344a-4c7b-9fc6-67d9f42c7607@q14g2000vbi.googlegroups.com> Message-ID: <62dbf088-4510-40d0-af3e-3feeb291d6e4@t13g2000yqt.googlegroups.com> On Aug 17, 11:35?pm, Carl Banks wrote: > On Aug 17, 8:49?pm, Mensanator wrote: > > > > > > > On Aug 17, 8:04 pm, Carl Banks wrote: > > > > On Aug 17, 5:40 pm, Mensanator wrote: > > > > > On Aug 17, 4:06 pm, Carl Banks wrote: > > > > > > On Aug 17, 10:03 am, Jean-Michel Pichavant > > > > > wrote: > > > > > > > I'm no English native, but I already heard women/men referring to a > > > > > > group as "guys", no matter that group gender configuration. It's even > > > > > > used for group composed exclusively of women. Moreover it looks like a > > > > > > *very* friendly form, so there is really nothing to worry about it. > > > > > > I like how being very friendly means calling people after a guy who > > > > > tried to blow up the English Parliament. > > > > > So? > > > > I also like how making an amusing pointless observation > > > Pointless, yes, but what was amusing abot the observation? > > The irony that in being friendly that you're calling someone a > terrorist. ? People of Irish Catholic heritage find that extremely offensive, like asking how many Jews you can fit into a Volswagen. > I guess I shouldn't have expected you to get it. Oh, I got it alright, moreso than you could possibly imagine. > > > > gets people all huffy. > > > That wasn't huffy. You want to see huffy, make a wisecrack > > comparing mothballs to Zyklon B, you'll REALLY get a load > > of huffy replies. > > > > (BTW, lest anyone is not aware, that is the origin of the word "guy", > > > It most certainly is not. > > My dictionary disagrees with you. hen yor dictionary is wrong. Or, more likely, you have comprehension problems. People have been named "Guy" for centuries prior to Mr. Fawkes. Try reading my whole post before shouting your mouth off. > > > Maybe the origin of that > > word's useage as a genric reference to a male, but > > you didn't say that. > > > > this was not some random association.) > > > Penny for the guy? > > Probably that phrase was part of the word's gradual common adoption. Kinda why I mentioned it. Duh. > > Carl Banks From mensanator at aol.com Wed Aug 19 01:07:09 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 18 Aug 2009 22:07:09 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <4A89CEA2.10400@mrabarnett.plus.com> Message-ID: On Aug 18, 6:36?am, Jean-Michel Pichavant wrote: > MRAB wrote: > > Carl Banks wrote: > >> On Aug 17, 10:03 am, Jean-Michel Pichavant > >> wrote: > >>> I'm no English native, but I already heard women/men referring to a > >>> group as "guys", no matter that group gender configuration. It's even > >>> used for group composed exclusively of women. Moreover it looks like a > >>> *very* friendly form, so there is really nothing to worry about it. > > >> I like how being very friendly means calling people after a guy who > >> tried to blow up the English Parliament. > > > Guy Fawkes adopted the name Guido while fighting for the Spanish in the > > Low Countries: > > >http://en.wikipedia.org/wiki/Guy_Fawkes > > I didn't get Carl's reference. The only thing I know about blowing the > parliament is from the movie V for Vendetta (no comment please !). > Now thanks to your link: > "In 18th-century England, the term "guy" was used to refer to an effigy > of Fawkes, which would be paraded > around town by children on the anniversary of the conspiracy" > > Well, my knowledge is much too low to get this kind of reference from > the start. :-/ So I guess you have no clue WHY Mr. Fawkes would want to blow up the parliment and assassinate the king. Read up a bit on how just how the Church of England came to be and it will be quite obvious. On some TV show, someone did a re-creation of that event to see what would have happened had he not gotten caught. They built a life-size mockuup of the room under which the gunpowder kegs were stashed and filled the room with dummys. The blast was spectacular. They eventually found the head of the dummy representing king James a couple miles away. Or maybe it was kilometers. Either way, the conclusion was it was very lucky to have worked out the way it did. > > JM From greg at cosc.canterbury.ac.nz Wed Aug 19 02:07:13 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 19 Aug 2009 18:07:13 +1200 Subject: Changing Python Opcodes In-Reply-To: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> References: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> Message-ID: <7f1j3gF2hsc2hU1@mid.individual.net> Sreejith K wrote: > I know this is not the best way to do it. But I have to do it at least > to make it *hard* to decompile the python bytecode. > So I compiled Python from source changing some opcode values It probably wouldn't be all that hard for someone to figure this out. A possible avenue of attack would be to use your python to compile a known piece of code that exercises all the opcodes, and compare the result with that from a standard python. -- Greg From sakib.iqbal at gmail.com Wed Aug 19 02:08:49 2009 From: sakib.iqbal at gmail.com (Sakib) Date: Tue, 18 Aug 2009 23:08:49 -0700 (PDT) Subject: can't retrieve data from pyxml Message-ID: <64baa6b4-2cd7-451e-a749-9fdca8c62d2c@k19g2000yqn.googlegroups.com> well, i need to retrive data from the following line of xml. i need the Caption and the type data. is any one out there help me doing that? thanks, Sakib From greg at cosc.canterbury.ac.nz Wed Aug 19 02:11:43 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 19 Aug 2009 18:11:43 +1200 Subject: define class over 2 files In-Reply-To: <6a490ec8-3536-4508-afd4-90a5cf9317b5@g10g2000yqh.googlegroups.com> References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> <6a490ec8-3536-4508-afd4-90a5cf9317b5@g10g2000yqh.googlegroups.com> Message-ID: <7f1jbuF2ifjr1U1@mid.individual.net> naveen wrote: >>>Is it possible to split up a class definition over multiple files? >> >>Not exactly, but you can do variations of this: > > ... [subclass a class] Multiple inheritance can also be useful: # A_Part1.py class A_Part1: ... # A_Part2.py class A_Part2: ... # A.py from A_Part1 import A_Part1 from A_Part2 import A_Part2 class A(A_Part1, A_Part2): ... -- Greg From danb_83 at yahoo.com Wed Aug 19 02:17:55 2009 From: danb_83 at yahoo.com (AggieDan04) Date: Tue, 18 Aug 2009 23:17:55 -0700 (PDT) Subject: Read C++ enum in python References: <4a8b3342$0$25403$426a34cc@news.free.fr> Message-ID: On Aug 18, 6:03?pm, Ludo wrote: > Hello, > > I work in a very large project where we have C++ packages and pieces of > python code. > > I've been googleing for days but what I find seems really too > complicated for what I want to do. > > My business is, in python, to read enum definitions provided by the > header file of an c++ package. > Of course I could open the .h file, read the enum and transcode it by > hand into a .py file but the package is regularly updated and thus is > the enum. > > My question is then simple : do we have : > ? ? ? ? - either a simple way in python to read the .h file, retrieve the c++ > enum and provide an access to it in my python script Try something like this: file_data = open(filename).read() # Remove comments and preprocessor directives file_data = ' '.join(line.split('//')[0].split('#')[0] for line in file_data.splitlines()) file_data = ' '.join(re.split(r'\/\*.*\*\/', file_data)) # Look for enums: In the first { } block after the keyword "enum" enums = [text.split('{')[1].split('}')[0] for text in re.split(r'\benum \b', file_data)[1:]] for enum in enums: last_value = -1 for enum_name in enum.split(','): if '=' in enum_name: enum_name, enum_value = enum_name.split('=') enum_value = int(enum_value, 0) else: enum_value = last_value + 1 last_value = enum_value enum_name = enum_name.strip() print '%s = %d' % (enum_name, enum_value) print From stefan_ml at behnel.de Wed Aug 19 02:42:59 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 19 Aug 2009 08:42:59 +0200 Subject: Parallelization in Python 2.6 In-Reply-To: References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> Message-ID: <4a8b9ef4$0$31865$9b4e6d93@newsspool3.arcor-online.net> Dennis Lee Bieber wrote: > On Tue, 18 Aug 2009 13:45:38 -0700 (PDT), Robert Dailey wrote: >> Really, all I'm trying to do is the most trivial type of >> parallelization. Take two functions, execute them in parallel. This >> type of parallelization is called "embarrassingly parallel", and is >> the simplest form. There are no dependencies between the two >> functions. They do requires read-only access to shared data, though. >> And if they are being spawned as sub-processes this could cause >> problems, unless the multiprocess module creates pipelines or other >> means to handle this situation. It wouldn't be much worth if it didn't, as the subprocess module handles everything else nicely. See the Queue classes. > If they are number crunchers (CPU-bound) and don't make use of > binary extension libraries that release the GIL (for the most common > Python implementation), they'll run faster being called in sequence > since you won't have the overhead of task switching. ... unless, obviously, the hardware is somewhat up to date (which is not that uncommon for number crunching environments) and can execute more than one thing at once. Stefan From deets at nospam.web.de Wed Aug 19 02:56:11 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 08:56:11 +0200 Subject: recording input from USB port and write to text file In-Reply-To: References: Message-ID: <7f1m0bF2iv0uuU1@mid.uni-berlin.de> Allan schrieb: > Hi! I'm fairly new to Python. I understand the basics basics but I'm > been trying to write a simple python code that will let me read input > data (such as mouse movement) from my USB port and write it in a text > file and I am so lost. Can anyone help or direct me to some > resources? Thank you! This isn't as easy as you think. And dependend on your operating-system. Diez From deets at nospam.web.de Wed Aug 19 03:01:45 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 09:01:45 +0200 Subject: can't retrieve data from pyxml In-Reply-To: <64baa6b4-2cd7-451e-a749-9fdca8c62d2c@k19g2000yqn.googlegroups.com> References: <64baa6b4-2cd7-451e-a749-9fdca8c62d2c@k19g2000yqn.googlegroups.com> Message-ID: <7f1mapF2iv0uuU2@mid.uni-berlin.de> Sakib schrieb: > well, i need to retrive data from the following line of xml. > > msdata:Caption="Microtia" type="xs:string" minOccurs="0" /> > > i need the Caption and the type data. > > is any one out there help me doing that? That's not XML. It lacks namespace-declarations. So no XML-parser will (or should) grok it. Also, to get help here it's better to show what you already tried, instead of simply asking others to do your work for you. Diez From hendrik at microcorp.co.za Wed Aug 19 03:03:49 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 19 Aug 2009 09:03:49 +0200 Subject: Diversity in Python In-Reply-To: <8763cliez7.fsf@benfinney.id.au> References: <8763cliez7.fsf@benfinney.id.au> Message-ID: <200908190903.49977.hendrik@microcorp.co.za> On Tuesday 18 August 2009 12:38:36 Ben Finney wrote: > Hendrik van Rooyen writes: > > On Tuesday 18 August 2009 06:45:39 Aahz wrote: > > > Mainly an opportunity to flog the new diversity list. > > > > Here my English fails me - flog as in "whip", or flog as in "sell"? > > Yes :-) Thank you that clears it up. :-) - Hendrik From hendrik at microcorp.co.za Wed Aug 19 03:24:13 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 19 Aug 2009 09:24:13 +0200 Subject: Inheriting dictionary In-Reply-To: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: <200908190924.13792.hendrik@microcorp.co.za> On Tuesday 18 August 2009 21:44:55 Pavel Panchekha wrote: > I want a dictionary that will transparently "inherit" from a parent > dictionary. So, for example: > > """ > a = InheritDict({1: "one", 2: "two", 4: "four"}) > b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) > > a[1] # "one" > a[4] # "four" > b[1] # "one" > b[3] # "three" > b[4] # "foobar" > """ > > I've written something like this in Python already, but I'm wondering > if something like this already exists, preferably written in C, for > speed. Its not inheritance, but have you looked at the update method? -Hendrik From metolone+gmane at gmail.com Wed Aug 19 03:28:15 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Wed, 19 Aug 2009 00:28:15 -0700 Subject: Read C++ enum in python References: <4a8b3342$0$25403$426a34cc@news.free.fr> <4A8B3E2D.7040702@mrabarnett.plus.com> Message-ID: "MRAB" wrote in message news:4A8B3E2D.7040702 at mrabarnett.plus.com... > Ludo wrote: >> Hello, >> >> I work in a very large project where we have C++ packages and pieces of >> python code. >> >> I've been googleing for days but what I find seems really too complicated >> for what I want to do. >> >> My business is, in python, to read enum definitions provided by the >> header file of an c++ package. >> Of course I could open the .h file, read the enum and transcode it by >> hand into a .py file but the package is regularly updated and thus is the >> enum. >> >> My question is then simple : do we have : >> - either a simple way in python to read the .h file, retrieve the c++ >> enum and provide an access to it in my python script >> - either a simple tool (in a long-term it would be automatically run >> when the c++ package is compiled) generating from the .h file a .py file >> containing the python definition of the enums ? >> >> Thank you for any suggestion. > > Speaking personally, I'd parse the .h file using a regular expression > (re module) and generate a .py file. Compilers typically have a way of > letting you run external scripts (eg batch files in Windows or, in this > case, a Python script) when an application is compiled. This is what 3rd party library pyparsing is great for: --------begin code---------- from pyparsing import * # sample string with enums and other stuff sample = ''' stuff before enum hello { Zero, One, Two, Three, Five=5, Six, Ten=10 } in the middle enum blah { alpha, beta, gamma = 10 , zeta = 50 } at the end ''' # syntax we don't want to see in the final parse tree _lcurl = Suppress('{') _rcurl = Suppress('}') _equal = Suppress('=') _comma = Suppress(',') _enum = Suppress('enum') identifier = Word(alphas,alphanums+'_') integer = Word(nums) enumValue = Group(identifier('name') + Optional(_equal + integer('value'))) enumList = Group(enumValue + ZeroOrMore(_comma + enumValue)) enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl # find instances of enums ignoring other syntax for item,start,stop in enum.scanString(sample): id = 0 for entry in item.list: if entry.value != '': id = int(entry.value) print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id) id += 1 --------------end code------------ Output: HELLO_ZERO = 0 HELLO_ONE = 1 HELLO_TWO = 2 HELLO_THREE = 3 HELLO_FIVE = 5 HELLO_SIX = 6 HELLO_TEN = 10 BLAH_ALPHA = 0 BLAH_BETA = 1 BLAH_GAMMA = 10 BLAH_ZETA = 50 -Mark From hendrik at microcorp.co.za Wed Aug 19 03:31:18 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 19 Aug 2009 09:31:18 +0200 Subject: Parallelization in Python 2.6 In-Reply-To: <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> Message-ID: <200908190931.18297.hendrik@microcorp.co.za> On Tuesday 18 August 2009 22:45:38 Robert Dailey wrote: > Really, all I'm trying to do is the most trivial type of > parallelization. Take two functions, execute them in parallel. This > type of parallelization is called "embarrassingly parallel", and is > the simplest form. There are no dependencies between the two > functions. They do requires read-only access to shared data, though. > And if they are being spawned as sub-processes this could cause > problems, unless the multiprocess module creates pipelines or other > means to handle this situation. Just use thread then and thread.start_new_thread. It just works. - Hendrik From gabriel.rossetti at arimaz.com Wed Aug 19 03:34:52 2009 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 19 Aug 2009 09:34:52 +0200 Subject: socket bug or not? Message-ID: <4A8BAB1C.7090700@arimaz.com> Hello everyone, I found what was not working in my code (see Twisted mailing list topics "self.socket.accept() in doRead() in tcp.py has (11, 'Resource temporarily unavailable') error", "Twisted, PushProducer, Words & big msgs, any limit?" and Python mailing list topic "socket.send : (11, 'Resource temporarily unavailable')"). I was just wondering if this was a bug or not, so here it is, I wrote aserver using twisted words' xmlstream class. When a client connects, it sends "" and the server also sends it, so a bi-directional xmlstream communication is established. This works fine, I at some point wrote a webservice to send msgs to my system, not using any twisted code, that sends a message to my server in this format : ".....". This worked fine as long as the messages were small, but if it send larger msgs (I tried +128k msgs) the server only received part of the msg and then the parser died because of this, so my msg appeared to be dropped. I discovered that it was because my webservice did not read the "" element sent by the server when it connected (since I was not interested in having a bidirectional xml stream communication with it), when I added the code to read it, everything worked as expected. I tested the webservice to without the server to see if it had a problem, using netcat, and it does, so I wonder if there is a bug in the socket code or not. Here is the test code : ###################### Listing 1 Start ###################### import socket, time STREAM_START = "" STREAM_END = "" def sendTestMessage(host, port): msg = "" + ('a' * 175177) + "" burstSize = 4096 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.send(STREAM_START) time.sleep(5) while msg: sent = sock.send(msg[:burstSize]) print "Sending %d bytes..." % sent if sent == 0: raise RuntimeError, "socket connection broken" msg = msg[burstSize:] sock.send(STREAM_END) sock.close() ###################### Listing 1 End ###################### To test it: 1) open a python interpretor, copy-past the code above 2) open another terminal and run netcat using the following command : nc -v -l -p 4444 3) call the above function using : sendTestMessage("localhost", 4444), it will wait 5 seconds after having sent the , for the first test, just wait. The message will be completely send and received by the netcat "server", now let's test the case I have, where the server sends a , to do that, repeat the above steps (you have to re-run netcat as it exits when the client disconnects), except in step 3 instead of just waiting, type and press enter in the netcat terminal after having received the element from the sending code. This time you will see that the message is incomplete. If you send a smaller message, like by replacing the following line : msg = "" + ('a' * 175177) + "" with : msg = "" + ('a' * (175177/4)) + "" it works in both cases. Now test the "fixed" code : ###################### Listing 2 Start ###################### import socket STREAM_START = "" STREAM_END = "" def sendTestMessage(host, port): msg = "" + ('a' * 175177) + "" burstSize = 4096 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.send(STREAM_START) sock.recv(len(STREAM_START)+1) while msg: sent = sock.send(msg[:burstSize]) print "Sending %d bytes..." % sent if sent == 0: raise RuntimeError, "socket connection broken" msg = msg[burstSize:] sock.send(STREAM_END) sock.close() ###################### Listing 2 End ###################### This time the code reads for the element after sending the element so it works, just try the steps described above, the ones where you have to type and press enter in the netcat terminal and this time it works. Is this a bug in the sockets code, or is this normal? If it's normal I think it should be mentioned somewhere. Oh, by the way, I use linux and this code was tested only on linux, I don't know if the problem also occurs on other platforms. Gabriel From digisatori at gmail.com Wed Aug 19 03:57:44 2009 From: digisatori at gmail.com (digisatori at gmail.com) Date: Wed, 19 Aug 2009 00:57:44 -0700 (PDT) Subject: expandtabs acts unexpectedly Message-ID: <7e598693-c248-4304-bc46-ac79a8a3969b@t11g2000prh.googlegroups.com> Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ' test\ttest'.expandtabs(4) ' test test' >>> 'test \ttest'.expandtabs(4) 'test test' 1st example: expect returning 4 spaces between 'test', 3 spaces returned 2nd example: expect returning 5 spaces between 'test', 4 spaces returned Is it a bug or something, please advice. From contact at xavierho.com Wed Aug 19 04:10:49 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 19 Aug 2009 18:10:49 +1000 Subject: expandtabs acts unexpectedly In-Reply-To: <7e598693-c248-4304-bc46-ac79a8a3969b@t11g2000prh.googlegroups.com> References: <7e598693-c248-4304-bc46-ac79a8a3969b@t11g2000prh.googlegroups.com> Message-ID: <2d56febf0908190110o57d6b345xc2010dd14f5d503a@mail.gmail.com> On Wed, Aug 19, 2009 at 5:57 PM, digisatori at gmail.com wrote: > Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> ' test\ttest'.expandtabs(4) > ' test test' > >>> 'test \ttest'.expandtabs(4) > 'test test' > > Is it a bug or something, please advice. > -- It is completely working as intended. What were you expecting instead? Regards, -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From nyamatongwe+thunder at gmail.com Wed Aug 19 04:12:48 2009 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 19 Aug 2009 08:12:48 GMT Subject: Read C++ enum in python In-Reply-To: References: <4a8b3342$0$25403$426a34cc@news.free.fr> Message-ID: <4uOim.12753$ze1.6481@news-server.bigpond.net.au> AggieDan04: > file_data = open(filename).read() > # Remove comments and preprocessor directives > file_data = ' '.join(line.split('//')[0].split('#')[0] for line in > file_data.splitlines()) > file_data = ' '.join(re.split(r'\/\*.*\*\/', file_data)) For some headers I tried it didn't work until the .* was changed to a non-greedy .*? to avoid removing from the start of the first comment to the end of the last comment. file_data = ' '.join(re.split(r'\/\*.*?\*\/', file_data)) Neil From http Wed Aug 19 04:13:41 2009 From: http (Paul Rubin) Date: 19 Aug 2009 01:13:41 -0700 Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> Message-ID: <7xbpmcnruy.fsf@ruckus.brouhaha.com> Hendrik van Rooyen writes: > Just use thread then and thread.start_new_thread. > It just works. The GIL doesn't apply to threads made like that?! From peter at peter-b.co.uk Wed Aug 19 04:16:35 2009 From: peter at peter-b.co.uk (Peter Brett) Date: Wed, 19 Aug 2009 09:16:35 +0100 Subject: expandtabs acts unexpectedly References: <7e598693-c248-4304-bc46-ac79a8a3969b@t11g2000prh.googlegroups.com> Message-ID: "digisatori at gmail.com" writes: > Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> ' test\ttest'.expandtabs(4) > ' test test' >>>> 'test \ttest'.expandtabs(4) > 'test test' > > 1st example: expect returning 4 spaces between 'test', 3 spaces > returned > 2nd example: expect returning 5 spaces between 'test', 4 spaces > returned > > Is it a bug or something, please advice. Consider where the 4-space tabstops are relative to those strings: test test test test ^ ^ ^ So no, it's not a bug. If you just want to replace the tab characters by spaces, use: >>> " test\ttest".replace("\t", " ") ' test test' >>> "test \ttest".replace("\t", " ") 'test test' HTH, Peter -- Peter Brett Remote Sensing Research Group Surrey Space Centre From user at example.net Wed Aug 19 04:40:28 2009 From: user at example.net (superpollo) Date: Wed, 19 Aug 2009 10:40:28 +0200 Subject: reading a text file Message-ID: <4a8bba7d$0$40004$4fafbaef@reader3.news.tin.it> hi clp what's the difference between: while True: input_line = sys.stdin.readline() if input_line: sys.stdout.write(input_line.upper()) else: break and: while True: try: sys.stdout.write(sys.stdin.next().upper()) except StopIteration: break ??? From http Wed Aug 19 04:46:16 2009 From: http (Paul Rubin) Date: 19 Aug 2009 01:46:16 -0700 Subject: reading a text file References: <4a8bba7d$0$40004$4fafbaef@reader3.news.tin.it> Message-ID: <7xocqci42v.fsf@ruckus.brouhaha.com> superpollo writes: > while True: > try: > sys.stdout.write(sys.stdin.next().upper()) > except StopIteration: > break Maybe there is some subtle difference, but it looks like you really mean for line in sys.stdin: sys.stdout.write(line.upper()) From pierre.gaillard at gmail.com Wed Aug 19 04:48:43 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Wed, 19 Aug 2009 01:48:43 -0700 (PDT) Subject: difference between 2 arrays Message-ID: Hello, I would like to know how to find the difference (set operation) between 2 arrays : a = array([1,2, 3,2,5,2]) b = array([1,2]) I want a - b = [3,5] Well, the equivalence of setdiff in matlab... I thought a.difference(b) could work, but no : AttributeError: 'numpy.ndarray' object has no attribute 'difference' Thanks ! From deets at nospam.web.de Wed Aug 19 04:52:13 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 10:52:13 +0200 Subject: Code formatting question: conditional expression References: Message-ID: <7f1sptF2gcfgnU1@mid.uni-berlin.de> > BTW, from the (admittedly few) responses to my original post, it seems > there's some sentiment that "conditional expressions" are a non-Pythonic > misfeature. Interesting ... No. I love them. But not if they are so large that they stretch over several lines (or to many columns). foo = bar if cond else baz is more than fine for me. But foo = I_need_to_do_something_really_complicated_here() if cond else baz isn't, because one doesn't grasp as easily in one look that we're talking a ternary operator here. Diez From james.harris.1 at googlemail.com Wed Aug 19 04:52:22 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Wed, 19 Aug 2009 01:52:22 -0700 (PDT) Subject: Identifying a class type - bad practice? References: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> Message-ID: <520f55a6-38ac-432b-97e7-ec327740645a@o6g2000yqj.googlegroups.com> On 18 Aug, 21:50, Chris Rebert wrote: > On Tue, Aug 18, 2009 at 10:09 AM, James > > Harris wrote: > > I am writing some code to form a tree of nodes of different types. The > > idea is to define one class per node type such as > > > class node_type_1(node): > > ? > > class node_type_2(node): > > ? > > etc > > > (Class "node" would hold any common properties). > > > When walking the tree I need to know what type of node I'm dealing > > with so polymorphism isn't generally useful. The action to be taken > > depends on the node type. > > I'm sure it relates to the exact type of tree you're walking and the > calculation you're doing on it, but what is the reason why your code, > which in the abstract sounds like it will vaguely resemble this: > > def walk_tree(tree): > ? ? if isinstance(tree, node_type_1): > ? ? ? ? #code > ? ? ? ? walk_tree(subtree) > ? ? elif isinstance(tree, node_type_2): > ? ? ? ? #code > ? ? ? ? walk_tree(subtree) > ? ? #etc... > > can't be written instead as: > > class node_type_1: > ? ? def walk_tree(self): > ? ? ? ? #code > ? ? ? ? self.subtree.walk() > > class node_type_2: > ? ? def walk_tree(self): > ? ? ? ? #code > ? ? ? ? self.subtree.walk() > > #etc Interesting idea. This may be a better and a more OO solution than what I had in mind. I'm not sure if I can use this but I'll see how it fits in as the work progresses. The tree is for a compiler. Initially the tree is for parsing of source code. Then it will need to be processed and changed as further compiler phases are written. I don't know yet whether it will be easier to modify the tree or to create a new one for each phase. So I guess whether I use the idea depends on the commonality of operations. James From deets at nospam.web.de Wed Aug 19 04:54:16 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 10:54:16 +0200 Subject: difference between 2 arrays References: Message-ID: <7f1stoF2gcfgnU2@mid.uni-berlin.de> Pierre wrote: > Hello, > > I would like to know how to find the difference (set operation) > between 2 arrays : > > a = array([1,2, 3,2,5,2]) > b = array([1,2]) > I want a - b = [3,5] > > Well, the equivalence of setdiff in matlab... > > I thought a.difference(b) could work, but no : AttributeError: > 'numpy.ndarray' object has no attribute 'difference' Not sure if this works with numpy-arrays, but set(a) - set(b) might just work if the arrays are iterable. Diez From enleverLesX_XXmcX at XmclavXeauX.com Wed Aug 19 04:56:20 2009 From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP) Date: Wed, 19 Aug 2009 10:56:20 +0200 Subject: difference between 2 arrays References: Message-ID: <4a8bbe36$0$12654$ba4acef3@news.orange.fr> (envoy? via news:\\news.wanadoo.fr\comp.lang.python) Hi! See the module "sets" @-salutations -- Michel Claveau From enleverLesX_XXmcX at XmclavXeauX.com Wed Aug 19 04:58:53 2009 From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP) Date: Wed, 19 Aug 2009 10:58:53 +0200 Subject: difference between 2 arrays References: Message-ID: <4a8bbecf$0$12634$ba4acef3@news.orange.fr> Re ! Juste pour signaler qu'il existe un newsgroup en fran?ais sur Python, qui permet de recevoir des r?ponses en fran?ais (donc plus compl?tes/d?taill?es). @-salutations -- Michel Claveau From h.jaeger at medienkonzepte.de Wed Aug 19 05:00:52 2009 From: h.jaeger at medienkonzepte.de (=?ISO-8859-1?Q?Horst_J=E4ger?=) Date: Wed, 19 Aug 2009 11:00:52 +0200 Subject: How to create ones own lib Message-ID: Hi, I would like to create my own lib "hotte.py" which I can import like import string,hotte . How do I do that? I'm working on MacOS 10.5.6 . Thanks in advance From __peter__ at web.de Wed Aug 19 05:08:06 2009 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Aug 2009 11:08:06 +0200 Subject: reading a text file References: <4a8bba7d$0$40004$4fafbaef@reader3.news.tin.it> Message-ID: superpollo wrote: > hi clp > > what's the difference between: > > while True: > input_line = sys.stdin.readline() > if input_line: > sys.stdout.write(input_line.upper()) > else: > break > > and: > > > while True: > try: > sys.stdout.write(sys.stdin.next().upper()) > except StopIteration: > break You should write the latter as for line in sys.stdin: sys.stdout.write(line.upper()) or sys.stdout.writelines(line.upper() for line in sys.stdin) You seem to know already that next() and readline() use different ways to signal "I'm done with the file". Also, after the first StopIteration subsequent next() calls are guaranteed to raise a StopIteration. But the main difference is that file.next() uses an internal buffer, file.readline() doesn't. That means you would lose data if you tried to replace the readline() call below with next() first_line = f.readline() read_of_the_file = f.read() In newer Python versions you will get a ValueError when mixing next() and read()/readline() but in older Pythons (before 2.5 I think) you are in for a surprise. As for line in file: ... is both the fastest and most readable approach if you want to access a file one line at a time I recommend that you use it unless there is a specific reason not to. Peter From gforgx at lavabit.com Wed Aug 19 05:18:37 2009 From: gforgx at lavabit.com (Sergey Simonenko) Date: Wed, 19 Aug 2009 03:18:37 -0600 Subject: Subclass dynamically In-Reply-To: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com> References: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com> Message-ID: On Sat, 08 Aug 2009 11:12:30 -0600, Robert Dailey wrote: How can you subclass a class from an object?.. > Hey, > > I have a class that I want to have a different base class depending on > a parameter that I pass to its __init__method. For example > (pseudocode): > > class MyDerived( self.base ): > def __init__( self, base ): > self.base = base > > > Something like that... and then I would do this: > > foo = MyDerived( MyBase() ) > > Note I'm using Python 3.1 on Windows. Thanks in advance. -- Kind regards, Sergey Simonenko. From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 19 05:18:59 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 19 Aug 2009 11:18:59 +0200 Subject: Scope and classes In-Reply-To: References: Message-ID: <4a8bc383$0$1556$426a34cc@news.free.fr> Chris Rebert a ?crit : (snip) > To access class-level variables from within instance methods of the > class, you have 2 options: > A. Use the class name, i.e. Abc.message > B. Reference the class indirectly, i.e. self.__class__.message Or even simpler - *if* there's no synonym instance attribute: => self.message Attribute lookup will try to resolve the attribute name on the class (and it's parent classes) if it's not found on the instance. From contact at xavierho.com Wed Aug 19 05:28:50 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 19 Aug 2009 19:28:50 +1000 Subject: How to create ones own lib In-Reply-To: References: Message-ID: <2d56febf0908190228q72edb74fr43274d9f253cf014@mail.gmail.com> On Wed, Aug 19, 2009 at 7:00 PM, Horst J?ger wrote: > Hi, > > I would like to create my own lib "hotte.py" which I can import like > > > import string,hotte > > . How do I do that? > 1) Have the hotte.py in the same directory of any of your other Python code that imports it, or 2) Put the hotte.py file in the Python import directive, whose location I do not know in Mac.. someone else will know, I'm sure =] All in all, I'm pretty sure you don't have to compile it or anything, but it can be an option. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From bieffe62 at gmail.com Wed Aug 19 05:30:10 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Wed, 19 Aug 2009 02:30:10 -0700 (PDT) Subject: How to create ones own lib References: Message-ID: On 19 Ago, 11:00, Horst J?ger wrote: > Hi, > > I would like to create my own lib "hotte.py" which I can import like > > ? ? ? ? import string,hotte > > . How do I do that? > > I'm working on MacOS 10.5.6 . > > Thanks in advance Just create the file 'hotte.py' and place it somewhere python can find it, that is: - in the same directory of the code using it (which is most probablyt what you want to do ) - in a directory listed in sys.path variable (which you can extend using sys.path.append("full_path_of_my_library_directory") before doing import hotte There are other options, but these should cover your needs. Ciao ----- FB From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 19 05:31:55 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 19 Aug 2009 11:31:55 +0200 Subject: Scope and classes In-Reply-To: References: Message-ID: <4a8bc68b$0$4054$426a74cc@news.free.fr> David a ?crit : (snip) > Out of 'Abc.message' and 'self.message', which is the favoured > convention? It would be very easy to accidentally override > 'self.messages' with an instance attribute! Only use 'Abc.message' if you want to make sure you get the Abc class 'message' attribute - that is, if you want to skip possible overrides in subclasses. As far as I'm concerned, I'd tend to consider this bad style unless it's a very very specific implementation point of an abstract class (in which case it would probably be named '__message' to prevent accidental override) - but YMMV of course. Use 'self.__class__.message' (or 'type(self).message') if you want to make sure you get the class 'message' attribute - that is, if you want to honor possible overrides in subclasses, but not per-instance override. But then - at least in your example code - I'd use a classmethod: class Abc: message = 'Hello World' @classmethod def print_message(cls): print cls.message Now the most common idiom - that is, outside classmethods - is to just use 'self.message'. Someone (even you) might have a very valid reason to override the 'message' attribute on a per-instance basis. FWIW, if you start to worry about possible accidental overrides here, then Python might not be the right language for you - nothing prevents "accidental" overrides of method and even the class (the '__class__' attribute) itself - yes, they are all attributes, and you can dynamically override them !-) From Bill at SynectixLtd.com Wed Aug 19 05:34:11 2009 From: Bill at SynectixLtd.com (Bill Davy) Date: Wed, 19 Aug 2009 10:34:11 +0100 Subject: Read C++ enum in python References: <4a8b3342$0$25403$426a34cc@news.free.fr><4A8B3E2D.7040702@mrabarnett.plus.com> Message-ID: <7f1v8eF2i0es3U1@mid.individual.net> "Mark Tolonen" wrote in message news:mailman.89.1250666942.2854.python-list at python.org... > > "MRAB" wrote in message > news:4A8B3E2D.7040702 at mrabarnett.plus.com... >> Ludo wrote: >>> Hello, >>> >>> I work in a very large project where we have C++ packages and pieces of >>> python code. >>> >>> I've been googleing for days but what I find seems really too >>> complicated for what I want to do. >>> >>> My business is, in python, to read enum definitions provided by the >>> header file of an c++ package. >>> Of course I could open the .h file, read the enum and transcode it by >>> hand into a .py file but the package is regularly updated and thus is >>> the enum. >>> >>> My question is then simple : do we have : >>> - either a simple way in python to read the .h file, retrieve the >>> c++ enum and provide an access to it in my python script >>> - either a simple tool (in a long-term it would be automatically run >>> when the c++ package is compiled) generating from the .h file a .py file >>> containing the python definition of the enums ? >>> >>> Thank you for any suggestion. >> >> Speaking personally, I'd parse the .h file using a regular expression >> (re module) and generate a .py file. Compilers typically have a way of >> letting you run external scripts (eg batch files in Windows or, in this >> case, a Python script) when an application is compiled. > > This is what 3rd party library pyparsing is great for: > > --------begin code---------- > from pyparsing import * > > # sample string with enums and other stuff > sample = ''' > stuff before > > enum hello { > Zero, > One, > Two, > Three, > Five=5, > Six, > Ten=10 > } > > in the middle > > enum blah > { > alpha, > beta, > gamma = 10 , > zeta = 50 > } > > at the end > ''' > > # syntax we don't want to see in the final parse tree > _lcurl = Suppress('{') > _rcurl = Suppress('}') > _equal = Suppress('=') > _comma = Suppress(',') > _enum = Suppress('enum') > > identifier = Word(alphas,alphanums+'_') > integer = Word(nums) > > enumValue = Group(identifier('name') + Optional(_equal + > integer('value'))) > enumList = Group(enumValue + ZeroOrMore(_comma + enumValue)) > enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl > > # find instances of enums ignoring other syntax > for item,start,stop in enum.scanString(sample): > id = 0 > for entry in item.list: > if entry.value != '': > id = int(entry.value) > print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id) > id += 1 > --------------end code------------ > > Output: > HELLO_ZERO = 0 > HELLO_ONE = 1 > HELLO_TWO = 2 > HELLO_THREE = 3 > HELLO_FIVE = 5 > HELLO_SIX = 6 > HELLO_TEN = 10 > BLAH_ALPHA = 0 > BLAH_BETA = 1 > BLAH_GAMMA = 10 > BLAH_ZETA = 50 > > -Mark > > Python and pythoneers are amazing! From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 19 05:39:07 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 19 Aug 2009 11:39:07 +0200 Subject: Identifying a class type - bad practice? In-Reply-To: <520f55a6-38ac-432b-97e7-ec327740645a@o6g2000yqj.googlegroups.com> References: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> <520f55a6-38ac-432b-97e7-ec327740645a@o6g2000yqj.googlegroups.com> Message-ID: <4a8bc83b$0$24683$426a74cc@news.free.fr> James Harris a ?crit : > On 18 Aug, 21:50, Chris Rebert wrote: (snip) >> class node_type_1: >> def walk_tree(self): >> #code >> self.subtree.walk() >> >> class node_type_2: >> def walk_tree(self): >> #code >> self.subtree.walk() >> >> #etc > > Interesting idea. Basic OO stuff, really. I'd say it's even the whole point of OO. (snip) > The tree is for a compiler. Initially the tree is for parsing of > source code. Then it will need to be processed and changed as further > compiler phases are written. I don't know yet whether it will be > easier to modify the tree or to create a new one for each phase. > > So I guess whether I use the idea depends on the commonality of > operations. You may want to have a look at the "composite" and "visitor" design patterns. AST are canonical use case for these patterns. HTH From jeanmichel at sequans.com Wed Aug 19 05:47:36 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 19 Aug 2009 11:47:36 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: <4A8BCA38.5030308@sequans.com> Grant Edwards wrote: > On 2009-08-18, Simon Forman wrote: > > >> Sexism, racism, homophobia, religious intolerance, etc., all >> stem from a fundamental forgetfulness of our Unity in God (as >> I would put it) and this is perhaps the single greatest cause >> of human misery. >> > > You mean the single greatest cause of human misery isn't > Microsoft Windows? > > No, emacs is responsible ! Hail to Vi ! JM From jeanmichel at sequans.com Wed Aug 19 06:05:29 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 19 Aug 2009 12:05:29 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <50f98a4c0908182043i8a619fdydb9311eadf7cef9@mail.gmail.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <0014c4c0$0$2963$c3e8da3@news.astraweb.com> <50f98a4c0908182043i8a619fdydb9311eadf7cef9@mail.gmail.com> Message-ID: <4A8BCE69.6030508@sequans.com> Simon Forman wrote: > On Tue, Aug 18, 2009 at 8:03 PM, Steven > D'Aprano wrote: > >> On Tue, 18 Aug 2009 17:13:02 -0400, Simon Forman wrote: >> >> >>> Sexism, racism, homophobia, religious intolerance, etc., all stem from a >>> fundamental forgetfulness of our Unity in God (as I would put it) and >>> >> Of the tens of thousands of Gods that people have invented, which is the >> one we're supposed to believe in? I always forget which ones we're >> supposed to dismiss as nonsense, and which one we're not. >> > > Why the heck are you asking me? (I'd say "/you/ are the God you > should believe in.") > Steven, a God... funny :o) No the only God we should surely worship is Guido, our BDFL :bow:. That is not questionable, and those who dare will be hung by the balls. (In order to be fairly cruel we should find an appropriate torture for our ladies, I don't want to be tagged as sexist). JM From nick at craig-wood.com Wed Aug 19 06:29:53 2009 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 19 Aug 2009 05:29:53 -0500 Subject: How to create ones own lib References: Message-ID: Horst J?ger wrote: > I would like to create my own lib "hotte.py" which I can import like > > import string,hotte > > . How do I do that? One of the nice things about python is that you don't need to do anything special to define a library. Just define your classes / functions in hotte.py then use them like import hotte hotte.MyClass() hotte.my_function() See here for the relevant bit of the tutorial http://docs.python.org/tutorial/modules.html -- Nick Craig-Wood -- http://www.craig-wood.com/nick From digisatori at gmail.com Wed Aug 19 06:40:44 2009 From: digisatori at gmail.com (digisatori at gmail.com) Date: Wed, 19 Aug 2009 03:40:44 -0700 (PDT) Subject: expandtabs acts unexpectedly References: <7e598693-c248-4304-bc46-ac79a8a3969b@t11g2000prh.googlegroups.com> Message-ID: <12da5573-4cc0-47ca-837c-b2d75a786eb1@p10g2000prm.googlegroups.com> On Aug 19, 4:16?pm, Peter Brett wrote: > "digisat... at gmail.com" writes: > > Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) > > [GCC 4.3.3] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> ' test\ttest'.expandtabs(4) > > ' test ? test' > >>>> 'test \ttest'.expandtabs(4) > > 'test ? ?test' > > > 1st example: expect returning 4 spaces between 'test', 3 spaces > > returned > > 2nd example: expect returning 5 spaces between 'test', 4 spaces > > returned > > > Is it a bug or something, please advice. > > Consider where the 4-space tabstops are relative to those strings: > > ?test ? test > test ? ?test > ^ ? ^ ? ^ > > So no, it's not a bug. > > If you just want to replace the tab characters by spaces, use: > > ? >>> " test\ttest".replace("\t", " ? ?") > ? ' test ? ?test' > ? >>> "test \ttest".replace("\t", " ? ?") > ? 'test ? ? test' > > HTH, > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Peter > > -- > Peter Brett > Remote Sensing Research Group > Surrey Space Centre You corrected me for the understanding of tab stop. Great explanation. Thank you so much. From tjreedy at udel.edu Wed Aug 19 06:48:13 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Aug 2009 19:48:13 +0900 Subject: How to create functors? In-Reply-To: References: Message-ID: Robert Dailey wrote: > I'm using Python 2.6. And using the legacy syntax in the lambda does > not work either. I want to avoid using a def if possible. Thanks. In Python, writing name = lambda arg: expr instead of def name(arg): return expr is all negative and no positive and should be avoided. Your experience illustrates one reason why. tjr From tjreedy at udel.edu Wed Aug 19 06:52:14 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Aug 2009 19:52:14 +0900 Subject: Raw Strings with Variables In-Reply-To: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: WilsonOfCanada wrote: > Hellos, > > I know that if you have: > > happy = r"C:\moo" > print happy > > you get C:\moo instead of C:\\moo > > The thing is that I want to do this a variable instead. > > ex. testline = fileName.readline() > rawtestline = r testline Python does not have 'raw strings'. It only has 'raw string literals', which is to say, string literals with 'r' prepended to signal less processing (cooking) of the literal in the process of turning it into a string object. tjr From sleepy at cabbage.co.uk Wed Aug 19 07:06:41 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Wed, 19 Aug 2009 11:06:41 GMT Subject: urlopen errors in script References: <3Gxim.148238$XK2.30441@newsfe15.ams2> Message-ID: <51Rim.226342$e11.13364@newsfe14.ams2> On Tue, 18 Aug 2009 13:05:03 +0000, Sleepy Cabbage wrote: > Thanks for the time you've spent anyway Peter. I have superkaramba > installed and the rest of the script is running fine, it's only when I > put the urlopen part in that it comes back with errors. The quotes are > just to make it readable on here as my first attempt at posting muted > the text. This has been solved by upgrading to kde 4.3 From tino at wildenhain.de Wed Aug 19 07:09:28 2009 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 19 Aug 2009 13:09:28 +0200 Subject: reading a text file In-Reply-To: <4a8bba7d$0$40004$4fafbaef@reader3.news.tin.it> References: <4a8bba7d$0$40004$4fafbaef@reader3.news.tin.it> Message-ID: <4A8BDD68.4050108@wildenhain.de> superpollo wrote: > hi clp > > what's the difference between: > > while True: > input_line = sys.stdin.readline() > if input_line: > sys.stdout.write(input_line.upper()) > else: > break > > and: > > > while True: > try: > sys.stdout.write(sys.stdin.next().upper()) > except StopIteration: > break > More useless code, under the hood its working similar. But why not use it in the way intended? for input_line in sys.stdin: sys.stdout.write(input_line.upper()) ? Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From nuno.hespanhol at gmail.com Wed Aug 19 07:55:02 2009 From: nuno.hespanhol at gmail.com (Nuno Santos) Date: Wed, 19 Aug 2009 12:55:02 +0100 Subject: Help with libxml2dom Message-ID: <4A8BE816.9050901@gmail.com> I have just started using libxml2dom to read html files and I have some questions I hope you guys can answer me. The page I am working on (teste.htm): Title
8/15/2009
>>> import libxml2dom >>> foo = open('teste.htm', 'r') >>> str1 = foo.read() >>> doc = libxml2dom.parseString(str1, html=1) >>> html = doc.firstChild >>> html.nodeName u'html' >>> head = html.firstChild >>> head.nodeName u'head' >>> title = head.firstChild >>> title.nodeName u'title' >>> body = head.nextSibling >>> body.nodeName u'body' >>> table = body.firstChild >>> table.nodeName u'text' #?! Why!? Shouldn't it be a table? (1) >>> table = body.firstChild.nextSibling #why this works? is there a text element hidden? (2) >>> table.nodeName u'table' >>> tr = table.firstChild >>> tr.nodeName u'tr' >>> td = tr.firstChild >>> td.nodeName u'td' >>> font = td.firstChild >>> font.nodeName u'text' # (1) >>> font = td.firstChild.nextSibling # (2) >>> font.nodeName u'font' >>> a = font.firstChild >>> a.nodeName u'text' #(1) >>> a = font.firstChild.nextSibling #(2) >>> a.nodeName u'a' It seems like sometimes there are some text elements 'hidden'. This is probably a standard in DOM I simply am not familiar with this and I would very much appreciate if anyone had the kindness to explain me this. Thanks. From kannan4k at gmail.com Wed Aug 19 08:09:16 2009 From: kannan4k at gmail.com (Kannan) Date: Wed, 19 Aug 2009 17:39:16 +0530 Subject: About Python Symbian 60 Message-ID: Hi friends.... I want a Python SDK like Netbeans to work with the Symbian 60 python. I don't have the Symbian 60 mobile.I create some Apps for S60 Platform.To execute that i want this.... Help me.. With regards, Kannan. R. P, -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Wed Aug 19 08:16:17 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 05:16:17 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> Message-ID: On 18 Aug, 11:19, Robert Dailey wrote: > I'm looking for a way to parallelize my python script without using > typical threading primitives. For example, C++ has pthreads and TBB to > break things into "tasks". In C++, parallelization without "typical threading primitives" usually means one of three things: - OpenMP pragmas - the posix function fork(), unless you are using Windows - MPI In Python, you find the function os.fork and wrappers for MPI, and they are used as in C++. With os.fork, I like to use a context manager, putting the calls to fork in __enter__ and the calls to sys.exit in __exit__. Then I can just write code like this: with parallel(): # parallel block here You can also program in the same style as OpenMP using closures. Just wrap whatever loop or block you want to execute in parallel in a closure. It requires minimal edition of the serial code. Instead of def foobar(): for i in iterable: #whatever you can add a closure (internal function) and do this: def foobar(): def section(): # add a closure for i in sheduled(iterable): # balance load #whatever parallel(section) # spawn off threads Programs written in C++ are much more difficult to parallelize with threads because C++ do not have closures. This is why pragma-based parallelization (OpenMP) was invented: #pragma omp parallel for private(i) for (i=0; i Hi, Is there any package to edit the existing excel cell data using python or to create excel charts using python.... please help. Thanks, From davea at ieee.org Wed Aug 19 08:27:43 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 19 Aug 2009 08:27:43 -0400 Subject: Parallelization in Python 2.6 In-Reply-To: <200908190931.18297.hendrik@microcorp.co.za> References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> <200908190931.18297.hendrik@microcorp.co.za> Message-ID: <4A8BEFBF.4010905@ieee.org> Hendrik van Rooyen wrote: > On Tuesday 18 August 2009 22:45:38 Robert Dailey wrote: > > >> Really, all I'm trying to do is the most trivial type of >> parallelization. Take two functions, execute them in parallel. This >> type of parallelization is called "embarrassingly parallel", and is >> the simplest form. There are no dependencies between the two >> functions. They do requires read-only access to shared data, though. >> And if they are being spawned as sub-processes this could cause >> problems, unless the multiprocess module creates pipelines or other >> means to handle this situation. >> > > Just use thread then and thread.start_new_thread. > It just works. > > - Hendrik > > But if you do it that way, it's slower than sequential. And if you have a multi-core processor, or two processors, or ... then it gets much slower yet, and slows down other tasks as well. With the current GIL implementation, for two CPU-bound tasks, you either do them sequentially, or make a separate process. Now, you can share data between separate processes, and if the data is truly going to be readonly, you shouldn't have any locking issues. Naturally you should do your own timings. Maybe your particular CPU and OS will have different results. DaveA From sturlamolden at yahoo.no Wed Aug 19 08:31:37 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 05:31:37 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> Message-ID: <250fb031-d955-45a7-8089-a3973f9af307@g10g2000yqh.googlegroups.com> On 18 Aug, 13:45, Robert Dailey wrote: > Really, all I'm trying to do is the most trivial type of > parallelization. Take two functions, execute them in parallel. This > type of parallelization is called "embarrassingly parallel", and is > the simplest form. There are no dependencies between the two > functions. If you are using Linux or Mac, just call os.fork for this. You should also know that you function "create_task" is simply from threading import Thread def create_task(task): Thread(target=task).start() If your task releases the GIL, this will work fine. > They do requires read-only access to shared data, though. > And if they are being spawned as sub-processes this could cause > problems, unless the multiprocess module creates pipelines or other > means to handle this situation. With forking or multiprocessing, you have to use IPC. That is, usually pipes, unix sockets / named pipes, or shared memory. Multiprocessing helps you with this. Multiprocessing also has a convinient Queue object for serialised read/write access to a pipe. You can also create shared memory with mmap.mmap, using fd 0 with Windows or -1 with Linux. From hendrik at microcorp.co.za Wed Aug 19 08:34:17 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 19 Aug 2009 14:34:17 +0200 Subject: Parallelization in Python 2.6 In-Reply-To: <7xbpmcnruy.fsf@ruckus.brouhaha.com> References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <7xbpmcnruy.fsf@ruckus.brouhaha.com> Message-ID: <200908191434.17399.hendrik@microcorp.co.za> On Wednesday 19 August 2009 10:13:41 Paul Rubin wrote: > Hendrik van Rooyen writes: > > Just use thread then and thread.start_new_thread. > > It just works. > > The GIL doesn't apply to threads made like that?! The GIL does apply - I was talking nonsense again. Misread the OP's intention. - Hendrik From tim.wintle at teamrubber.com Wed Aug 19 08:36:40 2009 From: tim.wintle at teamrubber.com (Tim Wintle) Date: Wed, 19 Aug 2009 13:36:40 +0100 Subject: Excel edit using python In-Reply-To: <405ea65b-434b-4b93-914f-c0ddbf92077f@2g2000prl.googlegroups.com> References: <405ea65b-434b-4b93-914f-c0ddbf92077f@2g2000prl.googlegroups.com> Message-ID: <1250685400.4676.8.camel@tim-laptop> On Wed, 2009-08-19 at 05:25 -0700, suman wrote: > > Is there any package to edit the existing excel cell data using python > or > to create excel charts using python.... Chris, Chris, where are you? http://www.python-excel.org/ Site provided by Chris Withers: http://mail.python.org/pipermail/python-list/2009-June/716845.html Tim Wintle From sturlamolden at yahoo.no Wed Aug 19 08:39:15 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 05:39:15 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> <200908190931.18297.hendrik@microcorp.co.za> Message-ID: On 19 Aug, 05:27, Dave Angel wrote: > But if you do it that way, it's slower than sequential. ?And if you have > a multi-core processor, or two processors, or ... ? then it gets much > slower yet, and slows down other tasks as well. > > With the current GIL implementation, for two CPU-bound tasks, you either > do them sequentially, or make a separate process. For CPU bound tasks, one should put the bottleneck in C/Fortran/Cython and release the GIL. There is a speed penalty of 200x from using Python instead of C. With a quadcore processor you can gain less than 4x speed-up by parallelizing. If you really care enough about speed to write parallel code, the first thing you should do is migrate the bottleneck to C. From martin.hellwig at dcuktec.org Wed Aug 19 08:40:59 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 19 Aug 2009 13:40:59 +0100 Subject: Parallelization in Python 2.6 In-Reply-To: References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> Message-ID: sturlamolden wrote: > The human brain is bad at detecting > computational bottlenecks though. So it almost always pays off to > write everything in Python first, and use the profiler to locate the > worst offenders. +1 QOTW -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From deets at nospam.web.de Wed Aug 19 08:45:13 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 14:45:13 +0200 Subject: Help with libxml2dom References: Message-ID: <7f2aepF2i8bttU1@mid.uni-berlin.de> Nuno Santos wrote: > I have just started using libxml2dom to read html files and I have some > questions I hope you guys can answer me. > > The page I am working on (teste.htm): > > > > Title > > > > > > > > >
> > > > 8/15/2009 >
> > > > >>> import libxml2dom > >>> foo = open('teste.htm', 'r') > >>> str1 = foo.read() > >>> doc = libxml2dom.parseString(str1, html=1) > >>> html = doc.firstChild > >>> html.nodeName > u'html' > >>> head = html.firstChild > >>> head.nodeName > u'head' > >>> title = head.firstChild > >>> title.nodeName > u'title' > >>> body = head.nextSibling > >>> body.nodeName > u'body' > >>> table = body.firstChild > >>> table.nodeName > u'text' #?! Why!? Shouldn't it be a table? (1) > >>> table = body.firstChild.nextSibling #why this works? is there a > text element hidden? (2) > >>> table.nodeName > u'table' > >>> tr = table.firstChild > >>> tr.nodeName > u'tr' > >>> td = tr.firstChild > >>> td.nodeName > u'td' > >>> font = td.firstChild > >>> font.nodeName > u'text' # (1) > >>> font = td.firstChild.nextSibling # (2) > >>> font.nodeName > u'font' > >>> a = font.firstChild > >>> a.nodeName > u'text' #(1) > >>> a = font.firstChild.nextSibling #(2) > >>> a.nodeName > u'a' > > > It seems like sometimes there are some text elements 'hidden'. This is > probably a standard in DOM I simply am not familiar with this and I > would very much appreciate if anyone had the kindness to explain me this. Without a schema or something similar, a parser can't tell if whitespace is significant or not. So if you have you will have not 2, but 4 nodes - root, text containing a newline + 2 spaces, child, and again a text with a newline. You have to skip over those that you are not interested in, or use a different XML-library such as ElementTree (e.g. in the form of lxml) that has a different approach about text-nodes. Diez From piet at cs.uu.nl Wed Aug 19 08:51:48 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 19 Aug 2009 14:51:48 +0200 Subject: recording input from USB port and write to text file References: Message-ID: >>>>> Allan (A) wrote: >A> Hi! I'm fairly new to Python. I understand the basics basics but I'm >A> been trying to write a simple python code that will let me read input >A> data (such as mouse movement) from my USB port and write it in a text >A> file and I am so lost. Can anyone help or direct me to some >A> resources? Thank you! You could try http://sourceforge.net/projects/pyusb/ -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From sturlamolden at yahoo.no Wed Aug 19 08:56:21 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 05:56:21 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> Message-ID: <4575acc6-6045-4b5e-9a60-6dbde6b6d5db@k19g2000yqn.googlegroups.com> On 19 Aug, 05:16, sturlamolden wrote: > You should know about the GIL. It prevents multiple threads form using > the Python interpreter simultaneously. For parallel computing, this is > a blessing and a curse. Only C extensions can release the GIL; this > includes I/0 routines in Python's standard library. If the GIL is not > released, the C library call are guaranteed to be thread-safe. > However, the Python interpreter will be blocked while waiting for the > library call to return. If the GIL is released, parallelization works > as expected; you can also utilise multi-core CPUs (it is a common > misbelief that Python cannot do this). Since I am at it, this is how the GIL can be released: - Many functions in Python's standard library, particularly all blocking i/o functions, release the GIL. - In C or C++ extensions, use the macros Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS. - With ctypes, functions called from a cdll release the GIL, whereas functions called from a pydll do not. - In f2py, declaring a Fortran function threadsafe in a .pyf file or cf2py comment releases the GIL. - In Cython or Pyrex, use a "with nogil:" block to execute code without holding the GIL. Regards, Sturla Molden From piet at cs.uu.nl Wed Aug 19 08:59:43 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 19 Aug 2009 14:59:43 +0200 Subject: Subclass dynamically References: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com> Message-ID: >>>>> Robert Dailey (RD) wrote: >RD> Hey, >RD> I have a class that I want to have a different base class depending on >RD> a parameter that I pass to its __init__method. For example >RD> (pseudocode): >RD> class MyDerived( self.base ): >RD> def __init__( self, base ): >RD> self.base = base >RD> Something like that... and then I would do this: >RD> foo = MyDerived( MyBase() ) What do you want? As you write it now foo would be an instance of MyDerived, but you say you want to have a class with a different base class... So does this mean that foo should become that class or that foo should become an instance of a new anonymous class that has a specified base class? And on the other hand is MyBase the required base class. But you pass an instance of MyBase, not MyBase itself. As you have it above MyBase() should be a class, therefore MyBase should be a metaclass. Or is that not what you want? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From deets at nospam.web.de Wed Aug 19 09:12:55 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 15:12:55 +0200 Subject: recording input from USB port and write to text file References: Message-ID: <7f2c2nF2i8qovU1@mid.uni-berlin.de> Piet van Oostrum wrote: >>>>>> Allan (A) wrote: > >>A> Hi! I'm fairly new to Python. I understand the basics basics but I'm >>A> been trying to write a simple python code that will let me read input >>A> data (such as mouse movement) from my USB port and write it in a text >>A> file and I am so lost. Can anyone help or direct me to some >>A> resources? Thank you! > > You could try http://sourceforge.net/projects/pyusb/ As I said - this is more complicated as it appears. HID-devices will be captured by the OS and can't be accessed by libusb then (with good reason - otherwise writing a keylogger is something not even kernel-space is needed anymore) Diez From sturlamolden at yahoo.no Wed Aug 19 09:14:01 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 06:14:01 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> <200908190931.18297.hendrik@microcorp.co.za> Message-ID: On 19 Aug, 05:27, Dave Angel wrote: > With the current GIL implementation, for two CPU-bound tasks, you either > do them sequentially, or make a separate process. I'd also like to add that most compute-bound code should be delegated to specialized C libraries, many of which are prewritten. For example, FFTW, Intel MKL, ATLAS, LAPACK, NAG. When you do this, the GIL has no consequence unless it is kept locked. So even for scientific programs, writing parallel compute-bound code mostly involves calling into a C or Fortran library with the GIL released. I have yet to see compute- bound code that could not be easily migrated to C or Fortran, either using existing libraries (the common case) or specialised code. From sturlamolden at yahoo.no Wed Aug 19 09:18:16 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 06:18:16 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <7xbpmcnruy.fsf@ruckus.brouhaha.com> Message-ID: On 19 Aug, 05:34, Hendrik van Rooyen wrote: > The GIL does apply - I was talking nonsense again. ?Misread the OP's > intention. It depends on what the OP's functions "doStuff1" and "doStuff2" actually do. If they release the GIL (e.g. make I/O calls) it does not apply. The GIL only serialize access to the interpreter. From sturlamolden at yahoo.no Wed Aug 19 09:31:20 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 06:31:20 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <4a8af5ce$0$30224$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <9d96a617-75b2-413f-bb8a-81d51e42197c@f37g2000yqn.googlegroups.com> On 18 Aug, 11:41, Stefan Behnel wrote: > I think the canonical answer is to use the threading module or (preferably) > the multiprocessing module, which is new in Py2.6. > > http://docs.python.org/library/threading.htmlhttp://docs.python.org/library/multiprocessing.html > > Both share a (mostly) common interface and are simple enough to use. They > are pretty close to the above interface already. There is a big difference between them, which is that multiprocessing do not work with closures. This means that the threading module is simpler to use than multiprocessing if you want to parallelize serial code. You just wrap a closure around whatever block of code you want to run in a thread. For the same reason, programming with OpenMP is easier than using pthreads directly in C/C++. C does not have closures, which is the raison d'etre for OpenMP. Multiprocessing has the same limitation as abstraction for parallel programming as pthreads in C. Python's threading module do not, but the GIL can be a limitation. From ndbecker2 at gmail.com Wed Aug 19 09:41:58 2009 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 19 Aug 2009 09:41:58 -0400 Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <4a8af5ce$0$30224$9b4e6d93@newsspool1.arcor-online.net> <9d96a617-75b2-413f-bb8a-81d51e42197c@f37g2000yqn.googlegroups.com> Message-ID: sturlamolden wrote: > On 18 Aug, 11:41, Stefan Behnel wrote: > >> I think the canonical answer is to use the threading module or >> (preferably) the multiprocessing module, which is new in Py2.6. >> >> http://docs.python.org/library/threading.htmlhttp://docs.python.org/library/multiprocessing.html >> >> Both share a (mostly) common interface and are simple enough to use. They >> are pretty close to the above interface already. > > There is a big difference between them, which is that multiprocessing > do not work with closures. This means that the threading module is > simpler to use than multiprocessing if you want to parallelize serial > code. You just wrap a closure around whatever block of code you want > to run in a thread. Do you have an example of this technique? From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 19 09:43:38 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 19 Aug 2009 15:43:38 +0200 Subject: Subclass dynamically In-Reply-To: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com> References: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com> Message-ID: <4a8c0189$0$9983$426a34cc@news.free.fr> Robert Dailey a ?crit : > Hey, > > I have a class that I want to have a different base class depending on > a parameter that I pass to its __init__method. For example > (pseudocode): > > class MyDerived( self.base ): > def __init__( self, base ): > self.base = base > > > Something like that... and then I would do this: > > foo = MyDerived( MyBase() ) What is your real use case ? I mean, what problem are you actually trying to solve this way ? From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 19 09:48:48 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 19 Aug 2009 15:48:48 +0200 Subject: Code formatting question: conditional expression In-Reply-To: References: Message-ID: <4a8c02bf$0$716$426a74cc@news.free.fr> Richard Brodie a ?crit : > "John Posner" wrote in message > news:mailman.26.1250604346.2854.python-list at python.org... > >> if total > P.BASE: >> excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) >> else: >> excessblk = None > > I wonder if it is appropriate to replace the None sentinel with one that is an instance > of Block() e.g. > > size = total - P.BASE > excessblk = Block(size, srccol, carry_button_suppress=True, empty_block=(size <= 0) ) In which case the last param is possibly redundant - the Block object knows its size, so it might be able to know by itself if it's empty. NB : please notice the 'possibly' and 'might' cautions !-) From mczwhiners at yahoo.com Wed Aug 19 09:50:44 2009 From: mczwhiners at yahoo.com (Smeagol) Date: Wed, 19 Aug 2009 06:50:44 -0700 (PDT) Subject: NOOB: Developing using python on two different computers Message-ID: <610dc365-476f-4c5d-a307-b7b4141244ba@q40g2000prh.googlegroups.com> Hi there, Occasionally I have to develop on two different computers, and I was wondering if there was a way to copy the python "environment" from one to the other? Access to the data is trivial (networked database) but various packages etc exist on one computer, and I want to ensure I have everything package-wise on the other. Both are "windows" machines (native windows box and a Macbook with VMWare running XP)... Is it as simple as copying the Python directory, or is there a script I can run that will tell me what packages are installed on the native windows box and then I can use easy_install to update the VM partition on the Macbook? Much obliged for any help. From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 19 09:56:08 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 19 Aug 2009 15:56:08 +0200 Subject: How to create functors? In-Reply-To: References: Message-ID: <4a8c0478$0$2752$426a74cc@news.free.fr> Terry Reedy a ?crit : > Robert Dailey wrote: > >> I'm using Python 2.6. And using the legacy syntax in the lambda does >> not work either. I want to avoid using a def if possible. Thanks. > > In Python, writing > > name = lambda arg: expr > > instead of > > def name(arg): return expr > > is all negative and no positive and should be avoided. Except that def is a statement, and as such can't be used as a named params when calling a function expecting a callback, ie: vroom = some_dead('parrot', name=lambda arg: exp) (notice the 'name = lambda arg: exp' ?-) Ok, nitpicking. Me --->[] From sjmachin at lexicon.net Wed Aug 19 10:06:28 2009 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Aug 2009 07:06:28 -0700 (PDT) Subject: difference between 2 arrays References: <4a8bbe36$0$12654$ba4acef3@news.orange.fr> Message-ID: On Aug 19, 6:56?pm, "Michel Claveau - MVP" wrote: > See the module "sets" See especially the notice at the front of the current sets doc which says "deprecated since 2.6" and the comparison down the end which explains why the built-in set() and frozenset() are better than the sets module. Starting now to use the sets module is not a good idea unless the OP is stuck on using Python 2.3 . From paul at boddie.org.uk Wed Aug 19 10:10:08 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 19 Aug 2009 07:10:08 -0700 (PDT) Subject: Help with libxml2dom References: Message-ID: <55183f22-2687-4426-b38d-054743b9f150@h21g2000yqa.googlegroups.com> On 19 Aug, 13:55, Nuno Santos wrote: > I have just started using libxml2dom to read html files and I have some > questions I hope you guys can answer me. [...] > ?>>> table = body.firstChild > ?>>> table.nodeName > u'text' #?! Why!? Shouldn't it be a table? (1) You answer this yourself just below. > ?>>> table = body.firstChild.nextSibling #why this works? is there a > text element hidden? (2) > ?>>> table.nodeName > u'table' Yes, in the DOM, the child nodes of elements include text nodes, and even though one might regard the whitespace before the first child element and that appearing after the last child element as unimportant, the DOM keeps it around in case it really is important. [...] > It seems like sometimes there are some text elements 'hidden'. This is > probably a standard in DOM I simply am not familiar with this and I > would very much appreciate if anyone had the kindness to explain me this. Well, the nodes are actually there: they're whitespace used to provide the indentation in your example. I recommend using XPath to get actual elements: table = body.xpath("*")[0] # get child elements and then select the first Although people make a big "song and dance" about the DOM being a nasty API, it's quite bearable if you use it together with XPath queries. Paul From invalid at invalid Wed Aug 19 10:14:11 2009 From: invalid at invalid (Grant Edwards) Date: Wed, 19 Aug 2009 09:14:11 -0500 Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> <4a8b9ef4$0$31865$9b4e6d93@newsspool3.arcor-online.net> Message-ID: On 2009-08-19, Stefan Behnel wrote: > Dennis Lee Bieber wrote: >> If they are number crunchers (CPU-bound) and don't make use of >> binary extension libraries that release the GIL (for the most common >> Python implementation), they'll run faster being called in sequence >> since you won't have the overhead of task switching. > > ... unless, obviously, the hardware is somewhat up to date > (which is not that uncommon for number crunching environments) > and can execute more than one thing at once. Even with multiple processors, it'll still be faster to call them sequentially in a single thread than run them sequentially in multiple threads with the GIL serializing them. -- Grant Edwards grante Yow! Gibble, Gobble, we at ACCEPT YOU ... visi.com From baaluaanand at gmail.com Wed Aug 19 10:20:05 2009 From: baaluaanand at gmail.com (baalu aanand) Date: Wed, 19 Aug 2009 07:20:05 -0700 (PDT) Subject: difference between 2 arrays References: Message-ID: <9a598f0b-f694-4011-b567-1d089f4062e7@v36g2000yqv.googlegroups.com> On Aug 19, 1:48?pm, Pierre wrote: > Hello, > > I would like to know how to find the difference (set operation) > between 2 arrays : > > a = array([1,2, 3,2,5,2]) > b = array([1,2]) > I want a - b = [3,5] > > Well, the equivalence of setdiff in matlab... > > I thought a.difference(b) could work, but no : AttributeError: > 'numpy.ndarray' object has no attribute 'difference' > > Thanks ! Hi, Here I have given my logic, check whether it helps for you a = [1,2, 3,2,5,2] b = [1,2] j = 0 dif = [] for i in range(len(a)) : if a[i] not in b: dif.append(a[i]) j += 1 print dif[k] Thanks Baalu From baaluaanand at gmail.com Wed Aug 19 10:25:55 2009 From: baaluaanand at gmail.com (baalu aanand) Date: Wed, 19 Aug 2009 07:25:55 -0700 (PDT) Subject: difference between 2 arrays References: Message-ID: <1da8e2d5-7a43-4b8c-b447-07f4f8e2f249@z24g2000yqb.googlegroups.com> On Aug 19, 1:48?pm, Pierre wrote: > Hello, > > I would like to know how to find the difference (set operation) > between 2 arrays : > > a = array([1,2, 3,2,5,2]) > b = array([1,2]) > I want a - b = [3,5] > > Well, the equivalence of setdiff in matlab... > > I thought a.difference(b) could work, but no : AttributeError: > 'numpy.ndarray' object has no attribute 'difference' > > Thanks ! Hi, Here I have given my logic, check whether it helps for you a = [1,2, 3,2,5,2] b = [1,2] j = 0 dif = [] for i in range(len(a)) : if a[i] not in b: dif.append(a[i]) j += 1 print dif Thanks Baalu From mhuening at zedat.fu-berlin.de Wed Aug 19 10:44:48 2009 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Wed, 19 Aug 2009 16:44:48 +0200 Subject: difference between 2 arrays In-Reply-To: References: Message-ID: <7f2heuF2hnhj3U1@mid.uni-berlin.de> Pierre (19.08.2009 10:48): > Hello, > > I would like to know how to find the difference (set operation) > between 2 arrays : > > a = array([1,2, 3,2,5,2]) > b = array([1,2]) > I want a - b = [3,5] > What about set()? >>> a = set([1,2, 3,2,5,2]) >>> b = set([1,2]) >>> a.difference(b) set([3, 5]) Matthias From jhnhndly at aol.com Wed Aug 19 10:52:56 2009 From: jhnhndly at aol.com (La Vie Spirituelle) Date: Wed, 19 Aug 2009 16:52:56 +0200 Subject: New message Message-ID: Test -------------- next part -------------- An HTML attachment was scrubbed... URL: From drobinow at gmail.com Wed Aug 19 11:15:07 2009 From: drobinow at gmail.com (David Robinow) Date: Wed, 19 Aug 2009 11:15:07 -0400 Subject: difference between 2 arrays In-Reply-To: References: Message-ID: <4eb0089f0908190815h867d13ci23494b54d1e06947@mail.gmail.com> On Wed, Aug 19, 2009 at 4:48 AM, Pierre wrote: > Hello, > > I would like to know how to find the difference (set operation) > between 2 arrays : > > a = array([1,2, 3,2,5,2]) > b = array([1,2]) > I want a - b = [3,5] > > Well, the equivalence of setdiff in matlab... > > I thought a.difference(b) could work, but no : AttributeError: > 'numpy.ndarray' object has no attribute 'difference' > > Thanks ! > -- > http://mail.python.org/mailman/listinfo/python-list > import numpy a = numpy.array([1,2,3,2,5,2]) b = numpy.array([1,2]) c = list(set(a)-set(b)) # or c = numpy.array(list(set(a)-set(b))) if you want to continue w/ arrays print c From olivier.anospamrnospamnnospamanospamenospamz at affaires.net Wed Aug 19 11:37:56 2009 From: olivier.anospamrnospamnnospamanospamenospamz at affaires.net (Ludo) Date: Wed, 19 Aug 2009 17:37:56 +0200 Subject: Read C++ enum in python In-Reply-To: <4uOim.12753$ze1.6481@news-server.bigpond.net.au> References: <4a8b3342$0$25403$426a34cc@news.free.fr> <4uOim.12753$ze1.6481@news-server.bigpond.net.au> Message-ID: <4a8c1c55$0$420$426a74cc@news.free.fr> Neil Hodgson a ?crit : > > For some headers I tried it didn't work until the .* was changed to a > non-greedy .*? to avoid removing from the start of the first comment to > the end of the last comment. > > file_data = ' '.join(re.split(r'\/\*.*?\*\/', file_data)) Thank you ! I adopt it ! Cheers. From gunterhenriksen at gmail.com Wed Aug 19 11:43:55 2009 From: gunterhenriksen at gmail.com (Gunter Henriksen) Date: Wed, 19 Aug 2009 08:43:55 -0700 Subject: warnings.warn vs logging.warning Message-ID: When I want to issue a warning, I am uncertain about the distinction between warnings.warn() and logging.warning(). My naive thought is to presume "warning" means the same thing in both cases, and so if I call logging.warning(), it should take care of making sure something equivalent to my calling warnings.warn() will happen... more than just having a message go to wherever a message to warnings.warn() would go. If I want to utilize the capabilities of both mechanisms (like having an exception raised), should I call both functions? From deets at nospam.web.de Wed Aug 19 11:52:29 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 17:52:29 +0200 Subject: difference between 2 arrays References: <9a598f0b-f694-4011-b567-1d089f4062e7@v36g2000yqv.googlegroups.com> Message-ID: <7f2ldtF2gd9ttU1@mid.uni-berlin.de> baalu aanand wrote: > On Aug 19, 1:48?pm, Pierre wrote: >> Hello, >> >> I would like to know how to find the difference (set operation) >> between 2 arrays : >> >> a = array([1,2, 3,2,5,2]) >> b = array([1,2]) >> I want a - b = [3,5] >> >> Well, the equivalence of setdiff in matlab... >> >> I thought a.difference(b) could work, but no : AttributeError: >> 'numpy.ndarray' object has no attribute 'difference' >> >> Thanks ! > > > > Hi, > > Here I have given my logic, check whether it helps for you > > a = [1,2, 3,2,5,2] > b = [1,2] > j = 0 > dif = [] > for i in range(len(a)) : > if a[i] not in b: > dif.append(a[i]) > j += 1 > > print dif[k] EEEK, quadratic behavior!! Diez From robert.kern at gmail.com Wed Aug 19 12:17:16 2009 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 19 Aug 2009 09:17:16 -0700 Subject: difference between 2 arrays In-Reply-To: References: Message-ID: On 2009-08-19 01:48 AM, Pierre wrote: > Hello, > > I would like to know how to find the difference (set operation) > between 2 arrays : > > a = array([1,2, 3,2,5,2]) > b = array([1,2]) > I want a - b = [3,5] > > Well, the equivalence of setdiff in matlab... You will want to ask numpy questions on the numpy mailing list. http://www.scipy.org/Mailing_Lists Using set() is frequently a good option, but for large arrays, you will want to avoid the overhead of converting to and from sets and use numpy.setdiff1d(a, b): In [2]: a = array([1,2, 3,2,5,2]) In [3]: b = array([1,2]) In [4]: numpy.setdiff1d(a, b) Out[4]: array([3, 5]) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From markscottwright at gmail.com Wed Aug 19 12:49:07 2009 From: markscottwright at gmail.com (markscottwright) Date: Wed, 19 Aug 2009 09:49:07 -0700 (PDT) Subject: How do I convert an iterator over bytes into a str? References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> Message-ID: <2c212222-0dac-4bd3-8130-5bd302d12dd5@c2g2000yqi.googlegroups.com> On Aug 18, 6:52?pm, "Jan Kaliszewski" wrote: > 19-08-2009 o 00:24:20 markscottwright wrote: > > > What's the correct way to turn an iterator over bytes into a string? > > This works, but, ewww: > > ? ? In [8]: "".join(iter("four score and seven years ago")) > > ? ? Out[8]: 'four score and seven years ago' > > But it is the correct way (and even recommended over s=s+t or s+=t, when > applicable > -- see: ?http://docs.python.org/library/stdtypes.html#sequence-types-str-unico...). > > Cheers, > *j > > -- > Jan Kaliszewski (zuo) Thanks Jan (and all other responders). I suppose I shouldn't be surprised - it's a known wart (http://wiki.python.org/moin/ PythonWarts), but it just looks so darn wrong. It is, as you point out, much faster than "better looking" alternatives, though - http://www.skymind.com/~ocrow/python_string/ From aahz at pythoncraft.com Wed Aug 19 13:08:56 2009 From: aahz at pythoncraft.com (Aahz) Date: 19 Aug 2009 10:08:56 -0700 Subject: Need cleanup advice for multiline string References: <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <4A89CEA2.10400@mrabarnett.plus.com> Message-ID: In article , Jean-Michel Pichavant wrote: >MRAB wrote: >> Carl Banks wrote: >>> On Aug 17, 10:03 am, Jean-Michel Pichavant >>> wrote: >>>> >>>> I'm no English native, but I already heard women/men referring to a >>>> group as "guys", no matter that group gender configuration. It's even >>>> used for group composed exclusively of women. Moreover it looks like a >>>> *very* friendly form, so there is really nothing to worry about it. >>> >>> I like how being very friendly means calling people after a guy who >>> tried to blow up the English Parliament. >> >> Guy Fawkes adopted the name Guido while fighting for the Spanish in the >> Low Countries: >> >> http://en.wikipedia.org/wiki/Guy_Fawkes > >I didn't get Carl's reference. The only thing I know about blowing the >parliament is from the movie V for Vendetta (no comment please !). You should read the original comic book, it's much more interesting (and clearly mentions the Guy Fawkes connection). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From sturlamolden at yahoo.no Wed Aug 19 13:09:46 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 10:09:46 -0700 (PDT) Subject: difference between 2 arrays References: Message-ID: <7470d887-6c9c-4013-8dc5-ffa7ef344f3f@j21g2000yqe.googlegroups.com> On 19 Aug, 01:48, Pierre wrote: > Well, the equivalence of setdiff in matlab... That would be numpy.setdiff1d. From sajmikins at gmail.com Wed Aug 19 13:35:59 2009 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 19 Aug 2009 10:35:59 -0700 (PDT) Subject: recording input from USB port and write to text file References: Message-ID: On Aug 18, 7:33?pm, Allan wrote: > Hi! I'm fairly new to Python. ?I understand the basics basics but I'm > been trying to write a simple python code that will let me read input > data (such as mouse movement) from my USB port and write it in a text > file and I am so lost. ?Can anyone help or direct me to some > resources? ?Thank you! This isn't exactly what you were looking for, but maybe it will give you some ideas: from Tkinter import * def printMotionEvents(event): print "mouse coords: %i x %i" % (event.x, event.y) t = Tk() t.bind('', printMotionEvents) t.mainloop() This script creates a little Tkinter window and then makes it so that when you move the mouse over the window the mouse coordinates are printed to stdout. From rui.vapps at gmail.com Wed Aug 19 13:44:56 2009 From: rui.vapps at gmail.com (Ray) Date: Wed, 19 Aug 2009 10:44:56 -0700 (PDT) Subject: generate keyboard/mouse event under windows Message-ID: <96047669-1bfd-4dbe-bed8-fafea07bbc5a@z34g2000vbl.googlegroups.com> Hi, Anyone can give some help on how to generate keyboard mouse event under windows? (python 2.5) I tried pyhook, I only know how to monitor the keyboard/mouse events. but don't know how to generate/send the the event. thanks for any help. -Ray From aahz at pythoncraft.com Wed Aug 19 13:49:09 2009 From: aahz at pythoncraft.com (Aahz) Date: 19 Aug 2009 10:49:09 -0700 Subject: Database query execution times in Python? References: <24870050.post@talk.nabble.com> Message-ID: In article , pwnedd wrote: > >> Look up EXPLAIN > >Thanks for the suggestion. I don't see any option to have EXPLAIN display >the query time though? My suggestion was partly a gentle push toward a database forum to get more information -- this isn't really a Python question. Unless all you want to do is get the wall-clock time, in which case just use time.time(). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith From sajmikins at gmail.com Wed Aug 19 13:51:08 2009 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 19 Aug 2009 10:51:08 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> <87r5v8e9cu.fsf@benfinney.id.au> Message-ID: On Aug 19, 12:05?am, Ben Finney wrote: > Simon Forman writes: > > On Tue, Aug 18, 2009 at 8:42 PM, Ben Finney wrote: > > > We're all unified by our humanity. Bringing any god into the picture > > > is surely counter to any goals of unity. > > > Unity "in humanity" is, to my way of thinking, the same as Unity "in > > God". > > Then you're playing Humpty-Dumpty games with words. You know very well > that ?God? has established meanings entirely different from ?humanity?, > and those meanings played a part in your choice of that word. > > I maintain that you can't consistently make a declaration in favour of > human unity and unfounded religious assertions. > > > I think Unity, like None, is a built-in singleton, so to speak. > > This is white noise. > > > >> We are one family. > > > > Agreed. > > > <3 > > I think we can peaceably leave it at that. Hear hear! (FWIW, I've always admired Humpty Dumpty's attitude to words. Have you ever read R.A. Wilson's "Quantum Psychology"?) Regards, ~Simon From gu.yakahughes at gmail.com Wed Aug 19 14:07:16 2009 From: gu.yakahughes at gmail.com (yaka) Date: Wed, 19 Aug 2009 11:07:16 -0700 (PDT) Subject: generate keyboard/mouse event under windows References: <96047669-1bfd-4dbe-bed8-fafea07bbc5a@z34g2000vbl.googlegroups.com> Message-ID: Read this and see if it helps: http://kvance.livejournal.com/985732.html From aahz at pythoncraft.com Wed Aug 19 14:20:22 2009 From: aahz at pythoncraft.com (Aahz) Date: 19 Aug 2009 11:20:22 -0700 Subject: httplib incredibly slow :-( References: Message-ID: In article , Chris Withers wrote: >Aahz wrote: >> >> What do you need to know for a decent example? > >Simple download of a file from a url with some auth headers added would >do me. Well, I've hacked up some sample code from my company's codebase: # !!! UNTESTED !!! c = pycurl.Curl() c.setopt(pycurl.URL, url) c.setopt(pycurl.USERPWD, "%s:%s" % (user, pwd)) c.setopt(pycurl.FOLLOWLOCATION, 1) c.setopt(pycurl.MAXREDIRS, 5) c.setopt(pycurl.CONNECTTIMEOUT, 30) f = StringIO() c.setopt(pycurl.WRITEDATA, f) c.perform() c.close() -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith From rui.vapps at gmail.com Wed Aug 19 14:55:25 2009 From: rui.vapps at gmail.com (Ray) Date: Wed, 19 Aug 2009 11:55:25 -0700 (PDT) Subject: generate keyboard/mouse event under windows References: <96047669-1bfd-4dbe-bed8-fafea07bbc5a@z34g2000vbl.googlegroups.com> Message-ID: <9f107280-5d5c-4e6e-b47b-779e8012fdbc@h30g2000vbr.googlegroups.com> On Aug 19, 2:07?pm, yaka wrote: > Read this and see if it helps: > > http://kvance.livejournal.com/985732.html is there a way to generate a 'true' keyboard event? (works like user pressed a key on keyboard) not send the 'send keyboard event to application' ? From jcn-france1972 at pobox.com Wed Aug 19 15:01:25 2009 From: jcn-france1972 at pobox.com (Jean-Claude Neveu) Date: Wed, 19 Aug 2009 12:01:25 -0700 Subject: Python and PHP encryption/decryption Message-ID: I'm looking for a recommendation about encryption/decryption packages for Python. I'm working on a project that will require me to store some values in a database in encrypted format. I'll be storing them from a PHP script and retrieving them (decrypting them) using Python. I'm currently using PHP's mcrypt package to encrypt the values, and I'm using AES for encryption, so something AES-compatible would be ideal. However, the project is at the development stage so I can easily change how I'm encrypting things in PHP if there is a compelling reason on the Python side of things to do so. Many Thanks, Jean-Claude From aahz at pythoncraft.com Wed Aug 19 15:43:00 2009 From: aahz at pythoncraft.com (Aahz) Date: 19 Aug 2009 12:43:00 -0700 Subject: Any way to adjust difflib algorithm? References: Message-ID: In article , Grant Edwards wrote: >On 2009-08-14, Grant Edwards wrote: >> >> In my particular usage, no lines have ever been >> inserted/deleted, so perhaps I should be running diffs on >> individual lines instead? If I do that, I can't figure out >> how to generate HTML output. > >I ended up using the SequenceMatcher on individual pairs of >lines and generating my own HTML based on the results of >get_matching_blocks(). > >That produced the desired results. Good work! Note that IME most diff software shows changed lines as a delete-and-add. For example, diff -u -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith From jgardner at jonathangardner.net Wed Aug 19 16:10:17 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Wed, 19 Aug 2009 13:10:17 -0700 (PDT) Subject: NOOB: Developing using python on two different computers References: <610dc365-476f-4c5d-a307-b7b4141244ba@q40g2000prh.googlegroups.com> Message-ID: <75f2e1e8-49c4-4564-9fab-b0a6b96adaa4@p36g2000prn.googlegroups.com> On Aug 19, 6:50?am, Smeagol wrote: > Hi there, > > Occasionally I have to develop on two different computers, and I was > wondering if there was a way to copy the python "environment" from one > to the other? > > Access to the data is trivial (networked database) but various > packages etc exist on one computer, and I want to ensure I have > everything package-wise on the other. > > Both are "windows" machines (native windows box and a Macbook with > VMWare running XP)... > > Is it as simple as copying the Python directory, or is there a script > I can run that will tell me what packages are installed on the native > windows box and then I can use easy_install to update the VM partition > on the Macbook? > Simple copy won't do it. Check out virtualenv (http://pypi.python.org/pypi/virtualenv). Reinstalling each env from scratch is usually the best bet. List your dependencies in your packages and all you have to do is easy_install your packages. From invalid at invalid Wed Aug 19 16:16:22 2009 From: invalid at invalid (Grant Edwards) Date: Wed, 19 Aug 2009 15:16:22 -0500 Subject: Any way to adjust difflib algorithm? References: Message-ID: On 2009-08-19, Aahz wrote: > In article , > Grant Edwards wrote: >>On 2009-08-14, Grant Edwards wrote: >>> >>> In my particular usage, no lines have ever been >>> inserted/deleted, so perhaps I should be running diffs on >>> individual lines instead? If I do that, I can't figure out >>> how to generate HTML output. >> >>I ended up using the SequenceMatcher on individual pairs of >>lines and generating my own HTML based on the results of >>get_matching_blocks(). >> >>That produced the desired results. > > Good work! Note that IME most diff software shows changed > lines as a delete-and-add. For example, diff -u Right -- though difflib did show _some_ lines as changed rather than deleted/added, it wasn't obvious how it decided between the two. I suspect it used some sort of percentage-changed threshold. For this application both files had all the same lines (by definition), so what I was interested in was what parts of each line changed. -- Grant Edwards grante Yow! I just heard the at SEVENTIES were over!! And visi.com I was just getting in touch with my LEISURE SUIT!! From politza at googlemail.com Wed Aug 19 16:17:19 2009 From: politza at googlemail.com (A.Politz) Date: Wed, 19 Aug 2009 13:17:19 -0700 (PDT) Subject: python doc available in emacs info format? References: Message-ID: On Aug 17, 6:43?am, Xah Lee wrote: > btw, is there still [no] info format for python doc? > > i feel kinda sad [...] > Part of this is due to [other peoples fault] Someone started a rst2info project (google it), maybe you want to help this guy out. Though, he might be a techgeeker, so watch out ! -ap From israelu at elbit.co.il Wed Aug 19 16:31:17 2009 From: israelu at elbit.co.il (iu2) Date: Wed, 19 Aug 2009 13:31:17 -0700 (PDT) Subject: Dictionary from a list Message-ID: Hi all, I need to create a dictionary out of a list. Given the list [1, 2, 3, 4, 5, 6] I need the dictionary: {1:2, 3:4, 5:6} I'll appreciate your help Thanks iu2 From jjposner at optimum.net Wed Aug 19 16:36:20 2009 From: jjposner at optimum.net (John Posner) Date: Wed, 19 Aug 2009 16:36:20 -0400 Subject: Code formatting question: conditional expression In-Reply-To: References: Message-ID: <4A8C6244.40706@optimum.net> Diez wrote: > No. I love them. But not if they are so large that they stretch over several > lines (or to many columns). > > foo = bar if cond else baz > > is more than fine for me. But > > foo = I_need_to_do_something_really_complicated_here() if cond else baz > > isn't, because one doesn't grasp as easily in one look that we're talking a > ternary operator here. > But the right side of my brain (see Peter Keller's discussion in the recent "importance of syntax" thread) finds it quite easy to recognize this as a ternary op: foo = (I_need_to_do_something_really_complicated_here() if cond else baz) The whitespace below "foo" provides a visual hint, which is confirmed by the nearby appearance of "if" on the second line. De gustibus non est disputandum! (or not) Many thanks to all responders! -John From deets at nospam.web.de Wed Aug 19 16:39:47 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 22:39:47 +0200 Subject: Dictionary from a list In-Reply-To: References: Message-ID: <7f368jF2it5a5U1@mid.uni-berlin.de> iu2 schrieb: > Hi all, > > I need to create a dictionary out of a list. > > Given the list [1, 2, 3, 4, 5, 6] > > I need the dictionary: {1:2, 3:4, 5:6} dict(zip(l[::2], l[1::2])) Diez From deets at nospam.web.de Wed Aug 19 16:42:43 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 22:42:43 +0200 Subject: Python and PHP encryption/decryption In-Reply-To: References: Message-ID: <7f36e3F2it5a5U2@mid.uni-berlin.de> Jean-Claude Neveu schrieb: > I'm looking for a recommendation about encryption/decryption packages > for Python. > > I'm working on a project that will require me to store some values in a > database in encrypted format. I'll be storing them from a PHP script and > retrieving them (decrypting them) using Python. I'm currently using > PHP's mcrypt package to encrypt the values, and I'm using AES for > encryption, so something AES-compatible would be ideal. However, the > project is at the development stage so I can easily change how I'm > encrypting things in PHP if there is a compelling reason on the Python > side of things to do so. With PyCrypto[1] you have a wide range of choices, amongst others AES. If that's the best algorithm, or even the best python-package to implement it, I don't know. [1] http://www.dlitz.net/software/pycrypto/ Diez From deets at nospam.web.de Wed Aug 19 16:46:43 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 22:46:43 +0200 Subject: recording input from USB port and write to text file In-Reply-To: References: Message-ID: <7f36ljF2hd2f3U1@mid.uni-berlin.de> Simon Forman schrieb: > On Aug 18, 7:33 pm, Allan wrote: >> Hi! I'm fairly new to Python. I understand the basics basics but I'm >> been trying to write a simple python code that will let me read input >> data (such as mouse movement) from my USB port and write it in a text >> file and I am so lost. Can anyone help or direct me to some >> resources? Thank you! > > This isn't exactly what you were looking for, but maybe it will give > you some ideas: > > > from Tkinter import * > > def printMotionEvents(event): > print "mouse coords: %i x %i" % (event.x, event.y) > > t = Tk() > t.bind('', printMotionEvents) > t.mainloop() > > > This script creates a little Tkinter window and then makes it so that > when you move the mouse over the window the mouse coordinates are > printed to stdout. If it has focus. The overall problem is hard - see e.g. this: http://www.wintellect.com/CS/blogs/jrobbins/archive/2008/08/30/so-you-want-to-set-a-windows-journal-recording-hook-on-vista-it-s-not-nearly-as-easy-as-you-think.aspx Diez From israelu at elbit.co.il Wed Aug 19 16:52:54 2009 From: israelu at elbit.co.il (iu2) Date: Wed, 19 Aug 2009 13:52:54 -0700 (PDT) Subject: Dictionary from a list References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: On Aug 19, 11:39?pm, "Diez B. Roggisch" wrote: > iu2 schrieb: > > > Hi all, > > > I need to create a dictionary out of a list. > > > Given the list [1, 2, 3, 4, 5, 6] > > > I need the dictionary: {1:2, 3:4, 5:6} > > dict(zip(l[::2], l[1::2])) > > Diez Wow, this is cool! thanks iu2 From deets at nospam.web.de Wed Aug 19 17:16:32 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 23:16:32 +0200 Subject: recording input from USB port and write to text file In-Reply-To: <7f36ljF2hd2f3U1@mid.uni-berlin.de> References: <7f36ljF2hd2f3U1@mid.uni-berlin.de> Message-ID: <7f38dgF2i8dt7U1@mid.uni-berlin.de> Diez B. Roggisch schrieb: > Simon Forman schrieb: >> On Aug 18, 7:33 pm, Allan wrote: >>> Hi! I'm fairly new to Python. I understand the basics basics but I'm >>> been trying to write a simple python code that will let me read input >>> data (such as mouse movement) from my USB port and write it in a text >>> file and I am so lost. Can anyone help or direct me to some >>> resources? Thank you! >> >> This isn't exactly what you were looking for, but maybe it will give >> you some ideas: >> >> >> from Tkinter import * >> >> def printMotionEvents(event): >> print "mouse coords: %i x %i" % (event.x, event.y) >> >> t = Tk() >> t.bind('', printMotionEvents) >> t.mainloop() >> >> >> This script creates a little Tkinter window and then makes it so that >> when you move the mouse over the window the mouse coordinates are >> printed to stdout. > > If it has focus. > > The overall problem is hard - see e.g. this: > > http://www.wintellect.com/CS/blogs/jrobbins/archive/2008/08/30/so-you-want-to-set-a-windows-journal-recording-hook-on-vista-it-s-not-nearly-as-easy-as-you-think.aspx But then, there is a solution :) http://pypi.python.org/pypi/pyHook/1.4/ Diez From shearichard at gmail.com Wed Aug 19 18:55:49 2009 From: shearichard at gmail.com (northof40) Date: Wed, 19 Aug 2009 15:55:49 -0700 (PDT) Subject: What file is foo in package bar in ? Message-ID: Hi - I think this is a pretty basic question but it's never worried me before. To improve my skills I'm reading the source code of a library written by someone else. I've come across a problem doing that. Commonly a function is called like this: thepackage.theclass.foo The problem is that 'theclass' is implemented in a file called nothingliketheclass.py so finding the implemention of foo is a bit boring. Now I can grep for foo and depending on how common the method name is that helps ... or not but I'm sure there must be a better way. Given an arbitary package is there some programmatic way to 'ask' what file the method/function is implemented in ? thanks R. From jcd at sdf.lonestar.org Wed Aug 19 19:01:16 2009 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Wed, 19 Aug 2009 19:01:16 -0400 Subject: How to create functors? In-Reply-To: <4a8c0478$0$2752$426a74cc@news.free.fr> References: <4a8c0478$0$2752$426a74cc@news.free.fr> Message-ID: <1250722876.5792.3.camel@webb> On Wed, 2009-08-19 at 15:56 +0200, Bruno Desthuilliers wrote: > Terry Reedy a ?crit : > > Robert Dailey wrote: > > > >> I'm using Python 2.6. And using the legacy syntax in the lambda does > >> not work either. I want to avoid using a def if possible. Thanks. > > > > In Python, writing > > > > name = lambda arg: expr > > > > instead of > > > > def name(arg): return expr > > > > is all negative and no positive and should be avoided. > > Except that def is a statement, and as such can't be used as a named > params when calling a function expecting a callback, ie: > > vroom = some_dead('parrot', name=lambda arg: exp) > > (notice the 'name = lambda arg: exp' ?-) > Which offers no added functionality over: def name_func(arg): return exp vroom = some_dead('parrot', name=name_func) except for confusion in debugging. :) (See other excessively long threads on lambda for further discussion of the debugging headaches caused by lambdas. > Ok, nitpicking. Me --->[] > > From lists at cheimes.de Wed Aug 19 19:06:00 2009 From: lists at cheimes.de (Christian Heimes) Date: Thu, 20 Aug 2009 01:06:00 +0200 Subject: What file is foo in package bar in ? In-Reply-To: References: Message-ID: northof40 wrote: > Given an arbitary package is there some programmatic way to 'ask' what > file the method/function is implemented in ? Indeed, the inspect module contains several useful functions for the job, for example http://docs.python.org/library/inspect.html#inspect.getfile Christian From ndbecker2 at gmail.com Wed Aug 19 19:19:24 2009 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 19 Aug 2009 19:19:24 -0400 Subject: #elements of seq A in seq B Message-ID: What would be a time efficient way to count the number of occurrences of elements of sequence A in sequence B? (in this particular case, these sequences are strings, if that matters). From zuo at chopin.edu.pl Wed Aug 19 19:36:19 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 20 Aug 2009 01:36:19 +0200 Subject: difference between 2 arrays In-Reply-To: <4a8bbe36$0$12654$ba4acef3@news.orange.fr> References: <4a8bbe36$0$12654$ba4acef3@news.orange.fr> Message-ID: 19-08-2009 o 10:56:20 <""Michel Claveau - MVP"> wrote: > (envoy? via news:\\news.wanadoo.fr\comp.lang.python) > > Hi! > > See the module "sets" No, see the builtin set type. Module sets is deprecated (removed in Py 3.x) -- Jan Kaliszewski (zuo) From shearichard at gmail.com Wed Aug 19 19:42:16 2009 From: shearichard at gmail.com (northof40) Date: Wed, 19 Aug 2009 16:42:16 -0700 (PDT) Subject: What file is foo in package bar in ? References: Message-ID: <48a9837b-eb37-47ba-9032-5c5ff7d42223@x25g2000prf.googlegroups.com> On Aug 20, 11:06?am, Christian Heimes wrote: > northof40 wrote: > > Given an arbitary package is there some programmatic way to 'ask' what > > file the method/function is implemented in ? > > Indeed, the inspect module contains several useful functions for the > job, for examplehttp://docs.python.org/library/inspect.html#inspect.getfile > > Christian That's really great thanks - just what I was after. regards R. From ronn.ross at gmail.com Wed Aug 19 19:55:06 2009 From: ronn.ross at gmail.com (Ronn Ross) Date: Wed, 19 Aug 2009 19:55:06 -0400 Subject: Barcodes In-Reply-To: <9c8c445f0908190619v5f50de1bvbbfbd8c0557f9783@mail.gmail.com> References: <9c8c445f0908171318x2d9d862bi35ccb398376aceca@mail.gmail.com> <4A89C3BB.2030605@tim.thechases.com> <9c8c445f0908190619v5f50de1bvbbfbd8c0557f9783@mail.gmail.com> Message-ID: <9c8c445f0908191655i42ec8f86p8f699f2b35cbf6f7@mail.gmail.com> On Wed, Aug 19, 2009 at 9:19 AM, Ronn Ross wrote: > I was hoping that python would have a library to help me print my own bar > codes? We will need labels in all sizes and most label printer just work > with 1 or 2 sizes. I would like to just print a grid of different sizes on > standard paper. Does python have a bar code printing library? > > > > On Mon, Aug 17, 2009 at 4:55 PM, Tim Chase wrote: > >> My company needs a small inventory management app. Does >>>> python have any libraries to help with reading and writing >>>> bar codes? >>>> >>> >>> I've written bar code apps and python really doesn't enter >>> into that part of things. Printers generally have bar code >>> printing capabilities so you just send the right escape >>> sequences and you get the bar codes. To read them, bar code >>> readers scan and translate before sending the values through >>> typically a keyboard wedge or serial port. >>> >> >> To add to what Emile mentions, most barcode readers present a >> keyboard-wedge interface, so that scanning a barcode merely appears as if >> you typed it at the keyboard (USB readers show up as a HID profile). Often >> they'll have configuration barcodes that you can scan to tweak the profile >> (such as pressing , or an arrow-key after sending the barcode; >> controlling beep tone & volume, etc). >> >> For printing barcodes, you can use any number of solutions -- the most >> popular usually just involves installing a "barcode font" and then rendering >> text in that font to your desired output canvas. I believe there are some >> native rendering solutions as well, but I've not investigated since the font >> method was more than sufficient for my wants. >> >> -tkc >> >> >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > I found this library, but no documentation( https://cybernetics.hudora.biz/projects/wiki/huBarcode). Has anyone used this or know of a similar library with better documentation? -------------- next part -------------- An HTML attachment was scrubbed... URL: From zuo at chopin.edu.pl Wed Aug 19 20:05:57 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 20 Aug 2009 02:05:57 +0200 Subject: Dictionary from a list In-Reply-To: References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: 19-08-2009 o 22:52:54 iu2 wrote: > On Aug 19, 11:39?pm, "Diez B. Roggisch" wrote: >> iu2 schrieb: >> >> > Hi all, >> >> > I need to create a dictionary out of a list. >> >> > Given the list [1, 2, 3, 4, 5, 6] >> >> > I need the dictionary: {1:2, 3:4, 5:6} >> >> dict(zip(l[::2], l[1::2])) Or (for long lists, when memory becomes expensive): dict(li[i:i+2] for i in xrange(0, len(li), 2)) Or probably better: from itertools import islice, izip dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2))) Cheers, *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Wed Aug 19 20:17:47 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 20 Aug 2009 02:17:47 +0200 Subject: #elements of seq A in seq B In-Reply-To: References: Message-ID: 20-08-2009 o 01:19:24 Neal Becker wrote: > What would be a time efficient way to count the number of occurrences of > elements of sequence A in sequence B? (in this particular case, these > sequences are strings, if that matters). If you mean: to count occurences of each element of A (separately) in B... Hm, maybe something like this: # result as a dict {: , ...} dict((element, B.count(element)) for element in A) If you mean: to count non overlaping occurences of string A in B -- simply: B.count(A) Regards, *j -- Jan Kaliszewski (zuo) From mhanuel at ieee.org Wed Aug 19 20:27:07 2009 From: mhanuel at ieee.org (Manuel A. Iglesias Abbatemarco) Date: Thu, 20 Aug 2009 00:27:07 +0000 Subject: grokproject and zope.security==3.4.1 error Message-ID: I will apprreciate if someone could help me with the following error. I a trying to create a grokproject application in my debian 5.0 box, the following is the output after executing # grokproject Sample command. debian-box:/home/manuel-debian# grokproject Sample Enter user (Name of an initial administrator user): grok Enter passwd (Password for the initial administrator user): Downloading info about versions... Creating directory ./Sample Downloading zc.buildout... Invoking zc.buildout... Develop: '/home/manuel-debian/Sample/.' Installing eggbasket. Couldn't find index page for 'zope.security' (maybe misspelled?) Getting distribution for 'zope.security==3.4.1'. eggbasket: Distributions are not installed. A tarball will be downloaded. eggbasket: Distributions are not installed. A tarball will be downloaded. eggbasket: Downloading http://grok.zope.org/releaseinfo/grok-eggs-1.0a4.tgz ... eggbasket: Downloading http://grok.zope.org/releaseinfo/grok-eggs-1.0a4.tgz ... eggbasket: Finished downloading. eggbasket: Finished downloading. eggbasket: Extracting tarball contents... eggbasket: Extracting tarball contents... eggbasket: Installing eggs to /root/.buildout/eggs which will take a while... eggbasket: Installing eggs to /root/.buildout/eggs which will take a while... Getting distribution for 'zope.security==3.4.1'. src/zope/security/_proxy.c:19:20: error: Python.h: No such file or directory In file included from src/zope/security/_proxy.c:20: include/zope.proxy/proxy.h:8: error: expected ?)? before ?*? token include/zope.proxy/proxy.h:9: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token include/zope.proxy/proxy.h:10: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token include/zope.proxy/proxy.h:11: error: expected ?)? before ?*? token include/zope.proxy/proxy.h:12: error: expected ?)? before ?*? token include/zope.proxy/proxy.h:16: error: expected specifier-qualifier-list before ?PyObject_HEAD? include/zope.proxy/proxy.h:23: error: expected specifier-qualifier-list before ?PyTypeObject? include/zope.proxy/proxy.h:37: error: ?NULL? undeclared here (not in a function) include/zope.proxy/proxy.h: In function ?Proxy_Import?: include/zope.proxy/proxy.h:43: error: ?PyObject? undeclared (first use in this function) include/zope.proxy/proxy.h:43: error: (Each undeclared identifier is reported only once include/zope.proxy/proxy.h:43: error: for each function it appears in.) include/zope.proxy/proxy.h:43: error: ?m? undeclared (first use in this function) include/zope.proxy/proxy.h:43: warning: implicit declaration of function ?PyImport_ImportModule? include/zope.proxy/proxy.h:45: error: ?tmp? undeclared (first use in this function) include/zope.proxy/proxy.h:45: warning: implicit declaration of function ?PyObject_GetAttrString? include/zope.proxy/proxy.h:47: warning: implicit declaration of function ?PyCObject_Check? include/zope.proxy/proxy.h:49: warning: implicit declaration of function ?PyCObject_AsVoidPtr? include/zope.proxy/proxy.h:50: warning: implicit declaration of function ?Py_DECREF? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:22: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:26: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:27: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:28: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:29: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:30: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:31: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:32: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:33: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:34: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:35: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:36: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:37: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:38: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:39: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:40: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:41: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:42: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:43: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:44: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:45: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:46: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:47: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:48: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:49: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:50: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:51: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:52: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:53: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:54: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:55: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:56: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:57: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:58: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:59: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:60: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:61: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:62: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:63: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:64: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:65: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:66: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:67: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:68: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:69: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:70: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:71: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:72: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:73: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:74: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:75: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:76: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:77: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:78: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:79: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:80: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:81: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:82: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:83: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:84: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:85: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:86: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:87: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:88: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:89: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:90: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:91: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:92: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:93: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:94: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:95: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:96: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:100: error: expected specifier-qualifier-list before ?PyObject? src/zope/security/_proxy.c:109: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?SecurityProxyType? src/zope/security/_proxy.c:116: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c:116: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?check?: src/zope/security/_proxy.c:118: error: ?PyObject? undeclared (first use in this function) src/zope/security/_proxy.c:118: error: ?r? undeclared (first use in this function) src/zope/security/_proxy.c:126: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:127: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:128: error: ?meth? undeclared (first use in this function) src/zope/security/_proxy.c:128: error: ?str_check_setattr? undeclared (first use in this function) src/zope/security/_proxy.c:129: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:130: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:130: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:130: error: ?name? undeclared (first use in this function) src/zope/security/_proxy.c:132: warning: implicit declaration of function ?PyObject_CallMethodObjArgs? src/zope/security/_proxy.c:132: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:133: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:162: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:164: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:176: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:210: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:250: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:282: error: expected ?)? before ?*? token src/zope/security/_proxy.c: In function ?proxy_clear?: src/zope/security/_proxy.c:290: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:290: error: ?PyObject? undeclared (first use in this function) src/zope/security/_proxy.c:290: error: ?t? undeclared (first use in this function) src/zope/security/_proxy.c:290: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:290: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:291: error: ?SecurityProxyType? undeclared (first use in this function) src/zope/security/_proxy.c:291: error: expected expression before ?)? token src/zope/security/_proxy.c: In function ?proxy_dealloc?: src/zope/security/_proxy.c:299: error: ?SecurityProxyType? undeclared (first use in this function) src/zope/security/_proxy.c:299: error: ?PyObject? undeclared (first use in this function) src/zope/security/_proxy.c:299: error: expected expression before ?)? token src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:303: error: expected declaration specifiers or ?...? before ?visitproc? src/zope/security/_proxy.c: In function ?proxy_traverse?: src/zope/security/_proxy.c:305: warning: implicit declaration of function ?visit? src/zope/security/_proxy.c:305: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:307: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:312: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:324: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:337: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:350: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:364: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c:364: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?proxy_setattro?: src/zope/security/_proxy.c:366: error: ?str_check_setattr? undeclared (first use in this function) src/zope/security/_proxy.c:366: error: ?name? undeclared (first use in this function) src/zope/security/_proxy.c:366: error: too many arguments to function ?check? src/zope/security/_proxy.c:367: warning: implicit declaration of function ?PyObject_SetAttr? src/zope/security/_proxy.c:367: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:367: error: ?value? undeclared (first use in this function) src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:371: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:410: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:427: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:443: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?proxy_compare?: src/zope/security/_proxy.c:445: warning: implicit declaration of function ?PyObject_Compare? src/zope/security/_proxy.c:445: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:445: error: ?other? undeclared (first use in this function) src/zope/security/_proxy.c: In function ?proxy_hash?: src/zope/security/_proxy.c:451: warning: implicit declaration of function ?PyObject_Hash? src/zope/security/_proxy.c:451: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:454: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:484: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:485: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:486: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:487: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:488: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:490: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:497: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:498: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:499: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:500: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:501: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:502: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:504: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:544: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:545: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:546: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:547: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:548: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:551: error: expected ?)? before ?*? token src/zope/security/_proxy.c:596: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:597: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:598: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:601: error: expected ?)? before ?*? token src/zope/security/_proxy.c:606: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:607: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:608: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:609: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:610: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:611: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:613: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:614: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:615: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:616: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:617: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:618: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:619: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:620: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:621: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:622: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:623: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:625: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:626: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:627: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:628: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c: In function ?proxy_length?: src/zope/security/_proxy.c:637: error: ?str_check? undeclared (first use in this function) src/zope/security/_proxy.c:637: error: ?str___len__? undeclared (first use in this function) src/zope/security/_proxy.c:637: error: too many arguments to function ?check? src/zope/security/_proxy.c:638: warning: implicit declaration of function ?PyObject_Length? src/zope/security/_proxy.c:638: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:643: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:644: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c:644: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c:646: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:661: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?proxy_isetitem?: src/zope/security/_proxy.c:663: error: ?PyObject? undeclared (first use in this function) src/zope/security/_proxy.c:663: error: ?key? undeclared (first use in this function) src/zope/security/_proxy.c:663: warning: implicit declaration of function ?PyInt_FromLong? src/zope/security/_proxy.c:667: error: ?value? undeclared (first use in this function) src/zope/security/_proxy.c:667: error: too many arguments to function ?proxy_setitem? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:673: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:686: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?proxy_ass_slice?: src/zope/security/_proxy.c:688: error: ?str_check? undeclared (first use in this function) src/zope/security/_proxy.c:688: error: ?str___setslice__? undeclared (first use in this function) src/zope/security/_proxy.c:688: error: too many arguments to function ?check? src/zope/security/_proxy.c:689: warning: implicit declaration of function ?PySequence_SetSlice? src/zope/security/_proxy.c:689: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:689: error: ?value? undeclared (first use in this function) src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:694: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?proxy_contains?: src/zope/security/_proxy.c:696: error: ?str_check? undeclared (first use in this function) src/zope/security/_proxy.c:696: error: ?str___contains__? undeclared (first use in this function) src/zope/security/_proxy.c:696: error: too many arguments to function ?check? src/zope/security/_proxy.c:697: warning: implicit declaration of function ?PySequence_Contains? src/zope/security/_proxy.c:697: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:697: error: ?value? undeclared (first use in this function) src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:705: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:719: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c:719: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?proxy_setitem?: src/zope/security/_proxy.c:721: error: ?value? undeclared (first use in this function) src/zope/security/_proxy.c:722: error: ?str_check? undeclared (first use in this function) src/zope/security/_proxy.c:722: error: ?str___delitem__? undeclared (first use in this function) src/zope/security/_proxy.c:722: error: too many arguments to function ?check? src/zope/security/_proxy.c:723: warning: implicit declaration of function ?PyObject_DelItem? src/zope/security/_proxy.c:723: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:723: error: ?key? undeclared (first use in this function) src/zope/security/_proxy.c:726: error: ?str___setitem__? undeclared (first use in this function) src/zope/security/_proxy.c:726: error: too many arguments to function ?check? src/zope/security/_proxy.c:727: warning: implicit declaration of function ?PyObject_SetItem? src/zope/security/_proxy.c:727: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:737: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?proxy_as_number? src/zope/security/_proxy.c:785: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?proxy_as_sequence? src/zope/security/_proxy.c:797: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?proxy_as_mapping? src/zope/security/_proxy.c:817: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?PyTypeObject? src/zope/security/_proxy.c:862: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:877: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:892: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?module_functions? src/zope/security/_proxy.c: In function ?init_proxy?: src/zope/security/_proxy.c:905: error: ?PyObject? undeclared (first use in this function) src/zope/security/_proxy.c:905: error: ?m? undeclared (first use in this function) src/zope/security/_proxy.c:915: error: ?str___3pow__? undeclared (first use in this function) src/zope/security/_proxy.c:915: warning: implicit declaration of function ?PyString_InternFromString? src/zope/security/_proxy.c:916: error: ?str___call__? undeclared (first use in this function) src/zope/security/_proxy.c:917: error: ?str_check? undeclared (first use in this function) src/zope/security/_proxy.c:918: error: ?str_check_getattr? undeclared (first use in this function) src/zope/security/_proxy.c:919: error: ?str_check_setattr? undeclared (first use in this function) src/zope/security/_proxy.c:920: error: ?str___cmp__? undeclared (first use in this function) src/zope/security/_proxy.c:921: error: ?str___coerce__? undeclared (first use in this function) src/zope/security/_proxy.c:922: error: ?str___contains__? undeclared (first use in this function) src/zope/security/_proxy.c:923: error: ?str___delitem__? undeclared (first use in this function) src/zope/security/_proxy.c:924: error: ?str___getitem__? undeclared (first use in this function) src/zope/security/_proxy.c:925: error: ?str___getslice__? undeclared (first use in this function) src/zope/security/_proxy.c:926: error: ?str___hash__? undeclared (first use in this function) src/zope/security/_proxy.c:927: error: ?str___iter__? undeclared (first use in this function) src/zope/security/_proxy.c:928: error: ?str___len__? undeclared (first use in this function) src/zope/security/_proxy.c:929: error: ?str_next? undeclared (first use in this function) src/zope/security/_proxy.c:930: error: ?str___nonzero__? undeclared (first use in this function) src/zope/security/_proxy.c:931: error: ?str_op_abs? undeclared (first use in this function) src/zope/security/_proxy.c:932: error: ?str_op_add? undeclared (first use in this function) src/zope/security/_proxy.c:933: error: ?str_op_and? undeclared (first use in this function) src/zope/security/_proxy.c:934: error: ?str_op_div? undeclared (first use in this function) src/zope/security/_proxy.c:935: error: ?str_op_divmod? undeclared (first use in this function) src/zope/security/_proxy.c:936: error: ?str_op_float? undeclared (first use in this function) src/zope/security/_proxy.c:937: error: ?str_op_floordiv? undeclared (first use in this function) src/zope/security/_proxy.c:938: error: ?str_op_hex? undeclared (first use in this function) src/zope/security/_proxy.c:939: error: ?str_op_iadd? undeclared (first use in this function) src/zope/security/_proxy.c:940: error: ?str_op_iand? undeclared (first use in this function) src/zope/security/_proxy.c:941: error: ?str_op_idiv? undeclared (first use in this function) src/zope/security/_proxy.c:942: error: ?str_op_ifloordiv? undeclared (first use in this function) src/zope/security/_proxy.c:943: error: ?str_op_ilshift? undeclared (first use in this function) src/zope/security/_proxy.c:944: error: ?str_op_imod? undeclared (first use in this function) src/zope/security/_proxy.c:945: error: ?str_op_imul? undeclared (first use in this function) src/zope/security/_proxy.c:946: error: ?str_op_int? undeclared (first use in this function) src/zope/security/_proxy.c:947: error: ?str_op_invert? undeclared (first use in this function) src/zope/security/_proxy.c:948: error: ?str_op_ior? undeclared (first use in this function) src/zope/security/_proxy.c:949: error: ?str_op_ipow? undeclared (first use in this function) src/zope/security/_proxy.c:950: error: ?str_op_irshift? undeclared (first use in this function) src/zope/security/_proxy.c:951: error: ?str_op_isub? undeclared (first use in this function) src/zope/security/_proxy.c:952: error: ?str_op_itruediv? undeclared (first use in this function) src/zope/security/_proxy.c:953: error: ?str_op_ixor? undeclared (first use in this function) src/zope/security/_proxy.c:954: error: ?str_op_long? undeclared (first use in this function) src/zope/security/_proxy.c:955: error: ?str_op_lshift? undeclared (first use in this function) src/zope/security/_proxy.c:956: error: ?str_op_mod? undeclared (first use in this function) src/zope/security/_proxy.c:957: error: ?str_op_mul? undeclared (first use in this function) src/zope/security/_proxy.c:958: error: ?str_op_neg? undeclared (first use in this function) src/zope/security/_proxy.c:959: error: ?str_op_oct? undeclared (first use in this function) src/zope/security/_proxy.c:960: error: ?str_op_or? undeclared (first use in this function) src/zope/security/_proxy.c:961: error: ?str_op_pos? undeclared (first use in this function) src/zope/security/_proxy.c:962: error: ?str_op_radd? undeclared (first use in this function) src/zope/security/_proxy.c:963: error: ?str_op_rand? undeclared (first use in this function) src/zope/security/_proxy.c:964: error: ?str_op_rdiv? undeclared (first use in this function) src/zope/security/_proxy.c:965: error: ?str_op_rdivmod? undeclared (first use in this function) src/zope/security/_proxy.c:966: error: ?str_op_rfloordiv? undeclared (first use in this function) src/zope/security/_proxy.c:967: error: ?str_op_rlshift? undeclared (first use in this function) src/zope/security/_proxy.c:968: error: ?str_op_rmod? undeclared (first use in this function) src/zope/security/_proxy.c:969: error: ?str_op_rmul? undeclared (first use in this function) src/zope/security/_proxy.c:970: error: ?str_op_ror? undeclared (first use in this function) src/zope/security/_proxy.c:971: error: ?str_op_rrshift? undeclared (first use in this function) src/zope/security/_proxy.c:972: error: ?str_op_rshift? undeclared (first use in this function) src/zope/security/_proxy.c:973: error: ?str_op_rsub? undeclared (first use in this function) src/zope/security/_proxy.c:974: error: ?str_op_rtruediv? undeclared (first use in this function) src/zope/security/_proxy.c:975: error: ?str_op_rxor? undeclared (first use in this function) src/zope/security/_proxy.c:976: error: ?str_op_sub? undeclared (first use in this function) src/zope/security/_proxy.c:977: error: ?str_op_truediv? undeclared (first use in this function) src/zope/security/_proxy.c:978: error: ?str_op_xor? undeclared (first use in this function) src/zope/security/_proxy.c:979: error: ?str___pow__? undeclared (first use in this function) src/zope/security/_proxy.c:980: error: ?str_proxy? undeclared (first use in this function) src/zope/security/_proxy.c:981: error: ?str___repr__? undeclared (first use in this function) src/zope/security/_proxy.c:982: error: ?str___rpow__? undeclared (first use in this function) src/zope/security/_proxy.c:983: error: ?str___setitem__? undeclared (first use in this function) src/zope/security/_proxy.c:984: error: ?str___setslice__? undeclared (first use in this function) src/zope/security/_proxy.c:985: error: ?str___str__? undeclared (first use in this function) src/zope/security/_proxy.c:988: error: ?__class__str? undeclared (first use in this function) src/zope/security/_proxy.c:988: warning: implicit declaration of function ?PyString_FromString? src/zope/security/_proxy.c:991: error: ?__name__str? undeclared (first use in this function) src/zope/security/_proxy.c:994: error: ?__module__str? undeclared (first use in this function) src/zope/security/_proxy.c:997: error: ?SecurityProxyType? undeclared (first use in this function) src/zope/security/_proxy.c:997: error: ?PyType_Type? undeclared (first use in this function) src/zope/security/_proxy.c:998: error: ?PyType_GenericAlloc? undeclared (first use in this function) src/zope/security/_proxy.c:999: error: ?_PyObject_GC_Del? undeclared (first use in this function) src/zope/security/_proxy.c:1000: error: ?ProxyInterface? has no member named ?proxytype? src/zope/security/_proxy.c:1001: warning: implicit declaration of function ?PyType_Ready? src/zope/security/_proxy.c:1004: warning: implicit declaration of function ?Py_InitModule3? src/zope/security/_proxy.c:1004: error: ?module_functions? undeclared (first use in this function) src/zope/security/_proxy.c:1008: warning: implicit declaration of function ?Py_INCREF? src/zope/security/_proxy.c:1009: warning: implicit declaration of function ?PyModule_AddObject? src/zope/security/_proxy.c:1009: error: expected expression before ?)? token error: Setup script exited with error: command 'gcc' failed with exit status 1 An error occured when trying to install zope.security 3.4.1.Look above this message for any errors thatwere output by easy_install. While: Installing eggbasket. Getting distribution for 'zope.security==3.4.1'. Error: Couldn't install: zope.security 3.4.1 Thank you in advance. Manuel _________________________________________________________________ With Windows Live, you can organize, edit, and share your photos. http://www.windowslive.com/Desktop/PhotoGallery -------------- next part -------------- An HTML attachment was scrubbed... URL: From zuo at chopin.edu.pl Wed Aug 19 20:29:32 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 20 Aug 2009 02:29:32 +0200 Subject: Dictionary from a list In-Reply-To: References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: 20-08-2009 o 02:05:57 Jan Kaliszewski wrote: > Or probably better: > > from itertools import islice, izip > dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2))) Or similarly, perhaps more readable: iterator = iter(li) dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2)) -- Jan Kaliszewski (zuo) From greg at cosc.canterbury.ac.nz Wed Aug 19 20:51:36 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 20 Aug 2009 12:51:36 +1200 Subject: Identifying a class type - bad practice? In-Reply-To: <520f55a6-38ac-432b-97e7-ec327740645a@o6g2000yqj.googlegroups.com> References: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> <520f55a6-38ac-432b-97e7-ec327740645a@o6g2000yqj.googlegroups.com> Message-ID: <7f3kvpF2in935U1@mid.individual.net> James Harris wrote: > I don't know yet whether it will be > easier to modify the tree or to create a new one for each phase. You can create a new tree using this style as well. Just have each method create and return a new node instead of modifying the existing one. -- Greg From nat.k at gm.ml Wed Aug 19 20:58:15 2009 From: nat.k at gm.ml (Nathan Keel) Date: Wed, 19 Aug 2009 17:58:15 -0700 Subject: python doc available in emacs info format? References: Message-ID: A.Politz wrote: > On Aug 17, 6:43?am, Xah Lee wrote: >> btw, is there still [no] info format for python doc? >> >> i feel kinda sad [...] >> Part of this is due to [other peoples fault] > > Someone started a rst2info project (google it), maybe you want to help > this guy out. > > Though, he might be a techgeeker, so watch out ! > > -ap Don't bother with this Xah Lee clown. He posts random crap because he thinks everyone wants to hear what he has to say about unrelated subject material and thinks he looks smart for doing it. Unfortunately, he usually lacks a clue about any topic he brings up (and he always starts a new thread like he's some authority). His goals are nothing more than to post arrogant, clueless rants thinking he's showing off. this is why he ALWAYS cross posts to the same groups (Emacs, Python,, Perl, etc.), even when the topic or content has nothing to do with those things. He thinks people in these groups automatically respect him, when most have killfiled him. From http Wed Aug 19 21:42:32 2009 From: http (Paul Rubin) Date: 19 Aug 2009 18:42:32 -0700 Subject: How to create functors? References: Message-ID: <7xab1vl0qf.fsf@ruckus.brouhaha.com> Robert Dailey writes: > I want to simply wrap a function up into an object so it can be called > with no parameters. Nitpick: what you are asking for is called a closure. "Functor" means something completely different. As a few other people have explained, "print" in python 2.x is a statement rather than a function. You could use sys.stdout.write instead of print. From http Wed Aug 19 21:45:53 2009 From: http (Paul Rubin) Date: 19 Aug 2009 18:45:53 -0700 Subject: Python and PHP encryption/decryption References: Message-ID: <7x63cjl0ku.fsf@ruckus.brouhaha.com> Jean-Claude Neveu writes: > I'm working on a project that will require me to store some values in > a database in encrypted format. I'll be storing them from a PHP script > and retrieving them (decrypting them) using Python. I'm currently > using PHP's mcrypt package to encrypt the values, and I'm using AES > for encryption, so something AES-compatible would be ideal. There are several python libraries that support AES in the standard operating modes. If you are doing something sensible on the PHP side, you should be able to get Python to interoperate with it. Be careful that you are doing the right things algorithmically in terms of modes, IV's, etc. If you don't know what you're doing in this area, it's best to (at minimum) seek more specific advice. From sajmikins at gmail.com Wed Aug 19 22:12:14 2009 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 19 Aug 2009 19:12:14 -0700 (PDT) Subject: #elements of seq A in seq B References: Message-ID: <7c16abe1-7502-432a-acff-aff95c22a8ac@q14g2000vbi.googlegroups.com> On Aug 19, 8:17?pm, "Jan Kaliszewski" wrote: > 20-08-2009 o 01:19:24 Neal Becker wrote: > > > What would be a time efficient way to count the number of occurrences of > > elements of sequence A in sequence B? ?(in this particular case, these > > sequences are strings, if that matters). > > If you mean: to count occurences of each element of A (separately) in B... > > Hm, maybe something like this: > > ? ?# result as a dict {: , ...} > ? ?dict((element, B.count(element)) for element in A) > > If you mean: to count non overlaping occurences of string A in B > -- simply: > > ? ?B.count(A) > > Regards, > *j > > -- > Jan Kaliszewski (zuo) You don't want to use count() in a case like this because it iterates through B len(A) times, i.e. this algorithm is O(A x B). If all you want is the total you can do it like this: def f(a, b): a = set(a) return sum(item in a for item in b) A = 'some string' B = 'another string' print f(A, B) # prints 12 If you want to know the count for each element you can use this: from collections import defaultdict def g(a, b): a = set(a) d = defaultdict(int) for item in b: if item in a: d[item] += 1 return d print g(A, B) # prints defaultdict(, {' ': 1, 'e': 1, 'g': 1, 'i': 1, 'o': 1, 'n': 2, 's': 1, 'r': 2, 't': 2}) HTH, ~Simon From rtomek at ceti.com.pl Wed Aug 19 22:45:46 2009 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Thu, 20 Aug 2009 04:45:46 +0200 (CEST) Subject: #elements of seq A in seq B In-Reply-To: References: Message-ID: On Wed, 19 Aug 2009, Neal Becker wrote: > What would be a time efficient way to count the number of occurrences of > elements of sequence A in sequence B? (in this particular case, these > sequences are strings, if that matters). If A and B are rather lengthy, then maybe build a tree from elements of A and use it to count elements of B. I.e., tree nodes would be counters. Building trees in Python, however, I guess it is a little bit tricky. Of course it is possible. But maybe you would rather have this tree maintained in C. Regards Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From wuwei23 at gmail.com Wed Aug 19 23:04:12 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 19 Aug 2009 20:04:12 -0700 (PDT) Subject: How do I convert an iterator over bytes into a str? References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> <2c212222-0dac-4bd3-8130-5bd302d12dd5@c2g2000yqi.googlegroups.com> Message-ID: markscottwright wrote: > Thanks Jan (and all other responders). ?I suppose I shouldn't be > surprised - it's a known wart (http://wiki.python.org/moin/ > PythonWarts), but it just looks so darn wrong. Don't forget that it's exceptionally easy to create your own mechanism for doing this: def join(seq, sep): return sep.join(map(str, seq)) From laser.yuan at gmail.com Wed Aug 19 23:22:55 2009 From: laser.yuan at gmail.com (laser) Date: Wed, 19 Aug 2009 20:22:55 -0700 (PDT) Subject: IDLE is not as interactive as Maple Message-ID: <7aa51a98-965c-4c74-a3b5-650140f1d589@v23g2000pro.googlegroups.com> In the future, will Python provide programe enviroment like Maple does? In Maple, you can remove anything unneeded in the editor. And the code execution order are not necessary in one direction. You can run any command line on the screen by push Enter key. These functions gave a lot of flaxibility for users to start with programming something. From sjmachin at lexicon.net Wed Aug 19 23:34:51 2009 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Aug 2009 20:34:51 -0700 (PDT) Subject: #elements of seq A in seq B References: <7c16abe1-7502-432a-acff-aff95c22a8ac@q14g2000vbi.googlegroups.com> Message-ID: <285422cf-9a8d-43ef-a5ac-a04a3ce9a002@a39g2000pre.googlegroups.com> On Aug 20, 12:12?pm, Simon Forman wrote: > On Aug 19, 8:17?pm, "Jan Kaliszewski" wrote: > > If you mean: to count non overlaping occurences of string A in B > > -- simply: > > > ? ?B.count(A) > > You don't want to use count() in a case like this because it iterates > through B len(A) times, i.e. this algorithm is O(A x B). There's seems to be multiple confusion here. Jan was talking about counting non-overlapping occurrences of string A in [string] B. In that case B.count(A) is nowhere near O(A*B)... in fact in reasonable cases it is sub-linear i.e. O(B/A) See http://svn.python.org/view/python/trunk/Objects/stringlib/fastsearch.h?revision=68811&view=markup And even a naive implementation of str.count() would not "iterate through B len(A) times". and list.count() can't be used on its own to solve Neal's problem; its arg is a single element so it would have to be wrapped in a loop: sum (B.count(a) for a in A) which would of course be O(A*B) From metolone+gmane at gmail.com Thu Aug 20 00:01:23 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Wed, 19 Aug 2009 21:01:23 -0700 Subject: Read C++ enum in python References: <4a8b3342$0$25403$426a34cc@news.free.fr><4A8B3E2D.7040702@mrabarnett.plus.com> Message-ID: "Mark Tolonen" wrote in message news:h6g9ig$vh0$1 at ger.gmane.org... [snip] > > This is what 3rd party library pyparsing is great for: > > --------begin code---------- > from pyparsing import * > > # sample string with enums and other stuff > sample = ''' > stuff before > > enum hello { > Zero, > One, > Two, > Three, > Five=5, > Six, > Ten=10 > } > > in the middle > > enum blah > { > alpha, > beta, > gamma = 10 , > zeta = 50 > } > > at the end > ''' > > # syntax we don't want to see in the final parse tree > _lcurl = Suppress('{') > _rcurl = Suppress('}') > _equal = Suppress('=') > _comma = Suppress(',') > _enum = Suppress('enum') > > identifier = Word(alphas,alphanums+'_') > integer = Word(nums) > > enumValue = Group(identifier('name') + Optional(_equal + > integer('value'))) > enumList = Group(enumValue + ZeroOrMore(_comma + enumValue)) > enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl > > # find instances of enums ignoring other syntax > for item,start,stop in enum.scanString(sample): > id = 0 > for entry in item.list: > if entry.value != '': > id = int(entry.value) > print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id) > id += 1 > --------------end code------------ > > Output: > HELLO_ZERO = 0 > HELLO_ONE = 1 > HELLO_TWO = 2 > HELLO_THREE = 3 > HELLO_FIVE = 5 > HELLO_SIX = 6 > HELLO_TEN = 10 > BLAH_ALPHA = 0 > BLAH_BETA = 1 > BLAH_GAMMA = 10 > BLAH_ZETA = 50 Paul McGuire (pyparsing author) reminded me that: enum.ignore(cppStyleComment) before scanString will skip commented out sections as well. -Mark From half.italian at gmail.com Thu Aug 20 00:04:47 2009 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 19 Aug 2009 21:04:47 -0700 (PDT) Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <92338aa1-0913-483a-b950-c73f0fdb0b1f@v37g2000prg.googlegroups.com> Message-ID: <4213ecf5-4981-48b4-a038-229cc330db32@p36g2000prn.googlegroups.com> On Aug 18, 4:58?pm, birdsong wrote: > On Aug 18, 3:18?pm, Derek Martin wrote: > > > > > On Tue, Aug 18, 2009 at 03:10:15PM -0500, Derek Martin wrote: > > > I have some simple threaded code... ?If I run this > > > with an arg of 1 (start one thread), it pegs one cpu, as I would > > > expect. ?If I run it with an arg of 2 (start 2 threads), it uses both > > > CPUs, but utilization of both is less than 50%. ?Can anyone explain > > > why? ? > > > Ah, searching while waiting for an answer (the e-mail gateway is a bit > > slow, it seems...) I discovered that the GIL is the culprate. > > Evidently this question comes up a lot. ?It would probably save a lot > > of time on the part of those who answer questions here, as well as > > those implementing solutions in Python, if whoever is maintaining the > > docs these days would put a blurb about this in the docs in big bold > > letters... ?Concurrency being perhaps the primary reason to use > > threading, essentially it means that Python is not useful for the > > sorts of problems that one would be inclined to solve they way my code > > works (or rather, was meant to). ?It would be very helpful to know > > that *before* one tried to implement a solution that way... especially > > for solutions significantly less trivial than mine. ;-) > > > Thanks > > > -- > > Derek D. Martinhttp://www.pizzashack.org/ > > GPG Key ID: 0x81CFE75D > > > ?application_pgp-signature_part > > < 1KViewDownload > > I would still watch that video which will explain a bit more about the > GIL. Thank you for the video! It's good to know, but it raises lots of other questions in my mind. Lots of examples would have helped. ~Sean From Brian.Mingus at colorado.edu Thu Aug 20 00:08:46 2009 From: Brian.Mingus at colorado.edu (Brian) Date: Wed, 19 Aug 2009 22:08:46 -0600 Subject: Read C++ enum in python In-Reply-To: <4a8b3342$0$25403$426a34cc@news.free.fr> References: <4a8b3342$0$25403$426a34cc@news.free.fr> Message-ID: <9839a05c0908192108w32148026r8112f1683010620a@mail.gmail.com> pygccxml http://www.language-binding.net/pygccxml/pygccxml.html It uses gccxml to compile your source code into xml, and then makes all of your source code available to you via a high level and convenient query interface in python. On Tue, Aug 18, 2009 at 5:03 PM, Ludo < olivier.anospamrnospamnnospamanospamenospamz at affaires.net> wrote: > Hello, > > I work in a very large project where we have C++ packages and pieces of > python code. > > I've been googleing for days but what I find seems really too complicated > for what I want to do. > > My business is, in python, to read enum definitions provided by the header > file of an c++ package. > Of course I could open the .h file, read the enum and transcode it by hand > into a .py file but the package is regularly updated and thus is the enum. > > My question is then simple : do we have : > - either a simple way in python to read the .h file, retrieve the > c++ enum and provide an access to it in my python script > - either a simple tool (in a long-term it would be automatically run > when the c++ package is compiled) generating from the .h file a .py file > containing the python definition of the enums ? > > Thank you for any suggestion. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 00:11:32 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 04:11:32 GMT Subject: How to create functors? References: <7xab1vl0qf.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 19 Aug 2009 18:42:32 -0700, Paul Rubin wrote: > Robert Dailey writes: >> I want to simply wrap a function up into an object so it can be called >> with no parameters. > > Nitpick: what you are asking for is called a closure. "Functor" means > something completely different. I'm glad somebody else noticed this. I would have said something about it myself, except I wasn't entirely sure my understanding of functor is correct. As near as I can tell, a functor is just an object which is callable like a function without actually being implemented as a function, e.g.: class Functor: def __call__(self): return None f = Functor() result = f() -- Steven From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 00:13:50 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 04:13:50 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> <87r5v8e9cu.fsf@benfinney.id.au> Message-ID: On Wed, 19 Aug 2009 10:51:08 -0700, Simon Forman wrote: > (FWIW, I've always admired Humpty Dumpty's attitude to words. "When I use a word," Humpty Dumpty said in rather a scornful tone, "it means just what I choose it to mean -- neither more nor less." When you say "admired", do you mean what the rest of us understand by "admired", or something completely different? How about "always", "attitude", "to" and "words"? For all I know, you're talking about baking a birthday cake for your cat, by which I mean shaving off all your hair, and by "hair" I mean "lunch" and by "shaving off" I mean "eating". > Have you > ever read R.A. Wilson's "Quantum Psychology"?) Perhaps I have, perhaps I haven't, it depends on who asks first. -- Steven From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 00:20:09 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 04:20:09 GMT Subject: How do I convert an iterator over bytes into a str? References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> <2c212222-0dac-4bd3-8130-5bd302d12dd5@c2g2000yqi.googlegroups.com> Message-ID: On Wed, 19 Aug 2009 20:04:12 -0700, alex23 wrote: > markscottwright wrote: >> Thanks Jan (and all other responders). ?I suppose I shouldn't be >> surprised - it's a known wart (http://wiki.python.org/moin/ >> PythonWarts), but it just looks so darn wrong. > > Don't forget that it's exceptionally easy to create your own mechanism > for doing this: > > def join(seq, sep): > return sep.join(map(str, seq)) Oh oh oh my brain hurts!!! Neither "seq" nor "sep" are real words, both are abbreviations, they differ by a single letter, and the two letters are mirror images of each other!!! This is a recipe for confusion when people get the order of sep and seq mixed up. Hopefully in real life code, you'd use a less easily confused function signature -- even just spelling out sequence and separator in full would reduce confusion to essentially zero. -- Steven From jsrat10 at gmail.com Thu Aug 20 00:34:22 2009 From: jsrat10 at gmail.com (jo) Date: Wed, 19 Aug 2009 21:34:22 -0700 (PDT) Subject: starting selenium rc server from python code Message-ID: Hi, Is there anyway to start the selenium rc server within python code? Thank you Jo From metolone+gmane at gmail.com Thu Aug 20 00:52:36 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Wed, 19 Aug 2009 21:52:36 -0700 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: "Gilles Ganault" wrote in message news:rtqk859vm3rkdfor0gd2u2pq5sftl8mccm at 4ax.com... >I find it odd that the regex library can't handle European characters It can. Read the documentation about the re.LOCALE flag. -Mark From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 01:17:21 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 05:17:21 GMT Subject: starting selenium rc server from python code References: Message-ID: On Wed, 19 Aug 2009 21:34:22 -0700, jo wrote: > Hi, > Is there anyway to start the selenium rc server within python code? How would you start the selenium rc server outside of Python code? -- Steven From narkewoody at gmail.com Thu Aug 20 01:31:14 2009 From: narkewoody at gmail.com (Steven Woody) Date: Thu, 20 Aug 2009 13:31:14 +0800 Subject: Blank Line at Program Exit Message-ID: Hi, Any python program, even that does absolutely nothing in the code, will cause a blank line printed out when the program exit. What's the reason? Thanks. -- Life is the only flaw in an otherwise perfect nonexistence -- Schopenhauer narke public key at http://subkeys.pgp.net:11371 (narkewoody at gmail.com) -------------- next part -------------- An HTML attachment was scrubbed... URL: From sajmikins at gmail.com Thu Aug 20 01:44:02 2009 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 19 Aug 2009 22:44:02 -0700 (PDT) Subject: #elements of seq A in seq B References: <7c16abe1-7502-432a-acff-aff95c22a8ac@q14g2000vbi.googlegroups.com> <285422cf-9a8d-43ef-a5ac-a04a3ce9a002@a39g2000pre.googlegroups.com> Message-ID: <02165547-8143-4f46-a74e-babe9145c033@s6g2000vbp.googlegroups.com> On Aug 19, 11:34?pm, John Machin wrote: > On Aug 20, 12:12?pm, Simon Forman wrote: > > > On Aug 19, 8:17?pm, "Jan Kaliszewski" wrote: > > > If you mean: to count non overlaping occurences of string A in B > > > -- simply: > > > > ? ?B.count(A) > > > You don't want to use count() in a case like this because it iterates > > through B len(A) times, i.e. this algorithm is O(A x B). > > There's seems to be multiple confusion here. Jan was talking about > counting non-overlapping occurrences of string A in [string] B. In > that case B.count(A) is nowhere near O(A*B)... in fact in reasonable > cases it is sub-linear i.e. O(B/A) > > Seehttp://svn.python.org/view/python/trunk/Objects/stringlib/fastsearch.... > > And even a naive implementation of str.count() would not "iterate > through B len(A) times". > > and list.count() can't be used on its own to solve Neal's problem; its > arg is a single element so it would have to be wrapped in a loop: sum > (B.count(a) for a in A) which would of course be O(A*B) First, thanks for pointing out str.count(). I didn't know of it and I didn't notice that that was what was being used in Jan's code. (It's blindingly obvious-- now that you've pointed it out. :] ) Second, I was referring to this: dict((element, B.count(element)) for element in A) not B.count(A). Sorry for not interspersing my comment better. Regards, ~Simon From rylesny at gmail.com Thu Aug 20 01:46:17 2009 From: rylesny at gmail.com (ryles) Date: Wed, 19 Aug 2009 22:46:17 -0700 (PDT) Subject: Setuptools - help! References: <9fauk6-t24.ln1@phoenix.fire> Message-ID: <9b2b4500-3670-40b7-8148-57448500c074@p15g2000vbl.googlegroups.com> On Aug 7, 3:04?pm, Peter Chant wrote: > Robert Kern wrote: > > You need to put main.py into the pphoto package. > > > $ mkdir pphoto/ > > $ mv main.py pphoto/ > > $ touch pphoto/__init__.py > > Thanks, it worked. ?Any ideas how to run the resulting scripts without > installing or running as root? > > Pete > > --http://www.petezilla.co.uk If you are using Python 2.6+ you have your own site-packages directory, e.g. ~/.local/lib/python2.6/site-packages. So, if this package is only for your own use, you can use easy_install's --install- dir option to have setuptools install it there, and can also set -- script-dir to ~/bin, where your console script will go. This, and other options are discussed here: http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations From __peter__ at web.de Thu Aug 20 02:10:28 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Aug 2009 08:10:28 +0200 Subject: Dictionary from a list References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: Jan Kaliszewski wrote: > 20-08-2009 o 02:05:57 Jan Kaliszewski wrote: > >> Or probably better: >> >> from itertools import islice, izip >> dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2))) > > Or similarly, perhaps more readable: > > iterator = iter(li) > dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2)) I just can't stop posting this one: >>> from itertools import izip >>> it = iter([1,2,3,4,5,6]) >>> dict(izip(it, it)) {1: 2, 3: 4, 5: 6} I really tried, but yours drove me over the edge. Peter From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 03:05:41 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 07:05:41 GMT Subject: Dictionary from a list References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: On Thu, 20 Aug 2009 08:10:28 +0200, Peter Otten wrote: > I just can't stop posting this one: > >>>> from itertools import izip >>>> it = iter([1,2,3,4,5,6]) >>>> dict(izip(it, it)) > {1: 2, 3: 4, 5: 6} > > I really tried, but yours drove me over the edge. If you want something to drive you over the edge: >>> alist = [1, 2, 3, 4, 5, 6] >>> dict(apply(zip, map(lambda n: map(lambda t: t[1], filter(lambda t: ((not (t[0]%2)) == 1) == n, enumerate(alist))), range(1, -1, -1)))) {1: 2, 3: 4, 5: 6} Enjoy :) -- Steven From pierre.gaillard at gmail.com Thu Aug 20 03:18:23 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Thu, 20 Aug 2009 00:18:23 -0700 (PDT) Subject: regular expression Message-ID: Hello, I would like to change the string "(1 and (2 or 3))" by "(x[1] & (x [2] || x[3]))" using regular expression... Anyone can help me ? Thanks. From rami.chowdhury at gmail.com Thu Aug 20 03:34:38 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 20 Aug 2009 00:34:38 -0700 Subject: How to create functors? In-Reply-To: References: <7xab1vl0qf.fsf@ruckus.brouhaha.com> Message-ID: <223ACEB9-09FE-4BBB-8B1D-25C66ABB46E3@gmail.com> > As near as I can tell, a functor is just an object which is > callable like a function I believe that's how they're defined in the C++ world, in which, of course, functions aren't first-class objects... ------------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Aug 19, 2009, at 21:11 , Steven D'Aprano wrote: > On Wed, 19 Aug 2009 18:42:32 -0700, Paul Rubin wrote: > >> Robert Dailey writes: >>> I want to simply wrap a function up into an object so it can be >>> called >>> with no parameters. >> >> Nitpick: what you are asking for is called a closure. "Functor" >> means >> something completely different. > > > I'm glad somebody else noticed this. I would have said something > about it > myself, except I wasn't entirely sure my understanding of functor is > correct. As near as I can tell, a functor is just an object which is > callable like a function without actually being implemented as a > function, e.g.: > > class Functor: > def __call__(self): > return None > > f = Functor() > result = f() > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 03:40:06 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 07:40:06 GMT Subject: regular expression References: Message-ID: On Thu, 20 Aug 2009 00:18:23 -0700, Pierre wrote: > Hello, > > I would like to change the string "(1 and (2 or 3))" by "(x[1] & (x > [2] || x[3]))" using regular expression... Anyone can help me ? Do you mean you want to change the string into "(x[1] & (x[2] || x[3]))" ? Does it have to be using regular expressions? Would this be good enough? >>> s = "(1 and (2 or 3))" >>> for c in '123': ... s = s.replace(c, 'x[%s]'%c) ... >>> s = s.replace('or', '||') >>> s = s.replace('and', '&') >>> s '(x[1] & (x[2] || x[3]))' -- Steven From __peter__ at web.de Thu Aug 20 03:45:37 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Aug 2009 09:45:37 +0200 Subject: Dictionary from a list References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: Steven D'Aprano wrote: > On Thu, 20 Aug 2009 08:10:28 +0200, Peter Otten wrote: > > >> I just can't stop posting this one: >> >>>>> from itertools import izip >>>>> it = iter([1,2,3,4,5,6]) >>>>> dict(izip(it, it)) >> {1: 2, 3: 4, 5: 6} >> >> I really tried, but yours drove me over the edge. > > If you want something to drive you over the edge: I meant that figuratively... >>>> alist = [1, 2, 3, 4, 5, 6] >>>> dict(apply(zip, map(lambda n: map(lambda t: t[1], filter(lambda t: > ((not (t[0]%2)) == 1) == n, enumerate(alist))), range(1, -1, -1)))) > {1: 2, 3: 4, 5: 6} ...originally. > Enjoy :) Not ;) From python.list at tim.thechases.com Thu Aug 20 03:47:25 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 20 Aug 2009 02:47:25 -0500 Subject: Dictionary from a list In-Reply-To: References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: <4A8CFF8D.9080405@tim.thechases.com> Peter Otten wrote: >>>> it = iter([1,2,3,4,5,6]) >>>> dict(izip(it, it)) > {1: 2, 3: 4, 5: 6} Zip(it). Zip(it) good. it's-3:00am-and-i-seriously-need-to-sleep'ly yers... -tkc From __peter__ at web.de Thu Aug 20 03:56:07 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Aug 2009 09:56:07 +0200 Subject: regular expression References: Message-ID: Pierre wrote: > I would like to change the string "(1 and (2 or 3))" by "(x[1] & (x > [2] || x[3]))" using regular expression... > Anyone can help me ? >>> re.compile(r"(\d+)").sub(r"x[\1]", "(1 and (2 or 3))") '(x[1] and (x[2] or x[3]))' >>> re.compile("and|or").sub(lambda m, d={"and":"&", "or":"||"}: d[m.group()], _) '(x[1] & (x[2] || x[3]))' Peter From catalinfest at gmail.com Thu Aug 20 04:23:39 2009 From: catalinfest at gmail.com (catafest) Date: Thu, 20 Aug 2009 01:23:39 -0700 (PDT) Subject: PIL and Python References: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> Message-ID: On my photo jpg i have this : Image Type: jpeg (The JPEG image format) Width: 1224 pixels Height: 1632 pixels Camera Brand: Sony Ericsson Camera Model: W810i Date Taken: 2009:07:09 08:16:21 Exposure Time: 1/19 sec. ISO Speed Rating: 320 Flash Fired: Flash did not fire, compulsory flash mode. Metering Mode: Center-Weighted Average Software: R4EA031 prgCXC1250321_ORANGE_HN 4.5 This is the data i want edit it to make some copyright for my site. From http Thu Aug 20 04:36:14 2009 From: http (Paul Rubin) Date: 20 Aug 2009 01:36:14 -0700 Subject: How to create functors? References: <7xab1vl0qf.fsf@ruckus.brouhaha.com> Message-ID: <7xmy5uanlt.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > As near as I can tell, a functor is just an object which is > callable like a function without actually being implemented as a > function, e.g.: No it's not anything like that either, at least as I'm used to the term in programming or in mathematics. Maybe it's used other ways though. As I'm used to it, it's a feature of certain static type systems. The notion isn't that useful in Python but you could translate it something like this: imagine that the "list" datatype has a couple extra operations: # lift_value turns a normal value from a base type to a 1-element list list.lift_value(x) = [x] # lift_function turns a function on a base type to a higher order # function that operates on a whole list list.lift_function(f) = partial(map, f) Then given a function like def square(x): return x*x you could say lifted_square = list.lifted_function(square) print lifted_square([1,2,3,4,5]) and get [1,4,9,16,25]. Similarly if you had some other type (like a tree data structure), that type could also support a map-like operation so you could lift functions to it (lifting a function and applying it to a tree like [1,[2,3],4] would result in [1,[4,9],16] or whatever). If I remember properly, for type t to be a functor it needs the above two lifting operations, with the property that for a given function f, t.lifted_value(f(x)) = (t.lifted_function(f))(t.lifted_value(x)) I guess this explanation isn't going that well but basically in a statically typed language you'd use functors to convert the signatures of functions to versions that operate on higher types. The idea comes from ML and is used explicitly in Haskell, and I think some of the C++ standard template library can be explained in terms of functors. For the mathematical concept of functors and how they relate to programming (at least Haskell's version), see: http://en.wikibooks.org/Haskell/Category_theory From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 05:25:48 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 09:25:48 GMT Subject: How to create functors? References: <7xab1vl0qf.fsf@ruckus.brouhaha.com> <7xmy5uanlt.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 20 Aug 2009 01:36:14 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> As near as I can tell, a functor is just an object which is callable >> like a function without actually being implemented as a function, e.g.: > > No it's not anything like that either, at least as I'm used to the term > in programming or in mathematics. Maybe it's used other ways though. According to Wikipedia, functor can be used as a synonym for "function object": http://en.wikipedia.org/wiki/Function_object which is what I was thinking of. So it seems there are at least two meanings for the word, neither of which seems to apply to this thread :) > As I'm used to it, it's a feature of certain static type systems. The > notion isn't that useful in Python I find the Haskell page entirely opaque and unintelligible. Well, perhaps not *entirely* opaque, but pretty close: it assumes a mathematical sophistication that I don't think I even had when I was getting my maths degree, let alone can remember two decades later. (Pity the poor VB coders wondering what Haskell is good for...) The Wikipedia page is a little better, but it's section on Examples is laughable -- the examples are as unintelligible to this reader as the description before them. But let me try an example to see if I've got it right: class Int2StrFunctor: def map1(self, n): if type(n) is not int: raise TypeError('argument must be an int') return "-"*n def map2(self, f): if type(f) is not type(lambda: None): raise TypeError('argument must be a function') # assume f takes an int, and returns another int def inner(n): return self.map1(f(n)) return inner The functor can take an int and return a string: >>> F = Int2StrFunctor() # F is a functor >>> F.map1(3) '---' It can also take a function (of int -> int) and return a new function (int -> str): >>> def myfunc(n): ... return n+2 ... >>> f = F.map2(myfunc) >>> f(3) '-----' >>> f(4) '------' There's nothing special about the methods map1() and map2(), I could call them anything I like, or even do this: >>> def __call__(self, arg): ... if type(arg) is int: ... return self.map1(arg) ... else: ... return self.map2(arg) ... >>> Int2StrFunctor.__call__ = __call__ >>> >>> F(2) '--' >>> F(myfunc)(0) '--' There are some technical restrictions on functors, relating to the sorts of functions and types (strictly "categories") they can accept, presumably to make them mathematically well-behaved. Have I got it correct? -- Steven From nitebirdz at sacredchaos.com Thu Aug 20 05:46:34 2009 From: nitebirdz at sacredchaos.com (Nitebirdz) Date: Thu, 20 Aug 2009 11:46:34 +0200 Subject: What file is foo in package bar in ? In-Reply-To: References: Message-ID: <20090820094633.GD7136@sevilla.sacredchaos.com> On Thu, Aug 20, 2009 at 01:06:00AM +0200, Christian Heimes wrote: > northof40 wrote: >> Given an arbitary package is there some programmatic way to 'ask' what >> file the method/function is implemented in ? > > Indeed, the inspect module contains several useful functions for the > job, for example > http://docs.python.org/library/inspect.html#inspect.getfile > Stupid question from someone who ignores it all: since the OP is reading code from an existing tree in order to learn from it, wouldn't it make more sense to use something like Cscope? Assuming it works with Python, of course. If it doesn't, is there a similar tool that can be used? A related question too is whether any of these tools actually help in an object-oriented environment. http://cscope.sourceforge.net/ http://www.linux.com/archive/feature/114237 From enleverLesX_XXmcX at XmclavXeauX.com Thu Aug 20 05:54:05 2009 From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP) Date: Thu, 20 Aug 2009 11:54:05 +0200 Subject: difference between 2 arrays References: Message-ID: <4a8d1d3f$0$23447$ba4acef3@news.orange.fr> (envoy? via news:\\news.wanadoo.fr\comp.lang.python) Hi! Yes, the module sets is written, in doc, like "deprecated". But: - sets exist in Python 2.6 (& 2.5 or 2.4) - documentation of sets (module) is better tha, documentation of set (builtin) The best: read the documentaion of the module, and use the builtin... @-salutations -- MCI From ashwin.u.rao at nokia.com Thu Aug 20 06:02:26 2009 From: ashwin.u.rao at nokia.com (ashwin.u.rao at nokia.com) Date: Thu, 20 Aug 2009 12:02:26 +0200 Subject: Zipimport leaks memory? Message-ID: <6CC019B5D220A147932441E798B252B910B0193FEF@NOK-EUMSG-05.mgdnok.nokia.com> Hi, We are currently trying to identify and fix all the memory leaks by just doing Py_Initialize-PyRun_SimpleFile(some simple script)-Py_Finalize and found that there are around 70 malloc-ed blocks which are not freed. One of the significant contributor to this number is the 'files' object in ZipImporter. I am not able to identify the reason for this leak and was wondering if anyone on this list would help me out here. So, here goes : Since we have a zip file in our sys.path, this object is initialized and added to the zip_directory_cache dict during Py_Initialize. One point to note here is that there is no DECREF on the 'files' object after adding it to the zip_directory_cache dict. When a module in a directory is imported(encoding.alias) then the reference count of 'files' is increased. When this module is unloaded during Py_Finalize-PyImport_Cleanup, the ref count of files object is decremented properly. So at the end of Py_Finalize the files object still has one reference count which is a result of it being an entry in the zip_directory_cache. To summarize : ZipImporter->files - zipimporter_init function: Py_Initialize - Read files from zip - ref_count -1 Add files to zip_directory_cache - ref count - 2 Import some modules from different directory in zip - ref count - 3 Py_Finalze - PyImport_Cleanup - sub-directory - ref-count - 2 PyImport_Cleanup - main directory - ref-count - 1 So the reference count of 'files' is still 1 after Py_Finalize. The zip_directory_cache is the dict that has this 'files' object and this dict is added to the module during zipimport module initialization. This dict is destroyed during _PyModule_Clear(called by PyImport_Cleanup) but the 'files' object's reference count is not decremented. Please excuse me if I have misinterpreted the whole logic. Any pointers towards solving this would be great. Thank you. ~Ashwin From iain at kandaba.com Thu Aug 20 06:19:56 2009 From: iain at kandaba.com (Iain) Date: Thu, 20 Aug 2009 03:19:56 -0700 (PDT) Subject: Polling a net address Message-ID: <99ddf4e1-d327-4fb1-aee4-aa881de3b3af@d23g2000vbm.googlegroups.com> Hi All, I'm writing a system tray application for windows, and the app needs to poll a remote site at a pre-defined interval, and then process any data returned. The GUI needs to remain responsive as this goes on, so the polling needs to be done in the background. I've been looking into Twisted as a way of achieving this, but can't seem to get anything to loop successfully. Does anyone have any pointers that they might be able to give me? TIA. From baaluaanand at gmail.com Thu Aug 20 06:24:15 2009 From: baaluaanand at gmail.com (baalu aanand) Date: Thu, 20 Aug 2009 03:24:15 -0700 (PDT) Subject: difference between raw_input() and input() Message-ID: <3c91915d-bcb1-4ea9-9b37-6b30ea0588a0@e34g2000vbm.googlegroups.com> Hi, I have used both raw_input() and input() for a same input value. But these gives different output. I have listed below what actually I have done >>> a = raw_input("===>") ===> 023 >>> a '023' I have given the same value for the input() but it gives 19 as result >>> a = input("===>") ===> 023 >>> a 19 Is there anything hide within this. Please illustrate the difference between raw_input() and input() Thanks in advance Baalu From clp2 at rebertia.com Thu Aug 20 06:49:42 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 20 Aug 2009 03:49:42 -0700 Subject: difference between raw_input() and input() In-Reply-To: <3c91915d-bcb1-4ea9-9b37-6b30ea0588a0@e34g2000vbm.googlegroups.com> References: <3c91915d-bcb1-4ea9-9b37-6b30ea0588a0@e34g2000vbm.googlegroups.com> Message-ID: <50697b2c0908200349i5e0a13aeq63252c162fbfe492@mail.gmail.com> On Thu, Aug 20, 2009 at 3:24 AM, baalu aanand wrote: > Hi, > > ? ? I have used both raw_input() and input() for a same input value. > But these gives different output. > > ? ? I have listed below what actually I have done > > ? ? ? ? ? ?>>> a = raw_input("===>") > ? ? ? ? ? ? ? ? ? ===> 023 > ? ? ? ? ? ?>>> a > ? ? ? ? ? ? ? ? ? ?'023' > > ? ? I have given the same value for the input() but it gives 19 as > result > ? ? ? ? ? ?>>> a = input("===>") > ? ? ? ? ? ? ? ? ? ===> ?023 > ? ? ? ? ? ?>>> a > ? ? ? ? ? ? ? ? ? ?19 > > ?Is there anything hide within this. Please illustrate the difference > between raw_input() and input() input() === eval(raw_input()) eval("023") --> int("23", 8) --> 19 [an integer, not a string] raw_input() /always/ returns a string. Never use input() in Python 2.x. In Python 3, raw_input() was renamed to input() because it's a better name and the old input() was hardly ever used (correctly). Cheers, Chris -- http://blog.rebertia.com From ashagow at gmail.com Thu Aug 20 06:50:27 2009 From: ashagow at gmail.com (Asha Gowda) Date: Thu, 20 Aug 2009 16:20:27 +0530 Subject: pexpect on QNX platform Message-ID: <375470f50908200350n57ce3e7csccd83ddad08e7de9@mail.gmail.com> Hi, I found that pexpect is available only for linux. But we need to port to QNX, Is pexpect is available? If yes, where can I find it. Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxthemouse at googlemail.com Thu Aug 20 07:01:20 2009 From: maxthemouse at googlemail.com (MaxTheMouse) Date: Thu, 20 Aug 2009 04:01:20 -0700 (PDT) Subject: PIL and Python References: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> Message-ID: On Aug 20, 10:23?am, catafest wrote: > On my photo jpg i have this : > > Image Type: jpeg (The JPEG image format) > Width: 1224 pixels > Height: 1632 pixels > Camera Brand: Sony Ericsson > Camera Model: W810i > Date Taken: 2009:07:09 08:16:21 > Exposure Time: 1/19 sec. > ISO Speed Rating: 320 > Flash Fired: Flash did not fire, compulsory flash mode. > Metering Mode: Center-Weighted Average > Software: R4EA031 ? ? prgCXC1250321_ORANGE_HN 4.5 > > This is the data i want edit it to make some copyright for my site. I don't know about PIL but you might want to try exif.py. http://sourceforge.net/projects/exif-py/ From ndbecker2 at gmail.com Thu Aug 20 07:01:29 2009 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 20 Aug 2009 07:01:29 -0400 Subject: #elements of seq A in seq B References: Message-ID: Jan Kaliszewski wrote: > 20-08-2009 o 01:19:24 Neal Becker wrote: > >> What would be a time efficient way to count the number of occurrences of >> elements of sequence A in sequence B? (in this particular case, these >> sequences are strings, if that matters). > > If you mean: to count occurences of each element of A (separately) in B... > > Hm, maybe something like this: > > # result as a dict {: , ...} > dict((element, B.count(element)) for element in A) > > > If you mean: to count non overlaping occurences of string A in B > -- simply: > > B.count(A) > > > Regards, > *j > I meant #occurrences of characters from the set A in string B From muhammadsalman712 at gmail.com Thu Aug 20 07:17:41 2009 From: muhammadsalman712 at gmail.com (Muhammad Salman) Date: Thu, 20 Aug 2009 04:17:41 -0700 (PDT) Subject: New Windows Mobile Smartphones from I-mate Message-ID: Windows Mobile smart phone device manufacturer, i-mate has shown off its latest models -the Ultimate 9502 and the Ultimate 8502.for other details http://infomobilepk.blogspot.com From __peter__ at web.de Thu Aug 20 08:05:12 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Aug 2009 14:05:12 +0200 Subject: #elements of seq A in seq B References: Message-ID: Neal Becker wrote: > I meant #occurrences of characters from the set A in string B If a contains "few" characters: n = sum(b.count(c) for c in a) If a contains "many" characters: identity = "".join(map(chr, range(256))) n = len(b) - len(b.translate(identity, a)) Peter From ballacky13 at gmail.com Thu Aug 20 08:07:31 2009 From: ballacky13 at gmail.com (Yan Jian) Date: Thu, 20 Aug 2009 20:07:31 +0800 Subject: Hi everyone, I get a problem when using binhex module Message-ID: Below is what I copy from the Internet: import binhex import sys infile = "in.txt" binhex.binhex(infile, sys.stdout) Every time I try to run this script, I get a message saying Traceback (most recent call last): File "D:\eclipse_workspace\encode\src\binhex.sample.py", line 6, in import binhex File "C:\Python25\lib\binhex.py", line 12, in # easy interface should work "as expected" on any platform. TypeError: 'module' object is not callable Does anyone encounter similar situation. Thank you for your help? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jelleferinga at gmail.com Thu Aug 20 08:19:42 2009 From: jelleferinga at gmail.com (jelle) Date: Thu, 20 Aug 2009 05:19:42 -0700 (PDT) Subject: pypi category Message-ID: Hi, Would someone be able to inform me how a category can be added to the pypy list of categories? I'd like to add a CAD & Geometry category. ( I develop PythonOCC, wrappers for the OpenCASCADE CAD kernel, which is why ) Thanks! -jelle From contact at xavierho.com Thu Aug 20 08:20:32 2009 From: contact at xavierho.com (Xavier Ho) Date: Thu, 20 Aug 2009 22:20:32 +1000 Subject: Hi everyone, I get a problem when using binhex module In-Reply-To: References: Message-ID: <2d56febf0908200520n697ae725v4e0a2abcc3a10c11@mail.gmail.com> On Thu, Aug 20, 2009 at 10:07 PM, Yan Jian wrote: > > Does anyone encounter similar situation. Thank you for your help? > Yeah, in Python 3.1 I get this: Traceback (most recent call last): File "test.py", line 6, in binhex.binhex(file, sys.stdout) File "c:\Python31\lib\binhex.py", line 228, in binhex ofp = BinHex(finfo, out) File "c:\Python31\lib\binhex.py", line 149, in __init__ ofp.write(b'(This file must be converted with BinHex 4.0)\r\r:') TypeError: write() argument 1 must be str, not bytes Python 2.6.2 runs fine though: :"QPZ,R4iG!"849K82j!%!*!&&3#3"1#$6A*bB@%Z$3T0FR*KB5iJ6A*bB@%ZY@% !!!: I never used binhex however, so someone else might have a better insight. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From aaron.watters at gmail.com Thu Aug 20 08:21:54 2009 From: aaron.watters at gmail.com (Aaron Watters) Date: Thu, 20 Aug 2009 05:21:54 -0700 (PDT) Subject: Data visualization in Python References: Message-ID: <15325820-dae0-4ba4-b25a-d33e17908fde@p15g2000vbl.googlegroups.com> On Aug 17, 3:10?pm, kj wrote: > I'm looking for a good Python package for visualizing > scientific/statistical data. ?(FWIW, the OS I'm interested in is > Mac OS X). Please take a look at the amcharts embedding in WHIFF http://aaron.oirt.rutgers.edu/myapp/amcharts/doc WHIFF is a collection of support services for WSGI applications which allows applications to be composed by "dropping" dynamic pages into container directories. http://aaron.oirt.rutgers.edu/myapp/docs/W.intro thanks, -- Aaron Watters === Sisyphus got ripped. From andre.roberge at gmail.com Thu Aug 20 09:11:30 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Thu, 20 Aug 2009 06:11:30 -0700 (PDT) Subject: IDLE is not as interactive as Maple References: <7aa51a98-965c-4c74-a3b5-650140f1d589@v23g2000pro.googlegroups.com> Message-ID: <399082f9-3765-46dc-b71e-618e75256cf9@d34g2000vbm.googlegroups.com> On Aug 20, 12:22?am, laser wrote: > In the future, will Python provide programe enviroment like Maple > does? A quick, flip answer: perhaps if you design one? Tools for Python are designed by people scratching an itch. That being said, have a look at reinteract: http://www.reinteract.org/trac/wiki/Tutorial/Introduction > In Maple, you can remove anything unneeded in the editor. And > the code execution order are not necessary in one direction. You can > run any command line on the screen by > push Enter key. These functions gave a lot of flaxibility for users to > start with programming something. Andr? From benjamin.kaplan at case.edu Thu Aug 20 09:29:45 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 20 Aug 2009 09:29:45 -0400 Subject: IDLE is not as interactive as Maple In-Reply-To: <7aa51a98-965c-4c74-a3b5-650140f1d589@v23g2000pro.googlegroups.com> References: <7aa51a98-965c-4c74-a3b5-650140f1d589@v23g2000pro.googlegroups.com> Message-ID: On Wed, Aug 19, 2009 at 11:22 PM, laser wrote: > In the future, will Python provide programe enviroment like Maple > does? In Maple, you can remove anything unneeded in the editor. And > the code execution order are not necessary in one direction. You can > run any command line on the screen by > push Enter key. These functions gave a lot of flaxibility for users to > start with programming something. > -- > http://mail.python.org/mailman/listinfo/python-list > Maple is a very expensive IDE that happens to have a language that goes with it. Python is a language that happens to come with a free text editor/integrated shell. For languages like Mathematica and Maple, the IDE is everything- you almost never use the language without the integrated IDE. Python focuses more on language features. IDLE is not supposed to be a great editor on the level of Visual Studio or Maple, it's supposed to be a convenient way to run your code for people who are scared of the command line. I would venture a guess that very few people on this list use IDLE for their coding. Based on previous answers to questions, most people use Eclipse/PyDev, Netbeans, Wing, Komodo, emacs, and vim. Wing and Komodo are the only Python-specific IDEs on that list and neither of them are free (though the have stripped-down free versions). If you want a better editor, use one of those. From haricibi83 at gmail.com Thu Aug 20 09:44:52 2009 From: haricibi83 at gmail.com (hari) Date: Thu, 20 Aug 2009 06:44:52 -0700 (PDT) Subject: Python libexpat and EXPAT are same/Different? Message-ID: Hi all, Am very new to XML, I have a query, Does Python libexpat and EXPAT are same or they are diffrent? Thanks in advance. Regards, Hari From stefan_ml at behnel.de Thu Aug 20 10:05:21 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 20 Aug 2009 16:05:21 +0200 Subject: Python libexpat and EXPAT are same/Different? In-Reply-To: References: Message-ID: <4a8d5821$0$30236$9b4e6d93@newsspool1.arcor-online.net> hari wrote: > Am very new to XML, I have a query, Does Python libexpat and EXPAT > are same or they are diffrent? Depends on what you mean with "EXPAT". Python's expat module that you can find in the standard library is the well known non-validating XML parser originally written by James Clark. BTW, if you are new to XML and want to use it in Python, you might want to start with the xml.etree package. Stefan From jelleferinga at gmail.com Thu Aug 20 10:10:26 2009 From: jelleferinga at gmail.com (jelle) Date: Thu, 20 Aug 2009 07:10:26 -0700 (PDT) Subject: pypi category References: Message-ID: The pypi list of categories, sorry... From sturlamolden at yahoo.no Thu Aug 20 10:25:59 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Aug 2009 07:25:59 -0700 (PDT) Subject: IDLE is not as interactive as Maple References: <7aa51a98-965c-4c74-a3b5-650140f1d589@v23g2000pro.googlegroups.com> Message-ID: On 19 Aug, 20:22, laser wrote: > In the future, will Python provide programe enviroment like Maple > does? You might be looking for SAGE. http://www.sagemath.org/ From steve at REMOVE-THIS-cybersource.com.au Thu Aug 20 10:54:04 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 14:54:04 GMT Subject: difference between raw_input() and input() References: <3c91915d-bcb1-4ea9-9b37-6b30ea0588a0@e34g2000vbm.googlegroups.com> Message-ID: <029d53bb$0$25987$c3e8da3@news.astraweb.com> On Thu, 20 Aug 2009 03:24:15 -0700, baalu aanand wrote: > Hi, > > I have used both raw_input() and input() for a same input value. > But these gives different output. > > I have listed below what actually I have done > > >>> a = raw_input("===>") > ===> 023 > >>> a > '023' > > I have given the same value for the input() but it gives 19 as > result > >>> a = input("===>") > ===> 023 > >>> a > 19 > > Is there anything hide within this. Please illustrate the difference > between raw_input() and input() Did you look them up in the documentation? Did you try the interactive help? help(input) help(raw_input) Perhaps you could try some further experiments: >>> raw_input() hello world 'hello world' >>> input() hello world Traceback (most recent call last): File "", line 1, in File "", line 1 hello world ^ SyntaxError: unexpected EOF while parsing Does that give you a hint as to what is happening? How about this? >>> 07 7 >>> 08 File "", line 1 08 ^ SyntaxError: invalid token >>> 010 8 >>> oct(8) 010 -- Steven From davea at ieee.org Thu Aug 20 11:08:07 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 20 Aug 2009 11:08:07 -0400 Subject: Hi everyone, I get a problem when using binhex module In-Reply-To: References: Message-ID: <4A8D66D7.4070006@ieee.org> Yan Jian wrote: > Below is what I copy from the Internet: > > import binhex > import sys > > infile = "in.txt" > > binhex.binhex(infile, sys.stdout) > > Every time I try to run this script, I get a message saying > > Traceback (most recent call last): > File "D:\eclipse_workspace\encode\src\binhex.sample.py", line 6, in > > import binhex > File "C:\Python25\lib\binhex.py", line 12, in > # easy interface should work "as expected" on any platform. > TypeError: 'module' object is not callable > > Does anyone encounter similar situation. Thank you for your help? > > First question: Are you running Python2.5 ? And do you actually have it installed in c:\Python25 directory? Do you in fact have 5 blank lines in front of the "import binhex" line? Assuming yes for all of those, the only cause I can figure for that particular error string is that binhex.pyc is out of synch with binhex.py. To test that theory, try deleting it (in general that means renaming it temporarily, so you could restore it if I'm wrong), and running again. I would also add the lines: import sys print sys.version in front of the import, just to make sure you're running what you think you are. And then I'd get a console prompt, change directory to D:\eclipse_workspace\encode\src\binhex and run sample.py from that command prompt. Compare the two version strings, and see if anything's different in the two error messages. DaveA From manu3d at gmail.com Thu Aug 20 11:16:51 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 20 Aug 2009 08:16:51 -0700 (PDT) Subject: Executing untrusted code References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com> Message-ID: Sorry for digging this back from the grave. I've had to chew on it for a little while. On Aug 8, 1:40?am, Nobody wrote: > If you want to support restricted execution within a language, it > has to be built into the language from day one. Trying to bolt it > on later is a fool's errand. Fair enough. In this context, let's say I do this: import __builtin__ import imp originalBuiltins = imp.new_module("OriginalBuiltins") def readOnlyOpen(filename): return originalBuiltins.open(filename, "r") __builtin__.open = readOnlyOpen exec(anUntrustedString, {}) In what ways would the untrusted string be able to obtain the original, built-in open function and open a file for writing? Manu From lists at cheimes.de Thu Aug 20 11:26:33 2009 From: lists at cheimes.de (Christian Heimes) Date: Thu, 20 Aug 2009 17:26:33 +0200 Subject: Executing untrusted code In-Reply-To: References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com> Message-ID: <4A8D6B29.3040800@cheimes.de> Emanuele D'Arrigo write: > In what ways would the untrusted string be able to obtain the > original, built-in open function and open a file for writing? Yes, if you know some tricks: >>> [cls for cls in object.__subclasses__() if cls.__name__ == 'file'][0] Christian From rami.chowdhury at gmail.com Thu Aug 20 11:27:24 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 20 Aug 2009 08:27:24 -0700 Subject: Executing untrusted code In-Reply-To: References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com> Message-ID: They could, of course, use the file object constructor directly, e.g.: f = file("/etc/passwd", "w") On Thu, 20 Aug 2009 08:16:51 -0700, Emanuele D'Arrigo wrote: > Sorry for digging this back from the grave. > I've had to chew on it for a little while. > > On Aug 8, 1:40?am, Nobody wrote: >> If you want to support restricted execution within a language, it >> has to be built into the language from day one. Trying to bolt it > on >> later is a fool's errand. > > Fair enough. In this context, let's say I do this: > > import __builtin__ > import imp > originalBuiltins = imp.new_module("OriginalBuiltins") > > def readOnlyOpen(filename): > return originalBuiltins.open(filename, "r") > > __builtin__.open = readOnlyOpen > > exec(anUntrustedString, {}) > > In what ways would the untrusted string be able to obtain the > original, built-in open function and open a file for writing? > > Manu > -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From narkewoody at gmail.com Thu Aug 20 12:06:55 2009 From: narkewoody at gmail.com (Steven Woody) Date: Fri, 21 Aug 2009 00:06:55 +0800 Subject: line completion Message-ID: Hi, I wrote a program that takes some user input. Many inputs are quit often used by user, so when a user launch the program, and type in "The Sha", he wants to get "wshank Redemption" displayed automatically in reversed color (black text on white background) along his cursor. When he decided to use "The Shawshank Redemption", he just press the enter key, otherwise, he type in other words anyway. My question is, is there any module that can easy the implementation of this feature? Thanks. -- Life is the only flaw in an otherwise perfect nonexistence -- Schopenhauer narke public key at http://subkeys.pgp.net:11371 (narkewoody at gmail.com) -------------- next part -------------- An HTML attachment was scrubbed... URL: From inigoserna at gmail.com Thu Aug 20 12:36:05 2009 From: inigoserna at gmail.com (=?UTF-8?B?ScOxaWdvIFNlcm5h?=) Date: Thu, 20 Aug 2009 18:36:05 +0200 Subject: ncurses getch & unicode (was: decoding keyboard input when using curses) Message-ID: <65a1d6f80908200936g18b235fcw49d0047168cf9548@mail.gmail.com> Hello, I have the same problem mentioned in http://groups.google.com/group/comp.lang.python/browse_thread/thread/c70c80cd9bc7bac6?pli=1some months ago. Python 2.6 program which uses ncurses module in a terminal configured to use UTF-8 encoding. When trying to get input from keyboard, a non-ascii character (like ?) is returned as 2 integers < 255, needing 2 calls to getch method to get both. These two integers \xc3 \xa7 forms the utf-8 encoded representation of ? character. ncurses get_wch documentation states the function should return an unique integer > 255 with the ordinal representation of that unicode char encoded in UTF-8, \xc3a7. [Please, read the link above, it explains the issue much better that what I could do.] Any idea or update on this? Thanks, I?igo Serna PS: my system is a Linux Fedora 11 x86_64. Same happens on console, gnome-terminal or xterm. -------------- next part -------------- An HTML attachment was scrubbed... URL: From israelu at elbit.co.il Thu Aug 20 12:41:14 2009 From: israelu at elbit.co.il (iu2) Date: Thu, 20 Aug 2009 09:41:14 -0700 (PDT) Subject: Dictionary from a list References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: <04452fa5-b76f-4e5d-93f3-6348ca466bc8@b15g2000yqd.googlegroups.com> On Aug 20, 9:10?am, Peter Otten <__pete... at web.de> wrote: > Jan Kaliszewski wrote: > > 20-08-2009 o 02:05:57 Jan Kaliszewski wrote: > > >> Or probably better: > > >> ? ? ?from itertools import islice, izip > >> ? ? ?dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2))) > > > Or similarly, perhaps more readable: > > > ? ? ?iterator = iter(li) > > ? ? ?dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2)) > > I just can't stop posting this one: > > >>> from itertools import izip > >>> it = iter([1,2,3,4,5,6]) > >>> dict(izip(it, it)) > > {1: 2, 3: 4, 5: 6} > > I really tried, but yours drove me over the edge. > > Peter Nice. (but looks like stepping towards the dark side ... :-) I also liked this one: iterator = iter(li) dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2)) which inspired me to do something quite similar: a=range(1, 11) >>> a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> dict([[a.pop(0), a.pop(0)] for i in range(len(a)/2)]) {1: 2, 3: 4, 9: 10, 5: 6, 7: 8} Thanks From tim.arnold at sas.com Thu Aug 20 13:21:34 2009 From: tim.arnold at sas.com (Tim Arnold) Date: Thu, 20 Aug 2009 13:21:34 -0400 Subject: 2.6 windows install Message-ID: Hi, I installed python2.6 to a netapp device. I can use it from my local windows machine (XP). But others cannot use it from their pcs. They get this response "The system cannot execute the specified program.". If they double click on python.exe, they get a window with: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. When I installed it I didn't see any mention of an 'administrators' install, it just installed. The permissions on the directories where it installed are set wide-open for everyone. Any ideas on what I'm missing here? thanks, --Tim Arnold From dullrich at sprynet.com Thu Aug 20 14:13:35 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Thu, 20 Aug 2009 13:13:35 -0500 Subject: Silly question Message-ID: I just noticed that sequence[i:j:k] syntax in a post here. When did this happen? (I'm just curious whether it existed in 1.5.x or not. If so I'm stupid - otoh if it was introduced in 2.x I'm just slow...) From benjamin.kaplan at case.edu Thu Aug 20 14:36:35 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 20 Aug 2009 14:36:35 -0400 Subject: Silly question In-Reply-To: References: Message-ID: On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrich wrote: > I just noticed that > > ?sequence[i:j:k] > > syntax in a post here. When did this happen? > > (I'm just curious whether it existed in 1.5.x or not. > If so I'm stupid - otoh if it was introduced in 2.x > I'm just slow...) > Well, I got some good news and some bad news. According to the docs, it existed in 1.4 but the built-in sequences didn't support it until 2.3. It's not used that often anyway so you haven't been missing much. http://www.python.org/doc/2.3.5/whatsnew/section-slices.html From steve at REMOVE-THIS-cybersource.com.au Thu Aug 20 14:38:09 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 18:38:09 GMT Subject: Executing untrusted code References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com> Message-ID: <029d8840$0$25987$c3e8da3@news.astraweb.com> On Thu, 20 Aug 2009 08:16:51 -0700, Emanuele D'Arrigo wrote: > Fair enough. In this context, let's say I do this: > > import __builtin__ > import imp > originalBuiltins = imp.new_module("OriginalBuiltins") > > def readOnlyOpen(filename): > return originalBuiltins.open(filename, "r") > > __builtin__.open = readOnlyOpen Have you actually tested this? I don't think it works the way you think it does. >>> import __builtin__ >>> import imp >>> originalBuiltins = imp.new_module("OriginalBuiltins") >>> originalBuiltins.open Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'open' So your strategy fails to provide read-only file access. But moving on... > In what ways would the untrusted string be able to obtain the original, > built-in open function and open a file for writing? That's hardly even a challenge. >>> __builtin__.open = readOnlyOpen >>> anUntrustedString = """import __builtin__ ... reload(__builtin__) ... open('junk', 'w').write('a') ... """ >>> exec(anUntrustedString, {}) >>> open('junk').read() 'a' Not only have I broken your "read only" open within the call to exec, but I've broken it outside as well. With a little bit more effort, I could probably save and restore the open, so that my untrusted string could write to files inside the exec(), but code outside of the exec() would still see the readOnlyOpen. -- Steven From duncan.booth at invalid.invalid Thu Aug 20 14:41:34 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Aug 2009 18:41:34 GMT Subject: Silly question References: Message-ID: David C Ullrich wrote: > I just noticed that > > sequence[i:j:k] > > syntax in a post here. When did this happen? > > (I'm just curious whether it existed in 1.5.x or not. > If so I'm stupid - otoh if it was introduced in 2.x > I'm just slow...) > > Googling for 'python extended slice' returns this as the first hit: http://www.python.org/doc/2.3.5/whatsnew/section-slices.html > 15 Extended Slices > > Ever since Python 1.4, the slicing syntax has supported an optional > third ``step'' or ``stride'' argument. For example, these are all > legal Python syntax: L[1:10:2], L[:-1:1], L[::-1]. This was added to > Python at the request of the developers of Numerical Python, which > uses the third argument extensively. However, Python's built-in list, > tuple, and string sequence types have never supported this feature, > raising a TypeError if you tried it. Michael Hudson contributed a > patch to fix this shortcoming. So extended slices have existed since Python 1.4, but builtin types only started to support them from 2.3. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 20 14:42:24 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 18:42:24 GMT Subject: Executing untrusted code References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com> Message-ID: <029d893f$0$25987$c3e8da3@news.astraweb.com> On Thu, 20 Aug 2009 08:16:51 -0700, Emanuele D'Arrigo wrote: > In what ways would the untrusted string be able to obtain the original, > built-in open function and open a file for writing? On a related topic, you should read this post here: http://tav.espians.com/a-challenge-to-break-python-security.html -- Steven From 71david at libero.it Thu Aug 20 15:06:43 2009 From: 71david at libero.it (David) Date: Thu, 20 Aug 2009 21:06:43 +0200 Subject: Annoying octal notation Message-ID: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Hi all, Is there some magic to make the 2.x CPython interpreter to ignore the annoying octal notation? I'd really like 012 to be "12" and not "10". If I want an octal I'll use oct()! "Explicit is better than implicit..." TIA David From info at wingware.com Thu Aug 20 15:21:42 2009 From: info at wingware.com (Wingware) Date: Thu, 20 Aug 2009 15:21:42 -0400 Subject: ANN: Wing IDE 3.2 released Message-ID: <4A8DA246.9030908@wingware.com> Hi, Wingware has released version 3.2.0 final of Wing IDE, our integrated development environment for the Python programming language. *Release Highlights* This release includes the following new features: * Support for Python 3.0 and 3.1 * Rewritten version control integration with support for Subversion, CVS, Bazaar, git, Mercurial, and Perforce (*) * Added 64-bit Debian, RPM, and tar file installers for Linux * File management in Project view (**) * Auto-completion in the editor obtains completion data from live runtime when the debugger is active (**) * Perspectives: Create and save named GUI layouts and optionally automatically transition when debugging is started (*) * Improved support for Cython and Pyrex (*.pyx files) * Added key binding documentation to the manual * Added Restart Debugging item in Debug menu and tool bar (**) (*)'d items are available in Wing IDE Professional only. (**)'d items are available in Wing IDE Personal and Professional only. The release also contains many other minor features and bug fixes; see the change log for details: http://wingware.com/pub/wingide/3.2.0/CHANGELOG.txt *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product when launched. Wing IDE 101 can be used free of charge. Wing IDE Pro 3.2.0 http://wingware.com/downloads/wingide/3.2 Wing IDE Personal 3.2.0 http://wingware.com/downloads/wingide-personal/3.2 Wing IDE 101 3.2.0 http://wingware.com/downloads/wingide-101/3.2 *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, version control, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE 3.2 supports Python versions 2.0.x through 3.1.x. *Purchasing and Upgrading* Wing 3.2 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license: https://wingware.com/store/purchase -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From rui.vapps at gmail.com Thu Aug 20 15:23:40 2009 From: rui.vapps at gmail.com (Ray) Date: Thu, 20 Aug 2009 12:23:40 -0700 (PDT) Subject: thread and win32com.client problem Message-ID: <970c1cee-71ac-4b01-91ce-8ca2014570f8@p9g2000vbl.googlegroups.com> Hi, I have a problem with thread and win32com.client running python 2.5 on vista (activestate python) import win32com.client, thread def child(test): problem=win32com.client.Dispatch("WScript.Shell") print 'hello from thread', test def parent(): i=0 while 1: i+=1 thread.start_new(child,('abc',)) if raw_input()=='q': break parent() above codes will give me error when I run it. but if without the line problem=win32com.client.Dispatch("WScript.Shell") it just works fine. errors are: Unhandled exception in thread started by Traceback (most recent call last): File "C:\Users\Test\Desktop\Test\test_thread.py", line 3, in child problem=win32com.client.Dispatch("WScript.Shell") File "C:\Python25\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName (dispatch,userName,clsctx) File "C:\Python25\lib\site-packages\win32com\client\dynamic.py", line 98, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python25\lib\site-packages\win32com\client\dynamic.py", line 78, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None) Traceback (most recent call last): File "C:\Users\Test\Desktop\Test\test_thread.py", line 11, in parent() File "C:\Users\Test\Desktop\Test\test_thread.py", line 10, in parent if raw_input()=='q': break Thanks for any help. From dullrich at sprynet.com Thu Aug 20 15:31:30 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Thu, 20 Aug 2009 14:31:30 -0500 Subject: Silly question References: Message-ID: On Thu, 20 Aug 2009 18:41:34 +0000, Duncan Booth wrote: > David C Ullrich wrote: > >> I just noticed that >> >> sequence[i:j:k] >> >> syntax in a post here. When did this happen? >> >> (I'm just curious whether it existed in 1.5.x or not. If so I'm stupid >> - otoh if it was introduced in 2.x I'm just slow...) >> >> > Googling for 'python extended slice' returns this as the first hit: > > http://www.python.org/doc/2.3.5/whatsnew/section-slices.html > >> 15 Extended Slices >> >> Ever since Python 1.4, the slicing syntax has supported an optional >> third ``step'' or ``stride'' argument. For example, these are all legal >> Python syntax: L[1:10:2], L[:-1:1], L[::-1]. This was added to Python >> at the request of the developers of Numerical Python, which uses the >> third argument extensively. However, Python's built-in list, tuple, and >> string sequence types have never supported this feature, raising a >> TypeError if you tried it. Michael Hudson contributed a patch to fix >> this shortcoming. > > So extended slices have existed since Python 1.4, but builtin types only > started to support them from 2.3. Fine (I knew they existed in Numerical Python way back when...) From dullrich at sprynet.com Thu Aug 20 15:33:05 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Thu, 20 Aug 2009 14:33:05 -0500 Subject: Silly question References: Message-ID: On Thu, 20 Aug 2009 14:36:35 -0400, Benjamin Kaplan wrote: > On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrich > wrote: >> I just noticed that >> >> ?sequence[i:j:k] >> >> syntax in a post here. When did this happen? >> >> (I'm just curious whether it existed in 1.5.x or not. If so I'm stupid >> - otoh if it was introduced in 2.x I'm just slow...) >> >> > Well, I got some good news and some bad news. According to the docs, it > existed in 1.4 but the built-in sequences didn't support it until 2.3. > It's not used that often anyway so you haven't been missing much. So I'm slow, fine. (There were several times when I was using 1.5.3 and wished they were there - transposing matrices, etc.) > > http://www.python.org/doc/2.3.5/whatsnew/section-slices.html From rui.vapps at gmail.com Thu Aug 20 15:53:39 2009 From: rui.vapps at gmail.com (Ray) Date: Thu, 20 Aug 2009 12:53:39 -0700 (PDT) Subject: thread and win32com.client problem References: <970c1cee-71ac-4b01-91ce-8ca2014570f8@p9g2000vbl.googlegroups.com> Message-ID: <319b2ae1-276b-41af-9fd9-7086353ed193@p23g2000vbl.googlegroups.com> I already find the way to fix it. :-) From fuzzyman at gmail.com Thu Aug 20 15:55:47 2009 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 20 Aug 2009 12:55:47 -0700 (PDT) Subject: ANN: discover 0.3.0 released, automatic test discovery for unittest Message-ID: <096a6bb5-9b09-4d5c-86cf-ba826cf3a39a@f37g2000yqn.googlegroups.com> The discover module is a backport of the automatic test discovery from the unittest module in Python-trunk (what will become Python 2.7 and 3.2). The discover module should work on versions of Python 2.4 upwards: * discover module on PyPI: http://pypi.python.org/pypi/discover The discover module can be used to run all, or a subset, of your unittest based tests automatically from the command line. See the PyPI page for details. Version 0.3.0 has two new features: * Failing to import a file (e.g. due to a syntax error) no longer halts discovery but is reported as an error. * Discovery will not attempt to import test files whose names are not valid Python identifiers, even if they match the pattern. From aaron.hildebrandt at gmail.com Thu Aug 20 16:02:57 2009 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Thu, 20 Aug 2009 13:02:57 -0700 (PDT) Subject: Problem with arrays in a recursive class function Message-ID: <190378bc-f095-46fa-9104-cb94fa09698f@g10g2000yqh.googlegroups.com> I have a list of nodes, and I need to find a path from one node to another. The nodes each have a list of nodes they are connected to, set up like this: class Node(object): def __init__(self, connectedNodes): self.connectedNodes = connectedNodes nodes = { 1: Node([4]), 2: Node([3]), 3: Node([2, 4, 5]), 4: Node([1, 6, 3]), 5: Node([3, 7]), 6: Node([4, 9]), 7: Node([5, 8]), 8: Node([7, 9]), 9: Node([6, 8]) } I made a quick brute-force pathfinder to solve it (in this case, a path from node 1 to node 9). Here it is: class PathFind(object): def __init__(self, source, destination): self.source = source self.destination = destination self.solved = [] def Search(self): self.PathFind([self.source]) if self.solved: print "Solutions: " for i in self.solved: print "\t" + str(i) else: print "Couldn't solve." def PathFind(self, trail): location = trail[-1] if location == self.destination: self.solved.append(trail) print "Solution found: " + str(trail) else: possibilities = [] for i in nodes[location].connectedNodes: if not i in trail: possibilities.append(i) for i in possibilities: trail.append(i) self.PathFind(trail[:]) if not possibilities: print "Dead end: " + str(trail) finder = PathFind(1, 9) finder.Search() Unfortunately, it doesn't seem to be giving me the result I was after. This is the output: Solution found: [1, 4, 6, 9] Dead end: [1, 4, 6, 3, 2] Solution found: [1, 4, 6, 3, 2, 5, 7, 8, 9] Solutions: [1, 4, 6, 9] [1, 4, 6, 3, 2, 5, 7, 8, 9] The problem is the array trail[], which seems to survive from instance to instance of PathFind(). I thought that by calling self.PathFind (trail[:]), I was creating a new copy of trail[], but obviously something isn't running like I expected. Is there something I'm misunderstanding here, or is there just a stupid bug in my code I haven't caught? From dfnsonfsduifb at gmx.de Thu Aug 20 16:24:24 2009 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Thu, 20 Aug 2009 22:24:24 +0200 Subject: Annoying octal notation In-Reply-To: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: <7f5pohF2k259vU1@mid.dfncis.de> David schrieb: > If I want an octal I'll use oct()! > > "Explicit is better than implicit..." A leading "0" *is* explicit. Implicit would be when some functions would interpret a "0" prefix as octal and others wouldn't. Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From lists at cheimes.de Thu Aug 20 16:35:48 2009 From: lists at cheimes.de (Christian Heimes) Date: Thu, 20 Aug 2009 22:35:48 +0200 Subject: thread and win32com.client problem In-Reply-To: <319b2ae1-276b-41af-9fd9-7086353ed193@p23g2000vbl.googlegroups.com> References: <970c1cee-71ac-4b01-91ce-8ca2014570f8@p9g2000vbl.googlegroups.com> <319b2ae1-276b-41af-9fd9-7086353ed193@p23g2000vbl.googlegroups.com> Message-ID: <4A8DB3A4.4030800@cheimes.de> Ray wrote: > I already find the way to fix it. :-) I consider it good style when people describe their solution to a problem, too. Other Python users may run into the same issue someday. :) Christian From sajmikins at gmail.com Thu Aug 20 16:37:33 2009 From: sajmikins at gmail.com (Simon Forman) Date: Thu, 20 Aug 2009 13:37:33 -0700 (PDT) Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: <6a523329-3287-4271-ba37-7be450cfc5f6@d32g2000yqh.googlegroups.com> On Aug 20, 3:06?pm, David <71da... at libero.it> wrote: > Hi all, > > Is there some magic to make the 2.x CPython interpreter to ignore the > annoying octal notation? No. You would have to modify and recompile the interpreter. This is not exactly trivial, see "How to Change Python's Grammar" http://www.python.org/dev/peps/pep-0306/ However, see "Integer Literal Support and Syntax" http://www.python.org/dev/peps/pep-3127/ (Basically in 2.6 and onwards you can use 0oNNN notation.) > I'd really like 012 to be "12" and not "10". > > If I want an octal I'll use oct()! But that gives you a string, you're asking about literals. From luk.art.q1 at gmail.com Thu Aug 20 16:43:37 2009 From: luk.art.q1 at gmail.com (artur lukowicz) Date: Thu, 20 Aug 2009 22:43:37 +0200 Subject: No subject Message-ID: 6344a24de14243c76060bedd42f79bc302679dad -------------- next part -------------- An HTML attachment was scrubbed... URL: From aaron.hildebrandt at gmail.com Thu Aug 20 16:57:07 2009 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Thu, 20 Aug 2009 13:57:07 -0700 (PDT) Subject: Problem with arrays in a recursive class function References: <190378bc-f095-46fa-9104-cb94fa09698f@g10g2000yqh.googlegroups.com> Message-ID: <5f185928-131e-4718-bbb2-a775157d966c@c34g2000yqi.googlegroups.com> Never mind -- ditched the attempt and implemented Dijkstra. From MatzeGuentert at gmx.de Thu Aug 20 17:08:34 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Thu, 20 Aug 2009 23:08:34 +0200 Subject: incrementing string/hex value from file and write back Message-ID: <1250802514.3331.0.camel@celsius> Hello guys I would like to read a hex number from an ASCII file, increment it and write it back. How can this be performed? I have tried several approaches: my file serial.txt contains: 0C ---------------------------------- f = open('serial.txt', 'r') val = f.read() val = val.encode('hex') print val ---------------------------------- --> 3043 ---------------------------------- f = open('serial.txt', 'r') val = f.read() print val val = val+1 ---------------------------------- --> TypeError: cannot concatenate 'str' and 'int' objects ---------------------------------- f = open('serial.txt', 'rb') val = f.read() val = val + 1 ---------------------------------- --> TypeError: cannot concatenate 'str' and 'int' objects hm.... From rami.chowdhury at gmail.com Thu Aug 20 17:18:28 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 20 Aug 2009 14:18:28 -0700 Subject: incrementing string/hex value from file and write back In-Reply-To: <1250802514.3331.0.camel@celsius> References: <1250802514.3331.0.camel@celsius> Message-ID: > val = val.encode('hex') That's the crucial line -- it's returning a new integer, which you are re-binding to val. If you then did: val = val + 1 you'd be fine, and could then write val back to your file :-) On Thu, 20 Aug 2009 14:08:34 -0700, Matthias G?ntert wrote: > Hello guys > > I would like to read a hex number from an ASCII file, increment it and > write it back. > How can this be performed? > > I have tried several approaches: > > my file serial.txt contains: 0C > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > val = val.encode('hex') > print val > ---------------------------------- > --> 3043 > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > print val > val = val+1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > ---------------------------------- > f = open('serial.txt', 'rb') > val = f.read() > val = val + 1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > > hm.... > -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From sajmikins at gmail.com Thu Aug 20 17:35:12 2009 From: sajmikins at gmail.com (Simon Forman) Date: Thu, 20 Aug 2009 14:35:12 -0700 (PDT) Subject: incrementing string/hex value from file and write back References: Message-ID: <6d707639-7d1b-44a3-b4a5-3a0cbf1240fc@j21g2000yqe.googlegroups.com> On Aug 20, 5:08?pm, Matthias G?ntert wrote: > Hello guys > > I would like to read a hex number from an ASCII file, increment it and > write it back. > How can this be performed? > > I have tried several approaches: > > my file serial.txt contains: 0C > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > val = val.encode('hex') > print val > ---------------------------------- > --> 3043 > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() ? > print val > val = val+1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > ---------------------------------- > f = open('serial.txt', 'rb') > val = f.read() > val = val + 1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > hm.... Check this out: In [1]: val = '0C' In [2]: val.encode('hex') Out[2]: '3043' That's not what you want. Try this: In [3]: int(val, 16) Out[3]: 12 And to convert an int to a hex string. In [4]: '%x' % 13 Out[4]: 'd' The interpreter has a help() function that gives you quick access to information about python objects: >>> help(str.encode) Help on method_descriptor: encode(...) S.encode([encoding[,errors]]) -> object Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors. >>> help(int) Help on class int in module __builtin__: class int(object) | int(x[, base]) -> integer | | Convert a string or number to an integer, if possible. A floating point | argument will be truncated towards zero (this does not include a string | representation of a floating point number!) When converting a string, use | the optional base. It is an error to supply a base when converting a | non-string. If the argument is outside the integer range a long object | will be returned instead. | | Methods defined here: | ... Unfortunately you can't use it on the '%' string formatting operator... >>> help(%) SyntaxError: invalid syntax So here's a link to the docs: http://docs.python.org/library/stdtypes.html#string-formatting-operations HTH, ~Simon From breamoreboy at yahoo.co.uk Thu Aug 20 17:36:37 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 20 Aug 2009 22:36:37 +0100 Subject: incrementing string/hex value from file and write back In-Reply-To: <1250802514.3331.0.camel@celsius> References: <1250802514.3331.0.camel@celsius> Message-ID: Matthias G?ntert wrote: > Hello guys > > I would like to read a hex number from an ASCII file, increment it and > write it back. > How can this be performed? > > I have tried several approaches: > > my file serial.txt contains: 0C > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > val = val.encode('hex') val = int(val, 16) + 1 f.write('%02X' % val) > print val > ---------------------------------- > --> 3043 > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > print val > val = val+1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > ---------------------------------- > f = open('serial.txt', 'rb') > val = f.read() > val = val + 1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > > hm.... > -- Kindest regards. Mark Lawrence. From ethan at stoneleaf.us Thu Aug 20 17:36:41 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 20 Aug 2009 14:36:41 -0700 Subject: incrementing string/hex value from file and write back In-Reply-To: References: <1250802514.3331.0.camel@celsius> Message-ID: <4A8DC1E9.30504@stoneleaf.us> [fixed top-posting] Rami Chowdhury wrote: > On Thu, 20 Aug 2009 14:08:34 -0700, Matthias G?ntert > wrote: > >> Hello guys >> >> I would like to read a hex number from an ASCII file, increment it and >> write it back. >> How can this be performed? >> >> I have tried several approaches: >> >> my file serial.txt contains: 0C >> >> ---------------------------------- >> f = open('serial.txt', 'r') >> val = f.read() >> val = val.encode('hex') > > That's the crucial line -- it's returning a new integer, which you are > re-binding to val. If you then did: > > val = val + 1 > > you'd be fine, and could then write val back to your file :-) > .encode('hex') is returning a string -- attempting to add one to it will raise the same error the OP is getting below. To get a number you can do (after reading val from the file): val = int(val, '16') # convert from base 16 val += 1 # increment val = "%X" % val # back to heg digits and then write it back out again. Don't forget to close and reopen the file for writing. :) ~Ethan~ >> print val >> ---------------------------------- >> --> 3043 >> >> ---------------------------------- >> f = open('serial.txt', 'r') >> val = f.read() >> print val >> val = val+1 >> ---------------------------------- >> --> TypeError: cannot concatenate 'str' and 'int' objects >> >> ---------------------------------- >> f = open('serial.txt', 'rb') >> val = f.read() >> val = val + 1 >> ---------------------------------- >> --> TypeError: cannot concatenate 'str' and 'int' objects >> >> >> hm.... From sajmikins at gmail.com Thu Aug 20 17:38:08 2009 From: sajmikins at gmail.com (Simon Forman) Date: Thu, 20 Aug 2009 14:38:08 -0700 (PDT) Subject: incrementing string/hex value from file and write back References: <1250802514.3331.0.camel@celsius> Message-ID: On Aug 20, 5:18?pm, "Rami Chowdhury" wrote: > > val = val.encode('hex') > > That's the crucial line -- it's returning a new integer, which you are ? > re-binding to val. If you then did: No, it returns another string, which still isn't the decimal representation of the hex string. hex C => decimal 12 In [1]: '0C'.encode('hex') Out[1]: '3043' From rami.chowdhury at gmail.com Thu Aug 20 17:44:57 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 20 Aug 2009 14:44:57 -0700 Subject: incrementing string/hex value from file and write back In-Reply-To: References: <1250802514.3331.0.camel@celsius> Message-ID: Of course - my apologies, I was being an idiot. On Thu, 20 Aug 2009 14:38:08 -0700, Simon Forman wrote: > On Aug 20, 5:18?pm, "Rami Chowdhury" wrote: >> > val = val.encode('hex') >> >> That's the crucial line -- it's returning a new integer, which you are ? >> re-binding to val. If you then did: > > No, it returns another string, which still isn't the decimal > representation of the hex string. hex C => decimal 12 > > In [1]: '0C'.encode('hex') > Out[1]: '3043' -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From manu3d at gmail.com Thu Aug 20 17:46:19 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 20 Aug 2009 14:46:19 -0700 (PDT) Subject: Executing untrusted code References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com> <029d893f$0$25987$c3e8da3@news.astraweb.com> Message-ID: <4a5db5ed-4413-46a6-bc2b-6e9200b26ea3@s31g2000yqs.googlegroups.com> Christian, Rami and Steven, thank you all for your help. It wasn't meant to be a challenge, I knew it ought to be easily breakable. I'm no hacker and it just helps to have some examples to better understand the issue. On Aug 20, 7:42?pm, Steven D'Aprano On a related topic, you should read this post here: > http://tav.espians.com/a-challenge-to-break-python-security.html Indeed I did read the post and my minimalistic test was inspired by some of the code in it (I didn't know you could replace the builtins!). Tav's effort kinda of ended nowhere though. My understanding of it is that it hasn't been broken and that Tav has submitted a patch to secure some of python's innards. But Steven, you are perfectly right, I didn't test it and I missed the crucial part in which I store the __builtins__ dictionary in the dictionary of the new originalBuiltins module. My bad. Still, you did understand my intentions and did give me a simple example of how it could be broken. Thank you. -However- I would suggest that conceptually the "award" goes to Christian. ;) In the same way the open builtin function can be replaced or removed, also reload, file, __import__, exec, execfile and any other potentially "unsafe" builtin can be replaced with safer versions. Or not? Christian's solution though, seems to be much trickier to evade. Can the object class be replaced at runtime with a version that does not provide a way to reach its subclasses? Manu From inigoserna at gmail.com Thu Aug 20 18:12:07 2009 From: inigoserna at gmail.com (=?UTF-8?B?ScOxaWdvIFNlcm5h?=) Date: Fri, 21 Aug 2009 00:12:07 +0200 Subject: ncurses getch & unicode (was: decoding keyboard input when using curses) In-Reply-To: <65a1d6f80908200936g18b235fcw49d0047168cf9548@mail.gmail.com> References: <65a1d6f80908200936g18b235fcw49d0047168cf9548@mail.gmail.com> Message-ID: <65a1d6f80908201512w4b90c646r315e699ed78a525a@mail.gmail.com> Hi again, 2009/8/20 I?igo Serna > > I have the same problem mentioned in http://groups.google.com/group/comp.lang.python/browse_thread/thread/c70c80cd9bc7bac6?pli=1 some months ago. > > Python 2.6 program which uses ncurses module in a terminal configured to use UTF-8 encoding. > > When trying to get input from keyboard, a non-ascii character (like ?) is returned as 2 integers < 255, needing 2 calls to getch method to get both. > These two integers \xc3 \xa7 forms the utf-8 encoded representation of ? character. > > ncurses get_wch documentation states the function should return an unique integer > 255 with the ordinal representation of that unicode char encoded in UTF-8, \xc3a7. Answering myself, I've copied at the bottom of this email a working solution, but the question still remains: why win.getch() doesn't return the correct value? Kind regards, I?igo Serna ###################################################################### # test.py import curses import locale locale.setlocale(locale.LC_ALL, '') print locale.getpreferredencoding() def get_char(win): ??? def get_check_next_byte(): ??????? c = win.getch() ??????? if 128 <= c <= 191: ??????????? return c ??????? else: ??????????? raise UnicodeError ??? bytes = [] ??? c = win.getch() ??? if c <= 127: ??????? # 1 bytes ??????? bytes.append(c) ??? elif 194 <= c <= 223: ??????? # 2 bytes ??????? bytes.append(c) ??????? bytes.append(get_check_next_byte()) ??? elif 224 <= c <= 239: ??????? # 3 bytes ??????? bytes.append(c) ??????? bytes.append(get_check_next_byte()) ??????? bytes.append(get_check_next_byte()) ??? elif 240 <= c <= 244: ??????? # 4 bytes ??????? bytes.append(c) ??????? bytes.append(get_check_next_byte()) ??????? bytes.append(get_check_next_byte()) ??????? bytes.append(get_check_next_byte()) ??? buf = ''.join([chr(b) for b in bytes]) ??? buf = buf.decode('utf-8') ??? return buf def getcodes(win): ??? codes = [] ??? while True: ??????? try: ??????????? ch = get_char(win) ??????? except KeyboardInterrupt: ??????????? return codes ??????? codes.append(ch) lst = curses.wrapper(getcodes) print lst for c in lst: ??? print c.encode('utf-8'), print ###################################################################### From mensanator at aol.com Thu Aug 20 18:18:35 2009 From: mensanator at aol.com (Mensanator) Date: Thu, 20 Aug 2009 15:18:35 -0700 (PDT) Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: On Aug 20, 2:06?pm, David <71da... at libero.it> wrote: > Hi all, > > Is there some magic to make the 2.x CPython interpreter to ignore the > annoying octal notation? > I'd really like 012 to be "12" and not "10". Use 3.1: >>> int('012') 12 (Just kidding! That works in 2.5 also. How are you using it where it's coming out wrong? I can see you pulling '012' out of a text file and want to calculate with it, but how would you use a string without using int()? Passing it to functions that allow string representations of numbers?) > > If I want an octal I'll use oct()! > > "Explicit is better than implicit..." > > TIA > David From davea at ieee.org Thu Aug 20 19:05:17 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 20 Aug 2009 19:05:17 -0400 Subject: incrementing string/hex value from file and write back In-Reply-To: <1250802514.3331.0.camel@celsius> References: <1250802514.3331.0.camel@celsius> Message-ID: <4A8DD6AD.5080108@ieee.org> Matthias G?ntert wrote: > Hello guys > > I would like to read a hex number from an ASCII file, increment it and > write it back. > How can this be performed? > > I have tried several approaches: > > my file serial.txt contains: 0C > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > val = val.encode('hex') > print val > ---------------------------------- > --> 3043 > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > print val > val = val+1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > ---------------------------------- > f = open('serial.txt', 'rb') > val = f.read() > val = val + 1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > > hm.... > > > You don't say much to constrain the file. Is it always two characters (nibbles) long? Or might it have a newline at the end? If it could be multiple lines, is each line limited to 2 columns? or to 8 columns? or no limit? To interpret val as an integer, try new = int(val, 16) Then to convert back to hex digits, try line = "%x" % (val+1) For fancier conversions, look at binascii.unhexlify() and hexlify(). Look also at chr() and ord(). and str.format() DaveA From martin.hellwig at dcuktec.org Thu Aug 20 19:06:10 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 21 Aug 2009 00:06:10 +0100 Subject: thread and win32com.client problem In-Reply-To: References: <970c1cee-71ac-4b01-91ce-8ca2014570f8@p9g2000vbl.googlegroups.com> <319b2ae1-276b-41af-9fd9-7086353ed193@p23g2000vbl.googlegroups.com> Message-ID: Christian Heimes wrote: > Ray wrote: >> I already find the way to fix it. :-) > > I consider it good style when people describe their solution to a > problem, too. Other Python users may run into the same issue someday. :) > > Christian He probably used: pythoncom.CoInitialize() -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From farberow at wisc.edu Thu Aug 20 19:21:50 2009 From: farberow at wisc.edu (Carrie Farberow) Date: Thu, 20 Aug 2009 18:21:50 -0500 Subject: Python on Crays Message-ID: <6fb0f9aeb382.4a8d943e@wiscmail.wisc.edu> I am trying to build a statically-linked Python based on directions at: http://yt.enzotools.org/wiki/CrayXT5Installation I have tried this on multiple systems. The first time I attempt to build python, 'make' runs fine but 'make install' fails with the following error: Sorry: UnicodeError: ("\\N escapes not supported (can't load unicodedata module)",) Any help regarding the source of this error and possible fixes would be appreciated. Carrie From zuo at chopin.edu.pl Thu Aug 20 19:25:38 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Fri, 21 Aug 2009 01:25:38 +0200 Subject: #elements of seq A in seq B In-Reply-To: <7c16abe1-7502-432a-acff-aff95c22a8ac@q14g2000vbi.googlegroups.com> References: <7c16abe1-7502-432a-acff-aff95c22a8ac@q14g2000vbi.googlegroups.com> Message-ID: 20-08-2009 o 04:12:14 Simon Forman wrote: > If you want to know the count for each element you can use this: > > from collections import defaultdict > > def g(a, b): > a = set(a) > d = defaultdict(int) > for item in b: > if item in a: > d[item] += 1 > return d > > print g(A, B) > > # prints defaultdict(, {' ': 1, 'e': 1, 'g': 1, 'i': 1, > 'o': 1, 'n': 2, 's': 1, 'r': 2, 't': 2}) Yeah, your sollution is better (and more interesting :-)). Thanks! *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Thu Aug 20 19:44:43 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Fri, 21 Aug 2009 01:44:43 +0200 Subject: #elements of seq A in seq B In-Reply-To: References: Message-ID: 20-08-2009 o 13:01:29 Neal Becker wrote: > I meant #occurrences of characters from the set A in string B But: 1) separately for each element of A? (see Simon's sollution with defaultdict) 2) or total number of all occurrences of elements of A? (see below) 20-08-2009 o 14:05:12 Peter Otten <__peter__ at web.de> wrote: > identity = "".join(map(chr, range(256))) > n = len(b) - len(b.translate(identity, a)) Nice, though I'd prefer Simon's sollution: a = set(a) n = sum(item in a for item in b) Regards, *j -- Jan Kaliszewski (zuo) From aahz at pythoncraft.com Thu Aug 20 19:51:00 2009 From: aahz at pythoncraft.com (Aahz) Date: 20 Aug 2009 16:51:00 -0700 Subject: Silly question References: Message-ID: In article , Benjamin Kaplan wrote: >On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrich wrot= >e: >> >> I just noticed that >> sequence[i:j:k] > >Well, I got some good news and some bad news. According to the docs, >it existed in 1.4 but the built-in sequences didn't support it until >2.3. It's not used that often anyway so you haven't been missing much. Except that it's canonical for one specific operation: 'reverseme'[::-1] -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith From james.harris.1 at googlemail.com Thu Aug 20 19:59:14 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Thu, 20 Aug 2009 16:59:14 -0700 (PDT) Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: On 20 Aug, 20:06, David <71da... at libero.it> wrote: > Hi all, > > Is there some magic to make the 2.x CPython interpreter to ignore the > annoying octal notation? > I'd really like 012 to be "12" and not "10". This is (IMHO) a sad hangover from C (which took it from B but not from BCPL which used # and #x) and it appears in many places. It sounds like you want to use leading zeroes in literals - perhaps for spacing. I don't think there's an easy way. You just have to be aware of it. Note that it seems to apply to integers and not floating point literals >>> 012 10 >>> int("012") 12 >>> 012.5 12.5 >>> This daft notation is recognised in some surprising places to catch the unwary. For example, the place I first came across it was in a windows command prompt: s:\>ping 192.168.1.012 Pinging 192.168.1.10 with 32 bytes of data: On B's use of the leading zero see http://cm.bell-labs.com/cm/cs/who/dmr/kbman.html and note the comment: "An octal constant is the same as a decimal constant except that it begins with a zero. It is then interpreted in base 8. Note that 09 (base 8) is legal and equal to 011." It maybe made sense once but this relic of the past should have been consigned to the waste bin of history long ago. James From sjmachin at lexicon.net Thu Aug 20 20:45:11 2009 From: sjmachin at lexicon.net (John Machin) Date: Thu, 20 Aug 2009 17:45:11 -0700 (PDT) Subject: Silly question References: Message-ID: <97ae0d22-7eaa-4ad6-8603-69699703d508@u16g2000pru.googlegroups.com> On Aug 21, 5:33?am, David C Ullrich wrote: > So I'm slow, fine. (There were several times when I was using 1.5.3 > and wished they were there - transposing matrices, etc.) 1.5.THREE ?? From sflennik at comcast.net Thu Aug 20 20:57:53 2009 From: sflennik at comcast.net (Steve1234) Date: Thu, 20 Aug 2009 17:57:53 -0700 (PDT) Subject: install package in a particular python version Message-ID: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> I installed the boto module in my Ubuntu system using "python setup.py install" and it installs in my python2.6 version and works great. Now I want to install boto into my python2.5 version because my hosting services supports 2.5 but not 2.6. and I want to test my code locally, "sting".format() is not in 2.5. How do I install a package in a particular version of python? I tried several different install switches without any luck. From aahz at pythoncraft.com Thu Aug 20 20:58:53 2009 From: aahz at pythoncraft.com (Aahz) Date: 20 Aug 2009 17:58:53 -0700 Subject: platform-specific overrides of functions and class methods (expanding on imputils demo code) References: <77715735-2668-43e7-95da-c91d175b35c9@z31g2000yqd.googlegroups.com> Message-ID: In article <77715735-2668-43e7-95da-c91d175b35c9 at z31g2000yqd.googlegroups.com>, lkcl wrote: > >if somebody would like to add this to the python bugtracker, as a >contribution, that would be great. alternatively, you might like to >have a word with the python developers to get them to remove the >censorship on my contributions. Excuse me? What censorship? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith From benjamin.kaplan at case.edu Thu Aug 20 21:05:34 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 20 Aug 2009 21:05:34 -0400 Subject: install package in a particular python version In-Reply-To: References: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> Message-ID: whoops, sent it to you instead of the list On Thu, Aug 20, 2009 at 9:05 PM, Benjamin Kaplan wrote: > On Thu, Aug 20, 2009 at 8:57 PM, Steve1234 wrote: >> >> I installed the boto module in my Ubuntu system using "python setup.py >> install" and it installs in my python2.6 version and works great. ?Now >> I want to install boto into my python2.5 version because my hosting >> services supports 2.5 but not 2.6. and I want to test my code locally, >> "sting".format() is not in 2.5. >> >> How do I install a package in a particular version of python? >> >> I tried several different install switches without any luck. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > It's not an install switch- it's the version of python you use to > install it. If you want to install it to Python 2.5, run python2.5 > setup.py install > From david.lyon at preisshare.net Thu Aug 20 21:34:08 2009 From: david.lyon at preisshare.net (David Lyon) Date: Thu, 20 Aug 2009 21:34:08 -0400 Subject: install package in a particular python version In-Reply-To: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> References: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> Message-ID: <85a5395c9a481e1dfc74f5a76a62e85a@preisshare.net> On Thu, 20 Aug 2009 17:57:53 -0700 (PDT), Steve1234 wrote: > I installed the boto module in my Ubuntu system using "python setup.py > install" and it installs in my python2.6 version and works great. Now > I want to install boto into my python2.5 version because my hosting > services supports 2.5 but not 2.6. and I want to test my code locally, > "sting".format() is not in 2.5. > > How do I install a package in a particular version of python? > > I tried several different install switches without any luck. If you wish to do it in a gui rather than at the commandline then you could try the python package manager at : http://sourceforge.net/projects/pythonpkgmgr/ You will need to download it from source. In the Options Dialog, there is a dropdown list that allow you to easily change from one version of python to another. Regards David From zuo at chopin.edu.pl Thu Aug 20 21:42:42 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Fri, 21 Aug 2009 03:42:42 +0200 Subject: #elements of seq A in seq B In-Reply-To: <200908202009.59909.ndbecker2@gmail.com> References: <200908202009.59909.ndbecker2@gmail.com> Message-ID: >> a = set(a) >> n = sum(item in a for item in b) > Why set? Does it matter if I say that items in A are already unique? Sets are hash-based, so it's (most probably) far more efficient for sets than for sequences (especially if we say about big/long ones). Regards, *j -- Jan Kaliszewski (zuo) From charles at declareSub.com Thu Aug 20 22:12:32 2009 From: charles at declareSub.com (Charles Yeomans) Date: Thu, 20 Aug 2009 22:12:32 -0400 Subject: How to create functors? In-Reply-To: References: <7xab1vl0qf.fsf@ruckus.brouhaha.com> <7xmy5uanlt.fsf@ruckus.brouhaha.com> Message-ID: <33BB3F81-177F-4A02-9F09-44520F4823C4@declareSub.com> On Aug 20, 2009, at 5:25 AM, Steven D'Aprano wrote: > On Thu, 20 Aug 2009 01:36:14 -0700, Paul Rubin wrote: > >> Steven D'Aprano writes: >>> As near as I can tell, a functor is just an object which is callable >>> like a function without actually being implemented as a function, >>> e.g.: >> >> No it's not anything like that either, at least as I'm used to the >> term >> in programming or in mathematics. Maybe it's used other ways though. > > According to Wikipedia, functor can be used as a synonym for "function > object": > > http://en.wikipedia.org/wiki/Function_object > > which is what I was thinking of. So it seems there are at least two > meanings for the word, neither of which seems to apply to this > thread :) > > > >> As I'm used to it, it's a feature of certain static type systems. >> The >> notion isn't that useful in Python > > I find the Haskell page entirely opaque and unintelligible. Well, > perhaps > not *entirely* opaque, but pretty close: it assumes a mathematical > sophistication that I don't think I even had when I was getting my > maths > degree, let alone can remember two decades later. (Pity the poor VB > coders wondering what Haskell is good for...) The Wikipedia page is a > little better, but it's section on Examples is laughable -- the > examples > are as unintelligible to this reader as the description before them. > To this reader -- an Rb coder -- the examples were pretty clear. > > But let me try an example to see if I've got it right: > > > class Int2StrFunctor: > def map1(self, n): > if type(n) is not int: > raise TypeError('argument must be an int') > return "-"*n > def map2(self, f): > if type(f) is not type(lambda: None): > raise TypeError('argument must be a function') > # assume f takes an int, and returns another int > def inner(n): > return self.map1(f(n)) > return inner > > > The functor can take an int and return a string: > >>>> F = Int2StrFunctor() # F is a functor >>>> F.map1(3) > '---' > > It can also take a function (of int -> int) and return a new function > (int -> str): > >>>> def myfunc(n): > ... return n+2 > ... >>>> f = F.map2(myfunc) >>>> f(3) > '-----' >>>> f(4) > '------' > > > There's nothing special about the methods map1() and map2(), I could > call > them anything I like, or even do this: > > >>>> def __call__(self, arg): > ... if type(arg) is int: > ... return self.map1(arg) > ... else: > ... return self.map2(arg) > ... >>>> Int2StrFunctor.__call__ = __call__ >>>> >>>> F(2) > '--' >>>> F(myfunc)(0) > '--' > > > There are some technical restrictions on functors, relating to the > sorts > of functions and types (strictly "categories") they can accept, > presumably to make them mathematically well-behaved. > > > Have I got it correct? > I don't think so. Paul Rubin's square example was, I thought, particularly instructive. Charles Yeomans -------------- next part -------------- An HTML attachment was scrubbed... URL: From laser.yuan at gmail.com Thu Aug 20 23:34:20 2009 From: laser.yuan at gmail.com (laser) Date: Thu, 20 Aug 2009 20:34:20 -0700 (PDT) Subject: IDLE is not as interactive as Maple References: <7aa51a98-965c-4c74-a3b5-650140f1d589@v23g2000pro.googlegroups.com> <399082f9-3765-46dc-b71e-618e75256cf9@d34g2000vbm.googlegroups.com> Message-ID: <80f61e9c-9c0d-4fc9-a16a-9ef9f90b928c@o9g2000prg.googlegroups.com> Thanks very much for your information. Reinteract looks like exactly what I want. It give me the similary feeling of using Maple. I like this kind of programming style. People who did not have this experience really should take a try. On 8?20?, ??9?11?, Andr? wrote: > On Aug 20, 12:22 am, laser wrote: > > > In the future, will Python provide programe enviroment like Maple > > does? > > A quick, flip answer: perhaps if you design one? Tools for Python are > designed by people scratching an itch. > > That being said, have a look at reinteract:http://www.reinteract.org/trac/wiki/Tutorial/Introduction > > > In Maple, you can remove anything unneeded in the editor. And > > the code execution order are not necessary in one direction. You can > > run any command line on the screen by > > push Enter key. These functions gave a lot of flaxibility for users to > > start with programming something. > > Andr? From sflennik at comcast.net Thu Aug 20 23:53:18 2009 From: sflennik at comcast.net (Steve1234) Date: Thu, 20 Aug 2009 20:53:18 -0700 (PDT) Subject: install package in a particular python version References: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> Message-ID: <99822c4d-74ef-4a28-b133-42144c7fd25a@f20g2000prn.googlegroups.com> Benjamin suggested: sudo python2.5 setup.py install and it works. This makes sense, thanks. I downloaded pythonpkgmgr from source and installed it. I got the error that reguired wx package was missing. I couldn't find this package for Linux or source. From ben+python at benfinney.id.au Fri Aug 21 01:13:56 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 15:13:56 +1000 Subject: Waiting for a subprocess to exit Message-ID: <873a7l21gr.fsf@benfinney.id.au> Howdy all, I'm looking to replace some usages of ?os.system? with the more secure ?subprocess.Popen? methods. The module documentation has a section on replacing ?os.system? , which says to use:: process = subprocess.Popen("mycmd" + " myarg", shell=True) status = os.waitpid(process.pid, 0) But a ?Popen? instance has its own ?wait? method, which waits for exit . Why would I use ?os.waitpid? instead of:: process = subprocess.Popen("mycmd" + " myarg", shell=True) process.wait() status = process.returncode -- \ ?The best is the enemy of the good.? ?Voltaire, _Dictionnaire | `\ Philosophique_ | _o__) | Ben Finney From wuwei23 at gmail.com Fri Aug 21 01:17:29 2009 From: wuwei23 at gmail.com (alex23) Date: Thu, 20 Aug 2009 22:17:29 -0700 (PDT) Subject: 2.6 windows install References: Message-ID: <1e18d400-03ec-48ae-b59d-72aa6f5d9f64@l5g2000pra.googlegroups.com> "Tim Arnold" wrote: > Any ideas on what I'm missing here? Most likely the required configuration of the local environments. Did you install Python to the network device from your XP box? That would explain why you can run it: the required registry settings & environment variables are added by the installer, none of which is occurring on any computer other than the one from which you installed. To be honest, I've never seen a single-point-of-access network installation of Python for a Windows environment. If it was possible, I'd expect ActiveState's ActivePython to support it but there's no mention of it in the list of acceptable installer switches[1]. [1]: http://docs.activestate.com/activepython/2.6/installnotes.html#msi From ben+python at benfinney.id.au Fri Aug 21 01:18:09 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 15:18:09 +1000 Subject: install package in a particular python version References: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> Message-ID: <87y6pdzqwe.fsf@benfinney.id.au> Steve1234 writes: > I installed the boto module in my Ubuntu system using "python setup.py > install" and it installs in my python2.6 version and works great. That's because your ?python? command is doing the same thing as if you'd typed:: $ python2.6 setup.py install The Python 2.6 interpreter knows where its ?site-packages? path is, and so ?setup.py? in turn knows where to put files. > Now I want to install boto into my python2.5 version Invoke the specific Python interpreter you want:: $ python2.5 setup.py install -- \ ?Don't worry about people stealing your ideas. If your ideas | `\ are any good, you'll have to ram them down people's throats.? | _o__) ?Howard Aiken | Ben Finney From josefg at gmail.com Fri Aug 21 02:07:18 2009 From: josefg at gmail.com (josef) Date: Thu, 20 Aug 2009 23:07:18 -0700 (PDT) Subject: Object Reference question Message-ID: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> To begin, I'm new with python. I've read a few discussions about object references and I think I understand them. To be clear, Python uses a "Pass By Object Reference" model. x = 1 x becomes the object reference, while an object is created with the type 'int', value 1, and identifier (id(x)). Doing this with a class, x = myclass(), does the same thing, but with more or less object attributes. Every object has a type and an identifier (id()), according to the Python Language Reference for 2.6.2 section 3.1. x in both cases is the object reference. I would like to use the object to refer to the object reference. If I have a gross misunderstanding, please correct me. The following is what I would like to do: I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d is an object reference. Entering dk gives me the object: [MyClass0 instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at 0x0010 ... ] I need the object reference name (a,b,c,d) from dk to use as input for a file. Where do I find the memory location of the object reference and the object reference name memory location? I am unconcerned with the fact that the memory location will change the next time I run a python session. I will be using the object reference name for processing right away. My main focus of this post is: "How do I find and use object reference memory locations?" Thoughts? Thanks, Josef From milesck at umich.edu Fri Aug 21 02:18:35 2009 From: milesck at umich.edu (Miles Kaufmann) Date: Thu, 20 Aug 2009 23:18:35 -0700 Subject: Waiting for a subprocess to exit In-Reply-To: <873a7l21gr.fsf@benfinney.id.au> References: <873a7l21gr.fsf@benfinney.id.au> Message-ID: On Aug 20, 2009, at 10:13 PM, Ben Finney wrote: > The module documentation has a section on replacing ?os.system? > , which > says to use:: > > process = subprocess.Popen("mycmd" + " myarg", shell=True) > status = os.waitpid(process.pid, 0) > > But a ?Popen? instance has its own ?wait? method, which waits for exit > . > Why would I use ?os.waitpid? instead of:: > > process = subprocess.Popen("mycmd" + " myarg", shell=True) > process.wait() > status = process.returncode Really, you can just use: process = subprocess.Popen("mycmd" + " myarg", shell=True) status = process.wait() I'm not sure why the documentation suggests using os.waitpid. I would recommend avoiding shell=True whenever possible. It's used in the examples, I suspect, to ease the transition from the functions being replaced, but all it takes is for a filename or some other input to unexpectedly contain whitespace or a metacharacter and your script will stop working--or worse, do damage (cf. the iTunes 2 installer debacle[1]). Leaving shell=False makes scripts more secure and robust; besides, when I'm putting together a command and its arguments, it's as convenient to build a list (['mycmd', 'myarg']) as it is a string (if not more so). -Miles [1]: http://apple.slashdot.org/article.pl?sid=01/11/04/0412209#comment_2518563 From milesck at umich.edu Fri Aug 21 02:34:13 2009 From: milesck at umich.edu (Miles Kaufmann) Date: Thu, 20 Aug 2009 23:34:13 -0700 Subject: Object Reference question In-Reply-To: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <502C2E44-39EE-42E5-A9EA-3110CAEFF99D@umich.edu> On Aug 20, 2009, at 11:07 PM, josef wrote: > To begin, I'm new with python. I've read a few discussions about > object references and I think I understand them. > > To be clear, Python uses a "Pass By Object Reference" model. > x = 1 > x becomes the object reference, while an object is created with the > type 'int', value 1, and identifier (id(x)). Doing this with a class, > x = myclass(), does the same thing, but with more or less object > attributes. Every object has a type and an identifier (id()), > according to the Python Language Reference for 2.6.2 section 3.1. > > x in both cases is the object reference. I would like to use the > object to refer to the object reference. Stop right there. 'x' is not *the* object reference. It is *an* object reference (or in my preferred terminology, a label). Suppose you do: x = myclass() y = x The labels 'x' and 'y' both refer to the same object with equal precedence. There is no mapping from object back to label; it is a one-way pointer. Also importantly, labels themselves are not objects, and cannot be accessed or referred to. (This is a slight oversimplification; thanks to Python's reflection and introspection capabilities, it is possible to access labels to some extent, and in some limited situations it is possible to use stack inspection to obtain a label for an object. But this is hackish and error-prone, and should never be used when a more Pythonic method is available.) > The following is what I would like to do: > I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d > is an object reference. Entering dk gives me the object: [MyClass0 > instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at > 0x0010 ... ] > > I need the object reference name (a,b,c,d) from dk to use as input for > a file. It sounds like you should either be storing that name as an attribute of the object, or using a dictionary ({'a': a, 'b': b, ...}). -Miles From clp2 at rebertia.com Fri Aug 21 02:39:41 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 20 Aug 2009 23:39:41 -0700 Subject: Object Reference question In-Reply-To: <502C2E44-39EE-42E5-A9EA-3110CAEFF99D@umich.edu> References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <502C2E44-39EE-42E5-A9EA-3110CAEFF99D@umich.edu> Message-ID: <50697b2c0908202339w46e11252xc1fb86f770423f19@mail.gmail.com> On Thu, Aug 20, 2009 at 11:34 PM, Miles Kaufmann wrote: > On Aug 20, 2009, at 11:07 PM, josef wrote: >> The following is what I would like to do: >> I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d >> is an object reference. Entering dk gives me the object: [MyClass0 >> instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at >> 0x0010 ... ] >> >> I need the object reference name (a,b,c,d) from dk to use as input for >> a file. > > It sounds like you should either be storing that name as an attribute of the > object, or using a dictionary ({'a': a, 'b': b, ...}). Shorter way to produce the same dictionary: dict(a=a, b=b, ...) Cheers, Chris -- http://blog.rebertia.com From python at rcn.com Fri Aug 21 02:42:34 2009 From: python at rcn.com (Raymond Hettinger) Date: Thu, 20 Aug 2009 23:42:34 -0700 (PDT) Subject: #elements of seq A in seq B References: Message-ID: On Aug 19, 4:19?pm, Neal Becker wrote: > What would be a time efficient way to count the number of occurrences of > elements of sequence A in sequence B? ?(in this particular case, these > sequences are strings, if that matters). Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import collections >>> A = 'abc' >>> B = 'abracadabra' >>> collections.Counter(filter(A.__contains__, B)) Counter({'a': 5, 'b': 2, 'c': 1}) Raymond From python at rcn.com Fri Aug 21 02:44:29 2009 From: python at rcn.com (Raymond Hettinger) Date: Thu, 20 Aug 2009 23:44:29 -0700 (PDT) Subject: #elements of seq A in seq B References: Message-ID: <3f0fe16b-19df-4e48-94a6-96ea303c6ff2@g1g2000pra.googlegroups.com> On Aug 19, 4:19?pm, Neal Becker wrote: > What would be a time efficient way to count the number of occurrences of > elements of sequence A in sequence B? ?(in this particular case, these > sequences are strings, if that matters). Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import collections >>> A = 'abc' >>> B = 'abracadabra' >>> collections.Counter(filter(set(A).__contains__, B)) Counter({'a': 5, 'b': 2, 'c': 1}) Raymond From hendrik at microcorp.co.za Fri Aug 21 02:50:13 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 21 Aug 2009 08:50:13 +0200 Subject: Object Reference question In-Reply-To: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <200908210850.14075.hendrik@microcorp.co.za> On Friday 21 August 2009 08:07:18 josef wrote: > My main focus of this post is: "How do I find and use object reference > memory locations?" >>> a = [1,2,3,4] >>> id(a) 8347088 >>> - Hendrik From josefg at gmail.com Fri Aug 21 02:56:57 2009 From: josefg at gmail.com (josef) Date: Thu, 20 Aug 2009 23:56:57 -0700 (PDT) Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <627db5cc-7758-4d09-9ca4-78bc501c2626@d4g2000yqa.googlegroups.com> On Aug 21, 1:34?am, Miles Kaufmann wrote: > On Aug 20, 2009, at 11:07 PM, josef wrote: > > > To begin, I'm new with python. I've read a few discussions about > > object references and I think I understand them. > > > To be clear, Python uses a "Pass By Object Reference" model. > > x = 1 > > x becomes the object reference, while an object is created with the > > type 'int', value 1, and identifier (id(x)). Doing this with a class, > > x = myclass(), does the same thing, but with more or less object > > attributes. Every object has a type and an identifier (id()), > > according to the Python Language Reference for 2.6.2 section 3.1. > > > x in both cases is the object reference. I would like to use the > > object to refer to the object reference. > > Stop right there. ?'x' is not *the* object reference. ?It is *an* ? > object reference (or in my preferred terminology, a label). ?Suppose ? > you do: > > x = myclass() > y = x It would not make sense to do that in the context of the software I am writing. The documentation will specifically state not to do that. If the user does do that, then the user will be disappointed and possibly angry. > > The labels 'x' and 'y' both refer to the same object with equal ? > precedence. ?There is no mapping from object back to label; it is a ? > one-way pointer. ?Also importantly, labels themselves are not objects, ? > and cannot be accessed or referred to. I would just like to store the name of the one way pointer. > > (This is a slight oversimplification; thanks to Python's reflection ? > and introspection capabilities, it is possible to access labels to ? > some extent, and in some limited situations it is possible to use ? > stack inspection to obtain a label for an object. ?But this is hackish ? > and error-prone, and should never be used when a more Pythonic method ? > is available.) Hackish is fine. How error-prone is this method? > > > The following is what I would like to do: > > I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d > > is an object reference. Entering dk gives me the object: [MyClass0 > > instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at > > 0x0010 ... ] > > > I need the object reference name (a,b,c,d) from dk to use as input for > > a file. > > It sounds like you should either be storing that name as an attribute ? > of the object, or using a dictionary ({'a': a, 'b': b, ...}). That solution was mentioned in some of the discussions I read, but I would like to stay away from something like: a = MyClass (name='a', ...). Is it possible to assign an object reference name in a class __init__ defintion? From __peter__ at web.de Fri Aug 21 03:43:51 2009 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Aug 2009 09:43:51 +0200 Subject: #elements of seq A in seq B References: Message-ID: Jan Kaliszewski wrote: > 20-08-2009 o 13:01:29 Neal Becker wrote: > >> I meant #occurrences of characters from the set A in string B > > But: > > 1) separately for each element of A? (see Simon's sollution with > defaultdict) > > 2) or total number of all occurrences of elements of A? (see below) > > > 20-08-2009 o 14:05:12 Peter Otten <__peter__ at web.de> wrote: > >> identity = "".join(map(chr, range(256))) >> n = len(b) - len(b.translate(identity, a)) > > Nice, though I'd prefer Simon's sollution: > > a = set(a) > n = sum(item in a for item in b) Just to give you an idea why I posted the former: $ python -m timeit -s"a = set('abc'); b = 'abcdefg'*10**5" 'sum(item in a for item in b)' 10 loops, best of 3: 195 msec per loop $ python -m timeit -s"a = 'abc'; b = 'abcdefg'*10**5; id=''.join(map(chr, range(256)))" 'len(b) - len(b.translate(id, a))' 100 loops, best of 3: 4.97 msec per loop Peter From davea at ieee.org Fri Aug 21 03:56:57 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 21 Aug 2009 03:56:57 -0400 Subject: Object Reference question In-Reply-To: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <4A8E5349.80104@ieee.org> josef wrote: > To begin, I'm new with python. I've read a few discussions about > object references and I think I understand them. > > To be clear, Python uses a "Pass By Object Reference" model. > x = 1 > x becomes the object reference, while an object is created with the > type 'int', value 1, and identifier (id(x)). Doing this with a class, > x = myclass(), does the same thing, but with more or less object > attributes. Every object has a type and an identifier (id()), > according to the Python Language Reference for 2.6.2 section 3.1. > > x in both cases is the object reference. I would like to use the > object to refer to the object reference. If I have a gross > misunderstanding, please correct me. > > The following is what I would like to do: > I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d > is an object reference. Entering dk gives me the object: [MyClass0 > instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at > 0x0010 ... ] > > I need the object reference name (a,b,c,d) from dk to use as input for > a file. Where do I find the memory location of the object reference > and the object reference name memory location? I am unconcerned with > the fact that the memory location will change the next time I run a > python session. I will be using the object reference name for > processing right away. > > My main focus of this post is: "How do I find and use object reference > memory locations?" > > Thoughts? > Thanks, > > Josef > > There was a similar query here within the last couple of months, and lots of interesting discussion. But I never saw a use case convincing enough for me to want to remember how the various suggestions worked. Just how are you planning to use this? Are you planning to write a debugger? Or are you trying to keep mnemonic names for all instances of a particular class? Is this for a particular program's use, or are you trying to create a library to be used to reverse engineer some software you con't control? Several of your phrasings imply you don't understand Python yet. "memory location" - invisible to python use. And although id() will give you a hash-code that's actually a memory address, there's no direct way to use it. And names (attributes) don't necessarily have an address. "the object reference name (a,b,c,d) from dk" What is this? There's nothing that even conceptually looks like that when you assign dk = [a, b, c, d] A given object may have one to many references, and some of these may have names. If you constrain those names to be in a particular context, it may be possible to search for which name(s) currently happen(s) to point to the given object. For example, if you have the following at top level in a module: a = MyClass0() b = MyClass1() c = MyClass2() dk = [a, b, c] then, given the id() of dk[2], you could search the particular modules global name dictionary, and find c. But for the following fragment, you could not: a = MyClass0() b = MyClass1() c = MyClass2() dk = [a, b, c] c = 42 dk remains the same, but the dk[2] item no longer has any name referencing it. At any given instant of time, most objects in a typical program have no name associated with them. Many of them never did have a name. What would you want if dk had been created as: dk = [MyClass0(), MyClass1(), MyClass2()] or if a, b, and/or c were local variables in a function that's long since quit running, or that has run many times, each time creating new objects? DaveA From catalinfest at gmail.com Fri Aug 21 04:09:09 2009 From: catalinfest at gmail.com (catafest) Date: Fri, 21 Aug 2009 01:09:09 -0700 (PDT) Subject: PIL and Python References: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> Message-ID: <5df342cf-c742-42d6-bc8c-97a3c44a0816@h21g2000yqa.googlegroups.com> I don't extract data from jpegs. I wanna put some data in this (copyright of my site) ... On Aug 20, 2:01?pm, MaxTheMouse wrote: > On Aug 20, 10:23?am, catafest wrote: > > > On my photo jpg i have this : > > > Image Type: jpeg (The JPEG image format) > > Width: 1224 pixels > > Height: 1632 pixels > > Camera Brand: Sony Ericsson > > Camera Model: W810i > > Date Taken: 2009:07:09 08:16:21 > > Exposure Time: 1/19 sec. > > ISO Speed Rating: 320 > > Flash Fired: Flash did not fire, compulsory flash mode. > > Metering Mode: Center-Weighted Average > > Software: R4EA031 ? ? prgCXC1250321_ORANGE_HN 4.5 > > > This is the data i want edit it to make some copyright for my site. > > I don't know about PIL but you might want to try exif.py.http://sourceforge.net/projects/exif-py/ From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 21 04:34:09 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 21 Aug 2009 10:34:09 +0200 Subject: Object Reference question In-Reply-To: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <4a8e5bf6$0$15180$426a74cc@news.free.fr> josef a ?crit : > To begin, I'm new with python. I've read a few discussions about > object references and I think I understand them. > > To be clear, Python uses a "Pass By Object Reference" model. > x = 1 > x becomes the object reference, while an object is created with the > type 'int', value 1, and identifier (id(x)). Doing this with a class, > x = myclass(), does the same thing, but with more or less object > attributes. Every object has a type and an identifier (id()), > according to the Python Language Reference for 2.6.2 section 3.1. > > x in both cases is the object reference. Nope. It's *a* reference to the object - or, more exactly, a key in a mapping (the current namespace), which is associatied with a reference to the object. You can translate: x = 1 to: current_namespace['x'] = int(1) > I would like to use the > object to refer to the object reference. If I have a gross > misunderstanding, please correct me. > > The following is what I would like to do: > I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d > is an object reference. Entering dk gives me the object: [MyClass0 > instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at > 0x0010 ... ] > > I need the object reference name (a,b,c,d) from dk to use as input for > a file. ??? Could you elaborate, please ? > Where do I find the memory location of the object reference > and the object reference name memory location? short answer : you don't. Python is a high level language, 'memory location' is an implementation detail (and highly implementation-dependant), and *not* exposed (at least not in any usable way). > I am unconcerned with > the fact that the memory location will change the next time I run a > python session. I will be using the object reference name for > processing right away. > > My main focus of this post is: "How do I find and use object reference > memory locations?" > > Thoughts? Yes : please explain the problem you're trying to solve. I mean, the *real* problem - what you want to achieve -, not what you think is the solution !-) From gagsl-py2 at yahoo.com.ar Fri Aug 21 04:36:38 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Aug 2009 05:36:38 -0300 Subject: difference between 2 arrays References: <4a8d1d3f$0$23447$ba4acef3@news.orange.fr> Message-ID: En Thu, 20 Aug 2009 06:54:05 -0300, <""Michel Claveau - MVP"> escribi?: > Yes, the module sets is written, in doc, like "deprecated". > But: > - sets exist in Python 2.6 (& 2.5 or 2.4) > - documentation of sets (module) is better tha, documentation of set > (builtin) > > The best: read the documentaion of the module, and use the builtin... Any suggestion to improve the builtin set documentation? In what ways do you see one is better than the other? -- Gabriel Genellina From dickey at his.com Fri Aug 21 04:47:42 2009 From: dickey at his.com (Thomas Dickey) Date: Fri, 21 Aug 2009 01:47:42 -0700 (PDT) Subject: ncurses getch & unicode (was: decoding keyboard input when using curses) References: <65a1d6f80908200936g18b235fcw49d0047168cf9548@mail.gmail.com> Message-ID: <0a683d75-ac07-40a6-8374-2a2e900ac0ba@j21g2000yqe.googlegroups.com> On Aug 20, 6:12?pm, I?igo Serna wrote: > Hi again, > > 2009/8/20 I?igo Serna > > I have the same problem mentioned inhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...some months ago. > > > Python 2.6 program which usesncursesmodule in a terminal configured to use UTF-8 encoding. > > > When trying to get input from keyboard, a non-ascii character (like ?) is returned as 2 integers < 255, needing 2 calls to getch method to get both. > > These two integers \xc3 \xa7 forms the utf-8 encoded representation of ? character. > > >ncursesget_wch documentation states the function should return an unique integer > 255 with the ordinal representation of that unicode char encoded in UTF-8, \xc3a7. > > Answering myself, I've copied at the bottom of this email a working > solution, but the question still remains: why win.getch() doesn't > return the correct value? The code looks consistent with the curses functions... > Kind regards, > I?igo Serna > > ###################################################################### > # test.py > import curses > > import locale > locale.setlocale(locale.LC_ALL, '') > print locale.getpreferredencoding() > > def get_char(win): > ??? def get_check_next_byte(): > ??????? c = win.getch() You're using "getch", not "get_wch" (Python's ncurses binding may/may not have the latter). curses getch returns 8-bit values, get_wch would return wider values. From ben+python at benfinney.id.au Fri Aug 21 04:49:19 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 18:49:19 +1000 Subject: Waiting for a subprocess to exit References: <873a7l21gr.fsf@benfinney.id.au> Message-ID: <87fxbllfg0.fsf@benfinney.id.au> Miles Kaufmann writes: > On Aug 20, 2009, at 10:13 PM, Ben Finney wrote: > > Why would I use ?os.waitpid? instead of:: > > > > process = subprocess.Popen("mycmd" + " myarg", shell=True) > > process.wait() > > status = process.returncode > > Really, you can just use: > > process = subprocess.Popen("mycmd" + " myarg", shell=True) > status = process.wait() Ah thanks, that's even better. > I'm not sure why the documentation suggests using os.waitpid. Could someone who knows how to drive the Python BTS please report that against the ?subprocess? documentation? -- \ ?I am amazed, O Wall, that you have not collapsed and fallen, | `\ since you must bear the tedious stupidities of so many | _o__) scrawlers.? ?anonymous graffiti, Pompeii, 79 CE | Ben Finney From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 21 04:52:05 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 21 Aug 2009 10:52:05 +0200 Subject: Problem with arrays in a recursive class function In-Reply-To: <190378bc-f095-46fa-9104-cb94fa09698f@g10g2000yqh.googlegroups.com> References: <190378bc-f095-46fa-9104-cb94fa09698f@g10g2000yqh.googlegroups.com> Message-ID: <4a8e6029$0$20864$426a34cc@news.free.fr> Aaron Scott a ?crit : > I have a list of nodes, and I need to find a path from one node to > another. The nodes each have a list of nodes they are connected to, > set up like this: > > > > class Node(object): > def __init__(self, connectedNodes): > self.connectedNodes = connectedNodes > > nodes = { > 1: Node([4]), > 2: Node([3]), > 3: Node([2, 4, 5]), > 4: Node([1, 6, 3]), > 5: Node([3, 7]), > 6: Node([4, 9]), > 7: Node([5, 8]), > 8: Node([7, 9]), > 9: Node([6, 8]) > } > > > > I made a quick brute-force pathfinder to solve it (in this case, a > path from node 1 to node 9). Here it is: > > > > class PathFind(object): > def __init__(self, source, destination): > self.source = source > self.destination = destination > self.solved = [] > def Search(self): > self.PathFind([self.source]) > > if self.solved: > print "Solutions: " > for i in self.solved: > print "\t" + str(i) print "\t%s" % i > else: > print "Couldn't solve." > def PathFind(self, trail): > location = trail[-1] > if location == self.destination: > self.solved.append(trail) I think you want self.solved.append(trail[:]) Hint : Python doesn't use "pass by value". > The problem is the array trail[], which seems to survive from instance > to instance of PathFind(). I thought that by calling self.PathFind > (trail[:]), I was creating a new copy of trail[], Yes. But on the 'not solved' branch, you do mutate trail !-) From ben+python at benfinney.id.au Fri Aug 21 05:08:08 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 19:08:08 +1000 Subject: Sanitising arguments to shell commands (was: Waiting for a subprocess to exit) References: <873a7l21gr.fsf@benfinney.id.au> Message-ID: <87ab1tlekn.fsf_-_@benfinney.id.au> Miles Kaufmann writes: > I would recommend avoiding shell=True whenever possible. It's used in > the examples, I suspect, to ease the transition from the functions > being replaced, but all it takes is for a filename or some other input > to unexpectedly contain whitespace or a metacharacter and your script > will stop working--or worse, do damage (cf. the iTunes 2 installer > debacle[1]). Agreed, and that's my motivation for learning about ?subprocess.Popen?. > Leaving shell=False makes scripts more secure and robust; besides, > when I'm putting together a command and its arguments, it's as > convenient to build a list (['mycmd', 'myarg']) as it is a string (if > not more so). Which leads to another issue: I'm modifying a program that gets its child process command arguments from three places: * hard-coded text within the program (e.g. the command name, and context-specific arguments for the specific operation to be performed) * user-customised options to be added to the command line * filenames from the program's own command line For the hard-coded argument text, obviously they can simply be hard-coded as list elements:: command_args = ["foo", "--bar"] The filenames to be processed can also be appended one item per filename. However, the user-customised options are specified by the user in a configuration file, as a single string argument:: [fooprogram] additional_args = --baz 'crunch cronch' --wobble This works fine if the command line is constructed by dumb string concatenation; but obviously it fails when I try to construct a list of command line arguments. It's quite reasonable for the user to expect to be able to put any partial shell command-line in that string option and expect it will be processed by the shell, including any quoting or other escaping. How can I take a string that is intended to be part of a command line, representing multiple arguments and the shell's own escape characters as in the above example, and end up with a sane command argument list for ?subprocess.Popen?? E.g.:: parser = optparse.OptionParser() (options_args) = parser.parse_args(argv[1:]) filenames = args config = configparser.ConfigParser() config.read([system_config_file_path, user_config_file_path]) user_configured_args = config.get('fooprogram', 'additional_args') command_args = ["foo", "--bar"] somehow_append_each_argument(command_args, user_configured_args) command_args.extend(filenames) command_process = subprocess.Popen(command_args, shell=False) The resulting ?command_args? list should be:: ["foo", "--bar", "--baz", "crunch cronch", "--wobble", "spam.txt", "beans.txt"] How can I write the ?somehow_append_each_argument? step to get that result? -- \ ?Every sentence I utter must be understood not as an | `\ affirmation, but as a question.? ?Niels Bohr | _o__) | Ben Finney From clp2 at rebertia.com Fri Aug 21 05:19:13 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 Aug 2009 02:19:13 -0700 Subject: Sanitising arguments to shell commands (was: Waiting for a subprocess to exit) In-Reply-To: <87ab1tlekn.fsf_-_@benfinney.id.au> References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> Message-ID: <50697b2c0908210219i5e02c0cbq2d63bff891624ef4@mail.gmail.com> On Fri, Aug 21, 2009 at 2:08 AM, Ben Finney wrote: > How can I take a string that is intended to be part of a command line, > representing multiple arguments and the shell's own escape characters as > in the above example, and end up with a sane command argument list for > ?subprocess.Popen?? http://docs.python.org/library/shlex.html module shlex ? Simple lexical analysis New in version 1.5.2. "The shlex class makes it easy to write lexical analyzers for simple syntaxes resembling that of the Unix shell." Cheers, Chris -- http://blog.rebertia.com From jeanmichel at sequans.com Fri Aug 21 05:22:03 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 21 Aug 2009 11:22:03 +0200 Subject: Sanitising arguments to shell commands In-Reply-To: <87ab1tlekn.fsf_-_@benfinney.id.au> References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> Message-ID: <4A8E673B.3060606@sequans.com> Ben Finney wrote: > Miles Kaufmann writes: > > >> I would recommend avoiding shell=True whenever possible. It's used in >> the examples, I suspect, to ease the transition from the functions >> being replaced, but all it takes is for a filename or some other input >> to unexpectedly contain whitespace or a metacharacter and your script >> will stop working--or worse, do damage (cf. the iTunes 2 installer >> debacle[1]). >> > > Agreed, and that's my motivation for learning about ?subprocess.Popen?. > Can someone explain the difference with the shell argument ? giving for instance an example of what True will do that False won't. I mean, I've read the doc, and to be honest, I didn't get it. I'm concerned because I'm using subprocess, but I guess my shell arg has been filled a little bit random.. JM From ben+python at benfinney.id.au Fri Aug 21 05:26:54 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 19:26:54 +1000 Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <8763chldpd.fsf@benfinney.id.au> josef writes: > To be clear, Python uses a "Pass By Object Reference" model. Yes. (I'm glad this concept has propagated to newcomers so well :-) > x = 1 > x becomes the object reference It becomes *a* reference to that object, independent of any other references to that same object. > while an object is created with the type 'int', value 1, and > identifier (id(x)). Not really ?while?. The object creation happens first, then the assignment statement binds a reference to that object. > Doing this with a class, x = myclass(), does the same thing, but with > more or less object attributes. Every object has a type and an > identifier (id()), according to the Python Language Reference for > 2.6.2 section 3.1. Any expression can be on the right side of the assignment operator. The expression will evaluate to some object, which the assignment will then bind to the reference on the left side of the assignment operator. > x in both cases is the object reference. It is *an* object reference; that is, it's an identifier which refers to an object. There's nothing about that identifier that makes it ?the (one and only) object reference?. > I would like to use the object to refer to the object reference. If I > have a gross misunderstanding, please correct me. Yes, it's a simple misunderstanding: objects do not, in general, know any of the references there may be to them. > The following is what I would like to do: I have a list of class > instances dk = [ a, b, c, d ], where a, b, c, d is an object > reference. Note that, after that list is created, each item in that list is *also* a reference to the corresponding object. That is, ?a? is a reference to an object, and ?dk[0]? is a *different* reference to the *same* object. The object has no knowledge about those references. > Entering dk gives me the object: [MyClass0 instance at 0x0000, > MyClass1 instance at 0x0008, MyClass2 instance at 0x0010 ... ] This is a hint that, when asked for a string representation, each of the objects in that list can say little more than that they are of a particular type, and are located at a particular memory address. They do not know any of the references to themselves. > I need the object reference name (a,b,c,d) from dk to use as input for > a file. You'll have to track that yourself. A good way to keep track of name-to-object mappings is with Python's built-in mapping type, ?dict?:: dk = {'a': a, 'b': b, 'c': c, 'd': d} (There are more efficient ways to create a dictionary without such repetition, of course, but this is more illustrative of the point.) You can then get a list (assembled in arbitrary sequence) of just the keys, or just the values, or the key-value pairs, from the dict with its ?keys?, ?values?, and ?items? methods respectively:: >>> dk = {'a': a, 'b': b, 'c': c, 'd': d} >>> dk.keys() ['a', 'c', 'd', 'b'] >>> dk.values() [, , , ] >>> dk.items() [('b', ), ('c', ), ('a', ), ('d', )] Each of these is even better used as the iterable for a ?for? loop:: >>> for (key, value) in dk.items(): ... print "Here is item named", key ... print value > My main focus of this post is: "How do I find and use object reference > memory locations?" You don't. Use the references in your code, forget about the memory addresses, and remember that container objects themselves contain references, so use them for organising your objects. -- \ ?Demagogue: One who preaches doctrines he knows to be untrue to | `\ men he knows to be idiots.? ?Henry L. Mencken | _o__) | Ben Finney From ben+python at benfinney.id.au Fri Aug 21 06:18:29 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 20:18:29 +1000 Subject: Sanitising arguments to shell commands References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> Message-ID: <87ws4xjwqy.fsf@benfinney.id.au> Jean-Michel Pichavant writes: > Can someone explain the difference with the shell argument ? giving > for instance an example of what True will do that False won't. The ?shell? argument to the ?subprocess.Popen? constructor specifies whether the command-line should be invoked directly (?shell=False?) or indirectly through invoking a shell (?shell=True?). If ?shell=False?, the command-line arguments are used as direct arguments to the kernel's ?run this program for me?. If ?shell=True? the command-line arguments are themselves passed to a new instance of the user's current shell, as a command line that *it* should invoke on the program's behalf. This allows the command line to be manipulated and interpolated etc., the way it would be if typed at a new shell prompt. Then, that shell will in turn ask the kernel ?run this program for me? as it normally does after processing the arguments. > I mean, I've read the doc, and to be honest, I didn't get it. I'm > concerned because I'm using subprocess, but I guess my shell arg has > been filled a little bit random.. Use ?shell=False? by default (which, since that's the default for ?subprocess.Popen?, means you can omit it entirely), and specify exactly the command line arguments you want the kernel to execute. Only if you know you want a shell process to be involved should you use ?shell=True?. -- \ ?Welchen Teil von ?Gestalt? verstehen Sie nicht? [What part of | `\ ?gestalt? don't you understand?]? ?Karsten M. Self | _o__) | Ben Finney From ben+python at benfinney.id.au Fri Aug 21 06:26:02 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 20:26:02 +1000 Subject: Sanitising arguments to shell commands References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> Message-ID: <87skfljwed.fsf@benfinney.id.au> Chris Rebert writes: > module shlex ? Simple lexical analysis > New in version 1.5.2. > "The shlex class makes it easy to write lexical analyzers for simple > syntaxes resembling that of the Unix shell." Exactly what I needed: >>> import shlex >>> user_configured_args = "--baz 'crunch cronch' --wobble" >>> filenames = ["spam.txt", "beans.txt"] >>> command_args = ["foo", "--bar"] >>> command_args.extend(shlex.split(user_configured_args)) >>> command_args.extend(filenames) >>> command_args ['foo', '--bar', '--baz', 'crunch cronch', '--wobble', 'spam.txt', 'beans.txt'] -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but if we get Sam Spade, we'll never have any puppies.? | _o__) ?_Pinky and The Brain_ | Ben Finney From gagsl-py2 at yahoo.com.ar Fri Aug 21 06:31:33 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Aug 2009 07:31:33 -0300 Subject: Zipimport leaks memory? References: <6CC019B5D220A147932441E798B252B910B0193FEF@NOK-EUMSG-05.mgdnok.nokia.com> Message-ID: En Thu, 20 Aug 2009 07:02:26 -0300, ashwin.u.rao at nokia.com escribi?: > We are currently trying to identify and fix all the memory leaks by just > doing Py_Initialize-PyRun_SimpleFile(some simple script)-Py_Finalize and > found that there are around 70 malloc-ed blocks which are not freed. One > of the significant contributor to this number is the 'files' object in > ZipImporter. I am not able to identify the reason for this leak and was > wondering if anyone on this list would help me out here. > > So, here goes : > > Since we have a zip file in our sys.path, this object is initialized and > added to the zip_directory_cache dict during Py_Initialize. One point to > note here is that there is no DECREF on the 'files' object after adding > it to the zip_directory_cache dict. > > When a module in a directory is imported(encoding.alias) then the > reference count of 'files' is increased. When this module is unloaded > during Py_Finalize-PyImport_Cleanup, the ref count of files object is > decremented properly. So at the end of Py_Finalize the files object > still has one reference count which is a result of it being an entry in > the zip_directory_cache. I didn't read the source, but isn't that the expected behavior? If the module is still referenced by zip_directory_cache, the reference count must be 1 or more. Maybe zip_directory_cache should be cleared at interpreter shutdown? -- Gabriel Genellina From inigoserna at gmail.com Fri Aug 21 07:58:38 2009 From: inigoserna at gmail.com (=?UTF-8?B?ScOxaWdvIFNlcm5h?=) Date: Fri, 21 Aug 2009 13:58:38 +0200 Subject: ncurses getch & unicode (was: decoding keyboard input when using curses) In-Reply-To: <0a683d75-ac07-40a6-8374-2a2e900ac0ba@j21g2000yqe.googlegroups.com> References: <65a1d6f80908200936g18b235fcw49d0047168cf9548@mail.gmail.com> <0a683d75-ac07-40a6-8374-2a2e900ac0ba@j21g2000yqe.googlegroups.com> Message-ID: <65a1d6f80908210458hfa33699m398d9af6eab67674@mail.gmail.com> 2009/8/21 Thomas Dickey : > On Aug 20, 6:12?pm, I?igo Serna wrote: >> ??????? c = win.getch() > > You're using "getch", not "get_wch" (Python's ncurses binding may/may > not have the latter). > curses getch returns 8-bit values, get_wch would return wider values. you are right, ncurses binding does not have get_wch, only getch, and this last is the only one called in ncurses library bindings. Anyway, I've written a patch to include the get_wch method in the bindings. See http://bugs.python.org/issue6755 Thanks for the clarification, I?igo From georavel at yahoo.com Fri Aug 21 08:46:07 2009 From: georavel at yahoo.com (Justin) Date: Fri, 21 Aug 2009 05:46:07 -0700 (PDT) Subject: list 'results' from maps.google then crawl Message-ID: <81b5a7ba-49c7-4750-ad1d-5564973b6b8c@v36g2000yqv.googlegroups.com> list 'results' from maps.google then crawl through the (engine of some sort) space to the 'results' website and look at it html to find the contact From jeanmichel at sequans.com Fri Aug 21 08:55:33 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 21 Aug 2009 14:55:33 +0200 Subject: Sanitising arguments to shell commands In-Reply-To: <87ws4xjwqy.fsf@benfinney.id.au> References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> <87ws4xjwqy.fsf@benfinney.id.au> Message-ID: <4A8E9945.40906@sequans.com> Ben Finney wrote: > Jean-Michel Pichavant writes: > > >> Can someone explain the difference with the shell argument ? giving >> for instance an example of what True will do that False won't. >> > > The ?shell? argument to the ?subprocess.Popen? constructor specifies > whether the command-line should be invoked directly (?shell=False?) or > indirectly through invoking a shell (?shell=True?). > > If ?shell=False?, the command-line arguments are used as direct > arguments to the kernel's ?run this program for me?. > > If ?shell=True? the command-line arguments are themselves passed to a > new instance of the user's current shell, as a command line that *it* > should invoke on the program's behalf. This allows the command line to > be manipulated and interpolated etc., the way it would be if typed at a > new shell prompt. Then, that shell will in turn ask the kernel ?run this > program for me? as it normally does after processing the arguments. > > >> I mean, I've read the doc, and to be honest, I didn't get it. I'm >> concerned because I'm using subprocess, but I guess my shell arg has >> been filled a little bit random.. >> > > Use ?shell=False? by default (which, since that's the default for > ?subprocess.Popen?, means you can omit it entirely), and specify exactly > the command line arguments you want the kernel to execute. Only if you > know you want a shell process to be involved should you use > ?shell=True?. > > Thank you Ben for the update. It's clear for me now, I've checked and I use it with no shell arg, except at one place, but I don't think it's intended and it happens to work anyway. I've added a small comment just in case it fails in the future. JM From rickbking at comcast.net Fri Aug 21 09:07:04 2009 From: rickbking at comcast.net (Rick King) Date: Fri, 21 Aug 2009 09:07:04 -0400 Subject: Sanitising arguments to shell commands In-Reply-To: <50697b2c0908210219i5e02c0cbq2d63bff891624ef4@mail.gmail.com> References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> <50697b2c0908210219i5e02c0cbq2d63bff891624ef4@mail.gmail.com> Message-ID: <4A8E9BF8.8040206@comcast.net> shlex doesn't handle unicode input though, so, in general, it's not a good solution. Rick King Southfield MI > http://docs.python.org/library/shlex.html > > module shlex ? Simple lexical analysis > New in version 1.5.2. > "The shlex class makes it easy to write lexical analyzers for simple > syntaxes resembling that of the Unix shell." > From countryone77 at yahoo.com Fri Aug 21 09:34:04 2009 From: countryone77 at yahoo.com (Bev in TX) Date: Fri, 21 Aug 2009 06:34:04 -0700 (PDT) Subject: Logging with SMTP Error on Mac Message-ID: Hi, I've done some Python programming, but I still consider myself a Python newbie. I have a Mac Pro OS X 10.5.8 system and I installed Python 2.6.2 (the latest package available for the Mac) yesterday. I was working through Matt Wilson's article on using the logging module: http://blog.tplus1.com/index.php/2007/09/28/the-python-logging-module-is-much-better-than-print-statements/ (If that does not work, then try: http://tinyurl.com/5v2lcy ) Everything worked great until his last example. My ISP does not provide e-mail, so I tried using gmail in the line that sets h2. I substituted "mailid" for my actual e-mail address in the following examples; in my test I used my actual e-mail ID. Also, I used the full path to the newly installed Python 2.6.2; otherwise it picked up the older Python 2.5: #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python First attempt: h2 = logging.handlers.SMTPHandler('smtp.gmail.com', 'mailid at gmail.com', ['mailid at gmail.com'],'ERROR log') However, that caused the following error to be issued: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/logging/handlers.py", line 868, in emit smtp.sendmail(self.fromaddr, self.toaddrs, msg) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/smtplib.py", line 698, in sendmail raise SMTPSenderRefused(code, resp, from_addr) SMTPSenderRefused: (530, '5.7.0 Must issue a STARTTLS command first. 7sm3867994qwf.47', 'mailid at gmail.com') I also tried providing my gmail userid/password, I tried adding a 5th, credential, argument, which is a tupple, (username,password) (new in 2.6). Second attempt: h2 = logging.handlers.SMTPHandler('smtp.gmail.com', 'mailid at gmail.com', ['mailid at gmail.com'],'ERROR log',('mailid at gmail.com','gmail- password')) However, that caused the following error message: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/logging/handlers.py", line 867, in emit smtp.login(self.username, self.password) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/smtplib.py", line 552, in login raise SMTPException("SMTP AUTH extension not supported by server.") SMTPException: SMTP AUTH extension not supported by server. I am able access gmail via Mac's Mail, in which it says that outgoing mail is going to: smtp.gmail.com:mailid I tried using that as the server in the Python script, but it could not find that server. Is this possible? If I am doing something incorrectly, would someone please indicate what it is? Thanks, Bev in TX From fabio at aptana.com Fri Aug 21 09:36:34 2009 From: fabio at aptana.com (Fabio Zadrozny) Date: Fri, 21 Aug 2009 10:36:34 -0300 Subject: Pydev 1.4.8 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.4.8 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Created public API for starting/finishing debug server * Import based on unresolved variables works correctly when the document is changed * Ignore error works correctly when the document is changed * No longer showing the replace button for the search Release Highlights in Pydev: ---------------------------------------------- * Debugger can jump to line * Reloading module when code changes in the editor if inside debug session * Usability improvement on the preferences pages (editor, code-formatter, comment block and code-style showing examples) * Pythonpath reported in the main tab was not correct for ironpython launch configs * Main module tab in launch configuration was not appearing for jython * Multiline block comments considering the current indentation (and working with tabs) * Hover works correctly when the document is changed * The interactive console no longer uses the UI thread (so, it doesn't make eclipse halt anymore on slow requests to the shell) * The interactive console save history now saves the contents in the same way they're written * When creating a python run, the classpath was being set (and overridden), which should only happen in jython runs * Fixed issue where a line with only tabs and a close parenthesis would have additional tabs entered on code-formatting * A Pydev (Jython) project can coexist with a JDT project (and properly use its info -- only project references worked previously) * Many small usability improvements (editors improved) * Verbosity option added to run as unit-test * No longer using respectJavaAccessibility=False for jython * When there are too many items to show in the debugger, handle it gracefully What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python, Jython and Iron Python development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer Aptana http://aptana.com/python Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Environment for Eclipse http://pydev.sf.net http://pydev.blogspot.com From jfine at pytex.org Fri Aug 21 09:36:35 2009 From: jfine at pytex.org (Jonathan Fine) Date: Fri, 21 Aug 2009 14:36:35 +0100 Subject: Using 'apply' as a decorator, to define constants Message-ID: Hi It might seem odd to use 'apply' as a decorator, but it can make sense. I want to write: # Top level in module. tags = where the list is most easily constructed using a function. And so I write: @apply def tags(): value = [] # complicated code return value And now 'tags' has the result of running the complicated code. Without using 'apply' as a decorator one alternative is def tmp(): value = [] # complicated code return value tags = tmp() del tmp Like all uses of decorators, it is simply syntactic sugar. It allows you to see, up front, what is going to happen. I think, once I get used to it, I'll get to like it. The way to read @apply def name(): # code is that we are defining 'name' to be the return value of the effectively anonymous function that follows. -- Jonathan From stefan_ml at behnel.de Fri Aug 21 09:37:44 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 21 Aug 2009 15:37:44 +0200 Subject: list 'results' from maps.google then crawl In-Reply-To: <81b5a7ba-49c7-4750-ad1d-5564973b6b8c@v36g2000yqv.googlegroups.com> References: <81b5a7ba-49c7-4750-ad1d-5564973b6b8c@v36g2000yqv.googlegroups.com> Message-ID: <4a8ea328$0$31861$9b4e6d93@newsspool3.arcor-online.net> Justin wrote: > list 'results' from maps.google then crawl through the (engine of some > sort) space to the 'results' website and look at it html to find the > contact Good idea. How do you know how to recognise the contact? He/she might come disguised. Stefan From sajmikins at gmail.com Fri Aug 21 10:23:30 2009 From: sajmikins at gmail.com (Simon Forman) Date: Fri, 21 Aug 2009 07:23:30 -0700 (PDT) Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: On Aug 21, 2:07?am, josef wrote: > To begin, I'm new with python. I've read a few discussions about > object references and I think I understand them. > > To be clear, Python uses a "Pass By Object Reference" model. > x = 1 > x becomes the object reference, while an object is created with the > type 'int', value 1, and identifier (id(x)). Doing this with a class, > x = myclass(), does the same thing, but with more or less object > attributes. Every object has a type and an identifier (id()), > according to the Python Language Reference for 2.6.2 section 3.1. > > x in both cases is the object reference. I would like to use the > object to refer to the object reference. If I have a gross > misunderstanding, please correct me. x is not the object reference, it's just a string used as a key in a dict (the value is the object reference): |>>> globals() |{'__builtins__': , '__name__': '__main__', '__doc__': None} |>>> x = 1 |>>> globals() |{'__builtins__': , '__name__': '__main__', '__doc__': None, 'x': 1} I don't understand what you're trying to do, but give up the idea of "object reference memory locations". Any name binding in python just associates a string with a object in one of various namespace dictionaries. HTH, ~Simon From tsuraan at gmail.com Fri Aug 21 10:50:01 2009 From: tsuraan at gmail.com (tsuraan) Date: Fri, 21 Aug 2009 09:50:01 -0500 Subject: Conditionally skipping the contents of a with-statement Message-ID: <84fb38e30908210750v212339c2x2c87df33c2fcf069@mail.gmail.com> I'd like to write a Fork class to wrap os.fork that allows something like this: with Fork(): # to child stuff, end of block will automatically os._exit() # parent stuff goes here This would require (I think) that the __enter__ method of my Fork class to be able to return a value or raise an exception indicating that the block should not be run. It looks like, from PEP343, any exception thrown in the __enter__ isn't handled by with, and my basic tests confirm this. I could have __enter__ raise a custom exception and wrap the entire with statement in a try/except block, but that sort of defeats the purpose of the with statement. Is there a clean way for the context manager to signal that the execution of the block should be skipped altogether? From deets at nospam.web.de Fri Aug 21 11:02:08 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 21 Aug 2009 17:02:08 +0200 Subject: Conditionally skipping the contents of a with-statement In-Reply-To: References: Message-ID: <7f7r7hF2i7ba6U1@mid.uni-berlin.de> tsuraan schrieb: > I'd like to write a Fork class to wrap os.fork that allows something like this: > > with Fork(): > # to child stuff, end of block will automatically os._exit() > # parent stuff goes here > > This would require (I think) that the __enter__ method of my Fork > class to be able to return a value or raise an exception indicating > that the block should not be run. It looks like, from PEP343, any > exception thrown in the __enter__ isn't handled by with, and my basic > tests confirm this. I could have __enter__ raise a custom exception > and wrap the entire with statement in a try/except block, but that > sort of defeats the purpose of the with statement. Is there a clean > way for the context manager to signal that the execution of the block > should be skipped altogether? No. The only way would be something like this: with Fork() as is_child: if is_child: ... Diez From mhecht2909 at instant-mail.de Fri Aug 21 11:31:34 2009 From: mhecht2909 at instant-mail.de (M. Hecht) Date: Fri, 21 Aug 2009 08:31:34 -0700 (PDT) Subject: Three-Phase-Diagrams with matplotlib Message-ID: <25082083.post@talk.nabble.com> Hello, does anyone know whether it is possible to draw three-phase-diagrams with matplotlib? A three-phase-diagram is a triangular diagram applied in chemistry e.g. for slags where one has three main components of a chemical substance at the corners and points or lines within the triangle marking different compositions of the substances in percent, e.g. in metallurgy 20% Al2O3, 45% CaO and 35% SiO2. -- View this message in context: http://www.nabble.com/Three-Phase-Diagrams-with-matplotlib-tp25082083p25082083.html Sent from the Python - python-list mailing list archive at Nabble.com. From martin at v.loewis.de Fri Aug 21 11:36:53 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Aug 2009 17:36:53 +0200 Subject: pypi category In-Reply-To: References: Message-ID: <4A8EBF15.2090006@v.loewis.de> > Would someone be able to inform me how a category can be added to the > pypy list of categories? > I'd like to add a CAD & Geometry category. > ( I develop PythonOCC, wrappers for the OpenCASCADE CAD kernel, which > is why ) Make a specific proposal to catalog-sig at lists.python.org, along with a list of packages that are already on PyPI that could use that classifier. Having a classifier that classifies zero or one package is pointless. Regards, Martin From martin at v.loewis.de Fri Aug 21 11:39:09 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Aug 2009 17:39:09 +0200 Subject: 2.6 windows install In-Reply-To: <1e18d400-03ec-48ae-b59d-72aa6f5d9f64@l5g2000pra.googlegroups.com> References: <1e18d400-03ec-48ae-b59d-72aa6f5d9f64@l5g2000pra.googlegroups.com> Message-ID: <4A8EBF9D.6020306@v.loewis.de> > Did you install Python to the network device from your XP box? That > would explain why you can run it: the required registry settings & > environment variables are added by the installer, none of which is > occurring on any computer other than the one from which you installed. In principle, Python doesn't need any registry settings or environment variables in order to run. Regards, Martin From wuwei23 at gmail.com Fri Aug 21 12:09:02 2009 From: wuwei23 at gmail.com (alex23) Date: Fri, 21 Aug 2009 09:09:02 -0700 (PDT) Subject: Using 'apply' as a decorator, to define constants References: Message-ID: On Aug 21, 11:36?pm, Jonathan Fine wrote: > It might seem odd to use 'apply' as a decorator, but it can make sense. Yes, it's an idiom I've used myself for property declarations, but one I find myself using less often: class ColourThing(object): @apply def rgb(): def fset(self, rgb): self.r, self.g, self.b = rgb def fget(self): return (self.r, self.g, self.b) return property(**locals()) Unfortunately, apply() has been removed as a built-in in 3.x. I'm not sure if it has been relocated to a module somewhere, there's no mention of such in the docs. > Without using 'apply' as a decorator one alternative is > ? ? ?def tmp(): > ? ? ? ? ?value = [] > ? ? ? ? ?# complicated code > ? ? ? ? ?return value > ? ? ?tags = tmp() > ? ? ?del tmp You can save yourself the tidy up by using the same name for the function & the label: def tags(): value = [] # ... return value tags = tags() > Like all uses of decorators, it is simply syntactic sugar. ?It allows > you to see, up front, what is going to happen. ?I think, once I get used > to it, I'll get to like it. The question is, is it really that useful, or is it just a slight aesthetic variation? Given that apply(f, args, kwargs) is identical to f(*args, **kwargs), it's understandable that's apply() isn't seen as worth keeping in the language. Why I've personally stopped using it: I've always had the impression that decorators were intended to provide a convenient and obvious way of augmenting functions. Having one that automatically executes the function at definition just runs counter to the behaviour I expect from a decorator. Especially when direct assignment... foo = foo () ...is a far more direct and clear way of expressing exactly what is happening. But that's all IMO, if you feel it makes your code cleaner and don't plan on moving to 3.x any time soon (come on in! the water's great!), go for it :) From josefg at gmail.com Fri Aug 21 12:12:36 2009 From: josefg at gmail.com (josef) Date: Fri, 21 Aug 2009 09:12:36 -0700 (PDT) Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <8763chldpd.fsf@benfinney.id.au> Message-ID: On Aug 21, 4:26?am, Ben Finney wrote: > josef writes: > > To be clear, Python uses a "Pass By Object Reference" model. > > Yes. (I'm glad this concept has propagated to newcomers so well :-) I found one really good discussion on python semantics versus other languages. It gave me this gem of a quote: "When I turn on the TV and see Chuck Norris, though, I know it's only a reference to Chuck Norris, or I would be blinded. The only case he needs is "Pass By Roundhouse Kick"." -Chuckk > > > x = 1 > > x becomes the object reference > > It becomes *a* reference to that object, independent of any other > references to that same object. > > > while an object is created with the type 'int', value 1, and > > identifier (id(x)). > > Not really ?while?. The object creation happens first, then the > assignment statement binds a reference to that object. > > > Doing this with a class, x = myclass(), does the same thing, but with > > more or less object attributes. Every object has a type and an > > identifier (id()), according to the Python Language Reference for > > 2.6.2 section 3.1. > > Any expression can be on the right side of the assignment operator. The > expression will evaluate to some object, which the assignment will then > bind to the reference on the left side of the assignment operator. > > > x in both cases is the object reference. > > It is *an* object reference; that is, it's an identifier which refers to > an object. There's nothing about that identifier that makes it ?the (one > and only) object reference?. > > > I would like to use the object to refer to the object reference. If I > > have a gross misunderstanding, please correct me. > > Yes, it's a simple misunderstanding: objects do not, in general, know > any of the references there may be to them. > > > The following is what I would like to do: I have a list of class > > instances dk = [ a, b, c, d ], where a, b, c, d is an object > > reference. > > Note that, after that list is created, each item in that list is *also* > a reference to the corresponding object. That is, ?a? is a reference to > an object, and ?dk[0]? is a *different* reference to the *same* object. > The object has no knowledge about those references. This is surprising. My initial thought is that dk[0] hold the object reference 'a,' but that wouldn't be true "pass by object reference." When defining the object reference dk[0], python takes the object reference 'a,' finds the object MyClass0(), and then assigns the object identity to dk[0]? Or something close to that. > > > Entering dk gives me the object: [MyClass0 instance at 0x0000, > > MyClass1 instance at 0x0008, MyClass2 instance at 0x0010 ... ] > > This is a hint that, when asked for a string representation, each of the > objects in that list can say little more than that they are of a > particular type, and are located at a particular memory address. They do > not know any of the references to themselves. > > > I need the object reference name (a,b,c,d) from dk to use as input for > > a file. > > You'll have to track that yourself. I'm a bit shocked that there isn't a method for catching object reference names. I think that something like a = MyClass0(name = 'a', ...) is a bit redundant. Are definitions treated the same way? How would one print or pass function names? > > A good way to keep track of name-to-object mappings is with Python's > built-in mapping type, ?dict?:: > > ? ? dk = {'a': a, 'b': b, 'c': c, 'd': d} > > (There are more efficient ways to create a dictionary without such > repetition, of course, but this is more illustrative of the point.) > > You can then get a list (assembled in arbitrary sequence) of just the > keys, or just the values, or the key-value pairs, from the dict with its > ?keys?, ?values?, and ?items? methods respectively:: > > ? ? >>> dk = {'a': a, 'b': b, 'c': c, 'd': d} > ? ? >>> dk.keys() > ? ? ['a', 'c', 'd', 'b'] > ? ? >>> dk.values() > ? ? [, , , ] > ? ? >>> dk.items() > ? ? [('b', ), ('c', ), ('a', ?), ('d', ?)] > > Each of these is even better used as the iterable for a ?for? loop:: > > ? ? >>> for (key, value) in dk.items(): > ? ? ... ? ? print "Here is item named", key > ? ? ... ? ? print value I think I'll just add a 'name' to the classes' init defintion. > > > My main focus of this post is: "How do I find and use object reference > > memory locations?" > > You don't. Use the references in your code, forget about the memory > addresses, and remember that container objects themselves contain > references, so use them for organising your objects. > > -- > ?\ ? ? ?Demagogue: One who preaches doctrines he knows to be untrue to | > ? `\ ? ? ? ? ? ? ? ? ? ? men he knows to be idiots.? ?Henry L. Mencken | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| > Ben Finney Thanks, Josef From jamie.ivanov at gmail.com Fri Aug 21 12:33:57 2009 From: jamie.ivanov at gmail.com (Jamie) Date: Fri, 21 Aug 2009 09:33:57 -0700 (PDT) Subject: Problem with winreg - The object is not a PyHKEY object Message-ID: My goal is to remotely remove the registry keys for McAfee. I don't know how winreg handles an exception if a key doesn't exist, but I setup my script to skip the exception. But it doesn't seem to work right.. I think the script should be self explanitory, please help! Please forgive me, but I'm a python newbie. ## SCRIPT ## import _winreg print "Removing McAfee registry entries" hkey = _winreg.ConnectRegistry(r'\ \000000439140PC',_winreg.HKEY_LOCAL_MACHINE) try: _winreg.DeleteKey('SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFEAPFK') except: pass #try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFEAVFK') #except: # pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFEBOPK') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFEHIDK') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFEHIDK01') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFERKDK') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFETDIK') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_NAIAVFILTER1') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_NAIAVFILTER101') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MCSHIELD') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','MCTASKMANAGER') except: pass try: _winreg.DeleteKey('\SOFTWARE','McAfee') except: pass try: _winreg.DeleteKey('\SOFTWARE','Network Associates') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','AlertManager') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet \Services','McAfeeFramework') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','McShield') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet \Services','McTaskManager') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfeapfk') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfeavfk') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfebopk') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfehidk') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfehidk01') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mferkdk') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfetdik') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','NaiAvFilter1') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet \Services','NaiAvFilter101') except: pass ## END SCRIPT ## ## OUTPUT ## Removing McAfee registry entries Traceback (most recent call last): File "uninstallMcafee.py", line 11, in _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFEAVFK') TypeError: The object is not a PyHKEY object ## END OUTPUT ## From 71david at libero.it Fri Aug 21 12:35:07 2009 From: 71david at libero.it (David) Date: Fri, 21 Aug 2009 18:35:07 +0200 Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <7f5pohF2k259vU1@mid.dfncis.de> Message-ID: <12e1y7snryy06$.1r84z897tmw7u$.dlg@40tude.net> Il Thu, 20 Aug 2009 22:24:24 +0200, Johannes Bauer ha scritto: > David schrieb: > >> If I want an octal I'll use oct()! >> >> "Explicit is better than implicit..." > > A leading "0" *is* explicit. It isn't explicit enough, at least IMO. regards David From 71david at libero.it Fri Aug 21 12:40:55 2009 From: 71david at libero.it (David) Date: Fri, 21 Aug 2009 18:40:55 +0200 Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: <14hj3v50qg77e$.1pk6i6w7h7q6s.dlg@40tude.net> Il Thu, 20 Aug 2009 15:18:35 -0700 (PDT), Mensanator ha scritto: > (Just kidding! That works in 2.5 also. How are you using it where > it's coming out wrong? I can see you pulling '012' out of a text > file and want to calculate with it, but how would you use a > string without using int()? Passing it to functions that allow > string representations of numbers?) Obviously it's not a progamming issue, just a hassle using the interpreter on command line. David From Kevin.Smith at sixquickrun.com Fri Aug 21 12:43:31 2009 From: Kevin.Smith at sixquickrun.com (Kevin D. Smith) Date: Fri, 21 Aug 2009 11:43:31 -0500 Subject: 2.6 windows install References: <4A8EBF9D.6020306@v.loewis.de> Message-ID: On 2009-08-21 10:39:09 -0500, "Martin v. L?wis" said: >> Did you install Python to the network device from your XP box? That >> would explain why you can run it: the required registry settings & >> environment variables are added by the installer, none of which is >> occurring on any computer other than the one from which you installed. > > In principle, Python doesn't need any registry settings or environment > variables in order to run. That may be true, but it doesn't explain why python won't run. I'm guessing that it has something to do with the msvc*90.dll files not getting installed. If those dlls haven't been previously installed, they won't be on the client machine in order for python to use them. However, I haven't had any luck installing these files manually and getting python to work that way. -- Kevin D. Smith From 71david at libero.it Fri Aug 21 12:46:09 2009 From: 71david at libero.it (David) Date: Fri, 21 Aug 2009 18:46:09 +0200 Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: <1bzp9xkx7u4a4$.hp3xb39tz5vv.dlg@40tude.net> Il Thu, 20 Aug 2009 16:59:14 -0700 (PDT), James Harris ha scritto: > > It maybe made sense once but this relic of the past should have been > consigned to the waste bin of history long ago. I perfectly agree with you! David. From python at mrabarnett.plus.com Fri Aug 21 12:58:25 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 21 Aug 2009 17:58:25 +0100 Subject: Annoying octal notation In-Reply-To: <12e1y7snryy06$.1r84z897tmw7u$.dlg@40tude.net> References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <7f5pohF2k259vU1@mid.dfncis.de> <12e1y7snryy06$.1r84z897tmw7u$.dlg@40tude.net> Message-ID: <4A8ED231.3010409@mrabarnett.plus.com> David wrote: > Il Thu, 20 Aug 2009 22:24:24 +0200, Johannes Bauer ha scritto: > >> David schrieb: >> >>> If I want an octal I'll use oct()! >>> >>> "Explicit is better than implicit..." >> A leading "0" *is* explicit. > > It isn't explicit enough, at least IMO. > Is this better? Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> 010 File "", line 1 010 ^ I would've preferred it to be decimal unless there's a prefix: Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> 0x10 16 >>> 0o10 8 Ah well, something for Python 4. :-) From michele.petrazz at REMOTEME_unipex.it Fri Aug 21 13:14:07 2009 From: michele.petrazz at REMOTEME_unipex.it (Michele Petrazzo) Date: Fri, 21 Aug 2009 19:14:07 +0200 Subject: PIL and Python In-Reply-To: <5df342cf-c742-42d6-bc8c-97a3c44a0816@h21g2000yqa.googlegroups.com> References: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> <5df342cf-c742-42d6-bc8c-97a3c44a0816@h21g2000yqa.googlegroups.com> Message-ID: catafest wrote: > I don't extract data from jpegs. I wanna put some data in this > (copyright of my site) ... > My wrap for freeimage, called freeimagepy :) can't, as now, wrote exif information on the image, but since freeimage can do it, I think that it's not so difficult to add this type of feature. If you have some time for investigate and create a patch, I'll be happy to include it into the mainline! Contact me directly if you want to talk of need some help on how do it. Michele From apt.shansen at gmail.com Fri Aug 21 13:22:04 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Fri, 21 Aug 2009 10:22:04 -0700 Subject: Problem with winreg - The object is not a PyHKEY object In-Reply-To: References: Message-ID: <7a9c25c20908211022l751a2df8r5476887515272f1f@mail.gmail.com> On Fri, Aug 21, 2009 at 9:33 AM, Jamie wrote: > My goal is to remotely remove the registry keys for McAfee. I don't > know how winreg handles an exception if a key doesn't exist, but I > setup my script to skip the exception. But it doesn't seem to work > right.. I think the script should be self explanitory, please help! > Please forgive me, but I'm a python newbie. > > ## SCRIPT ## > > import _winreg > > print "Removing McAfee registry entries" > hkey = _winreg.ConnectRegistry(r'\ > \000000439140PC',_winreg.HKEY_LOCAL_MACHINE) > try: > _winreg.DeleteKey('SYSTEM\CurrentControlSet\Enum\Root','LEGACY_MFEAPFK') > except: > pass > You have to "open" the key first-- the first argument to .DeleteKey is not a string. E.g., do: key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Enum\Root') _winreg.DeleteKey(key, 'LEGACY_MFEAPFK' _winreg.CloseKey(key) The above is an example off the top of my head, not actually tested-- But that's sorta your problem, I believe: .DeleteKey operates on a key /handle/ in its first argument, not a string. The second argument is a string. HTH, --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From ryniek90 at gmail.com Fri Aug 21 13:33:29 2009 From: ryniek90 at gmail.com (ryniek90) Date: Fri, 21 Aug 2009 19:33:29 +0200 Subject: TypeError while checking for permissions with os.access() on windows xp In-Reply-To: References: Message-ID: <4A8EDA69.6030103@gmail.com> I've got some code that checks priviliges on two paths: First - chosen by user Second - hardcoded home directory represented by **os.getenv('HOME')** - (os.getenv('HOME') works both on Linux and Windows) Here's the code: " def __check_set_perm(self, rd_obj_path, backup_dest): try: if os.path.exists(rd_obj_path): if os.access(rd_obj_path, os.R_OK) != True: print "Have no permissions on [%s] for reading operation.\nTrying to set them..." % os.path.split(rd_obj_path)[1] if not os.path.isdir(rd_obj_path): os.chmod(rd_obj_path, stat.S_IREAD) else: for root, dirs, files in os.walk(rd_obj_path): for f in files: os.chmod(os.path.join(root, f), stat.S_IREAD) print "Get permissions for reading on [%s] successfully." % os.path.split(rd_obj_path)[1] else: print "Have permissions on [%s] for reading." % os.path.split(rd_obj_path)[1] if os.access(backup_dest, os.W_OK) != True: print "Have no permissions on [%s] for writing operation.\nTrying to set them..." % os.path.split(backup_dest)[1] os.chmod(backup_dest, stat.S_IWRITE) print "Get permissions for reading on [%s] successfully." % os.path.split(backup_dest)[1] else: print "Have permissions on [%s] for writing." % os.path.split(backup_dest)[1] else: return "Can't find specified path - [%s]." % rd_obj_path sys.exit(0) except (Except), ex: return ex " This code is part of my backup script. When script checks for reading permission on 'user chosen path' it seems ok, but when it checks for writing permissions on 'home directory', (this line: **if os.access(backup_dest, os.W_OK) != True**), i get error: **TypeError: coercing to Unicode: need string or buffer, NoneType found** The second os.access check fails, but don't know why. When i turned os.W_OK to integer, i get the same error. But when changed os.W_OK or that int to string, i get error that integer is required. I'm launching this code on WinXP Prof+SP3, on Administrator account. Is it bug in os.acces() or my code is written wrong? Btw. i kow that os.chmod in windows can set only read-olny flag, so later i'll change the line with **os.chmod(path, stat.S_IWRITE)** Thanks and cheers. From piet at cs.uu.nl Fri Aug 21 13:36:00 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 21 Aug 2009 19:36:00 +0200 Subject: Python and PHP encryption/decryption References: <7f36e3F2it5a5U2@mid.uni-berlin.de> Message-ID: >>>>> "Diez B. Roggisch" (DBR) wrote: >DBR> Jean-Claude Neveu schrieb: >>> I'm looking for a recommendation about encryption/decryption packages for >>> Python. >>> >>> I'm working on a project that will require me to store some values in a >>> database in encrypted format. I'll be storing them from a PHP script and >>> retrieving them (decrypting them) using Python. I'm currently using PHP's >>> mcrypt package to encrypt the values, and I'm using AES for encryption, >>> so something AES-compatible would be ideal. However, the project is at >>> the development stage so I can easily change how I'm encrypting things in >>> PHP if there is a compelling reason on the Python side of things to do >>> so. >DBR> With PyCrypto[1] you have a wide range of choices, amongst others AES. >DBR> If that's the best algorithm, or even the best python-package to implement >DBR> it, I don't know. >DBR> [1] http://www.dlitz.net/software/pycrypto/ Pycrypto had been stalled in development. The latest release was in 2005. There is now a new developer and that it were the link above goes, but he has not yet released anything. so you will have to do with the 2005 release. There is an alternative library: m2crypto (http://chandlerproject.org/Projects/MeTooCrypto). It is built on top of OpenSSL which is available for most platforms that have Python whereas Pycrypto has its own C implementations of crypto algorithms. M2crypto has a recent release. Also I think because OpenSSL is widely used, its vulnerabilities are easier detected and corrected, whereas I don't think that is the case for Pycrypto. M2crypto is much bigger than you need for this project, however. If that doesn't bother you I would recommend it. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From mensanator at aol.com Fri Aug 21 13:36:35 2009 From: mensanator at aol.com (Mensanator) Date: Fri, 21 Aug 2009 10:36:35 -0700 (PDT) Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <14hj3v50qg77e$.1pk6i6w7h7q6s.dlg@40tude.net> Message-ID: On Aug 21, 11:40?am, David <71da... at libero.it> wrote: > Il Thu, 20 Aug 2009 15:18:35 -0700 (PDT), Mensanator ha scritto: > > > (Just kidding! That works in 2.5 also. How are you using it where > > it's coming out wrong? I can see you pulling '012' out of a text > > file and want to calculate with it, but how would you use a > > string without using int()? Passing it to functions that allow > > string representations of numbers?) > > Obviously it's not a progamming issue, just a hassle using the interpreter > on command line. Aha! Then I WAS right after all. Switch to 3.1 and you'll soon be cured of that bad habit: >>> 012 + 012 SyntaxError: invalid token (, line 1) > > David From nagle at animats.com Fri Aug 21 13:45:51 2009 From: nagle at animats.com (John Nagle) Date: Fri, 21 Aug 2009 10:45:51 -0700 Subject: Annoying octal notation In-Reply-To: <6a523329-3287-4271-ba37-7be450cfc5f6@d32g2000yqh.googlegroups.com> References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <6a523329-3287-4271-ba37-7be450cfc5f6@d32g2000yqh.googlegroups.com> Message-ID: <4a8edc29$0$1599$742ec2ed@news.sonic.net> Simon Forman wrote: > On Aug 20, 3:06 pm, David <71da... at libero.it> wrote: >> Hi all, >> >> Is there some magic to make the 2.x CPython interpreter to ignore the >> annoying octal notation? > > No. You would have to modify and recompile the interpreter. This is > not exactly trivial, see "How to Change Python's Grammar" > http://www.python.org/dev/peps/pep-0306/ > > However, see "Integer Literal Support and Syntax" http://www.python.org/dev/peps/pep-3127/ > > (Basically in 2.6 and onwards you can use 0oNNN notation.) Yes, and making lead zeros an error as suggested in PEP 3127 is a good idea. It will be interesting to see what bugs that flushes out. In 2009, Unisys finally exited the mainframe hardware business, and the last of the 36-bit machines, the ClearPath servers, are being phased out. That line of machines goes back to the UNIVAC 2200 series, and the UNIVAC 1100 series, all the way back to the vacuum-tube UNIVAC 1103 from 1952. It's the longest running series of computers in history, and code for all those machines used octal heavily. And it's over. We can finally dispense with octal by default. John Nagle From dickinsm at gmail.com Fri Aug 21 13:49:20 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 21 Aug 2009 10:49:20 -0700 (PDT) Subject: Python on Crays References: Message-ID: <1f5c81d8-4f79-4eea-b1bd-af48ab9ddc82@c2g2000yqi.googlegroups.com> On Aug 21, 12:21?am, Carrie Farberow wrote: > I am trying to build a statically-linked Python based on directions at: > > http://yt.enzotools.org/wiki/CrayXT5Installation > > I have tried this on multiple systems. ?The first time I attempt to build python, 'make' runs fine but 'make install' fails with the following error: > > Sorry: UnicodeError: ("\\N escapes not supported (can't load unicodedata module)",) > > Any help regarding the source of this error and possible fixes would be appreciated. Hmm. There's not a lot of information to go on here. What version of Python is this? Python 2.6.2? Have you tried Googling for that exact error message? The following issue looks as though it might be relevant: http://bugs.python.org/issue1594809 especially since it looks as though the directions you linked to involve messing with the PYTHONPATH environment variable. If you could post a log somewhere[*] showing the exact commands that you executed, along with all the output (and especially all the output from 'make' and 'make install'), that might help someone diagnose the problem further. Mark [*] I'm not sure where, though. Posting all that output directly in a newsgroup message might not be considered very friendly. From sajmikins at gmail.com Fri Aug 21 13:54:13 2009 From: sajmikins at gmail.com (Simon Forman) Date: Fri, 21 Aug 2009 10:54:13 -0700 (PDT) Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <8763chldpd.fsf@benfinney.id.au> Message-ID: On Aug 21, 12:12?pm, josef wrote: > > > I need the object reference name (a,b,c,d) from dk to use as input for > > > a file. > > > You'll have to track that yourself. > > I'm a bit shocked that there isn't a method for catching object > reference names. I think that something like a = MyClass0(name = > 'a', ...) is a bit redundant. Are definitions treated the same way? > How would one print or pass function names? There's no such thing as "object reference names". Object references do not have names. When you run a piece of code like "a = object()" a string "a" is used as a key in a dictionary and the value is the "object reference". Consider: [None][0] = object() (Create an anonymous list object with one item in it and immediately replace that item with an anonymous object instance.) There's no name to catch. Objects know nothing about their "enclosing" namespace. So if you want them to have names you have to explicitly give them name attributes. (However, this won't affect their enclosing namespaces.) As Bruno said, think of "foo = something" as shorthand for "some_namespace_dictionary['foo'] = something". The two exceptions to this are 'def' and 'class' statements which both create name->object (key, value) pairs in their current namespace AND give the objects they create '__name__' attributes (pretty much just as an aid to debugging.) In [1]: def foo(): pass ...: In [2]: foo.__name__ Out[2]: 'foo' In [3]: class foo(): pass ...: In [4]: foo.__name__ Out[4]: 'foo' > > A good way to keep track of name-to-object mappings is with Python's > > built-in mapping type, ?dict?:: > > > ? ? dk = {'a': a, 'b': b, 'c': c, 'd': d} > > > (There are more efficient ways to create a dictionary without such > > repetition, of course, but this is more illustrative of the point.) > > > You can then get a list (assembled in arbitrary sequence) of just the > > keys, or just the values, or the key-value pairs, from the dict with its > > ?keys?, ?values?, and ?items? methods respectively:: > > > ? ? >>> dk = {'a': a, 'b': b, 'c': c, 'd': d} > > ? ? >>> dk.keys() > > ? ? ['a', 'c', 'd', 'b'] > > ? ? >>> dk.values() > > ? ? [, , , ] > > ? ? >>> dk.items() > > ? ? [('b', ), ('c', ), ('a', ?), ('d', ?)] > > > Each of these is even better used as the iterable for a ?for? loop:: > > > ? ? >>> for (key, value) in dk.items(): > > ? ? ... ? ? print "Here is item named", key > > ? ? ... ? ? print value > > I think I'll just add a 'name' to the classes' init defintion. That's the way to do it. :] From ronn.ross at gmail.com Fri Aug 21 14:14:32 2009 From: ronn.ross at gmail.com (Ronn Ross) Date: Fri, 21 Aug 2009 14:14:32 -0400 Subject: convert date time Message-ID: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> I'm new to python and I'm getting a date time from a field in the database that looks like this: 8/2/2009 8:36:16 AM (UTC) I want to split it into two fields one with the date formatted like this: YYYY-MM-DD 2009-08-02 and the time to be 24 hour or military time. How every you call it. Similar to this: 15:22:00 I found it easy to truncate off the (UTC), but having trouble converting the date. Can someone point me in the right direction? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sajmikins at gmail.com Fri Aug 21 14:20:53 2009 From: sajmikins at gmail.com (Simon Forman) Date: Fri, 21 Aug 2009 11:20:53 -0700 (PDT) Subject: TypeError while checking for permissions with os.access() on windows xp References: Message-ID: On Aug 21, 1:33?pm, ryniek90 wrote: > I've got some code that checks priviliges on two paths: > First - chosen by user > Second - hardcoded home directory represented by **os.getenv('HOME')** - > (os.getenv('HOME') works both on Linux and Windows) > > Here's the code: > " > def __check_set_perm(self, rd_obj_path, backup_dest): > > ? ? ? ? try: > > ? ? ? ? ? ? if os.path.exists(rd_obj_path): > ? ? ? ? ? ? ? ? if os.access(rd_obj_path, os.R_OK) != True: > ? ? ? ? ? ? ? ? ? ? print "Have no permissions on [%s] for reading > operation.\nTrying to set them..." % os.path.split(rd_obj_path)[1] > ? ? ? ? ? ? ? ? ? ? if not os.path.isdir(rd_obj_path): > ? ? ? ? ? ? ? ? ? ? ? ? os.chmod(rd_obj_path, stat.S_IREAD) > ? ? ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? for root, dirs, files in os.walk(rd_obj_path): > ? ? ? ? ? ? ? ? ? ? ? ? ? ? for f in files: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? os.chmod(os.path.join(root, f), > stat.S_IREAD) > ? ? ? ? ? ? ? ? ? ? print "Get permissions for reading on [%s] > successfully." % os.path.split(rd_obj_path)[1] > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? print "Have permissions on [%s] for reading." % > os.path.split(rd_obj_path)[1] > > ? ? ? ? ? ? ? ? if os.access(backup_dest, os.W_OK) != True: > ? ? ? ? ? ? ? ? ? ? print "Have no permissions on [%s] for writing > operation.\nTrying to set them..." % os.path.split(backup_dest)[1] > ? ? ? ? ? ? ? ? ? ? os.chmod(backup_dest, stat.S_IWRITE) > ? ? ? ? ? ? ? ? ? ? print "Get permissions for reading on [%s] > successfully." % os.path.split(backup_dest)[1] > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? print "Have permissions on [%s] for writing." % > os.path.split(backup_dest)[1] > ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? return "Can't find specified path - [%s]." % rd_obj_path > ? ? ? ? ? ? ? ? sys.exit(0) > > ? ? ? ? except (Except), ex: > ? ? ? ? ? ? return ex > " > > This code is part of my backup script. When script checks for reading > permission on 'user chosen path' it seems ok, but when it checks for > writing permissions on 'home directory', (this line: **if > os.access(backup_dest, os.W_OK) != True**), i get error: > **TypeError: coercing to Unicode: need string or buffer, NoneType found** > The second os.access check fails, but don't know why. When i turned > os.W_OK to integer, i get the same error. > But when changed os.W_OK or that int to string, i get error that integer > is required. I'm launching this code on WinXP Prof+SP3, on Administrator > account. Is it bug in os.acces() or my code is written wrong? > Btw. i kow that os.chmod in windows can set only read-olny flag, so > later i'll change the line with **os.chmod(path, stat.S_IWRITE)** > > Thanks and cheers. First, some nitpicking: Include the whole traceback when posting about errors please. Don't write "if some_boolean_expression != True:" instead prefer "if not some_boolean_expression:". Also, in your code "except (Except), ex: return ex" the parentheses are redundant, there's no "Except" Exception (unless you created one yourself) and why are you catching and returning the Exception object? (Also, what's that "sys.exit(0)" doing in there? And why exit with 0 if there was a problem? Exit code 0 means "no problem".) Second, from what you've said backup_dest must be None: >>> import os >>> os.access(None, os.W_OK) Traceback (most recent call last): File "", line 1, in os.access(None, os.W_OK) TypeError: coercing to Unicode: need string or buffer, NoneType found From darcy at druid.net Fri Aug 21 14:26:38 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 21 Aug 2009 14:26:38 -0400 Subject: convert date time In-Reply-To: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> References: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> Message-ID: <20090821142638.92d91382.darcy@druid.net> On Fri, 21 Aug 2009 14:14:32 -0400 Ronn Ross wrote: > I want to split it into two fields one with the date formatted like this: > YYYY-MM-DD 2009-08-02 > > and the time to be 24 hour or military time. How every you call it. Similar > to this: > 15:22:00 > > I found it easy to truncate off the (UTC), but having trouble converting the > date. Can someone point me in the right direction? You don't say what database you are using but you may find it simpler to do the conversion in your SELECT statement. For example, see http://www.postgresql.org/docs/8.3/static/functions-formatting.html for PostgreSQL formatting functions. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From tommy.nordgren at comhem.se Fri Aug 21 14:29:08 2009 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Fri, 21 Aug 2009 20:29:08 +0200 Subject: Mac OS 9.2 In-Reply-To: <96ab6db4-55c5-4142-8ef8-d7fbe97e4c4d@f37g2000yqn.googlegroups.com> References: <96ab6db4-55c5-4142-8ef8-d7fbe97e4c4d@f37g2000yqn.googlegroups.com> Message-ID: <8683E1B6-367C-4A05-B6FA-667F0D4FC7DF@comhem.se> On Aug 18, 2009, at 6:04 PM, madzientist wrote: > hi, > > i have to work with mac OS 9.2 for legacy reasons...is there a > compiled version of python for this os ? i need to get input about > variable values from the user and then print out some text files that > make use of this input. a gui would be nice, but keyboard based input > would be ok too... > > thanks much, > > suresh > > ps. if there isn't a version of pythn that will work, perhaps you > could suggest some other scripting language for 0S 9.2 ? > -- > http://mail.python.org/mailman/listinfo/python-list There was a port (MacPython) of versions 2.3 and 2.3 that worked on MacOS 9 Maybe Google will help you locate a copy. ------ What is a woman that you forsake her, and the hearth fire and the home acre, to go with the old grey Widow Maker. --Kipling, harp song of the Dane women Tommy Nordgren tommy.nordgren at comhem.se From dullrich at sprynet.com Fri Aug 21 14:36:02 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Fri, 21 Aug 2009 13:36:02 -0500 Subject: Silly question References: <97ae0d22-7eaa-4ad6-8603-69699703d508@u16g2000pru.googlegroups.com> Message-ID: On Thu, 20 Aug 2009 17:45:11 -0700, John Machin wrote: > On Aug 21, 5:33?am, David C Ullrich wrote: > >> So I'm slow, fine. (There were several times when I was using 1.5.3 and >> wished they were there - transposing matrices, etc.) > > 1.5.THREE ?? Not sure. 1.SOMETHING. Sorry about the CONFUSION... From ronn.ross at gmail.com Fri Aug 21 14:43:55 2009 From: ronn.ross at gmail.com (Ronn Ross) Date: Fri, 21 Aug 2009 14:43:55 -0400 Subject: convert date time In-Reply-To: <20090821142638.92d91382.darcy@druid.net> References: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> <20090821142638.92d91382.darcy@druid.net> Message-ID: <9c8c445f0908211143g38382e7aocbee20155e525573@mail.gmail.com> On Fri, Aug 21, 2009 at 2:26 PM, D'Arcy J.M. Cain wrote: > On Fri, 21 Aug 2009 14:14:32 -0400 > Ronn Ross wrote: > > I want to split it into two fields one with the date formatted like this: > > YYYY-MM-DD 2009-08-02 > > > > and the time to be 24 hour or military time. How every you call it. > Similar > > to this: > > 15:22:00 > > > > I found it easy to truncate off the (UTC), but having trouble converting > the > > date. Can someone point me in the right direction? > > You don't say what database you are using but you may find it simpler > to do the conversion in your SELECT statement. For example, see > http://www.postgresql.org/docs/8.3/static/functions-formatting.html for > PostgreSQL formatting functions. > > -- > D'Arcy J.M. Cain | Democracy is three wolves > http://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. > I apologize I should have made it clear that this date is stored in the db as a string/varchar. The reason it is stored that way is before it's being read in from a text file where it is formatted that way. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jfine at pytex.org Fri Aug 21 15:23:51 2009 From: jfine at pytex.org (Jonathan Fine) Date: Fri, 21 Aug 2009 20:23:51 +0100 Subject: Using 'apply' as a decorator, to define constants In-Reply-To: References: Message-ID: <_L2dne59TJ3baRPXnZ2dnUVZ8gCdnZ2d@brightview.co.uk> alex23 wrote: > Unfortunately, apply() has been removed as a built-in in 3.x. I'm not > sure if it has been relocated to a module somewhere, there's no > mention of such in the docs. The old use of apply() > You can save yourself the tidy up by using the same name for the > function & the label: > > def tags(): > value = [] > # ... > return value > tags = tags() I don't like that because there's no hint at def tags(): that this is /not/ the value of tags. >> Like all uses of decorators, it is simply syntactic sugar. It allows >> you to see, up front, what is going to happen. I think, once I get used >> to it, I'll get to like it. > > The question is, is it really that useful, or is it just a slight > aesthetic variation? Given that apply(f, args, kwargs) is identical to > f(*args, **kwargs), it's understandable that's apply() isn't seen as > worth keeping in the language. Yes, I agree with that, completely. > Why I've personally stopped using it: I've always had the impression > that decorators were intended to provide a convenient and obvious way > of augmenting functions. Yes, that was the intended use case. > Having one that automatically executes the > function at definition just runs counter to the behaviour I expect > from a decorator. I'd expect the name of the decorator to explain what is going on. If apply() were a well known part of the language, that would be fine. > Especially when direct assignment... foo = foo > () ...is a far more direct and clear way of expressing exactly what is > happening. Actually, I think the decorator approach is clearer. But that's just my opinion, and not with the benefit of a lot of experience. > But that's all IMO, if you feel it makes your code cleaner and don't > plan on moving to 3.x any time soon (come on in! the water's great!), > go for it :) Thank you for your comments, Alex. And particularly for telling me that apply() is no longer a builtin for Python 3. -- Jonathan From dullrich at sprynet.com Fri Aug 21 15:40:30 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Fri, 21 Aug 2009 14:40:30 -0500 Subject: Silly question References: Message-ID: On Thu, 20 Aug 2009 16:51:00 -0700, Aahz wrote: > In article , > Benjamin Kaplan wrote: >>On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrich >>wrot= e: >>> >>> I just noticed that >>> sequence[i:j:k] >> >>Well, I got some good news and some bad news. According to the docs, it >>existed in 1.4 but the built-in sequences didn't support it until 2.3. >>It's not used that often anyway so you haven't been missing much. > > Except that it's canonical for one specific operation: > > 'reverseme'[::-1] It's like you guys are a bunch of programmers or something: from math import sqrt def Primes(n): """Return a list of the primes < n""" sieve = range(n) for k in range(2,int(sqrt(n))+2): sieve[::k] = [1]*((n+k-1)/k) return [p for p in sieve if p > 1] From darcy at druid.net Fri Aug 21 15:42:27 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 21 Aug 2009 15:42:27 -0400 Subject: convert date time In-Reply-To: <9c8c445f0908211143g38382e7aocbee20155e525573@mail.gmail.com> References: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> <20090821142638.92d91382.darcy@druid.net> <9c8c445f0908211143g38382e7aocbee20155e525573@mail.gmail.com> Message-ID: <20090821154227.b9fe0bdd.darcy@druid.net> On Fri, 21 Aug 2009 14:43:55 -0400 Ronn Ross wrote: > On Fri, Aug 21, 2009 at 2:26 PM, D'Arcy J.M. Cain wrote: > > You don't say what database you are using but you may find it simpler > > to do the conversion in your SELECT statement. For example, see > > http://www.postgresql.org/docs/8.3/static/functions-formatting.html for > > PostgreSQL formatting functions. > > > I apologize I should have made it clear that this date is stored in the db > as a string/varchar. The reason it is stored that way is before it's being > read in from a text file where it is formatted that way. You can still save it as a timestamp: SELECT '8/2/2009 8:36:16 AM (UTC)'::timestamp(0); timestamp --------------------- 2009-08-02 08:36:16 (1 row) Your input format is read into PostgreSQL time types directly. Same may be true of other databases. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From dullrich at sprynet.com Fri Aug 21 15:45:55 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Fri, 21 Aug 2009 14:45:55 -0500 Subject: Silly question References: Message-ID: On Fri, 21 Aug 2009 14:40:30 -0500, David C Ullrich wrote: > On Thu, 20 Aug 2009 16:51:00 -0700, Aahz wrote: > >> In article , >> Benjamin Kaplan wrote: >>>On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrich >>>wrot= e: >>>> >>>> I just noticed that >>>> sequence[i:j:k] >>> >>>Well, I got some good news and some bad news. According to the docs, it >>>existed in 1.4 but the built-in sequences didn't support it until 2.3. >>>It's not used that often anyway so you haven't been missing much. >> >> Except that it's canonical for one specific operation: >> >> 'reverseme'[::-1] > > It's like you guys are a bunch of programmers or something: > > from math import sqrt > > def Primes(n): > """Return a list of the primes < n""" sieve = range(n) > for k in range(2,int(sqrt(n))+2): > sieve[::k] = [1]*((n+k-1)/k) > return [p for p in sieve if p > 1] Oops. Should have tested that a little more carefully before posting. No time to fix it right now, customer just got here. Let's just say we're looking for the primes between sqrt(n) and n... From code at pizzashack.org Fri Aug 21 15:48:57 2009 From: code at pizzashack.org (Derek Martin) Date: Fri, 21 Aug 2009 14:48:57 -0500 Subject: Annoying octal notation Message-ID: <20090821194857.GU20434@dragontoe.org> John Nagle wrote: > Yes, and making lead zeros an error as suggested in PEP 3127 is a > good idea. It will be interesting to see what bugs that flushes > out. James Harris wrote: > It maybe made sense once but this relic of the past should have been > consigned to the waste bin of history long ago. Sigh. Nonsense. I use octal notation *every day*, for two extremely prevalent purposes: file creation umask, and Unix file permissions (i.e. the chmod() function/command). I fail to see how 0O012, or even 0o012 is more intelligible than 012. The latter reads like a typo, and the former is virtually indistinguishable from 00012, O0012, or many other combinations that someone might accidentally type (or intentionally type, having to do this in dozens of other programming languages). I can see how 012 can be confusing to new programmers, but at least it's legible, and the great thing about humans is that they can be taught (usually). I for one think this change is completely misguided. More than flushing out bugs, it will *cause* them in ubiquity, requiring likely terabytes of code to be poured over and fixed. Changing decades-old behaviors common throughout a community for the sake of avoiding a minor inconvenience of the n00b is DUMB. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From dickey at his.com Fri Aug 21 15:53:17 2009 From: dickey at his.com (Thomas Dickey) Date: Fri, 21 Aug 2009 15:53:17 -0400 (EDT) Subject: ncurses getch & unicode (was: decoding keyboard input when using curses) In-Reply-To: <65a1d6f80908210458hfa33699m398d9af6eab67674@mail.gmail.com> References: <65a1d6f80908200936g18b235fcw49d0047168cf9548@mail.gmail.com> <0a683d75-ac07-40a6-8374-2a2e900ac0ba@j21g2000yqe.googlegroups.com> <65a1d6f80908210458hfa33699m398d9af6eab67674@mail.gmail.com> Message-ID: <20090821155306.K929@mail101.his.com> On Fri, 21 Aug 2009, I?igo Serna wrote: > 2009/8/21 Thomas Dickey : >> On Aug 20, 6:12?pm, I?igo Serna wrote: >>> ??????? c = win.getch() >> >> You're using "getch", not "get_wch" (Python's ncurses binding may/may >> not have the latter). >> curses getch returns 8-bit values, get_wch would return wider values. > > you are right, ncurses binding does not have get_wch, only getch, and > this last is the only one called in ncurses library bindings. > > > Anyway, I've written a patch to include the get_wch method in the bindings. > See http://bugs.python.org/issue6755 > > > Thanks for the clarification, no problem (report bugs) > I?igo > -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net From Kevin.Smith at sixquickrun.com Fri Aug 21 15:58:50 2009 From: Kevin.Smith at sixquickrun.com (Kevin D. Smith) Date: Fri, 21 Aug 2009 14:58:50 -0500 Subject: 2.6 windows install References: <4A8EBF9D.6020306@v.loewis.de> Message-ID: On 2009-08-21 11:43:31 -0500, Kevin D. Smith said: > On 2009-08-21 10:39:09 -0500, "Martin v. L?wis" said: > >>> Did you install Python to the network device from your XP box? That >>> would explain why you can run it: the required registry settings & >>> environment variables are added by the installer, none of which is >>> occurring on any computer other than the one from which you installed. >> >> In principle, Python doesn't need any registry settings or environment >> variables in order to run. > > That may be true, but it doesn't explain why python won't run. I'm > guessing that it has something to do with the msvc*90.dll files not > getting installed. If those dlls haven't been previously installed, > they won't be on the client machine in order for python to use them. > However, I haven't had any luck installing these files manually and > getting python to work that way. Installing those files from does seem to help, but python still gives an error of "The application failed to initialize properly (0xc00000022)." I'm not really sure where to go from here. -- Kevin D. Smith From travis+ml-python at subspacefield.org Fri Aug 21 16:09:08 2009 From: travis+ml-python at subspacefield.org (Travis) Date: Fri, 21 Aug 2009 15:09:08 -0500 Subject: zlib interface semi-broken In-Reply-To: <20090212172619.GG6522@subspacefield.org> References: <20090210205739.GT6522@subspacefield.org> <20090212172619.GG6522@subspacefield.org> Message-ID: <20090821200908.GI1215@subspacefield.org> I've come up with a good test for issue5210 and uploaded it to the bug tracker. This patch should be ready for inclusion now. -- Obama Nation | My emails do not have attachments; it's a digital signature that your mail program doesn't understand. | http://www.subspacefield.org/~travis/ If you are a spammer, please email john at subspacefield.org to get blacklisted. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 850 bytes Desc: not available URL: From travis at subspacefield.org Fri Aug 21 16:13:12 2009 From: travis at subspacefield.org (travis at subspacefield.org) Date: Fri, 21 Aug 2009 15:13:12 -0500 Subject: proposal: add setresuid() system call to python In-Reply-To: <20090717205953.2543.1223422516.divmod.quotient.3129@henry.divmod.com> References: <20090717200141.GI6065@subspacefield.org> <20090717205953.2543.1223422516.divmod.quotient.3129@henry.divmod.com> Message-ID: <20090821201312.GJ1215@subspacefield.org> On Fri, Jul 17, 2009 at 04:59:53PM -0400, Jean-Paul Calderone wrote: > On Fri, 17 Jul 2009 15:01:41 -0500, travis+ml-python at subspacefield.org wrote: >> I am suggesting that the setresuid function be added to python, >> perhaps in the OS module, because it has the clearest semantics for >> manipulating user ids. The reason why is best described in the >> following paper: > > Yes, it'd be good for Python to expose setresuid. The best course of > action is to file a ticket in the issue tracker. Things will be sped > along if you also attach a patch implementing the change. :) I'm now working on this as issue6758 in the tracker. Adding the calls to the os module doesn't seem like a good idea to me, because the calls are not POSIX, and it appears that os maps to posixmodule.c. Since the authors of the paper (Wagner et. al.) are proposing a new set of APIs to make all of this clearer, I'm thinking that I will create a module specifically for dropping permissions. -- Obama Nation | My emails do not have attachments; it's a digital signature that your mail program doesn't understand. | http://www.subspacefield.org/~travis/ If you are a spammer, please email john at subspacefield.org to get blacklisted. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 850 bytes Desc: not available URL: From mccredie at gmail.com Fri Aug 21 16:20:11 2009 From: mccredie at gmail.com (Matimus) Date: Fri, 21 Aug 2009 13:20:11 -0700 (PDT) Subject: 2.6 windows install References: Message-ID: On Aug 20, 10:21?am, "Tim Arnold" wrote: > Hi, > I installed python2.6 to a netapp device. I can use it from my local windows > machine (XP). But others cannot use it from their pcs. > > They get this response > "The system cannot execute the specified program.". > > If they double click on python.exe, they get a window > > with: This application has failed to start because the application > > configuration is incorrect. ?Reinstalling the application may fix this > > problem. > > When I installed it I didn't see any mention of an 'administrators' install, > it just installed. The permissions on the directories where it installed are > set wide-open for everyone. > > Any ideas on what I'm missing here? > > thanks, > --Tim Arnold The default windows install puts Python26.dll in \windows\system32. I haven't tried this, but you could probably fix your install by moving Python26.dll into the Python26 directory. That being said, the usual thing to do would be to install it on each machine. Matt From benjamin at python.org Fri Aug 21 16:22:47 2009 From: benjamin at python.org (Benjamin Peterson) Date: Fri, 21 Aug 2009 20:22:47 +0000 (UTC) Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <6a523329-3287-4271-ba37-7be450cfc5f6@d32g2000yqh.googlegroups.com> Message-ID: Simon Forman gmail.com> writes: > No. You would have to modify and recompile the interpreter. This is > not exactly trivial, see "How to Change Python's Grammar" > http://www.python.org/dev/peps/pep-0306/ And even that's incorrect. You'd have to modify the tokenizer. From benjamin at python.org Fri Aug 21 16:25:45 2009 From: benjamin at python.org (Benjamin Peterson) Date: Fri, 21 Aug 2009 20:25:45 +0000 (UTC) Subject: Annoying octal notation References: <20090821194857.GU20434@dragontoe.org> Message-ID: Derek Martin pizzashack.org> writes: > More than flushing out > bugs, it will *cause* them in ubiquity, requiring likely terabytes of > code to be poured over and fixed. 2to3, however, can fix it for you extreme easily. From code at pizzashack.org Fri Aug 21 16:44:14 2009 From: code at pizzashack.org (Derek Martin) Date: Fri, 21 Aug 2009 15:44:14 -0500 Subject: Annoying octal notation In-Reply-To: References: <20090821194857.GU20434@dragontoe.org> Message-ID: <20090821204414.GV20434@dragontoe.org> On Fri, Aug 21, 2009 at 08:25:45PM +0000, Benjamin Peterson wrote: > > More than flushing out bugs, it will *cause* them in ubiquity, > > requiring likely terabytes of code to be poured over and fixed. > > 2to3, however, can fix it for you extreme easily. Sure, but that won't stop people who've been writing code for 20 years from continuing to type octal that way... Humans can learn fairly easily, but UN-learning is often much harder, especially when the behavior to be unlearned is still very commonly in use. Anyway, whatever. This change (along with a few of the other seemingly arbitrary changes in 3.x) is annoying, but Python is still one of the best languages to code in for any multitude of problems. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From piet at cs.uu.nl Fri Aug 21 16:44:41 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 21 Aug 2009 22:44:41 +0200 Subject: Annoying octal notation References: Message-ID: >>>>> Derek Martin (DM) wrote: >DM> I fail to see how 0O012, or even 0o012 is more intelligible than 012. >DM> The latter reads like a typo, and the former is virtually >DM> indistinguishable from 00012, O0012, or many other combinations that >DM> someone might accidentally type (or intentionally type, having to do >DM> this in dozens of other programming languages). You're right. Either hexadecimal should have been 0h or octal should have been 0t :=) -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From martin at v.loewis.de Fri Aug 21 16:45:41 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Aug 2009 22:45:41 +0200 Subject: 2.6 windows install In-Reply-To: References: Message-ID: <4A8F0775.1000208@v.loewis.de> > The default windows install puts Python26.dll in \windows\system32. I > haven't tried this, but you could probably fix your install by moving > Python26.dll into the Python26 directory. Only the admin installation should do that (for all users). The "just for me" installation won't. Regards, Martin From travis+ml-python at subspacefield.org Fri Aug 21 16:50:40 2009 From: travis+ml-python at subspacefield.org (travis+ml-python at subspacefield.org) Date: Fri, 21 Aug 2009 15:50:40 -0500 Subject: proposal: add setresuid() system call to python In-Reply-To: <877hy38mxw.fsf@busola.homelinux.net> References: <20090717200141.GI6065@subspacefield.org> <148918f0907171315i4ed5b274v77581a43c4464f8f@mail.gmail.com> <7cj89qF27mfrjU1@mid.uni-berlin.de> <877hy38mxw.fsf@busola.homelinux.net> Message-ID: <20090821205040.GK1215@subspacefield.org> On Mon, Jul 20, 2009 at 04:10:35PM +0200, Hrvoje Niksic wrote: > To emulate the os-module-type calls, it's better to raise exceptions > than return negative values: > > > def setresuid(ruid, euid, suid): > > return _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid)) > > def setresuid(ruid, euid, suid): > res = _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid)) > if res < 0: > raise OSError('[Errno %d] %s' % (os.errno, errno.strerror(os.errno))) I am working on a module to implement all of this, but that raise command won't work in Python 2.6.1; it turns out that os.errno is a module, not an integer. Does anyone know how to do what I want (that is, how to access the errno set in C functions)? -- Obama Nation | My emails do not have attachments; it's a digital signature that your mail program doesn't understand. | http://www.subspacefield.org/~travis/ If you are a spammer, please email john at subspacefield.org to get blacklisted. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 850 bytes Desc: not available URL: From seanm.py at gmail.com Fri Aug 21 16:55:51 2009 From: seanm.py at gmail.com (newb.py) Date: Fri, 21 Aug 2009 13:55:51 -0700 (PDT) Subject: IDLE file saving problem Message-ID: <70222640-1990-4fae-bbca-8451d252a1ab@13g2000prl.googlegroups.com> I am learning Python and need to use use IDLE, but I am having a problem. When I open a new window in IDLE and write my code, all is well. The coloring works and is very helpful. However, when I save the file I am working on, all the color disappears. And what is more frustrating is that when I open the saved file, it opens in TextEdit, so I have to copy it back into a new IDLE window to work on the code. If someone could clear up this seemingly simple problem for me, I would really appreciate it. Much thanks, Sean From python at mrabarnett.plus.com Fri Aug 21 17:10:49 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 21 Aug 2009 22:10:49 +0100 Subject: IDLE file saving problem In-Reply-To: <70222640-1990-4fae-bbca-8451d252a1ab@13g2000prl.googlegroups.com> References: <70222640-1990-4fae-bbca-8451d252a1ab@13g2000prl.googlegroups.com> Message-ID: <4A8F0D59.9010508@mrabarnett.plus.com> newb.py wrote: > I am learning Python and need to use use IDLE, but I am having a > problem. When I open a new window in IDLE and write my code, all is > well. The coloring works and is very helpful. However, when I save the > file I am working on, all the color disappears. And what is more > frustrating is that when I open the saved file, it opens in TextEdit, > so I have to copy it back into a new IDLE window to work on the code. > > If someone could clear up this seemingly simple problem for me, I > would really appreciate it. > That happens if you don't provide the extension, eg you save as "my_script" instead of "my_script.py". (Perhaps IDLE should add the extension if the user doesn't.) From python at mrabarnett.plus.com Fri Aug 21 17:18:41 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 21 Aug 2009 22:18:41 +0100 Subject: Annoying octal notation In-Reply-To: References: Message-ID: <4A8F0F31.4080107@mrabarnett.plus.com> Piet van Oostrum wrote: >>>>>> Derek Martin (DM) wrote: > >> DM> I fail to see how 0O012, or even 0o012 is more intelligible than 012. >> DM> The latter reads like a typo, and the former is virtually >> DM> indistinguishable from 00012, O0012, or many other combinations that >> DM> someone might accidentally type (or intentionally type, having to do >> DM> this in dozens of other programming languages). > > You're right. Either hexadecimal should have been 0h or octal should > have been 0t :=) I have seen the use of Q/q instead in order to make it clearer. I still prefer Smalltalk's 16rFF and 8r377. From breamoreboy at yahoo.co.uk Fri Aug 21 17:20:20 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 21 Aug 2009 22:20:20 +0100 Subject: Three-Phase-Diagrams with matplotlib In-Reply-To: <25082083.post@talk.nabble.com> References: <25082083.post@talk.nabble.com> Message-ID: M. Hecht wrote: > Hello, > > does anyone know whether it is possible to draw three-phase-diagrams with > matplotlib? > > A three-phase-diagram is a triangular diagram applied in chemistry e.g. for > slags where > one has three main components of a chemical substance at the corners and > points or lines > within the triangle marking different compositions of the substances in > percent, e.g. > in metallurgy 20% Al2O3, 45% CaO and 35% SiO2. > > As noone else has responded try the matplotlib users' mailing list, see http://sourceforge.net/mail/?group_id=80706 -- Kindest regards. Mark Lawrence. From rt8396 at gmail.com Fri Aug 21 17:48:56 2009 From: rt8396 at gmail.com (r) Date: Fri, 21 Aug 2009 14:48:56 -0700 (PDT) Subject: IDLE file saving problem References: <70222640-1990-4fae-bbca-8451d252a1ab@13g2000prl.googlegroups.com> Message-ID: On Aug 21, 4:10?pm, MRAB wrote: [snip] > That happens if you don't provide the extension, eg you save as > "my_script" instead of "my_script.py". (Perhaps IDLE should add the > extension if the user doesn't.) Yes, and much more needs improvement! I have made many changes already and i am polishing an "IDLE 3000" for the good people of Pythonia, stay tuned more to come.... From jgardner at jonathangardner.net Fri Aug 21 17:53:55 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 21 Aug 2009 14:53:55 -0700 (PDT) Subject: Using 'apply' as a decorator, to define constants References: Message-ID: On Aug 21, 6:36?am, Jonathan Fine wrote: > ? ? ?@apply > ? ? ?def tags(): > ? ? ? ? ?value = [] > ? ? ? ? ?# complicated code > ? ? ? ? ?return value > Is this different from: tags = [] # complicated code I can see the argument that you are cleaning up a lot of intermediary variables upon return, though. From jgardner at jonathangardner.net Fri Aug 21 18:17:40 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 21 Aug 2009 15:17:40 -0700 (PDT) Subject: Using 'apply' as a decorator, to define constants References: Message-ID: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> On Aug 21, 9:09?am, alex23 wrote: > On Aug 21, 11:36?pm, Jonathan Fine wrote: > > class ColourThing(object): > ? ? @apply > ? ? def rgb(): > ? ? ? ? def fset(self, rgb): > ? ? ? ? ? ? self.r, self.g, self.b = rgb > ? ? ? ? def fget(self): > ? ? ? ? ? ? return (self.r, self.g, self.b) > ? ? ? ? return property(**locals()) > This is brilliant. I am going to use this more often. I've all but given up on property() since defining "get_foo", "get_bar", etc... has been a pain and polluted the namespace. > Unfortunately, apply() has been removed as a built-in in 3.x. I'm not > sure if it has been relocated to a module somewhere, there's no > mention of such in the docs. apply = lambda f: f() It's one of those functions that is easier to define than import. > Why I've personally stopped using it: I've always had the impression > that decorators were intended to provide a convenient and obvious way > of augmenting functions. Having one that automatically executes the > function at definition just runs counter to the behaviour I expect > from a decorator. Especially when direct assignment... foo = foo > () ...is a far more direct and clear way of expressing exactly what is > happening. > If anyone reads the decorator and doesn't think "this thing below is defined as the result of this decorator function" then they don't understand decorators at all. From sean.marimpietri at gmail.com Fri Aug 21 18:21:52 2009 From: sean.marimpietri at gmail.com (seanm) Date: Fri, 21 Aug 2009 15:21:52 -0700 (PDT) Subject: Reading, writing files Message-ID: In the book I am using, they give the following function as an example: def copyFile(oldFile, newFile): f1 = open(oldFile, 'r') f2 = open(newFile, 'w') while True: text = f1.read(50) if text == "": break f2.write(text) f1.close() f2.close() return My question is why does this function successfully copy a 200 character file, oldFile, to newFile? The line of code that reads, text = f1.read(50), does not seem to be iterative in any way to me. How is this fuction succeding in adding each additional set up 50 characters to the previous set of 50 characters read from oldFile? How does it even succeed in copying a 25 character file? If oldFile contains 25 characters, how does the program ever break out of the 'while True:' loop? I just don't see it. Again, much thanks to anyone who can clear this up. -Sean From seanm.py at gmail.com Fri Aug 21 18:25:17 2009 From: seanm.py at gmail.com (newb.py) Date: Fri, 21 Aug 2009 15:25:17 -0700 (PDT) Subject: Help Please Message-ID: <75c475fc-5f93-4e41-98f3-9bde17859343@d4g2000prc.googlegroups.com> In the book I am using, they give the following function as an example: def copyFile(oldFile, newFile): f1 = open(oldFile, 'r') f2 = open(newFile, 'w') while True: text = f1.read(50) if text == "": break f2.write(text) f1.close() f2.close() return My question is why does this function successfully copy a 200 character file, oldFile, to newFile? The line of code that reads, text = f1.read(50), does not seem to be iterative in any way to me. How is this fuction succeding in adding each additional set up 50 characters to the previous set of 50 characters read from oldFile? How does it even succeed in copying a 25 character file? If oldFile contains 25 characters, how does the program ever break out of the 'while True:' loop? I just don't see it. Again, much thanks to anyone who can clear this up. -Sean From marduk at letterboxes.org Fri Aug 21 18:42:56 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Fri, 21 Aug 2009 18:42:56 -0400 Subject: Reading, writing files In-Reply-To: References: Message-ID: <1250894576.5655.5.camel@centar.nbk> On Fri, 2009-08-21 at 15:21 -0700, seanm wrote: > In the book I am using, they give the following function as an > example: > > def copyFile(oldFile, newFile): > f1 = open(oldFile, 'r') > f2 = open(newFile, 'w') > while True: > text = f1.read(50) > if text == "": > break > f2.write(text) > f1.close() > f2.close() > return > > My question is why does this function successfully copy a 200 > character file, oldFile, to newFile? The line of code that reads, text > = f1.read(50), does not seem to be iterative in any way to me. How is > this fuction succeding in adding each additional set up 50 characters > to the previous set of 50 characters read from oldFile? The body of the loop will execute forever (unless cut short by the "break" statement. What the loop is essentially doing is reading 50 bytes at a time from f1 and writing it into f2. When f1 reaches end of file it will stop returning bytes (if text == "":) the loop is broken and both files are closed. > How does it even succeed in copying a 25 character file? If oldFile > contains 25 characters, how does the program ever break out of the > 'while True:' loop? > > I just don't see it. Have you read the documentation for file objects? During the first iteration of the loop 25 bytes are read from f1. Then they are written to f2. During the next iteration there is nothing else to be read from f1 so f1.read(50) returns "", which causes the loop to break. > Again, much thanks to anyone who can clear this up. > From marduk at letterboxes.org Fri Aug 21 18:43:54 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Fri, 21 Aug 2009 18:43:54 -0400 Subject: Help Please In-Reply-To: <75c475fc-5f93-4e41-98f3-9bde17859343@d4g2000prc.googlegroups.com> References: <75c475fc-5f93-4e41-98f3-9bde17859343@d4g2000prc.googlegroups.com> Message-ID: <1250894634.5655.6.camel@centar.nbk> Why do you post the same question twice within 5 minutes of each other? From python at mrabarnett.plus.com Fri Aug 21 18:52:17 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 21 Aug 2009 23:52:17 +0100 Subject: Reading, writing files In-Reply-To: References: Message-ID: <4A8F2521.2040406@mrabarnett.plus.com> seanm wrote: > In the book I am using, they give the following function as an > example: > > def copyFile(oldFile, newFile): > f1 = open(oldFile, 'r') > f2 = open(newFile, 'w') > while True: > text = f1.read(50) This will read up to 50 characters from the input file. At the end of the file it'll return an empty string (""). In fact, the only time it'll return an empty string is at the end of the file. > if text == "": > break > f2.write(text) > f1.close() > f2.close() > return > > My question is why does this function successfully copy a 200 > character file, oldFile, to newFile? The line of code that reads, text > = f1.read(50), does not seem to be iterative in any way to me. How is > this fuction succeding in adding each additional set up 50 characters > to the previous set of 50 characters read from oldFile? > > How does it even succeed in copying a 25 character file? If oldFile > contains 25 characters, how does the program ever break out of the > 'while True:' loop? > > I just don't see it. > > Again, much thanks to anyone who can clear this up. > It reads some characters from the input file and then writes then to the output file, and because of the 'while' loop it'll repeat action that until the read returns an empty string, which will be when it has read all the way to the end of file and tries to read some more. From ben+python at benfinney.id.au Fri Aug 21 18:52:21 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 22 Aug 2009 08:52:21 +1000 Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <8763chldpd.fsf@benfinney.id.au> Message-ID: <87ocq8kcey.fsf@benfinney.id.au> josef writes: > On Aug 21, 4:26?am, Ben Finney wrote: > > Note that, after that list is created, each item in that list is > > *also* a reference to the corresponding object. That is, ?a? is a > > reference to an object, and ?dk[0]? is a *different* reference to > > the *same* object. The object has no knowledge about those > > references. > > This is surprising. Perhaps so, depending on your initial assumptions. But it's quite consistent: every time you use an object, you do so via some kind of reference to that object. Those references are the way you get at the same object again later. > My initial thought is that dk[0] hold the object reference 'a,' but > that wouldn't be true "pass by object reference." Right. It stores an entirely *separate* reference to that object. The reference ?dk[0]?, a list item, and the reference ?a?, a name, both refer to the same object. Neither of those references knows anything about the other. > When defining the object reference dk[0] Not ?defining?. You're binding (?assigning?, if you like) a reference. > python takes the object reference 'a,' More accurately, it takes the object referred to by ?a?. (Also, please don't put the comma inside the quotes; it's syntactically significant, and changes the meaning of what you're writing in code.) > finds the object MyClass0() No. ?MyClass0()? is syntax for ?call MyClass0 and get its return value?. The return value will be a new instance of the class ? a *new* object every time you use that syntax. Rather, the object referred to by ?a? will be the result of evaluating the identifier ?a?. As a shortcut for discussion, you can talk about ?the object ?a??, but remember that the only things you're using in the syntax of your Python code is object *references*, be they identifiers (names) or some other kind of reference. > and then assigns the object identity to dk[0]? Or something close to > that. You'd do well to read for a good, simple coverage of the Python object model. > I'm a bit shocked that there isn't a method for catching object > reference names. Don't be; there is no such thing as an ?object reference name?. A name is an object reference. So is every other way of getting at a Python object in your code. > I think that something like a = MyClass0(name = 'a', ...) is a bit > redundant. It usually is, yes. Why do you think you need it? The natural way to handle objects and names together in Python is with a mapping; a ?dict? instance. > Are definitions treated the same way? How would one print or pass > function names? Functions are objects like any other, but since they're more likely to want to know their own name, the name is stored as an attribute:: >>> def frobnicate_nodule(spam): ... """ Frobnicate the spam nodule. """ ... >>> type(frobnicate_nodule) >>> frobnicate_nodule.__name__ 'frobnicate_nodule' The fact that the function name is stored in one of those funky double-underscore names is a big clue that the attribute is special (in this case, because it gets assigned automatically by the Python interpreter). That's not the case for most types, though. > I think I'll just add a 'name' to the classes' init defintion. What is the larger problem you're trying to solve, and why do you think it will be helped by instances knowing a name for themselves? (Note: an object can never know *all* names for itself, let alone all the other references to itself; and you must write your program in the knowledge that no reference to an object has any intrinsic special status against any of the other references to that object.) -- \ ?I spent a lot of money on wine and women, and like a fool I | `\ squandered the rest.? ?Benny Hill | _o__) | Ben Finney From ben+python at benfinney.id.au Fri Aug 21 18:55:11 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 22 Aug 2009 08:55:11 +1000 Subject: Sanitising arguments to shell commands References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> <50697b2c0908210219i5e02c0cbq2d63bff891624ef4@mail.gmail.com> Message-ID: <87k50wkca8.fsf@benfinney.id.au> Rick King writes: > shlex doesn't handle unicode input though, so, in general, it's not a > good solution. Argh. Is there a Python bug tracker number for fixing that? Or is there a better solution? -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but if we have nothing to fear but fear itself, why does | _o__) Elanore Roosevelt wear that spooky mask?? ?_Pinky and The Brain_ | Ben Finney From pavlovevidence at gmail.com Fri Aug 21 19:23:29 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 21 Aug 2009 16:23:29 -0700 (PDT) Subject: proposal: add setresuid() system call to python References: <20090717200141.GI6065@subspacefield.org> <148918f0907171315i4ed5b274v77581a43c4464f8f@mail.gmail.com> <7cj89qF27mfrjU1@mid.uni-berlin.de> <877hy38mxw.fsf@busola.homelinux.net> Message-ID: On Aug 21, 1:50?pm, travis+ml-pyt... at subspacefield.org wrote: > On Mon, Jul 20, 2009 at 04:10:35PM +0200, Hrvoje Niksic wrote: > > To emulate the os-module-type calls, it's better to raise exceptions > > than return negative values: > > > > def setresuid(ruid, euid, suid): > > > ? ? return _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid)) > > > def setresuid(ruid, euid, suid): > > ? ? res = _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid)) > > ? ? if res < 0: > > ? ? ? ? raise OSError('[Errno %d] %s' % (os.errno, errno.strerror(os.errno))) > > I am working on a module to implement all of this, but that raise command > won't work in Python 2.6.1; it turns out that os.errno is a module, not > an integer. ?Does anyone know how to do what I want (that is, how to access > the errno set in C functions)? You are using ctypes, I presume? Try replacing raise OSError with this: ctypes.pythonapi.PyErr_SetFromErrno(ctypes.py_object(OSError)) Not entirely sure it'll work with Python built with a static library, but I think it will. Carl Banks From james.harris.1 at googlemail.com Fri Aug 21 19:23:57 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Fri, 21 Aug 2009 16:23:57 -0700 (PDT) Subject: Annoying octal notation References: Message-ID: On 21 Aug, 20:48, Derek Martin wrote: ... > James Harris wrote: > > It maybe made sense once but this relic of the past should have been > > consigned to the waste bin of history long ago. > > Sigh. ?Nonsense. ?I use octal notation *every day*, for two extremely > prevalent purposes: file creation umask, and Unix file permissions > (i.e. the chmod() function/command). ? You misunderstand. I was saying that taking a leading zero as indicating octal is archaic. Octal itself is fine where appropriate. The chmod command doesn't require a leading zero. James From dullrich at sprynet.com Fri Aug 21 19:32:41 2009 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 21 Aug 2009 18:32:41 -0500 Subject: Silly question References: Message-ID: <5jbu85dvva20ntj9iai1rhp9a51ipan989@4ax.com> On Fri, 21 Aug 2009 14:45:55 -0500, David C Ullrich wrote: >[...] > >Oops. Should have tested that a little more carefully >before posting. No time to fix it right now, customer just >got here. Let's just say we're looking for the primes >between sqrt(n) and n... from math import sqrt def Primes(n): """Return a list of the primes < n""" sieve = range(n) for k in range(2,int(sqrt(n))+2): sieve[2*k::k] = [1]*((n-k-1)/k) return [p for p in sieve if p > 1] David C. Ullrich "Understanding Godel isn't about following his formal proof. That would make a mockery of everything Godel was up to." (John Jones, "My talk about Godel to the post-grads." in sci.logic.) From aahz at pythoncraft.com Fri Aug 21 19:38:42 2009 From: aahz at pythoncraft.com (Aahz) Date: 21 Aug 2009 16:38:42 -0700 Subject: Code formatting question: conditional expression References: <7evr1pF2i4mouU1@mid.uni-berlin.de> <87ocqchl2k.fsf@benfinney.id.au> Message-ID: In article <87ocqchl2k.fsf at benfinney.id.au>, Ben Finney wrote: >"Diez B. Roggisch" writes: >> >> excessblk = None >> if total > P.BASE: >> excessblk = ... >> >> You don't lose any vertical space, > >I don't see vertical space as such a scarce resource; we don't have an >imminent newline shortage, to my knowledge. I value it far lower than, >say, local readability. We don't have a newline shortage, but we do have a pixel shortage. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From james.harris.1 at googlemail.com Fri Aug 21 19:52:29 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Fri, 21 Aug 2009 16:52:29 -0700 (PDT) Subject: Annoying octal notation References: Message-ID: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> On 21 Aug, 22:18, MRAB wrote: > Piet van Oostrum wrote: > >>>>>> Derek Martin (DM) wrote: > > >> DM> I fail to see how 0O012, or even 0o012 is more intelligible than 012. > >> DM> The latter reads like a typo, and the former is virtually > >> DM> indistinguishable from 00012, O0012, or many other combinations that > >> DM> someone might accidentally type (or intentionally type, having to do > >> DM> this in dozens of other programming languages). ? > > > You're right. Either hexadecimal should have been 0h or octal should > > have been 0t :=) > > I have seen the use of Q/q instead in order to make it clearer. I still > prefer Smalltalk's 16rFF and 8r377. Two interesting options. In a project I have on I have also considered using 0q as indicating octal. I maybe saw it used once somewhere else but I have no idea where. 0t was a second choice and 0c third choice (the other letters of oct). 0o should NOT be used for obvious reasons. So you are saying that Smalltalk has r where r is presumably for radix? That's maybe best of all. It preserves the syntactic requirement of starting a number with a digit and seems to have greatest flexibility. Not sure how good it looks but it's certainly not bad. 0xff & 0x0e | 0b1101 16rff & 16r0e | 2r1101 Hmm. Maybe a symbol would be better than a letter. James From wgheath at gmail.com Fri Aug 21 19:58:50 2009 From: wgheath at gmail.com (Tim Heath) Date: Fri, 21 Aug 2009 16:58:50 -0700 (PDT) Subject: Invitation to connect on LinkedIn Message-ID: <485663771.786023.1250899130772.JavaMail.app@ech3-cdn10.prod> LinkedIn ------------ Tim Heath requested to add you as a connection on LinkedIn: ------------------------------------------ Jaime, I'd like to add you to my professional network on LinkedIn. - Tim View invitation from Tim Heath http://www.linkedin.com/e/I2LlXdLlWUhFABKmxVOlgGLlWUhFAfhMPPF/blk/I287618177_3/0PnPsTcjwNdzsUcAALqnpPbOYWrSlI/svi/ ------------------------------------------ DID YOU KNOW you can be the first to know when a trusted member of your network changes jobs? With Network Updates on your LinkedIn home page, you'll be notified as members of your network change their current position. Be the first to know and reach out! http://www.linkedin.com/ ------ (c) 2009, LinkedIn Corporation -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Fri Aug 21 20:02:14 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 Aug 2009 17:02:14 -0700 Subject: Sanitising arguments to shell commands In-Reply-To: <87k50wkca8.fsf@benfinney.id.au> References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> <50697b2c0908210219i5e02c0cbq2d63bff891624ef4@mail.gmail.com> <87k50wkca8.fsf@benfinney.id.au> Message-ID: <50697b2c0908211702h2a2017f8r18f9a7b4b56d87fa@mail.gmail.com> On Fri, Aug 21, 2009 at 3:55 PM, Ben Finney wrote: > Rick King writes: > >> shlex doesn't handle unicode input though, so, in general, it's not a >> good solution. > > Argh. Is there a Python bug tracker number for fixing that? Indeed there is: http://bugs.python.org/issue1170 It even has a patch. I wonder why it's unapplied. Cheers, Chris -- http://blog.rebertia.com From ben+python at benfinney.id.au Fri Aug 21 20:03:35 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 22 Aug 2009 10:03:35 +1000 Subject: Annoying octal notation References: Message-ID: <87d46ok948.fsf@benfinney.id.au> Derek Martin writes: > James Harris wrote: > > It maybe made sense once but this relic of the past should have been > > consigned to the waste bin of history long ago. > > Sigh. Nonsense. I use octal notation *every day*, for two extremely > prevalent purposes: file creation umask, and Unix file permissions > (i.e. the chmod() function/command). Right. Until Unix stops using these (and whatever replaces it would have to be pretty compelling, given the prevalence of these in octal notation), or until people stop using Unix, these will be with us and require octal notation. That doesn't mean, of course, that we need to elevate it above hexadecimal in our language syntax; ?0o012? will allow octal notation for literals just fine. > I fail to see how 0O012, or even 0o012 is more intelligible than 012. > The latter reads like a typo No, it reads like a very common notation for decimal numbers in natural usage. It's very frequently not a typo, but an expression of a three-digit decimal number that happens to be less than 100. > and the former is virtually indistinguishable from 00012, O0012, or > many other combinations that someone might accidentally type (or > intentionally type, having to do this in dozens of other programming > languages). Only if you type the letter in uppercase. The lower-case ?o? is much easier to distinguish. Whether or not you find ?0o012? easily distinguishable as a non-decimal notation, it's undoubtedly easier to distinguish than ?012?. > I can see how 012 can be confusing to new programmers, but at least > it's legible, and the great thing about humans is that they can be > taught (usually). I for one think this change is completely misguided. These human programmers, whether newbies or long-experienced, also deal with decimal numbers every day, many of which are presented as a sequence of digits with leading zeros ? and we continue to think of them as decimal numbers regardless. Having the language syntax opposed to that is a wart, a cognitive overhead with little benefit, and I'll be glad to see it go in favour of a clearer syntax. -- \ ?? one of the main causes of the fall of the Roman Empire was | `\ that, lacking zero, they had no way to indicate successful | _o__) termination of their C programs.? ?Robert Firth | Ben Finney -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 202 bytes Desc: not available URL: From ben+python at benfinney.id.au Fri Aug 21 20:09:29 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 22 Aug 2009 10:09:29 +1000 Subject: Annoying octal notation References: <20090821194857.GU20434@dragontoe.org> Message-ID: <878whck8ue.fsf@benfinney.id.au> Derek Martin writes: > Sure, but that won't stop people who've been writing code for 20 years > from continuing to type octal that way... Humans can learn fairly > easily, but UN-learning is often much harder, especially when the > behavior to be unlearned is still very commonly in use. This is exactly the argument for removing ?012? octal notation: humans (and programmers who have far less need for octal numbers than for decimal numbers) are *already* trained, and reinforced many times daily, to think of that notation as a decimal number. They should not need to un-learn that association in order to understand octal literals in code. > Anyway, whatever. This change (along with a few of the other seemingly > arbitrary changes in 3.x) is annoying, but Python is still one of the > best languages to code in for any multitude of problems. Hear hear. -- \ ?I wrote a song, but I can't read music so I don't know what it | `\ is. Every once in a while I'll be listening to the radio and I | _o__) say, ?I think I might have written that.?? ?Steven Wright | Ben Finney -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 202 bytes Desc: not available URL: From smono927 at gmail.com Fri Aug 21 21:15:35 2009 From: smono927 at gmail.com (SeanMon) Date: Fri, 21 Aug 2009 18:15:35 -0700 (PDT) Subject: Decompressing gzip over FTP Message-ID: Is there a way to decompress a large (2GB) gzipped file being retrieved over FTP on the fly? I'm using ftplib.FTP to open a connection to a remote server, and I have had no success connecting retrbinary to gzip without using an intermediate file. Is there any way to get a file-like object describing the remote file, or a way to utilize gzip's decompression without providing it a file- like object? Thanks, Sean From lists at cheimes.de Fri Aug 21 21:40:58 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 Aug 2009 03:40:58 +0200 Subject: Decompressing gzip over FTP In-Reply-To: References: Message-ID: <4A8F4CAA.7040903@cheimes.de> SeanMon schrieb: > Is there a way to decompress a large (2GB) gzipped file being > retrieved over FTP on the fly? > > I'm using ftplib.FTP to open a connection to a remote server, and I > have had no success connecting retrbinary to gzip without using an > intermediate file. > > Is there any way to get a file-like object describing the remote file, > or a way to utilize gzip's decompression without providing it a file- > like object? gzip is really just a file format. In order to work with compressed streams you should use the low level zlib module. http://docs.python.org/library/zlib.html#module-zlib Have fun! Christian From smono927 at gmail.com Fri Aug 21 21:51:47 2009 From: smono927 at gmail.com (SeanMon) Date: Fri, 21 Aug 2009 18:51:47 -0700 (PDT) Subject: Decompressing gzip over FTP References: Message-ID: <0bf17e27-408c-4d67-90cc-74f28789f524@32g2000yqj.googlegroups.com> On Aug 21, 9:40?pm, Christian Heimes wrote: > SeanMon schrieb: > > > Is there a way to decompress a large (2GB) gzipped file being > > retrieved over FTP on the fly? > > > I'm using ftplib.FTP to open a connection to a remote server, and I > > have had no success connecting retrbinary to gzip without using an > > intermediate file. > > > Is there any way to get a file-like object describing the remote file, > > or a way to utilize gzip's decompression without providing it a file- > > like object? > > gzip is really just a file format. In order to work with compressed > streams you should use the low level zlib module. > > http://docs.python.org/library/zlib.html#module-zlib > > Have fun! > > Christian Unfortunately, the file on the server is a gzip file, so I cannot simply pipe the contents into a zlib.decompressobj (which does have the ability to decompress in chunks, as I wish gzip did!). Thanks, Sean From subhakolkata1234 at gmail.com Fri Aug 21 22:15:31 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Fri, 21 Aug 2009 19:15:31 -0700 (PDT) Subject: Questions on XML Message-ID: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Dear Group, I like to convert some simple strings of natural language to XML. May I use Python to do this? If any one can help me, on this. I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I use Python to help me in this regard? How can I learn good XML aspects of Python. If any one can kindly name me a book or URL. I am using Python2.6 on Windows XP with IDLE as GUI. Best Regards, Subhabrata. From wuwei23 at gmail.com Fri Aug 21 22:35:38 2009 From: wuwei23 at gmail.com (alex23) Date: Fri, 21 Aug 2009 19:35:38 -0700 (PDT) Subject: Using 'apply' as a decorator, to define constants References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> Message-ID: Jonathan Gardner wrote: > This is brilliant. I am going to use this more often. I've all but > given up on property() since defining "get_foo", "get_bar", etc... has > been a pain and polluted the namespace. Unfortunately I can't remember who I first learned it from - it was definitely in a post to this group - otherwise all credit would be their's. > It's one of those functions that is easier to define than import. And so obvious now :) > If anyone reads the decorator and doesn't think "this thing below is > defined as the result of this decorator function" then they don't > understand decorators at all. Well, it's not so much a question of the reader's intelligence as that Python already has a readily identifiable assignment operator. Having a second mechanism for assignment with no real similarity to the first just adds cognitive friction to reading the code...not because the reader doesn't understand what is happening, but because it's not obvious _why_ this second form would have been chosen. Nothing that couldn't be mitigated with a comment, I guess. # @apply used to prevent having to repeat references That would work for me. From steve at REMOVE-THIS-cybersource.com.au Fri Aug 21 22:54:27 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 02:54:27 GMT Subject: Using 'apply' as a decorator, to define constants References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> Message-ID: <0018e14c$0$2938$c3e8da3@news.astraweb.com> On Fri, 21 Aug 2009 15:17:40 -0700, Jonathan Gardner wrote: >> Unfortunately, apply() has been removed as a built-in in 3.x. I'm not >> sure if it has been relocated to a module somewhere, there's no mention >> of such in the docs. > > apply = lambda f: f() > > It's one of those functions that is easier to define than import. >>> apply = lambda f: f() >>> __builtin__.apply(len, 'a') 1 >>> apply(len, 'a') Traceback (most recent call last): File "", line 1, in TypeError: () takes exactly 1 argument (2 given) It's a little bit more difficult to define it *correctly*. Here's a working version of apply: def apply(object, *args, **kwargs): """apply(object[, args[, kwargs]]) -> value Call a callable object with positional and keyword arguments. >>> apply(max, 'one', 'two', 'three', 'four', key=len) 'three' """ return object(*args, **kwargs) Note that this: * actually does what apply() is supposed to do; * defines the function name, useful for tracebacks; * has a docstring, useful for interactive use and documentation; * includes an example suitable for automated testing with doctest. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 21 22:55:51 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 02:55:51 GMT Subject: Annoying octal notation References: Message-ID: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> On Fri, 21 Aug 2009 14:48:57 -0500, Derek Martin wrote: >> It maybe made sense once but this relic of the past should have been >> consigned to the waste bin of history long ago. > > Sigh. Nonsense. I use octal notation *every day*, for two extremely > prevalent purposes: file creation umask, and Unix file permissions (i.e. > the chmod() function/command). And you will still be able to, by explicitly using octal notation. > I fail to see how 0O012, or even 0o012 is more intelligible than 012. The first is wrong, bad, wicked, and if I catch anyone using it, they will be soundly slapped with a halibut. *wink* Using O instead of o for octal is so unreadable that I think it should be prohibited by the language, no matter that hex notation accepts both x and X. > The latter reads like a typo, *Everything* reads like a typo if you're unaware of the syntax being used. > and the former is virtually > indistinguishable from 00012, O0012, or many other combinations that > someone might accidentally type (or intentionally type, having to do > this in dozens of other programming languages). Agreed. > I can see how 012 can > be confusing to new programmers, but at least it's legible, and the > great thing about humans is that they can be taught (usually). And the great thing is that now you get to teach yourself to stop writing octal numbers implicitly and be write them explicitly with a leading 0o instead :) It's not just new programmers -- it's any programmer who is unaware of the notation (possibly derived from C) that a leading 0 means "octal". That's a strange and bizarre notation to use, because 012 is a perfectly valid notation for decimal 12, as are 0012, 00012, 000012 and so forth. Anyone who has learnt any mathematics beyond the age of six will almost certainly expect 012 to equal 12. Having 012 equal 10 comes as a surprise even to people who are familiar with octal. > I for > one think this change is completely misguided. More than flushing out > bugs, it will *cause* them in ubiquity, requiring likely terabytes of > code to be poured over and fixed. Changing decades-old behaviors common > throughout a community for the sake of avoiding a minor inconvenience of > the n00b is DUMB. Use of octal isn't common. You've given two cases were octal notation is useful, but for every coder who frequently writes umasks on Unix systems, there are a thousand who don't. It's no hardship to write 0o12 instead of 012. -- Steven From dns4 at cornell.edu Fri Aug 21 22:57:16 2009 From: dns4 at cornell.edu (David Smith) Date: Fri, 21 Aug 2009 22:57:16 -0400 Subject: Questions on XML In-Reply-To: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Message-ID: joy99 wrote: > Dear Group, > > I like to convert some simple strings of natural language to XML. May > I use Python to do this? If any one can help me, on this. > > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > use Python to help me in this regard? > > How can I learn good XML aspects of Python. If any one can kindly name > me a book or URL. > > I am using Python2.6 on Windows XP with IDLE as GUI. > > Best Regards, > Subhabrata. Take a look at xml.etree.ElementTree package and it's contents. It's included in the binary distributions of Python 2.6. There are lot's of books out covering XML and UTF-8 is exactly where you want to be w/ XML. --David From rami.chowdhury at gmail.com Sat Aug 22 00:18:13 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Fri, 21 Aug 2009 21:18:13 -0700 Subject: Questions on XML In-Reply-To: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Message-ID: > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > use Python to help me in this regard? I can say from experience that Python on Windows (at least, Python 2.5 on 32-bit Vista) works perfectly well with UTF-8 files containing Bangla. I have had trouble with working with the data in IDLE, however, which seems to prefer ASCII by default. ------------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Aug 21, 2009, at 19:15 , joy99 wrote: > Dear Group, > > I like to convert some simple strings of natural language to XML. May > I use Python to do this? If any one can help me, on this. > > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > use Python to help me in this regard? > > How can I learn good XML aspects of Python. If any one can kindly name > me a book or URL. > > I am using Python2.6 on Windows XP with IDLE as GUI. > > Best Regards, > Subhabrata. > -- > http://mail.python.org/mailman/listinfo/python-list From stefan_ml at behnel.de Sat Aug 22 01:53:31 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 22 Aug 2009 07:53:31 +0200 Subject: Questions on XML In-Reply-To: References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Message-ID: <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> Rami Chowdhury wrote: >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I >> use Python to help me in this regard? > > I can say from experience that Python on Windows (at least, Python 2.5 > on 32-bit Vista) works perfectly well with UTF-8 files containing > Bangla. I have had trouble with working with the data in IDLE, however, > which seems to prefer ASCII by default. Defaults almost never work for encodings. You have to be explicit: add an encoding declaration to the top of your source file if you use encoded literal strings in your code; use the codecs module with a suitable encoding to read encoded text files, and use an XML parser when reading XML. Stefan From kee at kagi.com Sat Aug 22 02:09:36 2009 From: kee at kagi.com (Kee Nethery) Date: Fri, 21 Aug 2009 23:09:36 -0700 Subject: Questions on XML In-Reply-To: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Message-ID: On Aug 21, 2009, at 7:15 PM, joy99 wrote: > Dear Group, > > I like to convert some simple strings of natural language to XML. May > I use Python to do this? If any one can help me, on this. > > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > use Python to help me in this regard? As a newbie, the thing that caused me trouble was importing a string into the XML parser. The parser seemed to want to open a file and I had a string. The solution was one of these: from xml.etree import ElementTree as et theXmlDataTree = et.parse(StringIO.StringIO(theXmlString)) from xml.etree import ElementTree as et theXmlDataTree = et.ElementTree(et.XML(theXmlString)) Not sure which you would use nor what the differences are. I have the first set commented out in my code so for some reason I switched to the second set of code to take a string and pull it into the XML parser. Once the string is in the parser, all the examples worked. It was getting it into the parser that had me stumped because none of the examples showed this situation, it appears to be obvious to someone who has used Python for a while. Kee From subhakolkata1234 at gmail.com Sat Aug 22 02:13:33 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Fri, 21 Aug 2009 23:13:33 -0700 (PDT) Subject: Questions on XML References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <575587f9-b2d2-498f-a907-0a90c260aa60@i4g2000prm.googlegroups.com> On Aug 22, 10:53?am, Stefan Behnel wrote: > Rami Chowdhury wrote: > >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > >> use Python to help me in this regard? > > > I can say from experience that Python on Windows (at least, Python 2.5 > > on 32-bit Vista) works perfectly well with UTF-8 files containing > > Bangla. I have had trouble with working with the data in IDLE, however, > > which seems to prefer ASCII by default. > > Defaults almost never work for encodings. You have to be explicit: add an > encoding declaration to the top of your source file if you use encoded > literal strings in your code; use the codecs module with a suitable > encoding to read encoded text files, and use an XML parser when reading XML. > > Stefan Dear Group, Thanx for your reply. Python works perfectly for Hindi and Bangla with Win XP. I never had a trouble. Best Regards, Subhabrata. From emmanuel.surleau at gmail.com Sat Aug 22 02:55:17 2009 From: emmanuel.surleau at gmail.com (Emmanuel Surleau) Date: Sat, 22 Aug 2009 08:55:17 +0200 Subject: Questions on XML In-Reply-To: <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <200908220855.17815.emmanuel.surleau@gmail.com> > >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > >> use Python to help me in this regard? > > > > I can say from experience that Python on Windows (at least, Python 2.5 > > on 32-bit Vista) works perfectly well with UTF-8 files containing > > Bangla. I have had trouble with working with the data in IDLE, however, > > which seems to prefer ASCII by default. > > Defaults almost never work for encodings. You have to be explicit: add an > encoding declaration to the top of your source file if you use encoded > literal strings in your code; use the codecs module with a suitable > encoding to read encoded text files, and use an XML parser when reading > XML. Actually, default *should* work for XML. The default encoding for an XML file is UTF-8 (AFAIK). Cheers, Emm From emmanuel.surleau at gmail.com Sat Aug 22 02:59:56 2009 From: emmanuel.surleau at gmail.com (Emmanuel Surleau) Date: Sat, 22 Aug 2009 08:59:56 +0200 Subject: Questions on XML In-Reply-To: <575587f9-b2d2-498f-a907-0a90c260aa60@i4g2000prm.googlegroups.com> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> <575587f9-b2d2-498f-a907-0a90c260aa60@i4g2000prm.googlegroups.com> Message-ID: <200908220859.56127.emmanuel.surleau@gmail.com> On Saturday 22 August 2009 08:13:33 joy99 wrote: > On Aug 22, 10:53 am, Stefan Behnel wrote: > > Rami Chowdhury wrote: > > >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > > >> use Python to help me in this regard? > > > > > > I can say from experience that Python on Windows (at least, Python 2.5 > > > on 32-bit Vista) works perfectly well with UTF-8 files containing > > > Bangla. I have had trouble with working with the data in IDLE, however, > > > which seems to prefer ASCII by default. > > > > Defaults almost never work for encodings. You have to be explicit: add an > > encoding declaration to the top of your source file if you use encoded > > literal strings in your code; use the codecs module with a suitable > > encoding to read encoded text files, and use an XML parser when reading > > XML. > > > > Stefan > > Dear Group, > Thanx for your reply. Python works perfectly for Hindi and Bangla with > Win XP. I never had a trouble. > Best Regards, > Subhabrata. You might also want to have a look at lxml. It can much more than the XML module in the default distribution, uses ElementTree as well, and is backed by the kickass, fast libxml library (http://codespeak.net/lxml/). It will allow you to use XSLs, for instance. Regardless of whether you use lxml or not, have a look at etree.iterparse, it is invaluable when processing huge XML documents. Cheers, Emm From jfine at pytex.org Sat Aug 22 03:09:52 2009 From: jfine at pytex.org (Jonathan Fine) Date: Sat, 22 Aug 2009 08:09:52 +0100 Subject: Using 'apply' as a decorator, to define constants In-Reply-To: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> Message-ID: Jonathan Gardner wrote: > On Aug 21, 9:09 am, alex23 wrote: >> On Aug 21, 11:36 pm, Jonathan Fine wrote: >> >> class ColourThing(object): >> @apply >> def rgb(): >> def fset(self, rgb): >> self.r, self.g, self.b = rgb >> def fget(self): >> return (self.r, self.g, self.b) >> return property(**locals()) >> > > This is brilliant. I am going to use this more often. I've all but > given up on property() since defining "get_foo", "get_bar", etc... has > been a pain and polluted the namespace. I think we can do better, with a little work. And also solve the problem that 'apply' is no longer a builtin in Python3. Here's my suggestion: === import wibble # Informs reader we're doing something special here. class ColourThing(object): @wibble.property def rgb(): '''This is the docstring for the property.''' def fset(self, rgb): self.r, self.g, self.b = rgb def fget(self): return (self.r, self.g, self.b) return locals() === And here's wibble.property() === _property = property # Avoid collision. def property(fn): return _property(doc=fn.__doc__, **fn()) === We can add apply() to the wibble module. By the way, 'wibble' is a placeholder to the real name. Any suggestions? -- Jonathan From kushal.kumaran+python at gmail.com Sat Aug 22 03:11:49 2009 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Sat, 22 Aug 2009 12:41:49 +0530 Subject: convert date time In-Reply-To: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> References: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> Message-ID: <1e364c4e0908220011qd99b59ek973060fd767d1dc0@mail.gmail.com> On Fri, Aug 21, 2009 at 11:44 PM, Ronn Ross wrote: > I'm new to python and I'm getting a date time from a field in the database > that looks like this: > 8/2/2009 8:36:16 AM (UTC) > > I want to split it into two fields one with the date formatted like this: > YYYY-MM-DD? 2009-08-02 > > and the time to be 24 hour or military time. How every you call it. Similar > to this: > 15:22:00 > > I found it easy to truncate off the (UTC), but having trouble converting the > date. Can someone point me in the right direction? > datetime.datetime.strptime() will give you a datetime object, which you can then format in a wide variety of ways using its strftime() method. Doesn't work with dates earlier than 1900, I believe. -- kushal From rami.chowdhury at gmail.com Sat Aug 22 03:16:29 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Sat, 22 Aug 2009 00:16:29 -0700 Subject: Questions on XML In-Reply-To: <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <89952E85-0E6C-4B62-A638-E742E67030CF@gmail.com> > encoding declaration to the top of your source file if you use encoded > literal strings in your code Any tips for how to set the encoding in IDLE? printing the Unicode strings works -- trying to repr() the variable chokes with a UnicodeDecodeError, and trying to enter the literals inside IDLE just gets me '?' characters instead. (this is Python 2.5 + IDLE installed from the Python-2.5.msi on python.org) ------------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Aug 21, 2009, at 22:53 , Stefan Behnel wrote: > Rami Chowdhury wrote: >>> I am using primarily UTF-8 based strings, like Hindi or Bengali. >>> Can I >>> use Python to help me in this regard? >> >> I can say from experience that Python on Windows (at least, Python >> 2.5 >> on 32-bit Vista) works perfectly well with UTF-8 files containing >> Bangla. I have had trouble with working with the data in IDLE, >> however, >> which seems to prefer ASCII by default. > > Defaults almost never work for encodings. You have to be explicit: > add an > encoding declaration to the top of your source file if you use encoded > literal strings in your code; use the codecs module with a suitable > encoding to read encoded text files, and use an XML parser when > reading XML. > > Stefan > -- > http://mail.python.org/mailman/listinfo/python-list From ray.belanger at gmail.com Sat Aug 22 04:17:49 2009 From: ray.belanger at gmail.com (flagmino) Date: Sat, 22 Aug 2009 01:17:49 -0700 (PDT) Subject: debugger Message-ID: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> To get familiar with the debugger, I have loaded this program: import math def s1(x, y): a = (x + y) print("Answer from s1"), a return def s2(x, y): b = (x - y) print("This comes from s2"), b #print z print("call from s2: "), s1(x, y) return I am trying to debug: I press shift-F9 and F7. I end up in the interpreter where I enter s2 (1, 2). >From that point if I press F7, the program restart all over. If I press Enter, the program gets out of debug mode. Please help me figuring out how I can use the dbugger. You are welcome to send a sound file if this is easier for you. Thanks ray From ak at nothere.com Sat Aug 22 04:20:23 2009 From: ak at nothere.com (AK) Date: Sat, 22 Aug 2009 04:20:23 -0400 Subject: How to 'de-slashify' a string? Message-ID: <4a8faa47$0$31283$607ed4bc@cv.net> Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' in a general way? The problem I'm running into is that I'm connecting with pygresql to a postgres database and when I get fields that are of 'char' type, I get them in unicode, but when I get fields of 'byte' type, I get the text with quoted slashes, e.g. '\303' becomes '\\303' and so on. I saw posts online to do cursor.execute("set client-encoding to unicode") before running queries but this command causes an error. So I think I need a way to de-quote the slashes or alternatively some way to tell pygresql not to quote slashes for 'byte' fields. Any help, hints, etc appreciated.. -- AK From contact at xavierho.com Sat Aug 22 04:53:59 2009 From: contact at xavierho.com (Xavier Ho) Date: Sat, 22 Aug 2009 18:53:59 +1000 Subject: debugger In-Reply-To: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> Message-ID: <2d56febf0908220153r6455323al4610f453443bc175@mail.gmail.com> On Sat, Aug 22, 2009 at 6:17 PM, flagmino wrote: > To get familiar with the debugger, I have loaded this program: > > import math > > def s1(x, y): > a = (x + y) > print("Answer from s1"), a > return > > def s2(x, y): > b = (x - y) > print("This comes from s2"), b > #print z > print("call from s2: "), s1(x, y) > return > > I am trying to debug: > I press shift-F9 and F7. I end up in the interpreter where I enter s2 > (1, 2). > > >From that point if I press F7, the program restart all over. > If I press Enter, the program gets out of debug mode. > > Please help me figuring out how I can use the dbugger. You are welcome > to send a sound file if this is easier for you. > > Thanks > > ray > -- > http://mail.python.org/mailman/listinfo/python-list Sorry, but which debugger are you referring to? Also, note that you're printing s1(x,y) which is returning nothing. Not sure why you want to do that, but just mentioning it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From leonhard.vogt at gmx.ch Sat Aug 22 04:58:47 2009 From: leonhard.vogt at gmx.ch (Leonhard Vogt) Date: Sat, 22 Aug 2009 10:58:47 +0200 Subject: Using 'apply' as a decorator, to define constants In-Reply-To: References: Message-ID: <86f8e$4a8fb348$544b15b8$5398@news.hispeed.ch> > Why I've personally stopped using it: I've always had the impression > that decorators were intended to provide a convenient and obvious way > of augmenting functions. Having one that automatically executes the > function at definition just runs counter to the behaviour I expect > from a decorator. Especially when direct assignment... foo = foo > () ...is a far more direct and clear way of expressing exactly what is > happening. if you have to define it yourself, you could call it store_result or something else instead of apply. @store_result def tags(): return result Leonhard From steve at REMOVE-THIS-cybersource.com.au Sat Aug 22 05:03:39 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 09:03:39 GMT Subject: Using 'apply' as a decorator, to define constants References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> Message-ID: <001937d5$0$2938$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 08:09:52 +0100, Jonathan Fine wrote: > Jonathan Gardner wrote: >> On Aug 21, 9:09 am, alex23 wrote: >>> On Aug 21, 11:36 pm, Jonathan Fine wrote: >>> >>> class ColourThing(object): >>> @apply >>> def rgb(): >>> def fset(self, rgb): >>> self.r, self.g, self.b = rgb >>> def fget(self): >>> return (self.r, self.g, self.b) >>> return property(**locals()) >>> >>> >> This is brilliant. I am going to use this more often. I've all but >> given up on property() since defining "get_foo", "get_bar", etc... has >> been a pain and polluted the namespace. > > > I think we can do better, with a little work. And also solve the > problem that 'apply' is no longer a builtin in Python3. There's a standard idiom for that, using the property() built-in, for Python 2.6 or better. Here's an example including a getter, setter, deleter and doc string, with no namespace pollution, imports, or helper functions or deprecated built-ins: class ColourThing(object): @property def rgb(self): """Get and set the (red, green, blue) colours.""" return (self.r, self.g, self.b) @rgb.setter def rgb(self, rgb): self.r, self.g, self.b = rgb @rgb.deleter def rgb(self): del self.r, self.g, self.b -- Steven From 71david at libero.it Sat Aug 22 05:15:16 2009 From: 71david at libero.it (David) Date: Sat, 22 Aug 2009 11:15:16 +0200 Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <14hj3v50qg77e$.1pk6i6w7h7q6s.dlg@40tude.net> Message-ID: <8aeik0nwe7l6$.znpheg2zqrj3.dlg@40tude.net> Il Fri, 21 Aug 2009 10:36:35 -0700 (PDT), Mensanator ha scritto: > Aha! Then I WAS right after all. Switch to 3.1 and you'll > soon be cured of that bad habit: > >>>> 012 + 012 > SyntaxError: invalid token (, line 1) I have tre (four) problems: 1) I am forced to use 2.5 since the production server has 2.5 installed. 2) Quite often I have to enter many zero-leading numbers and now my fingers put a leading zero almost everywhere 3) I don't understand why useless but *harmless* things like algebrically insignificant leading zeros should be *forbidden* and promoted to errors. 4) I still don't like the '0o..' notation because 0 (zero) and o (lowercase O) glyphs appear very similar in many character sets. I'd prefer something like '0c..' so it resembles the word 'oc' for 'octal'. David From steve at REMOVE-THIS-cybersource.com.au Sat Aug 22 05:18:52 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 09:18:52 GMT Subject: How to 'de-slashify' a string? References: <4a8faa47$0$31283$607ed4bc@cv.net> Message-ID: <00193b65$0$2938$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 04:20:23 -0400, AK wrote: > Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' > in a general way? It's not clear what you mean. Do you mean you have a string '\\303\\266', that is: backslash backslash three zero three backslash backslash two six six If so, then the simplest way is: >>> s = r'\\303\\266' # note the raw string >>> len(s) 10 >>> print s \\303\\266 >>> print s.replace('\\\\', '\\') \303\266 Another possibility: >>> s = '\\303\\266' # this is not a raw string >>> len(s) 8 >>> print s \303\266 So s is: backslash three zero three backslash two six six and you don't need to do any more. > The problem I'm running into is that I'm connecting with pygresql to a > postgres database and when I get fields that are of 'char' type, I get > them in unicode, but when I get fields of 'byte' type, I get the text > with quoted slashes, e.g. '\303' becomes '\\303' and so on. Is pygresql quoting the backslash, or do you just think it is quoting the backslashes? How do you know? E.g. if you have '\\303', what is the length of that? 4 or 5? -- Steven From 71david at libero.it Sat Aug 22 05:27:32 2009 From: 71david at libero.it (David) Date: Sat, 22 Aug 2009 11:27:32 +0200 Subject: Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> Message-ID: <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Il Fri, 21 Aug 2009 16:52:29 -0700 (PDT), James Harris ha scritto: > > 0xff & 0x0e | 0b1101 > 16rff & 16r0e | 2r1101 > > Hmm. Maybe a symbol would be better than a letter. What about 2_1011, 8_7621, 16_c26h or 2;1011, 8;7621, 16;c26h ? David From sjmachin at lexicon.net Sat Aug 22 05:29:53 2009 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Aug 2009 02:29:53 -0700 (PDT) Subject: convert date time References: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> Message-ID: On Aug 22, 5:11?pm, Kushal Kumaran wrote: > On Fri, Aug 21, 2009 at 11:44 PM, Ronn Ross wrote: > > I'm new to python and I'm getting a date time from a field in the database > > that looks like this: > > 8/2/2009 8:36:16 AM (UTC) > datetime.datetime.strptime() will give you a datetime object, which > you can then format in a wide variety of ways using its strftime() > method. ?Doesn't work with dates earlier than 1900, I believe. The datetime module works from 0001-01-01 onwards; see http://docs.python.org/library/datetime.html#datetime.MINYEAR Other things worth mentioning: (1) datetime.datetime.strptime() was introduced in Python 2.5; for Python 2.3 and 2.4, use time.strptime() [which may not like years before 1970] followed by datetime.datetime() (2) as the input has 12-hour clock plus AM/PM, ensure that you use %I instead of %H for the hour component; %H won't do what you expect if your expectation is not based on reading the docs :-) From jfine at pytex.org Sat Aug 22 05:51:27 2009 From: jfine at pytex.org (Jonathan Fine) Date: Sat, 22 Aug 2009 10:51:27 +0100 Subject: Using 'apply' as a decorator, to define constants In-Reply-To: <001937d5$0$2938$c3e8da3@news.astraweb.com> References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> <001937d5$0$2938$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > There's a standard idiom for that, using the property() built-in, for > Python 2.6 or better. > > Here's an example including a getter, setter, deleter and doc string, > with no namespace pollution, imports, or helper functions or deprecated > built-ins: > > class ColourThing(object): > @property > def rgb(self): > """Get and set the (red, green, blue) colours.""" > return (self.r, self.g, self.b) > @rgb.setter > def rgb(self, rgb): > self.r, self.g, self.b = rgb > @rgb.deleter > def rgb(self): > del self.r, self.g, self.b Sorry, Steve, but I don't understand this. In fact, I don't even see how it can be made to work. Unless an exception is raised, @wibble def wobble(): pass will make an assignment to wobble, namely the return value of wibble. So in your example above, there will be /three/ assignments to rgb. Unless you do some complicated introspection (and perhaps not even then) surely they will clobber each other. I still prefer: @wibble.property def rgb(): '''Red Green Blue color settings (property)''' def fset(rgb): self.r, self.g, self.b = rgb return locals() -- Jonathan From steve at REMOVE-THIS-cybersource.com.au Sat Aug 22 05:57:32 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 09:57:32 GMT Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <14hj3v50qg77e$.1pk6i6w7h7q6s.dlg@40tude.net> <8aeik0nwe7l6$.znpheg2zqrj3.dlg@40tude.net> Message-ID: <00194475$0$2938$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 11:15:16 +0200, David wrote: > 3) I don't understand why useless but *harmless* things like > algebrically insignificant leading zeros should be *forbidden* and > promoted to errors. The PEP covering this change says: "There are still some strong feelings that '0123' should be allowed as a literal decimal in Python 3.0. If this is the right thing to do, this can easily be covered in an additional PEP. This proposal only takes the first step of making '0123' not be a valid octal number, for reasons covered in the rationale." http://www.python.org/dev/peps/pep-3127/ -- Steven From ekayxu at gmail.com Sat Aug 22 06:03:27 2009 From: ekayxu at gmail.com (EK) Date: Sat, 22 Aug 2009 03:03:27 -0700 (PDT) Subject: Dictionary from a list References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: On Aug 20, 2:10?pm, Peter Otten <__pete... at web.de> wrote: > Jan Kaliszewski wrote: > > 20-08-2009 o 02:05:57 Jan Kaliszewski wrote: > > >> Or probably better: > > >> ? ? ?from itertools import islice, izip > >> ? ? ?dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2))) > > > Or similarly, perhaps more readable: > > > ? ? ?iterator = iter(li) > > ? ? ?dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2)) > > I just can't stop posting this one: > > >>> from itertools import izip > >>> it = iter([1,2,3,4,5,6]) > >>> dict(izip(it, it)) > > {1: 2, 3: 4, 5: 6} > > I really tried, but yours drove me over the edge. > > Peter dict(zip(*[iter(l)]*2)) From ak at nothere.com Sat Aug 22 06:09:20 2009 From: ak at nothere.com (AK) Date: Sat, 22 Aug 2009 06:09:20 -0400 Subject: How to 'de-slashify' a string? In-Reply-To: <00193b65$0$2938$c3e8da3@news.astraweb.com> References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> Message-ID: <4a8fc3d1$0$22535$607ed4bc@cv.net> Steven D'Aprano wrote: > On Sat, 22 Aug 2009 04:20:23 -0400, AK wrote: > >> Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' >> in a general way? > > It's not clear what you mean. > > Do you mean you have a string '\\303\\266', that is: > > backslash backslash three zero three backslash backslash two six six > > If so, then the simplest way is: > >>>> s = r'\\303\\266' # note the raw string >>>> len(s) > 10 >>>> print s > \\303\\266 >>>> print s.replace('\\\\', '\\') > \303\266 > > > Another possibility: > >>>> s = '\\303\\266' # this is not a raw string >>>> len(s) > 8 >>>> print s > \303\266 > > So s is: > backslash three zero three backslash two six six > > and you don't need to do any more. Well, I need the string itself to become '\303\266', not to print that way. In other words, when I do 'print s', it should display unicode characters if my term is set to show them, instead of showing \303\266. > > >> The problem I'm running into is that I'm connecting with pygresql to a >> postgres database and when I get fields that are of 'char' type, I get >> them in unicode, but when I get fields of 'byte' type, I get the text >> with quoted slashes, e.g. '\303' becomes '\\303' and so on. > > Is pygresql quoting the backslash, or do you just think it is quoting the > backslashes? How do you know? E.g. if you have '\\303', what is the > length of that? 4 or 5? Length is 4, and I need it to be length of 1. E.g.: >>> s = '\303' >>> s '\xc3' >>> x = '\\303' >>> x '\\303' >>> len(x) 4 >>> len(s) 1 What I get from pygresql is x, what I need is s. Either by asking pygresql to do this or convert it afterwards. I can't do replace('\\303', '\303') because it can be any unicode character. > > -- AK From stefan_ml at behnel.de Sat Aug 22 06:32:52 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 22 Aug 2009 12:32:52 +0200 Subject: Questions on XML In-Reply-To: References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Message-ID: <4a8fc954$0$31331$9b4e6d93@newsspool4.arcor-online.net> Kee Nethery wrote: > As a newbie, the thing that caused me trouble was importing a string > into the XML parser. That would be root_element = et.fromstring(some_string) The parse() function is meant to parse from a file. > from xml.etree import ElementTree as et > theXmlDataTree = et.parse(StringIO.StringIO(theXmlString)) > > from xml.etree import ElementTree as et > theXmlDataTree = et.ElementTree(et.XML(theXmlString)) You can use both, but I suspect parsing from StringIO to be slower than parsing from the string directly. That's the case for lxml, at least. Note that fromstring() behaves the same as XML(), but it reads better when parsing from a string variable. XML() reads better when parsing from a literal string. Stefan From vlastimil.brom at gmail.com Sat Aug 22 06:33:32 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 22 Aug 2009 12:33:32 +0200 Subject: How to 'de-slashify' a string? In-Reply-To: <4a8fc3d1$0$22535$607ed4bc@cv.net> References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> <4a8fc3d1$0$22535$607ed4bc@cv.net> Message-ID: <9fdb569a0908220333u41a662f0j7a898500df50a324@mail.gmail.com> 2009/8/22 AK : > Steven D'Aprano wrote: >> >> On Sat, 22 Aug 2009 04:20:23 -0400, AK wrote: >> >>> Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' >>> in a general way? >> >> It's not clear what you mean. >> >> Do you mean you have a string '\\303\\266', that is: >> >> backslash backslash three zero three backslash backslash two six six >> >> If so, then the simplest way is: >> >>>>> s = r'\\303\\266' ?# note the raw string >>>>> len(s) >> >> 10 >>>>> >>>>> print s >> >> \\303\\266 >>>>> >>>>> print s.replace('\\\\', '\\') >> >> \303\266 >> >> >> Another possibility: >> >>>>> s = '\\303\\266' ?# this is not a raw string >>>>> len(s) >> >> 8 >>>>> >>>>> print s >> >> \303\266 >> >> So s is: >> backslash three zero three backslash two six six >> >> and you don't need to do any more. > > Well, I need the string itself to become '\303\266', not to print > that way. In other words, when I do 'print s', it should display > unicode characters if my term is set to show them, instead of > showing \303\266. > >> >> >>> The problem I'm running into is that I'm connecting with pygresql to a >>> postgres database and when I get fields that are of 'char' type, I get >>> them in unicode, but when I get fields of 'byte' type, I get the text >>> with quoted slashes, e.g. '\303' becomes '\\303' and so on. >> >> Is pygresql quoting the backslash, or do you just think it is quoting the >> backslashes? How do you know? E.g. if you have '\\303', what is the length >> of that? 4 or 5? > > Length is 4, and I need it to be length of 1. E.g.: > >>>> s = '\303' >>>> s > '\xc3' >>>> x = '\\303' >>>> x > '\\303' >>>> len(x) > 4 >>>> len(s) > 1 > > > What I get from pygresql is x, what I need is s. Either by asking pygresql > to do this or convert it afterwards. I can't do replace('\\303', '\303') > because it can be any unicode character. > >> >> > > > -- > AK > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, do you mean something like >>> u"\u0303" u'\u0303' >>> print u"\u0303" ? ? (dec.: 771) (hex.: 0x303) ? COMBINING TILDE (Mark, Nonspacing) ? vbr From steve at REMOVE-THIS-cybersource.com.au Sat Aug 22 06:45:13 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 10:45:13 GMT Subject: Using 'apply' as a decorator, to define constants References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> <001937d5$0$2938$c3e8da3@news.astraweb.com> Message-ID: <00194fa2$0$2938$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 10:51:27 +0100, Jonathan Fine wrote: > Steven D'Aprano wrote: > >> There's a standard idiom for that, using the property() built-in, for >> Python 2.6 or better. >> >> Here's an example including a getter, setter, deleter and doc string, >> with no namespace pollution, imports, or helper functions or deprecated >> built-ins: >> >> class ColourThing(object): >> @property >> def rgb(self): >> """Get and set the (red, green, blue) colours.""" return >> (self.r, self.g, self.b) >> @rgb.setter >> def rgb(self, rgb): >> self.r, self.g, self.b = rgb >> @rgb.deleter >> def rgb(self): >> del self.r, self.g, self.b > > > Sorry, Steve, but I don't understand this. In fact, I don't even see > how it can be made to work. Nevertheless, it does work, and it's not even magic. It's described (very briefly) in the docstring for property: help(property) will show it to you. More detail is here: http://docs.python.org/library/functions.html#property As for how it can work, it's not that difficult. All you need is for the setter and deleter methods to add an appropriate fset and fdel method to the property, then return it. Here's a toy example which may demonstrate the process (although unlike property, fget, fset and fdel don't have any special meanings): class ToyProperty(object): def __init__(self, fget, fset=None, fdel=None, fdoc=None): if fdoc is None: fdoc = fget.__doc__ self.fget = fget self.fset = fset self.fdel = fdel def getter(self, fget): self.fget = fget return self def setter(self, fset): self.fset = fset return self def deleter(self, fdel): self.fdel = fdel return self > Unless an exception is raised, > @wibble > def wobble(): > pass > will make an assignment to wobble, namely the return value of wibble. So > in your example above, there will be /three/ assignments to rgb. Yes. A tiny inefficiency, which only occurs when the class is created. If you care about that, then (1) use the full form of property() where you supply the fget, fset and fdel arguments all at once, and (2) you really need to get out into the fresh air more *wink* > Unless > you do some complicated introspection (and perhaps not even then) surely > they will clobber each other. So what? The process is no weirder than: x = ['fget'] x = x + ['fset'] x = x + ['fdel'] -- Steven From ak at nothere.com Sat Aug 22 06:52:53 2009 From: ak at nothere.com (AK) Date: Sat, 22 Aug 2009 06:52:53 -0400 Subject: How to 'de-slashify' a string? In-Reply-To: References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> <4a8fc3d1$0$22535$607ed4bc@cv.net> Message-ID: <4a8fce05$0$31285$607ed4bc@cv.net> Vlastimil Brom wrote: > 2009/8/22 AK : >> Steven D'Aprano wrote: >>> On Sat, 22 Aug 2009 04:20:23 -0400, AK wrote: >>> >>>> Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' >>>> in a general way? >>> It's not clear what you mean. >>> >>> Do you mean you have a string '\\303\\266', that is: >>> >>> backslash backslash three zero three backslash backslash two six six >>> >>> If so, then the simplest way is: >>> >>>>>> s = r'\\303\\266' # note the raw string >>>>>> len(s) >>> 10 >>>>>> print s >>> \\303\\266 >>>>>> print s.replace('\\\\', '\\') >>> \303\266 >>> >>> >>> Another possibility: >>> >>>>>> s = '\\303\\266' # this is not a raw string >>>>>> len(s) >>> 8 >>>>>> print s >>> \303\266 >>> >>> So s is: >>> backslash three zero three backslash two six six >>> >>> and you don't need to do any more. >> Well, I need the string itself to become '\303\266', not to print >> that way. In other words, when I do 'print s', it should display >> unicode characters if my term is set to show them, instead of >> showing \303\266. >> >>> >>>> The problem I'm running into is that I'm connecting with pygresql to a >>>> postgres database and when I get fields that are of 'char' type, I get >>>> them in unicode, but when I get fields of 'byte' type, I get the text >>>> with quoted slashes, e.g. '\303' becomes '\\303' and so on. >>> Is pygresql quoting the backslash, or do you just think it is quoting the >>> backslashes? How do you know? E.g. if you have '\\303', what is the length >>> of that? 4 or 5? >> Length is 4, and I need it to be length of 1. E.g.: >> >>>>> s = '\303' >>>>> s >> '\xc3' >>>>> x = '\\303' >>>>> x >> '\\303' >>>>> len(x) >> 4 >>>>> len(s) >> 1 >> >> >> What I get from pygresql is x, what I need is s. Either by asking pygresql >> to do this or convert it afterwards. I can't do replace('\\303', '\303') >> because it can be any unicode character. >> >>> >> >> -- >> AK >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > Hi, > do you mean something like > >>>> u"\u0303" > u'\u0303' >>>> print u"\u0303" > ? > ? (dec.: 771) (hex.: 0x303) ? COMBINING TILDE (Mark, Nonspacing) > ? > > vbr Yes, something like that except that it starts out as '\\303\\266', and it's good enough for me if it turns into '\303\266', in fact that's rendered as one unicode char. In other words, when you do: >>> print "\\303\\266" '\303\266' I need that result to become a python string, i.e. the slashes need to be converted from literal slashes to escape slashes. -- AK From marduk at letterboxes.org Sat Aug 22 07:34:17 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sat, 22 Aug 2009 07:34:17 -0400 Subject: debugger In-Reply-To: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> Message-ID: <1250940857.28537.0.camel@centar.nbk> On Sat, 2009-08-22 at 01:17 -0700, flagmino wrote: [...] > I am trying to debug: > I press shift-F9 and F7. I end up in the interpreter where I enter s2 > (1, 2). > > >From that point if I press F7, the program restart all over. > If I press Enter, the program gets out of debug mode. Umm.. which debugger is that? My debugger doesn't have shift-F9... -a From steve at REMOVE-THIS-cybersource.com.au Sat Aug 22 07:40:33 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 11:40:33 GMT Subject: How to 'de-slashify' a string? References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> <4a8fc3d1$0$22535$607ed4bc@cv.net> Message-ID: <00195c9b$0$2938$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 06:09:20 -0400, AK wrote: >> Is pygresql quoting the backslash, or do you just think it is quoting >> the backslashes? How do you know? E.g. if you have '\\303', what is the >> length of that? 4 or 5? > > Length is 4, and I need it to be length of 1. E.g.: > > >>> s = '\303' > >>> s > '\xc3' > >>> x = '\\303' > >>> x > '\\303' > >>> len(x) > 4 > >>> len(s) > 1 > > > What I get from pygresql is x, what I need is s. Either by asking > pygresql to do this or convert it afterwards. I can't do > replace('\\303', '\303') because it can be any unicode character. Use the 'unicode-escape' codec to decode the byte-string to Unicode. >>> s = '\\303\\266' >>> print s \303\266 >>> s '\\303\\266' >>> len(s) 8 >>> u = s.decode('unicode-escape') >>> print u ?? >>> u u'\xc3\xb6' >>> len(u) 2 -- Steven From vlastimil.brom at gmail.com Sat Aug 22 07:43:22 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 22 Aug 2009 13:43:22 +0200 Subject: How to 'de-slashify' a string? In-Reply-To: <4a8fce05$0$31285$607ed4bc@cv.net> References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> <4a8fc3d1$0$22535$607ed4bc@cv.net> <4a8fce05$0$31285$607ed4bc@cv.net> Message-ID: <9fdb569a0908220443i47998230o115e6109835e3b67@mail.gmail.com> 2009/8/22 AK : > Vlastimil Brom wrote: >> >> 2009/8/22 AK : >>> >>> Steven D'Aprano wrote: >>>> >>>> On Sat, 22 Aug 2009 04:20:23 -0400, AK wrote: >>>> >>>>> Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' >>>>> in a general way? >>>> >>>> It's not clear what you mean. >>>> >>>> Do you mean you have a string '\\303\\266', that is: >>>> >>>> backslash backslash three zero three backslash backslash two six six >>>> >>>> If so, then the simplest way is: >>>> >>>>>>> s = r'\\303\\266' ?# note the raw string >>>>>>> len(s) >>>> >>>> 10 >>>>>>> >>>>>>> print s >>>> >>>> \\303\\266 >>>>>>> >>>>>>> print s.replace('\\\\', '\\') >>>> >>>> \303\266 >>>> >>>> >>>> Another possibility: >>>> >>>>>>> s = '\\303\\266' ?# this is not a raw string >>>>>>> len(s) >>>> >>>> 8 >>>>>>> >>>>>>> print s >>>> >>>> \303\266 >>>> >>>> So s is: >>>> backslash three zero three backslash two six six >>>> >>>> and you don't need to do any more. >>> >>> Well, I need the string itself to become '\303\266', not to print >>> that way. In other words, when I do 'print s', it should display >>> unicode characters if my term is set to show them, instead of >>> showing \303\266. >>> >>>> >>>>> The problem I'm running into is that I'm connecting with pygresql to a >>>>> postgres database and when I get fields that are of 'char' type, I get >>>>> them in unicode, but when I get fields of 'byte' type, I get the text >>>>> with quoted slashes, e.g. '\303' becomes '\\303' and so on. >>>> >>>> Is pygresql quoting the backslash, or do you just think it is quoting >>>> the >>>> backslashes? How do you know? E.g. if you have '\\303', what is the >>>> length >>>> of that? 4 or 5? >>> >>> Length is 4, and I need it to be length of 1. E.g.: >>> >>>>>> s = '\303' >>>>>> s >>> >>> '\xc3' >>>>>> >>>>>> x = '\\303' >>>>>> x >>> >>> '\\303' >>>>>> >>>>>> len(x) >>> >>> 4 >>>>>> >>>>>> len(s) >>> >>> 1 >>> >>> >>> What I get from pygresql is x, what I need is s. Either by asking >>> pygresql >>> to do this or convert it afterwards. I can't do replace('\\303', '\303') >>> because it can be any unicode character. >>> >>>> >>> >>> -- >>> AK >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> Hi, >> do you mean something like >> >>>>> u"\u0303" >> >> u'\u0303' >>>>> >>>>> print u"\u0303" >> >> ? >> ? ?? (dec.: 771) ?(hex.: 0x303) ? ? COMBINING TILDE (Mark, Nonspacing) >> ? >> >> vbr > > Yes, something like that except that it starts out as '\\303\\266', and it's > good enough for me if it turns into '\303\266', in fact that's rendered as > one unicode char. In other words, when you do: > >>>> print "\\303\\266" > '\303\266' > > I need that result to become a python string, i.e. the slashes need to > be converted from literal slashes to escape slashes. > > > > > -- > AK > -- > http://mail.python.org/mailman/listinfo/python-list > Not sure, whether it is the right way of handling the such text data, but maybe: >>> decoded = '\\303\\266'.decode("string_escape") >>> decoded '\xc3\xb6' >>> print decoded ?? >>> print '\303\266' ?? >>> It might be an IDLE issue, but it still isn't one unicode glyph. I guess, you have to ensure, that the input data is valid and the right encoding is used. hth vbr From jfine at pytex.org Sat Aug 22 08:04:02 2009 From: jfine at pytex.org (Jonathan Fine) Date: Sat, 22 Aug 2009 13:04:02 +0100 Subject: Using 'apply' as a decorator, to define constants In-Reply-To: <00194fa2$0$2938$c3e8da3@news.astraweb.com> References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> <001937d5$0$2938$c3e8da3@news.astraweb.com> <00194fa2$0$2938$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sat, 22 Aug 2009 10:51:27 +0100, Jonathan Fine wrote: > >> Steven D'Aprano wrote: >> >>> There's a standard idiom for that, using the property() built-in, for >>> Python 2.6 or better. >>> >>> Here's an example including a getter, setter, deleter and doc string, >>> with no namespace pollution, imports, or helper functions or deprecated >>> built-ins: >>> >>> class ColourThing(object): >>> @property >>> def rgb(self): >>> """Get and set the (red, green, blue) colours.""" return >>> (self.r, self.g, self.b) >>> @rgb.setter >>> def rgb(self, rgb): >>> self.r, self.g, self.b = rgb >>> @rgb.deleter >>> def rgb(self): >>> del self.r, self.g, self.b >> >> Sorry, Steve, but I don't understand this. In fact, I don't even see >> how it can be made to work. > > Nevertheless, it does work, and it's not even magic. It's described (very > briefly) in the docstring for property: help(property) will show it to > you. More detail is here: > > http://docs.python.org/library/functions.html#property My apologies. I wasn't up to date with my Python versions: | Changed in version 2.6: The getter, setter, and deleter | attributes were added. I was still thinking Python2.5 (or perhaps earlier?). I still don't like it. All those repetitions of 'rgb'. -- Jonathan From lists at cheimes.de Sat Aug 22 08:35:21 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 Aug 2009 14:35:21 +0200 Subject: grokproject and zope.security==3.4.1 error In-Reply-To: References: Message-ID: Manuel A. Iglesias Abbatemarco schrieb: > I will apprreciate if someone could help me with the following error. > > I a trying to create a grokproject application in my debian 5.0 box, > the following is the output after executing # grokproject Sample > command. > > Getting distribution for 'zope.security==3.4.1'. > > src/zope/security/_proxy.c:19:20: error: Python.h: No such file or directory sudo apt-get install python2.4-dev Have fun :) Christian From python at mrabarnett.plus.com Sat Aug 22 08:55:39 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 22 Aug 2009 13:55:39 +0100 Subject: Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> Message-ID: <4A8FEACB.7030202@mrabarnett.plus.com> Dennis Lee Bieber wrote: > On Fri, 21 Aug 2009 16:52:29 -0700 (PDT), James Harris > declaimed the following in > gmane.comp.python.general: > >> So you are saying that Smalltalk has r where >> r is presumably for radix? That's maybe best of all. It preserves the >> syntactic requirement of starting a number with a digit and seems to >> have greatest flexibility. Not sure how good it looks but it's >> certainly not bad. >> >> 0xff & 0x0e | 0b1101 >> 16rff & 16r0e | 2r1101 >> >> Hmm. Maybe a symbol would be better than a letter. >> > Or Ada's 16#FF#, 8#377#... > '#' starts a comment, so that's right out! :-) > I forget if DEC/VMS FORTRAN or Xerox Sigma FORTRAN used x'FF' or > 'FF'x, and o'377' or '377'o From python at mrabarnett.plus.com Sat Aug 22 08:55:42 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 22 Aug 2009 13:55:42 +0100 Subject: Annoying octal notation In-Reply-To: <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <4A8FEACE.9060503@mrabarnett.plus.com> David wrote: > Il Fri, 21 Aug 2009 16:52:29 -0700 (PDT), James Harris ha scritto: > > >> 0xff & 0x0e | 0b1101 >> 16rff & 16r0e | 2r1101 >> >> Hmm. Maybe a symbol would be better than a letter. > > What about 2_1011, 8_7621, 16_c26h or 2;1011, 8;7621, 16;c26h ? > '_': what if in the future we want to allow them in numbers for clarity? ';': used to separate multiple statements on a line (but not used that often). From catalinfest at gmail.com Sat Aug 22 09:14:25 2009 From: catalinfest at gmail.com (catafest) Date: Sat, 22 Aug 2009 06:14:25 -0700 (PDT) Subject: PIL and Python References: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> <5df342cf-c742-42d6-bc8c-97a3c44a0816@h21g2000yqa.googlegroups.com> Message-ID: If I make it work, i will send the solution. Thank you ! From stef.mientki at gmail.com Sat Aug 22 09:40:51 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 22 Aug 2009 15:40:51 +0200 Subject: debugger In-Reply-To: <1250940857.28537.0.camel@centar.nbk> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> <1250940857.28537.0.camel@centar.nbk> Message-ID: <4A8FF563.5070003@gmail.com> Albert Hopkins wrote: > On Sat, 2009-08-22 at 01:17 -0700, flagmino wrote: > [...] > >> I am trying to debug: >> I press shift-F9 and F7. I end up in the interpreter where I enter s2 >> (1, 2). >> >> >From that point if I press F7, the program restart all over. >> If I press Enter, the program gets out of debug mode. >> > > Umm.. which debugger is that? My debugger doesn't have shift-F9... > then you probably not working under windows ... Stef From piet at cs.uu.nl Sat Aug 22 09:52:44 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 22 Aug 2009 15:52:44 +0200 Subject: How to 'de-slashify' a string? References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> <4a8fc3d1$0$22535$607ed4bc@cv.net> <4a8fce05$0$31285$607ed4bc@cv.net> Message-ID: >>>>> Vlastimil Brom (VB) wrote: >>>>> decoded = '\\303\\266'.decode("string_escape") >>>>> decoded >VB> '\xc3\xb6' >>>>> print decoded >VB> ?? >>>>> print '\303\266' >VB> ?? >>>>> >VB> It might be an IDLE issue, but it still isn't one unicode glyph. >VB> I guess, you have to ensure, that the input data is valid and the >VB> right encoding is used. >>> decoded = '\\303\\266'.decode("string_escape").decode('utf-8') >>> decoded u'\xf6' >>> print decoded ? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From python.list at tim.thechases.com Sat Aug 22 10:07:52 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 22 Aug 2009 09:07:52 -0500 Subject: debugger In-Reply-To: <4A8FF563.5070003@gmail.com> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> <1250940857.28537.0.camel@centar.nbk> <4A8FF563.5070003@gmail.com> Message-ID: <4A8FFBB8.4070706@tim.thechases.com> Stef Mientki wrote: > Albert Hopkins wrote: >> On Sat, 2009-08-22 at 01:17 -0700, flagmino wrote: >> [...] >> >>> I am trying to debug: >>> I press shift-F9 and F7. I end up in the interpreter where I enter s2 >>> (1, 2). >>> >>> >From that point if I press F7, the program restart all over. >>> If I press Enter, the program gets out of debug mode. >>> >> Umm.. which debugger is that? My debugger doesn't have shift-F9... >> > then you probably not working under windows ... Even under Windows, you still have to specify your environment. In both Win32 and *nix I use pdb as my debugger and shift+F9 does nothing ;-) So the question is what is the debugger the OP is using? Because it's not pdb. :) -tkc From grante at visi.com Sat Aug 22 10:08:09 2009 From: grante at visi.com (Grant Edwards) Date: Sat, 22 Aug 2009 09:08:09 -0500 Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <6a523329-3287-4271-ba37-7be450cfc5f6@d32g2000yqh.googlegroups.com> <4a8edc29$0$1599$742ec2ed@news.sonic.net> Message-ID: On 2009-08-22, Dennis Lee Bieber wrote: > On Fri, 21 Aug 2009 10:45:51 -0700, John Nagle > declaimed the following in gmane.comp.python.general: > >> >> And it's over. We can finally dispense with octal by default. >> > I've not looked at modern Intel processor format, but if there are > folks still using variants of 8080 (8051?) and Z-80, Octal still works > nice for op-codes... I don't recall the exact values, but the MOV > instruction was something like '1SD'o, where S and D are three bit > register specifications (A, B, C, D, E, H, L, and Memory as I recall) The Heathkit's terminal I have uses a Z80, and IIRC, the assembly listings were in split-octal [a 16 bit word ranges from 000 000 to 377 377]. Stuff for the PDP-11 (which also had instruction fields 3 bits wide) was always in octal as well. The PDP-11 is pretty much dead, but I think there are embedded Z80 derivitives still in use. -- Grant From ebonak at hotmail.com Sat Aug 22 10:25:37 2009 From: ebonak at hotmail.com (Esmail) Date: Sat, 22 Aug 2009 10:25:37 -0400 Subject: your favorite debugging tool? Message-ID: Hi all, What is your favorite tool to help you debug your code? I've been getting along with 'print' statements but that is getting old and somewhat cumbersome. I'm primarily interested in utilities for Linux (but if you have recommendations for Windows, I'll take them too :) I use emacs as my primary development environment, FWIW. Someone mentioned winpdb .. anyone have experience/comments on this? Others? Thanks, Esmail From Scott.Daniels at Acm.Org Sat Aug 22 10:37:08 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 22 Aug 2009 07:37:08 -0700 Subject: debugger In-Reply-To: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> Message-ID: flagmino wrote: > To get familiar with the debugger, I have loaded this program: > > import math > > def s1(x, y): > a = (x + y) > print("Answer from s1"), a > return > > def s2(x, y): > b = (x - y) > print("This comes from s2"), b > #print z > print("call from s2: "), s1(x, y) > return > > I am trying to debug: > I press shift-F9 and F7. I end up in the interpreter where I enter s2 > (1, 2). > > From that point if I press F7, the program restart all over. > If I press Enter, the program gets out of debug mode. > > Please help me figuring out how I can use the dbugger. You are welcome > to send a sound file if this is easier for you. > > Thanks > > ray You need to tell us: Which Python version (e.g. 2.6.2) Which "platform" (hardware & OS) (e.g. 64-bit AMD FreeBSD) Which debugger (e.g. Idle) What you expected to happen that did not, and why you expected it. or What happened and why you did not expect it. Often you can lots of this information by going to your debugger window and doing Help // About, and go to your Python environment and type: import sys print sys.version # cut the results and paste in your message as "sys.version says, "'2.6.2 (r262:71605, ...'" [don't do dots yourself] To understand more of why we need this on every question, see: http://www.mikeash.com/getting_answers.html or google for "smart questions". --Scott David Daniels Scott.Daniels at Acm.Org From aahz at pythoncraft.com Sat Aug 22 10:49:22 2009 From: aahz at pythoncraft.com (Aahz) Date: 22 Aug 2009 07:49:22 -0700 Subject: your favorite debugging tool? References: Message-ID: In article , Esmail wrote: > >What is your favorite tool to help you debug your code? I've been >getting along with 'print' statements but that is getting old and >somewhat cumbersome. Despite the fact that I've been using Python for more than a decade, print is still my mainstay (or possibly logging to a file). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From davea at ieee.org Sat Aug 22 10:51:08 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 22 Aug 2009 10:51:08 -0400 Subject: Blank Line at Program Exit In-Reply-To: References: Message-ID: <4A9005DC.1050906@ieee.org> Steven Woody wrote: > Hi, > Any python program, even that does absolutely nothing in the code, will > cause a blank line printed out when the program exit. What's the reason? > Thanks. > > > I think the "blank line" is coming from your shell. In Windows, I believe the shell emits a newline after running a program, probably to make sure the prompt starts in column 0. Note that if your python program writes a partial line to stdout, this will "finish" the line before giving you the next prompt. So the line isn't necessarily blank. DaveA From marduk at letterboxes.org Sat Aug 22 10:59:55 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sat, 22 Aug 2009 10:59:55 -0400 Subject: Decompressing gzip over FTP In-Reply-To: References: Message-ID: <1250953195.7115.5.camel@centar.nbk> On Fri, 2009-08-21 at 18:15 -0700, SeanMon wrote: > Is there a way to decompress a large (2GB) gzipped file being > retrieved over FTP on the fly? > > I'm using ftplib.FTP to open a connection to a remote server, and I > have had no success connecting retrbinary to gzip without using an > intermediate file. > > Is there any way to get a file-like object describing the remote file, > or a way to utilize gzip's decompression without providing it a file- > like object? I tried to solve your problem with StringIO and .truncate(). I also tried to solve it with us.pipe(), but was unsuccessful with either. The problem is the gzip module uses .seek() which you can't do with pipes... You could probably get away with just using the compress module (as zlib does) but you will have to deal with handling the headers, footers, CRC checks, etc. on your own. The cheap alternative is to just have your script open a pipe to "gunzip -c" and read/write from that pipe. hth, -a From ryniek90 at gmail.com Sat Aug 22 11:00:41 2009 From: ryniek90 at gmail.com (ryniek90) Date: Sat, 22 Aug 2009 17:00:41 +0200 Subject: TypeError while checking for permissions with os.access() on windows xp In-Reply-To: References: Message-ID: <4A900819.8010702@gmail.com> > First, some nitpicking: Include the whole traceback when posting about > errors please. Don't write "if some_boolean_expression != True:" > instead prefer "if not some_boolean_expression:". Also, in your code > "except (Except), ex: return ex" the parentheses are redundant, > there's no "Except" Exception (unless you created one yourself) and > why are you catching and returning the Exception object? (Also, > what's that "sys.exit(0)" doing in there? And why exit with 0 if there > was a problem? Exit code 0 means "no problem".) > > > Second, from what you've said backup_dest must be None: > > >>>> import os >>>> os.access(None, os.W_OK) >>>> > > Traceback (most recent call last): > File "", line 1, in > os.access(None, os.W_OK) > TypeError: coercing to Unicode: need string or buffer, NoneType found > > No, backup_dest is destination for backup. It's this variable: *backup_dest = self.__backup_dest* . *self.__backup_dest = os.getenv('HOME')* - as you can see, self.__backup_dest is a reference to the home directory which is a string. Then backup_dest is a reference to the variable self.__backup_dest. But that second reference seems to be recognised as a NoneType ?? I'm using optparse in my script (that code for checking for permission is a part of my backup script). Maybe i post my complete code: " #!/usr/bin/env python #-*- coding: utf-8 -*- #MyBackUper import os, sys, tarfile import datetime from optparse import OptionParser class Except(Exception): pass class Packer(Except): def __init__(self): self.__backup_dest = os.getenv('HOME') __current_time = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S') Except.__init__(self) def doc_note(self): print """ DOCUMENTATION 'Backuper' is a script for doing backups. You can backup with it single files or whole directories. For available commands type 'backuper.py -h' or 'backuper.py --help'. Using it is simple: - to backup single file, type: 'backuper.py -f FILE_PATH BCKP_NAME [DEST_PATH]', where 'FILE_PATH' is exact path to prefered file which you want to backup and 'BCKP_NAME' is the name for backup output file. Default 'DEST_PATH' is placed in home directory, it can't be changed. 'BCKP_NAME' must be given; - to backup whole directory, type: 'backuper.py -d DIR_PATH BCKP_NAME [DEST_PATH]', where 'DIR_PATH' is exact path to prefered directory, which you want to backup and 'BCKP_NAME' is the name for backup output file. Default 'DEST_PATH' is placed in home directory, it can't be changed. 'BCKP_NAME' must be given; """ def __check_set_perm(self, rd_obj_path, backup_dest): try: if os.path.exists(rd_obj_path): if not os.access(rd_obj_path, os.R_OK): print "Have no permissions on [%s] for reading operation.\nTrying to set them..." % os.path.split(rd_obj_path)[1] if not os.path.isdir(rd_obj_path): os.chmod(rd_obj_path, stat.S_IREAD) else: for root, dirs, files in os.walk(rd_obj_path): for f in files: os.chmod(os.path.join(root, f), stat.S_IREAD) print "Get permissions for reading on [%s] successfully." % os.path.split(rd_obj_path)[1] else: print "Have permissions on [%s] for reading." % os.path.split(rd_obj_path)[1] if not os.access(backup_dest, os.W_OK): print "Have no permissions on [%s] for writing operation.\nTrying to set them..." % os.path.split(backup_dest)[1] os.chmod(backup_dest, stat.S_IWRITE) print "Get permissions for reading on [%s] successfully." % os.path.split(backup_dest)[1] else: print "Have permissions on [%s] for writing." % os.path.split(backup_dest)[1] else: return "Can't find specified path - [%s]." % rd_obj_path sys.exit(1) except (Except), ex: return ex def backup_file(self, rd_obj_path, bkp_obj_name): try: if os.name == "nt": rd_obj_path = rd_obj_path.replace('~/', '%s\\' % os.getenv('HOME')).replace('\\', '\\\\') backup_dest = self.__backup_dest print "Checking permissions for reading and writing..." self.__check_set_perm(rd_obj_path, backup_dest) backup_obj = tarfile.open("%s\\%s(%s).tar.bz2" % (backup_dest, bkp_obj_name, __current_time), 'w:bz2') else: rd_obj_path = rd_obj_path.replace('~/', '%s/' % os.getenv('HOME')) backup_dest = self.__backup_dest print "Checking permissions for reading and writing..." self.__check_set_perm(rd_obj_path, backup_dest) backup_obj = tarfile.open("%s/%s(%s).tar.bz2" % (backup_dest, bkp_obj_name, __current_time), 'w:bz2') print "Preparing for backup [%s]..." % os.path.split(rd_obj_path)[1] print "Starting backup..." read_obj = open(rd_obj_path, 'rb') print "Now adding [%s]..." % os.path.split(rd_obj_path)[1] backup_obj.add(read_obj.read()) read_obj.close(), backup_obj.close() print "Backup [%s] made successfully. :-)" % os.path.split(backup_dest)[1] except (Except), ex: return ex def backup_dir(self, rd_obj_path, bkp_obj_name): try: if os.name == "nt": rd_obj_path = rd_obj_path.replace('~/', '%s\\' % os.getenv('HOME')).replace('\\', '\\\\') backup_dest = self.__backup_dest print "Checking permissions for reading and writing..." self.__check_set_perm(rd_obj_path, backup_dest) backup_obj = tarfile.open("%s\\%s(%s).tar.bz2" % (backup_dest, bkp_obj_name, __current_time), 'w:bz2') else: rd_obj_path = rd_obj_path.replace('~/', '%s/' % os.getenv('HOME')) backup_dest = self.__backup_dest print "Checking permissions for reading and writing..." self.__check_set_perm(rd_obj_path, backup_dest) backup_obj = tarfile.open("%s/%s(%s).tar.bz2" % (backup_dest, bkp_obj_name, __current_time), 'w:bz2') print "Preparing for backup '%s'..." % os.path.split(rd_obj_path)[1] print "Gathering files for backup..." path_list = [] for root, dirs, files in os.walk(rd_obj_path): for f in files: path_list.append(os.path.join(root, f)) print "Starting backup..." for p in path_list: fl = open(p, 'rb') print "Now adding [%s] from [%s] directory" % (os.path.split(p)[1], os.path.split(p)[0]) backup_obj.add(fl.read()) fl.close() print "Added [%s] successfully" % os.path.split(p)[1] backup_obj.close() print "Backup [%s] made successfully. :-)" % os.path.split(backup_dest)[1] except (Except), ex: return ex class ParseIt(object): def __init__(self): self.__initial = True _usage = "usage: %prog [options] Arg1 Arg2" parser = OptionParser(_usage) parser.add_option("-f", "--file", action="store", type="string", dest="filename", help="Make backup of a single file", metavar="FILE_PATH CKP_NAME", nargs=2) parser.add_option("-d", "--dir", action="store", type="string", dest="dirname", help="Recursively backup a whole directory", metavar="DIR_PATH BCKP_NAME", nargs=2) parser.add_option("-i", "--info", dest="info_note", action="store_true", help="Show script's documentation") (options, args) = parser.parse_args() def main_meth(): paq = Packer() pars = ParseIt() if pars.options.filename: paq.backup_file(pars.options.filename[0], pars.options.filename[1]) elif pars.options.dirname: paq.backup_dir(pars.options.dirname[0], pars.options.dirname[1]) elif pars.options.info_note: paq.doc_note() if __name__ == "__main__": main_meth() " From davea at ieee.org Sat Aug 22 11:15:32 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 22 Aug 2009 11:15:32 -0400 Subject: debugger In-Reply-To: <4A8FF563.5070003@gmail.com> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> <1250940857.28537.0.camel@centar.nbk> <4A8FF563.5070003@gmail.com> Message-ID: <4A900B94.6060607@ieee.org> Stef Mientki wrote: >
Albert > Hopkins wrote: >> On Sat, 2009-08-22 at 01:17 -0700, flagmino wrote: >> [...] >> >>> I am trying to debug: >>> I press shift-F9 and F7. I end up in the interpreter where I enter s2 >>> (1, 2). >>> >>> >From that point if I press F7, the program restart all over. >>> If I press Enter, the program gets out of debug mode. >>> >> >> Umm.. which debugger is that? My debugger doesn't have shift-F9... >> > then you probably not working under windows ... > > Stef > >
> That doesn't help. If you want help, describe the environment. Python version, OS, and what command you did to start this "debugger." Or at least its name. The Windows debugger is called Debug.exe, and it doesn't accept Shift-F9. But I doubt the OP was talking about that one. Komodo doesn't seem to do anything with Shift-F9 either. PythonWin doesn't seem to, nor does Idle. Most of these could be customized, but that's besides the point. In version: 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)], running under XPsp3, with win32 extensions loaded, there are a bunch of files called debug or debugger. Which one might be meant here? Or perhaps the debugger was part of NetBeans, or Eclipse, or some other IDE? DaveA From nitebirdz at sacredchaos.com Sat Aug 22 11:25:16 2009 From: nitebirdz at sacredchaos.com (Nitebirdz) Date: Sat, 22 Aug 2009 17:25:16 +0200 Subject: Blank Line at Program Exit In-Reply-To: References: Message-ID: <20090822152515.GC10584@sevilla.sacredchaos.com> On Thu, Aug 20, 2009 at 01:31:14PM +0800, Steven Woody wrote: > Hi, > Any python program, even that does absolutely nothing in the code, will > cause a blank line printed out when the program exit. What's the reason? > Thanks. > Chances are it is related to whichever operating system and/or shell you are using. For instance, this is taken from a system running Ubuntu Linux 8.04: ------------------------------------------------- laptop:$ cat hello.py #!/usr/bin/env python print "Hello, there!" laptop:$ ./hello.py Hello, there! laptop:$ cat nothing.py #!/usr/bin/env python laptop:$ ./nothing.py laptop:$ ------------------------------------------------- As you can see, no blank line was printed out. From python at mrabarnett.plus.com Sat Aug 22 11:49:30 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 22 Aug 2009 16:49:30 +0100 Subject: debugger In-Reply-To: <4A900B94.6060607@ieee.org> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> <1250940857.28537.0.camel@centar.nbk> <4A8FF563.5070003@gmail.com> <4A900B94.6060607@ieee.org> Message-ID: <4A90138A.4000905@mrabarnett.plus.com> Dave Angel wrote: > Stef Mientki wrote: >>
Albert >> Hopkins wrote: >>> On Sat, 2009-08-22 at 01:17 -0700, flagmino wrote: >>> [...] >>> >>>> I am trying to debug: >>>> I press shift-F9 and F7. I end up in the interpreter where I enter s2 >>>> (1, 2). >>>> >>>> >From that point if I press F7, the program restart all over. >>>> If I press Enter, the program gets out of debug mode. >>>> >>> >>> Umm.. which debugger is that? My debugger doesn't have shift-F9... >>> >> then you probably not working under windows ... >> >> Stef >> >>
>> > That doesn't help. If you want help, describe the environment. Python > version, OS, and what command you did to start this "debugger." Or at > least its name. > > The Windows debugger is called Debug.exe, and it doesn't accept > Shift-F9. But I doubt the OP was talking about that one. Komodo > doesn't seem to do anything with Shift-F9 either. > > PythonWin doesn't seem to, nor does Idle. Most of these could be > customized, but that's besides the point. > > In version: 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 > bit (Intel)], running under XPsp3, with win32 extensions loaded, there > are a bunch of files called debug or debugger. Which one might be meant > here? > > Or perhaps the debugger was part of NetBeans, or Eclipse, or some other > IDE? > It might be winpdb, although I haven't been able to confirm it. From davea at ieee.org Sat Aug 22 13:36:12 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 22 Aug 2009 13:36:12 -0400 Subject: TypeError while checking for permissions with os.access() on windows xp In-Reply-To: <4A900819.8010702@gmail.com> References: <4A900819.8010702@gmail.com> Message-ID: <4A902C8C.4070108@ieee.org> ryniek90 wrote: >
>> First, some nitpicking: Include the whole traceback when posting about >> errors please. Don't write "if some_boolean_expression != True:" >> instead prefer "if not some_boolean_expression:". Also, in your code >> "except (Except), ex: return ex" the parentheses are redundant, >> there's no "Except" Exception (unless you created one yourself) and >> why are you catching and returning the Exception object? (Also, >> what's that "sys.exit(0)" doing in there? And why exit with 0 if there >> was a problem? Exit code 0 means "no problem".) >> >> >> Second, from what you've said backup_dest must be None: >> >> >>>>> import os >>>>> os.access(None, os.W_OK) >>>>> >> >> Traceback (most recent call last): >> File "", line 1, in >> os.access(None, os.W_OK) >> TypeError: coercing to Unicode: need string or buffer, NoneType found >> >> > > No, backup_dest is destination for backup. It's this variable: > *backup_dest = self.__backup_dest* . > *self.__backup_dest = os.getenv('HOME')* - as you can see, > self.__backup_dest is a reference to the home directory which is a > string. Then backup_dest is a reference to the variable > self.__backup_dest. But that second reference seems to be recognised > as a NoneType ?? > > I'm using optparse in my script (that code for checking for permission > is a part of my backup script). > > Maybe i post my complete code: > " > #!/usr/bin/env python > #-*- coding: utf-8 -*- > #MyBackUper > > import os, sys, tarfile > import datetime > from optparse import OptionParser > > > class Except(Exception): > pass > > > class Packer(Except): > > def __init__(self): > self.__backup_dest = os.getenv('HOME') > __current_time = datetime.datetime.today().strftime('%Y-%m-%d > %H:%M:%S') > Except.__init__(self) > > def doc_note(self): > > print """ > > DOCUMENTATION > > 'Backuper' is a script for doing backups. > You can backup with it single files or whole directories. > For available commands type 'backuper.py -h' or 'backuper.py > --help'. > > Using it is simple: > > - to backup single file, type: > 'backuper.py -f FILE_PATH BCKP_NAME [DEST_PATH]', > where 'FILE_PATH' is exact path to prefered file which you want > to backup and 'BCKP_NAME' is the name for backup output file. Default > 'DEST_PATH' is placed in home directory, it can't be changed. > 'BCKP_NAME' must be given; > > - to backup whole directory, type: > 'backuper.py -d DIR_PATH BCKP_NAME [DEST_PATH]', where > 'DIR_PATH' is exact path to prefered directory, which you want to > backup and 'BCKP_NAME' is the name for backup output file. Default > 'DEST_PATH' is placed in home directory, it can't be changed. > 'BCKP_NAME' must be given; > > """ > > def __check_set_perm(self, rd_obj_path, backup_dest): > > try: > > if os.path.exists(rd_obj_path): > if not os.access(rd_obj_path, os.R_OK): > print "Have no permissions on [%s] for reading > operation.\nTrying to set them..." % os.path.split(rd_obj_path)[1] > if not os.path.isdir(rd_obj_path): > os.chmod(rd_obj_path, stat.S_IREAD) > else: > for root, dirs, files in os.walk(rd_obj_path): > for f in files: > os.chmod(os.path.join(root, f), > stat.S_IREAD) > print "Get permissions for reading on [%s] > successfully." % os.path.split(rd_obj_path)[1] > else: > print "Have permissions on [%s] for reading." % > os.path.split(rd_obj_path)[1] > > if not os.access(backup_dest, os.W_OK): > print "Have no permissions on [%s] for writing > operation.\nTrying to set them..." % os.path.split(backup_dest)[1] > os.chmod(backup_dest, stat.S_IWRITE) > print "Get permissions for reading on [%s] > successfully." % os.path.split(backup_dest)[1] > else: > print "Have permissions on [%s] for writing." % > os.path.split(backup_dest)[1] > else: > return "Can't find specified path - [%s]." % rd_obj_path > sys.exit(1) > > except (Except), ex: > return ex > > > def backup_file(self, rd_obj_path, bkp_obj_name): > > try: > > if os.name == "nt": > rd_obj_path = rd_obj_path.replace('~/', '%s\\' % > os.getenv('HOME')).replace('\\', '\\\\') > backup_dest = self.__backup_dest > print "Checking permissions for reading and writing..." > self.__check_set_perm(rd_obj_path, backup_dest) > backup_obj = tarfile.open("%s\\%s(%s).tar.bz2" % > (backup_dest, bkp_obj_name, __current_time), 'w:bz2') > > else: > rd_obj_path = rd_obj_path.replace('~/', '%s/' % > os.getenv('HOME')) > backup_dest = self.__backup_dest > print "Checking permissions for reading and writing..." > self.__check_set_perm(rd_obj_path, backup_dest) > backup_obj = tarfile.open("%s/%s(%s).tar.bz2" % > (backup_dest, bkp_obj_name, __current_time), 'w:bz2') > > print "Preparing for backup [%s]..." % > os.path.split(rd_obj_path)[1] > print "Starting backup..." > read_obj = open(rd_obj_path, 'rb') > print "Now adding [%s]..." % os.path.split(rd_obj_path)[1] > backup_obj.add(read_obj.read()) > read_obj.close(), backup_obj.close() > print "Backup [%s] made successfully. :-)" % > os.path.split(backup_dest)[1] > > except (Except), ex: > return ex > > def backup_dir(self, rd_obj_path, bkp_obj_name): > > try: > > if os.name == "nt": > rd_obj_path = rd_obj_path.replace('~/', '%s\\' % > os.getenv('HOME')).replace('\\', '\\\\') > backup_dest = self.__backup_dest > print "Checking permissions for reading and writing..." > self.__check_set_perm(rd_obj_path, backup_dest) > backup_obj = tarfile.open("%s\\%s(%s).tar.bz2" % > (backup_dest, bkp_obj_name, __current_time), 'w:bz2') > > else: > rd_obj_path = rd_obj_path.replace('~/', '%s/' % > os.getenv('HOME')) > backup_dest = self.__backup_dest > print "Checking permissions for reading and writing..." > self.__check_set_perm(rd_obj_path, backup_dest) > backup_obj = tarfile.open("%s/%s(%s).tar.bz2" % > (backup_dest, bkp_obj_name, __current_time), 'w:bz2') > > print "Preparing for backup '%s'..." % > os.path.split(rd_obj_path)[1] > print "Gathering files for backup..." > path_list = [] > for root, dirs, files in os.walk(rd_obj_path): > for f in files: > path_list.append(os.path.join(root, f)) > print "Starting backup..." > for p in path_list: > fl = open(p, 'rb') > print "Now adding [%s] from [%s] directory" % > (os.path.split(p)[1], os.path.split(p)[0]) > backup_obj.add(fl.read()) > fl.close() > print "Added [%s] successfully" % os.path.split(p)[1] > backup_obj.close() > print "Backup [%s] made successfully. :-)" % > os.path.split(backup_dest)[1] > > except (Except), ex: > return ex > > > class ParseIt(object): > > def __init__(self): > self.__initial = True > > _usage = "usage: %prog [options] Arg1 Arg2" > parser = OptionParser(_usage) > parser.add_option("-f", "--file", action="store", type="string", > dest="filename", help="Make backup of a single file", > metavar="FILE_PATH CKP_NAME", nargs=2) > parser.add_option("-d", "--dir", action="store", type="string", > dest="dirname", help="Recursively backup a whole directory", > metavar="DIR_PATH BCKP_NAME", nargs=2) > parser.add_option("-i", "--info", dest="info_note", > action="store_true", help="Show script's documentation") > > (options, args) = parser.parse_args() > > def main_meth(): > paq = Packer() > pars = ParseIt() > if pars.options.filename: > paq.backup_file(pars.options.filename[0], > pars.options.filename[1]) > elif pars.options.dirname: > paq.backup_dir(pars.options.dirname[0], pars.options.dirname[1]) > elif pars.options.info_note: > paq.doc_note() > > > if __name__ == "__main__": > main_meth() > > " > > > >
> I don't know why you didn't immediately add a print statement just before the failing os.access(), once you saw the error message. You could have printed out both the formal parameter and the instance attribute. Simple explanation: you probably don't have an environment variable named "HOME". I don't either, on Windows. You need to test for that, and put some error handling, so the lack of an environment variable won't crash your program. > Then backup_dest is a reference to the variable self.__backup_dest. But that second reference seems to be recognised as a NoneType ?? backup_dest is a local variable which is a reference to whatever object self.__backup_dest referenced. That could be a very different thing. But in this case the subtlety isn't important -- they're both referencing None, which is the object returned by os.getenv() when the requested environment variable doesn't exist. DaveA From kee at kagi.com Sat Aug 22 13:46:51 2009 From: kee at kagi.com (Kee Nethery) Date: Sat, 22 Aug 2009 10:46:51 -0700 Subject: string literal vs string variable In-Reply-To: <4a8fc954$0$31331$9b4e6d93@newsspool4.arcor-online.net> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8fc954$0$31331$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On Aug 22, 2009, at 3:32 AM, Stefan Behnel wrote: > > You can use both, but I suspect parsing from StringIO to be slower > than > parsing from the string directly. That's the case for lxml, at least. > > Note that fromstring() behaves the same as XML(), but it reads > better when > parsing from a string variable. XML() reads better when parsing from a > literal string. I'm not sure I know the difference between a string variable and a literal string. Is the difference as simple as: somestring = u'hello world' fromstring(somestring) <-- string variable vs XML(u'hello world') <-- literal string Kee From gnuist006 at gmail.com Sat Aug 22 14:11:32 2009 From: gnuist006 at gmail.com (bolega) Date: Sat, 22 Aug 2009 11:11:32 -0700 (PDT) Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? Message-ID: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? I really prefer a sed one liner. Example Input : This is my book. It is too thick to read. The author gets little royalty but the publisher makes a lot. Output: This_is_my_book._It_is_too__thick_to read. The author gets little royalty but the publisher makes a lot. We replaced all the spaces with underscores before the first occurence of the string "to ". Thanks Gnuist From carlosfabianramirez at gmail.com Sat Aug 22 14:12:50 2009 From: carlosfabianramirez at gmail.com (Carlos Fabian Ramirez) Date: Sat, 22 Aug 2009 14:12:50 -0400 Subject: Urllib2 not working Message-ID: <51303220908221112w79ccb746i900c22d45fff07c7@mail.gmail.com> Hello, When I try to open a URL using urllib2.urlopen it returns Name or service not known. It is not a problem with my Internet I believe, since I have Internet access on my computer, and I have verified it is not a syntax, or spelling, error on my part. I have also tried accessing the site (google.com) by IP like so: urllib2.urlopen('http://74.125.67.100/') but this does not work either. This is a traceback of an attempt to access it through its URL ( http://www.google.com/) http://dpaste.com/84016/ Any help would be very appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From w_a_x_man at yahoo.com Sat Aug 22 14:24:56 2009 From: w_a_x_man at yahoo.com (w_a_x_man) Date: Sat, 22 Aug 2009 11:24:56 -0700 (PDT) Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> Message-ID: <1bc82397-1e91-4055-879a-c178534e1c17@z24g2000yqb.googlegroups.com> On Aug 22, 1:11?pm, bolega wrote: > sed/awk/perl: > > How to replace all spaces each with an underscore that occur before a > specific string ? > > I really prefer a sed one liner. > > Example > Input : ?This is my book. It is too ?thick to read. The author gets > little royalty but the publisher makes a lot. > Output: This_is_my_book._It_is_too__thick_to read. The author gets > little royalty but the publisher makes a lot. > > We replaced all the spaces with underscores before the first occurence > of the string "to ". > > Thanks > Gnuist awk 'BEGIN{FS=OFS="to "}{gsub(/ /,"_",$1);print}' myfile From MacRules at nome.com Sat Aug 22 14:25:25 2009 From: MacRules at nome.com (MacRules) Date: Sat, 22 Aug 2009 14:25:25 -0400 Subject: Python - insert image / pdf / blob files to MySQL, MSSQL Message-ID: <4a903814$0$10311$607ed4bc@cv.net> Where to find code examples? Or someone can post sample codes here. Thanks From code at pizzashack.org Sat Aug 22 15:04:17 2009 From: code at pizzashack.org (Derek Martin) Date: Sat, 22 Aug 2009 14:04:17 -0500 Subject: Annoying octal notation In-Reply-To: <87d46ok948.fsf@benfinney.id.au> References: <87d46ok948.fsf@benfinney.id.au> Message-ID: <20090822190417.GW20434@dragontoe.org> On Sat, Aug 22, 2009 at 10:03:35AM +1000, Ben Finney wrote: > > and the former is virtually indistinguishable from 00012, O0012, or > > many other combinations that someone might accidentally type (or > > intentionally type, having to do this in dozens of other programming > > languages). > > Only if you type the letter in uppercase. The lower-case ?o? is much > easier to distinguish. It is easier, but I dispute that it is much easier. > Whether or not you find ?0o012? easily distinguishable as a non-decimal > notation, it's undoubtedly easier to distinguish than ?012?. 012 has meant decimal 10 in octal to me for so long, from its use in MANY other programming languages, that I disagree completely. > > I can see how 012 can be confusing to new programmers, but at least > > it's legible, and the great thing about humans is that they can be > > taught (usually). I for one think this change is completely misguided. > > These human programmers, whether newbies or long-experienced, also deal > with decimal numbers every day, many of which are presented as a > sequence of digits with leading zeros ? and we continue to think of them > as decimal numbers regardless. Having the language syntax opposed to > that is ...consistent with virtually every other popular programming language. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ryniek90 at gmail.com Sat Aug 22 15:16:11 2009 From: ryniek90 at gmail.com (ryniek90) Date: Sat, 22 Aug 2009 21:16:11 +0200 Subject: TypeError while checking for permissions with os.access() on windows xp In-Reply-To: References: Message-ID: <4A9043FB.7070108@gmail.com> > >>> First, some nitpicking: Include the whole traceback when posting about >>> errors please. Don't write "if some_boolean_expression != True:" >>> instead prefer "if not some_boolean_expression:". Also, in your code >>> "except (Except), ex: return ex" the parentheses are redundant, >>> there's no "Except" Exception (unless you created one yourself) and >>> why are you catching and returning the Exception object? (Also, >>> what's that "sys.exit(0)" doing in there? And why exit with 0 if there >>> was a problem? Exit code 0 means "no problem".) >>> >>> >>> Second, from what you've said backup_dest must be None: >>> >>> >>>>>> import os >>>>>> os.access(None, os.W_OK) >>>>>> >>> >>> Traceback (most recent call last): >>> File "", line 1, in >>> os.access(None, os.W_OK) >>> TypeError: coercing to Unicode: need string or buffer, NoneType found >>> >>> >> >> No, backup_dest is destination for backup. It's this variable: >> *backup_dest = self.__backup_dest* . >> *self.__backup_dest = os.getenv('HOME')* - as you can see, >> self.__backup_dest is a reference to the home directory which is a >> string. Then backup_dest is a reference to the variable >> self.__backup_dest. But that second reference seems to be recognised >> as a NoneType ?? >> >> I'm using optparse in my script (that code for checking for >> permission is a part of my backup script). >> >> Maybe i post my complete code: >> " >> #!/usr/bin/env python >> #-*- coding: utf-8 -*- >> #MyBackUper >> >> import os, sys, tarfile >> import datetime >> from optparse import OptionParser >> >> >> class Except(Exception): >> pass >> >> >> class Packer(Except): >> >> def __init__(self): >> self.__backup_dest = os.getenv('HOME') >> __current_time = datetime.datetime.today().strftime('%Y-%m-%d >> %H:%M:%S') >> Except.__init__(self) >> >> def doc_note(self): >> >> print """ >> >> DOCUMENTATION >> >> 'Backuper' is a script for doing backups. >> You can backup with it single files or whole directories. >> For available commands type 'backuper.py -h' or 'backuper.py >> --help'. >> >> Using it is simple: >> >> - to backup single file, type: >> 'backuper.py -f FILE_PATH BCKP_NAME [DEST_PATH]', >> where 'FILE_PATH' is exact path to prefered file which you >> want to backup and 'BCKP_NAME' is the name for backup output file. >> Default 'DEST_PATH' is placed in home directory, it can't be changed. >> 'BCKP_NAME' must be given; >> >> - to backup whole directory, type: >> 'backuper.py -d DIR_PATH BCKP_NAME [DEST_PATH]', where >> 'DIR_PATH' is exact path to prefered directory, which you want to >> backup and 'BCKP_NAME' is the name for backup output file. Default >> 'DEST_PATH' is placed in home directory, it can't be changed. >> 'BCKP_NAME' must be given; >> >> """ >> >> def __check_set_perm(self, rd_obj_path, backup_dest): >> >> try: >> >> if os.path.exists(rd_obj_path): >> if not os.access(rd_obj_path, os.R_OK): >> print "Have no permissions on [%s] for reading >> operation.\nTrying to set them..." % os.path.split(rd_obj_path)[1] >> if not os.path.isdir(rd_obj_path): >> os.chmod(rd_obj_path, stat.S_IREAD) >> else: >> for root, dirs, files in os.walk(rd_obj_path): >> for f in files: >> os.chmod(os.path.join(root, f), >> stat.S_IREAD) >> print "Get permissions for reading on [%s] >> successfully." % os.path.split(rd_obj_path)[1] >> else: >> print "Have permissions on [%s] for reading." % >> os.path.split(rd_obj_path)[1] >> >> if not os.access(backup_dest, os.W_OK): >> print "Have no permissions on [%s] for writing >> operation.\nTrying to set them..." % os.path.split(backup_dest)[1] >> os.chmod(backup_dest, stat.S_IWRITE) >> print "Get permissions for reading on [%s] >> successfully." % os.path.split(backup_dest)[1] >> else: >> print "Have permissions on [%s] for writing." % >> os.path.split(backup_dest)[1] >> else: >> return "Can't find specified path - [%s]." % rd_obj_path >> sys.exit(1) >> >> except (Except), ex: >> return ex >> >> >> def backup_file(self, rd_obj_path, bkp_obj_name): >> >> try: >> >> if os.name == "nt": >> rd_obj_path = rd_obj_path.replace('~/', '%s\\' % >> os.getenv('HOME')).replace('\\', '\\\\') >> backup_dest = self.__backup_dest >> print "Checking permissions for reading and writing..." >> self.__check_set_perm(rd_obj_path, backup_dest) >> backup_obj = tarfile.open("%s\\%s(%s).tar.bz2" % >> (backup_dest, bkp_obj_name, __current_time), 'w:bz2') >> >> else: >> rd_obj_path = rd_obj_path.replace('~/', '%s/' % >> os.getenv('HOME')) >> backup_dest = self.__backup_dest >> print "Checking permissions for reading and writing..." >> self.__check_set_perm(rd_obj_path, backup_dest) >> backup_obj = tarfile.open("%s/%s(%s).tar.bz2" % >> (backup_dest, bkp_obj_name, __current_time), 'w:bz2') >> >> print "Preparing for backup [%s]..." % >> os.path.split(rd_obj_path)[1] >> print "Starting backup..." >> read_obj = open(rd_obj_path, 'rb') >> print "Now adding [%s]..." % os.path.split(rd_obj_path)[1] >> backup_obj.add(read_obj.read()) >> read_obj.close(), backup_obj.close() >> print "Backup [%s] made successfully. :-)" % >> os.path.split(backup_dest)[1] >> >> except (Except), ex: >> return ex >> >> def backup_dir(self, rd_obj_path, bkp_obj_name): >> >> try: >> >> if os.name == "nt": >> rd_obj_path = rd_obj_path.replace('~/', '%s\\' % >> os.getenv('HOME')).replace('\\', '\\\\') >> backup_dest = self.__backup_dest >> print "Checking permissions for reading and writing..." >> self.__check_set_perm(rd_obj_path, backup_dest) >> backup_obj = tarfile.open("%s\\%s(%s).tar.bz2" % >> (backup_dest, bkp_obj_name, __current_time), 'w:bz2') >> >> else: >> rd_obj_path = rd_obj_path.replace('~/', '%s/' % >> os.getenv('HOME')) >> backup_dest = self.__backup_dest >> print "Checking permissions for reading and writing..." >> self.__check_set_perm(rd_obj_path, backup_dest) >> backup_obj = tarfile.open("%s/%s(%s).tar.bz2" % >> (backup_dest, bkp_obj_name, __current_time), 'w:bz2') >> >> print "Preparing for backup '%s'..." % >> os.path.split(rd_obj_path)[1] >> print "Gathering files for backup..." >> path_list = [] >> for root, dirs, files in os.walk(rd_obj_path): >> for f in files: >> path_list.append(os.path.join(root, f)) >> print "Starting backup..." >> for p in path_list: >> fl = open(p, 'rb') >> print "Now adding [%s] from [%s] directory" % >> (os.path.split(p)[1], os.path.split(p)[0]) >> backup_obj.add(fl.read()) >> fl.close() >> print "Added [%s] successfully" % os.path.split(p)[1] >> backup_obj.close() >> print "Backup [%s] made successfully. :-)" % >> os.path.split(backup_dest)[1] >> >> except (Except), ex: >> return ex >> >> >> class ParseIt(object): >> >> def __init__(self): >> self.__initial = True >> >> _usage = "usage: %prog [options] Arg1 Arg2" >> parser = OptionParser(_usage) >> parser.add_option("-f", "--file", action="store", type="string", >> dest="filename", help="Make backup of a single file", >> metavar="FILE_PATH CKP_NAME", nargs=2) >> parser.add_option("-d", "--dir", action="store", type="string", >> dest="dirname", help="Recursively backup a whole directory", >> metavar="DIR_PATH BCKP_NAME", nargs=2) >> parser.add_option("-i", "--info", dest="info_note", >> action="store_true", help="Show script's documentation") >> >> (options, args) = parser.parse_args() >> >> def main_meth(): >> paq = Packer() >> pars = ParseIt() >> if pars.options.filename: >> paq.backup_file(pars.options.filename[0], >> pars.options.filename[1]) >> elif pars.options.dirname: >> paq.backup_dir(pars.options.dirname[0], pars.options.dirname[1]) >> elif pars.options.info_note: >> paq.doc_note() >> >> >> if __name__ == "__main__": >> main_meth() >> >> " >> >> >> >>
>> > I don't know why you didn't immediately add a print statement just > before the failing os.access(), once you saw the error message. You > could have printed out both the formal parameter and the instance > attribute. > > Simple explanation: you probably don't have an environment variable > named "HOME". I don't either, on Windows. You need to test for that, > and put some error handling, so the lack of an environment variable > won't crash your program. > > > Then backup_dest is a reference to the variable self.__backup_dest. > But that second reference seems to be recognised as a NoneType ?? > > backup_dest is a local variable which is a reference to whatever > object self.__backup_dest referenced. That could be a very different > thing. But in this case the subtlety isn't important -- they're both > referencing None, which is the object returned by os.getenv() when the > requested environment variable doesn't exist. > > DaveA Yes, You have right Dave. This reference don't exist in windows's cmd.exe, but in IDLE does. Check this out: " Microsoft Windows XP [Wersja 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\Adrian-Admin>python ActivePython 2.6.2.2 (ActiveState Software Inc.) based on Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.getenv('HOME') >>> print os.getenv('HOME') None >>> " And now output from IDLE: " Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [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.4 >>> import os >>> os.getenv('HOME') 'C:\\Documents and Settings\\Adrian-Admin' >>> " WTF?? Why on IDLE it works, but when i run this script in cmd.exe, the os.getenv('HOME') goes NoneType? I'm to newbie yet to understand this :/ That's the example with Traceback: " C:\Documents and Settings\Adrian-Admin\Moje dokumenty\My Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python backuper.py -f E:\ISO\archlinux-2009.02-core-i686.img ArchLinBackup Checking permissions for reading and writing... Have permissions on [archlinux-2009.02-core-i686.img] for reading. Traceback (most recent call last): File "backuper.py", line 200, in main_meth() File "backuper.py", line 190, in main_meth paq.backup_file(pars.options.filename[0], pars.options.filename[1]) File "backuper.py", line 111, in backup_file self.__check_set_perm(rd_obj_path, self._backup_dest) File "backuper.py", line 90, in __check_set_perm if not os.access(self._backup_dest, os.W_OK): TypeError: coercing to Unicode: need string or buffer, NoneType found C:\Documents and Settings\Adrian-Admin\Moje dokumenty\My Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty> " So....it's cmd.exe fault? From sajmikins at gmail.com Sat Aug 22 15:27:52 2009 From: sajmikins at gmail.com (Simon Forman) Date: Sat, 22 Aug 2009 15:27:52 -0400 Subject: Urllib2 not working In-Reply-To: <51303220908221112w79ccb746i900c22d45fff07c7@mail.gmail.com> References: <51303220908221112w79ccb746i900c22d45fff07c7@mail.gmail.com> Message-ID: <50f98a4c0908221227k4cfe3387t205c91ba20d5e514@mail.gmail.com> On Sat, Aug 22, 2009 at 2:12 PM, Carlos Fabian Ramirez wrote: > Hello, > When I try to open a URL using urllib2.urlopen it returns Name or service > not known. It is not a problem with my Internet I believe, since I have > Internet access on my computer, and I have verified it is not a syntax, or > spelling, error on my part. I have also tried accessing the site > (google.com) by IP like so: > urllib2.urlopen('http://74.125.67.100/') > but this does not work either. > This is a traceback of an attempt to access it through its URL > (http://www.google.com/) > http://dpaste.com/84016/ > Any help would be very appreciated. > Try googling the error message "Name or service not known" and urllib2. HTH From apt.shansen at gmail.com Sat Aug 22 15:30:16 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sat, 22 Aug 2009 12:30:16 -0700 Subject: TypeError while checking for permissions with os.access() on windows xp In-Reply-To: <4A9043FB.7070108@gmail.com> References: <4A9043FB.7070108@gmail.com> Message-ID: <7a9c25c20908221230p673bffdane36b67482ab4621f@mail.gmail.com> > > > WTF?? > Why on IDLE it works, but when i run this script in cmd.exe, the > os.getenv('HOME') goes NoneType? > I'm to newbie yet to understand this :/ > HOME is simply not a standard environment variable that Windows provides. Any program can set/add environment variables as it deems fit; in this case it seems IDLE is setting one, but you can't rely on it outside of IDLE. If you do os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] it may be what you want. Start up cmd.exe, type 'set' -- that's the default/standard environment variables you have to work with. That's it. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From jurajg at gmail.com Sat Aug 22 15:49:52 2009 From: jurajg at gmail.com (Juraj G.) Date: Sat, 22 Aug 2009 21:49:52 +0200 Subject: difference between raw_input() and input() In-Reply-To: <029d53bb$0$25987$c3e8da3@news.astraweb.com> References: <3c91915d-bcb1-4ea9-9b37-6b30ea0588a0@e34g2000vbm.googlegroups.com> <029d53bb$0$25987$c3e8da3@news.astraweb.com> Message-ID: <3cdfc0a80908221249t7b7042b8reab3b0202ef3b2a3@mail.gmail.com> if you prefix number with zero, it will turn into octal number... I too wasn't aware of it... at least in python :/ http://en.wikipedia.org/wiki/Octal It seems like bad practice to put zeroes before any decimal number in any language :) Juraj From python.list at tim.thechases.com Sat Aug 22 15:49:55 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 22 Aug 2009 14:49:55 -0500 Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? In-Reply-To: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> Message-ID: <4A904BE3.6030507@tim.thechases.com> bolega wrote: > sed/awk/perl: Better to post in the "sed" or "perl" mailing lists rather than a Python list. I saw an awk solution flew by. > How to replace all spaces each with an underscore that occur > before a specific string ? > > I really prefer a sed one liner. Here's a one-liner sed solution: sed '/to /{s//\n&/;h;s/.*\n//;x;s/\n.*//;s/ /_/g;G;s/\n//}' There's a reason I prefer Python for these sorts of things: readability! You win 5 free internets (as a stand-in for the "real life" you clearly don't have) if you can decipher that in under 20 seconds ;-) expecting-to-see-NO CARRIER-after-typing-that'ly yers, -tkc +++ATH0 From zuo at chopin.edu.pl Sat Aug 22 16:11:20 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 22 Aug 2009 22:11:20 +0200 Subject: Using 'apply' as a decorator, to define constants In-Reply-To: References: Message-ID: 21-08-2009 o 18:09:02 alex23 wrote: > Unfortunately, apply() has been removed as a built-in in 3.x. You can always implement it yourself :) def apply(function, args=(), keywords={}): return function(*args, **keywords) -- Jan Kaliszewski (zuo) From subhakolkata1234 at gmail.com Sat Aug 22 16:27:02 2009 From: subhakolkata1234 at gmail.com (SUBHABRATA BANERJEE) Date: Sun, 23 Aug 2009 01:57:02 +0530 Subject: Questions on XML In-Reply-To: References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Message-ID: <97c638a50908221327ge57818ahc1bb4c9ad3eb186b@mail.gmail.com> Should I help you? If you answered my questions I am differing from your view I do not get any problem in processing Hindi or Bangla or any Indian language in Python it is perfectly fine. Best Regards, Subhabrata. On Sat, Aug 22, 2009 at 9:48 AM, Rami Chowdhury wrote: > > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I >> use Python to help me in this regard? >> > > I can say from experience that Python on Windows (at least, Python 2.5 on > 32-bit Vista) works perfectly well with UTF-8 files containing Bangla. I > have had trouble with working with the data in IDLE, however, which seems to > prefer ASCII by default. > > ------------- > Rami Chowdhury > "Never assume malice when stupidity will suffice." -- Hanlon's Razor > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > > > > > > On Aug 21, 2009, at 19:15 , joy99 wrote: > > Dear Group, >> >> I like to convert some simple strings of natural language to XML. May >> I use Python to do this? If any one can help me, on this. >> >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I >> use Python to help me in this regard? >> >> How can I learn good XML aspects of Python. If any one can kindly name >> me a book or URL. >> >> I am using Python2.6 on Windows XP with IDLE as GUI. >> >> Best Regards, >> Subhabrata. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at cs.uu.nl Sat Aug 22 16:43:13 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 22 Aug 2009 22:43:13 +0200 Subject: string literal vs string variable References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8fc954$0$31331$9b4e6d93@newsspool4.arcor-online.net> Message-ID: >>>>> Kee Nethery (KN) wrote: >KN> On Aug 22, 2009, at 3:32 AM, Stefan Behnel wrote: >>> >>> You can use both, but I suspect parsing from StringIO to be slower than >>> parsing from the string directly. That's the case for lxml, at least. >>> >>> Note that fromstring() behaves the same as XML(), but it reads better >>> when >>> parsing from a string variable. XML() reads better when parsing from a >>> literal string. >KN> I'm not sure I know the difference between a string variable and a literal >KN> string. Is the difference as simple as: >KN> somestring = u'hello world' >KN> fromstring(somestring) <-- string variable >KN> vs >KN> XML(u'hello world') <-- literal string Yes. Stefan probably means `looks better for the human reader' when he says `reads better'. XML and fromstring are just different names for the same function. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From zuo at chopin.edu.pl Sat Aug 22 16:44:35 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 22 Aug 2009 22:44:35 +0200 Subject: Annoying octal notation In-Reply-To: <20090822190417.GW20434@dragontoe.org> References: <87d46ok948.fsf@benfinney.id.au> <20090822190417.GW20434@dragontoe.org> Message-ID: 22-08-2009 o 21:04:17 Derek Martin wrote: > On Sat, Aug 22, 2009 at 10:03:35AM +1000, Ben Finney wrote: >> These human programmers, whether newbies or long-experienced, also deal >> with decimal numbers every day, many of which are presented as a >> sequence of digits with leading zeros ? and we continue to think of them >> as decimal numbers regardless. Having the language syntax opposed to >> that is > ...consistent with virtually every other popular programming language. Probably not every other... Anyway -- being (as it was said) inconsistent with every-day-convention -- it'd be also inconsistent with *Python* conventions, i.e.: 0x <- hex prefix 0b <- bin prefix Cheers, *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Sat Aug 22 16:51:44 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 22 Aug 2009 22:51:44 +0200 Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? In-Reply-To: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> Message-ID: 22-08-2009 o 20:11:32 bolega wrote: > sed/awk/perl: > > How to replace all spaces each with an underscore that occur before a > specific string ? $ rm -rf /home/bolega ; python -c 'for i in xrange(1000): print "I will never crosspost senselessly."' ;~] -- Jan Kaliszewski (zuo) From subhakolkata1234 at gmail.com Sat Aug 22 16:53:16 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Sat, 22 Aug 2009 13:53:16 -0700 (PDT) Subject: Questions on XML References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <11b8af5c-de10-4583-979c-64109c8fe698@g1g2000pra.googlegroups.com> On Aug 22, 12:16?pm, Rami Chowdhury wrote: > > encoding declaration to the top of your source file if you use encoded > > literal strings in your code > > Any tips for how to set the encoding in IDLE? printing the Unicode ? > strings works -- trying to repr() the variable chokes with a ? > UnicodeDecodeError, and trying to enter the literals inside IDLE just ? > gets me '?' characters instead. > > (this is Python 2.5 + IDLE installed from the Python-2.5.msi on ? > python.org) > > ------------- > Rami Chowdhury > "Never assume malice when stupidity will suffice." -- Hanlon's Razor > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > > On Aug 21, 2009, at 22:53 , Stefan Behnel wrote: > > > > > Rami Chowdhury wrote: > >>> I am using primarily UTF-8 based strings, like Hindi or Bengali. ? > >>> Can I > >>> use Python to help me in this regard? > > >> I can say from experience that Python on Windows (at least, Python ? > >> 2.5 > >> on 32-bit Vista) works perfectly well with UTF-8 files containing > >> Bangla. I have had trouble with working with the data in IDLE, ? > >> however, > >> which seems to prefer ASCII by default. > > > Defaults almost never work for encodings. You have to be explicit: ? > > add an > > encoding declaration to the top of your source file if you use encoded > > literal strings in your code; use the codecs module with a suitable > > encoding to read encoded text files, and use an XML parser when ? > > reading XML. > > > Stefan > > -- > >http://mail.python.org/mailman/listinfo/python-list- Hide quoted text - > > - Show quoted text - Dear Sir, There is no big issue for this. I simply downloaded Python2.5 and using IDLE on Windows XP with service pack 2. I used Python 2.5 earlier and presently using Python 2.6 and it is also perfectly fine. I am not using it for small programs but machine learning programs, where code itself runs few million lines over some terabytes of Hindi and Bengali data, and I never found any problem. What is the exact nature of problem you are getting? If you can kindly specify. If possible, with some sample codes. And printing is also never been a problem, all good printers like HP,Epson,Xerox,Canon are printing Hindi or Bengali data finely. If you can kindly specify the problem. Best Regards, Subhabrata. From zuo at chopin.edu.pl Sat Aug 22 17:06:57 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 22 Aug 2009 23:06:57 +0200 Subject: string literal vs string variable In-Reply-To: References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8fc954$0$31331$9b4e6d93@newsspool4.arcor-online.net> Message-ID: 22-08-2009 o 19:46:51 Kee Nethery wrote: > I'm not sure I know the difference between a string variable and a > literal string. Is the difference as simple as: > > somestring = u'hello world' > fromstring(somestring) <-- string variable > vs > XML(u'hello world') <-- literal string Yes, simply: s = 'hello world' # ^ # it is a *string literal* s # <- it is a *string object* # (or rather a name referring to it :-)) (In Python we have rather 'names' than 'variables', though -- as a mental leap -- they are commonly referred to as 'variables', regarding other languages' terminology). Cheers, *j -- Jan Kaliszewski (zuo) From fuzzyman at gmail.com Sat Aug 22 17:25:08 2009 From: fuzzyman at gmail.com (Fuzzyman) Date: Sat, 22 Aug 2009 14:25:08 -0700 (PDT) Subject: ANN: mock 0.6.0, Python mocking and testing library Message-ID: <5a8c8a3a-8bf0-40ad-bf21-89b6fc6a3c9f@z31g2000yqd.googlegroups.com> mock is a Python mock object library for testing, with additional support for runtime monkey patching. Most mocking libraries follow the ?record -> replay? pattern of mocking. I prefer the ?action -> assertion? pattern, which is more readable and intuitive; particularly when working with the Python unittest module. This release, version 0.6.0, is a minor release but with a few new features: * mock homepage http://www.voidspace.org.uk/python/mock/ * download http://www.voidspace.org.uk/downloads/mock-0.6.0.zip * PDF documentation http://www.voidspace.org.uk/downloads/mock.pdf * Google code project and SVN repository http://code.google.com/p/mock/ New in 0.6.0: * New test layout compatible with test discovery * Descriptors (static methods / class methods etc) can now be patched and restored correctly * Mocks can raise exceptions when called by setting side_effect to an exception class or instance * Mocks that wrap objects will not pass on calls to the underlying object if an explicit return_value is set From countryone77 at yahoo.com Sat Aug 22 17:26:16 2009 From: countryone77 at yahoo.com (Bev in TX) Date: Sat, 22 Aug 2009 14:26:16 -0700 (PDT) Subject: logging SMTPhandler Error References: Message-ID: On Aug 21, 8:34?am, Bev in TX wrote: > Hi, > > I've done some Python programming, but I still consider myself a > Python newbie. ?I have a Mac Pro OS X 10.5.8 system and I installed > Python 2.6.2 (the latest package available for the Mac) yesterday. > > I was working through Matt Wilson's article on using the logging > module:http://blog.tplus1.com/index.php/2007/09/28/the-python-logging-module... > (If that does not work, then try:http://tinyurl.com/5v2lcy) > > Everything worked great until his last example. ?My ISP does not > provide e-mail, so I tried using gmail in the line that sets h2. ?I > substituted "mailid" for my actual e-mail address in the following > examples; in my test I used my actual e-mail ID. ?Also, I used the > full path to the newly installed Python 2.6.2; otherwise it picked up > the older Python 2.5: > #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python > > First attempt: > h2 = logging.handlers.SMTPHandler('smtp.gmail.com', 'mai... at gmail.com', > ['mai... at gmail.com'],'ERROR log') > However, that caused the following error to be issued: > > Traceback (most recent call last): > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/logging/handlers.py", line 868, in emit > ? ? smtp.sendmail(self.fromaddr, self.toaddrs, msg) > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/smtplib.py", line 698, in sendmail > ? ? raise SMTPSenderRefused(code, resp, from_addr) > SMTPSenderRefused: (530, '5.7.0 Must issue a STARTTLS command first. > 7sm3867994qwf.47', 'mai... at gmail.com') > > I also tried providing my gmail userid/password, I tried adding a 5th, > credential, argument, which is a tupple, (username,password) (new in > 2.6). > > Second attempt: > h2 = logging.handlers.SMTPHandler('smtp.gmail.com', 'mai... at gmail.com', > ['mai... at gmail.com'],'ERROR log',('mai... at gmail.com','gmail- > password')) > However, that caused the following error message: > > Traceback (most recent call last): > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/logging/handlers.py", line 867, in emit > ? ? smtp.login(self.username, self.password) > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/smtplib.py", line 552, in login > ? ? raise SMTPException("SMTP AUTH extension not supported by > server.") > SMTPException: SMTP AUTH extension not supported by server. > > I am able access gmail via Mac's Mail, in which it says that outgoing > mail is going to: > ? ? ? smtp.gmail.com:mailid > I tried using that as the server in the Python script, but it could > not find that server. > > Is this possible? ?If I am doing something incorrectly, would someone > please indicate what it is? > > Thanks, > Bev in TX Today I tried this with both Python 2.6.2 and 3.1.1 on an XP system, with the same error. For the 3.1.1 test, I had to change the syntax of the exception from "except exc, var" to "except exc as var". Here is the modified script, with my email ID changed to "mailid": import logging import logging.handlers #Make a global logging object x = logging.getLogger("logfun") x.setLevel(logging.DEBUG) #This handler writes out everything to stdout h1 = logging.StreamHandler() f = logging.Formatter("%(levelname)s %(asctime)s %(funcName)s %(lineno) d %(message)s") h1.setFormatter(f) h1.setLevel(logging.DEBUG) x.addHandler(h1) #This handler emails me anything that is an error or worse h2 = logging.handlers.SMTPHandler('smtp.gmail.com', 'mailid at gmail.com', ['mailid at gmail.com'],'ERROR log') f = logging.Formatter("%(levelname)s %(asctime)s %(funcName)s %(lineno) d %(message)s") h2.setLevel(logging.ERROR) h2.setFormatter(f) x.addHandler(h2) def g(): 1 / 0 def f(): logfun = logging.getLogger("logfun") logfun.debug("inside f!") try: g() except Exception as ex: logfun.exception("Something awful happened!") logfun.debug("Finishing f!") if __name__ == "__main__": f() Thanks, Bev in TX From ryniek90 at gmail.com Sat Aug 22 17:37:22 2009 From: ryniek90 at gmail.com (ryniek90) Date: Sat, 22 Aug 2009 23:37:22 +0200 Subject: TypeError while checking for permissions with os.access() on windows xp In-Reply-To: References: Message-ID: <4A906512.1060606@gmail.com> > > > > WTF?? > Why on IDLE it works, but when i run this script in cmd.exe, the > os.getenv('HOME') goes NoneType? > I'm to newbie yet to understand this :/ > > > HOME is simply not a standard environment variable that Windows > provides. Any program can set/add environment variables as it deems > fit; in this case it seems IDLE is setting one, but you can't rely on > it outside of IDLE. > > If you do os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] it may be > what you want. > > Start up cmd.exe, type 'set' -- that's the default/standard > environment variables you have to work with. That's it. > > --S Yep, now that variable works fine. Thanks. From james.harris.1 at googlemail.com Sat Aug 22 17:54:41 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Sat, 22 Aug 2009 14:54:41 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: On 22 Aug, 10:27, David <71da... at libero.it> wrote: ... (snipped a discussion on languages and other systems interpreting numbers with a leading zero as octal) > > Either hexadecimal should have been 0h or octal should > > have been 0t :=) > > > I have seen the use of Q/q instead in order to make it clearer. I still > prefer Smalltalk's 16rFF and 8r377. > > > Two interesting options. In a project I have on I have also considered > using 0q as indicating octal. I maybe saw it used once somewhere else > but I have no idea where. 0t was a second choice and 0c third choice > (the other letters of oct). 0o should NOT be used for obvious reasons. > > So you are saying that Smalltalk has r where > r is presumably for radix? That's maybe best of all. It preserves the > syntactic requirement of starting a number with a digit and seems to > have greatest flexibility. Not sure how good it looks but it's > certainly not bad. > > > > ? 0xff & 0x0e | 0b1101 > > ? 16rff & 16r0e | 2r1101 > > > Hmm. Maybe a symbol would be better than a letter. ... > > Or Ada's 16#FF#, 8#377#... > > I forget if DEC/VMS FORTRAN or Xerox Sigma FORTRAN used x'FF' or > > 'FF'x, and o'377' or '377'o ... > > What about 2_1011, 8_7621, 16_c26h or 2;1011, 8;7621, 16;c26h ? They look good - which is important. The trouble (for me) is that I want the notation for a new programming language and already use these characters. I have underscore as an optional separator for groups of digits - 123000 and 123_000 mean the same. The semicolon terminates a statement. Based on your second idea, though, maybe a colon could be used instead as in 2:1011, 8:7621, 16:c26b I don't (yet) use it as a range operator. I could also use a hash sign as although I allow hash to begin comments it cannot be preceded by anything other than whitespace so these would be usable 2#1011, 8#7621, 16#c26b I have no idea why Ada which uses the # also apparently uses it to end a number 2#1011#, 8#7621#, 16#c26b# Copying this post also to comp.lang.misc. Folks there may either be interested in the discussion or have comments to add. James From kkumerNOTTHIS at thatfamoussearchenginesmail.com Sat Aug 22 18:49:22 2009 From: kkumerNOTTHIS at thatfamoussearchenginesmail.com (Kreso) Date: Sat, 22 Aug 2009 22:49:22 +0000 (UTC) Subject: Items inheriting attributes from its container? Message-ID: I would like to create a list-like container class so that, additionally to usual list methods, I could attach attributes to the container instances. However, I would like it so that the items contained in the particular instance of container somehow 'inherit' those attributes i.e. cont = Container() cont.color = 'blue' cont.append(item) print item.color 'blue' The example appended below does that, but with the restriction that container attributes must be set in the instantiation phase. This is actually fine for me at the moment because my objects are "read only", but I would like to hear about better solutions, with more flexibility, please. #-----8<---------------------------- class Player: """Class for items""" def __init__(self, playerdata, team): self.data = playerdata for key in team.__dict__: setattr(self, key, team.__dict__[key]) return class Team(list): """Class for containers""" def __init__(self, teamdata, playerdata): for key in teamdata: setattr(self, key, teamdata[key]) for item in playerdata: self.append(Player(item, self)) return lakersdata = {'name' : 'Lakers', 'kitcolor' : 'yellow'} lakersplayers = [['Kobe', 'PG', 12, 123], ['Kareem', 'FW', 23, 345]] lakers = Team(lakersdata, lakersplayers) # This is fine: p1 = lakers[1] print p1.kitcolor # However the following doesn't work: lakers.kitcolor = 'blue' print p1.kitcolor #-----8<---------------------------- From clp2 at rebertia.com Sat Aug 22 18:52:29 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 22 Aug 2009 15:52:29 -0700 Subject: line completion In-Reply-To: References: Message-ID: <50697b2c0908221552k3a44156ek509a35ad0764dd2b@mail.gmail.com> On Thu, Aug 20, 2009 at 9:06 AM, Steven Woody wrote: > Hi, > I wrote a program that takes some user input. ?Many inputs are quit often > used by user, so when a user launch the program, and type in "The Sha", ?he > wants to get "wshank Redemption" displayed automatically in reversed color > (black text on white background) along his cursor. ?When he decided to use > "The Shawshank Redemption", he just press the enter key, otherwise, he type > in other words anyway. > My question is, is there any module that can easy the implementation of this > feature? ?Thanks. The `readline` module in the standard library: http://docs.python.org/library/readline.html Although I don't know how to get it to colorize the interface. Cheers, Chris -- http://blog.rebertia.com From mortonspam at gmail.com Sat Aug 22 19:02:27 2009 From: mortonspam at gmail.com (Ed Morton) Date: Sat, 22 Aug 2009 16:02:27 -0700 (PDT) Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> Message-ID: On Aug 22, 1:11?pm, bolega wrote: > sed/awk/perl: > > How to replace all spaces each with an underscore that occur before a > specific string ? > > I really prefer a sed one liner. Why? > Example > Input : ?This is my book. It is too ?thick to read. The author gets > little royalty but the publisher makes a lot. > Output: This_is_my_book._It_is_too__thick_to read. The author gets > little royalty but the publisher makes a lot. > > We replaced all the spaces with underscores before the first occurence > of the string "to ". No, you replaced all ... the string "to " (note the space). awk '{idx=index($0,"to "); tgt=substr($0,1,idx-1); gsub(/ /,"_",tgt); print tgt substr($0,idx)}' file Ed. From lists at cheimes.de Sat Aug 22 19:14:03 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 23 Aug 2009 01:14:03 +0200 Subject: Items inheriting attributes from its container? In-Reply-To: References: Message-ID: Kreso schrieb: > I would like to create a list-like container class so that, additionally > to usual list methods, I could attach attributes to the container instances. > However, I would like it so that the items contained in the particular > instance of container somehow 'inherit' those attributes i.e. The Python web application framework Zope implements the feature under the name "acquisition". Happy Googling! Christian From mwilson at the-wire.com Sat Aug 22 19:16:39 2009 From: mwilson at the-wire.com (Mel) Date: Sat, 22 Aug 2009 19:16:39 -0400 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: James Harris wrote: > I have no idea why Ada which uses the # also apparently uses it to end > a number > > 2#1011#, 8#7621#, 16#c26b# Interesting. They do it because of this example from : 2#1#E8 -- an integer literal of value 256 where the E prefixes a power-of-2 exponent, and can't be taken as a digit of the radix. That is to say 16#1#E2 would also equal 256, since it's 1*16**2 . Mel. From pavlovevidence at gmail.com Sat Aug 22 19:45:20 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 22 Aug 2009 16:45:20 -0700 (PDT) Subject: Annoying octal notation References: <87d46ok948.fsf@benfinney.id.au> Message-ID: On Aug 22, 12:04?pm, Derek Martin wrote: > On Sat, Aug 22, 2009 at 10:03:35AM +1000, Ben Finney wrote: > > These human programmers, whether newbies or long-experienced, also deal > > with decimal numbers every day, many of which are presented as a > > sequence of digits with leading zeros ? and we continue to think of them > > as decimal numbers regardless. Having the language syntax opposed to > > that is > > ...consistent with virtually every other popular programming language. If you know anything about Python, you should know that "consistent with virtually every other programming langauge" is, at most, a polite suggestion for how Python should do it. Carl Banks From somebody at somewhere.com Sat Aug 22 19:46:26 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Sun, 23 Aug 2009 00:46:26 +0100 Subject: Items inheriting attributes from its container? References: Message-ID: <_MSdnWJk2KnPHg3XnZ2dnUVZ8hmdnZ2d@giganews.com> Kreso wrote: > I would like to create a list-like container class so that, additionally > to usual list methods, I could attach attributes to the container > instances. However, I would like it so that the items contained in the > particular instance of container somehow 'inherit' those attributes i.e. > > cont = Container() > cont.color = 'blue' > cont.append(item) > print item.color > 'blue' > > The example appended below does that, but with the restriction that > container attributes must be set in the instantiation phase. This is > actually fine for me at the moment because my objects are "read only", but > I would like to hear about better solutions, with more flexibility, > please. > > > #-----8<---------------------------- > class Player: > """Class for items""" > > def __init__(self, playerdata, team): > self.data = playerdata > for key in team.__dict__: > setattr(self, key, team.__dict__[key]) > return > > > class Team(list): > """Class for containers""" > > def __init__(self, teamdata, playerdata): > for key in teamdata: > setattr(self, key, teamdata[key]) > for item in playerdata: > self.append(Player(item, self)) > return > > > lakersdata = {'name' : 'Lakers', 'kitcolor' : 'yellow'} > lakersplayers = [['Kobe', 'PG', 12, 123], ['Kareem', 'FW', 23, 345]] > > lakers = Team(lakersdata, lakersplayers) > > # This is fine: > p1 = lakers[1] > print p1.kitcolor > > # However the following doesn't work: > lakers.kitcolor = 'blue' > print p1.kitcolor > > #-----8<---------------------------- I hope this gives you some good ideas. http://en.wikipedia.org/wiki/Join_(SQL) I suspect you will be finding a use for the special __getattr__ method, which is called when an attribute is not found. This can be used to search on your set of joined objects. Your list of joined objects should be a set() to prevent duplicates. -- Stephen Fairchild From pavlovevidence at gmail.com Sat Aug 22 19:49:40 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 22 Aug 2009 16:49:40 -0700 (PDT) Subject: Annoying octal notation References: Message-ID: On Aug 21, 12:48?pm, Derek Martin wrote: > John Nagle wrote: > > Yes, and making lead zeros an error as suggested in PEP 3127 is a > > good idea. ?It will be interesting to see what bugs that flushes > > out. > James Harris wrote: > > It maybe made sense once but this relic of the past should have been > > consigned to the waste bin of history long ago. > > Sigh. ?Nonsense. ?I use octal notation *every day*, for two extremely > prevalent purposes: file creation umask, and Unix file permissions > (i.e. the chmod() function/command). Unix file permissions maybe made sense once but this relic of the past should have been consigned to the waste bin of history long ago. :) Carl Banks From nad at acm.org Sat Aug 22 20:07:29 2009 From: nad at acm.org (Ned Deily) Date: Sat, 22 Aug 2009 17:07:29 -0700 Subject: logging SMTPhandler Error References: Message-ID: In article , Bev in TX wrote: > On Aug 21, 8:34?am, Bev in TX wrote: > > Hi, > > > > I've done some Python programming, but I still consider myself a > > Python newbie. ?I have a Mac Pro OS X 10.5.8 system and I installed > > Python 2.6.2 (the latest package available for the Mac) yesterday. > > > > I was working through Matt Wilson's article on using the logging > > module:http://blog.tplus1.com/index.php/2007/09/28/the-python-logging-module > > ... > > (If that does not work, then try:http://tinyurl.com/5v2lcy) > > > > Everything worked great until his last example. ?My ISP does not > > provide e-mail, so I tried using gmail in the line that sets h2. ?I > > substituted "mailid" for my actual e-mail address in the following > > examples; in my test I used my actual e-mail ID. ?Also, I used the > > full path to the newly installed Python 2.6.2; otherwise it picked up > > the older Python 2.5: > > #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python > > > > First attempt: > > h2 = logging.handlers.SMTPHandler('smtp.gmail.com', 'mai... at gmail.com', > > ['mai... at gmail.com'],'ERROR log') > > However, that caused the following error to be issued: > > > > Traceback (most recent call last): > > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > > python2.6/logging/handlers.py", line 868, in emit > > ? ? smtp.sendmail(self.fromaddr, self.toaddrs, msg) > > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > > python2.6/smtplib.py", line 698, in sendmail > > ? ? raise SMTPSenderRefused(code, resp, from_addr) > > SMTPSenderRefused: (530, '5.7.0 Must issue a STARTTLS command first. > > 7sm3867994qwf.47', 'mai... at gmail.com') The problem here is that gmail, like most modern mail services, requires the use of an encrypted (SSL or TLS) connection for mail relaying so that the required user name and password are not sent in the clear. The logging SMTP handler uses the smtplib module from the standard module to send mail and, when built properly, smtplib does support TLS. However, the caller of smtplib does need to do some extra work in that case, i.e. it needs to call the server object's starttls method at the right point in the protocol handshaking. It's currently not done automatically in smtplib and, unfortunately, there is no code in the logging smtp handler to detect the need for and to call starttls (in response to a 250-STARTTLS response to an EHLO). To make this work, either the logging module or, perhaps better, the smptlib module needs to be smarter about this case. I didn't see an open issue on the Python bug tracker about this; you might want to open one. In the meantime, some options would be to find an SMTP mail host that doesn't require TLS. Or write a custom logger. Or on OS X it's not *too* difficult to set up a local host mailer using the Apple-supplied prefix that would accept mail locally and forward it to a more sophisticated remote mailer. -- Ned Deily, nad at acm.org From someone at example.com Sat Aug 22 20:14:29 2009 From: someone at example.com (John W. Krahn) Date: Sat, 22 Aug 2009 17:14:29 -0700 Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? In-Reply-To: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> Message-ID: bolega wrote: > sed/awk/perl: > > How to replace all spaces each with an underscore that occur before a > specific string ? > > I really prefer a sed one liner. > > Example > Input : This is my book. It is too thick to read. The author gets > little royalty but the publisher makes a lot. > Output: This_is_my_book._It_is_too__thick_to read. The author gets > little royalty but the publisher makes a lot. > > We replaced all the spaces with underscores before the first occurence > of the string "to ". $ perl -le' $x = "This is my book. It is too thick to read. The author gets little royalty but the publisher makes a lot."; print $x; $x =~ /to / && substr( $x, 0, $-[0] ) =~ tr/ /_/; print $x; ' This is my book. It is too thick to read. The author gets little royalty but the publisher makes a lot. This_is_my_book._It_is_too__thick_to read. The author gets little royalty but the publisher makes a lot. John -- Those people who think they know everything are a great annoyance to those of us who do. -- Isaac Asimov From python at mrabarnett.plus.com Sat Aug 22 20:45:18 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 23 Aug 2009 01:45:18 +0100 Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? In-Reply-To: References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> Message-ID: <4A90911E.3000402@mrabarnett.plus.com> John W. Krahn wrote: > bolega wrote: >> sed/awk/perl: >> >> How to replace all spaces each with an underscore that occur before a >> specific string ? >> >> I really prefer a sed one liner. >> >> Example >> Input : This is my book. It is too thick to read. The author gets >> little royalty but the publisher makes a lot. >> Output: This_is_my_book._It_is_too__thick_to read. The author gets >> little royalty but the publisher makes a lot. >> >> We replaced all the spaces with underscores before the first occurence >> of the string "to ". > > $ perl -le' > $x = "This is my book. It is too thick to read. The author gets little > royalty but the publisher makes a lot."; > print $x; > $x =~ /to / && substr( $x, 0, $-[0] ) =~ tr/ /_/; > print $x; > ' > This is my book. It is too thick to read. The author gets little > royalty but the publisher makes a lot. > This_is_my_book._It_is_too__thick_to read. The author gets little > royalty but the publisher makes a lot. > If you're interested in a Python regex solution: s = "This is my book. It is too thick to read. The author gets little royalty but the publisher makes a lot." s = re.sub(".*?(?=to )", lambda m: m.group().replace(" ", "_"), s) From countryone77 at yahoo.com Sat Aug 22 20:45:52 2009 From: countryone77 at yahoo.com (Bev in TX) Date: Sat, 22 Aug 2009 17:45:52 -0700 (PDT) Subject: logging SMTPhandler Error References: Message-ID: <87236fb1-c09f-46e8-8492-514ba000c74a@24g2000yqm.googlegroups.com> On Aug 22, 7:07?pm, Ned Deily wrote: > > The problem here is that gmail, like most modern mail services, requires > the use of an encrypted (SSL or TLS) connection for mail relaying so > that the required user name and password are not sent in the clear. ?The > logging SMTP handler uses the smtplib module from the standard module to > send mail and, when built properly, smtplib does support TLS. ?However, > the caller of smtplib does need to do some extra work in that case, i.e. > it needs to call the server object's starttls method at the right point > in the protocol handshaking. It's currently not done automatically in > smtplib and, unfortunately, there is no code in the logging smtp handler > to detect the need for and to call starttls (in response to a > 250-STARTTLS response to an EHLO). > > To make this work, either the logging module or, perhaps better, the > smptlib module needs to be smarter about this case. ?I didn't see an > open issue on the Python bug tracker about this; you might want to open > one. ?In the meantime, some options would be to find an SMTP mail host > that doesn't require TLS. ?Or write a custom logger. ?Or on OS X it's > not *too* difficult to set up a local host mailer using the > Apple-supplied prefix that would accept mail locally and forward it to a > more sophisticated remote mailer. > > -- > ?Ned Deily, > ?n... at acm.org- Hide quoted text - > > - Show quoted text - Thanks for the excellent and informative response :-). I'll investigate further, as you suggested, now that I understand what is happening. Bev in TX From zuo at chopin.edu.pl Sat Aug 22 20:56:08 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sun, 23 Aug 2009 02:56:08 +0200 Subject: Items inheriting attributes from its container? In-Reply-To: References: Message-ID: 23-08-2009 Kreso wrote: > I would like to create a list-like container class so that, additionally > to usual list methods, I could attach attributes to the container > instances. > However, I would like it so that the items contained in the particular > instance of container somehow 'inherit' those attributes i.e. > > cont = Container() > cont.color = 'blue' > cont.append(item) > print item.color > 'blue' [snip] > class Player: > """Class for items""" > > def __init__(self, playerdata, team): > self.data = playerdata > for key in team.__dict__: > setattr(self, key, team.__dict__[key]) > return > > > class Team(list): > """Class for containers""" > def __init__(self, teamdata, playerdata): > for key in teamdata: > setattr(self, key, teamdata[key]) > for item in playerdata: > self.append(Player(item, self)) > return > > lakersdata = {'name' : 'Lakers', 'kitcolor' : 'yellow'} > lakersplayers = [['Kobe', 'PG', 12, 123], ['Kareem', 'FW', 23, 345]] > > lakers = Team(lakersdata, lakersplayers) [snip] > p1 = lakers[1] > print p1.kitcolor [snip] > lakers.kitcolor = 'blue' > print p1.kitcolor [Not tested. I believe that the idea is clear] class RecruitmentError(ValueError): """Raised when a player cannot be recruited.""" class Player(object): """A potential item of a Team() instance.""" def __init__(self, playerdata, team=None): self.data = playerdata self.team = None if team: team.append(self) # (called when the usual attribute lookup didn't succeed) def __getattr__(self, name): return getattr(self.team, name) # ^ the last method may not be necessary -- you can always # access to team data via 'team' attribute # (and 'explicit is better than implicit') class Team(list): """A container for Player() instances.""" def __init__(self, teamdata, playerdata=None): for key in teamdata: setattr(self, key, teamdata[key]) for data in playerdata: self.append(Player(data)) def _validate_and_get(self, index=None, player=None): if player is not None and not isinstance(player, Player): raise TypeError('A Player instance is required') if index is not None: if isinstance(index, slice): raise TypeError('Slicing is not allowed') return self[index] # (raise IndexError for bad index) _validate = _validate_and_get def _recruit(self, player): if player.team is None: player.team = self else: raise RecruitmentError('Player %s has already recruited') def _dismiss(self, player): player.team = None def __setitem__(self, index, player): current = self._validate_and_get(index, player) if player is not current: self._recruit(player) self._dismiss(current) list.__setitem__(self, index, player) def __delitem__(self, index): player = self._validate_and_get(index) self._dismiss(player) list.__delitem__(self, index) def append(self, player): self._validate(player=player) self._recruit(player) list.append(self, player) # and similarly: # * def extend... # * def insert... # * def pop... # * def remove... ...if you really need ordered container (reflecting functions/hierarchy of players in a team?). Otherwise, as Stephen noted, you should subclass set rather than list. Cheers, *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Sat Aug 22 21:08:37 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sun, 23 Aug 2009 03:08:37 +0200 Subject: Items inheriting attributes from its container? In-Reply-To: References: Message-ID: PS. Erratum: > class Team(list): > """A container for Player() instances.""" > > def __init__(self, teamdata, playerdata=None): *** Here should be added: list.__init__(self) *** > for key in teamdata: > setattr(self, key, teamdata[key]) > for data in playerdata: > self.append(Player(data)) -- Jan Kaliszewski (zuo) From ben+python at benfinney.id.au Sat Aug 22 21:27:25 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 23 Aug 2009 11:27:25 +1000 Subject: your favorite debugging tool? References: Message-ID: <87vdkfiaki.fsf@benfinney.id.au> Esmail writes: > What is your favorite tool to help you debug your code? A ?print? statement (or equivalent, like logging output). > I've been getting along with 'print' statements but that is getting > old and somewhat cumbersome. Whenever a simple output statement is too cumbersome for debugging, I take it as a sign that the program is too cumbersome to follow. My debugging questions at that point are best taken to the unit test suite: record the questions and the expected answers, so that in the future anyone can get the benefit of them in a repeatable and automated fashion. -- \ ?The power of accurate observation is frequently called | `\ cynicism by those who don't have it.? ?George Bernard Shaw | _o__) | Ben Finney From nad at acm.org Sat Aug 22 22:05:51 2009 From: nad at acm.org (Ned Deily) Date: Sat, 22 Aug 2009 19:05:51 -0700 Subject: logging SMTPhandler Error References: <87236fb1-c09f-46e8-8492-514ba000c74a@24g2000yqm.googlegroups.com> Message-ID: In article <87236fb1-c09f-46e8-8492-514ba000c74a at 24g2000yqm.googlegroups.com>, Bev in TX wrote: > On Aug 22, 7:07?pm, Ned Deily wrote: > > [...] Or on OS X it's > > not *too* difficult to set up a local host mailer using the > > Apple-supplied prefix that would accept mail locally and forward it to a > > more sophisticated remote mailer. Um, notation fail: s/prefix/Postfix/ -- Ned Deily, nad at acm.org From code at pizzashack.org Sat Aug 22 23:19:01 2009 From: code at pizzashack.org (Derek Martin) Date: Sat, 22 Aug 2009 22:19:01 -0500 Subject: Annoying octal notation In-Reply-To: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> Message-ID: <20090823031901.GX20434@dragontoe.org> On Sat, Aug 22, 2009 at 02:55:51AM +0000, Steven D'Aprano wrote: > > I can see how 012 can > > be confusing to new programmers, but at least it's legible, and the > > great thing about humans is that they can be taught (usually). > > And the great thing is that now you get to teach yourself to stop writing > octal numbers implicitly and be write them explicitly with a leading 0o > instead :) Sorry, I don't write them implicitly. A leading zero explicitly states that the numeric constant that follows is octal. It is so in 6 out of 7 computer languages I have more than a passing familiarity with (the 7th being scheme, which is a thing unto itself), including Python. It's that way on Bourne-compatible and POSIX-compatible Unix shells (though it requires a leading backslash before the leading zero there). I'm quite certain it can not be the case on only those 6 languages that I happen to be familiar with... While it may be true that people commonly write decimal numbers with leading zeros (I dispute even this, having to my recollection only recently seen it as part of some serial number, which in practice is really more of a string identifier than a number, often containing characters other than numbers), it's also true that in the context of computer programming languages, for the last 40+ years, a number represented with a leading zero is most often an octal number. This has been true even in Python for nearly *twenty years*. Why the sudden need to change it? So no, I don't get to teach myself to stop writing octal numbers with a leading zero. Instead, I have to remember an exception to the rule. Also I don't think it's exactly uncommon for computer languages to do things differently than they are done in non-CS circles. A couple of easy examples: we do not write x+=y except in computer languages. The POSIX system call to create a file is called creat(). If you think about it, I'm sure you can come up with lots of examples where even Python takes liberties. Is this a bad thing? Not inherently, no. Will it be confusing to people who aren't familiar with the usage? Quite possibly, but that is not inherently bad either. It's all about context. > Use of octal isn't common. It's common enough. Peruse the include files for your C libraries, or the source for your operating system's kernel, or system libraries, and I bet you'll find plenty of octal. I did. [Note that it is irrelevant that these are C/C++ files; here we are only concerned with whether they use octal, not how it is represented therein.] I'd guess there's a fair chance that any math or scientific software package uses octal. Octal is a convenient way to represent bit fields that naturally occur in groups of 3, of which there are potentially limitless cases. > You've given two cases were octal notation is useful, but for every > coder who frequently writes umasks on Unix systems, there are a > thousand who don't. I gave two cases that I use *daily*, or very nearly daily. My hats currently include system admin, SQA, and software development, and I find it convenient to use octal in each of those. But those are hardly the only places where octal is useful. Have a look at the ncurses library, for example. Given that Python has an ncurses interface, I'm guessing it's used there too. In fact if the Python source had no octal in it, I would find that very surprising. > It's no hardship to write 0o12 instead of 012. Computer languages are not write-only, excepting maybe Perl. ;-) Writing 0o12 presents no hardship; but I assert, with at least some support from others here, that *reading* it does. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From code at pizzashack.org Sat Aug 22 23:32:03 2009 From: code at pizzashack.org (Derek Martin) Date: Sat, 22 Aug 2009 22:32:03 -0500 Subject: Annoying octal notation In-Reply-To: References: Message-ID: <20090823033203.GY20434@dragontoe.org> On Fri, Aug 21, 2009 at 04:23:57PM -0700, James Harris wrote: > You misunderstand. I was saying that taking a leading zero as > indicating octal is archaic. Octal itself is fine where appropriate. I don't see that the leading zero is any more archaic than the use of octal itself... Both originate from around the same time period, and are used in the same cases. We should just prohibit octal entirely then. But I suppose it depends on which definition of "archaic" you use. In the other common sense of the word, the leading zero is no more archaic than the C programming language. Let's ban the use of all three. :) (I believe C is still the language in which the largest number of lines of new code are written, but if not, it's way up there.) > The chmod command doesn't require a leading zero. No, but it doesn't need any indicator that the number given to it is in octal; in the case of the command line tool, octal is *required*, and the argument is *text*. However, the chmod() system call, and the interfaces to it in every language I'm familiar with that has one, do require the leading zero (because that's how you represent octal). Including Python, for some 20 years or so. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From cri at tiac.net Sat Aug 22 23:38:59 2009 From: cri at tiac.net (Richard Harter) Date: Sun, 23 Aug 2009 03:38:59 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <4a90b50e.154654859@text.giganews.com> On Sat, 22 Aug 2009 14:54:41 -0700 (PDT), James Harris wrote: >On 22 Aug, 10:27, David <71da... at libero.it> wrote: > >... (snipped a discussion on languages and other systems interpreting >numbers with a leading zero as octal) > >> > Either hexadecimal should have been 0h or octal should >> > have been 0t :=3D) >> >> >> I have seen the use of Q/q instead in order to make it clearer. I still >> prefer Smalltalk's 16rFF and 8r377. >> >> >> Two interesting options. In a project I have on I have also considered >> using 0q as indicating octal. I maybe saw it used once somewhere else >> but I have no idea where. 0t was a second choice and 0c third choice >> (the other letters of oct). 0o should NOT be used for obvious reasons. >> >> So you are saying that Smalltalk has r where >> r is presumably for radix? That's maybe best of all. It preserves the >> syntactic requirement of starting a number with a digit and seems to >> have greatest flexibility. Not sure how good it looks but it's >> certainly not bad. I opine that a letter is better; special characters are a valuable piece of real estate. However for floating point you need at least three letters because a floating point number has three parts: the fixed point point, the exponent base, and the exponent. Now we can represent the radices of the individual parts with the 'r'scheme, e.g., 2r101001, but we need separate letters to designate the exponent base and the exponent. B and E are the obvious choices, though we want to be careful about a confusion with 'b' in hex. For example, using 'R', 3R20.1B2E16Rac is 20.1 in trinary (6 1/3) times 2**172 (hex ac). I grant that this example looks a bit gobbledegookish, but normal usage would be much simpler. The notation doesn't handle balanced trinary; however I opine that balanced trinary requires special notation. Richard Harter, cri at tiac.net http://home.tiac.net/~cri, http://www.varinoma.com No one asks if a tree falls in the forest if there is no one there to see it fall. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 23 00:07:05 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Aug 2009 04:07:05 GMT Subject: Annoying octal notation References: <87d46ok948.fsf@benfinney.id.au> Message-ID: <02a0b085$0$30337$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 14:04:17 -0500, Derek Martin wrote: >> These human programmers, whether newbies or long-experienced, also deal >> with decimal numbers every day, many of which are presented as a >> sequence of digits with leading zeros ? and we continue to think of >> them as decimal numbers regardless. Having the language syntax opposed >> to that is > > ...consistent with virtually every other popular programming language. A mistake is still a mistake even if it shared with others. Treating its with a lead zero as octal was a design error when it was first thought up (possibly in C?) and it remains a design error no matter how many languages copy it. I feel your pain of having to unlearn something you have learned, but just because you have been lead astray by the languages you use doesn't mean we should compound the error by leading the next generation of coders astray too. Octal is of little importance today, as near as I can tell it only has two common uses in high level languages: file umasks and permissions on Unix systems. It simply isn't special enough to justify implicit notation that surprises people, leads to silent errors, and is inconsistent with standard mathematical notation and treatment of floats: >>> 123.2000 # insignificant trailing zeroes don't matter 123.2 >>> 000123.2 # neither do insignificant leading zeroes 123.2 >>> 001.23e0023 # not even if it is an integer 1.23e+23 >>> 000123 # but here is matters 83 -- Steven From goldtech at worldpost.com Sun Aug 23 00:47:52 2009 From: goldtech at worldpost.com (goldtech) Date: Sat, 22 Aug 2009 21:47:52 -0700 (PDT) Subject: Idle does not recognize PYTHONPATH Message-ID: <1eaa9d66-b1ff-4d2d-961f-ee40054a0953@r38g2000yqn.googlegroups.com> Hi, Idle does not recognize PYTHONPATH set in .bashrc. Starting Python shell in the terminal sys.path shows the PYTHONPATH, but again not shown in IDLE. This is a common problem but I could not find a fix. Using Ubuntu 9.04. Python 2.6. Thanks From ak at nothere.com Sun Aug 23 01:01:46 2009 From: ak at nothere.com (AK) Date: Sun, 23 Aug 2009 01:01:46 -0400 Subject: How to 'de-slashify' a string? In-Reply-To: References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> <4a8fc3d1$0$22535$607ed4bc@cv.net> <4a8fce05$0$31285$607ed4bc@cv.net> Message-ID: <4a90cd3a$0$22525$607ed4bc@cv.net> Vlastimil Brom wrote: > 2009/8/22 AK : >> Vlastimil Brom wrote: >>> 2009/8/22 AK : >>>> Steven D'Aprano wrote: >>>>> On Sat, 22 Aug 2009 04:20:23 -0400, AK wrote: >>>>> >>>>>> Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' >>>>>> in a general way? >>>>> It's not clear what you mean. >>>>> >>>>> Do you mean you have a string '\\303\\266', that is: >>>>> >>>>> backslash backslash three zero three backslash backslash two six six >>>>> >>>>> If so, then the simplest way is: >>>>> >>>>>>>> s = r'\\303\\266' # note the raw string >>>>>>>> len(s) >>>>> 10 >>>>>>>> print s >>>>> \\303\\266 >>>>>>>> print s.replace('\\\\', '\\') >>>>> \303\266 >>>>> >>>>> >>>>> Another possibility: >>>>> >>>>>>>> s = '\\303\\266' # this is not a raw string >>>>>>>> len(s) >>>>> 8 >>>>>>>> print s >>>>> \303\266 >>>>> >>>>> So s is: >>>>> backslash three zero three backslash two six six >>>>> >>>>> and you don't need to do any more. >>>> Well, I need the string itself to become '\303\266', not to print >>>> that way. In other words, when I do 'print s', it should display >>>> unicode characters if my term is set to show them, instead of >>>> showing \303\266. >>>> >>>>>> The problem I'm running into is that I'm connecting with pygresql to a >>>>>> postgres database and when I get fields that are of 'char' type, I get >>>>>> them in unicode, but when I get fields of 'byte' type, I get the text >>>>>> with quoted slashes, e.g. '\303' becomes '\\303' and so on. >>>>> Is pygresql quoting the backslash, or do you just think it is quoting >>>>> the >>>>> backslashes? How do you know? E.g. if you have '\\303', what is the >>>>> length >>>>> of that? 4 or 5? >>>> Length is 4, and I need it to be length of 1. E.g.: >>>> >>>>>>> s = '\303' >>>>>>> s >>>> '\xc3' >>>>>>> x = '\\303' >>>>>>> x >>>> '\\303' >>>>>>> len(x) >>>> 4 >>>>>>> len(s) >>>> 1 >>>> >>>> >>>> What I get from pygresql is x, what I need is s. Either by asking >>>> pygresql >>>> to do this or convert it afterwards. I can't do replace('\\303', '\303') >>>> because it can be any unicode character. >>>> >>>> -- >>>> AK >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>>> >>> >>> Hi, >>> do you mean something like >>> >>>>>> u"\u0303" >>> u'\u0303' >>>>>> print u"\u0303" >>> ? >>> ? (dec.: 771) (hex.: 0x303) ? COMBINING TILDE (Mark, Nonspacing) >>> ? >>> >>> vbr >> Yes, something like that except that it starts out as '\\303\\266', and it's >> good enough for me if it turns into '\303\266', in fact that's rendered as >> one unicode char. In other words, when you do: >> >>>>> print "\\303\\266" >> '\303\266' >> >> I need that result to become a python string, i.e. the slashes need to >> be converted from literal slashes to escape slashes. >> >> >> >> >> -- >> AK >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > Not sure, whether it is the right way of handling the such text data, but maybe: > >>>> decoded = '\\303\\266'.decode("string_escape") >>>> decoded > '\xc3\xb6' >>>> print decoded > ?? >>>> print '\303\266' > ?? > > It might be an IDLE issue, but it still isn't one unicode glyph. > > I guess, you have to ensure, that the input data is valid and the > right encoding is used. > > hth > vbr Actually, this works perfectly for me. It prints out as one character in gnome-terminal and also when I write it to a text file, and open it as utf-8 format in gnumeric, it also shows up properly. Thanks to all who helped! -AK From http Sun Aug 23 01:27:57 2009 From: http (Paul Rubin) Date: 22 Aug 2009 22:27:57 -0700 Subject: How to create functors? References: <7xab1vl0qf.fsf@ruckus.brouhaha.com> <7xmy5uanlt.fsf@ruckus.brouhaha.com> Message-ID: <7xljlbf6aq.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > According to Wikipedia, functor can be used as a synonym for "function > object": ... http://en.wikipedia.org/wiki/Function_object Hmm, I hadn't seen that usage before. I guess there's no law against it, but it seems a bit bogus to me. > I find the Haskell page entirely opaque and unintelligible... The > Wikipedia page is a little better I thought it was the other way around, but I've been banging my head against Haskell on and off for the past year or so, so it could be that the Haskell page is more intelligible if the reader already has some familiarity with Haskell and its type system. Here's another attempt of my own, from the mathematical perspective: "categories" generalize the concept of structured collections of objects. For example, groups, rings, and sets are each a type of structured collection, so there is a category of groups (called "Grp" since for some reason categorists like to use capitalized, abbreviated names), a category of rings ("Rng"), and a category of sets ("Set"). Each category has a collection of objects and a collection of "arrows" (sometimes called morphisms) which are associative relations between objects in the category. So in the category of sets, the objects are sets and the arrows are functions mapping one set to another. In the category of groups, the objects are groups and the arrows are the homeomorphisms between groups. Functors are mappings from one category to another, that map both the objects and the arrows. That is they are arrows on the categories of categories. The concepts of categories and functors came from the loftier reaches of algebraic geometry (further in math than I ever got) in the 1950's or so. These days they turn out to be useful in studying type systems of programming languages, which is where most of my exposure to them has come from. > But let me try an example to see if I've got it right: > class Int2StrFunctor: > def map1(self, n): > if type(n) is not int: > raise TypeError('argument must be an int') I don't think this is right. A functor (in the PL sense that I've been describing) acts on types, not on members of types. That is, your example turns "3" into "---", i.e. it turns a member of type "int" into a member of type "str". A functor would be something that acts on arbitrary types, e.g. one might turn "int" into "array of int", and "str" into "array of str" and so forth. Another might turn "int" into "red-black tree containing a pair of ints at each node" and doing something similar with str. The map1 and map2 functions (I guess it is ok to call them that) are supposed to be generic. I guess you could have a "String" functor whose map1 function is repr and whose map2 functor is (lambda f: lambda x,f=f: repr(f(x))) or something like that. It would transport every type to the str type. > There are some technical restrictions on functors, relating to the sorts > of functions and types (strictly "categories") they can accept, > presumably to make them mathematically well-behaved. Right. From aahz at pythoncraft.com Sun Aug 23 01:48:34 2009 From: aahz at pythoncraft.com (Aahz) Date: 22 Aug 2009 22:48:34 -0700 Subject: logging SMTPhandler Error References: Message-ID: In article , Ned Deily wrote: > >Or on OS X it's not *too* difficult to set up a local host mailer using >the Apple-supplied prefix that would accept mail locally and forward it >to a more sophisticated remote mailer. It's also not too difficult to do the moral equivalent with dnspython and find the MX host for the domain you're trying to send e-mail to; that usually does not require an encrypted connection. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From steve at REMOVE-THIS-cybersource.com.au Sun Aug 23 02:13:31 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Aug 2009 06:13:31 GMT Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> Message-ID: <02a0ce27$0$30337$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 22:19:01 -0500, Derek Martin wrote: > On Sat, Aug 22, 2009 at 02:55:51AM +0000, Steven D'Aprano wrote: >> > I can see how 012 can >> > be confusing to new programmers, but at least it's legible, and the >> > great thing about humans is that they can be taught (usually). >> >> And the great thing is that now you get to teach yourself to stop >> writing octal numbers implicitly and be write them explicitly with a >> leading 0o instead :) > > Sorry, I don't write them implicitly. A leading zero explicitly states > that the numeric constant that follows is octal. That is incorrect. Decimal numbers implicitly use base 10, because there's nothing in the literal 12340 (say) to indicate the base is ten, rather than 16 or 9 or 23. Although implicit is usually bad, when it's as common and expected as decimal notation, it's acceptable. Hex decimals explicitly use base 16, because the leading 0x is defined to mean "base 16". 0x is otherwise not a legal decimal number, or hex number for that matter. (It would be legal in base 34 or greater, but that's rare enough that we can ignore this.) For the bases we care about, a leading 0x can't have any other meaning -- there's no ambiguity, so we can treat it as a synonym for "base 16". (Explicitness isn't a binary state, and it would be even more explicit if the base was stated in full, as in e.g. Ada where 16#FF# = decimal 255.) However, octal numbers are defined implicitly: 012 is a legal base 10 number, or base 3, or base 9, or base 16. There's nothing about a leading zero that says "base 8" apart from familiarity. We can see the difference between leading 0x and leading 0 if you repeat it: repeating an explicit 0x, as in 0x0xFF, is a syntax error, while repeating an implicit 0 silently does nothing different: >>> 0x0xFF File "", line 1 0x0xFF ^ SyntaxError: invalid syntax >>> 0077 63 > It is so in 6 out of 7 > computer languages I have more than a passing familiarity with (the 7th > being scheme, which is a thing unto itself), including Python. It's > that way on Bourne-compatible and POSIX-compatible Unix shells (though > it requires a leading backslash before the leading zero there). I'm > quite certain it can not be the case on only those 6 languages that I > happen to be familiar with... No, of course not. There are a bunch of languages, pretty much all heavily influenced by C, which treat integer literals with leading 0s as oct: C++, Javascript, Python 2.x, Ruby, Perl, Java. As so often is the case, C's design mistakes become common practice. Sigh. However, there are many, many languages that don't, or otherwise do things differently to C. Even some modern C-derived languages reject the convention: C# doesn't have octal literals at all. As far as I can tell, Objective-C and Cocoa requires you to explicitly enable support for octal literals before you use them. In D, at least some people want to follow Python's lead and either drop support for oct literals completely, or require a 0o prefix: http://d.puremagic.com/issues/show_bug.cgi?id=2656 E makes a leading 0 a syntax error. As far as other, non-C languages go, leading 0 = octal seems to be rare or non-existent: Basic and VB use a leading &O for octal. FORTRAN 90 uses a leading O (uppercase o) for octal, and surrounds the literal in quotation marks: O"12" would be ten in octal. 012 would be decimal 12. As far as I can tell, COBOL also ignores leading zeroes. Forth interprets literals according to the current value of BASE (which defaults to 10). There's no special syntax for it.To enter ten in octal, you might say: 8 BASE ! 12 or if your system provides it: OCT 12 Standard Pascal ignores leading 0s in integers, and doesn't support octal at all. A leading $ is used for hex. At least one non-standard Pascal uses leading zero for octal. Haskell requires an explicit 0o: http://www.haskell.org/onlinereport/lexemes.html#lexemes-numeric So does OCaml. Ada uses decimal unless you explicitly give the base: http://archive.adaic.com/standards/83lrm/html/lrm-02-04.html Leading zeroes are insignificant in bc: [steve at sylar ~]$ bc bc 1.06 Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. 012 + 011 23 Leading zeroes are also insignificant in Hewlett-Packard RPN language (e.g. HP-48GX calculators), Hypertalk and languages derived from it. I'm not sure, but it looks to me like Boo doesn't support octal literals, although it supports hex with 0x and binary with 0b. Algol uses an explicit base: 8r12 to indicate octal 10. Common Lisp and Scheme use a #o prefix. As far as *languages* go, 0-based octal literals are in the tiny minority. As far as *programmers* go, it may be in a plurality, perhaps even a small minority, but remember there are still millions of VB programmers out there who are just as unfamiliar with C conventions. > While it may be true that people commonly write decimal numbers with > leading zeros (I dispute even this [...] Leading zeroes in decimal numbers are *very* common in dates and times. [...] > Given that Python has an ncurses interface, I'm > guessing it's used there too. In fact if the Python source had no octal > in it, I would find that very surprising. I can't see any oct literals in the standard library, not even in the ncurses interface, but then my grep-foo is weak and I may have made a mistake. I encourage you to look for yourself. >> It's no hardship to write 0o12 instead of 012. > > Computer languages are not write-only, excepting maybe Perl. ;-) Writing > 0o12 presents no hardship; but I assert, with at least some support from > others here, that *reading* it does. No more so than 0x or 0b literals. If anything, 0o12 stands out as "not twelve" far more than 012 does. -- Steven From hendrik at microcorp.co.za Sun Aug 23 03:10:22 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 23 Aug 2009 09:10:22 +0200 Subject: Blank Line at Program Exit In-Reply-To: References: Message-ID: <200908230910.22246.hendrik@microcorp.co.za> On Thursday 20 August 2009 07:31:14 Steven Woody wrote: > Hi, > Any python program, even that does absolutely nothing in the code, will > cause a blank line printed out when the program exit. What's the reason? not for me: hvr at Linuxbox:~/Sasol/lib> cat blank.py hvr at Linuxbox:~/Sasol/lib> python blank.py hvr at Linuxbox:~/Sasol/lib> - Hendrik From hendrik at microcorp.co.za Sun Aug 23 03:21:54 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 23 Aug 2009 09:21:54 +0200 Subject: your favorite debugging tool? In-Reply-To: References: Message-ID: <200908230921.54199.hendrik@microcorp.co.za> On Saturday 22 August 2009 16:49:22 Aahz wrote: > In article , > > Esmail wrote: > >What is your favorite tool to help you debug your code? I've been > >getting along with 'print' statements but that is getting old and > >somewhat cumbersome. > > Despite the fact that I've been using Python for more than a decade, > print is still my mainstay (or possibly logging to a file). Same here, although I have not been abusing python for as long as Aahz has been using it. I find that python pretty much does more or less what I expect it to, and where it does not, a print quickly gets me to RTFM when I have been rolling along under intuition. And the final arbiter is of course the interactive prompt. - Hendrik From ben+python at benfinney.id.au Sun Aug 23 03:40:47 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 23 Aug 2009 17:40:47 +1000 Subject: your favorite debugging tool? References: Message-ID: <873a7jhta8.fsf@benfinney.id.au> Hendrik van Rooyen writes: > And the final arbiter is of course the interactive prompt. Oh yes, of course I forget to mention that! Write your code so it can be imported, and write your functionality so it has narrow interfaces, and you can do whatever inspection is needed from the interactive prompt. -- \ ?We have to go forth and crush every world view that doesn't | `\ believe in tolerance and free speech.? ?David Brin | _o__) | Ben Finney From robert.kern at gmail.com Sun Aug 23 03:54:31 2009 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 23 Aug 2009 00:54:31 -0700 Subject: your favorite debugging tool? In-Reply-To: References: Message-ID: On 2009-08-22 07:25 AM, Esmail wrote: > Hi all, > > What is your favorite tool to help you debug your > code? I've been getting along with 'print' statements > but that is getting old and somewhat cumbersome. > > I'm primarily interested in utilities for Linux (but > if you have recommendations for Windows, I'll take > them too :) > > I use emacs as my primary development environment, FWIW. > Someone mentioned winpdb .. anyone have experience/comments > on this? Others? I am frequently in the IPython interactive prompt for testing out stuff and even as the main way of running my code. It has a nice feature that when you get a traceback, you can open up pdb post-mortem. In [8]: def f(x): ...: y = 1 / x ...: return y ...: In [9]: f(1) Out[9]: 1 In [10]: f(0) --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) /Users/rkern/ in () /Users/rkern/ in f(x) ZeroDivisionError: integer division or modulo by zero In [11]: %debug > (2)f() ipdb> print x 0 I have a little function that I've been using recently to print out the function I am currently in along with the arguments: def whereami(): """ Print the current function call. import kerntrace;kerntrace.whereami() """ import inspect frame = inspect.currentframe(1) args, varargs, varkw, f_locals = inspect.getargvalues(frame) if args[:1] == ['self']: del args[0] print '%s%s' % (frame.f_code.co_name, inspect.formatargvalues(args, varargs, varkw, f_locals)) I think pdb is okay, but I am looking forward to pydbgr's completion. http://code.google.com/p/pydbgr/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sdementen at gmail.com Sun Aug 23 04:09:04 2009 From: sdementen at gmail.com (seb) Date: Sun, 23 Aug 2009 01:09:04 -0700 (PDT) Subject: conditional for-statement Message-ID: Hi, i was wondering if there is a syntax alike: for i in range(10) if i > 5: print i equivalent to for i in (for i in range(10) if i>5): print i sebastien From benjamin at python.org Sun Aug 23 04:12:40 2009 From: benjamin at python.org (Benjamin Peterson) Date: Sun, 23 Aug 2009 08:12:40 +0000 (UTC) Subject: conditional for-statement References: Message-ID: seb gmail.com> writes: > > Hi, > > i was wondering if there is a syntax alike: > > for i in range(10) if i > 5: > print i for i in range(10): if i > 5: print i From bieffe62 at gmail.com Sun Aug 23 04:12:52 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Sun, 23 Aug 2009 01:12:52 -0700 (PDT) Subject: your favorite debugging tool? References: Message-ID: <7694a678-fb08-4cd4-a1f7-de71e0a26cb2@o6g2000yqj.googlegroups.com> On Aug 22, 4:25?pm, Esmail wrote: > Hi all, > > What is your favorite tool to help you debug your > code? I've been getting along with 'print' statements > but that is getting old and somewhat cumbersome. > > I'm primarily interested in utilities for Linux (but > if you have recommendations for Windows, I'll take > them too :) > > I use emacs as my primary development environment, FWIW. > Someone mentioned winpdb .. anyone have experience/comments > on this? Others? > > Thanks, > Esmail Although like the others I mostly use print statements, in a few occasions I have found useful to resort to a full-blown debugger. Of the ones I have used, the one provided by eclipse+pydev is the one I liked most. The one in pywin32 IDE is basic but can be useful. With emacs, one should be able to use pydb, but I never used that, although emacs is my most used programming environment on most platforms. About print cumbersomeness, I agree. As I posted elsewhere, I'd like a 'trace mechanism' with the following characteristics: 1. Can be enabled/disabled easily, and when it is dsabled it has no runtime costs ( i.e. disabled 'trace' statements do not generate any code) 2. Can be enabled/disabled on a class/function/method base (e.g. enable only the trace in a method ), to only get the trace output from the code you are debugging 3. Make it easy to report the context (i.e. generate messages which starts with 'class.method:', without hanving to hardcode class name and method name). I know about the 'trace' and 'logging' modules, but neither seem to satisfy the above requirements. Probably using python introspection and metaprogramming features it is possible to do somethinmg that covers at least 2 and 3. Not sure about one (using if __debug__ you can reduce the runtime cost when compiling in optimized mode, but probably not nullify it). Ciao ----- FB From mailbox at dmitry-kazakov.de Sun Aug 23 04:21:52 2009 From: mailbox at dmitry-kazakov.de (Dmitry A. Kazakov) Date: Sun, 23 Aug 2009 10:21:52 +0200 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <1gl24ajxu6dsk.1btjdkwwj6m.dlg@40tude.net> On Sat, 22 Aug 2009 14:54:41 -0700 (PDT), James Harris wrote: > They look good - which is important. The trouble (for me) is that I > want the notation for a new programming language and already use these > characters. I have underscore as an optional separator for groups of > digits - 123000 and 123_000 mean the same. The semicolon terminates a > statement. Based on your second idea, though, maybe a colon could be > used instead as in > > 2:1011, 8:7621, 16:c26b > > I don't (yet) use it as a range operator. > > I could also use a hash sign as although I allow hash to begin > comments it cannot be preceded by anything other than whitespace so > these would be usable > > 2#1011, 8#7621, 16#c26b > > I have no idea why Ada which uses the # also apparently uses it to end > a number > > 2#1011#, 8#7621#, 16#c26b# If you are going Unicode, you could use the mathematical notation, which is 10112, 76218, c26b16 (subscript specification of the base). Yes, it might be difficult to type (:-)), and would require some look-ahead in the parser. One of the advantages of Ada notation, is that a numeric literal always starts with decimal digit. That makes things simple for a descent recursive parser. I guess this choice was intentional, back in 1983 a complex parser would eat too much resources... -- Regards, Dmitry A. Kazakov http://www.dmitry-kazakov.de From bieffe62 at gmail.com Sun Aug 23 04:30:16 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Sun, 23 Aug 2009 01:30:16 -0700 (PDT) Subject: conditional for-statement References: Message-ID: On Aug 23, 10:09?am, seb wrote: > Hi, > > i was wondering if there is a syntax alike: > > for i in range(10) if i > 5: > ? ? print i > > equivalent to > > for i in (for i in range(10) if i>5): > ? ? print i > > sebastien AFAIK, no syntax fo that. But the standard syntax is not too different: for i in range(0): if i > 5 : print i Or you can use itertools.ifilter: for i in itertools.ifilter( lambda x: x > 5, range(10) ): print i Or, if you define a function corresponding to the loop body, you could do something like: map( print, (i for i in range(10) if i> 5 )) # only works if print is a function Ciao ---- FB From bearophileHUGS at lycos.com Sun Aug 23 05:09:20 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Sun, 23 Aug 2009 02:09:20 -0700 (PDT) Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <02a0ce27$0$30337$c3e8da3@news.astraweb.com> Message-ID: <6b5ea596-d1e3-483d-ba79-7b139d3c7a47@z24g2000yqb.googlegroups.com> MRAB: >'_': what if in the future we want to allow them in numbers for clarity? Hettinger says it's hard (= requires too many changes) to do that and Python programs don't have big integer constants often enough, so probably that improvement will not see the light. In the meantime in a Python program of mine I have put a small bug, writing 1000000 instead of 10000000. Now in Python I write 10*1000*1000, because I try to learn from my bugs. In D I enjoy writing 10_000_000. ------------------------------- Steven D'Aprano: > In D, at least some people want to follow Python's lead and either drop > support for oct literals completely, or require a 0o prefix:http://d.puremagic.com/issues/show_bug.cgi?id=2656 Yes, people in the D community are trying to improve things, but it's a slow and painful process, and often it goes nowhere. There's lot of politics. Bye, bearophile From harald.luessen at gmx.de Sun Aug 23 05:12:43 2009 From: harald.luessen at gmx.de (Harald Luessen) Date: Sun, 23 Aug 2009 11:12:43 +0200 Subject: IDLE file saving problem References: <70222640-1990-4fae-bbca-8451d252a1ab@13g2000prl.googlegroups.com> Message-ID: <9d12959olkh5l3oamr9lfhedcrqd5nt7v7@4ax.com> On Fri, 21 Aug 2009 14:48:56 -0700 (PDT), r wrote: >On Aug 21, 4:10?pm, MRAB wrote: > >Yes, and much more needs improvement! I have made many changes already >and i am polishing an "IDLE 3000" for the good people of Pythonia, >stay tuned more to come.... There is a small little detail that nags me when I use IDLE: When the cursor is somewhere in the white space at the beginning of the lines and I use Ctrl-rightArrow [ctrl]-[->] to go to the first word in the line then IDLE skips the position with the first non-whitespace letter and places the cursor after the first word in the line. This is not consistent because moving backwards works. [ctrl]-[<-] Similar things happen at the end of a line. I suggest that these movements should consider 'before the first' and 'after the last' text in the line as stop positions. I think other editors do that, at least MS Visual Studio. (The [pos1] alternating between first column and first text in line does not help much.) Harald From 71david at libero.it Sun Aug 23 05:50:30 2009 From: 71david at libero.it (David) Date: Sun, 23 Aug 2009 11:50:30 +0200 Subject: conditional for-statement References: Message-ID: Il Sun, 23 Aug 2009 01:09:04 -0700 (PDT), seb ha scritto: > Hi, > > i was wondering if there is a syntax alike: > > for i in range(10) if i > 5: > print i You can write for i in filter(lambda i: i > 5, range(10)): print i but for i in range(10): if i > 5: print i it' better readable, and for i in range(6,10): print i it's event better. From garabik-news-2005-05 at kassiopeia.juls.savba.sk Sun Aug 23 06:08:43 2009 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Sun, 23 Aug 2009 10:08:43 +0000 (UTC) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: In comp.lang.python James Harris wrote: > On 22 Aug, 10:27, David <71da... at libero.it> wrote: ... >> >> What about 2_1011, 8_7621, 16_c26h or 2;1011, 8;7621, 16;c26h ? > > They look good - which is important. The trouble (for me) is that I > want the notation for a new programming language and already use these > characters. I have underscore as an optional separator for groups of > digits - 123000 and 123_000 mean the same. Why not just use the space? 123 000 looks better than 123_000, and is not syntactically ambiguous (at least in python). And as it already works for string literals, it could be applied to numbers, too? -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From nmm1 at cam.ac.uk Sun Aug 23 06:35:10 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Sun, 23 Aug 2009 11:35:10 +0100 (BST) Subject: Python/Fortran interoperability Message-ID: I am interested in surveying people who want to interoperate between Fortran and Python to find out what they would like to be able to do more conveniently, especially with regard to types not supported for C interoperability by the current Fortran standard. Any suggestions as to other ways that I could survey such people (Usenet is no longer as ubiquitous as it used to be) would be welcomed. My Email address is real, so direct messages will be received. Specifically, I should like to know the answers to the following questions: 1) Do you want to use character strings of arbitrary length? 2) Do you want to use Python classes with list members, where the length of the list is not necessarily fixed for all instances of the class? Or, equivalently, Fortran derived types containing allocatable or pointer arrays? 2) Do you want to use Fortran derived types or Python classes that contain type-bound procedures (including finalizers)? Please answer "yes" whether or nor you would like to call those type-bound procedures from the other language. 4) Do you want to call functions where the called language allocates or deallocates arrays/lists/strings for use by the calling language? Note that this is specifically Fortran->Python and Python->Fortran. Regards, Nick Maclaren. From countryone77 at yahoo.com Sun Aug 23 06:57:49 2009 From: countryone77 at yahoo.com (Bev in TX) Date: Sun, 23 Aug 2009 03:57:49 -0700 (PDT) Subject: logging SMTPhandler Error References: Message-ID: <60de8d40-61f4-4ffd-bcef-749bf06675d0@k19g2000yqn.googlegroups.com> On Aug 23, 12:48?am, a... at pythoncraft.com (Aahz) wrote: > It's also not too difficult to do the moral equivalent with dnspython and > find the MX host for the domain you're trying to send e-mail to; that > usually does not require an encrypted connection. > -- > Aahz (a... at pythoncraft.com) ? ? ? ? ? <*> ? ? ? ?http://www.pythoncraft.com/ > > "I support family values -- Addams family values" --www.nancybuttons.com Thanks :-). I'm not sure that I understand exactly what needs to be done, but I'll read the documentation and see what I can come up with. Bev in TX From sp.bylc at gmail.com Sun Aug 23 07:26:35 2009 From: sp.bylc at gmail.com (newbie) Date: Sun, 23 Aug 2009 04:26:35 -0700 (PDT) Subject: Is Python what I need? Message-ID: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Hi all I'm interested in developing computer based, interactive programs for students in a special school who have an aversion to pen and paper. I've searched the net to find ready made software that will meet my needs but it is either written to a level much higher than these students can cope with or priced beyond our school budget. I came across a blog of someone singing the praises of Python. My question is therefore aimed at those that know what they are talking about (ie users in this group). Is Python the language I need to learn to develop these programs? From contact at xavierho.com Sun Aug 23 07:42:30 2009 From: contact at xavierho.com (Xavier Ho) Date: Sun, 23 Aug 2009 21:42:30 +1000 Subject: Is Python what I need? In-Reply-To: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: <2d56febf0908230442r32088956gb504b0149d2808a7@mail.gmail.com> On Sun, Aug 23, 2009 at 9:26 PM, newbie wrote: > Hi all > I'm interested in developing computer based, interactive programs for > students in a special school who have an aversion to pen and paper. What sort of interactive program? Would it be educational, for example? > I've searched the net to find ready made software that will meet my > needs but it is either written to a level much higher than these > students can cope with or priced beyond our school budget. Could you give us the details of which software you've encountered that were either too expensive or did not meet your needs? > I came across a blog of someone singing the praises of Python. My question > is > therefore aimed at those that know what they are talking about (ie > users in this group). Is Python the language I need to learn to > develop these programs? Any language can do the job. What a program does depends on the design, and specification. Different languages simply have different behaviours, and perhaps platform dependence and requirements. So, in some way, yes, Python can do what you need, but you need to tell us in exact details what you were really looking for. Good luck, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From 71david at libero.it Sun Aug 23 08:01:41 2009 From: 71david at libero.it (David) Date: Sun, 23 Aug 2009 14:01:41 +0200 Subject: your favorite debugging tool? References: Message-ID: <142n6tb9nof0p$.1f2kw0c0vhj8u.dlg@40tude.net> Il Sat, 22 Aug 2009 10:25:37 -0400, Esmail ha scritto: > > I use emacs as my primary development environment, FWIW. > Someone mentioned winpdb .. anyone have experience/comments > on this? Others? I use Winpdb on Windows and I feel quite comfortable. The interface is not so clever as more advanced (and expensive, winpdb is free) debuggers but there is all yuo need for deep-source debugging. It is especially suited for multi threaded programs and GUI debugging, where command line debugging is a pain. It supports remote debugging over encrypted connection also. regards David From pengyu.ut at gmail.com Sun Aug 23 08:37:24 2009 From: pengyu.ut at gmail.com (Peng Yu) Date: Sun, 23 Aug 2009 05:37:24 -0700 (PDT) Subject: Combining python and perl Message-ID: <743337bf-487f-434d-b15c-4b675b6487f4@d21g2000vbm.googlegroups.com> Hi, According to http://www.python.org/doc/essays/comparisons.html, it says "Python and Perl come from a similar background (Unix scripting, which both have long outgrown), and sport many similar features, but have a different philosophy. Perl emphasizes support for common application- oriented tasks, e.g. by having built-in regular expressions, file scanning and report generating features. Python emphasizes support for common programming methodologies such as data structure design and object-oriented programming, and encourages programmers to write readable (and thus maintainable) code by providing an elegant but not overly cryptic notation. As a consequence, Python comes close to Perl but rarely beats it in its original application domain; however Python has an applicability well beyond Perl's niche." My question is that how to combine both python and perl to take advantages of both their strong aspects. Of course, I want to primarily use python---that is why I send this message to this group. I see a module 'perlmodule'. But I would like to know whether there are other tips besides using 'perlmodule' to take perl's advantage in python. Regards, Peng From marduk at letterboxes.org Sun Aug 23 09:00:00 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 23 Aug 2009 09:00:00 -0400 Subject: Combining python and perl In-Reply-To: <743337bf-487f-434d-b15c-4b675b6487f4@d21g2000vbm.googlegroups.com> References: <743337bf-487f-434d-b15c-4b675b6487f4@d21g2000vbm.googlegroups.com> Message-ID: <1251032400.19411.17.camel@centar.nbk> On Sun, 2009-08-23 at 05:37 -0700, Peng Yu wrote: > Hi, > > According to http://www.python.org/doc/essays/comparisons.html, it > says > > "Python and Perl come from a similar background (Unix scripting, which > both have long outgrown), and sport many similar features, but have a > different philosophy. Perl emphasizes support for common application- > oriented tasks, e.g. by having built-in regular expressions, file > scanning and report generating features. Python emphasizes support for > common programming methodologies such as data structure design and > object-oriented programming, and encourages programmers to write > readable (and thus maintainable) code by providing an elegant but not > overly cryptic notation. As a consequence, Python comes close to Perl > but rarely beats it in its original application domain; however Python > has an applicability well beyond Perl's niche." > > My question is that how to combine both python and perl to take > advantages of both their strong aspects. Of course, I want to > primarily use python---that is why I send this message to this group. I'm not sure why you'd want to "combine" them. You can pretty much do the same things with both language, it's just that one may emphasize one thing or make it easier for the user than the other. For example, regular expressions in Perl. It's built into the language, but that doesn't mean Python doesn't have regular expressions, just that Python is less "centered" around them. If you want to use regular expressions with Python just "import re". -a From motoom at xs4all.nl Sun Aug 23 09:05:51 2009 From: motoom at xs4all.nl (Michiel Overtoom) Date: Sun, 23 Aug 2009 15:05:51 +0200 Subject: your favorite debugging tool? In-Reply-To: References: Message-ID: <4A913EAF.8050703@xs4all.nl> Esmail wrote: > What is your favorite tool to help you debug your > code? import pdb pdb.set_trace() pdb has commands to inspect code, variables, set breakpoints, watches, walk up and down stack frames, single-step through the program, run the rest of the function, run until return, etc... http://www.ferg.org/papers/debugging_in_python.html http://onlamp.com/pub/a/python/2005/09/01/debugger.html http://plone.org/documentation/how-to/using-pdb http://docs.python.org/library/pdb.html Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Valloppillil http://www.catb.org/~esr/halloween/halloween4.html From narkewoody at gmail.com Sun Aug 23 09:07:53 2009 From: narkewoody at gmail.com (Steven Woody) Date: Sun, 23 Aug 2009 21:07:53 +0800 Subject: Blank Line at Program Exit In-Reply-To: <20090822152515.GC10584@sevilla.sacredchaos.com> References: <20090822152515.GC10584@sevilla.sacredchaos.com> Message-ID: On Sat, Aug 22, 2009 at 11:25 PM, Nitebirdz wrote: > On Thu, Aug 20, 2009 at 01:31:14PM +0800, Steven Woody wrote: > > Hi, > > Any python program, even that does absolutely nothing in the code, will > > cause a blank line printed out when the program exit. What's the reason? > > Thanks. > > > > Chances are it is related to whichever operating system and/or shell you > are using. For instance, this is taken from a system running Ubuntu > Linux 8.04: > > ------------------------------------------------- > laptop:$ cat hello.py > #!/usr/bin/env python > > print "Hello, there!" > laptop:$ ./hello.py > Hello, there! > laptop:$ cat nothing.py > #!/usr/bin/env python > > laptop:$ ./nothing.py > laptop:$ > ------------------------------------------------- > > > As you can see, no blank line was printed out. > > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, I am using cywin on XP. -- Life is the only flaw in an otherwise perfect nonexistence -- Schopenhauer narke public key at http://subkeys.pgp.net:11371 (narkewoody at gmail.com) -------------- next part -------------- An HTML attachment was scrubbed... URL: From visionat at mail.infochan.com Sun Aug 23 09:08:52 2009 From: visionat at mail.infochan.com (viper-2) Date: Sun, 23 Aug 2009 06:08:52 -0700 (PDT) Subject: Python/Fortran interoperability References: Message-ID: <1f39d176-28e4-4e4f-a4d1-b3168349510b@34g2000yqi.googlegroups.com> On Aug 23, 6:35 am, n... at cam.ac.uk wrote: > I am interested in surveying people who want to interoperate between > Fortran and Python to find out what they would like to be able to do > more conveniently, especially with regard to types not supported for C > interoperability by the current Fortran standard. Python is still on my "to do" list, but I know I'll be interested in the following: > 1) Do you want to use character strings of arbitrary length? > Yes > 2) Do you want to use Python classes with list members, where the > length of the list is not necessarily fixed for all instances of the > class? Or, equivalently, Fortran derived types containing allocatable > or pointer arrays? > Yes > 2) Do you want to use Fortran derived types or Python classes that > contain type-bound procedures (including finalizers)? Please answer > "yes" whether or nor you would like to call those type-bound procedures > from the other language. > Don't know yet > 4) Do you want to call functions where the called language allocates > or deallocates arrays/lists/strings for use by the calling language? > Note that this is specifically Fortran->Python and Python->Fortran. > Yes agt -- Freedom - no pane, all gaiGN! Code Art Now http://codeartnow.com Email: agt at codeartnow.com From narkewoody at gmail.com Sun Aug 23 09:09:24 2009 From: narkewoody at gmail.com (Steven Woody) Date: Sun, 23 Aug 2009 21:09:24 +0800 Subject: How to distribute an application Message-ID: Hi, My application contains a main python source file as well as a set of modules (also .py files). Now, I am considering distribute my application to others. But the distutils seems made for distributing packages not for main applications. Am I right? Thanks. -- Life is the only flaw in an otherwise perfect nonexistence -- Schopenhauer narke public key at http://subkeys.pgp.net:11371 (narkewoody at gmail.com) -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Sun Aug 23 09:11:05 2009 From: aahz at pythoncraft.com (Aahz) Date: 23 Aug 2009 06:11:05 -0700 Subject: Dictionary from a list References: Message-ID: In article , EK wrote: >On Aug 20, 2:10=A0pm, Peter Otten <__pete... at web.de> wrote: >> >> >>> from itertools import izip >> >>> it =3D iter([1,2,3,4,5,6]) >> >>> dict(izip(it, it)) >> >> {1: 2, 3: 4, 5: 6} > >dict(zip(*[iter(l)]*2)) No, that's not a good solution. For starters, it's less readable than Peter's version. More importantly, it has poor memory use because it needs to construct both the intermediate tuple and the zip() list. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From matthew at woodcraft.me.uk Sun Aug 23 09:13:32 2009 From: matthew at woodcraft.me.uk (Matthew Woodcraft) Date: Sun, 23 Aug 2009 13:13:32 GMT Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> Message-ID: <87fxbifzb7.fsf@golux.woodcraft.me.uk> Dennis Lee Bieber writes: > About the only place one commonly sees leading zeros on decimal > numbers, in my experience, is zero-filled COBOL data decks (and since > classic COBOL stores in BCD anyway... binary (usage is > computational/comp-1) was a later add-on to the data specification model > as I recall...) A more common case is dates. I've seen people trip over this writing things like xxx = [ date(2009, 10, 12), date(2009, 12, 26), date(2010, 02, 09), ] -M- From aahz at pythoncraft.com Sun Aug 23 09:14:00 2009 From: aahz at pythoncraft.com (Aahz) Date: 23 Aug 2009 06:14:00 -0700 Subject: logging SMTPhandler Error References: <60de8d40-61f4-4ffd-bcef-749bf06675d0@k19g2000yqn.googlegroups.com> Message-ID: In article <60de8d40-61f4-4ffd-bcef-749bf06675d0 at k19g2000yqn.googlegroups.com>, Bev in TX wrote: >On Aug 23, 12:48=A0am, a... at pythoncraft.com (Aahz) wrote: >> >> It's also not too difficult to do the moral equivalent with dnspython and >> find the MX host for the domain you're trying to send e-mail to; that >> usually does not require an encrypted connection. > >Thanks :-). I'm not sure that I understand exactly what needs to be >done, but I'll read the documentation and see what I can come up with. Slightly expanded: most mail servers accept connections from any other mail server for addresses that are hosted by them. The MX address for a domain tells you what mail server hosts that address. By connecting directly to the MX, your script is essentially acting as a mail server itself. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From ben+python at benfinney.id.au Sun Aug 23 10:01:46 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 24 Aug 2009 00:01:46 +1000 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <87ljlahbn9.fsf@benfinney.id.au> garabik-news-2005-05 at kassiopeia.juls.savba.sk writes: > Why not just use the space? 123 000 looks better than 123_000, and is > not syntactically ambiguous (at least in python). And as it already > works for string literals, it could be applied to numbers, too? +1 to all this. I think this discussion was had many months ago, but can't recall how it ended back then. -- \ ?Only the educated are free.? ?Epictetus, _Discourses_ | `\ | _o__) | Ben Finney From stefan_ml at behnel.de Sun Aug 23 10:21:27 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Aug 2009 16:21:27 +0200 Subject: Python/Fortran interoperability In-Reply-To: References: Message-ID: <4a915067$0$31339$9b4e6d93@newsspool4.arcor-online.net> nmm1 at cam.ac.uk wrote: > I am interested in surveying people who want to interoperate between > Fortran and Python to find out what they would like to be able to do > more conveniently, especially with regard to types not supported for C > interoperability by the current Fortran standard. Any suggestions as to > other ways that I could survey such people (Usenet is no longer as > ubiquitous as it used to be) would be welcomed. You might want to ask also on the Cython, NumPy and SciPy mailing lists. NumPy and SciPy have a rather large audience of scientific developers, and Cython has a running sub-project on providing better Fortran integration (which might be of interest to you anyway). Stefan From jcd at sdf.lonestar.org Sun Aug 23 10:35:22 2009 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Sun, 23 Aug 2009 10:35:22 -0400 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: <87ljlahbn9.fsf@benfinney.id.au> References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> Message-ID: <1251038122.7067.29.camel@webb> I had an objection to using spaces in numeric literals last time around and it still stands, and it still stands in the new one. What happens if you use a literal like 0x10f 304? Is 304 treated as decimal or hexadecimal? It's not clear how you would begin to combine it The way string concatenation works, it takes two independent string literals, and combines them. If you specify r'\n' 'abc\n', the first half is treated independently as a raw string, and the second half is treated as a normal string. The result is '\\nabc\n'. With numeric literals, this behavior doesn't even make sense. How do you concatenate hex 10f with decimal 304? I suppose you could multiply 0x10f by 1000, and add them, but this probably wouldn't fit any practical usecase. Alternatively, you could raise an exception, and require the user to use numeric literals of the same type, like 0x10f 0x304, but then you lose any readability benefit you might have gained by dropping the _ to begin with. If, on the other hand, you want to combine the tokens before processing their independent meanings, which makes the most intuitive sense, well, in that case we're no longer talking about an operation analogous to string contcatenation. We're talking about integers no longer being simple tokens that can be assigned a value. I'm not familiar with the code that makes all this happen in C Python (or any other implementation for that matter), but it seems like it extends the complexity of the parser unnecessarily. I'm concerned that the benefit in readability will be outweighed by the burden it places on the parser, and the cognitive burden on the programmer of knowing what to expect when using non-decimal numeric literals. For that reason, I'm a -1 on using a space in numeric literals, but +1 on using some other separator, and an _, in spite of its slight awkwardness in typing, seems like a good idea. If someone with a solid understanding of the python parser could chime in that this wouldn't cause as much friction as I think, and explain a clean, elegant implementation for this, many of my concerns would be alleviated, and I would change my -1 to a -0. Cheers, Cliff On Mon, 2009-08-24 at 00:01 +1000, Ben Finney wrote: > garabik-news-2005-05 at kassiopeia.juls.savba.sk writes: > > Why not just use the space? 123 000 looks better than 123_000, and is > > not syntactically ambiguous (at least in python). And as it already > > works for string literals, it could be applied to numbers, too? > > +1 to all this. I think this discussion was had many months ago, but > can't recall how it ended back then. > > -- > \ ?Only the educated are free.? ?Epictetus, _Discourses_ | > `\ | > _o__) | > Ben Finney From ryniek90 at gmail.com Sun Aug 23 10:39:42 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Sun, 23 Aug 2009 16:39:42 +0200 Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: References: Message-ID: <4A9154AE.1000609@gmail.com> Hi I've got my backup script which opens tarfile for add chosen file to it. But while setting it up, i've got Traceback: here's the url: -->http://paste.ubuntu.com/258081/<-- I have searched among google's result but didn't found anything useful. Only found info that it may be the backslashes fault in path, but i have written proper the path. Here's link to my script paste: http://paste.ubuntu.com/258087/ Is its the '|\U' literal fault in path '|C:\\Users\\Ryniek's WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2|' ? Sorry if i'm annoying but i'm still learning. | From phillip.oldham at gmail.com Sun Aug 23 11:02:34 2009 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Sun, 23 Aug 2009 08:02:34 -0700 (PDT) Subject: Most "active" coroutine library project? Message-ID: <64183b73-9cb0-4ce1-98d0-f47e13a818e4@f37g2000yqn.googlegroups.com> I've been taking a look at the multitude of coroutine libraries available for Python, but from the looks of the projects they all seem to be rather "quiet". I'd like to pick one up to use on a current project but can't deduce which is the most popular/has the largest community. Libraries I looked at include: cogen, weightless, eventlet and circuits (which isn't exactly coroutine-based but it's event-driven model was intriguing). Firstly, are there any others I've missed? And what would the consensus be on the which has the most active community behind it? From victorsubervi at gmail.com Sun Aug 23 11:04:57 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 23 Aug 2009 10:04:57 -0500 Subject: Trying To Catch Invalid User Input Message-ID: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> Hi; I have the following: style = raw_input('What style is this? (1 = short, 2 = long): ') flag = 0 while flag == 0: if (style != 1) or (style != 2): style = raw_input('There was a mistake. What style is this? (1 = short, 2 = long): ') else: flag = 1 I would think this would catch errors and permit valid values, but it doesn't. If I enter an erroneous value the first time, and the second time a good value, it doesn't break the loop. Why? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From doctoresam at gmail.com Sun Aug 23 11:12:26 2009 From: doctoresam at gmail.com (Deep_Feelings) Date: Sun, 23 Aug 2009 08:12:26 -0700 (PDT) Subject: can python make web applications? Message-ID: can python make powerfull database web applications that can replace desktop database applications? e.g: entrprise accounting programs,enterprise human resource management programs ...etc From sturlamolden at yahoo.no Sun Aug 23 11:17:56 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 08:17:56 -0700 (PDT) Subject: Python/Fortran interoperability References: Message-ID: <1032c78d-d4dd-41c0-a877-b85ca000d871@g31g2000yqc.googlegroups.com> On 23 Aug, 12:35, n... at cam.ac.uk wrote: > I am interested in surveying people who want to interoperate between > Fortran and Python to find out what they would like to be able to do > more conveniently, especially with regard to types not supported for C > interoperability by the current Fortran standard. ?Any suggestions as to > other ways that I could survey such people (Usenet is no longer as > ubiquitous as it used to be) would be welcomed. I think you will find that 99.9% of Python and Fortran programmers are scientists and engineers that also use NumPy and f2py. Go to scipy.org and ask your question on the numpy mailing list. Regards, Sturla Molden From __peter__ at web.de Sun Aug 23 11:31:47 2009 From: __peter__ at web.de (Peter Otten) Date: Sun, 23 Aug 2009 17:31:47 +0200 Subject: Is Python what I need? References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: newbie wrote: > I'm interested in developing computer based, interactive programs for > students in a special school who have an aversion to pen and paper. > I've searched the net to find ready made software that will meet my > needs but it is either written to a level much higher than these > students can cope with or priced beyond our school budget. I came > across a blog of someone singing the praises of Python. My question is > therefore aimed at those that know what they are talking about (ie > users in this group). Is Python the language I need to learn to > develop these programs? >From the distance it looks like these children need a good teacher rather than a bad (or just starting) programmer. They need goals they can understand and share, not yet another tool. But it's interactive? Yeah, three canned answers instead of just one... That said, Python is a good language for the casual developer. You can whack together something pretty quickly. It may not be perfect, but you don't waste time on administrative overhead either. Peter From python at mrabarnett.plus.com Sun Aug 23 11:36:10 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 23 Aug 2009 16:36:10 +0100 Subject: Trying To Catch Invalid User Input In-Reply-To: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> References: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> Message-ID: <4A9161EA.5050602@mrabarnett.plus.com> Victor Subervi wrote: > Hi; > I have the following: > > style = raw_input('What style is this? (1 = short, 2 = long): ') > flag = 0 > while flag == 0: > if (style != 1) or (style != 2): > style = raw_input('There was a mistake. What style is this? (1 = > short, 2 = long): ') > else: > flag = 1 > > I would think this would catch errors and permit valid values, but it > doesn't. If I enter an erroneous value the first time, and the second > time a good value, it doesn't break the loop. Why? > This is wrong: (style != 1) or (style != 2) For example, if style is 1 (which should be a valid value): (style != 1) or (style != 2) => (1 != 1) or (1 != 2) => False or True => True What you mean is: (style != 1) and (style != 2) From rtomek at ceti.com.pl Sun Aug 23 11:36:32 2009 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Sun, 23 Aug 2009 17:36:32 +0200 Subject: Is Python what I need? In-Reply-To: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: On Sun, 23 Aug 2009, newbie wrote: > Hi all > I'm interested in developing computer based, interactive programs for > students in a special school who have an aversion to pen and paper. > I've searched the net to find ready made software that will meet my > needs but it is either written to a level much higher than these > students can cope with or priced beyond our school budget. I came > across a blog of someone singing the praises of Python. My question is > therefore aimed at those that know what they are talking about (ie > users in this group). Is Python the language I need to learn to > develop these programs? Perhaps, maybe, yes. Python has simple syntax and it can be grasped quite fast. It is also quite easy IMHO to go from easy interactive, calculator-like stuff to bigger things. It also has quite big library of specialized functions, to be used in bigger programs. So if this is what you are looking for, it seems you are in the right place. You may also have a look at Squeak. It is an implementation of Smalltalk language. As far as I can tell, it is targeted for kid users or young students, who are interested in programming. http://en.wikipedia.org/wiki/Smalltalk http://www.squeak.org/ http://en.wikipedia.org/wiki/Squeak Or, I mean, Smalltalk is a general purpose language, just as Python. It is not a "kid language". Squeak, however, seems to be a bit easier for new users. After tinkering with it a little, I think it has few batteries not only included (like Python has) but connected to few toys as well. This makes it more playable than Python after unpacking the box. Wrt languages, their "goodness" or differences between them - I am pretty much sure a number of people will start pointing them out to you. But I don't think this is really that much important. All languages are more or less similar because they serve the same purpose. Just try and do not use (Visual) Basic :-) and you should be ok. Well, maybe this is just me, but I consider VB to be a dead-end. Besides, if this is going to be "let's show them how interesting it is", you should stay away from languages more complicated, like Java. Those who are going to learn Java, will learn it anyway. Knowing something different and cool first should not kill them. Quite the contrary, it can be an eye opener. Regards Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From gherron at islandtraining.com Sun Aug 23 11:37:26 2009 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 23 Aug 2009 08:37:26 -0700 Subject: Trying To Catch Invalid User Input In-Reply-To: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> References: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> Message-ID: <4A916236.6070007@islandtraining.com> Victor Subervi wrote: > Hi; > I have the following: > > style = raw_input('What style is this? (1 = short, 2 = long): ') > flag = 0 > while flag == 0: > if (style != 1) or (style != 2): > style = raw_input('There was a mistake. What style is this? (1 = > short, 2 = long): ') > else: > flag = 1 > > I would think this would catch errors and permit valid values, but it > doesn't. If I enter an erroneous value the first time, and the second > time a good value, it doesn't break the loop. Why? > TIA, > Victor First, raw_input will not return an integer, but rather characters, so the value of style will never be 1 or 2, but rather '1', or '2'. But even if you make your comparisons against '1' and '2', this will not work since you've also made a simple logic error. The conditional if (style != '1') or (style != '2'): will always be True no matter what value style has. For instance if style is '1', then the conditional evaluates like (False) or (True) which evaluates to True. You want one of the following: if (style != '1') and (style != '2'): or if not (style == '1' or style == '2'): or if style == '1' or style == '2': flag = 1 ... or if style in ['1','2']: flag = 1 ... or better yet dispense with flag altogether while style not in ['1','2']: style = raw_input('There was a mistake ... Gary Herron From python-url at phaseit.net Sun Aug 23 11:54:40 2009 From: python-url at phaseit.net (Gabriel Genellina) Date: Sun, 23 Aug 2009 15:54:40 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Aug 23) Message-ID: QOTW: "... [O]nce you accept that text is best handled in Unicode, there's little sense in making an exception for the limited subset that happens to be representable in ASCII." - Ben Finney http://groups.google.com/group/comp.lang.python/msg/accc8c2ae9d7ed15 Python 3.1.1 released: http://groups.google.com/group/comp.lang.python/t/f34c4b07a61f4414/ Parallelization in Python 2.6: http://groups.google.com/group/comp.lang.python/t/c8169c393e58a5d5/ 012=3D=3D10, a relic from ancient times, is finally gone: http://groups.google.com/group/comp.lang.python/t/3bc42fffb012635b/ How to ensure a method is actually implemented in a derived class: http://groups.google.com/group/comp.lang.python/t/42d0ec54b7683f23/ Is this community sexist? (Also, etymology of the word "guy" < "Guy" ~ "Guido") http://groups.google.com/group/comp.lang.python/t/7a190c24d8025bb4/ A "for" loop using range() is inefficient, but other Python variants are able to optimize it: http://groups.google.com/group/comp.lang.python/t/27df793be6f5675/ The scope of names inside a "class" statement: http://groups.google.com/group/comp.lang.python/t/4a244346dc9a5f15/ Counting how many times items from a set appear on a given list: http://groups.google.com/group/comp.lang.python/t/fb0580cefff96682/ Construct a dictionary from a list [key,value,key,value,...] (many recipes!): http://groups.google.com/group/comp.lang.python/t/e16e180b5f61f748/ And more recipes: format a number with thousand separators: http://groups.google.com/group/comp.lang.python/t/2eb729797f162a6e/ Code style: how to write a long conditional expression: http://groups.google.com/group/comp.lang.python/t/6876917a4d579d59/ On the concept of "functor" and how it may be applied to Python: http://groups.google.com/group/comp.lang.python/t/8fbc7ad2ec11841c/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiasts": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python Enjoy the *Python Magazine*. http://pymag.phparch.com/ *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From claird at lairds.us Sun Aug 23 11:55:11 2009 From: claird at lairds.us (Cameron Laird) Date: Sun, 23 Aug 2009 15:55:11 +0000 Subject: [Diversity] Language note References: <20090807143826.GA19246@panix.com> <12470af00908080943g1e559273sdd5e4fc92336a5eb@mail.gmail.com> Message-ID: In article , Rami Chowdhury wrote: > >> Most indian languages have a different >> grammer (compared to English). So i'm curious to see how that would be >> implemented in a parser > >+1 -- I'd be interested in seeing this too, although we have drifted >OT here and perhaps this conversation would be better had on Python- >list. The closest I've seen to a language being able to support >different grammatical structures is Perligata (http:// >www.csse.monash.edu.au/~damian/papers/HTML/Perligata.html), does >Python have anything similar? . . . Yes and no. There's considerably more to say on the subject than my own patience permits for now. Highlights, though: I regard it as a big deal whether a language permits Unicode in spelling variable names (Python 3 does, despite , and presumably you know the situation in Perl); languages like Lisp, Forth, and Tcl have minimal syntax, and rich traditions of construction of problem-specific "little languages", so it's common in them to see, for example, object orientation modeled with a variety of lexical orders; and my own favorite "little-language" work in Python has generally modeled VSO human languages. From bartc at freeuk.com Sun Aug 23 11:57:57 2009 From: bartc at freeuk.com (bartc) Date: Sun, 23 Aug 2009 15:57:57 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <9Gdkm.71135$OO7.46868@text.news.virginmedia.com> wrote in message news:h6r4fb$18a$1 at aioe.org... > In comp.lang.python James Harris wrote: >> On 22 Aug, 10:27, David <71da... at libero.it> wrote: > > ... >>> >>> What about 2_1011, 8_7621, 16_c26h or 2;1011, 8;7621, 16;c26h ? >> >> They look good - which is important. The trouble (for me) is that I >> want the notation for a new programming language and already use these >> characters. I have underscore as an optional separator for groups of >> digits - 123000 and 123_000 mean the same. > > Why not just use the space? 123 000 looks better than 123_000, and > is not syntactically ambiguous (at least in python). If the purpose is to allow "_" to introduce a non-base ten literal, using this to enter a hexadecimal number might result in: 16_1234 ABCD I'd say that that was ambiguous (depending on whether a name can follow a number; if you have a operator called ABCD, then that would be a problem). Unless each block of digits used it's own base: 16_1234 16_ABCD > And as it > already works for string literals, it could be applied to numbers, too? String literals are conveniently surround by quotes, so they're a bit easier to recognise. -- Bart From marduk at letterboxes.org Sun Aug 23 12:08:02 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 23 Aug 2009 12:08:02 -0400 Subject: Trying To Catch Invalid User Input In-Reply-To: <4A9161EA.5050602@mrabarnett.plus.com> References: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> <4A9161EA.5050602@mrabarnett.plus.com> Message-ID: <1251043682.19411.38.camel@centar.nbk> On Sun, 2009-08-23 at 16:36 +0100, MRAB wrote: > Victor Subervi wrote: > > Hi; > > I have the following: > > > > style = raw_input('What style is this? (1 = short, 2 = long): ') > > flag = 0 > > while flag == 0: > > if (style != 1) or (style != 2): > > style = raw_input('There was a mistake. What style is this? (1 = > > short, 2 = long): ') > > else: > > flag = 1 > > > > I would think this would catch errors and permit valid values, but it > > doesn't. If I enter an erroneous value the first time, and the second > > time a good value, it doesn't break the loop. Why? > > > This is wrong: > > (style != 1) or (style != 2) > > For example, if style is 1 (which should be a valid value): > > (style != 1) or (style != 2) > => (1 != 1) or (1 != 2) > => False or True > => True > > What you mean is: > > (style != 1) and (style != 2) Or (perhaps) better: VALID_STYLES = {1: 'short', 2: 'long'} style = None while style not in VALID_STYLES: style = raw_input('What style is this? %s: ' % str(VALID_STYLES).replace(':', ' =')) # also, raw_input() returns a string try: style = int(style) except ValueError: pass From Scott.Daniels at Acm.Org Sun Aug 23 12:12:50 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 23 Aug 2009 09:12:50 -0700 Subject: generate keyboard/mouse event under windows In-Reply-To: <9f107280-5d5c-4e6e-b47b-779e8012fdbc@h30g2000vbr.googlegroups.com> References: <96047669-1bfd-4dbe-bed8-fafea07bbc5a@z34g2000vbl.googlegroups.com> <9f107280-5d5c-4e6e-b47b-779e8012fdbc@h30g2000vbr.googlegroups.com> Message-ID: Ray wrote: > On Aug 19, 2:07 pm, yaka wrote: >> Read this and see if it helps: >> >> http://kvance.livejournal.com/985732.html > > is there a way to generate a 'true' keyboard event? (works like user > pressed a key on keyboard) > not send the 'send keyboard event to application' ? If there is such a spot, it is a major security weakness. You'd be able to automate password attacks. --Scott David Daniels Scott.Daniels at Acm.Org From jjposner at optimum.net Sun Aug 23 12:18:43 2009 From: jjposner at optimum.net (John Posner) Date: Sun, 23 Aug 2009 12:18:43 -0400 Subject: conditional for-statement In-Reply-To: References: Message-ID: <4A916BE3.5010804@optimum.net> >> Hi, >> >> i was wondering if there is a syntax alike: >> >> for i in range(10) if i > 5: >> print i >> > > You can write > > for i in filter(lambda i: i > 5, range(10)): > print i > > but > > for i in range(10): > if i > 5: > print i > > it' better readable, and > > for i in range(6,10): > print i > > it's event better. > > How about using a generator expression instead of a list? for i in (x for x in range(10) if x > 5): print i -John From koranthala at gmail.com Sun Aug 23 12:25:48 2009 From: koranthala at gmail.com (koranthala) Date: Sun, 23 Aug 2009 09:25:48 -0700 (PDT) Subject: can python make web applications? References: Message-ID: <7f0cc793-c4ae-4f7d-87a4-9471f640db89@y4g2000prf.googlegroups.com> On Aug 23, 8:12?pm, Deep_Feelings wrote: > can python make powerfull database web applications that can replace > desktop database applications? e.g: entrprise accounting > programs,enterprise human resource management programs ...etc Very much so. The web frameworks, Django & TurboGears are quite powerful and can be used to do what you just now mentioned. Check out Django - esp if the application is database centric. It has very good documentation and a free online book - djangobook. From victorsubervi at gmail.com Sun Aug 23 12:27:48 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 23 Aug 2009 11:27:48 -0500 Subject: Trying To Catch Invalid User Input In-Reply-To: <1251043682.19411.38.camel@centar.nbk> References: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> <4A9161EA.5050602@mrabarnett.plus.com> <1251043682.19411.38.camel@centar.nbk> Message-ID: <4dc0cfea0908230927m45420f3dxbae2c42c95540c59@mail.gmail.com> Really slick! Thanks! V On Sun, Aug 23, 2009 at 11:08 AM, Albert Hopkins wrote: > On Sun, 2009-08-23 at 16:36 +0100, MRAB wrote: > > Victor Subervi wrote: > > > Hi; > > > I have the following: > > > > > > style = raw_input('What style is this? (1 = short, 2 = long): ') > > > flag = 0 > > > while flag == 0: > > > if (style != 1) or (style != 2): > > > style = raw_input('There was a mistake. What style is this? (1 = > > > short, 2 = long): ') > > > else: > > > flag = 1 > > > > > > I would think this would catch errors and permit valid values, but it > > > doesn't. If I enter an erroneous value the first time, and the second > > > time a good value, it doesn't break the loop. Why? > > > > > This is wrong: > > > > (style != 1) or (style != 2) > > > > For example, if style is 1 (which should be a valid value): > > > > (style != 1) or (style != 2) > > => (1 != 1) or (1 != 2) > > => False or True > > => True > > > > What you mean is: > > > > (style != 1) and (style != 2) > > Or (perhaps) better: > > VALID_STYLES = {1: 'short', 2: 'long'} > > style = None > while style not in VALID_STYLES: > style = raw_input('What style is this? %s: ' % > str(VALID_STYLES).replace(':', ' =')) > > # also, raw_input() returns a string > try: > style = int(style) > except ValueError: > pass > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nmm1 at cam.ac.uk Sun Aug 23 12:34:16 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Sun, 23 Aug 2009 17:34:16 +0100 (BST) Subject: Python/Fortran interoperability References: <1032c78d-d4dd-41c0-a877-b85ca000d871@g31g2000yqc.googlegroups.com> Message-ID: In article <1032c78d-d4dd-41c0-a877-b85ca000d871 at g31g2000yqc.googlegroups.com>, sturlamolden wrote: >On 23 Aug, 12:35, n... at cam.ac.uk wrote: > >> I am interested in surveying people who want to interoperate between >> Fortran and Python to find out what they would like to be able to do >> more conveniently, especially with regard to types not supported for C >> interoperability by the current Fortran standard. =A0Any suggestions as t= >o >> other ways that I could survey such people (Usenet is no longer as >> ubiquitous as it used to be) would be welcomed. > >I think you will find that 99.9% of Python and Fortran programmers are >scientists and engineers that also use NumPy and f2py. Go to scipy.org >and ask your question on the numpy mailing list. > >Regards, >Sturla Molden > > > Thanks. I had forgotten they had a mailing list. Nick. From dmw at coder.cl Sun Aug 23 12:35:33 2009 From: dmw at coder.cl (Daniel Molina Wegener) Date: Sun, 23 Aug 2009 12:35:33 -0400 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module Message-ID: <2571343.k9db9GJWqV@coder.cl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Hello, I'm pleased to announce pyxser-1.2r, a Python-Object to XML serializer and deserializer. This module package it's completely written in C and licensed under LGPLv3. The tested Python versions are 2.5.X and 2.7.X. * home page: ? http://coder.cl/software/pyxser * hosted at: ? http://sourceforge.net/projects/pyxser/ * pypi entry: ? http://pypi.python.org/pypi?:action=display&name=pyxser&version=1.2r The current ChangeLog is as follows: - -----8<----------8<----------8<----------8<----- 1.2r (2009.08.23): ? ? ? ? Daniel Molina Wegener ? ? ? ? * Added encoded serialization of Unicode strings by using ? ? ? ? the user defined encoding as is passed to the serialization ? ? ? ? functions as enc parameter ? ? ? ? * Refactored some functions to allow more ordered code. - -----8<----------8<----------8<----------8<----- As you see, now Unicode strings are serialized as encoded byte string by using the encoding that the user pass as enc parameter to the serialization function. This means that Unicode strings are serialized in a human readable form, regarding a better interoperability with other platforms. Best regards... - -- ?.O. | Daniel Molina Wegener ? | FreeBSD & Linux ?..O | dmw [at] coder [dot] cl | Open Standards ?OOO | http://coder.cl/ ? ? ? ?| FOSS Developer -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (FreeBSD) iQIcBAEBCgAGBQJKkW/VAAoJEHxqfq6Y4O5N36oP/3iV+D9YUgLStFoZiJvb5b7x +UyrfyWpg6oxqeH4oOUVmyrWYlIaM3IStOtCayYEIrRJeg7FfHM8rvUV89FhDgVy xb/4R9UyqSOqcev/edmXvhbUKfOjUDu/kaKNjK4HiI3Ewh6BBjxbythZSQ/BcvGc OzAsZU9bACbuTuiYLumoum/KjRg/13Tzc8R+xhugJ7fjqH94kWGmUN8l8E/DU7O1 IULm4da4y4mPzhdyIxIGzncOGEZmQLLcv7jYcMVBvkuXe8Ar0WlGQ6YjyvQMLVlz KBn5JiNC1/gzImQXXDfT2u454gyH86i7BRtOCk0RbUmTVFsQ32wjnF0u4bngrtm7 3dD0WVIWV/n/27UZtYte3YlVoHzYu+M6TsX9vwhxvg4SHvg74XigXuXgD8vWQxGE FP6YENbHOND3oSNJIRO9368irvCbYrcpndtYBLyyDlfwdN5YTAME+Z5eEGvl4j4P D7aPryOKCzklxv33qtA1si6f//4JPqdKHGXnl8ysPC7QWh6u+ImmYFYj2kAu7l/N PfUvf8hfQqWOz53W4AuFGg5u+L29TIMUUvxc4r446SFdLUZEaHueJ5GQ0G8uNF/B QoWUnwynLlasyeo+JTcrG9NBgm85QfT3jDd+z4Zba9yWCqojymOpVCQ5duKifMb3 x9fc1ulI44AGNAv+UhnB =4C1g -----END PGP SIGNATURE----- From foo at bar.invalid Sun Aug 23 13:06:48 2009 From: foo at bar.invalid (JB) Date: Sun, 23 Aug 2009 20:06:48 +0300 (EEST) Subject: Python/Fortran interoperability References: Message-ID: ["Followup-To:" header set to comp.lang.fortran.] On 2009-08-23, nmm1 at cam.ac.uk wrote: > > I am interested in surveying people who want to interoperate between > Fortran and Python to find out what they would like to be able to do > more conveniently, especially with regard to types not supported for C > interoperability by the current Fortran standard. Any suggestions as to > other ways that I could survey such people (Usenet is no longer as > ubiquitous as it used to be) would be welcomed. > > My Email address is real, so direct messages will be received. > > Specifically, I should like to know the answers to the following > questions: > > 1) Do you want to use character strings of arbitrary length? As in, a signed C int (that most Fortran implementations use to keep track of string lengths) may not be sufficient? No, I'm not particularly interested in that. > 2) Do you want to use Python classes with list members, where the > length of the list is not necessarily fixed for all instances of the > class? Or, equivalently, Fortran derived types containing allocatable > or pointer arrays? Yes. > 2) Do you want to use Fortran derived types or Python classes that > contain type-bound procedures (including finalizers)? Please answer > "yes" whether or nor you would like to call those type-bound procedures > from the other language. In python I use it all the time, haven't used any F2003 OOP features yet. > 4) Do you want to call functions where the called language allocates > or deallocates arrays/lists/strings for use by the calling language? > Note that this is specifically Fortran->Python and Python->Fortran. Yes. Generally speaking, f2py today is not that bad, though it's getting long in the tooth. There is a project called fwrap that aims to create an improved python/Fortran bridge: http://conference.scipy.org/static/wiki/smith_fwrap.pdf This project uses ISO_C_BINDING, and I think that this is the correct approach rather than trying to keep up with whatever ABI's all those Fortran compilers use. So from the Fortran side of the fence, I suppose the path forward would be to improve on the C binding functionality (this would also of course benefit other language bindings than just python). Whether TR 29113 is the right path forward or not I have no strong opinion on. Specifically what's needed is some way to portably access the array descriptor data, and maybe also how to access the OOP functionality in a standardized way. The experience with C++ ABI's suggests that this might not be as straightforward as it sounds. -- JB From matthew at woodcraft.me.uk Sun Aug 23 13:23:06 2009 From: matthew at woodcraft.me.uk (Matthew Woodcraft) Date: Sun, 23 Aug 2009 17:23:06 GMT Subject: Most "active" coroutine library project? References: <64183b73-9cb0-4ce1-98d0-f47e13a818e4@f37g2000yqn.googlegroups.com> Message-ID: <87ab1qfnr9.fsf@golux.woodcraft.me.uk> Phillip B Oldham writes: > I've been taking a look at the multitude of coroutine libraries > available for Python, but from the looks of the projects they all seem > to be rather "quiet". I'd like to pick one up to use on a current > project but can't deduce which is the most popular/has the largest > community. > > Libraries I looked at include: cogen, weightless, eventlet and > circuits (which isn't exactly coroutine-based but it's event-driven > model was intriguing). > > Firstly, are there any others I've missed? There's greenlets http://pypi.python.org/pypi/greenlet which I think is also fairly described as "quiet". -M- From james.harris.1 at googlemail.com Sun Aug 23 14:11:36 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Sun, 23 Aug 2009 11:11:36 -0700 (PDT) Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: <583bb6bd-9723-4ff7-bc0e-d58782cf9296@k30g2000yqf.googlegroups.com> On 21 Aug, 00:59, James Harris wrote: ... > > Is there some magic to make the 2.x CPython interpreter to ignore the > > annoying octal notation? > > I'd really like 012 to be "12" and not "10". > > This is (IMHO) a sad hangover from C (which took it from B ... This seemed worth writing up so I've taken the snipped comments and posted them at http://sundry.wikispaces.com/octal-zero-prefix The idea is that the page can be pointed to any time the issue comes up again. I've also fleshed the comments out a bit. James From aahz at pythoncraft.com Sun Aug 23 14:12:00 2009 From: aahz at pythoncraft.com (Aahz) Date: 23 Aug 2009 11:12:00 -0700 Subject: Polling a net address References: <99ddf4e1-d327-4fb1-aee4-aa881de3b3af@d23g2000vbm.googlegroups.com> Message-ID: In article <99ddf4e1-d327-4fb1-aee4-aa881de3b3af at d23g2000vbm.googlegroups.com>, Iain wrote: > >I'm writing a system tray application for windows, and the app needs >to poll a remote site at a pre-defined interval, and then process any >data returned. > >The GUI needs to remain responsive as this goes on, so the polling >needs to be done in the background. I've been looking into Twisted as >a way of achieving this, but can't seem to get anything to loop >successfully. > >Does anyone have any pointers that they might be able to give me? You might prefer trying out threads instead; there's a simple Tkinter example in http://www.pythoncraft.com/OSCON2001/index.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From stefaan.himpe at gmail.com Sun Aug 23 14:32:04 2009 From: stefaan.himpe at gmail.com (Stefaan Himpe) Date: Sun, 23 Aug 2009 20:32:04 +0200 Subject: can python make web applications? In-Reply-To: References: Message-ID: Deep_Feelings wrote: > can python make powerfull database web applications that can replace > desktop database applications? e.g: entrprise accounting > programs,enterprise human resource management programs ...etc In addition to the recommendations by other people, I'd like to recommend the very easy to learn and use web2py. (www.web2py.com). From nmm1 at cam.ac.uk Sun Aug 23 14:42:51 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Sun, 23 Aug 2009 19:42:51 +0100 (BST) Subject: Python/Fortran interoperability References: Message-ID: In article , JB wrote: >["Followup-To:" header set to comp.lang.fortran.] Sorry - set back again, because you don't provide an Email address, and there's a significant issue. Thanks for the response. >> 1) Do you want to use character strings of arbitrary length? > >As in, a signed C int (that most Fortran implementations use to keep >track of string lengths) may not be sufficient? No, I'm not >particularly interested in that. No, I mean things like 'Kilroy was here'. Currently, Fortran's C interoperability supports only strings of length 1, and you have to kludge them up as arrays. That doesn't work very well, especially for things like function results. >Generally speaking, f2py today is not that bad, though it's getting >long in the tooth. There is a project called fwrap that aims to create >an improved python/Fortran bridge: Thanks. I will look at that. >This project uses ISO_C_BINDING, and I think that this is the correct >approach rather than trying to keep up with whatever ABI's all those >Fortran compilers use. So from the Fortran side of the fence, I >suppose the path forward would be to improve on the C binding >functionality (this would also of course benefit other language >bindings than just python). Whether TR 29113 is the right path forward >or not I have no strong opinion on. Specifically what's needed is some >way to portably access the array descriptor data, and maybe also how >to access the OOP functionality in a standardized way. The experience >with C++ ABI's suggests that this might not be as straightforward as >it sounds. That is precisely what I am investigating. TR 29113 falls a LONG way before it gets to any of the OOP data - indeed, you can't even pass OOP derived types as pure data (without even the functionality) in its model. Nor most of what else Python would expect. Regards, Nick Maclaren. From rami.chowdhury at gmail.com Sun Aug 23 14:48:50 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Sun, 23 Aug 2009 11:48:50 -0700 Subject: Questions on XML In-Reply-To: <97c638a50908221327ge57818ahc1bb4c9ad3eb186b@mail.gmail.com> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <97c638a50908221327ge57818ahc1bb4c9ad3eb186b@mail.gmail.com> Message-ID: <200908231148.51151.rami.chowdhury@gmail.com> My problem is with IDLE on Windows. When I try to type Bangla directly into the IDLE window I only get '?' characters, and repr() fails with a UnicodeDecodeError. I expect, though, that that's because of my specific installation / Windows issues, as it works fine on Fedora 10... > I do not get any problem in processing Hindi or Bangla or any Indian > language in Python it is perfectly fine. I have no problems either -- my issues are with IDLE, and only on Windows. ---- Rami Chowdhury "Strangers are just friends who haven't had enough gin." -- Howdle's Saying 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Saturday 22 August 2009 13:27:02 SUBHABRATA BANERJEE wrote: > Should I help you? If you answered my questions I am differing from your > view I do not get any problem in processing Hindi or Bangla or any Indian > language in Python it is perfectly fine. > Best Regards, > Subhabrata. > > On Sat, Aug 22, 2009 at 9:48 AM, Rami Chowdhury wrote: > > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > > > >> use Python to help me in this regard? > > > > I can say from experience that Python on Windows (at least, Python 2.5 on > > 32-bit Vista) works perfectly well with UTF-8 files containing Bangla. I > > have had trouble with working with the data in IDLE, however, which seems > > to prefer ASCII by default. > > > > ------------- > > Rami Chowdhury > > "Never assume malice when stupidity will suffice." -- Hanlon's Razor > > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > > > > > > > > > > > > On Aug 21, 2009, at 19:15 , joy99 wrote: > > > > Dear Group, > > > >> I like to convert some simple strings of natural language to XML. May > >> I use Python to do this? If any one can help me, on this. > >> > >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > >> use Python to help me in this regard? > >> > >> How can I learn good XML aspects of Python. If any one can kindly name > >> me a book or URL. > >> > >> I am using Python2.6 on Windows XP with IDLE as GUI. > >> > >> Best Regards, > >> Subhabrata. > >> -- > >> http://mail.python.org/mailman/listinfo/python-list From stefan_ml at behnel.de Sun Aug 23 14:52:16 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Aug 2009 20:52:16 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <4a918fe0$0$30226$9b4e6d93@newsspool1.arcor-online.net> Simon Brunning wrote: > 2009/8/11 Robert Dailey: >> On Aug 11, 3:40 pm, Bearophile wrote: >>> There are gals too here. >> It's a figure of speech. And besides, why would I want programming >> advice from a woman? lol. Thanks for the help. > > Give the attitudes still prevalent in our industry (cf > and many more), I'm sorry to say that I > don't think this is funny. Me neither. I used to reply with comments like "you just missed more than half of the world's population" to people who started their postings with "hi guys!", and I stopped doing that as a) it became too tiring, especially on a potentially-for-newbees group like c.l.py, and b) to many people it actually *is* a figure of speech. But reading statements like the above really makes me feel that it's best to comment even on simple things like "hi guys!". Stefan From stefan_ml at behnel.de Sun Aug 23 15:11:57 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Aug 2009 21:11:57 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: <4a91947d$0$30226$9b4e6d93@newsspool1.arcor-online.net> Jean-Michel Pichavant wrote: > Grant Edwards wrote: >> On 2009-08-18, Simon Forman wrote: >>> Sexism, racism, homophobia, religious intolerance, etc., all >>> stem from a fundamental forgetfulness of our Unity in God (as >>> I would put it) and this is perhaps the single greatest cause >>> of human misery. >> >> You mean the single greatest cause of human misery isn't >> Microsoft Windows? >> > No, emacs is responsible ! Hail to Vi ! Heck, where's Godwin's law when you need it? Stefan From stefan_ml at behnel.de Sun Aug 23 15:25:51 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Aug 2009 21:25:51 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <62dbf088-4510-40d0-af3e-3feeb291d6e4@t13g2000yqt.googlegroups.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> <86bb893a-344a-4c7b-9fc6-67d9f42c7607@q14g2000vbi.googlegroups.com> <62dbf088-4510-40d0-af3e-3feeb291d6e4@t13g2000yqt.googlegroups.com> Message-ID: <4a9197c0$0$30226$9b4e6d93@newsspool1.arcor-online.net> Mensanator wrote: > asking how many Jews you can fit into a Volswagen. None, because it's already full. (or "voll" as those who design Volkswagens would put it...) Stefan From voodoorai2000 at gmail.com Sun Aug 23 15:47:21 2009 From: voodoorai2000 at gmail.com (Raimond Garcia) Date: Sun, 23 Aug 2009 21:47:21 +0200 Subject: Is python faster than java? Message-ID: I'm building a large application, kind of fancy python but I'm concerned about speed. Cheers Peter -------------- next part -------------- An HTML attachment was scrubbed... URL: From pengyu.ut at gmail.com Sun Aug 23 15:54:15 2009 From: pengyu.ut at gmail.com (Peng Yu) Date: Sun, 23 Aug 2009 12:54:15 -0700 (PDT) Subject: Combining python and perl References: <743337bf-487f-434d-b15c-4b675b6487f4@d21g2000vbm.googlegroups.com> Message-ID: On Aug 23, 8:00?am, Albert Hopkins wrote: > On Sun, 2009-08-23 at 05:37 -0700, Peng Yu wrote: > > Hi, > > > According tohttp://www.python.org/doc/essays/comparisons.html, it > > says > > > "Python and Perl come from a similar background (Unix scripting, which > > both have long outgrown), and sport many similar features, but have a > > different philosophy. Perl emphasizes support for common application- > > oriented tasks, e.g. by having built-in regular expressions, file > > scanning and report generating features. Python emphasizes support for > > common programming methodologies such as data structure design and > > object-oriented programming, and encourages programmers to write > > readable (and thus maintainable) code by providing an elegant but not > > overly cryptic notation. As a consequence, Python comes close to Perl > > but rarely beats it in its original application domain; however Python > > has an applicability well beyond Perl's niche." > > > My question is that how to combine both python and perl to take > > advantages of both their strong aspects. Of course, I want to > > primarily use python---that is why I send this message to this group. > > I'm not sure why you'd want to "combine" them. ?You can pretty much do > the same things with both language, it's just that one may emphasize one > thing or make it easier for the user than the other. ?For example, > regular expressions in Perl. ?It's built into the language, but that > doesn't mean Python doesn't have regular expressions, just that Python > is less "centered" around them. ?If you want to use regular expressions > with Python just "import re". I understand that the sames things can be done with both language. But I do think that certain applications can be done faster (in term of the coding & debugging time, I don't care runtime here) with one language than with another. Therefore, for any give problem, it is meaningful to decide, based on the time to write and debug the code, which part should be programmed with perl and which part should be programed with python. However, when I split the code in perl and python, the problem of the integration is introduced, which incur additional coding and maintenance cost. I am sure that somebody must has already encounter the similar situation like I described above. I am wondering whether there are any advices on how to take advantages of both languages to speed up the code development time and reduce maintenance cost. Regards, Peng From emile at fenx.com Sun Aug 23 15:59:37 2009 From: emile at fenx.com (Emile van Sebille) Date: Sun, 23 Aug 2009 12:59:37 -0700 Subject: Is python faster than java? In-Reply-To: References: Message-ID: On 8/23/2009 12:47 PM Raimond Garcia said... > I'm building a large application, What kind of application? > kind of fancy python but I'm concerned > about speed. Speed of what? Development? User interaction? Responsiveness to queries? Mostly, you should worry about speed later. Writing it in python is probably faster than java. Then optimize the slow bits once you've identified where its needed. Emile From brannerchinese at gmail.com Sun Aug 23 16:13:16 2009 From: brannerchinese at gmail.com (David Prager Branner) Date: Sun, 23 Aug 2009 13:13:16 -0700 (PDT) Subject: web frameworks that support Python 3 Message-ID: I use Chinese and therefore Unicode very heavily, and so Python 3 is an unavoidable choice for me. But I'm frustrated by the fact that Django, Pylons, and TurboGears do not support Python 3 yet and (according to their development websites) will not for a very long time to come. So I am asking for recommendations for web frameworks that support Python 3. I am running Ubuntu 9.04 (Jaunty). Thanks! From max at alcyone.com Sun Aug 23 16:14:41 2009 From: max at alcyone.com (Erik Max Francis) Date: Sun, 23 Aug 2009 13:14:41 -0700 Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: References: Message-ID: Ryniek90 wrote: > I've got my backup script which opens tarfile for add chosen file to it. > But while setting it up, i've got Traceback: > here's the url: -->http://paste.ubuntu.com/258081/<-- > > I have searched among google's result but didn't found anything useful. > Only found info that it may be the backslashes fault in path, but i have > written proper the path. > > Here's link to my script paste: http://paste.ubuntu.com/258087/ > > Is its the '|\U' literal fault in path '|C:\\Users\\Ryniek's > WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2|' ? > > Sorry if i'm annoying but i'm still learning. It's probably a misleading error from the OS; I would guess the problem is that the filename contains colons, which I believe is a no-no on Windows. You want to make sure to always escape your backslashes (or use raw strings), too, or that's going to bite you sometime later (but it's not your main problem here). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Every human being is a problem in search of a solution. -- Ashley Montague From marduk at letterboxes.org Sun Aug 23 16:32:09 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 23 Aug 2009 16:32:09 -0400 Subject: web frameworks that support Python 3 In-Reply-To: References: Message-ID: <1251059529.12426.23.camel@centar.nbk> On Sun, 2009-08-23 at 13:13 -0700, David Prager Branner wrote: > I use Chinese and therefore Unicode very heavily, and so Python 3 is > an unavoidable choice for me. But I'm frustrated by the fact that > Django, Pylons, and TurboGears do not support Python 3 yet and > (according to their development websites) will not for a very long > time to come. > > So I am asking for recommendations for web frameworks that support > Python 3. I am running Ubuntu 9.04 (Jaunty). Python 2.x has Unicode. In fact Django and the like use unicode heavily. What's different about Python 3 is that there is only unicode strings, whereas Python 2 has a string type and a unicode type. So it's not true that Python 3 is an unavoidable choice for using unicode. From basti.wiesner at gmx.net Sun Aug 23 16:34:50 2009 From: basti.wiesner at gmx.net (Sebastian Wiesner) Date: Sun, 23 Aug 2009 22:34:50 +0200 Subject: web frameworks that support Python 3 In-Reply-To: References: Message-ID: <200908232234.58373.basti.wiesner@gmx.net> At Sunday 23 August 2009 22:13:16 you wrote: > I use Chinese and therefore Unicode very heavily, and so Python 3 is > an unavoidable choice for me. Python 2.x supports Unicode just as well as Python 3. Every common web framework works perfectly with unicode. In any case, there is bottle [1], which provides a *very minimal* framework for WSGI web development. Don't expect too much, it is really small, and doesn't do much more than routing and minimal templating. However, it is the only Python-3-compatible web framework I know of. [1] http://bottle.paws.de/page/start -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 205 bytes Desc: This is a digitally signed message part. URL: From marduk at letterboxes.org Sun Aug 23 16:34:55 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 23 Aug 2009 16:34:55 -0400 Subject: Combining python and perl In-Reply-To: References: <743337bf-487f-434d-b15c-4b675b6487f4@d21g2000vbm.googlegroups.com> Message-ID: <1251059695.12426.27.camel@centar.nbk> On Sun, 2009-08-23 at 12:54 -0700, Peng Yu wrote: > I understand that the sames things can be done with both language. > > But I do think that certain applications can be done faster (in term > of the coding & debugging time, I don't care runtime here) with one > language than with another. Yes, and usually that application is written in that language *or* the other. > Therefore, for any give problem, it is > meaningful to decide, based on the time to write and debug the code, > which part should be programmed with perl and which part should be > programed with python. However, when I split the code in perl and > python, the problem of the integration is introduced, which incur > additional coding and maintenance cost. > Couldn't agree more. > I am sure that somebody must has already encounter the similar > situation like I described above. I am wondering whether there are any > advices on how to take advantages of both languages to speed up the > code development time and reduce maintenance cost. Perhaps you need to give more specific criteria. I've worked on a few projects where different languages are used, but in different "domains". For example, the client may be written in Python but the server written in Java or PHP. Or different subsystems written in different languages. For example, the workflow engine may be written in Python but the batch processor written in C. However in these cases, for the most part, the systems themselves are monolingual though they communicate with each other using well-defined, common interfaces (e.g. TCP/IP, XMLRPC, HL7, etc.). If, however, you are thinking of writing a sub-system in multiple languages (ala permodule, for example), you are in for a world of hurt. Not only will the code be difficult to maintain yourself, it will be difficult for others to maintain/understand it. Most people don't say things like "Well I'm going to write all the 'object' stuff in Python but all the string processing in Perl. What usually motivates people to write systems in multiple languages are: * Availability of third-party libraries in a certain language. * Combining separate systems written in different languages. * Developer's capabilities in one language or the other * External dependencies (e.g. need to to have a plugin system for people to program in Python). * Performance. * Other types of "glue" (e.g. installation scripts need to be written in Perl, test system is Java based so CI scripts need to be in Java). permodule is nice for "simple" or "one-off" kind of stuff (or for any of the above reasons). But any reasonably-sized application using something like that throughout is going to be a maintenance nightmare. From sdementen at gmail.com Sun Aug 23 16:36:10 2009 From: sdementen at gmail.com (seb) Date: Sun, 23 Aug 2009 13:36:10 -0700 (PDT) Subject: conditional for-statement References: Message-ID: On Aug 23, 6:18?pm, John Posner wrote: > >> Hi, > > >> i was wondering if there is a syntax alike: > > >> for i in range(10) if i > 5: > >> ? ? print i > > > You can write > > > for i in filter(lambda i: i > 5, range(10)): > > ? ? print i > > > but > > > for i in range(10): > > ? ? if i > 5: > > ? ? ? ? print i > > > it' better readable, and > > > for i in range(6,10): > > ? ? print i > > > it's event better. > > How about using a generator expression instead of a list? > > ? for i in (x for x in range(10) if x > 5): > ? ? ? print i > > -John Indeed, but we could have the same syntax than for generators but directly in the for statement as in for variable in generator if condition: body Is there a special reason for not doing so ? A rejected PEP ? From stefan_ml at behnel.de Sun Aug 23 16:43:20 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Aug 2009 22:43:20 +0200 Subject: web frameworks that support Python 3 In-Reply-To: References: Message-ID: <4a91a9e8$0$30226$9b4e6d93@newsspool1.arcor-online.net> David Prager Branner wrote: > I use Chinese and therefore Unicode very heavily, and so Python 3 is > an unavoidable choice for me. As others noted before, this statement is not true by itself. > But I'm frustrated by the fact that > Django, Pylons, and TurboGears do not support Python 3 yet and > (according to their development websites) will not for a very long > time to come. http://wiki.python.org/moin/PortingDjangoTo3k Stefan From pyklass at gmail.com Sun Aug 23 16:45:17 2009 From: pyklass at gmail.com (Goke Aruna) Date: Sun, 23 Aug 2009 21:45:17 +0100 Subject: can python make web applications? In-Reply-To: References: Message-ID: <30ef32480908231345l1d3f96eqb59825fdd2d2e1cd@mail.gmail.com> A lot check this fantastic open source application, http://www.openerp.com, all done is python. On 8/23/09, Stefaan Himpe wrote: > Deep_Feelings wrote: >> can python make powerfull database web applications that can replace >> desktop database applications? e.g: entrprise accounting >> programs,enterprise human resource management programs ...etc > > In addition to the recommendations by other people, I'd like to > recommend the very easy to learn and use web2py. (www.web2py.com). > -- > http://mail.python.org/mailman/listinfo/python-list > -- Sent from my mobile device From voodoorai2000 at gmail.com Sun Aug 23 16:49:32 2009 From: voodoorai2000 at gmail.com (Raimond Garcia) Date: Sun, 23 Aug 2009 22:49:32 +0200 Subject: Is python faster than java? In-Reply-To: References: Message-ID: Makes sense. +1 Cheers Peter On Sun, Aug 23, 2009 at 9:59 PM, Emile van Sebille wrote: > On 8/23/2009 12:47 PM Raimond Garcia said... > >> I'm building a large application, >> > > What kind of application? > > kind of fancy python but I'm concerned about speed. >> > > Speed of what? Development? User interaction? Responsiveness to queries? > Mostly, you should worry about speed later. Writing it in python is > probably faster than java. Then optimize the slow bits once you've > identified where its needed. > > Emile > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From james.harris.1 at googlemail.com Sun Aug 23 16:55:19 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Sun, 23 Aug 2009 13:55:19 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <4a90b50e.154654859@text.giganews.com> Message-ID: <9411f79a-934f-494c-93bc-dc020646f281@z24g2000yqb.googlegroups.com> On 23 Aug, 04:38, c... at tiac.net (Richard Harter) wrote: > On Sat, 22 Aug 2009 14:54:41 -0700 (PDT), James Harris > > > > > > wrote: > >On 22 Aug, 10:27, David <71da... at libero.it> wrote: > > >... (snipped a discussion on languages and other systems interpreting > >numbers with a leading zero as octal) > > >> > Either hexadecimal should have been 0h or octal should > >> > have been 0t :=3D) > > >> I have seen the use of Q/q instead in order to make it clearer. I still > >> prefer Smalltalk's 16rFF and 8r377. > > >> Two interesting options. In a project I have on I have also considered > >> using 0q as indicating octal. I maybe saw it used once somewhere else > >> but I have no idea where. 0t was a second choice and 0c third choice > >> (the other letters of oct). 0o should NOT be used for obvious reasons. > > >> So you are saying that Smalltalk has r where > >> r is presumably for radix? That's maybe best of all. It preserves the > >> syntactic requirement of starting a number with a digit and seems to > >> have greatest flexibility. Not sure how good it looks but it's > >> certainly not bad. > > I opine that a letter is better; special characters are a > valuable piece of real estate. Very very true. > ?However for floating point you > need at least three letters because a floating point number has > three parts: the fixed point point, the exponent base, and the > exponent. ?Now we can represent the radices of the individual > parts with the 'r'scheme, e.g., 2r101001, but we need separate > letters to designate the exponent base and the exponent. ?B and E > are the obvious choices, though we want to be careful about a > confusion with 'b' in hex. ?For example, using 'R', > > 3R20.1B2E16Rac Ooh err! > is 20.1 in trinary (6 1/3) times 2**172 (hex ac). > > I grant that this example looks a bit gobbledegookish, You think? :-) > but normal > usage would be much simpler. ?The notation doesn't handle > balanced trinary; however I opine that balanced trinary requires > special notation. When the programmer needs to construct such values how about allowing him or her to specify something like (20.1 in base 3) times 2 to the power of 0xac Leaving out how to specify (20.1 in base 3) for now this could be (20.1 in base 3) * 2 ** 0xac The compiler could convert this to a constant. James From sdementen at gmail.com Sun Aug 23 16:58:01 2009 From: sdementen at gmail.com (seb) Date: Sun, 23 Aug 2009 13:58:01 -0700 (PDT) Subject: conditional for-statement References: Message-ID: <9571ca2a-8559-403a-8ba5-aa6626f13ee6@32g2000yqj.googlegroups.com> On Aug 23, 10:36?pm, seb wrote: > On Aug 23, 6:18?pm, John Posner wrote: > > > > > > > >> Hi, > > > >> i was wondering if there is a syntax alike: > > > >> for i in range(10) if i > 5: > > >> ? ? print i > > > > You can write > > > > for i in filter(lambda i: i > 5, range(10)): > > > ? ? print i > > > > but > > > > for i in range(10): > > > ? ? if i > 5: > > > ? ? ? ? print i > > > > it' better readable, and > > > > for i in range(6,10): > > > ? ? print i > > > > it's event better. > > > How about using a generator expression instead of a list? > > > ? for i in (x for x in range(10) if x > 5): > > ? ? ? print i > > > -John > > Indeed, but we could have the same syntax than for generators but > directly in the for statement as in > for variable in generator if condition: > ? ? body > > Is there a special reason for not doing so ? A rejected PEP ?- Hide quoted text - > > - Show quoted text - I just found the same thread on the python ideas group at http://mail.python.org/pipermail/python-ideas/2009-April/004278.html sorry for reposting From clp2 at rebertia.com Sun Aug 23 17:02:16 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Aug 2009 14:02:16 -0700 Subject: conditional for-statement In-Reply-To: References: Message-ID: <50697b2c0908231402p1ff54041jba173c3e23ffab12@mail.gmail.com> On Sun, Aug 23, 2009 at 1:36 PM, seb wrote: > On Aug 23, 6:18?pm, John Posner wrote: >> >> Hi, >> >> >> i was wondering if there is a syntax alike: >> >> >> for i in range(10) if i > 5: >> >> ? ? print i >> >> > You can write >> >> > for i in filter(lambda i: i > 5, range(10)): >> > ? ? print i >> >> > but >> >> > for i in range(10): >> > ? ? if i > 5: >> > ? ? ? ? print i >> >> > it' better readable, and >> >> > for i in range(6,10): >> > ? ? print i >> >> > it's event better. >> >> How about using a generator expression instead of a list? >> >> ? for i in (x for x in range(10) if x > 5): >> ? ? ? print i >> >> -John > > Indeed, but we could have the same syntax than for generators but > directly in the for statement as in > for variable in generator if condition: > ? ?body > > Is there a special reason for not doing so ? A rejected PEP ? It's not been added since it's completely unnecessary (see the several alternatives already presented by others). There have been a few other mailinglist threads on adding essentially the same syntax. None have proved fruitful. Cheers, Chris -- http://blog.rebertia.com From james.harris.1 at googlemail.com Sun Aug 23 17:42:16 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Sun, 23 Aug 2009 14:42:16 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: On 23 Aug, 00:16, Mel wrote: > James Harris wrote: > > I have no idea why Ada which uses the # also apparently uses it to end > > a number > > > ? 2#1011#, 8#7621#, 16#c26b# > > Interesting. ?They do it because of this example from > : Thanks for providing an explanation. > > 2#1#E8 ? ? ? ? ? ? ? ? ? ?-- an integer literal of value 256 > > where the E prefixes a power-of-2 exponent, and can't be taken as a digit of > the radix. ?That is to say > > 16#1#E2 > > would also equal 256, since it's 1*16**2 . Here's another suggested number literal format. First, keep the familar 0x and 0b of C and others and to add 0t for octal. (T is the third letter of octal as X is the third letter of hex.) The numbers above would be 0b1011, 0t7621, 0xc26b Second, allow an arbitrary number base by putting base and number in quotes after a zero as in 0"2:1011", 0"8:7621", 0"16:c26b" This would work for arbitrary bases and allows an exponent to be tagged on the end. It only depends on zero followed by a quote mark not being used elsewhere. Finally, although it uses a colon it doesn't take it away from being used elsewhere in the language. Another option: 0.(2:1011), 0.(8:7621), 0.(16:c26b) where the three characters "0.(" begin the sequence. Comments? Improvements? James From james.harris.1 at googlemail.com Sun Aug 23 17:45:39 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Sun, 23 Aug 2009 14:45:39 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <4a90b50e.154654859@text.giganews.com> <9411f79a-934f-494c-93bc-dc020646f281@z24g2000yqb.googlegroups.com> Message-ID: On 23 Aug, 21:55, James Harris wrote: ... > > ?However for floating point you > > need at least three letters because a floating point number has > > three parts: the fixed point point, the exponent base, and the > > exponent. ?Now we can represent the radices of the individual > > parts with the 'r'scheme, e.g., 2r101001, but we need separate > > letters to designate the exponent base and the exponent. ?B and E > > are the obvious choices, though we want to be careful about a > > confusion with 'b' in hex. ?For example, using 'R', > > > 3R20.1B2E16Rac > > Ooh err! > > > is 20.1 in trinary (6 1/3) times 2**172 (hex ac). > > > I grant that this example looks a bit gobbledegookish, > > You think? :-) > > > but normal > > usage would be much simpler. ?The notation doesn't handle > > balanced trinary; however I opine that balanced trinary requires > > special notation. > > When the programmer needs to construct such values how about allowing > him or her to specify something like > > ? (20.1 in base 3) times 2 to the power of 0xac > > Leaving out how to specify (20.1 in base 3) for now this could be > > ? (20.1 in base 3) * 2 ** 0xac Using the suggestion from another post would convert this to 0.(3:20.1) * 2 ** 0xac > > The compiler could convert this to a constant. From phily05 at gmail.com Sun Aug 23 17:51:32 2009 From: phily05 at gmail.com (Phil) Date: Sun, 23 Aug 2009 14:51:32 -0700 (PDT) Subject: __import__(x) VS __import__(x, {}, {}, ['']) Message-ID: I am trying to understand the difference between __import__(x) and __import__(x, {}, {}, ['']). The documentations wording was a bit weird for me to understand: "The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement." Does that mean it passes in the globals by default, or does the above statement stand true only if globals() is passed in? From mwilson at the-wire.com Sun Aug 23 18:05:44 2009 From: mwilson at the-wire.com (Mel) Date: Sun, 23 Aug 2009 18:05:44 -0400 Subject: conditional for-statement References: Message-ID: seb wrote: > On Aug 23, 6:18 pm, John Posner wrote: [ ... ] >> How about using a generator expression instead of a list? >> >> for i in (x for x in range(10) if x > 5): >> print i >> >> -John > > Indeed, but we could have the same syntax than for generators but > directly in the for statement as in > for variable in generator if condition: > body > > Is there a special reason for not doing so ? A rejected PEP ? Well, the Zen of Python does say There should be one-- and preferably only one --obvious way to do it. Beyond that, I refer you to Gerald M. Weinberg's _The Psychology of Computer Programming_, specifically chapters 11 and 12, about Programming Languages, and their design. The proposal creates an case where one particular pair of syntactic constructs can be mooshed together. OK for them, but everything else becomes an exception; what about while a==c if b != d: why not if b != d while a==c: or for a in range(7) if os.name == 'posix': It winds up burdening the programmers with remembering which constructs are and which are not mooshable. Weinberg gave an example: FORTRAN had some stringent rules for what expressions were and were not allowed as array subscripts. The result was that many programmers couldn't remember all the rules, and often avoided using legal forms, having forgotten they were legal. Maybe the line was already crossed when list comprehensions came into being, still, the damage is localized in a particular context: building a list. It isn't out creating wild options in the program control flow at large. Mel. From voodoorai2000 at gmail.com Sun Aug 23 18:07:31 2009 From: voodoorai2000 at gmail.com (Raimond Garcia) Date: Mon, 24 Aug 2009 00:07:31 +0200 Subject: What is the recommended library for xml parsing? Message-ID: Is there a good build in library or should I use a third party one? Cheers, Peter -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sun Aug 23 18:15:55 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 23 Aug 2009 23:15:55 +0100 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <4A91BF9B.9080100@mrabarnett.plus.com> James Harris wrote: > On 23 Aug, 00:16, Mel wrote: >> James Harris wrote: >>> I have no idea why Ada which uses the # also apparently uses it to end >>> a number >>> 2#1011#, 8#7621#, 16#c26b# >> Interesting. They do it because of this example from >> : > > Thanks for providing an explanation. > >> 2#1#E8 -- an integer literal of value 256 >> >> where the E prefixes a power-of-2 exponent, and can't be taken as a digit of >> the radix. That is to say >> >> 16#1#E2 >> >> would also equal 256, since it's 1*16**2 . > > Here's another suggested number literal format. First, keep the > familar 0x and 0b of C and others and to add 0t for octal. (T is the > third letter of octal as X is the third letter of hex.) The numbers > above would be > > 0b1011, 0t7621, 0xc26b > > Second, allow an arbitrary number base by putting base and number in > quotes after a zero as in > > 0"2:1011", 0"8:7621", 0"16:c26b" > Why not just put the base first, followed by the value in quotes: 2"1011", 8"7621", 16"c26b" > This would work for arbitrary bases and allows an exponent to be > tagged on the end. It only depends on zero followed by a quote mark > not being used elsewhere. Finally, although it uses a colon it doesn't > take it away from being used elsewhere in the language. > > Another option: > > 0.(2:1011), 0.(8:7621), 0.(16:c26b) > > where the three characters "0.(" begin the sequence. > > Comments? Improvements? > From aahz at pythoncraft.com Sun Aug 23 18:44:01 2009 From: aahz at pythoncraft.com (Aahz) Date: 23 Aug 2009 15:44:01 -0700 Subject: logging SMTPhandler Error References: <60de8d40-61f4-4ffd-bcef-749bf06675d0@k19g2000yqn.googlegroups.com> Message-ID: In article , Dennis Lee Bieber wrote: >On 23 Aug 2009 06:14:00 -0700, aahz at pythoncraft.com (Aahz) declaimed the >following in gmane.comp.python.general: >> >> Slightly expanded: most mail servers accept connections from any other >> mail server for addresses that are hosted by them. The MX address for a >> domain tells you what mail server hosts that address. By connecting >> directly to the MX, your script is essentially acting as a mail server >> itself. > > But is not possible if one's ISP blocks pass-through SMTP >connections. Correct, but the OP said that zir ISP did not have a mailserver; AFAIK all ISPs that block SMTP have their own mailserver that you can point at instead. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From Scott.Daniels at Acm.Org Sun Aug 23 18:50:29 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 23 Aug 2009 15:50:29 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: James Harris wrote:... > Another option: > > 0.(2:1011), 0.(8:7621), 0.(16:c26b) > > where the three characters "0.(" begin the sequence. > > Comments? Improvements? I did a little interpreter where non-base 10 numbers (up to base 36) were: .7.100 == 64 (octal) .9.100 == 100 (decimal) .F.100 == 256 (hexadecimal) .1.100 == 4 (binary) .3.100 == 9 (trinary) .Z.100 == 46656 (base 36) Advantages: Tokenizer can recognize chunks easily. Not visually too confusing, No issue of what base the base indicator is expressed in. --Scott David Daniels Scott.Daniels at Acm.Org From clp2 at rebertia.com Sun Aug 23 18:59:35 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Aug 2009 15:59:35 -0700 Subject: What is the recommended library for xml parsing? In-Reply-To: References: Message-ID: <50697b2c0908231559vf6c42dcn321296edd7d033b7@mail.gmail.com> On Sun, Aug 23, 2009 at 3:07 PM, Raimond Garcia wrote: > Is there a good build in library or should I use a third party one? xml.etree.ElementTree: http://docs.python.org/library/xml.etree.elementtree.html Cheers, Chris -- http://blog.rebertia.com From bartc at freeuk.com Sun Aug 23 19:04:37 2009 From: bartc at freeuk.com (bartc) Date: Sun, 23 Aug 2009 23:04:37 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> "Scott David Daniels" wrote in message news:kN2dnSZR5b0BWAzXnZ2dnUVZ_s-dnZ2d at pdx.net... > James Harris wrote:... >> Another option: >> >> 0.(2:1011), 0.(8:7621), 0.(16:c26b) >> >> where the three characters "0.(" begin the sequence. >> >> Comments? Improvements? > > I did a little interpreter where non-base 10 numbers > (up to base 36) were: > > .7.100 == 64 (octal) > .9.100 == 100 (decimal) > .F.100 == 256 (hexadecimal) > .1.100 == 4 (binary) > .3.100 == 9 (trinary) > .Z.100 == 46656 (base 36) > Advantages: > Tokenizer can recognize chunks easily. > Not visually too confusing, > No issue of what base the base indicator is expressed in. It can be assumed however that .9. isn't in binary? That's a neat idea. But an even simpler scheme might be: .octal.100 .decimal.100 .hex.100 .binary.100 .trinary.100 until it gets to this anyway: .thiryseximal.100 -- Bartc From sjmachin at lexicon.net Sun Aug 23 19:04:55 2009 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Aug 2009 23:04:55 +0000 (UTC) Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in =?utf-8?b?d2luZG93cwl4cA==?= while making tarfile References: Message-ID: Erik Max Francis alcyone.com> writes: > > Ryniek90 wrote: > > Is its the '|\U' literal fault in path '|C:\\Users\\Ryniek's > > WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2|' ? What is "the '|\U' literal fault" ??? > > It's probably a misleading error from the OS; I would guess the problem > is that the filename contains colons, which I believe is a no-no on Windows. The colons are the problem. The error message is not from the OS; it is concocted by Python (see fileobject.c) as what appears to be the best possible text given vague error reporting by Windows. I don't understand "probably a misleading error [message]" -- invalid mode (actual value) or filename -> invalid something-obviously-not-invalid or filename -> invalid filename From sturlamolden at yahoo.no Sun Aug 23 19:17:19 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 16:17:19 -0700 (PDT) Subject: Python/Fortran interoperability References: Message-ID: On 23 Aug, 20:42, n... at cam.ac.uk wrote: > That is precisely what I am investigating. ?TR 29113 falls a LONG > way before it gets to any of the OOP data - indeed, you can't even > pass OOP derived types as pure data (without even the functionality) > in its model. ?Nor most of what else Python would expect. I am note sure what you mean. This has the same ABI: typedef struct { int m, n; float r; } myctype; use iso_c_binding type, bind(c) :: myftype integer(c_int) :: m, n real(c_float) :: s end type You thus can pass derived types between C and Fortran. From mattaman at gmail.com Sun Aug 23 19:27:21 2009 From: mattaman at gmail.com (mm) Date: Sun, 23 Aug 2009 16:27:21 -0700 (PDT) Subject: Newbie: list comprehension troubles.. Message-ID: Hi, I'm trying to replace this... # this works but there must be a more pythonic way, right? tlist = [] for obj in self.objs: t = obj.intersect(ray) if (t != None): tlist.append((obj,t)) with a list comprehension- can it be done? What I need to do is iterate over a list of graphics primitives and call their intersect method. If the returned t value is not None then I want to store the obj refernence and its t value in a list of tuples for further processing. I've tried stuff like ... tlist = [(obj,t) for obj,t in (self.objs, obj.intersect(ray)) if (t != None)] tlist = [(obj,t) for obj in self.objs for t in obj.intersect (ray) ] print ">>> ",len(tlist), tlist but they don't work. Any help greatly appreciated. matt From clp2 at rebertia.com Sun Aug 23 19:36:02 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Aug 2009 16:36:02 -0700 Subject: Newbie: list comprehension troubles.. In-Reply-To: References: Message-ID: <50697b2c0908231636l77357d21icca87edf2248f15d@mail.gmail.com> On Sun, Aug 23, 2009 at 4:27 PM, mm wrote: > Hi, I'm trying to replace this... > > ? ? ? ?# this works but there must be a more pythonic way, right? > ? ? ? ?tlist = [] > ? ? ? ?for obj in self.objs: > ? ? ? ? ? ?t = obj.intersect(ray) > ? ? ? ? ? ?if (t != None): > ? ? ? ? ? ? ? ?tlist.append((obj,t)) > > with a list comprehension- can it be done? Yes: tlist = [pair for pair in ((obj, obj.intersect(ray)) for obj in self.objs) if pair[1] is not None] Should it be done? Probably not. It's less readable and less efficient. Cheers, Chris -- http://blog.rebertia.com From sturlamolden at yahoo.no Sun Aug 23 19:59:34 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 16:59:34 -0700 (PDT) Subject: Python/Fortran interoperability References: Message-ID: <277abf44-d218-45de-90c8-9bed0f1c8abf@k30g2000yqf.googlegroups.com> On 24 Aug, 00:02, Dennis Lee Bieber wrote: > ? ? ? ? That's a C language problem -- since a string in C is just an array > of character. The last FORTRAN dialect (and implementation) I used > passed strings On 24 Aug, 00:02, Dennis Lee Bieber wrote: > values -- FORTRAN strings were typically static, the called function > could not reallocate to fit in longer data and update the descriptor to > match) It is possible to pass an arbitrary length. You have to convert a pointer from C to Fortran: subroutine foobar(cstr) bind(c, name='foobar') use, intrinsic :: iso_c_binding type(c_ptr) :: cstr character(*), pointer :: fstr call c_f_pointer(cptr, fptr) If you need the length, call strlen from libc. I think the OP has misunderstood how the Fortran 2003 C bindings work. They don't convert C pointers to Fortran strings or Fortran arryas. They convert C pointers to Fortran pointers. Sturla From tjreedy at udel.edu Sun Aug 23 20:05:38 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Aug 2009 09:05:38 +0900 Subject: Newbie: list comprehension troubles.. In-Reply-To: <50697b2c0908231636l77357d21icca87edf2248f15d@mail.gmail.com> References: <50697b2c0908231636l77357d21icca87edf2248f15d@mail.gmail.com> Message-ID: Chris Rebert wrote: > On Sun, Aug 23, 2009 at 4:27 PM, mm wrote: >> Hi, I'm trying to replace this... >> >> # this works but there must be a more pythonic way, right? 'Pythonic' is readable, if nothing else >> tlist = [] >> for obj in self.objs: >> t = obj.intersect(ray) >> if (t != None): >> tlist.append((obj,t)) This, to me, is more readable than the lc replacement. >> >> with a list comprehension- can it be done? > > Yes: > tlist = [pair for pair in ((obj, obj.intersect(ray)) for obj in > self.objs) if pair[1] is not None] > > Should it be done? Probably not. It's less readable and less efficient. I agree. tjr From sturlamolden at yahoo.no Sun Aug 23 20:06:43 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 17:06:43 -0700 (PDT) Subject: Python/Fortran interoperability References: <277abf44-d218-45de-90c8-9bed0f1c8abf@k30g2000yqf.googlegroups.com> Message-ID: On 24 Aug, 01:59, sturlamolden wrote: > subroutine foobar(cstr) bind(c, name='foobar') > ? ? use, intrinsic :: iso_c_binding > ? ? type(c_ptr) :: cstr > ? ? character(*), pointer :: fstr > ? ? call c_f_pointer(cptr, fptr) > Which means that you can write a wrapper in Fortran callable from C, that calls a Fortran routine you want to expose: subroutine wrap_foobar(cstr) bind(c, name='foobar') use, intrinsic :: iso_c_binding type(c_ptr) :: cstr character(*), pointer :: fstr call c_f_pointer(cptr, fptr) call foobar(fstr) end subroutine subroutine foobar(fstr) character(*) :: fstr ! whatever end subroutine This by the way is how wrap exposes Fortran functions to Cython. From ben+python at benfinney.id.au Sun Aug 23 20:09:29 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 24 Aug 2009 10:09:29 +1000 Subject: Newbie: list comprehension troubles.. References: Message-ID: <87ab1qgjie.fsf@benfinney.id.au> Chris Rebert writes: > tlist = [pair for pair in ((obj, obj.intersect(ray)) for obj in > self.objs) if pair[1] is not None] > > Should it be done? Probably not. [Compared to a ?for? suite with an > ?if? suite, it's] less readable and less efficient. I disagree on the ?less efficient?, unless you've measured it. The Python compiler and machine make list comprehensions and generator expressions turn into quite efficient code. I also disagree on ?less readable?, if you show the structure and choose meaningful names (I can only guess at the meaning from the OP's code):: tribbles = [ (obj, tribble) for (obj, tribble) in ( (obj, obj.intersect(ray)) for obj in self.objs) if tribble is not None] -- \ ?I must say that I find television very educational. The minute | `\ somebody turns it on, I go to the library and read a book.? | _o__) ?Groucho Marx | Ben Finney From find.mig at paa.google Sun Aug 23 20:14:24 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Mon, 24 Aug 2009 02:14:24 +0200 Subject: Protecting against callbacks queuing up? Message-ID: <4a91db65$0$305$14726298@news.sunsite.dk> Hello I'm using Python for S60 1.9.7 on my Nokia phone. I've made a program that gets input from an accelerometer sensor, and then calculates some stuff and displays the result. The sensor framework API does a callback to a function defined by me, every time new data is available. The problem is, that sometimes, the calculations may take longer than others, but if the callback is called before the first calculation is done, it seems like it's queuing up all the callbacks, and execute them sequentially, afterwards. What I need, is to simply ignore the callback, if the previous call hasn't finished it's operations before it's called again. I thought that this code would do the trick, but it obviously doesn't help at all, and i can't understand why... def doCallback(self): if self.process_busy==False: self.process_busy=True self.data_callback() self.process_busy=False doCallback is defined as a callback function for the accelerometer instance, and data_callback does some calculations and show them on the display of the phone. What to do? Thanks... From steve at REMOVE-THIS-cybersource.com.au Sun Aug 23 20:17:11 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2009 00:17:11 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <4a918fe0$0$30226$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <02a1cc1d$0$30337$c3e8da3@news.astraweb.com> On Sun, 23 Aug 2009 20:52:16 +0200, Stefan Behnel wrote: > Simon Brunning wrote: >> 2009/8/11 Robert Dailey: >>> On Aug 11, 3:40 pm, Bearophile wrote: >>>> There are gals too here. >>> It's a figure of speech. And besides, why would I want programming >>> advice from a woman? lol. Thanks for the help. >> >> Give the attitudes still prevalent in our industry (cf >> and many more), I'm sorry to say that I >> don't think this is funny. > > Me neither. > > I used to reply with comments like "you just missed more than half of > the world's population" to people who started their postings with "hi > guys!", If you start your post with "Hi guys", you've missed more than EIGHTY percent of the world's population, namely the 5.5 to 6 billion people who speak no English. To say nothing of the 99.9% of the world's population who couldn't help you with your query, even if they spoke English, and even if they were on the Internet. In that case, missing out on the small percentage of English-speaking women who don't know that "guys" has become sexless probably doesn't matter. (I'm amused and somewhat perplexed that somebody with the non-English name of Stefan, writing from a .de email address, seems to be assuming that (1) everybody is on the Internet, and (2) everybody on the Internet speaks English. Awareness of sexism is a good thing, but so is awareness of cultural chauvinism.) > and I stopped doing that as a) it became too tiring, especially > on a potentially-for-newbees group like c.l.py, and b) to many people it > actually *is* a figure of speech. > > But reading statements like the above really makes me feel that it's > best to comment even on simple things like "hi guys!". Or you could enter the 21 century and understand that "guys" has become a generic term for people of any sex. -- Steven From nospam at see.signature Sun Aug 23 20:26:31 2009 From: nospam at see.signature (Richard Maine) Date: Sun, 23 Aug 2009 17:26:31 -0700 Subject: Python/Fortran interoperability References: Message-ID: <1j4ww90.pvvxweehycu0N%nospam@see.signature> sturlamolden wrote: > On 23 Aug, 20:42, n... at cam.ac.uk wrote: > > > That is precisely what I am investigating. TR 29113 falls a LONG > > way before it gets to any of the OOP data - indeed, you can't even > > pass OOP derived types as pure data (without even the functionality) > > in its model. Nor most of what else Python would expect. > > I am note sure what you mean. ... > You thus can pass derived types between C and Fortran. You missed the word "OOP", which seemed like the whole point. Not that the particular word is used in the Fortran standard, but it isn't hard to guess that he means a derived type that uses some of the OOP features. Inheritance, polymorphism, and type-bound procedure (aka methods in some other languages) come to mind. Since you say that you haven't used any of the F2003 OOP features, it isn't too surprising that you'd miss the allusion. -- Richard Maine | Good judgment comes from experience; email: last name at domain . net | experience comes from bad judgment. domain: summertriangle | -- Mark Twain From python at mrabarnett.plus.com Sun Aug 23 20:34:41 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 24 Aug 2009 01:34:41 +0100 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a91db65$0$305$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> Message-ID: <4A91E021.1040502@mrabarnett.plus.com> Esben von Buchwald wrote: > Hello > > I'm using Python for S60 1.9.7 on my Nokia phone. > > I've made a program that gets input from an accelerometer sensor, and > then calculates some stuff and displays the result. > > The sensor framework API does a callback to a function defined by me, > every time new data is available. > > The problem is, that sometimes, the calculations may take longer than > others, but if the callback is called before the first calculation is > done, it seems like it's queuing up all the callbacks, and execute them > sequentially, afterwards. > > What I need, is to simply ignore the callback, if the previous call > hasn't finished it's operations before it's called again. > > I thought that this code would do the trick, but it obviously doesn't > help at all, and i can't understand why... > > def doCallback(self): > if self.process_busy==False: > self.process_busy=True > self.data_callback() > self.process_busy=False > > > doCallback is defined as a callback function for the accelerometer > instance, and data_callback does some calculations and show them on the > display of the phone. > If it is, in fact, queuing the callbacks then that means that it's just recording that the callback needs to be called, but doesn't actually do it while a previous one is in effect, ie it'll wait for the current call to return before doing the next one. > What to do? Thanks... If you want to try multithreading you could make the callback just trigger the actual action in another thread. The other thread could wait for an event, perform the calculation, then clear any pending events before waiting again. From sturlamolden at yahoo.no Sun Aug 23 20:39:34 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 17:39:34 -0700 (PDT) Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> Message-ID: <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> On 24 Aug, 02:26, nos... at see.signature (Richard Maine) wrote: > You missed the word "OOP", which seemed like the whole point. Not that > the particular word is used in the Fortran standard, but it isn't hard > to guess that he means a derived type that uses some of the OOP > features. Inheritance, polymorphism, and type-bound procedure (aka > methods in some other languages) come to mind. But C is not OOP. The ISO C bindings in Fortran are not ISO C++ bindings. This is for a reason: C++ does not have a standard ABI like ISO C. From david.lyon at preisshare.net Sun Aug 23 20:46:12 2009 From: david.lyon at preisshare.net (David Lyon) Date: Sun, 23 Aug 2009 20:46:12 -0400 Subject: install package in a particular python version In-Reply-To: <99822c4d-74ef-4a28-b133-42144c7fd25a@f20g2000prn.googlegroups.com> References: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> <99822c4d-74ef-4a28-b133-42144c7fd25a@f20g2000prn.googlegroups.com> Message-ID: <0e4f0ed1c46760d844a603fae3ebc3a3@preisshare.net> On Thu, 20 Aug 2009 20:53:18 -0700 (PDT), Steve1234 wrote: > Benjamin suggested: > sudo python2.5 setup.py install > and it works. This makes sense, thanks. > > I downloaded pythonpkgmgr from source and installed it. I got the > error that reguired wx package was missing. I couldn't find this > package for Linux or source. That's wxpython. You'll need to look at http://www.wxpython.org/download.php#binaries David From clp2 at rebertia.com Sun Aug 23 20:52:47 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Aug 2009 17:52:47 -0700 Subject: Newbie: list comprehension troubles.. In-Reply-To: <87ab1qgjie.fsf@benfinney.id.au> References: <87ab1qgjie.fsf@benfinney.id.au> Message-ID: <50697b2c0908231752h2ec893fal92a9dc2d8a8d6aba@mail.gmail.com> On Sun, Aug 23, 2009 at 5:09 PM, Ben Finney wrote: > Chris Rebert writes: > >> tlist = [pair for pair in ((obj, obj.intersect(ray)) for obj in >> self.objs) if pair[1] is not None] >> >> Should it be done? Probably not. [Compared to a ?for? suite with an >> ?if? suite, it's] less readable and less efficient. > > I disagree on the ?less efficient?, unless you've measured it. The > Python compiler and machine make list comprehensions and generator > expressions turn into quite efficient code. Well, I hadn't benchmarked it originally, but since you bring it up: class Foo(object): def __init__(self, n): self.n = n def intersect(self, ray): return ray + self.n objs = [Foo(n) for n in range(300)] ray = 42 def listcomp(objs, ray): tlist = [pair for pair in ((obj, obj.intersect(ray)) for obj in objs) if pair[1] is not None] def naive(objs, ray): tlist = [] for obj in objs: t = obj.intersect(ray) if t is not None: tlist.append((obj,t)) chris at morpheus Desktop $ python Python 2.6.2 (r262:71600, May 14 2009, 16:34:51) [GCC 4.0.1 (Apple Inc. build 5484)] on darwin chris at morpheus Desktop $ python -m timeit -n 10000 -s 'from tmp import naive, ray, objs' 'naive(objs, ray)' 10000 loops, best of 3: 227 usec per loop chris at morpheus Desktop $ python -m timeit -n 10000 -s 'from tmp import listcomp, ray, objs' 'listcomp(objs, ray)' 10000 loops, best of 3: 254 usec per loop The numbers for each test stayed within a few usec of each other over a few runs. I thus conclude that the list comprehension method is indeed slower (which makes sense looking at the 2 algorithms). > I also disagree on ?less readable?, if you show the structure and choose > meaningful names (I can only guess at the meaning from the OP's code):: > > ? ?tribbles = [ > ? ? ? ?(obj, tribble) for (obj, tribble) in ( > ? ? ? ? ? ?(obj, obj.intersect(ray)) > ? ? ? ? ? ?for obj in self.objs) > ? ? ? ?if tribble is not None] I do concede it becomes somewhat more readable if split over multiple lines: pairs = ((obj, obj.intersect(ray)) for obj in self.objs) tlist = [pair for pair in pairs if pair[1] is not None] Cheers, Chris -- http://blog.rebertia.com From nospam at see.signature Sun Aug 23 20:57:52 2009 From: nospam at see.signature (Richard Maine) Date: Sun, 23 Aug 2009 17:57:52 -0700 Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> Message-ID: <1j4wx7d.18cr6dvw3j79yN%nospam@see.signature> sturlamolden wrote: > On 24 Aug, 02:26, nos... at see.signature (Richard Maine) wrote: > > > You missed the word "OOP", which seemed like the whole point. Not that > > the particular word is used in the Fortran standard, but it isn't hard > > to guess that he means a derived type that uses some of the OOP > > features. Inheritance, polymorphism, and type-bound procedure (aka > > methods in some other languages) come to mind. > > But C is not OOP. The ISO C bindings in Fortran are not ISO C++ > bindings. This is for a reason: C++ does not have a standard ABI like > ISO C. That seems irrelevant to the question originally asked, which was >>> Do you want to use Fortran derived types or Python classes that >>> contain type-bound procedures (including finalizers)? Yes, it is no surprise that the C interop stuff fails to address this, since it isn't in C. Something different/extra would be needed, which is exactly what Nick said. I'm going to jump out of the middle of this now. The only reason I jumped in was to point out the gap in communication, where Nick said that the TR doesn't handle "OOP derived types" and you replied that it does so do derived types, omitting the OOP part, which was clearly (to me) Nick's whole point. However, I don't seem to be facilitating the communication, as the replies just seem to be wandering farther afield, or maybe it is around in a circle. I think you just explained that the ISO C bindings in Fortran don't handle what Nick is asking about... but that somehow this makes it puzzling that Nick also says that they don't handle it. Well, I'll leave it to Nick and you, I guess. I'm lost. -- Richard Maine | Good judgment comes from experience; email: last name at domain . net | experience comes from bad judgment. domain: summertriangle | -- Mark Twain From maxerickson at gmail.com Sun Aug 23 21:19:53 2009 From: maxerickson at gmail.com (Max Erickson) Date: Mon, 24 Aug 2009 01:19:53 +0000 (UTC) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: "bartc" wrote: > > "Scott David Daniels" wrote in message > news:kN2dnSZR5b0BWAzXnZ2dnUVZ_s-dnZ2d at pdx.net... >> James Harris wrote:... >>> Another option: > > It can be assumed however that .9. isn't in binary? > > That's a neat idea. But an even simpler scheme might be: > > .octal.100 > .decimal.100 > .hex.100 > .binary.100 > .trinary.100 > > until it gets to this anyway: > > .thiryseximal.100 > At some point, abandoning direct support for literals and just having a function that can handle different bases starts to make a lot of sense to me: >>> int('100', 8) 64 >>> int('100', 10) 100 >>> int('100', 16) 256 >>> int('100', 2) 4 >>> int('100', 3) 9 >>> int('100', 36) 1296 max From voodoorai2000 at gmail.com Sun Aug 23 21:25:11 2009 From: voodoorai2000 at gmail.com (Raimond Garcia) Date: Mon, 24 Aug 2009 03:25:11 +0200 Subject: What is the recommended library for xml parsing? In-Reply-To: <50697b2c0908231559vf6c42dcn321296edd7d033b7@mail.gmail.com> References: <50697b2c0908231559vf6c42dcn321296edd7d033b7@mail.gmail.com> Message-ID: +1 ::results:: Cheers, Peter Petrelli On Mon, Aug 24, 2009 at 12:59 AM, Chris Rebert wrote: > On Sun, Aug 23, 2009 at 3:07 PM, Raimond Garcia > wrote: > > Is there a good build in library or should I use a third party one? > > xml.etree.ElementTree: > http://docs.python.org/library/xml.etree.elementtree.html > > Cheers, > Chris > -- > http://blog.rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bot at letsdecide.us Sun Aug 23 21:27:04 2009 From: bot at letsdecide.us (bot at letsdecide.us) Date: Mon, 24 Aug 2009 01:27:04 +0000 Subject: What is the recommended library for xml parsing? Message-ID: <4a91ec68908f7_7144..fdbe3c0dc13e@li86-209.tmail> voodoorai2000 on gmail.com has asked me for the current status of our votation.. so here you go: +1 => 1 vote -1 => 0 votes Time Line: ---------- (2009-08-24 01:25:11) Raimond Garcia: +1 Visit the fancy votation page: * http://letsdecide.us/4130bc4e0051016cb377d3436f4e8e683ed820ed From sturlamolden at yahoo.no Sun Aug 23 21:28:24 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 18:28:24 -0700 (PDT) Subject: Python/Fortran interoperability References: <277abf44-d218-45de-90c8-9bed0f1c8abf@k30g2000yqf.googlegroups.com> Message-ID: <310696bd-f51e-42bc-80cf-89a2a9e04c0c@v20g2000yqm.googlegroups.com> On 24 Aug, 01:59, sturlamolden wrote: > subroutine foobar(cstr) bind(c, name='foobar') > ? ? use, intrinsic :: iso_c_binding > ? ? type(c_ptr) :: cstr > ? ? character(*), pointer :: fstr > ? ? call c_f_pointer(cptr, fptr) Actually, this does not work, as it is illegal to create a pointer to a character(*). However, we can create a pointer to a huge string (say 2 GB or whatever maximum the system allows), and slice that down to a substring using strlen to obtain the length. So here is how to pass a variable-length string from C to Fortran, tested with gcc and gfortran 4.1.1. In foobar.f03: subroutine wrap_foobar(cstr) bind(c, name='foobar') ! a wrapper for foobar we expose to C use, intrinsic :: iso_c_binding interface function strlen(cstr) bind(c, name='strlen') use, intrinsic :: iso_c_binding integer(c_int) :: strlen type(c_ptr), value :: cstr end function strlen end interface type(c_ptr), value :: cstr character(2147483647), pointer :: p_fstr integer :: n n = strlen(cstr) call c_f_pointer(cstr, p_fstr) call foobar(p_fstr(1:n)) end subroutine subroutine foobar(fstr) ! this is the Fortran function we want to call from C ! it takes a variable length string as argument and print its length character(*) :: fstr write (*,*) len(fstr) end subroutine In main.c: extern void foobar(char *); int main(int argc, char *argv[]) { foobar(argv[1]); return 0; } Sturla at STURLA-PC /d/fortrantest $ gfortran -c foobar.f03 Sturla at STURLA-PC /d/fortrantest $ gcc -c main.c Sturla at STURLA-PC /d/fortrantest $ gcc -o test.exe main.o foobar.o -lgfortran Sturla at STURLA-PC /d/fortrantest $ ./test 1234 4 Sturla at STURLA-PC /d/fortrantest $ ./test 0123456789 10 So it works... Regards, Sturla Molden From davea at ieee.org Sun Aug 23 21:32:13 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 23 Aug 2009 21:32:13 -0400 Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: References: Message-ID: <4A91ED9D.4090803@ieee.org> John Machin wrote: > Erik Max Francis alcyone.com> writes: > > >> Ryniek90 wrote: >> > > >>> Is its the '|\U' literal fault in path '|C:\\Users\\Ryniek's >>> WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2|' ? >>> > > What is "the '|\U' literal fault" ??? > > >> It's probably a misleading error from the OS; I would guess the problem >> is that the filename contains colons, which I believe is a no-no on Windows. >> > > The colons are the problem. The error message is not from the OS; it is > concocted by Python (see fileobject.c) as what appears to be the best possible > text given vague error reporting by Windows. I don't understand "probably a > misleading error [message]" -- invalid mode (actual value) or filename -> > invalid something-obviously-not-invalid or filename -> invalid filename > > > I also suspect the "pipe" symbol. I don't know if it's an invalid character to Windows, but it's certainly a bad idea. The '|' character means something special to the shell. DaveA From sturlamolden at yahoo.no Sun Aug 23 21:40:06 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 18:40:06 -0700 (PDT) Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> <1j4wx7d.18cr6dvw3j79yN%nospam@see.signature> Message-ID: <800c6f66-7074-451f-8c1b-47c93d07c5a4@s13g2000yql.googlegroups.com> On 24 Aug, 02:57, nos... at see.signature (Richard Maine) wrote: > Yes, it is no surprise that the C interop stuff fails to address this, > since it isn't in C. Something different/extra would be needed, which is > exactly what Nick said. I'm going to jump out of the middle of this now. > The only reason I jumped in was to point out the gap in communication, > where Nick said that the TR doesn't handle "OOP derived types" and you > replied that it does so do derived types, omitting the OOP part, which > was clearly (to me) Nick's whole point. You are right, I missed th OOP part. It might be interesting in teh future to say inherit a Python class from a Fortran 2003 derived type. I have no idea how to do this (I don't know Fortran 2003 that well). But possibly one could do some magic with the ISO C bindings, exposing the Fortran 2003 derived type as a C etxtension class to Python. Does anyone use OOP in Fortran anyway? I sure do not. And Fortran 2003 compilers are not ubiquitous. Fortran compilers tend to support a subset for Fortran 2003, usually ISO C bindings but not OOP. Sturla From greg at cosc.canterbury.ac.nz Sun Aug 23 21:46:18 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 24 Aug 2009 13:46:18 +1200 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> Message-ID: <7fe9mbF2l83bmU1@mid.individual.net> J. Cliff Dyer wrote: > What happens if you use a literal like 0x10f 304? To me the obvious thing to do is concatenate them textually and then treat the whole thing as a single numeric literal. Anything else wouldn't be sane, IMO. -- Greg From nospam at see.signature Sun Aug 23 21:58:40 2009 From: nospam at see.signature (Richard Maine) Date: Sun, 23 Aug 2009 18:58:40 -0700 Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> <1j4wx7d.18cr6dvw3j79yN%nospam@see.signature> <800c6f66-7074-451f-8c1b-47c93d07c5a4@s13g2000yql.googlegroups.com> Message-ID: <1j4x00p.nyarf2ce8dxcN%nospam@see.signature> sturlamolden wrote: > Does anyone use OOP in Fortran anyway? Presumably not many people yet because... > And Fortran 2003 compilers are not ubiquitous. I'd not only agree, I'd say that was quite a bit understated. Last time I checked, the number of Fortran 2003 compilers available on the most widely used platforms was zero, which is quite a bit short of ubiquitous. No I don't have an IBM workstation handy; or a Cray. Nor do most people. I did try playing with the Fortran OOP stuff quite a few years ago, when NAG first added some of the OOP features to their f95 compiler. But alas, although they added some of the OOP features, there were critical parts that were not included. Play with it a little is all I could do. I couldn't write any serious code, or even "play" very extensively. (Lack of allocatable scalars was a show stopper; it seems so simple and isn't even normally identified as an OOP feature per se, but you need it to do much with OOP in F2003). I'm told that NAG's 5.2 finally has the needed stuff, but it has been an awful long time in coming... and still isn't yet here for anything but Linux (I'm told "soon"). Some other compilers are also getting there. But there is just no way that most people have spent much time developing with compilers that adequately supported the f2003 OOP features. (I'd cite my formal comment on f2008, and maybe David Muxworthy's recent article as well, but we've already been down that path.) -- Richard Maine | Good judgment comes from experience; email: last name at domain . net | experience comes from bad judgment. domain: summertriangle | -- Mark Twain From davea at ieee.org Sun Aug 23 22:05:42 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 23 Aug 2009 22:05:42 -0400 Subject: Is Python what I need? In-Reply-To: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: <4A91F576.30707@ieee.org> newbie wrote: > Hi all > I'm interested in developing computer based, interactive programs for > students in a special school who have an aversion to pen and paper. > I've searched the net to find ready made software that will meet my > needs but it is either written to a level much higher than these > students can cope with or priced beyond our school budget. I came > across a blog of someone singing the praises of Python. My question is > therefore aimed at those that know what they are talking about (ie > users in this group). Is Python the language I need to learn to > develop these programs? > > I think I'm a bit confused as to just what you're intending, and what your background is. So if this response doesn't fit, please don't be offended. I'm guessing you don't want these special students to do any programming, but instead you just want to find/develop inexpensive applications for their use. You have some specific ideas, but haven't found anything already available within your budget. I'm also guessing that you're a total beginner at programming. If so, I claim that most programs are much, much harder to write than you can imagine. Python is one of the easiest languages to learn and to write things in, but even so, most GUI programs take hundreds of hours to develop. And I've been doing it for forty years, in about 30 languages. DaveA From sjmachin at lexicon.net Sun Aug 23 22:10:12 2009 From: sjmachin at lexicon.net (John Machin) Date: Mon, 24 Aug 2009 02:10:12 +0000 (UTC) Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in =?utf-8?b?d2luZG93cwl4cA==?= while making tarfile References: <4A91ED9D.4090803@ieee.org> Message-ID: Dave Angel ieee.org> writes: > John Machin wrote: > > Erik Max Francis alcyone.com> writes: > I also suspect the "pipe" symbol. I don't know if it's an invalid > character to Windows, but it's certainly a bad idea. The '|' character > means something special to the shell. The "pipe" character is not a valid character in a Windows file. Despite the OP's message wrapping the filename in "pipes", there are no pipes in the filename in the traceback to which he posted a link. Wrapping the filename in "pipes" and the cryptic reference to "the '|\U' literal fault" appear to be side-issue bogglements. >>> open('boggle|txt', 'wb') Traceback (most recent call last): File "", line 1, in IOError: [Errno 22] invalid mode ('wb') or filename: 'boggle|txt' >>> open('|boggle.txt|', 'wb') Traceback (most recent call last): File "", line 1, in IOError: [Errno 22] invalid mode ('wb') or filename: '|boggle.txt|' From sturlamolden at yahoo.no Sun Aug 23 22:28:10 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 19:28:10 -0700 (PDT) Subject: Is python faster than java? References: Message-ID: On 23 Aug, 21:59, Emile van Sebille wrote: > Speed of what? Development? User interaction? Responsiveness to queries? My personal view on the 'Is Python faster than Java' question: - Coding? Yes, if you program 'pythonic'. - String handling? Often. - I/O and networking? Often. - Iteration? No. - Function calls and recursion? No. - Arithmetics with elemental types? No. - Numerics? Yes, if you use NumPy. Is never interesting which language generates the most efficient code. If that were the case, we would be writing everything in assembly. If the code is fast enough, it is fast enough. Fast enough is sufficient. If some part of the code turn out to be too slow, we have two options: Either we use faster hardware, which is often the cheapest solution. Or we can alternatively try to move that part to something less high- level (Cython, C, C++, Fortran, assembly). Unlike Java, Python integrates easily with C. Also beware that Python is not Java: There is an old saying that you can write FORTRAN in any language. You can also write Java in Python. It will be just as slow to program as Java, and it will run a lot slower than Java. Most of the complaints about 'Python being slow' stems from people writing Java in Python. From ben+python at benfinney.id.au Sun Aug 23 22:29:20 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 24 Aug 2009 12:29:20 +1000 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: <8763cegd1b.fsf@benfinney.id.au> Max Erickson writes: > At some point, abandoning direct support for literals and just > having a function that can handle different bases starts to make a > lot of sense to me: > > >>> int('100', 8) > 64 > >>> int('100', 10) > 100 > >>> int('100', 16) > 256 > >>> int('100', 2) > 4 > >>> int('100', 3) > 9 > >>> int('100', 36) > 1296 Hah! You don't get me that easily, nobody would make something so simple and obvious. Right, guys? -- \ ?When a well-packaged web of lies has been sold to the masses | `\ over generations, the truth will seem utterly preposterous and | _o__) its speaker a raving lunatic.? ?Dresden James | Ben Finney From greg at cosc.canterbury.ac.nz Sun Aug 23 22:34:41 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 24 Aug 2009 14:34:41 +1200 Subject: __import__(x) VS __import__(x, {}, {}, ['']) In-Reply-To: References: Message-ID: <7fech5F2kofoqU1@mid.individual.net> Phil wrote: > I am trying to understand the difference between __import__(x) and > __import__(x, {}, {}, ['']). > > The documentations wording was a bit weird for me to understand: > "The standard implementation does not use its locals argument at all, > and uses its globals only to determine the package context of the > import statement." > > Does that mean it passes in the globals by default, or does the above > statement stand true only if globals() is passed in? Not sure what you mean by "it" in that question. This is talking about the built-in implementation of the __import__ function, and what it does with the 'globals' and 'locals' arguments that get passed to it (by whatever means). If you call it without a value for 'globals', it uses the current value of globals(). The bytecode generated for the 'import' statement always calls it with the current globals() and locals(). If you pass an empty dict for 'globals', I think the effect will be to cause the module name to always be interpreted as a top-level module (i.e. no relative import). But I'm not sure. -- Greg From ben+python at benfinney.id.au Sun Aug 23 22:45:25 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 24 Aug 2009 12:45:25 +1000 Subject: Literal concatenation, strings vs. numbers (was: Numeric literals in other than base 10 - was Annoying octal notation) References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> <7fe9mbF2l83bmU1@mid.individual.net> Message-ID: <871vn2gcai.fsf_-_@benfinney.id.au> greg writes: > J. Cliff Dyer wrote: > > > What happens if you use a literal like 0x10f 304? > > To me the obvious thing to do is concatenate them textually and then > treat the whole thing as a single numeric literal. Anything else > wouldn't be sane, IMO. Yet, as was pointed out, that behaviour would be inconsistent with the concatenation of string literals:: >>> "abc" r'def' u"ghi" 'jkl' u'abcdefghijkl' So, different representations of literals are parsed as separate literals, then concatenated. To have the behaviour you describe, the case needs to be made separately that digit concatenation should not be consistent with the established string literal parsing behaviour. -- \ ?What if the Hokey Pokey IS what it's all about?? ?anonymous | `\ | _o__) | Ben Finney From phily05 at gmail.com Sun Aug 23 22:58:42 2009 From: phily05 at gmail.com (Phil) Date: Sun, 23 Aug 2009 19:58:42 -0700 (PDT) Subject: __import__(x) VS __import__(x, {}, {}, ['']) References: <7fech5F2kofoqU1@mid.individual.net> Message-ID: <7d34f960-39a2-4447-9879-77a2794266a0@a26g2000yqn.googlegroups.com> "If you call it without a value for 'globals', it uses the current value of globals()." Thanks, this is what I was trying to ask. I typed my question up way too fast before dinner. You've been great help. From kerensaelise at hotmail.com Sun Aug 23 23:51:00 2009 From: kerensaelise at hotmail.com (elsa) Date: Sun, 23 Aug 2009 20:51:00 -0700 (PDT) Subject: sgmllib.py Message-ID: Hi all, I'm new to both this forum and Python, and I've got a bit stuck trying to learn how to parse HTML.... here is my problem I'm using a textbook that uses sgmllib.py for all its examples. I'm aware that sgmllib is not in the current release, however I want to get it to work, as I have python 2.5, and the text book uses it. So, the first example says to type something like (to test the sgmllib): python sgmllib.py "path/to/my/file.html" .... example (1) this doesn't work for me. I think I have figured out the problem - the error says "/System/Library/Frameworks/Python.framework/Versions/2.5/Resources/ Python.app/Contents/MacOS/Python: can't open file 'sgmllib.py': [Errno 2] No such file or directory" the problem is that this path is wrong. My sgmllib.py is in: "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/sgmllib.py" if I substitute this path for sgmllib.py in example (1), everything works fine. However, I don't want to do all that typing everytime I want to use sgmllib.py. So, I thought maybe the problem was with PYTHONPATH. I executed the following command: export PYTHONPATH=/System/Library/Frameworks/Python.framework/Versions/ 2.5/li/python2.5:$PYTHONPATH this seemed to work - no errors raised. However, when I retyped example (1), I got the same original error. Any assistance would be much appreciated. I'm working on max os x leopard. Thanks, elsa From doron.tal.list at gmail.com Sun Aug 23 23:51:05 2009 From: doron.tal.list at gmail.com (Doron Tal) Date: Mon, 24 Aug 2009 06:51:05 +0300 Subject: Most "active" coroutine library project? In-Reply-To: <64183b73-9cb0-4ce1-98d0-f47e13a818e4@f37g2000yqn.googlegroups.com> References: <64183b73-9cb0-4ce1-98d0-f47e13a818e4@f37g2000yqn.googlegroups.com> Message-ID: <2a8674c60908232051p71e743d0g9136ff2672e846f9@mail.gmail.com> On Sun, Aug 23, 2009 at 6:02 PM, Phillip B Oldham wrote: > I've been taking a look at the multitude of coroutine libraries > available for Python, but from the looks of the projects they all seem > to be rather "quiet". I'd like to pick one up to use on a current > project but can't deduce which is the most popular/has the largest > community. > > Libraries I looked at include: cogen, weightless, eventlet and > circuits (which isn't exactly coroutine-based but it's event-driven > model was intriguing). > > Firstly, are there any others I've missed? And what would the > consensus be on the which has the most active community behind it? > -- > http://mail.python.org/mailman/listinfo/python-list > If you seek also event-driven libraries: Twisted - http://twistedmatrix.com/trac/ --doron -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Mon Aug 24 00:36:19 2009 From: mensanator at aol.com (Mensanator) Date: Sun, 23 Aug 2009 21:36:19 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> <86bb893a-344a-4c7b-9fc6-67d9f42c7607@q14g2000vbi.googlegroups.com> <62dbf088-4510-40d0-af3e-3feeb291d6e4@t13g2000yqt.googlegroups.com> <4a9197c0$0$30226$9b4e6d93@newsspool1.arcor-online.net> Message-ID: On Aug 23, 2:25?pm, Stefan Behnel wrote: > Mensanator wrote: > > asking how many Jews you can fit into a Volswagen. > > None, because it's already full. A spelling error does not make it any less offensive. > > (or "voll" as those who design Volkswagens would put it...) > > Stefan From chaelon at gmail.com Mon Aug 24 01:09:45 2009 From: chaelon at gmail.com (c) Date: Sun, 23 Aug 2009 22:09:45 -0700 (PDT) Subject: Is Python what I need? References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: <22af46a4-91d1-4941-b914-ce78f136a151@p15g2000vbl.googlegroups.com> > I'm interested in developing computer based, interactive programs That is so open-ended it could mean anything. If you give a much more specified idea of what you are imagining creating, people could be helpful. > for students in a special school who have an aversion to pen and paper. Aversion? Why? Is it that they have such bad penmanship that writing is too frustrating? I've taught such students in college, and suspect (but do not know) that what would be good is to get them young and really put in the remedial time to train their penmanship up to sustained legibility and speed. Eventually society might go 100% electronic; for now, being able to write notes on paper is very helpful, and paper is still such a great technology aside from renewable concerns, but they can be greatly improved. (I even suspect rigorous and successful penmanship training might pay off in "general intelligence" gains) > I've searched the net to find ready made software that will meet my > needs but it is either written to a level much higher than these > students can cope with or priced beyond our school budget. I came > across a blog of someone singing the praises of Python. My question is > therefore aimed at those that know what they are talking about (ie > users in this group). Is Python the language I need to learn to > develop these programs? I agree with Dave A that writing a useful program is often far harder than a beginner might imagine. That said, much would depend on what you would need the program to do. Python, in my limited experience as a hobbyist, strikes me as fairly easy to get started with in programming, and yet can do a great deal, too. So, as I said, more details about the intended program would help people guide your choice. Che From nagle at animats.com Mon Aug 24 01:14:17 2009 From: nagle at animats.com (John Nagle) Date: Sun, 23 Aug 2009 22:14:17 -0700 Subject: basic thread question In-Reply-To: References: <20090818201015.GP20434@dragontoe.org> Message-ID: <4a922086$0$1619$742ec2ed@news.sonic.net> Jan Kaliszewski wrote: > 18-08-2009 o 22:10:15 Derek Martin wrote: > >> I have some simple threaded code... If I run this >> with an arg of 1 (start one thread), it pegs one cpu, as I would >> expect. If I run it with an arg of 2 (start 2 threads), it uses both >> CPUs, but utilization of both is less than 50%. Can anyone explain >> why? >> >> I do not pretend it's impeccable code, and I'm not looking for a >> critiqe of the code per se, excepting the case where what I've written >> is actually *wrong*. I hacked this together in a couple of minutes, >> with the intent of pegging my CPUs. Performance with two threads is >> actually *worse* than with one, which is highly unintuitive. I can >> accomplish my goal very easily with bash, but I still want to >> understand what's going on here... >> >> The OS is Linux 2.6.24, on a Ubuntu base. Here's the code: > > Python threads can't benefit from multiple processors (because of GIL, > see: http://docs.python.org/glossary.html#term-global-interpreter-lock). This is a CPython implementation restriction. It's not inherent in the language. Multiple threads make overall performance worse because Python's approach to thread locking produces a large number of context switches. The interpreter unlocks the "Global Interpreter Lock" every N interpreter cycles and on any system call that can block, which, if there is a thread waiting, causes a context switch. Multiple Python processes can run concurrently, but each process has a copy of the entire Python system, so the memory and cache footprints are far larger than for multiple threads. John Nagle From graham.dumpleton at gmail.com Mon Aug 24 02:51:33 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 23 Aug 2009 23:51:33 -0700 (PDT) Subject: web frameworks that support Python 3 References: Message-ID: On Aug 24, 6:34?am, Sebastian Wiesner wrote: > At Sunday 23 August 2009 22:13:16 you wrote:> I use Chinese and therefore Unicode very heavily, and so Python 3 is > > an unavoidable choice for me. > > Python 2.x supports Unicode just as well as Python 3. ?Every common web > framework works perfectly with unicode. > > In any case, there is bottle [1], which provides a *very minimal* framework > for WSGI web development. ?Don't expect too much, it is really small, and > doesn't do much more than routing and minimal templating. > > However, it is the only Python-3-compatible web framework I know of. > > [1]http://bottle.paws.de/page/start There is one big flaw with your claim. That is the there is no WSGI specification for Python 3.0 as yet. Anything that claims to work with WSGI and Python 3.0 is just a big guess as far as how WSGI for Python 3.0 may work. I would therefore be a bit cautious with your claim. Graham From kerensaelise at hotmail.com Mon Aug 24 03:04:57 2009 From: kerensaelise at hotmail.com (elsa) Date: Mon, 24 Aug 2009 00:04:57 -0700 (PDT) Subject: elementtree Message-ID: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> I have a question about elementtree: I know how to turn HTML into an ElementTree object, but I don't know how to then view the structure of this object. Is there a method or module that you can give an ElementTree object to, and it returns some kind of graphical or printed representation of the tree? Otherwise, if you can't see you're tree's structure, how do you know what is a sensible way of iterating over the tree to access the info you need? Thanks! From stefan_ml at behnel.de Mon Aug 24 03:08:07 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 09:08:07 +0200 Subject: sgmllib.py In-Reply-To: References: Message-ID: <4a923c57$0$32664$9b4e6d93@newsspool2.arcor-online.net> elsa wrote: > I'm new to both this forum and Python, and I've got a bit stuck trying > to learn how to parse HTML... If what you want to do is *parse* the HTML instead of trying to *learn* how to parse it, you might want to give the existing (external) HTML parser libraries a try. There's lxml.html (extremely fast and fixes up broken HTML), html5lib (very slow, but very browser-like parse results) and BeautifulSoup (slow, but good encoding detection if you need that). Here are a couple of (only slightly biased) comparisons: http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/ http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/ > python sgmllib.py "path/to/my/file.html" .... example (1) > > this doesn't work for me. I think I have figured out the problem - > the error says > > "/System/Library/Frameworks/Python.framework/Versions/2.5/Resources/ > Python.app/Contents/MacOS/Python: can't open file 'sgmllib.py': [Errno > 2] No such file or directory" > > the problem is that this path is wrong. My sgmllib.py is in: > > "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/sgmllib.py" You can use "python -m sgmllib" to call a module from the stdlib (or the PYTHONPATH, to be more accurate). But note that sgmllib is a particularly cumbersome way to deal with HTML. Stefan From stefan_ml at behnel.de Mon Aug 24 03:13:14 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 09:13:14 +0200 Subject: elementtree In-Reply-To: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> References: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> Message-ID: <4a923d8b$0$32664$9b4e6d93@newsspool2.arcor-online.net> Hi, elsa wrote: > I know how to turn HTML into an ElementTree object I don't. ;) ElementTree doesn't have an HTML parser, so what do you use for parsing? > but I don't know > how to then view the structure of this object. Is there a method or > module that you can give an ElementTree object to, and it returns some > kind of graphical or printed representation of the tree? Otherwise, if > you can't see you're tree's structure, how do you know what is a > sensible way of iterating over the tree to access the info you need? ElementTree has a tostring() method that returns a string. To get a pretty printed representation, you can use the indent() function from this recipe: http://effbot.org/zone/element-lib.htm#prettyprint Stefan From stefan_ml at behnel.de Mon Aug 24 03:16:32 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 09:16:32 +0200 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module In-Reply-To: <2571343.k9db9GJWqV@coder.cl> References: <2571343.k9db9GJWqV@coder.cl> Message-ID: <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> Daniel Molina Wegener wrote: > * Added encoded serialization of Unicode strings by using > the user defined encoding as is passed to the serialization > functions as enc parameter > > As you see, now Unicode strings are serialized as encoded byte string > by using the encoding that the user pass as enc parameter to the > serialization function. This means that Unicode strings are serialized > in a human readable form, regarding a better interoperability with > other platforms. You mean, the whole XML document is serialised with that encoding, right? Stefan From osky50 at gmail.com Mon Aug 24 03:25:44 2009 From: osky50 at gmail.com (osky) Date: Mon, 24 Aug 2009 00:25:44 -0700 (PDT) Subject: Python and JMS Message-ID: <679a2898-abf1-4938-a456-59e0bf5ba666@k6g2000yqn.googlegroups.com> Hi all, I would like to make a JMS client connection from Python to Progress Sonic ESB (JMS message provider similar to WebSphere MQ or Active MQ). What would be the best way to implement that within Python 2.6 ? Any ideas ? Thanks Oscar From ajoys123 at gmail.com Mon Aug 24 03:39:21 2009 From: ajoys123 at gmail.com (devaru) Date: Mon, 24 Aug 2009 00:39:21 -0700 (PDT) Subject: Simple IRC library Message-ID: <752884c5-c6fb-4974-a21a-bf3017fa4145@y4g2000prf.googlegroups.com> Hi all, I am new to Python language. I want to capture(either in database or a file) the conversation in IRC. Please suggest me some simple IRC library or code snippet for this. From stefan_ml at behnel.de Mon Aug 24 03:40:03 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 09:40:03 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <02a1cc1d$0$30337$c3e8da3@news.astraweb.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <4a918fe0$0$30226$9b4e6d93@newsspool1.arcor-online.net> <02a1cc1d$0$30337$c3e8da3@news.astraweb.com> Message-ID: <4a9243d3$0$32677$9b4e6d93@newsspool2.arcor-online.net> Steven D'Aprano wrote: > I'm amused and somewhat perplexed that somebody with the non-English > name of Stefan, writing from a .de email address, seems to be assuming > that (1) everybody is on the Internet, and (2) everybody on the Internet > speaks English. Oh, I totally don't. But most people who read c.l.py do at least understand it to a certain extent. I don't commonly read /that/ many non-english-speaking Python forums thoroughly enough to assume that the OP posted the question only in English and only in c.l.py. I don't even assume that he only posted that question to an Internet newsgroup. You know, there's real-life, too. >> But reading statements like the above really makes me feel that it's >> best to comment even on simple things like "hi guys!". > > Or you could enter the 21 century and understand that "guys" has become a > generic term for people of any sex. Is that true for everyone who understands and/or writes English? In that case, I'm fine with your above statement. Otherwise, I'd wonder who you meant with the term "cultural chauvinism". So far, I only learned that most North-American English native speakers use that term in the way you refer to. That doesn't even get you close to the majority of English speakers. Stefan From stefan_ml at behnel.de Mon Aug 24 03:43:49 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 09:43:49 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> <86bb893a-344a-4c7b-9fc6-67d9f42c7607@q14g2000vbi.googlegroups.com> <62dbf088-4510-40d0-af3e-3feeb291d6e4@t13g2000yqt.googlegroups.com> <4a9197c0$0$30226$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <4a9244b5$0$32671$9b4e6d93@newsspool2.arcor-online.net> Mensanator wrote: > On Aug 23, 2:25?pm, Stefan Behnel wrote: >> Mensanator wrote: >>> asking how many Jews you can fit into a Volswagen. >> None, because it's already full. > > A spelling error does not make it any less offensive. As it stands, I find the joke above perfectly acceptable. Using the word "Jew" in a joke doesn't make it anti-semitic by default. Stefan From piet at cs.uu.nl Mon Aug 24 03:51:37 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 24 Aug 2009 09:51:37 +0200 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: >>>>> Scott David Daniels (SDD) wrote: >SDD> James Harris wrote:... >>> Another option: >>> >>> 0.(2:1011), 0.(8:7621), 0.(16:c26b) >>> >>> where the three characters "0.(" begin the sequence. >>> >>> Comments? Improvements? >SDD> I did a little interpreter where non-base 10 numbers >SDD> (up to base 36) were: >SDD> .7.100 == 64 (octal) >SDD> .9.100 == 100 (decimal) >SDD> .F.100 == 256 (hexadecimal) >SDD> .1.100 == 4 (binary) >SDD> .3.100 == 9 (trinary) >SDD> .Z.100 == 46656 (base 36) I wonder how you wrote that interpreter, given that some answers are wrong. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From max at alcyone.com Mon Aug 24 04:05:40 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 01:05:40 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: MRAB wrote: > James Harris wrote: >> On 23 Aug, 00:16, Mel wrote: >>> James Harris wrote: >>>> I have no idea why Ada which uses the # also apparently uses it to end >>>> a number >>>> 2#1011#, 8#7621#, 16#c26b# >>> Interesting. They do it because of this example from >>> : >> >> Thanks for providing an explanation. >> >>> 2#1#E8 -- an integer literal of value 256 >>> >>> where the E prefixes a power-of-2 exponent, and can't be taken as a >>> digit of >>> the radix. That is to say >>> >>> 16#1#E2 >>> >>> would also equal 256, since it's 1*16**2 . >> >> Here's another suggested number literal format. First, keep the >> familar 0x and 0b of C and others and to add 0t for octal. (T is the >> third letter of octal as X is the third letter of hex.) The numbers >> above would be >> >> 0b1011, 0t7621, 0xc26b >> >> Second, allow an arbitrary number base by putting base and number in >> quotes after a zero as in >> >> 0"2:1011", 0"8:7621", 0"16:c26b" >> > Why not just put the base first, followed by the value in quotes: > > 2"1011", 8"7621", 16"c26b" It's always a bit impressive how syntax suggestions get more and more involved and, if you'll forgive me for saying, ridiculous as the conversation continues. This is starting to get truly nutty. What I've done in my projects is simply extend the pattern of 0x... for hexadecimal literals in C to 0b... for binary, 0o... for octal, 0d... for decimal (though redundant as that's the default), and so on. (Go crazy and add 0t... for trinary and 0q... for quaternary if you feel like it.) To me this always seemed elegant, simple, and understandable. If arbitrary radix values is what's desirable, then some syntax like r (e.g., 8r024222570 for an octal number which represents a very lame joke) would work, but seems to me like huge overkill. A normal string literal coupled with a "constructor" type function would seem far more appropriate -- and we already have that with `int`. As for large literals, I'd go with having spaces indicate automatic concatenation (though only the first in the series can indicate the radix, whichever method you choose above). It's the same as for strings, and it's the common SI recommendation for thousands separators anyway. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis The little I know, I owe to my ignorance. -- Sacha Guitry From max at alcyone.com Mon Aug 24 04:12:22 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 01:12:22 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> Message-ID: J. Cliff Dyer wrote: > I had an objection to using spaces in numeric literals last time around > and it still stands, and it still stands in the new one. > > What happens if you use a literal like 0x10f 304? Is 304 treated as > decimal or hexadecimal? It's not clear how you would begin to combine > it. Well, you can't combine them in any meaningful mathematical or computational sense if they're of different bases, so the answer lies therein: You shouldn't be allowed to do that. > The way string concatenation works, it takes two independent string > literals, and combines them. If you specify r'\n' 'abc\n', the first > half is treated independently as a raw string, and the second half is > treated as a normal string. The result is '\\nabc\n'. > > With numeric literals, this behavior doesn't even make sense. How do > you concatenate hex 10f with decimal 304? You can't, and the operation makes no sense, which is what makes the syntax unambiguous. An extended numeric literal continues the radix of wherever it started. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Do not seek death. Death will find you. -- Dag Hammarskjold From james.harris.1 at googlemail.com Mon Aug 24 04:16:07 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Mon, 24 Aug 2009 01:16:07 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: On 24 Aug, 02:19, Max Erickson wrote: ... > > It can be assumed however that .9. isn't in binary? > > > That's a neat idea. But an even simpler scheme might be: > > > .octal.100 > > .decimal.100 > > .hex.100 > > .binary.100 > > .trinary.100 > > > until it gets to this anyway: > > > .thiryseximal.100 > > At some point, abandoning direct support for literals and just > having a function that can handle different bases starts to make a > lot of sense to me: > > >>> int('100', 8) > 64 > >>> int('100', 10) > 100 > >>> int('100', 16) > 256 > >>> int('100', 2) > 4 > >>> int('100', 3) > 9 > >>> int('100', 36) > 1296 This is fine typed into the language directly but couldn't be entered by the user or read-in from or written to a file. James From max at alcyone.com Mon Aug 24 04:20:02 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 01:20:02 -0700 Subject: Literal concatenation, strings vs. numbers In-Reply-To: <871vn2gcai.fsf_-_@benfinney.id.au> References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> <7fe9mbF2l83bmU1@mid.individual.net> <871vn2gcai.fsf_-_@benfinney.id.au> Message-ID: Ben Finney wrote: > Yet, as was pointed out, that behaviour would be inconsistent with the > concatenation of string literals:: > > >>> "abc" r'def' u"ghi" 'jkl' > u'abcdefghijkl' > > So, different representations of literals are parsed as separate > literals, then concatenated. To have the behaviour you describe, the > case needs to be made separately that digit concatenation should not be > consistent with the established string literal parsing behaviour. Since digit concatenation can't possibly be useful any other way, it makes perfect sense. Why is the operator ** right-to-left associative? The same basic reason: Because it would be dumb for it not to be. Does that make it confusing and inconsistent compared to most of the other binary operators? In some sense, yes, it does. But it also makes it sane. Is anyone so upset by this that it didn't make it into the language, or cause huge confusion on a regular basis that upsets a lot of users? Nope. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Do not seek death. Death will find you. -- Dag Hammarskjold From nmm1 at cam.ac.uk Mon Aug 24 04:24:50 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Mon, 24 Aug 2009 09:24:50 +0100 (BST) Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> Message-ID: In article <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e at w6g2000yqw.googlegroups.com>, sturlamolden wrote: >On 24 Aug, 02:26, nos... at see.signature (Richard Maine) wrote: > >> You missed the word "OOP", which seemed like the whole point. Not that >> the particular word is used in the Fortran standard, but it isn't hard >> to guess that he means a derived type that uses some of the OOP >> features. Inheritance, polymorphism, and type-bound procedure (aka >> methods in some other languages) come to mind. > >But C is not OOP. The ISO C bindings in Fortran are not ISO C++ >bindings. This is for a reason: C++ does not have a standard ABI like >ISO C. Nor does C. Almost everything that most people believe about C is wrong, because C is not well-defined at any level, so there are many twisty little C languages, all different. Richard is perfectly correct that my point was OOP. C interoperability does not apply to any derived type with type-bound procedures, which include finalizers. Note that this ALSO forbids them from being passed as data, even if the other language never uses the OOP features of the type. Regards, Nick Maclaren. From james.harris.1 at googlemail.com Mon Aug 24 04:25:35 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Mon, 24 Aug 2009 01:25:35 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: On 24 Aug, 09:05, Erik Max Francis wrote: ... > >> Here's another suggested number literal format. First, keep the > >> familar 0x and 0b of C and others and to add 0t for octal. (T is the > >> third letter of octal as X is the third letter of hex.) The numbers > >> above would be > > >> ? 0b1011, 0t7621, 0xc26b > > >> Second, allow an arbitrary number base by putting base and number in > >> quotes after a zero as in > > >> ? 0"2:1011", 0"8:7621", 0"16:c26b" > > > Why not just put the base first, followed by the value in quotes: > > > ? ? 2"1011", 8"7621", 16"c26b" > > It's always a bit impressive how syntax suggestions get more and more > involved and, if you'll forgive me for saying, ridiculous as the > conversation continues. ?This is starting to get truly nutty. Why do you say that here? MRAB's suggestion is one of the clearest there has been. And it incorporates the other requirements: starts with a digit, allows an appropriate alphabet, has no issues with spacing digit groups, shows clearly where the number ends and could take an exponent suffix. James From hendrik at microcorp.co.za Mon Aug 24 04:29:20 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 24 Aug 2009 10:29:20 +0200 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: <200908241029.20487.hendrik@microcorp.co.za> On Monday 24 August 2009 01:04:37 bartc wrote: > That's a neat idea. But an even simpler scheme might be: > > .octal.100 > .decimal.100 > .hex.100 > .binary.100 > .trinary.100 > > until it gets to this anyway: > > .thiryseximal.100 Yeah right. So now I first have to type a string, which probably has a strict spelling, before a number. It is only marginally less stupid than this: 1.0 - Unary 11.0101 - Binary 111. 012012 - Trinary 11111111.01234567 - Octal 1111111111.0123456789 - Decimal 1111111111111111.0123456789abcdef - Hex Any parser that can count will immediately know what to do. I also tried to include an example of a literal with a base of a Googol but I ran out of both ink and symbols. :-) - Hendrik From max at alcyone.com Mon Aug 24 04:30:11 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 01:30:11 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <_oidnbiiYrgJ0g_XnZ2dnUVZ_uVi4p2d@giganews.com> James Harris wrote: > On 24 Aug, 09:05, Erik Max Francis wrote: >>>> Here's another suggested number literal format. First, keep the >>>> familar 0x and 0b of C and others and to add 0t for octal. (T is the >>>> third letter of octal as X is the third letter of hex.) The numbers >>>> above would be >>>> 0b1011, 0t7621, 0xc26b >>>> Second, allow an arbitrary number base by putting base and number in >>>> quotes after a zero as in >>>> 0"2:1011", 0"8:7621", 0"16:c26b" >>> Why not just put the base first, followed by the value in quotes: >>> 2"1011", 8"7621", 16"c26b" >> It's always a bit impressive how syntax suggestions get more and more >> involved and, if you'll forgive me for saying, ridiculous as the >> conversation continues. This is starting to get truly nutty. > > Why do you say that here? MRAB's suggestion is one of the clearest > there has been. And it incorporates the other requirements: starts > with a digit, allows an appropriate alphabet, has no issues with > spacing digit groups, shows clearly where the number ends and could > take an exponent suffix. In your opinion. Obviously not in others. Which is pretty obviously what I meant, so the rhetorical question is a bit weird here. There's a reason that languages designed by committee end up horrific nightmares. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Do not seek death. Death will find you. -- Dag Hammarskjold From max at alcyone.com Mon Aug 24 04:35:47 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 01:35:47 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: James Harris wrote: > On 24 Aug, 02:19, Max Erickson wrote: >>> It can be assumed however that .9. isn't in binary? >>> That's a neat idea. But an even simpler scheme might be: >>> .octal.100 >>> .decimal.100 >>> .hex.100 >>> .binary.100 >>> .trinary.100 >>> until it gets to this anyway: >>> .thiryseximal.100 >> At some point, abandoning direct support for literals and just >> having a function that can handle different bases starts to make a >> lot of sense to me: >> >>>>> int('100', 8) >> 64 >>>>> int('100', 10) >> 100 >>>>> int('100', 16) >> 256 >>>>> int('100', 2) >> 4 >>>>> int('100', 3) >> 9 >>>>> int('100', 36) >> 1296 > > This is fine typed into the language directly but couldn't be entered > by the user or read-in from or written to a file. Why would a programmer be expecting an arbitrary-radix numeric literal typed in by a user or read from a file? If you're reading it from a file, you've already got it in some satisfactory form, binary or otherwise. If you're taking it as input from a user, they're not going to know the Python syntax anyway, and would type in the radix and then the literal (in the unlikely case this would ever be required, which is still hard to imagine). Either way, conversion is, as Max showed, one line of code. It's hard to see the explicit need for truly arbitrary-radix literals in any language -- and I'm the guy who's put quaternary literals in syntaxes he's had to develop just for fun. Binary, octal, decimal, hexadecimal, sure. Beyond that it's a solution begging for problems. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Do not seek death. Death will find you. -- Dag Hammarskjold From hendrik at microcorp.co.za Mon Aug 24 04:40:06 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 24 Aug 2009 10:40:06 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a91db65$0$305$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> Message-ID: <200908241040.06613.hendrik@microcorp.co.za> On Monday 24 August 2009 02:14:24 Esben von Buchwald wrote: > Hello > > I'm using Python for S60 1.9.7 on my Nokia phone. > > I've made a program that gets input from an accelerometer sensor, and > then calculates some stuff and displays the result. > > The sensor framework API does a callback to a function defined by me, > every time new data is available. > > The problem is, that sometimes, the calculations may take longer than > others, but if the callback is called before the first calculation is > done, it seems like it's queuing up all the callbacks, and execute them > sequentially, afterwards. > > What I need, is to simply ignore the callback, if the previous call > hasn't finished it's operations before it's called again. > > I thought that this code would do the trick, but it obviously doesn't > help at all, and i can't understand why... > > def doCallback(self): > if self.process_busy==False: > self.process_busy=True > self.data_callback() > self.process_busy=False > see if there is an "after" method somewhere. What you have to do is to "break the link" between the callback and the processing. Your code above is all in the callback "thread", despite the fact that you call another function to do the processing. So if you replace the data_callback() with an after call, it should work as you expect. HTH - Hendrik From max at alcyone.com Mon Aug 24 04:41:14 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 01:41:14 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: Hendrik van Rooyen wrote: > I also tried to include an example of a literal with a base of a Googol but I > ran out of both ink and symbols. > :-) ... or particles in the observable Universe, for that matter. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Do not seek death. Death will find you. -- Dag Hammarskjold From piet at cs.uu.nl Mon Aug 24 04:41:58 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 24 Aug 2009 10:41:58 +0200 Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> Message-ID: >>>>> Dennis Lee Bieber (DLB) wrote: >DLB> On Sun, 23 Aug 2009 22:14:17 -0700, John Nagle >DLB> declaimed the following in gmane.comp.python.general: >>> Multiple Python processes can run concurrently, but each process >>> has a copy of the entire Python system, so the memory and cache footprints are >>> far larger than for multiple threads. >>> >DLB> One would think a smart enough OS would be able to share the >DLB> executable (interpreter) code, and only create a new stack/heap >DLB> allocation for data. Of course they do, but a significant portion of a Python system consists of imported modules and these are data as far as the OS is concerned. Only the modules written in C which are loaded as DLL's (shared libs) and of course the interpreter executable will be shared. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 24 04:44:21 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 24 Aug 2009 10:44:21 +0200 Subject: Items inheriting attributes from its container? In-Reply-To: References: Message-ID: <4a9252e5$0$17143$426a74cc@news.free.fr> Kreso a ?crit : > I would like to create a list-like container class so that, additionally > to usual list methods, I could attach attributes to the container instances. > However, I would like it so that the items contained in the particular > instance of container somehow 'inherit' those attributes i.e. > > cont = Container() > cont.color = 'blue' > cont.append(item) > print item.color > 'blue' > This is named "environmental aquisition" (or simply "aquisition") and is one of the base mechanisms in Zope 2. While an interesting idea, from experience, it can rapidly turn into a total maintainance nightmare if not used with care :-/ From james.harris.1 at googlemail.com Mon Aug 24 04:47:44 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Mon, 24 Aug 2009 01:47:44 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <_oidnbiiYrgJ0g_XnZ2dnUVZ_uVi4p2d@giganews.com> Message-ID: On 24 Aug, 09:30, Erik Max Francis wrote: > James Harris wrote: > > On 24 Aug, 09:05, Erik Max Francis wrote: > >>>> Here's another suggested number literal format. First, keep the > >>>> familar 0x and 0b of C and others and to add 0t for octal. (T is the > >>>> third letter of octal as X is the third letter of hex.) The numbers > >>>> above would be > >>>> ? 0b1011, 0t7621, 0xc26b > >>>> Second, allow an arbitrary number base by putting base and number in > >>>> quotes after a zero as in > >>>> ? 0"2:1011", 0"8:7621", 0"16:c26b" > >>> Why not just put the base first, followed by the value in quotes: > >>> ? ? 2"1011", 8"7621", 16"c26b" > >> It's always a bit impressive how syntax suggestions get more and more > >> involved and, if you'll forgive me for saying, ridiculous as the > >> conversation continues. ?This is starting to get truly nutty. > > > Why do you say that here? MRAB's suggestion is one of the clearest > > there has been. And it incorporates the other requirements: starts > > with a digit, allows an appropriate alphabet, has no issues with > > spacing digit groups, shows clearly where the number ends and could > > take an exponent suffix. > > In your opinion. ?Obviously not in others. ?Which is pretty obviously > what I meant, so the rhetorical question is a bit weird here. Don't get defensive.... Yes, in my opinion, if you like, but you can't say "obviously not in others" as no one else but you has commented on MRAB's suggestion. Also, when you say "This is starting to get truly nutty" would you accept that that's in your opinion? > There's a reason that languages designed by committee end up horrific > nightmares. True but I would suggest that mistakes are also made by designers who do not seek the opinions of others. There's a balance to be struck between a committee and an ivory tower. James From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 24 04:54:31 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 24 Aug 2009 10:54:31 +0200 Subject: Newbie: list comprehension troubles.. In-Reply-To: References: Message-ID: <4a925547$0$22644$426a74cc@news.free.fr> mm a ?crit : > Hi, I'm trying to replace this... > > # this works but there must be a more pythonic way, right? > tlist = [] > for obj in self.objs: > t = obj.intersect(ray) > if (t != None): hint 1 : this is Python, you don't need parens around conditionals. hint 2 : None is a singleton, so the usual idiom is to test for identity ('is') instead of equality ('==') IOW, make this line: if t is not None: > tlist.append((obj,t)) > > with a list comprehension- can it be done? See other answers here. As far as I'm concerned, while being a great fan of list comps etc, I'd stick with the plain old for loop here - much more readable if nothing else. From davea at ieee.org Mon Aug 24 05:04:19 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 24 Aug 2009 05:04:19 -0400 Subject: sgmllib.py In-Reply-To: References: Message-ID: <4A925793.9030305@ieee.org> elsa wrote: > Hi all, > > I'm new to both this forum and Python, and I've got a bit stuck trying > to learn how to parse HTML.... here is my problem > > I'm using a textbook that uses sgmllib.py for all its examples. I'm > aware that sgmllib is not in the current release, however I want to > get it to work, as I have python 2.5, and the text book uses it. > > So, the first example says to type something like (to test the > sgmllib): > > python sgmllib.py "path/to/my/file.html" .... example (1) > > this doesn't work for me. I think I have figured out the problem - > the error says > > "/System/Library/Frameworks/Python.framework/Versions/2.5/Resources/ > Python.app/Contents/MacOS/Python: can't open file 'sgmllib.py': [Errno > 2] No such file or directory" > > the problem is that this path is wrong. My sgmllib.py is in: > > "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/sgmllib.py" > > if I substitute this path for sgmllib.py in example (1), everything > works fine. However, I don't want to do all that typing everytime I > want to use sgmllib.py. So, I thought maybe the problem was with > PYTHONPATH. I executed the following command: > > export PYTHONPATH=/System/Library/Frameworks/Python.framework/Versions/ > 2.5/li/python2.5:$PYTHONPATH > > this seemed to work - no errors raised. However, when I retyped > example (1), I got the same original error. > > Any assistance would be much appreciated. I'm working on max os x > leopard. > > Thanks, > > elsa > > The path in the error message simply refers to the full path string to your Python interpreter, and reflects %0 in your shell. So I'd assume you've got a script called 'python' on your path, which spells out the full path name. That has nothing to do with your problem. Your problem, as you correctly surmised, is that Python's search path doesn't include the directory containing sgmllib.py Unfortunately, I haven't used Unix for over 15 years, so I don't recall the specifics of the shell 'export' operation. But you should be able to check the workings by inspecting the PYTHONPATH variable after trying to change it. There are a number of places that Python looks for a .py file. My choice, for a standard library like this that you don't plan to modify, would be to put it in the site-packages directory. You can see exactly where that is by doing the following in a simple script, and examining the output. import sys print sys.path From deets at nospam.web.de Mon Aug 24 05:06:00 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Aug 2009 11:06:00 +0200 Subject: Python and JMS References: <679a2898-abf1-4938-a456-59e0bf5ba666@k6g2000yqn.googlegroups.com> Message-ID: <7ff3foF2kcl0rU1@mid.uni-berlin.de> osky wrote: > Hi all, > > I would like to make a JMS client connection from Python to Progress > Sonic ESB (JMS message provider similar to WebSphere MQ or Active > MQ). > > What would be the best way to implement that within Python 2.6 ? > Any ideas ? I just recently learned about JCC - a Java-wrapper-compiler for python that is used by pylucene to embed (!) the JVM into python. This might be one viable option. I don't know much more, though. Diez From stefan_ml at behnel.de Mon Aug 24 05:16:38 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 11:16:38 +0200 Subject: sgmllib.py In-Reply-To: References: Message-ID: <4a925a76$0$32668$9b4e6d93@newsspool2.arcor-online.net> Dave Angel schrieb: > elsa wrote: >> python sgmllib.py "path/to/my/file.html" .... example (1) > > The path in the error message simply refers to the full path string to > your Python interpreter, and reflects %0 in your shell. So I'd assume > you've got a script called 'python' on your path, which spells out the > full path name. No, the problem is that "sgmllib.py" simply isn't in the directory where the Python interpreter is run. When you say python sgmllib.py you are instructing the Python interpreter to run the script "sgmllib.py" *in the current directory*. According to the original post, that's clearly not the intention of the OP. Stefan From davea at ieee.org Mon Aug 24 05:23:24 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 24 Aug 2009 05:23:24 -0400 Subject: basic thread question In-Reply-To: References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> Message-ID: <4A925C0C.4090906@ieee.org> Dennis Lee Bieber wrote: > On Sun, 23 Aug 2009 22:14:17 -0700, John Nagle > declaimed the following in gmane.comp.python.general: > > >> Multiple Python processes can run concurrently, but each process >> has a copy of the entire Python system, so the memory and cache footprints are >> far larger than for multiple threads. >> >> > One would think a smart enough OS would be able to share the > executable (interpreter) code, and only create a new stack/heap > allocation for data. > That's what fork is all about. (See os.fork(), available on most Unix/Linux) The two processes start out sharing their state, and only the things subsequently written need separate swap space. In Windows (and probably Unix/Linux), the swapspace taken by the executable and DLLs(shared libraries) is minimal. Each DLL may have a "preferred location" and if that part of the address space is available, it takes no swapspace at all, except for static variables, which are usually allocated together. I don't know whether the standard build of CPython (python.exe and the pyo libraries) uses such a linker option, but I'd bet they do. It also speeds startup time. On my system, a minimal python program uses about 50k of swapspace. But I'm sure that goes way up with lots of imports. DaveA From davea at ieee.org Mon Aug 24 05:29:43 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 24 Aug 2009 05:29:43 -0400 Subject: elementtree In-Reply-To: <4a923d8b$0$32664$9b4e6d93@newsspool2.arcor-online.net> References: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> <4a923d8b$0$32664$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4A925D87.5010905@ieee.org> Stefan Behnel wrote: > Hi, > > elsa wrote: > >> I know how to turn HTML into an ElementTree object >> > > I don't. ;) > > ElementTree doesn't have an HTML parser, so what do you use for parsing? > > > >> but I don't know >> how to then view the structure of this object. Is there a method or >> module that you can give an ElementTree object to, and it returns some >> kind of graphical or printed representation of the tree? Otherwise, if >> you can't see you're tree's structure, how do you know what is a >> sensible way of iterating over the tree to access the info you need? >> > > ElementTree has a tostring() method that returns a string. To get a pretty > printed representation, you can use the indent() function from this recipe: > > http://effbot.org/zone/element-lib.htm#prettyprint > > Stefan > > Perhaps the OP was referring to XHTML, which should be eligible for ElementTree. But could you tell me whether ElementTree is at all tolerant of malformed XML? Most HTML and XHTML I encounter in the wild is so buggy it's amazing it all works at all. DaveA From stefan_ml at behnel.de Mon Aug 24 05:54:39 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 11:54:39 +0200 Subject: elementtree In-Reply-To: References: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> <4a923d8b$0$32664$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4a92635f$0$32678$9b4e6d93@newsspool2.arcor-online.net> Dave Angel wrote: > Stefan Behnel wrote: >> elsa wrote: >>> I know how to turn HTML into an ElementTree object >> >> I don't. ;) >> >> ElementTree doesn't have an HTML parser, so what do you use for parsing? >> > Perhaps the OP was referring to XHTML, which should be eligible for > ElementTree. But could you tell me whether ElementTree is at all > tolerant of malformed XML? Most HTML and XHTML I encounter in the wild > is so buggy it's amazing it all works at all. Well, if the XHTML is "buggy", it's not XHTML at all. XHTML is XML, which is defined as being well-formed. Any XHTML parser is required to reject malformed input, and the expat parser that ElementTree uses is (luckily) no exception. Regarding malformed HTML: that's not directly supported by ElementTree, hence my question. You can use ElementSoup to interface with BeautifulSoup, or elementtidy to interface with tidy, or html5lib with ElementTree as backend, or you can use lxml instead, which handles malformed HTML (and is all fast and shiny and ... ;). Stefan From stefan_ml at behnel.de Mon Aug 24 06:12:19 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 12:12:19 +0200 Subject: Python and JMS In-Reply-To: <679a2898-abf1-4938-a456-59e0bf5ba666@k6g2000yqn.googlegroups.com> References: <679a2898-abf1-4938-a456-59e0bf5ba666@k6g2000yqn.googlegroups.com> Message-ID: <4a926783$0$32673$9b4e6d93@newsspool2.arcor-online.net> osky wrote: > I would like to make a JMS client connection from Python to Progress > Sonic ESB (JMS message provider similar to WebSphere MQ or Active > MQ). Never needed this, but Google gives me this as first hit http://hjb.python-hosting.com/ and this c.l.py thread reference a little further down: http://mail.python.org/pipermail/python-list/2006-July/567400.html Stefan From pavlovevidence at gmail.com Mon Aug 24 06:56:08 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 24 Aug 2009 03:56:08 -0700 (PDT) Subject: Literal concatenation, strings vs. numbers (was: Numeric literals in other than base 10 - was Annoying octal notation) References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> <7fe9mbF2l83bmU1@mid.individual.net> <871vn2gcai.fsf_-_@benfinney.id.au> Message-ID: <3353e3ec-384a-4786-bd33-b26ab26df129@l5g2000yqo.googlegroups.com> On Aug 23, 7:45?pm, Ben Finney wrote: > greg writes: > > J. Cliff Dyer wrote: > > > > What happens if you use a literal like 0x10f 304? > > > To me the obvious thing to do is concatenate them textually and then > > treat the whole thing as a single numeric literal. Anything else > > wouldn't be sane, IMO. > > Yet, as was pointed out, that behaviour would be inconsistent with the > concatenation of string literals:: > > ? ? >>> "abc" r'def' u"ghi" 'jkl' > ? ? u'abcdefghijkl' Well my take on it is that this would not be the same as string concatenation, the series of digits would be parsed as a single token with spaces automatically removed. That does make a difference to the users (it's not just under the covers). For instance, string concatenation works across lines: "abc" "def" but if the numbers were parsed as a single token it wouldn't necessarily be allowed, and would be unwise, so this is out: 100 200 You might want to also enforce rules such as only a single space can separate digits, no tabs, not multiple spaces, so this 100 200 would also be right out. You might even want to enforce that spaces be at regular intervals. I don't think it would matter too much that digit separation can superficially resemble string concatenation if you don't break the strings across lines, it's not too difficult to explain what the difference is, and there's really not much chance anyone would be confused by their meanings. Having said all that, I would favor _ as a digit separator in Python any day of the week, and I don't think it's all that important to have one at all. HOWEVER, I once proposed that if I were designing a new language I'd consider allowing spaces in identifiers. (That didn't stop people from arguing why it would be confusing in Python, but never mind that.) If spaces were allowed in identifiers, then I'd be also in favor of spaces in numeric literals. > So, different representations of literals are parsed as separate > literals, then concatenated. To have the behaviour you describe, the > case needs to be made separately that digit concatenation should not be > consistent with the established string literal parsing behaviour. Well, one doesn't really *need* to make that case, they just might not care about consistency. But if they did I think Erik's case is a good one: very little chance of confusion because there's really only one reasonable interpretation. The point of consistency is to help understand things by analogy, but if analogy doesn't help understanding--and it wouldn't in this case--there's no point. Carl Banks From pavlovevidence at gmail.com Mon Aug 24 07:00:46 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 24 Aug 2009 04:00:46 -0700 (PDT) Subject: elementtree References: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> <4a923d8b$0$32664$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <446e340c-82cc-4533-ae64-53d45ce765a2@24g2000yqm.googlegroups.com> On Aug 24, 12:13?am, Stefan Behnel wrote: > Hi, > > elsa wrote: > > I know how to turn HTML into an ElementTree object > > I don't. ;) > > ElementTree doesn't have an HTML parser, so what do you use for parsing? The OP could be feeding the HTML through tidy, or it could be XHTML. > > but I don't know > > how to then view the structure of this object. Is there a method or > > module that you can give an ElementTree object to, and it returns some > > kind of graphical or printed representation of the tree? Otherwise, if > > you can't see you're tree's structure, how do you know what is a > > sensible way of iterating over the tree to access the info you need? > > ElementTree has a tostring() method that returns a string. To get a pretty > printed representation, you can use the indent() function from this recipe: > > http://effbot.org/zone/element-lib.htm#prettyprint Another possibility is to write out the ElementTree object as XML with an .xml extension, and view it in a modern web browser (Firefox, IE, others maybe) that can show XML structure. Carl Banks From martin.hellwig at dcuktec.org Mon Aug 24 07:06:30 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Mon, 24 Aug 2009 12:06:30 +0100 Subject: can python make web applications? In-Reply-To: References: Message-ID: Deep_Feelings wrote: > can python make powerfull database web applications that can replace > desktop database applications? e.g: entrprise accounting > programs,enterprise human resource management programs ...etc As the other replies already mentioned that these already exists, I would like to add that with Pyjamas you can write 'webgui' programs relatively easily: http://pyjs.org/ -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From piet at cs.uu.nl Mon Aug 24 07:21:03 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 24 Aug 2009 13:21:03 +0200 Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> Message-ID: >>>>> Dave Angel (DA) wrote: >DA> Dennis Lee Bieber wrote: >>> On Sun, 23 Aug 2009 22:14:17 -0700, John Nagle >>> declaimed the following in gmane.comp.python.general: >>> >>> >>>> Multiple Python processes can run concurrently, but each process >>>> has a copy of the entire Python system, so the memory and cache footprints are >>>> far larger than for multiple threads. >>>> >>>> >>> One would think a smart enough OS would be able to share the >>> executable (interpreter) code, and only create a new stack/heap >>> allocation for data. >>> >DA> That's what fork is all about. (See os.fork(), available on most >DA> Unix/Linux) The two processes start out sharing their state, and only the >DA> things subsequently written need separate swap space. But os.fork() is not available on Windows. And I guess refcounts et al. will soon destroy the sharing. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From jeanmichel at sequans.com Mon Aug 24 07:33:07 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 Aug 2009 13:33:07 +0200 Subject: your favorite debugging tool? In-Reply-To: References: Message-ID: <4A927A73.5080207@sequans.com> Esmail wrote: > Hi all, > > What is your favorite tool to help you debug your > code? I've been getting along with 'print' statements > but that is getting old and somewhat cumbersome. > > I'm primarily interested in utilities for Linux (but > if you have recommendations for Windows, I'll take > them too :) > > I use emacs as my primary development environment, FWIW. > Someone mentioned winpdb .. anyone have experience/comments > on this? Others? > > Thanks, > Esmail > I execute the program within IPython. >>> run test.py I usually write a CTRL+C except clause that will spawn an Ipython shell so I can inspect the namespace at that time. I'm also using the ipdb to spawn the debugger. import IPython ipdb = IPython.Debugger.Pdb(color_scheme='Linux') ipdb.set_trace() it spawns the IPython debugger, allowing step by step execution, code inspection, changing the namespace. You get all the IPython benefits (espacially the TAB completion, history ...) I used to proceed with print statements, but they are some situations where it won't just make it. Sometimes the code is so complex you can't anticipate all the required prints to catch a bug. JM From bieffe62 at gmail.com Mon Aug 24 07:42:29 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Mon, 24 Aug 2009 04:42:29 -0700 (PDT) Subject: Newbie: list comprehension troubles.. References: Message-ID: <86e872ed-eb86-4def-ad55-49ee60f61cf0@a26g2000yqn.googlegroups.com> On 24 Ago, 01:27, mm wrote: > Hi, I'm trying to replace this... > > ? ? ? ? # this works but there must be a more pythonic way, right? > ? ? ? ? tlist = [] > ? ? ? ? for obj in self.objs: > ? ? ? ? ? ? t = obj.intersect(ray) > ? ? ? ? ? ? if (t != None): > ? ? ? ? ? ? ? ? tlist.append((obj,t)) > > with a list comprehension- can it be done? > > What I need to do is iterate over a list of graphics primitives and > call their intersect method. If the returned t value is not None then > I want to store the obj refernence and its t value in a list of tuples > for further processing. I've tried stuff like ... > > ? ? ? ? tlist = [(obj,t) for obj,t in (self.objs, obj.intersect(ray)) > if (t != None)] > ? ? ? ? tlist = [(obj,t) for obj in self.objs for t in obj.intersect > (ray) ] > ? ? ? ? print ">>> ",len(tlist), tlist > > but they don't work. Any help greatly appreciated. matt What about this: def intersections(objlist, ray): for obj in objlist: yield obj, obj.intersect(ray) tlist = [(obj, t) in intersections(self.objs, ray) if t != None ] It is still quite readable but a bit more compact. More efficient? Maybe. Ciao ---- FB From nospam at nospam.com Mon Aug 24 08:08:40 2009 From: nospam at nospam.com (Gilles Ganault) Date: Mon, 24 Aug 2009 14:08:40 +0200 Subject: Python for professsional Windows GUI apps? Message-ID: Hello I was wondering if some people in this ng use Python and some GUI toolkit (PyWin32, wxWidgets, QT, etc.) to build professional applications, and if yes, what it's like, the pros and cons, etc. I'm especially concerned about the lack of controls, the lack of updates (lots of controls in wxWidgets are 1.0 deadware), and problems linked to how to update users' PC remotely when I build a new version using eg. Py2exe. I need controls for business apps like access to databases, good data grid, printing reports (with or without barcodes), etc. Thank you. From jeanmichel at sequans.com Mon Aug 24 08:08:47 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 Aug 2009 14:08:47 +0200 Subject: Is Python what I need? In-Reply-To: References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: <4A9282CF.3000204@sequans.com> Peter Otten wrote: > newbie wrote: > > >> I'm interested in developing computer based, interactive programs for >> students in a special school who have an aversion to pen and paper. >> I've searched the net to find ready made software that will meet my >> needs but it is either written to a level much higher than these >> students can cope with or priced beyond our school budget. I came >> across a blog of someone singing the praises of Python. My question is >> therefore aimed at those that know what they are talking about (ie >> users in this group). Is Python the language I need to learn to >> develop these programs? >> > > >From the distance it looks like these children need a good teacher rather > than a bad (or just starting) programmer. Wow, that is rude. Let's keep this list friendly, won't we ? JM From nevillednz at gmail.com Mon Aug 24 08:22:42 2009 From: nevillednz at gmail.com (NevilleDNZ) Date: Mon, 24 Aug 2009 05:22:42 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: On Aug 23, 9:42 pm, James Harris wrote: > The numbers above would be > > 0b1011, 0t7621, 0xc26b Algol68 has the type BITS, that is converted to INT with the ABS operator. The numbers above would be: > 2r1011, 8r7621, 16rc26b "r" is for radix: http://en.wikipedia.org/wiki/Radix The standard supports 2r, 4r, 8r & 16r only. The standard supports LONG BITS, LONG LONG BITS etc, but does not include UNSIGNED. Compare gcc's: bash$ cat num_lit.c #include main(){ printf("%d %d %d %d\n",0xffff,07777,9999,0b1111); } bash$ ./num_lit 65535 4095 9999 15 With Algol68's: https://sourceforge.net/projects/algol68/ bash$ cat num_lit.a68 main:( printf(($g$,ABS 16rffff,ABS 8r7777,9999,ABS 2r1111,$l$)) ) bash$ algol68g ./num_lit.a68 +65535 +4095 +9999 +15 Enjoy N From dmw at coder.cl Mon Aug 24 08:29:48 2009 From: dmw at coder.cl (Daniel Molina Wegener) Date: Mon, 24 Aug 2009 08:29:48 -0400 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module References: <2571343.k9db9GJWqV@coder.cl> <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <2665032.o6QR52tnKS@coder.cl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Stefan Behnel on Monday 24 August 2009 03:16 wrote in comp.lang.python: > Daniel Molina Wegener wrote: >> * Added encoded serialization of Unicode strings by using >> the user defined encoding as is passed to the serialization >> functions as enc parameter >> >> As you see, now Unicode strings are serialized as encoded byte string >> by using the encoding that the user pass as enc parameter to the >> serialization function. This means that Unicode strings are serialized >> in a human readable form, regarding a better interoperability with >> other platforms. > > You mean, the whole XML document is serialised with that encoding, right? Well, if you call pyxser with: xmldocstr = pyxser.serialize(obj = someobj, enc = "utf-8", depth = 3) pyxser will serialize someobj into XML document (xmldocstr) using the utf-8 encoding with a depth of three levels in the object tree. If the object tree has unicode objects, those objects will be encoded into utf-8 too. And yes, it means that unicode objects are encoded into the encoding that the XML document encoding has, and as you say, the whole XML document has one encoding. There is no mixing of byte encoded strings with different encodings in the outout document. When the object is restored, by using pyxser.unserialize: pyobj = pyxser.unserialize(obj = xmldocstr, enc = "utf-8") Unicode objects are restored as unicode objects, by decoding the utf-8 strings on the document. Byte string objects are restored as byte string objects. And the other types of objects are restored as their original type. Another issue is the fact that if you have mixed some encodings in byte strings objects in your object tree, such as iso-8859-1 and utf-8, and you try to serialize that object, pyxser will output to stdout the serialization errors by trying to handle those mixed encodings which are not regarding the document encoding. There are some restrictions, if the class of the object is declared on the __main__ module, pyxser can not handle it... This is a bug but I'm expecting to solve it in near future. A depth level of zero (depth = 0) will serialize the complete object tree with a fixed limit of 50 levels, pyxser can handle cross referenced objects and circular references. Sorry if don't answer more questions until we reach the night --- here in Chile --- the night, I must go to my job right now, and there I don't have access to usenet or google groups. > > Stefan Best regards, - -- .O. | Daniel Molina Wegener | FreeBSD & Linux ..O | dmw [at] coder [dot] cl | Open Standards OOO | http://coder.cl/ | FOSS Developer -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (FreeBSD) iQIcBAEBCgAGBQJKkoe8AAoJEHxqfq6Y4O5Na3gP/R2BTdmZpUPn8PrsPhMPaKLf dmAUAyQ2Ukj1461eiYGAa1zly5bz/rKV8UJXq6zp0cFIIimBHWCYkFlbtCIdCl5k qclT6y3d5N9/VggZi92ICK4xFe4CCOzLeJCaYkBcVgvbpks9oRJwlS9LrTZAMdOw WdnaUdNadj2lRcXHwqV7uk5D5CwBdNujgpp+7vJXZbEnPD9diXEbPDUeHznn7cEa 2zwtGK3+kyPEkLpS5F+zE2iPUQK+HOw4r1s7kow9mSUU0n3p+gJj9J0NtBKDa92d hXGQ6M52jtoyZlv0bWJl8R1YQLnezvNDMu9F/NqB79wmLhJqIZm3Py57rtIaD96J 2a7BN/LcM8fhs+dgTlt6538EKoM5Jj+gv+birSIUwxKFChRpGsj7229cmTzjQc7q mcXlXPa6aknOWxVlhPSpGDSbZ+HpqGH7s9cOHAAuUt+WRcaafeRpy7K3BXJ+AaJ6 Rz69j2nsOgqGufLlBiDf9aRIrX3A47eE0DGZLwVuolValgmBhgedn43T4XH85wrE BfXERoIrIlMS8hmcxs6Ao6TayLHmaZjSVaLmP+qsN9qHCs8hCbQBNBfaU1vrsM2u nppo/+yGepLGZSW35yA8ha7m3RAX1HTyHcKrPcrbTmK5IVjVWjHRbTz4XcqNt1v6 5prWXP8WUIfIr4E2112J =JjU5 -----END PGP SIGNATURE----- From ryniek90 at gmail.com Mon Aug 24 08:44:59 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Mon, 24 Aug 2009 14:44:59 +0200 Subject: Temat:,Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: References: Message-ID: <4A928B4B.9030502@gmail.com> >> John Machin wrote: >> >>> Erik Max Francis alcyone.com> writes: >>> > > >> I also suspect the "pipe" symbol. I don't know if it's an invalid >> character to Windows, but it's certainly a bad idea. The '|' character >> means something special to the shell. >> > > The "pipe" character is not a valid character in a Windows file. > Despite the OP's message wrapping the filename in "pipes", > there are no pipes in the filename in the traceback to > which he posted a link. Wrapping the filename in "pipes" > and the cryptic reference to "the '|\U' literal fault" > appear to be side-issue bogglements. > > >>> open('boggle|txt', 'wb') > Traceback (most recent call last): > File "", line 1, in > IOError: [Errno 22] invalid mode ('wb') or filename: 'boggle|txt' > >>> open('|boggle.txt|', 'wb') > Traceback (most recent call last): > File "", line 1, in > IOError: [Errno 22] invalid mode ('wb') or filename: '|boggle.txt|' > > > > Sorry, but i don't know where those pipes came from : P The proper path is "C:\\Users\\Ryniek's WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2" and that string literal is "\U", without any pipes :) The truth is that script works on linux (ubuntu) but not on windows (neither Win7 nor WinXP). Maybe it's good idea to use raw string for specifing those paths? As i mentioned later, some python users had the same problem with this IOError ( like here: http://www.daniweb.com/forums/thread174552.html or here: http://groups.google.com/group/sympy/browse_thread/thread/c42aca3eb532928c ). From stefan_ml at behnel.de Mon Aug 24 09:00:06 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 15:00:06 +0200 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module In-Reply-To: <2665032.o6QR52tnKS@coder.cl> References: <2571343.k9db9GJWqV@coder.cl> <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> <2665032.o6QR52tnKS@coder.cl> Message-ID: <4a928ed7$0$32666$9b4e6d93@newsspool2.arcor-online.net> Daniel Molina Wegener wrote: > unicode objects are encoded into the > encoding that the XML document encoding has, and as you say, the whole > XML document has one encoding. There is no mixing of byte encoded strings > with different encodings in the outout document. Ok, that's what I hoped anyway. It just wasn't clear from your description. > When the object is restored, by using pyxser.unserialize: > > pyobj = pyxser.unserialize(obj = xmldocstr, enc = "utf-8") But this is XML, right? What do you need to pass the encoding for at this point? > Another issue is the fact that if you have mixed some encodings in byte > strings objects in your object tree, such as iso-8859-1 and utf-8, and > you try to serialize that object, pyxser will output to stdout the > serialization errors by trying to handle those mixed encodings which are > not regarding the document encoding. There shouldn't be any serialisation errors (unless you try to recode byte strings on the way out, which is a no-no for arbitrary user input). All you have to do is properly escape the byte string so that it passes the XML encoding step. One trick to do that is to decode the byte string as ISO-8859-1 and serialise the result as a normal Unicode string. Then you can re-encode the unicode string on input back to ISO-8859-1. I choose ISO-8859-1 here because it has the well-defined side-effect of mapping byte values directly to Unicode characters with an identical code point value. So you do not risk any failures or data loss. Stefan From mwilson at the-wire.com Mon Aug 24 09:05:24 2009 From: mwilson at the-wire.com (Mel) Date: Mon, 24 Aug 2009 09:05:24 -0400 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: James Harris wrote: > On 24 Aug, 02:19, Max Erickson wrote: [ ... ] >> >>> int('100', 3) >> 9 >> >>> int('100', 36) >> 1296 > > This is fine typed into the language directly but couldn't be entered > by the user or read-in from or written to a file. That's rather beside the point. Literals don't essentially come from files or user input. Essentially literals are a subset of expressions, just like function calls are, and they have to be evaluated by Python to yield a value. I'm not averse to 32'rst', but we already have Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> int ('rst', 32) 28573 Mel. > > James From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 24 09:07:58 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 24 Aug 2009 15:07:58 +0200 Subject: conditional for-statement In-Reply-To: References: Message-ID: <4a9290ad$0$406$426a34cc@news.free.fr> seb a ?crit : > Hi, > > i was wondering if there is a syntax alike: > > for i in range(10) if i > 5: > print i > > equivalent to > > for i in (for i in range(10) if i>5): > print i what about : for i in range(6, 10): print i More seriously: for i in range(10): if i > 5: print i From jjalocha at gmail.com Mon Aug 24 09:13:40 2009 From: jjalocha at gmail.com (Jerzy Jalocha N) Date: Mon, 24 Aug 2009 09:13:40 -0400 Subject: P3 weird sys.stdout.write() Message-ID: <9b72f9a90908240613i513597bbk83a30946ab0b04ae@mail.gmail.com> I've stumbled upon the following in Python 3: Python 3.0.1+ (r301:69556, Apr 15 2009, 15:59:22) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdout.write("") 0 >>> sys.stdout.write("something") something9 >>> write() is appending the length of the string to it's output. That's not how it worked in 2.6. What's the reason for this? Is this intended? I couldn't find a bug report for this. From deets at nospam.web.de Mon Aug 24 09:21:31 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Aug 2009 15:21:31 +0200 Subject: P3 weird sys.stdout.write() References: Message-ID: <7ffierF2ken49U1@mid.uni-berlin.de> Jerzy Jalocha N wrote: > I've stumbled upon the following in Python 3: > > Python 3.0.1+ (r301:69556, Apr 15 2009, 15:59:22) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> sys.stdout.write("") > 0 >>>> sys.stdout.write("something") > something9 >>>> > > write() is appending the length of the string to it's output. That's > not how it worked in 2.6. > > What's the reason for this? Is this intended? I couldn't find a bug > report for this. Write returns the number of bytes written. And because you don't capture that output into a variable, the interpreter puts it out as well. If you do >>> n = sys.stdout.write("") instead, you won't see the behavior. Diez From andre.roberge at gmail.com Mon Aug 24 09:22:36 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 24 Aug 2009 06:22:36 -0700 (PDT) Subject: P3 weird sys.stdout.write() References: Message-ID: <9ad77db9-08a7-474d-b6a3-588e82cd8b85@b15g2000yqd.googlegroups.com> On Aug 24, 10:13?am, Jerzy Jalocha N wrote: > I've stumbled upon the following in Python 3: > > Python 3.0.1+ (r301:69556, Apr 15 2009, 15:59:22) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > >>> import sys > >>> sys.stdout.write("") > 0 > >>> sys.stdout.write("something") > something9 > > write() is appending the length of the string to it's output. Not quite right, see below. > That's > not how it worked in 2.6. > > What's the reason for this? Is this intended? I couldn't find a bug > report for this. I don't know what the reason for the change, but try the following: >>> out = sys.stdout.write("test\n") test >>> out 5 What you are seeing is the concatenation of the return value of the write() method with its output. Andr? From __peter__ at web.de Mon Aug 24 09:32:48 2009 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Aug 2009 15:32:48 +0200 Subject: Is Python what I need? References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: Jean-Michel Pichavant wrote: >> >From the distance it looks like these children need a good teacher >> >rather than a bad (or just starting) programmer. > Wow, that is rude. Let's keep this list friendly, won't we ? I may have been too blunt, and if my message has come across as an insult I apologize for that. Let me try again: If you are trying to teach children that are unwilling to use pen and paper putting them in front of a computer doesn't help you and them one bit. As a starting programmer you'll have to spend a lot of time in front of your computer that may be better spent with your students. Better? Peter From code at pizzashack.org Mon Aug 24 09:42:31 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 08:42:31 -0500 Subject: Annoying octal notation In-Reply-To: <02a0ce27$0$30337$c3e8da3@news.astraweb.com> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <02a0ce27$0$30337$c3e8da3@news.astraweb.com> Message-ID: <20090824134231.GZ20434@dragontoe.org> On Sun, Aug 23, 2009 at 06:13:31AM +0000, Steven D'Aprano wrote: > On Sat, 22 Aug 2009 22:19:01 -0500, Derek Martin wrote: > > On Sat, Aug 22, 2009 at 02:55:51AM +0000, Steven D'Aprano wrote: > >> And the great thing is that now you get to teach yourself to stop > >> writing octal numbers implicitly and be write them explicitly with a > >> leading 0o instead :) > > > > Sorry, I don't write them implicitly. A leading zero explicitly states > > that the numeric constant that follows is octal. > > That is incorrect. No, it simply isn't. It is a stated specification in most popular programming languages that an integer preceded by a leading zero is an octal number. That makes it explicit, when used by a programmer to write an octal literal. By definition. End of discussion. > (Explicitness isn't a binary state Of course it is. Something can be either stated or implied... there are no shades in between. Perhaps you mean "obvious and intutitive" where you are using the word "explicit" above (and that would be a matter of subjective opinion). The leading zero, however, is undoubtedly explicit. It is an explicitly written token which, in that context, has the meaning that the digits that follow are an octal number. One simply needs to be aware of that aspect of the specification of the programming language, and one will clearly know that it is octal. My point in mentioning that many other programming languages, by the way, was NOT to suggest that, "See, look here, all these other folks do it that way too, so it must be right." It was to refute the notion that the leading zero as octal was in some way unusual. It is, in fact, ubiquitous in computing, taught roughly in the first week of any beginning computing course using nearly any modern popular programming language, and discussed within the first full page of text in the section on numerical literals in _Learning Python_ (and undoubtedly many other books on Python). It may be a surprise the first time you run into it, but you typically won't forget that detail after you run into it the first time. > However, octal numbers are defined implicitly: 012 is a legal base 10 > number, or base 3, or base 9, or base 16. Not in any programming language I use today, it's not. In all of those, 012 is an octal integer literal, per the language spec. > There's nothing about a leading zero that says "base 8" apart from > familiarity. That is simply untrue. What says base 8 about a leading zero is the formal specification of the programming language. The only way using octal could be implicit in the code is if you wrote something like: x = 12 in your code, and then had to pass a flag to your compiler or interpreter to tell it that you meant to use octal integer literals instead of decimal ones. That, of course, would be insane. But specifying a leading zero to represent an octal number zero is very much explicit, by definition. > We can see the difference between leading 0x and leading 0 if you > repeat it: repeating an explicit 0x, as in 0x0xFF, is a syntax > error, while repeating an implicit 0 silently does nothing > different: No, we can't. Just as you can type 0012, you can also type 0x0FF. It's not different AT ALL. In both cases, the marker designated by the programming language as the base indicator can be followed by an arbitrary number of zeros which do not impact the magnitude of the integer so specified. Identical behavior. The key is simply to understand that the first 0 is not a digit -- it's a syntactic marker, an operator if you will (though Python may not technically think of it that way). The definition of '0' is overloaded, just as other language tokens often are. This, too, is hardly unusual. > There are a bunch of languages, pretty much all heavily influenced > by C, which treat integer literals with leading 0s as oct: C++, > Javascript, Python 2.x, Ruby, Perl, Java. As so often is the case, > C's design mistakes become common practice. Sigh. That it is a design mistake is a matter of opinion. Obviously the people who designed it didn't think it was a mistake, and neither do I. If you search the web for this topic (I did), you will find no shortage of people who think the recent movement to irradicate the leading zero to be frustrating, annoying, and/or stupid. And by the way, this representation predates C. It was at least present in B. > FORTRAN 90 uses a leading O (uppercase o) for octal That clearly IS a design mistake, because O is virtually indistinguishable from 0, especially considering varying fonts and people's variable eye sight quality. > Algol uses an explicit base: 8r12 to indicate octal 10. This is far better than 0o01. I maintain that 0o1 is only marginally better than O01 (from your fortran example) or 0O1, allowed by Python. The string 8r12 has the nicety that it can easily be used to represent integers of any radix in a consistent fashion. But I maintain that the leading zero is just fine, and changing it after 20 years of Python seems more than a little arbitrary and brain-damaged to me. > > Computer languages are not write-only, excepting maybe Perl. ;-) Writing > > 0o12 presents no hardship; but I assert, with at least some support from > > others here, that *reading* it does. > > No more so than 0x or 0b literals. If anything, 0o12 stands out as "not > twelve" far more than 012 does. Obviously, I don't agree. Moving on... I've wasted enough time arguing about this. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jjalocha at gmail.com Mon Aug 24 09:44:47 2009 From: jjalocha at gmail.com (Jerzy Jalocha N) Date: Mon, 24 Aug 2009 09:44:47 -0400 Subject: P3 weird sys.stdout.write() In-Reply-To: <9b72f9a90908240613i513597bbk83a30946ab0b04ae@mail.gmail.com> References: <9b72f9a90908240613i513597bbk83a30946ab0b04ae@mail.gmail.com> Message-ID: <9b72f9a90908240644i77caaa0avb3c305925be86092@mail.gmail.com> >>> import sys >>> n = sys.stdout.write('something') something>>> n 9 >>> Yes, that works as expected, now, similar to 2.6. Thank you both, Diez and Andr?! -Jerzy From sturlamolden at yahoo.no Mon Aug 24 09:46:02 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 06:46:02 -0700 (PDT) Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> Message-ID: On 24 Aug, 10:24, n... at cam.ac.uk wrote: > In article <5134d9f1-0e23-4e05-a817-bf0cc9e85... at w6g2000yqw.googlegroups.com>, > > sturlamolden ? wrote: > >On 24 Aug, 02:26, nos... at see.signature (Richard Maine) wrote: > > >> You missed the word "OOP", which seemed like the whole point. Not that > >> the particular word is used in the Fortran standard, but it isn't hard > >> to guess that he means a derived type that uses some of the OOP > >> features. Inheritance, polymorphism, and type-bound procedure (aka > >> methods in some other languages) come to mind. > > >But C is not OOP. The ISO C bindings in Fortran are not ISO C++ > >bindings. This is for a reason: C++ does not have a standard ABI like > >ISO C. > > Nor does C. ?Almost everything that most people believe about C is > wrong, because C is not well-defined at any level, so there are > many twisty little C languages, all different. > > Richard is perfectly correct that my point was OOP. ?C interoperability > does not apply to any derived type with type-bound procedures, which > include finalizers. ?Note that this ALSO forbids them from being > passed as data, even if the other language never uses the OOP features > of the type. You also made this claim regarding Fortran's C interop with strings: "No, I mean things like 'Kilroy was here'. Currently, Fortran's C interoperability supports only strings of length 1, and you have to kludge them up as arrays. That doesn't work very well, especially for things like function results." This obviosuly proves you wrong: subroutine foobar(fstr) ! this is the Fortran function we want to call from C ! it takes a variable length string as argument and ! print its length character(*) :: fstr write (*,*) len(fstr) end subroutine subroutine wrap_foobar(cstr) bind(c, name='foobar') ! a wrapper for foobar which we expose to C use, intrinsic :: iso_c_binding interface function strlen(cstr) bind(c, name='strlen') use, intrinsic :: iso_c_binding integer(c_int) :: strlen type(c_ptr), value :: cstr end function strlen end interface type(c_ptr), value :: cstr character(2147483647), pointer :: p_fstr integer :: n n = strlen(cstr) call c_f_pointer(cstr, p_fstr) call foobar(p_fstr(1:n)) end subroutine I am not saying you are wrong regarding OOP derives types, but I'm not taking your word for it. However, I am not wasting my time on Fortran 2003 OOP now, as it lacks compiler support. So I'll leave your claim uncontested. By the way, I am more than happy using Python for OOP and Fortran 95 for speed. As for numerical computing, I'd rather see better support for array and matrix types in Cython than OOP in Fortran. Regards, Sturla Molden From paul.vandelst at noaa.gov Mon Aug 24 09:46:49 2009 From: paul.vandelst at noaa.gov (Paul van Delst) Date: Mon, 24 Aug 2009 09:46:49 -0400 Subject: Python/Fortran interoperability In-Reply-To: <800c6f66-7074-451f-8c1b-47c93d07c5a4@s13g2000yql.googlegroups.com> References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> <1j4wx7d.18cr6dvw3j79yN%nospam@see.signature> <800c6f66-7074-451f-8c1b-47c93d07c5a4@s13g2000yql.googlegroups.com> Message-ID: sturlamolden wrote: > On 24 Aug, 02:57, nos... at see.signature (Richard Maine) wrote: > > Does anyone use OOP in Fortran anyway? I do - currently for learning (and eventually training) purposes so I don't distribute any of the code. But, the fact that... > Fortran 2003 compilers are not ubiquitous. ...is a major sticking point towards a fully engaged f2003 programme (not program :o) > Fortran compilers tend to support a > subset for Fortran 2003, usually ISO C bindings but not OOP. Yeah, I'm starting to find it a little bit tiresome that vendors now appear convinced that implementing some of the more note-worthy features of f2008 is of greater importance that wrapping up the f2003 implementations. But, it's their business for their customers so c'est la vie I guess If I ignore parameterised derived types then my f2003 platform/compiler of "choice", IBM AIX xlf2003, works well for OOP stuff. cheers, paulv From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 24 09:55:16 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 24 Aug 2009 15:55:16 +0200 Subject: Object Reference question In-Reply-To: References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <8763chldpd.fsf@benfinney.id.au> Message-ID: <4a929bc3$0$22636$426a74cc@news.free.fr> josef a ?crit : (snip) > I think that something like a = MyClass0(name = > 'a', ...) is a bit redundant. Are definitions treated the same way? > How would one print or pass function names? In Python, classes and functions are objects too. The class and def statements are mostly syntactic sugar that *both* instanciate the (resp) class of function objet *and* bind it in the local namespace. FWIW, while class and function objects do (usually) have a __name__ attribute (usually the one used in the class or def statement...), this doesn't mean they're still bound to this name, nor that they are not bound to any other name: bruno at bruno:~$ python Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. pythonrc start pythonrc done >>> def foo(): print "function foo ???" ... >>> foo >>> foo.__name__ 'foo' >>> bar = foo >>> bar.__name__ 'foo' >>> bar() function foo ??? >>> import sys >>> foo = lambda: sys.stdout.write("pick a boo !\n") >>> foo.__name__ '' >>> foo() pick a boo ! >>> funcs = [foo, bar] >>> del foo >>> funcs[0] at 0x8563ed4> >>> funcs[0]() pick a boo ! >>> funcs[1] >>> funcs[1]() function foo ??? >>> funcs[1].__name__ 'foo' >>> del bar >>> funcs[1]() function foo ??? >>> funcs[1].__name__ = "yadda" >>> funcs[1]() function foo ??? >>> funcs[1].__name__ 'yadda' >>> HTH From code at pizzashack.org Mon Aug 24 09:56:48 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 08:56:48 -0500 Subject: Annoying octal notation In-Reply-To: <87fxbifzb7.fsf@golux.woodcraft.me.uk> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> Message-ID: <20090824135648.GA20434@dragontoe.org> On Sun, Aug 23, 2009 at 01:13:32PM +0000, Matthew Woodcraft wrote: > Dennis Lee Bieber writes: > > About the only place one commonly sees leading zeros on decimal > > numbers, in my experience, is zero-filled COBOL data decks (and since > > classic COBOL stores in BCD anyway... binary (usage is > > computational/comp-1) was a later add-on to the data specification model > > as I recall...) > > A more common case is dates. I suppose this is true, but I can't remember the last time I hard-coded a date in a program, or worked on someone else's code with hard-coded dates. I'm fairly certain I've never done it, and if I had, I obviously would not have used leading zeros. I think hard-coding dates is more uncommon than using octal. ;-) [It unquestionably is, for me personally.] I tend to also discount this example, because when we write dates with leading zeros, usually it's in some variation of the form 08/09/2009, which, containing slashes, is a string, not a number, and can not be used as a date literal in any language I know. We do it for reasons of format, which again implies that it has more the characteristics of a string than of a number. To use such a thing in any programming language I can think of would require translation from a string. > I've seen people trip over this writing things like > > xxx = [ > date(2009, 10, 12), > date(2009, 12, 26), > date(2010, 02, 09), > ] I've never seen anyone do this (no doubt because it would be an error), but as I said, I don't think I've ever seen hard-coded dates in any programs I've worked on. I've never encountered anyone having problems with octals who was not a total noob at programming. The changing of this syntax seems like much ado about nothing to me, and as such is annoying, consider that I use it very often. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ryniek90 at gmail.com Mon Aug 24 10:04:07 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Mon, 24 Aug 2009 16:04:07 +0200 Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile Message-ID: <4A929DD7.4070507@gmail.com> >> John Machin wrote: >>> Erik Max Francis alcyone.com> writes: >> I also suspect the "pipe" symbol. I don't know if it's an invalid >> character to Windows, but it's certainly a bad idea. The '|' character >> means something special to the shell. > The "pipe" character is not a valid character in a Windows file. > Despite the OP's message wrapping the filename in "pipes", > there are no pipes in the filename in the traceback to > which he posted a link. Wrapping the filename in "pipes" > and the cryptic reference to "the '|\U' literal fault" > appear to be side-issue bogglements. > >>> open('boggle|txt', 'wb') > Traceback (most recent call last): > File "", line 1, in > IOError: [Errno 22] invalid mode ('wb') or filename: 'boggle|txt' > >>> open('|boggle.txt|', 'wb') > Traceback (most recent call last): > File "", line 1, in > IOError: [Errno 22] invalid mode ('wb') or filename: '|boggle.txt|' Sorry, but i don't know where those pipes came from : P The proper path is "C:\\Users\\Ryniek's WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2" and that string literal is "\U", without any pipes :) The truth is that script works on linux (ubuntu) but not on windows (neither Win7 nor WinXP). Maybe it's good idea to use raw string for specifing those paths? As i mentioned later, some python users had the same problem with this IOError ( like here: http://www.daniweb.com/forums/thread174552.html or here: http://groups.google.com/group/sympy/browse_thread/thread/c42aca3eb53... ). From code at pizzashack.org Mon Aug 24 10:14:25 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 09:14:25 -0500 Subject: Annoying octal notation In-Reply-To: <20090824135648.GA20434@dragontoe.org> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <20090824135648.GA20434@dragontoe.org> Message-ID: <20090824141425.GB20434@dragontoe.org> On Mon, Aug 24, 2009 at 08:56:48AM -0500, Derek Martin wrote: > On Sun, Aug 23, 2009 at 01:13:32PM +0000, Matthew Woodcraft wrote: > > A more common case is dates. > > I suppose this is true, but [...] > I tend to also discount this example, because when we write dates > with leading zeros, usually it's in some variation of the form > 08/09/2009, which, containing slashes, is a string, not a number In fact, now that I think of it... I just looked at some old school papers I had tucked away in a family album. I'm quite sure that in grammar school, I was tought to use a date format of 8/9/79, without leading zeros. I can't prove it, of course, but feel fairly sure that the prevalence of leading zeros in dates occured only in the mid to late 1980's as computers became more prevalent in our society (no doubt because thousands of cobol programmers writing business apps needed a way to convert dates as strings to numbers that was easy and fit in small memory). Assuming I'm right about that, then the use of a leading 0 to represent octal actually predates the prevalence of using 0 in dates by almost two decades. And while using leading zeros in other contexts is "familiar" to me, I would certainly not consider it "common" by any means. Thus I think it's fair to say that when this syntax was selected, it was a rather good choice. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From victorsubervi at gmail.com Mon Aug 24 10:17:04 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 24 Aug 2009 09:17:04 -0500 Subject: Trying To Catch Invalid User Input In-Reply-To: References: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> Message-ID: <4dc0cfea0908240717y562d89dcqb84bef146fcd08f4@mail.gmail.com> That's nice. Thanks! V On Sun, Aug 23, 2009 at 5:02 PM, Dennis Lee Bieber wrote: > On Sun, 23 Aug 2009 10:04:57 -0500, Victor Subervi > declaimed the following in > gmane.comp.python.general: > > > Hi; > > I have the following: > > > > style = raw_input('What style is this? (1 = short, 2 = long): ') > > flag = 0 > > while flag == 0: > > if (style != 1) or (style != 2): > > style = raw_input('There was a mistake. What style is this? (1 = > short, > > 2 = long): ') > > else: > > flag = 1 > > > Ugh... Unless you are using an archaic version of Python, the > language has support for booleans... > > done = False > while not done: > ... > done = True > > > You fail to convert the character input from raw_input into an > integer for comparison... Oh, and you say the input is wrong if it is > NOT 1 OR NOT 2... 1 is not 2, and 2 is not 1, so... even if you did > convert to an integer, it would be rejected. > > Consider: > > -=-=-=-=-=-=-=- > while True: > charin = raw_input("What style is this? (1: short, 2: long): ") > try: > style = int(charin) > except: #I know, should not use naked except clause > print ("The input '%s' is not a valid integer value; try again" > % charin) > else: > if style in (1, 2): break > print ("The input value '%s' is not in the valid range; try > again" > % style) > -=-=-=-=-=-=-=- > {Watch out for line wraps} > Works in Python 2.5 > > E:\UserData\Dennis Lee Bieber\My Documents>python Script1.py > What style is this? (1: short, 2: long): ab1 > The input 'ab1' is not a valid integer value; try again > What style is this? (1: short, 2: long): 1a > The input '1a' is not a valid integer value; try again > What style is this? (1: short, 2: long): 12 > The input value '12' is not in the valid range; try again > What style is this? (1: short, 2: long): 2 > > E:\UserData\Dennis Lee Bieber\My Documents> > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Mon Aug 24 10:20:32 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 07:20:32 -0700 (PDT) Subject: basic thread question References: Message-ID: <4ddd2bd2-de39-487f-95ad-64c670a9b710@t13g2000yqt.googlegroups.com> On 18 Aug, 22:10, Derek Martin wrote: > I have some simple threaded code... ?If I run this > with an arg of 1 (start one thread), it pegs one cpu, as I would > expect. ?If I run it with an arg of 2 (start 2 threads), it uses both > CPUs, but utilization of both is less than 50%. ?Can anyone explain > why? ? Access to the Python interpreter is serialized by the global interpreter lock (GIL). You created two threads the OS could schedule, but they competed for access to the Python interpreter. If you want to utilize more than one CPU, you have to release the GIL or use multiple processes instead (os.fork since you are using Linux). This is how the GIL can be released: * Many functions in Python's standard library, particularly all blocking i/o functions, release the GIL. This covers the by far most common use of threads. * In C or C++ extensions, use the macros Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS. * With ctypes, functions called from a cdll release the GIL, whereas functions called from a pydll do not. * In f2py, declaring a Fortran function threadsafe in a .pyf file or cf2py comment releases the GIL. * In Cython or Pyrex extensions, use a "with nogil:" block to execute code without holding the GIL. Sturla Molden From sturlamolden at yahoo.no Mon Aug 24 10:31:57 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 07:31:57 -0700 (PDT) Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> Message-ID: <4224e772-5b67-4eea-9bdf-a7d2bf7cc128@c14g2000yqm.googlegroups.com> On 24 Aug, 13:21, Piet van Oostrum wrote: > But os.fork() is not available on Windows. And I guess refcounts et al. > will soon destroy the sharing. Well, there is os.fork in Cygwin and SUA (SUA is the Unix subsytem in Windows Vista Professional). Cygwin's fork is a bit sluggish. Multiprocessing works on Windows and Linux alike. Apart from that, how are you going to use threads? The GIL will not be a problem if it can be released. Mostly, the GIL is a hypothetical problem. It is only a problem for compute-bound code written in pure Python. But very few use Python for that. However, if you do and can afford the 200x speed penalty from using Python (instead of C, C++, Fortran, Cython), you can just as well accept that only one CPU is used. Sturla Molden From drobinow at gmail.com Mon Aug 24 10:33:45 2009 From: drobinow at gmail.com (David Robinow) Date: Mon, 24 Aug 2009 10:33:45 -0400 Subject: Is Python what I need? In-Reply-To: References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: <4eb0089f0908240733h17f02cbte4154bf552404509@mail.gmail.com> On Mon, Aug 24, 2009 at 9:32 AM, Peter Otten<__peter__ at web.de> wrote: > If you are trying to teach children that are unwilling to use pen and paper > putting them in front of a computer doesn't help you and them one bit. As a > starting programmer you'll have to spend a lot of time in front of your > computer that may be better spent with your students. I don't think you were rude at all, but I like your second answer even more than the first. Nevertheless, I'd still like to hear from the Original Poster. What are you trying to accomplish? What software have you found that is too expensive? Given more information, somebody might be able to help. From ronn.ross at gmail.com Mon Aug 24 10:35:09 2009 From: ronn.ross at gmail.com (Ronn Ross) Date: Mon, 24 Aug 2009 10:35:09 -0400 Subject: Reading binary files Message-ID: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> I need to read a binary file. When I open it up in a text editor it is just junk. Does Python have a class to help with this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From garabik-news-2005-05 at kassiopeia.juls.savba.sk Mon Aug 24 10:35:56 2009 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Mon, 24 Aug 2009 14:35:56 +0000 (UTC) Subject: Numeric literals in other than base 10 - was Annoying octal?notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> Message-ID: J. Cliff Dyer wrote: > I had an objection to using spaces in numeric literals last time around > and it still stands, and it still stands in the new one. > Or, we can use U+00A0 NO-BREAK SPACE, once we already have unicode variable names :-) (probably some people would find it difficult to type, though with my keyboard layout it is COMPOSE + SPACE + SPACE, not more difficult than _). Well, reading code listings could be a bit confusing. Thinking about it, U+2005 FOUR-PER-EM SPACE makes more sense. Aesthetically, too :-) -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From davea at dejaviewphoto.com Mon Aug 24 10:36:42 2009 From: davea at dejaviewphoto.com (Dave Angel) Date: Mon, 24 Aug 2009 10:36:42 -0400 Subject: Temat:,Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: <4A928B4B.9030502@gmail.com> References: <4A928B4B.9030502@gmail.com> Message-ID: <4A92A57A.5010105@dejaviewphoto.com> Ryniek90 wrote: >
>>> John Machin wrote: >>> >>>> Erik Max Francis alcyone.com> writes: >>>> >> >>> I also suspect the "pipe" symbol. I don't know if it's an invalid >>> character to Windows, but it's certainly a bad idea. The '|' >>> character means something special to the shell. >>> >> >> The "pipe" character is not a valid character in a Windows file. >> Despite the OP's message wrapping the filename in "pipes", >> there are no pipes in the filename in the traceback to >> which he posted a link. Wrapping the filename in "pipes" >> and the cryptic reference to "the '|\U' literal fault" >> appear to be side-issue bogglements. >> >> >>> open('boggle|txt', 'wb') >> Traceback (most recent call last): >> File "", line 1, in >> IOError: [Errno 22] invalid mode ('wb') or filename: 'boggle|txt' >> >>> open('|boggle.txt|', 'wb') >> Traceback (most recent call last): >> File "", line 1, in >> IOError: [Errno 22] invalid mode ('wb') or filename: '|boggle.txt|' >> >> >> >> > > Sorry, but i don't know where those pipes came from : P > > The proper path is "C:\\Users\\Ryniek's > WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2" > and that string literal is "\U", without any pipes :) > > The truth is that script works on linux (ubuntu) but not on windows > (neither Win7 nor WinXP). > Maybe it's good idea to use raw string for specifing those paths? > > As i mentioned later, some python users had the same problem with this > IOError ( like here: http://www.daniweb.com/forums/thread174552.html > or here: > http://groups.google.com/group/sympy/browse_thread/thread/c42aca3eb532928c > ). > > > >
> You still haven't gotten rid of those illegal colons in the filename. They're not legal in Windows, as has been pointed out a couple of times in this thread. DaveA From aotto1968 at users.sourceforge.net Mon Aug 24 10:40:21 2009 From: aotto1968 at users.sourceforge.net (Andreas Otto) Date: Mon, 24 Aug 2009 16:40:21 +0200 Subject: problem to write a THREAD enabled python extension Message-ID: Hi, the following scenario: 1. using GIL 2. a pthread is created in a library and have to be "announced" to python 3. the thread is created in a "PyObject_CallObject" function call from extension c code using a other extension c-code function called from python code python CRASH with invalid thread-state object http://www.linuxjournal.com/article/3641 has information that GIL is NOT able to keep thread state information for cross thread operation. workaround -> ...... PyGILState_STATE gilState = PyGILState_Ensure(); // PyEval_RestoreThread // Call Python/C API... PyGILState_Release(gilState); // PyEval_SaveThread ...... // Create new thread... ...... PyGILState_STATE gilState = PyGILState_Ensure(); // PyEval_RestoreThread // Call Python/C API... PyGILState_Release(gilState); // PyEval_SaveThread ...... the problem is that PyGILState_Release have to be done in the call of "PyObject_CallObject" and not in the extension c-code -> for now i call it impossible to provide thread support if thread is created in extension code -> more info by valgrind ==29105== ==29105== Invalid read of size 4 ==29105== at 0x4F099AB: PyEval_EvalFrameEx (ceval.c:3728) ==29105== by 0x4F0B476: PyEval_EvalCodeEx (ceval.c:3180) ==29105== by 0x4E9DE50: function_call (funcobject.c:630) ==29105== by 0x4E7610C: PyObject_Call (abstract.c:2160) ==29105== by 0x4E8BEFB: method_call (classobject.c:323) ==29105== by 0x4E7610C: PyObject_Call (abstract.c:2160) ==29105== by 0x4F04975: PyEval_CallObjectWithKeywords (ceval.c:3624) ==29105== by 0x72132DF: pymsgque_ProcCall (misc_python.c:48) ==29105== by 0x742A23E: pTokenInvoke (token.c:327) ==29105== by 0x742E7E2: sMqEventStart (msgque.c:908) ==29105== by 0x7425365: pEventStart (event.c:360) ==29105== by 0x742ECBF: MqProcessEvent (msgque.c:1081) ==29105== by 0x7215F24: pymsgque_ProcessEvent (context_python.c:176) ==29105== by 0x4F09BFA: PyEval_EvalFrameEx (ceval.c:3961) ==29105== by 0x4F0B476: PyEval_EvalCodeEx (ceval.c:3180) ==29105== by 0x4F0B58A: PyEval_EvalCode (ceval.c:650) ==29105== by 0x4F2EE29: PyRun_FileExFlags (pythonrun.c:1697) ==29105== by 0x4F2F134: PyRun_SimpleFileExFlags (pythonrun.c:1182) ==29105== by 0x4F43CFB: Py_Main (main.c:625) ==29105== by 0x400D11: main (python.c:152) ==29105== Address 0x24 is not stack'd, malloc'd or (recently) free'd -> extension code ... (including some debugging output) M0 PyGILState_STATE gstate = PyGILState_Ensure(); PyObject *result; PyObject * const self = (PyObject*) CONTEXT->self; PyObject * const callable = (PyObject*) dataP; enum MqErrorE ret = MQ_OK; // clean Python and libmsgque error PyErr_Clear(); MqErrorReset(msgque->error); // call the function M1 printP(PyThreadState_Get()) if (PyMethod_Check(callable) && PyMethod_Self(callable) == self) { //PyGILState_Release(gstate); result = PyObject_CallObject(callable, NULL); //gstate = PyGILState_Ensure(); } else { //PyGILState_Release(gstate); result = PyObject_CallFunctionObjArgs(callable, self, NULL); //gstate = PyGILState_Ensure(); } M2 printP(PyThreadState_Get()) Py_XDECREF(result); // no error return OK if (PyErr_Occurred() != NULL) { NS(ErrorSet) (self); ret = MqErrorGetCode(msgque->error); } PyGILState_Release(gstate); return ret; } with GIL wrapper 'PyGILState_Release' and 'PyGILState_Ensure' enabled for 'PyObject_CallObject' the following SEG happen if (PyMethod_Check(callable) && PyMethod_Self(callable) == self) { PyGILState_Release(gstate); result = PyObject_CallObject(callable, NULL); gstate = PyGILState_Ensure(); } else { PyGILState_Release(gstate); result = PyObject_CallFunctionObjArgs(callable, self, NULL); gstate = PyGILState_Ensure(); } pymsgque_ProcCall(misc_python.c:32) -> 00000000000000000 pymsgque_ProcCall(misc_python.c:44) -> 11111111111111111 pymsgque_ProcCall(misc_python.c:45) -> PyThreadState_Get()<0x68c2ad8> ==29223== ==29223== Thread 2: ==29223== Invalid read of size 4 ==29223== at 0x4E760EA: PyObject_Call (abstract.c:2158) ==29223== by 0x4F04975: PyEval_CallObjectWithKeywords (ceval.c:3624) ==29223== by 0x72132F7: pymsgque_ProcCall (misc_python.c:48) ==29223== by 0x7430092: MqLinkCreate (msgque.c:644) ==29223== by 0x7430AB0: MqDefaultLinkCreate (msgque.c:681) ==29223== by 0x742F73B: MqLinkCreate (msgque.c:346) ==29223== by 0x7432C3D: sSysServerThreadCreate (sys.c:502) ==29223== by 0x521606F: start_thread (in /lib64/libpthread-2.9.so) ==29223== by 0x5B5B10C: clone (in /lib64/libc-2.9.so) ==29223== Address 0x18 is not stack'd, malloc'd or (recently) free'd ==29223== ==29223== Process terminating with default action of signal 11 (SIGSEGV) mfg aotto1968 From rami.chowdhury at gmail.com Mon Aug 24 10:41:09 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Mon, 24 Aug 2009 07:41:09 -0700 Subject: Reading binary files In-Reply-To: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> References: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> Message-ID: The built-in file type deals with this just fine. You can simply specify when opening the file that it is to be opened as binary: http://docs.python.org/library/functions.html#open On Mon, 24 Aug 2009 07:35:09 -0700, Ronn Ross wrote: > I need to read a binary file. When I open it up in a text editor it is > just > junk. Does Python have a class to help with this? -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From marduk at letterboxes.org Mon Aug 24 10:43:59 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Mon, 24 Aug 2009 10:43:59 -0400 Subject: Reading binary files In-Reply-To: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> References: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> Message-ID: <1251125039.23757.0.camel@brotherus.corp.redhat.com> On Mon, 2009-08-24 at 10:35 -0400, Ronn Ross wrote: > I need to read a binary file. When I open it up in a text editor it is > just junk. Does Python have a class to help with this? Yes, the "file" class. >>> myfile = open('/path/to/binary/file', 'rb') -a From sturlamolden at yahoo.no Mon Aug 24 10:45:44 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 07:45:44 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: On 24 Aug, 14:08, Gilles Ganault wrote: > I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. There is pywin32 if you like to work with MFC and ActiveX. Apart from that, lack of controls is not what I associate with GTK, Qt or wxWidgets. > I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. Why do you want GUI controls for this? If you think you do, Visual Basic has crippled your mind. Python has packages for database connectivity. There is ReportLab for reports, matplotlib for graphs, pyagg or pycairo for whatever you want to draw, etc. You can find Python packages for anything you can imagine. Sturla From mail at timgolden.me.uk Mon Aug 24 10:46:46 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 24 Aug 2009 15:46:46 +0100 Subject: Temat:,Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: <4A92A57A.5010105@dejaviewphoto.com> References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> Message-ID: <4A92A7D6.4050903@timgolden.me.uk> Dave Angel wrote: > You still haven't gotten rid of those illegal colons in the filename. > They're not legal in Windows, as has been pointed out a couple of times > in this thread. Ummm.. Colons are of course legal in Windows filenames as designating the Alternate Data Streams: with open ("c:/temp/test.txt", "w") as f: f.write ("base text") with open ("c:/temp/test.txt:blah", "w") as f: f.write ("ADS text") print open ("c:/temp/test.txt:blah").read () On the other hand, though, you can't have more than one of them: with open ("c:/temp/test.txt:blah:blah2", "w") as f: f.write ("ADS text2") should raise an error. TJG From kwmsmith at gmail.com Mon Aug 24 10:49:56 2009 From: kwmsmith at gmail.com (Kurt Smith) Date: Mon, 24 Aug 2009 09:49:56 -0500 Subject: Python/Fortran interoperability In-Reply-To: <4a915067$0$31339$9b4e6d93@newsspool4.arcor-online.net> References: <4a915067$0$31339$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On Sun, Aug 23, 2009 at 9:21 AM, Stefan Behnel wrote: > nmm1 at cam.ac.uk wrote: >> I am interested in surveying people who want to interoperate between >> Fortran and Python to find out what they would like to be able to do >> more conveniently, especially with regard to types not supported for C >> interoperability by the current Fortran standard. ?Any suggestions as to >> other ways that I could survey such people (Usenet is no longer as >> ubiquitous as it used to be) would be welcomed. > > You might want to ask also on the Cython, NumPy and SciPy mailing lists. > NumPy and SciPy have a rather large audience of scientific developers, and > Cython has a running sub-project on providing better Fortran integration > (which might be of interest to you anyway). Thanks for the mention, Stefan. For those who are interested, here's my blog summarizing the status of 'fwrap,' a Fortran wrapper utility for the C, Cython & Python languages. http://fortrancython.wordpress.com/ Linked there are my talk slides & presentation at last week's SciPy 2009 conference, which gives a good overview. Kurt From davea at ieee.org Mon Aug 24 10:52:16 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 24 Aug 2009 10:52:16 -0400 Subject: P3 weird sys.stdout.write() In-Reply-To: <9b72f9a90908240613i513597bbk83a30946ab0b04ae@mail.gmail.com> References: <9b72f9a90908240613i513597bbk83a30946ab0b04ae@mail.gmail.com> Message-ID: <4A92A920.70703@ieee.org> Jerzy Jalocha N wrote: > I've stumbled upon the following in Python 3: > > Python 3.0.1+ (r301:69556, Apr 15 2009, 15:59:22) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>> import sys >>>> sys.stdout.write("") >>>> > 0 > >>>> sys.stdout.write("something") >>>> > something9 > > > write() is appending the length of the string to it's output. That's > not how it worked in 2.6. > > What's the reason for this? Is this intended? I couldn't find a bug > report for this. > > (You probably should be using 3.1, but that's not your particular problem here.) The write() function changed in 3.0, but not in the way you're describing. It now (usually) has a return value, the count of the number of characters written. See the 3.1 docs: file.write(/str/) Write a string to the file. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called. The meaning of the return value is not defined for every file-like object. Some (mostly low-level) file-like objects may return the number of bytes actually written, others return None. But because you're running from the interpreter, you're seeing the return value(9), which is suppressed if it's None, which it was in 2.x. This has nothing to do with how the language behaves in normal use. DaveA From sjmachin at lexicon.net Mon Aug 24 10:56:24 2009 From: sjmachin at lexicon.net (John Machin) Date: Mon, 24 Aug 2009 07:56:24 -0700 (PDT) Subject: Temat:, Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> Message-ID: <4ec18c68-b8b5-401e-b910-802b7662dced@i18g2000pro.googlegroups.com> On Aug 25, 12:46?am, Tim Golden wrote: > Dave Angel wrote: > > You still haven't gotten rid of those illegal colons in the filename. ? > > They're not legal in Windows, as has been pointed out a couple of times > > in this thread. > > Ummm.. Colons are of course legal in Windows filenames as designating That is the most inappropriate "of course" I've seen for quite a while. > the Alternate Data Streams: OK, so s/illegal/evil/ From apt.shansen at gmail.com Mon Aug 24 11:03:56 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Mon, 24 Aug 2009 08:03:56 -0700 Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: <4A929DD7.4070507@gmail.com> References: <4A929DD7.4070507@gmail.com> Message-ID: <7a9c25c20908240803v53cabd08la78e08163fae1aa7@mail.gmail.com> > > The proper path is "C:\\Users\\Ryniek's > WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2" > and that string literal is "\U", without any pipes :) > > The truth is that script works on linux (ubuntu) but not on windows > (neither Win7 nor WinXP). > Maybe it's good idea to use raw string for specifing those paths? > Colons are not valid in filenames on Windows. You won't get that filename to work. The error may be somewhat cryptic. Depending on the version of Windows and the particulars of your filesystem, *attempting* to read/write a filename with a colon may lead to very surprising results-- 0 sized files with names up to the colon... as you may actually be writing to an alternate named data stream (like a resource fork on the mac). Basically, the error is just cryptic. The problem is your filename isn't a valid windows filename :) --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From gtaylor at l11solutions.com Mon Aug 24 11:04:34 2009 From: gtaylor at l11solutions.com (Greg Taylor) Date: Mon, 24 Aug 2009 08:04:34 -0700 (PDT) Subject: Fedex + SOAP Message-ID: <55f5539e-2cb7-4e51-b897-da42e673ff57@r42g2000yqj.googlegroups.com> Fedex has recently started the process to transition from their XML- based Web Services to the new SOAP-based equivalent. I've been trying unsuccessfully to get an example SOAP transaction working with their new service, but am running into validation problems. I was wondering if anyone has already started tinkering with a Fedex +SOAP module before I potentially re-invent the wheel. If there's nothing in the works yet, would anyone be interested in working with me on such a module? Thanks, Greg From sturlamolden at yahoo.no Mon Aug 24 11:08:07 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 08:08:07 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: On 24 Aug, 14:08, Gilles Ganault wrote: > and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. Remote update is a problem regardless of language. It typically involves the following steps: 1. Download the update from a server using a background thread. 2. When the program starts, look for downloaded updates. Install updates, then launch the Python app. The problem is that a program's DLLs etc. become write-protected when the program runs. So you nees two programs that cooperate to install updates. But regardless of language you will run into this problem - it is not Python specific. With py2exe, you can solve this using two executables. The first py2exe launch a script that installs updates, then spawns the second py2exe executable. The second py2exe lauch a script that installs updates in the first, then launch the Python app. The Python app then run a background thread that downloads new updates. Sturla Molden From ebonak at hotmail.com Mon Aug 24 11:17:37 2009 From: ebonak at hotmail.com (Esmail) Date: Mon, 24 Aug 2009 11:17:37 -0400 Subject: your favorite debugging tool? In-Reply-To: References: Message-ID: Hello, thank you all for your suggestions/comments. While I do believe in a minimalist approach (part of the reason I find Python so appealing), using print statements sometimes only goes so far (for me). I probably should look into using iPython in the context of debugging (I already use this shell). For now I ended up giving winpdb a whirl and it did help me find the bug that had been elusive to my print statement approach :-) Thanks again .. and if there are additional postings, I'll be reading them too with great interest. Esmail From stefan_ml at behnel.de Mon Aug 24 11:18:40 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 17:18:40 +0200 Subject: problem to write a THREAD enabled python extension In-Reply-To: References: Message-ID: <4a92af50$0$32675$9b4e6d93@newsspool2.arcor-online.net> Andreas Otto wrote: > Hi, > > the following scenario: > > 1. using GIL > 2. a pthread is created in a library and have to be "announced" to python > 3. the thread is created in a "PyObject_CallObject" function call from > extension c code using a other extension c-code function called > from python code > > python CRASH with invalid thread-state object You forgot to create a thread state for the new thread. See the PyThreadState_New() function. Stefan From hendrik at microcorp.co.za Mon Aug 24 11:22:39 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 24 Aug 2009 17:22:39 +0200 Subject: Annoying octal notation In-Reply-To: <20090824141425.GB20434@dragontoe.org> References: <20090824135648.GA20434@dragontoe.org> <20090824141425.GB20434@dragontoe.org> Message-ID: <200908241722.39942.hendrik@microcorp.co.za> On Monday 24 August 2009 16:14:25 Derek Martin wrote: > In fact, now that I think of it... > > I just looked at some old school papers I had tucked away in a family > album. I'm quite sure that in grammar school, I was tought to use a > date format of 8/9/79, without leading zeros. I can't prove it, of > course, but feel fairly sure that the prevalence of leading zeros in > dates occured only in the mid to late 1980's as computers became more > prevalent in our society (no doubt because thousands of cobol I was one of those COBOL programmers, and the time was around the end of the sixties, running into the seventies. And the reason for leading zeroes on dates was the punched card, and its handmaiden, the data entry form, with a nice little block for every character. > programmers writing business apps needed a way to convert dates as > strings to numbers that was easy and fit in small memory). > > Assuming I'm right about that, then the use of a leading 0 to > represent octal actually predates the prevalence of using 0 in dates > by almost two decades. Not quite - at the time I started, punch cards and data entry forms were already well established practice, and at least on the English machines, (ICL 1500/1900 series) octal was prevalent, but I don't know when the leading zero octal notation started, and where. I only met it much later in life, and learned it through hard won irritation, because it is a stupid convention, when viewed dispassionately. > And while using leading zeros in other > contexts is "familiar" to me, I would certainly not consider it > "common" by any means. Thus I think it's fair to say that when this > syntax was selected, it was a rather good choice. I think you give it credence for far more depth of design thinking than what actually happened in those days - some team working on a compiler made a decision (based on gut feel or experience, or precedent, or whim ) and that was that - lo! - a standard is born! -- We have always done it this way, here at company x. And besides, we cannot ask our main guru to spend any of his precious time mucking around with trivia - the man may leave us for the opposition if we irritate him, and systems people do not grow on trees, you know. - Hendrik From jjalocha at gmail.com Mon Aug 24 11:25:15 2009 From: jjalocha at gmail.com (Jerzy Jalocha N) Date: Mon, 24 Aug 2009 11:25:15 -0400 Subject: P3 weird sys.stdout.write() In-Reply-To: <4A92A920.70703@ieee.org> References: <9b72f9a90908240613i513597bbk83a30946ab0b04ae@mail.gmail.com> <4A92A920.70703@ieee.org> Message-ID: <9b72f9a90908240825m5d04cdb9m74f28e9eac1ab02f@mail.gmail.com> On Mon, Aug 24, 2009 at 10:52 AM, Dave Angel wrote: > The write() function changed in 3.0, but not in the way you're describing. > ?It now (usually) has a return value, the count of the number of characters > written. [...] > But because you're running from the interpreter, you're seeing the return > value(9), which is suppressed if it's None, which it was in 2.x. ? This has > nothing to do with how the language behaves in normal use. This makes it much clearer! You are right, output in a shell script is "normal", without the return value. Thank you, Dave. -Jerzy From bbxx789_05ss at yahoo.com Mon Aug 24 11:29:39 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 24 Aug 2009 08:29:39 -0700 (PDT) Subject: print() and unicode strings (python 3.1) Message-ID: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> ======python 2.6 ====== import sys print sys.getdefaultencoding() s = u"\u20ac" print s.encode("utf-8") $ python2.6 1test.py ascii ? =====python 3.1 ======= import sys print(sys.getdefaultencoding()) s = "?" print(s.encode("utf-8")) print(s) $ python3.1 1test.py utf-8 b'\xe2\x82\xac' Traceback (most recent call last): File "1test.py", line 7, in print(s) UnicodeEncodeError: 'ascii' codec can't encode character '\u20ac' in position 0: ordinal not in range(12 I don't understand why I'm getting an encode error in python 3.1. From pavlovevidence at gmail.com Mon Aug 24 11:31:13 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 24 Aug 2009 08:31:13 -0700 (PDT) Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> Message-ID: <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> On Aug 24, 6:56?am, Derek Martin wrote: >?I think > hard-coding dates is more uncommon than using octal. ;-) ?[It > unquestionably is, for me personally.] You just don't get it, do you? Do you really think this is a contest over what's more common and the winner gets to choose the syntax? You really think that's the issue? It is not. The issue is that C's arcane octal notation is MIND- BOGGLINGLY RETARDED. So, even if Unix file permissions were a hundred times more common than padding integer constants with zero, it still wouldn't be a good idea to have it in Python because the notation is retarded. Even if 99.999% of other languages use the notation, it still wouldn't be a good idea to have it in Python because the notation is retarded. The vast majority of people reading this will understand intuitively why the arcane octal notation is retarded. I was going to explain it, but I decided it's not worth a serious argument. Carl Banks From find.mig at paa.google Mon Aug 24 11:32:23 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Mon, 24 Aug 2009 17:32:23 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: References: <4a91db65$0$305$14726298@news.sunsite.dk> Message-ID: <4a92b290$0$305$14726298@news.sunsite.dk> Hendrik van Rooyen wrote: > see if there is an "after" method somewhere. > > What you have to do is to "break the link" between the callback > and the processing. Your code above is all in the callback "thread", despite > the fact that you call another function to do the processing. > > So if you replace the data_callback() with an after call, it should work as > you expect. > > HTH - Hendrik > Thanks I'm new to python, what is an after function and an after call? Couldn't find excact answer on google...? Do you have a link to some docs? From steve at REMOVE-THIS-cybersource.com.au Mon Aug 24 11:36:24 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2009 15:36:24 GMT Subject: Literal concatenation, strings vs. numbers (was: Numeric literals in other than base 10 - was Annoying octal notation) References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> <7fe9mbF2l83bmU1@mid.individual.net> <871vn2gcai.fsf_-_@benfinney.id.au> Message-ID: <02a2a388$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 12:45:25 +1000, Ben Finney wrote: > greg writes: > >> J. Cliff Dyer wrote: >> >> > What happens if you use a literal like 0x10f 304? >> >> To me the obvious thing to do is concatenate them textually and then >> treat the whole thing as a single numeric literal. Anything else >> wouldn't be sane, IMO. Agreed. It's the only sane way to deal with concatenating numeric literals. It makes it simple and easy to understand: remove the whitespace from inside the literal, and parse as normal. 123 4567 => 1234567 # legal 0xff 123 => 0xff123 # legal 123 0xff => 1230xff # illegal The first two examples would be legal, the last would raise a syntax error, for obvious reasons. This would also work for floats: 1.23 4e5 => 1.234e5 # legal 1.23 4.5 => 1.234.5 # illegal 1e23 4e5 => 1e234e5 # illegal > Yet, as was pointed out, that behaviour would be inconsistent with the > concatenation of string literals:: > > >>> "abc" r'def' u"ghi" 'jkl' > u'abcdefghijkl' Unicode/byte conversion is obviously a special case, and arguably should have been prohibited, although "practicality beats purity" suggests that a single unicode string in the sequence should make the lot unicode. (What else could it mean?) In any case, numeric concatenation and string concatenation are very different beasts. With strings, you have to interpret each piece as either bytes or characters, you have to treat escapes specially, you have to deal with matching delimiters. For numeric concatenation, none of those complications is relevant: there is no equivalent to the byte/ character dichotomy, there are no escape sequences, there are no delimiters. Numeric literals are much simpler than string literals, consequently the concatenation rule can be correspondingly simpler too. There's no need to complicate it by *adding* complexity: you can't have mixed bases in a single numeric literal without spaces, why would you expect to have mixed bases in one with spaces? -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Aug 24 11:40:24 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2009 15:40:24 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <4a918fe0$0$30226$9b4e6d93@newsspool1.arcor-online.net> <02a1cc1d$0$30337$c3e8da3@news.astraweb.com> <4a9243d3$0$32677$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <02a2a478$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 09:40:03 +0200, Stefan Behnel wrote: >> Or you could enter the 21 century and understand that "guys" has become >> a generic term for people of any sex. > > Is that true for everyone who understands and/or writes English? In that > case, I'm fine with your above statement. Otherwise, I'd wonder who you > meant with the term "cultural chauvinism". So far, I only learned that > most North-American English native speakers use that term in the way you > refer to. That doesn't even get you close to the majority of English > speakers. If you read the entire thread, you'd see that we've already discussed the issue of "guys" for mixed sex groups and females. In fact, as I'd already said, I'm one of those old fashioned guys who still gets surprised when women refer to themselves as guys, but I'm learning to keep up with the times. I'm Australian, not North American, and the British author Michael Quinion, one of the researchers for the Oxford Dictionary, also states that "guys" now refers to both men and women: http://www.worldwidewords.org/weirdwords/ww-guy1.htm When "guys" can refer to either sex in English, American, Canadian and Australian English, I think it should be pretty uncontroversial to treat it as standard now. -- Steven From apt.shansen at gmail.com Mon Aug 24 11:49:36 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Mon, 24 Aug 2009 08:49:36 -0700 Subject: Python for professsional Windows GUI apps? In-Reply-To: References: Message-ID: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> > > I was wondering if some people in this ng use Python and some GUI > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > applications, and if yes, what it's like, the pros and cons, etc. My company does. A few years ago we decided to re-write our entire aging product line in Python using wxPython as the GUI layer (PyWin32 was out because we wanted Mac compatibility, and at that time between QT's commercial license and my own familiarity with wx meant we just used that by default.) It took some time to get solid; there's a learning curve involved in doing things "the pythonic way", and wxPython is -- not really pythonic(and no powerful GUI library is, though there are some simpler libraries out there which are), so you're learning in two directions at once. It's been a pretty interesting experience, and I'd consider it a complete success, honestly. It took some time to get the full suite going from "functional" to "mature", mostly because of certain complexities to our system which have nothing to do with Python. But, Python and wxPython as the foundation for the system has allowed some pretty remarkable flexibility in getting something usable to the customer quickly, getting early feedback and rapidly responding to their needs and growing the application as we did so. It's been a very iterative process, but I don't know if you want to create a long-term project or get something out that works Just Fine, Right Now. For us we started out with a basic re-implementation of the legacy system which just 'worked', and have over the last few years probably rewritten most of the original code at least twice (a piece at a time)-- re-factoring and redesigning both the insides and UI as new controls and technologies (and our own knowledge!) improve over time. For us that's good, because we like maintenance contracts :) But we've had a continually evolving product line-- getting faster with every new release, slicker, with new features and evolving continually. Sure, every program /should/ do that -- but using Python+wxPython IMHO has been invaluable to the process of evolving /efficiently/. It takes very little effort to /maintain/ the system, very little effort going back to some deep dark place in the codebase and figuring out what the heck was done by someone else three years ago... and very little effort to pull the whole thing apart and piece it back together with a new heart when it's discovered the original didn't quite do things as well as it should. I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), I find this comment -- frankly bizarre. There's a plethora if controls in wxWidgets, and it's not terribly hard once you learn the system how to make your own. Check out Andrea Gavana's excellent suite of custom widgets (which continually get migrated into the core wxPython) and the AUI, and the sublime ObjectListView for Python. Now, if you're talking about "lack of the latest Microsoft-specialized controls", that's true. wxWidgets is cross-platform so doesn't readily adopt the latest and newest way that Microsoft does things with each new iteration of Office and Windows pumping out a new UI paradigm. But you can still create very native and impressively functional looking apps. With wxWidgets at least (I have no idea about QT), you also don't have a series of data-aware controls that you may be used to, but it's *really* not that hard to write that layer yourself. You may also want to look into Dabo, which builds on top of wxPython and I believe solves some of its limitations with regards to data-integration if you do things in a way that are Dabo-esque. I'm only vaguely familiar with it, though. Depending on your needs, you can use various dialog builders to create XRC/XML "descriptions" of your interface and load them up-- but personally I hand-code all the controls and interfaces, and doing so once you learn the system is really quite rapid. I can dummy up a very functional interface for testing/dummying much faster in Python/wxPython then I can in Visual Studio. It doesn't have as many bells and whistles, but I really can't imagine why anyone would find themselves control-starved. > and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. > What problems? Yes, you have to learn py2exe, but once you have your program packaged together, it's no different then any other program on windows. Build a MSI, and have the IT guy push that MSI out via an active directory group policy. Isn't that the standard way you install and update /any/ group of users' software on a windows network? Regardless of in what language you write it in? I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. Data access is easy and well supported to a wide-variety of databases, depending on just how you want to do it. I've recently fallen in love with SQLAlchemy, though previously I did mostly simple DB-API based access and home-grown model objects representing data models. The wxWidgets "data grid" is somewhat somewhat lacking at present in that it doesn't really connect "to" the database-- but it is not significantly hard to write a table implementation to serve as your 'backend' to connect to the database, which the grid can then uses to define what it shows. Dabo's grid implementation solves that, I believe, so may be good for you. Reports, I have no idea-- in my company's domain the reporting needs are very limited, and we've found it sufficient to write out a HTML file and toss up IE to print out the table. But there is reportlab which is an excellent library for PDF generation -- and making reports in particular, of course. It has support for barcodes, I believe. Dabo also has some links to a report generator they include -- never really looked in beyond glancing and going 'Oh, neat.' --S P.S. I have no idea why I'm pumping Dabo so much in this though I've never used it! -------------- next part -------------- An HTML attachment was scrubbed... URL: From john.haxby at oracle.com Mon Aug 24 11:50:11 2009 From: john.haxby at oracle.com (John Haxby) Date: Mon, 24 Aug 2009 16:50:11 +0100 Subject: Bash-like brace expansion In-Reply-To: References: Message-ID: <4A92B6B3.9020509@oracle.com> Peter Waller wrote: > Okay, I got fed up with there not being any (obvious) good examples of > how to do bash-like brace expansion in Python, so I wrote it myself. > Here it is for all to enjoy! > > If anyone has any better solutions or any other examples of how to do > this, I'd be glad to hear from them. > That was a little while ago and while I found Peter's BraceExpand was a good start it wasn't quite what I wanted. It's not quite the same as bash: for example, BraceExpand("{1,3..5}") gives "1 3 4 5" but bash gives "1 3..5" (use "{1,{3..5}}") and bash turns all of "{a..z}", "{z..a}, "{10..-10}" into sequences. My version is a little shorter, mostly because it's heavily recursive so it may fail spectacularly on some pathological cases :-) jch -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: bp.py URL: From code at pizzashack.org Mon Aug 24 11:50:28 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 10:50:28 -0500 Subject: Annoying octal notation In-Reply-To: <200908241722.39942.hendrik@microcorp.co.za> References: <20090824135648.GA20434@dragontoe.org> <20090824141425.GB20434@dragontoe.org> <200908241722.39942.hendrik@microcorp.co.za> Message-ID: <20090824155028.GC20434@dragontoe.org> On Mon, Aug 24, 2009 at 05:22:39PM +0200, Hendrik van Rooyen wrote: > > Assuming I'm right about that, then the use of a leading 0 to > > represent octal actually predates the prevalence of using 0 in dates > > by almost two decades. > > Not quite - at the time I started, punch cards and data entry forms were > already well established practice, and at least on the English machines, (ICL > 1500/1900 series) octal was prevalent, but I don't know when the leading zero > octal notation started, and where. I said "prevalence." The key is that the average person did not start using leading zeros in dates until (I think) much, much later, and that's what's relevant to this discussion. If it were not commonplace for people to use decimal numbers with leading zeros, this whole thread would be a moot point, the python devs likely never would have considered changing the syntax, and we would not be having this discussion. Most people did not work as data entry clerks on ICL computers... :) Those participating in this thread have pretty much all seem to agree that the only places where decimal numbers with leading zeros really are common are either in rather specialized applications, such as computer-oriented data or serial numbers (which typically behave more like strings, from a computer science perspective), or the rather common one of dates. The latter case is perhaps what's significant, if any of those cases are. I tend to think that within the computer science arena, the history and prevalence of the leading 0 indicating octal far outweighs all of those cases combined. > I think you give it credence for far more depth of design thinking than what > actually happened in those days - some team working on a compiler made a > decision (based on gut feel or experience, or precedent, or whim ) and that > was that - lo! - a standard is born! Rather, I think you give the folks at Bell Labs way too little credit. They designed a programming language and an operating system that, while certainly not exactly the same as their original incarnations, even then contained a lot of features and design principles that remain state-of-the-art (though perhaps their specific implementation details have since been improved) and in many ways superior to a lot of what has come since (e.g. virtually anything that came out of Microsoft). [That's just my opinion, of course... but shared by many. :)] I don't think that happened by mere accident. That's not to say they were perfect, but those guys had their proverbial $#!t together. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From martin at v.loewis.de Mon Aug 24 11:56:43 2009 From: martin at v.loewis.de (=?windows-1252?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 24 Aug 2009 17:56:43 +0200 Subject: print() and unicode strings (python 3.1) In-Reply-To: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> Message-ID: <4a92b83b$0$27209$9b622d9e@news.freenet.de> > I don't understand why I'm getting an encode error in python 3.1. The default encoding is not relevant here at all. Look at sys.stdout.encoding. Regards, Martin From chris at simplistix.co.uk Mon Aug 24 12:08:15 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 24 Aug 2009 17:08:15 +0100 Subject: Python 2.6 still not giving memory back to the OS... In-Reply-To: <4A88406C.3060609@v.loewis.de> References: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> <762603ba-0a4c-4504-94d9-34a8b1e3f9c3@s15g2000yqs.googlegroups.com> <4A88406C.3060609@v.loewis.de> Message-ID: <4A92BAEF.2010303@simplistix.co.uk> Martin v. L?wis wrote: > Today, there are two cases when malloc returns memory on a typical > Unix system (in particular, in Linux malloc): > a) if the malloc block block is small (below page size), it is allocated > from the brk heap, where it can only be returned if the last page of > that heap is completely free, and > b) if the block is large (multiple pages), it gets returned to the > system right away. > > Case b) can only happen if the C malloc uses mmap to allocate large > blocks. I believe (and John will correct me if I'm wrong) that xlrd uses mmap, so why am I not seeing the memory being returned? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From stefan_ml at behnel.de Mon Aug 24 12:12:11 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 18:12:11 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <02a2a478$0$20629$c3e8da3@news.astraweb.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <4a918fe0$0$30226$9b4e6d93@newsspool1.arcor-online.net> <02a1cc1d$0$30337$c3e8da3@news.astraweb.com> <4a9243d3$0$32677$9b4e6d93@newsspool2.arcor-online.net> <02a2a478$0$20629$c3e8da3@news.astraweb.com> Message-ID: <4a92bbdb$0$32676$9b4e6d93@newsspool2.arcor-online.net> Steven D'Aprano wrote: > On Mon, 24 Aug 2009 09:40:03 +0200, Stefan Behnel wrote: > >>> Or you could enter the 21 century and understand that "guys" has become >>> a generic term for people of any sex. >> Is that true for everyone who understands and/or writes English? In that >> case, I'm fine with your above statement. Otherwise, I'd wonder who you >> meant with the term "cultural chauvinism". So far, I only learned that >> most North-American English native speakers use that term in the way you >> refer to. That doesn't even get you close to the majority of English >> speakers. > > If you read the entire thread, you'd see that we've already discussed the > issue of "guys" for mixed sex groups and females. In fact, as I'd already > said, I'm one of those old fashioned guys who still gets surprised when > women refer to themselves as guys, but I'm learning to keep up with the > times. I'm Australian, not North American, and the British author Michael > Quinion, one of the researchers for the Oxford Dictionary, also states > that "guys" now refers to both men and women: > > http://www.worldwidewords.org/weirdwords/ww-guy1.htm > > When "guys" can refer to either sex in English, American, Canadian and > Australian English, I think it should be pretty uncontroversial to treat > it as standard now. Ok, then I guess I just misread "after being adopted in the USA it started to change meaning" in one of the cited articles as "it changed meaning in the USA". I didn't expect Australians (and Oxford dictionary writers, and potentially others) to be /that/ influenced by shifts in US juvenile word semantics... I for one wouldn't start calling my leg "foot", even though the Austrians kept insisting for ages now. Stefan From chris at simplistix.co.uk Mon Aug 24 12:13:45 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 24 Aug 2009 17:13:45 +0100 Subject: Barcodes In-Reply-To: <9c8c445f0908191655i42ec8f86p8f699f2b35cbf6f7@mail.gmail.com> References: <9c8c445f0908171318x2d9d862bi35ccb398376aceca@mail.gmail.com> <4A89C3BB.2030605@tim.thechases.com> <9c8c445f0908190619v5f50de1bvbbfbd8c0557f9783@mail.gmail.com> <9c8c445f0908191655i42ec8f86p8f699f2b35cbf6f7@mail.gmail.com> Message-ID: <4A92BC39.3010007@simplistix.co.uk> Ronn Ross wrote: > > I found this library, but no > documentation(https://cybernetics.hudora.biz/projects/wiki/huBarcode). > Has anyone used this or know of a similar library with better > documentation? Yup, reportlab has really good barcode generation stuff. I use it to generate labels with barcodes on for asset tracking :-) http://the-gay-bar.com/index.php?/archives/221-Howto-generate-barcodes-in-Python-with-reportlab/ Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From Scott.Daniels at Acm.Org Mon Aug 24 12:18:20 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 24 Aug 2009 09:18:20 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: Piet van Oostrum wrote: >>>>>> Scott David Daniels (SDD) wrote: > >> SDD> James Harris wrote:... >>>> Another option: >>>> >>>> 0.(2:1011), 0.(8:7621), 0.(16:c26b) >>>> >>>> where the three characters "0.(" begin the sequence. >>>> >>>> Comments? Improvements? > >> SDD> I did a little interpreter where non-base 10 numbers >> SDD> (up to base 36) were: > >> SDD> .7.100 == 64 (octal) >> SDD> .9.100 == 100 (decimal) >> SDD> .F.100 == 256 (hexadecimal) >> SDD> .1.100 == 4 (binary) >> SDD> .3.100 == 9 (trinary) >> SDD> .Z.100 == 46656 (base 36) > > I wonder how you wrote that interpreter, given that some answers are wrong. Obviously I started with a different set of examples and edited after starting to make a table that could be interpretted in each base. After doing that, I forgot to double check, and lo and behold .F.1000 = 46656, while .F.100 = 1296. Since it has been decades since I've had access to that interpreter, this is all from memory. --Scott David Daniels Scott.Daniels at Acm.Org From nmm1 at cam.ac.uk Mon Aug 24 12:20:23 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Mon, 24 Aug 2009 17:20:23 +0100 (BST) Subject: Python/Fortran interoperability References: <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> Message-ID: In article , sturlamolden wrote: > >You also made this claim regarding Fortran's C interop with strings: > >"No, I mean things like 'Kilroy was here'. Currently, Fortran's C >interoperability supports only strings of length 1, and you have >to kludge them up as arrays. That doesn't work very well, especially >for things like function results." > >This obviosuly proves you wrong: Er, no, it doesn't. I suggest that you read what I said more carefully - and the Fortran standard. As I said, you can kludge them up, and that is precisely one such kludge - but, as I also said, it doesn't work very well. However, I shall take your answer as a "yes, I want to do that". Regards, Nick Maclaren. From code at pizzashack.org Mon Aug 24 12:21:46 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 11:21:46 -0500 Subject: Annoying octal notation In-Reply-To: <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> Message-ID: <20090824162146.GD20434@dragontoe.org> On Mon, Aug 24, 2009 at 08:31:13AM -0700, Carl Banks wrote: > On Aug 24, 6:56?am, Derek Martin wrote: > >?I think hard-coding dates is more uncommon than using octal. ;-) > >?[It unquestionably is, for me personally.] > > You just don't get it, do you? I think I get it just fine, thanks. > Do you really think this is a contest over what's more common and > the winner gets to choose the syntax? You really think that's the > issue? No, I think it's about egos. Someone got the idea that 0o1 was better than 01, and had to be Right. And had the power to make it happen, or at least (sadly) convince the people with the power. I'm simply presenting an argument that the need for the change is not so clear. You say the old syntax is retarded. I say the new syntax, and the very act of making the change itself is retarded. I think my argument is very solid and persuasive; but of course some minds are invulnerable to persuasion. I might not even disagree that the old syntax could be improved upon, except that it already is what it is, and the new syntax is NOT better; I personally believe it's not only not better, but that it's actually worse. Others have agreed. > It is not. The issue is that C's arcane octal notation is MIND- > BOGGLINGLY RETARDED. As I said, I searched the web on this topic before I bothered to post. I did a bit of research. One of the things that my search turned up: A lot of smart people disagree with you. If the use of the leading zero boggles your mind, then perhaps your mind is too easily boggled, and perhaps you should seek a different way to occupy your time. This is yet another case where some Pythonista has gotten it in his head that "There is One Truth, and the Old Way be Damned, my way is The Way, and Thus Shall It Be Evermore." And worse yet, managed to convince others. Well, there's no such thing as One Truth, and there are different perspectives that are just as valid as yours. I'm expressing one now. This change sucks. I already know that my rant won't change the syntax. The only reason I bothered to post is because I do actually quite like Python -- something I can say of only one other programming language -- and I think the powers that be are (in some cases) making it worse, not better. I hoped to open a few minds with a different perspective, but of course I should have known better. 0o1 is not better than 01. On my terminal it's hard to see the difference between 0 and o. YMMV. But since YMMV, and since the old syntax is prevalent both within and without the Python community, making the change is, was, and always will be a bad idea. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve at REMOVE-THIS-cybersource.com.au Mon Aug 24 12:47:43 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2009 16:47:43 GMT Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <20090824135648.GA20434@dragontoe.org> Message-ID: <02a2b43f$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 09:14:25 -0500, Derek Martin wrote: > Assuming I'm right about that, then the use of a leading 0 to represent > octal actually predates the prevalence of using 0 in dates by almost two > decades. And while using leading zeros in other contexts is "familiar" > to me, I would certainly not consider it "common" by any means. Thus I > think it's fair to say that when this syntax was selected, it was a > rather good choice. Except of course to anyone familiar with mathematics in the last, oh, five hundred years or so. Mathematics has used a positional system for numbers for centuries now: leading zeroes have been insignificant, just like trailing zeroes after the decimal point: 9 = 09 = 009 = 9.0 = 9.00 = 0009.000 etc. -- Steven From ronn.ross at gmail.com Mon Aug 24 12:50:37 2009 From: ronn.ross at gmail.com (Ronn Ross) Date: Mon, 24 Aug 2009 12:50:37 -0400 Subject: Reading binary files In-Reply-To: <9c8c445f0908240818k1ae301acr49c65ccb21435cd7@mail.gmail.com> References: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> <1251125039.23757.0.camel@brotherus.corp.redhat.com> <9c8c445f0908240818k1ae301acr49c65ccb21435cd7@mail.gmail.com> Message-ID: <9c8c445f0908240950h24e5bfccoc9ae809c1048be5d@mail.gmail.com> On Mon, Aug 24, 2009 at 11:18 AM, Ronn Ross wrote: > > > On Mon, Aug 24, 2009 at 10:43 AM, Albert Hopkins wrote: > >> On Mon, 2009-08-24 at 10:35 -0400, Ronn Ross wrote: >> > I need to read a binary file. When I open it up in a text editor it is >> > just junk. Does Python have a class to help with this? >> >> Yes, the "file" class. >> >> >>> myfile = open('/path/to/binary/file', 'rb') >> >> -a >> > This works for a simple binary file, but the actual file I'm trying to read > is give throwing an error that the file cannot be found. Here is the name of > the my file: > 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars > > Should python have trouble reading this file name or extension? > I'm having trouble with the filename: 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars It throws an error with that file name, When I change it to something like sample.txt it runs, but the data is still garbled. Is there any reason why I can't use the above file name? If I'm using 'rb' to read the binary file why is it still garbled? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Mon Aug 24 12:54:03 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 24 Aug 2009 09:54:03 -0700 (PDT) Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> Message-ID: On Aug 24, 9:56?am, "Martin v. L?wis" wrote: > > I don't understand why I'm getting an encode error in python 3.1. > > The default encoding is not relevant here at all. Look at > sys.stdout.encoding. > > Regards, > Martin Hi, Thanks for the response. I get US-ASCII for both 2.6 and 3.1: ===python 3.1====== import sys print(sys.stdout.encoding) $ python3.1 1test.py US-ASCII I can't figure out a way to programatically set the encoding for sys.stdout. So where does that leave me? python 3.1 won't let me explicitly encode my unicode string, and python 3.1 implicitly does the encoding with the wrong codec. And why would any programmer rely on python 3.1's implicit encoding of unicode strings anyway? Presumably, different systems will have different encodings for sys.stdout, some encodings might cause encode errors. From rurpy at yahoo.com Mon Aug 24 12:56:47 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 24 Aug 2009 09:56:47 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: <8e65beea-eb8e-45cf-b286-36055be5eb2e@c2g2000yqi.googlegroups.com> On 08/24/2009 06:08 AM, Gilles Ganault wrote: > I was wondering if some people in this ng use Python and some GUI > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > applications, and if yes, what it's like, the pros and cons, etc. > > I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. > > I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. I sure you'll get plenty of GUI-x is really great and you'll is just as good as anything commercial out there, so I thought a minority opinion, even if unpopular, might be useful. Won't comment on the control choices or packaging issues, but I am at the moment doing a little database-connected app that presents editable data in a spreadsheet like (grid) form using wxPython. It has been a very painful process. I have not found any simple pre-written code to connect a wxPython grid to a database so that the result is something like a Microsoft Access datasheet.[*1] It is probably taking me 10 times as long to develop this app in WxPython/Postgresql as it did to develop something similar in MS Access/VBA/SQL Server. I haven't needed for printing yet, but I've read wxpython maillist posts about the difficultly of getting printing to work so you may want to check that out as well before commiting to wxpython. A meta-issue that applies (I think) to both wxPython and PyQt is that both projects seem to be highly dependent on a single person leading one to worry about the "bus" scenario. I am not a fan of Microsoft (in fact I despise their commercial behavior and many aspects of thier products) but I am reporting the reality as I've experienced it. [*1] There are ORMs like Sqlalchemy but they introduce a additional problems like inefficient database operations, dependency on a large external package, etc. It is hard to tell for sure since the Sqlalchemy docs are lousy, which of course means even more development time. From code at pizzashack.org Mon Aug 24 13:02:39 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 12:02:39 -0500 Subject: Annoying octal notation In-Reply-To: <02a2b43f$0$20629$c3e8da3@news.astraweb.com> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <20090824135648.GA20434@dragontoe.org> <02a2b43f$0$20629$c3e8da3@news.astraweb.com> Message-ID: <20090824170239.GE20434@dragontoe.org> On Mon, Aug 24, 2009 at 04:47:43PM +0000, Steven D'Aprano wrote: > Except of course to anyone familiar with mathematics in the last, oh, > five hundred years or so. Mathematics has used a positional system for > numbers for centuries now: leading zeroes have been insignificant, just > like trailing zeroes after the decimal point: > > 9 = 09 = 009 = 9.0 = 9.00 = 0009.000 etc. Dude, seriously. No one ever *uses* leading zeros in the context of mathematics except in 2nd grade math class. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve at REMOVE-THIS-cybersource.com.au Mon Aug 24 13:03:28 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2009 17:03:28 GMT Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> Message-ID: <02a2b7f1$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 11:21:46 -0500, Derek Martin wrote: > since the old > syntax is prevalent both within and without the Python community, making > the change is, was, and always will be a bad idea. Octal syntax isn't prevalent *at all*, except in a small number of niche areas. You've said that this change is a hardship for you, because on your terminal 0 and o are hard to distinguish. Personally, I'd say that's a good sign that your terminal is crappy and you should use a better one, but putting that aside, let's accept that. To you, for whatever reason, 0o looks just like 00. Okay then. Under the current 2.x syntax, 0012 would be interpreted as octal. Under the new 3.x syntax, 0o12 which looks just like 0012 also would be interpreted as octal. You have argued that it might not be any harder to type the extra 'o' to get an octal literal, but that it will hurt readability. I quote: "Writing 0o12 presents no hardship; but I assert, with at least some support from others here, that *reading* it does." But according to you, reading 0o12 is just like reading 0012. 0o12 under the new syntax gives decimal ten, and it looks just like 0012 in the old syntax, which also gives ten. So there's no difference in reading, and you've already accepted that the extra effort in writing it "presents no hardship". A whole lot of noise over a change which is more or less invisible. -- Steven From harald.luessen at gmx.de Mon Aug 24 13:18:16 2009 From: harald.luessen at gmx.de (Harald Luessen) Date: Mon, 24 Aug 2009 19:18:16 +0200 Subject: Annoying octal notation References: <20090824135648.GA20434@dragontoe.org> <20090824141425.GB20434@dragontoe.org> <200908241722.39942.hendrik@microcorp.co.za> Message-ID: On Mon, 24 Aug 2009 Derek Martin wrote: >Those participating in this thread have pretty much all seem to agree >that the only places where decimal numbers with leading zeros really >are common are either in rather specialized applications, such as >computer-oriented data or serial numbers (which typically behave more >like strings, from a computer science perspective), or the rather >common one of dates. The latter case is perhaps what's significant, >if any of those cases are. I don't like the 'leading 0 is octal'-syntax. I typically think of numbers as decimal and bytes as hexadecimal. I would even write something like this: # iterate over bits 3 to 5 for i in range(0x00, 0x40, 0x08): ... print "0x%02x\n" % i 0x00 0x08 0x10 0x18 0x20 0x28 0x30 0x38 For me it is easier to see where the bits are in the hex notation. And it is very common to use numbers with leading zeroes that are hexadecimal. Like this: # print address and data for i in range(0x10000): print "%04x: %d\n" % i, data[i] 0000: ... 0001: ... ... 000f: ... 0010: ... ... When you are looking for examples of numbers where leading zeroes do not mean octal then consider decimal AND hexadecimal. >I tend to think that within the computer >science arena, the history and prevalence of the leading 0 indicating >octal far outweighs all of those cases combined. I disagree. Harald From robert.kern at gmail.com Mon Aug 24 13:19:27 2009 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 24 Aug 2009 12:19:27 -0500 Subject: Is Python what I need? In-Reply-To: References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: On 2009-08-24 08:32 AM, Peter Otten wrote: > Jean-Michel Pichavant wrote: > >>> > From the distance it looks like these children need a good teacher >>>> rather than a bad (or just starting) programmer. > >> Wow, that is rude. Let's keep this list friendly, won't we ? > > I may have been too blunt, and if my message has come across as an insult I > apologize for that. Let me try again: > > If you are trying to teach children that are unwilling to use pen and paper > putting them in front of a computer doesn't help you and them one bit. As a > starting programmer you'll have to spend a lot of time in front of your > computer that may be better spent with your students. I suspect everyone is reading too much into the word "aversion". There may be physical or mental handicaps involved, not the personal preference of the students. In such a case, the OP's word choice is not ideal, but the readers here should give a little more thought before assuming the most ludicrous interpretation. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sturlamolden at yahoo.no Mon Aug 24 13:23:55 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 10:23:55 -0700 (PDT) Subject: Python/Fortran interoperability References: <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> Message-ID: <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> On 24 Aug, 18:20, n... at cam.ac.uk wrote: >This obviosuly proves you wrong: > > Er, no, it doesn't. ?I suggest that you read what I said more > carefully - and the Fortran standard. ?As I said, you can kludge > them up, and that is precisely one such kludge - You said we have to kludge them up as arrays. I did not. I kludged up the C string as a pointer to a Fortran string, and called strlen to get the length of the C string. You also said we can only interop with length-1 character strings. My kludge was valid Fortran and works with strings of any length up to some sane limit that you can specify. You cannot expect a C pointer to carry information about the length of the string. C strings are nul terminated, which is precisely why we have strlen. When C has to use strlen to get the length of a C string, so does Fortran. You cannot use the Fortran standard to change the behaviour of C. > but, as I also > said, it doesn't work very well. Only if you have an incredibly stupid compiler. Sturla From dirkmoors at gmail.com Mon Aug 24 13:30:09 2009 From: dirkmoors at gmail.com (gravityzoo-dmo) Date: Mon, 24 Aug 2009 10:30:09 -0700 (PDT) Subject: Python memory management <-> virtualized server environments Message-ID: Hello everyone, I was wondering if anyone here has had any experience in running Python in a virtualized server environment? The reason I'm asking is the recent thing I noticed when running my server application (written in Python + Twisted); The memory of the server application seems to only grow, and not give back memory space to the OS. I realize that this won't be a problem on a single physical server, but I'm curious of the effect this behaviour has on a virtualized environment. Could anyone provide me with a little more insight please? Thanks in advance! Dirk From jkpeck at gmail.com Mon Aug 24 13:30:23 2009 From: jkpeck at gmail.com (JKPeck) Date: Mon, 24 Aug 2009 10:30:23 -0700 (PDT) Subject: csv module and None values Message-ID: I'm trying to get the csv module (Python 2.6) to write data records like Excel. The excel dialect isn't doing it. The problem is in writing None values. I want them to result in just sequential commas - ,, but csv treats None specially, as the doc says, "To make it as easy as possible to interface with modules which implement the DB API, the value None is written as the empty string." I need strings to be quoted but not None values. Is there any way to get around this special None treatment? TIA, Jon Peck From code at pizzashack.org Mon Aug 24 13:40:24 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 12:40:24 -0500 Subject: Annoying octal notation In-Reply-To: <02a2b7f1$0$20629$c3e8da3@news.astraweb.com> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> <02a2b7f1$0$20629$c3e8da3@news.astraweb.com> Message-ID: <20090824174024.GF20434@dragontoe.org> On Mon, Aug 24, 2009 at 05:03:28PM +0000, Steven D'Aprano wrote: > On Mon, 24 Aug 2009 11:21:46 -0500, Derek Martin wrote: > > since the old syntax is prevalent both within and without the > > Python community, making the change is, was, and always will be a > > bad idea. > > Octal syntax isn't prevalent *at all*, except in a small number of > niche areas. Steven, don't be obtuse. Where octal is used in programming, the leading zero is prevalent. > You've said that this change is a hardship for you, because on your > terminal 0 and o are hard to distinguish. Personally, I'd say that's a > good sign that your terminal is crappy and you should use a better one, The terminal I use is just fine. Stringing together similar characters always has the possibility of confusing the reader. The human mind tends to see what it expects, and fills in the gaps when it does not. It wouldn't matter much if I changed my terminal font, unless I made the font big enough to be not especially useful, except for the rather exceptional case of detecting 0o1 and similar patterns in python code. The suggestion is asinine, and you know it. > but putting that aside, let's accept that. To you, for whatever reason, > 0o looks just like 00. It doesn't look "just like" 00, but similar enough that you have to pay close attention. > Okay then. Under the current 2.x syntax, 0012 would be interpreted as > octal. Under the new 3.x syntax, 0o12 which looks just like 0012 also > would be interpreted as octal. You have argued that it might not be any > harder to type the extra 'o' to get an octal literal, but that it will > hurt readability. I quote: > > "Writing 0o12 presents no hardship; but I assert, with at least some > support from others here, that *reading* it does." Let me clarify my statement. Writing 0o12 is easy -- there is no hardship to type the characters 0o12 (well, actually it feels a bit cumbersome, to be honest). Remembering to do so, however, when virtually everwhere else one uses octal writes it 012, is not easy. Then I stand corrected: There is indeed hardship. > But according to you, reading 0o12 is just like reading 0012. 0o12 under > the new syntax gives decimal ten, and it looks just like 0012 in the old > syntax, which also gives ten. So there's no difference in reading, But there *IS* a difference in reading, because 0o12 is not the same as 0012, and which one you use *matters*. In particular, it will matter with the adoption of Python 3.x, where the latter will be an error. But it matters even in 2.6 because right now, you can write it either way, and that is (I think) even more confusing... There is also still discussion (mentioned in the relevant PEP) about making 0012 *valid decimal*. That should never, ever, ever happen. Why is it so hard for you to accept that intelligent people can disagree with you, and that what's right for you might be bad for others? -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From manu3d at gmail.com Mon Aug 24 13:43:24 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Mon, 24 Aug 2009 10:43:24 -0700 (PDT) Subject: List iterator thread safety Message-ID: Let's say I have a list accessed by two threads, one removing list items via "del myList[index]" statement the other iterating through the list and printing out the items via "for item in myList:" statement. Am I right to say this -won't- generate exceptions because the list iterator is not concerned with the list changing in size under its nose? Or are there pitfalls I should be aware of? Manu From nospam at see.signature Mon Aug 24 14:04:56 2009 From: nospam at see.signature (Richard Maine) Date: Mon, 24 Aug 2009 11:04:56 -0700 Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> Message-ID: <1j4y84p.v5docbtueccmN%nospam@see.signature> sturlamolden wrote: > You also said we can only interop with > length-1 character strings. My kludge was valid Fortran and works with > strings of any length up to some sane limit that you can specify. There might be a confusion here (and I'm not even sure on whose part) on a picky but important detail of wording. I have seen multiple people confused by this one before. In fact, some potential confusion was forseen, which is why there are notes specifically about it in the Fortran standard (see below). Those notes do tend to get overlooked though. Only character strings of length 1 are interoperable, as the term "interoperable" is defined in the Fortran standard. However, that does not mean that only character strings of length 1 will work with C. The distinction might be picky, but it is important. See Note 15.19 (which in turn cites an example in Note 15.23) of f2003. You can pass a Fortran string of length n as an actual argument corrseponding to a dummy argument that is an array of n character*1 elements. This isn't considered a question of "interoperability", as it is a feature purely within Fortran, but it does impact on what kinds of things work. One might plausibly regard this as a kludge, but it is a kludge that is part of the Fortran standard and is guaranteed to work with all Fortran compilers. I almost said all f2003-compliant compilers (admittedly a limited set), but then I recalled that the feature actually dates back to f77 when character type was introduced; f2003 just extends it to the C character kind for the obscure case where the C character kind might be different from the default character kind (I don't know of any compilers where this is so, but the standard allows for it). -- Richard Maine | Good judgment comes from experience; email: last name at domain . net | experience comes from bad judgment. domain: summertriangle | -- Mark Twain From stefan_ml at behnel.de Mon Aug 24 14:19:28 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 20:19:28 +0200 Subject: print() and unicode strings (python 3.1) In-Reply-To: References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> Message-ID: <4a92d9b0$0$32667$9b4e6d93@newsspool2.arcor-online.net> 7stud wrote: > python 3.1 won't let me > explicitly encode my unicode string Sure it does. But encoding a non-ASCII string to ASCII will necessarily fail. > and python 3.1 implicitly does > the encoding with the wrong codec. That's not a Python problem, though. Your terminal is configured for US-ASCII, so you can't output anything but US-ASCII characters. Change your terminal setup to e.g. UTF-8 and see how things start working. Stefan From davea at ieee.org Mon Aug 24 14:35:21 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 24 Aug 2009 14:35:21 -0400 Subject: Reading binary files In-Reply-To: <9c8c445f0908240950h24e5bfccoc9ae809c1048be5d@mail.gmail.com> References: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> <1251125039.23757.0.camel@brotherus.corp.redhat.com> <9c8c445f0908240818k1ae301acr49c65ccb21435cd7@mail.gmail.com> <9c8c445f0908240950h24e5bfccoc9ae809c1048be5d@mail.gmail.com> Message-ID: <4A92DD69.7090007@ieee.org> Ronn Ross wrote: > On Mon, Aug 24, 2009 at 11:18 AM, Ronn Ross wrote: > > >> On Mon, Aug 24, 2009 at 10:43 AM, Albert Hopkins wrote: >> >> >>> On Mon, 2009-08-24 at 10:35 -0400, Ronn Ross wrote: >>> >>>> I need to read a binary file. When I open it up in a text editor it is >>>> just junk. Does Python have a class to help with this? >>>> >>> Yes, the "file" class. >>> >>> >>>>>> myfile = open('/path/to/binary/file', 'rb') >>>>>> >>> -a >>> >>> >> This works for a simple binary file, but the actual file I'm trying to read >> is give throwing an error that the file cannot be found. Here is the name of >> the my file: >> 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars >> >> Should python have trouble reading this file name or extension? >> >> > I'm having trouble with the filename: > 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars > > It throws an error with that file name, When I change it to something like > sample.txt it runs, but the data is still garbled. Is there any reason why I > can't use the above file name? If I'm using 'rb' to read the binary file why > is it still garbled? > > > You're describing two separate problems here. One is an error in the open statement, and the other is "something is garbled." If you hand a relative path name to the open() function, it'll have to get the absolute path from somewhere else, presumably the current directory. Do you know for sure what the current directory is, and is that file located there? Try printing os.path.abspath(os.curdir). Or pass a complete (absolute) path to open(). As for garbled... Just what do you expect? A binary file is a completely arbitrary sequence of bytes. So if you're trying to print it, you may see "garbled." Just what is the file's purpose anyway? You can't do much with it without knowing something about it. DaveA From martin.hellwig at dcuktec.org Mon Aug 24 14:35:45 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Mon, 24 Aug 2009 19:35:45 +0100 Subject: Python memory management <-> virtualized server environments In-Reply-To: References: Message-ID: gravityzoo-dmo wrote: > Hello everyone, > > I was wondering if anyone here has had any experience in running > Python in a virtualized server environment? > The reason I'm asking is the recent thing I noticed when running my > server application (written in Python + Twisted); > The memory of the server application seems to only grow, and not give > back memory space to the OS. I realize that this won't be a problem on > a single physical server, but I'm curious of the effect this behaviour > has on a virtualized environment. > Could anyone provide me with a little more insight please? > Thanks in advance! > > Dirk Might help if you say which version of Python you are running, although I'm not a memory expert I do know there have been some changes between the versions. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From bbxx789_05ss at yahoo.com Mon Aug 24 14:45:17 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 24 Aug 2009 11:45:17 -0700 (PDT) Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92d9b0$0$32667$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <00daf8f6-ee6a-47ab-8d92-1676a473d7cc@y4g2000prf.googlegroups.com> On Aug 24, 12:19?pm, Stefan Behnel wrote: > 7stud wrote: > > python 3.1 won't let me > > explicitly encode my unicode string > > Sure it does. But encoding a non-ASCII string to ASCII will necessarily fail. > As you should be able to see in the python 3.1 example I posted, I did not encode the string using the ascii codec. I encoded it with the utf-8 codec, and unfortunately in python 3.1 that creates a "bytes string", and print()'ing a bytes string does not produce human readable text. > > and python 3.1 implicitly does > > the encoding with the wrong codec. > > That's not a Python problem, though. Your terminal is configured for > US-ASCII, so you can't output anything but US-ASCII characters. > My terminal is configured for utf-8, and from the output of the python 2.6 example I posted, it should be apparent that my terminal is capable of rendering the euro character. From gert.cuykens at gmail.com Mon Aug 24 14:50:55 2009 From: gert.cuykens at gmail.com (gert) Date: Mon, 24 Aug 2009 11:50:55 -0700 (PDT) Subject: How does the file.seek() work ? Message-ID: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> I want the file pointer set to 100 and overwrite everything from there curl -C 100 -T upload2.wsgi http://192.168.2.17/appwsgi/wsgi/upload2.wsgi -v w+ overwrites my file completely r+ overwrites nothing a+ only makes my file bigger import os def application(environ, response): query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') range=environ.get('HTTP_RANGE','bytes=0-').replace ('bytes=','').split(',') offset=[] for r in range: offset.append(r.split('-')) with open(query,'w+') as f: f.seek(int(offset[0][0])) while True: chunk=environ['wsgi.input'].read(8192).decode('latin1') if not chunk: break f.write(chunk) f=open(query) l=str(os.fstat(f.fileno()).st_size) response('200 OK', [('Content-Type', 'text/plain'), ('Content- Length', str(len(l)))]) return [l] also why must I open the file a second time to know how big it is ? From nmm1 at cam.ac.uk Mon Aug 24 14:55:38 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Mon, 24 Aug 2009 19:55:38 +0100 (BST) Subject: Python/Fortran interoperability References: <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> <1j4y84p.v5docbtueccmN%nospam@see.signature> Message-ID: In article <1j4y84p.v5docbtueccmN%nospam at see.signature>, Richard Maine wrote: > >Only character strings of length 1 are interoperable, as the term >"interoperable" is defined in the Fortran standard. However, that does >not mean that only character strings of length 1 will work with C. The >distinction might be picky, but it is important. Precisely. And the kludge does NOT work under all circumstances, which is why I said that it doesn't work very well. Consider, for example: SUBROUTINE Fred (X) BIND(C) CHARACTER*(*) :: X END SUBROUTINE Fred CHARACTER(LEN=100) :: string CALL Fred(string(40:60)) CALL Fred(string(5:50)) This is not currently allowed and raises all sorts of 'interesting' implementation and portability questions. For example, I defy anyone to write Fred portably in C :-) It gets really hairy if you have functions that have assumed length results, but those are obsolescent. Even when Fred has an explicit length, there are some problematic cases, which could catch out programmers in one language that don't know the other fairly well. But those are much less of a problem than the common need for assumed length CHARACTER arguments. Regards, Nick Maclaren. From sturlamolden at yahoo.no Mon Aug 24 15:14:26 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 12:14:26 -0700 (PDT) Subject: Python/Fortran interoperability References: <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> <1j4y84p.v5docbtueccmN%nospam@see.signature> Message-ID: <7abee4bb-b18a-4680-817b-7e76aed40194@c2g2000yqi.googlegroups.com> On 24 Aug, 20:55, n... at cam.ac.uk wrote: > Precisely. ?And the kludge does NOT work under all circumstances, > which is why I said that it doesn't work very well. Do you have an example? > Consider, for example: > > ? ? SUBROUTINE Fred (X) BIND(C) > ? ? CHARACTER*(*) :: X > ? ? END SUBROUTINE Fred Obviously that is not allowed, because C does not know anything about Fortran strings. How should a C compiler pass the correct data structure to Fred? The C bindings in Fortran 2003 has functions to convert C pointers to Fortran pointers (c_f_pointer, c_f_procpointer), because C does not know the ABI of a particular Fortran implementation. From http Mon Aug 24 15:17:39 2009 From: http (Paul Rubin) Date: 24 Aug 2009 12:17:39 -0700 Subject: your favorite debugging tool? References: Message-ID: <7xocq5vx64.fsf@ruckus.brouhaha.com> Esmail writes: > What is your favorite tool to help you debug your > code? I've been getting along with 'print' statements > but that is getting old and somewhat cumbersome. Beyond print statements, I use pdb a lot. Winpdb (www.winpdb.org) is even better, but is kind of cumbersome to get working. From gah at ugcs.caltech.edu Mon Aug 24 15:23:53 2009 From: gah at ugcs.caltech.edu (glen herrmannsfeldt) Date: Mon, 24 Aug 2009 19:23:53 +0000 (UTC) Subject: Python/Fortran interoperability References: <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> <1j4y84p.v5docbtueccmN%nospam@see.signature> Message-ID: In comp.lang.fortran nmm1 at cam.ac.uk wrote: (snip) < Precisely. And the kludge does NOT work under all circumstances, < which is why I said that it doesn't work very well. < Consider, for example: < SUBROUTINE Fred (X) BIND(C) < CHARACTER*(*) :: X < END SUBROUTINE Fred < CHARACTER(LEN=100) :: string < CALL Fred(string(40:60)) < CALL Fred(string(5:50)) < This is not currently allowed and raises all sorts of 'interesting' < implementation and portability questions. For example, I defy anyone < to write Fred portably in C :-) You mean, how does FRED know the length? It seems to me the usual question for Fortran assumed size arrays. Assuming that FRED can tell from the passed string, it seems fine to me. If not, it is a problem. Null terminated strings are a C convention, supported by the library and compiler (string constants). Others are legal C, though you have to be careful which library routines you use. < It gets really hairy if you have functions that have assumed length < results, but those are obsolescent. < Even when Fred has an explicit length, there are some problematic < cases, which could catch out programmers in one language that don't < know the other fairly well. But those are much less of a problem < than the common need for assumed length CHARACTER arguments. Maybe Fortran programmers who started in Fortran 66 will not have so much problem with this. The usual way would be to pass the length, as with assumed size arrays. I believe terminating strings with unusual (likely not null) characters was also done. -- glen From nmm1 at cam.ac.uk Mon Aug 24 15:24:35 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Mon, 24 Aug 2009 20:24:35 +0100 (BST) Subject: Python/Fortran interoperability References: <1j4y84p.v5docbtueccmN%nospam@see.signature> <7abee4bb-b18a-4680-817b-7e76aed40194@c2g2000yqi.googlegroups.com> Message-ID: In article <7abee4bb-b18a-4680-817b-7e76aed40194 at c2g2000yqi.googlegroups.com>, sturlamolden wrote: > >> Precisely. =A0And the kludge does NOT work under all circumstances, >> which is why I said that it doesn't work very well. > >Do you have an example? I gave you one. Also see below. >> Consider, for example: >> >> =A0 =A0 SUBROUTINE Fred (X) BIND(C) >> =A0 =A0 CHARACTER*(*) :: X >> =A0 =A0 END SUBROUTINE Fred > >Obviously that is not allowed, because C does not know anything about >Fortran strings. How should a C compiler pass the correct data >structure to Fred? Precisely. The reason I asked that question is that it would be possible to extend the standard to make it possible in a portable fashion. You might also like to consider the converse problem: how to write a Fortran function that takes a C string of arbitrary length and uses it. Regards, Nick Maclaren. From python.list at tim.thechases.com Mon Aug 24 15:37:00 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 24 Aug 2009 14:37:00 -0500 Subject: How does the file.seek() work ? In-Reply-To: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> References: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> Message-ID: <4A92EBDC.8010901@tim.thechases.com> > I want the file pointer set to 100 and overwrite everything from there [snip] > def application(environ, response): > query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') > range=environ.get('HTTP_RANGE','bytes=0-').replace > ('bytes=','').split(',') > offset=[] > for r in range: offset.append(r.split('-')) > with open(query,'w+') as f: > f.seek(int(offset[0][0])) > while True: > chunk=environ['wsgi.input'].read(8192).decode('latin1') > if not chunk: break > f.write(chunk) > f=open(query) > l=str(os.fstat(f.fileno()).st_size) > response('200 OK', [('Content-Type', 'text/plain'), ('Content- > Length', str(len(l)))]) > return [l] A couple items of note: - you don't open the file in binary mode -- seek is more reliable in binary mode :) - if you want to lop off the rest of the file, use f.truncate() An example: # create the initial file >>> f = file('zzz.zzz', 'wb+') >>> f.write('abcdefghijklmnop') >>> f.close() >>> f = file('zzz.zzz', 'ab+') >>> f.read() # show the existing content 'abcdefghijklmnop' >>> f.seek(5) # seek to the desired offset >>> f.truncate() # throw away everything after here >>> f.write('zyx') # write the new data at pos=5 >>> f.close() # demonstrate that it worked >>> f = file('zzz.zzz', 'rb') >>> f.read() 'abcdezyx' >>> f.close() > also why must I open the file a second time to know how big it is ? Likely the output has been buffered. You can try using f.flush() # write all the data to the disk first size = os.fstat(f.fileno()).st_size which seems to do the trick for me. -tkc From gagsl-py2 at yahoo.com.ar Mon Aug 24 15:40:14 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Aug 2009 16:40:14 -0300 Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> <02a2b7f1$0$20629$c3e8da3@news.astraweb.com> <20090824174024.GF20434@dragontoe.org> Message-ID: En Mon, 24 Aug 2009 14:40:24 -0300, Derek Martin escribi?: > Why is it so hard for you to accept that intelligent people can > disagree with you, and that what's right for you might be bad for > others? Ask the same question yourself please. -- Gabriel Genellina From gordon at panix.com Mon Aug 24 15:41:17 2009 From: gordon at panix.com (John Gordon) Date: Mon, 24 Aug 2009 19:41:17 +0000 (UTC) Subject: Web Services examples using "raw" xml? Message-ID: I'm developing a program that will use web services, which I have never used before. There are several tutorials out there that advise you to get the WSDL and then call a method (such as wsdl2py) that inspects the wsdl and automagically generates the python classes and methods you need for interacting with that web service. I've tried this, and have run into a number of roadblocks that have left me frustrated. For example I tried wsdl2py() from the ZSI package, and got this error: Error loading services.xml: namespace of schema and import match I tried WSDL.Proxy() from the SOAPpy package and eventually end up with this error: xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 6 I tried Client() from the suds package, and got this error: File "/usr/lib/python2.3/site-packages/suds/client.py", line 59 @classmethod ^ SyntaxError: invalid syntax I'm not an expert; I have no idea what any of these errors mean, and I have no idea how to go about resolving them. So I decided to take a step back and see if I could bypass all the fancy automagic methods and just create my own SOAP xml message from scratch and then send it to the web server. That would work, surely. But I'm having a tough time finding some good examples of that, because all the tutorials I've found just tell you to use the aforementioned magic methods, which unfortunately don;t seem to be working for me. Does anyone have some good examples of code that builds a "raw" xml SOAP message and sends it to a webserver, then reads the response? I think that would be a good place for me to start. Thanks for any replies. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From gert.cuykens at gmail.com Mon Aug 24 15:41:59 2009 From: gert.cuykens at gmail.com (gert) Date: Mon, 24 Aug 2009 12:41:59 -0700 (PDT) Subject: How does the file.seek() work ? References: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> Message-ID: <6a22c4d5-1f6b-4ebf-9f4e-3f039d213a49@r42g2000yqj.googlegroups.com> On Aug 24, 9:37?pm, Tim Chase wrote: > > I want the file pointer set to 100 and overwrite everything from there > [snip] > > def application(environ, response): > > ? ? query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') > > ? ? range=environ.get('HTTP_RANGE','bytes=0-').replace > > ('bytes=','').split(',') > > ? ? offset=[] > > ? ? for r in range: offset.append(r.split('-')) > > ? ? with open(query,'w+') as f: > > ? ? ? ? ?f.seek(int(offset[0][0])) > > ? ? ? ? ?while True: > > ? ? ? ? ? ? ?chunk=environ['wsgi.input'].read(8192).decode('latin1') > > ? ? ? ? ? ? ?if not chunk: break > > ? ? ? ? ? ? ?f.write(chunk) > > ? ? f=open(query) > > ? ? l=str(os.fstat(f.fileno()).st_size) > > ? ? response('200 OK', [('Content-Type', 'text/plain'), ('Content- > > Length', str(len(l)))]) > > ? ? return [l] > > A couple items of note: > > - you don't open the file in binary mode -- seek is more reliable > in binary mode :) > > - if you want to lop off the rest of the file, use f.truncate() > > An example: > > # create the initial file > ?>>> f = file('zzz.zzz', 'wb+') > ?>>> f.write('abcdefghijklmnop') > ?>>> f.close() > > ?>>> f = file('zzz.zzz', 'ab+') > ?>>> f.read() # show the existing content > 'abcdefghijklmnop' > ?>>> f.seek(5) # seek to the desired offset > ?>>> f.truncate() # throw away everything after here > ?>>> f.write('zyx') # write the new data at pos=5 > ?>>> f.close() > > # demonstrate that it worked > ?>>> f = file('zzz.zzz', 'rb') > ?>>> f.read() > 'abcdezyx' > ?>>> f.close() > > > also why must I open the file a second time to know how big it is ? > > Likely the output has been buffered. ?You can try using > > ? ?f.flush() # write all the data to the disk first > ? ?size = os.fstat(f.fileno()).st_size > > which seems to do the trick for me. > > -tkc Doh! my curl was wrong, thanks :) curl -C 100 upload2.wsgi http://192.168.2.17/appwsgi/wsgi/upload2.wsgi -v From nagle at animats.com Mon Aug 24 15:51:55 2009 From: nagle at animats.com (John Nagle) Date: Mon, 24 Aug 2009 12:51:55 -0700 Subject: Web Services examples using "raw" xml? In-Reply-To: References: Message-ID: <4a92ee38$0$1627$742ec2ed@news.sonic.net> John Gordon wrote: > I'm developing a program that will use web services, which I have never > used before. Web services in general, or some Microsoft interface? John Nagle From nmm1 at cam.ac.uk Mon Aug 24 15:54:38 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Mon, 24 Aug 2009 20:54:38 +0100 (BST) Subject: Python/Fortran interoperability References: <1j4y84p.v5docbtueccmN%nospam@see.signature> Message-ID: In article , glen herrmannsfeldt wrote: > >< Consider, for example: > >< SUBROUTINE Fred (X) BIND(C) >< CHARACTER*(*) :: X >< END SUBROUTINE Fred > >< CHARACTER(LEN=100) :: string >< CALL Fred(string(40:60)) >< CALL Fred(string(5:50)) > >< This is not currently allowed and raises all sorts of 'interesting' >< implementation and portability questions. For example, I defy anyone >< to write Fred portably in C :-) > >You mean, how does FRED know the length? It seems to me the >usual question for Fortran assumed size arrays. Assuming that >FRED can tell from the passed string, it seems fine to me. >If not, it is a problem. Precisely. And the whole point of my question is how many people WANT to do it, from the point of view of extending BIND(C). >< Even when Fred has an explicit length, there are some problematic >< cases, which could catch out programmers in one language that don't >< know the other fairly well. But those are much less of a problem >< than the common need for assumed length CHARACTER arguments. > >Maybe Fortran programmers who started in Fortran 66 will not >have so much problem with this. The usual way would be to >pass the length, as with assumed size arrays. I believe terminating >strings with unusual (likely not null) characters was also done. Yeah. But there are a decreasing number of us left :-) Prefix length strings were also used. Regards, Nick Maclaren. From jkpeck at gmail.com Mon Aug 24 15:55:31 2009 From: jkpeck at gmail.com (JKPeck) Date: Mon, 24 Aug 2009 12:55:31 -0700 (PDT) Subject: csv module and None values References: Message-ID: <040ec55a-5b14-41c4-8099-683a6d3a0a45@n11g2000yqb.googlegroups.com> On Aug 24, 11:30?am, JKPeck wrote: > I'm trying to get the csv module (Python 2.6) to write data records > like Excel. ?The excel dialect isn't doing it. ?The problem is in > writing None values. ?I want them to result in just sequential commas > - ,, but csv treats None specially, as the doc says, > > "To make it as easy as possible to interface with modules which > implement the DB API, the value None is written as the empty string." > > I need strings to be quoted but not None values. ?Is there any way to > get around this special None treatment? > > TIA, > Jon Peck Solved the problem myself by giving a writer class to csv.writer that looks for sentinel markers inserted in place of None and wipes them out before writing to a file. Pretty ugly, but it works. Regards, Jon Peck From gordon at panix.com Mon Aug 24 15:57:06 2009 From: gordon at panix.com (John Gordon) Date: Mon, 24 Aug 2009 19:57:06 +0000 (UTC) Subject: Web Services examples using "raw" xml? References: <4a92ee38$0$1627$742ec2ed@news.sonic.net> Message-ID: In <4a92ee38$0$1627$742ec2ed at news.sonic.net> John Nagle writes: > John Gordon wrote: > > I'm developing a program that will use web services, which I have never > > used before. > Web services in general, or some Microsoft interface? Microsoft. Exchange Web Services, specifically. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From sturlamolden at yahoo.no Mon Aug 24 16:03:06 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 13:03:06 -0700 (PDT) Subject: Python/Fortran interoperability References: <1j4y84p.v5docbtueccmN%nospam@see.signature> <7abee4bb-b18a-4680-817b-7e76aed40194@c2g2000yqi.googlegroups.com> Message-ID: On 24 Aug, 21:24, n... at cam.ac.uk wrote: > You might also like to consider the converse problem: how to write > a Fortran function that takes a C string of arbitrary length and > uses it. That's what the code I showed you does. From code at pizzashack.org Mon Aug 24 16:14:24 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 15:14:24 -0500 Subject: Annoying octal notation In-Reply-To: References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> <02a2b7f1$0$20629$c3e8da3@news.astraweb.com> <20090824174024.GF20434@dragontoe.org> Message-ID: <20090824201424.GG20434@dragontoe.org> On Mon, Aug 24, 2009 at 04:40:14PM -0300, Gabriel Genellina wrote: > En Mon, 24 Aug 2009 14:40:24 -0300, Derek Martin > escribi?: > > >Why is it so hard for you to accept that intelligent people can > >disagree with you, and that what's right for you might be bad for > >others? > > Ask the same question yourself please. I accept it. But I reserve the right to voice my dissent, and am doing so. The Usual Suspects in this forum seem to suggest that the change is some silver bullet that makes Python suddenly Right With The World, and I say it just ain't so. I happen to opine that the old behavior was better, and I will not be dissuaded from that opinion just because a few prominent posters in this forum suggest that I'm an idiot for disagreeing with them. My original post in this thread, if you weren't paying attention, was in opposition to several people trying to cram the idea down the throats of other posters that leading zeros to represent octal numbers is inherently evil, and that anyone who suggests otherwise is an Apostate to be damned for all eternity. Alright, I exaggerate. Slightly. :) -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From vorticitywolfe at gmail.com Mon Aug 24 16:29:07 2009 From: vorticitywolfe at gmail.com (J Wolfe) Date: Mon, 24 Aug 2009 13:29:07 -0700 (PDT) Subject: Pmw optionmenu color Message-ID: <0faab022-2ad1-4579-a5b9-54f93591c953@26g2000yqk.googlegroups.com> Hello, It seems like this should be easy to do... change the background color of the Pmw optionmenu. I have not been able to find this. Anyone have a hint or know how to do this? Thanks, Jonathan From ryniek90 at gmail.com Mon Aug 24 16:34:51 2009 From: ryniek90 at gmail.com (ryniek) Date: Mon, 24 Aug 2009 13:34:51 -0700 (PDT) Subject: Temat:, Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> <4ec18c68-b8b5-401e-b910-802b7662dced@i18g2000pro.googlegroups.com> Message-ID: <321b8396-0806-4a1a-9a32-efbb147e6b4b@c2g2000yqi.googlegroups.com> On 24 Sie, 16:56, John Machin wrote: > On Aug 25, 12:46?am, Tim Golden wrote: > > > Dave Angel wrote: > > > You still haven't gotten rid of those illegal colons in the filename. ? > > > They're not legal in Windows, as has been pointed out a couple of times > > > in this thread. > > > Ummm.. Colons are of course legal in Windows filenames as designating > > That is the most inappropriate "of course" I've seen for quite a > while. > > > the Alternate Data Streams: > > OK, so s/illegal/evil/ Ok, but how to get rid of those colons? Is it necessary? From deets at nospam.web.de Mon Aug 24 16:36:54 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Aug 2009 22:36:54 +0200 Subject: Web Services examples using "raw" xml? In-Reply-To: References: Message-ID: <7fgbv7F2l9u4oU1@mid.uni-berlin.de> John Gordon schrieb: > I'm developing a program that will use web services, which I have never > used before. > > There are several tutorials out there that advise you to get the WSDL > and then call a method (such as wsdl2py) that inspects the wsdl and > automagically generates the python classes and methods you need for > interacting with that web service. > > I've tried this, and have run into a number of roadblocks that have left > me frustrated. Welcome to the wonderful world of SOAP. If you didn't know - the S stands for simple [1]. I don't want to go into a rant about the why and how SOAP sucks, and why it's support in Python is lacking - to say the least. What we did in a similar situation was this: - got hold of a client that was able to speak with the server. In your case, a .NET-client shouldn't be hard to get working. - monitor the traffic that went on between the client and server using some HTTP-proxy or WireShark. - mimicked the server-side protocol by dynamising the sniffed traffic through an XML-templating tool, genshi in our case. Sounds archaic, and complicated? Yes. Blame SOAP (and Microsoft, it's biggest proponent) Diez [1] http://72.249.21.88/nonintersecting/2006/11/15/the-s-stands-for-simple/ From martin at v.loewis.de Mon Aug 24 16:41:37 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 24 Aug 2009 22:41:37 +0200 Subject: print() and unicode strings (python 3.1) In-Reply-To: References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> Message-ID: <4a92fb02$0$2582$9b622d9e@news.freenet.de> > I can't figure out a way to programatically set the encoding for > sys.stdout. So where does that leave me? You should be setting the terminal encoding administratively, not programmatically. Regards, Martin From not_valid at comcast.net Mon Aug 24 16:55:19 2009 From: not_valid at comcast.net (James Van Buskirk) Date: Mon, 24 Aug 2009 14:55:19 -0600 Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> <1j4y84p.v5docbtueccmN%nospam@see.signature> Message-ID: "Richard Maine" wrote in message news:1j4y84p.v5docbtueccmN%nospam at see.signature... > There might be a confusion here (and I'm not even sure on whose part) on > a picky but important detail of wording. I have seen multiple people > confused by this one before. In fact, some potential confusion was > forseen, which is why there are notes specifically about it in the > Fortran standard (see below). Those notes do tend to get overlooked > though. > Only character strings of length 1 are interoperable, as the term > "interoperable" is defined in the Fortran standard. However, that does > not mean that only character strings of length 1 will work with C. The > distinction might be picky, but it is important. > See Note 15.19 (which in turn cites an example in Note 15.23) of f2003. > You can pass a Fortran string of length n as an actual argument > corrseponding to a dummy argument that is an array of n character*1 > elements. This isn't considered a question of "interoperability", as it > is a feature purely within Fortran, but it does impact on what kinds of > things work. > One might plausibly regard this as a kludge, but it is a kludge that is > part of the Fortran standard and is guaranteed to work with all Fortran > compilers. I almost said all f2003-compliant compilers (admittedly a > limited set), but then I recalled that the feature actually dates back > to f77 when character type was introduced; f2003 just extends it to the > C character kind for the obscure case where the C character kind might > be different from the default character kind (I don't know of any > compilers where this is so, but the standard allows for it). No, this is a tricky point. It was allowed in f77 to pass an array actual argument to a scalar character dummy argument, but the ability to pass a scalar character actual argument to an array dummy argument is new to the sequence association rules of f2003. So your first impression was more accurate than the result of thoughtful reflection :) -- write(*,*) transfer((/17.392111325966148d0,6.5794487871554595D-85, & 6.0134700243160014d-154/),(/'x'/)); end From __peter__ at web.de Mon Aug 24 17:00:44 2009 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Aug 2009 23:00:44 +0200 Subject: csv module and None values References: Message-ID: JKPeck wrote: > I'm trying to get the csv module (Python 2.6) to write data records > like Excel. The excel dialect isn't doing it. The problem is in > writing None values. I want them to result in just sequential commas > - ,, but csv treats None specially, as the doc says, > > "To make it as easy as possible to interface with modules which > implement the DB API, the value None is written as the empty string." > > I need strings to be quoted but not None values. Is there any way to > get around this special None treatment? If I understand you correctly the csv.writer already does what you want: Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import csv, sys >>> w = csv.writer(sys.stdout) >>> w.writerow([1,None,2]) 1,,2 just sequential commas, but that is the special treatment. Without it the the None value would be converted to a string and the line would look like this one: >>> class LooksLikeNone: ... def __str__(self): return "None" ... >>> w.writerow([1,LooksLikeNone(),2]) 1,None,2 Peter From ryniek90 at gmail.com Mon Aug 24 17:23:41 2009 From: ryniek90 at gmail.com (ryniek) Date: Mon, 24 Aug 2009 14:23:41 -0700 (PDT) Subject: Temat:, Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> <4ec18c68-b8b5-401e-b910-802b7662dced@i18g2000pro.googlegroups.com> <321b8396-0806-4a1a-9a32-efbb147e6b4b@c2g2000yqi.googlegroups.com> Message-ID: On 24 Sie, 22:34, ryniek wrote: > On 24 Sie, 16:56, John Machin wrote: > > > On Aug 25, 12:46?am, Tim Golden wrote: > > > > Dave Angel wrote: > > > > You still haven't gotten rid of those illegal colons in the filename. ? > > > > They're not legal in Windows, as has been pointed out a couple of times > > > > in this thread. > > > > Ummm.. Colons are of course legal in Windows filenames as designating > > > That is the most inappropriate "of course" I've seen for quite a > > while. > > > > the Alternate Data Streams: > > > OK, so s/illegal/evil/ > > Ok, but how to get rid of those colons? > Is it necessary? I dealt with it. Had to change 'w:bz2' into 'w|bz2'. But now have another problem: " C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje \Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba ckuper.py -f E:\APLIKACJE\nowegg.exe E:\ MyGG Checking permissions for reading and writing... Traceback (most recent call last): File "backuper.py", line 194, in main_meth() File "backuper.py", line 186, in main_meth paq.backup_file(pars.options.filename[0], pars.options.filename [1], pars.options.filename[2]) File "backuper.py", line 114, in backup_file backup_obj = tarfile.open(dest, 'w|bz2') File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib \tarfile.py", line 1675, in open _Stream(name, filemode, comptype, fileobj, bufsize), File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib \tarfile.py", line 400, in __init__ fileobj = _LowLevelFile(name, mode) File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib \tarfile.py", line 373, in __init__ self.fd = os.open(name, mode) OSError: [Errno 22] Invalid argument: 'E:\\MyGG(2009-08-24 23:18:25).tar.bz2' " When i type path with foreward slashes, Python converts them to double backslashes :P " C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje \Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python backuper.py -f E:/ APLIKACJE/nowegg.exe E:/ MyGG Checking permissions for reading and writing... Traceback (most recent call last): File "backuper.py", line 194, in main_meth() File "backuper.py", line 186, in main_meth paq.backup_file(pars.options.filename[0], pars.options.filename [1], pars.options.filename[2]) File "backuper.py", line 114, in backup_file backup_obj = tarfile.open(dest, 'w|bz2') File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib \tarfile.py", line 1675, in open _Stream(name, filemode, comptype, fileobj, bufsize), File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib \tarfile.py", line 400, in __init__ fileobj = _LowLevelFile(name, mode) File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib \tarfile.py", line 373, in __init__ self.fd = os.open(name, mode) OSError: [Errno 22] Invalid argument: 'E:\\MyGG(2009-08-24 23:20:19).tar.bz2' " I tried raw string also, but nothing helps. :-/ From van.lindberg at gmail.com Mon Aug 24 17:37:34 2009 From: van.lindberg at gmail.com (VanL) Date: Mon, 24 Aug 2009 16:37:34 -0500 Subject: Graph library recommendations for large graphs Message-ID: I am working on a project that will require building and querying large graph objects (initially 8M nodes, 30-40M edges; eventually 40M nodes, 100M edges). NetworkX seems to be the most popular, but I am concerned that a dict representation for nodes would use too much memory -- my initial tests suggest that a graph with 3M nodes and 12M edges creates substantial memory pressure on my machine. Can anybody who has worked with large graphs before give a recommendation? Thanks, Van From nospam at see.signature Mon Aug 24 17:39:32 2009 From: nospam at see.signature (Richard Maine) Date: Mon, 24 Aug 2009 14:39:32 -0700 Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> <1j4y84p.v5docbtueccmN%nospam@see.signature> Message-ID: <1j4yiym.1jxu2ko10c7zucN%nospam@see.signature> James Van Buskirk wrote: > "Richard Maine" wrote in message > news:1j4y84p.v5docbtueccmN%nospam at see.signature... > > > One might plausibly regard this as a kludge, but it is a kludge that is > > part of the Fortran standard and is guaranteed to work with all Fortran > > compilers. I almost said all f2003-compliant compilers (admittedly a > > limited set), but then I recalled that the feature actually dates back > > to f77 when character type was introduced; f2003 just extends it to the > > C character kind for the obscure case where the C character kind might > > be different from the default character kind (I don't know of any > > compilers where this is so, but the standard allows for it). > > No, this is a tricky point. It was allowed in f77 to pass an array > actual argument to a scalar character dummy argument, but the ability > to pass a scalar character actual argument to an array dummy argument > is new to the sequence association rules of f2003. So your first > impression was more accurate than the result of thoughtful reflection :) Ah. You might be right - probably you are. I know there is some closely related stuff that goes back a ways and was just extended to the C character kind in f2003, but it might not have been that exact bit. I'm probably thinking of the rule for sequence association that allows the character length parameter to differ between the actual and dummy... as long as you are doing sequence association. But it might be a new rule that puts the scalar case under sequence association; that's probably it. Not worth dragging out the standards to check, but I bet that's it. -- Richard Maine | Good judgment comes from experience; email: last name at domain . net | experience comes from bad judgment. domain: summertriangle | -- Mark Twain From drobinow at gmail.com Mon Aug 24 17:43:41 2009 From: drobinow at gmail.com (David Robinow) Date: Mon, 24 Aug 2009 17:43:41 -0400 Subject: Reading binary files In-Reply-To: <9c8c445f0908240950h24e5bfccoc9ae809c1048be5d@mail.gmail.com> References: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> <1251125039.23757.0.camel@brotherus.corp.redhat.com> <9c8c445f0908240818k1ae301acr49c65ccb21435cd7@mail.gmail.com> <9c8c445f0908240950h24e5bfccoc9ae809c1048be5d@mail.gmail.com> Message-ID: <4eb0089f0908241443p348eea3dxd57581e37f94d0bd@mail.gmail.com> >> This works for a simple binary file, but the actual file I'm trying to >> read is give throwing an error that the file cannot be found. Here is the >> name of the my file: >> 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars >> >> Should python have trouble reading this file name or extension? > > I'm having trouble with the filename: > 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars > > It throws an error with that file name, When I change it to something like > sample.txt it runs, but the data is still garbled. Is there any reason why I > can't use the above file name? If I'm using 'rb' to read the binary file why > is it still garbled? I don't think it's garbled. It's a binary file. What do you expect? It's been over ten years since I've worked with any JSTARS stuff so I can't give you any details but you almost certainly have some sort of imagery. The military has a lot of bizarre formats and whoever sent you the data should have included a data sheet describing the format (or a pointer to such). Ideally, you'll also get a pointer to code to read the thing, but sometimes you just have to bite the bullet and write a program to process the file. (If all else fails, look at a dump of the first 512 bytes or so; often the image size is included at the beginning; maybe in ASCII, 16 bit ints, 32 bit ints, floating point -- who knows) There've been times when I had to just display the thing at 512 or 1024 bytes (or ints) per row and try to surmise the info from that. So, look for the file description. ... Googling a bit: I see there's a package at http://www.mbari.org/data/mbsystem/index.html which purports to handle some JSTARS stuff. I've no idea if that will help you. From pavpanchekha at gmail.com Mon Aug 24 18:07:54 2009 From: pavpanchekha at gmail.com (Pavel Panchekha) Date: Mon, 24 Aug 2009 15:07:54 -0700 (PDT) Subject: Distutils evil voodoo: install into a package Message-ID: <824505df-5534-423e-b72c-06d0f62b376b@p15g2000vbl.googlegroups.com> Before you flame me, I know that what I'm trying to do is beyond evil. But I nonetheless want to do it. Feel free to rant if you must. :) I have a package that I want to install into another package. For example, I have the packages pya and pyb. pya is guaranteed to be installed before pyb is, so that's not an issue. pya is installed as the module `pya`. I want to install pyb into the module `pya.pyb`. Is there any way to do this beyond figuring out what the path is and installing the entire pyb directory as data_files? From deets at nospam.web.de Mon Aug 24 18:21:05 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 00:21:05 +0200 Subject: Graph library recommendations for large graphs In-Reply-To: References: Message-ID: <7fgi2iF2juk72U1@mid.uni-berlin.de> VanL schrieb: > I am working on a project that will require building and querying large > graph objects (initially 8M nodes, 30-40M edges; eventually 40M nodes, > 100M edges). NetworkX seems to be the most popular, but I am concerned > that a dict representation for nodes would use too much memory -- my > initial tests suggest that a graph with 3M nodes and 12M edges creates > substantial memory pressure on my machine. > > Can anybody who has worked with large graphs before give a recommendation? My initial tests show otherwise. The below test-script creates 3 million nodes with 12 million adjacencies, on my 2GB Notebook. The theoretical limit for this (if we assume pointer-based adjacency-references which makes sense if we have sparse graphs as your numbers indicate) is (32 bits assumed): - 8 bytes per node (4 byte pointer to adjacency list, 4 byte int for counting the number of adjacencies in that list) - 4 bytes per adjacency This is 60.000.000 for your example - roughly 60MB. On my machine, the process has 320.000.000MB - (roughly) a factor five. Given the much richer properties a Python-object (and python-lists) have thas is pretty good I'd say. So for your eventual size of 40M nodes, 100M edges, we have a theoretical amount of 560MB, times 5 makes 2.5 GB. Not exactly a low memory profile, but manageable on modern hardware. I don't know anything about NetworkX - it still might be the better solution, given the underlying C-based algorithms. But if all you need is to represent a graph of that size, it appears to be working. ---- test.py ---- import random import gc import time class Node(object): __slots__ = ["adjacencies", "value", "id"] def __init__(self, id): id = id value = random.random() self.adjacencies = [] nodes = [] gc.disable() nc = 3000000 for i in xrange(nc): nodes.append(Node(i)) if (i % 1000) == 0: print i for i in xrange(12000000): a = random.randint(0, nc - 1) b = random.randint(0, nc - 1) while a == b: b = random.randint(0, nc) nodes[a].adjacencies.append(nodes[b]) if (i % 1000) == 0: print "e", i gc.enable() while True: time.sleep(1) traversed = set() def depth_search(node, depth=0): traversed.add(node) if depth == 4: return for child in node.adjacencies: if child not in traversed: depth_search(child, depth+1) depth_search(nodes[random.randint(0, nc - 1)]) ------ Diez From deets at nospam.web.de Mon Aug 24 18:22:48 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 00:22:48 +0200 Subject: Distutils evil voodoo: install into a package In-Reply-To: <824505df-5534-423e-b72c-06d0f62b376b@p15g2000vbl.googlegroups.com> References: <824505df-5534-423e-b72c-06d0f62b376b@p15g2000vbl.googlegroups.com> Message-ID: <7fgi5oF2juk72U2@mid.uni-berlin.de> Pavel Panchekha schrieb: > Before you flame me, I know that what I'm trying to do is beyond evil. > But I nonetheless want to do it. Feel free to rant if you must. :) > > I have a package that I want to install into another package. For > example, I have the packages pya and pyb. > pya is guaranteed to be installed before pyb is, so that's not an > issue. pya is installed as the module `pya`. I want to install pyb > into the module `pya.pyb`. > > Is there any way to do this beyond figuring out what the path is and > installing the entire pyb directory as data_files? This is what whe world has created namespace-packages for. At least if you can live with the namespace "pya" being otherwise empty. Pray tell - what is your usecase? Diez From bearophileHUGS at lycos.com Mon Aug 24 18:46:25 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Mon, 24 Aug 2009 15:46:25 -0700 (PDT) Subject: Graph library recommendations for large graphs References: Message-ID: You may try the Python bindings for the Boost Graph Library, the graph you talk about may fit in 2GB of a 32 bit OS too (this is the first link I have found, it's a lot of time I don't use those graph bindings): http://banyan.usc.edu/log/c_cpp/boost-graph-library-python-bindings Bye, bearophile From james.harris.1 at googlemail.com Mon Aug 24 19:23:06 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Mon, 24 Aug 2009 16:23:06 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: On 24 Aug, 14:05, Mel wrote: > James Harris wrote: > > On 24 Aug, 02:19, Max Erickson wrote: > [ ... ] > >> >>> int('100', 3) > >> 9 > >> >>> int('100', 36) > >> 1296 > > > This is fine typed into the language directly but couldn't be entered > > by the user or read-in from or written to a file. > > That's rather beside the point. ?Literals don't essentially come from files > or user input. ?Essentially literals are a subset of expressions, just like > function calls are, and they have to be evaluated by Python to yield a > value. ?I'm not averse to 32'rst', but we already have ... > >>> int ('rst', 32) > > 28573 Sure but while I wouldn't normally want to type something as obscure as 32"rst" into a file of data I might want to type 0xff00 or similar. That is far clearer than 65280 in some cases. My point was that int('ff00', 16) is OK for the programmer but cannot be used generally as it includes a function call. James From piet at cs.uu.nl Mon Aug 24 19:26:38 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 25 Aug 2009 01:26:38 +0200 Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> <4224e772-5b67-4eea-9bdf-a7d2bf7cc128@c14g2000yqm.googlegroups.com> Message-ID: >>>>> sturlamolden (s) wrote: >s> On 24 Aug, 13:21, Piet van Oostrum wrote: >>> But os.fork() is not available on Windows. And I guess refcounts et al. >>> will soon destroy the sharing. >s> Well, there is os.fork in Cygwin and SUA (SUA is the Unix subsytem in >s> Windows Vista Professional). Cygwin's fork is a bit sluggish. That's because it doesn't use copy-on-write. Thereby losing most of its advantages. I don't know SUA, but I have vaguely heard about it. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From istvan.albert at gmail.com Mon Aug 24 19:54:43 2009 From: istvan.albert at gmail.com (Istvan Albert) Date: Mon, 24 Aug 2009 16:54:43 -0700 (PDT) Subject: Graph library recommendations for large graphs References: Message-ID: <1ea9e905-e758-4c83-917b-862b63fdc8fb@p36g2000vbn.googlegroups.com> On Aug 24, 5:37?pm, VanL wrote: > > Can anybody who has worked with large graphs before give a recommendation? > when using large graphs another limitation may come from the various graph algorithm run times. Most likely you will need to squeeze out as much as possible and a python implementation has a lot of overhead. I've used the LEDA graph library with great success. This is a C++ library with substantial syntax sugar that looks a bit like python (and I made some python bindings for it via SWIG and thus got the best of both worlds, lost the code I'm afraid). http://www.algorithmic-solutions.info/leda_guide/Graphs.html i. From davea at ieee.org Mon Aug 24 20:09:10 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 24 Aug 2009 20:09:10 -0400 Subject: Temat:, Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> <4ec18c68-b8b5-401e-b910-802b7662dced@i18g2000pro.googlegroups.com> <321b8396-0806-4a1a-9a32-efbb147e6b4b@c2g2000yqi.googlegroups.com> Message-ID: <4A932BA6.3090801@ieee.org> You shouldn't want either a colon or a pipe symbol in the filename string (not counting the drive letter prefix). A single colon gives you surprising behavior, and two will give you Invalid Argument. See inline responses. ryniek wrote: > On 24 Sie, 22:34, ryniek wrote: > >>> >>> >> Ok, but how to get rid of those colons? >> Is it necessary? >> > > I dealt with it. Had to change 'w:bz2' into 'w|bz2'. > > Looks to me like you're putting a pipe in again (unless that's just an artifact of the mail system) > But now have another problem: > " > C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje > \Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba > ckuper.py -f E:\APLIKACJE\nowegg.exe E:\ MyGG > Checking permissions for reading and writing... > Traceback (most recent call last): > File "backuper.py", line 194, in > main_meth() > File "backuper.py", line 186, in main_meth > paq.backup_file(pars.options.filename[0], pars.options.filename > [1], pars.options.filename[2]) > File "backuper.py", line 114, in backup_file > backup_obj =arfile.open(dest, 'w|bz2') > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib > \tarfile.py", line 1675, in open > _Stream(name, filemode, comptype, fileobj, bufsize), > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib > \tarfile.py", line 400, in __init__ > fileobj =LowLevelFile(name, mode) > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib > \tarfile.py", line 373, in __init__ > self.fd =s.open(name, mode) > OSError: [Errno 22] Invalid argument: 'E:\\MyGG(2009-08-24 > 23:18:25).tar.bz2' > " > > Still have two erroneous colons in that string. The one after the E is okay. > When i type path with foreward slashes, Python converts them to double > backslashes :P > " > C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje > \Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python backuper.py -f E:/ > APLIKACJE/nowegg.exe E:/ MyGG > Checking permissions for reading and writing... > Traceback (most recent call last): > File "backuper.py", line 194, in > main_meth() > File "backuper.py", line 186, in main_meth > paq.backup_file(pars.options.filename[0], pars.options.filename > [1], pars.options.filename[2]) > File "backuper.py", line 114, in backup_file > backup_obj =arfile.open(dest, 'w|bz2') > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib > \tarfile.py", line 1675, in open > _Stream(name, filemode, comptype, fileobj, bufsize), > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib > \tarfile.py", line 400, in __init__ > fileobj =LowLevelFile(name, mode) > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib > \tarfile.py", line 373, in __init__ > self.fd =s.open(name, mode) > OSError: [Errno 22] Invalid argument: 'E:\\MyGG(2009-08-24 > 23:20:19).tar.bz2' > " > > I tried raw string also, but nothing helps. :-/ > > If a string has a backslash in it, and it is printed, you see a single backslash. But if it is output with repr(), then you see it doubled, just as you would do if you were typing it in as a literal. That does NOT mean that it has a double backslash, it just means that particular display formatting shows you that. Try the following to see what I mean: >>> st = r"e:\testing\again.txt" >>> st 'e:\\testing\\again.txt' >>> print st e:\testing\again.txt >>> print [st, st] ['e:\\testing\\again.txt', 'e:\\testing\\again.txt'] >>> Since you don't know how a particular error message was constructed, you don't know for sure which way to interpret the results. That comes with practice. In the meantime, if you print a simple string with simple print, you should be able to see it fine. Incidentally, in nearly every case, Windows ignores extra backslashes. So that's not likely to be your problem. Get rid of those colons, without replacing them with pipes. DaveA From sturlamolden at yahoo.no Mon Aug 24 20:16:33 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 17:16:33 -0700 (PDT) Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> <4224e772-5b67-4eea-9bdf-a7d2bf7cc128@c14g2000yqm.googlegroups.com> Message-ID: <864e2d5f-0855-4f35-a78c-b09054e75f0d@w41g2000yqb.googlegroups.com> On 25 Aug, 01:26, Piet van Oostrum wrote: > That's because it doesn't use copy-on-write. Thereby losing most of its > advantages. I don't know SUA, but I have vaguely heard about it. SUA is a version of UNIX hidden inside Windows Vista and Windows 7 (except in Home and Home Premium), but very few seem to know of it. SUA (Subsystem for Unix based Applications) is formerly known as Interix, which is a certified version of UNIX based on OpenBSD. If you go to http://www.interopsystems.com (a website run by Interop Systems Inc., a company owned by Microsoft), you will find a lot of common unix tools prebuilt for SUA, including Python 2.6.2. The NT-kernel supports copy-on-write fork with a special system call (ZwCreateProcess in ntdll.dll), which is what SUA's implementation of fork() uses. From steve at REMOVE-THIS-cybersource.com.au Mon Aug 24 20:25:39 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Aug 2009 00:25:39 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: <02a31f91$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 16:23:06 -0700, James Harris wrote: > Sure but while I wouldn't normally want to type something as obscure as > 32"rst" into a file of data I might want to type 0xff00 or similar. That > is far clearer than 65280 in some cases. > > My point was that int('ff00', 16) is OK for the programmer but cannot be > used generally as it includes a function call. No, it's the other way around. If you have *data*, whether entered at run time by the user or read from a file, you can easily pass it to a function to convert to an int. (In fact you have to do this anyway, because the data will be a string and you need an int.) If you want your data file to have values entered in hex, or oct, or even unary (1=one, 11=two, 111=three, 1111=four...) you can. There's no need to have the user enter int('ff00', 16) to get hex, just have them enter ff00. But when writing *code*, you want syntax which will accept integers in the most common bases (decimal, a distant second hex, an even more distant third octal, and way out on the horizon binary) without the runtime cost of a function call. -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Aug 24 20:37:36 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Aug 2009 00:37:36 GMT Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> <02a2b7f1$0$20629$c3e8da3@news.astraweb.com> Message-ID: <02a3225f$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 12:40:24 -0500, Derek Martin wrote: > On Mon, Aug 24, 2009 at 05:03:28PM +0000, Steven D'Aprano wrote: >> On Mon, 24 Aug 2009 11:21:46 -0500, Derek Martin wrote: >> > since the old syntax is prevalent both within and without the Python >> > community, making the change is, was, and always will be a bad idea. >> >> Octal syntax isn't prevalent *at all*, except in a small number of >> niche areas. > > Steven, don't be obtuse. Where octal is used in programming, the > leading zero is prevalent. Now who is being obtuse? If you take *any* feature at all, no matter how rare, you can say "Where it is used, it is prevalent". Among people who program in Whitespace, all three of them, the use of spaces and tabs as significant programming tokens is prevalent. This whole argument is over whether or not a "feature" desired by a tiny proportion of the programming community -- the intersection of those who use octal frequently enough that using an extra 'o' is a hardship, and those who use C-based languages -- should hold *everyone else* hostage to their badly thought out notation. [...] > Why is it so hard for you to accept that intelligent people can disagree > with you, and that what's right for you might be bad for others? I can accept that intelligent people can disagree with me. I even sympathise with you, that you're one of the minority who don't find octal archaic and unnecessary, and you'll need to learn a new syntax for octal literals in Python 3.x. But your argument is fundamentally "but we've always done it this way, and other languages do it, so why should we change?". We should change because the desire to prevent silent errors caused by (e.g.) 012 being interpreted as 10, and the desire to be consistent with both mathematical notation and floating point syntax outweighs the need to be backward compatible. This change was not a spur of the moment thing, it went through the entire PEP process with due concern for backward compatibility, which Python does *not* change without good reason. You lost, get over it. I'm sorry that you personally find this change a hardship, but HTFU. If and when you move to Python 3.x, you'll get used to it. If you can get used to putting braces around code blocks in C and braces around dicts in Python, you're more than capable of getting used to writing 012 in C and 0o12 in Python. -- Steven From greg at cosc.canterbury.ac.nz Mon Aug 24 20:54:13 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 25 Aug 2009 12:54:13 +1200 Subject: Literal concatenation, strings vs. numbers In-Reply-To: <871vn2gcai.fsf_-_@benfinney.id.au> References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> <7fe9mbF2l83bmU1@mid.individual.net> <871vn2gcai.fsf_-_@benfinney.id.au> Message-ID: <7fgr0nF2l3st0U1@mid.individual.net> Ben Finney wrote: > So, different representations of literals are parsed as separate > literals, then concatenated. To have the behaviour you describe, the > case needs to be made separately that digit concatenation should not be > consistent with the established string literal parsing behaviour. I think it's a pretty easy case to make, since there is no obvious way of "concatenating" numbers written in different bases. So if it's to be allowed at all, it pretty much has to be restricted to a single base. However, I'd be just as happy with underscores. I don't see how there could be any great difficulty with implementing that -- it only affects the scanner. -- Greg From mensanator at aol.com Mon Aug 24 21:01:38 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 24 Aug 2009 18:01:38 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> Message-ID: <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> On Aug 24, 7:25?pm, Steven D'Aprano wrote: > On Mon, 24 Aug 2009 16:23:06 -0700, James Harris wrote: > > Sure but while I wouldn't normally want to type something as obscure as > > 32"rst" into a file of data I might want to type 0xff00 or similar. That > > is far clearer than 65280 in some cases. > > > My point was that int('ff00', 16) is OK for the programmer but cannot be > > used generally as it includes a function call. > > No, it's the other way around. If you have *data*, whether entered at run > time by the user or read from a file, you can easily pass it to a > function to convert to an int. (In fact you have to do this anyway, > because the data will be a string and you need an int.) > > If you want your data file to have values entered in hex, or oct, or even > unary (1=one, 11=two, 111=three, 1111=four...) you can. Unary? I think you'll find that Standard Positional Number Systems are not defined for radix 1. > There's no need > to have the user enter int('ff00', 16) to get hex, just have them enter > ff00. > > But when writing *code*, you want syntax which will accept integers in > the most common bases (decimal, a distant second hex, an even more > distant third octal, and way out on the horizon binary) without the > runtime cost of a function call. > > -- > Steven From mwilson at the-wire.com Mon Aug 24 21:21:32 2009 From: mwilson at the-wire.com (Mel) Date: Mon, 24 Aug 2009 21:21:32 -0400 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> Message-ID: Mensanator wrote: [ ... ] >> If you want your data file to have values entered in hex, or oct, or even >> unary (1=one, 11=two, 111=three, 1111=four...) you can. > > Unary? I think you'll find that Standard Positional Number > Systems are not defined for radix 1. It has to be tweaked. If the only digit you have is 0 then your numbers take the form 0*1 + 0*1**2 + 0*1**3 ... and every number has an infinitely long representation. If you cheat and take a 1 digit instead then it becomes workable. Mel. From pydecker at gmail.com Mon Aug 24 21:51:42 2009 From: pydecker at gmail.com (Peter Decker) Date: Mon, 24 Aug 2009 21:51:42 -0400 Subject: Python for professsional Windows GUI apps? In-Reply-To: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> Message-ID: On Mon, Aug 24, 2009 at 11:49 AM, Stephen Hansen wrote: > P.S. I have no idea why I'm pumping Dabo so much in this though I've never > used it! I've used in fairly regularly for about 2 years now. I haven't had to write that ugly wxPython code for so long that every time I see examples on their mail list I wanna barf. Dabo is powerful, Pythonic, and strongly supported by its developers. Check it out at http://dabodev.com -- # p.d. From samwyse at gmail.com Mon Aug 24 21:53:00 2009 From: samwyse at gmail.com (samwyse) Date: Mon, 24 Aug 2009 18:53:00 -0700 (PDT) Subject: best way to display photos Message-ID: <96e9b045-d591-485e-b831-ba1462345df9@z31g2000yqd.googlegroups.com> I have several thousand photographs that I need to quickly classify, all by myself. After extensive searches, I have been unable to find anything to my liking, so desire to write something myself. I'm thinking about displaying a photo and waiting for keystrokes to tag it; 'i' for interior, 'e' for exterior, etc., while hitting space or enter will advance to the next photo. My big question is, what's the best way to display the photos. I've used PIL in the past, but IIRC it uses an external program. Pygame is the next obvious choice, but like PIL it requires an add-in. That leaves Tkinter. Has anyone used it to display .JPG files, perhaps with rescaling to fit my screen? How is its performance? Is there any other possibilities that I've missed? Thanks. From http Mon Aug 24 22:01:49 2009 From: http (Paul Rubin) Date: 24 Aug 2009 19:01:49 -0700 Subject: best way to display photos References: <96e9b045-d591-485e-b831-ba1462345df9@z31g2000yqd.googlegroups.com> Message-ID: <7x3a7gmz1u.fsf@ruckus.brouhaha.com> samwyse writes: > My big question is, what's the > best way to display the photos. I've used PIL in the past, but IIRC > it uses an external program. Pygame is the next obvious choice, but > like PIL it requires an add-in. That leaves Tkinter. Has anyone used > it to display .JPG files, perhaps with rescaling to fit my screen? I've displayed images with tkinter -- I remember there is some kind of trick you have to do to prevent them from being gc'd prematurely but I've forgotten the specifics. However, for the kind of thing you're doing, a one-off app that you don't have to impress anyone with by making it slick, the simplest thing to do is just slam together an HTML page and view it with a browser, with an entry field next to each picture, and a "submit" button. Then run a near-trivial http server that collects the form submissions and saves them to a file. From sturlamolden at yahoo.no Mon Aug 24 22:26:40 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 19:26:40 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> Message-ID: <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> On 25 Aug, 03:51, Peter Decker wrote: > I've used in fairly regularly for about 2 years now. I haven't had to > write that ugly wxPython code for so long that every time I see > examples on their mail list I wanna barf. I prefer wxFormBuilder. GUIs should be designed visually whenever possible. From afriere at yahoo.co.uk Mon Aug 24 22:29:24 2009 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 24 Aug 2009 19:29:24 -0700 (PDT) Subject: Web Services examples using "raw" xml? References: Message-ID: <115acae5-b3cb-4879-b464-80301d817018@p36g2000prn.googlegroups.com> On Aug 25, 5:41?am, John Gordon wrote: > > ? File "/usr/lib/python2.3/site-packages/suds/client.py", line 59 > ? ? @classmethod > ? ? ^ > SyntaxError: invalid syntax > If memory serves me correctly, decorators were introduced in python2.4. That would account for your SyntaxError. From rodrigodocarmo at gmail.com Mon Aug 24 22:29:57 2009 From: rodrigodocarmo at gmail.com (Rodrigo do Carmo) Date: Mon, 24 Aug 2009 23:29:57 -0300 Subject: Any Softphone wrote in Python? Message-ID: Hi python-community, I would like to ask you if someone know any open source softphone wrote entirely in Python. The thing is that I want to write a honeyphone but starting from a softphone. Sorry if you think that I haven't "googled" enough. Regards, Rodrigo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mbezovnik at freenet.si Mon Aug 24 22:30:52 2009 From: mbezovnik at freenet.si (Matjaz Bezovnik) Date: Tue, 25 Aug 2009 04:30:52 +0200 Subject: Putting together a larger matrix from smaller matrices Message-ID: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> Dear all, I'm but a layman so do not take offence at this maybe over simple question. This is something which is done often in FEM methods, and the alike. I have matrix A of 3x3 elements, and B, of the same number of elements, 3x3. What would be the most obvious way to assemble a matrix which: a11 a12 a13 a21 a22 a23 a31 a32 a33+b11 b12 b13 b21 b22 b23 b31 b32 b33 (the missing elements = zero) (you see the pattern - if there was a third matrix C, it would "connect" to b33 on the main diagonal) Matjaz From bbxx789_05ss at yahoo.com Mon Aug 24 22:42:36 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 24 Aug 2009 19:42:36 -0700 (PDT) Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> Message-ID: On Aug 24, 2:41?pm, "Martin v. L?wis" wrote: > > I can't figure out a way to programatically set the encoding for > > sys.stdout. ?So where does that leave me? > > You should be setting the terminal encoding administratively, not > programmatically. > The terminal encoding has always been utf-8. It was not set programmatically. It seems to me that python 3.1's string handling is broken. Apparently, in python 3.1 I am unable to explicitly set the encoding of a string and print() it out with the result being human readable text. On the other hand, if I let python do the encoding implicitly, python uses a codec I don't want it to. From rylesny at gmail.com Mon Aug 24 22:48:20 2009 From: rylesny at gmail.com (ryles) Date: Mon, 24 Aug 2009 19:48:20 -0700 (PDT) Subject: Protecting against callbacks queuing up? References: <4a91db65$0$305$14726298@news.sunsite.dk> Message-ID: <18241686-02a5-4433-bd45-ba280d5705a1@r33g2000vbp.googlegroups.com> On Aug 23, 8:14?pm, Esben von Buchwald wrote: > I thought that this code would do the trick, but it obviously doesn't > help at all, and i can't understand why... > > ? ? ?def doCallback(self): > ? ? ? ? ?if self.process_busy==False: > ? ? ? ? ? ? ?self.process_busy=True > ? ? ? ? ? ? ?self.data_callback() > ? ? ? ? ? ? ?self.process_busy=False > > doCallback is defined as a callback function for the accelerometer > instance, and data_callback does some calculations and show them on the > display of the phone. > > What to do? Thanks... As Dennis pointed out, it sounds like doCallback() is called serially. That is, you can think of doCallback() as being called in a loop, rather than entered multiple times simultaneously. Your 'busy' flag is never actually checked until after it has already been reset to False. If the data accessed by the callback as a unique copy and has a timestamp then a simple approach which avoids multithreading would be to have your callback ensure that any 'old' data is simply ignored. This will allow it to quickly catch up to a 'new' event. From r1chardj0n3s at gmail.com Mon Aug 24 23:20:19 2009 From: r1chardj0n3s at gmail.com (Richard Jones) Date: Tue, 25 Aug 2009 13:20:19 +1000 Subject: Next week: the 9th PyWeek game programming challenge! Message-ID: The ninth PyWeek challenge starts this weekend, running between Sunday 30th August to Sunday 6th September (00:00UTC to 00:00UTC) The PyWeek challenge invites entrants to write a game in one week from scratch either as an individual or in a team. Entries must be developed in Python, during the challenge, and must incorporate some theme chosen at the start of the challenge. REGISTRATION IS NOW OPEN -- Visit the challenge website to sign up, join discussions in the message board or read the timetable and rules: http://www.pyweek.org/9/ PLANNING FOR THE CHALLENGE -- Make sure you have working versions of the libraries you're going to use. The rules page has a list of libraries and other resources. Make sure you can build packages to submit as your final submission (if you're going to use py2exe, make sure you know how to use it and that it works). If you don't have access to Linux, Windows or a Mac to test on, contact friends, family or other competitors to find someone who is able to test for you. From max at alcyone.com Mon Aug 24 23:20:21 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 20:20:21 -0700 Subject: Annoying octal notation In-Reply-To: <02a2b43f$0$20629$c3e8da3@news.astraweb.com> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <20090824135648.GA20434@dragontoe.org> <02a2b43f$0$20629$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Mon, 24 Aug 2009 09:14:25 -0500, Derek Martin wrote: > >> Assuming I'm right about that, then the use of a leading 0 to represent >> octal actually predates the prevalence of using 0 in dates by almost two >> decades. And while using leading zeros in other contexts is "familiar" >> to me, I would certainly not consider it "common" by any means. Thus I >> think it's fair to say that when this syntax was selected, it was a >> rather good choice. > > Except of course to anyone familiar with mathematics in the last, oh, > five hundred years or so. Mathematics has used a positional system for > numbers for centuries now: leading zeroes have been insignificant, just > like trailing zeroes after the decimal point: > > 9 = 09 = 009 = 9.0 = 9.00 = 0009.000 etc. Trailing zeroes are quite important when you're indicating the significance of a figure. 9 is not the same as 9.0 or 9.000. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis If the sky should fall, hold up your hands. -- (a Spanish proverb) From max at alcyone.com Mon Aug 24 23:23:34 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 20:23:34 -0700 Subject: Temat:,Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> <4ec18c68-b8b5-401e-b910-802b7662dced@i18g2000pro.googlegroups.com> <321b8396-0806-4a1a-9a32-efbb147e6b4b@c2g2000yqi.googlegroups.com> Message-ID: ryniek wrote: > On 24 Sie, 22:34, ryniek wrote: >> On 24 Sie, 16:56, John Machin wrote: >> >>> On Aug 25, 12:46 am, Tim Golden wrote: >>>> Dave Angel wrote: >>>>> You still haven't gotten rid of those illegal colons in the filename. >>>>> They're not legal in Windows, as has been pointed out a couple of times >>>>> in this thread. >>>> Ummm.. Colons are of course legal in Windows filenames as designating >>> That is the most inappropriate "of course" I've seen for quite a >>> while. >>>> the Alternate Data Streams: >>> OK, so s/illegal/evil/ >> Ok, but how to get rid of those colons? >> Is it necessary? > > I dealt with it. Had to change 'w:bz2' into 'w|bz2'. > > But now have another problem: It's the same problem, asked and answered. Why not read the replies of the people telling you what the problem is? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis If the sky should fall, hold up your hands. -- (a Spanish proverb) From apt.shansen at gmail.com Mon Aug 24 23:37:11 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Mon, 24 Aug 2009 20:37:11 -0700 Subject: print() and unicode strings (python 3.1) In-Reply-To: References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> Message-ID: <7a9c25c20908242037n41dde072h7eec82c78cd8f864@mail.gmail.com> > > > You should be setting the terminal encoding administratively, not > > programmatically. > > > > The terminal encoding has always been utf-8. It was not set > programmatically. > > It seems to me that python 3.1's string handling is broken. > Apparently, in python 3.1 I am unable to explicitly set the encoding > of a string and print() it out with the result being human readable > text. On the other hand, if I let python do the encoding implicitly, > python uses a codec I don't want it to. This isn't Python's string handling-- its the streams. The string handling is behaving precisely as it should, and you can explicitly set the encoding of any string to anything you want (as long as the data can translate). sys.stdout is a text stream: so has an explicit encoding. You can set your string to any encoding, but if you try to pass it through a text-stream which has an incompatible encoding, of course it will error out. That's the correct behavior. The problem seems to be that Python appears to be auto-detecting an encoding for your terminal (and assigning it to sys.stdout) that you think is incorrect; and it appears that this detection routine has changed (though I don't know if its the routine itself or sys.stdout being a "byte string" based object in 2.6 and a "unicode string" based object in 3.x that has caused this difference in behavior-- this is probably the case, really). How are you 'setting' your terminal encoding? Is your LC_CTYPE environment variable set to "en_US.UTF-8"? That's how Python (on nix'ses, at least, I believe) determines the encoding of the terminal and thus the sys.std(out|err) streams. If for some reason Python's detecting it wrong, the only way I know to change it would be to: import io, sys sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') HTH, --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From stephen.mc at gmail.com Mon Aug 24 23:37:19 2009 From: stephen.mc at gmail.com (Steve) Date: Mon, 24 Aug 2009 20:37:19 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: You can also use Windows Forms with IronPython http://www.ironpython.info/index.php/Contents#Windows_Forms From cmpython at gmail.com Mon Aug 24 23:37:23 2009 From: cmpython at gmail.com (Che M) Date: Mon, 24 Aug 2009 20:37:23 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: > I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), I use wxPython. No lack of controls there, and most are up to date. Which "lots" in wxWidgets are you thinking of? > I need controls for business apps like access to databases, good data > grid, Should be fine with wxPython. > printing reports (with or without barcodes), etc. Maybe ReportManager? (haven't used) or other options. -cm From pydecker at gmail.com Mon Aug 24 23:56:23 2009 From: pydecker at gmail.com (Peter Decker) Date: Mon, 24 Aug 2009 23:56:23 -0400 Subject: Python for professsional Windows GUI apps? In-Reply-To: <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: On Mon, Aug 24, 2009 at 10:26 PM, sturlamolden wrote: > On 25 Aug, 03:51, Peter Decker wrote: > >> I've used in fairly regularly for about 2 years now. I haven't had to >> write that ugly wxPython code for so long that every time I see >> examples on their mail list I wanna barf. > > I prefer wxFormBuilder. GUIs should be designed visually whenever > possible. I use the Dabo Class Designer to visually design my forms. So what's you're point? :) -- # p.d. From timr at probo.com Tue Aug 25 00:02:05 2009 From: timr at probo.com (Tim Roberts) Date: Mon, 24 Aug 2009 21:02:05 -0700 Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile References: Message-ID: Ryniek90 wrote: > >Sorry, but i don't know where those pipes came from : P > >The proper path is "C:\\Users\\Ryniek's >WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2" >and that string literal is "\U", without any pipes :) > >The truth is that script works on linux (ubuntu) but not on windows >(neither Win7 nor WinXP). Right, and it' not going to work as long as you have a colon (:) in the file name. Colons are not valid in a Windows file name. Colons are used to separate the drive letter and the "stream" name. It's just that simple. >Maybe it's good idea to use raw string for specifing those paths? Doesn't matter. Get rid of the colons, and your file name will work. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dmw at coder.cl Tue Aug 25 00:03:55 2009 From: dmw at coder.cl (Daniel Molina Wegener) Date: Tue, 25 Aug 2009 00:03:55 -0400 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module References: <2571343.k9db9GJWqV@coder.cl> <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> <2665032.o6QR52tnKS@coder.cl> <4a928ed7$0$32666$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1685404.FXBiJzzPRc@coder.cl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Stefan Behnel on Monday 24 August 2009 09:00 wrote in comp.lang.python: > Daniel Molina Wegener wrote: >> unicode objects are encoded into the >> encoding that the XML document encoding has, and as you say, the whole >> XML document has one encoding. There is no mixing of byte encoded strings >> with different encodings in the outout document. > > Ok, that's what I hoped anyway. It just wasn't clear from your > description. > > >> When the object is restored, by using pyxser.unserialize: >> >> pyobj = pyxser.unserialize(obj = xmldocstr, enc = "utf-8") > > But this is XML, right? What do you need to pass the encoding for at this > point? The user may want a different encoding, other than utf-8, it can be any encoding supported by libxml2. > > >> Another issue is the fact that if you have mixed some encodings in byte >> strings objects in your object tree, such as iso-8859-1 and utf-8, and >> you try to serialize that object, pyxser will output to stdout the >> serialization errors by trying to handle those mixed encodings which are >> not regarding the document encoding. > > There shouldn't be any serialisation errors (unless you try to recode byte > strings on the way out, which is a no-no for arbitrary user input). All > you have to do is properly escape the byte string so that it passes the > XML encoding step. Yup, but if the encodings are mixed inside Python byte strings, I think that there is no way to know which encoding are using them. This may cause XML serialization errors, by having a different encoding that the user have set as the document encoding. > > One trick to do that is to decode the byte string as ISO-8859-1 and > serialise the result as a normal Unicode string. Then you can re-encode > the unicode string on input back to ISO-8859-1. > > I choose ISO-8859-1 here because it has the well-defined side-effect of > mapping byte values directly to Unicode characters with an identical code > point value. So you do not risk any failures or data loss. Sure, but if there are Python byte strings (not Unicode strings), ones encoded in big5 and others in iso-8859-1 inside the object tree, the XML serialization would throw errors on the encoding conversion, by setting those bytes inside the document... > > Stefan Thanks for commenting, and sorry for the late answer. This day was busy... Best regards, - -- .O. | Daniel Molina Wegener | FreeBSD & Linux ..O | dmw [at] coder [dot] cl | Open Standards OOO | http://coder.cl/ | FOSS Developer -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (FreeBSD) iQIcBAEBCgAGBQJKk2KrAAoJEHxqfq6Y4O5N6mAQAK6a121n6ZeTl/Xm/UqlFw3S YyN0ZLY7qEgBPOz4NO3PC9DxQbo1F5/V4ZOLS86Tdc4OgRjq1dRHG2EoxzV7wQFJ yBzGTWbgyOOX1lNlnBSVLvlPooz/pBBYa0WMejUG2Sa4xDVXSXDEA5aPFy3xrYHy gj7zkWcBg3on0U+OC2l7Xdy4vIXmtTKSXMLQc01C2/yJdsNKGm2vOm8SG/gsEHo4 XYaOje3fI9WE9HUbeGrFMEnmPXpXTvodkdHY6mzRBqXws9K/ot5pz03R94boALKz MAgc/eZbPTkxViy8N98G0d4aXutNWy3cEr4B9kk6c5ZjIhmGzpSers/MrqJS+LiY t8O8d/1sT6uHQKKYOoFWCojagsDG3HFXClQyvNlqoZyj9IdN2fHNrrjmgCyeNdr3 njJNhfu7IVuZTtjwHQWscG2TVgh5slsTjEpzB/LR3V4Kt+x6Ptiy636LF7L4dqmm 7lL9dXhWRnZK7W8FzzzZDnk0qtJdsYRXsXdZ8opOqQwTnx47+HdwFClp88vbpASH YvNVn76m/Jx37WfXUXVoPDVuiQHsWDPNn3anZ60d6pDOCK9x7A065f7OCtyjq12k 2sDR1RUMBbJ0u11m7+JxIqTdcut/cJS7piiSE95vqviob4jKOQgF9y5i5eUget60 uWmCsGjI65Naxq+BWFrb =BJOF -----END PGP SIGNATURE----- From nad at acm.org Tue Aug 25 00:09:53 2009 From: nad at acm.org (Ned Deily) Date: Mon, 24 Aug 2009 21:09:53 -0700 Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> Message-ID: In article , 7stud wrote: > On Aug 24, 2:41?pm, "Martin v. L?wis" wrote: > > > I can't figure out a way to programatically set the encoding for > > > sys.stdout. ?So where does that leave me? > > > > You should be setting the terminal encoding administratively, not > > programmatically. > > > > The terminal encoding has always been utf-8. It was not set > programmatically. > > It seems to me that python 3.1's string handling is broken. > Apparently, in python 3.1 I am unable to explicitly set the encoding > of a string and print() it out with the result being human readable > text. On the other hand, if I let python do the encoding implicitly, > python uses a codec I don't want it to. If you are running on a Unix-y system, check your locale settings (LANG, LC.*, et al). I think you'll likely find that your locale is really not UTF-8. The following was on Python 3.1 on OS X 10.5, similar results on Debian Linux: $ cat t3.py import sys print(sys.stdout.encoding) s = "?" print(s.encode("utf-8")) print(s) $ export LANG=en_US.UTF-8 $ python3.1 t3.py UTF-8 b'\xe2\x82\xac' ? $ export LANG=C $ python3.1 t3.py US-ASCII b'\xe2\x82\xac' Traceback (most recent call last): File "t3.py", line 7, in print(s) UnicodeEncodeError: 'ascii' codec can't encode character '\u20ac' in position 0: ordinal not in range(128) -- Ned Deily, nad at acm.org From bbxx789_05ss at yahoo.com Tue Aug 25 00:14:44 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 24 Aug 2009 21:14:44 -0700 (PDT) Subject: best way to display photos References: <96e9b045-d591-485e-b831-ba1462345df9@z31g2000yqd.googlegroups.com> <7x3a7gmz1u.fsf@ruckus.brouhaha.com> Message-ID: <3c6c5a60-c969-4db8-8787-fb01a174249d@p10g2000prm.googlegroups.com> On Aug 24, 8:01?pm, Paul Rubin wrote: > samwyse writes: > > My big question is, what's the > > best way to display the photos. ?I've used PIL in the past, but IIRC > > it uses an external program. ?Pygame is the next obvious choice, but > > like PIL it requires an add-in. ?That leaves Tkinter. ?Has anyone used > > it to display .JPG files, perhaps with rescaling to fit my screen? > > I've displayed images with tkinter -- I remember there is some kind of > trick you have to do to prevent them from being gc'd prematurely but > I've forgotten the specifics. ? > You store the images in a list or dictionary. From gallium.arsenide at gmail.com Tue Aug 25 00:34:57 2009 From: gallium.arsenide at gmail.com (John Yeung) Date: Mon, 24 Aug 2009 21:34:57 -0700 (PDT) Subject: csv module and None values References: Message-ID: <54b4b6f9-38d5-4a8e-8ec2-fbca4a0fe1f4@r27g2000vbn.googlegroups.com> On Aug 24, 1:30?pm, JKPeck wrote: > I'm trying to get the csv module (Python 2.6) to write data > records like Excel. ?The excel dialect isn't doing it. ?The > problem is in writing None values. ?I want them to result > in just sequential commas - ,, but csv treats None specially, > as the doc says, > > "To make it as easy as possible to interface with modules > which implement the DB API, the value None is written as > the empty string." > > I need strings to be quoted but not None values. ?Is there > any way to get around this special None treatment? If you need all nonempty strings to be quoted unconditionally, then you are not writing CSV records the way Excel writes CSV records. The csv module is surprisingly good at behaving like Excel, and by default writes strings with quotes only when needed (that is, when the string itself contains commas, quotes, or newlines). If you truly want Excel-style CSVs, just let the csv module do its thing, as pointed out by Peter Otten. >From the sounds of it, you have specified QUOTE_NONNUMERIC or perhaps QUOTE_ALL as the quoting property of the dialect you are using. If so, and if this is really what you need except for *your* special None treatment, then using a sentinel is in my opinion as good a way as any to achieve that. John From wuwei23 at gmail.com Tue Aug 25 00:40:42 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 24 Aug 2009 21:40:42 -0700 (PDT) Subject: Simple IRC library References: <752884c5-c6fb-4974-a21a-bf3017fa4145@y4g2000prf.googlegroups.com> Message-ID: devaru wrote: > I am new to Python language. I want to capture(either in database or a > file) the conversation in IRC. > Please suggest me some simple IRC library or code snippet for this. I recommend the circuits[1] library, which contains a sample irc bot [2]. You'll want to override the message method to do something with the data captured. #!/usr/bin/env python from circuits import Component, Debugger from circuits.net.sockets import TCPClient, Connect from circuits.net.protocols.irc import IRC, Message, User, Nick class Bot(Component): def __init__(self, host, port=6667, channel=None): super(Bot, self).__init__(channel=channel) self += TCPClient(channel=channel) + IRC(channel=channel) self.push(Connect(host, port), "connect") def connected(self, host, port): self.push(User("test", host, host, "Test Bot"), "USER") self.push(Nick("test"), "NICK") def numeric(self, source, target, numeric, args, message): if numeric == 433: self.push(Nick("%s_" % self("getNick")), "NICK") def message(self, source, target, message): self.push(Message(source[0], message), "PRIVMSG") bot = Bot("irc.freenode.net", channel="bot") + Debugger() bot.run() [1]: http://pypi.python.org/pypi/circuits [2]: http://trac.softcircuit.com.au/circuits/browser/examples/ircbot.py From gallium.arsenide at gmail.com Tue Aug 25 00:43:57 2009 From: gallium.arsenide at gmail.com (John Yeung) Date: Mon, 24 Aug 2009 21:43:57 -0700 (PDT) Subject: csv module and None values References: Message-ID: <23c02daf-dc5a-4676-8d73-9dc63791825f@o36g2000vbl.googlegroups.com> On Aug 24, 5:00?pm, Peter Otten <__pete... at web.de> wrote: > If I understand you correctly the csv.writer already does > what you want: > > >>> w.writerow([1,None,2]) > 1,,2 > > just sequential commas, but that is the special treatment. > Without it the None value would be converted to a string > and the line would look like this one: > > 1,None,2 No, I think he means he is getting >>> w.writerow([1,None,2]) 1,"",2 He evidently wants to quote "all" strings, but doesn't want None to be considered a string. John From denis.bilenko at gmail.com Tue Aug 25 00:51:52 2009 From: denis.bilenko at gmail.com (Denis) Date: Mon, 24 Aug 2009 21:51:52 -0700 (PDT) Subject: Most "active" coroutine library project? References: <64183b73-9cb0-4ce1-98d0-f47e13a818e4@f37g2000yqn.googlegroups.com> Message-ID: You can also at gevent http://pypi.python.org/pypi/gevent On Aug 23, 10:02?pm, Phillip B Oldham wrote: > I've been taking a look at the multitude of coroutine libraries > available for Python, but from the looks of the projects they all seem > to be rather "quiet". I'd like to pick one up to use on a current > project but can't deduce which is the most popular/has the largest > community. > > Libraries I looked at include: cogen, weightless, eventlet and > circuits (which isn't exactly coroutine-based but it's event-driven > model was intriguing). > > Firstly, are there any others I've missed? And what would the > consensus be on the which has the most active community behind it? From stefan_ml at behnel.de Tue Aug 25 00:54:28 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 25 Aug 2009 06:54:28 +0200 Subject: Web Services examples using "raw" xml? In-Reply-To: References: Message-ID: <4a936e84$0$31337$9b4e6d93@newsspool4.arcor-online.net> John Gordon wrote: > I'm developing a program that will use web services, which I have never > used before. > > There are several tutorials out there that advise you to get the WSDL > and then call a method (such as wsdl2py) that inspects the wsdl and > automagically generates the python classes and methods you need for > interacting with that web service. There are a number of tools that help in building WS clients. One is soaplib. It's pretty easy to use and was recently ported (V0.8) to the lxml XML library. I actually still use a 0.7.x, also fixed to work with Py2.3. It doesn't do any code generation. Instead, you have to write up a short code snippet that describes the WS interface. Works pretty well. > I tried WSDL.Proxy() from the SOAPpy package and eventually end up > with this error: > > xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 6 Is that while parsing the WSDL file? Have you tried pushing it through an XML parser yourself (or opening it with an XML editor) to see if it really is XML? Or does this happen while communicating with the remote side? (in which case I'd trap the wire and look at the transferred XML messages) > I tried Client() from the suds package, and got this error: > > File "/usr/lib/python2.3/site-packages/suds/client.py", line 59 > @classmethod > ^ > SyntaxError: invalid syntax That's a Py2.4-ism. You can make the code backwards compatible by replacing all @classmethod def some_function(): ... lines with def some_function(): ... some_function = classmethod(some_function) That's how I fixed up soaplib, BTW. > So I decided to take a step back and see if I could bypass all the fancy > automagic methods and just create my own SOAP xml message from scratch > and then send it to the web server. That would work, surely. Yes, that's a good way also. And it avoids an additional dependency on a convoluted SOAP library. > But I'm having a tough time finding some good examples of that, because > all the tutorials I've found just tell you to use the aforementioned > magic methods, which unfortunately don;t seem to be working for me. http://effbot.org/zone/element-soap.htm Stefan From stefan_ml at behnel.de Tue Aug 25 01:11:01 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 25 Aug 2009 07:11:01 +0200 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module In-Reply-To: <1685404.FXBiJzzPRc@coder.cl> References: <2571343.k9db9GJWqV@coder.cl> <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> <2665032.o6QR52tnKS@coder.cl> <4a928ed7$0$32666$9b4e6d93@newsspool2.arcor-online.net> <1685404.FXBiJzzPRc@coder.cl> Message-ID: <4a937266$0$31337$9b4e6d93@newsspool4.arcor-online.net> Daniel Molina Wegener wrote: > Stefan Behnel wrote: >> Daniel Molina Wegener wrote: >>> When the object is restored, by using pyxser.unserialize: >>> >>> pyobj = pyxser.unserialize(obj = xmldocstr, enc = "utf-8") >> But this is XML, right? What do you need to pass the encoding for at this >> point? > > The user may want a different encoding, other than utf-8, it can > be any encoding supported by libxml2. I really meant what I wrote: this is XML. The encoding is well defined in the XML declaration at the start of the document (and will default to UTF-8 if not provided). Passing it externally will allow users to override that, which doesn't make any sense at all. > if the encodings are mixed inside Python byte strings, I think > that there is no way to know which encoding are using them. Correct. > This may cause XML serialization errors Yes, but only if you try to recode the strings (which, as I said, is a no-no). >> One trick to do that is to decode the byte string as ISO-8859-1 and >> serialise the result as a normal Unicode string. Then you can re-encode >> the unicode string on input back to ISO-8859-1. > >> I choose ISO-8859-1 here because it has the well-defined side-effect of >> mapping byte values directly to Unicode characters with an identical code >> point value. So you do not risk any failures or data loss. > > Sure, but if there are Python byte strings (not Unicode strings), ones > encoded in big5 and others in iso-8859-1 inside the object tree, the > XML serialization would throw errors on the encoding conversion, by > setting those bytes inside the document... No, I really meant: decoding from ISO-8859-1 to Unicode, for all byte strings, regardless of their encoding (since you can't even know if they represent encoded text at all). So you get a unicode string that you can serialise to the target encoding, although it may result in character references (&#xyz;) being output. But you won't get any errors, at least. On the way in, you get a unicode string again, which you can encode to ISO-8859-1 to get the original byte string back. Stefan From sturlamolden at yahoo.no Tue Aug 25 01:22:20 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 22:22:20 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: On 25 Aug, 05:56, Peter Decker wrote: > I use the Dabo Class Designer to visually design my forms. So what's > you're point? ?:) Nothing, except lobbying for wxFormBuilder for anyone who still doesn't know of it. :) From stefan_ml at behnel.de Tue Aug 25 01:23:18 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 25 Aug 2009 07:23:18 +0200 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module In-Reply-To: <4a937266$0$31337$9b4e6d93@newsspool4.arcor-online.net> References: <2571343.k9db9GJWqV@coder.cl> <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> <2665032.o6QR52tnKS@coder.cl> <4a928ed7$0$32666$9b4e6d93@newsspool2.arcor-online.net> <1685404.FXBiJzzPRc@coder.cl> <4a937266$0$31337$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <4a937546$0$31332$9b4e6d93@newsspool4.arcor-online.net> Stefan Behnel wrote: > for all byte > strings, regardless of their encoding (since you can't even know if they > represent encoded text at all). Hmm, having written that, I guess it's actually best to encode byte strings as base64 instead. Otherwise, null bytes and other special byte values won't pass. I also think that if the user wants readable output for text strings, it's reasonable to require Unicode input instead of byte strings. Handling text in byte strings is just too error prone. Still, you may have to sanitize text input to make sure it doesn't contain special characters either. Take a look at the way lxml does it in the apihelpers.pxi source file, or read the XML spec on character content. Stefan From mensanator at aol.com Tue Aug 25 01:27:51 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 24 Aug 2009 22:27:51 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> Message-ID: <4468c5f5-435f-48aa-a259-7ab51069d1f7@24g2000yqm.googlegroups.com> On Aug 24, 8:21?pm, Mel wrote: > Mensanator wrote: > > [ ... ] > > >> If you want your data file to have values entered in hex, or oct, or even > >> unary (1=one, 11=two, 111=three, 1111=four...) you can. > > > Unary? I think you'll find that Standard Positional Number > > Systems are not defined for radix 1. > > It has to be tweaked. ?If the only digit you have is 0 then your numbers > take the form > > 0*1 + 0*1**2 + 0*1**3 ... > > and every number has an infinitely long representation. ?If you cheat and > take a 1 digit instead then it becomes workable. Not really. If your single digit is one, you still have an infinitely long representation only instead of every position being zero, every position is one. So either the only number that can be represented is 0, or the only number that can be represented is infinity. No amount of tweaking can fix this. So, to use radix 1, you have to abandon the concept of "Standard" (contains a 0) AND abandon "Positional" (infinitely long representation). It's all in TAOCP by Knuth if you want to get it straight. You can have a radix 1 number system, but is meaningless to speak of "unary" in the same context as hex, decimal, octal & binary. > > ? ? ? ? Mel. From spam at chezmarshall.freeserve.co.uk Tue Aug 25 01:44:28 2009 From: spam at chezmarshall.freeserve.co.uk (Robert Marshall) Date: Tue, 25 Aug 2009 06:44:28 +0100 Subject: your favorite debugging tool? References: <7xocq5vx64.fsf@ruckus.brouhaha.com> Message-ID: On 24 Aug 2009, Paul Rubin wrote: > Esmail writes: >> What is your favorite tool to help you debug your >> code? I've been getting along with 'print' statements >> but that is getting old and somewhat cumbersome. > > Beyond print statements, I use pdb a lot. Winpdb (www.winpdb.org) is > even better, but is kind of cumbersome to get working. And you can run it (pdb) within emacs - though I find a little roughness in working out the exact interactions keeps ending up (ie the source buffer displayed) in the wrong stack frame - afaict Robert -- La grenouille songe..dans son ch?teau d'eau Links and things http://rmstar.blogspot.com/ From mensanator at aol.com Tue Aug 25 02:01:30 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 24 Aug 2009 23:01:30 -0700 (PDT) Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <20090824135648.GA20434@dragontoe.org> <02a2b43f$0$20629$c3e8da3@news.astraweb.com> Message-ID: On Aug 24, 10:20?pm, Erik Max Francis wrote: > Steven D'Aprano wrote: > > On Mon, 24 Aug 2009 09:14:25 -0500, Derek Martin wrote: > > >> Assuming I'm right about that, then the use of a leading 0 to represent > >> octal actually predates the prevalence of using 0 in dates by almost two > >> decades. ?And while using leading zeros in other contexts is "familiar" > >> to me, I would certainly not consider it "common" by any means. ?Thus I > >> think it's fair to say that when this syntax was selected, it was a > >> rather good choice. > > > Except of course to anyone familiar with mathematics in the last, oh, > > five hundred years or so. Mathematics has used a positional system for > > numbers for centuries now: leading zeroes have been insignificant, just > > like trailing zeroes after the decimal point: > > > 9 = 09 = 009 = 9.0 = 9.00 = 0009.000 etc. > > Trailing zeroes are quite important when you're indicating the > significance of a figure. ?9 is not the same as 9.0 or 9.000. Tell me about it. Unfortunnately, Microsoft doesn't understand the difference between precision and significance. Makes my job a nightmare when I have to convert ug/kg to mg/kg. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > ? San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis > ? ?If the sky should fall, hold up your hands. > ? ? -- (a Spanish proverb)- Hide quoted text - > > - Show quoted text - From hv at tbz-pariv.de Tue Aug 25 02:40:56 2009 From: hv at tbz-pariv.de (Thomas Guettler) Date: Tue, 25 Aug 2009 08:40:56 +0200 Subject: best way to display photos In-Reply-To: <96e9b045-d591-485e-b831-ba1462345df9@z31g2000yqd.googlegroups.com> References: <96e9b045-d591-485e-b831-ba1462345df9@z31g2000yqd.googlegroups.com> Message-ID: <7fhfboF2ksfhiU1@mid.individual.net> Some years ago I had the same problem. I wrote a simple app with pygtk. You get get it from here: http://guettli.sourceforge.net/gthumpy/src/README.html The next pictures get loaded in background. Switching from one image to the next is faster then in some other apps. But somehow it is not ready for the public. I guess I am the only one who uses it. Flags are symlinks in the home directory .local/share/app/gthumpy. This means you should not move your images, otherwise the flags get lost. I don't think it will work on ms-windows, but it could be ported. Or you use mirage: http://mirageiv.berlios.de/index.html It is a pygtk image viewer. You can define shortcuts that execute user defined commands. Thomas samwyse schrieb: > I have several thousand photographs that I need to quickly classify, > all by myself. After extensive searches, I have been unable to find > anything to my liking, so desire to write something myself. I'm > thinking about displaying a photo and waiting for keystrokes to tag > it; 'i' for interior, 'e' for exterior, etc., while hitting space or > enter will advance to the next photo. My big question is, what's the > best way to display the photos. I've used PIL in the past, but IIRC > it uses an external program. Pygame is the next obvious choice, but > like PIL it requires an add-in. That leaves Tkinter. Has anyone used > it to display .JPG files, perhaps with rescaling to fit my screen? > How is its performance? Is there any other possibilities that I've > missed? Thanks. -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From sjmachin at lexicon.net Tue Aug 25 02:54:36 2009 From: sjmachin at lexicon.net (John Machin) Date: Mon, 24 Aug 2009 23:54:36 -0700 (PDT) Subject: Python 2.6 still not giving memory back to the OS... References: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> <762603ba-0a4c-4504-94d9-34a8b1e3f9c3@s15g2000yqs.googlegroups.com> <4A88406C.3060609@v.loewis.de> Message-ID: <64ac5a03-ebf2-4a78-8ada-9e2dc46c86ac@d9g2000prh.googlegroups.com> On Aug 25, 2:08?am, Chris Withers wrote: > Martin v. L?wis wrote: > > Today, there are two cases when malloc returns memory on a typical > > Unix system (in particular, in Linux malloc): > > a) if the malloc block block is small (below page size), it is allocated > > ? ?from the brk heap, where it can only be returned if the last page of > > ? ?that heap is completely free, and > > b) if the block is large (multiple pages), it gets returned to the > > ? ?system right away. > > > Case b) can only happen if the C malloc uses mmap to allocate large > > blocks. > > I believe (and John will correct me if I'm wrong) that xlrd uses mmap, > so why am I not seeing the memory being returned? xlrd uses mmap to access the input file; this seems to have zero correlation with "the C malloc uses mmap to allocate large blocks". From nadia.helen.johnson at gmail.com Tue Aug 25 03:12:57 2009 From: nadia.helen.johnson at gmail.com (Nadia Johnson) Date: Tue, 25 Aug 2009 00:12:57 -0700 (PDT) Subject: elementtree References: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> <4a923d8b$0$32664$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <2b3279b4-ed91-4d46-823a-1bf89acf33fb@j9g2000prh.googlegroups.com> On Aug 24, 7:29?pm, Dave Angel wrote: > Stefan Behnel wrote: > > Hi, > > > elsa wrote: > > >> I know how to turn HTML into an ElementTree object > > > I don't. ;) > > > ElementTree doesn't have an HTML parser, so what do you use for parsing? > > >> but I don't know > >> how to then view the structure of this object. Is there a method or > >> module that you can give an ElementTree object to, and it returns some > >> kind of graphical or printed representation of the tree? Otherwise, if > >> you can't see you're tree's structure, how do you know what is a > >> sensible way of iterating over the tree to access the info you need? > > > ElementTree has a tostring() method that returns a string. To get a pretty > > printed representation, you can use the indent() function from this recipe: > > >http://effbot.org/zone/element-lib.htm#prettyprint > > > Stefan > > Perhaps the OP was referring to XHTML, which should be eligible for > ElementTree. ?But could you tell me whether ElementTree is at all > tolerant of malformed XML? ? Most HTML and XHTML I encounter in the wild > is so ?buggy it's amazing it all works at all. > > DaveA I used elementtidy, also available from effbot From dirkmoors at gmail.com Tue Aug 25 03:54:34 2009 From: dirkmoors at gmail.com (gravityzoo-dmo) Date: Tue, 25 Aug 2009 00:54:34 -0700 (PDT) Subject: Python memory management <-> virtualized server environments References: Message-ID: <5773f2ee-5654-4f82-82c5-7668eb419f36@w41g2000yqb.googlegroups.com> On 24 aug, 20:35, "Martin P. Hellwig" wrote: > gravityzoo-dmo wrote: > > Hello everyone, > > > I was wondering if anyone here has had any experience in running > > Python in a virtualized server environment? > > The reason I'm asking is the recent thing I noticed when running my > > server application (written in Python + Twisted); > > The memory of the server application seems to only grow, and not give > > back memory space to the OS. I realize that this won't be a problem on > > a single physical server, but I'm curious of the effect this behaviour > > has on a virtualized environment. > > Could anyone provide me with a little more insight please? > > Thanks in advance! > > > Dirk > > Might help if you say which version of Python you are running, although > I'm not a memory expert I do know there have been some changes between > the versions. > > -- > MPHhttp://blog.dcuktec.com > 'If consumed, best digested with added seasoning to own preference.' Hi, I'm sorry, I forgot to post the version indeed. The Python version I'm running is 2.5.2 (r252:60911, January 4 2009) The Twisted version I'm running is 8.2.0, and I'm using the EPOLL- Reactor (don't know if that matters) The OS I'm running on is Debian version 2.6.26-2-686 (i686 GNU/Linux) Is that enough info? Best regards, Dirk From __peter__ at web.de Tue Aug 25 04:03:57 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Aug 2009 10:03:57 +0200 Subject: Putting together a larger matrix from smaller matrices References: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> Message-ID: Matjaz Bezovnik wrote: > This is something which is done often in FEM methods, and the alike. > > I have matrix A of 3x3 elements, and B, of the same number of > elements, 3x3. > > What would be the most obvious way to assemble a matrix which: > a11 a12 a13 > a21 a22 a23 > a31 a32 a33+b11 b12 b13 > b21 b22 b23 > b31 b32 b33 > > (the missing elements = zero) > > (you see the pattern - if there was a third matrix C, it would > "connect" to b33 on the main diagonal) Unless there is a dedicated function: partial = [...] # list of matrices of shape NxN N = partial[0].shape[0] width = N*len(partial) b = numpy.zeros((width, width)) off = 0 for m in partial: b[off:off+N, off:off+N] = m off += N print b Peter From martin.hellwig at dcuktec.org Tue Aug 25 04:09:06 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 25 Aug 2009 09:09:06 +0100 Subject: Python memory management <-> virtualized server environments In-Reply-To: <5773f2ee-5654-4f82-82c5-7668eb419f36@w41g2000yqb.googlegroups.com> References: <5773f2ee-5654-4f82-82c5-7668eb419f36@w41g2000yqb.googlegroups.com> Message-ID: <3oSdnePt4Mu_AQ7XnZ2dnUVZ8j9i4p2d@bt.com> gravityzoo-dmo wrote: > On 24 aug, 20:35, "Martin P. Hellwig" > wrote: >> gravityzoo-dmo wrote: >>> Hello everyone, >>> I was wondering if anyone here has had any experience in running >>> Python in a virtualized server environment? >>> The reason I'm asking is the recent thing I noticed when running my >>> server application (written in Python + Twisted); >>> The memory of the server application seems to only grow, and not give >>> back memory space to the OS. I realize that this won't be a problem on >>> a single physical server, but I'm curious of the effect this behaviour >>> has on a virtualized environment. >>> Could anyone provide me with a little more insight please? >>> Thanks in advance! >>> Dirk >> Might help if you say which version of Python you are running, although >> I'm not a memory expert I do know there have been some changes between >> the versions. >> >> -- >> MPHhttp://blog.dcuktec.com >> 'If consumed, best digested with added seasoning to own preference.' > > Hi, I'm sorry, I forgot to post the version indeed. > > The Python version I'm running is 2.5.2 (r252:60911, January 4 2009) > The Twisted version I'm running is 8.2.0, and I'm using the EPOLL- > Reactor (don't know if that matters) > The OS I'm running on is Debian version 2.6.26-2-686 (i686 GNU/Linux) > > Is that enough info? > > Best regards, > Dirk According to Python 2.6 release document: "To reduce memory usage, the garbage collector will now clear internal free lists when garbage-collecting the highest generation of objects. This may return memory to the operating system sooner." Which might apply to your situation, but to be really sure you can only try it out :-) -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From pierre.gaillard at gmail.com Tue Aug 25 04:12:51 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Tue, 25 Aug 2009 01:12:51 -0700 (PDT) Subject: matplotlib / backend Message-ID: <5c24850b-462f-4d2e-9d75-e9317c093e5e@z31g2000yqd.googlegroups.com> Hello, I'm to plot some results but it doesn't work. I got this error : /usr/local/libre_rep/python-2.6.1/RHEL_5__x86_64/lib/python2.6/site- packages/matplotlib/backends/__init__.py:41: UserWarning: Your currently selected backend, 'agg' does not support show(). Please select a GUI backend in your matplotlibrc file ('/usr/local/ libre_rep/python-2.6.1/RHEL_5__x86_64/lib/python2.6/site-packages/ matplotlib/mpldata/matplotlibrc') or with matplotlib.use() Any idea to fix it ? Thanks From james.harris.1 at googlemail.com Tue Aug 25 04:22:29 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Tue, 25 Aug 2009 01:22:29 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> Message-ID: <68540205-9970-41a2-b0b0-7b66a9865c9b@s15g2000yqs.googlegroups.com> On 25 Aug, 01:25, Steven D'Aprano wrote: > On Mon, 24 Aug 2009 16:23:06 -0700, James Harris wrote: > > Sure but while I wouldn't normally want to type something as obscure as > > 32"rst" into a file of data I might want to type 0xff00 or similar. That > > is far clearer than 65280 in some cases. > > > My point was that int('ff00', 16) is OK for the programmer but cannot be > > used generally as it includes a function call. > > No, it's the other way around. If you have *data*, whether entered at run > time by the user or read from a file, you can easily pass it to a > function to convert to an int. (In fact you have to do this anyway, > because the data will be a string and you need an int.) > > If you want your data file to have values entered in hex, or oct, or even You are looking at this the other way round from me and I'll explain why I think this is important. I'm not talking about the *programmer* prescribing how the user should enter the data but the *user* being able to choose to prepare the data in a certain format - the format which makes sense for the data being entered. Your way only works if those fields in every row have the same format. That may be the case sometimes but is not general. > unary (1=one, 11=two, 111=three, 1111=four...) you can. There's no need > to have the user enter int('ff00', 16) to get hex, just have them enter > ff00. > > But when writing *code*, you want syntax which will accept integers in > the most common bases (decimal, a distant second hex, an even more > distant third octal, and way out on the horizon binary) without the > runtime cost of a function call. Be careful! When designing a language feature don't be too ready to *tell* the users of that language what restrictions they want. Just because the designer wants features with a certain frequency does not mean that all users will have the same priorities. (If it is impossible or unreasonable to support a feature then by all means don't support it. But don't decide up-front before examining the options that something in not personally appealing.) James From hendrik at microcorp.co.za Tue Aug 25 04:28:11 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 25 Aug 2009 10:28:11 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a92b290$0$305$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a92b290$0$305$14726298@news.sunsite.dk> Message-ID: <200908251028.12047.hendrik@microcorp.co.za> On Monday 24 August 2009 17:32:23 Esben von Buchwald wrote: > Hendrik van Rooyen wrote: 8< -------------- some stuff about an "after" call -------------------------- > > I'm new to python, what is an after function and an after call? Couldn't > find excact answer on google...? Do you have a link to some docs? The after call is common in GUI stuff. Here is a link to nice Tkinter manual - it is the first link if you google for: tkinter "new mexico tech" shipman www.nmt.edu/tcc/help/pubs/tkinter/ What after does is that it is like a normal call, except that it is not done immediately, but after some settable time, hence the "after". - Hendrik From thebiggestbangtheory at gmail.com Tue Aug 25 04:36:08 2009 From: thebiggestbangtheory at gmail.com (nickname) Date: Tue, 25 Aug 2009 01:36:08 -0700 (PDT) Subject: os.popen output different from native shell output Message-ID: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Hi all, I am a relative newbie to python, I am using os.popen to run an ls command. The output that I get using the read() function is different in look and feel from when I run the ls command natively from the shell (not via python). I display the ouput via python by using the print function on the variable that accepts the os.popen ().read() function. For example: output from native shell (as seen on the bash shell) file1 file2 dir1(highlighted in blue color) file3longnamewhichwillcausenextfiletoappearonnextline file 4 output from python (as seen on the bash shell) file1 file2 dir1 (no blue color) file3longnamewhichwillcausenextfiletoappearonnextline file4 Is there an easy way to "mirror" the output. When python displays the output, how can it tell the bash shell that some of the entries are directories and they should appear blue on the bash shell, and that everything should not be appearing on 1 column only. Thanks for any pointers. From clp2 at rebertia.com Tue Aug 25 04:52:55 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 25 Aug 2009 01:52:55 -0700 Subject: os.popen output different from native shell output In-Reply-To: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Message-ID: <50697b2c0908250152y4e6a7fb8ke20f9aae28193b40@mail.gmail.com> On Tue, Aug 25, 2009 at 1:36 AM, nickname wrote: > Hi all, > ? ? ? I am a relative newbie to python, I am using os.popen to run an > ls command. The output that I get using the read() function is > different in look and feel from when I run the ls command natively > from the shell (not via python). I display the ouput via python by > using the print function on the variable that accepts the os.popen > ().read() function. > > For example: > > output from native shell (as seen on the bash shell) > > file1 file2 dir1(highlighted in blue color) > file3longnamewhichwillcausenextfiletoappearonnextline > > file 4 > > output from python (as seen on the bash shell) > > file1 > file2 > dir1 (no blue color) > file3longnamewhichwillcausenextfiletoappearonnextline > file4 > > Is there an easy way to "mirror" the output. When python displays the > output, how can it tell the bash shell that some of the entries are > directories and they should appear blue on the bash shell, and that > everything should not be appearing on 1 column only. I would assume the difference is caused by `ls` changing behavior (for example, enabling/disabling colorization) based on whether its output is going to a terminal or a pipe. Is there a reason you can't use os.listdir() instead of running ls?: http://docs.python.org/library/os.html#os.listdir For the colorization, google for "ANSI color escape sequences" Cheers, Chris -- http://blog.rebertia.com From subhakolkata1234 at gmail.com Tue Aug 25 05:08:31 2009 From: subhakolkata1234 at gmail.com (SUBHABRATA BANERJEE) Date: Tue, 25 Aug 2009 14:38:31 +0530 Subject: Questions on XML In-Reply-To: <200908231148.51151.rami.chowdhury@gmail.com> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <97c638a50908221327ge57818ahc1bb4c9ad3eb186b@mail.gmail.com> <200908231148.51151.rami.chowdhury@gmail.com> Message-ID: <97c638a50908250208n3a81007n92b7507ca8515bf2@mail.gmail.com> I was trying this. Looks perfectly fine. There must be something really wrong. If you can reinstall Python 2.5. >>> a1=raw_input("String") String?? On Mon, Aug 24, 2009 at 12:18 AM, Rami Chowdhury wrote: > My problem is with IDLE on Windows. When I try to type Bangla directly into > the IDLE window I only get '?' characters, and repr() fails with a > UnicodeDecodeError. I expect, though, that that's because of my specific > installation / Windows issues, as it works fine on Fedora 10... > > > I do not get any problem in processing Hindi or Bangla or any Indian > > language in Python it is perfectly fine. > I have no problems either -- my issues are with IDLE, and only on Windows. > > ---- > Rami Chowdhury > "Strangers are just friends who haven't had enough gin." -- Howdle's Saying > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > > On Saturday 22 August 2009 13:27:02 SUBHABRATA BANERJEE wrote: > > Should I help you? If you answered my questions I am differing from your > > view I do not get any problem in processing Hindi or Bangla or any Indian > > language in Python it is perfectly fine. > > Best Regards, > > Subhabrata. > > > > On Sat, Aug 22, 2009 at 9:48 AM, Rami Chowdhury > wrote: > > > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > > > > > >> use Python to help me in this regard? > > > > > > I can say from experience that Python on Windows (at least, Python 2.5 > on > > > 32-bit Vista) works perfectly well with UTF-8 files containing Bangla. > I > > > have had trouble with working with the data in IDLE, however, which > seems > > > to prefer ASCII by default. > > > > > > ------------- > > > Rami Chowdhury > > > "Never assume malice when stupidity will suffice." -- Hanlon's Razor > > > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > > > > > > > > > > > > > > > > > > On Aug 21, 2009, at 19:15 , joy99 wrote: > > > > > > Dear Group, > > > > > >> I like to convert some simple strings of natural language to XML. May > > >> I use Python to do this? If any one can help me, on this. > > >> > > >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > > >> use Python to help me in this regard? > > >> > > >> How can I learn good XML aspects of Python. If any one can kindly name > > >> me a book or URL. > > >> > > >> I am using Python2.6 on Windows XP with IDLE as GUI. > > >> > > >> Best Regards, > > >> Subhabrata. > > >> -- > > >> http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From baloand at googlemail.com Tue Aug 25 05:52:45 2009 From: baloand at googlemail.com (baloan) Date: Tue, 25 Aug 2009 02:52:45 -0700 (PDT) Subject: matplotlib / backend References: <5c24850b-462f-4d2e-9d75-e9317c093e5e@z31g2000yqd.googlegroups.com> Message-ID: <5480dbe7-d9cc-44fb-a6cb-b866c01cd545@o6g2000yqj.googlegroups.com> On Aug 25, 10:12?am, Pierre wrote: > Hello, > > I'm to plot some results but it doesn't work. > I got this error : > > /usr/local/libre_rep/python-2.6.1/RHEL_5__x86_64/lib/python2.6/site- > packages/matplotlib/backends/__init__.py:41: UserWarning: > Your currently selected backend, 'agg' does not support show(). > Please select a GUI backend in your matplotlibrc file ('/usr/local/ > libre_rep/python-2.6.1/RHEL_5__x86_64/lib/python2.6/site-packages/ > matplotlib/mpldata/matplotlibrc') > or with matplotlib.use() > > Any idea to fix it ? > > Thanks Try: import matplotlib matplotlib.use('TkAgg') before coding anything else from the examples section of the matplotlib documentation http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk.html From hv at tbz-pariv.de Tue Aug 25 06:18:59 2009 From: hv at tbz-pariv.de (Thomas Guettler) Date: Tue, 25 Aug 2009 12:18:59 +0200 Subject: os.popen output different from native shell output In-Reply-To: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Message-ID: <7fhs4jF2b5i5pU1@mid.individual.net> hi, you get the popen output like this: user at unixhost> ls | cat nickname schrieb: > Hi all, > I am a relative newbie to python, I am using os.popen to run an > ls command. The output that I get using the read() function is > different in look and feel from when I run the ls command natively > from the shell (not via python). I display the ouput via python by > using the print function on the variable that accepts the os.popen > ().read() function. ... Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From michele.simionato at gmail.com Tue Aug 25 06:28:44 2009 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 25 Aug 2009 03:28:44 -0700 (PDT) Subject: your favorite debugging tool? References: Message-ID: <57d65219-8134-4c2e-9739-825a5ef450d0@s15g2000yqs.googlegroups.com> On Aug 22, 4:25?pm, Esmail wrote: > Hi all, > > What is your favorite tool to help you debug your > code? The times when I would just use 'print' are long past. Nowadays I spend lots of my time with code written by others than myself. I use pdb all the time, and now also ipdb (ipdb is very cool if you are used to ipython). M.S. From bbxx789_05ss at yahoo.com Tue Aug 25 06:41:54 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 25 Aug 2009 03:41:54 -0700 (PDT) Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> Message-ID: <84154e6e-c425-4b71-89e3-7d2877a19418@m7g2000prd.googlegroups.com> On Aug 24, 10:09 pm, Ned Deily wrote: > In article > , > > > > 7stud wrote: > > On Aug 24, 2:41 pm, "Martin v. L?wis" wrote: > > > > I can't figure out a way to programatically set the encoding for > > > > sys.stdout. So where does that leave me? > > > > You should be setting the terminal encoding administratively, not > > > programmatically. > > > The terminal encoding has always been utf-8. It was not set > > programmatically. > > > It seems to me that python 3.1's string handling is broken. > > Apparently, in python 3.1 I am unable to explicitly set the encoding > > of a string and print() it out with the result being human readable > > text. On the other hand, if I let python do the encoding implicitly, > > python uses a codec I don't want it to. > > If you are running on a Unix-y system, check your locale settings (LANG, > LC.*, et al). I think you'll likely find that your locale is really not > UTF-8. The following was on Python 3.1 on OS X 10.5, similar results > on Debian Linux: > > $ cat t3.py > import sys > print(sys.stdout.encoding) > s = "?" > print(s.encode("utf-8")) > print(s) > > $ export LANG=en_US.UTF-8 > $ python3.1 t3.py > UTF-8 > b'\xe2\x82\xac' > ? > > $ export LANG=C > $ python3.1 t3.py > US-ASCII > b'\xe2\x82\xac' > Traceback (most recent call last): > File "t3.py", line 7, in > print(s) > UnicodeEncodeError: 'ascii' codec can't encode character '\u20ac' in > position 0: ordinal not in range(128) > > -- > Ned Deily, > n... at acm.org Hi, Thanks for the response. My OS is mac osx 10.4.11. I'm not really sure how to check my locale settings. Here is some stuff I tried: $ echo $LANG $ echo $LC_ALL $ echo $LC_CTYPE $ locale LANG= LC_COLLATE="C" LC_CTYPE="C" LC_MESSAGES="C" LC_MONETARY="C" LC_NUMERIC="C" LC_TIME="C" LC_ALL="C" $man locale ... ... ... ENVIRONMENT: LANG Used as a substitute for any unset LC_* variable. If LANG is unset it will act as if set to "C". If any of LANG or LC_* are set to invalide values locale acts as if they are all unset. =========== As in your last example, my 'C' settings mean that an ascii codec is used somewhere to encode() the unicode string. -- The locale C or POSIX is a portable locale; its LC_CTYPE part corresponds to the 7-bit ASCII character set. http://linux.about.com/library/cmd/blcmdl3_setlocale.htm -- Is this the way it works: 1) python sets the codec for sys.stdout to the LANG environment variable. 2) It doesn't matter that my terminal's encoding is set to utf-8 because output has to pass through sys.stdout first. So: a) My terminal's environment is telling python(and all other programs running in the terminal) that output sent to sys.stdout must be encoded in ascii. b) The solution is to set a LANG environment variable. Why does echoing $LC_ALL or $LC_CTYPE just give me a blank string? Previously, I've set environment variables that I want to be permanent, e.g PATH, in ~/.bash_profile, so I did this: ~/.bash_profile: -------------- ... ... LANG="en_US.UTF-8" export LANG and now python 3.1 acts like I expect it to: ------- import locale import sys print(locale.getlocale(locale.LC_CTYPE)) print(sys.stdout.encoding) s = "?" print(s) print(s.encode("utf-8")) --output:-- ('en_US', 'UTF8') UTF-8 ? b'\xe2\x82\xac' ---------- In conclusion, as far as I can tell, if your python 3.1 program tries to output a unicode string, and the unicode string cannot be encoded by the codec specified in the user's LANG environment variable**, then the user will get an encode error. Just because the programmer's system can handle the output doesn't mean that another user's system can. I guess that's the way it goes: if a user's environment is telling all programs that it only wants ascii output to go to the screen(sys.stdout), you can't(or shouldn't) do anything about it. **Or if the LANG environment variable is not present, then the codec corresponding to the locale settings(C' corresponds to ascii). some good locale info: http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_19.html From bbarbero at inescporto.pt Tue Aug 25 06:57:07 2009 From: bbarbero at inescporto.pt (bbarbero at inescporto.pt) Date: Tue, 25 Aug 2009 12:57:07 +0200 Subject: unexpected token `;' Message-ID: <20090825125707.96162cpxx4xdaglf@horde.inescporto.pt> Hello to all! I am struggling with a script in python for a while now, and decided to look for some help. I am running a code that takes commands from Marsyas(open source for Music analysis). #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 #!/bin/bashimport math import re import numpy import string import os.path import sys import commands l = "/Users/bmorab/Audio_Projecto/Data/Palco/PP3_44_distance_matrix/PP3_44_5.mf" Col = open(l, 'r') colist= [] songlist = [] for line in Col: #print line song = os.path.split(line)[1] #print song songlist.append(song) colist.append(line) cmd = "sfplay " + colist[2] print cmd fileout = commands.getoutput(cmd) print fileout It basically reads song files from the .mf file, stores them in a list and play one of the songs from the list. It does work with some music but mostly it gives an error like this: sfplay /Volumes/HAL/Datasets/Audio/PalcoPrincipal/mp3_resampled_44100/10005.mp3 sh: -c: line 1: syntax error near unexpected token `;' sh: -c: line 1: `; } 2>&1' Ive been searching for the meaning of the error, and It really depends on the script, but I would conclude that I am missing a punctuation mark?? Thank you very much for taking your time reading my request. Looking forward to hearing from you. Regards, Bea ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From mmelchert03 at yahoo.com Tue Aug 25 07:24:37 2009 From: mmelchert03 at yahoo.com (mmelchert) Date: Tue, 25 Aug 2009 13:24:37 +0200 Subject: unexpected token `;' References: Message-ID: <4a93c9f6$0$2370$9b622d9e@news.freenet.de> bbarbero at inescporto.pt wrote: > Hello to all! > > I am struggling with a script in python for a while now, and decided > to look for some help. I am running a code that takes commands from > Marsyas(open source for Music analysis). > > #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 > #!/bin/bashimport math <<== > import re > import numpy have a close look at the <<== line: I think you wanted it to read import math rather than #!/bin/bashimport math? From aotto1968 at users.sourceforge.net Tue Aug 25 07:24:37 2009 From: aotto1968 at users.sourceforge.net (Andreas Otto) Date: Tue, 25 Aug 2009 13:24:37 +0200 Subject: problem to write a THREAD enabled python extension References: <4a92af50$0$32675$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Stefan Behnel wrote: > > You forgot to create a thread state for the new thread. See the > PyThreadState_New() function. > this does not really solve the problem even if the original error does no happen anymore ... but a bucket of other error happen >>> sometimes <<< and this mean that time and (I call it so) internal state stuff has influence on the problem and create errors like: 1. http://mail.python.org/pipermail/python-list/2004-January/242740.html 2. various PyThreadState_Get -> PyThreadState_Get: no current thread 3. sometimes ThreadState has NULL sometimes not and NULL create an CORE for "tstate" pointer access operations 4. ... a lot of other problems too all problems together I come to the conclusion: 1. I spend ~ 1week for a job done in C# or java in a day - and have no usable solution 2. python need a couple of 100+ C API function for the same job java need 10+ 3. the design on the C-API is amateurish -> significant parts are implemented as GLOBAL variables 4. the thread support is not more than a joke -> go to 3 5. after pay a lot of effort to get something working the final solution is significant slower than C# or JAVA 6. you can not truss any-thing in python because you never know if under some circumstance you get a CORE the resulting PYTHON code is usable but not significant more readable as JAVA, C* or even C++ code mfg aotto1968 From feliphil at gmx.net Tue Aug 25 07:24:39 2009 From: feliphil at gmx.net (Wolfgang Keller) Date: Tue, 25 Aug 2009 13:24:39 +0200 Subject: Python for professsional Windows GUI apps? References: Message-ID: <20090825132439.d6cb18ca.feliphil@gmx.net> > I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. The area of _desktop_ database application development indeed looks like a vast and very hostile desert in the Python landscape. The only framework that seems to be worth trying is Dabo. Unfortunately there's little documentation, and that's mostly outdated. There's also Kiwi, but that's even less well documented. And GNU Enterprise essentially seems to be dead. Sincerely, Wolfgang -- NO "Courtesy Copies" PLEASE! From deets at nospam.web.de Tue Aug 25 07:25:04 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 13:25:04 +0200 Subject: unexpected token `;' References: Message-ID: <7fi00gF2kr205U1@mid.uni-berlin.de> bbarbero at inescporto.pt wrote: > Hello to all! > > I am struggling with a script in python for a while now, and decided > to look for some help. I am running a code that takes commands from > Marsyas(open source for Music analysis). > > #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 > #!/bin/bashimport math This is bogus. Replace it with #!/usr/bin/python and put the "import math" on the next line. Diez From markonlinux at internode.on.net Tue Aug 25 07:26:40 2009 From: markonlinux at internode.on.net (Mark) Date: 25 Aug 2009 11:26:40 GMT Subject: can python make web applications? References: Message-ID: <02a3ba7c$0$18215$c3e8da3@news.astraweb.com> On Sun, 23 Aug 2009 21:45:17 +0100, Goke Aruna wrote: > A lot check this fantastic open source application, > http://www.openerp.com, all done is python. That does look impressive. Is that Django or Turbogears? -- Mark From gslindstrom at gmail.com Tue Aug 25 07:28:40 2009 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Tue, 25 Aug 2009 06:28:40 -0500 Subject: PyCon 2010 - Call for Tutorials Message-ID: The period to submit proposals for PyCon 2010 in Atlanta, Georgia (USA) is now open and will close on October 18. Tutorials are 3-hour long classes on a specific Python technique, package or technology and are taught by members of the Python community. If you have knowledge in a particular topic and would like to be considered to teach a class we invite you to submit a proposal outlining the material you would like to cover. Once we receive your proposal, we will "score" it based on content and then select 24 classes (subject to change) for presentation. Class instructors will be paid $1000.00 per class. If a class has more than one teacher, the fee will be split between them. Interested? Click on over to the Tutorial Proposal Pageto see more details, examples of classes that have been requested in the past (though you are free to submit a proposal on anything Python), an example proposal and an empty template to help you prepare your own proposal. Once complete, email your proposal to pycon-tutorials at python.orgso we can get it out to the evaluation committee and get you on your way to being a PyCon Questions? You can contact us at the PyCon Email Listand we will get back with you. We look forward to hearing from you! Greg Lindstrom Tutorial Coordinator PyCon 2010 (Atlanta) -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at cs.uu.nl Tue Aug 25 07:33:02 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 25 Aug 2009 13:33:02 +0200 Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> <4224e772-5b67-4eea-9bdf-a7d2bf7cc128@c14g2000yqm.googlegroups.com> <864e2d5f-0855-4f35-a78c-b09054e75f0d@w41g2000yqb.googlegroups.com> Message-ID: >>>>> sturlamolden (s) wrote: >s> On 25 Aug, 01:26, Piet van Oostrum wrote: >>> That's because it doesn't use copy-on-write. Thereby losing most of its >>> advantages. I don't know SUA, but I have vaguely heard about it. >s> SUA is a version of UNIX hidden inside Windows Vista and Windows 7 >s> (except in Home and Home Premium), but very few seem to know of it. >s> SUA (Subsystem for Unix based Applications) is formerly known as >s> Interix, which is a certified version of UNIX based on OpenBSD. If you >s> go to http://www.interopsystems.com (a website run by Interop Systems >s> Inc., a company owned by Microsoft), you will find a lot of common >s> unix tools prebuilt for SUA, including Python 2.6.2. >s> The NT-kernel supports copy-on-write fork with a special system call >s> (ZwCreateProcess in ntdll.dll), which is what SUA's implementation of >s> fork() uses. I have heard about that also, but is there a Python implementation that uses this? (Just curious, I am not using Windows.) -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From nobody at nowhere.com Tue Aug 25 07:34:59 2009 From: nobody at nowhere.com (Nobody) Date: Tue, 25 Aug 2009 12:34:59 +0100 Subject: web frameworks that support Python 3 References: Message-ID: On Sun, 23 Aug 2009 16:32:09 -0400, Albert Hopkins wrote: > What's different about Python 3 is that there is only unicode strings, > whereas Python 2 has a string type and a unicode type. Python 2 has "str" (char) and "unicode" (wchar) types. Python 3 has "bytes" (char) and "str" (wchar) types. The main difference is that Python 3 uses unicode "by default", i.e. string literals are unicode rather than byte strings, variables such as sys.argv and os.environ contain unicode strings, etc. There are other differences, e.g.: + Passing a "bytes" object where "str" is expected will raise an exception rather than using an automatic conversion + Subscripting a "bytes" object returns an integer between 0 and 255 + upper(), isalpha(), etc assume ASCII rather than the system encoding From nobody at nowhere.com Tue Aug 25 07:47:54 2009 From: nobody at nowhere.com (Nobody) Date: Tue, 25 Aug 2009 12:47:54 +0100 Subject: sgmllib.py References: <4a923c57$0$32664$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Mon, 24 Aug 2009 09:08:07 +0200, Stefan Behnel wrote: > But note that sgmllib is a particularly cumbersome way to deal with HTML. Mostly because it only provides a tokeniser, not a parser. Whoever wrote it doesn't appear to understand the difference. From benjamin.kaplan at case.edu Tue Aug 25 07:50:59 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 25 Aug 2009 07:50:59 -0400 Subject: unexpected token `;' In-Reply-To: <7fi00gF2kr205U1@mid.uni-berlin.de> References: <7fi00gF2kr205U1@mid.uni-berlin.de> Message-ID: On Tue, Aug 25, 2009 at 7:25 AM, Diez B. Roggisch wrote: > > > Hello to all! > > > > I am struggling with a script in python for a while now, and decided > > to look for some help. I am running a code that takes commands from > > Marsyas(open source for Music analysis). > > > > #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 > > #!/bin/bashimport math > > This is bogus. Replace it with > > #!/usr/bin/python > > and put the "import math" on the next line. > > Diez It's not bogus. That is perfectly legitimate for using the user-installed Python2.6 on OS X. /usr/bin/ is reserved for system programs on that platform so it will always point to the system python install, which is 2.5.1 on Leopard and 2.3.5 on Tiger. That being said, the #!/bin/bash line is what's screwing it up. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Aug 25 07:51:24 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Aug 2009 13:51:24 +0200 Subject: unexpected token `;' References: Message-ID: bbarbero at inescporto.pt wrote: > I am struggling with a script in python for a while now, and decided > to look for some help. I am running a code that takes commands from > Marsyas(open source for Music analysis). > cmd = "sfplay " + colist[2] > print cmd > fileout = commands.getoutput(cmd) You have to ensure here that characters that have a special meaning for the shell are escaped correctly. The best approach is probably to use subprocess instead of commands: fileoutput = subprocess.Popen(["sfplay", colist[2]], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] Peter From ebonak at hotmail.com Tue Aug 25 07:55:22 2009 From: ebonak at hotmail.com (Esmail) Date: Tue, 25 Aug 2009 07:55:22 -0400 Subject: your favorite debugging tool? In-Reply-To: <7xocq5vx64.fsf@ruckus.brouhaha.com> References: <7xocq5vx64.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Esmail writes: >> What is your favorite tool to help you debug your >> code? I've been getting along with 'print' statements >> but that is getting old and somewhat cumbersome. > > Beyond print statements, I use pdb a lot. Winpdb (www.winpdb.org) is > even better, but is kind of cumbersome to get working. Hi, 2 quick questions. Re pdb, if you have a 'pointer' (ie reference) to an object, is there an easy way to dump out its contents, ie all of its members short of writing a method that does that and then calling it? Anyone know what is going on with the winpdb site? I haven't been able to get to it in the last few days. Thanks, Esmail From ebonak at hotmail.com Tue Aug 25 07:55:56 2009 From: ebonak at hotmail.com (Esmail) Date: Tue, 25 Aug 2009 07:55:56 -0400 Subject: your favorite debugging tool? In-Reply-To: References: <7xocq5vx64.fsf@ruckus.brouhaha.com> Message-ID: Robert Marshall wrote: > On 24 Aug 2009, Paul Rubin wrote: > >> Esmail writes: >>> What is your favorite tool to help you debug your >>> code? I've been getting along with 'print' statements >>> but that is getting old and somewhat cumbersome. >> Beyond print statements, I use pdb a lot. Winpdb (www.winpdb.org) is >> even better, but is kind of cumbersome to get working. > > And you can run it (pdb) within emacs - though I find a little roughness > in working out the exact interactions keeps ending up (ie the source > buffer displayed) in the wrong stack frame - afaict Thanks Robert, I'll have to give that a try. Esmail From ebonak at hotmail.com Tue Aug 25 07:57:26 2009 From: ebonak at hotmail.com (Esmail) Date: Tue, 25 Aug 2009 07:57:26 -0400 Subject: your favorite debugging tool? In-Reply-To: <57d65219-8134-4c2e-9739-825a5ef450d0@s15g2000yqs.googlegroups.com> References: <57d65219-8134-4c2e-9739-825a5ef450d0@s15g2000yqs.googlegroups.com> Message-ID: Michele Simionato wrote: > On Aug 22, 4:25 pm, Esmail wrote: >> Hi all, >> >> What is your favorite tool to help you debug your >> code? > > The times when I would just use 'print' are long past. Nowadays I > spend lots of my time > with code written by others than myself. I use pdb all the time, and > now also ipdb > (ipdb is very cool if you are used to ipython). Never heard of ipdb, I'll have to check it out. Thanks, Esmail From dmw at coder.cl Tue Aug 25 08:08:02 2009 From: dmw at coder.cl (Daniel Molina Wegener) Date: Tue, 25 Aug 2009 08:08:02 -0400 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module References: <2571343.k9db9GJWqV@coder.cl> <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> <2665032.o6QR52tnKS@coder.cl> <4a928ed7$0$32666$9b4e6d93@newsspool2.arcor-online.net> <1685404.FXBiJzzPRc@coder.cl> <4a937266$0$31337$9b4e6d93@newsspool4.arcor-online.net> <4a937546$0$31332$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <1731852.i11Z6b9PKs@coder.cl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Stefan Behnel on Tuesday 25 August 2009 01:23 wrote in comp.lang.python: > Stefan Behnel wrote: >> for all byte >> strings, regardless of their encoding (since you can't even know if they >> represent encoded text at all). > > Hmm, having written that, I guess it's actually best to encode byte > strings as base64 instead. Otherwise, null bytes and other special byte > values won't pass. Sure, base64 is a good option for byte string input. > > I also think that if the user wants readable output for text strings, it's > reasonable to require Unicode input instead of byte strings. Handling text > in byte strings is just too error prone. > > Still, you may have to sanitize text input to make sure it doesn't contain > special characters either. Take a look at the way lxml does it in the > apihelpers.pxi source file, or read the XML spec on character content. Thanks, I will look for that. I must to do a better implementation on handling byte strings, since would be many cases on where encoded strings are mixed. For example different database inputs with different encodings --- if those byte strings are not readed as Unicode strings. Both sanitizing and base64 encoding are good options, and also, both are readable from other platforms. The problem with later implementations of pyxser was that it was using *RawUnicodeEscape* which is not readable from other platforms. > > Stefan Best regards, - -- .O. | Daniel Molina Wegener | FreeBSD & Linux ..O | dmw [at] coder [dot] cl | Open Standards OOO | http://coder.cl/ | FOSS Developer -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (FreeBSD) iQIcBAEBCgAGBQJKk9QiAAoJEHxqfq6Y4O5NvxcP/1plIdop5ghbwAKwavU8PSSe 05Lx/3AqThiQTJgG1qIrUXqA70KKGbgnyRAyOb8lTo3E1EcYnrEyM3pIg9xKbEr1 aRbpMVPIUPv//ckJxIwJlszjWoxjpSWKpRFqOkHnBjL6NcAqD7r3LxMLaDKMHNXl Ka07clukcarEeU5f93mcOpCXMg1XFxfQFr126wbEkC5M2WxwpSJrsX6NIXL34peU 37sjuYOQGEgifw7KKVDNCmt3JNTmojCeRL+xzUiFDXRmm2B9A2Q7fGKKudNC2+u7 d5vUdWUhsK8a2P7o3c8ka/N9hcZ7ESjhlLDjtXEAb45yGUOXkpoOSLznObhGM3H9 MpPbmprvFL8sUX8F8+EOHOAbfaTtTRO384hwY2e7tVaaf6CNutK00Z5nBM7UPdWW nclS7owNOVsrR62ZGwEcjDwjeYqXp3kIixbbSM9kALu1iKYxaueauIXct6oPQwl7 A3rEmultt7pjfbaDw+kYCouP4YnbPQn84H7Qgle/TMATPgnlD+93OnbCgWhpkx0h 21l4STWHNIZ2yi538lDDnkxKXS9reJQOYiiB9ImueIJJBZhqTwCDiCZDJg7QBVH0 7zsKH70Pbl3ENpTjBmPsxTUbOjzMwaFCbJ/h9+JCLV98TRfwa4KOAsRDC+mThnrY k6Pj1jxY4uYmAn+xK+x+ =5B9H -----END PGP SIGNATURE----- From walterbyrd at iname.com Tue Aug 25 08:28:31 2009 From: walterbyrd at iname.com (walterbyrd) Date: Tue, 25 Aug 2009 05:28:31 -0700 (PDT) Subject: Would there be work for a sysadmin who specializes in python? Message-ID: If I took the time to really learn to use python for sysadmin work, would I be able to find jobs, or even contract jobs? >From what I am seeing on the job boards etc., I would have to say no. It looks to me as though I could possibly do that with perl, but not python. Of course, I could be missing something. Job board ads can be deceptive. From ryniek90 at gmail.com Tue Aug 25 08:29:27 2009 From: ryniek90 at gmail.com (ryniek) Date: Tue, 25 Aug 2009 05:29:27 -0700 (PDT) Subject: Temat:, Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> <4ec18c68-b8b5-401e-b910-802b7662dced@i18g2000pro.googlegroups.com> <321b8396-0806-4a1a-9a32-efbb147e6b4b@c2g2000yqi.googlegroups.com> Message-ID: <62ee06b6-4d8b-4033-828a-bad0bd6ea329@r42g2000yqj.googlegroups.com> On 25 Sie, 07:33, Dennis Lee Bieber wrote: > On Mon, 24 Aug 2009 14:23:41 -0700 (PDT), ryniek > declaimed the following in gmane.comp.python.general: > > > C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje > > \Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba > > ckuper.py -f E:\APLIKACJE\nowegg.exe E:\ MyGG > > ? ? ? ? > > > OSError: [Errno 22] Invalid argument: 'E:\\MyGG(2009-08-24 > > 23:18:25).tar.bz2' > > " > > ? ? ? ? WHERE in your program are you creating that file name? Based upon > the invocation line, all you are supplying is the E:\MyGG part... > Somewhere you are creating a timestamp and attaching that to the prefix. > > ? ? ? ? THAT is where you need to get rid of the colons -- the ones in the > timestamp. Instead of 23:18:25 (or whatever the next run generates) you > want something like 23_18_25... > -- > ? ? ? ? Wulfraed ? ? ? ? Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ?HTTP://wlfraed.home.netcom.com/ Yep, i realized that it were THOSE colons. Thanks very much. I think i must work on my perceptivity : P Thanks again. From nobody at nowhere.com Tue Aug 25 08:34:33 2009 From: nobody at nowhere.com (Nobody) Date: Tue, 25 Aug 2009 13:34:33 +0100 Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> <84154e6e-c425-4b71-89e3-7d2877a19418@m7g2000prd.googlegroups.com> Message-ID: On Tue, 25 Aug 2009 03:41:54 -0700, 7stud wrote: > Why does echoing $LC_ALL or $LC_CTYPE just give me a blank string? Because the variables aren't set. The default locale for a particular category (e.g. LC_CTYPE) is taken from $LC_ALL if that is set, otherwise $LC_CTYPE, otherwise $LANG, otherwise "C" is used. Normally, you would either set LANG (and possibly some individual LC_* variables), or LC_ALL. There's no point in setting all of them. > In conclusion, as far as I can tell, if your python 3.1 program tries > to output a unicode string, and the unicode string cannot be encoded > by the codec specified in the user's LANG environment variable**, then > the user will get an encode error. Just because the programmer's > system can handle the output doesn't mean that another user's system > can. I guess that's the way it goes: if a user's environment is > telling all programs that it only wants ascii output to go to the > screen(sys.stdout), you can't(or shouldn't) do anything about it. > > **Or if the LANG environment variable is not present, then the codec > corresponding to the locale settings(C' corresponds to ascii). The underlying OS primitive can only handle bytes. If you read or write a (unicode) string, Python needs to know which encoding is used. For Python file objects created by the user (via open() etc), you can specify the encoding; for those created by the runtime (e.g. sys.stdin), Python uses the locale's LC_CTYPE category to select an encoding. Data written to or read from text streams is encoded or decoded using the stream's encoding. Filenames are encoded and decoded using the filesystem encoding (sys.getfilesystemencoding()). Anything else uses the default encoding (sys.getdefaultencoding()). In Python 3, text streams are handled using io.TextIOWrapper: http://docs.python.org/3.1/library/io.html#text-i-o This implements a stream which can read and/or write text data on top of one which can read and/or write binary data. The sys.std{in,out,err} streams are instances of TextIOWrapper. You can get the underlying binary stream from the "buffer" attribute, e.g.: sys.stdout.buffer.write(b'hello world\n') If you need to force a specific encoding (e.g. if the user has specified an encoding via a command-line option), you can detach the existing wrapper and create a new one, e.g.: sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = new_encoding) From ebonak at hotmail.com Tue Aug 25 08:40:24 2009 From: ebonak at hotmail.com (Esmail) Date: Tue, 25 Aug 2009 08:40:24 -0400 Subject: Would there be work for a sysadmin who specializes in python? In-Reply-To: References: Message-ID: walterbyrd wrote: > If I took the time to really learn to use python for sysadmin work, > would I be able to find jobs, or even contract jobs? > FWIW, I think one of the qualities of a good system admin would be the ability to work with a variety of tools and languages and not focus on one particular language. Though Perl (not a favorite of mine at all :) seems to be quite popular for admin type work, and of course knowing some sort of shell programming etc would come in handy. From ben+python at benfinney.id.au Tue Aug 25 08:44:47 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 25 Aug 2009 22:44:47 +1000 Subject: your favorite debugging tool? References: Message-ID: <87ws4sf4g0.fsf@benfinney.id.au> Esmail writes: > While I do believe in a minimalist approach (part of the reason I find > Python so appealing), using print statements sometimes only goes so > far (for me). Right, which is where the Python interactive interpreter (which I failed to mention in my initial response) comes in as my favourite debugging tool. -- \ ?When I was a kid I used to pray every night for a new bicycle. | `\ Then I realised that the Lord doesn't work that way so I stole | _o__) one and asked Him to forgive me.? ?Emo Philips | Ben Finney From ebonak at hotmail.com Tue Aug 25 08:51:06 2009 From: ebonak at hotmail.com (Esmail) Date: Tue, 25 Aug 2009 08:51:06 -0400 Subject: your favorite debugging tool? In-Reply-To: <87vdkfiaki.fsf@benfinney.id.au> References: <87vdkfiaki.fsf@benfinney.id.au> Message-ID: Hi Ben, Ben Finney wrote: > > Whenever a simple output statement is too cumbersome for debugging, I > take it as a sign that the program is too cumbersome to follow. I'll have to think about this .. though my gut says this is true :-) re your other point about the interactive shell, I agree it's useful, but to me still doesn't quite do what a full-fledged debugger can - but perhaps that is a reflection of my skill with the shell at this point. Always more to learn. Esmail From hniksic at xemacs.org Tue Aug 25 09:03:12 2009 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 25 Aug 2009 15:03:12 +0200 Subject: proposal: add setresuid() system call to python In-Reply-To: <20090821205040.GK1215@subspacefield.org> (travis's message of "Fri, 21 Aug 2009 15:50:40 -0500") References: <20090717200141.GI6065@subspacefield.org> <148918f0907171315i4ed5b274v77581a43c4464f8f@mail.gmail.com> <7cj89qF27mfrjU1@mid.uni-berlin.de> <877hy38mxw.fsf@busola.homelinux.net> <20090821205040.GK1215@subspacefield.org> Message-ID: <87d46kdp0v.fsf@busola.homelinux.net> travis+ml-python at subspacefield.org writes: > On Mon, Jul 20, 2009 at 04:10:35PM +0200, Hrvoje Niksic wrote: >> To emulate the os-module-type calls, it's better to raise exceptions >> than return negative values: >> >> > def setresuid(ruid, euid, suid): >> > return _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid)) >> >> def setresuid(ruid, euid, suid): >> res = _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid)) >> if res < 0: >> raise OSError('[Errno %d] %s' % (os.errno, errno.strerror(os.errno))) > > I am working on a module to implement all of this, but that raise command > won't work in Python 2.6.1; it turns out that os.errno is a module, not > an integer. Does anyone know how to do what I want (that is, how to access > the errno set in C functions)? You should use ctypes.get_errno() instead of os.errno; sorry about that. Also, when raising OSError, you should set the 'errno' attribute to the appropriate code. From nobody at nowhere.com Tue Aug 25 09:16:23 2009 From: nobody at nowhere.com (Nobody) Date: Tue, 25 Aug 2009 14:16:23 +0100 Subject: os.popen output different from native shell output References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Message-ID: On Tue, 25 Aug 2009 01:36:08 -0700, nickname wrote: > I am a relative newbie to python, I am using os.popen to run an > ls command. The output that I get using the read() function is > different in look and feel from when I run the ls command natively > from the shell (not via python). As others have pointed out, the default behaviour of ls is different if its output is a terminal. > Is there an easy way to "mirror" the output. When python displays the > output, how can it tell the bash shell that some of the entries are > directories and they should appear blue on the bash shell, and that > everything should not be appearing on 1 column only. You can get the terminal-style behaviour even when using a pipe with: ls -x --color But why are you reading this information into Python then writing it back out to the terminal? If you're planning on processing the output within Python, both the multi-column format and the escape sequences used for colour will make such processing awkward. If you want to enumerate the contents of a directory within Python, use os.listdir(). If you want to generate coloured output, use the curses module, e.g.: #!/usr/bin/env python import sys import curses curses.setupterm() setaf = curses.tigetstr('setaf') or "" setab = curses.tigetstr('setab') or "" origp = curses.tigetstr('op') or "" def fg(c): sys.stdout.write(curses.tparm(setaf, c)) def bg(c): sys.stdout.write(curses.tparm(setab, c)) def orig(): sys.stdout.write(origp) # example bg(curses.COLOR_BLUE) fg(curses.COLOR_YELLOW) print "hello, world" orig() From find.mig at paa.google Tue Aug 25 09:21:16 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Tue, 25 Aug 2009 15:21:16 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a92b290$0$305$14726298@news.sunsite.dk> Message-ID: <4a93e575$0$298$14726298@news.sunsite.dk> Dennis Lee Bieber wrote: > On Mon, 24 Aug 2009 17:32:23 +0200, Esben von Buchwald > declaimed the following in > gmane.comp.python.general: > >> I'm new to python, what is an after function and an after call? Couldn't >> find excact answer on google...? Do you have a link to some docs? > > They would be particular to whatever GUI/event library is in use. > They aren't part of Python itself. This is how the accelerometer is accessed http://pys60.garage.maemo.org/doc/s60/node59.html I found this called "after"... http://pys60.garage.maemo.org/doc/s60/node12.html would that be usable? If so, how? From kkuNOTHISmer at thatsearchenginesmail.com Tue Aug 25 09:30:28 2009 From: kkuNOTHISmer at thatsearchenginesmail.com (Kreso) Date: Tue, 25 Aug 2009 13:30:28 +0000 (UTC) Subject: Items inheriting attributes from its container? References: Message-ID: Jan Kaliszewski wrote: [...] Great! Thanks to all of you for advices and code. K. From brentb at beanfield.com Tue Aug 25 09:42:00 2009 From: brentb at beanfield.com (Brent Bloxam) Date: Tue, 25 Aug 2009 09:42:00 -0400 Subject: Would there be work for a sysadmin who specializes in python? In-Reply-To: References: Message-ID: <4A93EA28.8060703@beanfield.com> walterbyrd wrote: > If I took the time to really learn to use python for sysadmin work, > would I be able to find jobs, or even contract jobs? > >>From what I am seeing on the job boards etc., I would have to say no. > It looks to me as though I could possibly do that with perl, but not > python. > > Of course, I could be missing something. Job board ads can be > deceptive. Being a system admin is about being able to handle to many different situations, and your tasks can often include automating various things and writing tools. Depending on the sort of place you're working in and the size of the IT department, you could find yourself doing a lot of work that lies outside of the standard job description for a system administrator. If you're looking to start out in the field, it would be better to have general knowledge, and as you gain experience you can begin to specialize. Being adaptable is key, so specializing in python probably won't gain you any ground as a system administrator. That being said, knowing python will mean you have another tool in your chest, which is definitely a good thing. If there's one thing I'd recommend, if you're not going to focus on a windows environment, would be to at least get perl under your belt as well. From jkpeck at gmail.com Tue Aug 25 10:02:36 2009 From: jkpeck at gmail.com (JKPeck) Date: Tue, 25 Aug 2009 07:02:36 -0700 (PDT) Subject: csv module and None values References: <23c02daf-dc5a-4676-8d73-9dc63791825f@o36g2000vbl.googlegroups.com> Message-ID: <4006702e-14c5-4917-b76f-906233cad71e@k30g2000yqf.googlegroups.com> On Aug 24, 10:43?pm, John Yeung wrote: > On Aug 24, 5:00?pm, Peter Otten <__pete... at web.de> wrote: > > > If I understand you correctly the csv.writer already does > > what you want: > > > >>> w.writerow([1,None,2]) > > 1,,2 > > > just sequential commas, but that is the special treatment. > > Without it the None value would be converted to a string > > and the line would look like this one: > > > 1,None,2 > > No, I think he means he is getting > > >>> w.writerow([1,None,2]) > > 1,"",2 > > He evidently wants to quote "all" strings, but doesn't want None to be > considered a string. > > John Exactly so. The requirement of the receiving program, which is out of my control, is that all strings be quoted but a None in a numeric field result in the ,, output rather than "". Excel quotes strings conditionally, which doesn't do what is needed in this case. For QUOTE_NONNUMERIC to quote None values makes some sense, but it gets in the way of representing missing values in a numeric field. It would be nice to have a choice here in the dialects. I thought of replacing the None values with float(nan), since that has a numeric type, but unfortunately that results in writing the string (unquoted) nan for the value. So the sentinel approach seems to be the best I can do. Thanks, Jon From chris0wj at gmail.com Tue Aug 25 10:14:12 2009 From: chris0wj at gmail.com (Chris) Date: Tue, 25 Aug 2009 07:14:12 -0700 (PDT) Subject: multiprocessing managers and socket connection. Message-ID: <722664f1-81af-45da-ae40-070bca8f3ee0@k6g2000yqn.googlegroups.com> I've been using multiprocessing managers and I really like the functionality. I have a question about reconnecting to a manager. I have a situation where I start on one machine (A) a manager that is listening and then on another machine (B) connects to that manager and uses its proxy object to call functions on the manager's computer; this all works as expected. But, if the manager from A shuts down, B's application won't notice because in the MP code it ignores socket error errno.ECONNREFUSED. If A becomes available again or is restarted, B doesn't automatically reconnect either and continue its operation. It's function is basically stopped. Here is the code from connection.py: while 1: try: s.connect(address) except socket.error, e: if e.args[0] != errno.ECONNREFUSED: # connection refused debug('failed to connect to address %s', address) raise time.sleep(0.01) else: break How can I have B automatically reconnect to A and continue its work once A is available again? From steve at REMOVE-THIS-cybersource.com.au Tue Aug 25 10:14:49 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Aug 2009 14:14:49 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> Message-ID: <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 18:01:38 -0700, Mensanator wrote: >> If you want your data file to have values entered in hex, or oct, or >> even unary (1=one, 11=two, 111=three, 1111=four...) you can. > > Unary? I think you'll find that Standard Positional Number Systems are > not defined for radix 1. Of course not. But unary isn't a positional number system. It's a tally system, like my example above shows. Roman numerals are another tally system. Like Roman numerals, the disadvantages of unary are that you can't represent negative numbers, zero, or fractions, and anything but addition and subtraction is difficult. But if you want to use it, perhaps out of a sense of sadism towards your users, it's easy: def int2unary(n): return '1'*n def unary2int(s): n = 0 for c in s: if c == '1': n+=1 else: raise ValueError('invalid unary string') return n -- Steven From jeanmichel at sequans.com Tue Aug 25 10:27:40 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 25 Aug 2009 16:27:40 +0200 Subject: your favorite debugging tool? In-Reply-To: References: <87vdkfiaki.fsf@benfinney.id.au> Message-ID: <4A93F4DC.3090708@sequans.com> Esmail wrote: > Hi Ben, > > Ben Finney wrote: >> >> Whenever a simple output statement is too cumbersome for debugging, I >> take it as a sign that the program is too cumbersome to follow. > > I'll have to think about this .. though my gut says this is true :-) > That is not always true. When it comes to implement complex tasks, you can't always avoid writing complex code. Python does not get your code more complex than your algorithm, but it cannot always simplify it. Ben is right when he says that code can often be written in a more simpler manner, but they are some occasions when you have to write complex code, that the print debug statement won't be efficient enough to sort things out. I personally develop/maintain a full application written in python (and quite complex for some parts), using the ipdb debugger just saved my hours (days) of headache about some very difficult bug to spot > re your other point about the interactive shell, I agree it's useful, but > to me still doesn't quite do what a full-fledged debugger can - but > perhaps > that is a reflection of my skill with the shell at this point. > > Always more to learn. > > Esmail > 90% of the time, print statements + ipython shell will do the trick. The post mortem debugging is also very useful. Execute your python file in ipython, then when it exits upon exception, execute >>> import pdb ; pdb.pm() You can then inspect the symbols easily. JM From ryniek90 at gmail.com Tue Aug 25 10:37:21 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Tue, 25 Aug 2009 16:37:21 +0200 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile Message-ID: <4A93F721.10104@gmail.com> Referring to my earlier posts: http://groups.google.pl/group/comp.lang.python/browse_thread/thread/4e34f995800f5352?hl=pl and http://groups.google.pl/group/comp.lang.python/browse_thread/thread/abf5573b8fceb37e?hl=pl# I've dealt with those errors. but now have another. When my backup scripts starts to backup chosen file, python gave me Traceback: " C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba ckuper.py -f F:\APLIKACJE\nowegg.exe F:\ MyGGBackup Checking permissions for reading and writing... Have permissions on [F:\APLIKACJE\nowegg.exe] for reading. Have permissions on [F:\] for writing. Preparing for backup [nowegg.exe]... Starting backup... Now adding [nowegg.exe]... Traceback (most recent call last): File "backuper.py", line 197, in main_meth() File "backuper.py", line 189, in main_meth paq.backup_file(pars.options.filename[0], pars.options.filename[1], pars.options.filename[2]) File "backuper.py", line 127, in backup_file backup_obj.add(read_bin_obj) File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\tarfile.py", line 1948, in add if self.name is not None and os.path.abspath(name) == self.name: File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\ntpath.py", line 458, in abspath path = _getfullpathname(path) TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str " I've searched over google, but found only that is bug in Python ( http://bugs.python.org/issue4071 - in that issue bug is inside Python 2.5.2 - i've got ActiveState Active Python with core Python 2.6.2), and another info: *http://tinyurl.com/lvyn7o and **http://tinyurl.com/kn49vk * Here's my script code: *http://paste.ubuntu.com/259310/ *Shouldn't that bug be patched already :-? From chris at simplistix.co.uk Tue Aug 25 10:45:53 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 25 Aug 2009 15:45:53 +0100 Subject: inconsistent sitecustomize.py importing... Message-ID: <4A93F921.9080904@simplistix.co.uk> Hi All, Give this sitecustomize.py: print "ping" ...and this script: #!/usr/local/bin/python2.5 print "pong!" ...both in ~/folder, I would expect the output from: ~$./folder/script ...to be: ping pong ...but sitecustomize.py is not imported :-( If I do: ~$/usr/local/bin/python2.5 folder/script ...still no import. However, if I do: ~/folder$/usr/local/bin/python2.5 script ...sitecustomize.py IS imported! What gives?! Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From __peter__ at web.de Tue Aug 25 10:49:07 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Aug 2009 16:49:07 +0200 Subject: csv module and None values References: <23c02daf-dc5a-4676-8d73-9dc63791825f@o36g2000vbl.googlegroups.com> <4006702e-14c5-4917-b76f-906233cad71e@k30g2000yqf.googlegroups.com> Message-ID: JKPeck wrote: > On Aug 24, 10:43 pm, John Yeung wrote: >> On Aug 24, 5:00 pm, Peter Otten <__pete... at web.de> wrote: >> >> > If I understand you correctly the csv.writer already does >> > what you want: >> >> > >>> w.writerow([1,None,2]) >> > 1,,2 >> >> > just sequential commas, but that is the special treatment. >> > Without it the None value would be converted to a string >> > and the line would look like this one: >> >> > 1,None,2 >> >> No, I think he means he is getting >> >> >>> w.writerow([1,None,2]) >> >> 1,"",2 >> >> He evidently wants to quote "all" strings, but doesn't want None to be >> considered a string. >> >> John > > Exactly so. The requirement of the receiving program, which is out of > my control, is that all strings be quoted but a None in a numeric > field result in the ,, output rather than "". Excel quotes strings > conditionally, which doesn't do what is needed in this case. For > QUOTE_NONNUMERIC to quote None values makes some sense, but it gets in > the way of representing missing values in a numeric field. It would > be nice to have a choice here in the dialects. > > I thought of replacing the None values with float(nan), since that has > a numeric type, but unfortunately that results in writing the string > (unquoted) nan for the value. So the sentinel approach seems to be > the best I can do. How about: >>> import csv, sys >>> class N(int): ... def __str__(self): return "" ... >>> pseudo_none = N() >>> w = csv.writer(sys.stdout, quoting=csv.QUOTE_NONNUMERIC) >>> w.writerow([1, "foo", pseudo_none, "bar"]) 1,"foo",,"bar" Peter From ben+python at benfinney.id.au Tue Aug 25 10:49:56 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 26 Aug 2009 00:49:56 +1000 Subject: your favorite debugging tool? References: <87vdkfiaki.fsf@benfinney.id.au> Message-ID: <87skfgeynf.fsf@benfinney.id.au> Esmail writes: > Hi Ben, > > Ben Finney wrote: > > > > Whenever a simple output statement is too cumbersome for debugging, I > > take it as a sign that the program is too cumbersome to follow. > > I'll have to think about this .. though my gut says this is true :-) Note that it's only a sign, *not* an ironclad guarantee. But it's the right way to bet, IME. > re your other point about the interactive shell, I agree it's useful, > but to me still doesn't quite do what a full-fledged debugger can - > but perhaps that is a reflection of my skill with the shell at this > point. This, on the other hand, I find even more consistent: if the code can't be effectively inspected from the interactive interpreter, that's a sure sign that its external interfaces are poor or its internal dependencies too tightly coupled; or more likely both. Fixing that set of problems is both useful for debugging *and* good design. -- \ ?Alternative explanations are always welcome in science, if | `\ they are better and explain more. Alternative explanations that | _o__) explain nothing are not welcome.? ?Victor J. Stenger, 2001-11-05 | Ben Finney From chris at simplistix.co.uk Tue Aug 25 10:53:03 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 25 Aug 2009 15:53:03 +0100 Subject: Even more inconsistent sitecustomize.py importing with PYTHONPATH rolled in... In-Reply-To: <4A93F921.9080904@simplistix.co.uk> References: <4A93F921.9080904@simplistix.co.uk> Message-ID: <4A93FACF.9000608@simplistix.co.uk> Chris Withers wrote: > However, if I do: > > ~/folder$/usr/local/bin/python2.5 script > > ...sitecustomize.py IS imported! However, the following doesn't import sitecustomize.py: ~/folder$ ./script While the following DOES import sitecustomize.py: ~/folder$ export PYTHONPATH= ~/folder$ ./script Bizarrely, none of the following import sitecustomize.py: ~$ export PYTHONPATH=~/folder ~$ ./script ~$ export PYTHONPATH=~/folder/ ~$ ./script ~$ export PYTHONPATH=~/folder ~/folder$ ./script ~$ export PYTHONPATH=~/folder/ ~/folder$ ./script Does anyone have any clue why there's such a huge level of inconsistency here?! Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From chris at simplistix.co.uk Tue Aug 25 11:05:14 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 25 Aug 2009 16:05:14 +0100 Subject: Even more inconsistent sitecustomize.py importing with PYTHONPATH rolled in... In-Reply-To: <4A93FACF.9000608@simplistix.co.uk> References: <4A93F921.9080904@simplistix.co.uk> <4A93FACF.9000608@simplistix.co.uk> Message-ID: <4A93FDAA.2050206@simplistix.co.uk> Chris Withers wrote: > Bizarrely, none of the following import sitecustomize.py: > > ~$ export PYTHONPATH=~/folder > ~$ ./script > > ~$ export PYTHONPATH=~/folder/ > ~$ ./script > > ~$ export PYTHONPATH=~/folder > ~/folder$ ./script > > ~$ export PYTHONPATH=~/folder/ > ~/folder$ ./script Okay, brain fail on my part, these do work, the others are still as described though... Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From Scott.Daniels at Acm.Org Tue Aug 25 11:26:44 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 25 Aug 2009 08:26:44 -0700 Subject: Putting together a larger matrix from smaller matrices In-Reply-To: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> References: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> Message-ID: <95-dnVK31vsFnQnXnZ2dnUVZ_qmdnZ2d@pdx.net> Matjaz Bezovnik wrote: If you are using numpy (which it sounds like you are): IDLE 2.6.2 >>> import numpy as np >>> v = np.array([[0,1,2],[3,4,5],[6,7,8]], dtype=float) >>> v array([[ 0., 1., 2.], [ 3., 4., 5.], [ 6., 7., 8.]]) >>> w = np.array([[10,11,12],[13,14,15],[16,17,18]], dtype=float) >>> w array([[ 10., 11., 12.], [ 13., 14., 15.], [ 16., 17., 18.]]) >>> r = np.zeros((6,6)) >>> r array([[ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.]]) >>> r[:3,:3] = v >>> r array([[ 0., 1., 2., 0., 0., 0.], [ 3., 4., 5., 0., 0., 0.], [ 6., 7., 8., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.]]) >>> r[3:,3:] = w >>> r array([[ 0., 1., 2., 0., 0., 0.], [ 3., 4., 5., 0., 0., 0.], [ 6., 7., 8., 0., 0., 0.], [ 0., 0., 0., 10., 11., 12.], [ 0., 0., 0., 13., 14., 15.], [ 0., 0., 0., 16., 17., 18.]]) >>> In general, make the right-sized array of zeros, and at various points: and you can ssign to subranges of the result array: N = 3 result = np.zeros((len(parts) * N, len(parts) * N), dtype=float) for n, chunk in enumerate(parts): base = n * 3 result[base : base + 3, base : base + 3] = chunk --Scott David Daniels Scott.Daniels at Acm.Org From steve at REMOVE-THIS-cybersource.com.au Tue Aug 25 11:28:31 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Aug 2009 15:28:31 GMT Subject: inconsistent sitecustomize.py importing... References: Message-ID: <02a3f329$0$20629$c3e8da3@news.astraweb.com> On Tue, 25 Aug 2009 15:45:53 +0100, Chris Withers wrote: > Hi All, > > Give this sitecustomize.py: [...] > What gives?! Perhaps this? http://bugs.python.org/issue1734860 -- Steven From no.email at please.post Tue Aug 25 11:33:26 2009 From: no.email at please.post (kj) Date: Tue, 25 Aug 2009 15:33:26 +0000 (UTC) Subject: Need help with Python scoping rules Message-ID: I have many years of programming experience, and a few languages, under my belt, but still Python scoping rules remain mysterious to me. (In fact, Python's scoping behavior is the main reason I gave up several earlier attempts to learn Python.) Here's a toy example illustrating what I mean. It's a simplification of a real-life coding situation, in which I need to initialize a "private" class variable by using a recursive helper function. class Demo(object): def fact(n): if n < 2: return 1 else: return n * fact(n - 1) _classvar = fact(5) This code fails to compile, with the error "global name 'fact' not defined". Scanning the Python Language Reference page I see nothing that would suggest to me a discussion of Python's scoping rules, let alone anything that would help me solve the specific problem above. I'm sure it's in there, *somewhere*, but it's anyone's guess where. Likewise, my book, Beazley's "Python: Essential Reference" is of no help. I don't doubt that the answer to my question "is in there, *somewhere*", but finding it (without reading the book sequentially from page 1) is a tall order. All that's left is trial-and-error, the worst kind of programming. And still I can't find the right way to do this... I've tried every variant of this code that I can imagine, including decorating fact with @staticmethod or @classmethod, etc., etc. (In the latter case, I get cryptic errors saying that the staticmethod or classmethod object is not callable. Or something like that.) Needless to say, I'm pretty beat by this point. Any help would be appreciated. Thanks, kynn From mbezovnik at freenet.si Tue Aug 25 11:37:09 2009 From: mbezovnik at freenet.si (Matjaz Bezovnik) Date: Tue, 25 Aug 2009 17:37:09 +0200 Subject: Putting together a larger matrix from smaller matrices References: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> <95-dnVK31vsFnQnXnZ2dnUVZ_qmdnZ2d@pdx.net> Message-ID: On Tue, 25 Aug 2009 08:26:44 -0700, Scott David Daniels wrote: >Matjaz Bezovnik wrote: > >If you are using numpy (which it sounds like you are): > >IDLE 2.6.2 > >>> import numpy as np > >>> v = np.array([[0,1,2],[3,4,5],[6,7,8]], dtype=float) > >>> v >array([[ 0., 1., 2.], > [ 3., 4., 5.], > [ 6., 7., 8.]]) > >>> w = np.array([[10,11,12],[13,14,15],[16,17,18]], dtype=float) > >>> w >array([[ 10., 11., 12.], > [ 13., 14., 15.], > [ 16., 17., 18.]]) > >>> r = np.zeros((6,6)) > >>> r >array([[ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.]]) > >>> r[:3,:3] = v > >>> r >array([[ 0., 1., 2., 0., 0., 0.], > [ 3., 4., 5., 0., 0., 0.], > [ 6., 7., 8., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.]]) > >>> r[3:,3:] = w > >>> r >array([[ 0., 1., 2., 0., 0., 0.], > [ 3., 4., 5., 0., 0., 0.], > [ 6., 7., 8., 0., 0., 0.], > [ 0., 0., 0., 10., 11., 12.], > [ 0., 0., 0., 13., 14., 15.], > [ 0., 0., 0., 16., 17., 18.]]) > >>> > >In general, make the right-sized array of zeros, and at various points: >and you can ssign to subranges of the result array: > > N = 3 > result = np.zeros((len(parts) * N, len(parts) * N), dtype=float) > for n, chunk in enumerate(parts): > base = n * 3 > result[base : base + 3, base : base + 3] = chunk > >--Scott David Daniels >Scott.Daniels at Acm.Org Scott, thank you very much for the snippet. It is exactly what I looked for; simple to read and obvious as to what it does even a month later to a non-pythonist! Matjaz From ndbecker2 at gmail.com Tue Aug 25 11:49:03 2009 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 25 Aug 2009 11:49:03 -0400 Subject: Graph library recommendations for large graphs References: Message-ID: VanL wrote: > I am working on a project that will require building and querying large > graph objects (initially 8M nodes, 30-40M edges; eventually 40M nodes, > 100M edges). NetworkX seems to be the most popular, but I am concerned > that a dict representation for nodes would use too much memory -- my > initial tests suggest that a graph with 3M nodes and 12M edges creates > substantial memory pressure on my machine. > > Can anybody who has worked with large graphs before give a recommendation? > > Thanks, > > Van > How about python-igraph? From python at mrabarnett.plus.com Tue Aug 25 12:00:35 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 25 Aug 2009 17:00:35 +0100 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile In-Reply-To: <4A93F721.10104@gmail.com> References: <4A93F721.10104@gmail.com> Message-ID: <4A940AA3.8080003@mrabarnett.plus.com> Ryniek90 wrote: > Referring to my earlier posts: > http://groups.google.pl/group/comp.lang.python/browse_thread/thread/4e34f995800f5352?hl=pl > > > and > > http://groups.google.pl/group/comp.lang.python/browse_thread/thread/abf5573b8fceb37e?hl=pl# > > > I've dealt with those errors. but now have another. > When my backup scripts starts to backup chosen file, python gave me > Traceback: > > " > C:\Users\Ryniek's WinSe7en\Documents\My > Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba > ckuper.py -f F:\APLIKACJE\nowegg.exe F:\ MyGGBackup > Checking permissions for reading and writing... > Have permissions on [F:\APLIKACJE\nowegg.exe] for reading. > Have permissions on [F:\] for writing. > Preparing for backup [nowegg.exe]... > Starting backup... > Now adding [nowegg.exe]... > Traceback (most recent call last): > File "backuper.py", line 197, in > main_meth() > File "backuper.py", line 189, in main_meth > paq.backup_file(pars.options.filename[0], pars.options.filename[1], > pars.options.filename[2]) > File "backuper.py", line 127, in backup_file > backup_obj.add(read_bin_obj) > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python > 2.6\lib\tarfile.py", line 1948, in add > if self.name is not None and os.path.abspath(name) == self.name: > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\ntpath.py", > line 458, in abspath > path = _getfullpathname(path) > TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str > " > > I've searched over google, but found only that is bug in Python ( > http://bugs.python.org/issue4071 - in that issue bug is inside Python > 2.5.2 - i've got ActiveState Active Python with core Python 2.6.2), and > another info: *http://tinyurl.com/lvyn7o and > **http://tinyurl.com/kn49vk > * > > Here's my script code: > *http://paste.ubuntu.com/259310/ > > *Shouldn't that bug be patched already :-? Are you giving it the contents of the file when it's actually expecting the filename? From hendrik at microcorp.co.za Tue Aug 25 12:02:31 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 25 Aug 2009 18:02:31 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a93e575$0$298$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a93e575$0$298$14726298@news.sunsite.dk> Message-ID: <200908251802.31556.hendrik@microcorp.co.za> On Tuesday 25 August 2009 15:21:16 Esben von Buchwald wrote: > Dennis Lee Bieber wrote: > > On Mon, 24 Aug 2009 17:32:23 +0200, Esben von Buchwald > > declaimed the following in > > > > gmane.comp.python.general: > >> I'm new to python, what is an after function and an after call? Couldn't > >> find excact answer on google...? Do you have a link to some docs? > > > > They would be particular to whatever GUI/event library is in use. > > They aren't part of Python itself. > > This is how the accelerometer is accessed > http://pys60.garage.maemo.org/doc/s60/node59.html > > I found this called "after"... > http://pys60.garage.maemo.org/doc/s60/node12.html > > would that be usable? Probably > > If so, how? This is a guess, for your device, but I suspect something along these lines: t = Ao_timer() cb = t.after(100,thing_that_does_the_work(with_its_arguments)) Lots of assumptions here - the 100 should give you a tenth of a second... Don't know what the arguments look like, and if you need to pass an instance (like self) - that would depend on where you are calling it from. Play and see :-) You should also be able to cancel the callback like this: t.cancel(cb) If you do it before the time out - Hendrik From nicola.larosa at gmail.com Tue Aug 25 12:06:37 2009 From: nicola.larosa at gmail.com (Nicola Larosa (tekNico)) Date: Tue, 25 Aug 2009 09:06:37 -0700 (PDT) Subject: Code formatting question: conditional expression References: Message-ID: <421c8c9d-efb5-4e70-9321-51736b42bc9a@g10g2000yqh.googlegroups.com> John Posner wrote: > Is there any consensus on how to format a conditional expression > that is too long for one line? Here's my take: excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True ) if total > P.BASE else None -- Nicola Larosa - http://www.tekNico.net/ Nobody knows everything, and nobody is expected to be perfect in the Ubuntu community (except of course the SABDFL). - https://launchpad.net/codeofconduct/1.0 From martin.hellwig at dcuktec.org Tue Aug 25 12:09:09 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 25 Aug 2009 17:09:09 +0100 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <9t2dnVFZo-g4kQnXnZ2dnUVZ8uidnZ2d@bt.com> kj wrote: > > Here's a toy example illustrating what I mean. It's a simplification > of a real-life coding situation, in which I need to initialize a > "private" class variable by using a recursive helper function. eh? > > class Demo(object): > def fact(n): > if n < 2: > return 1 > else: > return n * fact(n - 1) > > _classvar = fact(5) > Sorry still doesn't make sense, I'll give it a try though: class Demo(object): """Apparently a 'real-life coding situation'""" def __init__(self): # Look at http://docs.python.org/tutorial/classes.html # for init explanation. self.__class_var = self.fact(5) def fact(self, number): """Look at http://docs.python.org/tutorial/classes.html why you need self.""" if number < 2: return(1) else: return_value = number * self.fact(number -1) return(return_value) TEST = Demo() # Print the 'private' class variable print(TEST._Demo__class_var) -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From garrickp at gmail.com Tue Aug 25 12:11:47 2009 From: garrickp at gmail.com (Falcolas) Date: Tue, 25 Aug 2009 09:11:47 -0700 (PDT) Subject: your favorite debugging tool? References: Message-ID: <97f6dd5f-ffa7-4d73-8545-378301a5f6e1@13g2000prl.googlegroups.com> On Aug 23, 1:21?am, Hendrik van Rooyen wrote: > On Saturday 22 August 2009 16:49:22 Aahz wrote: > > > In article , > > > Esmail ? wrote: > > >What is your favorite tool to help you debug your code? I've been > > >getting along with 'print' statements but that is getting old and > > >somewhat cumbersome. > > > Despite the fact that I've been using Python for more than a decade, > > print is still my mainstay (or possibly logging to a file). > > Same here, although I have not been abusing python for as long as Aahz has > been using it. > > ... > > And the final arbiter is of course the interactive prompt. > > - Hendrik The only thing I would add to these comments is the fact that writing helper functions for using print with complicated routines is very simple, though perhaps not obvious. For example, consider the following for unrolling list comprehensions or generators without having to re-write them: def trace(iterable): for x in iterable: print x yield x ~G From deets at nospam.web.de Tue Aug 25 12:14:26 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 18:14:26 +0200 Subject: Need help with Python scoping rules References: Message-ID: <7figv3F2m3p0dU1@mid.uni-berlin.de> kj wrote: > > > > I have many years of programming experience, and a few languages, > under my belt, but still Python scoping rules remain mysterious to > me. (In fact, Python's scoping behavior is the main reason I gave > up several earlier attempts to learn Python.) > > Here's a toy example illustrating what I mean. It's a simplification > of a real-life coding situation, in which I need to initialize a > "private" class variable by using a recursive helper function. > > class Demo(object): > def fact(n): > if n < 2: > return 1 > else: > return n * fact(n - 1) > > _classvar = fact(5) > > This code fails to compile, with the error "global name 'fact' not > defined". > > Scanning the Python Language Reference page I see nothing that > would suggest to me a discussion of Python's scoping rules, let > alone anything that would help me solve the specific problem above. > I'm sure it's in there, *somewhere*, but it's anyone's guess where. > > Likewise, my book, Beazley's "Python: Essential Reference" is of > no help. I don't doubt that the answer to my question "is in there, > *somewhere*", but finding it (without reading the book sequentially > from page 1) is a tall order. > > All that's left is trial-and-error, the worst kind of programming. > And still I can't find the right way to do this... I've tried > every variant of this code that I can imagine, including decorating > fact with @staticmethod or @classmethod, etc., etc. (In the latter > case, I get cryptic errors saying that the staticmethod or classmethod > object is not callable. Or something like that.) Classes are not scopes. So the above doesn't work because name resolution inside functions/methods looks for local variables first, then for the *global* scope. There is no class-scope-lookup. If you want anything else, you need to qualify it with a full name, Demo.fact. Which isn't working for your example because "Demo" isn't available yet. But if you insist on the above methodology, you can do this: class Demo(object): def fact(n): def inner(n): if n < 2: return 1 else: return n * inner(n - 1) return inner(n) _classvar = fact(5) This makes inner a *local* variable, which is found. Diez From gordon at panix.com Tue Aug 25 12:19:33 2009 From: gordon at panix.com (John Gordon) Date: Tue, 25 Aug 2009 16:19:33 +0000 (UTC) Subject: Web Services examples using "raw" xml? References: <4a936e84$0$31337$9b4e6d93@newsspool4.arcor-online.net> Message-ID: In <4a936e84$0$31337$9b4e6d93 at newsspool4.arcor-online.net> Stefan Behnel writes: > > I tried WSDL.Proxy() from the SOAPpy package and eventually end up > > with this error: > > > > xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 6 > Is that while parsing the WSDL file? Have you tried pushing it through an > XML parser yourself (or opening it with an XML editor) to see if it really > is XML? The 'invalid token' error happens if the argument to WSDL.Proxy() is a string containing a URL beginning with https. (It doesn't happen with a http URL, but I'm stuck with https.) As a next step, I grabbed the content from the https url in a browser, saved it to a file, inserted it into the python code as a large string, and passed that string to WSDL.Proxy(). That produced a KeyError 'targetNamespace' from this snippet of XML: I looked at the code and it apparently requires that the parent tag of have a targetNamespace attribute. So I made one up and added it, like so: I have no idea if this was the right thing to do, but it did let me advance to the next error: Traceback (most recent call last): File "soappytest.py", line 1020, in ? server = jrgWSDL.Proxy(wsdlFile) File "/home/gordonj/wsdl/jrgSOAPpy/jrgWSDL.py", line 75, in __init__ service = self.wsdl.services[0] File "/home/gordonj/wsdl/jrgwstools/Utility.py", line 631, in __getitem__ return self.list[key] IndexError: list index out of range After poking around in the code a bit more, I think that self.wsdl.services is supposed to be a collection of all the services offered by the wsdl, but it's actually empty, which is why it throws an error when it tries to access the first element. So that's where I'm stuck at the moment. I have no idea why self.wsdl.services isn't getting populated correctly -- or even if that's the real problem! Any suggestions? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From jeanmichel at sequans.com Tue Aug 25 12:36:28 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 25 Aug 2009 18:36:28 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A94130C.9050809@sequans.com> kj wrote: > > I have many years of programming experience, and a few languages, > under my belt, but still Python scoping rules remain mysterious to > me. (In fact, Python's scoping behavior is the main reason I gave > up several earlier attempts to learn Python.) > > Here's a toy example illustrating what I mean. It's a simplification > of a real-life coding situation, in which I need to initialize a > "private" class variable by using a recursive helper function. > > class Demo(object): > def fact(n): > if n < 2: > return 1 > else: > return n * fact(n - 1) > > _classvar = fact(5) > > This code fails to compile, with the error "global name 'fact' not > defined". > [snip] fact is defined within the Demo class, so to access it, you'll need to prefix it with Demo: _classvar = Demo.fact(5). The problem is, Demo will raise a NameError exception. The solution is pretty simple, cause your fact function seems to be unrelated to the Demo class : def _fact(n): # some code class Demo(object): _classvar = _fact(5) It may happen that you *want* your fact within the Demo, in you example it's not that obvious, but I think Java would allow such following patern: class Color: def __init__(self, r, g,b): pass BLACK = Color(0,0,0) It make sens from a design point of view to put BLACK in the Color namespace. But I don't think it's possible with python. You could trick the system using inheritance: class Chrome: def __init__(self, r,g,b) pass Putting all your code in the Chrome class then: class Color(Chrome): BLACK = Chrome(0,0,0) I'm not sure this is satisfying. JM From jeanmichel at sequans.com Tue Aug 25 12:47:20 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 25 Aug 2009 18:47:20 +0200 Subject: Need help with Python scoping rules In-Reply-To: <7figv3F2m3p0dU1@mid.uni-berlin.de> References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <4A941598.3000207@sequans.com> Diez B. Roggisch wrote > Classes are not scopes. > > Too bad, could have been handy. JM From contact at xavierho.com Tue Aug 25 12:55:41 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 26 Aug 2009 02:55:41 +1000 Subject: Need help with Python scoping rules In-Reply-To: <4A94130C.9050809@sequans.com> References: <4A94130C.9050809@sequans.com> Message-ID: <2d56febf0908250955h6aedb3efp52168a719bfaf5e5@mail.gmail.com> I'm not really quite sure what voodoo I did here, but my code seems to work in Python 3.1.1 in the following way: class Demo(object): def func(self, n): return n * 5 _f = func(None, 5) d = Demo() print(d._f) print(d.func(5)) # OUTPUT 25 25 So, hmm? Regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Aug 25 12:55:41 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 18:55:41 +0200 Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <7fijcdF2kheecU1@mid.uni-berlin.de> Jean-Michel Pichavant wrote: > Diez B. Roggisch wrote >> Classes are not scopes. >> >> > Too bad, could have been handy. Nope. Because then a lot of people would write something like this: class Foo(object): def bar(self): bar() # note the missing self. And this would lead to errors because self was missing from the call to "bar". And you'd need a disambiguation for methodname/global-name-clashes. The global-statement would work, but then code could break when all of a sudden a subclass defines a method that hitherto was only known as global. So via subclassing, you introduce *arbitray* and hard to debug errors. No. I'm certain, not a good idea. Diez From contact at xavierho.com Tue Aug 25 12:58:58 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 26 Aug 2009 02:58:58 +1000 Subject: Need help with Python scoping rules In-Reply-To: <7figv3F2m3p0dU1@mid.uni-berlin.de> References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <2d56febf0908250958q96905caw4185c20b9e12cd33@mail.gmail.com> On Wed, Aug 26, 2009 at 2:14 AM, Diez B. Roggisch wrote: > > Classes are not scopes. > > So the above doesn't work because name resolution inside functions/methods > looks for local variables first, then for the *global* scope. There is no > class-scope-lookup. Sorry, I'm coming here with sincere ignorance. If local variables and global variables are not "scopes", then what would it be? Cheers, -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From sdementen at gmail.com Tue Aug 25 13:25:27 2009 From: sdementen at gmail.com (seb) Date: Tue, 25 Aug 2009 10:25:27 -0700 (PDT) Subject: conditional for-statement References: Message-ID: On Aug 23, 11:02?pm, Chris Rebert wrote: > On Sun, Aug 23, 2009 at 1:36 PM, seb wrote: > > On Aug 23, 6:18?pm, John Posner wrote: > >> >> Hi, > > >> >> i was wondering if there is a syntax alike: > > >> >> for i in range(10) if i > 5: > >> >> ? ? print i > > >> > You can write > > >> > for i in filter(lambda i: i > 5, range(10)): > >> > ? ? print i > > >> > but > > >> > for i in range(10): > >> > ? ? if i > 5: > >> > ? ? ? ? print i > > >> > it' better readable, and > > >> > for i in range(6,10): > >> > ? ? print i > > >> > it's event better. > > >> How about using a generator expression instead of a list? > > >> ? for i in (x for x in range(10) if x > 5): > >> ? ? ? print i > > >> -John > > > Indeed, but we could have the same syntax than for generators but > > directly in the for statement as in > > for variable in generator if condition: > > ? ?body > > > Is there a special reason for not doing so ? A rejected PEP ? > > It's not been added since it's completely unnecessary (see the several > alternatives already presented by others). > There have been a few other mailinglist threads on adding essentially > the same syntax. None have proved fruitful. > > Cheers, > Chris > --http://blog.rebertia.com- Hide quoted text - > > - Show quoted text - On Aug 23, 11:02 pm, Chris Rebert wrote: > On Sun, Aug 23, 2009 at 1:36 PM, seb wrote: > > On Aug 23, 6:18 pm, John Posner wrote: > >> >> Hi, > > >> >> i was wondering if there is a syntax alike: > > >> >> for i in range(10) if i > 5: > >> >> print i > > >> > You can write > > >> > for i in filter(lambda i: i > 5, range(10)): > >> > print i > > >> > but > > >> > for i in range(10): > >> > if i > 5: > >> > print i > > >> > it' better readable, and > > >> > for i in range(6,10): > >> > print i > > >> > it's event better. > > >> How about using a generator expression instead of a list? > > >> for i in (x for x in range(10) if x > 5): > >> print i > > >> -John > > > Indeed, but we could have the same syntax than for generators but > > directly in the for statement as in > > for variable in generator if condition: > > body > > > Is there a special reason for not doing so ? A rejected PEP ? > > It's not been added since it's completely unnecessary (see the several > alternatives already presented by others). > There have been a few other mailinglist threads on adding essentially > the same syntax. None have proved fruitful. > > Cheers, > Chris > --http://blog.rebertia.com- Hide quoted text - > > - Show quoted text - Tx Chris for your reply ! i am still a bit puzzle by the following. I read in http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generators """Python 3.0 unifies all collection types by introducing dict and set comprehensions, similar to list comprehensions: >>> [ n*n for n in range(5) ] # regular list comprehension [0, 1, 4, 9, 16] >>> >>> { n*n for n in range(5) } # set comprehension {0, 1, 4, 16, 9} >>> >>> { n: n*n for n in range(5) } # dict comprehension {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} """ and we can add to this list the quite similar syntax for generator expressions. On all these loop constructs, one can consistenly add filtering on a condition by adding an "if ..." after the "for ... in ..." part (and it looks to me difficult to argue, for instance, that we should not allow filtering for dict comprehesion because we could get the same result by some other construct) If the "if ..." part after the "for ... in ..." is so much used in all these list/dict/set comprehensions and in the generator expressions, it makes sense to me to have it also for the "for as a statement" syntax : [ n*n for n in range(10) if n%3 == 0] { n*n for n in range(10) if n%3 == 0} { n: n*n for n in range(10) if n%3 == 0} ( n*n for n in range(10) if n%3 == 0) for n in range(10) if n%3 == 0: print n*n In fact, we often see the list comprehension [ n*n for n in range(10) if n%3 == 0] explained as being equivalent to l = [] for n in range(10): if n%3 == 0: l.append(n) We could as consistenly explain that the syntax for n in range(10) if n%3==0: body means for n in range(10): if n%3==0: body This syntax has also the benefit of avoiding an extra level of indentation (the one for the if) that bears no real meaning on a structural level. Maybe a PEP could do the job... S?bastien From sdementen at gmail.com Tue Aug 25 13:30:15 2009 From: sdementen at gmail.com (seb) Date: Tue, 25 Aug 2009 10:30:15 -0700 (PDT) Subject: conditional for-statement References: Message-ID: <40ae96a4-6f86-4daa-a06b-5556339cb032@c2g2000yqi.googlegroups.com> On Aug 24, 12:05?am, Mel wrote: > seb wrote: > > On Aug 23, 6:18 pm, John Posner wrote: > [ ... ] > >> How about using a generator expression instead of a list? > > >> for i in (x for x in range(10) if x > 5): > >> print i > > >> -John > > > Indeed, but we could have the same syntax than for generators but > > directly in the for statement as in > > for variable in generator if condition: > > ? ? body > > > Is there a special reason for not doing so ? A rejected PEP ? > > Well, the Zen of Python does say > > There should be one-- and preferably only one --obvious way to do it. > > Beyond that, I refer you to Gerald M. Weinberg's _The Psychology of Computer > Programming_, specifically chapters 11 and 12, about Programming Languages, > and their design. > > The proposal creates an case where one particular pair of syntactic > constructs can be mooshed together. ?OK for them, but everything else > becomes an exception; what about > > while a==c if b != d: > > why not > > if b != d while a==c: > what would be the unambiguous meaning of any of these forms ? they could be interesting but I do not understand them (yet!). > or > > for a in range(7) if os.name == 'posix': > > It winds up burdening the programmers with remembering which constructs are > and which are not mooshable. ?Weinberg gave an example: FORTRAN had some > stringent rules for what expressions were and were not allowed as array > subscripts. ?The result was that many programmers couldn't remember all the > rules, and often avoided using legal forms, having forgotten they were > legal. indeed, the language features should stay as orthogonal as possible (at least as a general rule) > > Maybe the line was already crossed when list comprehensions came into being, > still, the damage is localized in a particular context: building a list. ?It > isn't out creating wild options in the program control flow at large. > indeed and it proved to be very useful & successful. one cannot recommend to mix all features together as a general rule but using common sense and practice, we can have some exceptions that are definitely worth. > ? ? ? ? Mel.- Hide quoted text - > > - Show quoted text - From stefan_ml at behnel.de Tue Aug 25 13:53:46 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 25 Aug 2009 19:53:46 +0200 Subject: Web Services examples using "raw" xml? In-Reply-To: References: <4a936e84$0$31337$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <4a94252a$0$31870$9b4e6d93@newsspool3.arcor-online.net> John Gordon wrote: > Any suggestions? Well, yes, see the link I posted. http://effbot.org/zone/element-soap.htm That might actually be the easiest way to get your stuff done, and it avoids external dependencies (well, except for ElementTree, if you continue to use Python <= 2.4). Stefan From jjposner at optimum.net Tue Aug 25 14:11:32 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 25 Aug 2009 14:11:32 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A942954.7070702@optimum.net> Diez said: > > Classes are not scopes. > > So the above doesn't work because name resolution inside functions/methods > looks for local variables first, then for the *global* scope. There is no > class-scope-lookup. But http://docs.python.org/tutorial/classes.html says, in Section 9.3 "A First Look at Classes": When a class definition is entered, a new namespace is created, and used as the local scope ? thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here. The following example confirms this: class Spam(object): clsvar_1 = 555 clsvar_2 = clsvar_1 + 222 def __init__(self): print "Spam instance initialized" sp = Spam() print sp.clsvar_1, sp.clsvar_2 output: Spam instance initialized 555 777 Does the OP (kj) have a legitimate gripe, though? I confess that I know nothing about Python's implementation -- I'm strictly a user. So it's just a suspicion of mine that something special enables a recursive function definition to refer to the function's own name before the definition has been completed. It works at the module-namespace (i.e. global) level, and Diez's "toy example" shows that it works at function-namespace level: class Demo(object): def fact(n): def inner(n): if n < 2: return 1 else: return n * inner(n - 1) return inner(n) _classvar = fact(5) So why can't it work at the class-namespace level, too? (BTW, Diez, your toy example is another demonstration that there *is* a class-scope-lookup: the "def" statement binds the name "fact" in the class scope, and the assignment statement looks up the name "fact" in that scope.) -John From rami.chowdhury at gmail.com Tue Aug 25 14:17:49 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 25 Aug 2009 11:17:49 -0700 Subject: conditional for-statement In-Reply-To: References: Message-ID: > We could as consistenly explain that the syntax > > for n in range(10) if n%3==0: > body > > means > > for n in range(10): > if n%3==0: > body > > This syntax has also the benefit of avoiding an extra level of > indentation (the one for the if) that bears no real meaning on a > structural level. > I'm sorry, I don't see what you mean about avoiding the extra level of indentation? I can see a very real structural and logical distinction that the if-block makes, and IMO it's a good thing that that needs to be set apart. On Tue, 25 Aug 2009 10:25:27 -0700, seb wrote: > > Tx Chris for your reply ! > > i am still a bit puzzle by the following. > > I read in > http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generators > > """Python 3.0 unifies all collection types by introducing dict and set > comprehensions, similar to list comprehensions: > >>>> [ n*n for n in range(5) ] # regular list comprehension > [0, 1, 4, 9, 16] >>>> >>>> { n*n for n in range(5) } # set comprehension > {0, 1, 4, 16, 9} >>>> >>>> { n: n*n for n in range(5) } # dict comprehension > {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} > """ > and we can add to this list the quite similar syntax for generator > expressions. > > On all these loop constructs, one can consistenly add filtering on a > condition by adding an "if ..." after the "for ... in ..." part (and > it looks to me difficult to argue, for instance, that we should not > allow filtering for dict comprehesion because we could get the same > result by some other construct) > > If the "if ..." part after the "for ... in ..." is so much used in all > these list/dict/set comprehensions and in the generator expressions, > it makes sense to me to have it also for the "for as a statement" > syntax : > [ n*n for n in range(10) if n%3 == 0] > { n*n for n in range(10) if n%3 == 0} > { n: n*n for n in range(10) if n%3 == 0} > ( n*n for n in range(10) if n%3 == 0) > for n in range(10) if n%3 == 0: > print n*n > > In fact, we often see the list comprehension [ n*n for n in range(10) > if n%3 == 0] explained as being equivalent to > l = [] > for n in range(10): > if n%3 == 0: > l.append(n) > > We could as consistenly explain that the syntax > > for n in range(10) if n%3==0: > body > > means > > for n in range(10): > if n%3==0: > body > > This syntax has also the benefit of avoiding an extra level of > indentation (the one for the if) that bears no real meaning on a > structural level. > > Maybe a PEP could do the job... > > S?bastien -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From sturlamolden at yahoo.no Tue Aug 25 14:25:19 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 25 Aug 2009 11:25:19 -0700 (PDT) Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> <4224e772-5b67-4eea-9bdf-a7d2bf7cc128@c14g2000yqm.googlegroups.com> <864e2d5f-0855-4f35-a78c-b09054e75f0d@w41g2000yqb.googlegroups.com> Message-ID: On 25 Aug, 13:33, Piet van Oostrum wrote: > I have heard about that also, but is there a Python implementation that > uses this? (Just curious, I am not using Windows.) On Windows we have three different versions of Python 2.6: * Python 2.6 for Win32/64 (from python.org) does not have os.fork. * Python 2.6 for Cygwin has os.fork, but it is non-COW and sluggish. * Python 2.6 for SUA has a fast os.fork with copy-on-write. You get Python 2.6.2 for SUA prebuilt by Microsoft from http://www.interopsystems.com. Using Python 2.6 for SUA is not without surprices: For example, the process is not executed from the Win32 subsystem, hence the Windows API is inaccessible. That means we cannot use native Windows GUI. Instead we must run an X11 server on the Windows subsystem (e.g. X- Win32), and use the Xlib SUA has installed. You can compare SUA to a stripped down Linux distro, on which you have to build and install most of the software you want to use. I do not recommend using Python for SUA instead of Python for Windows unless you absolutely need a fast os.fork or have a program that otherwise requires Unix. But for running Unix apps on Windows, SUA is clearly superior to Cygwin. Licencing is also better: Programs compiled against Cygwin libraries are GPL (unless you buy a commercial license). Program compiled against SUA libraries are not. Sturla Molden From nospam at nospam.com Tue Aug 25 14:30:27 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 25 Aug 2009 20:30:27 +0200 Subject: Python for professsional Windows GUI apps? References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: On Tue, 25 Aug 2009 13:24:39 +0200, Wolfgang Keller wrote: >The area of _desktop_ database application development indeed looks like a vast and very hostile desert in the Python landscape. > >The only framework that seems to be worth trying is Dabo. Unfortunately there's little documentation, and that's mostly outdated. > >There's also Kiwi, but that's even less well documented. > >And GNU Enterprise essentially seems to be dead. Combined with the comment above about issues with printing, it looks like Python for GUI apps isn't a very good idea :-/ I'd be interested in checking out commercial applications written in Python for the Windows OS, if there are any. Thank you. From bbxx789_05ss at yahoo.com Tue Aug 25 14:36:46 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 25 Aug 2009 11:36:46 -0700 (PDT) Subject: Need help with Python scoping rules References: Message-ID: <62d4c548-c45f-4345-b9b2-42a7ba7a309a@g1g2000pra.googlegroups.com> On Aug 25, 12:11?pm, John Posner wrote: > Diez said: > > > > > Classes are not scopes. > > > So the above doesn't work because name resolution inside functions/methods > > looks for local variables first, then for the *global* scope. There is no > > class-scope-lookup. > > Buthttp://docs.python.org/tutorial/classes.htmlsays, in Section 9.3 "A > First Look at Classes": > > When a class definition is entered, a new namespace is created, > and used as the local scope ? thus, all assignments to local variables > go into this new namespace. In particular, function definitions bind > the name of the new function here. > > The following example confirms this: > > class Spam(object): > clsvar_1 = 555 > clsvar_2 = clsvar_1 + 222 > > def __init__(self): > print "Spam instance initialized" > > sp = Spam() > print sp.clsvar_1, sp.clsvar_2 > > output: > Spam instance initialized > 555 777 > > Does the OP (kj) have a legitimate gripe, though? I confess that I know I guess a counter example would be something like this: y = "hello" class Demo(object): y = "goodbye" def __init__(self): self.x = 10 print y Demo() --output:-- hello > > nothing about Python's implementation -- I'm strictly a user. So it's > just a suspicion of mine that > something special enables a recursive function definition to refer to > the function's own name before the definition has been completed. > python ignores the names inside a function when it creates the function. This "program" will not produce an error: def f(): print x python parses the file and creates the function object and assigns the function object to the variable f. It's not until you execute the function that python will raise an error. The same thing happens with the recursive function. From david at boddie.org.uk Tue Aug 25 14:37:35 2009 From: david at boddie.org.uk (David Boddie) Date: Tue, 25 Aug 2009 20:37:35 +0200 Subject: Python for professsional Windows GUI apps? References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: On Tuesday 25 August 2009 13:24, Wolfgang Keller wrote: > The area of _desktop_ database application development indeed looks like a > vast and very hostile desert in the Python landscape. > > The only framework that seems to be worth trying is Dabo. Unfortunately > there's little documentation, and that's mostly outdated. > > There's also Kiwi, but that's even less well documented. > > And GNU Enterprise essentially seems to be dead. There's also Camelot, if that's the kind of thing you're after: http://www.conceptive.be/projects/camelot David From sturlamolden at yahoo.no Tue Aug 25 14:39:14 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 25 Aug 2009 11:39:14 -0700 (PDT) Subject: Putting together a larger matrix from smaller matrices References: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> <95-dnVK31vsFnQnXnZ2dnUVZ_qmdnZ2d@pdx.net> Message-ID: <7df5f26b-5f31-4e93-b873-946c99d9a5e4@w41g2000yqb.googlegroups.com> On 25 Aug, 17:37, Matjaz Bezovnik wrote: > Scott, thank you very much for the snippet. > > It is exactly what I looked for; simple to read and obvious as to what > it does even a month later to a non-pythonist! Since you were talking about matrices, observe that numpy has a matrix subclass of ndarray, which e.g. changes the meaning of the * operator mean indicate matrix multiplication. Thus, >>> import numpy as np >>> np.eye(4) array([[ 1., 0., 0., 0.], [ 0., 1., 0., 0.], [ 0., 0., 1., 0.], [ 0., 0., 0., 1.]]) >>> np.matrix(np.eye(4)) matrix([[ 1., 0., 0., 0.], [ 0., 1., 0., 0.], [ 0., 0., 1., 0.], [ 0., 0., 0., 1.]]) >>> a = np.ones((4,4)) >>> a*a array([[ 1., 1., 1., 1.], [ 1., 1., 1., 1.], [ 1., 1., 1., 1.], [ 1., 1., 1., 1.]]) >>> b = np.matrix(a) >>> b*b matrix([[ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.]]) >>> b**2 matrix([[ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.]]) >>> b**4 matrix([[ 64., 64., 64., 64.], [ 64., 64., 64., 64.], [ 64., 64., 64., 64.], [ 64., 64., 64., 64.]]) In Matlab, you use .* vs. * and .^ vs. ^ to obtain the same effect. In NumPy we use different classes for arrays and matrices. Sturla Molden From robert.kern at gmail.com Tue Aug 25 14:42:31 2009 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 25 Aug 2009 13:42:31 -0500 Subject: Putting together a larger matrix from smaller matrices In-Reply-To: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> References: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> Message-ID: On 2009-08-24 21:30 PM, Matjaz Bezovnik wrote: > Dear all, > > I'm but a layman so do not take offence at this maybe over simple > question. > > This is something which is done often in FEM methods, and the alike. > > I have matrix A of 3x3 elements, and B, of the same number of > elements, 3x3. > > What would be the most obvious way to assemble a matrix which: > a11 a12 a13 > a21 a22 a23 > a31 a32 a33+b11 b12 b13 > b21 b22 b23 > b31 b32 b33 > > (the missing elements = zero) > > (you see the pattern - if there was a third matrix C, it would > "connect" to b33 on the main diagonal) You will certainly want to use numpy for this and ask questions on the numpy mailing list. http://www.scipy.org/Mailing_Lists I believe that someone recently posted a recipe for constructing such "block diagonal" arrays. I think it will be included in a future release of numpy. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From thebiggestbangtheory at gmail.com Tue Aug 25 14:42:31 2009 From: thebiggestbangtheory at gmail.com (nickname) Date: Tue, 25 Aug 2009 11:42:31 -0700 (PDT) Subject: os.popen output different from native shell output References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Message-ID: On Aug 25, 6:16?am, Nobody wrote: > On Tue, 25 Aug 2009 01:36:08 -0700, nickname wrote: > > ? ? ? ?I am a relative newbie to python, I am using os.popen to run an > > ls command. The output that I get using the read() function is > > different in look and feel from when I run the ls command natively > > from the shell (not via python). > > As others have pointed out, the default behaviour of ls is different if > its output is a terminal. > > > Is there an easy way to "mirror" the output. When python displays the > > output, how can it tell the bash shell that some of the entries are > > directories and they should appear blue on the bash shell, and that > > everything should not be appearing on 1 column only. > > You can get the terminal-style behaviour even when using a pipe with: > > ? ? ? ? ls -x --color > > But why are you reading this information into Python then writing it > back out to the terminal? > > If you're planning on processing the output within Python, both the > multi-column format and the escape sequences used for colour will make > such processing awkward. > > If you want to enumerate the contents of a directory within Python, use > os.listdir(). > > If you want to generate coloured output, use the curses module, e.g.: > > #!/usr/bin/env python > > import sys > import curses > > curses.setupterm() > setaf = curses.tigetstr('setaf') or "" > setab = curses.tigetstr('setab') or "" > origp = curses.tigetstr('op') or "" > > def fg(c): > ? ? sys.stdout.write(curses.tparm(setaf, c)) > > def bg(c): > ? ? sys.stdout.write(curses.tparm(setab, c)) > > def orig(): > ? ? sys.stdout.write(origp) > > # example > bg(curses.COLOR_BLUE) > fg(curses.COLOR_YELLOW) > print "hello, world" > orig() wow guys! thanks for all the great leads! this is awesome! The reason why I want to do this is because I am going to do a little project. I will write a python script called ls which will log the time and username and then will show the actual ls output. I want this to be transparent and so want to throw the ls output (via python) exactly as it will be in native shell execution. I know there's history files I can look up, but I just am exploring my own intermediate-logging-layer the functionality for which is executed right before the actual command is executed. Thanks, -A From sturlamolden at yahoo.no Tue Aug 25 14:44:11 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 25 Aug 2009 11:44:11 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: On 25 Aug, 20:30, Gilles Ganault wrote: > Combined with the comment above about issues with printing, it looks > like Python for GUI apps isn't a very good idea :-/ With pywin32, printing is the same as for any other Windows app (you get MFC for Python). From mensanator at aol.com Tue Aug 25 14:45:28 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 25 Aug 2009 11:45:28 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> Message-ID: On Aug 25, 9:14?am, Steven D'Aprano wrote: > On Mon, 24 Aug 2009 18:01:38 -0700, Mensanator wrote: > >> If you want your data file to have values entered in hex, or oct, or > >> even unary (1=one, 11=two, 111=three, 1111=four...) you can. > > > Unary? I think you'll find that Standard Positional Number Systems are > > not defined for radix 1. > > Of course not. But unary isn't a positional number system. It's a tally > system, like my example above shows. Roman numerals are another tally > system. Like Roman numerals, the disadvantages of unary are that you > can't represent negative numbers, zero, or fractions, and anything but > addition and subtraction is difficult. But if you want to use it, perhaps > out of a sense of sadism towards your users, it's easy: > > def int2unary(n): > ? ? return '1'*n > > def unary2int(s): > ? ? n = 0 > ? ? for c in s: > ? ? ? ? if c == '1': n+=1 > ? ? ? ? else: raise ValueError('invalid unary string') > ? ? return n But without insignificant leading 0's, I fail to see the relevance of unary to this discussion. And what would you call a tally system of radix 2? Certainly not binary. > > -- > Steven From robert.kern at gmail.com Tue Aug 25 14:54:10 2009 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 25 Aug 2009 13:54:10 -0500 Subject: your favorite debugging tool? In-Reply-To: <87skfgeynf.fsf@benfinney.id.au> References: <87vdkfiaki.fsf@benfinney.id.au> <87skfgeynf.fsf@benfinney.id.au> Message-ID: On 2009-08-25 09:49 AM, Ben Finney wrote: > Esmail writes: > >> Hi Ben, >> >> Ben Finney wrote: >>> >>> Whenever a simple output statement is too cumbersome for debugging, I >>> take it as a sign that the program is too cumbersome to follow. >> >> I'll have to think about this .. though my gut says this is true :-) > > Note that it's only a sign, *not* an ironclad guarantee. But it's the > right way to bet, IME. > >> re your other point about the interactive shell, I agree it's useful, >> but to me still doesn't quite do what a full-fledged debugger can - >> but perhaps that is a reflection of my skill with the shell at this >> point. > > This, on the other hand, I find even more consistent: if the code can't > be effectively inspected from the interactive interpreter, that's a sure > sign that its external interfaces are poor or its internal dependencies > too tightly coupled; or more likely both. And a debugger is a great tool to help you figure out exactly why your code doesn't actually have the wonderful decoupling that you thought you designed into it so you can fix it. :-) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sturlamolden at yahoo.no Tue Aug 25 14:54:21 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 25 Aug 2009 11:54:21 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: <7d48a1c7-b406-499e-a0e1-3c7d3b91d8a0@k30g2000yqf.googlegroups.com> On 25 Aug, 13:24, Wolfgang Keller wrote: > The area of _desktop_ database application development indeed looks like a vast and very hostile desert in the Python landscape. Yes, you don't have drag-and-drop database tools like MS Access or FoxPro. You actually have to use a database API (such as pyodbc or pymssql) with GUI (tkinter, wxPython, PyGTK, PyQt, MFC) manually. If you need a framework for this, you should not be developing software anyway. From robert.kern at gmail.com Tue Aug 25 14:55:28 2009 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 25 Aug 2009 13:55:28 -0500 Subject: your favorite debugging tool? In-Reply-To: References: <57d65219-8134-4c2e-9739-825a5ef450d0@s15g2000yqs.googlegroups.com> Message-ID: On 2009-08-25 06:57 AM, Esmail wrote: > Michele Simionato wrote: >> On Aug 22, 4:25 pm, Esmail wrote: >>> Hi all, >>> >>> What is your favorite tool to help you debug your >>> code? >> >> The times when I would just use 'print' are long past. Nowadays I >> spend lots of my time >> with code written by others than myself. I use pdb all the time, and >> now also ipdb >> (ipdb is very cool if you are used to ipython). > > Never heard of ipdb, I'll have to check it out. It's not really a separate thing, just the pdb integration into the IPython interactive shell (which I highly recommend that you check out). -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From guettli at thomas-guettler.de Tue Aug 25 14:57:59 2009 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 25 Aug 2009 20:57:59 +0200 Subject: os.popen output different from native shell output In-Reply-To: References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Message-ID: <7fiqhnF2l2bs6U1@mid.individual.net> In one of the first chapters of "Advanced programming in the unix environment (second edition)" there is explained how a unix shell works. You could write you own shell using python. This way the python interpreter gets stared only once, and not for every call to "ls". Have fun, Thomas nickname schrieb: > wow guys! thanks for all the great leads! this is awesome! > > The reason why I want to do this is because I am going to do a little > project. I will write a python script called ls which will log the > time and username and then will show the actual ls output. I want this > to be transparent and so want to throw the ls output (via python) > exactly as it will be in native shell execution. From travis at subspacefield.org Tue Aug 25 15:16:59 2009 From: travis at subspacefield.org (travis at subspacefield.org) Date: Tue, 25 Aug 2009 14:16:59 -0500 Subject: proposal: add setresuid() system call to python In-Reply-To: <87d46kdp0v.fsf@busola.homelinux.net> References: <20090717200141.GI6065@subspacefield.org> <148918f0907171315i4ed5b274v77581a43c4464f8f@mail.gmail.com> <7cj89qF27mfrjU1@mid.uni-berlin.de> <877hy38mxw.fsf@busola.homelinux.net> <20090821205040.GK1215@subspacefield.org> <87d46kdp0v.fsf@busola.homelinux.net> Message-ID: <20090825191659.GL1215@subspacefield.org> On Tue, Aug 25, 2009 at 03:03:12PM +0200, Hrvoje Niksic wrote: > You should use ctypes.get_errno() instead of os.errno; sorry about that. > > Also, when raising OSError, you should set the 'errno' attribute to the > appropriate code. How does that compare to: raise pythonapi.PyErr_SetFromErrno(py_object(OSError)) ? -- Obama Nation | My emails do not have attachments; it's a digital signature that your mail program doesn't understand. | http://www.subspacefield.org/~travis/ If you are a spammer, please email john at subspacefield.org to get blacklisted. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 850 bytes Desc: not available URL: From aahz at pythoncraft.com Tue Aug 25 15:19:33 2009 From: aahz at pythoncraft.com (Aahz) Date: 25 Aug 2009 12:19:33 -0700 Subject: Waiting for a subprocess to exit References: <873a7l21gr.fsf@benfinney.id.au> Message-ID: In article , Miles Kaufmann wrote: > >debacle[1]). Leaving shell=3DFalse makes scripts more secure and =20 >robust; besides, when I'm putting together a command and its =20 >arguments, it's as convenient to build a list (['mycmd', 'myarg']) as =20= > >it is a string (if not more so). ....unless you want to use "~" on Mac or Unix. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From jason at nospam.org Tue Aug 25 15:21:25 2009 From: jason at nospam.org (jason) Date: Tue, 25 Aug 2009 13:21:25 -0600 Subject: Simple IRC library References: <752884c5-c6fb-4974-a21a-bf3017fa4145@y4g2000prf.googlegroups.com> Message-ID: <2009082513212516807-jason@nospamorg> On 2009-08-24 01:39:21 -0600, devaru said: > Hi all, > I am new to Python language. I want to capture(either in database or a > file) the conversation in IRC. Fed. > Please suggest me some simple IRC library or code snippet for this. I have used the oyoyo library with success. It's pretty nice and has a framework for bots which you might be interested in looking at. http://code.google.com/p/oyoyo/ From jjposner at optimum.net Tue Aug 25 15:31:48 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 25 Aug 2009 15:31:48 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A943C24.6090209@optimum.net> 7stud said: > python ignores the names inside a function when it creates the > function. This "program" will not produce an error: > > > def f(): > print x > > python parses the file and creates the function object and assigns the > function object to the variable f. It's not until you execute the > function that python will raise an error. The same thing happens with > the recursive function. > Thanks for that explanation. So in the OP's example: Class Demo(object): def fact(n): if n < 2: return 1 else: return n * fact(n - 1) _classvar = fact(5) ... no failure occurs when "fact(5)" is invoked, because the lookup of "fact" in the local scope is a class-scope-lookup, which succeeds. The failure occurs on the first recursive invocation of fact() in the statement "return n * fact(n - 1)": the function-scope-lookup of "fact" fails, and then the interpreter falls back to a global-scope-lookup of "fact", which also fails. From aahz at pythoncraft.com Tue Aug 25 15:32:09 2009 From: aahz at pythoncraft.com (Aahz) Date: 25 Aug 2009 12:32:09 -0700 Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: In article , Hendrik van Rooyen wrote: >On Friday 21 August 2009 08:07:18 josef wrote: >> >> My main focus of this post is: "How do I find and use object reference >> memory locations?" > >>>> a = [1,2,3,4] >>>> id(a) >8347088 >>>> Of course, that doesn't actually allow you to do anything... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From evaned at gmail.com Tue Aug 25 15:33:51 2009 From: evaned at gmail.com (Evan Driscoll) Date: Tue, 25 Aug 2009 12:33:51 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] Message-ID: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> (If you don't want to read the following, note that you can answer my question by writing a swap function.) I want to make a context manager that will temporarily change the value of a variable within the scope of a 'with' that uses it. This is inspired by a C++ RAII object I've used in a few projects. Ideally, what I want is something like the following: x = 5 print x # prints 5 with changed_value(x, 10): print x # prints 10 print x # prints 5 This is similar to PEP 343's example 5 ("Redirect stdout temporarily"; see http://www.python.org/dev/peps/pep-0343/), except that the variable that I want to temporarily change isn't hard-coded in the stdout_redirected function. What I want to write is something like this: @contextmanager def changed_value(variable, temp_value): old_value = variable variable = temp_value try: yield None finally: variable = old_value with maybe a check in 'finally' to make sure that the value hasn't changed during the execution of the 'with'. Of course this doesn't work since it only changes the binding of 'variable', not whatever was passed in, and I kind of doubt I can stick a "&" and "*" in a couple places to make it do what I want. :-) So my question is: is what I want possible to do in Python? How? I think it might be possible to rig something up by passing in the variable that i want to change as a *string* and looking up that string in a dictionary somewhere, but I think what I need is the locals () dictionary of the calling function, and I'm not sure how to get that. Thanks, Evan Driscoll From garrickp at gmail.com Tue Aug 25 15:42:34 2009 From: garrickp at gmail.com (Falcolas) Date: Tue, 25 Aug 2009 12:42:34 -0700 (PDT) Subject: conditional for-statement References: Message-ID: On Aug 25, 11:25?am, seb wrote: > We could as consistenly explain that the syntax > > for n in range(10) if n%3==0: > ? body > > means > > for n in range(10): > ? if n%3==0: > ? ? body > > This syntax has also the benefit of avoiding an extra level of > indentation (the one for the if) that bears no real meaning on a > structural level. > > Maybe a PEP could do the job... > > S?bastien So, what part of the statement does the "if" statement belong to; particularly a concern considering this is valid python: for x in y if y else z: body You can always do the following at the cost of 6 symbols, and the gain of clarity: for n in (x for x in y if y%3==0): body ~G From tjreedy at udel.edu Tue Aug 25 15:45:09 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 Aug 2009 15:45:09 -0400 Subject: Python, qt, and lgpl Message-ID: " New LGPL Python bindings for Qt slither into the light A new set of LGPL-licensed Python bindings for Qt has been announced. The project, which is backed by Nokia, will make it easier for commercial software developers to adopt Python and Qt for rapid application development." http://arstechnica.com/open-source/news/2009/08/openbossa-announces-new-lgpl-python-bindings-for-qt.ars Will be good news if realized. From rurpy at yahoo.com Tue Aug 25 15:45:49 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Tue, 25 Aug 2009 12:45:49 -0700 (PDT) Subject: break unichr instead of fix ord? Message-ID: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> In Python 2.5 on Windows I could do [*1]: # Create a unicode character outside of the BMP. >>> a = u'\U00010040' # On Windows it is represented as a surogate pair. >>> len(a) 2 >>> a[0],a[1] (u'\ud800', u'\udc40') # Create the same character with the unichr() function. >>> a = unichr (65600) >>> a[0],a[1] (u'\ud800', u'\udc40') # Although the unichr() function works fine, its # inverse, ord(), doesn't. >>> ord (a) TypeError: ord() expected a character, but string of length 2 found On Python 2.6, unichr() was "fixed" (using the word loosely) so that it too now fails with characters outside the BMP. >>> a = unichr (65600) ValueError: unichr() arg not in range(0x10000) (narrow Python build) Why was this done rather than changing ord() to accept a surrogate pair? Does not this effectively make unichr() and ord() useless on Windows for all but a subset of unicode characters? From emile at fenx.com Tue Aug 25 15:48:41 2009 From: emile at fenx.com (Emile van Sebille) Date: Tue, 25 Aug 2009 12:48:41 -0700 Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] In-Reply-To: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> Message-ID: On 8/25/2009 12:33 PM Evan Driscoll said... > So my question is: is what I want possible to do in Python? Probably not with immutables (as in your example) -- maybe otherwise. Emile From sdementen at gmail.com Tue Aug 25 15:58:38 2009 From: sdementen at gmail.com (seb) Date: Tue, 25 Aug 2009 12:58:38 -0700 (PDT) Subject: conditional for-statement References: Message-ID: <14afbe5a-62e7-4944-ab9d-42b86530ac41@s31g2000yqs.googlegroups.com> On Aug 25, 9:42?pm, Falcolas wrote: > On Aug 25, 11:25?am, seb wrote: > > > > > We could as consistenly explain that the syntax > > > for n in range(10) if n%3==0: > > ? body > > > means > > > for n in range(10): > > ? if n%3==0: > > ? ? body > > > This syntax has also the benefit of avoiding an extra level of > > indentation (the one for the if) that bears no real meaning on a > > structural level. > > > Maybe a PEP could do the job... > > > S?bastien > > So, what part of the statement does the "if" statement belong to; > particularly a concern considering this is valid python: > > for x in y if y else z: > ? ? body > can this be done in list/set/dict comprehensions/generator expressions ? > You can always do the following at the cost of 6 symbols, and the gain > of clarity: > > for n in (x for x in y if y%3==0): > ? ? body it is in fact precisely to avoid this sort of line: for n in (x for x in y if x%3==0): and have instead the (more readable IMO) line for n in y if n%3==0: with: - 1 "for ... in ..." instead of 2 (where one is the repetition of the other) - no parentheses - no extra technical variable with local binding to the expression generator ('x') it looks more pythonic to me but it is a personal taste. > > ~G From evaned at gmail.com Tue Aug 25 16:07:13 2009 From: evaned at gmail.com (Evan Driscoll) Date: Tue, 25 Aug 2009 13:07:13 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> Message-ID: <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> On Aug 25, 2:33?pm, Evan Driscoll wrote: > I want to make a context manager that will temporarily change the > value of a variable within the scope of a 'with' that uses it. This is > inspired by a C++ RAII object I've used in a few projects. Ideally, > what I want is something like the following: Okay, so I think I actually got this with some consultation with a friend. Critiques? from contextlib import contextmanager import inspect def get_parents_var(offset, var): f = inspect.stack()[offset][0] if var in f.f_locals: return f.f_locals[var] else: return f.f_globals[var] def set_parents_var(offset, var, val): f = inspect.stack()[offset][0] if var in f.f_locals: f.f_locals[var] = val elif var in f_globals: f.f_globals[var] = val else: assert False @contextmanager def changed_value_tb(var_name, temp_value): # 1 is here, 2 will be the implicit next() function, 3 is the real caller offset = 3 old_value = get_parents_var(offset, var_name) set_parents_var(offset, var_name, temp_value) try: yield None finally: set_parents_var(offset, var_name, old_value) x = 5 print x # prints 5 with changed_value_tb("x", 10): print x # prints 10 print x # prints 5 From deets at nospam.web.de Tue Aug 25 16:10:00 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 22:10:00 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <7fiuooF2l2oogU1@mid.uni-berlin.de> John Posner schrieb: > Diez said: >> >> Classes are not scopes. >> So the above doesn't work because name resolution inside >> functions/methods >> looks for local variables first, then for the *global* scope. There is no >> class-scope-lookup. > > But http://docs.python.org/tutorial/classes.html says, in Section 9.3 "A > First Look at Classes": > > When a class definition is entered, a new namespace is created, > and used as the local scope ? thus, all assignments to local variables > go into this new namespace. In particular, function definitions bind > the name of the new function here. > > > The following example confirms this: > > class Spam(object): > clsvar_1 = 555 > clsvar_2 = clsvar_1 + 222 > > def __init__(self): > print "Spam instance initialized" > > sp = Spam() > print sp.clsvar_1, sp.clsvar_2 > > output: > Spam instance initialized > 555 777 > > > Does the OP (kj) have a legitimate gripe, though? I confess that I know > nothing about Python's implementation -- I'm strictly a user. So it's > just a suspicion of mine that > something special enables a recursive function definition to refer to > the function's own name before the definition has been completed. It > works at the module-namespace (i.e. global) level, and Diez's "toy > example" shows that it works at function-namespace level: > > class Demo(object): > > def fact(n): > def inner(n): > if n < 2: > return 1 > else: > return n * inner(n - 1) > return inner(n) > > _classvar = fact(5) > > > So why can't it work at the class-namespace level, too? See my other post on what name lookup with class-scope *inside* functions would mean. Diez From deets at nospam.web.de Tue Aug 25 16:14:48 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 22:14:48 +0200 Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] In-Reply-To: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> Message-ID: <7fiv1oF2l2ejnU1@mid.uni-berlin.de> Evan Driscoll schrieb: > (If you don't want to read the following, note that you can answer my > question by writing a swap function.) > > I want to make a context manager that will temporarily change the > value of a variable within the scope of a 'with' that uses it. This is > inspired by a C++ RAII object I've used in a few projects. Ideally, > what I want is something like the following: > > x = 5 > print x # prints 5 > with changed_value(x, 10): > print x # prints 10 > print x # prints 5 > > This is similar to PEP 343's example 5 ("Redirect stdout temporarily"; > see http://www.python.org/dev/peps/pep-0343/), except that the > variable that I want to temporarily change isn't hard-coded in the > stdout_redirected function. > > What I want to write is something like this: > @contextmanager > def changed_value(variable, temp_value): > old_value = variable > variable = temp_value > try: > yield None > finally: > variable = old_value > with maybe a check in 'finally' to make sure that the value hasn't > changed during the execution of the 'with'. > > Of course this doesn't work since it only changes the binding of > 'variable', not whatever was passed in, and I kind of doubt I can > stick a "&" and "*" in a couple places to make it do what I want. :-) > > So my question is: is what I want possible to do in Python? How? No. And unfortunately, the with-statement (as the for-statement and others) leaks it's name, so you can't even use it like this: with changed_value(variable, temp_value) as new_name: ... The new_name will be defined afterwards. Diez From travis+ml-python at subspacefield.org Tue Aug 25 16:15:35 2009 From: travis+ml-python at subspacefield.org (travis+ml-python at subspacefield.org) Date: Tue, 25 Aug 2009 15:15:35 -0500 Subject: proposal: add setresuid() system call to python In-Reply-To: <20090821201312.GJ1215@subspacefield.org> References: <20090717200141.GI6065@subspacefield.org> <20090717205953.2543.1223422516.divmod.quotient.3129@henry.divmod.com> <20090821201312.GJ1215@subspacefield.org> Message-ID: <20090825201535.GM1215@subspacefield.org> On Fri, Aug 21, 2009 at 03:13:12PM -0500, travis at subspacefield.org wrote: > Since the authors of the paper (Wagner et. al.) are proposing a new > set of APIs to make all of this clearer, I'm thinking that I will > create a module specifically for dropping permissions. I've created the module here: http://www.subspacefield.org/~travis/python/privilege/ I could sure use any comments people had on my python style. PyPi link: http://pypi.python.org/pypi/privilege/1.0 -- Obama Nation | My emails do not have attachments; it's a digital signature that your mail program doesn't understand. | http://www.subspacefield.org/~travis/ If you are a spammer, please email john at subspacefield.org to get blacklisted. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 850 bytes Desc: not available URL: From apt.shansen at gmail.com Tue Aug 25 16:16:24 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Tue, 25 Aug 2009 13:16:24 -0700 Subject: Need help with Python scoping rules In-Reply-To: <4A942954.7070702@optimum.net> References: <4A942954.7070702@optimum.net> Message-ID: <7a9c25c20908251316k2ebc304fk1422c96ddb4158c4@mail.gmail.com> > > > But http://docs.python.org/tutorial/classes.html says, in Section 9.3 "A > First Look at Classes": > > When a class definition is entered, a new namespace is created, > and used as the local scope ? thus, all assignments to local variables > go into this new namespace. In particular, function definitions bind > the name of the new function here. > > [snip] > > (BTW, Diez, your toy example is another demonstration that there *is* a > class-scope-lookup: the "def" statement binds the name "fact" in the class > scope, and the assignment statement looks up the name "fact" in that scope.) > This sounds like a fundamental confusion -- a namespace is not equivalent to a scope, really, I think. The def statement creates a function object, and assigns it to the given name, in its /local scope/ which is the class's namespace -- but that is not a new scope. Its just, during class creation, the local scope. When you enter a class definition, a new namespace is created, and that is used as the local scope during the class's definition. Under "class Foo", the local scope is this class's namespace-- and the global scope is the module's namespace. Any lookup operation checks first in the local scope, then in the global scope... When the "def fact(...)" is executed (note that class bodies are executed on load, function bodies aren't), a new namespace is created as well-- the function's namespace-- and its used as the local scope. During execution of the code, it looks up in the local scope first-- and then it looks up in the global scope if it doesn't find anything. There /is/ no class-lookup-scope... but there IS a class namespace. There's just those two scopes: but the namespace bound to those scopes changes as you enter different parts of the code. For a long time that's all there was, just the local and global scope: to access any other namespace required you to explicitly address it. The class namespace remains accessible only via explicit addressing, but PEP 227 in Python 2.1/2.2 introduced static nested scopes. But that applies only to enclosing functions: embedding one function into another. You can only call recursive functions if the function is able to refer to itself according to the same lookup rules: is the function's name in the local scope? No it's not... is it in the global scope? No? Then it can't call itself recursively... well, unless its a method, and it addresses itself specifically-- with "self.". The OP's probably is that during the execution of the class body, the class doesn't exist... so the 'def fact' -can't- use Classname.fact to address itself explicitly, and within fact the locals don't contain a reference to the function itself, and its globals don't either. You just can't do that. The right way, IMHO, is to move 'fact' up and out of the class into a _fact global variable. Alternatively, you can use a metaclass. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From evaned at gmail.com Tue Aug 25 16:24:08 2009 From: evaned at gmail.com (Evan Driscoll) Date: Tue, 25 Aug 2009 13:24:08 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> Message-ID: On Aug 25, 3:07?pm, Evan Driscoll wrote: > Okay, so I think I actually got this with some consultation with a > friend. Critiques? This is wrong; it's not quite working right. It does with the example I posted, but not in a more thorough test. I'm still ignoring the "you can't do this" answers for a little while more and continuing to try to hack on it. :-) Evan From deets at nospam.web.de Tue Aug 25 16:25:31 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 22:25:31 +0200 Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] In-Reply-To: <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> Message-ID: <7fivlrF2lsrsuU1@mid.uni-berlin.de> Evan Driscoll schrieb: > On Aug 25, 2:33 pm, Evan Driscoll wrote: >> I want to make a context manager that will temporarily change the >> value of a variable within the scope of a 'with' that uses it. This is >> inspired by a C++ RAII object I've used in a few projects. Ideally, >> what I want is something like the following: > > Okay, so I think I actually got this with some consultation with a > friend. Critiques? Modifying locals isn't really allowed - it might stop working with certain implementations of python. And to be honest - I don't really see a use-case for your whole approache. Why don't you want to introduce a new name? Diez From thebiggestbangtheory at gmail.com Tue Aug 25 16:32:57 2009 From: thebiggestbangtheory at gmail.com (nickname) Date: Tue, 25 Aug 2009 13:32:57 -0700 (PDT) Subject: os.popen output different from native shell output References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> <7fiqhnF2l2bs6U1@mid.individual.net> Message-ID: On Aug 25, 11:57?am, Thomas Guettler wrote: > In one of the first chapters of "Advanced programming in the unix > environment (second edition)" there is explained how a unix shell works. > > You could write you own shell using python. This way the python > interpreter gets stared only once, and not for every call to "ls". > > Have fun, > ? Thomas > > nickname schrieb: > > > wow guys! thanks for all the great leads! this is awesome! > > > The reason why I want to do this is because I am going to do a little > > project. I will write a python script called ls which will log the > > time and username and then will show the actual ls output. I want this > > to be transparent and so want to throw the ls output (via python) > > exactly as it will be in native shell execution. > > very good point, I will look it up :-) From ebonak at hotmail.com Tue Aug 25 16:33:53 2009 From: ebonak at hotmail.com (Esmail) Date: Tue, 25 Aug 2009 16:33:53 -0400 Subject: your favorite debugging tool? In-Reply-To: <87skfgeynf.fsf@benfinney.id.au> References: <87vdkfiaki.fsf@benfinney.id.au> <87skfgeynf.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Esmail writes: > >> Hi Ben, >> >> Ben Finney wrote: >>> Whenever a simple output statement is too cumbersome for debugging, I >>> take it as a sign that the program is too cumbersome to follow. >> I'll have to think about this .. though my gut says this is true :-) > > Note that it's only a sign, *not* an ironclad guarantee. But it's the > right way to bet, IME. :-) .. I took it as a rule of thumb too .. I didn't meant to imply anything more serious. These design guidelines help though. Thanks, Esmail From garrickp at gmail.com Tue Aug 25 16:46:19 2009 From: garrickp at gmail.com (Falcolas) Date: Tue, 25 Aug 2009 13:46:19 -0700 (PDT) Subject: conditional for-statement References: <14afbe5a-62e7-4944-ab9d-42b86530ac41@s31g2000yqs.googlegroups.com> Message-ID: <4720bbf4-1be7-4f02-9869-df8e0cd9e221@y10g2000prf.googlegroups.com> On Aug 25, 1:58?pm, seb wrote: > On Aug 25, 9:42?pm, Falcolas wrote: > > On Aug 25, 11:25?am, seb wrote: > > So, what part of the statement does the "if" statement belong to; > > particularly a concern considering this is valid python: > > > for x in y if y else z: > > ? ? body > > can this be done in list/set/dict comprehensions/generator > expressions ? It's a statement, so anywhere you use a statement (such as in generators and list comprehensions), it can exist. for ... in ... only requires that the statement return an iterable, it doesn't matter what statement you use to get there. For example, the following is perfectly valid (if nonsensical - I don't use ternary operators very often in my programming, so I don't have many good examples of their use) list = [x if x else y for x, y in iterable] > it is in fact precisely to avoid this sort of line: > ? for n in (x for x in y if x%3==0): > and have instead the (more readable IMO) line > ? for n in y if n%3==0: > with: > ?- 1 "for ... in ..." instead of 2 (where one is the repetition of the > other) > ?- no parentheses > ?- no extra technical variable with local binding to the expression > generator ('x') > it looks more pythonic to me but it is a personal taste. > It doesn't feel clear to me, which is why I would have to disagree. IIRC, these very filters are the main reason that list comprehensions, and later one-line generators and dictionary comprehensions were originally created: so you can filter the stream before acting on it. One statement performs one action - very precise and understandable. It's just my two cents, but I would not agree that adding a filter keyword to for loops is required. Not when we have the filter function, various types of comprehensions, and if statements which all provide that very functionality. ~G From evaned at gmail.com Tue Aug 25 16:47:17 2009 From: evaned at gmail.com (Evan Driscoll) Date: Tue, 25 Aug 2009 13:47:17 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> <7fivlrF2lsrsuU1@mid.uni-berlin.de> Message-ID: On Aug 25, 3:25?pm, "Diez B. Roggisch" wrote: > Modifying locals isn't really allowed - it might stop working with > certain implementations of python. > > And to be honest - I don't really see a use-case for your whole > approache. Why don't you want to introduce a new name? Wow, this actually was very helpful, because it forced me to clarify what I'm doing to myself, and I *am* making it rather too complicated. The reason that I can't introduce a new name is that I want to call another function that refers to the old name. (Specifically, I'm using this in a testing framework, and I want to mock out some things like file I/O so want to replace 'open' and others temporarily. I don't really want to make said function take an extra parameter which is "the open function to use" or something like that.) But then I don't need to modify locals. In fact, the references that I want to affect are used in a function that isn't even on the stack when the "with" statement is entered! So I only need to modify a global, which is much easier than what I was mucking about with. So here is my simplified version that only works for globals: from contextlib import contextmanager @contextmanager def changed_value(var_name, temp_value): old_value = globals()[var_name] globals()[var_name] = temp_value try: yield None finally: globals()[var_name] = old_value x = 5 print "5:", x with changed_value("x", 10): print "10:", x print "5:", x y = 7 def test(): print "5:", x with changed_value("x", 20): print "20:", x print "7:", y print "5:", x test() print "5:", x How does that look? And thanks for making me think about what I'm doing. :-) Evan From gbelov at gmail.com Tue Aug 25 16:51:14 2009 From: gbelov at gmail.com (Gleb Belov) Date: Tue, 25 Aug 2009 13:51:14 -0700 (PDT) Subject: Is it a bug? Message-ID: <87b7ce88-1f2f-43ff-8096-6a95a89b6e27@e27g2000yqm.googlegroups.com> Hey everyone! I'm quite new to Python and equally new to newsgroups in general, so apologies if this makes no sense. Basically, I was just exploring Python "arrays" on my own, since I come from C++. What I did was: >>> words = ["Hi!", "What's up?", "Bye!"] >>> print words ['Hi!', "What's up?", 'Bye!'] I have two questions: 1) Is it possible and if so, how do I access each individual element? Are there any indexes and what is the syntax? 2) I just noticed that the first and the last words in the output are enclosed in single quotes, and the middle one is enclosed in double quotes. Is it a bug? If not, why does the output work that way? Alright, thanks in advance for any replies and I hope I'll manage to actually find this topic... From somebody at somewhere.com Tue Aug 25 16:59:00 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Tue, 25 Aug 2009 21:59:00 +0100 Subject: Is it a bug? References: <87b7ce88-1f2f-43ff-8096-6a95a89b6e27@e27g2000yqm.googlegroups.com> Message-ID: Gleb Belov wrote: > Hey everyone! I'm quite new to Python and equally new to newsgroups in > general, so apologies if this makes no sense. > > Basically, I was just exploring Python "arrays" on my own, since I > come from C++. What I did was: >>>> words = ["Hi!", "What's up?", "Bye!"] >>>> print words > ['Hi!', "What's up?", 'Bye!'] > > I have two questions: > 1) Is it possible and if so, how do I access each individual element? > Are there any indexes and what is the syntax? For the first element: >>> words[0] > 2) I just noticed that the first and the last words in the output are > enclosed in single quotes, and the middle one is enclosed in double > quotes. Is it a bug? If not, why does the output work that way? The output is valid python code. To represent with single quotes for the second item, there would have to be a \ escape character for the apostrophe. -- Stephen Fairchild From gbelov at gmail.com Tue Aug 25 17:12:47 2009 From: gbelov at gmail.com (Gleb Belov) Date: Tue, 25 Aug 2009 14:12:47 -0700 (PDT) Subject: Is it a bug? References: <87b7ce88-1f2f-43ff-8096-6a95a89b6e27@e27g2000yqm.googlegroups.com> Message-ID: On Aug 26, 12:59?am, Stephen Fairchild wrote: > Gleb Belov wrote: > > Hey everyone! I'm quite new to Python and equally new to newsgroups in > > general, so apologies if this makes no sense. > > > Basically, I was just exploring Python "arrays" on my own, since I > > come from C++. What I did was: > >>>> words = ["Hi!", "What's up?", "Bye!"] > >>>> print words > > ['Hi!', "What's up?", 'Bye!'] > > > I have two questions: > > 1) Is it possible and if so, how do I access each individual element? > > Are there any indexes and what is the syntax? > > For the first element: > > >>> words[0] > > 2) I just noticed that the first and the last words in the output are > > enclosed in single quotes, and the middle one is enclosed in double > > quotes. Is it a bug? If not, why does the output work that way? > > The output is valid python code. To represent with single quotes for the > second item, there would have to be a \ escape character for the > apostrophe. > -- > Stephen Fairchild Oh, thank you! That makes sense! Should have thought of the escape character issue... From sdementen at gmail.com Tue Aug 25 17:19:31 2009 From: sdementen at gmail.com (seb) Date: Tue, 25 Aug 2009 14:19:31 -0700 (PDT) Subject: conditional for-statement References: <14afbe5a-62e7-4944-ab9d-42b86530ac41@s31g2000yqs.googlegroups.com> <4720bbf4-1be7-4f02-9869-df8e0cd9e221@y10g2000prf.googlegroups.com> Message-ID: On Aug 25, 10:46?pm, Falcolas wrote: > On Aug 25, 1:58?pm, seb wrote: > > > On Aug 25, 9:42?pm, Falcolas wrote: > > > On Aug 25, 11:25?am, seb wrote: > > > So, what part of the statement does the "if" statement belong to; > > > particularly a concern considering this is valid python: > > > > for x in y if y else z: > > > ? ? body > > > can this be done in list/set/dict comprehensions/generator > > expressions ? > > It's a statement, so anywhere you use a statement (such as in > generators and list comprehensions), it can exist. for ... in ... only > requires that the statement return an iterable, it doesn't matter what > statement you use to get there. > I never thought about this case... Testing that in python 3.0, i see that >>> [x for x in range(5) if False else range(10)] SyntaxError: invalid syntax (, line 1) >>> [x for x in (range(5) if False else range(10))] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] hence, to avoid the ambiguity you mentionned (that already exists with list comprehensions), one can use the parenthesis. This minor incompatibility is referenced in http://www.python.org/dev/peps/pep-0308/ > It doesn't feel clear to me, which is why I would have to disagree. > IIRC, these very filters are the main reason that list comprehensions, > and later one-line generators and dictionary comprehensions were > originally created: so you can filter the stream before acting on it. > One statement performs one action - very precise and understandable. in my mind, I am thinking as you are but with 'loop' instead of 'stream' """so you can filter the 'loop' before acting on it. One statement performs one action - very precise and understandable.""" and it doesn't look that dissimilar to your own reasoning. > > It's just my two cents, but I would not agree that adding a filter > keyword to for loops is required. Not when we have the filter > function, various types of comprehensions, and if statements which all > provide that very functionality. > before having list comprehensions, we could also have said that """ I would not agree that adding a 'list comprehension' feature is required. Not when we have the filter function, and the 'for+if' statements which all provide that very functionality.""" How can unifying the "for ... in ..." statement with the "for ... in ... if ..." syntax be detrimental ? It would be an inconsistence less to remember, wouldn't it ? cheers, sebastien From ryniek90 at gmail.com Tue Aug 25 17:22:13 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Tue, 25 Aug 2009 23:22:13 +0200 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile In-Reply-To: References: Message-ID: <4A945605.1050105@gmail.com> > > Ryniek90 wrote: >> Referring to my earlier posts: >> http://groups.google.pl/group/comp.lang.python/browse_thread/thread/4e34f995800f5352?hl=pl >> >> >> and >> >> http://groups.google.pl/group/comp.lang.python/browse_thread/thread/abf5573b8fceb37e?hl=pl# >> >> >> I've dealt with those errors. but now have another. >> When my backup scripts starts to backup chosen file, python gave me >> Traceback: >> >> " >> C:\Users\Ryniek's WinSe7en\Documents\My >> Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba >> ckuper.py -f F:\APLIKACJE\nowegg.exe F:\ MyGGBackup >> Checking permissions for reading and writing... >> Have permissions on [F:\APLIKACJE\nowegg.exe] for reading. >> Have permissions on [F:\] for writing. >> Preparing for backup [nowegg.exe]... >> Starting backup... >> Now adding [nowegg.exe]... >> Traceback (most recent call last): >> File "backuper.py", line 197, in >> main_meth() >> File "backuper.py", line 189, in main_meth >> paq.backup_file(pars.options.filename[0], >> pars.options.filename[1], pars.options.filename[2]) >> File "backuper.py", line 127, in backup_file >> backup_obj.add(read_bin_obj) >> File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python >> 2.6\lib\tarfile.py", line 1948, in add >> if self.name is not None and os.path.abspath(name) == self.name: >> File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python >> 2.6\lib\ntpath.py", line 458, in abspath >> path = _getfullpathname(path) >> TypeError: _getfullpathname() argument 1 must be (buffer overflow), >> not str >> " >> >> I've searched over google, but found only that is bug in Python ( >> http://bugs.python.org/issue4071 - in that issue bug is inside >> Python 2.5.2 - i've got ActiveState Active Python with core Python >> 2.6.2), and another info: *http://tinyurl.com/lvyn7o and >> **http://tinyurl.com/kn49vk >> * >> >> Here's my script code: >> *http://paste.ubuntu.com/259310/ >> >> *Shouldn't that bug be patched already :-? > Are you giving it the contents of the file when it's actually expecting > the filename? > > Of course the content of the file: " C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba ckuper.py -f F:\APLIKACJE\nowegg.exe F:\ MyGGBackup Checking permissions for reading and writing... Have permissions on [F:\APLIKACJE\nowegg.exe] for reading. Have permissions on [F:\] for writing. Preparing for backup [nowegg.exe]... Starting backup... Now adding [nowegg.exe]... Traceback (most recent call last): File "backuper.py", line 196, in main_meth() File "backuper.py", line 188, in main_meth paq.backup_file(pars.options.filename[0], pars.options.filename[1], pars.options.filename[2]) File "backuper.py", line 126, in backup_file backup_obj.add(read_obj.read()) File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\tarfile.py", line 1948, in add if self.name is not None and os.path.abspath(name) == self.name: File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\ntpath.py", line 458, in abspath path = _getfullpathname(path) TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str " See? *backup_obj.add(read_obj.read())* In previous pasted Traceback you can see *backup_obj.add(read_bin_obj)* - read_obj_bin was a reference to the *read_obj.read()* . Do only I have this problem or Python programming under Windows is nightmare? From james.harris.1 at googlemail.com Tue Aug 25 17:26:05 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Tue, 25 Aug 2009 14:26:05 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: On 24 Aug, 03:49, Dennis Lee Bieber wrote: ... > > Here's another suggested number literal format. First, keep the > > familar 0x and 0b of C and others and to add 0t for octal. (T is the > >thirdletter of octal as X is thethirdletter of hex.) The numbers > > above would be > > ? ? ? ? The thing is -- "x" and "hex" have similar pronunciations: (h)ecks; > the name of the radix is its own reminder for the character to use > without thinking such conventions as "thirdletter of the radix name". > > ? ? ? ? But "t" (tee) has no pronunciation resemblance to "oct" (o'kt) > whereas the unlovely "o" at least if taken as a short vowel sound is > similar to the "o" of "oct" given the short stop between it and the > "ct". > > > ? 0b1011, 0t7621, 0xc26b > > ? ? ? ? And "b" for binary breaks the "thirdletter of radix name" > convention... You should be using "n" for that (and "c" for decimal ) I wasn't proposing a convention of using the third character of the base name. I was saying that t is not too unreasonable given that we use x for hex (rather than h). > > ? ? ? ? Or we use b, o, d, h (as the HP calculator) and drop the "x" > version. > > > > > where the three characters "0.(" begin the sequence. > > ? ? ? ? Ugly... > > > Comments? Improvements? > > ? ? ? ? Retaining which ever character is finally decided, I'd make all > radix specified literals follow a quoted format: > > ? ? ? ? "digits"radix > > ? ? ? ? "01110"b > ? ? ? ? "123"d (of course, just 123 would be allowed for simplicity) > ? ? ? ? "7C"x > ? ? ? ? "327"o The quoting is good. For hex, decimal, octal and binary, however, I can't see a good reason to change away from the conventional prefix form. And, in general, it's easier for a human to parse if the base is specified first. > > ? ? ? ? Probably wouldn't need that much change to the parser as it would, > left to right, see a string, and then when the string is not followed by > one white space character, find a radix marker -- the parser would then > parse the string using the specified radix, and emit the appropriate > numeric value instead of a string value. Maybe. I think, though, that having the base as prefix would make the parser's job easier as well as the job of humans. It's easier if we know what we are parsing before we parse it rather than afterwards. > ? ? ? ?It only adds one extra > character (instead of leading 0r, one has ""r), and the leading " serves > as a warning to a reader that this is not directly readable as a number. > > ? ? ? ? The alternative syntax of radix"digits" is the same length, but adds > to the parsing as it initially looks like a name entity, then hits the > quote, and has to back up to interpret the result as a radix marker. True. The beginning of a number should be numeric. Using your scheme, though, instead of radix"digits" you could have 0radix"digits". > 0r > format starts as a number, hits a radix marker while the > "conversion/accumulator" is still a 0 value (0 is 0 in all radix) and > switches the converter to accept the digits in the specified radix. Sounds like you are suggesting 0radix"digits" but I'm not sure. > > ? ? ? ? Whereas all prefix versions that don't start with a 0r tend to > require more complex parsing: > > ? ? ? ? 0.( > > starts out looking like a number (the 0)... a floating point number (the > .)... a function/method call on a floating point 0... WAIT? floating > point numbers aren't callables (yet! I'm sure someone is going to show a > way to define a variable bound to a number as a callable, though not to > a literal number)... throw away this parse tree branch, back up and > reparse as special numeric radix prefix... You've laid it on thick but I agree in principle. What about radix"digits" where radix is numeric: So 2"1101" or 3"122"? (Not to replace 0b1101 etc but to supplement it for arbitrary bases.) > > ? ? ? ? Of course, one still has to consider what will be used for \ > character encoding... \x0F vs \013 vs \b0001111? The plans I had did not allow for the suggestions above so I have no comments on character encoding yet but it's good that you mentioned it. James From pydecker at gmail.com Tue Aug 25 17:31:55 2009 From: pydecker at gmail.com (Peter Decker) Date: Tue, 25 Aug 2009 17:31:55 -0400 Subject: Python for professsional Windows GUI apps? In-Reply-To: <20090825132439.d6cb18ca.feliphil@gmx.net> References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: On Tue, Aug 25, 2009 at 7:24 AM, Wolfgang Keller wrote: > The only framework that seems to be worth trying is Dabo. Unfortunately there's little documentation, and that's mostly outdated. To be honest, that was my biggest concern when I tried Dabo. However, after as small a learning curve as one could expect for any non-trivial tool, it seemed that if I wasn't sure what a particular way to do something was, the most obvious guess was almost always correct. Contrast that with developing in wxPython, which has quite a bit of documentation, which I constantly had to refer to, because the confusing and inconsistent design. There is a step by step guide on Google docs written by one of the authors that is a very helpful approach to using Dabo. The authors are also very active on the dabo-users list, and any questions are quickly answered. So I guess if you need a desktop framework in Python, I would strongly urge you to check out Dabo and not let the volume of documentation scare you off. -- # p.d. From jjposner at optimum.net Tue Aug 25 17:56:51 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 25 Aug 2009 17:56:51 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A945E23.2060802@optimum.net> Stephen Hansen said: > > > But http://docs.python.org/tutorial/classes.html says, in Section > 9.3 "A First Look at Classes": > > When a class definition is entered, a new namespace is created, > and used as the local scope ? thus, all assignments to local variables > go into this new namespace. In particular, function definitions bind > the name of the new function here. > > [snip] > > > (BTW, Diez, your toy example is another demonstration that there > *is* a class-scope-lookup: the "def" statement binds the name > "fact" in the class scope, and the assignment statement looks up > the name "fact" in that scope.) > > > This sounds like a fundamental confusion -- a namespace is not > equivalent to a scope, really, I think. My apologies if I was being too loose with the terms "namespace" and "scope". I was trying to use Diez's terminology (e.g. "class-scope-lookup"). But I think you agree with me in *almost* everything you say below. > > The def statement creates a function object, and assigns it to the > given name, in its /local scope/ which is the class's namespace -- but > that is not a new scope. Its just, during class creation, the local scope. > > When you enter a class definition, a new namespace is created, and > that is used as the local scope during the class's definition. Under > "class Foo", the local scope is this class's namespace-- and the > global scope is the module's namespace. Any lookup operation checks > first in the local scope, then in the global scope... > > When the "def fact(...)" is executed (note that class bodies are > executed on load, function bodies aren't), a new namespace is created > as well-- the function's namespace-- and its used as the local scope. > During execution of the code, it looks up in the local scope first-- > and then it looks up in the global scope if it doesn't find anything. > There /is/ no class-lookup-scope... but there IS a class namespace. > > There's just those two scopes: but the namespace bound to those scopes > changes as you enter different parts of the code. > > For a long time that's all there was, just the local and global scope: > to access any other namespace required you to explicitly address it. > The class namespace remains accessible only via explicit addressing, > but PEP 227 in Python 2.1/2.2 introduced static nested scopes. But > that applies only to enclosing functions: embedding one function into > another. > > You can only call recursive functions if the function is able to refer > to itself according to the same lookup rules: is the function's name > in the local scope? No it's not... is it in the global scope? No? Then > it can't call itself recursively... well, unless its a method, and it > addresses itself specifically-- with "self.". All of the above is consistent with my previous post. > > The OP's probably is that during the execution of the class body, the > class doesn't exist... so the 'def fact' -can't- use Classname.fact to > address itself explicitly, and within fact the locals don't contain a > reference to the function itself, and its globals don't either. You > just can't do that. Here's where we disagree, and I'm sticking to my guns. The fact that the class definition has not been completely processed is irrelevant. The OP's problem was attempting to implement a recursive function. A non-recursive implementation of fact() works fine: class ThisWorks(object): def fact(n): answer = 1 i = 1 while i <= n: answer *= i i += 1 return answer clsvar = fact(4) print ThisWorks.clsvar # output: 24 > The right way, IMHO, is to move 'fact' up and out of the class ... We're back to agreement on this point! -John From piet at cs.uu.nl Tue Aug 25 17:57:21 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 25 Aug 2009 23:57:21 +0200 Subject: conditional for-statement References: Message-ID: >>>>> seb (s) wrote: >s> i am still a bit puzzle by the following. >s> I read in http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generators >s> """Python 3.0 unifies all collection types by introducing dict and set >s> comprehensions, similar to list comprehensions: >>>>> [ n*n for n in range(5) ] # regular list comprehension >s> [0, 1, 4, 9, 16] >>>>> >>>>> { n*n for n in range(5) } # set comprehension >s> {0, 1, 4, 16, 9} >>>>> >>>>> { n: n*n for n in range(5) } # dict comprehension >s> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} >s> """ >s> and we can add to this list the quite similar syntax for generator >s> expressions. >s> On all these loop constructs, one can consistenly add filtering on a >s> condition by adding an "if ..." after the "for ... in ..." part (and >s> it looks to me difficult to argue, for instance, that we should not >s> allow filtering for dict comprehesion because we could get the same >s> result by some other construct) You can also say: [x+y for x in range(3) for y in range(4) if x < y] If you want to write this as a loop you have to put the for's on separate lines separated by colons, so why not the if also? Or would you also like to have the for's on one line? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From python at mrabarnett.plus.com Tue Aug 25 18:05:01 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 25 Aug 2009 23:05:01 +0100 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile In-Reply-To: <4A945605.1050105@gmail.com> References: <4A945605.1050105@gmail.com> Message-ID: <4A94600D.60409@mrabarnett.plus.com> Ryniek90 wrote: >> >> Ryniek90 wrote: [snip] >>> Here's my script code: >>> *http://paste.ubuntu.com/259310/ >>> >>> *Shouldn't that bug be patched already :-? >> Are you giving it the contents of the file when it's actually expecting >> the filename? >> > > Of course the content of the file: [snip] > See? *backup_obj.add(read_obj.read())* > In previous pasted Traceback you can see *backup_obj.add(read_bin_obj)* > - read_obj_bin was a reference to the *read_obj.read()* . > The documentation lists the methods "add" and "addfile". Pick one and provide the values it's expecting. For example, if you choose "add" then provide the filename, not the contents of the file. > Do only I have this problem or Python programming under Windows is > nightmare? It's only a nightmare if you don't follow the documentation. :-) From gbelov at gmail.com Tue Aug 25 18:14:26 2009 From: gbelov at gmail.com (Gleb Belov) Date: Tue, 25 Aug 2009 15:14:26 -0700 (PDT) Subject: Help with arrays Message-ID: Hello! I'm working on an exercise wherein I have to write a Guess The Number game, but it's the computer who's guessing MY number. I can get it to work, but there's one obvious problem: the computer generates random numbers until one of them corresponds to my number, but it will often generate one number (eg. 4) numerous times, meaning it doesn't know that this number is invalid. What I mean is, it will sometimes use 37 tries to guess a number out of 1 - 9, which makes no sense, since it should only take 9 tries, at most. I was trying to find a way to make a dynamic list of all the numbers the computer generates in the loop and then make it re-generate the number if the previous number is present in the list, so it doesn't keep on generating 4 (as an example). I don't know if that makes sense... Basically, we humans know that once something is incorrect, there's no point in trying to use it as the answer next time, because we already know it's incorrect. How do I go about coding this in Python? I'm still quite new to the language so any help will be appreciated... From philip at semanchuk.com Tue Aug 25 18:21:46 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 25 Aug 2009 18:21:46 -0400 Subject: Help with arrays In-Reply-To: References: Message-ID: <9AE5AB62-5991-4A6E-81EC-2AEE8BFE71F3@semanchuk.com> On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: > Hello! I'm working on an exercise wherein I have to write a Guess The > Number game, but it's the computer who's guessing MY number. I can get > it to work, but there's one obvious problem: the computer generates > random numbers until one of them corresponds to my number, but it will > often generate one number (eg. 4) numerous times, meaning it doesn't > know that this number is invalid. What I mean is, it will sometimes > use 37 tries to guess a number out of 1 - 9, which makes no sense, > since it should only take 9 tries, at most. I was trying to find a way > to make a dynamic list of all the numbers the computer generates in > the loop and then make it re-generate the number if the previous > number is present in the list, so it doesn't keep on generating 4 (as > an example). I don't know if that makes sense... Basically, we humans > know that once something is incorrect, there's no point in trying to > use it as the answer next time, because we already know it's > incorrect. How do I go about coding this in Python? I'm still quite > new to the language so any help will be appreciated... One cheap way to do it (not necessarily efficient) is to make a list of your possible guesses (e.g. range(1,10)), use random.shuffle() to put them in random order and then run through the guesses one at a time. HTH Philip From farberow at wisc.edu Tue Aug 25 18:34:10 2009 From: farberow at wisc.edu (Carrie Farberow) Date: Tue, 25 Aug 2009 17:34:10 -0500 Subject: Python on Crays In-Reply-To: <1f5c81d8-4f79-4eea-b1bd-af48ab9ddc82@c2g2000yqi.googlegroups.com> References: <1f5c81d8-4f79-4eea-b1bd-af48ab9ddc82@c2g2000yqi.googlegroups.com> Message-ID: <6e80874a13151.4a942092@wiscmail.wisc.edu> Ok, here are links to word documents outlining the commands I executed as well as the make.log file and the make_install.log file instructions/commands: https://mywebspace.wisc.edu/xythoswfs/webui/_xy-29018965_1-t_dSnfEm5b make.log: https://mywebspace.wisc.edu/xythoswfs/webui/_xy-29018966_1-t_zjqLuV5v javascript:parent.send('smtp') make_install.log: https://mywebspace.wisc.edu/xythoswfs/webui/_xy-29018967_1-t_n8aqH2P The issue referred to in the previous message (http://bugs.python.org/issue1594809) sounds similar - however I do not think that I can just build the shared unicodedata module and have it work properly, as I am trying to statically link the necessary modules. I am very new with this, so if I am completely misunderstanding, please feel free to let me know. Thanks! Carrie ----- Original Message ----- From: Mark Dickinson Date: Friday, August 21, 2009 12:50 pm Subject: Re: Python on Crays To: python-list at python.org > On Aug 21, 12:21?am, Carrie Farberow wrote: > > I am trying to build a statically-linked Python based on directions > at: > > > > http://yt.enzotools.org/wiki/CrayXT5Installation > > > > I have tried this on multiple systems. ?The first time I attempt to > build python, 'make' runs fine but 'make install' fails with the > following error: > > > > Sorry: UnicodeError: ("\\N escapes not supported (can't load > unicodedata module)",) > > > > Any help regarding the source of this error and possible fixes would > be appreciated. > > Hmm. There's not a lot of information to go on here. > What version of Python is this? Python 2.6.2? > Have you tried Googling for that exact error message? > > The following issue looks as though it might be relevant: > > http://bugs.python.org/issue1594809 > > especially since it looks as though the directions you linked > to involve messing with the PYTHONPATH environment variable. > > If you could post a log somewhere[*] showing the exact commands > that you executed, along with all the output (and especially > all the output from 'make' and 'make install'), that might help > someone diagnose the problem further. > > Mark > > [*] I'm not sure where, though. Posting all that output directly > in a newsgroup message might not be considered very friendly. > -- > http://mail.python.org/mailman/listinfo/python-list From samwyse at gmail.com Tue Aug 25 18:35:55 2009 From: samwyse at gmail.com (samwyse) Date: Tue, 25 Aug 2009 15:35:55 -0700 (PDT) Subject: best way to display photos References: <96e9b045-d591-485e-b831-ba1462345df9@z31g2000yqd.googlegroups.com> <7fhfboF2ksfhiU1@mid.individual.net> Message-ID: On Aug 25, 1:40?am, Thomas Guettler wrote: > Some years ago I had the same problem. > > I wrote a simple app with pygtk. You get get it from here: > ? ?http://guettli.sourceforge.net/gthumpy/src/README.html > The next pictures get loaded in background. Switching from > one image to the next is faster then in some other apps. But > somehow it is not ready for the public. I guess I am the only > one who uses it. > > Flags are symlinks in the home directory .local/share/app/gthumpy. This > means you should not move your images, otherwise the flags get lost. > > I don't think it will work on ms-windows, but it could be ported. > > Or you use mirage:http://mirageiv.berlios.de/index.html > > It is a pygtk image viewer. You can define shortcuts that execute user defined > commands. > > ? Thomas > > samwyse schrieb: > > > I have several thousand photographs that I need to quickly classify, > > all by myself. ?After extensive searches, I have been unable to find > > anything to my liking, so desire to write something myself. ?I'm > > thinking about displaying a photo and waiting for keystrokes to tag > > it; 'i' for interior, 'e' for exterior, etc., while hitting space or > > enter will advance to the next photo. ?My big question is, what's the > > best way to display the photos. ?I've used PIL in the past, but IIRC > > it uses an external program. ?Pygame is the next obvious choice, but > > like PIL it requires an add-in. ?That leaves Tkinter. ?Has anyone used > > it to display .JPG files, perhaps with rescaling to fit my screen? > > How is its performance? ?Is there any other possibilities that I've > > missed? ?Thanks. > > -- > Thomas Guettler,http://www.thomas-guettler.de/ > E-Mail: guettli (*) thomas-guettler + de Thanks! Both of these look very similar to what I need. I will investigate further. From wwy58 at yahoo.com Tue Aug 25 18:43:28 2009 From: wwy58 at yahoo.com (David) Date: Tue, 25 Aug 2009 15:43:28 -0700 (PDT) Subject: mod_python: Permission denied Message-ID: <0fb0ed29-82bb-4bdf-aa24-071c158eea2a@k13g2000prh.googlegroups.com> Hello, I googled online however I did not find a clue my question. So I post it here. I created a mod_python CGI to upload a file and saves it in folder "/ var/www/keyword-query/files/". My code runs in root. fileitem = req.form['file'] # Test if the file was uploaded if fileitem.filename: # strip leading path from file name to avoid directory traversal attacks fname = os.path.basename(fileitem.filename) # build absolute path to files directory dir_path = os.path.join(os.path.dirname(req.filename), 'files') f = open(os.path.join(dir_path, fname), 'wb', 10000) # Read the file in chunks for chunk in fbuffer(fileitem.file): f.write(chunk) f.close() message = 'The file "%s" was uploaded successfully' % fname I got: File "/var/www/keyword-query/upload.py", line 30, in upload f = open(os.path.join(dir_path, fname), 'wb', 10000) IOError: [Errno 13] Permission denied: '/var/www/keyword-query/files/ Defrosting.rtf' "Defrosting.rtf" is a file on the desktop of my Windows XP computer. Anybody knows what the problem is? Thanks for your replies. From graham.dumpleton at gmail.com Tue Aug 25 18:46:07 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Aug 2009 15:46:07 -0700 (PDT) Subject: How does the file.seek() work ? References: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> Message-ID: <1532ff09-f892-44c8-8206-10b3c2d16050@13g2000prl.googlegroups.com> On Aug 25, 5:37?am, Tim Chase wrote: > > I want the file pointer set to 100 and overwrite everything from there > [snip] > > def application(environ, response): > > ? ? query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') > > ? ? range=environ.get('HTTP_RANGE','bytes=0-').replace > > ('bytes=','').split(',') > > ? ? offset=[] > > ? ? for r in range: offset.append(r.split('-')) > > ? ? with open(query,'w+') as f: > > ? ? ? ? ?f.seek(int(offset[0][0])) > > ? ? ? ? ?while True: > > ? ? ? ? ? ? ?chunk=environ['wsgi.input'].read(8192).decode('latin1') > > ? ? ? ? ? ? ?if not chunk: break > > ? ? ? ? ? ? ?f.write(chunk) > > ? ? f=open(query) > > ? ? l=str(os.fstat(f.fileno()).st_size) > > ? ? response('200 OK', [('Content-Type', 'text/plain'), ('Content- > > Length', str(len(l)))]) > > ? ? return [l] > > A couple items of note: > > - you don't open the file in binary mode -- seek is more reliable > in binary mode :) If my memory is right, if file is opened in binary mode, also wouldn't need to be decoding the WSGI input stream as latin-1 to get a string. Instead can just deal with bytes and write bytes to file. Graham > - if you want to lop off the rest of the file, use f.truncate() > > An example: > > # create the initial file > ?>>> f = file('zzz.zzz', 'wb+') > ?>>> f.write('abcdefghijklmnop') > ?>>> f.close() > > ?>>> f = file('zzz.zzz', 'ab+') > ?>>> f.read() # show the existing content > 'abcdefghijklmnop' > ?>>> f.seek(5) # seek to the desired offset > ?>>> f.truncate() # throw away everything after here > ?>>> f.write('zyx') # write the new data at pos=5 > ?>>> f.close() > > # demonstrate that it worked > ?>>> f = file('zzz.zzz', 'rb') > ?>>> f.read() > 'abcdezyx' > ?>>> f.close() > > > also why must I open the file a second time to know how big it is ? > > Likely the output has been buffered. ?You can try using > > ? ?f.flush() # write all the data to the disk first > ? ?size = os.fstat(f.fileno()).st_size > > which seems to do the trick for me. > > -tkc From graham.dumpleton at gmail.com Tue Aug 25 18:48:38 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Aug 2009 15:48:38 -0700 (PDT) Subject: mod_python: Permission denied References: <0fb0ed29-82bb-4bdf-aa24-071c158eea2a@k13g2000prh.googlegroups.com> Message-ID: <09e25701-5d85-4aed-a4bb-4fa94df74f5c@v37g2000prg.googlegroups.com> On Aug 26, 8:43?am, David wrote: > Hello, > > I googled online however I did not find a clue my question. So I post > it here. > > I created a mod_python CGI to upload a file and saves it in folder "/ > var/www/keyword-query/files/". ?My code runs in root. > > ? ? ?fileitem = req.form['file'] > > ? ?# Test if the file was uploaded > ? ?if fileitem.filename: > > ? ? ? # strip leading path from file name to avoid directory traversal > attacks > ? ? ? fname = os.path.basename(fileitem.filename) > ? ? ? # build absolute path to files directory > ? ? ? dir_path = os.path.join(os.path.dirname(req.filename), 'files') > ? ? ? f = open(os.path.join(dir_path, fname), 'wb', 10000) > > ? ? ? # Read the file in chunks > ? ? ? for chunk in fbuffer(fileitem.file): > ? ? ? ? ?f.write(chunk) > ? ? ? f.close() > ? ? ? message = 'The file "%s" was uploaded successfully' % fname > > I got: > > ?File "/var/www/keyword-query/upload.py", line 30, in upload > ? ? f = open(os.path.join(dir_path, fname), 'wb', 10000) > > IOError: [Errno 13] Permission denied: '/var/www/keyword-query/files/ > Defrosting.rtf' > > "Defrosting.rtf" is a file on the desktop of my Windows XP computer. > > Anybody knows what the problem is? > > Thanks for your replies. Apache service likely running as a special user which doesn't have write permission to your directory. Graham From wwy58 at yahoo.com Tue Aug 25 18:48:47 2009 From: wwy58 at yahoo.com (David) Date: Tue, 25 Aug 2009 15:48:47 -0700 (PDT) Subject: mod_python: Permission denied References: <0fb0ed29-82bb-4bdf-aa24-071c158eea2a@k13g2000prh.googlegroups.com> Message-ID: <5fc7570c-8f77-429d-8c9d-5ba74573e440@k13g2000prh.googlegroups.com> A little more info: "Defrosting.rtf" is a file that I wanted to upload. This file was supposed to upload to folder '/var/www/keyword- query/files/'. My code runs in root. From somebody at somewhere.com Tue Aug 25 18:50:17 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Tue, 25 Aug 2009 23:50:17 +0100 Subject: Help with arrays References: Message-ID: Philip Semanchuk wrote: > > On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: > >> Hello! I'm working on an exercise wherein I have to write a Guess The >> Number game, but it's the computer who's guessing MY number. I can get >> it to work, but there's one obvious problem: the computer generates >> random numbers until one of them corresponds to my number, but it will >> often generate one number (eg. 4) numerous times, meaning it doesn't >> know that this number is invalid. What I mean is, it will sometimes >> use 37 tries to guess a number out of 1 - 9, which makes no sense, >> since it should only take 9 tries, at most. I was trying to find a way >> to make a dynamic list of all the numbers the computer generates in >> the loop and then make it re-generate the number if the previous >> number is present in the list, so it doesn't keep on generating 4 (as >> an example). I don't know if that makes sense... Basically, we humans >> know that once something is incorrect, there's no point in trying to >> use it as the answer next time, because we already know it's >> incorrect. How do I go about coding this in Python? I'm still quite >> new to the language so any help will be appreciated... > > One cheap way to do it (not necessarily efficient) is to make a list > of your possible guesses (e.g. range(1,10)), use random.shuffle() to > put them in random order and then run through the guesses one at a time. import random import time l = range(1, 10) while l: print l.pop(random.randint(0, len(l) - 1)) time.sleep(2) -- Stephen Fairchild From wwy58 at yahoo.com Tue Aug 25 18:58:54 2009 From: wwy58 at yahoo.com (David) Date: Tue, 25 Aug 2009 15:58:54 -0700 (PDT) Subject: mod_python: Permission denied References: <0fb0ed29-82bb-4bdf-aa24-071c158eea2a@k13g2000prh.googlegroups.com> <5fc7570c-8f77-429d-8c9d-5ba74573e440@k13g2000prh.googlegroups.com> Message-ID: <0ec8929f-eab8-4655-8661-40142ae8c908@j9g2000prh.googlegroups.com> disclaimer: i did not write this code. i copied it and inserted into my cgi code. it is from http://webpython.codepoint.net/mod_python_publisher_big_file_upload. From wwy58 at yahoo.com Tue Aug 25 19:00:46 2009 From: wwy58 at yahoo.com (David) Date: Tue, 25 Aug 2009 16:00:46 -0700 (PDT) Subject: mod_python: Permission denied References: <0fb0ed29-82bb-4bdf-aa24-071c158eea2a@k13g2000prh.googlegroups.com> <5fc7570c-8f77-429d-8c9d-5ba74573e440@k13g2000prh.googlegroups.com> <0ec8929f-eab8-4655-8661-40142ae8c908@j9g2000prh.googlegroups.com> Message-ID: <0c73d5bf-3f5d-4308-a7f0-276e4d6d9fa9@x25g2000prf.googlegroups.com> Thanks Graham. Let me contact Admin. From geekworking at gmail.com Tue Aug 25 19:04:01 2009 From: geekworking at gmail.com (geekworking) Date: Tue, 25 Aug 2009 16:04:01 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: <63bb7834-80ac-4894-9ef5-2598ecac72cc@k19g2000yqn.googlegroups.com> If you are planning a database driven app, you should first settle on a DB server. Any real enterprise DB system will put all of the business logic in the database server. The choice of a front end should be secondary. Wikipedia's list of Python apps: http://en.wikipedia.org/wiki/List_of_Python_software From wwy58 at yahoo.com Tue Aug 25 19:07:34 2009 From: wwy58 at yahoo.com (David) Date: Tue, 25 Aug 2009 16:07:34 -0700 (PDT) Subject: mod_python: Permission denied References: <0fb0ed29-82bb-4bdf-aa24-071c158eea2a@k13g2000prh.googlegroups.com> <5fc7570c-8f77-429d-8c9d-5ba74573e440@k13g2000prh.googlegroups.com> <0ec8929f-eab8-4655-8661-40142ae8c908@j9g2000prh.googlegroups.com> <0c73d5bf-3f5d-4308-a7f0-276e4d6d9fa9@x25g2000prf.googlegroups.com> Message-ID: <134a6022-f7d5-4871-bb7c-e38af0cd7679@x6g2000prc.googlegroups.com> On Aug 25, 4:00?pm, David wrote: > Thanks Graham. Let me contact Admin. Hi Graham: you are right. it's fixed now. Thanks again. From mdekauwe at gmail.com Tue Aug 25 19:48:35 2009 From: mdekauwe at gmail.com (Mart.) Date: Tue, 25 Aug 2009 16:48:35 -0700 (PDT) Subject: Help with arrays References: Message-ID: <9be8986b-95c8-48fa-a298-3b97fa598081@s15g2000yqs.googlegroups.com> On Aug 25, 11:50?pm, Stephen Fairchild wrote: > Philip Semanchuk wrote: > > > On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: > > >> Hello! I'm working on an exercise wherein I have to write a Guess The > >> Number game, but it's the computer who's guessing MY number. I can get > >> it to work, but there's one obvious problem: the computer generates > >> random numbers until one of them corresponds to my number, but it will > >> often generate one number (eg. 4) numerous times, meaning it doesn't > >> know that this number is invalid. What I mean is, it will sometimes > >> use 37 tries to guess a number out of 1 - 9, which makes no sense, > >> since it should only take 9 tries, at most. I was trying to find a way > >> to make a dynamic list of all the numbers the computer generates in > >> the loop and then make it re-generate the number if the previous > >> number is present in the list, so it doesn't keep on generating 4 (as > >> an example). I don't know if that makes sense... Basically, we humans > >> know that once something is incorrect, there's no point in trying to > >> use it as the answer next time, because we already know it's > >> incorrect. How do I go about coding this in Python? I'm still quite > >> new to the language so any help will be appreciated... > > > One cheap way to do it (not necessarily efficient) is to make a list > > of your possible guesses (e.g. range(1,10)), use random.shuffle() to > > put them in random order and then run through the guesses one at a time. > > import random > import time > > l = range(1, 10) > > while l: > ? ? print l.pop(random.randint(0, len(l) - 1)) > ? ? time.sleep(2) > > -- > Stephen Fairchild Perhaps generate all of the possible moves at the outset in some form of lookup table that you can refer to? I think it is a similar thing to how computers play chess, I think it is called "hash tables" From cevomed at gmail.com Tue Aug 25 19:48:52 2009 From: cevomed at gmail.com (=?ISO-8859-9?Q?Cevahir_Demirk=FDran?=) Date: Wed, 26 Aug 2009 01:48:52 +0200 Subject: Division and right shift in python Message-ID: <3f74e020908251648k7b391a09g78b155507b2f23c4@mail.gmail.com> Hi, I would like to do a floor division by a power of 2 in python to make it faster than / (modular division in 2.x). However, it is slower. What is the reason of that? I checked them via: def f2(x,n): t1 = clock() r = x/pow(2,n) t2 = clock() print (t2-t1) print r t2 = clock() r = x>>n t3 = clock() print (t3-t2) print r -------------- next part -------------- An HTML attachment was scrubbed... URL: From evaned at gmail.com Tue Aug 25 19:51:42 2009 From: evaned at gmail.com (Evan Driscoll) Date: Tue, 25 Aug 2009 16:51:42 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> <7fivlrF2lsrsuU1@mid.uni-berlin.de> Message-ID: <3da50b33-d79e-4579-9240-ef430ea7c697@m38g2000yqh.googlegroups.com> On Aug 25, 3:47?pm, Evan Driscoll wrote: > So here is my simplified version that only works for globals: So I think this works if (1) you only use changed_value in the same module as it's defined in (otherwise it picks up the globals from the module it's defined in, which is almost certainly not what you want), and (2) the value you want to change is just a simple variable and not either something like "os.path" or a builtin. I have worked on this a bit more and have something that addresses these issues in at least the cases I've tested. I'm not going to post the code here, but it is up at http://pages.cs.wisc.edu/~driscoll/python/utils.py and there are a few unit tests at http://pages.cs.wisc.edu/~driscoll/python/utils_test.py I solved issue (1) by reintroducing the use of inspect to walk back up the stack a couple frames, but I pulled out the f_globals member instead of f_locals. Issue (2a) I fixed by splitting the variable name at periods and walking through successive dictionaries with each component. Issue (2b) I fixed by looking for a '__builtins__' entry if the name I'm looking up doesn't exist. Right now it's sort of hackish... it probably doesn't respond particularly well if things go unexpectedly (e.g. a bad variable name is given) and I should probably verify that the value is unchanged during the with statement and throw an exception otherwise, but it probably works well enough for my purposes for now. Comments are appreciated... a couple of the things in there it seems like there could very well be reimplementations of things that are already done. Evan From sturlamolden at yahoo.no Tue Aug 25 20:04:51 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 25 Aug 2009 17:04:51 -0700 (PDT) Subject: Python, qt, and lgpl References: Message-ID: <1e7a9056-db73-4c4f-be8a-f1b65a91daec@v20g2000yqm.googlegroups.com> On 25 Aug, 21:45, Terry Reedy wrote: > Will be good news if realized. Good news for everyone except Riverbank. From zuo at chopin.edu.pl Tue Aug 25 20:34:11 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 26 Aug 2009 02:34:11 +0200 Subject: Need help with Python scoping rules In-Reply-To: <7a9c25c20908251316k2ebc304fk1422c96ddb4158c4@mail.gmail.com> References: <4A942954.7070702@optimum.net> <7a9c25c20908251316k2ebc304fk1422c96ddb4158c4@mail.gmail.com> Message-ID: 25-08-2009 o 22:16:24 Stephen Hansen wrote: > The OP's probably is that during the execution of the class body, the > class > doesn't exist... so the 'def fact' -can't- use Classname.fact to address > itself explicitly, and within fact the locals don't contain a reference > to > the function itself, and its globals don't either. You just can't do > that. > The right way, IMHO, is to move 'fact' up and out of the class into a > _fact global variable. Alternatively, you can use a metaclass. Note that you can also pass a function to the function itself, and then it works: >>> class Foo: ... def func(foo=None): ... if foo: ... return foo() ... else: ... return '2nd step' ... x = func(func) ... >>> Foo.x '2nd step' Note that when called from class definition body, func is an ordinary function, not a method. It become a method *when it's called as a method* (what is possible *after* creating the class => outside the definition). Cheers, *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Tue Aug 25 20:45:32 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 26 Aug 2009 02:45:32 +0200 Subject: Is it a bug? In-Reply-To: <87b7ce88-1f2f-43ff-8096-6a95a89b6e27@e27g2000yqm.googlegroups.com> References: <87b7ce88-1f2f-43ff-8096-6a95a89b6e27@e27g2000yqm.googlegroups.com> Message-ID: 25-08-2009 o 22:51:14 Gleb Belov wrote: > I have two questions: > 1) Is it possible and if so, how do I access each individual element? > Are there any indexes and what is the syntax? It's a 'Read-The-Friendly-Manual' question. (hint: library reference - Built-in Types - ...) -- Jan Kaliszewski (zuo) From somebody at somewhere.com Tue Aug 25 20:59:45 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Wed, 26 Aug 2009 01:59:45 +0100 Subject: Need help with Python scoping rules References: Message-ID: You are trying to run code in a class that does not exist yet. def Demo(): def fact(n): if n < 2: return 1 else: return n * fact(n - 1) return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar": fact(5)}) Demo = Demo() d = Demo() print d._classvar # prints 120 print d.fact(7) # prints 5040 print Demo # prints -- Stephen Fairchild From zuo at chopin.edu.pl Tue Aug 25 21:02:11 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 26 Aug 2009 03:02:11 +0200 Subject: break unichr instead of fix ord? In-Reply-To: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: 25-08-2009 o 21:45:49 wrote: > In Python 2.5 on Windows I could do [*1]: > > # Create a unicode character outside of the BMP. > >>> a = u'\U00010040' > > # On Windows it is represented as a surogate pair. [snip] > On Python 2.6, unichr() was "fixed" (using the word > loosely) so that it too now fails with characters outside > the BMP. [snip] > Does not this effectively make unichr() and ord() useless > on Windows for all but a subset of unicode characters? Are you sure, you couldn't have UCS-4-compiled Python distro for Windows?? :-O *j -- Jan Kaliszewski (zuo) From phily05 at gmail.com Tue Aug 25 21:09:28 2009 From: phily05 at gmail.com (Phil) Date: Tue, 25 Aug 2009 18:09:28 -0700 (PDT) Subject: Python on the Web Message-ID: I've seen lots of web sites explaining everything, but for whatever reason I seem to not be picking something up. I am a graphical person, which is probably the reason I haven't found my answer. May somebody please confirm if my diagram accurately represents the stack, generally speaking. http://i26.tinypic.com/1fe82x.png Even if that is the case, I'm having a hard time understanding the differences. I guess wsgiref has absolutely nothing to do with FCGI/ SCGI/CGI and simply receives and responds to HTTP requests following the WSGI specification? Does it just spawn a new thread for each request? If so, then how is this any different than a production server with FCGI? The way I am understanding the 'Production' side of that picture is that the web server (eg. lighttpd) creates a single FCGI process. The FCGI process is actually the entry point of the Framework/Application which sets up Flup's WSGIServer, being the interface between FCGI and the Framework/Application? What I mean is, it is just the code that the web server loads to start with, example... from flup.server.fcgi import WSGIServer from app import application WSGIServer(application).run() ... Then for each HTTP request, Flup's WSGIServer creates a new thread to handle the request? As I've read elsewhere, "These days, FastCGI is never used directly. Just like mod_python it is only used for the deployment of WSGI applications." As far as I understand, the main (or only?) reasoning for this is because WSGI makes Python applications easier to deploy without having to worry about whether using FCGI/SCGI/CGI. What would be involved to run Python on the web using FCGI without WSGI? I can feel the flames already. This isn't the only reason I want to know, but one reason is that I want to use Python 3.1 and as I understand, this will have to wait for the WSGI 2.0 specification to ensure time isn't wasted. I apologize if the questions are ridiculous. I've just recently got into web programming and it seems that in order for me to use Python, I need a deep understanding of web servers, HTTP, FCGI, etc. I have more questions but they go more off topic, so I will save it for another thread, another day. I realize there is a large number of questions, so thanks for any help. From terry.yinzhe at gmail.com Tue Aug 25 21:11:53 2009 From: terry.yinzhe at gmail.com (Terry) Date: Tue, 25 Aug 2009 18:11:53 -0700 (PDT) Subject: multiprocessing managers and socket connection. References: <722664f1-81af-45da-ae40-070bca8f3ee0@k6g2000yqn.googlegroups.com> Message-ID: <0af6687a-e36d-47c3-af5e-7e66eacbb3ce@v23g2000pro.googlegroups.com> On Aug 25, 10:14?pm, Chris wrote: > I've been using multiprocessing managers and I really like the > functionality. > > I have a question about reconnecting to a manager. I have a situation > where I start on one machine (A) a manager that is listening and then > on another machine (B) connects to that manager and uses its proxy > object to call functions on the manager's computer; this all works as > expected. But, if the manager from A shuts down, B's application won't > notice because in the MP code it ignores socket error > errno.ECONNREFUSED. If A becomes available again or is restarted, B > doesn't automatically reconnect either and continue its operation. > It's function is basically stopped. > > Here is the code from connection.py: > while 1: > ? ? ? ? try: > ? ? ? ? ? ? s.connect(address) > ? ? ? ? except socket.error, e: > ? ? ? ? ? ? if e.args[0] != errno.ECONNREFUSED: # connection refused > ? ? ? ? ? ? ? ? debug('failed to connect to address %s', address) > ? ? ? ? ? ? ? ? raise > ? ? ? ? ? ? time.sleep(0.01) > ? ? ? ? else: > ? ? ? ? ? ? break > > How can I have B automatically reconnect to A and continue its work > once A is available again? I think you need to retry repeatedly until successfully connected. br, Terry From wuwei23 at gmail.com Tue Aug 25 21:13:11 2009 From: wuwei23 at gmail.com (alex23) Date: Tue, 25 Aug 2009 18:13:11 -0700 (PDT) Subject: can python make web applications? References: <02a3ba7c$0$18215$c3e8da3@news.astraweb.com> Message-ID: <1e23a271-785b-4600-892f-32c85d717f2e@f18g2000prf.googlegroups.com> Mark wrote: > On Sun, 23 Aug 2009 21:45:17 +0100, Goke Aruna wrote: > >http://www.openerp.com, all done is python. > > That does look impressive. Is that Django or Turbogears? Turbogears, according to the product's wikipedia page. From terry.yinzhe at gmail.com Tue Aug 25 21:22:02 2009 From: terry.yinzhe at gmail.com (Terry) Date: Tue, 25 Aug 2009 18:22:02 -0700 (PDT) Subject: Return value of multiprocessing manager registerred function Message-ID: <4337084f-cf9b-4b9c-a0cc-ba8f0821f31a@v15g2000prn.googlegroups.com> Hi, I'm using the multiprocessing.manager to run procedures remotely. It all worked fine except I hope to have a different return value type. The remote function calls always return a proxy, which when I need to get the value it need to connect to the manager again to fetch it. But I just need the value, not the proxy. Can I just return the value instead of a proxy from a manager? br, Terry From davea at ieee.org Tue Aug 25 21:26:12 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 25 Aug 2009 21:26:12 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A948F34.3030703@ieee.org> Stephen Fairchild wrote: > You are trying to run code in a class that does not exist yet. > > > def Demo(): > def fact(n): > if n < 2: > return 1 > else: > return n * fact(n - 1) > return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar": > fact(5)}) > Demo = Demo() > > d = Demo() > print d._classvar # prints 120 > print d.fact(7) # prints 5040 > print Demo # prints > > In all these messages, something I haven't seen pointed out is that fact() has no self argument. Seems to me that makes it a staticmethod, so it should be declared that way. But you can't call a static method from the class scope, since the class hasn't been completed yet. That's the part I consider a problem, not all the rest. I've seen the same problem in Forth, where 'smudge' is used to prevent a definition from accidentally calling itself. But I don't recall whether that was in the standard, or just vendor's helpful additions. Anyway, my first choice is to move the static method out of the class. Second choice workaround follows, moving the initialization of the class variable to after the class, when it can properly use the class name.: class Demo(object): @staticmethod def fact(n): if n < 2: return 1 else: return n * Demo.fact(n - 1) Demo._classvar = Demo.fact(5) print Demo._classvar xx = Demo() print xx.fact(6) DaveA From aahz at pythoncraft.com Tue Aug 25 21:41:55 2009 From: aahz at pythoncraft.com (Aahz) Date: 25 Aug 2009 18:41:55 -0700 Subject: web frameworks that support Python 3 References: Message-ID: In article , Graham Dumpleton wrote: >On Aug 24, 6:34=A0am, Sebastian Wiesner wrote: >> >> In any case, there is bottle [1], which provides a *very minimal* framewo= >rk >> for WSGI web development. =A0Don't expect too much, it is really small, a= >nd >> doesn't do much more than routing and minimal templating. >> >> However, it is the only Python-3-compatible web framework I know of. >> >> [1]http://bottle.paws.de/page/start > >There is one big flaw with your claim. That is the there is no WSGI >specification for Python 3.0 as yet. Anything that claims to work with >WSGI and Python 3.0 is just a big guess as far as how WSGI for Python >3.0 may work. Perhaps you meant "library" instead of "specification"? I don't understand how a language can be missing a specification. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From robert.kern at gmail.com Tue Aug 25 21:47:22 2009 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 25 Aug 2009 20:47:22 -0500 Subject: Python on the Web In-Reply-To: References: Message-ID: On 2009-08-25 20:09 PM, Phil wrote: > I've seen lots of web sites explaining everything, but for whatever > reason I seem to not be picking something up. > I am a graphical person, which is probably the reason I haven't found > my answer. > May somebody please confirm if my diagram accurately represents the > stack, generally speaking. > > http://i26.tinypic.com/1fe82x.png > > Even if that is the case, I'm having a hard time understanding the > differences. I guess wsgiref has absolutely nothing to do with FCGI/ > SCGI/CGI and simply receives and responds to HTTP requests following > the WSGI specification? Correct. > Does it just spawn a new thread for each > request? No, it is single-threaded. > If so, then how is this any different than a production > server with FCGI? > > The way I am understanding the 'Production' side of that picture is > that the web server (eg. lighttpd) creates a single FCGI process. The > FCGI process is actually the entry point of the Framework/Application > which sets up Flup's WSGIServer, being the interface between FCGI and > the Framework/Application? What I mean is, it is just the code that > the web server loads to start with, example... > from flup.server.fcgi import WSGIServer > from app import application > WSGIServer(application).run() > ... Then for each HTTP request, Flup's WSGIServer creates a new thread > to handle the request? Something like that, yes. > As I've read elsewhere, "These days, FastCGI is never used directly. > Just like mod_python it is only used for the deployment of WSGI > applications." As far as I understand, the main (or only?) reasoning > for this is because WSGI makes Python applications easier to deploy > without having to worry about whether using FCGI/SCGI/CGI. Yes, that is the primary reason for WSGI, in my mind. There are other things like the composability of applications, but the decoupling of application authoring from deployment is the sine qua non, in my opinion. > What would be involved to run Python on the web using FCGI without > WSGI? I can feel the flames already. This isn't the only reason I want > to know, but one reason is that I want to use Python 3.1 and as I > understand, this will have to wait for the WSGI 2.0 specification to > ensure time isn't wasted. I am willing to bet that the FCGI libraries haven't been upgraded to Python 3.x, either. I suspect that the most 3.x-updating work will be going into WSGI and the adapters. E.g. http://www.saddi.com/software/news/archives/64-Dabbling-in-Python-3.0.html You may want to rethink the Python 3.x requirement, though. It will probably be much less a waste of your time to write your app using a framework like Django or Pylons on Python 2.x and then upgrade to Python 3.x when they do. > I apologize if the questions are ridiculous. I've just recently got > into web programming and it seems that in order for me to use Python, > I need a deep understanding of web servers, HTTP, FCGI, etc. I have > more questions but they go more off topic, so I will save it for > another thread, another day. Knowing something about HTTP will certainly help get into the right mindset to know what limitations and capabilities web apps can have. Typically, though, you use a framework that abstracts most of this stuff away from you. You usually only need to delve into the details in very specific circumstances. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From lists at cheimes.de Tue Aug 25 21:49:42 2009 From: lists at cheimes.de (Christian Heimes) Date: Wed, 26 Aug 2009 03:49:42 +0200 Subject: break unichr instead of fix ord? In-Reply-To: References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: Jan Kaliszewski wrote: > Are you sure, you couldn't have UCS-4-compiled Python distro > for Windows?? :-O Nope, Windows require UCS-2 builds. Christian From davea at ieee.org Tue Aug 25 22:02:56 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 25 Aug 2009 22:02:56 -0400 Subject: Help with arrays In-Reply-To: References: Message-ID: <4A9497D0.3010203@ieee.org> Stephen Fairchild wrote: > Philip Semanchuk wrote: > > >> On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: >> >> >>> Hello! I'm working on an exercise wherein I have to write a Guess The >>> Number game, but it's the computer who's guessing MY number. I can get >>> it to work, but there's one obvious problem: the computer generates >>> random numbers until one of them corresponds to my number, but it will >>> often generate one number (eg. 4) numerous times, meaning it doesn't >>> know that this number is invalid. What I mean is, it will sometimes >>> use 37 tries to guess a number out of 1 - 9, which makes no sense, >>> since it should only take 9 tries, at most. I was trying to find a way >>> to make a dynamic list of all the numbers the computer generates in >>> the loop and then make it re-generate the number if the previous >>> number is present in the list, so it doesn't keep on generating 4 (as >>> an example). I don't know if that makes sense... Basically, we humans >>> know that once something is incorrect, there's no point in trying to >>> use it as the answer next time, because we already know it's >>> incorrect. How do I go about coding this in Python? I'm still quite >>> new to the language so any help will be appreciated... >>> >> One cheap way to do it (not necessarily efficient) is to make a list >> of your possible guesses (e.g. range(1,10)), use random.shuffle() to >> put them in random order and then run through the guesses one at a time. >> > > import random > import time > > l = range(1, 10) > > while l: > print l.pop(random.randint(0, len(l) - 1)) > time.sleep(2) > > While both of these will work well, I'd point out that a direct translation of your question is to use a set. Define an empty set, and each time you try a number unsuccessfully, add it to the set. Then just use while x in myset: x = newguess() to find the next guess. This approach isn't as efficient, but it's a useful paradigm to understand. A separate question is whether the human is supposed to tell the computer whether the guess is high or low. If so, you can eliminate many numbers on each guess. For example, suppose the solution is 8. A guess of 5 would say "too low." Then you'd cross off now only 5 but 1-4 as well. With this change the best solution changes from a random shuffle to a binary search. DaveA From exarkun at twistedmatrix.com Tue Aug 25 22:19:59 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Wed, 26 Aug 2009 02:19:59 -0000 Subject: web frameworks that support Python 3 In-Reply-To: References: Message-ID: <20090826021959.7027.186838236.divmod.xquotient.13@localhost.localdomain> On 01:41 am, aahz at pythoncraft.com wrote: >In article >, >Graham Dumpleton wrote: >>On Aug 24, 6:34=A0am, Sebastian Wiesner wrote: >>> >>>In any case, there is bottle [1], which provides a *very minimal* >>>framewo= >>rk >>>for WSGI web development. =A0Don't expect too much, it is really >>>small, a= >>nd >>>doesn't do much more than routing and minimal templating. >>> >>>However, it is the only Python-3-compatible web framework I know of. >>> >>>[1]http://bottle.paws.de/page/start >> >>There is one big flaw with your claim. That is the there is no WSGI >>specification for Python 3.0 as yet. Anything that claims to work with >>WSGI and Python 3.0 is just a big guess as far as how WSGI for Python >>3.0 may work. > >Perhaps you meant "library" instead of "specification"? He meant specification. Python 3.x is different enough from any Python 2.x release that PEP 333 no longer completely makes sense. It needs to be modified to be applicable to Python 3.x. So, in the sense that there is no written down, generally agreed upon specification for what WSGI on Python 3.x means, there is no... specification. There is, however, apparently, a library. ;) Jean-Paul From phily05 at gmail.com Tue Aug 25 22:27:53 2009 From: phily05 at gmail.com (Phil) Date: Tue, 25 Aug 2009 19:27:53 -0700 (PDT) Subject: Python on the Web References: Message-ID: Thank you for the helpful and timely response. My interest in Python 3.1 was actually to develop a framework. Again, I can feel the flames. :) I understand there are enough frameworks but I actually have no applications that I wish to develop. I enjoy developing these kinds of things from scratch as a learning experience. I've been doing fine with 2.x and WSGI, even without understanding half of this stuff. It is actually my first Python project. Haha. I just have my own design philosophies that I wish to experiment with. Python 3.x just makes everything nicer with UNICODE, etc. Although you've been helpful with almost all of the mentioned concerns, I am still looking for more details on some of the questions I've asked. So, if others stumble upon this post, feel free to contribute further. Thanks again. From graham.dumpleton at gmail.com Tue Aug 25 22:52:16 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Aug 2009 19:52:16 -0700 (PDT) Subject: web frameworks that support Python 3 References: Message-ID: <7c16aca3-05c2-4aad-a645-f1e8ca37a097@2g2000prl.googlegroups.com> On Aug 26, 12:19?pm, exar... at twistedmatrix.com wrote: > On 01:41 am, a... at pythoncraft.com wrote: > > > > > > >In article > >, > >Graham Dumpleton ? wrote: > >>On Aug 24, 6:34=A0am, Sebastian Wiesner wrote: > > >>>In any case, there is bottle [1], which provides a *very minimal* > >>>framewo= > >>rk > >>>for WSGI web development. =A0Don't expect too much, it is really > >>>small, a= > >>nd > >>>doesn't do much more than routing and minimal templating. > > >>>However, it is the only Python-3-compatible web framework I know of. > > >>>[1]http://bottle.paws.de/page/start > > >>There is one big flaw with your claim. That is the there is no WSGI > >>specification for Python 3.0 as yet. Anything that claims to work with > >>WSGI and Python 3.0 is just a big guess as far as how WSGI for Python > >>3.0 may work. > > >Perhaps you meant "library" instead of "specification"? > > He meant specification. > > Python 3.x is different enough from any Python 2.x release that PEP 333 > no longer completely makes sense. ?It needs to be modified to be > applicable to Python 3.x. > > So, in the sense that there is no written down, generally agreed upon > specification for what WSGI on Python 3.x means, there is no... > specification. > > There is, however, apparently, a library. ;) If you are talking about wsgiref then that was somewhat broken in Python 3.0. In Python 3.1 it works for some definition of works. The problem again being that since WSGI specification hasn't been updated for Python 3.X, that how it works will likely not match what the specification may eventually say. This will become more and more of a problem if WSGI specification isn't updated. At the moment the discussion is going around in circles, although, if I put my optimistic face on, I would say it is a slow inward spiral. Not quite a death spiral at least. Graham From wuwei23 at gmail.com Tue Aug 25 23:17:15 2009 From: wuwei23 at gmail.com (alex23) Date: Tue, 25 Aug 2009 20:17:15 -0700 (PDT) Subject: Python on the Web References: Message-ID: <5ee192da-c56a-4adf-9572-6e5b72bafead@y4g2000prf.googlegroups.com> Phil wrote: > My interest in Python 3.1 was actually to develop a framework. Again, > I can feel the flames. :) I understand there are enough frameworks but > I actually have no applications that I wish to develop. No offense intended, but that's probably the worst approach to take. Frameworks created for the sake of creating a framework, as opposed to those written to meet a defined need, tend to be the worst examples of masturbatory coding. From phily05 at gmail.com Tue Aug 25 23:25:31 2009 From: phily05 at gmail.com (Phil) Date: Tue, 25 Aug 2009 20:25:31 -0700 (PDT) Subject: Python on the Web References: <5ee192da-c56a-4adf-9572-6e5b72bafead@y4g2000prf.googlegroups.com> Message-ID: On Aug 25, 11:17?pm, alex23 wrote: > Phil wrote: > > My interest in Python 3.1 was actually to develop a framework. Again, > > I can feel the flames. :) I understand there are enough frameworks but > > I actually have no applications that I wish to develop. > > No offense intended, but that's probably the worst approach to take. > > Frameworks created for the sake of creating a framework, as opposed to > those written to meet a defined need, tend to be the worst examples of > masturbatory coding. No offense taken. I understand your concern. I actually do have some important design decisions I wish to meet. It has sort of been a process of evaluating the things I love and hate most from existing frameworks. From metolone+gmane at gmail.com Tue Aug 25 23:40:46 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 25 Aug 2009 20:40:46 -0700 Subject: Division and right shift in python References: <3f74e020908251648k7b391a09g78b155507b2f23c4@mail.gmail.com> Message-ID: "Cevahir Demirkiran" wrote in message news:3f74e020908251648k7b391a09g78b155507b2f23c4 at mail.gmail.com... > Hi, > > I would like to do a floor division by a power of 2 in python to make it > faster than / (modular division in 2.x). > However, it is slower. > What is the reason of that? > I checked them via: > > def f2(x,n): > t1 = clock() > r = x/pow(2,n) > t2 = clock() > print (t2-t1) > print r > t2 = clock() > r = x>>n > t3 = clock() > print (t3-t2) > print r > It's not slower on my system, but note the inconsistent results also: >>> f2(1024,5) 3.47396033483e-06 32 2.19077375482e-06 32 >>> f2(1024,5) 4.84135603429e-06 32 3.08499440393e-06 32 >>> f2(1024,5) 4.6782844052e-06 32 3.77604384028e-06 32 Time it with timeit... C:\>python -m timeit -n 10000000 -s x=1024 "x>>5" 10000000 loops, best of 3: 0.113 usec per loop C:\>python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" 10000000 loops, best of 3: 0.468 usec per loop Right-shift is over 4x faster. -Mark From graham.dumpleton at gmail.com Tue Aug 25 23:45:26 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Aug 2009 20:45:26 -0700 (PDT) Subject: Python on the Web References: <5ee192da-c56a-4adf-9572-6e5b72bafead@y4g2000prf.googlegroups.com> Message-ID: On Aug 26, 1:17?pm, alex23 wrote: > Phil wrote: > > My interest in Python 3.1 was actually to develop a framework. Again, > > I can feel the flames. :) I understand there are enough frameworks but > > I actually have no applications that I wish to develop. > > No offense intended, but that's probably the worst approach to take. > > Frameworks created for the sake of creating a framework, as opposed to > those written to meet a defined need, tend to be the worst examples of > masturbatory coding. I would in part actually disagree with that. The problem with people creating frameworks to meet some defined need is that they often implement only just enough of that framework to meet that need and nothing more. End result is that the framework is more often than not ever fleshed out enough to be of much use to anyone else. Its existence though just pollutes the Internet with more crap that one has to wade through. Since there is already a plethora of good frameworks out there, if writing an application, you are better of using one of the existing frameworks. If interested in working at the framework level, you would still be much better off looking at the existing frameworks, first learn how they work and then consider contributing to them, rather than implementing your own. For some related reading, see: http://lucumr.pocoo.org/2009/7/30/nih-in-the-wsgi-world As far as low level framework (or anti frameworks), suggest looking at Werkzeug, Paste/Pylons and bobo. I'll comment more on original message later. Graham From clp2 at rebertia.com Tue Aug 25 23:51:30 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 25 Aug 2009 20:51:30 -0700 Subject: Division and right shift in python In-Reply-To: References: <3f74e020908251648k7b391a09g78b155507b2f23c4@mail.gmail.com> Message-ID: <50697b2c0908252051w2c0ad860t46a7651b2ccabcf1@mail.gmail.com> On Tue, Aug 25, 2009 at 8:40 PM, Mark Tolonen wrote: > > "Cevahir Demirkiran" wrote in message > news:3f74e020908251648k7b391a09g78b155507b2f23c4 at mail.gmail.com... >> >> Hi, >> >> I would like to do a floor division by a power of 2 in python to make it >> faster than / (modular division in 2.x). >> However, it is slower. >> What is the reason of that? >> I checked them via: >> >> def f2(x,n): >> ? t1 = clock() >> ? r = x/pow(2,n) >> ? t2 = clock() >> ? print (t2-t1) >> ? print r >> ? t2 = clock() >> ? r = x>>n >> ? t3 = clock() >> ? print (t3-t2) >> ? print r >> > > It's not slower on my system, but note the inconsistent results also: > >>>> f2(1024,5) > > 3.47396033483e-06 > 32 > 2.19077375482e-06 > 32 >>>> >>>> f2(1024,5) > > 4.84135603429e-06 > 32 > 3.08499440393e-06 > 32 >>>> >>>> f2(1024,5) > > 4.6782844052e-06 > 32 > 3.77604384028e-06 > 32 > > Time it with timeit... > > C:\>python -m timeit -n 10000000 -s x=1024 "x>>5" > 10000000 loops, best of 3: 0.113 usec per loop > > C:\>python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" > 10000000 loops, best of 3: 0.468 usec per loop > > Right-shift is over 4x faster. Adjusting for not having to lookup the name "pow", right shift is still faster, but only slightly. chris at morpheus ~ $ python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" 10000000 loops, best of 3: 0.318 usec per loop chris at morpheus ~ $ python -m timeit -n 10000000 -s x=1024 "x/(2**5)" 10000000 loops, best of 3: 0.0973 usec per loop chris at morpheus ~ $ python -m timeit -n 10000000 -s x=1024 "x>>5" 10000000 loops, best of 3: 0.0885 usec per loop Cheers, Chris -- http://blog.rebertia.com From metolone+gmane at gmail.com Tue Aug 25 23:53:52 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 25 Aug 2009 20:53:52 -0700 Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: wrote in message news:2ad21a79-4a6c-42a7-8923-beb304bb5e99 at v20g2000yqm.googlegroups.com... > In Python 2.5 on Windows I could do [*1]: > > # Create a unicode character outside of the BMP. > >>> a = u'\U00010040' > > # On Windows it is represented as a surogate pair. > >>> len(a) > 2 > >>> a[0],a[1] > (u'\ud800', u'\udc40') > > # Create the same character with the unichr() function. > >>> a = unichr (65600) > >>> a[0],a[1] > (u'\ud800', u'\udc40') > > # Although the unichr() function works fine, its > # inverse, ord(), doesn't. > >>> ord (a) > TypeError: ord() expected a character, but string of length 2 found > > On Python 2.6, unichr() was "fixed" (using the word > loosely) so that it too now fails with characters outside > the BMP. > > >>> a = unichr (65600) > ValueError: unichr() arg not in range(0x10000) (narrow Python build) > > Why was this done rather than changing ord() to accept a > surrogate pair? > > Does not this effectively make unichr() and ord() useless > on Windows for all but a subset of unicode characters? Switch to Python 3? >>> x='\U00010040' >>> import unicodedata >>> unicodedata.name(x) 'LINEAR B SYLLABLE B025 A2' >>> ord(x) 65600 >>> hex(ord(x)) '0x10040' >>> unicodedata.name(chr(0x10040)) 'LINEAR B SYLLABLE B025 A2' >>> ord(chr(0x10040)) 65600 >>> print(ascii(chr(0x10040))) '\ud800\udc40' -Mark From christopher.nebergall at gmail.com Wed Aug 26 00:32:28 2009 From: christopher.nebergall at gmail.com (Christopher Nebergall) Date: Tue, 25 Aug 2009 22:32:28 -0600 Subject: PyObject_CallFunction and writable memory Message-ID: I'm working a patch to a hex editor (frhed) written in c++ so it can load python scripts. Internally the c++ code has a unsigned char * of possibly serveral hundred megs which I want to send into the python code to modify. What is the best way to send the unsigned char * as writable memory into the python code, so I don't have to duplicate the memory in order to return a modified copy? I'm currently using "PyObject_CallFunction(pFunc, "(s#)",p->lpbMemory, p->dwSize);" to send an immutable string but I haven't seen what I need to set in the format string which makes the data writable to python. The solution can be for either python 2.6 or 3.1. Thanks, Christopher From graham.dumpleton at gmail.com Wed Aug 26 00:34:23 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Aug 2009 21:34:23 -0700 (PDT) Subject: Python on the Web References: Message-ID: <08ac740a-de74-4b5d-94af-35ab4dbe6ecc@m3g2000pri.googlegroups.com> A few additional comments on top of what others have said. On Aug 26, 11:09?am, Phil wrote: > I've seen lots of web sites explaining everything, but for whatever > reason I seem to not be picking something up. > I am a graphical person, which is probably the reason I haven't found > my answer. > May somebody please confirm if my diagram accurately represents the > stack, generally speaking. > > http://i26.tinypic.com/1fe82x.png > > Even if that is the case, I'm having a hard time understanding the > differences. I guess wsgiref has absolutely nothing to do with FCGI/ > SCGI/CGI and simply receives and responds to HTTP requests following > the WSGI specification? Technically it receives and responses to request based on HTTP specification, not WSGI specification. The underlying HTTP server translates to and communicates with a Python web application using the WSGI interface. > Does it just spawn a new thread for each > request? If so, then how is this any different than a production > server with FCGI? I would describe there as being four major ways that WSGI can be hosted. These are: 1. Custom build HTTP/WSGI server written in Python. Production quality examples are CherryPy WSGI server and Paste HTTP server. You shouldn't use wsgiref for anything but very simple stuff. 2. Per request process execution by way of CGI and a CGI/WSGI adapter. This could be under Apache or any other web server which supports CGI. 3. Module that embeds Python interpreter into a C based web server. Example are mod_wsgi and mod_python for Apache. Note that mod_python would infrequently be used to host WSGI and doesn't include its own WSGI adapter. These days mod_wsgi for Apache would be used. Processes in this would be persistent. 4. Module in a web server that allows one to communicate using a custom protocol with a separate persistent web application process hosting the web application through a WSGI interface. This convers FASTCGI, SCGI and AJP. The mod_wsgi module for Apache has a hybrid mode which work in a similar way but uses an internal protocol. Amongst these, there are many variations as far as number of process and threads. For a bit of discussion about this in relation to mod_wsgi read: http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading > The way I am understanding the 'Production' side of that picture is > that the web server (eg. lighttpd) creates a single FCGI process. FASTCGI isn't restricted to a single process, nor single threading. Whether a particular implementation allows for the variations depends on the implementation. > The > FCGI process is actually the entry point of the Framework/Application > which sets up Flup's WSGIServer, being the interface between FCGI and > the Framework/Application? What I mean is, it is just the code that > the web server loads to start with, example... > ? ? from flup.server.fcgi import WSGIServer > ? ? from app import application > ? ? WSGIServer(application).run() > ... Then for each HTTP request, Flup's WSGIServer creates a new thread > to handle the request? > > As I've read elsewhere, "These days, FastCGI is never used directly. Even back in time, I don't think it was really ever used as a generic interface that people worked with directly, there was always a more usable layer built on top of it. > Just like mod_python it is only used for the deployment of WSGI > applications. The mod_python module isn't used just for WSGI applications and is probably rarely used for them. This is because mod_python has its own interface for building web applications. It also has abilities to hook into Apache request handling phases, meaning it can do more than host a a content handler/web application. > As far as I understand, the main (or only?) reasoning > for this is because WSGI makes Python applications easier to deploy > without having to worry about whether using FCGI/SCGI/CGI. WSGI provides for portability, it isn't necessarily easier to use than mod_python. > What would be involved to run Python on the web using FCGI without > WSGI? I can feel the flames already. No, you really don't want to do that. > This isn't the only reason I want > to know, but one reason is that I want to use Python 3.1 and as I > understand, this will have to wait for the WSGI 2.0 specification to > ensure time isn't wasted. Then look at mod_wsgi. It already has support for Python 3.X. Some aspects of how it implements WSGI 1.0 may change, but will not be too much and details are being sorted out in the back rooms as we speak. See: http://code.google.com/p/modwsgi/wiki/ChangesInVersion0300 The other option is CherryPy WSGI server as that is close to a Python 3.X release as well, as I perceive it. I wouldn't bother waiting for WSGI 2.0. That is more of a pipe dream. There will be an updated WSGI 1.0 for Python 3.0. Graham > I apologize if the questions are ridiculous. I've just recently got > into web programming and it seems that in order for me to use Python, > I need a deep understanding of web servers, HTTP, FCGI, etc. I have > more questions but they go more off topic, so I will save it for > another thread, another day. > > I realize there is a large number of questions, so thanks for any help. From nicola.larosa at gmail.com Wed Aug 26 01:54:59 2009 From: nicola.larosa at gmail.com (Nicola Larosa (tekNico)) Date: Tue, 25 Aug 2009 22:54:59 -0700 (PDT) Subject: Code formatting question: conditional expression References: <421c8c9d-efb5-4e70-9321-51736b42bc9a@g10g2000yqh.googlegroups.com> Message-ID: <46c5c882-c38b-4439-a3cf-62783309cc08@t13g2000yqt.googlegroups.com> Nicola Larosa wrote: > Here's my take: > > ? ? excessblk = Block(total - P.BASE, srccol, > carry_button_suppress=True > ? ? ? ? ) if total > P.BASE else None Oops, it got shortened out: line longer than 72 chars, acceptable in code, but not in email. I'll try again. If the first line is too long, I would write it like this: excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None If not, like this: excessblk = Block(total - P.BASE, srccol, cbs=True ) if total > P.BASE else None If the condition or the last value were too long to make it all fit on two lines, then it would probably best to revert to a plain "if" statement. -- Nicola Larosa - http://www.tekNico.net/ From http Wed Aug 26 02:19:25 2009 From: http (Paul Rubin) Date: 25 Aug 2009 23:19:25 -0700 Subject: your favorite debugging tool? References: Message-ID: <7xpraj5c7m.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > My normal debug technique is wolf fencing* (eg; print statements) That method was formerly completely automated on the web: http://www.st.cs.uni-saarland.de/askigor/faq.php It was amazing. Further info is here: http://www.st.cs.uni-saarland.de/dd/ From hendrik at microcorp.co.za Wed Aug 26 02:44:50 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 26 Aug 2009 08:44:50 +0200 Subject: Object Reference question In-Reply-To: References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <200908260844.50220.hendrik@microcorp.co.za> On Tuesday 25 August 2009 21:32:09 Aahz wrote: > In article , > > Hendrik van Rooyen wrote: > >On Friday 21 August 2009 08:07:18 josef wrote: > >> My main focus of this post is: "How do I find and use object reference > >> memory locations?" > >> > >>>> a = [1,2,3,4] > >>>> id(a) > > > >8347088 > > Of course, that doesn't actually allow you to do anything... Well - if the OP is the sort of person who likes juggling with running chainsaws, then he can look up a thread I started about a thing I called a "can", which enabled you to get the object back from a string representation of the ID. I did not want to open that "can" of worms again, and I thought that answering half a question was better than nothing... *weg* - Hendrik From ben+python at benfinney.id.au Wed Aug 26 02:47:33 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 26 Aug 2009 16:47:33 +1000 Subject: Code formatting question: conditional expression References: <421c8c9d-efb5-4e70-9321-51736b42bc9a@g10g2000yqh.googlegroups.com> <46c5c882-c38b-4439-a3cf-62783309cc08@t13g2000yqt.googlegroups.com> Message-ID: <877hwrf4vu.fsf@benfinney.id.au> "Nicola Larosa (tekNico)" writes: > Nicola Larosa wrote: > > Here's my take: > > > > ? ? excessblk = Block(total - P.BASE, srccol, > > carry_button_suppress=True > > ? ? ? ? ) if total > P.BASE else None > > Oops, it got shortened out: line longer than 72 chars, acceptable in > code, but not in email. I'll try again. Fine in email; just munged on your behalf (and probably without your knowledge) by your email service provider. If you don't want that happening, it's probably best to avoid Google Mail. -- \ ?I wish a robot would get elected president. That way, when he | `\ came to town, we could all take a shot at him and not feel too | _o__) bad.? ?Jack Handey | Ben Finney From eckhardt at satorlaser.com Wed Aug 26 03:03:27 2009 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 26 Aug 2009 09:03:27 +0200 Subject: Need help with Python scoping rules References: Message-ID: Jean-Michel Pichavant wrote: > class Color: > def __init__(self, r, g,b): > pass > BLACK = Color(0,0,0) > > It make sens from a design point of view to put BLACK in the Color > namespace. But I don't think it's possible with python. class Color: ... setattrib(Color, "BLACK", Color(0,0,0)) Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From deets at nospam.web.de Wed Aug 26 03:33:26 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Aug 2009 09:33:26 +0200 Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] In-Reply-To: <3da50b33-d79e-4579-9240-ef430ea7c697@m38g2000yqh.googlegroups.com> References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> <7fivlrF2lsrsuU1@mid.uni-berlin.de> <3da50b33-d79e-4579-9240-ef430ea7c697@m38g2000yqh.googlegroups.com> Message-ID: <7fk6q6F2jq5otU1@mid.uni-berlin.de> Evan Driscoll schrieb: > On Aug 25, 3:47 pm, Evan Driscoll wrote: >> So here is my simplified version that only works for globals: > > So I think this works if (1) you only use changed_value in the same > module as it's defined in (otherwise it picks up the globals from the > module it's defined in, which is almost certainly not what you want), > and (2) the value you want to change is just a simple variable and not > either something like "os.path" or a builtin. > > I have worked on this a bit more and have something that addresses > these issues in at least the cases I've tested. I'm not going to post > the code here, but it is up at > http://pages.cs.wisc.edu/~driscoll/python/utils.py > and there are a few unit tests at > http://pages.cs.wisc.edu/~driscoll/python/utils_test.py > > I solved issue (1) by reintroducing the use of inspect to walk back up > the stack a couple frames, but I pulled out the f_globals member > instead of f_locals. > > Issue (2a) I fixed by splitting the variable name at periods and > walking through successive dictionaries with each component. Issue > (2b) I fixed by looking for a '__builtins__' entry if the name I'm > looking up doesn't exist. > > Right now it's sort of hackish... it probably doesn't respond > particularly well if things go unexpectedly (e.g. a bad variable name > is given) and I should probably verify that the value is unchanged > during the with statement and throw an exception otherwise, but it > probably works well enough for my purposes for now. > > Comments are appreciated... a couple of the things in there it seems > like there could very well be reimplementations of things that are > already done. I'd still won't use it :) instead, something like this might be something I'd use, if I need a local "rebound". Or, again, just use a different *name* alltogether. foo = "bar" @apply def f(foo="baz"): ... Other than that, for your original use-case, I have a context-manager I call "safe modifier" that - takes an object, key and value - stores the old value of the key on the object - sets the new value - on exit, restores the old value This is for e.g. temporary config-changes in tests. Diez From deets at nospam.web.de Wed Aug 26 03:34:31 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Aug 2009 09:34:31 +0200 Subject: PyObject_CallFunction and writable memory In-Reply-To: References: Message-ID: <7fk6s7F2jq5otU2@mid.uni-berlin.de> Christopher Nebergall schrieb: > I'm working a patch to a hex editor (frhed) written in c++ so it can > load python scripts. Internally the c++ code has a unsigned char * of > possibly serveral hundred megs which I want to send into the python > code to modify. What is the best way to send the unsigned char * as > writable memory into the python code, so I don't have to duplicate the > memory in order to return a modified copy? I'm currently using > "PyObject_CallFunction(pFunc, "(s#)",p->lpbMemory, p->dwSize);" to > send an immutable string but I haven't seen what I need to set in the > format string which makes the data writable to python. The solution > can be for either python 2.6 or 3.1. Take a look at the buffer-protocol. Diez From deets at nospam.web.de Wed Aug 26 03:36:21 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Aug 2009 09:36:21 +0200 Subject: Python, qt, and lgpl In-Reply-To: <1e7a9056-db73-4c4f-be8a-f1b65a91daec@v20g2000yqm.googlegroups.com> References: <1e7a9056-db73-4c4f-be8a-f1b65a91daec@v20g2000yqm.googlegroups.com> Message-ID: <7fk6vlF2jq5otU3@mid.uni-berlin.de> sturlamolden schrieb: > On 25 Aug, 21:45, Terry Reedy wrote: > >> Will be good news if realized. > > Good news for everyone except Riverbank. And only if LGPL is something you can live with. Some projects require more liberal licenses. Or is there a commercial license available, too? Diez From benjamin at python.org Wed Aug 26 03:37:40 2009 From: benjamin at python.org (Benjamin Peterson) Date: Wed, 26 Aug 2009 07:37:40 +0000 (UTC) Subject: =?utf-8?b?UHlPYmplY3RfQ2FsbEZ1bmN0aW9u?= and writable memory References: Message-ID: Christopher Nebergall gmail.com> writes: > > I'm currently using > "PyObject_CallFunction(pFunc, "(s#)",p->lpbMemory, p->dwSize);" to > send an immutable string but I haven't seen what I need to set in the > format string which makes the data writable to python. The solution > can be for either python 2.6 or 3.1. Have a look at the buffer interface: http://docs.python.org/3.1/c-api/buffer.html From sdementen at gmail.com Wed Aug 26 03:50:17 2009 From: sdementen at gmail.com (seb) Date: Wed, 26 Aug 2009 00:50:17 -0700 (PDT) Subject: conditional for-statement References: Message-ID: <0fce5130-3057-4393-94a2-320568ddc072@n11g2000yqb.googlegroups.com> On Aug 25, 11:57?pm, Piet van Oostrum wrote: > You can also say: > [x+y for x in range(3) for y in range(4) if x < y] > If you want to write this as a loop you have to put the for's on > separate lines separated by colons, so why not the if also? Or would you > also like to have the for's on one line? indeed, we could have the for's on one line too. In fact, if you have a double loop without any body that is specific to the outer loop, you can merge the two lines. Similarly, if you have a loop with a if (ie filter) without any body having to be executed outside the if, having them on the same line is also clearer. | for x in range(3): | for x in range(3) for y in range(4): | for y in range(4): could be written as | body | body and | for x in range(3): | for x in range(3) if cond(x): | if cond(x): could be written as | body | body Such loops are in fact mentally just one loop over the cartesian product (product set) of the two iterators or over the filter set of the iterator respectively in these examples. Moreover, for 'body' longer than a couple of lines, it is quite useful to see immediately that there is no additional code that could be only specific to the outher loop ie, when writing all in one line, we can be sure that we do not have this situation | for x in range(3): | for y in range(4): | long body | ... | long body | body related to outer loop The naturalness of iteration in the various comprehensions and the generator expressions can be smoothly extended to the standard code iteration. BTW, I noticed this inconsistency when, coming back to python after a couple of weeks of no python programming, I started coding loops like for obj in list_obj if obj.Size > 100: print(obj) and got an error message about syntax. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org- Hide quoted text - > > - Show quoted text - From vlastimil.brom at gmail.com Wed Aug 26 04:05:17 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Wed, 26 Aug 2009 10:05:17 +0200 Subject: break unichr instead of fix ord? In-Reply-To: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: <9fdb569a0908260105s7858b648of081d439bb73e3ae@mail.gmail.com> 2009/8/25 : > In Python 2.5 on Windows I could do [*1]: > > ?# Create a unicode character outside of the BMP. > ?>>> a = u'\U00010040' > > ?# On Windows it is represented as a surogate pair. > ?>>> len(a) > ?2 > ?>>> a[0],a[1] > ?(u'\ud800', u'\udc40') > > ?# Create the same character with the unichr() function. > ?>>> a = unichr (65600) > ?>>> a[0],a[1] > ?(u'\ud800', u'\udc40') > > ?# Although the unichr() function works fine, its > ?# inverse, ord(), doesn't. > ?>>> ord (a) > ?TypeError: ord() expected a character, but string of length 2 found > > On Python 2.6, unichr() was "fixed" (using the word > loosely) so that it too now fails with characters outside > the BMP. > > ?>>> a = unichr (65600) > ?ValueError: unichr() arg not in range(0x10000) (narrow Python build) > > Why was this done rather than changing ord() to accept a > surrogate pair? > > Does not this effectively make unichr() and ord() useless > on Windows for all but a subset of unicode characters? > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, I'm not sure about the exact reasons for this behaviour on narrow builds either (maybe the consistency of the input/ output data to exactly one character?). However, if I need these functions for higher unicode planes, the following rather hackish replacements seem to work. I presume, there might be smarter ways of dealing with this, but anyway... hth, vbr #### not (systematically) tested ##################################### import sys def wide_ord(char): try: return ord(char) except TypeError: if len(char) == 2 and 0xD800 <= ord(char[0]) <= 0xDBFF and 0xDC00 <= ord(char[1]) <= 0xDFFF: return (ord(char[0]) - 0xD800) * 0x400 + (ord(char[1]) - 0xDC00) + 0x10000 else: raise TypeError("invalid character input") def wide_unichr(i): if i <= sys.maxunicode: return unichr(i) else: return ("\U"+str(hex(i))[2:].zfill(8)).decode("unicode-escape") From lib_team at yahoo.fr Wed Aug 26 04:08:48 2009 From: lib_team at yahoo.fr (=?iso-8859-1?Q?Pr=E9mon_Nom?=) Date: Wed, 26 Aug 2009 08:08:48 +0000 (GMT) Subject: Getting the current PyCFunction while in a python function Message-ID: <526667.17255.qm@web24301.mail.ird.yahoo.com> Hi I would like to get the PyCFunction object which corresponds to the current function which is executed. I call PyFrameObject* frame = PyEval_GetFrame() I try to parse frame->f_valuestack, but I don't know how to get the index of the function in the stack or event the size of the stack to be able to parse it (from end to begin and to stop on the first PyCFunctionObject). There is a member call stack size (frame->f_valuestack->f_code->co_stacksize) but it doesn't correspond to the frame->f_valuestack size :-( In fact i know that when i call "print(myFunctionPrintNumber(123)) There is PyCfunctionObject corresponding to myFunctionPrintNumber but i don't know how to acces it :/ because i don't know how to get/compute frame->f_valuestack size or to get/compute directly the index where the current executed function is. Please help me!!! Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon at brunningonline.net Wed Aug 26 04:14:33 2009 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 26 Aug 2009 09:14:33 +0100 Subject: Python for professsional Windows GUI apps? In-Reply-To: <63bb7834-80ac-4894-9ef5-2598ecac72cc@k19g2000yqn.googlegroups.com> References: <20090825132439.d6cb18ca.feliphil@gmx.net> <63bb7834-80ac-4894-9ef5-2598ecac72cc@k19g2000yqn.googlegroups.com> Message-ID: <8c7f10c60908260114q45ac2ae0i91fba0ed56808d6a@mail.gmail.com> 2009/8/26 geekworking : > If you are planning a database driven app, you should first settle on > a DB server. Any real enterprise DB system will put all of the > business logic in the database server. The choice of a front end > should be secondary. The trend for some years now has been to get behavior out of the database and into the application, where it belongs. True, we tend to keep the presentation tier separate too, but we really don't "put all of the business logic in the database server". Going back to the OP's question, it would be worth taking a look at what the resolver boys are up to: . -- Cheers, Simon B. From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 26 04:16:13 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 26 Aug 2009 10:16:13 +0200 Subject: Python on the Web In-Reply-To: References: Message-ID: <4a94ef42$0$27774$426a74cc@news.free.fr> Phil a ?crit : > I've seen lots of web sites explaining everything, but for whatever > reason I seem to not be picking something up. > I am a graphical person, which is probably the reason I haven't found > my answer. > May somebody please confirm if my diagram accurately represents the > stack, generally speaking. > > http://i26.tinypic.com/1fe82x.png Seems correct. > Even if that is the case, I'm having a hard time understanding the > differences. I guess wsgiref has absolutely nothing to do with FCGI/ > SCGI/CGI and simply receives and responds to HTTP requests following > the WSGI specification? Yeps. > Does it just spawn a new thread for each > request? Not AFAICT. > The way I am understanding the 'Production' side of that picture is > that the web server (eg. lighttpd) creates a single FCGI process. The > FCGI process is actually the entry point of the Framework/Application > which sets up Flup's WSGIServer, being the interface between FCGI and > the Framework/Application? What I mean is, it is just the code that > the web server loads to start with, example... > from flup.server.fcgi import WSGIServer > from app import application > WSGIServer(application).run() > ... Then for each HTTP request, Flup's WSGIServer creates a new thread > to handle the request? I didn't bother reading Flup's source code, but I suppose this might be the case. > As I've read elsewhere, "These days, FastCGI is never used directly. > Just like mod_python it is only used for the deployment of WSGI > applications." As far as I understand, the main (or only?) reasoning > for this is because WSGI makes Python applications easier to deploy > without having to worry about whether using FCGI/SCGI/CGI. Nor about which web server you use (Apache, lighthttpd, whatever). > What would be involved to run Python on the web using FCGI without > WSGI? I can feel the flames already. This isn't the only reason I want > to know, but one reason is that I want to use Python 3.1 and as I > understand, this will have to wait for the WSGI 2.0 specification to > ensure time isn't wasted. My humble opinion (based on years of experience in both Python and web programming) is that you're taking the wrong approach. I can only second Robert Kern here: use an existing, well maintained wsgi-compliant framework like Django, Pylons etc, and wait for the framework to be ported to python 3.x. Any other solution will almost certainly end up needing a complete rewrite anytime soon. > I apologize if the questions are ridiculous. I've just recently got > into web programming and it seems that in order for me to use Python, > I need a deep understanding of web servers, HTTP, FCGI, etc. Programming for the web - whatever the language & techno - indeed require a deep (or at least correct) understanding of HTTP and web servers, yes. Even with the abstraction layers provided by frameworks, you still need to understand how the whole damn thing works, what's an HTTP resquest & response and quite a few other things as well. From frank at chagford.com Wed Aug 26 04:22:41 2009 From: frank at chagford.com (Frank Millman) Date: Wed, 26 Aug 2009 10:22:41 +0200 Subject: Move dictionary from instance to class level Message-ID: Hi all I have a class that uses a dictionary to map message numbers to methods. Here is a simple example - class MyClass(object): def __init__(self): self.method_dict = {} self.method_dict[0] = self.method_0 self.method_dict[1] = self.method_1 def on_message_received(self, msg): self.method_dict[msg]() def method_0(self): print 'in method_0' def method_1(self): print 'in method_1' I have quite a few methods, so the dictionary is growing - up to 28 methods so far. To avoid having to recreate the dictionary every time I create an instance of the class, I tried to move it up to the class level. Unfortunately it does not work. This is what I tried - class MyClass(object): method_dict = {} method_dict[0] = method_0 # this gives an error method_dict[1] = method_1 def on_message_received(self, msg): self.method_dict[msg]() def method_0(self): print 'in method_0' def method_1(self): print 'in method_1' As written above, I get the following error - NameError: name 'method_0' is not defined If I try self.method_0, I get 'self' is not defined. If I try __class__.method_0, I get '__class__' is not defined. If I try MyClass.method_0, I get 'MyClass' is not defined. Is there any variation on this theme that will work? #---------------------------------------------------- Ok, I found a variation that seems to work. Is this the preferred way, or is there a better alternative? class MyClass(object): def on_message_received(self, msg): #self.method_dict[msg]() # had to change this to get it to work self.method_dict[msg](self) def method_0(self): print 'in method_0' def method_1(self): print 'in method_1' MyClass.method_dict = {} MyClass.method_dict[0] = MyClass.method_0 MyClass.method_dict[1] = MyClass.method_1 As you can see, I had to add 'self' to the method arguments when calling the method. Any comments? Thanks Frank Millman From tw55413 at gmail.com Wed Aug 26 04:29:52 2009 From: tw55413 at gmail.com (erikj) Date: Wed, 26 Aug 2009 01:29:52 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: <7f519c34-2d6e-4fff-9489-dae43c6b2df1@r42g2000yqj.googlegroups.com> Hi, You could have a look at Camelot, to see if it fits your needs : http://www.conceptive.be/projects/camelot/ it was developed with cross platform business apps in mind. when developing Camelot, we tried to build it using wxWidgets first (because of the licensing at that time), but it turned out that developing with QT proved to be much more straightforward. QT is documented very well and you seldom encounter 'strange' issues that cost hours of time to pinpoint and fix. the datagrid was developed to be able to handle millions of database records without glitches and is flexible thanks to QT's model-view-delegate framework. we do print barcodes with this app (even directly to zebra printers) if you have questions regarding Camelot, please feel free to post on our mailing list : http://groups.google.com/group/project-camelot Regards, Erik On Aug 24, 2:08?pm, Gilles Ganault wrote: > Hello > > ? ? ? ? I was wondering if some people in this ng use Python and some GUI > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > applications, and if yes, what it's like, the pros and cons, etc. > > I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. > > I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. > > Thank you. From pierre.gaillard at gmail.com Wed Aug 26 04:30:32 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Wed, 26 Aug 2009 01:30:32 -0700 (PDT) Subject: quantiles of a student distribution Message-ID: Hello... Do you know how I can calculate the quantiles of a student distribution in pyhton ? Thanks From piet at cs.uu.nl Wed Aug 26 04:41:56 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 26 Aug 2009 10:41:56 +0200 Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> <84154e6e-c425-4b71-89e3-7d2877a19418@m7g2000prd.googlegroups.com> Message-ID: >>>>> 7stud (7) wrote: >7> Thanks for the response. My OS is mac osx 10.4.11. I'm not really >7> sure how to check my locale settings. Here is some stuff I tried: >7> $ echo $LANG >7> $ echo $LC_ALL >7> $ echo $LC_CTYPE >7> $ locale >7> LANG= >7> LC_COLLATE="C" >7> LC_CTYPE="C" >7> LC_MESSAGES="C" >7> LC_MONETARY="C" >7> LC_NUMERIC="C" >7> LC_TIME="C" >7> LC_ALL="C" IIRC, Mac OS X 10.4 does not set LANG or LC_* automatically. In 10.5 Terminal has an option in the preferences to set LANG according to the encoding chosen (and presumably the language of the user). -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From clp2 at rebertia.com Wed Aug 26 04:54:05 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 26 Aug 2009 01:54:05 -0700 Subject: Move dictionary from instance to class level In-Reply-To: References: Message-ID: <50697b2c0908260154y2f4f6852ga3d6a3c41bd768de@mail.gmail.com> On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote: > Hi all > > I have a class that uses a dictionary to map message numbers to methods. > > Here is a simple example - > > ? ?class MyClass(object): > ? ? ? ?def __init__(self): > ? ? ? ? ? ?self.method_dict = {} > ? ? ? ? ? ?self.method_dict[0] = self.method_0 > ? ? ? ? ? ?self.method_dict[1] = self.method_1 > > ? ? ? ?def on_message_received(self, msg): > ? ? ? ? ? ?self.method_dict[msg]() > > ? ? ? ?def method_0(self): > ? ? ? ? ? ?print 'in method_0' > > ? ? ? ?def method_1(self): > ? ? ? ? ? ?print 'in method_1' > > I have quite a few methods, so the dictionary is growing - up to 28 methods > so far. To avoid > having to recreate the dictionary every time I create an instance of the > class, I tried to move it > up to the class level. Unfortunately it does not work. This is what I > tried - > > ? ?class MyClass(object): > ? ? ? ?method_dict = {} > ? ? ? ?method_dict[0] = method_0 ?# this gives an error > ? ? ? ?method_dict[1] = method_1 > > ? ? ? ?def on_message_received(self, msg): > ? ? ? ? ? ?self.method_dict[msg]() > > ? ? ? ?def method_0(self): > ? ? ? ? ? ?print 'in method_0' > > ? ? ? ?def method_1(self): > ? ? ? ? ? ?print 'in method_1' > > As written above, I get the following error - > ? ?NameError: name 'method_0' is not defined > > If I try self.method_0, I get 'self' is not defined. Right, because you're in the *class* body; there's no "current instance" to be "self"; in fact, there's not even any class for there to be instances of yet. > If I try __class__.method_0, I get '__class__' is not defined. Right, because the class isn't created until its body has finished executing > If I try MyClass.method_0, I get 'MyClass' is not defined. See previous note. The class name can't be bound to anything until the class itself has been created. > Is there any variation on this theme that will work? > > #---------------------------------------------------- > > Ok, I found a variation that seems to work. > > Is this the preferred way, or is there a better alternative? A class MyClass(object): def on_message_received(self, msg): self.method_dict[msg](self) def method_0(self): print 'in method_0' def method_1(self): print 'in method_1' method_dict method_dict = {0: method_0, 1: method_1} #note this comes *after* the methods in question have been defined Is there some reason you aren't using a list instead of a dict? e.g. method_dict = [method_0, method_1, method_2, etc] For that matter, why are you associating methods with integers in the first place? Cheers, Chris -- http://blog.rebertia.com From mriedel at inova-semiconductors.de Wed Aug 26 04:56:28 2009 From: mriedel at inova-semiconductors.de (Michael Riedel) Date: Wed, 26 Aug 2009 10:56:28 +0200 Subject: Q: multiprocessing.Queue size limitations or bug... Message-ID: <4A94F8BC.8050304@inova-semiconductors.de> Sorry for being not more specific but I'm not absolutely certain whether I encountered a bug or did anything wrong: The (stupid) code below results in a stall forever or not at 'p0.join()' depending on the value of TROUBLE_MAKER. Any help, thoughts, comments? Thank you for your time. Michael # ---------------------------------------------------------------------- from multiprocessing import Process, Queue # bit vector size BVS=8 # TROUBLE_MAKER=12 # for greater values p0.join() is never satisfied... def evaluate(q, id, start=0, stop=2**BVS): cmin = {0: []} for mask0 in range(start, stop): for mask1 in range(0, 2**BVS): for mask2 in range(mask1, TROUBLE_MAKER): cmin[0].append((mask0, mask1, mask2)) print 'process %d finished (dict layout: %d/%d)...' % (id, len(cmin), len(cmin[0])) q.put(cmin.copy()) q.close() if __name__ == '__main__': q0 = Queue() q1 = Queue() q2 = Queue() q3 = Queue() part = 2**BVS/4 p0 = Process(target=evaluate, args=(q0, 0, 0*part, 1*part), name='worker_0') p1 = Process(target=evaluate, args=(q1, 1, 1*part, 2*part), name='worker_1') p2 = Process(target=evaluate, args=(q2, 2, 2*part, 3*part), name='worker_2') p3 = Process(target=evaluate, args=(q3, 3, 3*part, 4*part), name='worker_3') p0.start() print 'process 0 started...' p1.start() print 'process 1 started...' p2.start() print 'process 2 started...' p3.start() print 'process 3 started...' # main process stalls at p0.join() for bigger TROUBLE_MAKER p0.join() p1.join() p2.join() p3.join() res0 = q0.get() res1 = q1.get() res2 = q2.get() res3 = q3.get() print 'results fetched...' # ---------------------------------------------------------------------- -- From eckhardt at satorlaser.com Wed Aug 26 05:04:43 2009 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 26 Aug 2009 11:04:43 +0200 Subject: Need help with Python scoping rules References: Message-ID: Ulrich Eckhardt wrote: > Jean-Michel Pichavant wrote: >> class Color: >> def __init__(self, r, g,b): >> pass >> BLACK = Color(0,0,0) >> >> It make sens from a design point of view to put BLACK in the Color >> namespace. But I don't think it's possible with python. > > class Color: > ... > > setattrib(Color, "BLACK", Color(0,0,0)) Apart from it being "setattr" and not "setattrib", a simple Color.BLACK = Color(0,0,0) should have done the job here. However, what I had in mind was this: class Color: _colors = [ ("BLACK", (0,0,0)), ("WHITE", (1,1,1)) ] def __str__(self): # try to locate a name for name, rgb in Color._colors: if self.rgb==rgb: return name # no name found, just format as a triplet return "(%s, %s, %s)" % self.rgb # add symbolic names for name, rgb in Color._colors: setattr(Colors, name, Color(rgb)) ...which I got as suggestion on my question how to model C enumeration lookalikes. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From frank at chagford.com Wed Aug 26 05:21:03 2009 From: frank at chagford.com (Frank Millman) Date: Wed, 26 Aug 2009 11:21:03 +0200 Subject: Move dictionary from instance to class level References: Message-ID: On Aug 26, 10:54 am, Chris Rebert wrote: > On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote: > > A > > class MyClass(object): > def on_message_received(self, msg): > self.method_dict[msg](self) > > def method_0(self): > print 'in method_0' > > def method_1(self): > print 'in method_1' > method_dict > > method_dict = {0: method_0, 1: method_1} > #note this comes *after* the methods in question have been defined > Thanks, Chris. This is much better. > Is there some reason you aren't using a list instead of a dict? > e.g. method_dict = [method_0, method_1, method_2, etc] > > For that matter, why are you associating methods with integers in the > first place? > I actually use constants to define my messages, like this - (MESSAGE_ONE ,MESSAGE_TWO ,MESSAGE_THREE ) = xrange(3) I can then refer to the messages by their description, but internally it uses integers. Frank From frank at chagford.com Wed Aug 26 05:22:21 2009 From: frank at chagford.com (Frank Millman) Date: Wed, 26 Aug 2009 11:22:21 +0200 Subject: Move dictionary from instance to class level References: Message-ID: <6ZKdnagdF6mZnwjXnZ2dnUVZ8jKdnZ2d@saix.net> On Aug 26, 10:54 am, Chris Rebert wrote: > On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote: > > A > > class MyClass(object): > def on_message_received(self, msg): > self.method_dict[msg](self) > > def method_0(self): > print 'in method_0' > > def method_1(self): > print 'in method_1' > method_dict > > method_dict = {0: method_0, 1: method_1} > #note this comes *after* the methods in question have been defined > Thanks, Chris. This is much better. > Is there some reason you aren't using a list instead of a dict? > e.g. method_dict = [method_0, method_1, method_2, etc] > > For that matter, why are you associating methods with integers in the > first place? > I actually use constants to define my messages, like this - (MESSAGE_ONE ,MESSAGE_TWO ,MESSAGE_THREE ) = xrange(3) I can then refer to the messages by their description, but internally it uses integers. Frank From frank at chagford.com Wed Aug 26 05:22:21 2009 From: frank at chagford.com (Frank Millman) Date: Wed, 26 Aug 2009 11:22:21 +0200 Subject: Move dictionary from instance to class level References: Message-ID: On Aug 26, 10:54 am, Chris Rebert wrote: > On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote: > > A > > class MyClass(object): > def on_message_received(self, msg): > self.method_dict[msg](self) > > def method_0(self): > print 'in method_0' > > def method_1(self): > print 'in method_1' > method_dict > > method_dict = {0: method_0, 1: method_1} > #note this comes *after* the methods in question have been defined > Thanks, Chris. This is much better. > Is there some reason you aren't using a list instead of a dict? > e.g. method_dict = [method_0, method_1, method_2, etc] > > For that matter, why are you associating methods with integers in the > first place? > I actually use constants to define my messages, like this - (MESSAGE_ONE ,MESSAGE_TWO ,MESSAGE_THREE ) = xrange(3) I can then refer to the messages by their description, but internally it uses integers. Frank From frank at chagford.com Wed Aug 26 05:48:38 2009 From: frank at chagford.com (Frank Millman) Date: Wed, 26 Aug 2009 11:48:38 +0200 Subject: Move dictionary from instance to class level References: Message-ID: "Frank Millman" wrote: Apologies for the triple-post. I use google-groups for reading c.l.py, but I know that some people reject messages from there due to the volume of spam, so on the odd occasion when I want to send something I fire up Outlook Express and send it from there. It seems to be misbehaving today. Sorry about that. Frank From somebody at somewhere.com Wed Aug 26 05:52:09 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Wed, 26 Aug 2009 10:52:09 +0100 Subject: Help with arrays References: Message-ID: Dave Angel wrote: > With this change the best solution changes from a random shuffle to a > binary search. Which is not what the OP asked for. Anyway, I think whatever solution is chosen it's probably best written as a generator. The new pushback syntax may prove useful. -- Stephen Fairchild From dksreddy at gmail.com Wed Aug 26 06:05:41 2009 From: dksreddy at gmail.com (Sandy) Date: Wed, 26 Aug 2009 03:05:41 -0700 (PDT) Subject: all possible matchings of elements of two lists Message-ID: Hi all, I basically want all possible matchings of elements from two lists, Ex: [1,2] [a,b,c] Required: [ [(1,a),(2,b)] [(1,b),(2,c)] [(1,c),(2,b)] [(1,b),(2,a)] [(1,c),(2,a)] [(1,a),(2,c)] ] My thought is to get all possible permutations of two lists given and select any combination and use zip to get the tuples. Repeat this for all possible combinations. Any other ideas? Sandy From no.email at please.post Wed Aug 26 06:08:38 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 10:08:38 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: In John Posner writes: >Stephen Hansen said: >> This sounds like a fundamental confusion -- a namespace is not >> equivalent to a scope, really, I think. >> ... Hmm. I can't find Stephen Hansen's original post anywhere. Where did you come across it? Is there an *official* write-up where these issues are discussed? To put it differently, where exactly in the Python docs would someone learning Python go to answer my original query? TIA! kynn From pavlovevidence at gmail.com Wed Aug 26 06:16:32 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Aug 2009 03:16:32 -0700 (PDT) Subject: Python, qt, and lgpl References: <1e7a9056-db73-4c4f-be8a-f1b65a91daec@v20g2000yqm.googlegroups.com> Message-ID: On Aug 25, 5:04?pm, sturlamolden wrote: > On 25 Aug, 21:45, Terry Reedy wrote: > > > Will be good news if realized. > > Good news for everyone except Riverbank. Oh well, Riverbank could have played ball but they didn't, so I guess I don't care if it's bad news for them. Carl Banks From manish.paradkar at gmail.com Wed Aug 26 06:28:01 2009 From: manish.paradkar at gmail.com (manish) Date: Wed, 26 Aug 2009 18:28:01 +0800 Subject: Python Processor Message-ID: <7670c8130908260328l6982ef4etad802a755b85a44f@mail.gmail.com> Hi, I am also wondering about how to implement a soft core reconfigurable processor in a FPGA which would directly execute the compiled python bytecode. I am trying to understand the bytecode format but apart from http://docs.python.org/library/dis.html there is hardly any documentation on the python bytecodes. Before going through the one of the existing VM implementations, i want to know if there is there any informaition available which elaborates on the structure of the bytecodes. Like details regarding co_names, co_cellvars, co_freevars, the concept of frames, global, local, objects, functions etc with respect to the bytecode. Thanks Manish -------------- next part -------------- An HTML attachment was scrubbed... URL: From robin at reportlab.com Wed Aug 26 06:30:22 2009 From: robin at reportlab.com (Robin Becker) Date: Wed, 26 Aug 2009 11:30:22 +0100 Subject: ubuntu dist-packages Message-ID: <4A950EBE.1090707@chamonix.reportlab.co.uk> I was surprised a couple of days ago when trying to assist a colleage with his python setup on a ubuntu 9.04 system. We built our c-extensions and manually copied them into place, but site-packages wasn't there. It seems that ubuntu now wants stuff to go into lib/python2.6/dist-packages. What is the relation between dist-packages/site-packages if any? Is this just a name change or is there some other problem being addressed? For developers is it best just to create one's own private installations from the original tarballs? -- Robin Becker From dksreddy at gmail.com Wed Aug 26 06:32:35 2009 From: dksreddy at gmail.com (dksr) Date: Wed, 26 Aug 2009 03:32:35 -0700 (PDT) Subject: all possible matchings of elements of two lists References: Message-ID: <2eb06442-7369-4c9f-83ad-b8f9d3d08c07@d4g2000yqa.googlegroups.com> Ok this is how I do it: l1 = [1,2] l2= ['a','b','c'] res = [] l2 = permute(l2) for i in l2: lis = [l1,l2] res.append(zip(*lis)) # or use map depending on what u want res.append(map(None,*lis)) print res On Aug 26, 11:05?am, Sandy wrote: > Hi all, > I basically want all possible matchings of elements from two lists, > Ex: [1,2] [a,b,c] > > Required: > ? ?[ [(1,a),(2,b)] > ? ? ?[(1,b),(2,c)] > ? ? ?[(1,c),(2,b)] > ? ? ?[(1,b),(2,a)] > ? ? ?[(1,c),(2,a)] > ? ? ?[(1,a),(2,c)] > ? ?] > > My thought is to get all possible permutations of two lists given and > select any combination and use zip to get the tuples. Repeat this for > all possible combinations. > > Any other ideas? > Sandy From ryniek90 at gmail.com Wed Aug 26 06:44:07 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Wed, 26 Aug 2009 12:44:07 +0200 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile In-Reply-To: References: Message-ID: <4A9511F7.7030909@gmail.com> > [snip] >>>> Here's my script code: >>>> *http://paste.ubuntu.com/259310/ >>>> >>>> *Shouldn't that bug be patched already :-? >>> Are you giving it the contents of the file when it's actually expecting >>> the filename? >>> >> >> Of course the content of the file: > [snip] >> See? *backup_obj.add(read_obj.read())* >> In previous pasted Traceback you can see >> *backup_obj.add(read_bin_obj)* - read_obj_bin was a reference to the >> *read_obj.read()* . >> > The documentation lists the methods "add" and "addfile". Pick one and > provide the values it's expecting. For example, if you choose "add" then > provide the filename, not the contents of the file. > >> Do only I have this problem or Python programming under Windows is >> nightmare? > > It's only a nightmare if you don't follow the documentation. :-) > Hahah right. My fault. Must remember to read documentation so many times until I find the solution. Thanks, now works fine. :-) From deets at nospam.web.de Wed Aug 26 06:46:13 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Aug 2009 12:46:13 +0200 Subject: ubuntu dist-packages References: Message-ID: <7fki3lF2kirnkU1@mid.uni-berlin.de> Robin Becker wrote: > I was surprised a couple of days ago when trying to assist a colleage with > his python setup on a ubuntu 9.04 system. > > We built our c-extensions and manually copied them into place, but > site-packages wasn't there. It seems that ubuntu now wants stuff to go > into lib/python2.6/dist-packages. > > What is the relation between dist-packages/site-packages if any? Is this > just a name change or is there some other problem being addressed? > > For developers is it best just to create one's own private installations > from the original tarballs? I don't know much about the atrocities distributions commit to python-installations (ripping out distutils "because it's a developer-only thing", trying to save a few bytes here and there by unifying install-locations between interpreter versions and whatnot), but I think the main problem is that you don't use distutils - or setuptools (that gets often a bad rap even if for most cases it works flawless) If you'd use that to build & install your extension, it would figure out where to place the resulting package (or egg) by itself. Diez From dickinsm at gmail.com Wed Aug 26 06:52:22 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 26 Aug 2009 03:52:22 -0700 (PDT) Subject: all possible matchings of elements of two lists References: Message-ID: On Aug 26, 11:05?am, Sandy wrote: > Hi all, > I basically want all possible matchings of elements from two lists, > Ex: [1,2] [a,b,c] > > Required: > ? ?[ [(1,a),(2,b)] > ? ? ?[(1,b),(2,c)] > ? ? ?[(1,c),(2,b)] > ? ? ?[(1,b),(2,a)] > ? ? ?[(1,c),(2,a)] > ? ? ?[(1,a),(2,c)] > ? ?] If you're using Python 2.6 (or 3.1), you might find the itertools module helpful: Python 2.6.2 (r262:71600, Aug 26 2009, 09:40:44) [GCC 4.2.1 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import itertools >>> for p in itertools.permutations('abc', 2): print zip([1,2], p) ... [(1, 'a'), (2, 'b')] [(1, 'a'), (2, 'c')] [(1, 'b'), (2, 'a')] [(1, 'b'), (2, 'c')] [(1, 'c'), (2, 'a')] [(1, 'c'), (2, 'b')] -- Mark From no.email at please.post Wed Aug 26 06:57:32 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 10:57:32 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: In <7figv3F2m3p0dU1 at mid.uni-berlin.de> "Diez B. Roggisch" writes: >Classes are not scopes. This looks to me like a major wart, on two counts. First, one of the goals of OO is encapsulation, not only at the level of instances, but also at the level of classes. Your comment suggests that Python does not fully support class-level encapsulation. Second, my example shows that Python puts some peculiar restrictions on recursion. Recursion! One of the central concepts in the theory of functions! This is shown most clearly by the following elaboration of my original example: class Demo(object): def fact_rec(n): if n < 2: return 1 else: return n * fact_rec(n - 1) def fact_iter(n): ret = 1 for i in range(1, n + 1): ret *= i return ret classvar1 = fact_iter(5) classvar2 = fact_rec(5) This code won't compile as shown, but it does compile if the last line (the call to the recursive fact_rec) is commented out. There is no justification for discriminating against recursive functions in this context. Recursive functions should be OK wherever functions are OK. I can't think of any other language that allows recursion but not anywhere. Is there any good reason (from the point of view of Python's overall design) for not fixing this? kynn From chris0wj at gmail.com Wed Aug 26 07:25:13 2009 From: chris0wj at gmail.com (Chris) Date: Wed, 26 Aug 2009 04:25:13 -0700 (PDT) Subject: multiprocessing managers and socket connection. References: <722664f1-81af-45da-ae40-070bca8f3ee0@k6g2000yqn.googlegroups.com> <0af6687a-e36d-47c3-af5e-7e66eacbb3ce@v23g2000pro.googlegroups.com> Message-ID: <7d8f3f17-3cd7-4eb1-b049-2990d638cc46@o6g2000yqj.googlegroups.com> On Aug 25, 9:11?pm, Terry wrote: > On Aug 25, 10:14?pm, Chris wrote: > > > > > I've been using multiprocessing managers and I really like the > > functionality. > > > I have a question about reconnecting to a manager. I have a situation > > where I start on one machine (A) a manager that is listening and then > > on another machine (B) connects to that manager and uses its proxy > > object to call functions on the manager's computer; this all works as > > expected. But, if the manager from A shuts down, B's application won't > > notice because in the MP code it ignores socket error > > errno.ECONNREFUSED. If A becomes available again or is restarted, B > > doesn't automatically reconnect either and continue its operation. > > It's function is basically stopped. > > > Here is the code from connection.py: > > while 1: > > ? ? ? ? try: > > ? ? ? ? ? ? s.connect(address) > > ? ? ? ? except socket.error, e: > > ? ? ? ? ? ? if e.args[0] != errno.ECONNREFUSED: # connection refused > > ? ? ? ? ? ? ? ? debug('failed to connect to address %s', address) > > ? ? ? ? ? ? ? ? raise > > ? ? ? ? ? ? time.sleep(0.01) > > ? ? ? ? else: > > ? ? ? ? ? ? break > > > How can I have B automatically reconnect to A and continue its work > > once A is available again? > > I think you need to retry repeatedly until successfully connected. > > br, Terry I'm having issue after once connected. If the server goes down during a long-running connection. I would want to be notified so I could try to reconnect. I'm doing more experimenting now and will try to post an example. From tibor.beck at hotmail.com Wed Aug 26 07:44:25 2009 From: tibor.beck at hotmail.com (gentlestone) Date: Wed, 26 Aug 2009 04:44:25 -0700 (PDT) Subject: Usefull python tutorial Message-ID: <0bd7592d-d705-4938-b13d-61157d7fbc7a@c2g2000yqi.googlegroups.com> Can somebody give me an advise where I can found a really good online tutorial? All I found are useless. For example no tutorial I found explains this piece of code: someList = [element for element in otherList if element is not None] or this example: a = a or [] There are only stupid elementary examples in the tutorials I found. From pavlovevidence at gmail.com Wed Aug 26 07:52:43 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Aug 2009 04:52:43 -0700 (PDT) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> On Aug 26, 3:57?am, kj wrote: > In <7figv3F2m3p0... at mid.uni-berlin.de> "Diez B. Roggisch" writes: > > >Classes are not scopes. > > This looks to me like a major wart, on two counts. Class statements *are* scopes, they are just not accessible from scopes nested within them. > First, one of the goals of OO is encapsulation, not only at the > level of instances, but also at the level of classes. ?Your comment > suggests that Python does not fully support class-level encapsulation. I can't answer this, I don't even know what you are talking about. The OO notion of encapsulation that I'm familar means that an object can seal off access to private data. This has nothing to do with class statement scoping. > Second, my example shows that Python puts some peculiar restrictions > on recursion. ?Recursion! ?One of the central concepts in the theory > of functions! ?This is shown most clearly by the following elaboration > of my original example: > > class Demo(object): > ? ? def fact_rec(n): > ? ? ? ? if n < 2: > ? ? ? ? ? ? return 1 > ? ? ? ? else: > ? ? ? ? ? ? return n * fact_rec(n - 1) > > ? ? def fact_iter(n): > ? ? ? ? ret = 1 > ? ? ? ? for i in range(1, n + 1): > ? ? ? ? ? ? ret *= i > ? ? ? ? return ret > > ? ? classvar1 = fact_iter(5) > ? ? classvar2 = fact_rec(5) > > This code won't compile as shown, but it does compile if the last > line (the call to the recursive fact_rec) is commented out. ?There > is no justification for discriminating against recursive functions > in this context. ?Recursive functions should be OK wherever functions > are OK. ?I can't think of any other language that allows recursion > but not anywhere. Inside class statements are not the place for this kind of thing. Define functions like fact_rec outside the class statement. > Is there any good reason (from the point of view of Python's overall > design) for not fixing this? I suspect that no reason, however profound, would satisfy you. Therefore I will merely answer your question without fanfare, and you can take it as you will. 1. One of the key aspects of Python's design is that attributes must be accessed explicitly with dot notation. Accessing class scopes from nested functions would (seemingly) allow access to class attributes without the dotted notation. Therefore it is not allowed. 2. This is considered more important that your ability to define recursive functions in the class statement. Carl Banks From cevomed at gmail.com Wed Aug 26 07:53:01 2009 From: cevomed at gmail.com (=?ISO-8859-9?Q?Cevahir_Demirk=FDran?=) Date: Wed, 26 Aug 2009 13:53:01 +0200 Subject: Division and right shift in python In-Reply-To: References: <3f74e020908251648k7b391a09g78b155507b2f23c4@mail.gmail.com> Message-ID: <3f74e020908260453p181d8134va4047019b60831b1@mail.gmail.com> Thanks for the answer. Run it with a big number: f2(9230821908403878236537264867326482638462035732098490238409328947638257462745672354627356427356742563256745362772537532756732673275732,9) I had this result: 8.1015883211e-06 1.06158743591e-05 512 2009/8/26 Mark Tolonen > > > "Cevahir Demirkiran" wrote in message > news:3f74e020908251648k7b391a09g78b155507b2f23c4 at mail.gmail.com... > > Hi, >> >> I would like to do a floor division by a power of 2 in python to make it >> faster than / (modular division in 2.x). >> However, it is slower. >> What is the reason of that? >> I checked them via: >> >> def f2(x,n): >> t1 = clock() >> r = x/pow(2,n) >> t2 = clock() >> print (t2-t1) >> print r >> t2 = clock() >> r = x>>n >> t3 = clock() >> print (t3-t2) >> print r >> >> > It's not slower on my system, but note the inconsistent results also: > > f2(1024,5) >>>> >>> 3.47396033483e-06 > 32 > 2.19077375482e-06 > 32 > >> f2(1024,5) >>>> >>> 4.84135603429e-06 > 32 > 3.08499440393e-06 > 32 > >> f2(1024,5) >>>> >>> 4.6782844052e-06 > 32 > 3.77604384028e-06 > 32 > > Time it with timeit... > > C:\>python -m timeit -n 10000000 -s x=1024 "x>>5" > 10000000 loops, best of 3: 0.113 usec per loop > > C:\>python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" > 10000000 loops, best of 3: 0.468 usec per loop > > Right-shift is over 4x faster. > > -Mark > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Cevahir Demirkiran -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Aug 26 08:11:25 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 26 Aug 2009 05:11:25 -0700 Subject: Usefull python tutorial In-Reply-To: <0bd7592d-d705-4938-b13d-61157d7fbc7a@c2g2000yqi.googlegroups.com> References: <0bd7592d-d705-4938-b13d-61157d7fbc7a@c2g2000yqi.googlegroups.com> Message-ID: <50697b2c0908260511u7445f434x6fc8481c2bb5c305@mail.gmail.com> On Wed, Aug 26, 2009 at 4:44 AM, gentlestone wrote: > Can somebody give me an advise where I can found a really good online > tutorial? All I found are useless. For example no tutorial I found > explains this piece of code: > > ? ?someList = [element for element in otherList if element is not > None] See http://docs.python.org/tutorial/datastructures.html#list-comprehensions > or this example: > > ? ?a = a or [] That's a bit more obscure, and I'm not entirely surprised it's not in a tutorial: http://docs.python.org/reference/expressions.html#boolean-operations You might want to try the official tutorial (unless it's the one you're complaining about): http://docs.python.org/tutorial/index.html I've also heard good things about Dive Into Python: http://diveintopython.org/ Cheers, Chris -- http://blog.rebertia.com From cevomed at gmail.com Wed Aug 26 08:17:48 2009 From: cevomed at gmail.com (=?ISO-8859-9?Q?Cevahir_Demirk=FDran?=) Date: Wed, 26 Aug 2009 14:17:48 +0200 Subject: Division and right shift in python In-Reply-To: <3f74e020908260453p181d8134va4047019b60831b1@mail.gmail.com> References: <3f74e020908251648k7b391a09g78b155507b2f23c4@mail.gmail.com> <3f74e020908260453p181d8134va4047019b60831b1@mail.gmail.com> Message-ID: <3f74e020908260517y77d6824esa9813b64031f5bf8@mail.gmail.com> The previous one was slower but now it is faster. How can I make this more consistent? Why cannot I control it? Where can I find the algorithms implemented under for example pow, /, %, etc.? I could not see them in python documentation? f2(281367918279371279712863756486284619792197836426862028028824908239084023984967328564836783686836834628136791827937127971286375648628461979219783642686202802882490823908402398496732856483678368683683462813679182793712797128637564862846197921978364268620280288249082390840239849673285648367836868368346,9) 8.3809534317e-06 6.70476276809e-06 512 Thanks in advance, 26 A?ustos 2009 13:53 tarihinde Cevahir Demirk?ran yazd?: > Thanks for the answer. > Run it with a big number: > > f2(9230821908403878236537264867326482638462035732098490238409328947638257462745672354627356427356742563256745362772537532756732673275732,9) > > I had this result: > > 8.1015883211e-06 > 1.06158743591e-05 > 512 > > 2009/8/26 Mark Tolonen > > > > >> "Cevahir Demirkiran" wrote in message >> news:3f74e020908251648k7b391a09g78b155507b2f23c4 at mail.gmail.com... >> >> Hi, >>> >>> I would like to do a floor division by a power of 2 in python to make it >>> faster than / (modular division in 2.x). >>> However, it is slower. >>> What is the reason of that? >>> I checked them via: >>> >>> def f2(x,n): >>> t1 = clock() >>> r = x/pow(2,n) >>> t2 = clock() >>> print (t2-t1) >>> print r >>> t2 = clock() >>> r = x>>n >>> t3 = clock() >>> print (t3-t2) >>> print r >>> >>> >> It's not slower on my system, but note the inconsistent results also: >> >> f2(1024,5) >>>>> >>>> 3.47396033483e-06 >> 32 >> 2.19077375482e-06 >> 32 >> >>> f2(1024,5) >>>>> >>>> 4.84135603429e-06 >> 32 >> 3.08499440393e-06 >> 32 >> >>> f2(1024,5) >>>>> >>>> 4.6782844052e-06 >> 32 >> 3.77604384028e-06 >> 32 >> >> Time it with timeit... >> >> C:\>python -m timeit -n 10000000 -s x=1024 "x>>5" >> 10000000 loops, best of 3: 0.113 usec per loop >> >> C:\>python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" >> 10000000 loops, best of 3: 0.468 usec per loop >> >> Right-shift is over 4x faster. >> >> -Mark >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > Cevahir Demirkiran > -- Cevahir Demirkiran -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon at brunningonline.net Wed Aug 26 08:17:57 2009 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 26 Aug 2009 13:17:57 +0100 Subject: Usefull python tutorial In-Reply-To: <0bd7592d-d705-4938-b13d-61157d7fbc7a@c2g2000yqi.googlegroups.com> References: <0bd7592d-d705-4938-b13d-61157d7fbc7a@c2g2000yqi.googlegroups.com> Message-ID: <8c7f10c60908260517q6819c17qd5bd6070b02eace9@mail.gmail.com> 2009/8/26 gentlestone : > Can somebody give me an advise where I can found a really good online > tutorial? All I found are useless. is really good, as I remember, as is . For example no tutorial I found > explains this piece of code: > > ? ?someList = [element for element in otherList if element is not > None] or > or this example: > > ? ?a = a or [] Strangely not in the tutorial: . -- Cheers, Simon B. From davea at ieee.org Wed Aug 26 08:18:15 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 08:18:15 -0400 Subject: Division and right shift in python In-Reply-To: References: <3f74e020908251648k7b391a09g78b155507b2f23c4@mail.gmail.com> Message-ID: <4A952807.5090608@ieee.org> Mark Tolonen wrote: >
> "Cevahir Demirkiran" wrote in message > news:3f74e020908251648k7b391a09g78b155507b2f23c4 at mail.gmail.com... >> Hi, >> >> I would like to do a floor division by a power of 2 in python to make it >> faster than / (modular division in 2.x). >> However, it is slower. >> What is the reason of that? >> I checked them via: >> >> def f2(x,n): >> t1 = clock() >> r = x/pow(2,n) >> t2 = clock() >> print (t2-t1) >> print r >> t2 = clock() >> r = x>>n >> t3 = clock() >> print (t3-t2) >> print r >> > > It's not slower on my system, but note the inconsistent results also: > >>>> f2(1024,5) > 3.47396033483e-06 > 32 > 2.19077375482e-06 > 32 >>>> f2(1024,5) > 4.84135603429e-06 > 32 > 3.08499440393e-06 > 32 >>>> f2(1024,5) > 4.6782844052e-06 > 32 > 3.77604384028e-06 > 32 > > Time it with timeit... > > C:\>python -m timeit -n 10000000 -s x=1024 "x>>5" > 10000000 loops, best of 3: 0.113 usec per loop > > C:\>python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" > 10000000 loops, best of 3: 0.468 usec per loop > > Right-shift is over 4x faster. > > -Mark > > > >
> There have been languages and processors in which right shift has been notably faster than divide. But with Python on a Pentium, you're both just measuring overhead. The actual divide or shift is probably less than 5% of the time measured. And that overhead will vary between versions of the interpreter. I measured with Python 2.6.2 on Windows XP, and got C:\>python -m timeit -n 10000000 -s x=1024 "x>>5" 10000000 loops, best of 3: 0.112 usec per loop C:\>python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" 10000000 loops, best of 3: 0.384 usec per loop But the real overhead is in the function call to pow(). If that had been precalculated, then the time for divide is nearly as fast as for right shift. C:\>python -m timeit -n 10000000 -s x=1024 "x/32" 10000000 loops, best of 3: 0.135 usec per loop And I suspect that some other implementation might well show this quicker than the right shift. I would use whichever code most clearly represents the problem being solved. There are undoubtedly other ways to speed up the code, without trying to micro-optimize one expression. DaveA From davea at ieee.org Wed Aug 26 08:34:26 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 08:34:26 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A952BD2.8010608@ieee.org> Ulrich Eckhardt wrote: > Jean-Michel Pichavant wrote: > >> class Color: >> def __init__(self, r, g,b): >> pass >> BLACK = Color(0,0,0) >> >> It make sens from a design point of view to put BLACK in the Color >> namespace. But I don't think it's possible with python. >> > > class Color: > ... > > setattrib(Color, "BLACK", Color(0,0,0)) > > Uli > > Or instead of setattrib, Color.BLACK = Color(0,0,0) DaveA From IDOL at il.ibm.com Wed Aug 26 08:38:50 2009 From: IDOL at il.ibm.com (Ido Levy) Date: Wed, 26 Aug 2009 15:38:50 +0300 Subject: pygtk - What is the best way to change the mouse pointer Message-ID: Hello All, I am writing a dialog which one of its widget is a gtk.ComboBoxEntry ( let's assume widget in the example below is its instance ) When the user select one of the values from the gtk.ComboBoxEntry I need to run some calculations that takes a few seconds. In order to reflect calculation time to the user I want to switch the mouse pointer to an hour glass and back to arrow what it finish the calculation. I use the following code but it doesn't seems to work in a deterministic way. From time to time it skips the last line and keep the mouse pointer as an hour glass. watch = gtk.gdk.Cursor(gtk.gdk.WATCH) widget.window.set_cursor(watch) calculation code widget.window.set_cursor(None) I would appreciate your advice on the right way to implement this. Thanks Ido -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Wed Aug 26 08:40:56 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 26 Aug 2009 13:40:56 +0100 Subject: Move dictionary from instance to class level In-Reply-To: References: Message-ID: <4A952D58.2050807@mrabarnett.plus.com> Frank Millman wrote: > On Aug 26, 10:54 am, Chris Rebert wrote: >> On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote: >> >> A >> >> class MyClass(object): >> def on_message_received(self, msg): >> self.method_dict[msg](self) >> >> def method_0(self): >> print 'in method_0' >> >> def method_1(self): >> print 'in method_1' >> method_dict >> >> method_dict = {0: method_0, 1: method_1} >> #note this comes *after* the methods in question have been defined >> > > Thanks, Chris. This is much better. > >> Is there some reason you aren't using a list instead of a dict? >> e.g. method_dict = [method_0, method_1, method_2, etc] >> >> For that matter, why are you associating methods with integers in the >> first place? >> > > I actually use constants to define my messages, like this - > > (MESSAGE_ONE > ,MESSAGE_TWO > ,MESSAGE_THREE > ) = xrange(3) > > I can then refer to the messages by their description, but internally it > uses integers. > An alternative is: >>> class MyClass(object): ... def on_message_received(self, msg): ... try: ... getattr(self, "method_%d" % msg)() ... except AttributeError: ... raise Exception("Unknown message") ... def method_0(self): ... print 'in method_0' ... def method_1(self): ... print 'in method_1' ... >>> my_obj = MyClass() >>> my_obj.on_message_received(0) in method_0 >>> my_obj.on_message_received(1) in method_1 >>> my_obj.on_message_received(2) Traceback (most recent call last): File "", line 1, in File "", line 6, in on_message_received Exception: Unknown message >>> From ben+python at benfinney.id.au Wed Aug 26 08:45:23 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 26 Aug 2009 22:45:23 +1000 Subject: ubuntu dist-packages References: Message-ID: <87tyzueobg.fsf@benfinney.id.au> Robin Becker writes: > What is the relation between dist-packages/site-packages if any? Is > this just a name change or is there some other problem being > addressed? The problem being addressed is to maintain the distinction between OS-vendor-managed files versus sysadmin-managed files. That is, the distinction between: * Python packages installed by the operating system package manager (the OS ?distribution?, as distinct from the Python-specific meaning of that term); versus * Python packages installed by the site administrator, outside the purview of the OS package manager. This distinction is important in operating systems with a functioning package manager. > For developers is it best just to create one's own private > installations from the original tarballs? Developers should be making changes as neither the system administrator nor the OS package manager, but as a regular user of the system. So installing to a user-specific package location seems best. -- \ ?Holy rising hemlines, Batman!? ?Robin | `\ | _o__) | Ben Finney From szport at gmail.com Wed Aug 26 08:51:20 2009 From: szport at gmail.com (zaur) Date: Wed, 26 Aug 2009 05:51:20 -0700 (PDT) Subject: Object's nesting scope Message-ID: Hi folk! What do you think about idea of "object's nesting scope" in python? Let's imaging this feature, for example, in this syntax: obj=: or : That's means that result object of evaluation is used as nested scope for evaluation. So is this idea useful? Zaur From martin.hellwig at dcuktec.org Wed Aug 26 09:02:04 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 26 Aug 2009 14:02:04 +0100 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: kj wrote: > First, one of the goals of OO is encapsulation, not only at the > level of instances, but also at the level of classes. Who says? Anyway, you could be right (I am not capable to judge it) and Python should change on this issue but from what I gathered, Pythons OO is inspired by the following: - Don't repeat yourself - Containing code into logical units makes it easier to understand and maintain. Note the absence of 'OO is defined as X so we are going to do X without thinking if X is actually the best way to do it' > Your comment suggests that Python does not fully support > class-level encapsulation. Probably right too, but being intrigued, why is that necessary, and given an example is that the best way to do it? > Second, my example shows that Python puts some peculiar restrictions > on recursion. Recursion! One of the central concepts in the theory > of functions! It is also one of the best ways to shoot yourself in the foot, but I ask you again, is the reason why you encountered this 'limitation' actually the best way to solve your problem? Please forgive my incompetence if this reply sounds harsh and patronizing. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From grahn+nntp at snipabacken.se Wed Aug 26 09:09:15 2009 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 26 Aug 2009 13:09:15 GMT Subject: Code formatting question: conditional expression References: <421c8c9d-efb5-4e70-9321-51736b42bc9a@g10g2000yqh.googlegroups.com> <46c5c882-c38b-4439-a3cf-62783309cc08@t13g2000yqt.googlegroups.com> <877hwrf4vu.fsf@benfinney.id.au> Message-ID: On Wed, 26 Aug 2009 16:47:33 +1000, Ben Finney wrote: > "Nicola Larosa (tekNico)" writes: > >> Nicola Larosa wrote: >> > Here's my take: >> > >> > ? ? excessblk = Block(total - P.BASE, srccol, >> > carry_button_suppress=True >> > ? ? ? ? ) if total > P.BASE else None >> >> Oops, it got shortened out: line longer than 72 chars, acceptable in >> code, but not in email. I'll try again. > > Fine in email; just munged on your behalf (and probably without your > knowledge) by your email service provider. If you don't want that > happening, it's probably best to avoid Google Mail. But this is Usenet (or at least it gets gatewayed there) and there are such limits here (either by common agreement or by RFC). Probably not Google's fault. /Jorgen -- // Jorgen Grahn O o . From deets at nospam.web.de Wed Aug 26 09:13:49 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Aug 2009 15:13:49 +0200 Subject: Object's nesting scope References: Message-ID: <7fkqodF2llnghU1@mid.uni-berlin.de> zaur wrote: > Hi folk! > > What do you think about idea of "object's nesting scope" in python? > > Let's imaging this feature, for example, in this syntax: > > obj=: > > > or > > : > > > That's means that result object of evaluation is used as > nested scope for evaluation. > > So is this idea useful? Whom am we to judge? Sure if you propose this, you have some usecases in mind - how about you present these? Diez From bbxx789_05ss at yahoo.com Wed Aug 26 09:28:28 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Wed, 26 Aug 2009 06:28:28 -0700 (PDT) Subject: Need help with Python scoping rules References: Message-ID: <8219d86d-cf0b-457f-b823-550dcf7cbf71@p36g2000prn.googlegroups.com> On Aug 25, 7:26?pm, Dave Angel wrote: > Stephen Fairchild wrote: > > You are trying to run code in a class that does not exist yet. > > > def Demo(): > > ? ? def fact(n): > > ? ? ? ? if n < 2: > > ? ? ? ? ? ? return 1 > > ? ? ? ? else: > > ? ? ? ? ? ? return n * fact(n - 1) > > ? ? return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar": > > fact(5)}) > > Demo = Demo() > > > d = Demo() > > print d._classvar ? ?# prints 120 > > print d.fact(7) ? ? ?# prints 5040 > > print Demo ? ? ? ? ? # prints > > > > In all these messages, something I haven't seen pointed out is that > fact() has no self argument. ? > An "argument" is something that is specified in the the function call. I assume you are trying to state something like, "fact() is not defined with a parameter variable named self". However, that has never been a requirement in python: class A(object): def fact(n): print n fact("hello") a = A() a.fact() --output:-- hello <__main__.A object at 0x7faf0> From jawad.karachi2010 at gmail.com Wed Aug 26 09:29:31 2009 From: jawad.karachi2010 at gmail.com (Jawad Alam) Date: Wed, 26 Aug 2009 06:29:31 -0700 (PDT) Subject: "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ Message-ID: "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ V From bbxx789_05ss at yahoo.com Wed Aug 26 09:31:48 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Wed, 26 Aug 2009 06:31:48 -0700 (PDT) Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> <84154e6e-c425-4b71-89e3-7d2877a19418@m7g2000prd.googlegroups.com> Message-ID: <811decac-b086-4ca1-af03-84c33819a710@a37g2000prf.googlegroups.com> On Aug 25, 6:34?am, Nobody wrote: > The underlying OS primitive can only handle bytes. If you read or write a > (unicode) string, Python needs to know which encoding is used. For Python > file objects created by the user (via open() etc), you can specify the > encoding; for those created by the runtime (e.g. sys.stdin), Python uses > the locale's LC_CTYPE category to select an encoding. > > Data written to or read from text streams is encoded or decoded using the > stream's encoding. Filenames are encoded and decoded using the > filesystem encoding (sys.getfilesystemencoding()). Anything else uses the > default encoding (sys.getdefaultencoding()). > > In Python 3, text streams are handled using io.TextIOWrapper: > > ? ? ? ?http://docs.python.org/3.1/library/io.html#text-i-o > > This implements a stream which can read and/or write text data on top of > one which can read and/or write binary data. The sys.std{in,out,err} > streams are instances of TextIOWrapper. You can get the underlying > binary stream from the "buffer" attribute, e.g.: > > ? ? ? ? sys.stdout.buffer.write(b'hello world\n') > > If you need to force a specific encoding (e.g. if the user has specified > an encoding via a command-line option), you can detach the existing > wrapper and create a new one, e.g.: > > ? ? ? ? sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = new_encoding) Thanks for the details. From mdekauwe at gmail.com Wed Aug 26 09:34:59 2009 From: mdekauwe at gmail.com (Mart.) Date: Wed, 26 Aug 2009 06:34:59 -0700 (PDT) Subject: Help with arrays References: Message-ID: <391bbc0f-08ea-4840-a2da-cb36b5632669@m38g2000yqh.googlegroups.com> On Aug 26, 3:02 am, Dave Angel wrote: > Stephen Fairchild wrote: > > Philip Semanchuk wrote: > > >> On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: > > >>> Hello! I'm working on an exercise wherein I have to write a Guess The > >>> Number game, but it's the computer who's guessing MY number. I can get > >>> it to work, but there's one obvious problem: the computer generates > >>> random numbers until one of them corresponds to my number, but it will > >>> often generate one number (eg. 4) numerous times, meaning it doesn't > >>> know that this number is invalid. What I mean is, it will sometimes > >>> use 37 tries to guess a number out of 1 - 9, which makes no sense, > >>> since it should only take 9 tries, at most. I was trying to find a way > >>> to make a dynamic list of all the numbers the computer generates in > >>> the loop and then make it re-generate the number if the previous > >>> number is present in the list, so it doesn't keep on generating 4 (as > >>> an example). I don't know if that makes sense... Basically, we humans > >>> know that once something is incorrect, there's no point in trying to > >>> use it as the answer next time, because we already know it's > >>> incorrect. How do I go about coding this in Python? I'm still quite > >>> new to the language so any help will be appreciated... > > >> One cheap way to do it (not necessarily efficient) is to make a list > >> of your possible guesses (e.g. range(1,10)), use random.shuffle() to > >> put them in random order and then run through the guesses one at a time. > > > import random > > import time > > > l = range(1, 10) > > > while l: > > print l.pop(random.randint(0, len(l) - 1)) > > time.sleep(2) > > While both of these will work well, I'd point out that a direct > translation of your question is to use a set. Define an empty set, and > each time you try a number unsuccessfully, add it to the set. Then just use > while x in myset: > x = newguess() > > to find the next guess. This approach isn't as efficient, but it's a > useful paradigm to understand. > > A separate question is whether the human is supposed to tell the > computer whether the guess is high or low. If so, you can eliminate > many numbers on each guess. For example, suppose the solution is 8. A > guess of 5 would say "too low." Then you'd cross off now only 5 but 1-4 > as well. > > With this change the best solution changes from a random shuffle to a > binary search. > > DaveA That's a good point if you can define whether the computer has guessed too low/high, then you could use the previous guess to set a bounds and rescale the next random guess. min + (random_number * max) although I think random.randomint does this for you! From no.email at please.post Wed Aug 26 09:57:23 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 13:57:23 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: In "Martin P. Hellwig" writes: >kj wrote: > >> First, one of the goals of OO is encapsulation, not only at the >> level of instances, but also at the level of classes. >Who says? Python itself: it already offers a limited form of class encapsulation (e.g. class variables). It would be nice if it went all the way and gave classes their own bona fide scope. (But I hasten to add: I *still* don't understand the Python scope model, and not for lack of trying. I've only succeeded in finding fragments of this model explained here and there, like pottery shards: a bit lost in a tutorial, or some comment in a newsgroup thread, etc. Maybe the full, authoritative documentation of Python's scope model got lost somewhere, and will be found by archaeologists in the 25th century...) >Anyway, you could be right (I am not capable to judge it) and Python >should change on this issue but from what I gathered, Pythons OO is >inspired by the following: >- Don't repeat yourself >- Containing code into logical units makes it easier to understand and >maintain. ...except, apparently, when that code is a recursive function, in which case one's out of luck. >> Second, my example shows that Python puts some peculiar restrictions >> on recursion. Recursion! One of the central concepts in the theory >> of functions! > >It is also one of the best ways to shoot yourself in the foot... If recursion is so evil, and Python so intent in saving us from shooting ourselves in the foot, why does it allow recursion at all? kynn From no.email at please.post Wed Aug 26 10:09:57 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 14:09:57 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> Message-ID: In <16b72319-8023-471c-ba40-8025aa6d462e at a26g2000yqn.googlegroups.com> Carl Banks writes: >> First, one of the goals of OO is encapsulation, not only at the >> level of instances, but also at the level of classes. =A0Your comment >> suggests that Python does not fully support class-level encapsulation. >I can't answer this, I don't even know what you are talking about. Yes, you do. As I said in another post, Python offers some degree of class-level encapsulation (e.g. class variables). But it is limited by the fact that these class-encapsulated elements can't always be accessed from within the class itself, which is kind of silly. >1. One of the key aspects of Python's design is that attributes must >be accessed explicitly with dot notation. Accessing class scopes from >nested functions would (seemingly) allow access to class attributes >without the dotted notation. Therefore it is not allowed. It would be trivial to define a keyword (e.g. this, or if you prefer, __this__), valid only within a class statement, and that the interpreter would recognize as "the current class", even before this class is full defined. kynn From nobody at nowhere.com Wed Aug 26 10:18:28 2009 From: nobody at nowhere.com (Nobody) Date: Wed, 26 Aug 2009 15:18:28 +0100 Subject: os.popen output different from native shell output References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Message-ID: On Tue, 25 Aug 2009 11:42:31 -0700, nickname wrote: > The reason why I want to do this is because I am going to do a little > project. I will write a python script called ls which will log the > time and username and then will show the actual ls output. I want this > to be transparent and so want to throw the ls output (via python) > exactly as it will be in native shell execution. If your script doesn't need the "ls" output for its own purposes, just run "ls" with its output to the terminal, rather than into a pipe. I.e. don't use os.popen(), but use os.spawnvp(), os.execvp() or subprocess.call(). If running "ls" is the very last thing which your script does, use os.execvp(). This causes the program to be executed in the existing process, rather than spawning a child process and waiting for it to exit. Because they replace the existing program (the Python interpreter), the various os.exec* functions don't return (unless there's an error). If you need to perform any action after the command completes (e.g. log the execution time), you need to use one of the other functions instead. From andre.cohen at gmail.com Wed Aug 26 10:19:42 2009 From: andre.cohen at gmail.com (Andre) Date: Wed, 26 Aug 2009 07:19:42 -0700 (PDT) Subject: Zlib: correct checksum but error decompressing Message-ID: <99c381ef-a146-4545-9344-7b15d60441de@y20g2000vbk.googlegroups.com> I have been trying to solve this issue for a while now. I receive data from a TCP connection which is compressed. I know the correct checksum for the data and both the client and server generate the same checksum. However, in Python when it comes to decompressing the data I get the exception: "Error -5 while decompressing data"! I would assume that if the string in python is equivalent to the correct checksum than the decompress function should also work on the same string, but that's clearly not the case. # convert data to a byte array data = array('b', raw_data) # print checksum for visual inspection print zlib.crc32(data.tostring()) # try to decompress, but fails! str = zlib.decompress(data.tostring()) Does anyone know what's going on? From davea at ieee.org Wed Aug 26 10:31:31 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 10:31:31 -0400 Subject: Need help with Python scoping rules In-Reply-To: <8219d86d-cf0b-457f-b823-550dcf7cbf71@p36g2000prn.googlegroups.com> References: <8219d86d-cf0b-457f-b823-550dcf7cbf71@p36g2000prn.googlegroups.com> Message-ID: <4A954743.4070804@ieee.org> 7stud wrote: > On Aug 25, 7:26 pm, Dave Angel wrote: > >> Stephen Fairchild wrote: >> >>> You are trying to run code in a class that does not exist yet. >>> >>> def Demo(): >>> def fact(n): >>> if n < 2: >>> return 1 >>> else: >>> return n * fact(n - 1) >>> return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar": >>> fact(5)}) >>> Demo =emo() >>> >>> d =emo() >>> print d._classvar # prints 120 >>> print d.fact(7) # prints 5040 >>> print Demo # prints >>> >> >> In all these messages, something I haven't seen pointed out is that >> fact() has no self argument. >> >> > > An "argument" is something that is specified in the the function > call. I assume you are trying to state something like, "fact() is not > defined with a parameter variable named self". However, that has > never been a requirement in python: > > > class A(object): > > def fact(n): > print n > > fact("hello") > > > a =() > a.fact() > > --output:-- > hello > <__main__.A object at 0x7faf0> > > > > You're good at nitpicking. I concede the distinction between argument and formal parameter. And self is a convention, not a requirement. But the fact is that the method as written would never have worked, when called from outside the class, since you'd have to call it with either the class name or an instance, and in either case, the method was then trying to do arithmetic on one of those. Thanks for diluting my point. The OP is chasing the wrong problem. Who cares whether a class initializer can call a method, if the method doesn't meet its original requirements, to be callable outside the class? And the arguments about how recursion is restricted are ridiculous. Nothing wrong with a method calling itself, once it's got a proper signature. You just have to make the call agree with the signature. The problem is only that the method may not be actually called until the class definition is complete. DaveA From mwilson at the-wire.com Wed Aug 26 10:38:50 2009 From: mwilson at the-wire.com (Mel) Date: Wed, 26 Aug 2009 10:38:50 -0400 Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: kj wrote: > Is there any good reason (from the point of view of Python's overall > design) for not fixing this? Python is not a compiled language, in the sense that a compiler can go back and forth over the program, filling in the details that make the program runnable. Python is an interpreted language in a sense that makes a `class` statement an executable statement, with a start time and an end time. Before the start time, the affected class doesn't exist. After the start time, the class does exist. In between, while the `class` statement is executing, it's best to make no promises so as not to constrain present and future implementations. Mel. From frank at chagford.com Wed Aug 26 10:54:32 2009 From: frank at chagford.com (Frank Millman) Date: Wed, 26 Aug 2009 16:54:32 +0200 Subject: Move dictionary from instance to class level References: Message-ID: "MRAB" wrote in message news:mailman.444.1251290454.2854.python-list at python.org... > An alternative is: > > >>> class MyClass(object): > ... def on_message_received(self, msg): > ... try: > ... getattr(self, "method_%d" % msg)() > ... except AttributeError: > ... raise Exception("Unknown message") > ... def method_0(self): > ... print 'in method_0' > ... def method_1(self): > ... print 'in method_1' > ... > >>> my_obj = MyClass() > >>> my_obj.on_message_received(0) > in method_0 > >>> my_obj.on_message_received(1) > in method_1 > >>> my_obj.on_message_received(2) > Traceback (most recent call last): > File "", line 1, in > File "", line 6, in on_message_received > Exception: Unknown message I like the idea. Unfortunately my real-world situation is a little more complex than my simple example implied. This is a more typical example - (EVT_GETLOGIN ,EVT_LOGOUT ,EVT_GETMENUOPT ,EVT_GOTFOCUS ,EVT_LOSTFOCUS ,EVT_BUTTONCLICKED ,EVT_CHECKBOX ... ) = xrange(28) method_dict = {} method_dict[EVT_GETLOGIN] = onGetLogin method_dict[EVT_LOGOUT] = onLogout method_dict[EVT_GETMENUOPT] = onGetMenuOpt method_dict[EVT_GOTFOCUS] = onGotFocus method_dict[EVT_LOSTFOCUS] = onLostFocus method_dict[EVT_BUTTONCLICKED] = onButtonClicked method_dict[EVT_CHECKBOX] = onCheckBox You can probably figure out from my method names what I am doing here - the messages are sent by a thin client (wxPython), and processed by a server.I am anticipating some "don't do that" responses, but I like the concept, and so far it is very fast and responsive, so I will pursue it for now. Thanks for the input. Frank From pavlovevidence at gmail.com Wed Aug 26 10:58:04 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Aug 2009 07:58:04 -0700 (PDT) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> Message-ID: <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> On Aug 26, 7:09?am, kj wrote: > In <16b72319-8023-471c-ba40-8025aa6d4... at a26g2000yqn.googlegroups.com> Carl Banks writes: > > >> First, one of the goals of OO is encapsulation, not only at the > >> level of instances, but also at the level of classes. =A0Your comment > >> suggests that Python does not fully support class-level encapsulation. > >I can't answer this, I don't even know what you are talking about. > > Yes, you do. ?As I said in another post, Python offers some degree > of class-level encapsulation (e.g. class variables). ?But it is > limited by the fact that these class-encapsulated elements can't > always be accessed from within the class itself, which is kind of > silly. Nope, you're wrong. Class variables are accessible wherever a class exists. The apparent silliness of this is because you are confusing classes with class statements. You know that the class isn't created until the class statement exits, don't you? Yeah, it's a little surprising that you can't access class scope from a function, but that has nothing to do with encapsulation. > >1. One of the key aspects of Python's design is that attributes must > >be accessed explicitly with dot notation. ?Accessing class scopes from > >nested functions would (seemingly) allow access to class attributes > >without the dotted notation. ?Therefore it is not allowed. > > It would be trivial to define a keyword (e.g. this, or if you > prefer, __this__), valid only within a class statement, and that > the interpreter would recognize as "the current class", even before > this class is full defined. Your solution to this "problem" is to add a keyword to Python. Laughable. (BTW, it's not trivial.) Carl Banks From no.email at please.post Wed Aug 26 10:58:10 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 14:58:10 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: In Dave Angel writes: >Stephen Fairchild wrote: >> You are trying to run code in a class that does not exist yet. >> >> def Demo(): >> def fact(n): >> if n < 2: >> return 1 >> else: >> return n * fact(n - 1) >> return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar": >> fact(5)}) >> Demo = Demo() >> >> d = Demo() >> print d._classvar # prints 120 >> print d.fact(7) # prints 5040 >> print Demo # prints >> >> >In all these messages, something I haven't seen pointed out is that >fact() has no self argument. Seems to me that makes it a staticmethod, >so it should be declared that way. No, the fact() function here represents an internal "helper" function. It is meant to be called only once to help initialize a class variable that would be inconvenient to initialize otherwise; this helper function is not meant to be called from outside the class statement. Granted, in the example I gave, the "helper" function (factorial) is a bit silly, but that was just intended as a simple and familiar example of a recursive function. The actual function that motivated this post would be considerably more difficult to explain and would have obscured the point of the post. kynn From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 10:58:15 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Aug 2009 14:58:15 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> Message-ID: <02a53d89$0$20629$c3e8da3@news.astraweb.com> On Tue, 25 Aug 2009 11:45:28 -0700, Mensanator wrote: > On Aug 25, 9:14?am, Steven D'Aprano cybersource.com.au> wrote: >> On Mon, 24 Aug 2009 18:01:38 -0700, Mensanator wrote: >> >> If you want your data file to have values entered in hex, or oct, or >> >> even unary (1=one, 11=two, 111=three, 1111=four...) you can. >> >> > Unary? I think you'll find that Standard Positional Number Systems >> > are not defined for radix 1. >> >> Of course not. But unary isn't a positional number system. It's a tally >> system, like my example above shows. Roman numerals are another tally >> system. Like Roman numerals, the disadvantages of unary are that you >> can't represent negative numbers, zero, or fractions, and anything but >> addition and subtraction is difficult. But if you want to use it, >> perhaps out of a sense of sadism towards your users, it's easy: [...] > But without insignificant leading 0's, I fail to see the relevance of > unary to this discussion. It was just an example of how you can use numeric data in any format, no matter how obscure, weird or difficult, you can use it by passing it through an appropriate converter. You don't need compiler support for user-supplied data, you just write your own function. As for insignificant leading zeroes, such a thing is meaningless in a base-1 tally system. Zero is the absence of a tally mark. > And what would you call a tally system of > radix 2? Certainly not binary. "Radix" isn't the correct term, because radix doesn't apply to tally counting systems. I'd accept "base 2", in the sense that the tally is based on two different marks. We do something similar when we mark four tally lines, then for five we mark a diagonal line through the previous four. So by analogy a base-2 tally could go: / one X two X/ three XX four XX/ five XXX six XXX/ seven But I certainly wouldn't call it "binary", for fear of confusion with radix-2 binary. Possibly binary-tally, for lack of a better term. -- Steven From patrol at invisibleroads.com Wed Aug 26 11:01:37 2009 From: patrol at invisibleroads.com (InvisibleRoads Patrol) Date: Wed, 26 Aug 2009 10:01:37 -0500 Subject: Zlib: correct checksum but error decompressing In-Reply-To: <99c381ef-a146-4545-9344-7b15d60441de@y20g2000vbk.googlegroups.com> References: <99c381ef-a146-4545-9344-7b15d60441de@y20g2000vbk.googlegroups.com> Message-ID: <1e55aa13bc60afb4835118cd3f027008@mail.webfaction.com> On Wed, 26 Aug 2009 07:19:42 -0700 (PDT), Andre wrote: > I have been trying to solve this issue for a while now. I receive data > from a TCP connection which is compressed. I know the correct checksum > for the data and both the client and server generate the same > checksum. However, in Python when it comes to decompressing the data I > get the exception: "Error -5 while decompressing data"! I would assume > that if the string in python is equivalent to the correct checksum > than the decompress function should also work on the same string, but > that's clearly not the case. > > # convert data to a byte array > data = array('b', raw_data) > # print checksum for visual inspection > print zlib.crc32(data.tostring()) > # try to decompress, but fails! > str = zlib.decompress(data.tostring()) > > Does anyone know what's going on? Hi Andre, Hmm. Can you decompress the string on the server before it was sent? Maybe the zipfile or gzip module will work. Reference: http://bytes.com/topic/python/answers/42131-zlib-decompress-cannot-gunzip-can from cStringIO import StringIO from gzip import GzipFile body = GzipFile('', 'r', 0, StringIO(raw_data)).read() You might want to try experimenting with the wbits parameter of zlib.decompress() Reference: http://mail.python.org/pipermail/python-list/2008-December/691694.html zlib.decompress(data, -15) The zlib module seems to work fine with both strings and byte arrays. import array, zlib dataAsString = zlib.compress('example string') dataAsArray = array.array('b', dataAsString) zlib.decompress(dataAsString) == zlib.decompress(dataAsArray) zlib.decompress(dataAsString) == zlib.decompress(dataAsArray.tostring()) -- http://invisibleroads.com We train ordinary people into Python software developers and connect them with jobs and projects for local businesses. From davea at ieee.org Wed Aug 26 11:13:14 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 11:13:14 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <4A95510A.2060704@ieee.org> kj wrote: > In <7figv3F2m3p0dU1 at mid.uni-berlin.de> "Diez B. Roggisch" writes: > > >> Classes are not scopes. >> > > This looks to me like a major wart, on two counts. > > First, one of the goals of OO is encapsulation, not only at the > level of instances, but also at the level of classes. Your comment > suggests that Python does not fully support class-level encapsulation. > > Second, my example shows that Python puts some peculiar restrictions > on recursion. Recursion! One of the central concepts in the theory > of functions! This is shown most clearly by the following elaboration > of my original example: > > class Demo(object): > def fact_rec(n): > if n < 2: > return 1 > else: > return n * fact_rec(n - 1) > > Why not fix the call? The correct way to call a method is with either the class name or an instance object, depending on whether it's a instance method or not. By default, a method is unbound, and its first argument is by convention called self. If you want to recurse, then add self in the appropriate places. As you have it, neither of the methods can be called outside the class: class Demo(object): def fact_rec(n): if n < 2: return 1 else: return n * fact_rec(n - 1) .... obj = Demo() print obj.fact_rec(5) gives error: Traceback (most recent call last): File "M:\Programming\Python\sources\dummy\stuff2.py", line 20, in print obj.fact_rec(5) TypeError: fact_rec() takes exactly 1 argument (2 given) To fix it, you need to either change the signature (add in 'self' argument before the n argument) or do some form of decorator to the function. If I assume you never intended this method to use 'self' (ie. it's a static method), then declare it so. And call it accordingly. class Demo(object): @staticmethod def fact(n): if n < 2: return 1 else: return n * Demo.fact(n - 1) print Demo.fact(6) On the other hand, if I assume you're just giving a simple example of what's really intended to be a normal method (called with an instance, that it uses), then you'd change it this way. class Demo2(object): def fact(self, n): if n<2: return 1 else: return n * self.fact(n-1) obj = Demo2() print obj.fact(5) Now the only real restriction, as opposed to all these red-herrings, is that the class may not be used before it's complete. That only comes to play when class attributes (non-instance "variables") are defined in terms of class methods. So if you have such attributes to define, move them outside of the class, perhaps immediately after it. class Demo(object): @staticmethod def fact(n): if n < 2: return 1 else: return n * Demo.fact(n - 1) Demo._classvar = Demo.fact(5) > def fact_iter(n): > ret = 1 > for i in range(1, n + 1): > ret *= i > return ret > > classvar1 = fact_iter(5) > classvar2 = fact_rec(5) > > This code won't compile as shown, Sure it will compile. It just won't run. You get the error after compiling the function when *calling* it from the classvar* line. But at that time the class is not defined, and not everything is ready for use. You can probably work around this by replacing the staticmethod decorator with an equivalent function call:. class Demo9(object): def fact(n): if n < 2: return 1 else: return n * Demo.fact(n - 1) _classvar = fact(5) fact = staticmethod(fact) print Demo9._classvar xx = Demo9() print xx.fact(6) print Demo9.fact(8) > but it does compile if the last > line (the call to the recursive fact_rec) is commented out. There > is no justification for discriminating against recursive functions > in this context. Recursive functions should be OK wherever functions > are OK. I can't think of any other language that allows recursion > but not anywhere. > > Is there any good reason (from the point of view of Python's overall > design) for not fixing this? > > kynn > > > From no.email at please.post Wed Aug 26 11:14:27 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 15:14:27 +0000 (UTC) Subject: Need help with Python scoping rules References: <8219d86d-cf0b-457f-b823-550dcf7cbf71@p36g2000prn.googlegroups.com> Message-ID: In Dave Angel writes: >Thanks for diluting my point. The OP is chasing the wrong problem. Who >cares whether a class initializer can call a method, if the method >doesn't meet its original requirements, to be callable outside the class? >And the arguments about how recursion is restricted are ridiculous. >Nothing wrong with a method calling itself, once it's got a proper >signature. You just have to make the call agree with the signature. >The problem is only that the method may not be actually called until the >class definition is complete. As I described at length in another reply, the function in question is not intended to be "callable outside the class". And yes, recursive functions in Python *are* restricted in ways that non-recursive functions aren't. The examples I've posted prove this point unambiguously. At this point the only defense for this restriction is to claim that it is somehow negligible. But I disagree. It's easy to come up with equally negligible, and equally indefensible, restrictions to the language would be found quite unacceptable by most users. E.g. suppose that Python's specification prohibited the use of upper case X in an identifier. That's certainly a negligible restriction: it is not harder at all to write great software without the services of the letter X than with them. Still, I think most users would find this restriction infuriatingly idiotic. Which pretty much captures what I feel about Python's prohibition of recursive functions within class statements. kynn From pavlovevidence at gmail.com Wed Aug 26 11:15:53 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Aug 2009 08:15:53 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> Message-ID: <42b95155-db9d-4865-9039-c11ba556f3b4@z31g2000yqd.googlegroups.com> On Aug 25, 1:07?pm, Evan Driscoll wrote: > On Aug 25, 2:33?pm, Evan Driscoll wrote: > > > I want to make a context manager that will temporarily change the > > value of a variable within the scope of a 'with' that uses it. This is > > inspired by a C++ RAII object I've used in a few projects. Ideally, > > what I want is something like the following: > > Okay, so I think I actually got this with some consultation with a > friend. Critiques? > > ? ? from contextlib import contextmanager > ? ? import inspect > > ? ? def get_parents_var(offset, var): > ? ? ? ? f = inspect.stack()[offset][0] > ? ? ? ? if var in f.f_locals: > ? ? ? ? ? ? ? ? return f.f_locals[var] > ? ? ? ? else: > ? ? ? ? ? ? ? ? return f.f_globals[var] > > ? ? def set_parents_var(offset, var, val): > ? ? ? ? f = inspect.stack()[offset][0] > ? ? ? ? if var in f.f_locals: > ? ? ? ? ? ? f.f_locals[var] = val > ? ? ? ? elif var in f_globals: > ? ? ? ? ? ? f.f_globals[var] = val > ? ? ? ? else: > ? ? ? ? ? ? assert False > > ? ? @contextmanager > ? ? def changed_value_tb(var_name, temp_value): > ? ? ? ? # 1 is here, 2 will be the implicit next() function, 3 is the > real caller > ? ? ? ? offset = 3 > ? ? ? ? old_value = get_parents_var(offset, var_name) > ? ? ? ? set_parents_var(offset, var_name, temp_value) > ? ? ? ? try: > ? ? ? ? ? ? yield None > ? ? ? ? finally: > ? ? ? ? ? ? set_parents_var(offset, var_name, old_value) > > ? ? x = 5 > ? ? print x ? # prints 5 > ? ? with changed_value_tb("x", 10): > ? ? ? ? print x ?# prints 10 > ? ? print x ?# prints 5 Well, it wouldn't be a "can I rebind a variable using a with- statement" thread if someone didn't post a solution that they thought worked, but didn't test it on local variables. Carl Banks From la.foma at gmail.com Wed Aug 26 11:18:23 2009 From: la.foma at gmail.com (Maggie) Date: Wed, 26 Aug 2009 08:18:23 -0700 (PDT) Subject: Raw data extraction question Message-ID: <250bf47b-6307-435a-b991-caee359c4ccf@n11g2000yqb.googlegroups.com> i have event timing stretch of code i need to alter. here is code below: -------------- # we start each run with one full silent trial # creating a "stub" with the duration of a full block # less the discarded acquisitions stub = block_dur - (distax * tr) feed = sys.stdin.readlines() sess = -1 for line in feed: if re.search(line != rest): time = (line + line (-1)) + (distax * tr) print time elif (line(-1) = rest): # block onsets are determined by # block number, block duration, # and the stub; 3dDeconvolve # takes care of making these # "global" time = (line) + (distax * tr) print time ----- my concern is that it is extracting line number and not data contained on a given line. I need it to extract data from each line (excluding lines with spaces and/or lines that contain the word "pause" or "silence"). Basically i need ONLY raw data extracted from line 1 - onward. Please let me know if you have any suggestions. Thanks! From no.email at please.post Wed Aug 26 11:27:06 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 15:27:06 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> Message-ID: In <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71 at j21g2000yqe.googlegroups.com> Carl Banks writes: >On Aug 26, 7:09=A0am, kj wrote: >> In <16b72319-8023-471c-ba40-8025aa6d4... at a26g2000yqn.googlegroups.com> Ca= >rl Banks writes: >> >> >> First, one of the goals of OO is encapsulation, not only at the >> >> level of instances, but also at the level of classes. =3DA0Your commen= >t >> >> suggests that Python does not fully support class-level encapsulation. >> >I can't answer this, I don't even know what you are talking about. >> >> Yes, you do. =A0As I said in another post, Python offers some degree >> of class-level encapsulation (e.g. class variables). =A0But it is >> limited by the fact that these class-encapsulated elements can't >> always be accessed from within the class itself, which is kind of >> silly. >Nope, you're wrong. Class variables are accessible wherever a class >exists. The apparent silliness of this is because you are confusing >classes with class statements. Repeating an earlier example (though I've switched the order of the two internal functions): class Demo(object): def fact_iter(n): ret = 1 for i in range(1, n + 1): ret *= i return ret def fact_rec(n): if n < 2: return 1 else: return n * fact_rec(n - 1) classvar1 = fact_iter(5) classvar2 = fact_rec(5) In the initialization of classvar1, fact_iter is invoked without any problem even though the class is not yet created: no need to qualify it with the name of the class. This is completely inconsistent with the requirement that fact_rec be so qualified when invoked within fact_rec. kynn From pavlovevidence at gmail.com Wed Aug 26 11:27:24 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Aug 2009 08:27:24 -0700 (PDT) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <90b1ff07-19cf-4eeb-abc5-80445da9f790@h21g2000yqa.googlegroups.com> On Aug 26, 8:13?am, Dave Angel wrote: > You can probably work around this by replacing the staticmethod > decorator with an equivalent function call:. > > class Demo9(object): > ? ? def fact(n): > ? ? ? ? if n < 2: > ? ? ? ? ? ? return 1 > ? ? ? ? else: > ? ? ? ? ? ? return n * Demo.fact(n - 1) > > ? ? _classvar = fact(5) > ? ? fact = staticmethod(fact) > > print Demo9._classvar > xx = Demo9() > print xx.fact(6) > print Demo9.fact(8) This won't work normally. It only worked for you because you made a typo. Carl Banks From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 11:32:38 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Aug 2009 15:32:38 GMT Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <02a54597$0$20629$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 10:57:32 +0000, kj wrote: > In <7figv3F2m3p0dU1 at mid.uni-berlin.de> "Diez B. Roggisch" > writes: > >>Classes are not scopes. > > This looks to me like a major wart, on two counts. > > First, one of the goals of OO is encapsulation, not only at the level of > instances, but also at the level of classes. Your comment suggests that > Python does not fully support class-level encapsulation. I don't even know what that is supposed to mean. If anything, your problem could be because Python has TOO MUCH "class-level encapsulation" compared to what you are expecting: functions inside a class don't see the class attributes you expect them too. Actually, I think your problem is that you are interpreting what you're seeing in terms of C++ or Java, and assuming that whatever they do is the One True Definition of OO. That's hardly valid -- if any language deserves the label of the One True OO Design, it might be Smalltalk, on the basis that it was the first OO language. But even that is silly -- just because something was the first, that doesn't make it the best example of something. > Second, my example shows that Python puts some peculiar restrictions on > recursion. Incorrect. Recursive calls are just like any other function call in Python: when you call *any* function from the body of a function, it must be in scope at runtime. def fact(n): print g() # g must be in scope when fact is called if n < 2: return 1 return n*fact(n-1) # fact must be in scope when fact is called Python doesn't treat recursive functions specially in any way. It is *classes*, not functions, that are special. This is explained in the docs: http://docs.python.org/reference/executionmodel.html It is also discussed in the PEP introducing nested scopes to Python: http://www.python.org/dev/peps/pep-0227/ It's even eluded to in the tutorial: http://docs.python.org/tutorial/classes.html > Recursion! One of the central concepts in the theory of > functions! This is shown most clearly by the following elaboration of > my original example: > > class Demo(object): > def fact_rec(n): > if n < 2: > return 1 > else: > return n * fact_rec(n - 1) Why are you defining a method without a self parameter? In any case, the problem has nothing to do with recursion: >>> class Broken: ... def f(): ... return g() ... def g(): ... return "gee" ... x = f() ... Traceback (most recent call last): File "", line 1, in File "", line 6, in Broken File "", line 3, in f NameError: global name 'g' is not defined > def fact_iter(n): > ret = 1 > for i in range(1, n + 1): > ret *= i > return ret > > classvar1 = fact_iter(5) > classvar2 = fact_rec(5) > > This code won't compile as shown, That's nonsense. It compiles, and then it suffers a runtime error when you *execute* it. (NameError occurs at runtime, not at compile time.) You can prove this for yourself by putting that above class definition inside a string, s: >>> x = compile(s, '', 'exec') >>> exec(x) Traceback (most recent call last): File "", line 1, in File "", line 1, in File "", line 15, in Demo File "", line 6, in fact_rec NameError: global name 'fact_rec' is not defined If you expect us to take your criticisms seriously, at least get your basic facts right. [...] > Is there any good reason (from the point of view of Python's overall > design) for not fixing this? It doesn't need to be "fixed" because it's not broken. The question is, should it be *changed* to match C++ programmers' expectations? -- Steven From no.email at please.post Wed Aug 26 11:36:35 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 15:36:35 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> Message-ID: In <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71 at j21g2000yqe.googlegroups.com> Carl Banks writes: >Yeah, it's a little surprising that you can't access class scope from >a function, but that has nothing to do with encapsulation. It does: it thwarts encapsulation. The helper function in my example is one that clearly rightfully belongs nowhere else than the class itself, i.e. encapsulated within the class. It is only this silly prohibition against recursive functions in a class statement that forces one to put it outside the class statement. kynn From davea at ieee.org Wed Aug 26 11:37:52 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 11:37:52 -0400 Subject: Help with arrays In-Reply-To: <391bbc0f-08ea-4840-a2da-cb36b5632669@m38g2000yqh.googlegroups.com> References: <391bbc0f-08ea-4840-a2da-cb36b5632669@m38g2000yqh.googlegroups.com> Message-ID: <4A9556D0.1060508@ieee.org> Mart. wrote: > On Aug 26, 3:02 am, Dave Angel wrote: > >> Stephen Fairchild wrote: >> >>> Philip Semanchuk wrote: >>> >>>> On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: >>>> >>>>> Hello! I'm working on an exercise wherein I have to write a Guess The >>>>> Number game, but it's the computer who's guessing MY number. I can get >>>>> it to work, but there's one obvious problem: the computer generates >>>>> random numbers until one of them corresponds to my number, but it will >>>>> often generate one number (eg. 4) numerous times, meaning it doesn't >>>>> know that this number is invalid. What I mean is, it will sometimes >>>>> use 37 tries to guess a number out of 1 - 9, which makes no sense, >>>>> since it should only take 9 tries, at most. I was trying to find a way >>>>> to make a dynamic list of all the numbers the computer generates in >>>>> the loop and then make it re-generate the number if the previous >>>>> number is present in the list, so it doesn't keep on generating 4 (as >>>>> an example). I don't know if that makes sense... Basically, we humans >>>>> know that once something is incorrect, there's no point in trying to >>>>> use it as the answer next time, because we already know it's >>>>> incorrect. How do I go about coding this in Python? I'm still quite >>>>> new to the language so any help will be appreciated... >>>>> >>>> One cheap way to do it (not necessarily efficient) is to make a list >>>> of your possible guesses (e.g. range(1,10)), use random.shuffle() to >>>> put them in random order and then run through the guesses one at a time. >>>> >>> import random >>> import time >>> >>> l = range(1, 10) >>> >>> while l: >>> print l.pop(random.randint(0, len(l) - 1)) >>> time.sleep(2) >>> >> While both of these will work well, I'd point out that a direct >> translation of your question is to use a set. Define an empty set, and >> each time you try a number unsuccessfully, add it to the set. Then just use >> while x in myset: >> x = newguess() >> >> to find the next guess. This approach isn't as efficient, but it's a >> useful paradigm to understand. >> >> A separate question is whether the human is supposed to tell the >> computer whether the guess is high or low. If so, you can eliminate >> many numbers on each guess. For example, suppose the solution is 8. A >> guess of 5 would say "too low." Then you'd cross off now only 5 but 1-4 >> as well. >> >> With this change the best solution changes from a random shuffle to a >> binary search. >> >> DaveA >> > > That's a good point if you can define whether the computer has guessed > too low/high, then you could use the previous guess to set a bounds > and rescale the next random guess. > > min + (random_number * max) > > although I think random.randomint does this for you! > > Actually, if you change the specs this way, you don't need random at all. Just guess halfway through the remaining range. To guess a number between 1 and 100 this way takes 7 guesses, worst case. (plus/minus 1, I haven't checked) Same problem as searching a sorted list. This code (from: http://stackoverflow.com/questions/212358/binary-search-in-python) appears to search a sorted list |def binary_search(a, x, lo=0, hi=None): if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 midval = a[mid] if midval < x: lo = mid+1 elif midval > x: hi = mid else: return mid return -1 | DaveA From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 11:40:35 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Aug 2009 15:40:35 GMT Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <02a54775$0$20629$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 13:57:23 +0000, kj wrote: > In "Martin P. Hellwig" > writes: > >>kj wrote: >> >>> First, one of the goals of OO is encapsulation, not only at the level >>> of instances, but also at the level of classes. >>Who says? > > Python itself: it already offers a limited form of class encapsulation > (e.g. class variables). An int variable is an int. A string variable is a string. A bool variable is a bool. A class variable is a class. Perhaps you mean a class attribute? > It would be nice if it went all the way and > gave classes their own bona fide scope. Classes have their own bona fide scope. It just doesn't work the way you expect it to. > (But I hasten to add: I *still* > don't understand the Python scope model, and not for lack of trying. > I've only succeeded in finding fragments of this model explained here > and there, like pottery shards: a bit lost in a tutorial, or some > comment in a newsgroup thread, etc. Maybe the full, authoritative > documentation of Python's scope model got lost somewhere, and will be > found by archaeologists in the 25th century...) It's all in the Fine Manual: http://docs.python.org/reference/executionmodel.html >>Anyway, you could be right (I am not capable to judge it) and Python >>should change on this issue but from what I gathered, Pythons OO is >>inspired by the following: >>- Don't repeat yourself >>- Containing code into logical units makes it easier to understand and >>maintain. > > ...except, apparently, when that code is a recursive function, in which > case one's out of luck. Incorrect. As I showed in my previous post, your problem has nothing to do with recursion. >>> Second, my example shows that Python puts some peculiar restrictions >>> on recursion. Recursion! One of the central concepts in the theory >>> of functions! >> >>It is also one of the best ways to shoot yourself in the foot... > > If recursion is so evil, and Python so intent in saving us from shooting > ourselves in the foot, why does it allow recursion at all? Recursion isn't evil, and Python isn't intent on preventing foot-shooting. -- Steven From no.email at please.post Wed Aug 26 11:45:54 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 15:45:54 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano writes: >On Wed, 26 Aug 2009 10:57:32 +0000, kj wrote: >> Recursion! One of the central concepts in the theory of >> functions! This is shown most clearly by the following elaboration of >> my original example: >> >> class Demo(object): >> def fact_rec(n): >> if n < 2: >> return 1 >> else: >> return n * fact_rec(n - 1) >Why are you defining a method without a self parameter? Because, as I've explained elsewhere, it is not a method: it's a "helper" function, meant to be called only once, within the class statement itself. Well, this is not strictly true, because the function is recursive, so it will also call itself a few times. But still, all these calls happen (loosely speaking) "within the class statement". In fact the only reason to use a function for such initialization work is when one needs recursion; otherwise there's no point in defining a function that will only be invoked exactly once. kynn From grahn+nntp at snipabacken.se Wed Aug 26 11:48:53 2009 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 26 Aug 2009 15:48:53 GMT Subject: ubuntu dist-packages References: <7fki3lF2kirnkU1@mid.uni-berlin.de> Message-ID: On Wed, 26 Aug 2009 12:46:13 +0200, Diez B. Roggisch wrote: > Robin Becker wrote: > >> I was surprised a couple of days ago when trying to assist a colleage with >> his python setup on a ubuntu 9.04 system. >> >> We built our c-extensions and manually copied them into place, but >> site-packages wasn't there. It seems that ubuntu now wants stuff to go >> into lib/python2.6/dist-packages. ... > I don't know much about the atrocities distributions commit to > python-installations (ripping out distutils "because it's a developer-only > thing", Well, if you are thinking about Debian Linux, it's not as much "ripping out" as "splitting into a separate package with a non-obvious name". Annoying at times, but hardly an atrocity. /Jorgen -- // Jorgen Grahn O o . From wiggly at wiggly.org Wed Aug 26 11:49:10 2009 From: wiggly at wiggly.org (Nigel Rantor) Date: Wed, 26 Aug 2009 16:49:10 +0100 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A955976.6000303@wiggly.org> kj wrote: > > Needless to say, I'm pretty beat by this point. Any help would be > appreciated. > > Thanks, Based on your statement above, and the fact that multiple people have now explained *exactly* why your attempt at recursion hasn't worked, it might be a good idea to step back, accept the advice and walk away instead of trying to convince people that the language forbids recursion and doesn't provide decent OO ecapsulation. Otherwise I'd wager you'll soon be appearing in multiple kill-files. n From davea at ieee.org Wed Aug 26 11:54:13 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 11:54:13 -0400 Subject: Move dictionary from instance to class level In-Reply-To: References: Message-ID: <4A955AA5.6000200@ieee.org> Frank Millman wrote: > "MRAB" wrote in message > news:mailman.444.1251290454.2854.python-list at python.org... > >> An alternative is: >> >> >>>>> class MyClass(object): >>>>> >> ... def on_message_received(self, msg): >> ... try: >> ... getattr(self, "method_%d" % msg)() >> ... except AttributeError: >> ... raise Exception("Unknown message") >> ... def method_0(self): >> ... print 'in method_0' >> ... def method_1(self): >> ... print 'in method_1' >> ... >> >>>>> my_obj = MyClass() >>>>> my_obj.on_message_received(0) >>>>> >> in method_0 >> >>>>> my_obj.on_message_received(1) >>>>> >> in method_1 >> >>>>> my_obj.on_message_received(2) >>>>> >> Traceback (most recent call last): >> File "", line 1, in >> File "", line 6, in on_message_received >> Exception: Unknown message >> > > I like the idea. Unfortunately my real-world situation is a little more > complex than my simple example implied. > > This is a more typical example - > > (EVT_GETLOGIN > ,EVT_LOGOUT > ,EVT_GETMENUOPT > ,EVT_GOTFOCUS > ,EVT_LOSTFOCUS > ,EVT_BUTTONCLICKED > ,EVT_CHECKBOX > ... > ) = xrange(28) > > method_dict = {} > method_dict[EVT_GETLOGIN] = onGetLogin > method_dict[EVT_LOGOUT] = onLogout > method_dict[EVT_GETMENUOPT] = onGetMenuOpt > method_dict[EVT_GOTFOCUS] = onGotFocus > method_dict[EVT_LOSTFOCUS] = onLostFocus > method_dict[EVT_BUTTONCLICKED] = onButtonClicked > method_dict[EVT_CHECKBOX] = onCheckBox > > You can probably figure out from my method names what I am doing here - the > messages are sent by a thin client (wxPython), and processed by a server.I > am anticipating some "don't do that" responses, but I like the concept, and > so far it is very fast and responsive, so I will pursue it for now. > > Thanks for the input. > > Frank > > > Any time I see multiple lists like that which have to stay in synch, I think code-smell. Why not let the EVT's be passed as strings, and avoid the whole mapping to integers and mapping back detail? And name the methods involved in a way that you can directly translate the string to the method name? Barring that, make a single "structure" which lists the event names and method names in matched pairs, and derive whatever lists and dictionaries you actually need from that one structure. And that structure should be shared between client and server code, perhaps as a text file that they both parse. Or as a stream that's passed from one to the other during startup. That way, consistency between them can be regulated (with version string in the file, for example) DaveA From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 11:55:08 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Aug 2009 15:55:08 GMT Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> Message-ID: <02a54ade$0$20629$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 14:09:57 +0000, kj wrote: >>1. One of the key aspects of Python's design is that attributes must be >>accessed explicitly with dot notation. Accessing class scopes from >>nested functions would (seemingly) allow access to class attributes >>without the dotted notation. Therefore it is not allowed. > > It would be trivial to define a keyword (e.g. this, or if you prefer, > __this__), valid only within a class statement, and that the interpreter > would recognize as "the current class", even before this class is full > defined. Python doesn't treat the addition of new keywords, and the corresponding breakage of code which used that word as a normal name, as "trivial" -- the Python dev team takes their responsibilities to not casually break people's code seriously. That pretty much rules out "this", although it would allow "__this__". However, what's your use-case? class Demo(object): def f(n): return n+1 x = f(10) is a poorly written class, because the user will expect to do this: instance = Demo() assert instance.c == 11 # suceeds instance.f(10) == 11 # fails Since the function f doesn't refer to a Demo instance, or the Demo class, why do you put it inside the Demo class? It doesn't belong there, it belongs in the global (module) scope. Move it out, and your problem goes away. The only use-case I can think of for __this__ is the following: class Example(object): @staticmethod def rec(n): if n < 2: return "x" return "x" + __this__.rec(n/2) Example.rec(15) but again, why include rec() in the class if it doesn't actually have anything to do with the class or the instance? Or why make it a staticmethod? Just make it a class method: class Example(object): @classmethod def rec(cls, n): if n < 2: return "x" return "x" + cls.rec(n/2) -- Steven From marcandre at abppers.com Wed Aug 26 12:10:34 2009 From: marcandre at abppers.com (=?iso-8859-1?Q?Marc-Andr=E9_Ouellette?=) Date: Wed, 26 Aug 2009 12:10:34 -0400 Subject: WEB PROGRAMMER ANALYST (with Python knowledge) for Laval, Quebec needed. Message-ID: <7116C98A7E6E4F8785817A4A92A545D7@abppers.local> To whom it may concern, ABP Personnel Consultants is a recruiting firm established in Montreal. We presently have a need for a web programmer with knowledge of Python. Below is the job description : Our client offers much more than simple Internet advertising and website design. They are a full-service automotive industry consulting company that develops integrated sales and CRM solutions, focussing on showing clients how to make the most of online communications. Their digital marketing services are geared towards measurable results attained with the help of rigorous online methodology. Du to the expansion of the company nationally, they are seeking talented individuals to fill full-time software development positions at their offices in Laval. The candidate will be responsible for analyzing client requests and/or specifications. Determine the functionality demanded by the system and resources/requirements, using the most appropriate development technology to produce the required application, and/or modification. Additionally, the candidate will work with Quality Assurance department to validate newly developed applications, and/or modifications. Software Developers will also be required to troubleshoot applications when problems arise. The working environment is flexible, easy going and encourages teamwork. EXPERIENCE (not required to know all): Candidates should have commercial programming experience (Python, SQL and Javascript). Knowledge in one or more of the following technologies is desirable: Languages: Python, SQL, JavaScript, C/C++, Delphi Servers: Apache, Sybase, PostgreSQL Markups: HTML, XML, CSS, XUL Frameworks/Toolkits: Django, Twisted Matrix, wxWidgets Protocols: TCP/UDP IP, XMLRPC/SOAP, AJAX, FTP, HTTP, POP/SMTP OSes: Linux, Windows, MacOSX Other: Client/server architectures, version control systems Mercurial SALARY: Based on level of experience, from 50000$ to 75000$ + benefits. If your interested to know more, please contact me. Regards, Marc-Andr? Ouellette marcandre at abppers.com Marc-Andr? Ouellette Consultant en recrutement Recruitment consultant T. 514-939-3399 poste 105 F. 514-939-0241 Courriel : marcandre at abppers.com Consultez nos offres d'emplois au www.abppers.com Visit us online at www.abppers.com Ce message, ainsi que tout fichier qui y est joint, est destin? exclusivement aux personnes ? qui il est adress?. Il peut contenir des renseignements ou des informations de nature confidentielle qui ne doivent ?tre divulgu?s en vertu des lois applicables. Si vous n'?tes pas le destinataire de ce message ou un mandataire autoris? de celui-ci, par la pr?sente vous ?tes avis? que toute impression, diffusion, distribution ou reproduction de ce message et de tout fichier qui y est joint est strictement interdite. L'int?grit? de ce message n'?tant pas assur?e sur Internet, ABP Consultants en Personnel inc. ne peut ?tre tenue responsable de son contenu s'il a ?t? alt?r?, d?form? ou falsifi?. Si ce message vous a ?t? transmis par erreur, veuillez en aviser sans d?lai l'exp?diteur et l'effacer ainsi que tout fichier joint sans en conserver de copie. This message, and any attachments, is intended only for the use of the addressee or his authorized representative. It may contain information that is privileged, confidential and exempt from disclosure under applicable law. If the reader of this message is not the intended recipient,or his authorized representative, you are hereby notified that any dissemination, distribution or copying of this message and any attachments isstrictly prohibited. The integrity of this message cannot be guaranteed on the Internet, ABP Personnel Consultants inc. shall not be liable for its content if altered, changed or falsified. If you have received this message in error, please contact right away with the sender and delete this message andany attachments from your system. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.jpg Type: image/jpeg Size: 10281 bytes Desc: not available URL: From pavlovevidence at gmail.com Wed Aug 26 12:13:40 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Aug 2009 09:13:40 -0700 (PDT) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> Message-ID: On Aug 26, 8:36?am, kj wrote: > In <1bf83a7e-f9eb-46ff-84fe-cf42d9608... at j21g2000yqe.googlegroups.com> Carl Banks writes: > > >Yeah, it's a little surprising that you can't access class scope from > >a function, but that has nothing to do with encapsulation. > > It does: it thwarts encapsulation. ?The helper function in my > example is one that clearly rightfully belongs nowhere else than > the class itself, i.e. encapsulated within the class. It is only > this silly prohibition against recursive functions in a class > statement that forces one to put it outside the class statement. Oh well, I guess that sucks for you. Carl Banks From robin at reportlab.com Wed Aug 26 12:20:35 2009 From: robin at reportlab.com (Robin Becker) Date: Wed, 26 Aug 2009 17:20:35 +0100 Subject: ubuntu dist-packages In-Reply-To: References: <7fki3lF2kirnkU1@mid.uni-berlin.de> Message-ID: <4A9560D3.4000009@chamonix.reportlab.co.uk> Jorgen Grahn wrote: > On Wed, 26 Aug 2009 12:46:13 +0200, Diez B. Roggisch ........ > Well, if you are thinking about Debian Linux, it's not as much > "ripping out" as "splitting into a separate package with a non-obvious > name". Annoying at times, but hardly an atrocity. so where is the official place for user installed stuff on ubuntu/debian ie will there be dist-packages and site-packages. -- Robin Becker From robin at reportlab.com Wed Aug 26 12:20:35 2009 From: robin at reportlab.com (Robin Becker) Date: Wed, 26 Aug 2009 17:20:35 +0100 Subject: ubuntu dist-packages In-Reply-To: References: <7fki3lF2kirnkU1@mid.uni-berlin.de> Message-ID: <4A9560D3.4000009@chamonix.reportlab.co.uk> Jorgen Grahn wrote: > On Wed, 26 Aug 2009 12:46:13 +0200, Diez B. Roggisch ........ > Well, if you are thinking about Debian Linux, it's not as much > "ripping out" as "splitting into a separate package with a non-obvious > name". Annoying at times, but hardly an atrocity. so where is the official place for user installed stuff on ubuntu/debian ie will there be dist-packages and site-packages. -- Robin Becker From tjreedy at udel.edu Wed Aug 26 12:21:45 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Aug 2009 12:21:45 -0400 Subject: Python Processor In-Reply-To: <7670c8130908260328l6982ef4etad802a755b85a44f@mail.gmail.com> References: <7670c8130908260328l6982ef4etad802a755b85a44f@mail.gmail.com> Message-ID: manish wrote: > Hi, > > I am also wondering about how to implement a soft core reconfigurable > processor in a FPGA > which would directly execute the compiled python bytecode. > > I am trying to understand the bytecode format but apart from > http://docs.python.org/library/dis.html > there is hardly any documentation on the python bytecodes. Contrary to the ancient and, I believe, obsolete text in the documentation, there is no 'python bytecode'. Dis is based on CPython bytecode. Jython uses Java bytecode. IronPython uses, I believe, Microsoft clr bytecode. Object code compilers do not use bytecode. > Before going through the one of the existing VM implementations, i want > to know if there is there any informaition > available which elaborates on the structure of the bytecodes. Like > details regarding co_names, co_cellvars, > co_freevars, the concept of frames, global, local, objects, functions > etc with respect to the bytecode. These are mostly version-specific Cpython implementation details. tjr From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 12:42:24 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Aug 2009 16:42:24 GMT Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> Message-ID: <02a555f2$0$20629$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 15:36:35 +0000, kj wrote: > In <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71 at j21g2000yqe.googlegroups.com> > Carl Banks writes: > >>Yeah, it's a little surprising that you can't access class scope from a >>function, but that has nothing to do with encapsulation. > > It does: it thwarts encapsulation. The helper function in my example is > one that clearly rightfully belongs nowhere else than the class itself, > i.e. encapsulated within the class. There's nothing "clearly" about it. This helper function doesn't reference the class, or any instance of the class. Why should it be encapsulated in the class? It's not *part* of the class, it shouldn't be *inside* the class. Look at it this way: classes are made from building blocks. Just because a building block ends up in a class, doesn't mean the function that makes the building block has to be inside the class too. It's an accident of Python's execution model that a single function call *sometimes* works as you expect inside the class statement: class Demo: def f(): return 2 def g(): return f()+1 x = f() # works y = g() # fails As you can see, the problem is not because of recursion, but because the class scope is not inserted into the function scope. As I said earlier, your problem isn't too little class encapsulation, but too much: the class scope doesn't leak into the function scope. Python could, of course, behave the way you want, but it would lead to some odd interactions: class Weird(object): x = 1 def __init__(self): self.y = 2 def test(self): print self.x # refers to attribute x with value 1 print x # refers to attribute x with value 1 print self.y # refers to attribute y with value 2 print y # refers to global y In existing Python, both x and y will refer to globals, because it's considered more important for all attribute access to be consistently explicit than to insert the class scope into the function scope. This isn't a design flaw, or a bug, it's a feature. Yes, it makes it hard for you to solve your problem the way you want to solve it, but it doesn't stop you from solving your problem. The module is encapsulation enough. -- Steven From cjw at ncf.ca Wed Aug 26 12:49:18 2009 From: cjw at ncf.ca (Colin J. Williams) Date: Wed, 26 Aug 2009 12:49:18 -0400 Subject: quantiles of a student distribution In-Reply-To: References: Message-ID: Pierre wrote: > Hello... > > Do you know how I can calculate the quantiles of a student > distribution in pyhton ? > > Thanks You might look at: http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/python/special.html Colin W. From szport at gmail.com Wed Aug 26 12:49:48 2009 From: szport at gmail.com (zaur) Date: Wed, 26 Aug 2009 09:49:48 -0700 (PDT) Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> Message-ID: <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> On 26 ???, 17:13, "Diez B. Roggisch" wrote: > Whom am we to judge? Sure if you propose this, you have some usecases in > mind - how about you present these Ok. Here is a use case: object initialization. For example, person = Person(): name = "john" age = 30 address = Address(): street = "Green Street" no = 12 vs. person = Person() person.name = "john" person.age = 30 address = person.address = Address() address.street = "Green Street" address.no = 12 In this example any assignment is an equivalence of setting attribute's address of the parent object. From phily05 at gmail.com Wed Aug 26 12:54:55 2009 From: phily05 at gmail.com (Phil) Date: Wed, 26 Aug 2009 09:54:55 -0700 (PDT) Subject: Python on the Web References: <4a94ef42$0$27774$426a74cc@news.free.fr> Message-ID: Thanks to everybody. I believe I am understanding things better. I have looked at the links that have been provided, although I have seen most of them in the past month or so that I've been looking into this stuff. I do agree with most of the things Armin stated in that NIH post. I agree with everybody in this thread so far. If I wanted to write an application, I would use an existing framework and wait for it to be ported to 3.x. However, I do not have the need to write a web application at this time, and creating blogs or other applications I do not need for fun is getting old. My reasoning for working on my own instead of following the 'NIH' concept or contributing to an existing framework is because I have experimented with many existing frameworks and I have figured out what I like/dislike, and have envisioned my own design that I feel would work potentially better for others, or at least newcomers. Things like this are fun for me, and I do not mind the challenge. I don't want to pollute the web with (sigh) 'another framework', but it would be fun for me to write it and get some feedback. I would love for people like you, Armin, and others who take a look at the various frameworks that pop up seemingly every day, to look at my (hypothetical) framework and just rip it apart with (constructive) criticism. That is just the way I do things, whether the community agrees with it or not. The reason I was asking about Python 3 on the web was just because I like some of the changes that have been made, and would like to use it for my framework. That is when I realized that I was absolutely clueless about the details of how Python, or any language, works on the web. Graham, regarding number 3 in your list of ways to host WSGI: I haven't really looked into mod_wsgi at all, but basically it sounds like the web server would be running this embedded module. That module would then serve the function of both FCGI and the 'WSGI Server' in my diagram? That actually sounds really neat. Unfortunately I missed this because I've been hooked on lighttpd, as the minimalist I am. Here are the things I am still confused with: 1) Why do I not want to consider running Python on the web with FCGI, without WSGI? You said 'no' straight up, no questions asked. I would imagine that there is a good reason of course, as you've been in this field for a long time. I just feel more comfortable understanding why. >From my understanding, the only real purpose of WSGI is to remain independent of FCGI/SCGI/CGI/AJP (whatever that is) and the web server it is run on. However, 99.9% of the discussion I see with Python on the web is around FCGI. So for example, lets say everybody used FCGI. All that would be left to deal with is web server independence. Now this is what I don't get, I thought that FCGI itself was supposed to be the protocol that deals with web server independence. Maybe I just need to re-read entire WSGI specification to understand, along with all the details of FCGI. There are just so many details regarding web servers, FCGI, and WSGI that it is hard to absorb it all and see how it works together. That is why I tried to create the diagram, but it doesn't provide enough details. And those are the details I am missing. I've been trying to find a simple diagram or explaination of the process a request takes to make a response, from HTTP all the way up to the application, to the the user. 2) In the development stack, the 'WSGI Server' seems to take on the role of the web server (dealing with HTTP specification), skips FCGI, and deals with the WSGI specification. Then, the 'WSGI Server' in the production stack (eg. Flup, CherryPy, etc) only deals with FCGI and WSGI specification, because the HTTP is already taken care of by the web server? From rami.chowdhury at gmail.com Wed Aug 26 13:11:15 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Wed, 26 Aug 2009 10:11:15 -0700 Subject: Object's nesting scope In-Reply-To: <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> Message-ID: > person = Person(): > name = "john" > age = 30 > address = Address(): > street = "Green Street" > no = 12 > Can you clarify what you mean? Would that define a Person class, and an Address class? If you are expecting those classes to be already defined, please bear in mind that if you want, you can do this: > > > class Person(object): def __init__(self, name='Nemo', age=0, address=None): self.name = name self.age = age self.address = address > > > class Address(object): def __init__(self, street=None, no=None): self.street = street self.no = no > > > otherperson = Person( name = 'Bob', age = 26, address = Address( street = 'Blue Street', no = 1 ) ) On Wed, 26 Aug 2009 09:49:48 -0700, zaur wrote: > On 26 ???, 17:13, "Diez B. Roggisch" wrote: >> Whom am we to judge? Sure if you propose this, you have some usecases in >> mind - how about you present these > > Ok. Here is a use case: object initialization. > > For example, > > person = Person(): > name = "john" > age = 30 > address = Address(): > street = "Green Street" > no = 12 > > vs. > > person = Person() > person.name = "john" > person.age = 30 > address = person.address = Address() > address.street = "Green Street" > address.no = 12 > > In this example any assignment is an equivalence of setting > attribute's address of the parent object. -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From eckhardt at satorlaser.com Wed Aug 26 13:17:22 2009 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 26 Aug 2009 19:17:22 +0200 Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> Message-ID: <2a7gm6-9h.ln1@satorlaser.homedns.org> kj wrote: > class Demo(object): > def fact_iter(n): > ret = 1 > for i in range(1, n + 1): > ret *= i > return ret > > def fact_rec(n): > if n < 2: > return 1 > else: > return n * fact_rec(n - 1) > > classvar1 = fact_iter(5) > classvar2 = fact_rec(5) > > > In the initialization of classvar1, fact_iter is invoked without > any problem even though the class is not yet created: no need to > qualify it with the name of the class. This is completely inconsistent > with the requirement that fact_rec be so qualified when invoked > within fact_rec. Let me take a shot at explaining this, maybe it helps that I'm mostly a C++ guy.... Firstly, if Python sees a name, it looks up that name first in the local scope and then in the global scope. This is very simple (especially compared to C++ when adding ADL there...), but it is something most people can live with. So, even inside a class function (static or member), you have to qualify a function call like 'ClassName.function_name', because neither is 'function_name' a local nor is it a global. Secondly, and that is due to the very dynamic nature of Python's types, the class doesn't exist until its definition is finished. Therefore, any attempt (directly or indirectly) to access a class member will usually fail before that time. The exception is that inside the class definition you can access the members directly, because they are in the same scope (access to locals). Note that the scope already seems to exist but that it is not yet available under any name! Looking at your example, you can not write 'classvar1 = Demo.fact_iter(42)', because the lookup of 'Demo' will fail. Now, what actually causes problems is that 'fact_rec' is not universally accessible until class 'Demo' is fully defined, but you need this in order to fully define it. Here comes a drawback of the dynamic nature of Python, that the declaration phase (compiling) is not separate from the execution. I fully agree that this case is rather vexing to my (and obviously your) biased brain. I wouldn't call this a bug before fully understanding why e.g. you can not access a class before its definition is finished. I think someone mentioned one or two PEPs, which are the design documents that explain Python including the rationale, I'd use that as a starting point. Suggestion: someone mentioned that you should make the function a normal function. You can mark it as private using an underscore as prefix. If you want to make it foolproof, you could even delete ("del fact_rec") the function after use. Other alternatives would be to put it into a separate baseclass, use a local function as implementation or to add the class attributes after defining the class. Neither of these provide the 'perfect' encapsulation of things in a class that you might be used to from e.g. Java, but they have proven to be very useful nonetheless. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From gert.cuykens at gmail.com Wed Aug 26 13:28:23 2009 From: gert.cuykens at gmail.com (gert) Date: Wed, 26 Aug 2009 10:28:23 -0700 (PDT) Subject: How does the file.seek() work ? References: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> <1532ff09-f892-44c8-8206-10b3c2d16050@13g2000prl.googlegroups.com> Message-ID: <40093737-2ff1-4527-a2ea-a016ee526463@k30g2000yqf.googlegroups.com> On Aug 26, 12:46?am, Graham Dumpleton wrote: > On Aug 25, 5:37?am, Tim Chase wrote: > > > > I want the file pointer set to 100 and overwrite everything from there > > [snip] > > > def application(environ, response): > > > ? ? query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') > > > ? ? range=environ.get('HTTP_RANGE','bytes=0-').replace > > > ('bytes=','').split(',') > > > ? ? offset=[] > > > ? ? for r in range: offset.append(r.split('-')) > > > ? ? with open(query,'w+') as f: > > > ? ? ? ? ?f.seek(int(offset[0][0])) > > > ? ? ? ? ?while True: > > > ? ? ? ? ? ? ?chunk=environ['wsgi.input'].read(8192).decode('latin1') > > > ? ? ? ? ? ? ?if not chunk: break > > > ? ? ? ? ? ? ?f.write(chunk) > > > ? ? f=open(query) > > > ? ? l=str(os.fstat(f.fileno()).st_size) > > > ? ? response('200 OK', [('Content-Type', 'text/plain'), ('Content- > > > Length', str(len(l)))]) > > > ? ? return [l] > > > A couple items of note: > > > - you don't open the file in binary mode -- seek is more reliable > > in binary mode :) > > If my memory is right, if file is opened in binary mode, also wouldn't > need to be decoding the WSGI input stream as latin-1 to get a string. > Instead can just deal with bytes and write bytes to file. > > Graham > > > - if you want to lop off the rest of the file, use f.truncate() > > > An example: > > > # create the initial file > > ?>>> f = file('zzz.zzz', 'wb+') > > ?>>> f.write('abcdefghijklmnop') > > ?>>> f.close() > > > ?>>> f = file('zzz.zzz', 'ab+') > > ?>>> f.read() # show the existing content > > 'abcdefghijklmnop' > > ?>>> f.seek(5) # seek to the desired offset > > ?>>> f.truncate() # throw away everything after here > > ?>>> f.write('zyx') # write the new data at pos=5 > > ?>>> f.close() > > > # demonstrate that it worked > > ?>>> f = file('zzz.zzz', 'rb') > > ?>>> f.read() > > 'abcdezyx' > > ?>>> f.close() > > > > also why must I open the file a second time to know how big it is ? > > > Likely the output has been buffered. ?You can try using > > > ? ?f.flush() # write all the data to the disk first > > ? ?size = os.fstat(f.fileno()).st_size > > > which seems to do the trick for me. > > -tkc > Works thanks curl -C 10 -T upload2.wsgi http://192.168.2.17/appwsgi/wsgi/upload2.wsgi --header "Transfer-Encoding: chunked" -v import os def application(environ, response): #query=environ.get['QUERY_STRING'] #print (query, file=environ['wsgi.errors']) query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') range=environ.get('HTTP_CONTENT_RANGE','bytes 0-').replace('bytes ','').split('/')[0].split(',') offset=[] for r in range: offset.append(r.split('-')) with open(query,'rb+') as f: f.seek(int(offset[0][0])) if environ['REQUEST_METHOD']=='PUT': f.truncate() while True: chunk=environ['wsgi.input'].read(8192) if not chunk: break f.write(chunk) f.flush() l=str(os.fstat(f.fileno()).st_size) response('200 OK', [('Content-Type', 'text/plain'), ('Content- Length', str(len(l)))]) return [l] From tjreedy at udel.edu Wed Aug 26 13:52:36 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Aug 2009 13:52:36 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: kj wrote: > In <7figv3F2m3p0dU1 at mid.uni-berlin.de> "Diez B. Roggisch" writes: > >> Classes are not scopes. Classes are objects. In particular, they are (by default) instances of class 'type'. Unless 'scopes' were instances of some other metaclass, the statement has to be true. I understand 'scope' as referring to a section of code, as opposed to a runtime object. Class statements introduce a new local namespace used to define the class. Whether one considers that as introducing a new 'scope' depends, I suppose, on one's exact definition of scope. > This looks to me like a major wart, on two counts. It is a 'wart' that a Python object is not a 'scope', whatever that is to you? I have trouble comprehending that claim. > First, one of the goals of OO is encapsulation, not only at the > level of instances, but also at the level of classes. Your comment > suggests that Python does not fully support class-level encapsulation. I really do not see how your claim follows from the comment. The irony of your 'two counts' is that the example of 'count 2' fails precisely because of the encapsulation that you claim does not exist as 'count 1'. > Second, my example shows that Python puts some peculiar restrictions > on recursion. I claim it does not. Name-based recursion inherently requires that a function be able to access itself by name at the time it is called. This can be a bit tricky, especially in a language with dynamic rather than static name binding and resolution, as it requires that code within the function be able to access a scope outside itself in which the function name is defined. In other words, it requires that function code *not* be completely encapsulated. It also require that the appropriate name be used when there is one. Neither of these is a 'peculiar restriction' imposed by Python. > class Demo(object): > def fact_rec(n): > if n < 2: > return 1 > else: > return n * fact_rec(n - 1) This function is just a function. It is not an instance method. It is not even a class method. It does not belong here and should not be here. If you insist on putting it where it does not belong, then you have to call it by a name that works. If you only call it after the class statement has finished, then 'Demo.fact_rec' works, as I believe someone else pointed out. If you want to call the function during class creation, before (in this case) Demo exists, then binding it to a local name works. With 3.1 class Demo: def f1(n): if n < 2: return 1 else: return n * Demo.f1(n - 1) def f2(n,f): if n < 2: return 1 else: return n * f(n - 1, f) cvar = f2(5, f2) print(Demo.f1(5), Demo.cvar, Demo.f2(5,Demo.f2)) # prints >>> 120 120 120 > Recursive functions should be OK wherever functions are OK. Iteration can and has been viewed as within-frame recursion. When iterative rather than recursive syntax is used, the naming issue is avoided. > Is there any good reason (from the point of view of Python's overall > design) for not fixing this? After reading the above, what, if anything, do you think still needs to be fixed? Before 2.2, Python functions were more encapsulated than they are today in that they could only access local and global namespaces but not outer function namespaces. It would be possible to further de-encapsulate them by giving them direct access to lexically surrounding class namespaces, but this would increase the problem of name clashes without solving any real problems in proper Python code. It could also break the intentional design principle that function code should mean the same thing whether placed within or without a class statement. This principle allows functions to be added to existing classes as attributes and work as methods that same as if they had been defined with the class. Terry Jan Reedy From mensanator at aol.com Wed Aug 26 13:58:12 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 26 Aug 2009 10:58:12 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> Message-ID: <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> On Aug 26, 9:58?am, Steven D'Aprano wrote: > On Tue, 25 Aug 2009 11:45:28 -0700, Mensanator wrote: > > On Aug 25, 9:14?am, Steven D'Aprano > cybersource.com.au> wrote: > >> On Mon, 24 Aug 2009 18:01:38 -0700, Mensanator wrote: > >> >> If you want your data file to have values entered in hex, or oct, or > >> >> even unary (1=one, 11=two, 111=three, 1111=four...) you can. > > >> > Unary? I think you'll find that Standard Positional Number Systems > >> > are not defined for radix 1. > > >> Of course not. But unary isn't a positional number system. It's a tally > >> system, like my example above shows. Roman numerals are another tally > >> system. Like Roman numerals, the disadvantages of unary are that you > >> can't represent negative numbers, zero, or fractions, and anything but > >> addition and subtraction is difficult. But if you want to use it, > >> perhaps out of a sense of sadism towards your users, it's easy: > [...] > > But without insignificant leading 0's, I fail to see the relevance of > > unary to this discussion. > > It was just an example of how you can use numeric data in any format, no > matter how obscure, weird or difficult, you can use it by passing it > through an appropriate converter. You don't need compiler support for > user-supplied data, you just write your own function. Ok, no problem with that. > > As for insignificant leading zeroes, such a thing is meaningless in a > base-1 tally system. Zero is the absence of a tally mark. > > > And what would you call a tally system of > > radix 2? Certainly not binary. > > "Radix" isn't the correct term, because radix doesn't apply to tally > counting systems. I'd accept "base 2", in the sense that the tally is > based on two different marks. I thought the two were equivalent, but maybe I'm wrong. Anyway, that's a minor quibble. > We do something similar when we mark four > tally lines, then for five we mark a diagonal line through the previous > four. So by analogy a base-2 tally could go: > > / ? ? one > X ? ? two > X/ ? ?three > XX ? ?four > XX/ ? five > XXX ? six > XXX/ ?seven Sure, as long as you're consistent, there's no problem. > > But I certainly wouldn't call it "binary", for fear of confusion with > radix-2 binary. That's my point. Since the common usage of "binary" is for Standard Positional Number System of Radix 2, it follows that "unary" is the common usage for Standard Positional Number System of Radix 1. That's VERY confusing since such a system is undefined. Remember, common usage does not necessarily properly define things. Saying simply "unary" sounds like you're extending common usage beyond its proper boundaries. > Possibly binary-tally, for lack of a better term. Then possibly unary-tally would be better than unary. Tally systems being much less common require a less common terminology to avoid confusion. > > -- > Steven From begin.middle.end at gmail.com Wed Aug 26 14:10:27 2009 From: begin.middle.end at gmail.com (Mahi Haile) Date: Wed, 26 Aug 2009 14:10:27 -0400 Subject: SimpleXMLRPCServer timeout issue Message-ID: <83d424980908261110m1f70b326ua4b7668c8bd173a4@mail.gmail.com> Hi all, I have an XML-RPC server running that is using SimpleXMLRPCServer, and I am trying to send a relatively large file on a poor connection [simulated low bandwidth, high latency]. The file is simply the return value of a function call available on the server. However, sometime in to the transfer, I get a timeout, seemingly regardless of what I do. The server is initiated as follows: s = SimpleXMLRPCServer((HOST, PORT), requestHandler = RequestHandler) s.timeout = 100000 #I tried setting this to None, and also a higher number And the exception I get is: Traceback (most recent call last): File "/python2.5/SocketServer.py", line 464, in process_request_thread self.finish_request(request, client_address) File "/python2.5/SocketServer.py", line 254, in finish_request self.RequestHandlerClass(request, client_address, self) File "/python2.5/SocketServer.py", line 522, in __init__ self.handle() File "/python2.5/BaseHTTPServer.py", line 316, in handle self.handle_one_request() File "python2.5/BaseHTTPServer.py", line 310, in handle_one_request method() File "/python2.5/SimpleXMLRPCServer.py", line 481, in do_POST self.wfile.write(response) File "/python2.5/socket.py", line 262, in write self.flush() File "/python2.5/socket.py", line 249, in flush self._sock.sendall(buffer) timeout: timed out Googling resulted in similar questions asked in the CherryPy forums, and the general suggestions seem to be to use a streaming transfer, using yield rather than return. Do you know how I go about solving when using the SimpleXMLRPCServer? For what it is worth, I am running the server on Mac OS X. Thank you, -------------- next part -------------- An HTML attachment was scrubbed... URL: From diesch at spamfence.net Wed Aug 26 14:37:30 2009 From: diesch at spamfence.net (Florian Diesch) Date: Wed, 26 Aug 2009 20:37:30 +0200 Subject: ubuntu dist-packages References: Message-ID: Robin Becker writes: > I was surprised a couple of days ago when trying to assist a colleage > with his python setup on a ubuntu 9.04 system. > > We built our c-extensions and manually copied them into place, but > site-packages wasn't there. It seems that ubuntu now wants stuff to go > into lib/python2.6/dist-packages. > > What is the relation between dist-packages/site-packages if any? Is > this just a name change or is there some other problem being > addressed? > > For developers is it best just to create one's own private > installations from the original tarballs? >From /usr/lib/python2.6/site.py: ,---- | For Debian and derivatives, this sys.path is augmented with directories | for packages distributed within the distribution. Local addons go | into /usr/local/lib/python/dist-packages, Debian addons | install into /usr/{lib,share}/python/dist-packages. | /usr/lib/python/site-packages is not used. `---- Florian -- From szport at gmail.com Wed Aug 26 14:57:54 2009 From: szport at gmail.com (zaur) Date: Wed, 26 Aug 2009 11:57:54 -0700 (PDT) Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> Message-ID: On 26 ???, 21:11, "Rami Chowdhury" wrote: > > person = Person(): > > ? name = "john" > > ? age = 30 > > ? address = Address(): > > ? ? ?street = "Green Street" > > ? ? ?no = 12 > > Can you clarify what you mean? Would that define a Person class, and an ? > Address class? I suppose that someone already define classes Person ans Address. For example, in this stupid way in a foreign module: class Person(object): pass class Address(object): pass and the following statements person = Person(): name = "john" age = 30 address = Address(): street = "Green Street" no = 12 are constructing an instance as follows: person = Person() person.name = "john" person.age = 30 address = person.address = Address() address.street = "Green Street" address.no = 12 > If you are expecting those classes to be already defined, please bear in ? > mind that if you want, you can do this: > > > > > class Person(object): > > ? ? ? ? def __init__(self, name='Nemo', age=0, address=None): > ? ? ? ? ? ? ? ? self.name = name > ? ? ? ? ? ? ? ? self.age = age > ? ? ? ? ? ? ? ? self.address = address > > > > > class Address(object): > > ? ? ? ? def __init__(self, street=None, no=None): > ? ? ? ? ? ? ? ? self.street = street > ? ? ? ? ? ? ? ? self.no = no > > > > > otherperson = Person( > > ? ? ? ? ? ? ? ? ? ? ?name = 'Bob', > ? ? ? ? ? ? ? ? ? ? ?age = 26, > ? ? ? ? ? ? ? ? ? ? ?address = Address( > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?street = 'Blue Street', > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?no = 1 > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?) > ? ? ? ? ? ? ? ? ? ? ?) > Yes, that's right. I aware about this way of instance initialization. From ethan at stoneleaf.us Wed Aug 26 15:00:02 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 26 Aug 2009 12:00:02 -0700 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A958632.9020301@stoneleaf.us> kj wrote: > > > I have many years of programming experience, and a few languages, > under my belt, but still Python scoping rules remain mysterious to > me. (In fact, Python's scoping behavior is the main reason I gave > up several earlier attempts to learn Python.) > > Here's a toy example illustrating what I mean. It's a simplification > of a real-life coding situation, in which I need to initialize a > "private" class variable by using a recursive helper function. > > class Demo(object): > def fact(n): > if n < 2: > return 1 > else: > return n * fact(n - 1) > > _classvar = fact(5) As has been pretty thoroughly discussed, the issue here is not recursion, but name lookup. Going back through the archives I found Arnaud's post with this decorator: def bindfunc(f): def boundf(*args, **kwargs): return f(boundf, *args, **kwargs) return boundf If you use it on your fact function like so... class Demo(object): @bindfunc def fact(recurse, n) # recurse can be any name you like if n < 2: return 1 else: return n * recurse(n-1) _classvar = fact(5) del fact # no longer needed, and won't work # once class is created This should do as you want. As a side note, if you're going to bother asking questions on this list, you really should try to understand the answers. I won't gripe at you too much, though, 'cause I learned a lot from the many responses given due to your refusal to do so. ;-) ~Ethan~ From evaned at gmail.com Wed Aug 26 15:12:59 2009 From: evaned at gmail.com (Evan Driscoll) Date: Wed, 26 Aug 2009 12:12:59 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> <42b95155-db9d-4865-9039-c11ba556f3b4@z31g2000yqd.googlegroups.com> Message-ID: On Aug 26, 10:15?am, Carl Banks wrote: > Well, it wouldn't be a "can I rebind a variable using a with- > statement" thread if someone didn't post a solution that they thought > worked, but didn't test it on local variables. I'm not going to deny it was pretty stupid... though in my defense, I'm new at more that trivial Python coding and don't have the Python scoping rules and such ingrained in my mind yet. :-) Evan From no.email at please.post Wed Aug 26 15:20:24 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 19:20:24 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano writes: >http://docs.python.org/reference/executionmodel.html >It is also discussed in the PEP introducing nested scopes to Python: >http://www.python.org/dev/peps/pep-0227/ >It's even eluded to in the tutorial: >http://docs.python.org/tutorial/classes.html Thanks! kynn From nagle at animats.com Wed Aug 26 15:30:05 2009 From: nagle at animats.com (John Nagle) Date: Wed, 26 Aug 2009 12:30:05 -0700 Subject: Python Processor In-Reply-To: References: <7670c8130908260328l6982ef4etad802a755b85a44f@mail.gmail.com> Message-ID: <4a958c1b$0$1600$742ec2ed@news.sonic.net> Terry Reedy wrote: > manish wrote: >> Hi, >> >> I am also wondering about how to implement a soft core reconfigurable >> processor in a FPGA >> which would directly execute the compiled python bytecode. It probably wouldn't help much. CPython's performance problems come from excessive dictionary lookups, not from instruction decode. John Nagle From robert.kern at gmail.com Wed Aug 26 15:30:08 2009 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 26 Aug 2009 14:30:08 -0500 Subject: quantiles of a student distribution In-Reply-To: References: Message-ID: On 2009-08-26 11:49 AM, Colin J. Williams wrote: > Pierre wrote: >> Hello... >> >> Do you know how I can calculate the quantiles of a student >> distribution in pyhton ? >> >> Thanks > You might look at: > http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/python/special.html [Please pardon the piggybacking. I have not gotten the original, yet.] Using scipy: In [1]: from scipy import stats In [2]: import numpy as np In [3]: x = np.linspace(-1.0, 1.0, 21) In [4]: x Out[4]: array([-1. , -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]) In [5]: ndof = 10 In [6]: stats.t.cdf(x, ndof) Out[6]: array([ 0.17044657, 0.19463963, 0.22115021, 0.24994379, 0.28092759, 0.3139468 , 0.3487837 , 0.3851603 , 0.4227446 , 0.46116036, 0.5 , 0.53883964, 0.5772554 , 0.6148397 , 0.6512163 , 0.6860532 , 0.71907241, 0.75005621, 0.77884979, 0.80536037, 0.82955343]) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sridharr at activestate.com Wed Aug 26 15:35:00 2009 From: sridharr at activestate.com (Sridhar Ratnakumar) Date: Wed, 26 Aug 2009 12:35:00 -0700 Subject: ANN: ActivePython 3.1.1.2 is now available Message-ID: I'm happy to announce that ActivePython 3.1.1.2 is now available for download from: http://www.activestate.com/activepython/python3/ This is a patch release that updates ActivePython to core Python 3.1.1 We recommend that you try 2.6 version first. See the release notes for full details: http://docs.activestate.com/activepython/3.1/relnotes.html What is ActivePython? --------------------- ActivePython is ActiveState's binary distribution of Python. Builds for Windows, Mac OS X, Linux, HP-UX and AIX are made freely available. ActivePython includes the Python core and the many core extensions: zlib and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3) database libraries, OpenSSL bindings for HTTPS support, the Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on supported platforms) for low-level library access, and others. The Windows distribution ships with PyWin32 -- a suite of Windows tools developed by Mark Hammond, including bindings to the Win32 API and Windows COM. See this page for full details: http://docs.activestate.com/activepython/3.1/whatsincluded.html As well, ActivePython ships with a wealth of documentation for both new and experienced Python programmers. In addition to the core Python docs, ActivePython includes the "What's New in Python" series, "Dive into Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs). An online version of the docs can be found here: http://docs.activestate.com/activepython/ We would welcome any and all feedback to: ActivePython-feedback at activestate.com Please file bugs against ActivePython at: http://bugs.activestate.com/query.cgi?set_product=ActivePython On what platforms does ActivePython run? ---------------------------------------- ActivePython includes installers for the following platforms: - Windows/x86 - Windows/x64 (aka "AMD64") - Mac OS X - Linux/x86 - Linux/x86_64 (aka "AMD64") - Solaris/SPARC - Solaris/x86 - HP-UX/PA-RISC - AIX/PowerPC - AIX/PowerPC64 Extra Bits ---------- ActivePython releases also include the following: - ActivePythonXY.chm: An MS compiled help collection of the full ActivePython documentation set. Linux users of applications such as xCHM might find this useful. This package is installed by default on Windows. Extra bits are available from: http://downloads.activestate.com/ActivePython/etc/ Thanks, and enjoy! The Python Team -- Sridhar Ratnakumar sridharr at activestate.com From davea at ieee.org Wed Aug 26 15:50:46 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 15:50:46 -0400 Subject: Need help with Python scoping rules In-Reply-To: <90b1ff07-19cf-4eeb-abc5-80445da9f790@h21g2000yqa.googlegroups.com> References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <90b1ff07-19cf-4eeb-abc5-80445da9f790@h21g2000yqa.googlegroups.com> Message-ID: <4A959216.3080507@ieee.org> Carl Banks wrote: > On Aug 26, 8:13 am, Dave Angel wrote: > >> You can probably work around this by replacing the staticmethod >> decorator with an equivalent function call:. >> >> class Demo9(object): >> def fact(n): >> if n < 2: >> return 1 >> else: >> return n * Demo.fact(n - 1) >> >> _classvar =act(5) >> fact =taticmethod(fact) >> >> print Demo9._classvar >> xx =emo9() >> print xx.fact(6) >> print Demo9.fact(8) >> > > This won't work normally. It only worked for you because you made a > typo. > > > Carl Banks > > Sorry about the typo. I was trying out several different versions of the class in the same module, and forgot to include to change Demo to Demo9 in the recursive call. I didn't like that approach anyway, as it smacked of taking advantage of some implementation accident. The other approaches are more straightforward. DaveA From python at mrabarnett.plus.com Wed Aug 26 15:56:54 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 26 Aug 2009 20:56:54 +0100 Subject: Object's nesting scope In-Reply-To: References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> Message-ID: <4A959386.6060809@mrabarnett.plus.com> zaur wrote: > On 26 ???, 21:11, "Rami Chowdhury" wrote: >>> person = Person(): >>> name = "john" >>> age = 30 >>> address = Address(): >>> street = "Green Street" >>> no = 12 >> Can you clarify what you mean? Would that define a Person class, and an >> Address class? > I suppose that someone already define classes Person ans Address. > For example, in this stupid way in a foreign module: > > class Person(object): > pass > > class Address(object): > pass > > and the following statements > > person = Person(): > name = "john" > age = 30 > address = Address(): > street = "Green Street" > no = 12 > > are constructing an instance as follows: > > person = Person() > person.name = "john" > person.age = 30 > address = person.address = Address() > address.street = "Green Street" > address.no = 12 > [snip] Create factory functions: def new_address(**kwargs): address = Address() address.__dict__.update(kwargs) return address def new_person(**kwargs): person = Person() person.__dict__.update(kwargs) return person person = new_person(name="john", age=30, address=new_address(street="Green Street", no=12)) From python at mrabarnett.plus.com Wed Aug 26 16:03:45 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 26 Aug 2009 21:03:45 +0100 Subject: pygtk - What is the best way to change the mouse pointer In-Reply-To: References: Message-ID: <4A959521.8020505@mrabarnett.plus.com> Ido Levy wrote: > Hello All, > > I am writing a dialog which one of its widget is a gtk.ComboBoxEntry ( > let's assume widget in the example below is its instance ) > When the user select one of the values from the gtk.ComboBoxEntry I need > to run some calculations that takes a few seconds. > In order to reflect calculation time to the user I want to switch the > mouse pointer to an hour glass and back to arrow what it finish the > calculation. > > I use the following code but it doesn't seems to work in a deterministic > way. From time to time it skips the last line and keep the mouse pointer > as an hour glass. > > watch = gtk.gdk.Cursor(gtk.gdk.WATCH) > widget.window.set_cursor(watch) > > calculation code > > widget.window.set_cursor(None) > > I would appreciate your advice on the right way to implement this. > Could the calculation code be raising an exception? Try adding some logging to see whether the last lien is actually being called. You could also use a try...finally... block to ensure that the last line is called: watch = gtk.gdk.Cursor(gtk.gdk.WATCH) widget.window.set_cursor(watch) try: calculation code finally: widget.window.set_cursor(None) From find.mig at paa.google Wed Aug 26 16:06:01 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Wed, 26 Aug 2009 22:06:01 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a93e575$0$298$14726298@news.sunsite.dk> Message-ID: <4a9595ca$0$300$14726298@news.sunsite.dk> Hendrik van Rooyen wrote: >> would that be usable? > Probably >> If so, how? > > This is a guess, for your device, but I suspect > something along these lines: > > t = Ao_timer() > > cb = t.after(100,thing_that_does_the_work(with_its_arguments)) > > Lots of assumptions here - the 100 should give you a tenth of a second... > Don't know what the arguments look like, and if you need to pass an instance > (like self) - that would depend on where you are calling it from. > > Play and see :-) > > You should also be able to cancel the callback like this: > > t.cancel(cb) > > If you do it before the time out > > - Hendrik > I don't really get it... I can see that I should put a t.after(...) around the function that does the work, when calling it. That delays each call for the given period. I just tried it out, the console keeps saying ------------------------------------------------------------------------- Traceback (most recent call last): File "c:\resource\python25\python25.zip\sensorfw.py", line 499, in data_cb File "c:\resource\python25\python25.zip\sensorfw.py", line 160, in custom_cb File "e:\python\r3s_contextdata.py", line 79, in acc_filter self.acc_callback() File "e:\python\r3s_contextdata.py", line 85, in acc_callback self.doCallback() File "e:\python\r3s_contextdata.py", line 47, in doCallback self.at.after(0.05,self.data_callback) RuntimeError: Timer pending - cancel first ------------------------------------------------------------------------- It seems like i should cancel the current counting timer, when a new call comes in - but how to determine when to cancel etc? I'm kind of new to all this async python stuff. From find.mig at paa.google Wed Aug 26 16:07:25 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Wed, 26 Aug 2009 22:07:25 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a92b290$0$305$14726298@news.sunsite.dk> <4a93e575$0$298$14726298@news.sunsite.dk> Message-ID: <4a95961d$0$300$14726298@news.sunsite.dk> Dennis Lee Bieber wrote: > On Tue, 25 Aug 2009 15:21:16 +0200, Esben von Buchwald > declaimed the following in > gmane.comp.python.general: > >> This is how the accelerometer is accessed >> http://pys60.garage.maemo.org/doc/s60/node59.html >> >> I found this called "after"... >> http://pys60.garage.maemo.org/doc/s60/node12.html >> >> would that be usable? > > Based on the documentation... I'd suggest... > > def doCallback(self): > self.accelerometer.stop_listening() > self.data_callback() > self.accelerometer.start_listening() > > with appropriate changes to whatever reference you use for the > accelerometer would solve the problem... IE, when the callback is > triggered, you STOP the accelerometer action, compute results, and then > restart the accelerometer.. I just tried that - it made the application lock up, leaving the sensors unusable until next reboot of the phone. I don't think these start/stop calls are supposed to be called as often as it does the callback... From no.email at please.post Wed Aug 26 16:11:02 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 20:11:02 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: In Ethan Furman writes: >Going back through the archives I found Arnaud's post with this decorator: >def bindfunc(f): > def boundf(*args, **kwargs): > return f(boundf, *args, **kwargs) > return boundf >If you use it on your fact function like so... >class Demo(object): > @bindfunc > def fact(recurse, n) # recurse can be any name you like > if n < 2: > return 1 > else: > return n * recurse(n-1) > _classvar = fact(5) > del fact # no longer needed, and won't work > # once class is created >This should do as you want. Thanks, this is instructive. >As a side note, if you're going to bother asking questions on this list, >you really should try to understand the answers. I think I understand the answers well enough. What I *really* don't understand is why this particular "feature" of Python (i.e. that functions defined within a class statement are forbidden from "seeing" other identifiers defined within the class statement) is generally considered to be perfectly OK. IMO it's a bizarre, inexplicable blindspot (which, among other things, gives rise to a certain worry about what other similar craziness lurks under Python's image of rationality). I have never seen even a half-hearted justification, from a language design point of view, for why this particular "feature" is worth having. Maybe some day the BDFL will deign to give one. kynn From no.email at please.post Wed Aug 26 16:16:54 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 20:16:54 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: In <7figv3F2m3p0dU1 at mid.uni-berlin.de> "Diez B. Roggisch" writes: >But if you insist on the above methodology, you can do this: >class Demo(object): > def fact(n): > def inner(n): > if n < 2: > return 1 > else: > return n * inner(n - 1) > return inner(n) > _classvar = fact(5) >This makes inner a *local* variable, which is found. Thanks for this. I think this is the most straightforward workaround. kynn From no.email at please.post Wed Aug 26 16:35:28 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 20:35:28 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> <2a7gm6-9h.ln1@satorlaser.homedns.org> Message-ID: In <2a7gm6-9h.ln1 at satorlaser.homedns.org> Ulrich Eckhardt writes: >kj wrote: >> class Demo(object): >> def fact_iter(n): >> ret = 1 >> for i in range(1, n + 1): >> ret *= i >> return ret >> >> def fact_rec(n): >> if n < 2: >> return 1 >> else: >> return n * fact_rec(n - 1) >> >> classvar1 = fact_iter(5) >> classvar2 = fact_rec(5) >> >> >> In the initialization of classvar1, fact_iter is invoked without >> any problem even though the class is not yet created: no need to >> qualify it with the name of the class. This is completely inconsistent >> with the requirement that fact_rec be so qualified when invoked >> within fact_rec. >Let me take a shot at explaining this, maybe it helps that I'm mostly a C++ >guy.... Thanks for your reply. >I fully agree that this case is rather vexing to my (and obviously your) >biased brain. I wouldn't call this a bug before fully understanding why >e.g. you can not access a class before its definition is finished. I understand this, what I don't understand is why do it this way. I've been trying to understand this particular design point for *literally* years. >I think >someone mentioned one or two PEPs, which are the design documents that >explain Python including the rationale, I'd use that as a starting point. I'm reading PEP 227 now, suggested by Steven D'Aprano. In it I find statements like the following alert: (Note: If a region is contained within a class definition, the name bindings that occur in the class block are not visible to enclosed functions.) I've seen this before, but never an explanation for why having this restriction. It's just one of life's mysteries. (Incidentally, the fact that the author of PEP 227 felt it necessary to add that parenthetical remark suggests that the expectation it warns against is not so crazy after all.) But I'm still not done with PEP 227. Maybe I'll see the light by the time I'm done. kynn From grahn+nntp at snipabacken.se Wed Aug 26 16:38:15 2009 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 26 Aug 2009 20:38:15 GMT Subject: ubuntu dist-packages References: <7fki3lF2kirnkU1@mid.uni-berlin.de> Message-ID: On Wed, 26 Aug 2009 17:20:35 +0100, Robin Becker wrote: > Jorgen Grahn wrote: >> On Wed, 26 Aug 2009 12:46:13 +0200, Diez B. Roggisch > ........ >> Well, if you are thinking about Debian Linux, it's not as much >> "ripping out" as "splitting into a separate package with a non-obvious >> name". Annoying at times, but hardly an atrocity. > so where is the official place for user installed stuff on > ubuntu/debian ie will > there be dist-packages and site-packages. I don't know, but I know Debian has a group of people working out how to package Python and software written in Python. Those guys have a home page somewhere at debian.org -- there should be information there, and/or under /usr/share/doc/python* on your system. Another answer is "let distutils do its job and do not worry", but sometimes you need to know the rules and the reasons ... /Jorgen -- // Jorgen Grahn O o . From dullrich at sprynet.com Wed Aug 26 16:47:23 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Wed, 26 Aug 2009 15:47:23 -0500 Subject: Python for professsional Windows GUI apps? References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: On Mon, 24 Aug 2009 22:22:20 -0700, sturlamolden wrote: > On 25 Aug, 05:56, Peter Decker wrote: > >> I use the Dabo Class Designer to visually design my forms. So what's >> you're point? ?:) > > Nothing, except lobbying for wxFormBuilder for anyone who still doesn't > know of it. :) That's great. But do you know of anything I can use as a visual form design tool in wxPython? From zuo at chopin.edu.pl Wed Aug 26 16:48:01 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 26 Aug 2009 22:48:01 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: 26-08-2009 o 09:03:27 Ulrich Eckhardt wrote: > Jean-Michel Pichavant wrote: >> class Color: >> def __init__(self, r, g,b): >> pass >> BLACK = Color(0,0,0) >> >> It make sens from a design point of view to put BLACK in the Color >> namespace. But I don't think it's possible with python. > > class Color: > ... > > setattrib(Color, "BLACK", Color(0,0,0)) Or simpler: class Color: ... Color.BLACK = Color(...) Then (Color.BLACK is Color.BLACK.BLACK.BLACK.BLACK) == True :-) *j PS. Obviously, that's nothing special (there is no problem with creating such "recursive" references in Python). -- Jan Kaliszewski (zuo) From cripto at ecn.org Wed Aug 26 16:56:16 2009 From: cripto at ecn.org (Anonymous) Date: Wed, 26 Aug 2009 22:56:16 +0200 (CEST) Subject: print() and unicode strings (python 3.1) Message-ID: <20090826205616.2B9231A7B03@www.ecn.org> Have you considered including an encoding line at the top of your file, as described in PEP 0263: http://www.python.org/dev/peps/pep-0263/ I just ran into a similar error, but it went away when I included # coding: utf-8 as the first line in my file. From kyrie at uh.cu Wed Aug 26 17:00:11 2009 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 26 Aug 2009 17:00:11 -0400 Subject: Confessions of a Python fanboy In-Reply-To: References: <200907301757.48761.kyrie@uh.cu> Message-ID: <200908261700.12060.kyrie@uh.cu> On Friday 31 July 2009 04:08:33 am Masklinn wrote: > On 30 Jul 2009, at 23:57 , Luis Zarrabeitia wrote: > > I'd like to ask, what "container.each" is, exactly? It looks like a > > function > > call (as I've learned a few posts ago), but, what are its arguments? > > How the > > looping "works"? Does it receive a "code" object that it has to > > execute? > > Is .each some kind of magic keyword? (This has little to do with > > python or > > the current thread, so feel free to reply off-list if you want to...) > > #each is simply a method that takes a function (called blocks in > ruby). One could call it a higher-order method I guess. > > It's an implementation of the concept of internal iteration: instead > of collections yielding iterator objects, and programmers using those > through specially-built iteration constructs (e.g. `for?in`), > collections control iteration over themselves (the iteration is > performed "inside" the collection, thus the "internal" part) and the > programmer provides the operations to perform at each iterative step > through (usually) a function. Interesting. I know what internal iteration is, and I suspected it was along these lines when I saw the syntax and that .each was a function and not a keyword. But if it is internal iteration and the .each method is receiving an anonymous function, I wonder what is the scope of the variables in that function. In pseudo-python terms (using your example), x = 5 some_list.each((def (item): do_something(item, x) x = do_something_else(item) )) (or something like that). In python, the inner function would be invalid (the 'x' is local). For that construct to be equivalent to a for loop, the anonymous function shouldn't create a new scope. Is that what is happening? (If it is, this would be a big difference between anonymous and non-anonymous functions). Anyway, this is OT. Thank you for your reply. (ah, sorry for taking so long... I was out of town) -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From paul at boddie.org.uk Wed Aug 26 17:00:26 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 26 Aug 2009 14:00:26 -0700 (PDT) Subject: ubuntu dist-packages References: <7fki3lF2kirnkU1@mid.uni-berlin.de> Message-ID: <71f5986e-6aae-46b0-8325-d67051c60a30@a13g2000yqc.googlegroups.com> On 26 Aug, 17:48, Jorgen Grahn wrote: > > Well, if you are thinking about Debian Linux, it's not as much > "ripping out" as "splitting into a separate package with a non-obvious > name". Annoying at times, but hardly an atrocity. Indeed. Having seen two packages today which insisted on setuptools, neither really needing it, and with one actively trying to download stuff from the Internet (fifteen seconds warning - how generous!) when running setup.py, it seems to me that it isn't the distribution packagers who need to be re-thinking how they install Python software. Generally, distributions have to manage huge amounts of software and uphold reasonable policies without creating unnecessary maintenance. Sadly, until very recently (and I'm still not entirely sure if there's really been an attitude change) the Pythonic packaging brigade has refused to even consider the needs of one of the biggest groups of consumers of the upstream code. Consequently, distributions will always devise different ways of storing installed Python software, documentation and resources, mostly because the Pythonic tools have been deficient, particularly in the management of the latter categories. Paul From zuo at chopin.edu.pl Wed Aug 26 17:02:42 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 26 Aug 2009 23:02:42 +0200 Subject: all possible matchings of elements of two lists In-Reply-To: References: Message-ID: 26-08-2009 o 12:05:41 Sandy wrote: > Hi all, > I basically want all possible matchings of elements from two lists, > Ex: [1,2] [a,b,c] > > Required: > [ [(1,a),(2,b)] > [(1,b),(2,c)] > [(1,c),(2,b)] > [(1,b),(2,a)] > [(1,c),(2,a)] > [(1,a),(2,c)] > ] > > My thought is to get all possible permutations of two lists given and > select any combination and use zip to get the tuples. Repeat this for > all possible combinations. > > Any other ideas? See: module itertools -- there are (OOTB) some combinatoric generators that may be useful for you. *j -- Jan Kaliszewski (zuo) From martin at v.loewis.de Wed Aug 26 17:10:41 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 26 Aug 2009 23:10:41 +0200 Subject: break unichr instead of fix ord? In-Reply-To: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: <4A95A4D1.9060008@v.loewis.de> > In Python 2.5 on Windows I could do [*1]: > > >>> a = unichr (65600) > >>> a[0],a[1] > (u'\ud800', u'\udc40') I can't reproduce that. My copy of Python on Windows gives Traceback (most recent call last): File "", line 1, in unichr(65600) ValueError: unichr() arg not in range(0x10000) (narrow Python build) This is Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Regards, Martin From martin.hellwig at dcuktec.org Wed Aug 26 17:19:05 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 26 Aug 2009 22:19:05 +0100 Subject: Python Processor In-Reply-To: <4a958c1b$0$1600$742ec2ed@news.sonic.net> References: <7670c8130908260328l6982ef4etad802a755b85a44f@mail.gmail.com> <4a958c1b$0$1600$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > CPython's performance problems > come from excessive dictionary lookups, not from instruction decode. > > John Nagle Could you please suggest some background information/links to this? I tried to Google for it but unsurprisingly any combination with 'cpython' and 'performance' results (to me that is) in a haystack of rants. I did find http://www.python.org/dev/peps/pep-0339/ but I would ideally like to read something more in depth but still in reasonable easy language. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From ethan at stoneleaf.us Wed Aug 26 17:23:47 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 26 Aug 2009 14:23:47 -0700 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A95A7E3.7040900@stoneleaf.us> kj wrote: > I think I understand the answers well enough. What I *really* > don't understand is why this particular "feature" of Python (i.e. > that functions defined within a class statement are forbidden from > "seeing" other identifiers defined within the class statement) is > generally considered to be perfectly OK. IMO it's a bizarre, > inexplicable blindspot (which, among other things, gives rise to > a certain worry about what other similar craziness lurks under > Python's image of rationality). I have never seen even a half-hearted > justification, from a language design point of view, for why this > particular "feature" is worth having. Maybe some day the BDFL will > deign to give one. > > kynn You keep using that word. I do not think it means what you think it means. :) Keep studying. Listen. Learn how it *is*. Understanding may come later. ~Ethan~ From piet at cs.uu.nl Wed Aug 26 17:24:32 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 26 Aug 2009 23:24:32 +0200 Subject: Web Services examples using "raw" xml? References: <7fgbv7F2l9u4oU1@mid.uni-berlin.de> Message-ID: >>>>> "Diez B. Roggisch" (DBR) wrote: >DBR> John Gordon schrieb: >>> I'm developing a program that will use web services, which I have never >>> used before. >>> >>> There are several tutorials out there that advise you to get the WSDL >>> and then call a method (such as wsdl2py) that inspects the wsdl and >>> automagically generates the python classes and methods you need for >>> interacting with that web service. >>> >>> I've tried this, and have run into a number of roadblocks that have left >>> me frustrated. >DBR> Welcome to the wonderful world of SOAP. If you didn't know - the S stands >DBR> for simple [1]. Stood. Like the O was supposed to stand for Object. Now out of shame they tend to talk more about `Service Oriented Architecture Protocol'. Whichever is a greater abomination you may choose (that almost sounds like Yoda-speak). -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From ignace.danneels at gmail.com Wed Aug 26 17:40:24 2009 From: ignace.danneels at gmail.com (BlueFlash) Date: Wed, 26 Aug 2009 14:40:24 -0700 (PDT) Subject: How do I insert a menu item in an existing menu. Message-ID: <73dd8da1-7b1e-4065-9c2f-2cee554093e2@j21g2000yqe.googlegroups.com> Idea: Use of a RecentFileList, update element 0 with new file opened. Appending a menu is easy menu.Append(-1, "Menu Name") when I try to insert a new menu item menu.Insert(-1, position, "Menu Name") does not work. full code: def addnew(self, position, path): path = path.strip() try: self.filelist.index(path) # index() throws ValueError if path does not exist. except: # ValueError, path is not in list, so add it: if position >= len(self.filelist): self.filelist.append(path) item = self.menu.Append(-1, path) #this does return a menu item self.window.Bind(wx.EVT_MENU, self.event, item) else: self.filelist.insert(position, path) item = self.menu.InsertItem(-1, position, path) # does Not return a menu item. throws some exception. print item #self.window.Bind(wx.EVT_MENU, self.event, item) How do I remove a menu item from a menu? The RecentUsedList is eg: 4 element long. When opening a new file, this should be added at the top, and the 4th element must be dropped. From zuo at chopin.edu.pl Wed Aug 26 17:54:16 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 26 Aug 2009 23:54:16 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: 26-08-2009 o 17:45:54 kj wrote: > In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano > writes: > >> On Wed, 26 Aug 2009 10:57:32 +0000, kj wrote: > >>> Recursion! One of the central concepts in the theory of >>> functions! This is shown most clearly by the following elaboration of >>> my original example: >>> >>> class Demo(object): >>> def fact_rec(n): >>> if n < 2: >>> return 1 >>> else: >>> return n * fact_rec(n - 1) > >> Why are you defining a method without a self parameter? > > Because, as I've explained elsewhere, it is not a method: it's a > "helper" function, meant to be called only once, within the class > statement itself. > > Well, this is not strictly true, because the function is recursive, > so it will also call itself a few times. But still, all these > calls happen (loosely speaking) "within the class statement". > > In fact the only reason to use a function for such initialization > work is when one needs recursion; otherwise there's no point in > defining a function that will only be invoked exactly once. 1. I don't understand then... Why do you desire to both define and run it *within* that class statement as if it was this class's method? 2. Could you please show me how it could be done in C++ or Java? (Or you want to say that that languages also are not fully valuable OO languages?) 3. Python makes function bodies "agnostic" about the context of their definition -- generally any non-global information must be passed explicitly to their interior. *It has nothing to do with recursion.* If you really must both define and use such a function within the class definition, pass function object to itself explicitly, and everybody will be happy: class Demo(object): def fact(fact, n): if n < 2: return 1 else: return n * fact(fact, n - 1) fact(fact, 3) *j -- Jan Kaliszewski (zuo) From http Wed Aug 26 17:57:25 2009 From: http (Paul Rubin) Date: 26 Aug 2009 14:57:25 -0700 Subject: Zlib: correct checksum but error decompressing References: <99c381ef-a146-4545-9344-7b15d60441de@y20g2000vbk.googlegroups.com> Message-ID: <7xk50qz1a2.fsf@ruckus.brouhaha.com> Andre writes: > I have been trying to solve this issue for a while now. I receive data > from a TCP connection which is compressed. Are you sure it is compressed with zlib? If yes, does it include the standard zlib header? Some applications save a few bytes by stripping the header. See the zlib doc page for how to deal with that, there is a flag that causes the header check to be skipped on decompression if you pass a negative number. That's the first thing I would try. From piet at cs.uu.nl Wed Aug 26 17:59:57 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 26 Aug 2009 23:59:57 +0200 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> Message-ID: >>>>> Mensanator (M) wrote: >M> That's my point. Since the common usage of "binary" is for >M> Standard Positional Number System of Radix 2, it follows >M> that "unary" is the common usage for Standard Positional >M> Number System of Radix 1. That's VERY confusing since such >M> a system is undefined. Remember, common usage does not >M> necessarily properly define things. Saying simply "unary" >M> sounds like you're extending common usage beyond its proper >M> boundaries. But the customary meaning of `unary' is the tally system, as a radix system wouldn't make sense. I don't know when this term came into use but I have known it for a long time. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From python at mrabarnett.plus.com Wed Aug 26 18:12:58 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 26 Aug 2009 23:12:58 +0100 Subject: How do I insert a menu item in an existing menu. In-Reply-To: <73dd8da1-7b1e-4065-9c2f-2cee554093e2@j21g2000yqe.googlegroups.com> References: <73dd8da1-7b1e-4065-9c2f-2cee554093e2@j21g2000yqe.googlegroups.com> Message-ID: <4A95B36A.9070109@mrabarnett.plus.com> BlueFlash wrote: > Idea: Use of a RecentFileList, update element 0 with new file opened. > > Appending a menu is easy > menu.Append(-1, "Menu Name") > > when I try to insert a new menu item > menu.Insert(-1, position, "Menu Name") > > does not work. > The following comments are the result of a brief search of the web, so I'm not sure whether they're correct, but they might be worth a try. > full code: > def addnew(self, position, path): > path = path.strip() > try: > self.filelist.index(path) # index() throws ValueError > if path does not exist. > except: > # ValueError, path is not in list, so add it: > if position >= len(self.filelist): > self.filelist.append(path) > item = self.menu.Append(-1, path) #this does return a > menu item > self.window.Bind(wx.EVT_MENU, self.event, item) > else: > self.filelist.insert(position, path) > item = self.menu.InsertItem(-1, position, path) # does > Not return a menu item. throws some exception. I think it should be: item = self.menu.InsertItem(position, -1, path) > print item > #self.window.Bind(wx.EVT_MENU, self.event, item) > > > How do I remove a menu item from a menu? The RecentUsedList is eg: 4 > element long. When opening a new file, this should be added at the > top, and the 4th element must be dropped. I think you need the 'Remove' method. From ubershmekel at gmail.com Wed Aug 26 18:16:20 2009 From: ubershmekel at gmail.com (RunThePun) Date: Wed, 26 Aug 2009 15:16:20 -0700 (PDT) Subject: Overriding iadd for dictionary like objects Message-ID: I'd like to build a database wrapper using DictMixin and allow items to be appended by my own code. The problem is += is always understood as setitem and getitem plainly. d = MyDict() d['a'] = 1 # this is the problem code that's I'd like to override. It's always setitem('a', getitem('a') + 3) d['a'] += 3 # i wanted to do something like my own 'appenditem' function which for example could be useful if getitem is an expensive operation which can be avoided. I hope that was clear enough of a request, it's really late at night here... thanks, RunPun From stef.mientki at gmail.com Wed Aug 26 18:24:34 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 27 Aug 2009 00:24:34 +0200 Subject: Python for professsional Windows GUI apps? In-Reply-To: References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: <4A95B622.50705@gmail.com> David C Ullrich wrote: > On Mon, 24 Aug 2009 22:22:20 -0700, sturlamolden wrote: > > >> On 25 Aug, 05:56, Peter Decker wrote: >> >> >>> I use the Dabo Class Designer to visually design my forms. So what's >>> you're point? :) >>> >> Nothing, except lobbying for wxFormBuilder for anyone who still doesn't >> know of it. :) >> > > That's great. But do you know of anything I can use as a > visual form design tool in wxPython? > > Not a real form designer, but very convenient is XRC or GUI-support http://mientki.ruhosting.nl/data_www/pylab_works/pw_gui_support.html cheers, Stef From john_ladasky at sbcglobal.net Wed Aug 26 18:26:13 2009 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Wed, 26 Aug 2009 15:26:13 -0700 (PDT) Subject: How do I insert a menu item in an existing menu. References: <73dd8da1-7b1e-4065-9c2f-2cee554093e2@j21g2000yqe.googlegroups.com> Message-ID: You might want to direct your wxPython questions to the dedicated wxPython newsgroup. It's Google-only, and thus not part of the Usenet hierarchy. But it's the most on-topic newsgroup you will find. http://groups.google.com/group/wxpython-users I attempted to crosspost this article to wx-python users, but that doesn't work for non-Usenet groups... Good luck! From matthew.bellis at gmail.com Wed Aug 26 18:27:55 2009 From: matthew.bellis at gmail.com (Matt Bellis) Date: Wed, 26 Aug 2009 15:27:55 -0700 (PDT) Subject: How to exclude "import"s from PyDoc Message-ID: Hi all, I tried PyDoc today for documentation for a small project on which I'm working. I have a class, foo, in foo.py. However, at the beginning of the file I "from math import *". When I use PyDoc, it's pulling in all the math functions.... ---snip--- . . . FUNCTIONS acos(...) acos(x) Return the arc cosine (measured in radians) of x. asin(...) asin(x) Return the arc sine (measured in radians) of x. . . . ----snip---- Anyone know the best way to get PyDoc to ignore this (or other) imported module(s)? Thanks in advance. Matt From robert.kern at gmail.com Wed Aug 26 18:48:33 2009 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 26 Aug 2009 17:48:33 -0500 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: Message-ID: On 2009-08-26 17:16 PM, RunThePun wrote: > I'd like to build a database wrapper using DictMixin and allow items > to be appended by my own code. The problem is += is always understood > as setitem and getitem plainly. > > d = MyDict() > d['a'] = 1 > > # this is the problem code that's I'd like to override. It's always > setitem('a', getitem('a') + 3) > d['a'] += 3 > # i wanted to do something like my own 'appenditem' function which for > example could be useful if getitem is an expensive operation which can > be avoided. > > I hope that was clear enough of a request, it's really late at night > here... I'm sorry, this is just part of the syntax of Python. You cannot override it. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mensanator at aol.com Wed Aug 26 18:58:43 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 26 Aug 2009 15:58:43 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> Message-ID: On Aug 26, 4:59?pm, Piet van Oostrum wrote: > >>>>> Mensanator (M) wrote: > >M> That's my point. Since the common usage of "binary" is for > >M> Standard Positional Number System of Radix 2, it follows > >M> that "unary" is the common usage for Standard Positional > >M> Number System of Radix 1. That's VERY confusing since such > >M> a system is undefined. Remember, common usage does not > >M> necessarily properly define things. Saying simply "unary" > >M> sounds like you're extending common usage beyond its proper > >M> boundaries. > > But the customary meaning of `unary' is the tally system, as a radix > system wouldn't make sense. I don't know when this term came into use > but I have known it for a long time. Ok, I'll accept that and in the same breath say such common usage is stupid. I, for one, have never heard such usage and would never use "unary" in the same breath as "decimal, octal, binary" even if I had. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org From deets at nospam.web.de Wed Aug 26 19:01:26 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Aug 2009 01:01:26 +0200 Subject: How to exclude "import"s from PyDoc In-Reply-To: References: Message-ID: <7flt66F2lho6lU1@mid.uni-berlin.de> Matt Bellis schrieb: > Hi all, > > I tried PyDoc today for documentation for a small project on which > I'm working. I have a class, foo, in foo.py. However, at the beginning > of the file I "from math import *". > > When I use PyDoc, it's pulling in all the math functions.... > > ---snip--- > . > . > . > FUNCTIONS > acos(...) > acos(x) > > Return the arc cosine (measured in radians) of x. > > asin(...) > asin(x) > > Return the arc sine (measured in radians) of x. > > . > . > . > ----snip---- > > > Anyone know the best way to get PyDoc to ignore this (or other) > imported module(s)? Don't know about pydoc, but epydoc (which generates much nicer docs imho) can be forced to only include certain packages. Diez From sturlamolden at yahoo.no Wed Aug 26 19:08:53 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 26 Aug 2009 16:08:53 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: <843fa78f-da92-4714-bac5-8807bf11e35a@f37g2000yqn.googlegroups.com> On 26 Aug, 22:47, David C Ullrich wrote: > > Nothing, except lobbying for wxFormBuilder for anyone who still doesn't > > know of it. :) > > That's great. But do you know of anything I can use as a > visual form design tool in wxPython? Right... I don't know if you are trying to be funny, but as I said there is wxFormBuilder... 3.0 generates XRC that you can use with wxPython. 3.1 beta generates wxPython classes you can subclass. Honestly, it's the best GUI builder for wxPython I know of. From cmpython at gmail.com Wed Aug 26 19:12:41 2009 From: cmpython at gmail.com (Che M) Date: Wed, 26 Aug 2009 16:12:41 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: <3a52c99d-6046-4e58-bed3-65d3e98980bb@r36g2000vbn.googlegroups.com> > Combined with the comment above about issues with printing, it looks > like Python for GUI apps isn't a very good idea :-/ I don't have that feeling at all. I don't have that much of a basis of comparison, but my experience with wxPython for making GUI apps has been pretty good. Does anyone know of a wxPython "gallery" of apps using it? That'd be the quickest way to prove its usefulness. Che From cmpython at gmail.com Wed Aug 26 19:27:07 2009 From: cmpython at gmail.com (Che M) Date: Wed, 26 Aug 2009 16:27:07 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: On Aug 26, 4:47?pm, David C Ullrich wrote: > On Mon, 24 Aug 2009 22:22:20 -0700, sturlamolden wrote: > > On 25 Aug, 05:56, Peter Decker wrote: > > >> I use the Dabo Class Designer to visually design my forms. So what's > >> you're point? ?:) > > > Nothing, except lobbying for wxFormBuilder for anyone who still doesn't > > know of it. :) > > That's great. But do you know of anything I can use as a > visual form design tool in wxPython? If in your mind GUI-builder = form builder (or close enough) there's Boa Constructor (my choice) and wxGlade. From rurpy at yahoo.com Wed Aug 26 19:27:33 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Wed, 26 Aug 2009 16:27:33 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> Message-ID: On 08/26/2009 03:10 PM, "Martin v. L?wis" wrote: >> >> In Python 2.5 on Windows I could do [*1]: >> >> >> >> >>> a = unichr (65600) >> >> >>> a[0],a[1] >> >> (u'\ud800', u'\udc40') > > > > I can't reproduce that. My copy of Python on Windows gives > > > > Traceback (most recent call last): > > File "", line 1, in > > unichr(65600) > > ValueError: unichr() arg not in range(0x10000) (narrow Python build) > > > > This is > > > > Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit > > (Intel)] on win32 My apologies for the red herring. I was working from a comment in my replacement ord() function. I dug up an old copy of Python 2.4.3 and could not reproduce it there either so I have no explanation for the comment (which I wrote). Python 2.3 maybe? But regardless, the significant question is, what is the reason for having ord() (and unichr) not work for surrogate pairs and thus not usable with a large number of unicode characters that Python otherwise supports? From rurpy at yahoo.com Wed Aug 26 19:29:34 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Wed, 26 Aug 2009 16:29:34 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: <5f561ea6-95bb-4ccc-9922-decf4e554331@q5g2000yqh.googlegroups.com> On Aug 25, 9:53?pm, "Mark Tolonen" wrote: > wrote in message > > news:2ad21a79-4a6c-42a7-8923-beb304bb5e99 at v20g2000yqm.googlegroups.com... > > > > > In Python 2.5 on Windows I could do [*1]: > > > ?# Create a unicode character outside of the BMP. > > ?>>> a = u'\U00010040' > > > ?# On Windows it is represented as a surogate pair. > > ?>>> len(a) > > ?2 > > ?>>> a[0],a[1] > > ?(u'\ud800', u'\udc40') > > > ?# Create the same character with the unichr() function. > > ?>>> a = unichr (65600) > > ?>>> a[0],a[1] > > ?(u'\ud800', u'\udc40') > > > ?# Although the unichr() function works fine, its > > ?# inverse, ord(), doesn't. > > ?>>> ord (a) > > ?TypeError: ord() expected a character, but string of length 2 found > > > On Python 2.6, unichr() was "fixed" (using the word > > loosely) so that it too now fails with characters outside > > the BMP. > > > ?>>> a = unichr (65600) > > ?ValueError: unichr() arg not in range(0x10000) (narrow Python build) > > > Why was this done rather than changing ord() to accept a > > surrogate pair? > > > Does not this effectively make unichr() and ord() useless > > on Windows for all but a subset of unicode characters? > > Switch to Python 3? > > >>> x='\U00010040' > >>> import unicodedata > >>> unicodedata.name(x) > > 'LINEAR B SYLLABLE B025 A2'>>> ord(x) > 65600 > >>> hex(ord(x)) > '0x10040' > >>> unicodedata.name(chr(0x10040)) > > 'LINEAR B SYLLABLE B025 A2'>>> ord(chr(0x10040)) > 65600 > >>> print(ascii(chr(0x10040))) > > '\ud800\udc40' > > -Mark I am still a long way away from moving to Python 3 but I am looking forward to hopefully more rational unicode handling there. Thanks for the info. From rurpy at yahoo.com Wed Aug 26 19:35:51 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Wed, 26 Aug 2009 16:35:51 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: On Aug 26, 2:05?am, Vlastimil Brom wrote: >[...] > Hi, > I'm not sure about the exact reasons for this behaviour on narrow > builds either (maybe the consistency of the input/ output data to > exactly one character?). > > However, if I need these functions for higher unicode planes, the > following rather hackish replacements seem to work. I presume, there > might be smarter ways of dealing with this, but anyway... > > hth, > ? ?vbr > >[...code snipped...] Thanks, I wrote a replacement ord function nearly identical to yours but will steal your unichr function if that's ok. :-) But I still wonder why all this is neccessary. From robert.kern at gmail.com Wed Aug 26 19:40:19 2009 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 26 Aug 2009 18:40:19 -0500 Subject: Python for professsional Windows GUI apps? In-Reply-To: <843fa78f-da92-4714-bac5-8807bf11e35a@f37g2000yqn.googlegroups.com> References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> <843fa78f-da92-4714-bac5-8807bf11e35a@f37g2000yqn.googlegroups.com> Message-ID: On 2009-08-26 18:08 PM, sturlamolden wrote: > On 26 Aug, 22:47, David C Ullrich wrote: > >>> Nothing, except lobbying for wxFormBuilder for anyone who still doesn't >>> know of it. :) >> >> That's great. But do you know of anything I can use as a >> visual form design tool in wxPython? > > Right... I don't know if you are trying to be funny, but as I said > there is wxFormBuilder... > > 3.0 generates XRC that you can use with wxPython. > 3.1 beta generates wxPython classes you can subclass. > > Honestly, it's the best GUI builder for wxPython I know of. It's possible that he is not asking for a visual form designer tool *for* building a wxPython app, but one that can be used *inside* a wxPython app like an IDE or something similar. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From stef.mientki at gmail.com Wed Aug 26 19:42:47 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 27 Aug 2009 01:42:47 +0200 Subject: Python for professsional Windows GUI apps? In-Reply-To: References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: <4A95C877.7020401@gmail.com> Gilles Ganault wrote: > On Tue, 25 Aug 2009 13:24:39 +0200, Wolfgang Keller > wrote: > >> The area of _desktop_ database application development indeed looks like a vast and very hostile desert in the Python landscape. >> >> The only framework that seems to be worth trying is Dabo. Unfortunately there's little documentation, and that's mostly outdated. >> >> There's also Kiwi, but that's even less well documented. >> >> And GNU Enterprise essentially seems to be dead. >> > > Combined with the comment above about issues with printing, it looks > like Python for GUI apps isn't a very good idea :-/ > > I'd be interested in checking out commercial applications written in > Python for the Windows OS, if there are any. > I've been grown up with (and still using) Delphi, known as having th? best GUI-builder. I now use wxPython (with GUI-support), with more comfort and more easy than Delphi ! cheers, Stef > Thank you. > From sjmachin at lexicon.net Wed Aug 26 19:53:28 2009 From: sjmachin at lexicon.net (John Machin) Date: Wed, 26 Aug 2009 23:53:28 +0000 (UTC) Subject: Zlib: correct checksum but error decompressing References: <99c381ef-a146-4545-9344-7b15d60441de@y20g2000vbk.googlegroups.com> <7xk50qz1a2.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > > Andre gmail.com> writes: > > I have been trying to solve this issue for a while now. I receive data > > from a TCP connection which is compressed. > > Are you sure it is compressed with zlib? If yes, does it include the > standard zlib header? Some applications save a few bytes by stripping > the header. See the zlib doc page for how to deal with that, there is > a flag that causes the header check to be skipped on decompression if > you pass a negative number. That's the first thing I would try. Short answer: Try this: zlib.decompress(incoming_data, -15) If that doesn't work: print repr(incoming_data[:30]) # post the results here Longer answer: A zlib stream consists of a deflate stream preceded by a 2-byte header and followed by a 4-byte Adler32 checksum of the original data. The problem occurs not out of a desire to save 6 bytes but through compounding of 2 mistakes: Mistake (1) is in the HTTP protocol. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html The "deflate" content coding should have been called "zlib". Read this and weep: """deflate The "zlib" format defined in RFC 1950 [31] in combination with the "deflate" compression mechanism described in RFC 1951 [29].""" Mistake (2) happens when software implementers read only the first word of the above quote and provide only a deflate stream. A reader can handle both possibilities by checking for a (usual, default) zlib header: data[0] == '\x78' and (ord(data[1]) + 0x7800) % 31 == 0 HTH, John From contact at xavierho.com Wed Aug 26 20:20:59 2009 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 Aug 2009 10:20:59 +1000 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: Message-ID: <2d56febf0908261720i70dd92cds13c0139f25646c70@mail.gmail.com> I haven't tested it, but did you encounter a problem defining __iadd__ in the class definition? See: http://docs.python.org/reference/datamodel.html#object.__iadd__ Cheers, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ On Thu, Aug 27, 2009 at 8:48 AM, Robert Kern wrote: > On 2009-08-26 17:16 PM, RunThePun wrote: > >> I'd like to build a database wrapper using DictMixin and allow items >> to be appended by my own code. The problem is += is always understood >> as setitem and getitem plainly. >> >> d = MyDict() >> d['a'] = 1 >> >> # this is the problem code that's I'd like to override. It's always >> setitem('a', getitem('a') + 3) >> d['a'] += 3 >> # i wanted to do something like my own 'appenditem' function which for >> example could be useful if getitem is an expensive operation which can >> be avoided. >> >> I hope that was clear enough of a request, it's really late at night >> here... >> > > I'm sorry, this is just part of the syntax of Python. You cannot override > it. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless > enigma > that is made terrible by our own mad attempt to interpret it as though it > had > an underlying truth." > -- Umberto Eco > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vlastimil.brom at gmail.com Wed Aug 26 20:26:28 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Thu, 27 Aug 2009 02:26:28 +0200 Subject: break unichr instead of fix ord? In-Reply-To: References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: <9fdb569a0908261726t23d19f82pa590b57a4297d662@mail.gmail.com> 2009/8/27 : > On Aug 26, 2:05?am, Vlastimil Brom wrote: >>[...] >>... >> However, if I need these functions for higher unicode planes, the >> following rather hackish replacements seem to work. I presume, there >> might be smarter ways of dealing with this, but anyway... >> >> hth, >> ? ?vbr >> >>[...code snipped...] > > Thanks, I wrote a replacement ord function nearly identical > to yours but will steal your unichr function if that's ok. :-) > > But I still wonder why all this is neccessary. > -- You are welcome :-), but make sure to test it, if you are going to use it for something more complex; as I said, it's only vaguely tested ... vbr From zuo at chopin.edu.pl Wed Aug 26 21:00:10 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 27 Aug 2009 03:00:10 +0200 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: Message-ID: 27-08-2009 o 00:48:33 Robert Kern wrote: > On 2009-08-26 17:16 PM, RunThePun wrote: >> I'd like to build a database wrapper using DictMixin and allow items >> to be appended by my own code. The problem is += is always understood >> as setitem and getitem plainly. >> >> d = MyDict() >> d['a'] = 1 >> >> # this is the problem code that's I'd like to override. It's always >> setitem('a', getitem('a') + 3) >> d['a'] += 3 >> # i wanted to do something like my own 'appenditem' function which for >> example could be useful if getitem is an expensive operation which can >> be avoided. >> >> I hope that was clear enough of a request, it's really late at night >> here... > > I'm sorry, this is just part of the syntax of Python. You cannot > override it. Though d['a'] = 3 is equivalent to: d.__setitem__('a', 3) The d['a'] += 3 *is not* equivalent to: d.__setitem__('a', d.__getitem__('a') + 3) *but is* equivalent to: d.__getitem__('a').__iadd__(3) Then you can override __getitem__() of MyDict in such a way that it returns prepared (wrapped) object with overriden __iadd__() as you want to. How could I now it: 1 import collections 2 import functools 3 import itertools 4 5 6 def verbose_func(func): 7 'Function decorator that makes a function "verbose"' 8 9 @functools.wraps(func, assigned=('__name__', '__doc__')) 10 def func_wrapper(*args, **kwargs): 11 iargs = (map(str, args)) 12 ikwargs = ('{0}={1}'.format(key, value) 13 for key, value in kwargs.items()) 14 func_args = ', '.join(itertools.chain(iargs, ikwargs)) 15 print('{0}({1})'.format(func.__name__, func_args)) 16 return func(*args, **kwargs) 17 18 return func_wrapper 19 20 21 def verbose_cls(base): 22 'Class decorator that makes callable attributes "verbose"' 23 24 quiet = ('__new__', '__repr__', '__str__') 25 26 def cls_wrapper(cls): 27 for name in vars(base): 28 attr = getattr(cls, name) 29 if isinstance(attr, collections.Callable) and name not in quiet: 30 setattr(cls, name, verbose_func(attr)) 31 return cls 32 33 return cls_wrapper 34 35 36 @verbose_cls(dict) 37 class VerboseDict(dict): 38 pass 39 40 41 @verbose_cls(int) 42 class MyInt(int): 43 44 @verbose_func 45 def __iadd__(self, other): 46 int.__add__(self, other) # can do something more interesting 47 48 49 if __name__ == '__main__': 50 d = VerboseDict() 51 52 print("d['a'] = 3") 53 d['a'] = MyInt(3) 54 55 print("d['a'] += 3") 56 d['a'] += MyInt(3) *j -- Jan Kaliszewski (zuo) From aahz at pythoncraft.com Wed Aug 26 21:01:35 2009 From: aahz at pythoncraft.com (Aahz) Date: 26 Aug 2009 18:01:35 -0700 Subject: List iterator thread safety References: Message-ID: In article , Emanuele D'Arrigo wrote: > >Let's say I have a list accessed by two threads, one removing list >items via "del myList[index]" statement the other iterating through >the list and printing out the items via "for item in myList:" >statement. Am I right to say this -won't- generate exceptions because >the list iterator is not concerned with the list changing in size >under its nose? Or are there pitfalls I should be aware of? Well, I'm not sure about exceptions, but you almost certainly won't get the results you want. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From zuo at chopin.edu.pl Wed Aug 26 21:02:19 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 27 Aug 2009 03:02:19 +0200 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: Message-ID: 27-08-2009 o 00:48:33 Robert Kern wrote: > On 2009-08-26 17:16 PM, RunThePun wrote: >> I'd like to build a database wrapper using DictMixin and allow items >> to be appended by my own code. The problem is += is always understood >> as setitem and getitem plainly. >> >> d = MyDict() >> d['a'] = 1 >> >> # this is the problem code that's I'd like to override. It's always >> setitem('a', getitem('a') + 3) >> d['a'] += 3 >> # i wanted to do something like my own 'appenditem' function which for >> example could be useful if getitem is an expensive operation which can >> be avoided. >> >> I hope that was clear enough of a request, it's really late at night >> here... > > I'm sorry, this is just part of the syntax of Python. You cannot > override it. Though d['a'] = 3 is equivalent to: d.__setitem__('a', 3) The d['a'] += 3 *is not* equivalent to: d.__setitem__('a', d.__getitem__('a') + 3) *but is* equivalent to: d.__setitem__('a', d.__getitem__('a').__iadd__(3)) Then you can override __getitem__() of MyDict in such a way that it returns prepared (wrapped) object with overriden __iadd__() as you want to. How could I now it: 1 import collections 2 import functools 3 import itertools 4 5 6 def verbose_func(func): 7 'Function decorator that makes a function "verbose"' 8 9 @functools.wraps(func, assigned=('__name__', '__doc__')) 10 def func_wrapper(*args, **kwargs): 11 iargs = (map(str, args)) 12 ikwargs = ('{0}={1}'.format(key, value) 13 for key, value in kwargs.items()) 14 func_args = ', '.join(itertools.chain(iargs, ikwargs)) 15 print('{0}({1})'.format(func.__name__, func_args)) 16 return func(*args, **kwargs) 17 18 return func_wrapper 19 20 21 def verbose_cls(base): 22 'Class decorator that makes callable attributes "verbose"' 23 24 quiet = ('__new__', '__repr__', '__str__') 25 26 def cls_wrapper(cls): 27 for name in vars(base): 28 attr = getattr(cls, name) 29 if isinstance(attr, collections.Callable) and name not in quiet: 30 setattr(cls, name, verbose_func(attr)) 31 return cls 32 33 return cls_wrapper 34 35 36 @verbose_cls(dict) 37 class VerboseDict(dict): 38 pass 39 40 41 @verbose_cls(int) 42 class MyInt(int): 43 44 @verbose_func 45 def __iadd__(self, other): 46 int.__add__(self, other) # can do something more interesting 47 48 49 if __name__ == '__main__': 50 d = VerboseDict() 51 52 print("d['a'] = 3") 53 d['a'] = MyInt(3) 54 55 print("d['a'] += 3") 56 d['a'] += MyInt(3) *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Wed Aug 26 21:06:16 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 27 Aug 2009 03:06:16 +0200 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: Message-ID: PS. Sorry for sending 2 posts -- the latter is the correct one. Cheers, *j From davea at ieee.org Wed Aug 26 21:19:37 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 21:19:37 -0400 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <1251323517.23132.6.camel@jabbar> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> <1251323517.23132.6.camel@jabbar> Message-ID: <4A95DF29.5070803@ieee.org> (Looks like you posted privately to me; should use Reply-all. I'm copying entire message here so others can add to my comments) Mac Ryan wrote: > On Wed, 2009-08-26 at 15:46 -0400, Dave Angel wrote: > >> So define a classmethod to finish the job, and invoke it later >> >> class Employee(object): >> @classmethod >> def finish(cls): >> cls.__storm_table__ = "employee" >> cls.company_id = [] >> cls.company = Company.id #where Company is a forward >> reference >> del cls.finish #remove this method so it won't be called a >> second time >> >> class Company: >> id = 42 >> >> Employee.finish() #This finishes initializing the class >> >> >> help(Employee) >> print Employee.company_id >> > > First things first, thank you Wayne, Kent and Dave for your extensive > and complementary explanations. As many things in python, what it seemed > obscure at first now - with your help - seems perfectly obvious. > > Second thing: the example that Dave gave me and that I left quoted above > makes use of decorators, but this is something that I still do not > understand. I believe I got a grasp of the concept of metaclasses, to > which the concept of decorator seems to be related, but the official > documentation is a a bit obscure for me. > > I don't want to steal your time asking for an explanation that probably > is already somewhere out there, but my google searches did not return > anything useful (I assume I am using the wrong keywords here), so if you > have a good pointer for me, I would be very grateful. :) > > Mac. > > > Decorators are syntactic sugar to save typing; what they accomplish can always be done another way, but generally not as readable. #somebody (eg., Python library) defines a function that takes a function as parameter, and returns a function, generally a different one related to the first def mydecorator(funct): .... return newfunct class myclass(object): @mydecorator def mymethod(self, arg1, arg2): ... Instead of the @syntax, we could also have written: class myclass(object): def mymethod(self, arg1, arg2) .... mymethod = mydecorator(mymethod) #this call happens when the class is being created Now there are a couple of decorators that are in the standard library that everyone should know about: classmethod() and staticmethod(). They wrap a method in a new one (which ends up having the same name), such that the first argument is either eaten (staticmethod), or changed to a class (classmethod). Hope that was sufficient detail. DaveA From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 21:34:10 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 01:34:10 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> Message-ID: <02a5d290$0$15633$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 10:58:12 -0700, Mensanator wrote: >> But I certainly wouldn't call it "binary", for fear of confusion with >> radix-2 binary. > > That's my point. Since the common usage of "binary" is for Standard > Positional Number System of Radix 2, it follows that "unary" is the > common usage for Standard Positional Number System of Radix 1. Er, no, that doesn't follow. There is no such thing as a radix-1 positional number system -- it just doesn't work. In any case, unary is the standard term for what I'm discussing: http://en.wikipedia.org/wiki/Unary_numeral_system although Mathworld doesn't seem to know it. > That's VERY confusing since such a system is undefined. Base-1 positional system is defined, it just doesn't work. You would have to write a number by the sum of 0*(1**i), which clearly doesn't get you very far. Positional unary is only capable of representing zero, and no other numbers, which is even less useful than unary, which at least can be used for counting positive numbers, addition and subtraction, and even has a use in Elias gamma coding. > Remember, common usage > does not necessarily properly define things. Saying simply "unary" > sounds like you're extending common usage beyond its proper boundaries. You're reasoning by analogy: "binary" means "positional number system with radix 2", "decimal" => radix 10, etc, so "unary" => radix 1. That's a reasonable heuristic to follow, but it can fail, because even in mathematics, names for things don't necessarily follow such patterns perfectly. Because the radix 1 positional system can't work and therefore doesn't exist, the name "unary" is available, and has been taken to describe a number system which counts by tally marks. -- Steven From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 21:52:27 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 01:52:27 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> <02a5d290$0$15633$c3e8da3@news.astraweb.com> Message-ID: <02a5d6da$0$15633$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 01:34:10 +0000, Steven D'Aprano wrote: > On Wed, 26 Aug 2009 10:58:12 -0700, Mensanator wrote: > >>> But I certainly wouldn't call it "binary", for fear of confusion with >>> radix-2 binary. >> >> That's my point. Since the common usage of "binary" is for Standard >> Positional Number System of Radix 2, it follows that "unary" is the >> common usage for Standard Positional Number System of Radix 1. > > Er, no, that doesn't follow. There is no such thing as a radix-1 > positional number system -- it just doesn't work. Sorry, this is clumsy writing... of course radix-1 positional number system is defined, it's just pointless -- it is only capable of representing 0 = 00 = 000 = 0000 ... -- Steven From max at alcyone.com Wed Aug 26 21:53:04 2009 From: max at alcyone.com (Erik Max Francis) Date: Wed, 26 Aug 2009 18:53:04 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: <02a5d290$0$15633$c3e8da3@news.astraweb.com> References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> <02a5d290$0$15633$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Wed, 26 Aug 2009 10:58:12 -0700, Mensanator wrote: > >>> But I certainly wouldn't call it "binary", for fear of confusion with >>> radix-2 binary. >> That's my point. Since the common usage of "binary" is for Standard >> Positional Number System of Radix 2, it follows that "unary" is the >> common usage for Standard Positional Number System of Radix 1. > > Er, no, that doesn't follow. There is no such thing as a radix-1 > positional number system -- it just doesn't work. > > In any case, unary is the standard term for what I'm discussing: > > http://en.wikipedia.org/wiki/Unary_numeral_system > > although Mathworld doesn't seem to know it. Psst. That's a hint. Googling for "unary number system" ("unary numeral system" just comes up with endless mirrors of Wikipedia) gives Wikipedia as hit #1. Hit #2 is from the Institute of Druidic Technology, another hint. The remaining hits are pretty much people pontificating in discussion groups just as they are in this one. Yes, you can define something that works. But it's not the usual mathematical definition of radix, so if you want to talk about it you have to disclaim that it's not a proper base and that's you're making up as you go. But you can't pretend like it's the "obvious" mathematical meaning just because the usual mathematical meaning doesn't apply, which is what you seem to be doing. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis And I've seen the promised land. I may not get there with you. -- Dr. Martin Luther King, Jr. From graham.dumpleton at gmail.com Wed Aug 26 22:09:49 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Wed, 26 Aug 2009 19:09:49 -0700 (PDT) Subject: Python on the Web References: <4a94ef42$0$27774$426a74cc@news.free.fr> Message-ID: On Aug 27, 2:54?am, Phil wrote: > Thanks to everybody. I believe I am understanding things better. > > I have looked at the links that have been provided, although I have > seen most of them in the past month or so that I've been looking into > this stuff. I do agree with most of the things Armin stated in that > NIH post. I agree with everybody in this thread so far. If I wanted to > write an application, I would use an existing framework and wait for > it to be ported to 3.x. However, I do not have the need to write a web > application at this time, and creating blogs or other applications I > do not need for fun is getting old. > > My reasoning for working on my own instead of following the 'NIH' > concept or contributing to an existing framework is because I have > experimented with many existing frameworks and I have figured out what > I like/dislike, and have envisioned my own design that I feel would > work potentially better for others, or at least newcomers. Things like > this are fun for me, and I do not mind the challenge. I don't want to > pollute the web with (sigh) 'another framework', but it would be fun > for me to write it and get some feedback. I would love for people like > you, Armin, and others who take a look at the various frameworks that > pop up seemingly every day, to look at my (hypothetical) framework and > just rip it apart with (constructive) criticism. That is just the way > I do things, whether the community agrees with it or not. The reason I > was asking about Python 3 on the web was just because I like some of > the changes that have been made, and would like to use it for my > framework. That is when I realized that I was absolutely clueless > about the details of how Python, or any language, works on the web. > > Graham, regarding number 3 in your list of ways to host WSGI: I > haven't really looked into mod_wsgi at all, but basically it sounds > like the web server would be running this embedded module. That module > would then serve the function of both FCGI and the 'WSGI Server' in my > diagram? That actually sounds really neat. Unfortunately I missed this > because I've been hooked on lighttpd, as the minimalist I am. > > Here are the things I am still confused with: > > 1) Why do I not want to consider running Python on the web with FCGI, > without WSGI? You said 'no' straight up, no questions asked. I would > imagine that there is a good reason of course, as you've been in this > field for a long time. Because FASTCGI is a wire protocol for socket communications and not a programming interface. As such, you would only be creating much more work for your self as you would need to implement a whole lot of code to handle the protocol and then still put a usable interface on top of it. You would also have to come up with what that usable interface should be as well. WSGI already provides that low level interface. > I just feel more comfortable understanding why. > From my understanding, the only real purpose of WSGI is to remain > independent of FCGI/SCGI/CGI/AJP (whatever that is) and the web server > it is run on. However, 99.9% of the discussion I see with Python on > the web is around FCGI. 99.9% of the discussion about Python on the web is not around FASTCGI. Even if there is quite a bit of discussion, it is because documentation on hosting Python on FASTCGI via flup is virtually non existent and so many people have a lot of trouble getting it to work due to peculiarities of different FASTCGI implementations. The dicusssion is therefore because people have problems with it, or feel the need to blog about how they finally got it to work. So, FASTCGI may be the only way for commodity web hosting, but it certainly isn't for self managed servers where mod_wsgi, mod_python and mod_proxy type solutions are going to be preferred. The latter are better documented or easier to setup and so why you possibly don't see as much discussion. In other words, people who get things working easily don't need to ask questions. > So for example, lets say everybody used FCGI. > All that would be left to deal with is web server independence. Now > this is what I don't get, I thought that FCGI itself was supposed to > be the protocol that deals with web server independence. Maybe I just > need to re-read entire WSGI specification to understand, along with > all the details of FCGI. There are just so many details regarding web > servers, FCGI, and WSGI that it is hard to absorb it all and see how > it works together. That is why I tried to create the diagram, but it > doesn't provide enough details. And those are the details I am > missing. I've been trying to find a simple diagram or explaination of > the process a request takes to make a response, from HTTP all the way > up to the application, to the the user. FASTCGI fills a role, but is not essential. Personally I feel that whole concept of FASTCGI/SCGI/AJP needs a refresh and modernised with better hosting support for it. > 2) In the development stack, the 'WSGI Server' seems to take on the > role of the web server (dealing with HTTP specification), It doesn't have to. Some servers may have a clear line between the two with WSGI being a properly distinct layer on top. > skips FCGI, > and deals with the WSGI specification. Then, the 'WSGI Server' in the > production stack (eg. Flup, CherryPy, etc) only deals with FCGI and > WSGI specification, because the HTTP is already taken care of by the > web server? Graham From manish.paradkar at gmail.com Wed Aug 26 22:39:21 2009 From: manish.paradkar at gmail.com (manish) Date: Thu, 27 Aug 2009 10:39:21 +0800 Subject: Python Processor Message-ID: <7670c8130908261939p7ef1726bodbae14d836d33ea5@mail.gmail.com> Hi, Contrary to the ancient and, I believe, obsolete text in the documentation, there is no 'python bytecode'. Dis is based on CPython bytecode. Jython uses Java bytecode. IronPython uses, I believe, Microsoft clr bytecode. Object code compilers do not use bytecode. Before going through the one of the existing VM implementations, i want to know if there is there any informaition available which elaborates on the structure of the bytecodes. Like details regarding co_names, co_cellvars, co_freevars, the concept of frames, global, local, objects, functions etc with respect to the bytecode. These are mostly version-specific Cpython implementation details. tjr I agree, i am looking at a version-specific CPython implementation, or can be PyPy even . I need some information on the implementation of these interpreters which would help me visualize how they can be mapped to hardware. It probably wouldn't help much. CPython's performance problems come from excessive dictionary lookups, not from instruction decode. John Nagle This is just for my personal interest so currently i am not looking at performance - just be able to implement a basic core at first. The idea is to then extend it and develop a self contained unit of computation which can be reconfigured on the fly. So given enough memory and I/Os the same module can behave differently depending on the script loaded. One can either have a large monolithic cpu running an OS of some sorts or smaller processors each executing their own little scripts and communicating with each other. Manish -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet at enigmacurry.com Wed Aug 26 22:52:19 2009 From: usenet at enigmacurry.com (Ryan McGuire) Date: Wed, 26 Aug 2009 19:52:19 -0700 (PDT) Subject: codecs.open on Win32 -- converting my newlines to CR+LF Message-ID: <8fbc2c4a-c347-43df-8830-3b4e86d95792@t13g2000yqt.googlegroups.com> I've got a UTF-8 encoded text file from Linux with standard newlines ("\n"). I'm reading this file on Win32 with Python 2.6: codecs.open("whatever.txt","r","utf-8").read() Inexplicably, all the newlines ("\n") are replaced with CR+LF ("\r \n") ... Why? As a workaround I'm having to do this: open("whatever.txt","r").read().decode("utf-8") which appropriately does not alter my newlines. What really gets me confused though is the Python docs for codecs.open: "Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8- bit values. This means that no automatic conversion of '\n' is done on reading and writing." The way I read that, codecs.open should not touch my newlines. What am I doing wrong? Is this a bug in Python, or in the docs, or both? From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 22:52:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 02:52:41 GMT Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> Message-ID: <02a5e4f7$0$15633$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 16:27:33 -0700, rurpy wrote: > But regardless, the significant question is, what is the reason for > having ord() (and unichr) not work for surrogate pairs and thus not > usable with a large number of unicode characters that Python otherwise > supports? I'm no expert on Unicode, but my guess is that the reason is out of a desire for simplicity: unichr() should always return a single char, not a pair of chars, and similarly ord() should take as input a single char, not two, and return a single number. Otherwise it would be ambiguous whether ord(surrogate_pair) should return a pair of ints representing the codes for each item in the pair, or a single int representing the code point for the whole pair. E.g. given your earlier example: >>> a = u'\U00010040' >>> len(a) 2 >>> a[0] u'\ud800' >>> a[1] u'\udc40' would you expect ord(a) to return (0xd800, 0xdc40) or 0x10040? If the latter, what about ord(u'ab')? Remember that a unicode string can contain code points that aren't valid characters: >>> ord(u'\ud800') # reserved for surrogates, not a character 55296 so if ord() sees a surrogate pair, it can't assume it's meant to be treated as a surrogate pair rather than a pair of code points that just happens to match a surrogate pair. None of this means you can't deal with surrogate pairs, it just means you can't deal with them using ord() and unichr(). The above is just my guess, I'd be interested to hear what others say. -- Steven From phily05 at gmail.com Wed Aug 26 23:02:55 2009 From: phily05 at gmail.com (Phil) Date: Wed, 26 Aug 2009 20:02:55 -0700 (PDT) Subject: Python on the Web References: <4a94ef42$0$27774$426a74cc@news.free.fr> Message-ID: <835a57b2-9a08-4f10-b2d4-78c96f22f3ee@n11g2000yqb.googlegroups.com> Thanks a lot for another response. I've never posted in groups like this before but the results are amazing. I will definitely consider trying mod_wsgi when I get a chance. I like the approach taken with it. It is unfortunate that I completely missed all Apache related material because I was using lighttpd. Is there no mod_wsgi for lighttpd? I guess I could always just Google that myself. Thanks again for the help. From philip at semanchuk.com Wed Aug 26 23:04:31 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 26 Aug 2009 23:04:31 -0400 Subject: codecs.open on Win32 -- converting my newlines to CR+LF In-Reply-To: <8fbc2c4a-c347-43df-8830-3b4e86d95792@t13g2000yqt.googlegroups.com> References: <8fbc2c4a-c347-43df-8830-3b4e86d95792@t13g2000yqt.googlegroups.com> Message-ID: <2E7FD302-C77A-48DD-B03D-B1959945BBA4@semanchuk.com> On Aug 26, 2009, at 10:52 PM, Ryan McGuire wrote: > I've got a UTF-8 encoded text file from Linux with standard newlines > ("\n"). > > I'm reading this file on Win32 with Python 2.6: > > codecs.open("whatever.txt","r","utf-8").read() > > Inexplicably, all the newlines ("\n") are replaced with CR+LF ("\r > \n") ... Why? Try using "rb" instead of "r" for the mode in the call to open(). HTH Philip From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 23:27:05 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 03:27:05 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> <02a5d290$0$15633$c3e8da3@news.astraweb.com> Message-ID: <02a5ed07$0$15633$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 18:53:04 -0700, Erik Max Francis wrote: >> In any case, unary is the standard term for what I'm discussing: >> >> http://en.wikipedia.org/wiki/Unary_numeral_system >> >> although Mathworld doesn't seem to know it. > > Psst. That's a hint. > > Googling for "unary number system" ("unary numeral system" just comes up > with endless mirrors of Wikipedia) gives Wikipedia as hit #1. Hit #2 is > from the Institute of Druidic Technology, another hint. The remaining > hits are pretty much people pontificating in discussion groups just as > they are in this one. Perhaps you should FOLLOW THE REFERENCES from the Wikipedia article, instead of relying on Google. http://www.research.att.com/~njas/sequences/A000042 which in turn points to primary references: K. G. Kroeber, Mathematik der Palindrome; p. 348; 2003; ISBN 3 499 615762; Rowohlt Verlag; Germany D. Olivastro, Ancient Puzzles. Bantam Books, NY, 1993, p. 276. Amarnath Murthy, On the divisors of the unary sequence, Smarandache Notions Journal Vol. - 11, 2000. Amarnath Murthy and Charles Ashbacher, Generalized Partitions and Some New Ideas on Number Theory and Smarandache Sequences, Hexis, Phoenix; USA 2005. See Section 2.12. > Yes, you can define something that works. But it's not the usual > mathematical definition of radix, It's not a radix. I never said it is a radix. Only you and Mensator are confusing it with a radix system, which is *your* problem, not mine. > so if you want to talk about it you > have to disclaim that it's not a proper base and that's you're making up > as you go. But you can't pretend like it's the "obvious" mathematical > meaning just because the usual mathematical meaning doesn't apply, which > is what you seem to be doing. I explicitly gave an example, showing what I meant by unary, because I knew it would be unfamiliar terminology for most people. When my example was ignored completely, I explained further, and showed that it's fairly standard terminology. It is *uncommon* terminology, since most mathematicians don't concern themselves with non-positional number representations, which is why Goggle doesn't find many references to it apart from Wikipedia and copies of Wikipedia. David Wheeler also discusses "base 1", and describes it as "cheating a bit". It's only cheating if you assume you're working with a positional radix system, which tallies aren't. Here's another example, from American Scientist: https://www.americanscientist.org/issues/pub/third-base/2 although that site seems to be having problems now and you're best off with the Google cache: http://74.125.153.132/search?q=cache:7hlZ33y4uCAJ:https:// www.americanscientist.org/issues/pub/third-base/2+%22base+1%22 +numbers&cd=18&hl=en&ct=clnk&gl=uk&ie=UTF-8 [quote] How do you measure the cost of a numeric representation? If you simply count digits, then the biggest base will always win; for example, base 1,000,000 can represent any number between 0 and decimal 999,999 in a single digit. The trouble is, that single digit can be any of a million different symbols, all of which you must somehow recognize. At the opposite pole are unary, or base-1, numbers. The unary representation of decimal 1,000,000 needs only one type of symbol, but that symbol is repeated a million times. (Unary notation is in a category apart from other bases?it's not really a positional number system?but in the present context it serves as a useful limiting case.) [end quote] This really isn't anywhere near as controversial as you guys are making it. Words sometimes have meanings different from what you expect from reasoning by analogy. Get over it. -- Steven From usenet at enigmacurry.com Wed Aug 26 23:40:36 2009 From: usenet at enigmacurry.com (Ryan McGuire) Date: Wed, 26 Aug 2009 20:40:36 -0700 (PDT) Subject: codecs.open on Win32 -- converting my newlines to CR+LF References: <8fbc2c4a-c347-43df-8830-3b4e86d95792@t13g2000yqt.googlegroups.com> Message-ID: <6085bece-97c6-4400-9571-7cd288da1578@g31g2000yqc.googlegroups.com> On Aug 26, 11:04?pm, Philip Semanchuk wrote: > Try using "rb" instead of "r" for the mode in the call to open(). > > HTH > Philip That does indeed fix the problem, thanks! Still seems like the docs are wrong though. From robert.kern at gmail.com Wed Aug 26 23:58:05 2009 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 26 Aug 2009 22:58:05 -0500 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: Message-ID: On 2009-08-26 20:00 PM, Jan Kaliszewski wrote: > 27-08-2009 o 00:48:33 Robert Kern wrote: > >> On 2009-08-26 17:16 PM, RunThePun wrote: >>> I'd like to build a database wrapper using DictMixin and allow items >>> to be appended by my own code. The problem is += is always understood >>> as setitem and getitem plainly. >>> >>> d = MyDict() >>> d['a'] = 1 >>> >>> # this is the problem code that's I'd like to override. It's always >>> setitem('a', getitem('a') + 3) >>> d['a'] += 3 >>> # i wanted to do something like my own 'appenditem' function which for >>> example could be useful if getitem is an expensive operation which can >>> be avoided. >>> >>> I hope that was clear enough of a request, it's really late at night >>> here... >> >> I'm sorry, this is just part of the syntax of Python. You cannot >> override it. > > Though > d['a'] = 3 > is equivalent to: > d.__setitem__('a', 3) > > The > d['a'] += 3 > *is not* equivalent to: > d.__setitem__('a', d.__getitem__('a') + 3) > *but is* equivalent to: > d.__getitem__('a').__iadd__(3) > > Then you can override __getitem__() of MyDict in such a way that it > returns prepared (wrapped) object with overriden __iadd__() as you > want to. You could, but then you will almost certainly run into problems using the wrapped object in places that really expect the true object. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From rylesny at gmail.com Thu Aug 27 00:44:43 2009 From: rylesny at gmail.com (ryles) Date: Wed, 26 Aug 2009 21:44:43 -0700 (PDT) Subject: Object's nesting scope References: Message-ID: On Aug 26, 8:51?am, zaur wrote: > Hi folk! > > What do you think about idea of "object's nesting scope" in python? > > Let's imaging this feature, for example, in this syntax: > > obj=: > ? ? ? > > or > > : > ? ? > > That's means that result object of evaluation is used as > nested scope for evaluation. > > So is this idea useful? > > Zaur FYI, there was recently a similar idea being discussed on the python- ideas list: http://groups.google.com/group/python-ideas/browse_thread/thread/1a13cd9a5189b01c?hl=en From rurpy at yahoo.com Thu Aug 27 01:36:12 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Wed, 26 Aug 2009 22:36:12 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <02a5e4f7$0$15633$c3e8da3@news.astraweb.com> Message-ID: <144510f3-3cc4-4b3f-bdcc-98e810d6ee35@2g2000prl.googlegroups.com> On 08/26/2009 08:52 PM, Steven D'Aprano wrote: > On Wed, 26 Aug 2009 16:27:33 -0700, rurpy wrote: > >> But regardless, the significant question is, what is the reason for >> having ord() (and unichr) not work for surrogate pairs and thus not >> usable with a large number of unicode characters that Python otherwise >> supports? > > > I'm no expert on Unicode, but my guess is that the reason is out of a > desire for simplicity: unichr() should always return a single char, not a > pair of chars, and similarly ord() should take as input a single char, > not two, and return a single number. > > Otherwise it would be ambiguous whether ord(surrogate_pair) should return > a pair of ints representing the codes for each item in the pair, or a > single int representing the code point for the whole pair. > > E.g. given your earlier example: > >>>> a = u'\U00010040' >>>> len(a) > 2 >>>> a[0] > u'\ud800' >>>> a[1] > u'\udc40' > > would you expect ord(a) to return (0xd800, 0xdc40) or 0x10040? The latter. > If the > latter, what about ord(u'ab')? I would expect a TypeError* (as ord() currently raises) because the string length is not 1 and 'ab' is not a surrogate pair. *Actually I would have expected ValueError but I'm not going to lose sleep over it. > Remember that a unicode string can contain code points that aren't valid > characters: > >>>> ord(u'\ud800') # reserved for surrogates, not a character > 55296 > > so if ord() sees a surrogate pair, it can't assume it's meant to be > treated as a surrogate pair rather than a pair of code points that just > happens to match a surrogate pair. Well, actually, yes it can. :-) Python has already made a strong statement that such a pair the representation of a character: >>> a = ''.join([u'\ud800',u'\udc40']) >>> a u'\U00010040' That is, Python prints, and treats in nearly all other contexts, that combination as a character. This is related to the practicality argument: what is the ratio of need treat a surrogate pair as character consistent with with the rest of Python, vs the need to treat it as a string of two separate (and invalid in the unicode sense?) characters? And if you want to treat each half of the pair separately it's not exactly hard: ord(a[0]), ord(a[1]). > None of this means you can't deal with surrogate pairs, it just means you > can't deal with them using ord() and unichr(). Kind of like saying, it doesn't mean you can't deal with integers larger that 2**32, you just can't multiply and divide them. > The above is just my guess, I'd be interested to hear what others say. From martin at v.loewis.de Thu Aug 27 01:51:29 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 27 Aug 2009 07:51:29 +0200 Subject: break unichr instead of fix ord? In-Reply-To: References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> Message-ID: <4A961EE1.9010103@v.loewis.de> > My apologies for the red herring. I was working from > a comment in my replacement ord() function. I dug up > an old copy of Python 2.4.3 and could not reproduce it > there either so I have no explanation for the comment > (which I wrote). Python 2.3 maybe? No. The behavior you observed would only happen on a wide Unicode build (e.g. on Unix). > But regardless, the significant question is, what is > the reason for having ord() (and unichr) not work for > surrogate pairs and thus not usable with a large number > of unicode characters that Python otherwise supports? See PEP 261, http://www.python.org/dev/peps/pep-0261/ It specifies all this. Regards, Martin From clp2 at rebertia.com Thu Aug 27 02:06:07 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 26 Aug 2009 23:06:07 -0700 Subject: codecs.open on Win32 -- converting my newlines to CR+LF In-Reply-To: <6085bece-97c6-4400-9571-7cd288da1578@g31g2000yqc.googlegroups.com> References: <8fbc2c4a-c347-43df-8830-3b4e86d95792@t13g2000yqt.googlegroups.com> <6085bece-97c6-4400-9571-7cd288da1578@g31g2000yqc.googlegroups.com> Message-ID: <50697b2c0908262306t223cc991o5564bac623d9697a@mail.gmail.com> On Wed, Aug 26, 2009 at 8:40 PM, Ryan McGuire wrote: > On Aug 26, 11:04?pm, Philip Semanchuk wrote: >> Try using "rb" instead of "r" for the mode in the call to open(). >> >> HTH >> Philip > > That does indeed fix the problem, thanks! Still seems like the docs > are wrong though. Yeah, the need to specify "b" does seem rather incongruous: codecs.open(filename, mode[, encoding[, errors[, buffering]]]) [...] Note: Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8-bit values. This means that no automatic conversion of b'\n' is done on reading and writing. File a bug perhaps?: http://bugs.python.org/ Cheers, Chris -- http://blog.rebertia.com From clp2 at rebertia.com Thu Aug 27 02:11:22 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 26 Aug 2009 23:11:22 -0700 Subject: codecs.open on Win32 -- converting my newlines to CR+LF In-Reply-To: <50697b2c0908262306t223cc991o5564bac623d9697a@mail.gmail.com> References: <8fbc2c4a-c347-43df-8830-3b4e86d95792@t13g2000yqt.googlegroups.com> <6085bece-97c6-4400-9571-7cd288da1578@g31g2000yqc.googlegroups.com> <50697b2c0908262306t223cc991o5564bac623d9697a@mail.gmail.com> Message-ID: <50697b2c0908262311w55faa8afh91eef611ca99f6b5@mail.gmail.com> On Wed, Aug 26, 2009 at 11:06 PM, Chris Rebert wrote: > On Wed, Aug 26, 2009 at 8:40 PM, Ryan McGuire wrote: >> On Aug 26, 11:04?pm, Philip Semanchuk wrote: >>> Try using "rb" instead of "r" for the mode in the call to open(). >>> >>> HTH >>> Philip >> >> That does indeed fix the problem, thanks! Still seems like the docs >> are wrong though. > > Yeah, the need to specify "b" does seem rather incongruous: > > codecs.open(filename, mode[, encoding[, errors[, buffering]]]) > ? ?[...] > ? ?Note: Files are always opened in binary mode, even if no binary > mode was specified. This is done to avoid data loss due to encodings > using 8-bit values. This means that no automatic conversion of b'\n' > is done on reading and writing. > > File a bug perhaps?: http://bugs.python.org/ Ah, I see you already did: http://bugs.python.org/issue6788 - Chris From hendrik at microcorp.co.za Thu Aug 27 02:38:29 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 08:38:29 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <200908270838.29673.hendrik@microcorp.co.za> On Wednesday 26 August 2009 17:14:27 kj wrote: > As I described at length in another reply, the function in question > is not intended to be "callable outside the class". And yes, I think this might go to nub of your problem - It might help you to think as follows: A Python class, even after it has been executed, does not really exist except as a kind of template or pattern - it is mostly useless until an instance of the class is made by calling it with whatever it needs to set up the instance. And once you have an instance, you can do stuff with that particular instance. Before that time, the class is mostly just a promise of things to come. > recursive functions in Python *are* restricted in ways that > non-recursive functions aren't. The examples I've posted prove > this point unambiguously. Yes and no - mostly no - your examples just illustrate the point I tried to make above. Pythons object model, and its classes, are different from what you are used to. A bare class is mostly useless without an instance, which is ultimately why accessing a function in a class from itself like you are doing, without reference to an instance, does not work - the function does not exist yet to a degree that it can be referenced. It is kind of subtle, and different from other languages. 8<------------- rant against the way things are ----------------------- Welcome to python, and the newsgroup, by the way. - Hendrik From ubershmekel at gmail.com Thu Aug 27 02:49:10 2009 From: ubershmekel at gmail.com (RunThePun) Date: Wed, 26 Aug 2009 23:49:10 -0700 (PDT) Subject: Overriding iadd for dictionary like objects References: Message-ID: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> On Aug 27, 6:58?am, Robert Kern wrote: > On 2009-08-26 20:00 PM, Jan Kaliszewski wrote: > > > > > > > 27-08-2009 o 00:48:33 Robert Kern wrote: > > >> On 2009-08-26 17:16 PM, RunThePun wrote: > >>> I'd like to build a database wrapper using DictMixin and allow items > >>> to be appended by my own code. The problem is += is always understood > >>> as setitem and getitem plainly. > > >>> d = MyDict() > >>> d['a'] = 1 > > >>> # this is the problem code that's I'd like to override. It's always > >>> setitem('a', getitem('a') + 3) > >>> d['a'] += 3 > >>> # i wanted to do something like my own 'appenditem' function which for > >>> example could be useful if getitem is an expensive operation which can > >>> be avoided. > > >>> I hope that was clear enough of a request, it's really late at night > >>> here... > > >> I'm sorry, this is just part of the syntax of Python. You cannot > >> override it. > > > Though > > d['a'] = 3 > > is equivalent to: > > d.__setitem__('a', 3) > > > The > > d['a'] += 3 > > *is not* equivalent to: > > d.__setitem__('a', d.__getitem__('a') + 3) > > *but is* equivalent to: > > d.__getitem__('a').__iadd__(3) > > > Then you can override __getitem__() of MyDict in such a way that it > > returns prepared (wrapped) object with overriden __iadd__() as you > > want to. > > You could, but then you will almost certainly run into problems using the > wrapped object in places that really expect the true object. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco Exactly my problem Robert. I'm actually going to be using this dict for storing and retrieving strings so wrapping str and replacing the iadd would cause alot of craziness. Anybody have any more ideas? I think python should/could havev a syntax for overriding this behaviour, i mean, obviously the complexity of supporting all operators with the getitem syntax could introduce alot of clutter. But maybe there's an elegant solution out there... ---RP From rylesny at gmail.com Thu Aug 27 02:56:49 2009 From: rylesny at gmail.com (ryles) Date: Wed, 26 Aug 2009 23:56:49 -0700 (PDT) Subject: Q: multiprocessing.Queue size limitations or bug... References: Message-ID: <9a338a3f-33a8-416c-af42-36f596c7cb71@r27g2000vbn.googlegroups.com> On Aug 26, 4:56?am, Michael Riedel wrote: > Sorry for being not more specific but I'm not absolutely certain whether > I encountered a bug or did anything wrong: > > The (stupid) code below results in a stall forever or not at 'p0.join()' > depending on the value of TROUBLE_MAKER. > > Any help, thoughts, comments? > > Thank you for your time. > > Michael > > # ---------------------------------------------------------------------- > > from multiprocessing import Process, Queue > > # bit vector size > BVS=8 > > # > TROUBLE_MAKER=12 ?# for greater values p0.join() is never satisfied... > > def evaluate(q, id, start=0, stop=2**BVS): > > ? ? cmin = {0: []} > > ? ? for mask0 in range(start, stop): > ? ? ? ? for mask1 in range(0, 2**BVS): > ? ? ? ? ? ? for mask2 in range(mask1, TROUBLE_MAKER): > ? ? ? ? ? ? ? ? cmin[0].append((mask0, mask1, mask2)) > > ? ? print 'process %d finished (dict layout: %d/%d)...' % (id, > len(cmin), len(cmin[0])) > ? ? q.put(cmin.copy()) > ? ? q.close() > > if __name__ == '__main__': > > ? ? q0 = Queue() > ? ? q1 = Queue() > ? ? q2 = Queue() > ? ? q3 = Queue() > > ? ? part = 2**BVS/4 > ? ? p0 = Process(target=evaluate, args=(q0, 0, 0*part, 1*part), > name='worker_0') > ? ? p1 = Process(target=evaluate, args=(q1, 1, 1*part, 2*part), > name='worker_1') > ? ? p2 = Process(target=evaluate, args=(q2, 2, 2*part, 3*part), > name='worker_2') > ? ? p3 = Process(target=evaluate, args=(q3, 3, 3*part, 4*part), > name='worker_3') > ? ? p0.start() > ? ? print 'process 0 started...' > ? ? p1.start() > ? ? print 'process 1 started...' > ? ? p2.start() > ? ? print 'process 2 started...' > ? ? p3.start() > ? ? print 'process 3 started...' > ? ? # main process stalls at p0.join() for bigger TROUBLE_MAKER > ? ? p0.join() > ? ? p1.join() > ? ? p2.join() > ? ? p3.join() > ? ? res0 = q0.get() > ? ? res1 = q1.get() > ? ? res2 = q2.get() > ? ? res3 = q3.get() > ? ? print 'results fetched...' > > # ---------------------------------------------------------------------- > > -- There is a warning related to this in the documentation: http://docs.python.org/library/multiprocessing.html#pipes-and-queues Basically, you should reverse the order of the get() and join() calls. multiprocessing does a pretty nice job of abstracting away the low- level details of IPC, but there are still some gotchas. As you've noticed, your program will deadlock when there is a large enough amount of data being put into the queue. This is related to a hidden thread that exists inside each of your child processes. The thread is responsible for taking your queue items from an internal buffer and then writing them into a pipe that your parent process will read from when get() is called. The pipe mechanism is what allows the two processes to pass information, and is supported directly by the Operating System. However, the pipe has a limited capacity, and when it is full, the writer thread is stuck waiting for the reader to read enough from the pipe so that it can finish its write. The problem is that your parent process (reader) is not actually calling get() to drain the pipe. Instead it's stuck in join() waiting for the writer to complete. From hendrik at microcorp.co.za Thu Aug 27 03:09:21 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 09:09:21 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: <200908270909.21886.hendrik@microcorp.co.za> On Wednesday 26 August 2009 17:45:54 kj wrote: > In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano writes: > >Why are you defining a method without a self parameter? > > Because, as I've explained elsewhere, it is not a method: it's a > "helper" function, meant to be called only once, within the class > statement itself. If the sole purpose of the function is to be used to define what will become a constant, why do you not just calculate the constant on your calculator, or at the interactive prompt, and assign it to the attribute, and be done with it? Why waste run time recalculating every time the programme is called? > > Well, this is not strictly true, because the function is recursive, > so it will also call itself a few times. But still, all these > calls happen (loosely speaking) "within the class statement". Why *must* it be there? > > In fact the only reason to use a function for such initialization > work is when one needs recursion; otherwise there's no point in > defining a function that will only be invoked exactly once. Seems no point to me even when there is recursion - a number is a number is a number. If you know the arguments when you write it, and if the function is known at time of writing, storing a literal is the best solution. Conversely, if the arguments are not known at time of writing, then they should be passed at run time, when an instance is created, and assigned as part of the __init__ method. And the same is true if the function is not known at time of writing - then it must be passed to the constructor of the instance. Storm in a teacup. - Hendrik From frank at chagford.com Thu Aug 27 03:10:02 2009 From: frank at chagford.com (Frank Millman) Date: Thu, 27 Aug 2009 09:10:02 +0200 Subject: Move dictionary from instance to class level In-Reply-To: <4A955AA5.6000200@ieee.org> Message-ID: <20090827071016.E9A7F8A3D@ctb-mesg-1-1.saix.net> Dave Angel wrote: > Any time I see multiple lists like that which have to stay in > synch, I think code-smell. > I don't think it is that bad, but I agree there is always room for improvement. > Why not let the EVT's be passed as strings, and avoid the whole mapping > to integers and mapping back detail? And name the methods involved in a > way that you can directly translate the string to the method name? > There is some merit in this. At present I am writing the server and the client, and copy/paste the list of constants, so they are guaranteed to stay in sync. (Maybe I should import it instead - even more fool-proof [the fool being me, of course]). However, it may happen that I want to open it up to 3rd-party clients in the future, in which case I would have to publish some sort of API. It would make more sense to identify the messages by a meaningful name rather than an integer. And yes, I could then use 'getattr' to retrieve the corresponding method on the server side. > Barring that, make a single "structure" which lists the event > names and > method names in matched pairs, and derive whatever lists and > dictionaries you actually need from that one structure. And that > structure should be shared between client and server code, > perhaps as a > text file that they both parse. Or as a stream that's passed > from one > to the other during startup. That way, consistency between > them can be > regulated (with version string in the file, for example) > I'm not sure how that would work. On the client side, I need to respond to a 'button-clicked' event from the gui system by sending an EVT_BUTTON_CLICKED message to the server. In other words it is hard-coded into the client program. I don't know how that would work if I read in a list of message-types at startup. > DaveA > Thanks for the input - it is always good to have some fresh ideas. Frank From tjreedy at udel.edu Thu Aug 27 03:26:31 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Aug 2009 03:26:31 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: kj wrote: > I think I understand the answers well enough. What I *really* > don't understand is why this particular "feature" of Python (i.e. > that functions defined within a class statement are forbidden from > "seeing" other identifiers defined within the class statement) is > generally considered to be perfectly OK. IMO it's a bizarre, > inexplicable blindspot (which, among other things, gives rise to > a certain worry about what other similar craziness lurks under > Python's image of rationality). I have never seen even a half-hearted > justification, from a language design point of view, for why this > particular "feature" is worth having. Maybe some day the BDFL will > deign to give one. I attempted to give an explanation in my previous post. From frank at chagford.com Thu Aug 27 03:31:01 2009 From: frank at chagford.com (Frank Millman) Date: Thu, 27 Aug 2009 09:31:01 +0200 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org Message-ID: <20090827073102.293C91DF2@ctb-mesg8.saix.net> Hi all I mentioned yesterday that I had a problem sending a message to the newsgroup via the Outlook Express news reader. Today I received an email from DaveA, which was sent to me via python-list at python.org. I tried simply replying to the email, to see if it behaved better than Outlook Express. I hit 'Reply to all', so it 'replied' to the sender and cc'ed to python-list at python.org. I have just checked in google-groups and my message does appear, in the correct thread, but not in its correct thread position. Is there a proper way to do this, or is it better to stick to a news reader like Outlook Express? Thanks Frank Millman P.S. I am sending this message via email to python-list at python.org - let's see what happens. From hendrik at microcorp.co.za Thu Aug 27 03:44:06 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 09:44:06 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a9595ca$0$300$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a9595ca$0$300$14726298@news.sunsite.dk> Message-ID: <200908270944.06268.hendrik@microcorp.co.za> On Wednesday 26 August 2009 22:06:01 Esben von Buchwald wrote: > > I don't really get it... > > I can see that I should put a t.after(...) around the function that does > the work, when calling it. That delays each call for the given period. I > just tried it out, the console keeps saying > ------------------------------------------------------------------------- > Traceback (most recent call last): > File "c:\resource\python25\python25.zip\sensorfw.py", line 499, in > data_cb > File "c:\resource\python25\python25.zip\sensorfw.py", line 160, in > custom_cb > File "e:\python\r3s_contextdata.py", line 79, in acc_filter > self.acc_callback() > File "e:\python\r3s_contextdata.py", line 85, in acc_callback > self.doCallback() > File "e:\python\r3s_contextdata.py", line 47, in doCallback > self.at.after(0.05,self.data_callback) > RuntimeError: Timer pending - cancel first > > ------------------------------------------------------------------------- > > It seems like i should cancel the current counting timer, when a new > call comes in - but how to determine when to cancel etc? Hmm - now I am really starting to fly by the seat of my pants - but it looks as if your problem is that your routine is basically being called faster than what it can do the processing. So what I would try is to define a global (you should really acquire a lock, but forget that for the moment) So lets call this thing running_calculation. Then you set this in the routine just before the after call, and reset it just before exiting the calculation routine, and if it is set when you get into the first routine, then you just exit, without doing the after. This should have the effect of skipping some calls, to make it all manageable. Then you should (hopefully) not have the duplication that it looks to me like you are now having. Bye the way, make the time short - like 1 - it could also be that the time is now so long before you start calculating, that you do not have a snowball's hope in hell to be finished before the next value comes in. - Hendrik From hendrik at microcorp.co.za Thu Aug 27 03:47:05 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 09:47:05 +0200 Subject: Python for professsional Windows GUI apps? In-Reply-To: References: Message-ID: <200908270947.05723.hendrik@microcorp.co.za> On Wednesday 26 August 2009 22:47:23 David C Ullrich wrote: > That's great. But do you know of anything I can use as a > visual form design tool in wxPython? Boa Constructor - Hendrik From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 04:07:46 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 10:07:46 +0200 Subject: Need help with Python scoping rules In-Reply-To: <2a7gm6-9h.ln1@satorlaser.homedns.org> References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> <2a7gm6-9h.ln1@satorlaser.homedns.org> Message-ID: <4a963ec1$0$20889$426a74cc@news.free.fr> Ulrich Eckhardt a ?crit : (snip) > Now, what actually causes problems is that 'fact_rec' is not universally > accessible until class 'Demo' is fully defined, but you need this in order > to fully define it. Here comes a drawback of the dynamic nature of Python, > that the declaration phase (compiling) is not separate from the execution. It is. You can manually compile a module, remove the source .py and still import (or execute) the compiled .pyc. The "problem" here is not with compilation, but with the fact that 'class' (and 'def') statements are *executable* statements. IOW, the class statement is executed when encountered, that is, usually (most class statements being top-level statements), when the module is first loaded. > I fully agree that this case is rather vexing to my (and obviously your) > biased brain. I wouldn't call this a bug before fully understanding why > e.g. you can not access a class before its definition is finished. Nor why it's a GoodThing(tm) for quite a lot of use case - while the OP's problem is in the splitting-hairs category - only a problem if yo?u insist in imposing your views on the language instead of learning how to use it. > Suggestion: someone mentioned that you should make the function a normal > function. (snip) Someone (Diez Roggisch IIRC) also mentionned a simple solution that mostly fulfills the OP's desires: use a nested function. From somebody at somewhere.com Thu Aug 27 04:10:46 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Thu, 27 Aug 2009 09:10:46 +0100 Subject: Need help with Python scoping rules References: <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: kj wrote: > Because, as I've explained elsewhere, it is not a method: it's a > "helper" function, meant to be called only once, within the class > statement itself. So why didn't you delete it after you were done with it? Class Demo(object): def fact(x): ... _classvar = fact(5) del fact() -- Stephen Fairchild From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 04:18:59 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 10:18:59 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> <2a7gm6-9h.ln1@satorlaser.homedns.org> Message-ID: <4a964162$0$7806$426a74cc@news.free.fr> kj a ?crit : (snip) > >> I fully agree that this case is rather vexing to my (and obviously your) >> biased brain. I wouldn't call this a bug before fully understanding why >> e.g. you can not access a class before its definition is finished. > > I understand this, what I don't understand is why do it this way. > I've been trying to understand this particular design point for > *literally* years. It's quitye simple: 'class' is an executable statement that creates a class object (yes, all this happens at runtime) and bind it in the current namespace. So until the class statement is executed, the class object doesn't exist and it's name is not bound. Now if you don't understand why it's a GoodThing(tm) that all this happens at runtime, have a look at metaclasses, how they are used in most major Python frameworks, and how this allows to vastly reduce the amount of needed boring and erreor-prone boilerplate code one cand find elsewhere. >> I think >> someone mentioned one or two PEPs, which are the design documents that >> explain Python including the rationale, I'd use that as a starting point. > > I'm reading PEP 227 now, suggested by Steven D'Aprano. In it I > find statements like the following alert: > > (Note: If a region is contained within a class definition, the > name bindings that occur in the class block are not visible to > enclosed functions.) > > I've seen this before, but never an explanation for why having this > restriction. You should re-read Carl Bank's answers more carefully then. > It's just one of life's mysteries. (Incidentally, > the fact that the author of PEP 227 felt it necessary to add that > parenthetical remark suggests that the expectation it warns against > is not so crazy after all.) It's not so crazy for someone coming from a more static language. Python's object model is indeed a bit peculiar, and it can take some times getting the big picture, but be sure it has been carefully designed, and is incredibly powerfull once you start understanding the whole thing. > But I'm still not done with PEP 227. Maybe I'll see the light by > the time I'm done. My 2 cents : learn about metaclasses, attributes lookup rules, and the descriptor protocol (and some practical applications of these features). Then you might decide that the few resulting restrictions are really worth the price. From david.westlund at hp.com Thu Aug 27 04:19:26 2009 From: david.westlund at hp.com (Westlund, David) Date: Thu, 27 Aug 2009 08:19:26 +0000 Subject: Python on HP-UX Message-ID: <2A1DB3DEDE43A7479FB4692CB732771A3CB9E9BF44@GVW1086EXB.americas.hpqcorp.net> Hi I'm trying to compile Python on an HP-UX v11.23 running on an Itanium. I have tried with both gcc and cc, and python versions 2.5.4, 2.6.2 as well as an SVN checkout. In all cases, alloca.h needs to be included. On most systems I'm guessing it is already included from stdlib.h, but not on HP-UX. The following code in the right header file solves that problem: #ifdef __hpux #include #endif My problem is that ctypes keeps seg faulting: ./python -v Lib/ctypes/test/runtests.py [...] # Python-2.5.4/Lib/encodings/ascii.pyc matches /Python-2.5.4/Lib/encodings/ascii.py import encodings.ascii # precompiled from Python-2.5.4/Lib/encodings/ascii.pyc ....Segmentation fault (core dumped) ./python -v ./Lib/ctypes/test/runtests.py [...] # Python-2.6.2/Lib/ctypes/test/test_numbers.pyc matches Python-2.6.2/Lib/ctypes/test/test_numbers.py import ctypes.test.test_numbers # precompiled from Python-2.6.2/Lib/ctypes/test/test_numbers.pyc ....Segmentation fault Have people managed to get a working ctypes installation on HP-UX? BR, David Westlund From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 04:35:51 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 10:35:51 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> Message-ID: <4a964556$0$748$426a74cc@news.free.fr> kj a ?crit : > In <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71 at j21g2000yqe.googlegroups.com> Carl Banks writes: > >> Yeah, it's a little surprising that you can't access class scope from >> a function, but that has nothing to do with encapsulation. > > It does: it thwarts encapsulation. The helper function in my > example is one that clearly rightfully belongs nowhere else than > the class itself, i.e. encapsulated within the class. I don't see what's wrong with having this function at the top-level. Sorry to have to say it this way, but IMHO you're border on cargo-cult thinking here. Python is an all-object language (ie : everything is an object, including functions, classes and modules), but it's by no mean 'pure-object', and module level functions are perfectly ok (and quite often the right thing). Now if you really want to "encapsulate" the function and the class together, you do have simple and and working solutions : using a nested recursive function (as explained by Diez), or nesting both the class and function in a factory function, ie: def Demo(): def fact(n): if n < 2: return 1 else: return n * fact(n - 1) class Demo(object): _classvar = fact(5) return Demo Demo = Demo() But anyway: this is really a WTF. Python's notion of encapsulation is very weak (by design), and you're really wasting time trying to fight the language instead of learning it. Just put that f... helper function at the top level (prefixing it's name with a '_' to mark it as implementation detail), and move on to something else !-) > It is only > this silly prohibition against recursive functions in a class > statement that forces one to put it outside the class statement. The "prohibition" only happens for recursive functions defined *and* called in the class statement. And once you get the big picture, it's certainly not "silly". From davea at ieee.org Thu Aug 27 04:36:34 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 27 Aug 2009 04:36:34 -0400 Subject: Move dictionary from instance to class level In-Reply-To: <20090827071016.E9A7F8A3D@ctb-mesg-1-1.saix.net> References: <20090827071016.E9A7F8A3D@ctb-mesg-1-1.saix.net> Message-ID: <4A964592.30100@ieee.org> Frank Millman wrote: > Dave Angel wrote: > > >> Any time I see multiple lists like that which have to stay in >> synch, I think code-smell. >> >> > > I don't think it is that bad, but I agree there is always room for > improvement. > > >> Why not let the EVT's be passed as strings, and avoid the whole mapping >> to integers and mapping back detail? And name the methods involved in a >> way that you can directly translate the string to the method name? >> >> > > There is some merit in this. At present I am writing the server and the > client, and copy/paste the list of constants, so they are guaranteed to stay > in sync. (Maybe I should import it instead - even more fool-proof [the fool > being me, of course]). > > However, it may happen that I want to open it up to 3rd-party clients in the > future, in which case I would have to publish some sort of API. It would > make more sense to identify the messages by a meaningful name rather than an > integer. > > And yes, I could then use 'getattr' to retrieve the corresponding method on > the server side. > > I've built such pairs of programs (not in Python), and studied the tradeoffs of various methods of coupling. Cut & Paste is probably the worst way to do it. Manual error is easy to creep in, where one copy is updated, and somebody neglects to update the other. It's especially bad if the item order matters, as it does for enums and for your xlist() example. Shared code works okay (have a module that both ends import). But it assumes both ends are built and ship and install on a consistent basis. Not too hard when it's a single product on a single machine. But if the two ends are on separate machines, especially separated by the Internet, you have to deal with version consistency problems. If there's a time shift as well (file format), then you're stuck at that level. Check the version, and either insist on exact match, or have a way to adapt to whichever end reports the earlier version. Make no mistake, there will be new versions, and you'll have to deal with it. Shared data is about the same, but can sometimes be more flexibly interpreted. It also can have the advantage of being able to have multiple simultaneous versions on the same machine. For the Internet case, picture a server that has to be able to serve several clients, each running different versions. And it's tougher for corruption (accidental or malicious) to do serious damage. I wouldn't want to do an import over the Internet live connection. Best is if the necessary data is passed between the two ends during initialization, and both ends know how to make that data describe the protocol they'll use. That can work as long as there's a notion of a session, and preferably if the session is two-way. In the case of file formats, it means you have this data in the header of the file. Sometimes for bandwidth reasons, you just want to transmit a version string, and not the entire table implied by that string. Just realize the increased risks involved. Probably the easiest way to stay in synch is if each message is self-describing. To me that screams "text" for the id's. It makes the message a bit larger, and you have to decide if it's worth it. The overhead could very well be lost in the noise of packeting, in any tcp/ip protocol. Note that all these have very gray boundaries. And that underneath it all, it's all just data. >> Barring that, make a single "structure" which lists the event >> names and >> method names in matched pairs, and derive whatever lists and >> dictionaries you actually need from that one structure. And that >> structure should be shared between client and server code, >> perhaps as a >> text file that they both parse. Or as a stream that's passed >> from one >> to the other during startup. That way, consistency between >> them can be >> regulated (with version string in the file, for example) >> >> > > I'm not sure how that would work. On the client side, I need to respond to a > 'button-clicked' event from the gui system by sending an EVT_BUTTON_CLICKED > message to the server. In other words it is hard-coded into the client > program. I don't know how that would work if I read in a list of > message-types at startup. > > > Show me a sample client event handler, and maybe I can suggest how to encode it. For example in wxPython, events are encoded with an event object. You could have the event send the object's type-string as an event ID. No lookup at all. And in fact, one event handler then might handle several of the events for a given widget, or even for multiple ones. I guess it's not that simple, since you frequently have to pass other information, such as the state of the Ctrl-key, or the mouse position on the screen, which is not directly encoded in the event type. >> DaveA >> >> > > Thanks for the input - it is always good to have some fresh ideas. > > Frank > > > From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 04:49:24 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 10:49:24 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <4a964883$0$18484$426a74cc@news.free.fr> kj a ?crit : > In "Martin P. Hellwig" writes: > >> kj wrote: >> >>> First, one of the goals of OO is encapsulation, not only at the >>> level of instances, but also at the level of classes. >> Who says? > > Python itself: it already offers a limited form of class encapsulation > (e.g. class variables). "class variables" - which FWIW include the "methods" - are just attributes of the class *object* (reminder : Python's classes and functions *are* objects too). Any name bound at the top level of the class statement scope becomes an attribute of the class object. IOW, this "limited form of class encapsulation" is just the ordinary "form of encapsulation" you'll get with Python objects. > It would be nice if it went all the way > and gave classes their own bona fide scope. (But I hasten to add: > I *still* don't understand the Python scope model, I think that what you should first understand are Python's execution and object models. >> Anyway, you could be right (I am not capable to judge it) and Python >> should change on this issue but from what I gathered, Pythons OO is >> inspired by the following: >> - Don't repeat yourself >> - Containing code into logical units makes it easier to understand and >> maintain. > > ...except, apparently, when that code is a recursive function, in > which case one's out of luck. I wrote quite a few recursive functions in Python and never had any problem. >>> Second, my example shows that Python puts some peculiar restrictions >>> on recursion. It's not a restriction on recursion, it's a scoping rule that apply to any other name. You can't access the class statement's scope from within a function, period. >>> Recursion! One of the central concepts in the theory >>> of functions! >> >> It is also one of the best ways to shoot yourself in the foot... > > If recursion is so evil, and Python so intent in saving us from > shooting ourselves in the foot, why does it allow recursion at all? Recursion is not evil, and Python doesn't try to prevent anyone from doing stupid things anyway. FWIW, do you know that you can add / replace / remove attributes (including methods) at runtime, both on a per-instance or per-class basis ? And even dynamically change the class of an object ?-) From jldunn2000 at googlemail.com Thu Aug 27 04:56:22 2009 From: jldunn2000 at googlemail.com (loial) Date: Thu, 27 Aug 2009 01:56:22 -0700 (PDT) Subject: Parse xml file Message-ID: Is there a quick way to retrieve data from an xml file in python 2.4, rather than read the whole file? From frank at chagford.com Thu Aug 27 04:56:47 2009 From: frank at chagford.com (Frank Millman) Date: Thu, 27 Aug 2009 10:56:47 +0200 Subject: Move dictionary from instance to class level In-Reply-To: <4A964592.30100@ieee.org> Message-ID: <20090827085652.E1339AE22@ctb-mesg-1-3.saix.net> Dave Angel wrote: > > Show me a sample client event handler, and maybe I can suggest how to > encode it. For example in wxPython, events are encoded with > an event > object. You could have the event send the object's type-string as an > event ID. No lookup at all. And in fact, one event handler > then might > handle several of the events for a given widget, or even for multiple > ones. I guess it's not that simple, since you frequently > have to pass > other information, such as the state of the Ctrl-key, or the mouse > position on the screen, which is not directly encoded in the > event type. That is definitely *not* what I want to do. I want to make the server as generic as possible, so that it can handle any type of client, hopefully even including a browser eventually. Therefore the server has no knowledge of wxPython event types. I have abstracted all the event types I am interested in (the list is fairly stable now). My protocol requires that the client maps a specific gui event type to a message identifier, and the server maps the message identifier to a method that handles the message. Hope that makes sense. Frank From davea at ieee.org Thu Aug 27 05:04:59 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 27 Aug 2009 05:04:59 -0400 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <20090827073102.293C91DF2@ctb-mesg8.saix.net> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> Message-ID: <4A964C3B.8090206@ieee.org> Frank Millman wrote: > Hi all > > I mentioned yesterday that I had a problem sending a message to the > newsgroup via the Outlook Express news reader. > > Today I received an email from DaveA, which was sent to me via > python-list at python.org. > > I tried simply replying to the email, to see if it behaved better than > Outlook Express. I hit 'Reply to all', so it 'replied' to the sender and > cc'ed to python-list at python.org. > > I have just checked in google-groups and my message does appear, in the > correct thread, but not in its correct thread position. > > Is there a proper way to do this, or is it better to stick to a news reader > like Outlook Express? > > Thanks > > Frank Millman > > P.S. I am sending this message via email to python-list at python.org - let's > see what happens. > > > I use Thunderbird, and treat the list as ordinary mail. I use reply-all, and it seems to do the right thing. Or at least if I'm breaking threads, nobody has pointed it out to me yet. I'm not sure how the list-server decides what thread a particular message belongs to. It's more than just the subject line, since when people change the subject, it stays in the same thread. I'm guessing it's somewhere in the boilerplate that's built by a normal mail program when it builds a reply message. And since I don't see threads this way, I wouldn't know if I broke things. I'd love to see an FAQ on how to handle these python.org mailing lists, with recommendations on settings to use both when you sign up for the list, and within various mail applications. For example, I see a single message containing typically around 10 attachments. I do the reply-all to one of these attachments, and it handles the message body okay, the To/CC fields okay, usually adds an extra RE: on the subject (so it becomes RE: RE: subject). But it defaults to the wrong From: address, so I have to change that by hand. I don't have that problem if I reply directly to a message, say from my in-box. The FAQ could also cover conventions and other techniques, such as whether to use html or plain-text for messages, how to use ** to mark a word as bold, top-posting suggestions.... DaveA From balamurugan.sekar at gmail.com Thu Aug 27 05:10:55 2009 From: balamurugan.sekar at gmail.com (Balamurugan S) Date: Thu, 27 Aug 2009 14:40:55 +0530 Subject: Parse xml file In-Reply-To: References: Message-ID: On Thu, Aug 27, 2009 at 2:26 PM, loial wrote: > Is there a quick way to retrieve data from an xml file in python 2.4, > rather than read the whole file? Universal Feed parser can do the job for you. This can be imported and used in your python programs. For more information, http://www.feedparser.org/ -- Regards, S.Balamurugan Free the code, Free the User From steve at REMOVE-THIS-cybersource.com.au Thu Aug 27 05:14:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 09:14:41 GMT Subject: Need help with Python scoping rules References: Message-ID: <02a63e7d$0$15633$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 08:38:29 +0200, Hendrik van Rooyen wrote: > On Wednesday 26 August 2009 17:14:27 kj wrote: > >> As I described at length in another reply, the function in question is >> not intended to be "callable outside the class". And yes, > > I think this might go to nub of your problem - It might help you to > think as follows: > > A Python class, even after it has been executed, does not really exist > except as a kind of template or pattern - it is mostly useless until an > instance of the class is made by calling it with whatever it needs to > set up the instance. And once you have an instance, you can do stuff > with that particular instance. Before that time, the class is mostly > just a promise of things to come. Oh my! I couldn't disagree more strongly! I think the above is totally incorrect. Classes and types are first class objects, you can treat them like anything else in Python. In fact, classes themselves are instances of type, so you can say: >>> class C(object): # must inherit from object ... pass ... >>> issubclass(C, object) True >>> isinstance(C, type) True Classes are themselves instances of their metaclass. By default, classes have a metaclass of type, but you can easily change that. Metaclass programming is advanced but very powerful. Because classes are themselves objects, you can (with a bit of metaclass jiggery-pokery) make them do all sorts of interesting things. For instance, huge amounts of effort are often put into creating a Singleton class, a class that has a single instance. Well, okay... but why not just use the class object itself, instead of an instance? There's already one of those, and you can't (easily) make a copy of it, and even if you did, it would be an independent class. Instead of this: singleton = SingletonClass(args) do_something_with(singleton) just do this: do_something_with(SingletonClass) Of course SingletonClass needs to be designed to work that way, which will probably need some metaclass magic. It would be interesting to see which requires less effort. When it comes to built-in classes (types), I often use the class object itself as an object. E.g. I might do something like this: def convert(seq): t = type(seq) # remember the original type result = process(seq) # always produces a list if t is list: return result # don't bother making a copy of the result elif t is str or t is unicode: empty = t() return empty.join(result) else: return t(result) # return the original type >> recursive functions in Python *are* restricted in ways that >> non-recursive functions aren't. The examples I've posted prove this >> point unambiguously. > > Yes and no - mostly no - your examples just illustrate the point I > tried to make above. Completely no. You may have missed the examples I've given, but the problems the Original Poster were having had nothing to do with recursion. > Pythons object model, and its classes, are different from what you are > used to. A bare class is mostly useless without an instance, which is > ultimately why accessing a function in a class from itself like you are > doing, without reference to an instance, does not work - the function > does not exist yet to a degree that it can be referenced. That is incorrect. What's going on is more subtle. >>> class Demo: ... def function(x): ... print "Calling function with argument %s" % x ... function(None) ... function(1) ... function(function) ... Calling function with argument None Calling function with argument 1 Calling function with argument >>> Demo -- Steven From davea at ieee.org Thu Aug 27 05:24:14 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 27 Aug 2009 05:24:14 -0400 Subject: Move dictionary from instance to class level In-Reply-To: <20090827085652.E1339AE22@ctb-mesg-1-3.saix.net> References: <20090827085652.E1339AE22@ctb-mesg-1-3.saix.net> Message-ID: <4A9650BE.9030909@ieee.org> Frank Millman wrote: > Dave Angel wrote: > >> Show me a sample client event handler, and maybe I can suggest how to >> encode it. For example in wxPython, events are encoded with >> an event >> object. You could have the event send the object's type-string as an >> event ID. No lookup at all. And in fact, one event handler >> then might >> handle several of the events for a given widget, or even for multiple >> ones. I guess it's not that simple, since you frequently >> have to pass >> other information, such as the state of the Ctrl-key, or the mouse >> position on the screen, which is not directly encoded in the >> event type. >> > > That is definitely *not* what I want to do. > > I want to make the server as generic as possible, so that it can handle any > type of client, hopefully even including a browser eventually. Therefore the > server has no knowledge of wxPython event types. > > I have abstracted all the event types I am interested in (the list is fairly > stable now). My protocol requires that the client maps a specific gui event > type to a message identifier, and the server maps the message identifier to > a method that handles the message. > > Hope that makes sense. > > Frank > > > Yes, it makes sense. Sorry for heading down that particular dead-end. But the more I think about it, the more likely I think it is that you'll be adding new message types, even if they're just variants of ones already defined. So it might behoove you to have a shared "data structure" that describes the whole message, not just equates a name to an integer. Or consider pickling. I don't know the tradeoffs, but the idea is that an object is constructed at the other end that has all the same data members as the object you had at this end. Perhaps with a flexible enough class definition, you could represent all or at least several of your messages with the same object. I am curious about your topology. You're sending events from the client (which presumably has a mouse and keyboard) to a server. But what does the server do with those? Does it have its own screen, or what? DaveA From steve at REMOVE-THIS-cybersource.com.au Thu Aug 27 05:31:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 09:31:41 GMT Subject: Need help with Python scoping rules References: <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: <02a6427a$0$15633$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 09:09:21 +0200, Hendrik van Rooyen wrote: > On Wednesday 26 August 2009 17:45:54 kj wrote: >> In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano > writes: > >> >Why are you defining a method without a self parameter? >> >> Because, as I've explained elsewhere, it is not a method: it's a >> "helper" function, meant to be called only once, within the class >> statement itself. > > If the sole purpose of the function is to be used to define what will > become a constant, why do you not just calculate the constant on your > calculator, or at the interactive prompt, and assign it to the > attribute, and be done with it? > > Why waste run time recalculating every time the programme is called? What you are calculating might actually be quite complicated to enter as a literal. You might have something like: class C(object): TABLE = [] for i in xrange(100): row = [] for j in xrange(100): row.append((i**3 + 2*i**2 - i*j + 7*j**2 + 9*i*j**2 - j)/3) TABLE.append(row) It's a little hard to type out C.TABLE as a literal. And even if you could, which would you rather see if you were debugging this class? The above, or: class C(object): TABLE = [ [0.0, 2.0, 8.6666666666666661, 20.0, 36.0, ... ], [1.0, 5.666666666666667, 21.0, 47.0, 83.666666666666671, ...], [5.333333333333333, 12.666666666666666, 36.666666666666664, ...], ... [... , 3143161.0, 3201497.6666666665, 3260433.0] ] For obvious reasons I haven't typed the whole thing out! And imagine trying to check it for typos! Clearly this is a made-up example, but the principle is sound. If Python can calculate values for you, why not let it do so? It is easier for you, easier to check that you've calculated them correctly, easier to debug and read, it makes the algorithm clearer (fewer "magic constants"). Yes, there is a run-time cost, but you only pay it once, when you import the module, and it's likely to be not that much more expensive than parsing the literals anyway. Of course, for something as big and complicated as the above table, I'd almost certainly put the code to calculate it in a function outside of the class, but that's a matter of style, and it will work to put it inside the class. -- Steven From tjreedy at udel.edu Thu Aug 27 05:47:50 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Aug 2009 05:47:50 -0400 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <4A964C3B.8090206@ieee.org> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: Dave Angel wrote: > Frank Millman wrote: > I use Thunderbird, and treat the list as ordinary mail. I use > reply-all, and it seems to do the right thing. Or at least if I'm > breaking threads, nobody has pointed it out to me yet. reply-all may send duplicate messages to the author. Not sure of this list. I use Thunderbird and access python-list as a newsgroup via news.gmane.org as gmane.comp.python.general. About 200 other python mailing lists are accessible as g.c.p.xxx. The first time one posts to a particular mailint list, the post is held until one replies to a email sent to the 'from:' address. This cuts spam tremendously. Otherwise, no signup seems to be needed. tjr From catalinfest at gmail.com Thu Aug 27 06:20:31 2009 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Thu, 27 Aug 2009 03:20:31 -0700 (PDT) Subject: About diagram and python Message-ID: <030422b7-a4f8-4ea6-8708-4486da4cf595@w6g2000yqw.googlegroups.com> Hello! I see on my Diagram Editor software this : File -> Export... -> (on Export option is : PyDia Code Generation ... .py) What python is in this file ? How help me with python code ? Thank you ! From frank at chagford.com Thu Aug 27 06:21:10 2009 From: frank at chagford.com (Frank Millman) Date: Thu, 27 Aug 2009 12:21:10 +0200 Subject: Move dictionary from instance to class level In-Reply-To: <4A9650BE.9030909@ieee.org> Message-ID: <20090827102111.ABC3B1F93@ctb-mesg4.saix.net> Dave Angel wrote: > > Frank Millman wrote: > > > > That is definitely *not* what I want to do. > > > > I want to make the server as generic as possible, so that > it can handle any > > type of client, hopefully even including a browser > eventually. Therefore the > > server has no knowledge of wxPython event types. > > > > I have abstracted all the event types I am interested in > (the list is fairly > > stable now). My protocol requires that the client maps a > specific gui event > > type to a message identifier, and the server maps the > message identifier to > > a method that handles the message. > > > > Hope that makes sense. > > > > Frank > > > > > > > Yes, it makes sense. Sorry for heading down that particular > dead-end. > But the more I think about it, the more likely I think it is > that you'll > be adding new message types, even if they're just variants of ones > already defined. So it might behoove you to have a shared "data > structure" that describes the whole message, not just equates > a name to > an integer. > > Or consider pickling. I don't know the tradeoffs, but the > idea is that > an object is constructed at the other end that has all the same data > members as the object you had at this end. Perhaps with a flexible > enough class definition, you could represent all or at least > several of > your messages with the same object. > > I am curious about your topology. You're sending events from > the client > (which presumably has a mouse and keyboard) to a server. But > what does > the server do with those? Does it have its own screen, or what? > I'll try to explain. I am writing a fairly standard business/accounting application. (I am now adding Business Process Management to it, which is complicating matters, but that is another story.) Most of the gui stuff is basic forms processing - screens with static data, text fields for display and input of data, and buttons for signifying certain actions to be taken. My original attempt had both the gui and the business logic running on the client, with a connection to a database running on a server. It worked, but then I realised it was very insecure - it would be easy to hack the python code, bypass the business logic, and allow any update to the database. So my second attempt took all the business logic out of the client and put it onto the server. To execute a form, the server builds a form definition by creating objects to represent each of the widgets, creates a list of the components with sufficient information for the client to render them , then sends a json'd copy of the list to the client, which interprets it and displays the required form. The client informs the server of each event, and the server handles the event in much the same way as it did before when the business logic was on the client. For example, clicking a button triggers a response which could involve updating the database, displaying another window with additional data, etc, etc. Previously there would have been a method on the client designed to handle the response, and the method would be added to the button constructor so that it would be called when the button was clicked. Now the method is on the server, and is stored as an attribute of the button object on the server. When the user clicks the button, the message is passed up to the server (each widget has its own id, which is part of the message), the server is notified that the button was clicked, and it calls the associated method. There is a lot more to it than that, but hopefully that will give you an idea. If I ever get this to a workable state (it is taking far longer than I anticipated) I will release it as open source, and will then welcome as much feedback as possible. Frank From contact at xavierho.com Thu Aug 27 06:26:19 2009 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 Aug 2009 20:26:19 +1000 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <4A964C3B.8090206@ieee.org> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: <2d56febf0908270326p58adda54w306eb823710bb952@mail.gmail.com> On Thu, Aug 27, 2009 at 7:04 PM, Dave Angel wrote: > I'm not sure how the list-server decides what thread a particular message > belongs to. It's more than just the subject line, since when people change > the subject, it stays in the same thread. > I'm just using gmail because it saves me the trouble of reconfiguring the mail server every time I use a new computer (which I do at uni quite a lot). When someone changes the Subject with (was: XXX), it opens as a new "thread" on gmail. also, when someone puts "Re:" in the subject it also puts it on a new thread. The magical thing about gmail is that it seems to ingnore the first "Re:" on the subject line, and make them the same thread. I rarely have threading issues, but occasionally I do see "Re:" messages in a separate place, maybe once a month. I'd love to see an FAQ on how to handle these python.org mailing lists, with > recommendations on settings to use both when you sign up for the list, and > within various mail applications. Google found me these: http://www.gnu.org/software/mailman/faq.html http://www.gnu.org/software/mailman/docs.html Maybe they're helpful, since that's what the python-list uses. I've only scanned for a bit and it seems comprehensive. > For example, I see a single message containing typically around 10 > attachments. I do the reply-all to one of these attachments, and it handles > the message body okay, the To/CC fields okay, What do you mean 10 attachments? O_o. I know some people like to attach a company logo in their signature. (The Aussie DLF list people do that heaps. Although some people post a hand-written sig in the attachment ... I'm not sure how smart that is, but I've seen it done.) Where are you getting these "attachments"? I haven't tried reply-all yet. May give that a try next time and see what pops up in the To: address. > usually adds an extra RE: on the subject (so it becomes RE: RE: subject). Gmail doesn't do that. Yay! (Re: is dumb anyway, and you can't prepend Re: forever. Fwd: is reasonable.) > But it defaults to the wrong From: address, so I have to change that by > hand. I don't have that problem if I reply directly to a message, say from > my in-box. Weird. I have a different problem: the "To:" Address is usually the sender I'm replying to. It's really annoying, because I always have to hand-change the To: address to python-list. I've sent two messages onto the list mentioning about adding a "Reply-to" attribute by the mailing list server, which would fix this problem. To-date everyone has seemed to ignore me. =/ > The FAQ could also cover conventions and other techniques, such as whether > to use html or plain-text for messages, how to use ** to mark a word as > bold, top-posting suggestions.... I didn't know ** marks bold. Does __ mark underline? Those are cool things I never hear about. Thanks! On another tangent, I only found out the Python Wiki on the official site today (http://wiki.python.org/moin/) Does anyone actually use it, and what for? - Kind regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Thu Aug 27 06:46:57 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 10:46:57 GMT Subject: About diagram and python References: <030422b7-a4f8-4ea6-8708-4486da4cf595@w6g2000yqw.googlegroups.com> Message-ID: <02a6541d$0$15633$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 03:20:31 -0700, catalinfest at gmail.com wrote: > Hello! > I see on my Diagram Editor software this : File -> Export... -> (on > Export option is : PyDia Code Generation ... .py) > What python is in this file ? Why don't you look for yourself? Just open the file in a text editor and read it. -- Steven From greg at cosc.canterbury.ac.nz Thu Aug 27 06:50:41 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 27 Aug 2009 22:50:41 +1200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <7fn6n4F2m1582U1@mid.individual.net> kj wrote: > No, the fact() function here represents an internal "helper" > function. It is meant to be called only once to help initialize > a class variable that would be inconvenient to initialize otherwise; > this helper function is not meant to be called from outside the > class statement. That, to me, is an excellent indication that the function does *not* belong inside the class! The only things that belong inside the class are things that users of the class will need to use, or that instances of the class will need to do their job. Your helper function belongs outside the class, in the module where the class is defined. -- Greg From IDOL at il.ibm.com Thu Aug 27 06:57:49 2009 From: IDOL at il.ibm.com (Ido Levy) Date: Thu, 27 Aug 2009 13:57:49 +0300 Subject: pygtk - What is the best way to change the mouse pointer In-Reply-To: <4A959521.8020505@mrabarnett.plus.com> References: <4A959521.8020505@mrabarnett.plus.com> Message-ID: > From: > > MRAB > > To: > > python-list at python.org > > Date: > > 26/08/2009 11:04 PM > > Subject: > > Re: pygtk - What is the best way to change the mouse pointer > > Ido Levy wrote: > > Hello All, > > > > I am writing a dialog which one of its widget is a gtk.ComboBoxEntry ( > > let's assume widget in the example below is its instance ) > > When the user select one of the values from the gtk.ComboBoxEntry I need > > to run some calculations that takes a few seconds. > > In order to reflect calculation time to the user I want to switch the > > mouse pointer to an hour glass and back to arrow what it finish the > > calculation. > > > > I use the following code but it doesn't seems to work in a deterministic > > way. From time to time it skips the last line and keep the mouse pointer > > as an hour glass. > > > > watch = gtk.gdk.Cursor(gtk.gdk.WATCH) > > widget.window.set_cursor(watch) > > > > calculation code > > > > widget.window.set_cursor(None) > > > > I would appreciate your advice on the right way to implement this. > > > Could the calculation code be raising an exception? Try adding some > logging to see whether the last lien is actually being called. You could > also use a try...finally... block to ensure that the last line is > called: > > watch = gtk.gdk.Cursor(gtk.gdk.WATCH) > widget.window.set_cursor(watch) > try: > calculation code > finally: > widget.window.set_cursor(None) > Thank you for your input. I used logging and it seems that the last line is called. I also used try...finally... block but it didn't solve the issue. Then I have noticed that the line before the last one is widget.connect() I insert time.sleep() in between the lines and it seems to solve the issue. I assume it's not suppose to work this way but it can be considered as a workaround -------------- next part -------------- An HTML attachment was scrubbed... URL: From graham.dumpleton at gmail.com Thu Aug 27 07:01:05 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Thu, 27 Aug 2009 04:01:05 -0700 (PDT) Subject: Python on the Web References: <4a94ef42$0$27774$426a74cc@news.free.fr> <835a57b2-9a08-4f10-b2d4-78c96f22f3ee@n11g2000yqb.googlegroups.com> Message-ID: <77a1add8-3b36-4b69-b21e-a7a496c30205@l35g2000pra.googlegroups.com> On Aug 27, 1:02?pm, Phil wrote: > Thanks a lot for another response. I've never posted in groups like > this before but the results are amazing. > > I will definitely consider trying mod_wsgi when I get a chance. I like > the approach taken with it. It is unfortunate that I completely missed > all Apache related material because I was using lighttpd. Is there no > mod_wsgi for lighttpd? I guess I could always just Google that myself. There is no mod_wsgi for lighttpd and suggest there never will be. WSGI doesn't lend itself to working on top of an event driven system. Someone did get a mod_wsgi going on nginx, which is also event driven, but it has limitations due to possibility of blocking other traffic to web server. See: http://blog.dscpl.com.au/2009/05/blocking-requests-and-nginx-version-of.html Graham From jeanmichel at sequans.com Thu Aug 27 07:17:32 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 27 Aug 2009 13:17:32 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A966B4C.7030307@sequans.com> Ulrich Eckhardt wrote: > Ulrich Eckhardt wrote: > >> Jean-Michel Pichavant wrote: >> >>> class Color: >>> def __init__(self, r, g,b): >>> pass >>> BLACK = Color(0,0,0) >>> >>> It make sens from a design point of view to put BLACK in the Color >>> namespace. But I don't think it's possible with python. >>> >> class Color: >> ... >> >> setattrib(Color, "BLACK", Color(0,0,0)) >> > > Apart from it being "setattr" and not "setattrib", a simple > > Color.BLACK = Color(0,0,0) > > Obviously ... I'll remember that. JM From jeanmichel at sequans.com Thu Aug 27 07:45:00 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 27 Aug 2009 13:45:00 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A9671BC.7030600@sequans.com> kj wrote: > I think I understand the answers well enough. What I *really* > don't understand is why this particular "feature" of Python (i.e. > that functions defined within a class statement are forbidden from > "seeing" other identifiers defined within the class statement) is > generally considered to be perfectly OK. IMO it's a bizarre, > inexplicable blindspot (which, among other things, gives rise to > a certain worry about what other similar craziness lurks under > Python's image of rationality). I have never seen even a half-hearted > justification, from a language design point of view, for why this > particular "feature" is worth having. Maybe some day the BDFL will > deign to give one. > > kynn > I think I got your point. I guess many people may not be receptive to your question, cause guess what, we're all python fans :o) in foo.py: a = 5 b = a # works fine class A: c = 5 d = c # broken d = A.c # broken either def foo(self): e = 5 f = e #works fine We should all acknowledge that any newcomer to python will not expect such behavior. There are plenty of good answers to that thread explaining why the fact that classes are not scopes is much better. Still this design fails at one point : insight. It may be solved by creating the class upon the "class" statement. If the class A object is created, then c is added as a property of that object, there's no problem accession one object property with A.c. JM From manu3d at gmail.com Thu Aug 27 08:03:07 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 27 Aug 2009 05:03:07 -0700 (PDT) Subject: List iterator thread safety References: Message-ID: <14e1469e-bcfe-4922-b135-3f0bd7e17a42@r42g2000yqj.googlegroups.com> On Aug 27, 2:01?am, a... at pythoncraft.com (Aahz) wrote: > Well, I'm not sure about exceptions, but you almost certainly won't get > the results you want. What I'd like in this context is to iterate through the items in the list without processing the same item twice and without skipping item that are in front of the current iterator position. Somehow I can't quite prove to myself if this is possible or not over multiple threads. I.e. a dictionary will throw an exception about the object changing size while iterating through it. A list doesn't, hence the question. Manu From no.email at please.post Thu Aug 27 08:09:44 2009 From: no.email at please.post (kj) Date: Thu, 27 Aug 2009 12:09:44 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: In Jean-Michel Pichavant writes: >kj wrote: >> I think I understand the answers well enough. What I *really* >> don't understand is why this particular "feature" of Python (i.e. >> that functions defined within a class statement are forbidden from >> "seeing" other identifiers defined within the class statement) is >> generally considered to be perfectly OK. IMO it's a bizarre, >> inexplicable blindspot (which, among other things, gives rise to >> a certain worry about what other similar craziness lurks under >> Python's image of rationality). I have never seen even a half-hearted >> justification, from a language design point of view, for why this >> particular "feature" is worth having. Maybe some day the BDFL will >> deign to give one. >> >> kynn >> >I think I got your point. >I guess many people may not be receptive to your question, cause guess >what, we're all python fans :o) >in foo.py: >a = 5 >b = a # works fine >class A: > c = 5 > d = c # broken > d = A.c # broken either > > def foo(self): > e = 5 > f = e #works fine >We should all acknowledge that any newcomer to python will not expect >such behavior. There are plenty of good answers to that thread >explaining why the fact that classes are not scopes is much better. >Still this design fails at one point : insight. >It may be solved by creating the class upon the "class" statement. If >the class A object is created, then c is added as a property of that >object, there's no problem accession one object property with A.c. Thanks! I was beginning to think I'd gone crazy. kynn From jvpic at free.fr Thu Aug 27 08:13:21 2009 From: jvpic at free.fr (jvpic) Date: Thu, 27 Aug 2009 14:13:21 +0200 Subject: Learning Python advanced features Message-ID: <4a967864$0$15193$426a74cc@news.free.fr> Hi, Learning Python, I understand the mechanism of : closure, __new__, descriptors, decorators and __metaclass__, but I interrogate myself on the interest of those technics ? May somebody explain me the interest ? Many thanks ! Jackes Bihan From steve at REMOVE-THIS-cybersource.com.au Thu Aug 27 08:17:15 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 12:17:15 GMT Subject: Need help with Python scoping rules References: Message-ID: <02a66947$0$15633$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 13:45:00 +0200, Jean-Michel Pichavant wrote: > in foo.py: > > a = 5 > b = a # works fine > > class A: > c = 5 > d = c # broken Incorrect. That works fine. >>> class A: ... c = 5 ... d = c # not actually broken ... >>> A.c 5 >>> A.d 5 The class is a scope, and inside the class scope, you can access local names. What you can't do is access the class scope from inside nested functions. -- Steven From no.email at please.post Thu Aug 27 08:20:13 2009 From: no.email at please.post (kj) Date: Thu, 27 Aug 2009 12:20:13 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: In Jean-Michel Pichavant writes: >in foo.py: >a = 5 >b = a # works fine > > def foo(self): > e = 5 > f = e #works fine >It may be solved by creating the class upon the "class" statement. If >the class A object is created, then c is added as a property of that >object, there's no problem accession one object property with A.c. I thought one could implement something like class A: c = 5 d = __thisclass__.c But apparently this is a *huge* deal. I'm not sure if the reason it is a huge deal is that it is technically difficult to implement, or that there is an implicit "lie" in having something (__thisclass__) standing for something else that doesn't yet exist (and the potential errors that may arise from this "lie" in sufficiently unfortunate code). Or maybe something else beyond my noobish ken altogether. kynn From no.email at please.post Thu Aug 27 08:21:38 2009 From: no.email at please.post (kj) Date: Thu, 27 Aug 2009 12:21:38 +0000 (UTC) Subject: Need help with Python scoping rules References: <02a54597$0$20629$c3e8da3@news.astraweb.com> <02a6427a$0$15633$c3e8da3@news.astraweb.com> Message-ID: In <02a6427a$0$15633$c3e8da3 at news.astraweb.com> Steven D'Aprano writes: >On Thu, 27 Aug 2009 09:09:21 +0200, Hendrik van Rooyen wrote: >> On Wednesday 26 August 2009 17:45:54 kj wrote: >>> In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano >> writes: >> >>> >Why are you defining a method without a self parameter? >>> >>> Because, as I've explained elsewhere, it is not a method: it's a >>> "helper" function, meant to be called only once, within the class >>> statement itself. >> >> If the sole purpose of the function is to be used to define what will >> become a constant, why do you not just calculate the constant on your >> calculator, or at the interactive prompt, and assign it to the >> attribute, and be done with it? >> >> Why waste run time recalculating every time the programme is called? >What you are calculating might actually be quite complicated to enter as >a literal. Thank you! kynn From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 08:25:36 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 14:25:36 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4a967b2f$0$19301$426a74cc@news.free.fr> Jean-Michel Pichavant a ?crit : > kj wrote: >> I think I understand the answers well enough. What I *really* >> don't understand is why this particular "feature" of Python (i.e. >> that functions defined within a class statement are forbidden from >> "seeing" other identifiers defined within the class statement) is >> generally considered to be perfectly OK. IMO it's a bizarre, >> inexplicable blindspot (which, among other things, gives rise to >> a certain worry about what other similar craziness lurks under >> Python's image of rationality). I have never seen even a half-hearted >> justification, from a language design point of view, for why this >> particular "feature" is worth having. Maybe some day the BDFL will >> deign to give one. >> >> kynn >> > > I think I got your point. > I guess many people may not be receptive to your question, cause guess > what, we're all python fans :o) > > in foo.py: > > a = 5 > b = a # works fine > > class A: > c = 5 > d = c # broken Err... Did you actually tried this ? >>> class A: ... c = 5 ... d = c ... >>> A.c 5 >>> A.d 5 >>> > d = A.c # broken either Not "broken" : the class doesn't yet exists, nor is it bound to global name 'A'. FWIW, *this* works (for some definitions of 'works') juts fine: >>> class Foo(object): ... c = 42 ... >>> A = Foo() >>> class A(object): ... d = A.c ... >>> A.d 42 > > We should all acknowledge that any newcomer to python will not expect > such behavior. Any newcomer to any language should aknowledge that her expectations based on previous experience with any other language should be kept aside or just plain abandoned, and start by learning the new language. The only thing one is entitled to expect when learning a new language is that the language's implementation follows the language specs. > There are plenty of good answers to that thread > explaining why the fact that classes are not scopes is much better. > Still this design fails at one point : insight. Oh, really ? > It may be solved by creating the class upon the "class" statement. If > the class A object is created, then c is added as a property of that > object, there's no problem accession one object property with A.c. Please, write a pep... From robin at reportlab.com Thu Aug 27 08:26:47 2009 From: robin at reportlab.com (Robin Becker) Date: Thu, 27 Aug 2009 13:26:47 +0100 Subject: ubuntu dist-packages In-Reply-To: References: Message-ID: <4A967B87.9040100@chamonix.reportlab.co.uk> Florian Diesch wrote: ......... > >>From /usr/lib/python2.6/site.py: > > ,---- > | For Debian and derivatives, this sys.path is augmented with directories > | for packages distributed within the distribution. Local addons go > | into /usr/local/lib/python/dist-packages, Debian addons > | install into /usr/{lib,share}/python/dist-packages. > | /usr/lib/python/site-packages is not used. > `---- the above is not present in my windows documentation (or indeed site.py) at all so it seems they just decided to change the name. Anyone trying to debug why their distutils or setuptools or whichever python packager is going wrong will have yet another detail to remember. In addition, as any one who has done such trivial changes will already know, they forgot to do it globally eg my 0.4.1.0 version of the "Debian Python Policy" document explicitly mentions site-packages. -- Robin Becker From robin at reportlab.com Thu Aug 27 08:26:47 2009 From: robin at reportlab.com (Robin Becker) Date: Thu, 27 Aug 2009 13:26:47 +0100 Subject: ubuntu dist-packages In-Reply-To: References: Message-ID: <4A967B87.9040100@chamonix.reportlab.co.uk> Florian Diesch wrote: ......... > >>From /usr/lib/python2.6/site.py: > > ,---- > | For Debian and derivatives, this sys.path is augmented with directories > | for packages distributed within the distribution. Local addons go > | into /usr/local/lib/python/dist-packages, Debian addons > | install into /usr/{lib,share}/python/dist-packages. > | /usr/lib/python/site-packages is not used. > `---- the above is not present in my windows documentation (or indeed site.py) at all so it seems they just decided to change the name. Anyone trying to debug why their distutils or setuptools or whichever python packager is going wrong will have yet another detail to remember. In addition, as any one who has done such trivial changes will already know, they forgot to do it globally eg my 0.4.1.0 version of the "Debian Python Policy" document explicitly mentions site-packages. -- Robin Becker From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 08:28:24 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 14:28:24 +0200 Subject: Learning Python advanced features In-Reply-To: <4a967864$0$15193$426a74cc@news.free.fr> References: <4a967864$0$15193$426a74cc@news.free.fr> Message-ID: <4a967bd6$0$19301$426a74cc@news.free.fr> jvpic a ?crit : > Hi, > > Learning Python, I understand the mechanism of : closure, __new__, > descriptors, decorators and __metaclass__, but I interrogate myself on > the interest of those technics ? > > May somebody explain me the interest ? Didn't like my answers on f.c.l.py ?-) From luismgz at gmail.com Thu Aug 27 08:31:30 2009 From: luismgz at gmail.com (Neuruss) Date: Thu, 27 Aug 2009 05:31:30 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <7f519c34-2d6e-4fff-9489-dae43c6b2df1@r42g2000yqj.googlegroups.com> Message-ID: <6b961048-782a-428c-9c0a-4fb17e87b57f@s13g2000yql.googlegroups.com> On 26 ago, 05:29, erikj wrote: > Hi, > > You could have a look at Camelot, to see if it fits > your needs :http://www.conceptive.be/projects/camelot/ > > it was developed with cross platform business apps in > mind. ?when developing Camelot, we tried to build it using > wxWidgets first (because of the licensing at that time), > but it turned out that developing with QT proved to be > much more straightforward. ?QT is documented very well > and you seldom encounter 'strange' issues that cost hours > of time to pinpoint and fix. > > the datagrid was developed to be able to handle millions > of database records without glitches and is flexible thanks > to QT's model-view-delegate framework. > > we do print barcodes with this app (even directly to > zebra printers) > > if you have questions regarding Camelot, please feel free > to post on our mailing list :http://groups.google.com/group/project-camelot > > Regards, > > Erik > > On Aug 24, 2:08?pm, Gilles Ganault wrote: > > > > > Hello > > > ? ? ? ? I was wondering if some people in this ng use Python and someGUI > > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > > applications, and if yes, what it's like, the pros and cons, etc. > > > I'm especially concerned about the lack of controls, the lack of > > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > > linked to how to update users' PC remotely when I build a new version > > using eg. Py2exe. > > > I need controls for business apps like access to databases, good data > > grid, printing reports (with or without barcodes), etc. > > > Thank you. Looks interesting, but I wonder if I can use Camelot without its ORM. I feel that ORMs make easy things easier, but complex things much harder... Can I use it with plain old sql? Luis From __peter__ at web.de Thu Aug 27 08:41:07 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Aug 2009 14:41:07 +0200 Subject: List iterator thread safety References: <14e1469e-bcfe-4922-b135-3f0bd7e17a42@r42g2000yqj.googlegroups.com> Message-ID: Emanuele D'Arrigo wrote: > On Aug 27, 2:01 am, a... at pythoncraft.com (Aahz) wrote: >> Well, I'm not sure about exceptions, but you almost certainly won't get >> the results you want. > > What I'd like in this context is to iterate through the items in the > list without processing the same item twice and without skipping item > that are in front of the current iterator position. Somehow I can't > quite prove to myself if this is possible or not over multiple > threads. I.e. a dictionary will throw an exception about the object > changing size while iterating through it. A list doesn't, hence the > question. This is not even possible in a single thread: >>> items = [1, 2, 3] >>> for i in items: ... print i ... if 1 in items: items.remove(1) ... 1 3 Basically a list iterator is just a list reference and an index into that list. No effort is made to keep track of added or removed items. Peter From dmhouse at gmail.com Thu Aug 27 08:41:08 2009 From: dmhouse at gmail.com (David House) Date: Thu, 27 Aug 2009 13:41:08 +0100 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: 2009/8/27 Terry Reedy : > reply-all may send duplicate messages to the author. Not sure of this list. I'm fairly sure Mailman deals with that. -- -David From darcy at druid.net Thu Aug 27 08:55:40 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 27 Aug 2009 08:55:40 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: <20090827085540.de12c38d.darcy@druid.net> On Thu, 27 Aug 2009 09:10:46 +0100 Stephen Fairchild wrote: > So why didn't you delete it after you were done with it? > > Class Demo(object): That should be "class". > _classvar = fact(5) > del fact() I suppose you mean "del fact". -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From contact at xavierho.com Thu Aug 27 08:59:51 2009 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 Aug 2009 22:59:51 +1000 Subject: List iterator thread safety In-Reply-To: References: Message-ID: <2d56febf0908270559h58809a2na75e382c6638e7ac@mail.gmail.com> On Tue, Aug 25, 2009 at 3:43 AM, Emanuele D'Arrigo wrote: > Let's say I have a list accessed by two threads, one removing list > items via "del myList[index]" statement the other iterating through > the list and printing out the items via "for item in myList:" > statement. I tried something similar to that before. Gave me an error. I *think* it was in compile-time, too, but I might be wrong. The message was something like that the list size cannot be changed. > Am I right to say this -won't- generate exceptions because > the list iterator is not concerned with the list changing in size > under its nose? It kind of concerns about the size, I think. If it just checked the "next" item, that would have been so awesome. > Or are there pitfalls I should be aware of? The pitfall is that I don't think it will work at all. At least I haven't succeeded in doing this in the past. If you make it work, be sure to share your thoughts =] Good luck, -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From manu3d at gmail.com Thu Aug 27 09:16:14 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 27 Aug 2009 06:16:14 -0700 (PDT) Subject: Does Class implements Interface? Message-ID: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> Greetings everybody, let's say I have a Class C and I'd like to verify if it implements Interface I. If I is available to me as a class object I can use issubclass(C, I) and I can at least verify that I is a superclass of C. There are a couple of issues with this approach however: 1) C might override not just I's methods code but also I's methods signatures, effectively changing the interface. 2) What if I is -not- available to me as the superclass of C but as a description of the interface, i.e. as an IDL(*) file? Are there resources such as tools, recipes, documents or strategies that could help me deal with these issues? I've already looked into the ABC module and the zope.interface. I'm just fishing for more things to look at. Manu (*) http://en.wikipedia.org/wiki/Interface_description_language From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 09:21:33 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 15:21:33 +0200 Subject: Python on the Web In-Reply-To: References: <4a94ef42$0$27774$426a74cc@news.free.fr> Message-ID: <4a96884b$0$22855$426a74cc@news.free.fr> Phil a ?crit : (snip) > However, 99.9% of the discussion I see with Python on > the web is around FCGI. May I suggest you spend some time reading django-users and django-dev on google groups ? (and that's only *one* of the way-too-many Python web frameworks). From pavlovevidence at gmail.com Thu Aug 27 09:26:04 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 27 Aug 2009 06:26:04 -0700 (PDT) Subject: List iterator thread safety References: <14e1469e-bcfe-4922-b135-3f0bd7e17a42@r42g2000yqj.googlegroups.com> Message-ID: On Aug 27, 5:03?am, "Emanuele D'Arrigo" wrote: > On Aug 27, 2:01?am, a... at pythoncraft.com (Aahz) wrote: > > > Well, I'm not sure about exceptions, but you almost certainly won't get > > the results you want. > > What I'd like in this context is to iterate through the items in the > list without processing the same item twice and without skipping item > that are in front of the current iterator position. Somehow I can't > quite prove to myself if this is possible or not over multiple > threads. I.e. a dictionary will throw an exception about the object > changing size while iterating through it. A list doesn't, hence the > question. Deleting items from a list while iterating over it is a bad idea, exceptions or not. Hmm, this sounds like something someone might do for a game. You have a list of objects, and in a given time step you have to iterate through the list and update each object. Problem is, one of the enemies is kill before you get to it, so you would like to remove the object from the list while iterating. Not an easy problem. For this simple appeoach, I would suggest writing a custom container (with an underlying list) with state to keep track of the current iterating position. Whenever an item is removed the index is modified (so as to prevent skipping objects), and because you are keeping track of the index yourself there is an iterator that might throw an exception. With threads, you would need to use a Condition or something to sychronize access to the object. Carl Banks From deets at nospam.web.de Thu Aug 27 09:27:16 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Aug 2009 15:27:16 +0200 Subject: ubuntu dist-packages References: <7fki3lF2kirnkU1@mid.uni-berlin.de> <71f5986e-6aae-46b0-8325-d67051c60a30@a13g2000yqc.googlegroups.com> Message-ID: <7fnftkF2m6bvdU1@mid.uni-berlin.de> Paul Boddie wrote: > On 26 Aug, 17:48, Jorgen Grahn wrote: >> >> Well, if you are thinking about Debian Linux, it's not as much >> "ripping out" as "splitting into a separate package with a non-obvious >> name". Annoying at times, but hardly an atrocity. > > Indeed. Having seen two packages today which insisted on setuptools, > neither really needing it, and with one actively trying to download > stuff from the Internet (fifteen seconds warning - how generous!) when > running setup.py, it seems to me that it isn't the distribution > packagers who need to be re-thinking how they install Python software. > > Generally, distributions have to manage huge amounts of software and > uphold reasonable policies without creating unnecessary maintenance. > Sadly, until very recently (and I'm still not entirely sure if there's > really been an attitude change) the Pythonic packaging brigade has > refused to even consider the needs of one of the biggest groups of > consumers of the upstream code. Consequently, distributions will > always devise different ways of storing installed Python software, > documentation and resources, mostly because the Pythonic tools have > been deficient, particularly in the management of the latter > categories. You mean it's the problem of the python packaging that it can't deal with RPMs, debs, tgzs, OSX bundles, MSIs and ? Multiplied by the various packaging philosophies the respective distros build based on these have? I'm a Python-developer. I develop libraries and tools for Python, and want others to be able to install these - as I want to install things *other* python developers created. Setuptools let's me do that (most of the time. And I mean most). If somebody thinks he wants to include these in whatever form he prefers - fine with me. But it's hardly *my* problem, or that of the Python world in general, to fulfill the requirements some other people come up with. Diez From hendrik at microcorp.co.za Thu Aug 27 09:27:59 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 15:27:59 +0200 Subject: Need help with Python scoping rules In-Reply-To: <02a63e7d$0$15633$c3e8da3@news.astraweb.com> References: <02a63e7d$0$15633$c3e8da3@news.astraweb.com> Message-ID: <200908271527.59982.hendrik@microcorp.co.za> On Thursday 27 August 2009 11:14:41 Steven D'Aprano wrote: > On Thu, 27 Aug 2009 08:38:29 +0200, Hendrik van Rooyen wrote: > > On Wednesday 26 August 2009 17:14:27 kj wrote: > >> As I described at length in another reply, the function in question is > >> not intended to be "callable outside the class". And yes, > > > > I think this might go to nub of your problem - It might help you to > > think as follows: > > > > A Python class, even after it has been executed, does not really exist > > except as a kind of template or pattern - it is mostly useless until an > > instance of the class is made by calling it with whatever it needs to > > set up the instance. And once you have an instance, you can do stuff > > with that particular instance. Before that time, the class is mostly > > just a promise of things to come. > > Oh my! I couldn't disagree more strongly! I think the above is totally > incorrect. It was intended to help the OP out of the mental hole he finds himself in. Most of the classes I use fall directly into such a classification - they are useless until an instance is created. And I would be so bold as to say that _all_ gui classes are like that. This is the pattern I am talking about: class thing(object): def __init__(self,foo,bar): stuff to do things with foo and bar, creating or modifying attributes of the instance. def somemethod(self,baz,bling): instance method to do further operations on the attributes of the instance Now kindly explain to me how a class like that is usefull before an instance of it is created, and I might agree with you that what I said is "totally incorrect" 8< --trivial examples showing that there is something there ------------ > Classes are themselves instances of their metaclass. By default, classes > have a metaclass of type, but you can easily change that. Metaclass > programming is advanced but very powerful. > > Because classes are themselves objects, you can (with a bit of metaclass > jiggery-pokery) make them do all sorts of interesting things. For > instance, huge amounts of effort are often put into creating a Singleton > class, a class that has a single instance. Well, okay... but why not just > use the class object itself, instead of an instance? There's already one > of those, and you can't (easily) make a copy of it, and even if you did, > it would be an independent class. Instead of this: > > singleton = SingletonClass(args) > do_something_with(singleton) > > just do this: > > do_something_with(SingletonClass) > > Of course SingletonClass needs to be designed to work that way, which > will probably need some metaclass magic. It would be interesting to see > which requires less effort. *nods* yes this would make sense - but it is not quite what either the OP or I was on about. > > When it comes to built-in classes (types), I often use the class object > itself as an object. E.g. I might do something like this: > > def convert(seq): > t = type(seq) # remember the original type > result = process(seq) # always produces a list > if t is list: > return result # don't bother making a copy of the result > elif t is str or t is unicode: > empty = t() > return empty.join(result) > else: > return t(result) # return the original type nice. now try doing it with object: thing = object() After that, thing will exist, but it is a bit like write only memory - completely useless, until you have done some more work with it. > > >> recursive functions in Python *are* restricted in ways that > >> non-recursive functions aren't. The examples I've posted prove this > >> point unambiguously. > > > > Yes and no - mostly no - your examples just illustrate the point I > > tried to make above. > > Completely no. You may have missed the examples I've given, but the > problems the Original Poster were having had nothing to do with recursion. The yes was in there to make the man feel a bit better, and because from where he stood, it _was_ the recursion that did him in. : - ) > > > Pythons object model, and its classes, are different from what you are > > used to. A bare class is mostly useless without an instance, which is > > ultimately why accessing a function in a class from itself like you are > > doing, without reference to an instance, does not work - the function > > does not exist yet to a degree that it can be referenced. > > That is incorrect. What's going on is more subtle. > Right - I can see that you are reading that to mean that there must be an instance. That is not what I intended to bring across. I was talking about the lack of a reference that is his original problem, which he only encountered with recursion. > >>> class Demo: > > ... def function(x): > ... print "Calling function with argument %s" % x > ... function(None) > ... function(1) > ... function(function) > ... > Calling function with argument None > Calling function with argument 1 > Calling function with argument > > >>> Demo > > two points: Of what earthly use is a bare class like that - except possibly as a container for all the good stuff those functions produced out of nothing? - You might as well use a list, or better a dict, to keep the results of such functions, unless the functions are procedures, doing things by side effect - and if that is the case, why bother putting them in a class? Secondly: Now what you have done is carefully avoided the OP's original problem, which arises when the function in the class is called, and tries to call itself at the time of execution of the class suite, and fails, for the reasons so nicely explained by a lot of people. So the OP had a point when he complained that python does not like recursion, because, until he understands what is happening, the simplest theory that fits his observed facts is that the failure is caused by the recursion. - a completely rational conclusion based on Occam's razor. It just happens to be wrong in this case. This was the source for my "Yes" above. This should also work for the OP - I cannot recall if it has been shown: class Demo(object): def fact(x,f): if x < 2: return 1 else: return x*f(x-1,f) thing = fact(42,fact) I still think it is stupid, though - thing should simply be set to 1405006117752879898543142606244511569936384000000000L and that would be the end of it for this use case, without the bother of a function and the concomitant waste of time. - Hendrik From benjamin.kaplan at case.edu Thu Aug 27 09:28:20 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 27 Aug 2009 09:28:20 -0400 Subject: Does Class implements Interface? In-Reply-To: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> Message-ID: On Thu, Aug 27, 2009 at 9:16 AM, Emanuele D'Arrigo wrote: > Greetings everybody, > > let's say I have a Class C and I'd like to verify if it implements > Interface I. If I is available to me as a class object I can use > issubclass(C, I) and I can at least verify that I is a superclass of > C. There are a couple of issues with this approach however: > > 1) C might override not just I's methods code but also I's methods > signatures, effectively changing the interface. > 2) What if I is -not- available to me as the superclass of C but as a > description of the interface, i.e. as an IDL(*) file? > > Are there resources such as tools, recipes, documents or strategies > that could help me deal with these issues? I've already looked into > the ABC module and the zope.interface. I'm just fishing for more > things to look at. > > Manu > > (*) http://en.wikipedia.org/wiki/Interface_description_language Python's general philosophy is that it's Easier to Ask Forgiveness than Permission. Don't check the interface, just assume it's true and wrap the code block in a try/except in case it isn't. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From anthony.tolle at gmail.com Thu Aug 27 09:36:25 2009 From: anthony.tolle at gmail.com (Anthony Tolle) Date: Thu, 27 Aug 2009 06:36:25 -0700 (PDT) Subject: Move dictionary from instance to class level References: Message-ID: <705c21b0-2858-46c2-8230-3cea64f5be3a@a26g2000yqn.googlegroups.com> To take things one step further, I would recommend using decorators to allow symbolic association of functions with the message identifiers, as follows: ====================================== (MESSAGE_ONE ,MESSAGE_TWO ,MESSAGE_THREE ) = xrange(3) class MyClass(object): method_dict = {} # create helper decorator register_method = lambda msg, method_dict=method_dict: lambda function: method_dict.setdefault(msg, function) @register_method(MESSAGE_ONE) def handle_one(self): print 'handling MESSAGE_ONE' @register_method(MESSAGE_TWO) def handle_two(self): print 'handling MESSAGE_TWO' @register_method(MESSAGE_THREE) def handle_three(self): print 'handling MESSAGE_THREE' # no longer need helper decorator del register_method # function to dispatch messages def on_message_received(self, msg): MyClass.method_dict[msg](self) x = MyClass() x.on_message_received(MESSAGE_ONE) x.on_message_received(MESSAGE_TWO) x.on_message_received(MESSAGE_THREE) ====================================== Note: the line containing the lambda definition is all one line. From hendrik at microcorp.co.za Thu Aug 27 09:44:35 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 15:44:35 +0200 Subject: Need help with Python scoping rules In-Reply-To: <02a6427a$0$15633$c3e8da3@news.astraweb.com> References: <02a6427a$0$15633$c3e8da3@news.astraweb.com> Message-ID: <200908271544.35328.hendrik@microcorp.co.za> On Thursday 27 August 2009 11:31:41 Steven D'Aprano wrote: > > What you are calculating might actually be quite complicated to enter as > a literal. You might have something like: 8< ---------- Complicated Table Example ------------------------------- Me? - never! I am just an assembler programmer. I would not touch a thing like that with a barge pole. Unless of course, I have to. > Clearly this is a made-up example, but the principle is sound. If Python > can calculate values for you, why not let it do so? It is easier for you, > easier to check that you've calculated them correctly, easier to debug > and read, it makes the algorithm clearer (fewer "magic constants"). Yes, > there is a run-time cost, but you only pay it once, when you import the > module, and it's likely to be not that much more expensive than parsing > the literals anyway. > > Of course, for something as big and complicated as the above table, I'd > almost certainly put the code to calculate it in a function outside of > the class, but that's a matter of style, and it will work to put it > inside the class. It is a hell of a thing if it needs recursion to calculate - If it was really that complex, I would calculate it, check it (if I can), document it and put it in a module of its own, with "This side up", "Fragile", and other warning stickers all over it. - Hendrik From knurxs at gmx.de Thu Aug 27 09:49:21 2009 From: knurxs at gmx.de (Michael) Date: Thu, 27 Aug 2009 06:49:21 -0700 (PDT) Subject: Q: multiprocessing.Queue size limitations or bug... References: <9a338a3f-33a8-416c-af42-36f596c7cb71@r27g2000vbn.googlegroups.com> Message-ID: <24428363-dd55-40de-8fc0-45441c1aab22@a13g2000yqc.googlegroups.com> On Aug 27, 8:56?am, ryles wrote: > On Aug 26, 4:56?am, Michael Riedel > wrote: > > > > > Sorry for being not more specific but I'm not absolutely certain whether > > I encountered a bug or did anything wrong: > > > The (stupid) code below results in a stall forever or not at 'p0.join()' > > depending on the value of TROUBLE_MAKER. > > > Any help, thoughts, comments? > > > Thank you for your time. > > > Michael > > > # ---------------------------------------------------------------------- > > > from multiprocessing import Process, Queue > > > # bit vector size > > BVS=8 > > > # > > TROUBLE_MAKER=12 ?# for greater values p0.join() is never satisfied... > > > def evaluate(q, id, start=0, stop=2**BVS): > > > ? ? cmin = {0: []} > > > ? ? for mask0 in range(start, stop): > > ? ? ? ? for mask1 in range(0, 2**BVS): > > ? ? ? ? ? ? for mask2 in range(mask1, TROUBLE_MAKER): > > ? ? ? ? ? ? ? ? cmin[0].append((mask0, mask1, mask2)) > > > ? ? print 'process %d finished (dict layout: %d/%d)...' % (id, > > len(cmin), len(cmin[0])) > > ? ? q.put(cmin.copy()) > > ? ? q.close() > > > if __name__ == '__main__': > > > ? ? q0 = Queue() > > ? ? q1 = Queue() > > ? ? q2 = Queue() > > ? ? q3 = Queue() > > > ? ? part = 2**BVS/4 > > ? ? p0 = Process(target=evaluate, args=(q0, 0, 0*part, 1*part), > > name='worker_0') > > ? ? p1 = Process(target=evaluate, args=(q1, 1, 1*part, 2*part), > > name='worker_1') > > ? ? p2 = Process(target=evaluate, args=(q2, 2, 2*part, 3*part), > > name='worker_2') > > ? ? p3 = Process(target=evaluate, args=(q3, 3, 3*part, 4*part), > > name='worker_3') > > ? ? p0.start() > > ? ? print 'process 0 started...' > > ? ? p1.start() > > ? ? print 'process 1 started...' > > ? ? p2.start() > > ? ? print 'process 2 started...' > > ? ? p3.start() > > ? ? print 'process 3 started...' > > ? ? # main process stalls at p0.join() for bigger TROUBLE_MAKER > > ? ? p0.join() > > ? ? p1.join() > > ? ? p2.join() > > ? ? p3.join() > > ? ? res0 = q0.get() > > ? ? res1 = q1.get() > > ? ? res2 = q2.get() > > ? ? res3 = q3.get() > > ? ? print 'results fetched...' > > > # ---------------------------------------------------------------------- > > > -- > > There is a warning related to this in the documentation: > > http://docs.python.org/library/multiprocessing.html#pipes-and-queues > > Basically, you should reverse the order of the get() and join() calls. > > multiprocessing does a pretty nice job of abstracting away the low- > level details of IPC, but there are still some gotchas. As you've > noticed, your program will deadlock when there is a large enough > amount of data being put into the queue. This is related to a hidden > thread that exists inside each of your child processes. The thread is > responsible for taking your queue items from an internal buffer and > then writing them into a pipe that your parent process will read from > when get() is called. The pipe mechanism is what allows the two > processes to pass information, and is supported directly by the > Operating System. However, the pipe has a limited capacity, and when > it is full, the writer thread is stuck waiting for the reader to read > enough from the pipe so that it can finish its write. The problem is > that your parent process (reader) is not actually calling get() to > drain the pipe. Instead it's stuck in join() waiting for the writer to > complete. I see. I really appreciate your valuable feedback. From no.email at please.post Thu Aug 27 09:53:07 2009 From: no.email at please.post (kj) Date: Thu, 27 Aug 2009 13:53:07 +0000 (UTC) Subject: Need help with Python scoping rules References: <4a967b2f$0$19301$426a74cc@news.free.fr> Message-ID: In <4a967b2f$0$19301$426a74cc at news.free.fr> Bruno Desthuilliers writes: >The only thing one is entitled to expect when learning a new language is >that the language's implementation follows the language specs. In fact, the official docs, when they discuss scopes, are off to a bad start: Names refer to objects. Names are introduced by name binding operations. Each occurrence of a name in the program text refers to the binding of that name established in the innermost function block containing the use. The first paragraph implies that binding can only occur within functions, which is either incorrect, or presupposes a definition of "function" that is not what most programmers would recognize. In general, I found the docs very unclear on the subject of scoping. PEP 227 is much better, but I wouldn't have thought of it as "the specs". kynn From szport at gmail.com Thu Aug 27 10:00:57 2009 From: szport at gmail.com (zaur) Date: Thu, 27 Aug 2009 07:00:57 -0700 (PDT) Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> Message-ID: On 26 ???, 23:56, MRAB wrote: > zaur wrote: > > On 26 ???, 21:11, "Rami Chowdhury" wrote: > >>> person = Person(): > >>> ? name = "john" > >>> ? age = 30 > >>> ? address = Address(): > >>> ? ? ?street = "Green Street" > >>> ? ? ?no = 12 > >> Can you clarify what you mean? Would that define a Person class, and an ? > >> Address class? > > I suppose that someone already define classes Person ans Address. > > For example, in this stupid way in a foreign module: > > > class Person(object): > > ? ?pass > > > class Address(object): > > ? ?pass > > > and the following statements > > > person = Person(): > > ? ?name = "john" > > ? ?age = 30 > > ? ?address = Address(): > > ? ? ? street = "Green Street" > > ? ? ? no = 12 > > > are constructing an instance as follows: > > > person = Person() > > person.name = "john" > > person.age = 30 > > address = person.address = Address() > > address.street = "Green Street" > > address.no = 12 > > [snip] > > Create factory functions: > > def new_address(**kwargs): > ? ? ?address = Address() > ? ? ?address.__dict__.update(kwargs) > ? ? ?return address > > def new_person(**kwargs): > ? ? ?person = Person() > ? ? ?person.__dict__.update(kwargs) > ? ? ?return person > > person = new_person(name="john", age=30, > address=new_address(street="Green Street", no=12)) Original idea isn't about how to organize my code in order to initialize these custom objects. The idea is about to use object's dictionary as nested scope. From paul at boddie.org.uk Thu Aug 27 10:05:51 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 27 Aug 2009 07:05:51 -0700 (PDT) Subject: ubuntu dist-packages References: <7fki3lF2kirnkU1@mid.uni-berlin.de> <71f5986e-6aae-46b0-8325-d67051c60a30@a13g2000yqc.googlegroups.com> <7fnftkF2m6bvdU1@mid.uni-berlin.de> Message-ID: <0298b834-78b4-4501-a09b-9b8da5e796c1@s15g2000yqs.googlegroups.com> On 27 Aug, 15:27, "Diez B. Roggisch" wrote: > > You mean it's the problem of the python packaging that it can't deal with > RPMs, debs, tgzs, OSX bundles, MSIs and > ? No, it's the problem of the Pythonic packaging brigade that package retrieval, building and installing is combined into one unsatisfactory whole. Certainly, it's annoying to discover when building some extension that the Python headers are missing, but the rhetorical vehicle used in the Python community is to frame the distributions as people who like to move stuff around unnecessarily and to corrupt other people's work. In fact, the distributions have proven themselves to be quite competent at managing huge numbers of software packages in a semi-automated fashion, so it's baffling that people doing work on Pythonic packaging tools wouldn't want to learn as much as they can about how those people manage it. For me, when making Debian packages, it has become easier to use the debhelper stuff to install things like documentation and resources than it is to figure out which special options have to be passed to the particular distutils incarnation of the setup function in order to get such stuff put in the right place, especially since distutils probably still employs an ad-hoc 1990s proprietary UNIX "oh just dump that stuff in some directory or other and forget about it" mentality. Really, distutils should be all about *dist*ribution and even then get out of the way as much as possible - the hard stuff is extracting the appropriate knowledge about the built Python interpreter in order to build extensions. Installation should be left to something which has an opinion about where things should be placed on a particular system, and which has the capability to know how to uninstall stuff - a capability which never seems to get any closer in the distutils scene. Paul From hendrik at microcorp.co.za Thu Aug 27 10:25:54 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 16:25:54 +0200 Subject: List iterator thread safety In-Reply-To: References: <14e1469e-bcfe-4922-b135-3f0bd7e17a42@r42g2000yqj.googlegroups.com> Message-ID: <200908271625.54609.hendrik@microcorp.co.za> On Thursday 27 August 2009 15:26:04 Carl Banks wrote: > Deleting items from a list while iterating over it is a bad idea, > exceptions or not. > > Hmm, this sounds like something someone might do for a game. You have > a list of objects, and in a given time step you have to iterate > through the list and update each object. Problem is, one of the > enemies is kill before you get to it, so you would like to remove the > object from the list while iterating. Not an easy problem. Its not too bad - if you crook a bit - the trick is that you iterate over the list backwards when you are removing stuff based on index, so that the remainder does not get jumbled up by losing their positions, as happens when you do it going forwards. - Hendrik From pavlovevidence at gmail.com Thu Aug 27 10:34:17 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 27 Aug 2009 07:34:17 -0700 (PDT) Subject: Object's nesting scope References: Message-ID: <2751e263-ace0-4649-997c-1302d0f3b320@m20g2000vbp.googlegroups.com> On Aug 26, 5:51?am, zaur wrote: > Hi folk! > > What do you think about idea of "object's nesting scope" in python? > > Let's imaging this feature, for example, in this syntax: > > obj=: > ? ? ? > > or > > : > ? ? > > That's means that result object of evaluation is used as > nested scope for evaluation. > > So is this idea useful? It might be marginally useful to save typing. The idea has been discussed in various forms here quite a bit over the years. I doubt there's any chance it'll be accepted into Python, because it goes against one of the main design points of Python: that attributes should always be accessed explicitly. Having said that, the syntax you propose is awful. :) Normally when this is proposed they use a keyword such as "using": p = Person() using p: name = "Carl Banks" location = "Los Angeles" or, perhaps to save a line (even though it'd be a minor syntax abuse): using Person() as p: name = "Carl Banks" location = "Los Angeles" Carl Banks From stefan_ml at behnel.de Thu Aug 27 10:39:24 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 27 Aug 2009 16:39:24 +0200 Subject: Parse xml file In-Reply-To: References: Message-ID: <4a969a9c$0$32665$9b4e6d93@newsspool2.arcor-online.net> loial wrote: > Is there a quick way to retrieve data from an xml file in python 2.4, > rather than read the whole file? ElementTree is available as an external package for Py2.4 (and it's in the stdlib xml.etree package since 2.5). It's pretty much the easiest way to get data out of XML files. If your statement "rather than read the whole file" was referring to the file size, note that the C implementation "cElementTree" of ElementTree is very memory efficient, so you might still get away with just reading the whole file into memory. There's also the iterparse() function which supports iterative parsing of an XML file and thus allows intermediate cleanup of used data. Stefan From pavlovevidence at gmail.com Thu Aug 27 10:50:16 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 27 Aug 2009 07:50:16 -0700 (PDT) Subject: List iterator thread safety References: <14e1469e-bcfe-4922-b135-3f0bd7e17a42@r42g2000yqj.googlegroups.com> Message-ID: <6bf89e55-2ddd-435f-925d-7cc3827c0f9a@24g2000yqm.googlegroups.com> On Aug 27, 7:25?am, Hendrik van Rooyen wrote: > On Thursday 27 August 2009 15:26:04 Carl Banks wrote: > > > Deleting items from a list while iterating over it is a bad idea, > > exceptions or not. > > > Hmm, this sounds like something someone might do for a game. ?You have > > a list of objects, and in a given time step you have to iterate > > through the list and update each object. ?Problem is, one of the > > enemies is kill before you get to it, so you would like to remove the > > object from the list while iterating. ?Not an easy problem. > > Its not too bad - if you crook a bit - the trick is that you iterate over the > list backwards when you are removing stuff based on index, so that the > remainder does not get jumbled up by losing their positions, as happens when > you do it going forwards. That's only if you remove the "current item". The OP has different threads accessing the list at the same time, so I have to assume that item being remove is not necessarily the current iteration. Getting back to the game example, suppose your "list of objects in the scene" looks like this: [ HandsomeHero, Enemy1, Bullet1, Enemy2, Bullet2, Enemy3] It might happen that Bullet1.update() detects a collision with Enemy2, thus killing Enemy2, which means Enemy2 would have to be removed before the next iteration. Otherwise you're updating a zombie. (Which, parenthetically, is another approach.) Conversely, suppose Bullet2.update() detects a collision with Enemy1, and Enemy1 is removed from the list. Then Enemy3 is going to be skipped. In order to handle both cases (where an item could be removed ahead of or before the current item), you have to keep track of the current index and adjust it. A list iterator won't work. For the record, I use a more sophisticated system that explicitly resolves cause and effect in my games. That's probably beyond the scope of this thread, though. Carl Banks From zuo at chopin.edu.pl Thu Aug 27 10:59:47 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 27 Aug 2009 16:59:47 +0200 Subject: Need help with Python scoping rules In-Reply-To: <02a66947$0$15633$c3e8da3@news.astraweb.com> References: <02a66947$0$15633$c3e8da3@news.astraweb.com> Message-ID: 14:17:15 Steven D'Aprano wrote: > The class is a scope, and inside the class scope, you can access local > names. What you can't do is access the class scope from inside nested > functions. s/from inside nested functions/from inside nested scopes Besides that detail, I fully agree. *j -- Jan Kaliszewski (zuo) From szport at gmail.com Thu Aug 27 11:01:14 2009 From: szport at gmail.com (zaur) Date: Thu, 27 Aug 2009 08:01:14 -0700 (PDT) Subject: Object's nesting scope References: <2751e263-ace0-4649-997c-1302d0f3b320@m20g2000vbp.googlegroups.com> Message-ID: On 27 ???, 18:34, Carl Banks wrote: > On Aug 26, 5:51?am, zaur wrote: > > > > > Hi folk! > > > What do you think about idea of "object's nesting scope" in python? > > > Let's imaging this feature, for example, in this syntax: > > > obj=: > > ? ? ? > > > or > > > : > > ? ? > > > That's means that result object of evaluation is used as > > nested scope for evaluation. > > > So is this idea useful? > > It might be marginally useful to save typing. It also allow to structure the code. > The idea has been > discussed in various forms here quite a bit over the years. ?I doubt > there's any chance it'll be accepted into Python, because it goes > against one of the main design points of Python: that attributes > should always be accessed explicitly. I don't in general consider this idea as a way for implicit access to object's attributes. Idea is about to use in some way object's dictionary as nested scope in a code block. I agree though that using this only for saving typing or implicit attribute access isn't a good idea. > Having said that, the syntax you propose is awful. :) Normally when > this is proposed they use a keyword such as "using": > > p = Person() > using p: > ? ? name = "Carl Banks" > ? ? location = "Los Angeles" > > or, perhaps to save a line (even though it'd be a minor syntax abuse): > > using Person() as p: > ? ? name = "Carl Banks" > ? ? location = "Los Angeles" I don't propose concrete syntax for using object's dictionary as nested scope. I used current only to explain the idea. From pavlovevidence at gmail.com Thu Aug 27 11:19:04 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 27 Aug 2009 08:19:04 -0700 (PDT) Subject: Object's nesting scope References: <2751e263-ace0-4649-997c-1302d0f3b320@m20g2000vbp.googlegroups.com> Message-ID: <03269cff-acd9-401a-b98d-0b1136b0d2e0@s13g2000yql.googlegroups.com> On Aug 27, 8:01?am, zaur wrote: > On 27 ???, 18:34, Carl Banks wrote: > > The idea has been > > discussed in various forms here quite a bit over the years. ?I doubt > > there's any chance it'll be accepted into Python, because it goes > > against one of the main design points of Python: that attributes > > should always be accessed explicitly. > > I don't in general consider this idea as a way for implicit access to > object's attributes. That's what is it regardless of what you consider it. > Idea is about to use in some way object's dictionary as nested scope > in a code block. Which is implicitly accessing the object's attributes. Carl Banks From davea at ieee.org Thu Aug 27 11:43:22 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 27 Aug 2009 11:43:22 -0400 Subject: Move dictionary from instance to class level In-Reply-To: <20090827102111.ABC3B1F93@ctb-mesg4.saix.net> References: <20090827102111.ABC3B1F93@ctb-mesg4.saix.net> Message-ID: <4A96A99A.1090100@ieee.org> Frank Millman wrote: > Dave Angel wrote: > >> Frank Millman wrote: >> >>> That is definitely *not* what I want to do. >>> >>> I want to make the server as generic as possible, so that >>> >> it can handle any >> >>> type of client, hopefully even including a browser >>> >> eventually. Therefore the >> >>> server has no knowledge of wxPython event types. >>> >>> I have abstracted all the event types I am interested in >>> >> (the list is fairly >> >>> stable now). My protocol requires that the client maps a >>> >> specific gui event >> >>> type to a message identifier, and the server maps the >>> >> message identifier to >> >>> a method that handles the message. >>> >>> Hope that makes sense. >>> >>> Frank >>> >>> >>> >>> >> Yes, it makes sense. Sorry for heading down that particular >> dead-end. >> But the more I think about it, the more likely I think it is >> that you'll >> be adding new message types, even if they're just variants of ones >> already defined. So it might behoove you to have a shared "data >> structure" that describes the whole message, not just equates >> a name to >> an integer. >> >> Or consider pickling. I don't know the tradeoffs, but the >> idea is that >> an object is constructed at the other end that has all the same data >> members as the object you had at this end. Perhaps with a flexible >> enough class definition, you could represent all or at least >> several of >> your messages with the same object. >> >> I am curious about your topology. You're sending events from >> the client >> (which presumably has a mouse and keyboard) to a server. But >> what does >> the server do with those? Does it have its own screen, or what? >> >> > > I'll try to explain. > > I am writing a fairly standard business/accounting application. (I am now > adding Business Process Management to it, which is complicating matters, but > that is another story.) > > Most of the gui stuff is basic forms processing - screens with static data, > text fields for display and input of data, and buttons for signifying > certain actions to be taken. > > My original attempt had both the gui and the business logic running on the > client, with a connection to a database running on a server. It worked, but > then I realised it was very insecure - it would be easy to hack the python > code, bypass the business logic, and allow any update to the database. > > So my second attempt took all the business logic out of the client and put > it onto the server. To execute a form, the server builds a form definition > by creating objects to represent each of the widgets, creates a list of the > components with sufficient information for the client to render them , then > sends a json'd copy of the list to the client, which interprets it and > displays the required form. The client informs the server of each event, and > the server handles the event in much the same way as it did before when the > business logic was on the client. > > For example, clicking a button triggers a response which could involve > updating the database, displaying another window with additional data, etc, > etc. Previously there would have been a method on the client designed to > handle the response, and the method would be added to the button constructor > so that it would be called when the button was clicked. > > Now the method is on the server, and is stored as an attribute of the button > object on the server. When the user clicks the button, the message is passed > up to the server (each widget has its own id, which is part of the message), > the server is notified that the button was clicked, and it calls the > associated method. > > There is a lot more to it than that, but hopefully that will give you an > idea. > > If I ever get this to a workable state (it is taking far longer than I > anticipated) I will release it as open source, and will then welcome as much > feedback as possible. > > Frank > > > OK, that makes good sense. And I withdraw any suggestion to use pickling, since that could be subject to hacking. It now appears that the messages are only incidentally GUI events. And that you would be well advised to make every possible event a separate message, so that if the server state and the client state get out of synch, you can readily check and reject such operations. For example, you'd have a message for pressing the SUBMIT button on a particular form, but you'd have different message types for other buttons on the same form, or for SUBMIT on other forms. DaveA From szport at gmail.com Thu Aug 27 11:43:55 2009 From: szport at gmail.com (zaur) Date: Thu, 27 Aug 2009 08:43:55 -0700 (PDT) Subject: Object's nesting scope References: <2751e263-ace0-4649-997c-1302d0f3b320@m20g2000vbp.googlegroups.com> <03269cff-acd9-401a-b98d-0b1136b0d2e0@s13g2000yql.googlegroups.com> Message-ID: <2c78ef30-3af6-45bd-b772-e09d895b0cd8@o15g2000yqm.googlegroups.com> On 27 ???, 19:19, Carl Banks wrote: > On Aug 27, 8:01?am, zaur wrote: > > > On 27 ???, 18:34, Carl Banks wrote: > > > The idea has been > > > discussed in various forms here quite a bit over the years. ?I doubt > > > there's any chance it'll be accepted into Python, because it goes > > > against one of the main design points of Python: that attributes > > > should always be accessed explicitly. > > > I don't in general consider this idea as a way for implicit access to > > object's attributes. > > That's what is it regardless of what you consider it. > > > Idea is about to use in some way object's dictionary as nested scope > > in a code block. > > Which is implicitly accessing the object's attributes. > > Carl Banks In my opinion idea of using object's dictionary as nested scope is more about structuring code blocks rather than just saving typing and implicit attribute access. From cournape at gmail.com Thu Aug 27 11:45:01 2009 From: cournape at gmail.com (David Cournapeau) Date: Thu, 27 Aug 2009 10:45:01 -0500 Subject: ubuntu dist-packages In-Reply-To: <7fnftkF2m6bvdU1@mid.uni-berlin.de> References: <7fki3lF2kirnkU1@mid.uni-berlin.de> <71f5986e-6aae-46b0-8325-d67051c60a30@a13g2000yqc.googlegroups.com> <7fnftkF2m6bvdU1@mid.uni-berlin.de> Message-ID: <5b8d13220908270845g67bb8d05w1dda70f433e29914@mail.gmail.com> On Thu, Aug 27, 2009 at 8:27 AM, Diez B. Roggisch wrote: > Paul Boddie wrote: > >> On 26 Aug, 17:48, Jorgen Grahn wrote: >>> >>> Well, if you are thinking about Debian Linux, it's not as much >>> "ripping out" as "splitting into a separate package with a non-obvious >>> name". Annoying at times, but hardly an atrocity. >> >> Indeed. Having seen two packages today which insisted on setuptools, >> neither really needing it, and with one actively trying to download >> stuff from the Internet (fifteen seconds warning - how generous!) when >> running setup.py, it seems to me that it isn't the distribution >> packagers who need to be re-thinking how they install Python software. >> >> Generally, distributions have to manage huge amounts of software and >> uphold reasonable policies without creating unnecessary maintenance. >> Sadly, until very recently (and I'm still not entirely sure if there's >> really been an attitude change) the Pythonic packaging brigade has >> refused to even consider the needs of one of the biggest groups of >> consumers of the upstream code. Consequently, distributions will >> always devise different ways of storing installed Python software, >> documentation and resources, mostly because the Pythonic tools have >> been deficient, particularly in the management of the latter >> categories. > > You mean it's the problem of the python packaging that it can't deal with > RPMs, debs, tgzs, OSX bundles, MSIs and > ? Of course it is - not because distutils should know about them but on the contrary because it should be possible to tweak the installation parameters to accomodate the various packaging solutions. Autotools, cmake, etc... do not need anything about rpm, debian, msi, and yet, they can be used to that purpose. cheers, David From diesch at spamfence.net Thu Aug 27 11:54:03 2009 From: diesch at spamfence.net (Florian Diesch) Date: Thu, 27 Aug 2009 17:54:03 +0200 Subject: ubuntu dist-packages References: Message-ID: Robin Becker writes: > Florian Diesch wrote: > ......... >> >>>From /usr/lib/python2.6/site.py: >> >> ,---- >> | For Debian and derivatives, this sys.path is augmented with directories >> | for packages distributed within the distribution. Local addons go >> | into /usr/local/lib/python/dist-packages, Debian addons >> | install into /usr/{lib,share}/python/dist-packages. >> | /usr/lib/python/site-packages is not used. >> `---- > > the above is not present in my windows documentation (or indeed > site.py) at all so it seems they just decided to change the > name. Anyone trying to debug why their distutils or setuptools or > whichever python packager is going wrong will have yet another detail > to remember. setuptools works fine for me in Ubuntu 9.04; eggs go to /usr/local/lib/python2.6/dist-packages/ like they should according to site.py > In addition, as any one who has done such trivial changes > will already know, they forgot to do it globally eg my 0.4.1.0 version > of the "Debian Python Policy" document explicitly mentions > site-packages. It's a change for the Python 2.6 package, see and /usr/lib/python2.5/site.py Python 2.6 is only in Debian experimental, I guess there is a new version of the Debian Python Policy coming. Florian -- From phily05 at gmail.com Thu Aug 27 11:58:19 2009 From: phily05 at gmail.com (Phil) Date: Thu, 27 Aug 2009 08:58:19 -0700 (PDT) Subject: Python on the Web References: <4a94ef42$0$27774$426a74cc@news.free.fr> <4a96884b$0$22855$426a74cc@news.free.fr> Message-ID: <1b7a2f45-dd10-4722-a9d8-8c6d2464e4d6@e27g2000yqm.googlegroups.com> Thanks Graham. I actually ended up reading that blog post from a Google search last night before I saw your response. It was very informative. Bruno, I will take a look at those groups to expand my knowledge. When I gave that arbitrary percentage, I was basing it off of the information I had seen with regards to launching applications built with existing frameworks using lighttpd. I do realize I was missing a lot of information by looking up something that specific. I also understand that there are enough frameworks. That still won't change my mind. I do not want to write a web application, otherwise I would use an existing framework as suggested. I just wanted to experiment and see what kind of framework I could develop with some ideas I had in mind. The original post was mostly just because I was having a difficulty understanding some lower level concepts as a result of trying to get Python 3 on the web before figuring out that it wasn't quite ready for that. I just really like some of the new features of Python 3, and most importantly, unicode compliance is just that much straight forward in my opinion. From robin_v at bigpond.com Thu Aug 27 12:07:20 2009 From: robin_v at bigpond.com (robin) Date: Thu, 27 Aug 2009 16:07:20 GMT Subject: Numeric literals in other than base 10 References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: "James Harris" wrote in message news:bc3607b3-7fdd-43fd-8ede-66ac3f597403 at 32g2000yqj.googlegroups.com... On 22 Aug, 10:27, David <71da... at libero.it> wrote: >They look good - which is important. The trouble (for me) is that I >want the notation for a new programming language and already use these >characters. I have underscore as an optional separator for groups of >digits - 123000 and 123_000 mean the same. The semicolon terminates a >statement. Based on your second idea, though, maybe a colon could be >used instead as in XPL uses "(2)1011" for base 4, "(3)03212" for octal, "(4)0741" for base 16. PL/I uses 8FXN for numeric hex and X suffix for a hex character constant. From sylvain.thenault at logilab.fr Thu Aug 27 12:10:22 2009 From: sylvain.thenault at logilab.fr (Sylvain =?utf-8?B?VGjDqW5hdWx0?=) Date: Thu, 27 Aug 2009 18:10:22 +0200 Subject: [ANN] pylint 0.18.1 / astng 0.19.1 Message-ID: <20090827161022.GF4791@lupus.logilab.fr> Hi there, I'm pleased to announce a new bug fixes release of pylint and astng. To see what have been fixed and to download it (unless your using debian, ubuntu or easy_install of course :), check: http://www.logilab.org/project/pylint/0.18.1 http://www.logilab.org/project/logilab-astng/0.19.1 -- Sylvain Th?nault LOGILAB, Paris (France) Formations Python, Debian, M?th. Agiles: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services CubicWeb, the semantic web framework: http://www.cubicweb.org From robert.kern at gmail.com Thu Aug 27 12:16:41 2009 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 27 Aug 2009 11:16:41 -0500 Subject: Overriding iadd for dictionary like objects In-Reply-To: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: On 2009-08-27 01:49 AM, RunThePun wrote: > Anybody have any more ideas? I think python should/could havev a > syntax for overriding this behaviour, i mean, obviously the complexity > of supporting all operators with the getitem syntax could introduce > alot of clutter. But maybe there's an elegant solution out there... I would recommend just adding a method to MyDict that does exactly what you want. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Thu Aug 27 12:26:31 2009 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 27 Aug 2009 11:26:31 -0500 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: On 2009-08-27 07:41 AM, David House wrote: > 2009/8/27 Terry Reedy: >> reply-all may send duplicate messages to the author. Not sure of this list. > > I'm fairly sure Mailman deals with that. Many of us read from comp.lang.python for gmane.comp.python.general. I do not appreciate getting reply emails to my inbox. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From shashank.sunny.singh at gmail.com Thu Aug 27 12:39:06 2009 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Thu, 27 Aug 2009 22:09:06 +0530 Subject: (Simple?) Unicode Question Message-ID: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> Hi All! I have a very simple (and probably stupid) question eluding me. When exactly is the char-set information needed? To make my question clear consider reading a file. While reading a file, all I get is basically an array of bytes. Now suppose a file has 10 bytes in it (all is data, no metadata, forget the BOM and stuff for a little while). I read it into an array of 10 bytes, replace, say, 2nd bytes and write all the bytes back to a new file. Do i need the character encoding mumbo jumbo anywhere in this? Further, does anything, except a printing device need to know the encoding of a piece of "text"? I mean, as long as we are not trying to get a symbolic representation of a "text" or get "i"th character of it, all we need to do is to carry the intended encoding as an auxiliary information to the data stored as byte array. Right? --shashank -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Aug 27 12:42:10 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 27 Aug 2009 12:42:10 -0400 Subject: About diagram and python In-Reply-To: <030422b7-a4f8-4ea6-8708-4486da4cf595@w6g2000yqw.googlegroups.com> References: <030422b7-a4f8-4ea6-8708-4486da4cf595@w6g2000yqw.googlegroups.com> Message-ID: <4A96B762.7030209@ieee.org> catalinfest at gmail.com wrote: > Hello! > I see on my Diagram Editor software this : > File -> Export... -> (on Export option is : PyDia Code > Generation ... .py) > What python is in this file ? > How help me with python code ? > Thank you ! > > And when I start my car the radio is tuned to the wrong station. Could somebody tell me how to change the tubes on it? Or maybe I have a flat tire? When asking a question, give enough information that somebody has a chance of answering it. Otherwise you're wasting your time and ours. There are hundreds of "diagram editors" out there. Brand, version, maybe the URL to a website to download it. DaveA From rami.chowdhury at gmail.com Thu Aug 27 12:44:41 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 27 Aug 2009 09:44:41 -0700 Subject: (Simple?) Unicode Question In-Reply-To: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> Message-ID: > Further, does anything, except a printing device need to know the > encoding of a piece of "text"? I may be wrong, but I believe that's part of the idea between separation of string and bytes types in Python 3.x. I believe, if you are using Python 3.x, you don't need the character encoding mumbo jumbo at all ;-) If you're using Python 2.x, though, I believe if you simply set the file opening mode to binary then data you read() should still be treated as an array of bytes, although you may encounter issues trying to access the n'th character. Please do correct me if I'm wrong, anyone. On Thu, 27 Aug 2009 09:39:06 -0700, Shashank Singh wrote: > Hi All! > > I have a very simple (and probably stupid) question eluding me. > When exactly is the char-set information needed? > > To make my question clear consider reading a file. > While reading a file, all I get is basically an array of bytes. > > Now suppose a file has 10 bytes in it (all is data, no metadata, > forget the BOM and stuff for a little while). I read it into an array of > 10 > bytes, replace, say, 2nd bytes and write all the bytes back to a new > file. > > Do i need the character encoding mumbo jumbo anywhere in this? > > Further, does anything, except a printing device need to know the > encoding of a piece of "text"? I mean, as long as we are not trying > to get a symbolic representation of a "text" or get "i"th character > of it, all we need to do is to carry the intended encoding as > an auxiliary information to the data stored as byte array. > > Right? > > --shashank -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From invalid at invalid Thu Aug 27 12:47:41 2009 From: invalid at invalid (Grant Edwards) Date: Thu, 27 Aug 2009 11:47:41 -0500 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: On 2009-08-27, Robert Kern wrote: > On 2009-08-27 07:41 AM, David House wrote: >> 2009/8/27 Terry Reedy: >>> reply-all may send duplicate messages to the author. Not sure of this list. >> >> I'm fairly sure Mailman deals with that. > > Many of us read from comp.lang.python or gmane.comp.python.general. > I do not appreciate getting reply emails to my inbox. Same here. I haven't noticed it happening much for c.l.p, but on some other lists it seems to be a common (and annoying) practice. For those lists, I usually set up e-mail filters for those lists to route such replys to /dev/null. I haven't yet done so for c.l.p... -- Grant Edwards grante Yow! I just forgot my whole at philosophy of life!!! visi.com From marduk at letterboxes.org Thu Aug 27 12:49:36 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Thu, 27 Aug 2009 12:49:36 -0400 Subject: (Simple?) Unicode Question In-Reply-To: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> Message-ID: <1251391776.79209.5.camel@centar.nbk> On Thu, 2009-08-27 at 22:09 +0530, Shashank Singh wrote: > Hi All! > > I have a very simple (and probably stupid) question eluding me. > When exactly is the char-set information needed? > > To make my question clear consider reading a file. > While reading a file, all I get is basically an array of bytes. > > Now suppose a file has 10 bytes in it (all is data, no metadata, > forget the BOM and stuff for a little while). I read it into an array > of 10 > bytes, replace, say, 2nd bytes and write all the bytes back to a new > file. > > Do i need the character encoding mumbo jumbo anywhere in this? > > Further, does anything, except a printing device need to know the > encoding of a piece of "text"? I mean, as long as we are not trying > to get a symbolic representation of a "text" or get "i"th character > of it, all we need to do is to carry the intended encoding as > an auxiliary information to the data stored as byte array. If you are just reading and writing bytes then you are just reading and writing bytes. Where you need to worry about unicode, etc. is when you start treating a series of bytes as TEXT (e.g. how many *characters* are in this byte array).* This is no different, IMO, than treating a byte stream vs a image file. You don't, need to worry about resolution, palette, bit-depth, etc. if you are only treating as a stream of bytes. The only difference between the two is that in Python "unicode" is a built-in type and "image" isn't ;) * Just make sure that if you are manipulating byte streams independent of it's textual representation that you open files, e.g., in binary mode. -a From davea at ieee.org Thu Aug 27 12:52:53 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 27 Aug 2009 12:52:53 -0400 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <2d56febf0908270326p58adda54w306eb823710bb952@mail.gmail.com> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> <2d56febf0908270326p58adda54w306eb823710bb952@mail.gmail.com> Message-ID: <4A96B9E5.3030709@ieee.org> Xavier Ho wrote: > On Thu, Aug 27, 2009 at 7:04 PM, Dave Angel wrote: > > > > Thanks for those pointers. >> For example, I see a single message containing typically around 10 >> attachments. I do the reply-all to one of these attachments, and it handles >> the message body okay, the To/CC fields okay, >> > > > What do you mean 10 attachments? O_o. I know some people like to attach a > company logo in their signature. (The Aussie DLF list people do that heaps. > Although some people post a hand-written sig in the attachment ... I'm not > sure how smart that is, but I've seen it done.) Where are you getting these > "attachments"? > > The message is a "digest" containing between 1 and 20 messages. The "index" is in the main message, and all the actual messages are encoded as attachments. I also see actual attachments, and sometimes signatures as attachments. But the ones I'm talking about have extension .eml. > I haven't tried reply-all yet. May give that a try next time and see what > pops up in the To: address. > > > >> usually adds an extra RE: on the subject (so it becomes RE: RE: subject). >> > > > Gmail doesn't do that. Yay! (Re: is dumb anyway, and you can't prepend Re: > forever. Fwd: is reasonable.) > > > If I have a direct message with a Re: at the beginning, Thunderbird does not add an extra one to my reply subject. Only when I'm doing it on one of these attachments. > > I didn't know ** marks bold. Does __ mark underline? Those are cool things > I never hear about. Thanks! > > I don't know about any others other than *bold* text. And I don't know if it shows up in everyone's viewer that way, or just some. DaveA From josefg at gmail.com Thu Aug 27 13:04:38 2009 From: josefg at gmail.com (josef) Date: Thu, 27 Aug 2009 10:04:38 -0700 (PDT) Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <9feee13c-117e-4806-b238-e4152a68adfb@18g2000yqa.googlegroups.com> Thanks to everyone who responded. I will be going with some sort of a = MyClass(name = 'a') format. It's the Python way. For me, it was very hard to accept that EVERYTHING is an object reference. And that there are no object reference names, just string entries in dictionaries. But I think it all makes sense now. Thanks again, Josef On Aug 21, 1:07?am, josef wrote: > To begin, I'm new with python. I've read a few discussions about > object references and I think I understand them. > > To be clear, Python uses a "Pass By Object Reference" model. > x = 1 > x becomes the object reference, while an object is created with the > type 'int', value 1, and identifier (id(x)). Doing this with a class, > x = myclass(), does the same thing, but with more or less object > attributes. Every object has a type and an identifier (id()), > according to the Python Language Reference for 2.6.2 section 3.1. > > x in both cases is the object reference. I would like to use the > object to refer to the object reference. If I have a gross > misunderstanding, please correct me. > > The following is what I would like to do: > I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d > is an object reference. Entering dk gives me the object: [MyClass0 > instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at > 0x0010 ... ] > > I need the object reference name (a,b,c,d) from dk to use as input for > a file. Where do I find the memory location of the object reference > and the object reference name memory location? I am unconcerned with > the fact that the memory location will change the next time I run a > python session. I will be using the object reference name for > processing right away. > > My main focus of this post is: "How do I find and use object reference > memory locations?" > > Thoughts? > Thanks, > > Josef From milesck at umich.edu Thu Aug 27 13:27:40 2009 From: milesck at umich.edu (Miles Kaufmann) Date: Thu, 27 Aug 2009 10:27:40 -0700 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <13DD6BD6-A688-4870-AA57-8FCF1A122C5A@umich.edu> On Aug 26, 2009, at 1:11 PM, kj wrote: > I think I understand the answers well enough. What I *really* > don't understand is why this particular "feature" of Python (i.e. > that functions defined within a class statement are forbidden from > "seeing" other identifiers defined within the class statement) is > generally considered to be perfectly OK. IMO it's a bizarre, > inexplicable blindspot (which, among other things, gives rise to > a certain worry about what other similar craziness lurks under > Python's image of rationality). I have never seen even a half-hearted > justification, from a language design point of view, for why this > particular "feature" is worth having. Guido's design justifications: http://mail.python.org/pipermail/python-dev/2000-November/010598.html -- My personal justification: Python has used the same basic method of class creation since the very beginning: create a new local namespace, execute the class suite in that namespace, and then create a class, using the contents of the namespace as the class attributes. The important thing to note here is that there are really *two* namespaces--the local namespace that exists while the class suite is being executed (what I call the "suite namespace"), and the namespace of the class itself--and the first ceases to exist when the second is created. The two namespaces generally contain the same names at the point that the transfer occurs, but they don't have to; the metaclass (which constructs the class) is free to mess with the dictionary of attributes before creating the class. Suppose for a moment that the suite namespace *were* visible to nested scopes. The simplest and most consistent implementation would be to have a closure generated by a class statement be similar to that generated by a function--i.e., the closure would be over the suite namespace. This hardly seems desirable, though, because the suite namespace and the class namespace would get out of sync when different objects were assigned to the class namespace: class C: x = 1 def foo(self): print x print self.x >>> o = C() >>> o.foo() 1 1 >>> o.x = 2 >>> o.foo() 1 2 Surely such an implementation would be considered an even larger Python wart then not having the suite namespace visible to nested scopes at all. But it's better than the alternative of trying to unify the class suite namespace and the class namespace, which would be a nightmare of special cases (adding/deleting class attributes? descriptors? __getattr__?) and require an implementation completely separate from that of normal nested scopes. -Miles P.S. Just for fun: import types def make_class(*bases): """Decorator to allow you to (ab)use a function as a class definition. The function must take no arguments and end with 'return locals()'; bases are (optionally) specified as arguments to make_class; metaclasses other than 'type' are not supported. >>> @make_class ... def C(): ... greeting = 'Hello' ... target = 'world' ... def greet(self): ... print '%s, %s' % (self.greeting, target) ... return locals() ... >>> C().greet() Hello, world """ def decorator(func): return type(func.func_name, bases, func()) if len(bases) == 1 and isinstance(bases[0], types.FunctionType): func = bases[0] bases = (object,) return decorator(func) if not bases: bases = (object,) return decorator From ethan at stoneleaf.us Thu Aug 27 13:31:04 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 Aug 2009 10:31:04 -0700 Subject: Annoying octal notation In-Reply-To: <02a0b085$0$30337$c3e8da3@news.astraweb.com> References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> Message-ID: <4A96C2D8.5040002@stoneleaf.us> Steven D'Aprano wrote: > A mistake is still a mistake even if it shared with others. > > Treating its with a lead zero as octal was a design error when it was > first thought up [snippage] I have to disagree with you on this one. The computing world was vastly different when that design decision was made. Space was at a premium, programmers were not touch-typists, every character had to count, and why in the world would somebody who had to use papertape or punch cards add a lead zero without a *real* good reason? I submit that that real good reason was to specify an octal literal, and not a decimal literal. Now many many years have passed, much has changed, and a leading zero (like so much else) no longer makes the sense in once did -- especially in a very wide-spread and general purpose language like Python. That does not mean it was not a very good decision at the time. ~Ethan~ From python at mrabarnett.plus.com Thu Aug 27 13:42:58 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 Aug 2009 18:42:58 +0100 Subject: Annoying octal notation In-Reply-To: <4A96C2D8.5040002@stoneleaf.us> References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> <4A96C2D8.5040002@stoneleaf.us> Message-ID: <4A96C5A2.4020307@mrabarnett.plus.com> Ethan Furman wrote: > Steven D'Aprano wrote: >> A mistake is still a mistake even if it shared with others. >> >> Treating its with a lead zero as octal was a design error when it was >> first thought up > > [snippage] > > I have to disagree with you on this one. The computing world was vastly > different when that design decision was made. Space was at a premium, > programmers were not touch-typists, every character had to count, and > why in the world would somebody who had to use papertape or punch cards > add a lead zero without a *real* good reason? I submit that that real > good reason was to specify an octal literal, and not a decimal literal. > > Now many many years have passed, much has changed, and a leading zero > (like so much else) no longer makes the sense in once did -- especially > in a very wide-spread and general purpose language like Python. That > does not mean it was not a very good decision at the time. > I think that it although it might have been reasonable when C was invented, it wasn't a good idea when Python was invented. From mensanator at aol.com Thu Aug 27 13:49:27 2009 From: mensanator at aol.com (Mensanator) Date: Thu, 27 Aug 2009 10:49:27 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> <02a5d290$0$15633$c3e8da3@news.astraweb.com> <02a5ed07$0$15633$c3e8da3@news.astraweb.com> Message-ID: <9f392780-cb72-4bdb-a571-b1c218f3cbf8@k19g2000yqn.googlegroups.com> On Aug 26, 10:27?pm, Steven D'Aprano wrote: > On Wed, 26 Aug 2009 18:53:04 -0700, Erik Max Francis wrote: > >> In any case, unary is the standard term for what I'm discussing: > > >>http://en.wikipedia.org/wiki/Unary_numeral_system > This really isn't anywhere near as controversial as you guys are making > it. Words sometimes have meanings different from what you expect from > reasoning by analogy. Get over it. Fine. I'm over it. Point is, I HAVE encountered plenty of people who DON'T properly understand it, Marilyn Vos Savant, for example. You can't blame me for thinking you don't understand it either when unary is brought up in a discussion of how to interpret insignificant leading 0's. > > -- > Steven From ethan at stoneleaf.us Thu Aug 27 13:51:16 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 Aug 2009 10:51:16 -0700 Subject: Annoying octal notation In-Reply-To: <4A96C5A2.4020307@mrabarnett.plus.com> References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> <4A96C2D8.5040002@stoneleaf.us> <4A96C5A2.4020307@mrabarnett.plus.com> Message-ID: <4A96C794.9090209@stoneleaf.us> MRAB wrote: > Ethan Furman wrote: > >> Steven D'Aprano wrote: >> >>> A mistake is still a mistake even if it shared with others. >>> >>> Treating its with a lead zero as octal was a design error when it was >>> first thought up >> >> >> [snippage] >> >> I have to disagree with you on this one. The computing world was >> vastly different when that design decision was made. Space was at a >> premium, programmers were not touch-typists, every character had to >> count, and why in the world would somebody who had to use papertape or >> punch cards add a lead zero without a *real* good reason? I submit >> that that real good reason was to specify an octal literal, and not a >> decimal literal. >> >> Now many many years have passed, much has changed, and a leading zero >> (like so much else) no longer makes the sense in once did -- >> especially in a very wide-spread and general purpose language like >> Python. That does not mean it was not a very good decision at the time. >> > I think that it although it might have been reasonable when C was > invented, it wasn't a good idea when Python was invented. Very good point. I was thinking Steven was talking about the earliest case, as opposed to the earliest Python case. My apologies if I misunderstood. ~Ethan~ From bakes at ymail.com Thu Aug 27 14:15:59 2009 From: bakes at ymail.com (Bakes) Date: Thu, 27 Aug 2009 11:15:59 -0700 (PDT) Subject: regexp help Message-ID: <4e548d26-f3c9-46b8-a82a-c012607e2ff8@o6g2000yqj.googlegroups.com> If I were using the code: (?P[0-9]+) to get an integer between 0 and 9, how would I allow it to register negative integers as well? From iurisilvio at gmail.com Thu Aug 27 14:28:09 2009 From: iurisilvio at gmail.com (Iuri) Date: Thu, 27 Aug 2009 15:28:09 -0300 Subject: regexp help In-Reply-To: <4e548d26-f3c9-46b8-a82a-c012607e2ff8@o6g2000yqj.googlegroups.com> References: <4e548d26-f3c9-46b8-a82a-c012607e2ff8@o6g2000yqj.googlegroups.com> Message-ID: <789aac5a0908271128j43b5cf93se3afe2a7477ecc5e@mail.gmail.com> You can use r"[+-]?\d+" to get positive and negative integers. It returns true to these strings: "+123", "-123", "123" On Thu, Aug 27, 2009 at 3:15 PM, Bakes wrote: > If I were using the code: > > (?P[0-9]+) > > to get an integer between 0 and 9, how would I allow it to register > negative integers as well? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Thu Aug 27 14:35:22 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 Aug 2009 11:35:22 -0700 Subject: Object Reference question In-Reply-To: <9feee13c-117e-4806-b238-e4152a68adfb@18g2000yqa.googlegroups.com> References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <9feee13c-117e-4806-b238-e4152a68adfb@18g2000yqa.googlegroups.com> Message-ID: <4A96D1EA.7030002@stoneleaf.us> josef wrote: > Thanks to everyone who responded. > > I will be going with some sort of a = MyClass(name = 'a') format. It's > the Python way. > > For me, it was very hard to accept that EVERYTHING is an object > reference. And that there are no object reference names, just string > entries in dictionaries. But I think it all makes sense now. > > Thanks again, > > Josef My apologies if I missed it, but what *exactly* are you planning on doing with your 'name' attribute? From the posts I've seen so far, I think you are only setting yourself up for failure. ~Ethan~ From dickinsm at gmail.com Thu Aug 27 14:48:11 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 27 Aug 2009 11:48:11 -0700 (PDT) Subject: Python on Crays References: <1f5c81d8-4f79-4eea-b1bd-af48ab9ddc82@c2g2000yqi.googlegroups.com> Message-ID: <9e853de8-3183-402f-ab11-c0fad2a2fb9b@d4g2000yqa.googlegroups.com> On Aug 25, 11:34?pm, Carrie Farberow wrote: > Ok, here are links to word documents outlining the commands I executed as well as the make.log file and the make_install.log file > [links snipped] So from the output of make, it looks as though none of the modules specified in the Modules/Setup file is being built at all on your system. So not just unicodedata, but the math, cmath, array, itertools modules and more are missing from your build. You can check this by running Python: after the make step finishes, you should have a working Python executable called 'python' in the current directory; if you start it up and then type 'import math' at the '>>>' prompt, I'm guessing you'll get an error message that looks something like: ImportError: No module named math I don't have much idea why those modules aren't being built; I tried imitating the relevant parts of your instructions (to the degree that they make sense on my non-Cray system) without any problems. Anyway, I agree that issue1594809 doesn't look so relevant; the only common factor is that in both cases Python is failing to find the unicodedata module; but in that issue the unicodedata module is present but doesn't get found because the paths are messed up, while in your case the unicodedata module isn't being built at all. Suggestions: (1) double check that you've uncommented the appropriate lines in the Modules/Setup file. E.g., after the configure step, there's a line in Modules/Setup that looks like: #unicodedata unicodedata.c # static Unicode character database that leading '#' should be removed so that it looks like: unicodedata unicodedata.c # static Unicode character database and similarly for the other modules in that section. Make sure that you're editing the Modules/Setup file *after* the configure step and *before* the make step. (2) Find a local Unix/Python guru and ask him/her to help out. These sorts of problems are generally much easier to figure out when you've got direct access to the machine. Sorry I can't be more help than this. -- Mark From enleverLesX_XXmcX at XmclavXeauX.com.invalid Thu Aug 27 14:57:38 2009 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Thu, 27 Aug 2009 20:57:38 +0200 Subject: Learning Python advanced features References: <4a967bd6$0$19301$426a74cc@news.free.fr> Message-ID: <4a96d723$0$12655$ba4acef3@news.orange.fr> Bonsoir ! Tu aurais peut-?tre d? r?pondre en anglais (pour certains, "advanced features", c'est mieux que "concepts sophistiqu?s"). @+ MCI From james.harris.1 at googlemail.com Thu Aug 27 15:06:19 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Thu, 27 Aug 2009 12:06:19 -0700 (PDT) Subject: Annoying octal notation References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> Message-ID: On 27 Aug, 18:31, Ethan Furman wrote: > Steven D'Aprano wrote: > > A mistake is still a mistake even if it shared with others. > > > Treating its with a lead zero as octal was a design error when it was > > first thought up > > [snippage] > > I have to disagree with you on this one. ?The computing world was vastly > different when that design decision was made. ?Space was at a premium, > programmers were not touch-typists, every character had to count, and > why in the world would somebody who had to use papertape or punch cards > add a lead zero without a *real* good reason? ?I submit that that real > good reason was to specify an octal literal, and not a decimal literal. Nice idea. Characters were expensive but not that expensive - even then. One extra character to make the octal prefix 0t or 0q or something could have been used. Check out the History heading at http://sundry.wikispaces.com/octal-zero-prefix Note how B migrated away from both BCPL's octal and its hex notation. # and #x in BCPL became 0 and 0x in B James From vicente.soler at gmail.com Thu Aug 27 15:06:53 2009 From: vicente.soler at gmail.com (vsoler) Date: Thu, 27 Aug 2009 12:06:53 -0700 (PDT) Subject: Question on the "csv" library Message-ID: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> I am trying to read a csv file generated by excel. Although I succeed in reading the file, the format that I get is not suitable for me. I've done: >>> import csv >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) >>> print spamReader <_csv.reader object at 0x01022E70> >>> for row in spamReader: print row ['codigo;nombre;cantidad'] ['a;qwe;1'] ['b;asd;2'] ['c;zxc;3'] My questions are: 1- Why using "print spamReader" I cannot see the data? I expected to see a list of lists, a kind of a matrix, but I get nothing 2- Why are the rows in a single string? I expected a list of fields that, when text, would be delimited by " To tell the truth, the file generated by excel does not contain the strings delimited by ". Isn't it weird? 3- Is there anything I can do to have my data in a list of lists structure? would another kind of data suit better my needs? Thank you for your help Vicente Soler From fasteliteprogrammer at yahoo.com Thu Aug 27 15:15:00 2009 From: fasteliteprogrammer at yahoo.com (Craig) Date: Thu, 27 Aug 2009 12:15:00 -0700 (PDT) Subject: Python on Crays In-Reply-To: <9e853de8-3183-402f-ab11-c0fad2a2fb9b@d4g2000yqa.googlegroups.com> Message-ID: <645368.38785.qm@web36503.mail.mud.yahoo.com> Who the one from wisconsin and did you try the python group in madison maybe they can help. Well i from madison are and i just a newbie with python.What OS you useing? --- On Thu, 8/27/09, Mark Dickinson wrote: > From: Mark Dickinson > Subject: Re: Python on Crays > To: python-list at python.org > Date: Thursday, August 27, 2009, 1:48 PM > On Aug 25, 11:34?pm, Carrie Farberow > > wrote: > > Ok, here are links to word documents outlining the > commands I executed as well as the make.log file and the > make_install.log file > > [links snipped] > > So from the output of make, it looks as though none of the > modules specified in the Modules/Setup file is being built > at all on your system.? So not just unicodedata, but > the > math, cmath, array, itertools modules and more are > missing from your build. > > You can check this by running Python:? after the make > step > finishes, you should have a working Python executable > called > 'python' in the current directory;? if you start it up > and > then type 'import math' at the '>>>' prompt, I'm > guessing > you'll get an error message that looks something like: > > ImportError: No module named math > > I don't have much idea why those modules aren't being > built; > I tried imitating the relevant parts of your instructions > (to the degree that they make sense on my non-Cray system) > without any problems. > > Anyway, I agree that issue1594809 doesn't look so > relevant; > the only common factor is that in both cases Python is > failing to find the unicodedata module;? but in that > issue > the unicodedata module is present but doesn't get found > because the paths are messed up, while in your case the > unicodedata module isn't being built at all. > > Suggestions: > > (1) double check that you've uncommented the appropriate > lines > in the Modules/Setup file.? E.g., after the configure > step, there's > a line in Modules/Setup that looks like: > > #unicodedata unicodedata.c? ? # static Unicode > character database > > that leading '#' should be removed so that it looks like: > > unicodedata unicodedata.c? ? # static Unicode > character database > > and similarly for the other modules in that section. > Make sure that you're editing the Modules/Setup file > *after* the configure step and *before* the make step. > > (2) Find a local Unix/Python guru and ask him/her to > help out.? These sorts of problems are generally much > easier to figure out when you've got direct access to > the machine. > > Sorry I can't be more help than this. > > -- > Mark > -- > http://mail.python.org/mailman/listinfo/python-list > From gert.cuykens at gmail.com Thu Aug 27 15:18:28 2009 From: gert.cuykens at gmail.com (gert) Date: Thu, 27 Aug 2009 12:18:28 -0700 (PDT) Subject: How does the file.seek() work ? References: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> <1532ff09-f892-44c8-8206-10b3c2d16050@13g2000prl.googlegroups.com> <40093737-2ff1-4527-a2ea-a016ee526463@k30g2000yqf.googlegroups.com> Message-ID: On Aug 26, 7:28?pm, gert wrote: > On Aug 26, 12:46?am, Graham Dumpleton > wrote: > > > > > On Aug 25, 5:37?am, Tim Chase wrote: > > > > > I want the file pointer set to 100 and overwrite everything from there > > > [snip] > > > > def application(environ, response): > > > > ? ? query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') > > > > ? ? range=environ.get('HTTP_RANGE','bytes=0-').replace > > > > ('bytes=','').split(',') > > > > ? ? offset=[] > > > > ? ? for r in range: offset.append(r.split('-')) > > > > ? ? with open(query,'w+') as f: > > > > ? ? ? ? ?f.seek(int(offset[0][0])) > > > > ? ? ? ? ?while True: > > > > ? ? ? ? ? ? ?chunk=environ['wsgi.input'].read(8192).decode('latin1') > > > > ? ? ? ? ? ? ?if not chunk: break > > > > ? ? ? ? ? ? ?f.write(chunk) > > > > ? ? f=open(query) > > > > ? ? l=str(os.fstat(f.fileno()).st_size) > > > > ? ? response('200 OK', [('Content-Type', 'text/plain'), ('Content- > > > > Length', str(len(l)))]) > > > > ? ? return [l] > > > > A couple items of note: > > > > - you don't open the file in binary mode -- seek is more reliable > > > in binary mode :) > > > If my memory is right, if file is opened in binary mode, also wouldn't > > need to be decoding the WSGI input stream as latin-1 to get a string. > > Instead can just deal with bytes and write bytes to file. > > > Graham > > > > - if you want to lop off the rest of the file, use f.truncate() > > > > An example: > > > > # create the initial file > > > ?>>> f = file('zzz.zzz', 'wb+') > > > ?>>> f.write('abcdefghijklmnop') > > > ?>>> f.close() > > > > ?>>> f = file('zzz.zzz', 'ab+') > > > ?>>> f.read() # show the existing content > > > 'abcdefghijklmnop' > > > ?>>> f.seek(5) # seek to the desired offset > > > ?>>> f.truncate() # throw away everything after here > > > ?>>> f.write('zyx') # write the new data at pos=5 > > > ?>>> f.close() > > > > # demonstrate that it worked > > > ?>>> f = file('zzz.zzz', 'rb') > > > ?>>> f.read() > > > 'abcdezyx' > > > ?>>> f.close() > > > > > also why must I open the file a second time to know how big it is ? > > > > Likely the output has been buffered. ?You can try using > > > > ? ?f.flush() # write all the data to the disk first > > > ? ?size = os.fstat(f.fileno()).st_size > > > > which seems to do the trick for me. > > > -tkc > > Works thanks > > curl -C 10 -T upload2.wsgihttp://192.168.2.17/appwsgi/wsgi/upload2.wsgi > --header "Transfer-Encoding: chunked" -v > > import os > > def application(environ, response): > ? ? #query=environ.get['QUERY_STRING'] > ? ? #print (query, file=environ['wsgi.errors']) > ? ? query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') > ? ? range=environ.get('HTTP_CONTENT_RANGE','bytes 0-').replace('bytes > ','').split('/')[0].split(',') > ? ? offset=[] > ? ? for r in range: offset.append(r.split('-')) > ? ? with open(query,'rb+') as f: > ? ? ? ? ?f.seek(int(offset[0][0])) > ? ? ? ? ?if environ['REQUEST_METHOD']=='PUT': > ? ? ? ? ? ? ?f.truncate() > ? ? ? ? ? ? ?while True: > ? ? ? ? ? ? ? ? ?chunk=environ['wsgi.input'].read(8192) > ? ? ? ? ? ? ? ? ?if not chunk: break > ? ? ? ? ? ? ? ? ?f.write(chunk) > ? ? ? ? ?f.flush() > ? ? ? ? ?l=str(os.fstat(f.fileno()).st_size) > ? ? response('200 OK', [('Content-Type', 'text/plain'), ('Content- > Length', str(len(l)))]) > ? ? return [l] Update it works on mod_wsgi but not on wsgiref.simple_server C:\Users\gert\Desktop\hg\appwsgi\wsgi>curl -T upload2.wsgi http://localhost/appwsgi/wsgi/upload2.wsg i -v * About to connect() to localhost port 80 (#0) * Trying 127.0.0.1... connected * Connected to localhost (127.0.0.1) port 80 (#0) > PUT /appwsgi/wsgi/upload2.wsgi HTTP/1.1 > User-Agent: curl/7.19.4 (amd64-pc-win32) libcurl/7.19.4 OpenSSL/0.9.8j zlib/1.2.3 > Host: localhost > Accept: */* > Content-Length: 869 > Expect: 100-continue > * Done waiting for 100-continue I not getting 100-continues ? From ethan at stoneleaf.us Thu Aug 27 15:22:45 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 Aug 2009 12:22:45 -0700 Subject: Annoying octal notation In-Reply-To: References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> Message-ID: <4A96DD05.8020603@stoneleaf.us> James Harris wrote: > On 27 Aug, 18:31, Ethan Furman wrote: > > >>Steven D'Aprano wrote: > > >>>A mistake is still a mistake even if it shared with others. >> >>>Treating its with a lead zero as octal was a design error when it was >>>first thought up >> >>[snippage] >> >>I have to disagree with you on this one. The computing world was vastly >>different when that design decision was made. Space was at a premium, >>programmers were not touch-typists, every character had to count, and >>why in the world would somebody who had to use papertape or punch cards >>add a lead zero without a *real* good reason? I submit that that real >>good reason was to specify an octal literal, and not a decimal literal. > > > Nice idea. Characters were expensive but not that expensive - even > then. One extra character to make the octal prefix 0t or 0q or > something could have been used. Check out the History heading at > > http://sundry.wikispaces.com/octal-zero-prefix > > Note how B migrated away from both BCPL's octal and its hex notation. > > # and #x in BCPL became > 0 and 0x in B > > James Nice link. I suspect that as much as anything is was abbreviate as much as possible. In unix we have copy as cp, list as ls move as mv, etc, etc. Different mind-set also when designing for yourself or a small group, versus thousands and thousands. I am in agreement that Python should not have a leading 0 for octal, as there are big inconsistencies with how it's treated. Visually, I would have preferred a prefix of 0c, but I understand it should be consistent with the string specifier of o. Oh well, win some, lose some. ~Ethan~ From piet at cs.uu.nl Thu Aug 27 15:26:04 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 27 Aug 2009 21:26:04 +0200 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> Message-ID: >>>>> Mensanator (M) wrote: >M> On Aug 26, 4:59?pm, Piet van Oostrum wrote: >>> >>>>> Mensanator (M) wrote: >>> >M> That's my point. Since the common usage of "binary" is for >>> >M> Standard Positional Number System of Radix 2, it follows >>> >M> that "unary" is the common usage for Standard Positional >>> >M> Number System of Radix 1. That's VERY confusing since such >>> >M> a system is undefined. Remember, common usage does not >>> >M> necessarily properly define things. Saying simply "unary" >>> >M> sounds like you're extending common usage beyond its proper >>> >M> boundaries. >>> >>> But the customary meaning of `unary' is the tally system, as a radix >>> system wouldn't make sense. I don't know when this term came into use >>> but I have known it for a long time. >M> Ok, I'll accept that and in the same breath say such common usage >M> is stupid. I, for one, have never heard such usage and would never >M> use "unary" in the same breath as "decimal, octal, binary" even if >M> I had. As I see it, unary just means that there is one symbol. Binary just means that there are two symbols, etc. With unary, the only sensible numerical interpretation is to count the number of occurrences of that symbol, or if you also want to have the number 0, the number of occurrences - 1. With binary and higher you can come up with more numerical interpretations but the most efficient one is the radix interpretation (for different values of `efficient'). I doubt that there are many other interpretations that you can call sensible. Therefore we immediately think of a radix system when we talk about binary, octal, decimal etc. But the word `binary' itself doesn't imply that. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From benjamin.kaplan at case.edu Thu Aug 27 15:29:15 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 27 Aug 2009 15:29:15 -0400 Subject: Question on the "csv" library In-Reply-To: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> Message-ID: On Thu, Aug 27, 2009 at 3:06 PM, vsoler wrote: > > I am trying to read a csv file generated by excel. > > Although I succeed in reading the file, the format that I get is not > suitable for me. > > I've done: > > >>> import csv > >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) > > >>> print spamReader > <_csv.reader object at 0x01022E70> > > >>> for row in spamReader: > ? ? ? ?print row > > > ['codigo;nombre;cantidad'] > ['a;qwe;1'] > ['b;asd;2'] > ['c;zxc;3'] > > My questions are: > > 1- Why using "print spamReader" I cannot see the data? > ? ?I expected to see a list of lists, a kind of a matrix, but I get > nothing It's because csv.reader does the same thing open does. It returns an iterable, not a list. The file is opened but not processed until you iterate through it. You cannot see the data when you do print spamReader because of this and because the csv reader object does define a __str__ method. > > 2- Why are the rows in a single string? > ? I expected a list of fields that, when text, would be delimited by > " > ?To tell the truth, the file generated by excel does not contain the > strings delimited by ". Isn't it weird? CSV stands for comma separated variables. It actually has nothing to do with the quotes- they're just used in case an element has a comma in it, so the reader knows it's a string literal and not a separate column. Your comma separated variable worksheet seems to be semicolon separated. That's why the reader isn't splitting it. > > 3- Is there anything I can do to have my data in a list of lists > structure? would another kind of data suit better my needs? > just do a list comprehension sheet = [row for row in spamReader] > Thank you for your help > > Vicente Soler > -- > http://mail.python.org/mailman/listinfo/python-list From piet at cs.uu.nl Thu Aug 27 15:40:28 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 27 Aug 2009 21:40:28 +0200 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile References: Message-ID: >>>>> Ryniek90 (R) wrote: >R> Hahah right. My fault. Must remember to read documentation so many times >R> until I find the solution. Thanks, now works fine. :-) And, by the way, how come the traceback refers to File "backuper.py", line 197, in while the posted code has only 188 lines? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From usenot at geekmail.INVALID Thu Aug 27 15:42:40 2009 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Thu, 27 Aug 2009 21:42:40 +0200 Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> Message-ID: <20090827214240.70aeb792@geekmail.INVALID> On Thu, 27 Aug 2009 21:36:28 +0200 Andreas Waldenburger wrote: > [snip] > > Might I humbly suggest > > >>> sheet = list(spamReader) # ? > Oh, and while I'm humbly suggesting: spam_reader instead of spamReader or SpamReader or SpamrEadeR or suchlike. Caps are "reserved" for classes. Not a necessity, of course. But it's the dialect around these parts. /W -- INVALID? DE! From farberow at wisc.edu Thu Aug 27 15:53:53 2009 From: farberow at wisc.edu (Carrie Farberow) Date: Thu, 27 Aug 2009 14:53:53 -0500 Subject: Python on Crays In-Reply-To: <645368.38785.qm@web36503.mail.mud.yahoo.com> References: <9e853de8-3183-402f-ab11-c0fad2a2fb9b@d4g2000yqa.googlegroups.com> <645368.38785.qm@web36503.mail.mud.yahoo.com> Message-ID: <6f30fc8f1d449.4a969e01@wiscmail.wisc.edu> I am from Wisconsin -- is there a python group here? Do you have any contact info.? The compute node operating system is Compute Node Linux (CNL). Carrie ----- Original Message ----- From: Craig Date: Thursday, August 27, 2009 2:15 pm Subject: Re: Python on Crays To: python-list at python.org, Mark Dickinson > Who the one from wisconsin and did you try the python group in madison > maybe they can help. > > Well i from madison are and i just a newbie with python.What OS you useing? > > --- On Thu, 8/27/09, Mark Dickinson wrote: > > > From: Mark Dickinson > > Subject: Re: Python on Crays > > To: python-list at python.org > > Date: Thursday, August 27, 2009, 1:48 PM > > On Aug 25, 11:34?pm, Carrie Farberow > > > > wrote: > > > Ok, here are links to word documents outlining the > > commands I executed as well as the make.log file and the > > make_install.log file > > > [links snipped] > > > > So from the output of make, it looks as though none of the > > modules specified in the Modules/Setup file is being built > > at all on your system.? So not just unicodedata, but > > the > > math, cmath, array, itertools modules and more are > > missing from your build. > > > > You can check this by running Python:? after the make > > step > > finishes, you should have a working Python executable > > called > > 'python' in the current directory;? if you start it up > > and > > then type 'import math' at the '>>>' prompt, I'm > > guessing > > you'll get an error message that looks something like: > > > > ImportError: No module named math > > > > I don't have much idea why those modules aren't being > > built; > > I tried imitating the relevant parts of your instructions > > (to the degree that they make sense on my non-Cray system) > > without any problems. > > > > Anyway, I agree that issue1594809 doesn't look so > > relevant; > > the only common factor is that in both cases Python is > > failing to find the unicodedata module;? but in that > > issue > > the unicodedata module is present but doesn't get found > > because the paths are messed up, while in your case the > > unicodedata module isn't being built at all. > > > > Suggestions: > > > > (1) double check that you've uncommented the appropriate > > lines > > in the Modules/Setup file.? E.g., after the configure > > step, there's > > a line in Modules/Setup that looks like: > > > > #unicodedata unicodedata.c? ? # static Unicode > > character database > > > > that leading '#' should be removed so that it looks like: > > > > unicodedata unicodedata.c? ? # static Unicode > > character database > > > > and similarly for the other modules in that section. > > Make sure that you're editing the Modules/Setup file > > *after* the configure step and *before* the make step. > > > > (2) Find a local Unix/Python guru and ask him/her to > > help out.? These sorts of problems are generally much > > easier to figure out when you've got direct access to > > the machine. > > > > Sorry I can't be more help than this. > > > > -- > > Mark > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From piet at cs.uu.nl Thu Aug 27 16:07:51 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 27 Aug 2009 22:07:51 +0200 Subject: Need help with Python scoping rules References: Message-ID: >>>>> kj (k) wrote: >k> No, the fact() function here represents an internal "helper" >k> function. It is meant to be called only once to help initialize >k> a class variable that would be inconvenient to initialize otherwise; >k> this helper function is not meant to be called from outside the >k> class statement. Granted, in the example I gave, the "helper" >k> function (factorial) is a bit silly, but that was just intended as >k> a simple and familiar example of a recursive function. The actual >k> function that motivated this post would be considerably more >k> difficult to explain and would have obscured the point of the post. Classes don't have helper functions; they have methods. Instance methods, static methods or class methods. Your's isn't either of these. Methods are to be called like `something.method(...)'. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From vicente.soler at gmail.com Thu Aug 27 16:12:07 2009 From: vicente.soler at gmail.com (vsoler) Date: Thu, 27 Aug 2009 13:12:07 -0700 (PDT) Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> Message-ID: <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> On Aug 27, 9:42?pm, Andreas Waldenburger wrote: > On Thu, 27 Aug 2009 21:36:28 +0200 Andreas Waldenburger > > wrote: > > [snip] > > > Might I humbly suggest > > > >>> sheet = list(spamReader) ?# ? > > Oh, and while I'm humbly suggesting: > > spam_reader instead of spamReader or SpamReader or SpamrEadeR or > suchlike. Caps are "reserved" for classes. > > Not a necessity, of course. But it's the dialect around these parts. > > /W > > -- > INVALID? DE! Thank you for your answers. Let me however make some comments: 1- the csv file was generated with Excel 2007; no prompts for what the separator should be; Excel has used ";" by default, without asking anything 2- about capitalisation, I used the var "spamReader" because I just copy/pasted from the official python site: http://docs.python.org/library/csv.html 3- when I try >>> sheet = [row for row in spamReader] >>> print sheet [] all I get is an empty list; something seems not to be working properly Same result list: I get an empty list sheet = list(spamReader) Thank you again for your help, which is highly appreciated. Vicente Soler From tjreedy at udel.edu Thu Aug 27 16:22:31 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Aug 2009 16:22:31 -0400 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: David House wrote: > 2009/8/27 Terry Reedy : >> reply-all may send duplicate messages to the author. Not sure of this list. > > I'm fairly sure Mailman deals with that. Nope. I got a duplicate sent to my mailbox, which I hate. From ppearson at nowhere.invalid Thu Aug 27 16:31:01 2009 From: ppearson at nowhere.invalid (Peter Pearson) Date: 27 Aug 2009 20:31:01 GMT Subject: regexp help References: <4e548d26-f3c9-46b8-a82a-c012607e2ff8@o6g2000yqj.googlegroups.com> Message-ID: <7fo8o5F2i2o8tU1@mid.individual.net> On Thu, 27 Aug 2009 11:15:59 -0700 (PDT), Bakes wrote: > If I were using the code: > > (?P[0-9]+) > > to get an integer between 0 and 9, how would I allow it to register > negative integers as well? (?P-?[0-9]+) -- To email me, substitute nowhere->spamcop, invalid->net. From usenot at geekmail.INVALID Thu Aug 27 16:37:26 2009 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Thu, 27 Aug 2009 22:37:26 +0200 Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> Message-ID: <20090827223726.23f99ef6@geekmail.INVALID> On Thu, 27 Aug 2009 13:12:07 -0700 (PDT) vsoler wrote: > On Aug 27, 9:42?pm, Andreas Waldenburger > wrote: > > [snip what I wrote] > > Thank you for your answers. Let me however make some comments: > > 1- the csv file was generated with Excel 2007; no prompts for what the > separator should be; Excel has used ";" by default, without asking > anything > Apparently it's possible, but it's a kludge http://astrochimp.com/2005/12/20/export-csv-with-any-delimiter/comment-page-1/ Anyways, ... > 2- about capitalisation, I used the var "spamReader" because I just > copy/pasted from the official python site: > > http://docs.python.org/library/csv.html > Oh, switcheroo! Well, those hypocrites! > 3- when I try > > >>> sheet = [row for row in spamReader] > >>> print sheet > [] > > all I get is an empty list; something seems not to be working properly > > Same result list: I get an empty list > > sheet = list(spamReader) > > Thank you again for your help, which is highly appreciated. > I'm assuming you do that after you've iterated over the file before? Because it did work in a previous post of yours. Here's the deal: When you iterate over a file (or read from it in any other manner) you "advance" in the file. After iteration, you're at the end, of course. So iterating again yields silch. Hmm ... don't know how that translates to a CSVReader. But I postulate that it'l work on a fresh run. /W -- INVALID? DE! From jgardner at jonathangardner.net Thu Aug 27 16:42:18 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 27 Aug 2009 13:42:18 -0700 (PDT) Subject: Does Class implements Interface? References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> Message-ID: <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> On Aug 27, 6:16?am, "Emanuele D'Arrigo" wrote: > Greetings everybody, > > let's say I have a Class C and I'd like to verify if it implements > Interface I. If I is available to me as a class object I can use > issubclass(C, I) and I can at least verify that I is a superclass of > C. There are a couple of issues with this approach however: > > 1) C might override not just I's methods code but also I's methods > signatures, effectively changing the interface. > 2) What if I is -not- available to me as the superclass of C but as a > description of the interface, i.e. as an IDL(*) file? > > Are there resources such as tools, recipes, documents or strategies > that could help me deal with these issues? I've already looked into > the ABC module and the zope.interface. I'm just fishing for more > things to look at. > Have you heard of duck typing? Ignore all those things and rely on human (aka natural language) documentation. That is, if you want to see if a class will work for an interface, go read the docs on the interface (or rather, what the function expects the interface to be) and what the class provides and see if they fit. From breamoreboy at yahoo.co.uk Thu Aug 27 16:44:17 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 27 Aug 2009 21:44:17 +0100 Subject: Question on the "csv" library In-Reply-To: <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> Message-ID: vsoler wrote: > On Aug 27, 9:42 pm, Andreas Waldenburger > wrote: >> On Thu, 27 Aug 2009 21:36:28 +0200 Andreas Waldenburger >> >> wrote: >>> [snip] >>> Might I humbly suggest >>>>>> sheet = list(spamReader) # ? >> Oh, and while I'm humbly suggesting: >> >> spam_reader instead of spamReader or SpamReader or SpamrEadeR or >> suchlike. Caps are "reserved" for classes. >> >> Not a necessity, of course. But it's the dialect around these parts. >> >> /W >> >> -- >> INVALID? DE! > > Thank you for your answers. Let me however make some comments: > > 1- the csv file was generated with Excel 2007; no prompts for what the > separator should be; Excel has used ";" by default, without asking > anything I find this difficult to believe, but assuming that you are correct then use the delimiter=';' argument in the call to csv.reader. See the csv module documentation section "Dialects and Formatting Parameters" for more information. > > 2- about capitalisation, I used the var "spamReader" because I just > copy/pasted from the official python site: > > http://docs.python.org/library/csv.html > > 3- when I try > >>>> sheet = [row for row in spamReader] >>>> print sheet > [] > > all I get is an empty list; something seems not to be working properly > > Same result list: I get an empty list > > sheet = list(spamReader) > > Thank you again for your help, which is highly appreciated. > > Vicente Soler -- Kindest regards. Mark Lawrence. From jgardner at jonathangardner.net Thu Aug 27 16:44:27 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 27 Aug 2009 13:44:27 -0700 (PDT) Subject: Learning Python advanced features References: <4a967864$0$15193$426a74cc@news.free.fr> Message-ID: <6b1a2aae-fd3d-40a8-9350-89a8661a6d4a@a37g2000prf.googlegroups.com> On Aug 27, 5:13?am, jvpic wrote: > Hi, > > Learning Python, I understand the mechanism of : closure, __new__, > descriptors, decorators and __metaclass__, but I interrogate myself on > the interest of those technics ? > > May somebody explain me the interest ? > I assume you are asking, "Why do these features exist? What makes them useful? When would I use them?" For that, you should re-read the documentation and discussion surrounding them. The short answer is that the above makes your job, as a programmer easier. It's easier because you have to write less code, read less code, and your code has fewer bugs. From tjreedy at udel.edu Thu Aug 27 16:57:44 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Aug 2009 16:57:44 -0400 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: Terry Reedy wrote: > David House wrote: >> 2009/8/27 Terry Reedy : >>> reply-all may send duplicate messages to the author. Not sure of this >>> list. >> >> I'm fairly sure Mailman deals with that. > > Nope. I got a duplicate sent to my mailbox, which I hate. In particular, because there is no indication that it is an exact duplicate of what I will also find on the list itself. Please use reply instead of reply-all. From aahz at pythoncraft.com Thu Aug 27 17:05:05 2009 From: aahz at pythoncraft.com (Aahz) Date: 27 Aug 2009 14:05:05 -0700 Subject: Python on the Web References: Message-ID: In article , Phil wrote: > >My interest in Python 3.1 was actually to develop a framework. Again, >I can feel the flames. :) I understand there are enough frameworks but >I actually have no applications that I wish to develop. I enjoy >developing these kinds of things from scratch as a learning >experience. Well, there's a standard joke that just as people learning Scheme write a new language (following SICP), people learning Python write a new web framework. That's why there are so many of them. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From nbdarvin at gmail.com Thu Aug 27 17:06:19 2009 From: nbdarvin at gmail.com (Darvin) Date: Thu, 27 Aug 2009 14:06:19 -0700 (PDT) Subject: Python Telnet client Message-ID: <09ac1e4e-2c17-4174-9ff3-f07576532960@t13g2000yqt.googlegroups.com> Is there telnet client in python? i want to write NetHack telnet GUI app) From jakecjacobson at gmail.com Thu Aug 27 17:10:22 2009 From: jakecjacobson at gmail.com (jakecjacobson) Date: Thu, 27 Aug 2009 14:10:22 -0700 (PDT) Subject: How to unencode a string Message-ID: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> This seems like a real simple newbie question but how can a person unencode a string? In Perl I use something like: "$part=~ s/\%([A-Fa- f0-9]{2})/pack('C', hex($1))/seg;" If I have a string like Word1%20Word2%20Word3 I want to get Word1 Word2 Word3. Would also like to handle special characters like '",(){} [] etc/ From clp2 at rebertia.com Thu Aug 27 17:14:24 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Aug 2009 14:14:24 -0700 Subject: Python Telnet client In-Reply-To: <09ac1e4e-2c17-4174-9ff3-f07576532960@t13g2000yqt.googlegroups.com> References: <09ac1e4e-2c17-4174-9ff3-f07576532960@t13g2000yqt.googlegroups.com> Message-ID: <50697b2c0908271414l78a79b4dm14de9d6ba359804e@mail.gmail.com> On Thu, Aug 27, 2009 at 2:06 PM, Darvin wrote: > Is there telnet client in python? > i want to write NetHack telnet GUI app) http://docs.python.org/library/telnetlib.html Cheers, Chris -- http://blog.rebertia.com From aahz at pythoncraft.com Thu Aug 27 17:16:28 2009 From: aahz at pythoncraft.com (Aahz) Date: 27 Aug 2009 14:16:28 -0700 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> Message-ID: In article , Terry Reedy wrote: >David House wrote: >> 2009/8/27 Terry Reedy : >>> >>> reply-all may send duplicate messages to the author. Not sure of >>> this list. >> >> I'm fairly sure Mailman deals with that. > >Nope. I got a duplicate sent to my mailbox, which I hate. More precisely, there is a Mailman option per-list to suppress list sending of posts for which you are cc'd. I don't remember where, you should be able to find it by poking around the Mailman interface (or searching the docs). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From exarkun at twistedmatrix.com Thu Aug 27 17:18:41 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Thu, 27 Aug 2009 21:18:41 -0000 Subject: Python Telnet client In-Reply-To: <09ac1e4e-2c17-4174-9ff3-f07576532960@t13g2000yqt.googlegroups.com> References: <09ac1e4e-2c17-4174-9ff3-f07576532960@t13g2000yqt.googlegroups.com> Message-ID: <20090827211841.7475.756920895.divmod.xquotient.59@localhost.localdomain> On 09:06 pm, nbdarvin at gmail.com wrote: >Is there telnet client in python? >i want to write NetHack telnet GUI app) The Python stdlib has a module named telnetlib which offers rudamentary telnet support. Twisted includes twisted.conch.telnet which implements a much more complete telnet library. Twisted also includes twisted.conch.insults which provides basic terminal control functionality (so you can tell what nethack is trying to do over your telnet connection). Jean-Paul From ryniek90 at gmail.com Thu Aug 27 17:21:25 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Thu, 27 Aug 2009 23:21:25 +0200 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile In-Reply-To: References: Message-ID: <4A96F8D5.5080709@gmail.com> > >>>>>> Ryniek90 (R) wrote: >>>>>> > > >> R> Hahah right. My fault. Must remember to read documentation so many times >> R> until I find the solution. Thanks, now works fine. :-) >> > > And, by the way, how come the traceback refers to > File "backuper.py", line 197, in > while the posted code has only 188 lines? > Cuz my original code is bit longer - i've got some bookkeepings like __author__, __version__ etc., just after module imports. From rt8396 at gmail.com Thu Aug 27 17:22:52 2009 From: rt8396 at gmail.com (r) Date: Thu, 27 Aug 2009 14:22:52 -0700 (PDT) Subject: An assessment of Tkinter and IDLE Message-ID: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> --------------------------------------------- Tkinter and IDLE Shortfalls --------------------------------------------- *The following is an assessment of Tkinter as i have experienced it. Even with all the problems i list below i strongly believe Tkinter is a great starter GUI toolkit and we (the Python Community), must keep and maintain this module for the foreseeable future. *However, as my assessment will reveal, much needs to be done to "freshen" up Tkinter and IDLE, and I am not just asking for someone to fix these problems. I have already coded solutions for most of them however, some of course still need work, and i would like to hear from others on this subject too. So buckle your seat belts folks, cause here we go... --------------------------------------------- Python offical docs and Tkinter --------------------------------------------- *The Python docs barely cover anything related to actual Tkinter coding. At the minimum the Tkinter doc page should have a subpage for all the widgets available --which is very small(approx 15) and each subpage should list the available methods on that wiget. Here are two great resources that really like from Fredrik Lundh and John Shipman... http://www.pythonware.com/library/tkinter/introduction/index.htm http://infohost.nmt.edu/tcc/help/pubs/tkinter/ ...I must say that I prefer the latter written by John Shipman because of the way he lists each widgets options in a nice table structure, and then lists the methods below. And intersestingly enough, his manual only weighs in at about 800kb completely uncommpressed and unedited. I'll bet you a wooden nickel i can reduce it to around 500kb for the official Python docs *wink* *Sadly however neither of these great works is mentioned or linked in the official docs Why?. *I think a short-and-to-the-point reference, like the afore mentioned along with a few links to full featured tuts would be a great addition to the Tkinter section of the official docs and i would be happy to help make this happen. --------------------------------------------- from Tkinter import * --------------------------------------------- *Too many noobs start out with the "from Tkinter import *" idiom, unknowing that they are horribly polluting their namespace. I feel that all (tkinter) code should follow the "import Tkinter as tk" policy and never use "from Tkinter import *". To push this agenda i propose all docs be modified so that no one should see such global import blasphemy again. We should at least keep all example code in the latter non-polluting form and frown heavily upon global imports in Tkinter code or any code for that matter. --------------------------------------------- Tkinter Constants --------------------------------------------- *The Tkconstants module needs to be removed *yesterday* because i think it reinforces sloppy coding styles. The main problem is with subtle bugs that are created when someone rebinds one or more of the constants, for example "W=20". At first i thought the constants were great but I quickly found out the shortfalls of such a Utopian approach . Since Tkinter allows strings to be passed-into widget constructors, we should remove the TkConstants immediately and force everyone to use strings instead... #-- instead of this --# w.pack(side=LEFT,fill=BOTH,anchor=W) #-- do this --# w.pack(side='left',fill='both',anchor='w') The few extra keystrokes are well worth the effort! --------------------------------------------- IDLE Shell --------------------------------------------- *IDLE and Pyshell are great but have major flaws in design. One of my biggest complaints is the shell's eight space indention which completely bloats your screen! Another annoying fact is that the prompt (>>>) is actually inside the text widget. This design is all wrong! The prompt should be in another widget to the left of the text so it never gets copied or pasted. Or at-least have the copy/paste action remove the initial four spaces and the prompt, but i think a full separation of "prompt" and "text" are the best solution. The following ASCII art won't win me any awards, but it may covey my idea. "W1" holds the prompt and "W2" is the actual text editor. <-------- W2 -----------> >>> | for x in range(10): | ... | print x | ... | for y in range(x): | ... | print y | |1 |2 And don't tell me about Geany or Pythonwin or emacs or vim or whatever editor happens to float your boat. I know there are tons of great editors out there but IDLE is most likely the first one a Pynoob will use so it must be usable! IDLE and Tkinter are what make Python a stater language -- after the beautiful syntax of course :) --------------------------------------------- IDLE Editor --------------------------------------------- *On M$ windows pressing the MMB without a motion causes the selected text to be pasted at the insertion cursor, and holding it repeats the action very quickly! Since IDLE has no horizontal scroll bar you must use MMB to scroll left-right. I am quite happy that there is no horizontal scrollbar since using MMB is much quicker, but the text pasting action always ruins my day :(. This pasting action is a real PITA and a waste of good processor time. I know how to override it with a hack in IDLE, but many newcomers won't and will probably get frustrated by it so this must be either fixed by hard coding IDLE or allowing a user to turn is off in the config options dialog. *Something that always gets a Python IDLE noob is "open-bracket-syntax- errors" in IDLE. When Python throws this type of error normally the only clue you will get from IDLE is to see the last line highlighted. However, the missing or misplaced bracket is usually no where near the end of the script. IDLE can be easily fixed to show a much closer or even exact location of the last open bracket. *The Find dialog forgets the regexp string after finding a match, this can be a real time waster especially if you typed in a long expression and need to tweak it just a bit for a second search! if the "regexp" check box is selected the dialog should not replace the contents of the Dialog.entry with the texts' selection. (easy fix) *The replace dialog seems buggy when doing a "replace+find". Sometimes it will highlight the next match but sometimes the highlight will immediately disappear so you can't be for sure what you may be replacing with the next push of the button? (could be a conflict with the colorizer) Real aggravating! This seems to always happen when a string is selected. *One of my all time pet peeves with all text editors. Everybody repeat after me... """NO TEXT EDITOR SHOULD EVER COPY AN EMPTY STRING TO THE CLIPBOARD!!""" ...I can't tell you how many times I've had to re-copy some text because i accidentally pressed instead of , arggh! This bug needs to be fixed yesterday! Pressing with no active selection should sound the error bell, not copy "". *Using the goto-line command should highlight the requested line. Currently all that IDLE does is place the insertion cursor at the start of the requested line which is completely useless. One more line of code in the goto method would make this action more useful --------------------------------------------- Tkinter Canvas --------------------------------------------- *The Tkinter Canvas widget should return (X,Y) pairs when calling canvas.coords(obj). The current implementation returns a flat array that is pretty much useless outside of canvas calls. Of course one could zip the coords into pairs, but it seems clumsy to call zip() on 2 LC's when Tkinter could, and should, do it for you. *Canvas needs a canvas.rotate() method for polygons, lines -- (easy). --------------------------------------------- Tkinter ComboBox -- where's Waldo? --------------------------------------------- *As much as i hate to support anything related to M$, Tkinter needs an M$ stlye combobox. Yes, I know Tix has combobox (*puke*), however using it is like pulling teeth. I have coded up an far more elegant/ simple solution -- and yes, i know about the OptionMenu widget which serves a useful purpose but is NOT a good replacement for a REAL M$ style combobox ;). *For instance, ComboBoxes need values that the user can select from, this is as universal as humans and oxygen. But sometimes you want to give the user a detailed set of values in the dropdown listbox and then insert an abbrieation of the value once selected, such as the case with state names... New Mexico -> MN California -> CA Florida -> FL ...instead of the laborious and wasteful convention of overriding a method to insert this value from a mapping each time why not just pass a pointer to the mapping into the constructor and create a combobox that actually knows how to walk and chew gum! [Warning: puesdo code ahead!] class ComboBox(master, values, etc..) def __init__(blahblahblah) self.values = values if type(values) == dict: self.values = values.keys()) listbox.load(self.values) def onUserPick(self, arg): if type(self.values) == dict: self.entry.set(self.values[arg]) return self.entry.set(arg) --------------------------------------------- Tix In General --------------------------------------------- *I am not a big fan of the Tix Module. The idea behind the widgets is great, but using most of them is a nightmare on elm street with Jason Voorhees in hot pursuit. I have hacked my own far more elegant versions of the more useful Tix Widgets and i feel mine are less buggy and more user friendly. So i say lose Tix and go with my fix, or get stuck with the Tix! *Python is missing good docs for Tix. The only thing i can find is the Tcl docs which are riddled with horribly cryptic tcl code. --------------------------------------------- Tix NoteBook --------------------------------------------- *The Tix.NoteBook widget has a bug. If you subclass Frame for your toplevel window you can't create a notebook widget as a descendant of the frame because it just blows chunks. The only way i have successfully used the widget is by the noobish style... >>> import Tix >>> root = Tix.Tk() >>> notebook = Tix.NoteBook...blah >>> root.mainloop() *Overall however i feel the IDLE "TabbedWidget" out-performs the Tix.NoteBook by miles and is easier to use, although it does have a few design problems that i have fixed. One of the most predominate being the inability to see the tabs clearly. The selected tab should "stand-out" from the others so a user can spot it quickly. Also there is no reason to export TabSet class and this can clean up the code a bit. --------------------------------------------- Tix ComboBox --------------------------------------------- *What is with that big ugly arrow? This widget is an exercise in cruelty to humans, and thats all i will say about it! --------------------------------------------- Final Thoughts --------------------------------------------- Well, that is all i can remember for now. If you've made it this far without losing your temper or your lunch well i am very surprised ;). Anyway, give me some feedback on these ideas so maybe i can get motivated to submit some patches/enhancements. psst... help is welcome too ya'know :) From kccnospam at glenevin.com Thu Aug 27 17:37:54 2009 From: kccnospam at glenevin.com (seanacais) Date: Thu, 27 Aug 2009 14:37:54 -0700 (PDT) Subject: variables of the class are not available as default values? Message-ID: I'm working on a program where I wish to define the default value of a method as a value that was set in __init__. I get a compilation error saying that self is undefined. As always a code snippet helps :-) class foo: def __init__(self, maxvalue): self.maxvalue = maxvalue self.value = 0 def put(self, value=self.maxvalue): self.value = value So if I call foo.put() the value is set to maxvalue but maxvalue can be specified when I instantiate foo. Explanations and/or workarounds much appreciated. python test.py Traceback (most recent call last): File "test.py", line 1, in class foo: File "test.py", line 6, in foo def put(self, value=self.maxvalue): NameError: name 'self' is not defined From clp2 at rebertia.com Thu Aug 27 17:44:53 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Aug 2009 14:44:53 -0700 Subject: variables of the class are not available as default values? In-Reply-To: References: Message-ID: <50697b2c0908271444t67b2c820pbcd0f6c82acaa832@mail.gmail.com> On Thu, Aug 27, 2009 at 2:37 PM, seanacais wrote: > I'm working on a program where I wish to define the default value of a > method as a value that was set in __init__. ?I get a compilation error > saying that self is undefined. > > As always a code snippet helps :-) > > class foo: > ? ?def __init__(self, maxvalue): > ? ? ? ?self.maxvalue = maxvalue > ? ? ? ?self.value = 0 > > ? ?def put(self, value=self.maxvalue): > ? ? ? ?self.value = value > > So if I call foo.put() the value is set to maxvalue but maxvalue can > be specified when I instantiate foo. > python test.py > Traceback (most recent call last): > File "test.py", line 1, in > class foo: > File "test.py", line 6, in foo > def put(self, value=self.maxvalue): > NameError: name 'self' is not defined > Explanations and/or workarounds much appreciated. Workaround: class foo: def __init__(self, maxvalue): self.maxvalue = maxvalue self.value = 0 def put(self, value=None): self.value = self.value if value is None else value Explanation: Default values are only evaluated once, when the class is defined, thus "self" is not defined at that point since the class is still being defined when the method definition is executed and thus there can be no instances yet anyway. Cheers, Chris -- http://blog.rebertia.com From andreengels at gmail.com Thu Aug 27 17:49:42 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 27 Aug 2009 23:49:42 +0200 Subject: variables of the class are not available as default values? In-Reply-To: References: Message-ID: <6faf39c90908271449ic980813n56a9873913ee2af9@mail.gmail.com> On Thu, Aug 27, 2009 at 11:37 PM, seanacais wrote: > I'm working on a program where I wish to define the default value of a > method as a value that was set in __init__. ?I get a compilation error > saying that self is undefined. > > As always a code snippet helps :-) > > class foo: > ? ?def __init__(self, maxvalue): > ? ? ? ?self.maxvalue = maxvalue > ? ? ? ?self.value = 0 > > ? ?def put(self, value=self.maxvalue): > ? ? ? ?self.value = value > > So if I call foo.put() the value is set to maxvalue but maxvalue can > be specified when I instantiate foo. > > Explanations and/or workarounds much appreciated. Explanation: The default value is calculated at the time the function is defined, not at the time it is called. And at that time there is no instance for "self" to refer to. Workaround: class foo: def __init__(self, maxvalue): self.maxvalue = maxvalue self.value = 0 def put(self, value=None): if value is None: self.value = self.maxvalue else: self.value = value -- Andr? Engels, andreengels at gmail.com From clp2 at rebertia.com Thu Aug 27 17:49:50 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Aug 2009 14:49:50 -0700 Subject: How to unencode a string In-Reply-To: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> References: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> Message-ID: <50697b2c0908271449x1854d875ncdde2280b46ecdcc@mail.gmail.com> On Thu, Aug 27, 2009 at 2:10 PM, jakecjacobson wrote: > This seems like a real simple newbie question but how can a person > unencode a string? ?In Perl I use something like: "$part=~ s/\%([A-Fa- > f0-9]{2})/pack('C', hex($1))/seg;" > > If I have a string like Word1%20Word2%20Word3 I want to get Word1 > Word2 Word3. ?Would also like to handle special characters like '",(){} > [] etc/ Use the `uu` module together with the `stringio` module: http://docs.python.org/library/uu.html http://docs.python.org/library/stringio.html Not sure about special character handling though. Cheers, Chris -- http://blog.rebertia.com From mdekauwe at gmail.com Thu Aug 27 17:51:08 2009 From: mdekauwe at gmail.com (Mart.) Date: Thu, 27 Aug 2009 14:51:08 -0700 (PDT) Subject: regexp help References: <4e548d26-f3c9-46b8-a82a-c012607e2ff8@o6g2000yqj.googlegroups.com> Message-ID: <93ec85b5-907e-4504-968d-b14f1577debf@z38g2000yqh.googlegroups.com> On Aug 27, 7:15?pm, Bakes wrote: > If I were using the code: > > (?P[0-9]+) > > to get an integer between 0 and 9, how would I allow it to register > negative integers as well? -? From phily05 at gmail.com Thu Aug 27 18:02:41 2009 From: phily05 at gmail.com (Phil) Date: Thu, 27 Aug 2009 15:02:41 -0700 (PDT) Subject: Python on the Web References: Message-ID: <633c57f3-fb46-4d11-93c7-64a07ecd0844@32g2000yqj.googlegroups.com> Haha. While I don't disagree with you, I seem to be under the impression that you think I haven't been reading the web where nearly every blog post complains about the abundance of Python frameworks. The thing is, most of the frameworks being commented on in such a way are 'microframeworks' that provide next to nothing. I'm do not mean to say anything negative about them, but I strongly feel that my approach will be much more functional without having to include, or at least a good starting point for newcomers to both Python and web programming. The ideas I had for mine lied somewhere in between a full stack framework and a minimalist approach like said microframeworks. From python at mrabarnett.plus.com Thu Aug 27 18:05:03 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 Aug 2009 23:05:03 +0100 Subject: How to unencode a string In-Reply-To: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> References: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> Message-ID: <4A97030F.9000805@mrabarnett.plus.com> jakecjacobson wrote: > This seems like a real simple newbie question but how can a person > unencode a string? In Perl I use something like: "$part=~ s/\%([A-Fa- > f0-9]{2})/pack('C', hex($1))/seg;" > > If I have a string like Word1%20Word2%20Word3 I want to get Word1 > Word2 Word3. Would also like to handle special characters like '",(){} > [] etc/ The Python equivalent of your regular expression code is: >>> import re >>> s = "Word1%20Word2%20Word3" >>> re.sub(r"%([A-Fa-f0-9]{2})", lambda m: chr(int(m.group(1), 16)), s) 'Word1 Word2 Word3' The replacement is a lambda expression (an anonymous function), which is called for each match with the match object and it works like this: m # m is the match object m.group(1) # get group 1 (the 2 hex digits) int(m.group(1), 16) # convert to an integer chr(int(m.group(1), 16)) # convert to a character From manu3d at gmail.com Thu Aug 27 18:09:18 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 27 Aug 2009 15:09:18 -0700 (PDT) Subject: Does Class implements Interface? References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> Message-ID: On Aug 27, 9:42?pm, Jonathan Gardner wrote: > Have you heard of duck typing? Yes. > Ignore all those things and rely on human (aka natural language) > documentation. That is, if you want to see if a class will work for an > interface, go read the docs on the interface (or rather, what the > function expects the interface to be) and what the class provides and > see if they fit. Apologies, my fault, I didn't explain that humans are out of the loop entirely. It's only at runtime that the program obtains the class object that might or might not conform to an expected interface. In fact the program might obtain multiple objects and have to decide which one conforms best to the expected interface. Of course I could use hasattr() and the inspect module (anything else?) to find out if existing attributes and method signatures are those expected. Or I could just deal with the exceptions as they are raised. However, if I could somehow rely that the object I'm getting has the right methods and signatures I could avoid peppering the code with try/except constructs. I was just wondering then if this has been somewhat dealt with and has been wrapped in a neat package, set of functions, recipe or pattern. Manu From somebody at somewhere.com Thu Aug 27 18:16:14 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Thu, 27 Aug 2009 23:16:14 +0100 Subject: How to unencode a string References: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> Message-ID: jakecjacobson wrote: > This seems like a real simple newbie question but how can a person > unencode a string? In Perl I use something like: "$part=~ s/\%([A-Fa- > f0-9]{2})/pack('C', hex($1))/seg;" > > If I have a string like Word1%20Word2%20Word3 I want to get Word1 > Word2 Word3. Would also like to handle special characters like '",(){} > [] etc/ import urllib print urllib.unquote("Word1%20Word2%20Word3") -- Stephen Fairchild From jgardner at jonathangardner.net Thu Aug 27 18:22:33 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 27 Aug 2009 15:22:33 -0700 (PDT) Subject: Does Class implements Interface? References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> Message-ID: On Aug 27, 3:09?pm, "Emanuele D'Arrigo" wrote: > > Apologies, my fault, No apology is necessary. > I didn't explain that humans are out of the loop > entirely. It's only at runtime that the program obtains the class > object that might or might not conform to an expected interface. In > fact the program might obtain multiple objects and have to decide > which one conforms best to the expected interface. Of course I could > use hasattr() and the inspect module (anything else?) to find out if > existing attributes and method signatures are those expected. Or I > could just deal with the exceptions as they are raised. However, if I > could somehow rely that the object I'm getting has the right methods > and signatures I could avoid peppering the code with try/except > constructs. > > I was just wondering then if this has been somewhat dealt with and has > been wrapped in a neat package, set of functions, recipe or pattern. > Don't bother with introspection using hasattr() and such. Use exceptions. If the object that is instantiated at run-time doesn't provide the right interface, throw an exception and direct it to the responsible party. This isn't much different than what you'd do if you're writing an app that expects a string of digits but is instead given a string of non- digits. Rather than inspecting the string before converting it (introspection), just try to convert it and catch the exception. Then handle the exception such that you tell the person who entered the data, "I wanted numbers, not letters" and allow them to try again. When you stop asking "Did I get something I expect?" except only when it is absolutely necessary, then you can get back to writing your program. From jgardner at jonathangardner.net Thu Aug 27 18:25:09 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 27 Aug 2009 15:25:09 -0700 (PDT) Subject: Does Class implements Interface? References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> Message-ID: <83dc3cba-a6f5-46ef-8a43-119b78be622d@v15g2000prn.googlegroups.com> On Aug 27, 3:09?pm, "Emanuele D'Arrigo" wrote: > On Aug 27, 9:42?pm, Jonathan Gardner > wrote: > > > Have you heard of duck typing? > > Yes. > > I was just wondering then if this has been somewhat dealt with and has > been wrapped in a neat package, set of functions, recipe or pattern. > As a joke (but only partly), here's the python code you'd use to check to see if a value conforms with expectations: As you can see, the above code is not only easy to write, but easy to write unit tests for, compile, run, and debug. It simply doesn't get better than this. From kccnospam at glenevin.com Thu Aug 27 18:29:53 2009 From: kccnospam at glenevin.com (seanacais) Date: Thu, 27 Aug 2009 15:29:53 -0700 (PDT) Subject: variables of the class are not available as default values? References: Message-ID: On Aug 27, 5:44?pm, Chris Rebert wrote: > On Thu, Aug 27, 2009 at 2:37 PM, seanacais wrote: > > I'm working on a program where I wish to define the default value of a > > method as a value that was set in __init__. ?I get a compilation error > > saying that self is undefined. > > > As always a code snippet helps :-) > > > class foo: > > ? ?def __init__(self, maxvalue): > > ? ? ? ?self.maxvalue = maxvalue > > ? ? ? ?self.value = 0 > > > ? ?def put(self, value=self.maxvalue): > > ? ? ? ?self.value = value > > > So if I call foo.put() the value is set to maxvalue but maxvalue can > > be specified when I instantiate foo. > > python test.py > > Traceback (most recent call last): > > ?File "test.py", line 1, in > > ? ?class foo: > > ?File "test.py", line 6, in foo > > ? ?def put(self, value=self.maxvalue): > > NameError: name 'self' is not defined > > Explanations and/or workarounds much appreciated. > > Workaround: > > class foo: > ? ? def __init__(self, maxvalue): > ? ? ? ? self.maxvalue = maxvalue > ? ? ? ? self.value = 0 > > ? ? def put(self, value=None): > ? ? ? ? self.value = self.value if value is None else value > > Explanation: > > Default values are only evaluated once, when the class is defined, > thus "self" is not defined at that point since the class is still > being defined when the method definition is executed and thus there > can be no instances yet anyway. > > Cheers, > Chris > --http://blog.rebertia.com That clears that up for me. Thank you! From find.mig at paa.google Thu Aug 27 18:31:15 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Fri, 28 Aug 2009 00:31:15 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a92b290$0$305$14726298@news.sunsite.dk> <4a93e575$0$298$14726298@news.sunsite.dk> <4a95961d$0$300$14726298@news.sunsite.dk> Message-ID: <4a970942$0$334$14726298@news.sunsite.dk> Dennis Lee Bieber wrote: > > The only other thing I could suggest is exactly what is done on: > http://pys60.garage.maemo.org/doc/s60/node59.html > > Initialize a counter value to 0, then increment it in the callback, > only doing REAL work every n calls. > > > def doCallback(self): > if self.count % 35 == 0: #doc says 35 hits/second, so this > self.data_callback() #will run one once per second > self.count += 1 > > You'll still get that slew of backlogged callbacks that built up > while doing the real processing, but unless self.data_callback() takes > more time than the "35" covers, most of the callbacks will just come in > and exit with an increment. Of course I can do that. But it'll only make a noticable delay EVERY time the user moves, and not prevent the build up of calls if it doesn't finish within the 35 callbacks. The point is that I don't know in advance, how long the call will take. It depends on the amount of data i load and process during the call. I only know when the calculations have finished, and when they are called, and think there might be some way to block further callbacks until the first one returns? From find.mig at paa.google Thu Aug 27 18:42:16 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Fri, 28 Aug 2009 00:42:16 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a9595ca$0$300$14726298@news.sunsite.dk> Message-ID: <4a970bd7$0$333$14726298@news.sunsite.dk> Hendrik van Rooyen wrote: > > Hmm - now I am really starting to fly by the seat of my pants - but it looks > as if your problem is that your routine is basically being called faster than > what it can do the processing. > > So what I would try is to define a global (you should really acquire a lock, > but forget that for the moment) So lets call this thing running_calculation. > > Then you set this in the routine just before the after call, and reset it just > before exiting the calculation routine, and if it is set when you get into > the first routine, then you just exit, without doing the after. This should > have the effect of skipping some calls, to make it all manageable. Then you > should (hopefully) not have the duplication that it looks to me like you are > now having. > > Bye the way, make the time short - like 1 - it could also be that the time is > now so long before you start calculating, that you do not have a snowball's > hope in hell to be finished before the next value comes in. > OK, now things starts to make sense. You tell me to do something like this? def doCallback(self): if self.process_busy==False: self.process_busy=True self.at.after(0.01,self.data_callback) def doneCallback(self): self.process_busy=False And the after command will cause python to spawn a new thread, which runs self.data_callback, which measn that the doCallback will return immediately, so the next callback from accelerometer can be processed? And when the self.data_callback() finishes, i'd make it call the doneCallback() to release my busy flag, right? I'm gonna try this tomorrow :) From somebody at somewhere.com Thu Aug 27 18:43:30 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Thu, 27 Aug 2009 23:43:30 +0100 Subject: Does Class implements Interface? References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> Message-ID: <6fidnfxppNqOkQrXnZ2dnUVZ8uydnZ2d@giganews.com> Emanuele D'Arrigo wrote: > Apologies, my fault, I didn't explain that humans are out of the loop > entirely. It's only at runtime that the program obtains the class > object that might or might not conform to an expected interface. In > fact the program might obtain multiple objects and have to decide > which one conforms best to the expected interface. Of course I could > use hasattr() and the inspect module (anything else?) to find out if > existing attributes and method signatures are those expected. Or I > could just deal with the exceptions as they are raised. However, if I > could somehow rely that the object I'm getting has the right methods > and signatures I could avoid peppering the code with try/except > constructs. > > I was just wondering then if this has been somewhat dealt with and has > been wrapped in a neat package, set of functions, recipe or pattern. http://docs.python.org/library/abc.html In particular, pay attention to the term virtual subclass and also note in the second code example the use of __subclasshook__ to define virtual subclass membership by the presence (or not) of class attributes. -- Stephen Fairchild From piet at cs.uu.nl Thu Aug 27 18:45:13 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 28 Aug 2009 00:45:13 +0200 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile References: Message-ID: >>>>> Ryniek90 (R) wrote: >>> >>>>>>>> Ryniek90 (R) wrote: >>>>>>>> >>> >>> >R> Hahah right. My fault. Must remember to read documentation so many times >R> until I find the solution. Thanks, now works fine. :-) >>>> >>> >>> And, by the way, how come the traceback refers to >>> File "backuper.py", line 197, in >>> while the posted code has only 188 lines? >>> >R> Cuz my original code is bit longer - i've got some bookkeepings like >R> __author__, __version__ etc., just after module imports. That can be very confusing for people that want to help you. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From piet at cs.uu.nl Thu Aug 27 18:51:55 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 28 Aug 2009 00:51:55 +0200 Subject: How to unencode a string References: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> Message-ID: >>>>> jakecjacobson (j) wrote: >j> This seems like a real simple newbie question but how can a person >j> unencode a string? In Perl I use something like: "$part=~ s/\%([A-Fa- >j> f0-9]{2})/pack('C', hex($1))/seg;" >j> If I have a string like Word1%20Word2%20Word3 I want to get Word1 >j> Word2 Word3. urllib.unquote(string) >j> Would also like to handle special characters like '",(){} >j> [] etc/ What would you like to do with them? Or do you mean to replace %27 by ' etc? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From python at mrabarnett.plus.com Thu Aug 27 18:58:06 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 Aug 2009 23:58:06 +0100 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a970942$0$334$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a92b290$0$305$14726298@news.sunsite.dk> <4a93e575$0$298$14726298@news.sunsite.dk> <4a95961d$0$300$14726298@news.sunsite.dk> <4a970942$0$334$14726298@news.sunsite.dk> Message-ID: <4A970F7E.9070006@mrabarnett.plus.com> Esben von Buchwald wrote: > Dennis Lee Bieber wrote: >> >> The only other thing I could suggest is exactly what is done on: >> http://pys60.garage.maemo.org/doc/s60/node59.html >> >> Initialize a counter value to 0, then increment it in the callback, >> only doing REAL work every n calls. >> >> >> def doCallback(self): >> if self.count % 35 == 0: #doc says 35 hits/second, so this >> self.data_callback() #will run one once per second >> self.count += 1 >> >> You'll still get that slew of backlogged callbacks that built up >> while doing the real processing, but unless self.data_callback() takes >> more time than the "35" covers, most of the callbacks will just come in >> and exit with an increment. > > Of course I can do that. > > > But it'll only make a noticable delay EVERY time the user moves, and not > prevent the build up of calls if it doesn't finish within the 35 callbacks. > > The point is that I don't know in advance, how long the call will take. > It depends on the amount of data i load and process during the call. > I only know when the calculations have finished, and when they are > called, and think there might be some way to block further callbacks > until the first one returns? You could record when your callback finishes (is about to return) and then ignore any callback that happens too soon after that: def doCallback(self): now = time.time() if now - self.last_call >= MIN_TIME: self.data_callback() now = time.time() self.last_call = now From clp2 at rebertia.com Thu Aug 27 19:05:04 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Aug 2009 16:05:04 -0700 Subject: How to unencode a string In-Reply-To: <50697b2c0908271449x1854d875ncdde2280b46ecdcc@mail.gmail.com> References: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> <50697b2c0908271449x1854d875ncdde2280b46ecdcc@mail.gmail.com> Message-ID: <50697b2c0908271605h1055dfd7qc786a7e0e067f4a5@mail.gmail.com> On Thu, Aug 27, 2009 at 2:49 PM, Chris Rebert wrote: > On Thu, Aug 27, 2009 at 2:10 PM, jakecjacobson wrote: >> This seems like a real simple newbie question but how can a person >> unencode a string? ?In Perl I use something like: "$part=~ s/\%([A-Fa- >> f0-9]{2})/pack('C', hex($1))/seg;" >> >> If I have a string like Word1%20Word2%20Word3 I want to get Word1 >> Word2 Word3. ?Would also like to handle special characters like '",(){} >> [] etc/ > > Use the `uu` module together with the `stringio` module: > http://docs.python.org/library/uu.html > http://docs.python.org/library/stringio.html > > Not sure about special character handling though. Ah, I misread our post in haste. Please disregard my reply. - Chris From python at mrabarnett.plus.com Thu Aug 27 19:05:37 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 28 Aug 2009 00:05:37 +0100 Subject: Protecting against callbacks queuing up? In-Reply-To: <4A970F7E.9070006@mrabarnett.plus.com> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a92b290$0$305$14726298@news.sunsite.dk> <4a93e575$0$298$14726298@news.sunsite.dk> <4a95961d$0$300$14726298@news.sunsite.dk> <4a970942$0$334$14726298@news.sunsite.dk> <4A970F7E.9070006@mrabarnett.plus.com> Message-ID: <4A971141.6050402@mrabarnett.plus.com> MRAB wrote: > Esben von Buchwald wrote: >> Dennis Lee Bieber wrote: >>> >>> The only other thing I could suggest is exactly what is done on: >>> http://pys60.garage.maemo.org/doc/s60/node59.html >>> >>> Initialize a counter value to 0, then increment it in the callback, >>> only doing REAL work every n calls. >>> >>> >>> def doCallback(self): >>> if self.count % 35 == 0: #doc says 35 hits/second, so this >>> self.data_callback() #will run one once per second >>> self.count += 1 >>> >>> You'll still get that slew of backlogged callbacks that built up >>> while doing the real processing, but unless self.data_callback() takes >>> more time than the "35" covers, most of the callbacks will just come in >>> and exit with an increment. >> >> Of course I can do that. >> >> >> But it'll only make a noticable delay EVERY time the user moves, and >> not prevent the build up of calls if it doesn't finish within the 35 >> callbacks. >> >> The point is that I don't know in advance, how long the call will >> take. It depends on the amount of data i load and process during the >> call. >> I only know when the calculations have finished, and when they are >> called, and think there might be some way to block further callbacks >> until the first one returns? > > You could record when your callback finishes (is about to return) and > then ignore any callback that happens too soon after that: > > def doCallback(self): > now = time.time() > if now - self.last_call >= MIN_TIME: > self.data_callback() > now = time.time() > self.last_call = now After a little more thought, I think that should be: def doCallback(self): if time.time() - self.last_call >= MIN_TIME: self.data_callback() self.last_call = time.time() From kkumNOTTHISer at thatsearchenginesguglsemail.com Thu Aug 27 19:05:41 2009 From: kkumNOTTHISer at thatsearchenginesguglsemail.com (Kreso) Date: Thu, 27 Aug 2009 23:05:41 +0000 (UTC) Subject: Algorithms as objects? Message-ID: I am writing an application that essentially calculates set of numbers, say N1, N2, ..., where they can be calculated by several different algorithms. (One should be able to choose the algorithm at run time.) In each algorithm one starts from a set of functions, say f1, f2, ..., which are then transformed into some other functions g1(f1, f2, ..), g2(f1, f2, ...), ... , then maybe transformed once more and result is obtained by evaluating final functions. I can naturally think about this as a collection of transformation blocks, which have functions as input and output, and which can be put together to get the final results. However, I am not sure how to program this, especially since one cannot subclass function type. To be clear let me give simplified example of what is needed: f(x) has unknown shape, so one would like to try, say f1(x) = ax - b x**2 or f2(x) = a sin(b*x), where a and b are variable parameters. Then, one would like to create, with known k(x,y), function g(x) in one of two ways: g1(x) = k(x, x)*f(x) or g2(x) = integrate(k(x, y) * f(y), y=0..1), and finally evaluate N=g(1) as result. In this simple example there are 4 different algorithms for f(x) -> g(x) -> N, and one should be able to simply choose between them, e.g. by calling N(g1, f2, (a,b)). In practice algorithm is not necessary so linear, but is generally tree-lika: (a,b) -> f1(x) --->g1(x)---+ |--> h(x) --> N (c,d) ---+--> g2(x)--------+ | f2(x) --+ It would be nice to have some class of function-objects, that f1(x), .., g1(x), ... could be members/instances of so that common operations on these functions could be possible (checking that they satisfy some necessary properties, plotting them, ...), and then second "class" of transformations/methods operating on these objects. I seem to be confused by the fact that I would like to somehow treat algorithms as objects (so that one can experiment with different algorithm systems) but I don't have clear picture how to do it. I am just brainstorming for ideas. Any advice is welcome. From clp2 at rebertia.com Thu Aug 27 19:14:35 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Aug 2009 16:14:35 -0700 Subject: Algorithms as objects? In-Reply-To: References: Message-ID: <50697b2c0908271614q6609884aw36de8ef27b97d930@mail.gmail.com> On Thu, Aug 27, 2009 at 4:05 PM, Kreso wrote: > > I am writing an application that essentially calculates set of numbers, > say N1, N2, ..., where they can be calculated by several different > algorithms. (One should be able to choose the algorithm at run time.) > In each algorithm one starts from a set of functions, say f1, f2, ..., > which are then transformed into some other functions g1(f1, f2, ..), > g2(f1, f2, ...), ... , then maybe transformed once more and result is > obtained by evaluating final functions. > ?I can naturally think about this as a collection of transformation > blocks, which have functions as input and output, and which can be > put together to get the final results. However, I am not sure > how to program this, especially since one cannot subclass function > type. To be clear let me give simplified example of what is needed: > > f(x) has unknown shape, so one would like to try, say > > f1(x) = ax - b x**2 ? or ? ?f2(x) = a sin(b*x), > > where a and b are variable parameters. > > Then, one would like to create, with known k(x,y), function g(x) > in one of two ways: > > g1(x) = k(x, x)*f(x) ?or ? g2(x) = integrate(k(x, y) * f(y), y=0..1), > > and finally evaluate N=g(1) as result. In this simple example > there are 4 different algorithms ?for f(x) -> g(x) -> N, and one > should be able to simply choose between them, e.g. by calling > N(g1, f2, (a,b)). > > In practice algorithm is not necessary so linear, ?but is > generally tree-lika: > > (a,b) -> f1(x) --->g1(x)---+ > ? ? ? ? ? ? ? ? ? ? ? ? ? |--> h(x) --> N > (c,d) ---+--> g2(x)--------+ > ? ? ? ? | > ?f2(x) --+ > > > It would be nice to have some class of function-objects, > that f1(x), .., g1(x), ... could be members/instances of so that common > operations on these functions could be possible (checking > that they satisfy some necessary properties, plotting them, ...), > and then second "class" of transformations/methods operating on > these objects. > I seem to be confused by the fact that I would like to somehow treat > algorithms as objects (so that one can experiment with different > algorithm systems) but I don't have clear picture how to do it. > I am just brainstorming for ideas. Any advice is welcome. It sounds like you're describing the Strategy Pattern (http://en.wikipedia.org/wiki/Strategy_pattern). To have objects callable like functions, just implement the __call__ special method in your class(es): http://docs.python.org/reference/datamodel.html#object.__call__ Cheers, Chris -- http://blog.rebertia.com From mensanator at aol.com Thu Aug 27 19:19:26 2009 From: mensanator at aol.com (Mensanator) Date: Thu, 27 Aug 2009 16:19:26 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> Message-ID: <4ee81a75-e22d-4bf7-8b40-b883cc6e69c6@k30g2000yqf.googlegroups.com> On Aug 27, 2:26?pm, Piet van Oostrum wrote: > >>>>> Mensanator (M) wrote: > >M> On Aug 26, 4:59?pm, Piet van Oostrum wrote: > >>> >>>>> Mensanator (M) wrote: > >>> >M> That's my point. Since the common usage of "binary" is for > >>> >M> Standard Positional Number System of Radix 2, it follows > >>> >M> that "unary" is the common usage for Standard Positional > >>> >M> Number System of Radix 1. That's VERY confusing since such > >>> >M> a system is undefined. Remember, common usage does not > >>> >M> necessarily properly define things. Saying simply "unary" > >>> >M> sounds like you're extending common usage beyond its proper > >>> >M> boundaries. > > >>> But the customary meaning of `unary' is the tally system, as a radix > >>> system wouldn't make sense. I don't know when this term came into use > >>> but I have known it for a long time. > >M> Ok, I'll accept that and in the same breath say such common usage > >M> is stupid. I, for one, have never heard such usage and would never > >M> use "unary" in the same breath as "decimal, octal, binary" even if > >M> I had. > > As I see it, unary just means that there is one symbol. Binary just > means that there are two symbols, etc. Right, and neither word, by itself, gives the full meaning. > > With unary, the only sensible numerical interpretation is to count the > number of occurrences of that symbol, or if you also want to have the > number 0, the number of occurrences - 1. Trouble is, nothing's stopping you from making a non-sensible interpretation. > > With binary and higher you can come up with more numerical > interpretations but the most efficient one is the radix interpretation > (for different values of `efficient'). I doubt that there are many other > interpretations that you can call sensible. But not impossible. You could have a base-3 tally system for ticking off how many cars on a three lane road pass a given point. And you can have mixed radix systems (pounds, shillings, pence or degrees, minutes seconds). > Therefore we immediately > think of a radix system when we talk about binary, octal, decimal etc. > But the word `binary' itself doesn't imply that. Just as unary doesn't imply that it's an extension of binary made by simply changing the base because there's more to it than that. Yet, I constantly run into people who get confused by this. As a result, I will never use the word "unary" even if it is considered acceptable. If I'm trying to imply some sort of base-1 system, I'll explain what I'm talking about and not assume the listener will fully understand what is meant by "unary". > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org From barcaroller at music.net Thu Aug 27 19:20:00 2009 From: barcaroller at music.net (barcaroller) Date: Thu, 27 Aug 2009 19:20:00 -0400 Subject: PyGTK problems after Linux update... Message-ID: I use a python-based program called 'meld' which worked fine until my latest Fedora11/KDE4.3 update; it now gives me the following error: prompt> meld /usr/lib/python2.6/site-packages/gtk-2.0/glib/_glib.so: undefined symbol: PyUnicodeUCS4_DecodeUTF8 Meld requires pygtk 2.8.0 or higher. If I run another GTK-based utility, I also get errors: prompt> gedit ** (gedit:28289): WARNING **: Error initializing Python interpreter: could not import pygtk. I have installed the latest PyGTK (pygtk-2.14.1), to no avail. Googling these messages have also produced no major results. When I run 'pygtk-demo', I get the following errors: prompt> python /usr/lib/pygtk/2.0/pygtk-demo.py Traceback (most recent call last): File "/usr/lib/pygtk/2.0/pygtk-demo.py", line 18, in import gobject File "/usr/lib/python2.6/site-packages/gtk-2.0/gobject/__init__.py", line 33, in from glib import spawn_async, idle_add, timeout_add, timeout_add_seconds, \ File "/usr/lib/python2.6/site-packages/gtk-2.0/glib/__init__.py", line 30, in from glib._glib import * ImportError: /usr/lib/python2.6/site-packages/gtk-2.0/glib/_glib.so: undefined symbol: PyUnicodeUCS4_DecodeUTF8 Does anyone know what needs to be done to resolve this? Using Python 2.6.2 on Fedora11/KDE4.3 32-bit i386/i586/i686. From upton at virginia.edu Thu Aug 27 19:35:04 2009 From: upton at virginia.edu (Dan Upton) Date: Thu, 27 Aug 2009 16:35:04 -0700 Subject: printing from child process in Tkinter window Message-ID: <5504f9ac0908271635j1926850y45c048f41c1ef0e@mail.gmail.com> Hi all, I've been messing with this for a couple hours now but can't make it work. Basically I have a Tkinter GUI that creates a child process via subprocess.Popen, and I would like to capture the child process's output to display it in a Text widget in the GUI. Relevant snippets: def click_start: #launch from clicking a button in the gui ... self.apppipe = Popen(cmdString, shell=True, stdout=PIPE, stderr=PIPE) self.master.after(200, self.readAppStdout) ... def readAppStdout(self): readers, writers, exceptionals = select.select( [self.apppipe.stdout], [], [], 0.001) if readers != []: pipetext = self.apppipe.stdout.readline() self.appoutput.insert(END, pipetext) #self.appoutput is the Text widget (same for apppipe.stderr) self.master.after(200, self.readAppStdout) I don't ever get any output in my window, even though I've waited long enough that the application would otherwise have printed to the console (based on its graphical outputs). Any suggestions for what I'm doing wrong? -dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From hjtoi-better-remove-before-reply at comcast.net Thu Aug 27 19:43:40 2009 From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen) Date: Thu, 27 Aug 2009 16:43:40 -0700 Subject: ANN: M2Crypto 0.20.1 Message-ID: M2Crypto is the most complete Python wrapper for OpenSSL featuring RSA, DSA, DH, HMACs, message digests, symmetric ciphers (including AES); SSL functionality to implement clients and servers; HTTPS extensions to Python's httplib, urllib, and xmlrpclib; unforgeable HMAC'ing AuthCookies for web session management; FTP/TLS client and server; S/MIME; ZServerSSL: A HTTPS server for Zope and ZSmime: An S/MIME messenger for Zope. Smartcards supported with the Engine interface. This is the 0.20.1 release. Download links and bug filing instructions on the homepage at http://chandlerproject.org/Projects/MeTooCrypto. Changelog: - Fix regression in httpslib.ProxyHTTPSConnection, by Miloslav Trmac -- Heikki Toivonen - http://heikkitoivonen.net From no.email at please.post Thu Aug 27 19:49:27 2009 From: no.email at please.post (kj) Date: Thu, 27 Aug 2009 23:49:27 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: Miles Kaufmann writes: >On Aug 26, 2009, at 1:11 PM, kj wrote: >> I think I understand the answers well enough. What I *really* >> don't understand is why this particular "feature" of Python (i.e. >> that functions defined within a class statement are forbidden from >> "seeing" other identifiers defined within the class statement) is >> generally considered to be perfectly OK. IMO it's a bizarre, >> inexplicable blindspot (which, among other things, gives rise to >> a certain worry about what other similar craziness lurks under >> Python's image of rationality). I have never seen even a half-hearted >> justification, from a language design point of view, for why this >> particular "feature" is worth having. >Guido's design justifications: >http://mail.python.org/pipermail/python-dev/2000-November/010598.html Ah! Clarity! Thanks! How did you find this? Did you know of this post already? Or is there some special way to search Guido's "design justifications"? >...because the suite >namespace and the class namespace would get out of sync when different >objects were assigned to the class namespace: >class C: > x = 1 > def foo(self): > print x > print self.x > >>> o = C() > >>> o.foo() >1 >1 > >>> o.x = 2 > >>> o.foo() >1 >2 But this unfortunate situation is already possible, because one can already define class C: x = 1 def foo(self): print C.x print self.x which would lead to exactly the same thing. I need to learn more about metaclasses, though, to fully understand your post. Many thanks! kynn From bearophileHUGS at lycos.com Thu Aug 27 20:00:36 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Thu, 27 Aug 2009 17:00:36 -0700 (PDT) Subject: Algorithms as objects? References: Message-ID: <9bd48179-a356-4d7f-8057-f68db29d6cad@a13g2000yqc.googlegroups.com> Chris Rebert: > It sounds like you're describing the Strategy Pattern > (http://en.wikipedia.org/wiki/Strategy_pattern). > > To have objects callable like functions, just implement the ?__call__ > special method in your class(es): Please, can't you just use a bit of functional-style programming? Like creating nested functions on the fly, etc. Bye, bearophile From doctoresam at gmail.com Thu Aug 27 20:34:17 2009 From: doctoresam at gmail.com (Deep_Feelings) Date: Thu, 27 Aug 2009 17:34:17 -0700 (PDT) Subject: why python got less developers ? Message-ID: python got relatively fewer numbers of developers than other high level languages like .NET , java .. etc why ? From mwilson at the-wire.com Thu Aug 27 20:39:56 2009 From: mwilson at the-wire.com (Mel) Date: Thu, 27 Aug 2009 20:39:56 -0400 Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <02a0ce27$0$30337$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Leading zeroes in decimal numbers are *very* common in dates and times. In banking too, according to someone at work today. Mel. From clp2 at rebertia.com Thu Aug 27 20:46:36 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Aug 2009 17:46:36 -0700 Subject: why python got less developers ? In-Reply-To: References: Message-ID: <50697b2c0908271746v7116a1ffo62d5dced879a2c6a@mail.gmail.com> On Thu, Aug 27, 2009 at 5:34 PM, Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc ?why ? We lack Sun and Microsoft's massive marketing departments. :) Cheers, Chris -- http://blog.rebertia.com From python at mrabarnett.plus.com Thu Aug 27 20:47:51 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 28 Aug 2009 01:47:51 +0100 Subject: why python got less developers ? In-Reply-To: References: Message-ID: <4A972937.9070405@mrabarnett.plus.com> Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc why ? Fewer needed? From gherron at islandtraining.com Thu Aug 27 20:49:02 2009 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 27 Aug 2009 17:49:02 -0700 Subject: why python got less developers ? In-Reply-To: References: Message-ID: <4A97297E.9020607@islandtraining.com> Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc why ? > Perhaps because we value QUALITY over QUANTITY ... Gary Herron From rurpy at yahoo.com Thu Aug 27 20:49:26 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Thu, 27 Aug 2009 17:49:26 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> Message-ID: <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> On 08/26/2009 11:51 PM, "Martin v. L?wis" wrote: >[...] >> But regardless, the significant question is, what is >> the reason for having ord() (and unichr) not work for >> surrogate pairs and thus not usable with a large number >> of unicode characters that Python otherwise supports? > > See PEP 261, http://www.python.org/dev/peps/pep-0261/ > It specifies all this. The PEP (AFAICT) says only what we already know... that on narrow builds unichr() will raise an exception with an argument >= 0x10000, and ord() is unichr()'s inverse. I have read the PEP twice now and still see no justification for that decision, it appears to have been made by fiat.[*1] Could you or someone please point me to specific justification for having unichr and ord work only for a subset of unicode characters on narrow builds, as opposed to the more general and IMO useful behavior proposed earlier in this thread? ---------------------------------------------------------- [*1] The PEP says: * unichr(i) for 0 <= i < 2**16 (0x10000) always returns a length-one string. * unichr(i) for 2**16 <= i <= TOPCHAR will return a length-one string on wide Python builds. On narrow builds it will raise ValueError. and * ord() is always the inverse of unichr() which of course we know; that is the current behavior. But there is no reason given for that behavior. Under the second *unicode bullet point, there are two issues raised: 1) Should surrogate pairs be disallowed on narrow builds? That appears to have been answered in the negative and is not relevant to my question. 2) Should access to code points above TOPCHAR be allowed? Not relevant to my question. * every Python Unicode character represents exactly one Unicode code point (i.e. Python Unicode Character = Abstract Unicode character) I'm not sure what this means (what's an abstract unicode character?). If it mandates that u'\ud800\udc40' be treated as a len() 2 string, that is that current case but does not say anything about how unichr and ord should behave. If it mandates that that string must always be treated as two separate code points then Python itself violates by printing that string as u'\U00010040' rather than u'\ud800\udc40'. Finally we read: * There is a convention in the Unicode world for encoding a 32-bit code point in terms of two 16-bit code points. These are known as "surrogate pairs". Python's codecs will adopt this convention. Is a distinction made between Python and Python codecs with only the latter having any knowledge of surrogate pairs? I guess that would explain why Python prints a surrogate pair as a single character. But this seems arbitrary and counter-useful if applied to ord() and unichr(). What possible use-case is there for *not* recognizing surrogate pairs in those two functions? Nothing else in the PEP seems remotely relevant. From ben+python at benfinney.id.au Thu Aug 27 20:55:35 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 28 Aug 2009 10:55:35 +1000 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: <87bpm0daew.fsf@benfinney.id.au> Terry Reedy writes: > In particular, because there is no indication that it is an exact > duplicate of what I will also find on the list itself. Please use > reply instead of reply-all. Better: If you don't want to reply to the author directly, and you don't want to reply to everyone, don't use ?reply to author? or ?reply to all?. When replying to the list, use the ?reply to list? command of your mail client. This will, in a standards-compliant mail client, reply to the posting address for the list (declared in the message header via the RFC 2369 ?List-Post? field, added automatically by every common mailing list system), without a copy to the sender. Thunderbird has a long-outstanding bug report requesting this feature , which is apparently fixed in recent versions. Before that bug was fixed, an add-on was developed to add it in a different way. If you're using a different mail client, look for the ?reply to list? command, and if it's not there (or doesn't work correctly), report it to the vendor as a bug and/or switch to one of the many alternative MUAs that get it right. -- \ ?I think it would be a good idea.? ?Mahatma Gandhi (when asked | `\ what he thought of Western civilization) | _o__) | Ben Finney From contact at xavierho.com Thu Aug 27 21:16:41 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 11:16:41 +1000 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <2d56febf0908271816m68b761deq778f5105c2957baa@mail.gmail.com> On Fri, Aug 28, 2009 at 9:49 AM, kj wrote: > > Miles Kaufmann writes: > > >...because the suite > >namespace and the class namespace would get out of sync when different > >objects were assigned to the class namespace: > > >class C: > > x = 1 > > def foo(self): > > print x > > print self.x > > > >>> o = C() > > >>> o.foo() > >1 > >1 > > >>> o.x = 2 > > >>> o.foo() > >1 > >2 > I haven't tested either codes, but that isn't "out of sync". Your x = 1 is a static variable, and shared between all isntances of class C. > But this unfortunate situation is already possible, because one > can already define > > class C: > x = 1 > def foo(self): > print C.x > print self.x > > which would lead to exactly the same thing. > It works because you're simply explicitly referring to the class's local scope, which leads to the same result. Again, that's just my understanding of the implementation. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Thu Aug 27 21:48:08 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 27 Aug 2009 18:48:08 -0700 (PDT) Subject: regexp help References: <4e548d26-f3c9-46b8-a82a-c012607e2ff8@o6g2000yqj.googlegroups.com> Message-ID: On Aug 27, 1:15?pm, Bakes wrote: > If I were using the code: > > (?P[0-9]+) > > to get an integer between 0 and 9, how would I allow it to register > negative integers as well? With that + sign in there, you will actually get an integer from 0 to 99999999999999999... -- Paul From pydecker at gmail.com Thu Aug 27 21:48:40 2009 From: pydecker at gmail.com (Peter Decker) Date: Thu, 27 Aug 2009 21:48:40 -0400 Subject: Python for professsional Windows GUI apps? In-Reply-To: References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: On Wed, Aug 26, 2009 at 4:47 PM, David C Ullrich wrote: > On Mon, 24 Aug 2009 22:22:20 -0700, sturlamolden wrote: > >> On 25 Aug, 05:56, Peter Decker wrote: >> >>> I use the Dabo Class Designer to visually design my forms. So what's >>> you're point? :) >> >> Nothing, except lobbying for wxFormBuilder for anyone who still doesn't >> know of it. :) > > That's great. But do you know of anything I can use as a > visual form design tool in wxPython? You mean you prefer the wxPython style of coding? No, I don't know what's available. Once I discovered that Dabo is the smart way to get all the benefits of wxPython without the ugly C++ style of coding, I haven't used raw wxPython. -- # p.d. From doctoresam at gmail.com Thu Aug 27 22:12:57 2009 From: doctoresam at gmail.com (Esam Qanadeely) Date: Thu, 27 Aug 2009 19:12:57 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: On Aug 28, 3:46?am, Chris Rebert wrote: > On Thu, Aug 27, 2009 at 5:34 PM, Deep_Feelings wrote: > > python got relatively fewer numbers of developers than other high > > level languages like .NET , java .. etc ?why ? > > We lack Sun and Microsoft's massive marketing departments. :) > > Cheers, > Chris > --http://blog.rebertia.com any technical reasons ?? From somebody at somewhere.com Thu Aug 27 22:23:00 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Fri, 28 Aug 2009 03:23:00 +0100 Subject: Need help with Python scoping rules References: Message-ID: kj wrote: > But this unfortunate situation is already possible, because one > can already define > > class C: > x = 1 > def foo(self): > print C.x > print self.x How is this a problem? There is no ambiguity between the global scope and the local from within foo. >From within foo C is accessed from the global scope having not found it as a local. Once you have C C.x is just one step away. Variable self is local to function foo since it was passed in as a parameter from the method which wraps it. Variable self refers to a class instance which contains a dictionary. Variable x is absent from the instance dictionary so the class self.__class__ is referenced, again from local scope to find x. If it wasn't found there the superclasses would have been searched before throwing an attribute error. It seems to me, you are confusing instance creation with class creation. -- Stephen Fairchild From benjamin.kaplan at case.edu Thu Aug 27 22:33:57 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 27 Aug 2009 22:33:57 -0400 Subject: why python got less developers ? In-Reply-To: References: Message-ID: On Thu, Aug 27, 2009 at 10:12 PM, Esam Qanadeely wrote: > On Aug 28, 3:46?am, Chris Rebert wrote: >> On Thu, Aug 27, 2009 at 5:34 PM, Deep_Feelings wrote: >> > python got relatively fewer numbers of developers than other high >> > level languages like .NET , java .. etc ?why ? >> >> We lack Sun and Microsoft's massive marketing departments. :) >> >> Cheers, >> Chris >> --http://blog.rebertia.com > > any technical reasons ?? > -- Not really. It's mostly because of the lack of marketing departments and pieces of paper to placate business majors (what Microsoft and Sun call "certification") > http://mail.python.org/mailman/listinfo/python-list > From milesck at umich.edu Thu Aug 27 23:27:23 2009 From: milesck at umich.edu (Miles Kaufmann) Date: Thu, 27 Aug 2009 20:27:23 -0700 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: On Aug 27, 2009, at 4:49 PM, kj wrote: > Miles Kaufmann writes: >> Guido's design justifications: >> http://mail.python.org/pipermail/python-dev/2000-November/010598.html > > Ah! Clarity! Thanks! How did you find this? Did you know of > this post already? Or is there some special way to search Guido's > "design justifications"? I just checked the python-dev archives around the time that PEP 227 was written. >> ...because the suite >> namespace and the class namespace would get out of sync when >> different >> objects were assigned to the class namespace: > >> class C: >> x = 1 >> def foo(self): >> print x >> print self.x > >>>>> o = C() >>>>> o.foo() >> 1 >> 1 >>>>> o.x = 2 >>>>> o.foo() >> 1 >> 2 > > But this unfortunate situation is already possible, because one > can already define > > class C: > x = 1 > def foo(self): > print C.x > print self.x > > which would lead to exactly the same thing. You're right, of course. If I had been thinking properly, I would have posted this: ... the suite namespace and the class namespace would get out of sync when different objects were assigned to the class namespace: # In a hypothetical Python with nested class suite scoping: class C: x = 1 @classmethod def foo(cls): print x print cls.x >>> C.foo() 1 1 >>> C.x = 2 >>> C.foo() 1 2 With your example, the result is at least easily explainable: self.x is originally 1 because the object namespace inherits from the class namespace, but running 'o.x = 2' rebinds 'x' in the object namespace (without affecting the class namespace). It's a distinction that sometimes trips up newbies (and me, apparently ;) ), but it's straightforward to comprehend once explained. But the distinction between the class suite namespace and the class namespace is far more subtle; extending the lifetime of the first so that it still exists after the second is created is, IMO, asking for trouble (and trying to unify the two double so). -Miles From rt8396 at gmail.com Thu Aug 27 23:41:47 2009 From: rt8396 at gmail.com (r) Date: Thu, 27 Aug 2009 20:41:47 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> On Aug 27, 7:34?pm, Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc ?why ? Ugh? Well maybe if you put some deep_thoughts into this conundrum you may reveal the answer to your self. Python is an interpreted "scripting", "glue", and "sys administation" language. As long as Java can be complied strait to machine code and constantly run light years faster than Python Java will always win in this area. But who cares, Python is not meant for writing OS's or 3D games of the year, and i am quite happy it is made to be that way. Python will never be as popular as C, Java, etc for all these reasons. And since your chances of making a living writing Java code verses Python code are absolute, then of course that is where the pros will go. From contact at xavierho.com Thu Aug 27 23:48:31 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 13:48:31 +1000 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <2d56febf0908272048m656cecb9nc68f1fd3bfdf02bb@mail.gmail.com> On Fri, Aug 28, 2009 at 1:27 PM, Miles Kaufmann wrote: > You're right, of course. If I had been thinking properly, I would have > posted this: > > ... the suite namespace and the class namespace would get out of sync when > different objects were assigned to the class namespace: I'm not an expert on Python, but could you define "out of sync" for me? When you call the class as a new instance and assign it to a new variable, the class attributes (self.x) are independent for each instance. The static variables in the class (x, or C.x in this case) is shared between all instances of this class. > # In a hypothetical Python with nested class suite scoping: Class already provides some kind of scoping/namespace, that is the locals() method for the class. What is pypothetical about this, if you could elaborate? With your example, the result is at least easily explainable: self.x is > originally 1 Incorrect. "self.x" (or cls.x in your sample code) doesn't exist until you called o.x = 2, which sets "cls.x = 2". Don't be confused between static variables that are initialised at class creation, and the class attributes which usually is declared inside the __init__ method. > because the object namespace inherits from the class namespace, but running > 'o.x = 2' rebinds 'x' in the object namespace (without affecting the class > namespace). See above comment. > It's a distinction that sometimes trips up newbies (and me, apparently ;) > ), but it's straightforward to comprehend once explained. But the > distinction between the class suite namespace and the class namespace is far > more subtle; extending the lifetime of the first so that it still exists > after the second is created is, IMO, asking for trouble (and trying to unify > the two double so). It is. I had trouble getting it also, but once I think of all the variables outside of the __init__() method as "static", and the ones within as "class attributes", everything clears out just fine. =] Any corrections appreciated. I'm merely posting my understanding of Python. Cheers, - Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Thu Aug 27 23:51:56 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 13:51:56 +1000 Subject: Need help with Python scoping rules In-Reply-To: <2d56febf0908272048m656cecb9nc68f1fd3bfdf02bb@mail.gmail.com> References: <2d56febf0908272048m656cecb9nc68f1fd3bfdf02bb@mail.gmail.com> Message-ID: <2d56febf0908272051h26f84ad9t218f39e86e74b2@mail.gmail.com> On Fri, Aug 28, 2009 at 1:48 PM, Xavier Ho wrote: > > Class already provides some kind of scoping/namespace, that is the locals() > method for the class. What is pypothetical about this, if you could > elaborate? > Obviously that was supposed to be "hypothetical". Oops. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dukeofperl at ml1.net Thu Aug 27 23:52:56 2009 From: dukeofperl at ml1.net (Duke Normandin) Date: Fri, 28 Aug 2009 03:52:56 GMT Subject: Transforming a str to an operator Message-ID: Hey.... I'm a Python noob.... So far so good! I've written the following: num1 = raw_input('Enter the first number: ') num2 = raw_input('Enter the second number: ') op = raw_input('Select one of the following [+-*/]: ') print 'The answer is: ', int(num1), eval(op), int(num2) ^^^^^^^^ How do I convert the contents of "op" from a string to an actual arithmetic operator? eval() does not seem to be the answer. TIA! -- duke From contact at xavierho.com Fri Aug 28 00:01:16 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 14:01:16 +1000 Subject: Transforming a str to an operator In-Reply-To: References: Message-ID: <2d56febf0908272101y3f237951o32c04f30bd42a69e@mail.gmail.com> On Fri, Aug 28, 2009 at 1:52 PM, Duke Normandin wrote: > How do I convert the contents of "op" from a string to an actual > arithmetic operator? eval() does not seem to be the answer. TIA! Maybe you were looking for print eval(num1 + op + num2) # it's a little ugly string concatenation. Hm? (untested, but it works in my head.) Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Fri Aug 28 00:08:54 2009 From: rt8396 at gmail.com (r) Date: Thu, 27 Aug 2009 21:08:54 -0700 (PDT) Subject: Transforming a str to an operator References: Message-ID: <6ee483f7-e92c-49e0-be27-125f3389b1f2@33g2000vbe.googlegroups.com> On Aug 27, 10:52?pm, Duke Normandin wrote: > How do I convert the contents of "op" from a string to an actual > arithmetic operator? eval() does not seem to be the answer. TIA! Try this.. >>> op = '+' >>> one = '1' >>> two = '2' >>> one+op+two '1+2' >>> eval(one+op+two) 3 you could also use string formatting. From sjmachin at lexicon.net Fri Aug 28 00:30:48 2009 From: sjmachin at lexicon.net (John Machin) Date: Thu, 27 Aug 2009 21:30:48 -0700 (PDT) Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> Message-ID: <9f3083b4-4886-41c3-9404-d7eac300964b@l35g2000pra.googlegroups.com> On Aug 28, 6:44?am, Mark Lawrence wrote: > vsoler wrote: > > On Aug 27, 9:42 pm, Andreas Waldenburger > > > 1- the csv file was generated with Excel 2007; no prompts for what the > > separator should be; Excel has used ";" by default, without asking > > anything > > I find this difficult to believe, Mark, there exist parallel universes the denizens of which use strange notation e.g. 1.234,56 instead of 1,234.56 and would you believe they use ';' instead of ',' as a list separator ... Excel perfidiously gives them what they expect rather than forcing them to comply with The One True Way. From apt.shansen at gmail.com Fri Aug 28 00:32:55 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Thu, 27 Aug 2009 21:32:55 -0700 Subject: Transforming a str to an operator In-Reply-To: References: Message-ID: <7a9c25c20908272132p737fe070w5a3c7b0a4970a2c9@mail.gmail.com> > > num1 = raw_input('Enter the first number: ') > num2 = raw_input('Enter the second number: ') > op = raw_input('Select one of the following [+-*/]: ') > print 'The answer is: ', int(num1), eval(op), int(num2) > ^^^^^^^^ > > How do I convert the contents of "op" from a string to an actual > arithmetic operator? eval() does not seem to be the answer. TIA! > You could eval(num1+op+num2), but it'd be safer to do: import operator operators = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div} fn = operators[op] print "The answer is:", fn(int(num1), int(num2)) Its best to avoid eval when possible :) --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Fri Aug 28 00:35:24 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 28 Aug 2009 14:35:24 +1000 Subject: Transforming a str to an operator References: Message-ID: <87skfcblo3.fsf@benfinney.id.au> Duke Normandin writes: > Hey.... > > I'm a Python noob.... > > So far so good! > > I've written the following: > > num1 = raw_input('Enter the first number: ') > num2 = raw_input('Enter the second number: ') > op = raw_input('Select one of the following [+-*/]: ') > print 'The answer is: ', int(num1), eval(op), int(num2) > ^^^^^^^^ > > How do I convert the contents of "op" from a string to an actual > arithmetic operator? eval() does not seem to be the answer. TIA! In general, ?eval? on unsanitised input is not the answer. I would use the following approach: import operator op_funcs = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div, } num_1 = int(raw_input('Enter the first number: ')) num_2 = int(raw_input('Enter the second number: ')) op_prompt = ( "Select an operator " + "[" + "".join(s for s in op_funcs.keys()) + "]" + ": ") op_symbol = raw_input(op_prompt) op_func = op_funcs[op_symbol] print 'The answer is: ', op_func(num_1, num_2) This has several advantages: * The input isn't evaluated directly as code. * The operator symbols are specified in one place, the ?op_funcs? mapping; if you want to change the set of possible operators, you just change it there. * If the input results in an operator that's not defined, it won't attempt to perform it; instead, a simple KeyError will result when trying to find the corresponding operator function. -- \ ?I do not believe in immortality of the individual, and I | `\ consider ethics to be an exclusively human concern with no | _o__) superhuman authority behind it.? ?Albert Einstein, letter, 1953 | Ben Finney From stefan_ml at behnel.de Fri Aug 28 00:49:45 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 28 Aug 2009 06:49:45 +0200 Subject: why python got less developers ? In-Reply-To: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> References: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> Message-ID: <4a9761e8$0$31876$9b4e6d93@newsspool3.arcor-online.net> r wrote: > As long as Java > can be complied strait to machine code I think you meant "compared" here. Stefan From contact at xavierho.com Fri Aug 28 00:50:37 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 14:50:37 +1000 Subject: Transforming a str to an operator In-Reply-To: <87skfcblo3.fsf@benfinney.id.au> References: <87skfcblo3.fsf@benfinney.id.au> Message-ID: <2d56febf0908272150y59e5d458hab1fc6aa9c14187e@mail.gmail.com> On Fri, Aug 28, 2009 at 2:35 PM, Ben Finney > wrote: > import operator > > op_funcs = { > '+': operator.add, > '-': operator.sub, > '*': operator.mul, > '/': operator.div, > } > > num_1 = int(raw_input('Enter the first number: ')) > num_2 = int(raw_input('Enter the second number: ')) > op_prompt = "Select an operator ({}):".format(','.join(op for op in > op_funcs)) > op_symbol = raw_input(op_prompt) > op_func = op_funcs[op_symbol] > print 'The answer is: ', op_func(num_1, num_2) Just fixing the code a little to be more "Pythonic" ;). Might also want to do exception handling, but with a program this small, meh. -------------- next part -------------- An HTML attachment was scrubbed... URL: From doctoresam at gmail.com Fri Aug 28 01:03:54 2009 From: doctoresam at gmail.com (Esam Qanadeely) Date: Thu, 27 Aug 2009 22:03:54 -0700 (PDT) Subject: why python got less developers ? References: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> Message-ID: who cares if a language is compiled or interpreted as long as it runs and perform the function. second thing is : even if java is faster than python , unless you are making performance critical operations : who cares? computers are getting faster all the time and languages like python or ruby are fast enough. any comment ? From doctoresam at gmail.com Fri Aug 28 01:05:29 2009 From: doctoresam at gmail.com (Esam Qanadeely) Date: Thu, 27 Aug 2009 22:05:29 -0700 (PDT) Subject: why python got less developers ? References: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> Message-ID: <42a1c81d-b2ec-46b7-9cf2-6e099bd260a3@j21g2000yqe.googlegroups.com> i meant fast enough for most (but not all) applications From rt8396 at gmail.com Fri Aug 28 01:08:01 2009 From: rt8396 at gmail.com (r) Date: Thu, 27 Aug 2009 22:08:01 -0700 (PDT) Subject: Transforming a str to an operator References: <87skfcblo3.fsf@benfinney.id.au> Message-ID: <91126ac3-e7fe-4b7a-a37d-d1e60beaa278@w41g2000yqb.googlegroups.com> On Aug 27, 11:35?pm, Ben Finney wrote: > In general, ?eval? on unsanitised input is not the answer. Yes i agree. > I would use the following approach: Abviously the OP is a python baby noob and casting your irrational fear (and many others irrational fears) of eval at him is akin to tales of Chupacabras running a muck in the jungle sucking the blood from live goats in the twilight hours. I use eval all the time and quite love it. This is nothing more than a throw away academic exercise that will serve no useful purpose for him in the future, but serves the very useful purpose now of establishing an IO between the student and Python interpretor. I'll bet most your example (albeit a good example) flew miles above his head into la-la land. The OP has plenty of time to learn about malicious input and protecting against it, right now the fundamentals are well... fundamental :) From timr at probo.com Fri Aug 28 01:27:45 2009 From: timr at probo.com (Tim Roberts) Date: Thu, 27 Aug 2009 22:27:45 -0700 Subject: why python got less developers ? References: Message-ID: Deep_Feelings wrote: > >python got relatively fewer numbers of developers than other high >level languages like .NET , java .. etc why ? How do you know, and why does it matter? By the way, .NET is not a language. I assume you meant C#. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From max at landaeus.com Fri Aug 28 01:36:33 2009 From: max at landaeus.com (Max Landaeus) Date: Fri, 28 Aug 2009 13:36:33 +0800 Subject: Does Class implements Interface? In-Reply-To: References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> Message-ID: <4A976CE1.2050506@landaeus.com> Emanuele D'Arrigo wrote: > On Aug 27, 9:42 pm, Jonathan Gardner > wrote: > >> Have you heard of duck typing? >> > > Yes. > > >> Ignore all those things and rely on human (aka natural language) >> documentation. That is, if you want to see if a class will work for an >> interface, go read the docs on the interface (or rather, what the >> function expects the interface to be) and what the class provides and >> see if they fit. >> > > Apologies, my fault, I didn't explain that humans are out of the loop > entirely. It's only at runtime that the program obtains the class > object that might or might not conform to an expected interface. In > fact the program might obtain multiple objects and have to decide > which one conforms best to the expected interface. Of course I could > use hasattr() and the inspect module (anything else?) to find out if > existing attributes and method signatures are those expected. Or I > could just deal with the exceptions as they are raised. However, if I > could somehow rely that the object I'm getting has the right methods > and signatures I could avoid peppering the code with try/except > constructs. > > I was just wondering then if this has been somewhat dealt with and has > been wrapped in a neat package, set of functions, recipe or pattern. > > Manu > Check out Alex Martelli's recipe 'Checking wheter an object has necessary attributes' in the Python Cookbook: http://books.google.co.uk/books?id=Q0s6Vgb98CQC&printsec=frontcover&dq=python+cookbook#v=onepage&q=&f=false Max From doctoresam at gmail.com Fri Aug 28 01:44:59 2009 From: doctoresam at gmail.com (Esam Qanadeely) Date: Thu, 27 Aug 2009 22:44:59 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: <1ccf54f5-b1f5-4c4a-b782-fde1a1648cf6@l5g2000yqo.googlegroups.com> On Aug 28, 8:27?am, Tim Roberts wrote: > Deep_Feelings wrote: > > >python got relatively fewer numbers of developers than other high > >level languages like .NET , java .. etc ?why ? > > How do you know, and why does it matter? > > By the way, .NET is not a language. ?I assume you meant C#. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. you know when you go to forums and compare the number of posts and topics ,and you know when you google and compare the number of results .NET= i meant all .NET languages From rt8396 at gmail.com Fri Aug 28 01:52:11 2009 From: rt8396 at gmail.com (r) Date: Thu, 27 Aug 2009 22:52:11 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: On Aug 27, 7:34?pm, Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc ?why ? Oh, and why on god's green would you ever compare Java (*puke*) and Python in the same breath? You say Python is a "high-level-language"? Well sir, i say Python is a "super-high-level-language" that approaches pseudo code simplicity *but* stays far enough away from it so as not to be scorched by it's asinine synonymous quirks. From frank at chagford.com Fri Aug 28 02:01:01 2009 From: frank at chagford.com (Frank Millman) Date: Fri, 28 Aug 2009 08:01:01 +0200 Subject: Move dictionary from instance to class level References: <705c21b0-2858-46c2-8230-3cea64f5be3a@a26g2000yqn.googlegroups.com> Message-ID: Anthony Tolle wrote: > To take things one step further, I would recommend using decorators to > allow symbolic association of functions with the message identifiers, > as follows: > [...] That's neat. Thanks. Frank From apt.shansen at gmail.com Fri Aug 28 02:01:29 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Thu, 27 Aug 2009 23:01:29 -0700 Subject: Transforming a str to an operator In-Reply-To: <91126ac3-e7fe-4b7a-a37d-d1e60beaa278@w41g2000yqb.googlegroups.com> References: <87skfcblo3.fsf@benfinney.id.au> <91126ac3-e7fe-4b7a-a37d-d1e60beaa278@w41g2000yqb.googlegroups.com> Message-ID: <7a9c25c20908272301p7675c8f4q91dbb5ea4b790210@mail.gmail.com> > > > I would use the following approach: > > Abviously the OP is a python baby noob and casting your irrational > fear (and many others irrational fears) of eval at him is akin to > tales of Chupacabras running a muck in the jungle sucking the blood > from live goats in the twilight hours. I use eval all the time and > quite love it. > Yes, the OP is clearly a newbie to the language and probably programming in general, but that response is nonsense. It's a perfect example of a false analogy. Chupacabras are superstition, baseless fear-mongering. eval() is a very real dangerous construct. There is absolutely nothing irrational about the unsafe nature of eval. It is a tool: it is a useful tool if one knows how to use it, but is a tool that you'll slam into your thumb and break it if you don't know how. When there are tools available which address the same problem without those dangers, newbies should be exposed to THOSE first. > This is nothing more than a throw away academic exercise that will > serve no useful purpose for him in the future, but serves the very > useful purpose now of establishing an IO between the student and > Python interpretor. I'll bet most your example (albeit a good example) > flew miles above his head into la-la land. > I prefer not to assume newbies are stupid; if they don't understand a part of a correct explanation that's given, they can ask for clarification and further details can be given. True, this is a very Python-specific "correct" example to this basic problem, with dictionary dispatch which is a very Pythonic idiom that might be a bit too much for a newbie to programming in general: if that's the case, the correct thing to show the newbie would be: if op == "+": print "The result is:", int(num1) + int(num2) elif op == "-": print "The result is:", int(num1) - int(num2) ..etc. Exposing newbies to eval() is simply irresponsible. It is not an irrational fear: eval has a purpose and it is useful and it's fine to use, IF you understand the language and implications enough to use it. If you don't, if you're a newbie to programming entirely, it is good sense and a benefit to the newbie to steer the person away from something that will get them in trouble down the road. If they're not ready to deal with input sanitization, that's fine... but exposing them to dangerous practices when there's clear and logical alternate approaches is fool-hearty. The OP has plenty of time to learn about malicious input and > protecting against it, right now the fundamentals are well... > fundamental :) eval is simply NOT a fundamental. It should be considered an advanced feature, for advanced usage; that it seems simple is all the more dangerous. No one should be taught from an early stage that 'this is how to address a problem', only to then teach them later, 'Oh, by the way, that thing I taught you? It's bad in most cases and you shouldn't do it again'. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From frank at chagford.com Fri Aug 28 02:06:14 2009 From: frank at chagford.com (Frank Millman) Date: Fri, 28 Aug 2009 08:06:14 +0200 Subject: Move dictionary from instance to class level References: <20090827102111.ABC3B1F93@ctb-mesg4.saix.net> Message-ID: Dave Angel wrote: > OK, that makes good sense. And I withdraw any suggestion to use pickling, > since that could be subject to hacking. > > It now appears that the messages are only incidentally GUI events. And > that you would be well advised to make every possible event a separate > message, so that if the server state and the client state get out of > synch, you can readily check and reject such operations. For example, > you'd have a message for pressing the SUBMIT button on a particular form, > but you'd have different message types for other buttons on the same form, > or for SUBMIT on other forms. > I use the same message type for all SUBMITs, but the body of the message contains a unique id for each button. When the server constructs the form, it assigns a unique id to each widget, and includes this id in the form definition it sends to the client. Therefore the server and client can unambiguously reference specific widgets, and there is no real danger of getting out of sync. Frank From chris at simplistix.co.uk Fri Aug 28 02:26:45 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 28 Aug 2009 07:26:45 +0100 Subject: why python got less developers ? In-Reply-To: <1ccf54f5-b1f5-4c4a-b782-fde1a1648cf6@l5g2000yqo.googlegroups.com> References: <1ccf54f5-b1f5-4c4a-b782-fde1a1648cf6@l5g2000yqo.googlegroups.com> Message-ID: <4A9778A5.1060105@simplistix.co.uk> Esam Qanadeely wrote: > .NET= i meant all .NET languages What? You mean like Python? ;-) Google IronPython ya troll... Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From jvpic at free.fr Fri Aug 28 02:37:16 2009 From: jvpic at free.fr (jvpic) Date: Fri, 28 Aug 2009 08:37:16 +0200 Subject: Learning Python advanced features In-Reply-To: <4a967bd6$0$19301$426a74cc@news.free.fr> References: <4a967864$0$15193$426a74cc@news.free.fr> <4a967bd6$0$19301$426a74cc@news.free.fr> Message-ID: <4a977b20$0$740$426a34cc@news.free.fr> Bruno Desthuilliers a ?crit : > jvpic a ?crit : >> Hi, >> >> Learning Python, I understand the mechanism of : closure, __new__, >> descriptors, decorators and __metaclass__, but I interrogate myself on >> the interest of those technics ? >> >> May somebody explain me the interest ? > > Didn't like my answers on f.c.l.py ?-) Si, mais je voulais savoir ce qu'on en pense sur un autre forum ! Merci encore... From simon at brunningonline.net Fri Aug 28 02:42:29 2009 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 28 Aug 2009 07:42:29 +0100 Subject: Question on the "csv" library In-Reply-To: <9f3083b4-4886-41c3-9404-d7eac300964b@l35g2000pra.googlegroups.com> References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> <9f3083b4-4886-41c3-9404-d7eac300964b@l35g2000pra.googlegroups.com> Message-ID: <8c7f10c60908272342o4fc91195m27b56e3b506eb540@mail.gmail.com> 2009/8/28 John Machin : > > Mark, there exist parallel universes the denizens of which use strange > notation e.g. 1.234,56 instead of 1,234.56 When displaying data, sure. > and would you believe they > use ';' instead of ',' as a list separator ... CSV is a data transfer format, not a display format. Locale specific stuff like this has no place in it. Dates, IMHO, should be in the ugly but unambiguous ISO 8601 format in a CSV. It's for import and export, not for looking pretty. Besides - CSV; the clue's in the name. ;-) > Excel perfidiously > gives them what they expect rather than forcing them to comply with > The One True Way. When people export to a comma separated value file, they are almost certainly expecting a file containing values separated by comas. If Excel isn't giving them this by default, it's broken. -- Cheers, Simon B. From beorn at seznam.cz Fri Aug 28 03:45:58 2009 From: beorn at seznam.cz (hoffik) Date: Fri, 28 Aug 2009 00:45:58 -0700 (PDT) Subject: Select column from a list Message-ID: <25185508.post@talk.nabble.com> Hello, I'm quite new in Python and I have one question. I have a 2D matrix of values stored in list (3 columns, many rows). I wonder if I can select one column without having to go through the list with 'for' command. For example I have list called 'values'. When I write 'values[0]' or 'values[0][:]' I'll get the first row. But when I write 'values[:][0]' I won't get the first column, but the first row again! I can't see why. Thanks Hoffik -- View this message in context: http://www.nabble.com/Select-column-from-a-list-tp25185508p25185508.html Sent from the Python - python-list mailing list archive at Nabble.com. From hendrik at microcorp.co.za Fri Aug 28 03:54:51 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 28 Aug 2009 09:54:51 +0200 Subject: List iterator thread safety In-Reply-To: <6bf89e55-2ddd-435f-925d-7cc3827c0f9a@24g2000yqm.googlegroups.com> References: <6bf89e55-2ddd-435f-925d-7cc3827c0f9a@24g2000yqm.googlegroups.com> Message-ID: <200908280954.51423.hendrik@microcorp.co.za> On Thursday 27 August 2009 16:50:16 Carl Banks wrote: > On Aug 27, 7:25?am, Hendrik van Rooyen > wrote: > > Its not too bad - if you crook a bit - the trick is that you iterate over > > the list backwards when you are removing stuff based on index, so that > > the remainder does not get jumbled up by losing their positions, as > > happens when you do it going forwards. > > That's only if you remove the "current item". The OP has different > threads accessing the list at the same time, so I have to assume that > item being remove is not necessarily the current iteration. Sorry - I did not pick that up - The threading screws the simple scheme up. In such a situation I would have a thread to run the list - almost like a mini data base - and link the lot together using queues. It is still a bugger, though, as one thread could try to kill something that is "checked out" to another one. Then you have to take hard decisions, and a list is the wrong structure, because you have to remember state. Better to use a dict, so you can at least mark a thing as "dead", and check for that before you update. 8<-------- example -------- > For the record, I use a more sophisticated system that explicitly > resolves cause and effect in my games. That's probably beyond the > scope of this thread, though. Yes - it is hairy - and there are probably as many different solutions as there are programmers, and then some. :-) - Hendrik From eric.brunel at pragmadev.com Fri Aug 28 03:55:22 2009 From: eric.brunel at pragmadev.com (eb303) Date: Fri, 28 Aug 2009 00:55:22 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> Message-ID: On Aug 27, 11:22 pm, r wrote: > --------------------------------------------- > Python offical docs and Tkinter > --------------------------------------------- > *The Python docs barely cover anything related to actual Tkinter > coding. At the minimum the Tkinter doc page should have a subpage for > all the widgets available --which is very small(approx 15) and each > subpage should list the available methods on that wiget. I think the general idea behind the 'lack' of documentation is that it would only double tcl/tk's own documentation. I've always used Tkinter using the tcl/tk docs here: http://www.tcl.tk/man/tcl8.5/TkCmd/contents.htm and once you get used to how you transform tcl syntax to Python syntax, it works pretty well. Maintaining a documentation for Tkinter in the official Python docs would force people to run after tcl. I understand why they don't want to do that, even if I'd love to see a better Tkinter documentation too. > --------------------------------------------- > from Tkinter import * > --------------------------------------------- > *Too many noobs start out with the "from Tkinter import *" idiom, > unknowing that they are horribly polluting their namespace. I feel > that all (tkinter) code should follow the "import Tkinter as tk" > policy and never use "from Tkinter import *". To push this agenda i > propose all docs be modified so that no one should see such global > import blasphemy again. We should at least keep all example code in > the latter non-polluting form and frown heavily upon global imports in > Tkinter code or any code for that matter. Well, I just don't agree with you on this one. AFAIK, Tkinter has been made to make the 'from Tkinter import *' idiom work without too much namespace pollution. I've always used it, still use it today, and never seen any problem with it. I do agree that this might lead newbies to think it's ok for all modules, and end up doing 'from os import *' and wonder why opening a file with 'open' no more works. But this is the only problem I can see. > --------------------------------------------- > Tkinter Constants > --------------------------------------------- > *The Tkconstants module needs to be removed *yesterday* because i > think it reinforces sloppy coding styles. The main problem is with > subtle bugs that are created when someone rebinds one or more of the > constants, for example "W=20". At first i thought the constants were > great but I quickly found out the shortfalls of such a Utopian > approach . Since Tkinter allows strings to be passed-into widget > constructors, we should remove the TkConstants immediately and force > everyone to use strings instead... > > #-- instead of this --# > w.pack(side=LEFT,fill=BOTH,anchor=W) > > #-- do this --# > w.pack(side='left',fill='both',anchor='w') > > The few extra keystrokes are well worth the effort! Well, again, I don't agree. I prefer having well defined constants than having to type strings. If the values for the fill option could be anything, well, OK. But they can't: they have to be either 'x' or 'y' or 'both'. So I prefer to have them defined in constants. [snip comments on IDLE, which I don't use] > --------------------------------------------- > Tkinter Canvas > --------------------------------------------- > *The Tkinter Canvas widget should return (X,Y) pairs when calling > canvas.coords(obj). The current implementation returns a flat array > that is pretty much useless outside of canvas calls. Of course one > could zip the coords into pairs, but it seems clumsy to call zip() on > 2 LC's when Tkinter could, and should, do it for you. We agree on this one, but it's a minor flaw. > *Canvas needs a canvas.rotate() method for polygons, lines -- (easy). All Canvas methods are actually forwarded to the underlying tcl interpreter. So you might want to suggest that to the tcl guys. > --------------------------------------------- > Tkinter ComboBox -- where's Waldo? > --------------------------------------------- > *As much as i hate to support anything related to M$, Tkinter needs an > M$ stlye combobox. Yes, I know Tix has combobox (*puke*), however > using it is like pulling teeth. I have coded up an far more elegant/ > simple solution -- and yes, i know about the OptionMenu widget which > serves a useful purpose but is NOT a good replacement for a REAL M$ > style combobox ;). You don't seem to be aware of the new widgets in tk, which do include a combo-box (and a lot of others BTW). See the ttk:: commands in the tcl/tk documentation (link above). These widgets already have a Python wrapper (see http://pypi.python.org/pypi/pyttk/0.3). > *For instance, ComboBoxes need values that the user can select from, > this is as universal as humans and oxygen. But sometimes you want to > give the user a detailed set of values in the dropdown listbox and > then insert an abbrieation of the value once selected, such as the > case with state names... > > New Mexico -> MN > California -> CA > Florida -> FL > > ...instead of the laborious and wasteful convention of overriding a > method to insert this value from a mapping each time why not just pass > a pointer to the mapping into the constructor and create a combobox > that actually knows how to walk and chew gum! Again, you might want to forward that to the tcl guys. And I do agree it would be nice. [snip code] [snip Tix comments...] Tix is more or less dead, since nearly all the widgets it provided have now way better alternatives which have been included in the tcl/ tk core in the ttk package, including comboboxes and notebooks. You might want to have a look at these. From contact at xavierho.com Fri Aug 28 03:55:50 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 17:55:50 +1000 Subject: Select column from a list In-Reply-To: <25185508.post@talk.nabble.com> References: <25185508.post@talk.nabble.com> Message-ID: <2d56febf0908280055g3b38bec9j1f1e812dc8bab11f@mail.gmail.com> On Fri, Aug 28, 2009 at 5:45 PM, hoffik wrote: > Hello, > > I'm quite new in Python and I have one question. I have a 2D matrix of > values stored in list (3 columns, many rows). I wonder if I can select one > column without having to go through the list with 'for' command. As far as I know though, you will have to loop through this if you built your matrix with nested lists. i.e.: li = [[1,2],[3,4]] result = [] for row in li: result.append(row[0]) # result == [1, 3] > For example I have list called 'values'. > When I write 'values[0]' or 'values[0][:]' I'll get the first row. > But when I write 'values[:][0]' I won't get the first column, but the first > row again! I can't see why. Let's say values = [[1,2][3,4]]. values[:] returns the entire values list, from beginning to end. So you end up what you started with. And, of course, values[:][0] is the same as values[0]. In fact: >>> li[:][:][:][0] is li[0] True It's... a very interesting behaviour, to say the least. You might be able to get a proper matrix behaviour using NumPy, (which I never used, so I'm just throwing it out there as a guess) or you might have to write your own iterator for later reuse. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Aug 28 04:03:49 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Aug 2009 09:03:49 +0100 Subject: Question on the "csv" library In-Reply-To: <9f3083b4-4886-41c3-9404-d7eac300964b@l35g2000pra.googlegroups.com> References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> <9f3083b4-4886-41c3-9404-d7eac300964b@l35g2000pra.googlegroups.com> Message-ID: John Machin wrote: > On Aug 28, 6:44 am, Mark Lawrence wrote: >> vsoler wrote: >>> On Aug 27, 9:42 pm, Andreas Waldenburger >>> 1- the csv file was generated with Excel 2007; no prompts for what the >>> separator should be; Excel has used ";" by default, without asking >>> anything >> I find this difficult to believe, > > Mark, there exist parallel universes the denizens of which use strange > notation e.g. 1.234,56 instead of 1,234.56 and would you believe they > use ';' instead of ',' as a list separator ... Excel perfidiously > gives them what they expect rather than forcing them to comply with > The One True Way. I suggest a new file type csvewtlsinac i.e. comma seperated value except when the list seperator is not a comma.:) Does this cover everything? p.s. is it "separator" or "seperator", after 50+ years I still can't remember? -- Kindest regards. Mark Lawrence. From martin at v.loewis.de Fri Aug 28 04:12:34 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 28 Aug 2009 10:12:34 +0200 Subject: break unichr instead of fix ord? In-Reply-To: <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> Message-ID: <4a979172$0$11759$9b622d9e@news.freenet.de> > The PEP says: > * unichr(i) for 0 <= i < 2**16 (0x10000) always returns a > length-one string. > > * unichr(i) for 2**16 <= i <= TOPCHAR will return a > length-one string on wide Python builds. On narrow > builds it will raise ValueError. > and > * ord() is always the inverse of unichr() > > which of course we know; that is the current behavior. But > there is no reason given for that behavior. Sure there is, right above the list: "Most things will behave identically in the wide and narrow worlds." That's the reason: scripts should work the same as much as possible in wide and narrow builds. What you propose would break the property "unichr(i) always returns a string of length one, if it returns anything at all". > 1) Should surrogate pairs be disallowed on narrow builds? > That appears to have been answered in the negative and is > not relevant to my question. It is, as it does lead to inconsistencies between wide and narrow builds. OTOH, it also allows the same source code to work on both versions, so it also preserves the uniformity in a different way. > * every Python Unicode character represents exactly > one Unicode code point (i.e. Python Unicode > Character = Abstract Unicode character) > > I'm not sure what this means (what's an abstract unicode > character?). I don't think this is actually the case, but I may be confusing Unicode terminology here - "abstract character" is a term from the Unicode standard. > Finally we read: > > * There is a convention in the Unicode world for > encoding a 32-bit code point in terms of two > 16-bit code points. These are known as > "surrogate pairs". Python's codecs will adopt > this convention. > > Is a distinction made between Python and Python > codecs with only the latter having any knowledge of > surrogate pairs? No. In the end, the Unicode type represents code units, not code points, i.e. half surrogates are individually addressable. Codecs need to adjust to that; in particular the UTF-8 and the UTF-32 codec in narrow builds, and the UTF-16 codec in wide builds (which didn't exist when the PEP was written). > Nothing else in the PEP seems remotely relevant. Except for the motivation, of course :-) In addition: your original question was "why has this been changed", to which the answer is "it hasn't". Then, the next question is "why is it implemented that way", to which the answer is "because the PEP says so". Only *then* the question is "what is the rationale for the PEP specifying things the way it does". The PEP is relevant so that we can both agree that Python behaves correctly (in the sense of behaving as specified). Regards, Martin From deets at nospam.web.de Fri Aug 28 04:14:59 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Aug 2009 10:14:59 +0200 Subject: Algorithms as objects? In-Reply-To: References: Message-ID: <7fpi03F2lmnccU1@mid.uni-berlin.de> Kreso schrieb: > I am writing an application that essentially calculates set of numbers, > say N1, N2, ..., where they can be calculated by several different > algorithms. (One should be able to choose the algorithm at run time.) > In each algorithm one starts from a set of functions, say f1, f2, ..., > which are then transformed into some other functions g1(f1, f2, ..), > g2(f1, f2, ...), ... , then maybe transformed once more and result is > obtained by evaluating final functions. > I can naturally think about this as a collection of transformation > blocks, which have functions as input and output, and which can be > put together to get the final results. However, I am not sure > how to program this, especially since one cannot subclass function > type. To be clear let me give simplified example of what is needed: > > f(x) has unknown shape, so one would like to try, say > > f1(x) = ax - b x**2 or f2(x) = a sin(b*x), > > where a and b are variable parameters. > > Then, one would like to create, with known k(x,y), function g(x) > in one of two ways: > > g1(x) = k(x, x)*f(x) or g2(x) = integrate(k(x, y) * f(y), y=0..1), > > and finally evaluate N=g(1) as result. In this simple example > there are 4 different algorithms for f(x) -> g(x) -> N, and one > should be able to simply choose between them, e.g. by calling > N(g1, f2, (a,b)). > > In practice algorithm is not necessary so linear, but is > generally tree-lika: > > (a,b) -> f1(x) --->g1(x)---+ > |--> h(x) --> N > (c,d) ---+--> g2(x)--------+ > | > f2(x) --+ > > > It would be nice to have some class of function-objects, > that f1(x), .., g1(x), ... could be members/instances of so that common > operations on these functions could be possible (checking > that they satisfy some necessary properties, plotting them, ...), > and then second "class" of transformations/methods operating on > these objects. > I seem to be confused by the fact that I would like to somehow treat > algorithms as objects (so that one can experiment with different > algorithm systems) but I don't have clear picture how to do it. > I am just brainstorming for ideas. Any advice is welcome. > Sound like simple function combinators to me. Like this: import inspect def combine(f, g): if len(inspect.getargspec(g)[0]) > 1: def h(*args): return g(*f(*args)) return h else: def h(*args): return g(f(*args)) return h def a(x): return 10 + x def b(x): return x ** 2 print combine(a, b)(20) def c(x): return x, x * 2 def d(x, y): return x + y print combine(c, d)(10) But to be honest - I don't think you win much with this whole thing. Spelling out the function-calls the way they are made is in the end as efficient and clear as it can get. And for *real* algorithms, you need non-strict constructs, control-structures and the like, and in the end of the day, you create a programming language on top of a programming language. Diez From hendrik at microcorp.co.za Fri Aug 28 04:18:01 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 28 Aug 2009 10:18:01 +0200 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> Message-ID: <200908281018.01750.hendrik@microcorp.co.za> On Thursday 27 August 2009 22:57:44 Terry Reedy wrote: > > Nope. I got a duplicate sent to my mailbox, which I hate. > > In particular, because there is no indication that it is an exact > duplicate of what I will also find on the list itself. Please use reply > instead of reply-all. If I do that, then the mail would go just to you, and not to the list at all, which is not what I suspect you want, in view of what you have just said. I have to do a "reply all", followed by deletion of the author, and sometimes addition of the list as a "to" too. Its a mess, and if I muck it up, the author gets a copy in his email, if he has not fudged his "reply to" It would really be nice if the "reply" would go to the list, but for the digest versions, at least, it does not. And different mail clients do not seem to make a difference. - Hendrik From contact at xavierho.com Fri Aug 28 04:31:59 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 18:31:59 +1000 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <200908281018.01750.hendrik@microcorp.co.za> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <200908281018.01750.hendrik@microcorp.co.za> Message-ID: <2d56febf0908280131p1599de21i62add26fc4e96ab4@mail.gmail.com> On Fri, Aug 28, 2009 at 6:18 PM, Hendrik van Rooyen wrote: > It would really be nice if the "reply" would go to the list, but for the > digest versions, at least, it does not. I'm on a few other lists. The Python ones are the only ones that I have to manually change. The Nuke-user mailing list automatically changes the To: to the correct address, and I *think* they also use mail-man. The DLF list I mentioned before also doesn't have this problem. When will this be fixed? It'll take someone like 5 minutes to do a setting . . . -Just my rambling again Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.i.dont at want.mail.from.spammers.com Fri Aug 28 04:37:15 2009 From: no.i.dont at want.mail.from.spammers.com (Fencer) Date: Fri, 28 Aug 2009 10:37:15 +0200 Subject: Sending email Message-ID: <7fpj9tF2clhemU1@mid.individual.net> Hello, I'm using Python version 2.6.2 and I discovered it has built-in libraries for sending email (imports smtplib and email). On the web I discovered how to send mail through smtp.gmail.com: mail_server = smtplib.SMTP() mail_server.connect('smtp.gmail.com') mail_server.ehlo() mail_server.starttls() mail_server.ehlo() mail_server.login('username', 'password') msg = MIMEText('Some message text') msg['Subject'] = 'Some subject' msg['From'] = 'Mr Underhill' msg['To'] = 'someemailaddress' me = 'myemailaddress' mail_server.sendmail(me, ['someemailaddress'], msg.as_string()) That seems to work just fine but for the messages I will be sending I don't want to use my private GMail account. We have an SMTP server at work, and I checked its settings in the Thunderbird mail client and it's using SSL over port 465, so a bit different from how GMail's SMTP server is configured in Thunderbird. I altered my code slightly to account for this: mail_server = smtplib.SMTP_SSL() mail_server.connect('mysmtpserver.at.work', 465) Everything I left untouched. However, it doesn't work: Traceback (most recent call last): File "C:\Users\fencer\workspace\Send Email\src\send_email.py", line 16, in mail_server.ehlo() File "C:\Python26\lib\smtplib.py", line 382, in ehlo self.putcmd(self.ehlo_msg, name or self.local_hostname) File "C:\Python26\lib\smtplib.py", line 318, in putcmd self.send(str) File "C:\Python26\lib\smtplib.py", line 310, in send raise SMTPServerDisconnected('please run connect() first') smtplib.SMTPServerDisconnected: please run connect() first As you can see, I'm on Windows Vista. What do I need to change in my code to fix this problem? Thunderbird manages to do it! :) Ideally, I would like send an email that the recipient can't reply to, but if doesn't work, it's fine too. I want to use this to send automated emails to students with account information for a course. - Fencer From manu3d at gmail.com Fri Aug 28 04:40:28 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Fri, 28 Aug 2009 01:40:28 -0700 (PDT) Subject: Does Class implements Interface? References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> Message-ID: <55a99698-49ae-4af9-a254-d4e1a429b3d5@k30g2000yqf.googlegroups.com> Jonathan, Stephen and Max, thank you all for the tips and tricks. Much appreciated. Manu From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 04:41:51 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 10:41:51 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: <4a967b2f$0$19301$426a74cc@news.free.fr> Message-ID: <4a979838$0$13005$426a34cc@news.free.fr> kj a ?crit : > In <4a967b2f$0$19301$426a74cc at news.free.fr> Bruno Desthuilliers writes: > >> The only thing one is entitled to expect when learning a new language is >> that the language's implementation follows the language specs. > > In fact, the official docs, when they discuss scopes, are off to > a bad start: > > Names refer to objects. Names are introduced by name binding > operations. Each occurrence of a name in the program text refers > to the binding of that name established in the innermost function > block containing the use. > > The first paragraph implies that binding can only occur within > functions, which is either incorrect, or presupposes a definition > of "function" that is not what most programmers would recognize. Indeed, and you're right to point it. I strongly suggest you submit a ticket to the doc maintainers. > In general, I found the docs very unclear on the subject of scoping. > PEP 227 is much better, but I wouldn't have thought of it as "the > specs". Well, here again, it sure would help to make clear that peps (and release specific "what's new") *are* part of the doc. But for sure, what used to be a simple and clear reference is now a bit of a mess, despite the hard work of the doc team. Side-effect of the rapid growth of the language I guess... From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 04:48:03 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 10:48:03 +0200 Subject: Algorithms as objects? In-Reply-To: References: Message-ID: <4a9799ac$0$8042$426a74cc@news.free.fr> Kreso a ?crit : > I am writing an application that essentially calculates set of numbers, > say N1, N2, ..., where they can be calculated by several different > algorithms. (One should be able to choose the algorithm at run time.) > In each algorithm one starts from a set of functions, say f1, f2, ..., > which are then transformed into some other functions g1(f1, f2, ..), > g2(f1, f2, ...), ... , then maybe transformed once more and result is > obtained by evaluating final functions. > I can naturally think about this as a collection of transformation > blocks, which have functions as input and output, and which can be > put together to get the final results. However, I am not sure > how to program this, especially since one cannot subclass function > type. Nope, but you can write your own callable types: class functor(object): def __call__(self): print "%s called" % self (snip) > I seem to be confused by the fact that I would like to somehow treat > algorithms as objects Strategy pattern anyone ? From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 04:51:43 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 10:51:43 +0200 Subject: variables of the class are not available as default values? In-Reply-To: References: Message-ID: <4a979a88$0$8042$426a74cc@news.free.fr> Chris Rebert a ?crit : (snip) > Default values are only evaluated once, when the class is defined, s/class/function/ The function objects (defined in a class statement body...) are created before the class object itself. > thus "self" is not defined at that point since the class is still > being defined when the method definition is executed and thus there > can be no instances yet anyway. From hendrik at microcorp.co.za Fri Aug 28 04:52:01 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 28 Aug 2009 10:52:01 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a970bd7$0$333$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a970bd7$0$333$14726298@news.sunsite.dk> Message-ID: <200908281052.01436.hendrik@microcorp.co.za> On Friday 28 August 2009 00:42:16 Esben von Buchwald wrote: > OK, now things starts to make sense. > > You tell me to do something like this? > > > def doCallback(self): > if self.process_busy==False: > self.process_busy=True > self.at.after(0.01,self.data_callback) This bit is allmost right - try to make the time a millisecond or less, if you can. (however that is specified - I do not know) The spelling is probably: self.at.after(1,self.data_callback, (other_stuff)) where "other stuff" comes from the event and is what is needed to do the calculation. - the event should be an argument to the doCallback thinghy too, somehow, so that you can get at what you need to do the calculation. > def doneCallback(self): > self.process_busy=False > you do not need this separate. just do this: def data_callback(self,other_stuff): calculate what must be calculated self.process_busy=False > > And the after command will cause python to spawn a new thread, which > runs self.data_callback, which measn that the doCallback will return > immediately, so the next callback from accelerometer can be processed? Yes and skipped if the calculation is not done yet. Obviously you will have to do whatever it takes to make sure the events keep coming (if anything), so it may end up a little more complex, but you basically have the idea now. The thing that happens as a result of the after is not really a new thread, it is a piece of the main loop that gets diverted for a while to do the calculation. if, in that routine, you go: while True: pass You will completely freeze up the whole bang shoot.. > > And when the self.data_callback() finishes, i'd make it call the > doneCallback() to release my busy flag, right? see above - just clear it from the called routine. > > I'm gonna try this tomorrow :) Good luck! - Hendrik From ben+python at benfinney.id.au Fri Aug 28 04:54:30 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 28 Aug 2009 18:54:30 +1000 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> Message-ID: <87k50ob9o9.fsf@benfinney.id.au> Hendrik van Rooyen writes: > If I [use the ?reply to author? command], then the mail would go just > to you, and not to the list at all, which is not what I suspect you > want, in view of what you have just said. Right. The common ?reply? command in most mail clients means ?reply to author?, and as you say, it requests to compose a reply addressed to the author. > It would really be nice if the "reply" would go to the list, but for > the digest versions, at least, it does not. No, it really wouldn't; because if you're asking to compose a message address to the *author*, and it instead gets addressed to the whole *list*, that's a recipe for disastrous communication errors. Instead, it would be nice if people had a ?reply to list? command, and used that when they choose to send a message to the list. > And different mail clients do not seem to make a difference. Fortunately, the messages that come from the list enable any mail client to know the correct address for ?reply to list?. It only remains to choose a mail client that knows how to use it. -- \ ?? one of the main causes of the fall of the Roman Empire was | `\ that, lacking zero, they had no way to indicate successful | _o__) termination of their C programs.? ?Robert Firth | Ben Finney From contact at xavierho.com Fri Aug 28 05:04:57 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 19:04:57 +1000 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <87k50ob9o9.fsf@benfinney.id.au> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <87k50ob9o9.fsf@benfinney.id.au> Message-ID: <2d56febf0908280204k73a41cc0j63717c8ca258ff33@mail.gmail.com> On Fri, Aug 28, 2009 at 6:54 PM, Ben Finney > wrote: > Fortunately, the messages that come from the list enable any mail client > to know the correct address for ?reply to list?. It only remains to > choose a mail client that knows how to use it. Would you be so kind and share with us for such a client that knows how to use the mailing list attribute? Thanks! -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 05:06:31 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 11:06:31 +0200 Subject: Select column from a list In-Reply-To: References: Message-ID: <4a979e00$0$3608$426a34cc@news.free.fr> hoffik a ?crit : > Hello, > > I'm quite new in Python and I have one question. I have a 2D matrix of > values stored in list (3 columns, many rows). I wonder if I can select one > column without having to go through the list with 'for' command. Lists don't have columns. What you have is a list of lists (and FWIW, in your case, it should be a list of tuples since obviously these are fixed-size items where position is meaningfull). > For example I have list called 'values'. > When I write 'values[0]' or 'values[0][:]' I'll get the first row. Not exactly. In the first case, you have a reference to values[0], in the second case a _copy_ of values[0] >>> alist = [[1, 2, 3], [4, 5, 6]] >>> ref = alist[0] >>> copy = alist[0][:] >>> ref is alist[0] True >>> copy is alist[0] False >>> copy[0] = 999 >>> copy [999, 2, 3] >>> alist [[1, 2, 3], [4, 5, 6]] >>> ref [1, 2, 3] >>> ref[0] = 888 >>> alist [[888, 2, 3], [4, 5, 6]] >>> > But when I write 'values[:][0]' I won't get the first column, but the first > row again! I can't see why. alist[:] returns a copy the whole list. As I said, lists don't have "columns". So yes, given your data structure, you do have to iterate over the outer list to collect items at specific positions of the inner lists (or tuples). Depending on the size of your dataset, the frequency of such operation in your code, and required perfs, you can either * just do the simplest thing, ie: first_column_items = [row[0] for row in values] * try to find a more suited datastructure * of just use the most appropriate tool for set operations, which is a relational database. FWIW, sqlite doesn't require any server setup, and can even be used with in-memory databases if you don't need persistance. HTH From vlastimil.brom at gmail.com Fri Aug 28 05:28:38 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 28 Aug 2009 11:28:38 +0200 Subject: Select column from a list In-Reply-To: <25185508.post@talk.nabble.com> References: <25185508.post@talk.nabble.com> Message-ID: <9fdb569a0908280228g59038ba1u30d6d5ef9d6a80ca@mail.gmail.com> 2009/8/28 hoffik : > > Hello, > > I'm quite new in Python and I have one question. I have a 2D matrix of > values stored in list (3 columns, many rows). I wonder if I can select one > column without having to go through the list with 'for' command. > ... I guess, it won't be possible without an explicit or implicit loop; you may try: >>> from operator import itemgetter >>> nested_list = [[1, 2, 3], [10, 20, 30], [100, 200, 300]] >>> map(itemgetter(1), nested_list) [2, 20, 200] >>> vbr From anthra.norell at bluewin.ch Fri Aug 28 05:59:17 2009 From: anthra.norell at bluewin.ch (Anthra Norell) Date: Fri, 28 Aug 2009 11:59:17 +0200 Subject: Select column from a list In-Reply-To: <9fdb569a0908280228g59038ba1u30d6d5ef9d6a80ca@mail.gmail.com> References: <25185508.post@talk.nabble.com> <9fdb569a0908280228g59038ba1u30d6d5ef9d6a80ca@mail.gmail.com> Message-ID: <4A97AA75.3040101@bluewin.ch> Vlastimil Brom wrote: > 2009/8/28 hoffik : > >> Hello, >> >> I'm quite new in Python and I have one question. I have a 2D matrix of >> values stored in list (3 columns, many rows). I wonder if I can select one >> column without having to go through the list with 'for' command. >> ... >> > > I guess, it won't be possible without an explicit or implicit loop; > you may try: > > >>>> from operator import itemgetter >>>> nested_list = [[1, 2, 3], [10, 20, 30], [100, 200, 300]] >>>> map(itemgetter(1), nested_list) >>>> > [2, 20, 200] > > > vbr > How about rotating the list with zip? >>> zip (*nested_list)[1] (2, 20, 200) Frederic From marduk at letterboxes.org Fri Aug 28 06:19:18 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Fri, 28 Aug 2009 06:19:18 -0400 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <2d56febf0908280204k73a41cc0j63717c8ca258ff33@mail.gmail.com> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <87k50ob9o9.fsf@benfinney.id.au> <2d56febf0908280204k73a41cc0j63717c8ca258ff33@mail.gmail.com> Message-ID: <1251454758.12823.1.camel@blackwidow.nbk> On Fri, 2009-08-28 at 19:04 +1000, Xavier Ho wrote: > On Fri, Aug 28, 2009 at 6:54 PM, Ben Finney +python at benfinney.id.au> wrote: > Fortunately, the messages that come from the list enable any > mail client > to know the correct address for ?reply to list?. It only > remains to > choose a mail client that knows how to use it. > > Would you be so kind and share with us for such a client that knows > how to use the mailing list attribute? Evolution at least is mailing-list aware. I usually "Reply to List" (CTRL-L) and fugetaboutit. From olivier.darge at gmail.com Fri Aug 28 06:53:03 2009 From: olivier.darge at gmail.com (OdarR) Date: Fri, 28 Aug 2009 03:53:03 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: <2aab5093-5381-42e3-a3dd-1d2e88e36004@32g2000yqj.googlegroups.com> On 28 ao?t, 02:47, MRAB wrote: > Deep_Feelings wrote: > > python got relatively fewer numbers of developers than other high > > level languages like .NET , java .. etc ?why ? > > Fewer needed? excellent answer. LOL. Olivier From usenot at geekmail.INVALID Fri Aug 28 07:13:22 2009 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Fri, 28 Aug 2009 13:13:22 +0200 Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> <9f3083b4-4886-41c3-9404-d7eac300964b@l35g2000pra.googlegroups.com> Message-ID: <20090828131322.6173ade1@geekmail.INVALID> On Fri, 28 Aug 2009 09:03:49 +0100 Mark Lawrence wrote: > p.s. is it "separator" or "seperator", after 50+ years I still can't > remember? The former. It's cognate to English "part" if that helps any. /W -- INVALID? DE! From find.mig at paa.google Fri Aug 28 07:15:50 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Fri, 28 Aug 2009 13:15:50 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a970bd7$0$333$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a9595ca$0$300$14726298@news.sunsite.dk> <4a970bd7$0$333$14726298@news.sunsite.dk> Message-ID: <4a97bc7e$0$339$14726298@news.sunsite.dk> It seems to solve the problem. What I did: def contextDataHandler(self): self.contextdata.process_busy=True self.services.findServices() self.drawDisplay() self.contextdata.process_busy=False def doCallback(self): self.at.cancel() if self.process_busy==False: self.at.after(0.01,self.data_callback) The app works awesomely stable now data_callback refers to contextDataHandler in parent class Thanks guys, good job From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 07:40:28 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 13:40:28 +0200 Subject: Python on the Web In-Reply-To: <1b7a2f45-dd10-4722-a9d8-8c6d2464e4d6@e27g2000yqm.googlegroups.com> References: <4a94ef42$0$27774$426a74cc@news.free.fr> <4a96884b$0$22855$426a74cc@news.free.fr> <1b7a2f45-dd10-4722-a9d8-8c6d2464e4d6@e27g2000yqm.googlegroups.com> Message-ID: <4a97c215$0$16809$426a74cc@news.free.fr> Phil a ?crit : > When > I gave that arbitrary percentage, I was basing it off of the > information I had seen with regards to launching applications built > with existing frameworks using lighttpd. I do realize I was missing a > lot of information by looking up something that specific. Indeed !-) > I also > understand that there are enough frameworks. That still won't change > my mind. I do not want to write a web application, otherwise I would > use an existing framework as suggested. I just wanted to experiment > and see what kind of framework I could develop with some ideas I had > in mind. I wrote quite a couple web and non web frameworks myself - all ending up in the trash can FWIW, but it certainly has been a very educative experience by itself. > I just really like some of the new features of > Python 3, and most importantly, unicode compliance is just that much > straight forward in my opinion. If you're only writing your framework for learning purposes, you could as well go with Python 3, and implement everything from the ground up (not a trivial task FWIW). From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 07:45:13 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 13:45:13 +0200 Subject: Learning Python advanced features In-Reply-To: <4a977b20$0$740$426a34cc@news.free.fr> References: <4a967864$0$15193$426a74cc@news.free.fr> <4a967bd6$0$19301$426a74cc@news.free.fr> <4a977b20$0$740$426a34cc@news.free.fr> Message-ID: <4a97c331$0$16809$426a74cc@news.free.fr> jvpic a ?crit : > Bruno Desthuilliers a ?crit : >> jvpic a ?crit : >>> Hi, >>> >>> Learning Python, I understand the mechanism of : closure, __new__, >>> descriptors, decorators and __metaclass__, but I interrogate myself >>> on the interest of those technics ? >>> >>> May somebody explain me the interest ? >> >> Didn't like my answers on f.c.l.py ?-) > Si, mais je voulais savoir ce qu'on en pense sur un autre forum ! > Merci encore... Hum... I guess the smiley was not big enough !-) From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 07:48:07 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 13:48:07 +0200 Subject: Learning Python advanced features In-Reply-To: <6b1a2aae-fd3d-40a8-9350-89a8661a6d4a@a37g2000prf.googlegroups.com> References: <4a967864$0$15193$426a74cc@news.free.fr> <6b1a2aae-fd3d-40a8-9350-89a8661a6d4a@a37g2000prf.googlegroups.com> Message-ID: <4a97c3df$0$16809$426a74cc@news.free.fr> Jonathan Gardner a ?crit : > On Aug 27, 5:13 am, jvpic wrote: >> Hi, >> >> Learning Python, I understand the mechanism of : closure, __new__, >> descriptors, decorators and __metaclass__, but I interrogate myself on >> the interest of those technics ? >> >> May somebody explain me the interest ? >> > > I assume you are asking, "Why do these features exist? What makes them > useful? When would I use them?" > > For that, you should re-read the documentation and discussion > surrounding them. The short answer is that the above makes your job, > as a programmer easier. It's easier because you have to write less > code, read less code, and your code has fewer bugs. I think the OP is mostly looking for practical use cases. FWIW, when I discovered Python's "lambda" (I only knew a couple low-level imperative languages by that time), I really wondered what an anonymous function could be used for !-) From martin.hellwig at dcuktec.org Fri Aug 28 07:56:08 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 28 Aug 2009 12:56:08 +0100 Subject: why python got less developers ? In-Reply-To: References: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> Message-ID: Esam Qanadeely wrote: > who cares if a language is compiled or interpreted as long as it runs > and perform the function. > > second thing is : even if java is faster than python , unless you are > making performance critical operations : who cares? computers are > getting faster all the time and languages like python or ruby are fast > enough. > > any comment ? I like to second that, if performance is *that* important you wouldn't go with Java either, you be better of with C or even assembly. Doesn't mean you should write everything in C, just the parts that are performance critical, preferably with a 'slow' fall back if there isn't an optimized routine available yet for a specific platform. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 08:07:05 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 14:07:05 +0200 Subject: Object's nesting scope In-Reply-To: <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> Message-ID: <4a97c851$0$307$426a74cc@news.free.fr> zaur a ?crit : > On 26 ???, 17:13, "Diez B. Roggisch" wrote: >> Whom am we to judge? Sure if you propose this, you have some usecases in >> mind - how about you present these > > Ok. Here is a use case: object initialization. > > For example, > > person = Person(): > name = "john" > age = 30 > address = Address(): > street = "Green Street" > no = 12 > > vs. > > person = Person() > person.name = "john" > person.age = 30 > address = person.address = Address() > address.street = "Green Street" > address.no = 12 Err... Looks like you really should read the FineManual(tm) - specifically, the parts on the __init__ method. class Person(object): def __init__(self, name, age, address): self.name = name self.age = age self.address = address class Address(object): def __init__(self, street, no): self.no = no self.street = street person = Person( name="john", age=30, address = Address( street="Green Street", no=12 ) ) From dukeofperl at ml1.net Fri Aug 28 08:34:08 2009 From: dukeofperl at ml1.net (Duke Normandin) Date: Fri, 28 Aug 2009 06:34:08 -0600 (MDT) Subject: Transforming a str to an operator In-Reply-To: <7a9c25c20908272132p737fe070w5a3c7b0a4970a2c9@mail.gmail.com> References: <7a9c25c20908272132p737fe070w5a3c7b0a4970a2c9@mail.gmail.com> Message-ID: On Thu, 27 Aug 2009, Stephen Hansen wrote: > > > > num1 = raw_input('Enter the first number: ') > > num2 = raw_input('Enter the second number: ') > > op = raw_input('Select one of the following [+-*/]: ') > > print 'The answer is: ', int(num1), eval(op), int(num2) > > ^^^^^^^^ > > > > How do I convert the contents of "op" from a string to an actual > > arithmetic operator? eval() does not seem to be the answer. TIA! > > > > You could eval(num1+op+num2), but it'd be safer to do: > > import operator > operators = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": > operator.div} > fn = operators[op] > print "The answer is:", fn(int(num1), int(num2)) > > Its best to avoid eval when possible :) > > --S > In *any* language "eval" is dangerous, so your second example would also be my choice. Thanks for the clue. BTW, I hunted hi-n-lo for something that would address my question at http://docs.python.org. I obviously didn't have much luck. Something about those docs that is confusing.... -- duke From bbxx789_05ss at yahoo.com Fri Aug 28 08:40:46 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 28 Aug 2009 05:40:46 -0700 (PDT) Subject: Sending email References: <7fpj9tF2clhemU1@mid.individual.net> Message-ID: <2b3621fd-53fc-4f20-a048-3608894e52af@o9g2000prg.googlegroups.com> On Aug 28, 2:37?am, Fencer wrote: > Hello, I'm using Python version 2.6.2 and I discovered it has built-in > libraries for sending email (imports smtplib and email). On the web I > discovered how to send mail through smtp.gmail.com: > > mail_server = smtplib.SMTP() > > mail_server.connect('smtp.gmail.com') > mail_server.ehlo() > mail_server.starttls() > mail_server.ehlo() > mail_server.login('username', 'password') > > msg = MIMEText('Some message text') > msg['Subject'] = 'Some subject' > msg['From'] = 'Mr Underhill' > msg['To'] = 'someemailaddress' > > me = 'myemailaddress' > mail_server.sendmail(me, ['someemailaddress'], msg.as_string()) > > That seems to work just fine but for the messages I will be sending I > don't want to use my private GMail account. > We have an SMTP server at work, and I checked its settings in the > Thunderbird mail client and it's using SSL over port 465, so a bit > different from how GMail's SMTP server is configured in Thunderbird. > > I altered my code slightly to account for this: > mail_server = smtplib.SMTP_SSL() > mail_server.connect('mysmtpserver.at.work', 465) > > Everything I left untouched. However, it doesn't work: > Traceback (most recent call last): > ? ?File "C:\Users\fencer\workspace\Send Email\src\send_email.py", line > 16, in > ? ? ?mail_server.ehlo() > ? ?File "C:\Python26\lib\smtplib.py", line 382, in ehlo > ? ? ?self.putcmd(self.ehlo_msg, name or self.local_hostname) > ? ?File "C:\Python26\lib\smtplib.py", line 318, in putcmd > ? ? ?self.send(str) > ? ?File "C:\Python26\lib\smtplib.py", line 310, in send > ? ? ?raise SMTPServerDisconnected('please run connect() first') > smtplib.SMTPServerDisconnected: please run connect() first > > As you can see, I'm on Windows Vista. > > What do I need to change in my code to fix this problem? Thunderbird > manages to do it! :) Ideally, I would like send an email that the > recipient can't reply to, but if doesn't work, it's fine too. I want to > use this to send automated emails to students with account information > for a course. > > - Fencer The docs say: --- class smtplib.SMTP_SSL([host[, port[, local_hostname[, keyfile[, certfile[, timeout]]]]]]) A SMTP_SSL instance behaves exactly the same as instances of SMTP. SMTP_SSL should be used for situations where SSL is required from the beginning of the connection and using starttls() is not appropriate. --- So try getting ride of these two lines: > mail_server.starttls() > mail_server.ehlo() There's also some info on google about a bug in this regard, so check to see when you installed python 2.6.2. From zvezdan at zope.com Fri Aug 28 09:12:29 2009 From: zvezdan at zope.com (Zvezdan Petkovic) Date: Fri, 28 Aug 2009 09:12:29 -0400 Subject: Does Class implements Interface? In-Reply-To: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> Message-ID: On Aug 27, 2009, at 9:16 AM, Emanuele D'Arrigo wrote: > Are there resources such as tools, recipes, documents or strategies > that could help me deal with these issues? I've already looked into > the ABC module and the zope.interface. I'm just fishing for more > things to look at. You say above that you looked at zope.interface. Did you look at zope.interface.verify? Specifically, verify.txt doctests state that: "An object provides an interface if - either its class declares that it implements the interfaces, or the object declares that it directly provides the interface - the object defines all the methods required by the interface - all the methods have the correct signature - the object defines all non-method attributes required by the interface" zope.interface.verify.verifyObject(I, obj) will check all of the above. Similarly, zope.interface.verify.verifyClass(I, C) will check the class. It is a good practice to call these functions in the regression tests. If this is not what you are looking for, sorry for the noise. Zvezdan From piet at cs.uu.nl Fri Aug 28 09:23:47 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 28 Aug 2009 15:23:47 +0200 Subject: Select column from a list References: Message-ID: >>>>> hoffik (h) wrote: >h> Hello, >h> I'm quite new in Python and I have one question. I have a 2D matrix of >h> values stored in list (3 columns, many rows). I wonder if I can select one >h> column without having to go through the list with 'for' command. >h> For example I have list called 'values'. >h> When I write 'values[0]' or 'values[0][:]' I'll get the first row. >h> But when I write 'values[:][0]' I won't get the first column, but the first >h> row again! I can't see why. If you work with matrices, numpy may be interesting for you. It does have the required functionality: M[:,0] will give you the first column. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From lucafbb at gmail.com Fri Aug 28 09:33:39 2009 From: lucafbb at gmail.com (Luca) Date: Fri, 28 Aug 2009 15:33:39 +0200 Subject: Read a content file from a P7M In-Reply-To: <20090320141244.GA31004@galliera.it> References: <27308d500903110905j336da086ya39300c876aa95a5@mail.gmail.com> <20090320141244.GA31004@galliera.it> Message-ID: <27308d500908280633u310ed4ffu8fe753d69a575265@mail.gmail.com> On Fri, Mar 20, 2009 at 4:12 PM, Emanuele Rocca wrote: > On 11/03/09 - 05:05, Luca wrote: >> There is standard or sugested way in python to read the content of a P7M file? >> >> I don't need no feature like verify sign, or sign using a certificate. >> I only need to extract the content file of the p7m (a doc, a pdf, ...) > > For PDF files you can just remove the P7M content before %PDF and after > %%EOF. > > The following snippet converts /tmp/test.p7m into PDF, saving the > resulting document into /tmp/test.pdf: > > import re > from gzip import GzipFile > > contents = GzipFile('/tmp/test.p7m').read() > > contents_re = re.compile('%PDF-.*%%EOF', re.MULTILINE | re.DOTALL) > contents = contents_re.search(contents).group() > > open('/tmp/test.pdf', 'w').write(contents) > After all those days... only to say THANKS! The example of the PDF file is perfect, I only needed to not execute the GzipFile call (it seems that our PDF are not GZipped). Unluckily now seems that we need the same feature for non-pdf files... -- -- luca From hv at tbz-pariv.de Fri Aug 28 09:42:36 2009 From: hv at tbz-pariv.de (Thomas Guettler) Date: Fri, 28 Aug 2009 15:42:36 +0200 Subject: PyGTK problems after Linux update... In-Reply-To: References: Message-ID: <7fq56dF2m6qlbU1@mid.individual.net> Looks like your pygtk package does not fit to the installed python package. > from glib._glib import * > ImportError: /usr/lib/python2.6/site-packages/gtk-2.0/glib/_glib.so: > undefined symbol: PyUnicodeUCS4_DecodeUTF8 -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From steve at REMOVE-THIS-cybersource.com.au Fri Aug 28 09:43:05 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2009 13:43:05 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> <02a5d290$0$15633$c3e8da3@news.astraweb.com> <02a5ed07$0$15633$c3e8da3@news.astraweb.com> <9f392780-cb72-4bdb-a571-b1c218f3cbf8@k19g2000yqn.googlegroups.com> Message-ID: <00216264$0$2930$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 10:49:27 -0700, Mensanator wrote: > Fine. I'm over it. Point is, I HAVE encountered plenty of people who > DON'T properly understand it, Marilyn Vos Savant, for example. I'm curious -- please explain. Links please? > You can't > blame me for thinking you don't understand it either when unary is > brought up in a discussion of how to interpret insignificant leading > 0's. Er, when I show an example of what I'm calling unary, and then later on explain in detail and link to a detailed discussion of it, who exactly should I blame for your confusion? -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 28 09:51:08 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2009 13:51:08 GMT Subject: Annoying octal notation References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> Message-ID: <00216447$0$2930$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 10:31:04 -0700, Ethan Furman wrote: > Steven D'Aprano wrote: >> A mistake is still a mistake even if it shared with others. >> >> Treating its with a lead zero as octal was a design error when it was >> first thought up > > [snippage] > > I have to disagree with you on this one. The computing world was vastly > different when that design decision was made. Space was at a premium, > programmers were not touch-typists, every character had to count, and > why in the world would somebody who had to use papertape or punch cards > add a lead zero without a *real* good reason? I submit that that real > good reason was to specify an octal literal, and not a decimal literal. Octal with a leading 0 comes from B, which influenced C, which influenced many languages. B was designed in 1969, the same year as Pascal, not the 1950s -- six years *after* Basic, ten years after Lisp and Cobol, eleven years after Algol, and thirteen years after Fortran. *None* of these other languages use a leading 0 for Octal, and none of them are particularly terse. Obviously I can't speak for Ken Thompson's motivation in creating this feature, but I'm pretty sure it wasn't to save typing or space on punchcards. Even in 1969, hex was more common than octal, and yet hex values are written with 0x. My guess is that he wanted all numbers to start with a digit, to simplify parsing, and beyond that, it was just his programming style -- why call the copy command `copy` when you could call it `cp`? (Thompson was the co-inventor of Unix.) -- Steven From bernhard.voigt at gmail.com Fri Aug 28 09:53:49 2009 From: bernhard.voigt at gmail.com (Bernhard Voigt) Date: Fri, 28 Aug 2009 06:53:49 -0700 (PDT) Subject: Select column from a list References: <25185508.post@talk.nabble.com> <9fdb569a0908280228g59038ba1u30d6d5ef9d6a80ca@mail.gmail.com> Message-ID: <708f2333-43d7-4091-8f73-67ef5ef4752a@c2g2000yqi.googlegroups.com> > >> I'm quite new in Python and I have one question. I have a 2D matrix of > >> values stored in list (3 columns, many rows). I wonder if I can select one > >> column without having to go through the list with 'for' command. In case you want to due numerical calculations take a look at numpy it has an extended slicing notation to select columns directly. See http://www.scipy.org # create 10x10 numpy array filled with 1 data = numpy.ones((10,10)) column = data[:,0] Best wishes! Bernhard From sturlamolden at yahoo.no Fri Aug 28 09:55:55 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 28 Aug 2009 06:55:55 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: On 28 Aug, 02:34, Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc ?why ? Because we are better, so fewer are needed. From jakecjacobson at gmail.com Fri Aug 28 09:57:59 2009 From: jakecjacobson at gmail.com (jakecjacobson) Date: Fri, 28 Aug 2009 06:57:59 -0700 (PDT) Subject: How to unencode a string References: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> Message-ID: <31799652-b530-4877-8e2d-c5e7e3477ff0@d38g2000yqi.googlegroups.com> On Aug 27, 6:51?pm, Piet van Oostrum wrote: > >>>>> jakecjacobson (j) wrote: > >j> This seems like a real simple newbie question but how can a person > >j> unencode a string? ?In Perl I use something like: "$part=~ s/\%([A-Fa- > >j> f0-9]{2})/pack('C', hex($1))/seg;" > >j> If I have a string like Word1%20Word2%20Word3 I want to get Word1 > >j> Word2 Word3. ? > > urllib.unquote(string) > > >j> Would also like to handle special characters like '",(){} > >j> [] etc/ > > What would you like to do with them? Or do you mean to replace %27 by ' etc? > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org Yes, take '%27' and replace with ', etc. From hamdori at gmail.com Fri Aug 28 10:11:58 2009 From: hamdori at gmail.com (Jinha Jung) Date: Fri, 28 Aug 2009 07:11:58 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: On Aug 28, 9:55?am, sturlamolden wrote: > On 28 Aug, 02:34, Deep_Feelings wrote: > > > python got relatively fewer numbers of developers than other high > > level languages like .NET , java .. etc ?why ? > > Because we are better, so fewer are needed. That makes sense!! :-) From python at mrabarnett.plus.com Fri Aug 28 10:13:00 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 28 Aug 2009 15:13:00 +0100 Subject: Annoying octal notation In-Reply-To: <00216447$0$2930$c3e8da3@news.astraweb.com> References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> <00216447$0$2930$c3e8da3@news.astraweb.com> Message-ID: <4A97E5EC.5010007@mrabarnett.plus.com> Steven D'Aprano wrote: > On Thu, 27 Aug 2009 10:31:04 -0700, Ethan Furman wrote: > >> Steven D'Aprano wrote: >>> A mistake is still a mistake even if it shared with others. >>> >>> Treating its with a lead zero as octal was a design error when it was >>> first thought up >> [snippage] >> >> I have to disagree with you on this one. The computing world was vastly >> different when that design decision was made. Space was at a premium, >> programmers were not touch-typists, every character had to count, and >> why in the world would somebody who had to use papertape or punch cards >> add a lead zero without a *real* good reason? I submit that that real >> good reason was to specify an octal literal, and not a decimal literal. > > Octal with a leading 0 comes from B, which influenced C, which influenced > many languages. B was designed in 1969, the same year as Pascal, not the > 1950s -- six years *after* Basic, ten years after Lisp and Cobol, eleven > years after Algol, and thirteen years after Fortran. *None* of these > other languages use a leading 0 for Octal, and none of them are > particularly terse. > > Obviously I can't speak for Ken Thompson's motivation in creating this > feature, but I'm pretty sure it wasn't to save typing or space on > punchcards. Even in 1969, hex was more common than octal, and yet hex > values are written with 0x. My guess is that he wanted all numbers to > start with a digit, to simplify parsing, and beyond that, it was just his > programming style -- why call the copy command `copy` when you could call > it `cp`? (Thompson was the co-inventor of Unix.) > Maybe it was because they were working on minicomputers, not mainframes, so there was less processing power and storage available. From steve at REMOVE-THIS-cybersource.com.au Fri Aug 28 10:14:07 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2009 14:14:07 GMT Subject: why python got less developers ? References: Message-ID: <002169aa$0$2930$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 17:34:17 -0700, Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high level > languages like .NET , java .. etc why ? Python programmers are the elite. The elite are always fewer than the masses. -- Steven who is three quarters joking From dukeofperl at ml1.net Fri Aug 28 10:18:48 2009 From: dukeofperl at ml1.net (Duke Normandin) Date: Fri, 28 Aug 2009 14:18:48 GMT Subject: Transforming a str to an operator In-Reply-To: <6ee483f7-e92c-49e0-be27-125f3389b1f2@33g2000vbe.googlegroups.com> References: <6ee483f7-e92c-49e0-be27-125f3389b1f2@33g2000vbe.googlegroups.com> Message-ID: On Thu, 27 Aug 2009, r wrote: > On Aug 27, 10:52?pm, Duke Normandin wrote: > > How do I convert the contents of "op" from a string to an actual > > arithmetic operator? eval() does not seem to be the answer. TIA! > > > Try this.. > > >>> op = '+' > >>> one = '1' > >>> two = '2' > >>> one+op+two > '1+2' > >>> eval(one+op+two) > 3 > > > you could also use string formatting. I see! Concatenate the strings within the "eval()" function. Of course, it's prudent not to expose "eval" to the outside world. But for learning purposes .... Thanks for the input! -- duke From no.i.dont at want.mail.from.spammers.com Fri Aug 28 10:18:57 2009 From: no.i.dont at want.mail.from.spammers.com (Fencer) Date: Fri, 28 Aug 2009 16:18:57 +0200 Subject: Sending email In-Reply-To: <2b3621fd-53fc-4f20-a048-3608894e52af@o9g2000prg.googlegroups.com> References: <7fpj9tF2clhemU1@mid.individual.net> <2b3621fd-53fc-4f20-a048-3608894e52af@o9g2000prg.googlegroups.com> Message-ID: <7fq7aiF2mp83gU1@mid.individual.net> 7stud wrote: [snip] Thanks for your reply. After consulting the sysadmins here I was able to get it to work. - Fencer From dukeofperl at ml1.net Fri Aug 28 10:23:16 2009 From: dukeofperl at ml1.net (Duke Normandin) Date: Fri, 28 Aug 2009 14:23:16 GMT Subject: Transforming a str to an operator In-Reply-To: <87skfcblo3.fsf@benfinney.id.au> References: <87skfcblo3.fsf@benfinney.id.au> Message-ID: On Fri, 28 Aug 2009, Ben Finney wrote: > Duke Normandin writes: > > > Hey.... > > > > I'm a Python noob.... > > > > So far so good! > > > > I've written the following: > > > > num1 = raw_input('Enter the first number: ') > > num2 = raw_input('Enter the second number: ') > > op = raw_input('Select one of the following [+-*/]: ') > > print 'The answer is: ', int(num1), eval(op), int(num2) > > ^^^^^^^^ > > > > How do I convert the contents of "op" from a string to an actual > > arithmetic operator? eval() does not seem to be the answer. TIA! > > In general, ?eval? on unsanitised input is not the answer. Agreed! If I were to expose "eval" to the 'net, I would have some input error checking and "type" checks to insure that only integers and valid operators were being input. > > I would use the following approach: > > import operator > > op_funcs = { > '+': operator.add, > '-': operator.sub, > '*': operator.mul, > '/': operator.div, > } > > num_1 = int(raw_input('Enter the first number: ')) > num_2 = int(raw_input('Enter the second number: ')) > op_prompt = ( > "Select an operator " > + "[" + "".join(s for s in op_funcs.keys()) + "]" > + ": ") > op_symbol = raw_input(op_prompt) > op_func = op_funcs[op_symbol] > print 'The answer is: ', op_func(num_1, num_2) > > This has several advantages: > > * The input isn't evaluated directly as code. > > * The operator symbols are specified in one place, the ?op_funcs? > mapping; if you want to change the set of possible operators, you just > change it there. > > * If the input results in an operator that's not defined, it won't > attempt to perform it; instead, a simple KeyError will result when > trying to find the corresponding operator function. Cool! Something useful to study... Thanks for the input! -- duke From steve at REMOVE-THIS-cybersource.com.au Fri Aug 28 10:30:00 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2009 14:30:00 GMT Subject: Algorithms as objects? References: Message-ID: <00216d63$0$2930$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 23:05:41 +0000, Kreso wrote: > I am writing an application that essentially calculates set of numbers, > say N1, N2, ..., where they can be calculated by several different > algorithms. (One should be able to choose the algorithm at run time.) In > each algorithm one starts from a set of functions, say f1, f2, ..., > which are then transformed into some other functions g1(f1, f2, ..), > g2(f1, f2, ...), ... , then maybe transformed once more and result is > obtained by evaluating final functions. Sounds like you're doing functional programming. There's a rich set of functional tools in languages like Haskell, but in Python there's only a few, such as partial(). (See the functools module.) However, you can make your own, using the following general technique. Suppose you want to compose two functions, f and g. Then with a helper function: def compose(f, g): def composed_function(*args): return f(g(*args)) return composed_function you can do this: >>> def add1(x): ... return x+1 ... >>> def double(y): ... return 2*y ... >>> double_plus_one = compose(add1, double) >>> double_plus_one(3.5) 8.0 Unfortunately, about the only thing you can't do is check the return type of functions without actually calling them. > I can naturally think about this as a collection of transformation > blocks, which have functions as input and output, and which can be put > together to get the final results. However, I am not sure how to program > this, especially since one cannot subclass function type. To be clear > let me give simplified example of what is needed: > > f(x) has unknown shape, so one would like to try, say > > f1(x) = ax - b x**2 or f2(x) = a sin(b*x), > > where a and b are variable parameters. You need factory functions! def axbx2_factory(a, b): # Return a function that returns a*x-b*x**2 def inner(x): return a*x -b*x**2 return inner And in use: >>> f1 = axbx2_factory(1, 2) >>> f2 = axbx2_factory(1, 0) >>> f1(2.5) -10.0 >>> f1(3.5) -21.0 >>> f2(2.5) 2.5 >>> f2(3.5) 3.5 Hope this helps. -- Steven From rt8396 at gmail.com Fri Aug 28 10:41:27 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 07:41:27 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> Message-ID: Thanks eb303 for the wonderful post I have looked over the new ttk widgets and everything looks nice. I am very glad to see the death of Tix as i never much liked it anyhow and always believed these widgets should have been in the main Tkinter module to start with. The tree widget has been needed for some time. However, i am not sure about the new "style" separation. Previously a simple command like root.option_add('*Label.Font'...) accomplished the same thing with less typing, but there may be a future method to this current madness that i am unaware of...??? From rknop at pobox.com Fri Aug 28 10:51:09 2009 From: rknop at pobox.com (Rob Knop) Date: Fri, 28 Aug 2009 09:51:09 -0500 Subject: write Unicode to sys.out.write without access to sitecustomize.py Message-ID: <871vmw56w2.fsf@pobox.com> I would like to tell the system that it's OK to write Unicode to sys.out and sys.err. However, I'm doing this in a CGI script where I don't have access to the system directories, and as such can't use sys.setdefaultencoding in sitecustomize.py. Is there a way to make this happen? -- --Rob Knop E-mail: rknop at pobox.com Home Page: http://www.pobox.com/~rknop/ Blog: http://www.sonic.net/~rknop/blog/ From gb345 at invalid.com Fri Aug 28 10:58:11 2009 From: gb345 at invalid.com (gb345) Date: Fri, 28 Aug 2009 14:58:11 +0000 (UTC) Subject: Modules/packages by GvR? Message-ID: Are there any Python-only modules or packages in the latest releases of Python 2.x or Python 3.x that were largely written by Guido van Rossum? What's the best way to find this out? I know that some modules mention the author(s) in the source code, but this does not seem to be true most of the time, as far as I can tell. I'm interested in reading this code as prime examplars of "Pythonicity". (I'm sure that many other programmers could serve as models of the Pythonic ideal, but I doubt that there would be a *less debatable* choice in this category than GvR.) Many thanks in advance, Gabe From gagsl-py2 at yahoo.com.ar Fri Aug 28 10:58:13 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Aug 2009 11:58:13 -0300 Subject: Transforming a str to an operator References: <87skfcblo3.fsf@benfinney.id.au> <2d56febf0908272150y59e5d458hab1fc6aa9c14187e@mail.gmail.com> Message-ID: En Fri, 28 Aug 2009 01:50:37 -0300, Xavier Ho escribi?: > On Fri, Aug 28, 2009 at 2:35 PM, Ben Finney > >> wrote: > >> op_funcs = { >> '+': operator.add, >> '-': operator.sub, >> '*': operator.mul, >> '/': operator.div, >> } >> op_prompt = "Select an operator ({}):".format(','.join(op for op in >> op_funcs)) op_prompt = "Select an operator ({}):".format(','.join(op_funcs)) > Just fixing the code a little to be more "Pythonic" ;). Even more ;) -- Gabriel Genellina From breamoreboy at yahoo.co.uk Fri Aug 28 11:12:50 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Aug 2009 16:12:50 +0100 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <2d56febf0908280204k73a41cc0j63717c8ca258ff33@mail.gmail.com> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <87k50ob9o9.fsf@benfinney.id.au> <2d56febf0908280204k73a41cc0j63717c8ca258ff33@mail.gmail.com> Message-ID: Xavier Ho wrote: > On Fri, Aug 28, 2009 at 6:54 PM, Ben Finney > >> wrote: > >> Fortunately, the messages that come from the list enable any mail client >> to know the correct address for ?reply to list?. It only remains to >> choose a mail client that knows how to use it. > > > Would you be so kind and share with us for such a client that knows how to > use the mailing list attribute? > > Thanks! > -Xav > > Further to the earlier reply from Albert Hopkins, I use Thunderbird on Windows and just hit reply. The message I reply to is "from Xavier Ho " and "to python-list at python.org". I think this sums it up. -- Kindest regards. Mark Lawrence. From bouncyinc at gmail.com Fri Aug 28 11:18:06 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Fri, 28 Aug 2009 09:18:06 -0600 Subject: Modules/packages by GvR? In-Reply-To: References: Message-ID: How is writing code like a language maintainer going to go towards a philosophic ideal? And more principally why would this be of a benefit. In the philosophic world dressing and acting like Socrates isn't necessarily the same as following his ideals and isn't necessarily being Socratic. On Fri, Aug 28, 2009 at 8:58 AM, gb345 wrote: > > > > > Are there any Python-only modules or packages in the latest releases > of Python 2.x or Python 3.x that were largely written by Guido van > Rossum? What's the best way to find this out? I know that some > modules mention the author(s) in the source code, but this does > not seem to be true most of the time, as far as I can tell. > > I'm interested in reading this code as prime examplars of "Pythonicity". > (I'm sure that many other programmers could serve as models of the > Pythonic ideal, but I doubt that there would be a *less debatable* > choice in this category than GvR.) > > Many thanks in advance, > > Gabe > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at twistedmatrix.com Fri Aug 28 11:22:49 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Fri, 28 Aug 2009 15:22:49 -0000 Subject: write Unicode to sys.out.write without access to sitecustomize.py In-Reply-To: <871vmw56w2.fsf@pobox.com> References: <871vmw56w2.fsf@pobox.com> Message-ID: <20090828152249.7507.1150495477.divmod.xquotient.5@localhost.localdomain> On 02:51 pm, rknop at pobox.com wrote: > >I would like to tell the system that it's OK to write Unicode to >sys.out >and sys.err. However, I'm doing this in a CGI script where I don't >have >access to the system directories, and as such can't use >sys.setdefaultencoding in sitecustomize.py. > >Is there a way to make this happen? Sure, just replace the two files with versions that know how to encode the unicode using the correct encoding: import sys, codecs info = codecs.lookup('utf-8') # for example sys.stdout = info.streamwriter(sys.stdout) sys.stderr = info.streamwriter(sys.stderr) Jean-Paul From mccredie at gmail.com Fri Aug 28 11:28:02 2009 From: mccredie at gmail.com (Matimus) Date: Fri, 28 Aug 2009 08:28:02 -0700 (PDT) Subject: Modules/packages by GvR? References: Message-ID: <789935e7-1952-49bb-8ae1-90b7787d5ff2@r24g2000prf.googlegroups.com> On Aug 28, 7:58?am, gb345 wrote: > Are there any Python-only modules or packages in the latest releases > of Python 2.x or Python 3.x that were largely written by Guido van > Rossum? ?What's the best way to find this out? ?I know that some > modules mention the author(s) in the source code, but this does > not seem to be true most of the time, as far as I can tell. > > I'm interested in reading this code as prime examplars of "Pythonicity". > (I'm sure that many other programmers could serve as models of the > Pythonic ideal, but I doubt that there would be a *less debatable* > choice in this category than GvR.) > > Many thanks in advance, > > Gabe I'm sure there are. You might be able to figure that out by browsing the source repository: http://hg.python.org. But, I wouldn't necessarily say that any code written by Guido would make a good example of 'Pythonic' code. Not that he doesn't create good code, but the language and standards have evolved over time. There may be code that he wrote from the 2.0 days that may have been perfectly 'Pythonic' then but is just out-of-date now. In general though, browsing the standard modules is a good way to find examples, no matter who wrote it. Just keep in mind when it was written more than who wrote it. Matt From jfabiani at yolo.com Fri Aug 28 11:36:24 2009 From: jfabiani at yolo.com (jfabiani at yolo.com) Date: Fri, 28 Aug 2009 08:36:24 -0700 Subject: why python got less developers ? References: Message-ID: Chris Rebert wrote: > On Thu, Aug 27, 2009 at 5:34 PM, Deep_Feelings > wrote: >> python got relatively fewer numbers of developers than other high >> level languages like .NET , java .. etc ?why ? > > We lack Sun and Microsoft's massive marketing departments. :) I'm inclined to agreed. But in recent years we lost a number of developers to Ruby. I don't know but I doubt Ruby has a marketing budget. So in my mind it is difficult for me to blame just the lack of marketing dollars for the lost. I do take heart in a recent article (on Linux today). that less than 5% of open source is using C#. Which tells me that .Net in the open source world is not doing well. So in my opinion the OP is wrong when he includes .Net in his assessment of developers. As far as what the OP is suggesting I'm not to sure it matters how many total developers are using Python. Python is always in the top ten of the languages in use. And therefore is very popular. I use it daily. But it does not mean I don't use other languages too. Johnf From ethan at stoneleaf.us Fri Aug 28 11:42:26 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 28 Aug 2009 08:42:26 -0700 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A97FAE2.4060108@stoneleaf.us> kj wrote: > Miles Kaufmann writes: >>...because the suite >>namespace and the class namespace would get out of sync when different >>objects were assigned to the class namespace: > > >>class C: >> x = 1 >> def foo(self): >> print x >> print self.x > > >>>>>o = C() >>>>>o.foo() >> >>1 >>1 >> >>>>>o.x = 2 >>>>>o.foo() >> >>1 >>2 > > > But this unfortunate situation is already possible, because one > can already define > > class C: > x = 1 > def foo(self): > print C.x > print self.x > > which would lead to exactly the same thing. > This is not the same thing, and definitely not exactly the same thing. In your example you are explicitly stating whether you want the original class variable, or the current, and possibly different, instance variable. Further, the instance variable will not be different from the class variable, even after C.x = whatever, unless the instance has had that variable set specifically for it. In [1]: class C(object): ...: x = 9 ...: def doit(self): ...: print C.x ...: print self.x ...: In [2]: test = C() In [3]: test.doit() 9 9 In [4]: C.x = 10 In [5]: test.doit() 10 10 In [6]: test.x = 7 In [7]: test.doit() 10 7 ~Ethan~ From googleaccount at rumbalski.com Fri Aug 28 11:43:42 2009 From: googleaccount at rumbalski.com (Steven Rumbalski) Date: Fri, 28 Aug 2009 08:43:42 -0700 (PDT) Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> Message-ID: <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> On Aug 27, 3:06?pm, vsoler wrote: > I am trying to read a csv file generated by excel. > > Although I succeed in reading the file, the format that I get is not > suitable for me. > > I've done: > > >>> import csv > >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) > >>> print spamReader > > <_csv.reader object at 0x01022E70> > > >>> for row in spamReader: > > ? ? ? ? print row > > ['codigo;nombre;cantidad'] > ['a;qwe;1'] > ['b;asd;2'] > ['c;zxc;3'] > > My questions are: > > 1- Why using "print spamReader" I cannot see the data? > ? ? I expected to see a list of lists, a kind of a matrix, but I get > nothing > > 2- Why are the rows in a single string? > ? ?I expected a list of fields that, when text, would be delimited by > " > ? To tell the truth, the file generated by excel does not contain the > strings delimited by ". Isn't it weird? > > 3- Is there anything I can do to have my data in a list of lists > structure? would another kind of data suit better my needs? > > Thank you for your help > > Vicente Soler the csv module can handle any delimiter. change this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) to this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r'), delimiter=';') hope this helps, Steven Rumbalski From bbxx789_05ss at yahoo.com Fri Aug 28 11:49:12 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 28 Aug 2009 08:49:12 -0700 (PDT) Subject: Sending email References: <7fpj9tF2clhemU1@mid.individual.net> <2b3621fd-53fc-4f20-a048-3608894e52af@o9g2000prg.googlegroups.com> <7fq7aiF2mp83gU1@mid.individual.net> Message-ID: On Aug 28, 8:18?am, Fencer wrote: > 7stud wrote: > > [snip] > > Thanks for your reply. After consulting the sysadmins here I was able to > get it to work. > > - Fencer Ok, but how about posting your code so that a future searcher will not be left screaming, "WHAT THE EFF WAS THE SOLUTION!!" From pavpanchekha at gmail.com Fri Aug 28 11:50:14 2009 From: pavpanchekha at gmail.com (Pavel Panchekha) Date: Fri, 28 Aug 2009 08:50:14 -0700 (PDT) Subject: Distutils evil voodoo: install into a package References: <824505df-5534-423e-b72c-06d0f62b376b@p15g2000vbl.googlegroups.com> <7fgi5oF2juk72U2@mid.uni-berlin.de> Message-ID: <08f192f0-fdcd-420d-9152-3873f5b77e59@j19g2000vbp.googlegroups.com> > This is what whe world has created namespace-packages for. At least if > you can live with the namespace "pya" being otherwise empty. That seems like a good solution. Thanks! From breamoreboy at yahoo.co.uk Fri Aug 28 11:56:38 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Aug 2009 16:56:38 +0100 Subject: Modules/packages by GvR? In-Reply-To: References: Message-ID: [fix top posting] > On Fri, Aug 28, 2009 at 8:58 AM, gb345 wrote: > >> >> >> >> Are there any Python-only modules or packages in the latest releases >> of Python 2.x or Python 3.x that were largely written by Guido van >> Rossum? What's the best way to find this out? I know that some >> modules mention the author(s) in the source code, but this does >> not seem to be true most of the time, as far as I can tell. >> >> I'm interested in reading this code as prime examplars of "Pythonicity". >> (I'm sure that many other programmers could serve as models of the >> Pythonic ideal, but I doubt that there would be a *less debatable* >> choice in this category than GvR.) >> >> Many thanks in advance, >> >> Gabe >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > John Haggerty wrote: > How is writing code like a language maintainer going to go towards a > philosophic ideal? And more principally why would this be of a benefit. In > the philosophic world dressing and acting like Socrates isn't necessarily > the same as following his ideals and isn't necessarily being Socratic. > So the poor old BDFL has been reduced to the rank of language maintainer. Is it safe to assume that somebody is organising a whip round for him? Any and all currencies accepted? -- Kindest regards. Mark Lawrence. From tjreedy at udel.edu Fri Aug 28 12:09:39 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Aug 2009 12:09:39 -0400 Subject: Modules/packages by GvR? In-Reply-To: <789935e7-1952-49bb-8ae1-90b7787d5ff2@r24g2000prf.googlegroups.com> References: <789935e7-1952-49bb-8ae1-90b7787d5ff2@r24g2000prf.googlegroups.com> Message-ID: Matimus wrote: > On Aug 28, 7:58 am, gb345 wrote: >> Are there any Python-only modules or packages in the latest releases >> of Python 2.x or Python 3.x that were largely written by Guido van >> Rossum? What's the best way to find this out? I know that some >> modules mention the author(s) in the source code, but this does >> not seem to be true most of the time, as far as I can tell. >> >> I'm interested in reading this code as prime examplars of "Pythonicity". >> (I'm sure that many other programmers could serve as models of the >> Pythonic ideal, but I doubt that there would be a *less debatable* >> choice in this category than GvR.) >> >> Many thanks in advance, >> >> Gabe > > I'm sure there are. You might be able to figure that out by browsing > the source repository: http://hg.python.org. But, I wouldn't > necessarily say that any code written by Guido would make a good > example of 'Pythonic' code. Not that he doesn't create good code, but > the language and standards have evolved over time. There may be code > that he wrote from the 2.0 days that may have been perfectly > 'Pythonic' then but is just out-of-date now. I am not aware of any recent stdlib modules written by Guido. I suspect most older ones have been updated at least once by someone else. > In general though, browsing the standard modules is a good way to find > examples, no matter who wrote it. Just keep in mind when it was > written more than who wrote it. The itertools module is relatively recent and has been recommended as one to read. From mark at markroseman.com Fri Aug 28 12:12:32 2009 From: mark at markroseman.com (Mark Roseman) Date: Fri, 28 Aug 2009 10:12:32 -0600 Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> Message-ID: With regard to Tkinter documentation, and in particular the newer, more modern aspects thereof (e.g. ttk, styles, etc.) please have a look at the tutorial at http://www.tkdocs.com Would it be useful to link to this from the main Python Tkinter documentation? Mark From nagle at animats.com Fri Aug 28 12:18:11 2009 From: nagle at animats.com (John Nagle) Date: Fri, 28 Aug 2009 09:18:11 -0700 Subject: Python on the Web In-Reply-To: <08ac740a-de74-4b5d-94af-35ab4dbe6ecc@m3g2000pri.googlegroups.com> References: <08ac740a-de74-4b5d-94af-35ab4dbe6ecc@m3g2000pri.googlegroups.com> Message-ID: <4a9801fa$0$1651$742ec2ed@news.sonic.net> Graham Dumpleton wrote: > A few additional comments on top of what others have said. > > On Aug 26, 11:09 am, Phil wrote: >> As I've read elsewhere, "These days, FastCGI is never used directly. Actually, FCGI works quite well. Sitetruth's AdRater (http://www.sitetruth.com/downloads/adrater.html) uses FCGI and Python on the server. FCGI is basically CGI with process reusability. Each app gets its own process in its own address space with its own global interpreter lock. mod_fcgi in Apache keeps a supply of such processes around, launching additional ones if there's heavy request traffic and shutting down existing ones when there isn't. Each process handles one transaction after another, so, unlike CGI, you're not spending all your time loading Python and its modules. Here's the main loop of a real FCGI application. This uses a small WSGI library on the Python side. No "framework" is involved. #!/usr/local/bin/python ... from fcgi import WSGIServer import MySQLdb db = None # database connection, held open for life of FCGI # # The application # def QuickSitetruthQuery(environ, start_response): global db # static global - active database handle try: if db : # if previously attached try : db.ping() # test whether connection is still up # handle loss of database connection except MySQLdb.OperationalError, message: db = None # we lost database connection if db is None : # if no valid database handle db = miscutils.dbattach(kdbfile) # connect to database status = '200 OK' # normal status headers = [('Content-type','text/xml'), ('charset','utf-8')] reqlist = cgi.parse_qsl(environ['QUERY_STRING']) # Parse params priority = 1 # priority of request sourceip = environ['REMOTE_ADDR'] # get IP address of client urls = [] # list of URLs to check for item in reqlist : # for all items (key, value) = item # extract item if key.lower() == 'url' : # want all "url" items urls.append(value) elif key.lower() == 'priority' : # if priority priority = int(value) # get priority value # Make request; no waiting, no details outstr = InfoDisplay.getratingXMLquick(db, kdbfile, urls, priority, sourceip) # get the rating XML, never wait start_response(status, headers) # compose result s = kprefixxml + outstr + ksuffixxml # construct output XML return [s.encode('utf8')] # encode as UTF8 except Exception, message: # if trouble, report to user # Error handling status = "500 Internal Error on Server" response_headers = [("Content-type","text/html")] start_response(status, response_headers) s = "

Internal error - request not processed.

\n\n" + traceback.format_exc() s = s.replace("\n","
") # convert to HTML return [s] # # Main FCGI program # WSGIServer(QuickSitetruthQuery).run() From bdesth.quelquechose at free.quelquepart.fr Fri Aug 28 12:32:36 2009 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 18:32:36 +0200 Subject: Python on the Web In-Reply-To: <4a9812d9$0$1617$742ec2ed@news.sonic.net> References: <4a94ef42$0$27774$426a74cc@news.free.fr> <4a96884b$0$22855$426a74cc@news.free.fr> <1b7a2f45-dd10-4722-a9d8-8c6d2464e4d6@e27g2000yqm.googlegroups.com> <4a97c215$0$16809$426a74cc@news.free.fr> <4a9812d9$0$1617$742ec2ed@news.sonic.net> Message-ID: <4a98224c$0$437$426a34cc@news.free.fr> John Nagle a ?crit : > Bruno Desthuilliers wrote: >> If you're only writing your framework for learning purposes, you could >> as well go with Python 3, and implement everything from the ground up >> (not a trivial task FWIW). > > Python 3 isn't ready for prime time on web servers. Too many major > modules, > haven't been ported yet. Which ones (sorry, still using 2.5 at work so I didn't bother that much with 2.6 so far) ? > MySQLdb is available only up to Python 2.5. So the basics > for web work aren't > ready yet. I wouldn't label MySQLdb as "a basic for web work" - I mean, something you just can't do without !-) From vicente.soler at gmail.com Fri Aug 28 12:35:19 2009 From: vicente.soler at gmail.com (vsoler) Date: Fri, 28 Aug 2009 09:35:19 -0700 (PDT) Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> Message-ID: On Aug 28, 5:43?pm, Steven Rumbalski wrote: > On Aug 27, 3:06?pm, vsoler wrote: > > > > > I am trying to read a csv file generated by excel. > > > Although I succeed in reading the file, the format that I get is not > > suitable for me. > > > I've done: > > > >>> import csv > > >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) > > >>> print spamReader > > > <_csv.reader object at 0x01022E70> > > > >>> for row in spamReader: > > > ? ? ? ? print row > > > ['codigo;nombre;cantidad'] > > ['a;qwe;1'] > > ['b;asd;2'] > > ['c;zxc;3'] > > > My questions are: > > > 1- Why using "print spamReader" I cannot see the data? > > ? ? I expected to see a list of lists, a kind of a matrix, but I get > > nothing > > > 2- Why are the rows in a single string? > > ? ?I expected a list of fields that, when text, would be delimited by > > " > > ? To tell the truth, the file generated by excel does not contain the > > strings delimited by ". Isn't it weird? > > > 3- Is there anything I can do to have my data in a list of lists > > structure? would another kind of data suit better my needs? > > > Thank you for your help > > > Vicente Soler > > the csv module can handle any delimiter. > > change this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) > to this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r'), > delimiter=';') > > hope this helps, > Steven Rumbalski Thank you very much for all your comments. After reading them I can conclude that: 1- the CSV format is not standardized; each piece of software uses it differently 2- the "C" in "CSV" does not mean "comma" for Microsoft Excel; the ";" comes from my regional Spanish settings 3- Excel does not even put quotes around litteral texts, not even when the text contains a blank But, perhaps, there is no standard alternative to CSV !!! From benjamin at python.org Fri Aug 28 12:35:40 2009 From: benjamin at python.org (Benjamin Peterson) Date: Fri, 28 Aug 2009 16:35:40 +0000 (UTC) Subject: Modules/packages by GvR? References: <789935e7-1952-49bb-8ae1-90b7787d5ff2@r24g2000prf.googlegroups.com> Message-ID: Terry Reedy udel.edu> writes > > I am not aware of any recent stdlib modules written by Guido. I suspect > most older ones have been updated at least once by someone else. Guido wrote a good deal of the new Python 3 code. However, maintence has now turned over to over Python developers. For example, I now maintain 2to3 and the io library, both of which were originally written by Guido. > > > In general though, browsing the standard modules is a good way to find > > examples, no matter who wrote it. Just keep in mind when it was > > written more than who wrote it. > > The itertools module is relatively recent and has been recommended as > one to read. That probably don't do much good for your sense of Pythonicity, since it's written in C. :) From gagsl-py2 at yahoo.com.ar Fri Aug 28 12:41:35 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Aug 2009 13:41:35 -0300 Subject: Object's nesting scope References: <2751e263-ace0-4649-997c-1302d0f3b320@m20g2000vbp.googlegroups.com> <03269cff-acd9-401a-b98d-0b1136b0d2e0@s13g2000yql.googlegroups.com> <2c78ef30-3af6-45bd-b772-e09d895b0cd8@o15g2000yqm.googlegroups.com> Message-ID: En Thu, 27 Aug 2009 12:43:55 -0300, zaur escribi?: > On 27 ???, 19:19, Carl Banks wrote: >> On Aug 27, 8:01?am, zaur wrote: >> > On 27 ???, 18:34, Carl Banks wrote: >> > > The idea has been >> > > discussed in various forms here quite a bit over the years. ?I doubt >> > > there's any chance it'll be accepted into Python, because it goes >> > > against one of the main design points of Python: that attributes >> > > should always be accessed explicitly. >> > In my opinion idea of using object's dictionary as nested scope is > more about structuring code blocks rather than just saving typing and > implicit attribute access. But you *are* doing implicit attribute access. Anyway, the topic was raised and rejected several times in the past; see this recent thread in the python-ideas list: http://comments.gmane.org/gmane.comp.python.ideas/5518 -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Aug 28 13:02:32 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Aug 2009 14:02:32 -0300 Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> Message-ID: En Fri, 28 Aug 2009 13:35:19 -0300, vsoler escribi?: > On Aug 28, 5:43?pm, Steven Rumbalski > wrote: >> On Aug 27, 3:06?pm, vsoler wrote: >> > I am trying to read a csv file generated by excel. >> > ['a;qwe;1'] >> > ['b;asd;2'] >> > ['c;zxc;3'] > > Thank you very much for all your comments. After reading them I can > conclude that: > > 1- the CSV format is not standardized; each piece of software uses it > differently Yes! And that's part of the pain of working with 'csv' files. > 2- the "C" in "CSV" does not mean "comma" for Microsoft Excel; the ";" > comes from my regional Spanish settings Yes - but not just Excel, other programs do call "CSV" files that are TAB-separated, by example. > 3- Excel does not even put quotes around litteral texts, not even when > the text contains a blank I guess you'll get quotes around text containing ';' characters > But, perhaps, there is no standard alternative to CSV !!! Of course there are! You may use SYLK, DIFF, XML, XDR... "The nice thing about standards is that there are so many to choose from." (Andrew S. Tanenbaum) But look for the xlrd package, it lets you read Excel files directly from Python. -- Gabriel Genellina From dns4 at cornell.edu Fri Aug 28 13:06:09 2009 From: dns4 at cornell.edu (David Smith) Date: Fri, 28 Aug 2009 13:06:09 -0400 Subject: Question on the "csv" library In-Reply-To: References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> Message-ID: vsoler wrote: > > Thank you very much for all your comments. After reading them I can > conclude that: > > 1- the CSV format is not standardized; each piece of software uses it > differently True, but there are commonalities. See http://en.wikipedia.org/wiki/Comma-separated_values > > 2- the "C" in "CSV" does not mean "comma" for Microsoft Excel; the ";" > comes from my regional Spanish settings The C really does stand for comma. I've never seen MS spit out semi-colon separated text on a CSV format. > > 3- Excel does not even put quotes around litteral texts, not even when > the text contains a blank There is no need to quote text literals with whitespace in them. There is a need when a newline exists or when the separator character is embedded in the field. --David From gagsl-py2 at yahoo.com.ar Fri Aug 28 13:09:52 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Aug 2009 14:09:52 -0300 Subject: Raw data extraction question References: <250bf47b-6307-435a-b991-caee359c4ccf@n11g2000yqb.googlegroups.com> Message-ID: En Wed, 26 Aug 2009 12:18:23 -0300, Maggie escribi?: > i have event timing stretch of code i need to alter. here is code > below: > -------------- > # we start each run with one full silent trial > # creating a "stub" with the duration of a full block > # less the discarded acquisitions > stub = block_dur - (distax * tr) > > feed = sys.stdin.readlines() > sess = -1 > for line in feed: > if re.search(line != rest): > time = (line + line (-1)) + (distax * tr) > print time > > elif (line(-1) = rest): > # block onsets are determined by > # block number, block duration, > # and the stub; 3dDeconvolve > # takes care of making these > # "global" > time = (line) + (distax * tr) > print time > ----- When you post some piece of code, copy & paste it from the original source; don't retype. The code above don't even compile. > my concern is that it is extracting line number and not data contained > on a given line. I need it to extract data from each line (excluding > lines with spaces and/or lines that contain the word "pause" or > "silence"). Basically i need ONLY raw data extracted from line 1 - > onward. How does a line look like? Post some sample lines. -- Gabriel Genellina From breamoreboy at yahoo.co.uk Fri Aug 28 13:14:36 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Aug 2009 18:14:36 +0100 Subject: Question on the "csv" library In-Reply-To: References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> Message-ID: vsoler wrote: > On Aug 28, 5:43 pm, Steven Rumbalski > wrote: >> On Aug 27, 3:06 pm, vsoler wrote: >> >> >> >>> I am trying to read a csv file generated by excel. >>> Although I succeed in reading the file, the format that I get is not >>> suitable for me. >>> I've done: >>>>>> import csv >>>>>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) >>>>>> print spamReader >>> <_csv.reader object at 0x01022E70> >>>>>> for row in spamReader: >>> print row >>> ['codigo;nombre;cantidad'] >>> ['a;qwe;1'] >>> ['b;asd;2'] >>> ['c;zxc;3'] >>> My questions are: >>> 1- Why using "print spamReader" I cannot see the data? >>> I expected to see a list of lists, a kind of a matrix, but I get >>> nothing >>> 2- Why are the rows in a single string? >>> I expected a list of fields that, when text, would be delimited by >>> " >>> To tell the truth, the file generated by excel does not contain the >>> strings delimited by ". Isn't it weird? >>> 3- Is there anything I can do to have my data in a list of lists >>> structure? would another kind of data suit better my needs? >>> Thank you for your help >>> Vicente Soler >> the csv module can handle any delimiter. >> >> change this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) >> to this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r'), >> delimiter=';') >> >> hope this helps, >> Steven Rumbalski > > Thank you very much for all your comments. After reading them I can > conclude that: > > 1- the CSV format is not standardized; each piece of software uses it > differently > > 2- the "C" in "CSV" does not mean "comma" for Microsoft Excel; the ";" > comes from my regional Spanish settings > > 3- Excel does not even put quotes around litteral texts, not even when > the text contains a blank > > But, perhaps, there is no standard alternative to CSV !!! This depends on the use case of yourself or your users. If you could give more detail on what you are trying to achieve then I'm sure that more help will be forthcoming. For example, could the file be saved in Excel 97-2003 xls format and then processed with the excellent xlrd/xlwt/xlutils? They are available here:- http://pypi.python.org/pypi/xlutils/1.4.0 -- Kindest regards. Mark Lawrence. From hniksic at xemacs.org Fri Aug 28 13:19:44 2009 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 28 Aug 2009 19:19:44 +0200 Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> Message-ID: <87ocpzdff3.fsf@busola.homelinux.net> David Smith writes: >> 2- the "C" in "CSV" does not mean "comma" for Microsoft Excel; the ";" >> comes from my regional Spanish settings > > The C really does stand for comma. I've never seen MS spit out > semi-colon separated text on a CSV format. That's because you're running MS Office in a US language environment. In almost all of Europe MS products use comma as the decimal separator, and semicolon for CSV field separation. From no.email at please.post Fri Aug 28 13:23:37 2009 From: no.email at please.post (kj) Date: Fri, 28 Aug 2009 17:23:37 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: In Ethan Furman writes: >kj wrote: >> Miles Kaufmann writes: >>>...because the suite >>>namespace and the class namespace would get out of sync when different >>>objects were assigned to the class namespace: >> >> >>>class C: >>> x = 1 >>> def foo(self): >>> print x >>> print self.x >> >> >>>>>>o = C() >>>>>>o.foo() >>> >>>1 >>>1 >>> >>>>>>o.x = 2 >>>>>>o.foo() >>> >>>1 >>>2 >> >> >> But this unfortunate situation is already possible, because one >> can already define >> >> class C: >> x = 1 >> def foo(self): >> print C.x >> print self.x >> >> which would lead to exactly the same thing. >> >This is not the same thing, and definitely not exactly the same thing. Thanks for the clarification! kynn From rt8396 at gmail.com Fri Aug 28 13:27:15 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 10:27:15 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> Message-ID: <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> On Aug 28, 11:12?am, Mark Roseman wrote: > Would it be useful to link to this from the main Python Tkinter > documentation? > > Mark Thanks Mark, but i would hate to see more links to TCL code in the python docs. Whats the use of Tkinter if the docs are in TCL. Just learn TCL and skip the Python middleman. But i don;t want to code in TCL (*puke*) i much prefer Python even if i am calling wrapped TCL. Not to mention this link is not a complete coverage of all the widgets anyway. We desperately need a complete reference for tkinter written with only Python code that covers all widgets, all widget options, and all widget methods. And this would be a minimal effort if someone would just do it. Most of the information is already out there in various locations around the net. We just need to compile, compress, and edit it into one short and to the point reference material. I will happily volunteer to create on my own or contribute to the docs if i can get a guarantee from the tkinter maintainer that my work would not be in vain. From nagle at animats.com Fri Aug 28 13:30:09 2009 From: nagle at animats.com (John Nagle) Date: Fri, 28 Aug 2009 10:30:09 -0700 Subject: Python on the Web In-Reply-To: <4a97c215$0$16809$426a74cc@news.free.fr> References: <4a94ef42$0$27774$426a74cc@news.free.fr> <4a96884b$0$22855$426a74cc@news.free.fr> <1b7a2f45-dd10-4722-a9d8-8c6d2464e4d6@e27g2000yqm.googlegroups.com> <4a97c215$0$16809$426a74cc@news.free.fr> Message-ID: <4a9812d9$0$1617$742ec2ed@news.sonic.net> Bruno Desthuilliers wrote: > If you're only writing your framework for learning purposes, you could > as well go with Python 3, and implement everything from the ground up > (not a trivial task FWIW). Python 3 isn't ready for prime time on web servers. Too many major modules, haven't been ported yet. Twisted and Django are now available up to Python 2.6; MySQLdb is available only up to Python 2.5. So the basics for web work aren't ready yet. Python 2.5 is more or less the "stable" version of Python for production use at the moment. 2.6 is a transition version to 3.0. John Nagle From breamoreboy at yahoo.co.uk Fri Aug 28 13:44:22 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Aug 2009 18:44:22 +0100 Subject: An assessment of Tkinter and IDLE In-Reply-To: <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> Message-ID: r wrote: > On Aug 28, 11:12 am, Mark Roseman wrote: >> Would it be useful to link to this from the main Python Tkinter >> documentation? >> >> Mark > > Thanks Mark, but i would hate to see more links to TCL code in the > python docs. Whats the use of Tkinter if the docs are in TCL. Just > learn TCL and skip the Python middleman. But i don;t want to code in > TCL (*puke*) i much prefer Python even if i am calling wrapped TCL. > Not to mention this link is not a complete coverage of all the widgets > anyway. > > We desperately need a complete reference for tkinter written with only > Python code that covers all widgets, all widget options, and all > widget methods. And this would be a minimal effort if someone would > just do it. Most of the information is already out there in various > locations around the net. We just need to compile, compress, and edit > it into one short and to the point reference material. > > I will happily volunteer to create on my own or contribute to the docs > if i can get a guarantee from the tkinter maintainer that my work > would not be in vain. Please go ahead and try it. Having read the "Summary of Python tracker Issues" on the python-dev mailing list, and followed from there to the bug tracker, it seems that all input is greatly appreciated. For the small issues the reply is often "Thanks, done". Some things get rejected, and usually rightly so from what I can see. Others the issue is closed with the half way house committed/rejected. Work that out for yourself if you can.:) -- Kindest regards. Mark Lawrence. From warpcat at sbcglobal.net Fri Aug 28 14:13:06 2009 From: warpcat at sbcglobal.net (AK Eric) Date: Fri, 28 Aug 2009 11:13:06 -0700 (PDT) Subject: Query screen resolution? Message-ID: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> Thought this would be easy, maybe I'm missing something :) Trying to query the x,y resolution of my screen. I've seen this available through http://python.net/crew/mhammond/win32/ : from win32api import GetSystemMetrics print "width =", GetSystemMetrics (0) print "height =",GetSystemMetrics (1) But I was hoping for something built-in, and something non-OS specific. Is that available? Would be nice to detect for multiple monitors as well, but I'm probably asking too much :) Thanks! From szport at gmail.com Fri Aug 28 14:25:55 2009 From: szport at gmail.com (zaur) Date: Fri, 28 Aug 2009 11:25:55 -0700 (PDT) Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> Message-ID: <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> On 28 ???, 16:07, Bruno Desthuilliers wrote: > zaur a ?crit : > > > > > On 26 ???, 17:13, "Diez B. Roggisch" wrote: > >> Whom am we to judge? Sure if you propose this, you have some usecases in > >> mind - how about you present these > > > Ok. Here is a use case: object initialization. > > > For example, > > > person = Person(): > > ? name = "john" > > ? age = 30 > > ? address = Address(): > > ? ? ?street = "Green Street" > > ? ? ?no = 12 > > > vs. > > > person = Person() > > person.name = "john" > > person.age = 30 > > address = person.address = Address() > > address.street = "Green Street" > > address.no = 12 > > Err... Looks like you really should read the FineManual(tm) - > specifically, the parts on the __init__ method. > > class Person(object): > ? ? def __init__(self, name, age, address): > ? ? ? ? self.name = name > ? ? ? ? self.age = age > ? ? ? ? self.address = address > > class Address(object): > ? ? def __init__(self, street, no): > ? ? ? ? self.no = no > ? ? ? ? self.street = street > > person = Person( > ? ? name="john", > ? ? age=30, > ? ? address = Address( > ? ? ? ? street="Green Street", > ? ? ? ? no=12 > ? ? ) > ) What are you doing if 1) classes Person and Address imported from foreign module 2) __init__ method is not defined as you want? From rami.chowdhury at gmail.com Fri Aug 28 14:27:15 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Fri, 28 Aug 2009 11:27:15 -0700 Subject: Query screen resolution? In-Reply-To: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> References: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> Message-ID: > But I was hoping for something built-in, and something non-OS > specific. I don't know about built-ins, but I do believe that pygame (which *is* cross-platform) will let you get at that information: http://www.pygame.org/docs/ref/display.html#pygame.display.Info On Fri, 28 Aug 2009 11:13:06 -0700, AK Eric wrote: > Thought this would be easy, maybe I'm missing something :) Trying to > query the x,y resolution of my screen. I've seen this available > through http://python.net/crew/mhammond/win32/ : > > from win32api import GetSystemMetrics > print "width =", GetSystemMetrics (0) > print "height =",GetSystemMetrics (1) > > But I was hoping for something built-in, and something non-OS > specific. Is that available? Would be nice to detect for multiple > monitors as well, but I'm probably asking too much :) > > Thanks! -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From gert.cuykens at gmail.com Fri Aug 28 14:31:31 2009 From: gert.cuykens at gmail.com (gert) Date: Fri, 28 Aug 2009 11:31:31 -0700 (PDT) Subject: how to edit .wsgi file extebtions with IDLE on windows Message-ID: I can't figure out how to enable the .py shell and syntax highlighting for .wsgi file extensions using IDLE for windows ? From davea at ieee.org Fri Aug 28 14:35:35 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 28 Aug 2009 14:35:35 -0400 Subject: Select column from a list In-Reply-To: <25185508.post@talk.nabble.com> References: <25185508.post@talk.nabble.com> Message-ID: <4A982377.7020402@ieee.org> hoffik wrote: > Hello, > > I'm quite new in Python and I have one question. I have a 2D matrix of > values stored in list (3 columns, many rows). I wonder if I can select one > column without having to go through the list with 'for' command. > > For example I have list called 'values'. > When I write 'values[0]' or 'values[0][:]' I'll get the first row. > But when I write 'values[:][0]' I won't get the first column, but the first > row again! I can't see why. > > Thanks > Hoffik > Python doesn't have 2d matrices as a native type. Others have already suggested Numpy. But I'll assume you really want to stick with what's included in base Python, because you're still learning. (Aren't we all?) The real question to me is how this data is related to each other. If it's uniform data, organized in a 3x20 rectangle, or whatever, then maybe you want to use a single list, and just use slicing to extract particular rows and columns. You were actually using slicing in your example above; that's what the colon does. But in your case, you used defaults for the 3 arguments, so you got a *copy* of the entire list. Slicing to get one row would be simply values[row*3:(row+1)*3], and one column would be print values[column: -1: 3] Notice that I hardcoded the width of our "matrix," since list doesn't know anything about it. And notice it's easy to add more rows, but not easy to change row size, because that's not part of the structure, but part of the code to access it. Next possibility is to make a class to describe the data structure. You can make methods that mimic the behavior you want. But I suspect that the row is 3 specific values, maybe not even the same type as each other. So they might be name, address, and phone number. Each row represents a family, and each column represents a type of data. In this case, I'd suggest making each row an instance of a new class you define, and making a list of those objects. Now, you might be representing a row by an object of your class. And representing a column by two things: your list & an accessor method that knows how to extract that particular field. DaveA From matthew.bellis at gmail.com Fri Aug 28 14:36:51 2009 From: matthew.bellis at gmail.com (Matt Bellis) Date: Fri, 28 Aug 2009 11:36:51 -0700 (PDT) Subject: How to exclude "import"s from PyDoc References: <7flt66F2lho6lU1@mid.uni-berlin.de> Message-ID: <613fc599-609a-4df3-b46b-8bba6297da55@i8g2000pro.googlegroups.com> Hi Diez, Thanks for the heads up. I'll give epydoc a shot. Matt > > > ? ?Anyone know the best way to getPyDocto ignore this (or other) > > imported module(s)? > > Don't know aboutpydoc, but epydoc (which generates much nicer docs > imho) can be forced to only include certain packages. > > Diez From xiaosongxia at yahoo.com Fri Aug 28 14:38:30 2009 From: xiaosongxia at yahoo.com (xiaosong xia) Date: Fri, 28 Aug 2009 11:38:30 -0700 (PDT) Subject: copy construtor question Message-ID: <613204.64791.qm@web53105.mail.re2.yahoo.com> Hi all, ? I am trying to define a class with copy constructor as following: ? class test: ???? def __init__(self, s=None): ????????? self=s ? x=[1,2] ? y=test(x) ? print y.__dict__ ? it gives {} ? The above code doesn't work. ? Questions are: ? 1. Can 'self ' be a class attribute? 2. How to make a copy constructor? ? Thanks for any help. ? Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From warpcat at sbcglobal.net Fri Aug 28 14:49:16 2009 From: warpcat at sbcglobal.net (Warpcat) Date: Fri, 28 Aug 2009 11:49:16 -0700 (PDT) Subject: Query screen resolution? References: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> Message-ID: <04a85dc7-d1e7-4566-9ee9-fa9090b45543@v15g2000prn.googlegroups.com> On Aug 28, 11:27?am, "Rami Chowdhury" wrote: > > But I was hoping for something built-in, and something non-OS > > specific. > > I don't know about built-ins, but I do believe that pygame (which *is* ? > cross-platform) will let you get at that information: > ? ? ? ?http://www.pygame.org/docs/ref/display.html#pygame.display.Info Actually, I just came up with another hack using PyGame as well like so: screen = pygame.display.set_mode((0,0)) WIDTH, HEIGHT = screen.get_size() If you pass zero values into the resolution, it will pop to the current screen resolution. And since I'm making a PyGame app, this actually works out ok. However, querying the current_w & current_h attrs from the Info object is a lot cleaner (I was unaware of that, thanks!) But I'd sure like to know if there is built-in way. From somebody at somewhere.com Fri Aug 28 14:57:28 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Fri, 28 Aug 2009 19:57:28 +0100 Subject: Select column from a list References: Message-ID: hoffik wrote: > > Hello, > > I'm quite new in Python and I have one question. I have a 2D matrix of > values stored in list (3 columns, many rows). I wonder if I can select one > column without having to go through the list with 'for' command. > > For example I have list called 'values'. > When I write 'values[0]' or 'values[0][:]' I'll get the first row. > But when I write 'values[:][0]' I won't get the first column, but the > first row again! I can't see why. rows = [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] cols = zip(*rows) To just get the second column: zip(*rows)[1] -- Stephen Fairchild From vicente.soler at gmail.com Fri Aug 28 14:58:48 2009 From: vicente.soler at gmail.com (vsoler) Date: Fri, 28 Aug 2009 11:58:48 -0700 (PDT) Subject: Colors on IDLE Message-ID: Everything that I see in IDLE is in black. I have tried to add colors, without success. I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic From vicente.soler at gmail.com Fri Aug 28 15:00:21 2009 From: vicente.soler at gmail.com (vsoler) Date: Fri, 28 Aug 2009 12:00:21 -0700 (PDT) Subject: Colors on IDLE References: Message-ID: On Aug 28, 8:58?pm, vsoler wrote: > Everything that I see in IDLE is in black. > > I have tried to add colors, without success. > > I've tried: ?/Options/Configure IDLE/Highlighting/IDLE Classic Couldn't finish writing... sorry ----------------------------------- Everything that I see in IDLE is in black. I have tried to add colors, without success. I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic However, everything remains black. Any help is highly appreciated Vicente Soler From pfeldman at verizon.net Fri Aug 28 15:00:31 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Fri, 28 Aug 2009 12:00:31 -0700 (PDT) Subject: comparison on list yields surprising result Message-ID: <25195170.post@talk.nabble.com> In [21]: x Out[21]: [1, 2, 3, 5] In [22]: x>6 Out[22]: True Is this a bug? -- View this message in context: http://www.nabble.com/comparison-on-list-yields-surprising-result-tp25195170p25195170.html Sent from the Python - python-list mailing list archive at Nabble.com. From sjmachin at lexicon.net Fri Aug 28 15:00:36 2009 From: sjmachin at lexicon.net (John Machin) Date: Fri, 28 Aug 2009 12:00:36 -0700 (PDT) Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> Message-ID: On Aug 29, 2:35?am, vsoler wrote: > 3- Excel does not even put quotes around litteral texts, not even when > the text contains a blank Correct. Quoting is necessary only if a text field contains a delimiter (semicolon/comma), a newline, or the quote character. You can read Excel CSV output using the Python csv module by specifying delimiter=";" If you need to feed a CSV file to some software that demands that text fields be quoted unconditionally, you have at least two options: (1) If you know which fields should be text fields, you can read the Excel-output file with Python csv, convert your non-text fields to float, and write it back out with quoting=csv.QUOTE_NONNUMERIC. (2) If you want precise control (and thus precise knowledge), use xlrd (http://pypi.python.org/pypi/xlrd) to read Excel 97-2003 .xls files -- it will tell you cell by cell (NOT column by column (the user has control of the type at the cell level)) whether the cell contains text (reported as a unicode object), a number (float), a Boolean (int, 1 or 0), a date (float, days since ? (read the docs)), or an error code e.g. #DIV/0! (int, read the docs) ... then you can write it out however you like. HTH, John From sjmachin at lexicon.net Fri Aug 28 15:16:59 2009 From: sjmachin at lexicon.net (John Machin) Date: Fri, 28 Aug 2009 12:16:59 -0700 (PDT) Subject: comparison on list yields surprising result References: Message-ID: On Aug 29, 5:00?am, "Dr. Phillip M. Feldman" wrote: > In [21]: x > Out[21]: [1, 2, 3, 5] > > In [22]: x>6 > Out[22]: True > > Is this a bug? No. http://docs.python.org/reference/expressions.html#notin From deets at nospam.web.de Fri Aug 28 15:19:43 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Aug 2009 21:19:43 +0200 Subject: comparison on list yields surprising result In-Reply-To: References: Message-ID: <4A982DCF.2060201@nospam.web.de> Dr. Phillip M. Feldman schrieb: > In [21]: x > Out[21]: [1, 2, 3, 5] > > In [22]: x>6 > Out[22]: True > > Is this a bug? In python2.x, it's the defined behavior - all types are somhow comparable. The comparison is stable (all lists compare larger to all ints), but of course this by no means well-defined. This debatable design-decision has been remedied in Python3: Python 3.1 (r31:73578, Jun 27 2009, 21:49:46) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> list(range(10)) < 10 Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: list() < int() >>> Diez From deets at nospam.web.de Fri Aug 28 15:19:58 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Aug 2009 21:19:58 +0200 Subject: comparison on list yields surprising result In-Reply-To: References: Message-ID: <7fqouuF2mlupvU2@mid.uni-berlin.de> Dr. Phillip M. Feldman schrieb: > In [21]: x > Out[21]: [1, 2, 3, 5] > > In [22]: x>6 > Out[22]: True > > Is this a bug? In python2.x, it's the defined behavior - all types are somhow comparable. The comparison is stable (all lists compare larger to all ints), but of course this by no means well-defined. This debatable design-decision has been remedied in Python3: Python 3.1 (r31:73578, Jun 27 2009, 21:49:46) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> list(range(10)) < 10 Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: list() < int() >>> Diez From motoom at xs4all.nl Fri Aug 28 15:23:12 2009 From: motoom at xs4all.nl (Michiel Overtoom) Date: Fri, 28 Aug 2009 21:23:12 +0200 Subject: An assessment of Tkinter and IDLE In-Reply-To: <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> Message-ID: <4A982EA0.10808@xs4all.nl> r wrote: > Whats the use of Tkinter if the docs are in TCL. Just > learn TCL and skip the Python middleman. But Mark's tutorial at http://www.tkdocs.com/tutorial/index.html allows you to select 'Python' as one of the languages you want to see the example code in. Too bad that the 'ttk' widgets are not mainstream yet. Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Valloppillil http://www.catb.org/~esr/halloween/halloween4.html From gert.cuykens at gmail.com Fri Aug 28 15:24:25 2009 From: gert.cuykens at gmail.com (gert) Date: Fri, 28 Aug 2009 12:24:25 -0700 (PDT) Subject: how to send 100 continues in wsgi application ? Message-ID: how do you send 100 continues in a wsgi applications ? when using curl -T file http://localhost/upload.wsgi on the wsgiref.simple_server it get stuck waiting for a 100 continue import os def application(environ, response): query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') range=environ.get('HTTP_CONTENT_RANGE','bytes 0-').replace('bytes ','').split('/')[0].split(',') offset=[] for r in range: offset.append(r.split('-')) with open(query,'ab+') as f: if environ['REQUEST_METHOD']=='PUT': f.seek(int(offset[0][0])) f.truncate() while True: chunk=environ['wsgi.input'].read(8192) if not chunk: break f.write(chunk) f.flush() l=str(os.fstat(f.fileno()).st_size) response('200 OK', [('Content-Type', 'text/plain'), ('Content- Length', str(len(l)))]) return [l] From aahz at pythoncraft.com Fri Aug 28 15:29:09 2009 From: aahz at pythoncraft.com (Aahz) Date: 28 Aug 2009 12:29:09 -0700 Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: In article <21e57363-4e92-41cb-9907-5aef96ad0a6e at o15g2000yqm.googlegroups.com>, RunThePun wrote: > >Anybody have any more ideas? I think python should/could havev a >syntax for overriding this behaviour, i mean, obviously the complexity >of supporting all operators with the getitem syntax could introduce >alot of clutter. But maybe there's an elegant solution out there... Any solution you create must support this: >>> L = [3] >>> L[0] += 7 >>> L [10] -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From pfeldman at verizon.net Fri Aug 28 15:47:13 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Fri, 28 Aug 2009 12:47:13 -0700 (PDT) Subject: comparison on list yields surprising result In-Reply-To: <4A982DCF.2060201@nospam.web.de> References: <25195170.post@talk.nabble.com> <4A982DCF.2060201@nospam.web.de> Message-ID: <25195893.post@talk.nabble.com> It looks as though what I should have done is the following: In [23]: array(x) > 6 Out[23]: array([False, False, False, False], dtype=bool) -- View this message in context: http://www.nabble.com/comparison-on-list-yields-surprising-result-tp25195170p25195893.html Sent from the Python - python-list mailing list archive at Nabble.com. From clp2 at rebertia.com Fri Aug 28 15:55:11 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 28 Aug 2009 12:55:11 -0700 Subject: Colors on IDLE In-Reply-To: References: Message-ID: <50697b2c0908281255n1f17d4c9l335c39a3acd5c7c4@mail.gmail.com> On Fri, Aug 28, 2009 at 12:00 PM, vsoler wrote: > On Aug 28, 8:58?pm, vsoler wrote: >> Everything that I see in IDLE is in black. >> >> I have tried to add colors, without success. >> >> I've tried: ?/Options/Configure IDLE/Highlighting/IDLE Classic > > Couldn't finish writing... ? sorry > ----------------------------------- > > Everything that I see in IDLE is in black. > > I have tried to add colors, without success. > > I've tried: ?/Options/Configure IDLE/Highlighting/IDLE Classic > > However, everything remains black. Any help is highly appreciated What OS are you on? - Chris From pavlovevidence at gmail.com Fri Aug 28 16:03:40 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 28 Aug 2009 13:03:40 -0700 (PDT) Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: On Aug 26, 11:49?pm, RunThePun wrote: > Anybody have any more ideas? I think python should/could havev a > syntax for overriding this behaviour, i mean, obviously the complexity > of supporting all operators with the getitem syntax could introduce > alot of clutter. But maybe there's an elegant solution out there... I don't think it needs a syntax for that, but I'm not so sure a method to modify a value in place with a single key lookup wouldn't occasioanally be useful. For instance: def increment(value): return value+1 d = { 'a': 1 } d.apply_to_value('a',increment) print d and d['a'] would be 2. The difference is that only one lookup occurs. (The dictionary would be locked to modifications while the callback function is called, same as if it were being iterated over.) Thing is, there's no way to get that ability except subclass dict in C; can't be done from Python. Which is why even though it'd be a pretty rare need it at least deserves a bit of consideration before being tabled. As a workaround, if lookups are expensive, you can add an indirection to the dict. For example, you could let each value in the dict be a singleton list which is permanently bound to the key. Then you only have look up the key once to modify the value. d = { 'a': [1] } ston = d['a'] ston[0] += 3 and now d['a'][0] is 4, and there was only one dict lookup. Downside is that you have the [0] to carry around, but that is the price of indirection. A wrapper class might help. Carl Banks From mwilson at the-wire.com Fri Aug 28 16:38:55 2009 From: mwilson at the-wire.com (Mel) Date: Fri, 28 Aug 2009 16:38:55 -0400 Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> Message-ID: zaur wrote: > On 28 ???, 16:07, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> zaur a ?crit : >> >> >> >> > On 26 ???, 17:13, "Diez B. Roggisch" wrote: >> >> Whom am we to judge? Sure if you propose this, you have some usecases >> >> in mind - how about you present these >> >> > Ok. Here is a use case: object initialization. >> >> > For example, >> >> > person = Person(): >> > name = "john" >> > age = 30 >> > address = Address(): >> > street = "Green Street" >> > no = 12 >> >> > vs. >> >> > person = Person() >> > person.name = "john" >> > person.age = 30 >> > address = person.address = Address() >> > address.street = "Green Street" >> > address.no = 12 >> >> Err... Looks like you really should read the FineManual(tm) - >> specifically, the parts on the __init__ method. >> >> class Person(object): >> def __init__(self, name, age, address): >> self.name = name >> self.age = age >> self.address = address >> >> class Address(object): >> def __init__(self, street, no): >> self.no = no >> self.street = street >> >> person = Person( >> name="john", >> age=30, >> address = Address( >> street="Green Street", >> no=12 >> ) >> ) > > What are you doing if 1) classes Person and Address imported from > foreign module 2) __init__ method is not defined as you want? My work-around would be: p = person = Person() p.name = "john" p.age = age # assuming, for a moment, that the age I wanted to set # happened to be in another variable a = p.address = Address() a.street = "Green Street" a.no = 12 del a, p # optional, for a tidier namespace Slightly verbose, but, saying what it means, it avoids having to guess which age of several ages might have to be used in various places; the same would go for other input variables. Actually, I probably wouldn't use p as a stand-in for person unless person were a global name and p could be local. Mel. From charles at declareSub.com Fri Aug 28 16:40:54 2009 From: charles at declareSub.com (Charles Yeomans) Date: Fri, 28 Aug 2009 16:40:54 -0400 Subject: why python got less developers ? In-Reply-To: References: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> Message-ID: On Aug 28, 2009, at 1:03 AM, Esam Qanadeely wrote: > who cares if a language is compiled or interpreted as long as it runs > and perform the function. > > second thing is : even if java is faster than python , unless you are > making performance critical operations : who cares? computers are > getting faster all the time and languages like python or ruby are fast > enough. > > any comment ? Many developers suffer from performance anxiety. Charles Yeomans From ken at seehart.com Fri Aug 28 16:59:57 2009 From: ken at seehart.com (Ken Seehart) Date: Fri, 28 Aug 2009 13:59:57 -0700 Subject: cgi and POST Message-ID: <4A98454D.6050006@seehart.com> I can't seem to find an answer to this simple question on the web, and the documentation doesn't seem to indicate how to do this... On the client I have: urllib.urlopen(uri, data) This does a POST, but it's not obvious to me how this maps onto the various cgi examples which assume that the POST operation came from an html form with a file field. In my case, there is no html form, and there is no file field, so please do not refer me to a page that just gives examples where the data is coming from a file transfer form. I have already visited those pages. My question is this: Using cgi, how do I get the /data /(not the uri arguments) originating from a POST that did not originate from a form. Thanks. From vicente.soler at gmail.com Fri Aug 28 17:34:07 2009 From: vicente.soler at gmail.com (vsoler) Date: Fri, 28 Aug 2009 14:34:07 -0700 (PDT) Subject: Colors on IDLE References: Message-ID: <59922ab5-f8c9-429f-b1ea-9b1418aa6b71@t13g2000yqt.googlegroups.com> On Aug 28, 9:55?pm, Chris Rebert wrote: > On Fri, Aug 28, 2009 at 12:00 PM, vsoler wrote: > > On Aug 28, 8:58?pm, vsoler wrote: > >> Everything that I see in IDLE is in black. > > >> I have tried to add colors, without success. > > >> I've tried: ?/Options/Configure IDLE/Highlighting/IDLE Classic > > > Couldn't finish writing... ? sorry > > ----------------------------------- > > > Everything that I see in IDLE is in black. > > > I have tried to add colors, without success. > > > I've tried: ?/Options/Configure IDLE/Highlighting/IDLE Classic > > > However, everything remains black. Any help is highly appreciated > > What OS are you on? > > - Chris Windows XP From tjreedy at udel.edu Fri Aug 28 17:42:04 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Aug 2009 17:42:04 -0400 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: Carl Banks wrote: > I don't think it needs a syntax for that, but I'm not so sure a method > to modify a value in place with a single key lookup wouldn't > occasioanally be useful. Augmented assignment does that. > > For instance: > > def increment(value): > return value+1 > d = { 'a': 1 } > d.apply_to_value('a',increment) > print d > > and d['a'] would be 2. The difference is that only one lookup > occurs. Like this? >>> d={'a': 2} >>> d['a'] += 2 >>> d['a'] 4 This does not cover all replacements, but certainly the most common. [snip] > As a workaround, if lookups are expensive, But they are not. Because (C)Python is heavily based on dict name lookup for builtins and global names and attributes, as well as overt dict lookup, must effort has gone into optimizing dict lookup. > you can add something even slower ;-). In particular, a method lookup + method call, as you suggest above. One can always avoid calculating the key object twice if that is expensive. Terry Jan Reedy From darcy at druid.net Fri Aug 28 17:48:57 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 28 Aug 2009 17:48:57 -0400 Subject: cgi and POST In-Reply-To: <4A98454D.6050006@seehart.com> References: <4A98454D.6050006@seehart.com> Message-ID: <20090828174857.843a4da2.darcy@druid.net> On Fri, 28 Aug 2009 13:59:57 -0700 Ken Seehart wrote: > Using cgi, how do I get the /data /(not the uri arguments) originating > from a POST that did not originate from a form. You don't care where it came from. Just treat it exactly as if it came from a form. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From saimapk81 at gmail.com Fri Aug 28 17:49:58 2009 From: saimapk81 at gmail.com (saima81) Date: Fri, 28 Aug 2009 14:49:58 -0700 (PDT) Subject: "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options Message-ID: <83e09538-4098-4f19-8164-f3a4c4702e32@u20g2000prg.googlegroups.com> "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options From robert.kern at gmail.com Fri Aug 28 18:13:19 2009 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 28 Aug 2009 17:13:19 -0500 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: On 2009-08-28 16:42 PM, Terry Reedy wrote: > Carl Banks wrote: > >> I don't think it needs a syntax for that, but I'm not so sure a method >> to modify a value in place with a single key lookup wouldn't >> occasioanally be useful. > > Augmented assignment does that. No, it uses one __getitem__ and one __setitem__ thus two key lookups. >> For instance: >> >> def increment(value): >> return value+1 >> d = { 'a': 1 } >> d.apply_to_value('a',increment) >> print d >> >> and d['a'] would be 2. The difference is that only one lookup >> occurs. > > Like this? > >>> d={'a': 2} > >>> d['a'] += 2 > >>> d['a'] > 4 > > This does not cover all replacements, but certainly the most common. Take look farther up in the thread for the actual point at issue. The OP knows that augmented assignment works for the common cases. He wants to override the behavior on the container to handle some uncommon cases, and this is not possible because Python breaks up the operation into three orthogonal actions. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From hkh00001 at gmail.com Fri Aug 28 18:19:35 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 15:19:35 -0700 (PDT) Subject: IDE for python similar to visual basic Message-ID: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> i have been searching for am IDE for python that is similar to Visual Basic but had no luck.shall you help me please? From fasteliteprogrammer at yahoo.com Fri Aug 28 18:22:47 2009 From: fasteliteprogrammer at yahoo.com (Craig) Date: Fri, 28 Aug 2009 15:22:47 -0700 (PDT) Subject: IDE for python similar to visual basic In-Reply-To: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> Message-ID: <504063.99893.qm@web36502.mail.mud.yahoo.com> Try wingware i have it and i like it. --- On Fri, 8/28/09, qwe rty wrote: > From: qwe rty > Subject: IDE for python similar to visual basic > To: python-list at python.org > Date: Friday, August 28, 2009, 5:19 PM > i have been searching for am IDE for > python that is similar to Visual > Basic but had no luck.shall you help me please? > -- > http://mail.python.org/mailman/listinfo/python-list > From josefg at gmail.com Fri Aug 28 18:25:13 2009 From: josefg at gmail.com (josef) Date: Fri, 28 Aug 2009 15:25:13 -0700 (PDT) Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <9feee13c-117e-4806-b238-e4152a68adfb@18g2000yqa.googlegroups.com> Message-ID: On Aug 27, 1:35?pm, Ethan Furman wrote: > josef wrote: > > Thanks to everyone who responded. > > > I will be going with some sort of a = MyClass(name = 'a') format. It's > > the Python way. > > > For me, it was very hard to accept that EVERYTHING is an object > > reference. And that there are no object reference names, just string > > entries in dictionaries. But I think it all makes sense now. > > > Thanks again, > > > Josef > > My apologies if I missed it, but what *exactly* are you planning on > doing with your 'name' attribute? ?From the posts I've seen so far, I > think you are only setting yourself up for failure. > > ~Ethan~ I'm going to use it for printing purposes. dk = MyClass(name='dk') When I need a name dk.name. There will only ever be one dk defined. Does that read like I'm setting myself up for failure? From hkh00001 at gmail.com Fri Aug 28 18:37:46 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 15:37:46 -0700 (PDT) Subject: What python can NOT do? Message-ID: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> i know that an interpreted language like python can't be used to make an operating system or system drivers. what else can NOT be done in python? what are the limitations of the language? From thudfoo at opensuse.us Fri Aug 28 18:39:28 2009 From: thudfoo at opensuse.us (member thudfoo) Date: Fri, 28 Aug 2009 15:39:28 -0700 Subject: [Tutor] Sending an email alert In-Reply-To: <000001ca2811$cb320b10$61962130$@org> References: <000001ca2811$cb320b10$61962130$@org> Message-ID: <3d881a310908281539k42b92449p804575eac3cd6e7@mail.gmail.com> On Fri, Aug 28, 2009 at 12:00 PM, Marc wrote: [...] > ??? s = smtplib.SMTP('smtp.marcd.org') > > AttributeError: 'module' object has no attribute 'SMTP' > > > > The code I am trying to use is: > > > > import smtplib > [...] Make sure you do not have a file called "smtplib.py" on the your python path: put this statement after "import smtplib": print smtplib.__file__ in order to find out what "smtplib" is being imported. HTH > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hkh00001 at gmail.com Fri Aug 28 18:43:51 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 15:43:51 -0700 (PDT) Subject: IDE for python similar to visual basic References: Message-ID: On Aug 29, 1:22?am, Craig wrote: > Try wingware i have it and i like it. > > --- On Fri, 8/28/09, qwe rty wrote: > > > From: qwe rty > > Subject: IDE for python similar to visual basic > > To: python-l... at python.org > > Date: Friday, August 28, 2009, 5:19 PM > > i have been searching for am IDE for > > python that is similar to Visual > > Basic but had no luck.shall you help me please? > > -- > >http://mail.python.org/mailman/listinfo/python-list > > OMG, it has no visual designer !! From mark at markroseman.com Fri Aug 28 18:48:35 2009 From: mark at markroseman.com (Mark Roseman) Date: Fri, 28 Aug 2009 16:48:35 -0600 Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> Message-ID: r wrote: > On Aug 28, 11:12?am, Mark Roseman wrote: > > Would it be useful to link to this from the main Python Tkinter > > documentation? > > Thanks Mark, but i would hate to see more links to TCL code in the > python docs. Whats the use of Tkinter if the docs are in TCL. The www.tkdocs.com site is 'language neutral' - currently the tutorial covers Tcl, Perl, Ruby and yes Python, and allows you to switch between any of those languages (or show all of them). From abecedarian314159 at yahoo.com Fri Aug 28 18:51:10 2009 From: abecedarian314159 at yahoo.com (William) Date: Fri, 28 Aug 2009 15:51:10 -0700 (PDT) Subject: IDE for python similar to visual basic In-Reply-To: Message-ID: <846470.11833.qm@web110601.mail.gq1.yahoo.com> For visual designers, you may try: QTDesigner with PyQt or WxForms or WxGlade or BoaConstructor with WxPython It's not like VB.NET where you can put in callbacks write after doing layout, but some prefer the above designers to hand coding guis.? Good luck, William --- On Fri, 8/28/09, qwe rty wrote: From: qwe rty Subject: Re: IDE for python similar to visual basic To: python-list at python.org Date: Friday, August 28, 2009, 6:43 PM On Aug 29, 1:22?am, Craig wrote: > Try wingware i have it and i like it. > > --- On Fri, 8/28/09, qwe rty wrote: > > > From: qwe rty > > Subject: IDE for python similar to visual basic > > To: python-l... at python.org > > Date: Friday, August 28, 2009, 5:19 PM > > i have been searching for am IDE for > > python that is similar to Visual > > Basic but had no luck.shall you help me please? > > -- > >http://mail.python.org/mailman/listinfo/python-list > > OMG, it has no visual designer !! -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Fri Aug 28 18:51:12 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 29 Aug 2009 00:51:12 +0200 Subject: IDE for python similar to visual basic In-Reply-To: References: Message-ID: <4A985F60.5060301@gmail.com> qwe rty wrote: > On Aug 29, 1:22 am, Craig wrote: > >> Try wingware i have it and i like it. >> >> --- On Fri, 8/28/09, qwe rty wrote: >> >> >>> From: qwe rty >>> Subject: IDE for python similar to visual basic >>> To: python-l... at python.org >>> Date: Friday, August 28, 2009, 5:19 PM >>> i have been searching for am IDE for >>> python that is similar to Visual >>> Basic but had no luck.shall you help me please? >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> > > OMG, it has no visual designer !! > That was my first reaction too. and I was even used to a better visual designer: Delphi ;-) I'm now very happy and design faster in wxPython (with GUI-support) than in Delphi ;-) cheers, Stef From pavlovevidence at gmail.com Fri Aug 28 19:02:00 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 28 Aug 2009 16:02:00 -0700 (PDT) Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: <58e91734-d03f-417c-89b1-f2717c3a9181@l5g2000yqo.googlegroups.com> On Aug 28, 2:42?pm, Terry Reedy wrote: > Carl Banks wrote: > > I don't think it needs a syntax for that, but I'm not so sure a method > > to modify a value in place with a single key lookup wouldn't > > occasioanally be useful. > > Augmented assignment does that. Internally uses two lookups, one for getting, and one for setting. I think this is an unavoidable given Python's semantics. Look at the traceback: >>> def x(): ... d['a'] += 1 ... >>> dis.dis(x) 2 0 LOAD_GLOBAL 0 (d) 3 LOAD_CONST 1 ('a') 6 DUP_TOPX 2 9 BINARY_SUBSCR 10 LOAD_CONST 2 (1) 13 INPLACE_ADD 14 ROT_THREE 15 STORE_SUBSCR 16 LOAD_CONST 0 (None) 19 RETURN_VALUE > > As a workaround, if lookups are expensive, > > But they are not. Because (C)Python is heavily based on dict name lookup > for builtins and global names and attributes, as well as overt dict > lookup, must effort has gone into optimizing dict lookup. The actual lookup algorithm Python dicts use is well-optimized, yes, but the dict could contain keys that have expensive comparison and hash-code calculation, in which case lookup is going to be slow. Carl Banks From nyamatongwe+thunder at gmail.com Fri Aug 28 19:02:33 2009 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 28 Aug 2009 23:02:33 GMT Subject: Annoying octal notation In-Reply-To: <00216447$0$2930$c3e8da3@news.astraweb.com> References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> <00216447$0$2930$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano: > Obviously I can't speak for Ken Thompson's motivation in creating this > feature, but I'm pretty sure it wasn't to save typing or space on > punchcards. The original implementation of UNIX was on a PDP-7 which was an 18-bit machine. Octal = 3 bits at a a time which evenly divides an 18-bit word whereas the 4 bits of hexadecimal do not. Early implementations of B were (according to Wikipedia) on the PDP-7, PDP-11 (a 16-bit machine) and Honeywell 36-bit mainframes. Octal was widely used on the PDP-11. DEC's PDP-11 Assembler defaulted to octal and didn't even support hexadecimal. The prefixes used in MACRO-11 for explicit radixes were ^D, ^O, and ^B. http://computer-refuge.org/bitsavers/pdf/dec/pdp11/rsx11/RSX11M_V2/DEC-11-OIMRA-A-D_MACRO_75.pdf Neil From ken at seehart.com Fri Aug 28 19:11:20 2009 From: ken at seehart.com (Ken Seehart) Date: Fri, 28 Aug 2009 16:11:20 -0700 Subject: cgi and POST In-Reply-To: <20090828174857.843a4da2.darcy@druid.net> References: <4A98454D.6050006@seehart.com> <20090828174857.843a4da2.darcy@druid.net> Message-ID: <4A986418.6000600@seehart.com> D'Arcy J.M. Cain wrote: > On Fri, 28 Aug 2009 13:59:57 -0700 > Ken Seehart wrote: > >> Using cgi, how do I get the /data /(not the uri arguments) originating >> from a POST that did not originate from a form. >> > > You don't care where it came from. Just treat it exactly as if it came > from a form. > Thanks. Anyway, the issue was that I made a mistake the urllib side of things. Problem solved. Ken From lists at cheimes.de Fri Aug 28 19:21:32 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 29 Aug 2009 01:21:32 +0200 Subject: What python can NOT do? In-Reply-To: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: qwe rty wrote: > i know that an interpreted language like python can't be used to make > an operating system or system drivers. > > what else can NOT be done in python? what are the limitations of the > language? Python is a high level language. It's not designed for low level stuff like bit operations or direct hardware access. However it can be used as a glue language for low level code written in C or ASM. Christian From rt8396 at gmail.com Fri Aug 28 19:27:27 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 16:27:27 -0700 (PDT) Subject: Colors on IDLE References: <59922ab5-f8c9-429f-b1ea-9b1418aa6b71@t13g2000yqt.googlegroups.com> Message-ID: <8d5d283f-b0bd-4e16-97c7-d2de1a148cae@l35g2000vba.googlegroups.com> Have you tried saving the files as MYScriptName.py? notice the py extension, very important ;) From rt8396 at gmail.com Fri Aug 28 19:33:38 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 16:33:38 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: <1b6492ae-ee59-4a09-a35a-b0db79b5db81@s13g2000yql.googlegroups.com> On Aug 28, 10:36?am, jfabi... at yolo.com wrote: (snip) > I'm inclined to agreed. ?But in recent years we lost a number of developers > to Ruby. ?I don't know but I doubt Ruby has a marketing budget. ?So in my > mind it is difficult for me to blame just the lack of marketing dollars for > the lost. ? Yes probably have since you can write Ruby code that almost mimics Python code, well except for that annoying "end" statement ;). But i think Ruby attracts more perl-heads and lispers anyhow. And i really doubt we want to caterer to that bunch *wink*. I shudder when i imagine a world without Python's simplistic beauty, it is a very scary thought... From rt8396 at gmail.com Fri Aug 28 19:56:44 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 16:56:44 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <8b9073d6-b539-4f0c-b26b-ecf9fd014a87@k6g2000yqn.googlegroups.com> On Aug 28, 5:37?pm, qwe rty wrote: > what else can NOT be done in python? what are the limitations of the > language? Why would you even want to know what can't be done? What is it that you would like to do with Python? If you want a one size fits all language you may be looking for a very long time... From python.list at tim.thechases.com Fri Aug 28 20:05:40 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 28 Aug 2009 19:05:40 -0500 Subject: What python can NOT do? In-Reply-To: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <4A9870D4.8070800@tim.thechases.com> qwe rty wrote: > i know that an interpreted language like python can't be used to make > an operating system or system drivers. As long as you are willing to write the OS hooks in C, you can write the userspace device drivers in Python: https://www.linuxquestions.org/questions/programming-9/how-to-write-device-driver-program-using-python-in-linux-687277/ Since Python is Turing-complete, there's no reason a whole OS couldn't be authored in Python. > what else can NOT be done in python? what are the limitations of the > language? I understand there's a little trouble getting Python to prove that P=NP You'll also find that it only comes close to solving the unrestricted three-body problem and the Traveling Salesman problem is still limited to fallible heuristics and searching the entire solution set in better than O(2**n) time. -tkc From aahz at pythoncraft.com Fri Aug 28 20:06:54 2009 From: aahz at pythoncraft.com (Aahz) Date: 28 Aug 2009 17:06:54 -0700 Subject: why python got less developers ? References: Message-ID: In article , wrote: >Chris Rebert wrote: >> On Thu, Aug 27, 2009 at 5:34 PM, Deep_Feelings >> wrote: >>> >>> python got relatively fewer numbers of developers than other high >>> level languages like .NET , java .. etc ??why ? >> >> We lack Sun and Microsoft's massive marketing departments. :) > >I'm inclined to agreed. But in recent years we lost a number of developers >to Ruby. Cite? I mean, I'm sure it's not zero, but "a number" implies quite a bit more than zero, which I'm inclined to doubt without good evidence. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From rt8396 at gmail.com Fri Aug 28 20:11:08 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 17:11:08 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> Message-ID: <827effaa-d0f7-4142-b4b9-6f9f8e0e7963@e34g2000vbm.googlegroups.com> On Aug 28, 5:48?pm, Mark Roseman wrote: (snip) > Thewww.tkdocs.comsite is 'language neutral' - currently the tutorial > covers Tcl, Perl, Ruby and yes Python, and allows you to switch between > any of those languages (or show all of them). True, however the coverage is incomplete. I would back this site if we can get a complete coverage of all widgets in the Python language. +0.1 From python.list at tim.thechases.com Fri Aug 28 20:14:39 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 28 Aug 2009 19:14:39 -0500 Subject: What python can NOT do? In-Reply-To: <4A9870D4.8070800@tim.thechases.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: <4A9872EF.2000708@tim.thechases.com> >> what else can NOT be done in python? what are the limitations of the >> language? > > I understand there's a little trouble getting Python to prove > that P=NP You'll also find that it only comes close to solving > the unrestricted three-body problem and the Traveling Salesman > problem is still limited to fallible heuristics and searching the > entire solution set in better than O(2**n) time. I forgot about solving the Spam problem entirely. And answering poorly worded/thought-out questions on the internet... I've also been sorely disappointed by Python's ability to make a good chocolate cream silk pie. -tkc From hkh00001 at gmail.com Fri Aug 28 20:26:06 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 17:26:06 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: On Aug 29, 3:14?am, Tim Chase wrote: > >> what else can NOT be done in python? what are the limitations of the > >> language? > > > I understand there's a little trouble getting Python to prove > > that P=NP ?You'll also find that it only comes close to solving > > the unrestricted three-body problem and the Traveling Salesman > > problem is still limited to fallible heuristics and searching the > > entire solution set in better than O(2**n) time. > > I forgot about solving the Spam problem entirely. ?And answering > poorly worded/thought-out questions on the internet... > > I've also been sorely disappointed by Python's ability to make a > good chocolate cream silk pie. > > -tkc if you don't know the answer please don't reply From rt8396 at gmail.com Fri Aug 28 20:31:22 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 17:31:22 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: On Aug 28, 7:05?pm, Tim Chase wrote: (snip) > Since Python is Turing-complete, there's no reason a whole OS > couldn't be authored in Python. Yes, and one could go from NY to LA on a unicycle but would one really want to? Talk about some redass and blueballs! *yikes* Yes, if i have learned anything in my life, i can say there are absolutely no boundaries to what humans can achieve short the limit of their own imagination and the ever fading remainder of ones life. From clp2 at rebertia.com Fri Aug 28 20:47:51 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 28 Aug 2009 17:47:51 -0700 Subject: copy construtor question In-Reply-To: <613204.64791.qm@web53105.mail.re2.yahoo.com> References: <613204.64791.qm@web53105.mail.re2.yahoo.com> Message-ID: <50697b2c0908281747q347d849cx3e8abe2ebe94a120@mail.gmail.com> On Fri, Aug 28, 2009 at 11:38 AM, xiaosong xia wrote: > Hi all, > > I am trying to define a class with copy constructor as following: > > class test: > > ???? def __init__(self, s=None): > > ????????? self=s Python uses call-by-object (http://effbot.org/zone/call-by-object.htm), so reassigning `self` does not affect the object outside of the body of the method. It is (practically) impossible to reassign `self` in the way and with the effect you're trying to do; that is, you never change what `self` points to from the outside world's perspective, you can only modify the object it already points at. > 1. Can 'self ' be a class attribute? Doing this would make no sense. > 2. How to make a copy constructor? Since Python lacks overloading based on parameter types, generally one does it the other way around and instead provides a method that produces a copy of the object. For example: class Point(object): def __init__(self, x, y): self. x = x self.y = y def copy(self): return Point(self.x, self.y) Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Fri Aug 28 21:17:35 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 01:17:35 GMT Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <0022052b$0$2930$c3e8da3@news.astraweb.com> On Fri, 28 Aug 2009 15:37:46 -0700, qwe rty wrote: > i know that an interpreted language like python Languages are neither interpreted nor compiled. *Implementations* are interpreted or compiled. Perl has only one implementation, which is interpreted (as far as I know); Java has a number of implementations, some of which compile to byte-code, some compile to machine-code. There are C interpreters as well as C compilers. And languages like Forth have an unusual programming model which doesn't easily match the conventional interpreted/compiled distinction. Python has a number of implementations, all of which are compiled to byte- code, like early Java. None are purely interpreted; none are compiled to machine-code, although there are add-ons to CPython which will compile most Python code to machine-code. Some day, Python may include implementations which compile directly to machine-code. > can't be used to make an operating system or system drivers. With existing Python implementations, it would be difficult to write an OS, because the implementations assume there is already an operating system available to handle things like memory and disk IO. So before you could write an OS in Python, you would need to write a new Python implementation. However, you could easily write a "virtual OS" in Python which sat on top of the regular OS. Device drivers would be less difficult, but performance may be slow compared to drivers written in (say) C. Boot loaders are another type of software which would be impractical to write in existing Python implementations. > what else can NOT be done in python? what are the limitations of the > language? As a language, Python has no theoretical limits -- it is Turing Complete, which means anything you can do in C, Java, Lisp, or any other Turing Complete language, you could do in Python -- with sufficient effort, and provided you don't care about efficiency. In practice, though, we *do* care about efficiency, and about the effort required to write the program in the first case. In practical terms, Python the language makes most things easy to write but slower to run, so there are very few applications which couldn't be written in Python. A few things are more difficult than others. One of the hardest things to do is to "sandbox" some arbitrary Python code from an untrusted source and execute it in a restricted environment. In practical terms, Python will let you write nearly any sort of program you want, provided absolute performance isn't your provided. (To put it another way, Python code is rarely "the fastest", but it is usually "fast enough".) If performance is too slow, Python is an excellent "glue" language, letting you write the bulk of your program in Python for ease, the performance-critical parts in C for speed. Some practical restrictions... if you are writing a web app, some hosting providers don't provide access to Python on their webserver, so you're limited to using whatever languages they provide, or finding another provider. All existing Python implementations require a minimum amount of memory to operate. This is relatively high, so you probably couldn't use Python on a device where you only had (say) 64K of memory. There's no Python implementation for your ancient Mac Plus or Commodore 64, and there probably never will be. Python the language is based on an execution model with relatively high overhead, so even if you wrote an implementation for such ancient machines, you probably couldn't do much with it. Existing Python implementations don't give you direct access to hardware, and bit-manipulation has a lot of overhead in Python. Numerical calculations (e.g. scientific array calculations) also suffer from overhead, which is barely noticeable if you're doing a few thousand calculations, but if you're doing a few tens of millions may be a little slow. For these, you should use Python as an interface to numeric libraries written in C, like Scipy and Numpy. -- Steven From aahz at pythoncraft.com Fri Aug 28 21:25:57 2009 From: aahz at pythoncraft.com (Aahz) Date: 28 Aug 2009 18:25:57 -0700 Subject: variables of the class are not available as default values? References: Message-ID: In article , Chris Rebert wrote: > >class foo: > def __init__(self, maxvalue): > self.maxvalue =3D maxvalue > self.value =3D 0 > > def put(self, value=3DNone): > self.value =3D self.value if value is None else value Stylistic nit: I'd make that self.value = value if value is not None else self.value The reason is that the "primary" value should go first. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From bcb at undisclosedlocation.net Fri Aug 28 21:29:31 2009 From: bcb at undisclosedlocation.net (Bruce C. Baker) Date: Fri, 28 Aug 2009 20:29:31 -0500 Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <1v%lm.174048$zq1.37846@newsfe22.iad> "qwe rty" wrote in message news:00a36f89-52dd-4d90-a455-cee6a0c9d10f at q5g2000yqh.googlegroups.com... >i know that an interpreted language like python can't be used to make > an operating system or system drivers. > > what else can NOT be done in python? what are the limitations of the > language? It's a floor wax and a dessert topping too! :-) From python.list at tim.thechases.com Fri Aug 28 21:32:17 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 28 Aug 2009 20:32:17 -0500 Subject: What python can NOT do? In-Reply-To: References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: <4A988521.7070005@tim.thechases.com> qwe rty wrote: > On Aug 29, 3:14 am, Tim Chase wrote: >>>> what else can NOT be done in python? what are the limitations of the >>>> language? >>> I understand there's a little trouble getting Python to prove >>> that P=NP You'll also find that it only comes close to solving >>> the unrestricted three-body problem and the Traveling Salesman >>> problem is still limited to fallible heuristics and searching the >>> entire solution set in better than O(2**n) time. >> I forgot about solving the Spam problem entirely. And answering >> poorly worded/thought-out questions on the internet... >> >> I've also been sorely disappointed by Python's ability to make a >> good chocolate cream silk pie. > > if you don't know the answer please don't reply I'm not sure you understand -- Being a Turing complete language, anything you can do in any other language, you can do in Python. As "r" observed, it might not be a pleasant experience (though there are a lot of things I'd rather do in Python than in C or Assembly) but certainly doable. So clearly the issue resides in your nonsensical question. You asked for things you can't do with Python so I listed some. The things you can't do in Python are things you can't do in any other language either. To turn your snark on end, "If you can't post a sensible question, please don't post in the first place". But this is usenet, and Python can't solve the problem of nonsensical questions posted on usenet. :-/ -tkc From b1540457 at tyldd.com Fri Aug 28 21:43:23 2009 From: b1540457 at tyldd.com (Anny Mous) Date: Sat, 29 Aug 2009 11:43:23 +1000 Subject: Transforming a str to an operator References: <87skfcblo3.fsf@benfinney.id.au> <91126ac3-e7fe-4b7a-a37d-d1e60beaa278@w41g2000yqb.googlegroups.com> Message-ID: r wrote: > Abviously the OP is a python baby noob and casting your irrational > fear (and many others irrational fears) of eval It isn't irrational to have a healthy caution towards eval. Apart from the security issues, running code in eval takes a massive performance hit. Its about ten times slower to run eval("x+1") than to run x+1 directly. > at him is akin to > tales of Chupacabras running a muck in the jungle sucking the blood > from live goats in the twilight hours. I use eval all the time and > quite love it. LOL I'm not surprised. > This is nothing more than a throw away academic exercise that will > serve no useful purpose for him in the future, What makes you think that learning to program well in Python is a throw-away exercise of no useful purpose? I'm sure the code itself will be thrown away and forgotten, but it has a very important purpose: for the OP to learn good programming skills. Looks like you want him to learn bad skills, then spend the rest of his life trying to unlearn them. > but serves the very > useful purpose now of establishing an IO between the student and > Python interpretor. I'll bet most your example (albeit a good example) > flew miles above his head into la-la land. How insulting. Is there anything that gave you the impression the OP was stupid? > The OP has plenty of time to learn about malicious input and > protecting against it, right now the fundamentals are well... > fundamental :) When would you recommend he learns? When his web app is hijacked by gangsters in Russia and the personal details and financial records of fifty thousand people stolen? Protecting against malicious input *IS* fundamental. From nobody at nowhere.com Fri Aug 28 21:50:20 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 29 Aug 2009 02:50:20 +0100 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: On Thu, 27 Aug 2009 05:47:50 -0400, Terry Reedy wrote: >> I use Thunderbird, and treat the list as ordinary mail. I use >> reply-all, and it seems to do the right thing. Or at least if I'm >> breaking threads, nobody has pointed it out to me yet. > > reply-all may send duplicate messages to the author. Not sure of this list. If the author doesn't want duplicate replies, they would normally set a Reply-To header which points to the list. Some listservs provide an option to suppress duplicates, i.e. a message isn't sent if the recipient is listed in the To/CC headers. Enabling this option is a bad idea if you're stuck behind an aggressive spam filter: the listserv only knows whether you're listed as a recipient; it can't know whether you actually got the message. From nobody at nowhere.com Fri Aug 28 22:06:03 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 29 Aug 2009 03:06:03 +0100 Subject: Query screen resolution? References: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> Message-ID: On Fri, 28 Aug 2009 11:13:06 -0700, AK Eric wrote: > Thought this would be easy, maybe I'm missing something :) Trying to > query the x,y resolution of my screen. I've seen this available > through http://python.net/crew/mhammond/win32/ : > > from win32api import GetSystemMetrics > print "width =", GetSystemMetrics (0) > print "height =",GetSystemMetrics (1) > > But I was hoping for something built-in, and something non-OS > specific. Is that available? Would be nice to detect for multiple > monitors as well, but I'm probably asking too much :) Your question is based upon the notion that "the screen" is a meaningful concept. Once you move away from Windows (and systems which intentionally try to be like Windows), that's no longer true. E.g. if the program is being run on a terminal, the screen size is measured in characters, not pixels (80x25 would be a reasonable size). If the program is being run as a cron job or CGI script, there is no screen. OTOH, if the system has the X libraries installed, there are a practically unlimited number of X displays which you could connect to, provided that you have the appropriate authentication credentials. From nobody at nowhere.com Fri Aug 28 22:10:18 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 29 Aug 2009 03:10:18 +0100 Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: On Fri, 28 Aug 2009 17:31:22 -0700, r wrote: >> Since Python is Turing-complete, there's no reason a whole OS >> couldn't be authored in Python. > > Yes, and one could go from NY to LA on a unicycle but would one really > want to? Talk about some redass and blueballs! *yikes* > > Yes, if i have learned anything in my life, i can say there are > absolutely no boundaries to what humans can achieve short the limit of > their own imagination and the ever fading remainder of ones life. Well, other than writing a program to determine whether a program in a Turing-complete language will terminate on some input, or devising a formal system which is sound, complete, and able to express its own metatheory, or ... Some things are actually impossible. From hkh00001 at gmail.com Fri Aug 28 22:10:30 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 19:10:30 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: > > if you don't know the answer please don't reply > > I'm not sure you understand -- Being a Turing complete language, > anything you can do in any other language, you can do in Python. > ? As "r" observed, it might not be a pleasant experience (though > there are a lot of things I'd rather do in Python than in C or > Assembly) but certainly doable. > > So clearly the issue resides in your nonsensical question. ?You > asked for things you can't do with Python so I listed some. ?The > things you can't do in Python are things you can't do in any > other language either. ?To turn your snark on end, "If you can't > post a sensible question, please don't post in the first place". > > But this is usenet, and Python can't solve the problem of > nonsensical questions posted on usenet. :-/ > > -tkc i am free to post , you are free to ignore From hkh00001 at gmail.com Fri Aug 28 22:11:24 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 19:11:24 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <0022052b$0$2930$c3e8da3@news.astraweb.com> Message-ID: <380e1617-cd42-4b9d-820a-90d226751915@b18g2000vbl.googlegroups.com> On Aug 29, 4:17?am, Steven D'Aprano wrote: > On Fri, 28 Aug 2009 15:37:46 -0700, qwe rty wrote: > > i know that an interpreted language like python > > Languages are neither interpreted nor compiled. *Implementations* are > interpreted or compiled. > > Perl has only one implementation, which is interpreted (as far as I > know); Java has a number of implementations, some of which compile to > byte-code, some compile to machine-code. There are C interpreters as well > as C compilers. And languages like Forth have an unusual programming > model which doesn't easily match the conventional interpreted/compiled > distinction. > > Python has a number of implementations, all of which are compiled to byte- > code, like early Java. None are purely interpreted; none are compiled to > machine-code, although there are add-ons to CPython which will compile > most Python code to machine-code. Some day, Python may include > implementations which compile directly to machine-code. > > > can't be used to make an operating system or system drivers. > > With existing Python implementations, it would be difficult to write an > OS, because the implementations assume there is already an operating > system available to handle things like memory and disk IO. So before you > could write an OS in Python, you would need to write a new Python > implementation. However, you could easily write a "virtual OS" in Python > which sat on top of the regular OS. > > Device drivers would be less difficult, but performance may be slow > compared to drivers written in (say) C. > > Boot loaders are another type of software which would be impractical to > write in existing Python implementations. > > > what else can NOT be done in python? what are the limitations of the > > language? > > As a language, Python has no theoretical limits -- it is Turing Complete, > which means anything you can do in C, Java, Lisp, or any other Turing > Complete language, you could do in Python -- with sufficient effort, and > provided you don't care about efficiency. > > In practice, though, we *do* care about efficiency, and about the effort > required to write the program in the first case. In practical terms, > Python the language makes most things easy to write but slower to run, so > there are very few applications which couldn't be written in Python. > > A few things are more difficult than others. One of the hardest things to > do is to "sandbox" some arbitrary Python code from an untrusted source > and execute it in a restricted environment. > > In practical terms, Python will let you write nearly any sort of program > you want, provided absolute performance isn't your provided. (To put it > another way, Python code is rarely "the fastest", but it is usually "fast > enough".) If performance is too slow, Python is an excellent "glue" > language, letting you write the bulk of your program in Python for ease, > the performance-critical parts in C for speed. > > Some practical restrictions... if you are writing a web app, some hosting > providers don't provide access to Python on their webserver, so you're > limited to using whatever languages they provide, or finding another > provider. > > All existing Python implementations require a minimum amount of memory to > operate. This is relatively high, so you probably couldn't use Python on > a device where you only had (say) 64K of memory. There's no Python > implementation for your ancient Mac Plus or Commodore 64, and there > probably never will be. Python the language is based on an execution > model with relatively high overhead, so even if you wrote an > implementation for such ancient machines, you probably couldn't do much > with it. > > Existing Python implementations don't give you direct access to hardware, > and bit-manipulation has a lot of overhead in Python. Numerical > calculations (e.g. scientific array calculations) also suffer from > overhead, which is barely noticeable if you're doing a few thousand > calculations, but if you're doing a few tens of millions may be a little > slow. For these, you should use Python as an interface to numeric > libraries written in C, like Scipy and Numpy. > > -- > Steven thank you very much ,THIS is the sort of answer i wanted From nobody at nowhere.com Fri Aug 28 22:11:48 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 29 Aug 2009 03:11:48 +0100 Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: On Fri, 28 Aug 2009 17:26:06 -0700, qwe rty wrote: > if you don't know the answer please don't reply If you don't understand the question, don't post it in the first place. From hkh00001 at gmail.com Fri Aug 28 22:37:23 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 19:37:23 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: On Aug 29, 5:11?am, Nobody wrote: > On Fri, 28 Aug 2009 17:26:06 -0700, qwe rty wrote: > > if you don't know the answer please don't reply > > If you don't understand the question, don't post it in the first place. don't be so angry ,not good for your health From warpcat at sbcglobal.net Fri Aug 28 23:15:57 2009 From: warpcat at sbcglobal.net (Warpcat) Date: Fri, 28 Aug 2009 20:15:57 -0700 (PDT) Subject: Query screen resolution? References: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> Message-ID: <409bf880-4e4b-48f4-8cfc-ecacf262d782@v15g2000prn.googlegroups.com> > Your question is based upon the notion that "the screen" is a meaningful > concept. Once you move away from Windows (and systems which intentionally > try to be like Windows), that's no longer true. Good points. Always something I haven't thought of. Ok so... let's *presume* the user has a measurable screen on win\mac\linux\etc since on any other OS they wouldn't be running the app.... From alan.isaac at gmail.com Fri Aug 28 23:36:12 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Sat, 29 Aug 2009 03:36:12 GMT Subject: Select column from a list In-Reply-To: References: Message-ID: On 8/28/2009 3:45 AM hoffik wrote: > I'm quite new in Python and I have one question. I have a 2D matrix of > values stored in list (3 columns, many rows). I wonder if I can select one > column without having to go through the list with 'for' command. Not quite what you asked but ... >>> rows = [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] >>> cols = map(None,*rows) >>> cols [(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12)] Now you can have any "column" you want. Alan Isaac PS You can also use imap if you prefer not to create the list. From rtomek at ceti.com.pl Fri Aug 28 23:37:34 2009 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Sat, 29 Aug 2009 05:37:34 +0200 Subject: What python can NOT do? In-Reply-To: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: On Fri, 28 Aug 2009, qwe rty wrote: > i know that an interpreted language like python can't be used to make > an operating system or system drivers. > > what else can NOT be done in python? what are the limitations of the > language? Oh, my. And now everybody points at you this Turing-completeness. The issue, in my opinion, is not that something cannot be done. The truth about Turing-completeness is, I would say, you can do whatever but sometimes you will not because it would be too ugly. My private list of things that when implemented in Python would be ugly to the point of calling it difficult: 1. AMB operator - my very favourite. In one sentence, either language allows one to do it easily or one would not want to do it (in an ugly way). http://www.randomhacks.net/articles/2005/10/11/amb-operator After quite some googling I was finally able to locate sample implementation, but I cannot say ATM how well it works and if it is practical enough to use it in any of my programs. If time permits, I will try it, hopefully. http://www.c2.com/cgi/wiki?AmbInPython 2. Changing the language from the inside. Everybody can change the interpreter, right? But how about doing some bigger, maybe even fundamental change to the language by means offered by the language itself? Example: If Python had no object system, or if I wanted to implement one in different way (say, I would like to experiment or I would not want to wait for a new release). In some languages that interest me now, it is possible and practical, more or less. So it can sometimes backfire - what OO system should I choose for my next Scheme program, etc. Because there are few of them :-), all (? - I believe) implemented as a code library. Just install it and off you go, now you have OO programming. Actually, I don't use OO all that much recently (maybe I feel disapointed a bit, or something). Also, I have read (but not checked it myself) that for some time Common Lisp had it's now-official CLOS distributed and tested in a form of library. Say, have they adopted OO with single inheritance as a part of CL ANSI standard - I would still be able to have OO with multiple inheritance. I would just have to download and install CLOS. No change to interpreter or compiler. From their point of view, CLOS would be just another library. http://en.wikipedia.org/wiki/Common_Lisp_Object_System Judging by this code, introducing OO to the language is relatively easy: http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme-Z-H-14.html It is not possible to alter Python in a minor way, I think. Something simpler than OO, like a new keyword or structures: http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme-Z-H-10.html http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme-Z-H-11.html Some readers could oppose the above by saying that Lisp's syntax is so primitive that it can be used to implement just any programming paradigm, so having it as a loadable code is not a big achievement. Well, it seems to me that Python has even simpler syntax or on par with Lisp family, so... Some (perhaps other) readers could also say, that there is no need to extend Python. It already has sets and "yield" and... But some time ago it did not. As far as I can tell, it can be a bit too hard to go into "experimenting mode" with Python. Something like adding "yield" all but myself. It only takes few kilos of code for a working OO in another language, so how hard could such "yield" be? Well, in Python I probably wouldn't dare. BTW I hope nobody's feeling have been hurt. This was meant to be informative, not offensive. BTW2. As I said, these are _possible_ things (Turing complete language, and so on). But adding them would require some hard work and would produce ugly and/or fragile code, so I decided it could be easier to learn another language... Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From aahz at pythoncraft.com Fri Aug 28 23:41:12 2009 From: aahz at pythoncraft.com (Aahz) Date: 28 Aug 2009 20:41:12 -0700 Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: In article , qwe rty wrote: > >> > if you don't know the answer please don't reply >> >> I'm not sure you understand -- Being a Turing complete language, >> anything you can do in any other language, you can do in Python. >> =A0 As "r" observed, it might not be a pleasant experience (though >> there are a lot of things I'd rather do in Python than in C or >> Assembly) but certainly doable. >> >> So clearly the issue resides in your nonsensical question. =A0You >> asked for things you can't do with Python so I listed some. =A0The >> things you can't do in Python are things you can't do in any >> other language either. =A0To turn your snark on end, "If you can't >> post a sensible question, please don't post in the first place". >> >> But this is usenet, and Python can't solve the problem of >> nonsensical questions posted on usenet. :-/ >> >> -tkc > >i am free to post , you are free to ignore Well -- don't you think the same applies in reverse? Remember that Python is named after the comedy group Monty Python, and jokes are a frequent occurrence on this group. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From sebouel at gmail.com Sat Aug 29 00:28:17 2009 From: sebouel at gmail.com (=?ISO-8859-1?Q?S=E9bastien_Ouellet?=) Date: Fri, 28 Aug 2009 21:28:17 -0700 (PDT) Subject: A lot of problem with pygame.mixer module! References: Message-ID: I had the same problem and struggled through every solution posted on the web. None actually helped but I discovered bbfreeze : http://pypi.python.org/pypi/bbfreeze/ It works as well as py2exe and there are no problems with pygame.mixer. It's easy to install and the example script at the end of the page does the trick. On 20 juil, 08:28, Alex wrote: > hi at all, > As email object I 'm not be able to run my program when compiled with > py2exe. > Everythink ?works fine until I try to make an exe. > After that, it crash and in the log: > > C:\dist\sponge.exe:97: RuntimeWarning: use mixer: DLL load failed: The > specified module could not be found. > Traceback (most recent call last): > ? File "sponge.py", line 97, in > ? File "pygame\__init__.pyo", line 70, in __getattr__ > NotImplementedError: mixer module not available > > The code about pygame.mixer is only: > > pygame.mixer.init() > music = pygame.mixer.Sound("popcorn.ogg") > music.play() > > in the dist folder there is SDL_mixer.dll so...HOW can I solve this > problem ?? > thanks in advance > Alex > Below my setup.py > > # py2exe setup program > from distutils.core import setup > import py2exe > import pygame > from modulefinder import Module > #from pygame import mixer > import ImageGrab > import sys > import os > import Tkinter > import glob, shutil > sys.argv.append("py2exe") > > VERSION = '1.0' > AUTHOR_NAME = 'Your Name' > AUTHOR_EMAIL = 'your_em... at somewhere.com' > AUTHOR_URL = "http://www.urlofyourgamesite.com/" > PRODUCT_NAME = "Sponge" > SCRIPT_MAIN = 'sponge.py' > VERSIONSTRING = PRODUCT_NAME + " ALPHA " + VERSION > ICONFILE = 'icon.ico' > > # Remove the build tree on exit automatically > REMOVE_BUILD_ON_EXIT = True > > if os.path.exists('dist/'): shutil.rmtree('dist/') > > extra_files = [ ("",[ICONFILE,'WinLockDll.dll','popcorn.ogg']), > ? ? ? ? ? ? ? ? ? ?#("data",glob.glob(os.path.join('data','*.dat'))), > ? ? ? ? ? ? ? ? ? ?#("gfx",glob.glob(os.path.join('gfx','*.jpg'))), > ? ? ? ? ? ? ? ? ? ?#("gfx",glob.glob(os.path.join('gfx','*.png'))), > ? ? ? ? ? ? ? ? ? ?("fonts",glob.glob(os.path.join('fonts','*.ttf'))), > ? ? ? ? ? ? ? ? ? ?("music",glob.glob(os.path.join('music','*.ogg')))] > ? ? ? ? ? ? ? ? ? ?#("snd",glob.glob(os.path.join('snd','*.wav')))] > > # List of all modules to automatically exclude from distribution build > # This gets rid of extra modules that aren't necessary for proper > functioning of app > # You should only put things in this list if you know exactly what you > DON'T need > # This has the benefit of drastically reducing the size of your dist > > MODULE_EXCLUDES =[ > 'email', > 'AppKit', > 'Foundation', > 'bdb', > 'difflib', > 'tcl', > #'Tkinter', > #'Tkconstants', > 'curses', > 'distutils', > 'setuptools', > 'urllib', > 'urllib2', > 'urlparse', > 'BaseHTTPServer', > '_LWPCookieJar', > '_MozillaCookieJar', > 'ftplib', > 'gopherlib', > '_ssl', > 'htmllib', > 'httplib', > 'mimetools', > 'mimetypes', > 'rfc822', > 'tty', > 'webbrowser', > 'socket', > 'hashlib', > #'base64', > 'compiler', > 'pydoc' > ] > > INCLUDE_STUFF = ['encodings',"encodings.latin_1"] > > setup(windows=[ > ? ? ? ? ? ? ?{'script': SCRIPT_MAIN, > ? ? ? ? ? ? ? ?'other_resources': [(u"VERSIONTAG",1,VERSIONSTRING)], > ? ? ? ? ? ? ? ?'icon_resources': [(1,ICONFILE)]}], > ? ? ? ? ?options = {"py2exe": { > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"optimize": 2, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"includes": INCLUDE_STUFF, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"compressed": 1, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"ascii": 1, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?#"bundle_files": 1, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"ignores": > ['tcl','AppKit','Numeric','Foundation'], > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"excludes": MODULE_EXCLUDES} }, > ? ? ? ? ? name = PRODUCT_NAME, > ? ? ? ? ? version = VERSION, > ? ? ? ? ? data_files = extra_files, > ? ? ? ? ? #zipfile = None, > ? ? ? ? ? author = AUTHOR_NAME, > ? ? ? ? ? author_email = AUTHOR_EMAIL, > ? ? ? ? ? url = AUTHOR_URL) > > # Create the /save folder for inclusion with the installer > #shutil.copytree('save','dist/save') > > #if os.path.exists('dist/tcl'): shutil.rmtree('dist/tcl') > > # Remove the build tree > if REMOVE_BUILD_ON_EXIT: > ? ? ?shutil.rmtree('build/') > > if os.path.exists('dist/tcl84.dll'): os.unlink('dist/tcl84.dll') > if os.path.exists('dist/tk84.dll'): os.unlink('dist/tk84.dll') From gagsl-py2 at yahoo.com.ar Sat Aug 29 00:37:37 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Aug 2009 01:37:37 -0300 Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> Message-ID: En Fri, 28 Aug 2009 15:25:55 -0300, zaur escribi?: > On 28 ???, 16:07, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> zaur a ?crit : >> >> > Ok. Here is a use case: object initialization. >> >> > For example, >> >> > person = Person(): >> > ? name = "john" >> > ? age = 30 >> > ? address = Address(): >> > ? ? ?street = "Green Street" >> > ? ? ?no = 12 >> >> > vs. >> >> > person = Person() >> > person.name = "john" >> > person.age = 30 >> > address = person.address = Address() >> > address.street = "Green Street" >> > address.no = 12 >> >> Err... Looks like you really should read the FineManual(tm) - >> specifically, the parts on the __init__ method. >> >> class Person(object): >> ? ? def __init__(self, name, age, address): >> ? ? ? ? self.name = name >> ? ? ? ? self.age = age >> ? ? ? ? self.address = address >> >> class Address(object): >> ? ? def __init__(self, street, no): >> ? ? ? ? self.no = no >> ? ? ? ? self.street = street >> >> person = Person( >> ? ? name="john", >> ? ? age=30, >> ? ? address = Address( >> ? ? ? ? street="Green Street", >> ? ? ? ? no=12 >> ? ? ) >> ) > > What are you doing if 1) classes Person and Address imported from > foreign module 2) __init__ method is not defined as you want? Welcome to dynamic languages! It doesn't matter *where* the class was defined. You may add new attributes to the instance (even methods to the class) at any time. 1) person = Person() vars(person).update(name="john",age=30,address=Address()) vars(person.Address).update(street="Green Street",no=12) 2) def the_initializer_i_would_like(person, name, age): person.name = name person.age = age person = Person() the_initializer_i_would_like(person, name="john", age=30) 3) def the_initializer_i_would_like(self, name, age): self.name = name self.age = age Person.init = the_initializer_i_would_like person = Person() person.init(name="john", age=30) 4) def a_generic_updater(obj, **kw): try: ns = vars(obj) except Exception: ns = None if ns is not None: ns.update(kw) else: for name in kw: setattr(obj, name, kw[name]) person = Person() a_generic_updater(person, name="john", age=30) -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sat Aug 29 00:43:09 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Aug 2009 01:43:09 -0300 Subject: how to edit .wsgi file extebtions with IDLE on windows References: Message-ID: En Fri, 28 Aug 2009 15:31:31 -0300, gert escribi?: > I can't figure out how to enable the .py shell and syntax highlighting > for .wsgi file extensions using IDLE for windows ? That's a Windows question, not a Python one. You have to associate the .wsgi extension with the Python.File file type (the one used for .py files): D:\USERDATA\Gabriel>assoc .py .py=Python.File D:\USERDATA\Gabriel>assoc .wsgi=Python.File .wsgi=Python.File -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sat Aug 29 00:48:36 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Aug 2009 01:48:36 -0300 Subject: copy construtor question References: <613204.64791.qm@web53105.mail.re2.yahoo.com> <50697b2c0908281747q347d849cx3e8abe2ebe94a120@mail.gmail.com> Message-ID: En Fri, 28 Aug 2009 21:47:51 -0300, Chris Rebert escribi?: > On Fri, Aug 28, 2009 at 11:38 AM, xiaosong xia > wrote: >> >> 2. How to make a copy constructor? > > Since Python lacks overloading based on parameter types, generally one > does it the other way around and instead provides a method that > produces a copy of the object. For example: > > class Point(object): > def __init__(self, x, y): > self. x = x > self.y = y > > def copy(self): > return Point(self.x, self.y) For simple enough cases, the copy and deepcopy functions in the copy module are just fine: http://docs.python.org/library/copy.html -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 01:21:08 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 05:21:08 GMT Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <00223e3f$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 05:37:34 +0200, Tomasz Rola wrote: > My private list of > things that when implemented in Python would be ugly to the point of > calling it difficult: > > 1. AMB operator - my very favourite. In one sentence, either language > allows one to do it easily or one would not want to do it (in an ugly > way). > > http://www.randomhacks.net/articles/2005/10/11/amb-operator Fascinating, but I don't exactly see how that's actually *useful*. It strikes me of combining all the benefits of COME FROM with the potential performance of Bogosort, but maybe I'm being harsh. On the other hand, it sounds rather like Prolog-like declarative programming. I fear that, like Prolog, it risks massive performance degradation if you don't apply the constraints in the right order. > 2. Changing the language from the inside. > > Everybody can change the interpreter, right? But how about doing some > bigger, maybe even fundamental change to the language by means offered > by the language itself? Like Forth. You need it in Forth, because it has a very sparse set of language features, and everything is bootstrapped from a small set of commands, so the ability to re-define the language as you go is (1) necessary and (2) free. But for Python, I don't know... it sounds cool, but in practice? It sounds like the sort of thing that allows programmers to spend three hours writing a new control structure which will save them three minutes. And of course, for all but the tiniest, one-man-band applications, readability is important. Sure, you've created a gee-whizz control structure which combines try, while and if into one keyword, and it automatically does logging and threading, fantastic. But how will anyone else be able to maintain it when you're gone? The ability to change the language is one step into a tarpit, where everything is possible but nothing is easy, and where you spend all your time writing language features and none of your time building the useful functionality you actually want. It sounds like something you want in a language you use for designing languages, rather than writing applications. -- Steven From rozzin at geekspace.com Sat Aug 29 01:23:59 2009 From: rozzin at geekspace.com (Joshua Judson Rosen) Date: Sat, 29 Aug 2009 01:23:59 -0400 Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: <87vdk76vm8.fsf@slice.rozzin.com> Robert Kern writes: > > On 2009-08-28 16:42 PM, Terry Reedy wrote: > > Carl Banks wrote: > > > > > I don't think it needs a syntax for that, but I'm not so sure a > > > method to modify a value in place with a single key lookup > > > wouldn't occasioanally be useful. > > > > Augmented assignment does that. > > No, it uses one __getitem__ and one __setitem__ thus two key lookups. Apparently you're defining "key lookup" some other way than as `what __getitem__ does'. What exactly does "key lookup" mean to you? I've always understood it as `retrieving the value associated with a key', which obviously isn't required for assignment--otherwise it wouldn't be possible to add new keys to a mapping. -- Don't be afraid to ask (Lf.((Lx.xx) (Lr.f(rr)))). From rozzin at geekspace.com Sat Aug 29 01:37:21 2009 From: rozzin at geekspace.com (Joshua Judson Rosen) Date: Sat, 29 Aug 2009 01:37:21 -0400 Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> <58e91734-d03f-417c-89b1-f2717c3a9181@l5g2000yqo.googlegroups.com> Message-ID: <87ws4n5gfi.fsf@slice.rozzin.com> Carl Banks writes: > > On Aug 28, 2:42?pm, Terry Reedy wrote: > > > Carl Banks wrote: > > > I don't think it needs a syntax for that, but I'm not so sure a method > > > to modify a value in place with a single key lookup wouldn't > > > occasioanally be useful. > > > > Augmented assignment does that. > > Internally uses two lookups, one for getting, and one for setting. > > I think this is an unavoidable given Python's semantics. Look at > the traceback: > > > >>> def x(): > ... d['a'] += 1 > ... > >>> dis.dis(x) > 2 0 LOAD_GLOBAL 0 (d) > 3 LOAD_CONST 1 ('a') > 6 DUP_TOPX 2 > 9 BINARY_SUBSCR OK, there's one lookup, but... > 10 LOAD_CONST 2 (1) > 13 INPLACE_ADD > 14 ROT_THREE > 15 STORE_SUBSCR > 16 LOAD_CONST 0 (None) > 19 RETURN_VALUE ... I don't see anything in there that retrieves the value a second time.... > > > As a workaround, if lookups are expensive, > > > > But they are not. Because (C)Python is heavily based on dict name lookup > > for builtins and global names and attributes, as well as overt dict > > lookup, must effort has gone into optimizing dict lookup. > > The actual lookup algorithm Python dicts use is well-optimized, yes, > but the dict could contain keys that have expensive comparison and > hash-code calculation, in which case lookup is going to be slow. I'll like the originator correct me if I've made a mistake, but I read "lookup" as actually meaning "lookup", not "value-comparison". At least in part because the question, as it was posed, specifically related to a wrapper-class (providing a mapping ("dict like") interface) around a database of some sort other than Python's dict class per se. How do the details of Python's native dict-type's internal (hashtable) algorithm matter when they're explicitly /not/ being used? -- Don't be afraid to ask (Lf.((Lx.xx) (Lr.f(rr)))). From icevi.icevi at gmail.com Sat Aug 29 02:09:45 2009 From: icevi.icevi at gmail.com (Vivian Wang) Date: Fri, 28 Aug 2009 23:09:45 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: On Aug 24, 8:08?pm, Gilles Ganault wrote: > Hello > > ? ? ? ? I was wondering if some people in this ng use Python and some GUI > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > applications, and if yes, what it's like, the pros and cons, etc. > > I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. > > I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. > > Thank you. On Aug 24, 8:08 pm, Gilles Ganault wrote: > Hello > > I was wondering if some people in this ng use Python and some GUI > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > applications, and if yes, what it's like, the pros and cons, etc. > > I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. > > I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. > > Thank you. You can try biform: http://www.bilive.com/download/Setup_BiForm_V2.1_en.msi.zip Demo: http://www.bilive.com/demo/BiForm_EN_demo.htm More demo:(Chinese version) http://www.bilive.com/demo/ BiForm is a form designer,one designed form will deploy as a PFF file. BiReader is a runtime PFF file process engine for end-users. Setup file above include BiForm and BiReader. Main features: *Python as script language,base on QT GUI library *Visible form designer *Internal database access framework *Auto connect database,auto create tables *Supports SQLite/Mssql2000/Sybase ASE,not need write diffrent script for diffrent database at most time *Simple deploy,simple upgrade *Different forms can share same tables, they will auto cooperation with other forms at runtime.If you want to deploy a new function , not need uninstall other forms,deploy the new PFF file is enough . From ivanko.rus at gmail.com Sat Aug 29 02:28:26 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 06:28:26 +0000 Subject: Monitoring stdout in (more or less) real time Message-ID: <000e0cd148be848541047241e842@google.com> Hello to everyone! I am making a program that will be a GTK+ frontend to ffmpeg. Naturally, one of the main functions is parsing ffmpeg's output. It's pretty simple when I, for example, retrieve information about a file (the program finishes and I read the output). But it also needs to parse working ffmpeg's output (in order to retrieve the percentage, remaining time, etc.). So, actually what I do is Popen ffmpeg, and connect to its stdout. And as stdout is represented by a file object, it needs to be read(). The problem is that read() reads until EOF is reached, which doesn't exist while the program is running (the same goes with communicate()). So my question is: is there a way to retrieve the stdout without waiting the program to finish? PS. I think it might be redirected to a "normal", existing file, but may be there are more optimal ways. I will be grateful for any answer! And sorry for my English =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From icevi.icevi at gmail.com Sat Aug 29 02:32:16 2009 From: icevi.icevi at gmail.com (Vivian Wang) Date: Fri, 28 Aug 2009 23:32:16 -0700 (PDT) Subject: IDE for python similar to visual basic References: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> Message-ID: <2127e0be-3b93-406f-99a7-5fe02e643b40@a39g2000pre.googlegroups.com> On Aug 29, 6:19?am, qwe rty wrote: > i have been searching for am IDE for python that is similar to Visual > Basic but had no luck.shall you help me please? You can try biform: http://www.bilive.com/download/Setup_BiForm_V2.1_en.msi.zip Demo: http://www.bilive.com/demo/BiForm_EN_demo.htm More demo:(Chinese version) http://www.bilive.com/demo/ BiForm is a form designer,one designed form will deploy as a PFF file. BiReader is a runtime PFF file process engine for end-users. Setup file above include BiForm and BiReader. Main features: *Python as script language,base on QT GUI library *Visible form designer *Internal database access framework *Auto connect database,auto create tables *Supports SQLite/Mssql2000/Sybase ASE,not need write diffrent script for diffrent database at most time *Simple deploy,simple upgrade *Different forms can share same tables,they will auto cooperation with other forms at runtime.If you want to deploy a new function , not need uninstall other forms,deploy the new PFF file is enough . From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 03:10:11 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 07:10:11 GMT Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> <87vdk76vm8.fsf@slice.rozzin.com> Message-ID: <002257cf$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 01:23:59 -0400, Joshua Judson Rosen wrote: > Robert Kern writes: >> >> On 2009-08-28 16:42 PM, Terry Reedy wrote: >> > Carl Banks wrote: >> > >> > > I don't think it needs a syntax for that, but I'm not so sure a >> > > method to modify a value in place with a single key lookup wouldn't >> > > occasioanally be useful. >> > >> > Augmented assignment does that. >> >> No, it uses one __getitem__ and one __setitem__ thus two key lookups. > > Apparently you're defining "key lookup" some other way than as `what > __getitem__ does'. > > What exactly does "key lookup" mean to you? > > I've always understood it as `retrieving the value associated with a > key', which obviously isn't required for assignment--otherwise it > wouldn't be possible to add new keys to a mapping. When you retrieve a value from a dictionary using __getitem__, e.g.: dict["K"] the dict has to search the hash table for the record with key "K". This a key lookup. (I use the term "search", but of course for hash tables this is usually very fast. For Python dicts, you can assume it will usually be a constant time, independent of the key or the size of the dict.) When you store a value in a dictionary using __setitem__, e.g.: dict["K"] = 42 the dict has to search the hash table for the correct place to store a record with key "K". It obviously can't place the record in some arbitrary place, it has to be in the correct place for future lookups to find it. This is also a key lookup. -- Steven From erik.reppen at gmail.com Sat Aug 29 03:20:59 2009 From: erik.reppen at gmail.com (Pherdnut) Date: Sat, 29 Aug 2009 00:20:59 -0700 (PDT) Subject: Python Noob - gui module, book, annoying questions Message-ID: <92cc4ca1-0e0d-4355-8d9a-b4928390e619@q35g2000vbi.googlegroups.com> I want to write cross-platform stuff. Any opinions on the best GUI module for that? I like a good juicy, but concise book for reading on my commute downtown. I was thinking of checking Python in a Nutshell. Good? Bad? Better? Is 3.0+ more object based? I'm actually an FED and one of the things I love about JS is the consistency of the language. I love Python 2.6 so far so I'm not knocking it. But I'm not really taking advantage of the non-core libraries as much right now anyway since I'm learning it. What do you guys like in Reg Ex books/sites? I'd like to become more fluent in some of the less commonly used stuff. From gagsl-py2 at yahoo.com.ar Sat Aug 29 03:21:20 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Aug 2009 04:21:20 -0300 Subject: Monitoring stdout in (more or less) real time References: <000e0cd148be848541047241e842@google.com> Message-ID: En Sat, 29 Aug 2009 03:28:26 -0300, escribi?: > Hello to everyone! I am making a program that will be a GTK+ frontend to > ffmpeg. Naturally, one of the main functions is parsing ffmpeg's output. > It's pretty simple when I, for example, retrieve information about a file > (the program finishes and I read the output). But it also needs to parse > working ffmpeg's output (in order to retrieve the percentage, remaining > time, etc.). So, actually what I do is Popen ffmpeg, and connect to its > stdout. And as stdout is represented by a file object, it needs to be > read(). The problem is that read() reads until EOF is reached, which > doesn't exist while the program is running (the same goes with > communicate()). > So my question is: is there a way to retrieve the stdout without waiting > the program to finish? You don't have to read the complete output at once - you may process it line by line, I presume. I'd use a second thread to read the pipe and put the lines onto a Queue object; the main thread gets lines from the Queue when available. -- Gabriel Genellina From thorsten at thorstenkampe.de Sat Aug 29 03:34:43 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 29 Aug 2009 09:34:43 +0200 Subject: (Simple?) Unicode Question References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> Message-ID: * Rami Chowdhury (Thu, 27 Aug 2009 09:44:41 -0700) > > Further, does anything, except a printing device need to know the > > encoding of a piece of "text"? Python needs to know if you are processing the text. > I may be wrong, but I believe that's part of the idea between separation > of string and bytes types in Python 3.x. I believe, if you are using > Python 3.x, you don't need the character encoding mumbo jumbo at all ;-) Nothing has changed in that regard. You still need to decode and encode text and for that you have to know the encoding. Thorsten From szport at gmail.com Sat Aug 29 03:34:48 2009 From: szport at gmail.com (zaur) Date: Sat, 29 Aug 2009 00:34:48 -0700 (PDT) Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> Message-ID: <9205fd44-90ec-4ce6-be2a-2f82dd99e13e@r27g2000vbn.googlegroups.com> On 29 ???, 08:37, "Gabriel Genellina" wrote: > En Fri, 28 Aug 2009 15:25:55 -0300, zaur escribi?: > > > > > On 28 ???, 16:07, Bruno Desthuilliers > 42.desthuilli... at websiteburo.invalid> wrote: > >> zaur a ?crit : > > >> > Ok. Here is a use case: object initialization. > > >> > For example, > > >> > person = Person(): > >> > ? name = "john" > >> > ? age = 30 > >> > ? address = Address(): > >> > ? ? ?street = "Green Street" > >> > ? ? ?no = 12 > > >> > vs. > > >> > person = Person() > >> > person.name = "john" > >> > person.age = 30 > >> > address = person.address = Address() > >> > address.street = "Green Street" > >> > address.no = 12 > > >> Err... Looks like you really should read the FineManual(tm) - > >> specifically, the parts on the __init__ method. > > >> class Person(object): > >> ? ? def __init__(self, name, age, address): > >> ? ? ? ? self.name = name > >> ? ? ? ? self.age = age > >> ? ? ? ? self.address = address > > >> class Address(object): > >> ? ? def __init__(self, street, no): > >> ? ? ? ? self.no = no > >> ? ? ? ? self.street = street > > >> person = Person( > >> ? ? name="john", > >> ? ? age=30, > >> ? ? address = Address( > >> ? ? ? ? street="Green Street", > >> ? ? ? ? no=12 > >> ? ? ) > >> ) > > > What are you doing if 1) classes Person and Address imported from > > foreign module 2) __init__ method is not defined as you want? > > Welcome to dynamic languages! It doesn't matter *where* the class was ? > defined. You may add new attributes to the instance (even methods to the ? > class) at any time. > > 1) > person = Person() > vars(person).update(name="john",age=30,address=Address()) > vars(person.Address).update(street="Green Street",no=12) > > 2) > def the_initializer_i_would_like(person, name, age): > ? ?person.name = name > ? ?person.age = age > > person = Person() > the_initializer_i_would_like(person, name="john", age=30) > > 3) > def the_initializer_i_would_like(self, name, age): > ? ?self.name = name > ? ?self.age = age > > Person.init = the_initializer_i_would_like > person = Person() > person.init(name="john", age=30) > > 4) > def a_generic_updater(obj, **kw): > ? ?try: ns = vars(obj) > ? ?except Exception: ns = None > ? ?if ns is not None: > ? ? ?ns.update(kw) > ? ?else: > ? ? ?for name in kw: > ? ? ? ?setattr(obj, name, kw[name]) > > person = Person() > a_generic_updater(person, name="john", age=30) > > -- > Gabriel Genellina I know about these ways of object initializing. What I said is about using object's dictionary as nested scope in code block. Object initialization is just one use case. So we say about different things. From hendrik at microcorp.co.za Sat Aug 29 03:36:38 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 29 Aug 2009 09:36:38 +0200 Subject: comparison on list yields surprising result In-Reply-To: <25195170.post@talk.nabble.com> References: <25195170.post@talk.nabble.com> Message-ID: <200908290936.38375.hendrik@microcorp.co.za> On Friday 28 August 2009 21:00:31 Dr. Phillip M. Feldman wrote: > In [21]: x > Out[21]: [1, 2, 3, 5] > > In [22]: x>6 > Out[22]: True > > Is this a bug? No, it is a feature, so that you can use sorted on this: [[1,2,3,4,5],6] - Hendrik From hendrik at microcorp.co.za Sat Aug 29 03:50:43 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 29 Aug 2009 09:50:43 +0200 Subject: What python can NOT do? In-Reply-To: <4A9872EF.2000708@tim.thechases.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> <4A9872EF.2000708@tim.thechases.com> Message-ID: <200908290950.43216.hendrik@microcorp.co.za> On Saturday 29 August 2009 02:14:39 Tim Chase wrote: > I've also been sorely disappointed by Python's ability to make a > good chocolate cream silk pie. This is not pythons fault - it is yours, for failing to collaborate with a good hardware designer for the robotics. - Hendrik From nomail at nomail.com Sat Aug 29 03:54:15 2009 From: nomail at nomail.com (Sortie) Date: Sat, 29 Aug 2009 07:54:15 +0000 (UTC) Subject: Combining C and Python programs Message-ID: I want to write a program that will use ode for the physics simulation, whose python bindings are outdated. So I'm writing the physics engine in C and want to write the drawing code in Python. What will be the best way of making those two programs work together? THe physics engine won't have to run concurrently with the drawing code. It will only return some position data so they can be drawn. From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 04:16:21 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 08:16:21 GMT Subject: comparison on list yields surprising result References: <25195170.post@talk.nabble.com> Message-ID: <00226752$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 09:36:38 +0200, Hendrik van Rooyen wrote: > On Friday 28 August 2009 21:00:31 Dr. Phillip M. Feldman wrote: >> In [21]: x >> Out[21]: [1, 2, 3, 5] >> >> In [22]: x>6 >> Out[22]: True >> >> Is this a bug? > > No, it is a feature, so that you can use sorted on this: > > [[1,2,3,4,5],6] If it's a feature, it has gone away in Python 3. Python 3.0.1 (r301:69556, Apr 2 2009, 00:41:38) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> [[1,2,3], 5].sort() Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: int() < list() -- Steven From hendrik at microcorp.co.za Sat Aug 29 04:24:52 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 29 Aug 2009 10:24:52 +0200 Subject: Combining C and Python programs In-Reply-To: References: Message-ID: <200908291024.52629.hendrik@microcorp.co.za> On Saturday 29 August 2009 09:54:15 Sortie wrote: > I want to write a program that will use ode for the physics > simulation, whose python bindings are outdated. So I'm writing > the physics engine in C and want to write the drawing code in > Python. What will be the best way of making those two programs > work together? THe physics engine won't have to run concurrently > with the drawing code. It will only return some position data so > they can be drawn. Have you looked at ctypes? - Hendrik From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 04:26:54 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 08:26:54 GMT Subject: (Simple?) Unicode Question References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> Message-ID: <002269cb$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 09:34:43 +0200, Thorsten Kampe wrote: > * Rami Chowdhury (Thu, 27 Aug 2009 09:44:41 -0700) >> > Further, does anything, except a printing device need to know the >> > encoding of a piece of "text"? > > Python needs to know if you are processing the text. Python only needs to know when you convert the text to or from bytes. I can do this: >>> s = "hello" >>> t = "world" >>> print(' '.join([s, t])) hello world and not need to care anything about encodings. So long as your terminal has a sensible encoding, and you have a good quality font, you should be able to print any string you can create. >> I may be wrong, but I believe that's part of the idea between >> separation of string and bytes types in Python 3.x. I believe, if you >> are using Python 3.x, you don't need the character encoding mumbo jumbo >> at all ;-) > > Nothing has changed in that regard. You still need to decode and encode > text and for that you have to know the encoding. You only need to worry about encoding when you convert from bytes to text, and visa versa. Admittedly, the most common time you need to do that is when reading input from files, but if all your text strings are generated by Python, and not output anywhere, you shouldn't need to care about encodings. If all your text contains nothing but ASCII characters, you should never need to worry about encodings at all. -- Steven From bilawal.samoon at gmail.com Sat Aug 29 04:46:15 2009 From: bilawal.samoon at gmail.com (bilawal samoon) Date: Sat, 29 Aug 2009 01:46:15 -0700 (PDT) Subject: SEI Job Opening Message-ID: SEI is seeking a FT, YR Photovoltaic Technical Manager. If you are a team player with a minimum of 4 years PV installation, curriculum and education development, management experience, the ability to multitask, strong verbal and written communication skills, and a sense of humor, SEI invites you to apply to join our team in Paonia, Colorado. For more details www.technicaledu.blogspot.com From thangappan143 at gmail.com Sat Aug 29 05:12:36 2009 From: thangappan143 at gmail.com (Thangappan.M) Date: Sat, 29 Aug 2009 14:42:36 +0530 Subject: Suggestion Message-ID: <7aa29e790908290212h17d27593u52d1a90b3e785386@mail.gmail.com> Dear all, I am in the process of learning Python programming language. I know Perl,PHP. Compare to both the language Python impressed me because here there is no lexical variables and all.Now I need suggestion saying that , What online book can I follow? I have not yet learnt any advanced programming stuffs in Python. Please suggest some book? or tutorial. net net my goal is that I will be able to do the project in any languages(Python,Perl,PHP).So I need to learn more depth knowledge of Python. So Please help me? -- Regards, Thangappan.M -------------- next part -------------- An HTML attachment was scrubbed... URL: From thangappan143 at gmail.com Sat Aug 29 05:14:00 2009 From: thangappan143 at gmail.com (Thangappan.M) Date: Sat, 29 Aug 2009 14:44:00 +0530 Subject: IDE for Python Message-ID: <7aa29e790908290214ode909c8od898918e86759daf@mail.gmail.com> Dear all, Please suggest some good IDE for python.I am working in linux platform. -- Regards, Thangappan.M -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sat Aug 29 06:58:10 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 29 Aug 2009 03:58:10 -0700 (PDT) Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> <58e91734-d03f-417c-89b1-f2717c3a9181@l5g2000yqo.googlegroups.com> <87ws4n5gfi.fsf@slice.rozzin.com> Message-ID: On Aug 28, 10:37?pm, Joshua Judson Rosen wrote: > Carl Banks writes: > > > On Aug 28, 2:42?pm, Terry Reedy wrote: > > > > Carl Banks wrote: > > > > I don't think it needs a syntax for that, but I'm not so sure a method > > > > to modify a value in place with a single key lookup wouldn't > > > > occasioanally be useful. > > > > Augmented assignment does that. > > > Internally uses two lookups, one for getting, and one for setting. > > > I think this is an unavoidable given Python's semantics. ?Look at > > the traceback: > > > >>> def x(): > > ... ? ? d['a'] += 1 > > ... > > >>> dis.dis(x) > > ? 2 ? ? ? ? ? 0 LOAD_GLOBAL ? ? ? ? ? ? ?0 (d) > > ? ? ? ? ? ? ? 3 LOAD_CONST ? ? ? ? ? ? ? 1 ('a') > > ? ? ? ? ? ? ? 6 DUP_TOPX ? ? ? ? ? ? ? ? 2 > > ? ? ? ? ? ? ? 9 BINARY_SUBSCR > > OK, there's one lookup, but... > > > ? ? ? ? ? ? ?10 LOAD_CONST ? ? ? ? ? ? ? 2 (1) > > ? ? ? ? ? ? ?13 INPLACE_ADD > > ? ? ? ? ? ? ?14 ROT_THREE > > ? ? ? ? ? ? ?15 STORE_SUBSCR > > ? ? ? ? ? ? ?16 LOAD_CONST ? ? ? ? ? ? ? 0 (None) > > ? ? ? ? ? ? ?19 RETURN_VALUE > > ... I don't see anything in there that retrieves the value a second time.... STORE_SUBSCR has to look up the position in the hash table to store the value, hence the second lookup. > > > > As a workaround, if lookups are expensive, > > > > But they are not. Because (C)Python is heavily based on dict name lookup > > > for builtins and global names and attributes, as well as overt dict > > > lookup, must effort has gone into optimizing dict lookup. > > > The actual lookup algorithm Python dicts use is well-optimized, yes, > > but the dict could contain keys that have expensive comparison and > > hash-code calculation, in which case lookup is going to be slow. > > I'll like the originator correct me if I've made a mistake, but I read > "lookup" as actually meaning "lookup", not "value-comparison". This has nothing to do with value comparison. I was talking about key comparison, which happens when looking up a position in a hash table. I was the first person to use the word "lookup" in this thread and I specifically meant hash-table position lookup. > At least in part because the question, as it was posed, specifically > related to a wrapper-class (providing a mapping ("dict like") interface) > around a database of some sort other than Python's dict class per se. > > How do the details of Python's native dict-type's internal (hashtable) > algorithm matter when they're explicitly /not/ being used? Well it doesn't apply specifically to the OP's problem. I changed the topic a bit by making it specific to dicts. Is that ok with you? Was that not allowed? The OP can add a method like apply_to_value to his own class, but one can't do that for dicts. Ergo why something like apply_to_value() would be useful enough in rare circumstances where lookup is very slow to merit a moments consideration before being rejected. (If dict did have a method like that, the OP would at least know which method to override.) Carl Banks From vicente.soler at gmail.com Sat Aug 29 07:01:46 2009 From: vicente.soler at gmail.com (vsoler) Date: Sat, 29 Aug 2009 04:01:46 -0700 (PDT) Subject: Colors on IDLE References: <59922ab5-f8c9-429f-b1ea-9b1418aa6b71@t13g2000yqt.googlegroups.com> <8d5d283f-b0bd-4e16-97c7-d2de1a148cae@l35g2000vba.googlegroups.com> Message-ID: <311ec593-4050-4a6a-adbd-2325698a4b61@h30g2000vbr.googlegroups.com> On Aug 29, 1:27?am, r wrote: > Have you tried saving the files as MYScriptName.py? notice the py > extension, very important ;) That was it!!! I see the colors again. Thank you. From paul at subsignal.org Sat Aug 29 07:16:00 2009 From: paul at subsignal.org (paul) Date: Sat, 29 Aug 2009 13:16:00 +0200 Subject: why python got less developers ? In-Reply-To: References: Message-ID: Deep_Feelings schrieb: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc why ? Besides the marketing argument, python never had a "hype". Both PHP and ruby(Rails to be precise) got widespread because they could at one point do "one" thing better than the competition. From there on, they had more ressources (developer time) and grew fast and beyond the original problem domain. Now you can write GUI apps in PHP, great! cheers Paul From thorsten at thorstenkampe.de Sat Aug 29 07:34:18 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 29 Aug 2009 13:34:18 +0200 Subject: Colors on IDLE References: <59922ab5-f8c9-429f-b1ea-9b1418aa6b71@t13g2000yqt.googlegroups.com> <8d5d283f-b0bd-4e16-97c7-d2de1a148cae@l35g2000vba.googlegroups.com> <311ec593-4050-4a6a-adbd-2325698a4b61@h30g2000vbr.googlegroups.com> Message-ID: * vsoler (Sat, 29 Aug 2009 04:01:46 -0700 (PDT)) > On Aug 29, 1:27?am, r wrote: > > Have you tried saving the files as MYScriptName.py? notice the py > > extension, very important ;) > > That was it!!! > > I see the colors again. Thank you. I suggest you start using familiar technical terms. Like "syntax highlighting" instead of "see colours". That would increase the number of useful answers you get - at least it will stop people from thinking you talk about controlled substances. Thorsten From mwawrzyczek at gmail.com Sat Aug 29 08:14:34 2009 From: mwawrzyczek at gmail.com (Marek Wawrzyczek) Date: Sat, 29 Aug 2009 05:14:34 -0700 (PDT) Subject: gettext translate problem Message-ID: Hi, I've got the following code in main.py file: import gettext import os t = gettext.translation(__file__.split('.')[0], os.getcwd()) _ = t.lgettext if __name__=='__main__': print _("Hello") then I call: xgettext main.py and after that I call: msgfmt messages.po wchich produces the following message: messages.po: warning: Charset "CHARSET" is not a portable encoding name. Message conversion to user's charset might not work. then after calling: python main.py the following output is print: Traceback (most recent call last): File "main.py", line 4, in t = gettext.translation(__file__.split('.')[0], os.getcwd()) File "/usr/lib/python2.5/gettext.py", line 484, in translation raise IOError(ENOENT, 'No translation file found for domain', domain) IOError: [Errno 2] No translation file found for domain: 'main' How to use gettext translation method properly? Regards, Marek From invalid at invalid Sat Aug 29 08:21:11 2009 From: invalid at invalid (Grant Edwards) Date: Sat, 29 Aug 2009 07:21:11 -0500 Subject: Annoying octal notation References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> <00216447$0$2930$c3e8da3@news.astraweb.com> Message-ID: On 2009-08-28, Neil Hodgson wrote: > Steven D'Aprano: > >> Obviously I can't speak for Ken Thompson's motivation in creating this >> feature, but I'm pretty sure it wasn't to save typing or space on >> punchcards. > > The original implementation of UNIX was on a PDP-7 which was an > 18-bit machine. Octal = 3 bits at a a time which evenly divides an > 18-bit word whereas the 4 bits of hexadecimal do not. Early > implementations of B were (according to Wikipedia) on the PDP-7, PDP-11 > (a 16-bit machine) and Honeywell 36-bit mainframes. > > Octal was widely used on the PDP-11. The PDP-11's 16-bit instruction word consisted mainly of 3-bit fields for destiation-mode, destination-register, source-mode, source-register. So, it was quite easy for the progammer to read/write machine code in octal. -- Grant Edwards grante Yow! I've read SEVEN at MILLION books!! visi.com From gert.cuykens at gmail.com Sat Aug 29 08:40:29 2009 From: gert.cuykens at gmail.com (gert) Date: Sat, 29 Aug 2009 05:40:29 -0700 (PDT) Subject: how to edit .wsgi file extebtions with IDLE on windows References: Message-ID: <58a021ce-3058-483d-b429-6ba4855807ac@o36g2000vbl.googlegroups.com> On Aug 29, 6:43?am, "Gabriel Genellina" wrote: > En Fri, 28 Aug 2009 15:31:31 -0300, gert escribi?: > > > I can't figure out how to enable the .py shell and syntax highlighting > > for .wsgi file extensions using IDLE for windows ? > > That's a Windows question, not a Python one. You have to associate the ? > .wsgi extension with the Python.File file type (the one used for .py ? > files): > > D:\USERDATA\Gabriel>assoc .py > .py=Python.File > > D:\USERDATA\Gabriel>assoc .wsgi=Python.File > .wsgi=Python.File > Thanks that does make it open exactly like a .py file, expect that there is no syntax highlighting. Don't know if this is also a windows issue or a IDLE issue ? From szport at gmail.com Sat Aug 29 08:45:54 2009 From: szport at gmail.com (zaur) Date: Sat, 29 Aug 2009 05:45:54 -0700 (PDT) Subject: Is behavior of += intentional for int? Message-ID: Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "copyright", "credits" or "license()" for more information. >>> a=1 >>> x=[a] >>> id(a)==id(x[0]) True >>> a+=1 >>> a 2 >>> x[0] 1 I thought that += should only change the value of the int object. But += create new. Is this intentional? From ptmcg at austin.rr.com Sat Aug 29 09:08:49 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 29 Aug 2009 06:08:49 -0700 (PDT) Subject: Is behavior of += intentional for int? References: Message-ID: On Aug 29, 7:45?am, zaur wrote: > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin > Type "copyright", "credits" or "license()" for more information.>>> a=1 > >>> x=[a] > >>> id(a)==id(x[0]) > True > >>> a+=1 > >>> a > 2 > >>> x[0] > > 1 > > I thought that += should only change the value of the int object. But > += create new. > Is this intentional? ints are immutable. But your logic works fine with a mutable object, like a list: >>> a = [1] >>> x = [a] >>> print id(a) == id(x[0]) True >>> a += [1] >>> print a [1, 1] >>> print x[0] [1, 1] What exactly are you trying to do? -- Paul From gd_usenet at spamfence.net Sat Aug 29 09:23:20 2009 From: gd_usenet at spamfence.net (=?UTF-8?Q?G=C3=BCnther?= Dietrich) Date: Sat, 29 Aug 2009 15:23:20 +0200 Subject: Is behavior of += intentional for int? References: Message-ID: <8nmnm6-g6g.ln1@spamfence.net> zaur wrote: >Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) >[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin >Type "copyright", "credits" or "license()" for more information. >>>> a=1 >>>> x=[a] >>>> id(a)==id(x[0]) >True >>>> a+=1 >>>> a >2 >>>> x[0] >1 > >I thought that += should only change the value of the int object. But >+= create new. >Is this intentional? An integer variable contains the reference (ID) to an (immutable) integer object; it doesn't contain the value itself. So, when you assign a new value to an integer variable, it will contain the reference to the object containing the new value, afterwards. If you assign an integer variable to a list element, this reference will be written into the list. The assignment of a new value to the integer variable will create a new integer object, containing the new value, and put the reference to it into the integer variable. The reference to the object with the old value, that is stored in the list, won't be touched. In fact, it is a result of integers in python being immutable. Best regards, G?nther From nitebirdz at sacredchaos.com Sat Aug 29 09:33:38 2009 From: nitebirdz at sacredchaos.com (Nitebirdz) Date: Sat, 29 Aug 2009 15:33:38 +0200 Subject: Blank Line at Program Exit In-Reply-To: References: <20090822152515.GC10584@sevilla.sacredchaos.com> Message-ID: <20090829133337.GA6751@sevilla.sacredchaos.com> On Sun, Aug 23, 2009 at 09:07:53PM +0800, Steven Woody wrote: > > Hi, > I am using cywin on XP. > Sorry for the late reply. I've been too busy with some personal matters. It'd seem to me that you're better off taking this issue to the Cygwin mailing lists, since it doesn't seem to be related to Python itself. From jkpeck at gmail.com Sat Aug 29 10:12:33 2009 From: jkpeck at gmail.com (JKPeck) Date: Sat, 29 Aug 2009 07:12:33 -0700 (PDT) Subject: csv module and None values References: <23c02daf-dc5a-4676-8d73-9dc63791825f@o36g2000vbl.googlegroups.com> <4006702e-14c5-4917-b76f-906233cad71e@k30g2000yqf.googlegroups.com> Message-ID: On Aug 25, 8:49?am, Peter Otten <__pete... at web.de> wrote: > JKPeck wrote: > > On Aug 24, 10:43 pm, John Yeung wrote: > >> On Aug 24, 5:00 pm, Peter Otten <__pete... at web.de> wrote: > > >> > If I understand you correctly the csv.writer already does > >> > what you want: > > >> > >>> w.writerow([1,None,2]) > >> > 1,,2 > > >> > just sequential commas, but that is the special treatment. > >> > Without it the None value would be converted to a string > >> > and the line would look like this one: > > >> > 1,None,2 > > >> No, I think he means he is getting > > >> >>> w.writerow([1,None,2]) > > >> 1,"",2 > > >> He evidently wants to quote "all" strings, but doesn't want None to be > >> considered a string. > > >> John > > > Exactly so. ?The requirement of the receiving program, which is out of > > my control, is that all strings be quoted but a None in a numeric > > field result in the ,, output rather than "". ?Excel quotes strings > > conditionally, which doesn't do what is needed in this case. ?For > > QUOTE_NONNUMERIC to quote None values makes some sense, but it gets in > > the way of representing missing values in a numeric field. ?It would > > be nice to have a choice here in the dialects. > > > I thought of replacing the None values with float(nan), since that has > > a numeric type, but unfortunately that results in writing the string > > (unquoted) nan for the value. ?So the sentinel approach seems to be > > the best I can do. > > How about: > > >>> import csv, sys > >>> class N(int): > > ... ? ? def __str__(self): return "" > ...>>> pseudo_none = N() > >>> w = csv.writer(sys.stdout, quoting=csv.QUOTE_NONNUMERIC) > >>> w.writerow([1, "foo", pseudo_none, "bar"]) > > 1,"foo",,"bar" > > Peter Clever. Thanks, Jon From forzamila2004 at hotmail.com Sat Aug 29 10:12:54 2009 From: forzamila2004 at hotmail.com (Momen) Date: Sat, 29 Aug 2009 16:12:54 +0200 Subject: the best book for learning python !? Message-ID: -------------- next part -------------- An HTML attachment was scrubbed... URL: From rurpy at yahoo.com Sat Aug 29 10:38:51 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sat, 29 Aug 2009 07:38:51 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: On 08/28/2009 02:12 AM, "Martin v. L?wis" wrote: [I reordered the quotes from your previous post to try and get the responses in a more coherent order. No intent to take anything out of context...] >> Nothing else in the PEP seems remotely relevant. [to providing justification for the behavior of unichr/ord] > > Except for the motivation, of course :-) > > In addition: your original question was "why has this > been changed", to which the answer is "it hasn't". My original interest was two-fold: can unichr/ord be changed to work in a more general and helpful way? That seemed remotely possible until it was pointed out that the two behave consistently, and that behavior is accurately documented. Second, why would they work the way they do when they could have been generalized to cover the full unicode space? An inadequate answer to this would have provided support for the first point but remains interesting to me for the reason below. > Then, the next question is "why is it implemented that > way", to which the answer is "because the PEP says so". Not at all a satisfying answer unless one believes in PEPal infallibility. :-) > Only *then* the question is "what is the rationale for > the PEP specifying things the way it does". The PEP is > relevant so that we can both agree that Python behaves > correctly (in the sense of behaving as specified). But my question had become: why that behavior, when a slightly different behavior would be more general with little apparent downside? To clarify, my interest in the justification for the current behavior is this: I think the best feature of python is not, as commonly stated, the clean syntax, but rather the pretty complete and orthogonal libraries. I often find, after I have written some code, that due to the right library functions being available, it turns out much shorter and concise than I expected. Nevertheless, every now and then, perhaps more than in some other languages (I'm not sure), I run into something that requires what seems to be excessive coding -- I have to do something it seems to me that a library function should have done for me. Sometimes this is because I don't under- stand the reason the library function needs to works the way it does. Other times it is one of the countless trade- off made in the design of the language, which didn't happen to go the way that would have been beneficial to me in a particular coding situation. But sometimes (and it feels too often) it seems as though, zen not withstanding, that purity -- adherence to some philosophic ideal -- beat practicality. unichr/ord seems such as case to me, But I want to be sure I am not missing something. The reasons for the current behavior so far: 1. > What you propose would break the property "unichr(i) always returns > a string of length one, if it returns anything at all". Yes. And i don't see the problem with that. Why is that property more desirable than the non-existent property that a Unicode literal always produces one python character? It would only occur on a narrow build with a unicode character outside of the bmp, exactly the condition a unicode literal can "behave differently" by producing two python characters. 2. > > But there is no reason given [in the PEP] for that behavior. > Sure there is, right above the list: > "Most things will behave identically in the wide and narrow worlds." > That's the reason: scripts should work the same as much as possible > in wide and narrow builds. So what else would work "differently"? My point was that extending unichr/ord to work with all unicode characters reduces differences far more often than it increase them. 3. >> * There is a convention in the Unicode world for >> encoding a 32-bit code point in terms of two >> 16-bit code points. These are known as >> "surrogate pairs". Python's codecs will adopt >> this convention. >> >> Is a distinction made between Python and Python >> codecs with only the latter having any knowledge of >> surrogate pairs? > > No. In the end, the Unicode type represents code units, > not code points, i.e. half surrogates are individually > addressable. Codecs need to adjust to that; in particular > the UTF-8 and the UTF-32 codec in narrow builds, and the > UTF-16 codec in wide builds (which didn't exist when the > PEP was written). OK, so that is not a reason either. 4. I'll speculate a little. If surrogate handling was added to ord/unichr, it would be the top of a slippery slope leading to demands that other string functions also handle surrogates. But this is not true -- there is a strong distinction between ord/unichr and other string methods. The latter deal with strings of multiple characters. But the former deals only with single characters (taking a surrogate pair as a single unicode character.) The behavior of ord/unichr is independent of the other string methods -- if they were changed with regard to surrogate handling they would all have to be changed to maintain consistent behavior. Unichr/str affect only each other. The functions of ord/unichr -- to map characters to numbers -- are fundamental string operations, akin to indexing or extracting a substring. So why would one want to limit them to a subset of characters if not absolutely necessary? To reiterate, I am not advocating for any change. I simply want to understand if there is a good reason for limiting the use of unchr/ord on narrow builds to a subset of the unicode characters that Python otherwise supports. So far, it seems not and that unichr/ord is a poster child for "purity beats practicality". From tw55413 at gmail.com Sat Aug 29 10:49:22 2009 From: tw55413 at gmail.com (erikj) Date: Sat, 29 Aug 2009 07:49:22 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <7f519c34-2d6e-4fff-9489-dae43c6b2df1@r42g2000yqj.googlegroups.com> <6b961048-782a-428c-9c0a-4fb17e87b57f@s13g2000yql.googlegroups.com> Message-ID: On Aug 27, 2:31?pm, Neuruss wrote: > On 26 ago, 05:29, erikj wrote: > > > > > Hi, > > > You could have a look at Camelot, to see if it fits > > your needs :http://www.conceptive.be/projects/camelot/ > > > it was developed with cross platform business apps in > > mind. ?when developing Camelot, we tried to build it using > > wxWidgets first (because of the licensing at that time), > > but it turned out that developing with QT proved to be > > much more straightforward. ?QT is documented very well > > and you seldom encounter 'strange' issues that cost hours > > of time to pinpoint and fix. > > > the datagrid was developed to be able to handle millions > > of database records without glitches and is flexible thanks > > to QT's model-view-delegate framework. > > > we do print barcodes with this app (even directly to > > zebra printers) > > > if you have questions regarding Camelot, please feel free > > to post on our mailing list :http://groups.google.com/group/project-camelot > > > Regards, > > > Erik > > > On Aug 24, 2:08?pm, Gilles Ganault wrote: > > > > Hello > > > > ? ? ? ? I was wondering if some people in this ng use Python and someGUI > > > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > > > applications, and if yes, what it's like, the pros and cons, etc. > > > > I'm especially concerned about the lack of controls, the lack of > > > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > > > linked to how to update users' PC remotely when I build a new version > > > using eg. Py2exe. > > > > I need controls for business apps like access to databases, good data > > > grid, printing reports (with or without barcodes), etc. > > > > Thank you. > > Looks interesting, but I wonder if I can use Camelot without its ORM. > I feel that ORMs make easy things easier, but complex things much > harder... > Can I use it with plain old sql? > > Luis Yes and no :) It uses sqlalchemy as it's orm, which is quite flexible and allows the use of plain old sql, but you still have to map the result to objects for the GUI to to handle them. You are right that the ORM makes easy things easier, eg. what we do a lot is to create our core model using the ORM, and then create the different summaries directly as views in the database (since these are usually very complex queries, and those tend to be easier to write/debug in plain old sql). Then we use the ORM again to map those views back to objects and have them visualized. Cheers, Erik From timothy.tsvetkov at gmail.com Sat Aug 29 10:52:03 2009 From: timothy.tsvetkov at gmail.com (Timothy N. Tsvetkov) Date: Sat, 29 Aug 2009 07:52:03 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: On Aug 29, 4:26?am, qwe rty wrote: > On Aug 29, 3:14?am, Tim Chase wrote: > > > > > > > >> what else can NOT be done in python? what are the limitations of the > > >> language? > > > > I understand there's a little trouble getting Python to prove > > > that P=NP ?You'll also find that it only comes close to solving > > > the unrestricted three-body problem and the Traveling Salesman > > > problem is still limited to fallible heuristics and searching the > > > entire solution set in better than O(2**n) time. > > > I forgot about solving the Spam problem entirely. ?And answering > > poorly worded/thought-out questions on the internet... > > > I've also been sorely disappointed by Python's ability to make a > > good chocolate cream silk pie. > > > -tkc > > if you don't know the answer please don't reply If you want to ask a silly question don't ask it. From deets at nospam.web.de Sat Aug 29 11:22:29 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Aug 2009 17:22:29 +0200 Subject: Combining C and Python programs In-Reply-To: References: Message-ID: <7fsvdlF2lo7cgU1@mid.uni-berlin.de> Sortie schrieb: > I want to write a program that will use ode for the physics > simulation, whose python bindings are outdated. So I'm writing > the physics engine in C and want to write the drawing code in > Python. What will be the best way of making those two programs > work together? THe physics engine won't have to run concurrently > with the drawing code. It will only return some position data so > they can be drawn. How about you update the ODE-bindings? They shouldn't be hard to enhance to cover the latest features. Diez From rtomek at ceti.com.pl Sat Aug 29 11:51:30 2009 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Sat, 29 Aug 2009 17:51:30 +0200 Subject: What python can NOT do? In-Reply-To: References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: On Sat, 29 Aug 2009, Timothy N. Tsvetkov wrote: > On Aug 29, 4:26?am, qwe rty wrote: > > On Aug 29, 3:14?am, Tim Chase wrote: > > > > > >> what else can NOT be done in python? what are the limitations of the > > > >> language? > > [...] > > > I forgot about solving the Spam problem entirely. ?And answering > > > poorly worded/thought-out questions on the internet... > > > > > I've also been sorely disappointed by Python's ability to make a > > > good chocolate cream silk pie. > > > > > -tkc > > > > if you don't know the answer please don't reply > > If you want to ask a silly question don't ask it. The question the OP asked was not silly. Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From gherron at islandtraining.com Sat Aug 29 12:12:29 2009 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 29 Aug 2009 09:12:29 -0700 Subject: Is behavior of += intentional for int? In-Reply-To: References: Message-ID: <4A99536D.6080002@islandtraining.com> zaur wrote: > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin > Type "copyright", "credits" or "license()" for more information. > >>>> a=1 >>>> x=[a] >>>> id(a)==id(x[0]) >>>> > True > >>>> a+=1 >>>> a >>>> > 2 > >>>> x[0] >>>> > 1 > > I thought that += should only change the value of the int object. But > += create new. > Is this intentional? > > You don't need the (slight) complexity of += to see this. Straight assignment shows the same behavior. Try this: a=1 print id(a) a=2 print id(a) The different results from the two prints happens because Python stores integers 1 and 2 in different locations and the assignments causes a to refer to one and then the other. Gary Herron -------------- next part -------------- An HTML attachment was scrubbed... URL: From vicente.soler at gmail.com Sat Aug 29 12:25:48 2009 From: vicente.soler at gmail.com (vsoler) Date: Sat, 29 Aug 2009 09:25:48 -0700 (PDT) Subject: Colors on IDLE References: <59922ab5-f8c9-429f-b1ea-9b1418aa6b71@t13g2000yqt.googlegroups.com> <8d5d283f-b0bd-4e16-97c7-d2de1a148cae@l35g2000vba.googlegroups.com> <311ec593-4050-4a6a-adbd-2325698a4b61@h30g2000vbr.googlegroups.com> Message-ID: On Aug 29, 1:34?pm, Thorsten Kampe wrote: > * vsoler (Sat, 29 Aug 2009 04:01:46 -0700 (PDT)) > > > On Aug 29, 1:27?am, r wrote: > > > Have you tried saving the files as MYScriptName.py? notice the py > > > extension, very important ;) > > > That was it!!! > > > I see the colors again. Thank you. > > I suggest you start using familiar technical terms. Like "syntax > highlighting" instead of "see colours". That would increase the number > of useful answers you get - at least it will stop people from thinking > you talk about controlled substances. > > Thorsten I'll keep it in mind for next time. Thank you Vicente Soler From gd_usenet at spamfence.net Sat Aug 29 12:25:54 2009 From: gd_usenet at spamfence.net (=?UTF-8?Q?G=C3=BCnther?= Dietrich) Date: Sat, 29 Aug 2009 18:25:54 +0200 Subject: Is behavior of += intentional for int? References: Message-ID: Paul McGuire wrote: >What exactly are you trying to do? I think, he wants to kind of dereference the list element. So that he can write >>> a += 1 instead of >>> long_name_of_a_list_which_contains_data[mnemonic_pointer_name] += 1 Regards, G?nther From cryzed at googlemail.com Sat Aug 29 12:28:24 2009 From: cryzed at googlemail.com (cryzed) Date: Sat, 29 Aug 2009 18:28:24 +0200 Subject: AutoIt/Autohotkey Python library for Linux Message-ID: Hey, maybe some of you are familiar with the tools "AutoIt" () and "Autohotkey" () for Windows - I was wondering if you knew about Python libraries which provide similiar functionality for Python programs under Linux. That said, those libraries would have to rely on X11 internally to provide their functionality. Also, yes, I know that there are X11-bindings for Python - but I honestly think that they aren't remotely useable and they are also incomplete. It would be great if you guys had some tips for me. From rt8396 at gmail.com Sat Aug 29 13:17:38 2009 From: rt8396 at gmail.com (r) Date: Sat, 29 Aug 2009 10:17:38 -0700 (PDT) Subject: Transforming a str to an operator References: <87skfcblo3.fsf@benfinney.id.au> <91126ac3-e7fe-4b7a-a37d-d1e60beaa278@w41g2000yqb.googlegroups.com> Message-ID: <38877ac9-cc2d-4293-b682-cfaf5cd3c861@o13g2000vbl.googlegroups.com> On Aug 28, 8:43?pm, Anny Mous wrote: > It isn't irrational to have a healthy caution towards eval. Ignorance is never an excuse for stupidity. No caution is needed if you know how to properly use eval. You can't shoot yourself in the foot without first pulling the trigger. > Apart from the security issues, running code in eval takes a massive > performance hit. Its about ten times slower to run eval("x+1") than to run > x+1 directly. And the point is...? eval is only for corner cases. Nobody is suggesting he eval entire scripts. Performance is the last of my worries. Optimizations can come later. First understand the problem at hand, code up a working solution, then tweak and optimize the code to perfection. > What makes you think that learning to program well in Python is a throw-away > exercise of no useful purpose? I'm sure the code itself will be thrown away > and forgotten, but it has a very important purpose: for the OP to learn > good programming skills. Looks like you want him to learn bad skills, then > spend the rest of his life trying to unlearn them. No i want him to use eval properly .If you think eval is scary well thats just your opinion. I showed the OP how to successfully pass the arguments into eval the way he was unsuccesfully struggling to pass them. Ben's approach is the professional/proper way to handle such input in the real world (there are other ways too), however the OP also must know that you don't *have* to go by the book all the time (python is not Java ya know?). > > but serves the very > > useful purpose now of establishing an IO between the student and > > Python interpretor. I'll bet most your example (albeit a good example) > > flew miles above his head into la-la land. > > How insulting. Is there anything that gave you the impression the OP was > stupid? Please quote the line from my post were i called the OP stupid or used otherwise derogatory comments? And if you can i'll buy you a beer. Obviously anyone who shows example code as the OP did is a noob and needs proper training on how to use it and there is nothing wrong with that. We have all been there, remember? > > The OP has plenty of time to learn about malicious input and > > protecting against it, right now the fundamentals are well... > > fundamental :) > > When would you recommend he learns? When his web app is hijacked by > gangsters in Russia and the personal details and financial records of fifty > thousand people stolen? Protecting against malicious input *IS* > fundamental. If the OP uses eval without inderstanding it and then shoots himself in the foot, well then i can't think of a better learning experience for him. I'll bet the next time he will read the docs first or ask on this list before he goes off on a turkey hunt ;). Fear is a product of ignorance. Educate yourself and your irrational fears shall bother you no more. From cryzed at googlemail.com Sat Aug 29 13:37:56 2009 From: cryzed at googlemail.com (cryzed) Date: Sat, 29 Aug 2009 19:37:56 +0200 Subject: AutoIt/Autohotkey-like library for Linux Message-ID: Hey, maybe some of you are familiar with the tools "AutoIt" (http://www.autoitscript.com/autoit3/) and "Autohotkey" (http://www.autohotkey.com/) for Windows - I was wondering if you knew about Python libraries which provide similiar functionality for Python programs under Linux. That said, those libraries would have to rely on X11 internally to provide their functionality. Also, yes, I know that there are X11-bindings for Python - but I honestly think that they aren't remotely useable and they are also incomplete. It would be great if you guys had some tips for me. From python at mrabarnett.plus.com Sat Aug 29 13:39:11 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 29 Aug 2009 18:39:11 +0100 Subject: Transforming a str to an operator In-Reply-To: <38877ac9-cc2d-4293-b682-cfaf5cd3c861@o13g2000vbl.googlegroups.com> References: <87skfcblo3.fsf@benfinney.id.au> <91126ac3-e7fe-4b7a-a37d-d1e60beaa278@w41g2000yqb.googlegroups.com> <38877ac9-cc2d-4293-b682-cfaf5cd3c861@o13g2000vbl.googlegroups.com> Message-ID: <4A9967BF.6000700@mrabarnett.plus.com> r wrote: > On Aug 28, 8:43 pm, Anny Mous wrote: >> It isn't irrational to have a healthy caution towards eval. > > Ignorance is never an excuse for stupidity. No caution is needed if > you know how to properly use eval. You can't shoot yourself in the > foot without first pulling the trigger. > >> Apart from the security issues, running code in eval takes a massive >> performance hit. Its about ten times slower to run eval("x+1") than to run >> x+1 directly. > > And the point is...? > eval is only for corner cases. Nobody is suggesting he eval entire > scripts. Performance is the last of my worries. Optimizations can come > later. First understand the problem at hand, code up a working > solution, then tweak and optimize the code to perfection. > >> What makes you think that learning to program well in Python is a throw-away >> exercise of no useful purpose? I'm sure the code itself will be thrown away >> and forgotten, but it has a very important purpose: for the OP to learn >> good programming skills. Looks like you want him to learn bad skills, then >> spend the rest of his life trying to unlearn them. > > No i want him to use eval properly .If you think eval is scary well > thats just your opinion. I showed the OP how to successfully pass the > arguments into eval the way he was unsuccesfully struggling to pass > them. Ben's approach is the professional/proper way to handle such > input in the real world (there are other ways too), however the OP > also must know that you don't *have* to go by the book all the time > (python is not Java ya know?). > >>> but serves the very >>> useful purpose now of establishing an IO between the student and >>> Python interpretor. I'll bet most your example (albeit a good example) >>> flew miles above his head into la-la land. >> How insulting. Is there anything that gave you the impression the OP was >> stupid? > > Please quote the line from my post were i called the OP stupid or used > otherwise derogatory comments? And if you can i'll buy you a beer. > Obviously anyone who shows example code as the OP did is a noob and > needs proper training on how to use it and there is nothing wrong with > that. We have all been there, remember? > >>> The OP has plenty of time to learn about malicious input and >>> protecting against it, right now the fundamentals are well... >>> fundamental :) >> When would you recommend he learns? When his web app is hijacked by >> gangsters in Russia and the personal details and financial records of fifty >> thousand people stolen? Protecting against malicious input *IS* >> fundamental. > > If the OP uses eval without inderstanding it and then shoots himself > in the foot, well then i can't think of a better learning experience > for him. I'll bet the next time he will read the docs first or ask on > this list before he goes off on a turkey hunt ;). > > Fear is a product of ignorance. Educate yourself and your irrational > fears shall bother you no more. > I think it's a good idea to warn the OP about the dangers of eval. If he still wants to use it, then that's his choice (and his problem). From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 14:06:34 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 18:06:34 GMT Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: <0022f1a7$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 07:38:51 -0700, rurpy wrote: > > Then, the next question is "why is it implemented that way", to which > > the answer is "because the PEP says so". > > Not at all a satisfying answer unless one believes in PEPal > infallibility. :-) Not at all. You don't have to believe that PEPs are infallible to accept the answer, you just have to understand that major changes to Python aren't made arbitrarily, they have to go through a PEP first. Even Guido himself has to write a PEP before making any major changes to the language. But PEPs aren't infallible, they can be challenged, rejected, withdrawn or made obsolete by new PEPs. > The reasons for the current behavior so far: > > 1. >> What you propose would break the property "unichr(i) always returns a >> string of length one, if it returns anything at all". > > Yes. And i don't see the problem with that. Why is that property more > desirable than the non-existent property that a Unicode literal always > produces one python character? What do you mean? Unicode literals don't always produce one character, e.g. u'abcd' is a Unicode literal with four characters. I think it's fairly self-evident that a function called uniCHR [emphasis added] should return a single character (technically a single code point). But even if you can come up with a reason for unichr() to return two or more characters, this would break code that relies on the documented promise that the length of the output of unichr() is always one. > It would only occur on a narrow build > with a unicode character outside of the bmp, exactly the condition a > unicode literal can "behave differently" by producing two python > characters. > 2. >> > But there is no reason given [in the PEP] for that behavior. >> Sure there is, right above the list: >> "Most things will behave identically in the wide and narrow worlds." >> That's the reason: scripts should work the same as much as possible in >> wide and narrow builds. > > So what else would work "differently"? unichr(n) sometimes would return one character and sometimes two; ord(c) would sometimes accept two characters and sometimes raise an exception. That's a fairly major difference. > My point was that extending > unichr/ord to work with all unicode characters reduces differences far > more often than it increase them. I don't see that at all. What differences do you think it would reduce? > 3. >>> * There is a convention in the Unicode world for >>> encoding a 32-bit code point in terms of two 16-bit code >>> points. These are known as "surrogate pairs". Python's codecs >>> will adopt this convention. >>> >>> Is a distinction made between Python and Python codecs with only the >>> latter having any knowledge of surrogate pairs? >> >> No. In the end, the Unicode type represents code units, not code >> points, i.e. half surrogates are individually addressable. Codecs need >> to adjust to that; in particular the UTF-8 and the UTF-32 codec in >> narrow builds, and the UTF-16 codec in wide builds (which didn't exist >> when the PEP was written). > > OK, so that is not a reason either. I think it is a very important reason. Python supports code points, so it has to support surrogate codes individually. Python can't tell if the pair of code points u'\ud800\udc40' represents the single character \U00010040 or a pair of code points \ud800 and \udc40. > 4. > I'll speculate a little. > If surrogate handling was added to ord/unichr, it would be the top of a > slippery slope leading to demands that other string functions also > handle surrogates. > > But this is not true -- there is a strong distinction between ord/unichr > and other string methods. The latter deal with strings of multiple > characters. But the former deals only with single characters (taking a > surrogate pair as a single unicode character.) Strictly speaking, unichr() deals with code points, not characters, although the distinction is very fine. >>> c = unichr(56384) >>> len(c) 1 >>> import unicodedata >>> unicodedata.category(c) 'Cs' Cs is the general category for "Other, Surrogate", so \udc40 is not strictly speaking a character. Nevertheless, Python treats it as one. > To reiterate, I am not advocating for any change. I simply want to > understand if there is a good reason for limiting the use of unchr/ord > on narrow builds to a subset of the unicode characters that Python > otherwise supports. So far, it seems not and that unichr/ord is a > poster child for "purity beats practicality". On the contrary, it seems pretty impractical to me for ord() to sometimes successfully accept strings of length two and sometimes to raise an exception. I would much rather see a pair of new functions, wideord() and widechr() used for converting between surrogate pairs and numbers. -- Steven From ivanko.rus at gmail.com Sat Aug 29 14:08:56 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 18:08:56 +0000 Subject: IDE for Python In-Reply-To: <7aa29e790908290214ode909c8od898918e86759daf@mail.gmail.com> Message-ID: <000e0cd20f80b36a6104724bb134@google.com> 29.08.2009 4:14 ???????????? "Thangappan.M" ???????: > Dear all, > Please suggest some good IDE for python.I am working in linux platform. > -- > Regards, > Thangappan.M You can use Eclipse + PyDev or Emacs+PythonMode . Also there are Anjuta and Code:Blocks, but they are designed mainly for C++ (but still can be used). -------------- next part -------------- An HTML attachment was scrubbed... URL: From szport at gmail.com Sat Aug 29 14:11:43 2009 From: szport at gmail.com (zaur) Date: Sat, 29 Aug 2009 11:11:43 -0700 (PDT) Subject: Is behavior of += intentional for int? References: Message-ID: On 29 ???, 20:25, "G?nther Dietrich" wrote: > Paul McGuire wrote: > >What exactly are you trying to do? > > I think, he wants to kind of dereference the list element. So that he > can write > > >>> a += 1 > > instead of > > >>> long_name_of_a_list_which_contains_data[mnemonic_pointer_name] += 1 > > Regards, > > G?nther That's right. I thought that int as object will stay the same object after += but with another integer value. My intuition said me that int object which represent integer value should behave this way. But by design python's integer behave differently. I fond that NumPy's 1-d types behaves as objects with mutable values. >>> from numpy import * >>> a=array([1]) >>> id(a) 10912544 >>> a += 1 >>> id(a) 10912544 >>> a array([2]) From rtomek at ceti.com.pl Sat Aug 29 14:18:07 2009 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Sat, 29 Aug 2009 20:18:07 +0200 Subject: What python can NOT do? In-Reply-To: <00223e3f$0$2930$c3e8da3@news.astraweb.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <00223e3f$0$2930$c3e8da3@news.astraweb.com> Message-ID: On Sat, 29 Aug 2009, Steven D'Aprano wrote: > On Sat, 29 Aug 2009 05:37:34 +0200, Tomasz Rola wrote: > > > My private list of > > things that when implemented in Python would be ugly to the point of > > calling it difficult: > > > > 1. AMB operator - my very favourite. In one sentence, either language > > allows one to do it easily or one would not want to do it (in an ugly > > way). > > > > http://www.randomhacks.net/articles/2005/10/11/amb-operator > > > Fascinating, but I don't exactly see how that's actually *useful*. It > strikes me of combining all the benefits of COME FROM with the potential > performance of Bogosort, but maybe I'm being harsh. Usefullness is totally different thing, I agree. However, amb could still find some following. I guess it is more about personal taste and willingness to look for better idioms in programming. I can imagine when they introduced for and while loops, people were pointing at conditional goto as more practical (I think every control structure can be modeled with it). Id doesn't mean amb is better idiom, but it is something that could be tried - or not. One could write like this: (partially stol####copied from the above link) a = amb 1, 2, 3 b = amb 4, 5, 6 c = amb 7, 8, 9 if a*b + c != 27 : amb print a,b,c or one could write like this: for a in [1, 2, 3]: for b in [4, 5, 6]: for c in [7, 8, 9]: if a*b+c == 27 : print a,b,c break Which one would I choose? Well, amb of course. I consider it to be more readable which is, for me at least, useful. Now, try to imagine the same with ten variables. And longer lists. And some problems do not fit well into numpy (they could be non-numerical in nature). > On the other hand, it sounds rather like Prolog-like declarative > programming. I fear that, like Prolog, it risks massive performance > degradation if you don't apply the constraints in the right order. Of course, but this can be optimised. Either by hand or by a good compiler (whatever this means). Performance degradation is connected with abuse of every other programming technique, too. And besides, I believe one would sometimes trade performance for the ability to clearly express the idea behind the algorithm. Just as is the case with choosing Python rather than Java. For things I use Python for, I wouldn't use Java or C. Even though C is one of my beloved languages. If I ever used Prolog for anything, I wouldn't like to rewrite it in C or Python. I mean, languages should (in theory) be chosen and used with some consideration. > > 2. Changing the language from the inside. > > > > Everybody can change the interpreter, right? But how about doing some > > bigger, maybe even fundamental change to the language by means offered > > by the language itself? > > Like Forth. You need it in Forth, because it has a very sparse set of > language features, and everything is bootstrapped from a small set of > commands, so the ability to re-define the language as you go is (1) > necessary and (2) free. It also leads to writing code in an incredibly expressive manner. I've never done anything big in Forth. I only had a two weeks long exposure to it in times, when you loaded such things from casette recorder ;-/... But from time to time I find some interesting pieces, like a disk driver whose source would fit into a comment of one Python function :-). > But for Python, I don't know... it sounds cool, but in practice? It > sounds like the sort of thing that allows programmers to spend three > hours writing a new control structure which will save them three minutes. It really is not so. Writing something for three hours and using it only once sounds more like programming excercise, less like real life work. To write a function I need to know at least two places in my code where it would be used (well, I am oversimplifying, ok? sometimes one place is sufficient). I think reasonable people would judge language extension by similar criteria. They would possibly stay away from this as long as possible (I have such possibility from some time but I just don't touch macros, which by my own words makes me reasonable, wow :-)... or a coward...). > And of course, for all but the tiniest, one-man-band applications, > readability is important. Sure, you've created a gee-whizz control > structure which combines try, while and if into one keyword, and it > automatically does logging and threading, fantastic. But how will anyone > else be able to maintain it when you're gone? This is comparable to me creating a gee-whizz function library and using it. I cannot see a problem as long as I document (with use cases, tests etc). There is something better in this idea. Suppose I would have invented a better control structure and posted the source code here? Some would have found it amusing, others would have tried it, posted their comments, leading to improvements and further spreading. Finally - who knows - it could have found a way in to a standard. And even if not, it should still remain as a loadable extension for quite some time. > The ability to change the language is one step into a tarpit, where > everything is possible but nothing is easy, and where you spend all your > time writing language features and none of your time building the useful > functionality you actually want. I don't think this is much different from the situation when I would write string processing library (that would be used further in the program) rather than "building useful functionality" - which would be what, programming buttons :-)? For me, it looks like language elements should not be protected from my tinkering. Think about operators in Python. I can define my own "+" for some objects, which has been decided on Python's upper levels :-). In fact, as far as I remember, I have never used this feature. But knowing there is some possibility, space to grow, is good. > It sounds like something you want in a > language you use for designing languages, rather than writing > applications. Yes indeed, Lisps have been used to prototype some other languages. However, I am not sure if the boundary between a language and an app could be strictly defined. If adding new words to the language dictionary by writing a library is considered a good programming practice, then why adding a new keyword and syntax should not be considered as such? Ok, since I myself have written above I didn't use those features from very upper shelve, one could ask what is my point. The point is, if I wanted to, I could have used them. Click and go. Do anything that by my own judgement is good for code progress rather than murmuring about my code being less elegant and expressive that it could have been. I mean, if my job was beheading people, I would rather do it with sharp axe because it is more expressive and elegant than sawing their necks with piece of wood. And besides the job is better done and less boring for parties involved. So, my going after elegance is not so much whimsical, at least not from my point of view. I believe there is something more to it than just esthetics. Just in case - I am not voting for changes in Python. Quite far from this. Only expressing my opinions etc. As I have already mentioned in some other posts of mine, Python is good for few things I do and for other things I use other tools. That's it. Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From bouncyinc at gmail.com Sat Aug 29 14:38:20 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 29 Aug 2009 12:38:20 -0600 Subject: What python can NOT do? In-Reply-To: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: Theoretically a microkernel could be used to do the stuff python directly couldn't do and the rest could be done once an interpreter was loaded in theory. On Fri, Aug 28, 2009 at 4:37 PM, qwe rty wrote: > i know that an interpreted language like python can't be used to make > an operating system or system drivers. > > what else can NOT be done in python? what are the limitations of the > language? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From philip at semanchuk.com Sat Aug 29 14:46:15 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Sat, 29 Aug 2009 14:46:15 -0400 Subject: Combining C and Python programs In-Reply-To: References: Message-ID: <0BBCF0D2-789B-4FD2-B5E6-AE81C07A6273@semanchuk.com> On Aug 29, 2009, at 3:54 AM, Sortie wrote: > I want to write a program that will use ode for the physics > simulation, whose python bindings are outdated. So I'm writing > the physics engine in C and want to write the drawing code in > Python. What will be the best way of making those two programs > work together? THe physics engine won't have to run concurrently > with the drawing code. It will only return some position data so > they can be drawn. I'd look at ctypes first, as Hendrik suggested. It's pretty simple and part of the standard library. If that doesn't work for you for some reason and you're willing to use something outside of the standard library, you might find Cython useful. Good luck Philip From diogo.neves at gmail.com Sat Aug 29 14:54:09 2009 From: diogo.neves at gmail.com (Diogo Neves) Date: Sat, 29 Aug 2009 19:54:09 +0100 Subject: IDE for Python In-Reply-To: <000e0cd20f80b36a6104724bb134@google.com> References: <7aa29e790908290214ode909c8od898918e86759daf@mail.gmail.com> <000e0cd20f80b36a6104724bb134@google.com> Message-ID: Is IDLE (the editor that comes with Python) good? I'm just starting now, but it looks ok. 2009/8/29 > 29.08.2009 4:14 ???????????? "Thangappan.M" > ???????: > > Dear all, > > > > > > Please suggest some good IDE for python.I am working in linux > platform. > > > > -- > > Regards, > > Thangappan.M > > > > You can use Eclipse + PyDev or Emacs+PythonMode . Also there are Anjuta and > Code:Blocks, but they are designed mainly for C++ (but still can be used). > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 15:03:23 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 19:03:23 GMT Subject: Is behavior of += intentional for int? References: Message-ID: <0022fef9$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: > I thought that int as object will stay the same object after += but with > another integer value. My intuition said me that int object which > represent integer value should behave this way. If it did, then you would have this behaviour: >>> n = 3 # bind the name n to the object 3 >>> saved_id = id(n) # get the id of the object >>> n += 1 # add one to the object 3 >>> assert n == 4 # confirm that it has value four >>> assert id(n) == saved_id # confirm that it is the same object >>> m = 3 # bind the name m to the object 3 >>> print m + 1 # but object 3 has been modified 5 This would be pretty disturbing behaviour, and anything but intuitive. Fortunately, Python avoids this behaviour by making ints immutable. You can't change the object 3 to have any other value, it will always have value three, and consequently n+=1 assigns a new object to n. -- Steven From nobody at nowhere.com Sat Aug 29 15:09:12 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 29 Aug 2009 20:09:12 +0100 Subject: (Simple?) Unicode Question References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> <002269cb$0$2930$c3e8da3@news.astraweb.com> Message-ID: On Sat, 29 Aug 2009 08:26:54 +0000, Steven D'Aprano wrote: > Python only needs to know when you convert the text to or from bytes. I > can do this: > >>>> s = "hello" >>>> t = "world" >>>> print(' '.join([s, t])) > hello world > > and not need to care anything about encodings. > > So long as your terminal has a sensible encoding, and you have a good > quality font, you should be able to print any string you can create. UTF-8 isn't a particularly sensible encoding for terminals. And "Unicode font" is an oxymoron. You can merge a whole bunch of fonts together and stuff them into a TTF file; that doesn't make them "a font", though. >>> I may be wrong, but I believe that's part of the idea between >>> separation of string and bytes types in Python 3.x. I believe, if you >>> are using Python 3.x, you don't need the character encoding mumbo jumbo >>> at all ;-) >> >> Nothing has changed in that regard. You still need to decode and encode >> text and for that you have to know the encoding. > > You only need to worry about encoding when you convert from bytes to > text, and visa versa. Admittedly, the most common time you need to do > that is when reading input from files, but if all your text strings are > generated by Python, and not output anywhere, you shouldn't need to care > about encodings. Why would you generate text strings and not output them anywhere? The main advantage of using Unicode internally is that you can associate encodings with the specific points where data needs to be converted to/from bytes, rather than having to carry the encoding details around the program. From nobody at nowhere.com Sat Aug 29 15:19:36 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 29 Aug 2009 20:19:36 +0100 Subject: Query screen resolution? References: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> <409bf880-4e4b-48f4-8cfc-ecacf262d782@v15g2000prn.googlegroups.com> Message-ID: On Fri, 28 Aug 2009 20:15:57 -0700, Warpcat wrote: >> Your question is based upon the notion that "the screen" is a meaningful >> concept. Once you move away from Windows (and systems which intentionally >> try to be like Windows), that's no longer true. > > Good points. Always something I haven't thought of. Ok so... let's > *presume* the user has a measurable screen on win\mac\linux\etc since > on any other OS they wouldn't be running the app.... If it's a GUI app, you ask the GUI toolkit which you're using. [And if it isn't a GUI app, why would the screen resolution be relevant?] From clp2 at rebertia.com Sat Aug 29 15:31:39 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 29 Aug 2009 12:31:39 -0700 Subject: how to edit .wsgi file extebtions with IDLE on windows In-Reply-To: <58a021ce-3058-483d-b429-6ba4855807ac@o36g2000vbl.googlegroups.com> References: <58a021ce-3058-483d-b429-6ba4855807ac@o36g2000vbl.googlegroups.com> Message-ID: <50697b2c0908291231l75e91893lffe18bc9d46f617a@mail.gmail.com> On Sat, Aug 29, 2009 at 5:40 AM, gert wrote: > On Aug 29, 6:43?am, "Gabriel Genellina" > wrote: >> En Fri, 28 Aug 2009 15:31:31 -0300, gert escribi?: >> >> > I can't figure out how to enable the .py shell and syntax highlighting >> > for .wsgi file extensions using IDLE for windows ? >> >> That's a Windows question, not a Python one. You have to associate the >> .wsgi extension with the Python.File file type (the one used for .py >> files): >> >> D:\USERDATA\Gabriel>assoc .py >> .py=Python.File >> >> D:\USERDATA\Gabriel>assoc .wsgi=Python.File >> .wsgi=Python.File >> > > Thanks that does make it open exactly like a .py file, expect that > there is no syntax highlighting. Don't know if this is also a windows > issue or a IDLE issue ? That's an IDLE issue; it only highlights files with .py (and possibly .pyw) extensions. Cheers, Chris -- http://blog.rebertia.com From aahz at pythoncraft.com Sat Aug 29 15:33:45 2009 From: aahz at pythoncraft.com (Aahz) Date: 29 Aug 2009 12:33:45 -0700 Subject: Select column from a list References: <25185508.post@talk.nabble.com> <9fdb569a0908280228g59038ba1u30d6d5ef9d6a80ca@mail.gmail.com> Message-ID: In article , Anthra Norell wrote: >Vlastimil Brom wrote: >> 2009/8/28 hoffik : >>> >>> I'm quite new in Python and I have one question. I have a 2D matrix of >>> values stored in list (3 columns, many rows). I wonder if I can select one >>> column without having to go through the list with 'for' command. >> >> I guess, it won't be possible without an explicit or implicit loop; >> you may try: >> >>>>> from operator import itemgetter >>>>> nested_list = [[1, 2, 3], [10, 20, 30], [100, 200, 300]] >>>>> map(itemgetter(1), nested_list) >> >> [2, 20, 200] > >How about rotating the list with zip? > >>> zip (*nested_list)[1] >(2, 20, 200) That's an implicit loop, plus it consumes an O(M*N) chunk of memory for the intermediate list. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From vlastimil.brom at gmail.com Sat Aug 29 15:43:58 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 29 Aug 2009 21:43:58 +0200 Subject: break unichr instead of fix ord? In-Reply-To: References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: <9fdb569a0908291243l9c33dbeu61debb104d2c13fc@mail.gmail.com> 2009/8/29 : > On 08/28/2009 02:12 AM, "Martin v. L?wis" wrote: > > So far, it seems not and that unichr/ord > is a poster child for "purity beats practicality". > -- > http://mail.python.org/mailman/listinfo/python-list > As Mark Tolonen pointed out earlier in this thread, in Python 3 the practicality apparently beat purity in this aspect: Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> goth_urus_1 = '\U0001033f' >>> list(goth_urus_1) ['\ud800', '\udf3f'] >>> len(goth_urus_1) 2 >>> ord(goth_urus_1) 66367 >>> goth_urus_2 = chr(66367) >>> len(goth_urus_2) 2 >>> import unicodedata >>> unicodedata.name(goth_urus_1) 'GOTHIC LETTER URUS' >>> goth_urus_3 = unicodedata.lookup("GOTHIC LETTER URUS") >>> goth_urus_4 = "\N{GOTHIC LETTER URUS}" >>> goth_urus_1 == goth_urus_2 == goth_urus_3 == goth_urus_4 True >>> As for the behaviour in python 2.x, it's probably good enough, that the surrogates aren't prohibited and the eventually needed behaviour can be easily added via custom functions. vbr From nagle at animats.com Sat Aug 29 15:46:52 2009 From: nagle at animats.com (John Nagle) Date: Sat, 29 Aug 2009 12:46:52 -0700 Subject: What python can NOT do? In-Reply-To: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <4a998465$0$1637$742ec2ed@news.sonic.net> qwe rty wrote: > i know that an interpreted language like python can't be used to make > an operating system or system drivers. > > what else can NOT be done in python? what are the limitations of the > language? Speed, basically. CPython is on the slow side. This is not inherent in the language; it's an implementation problem. The Shed Skin compiler is approaching C speeds, but you have to accept some modest restrictions on run-time dynamism. Also, CPython does not use multiple processors well. In fact, multiple cores make CPython performance worse. (There's a long analysis of this that's been discussed here recently.) Personally, I consider Python to be a good language held back by too-close ties to a naive interpreter implementation and the lack of a formal standard for the language. John Nagle From ivanko.rus at gmail.com Sat Aug 29 16:08:51 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 20:08:51 +0000 Subject: Python Noob - gui module, book, annoying questions In-Reply-To: <92cc4ca1-0e0d-4355-8d9a-b4928390e619@q35g2000vbi.googlegroups.com> Message-ID: <000e0cd117da963eed04724d5ea6@google.com> 29.08.2009 2:20 ???????????? Pherdnut ???????: > I want to write cross-platform stuff. Any opinions on the best GUI > module for that? There are many options for this. For example GTK+ (pygtk), tkinter, QT. GTK+ is a little bit complicated, but you can use glade to make the GUIs. Tkinter is built-in and pretty simple (although not so feature-rich). QT - ok, I haven't used it. Personally I prefer GTK+ (using pygtk module) -------------- next part -------------- An HTML attachment was scrubbed... URL: From webcokies at yahoo.com Sat Aug 29 16:13:12 2009 From: webcokies at yahoo.com (Joni Lee) Date: Sat, 29 Aug 2009 13:13:12 -0700 (PDT) Subject: a popen command line question Message-ID: <964997.10840.qm@web36907.mail.mud.yahoo.com> Hi all, I write a small script status = os.popen('top').readlines() print status It calls the command line "top" and will print out the status. But I have to press the keyboard "q" to quit "top", then the status will be printed, otherwise it just stands by with blank. Question is. Do you know how to give "q" into my python script so that "top" is automatically quit immediately or maybe after 1s (for gathering information) Sorry the question is weird. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gert.cuykens at gmail.com Sat Aug 29 16:14:14 2009 From: gert.cuykens at gmail.com (gert) Date: Sat, 29 Aug 2009 13:14:14 -0700 (PDT) Subject: how to edit .wsgi file extebtions with IDLE on windows References: <58a021ce-3058-483d-b429-6ba4855807ac@o36g2000vbl.googlegroups.com> Message-ID: <00795942-19ae-4d0e-9259-79ae00c34fc5@f10g2000vbf.googlegroups.com> On Aug 29, 9:31?pm, Chris Rebert wrote: > On Sat, Aug 29, 2009 at 5:40 AM, gert wrote: > > On Aug 29, 6:43?am, "Gabriel Genellina" > > wrote: > >> En Fri, 28 Aug 2009 15:31:31 -0300, gert escribi?: > > >> > I can't figure out how to enable the .py shell and syntax highlighting > >> > for .wsgi file extensions using IDLE for windows ? > > >> That's a Windows question, not a Python one. You have to associate the > >> .wsgi extension with the Python.File file type (the one used for .py > >> files): > > >> D:\USERDATA\Gabriel>assoc .py > >> .py=Python.File > > >> D:\USERDATA\Gabriel>assoc .wsgi=Python.File > >> .wsgi=Python.File > > > Thanks that does make it open exactly like a .py file, expect that > > there is no syntax highlighting. Don't know if this is also a windows > > issue or a IDLE issue ? > > That's an IDLE issue; it only highlights files with .py (and possibly > .pyw) extensions. > Any chance they would make a highlight option in the menu ? From danb_83 at yahoo.com Sat Aug 29 16:25:35 2009 From: danb_83 at yahoo.com (AggieDan04) Date: Sat, 29 Aug 2009 13:25:35 -0700 (PDT) Subject: Is behavior of += intentional for int? References: Message-ID: On Aug 29, 8:08?am, Paul McGuire wrote: > On Aug 29, 7:45?am, zaur wrote: > > > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) > > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin > > Type "copyright", "credits" or "license()" for more information.>>> a=1 > > >>> x=[a] > > >>> id(a)==id(x[0]) > > True > > >>> a+=1 > > >>> a > > 2 > > >>> x[0] > > > 1 > > > I thought that += should only change the value of the int object. But > > += create new. > > Is this intentional? > > ints are immutable. ?But your logic works fine with a mutable object, > like a list: Technically, mutability isn't the issue: There's nothing enforcing that a mutable object HAS to have an __iadd__ method that returns the same object. From pogonyshev at gmx.net Sat Aug 29 16:27:03 2009 From: pogonyshev at gmx.net (Paul Pogonyshev) Date: Sat, 29 Aug 2009 23:27:03 +0300 Subject: weak reference callback Message-ID: <200908292327.03416.pogonyshev@gmx.net> Hi, Is weak reference callback called immediately after the referenced object is deleted or at arbitrary point in time after that? I.e. is it possible to see a dead reference before the callback is called? More formally, will this ever raise? callback_called = False def note_deletion (ref): callback_called = True x = ... ref = weakref.ref (x, note_deletion) ... if ref () is None and not callback_called: raise RuntimeError ("reference is dead, yet callback hasn't been called yet") Paul From sergiocharpinel at gmail.com Sat Aug 29 16:27:45 2009 From: sergiocharpinel at gmail.com (Sergio Charpinel Jr.) Date: Sat, 29 Aug 2009 17:27:45 -0300 Subject: Sqlite format string Message-ID: Hi, I have this statement cursor.execute("SELECT * from session_attribute WHERE sid=%s", ( user )) and I'm receiving this error : TypeError: not all arguments converted during string formatting What is wrong ? -- Sergio Roberto Charpinel Jr. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivanko.rus at gmail.com Sat Aug 29 16:28:26 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 20:28:26 +0000 Subject: Monitoring stdout in (more or less) real time In-Reply-To: Message-ID: <000e0cd2175497123704724da485@google.com> 29.08.2009 2:21 ???????????? Gabriel Genellina ???????: > En Sat, 29 Aug 2009 03:28:26 -0300, ivanko.rus at gmail.com> escribi?: > Hello to everyone! I am making a program that will be a GTK+ frontend to > ffmpeg. Naturally, one of the main functions is parsing ffmpeg's output. > It's pretty simple when I, for example, retrieve information about a file > (the program finishes and I read the output). But it also needs to parse > working ffmpeg's output (in order to retrieve the percentage, remaining > time, etc.). So, actually what I do is Popen ffmpeg, and connect to its > stdout. And as stdout is represented by a file object, it needs to be > read(). The problem is that read() reads until EOF is reached, which > doesn't exist while the program is running (the same goes with > communicate()). > So my question is: is there a way to retrieve the stdout without waiting > the program to finish? > You don't have to read the complete output at once - you may process it > line by line, I presume. I'd use a second thread to read the pipe and put > the lines onto a Queue object; the main thread gets lines from the Queue > when available. > -- > Gabriel Genellina > -- > http://mail.python.org/mailman/listinfo/python-list Thanks, Gabriel, but I resolved that problem in another way. thrashold in irc.freenode.net gave me the solution. What i do now is: p = Popen(["cmd","arg"],stdout=PIPE,stderr=STDOUT) fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) p.stdout.read() And in that way p.stdout.read() doesn't wait the program to finish, but gives me instant response. But anyway, thanks! =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivanko.rus at gmail.com Sat Aug 29 16:31:38 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 20:31:38 +0000 Subject: IDE for python similar to visual basic In-Reply-To: <2127e0be-3b93-406f-99a7-5fe02e643b40@a39g2000pre.googlegroups.com> Message-ID: <000e0cd170f00a493904724db0ec@google.com> 29.08.2009 1:32 ???????????? Vivian Wang ???????: > On Aug 29, 6:19 am, qwe rty hkh00... at gmail.com> wrote: > > i have been searching for am IDE for python that is similar to Visual > > Basic but had no luck.shall you help me please? > You can try biform: > http://www.bilive.com/download/Setup_BiForm_V2.1_en.msi.zip > Demo: > http://www.bilive.com/demo/BiForm_EN_demo.htm > More demo:(Chinese version) > http://www.bilive.com/demo/ > BiForm is a form designer,one designed form will deploy as a PFF file. > BiReader is a runtime PFF file process engine for end-users. > Setup file above include BiForm and BiReader. > Main features: > *Python as script language,base on QT GUI library > *Visible form designer > *Internal database access framework > *Auto connect database,auto create tables > *Supports SQLite/Mssql2000/Sybase ASE,not need write diffrent script > for diffrent database at most time > *Simple deploy,simple upgrade > *Different forms can share same tables,they will auto cooperation with > other forms at runtime.If you want to deploy a new function , not need > uninstall other forms,deploy the new PFF file is enough . > -- > http://mail.python.org/mailman/listinfo/python-list You can also try Eclipse + PyDev. It's not the same as Visual Studio, and I am not sure about the GUI builder, but I think it's what you want. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Sat Aug 29 17:12:06 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 29 Aug 2009 16:12:06 -0500 Subject: Sqlite format string In-Reply-To: References: Message-ID: <4A9999A6.4030804@tim.thechases.com> > I have this statement cursor.execute("SELECT * from session_attribute WHERE > sid=%s", ( user )) > and I'm receiving this error : > > TypeError: not all arguments converted during string formatting Two possibilities occur to me: 1) the 2nd parameter to execute() usually needs to be a tuple (or maybe a list), so try cursor.execute("select ...", (user, )) with the extra comma after "user". 2) More likely, check your sqlite3.paramstyle to see what sqlite is expecting (it's defined at the module-level): import sqlite3 print sqlite3.paramstyle Mine here is set to "qmark" which means that sqlite is expecting cursor.execute("... WHERE sid=?", (user,)) instead of the "format" style you're using: cursor.execute("... WHERE sid=%s", (user,)) as defined in http://www.python.org/dev/peps/pep-0249/ Hope this helps, -tkc From lists at cheimes.de Sat Aug 29 17:14:17 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 29 Aug 2009 23:14:17 +0200 Subject: weak reference callback In-Reply-To: <200908292327.03416.pogonyshev@gmx.net> References: <200908292327.03416.pogonyshev@gmx.net> Message-ID: <4A999A29.4050108@cheimes.de> Paul Pogonyshev wrote: > Hi, > > Is weak reference callback called immediately after the referenced > object is deleted or at arbitrary point in time after that? I.e. is > it possible to see a dead reference before the callback is called? > > More formally, will this ever raise? > > callback_called = False > def note_deletion (ref): > callback_called = True > > x = ... > ref = weakref.ref (x, note_deletion) > > ... > > if ref () is None and not callback_called: > raise RuntimeError ("reference is dead, yet callback hasn't been called yet") Yes, you'll definitely see a RuntimeError because you forgot to declare callback_called as a global variable. :) Christian From pogonyshev at gmx.net Sat Aug 29 17:14:38 2009 From: pogonyshev at gmx.net (Paul Pogonyshev) Date: Sun, 30 Aug 2009 00:14:38 +0300 Subject: weak reference callback In-Reply-To: <4A999A29.4050108@cheimes.de> References: <200908292327.03416.pogonyshev@gmx.net> <4A999A29.4050108@cheimes.de> Message-ID: <200908300014.38644.pogonyshev@gmx.net> Christian Heimes wrote: > Paul Pogonyshev wrote: > > Hi, > > > > Is weak reference callback called immediately after the referenced > > object is deleted or at arbitrary point in time after that? I.e. is > > it possible to see a dead reference before the callback is called? > > > > More formally, will this ever raise? > > > > callback_called = False > > def note_deletion (ref): > > callback_called = True > > > > x = ... > > ref = weakref.ref (x, note_deletion) > > > > ... > > > > if ref () is None and not callback_called: > > raise RuntimeError ("reference is dead, yet callback hasn't been called yet") > > Yes, you'll definitely see a RuntimeError because you forgot to declare > callback_called as a global variable. :) Thanks. Any useful answers though? callback_called = False def note_deletion (ref): global callback_called callback_called = True x = ... ref = weakref.ref (x, note_deletion) ... if ref () is None and not callback_called: raise RuntimeError ("reference is dead, yet callback hasn't been called yet") Paul From gagsl-py2 at yahoo.com.ar Sat Aug 29 17:16:02 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Aug 2009 18:16:02 -0300 Subject: how to edit .wsgi file extebtions with IDLE on windows References: <58a021ce-3058-483d-b429-6ba4855807ac@o36g2000vbl.googlegroups.com> <00795942-19ae-4d0e-9259-79ae00c34fc5@f10g2000vbf.googlegroups.com> Message-ID: En Sat, 29 Aug 2009 17:14:14 -0300, gert escribi?: > On Aug 29, 9:31?pm, Chris Rebert wrote: >> On Sat, Aug 29, 2009 at 5:40 AM, gert wrote: >> > On Aug 29, 6:43?am, "Gabriel Genellina" >> > wrote: >> >> En Fri, 28 Aug 2009 15:31:31 -0300, gert >> escribi?: >> >> >> > I can't figure out how to enable the .py shell and syntax >> highlighting >> >> > for .wsgi file extensions using IDLE for windows ? >> >> >> That's a Windows question, not a Python one. You have to associate >> the >> >> .wsgi extension with the Python.File file type (the one used for .py >> >> files): >> >> >> D:\USERDATA\Gabriel>assoc .py >> >> .py=Python.File >> >> >> D:\USERDATA\Gabriel>assoc .wsgi=Python.File >> >> .wsgi=Python.File >> >> > Thanks that does make it open exactly like a .py file, expect that >> > there is no syntax highlighting. Don't know if this is also a windows >> > issue or a IDLE issue ? >> >> That's an IDLE issue; it only highlights files with .py (and possibly >> .pyw) extensions. >> > > Any chance they would make a highlight option in the menu ? Two alternatives: a) Ensure your scripts contain a shebang - no purpose on Windows, but IDLE recognizes the file as a Python file. That is, make sure the very first line is like this: #!c:\python26\python.exe (it must start with #! and contain the word "python" somewhere) b) Edit IDLE sources: - Locate the file EditorWindow.py in the idlelib package. - Add this line near the top: import _winreg - Modify function ispythonsource near line 580 as follows: def ispythonsource(self, filename): if not filename or os.path.isdir(filename): return True base, ext = os.path.splitext(os.path.basename(filename)) if os.path.normcase(ext) in (".py", ".pyw"): return True ### add these 4 lines ### with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, ext) as key: ftype = _winreg.QueryValueEx(key, None)[0] if ftype.lower() in ("python.file","python.noconfile"): return True ### end ### try: f = open(filename) line = f.readline() f.close() except IOError: return False return line.startswith('#!') and line.find('python') >= 0 -- Gabriel Genellina From ivanko.rus at gmail.com Sat Aug 29 17:44:10 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 21:44:10 +0000 Subject: Sqlite format string In-Reply-To: Message-ID: <000e0cd2142c6f325d04724eb3c7@google.com> 29.08.2009 15:40 ???????????? "Sergio Charpinel Jr." ???????: > Thanks. > Do you know if both of them works for mysql too? > 2009/8/29 ivanko.rus at gmail.com> > 29.08.2009 15:27 ???????????? "Sergio Charpinel Jr." > sergiocharpinel at gmail.com> ???????: Actually, this works for any string (it doesn't depend on anything else). So you can pass "somestring {0}".format(foo) to any function because the string will be formatted _first_ and then passed as an argument. The same goes with "somestring %s" % "foo". Both will work -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Sat Aug 29 18:23:38 2009 From: aahz at pythoncraft.com (Aahz) Date: 29 Aug 2009 15:23:38 -0700 Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4a998465$0$1637$742ec2ed@news.sonic.net> Message-ID: In article <4a998465$0$1637$742ec2ed at news.sonic.net>, John Nagle wrote: > > Personally, I consider Python to be a good language held back by >too-close ties to a naive interpreter implementation and the lack >of a formal standard for the language. Name one language under active development that has not been harmed by a formal standard. (I think C doesn't count -- there was relatively little development of C after the standards process started.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From python.list at tim.thechases.com Sat Aug 29 18:26:38 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 29 Aug 2009 17:26:38 -0500 Subject: Sqlite format string In-Reply-To: <000e0cd2142c6f325d04724eb3c7@google.com> References: <000e0cd2142c6f325d04724eb3c7@google.com> Message-ID: <4A99AB1E.5040600@tim.thechases.com> ivanko.rus at gmail.com wrote: > 29.08.2009 15:40 ???????????? "Sergio Charpinel Jr." > ???????: >> Thanks. >> Do you know if both of them works for mysql too? > >> 2009/8/29 ivanko.rus at gmail.com> > >> 29.08.2009 15:27 ???????????? "Sergio Charpinel Jr." >> sergiocharpinel at gmail.com> ???????: > > Actually, this works for any string (it doesn't depend on anything else). > So you can pass "somestring {0}".format(foo) to any function because the > string will be formatted _first_ and then passed as an argument. The same > goes with "somestring %s" % "foo". Both will work Bad idea when assembling SQL, unless you _like_ SQL-injection attacks: sql = "select * from users where name='%s' and password='%s'" # get some values from an untrusted user: name = "administrator" password = "' or 1=1; drop table users; --" cursor.execute(sql % (name, password)) # uh-oh! This is why it's so important to use the DB API's own escaping functions. -tkc From ivanko.rus at gmail.com Sat Aug 29 18:40:46 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 22:40:46 +0000 Subject: Sqlite format string In-Reply-To: <4A99AB1E.5040600@tim.thechases.com> Message-ID: <000e0cd2142ce07bf104724f7d3b@google.com> 29.08.2009 17:26 ???????????? Tim Chase ???????: > ivanko.rus at gmail.com wrote: > 29.08.2009 15:40 ???????????? "Sergio Charpinel Jr." > sergiocharpinel at gmail.com> ???????: > Thanks. > Do you know if both of them works for mysql too? > 2009/8/29 ivanko.rus at gmail.com> > 29.08.2009 15:27 ???????????? "Sergio Charpinel Jr." > sergiocharpinel at gmail.com> ???????: > Actually, this works for any string (it doesn't depend on anything else). > So you can pass "somestring {0}".format(foo) to any function because the > string will be formatted _first_ and then passed as an argument. The same > goes with "somestring %s" % "foo". Both will work > Bad idea when assembling SQL, unless you _like_ SQL-injection attacks: > sql = "select * from users where name='%s' and password='%s'" > # get some values from an untrusted user: > name = "administrator" > password = "' or 1=1; drop table users; --" > cursor.execute(sql % (name, password)) > # uh-oh! > This is why it's so important to use the DB API's own escaping functions. > -tkc Sergio, Tim Chase is absolutely right! What you can do here is check every field separately OR you can modify the format() method to automatically do that. In the second case, you need to create your method first and then assign it to the str.format method like that: str.format = your_format_method . Note that there are NO parenthesis. For more details, look at this recipe: http://code.activestate.com/recipes/92823/ . I think it will simplify the things for you later, as every time you will call the str.format method, the values will be checked automatically. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Sat Aug 29 18:46:31 2009 From: rt8396 at gmail.com (r) Date: Sat, 29 Aug 2009 15:46:31 -0700 (PDT) Subject: An assessment of the Unicode standard Message-ID: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> I was reading the thread here... http://groups.google.com/group/comp.lang.python/browse_thread/thread/db90a9629b92aab0/b0385050b4c6c84e?hl=en&lnk=raot#b0385050b4c6c84e and it raised some fundamental philophosical questions to me about natural languages and Unicode. Which IMO * Unicode* is simply a monkey patch for this soup of multiple languages we have to deal with in programming and communication. Unicode (*puke*) seems nothing more than a brain fart of morons. And sadly it was created by CS majors who i assumed used logic and deductive reasoning but i must be wrong. Why should the larger world keep supporting such antiquated languages and character sets through Unicode? What purpose does this serve? Are we merely trying to make everyone happy? A sort of Utopian free-language-love-fest-kinda- thing? But there is a larger problem that is at the heart of Unicode itself, and it has to do with this multi-language/multi-culture world we live in. Even today in 2009 AD with all our technology and advancements we still live in a dark ages of societal communication. Of the many things that divide us such as race, color, religion, geography, blah, the most perplexing and devastating seems to be why have we not accepted a single global language for all to speak. Take for instance the Chinese language with it's thousands of characters and BS, it's more of an art than a language. Why do we need such complicated languages in this day and time. Many languages have been perfected, (although not perfect) far beyond that of Chinese language. The A-Z char set is flawless! Some may say well how can we possibly force countries/people to speak/ code in a uniform manner? Well that's simple, you just stop supporting their cryptic languages by dumping Unicode and returning to the beautiful ASCII and adopting English as the universal world language. Why English? Well because it is so widely spoken. But whatever we choose just choose one language and stick with it, perfect it, and maintain it. IMO Multiple languages are barriers to communication, collaboration, and the continuation of our future evolution as intelligent Human beings and this language multiplicity will comprise our future until it is reigned in and utterly destroyed. And i think most of you are missing how important this really is to our future. And so these problems bring me to the main subject of this thread "Unicode Sucks" Now you may say to yourself "I am not a sociologist i am a programmer, so why should i give a flying fig about natural languages or Unicode, i just accept things as they are". Well yes you could just go on accepting the status quo that is surely the easy route, but your life would be so much easier if you crusaded for change. BUT STOP!, before i go any further i want to respond to what i know will be condemnation from the sociology nuts out there. Yes multiculturalism is great, yes art is great, but if you can't see how the ability to communicate is severely damperd by multi-languages then you only *feel* with your heart but you apparently have no ability to reason with your mind intelligently. [nested thoughts] A few months ago i was watching some tear-jerking documentary called something like "Save the Languages" or "The dying languages" blah! In the documentary these two bleeding-heart-ivy-leaguers were running all over the world to document some obscure languages that were on the verge of extinction. And at one utterly amazing point in the episode they start crying and moaning for the loss of these languages like their own mother had died a horrible death. I watched all this in much horror and disbelief with jaw-dropped and i am still scared by the thought that people actually buy into this BS! Has the world gone mad? [back on track] The death of a language is as natural as the death of a flower, or a fish, or even the ever long oxidation of aluminum coke can. When a life form dies it brings life to the next generation. With languages, each death compiles upon the last and we are one step closer to the unifying language that we all so disparately need. We should herald the death of the languages like the jazz funerals of New Orleans with much happiness and fanfare for there is no reason to be sad. It's called evolution people! Ever heard of science? So ditch the useless Unicode and save us all a few keystrokes and bottles of aspirin for the persistent headaches! Simplicity is beautiful!! From exarkun at twistedmatrix.com Sat Aug 29 19:07:17 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sat, 29 Aug 2009 23:07:17 -0000 Subject: What python can NOT do? In-Reply-To: References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4a998465$0$1637$742ec2ed@news.sonic.net> Message-ID: <20090829230717.14429.2004501285.divmod.xquotient.10@localhost.localdomain> On 10:23 pm, aahz at pythoncraft.com wrote: >In article <4a998465$0$1637$742ec2ed at news.sonic.net>, >John Nagle wrote: >> >> Personally, I consider Python to be a good language held back by >>too-close ties to a naive interpreter implementation and the lack >>of a formal standard for the language. > >Name one language under active development that has not been harmed by >a >formal standard. (I think C doesn't count -- there was relatively >little >development of C after the standards process started.) I think you must mean "harmed by a formal standard more than it has been helped", since that's clearly the interesting thing. And it's a pretty difficult question to answer. How do you quantify the harm done to a language by a standarization process? How do you quantify the help? These are extremely difficult things to measure objectively. For my part, I will agree with John. I feel like Python's big shortcomings stem from the areas he mentioned. They're related to each other as well - the lack of a standard hampers the development of a less naive interpreter (either one based on CPython or another one). It doesn't completely prevent such development (obviously, as CPython continues to undergo development, and there are a number of alternate runtimes for Python-like languages), but there's clearly a cost associated with the fact that in order to do this development, a lot of time has to be spent figuring out what Python *is*. This is the kind of thing that a standard would help with. Jean-Paul From apt.shansen at gmail.com Sat Aug 29 19:12:26 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sat, 29 Aug 2009 16:12:26 -0700 Subject: An assessment of the Unicode standard In-Reply-To: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <7a9c25c20908291612o4f134743h84753572dd71026@mail.gmail.com> > > Unicode (*puke*) seems nothing more than a brain fart of morons. And > sadly it was created by CS majors who i assumed used logic and > deductive reasoning but i must be wrong. Why should the larger world > keep supporting such antiquated languages and character sets through > Unicode? What purpose does this serve? Are we merely trying to make > everyone happy? A sort of Utopian free-language-love-fest-kinda- > thing? > One really shouldn't consider Xah Lee a role model and seek to imitate (poorly) his rants. The Real World isn't going away just because you think we should stick our heads in the sand and pretend it's not there. There are billions of people out there who are quite happy with their language, and I'd rather keep them as a customer, thanks. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sat Aug 29 19:22:03 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Aug 2009 20:22:03 -0300 Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> <9205fd44-90ec-4ce6-be2a-2f82dd99e13e@r27g2000vbn.googlegroups.com> Message-ID: En Sat, 29 Aug 2009 04:34:48 -0300, zaur escribi?: > On 29 ???, 08:37, "Gabriel Genellina" wrote: >> En Fri, 28 Aug 2009 15:25:55 -0300, zaur escribi?: >> > On 28 ???, 16:07, Bruno Desthuilliers > > 42.desthuilli... at websiteburo.invalid> wrote: >> >> zaur a ?crit : >> >> >> > Ok. Here is a use case: object initialization. >> >> >> Err... Looks like you really should read the FineManual(tm) - >> >> specifically, the parts on the __init__ method. >> >> > What are you doing if 1) classes Person and Address imported from >> > foreign module 2) __init__ method is not defined as you want? >> >> Welcome to dynamic languages! It doesn't matter *where* the class was ? >> defined. You may add new attributes to the instance (even methods to >> the class) at any time. [...4 examples...] > > I know about these ways of object initializing. What I said is about > using object's dictionary as nested scope in code block. Object > initialization is just one use case. > So we say about different things. Well, you asked how to proceed in certain cases and I showed several ways it can be done right now, without requiring a new scope. You'll have to think of another use case. Attribute lookup is explicit in Python, and that's a very good thing. If you follow the python-ideas thread posted earlier, you'll see the kind of problems an implicit attribute lookup would cause. The "with" statement is necesary (and a good thing) in Pascal, but not in Python. Zope2 departs from this explicitness: it has a construct (similar to what you propose), and I hate it profoundly every time I have to edit a DTML file - I can never tell *where* an attribute comes from. Another related "feature" is acquisition, a stack of namespaces where objects "inherit" attributes from their containers. Same thing, a complete waste of time every time I have to track a bug. Unless you can find a very compeling use case, I don't think this feature will become part of the language anytime soon... -- Gabriel Genellina From gert.cuykens at gmail.com Sat Aug 29 19:29:43 2009 From: gert.cuykens at gmail.com (gert) Date: Sat, 29 Aug 2009 16:29:43 -0700 (PDT) Subject: how to edit .wsgi file extebtions with IDLE on windows References: <58a021ce-3058-483d-b429-6ba4855807ac@o36g2000vbl.googlegroups.com> <00795942-19ae-4d0e-9259-79ae00c34fc5@f10g2000vbf.googlegroups.com> Message-ID: <00cc1c86-0100-44d2-af4b-5a5652e934c2@e18g2000vbe.googlegroups.com> On Aug 29, 11:16?pm, "Gabriel Genellina" wrote: > En Sat, 29 Aug 2009 17:14:14 -0300, gert escribi?: > > > On Aug 29, 9:31?pm, Chris Rebert wrote: > >> On Sat, Aug 29, 2009 at 5:40 AM, gert wrote: > >> > On Aug 29, 6:43?am, "Gabriel Genellina" > >> > wrote: > >> >> En Fri, 28 Aug 2009 15:31:31 -0300, gert ? > >> escribi?: > > >> >> > I can't figure out how to enable the .py shell and syntax ? > >> highlighting > >> >> > for .wsgi file extensions using IDLE for windows ? > > >> >> That's a Windows question, not a Python one. You have to associate ? > >> the > >> >> .wsgi extension with the Python.File file type (the one used for .py > >> >> files): > > >> >> D:\USERDATA\Gabriel>assoc .py > >> >> .py=Python.File > > >> >> D:\USERDATA\Gabriel>assoc .wsgi=Python.File > >> >> .wsgi=Python.File > > >> > Thanks that does make it open exactly like a .py file, expect that > >> > there is no syntax highlighting. Don't know if this is also a windows > >> > issue or a IDLE issue ? > > >> That's an IDLE issue; it only highlights files with .py (and possibly > >> .pyw) extensions. > > > Any chance they would make a highlight option in the menu ? > > Two alternatives: > > a) Ensure your scripts contain a shebang - no purpose on Windows, but IDLE ? > recognizes the file as a Python file. That is, make sure the very first ? > line is like this: > > #!c:\python26\python.exe > > (it must start with #! and contain the word "python" somewhere) > > b) Edit IDLE sources: > > - Locate the file EditorWindow.py in the idlelib package. > > - Add this line near the top: > ? ?import _winreg > > - Modify function ispythonsource near line 580 as follows: > > ? ? ?def ispythonsource(self, filename): > ? ? ? ? ?if not filename or os.path.isdir(filename): > ? ? ? ? ? ? ?return True > ? ? ? ? ?base, ext = os.path.splitext(os.path.basename(filename)) > ? ? ? ? ?if os.path.normcase(ext) in (".py", ".pyw"): > ? ? ? ? ? ? ?return True > ? ? ? ? ?### add these 4 lines ### > ? ? ? ? ?with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, ext) as key: > ? ? ? ? ? ? ?ftype = _winreg.QueryValueEx(key, None)[0] > ? ? ? ? ? ? ?if ftype.lower() in ("python.file","python.noconfile"): > ? ? ? ? ? ? ? ? ?return True > ? ? ? ? ?### end ### > ? ? ? ? ?try: > ? ? ? ? ? ? ?f = open(filename) > ? ? ? ? ? ? ?line = f.readline() > ? ? ? ? ? ? ?f.close() > ? ? ? ? ?except IOError: > ? ? ? ? ? ? ?return False > ? ? ? ? ?return line.startswith('#!') and line.find('python') >= 0 > Thanks. Can you make a ispythonsource menu option in the next python3.x release? There are many examples of txt, xml or wsgi files having python parts in them. From cjns1989 at gmail.com Sat Aug 29 20:07:19 2009 From: cjns1989 at gmail.com (Chris Jones) Date: Sat, 29 Aug 2009 20:07:19 -0400 Subject: An assessment of the Unicode standard In-Reply-To: <7a9c25c20908291612o4f134743h84753572dd71026@mail.gmail.com> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <7a9c25c20908291612o4f134743h84753572dd71026@mail.gmail.com> Message-ID: <20090830000719.GA30241@turki.gavron.org> On Sat, Aug 29, 2009 at 07:12:26PM EDT, Stephen Hansen wrote: > > > > Unicode (*puke*) seems nothing more than a brain fart of morons. And > > sadly it was created by CS majors who i assumed used logic and > > deductive reasoning but i must be wrong. Why should the larger world > > keep supporting such antiquated languages and character sets through > > Unicode? What purpose does this serve? Are we merely trying to make > > everyone happy? A sort of Utopian free-language-love-fest-kinda- > > thing? > > > > One really shouldn't consider Xah Lee a role model and seek to imitate > (poorly) his rants. :-) CJ From rurpy at yahoo.com Sat Aug 29 20:12:24 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sat, 29 Aug 2009 17:12:24 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> <0022f1a7$0$2930$c3e8da3@news.astraweb.com> Message-ID: On 08/29/2009 12:06 PM, Steven D'Aprano wrote: [...] >> The reasons for the current behavior so far: >> >> 1. >>> What you propose would break the property "unichr(i) always returns a >>> string of length one, if it returns anything at all". >> >> Yes. And i don't see the problem with that. Why is that property more >> desirable than the non-existent property that a Unicode literal always >> produces one python character? > > What do you mean? Unicode literals don't always produce one character, > e.g. u'abcd' is a Unicode literal with four characters. I'm sorry, I should have been clearer. I meant the literal representation of a *single* unicode character. u'\u4000' which results in a string of length 1, vs u'\U00010040' which results in a string of length 2. In both case the literal represents a single unicode code point. > I think it's fairly self-evident that a function called uniCHR [emphasis > added] should return a single character (technically a single code > point). There are two concepts of characters here, the 16-bit things that encodes a character in a Python unicode string (in a narrow build Python), and a character in the sense of one of the ~2**10 unicode characters. Python has chosen to represent the latter (when outside the BMP) as a pair of surrogate characters from the former. I don't see why one would assume that CHR would mean the python 16-bit character concept rather than the full unicode character concept. In fact, rather the opposite. > But even if you can come up with a reason for unichr() to return > two or more characters, I've given a number of reasons why it should return a two character representation of a non-BMP character, one of which is that that is how Python has chosen to represent such characters internally. I won't repeat the other reasons again. I'm not sure why you think more than two characters would ever be possible. > this would break code that relies on the > documented promise that the length of the output of unichr() is always > one. Ah, OK. This is the good reason I was looking for. I did not realize (until prompted by your remark to go back and look at the early docs) that unichr had been documented to return a single character since 2.0 and that wide character support was added in 2.2. Martin v. Loewis also implied that, I now see, although the implication was too deep for me to pick up. So although it leads to a suboptimal situation, I agree that maintaining the documented behavior was necessary. [...] > I would much rather see a pair of new functions, wideord() and > widechr() used for converting between surrogate pairs and numbers. I guess if it were still 2001 and Python 2.2 was coming out I would be in favor of this too. :-) From walkraft at gmail.com Sat Aug 29 20:12:45 2009 From: walkraft at gmail.com (casebash) Date: Sat, 29 Aug 2009 17:12:45 -0700 (PDT) Subject: Determining the metaclass Message-ID: <6f69f304-3cf1-45c8-b86d-f57751bcc2ed@d15g2000prc.googlegroups.com> Hi all, I cannot determine if a class is an instance of a particular metaclass. Here is my best attempt >>> class tmp(type): ... pass ... >>> def c(metaclass=tmp): ... pass ... >>> isinstance(c, tmp) False >>> isinstance(c.__class__, tmp) False Can anyone explain why this fails? Thanks very much, Chris From rurpy at yahoo.com Sat Aug 29 20:16:30 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sat, 29 Aug 2009 17:16:30 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: <55a533a7-20ab-42ed-b2c7-74706d7d5451@p36g2000vbn.googlegroups.com> On 08/29/2009 01:43 PM, Vlastimil Brom wrote: > > 2009/8/29: >> >> On 08/28/2009 02:12 AM, "Martin v. L?wis" wrote: >> >> >> >> So far, it seems not and that unichr/ord >> >> is a poster child for "purity beats practicality". >> >> -- >> >> http://mail.python.org/mailman/listinfo/python-list >> >> > > > > As Mark Tolonen pointed out earlier in this thread, in Python 3 the > > practicality apparently beat purity in this aspect: > > > > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit > > (Intel)] on win32 > > Type "copyright", "credits" or "license()" for more information. > > >>>> >>>> goth_urus_1 = '\U0001033f' >>>> >>>> list(goth_urus_1) > > ['\ud800', '\udf3f'] >>>> >>>> len(goth_urus_1) > > 2 >>>> >>>> ord(goth_urus_1) > > 66367 >>>> >>>> goth_urus_2 = chr(66367) >>>> >>>> len(goth_urus_2) > > 2 >>>> >>>> import unicodedata >>>> >>>> unicodedata.name(goth_urus_1) > > 'GOTHIC LETTER URUS' >>>> >>>> goth_urus_3 = unicodedata.lookup("GOTHIC LETTER URUS") >>>> >>>> goth_urus_4 = "\N{GOTHIC LETTER URUS}" >>>> >>>> goth_urus_1 == goth_urus_2 == goth_urus_3 == goth_urus_4 > > True >>>> >>>> Yes, that certainly seems like much more sensible behavior. > > As for the behaviour in python 2.x, it's probably good enough, that > > the surrogates aren't prohibited and the eventually needed behaviour > > can be easily added via custom functions. Yes, I agree that given the current behavior is well documented and further, is fixed in python 3, it can't be changed. I would a nit though with "can be easily added via custom functions." I don't think that is a good criterion for rejection of functionality from the library because it is not sufficient; their are many functions in the library that fail that test. I think the criterion should be more like a ratio: (how often needed) / (ease of writing). [where "ease" is not just the line count but also the obviousness to someone who is not a python expert yet.] And I would also dispute that the generalized unichr/ord functions are "easily" added. When I ran into the TypeError in ord(), I thought "surrogate pairs" were something used in sex therapy. :-) It took a lot of reading and research before I was able to write a generalized ord() function. From walkraft at gmail.com Sat Aug 29 20:18:46 2009 From: walkraft at gmail.com (casebash) Date: Sat, 29 Aug 2009 17:18:46 -0700 (PDT) Subject: Why does this group have so much spam? Message-ID: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> So much of it could be removed even by simple keyword filtering. From sjmachin at lexicon.net Sat Aug 29 20:20:47 2009 From: sjmachin at lexicon.net (John Machin) Date: Sat, 29 Aug 2009 17:20:47 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: On Aug 30, 8:46?am, r wrote: > > Take for instance the Chinese language with it's thousands of > characters and BS, it's more of an art than a language. ?Why do we > need such complicated languages in this day and time. Many languages > have been perfected, (although not perfect) far beyond that of Chinese > language. The Chinese language is more widely spoken than English, is quite capable of expression in ASCII ("r tongzhi shi sha gua") and doesn't have those pesky it's/its problems. > The A-Z char set is flawless! ... for expressing the sounds of a very limited number of languages, and English is *NOT* one of those. From nyamatongwe+thunder at gmail.com Sat Aug 29 20:22:26 2009 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 30 Aug 2009 00:22:26 GMT Subject: An assessment of the Unicode standard In-Reply-To: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> r: > Unicode (*puke*) seems nothing more than a brain fart of morons. And > sadly it was created by CS majors who i assumed used logic and > deductive reasoning but i must be wrong. Why should the larger world > keep supporting such antiquated languages and character sets through > Unicode? What purpose does this serve? Are we merely trying to make > everyone happy? A sort of Utopian free-language-love-fest-kinda- > thing? Wow, I like this world you live in: all that altruism! Unicode was developed by corporations from the US left coast in order to sell their products in foreign markets at minimal cost. Neil From pavlovevidence at gmail.com Sat Aug 29 20:31:19 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 29 Aug 2009 17:31:19 -0700 (PDT) Subject: Determining the metaclass References: <6f69f304-3cf1-45c8-b86d-f57751bcc2ed@d15g2000prc.googlegroups.com> Message-ID: <3e1b7e0b-e44c-4b34-9866-33aa7b33a3af@v37g2000prg.googlegroups.com> On Aug 29, 5:12?pm, casebash wrote: > Hi all, > > I cannot determine if a class is an instance of a particular > metaclass. Here is my best attempt > > >>> class tmp(type): > > ... ? ? pass > ...>>> def c(metaclass=tmp): > > ... ? ? pass > ...>>> isinstance(c, tmp) > False > >>> isinstance(c.__class__, tmp) > > False > > Can anyone explain why this fails? You're gonna kick yourself. It's because you used "def" and not "class" to define c. If you'd used "class" then then first test would have worked. Carl Banks From sccolbert at gmail.com Sat Aug 29 20:39:31 2009 From: sccolbert at gmail.com (Chris Colbert) Date: Sat, 29 Aug 2009 20:39:31 -0400 Subject: Permanently adding to the Python path in Ubuntu Message-ID: <7f014ea60908291739r70f724fbw626c32265198b5ae@mail.gmail.com> I'm having an issue with sys.path on Ubuntu. I want some of my home built packages to overshadow the system packages. Namely, I have built numpy 1.3.0 from source with atlas support, and I need it to overshadow the system numpy 1.2.1 which I had to drag along as a dependency for other stuff. I have numpy 1.3.0 installed into /usr/local/lib/python2.6/dist-packages/. The issue is that this directory is added to the path after the /usr/lib/python2.6/dist-packages/ is added, so python doesnt see my version of numpy. I have been combating this with a line in my .bashrc file: export PYTHONPATH=/usr/local/lib/python2.6/dist-packages So when I start python from the shell, everything works fine. Problems show up when python is not executed from the shell, and thus the path variable is never exported. This can occur when I have launcher in the gnome panel or i'm executing from within wing-ide. Is there a way to fix this so that the local dist-packages is added to sys.path before the system directory ALWAYS? I can do this by editing site.py but I think it's kind of bad form to do it this way. I feel there has to be a way to do this without root privileges. Any ideas? Cheers, Chris From rt8396 at gmail.com Sat Aug 29 20:40:42 2009 From: rt8396 at gmail.com (r) Date: Sat, 29 Aug 2009 17:40:42 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <1c10c974-beb6-4e71-90dd-4f23aa6c70a9@g23g2000vbr.googlegroups.com> On Aug 29, 7:20?pm, John Machin wrote: > On Aug 30, 8:46?am, r wrote: > The Chinese language is more widely spoken than English, is quite > capable of expression in ASCII ("r tongzhi shi sha gua") and doesn't > have those pesky it's/its problems. Oh yes of course it is the most widely spoken amongst Chinese people since one in every five people on this earth are Chinese. What i meant to say was that English language is more widespread outside of "normal" English speaking countries -- of course as a result of colonialism, and arguably, imperialism. ;) From rt8396 at gmail.com Sat Aug 29 21:03:12 2009 From: rt8396 at gmail.com (r) Date: Sat, 29 Aug 2009 18:03:12 -0700 (PDT) Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> Message-ID: On Aug 29, 7:18?pm, casebash wrote: > So much of it could be removed even by simple keyword filtering. A more interesting question is what morons are responding to this spam and enticing the spammers to proliferate their garbage? Do people actually see a spam like "Phallus enlargement pills" and say to themself "Alright!, just what i been looking for!". I guess i just can't understand foolishness... Yes i agree, far to much spam is getting through. From rt8396 at gmail.com Sat Aug 29 21:30:34 2009 From: rt8396 at gmail.com (r) Date: Sat, 29 Aug 2009 18:30:34 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: On Aug 29, 7:22?pm, Neil Hodgson wrote: > ? ?Wow, I like this world you live in: all that altruism! Well if i don't who will? *shrugs* > Unicode was > developed by corporations from the US left coast in order to sell their > products in foreign markets at minimal cost. So why the heck are we supporting such capitalistic implementations as Unicode. Sure we must support a winders installer but Unicode, dump it! We don't support a Python group in Chinese or French, so why this? Makes no sense to me really. Let M$ deal with it. From benjamin at python.org Sat Aug 29 21:38:50 2009 From: benjamin at python.org (Benjamin Peterson) Date: Sun, 30 Aug 2009 01:38:50 +0000 (UTC) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: Neil Hodgson gmail.com> writes: \\ > > Unicode was > developed by corporations from the US left coast in order to sell their > products in foreign markets at minimal cost. Like Sanskrit or Snowman language? From danb_83 at yahoo.com Sat Aug 29 21:40:36 2009 From: danb_83 at yahoo.com (AggieDan04) Date: Sat, 29 Aug 2009 18:40:36 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: On Aug 28, 7:05?pm, Tim Chase wrote: > qwe rty wrote: > > i know that an interpreted language like python can't be used to make > > an operating system or system drivers. > > As long as you are willing to write the OS hooks in C, you can > write the userspace device drivers in Python: Writing your OS hooks in C isn't a problem because you could write a C compiler in Python ;-) From zuo at chopin.edu.pl Sat Aug 29 22:25:45 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sun, 30 Aug 2009 04:25:45 +0200 Subject: copy construtor question In-Reply-To: <613204.64791.qm@web53105.mail.re2.yahoo.com> References: <613204.64791.qm@web53105.mail.re2.yahoo.com> Message-ID: 28-08-2009 o 20:38:30 xiaosong xia wrote: > I am trying to define a class with copy constructor as following: > ? > class test: > ???? def __init__(self, s=None): > ????????? self=s > ? > x=[1,2] > ? > y=test(x) > ? > print y.__dict__ > ? > it gives > {} > ? > The above code doesn't work. And cannot, as Chris has already written. But it is possible to customize construction of objects of your class -- using __new__(): [see: http://docs.python.org/reference/datamodel.html#object.__new__ ] import copy # in Python 2.x you must explicitly inherit from 'object' type class Test(object): "Not tested" def __new__(cls, s, way=None): if s is None: # a new object of 'Test' class return super(currentclass, cls).__new__(cls, *args) else: if way == 'alias': return s elif way == 'shallow': return copy.copy(s) elif way == 'deep': return copy.deepcopy(s) else: raise ValueError("'way' must be 'alias', " "'shallow' or 'deepcopy'") ...but in such cases as copying existing objects it is usualy better (though less romantic :-)) to use an ordinary function (e.g. simply copy.copy() or copy.deepcopy(), as Gabriel has pointed). Regards, *j -- Jan Kaliszewski (zuo) From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 22:36:49 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 02:36:49 GMT Subject: (Simple?) Unicode Question References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> <002269cb$0$2930$c3e8da3@news.astraweb.com> Message-ID: <0023693f$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 20:09:12 +0100, Nobody wrote: > On Sat, 29 Aug 2009 08:26:54 +0000, Steven D'Aprano wrote: > >> Python only needs to know when you convert the text to or from bytes. I >> can do this: >> >>>>> s = "hello" >>>>> t = "world" >>>>> print(' '.join([s, t])) >> hello world >> >> and not need to care anything about encodings. >> >> So long as your terminal has a sensible encoding, and you have a good >> quality font, you should be able to print any string you can create. > > UTF-8 isn't a particularly sensible encoding for terminals. Did I mention UTF-8? Out of curiosity, why do you say that UTF-8 isn't sensible for terminals? > And "Unicode font" is an oxymoron. You can merge a whole bunch of fonts > together and stuff them into a TTF file; that doesn't make them "a > font", though. I never mentioned "Unicode font" either. In any case, there's no reason why a skillful designer can't make a single font which covers the entire Unicode range in a consistent style. >>>> I may be wrong, but I believe that's part of the idea between >>>> separation of string and bytes types in Python 3.x. I believe, if you >>>> are using Python 3.x, you don't need the character encoding mumbo >>>> jumbo at all ;-) >>> >>> Nothing has changed in that regard. You still need to decode and >>> encode text and for that you have to know the encoding. >> >> You only need to worry about encoding when you convert from bytes to >> text, and visa versa. Admittedly, the most common time you need to do >> that is when reading input from files, but if all your text strings are >> generated by Python, and not output anywhere, you shouldn't need to >> care about encodings. > > Why would you generate text strings and not output them anywhere? Who knows? It doesn't matter -- the point is that you can if you want to. You only need to worry about encodings at input and output, therefore logically if you don't do I/O you can process strings all day long and never worry about encodings at all. > The main advantage of using Unicode internally is that you can associate > encodings with the specific points where data needs to be converted > to/from bytes, rather than having to carry the encoding details around > the program. Surely the main advantage of Unicode is that it gives you a full and consistent range of characters not limited to the 128 characters provided by ASCII? -- Steven From nyamatongwe+thunder at gmail.com Sat Aug 29 23:07:17 2009 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 30 Aug 2009 03:07:17 GMT Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: Benjamin Peterson: > Like Sanskrit or Snowman language? Sanskrit is mostly written in Devanagari these days which is also useful for selling things to people who speak Hindi and other Indian languages. Not sure if you are referring to the ? snowman character or Arctic region languages like Canadian Aboriginal syllabic writing like ????? which were added to Unicode 8 years after the initial version. I'd guess that was added from political rather than marketing motives. ? was required since it was present in Japanese character sets. Neil From cs at zip.com.au Sat Aug 29 23:24:22 2009 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 30 Aug 2009 13:24:22 +1000 Subject: Sqlite format string In-Reply-To: Message-ID: <20090830032422.GA23090@cskk.homeip.net> On 29Aug2009 17:27, Sergio Charpinel Jr. wrote: | Hi, | I have this statement cursor.execute("SELECT * from session_attribute WHERE | sid=%s", ( user )) | and I'm receiving this error : | | TypeError: not all arguments converted during string formatting | | What is wrong ? This: ( user ) is not a tuple containing the element user. It's just user. This: ( user, ) is what you want. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ [Alain] had been looking at his dashboard, and had not seen me, so I ran into him. - Jean Alesi on his qualifying prang at Imola '93 From half.italian at gmail.com Sat Aug 29 23:51:16 2009 From: half.italian at gmail.com (Sean DiZazzo) Date: Sat, 29 Aug 2009 20:51:16 -0700 (PDT) Subject: Permanently adding to the Python path in Ubuntu References: Message-ID: On Aug 29, 5:39?pm, Chris Colbert wrote: > I'm having an issue with sys.path on Ubuntu. I want some of my home > built packages to overshadow the system packages. Namely, I have built > numpy 1.3.0 from source with atlas support, and I need it to > overshadow the system numpy 1.2.1 which I had to drag along as a > dependency for other stuff. I have numpy 1.3.0 installed into > /usr/local/lib/python2.6/dist-packages/. The issue is that this > directory is added to the path after the > /usr/lib/python2.6/dist-packages/ is added, so python doesnt see my > version of numpy. > > I have been combating this with a line in my .bashrc file: > > export PYTHONPATH=/usr/local/lib/python2.6/dist-packages > > So when I start python from the shell, everything works fine. > > Problems show up when python is not executed from the shell, and thus > the path variable is never exported. This can occur when I have > launcher in the gnome panel or i'm executing from within wing-ide. > > Is there a way to fix this so that the local dist-packages is added to > sys.path before the system directory ALWAYS? I can do this by editing > site.py but I think it's kind of bad form to do it this way. I feel > there has to be a way to do this without root privileges. > > Any ideas? > > Cheers, > > Chris I think you can modify sys.path inside your application. Maybe this will work (at the top of your script): import sys sys.path[0] = "/usr/local/lib/python2.6/dist-packages" import numpy PS. Say hi to Steven for me! ~Sean From b1540457 at tyldd.com Sun Aug 30 00:05:24 2009 From: b1540457 at tyldd.com (Anny Mous) Date: Sun, 30 Aug 2009 14:05:24 +1000 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: r wrote: > Of the many > things that divide us such as race, color, religion, geography, blah, > the most perplexing and devastating seems to be why have we not > accepted a single global language for all to speak. I agree 1000% and obviously we should make Klingon that global language. Or possibly the Black Tongue of the Mordor Orcs, which is much better for cursing. I haven't decided yet. > Take for instance the Chinese language with it's thousands of > characters and BS, it's more of an art than a language. Why do we > need such complicated languages in this day and time. Many languages > have been perfected, (although not perfect) far beyond that of Chinese > language. The A-Z char set is flawless! How do we distinguish resume from r?sum? without accents? Even when we succeed in banning all languages that can't be written using A-Z, what do we do about the vast number of legacy documents? How do we write about obsolete English letters like ? and ? without Unicode? How do we write mathematical and scientific documents without characters like ? ? ? ? and ? ? What do we use to replace typographic symbols and dingbats like ? without Unicode? > Some may say well how can we possibly force countries/people to speak/ > code in a uniform manner? Well that's simple, you just stop supporting > their cryptic languages by dumping Unicode and returning to the > beautiful ASCII and adopting English as the universal world language. > Why English? Well because it is so widely spoken. World population: 6.7 billion Number of native Mandarin speakers: 873 million Number of native Hindi speakers: 370 million Number of native Spanish speakers: 350 million Number of native English speakers: 340 million Total number of Mandarin speakers: 1051 million Total number of English speakers: 510 million http://www.vistawide.com/languages/top_30_languages.htm Whichever way you look at it, we should all convert to Mandarin, not English. Looks like we still need Unicode. Besides, given that the US would be bankrupt if not for Chinese loans, do you really want to upset them by suggesting their language sucks? > But whatever we > choose just choose one language and stick with it, perfect it, and > maintain it. Just ask the Academie Francaise how well that works! Why stop with A-Z? We can improve on 26 letters. In the first year we should replace the soft 'c' with 's'. Any sivilized language will sertainly be better off with this change. The hard 'c' will be dropped in favour of 'k', which will klear up much konfusion and allow one key less on keyboards. In the sekond year I expect publik enthusiasm to grow, allowing us to replace the troublesome 'ph' with 'f', which will make words like 'fotograf' twenty persent shorter. In the third year, publik akseptanse of the new spelling kan be expekted to permit more komplikated changes. We will enkourage the removal of double leters which have always ben a deterent to akurate speling. Also, al wil agre that the horible mes of the silent 'e' is disgrasful. By the fourth yer, peopl wil be reseptiv to replasing 'th' with 'z' and 'w' with 'v'. Zis vil be a grat improvment. During ze fifz yer, ze unesesary 'o' kan be dropd from vords kontaining 'ou' and similar changes vud of kors be aplid to ozer kombinations of leters. After zis fifz yer, ve vil hav a reli sensibl riten styl. Zer vil be no mor trubls or difikultis and everivun vil find it ezi to understand ech ozer. ZE DREM VIL FINALI COM TRU! > IMO Multiple languages are barriers to communication, collaboration, > and the continuation of our future evolution as intelligent Human > beings and this language multiplicity will comprise our future until > it is reigned in and utterly destroyed. Yes, because language differences have utterly destroyed us so many times in the past! Have you thought about the difference between China, with one culture and one spoken language for thousands of years, and Europe, with dozens of competing cultures, competing governments, and alternate languages for just as long? If multiple languages are so harmful, why was it the British, French, Japanese, Russians, Germans, Italians, Austrians, Hungarians and Americans who were occupying China during the Opium Wars and the Boxer Rebellion, instead of the other way around? Strength comes from diversity, not monoculture. From kennyken747 at gmail.com Sun Aug 30 00:14:59 2009 From: kennyken747 at gmail.com (kennyken747) Date: Sat, 29 Aug 2009 21:14:59 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: <604b21ef-a3ad-4da8-92f5-c1d22345b4d7@p15g2000vbl.googlegroups.com> On Aug 29, 6:16?am, paul wrote: > Deep_Feelings schrieb:> python got relatively fewer numbers of developers than other high > > level languages like .NET , java .. etc ?why ? > > Besides the marketing argument, python never had a "hype". > > Both PHP and ruby(Rails to be precise) got widespread because they could > ? at one point do "one" thing better than the competition. From there > on, they had more ressources (developer time) and grew fast and beyond > the original problem domain. Now you can write GUI apps in PHP, great! > > cheers > ? Paul You guys can say anything you'd like it to be in this thread, but the actual reason comes down to 1. No marketing. Seriously, if Microsoft was pushing Python it would obviously be a lot bigger in terms of developers. 2. No certification. Millions go to college to get degrees in computer related study. Do the math. Also, really guys? This crap about speed? People have been saying this for years, and yet they still don't realize that there are plenty solutions to take care of that one problem. Just be happy that you've stumbled upon Python, just because it's not the most widespread language in the world certainly doesn't mean it's not a worthy language. Quite the opposite. From cjns1989 at gmail.com Sun Aug 30 00:22:00 2009 From: cjns1989 at gmail.com (Chris Jones) Date: Sun, 30 Aug 2009 00:22:00 -0400 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: <20090830042200.GC30241@turki.gavron.org> On Sat, Aug 29, 2009 at 11:07:17PM EDT, Neil Hodgson wrote: > Benjamin Peterson: > > Like Sanskrit or Snowman language? > Sanskrit is mostly written in Devanagari these days which is also > useful for selling things to people who speak Hindi and other Indian > languages. Is the implication that the principal usefulness of such languages as Hindi and "other Indian languages" is us selling "things" to them..? I am not from these climes but all the same, I do find you tone of voice rather offensive, considering that you are referring to a culture that's about 3000 years older and 3000 richer than ours and certainly deserves our respect. Maybe you didn't notice, but our plants shut down many years ago.. They are selling _us_ their wares. > Not sure if you are referring to the snowman character or Arctic > region languages like Canadian Aboriginal syllabic writing like ????? > which were added to Unicode 8 years after the initial version. I'd > guess that was added from political rather than marketing motives. ? > was required since it was present in Japanese character sets. Oh.. so.. now Unicode is not only about marketing.. there is also a political "aspect".. polytonic Greek, Runic, Shavian, Glagolitic, Carian, Phoenician, Lydian, Cuneiform, not to mention Mathematical symbols, Braille, Domino Tiles, the IPA..? What was I thinking..? Nothing personal, I assure you.. maybe I misunderstood what you were saying. In any event, you shouldn't feed the troll, even if he's teething. CJ From cmpython at gmail.com Sun Aug 30 00:45:19 2009 From: cmpython at gmail.com (Che M) Date: Sat, 29 Aug 2009 21:45:19 -0700 (PDT) Subject: IDE for python similar to visual basic References: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> Message-ID: <3d91c968-bd36-45b9-8ae0-3af8e855605e@o35g2000vbi.googlegroups.com> On Aug 28, 6:19?pm, qwe rty wrote: > i have been searching for am IDE for python that is similar to Visual > Basic but had no luck.shall you help me please? Boa Constructor. IDE/visual GUI-builder/sizer support, lots of other goodies. Not actively maintained, though, and some issues on Linux, in my experience. But I like it a lot. From cmpython at gmail.com Sun Aug 30 00:47:10 2009 From: cmpython at gmail.com (Che M) Date: Sat, 29 Aug 2009 21:47:10 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <62177729-0079-4cfc-bdf6-e31ebd3e883b@z28g2000vbl.googlegroups.com> On Aug 28, 6:37?pm, qwe rty wrote: > i know that an interpreted language like python can't be used to make > an operating system or system drivers. > > what else can NOT be done in python? what are the limitations of the > language? Now that you have some good answers, may I ask what what your reason was for posting this question? From cmpython at gmail.com Sun Aug 30 00:51:13 2009 From: cmpython at gmail.com (Che M) Date: Sat, 29 Aug 2009 21:51:13 -0700 (PDT) Subject: Python Noob - gui module, book, annoying questions References: <92cc4ca1-0e0d-4355-8d9a-b4928390e619@q35g2000vbi.googlegroups.com> Message-ID: On Aug 29, 3:20?am, Pherdnut wrote: > I want to write cross-platform stuff. Any opinions on the best GUI > module for that? > > I like a good juicy, but concise book for reading on my commute > downtown. I was thinking of checking Python in a Nutshell. Good? Bad? > Better? > > Is 3.0+ more object based? I'm actually an FED and one of the things I > love about JS is the consistency of the language. I love Python 2.6 so > far so I'm not knocking it. But I'm not really taking advantage of the > non-core libraries as much right now anyway since I'm learning it. > > What do you guys like in Reg Ex books/sites? I'd like to become more > fluent in some of the less commonly used stuff. Also wxPython. It's cross platform, but it does require occasional platform-dependent tweaks, since it mostly uses native controls and sometimes the native controls' requirements are different. You might want to consider that it's going to be some time before the 3rd party libraries catch up to Python 3. I'd recommend 2.5 or 2.6 for learning now if you plan on using them. From torriem at gmail.com Sun Aug 30 00:52:54 2009 From: torriem at gmail.com (Michael Torrie) Date: Sat, 29 Aug 2009 22:52:54 -0600 Subject: What python can NOT do? In-Reply-To: References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: <4A9A05A6.4080803@gmail.com> qwe rty wrote: > On Aug 29, 5:11 am, Nobody wrote: >> On Fri, 28 Aug 2009 17:26:06 -0700, qwe rty wrote: >>> if you don't know the answer please don't reply >> If you don't understand the question, don't post it in the first place. > > don't be so angry ,not good for your health You forgot your smiley emoticon! Since everyone else is posting in a light-hearted manner (not "angry" as you say), I choose to read your post in this light as well. What Nobody was really trying to say, is ask your question in a better way and you'll get a better answer. From dieter at handshake.de Sun Aug 30 00:54:21 2009 From: dieter at handshake.de (Dieter Maurer) Date: 30 Aug 2009 06:54:21 +0200 Subject: break unichr instead of fix ord? In-Reply-To: <4a979172$0$11759$9b622d9e@news.freenet.de> References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" writes on Fri, 28 Aug 2009 10:12:34 +0200: > > The PEP says: > > * unichr(i) for 0 <= i < 2**16 (0x10000) always returns a > > length-one string. > > > > * unichr(i) for 2**16 <= i <= TOPCHAR will return a > > length-one string on wide Python builds. On narrow > > builds it will raise ValueError. > > and > > * ord() is always the inverse of unichr() > > > > which of course we know; that is the current behavior. But > > there is no reason given for that behavior. > > Sure there is, right above the list: > > "Most things will behave identically in the wide and narrow worlds." > > That's the reason: scripts should work the same as much as possible > in wide and narrow builds. > > What you propose would break the property "unichr(i) always returns > a string of length one, if it returns anything at all". But getting a "ValueError" in some builds (and not in others) is rather worse than getting unicode strings of different length.... > > 1) Should surrogate pairs be disallowed on narrow builds? > > That appears to have been answered in the negative and is > > not relevant to my question. > > It is, as it does lead to inconsistencies between wide and narrow > builds. OTOH, it also allows the same source code to work on both > versions, so it also preserves the uniformity in a different way. Do you not have the inconsistencies in any case? ... "ValueError" in some builds and not in others ... From bcb at undisclosedlocation.net Sun Aug 30 01:00:54 2009 From: bcb at undisclosedlocation.net (Bruce C. Baker) Date: Sun, 30 Aug 2009 00:00:54 -0500 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> Message-ID: <7Hnmm.176524$zq1.39243@newsfe22.iad> "casebash" wrote in message news:7294bf8b-9819-4b6d-92b2-afc1c8042a06 at x6g2000prc.googlegroups.com... > So much of it could be removed even by simple keyword filtering. Assuming this is a serious question: 1. comp.lang.python has relatively little spam, compared to others. 2. The spam posters aren't looking for responses within the individual NGs, they're just hoping you'll click through to the link within the post. It's a version of "fire and forget" 3. Simple keyword filtering /by whom/? There is no central NG governing authority. The best response is to ignore[1] the spam posts; they'll eventually expire and disappear from your newsreader. [1] Although if they're egregiously stupid, you may find yourself mocking the OP. Realize that as witty and urbane as your response may be, the OP ain't listening. :-) From nagle at animats.com Sun Aug 30 01:14:55 2009 From: nagle at animats.com (John Nagle) Date: Sat, 29 Aug 2009 22:14:55 -0700 Subject: An assessment of the Unicode standard In-Reply-To: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <4a9a0988$0$1669$742ec2ed@news.sonic.net> r wrote: > I was reading the thread here... > http://groups.google.com/group/comp.lang.python/browse_thread/thread/db90a9629b92aab0/b0385050b4c6c84e?hl=en&lnk=raot#b0385050b4c6c84e > > and it raised some fundamental philophosical questions Rant ignored. Actually, Python 3.x seems finally to have character sets right. There's "bytes", for uninterpreted binary data, Unicode, and proper ASCII, 0..127. Within Python, we finally got rid of "upper code pages". (I wish the HTML standards people would do the same. HTML 5 should have been ASCII only (with the "&" escapes if desired) or Unicode. No "Latin-1", no upper code pages, no JIS, etc.) > > [nested thoughts] > A few months ago i was watching some tear-jerking documentary called > something like "Save the Languages" or "The dying languages" blah! It may be a bit much that Unicode supports Cretan Linear B. John Nagle From tjreedy at udel.edu Sun Aug 30 01:26:55 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Aug 2009 01:26:55 -0400 Subject: An assessment of the Unicode standard In-Reply-To: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: r wrote: > natural languages and Unicode. Which IMO * Unicode* is simply a monkey > patch for this soup of multiple languages we have to deal with in > programming and communication. A somewhat fair charactierization. [snip] > everyone happy? A sort of Utopian free-language-love-fest-kinda- > thing? Not utopian, but pragmatically political. Before unicode, and still today, we had and have multiple codes. Multiple ascii extenstions for European languages and even multiple codes just for Japanese. To get people in the major computing countries, including Japan, to agree to eventually replace their national codes with one worldwide code, some kludgy compromises were made. > language. The A-Z char set is flawless! Hardly. There are too few characters. A basic set should have at least 50. The international phonetic alphabet (IPA) has about 150. Here is a true Utopian proposal for you (from a non-CS major ;-): develop an extended IPA 256-character set with just a few control chars (rather than 32) and punctuation and other markers. Then develop dictionaries to translate texts in every languange and char set into and back out of this universal character set. Fat chance of approval, even if techical issues were resolved. > Some may say well how can we possibly force countries/people to speak/ > code in a uniform manner? Well that's simple, you just stop supporting > their cryptic languages by dumping Unicode and returning to the > beautiful ASCII But most everyone outside the US was not using ascii precisely because it did not support their language. Get over the imperfections of unicode. It improves on the prior status quo. Terry Jan Reedy From steve at lonetwin.net Sun Aug 30 01:28:50 2009 From: steve at lonetwin.net (steve) Date: Sun, 30 Aug 2009 10:58:50 +0530 Subject: An assessment of the Unicode standard In-Reply-To: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <4A9A0E12.9040308@lonetwin.net> On 08/30/2009 04:16 AM, r wrote: > I was reading the thread here... > http://groups.google.com/group/comp.lang.python/browse_thread/thread/db90a9629b92aab0/b0385050b4c6c84e?hl=en&lnk=raot#b0385050b4c6c84e > ... > ... > It's called evolution people! Ever heard of science? So ditch the > useless Unicode and save us all a few keystrokes and bottles of > aspirin for the persistent headaches! Simplicity is beautiful!! You are right ! In the same vein, we should all also standardize on using the Java language for programming, after all /everybody/ writes code in Java. cheers, - steve -- random non tech spiel: http://lonetwin.blogspot.com/ tech randomness: http://lonehacks.blogspot.com/ what i'm stumbling into: http://lonetwin.stumbleupon.com/ From tjreedy at udel.edu Sun Aug 30 01:37:37 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Aug 2009 01:37:37 -0400 Subject: What python can NOT do? In-Reply-To: <20090829230717.14429.2004501285.divmod.xquotient.10@localhost.localdomain> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4a998465$0$1637$742ec2ed@news.sonic.net> <20090829230717.14429.2004501285.divmod.xquotient.10@localhost.localdomain> Message-ID: exarkun at twistedmatrix.com wrote: > For my part, I will agree with John. I feel like Python's big > shortcomings stem from the areas he mentioned. They're related to each > other as well - the lack of a standard hampers the development of a less > naive interpreter (either one based on CPython or another one). The reference manual is *intended* to define the 'standard' Python language. > It > doesn't completely prevent such development (obviously, as CPython > continues to undergo development, and there are a number of alternate > runtimes for Python-like languages), but there's clearly a cost > associated with the fact that in order to do this development, a lot of > time has to be spent figuring out what Python *is*. This is the kind of > thing that a standard would help with. Such developers occasionally raise questions about ambiguities in the ref manual on the pydev list. This is part of the editing process. There is an effort underway to separate the CPython test suite into two parts: test of standard Python behavior, which all implementations should pass, and tests of the CPython implementation, which other implementations need not pass. It will move as fast as volunteer effort moves it. tjr From steve at REMOVE-THIS-cybersource.com.au Sun Aug 30 01:46:12 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 05:46:12 GMT Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: <002395a3$0$2930$c3e8da3@news.astraweb.com> On Sun, 30 Aug 2009 03:07:17 +0000, Neil Hodgson wrote: > Not sure if you are referring to the ? snowman character or Arctic > region languages like Canadian Aboriginal syllabic writing like ????? > which were added to Unicode 8 years after the initial version. I'd guess > that was added from political rather than marketing motives. ? was > required since it was present in Japanese character sets. If I recall correctly, the snowman was specifically added at the request of Japanese television producers, because it is a standard glyph used for representing snow when showing the weather on TV. Unicode's stated aim is to have a single universal standard for all characters needed for communication. From the Unicode Consortium: [quote] What is Unicode? Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language. ... Even for a single language like English no single encoding was adequate for all the letters, punctuation, and technical symbols in common use. These encoding systems also conflict with one another. That is, two encodings can use the same number for two different characters, or use different numbers for the same character. Any given computer (especially servers) needs to support many different encodings; yet whenever data is passed between different encodings or platforms, that data always runs the risk of corruption. Unicode is changing all that! Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language. [end quote] And from the FAQs: [quote] Unicode covers all the characters for all the writing systems of the world, modern and ancient. It also includes technical symbols, punctuations, and many other characters used in writing text. [end quote] It's not just about supporting languages used by foreigners too stupid to speak English (sarcasm!). It's about supporting business users who want a standard way of referring to dingbats and pictographs, historians who need to deal with ancient writings and obsolete characters, scientists and mathematicians who want to use mathematical symbols, editors and book publishers who want to use their own typographic symbols, including Braille, musical symbols, and even TV producers who want to include snowmen on their weather charts. The Unicode system replaces dozens of incompatible, clashing systems with a single universal, extensible system. Why would anyone want to go back to the Bad Old Days where you couldn't transfer data from one OS to another, or even from one application to another, without quote marks turning into mathematical symbols or boxes? -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 30 01:52:48 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 05:52:48 GMT Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <4a9a0988$0$1669$742ec2ed@news.sonic.net> Message-ID: <0023972f$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 22:14:55 -0700, John Nagle wrote: > It may be a bit much that Unicode supports Cretan Linear B. Thousands of historians who need to discuss Linear B would disagree. Well, hundreds. There are tens of thousands of characters available. If there's room for chess pieces, dingbats with drop shadows and numbers inside circles, there's room for actual characters from real (if extinct) languages. -- Steven From martin at v.loewis.de Sun Aug 30 01:58:39 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 30 Aug 2009 07:58:39 +0200 Subject: break unichr instead of fix ord? In-Reply-To: References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: <4A9A150F.6010503@v.loewis.de> > To reiterate, I am not advocating for any change. I > simply want to understand if there is a good reason > for limiting the use of unchr/ord on narrow builds to > a subset of the unicode characters that Python otherwise > supports. So far, it seems not and that unichr/ord > is a poster child for "purity beats practicality". I think that's actually the case. I went back to the discussions, and found that early 2.2 alpha releases did return two-byte strings from unichr, and that this was changed because Marc-Andre Lemburg insisted. Here are a few relevant messages from the archives (search for unichr) http://mail.python.org/pipermail/python-dev/2001-June/015649.html http://mail.python.org/pipermail/python-dev/2001-July/015662.html http://mail.python.org/pipermail/python-dev/2001-July/016110.html http://mail.python.org/pipermail/python-dev/2001-July/016153.html http://mail.python.org/pipermail/python-dev/2001-July/016155.html http://mail.python.org/pipermail/python-dev/2001-July/016186.html Eventually, in r28142, MAL changed it to give it its current state. Regards, Martin From nyamatongwe+thunder at gmail.com Sun Aug 30 02:17:14 2009 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 30 Aug 2009 06:17:14 GMT Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: Chris Jones: > Is the implication that the principal usefulness of such languages as > Hindi and "other Indian languages" is us selling "things" to them..? Unicode was developed by a group of US corporations: Xerox, Apple, Sun, Microsoft, ... The main motivation was to avoid dealing with multiple character set encodings since this was difficult, time consuming and expensive. > I > am not from these climes but all the same, I do find you tone of voice > rather offensive, considering that you are referring to a culture that's > about 3000 years older and 3000 richer than ours and certainly deserves > our respect. Eh? Was Unicode developed in India? China? What precisely is direspectful here? Is there a significant population that regards Unicode as their 'holy patrimony' that will suffer distress due to my post? > Maybe you didn't notice, but our plants shut down many years ago.. They > are selling _us_ their wares. Maybe your plants shut down but some of the plants I have worked at (such as the steelworks at Port Kembla) are still successfully exporting to Asia. Neil From steve at REMOVE-THIS-cybersource.com.au Sun Aug 30 02:27:32 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 06:27:32 GMT Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: <00239f52$0$2930$c3e8da3@news.astraweb.com> On Sun, 30 Aug 2009 00:22:00 -0400, Chris Jones wrote: > On Sat, Aug 29, 2009 at 11:07:17PM EDT, Neil Hodgson wrote: >> Benjamin Peterson: > >> > Like Sanskrit or Snowman language? > >> Sanskrit is mostly written in Devanagari these days which is also >> useful for selling things to people who speak Hindi and other Indian >> languages. > > Is the implication that the principal usefulness of such languages as > Hindi and "other Indian languages" is us selling "things" to them..? I > am not from these climes but all the same, I do find you tone of voice > rather offensive, I think Neil's point is that Unicode has succeeded in the wider world, outside of academic circles, because of the commercial need to communicate between cultures using different character sets. I suppose he could have worded it better, but fundamentally he's right: without the commercial need to trade across the world (information as well as physical goods) I doubt Unicode would be anything more than an interesting curiosity of use only to a few academics and linguists. > considering that you are referring to a culture that's > about 3000 years older and 3000 richer than ours and certainly deserves > our respect. Older, certainly, but richer? There's a reason that Indians come to the West rather than Westerners going to India. As Terry Pratchet has written, age is not linked to wisdom -- just because somebody is old, doesn't mean they're wise, perhaps they've just been stupid for a very long time. The same goes for cultures: old doesn't mean better. Indian culture has been responsible for many wonderful things over the millennia, but the cast system is not one of them, and any culture which glorified sati (suttee) as an act of piety is not one we should look up to. Sati was probably rare even at the height of it's popularity, and vanishingly rare now, and arguably could even be defended as the right of an adult to end their own life when they see fit, but dowry-burning is outright murder and is sadly very common across the Indian sub-continent: some estimates suggest that in the mid-1990s there were nearly 6000 such murders a year in India. If we are to be truly non-racist, we must recognise that the West does not have a monopoly on wickedness, ignorance, spite and sheer awfulness. In any case, I'm not sure we should be talking about Indian culture in the singular -- India is about as large as Western Europe, significantly more varied, and the culture has changed over time. The India which treated the Karma Sutra as a holy book is hardly the same India where people literally rioted in the street because Richard Gere gave the actress Shilpa Shetty a couple of rather theatrical and silly kisses on the cheek. -- Steven From szport at gmail.com Sun Aug 30 03:15:41 2009 From: szport at gmail.com (zaur) Date: Sun, 30 Aug 2009 00:15:41 -0700 (PDT) Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> <9205fd44-90ec-4ce6-be2a-2f82dd99e13e@r27g2000vbn.googlegroups.com> Message-ID: <109d0956-0675-4c12-94c4-1cd54d6016b3@33g2000vbe.googlegroups.com> On 30 ???, 03:22, "Gabriel Genellina" wrote: > En Sat, 29 Aug 2009 04:34:48 -0300, zaur escribi?: > > > > > On 29 ???, 08:37, "Gabriel Genellina" wrote: > >> En Fri, 28 Aug 2009 15:25:55 -0300, zaur escribi?: > >> > On 28 ???, 16:07, Bruno Desthuilliers >> > 42.desthuilli... at websiteburo.invalid> wrote: > >> >> zaur a ?crit : > > >> >> > Ok. Here is a use case: object initialization. > > >> >> Err... Looks like you really should read the FineManual(tm) - > >> >> specifically, the parts on the __init__ method. > > >> > What are you doing if 1) classes Person and Address imported from > >> > foreign module 2) __init__ method is not defined as you want? > > >> Welcome to dynamic languages! It doesn't matter *where* the class was ? > >> defined. You may add new attributes to the instance (even methods to ? > >> the class) at any time. [...4 examples...] > > > I know about these ways of object initializing. What I said is about > > using object's dictionary as nested scope in code block. Object > > initialization is just one use case. > > So we say about different things. > > Well, you asked how to proceed in certain cases and I showed several ways ? > it can be done right now, without requiring a new scope. You'll have to ? > think of another use case. > > Attribute lookup is explicit in Python, and that's a very good thing. If ? > you follow the python-ideas thread posted earlier, you'll see the kind of ? > problems an implicit attribute lookup would cause. The "with" statement is ? > necesary (and a good thing) in Pascal, but not in Python. > > Zope2 departs from this explicitness: it has a construct ? > (similar to what you propose), and I hate it profoundly every time I have ? > to edit a DTML file - I can never tell *where* an attribute comes from. ? > Another related "feature" is acquisition, a stack of namespaces where ? > objects "inherit" attributes from their containers. Same thing, a complete ? > waste of time every time I have to track a bug. > > Unless you can find a very compeling use case, I don't think this feature ? > will become part of the language anytime soon... > > -- > Gabriel Genellina The same can be said about multiple inheritance. However, multiple inheritance is a powerful tool in the hands of someone who can properly and effectively use it. From code at pizzashack.org Sun Aug 30 03:33:05 2009 From: code at pizzashack.org (Derek Martin) Date: Sun, 30 Aug 2009 02:33:05 -0500 Subject: Is behavior of += intentional for int? In-Reply-To: <0022fef9$0$2930$c3e8da3@news.astraweb.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: <20090830073305.GN20434@dragontoe.org> On Sat, Aug 29, 2009 at 07:03:23PM +0000, Steven D'Aprano wrote: > On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: > > > I thought that int as object will stay the same object after += but with > > another integer value. My intuition said me that int object which > > represent integer value should behave this way. > > If it did, then you would have this behaviour: No, you wouldn't; the behavior you described is completely different from, and incompatible with, what zaur wrote. He's saying that instead of thinking the integer value of 3 itself being the object, he expected Python's object model would behave as though the entity m is the object, and that object exists to contain an integer value. In that case, m is always m, but it has whatever integer value it is told to hold at any point in time. The self-referential addition would access the value of m, add the operand, and store the result back in the same object as the object's value. This is not the way Python works, but he's saying this is the intuitive behavior. I happen to agree, and argued at length with you and others about that very thing months ago, when some other third party posted with that exact same confusion. By contrast, your description maintains the concept of numerical value as object that Python uses, and completely misses the point. I did find the description you gave to be highly enlightening though... It highlighted perfectly, I think, exactly why it is that Python's behavior regarding numerical values as objects is *not* intuitive. Of course, intuition is highly subjective. I believe it boils down to this: People expect that objects they create are mutable. At least, unless they specify otherwise. It is so in some other programming languages which people may be likely to be familiar with (if they are not taking their first forray into the world of computing by learning Python), and even "real world" objects are essentially always mutable. If you have a 2002 Buick LeSabre, it has a number of attributes, including its length, which might be 8.5 feet, for instance. However, this is not fixed: by adding modified body parts, or as an extreme example by sawing off the trunk of the car, the length and indeed the object itself has been changed. However, despite having been modified, it is at least in some sense still the same object: it is still a 2002 Buick LeSabre, and it still has the same *identity* (the same VIN number). It's the same object, but its value(s) changed. [Not that it matters, but I do not own such a car. :)] Numbers are fundamentally different from objects. The number 3 is a symbol of the idea of the existence of three countable objects. It can not be changed (though it can be renamed, if you so choose -- just don't expect most people to know what you're talking about). It is unintuitive that 3 is an object; it is rather what we use to describe objects -- the value of the object. It is an abstract concept, and as such it is not an object at all. You cannot hear 3, taste 3, nor smell 3. You can neither see nor touch 3, though you can certainly see 3 *objects* if they are present, and you can certainly see the symbol '3' that we use to represent that idea... but you can not see three itself, because there is no such object. The only way to see three is to envision 3 of some object. The number 3 does not have a value; it IS a value (it is the symbolic representation of the value of three). To say that 3 is an object that has a value is a bit like saying the length of a car is an object that itself has a length. It just doesn't compute. THAT is why Python's behavior with regard to numerical objects is not intuitive, and frankly bizzare to me, and I dare say to others who find it so. Yes, that's right. BIZZARE. Of course, none of this is real. In the end, it's all just a bunch of wires that either have current or don't. It's only how *WE* organize and think about that current that gives it any meaning. So you're free to think about it any way you like. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From milesck at umich.edu Sun Aug 30 03:38:20 2009 From: milesck at umich.edu (Miles Kaufmann) Date: Sun, 30 Aug 2009 00:38:20 -0700 Subject: Why does this group have so much spam? In-Reply-To: <7Hnmm.176524$zq1.39243@newsfe22.iad> References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7Hnmm.176524$zq1.39243@newsfe22.iad> Message-ID: <5C6A9174-FE24-433F-8508-03FE8A4DE9D9@umich.edu> > "casebash" wrote in message > news:7294bf8b-9819-4b6d-92b2- > afc1c8042a06 at x6g2000prc.googlegroups.com... >> So much of it could be removed even by simple keyword filtering. Funny, I was just thinking recently about how *little* spam this list gets--on the other hand, I'm following it via the python-list@ mailing list. The list owners do a great job of keeping the level of spam at a minimum, though there are occasional false positives (like your post, apparently, since I'm only seeing the replies). -Miles From detlev at die-offenbachs.de Sun Aug 30 03:53:03 2009 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 30 Aug 2009 09:53:03 +0200 Subject: IDE for python similar to visual basic References: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> Message-ID: qwe rty wrote: > i have been searching for am IDE for python that is similar to Visual > Basic but had no luck.shall you help me please? eric4 should be a good candidate. http://eric-ide.python-projects.org Detlev -- Detlev Offenbach detlev at die-offenbachs.de From ubershmekel at gmail.com Sun Aug 30 03:56:31 2009 From: ubershmekel at gmail.com (RunThePun) Date: Sun, 30 Aug 2009 00:56:31 -0700 (PDT) Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> <58e91734-d03f-417c-89b1-f2717c3a9181@l5g2000yqo.googlegroups.com> <87ws4n5gfi.fsf@slice.rozzin.com> Message-ID: On Aug 29, 1:58?pm, Carl Banks wrote: > On Aug 28, 10:37?pm, Joshua Judson Rosen wrote: > > > > > > > Carl Banks writes: > > > > On Aug 28, 2:42?pm, Terry Reedy wrote: > > > > > Carl Banks wrote: > > > > > I don't think it needs a syntax for that, but I'm not so sure a method > > > > > to modify a value in place with a single key lookup wouldn't > > > > > occasioanally be useful. > > > > > Augmented assignment does that. > > > > Internally uses two lookups, one for getting, and one for setting. > > > > I think this is an unavoidable given Python's semantics. ?Look at > > > the traceback: > > > > >>> def x(): > > > ... ? ? d['a'] += 1 > > > ... > > > >>> dis.dis(x) > > > ? 2 ? ? ? ? ? 0 LOAD_GLOBAL ? ? ? ? ? ? ?0 (d) > > > ? ? ? ? ? ? ? 3 LOAD_CONST ? ? ? ? ? ? ? 1 ('a') > > > ? ? ? ? ? ? ? 6 DUP_TOPX ? ? ? ? ? ? ? ? 2 > > > ? ? ? ? ? ? ? 9 BINARY_SUBSCR > > > OK, there's one lookup, but... > > > > ? ? ? ? ? ? ?10 LOAD_CONST ? ? ? ? ? ? ? 2 (1) > > > ? ? ? ? ? ? ?13 INPLACE_ADD > > > ? ? ? ? ? ? ?14 ROT_THREE > > > ? ? ? ? ? ? ?15 STORE_SUBSCR > > > ? ? ? ? ? ? ?16 LOAD_CONST ? ? ? ? ? ? ? 0 (None) > > > ? ? ? ? ? ? ?19 RETURN_VALUE > > > ... I don't see anything in there that retrieves the value a second time.... > > STORE_SUBSCR has to look up the position in the hash table to store > the value, hence the second lookup. > > > > > > As a workaround, if lookups are expensive, > > > > > But they are not. Because (C)Python is heavily based on dict name lookup > > > > for builtins and global names and attributes, as well as overt dict > > > > lookup, must effort has gone into optimizing dict lookup. > > > > The actual lookup algorithm Python dicts use is well-optimized, yes, > > > but the dict could contain keys that have expensive comparison and > > > hash-code calculation, in which case lookup is going to be slow. > > > I'll like the originator correct me if I've made a mistake, but I read > > "lookup" as actually meaning "lookup", not "value-comparison". > > This has nothing to do with value comparison. ?I was talking about key > comparison, which happens when looking up a position in a hash table. > I was the first person to use the word "lookup" in this thread and I > specifically meant hash-table position lookup. > > > At least in part because the question, as it was posed, specifically > > related to a wrapper-class (providing a mapping ("dict like") interface) > > around a database of some sort other than Python's dict class per se. > > > How do the details of Python's native dict-type's internal (hashtable) > > algorithm matter when they're explicitly /not/ being used? > > Well it doesn't apply specifically to the OP's problem. ?I changed the > topic a bit by making it specific to dicts. ?Is that ok with you? ?Was > that not allowed? > > The OP can add a method like apply_to_value to his own class, but one > can't do that for dicts. ?Ergo why something like apply_to_value() > would be useful enough in rare circumstances where lookup is very slow > to merit a moments consideration before being rejected. > > (If dict did have a method like that, the OP would at least know which > method to override.) > > Carl Banks First of all I'd like to say thanks for this discussion, you guys are awesome. I probably should have explained my problem better to begin with and I apologize for that. So now I'll start from the top: I made a DictMixin where the keys are filenames and the values are the file contents. It was very simple and easy to do thanks to DictMixin. For example this code writes "abc" in a file named "temp.txt" and prints the contents of the file named "swallow", these files are looked up/created/deleted in the directory "spam": >>> d = FilesDict('spam') >>> d['temp.txt'] = 'abc' >>> print(d['swallow']) This was very convenient for me because I wanted to use a simple DB which could be read and edited by shell scripts and non-pythonistas, without the heavy ORM. Also, if in the future an online full featured DB would be needed, I could easily convert the DictMixin methods. So up to here I had a good solution. My problem arose when I wanted to append a string to a file which using open(..., 'ab') would have been miles more efficient because I wouldn't have to read the entire file (__getitem__) and then write the entire file back (__setitem__). The files are expected to be as big as 600 KB which will be appended 30 bytes at a time about 3 times a second. Performance-wise the system would probably work without open (..., 'ab') but it would be a real thrashing so the current solution uses a method "AddTo" as Robert suggested, sacrificing the neat getitem/setitem syntax. Just so I don't leave out any information, I actually also made a DirectoryDict for having multiple 'tables'. In this DictMixin, keys are directory names and values are FilesDict instances. So to write "European or African" to the file "/root/tmp/velocity" one would be just: >>> d = DirectoryDict("/root") >>> d["tmp"]["velocity"] = "European or African" So now I hope it's clearer why and how I wanted a special __item_iadd__ for the dictionary syntax, RunThePun From dickinsm at gmail.com Sun Aug 30 04:01:37 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 30 Aug 2009 01:01:37 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: On Aug 29, 8:03?pm, Steven D'Aprano wrote: > On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: > > I thought that int as object will stay the same object after += but with > > another integer value. My intuition said me that int object which > > represent integer value should behave this way. > > If it did, then you would have this behaviour: > > >>> n = 3 ? ? ? ? ? ? ? ? ? ? # bind the name n to the object 3 > >>> saved_id = id(n) ? ? ? ? ?# get the id of the object > >>> n += 1 ? ? ? ? ? ? ? ? ? ?# add one to the object 3 > >>> assert n == 4 ? ? ? ? ? ? # confirm that it has value four > >>> assert id(n) == saved_id ?# confirm that it is the same object > >>> m = 3 ? ? ? ? ? ? ? ? ? ? # bind the name m to the object 3 > >>> print m + 1 ? ? ? ? ? ? ? # but object 3 has been modified > > 5 I don't see how that follows. In an alternative interpretation, the int literals would all be thought of as distinct objects: that is, the line 'n = 3' creates an integer object with value 3 and binds the name n to it; the later line 'm = 3' then creates another *new* integer object with value 3 and binds the name m to it. In other words, it could work in exactly the same way as the following works in Python: >>> n = {} >>> n[1729] = 10585 >>> m = {} >>> m {} The modification to n doesn't affect m, since the two occurrences of {} give distinct dictionary objects. -- Mark From garabik-news-2005-05 at kassiopeia.juls.savba.sk Sun Aug 30 04:17:54 2009 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Sun, 30 Aug 2009 08:17:54 +0000 (UTC) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: r wrote: > Some may say well how can we possibly force countries/people to speak/ > code in a uniform manner? Well that's simple, you just stop supporting > their cryptic languages by dumping Unicode and returning to the > beautiful ASCII and adopting English as the universal world language. v> Why English? Well because it is so widely spoken. But whatever we > choose just choose one language and stick with it, perfect it, and > maintain it. > Y?know, it is na?ve to think that the ?beautiful? ASCII is sufficient for English? Besides, there is the APL... (though, you are right, we should dump those crappy old languages and use Python exclusively) -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From catalinfest at gmail.com Sun Aug 30 04:20:15 2009 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Sun, 30 Aug 2009 01:20:15 -0700 (PDT) Subject: How i follow tree folders from url Message-ID: <9f163791-417a-49e1-903b-54154ed3bc2b@p9g2000vbl.googlegroups.com> Hello ! I wanna use python to follow the tree folders from one url. Example : If url is "www.site.com/first/ and " "first" is first folder with next subfolders "01","02","03" The result of script should be : www.site.com/first/01/ www.site.com/first/02/ www.site.com/first/03/ Maybe urllib has some functions , but i don't know them. Please help me ! Thank you ! From thorsten at thorstenkampe.de Sun Aug 30 04:33:43 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 30 Aug 2009 10:33:43 +0200 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: * r (Sat, 29 Aug 2009 18:30:34 -0700 (PDT)) > We don't support a Python group in Chinese or French, so why this? "We" do - you don't (or to be more realistic, you simply didn't know it). > Makes no sense to me really. Like probably 99.99999% of all things you hear, read, see and encounter during the day. By the way: the dumbness of your "Unicode rant" would have even ashamed the great XL himself. Thorsten From thorsten at thorstenkampe.de Sun Aug 30 04:38:03 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 30 Aug 2009 10:38:03 +0200 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: * Neil Hodgson (Sun, 30 Aug 2009 06:17:14 GMT) > Chris Jones: > > > I am not from these climes but all the same, I do find you tone of > > voice rather offensive, considering that you are referring to a > > culture that's about 3000 years older and 3000 richer than ours and > > certainly deserves our respect. > > Eh? Was Unicode developed in India? China? Chris was obviously talking about Sanskrit... Thorsten From clp2 at rebertia.com Sun Aug 30 04:39:19 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 30 Aug 2009 01:39:19 -0700 Subject: How i follow tree folders from url In-Reply-To: <9f163791-417a-49e1-903b-54154ed3bc2b@p9g2000vbl.googlegroups.com> References: <9f163791-417a-49e1-903b-54154ed3bc2b@p9g2000vbl.googlegroups.com> Message-ID: <50697b2c0908300139o3247d2e3g8ef9039fd3f6f301@mail.gmail.com> On Sun, Aug 30, 2009 at 1:20 AM, catalinfest at gmail.com wrote: > Hello ! > > I wanna use python to follow the tree folders from one url. > Example : > If url is "www.site.com/first/ and " > "first" is first folder with next subfolders "01","02","03" > The result of script should be : > > www.site.com/first/01/ > www.site.com/first/02/ > www.site.com/first/03/ > Maybe urllib has some functions , but i don't know them. HTTP has no equivalent to "ls". You have to either know the format the of URLs yourself or spider the links on a given page. To generate the URLs if you know the scheme, use range() and str.zfill(). Cheers, Chris -- http://blog.rebertia.com From thorsten at thorstenkampe.de Sun Aug 30 04:43:24 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 30 Aug 2009 10:43:24 +0200 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: * Chris Jones (Sun, 30 Aug 2009 00:22:00 -0400) > On Sat, Aug 29, 2009 at 11:07:17PM EDT, Neil Hodgson wrote: > > Sanskrit is mostly written in Devanagari these days which is also > > useful for selling things to people who speak Hindi and other Indian > > languages. > > Is the implication that the principal usefulness of such languages as > Hindi and "other Indian languages" is us selling "things" to them..? I > am not from these climes but all the same, I do find you tone of voice > rather offensive, considering that you are referring to a culture that's > about 3000 years older and 3000 richer than ours and certainly deserves > our respect. Neil was obviously talking about Devanagari. Please also mind the principal difference between Neil's "also useful" and your "principal useful(ness)". Thorsten From solipsis at pitrou.net Sun Aug 30 04:48:43 2009 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sun, 30 Aug 2009 08:48:43 +0000 (UTC) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: r gmail.com> writes: > > Why should the larger world > keep supporting such antiquated languages and character sets through > Unicode? What purpose does this serve? Are we merely trying to make > everyone happy? A sort of Utopian free-language-love-fest-kinda- > thing? Can you go and troll somewhere else? Thanks. Antoine. From thorsten at thorstenkampe.de Sun Aug 30 04:53:04 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 30 Aug 2009 10:53:04 +0200 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: * John Machin (Sat, 29 Aug 2009 17:20:47 -0700 (PDT)) > On Aug 30, 8:46?am, r wrote: > > > > Take for instance the Chinese language with it's thousands of > > characters and BS, it's more of an art than a language. ?Why do we > > need such complicated languages in this day and time. Many languages > > have been perfected, (although not perfect) far beyond that of > > Chinese language. > > The Chinese language is more widely spoken than English, is quite > capable of expression in ASCII ("r tongzhi shi sha gua") and doesn't > have those pesky it's/its problems. You could also put it differently: the Chinese language (like any other language) doesn't even have "characters". It's really funny to see how someone who rants about Unicode doesn't event knows the most basic facts. Thorsten From 71david at libero.it Sun Aug 30 05:18:35 2009 From: 71david at libero.it (David) Date: Sun, 30 Aug 2009 11:18:35 +0200 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> Message-ID: <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> Il Sat, 29 Aug 2009 17:18:46 -0700 (PDT), casebash ha scritto: > So much of it could be removed even by simple keyword filtering. I think there is only one final solution to the spam pestilence: a tiny tax on email and posts. Spammers send hundreds of thousands of emails/posts a day and a tax of 0.0001$ each does not harm normal users but discurages spammers. This tax should be applied when a message is routed by a ISP server, this saves mails/posts internal to a LAN. Direct costs of this tax would be compensated by the simplified management of network traffic (70-90% of mail traffic is spam) and the reduced risk of virus infections. David From larudwer at freenet.de Sun Aug 30 05:21:46 2009 From: larudwer at freenet.de (larudwer) Date: Sun, 30 Aug 2009 11:21:46 +0200 Subject: weak reference callback References: Message-ID: "Paul Pogonyshev" schrieb im Newsbeitrag news:mailman.658.1251577954.2854.python-list at python.org... > Hi, > > Is weak reference callback called immediately after the referenced > object is deleted or at arbitrary point in time after that? I.e. is > it possible to see a dead reference before the callback is called? > > More formally, will this ever raise? > > callback_called = False > def note_deletion (ref): > callback_called = True > ref = weakref.ref (x, note_deletion) > if ref () is None and not callback_called: > raise RuntimeError ("reference is dead, yet callback hasn't been > called yet") The Manual says: "If callback is provided and not None, and the returned weakref object is still alive, the callback will be called when the object is about to be finalized; the weak reference object will be passed as the only parameter to the callback; the referent will no longer be available." This says that the Object is deleted first, and the callback functions will be called after that. Since after 'after that' IS an arbitrary point in time your example SHOULD raise. I think it is save to assume that this will never raise in an single threaded cpython application because the GIL and reference counting scheme etc. will prevent this. However, this is an implementation specific detail of the cpython runtime and it is not save to rely on this behavior. It may be completely different in an multi threaded environment or any other implementation of Python. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 30 06:34:17 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 10:34:17 GMT Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: <0023d927$0$2930$c3e8da3@news.astraweb.com> On Sun, 30 Aug 2009 02:33:05 -0500, Derek Martin wrote: > On Sat, Aug 29, 2009 at 07:03:23PM +0000, Steven D'Aprano wrote: >> On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: >> >> > I thought that int as object will stay the same object after += but >> > with another integer value. My intuition said me that int object >> > which represent integer value should behave this way. >> >> If it did, then you would have this behaviour: > > No, you wouldn't; the behavior you described is completely different > from, and incompatible with, what zaur wrote. > > He's saying that instead of thinking the integer value of 3 itself being > the object, he expected Python's object model would behave as though the > entity m is the object, and that object exists to contain an integer > value. What is "the entity m"? Is it the name m, as follows? >>> m = 3 # bind the object 3 to the name m Or is it the literal "3" (without quotes)? Or an object holding the value three? Or something else? > In that case, m is always m, > but it has whatever integer value > it is told to hold at any point in time. The self-referential addition > would access the value of m, add the operand, and store the result back > in the same object as the object's value. Ah wait, I think I get it... is m a memory location? So when you say: m = 3 the memory location that m represents is set to the value 3, and when you say: m += 1 the memory location that m represents is set to the value 4? That would be how Pascal and C (and presumably other languages) work, but not Python or Ruby or even VB (so I'm told) and similar languages. Java has a hybrid model, where a few data types (such as ints) are handled like C, and everything else is handled like Python. Consistency was never Java's strong suit. > This is not the way Python > works, but he's saying this is the intuitive behavior. It isn't intuitive if you've never been exposed to Pascal- or C-like languages. If your only programming language was Haskell, the very idea of mutating values would be alien. So I guess when you say "the intuitive behaviour", what you actually mean is "familiar". > I happen to > agree, and argued at length with you and others about that very thing > months ago, when some other third party posted with that exact same > confusion. > > By contrast, your description maintains the concept of numerical value > as object that Python uses, and completely misses the point. I did find > the description you gave to be highly enlightening though... It > highlighted perfectly, I think, exactly why it is that Python's behavior > regarding numerical values as objects is *not* intuitive. Of course, > intuition is highly subjective. What exactly is it about Python's behaviour regarding numbers that is not intuitive? That you can't do this? >>> anum = 2 >>> alist = [anum] >>> anum += 1 >>> print alist # this doesn't work [3] That won't work in any language that I know of -- as far as I am aware, the above is impossible in just about every common programming language. (My C and VB are nearly non-existent, so I may be wrong about them.) Here is Ruby's behaviour: irb(main):001:0> anum = 2 => 2 irb(main):002:0> alist = [anum] => [2] irb(main):003:0> anum += 1 => 3 irb(main):004:0> puts alist 2 => nil Just like Python. > I believe it boils down to this: People expect that objects they create > are mutable. Why would they expect that? Is there any evidence apart from the anecdotal complaints of a few people that they expect this? People complain equally when they use a mutable default value and it mutates, or that they can't use mutable objects as dict keys, so this suggests that people expect objects should be immutable and are surprised when they change. If you're going to argue by analogy with the real world (as you do further on), I think it's fair to argue that some objects are mutable (pieces of rubber that expand into a balloon when you blow into them), and some are immutable unless you expend extraordinary effort (rocks). I would be gobsmacked if my desk turned pink or changed into an armchair, I expect it to be essentially unchanging and immutable. But I fully expect a banana to turn black, then squishy, and finally white and fuzzy if I leave it long enough. > At least, unless they specify otherwise. It is so in some > other programming languages which people may be likely to be familiar > with (if they are not taking their first forray into the world of > computing by learning Python), and even "real world" objects are > essentially always mutable. [snip example of a 2002 Buick LeSabre] Be careful bringing real-world examples into this. People have been arguing about identity in the real-world for millennia. See, for example, the paradox of my great-grandfather's axe. My great-grandfather's axe is still in my family after 80 years, as good as new, although the handle has been replaced four times and the head twice. But it's still the same axe. An even older example is the paradox of the Ship of Theseus. > Numbers are fundamentally different from objects. The number 3 is a > symbol of the idea of the existence of three countable objects. It can > not be changed Doesn't this contradict your claim that people expect to be able to mutate numbers? That you should be able to do this? >>> x = 3 >>> id(x) 123456 >>> x += 1 >>> assert x == 4 >>> id(x) 123456 You can't have it both ways -- if people think of objects as mutable, and think of numbers as not-objects and unchanging, then why oh why would they find Python's numeric behaviour to be unintuitive? > (though it can be renamed, if you so choose -- just don't > expect most people to know what you're talking about). It is > unintuitive that 3 is an object; Says you. People have considered numbers to be eternal, unchanging, immutable entities going back to at least Plato. If people are comfortable thinking that there are Platonic ideal numbers, why wouldn't they think of them represented in computers as immutable objects? What I think is that some people, such as you and Zaur, have *learned* from C-like languages that numbers are mutable not-objects, and you've learned it so well that you've forgotten that you ever needed to learn it. Consequently what you actually mean when you say Python is unintuitive is that Python is not like some other language (and is like yet other languages). > it is rather what we use to describe > objects -- the value of the object. It is an abstract concept, and as > such it is not an object at all. You cannot hear 3, taste 3, nor smell > 3. You can neither see nor touch 3, though you can certainly see 3 > *objects* if they are present, and you can certainly see the symbol '3' > that we use to represent that idea... but you can not see three itself, > because there is no such object. Human beings are excellent at reifying abstract things into (imaginary) objects. We talk about letting in the cold (we actually let out the heat); we talk about souls and life-force as if they are things; we treat justice and love and mercy and hate as palpable things instead of emotions and abstract entities. Plato imagined that everything has a pure, abstract form, an ideal, and people find that intuitive: we expect that there is an archetypal "chair" that embodies everything that is chair-like and nothing which is not, if only we could find it. Numbers are no different. Reifying them into objects comes easy to people who haven't learned differently. > The only way to see three is to > envision 3 of some object. The number 3 does not have a value; it IS a > value (it is the symbolic representation of the value of three). To say > that 3 is an object that has a value is a bit like saying the length of > a car is an object that itself has a length. No, the length of a car is an object which *is* a length, it doesn't *have* a length. > It just doesn't compute. None of this explains why you would expect to be able to mutate the value three and turn it into four. I don't think your argument makes sense -- I think your explanation is tangled up in knots. Everything you say about numbers being unchangeable, immutable entities supports Python's behaviour to make numbers immutable, and yet you argue that since people expect numbers to be unchanging, they therefore expect Python ints to be mutable! This makes no sense. > THAT is why Python's behavior with regard to numerical objects is not > intuitive, and frankly bizzare to me, and I dare say to others who find > it so. > > Yes, that's right. BIZZARE. I think you have confused yourself. If the number three cannot change, and you have a label "m" associated with three, then if you add one to it, you *can't* have the three mutate into a four, because numbers cannot change. Obviously the label has to detach itself off the three and onto the four -- precisely the behaviour Python uses. Plato would surely have found this commonsensical, and I would say that it's only those who have become used to Pascal-like languages that don't. -- Steven From ptmcg at austin.rr.com Sun Aug 30 06:42:06 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 30 Aug 2009 03:42:06 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> On Aug 30, 2:33?am, Derek Martin wrote: > THAT is why Python's behavior with regard to numerical objects is > not intuitive, and frankly bizzare to me, and I dare say to others who > find it so. > > Yes, that's right. ?BIZZARE. > Can't we all just get along? I think the question boils down to "where is the object?". In this statement: a = 3 which is the object, a or 3? There exist languages (such as C++) that allow you to override the '=' assignment as a class operator. So that I could create a class where I decided that assigning an integer value to it applies some application logic, probably the setting of some fundamental attribute. In that language, 'a' is the object, and 3 is a value being assigned to it. This can cause some consternation when a reader (or worse, maintainer) isn't familiar with my code, sees this simple assignment, and figures that they can use 'a' elsewhere as a simple integer, with some surprising or disturbing results. Python just doesn't work that way. Python binds values to names. Always. In Python, "=" is not and never could be a class operator. In Python, any expression of LHS = RHS, LHS is always a name, and in this statement it is being bound to some object found by evaluating the right hand side, RHS. The bit of confusion here is that the in-place operators like +=, -=, etc. are something of a misnomer - obviously a *name* can't be incremented or decremented (unlike a pointer in C or C++). One has to see that these are really shortcuts for LHS = LHS + RHS, and once again, our LHS is just a name getting bound to the result of LHS + RHS. Is this confusing, or non-intuitive? Maybe. Do you want to write code in Python? Get used to it. It is surprising how many times we think things are "intuitive" when we really mean they are "familiar". For long-time C and Java developers, it is intuitive that variables are memory locations, and switching to Python's name model for them is non-intuitive. As for your quibble about "3 is not an object", I'm afraid that may be your own personal set of blinders. Integer constants as objects is not unique to Python, you can see it in other languages - Smalltalk and Ruby are two that I know personally. Ruby implements a loop using this interesting notation: 3.times do ...do something... end Of course, it is a core idiom of the language, and if I adopted Ruby, I would adopt its idioms and object model. Is it any odder that 3 is an object than that the string literal "Hello, World!" is an object? Perhaps we are just not reminded of it so often, because Python's int class defines no methods that are not "__" special methods (type in "dir(3)" at the Python prompt). So we never see any Python code referencing a numeric literal and immediately calling a method on it, as in Ruby's simple loop construct. But we do see methods implemented on str like split(), and so "about above across after against".split() gives me a list of the English prepositions that begin with "a". We see this kind of thing often enough, we get accustomed to the objectness of string literals. It gets to be so familiar, it eventually seems "intuitive". You yourself mentioned that intuition is subjective - unfortunately, the "intuitiveness" of a feature is often tied to its value as a coding concept, and so statements of non-intuitiveness can be interpreted as a slant against the virtue of that concept, or even against the language itself. Once we accept that 3 is an object, we clearly have to stipulate that there can be no changes allowed to it. 3 must *always* have the value of the integer between 2 and 4. So our language invokes the concept that some classes create instances that are immutable. For a Python long-timer like Mr. D'Aprano, I don't think he even consciously thinks about this kind of thing any more; his intuition has aligned with the Python stars, so he extrapolates from the OP's suggestion to the resulting aberrant behavior, as he posted it. You can dispute and rail at this core language concept if you like, but I think the more entrenched you become in the position that "'3 is an object' is bizarre", the less enjoyable your Python work will be. -- Paul From steve at REMOVE-THIS-cybersource.com.au Sun Aug 30 06:44:48 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 10:44:48 GMT Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: <0023db9f$0$2930$c3e8da3@news.astraweb.com> On Sun, 30 Aug 2009 01:01:37 -0700, Mark Dickinson wrote: > On Aug 29, 8:03?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: >> > I thought that int as object will stay the same object after += but >> > with another integer value. My intuition said me that int object >> > which represent integer value should behave this way. >> >> If it did, then you would have this behaviour: >> >> >>> n = 3 ? ? ? ? ? ? ? ? ? ? # bind the name n to the object 3 >> >>> saved_id = id(n) ? ? ? ? ?# get the id of the object n += 1 ? ? ? ? >> >>> ? ? ? ? ? ?# add one to the object 3 assert n == 4 ? ? ? ? ? ? # >> >>> confirm that it has value four assert id(n) == saved_id ?# confirm >> >>> that it is the same object m = 3 ? ? ? ? ? ? ? ? ? ? # bind the >> >>> name m to the object 3 print m + 1 ? ? ? ? ? ? ? # but object 3 has >> >>> been modified >> >> 5 > > I don't see how that follows. Okay, it follows given Python's caching of small integer objects. It also follows from the idea that there is one abstract entity which English speakers call "three" and write as 3. There's not two identical entities with value 3, or four, or a million of them, only one. But of course your alternative implementation (where every time the Python VM sees the literal 3 it creates a new integer object with that value) would also be a valid, albeit inefficient, implementation. To be honest, I didn't even think of that. -- Steven From ptmcg at austin.rr.com Sun Aug 30 06:52:36 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 30 Aug 2009 03:52:36 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> Message-ID: <71e92f9c-4094-409d-95d7-9836737d4dc2@d34g2000vbm.googlegroups.com> On Aug 30, 5:42?am, Paul McGuire wrote: > Python binds values to names. Always. In Python, "=" is not and never > could be a class operator. ?In Python, any expression of LHS = RHS, > LHS is always a name, and in this statement it is being bound to some > object found by evaluating the right hand side, RHS. > An interesting side note, and one that could be granted to the OP, is that Python *does* support the definition of class operator overrides for in-place assignment operators like += (by defining a method __iadd__). This is how numpy's values accomplish their mutability. > It is surprising how many times we > think things are "intuitive" when we really mean they are "familiar". Of course, just as I was typing my response, Steve D'Aprano beat me to the punch. Maybe it's time we added a new acronym to this group's ongoing discussions: PDWTW, or "Python doesn't work that way". -- Paul From marduk at letterboxes.org Sun Aug 30 07:09:46 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 30 Aug 2009 07:09:46 -0400 Subject: Is behavior of += intentional for int? In-Reply-To: <0023db9f$0$2930$c3e8da3@news.astraweb.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0023db9f$0$2930$c3e8da3@news.astraweb.com> Message-ID: <1251630586.9674.0.camel@centar.nbk> On Sun, 2009-08-30 at 10:44 +0000, Steven D'Aprano wrote: > It also follows from the idea that there is one abstract entity which > English speakers call "three" and write as 3. There's not two > identical > entities with value 3, or four, or a million of them, only one. That's not true. There are many different 3s in all the parallel universes. ;) -a From webcokies at yahoo.com Sun Aug 30 07:19:10 2009 From: webcokies at yahoo.com (Joni Lee) Date: Sun, 30 Aug 2009 04:19:10 -0700 (PDT) Subject: a popen question. Please help Message-ID: <473423.84282.qm@web36903.mail.mud.yahoo.com> Hi all, I write a small script texts = os.popen('top').readlines() print texts It calls the command line "top" and will print out some texts. But first I have to press the keyboard "q" to quit the subprocess "top", then the texts will be printed, otherwise it just stands by with blank. Question is. Do you know how to give "q" into my python script so that "top" is automatically quit immediately or maybe after 1s and print out the texts. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sun Aug 30 07:26:54 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 30 Aug 2009 04:26:54 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: <0221274c-994d-4130-93bb-a5fb528e7b83@x6g2000prc.googlegroups.com> On Aug 30, 12:33?am, Derek Martin wrote: [snip rant] > THAT is why Python's behavior with regard to numerical objects is > not intuitive, and frankly bizzare to me, and I dare say to others who > find it so. > > Yes, that's right. ?BIZZARE. You mean it's different from how you first learned it. Carl Banks From rolfpw at online.de Sun Aug 30 07:34:46 2009 From: rolfpw at online.de (Rolf) Date: Sun, 30 Aug 2009 13:34:46 +0200 Subject: How to install setuptools...egg? Message-ID: Hi, I would like to install setuptools for Python2.6 on Windows. Unfortunately I could only find setuptools-0.6c9-py2.6.egg but no *.exe for Python2.6. And as far as I understand I need setuptools to install a Python egg. I would be very appreciative for any help. Regards Rolf From python.list at tim.thechases.com Sun Aug 30 07:43:19 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 30 Aug 2009 06:43:19 -0500 Subject: a popen question. Please help In-Reply-To: <473423.84282.qm@web36903.mail.mud.yahoo.com> References: <473423.84282.qm@web36903.mail.mud.yahoo.com> Message-ID: <4A9A65D7.4020308@tim.thechases.com> > texts = os.popen('top').readlines() > print texts > > It calls the command line "top" and will print out some texts. > But first I have to press the keyboard "q" to quit the subprocess "top", then the texts will be printed, otherwise it just stands by with blank. > > Question > is. Do you know how to give "q" into my python script so that "top" is > automatically quit immediately or maybe after 1s and print out the texts. Well as a workaround, my version of top (on Debian) supports a "-n" parameter so you can tell it how many iterations you want it to perform before quitting. So you should be able to just use os.popen('top -n1').readlines() -tkc From clp2 at rebertia.com Sun Aug 30 07:49:17 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 30 Aug 2009 04:49:17 -0700 Subject: a popen question. Please help In-Reply-To: <4A9A65D7.4020308@tim.thechases.com> References: <473423.84282.qm@web36903.mail.mud.yahoo.com> <4A9A65D7.4020308@tim.thechases.com> Message-ID: <50697b2c0908300449i65d22994ra6d63b0bbdb1d201@mail.gmail.com> On Sun, Aug 30, 2009 at 4:43 AM, Tim Chase wrote: >> texts = os.popen('top').readlines() >> print texts >> >> It calls the command line "top" and will print out some texts. >> But first I have to press the keyboard "q" to quit the subprocess "top", >> then the texts will be printed, otherwise it just stands by with blank. >> >> Question >> is. Do you know how to give "q" into my python script so that "top" is >> automatically quit immediately or maybe after 1s and print out the texts. > > Well as a workaround, my version of top (on Debian) supports a "-n" > parameter so you can tell it how many iterations you want it to perform > before quitting. ?So you should be able to just use > > ?os.popen('top -n1').readlines() Hm, interesting. On Mac OS X's (and BSD's?) top, -n instead specifies the number of processes to list at a time (i.e. list only the top N processes), which is entirely different. Cheers, Chris From pavlovevidence at gmail.com Sun Aug 30 07:49:51 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 30 Aug 2009 04:49:51 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0023d927$0$2930$c3e8da3@news.astraweb.com> Message-ID: <051da35f-efc2-4c4a-9b87-6d7db59c4529@t11g2000prh.googlegroups.com> On Aug 30, 3:34?am, Steven D'Aprano wrote: > On Sun, 30 Aug 2009 02:33:05 -0500, Derek Martin wrote: > > On Sat, Aug 29, 2009 at 07:03:23PM +0000, Steven D'Aprano wrote: > >> On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: > > >> > I thought that int as object will stay the same object after += but > >> > with another integer value. My intuition said me that int object > >> > which represent integer value should behave this way. > > >> If it did, then you would have this behaviour: > > > No, you wouldn't; the behavior you described is completely different > > from, and incompatible with, what zaur wrote. > > > He's saying that instead of thinking the integer value of 3 itself being > > the object, he expected Python's object model would behave as though the > > entity m is the object, and that object exists to contain an integer > > value. > > What is "the entity m"? I think they (Derek and zaur) expect integer objects to be mutable. It's pretty common for people coming from "name is a location in memory" languages to have this conception of integers as an intermediate stage of learning Python's object system. Even once they've understood "everything is an object" and "names are references to objects" they won't have learned all the nuances of the system, and might still (not unreasonably) think integer objects could be mutable. However, it'd be nice if all these people didn't post here whining about how surprising and unintuitive it is and instead just said, "ah, integers are immutable, got it", quietly to themselves. Carl Banks From deets at nospam.web.de Sun Aug 30 07:51:21 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: 30 Aug 2009 11:51:21 GMT Subject: How to install setuptools...egg? References: Message-ID: <36484556273325783.562061deets-nospam.web.de@news.hansenet.de> Rolf wrote: > Hi, > > I would like to install setuptools for Python2.6 on Windows. > Unfortunately I could only find setuptools-0.6c9-py2.6.egg but no > *.exe > for Python2.6. And as far as I understand I need setuptools to install > a > Python egg. I would be very appreciative for any help. You bootstrap setuptools by downloading & executing ez_setup.py. Diez From cjw at ncf.ca Sun Aug 30 08:08:20 2009 From: cjw at ncf.ca (Colin J. Williams) Date: Sun, 30 Aug 2009 08:08:20 -0400 Subject: How to install setuptools...egg? In-Reply-To: <36484556273325783.562061deets-nospam.web.de@news.hansenet.de> References: <36484556273325783.562061deets-nospam.web.de@news.hansenet.de> Message-ID: Diez B. Roggisch wrote: > Rolf wrote: >> Hi, >> >> I would like to install setuptools for Python2.6 on Windows. >> Unfortunately I could only find setuptools-0.6c9-py2.6.egg but no >> *.exe >> for Python2.6. And as far as I understand I need setuptools to install >> a >> Python egg. I would be very appreciative for any help. > > > You bootstrap setuptools by downloading & executing ez_setup.py. > > > Diez You might try, at the command line: easy_install setuptools Colin W. From abecedarian314159 at yahoo.com Sun Aug 30 08:10:20 2009 From: abecedarian314159 at yahoo.com (William) Date: Sun, 30 Aug 2009 05:10:20 -0700 (PDT) Subject: Python for professsional Windows GUI apps? In-Reply-To: Message-ID: <669926.22777.qm@web110604.mail.gq1.yahoo.com> For wxFormbuilder, does it also support AUI (dockable windows,etc.)? Thanks, William --- On Wed, 8/26/09, Robert Kern wrote: From: Robert Kern Subject: Re: Python for professsional Windows GUI apps? To: python-list at python.org Date: Wednesday, August 26, 2009, 7:40 PM On 2009-08-26 18:08 PM, sturlamolden wrote: > On 26 Aug, 22:47, David C Ullrich? wrote: > >>> Nothing, except lobbying for wxFormBuilder for anyone who still doesn't >>> know of it. :) >> >> That's great. But do you know of anything I can use as a >> visual form design tool in wxPython? > > Right... I don't know if you are trying to be funny, but as I said > there is wxFormBuilder... > > 3.0 generates XRC that you can use with wxPython. > 3.1 beta generates wxPython classes you can subclass. > > Honestly, it's the best GUI builder for wxPython I know of. It's possible that he is not asking for a visual form designer tool *for* building a wxPython app, but one that can be used *inside* a wxPython app like an IDE or something similar. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." ? -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From hendrik at microcorp.co.za Sun Aug 30 08:11:15 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 30 Aug 2009 14:11:15 +0200 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <200908301411.15680.hendrik@microcorp.co.za> On Sunday 30 August 2009 02:20:47 John Machin wrote: > On Aug 30, 8:46?am, r wrote: > > Take for instance the Chinese language with it's thousands of > > characters and BS, it's more of an art than a language. ?Why do we > > need such complicated languages in this day and time. Many languages > > have been perfected, (although not perfect) far beyond that of Chinese > > language. > > The Chinese language is more widely spoken than English, is quite > capable of expression in ASCII ("r tongzhi shi sha gua") and doesn't > have those pesky it's/its problems. > > > The A-Z char set is flawless! > > ... for expressing the sounds of a very limited number of languages, > and English is *NOT* one of those. I suspect that the alphabet is not ideal for representing the sounds of _any_ language, and I would look for my proof in the plethora of things that we use when writing, other than the bare A-Z. - Punctuation, diacritics... But what really started me thinking, after reading this post of John's, read with Dennis'. - on the dissimilarity of the spoken and written Chinese - was the basic dichotomy of the two systems - a symbol for a sound vs a symbol for a word or an idea. I know that when I read, I do not actually read the characters, I recognize words, and only fall back to messing with characters when I hit something unfamiliar. So It would seem to me that r's "utopia" could sooner be realized if the former system were abandoned in favour of the latter. - and Horrors! The language of choice would not be English! Not that I agree that it would be a Utopia, whatever the language - more like a nightmare of Orwellian proportions - because the language you get taught first, moulds the way you think. And I know from personal experience that there are concepts that can be succinctly expressed in one language, that takes a lot of wordy handwaving to get across in another. So diversity would be less, creativity would suffer due to lack of cross pollination, and progress would slow or stop. - Hendrik From python.list at tim.thechases.com Sun Aug 30 08:17:08 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 30 Aug 2009 07:17:08 -0500 Subject: a popen question. Please help In-Reply-To: <50697b2c0908300449i65d22994ra6d63b0bbdb1d201@mail.gmail.com> References: <473423.84282.qm@web36903.mail.mud.yahoo.com> <4A9A65D7.4020308@tim.thechases.com> <50697b2c0908300449i65d22994ra6d63b0bbdb1d201@mail.gmail.com> Message-ID: <4A9A6DC4.5060804@tim.thechases.com> >> os.popen('top -n1').readlines() > > Hm, interesting. On Mac OS X's (and BSD's?) top, -n instead specifies > the number of processes to list at a time (i.e. list only the top N > processes), which is entirely different. [reaching over to my Mac] Looks like "top" there supports a -l parameter which does something similar. Darn "standards" :-/ -tkc From rt8396 at gmail.com Sun Aug 30 08:19:45 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 05:19:45 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <3e9ddb9b-8f61-4d8d-a25c-7e95e8a25c06@g1g2000vbr.googlegroups.com> On Aug 29, 11:05?pm, Anny Mous wrote: (snip) > How do we distinguish resume from r?sum? without accents? This is another quirk of some languages that befuddles me. What is with the ongoing language pronunciation tutorial some languages have turned into -- French is a good example (*puke*). Do you *really* need those squiggly lines and cues above letters so you won't forget how to pronounce a word. Pure ridiculousness! > Even when we succeed in banning all languages that can't be written using > A-Z, what do we do about the vast number of legacy documents? How do we > write about obsolete English letters like ? and ? without Unicode? Who gives a fig about obsolete languages, thank god they are dead and let's move on!! > > Some may say well how can we possibly force countries/people to speak/ > > code in a uniform manner? Well that's simple, you just stop supporting > > their cryptic languages by dumping Unicode and returning to the > > beautiful ASCII and adopting English as the universal world language. > > Why English? Well because it is so widely spoken. > > World population: 6.7 billion > > Number of native Mandarin speakers: 873 million > Number of native Hindi speakers: 370 million > Number of native Spanish speakers: 350 million > Number of native English speakers: 340 million > > Total number of Mandarin speakers: 1051 million > Total number of English speakers: 510 million > > http://www.vistawide.com/languages/top_30_languages.htm I was actually referring to countries where the majority of people *actually* know what a computer is and how to use it... If there culture has not caught up with western technology yet they are doomed to the fate of native American Indians. > Whichever way you look at it, we should all convert to Mandarin, not > English. Looks like we still need Unicode. see my last comment (snip entertaining assumptions) > Yes, because language differences have utterly destroyed us so many times in > the past! > > Have you thought about the difference between China, with one culture and > one spoken language for thousands of years, and Europe, with dozens of > competing cultures, competing governments, and alternate languages for just > as long? If multiple languages are so harmful, why was it the British, > French, Japanese, Russians, Germans, Italians, Austrians, Hungarians and > Americans who were occupying China during the Opium Wars and the Boxer > Rebellion, instead of the other way around? > > Strength comes from diversity, not monoculture. No strength comes from superior firepower. The Chinese culture stop evolving thousands of years ago. Who invented gun powder? Yes the Chinese and all they could do with it was create fireworks. Europeans took gun powered and started a revolution that changes the world forever -- for better and for worse, but that is how advancements work. It wasn't until western influence came along and finally nudged china into the 21st century. Europeans seek out technology and aren't dragged down by an antiquated culture which is good for innovation. If China with it's huge population thought like a European, they would rule the earth for 10,000 years. From rt8396 at gmail.com Sun Aug 30 08:25:58 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 05:25:58 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: <9077a084-bf0c-4480-b6e4-59f62558f3f4@p23g2000vbl.googlegroups.com> On Aug 30, 3:33?am, Thorsten Kampe wrote: [snip ridiculous trolling] > Thorsten Hmm, I wonder who's sock puppet you are Thorsten? From lists at cheimes.de Sun Aug 30 08:27:06 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 30 Aug 2009 14:27:06 +0200 Subject: How to install setuptools...egg? In-Reply-To: References: <36484556273325783.562061deets-nospam.web.de@news.hansenet.de> Message-ID: Colin J. Williams wrote: > You might try, at the command line: > easy_install setuptools That's not going to work. setuptools provides the easy_install command. If you have the easy_install command than setuptools is already installed. Christian From sjmachin at lexicon.net Sun Aug 30 08:41:23 2009 From: sjmachin at lexicon.net (John Machin) Date: Sun, 30 Aug 2009 05:41:23 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: On Aug 30, 4:47?pm, Dennis Lee Bieber wrote: > On Sun, 30 Aug 2009 14:05:24 +1000, Anny Mous > declaimed the following in gmane.comp.python.general: > > > Have you thought about the difference between China, with one culture and > > one spoken language for thousands of years, and Europe, with dozens of > > ? ? ? ? China has one WRITTEN language -- It has multiple SPOKEN languages ... hence Chinese movies have subtitles in Chinese. And it can't really be called one written language. For a start there are the Traditional characters and the Simplified characters. Then there are regional variations and add-ons e.g. the Hong Kong Special Character Set (now added into Unicode): not academic-only stuff, includes surnames, the "Hang" in Hang Seng Index and Hang Seng Bank, and the 5th character of the Chinese name of The Hongkong and Shanghai Banking Corporation Limited on the banknotes it issues. > (the main two being mandarin and cantonese -- with enough differences > between them that they might as well be spanish vs italian) Mandarin and Cantonese are groups of languages/dialects. Rough figures (millions): Mandarin 850, Wu 90, Min and Cantonese about 70 each. The intelligibility comparison is more like Romanian vs Portuguese, or Icelandic vs Dutch. I've heard that the PLA used Shanghainese (Wu group) as code talkers just like the USMC used Navajos. From rt8396 at gmail.com Sun Aug 30 08:49:19 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 05:49:19 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: On Aug 30, 7:11?am, Hendrik van Rooyen wrote: (snip) > I suspect that the alphabet is not ideal for representing the sounds of _any_ > language, and I would look for my proof in the plethora of things that we use > when writing, other than the bare A-Z. ? - Punctuation, diacritics... It can be made better and if that means add/removing letters or redefining what a letter represents i am fine with that. I know first hand the hypocrisy of the English language. I am thinking more on the lines of English redux! > Not that I agree that it would be a Utopia, whatever the language ?- more like > a nightmare of Orwellian proportions - because the language you get taught > first, moulds the way you think. ?And I know from personal experience that > there are concepts that can be succinctly expressed in one language, that > takes a lot of wordy handwaving to get across in another. ?So diversity would > be less, creativity would suffer due to lack of cross pollination, and > progress would slow or stop. We already live in a Orwellian language nightmare. Have you seen much change to the English language in your lifetime? i haven't. A language must constantly evolve and trim the excess cruft that pollutes it. And English has a mountain of cruft! After all our years on this planet i think it's high time to perfect a simplified language for world-wide usage. From bh at izb.knu.ac.kr Sun Aug 30 09:23:33 2009 From: bh at izb.knu.ac.kr (Byung-Hee HWANG) Date: Sun, 30 Aug 2009 22:23:33 +0900 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> Message-ID: <86vdk5o2p6.fsf@betla.izb.knu.ac.kr> casebash writes: > So much of it could be removed even by simple keyword filtering. Use python-list at python.org [1], instead. [1] http://mail.python.org/mailman/listinfo/python-list -- "He's a responsible man in his own way." -- Michael Corleone, "Chapter 25", page 363 From szport at gmail.com Sun Aug 30 09:32:22 2009 From: szport at gmail.com (zaur) Date: Sun, 30 Aug 2009 06:32:22 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: On 29 ???, 23:03, Steven D'Aprano wrote: > On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: > > I thought that int as object will stay the same object after += but with > > another integer value. My intuition said me that int object which > > represent integer value should behave this way. > > If it did, then you would have this behaviour: > > >>> n = 3 ? ? ? ? ? ? ? ? ? ? # bind the name n to the object 3 > >>> saved_id = id(n) ? ? ? ? ?# get the id of the object > >>> n += 1 ? ? ? ? ? ? ? ? ? ?# add one to the object 3 > >>> assert n == 4 ? ? ? ? ? ? # confirm that it has value four > >>> assert id(n) == saved_id ?# confirm that it is the same object > >>> m = 3 ? ? ? ? ? ? ? ? ? ? # bind the name m to the object 3 > >>> print m + 1 ? ? ? ? ? ? ? # but object 3 has been modified > > 5 > > This would be pretty disturbing behaviour, and anything but intuitive. > > Fortunately, Python avoids this behaviour by making ints immutable. You > can't change the object 3 to have any other value, it will always have > value three, and consequently n+=1 assigns a new object to n. > > -- > Steven This behavior is because small integers are cached internally. See Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> a=1 >>> c=1 >>> d=10000 >>> e=10000 >>> id(a),id(c),id(d),id(e) (16793992, 16793992, 17067336, 17067276) From rt8396 at gmail.com Sun Aug 30 09:37:19 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 06:37:19 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: On Aug 30, 7:11?am, Hendrik van Rooyen wrote: (snip) > Not that I agree that it would be a Utopia, whatever the language ?- more like > a nightmare of Orwellian proportions - because the language you get taught > first, moulds the way you think. ?And I know from personal experience that > there are concepts that can be succinctly expressed in one language, that > takes a lot of wordy handwaving to get across in another. ?So diversity would > be less, creativity would suffer due to lack of cross pollination, and > progress would slow or stop. > > - Hendrik What makes you think that diversity is lost with a single language? I say more pollination will occur and the seed will be more potent since all parties will contribute to the same pool. Sure there will be idioms of different regions but that is to be expected. But at least then i could make international crank calls without the language barrier ;-) From sergiocharpinel at gmail.com Sun Aug 30 09:51:04 2009 From: sergiocharpinel at gmail.com (Sergio Charpinel Jr.) Date: Sun, 30 Aug 2009 10:51:04 -0300 Subject: Sqlite format string In-Reply-To: <20090830032422.GA23090@cskk.homeip.net> References: <20090830032422.GA23090@cskk.homeip.net> Message-ID: Thank you very much. 2009/8/30 Cameron Simpson > On 29Aug2009 17:27, Sergio Charpinel Jr. > wrote: > | Hi, > | I have this statement cursor.execute("SELECT * from session_attribute > WHERE > | sid=%s", ( user )) > | and I'm receiving this error : > | > | TypeError: not all arguments converted during string formatting > | > | What is wrong ? > > This: > > ( user ) > > is not a tuple containing the element user. It's just user. > > This: > > ( user, ) > > is what you want. > -- > Cameron Simpson DoD#743 > http://www.cskk.ezoshosting.com/cs/ > > [Alain] had been looking at his dashboard, and had not seen me, so I > ran into him. - Jean Alesi on his qualifying prang at Imola '93 > -- Sergio Roberto Charpinel Jr. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Sun Aug 30 09:55:34 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 06:55:34 -0700 (PDT) Subject: How to install setuptools...egg? References: <36484556273325783.562061deets-nospam.web.de@news.hansenet.de> Message-ID: <2062b940-d248-47e3-adaf-2aaecd83e18c@g23g2000vbr.googlegroups.com> On Aug 30, 7:08?am, "Colin J. Williams" wrote: > You might try, at the command line: > ? ?easy_install setuptools Wait maybe you should try this command >>> help(setuptools) :-) From marduk at letterboxes.org Sun Aug 30 10:12:26 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 30 Aug 2009 10:12:26 -0400 Subject: Is behavior of += intentional for int? In-Reply-To: <051da35f-efc2-4c4a-9b87-6d7db59c4529@t11g2000prh.googlegroups.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0023d927$0$2930$c3e8da3@news.astraweb.com> <051da35f-efc2-4c4a-9b87-6d7db59c4529@t11g2000prh.googlegroups.com> Message-ID: <1251641546.14626.17.camel@centar.nbk> On Sun, 2009-08-30 at 04:49 -0700, Carl Banks wrote: > It's pretty common for people coming from "name is a location in > memory" languages to have this conception of integers as an > intermediate stage of learning Python's object system. Even once > they've understood "everything is an object" and "names are references > to objects" they won't have learned all the nuances of the system, and > might still (not unreasonably) think integer objects could be mutable. > I agree. Python (and other similar languages?) are different in that. 'x' does not point to an area in memory, where you can do anything with that area. But in Python there are objects, and they are "references" in memory that some magical "reference counter" keeps track of for us (and that's a wonderful thing). And what is 'x'? Well 'x' is just some "label" that just so happens to have the privelage of being associated with this "unnamed" object. 'x' could just as easily associate itself with another object. I think that the Blue programming language, which I have been looking at lately, makes this distinction even clearer. For example, functions are not defined by names at all. Instead of def funcname(): ... You have func{...}; If you actually want to be able to reference the function later (as you probably would) then it's just a simple assignment just like any other assignment: funcname = func{...}; But i think it makes it more clear that "funcname" just so happens to reference this object that's a function. It's the same basic philosophy when applied to methods: MyClass = sys.class(); MyClass.my_method = func{...}; Blue also has interesting, simple rules wrt scopes. It's a surprisingly small, simple language (yet in a very early stage of development. > However, it'd be nice if all these people didn't post here whining > about how surprising and unintuitive it is and instead just said, "ah, > integers are immutable, got it", quietly to themselves. Yes, when I was first learning Python, at least the book I used made it very clear when introducing a new type to specify that type as mutable or immutable. It's a very core concept to Python. If you choose to ignore it or refuse to understand it then you are asking for trouble. -a From catalinfest at gmail.com Sun Aug 30 10:27:10 2009 From: catalinfest at gmail.com (catafest) Date: Sun, 30 Aug 2009 07:27:10 -0700 (PDT) Subject: About diagram and python References: <030422b7-a4f8-4ea6-8708-4486da4cf595@w6g2000yqw.googlegroups.com> Message-ID: This is the software : http://projects.gnome.org/dia/ From magawake at gmail.com Sun Aug 30 10:27:10 2009 From: magawake at gmail.com (Mag Gam) Date: Sun, 30 Aug 2009 10:27:10 -0400 Subject: Parse xml file In-Reply-To: <4a969a9c$0$32665$9b4e6d93@newsspool2.arcor-online.net> References: <4a969a9c$0$32665$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1cbd6f830908300727lf4281f2wca2f5778dff181f@mail.gmail.com> XML is a structured file. I never knew you can read it line by line and process. iterparse() More info on iterparse(): http://effbot.org/zone/element-iterparse.htm On Thu, Aug 27, 2009 at 10:39 AM, Stefan Behnel wrote: > loial wrote: >> Is there a quick way to retrieve data from an xml file in python 2.4, >> rather than read the whole file? > > ElementTree is available as an external package for Py2.4 (and it's in the > stdlib xml.etree package since 2.5). > > It's pretty much the easiest way to get data out of XML files. > > If your statement "rather than read the whole file" was referring to the > file size, note that the C implementation "cElementTree" of ElementTree is > very memory efficient, so you might still get away with just reading the > whole file into memory. There's also the iterparse() function which > supports iterative parsing of an XML file and thus allows intermediate > cleanup of used data. > > Stefan > -- > http://mail.python.org/mailman/listinfo/python-list > From catalinfest at gmail.com Sun Aug 30 10:49:52 2009 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Sun, 30 Aug 2009 07:49:52 -0700 (PDT) Subject: How i follow tree folders from url Message-ID: <27fb7927-d3cd-446f-93b5-68bd2125c2ce@h30g2000vbr.googlegroups.com> Hello ! I wanna use python to follow the tree folders from one url to get data about dirs and folders. Example : If url is "www.site.com/first/ and " "first" is first folder with next subfolders "01","02","03" The result of script should be : www.site.com/first/01/ www.site.com/first/02/ www.site.com/first/03/ What is a easy way to make this ? From zuo at chopin.edu.pl Sun Aug 30 10:51:23 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sun, 30 Aug 2009 16:51:23 +0200 Subject: An assessment of the Unicode standard In-Reply-To: <200908301411.15680.hendrik@microcorp.co.za> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <200908301411.15680.hendrik@microcorp.co.za> Message-ID: 30-08-2009 o 14:11:15 Hendrik van Rooyen wrote: > a nightmare of Orwellian proportions - because the language you get > taught first, moulds the way you think. And I know from personal > experience that > there are concepts that can be succinctly expressed in one language, that > takes a lot of wordy handwaving to get across in another. So diversity > would be less, creativity would suffer due to lack of cross pollination, > and progress would slow or stop. That's the point! Even in the case of programming languages we say about 'culture' and 'way of thinking' connected with each of them, though after all they are only formal constructs. In case of natural languages it's incomparably richer and more complex. Each natural language has richness of culture and ages of history -- behind that language and recorded in it in many ways. Most probably such an unification would mean terrible impoverishment of our (humans') culture and, as a result, terrible squandering of our intelectual, emotional, cognitive etc. potential -- especially if such unification were a result of intentional policy (and not of a slow and 'patient' process of synthesis). *j -- Jan Kaliszewski (zuo) From paul at boddie.org.uk Sun Aug 30 11:09:40 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 30 Aug 2009 08:09:40 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: On 30 Aug, 14:49, r wrote: > > It can be made better and if that means add/removing letters or > redefining what a letter represents i am fine with that. I know first > hand the hypocrisy of the English language. I am thinking more on the > lines of English redux! Elsewhere in this thread you've written... "This is another quirk of some languages that befuddles me. What is with the ongoing language pronunciation tutorial some languages have turned into -- French is a good example (*puke*). Do you *really* need those squiggly lines and cues above letters so you won't forget how to pronounce a word. Pure ridiculousness!" And, in fact, there have been schemes to simplify written English such as Initial Teaching Alphabet: http://en.wikipedia.org/wiki/Initial_Teaching_Alphabet I imagine that this is the first time you've heard of it, though. [...] > We already live in a Orwellian language nightmare. Have you seen much > change to the English language in your lifetime? i haven't. Then you aren't paying attention. Especially in places where English isn't the first language, there is a lot of modification of English that is then considered an acceptable version of the language - this is one way in which languages change. Elsewhere, you wrote this... "What makes you think that diversity is lost with a single language? I say more pollination will occur and the seed will be more potent since all parties will contribute to the same pool." Parties are contributing to the same language already. It's just not the only language that they contribute to. >From what you've written, I get the impression that you don't really know any other languages, don't have much experience with non-native users of your own language, are oblivious to how languages change, and are oblivious to the existence of various attempts to "improve" the English language in the past in ways similar to those you appear to advocate, albeit incoherently: do you want to know how to pronounce a word from its spelling or not? Add to that a complete lack of appreciation for the relationship between language and culture, along with a perverted application of evolutionary models to such things, and you come across as a lazy cultural supremacist who regards everyone else's language as superfluous apart from his own. If you're just having problems with UnicodeDecodeError, at least have the honesty to say so instead of parading something not too short of bigotry in a public forum. Paul From mike at mhuffman.com Sun Aug 30 11:39:37 2009 From: mike at mhuffman.com (Mike) Date: Sun, 30 Aug 2009 08:39:37 -0700 (PDT) Subject: How to install setuptools...egg? References: Message-ID: <6ee4ad7f-7e78-42cb-8f0b-198f32c08b6d@i18g2000pro.googlegroups.com> > I would like to install setuptools for Python2.6 on Windows. 1. Download setuptools-0.6c9-py2.6.egg 2. Download setuptools-0.6c9.tar.gz 3. Use 7-zip from http://www.7-zip.org/ to extract ez_setup.py from setuptools-0.6c9.tar.gz 4. In a directory that contains setuptools-0.6c9-py2.6.egg and ez_setup.py run the command python ez_setup.py 5. Add C:\Python26\Scripts to your path to run easy_install Mike From rt8396 at gmail.com Sun Aug 30 12:00:07 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 09:00:07 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: On Aug 30, 10:09 am, Paul Boddie wrote: > On 30 Aug, 14:49, r wrote: Then you aren't paying attention. ...(snip: defamation of character) Hold the phone Paul you are calling me a retarded bigot and i don't much appreciate that. I think you are completely misinterpreting my post. i and i ask you read it again especially this part... [quote] BUT STOP!, before i go any further i want to respond to what i know will be condemnation from the sociology nuts out there. Yes multiculturalism is great, yes art is great, but if you can't see how the ability to communicate is severely damperd by multi-languages then you only *feel* with your heart but you apparently have no ability to reason with your mind intelligently. [/quote] I don't really care what language we adopt as long as we choose *only* one and then seek to perfect it to perfection. And also that this *one* language use simplicity as it's model. English sucks, but compared to traditional Chinese and Egyptian Hieroglyphs it's a god send. I think a good language would combine the best of the popular world languages into one super language for all. The same thing Python did for programming. But of course programming is not as evolved as natural language so we will need multiple programming languages for quite some time... And just as the internet enabled worldwide instant communication, the unification of all languages will cause a Renaissance of sorts for coloaboration which in turn will beget innovation of enormous proportions. The ability to communicate unhampered is in everyones best interest. --------------------------------------- History Lesson and the laws of Nature --------------------------------------- Look history is great but i am more concerned with the future. Learn the lessons of the past, move on, and live for the future. If you want to study the hair styles of Neanderthal women be my guest. Anybody with half a brain knows the one world government and language is coming. Why stop evolution, it is our destiny and it will improve the human experience. [Warning: facts of life ahead!!] I'll bet you weep and moan for the native Americans who where slaughtered don't you? Yes they suffered a tragic death as have many poor souls throughout history and yes they also contributed to human history and experience, but their time had come and they can only blame themselfs for it. They stopped evolving, and when you stop evolving you get left behind. We can't win wars with bows and arrows in the 21st century, we can't fly to the moon on horse back, And you damn sure can smoke a peace pipe and make all the bad things disappear. Nature can be cruel and unjust at times, but progress is absolute and that is all mother nature (and myself to some extent) really cares about. Without the survival of the fittest nothing you see, feel, touch, or experience would be. The universe would collapse upon itself and cease to exist. The system works because it is perfect. Don't knock that which you do not understand, or, you refuse to understand.. We are but pawns in an ever evolving higher order entity. And when this entity no longer has a use for us, we will be history... From sccolbert at gmail.com Sun Aug 30 12:07:58 2009 From: sccolbert at gmail.com (Chris Colbert) Date: Sun, 30 Aug 2009 12:07:58 -0400 Subject: Permanently adding to the Python path in Ubuntu In-Reply-To: References: Message-ID: <7f014ea60908300907l3d21fcb6v9ed0c51180161338@mail.gmail.com> I don't want to have to modify the path in each and every application. There has to be a way to do this... Personally, I don't agree with the Debian maintainers in the order they import anyway; it should be simple for me to overshadow system packagers. But that's another story. P.S. my first name is Steven! Cheers, Chris On Sat, Aug 29, 2009 at 11:51 PM, Sean DiZazzo wrote: > On Aug 29, 5:39?pm, Chris Colbert wrote: >> I'm having an issue with sys.path on Ubuntu. I want some of my home >> built packages to overshadow the system packages. Namely, I have built >> numpy 1.3.0 from source with atlas support, and I need it to >> overshadow the system numpy 1.2.1 which I had to drag along as a >> dependency for other stuff. I have numpy 1.3.0 installed into >> /usr/local/lib/python2.6/dist-packages/. The issue is that this >> directory is added to the path after the >> /usr/lib/python2.6/dist-packages/ is added, so python doesnt see my >> version of numpy. >> >> I have been combating this with a line in my .bashrc file: >> >> export PYTHONPATH=/usr/local/lib/python2.6/dist-packages >> >> So when I start python from the shell, everything works fine. >> >> Problems show up when python is not executed from the shell, and thus >> the path variable is never exported. This can occur when I have >> launcher in the gnome panel or i'm executing from within wing-ide. >> >> Is there a way to fix this so that the local dist-packages is added to >> sys.path before the system directory ALWAYS? I can do this by editing >> site.py but I think it's kind of bad form to do it this way. I feel >> there has to be a way to do this without root privileges. >> >> Any ideas? >> >> Cheers, >> >> Chris > > I think you can modify sys.path inside your application. > > Maybe this will work (at the top of your script): > > > import sys > sys.path[0] = "/usr/local/lib/python2.6/dist-packages" > > import numpy > > > PS. ?Say hi to Steven for me! > > ~Sean > -- > http://mail.python.org/mailman/listinfo/python-list > From lists at cheimes.de Sun Aug 30 12:29:22 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 30 Aug 2009 18:29:22 +0200 Subject: Permanently adding to the Python path in Ubuntu In-Reply-To: <7f014ea60908291739r70f724fbw626c32265198b5ae@mail.gmail.com> References: <7f014ea60908291739r70f724fbw626c32265198b5ae@mail.gmail.com> Message-ID: <4A9AA8E2.50201@cheimes.de> Chris Colbert wrote: > Is there a way to fix this so that the local dist-packages is added to > sys.path before the system directory ALWAYS? I can do this by editing > site.py but I think it's kind of bad form to do it this way. I feel > there has to be a way to do this without root privileges. > > Any ideas? Have you read my blog entry about my PEP 370? http://lipyrary.blogspot.com/2009/08/how-to-add-new-module-search-path.html Christian From szport at gmail.com Sun Aug 30 12:37:49 2009 From: szport at gmail.com (zaur) Date: Sun, 30 Aug 2009 09:37:49 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0023d927$0$2930$c3e8da3@news.astraweb.com> <051da35f-efc2-4c4a-9b87-6d7db59c4529@t11g2000prh.googlegroups.com> Message-ID: <1345f68a-9f1f-4314-8b5d-dbd60a1b37a9@p23g2000vbl.googlegroups.com> On 30 ???, 15:49, Carl Banks wrote: > I think they (Derek and zaur) expect integer objects to be mutable. > > It's pretty common for people coming from "name is a location in > memory" languages to have this conception of integers as an > intermediate stage of learning Python's object system. ?Even once > they've understood "everything is an object" and "names are references > to objects" they won't have learned all the nuances of the system, and > might still (not unreasonably) think integer objects could be mutable. > > However, it'd be nice if all these people didn't post here whining > about how surprising and unintuitive it is and instead just said, "ah, > integers are immutable, got it", quietly to themselves. > > Carl Banks Very expressive. I use python many years. And many years I just took python int as they are. I am also not think about names as reference to objects and so on. So this isn't the case. From hendrik at microcorp.co.za Sun Aug 30 12:40:31 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 30 Aug 2009 18:40:31 +0200 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <200908301840.31248.hendrik@microcorp.co.za> On Sunday 30 August 2009 15:37:19 r wrote: > What makes you think that diversity is lost with a single language? I am quite sure of this - it goes deeper than mere regional differences - your first language forms the way you think - and if we all get taught the same language, then on a very fundamental level we will all think in a similar way, and that loss will outweigh the normal regional or cultural differences on which you would have to rely for your diversity. Philip Larkin has explained the effect better than I can: "They f*ck you up, your mom and dad, They do not mean to, but they do. They fill you with the faults they had, And add some extra, just for you." > I > say more pollination will occur and the seed will be more potent since > all parties will contribute to the same pool. I think this effect, while it might be real, would be swamped by the loss of the real diversity. > Sure there will be > idioms of different regions but that is to be expected. But at least > then i could make international crank calls without the language > barrier ;-) You can make crank calls _now_ without a language barrier - heavy breathing is a universally understood idiom. :-) - Hendrik From code at pizzashack.org Sun Aug 30 12:40:51 2009 From: code at pizzashack.org (Derek Martin) Date: Sun, 30 Aug 2009 11:40:51 -0500 Subject: Is behavior of += intentional for int? In-Reply-To: <0023d927$0$2930$c3e8da3@news.astraweb.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0023d927$0$2930$c3e8da3@news.astraweb.com> Message-ID: <20090830164050.GO20434@dragontoe.org> On Sun, Aug 30, 2009 at 10:34:17AM +0000, Steven D'Aprano wrote: > > He's saying that instead of thinking the integer value of 3 itself being > > the object, he expected Python's object model would behave as though the > > entity m is the object, and that object exists to contain an integer > > value. > What is "the entity m"? The entity m is an object. Objects, in computer science, are abstractions created by humans to make solving a large class of problems easier to think about. An object is a piece of data, upon which you can perform programmatic actions, which are grouped together with the values contained in that data. It's an abstraction which translates, in the physical sense, to a group of memory locations with a reference in a symbol table. > Ah wait, I think I get it... is m a memory location? No, it isn't. It is an abstraction in the programmer's mind that sits on top of some memory. For that matter, the memory location is itself an abstraction. It is not a memory location, but a particular series of circuits which either have current or don't. It is simply convenient for us to think of it as a memory location. > That would be how Pascal and C (and presumably other languages) > work, but not Python or Ruby or even VB (so I'm told) and similar > languages. Well, except that, in fact, they do work that way. They simply present a different abstraction to the programmer than C or other languages. They have to work that way, at the lowest level, because that is how the hardware works. > > Numbers are fundamentally different from objects. The number 3 is a > > symbol of the idea of the existence of three countable objects. It can > > not be changed > > Doesn't this contradict your claim that people expect to be able to > mutate numbers? That you should be able to do this? This is where you continually fail. There is no contradiction at all. What I'm saying is that in my view, numbers CAN'T mutate; they are not objects! They are values, which are a means of describing objects. Only the objects which hold the values can mutate. However in Python they don't, and can't, but they EASILY could with a different design. You, however, seem to be completely stuck on Python's behavior with regard to numeric objects, and fail to see past that. Python's model is only one abstraction, among multiple possibilities. > You can't have it both ways -- if people think of objects as > mutable, and think of numbers as not-objects and unchanging, then > why oh why would they find Python's numeric behaviour to be > unintuitive? Because in Python, they ARE objects, which they think should be mutable, but in Python when they try to change the *value* of the object, they don't get the same object with a different value; they get a completely different object. This is counter to their experience. If you don't like the Buick example, then use algebra. We've been down this road before, so I'm probably wasting my time... In algebra, you don't assign a name to a value, you assign a value to a variable. You can, in a different problem, assign a different value to that variable, but the variable didn't change; only its value did. In Python, it's the opposite. > What I think is that some people, such as you and Zaur, have *learned* > from C-like languages that numbers are mutable not-objects, and you've > learned it so well that you've forgotten that you ever needed to learn > it. No, this is precisely why I provided the real-world examples -- to illustrate to you that there was no need to learn it in computer science, because the concept applies in the real world quite intuitively in every-day situations. I think rather it is YOU who have learned the concept in Python, and since then fail to imagine any other possible interpretation of an object, and somehow have completely forgotten the examples you encountered before Python, from algebra and from the real world. > Human beings are excellent at reifying abstract things into (imaginary) > objects. I don't know what the word "reifying" means, but irrelevant. Such things are abstract, and in fact not objects. > No, the length of a car is an object which *is* a length, it doesn't > *have* a length. It is not an object. It is an abstract idea used as a description of an object. > None of this explains why you would expect to be able to mutate the > value three and turn it into four. Again, you fail. I *DO NOT* expect that. I expect to be able to mutate the object m, changing its value from 3 to 4. > I think you have confused yourself. No Steven, on this topic, it is only you who have been confused, perpetually. Although, it could be said that Python's idea of what an object is also is itself confused... Python (or at least the docs) actually refrains from formally defining an object. The docs only say that an object has an identity, a name, and a value. Well, OK... so 3 is an object. You can bind a name to it... except that's not exactly correct. You can bind many names to it, and every time you write something like: m = 3 You are binding another name to the same object. That's intuitive? So you say. But what is the value of 3? Is it 3? How can the value of an object be the object itself? If that were true, then the value of the object is an object, which has a value... you have an infinite recursion. It's a paradox. How could you get any more unintuitive than that?! In practice it's not a paradox, because the values inside numeric objects are *not* objects. They're numerical constants, as used by the hardware (excepting that they are just an abstraction on top of current, as noted before). Python's model breaks down at that point; it is not so with most other types of objects... their values remain objects. And *that* is inconsistent. The same is true of character data as for numeric data. And that, I believe, is why Java treats these as atomic data types, rather than as objects. Because they are, in fact. They are types of data that the hardware knows how to deal with, directly. Everything else is not. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From nobody at nowhere.com Sun Aug 30 12:42:40 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 30 Aug 2009 17:42:40 +0100 Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: On Sun, 30 Aug 2009 06:54:21 +0200, Dieter Maurer wrote: >> What you propose would break the property "unichr(i) always returns >> a string of length one, if it returns anything at all". > > But getting a "ValueError" in some builds (and not in others) > is rather worse than getting unicode strings of different length.... Not necessarily. If the code assumes that unichr() always returns a single-character string, it will silently produce bogus results when unichr() returns a pair of surrogates. An exception is usually preferable to silently producing bad data. If unichr() returns a surrogate pair, what is e.g. unichr(i).isalpha() supposed to do? Using surrogates is fine in an external representation (UTF-16), but it doesn't make sense as an internal representation. Think: why do people use wchar_t[] rather than a char[] encoded in UTF-8? Because a wchar_t[] allows you to index *characters*, which you can't do with a multi-byte encoding. You can't do it with a multi-*word* encoding either. UCS-2 and UTF-16 are superficially so similar that people forget that they're completely different beasts. UCS-2 is fixed-length, UTF-16 is variable-length. This makes UTF-16 semantically much closer to UTF-8 than to UCS-2 or UCS-4. If your wchar_t is 16 bits, the only sane solution is to forego support for characters outside of the BMP. The alternative is to process wide strings in exactly the same way that you process narrow (mbcs) strings; e.g. extracting character N requires iterating over the string from the beginning until you have counted N-1 characters. This provides no benefit over using narrow strings except for a slight performance gain from halving the number of iterations. You still end up with indexing being O(n) rather than O(1). From vbabiy86 at gmail.com Sun Aug 30 12:56:07 2009 From: vbabiy86 at gmail.com (Vitaly Babiy) Date: Sun, 30 Aug 2009 12:56:07 -0400 Subject: Thread Pool Message-ID: <8abf49ac0908300956x30d41685xfa1a383adb466aea@mail.gmail.com> Hey, Any one know of a good thread pool library. I have tried a few but they don't seem to clean up after them selfs well. Thanks, Vitaly Babiy -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhodri at wildebst.demon.co.uk Sun Aug 30 12:57:23 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 30 Aug 2009 17:57:23 +0100 Subject: Is behavior of += intentional for int? In-Reply-To: <1345f68a-9f1f-4314-8b5d-dbd60a1b37a9@p23g2000vbl.googlegroups.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0023d927$0$2930$c3e8da3@news.astraweb.com> <051da35f-efc2-4c4a-9b87-6d7db59c4529@t11g2000prh.googlegroups.com> <1345f68a-9f1f-4314-8b5d-dbd60a1b37a9@p23g2000vbl.googlegroups.com> Message-ID: On Sun, 30 Aug 2009 17:37:49 +0100, zaur wrote: > On 30 ???, 15:49, Carl Banks wrote: >> I think they (Derek and zaur) expect integer objects to be mutable. >> >> It's pretty common for people coming from "name is a location in >> memory" languages to have this conception of integers as an >> intermediate stage of learning Python's object system. ?Even once >> they've understood "everything is an object" and "names are references >> to objects" they won't have learned all the nuances of the system, and >> might still (not unreasonably) think integer objects could be mutable. >> >> However, it'd be nice if all these people didn't post here whining >> about how surprising and unintuitive it is and instead just said, "ah, >> integers are immutable, got it", quietly to themselves. >> >> Carl Banks > > Very expressive. > > I use python many years. And many years I just took python int as they > are. > I am also not think about names as reference to objects and so on. Then you are doomed to surprises such as this. -- Rhodri James *-* Wildebeest Herder to the Masses From sccolbert at gmail.com Sun Aug 30 13:03:19 2009 From: sccolbert at gmail.com (Chris Colbert) Date: Sun, 30 Aug 2009 13:03:19 -0400 Subject: Permanently adding to the Python path in Ubuntu In-Reply-To: <4A9AA8E2.50201@cheimes.de> References: <7f014ea60908291739r70f724fbw626c32265198b5ae@mail.gmail.com> <4A9AA8E2.50201@cheimes.de> Message-ID: <7f014ea60908301003q5f28776q88f5603a5f885358@mail.gmail.com> Great! That was the solution I was looking for. Thanks! Chris On Sun, Aug 30, 2009 at 12:29 PM, Christian Heimes wrote: > Chris Colbert wrote: >> Is there a way to fix this so that the local dist-packages is added to >> sys.path before the system directory ALWAYS? I can do this by editing >> site.py but I think it's kind of bad form to do it this way. I feel >> there has to be a way to do this without root privileges. >> >> Any ideas? > > Have you read my blog entry about my PEP 370? > http://lipyrary.blogspot.com/2009/08/how-to-add-new-module-search-path.html > > Christian > From code at pizzashack.org Sun Aug 30 13:04:45 2009 From: code at pizzashack.org (Derek Martin) Date: Sun, 30 Aug 2009 12:04:45 -0500 Subject: Is behavior of += intentional for int? In-Reply-To: <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> Message-ID: <20090830170445.GP20434@dragontoe.org> On Sun, Aug 30, 2009 at 03:42:06AM -0700, Paul McGuire wrote: > Python binds values to names. Always. No, actually, it doesn't. It binds *objects* to names. This distinction is subtle, but important, as it is the crux of why this is confusing to people. If Python is to say that objects have values, then the object can not *be* the value that it has, because that is a paradoxical self-reference. It's an object, not a value. > Is it any odder that 3 is an object than that the string literal > "Hello, World!" is an object? Yes. Because 3 is a fundamental bit of data that the hardware knows how to deal with, requiring no higher level abstractions for the programmer to use it (though certainly, a programming language can provide them, if it is convenient). "Hello, World!" is not. They are fundamentally different in that way. > For a Python long-timer like Mr. D'Aprano, I don't think he even > consciously thinks about this kind of thing any more; his intuition > has aligned with the Python stars, so he extrapolates from the OP's > suggestion to the resulting aberrant behavior, as he posted it. I'm sure that's the case. But it's been explained to him before, and yet he still can't seem to comprehend that not everyone immediately gets this behavior, and that this is not without good reason. So, since it *has* been explained to him before, it's somewhat astonishing that he would reply to zaur's post, saying that the behavior zaur described would necessarily lead to the insane behavior that Steven described. When he makes such statements, it's tantamount to calling the OP an idiot. I find that offensive, especially considering that Steven's post displayed an overwhelming lack of understanding of what the OP was trying to say. > You can dispute and rail at this core language concept if you like, > but I think the more entrenched you become in the position that "'3 is > an object' is bizarre", the less enjoyable your Python work will be. While I did genuinely find the behavior bizarre when I encountered it, and honestly still do, I learned it quickly and moved past it. I'm not suggesting that it be changed, and I don't feel particularly strongly that it even should change. It's not so much the language I'm railing against, but the humans... -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From code at pizzashack.org Sun Aug 30 13:27:57 2009 From: code at pizzashack.org (Derek Martin) Date: Sun, 30 Aug 2009 12:27:57 -0500 Subject: Is behavior of += intentional for int? In-Reply-To: <71e92f9c-4094-409d-95d7-9836737d4dc2@d34g2000vbm.googlegroups.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> <71e92f9c-4094-409d-95d7-9836737d4dc2@d34g2000vbm.googlegroups.com> Message-ID: <20090830172757.GQ20434@dragontoe.org> On Sun, Aug 30, 2009 at 03:52:36AM -0700, Paul McGuire wrote: > > It is surprising how many times we > > think things are "intuitive" when we really mean they are "familiar". > > Of course, just as I was typing my response, Steve D'Aprano beat me to > the punch. Intuition means "The power or faculty of attaining to direct knowledge or cognition without evident rational thought and inference." Very naturally, things which behave in a familiar manner are intuitive. Familiar and intuitive are very closely tied. Correspondingly, when things look like something familiar, but behave differently, they are naturally unintuitive. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From nobody at nowhere.com Sun Aug 30 13:30:48 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 30 Aug 2009 18:30:48 +0100 Subject: (Simple?) Unicode Question References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> <002269cb$0$2930$c3e8da3@news.astraweb.com> <0023693f$0$2930$c3e8da3@news.astraweb.com> Message-ID: On Sun, 30 Aug 2009 02:36:49 +0000, Steven D'Aprano wrote: >>> So long as your terminal has a sensible encoding, and you have a good >>> quality font, you should be able to print any string you can create. >> >> UTF-8 isn't a particularly sensible encoding for terminals. > > Did I mention UTF-8? > > Out of curiosity, why do you say that UTF-8 isn't sensible for terminals? I don't think I've ever seen a terminal (whether an emulator running on a PC or a hardware terminal) which supports anything like the entire Unicode repertoire, along with right-to-left writing, complex scripts, etc. Even support for double-width characters is uncommon. If your terminal can't handle anything outside of ISO-8859-1, there isn't any advantage to using UTF-8, and some disadvantages; e.g. a typical Unix tty driver will delete the last *byte* from the input buffer when you press backspace (Linux 2.6.* has the IUTF8 flag, but this is non-standard). Historically, terminal I/O has tended to revolve around unibyte encodings, with everything except the endpoints being encoding-agnostic. Anything which falls outside of that is a dog's breakfast; it's no coincidence that the word for "messed-up text" (arising from an encoding mismatch) was borrowed from Japanese (mojibake). Life is simpler if you can use a unibyte encoding. Apart from anything else, the failure modes tend to be harmless. E.g. you get the wrong glyph rather than two glyphs where you expected one. On a 7-bit channel, you get the wrong printable character rather than a control character (this is why ISO-8859-* reserves \x80-\x9F as control codes rather than using them as printable characters). >> And "Unicode font" is an oxymoron. You can merge a whole bunch of fonts >> together and stuff them into a TTF file; that doesn't make them "a >> font", though. > > I never mentioned "Unicode font" either. In any case, there's no reason > why a skillful designer can't make a single font which covers the entire > Unicode range in a consistent style. Consistency between unrelated scripts is neither realistic nor desirable. E.g. Latin fonts tend to use uniform stroke widths unless they're specifically designed to look like handwriting, whereas Han fonts tend to prefer variable-width strokes which reflect the direction. >> The main advantage of using Unicode internally is that you can associate >> encodings with the specific points where data needs to be converted >> to/from bytes, rather than having to carry the encoding details around >> the program. > > Surely the main advantage of Unicode is that it gives you a full and > consistent range of characters not limited to the 128 characters provided > by ASCII? Nothing stops you from using other encodings, or from using multiple encodings. But using multiple encodings means keeping track of the encodings. This isn't impossible, and it may produce better results (e.g. no information loss from Han unification), but it can be a lot more work. From code at pizzashack.org Sun Aug 30 13:36:17 2009 From: code at pizzashack.org (Derek Martin) Date: Sun, 30 Aug 2009 12:36:17 -0500 Subject: Is behavior of += intentional for int? In-Reply-To: <0221274c-994d-4130-93bb-a5fb528e7b83@x6g2000prc.googlegroups.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0221274c-994d-4130-93bb-a5fb528e7b83@x6g2000prc.googlegroups.com> Message-ID: <20090830173617.GR20434@dragontoe.org> On Sun, Aug 30, 2009 at 04:26:54AM -0700, Carl Banks wrote: > On Aug 30, 12:33?am, Derek Martin wrote: > [snip rant] I was not ranting. I was explaining a perspective. > > THAT is why Python's behavior with regard to numerical objects is > > not intuitive, and frankly bizzare to me, and I dare say to others who > > find it so. > > > > Yes, that's right. ?BIZZARE. > > You mean it's different from how you first learned it. I mean exactly that I find it "strikingly out of the ordinary; odd, extravagant, or eccentric in style or mode" as Webster's defines the word. Whether it is so because it is different from how I first learned it, or for some other reason, it is so nonetheless. I have elsewhere gone into great detail about why I find it so. If you need it to be simple, then feel free to simplify it. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From brenNOSPAMbarn at NObrenSPAMbarn.net Sun Aug 30 13:43:42 2009 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Sun, 30 Aug 2009 17:43:42 GMT Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> Message-ID: Derek Martin wrote: > If Python is to say that objects have values, > then the object can not *be* the value that it has, because that is a > paradoxical self-reference. It's an object, not a value. But does it say that objects have values? I don't see where you get this idea. Consider this code: class A(object): pass class B(object): x = 0 a = A() b = B() b2 = B() b2.x = a What is the "value" of the object now bound to the name "a"? What about the "value" of the object bound to b, or b2? I would say that in Python, objects do not have values. Objects are values. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From rt8396 at gmail.com Sun Aug 30 13:48:24 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 10:48:24 -0700 (PDT) Subject: IDE for python similar to visual basic References: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> Message-ID: <6cb48259-3e42-4efe-b856-7b0f1a141024@o21g2000vbl.googlegroups.com> On Aug 28, 5:19?pm, qwe rty wrote: > i have been searching for am IDE for python that is similar to Visual > Basic but had no luck.shall you help me please? Hello qwe rty, I remember my first days with GUI programming and thinking to myself; how on earth can i write GUI code without a MS style GUI builder? Not to long after that i was coding up some pretty spectacular GUI's from nothing more than source code and loving it. [Warning: the following is only opinion!] I think a point and click GUI builder (although some may disagree) is actually detrimental to your programming skills. The ability to visualize the GUI only from the source code as you read it, is as important to a programmer as site reading sheet music is to a musician. And I like to program with the training wheels off. From rozzin at geekspace.com Sun Aug 30 13:54:17 2009 From: rozzin at geekspace.com (Joshua Judson Rosen) Date: Sun, 30 Aug 2009 13:54:17 -0400 Subject: Non-deterministic computing (was: What python can NOT do?) References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <00223e3f$0$2930$c3e8da3@news.astraweb.com> Message-ID: <87ab1h192u.fsf_-_@slice.rozzin.com> Steven D'Aprano writes: > > On Sat, 29 Aug 2009 05:37:34 +0200, Tomasz Rola wrote: > > > My private list of things that when implemented in Python would be > > ugly to the point of calling it difficult: > > > > 1. AMB operator - my very favourite. In one sentence, either language > > allows one to do it easily or one would not want to do it (in an ugly > > way). > > > > http://www.randomhacks.net/articles/2005/10/11/amb-operator > > > Fascinating, but I don't exactly see how that's actually *useful*. It > strikes me of combining all the benefits of COME FROM with the potential > performance of Bogosort, but maybe I'm being harsh. There's a chapter on this (non-deterministic computing in general, and `amb' in particular) in Abelson's & Sussman's book, `Structure and Interpretation of Computer Programs': http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-28.html#%_sec_4.3 It's an interesting read (the chapter, as well as the rest of the book). > On the other hand, it sounds rather like Prolog-like declarative > programming. I fear that, like Prolog, it risks massive performance > degradation if you don't apply the constraints in the right order. One of the classic arguments in the other direction is that imperative programming (as is common in Python ;)) risks massive *incorrect results* if you don't apply the side-effects in the right order :) -- Don't be afraid to ask (Lf.((Lx.xx) (Lr.f(rr)))). From nobody at nowhere.com Sun Aug 30 13:54:22 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 30 Aug 2009 18:54:22 +0100 Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4a998465$0$1637$742ec2ed@news.sonic.net> Message-ID: On Sat, 29 Aug 2009 23:07:17 +0000, exarkun wrote: >>> Personally, I consider Python to be a good language held back by >>>too-close ties to a naive interpreter implementation and the lack >>>of a formal standard for the language. >> >>Name one language under active development that has not been harmed by a >>formal standard. (I think C doesn't count -- there was relatively little >>development of C after the standards process started.) > > I think you must mean "harmed by a formal standard more than it has been > helped", since that's clearly the interesting thing. > > And it's a pretty difficult question to answer. How do you quantify the > harm done to a language by a standarization process? How do you > quantify the help? These are extremely difficult things to measure > objectively. For a start, you have to decide how to weight the different groups of users. For an application which is designed for end users and will be in a permanent state of flux, dealing with revisions to the language or its standard libraries are likely to be a small part of the ongoing development effort. For libraries or middleware which need to maintain a stable interface, or for code which needs extensive testing, documentation, audits, etc, even a minor update can incur significant costs. Users in the latter group will prefer languages with a stable and rigorous specification, and will tend to view any flexibility granted to the language implementors as an inconvenience. From rt8396 at gmail.com Sun Aug 30 14:01:21 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 11:01:21 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <8252056f-399d-4da5-a1da-d09468eaf149@l35g2000vba.googlegroups.com> Would someone please point me to one example where this sociology or anthropology crap has ever improved our day to day lives or moved use into the future with great innovation? A life spend studying this mumbo-jumbo is a complete waste of time when many other far more important and *real* problems need solving! To me this is nothing more than educated people going antiquing on a Saturday afternoon! All they are going to find is more useless, overpriced junk that clogs up the closets of society! From nobody at nowhere.com Sun Aug 30 14:08:34 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 30 Aug 2009 19:08:34 +0100 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <4a9a0988$0$1669$742ec2ed@news.sonic.net> Message-ID: On Sat, 29 Aug 2009 22:14:55 -0700, John Nagle wrote: > (I wish the HTML standards people would do the same. HTML 5 > should have been ASCII only (with the "&" escapes if desired) > or Unicode. No "Latin-1", no upper code pages, no JIS, etc.) IOW, you want the HTML standards to continue to be meaningless documents, and "HTML" to continue to mean "what browsers support". Because that would be the likely consequence of such a stance. Japanese websites will continue to use Shift-JIS, Japanese cellphones (or Scandanavian cellphones aimed at the Japanese market, for that matter) will continue to render websites which use Shift-JIS, and HTML 5 will be just as much a pure academic exercise as all of the other HTML standards. From ivanko.rus at gmail.com Sun Aug 30 14:13:12 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sun, 30 Aug 2009 18:13:12 +0000 Subject: a popen question. Please help In-Reply-To: <473423.84282.qm@web36903.mail.mud.yahoo.com> Message-ID: <000e0cd20f80cbfb7e04725fde8e@google.com> First, I think you should use subprocess.Popen (it's recommended by PEP-324) instead of os.popen. For example: p = subprocess.Popen(["top"], stdout = PIPE) p.stdout.readlines() And to write to stdin (in your case "q") you can use p.stdin.write("q"), or terminate the process with p.terminate(), or just specify the -n option (the number of iterations) to the value you desire. It's done in that way: subprocess.Popen(["top","-n 1"], stdout=PIPE) -------------- next part -------------- An HTML attachment was scrubbed... URL: From nobody at nowhere.com Sun Aug 30 14:13:38 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 30 Aug 2009 19:13:38 +0100 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> Message-ID: On Sun, 30 Aug 2009 11:18:35 +0200, David wrote: >> So much of it could be removed even by simple keyword filtering. > > I think there is only one final solution to the spam pestilence: a tiny tax > on email and posts. > Spammers send hundreds of thousands of emails/posts a day and a tax of > 0.0001$ each does not harm normal users but discurages spammers. Apart from the impossibility of implementing such a tax, it isn't going to discourage spammers when the tax will be paid by the owner of the compromised PC from which they're sending their spam. If you want to avoid usenet spam and don't want to filter it yourself, find a provider with more aggressive spam filter. Ultimately, it's up to the person running the news server as to which posts they will or will not accept. From code at pizzashack.org Sun Aug 30 14:21:09 2009 From: code at pizzashack.org (Derek Martin) Date: Sun, 30 Aug 2009 13:21:09 -0500 Subject: Is behavior of += intentional for int? In-Reply-To: References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> Message-ID: <20090830182109.GS20434@dragontoe.org> On Sun, Aug 30, 2009 at 05:43:42PM +0000, OKB (not okblacke) wrote: > Derek Martin wrote: > > > If Python is to say that objects have values, > > then the object can not *be* the value that it has, because that is a > > paradoxical self-reference. It's an object, not a value. > > But does it say that objects have values? I don't see where you > get this idea. Yes, it does say that. Read the docs. :) http://docs.python.org/reference/datamodel.html (paragraph 2) > class A(object): > pass > a = A() > > What is the "value" of the object now bound to the name "a" In Python, the value of objects depends on the context in which it is evaluated. But when you do that, you're not getting a value that is equivalent to object, but of some property of the object. The object has no intrinsic value until it is evaluated. In that sense, and as used by the python docs, I would say that the value of the object a is "true" -- you can use it in boolean expressions, and it will evaluate as such. > I would say that in Python, objects do not have values. > Objects are values. You can say that, but if you do you're using some definition of "value" that's only applicable in Python and programming languages which behave the same way. It would be more correct to say that an object is a collection of arbitrary data, which has a type and an identity, and that the data in that collection has a value that evaluates in context. An object is an abstract collection of data, and abstractions have no value. You can not measure them in any meaningful way. The data contained in the collection does, however, have a value. When you reference an object in an expression, what you get is not the value of the object, but the value of some peice of data about, or contained in, that object. It is this property of objects, that the value evaluated depends on the context, that I think demonstrates that an object is *not* a value. Values never change, as we've said in this thread: 3 is always 3. 'a' is always 'a'. But an object x can evaluate to many different values, depending on how it is used. The definition of the object would need to allow for it to do so, but Python allows that, and even encourages it. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From rolfpw at online.de Sun Aug 30 14:33:41 2009 From: rolfpw at online.de (Rolf) Date: Sun, 30 Aug 2009 20:33:41 +0200 Subject: How to install setuptools...egg? In-Reply-To: <6ee4ad7f-7e78-42cb-8f0b-198f32c08b6d@i18g2000pro.googlegroups.com> References: <6ee4ad7f-7e78-42cb-8f0b-198f32c08b6d@i18g2000pro.googlegroups.com> Message-ID: Mike schrieb: >> I would like to install setuptools for Python2.6 on Windows. > > 1. Download setuptools-0.6c9-py2.6.egg > 2. Download setuptools-0.6c9.tar.gz > 3. Use 7-zip from http://www.7-zip.org/ to extract ez_setup.py from > setuptools-0.6c9.tar.gz > 4. In a directory that contains setuptools-0.6c9-py2.6.egg and > ez_setup.py run the command python ez_setup.py > 5. Add C:\Python26\Scripts to your path to run easy_install > > Mike Thank you very much. Your recipe did the job. Rolf From steve at REMOVE-THIS-cybersource.com.au Sun Aug 30 14:37:38 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 18:37:38 GMT Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> Message-ID: <00244a72$0$2930$c3e8da3@news.astraweb.com> On Sun, 30 Aug 2009 12:04:45 -0500, Derek Martin wrote: > On Sun, Aug 30, 2009 at 03:42:06AM -0700, Paul McGuire wrote: >> Python binds values to names. Always. > > No, actually, it doesn't. It binds *objects* to names. This > distinction is subtle, but important, as it is the crux of why this is > confusing to people. If Python is to say that objects have values, then > the object can not *be* the value that it has, because that is a > paradoxical self-reference. It's an object, not a value. You're thinking about this too hard and tying yourself in knots trying to philosophise about it. In context of OO programming, the distinction between objects and values is fuzzy, and it depends on the context: e.g. if I have this: class MyInt(int): pass five = MyInt(5) five.thingy = 23 is thingy part of the value of the object or not? For most objects, at least for built-ins, the object *is* the value. (For custom classes you create yourself, you are free to do anything you like.) There's no need to try to distinguish between the object 3 and the value of the object 3: you're looking for a distinction that simply doesn't matter. >> Is it any odder that 3 is an object than that the string literal >> "Hello, World!" is an object? > > Yes. Because 3 is a fundamental bit of data that the hardware knows how > to deal with, requiring no higher level abstractions for the programmer > to use it (though certainly, a programming language can provide them, if > it is convenient). "Hello, World!" is not. They are fundamentally > different in that way. Nonsense on two levels. Firstly, in Python, *both* 3 and "Hello World" are complex objects, and neither are even close to the fundamental bits of data that the hardware can deal with. Secondly, in low level languages, both are nothing but a sequence of bytes, and hardware knows how to deal with bytes regardless of whether they are interpreted by the human reader as 3 or "Hello World". The compiler might stop you from adding 2371 to "Hell" or "o Wor" but the hardware would be perfectly happy to do so if asked. >> For a Python long-timer like Mr. D'Aprano, I don't think he even >> consciously thinks about this kind of thing any more; his intuition has >> aligned with the Python stars, so he extrapolates from the OP's >> suggestion to the resulting aberrant behavior, as he posted it. > > I'm sure that's the case. But it's been explained to him before, and > yet he still can't seem to comprehend that not everyone immediately gets > this behavior, and that this is not without good reason. Oh, it's obvious that not everybody gets this behaviour. I understand full well that it's different to some other languages, but not all, and so some people have their expectations violated. > So, since it *has* been explained to him before, it's somewhat > astonishing that he would reply to zaur's post, saying that the behavior > zaur described would necessarily lead to the insane behavior that Steven > described. When he makes such statements, it's tantamount to calling > the OP an idiot. Given Python's programming model and implementation, the behaviour asked for *would* lead to the crazy behaviour I described. (For the record, some early implementations of Fortran allowed the user to redefine literals like that, and I'm told that Lisp will do so too.) So what Zaur presumably saw as a little tiny difference is in fact the tip of the iceberg of a fairly major difference. I don't know how smart he is, but I'd be willing to bet he hadn't thought through the full consequences of the behaviour he'd prefer, given Python's execution model. You could make a language that behaved as he wants, and I wouldn't be surprised if Java was it, but whatever it is, it isn't Python. > I find that offensive, It's moments like this that I am reminded of a quote from Stephen Fry: "You're offended? So f***ing what?" Taking offense at an intellectual disagreement over the consequences of changes to a programming model is a good sign that you've got no rational argument to make and so have to resort to (real or pretend) outrage to win points. > especially considering that > Steven's post displayed an overwhelming lack of understanding of what > the OP was trying to say. I'm pretty sure I do understand what the OP was trying to say. He actually managed to communicate it very well. I think he expects to be able to do this: >>> n = 1 >>> id(n) 123456 >>> n += 1 >>> assert n == 2 >>> id(n) 123456 Do you disagree? What do *you* think he wants? -- Steven From paul at boddie.org.uk Sun Aug 30 15:05:54 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 30 Aug 2009 12:05:54 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <1ab2c088-bead-43fa-bf4a-3e7f4d84e871@g1g2000vbr.googlegroups.com> On 30 Aug, 18:00, r wrote: > > Hold the phone Paul you are calling me a retarded bigot and i don't > much appreciate that. I think you are completely misinterpreting my > post. i and i ask you read it again especially this part... I didn't call you a "retarded bigot", and yet I did read your post. [...] > I don't really care what language we adopt as long as we choose *only* > one and then seek to perfect it to perfection. And also that this > *one* language use simplicity as it's model. English sucks, but > compared to traditional Chinese and Egyptian Hieroglyphs it's a god > send. You don't care which language it is as long as it's the one you use. That's what this sounds like, layered on top of what you've already written (and what you write below). How about Esperanto? You have heard of Esperanto, right? Or take your pick from the other artificial languages - they're relatively popular in some places where English isn't the natural first-choice foreign language. [...] > Look history is great but i am more concerned with the future. Learn > the lessons of the past, move on, and live for the future. If you want > to study the hair styles of Neanderthal women be my guest. Anybody > with half a brain knows the one world government and language is > coming. Why stop evolution, it is our destiny and it will improve the > human experience. Again, we witness a distortion of scientific concepts through the use of political themes. > [Warning: facts of life ahead!!] Even Xah Lee's harshest critics must acknowledge that Xah delivers a less offensive, more entertaining rant than this. At least Xah has mastered the art of the expletive. > I'll bet you weep and moan for the native Americans who where > slaughtered don't you? Yes they suffered a tragic death as have many > poor souls throughout history and yes they also contributed to human > history and experience, but their time had come and they can only > blame themselfs for it. You're on a slippery slope when you claim that people deserve whatever mistreatment or misfortune comes their way through mere circumstances of birth. I suggest you step back and actually read your messages again and consider how others might interpret them. I also suggest that, unless you really wish to discuss deficiencies of Unicode with respect to Python, you don't use this list/group as a discussion forum for your ill-informed notions of "progress", but instead take them to a more appropriate forum where I'm sure people will be happy to scrutinise your ideas at their leisure. Paul From sebas0 at gmail.com Sun Aug 30 15:33:15 2009 From: sebas0 at gmail.com (Sebastian) Date: Sun, 30 Aug 2009 16:33:15 -0300 Subject: Popen question (redundant processes) Message-ID: Hello World! This is my first post on the list and I'm hoping it is the right forum and not OT, I've searched a bit on this, but, none-the-wiser! My question is on the Popen method, here is my snippet: p1 = Popen(["cat", "georgi_ddr7_allmag_kcor_in_test.dat"], stdout=PIPE ) > p2 = Popen(["fit_coeffs"], stdin=p1.stdout, stdout=PIPE) > p3 = Popen(["reconstruct_maggies"], stdin=p2.stdout,stdout=PIPE) > output_maggies_z=p3.communicate()[0] > > p1 = Popen(["cat", "georgi_ddr7_allmag_kcor_in_test.dat"], stdout=PIPE ) > p2 = Popen(["fit_coeffs"], stdin=p1.stdout, stdout=PIPE) > p4 = Popen(["reconstruct_maggies", "--band-shift", "0.1", "--redshift", > "0."], stdin=p2.stdout,stdout=PIPE) > output_maggies_z0=p4.communicate()[0] > > That is, p1 and p2 are the same, but p3 and p4 which they are passed to, are different. Is there a way to pass p1 and p2 to p3 AND p4 simultaneously, so as to not need to run p1 and p2 twice, as above? What arguments would I need to achieve this? NOTE: "georgi_ddr7_allmag_kcor_in_test.dat" is a very large file (~1E6 records) regards, - Sebastian -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Sun Aug 30 15:33:29 2009 From: aahz at pythoncraft.com (Aahz) Date: 30 Aug 2009 12:33:29 -0700 Subject: Overriding iadd for dictionary like objects References: <87ws4n5gfi.fsf@slice.rozzin.com> Message-ID: In article , RunThePun wrote: > >I made a DictMixin where the keys are filenames and the values are the >file contents. It was very simple and easy to do thanks to DictMixin. > >For example this code writes "abc" in a file named "temp.txt" and >prints the contents of the file named "swallow", these files are >looked up/created/deleted in the directory "spam": >>>> d =3D FilesDict('spam') >>>> d['temp.txt'] =3D 'abc' >>>> print(d['swallow']) > >My problem arose when I wanted to append a string to a file which >using open(..., 'ab') would have been miles more efficient because I >wouldn't have to read the entire file (__getitem__) and then write the >entire file back (__setitem__). The files are expected to be as big as >600 KB which will be appended 30 bytes at a time about 3 times a >second. Performance-wise the system would probably work without open >(..., 'ab') but it would be a real thrashing so the current solution >uses a method "AddTo" as Robert suggested, sacrificing the neat >getitem/setitem syntax. You can do mostly what you want, I think, by having __setitem__() convert string values into FileProxy() objects that have an appropriate __iadd__() method. That brings a whole new set of problems, of course. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From apt.shansen at gmail.com Sun Aug 30 15:43:44 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 30 Aug 2009 12:43:44 -0700 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: <7a9c25c20908301243r71fa3376uac02a0000e2ac27e@mail.gmail.com> > > So why the heck are we supporting such capitalistic implementations as > Unicode. Sure we must support a winders installer but Unicode, dump > it! We don't support a Python group in Chinese or French, so why this? > Makes no sense to me really. Let M$ deal with it. > Who, exactly, do you think "we" are? You're off talking about The Python Community again, aren't you. I thought we talked about that. "We" are a group of diverse people from diverse backgrounds-- national and linguistic-- and quite a few who either run our own business or are connected to businesses. A very huge chunk of folk around here quite like capitalistic implementations. Python's very business and closed-source friendly, remember? This "crusade change the world" crap is so strikingly stupid of a troll approach for this group, I'm startled that it's worked. But it has, so kudos to you! Can't you go try to get someone fired up who has some philosophical basis in the group's existence? Python's not the FSF*. It's not software-for-freedom to change the world. It's software to get things done, and keep things done down the road. ... sigh. I fed the troll. --S P.S. *And I mean no insult by this towards the FSFL. It's a political/philosophical for-the-good-of-humanity organization, is all. Good for them. -------------- next part -------------- An HTML attachment was scrubbed... URL: From apt.shansen at gmail.com Sun Aug 30 15:55:22 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 30 Aug 2009 12:55:22 -0700 Subject: Thread Pool In-Reply-To: <8abf49ac0908300956x30d41685xfa1a383adb466aea@mail.gmail.com> References: <8abf49ac0908300956x30d41685xfa1a383adb466aea@mail.gmail.com> Message-ID: <7a9c25c20908301255p13112f64q90a94a9e99fe125@mail.gmail.com> On Sun, Aug 30, 2009 at 9:56 AM, Vitaly Babiy wrote: > Hey, > Any one know of a good thread pool library. I have tried a few but they > don't seem to clean up after them selfs well. > > Thanks, > Vitaly Babiy > > As obscene as it seems, I actually use twisted's :) I mean, it's obscene not because it's badly done or anything, but because to use twisted to do threads sounds terribly wrong. But I have twisted installed anyway for a different purpose, so figured why not. It seems to work fine / scale well / clean up fine (assuming my code is correct). --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From bouncyinc at gmail.com Sun Aug 30 16:06:22 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sun, 30 Aug 2009 14:06:22 -0600 Subject: Thread Pool In-Reply-To: <7a9c25c20908301255p13112f64q90a94a9e99fe125@mail.gmail.com> References: <8abf49ac0908300956x30d41685xfa1a383adb466aea@mail.gmail.com> <7a9c25c20908301255p13112f64q90a94a9e99fe125@mail.gmail.com> Message-ID: twisted? I don't get it On Sun, Aug 30, 2009 at 1:55 PM, Stephen Hansen wrote: > > On Sun, Aug 30, 2009 at 9:56 AM, Vitaly Babiy wrote: > >> Hey, >> Any one know of a good thread pool library. I have tried a few but they >> don't seem to clean up after them selfs well. >> >> Thanks, >> Vitaly Babiy >> >> > As obscene as it seems, I actually use twisted's :) > > I mean, it's obscene not because it's badly done or anything, but because > to use twisted to do threads sounds terribly wrong. But I have twisted > installed anyway for a different purpose, so figured why not. It seems to > work fine / scale well / clean up fine (assuming my code is correct). > > --S > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From luke.leighton at googlemail.com Sun Aug 30 16:17:56 2009 From: luke.leighton at googlemail.com (lkcl) Date: Sun, 30 Aug 2009 13:17:56 -0700 (PDT) Subject: port of GWT GChart to python pyjamas Message-ID: the excellent GWT Chart Library, GChart: http://code.google.com/p/gchart/ is being ported to python, to run under the pyjamas [desktop / web] widget set: http://pyjamas.svn.sourceforge.net/viewvc/pyjamas/trunk/library/pyjamas/chart/ approximately 15 of the 30 examples and 1 of the 90 test charts have been ported already, enough to show that the libray is in a mostly useable state, even after only three days. pie-charts are proving slightly problematic (as GChartExample24, which is a pie chart editor, shows). on the TODO list is: * the rest of the examples and test charts * GWT's NumberFormat (a basic one is in place right now) * GWT's DateFormat (a basic one is in place right now) * a basic implementation of re.py (for use in pyjs) * a port of http://code.google.com/p/gwt-canvas/ (for GChart optimisation purposes) conversion of the examples from java to python is pretty straightfoward: pyjamas/contrib/java2py.py is a _very_ basic java to python converter which takes care of the majority of the global/search/ replace tricks, and also it converts all { } matched braces into the correct python indentation levels. when using java2py.py, it relies on well-formatted code (which 99.9% of GWT is, and 99.5% of GChart is). code MUST be converted to actually _have_ braces, so a single- line "if" statement will give a great deal of grief: pre-editing of the java code is therefore sometimes required. please note: no real experience of java programming is required to convert java into python with java2py.py. if anyone would like to help out with this porting project, feel free to check out the source code and submit patches to http://code.google.com/p/pyjamas/issues and contact http://groups.google.com/group/pyjamas-dev/ From apt.shansen at gmail.com Sun Aug 30 16:18:19 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 30 Aug 2009 13:18:19 -0700 Subject: Thread Pool In-Reply-To: References: <8abf49ac0908300956x30d41685xfa1a383adb466aea@mail.gmail.com> <7a9c25c20908301255p13112f64q90a94a9e99fe125@mail.gmail.com> Message-ID: <7a9c25c20908301318n742de97bydb8c9f9e63219069@mail.gmail.com> On Sun, Aug 30, 2009 at 1:06 PM, John Haggerty wrote: > twisted? I don't get it > Twisted. Big library / framework for network'd applications. Specifically, asynchronous network'd applications, really. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Aug 30 16:25:40 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 30 Aug 2009 13:25:40 -0700 Subject: Popen question (redundant processes) In-Reply-To: References: Message-ID: <50697b2c0908301325w67af40a0lfbde8418f4a89e5f@mail.gmail.com> On Sun, Aug 30, 2009 at 12:33 PM, Sebastian wrote: > Hello World! > This is my first post on the list and I'm hoping it is the right forum and > not OT, I've searched > a bit on this, but, none-the-wiser! > > My question is on the Popen method, here is my snippet: > >> p1 = Popen(["cat", "georgi_ddr7_allmag_kcor_in_test.dat"], stdout=PIPE ) >> p2 = Popen(["fit_coeffs"], stdin=p1.stdout, stdout=PIPE) >> p3 = Popen(["reconstruct_maggies"], stdin=p2.stdout,stdout=PIPE) >> output_maggies_z=p3.communicate()[0] >> >> p1 = Popen(["cat", "georgi_ddr7_allmag_kcor_in_test.dat"], stdout=PIPE ) >> p2 = Popen(["fit_coeffs"], stdin=p1.stdout, stdout=PIPE) >> p4 = Popen(["reconstruct_maggies", "--band-shift", "0.1", "--redshift", >> "0."], stdin=p2.stdout,stdout=PIPE) >> output_maggies_z0=p4.communicate()[0] >> > > That is, p1 and p2 are the same, but p3 and p4 which they are passed to, are > different. > Is there a way to pass p1 and p2 to p3 AND p4 simultaneously, so as to not > need to > run p1 and p2 twice, as above? > What arguments would I need to achieve this? > > NOTE: "georgi_ddr7_allmag_kcor_in_test.dat" is a very large file (~1E6 > records) Send the output of p2 through the unix command "tee" (http://unixhelp.ed.ac.uk/CGI/man-cgi?tee). Then put the output of tee into p3 and set p4's input to the file you specified to tee. Cheers, Chris -- http://blog.rebertia.com From exallion.long at gmail.com Sun Aug 30 16:33:45 2009 From: exallion.long at gmail.com (Mug) Date: Sun, 30 Aug 2009 13:33:45 -0700 (PDT) Subject: initilize a memory zone in python Message-ID: hello, i'm new in python, i used to program in C, i have a small problem, i tryed to do some serial port things manipulation with python. i have something like: import sys,termios fd = sys.stdin.fileno() term_conf=termios.tcgetattr(fd); now i want to modify the actuall values in term_conf zone to zero i don't see how to do it, in C we can do : bzero(&term_conf,sizeof(struct termios)); i want to know if it exist a similar function in python, thanks From pavlovevidence at gmail.com Sun Aug 30 16:52:29 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 30 Aug 2009 13:52:29 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> <71e92f9c-4094-409d-95d7-9836737d4dc2@d34g2000vbm.googlegroups.com> Message-ID: <8562f607-7bef-422b-b716-487af7c73abc@k13g2000prh.googlegroups.com> On Aug 30, 10:27?am, Derek Martin wrote: > On Sun, Aug 30, 2009 at 03:52:36AM -0700, Paul McGuire wrote: > > > It is surprising how many times we > > > think things are "intuitive" when we really mean they are "familiar". > > > Of course, just as I was typing my response, Steve D'Aprano beat me to > > the punch. > > Intuition means "The power or faculty of attaining to direct knowledge > or cognition without evident rational thought and inference." ?Very > naturally, things which behave in a familiar manner are intuitive. > Familiar and intuitive are very closely tied. ?Correspondingly, when > things look like something familiar, but behave differently, they are > naturally unintuitive. *You* find something unfamiliar, and by your logic that means it's unintuitive for everyone? Nice logic there, chief. Presumptuous much? Carl Banks From deets at nospam.web.de Sun Aug 30 16:58:54 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 30 Aug 2009 22:58:54 +0200 Subject: initilize a memory zone in python In-Reply-To: References: Message-ID: <7g07ghF2ngfq1U1@mid.uni-berlin.de> Mug schrieb: > hello, i'm new in python, i used to program in C, > i have a small problem, i tryed to do some serial port things > manipulation > with python. > i have something like: > > import sys,termios > > fd = sys.stdin.fileno() > term_conf=termios.tcgetattr(fd); > > now i want to modify the actuall values in term_conf zone to zero > i don't see how to do it, > in C we can do : bzero(&term_conf,sizeof(struct termios)); > i want to know if it exist a similar function in python, thanks In python you don't modify memory like that. For the above function, you pass a value as the one you got to tcgetattr, with values modified as you desire them. Diez From nobody at nowhere.com Sun Aug 30 17:12:49 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 30 Aug 2009 22:12:49 +0100 Subject: IDE for python similar to visual basic References: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> <6cb48259-3e42-4efe-b856-7b0f1a141024@o21g2000vbl.googlegroups.com> Message-ID: On Sun, 30 Aug 2009 10:48:24 -0700, r wrote: > I think a point and click GUI builder (although some may disagree) is > actually detrimental to your programming skills. The ability to > visualize the GUI only from the source code as you read it, is as > important to a programmer as site reading sheet music is to a > musician. And I like to program with the training wheels off. The main advantage of a GUI builder is that it helps prevent you from hard-coding the GUI into the program. You could get the same effect by coding a UIL/XRC/etc file manually, but a GUI builder tends to force it. It also allows the GUI to be edited by without requiring any programming knowledge. This eliminates the need for the GUI designer to be familiar with the programming language used (or any programming language), and allows customisation by end users. Creating a GUI programmatically is almost always the wrong approach. It tends to be adopted due to a path of least resistance, rather than any affirmative reason. From 71david at libero.it Sun Aug 30 17:23:20 2009 From: 71david at libero.it (David) Date: Sun, 30 Aug 2009 23:23:20 +0200 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> Message-ID: Il Sun, 30 Aug 2009 19:13:38 +0100, Nobody ha scritto: > Apart from the impossibility of implementing such a tax, it isn't going to > discourage spammers when the tax will be paid by the owner of the > compromised PC from which they're sending their spam. I don't agree. Each computer connected to internet is phisically connected to a carrer's hub. Each carrier can easily count smtp packets of each user as they can detect, filter and in some nations prosecute, p2p users. The owner of compromised PC should be responsible of his computer like the owner of a car is responsible of damages caused by its car. That owner should keep his computer clean as he *must* keep his car functional and safe. Today most of the people consider cyber security an optional, but all of us pay for their negligence. Those people are externalizing to the rest of the world their costs in terms of SO updating, antivirus, firewall and knowledge. This is unfair. This is mainly a matter of sensibility and culture: in '50/60s active and passive car safety was an optional, today is a must. I think it's time to switch to responsible computing and the mail-tax would charge each person of its own costs and annoyances without affectig the rest of the world. > > If you want to avoid usenet spam and don't want to filter it yourself, > find a provider with more aggressive spam filter. This is not the solution. You are saying that if your neighbour makes loud noises you can not call police to impose him to cease but you can only make your home soundproof. > Ultimately, it's up to > the person running the news server as to which posts they will or will not > accept. Are you suggesting to moderate every news server and mail server all over the world? THIS is impossible! D. From bouncyinc at gmail.com Sun Aug 30 17:30:57 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sun, 30 Aug 2009 15:30:57 -0600 Subject: Sending email In-Reply-To: References: <7fpj9tF2clhemU1@mid.individual.net> <2b3621fd-53fc-4f20-a048-3608894e52af@o9g2000prg.googlegroups.com> <7fq7aiF2mp83gU1@mid.individual.net> Message-ID: I would concur On Fri, Aug 28, 2009 at 9:49 AM, 7stud wrote: > On Aug 28, 8:18 am, Fencer > wrote: > > 7stud wrote: > > > > [snip] > > > > Thanks for your reply. After consulting the sysadmins here I was able to > > get it to work. > > > > - Fencer > > > Ok, but how about posting your code so that a future searcher will not > be left screaming, "WHAT THE EFF WAS THE SOLUTION!!" > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From barcaroller at music.net Sun Aug 30 17:37:11 2009 From: barcaroller at music.net (barcaroller) Date: Sun, 30 Aug 2009 17:37:11 -0400 Subject: PyGTK problems after Linux update... References: <7fq56dF2m6qlbU1@mid.individual.net> Message-ID: "Thomas Guettler" wrote in message news:7fq56dF2m6qlbU1 at mid.individual.net... > Looks like your pygtk package does not fit to the installed python > package. Okay, I won't disagree, but I how do if fix this? From exallion.long at gmail.com Sun Aug 30 17:59:50 2009 From: exallion.long at gmail.com (Mug) Date: Sun, 30 Aug 2009 14:59:50 -0700 (PDT) Subject: initilize a memory zone in python References: <7g07ghF2ngfq1U1@mid.uni-berlin.de> Message-ID: <18627379-8056-4ee9-b3b8-d5fd4cd0590c@y20g2000vbk.googlegroups.com> On Aug 30, 8:58?pm, "Diez B. Roggisch" wrote: > Mug schrieb: > > > hello, i'm new in python, i used to program in C, > > i have a small problem, i tryed to do some serial port things > > manipulation > > with python. > > i have something like: > > > import sys,termios > > > fd = sys.stdin.fileno() > > term_conf=termios.tcgetattr(fd); > > > now i want to modify the actuall values in term_conf ?zone to zero > > i don't see how to do it, > > in C we can do : bzero(&term_conf,sizeof(struct termios)); > > i want to know if it exist a similar function in python, thanks > > In python you don't modify memory like that. > > For the above function, you pass a value as the one you got to > tcgetattr, with values modified as you desire them. i tryed print term_conf and i saw that the term_conf is actually represent with an array in python: zsh/3 4201 [1] % python test.py [27906, 5, 1215, 35387, 15, 15, ['\x03', '\x1c', '\x7f', '\x15', '\x04', '\x00', '\x01', '\xff', '\x11', '\x13', '\x1a', '\xff', '\x12', '\x0f', '\x17', '\x16', '\xff', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00']] it's a array of 7 elements, with the seventh element it self a array, so in order to initialize them to zero, there's no other way than modify them one by one in a loop? is there a fonction like "memset" or "bzero" in python? > > Diez From tjreedy at udel.edu Sun Aug 30 18:24:00 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Aug 2009 18:24:00 -0400 Subject: quantiles of a student distribution In-Reply-To: References: Message-ID: Pierre wrote: > Hello... > > Do you know how I can calculate the quantiles of a student > distribution in pyhton ? Try searching the net for 'Python student distribution quantiles' From rt8396 at gmail.com Sun Aug 30 18:28:55 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 15:28:55 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <1ab2c088-bead-43fa-bf4a-3e7f4d84e871@g1g2000vbr.googlegroups.com> Message-ID: <59cad1ba-1162-4227-9375-d132ef030a7b@d21g2000vbm.googlegroups.com> On Aug 30, 2:05?pm, Paul Boddie wrote: (snip) > You don't care which language it is as long as it's the one you use. > That's what this sounds like, layered on top of what you've already > written (and what you write below). I said it before and i will say it again. I DON"T CARE WHAT LANGUAGE WE USE AS LONG AS IT IS A MODERN LANGUAGE FOUNDED ON IDEALS OF SIMPLICITY!!!! > How about Esperanto? You have > heard of Esperanto, right? Or take your pick from the other artificial > languages - they're relatively popular in some places where English > isn't the natural first-choice foreign language. English is by far already the de-facto lingua franca throughout the world. However it has many shortcommings. The most prevalent being idiotic pronunciation. You can thank neo-nazi-linguist and your third grade language teachers for this brainwashing. Academias raping of languages has been going on for centuries. > > Look history is great but i am more concerned with the future. Learn > > the lessons of the past, move on, and live for the future. If you want > > to study the hair styles of Neanderthal women be my guest. Anybody > > with half a brain knows the one world government and language is > > coming. Why stop evolution, it is our destiny and it will improve the > > human experience. > > Again, we witness a distortion of scientific concepts through the use > of political themes. You can deny the holocaust all you want but it still happened and so too shall the great unity! Sadly because of cultural and social fanatics like yourself, it will probably take another great war to usher in the new order. > Even Xah Lee's harshest critics must acknowledge that Xah delivers a > less offensive, more entertaining rant than this. At least Xah has > mastered the art of the expletive. So you are advocating for me to use derogatory statements in my post, no thanks i need not resort to adolescent rants to argue my points. And why do you continue to compare me to XL. Has XL *ever* helped a python user in this forum? I have, many times. I am *actually* a python programmer who cares about Python and my posts bring much vigor and intelligence to an otherwise boring NG -- like me or not. > You're on a slippery slope when you claim that people deserve whatever > mistreatment or misfortune comes their way through mere circumstances > of birth. I suggest you step back and actually read your messages > again and consider how others might interpret them. Paul: civilizations rise and fall, this is beyond our control. Every great power will utter fail at some point. Some die out like a slow burning candle, others go quickly and painfully from defeating blows in war time. This is an eventuality you must face friend. This whole save the whales BS is really getting on my nerves! Stop trying to play God Paul, it is not your decision when and where the blade shall fall. When a people stop evolving and no longer have anything productive to give to evolution, evolution stamps them out. If the Indians had developed gun power and industrialized America they might be running more than merely a casino. Oh No! Was that out of line, you will probably think so. Stay in know and you shall endure... From tjreedy at udel.edu Sun Aug 30 18:31:42 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Aug 2009 18:31:42 -0400 Subject: Why does this group have so much spam? In-Reply-To: <86vdk5o2p6.fsf@betla.izb.knu.ac.kr> References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <86vdk5o2p6.fsf@betla.izb.knu.ac.kr> Message-ID: Byung-Hee HWANG wrote: > casebash writes: > >> So much of it could be removed even by simple keyword filtering. > > Use python-list at python.org [1], instead. > > [1] http://mail.python.org/mailman/listinfo/python-list Or read python-list as a newsgroup via news.gmane.org, which mirrors python-list, not c.l.p. From tjreedy at udel.edu Sun Aug 30 18:33:30 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Aug 2009 18:33:30 -0400 Subject: Why does this group have so much spam? In-Reply-To: References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> Message-ID: Nobody wrote: > Apart from the impossibility of implementing such a tax, it isn't going to > discourage spammers when the tax will be paid by the owner of the > compromised PC from which they're sending their spam. It would encourge PC owners to not let their machine be used as a spambot. From cousinstanley at gmail.com Sun Aug 30 18:40:33 2009 From: cousinstanley at gmail.com (Cousin Stanley) Date: Sun, 30 Aug 2009 22:40:33 +0000 (UTC) Subject: Combining C and Python programs References: Message-ID: > I want to write a program that will use ode for the physics > simulation, whose python bindings are outdated. So I'm writing > the physics engine in C and want to write the drawing code in > Python. What will be the best way of making those two programs > work together? THe physics engine won't have to run concurrently > with the drawing code. It will only return some position data so > they can be drawn. You might find VPython useful .... http://www.vpython.org/ A VPython example using ode .... http://vpython.wikidot.com/forum/t-109218 -- Stanley C. Kitching Human Being Phoenix, Arizona From barcaroller at music.net Sun Aug 30 18:41:51 2009 From: barcaroller at music.net (barcaroller) Date: Sun, 30 Aug 2009 18:41:51 -0400 Subject: PyGTK problems after Linux update... References: <7fq56dF2m6qlbU1@mid.individual.net> Message-ID: "Thomas Guettler" wrote in message news:7fq56dF2m6qlbU1 at mid.individual.net... > Looks like your pygtk package does not fit to the installed python > package. Okay, I won't disagree, but how do I fix this? From rt8396 at gmail.com Sun Aug 30 19:08:46 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 16:08:46 -0700 (PDT) Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> Message-ID: On Aug 30, 4:23?pm, David <71da... at libero.it> wrote: (snip) > The owner of compromised PC should be responsible of his computer like the > owner of a car is responsible of damages caused by its car. > That owner should keep his computer clean as he *must* keep his car > functional and safe. Yes i agree but your logic is flawed. If someone cuts my brake lines and i cannot stop who is to blame? Or if someone throws nails on the highway and i crash, who is to blame? Obviously you cannot blame the car owner. However if i let my brake pads wear out until they are metal on metal and run over some poor old lady crossing the street -- well now you got me! ;) But you cannot apply this logic when a hacker compromises someones computer, it the same as cutting their brake lines. How can you honestly expect that Joe computer user will know of this infection? Do you even know where your brake lines are? Even hackers can be hacked without ever knowing it! The only sure fire way is VM's or system re- installs. > Today most of the people consider cyber security an optional, but all of us > pay for their negligence. Those people are externalizing to the rest of the > world their costs in terms of SO updating, antivirus, firewall and > knowledge. This is unfair. Yes, keeping a running AV and proper updating i agree with... > This is mainly a matter of sensibility and culture: in '50/60s active and > passive car safety was an optional, today is a must. > I think it's time to switch to responsible computing and the mail-tax would > charge each person of its own costs and annoyances without affectig the rest > of the world. What, this is madness! If you have terrorist terrorizing your country you don't tax the public when they blow up a shopping mall so you can rebuild it! No you kill the terrorist in a harsh and painful manner and make an example of them, then you seize there monies. You should direct your anger to the proper internet security authorities(and more importantly to the perpetrator's) and not the innocent victims of such attacks. I want you to sit back and think very deeply about your proposal here because it is horribly wrong. It is so easy to just slap a tax on something, yes that will solve everything. *sarcasm* > > If you want to avoid usenet spam and don't want to filter it yourself, > > find a provider with more aggressive spam filter. > > This is not the solution. You are saying that if your neighbour makes loud > noises you can not call police to impose him to cease but you can only make > your home soundproof. or you could go over and punch him in the nose, works every time for me ;-) From rt8396 at gmail.com Sun Aug 30 19:24:00 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 16:24:00 -0700 (PDT) Subject: Colors on IDLE References: <59922ab5-f8c9-429f-b1ea-9b1418aa6b71@t13g2000yqt.googlegroups.com> <8d5d283f-b0bd-4e16-97c7-d2de1a148cae@l35g2000vba.googlegroups.com> Message-ID: <45407662-a944-4e8c-922e-83095cd2ce9e@g23g2000vbr.googlegroups.com> On Aug 28, 6:27?pm, r wrote: > Have you tried saving the files as MYScriptName.py? notice the py > extension, very important ;) Just for fun try the .pyw extension and observe the result. From rt8396 at gmail.com Sun Aug 30 19:36:31 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 16:36:31 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <4a9a0988$0$1669$742ec2ed@news.sonic.net> Message-ID: On Aug 30, 1:08?pm, Nobody wrote: (snip) > Because that would be the likely consequence of such a stance. Japanese > websites will continue to use Shift-JIS, Japanese cellphones (or > Scandanavian cellphones aimed at the Japanese market, for that matter) > will continue to render websites which use Shift-JIS, and HTML 5 will be > just as much a pure academic exercise as all of the other HTML standards. Yes and this keep-everyone-happy crap will go on for centuries. Unicode will then turn into another elephant sized bloatware standard that only VB and MSDN, M$ Office, and Adobe PDF can hold a candle to. Who cares, hard drives can hold terabytes of useless junk, right? This is starting to border on OCD tendencies and i for one am getting very nervous. From david.lyon at preisshare.net Sun Aug 30 20:06:52 2009 From: david.lyon at preisshare.net (David Lyon) Date: Sun, 30 Aug 2009 20:06:52 -0400 Subject: ubuntu dist-packages In-Reply-To: <0298b834-78b4-4501-a09b-9b8da5e796c1@s15g2000yqs.googlegroups.com> References: <7fki3lF2kirnkU1@mid.uni-berlin.de> <71f5986e-6aae-46b0-8325-d67051c60a30@a13g2000yqc.googlegroups.com> <7fnftkF2m6bvdU1@mid.uni-berlin.de> <0298b834-78b4-4501-a09b-9b8da5e796c1@s15g2000yqs.googlegroups.com> Message-ID: On Thu, 27 Aug 2009 07:05:51 -0700 (PDT), Paul Boddie wrote: > No, it's the problem of the Pythonic packaging brigade that package > retrieval, building and installing is combined into one unsatisfactory > whole. Brigade? That implies a disciplined and systematic approach.. I would suggest a better term is just guerrilla fighters. There's no central planning.. no looking out for the greater good.. No sense of future.. forgive my pessimism.. > In fact, the distributions have proven themselves > to be quite competent at managing huge numbers of software packages in > a semi-automated fashion, so it's baffling that people doing work on > Pythonic packaging tools wouldn't want to learn as much as they can > about how those people manage it. That's a serious and true allegation. I think the answer is that the people that are running it aren't interested in cleaning things up for the linux or windows platform. Consensus seems to be just "remove" anything that relates to windows or linux as an approach to harmonising it. I believe that it should be harmonised. > For me, when making Debian packages, it has become easier to use the > debhelper stuff to install things like documentation and resources > than it is to figure out which special options have to be passed to > the particular distutils incarnation of the setup function in order to > get such stuff put in the right place, especially since distutils > probably still employs an ad-hoc 1990s proprietary UNIX "oh just dump > that stuff in some directory or other and forget about it" mentality. It doesn't. Actually, it can't even do that very well. 90's.... which '90s ? 1890's ? > Really, distutils should be all about *dist*ribution and even then get > out of the way as much as possible - the hard stuff is extracting the > appropriate knowledge about the built Python interpreter in order to > build extensions. Exactly. > Installation should be left to something which has > an opinion about where things should be placed on a particular system, > and which has the capability to know how to uninstall stuff - a > capability which never seems to get any closer in the distutils scene. (sigh) - it is true... David From grante at visi.com Sun Aug 30 20:25:45 2009 From: grante at visi.com (Grant Edwards) Date: Sun, 30 Aug 2009 19:25:45 -0500 Subject: initilize a memory zone in python References: Message-ID: On 2009-08-30, Mug wrote: > hello, i'm new in python, i used to program in C, i have a > small problem, i tryed to do some serial port things You're probably better off just using pyserial: http://pyserial.sourceforge.net/ If you really want to muck about with termios stuff, you can look at the posix serial module in pyserial to see how it's done. > import sys,termios > > fd = sys.stdin.fileno() > term_conf=termios.tcgetattr(fd); > > now i want to modify the actuall values in term_conf zone to > zero Have you looked at the documentation for termios.tcgettattr()? It returns a list of integers. If you want set them to zero, then just set them to zero. If you want a configuration that's all zeros, why bother calling tcgetattr() at all? Just set the configuration to zeros: term_conf = [0,0,0,0,0,0] -- Grant From grante at visi.com Sun Aug 30 20:37:15 2009 From: grante at visi.com (Grant Edwards) Date: Sun, 30 Aug 2009 19:37:15 -0500 Subject: initilize a memory zone in python References: Message-ID: On 2009-08-31, Grant Edwards wrote: > If you want a configuration that's all zeros, why bother > calling tcgetattr() at all? Just set the configuration to > zeros: > > term_conf = [0,0,0,0,0,0] Oops, I forgot about cc. That should be: term_conf = [0,0,0,0,0,0,['\x00']*32] That's why it's easier to just use pyserial ;) -- Grant From walkraft at gmail.com Sun Aug 30 20:49:52 2009 From: walkraft at gmail.com (casebash) Date: Sun, 30 Aug 2009 17:49:52 -0700 (PDT) Subject: Nice copy in interactive terminal References: <1250153823.228153@athprx03> <0dac8bc9-8f00-4f4e-bc29-b475bade7685@y10g2000prg.googlegroups.com> Message-ID: <67cb16ca-89a5-43f3-8074-990b491faa7d@a37g2000prf.googlegroups.com> I managed to get some more answers here: http://stackoverflow.com/questions/1352886/nice-copying-from-python-interpreter On Aug 14, 5:05?pm, casebash wrote: > I mainly develop on Linux these days, but if I ever end up doing > anything on windows I'll make sure to look at that. > > On Aug 13, 6:56?pm, "Elias Fotinis \(eliasf\)" > wrote: > > > "casebash" wrote: > > > I've been wondering for a while if there exists an interactive > > > terminal which has nice copy feature (ie. I can copy code without > > > getting the >>> in front of every line). > > > It would help if we knew what platform you're interested in -- your > > User-Agent is G2/1.0, but I don't know what that is. ?:o) > > > On Windows, PythonWin can copy from the interactive window without the > > prompts. > > From walkraft at gmail.com Sun Aug 30 20:50:45 2009 From: walkraft at gmail.com (casebash) Date: Sun, 30 Aug 2009 17:50:45 -0700 (PDT) Subject: Determining the metaclass References: <6f69f304-3cf1-45c8-b86d-f57751bcc2ed@d15g2000prc.googlegroups.com> <3e1b7e0b-e44c-4b34-9866-33aa7b33a3af@v37g2000prg.googlegroups.com> Message-ID: Thanks, I am silly > > > I cannot determine if a class is an instance of a particular > > metaclass. Here is my best attempt > > > >>> class tmp(type): > > > ... ? ? pass > > ...>>> def c(metaclass=tmp): > > > ... ? ? pass > > ...>>> isinstance(c, tmp) > > False > > >>> isinstance(c.__class__, tmp) > > > False > > > Can anyone explain why this fails? > > You're gonna kick yourself. > > It's because you used "def" and not "class" to define c. ?If you'd > used "class" then then first test would have worked. > > Carl Banks From rt8396 at gmail.com Sun Aug 30 20:51:28 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 17:51:28 -0700 (PDT) Subject: initilize a memory zone in python References: <7g07ghF2ngfq1U1@mid.uni-berlin.de> <18627379-8056-4ee9-b3b8-d5fd4cd0590c@y20g2000vbk.googlegroups.com> Message-ID: <2f4ad057-c88b-4fe7-8858-3511b2a10f27@y20g2000vbk.googlegroups.com> On Aug 30, 4:59?pm, Mug wrote: (snip) > is there a fonction like "memset" or "bzero" in python? Not that i know of ;). Try this link for a coverage of the Python built-in functions. You cannot write quality Python code without them. http://docs.python.org/3.1/library/functions.html What you refer to as an array is called a list round here, see this informative read http://docs.python.org/3.1/library/stdtypes.html#sequence-types-str-bytes-bytearray-list-tuple-range And be sure to check out list comprehentions too, just icing on the cake ;) python 3000 docs http://docs.python.org/3.1/ From gagsl-py2 at yahoo.com.ar Sun Aug 30 21:29:14 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Aug 2009 22:29:14 -0300 Subject: Popen question (redundant processes) References: <50697b2c0908301325w67af40a0lfbde8418f4a89e5f@mail.gmail.com> Message-ID: En Sun, 30 Aug 2009 17:25:40 -0300, Chris Rebert escribi?: > On Sun, Aug 30, 2009 at 12:33 PM, Sebastian wrote: >> Hello World! >> This is my first post on the list and I'm hoping it is the right forum >> and >> not OT, I've searched >> a bit on this, but, none-the-wiser! >> >> My question is on the Popen method, here is my snippet: >> >>> p1 = Popen(["cat", "georgi_ddr7_allmag_kcor_in_test.dat"], stdout=PIPE >>> ) >>> p2 = Popen(["fit_coeffs"], stdin=p1.stdout, stdout=PIPE) >>> p3 = Popen(["reconstruct_maggies"], stdin=p2.stdout,stdout=PIPE) >>> output_maggies_z=p3.communicate()[0] >>> >>> p1 = Popen(["cat", "georgi_ddr7_allmag_kcor_in_test.dat"], stdout=PIPE >>> ) >>> p2 = Popen(["fit_coeffs"], stdin=p1.stdout, stdout=PIPE) >>> p4 = Popen(["reconstruct_maggies", "--band-shift", "0.1", "--redshift", >>> "0."], stdin=p2.stdout,stdout=PIPE) >>> output_maggies_z0=p4.communicate()[0] >>> >> >> That is, p1 and p2 are the same, but p3 and p4 which they are passed >> to, are >> different. >> Is there a way to pass p1 and p2 to p3 AND p4 simultaneously, so as to >> not >> need to >> run p1 and p2 twice, as above? >> What arguments would I need to achieve this? >> >> NOTE: "georgi_ddr7_allmag_kcor_in_test.dat" is a very large file (~1E6 >> records) > > Send the output of p2 through the unix command "tee" > (http://unixhelp.ed.ac.uk/CGI/man-cgi?tee). Then put the output of tee > into p3 and set p4's input to the file you specified to tee. In addition to that, you can avoid the cat command (and omit p1 completely), just pass the georgi file as p2 stdin: p2 = Popen(["fit_coeffs"], stdin=open("georgi..."), ... In other words, the original shell commands are: cat georgi.dat | fit | reconstruct cat georgi.dat | fit | reconstruct --otherargs and we suggest doing: fit < georgi.dat | tee /tmp/foo | reconstruct reconstruct --otherargs < /tmp/foo -- Gabriel Genellina From timr at probo.com Sun Aug 30 23:18:41 2009 From: timr at probo.com (Tim Roberts) Date: Sun, 30 Aug 2009 20:18:41 -0700 Subject: why python got less developers ? References: <1ccf54f5-b1f5-4c4a-b782-fde1a1648cf6@l5g2000yqo.googlegroups.com> Message-ID: <3bfm959q7f430caogglsctpoc6j917d7m6@4ax.com> Esam Qanadeely wrote: >On Aug 28, 8:27?am, Tim Roberts wrote: >> Deep_Feelings wrote: >> >> >python got relatively fewer numbers of developers than other high >> >level languages like .NET , java .. etc ?why ? >> >> How do you know, and why does it matter? >> >> By the way, .NET is not a language. ?I assume you meant C#. > >you know when you go to forums and compare the number of posts and >topics ,and you know when you google and compare the number of results > >.NET= i meant all .NET languages That's hardly a fair way to categorize things. "All .NET languages" includes C++, C#, Basic, Java (in J#), Ocaml (in F#), and Python. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From drsalists at gmail.com Sun Aug 30 23:27:55 2009 From: drsalists at gmail.com (Dan Stromberg) Date: Sun, 30 Aug 2009 20:27:55 -0700 Subject: Reading binary files In-Reply-To: <4eb0089f0908241443p348eea3dxd57581e37f94d0bd@mail.gmail.com> References: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> <1251125039.23757.0.camel@brotherus.corp.redhat.com> <9c8c445f0908240818k1ae301acr49c65ccb21435cd7@mail.gmail.com> <9c8c445f0908240950h24e5bfccoc9ae809c1048be5d@mail.gmail.com> <4eb0089f0908241443p348eea3dxd57581e37f94d0bd@mail.gmail.com> Message-ID: <4A9B433B.8050203@gmail.com> David Robinow wrote: >>> This works for a simple binary file, but the actual file I'm trying to >>> read is give throwing an error that the file cannot be found. Here is the >>> name of the my file: >>> 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars >>> >>> Should python have trouble reading this file name or extension? >>> >> I'm having trouble with the filename: >> 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars >> >> It throws an error with that file name, When I change it to something like >> sample.txt it runs, but the data is still garbled. Is there any reason why I >> can't use the above file name? If I'm using 'rb' to read the binary file why >> is it still garbled? >> > I don't think it's garbled. It's a binary file. What do you expect? > > It's been over ten years since I've worked with any JSTARS stuff so I > can't give you any details but you almost certainly have some sort of > imagery. The military has a lot of bizarre formats and whoever sent > you the data should have included a data sheet describing the format > (or a pointer to such). Ideally, you'll also get a pointer to code to > read the thing, but sometimes you just have to bite the bullet and > write a program to process the file. > (If all else fails, look at a dump of the first 512 bytes or so; > often the image size is included at the beginning; maybe in ASCII, 16 > bit ints, 32 bit ints, floating point -- who knows) > There've been times when I had to just display the thing at 512 or > 1024 bytes (or ints) per row and try to surmise the info from that. > So, look for the file description. > ... > Googling a bit: I see there's a package at > http://www.mbari.org/data/mbsystem/index.html > which purports to handle some JSTARS stuff. I've no idea if that will help you. > If you don't find anything preexisting for reading JSTARS format, this might help: http://stromberg.dnsalias.org/~strombrg/converting-binary.html From nagle at animats.com Mon Aug 31 00:29:38 2009 From: nagle at animats.com (John Nagle) Date: Sun, 30 Aug 2009 21:29:38 -0700 Subject: What python can NOT do? In-Reply-To: References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4a998465$0$1637$742ec2ed@news.sonic.net> Message-ID: <4a9b506c$0$1675$742ec2ed@news.sonic.net> exarkun at twistedmatrix.com wrote: > On 10:23 pm, aahz at pythoncraft.com wrote: >> In article <4a998465$0$1637$742ec2ed at news.sonic.net>, >> John Nagle wrote: >>> >>> Personally, I consider Python to be a good language held back by >>> too-close ties to a naive interpreter implementation and the lack >>> of a formal standard for the language. ... > > For my part, I will agree with John. I feel like Python's big > shortcomings stem from the areas he mentioned. They're related to each > other as well - the lack of a standard hampers the development of a less > naive interpreter (either one based on CPython or another one). It > doesn't completely prevent such development (obviously, as CPython > continues to undergo development, and there are a number of alternate > runtimes for Python-like languages), but there's clearly a cost > associated with the fact that in order to do this development, a lot of > time has to be spent figuring out what Python *is*. This is the kind of > thing that a standard would help with. Right. Python is a moving target for developers of implementations other than CPython. IronPython's production version is at Python 2.5, with a beta at 2.6. Shed Skin is at 2.x and lacks the manpower to get to 3.x. Psyco I'm not sure about, but it's 2.x. PyPy is at Python 2.5, but PyPy is currently slower than CPython. A solid Python 3 standard would give everyone a target to shoot for that would be good for five years or so. John Nagle From rt8396 at gmail.com Mon Aug 31 00:31:29 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 21:31:29 -0700 (PDT) Subject: why python got less developers ? References: <604b21ef-a3ad-4da8-92f5-c1d22345b4d7@p15g2000vbl.googlegroups.com> Message-ID: <798eded3-b3fe-4995-9e63-bff718b18889@m20g2000vbp.googlegroups.com> On Aug 29, 11:14?pm, kennyken747 wrote: (snip) > You guys can say anything you'd like it to be in this thread, but the > actual reason comes down to > 1. No marketing. Seriously, if Microsoft was pushing Python it would > obviously be a lot bigger in terms of developers. I really don't care if 100 or 100 million are using Python as long as it will endure my lifetime so i can use it ;). But it would be interesting to see a good approx of this number... just for kicks > Also, really guys? This crap about speed? People have been saying this > for years, and yet they still don't realize that there are plenty > solutions to take care of that one problem. > > Just be happy that you've stumbled upon Python, just because it's not > the most widespread language in the world certainly doesn't mean it's > not a worthy language. Quite the opposite. Your post seems a contridiction of itself? i am confused :\ From kerensaelise at hotmail.com Mon Aug 31 00:55:52 2009 From: kerensaelise at hotmail.com (elsa) Date: Sun, 30 Aug 2009 21:55:52 -0700 (PDT) Subject: map Message-ID: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Hi, i have a question about the built in map function. Here 'tis: say I have a list, myList. Now say I have a function with more than one argument: myFunc(a, b='None') now, say I want to map myFunc onto myList, with always the same argument for b, but iterating over a: map(myFunc(b='booHoo'), myList) Why doesn't this work? is there a way to make it work? (Ultimately, I want to call myFunc(myList[0], 'booHoo'), myFunc(myList [1], 'booHoo'), myFunc(myList[2], 'booHoo') etc. However, I might want to call myFunc(myList[0], 'woo'), myFunc(myList[1], 'woo'), myFunc (myList[2], 'woo') some other time). Thanks, Elsa From mmm286 at gmail.com Mon Aug 31 01:08:39 2009 From: mmm286 at gmail.com (mierdatutis mi) Date: Sun, 30 Aug 2009 22:08:39 -0700 (PDT) Subject: connect to ms sql server with odbc Message-ID: Hi, I'm newbie in python. I try to connect to remote server with ms sql server from my ubuntu. I install pyodbc and I do: >>> conn = >>> Conn = pyodbc.connect("DRIVER= {FreeTDS};SERVER=defekas62;UID=emuser;PWD=temporal;DATABASE=em620") pyodbc.connect ( "DRIVER = () FreeTDS; SERVER = defekas62; UID = emuser; PWD = temporal; em620 DATABASE =") cursor = conn.cursor() cursor = conn.cursor () >>> for row in cursor.execute("select USERNAME from JOBACTIONS"): >>> Para la fila en cursor.execute ( "usuario seleccionar de JOBACTIONS"): ... ... print row.USERNAME row.USERNAME de impresi?n File "", line 2 Archivo "", l?nea 2 print row.USERNAME row.USERNAME de impresi?n ^ ^ IndentationError: expected an indented block Why this error? Many thanks and sorry for my english From clp2 at rebertia.com Mon Aug 31 01:17:30 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 30 Aug 2009 22:17:30 -0700 Subject: map In-Reply-To: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: <50697b2c0908302217o4d2f445m96bc713f93be961e@mail.gmail.com> On Sun, Aug 30, 2009 at 9:55 PM, elsa wrote: > Hi, > > i have a question about the built in map function. Here 'tis: > > say I have a list, myList. Now say I have a function with more than > one argument: > > myFunc(a, b='None') > > now, say I want to map myFunc onto myList, with always the same > argument for b, but iterating over a: > > map(myFunc(b='booHoo'), myList) > > Why doesn't this work? Because myFunc is executed before map() is ever called, and you didn't specify a value for the `a` parameter, hence you get an error about not giving a value for `a`. Another way of saying this: Python uses "eager evaluation" (http://en.wikipedia.org/wiki/Eager_evaluation) most of the time. > is there a way to make it work? Use functools.partial to fill in the `b` parameter: http://docs.python.org/library/functools.html#functools.partial #untested example: from functools import partial f = partial(myFunc, b='booHoo') map(f, myList) Cheers, Chris -- http://blog.rebertia.com From rurpy at yahoo.com Mon Aug 31 01:19:13 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sun, 30 Aug 2009 22:19:13 -0700 (PDT) Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: On 08/30/2009 10:55 PM, elsa wrote: > i have a question about the built in map function. Here 'tis: > > say I have a list, myList. Now say I have a function with more than > one argument: > > myFunc(a, b='None') > > now, say I want to map myFunc onto myList, with always the same > argument for b, but iterating over a: > > map(myFunc(b='booHoo'), myList) > > Why doesn't this work? is there a way to make it work? When you write "map(myFunc(b='booHoo'), myList)", you are telling Python to call myFunc before the map function is called, because an argument list, "(b='booHoo')", follows myFunc. You want to pass map a function object, not the results of calling a function object. A couple ways to do what you want: map(lambda a: myFunc(a, b='booHoo'), myList) The lamba expression creates a new function of one argument (which is needed by map) that, when executed, will call myFunc with the two arguments it needs. You can also just define an ordinary function that does the same thing as the lambda above: def tmpFunc (a) myFunc (a, b='booHoo') ... map (tmpFunc, myList) In the functools module there is a function called "partial" that does something similar to the lambda above. I'll leave it to you you look it up if interested. HTH From half.italian at gmail.com Mon Aug 31 01:24:22 2009 From: half.italian at gmail.com (Sean DiZazzo) Date: Sun, 30 Aug 2009 22:24:22 -0700 (PDT) Subject: connect to ms sql server with odbc References: Message-ID: On Aug 30, 10:08?pm, mierdatutis mi wrote: > Hi, > > I'm newbie in python. I try to connect to remote server with ms sql > server from my ubuntu. I install pyodbc and I do: > > ?>>> conn = >>> Conn = > ?pyodbc.connect("DRIVER= > {FreeTDS};SERVER=defekas62;UID=emuser;PWD=temporal;DATABASE=em620") > pyodbc.connect ( "DRIVER = () FreeTDS; SERVER = defekas62; UID = > emuser; PWD = temporal; em620 DATABASE =") > ?cursor = conn.cursor() cursor = conn.cursor () > ?>>> for row in cursor.execute("select USERNAME from JOBACTIONS"): >>> > Para la fila en cursor.execute ( "usuario seleccionar de > JOBACTIONS"): > ?... ... print row.USERNAME row.USERNAME de impresi?n > ? ?File "", line 2 Archivo "", l?nea 2 > ? ? ?print row.USERNAME row.USERNAME de impresi?n > ? ? ? ? ?^ ^ > ?IndentationError: expected an indented block > Why this error? > Many thanks and sorry for my english Welcome to python. The error is telling you exactly what it says. There is a block of code that is not indented properly. Perhaps your code was edited with two different editors? Tabs are not equal to spaces. Go thru your code and be sure that you are consistent with all of your spacing. I believe 4 spaces per indent (without tabs) is the current Python standard. ~Sean From news3 at mystrobl.de Mon Aug 31 01:34:28 2009 From: news3 at mystrobl.de (Wolfgang Strobl) Date: Mon, 31 Aug 2009 07:34:28 +0200 Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: <91om95pbqtcduss20iv37f44scr89fgudb@4ax.com> elsa : >now, say I want to map myFunc onto myList, with always the same >argument for b, but iterating over a: >>> from functools import partial >>> def g(x,y=1): return x+y ... >>> map(partial(g,y=2),[1,2]) [3, 4] >>> map(partial(g,y=42),[1,2]) [43, 44] -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From erik.reppen at gmail.com Mon Aug 31 02:10:07 2009 From: erik.reppen at gmail.com (Erik Reppen) Date: Sun, 30 Aug 2009 23:10:07 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: It seems to be a language embraced by people who enjoy coding. Not so much by the time-spent-seeking-degree to paycheck ratio balancing crowd. Or maybe I just hate bloated IDEs and I've heard too many Java dev jokes to be impartial. From ubershmekel at gmail.com Mon Aug 31 02:26:59 2009 From: ubershmekel at gmail.com (RunThePun) Date: Sun, 30 Aug 2009 23:26:59 -0700 (PDT) Subject: Overriding iadd for dictionary like objects References: <87ws4n5gfi.fsf@slice.rozzin.com> Message-ID: On Aug 30, 10:33?pm, a... at pythoncraft.com (Aahz) wrote: > In article , > > > > > > RunThePun ? wrote: > > >I made a DictMixin where the keys are filenames and the values are the > >file contents. It was very simple and easy to do thanks to DictMixin. > > >For example this code writes "abc" in a file named "temp.txt" and > >prints the contents of the file named "swallow", these files are > >looked up/created/deleted in the directory "spam": > >>>> d =3D FilesDict('spam') > >>>> d['temp.txt'] =3D 'abc' > >>>> print(d['swallow']) > > >My problem arose when I wanted to append a string to a file which > >using open(..., 'ab') would have been miles more efficient because I > >wouldn't have to read the entire file (__getitem__) and then write the > >entire file back (__setitem__). The files are expected to be as big as > >600 KB which will be appended 30 bytes at a time about 3 times a > >second. Performance-wise the system would probably work without open > >(..., 'ab') but it would be a real thrashing so the current solution > >uses a method "AddTo" as Robert suggested, sacrificing the neat > >getitem/setitem syntax. > > You can do mostly what you want, I think, by having __setitem__() > convert string values into FileProxy() objects that have an appropriate > __iadd__() method. ?That brings a whole new set of problems, of course. > -- > Aahz (a... at pythoncraft.com) ? ? ? ? ? <*> ? ? ? ?http://www.pythoncraft.com/ > > "I support family values -- Addams family values" --www.nancybuttons.com I'm guessing you meant __getitem__, which is what Jan Kaliszewski suggested, but as you noted, would be a bit cumbersome in this case. From pierre.gaillard at gmail.com Mon Aug 31 03:41:57 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Mon, 31 Aug 2009 00:41:57 -0700 (PDT) Subject: lambda functions Message-ID: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> Hello, I would like to know if it is possible to define a loop in a lambda function.... How to manage the indents ? Example : s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s [index]-1 Thanks ! From eric.brunel at pragmadev.com Mon Aug 31 03:50:20 2009 From: eric.brunel at pragmadev.com (eb303) Date: Mon, 31 Aug 2009 00:50:20 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> Message-ID: <7b4f243d-ac69-4351-aed7-924afb0b3b11@e18g2000vbe.googlegroups.com> On Aug 28, 4:41 pm, r wrote: > Thanks eb303 for the wonderful post > > I have looked over the new ttk widgets and everything looks nice. I am > very glad to see the death of Tix as i never much liked it anyhow and > always believed these widgets should have been in the main Tkinter > module to start with. The tree widget has been needed for some time. > > However, i am not sure about the new "style" separation. Previously a > simple command like root.option_add('*Label.Font'...) accomplished the > same thing with less typing, but there may be a future method to this > current madness that i am unaware of...??? The new widgets have been made mainly to make tk look better by making it possible to use native widgets. The drawback is that it limits a lot the possibilities of configuration you can have: on many platforms, the looks of the widgets are decided by the user via a system preference, not by the application programmer. This is why ttk widgets are not configurable directly, because 'native' styles usually don't allow it at application level anyway. Keep in mind that the new ttk widgets are not replacements for former widgets, but an addition to them. 'Old' widgets are still here, and there is no plan I know of to remove them. If you want to do an application with a very specific look, you can still use these. From clp2 at rebertia.com Mon Aug 31 03:51:07 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 31 Aug 2009 00:51:07 -0700 Subject: lambda functions In-Reply-To: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> References: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> Message-ID: <50697b2c0908310051n3bbe87d7n9929f90231062daa@mail.gmail.com> On Mon, Aug 31, 2009 at 12:41 AM, Pierre wrote: > Hello, > > I would like to know if it is possible to define a loop in a lambda > function.... Not possible. Lambdas can only contain a single expression. A loop is a block statement. Just use a named function instead. There's nothing that can be done with a lambda that can't be done with a named function instead. Cheers, Chris -- http://blog.rebertia.com From javier.collado at gmail.com Mon Aug 31 03:59:55 2009 From: javier.collado at gmail.com (Javier Collado) Date: Mon, 31 Aug 2009 09:59:55 +0200 Subject: lambda functions In-Reply-To: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> References: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> Message-ID: Hello, This page has some advice about how to avoid some of the lambda functions limitations: http://p-nand-q.com/python/stupid_lambda_tricks.html In particular, it suggests to use map function instead of for loops. Best regards, Javier 2009/8/31 Pierre : > Hello, > > I would like to know if it is possible to define a loop in a lambda > function.... > > How to manage the indents ? Example : > s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s > [index]-1 > > > Thanks ! > > -- > http://mail.python.org/mailman/listinfo/python-list > From deets at nospam.web.de Mon Aug 31 04:08:39 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 31 Aug 2009 10:08:39 +0200 Subject: initilize a memory zone in python In-Reply-To: <18627379-8056-4ee9-b3b8-d5fd4cd0590c@y20g2000vbk.googlegroups.com> References: <7g07ghF2ngfq1U1@mid.uni-berlin.de> <18627379-8056-4ee9-b3b8-d5fd4cd0590c@y20g2000vbk.googlegroups.com> Message-ID: <7g1eo9F2neh1fU1@mid.uni-berlin.de> Mug schrieb: > On Aug 30, 8:58 pm, "Diez B. Roggisch" wrote: >> Mug schrieb: >> >>> hello, i'm new in python, i used to program in C, >>> i have a small problem, i tryed to do some serial port things >>> manipulation >>> with python. >>> i have something like: >>> import sys,termios >>> fd = sys.stdin.fileno() >>> term_conf=termios.tcgetattr(fd); >>> now i want to modify the actuall values in term_conf zone to zero >>> i don't see how to do it, >>> in C we can do : bzero(&term_conf,sizeof(struct termios)); >>> i want to know if it exist a similar function in python, thanks >> In python you don't modify memory like that. >> >> For the above function, you pass a value as the one you got to >> tcgetattr, with values modified as you desire them. > i tryed > print term_conf > and i saw that the term_conf is actually represent with an array in > python: > > zsh/3 4201 [1] % python test.py > [27906, 5, 1215, 35387, 15, 15, ['\x03', '\x1c', '\x7f', '\x15', > '\x04', '\x00', '\x01', '\xff', '\x11', '\x13', '\x1a', '\xff', > '\x12', '\x0f', '\x17', '\x16', '\xff', '\x00', '\x00', '\x00', > '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', > '\x00', '\x00', '\x00', '\x00']] > > it's a array of 7 elements, with the seventh element it self a array, > so in order to initialize them to zero, there's no other way than > modify them > one by one in a loop? is there a fonction like "memset" or "bzero" in > python? Again: no, there is no such function. But for the above, you'd easily write: foo = [0] * 7 # only do this with immutables foo[-1] = ['\x00'] * 16 alternatively, you modify the result you got from tcgetattr in the places you want. Diez From gagsl-py2 at yahoo.com.ar Mon Aug 31 04:16:39 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Aug 2009 05:16:39 -0300 Subject: lambda functions References: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> Message-ID: En Mon, 31 Aug 2009 04:41:57 -0300, Pierre escribi?: > I would like to know if it is possible to define a loop in a lambda > function.... > > How to manage the indents ? Example : > s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s > [index]-1 You can't. lambda is just a way to define a short, inline, anonymous function, and its body can only contain expressions, not statements. Even if what you want were legal, giving a name to the resulting expression kind of defeats the purpose of lambda - use a normal function instead: def s_minus_1(s): "document usage here" for index,item in enumerate(s): s[index] -= 1 -- Gabriel Genellina From hendrik at microcorp.co.za Mon Aug 31 04:19:57 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 31 Aug 2009 10:19:57 +0200 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <3e9ddb9b-8f61-4d8d-a25c-7e95e8a25c06@g1g2000vbr.googlegroups.com> Message-ID: <200908311019.58029.hendrik@microcorp.co.za> On Sunday 30 August 2009 22:46:49 Dennis Lee Bieber wrote: > Rather elitist viewpoint... Why don't we just drop nukes on some 60% > of populated landmasses that don't have a "western" culture and avoid > the whole problem? Now yer talking, boyo! It will surely help with the basic problem which is the heavy infestation of people on the planet! :-) - Hendrik From hendrik at microcorp.co.za Mon Aug 31 04:43:07 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 31 Aug 2009 10:43:07 +0200 Subject: map In-Reply-To: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: <200908311043.07827.hendrik@microcorp.co.za> On Monday 31 August 2009 06:55:52 elsa wrote: 8< --------- map question ---------------------------- > > (Ultimately, I want to call myFunc(myList[0], 'booHoo'), myFunc(myList > [1], 'booHoo'), myFunc(myList[2], 'booHoo') etc. However, I might want > to call myFunc(myList[0], 'woo'), myFunc(myList[1], 'woo'), myFunc > (myList[2], 'woo') some other time). Here is some heretical advice: Do not use stuff like map and reduce unless they fit what you want to do perfectly, and "JustWorks" the first time. You have a very clear idea of what you want to do, so why do you not just simply write something to do it? something like this (untested): def woofer(thefunc,thelist,thething): theanswers = [] for x in thelist: theanswers.append(thefunc(x,thething)) return theanswers And the advantage is that you do not have to remember what map does... *ducks away from the inevitable flames* - Hendrik From pierre.gaillard at gmail.com Mon Aug 31 05:02:45 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Mon, 31 Aug 2009 02:02:45 -0700 (PDT) Subject: rcond in numpy : Message-ID: Hello, Anyone knows the numpy equivalent of the matlab function : rcond (Matrix reciprocal condition number estimate) ? Thanks. From gagsl-py2 at yahoo.com.ar Mon Aug 31 05:05:17 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Aug 2009 06:05:17 -0300 Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> <200908311043.07827.hendrik@microcorp.co.za> Message-ID: En Mon, 31 Aug 2009 05:43:07 -0300, Hendrik van Rooyen escribi?: > On Monday 31 August 2009 06:55:52 elsa wrote: > >> (Ultimately, I want to call myFunc(myList[0], 'booHoo'), myFunc(myList >> [1], 'booHoo'), myFunc(myList[2], 'booHoo') etc. However, I might want >> to call myFunc(myList[0], 'woo'), myFunc(myList[1], 'woo'), myFunc >> (myList[2], 'woo') some other time). > > Here is some heretical advice: > > Do not use stuff like map and reduce unless they fit what you want to do > perfectly, and "JustWorks" the first time. I think of that advice as "orthodox", not "heretical"! (functional guys are minority here...) > You have a very clear idea of what you want to do, so why do you not just > simply write something to do it? > > something like this (untested): > > def woofer(thefunc,thelist,thething): > theanswers = [] > for x in thelist: > theanswers.append(thefunc(x,thething)) > return theanswers > > And the advantage is that you do not have to remember what map does... This block: theanswers = [] for x in thelist: theanswers.append(thefunc(x,thething)) is formally the same as this one: theanswers = [thefunc(x,thething) for x in thelist] but the list comprehension is faster. So the function becomes: def woofer(thefunc,thelist,thething): return [thefunc(x,thething) for x in thelist] and may be inlined (it's usually easier to read). > *ducks away from the inevitable flames* *fights back to back with you against heretics* -- Gabriel Genellina From piet at cs.uu.nl Mon Aug 31 05:31:34 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 31 Aug 2009 11:31:34 +0200 Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: >>>>> Hendrik van Rooyen (HvR) wrote: >HvR> On Monday 31 August 2009 06:55:52 elsa wrote: >HvR> 8< --------- map question ---------------------------- >>> >>> (Ultimately, I want to call myFunc(myList[0], 'booHoo'), myFunc(myList >>> [1], 'booHoo'), myFunc(myList[2], 'booHoo') etc. However, I might want >>> to call myFunc(myList[0], 'woo'), myFunc(myList[1], 'woo'), myFunc >>> (myList[2], 'woo') some other time). >HvR> Here is some heretical advice: >HvR> Do not use stuff like map and reduce unless they fit what you want to do >HvR> perfectly, and "JustWorks" the first time. >HvR> You have a very clear idea of what you want to do, so why do you not just >HvR> simply write something to do it? >HvR> something like this (untested): >HvR> def woofer(thefunc,thelist,thething): >HvR> theanswers = [] >HvR> for x in thelist: >HvR> theanswers.append(thefunc(x,thething)) >HvR> return theanswers >HvR> And the advantage is that you do not have to remember what map does... Map should be in every good programmer's toolbox. So (s)he presumably knows already what map does. In order to follow your advise (s)he must first forget what map does :=) Agreed on the part that map shouldn't be used indiscriminately. Neither should loops. Your woofer is much harder to follow than map, I think. [myFunc(elt, 'booHoo') for elt in myList] is also a good candidate and in this case I think it is preferable to both the loop and the map with a partial or lambda in terms of clarity. On the other hand when you just want to call a function on each element of a list and you don't need to collect the result a simple loop is often preferable. But ultimately it is also very much a matter of taste, preference and habit. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From jacopo.pecci at gmail.com Mon Aug 31 05:44:23 2009 From: jacopo.pecci at gmail.com (jacopo) Date: Mon, 31 Aug 2009 02:44:23 -0700 (PDT) Subject: starting a client remotely Message-ID: <7013f2ee-3076-4abf-b609-18c023d3e28a@f33g2000vbm.googlegroups.com> I am playing with multiprocessing and I would like to have a python script on one machine which initialize my whole system, in other words, this script should start the server (a python script) on my local machine and the clients (python scripts) on the other machines in my local network. Would you have any suggestion? regards, jacopo From deets at nospam.web.de Mon Aug 31 05:47:44 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 31 Aug 2009 11:47:44 +0200 Subject: starting a client remotely References: <7013f2ee-3076-4abf-b609-18c023d3e28a@f33g2000vbm.googlegroups.com> Message-ID: <7g1ki0F2nifhkU1@mid.uni-berlin.de> jacopo wrote: > I am playing with multiprocessing and I would like to have a python > script on one machine which initialize my whole system, in other > words, this script should start the server (a python script) on my > local machine and the clients (python scripts) on the other machines > in my local network. > > Would you have any suggestion? This isn't possible witout some kind of service running on the remote machine. You don't write what OS you are using, on unix'ish machines this can be easily accomplished using SSH to invoke a remote-command that starts your server. I've used that + Pyro in the past to create distributed systems. Diez From jacopo.pecci at gmail.com Mon Aug 31 05:58:34 2009 From: jacopo.pecci at gmail.com (jacopo) Date: Mon, 31 Aug 2009 02:58:34 -0700 (PDT) Subject: Return value of multiprocessing manager registerred function References: <4337084f-cf9b-4b9c-a0cc-ba8f0821f31a@v15g2000prn.googlegroups.com> Message-ID: Hi Terry, I have just started working on similar things and I am strugling to find examples or documentations. So far I have found only the official documentation of the multiprocessing package. Would you be able to recommend me some good reference or a book. I dont want to overwhelm this newsgroup with questions... yet :) Regards, Jacopo On Aug 26, 4:22?am, Terry wrote: > Hi, > > I'm using the multiprocessing.manager to run proceduresremotely. It > all worked fine except I hope to have a different return value type. > > The remote function calls always return a proxy, which when I need to > get the value it need to connect to the manager again to fetch it. But > I just need the value, not the proxy. > > Can I just return the value instead of a proxy from a manager? > > br, Terry From paul at boddie.org.uk Mon Aug 31 06:00:58 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 31 Aug 2009 03:00:58 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <1ab2c088-bead-43fa-bf4a-3e7f4d84e871@g1g2000vbr.googlegroups.com> <59cad1ba-1162-4227-9375-d132ef030a7b@d21g2000vbm.googlegroups.com> Message-ID: <5a3acf8a-0f5f-4743-a477-f5dc2978d4ed@r36g2000vbn.googlegroups.com> On 31 Aug, 00:28, r wrote: > > I said it before and i will say it again. I DON"T CARE WHAT LANGUAGE > WE USE AS LONG AS IT IS A MODERN LANGUAGE FOUNDED ON IDEALS OF > SIMPLICITY!!!! [Esperanto] > English is by far already the de-facto lingua franca throughout the > world. You don't care, but here it comes: English! And is it a language "founded on ideals of simplicity"? I suggest you familiarise yourself with the history of the English language. [...] > You can deny the holocaust all you want but it still happened and so > too shall the great unity! Sadly because of cultural and social > fanatics like yourself, it will probably take another great war to > usher in the new order. Now you are just being offensive. [...] > So you are advocating for me to use derogatory statements in my post, > no thanks i need not resort to adolescent rants to argue my points. So what was the bulk of your opening message in this thread or the kind of gutter remarks made above if not "adolescent rants"? > And why do you continue to compare me to XL. Has XL *ever* helped a > python user in this forum? I have, many times. I am *actually* a > python programmer who cares about Python and my posts bring much vigor > and intelligence to an otherwise boring NG -- like me or not. Whether you actually care about Python or not, I repeat my suggestion that you take rants of this nature out of this forum and to a more appropriate place. At the very time the community seeks to increase diversity, such material is not only insensitive towards those who do not share your own cultural and political background, it also demonstrates a total lack of awareness of the kind of community people are trying to build and sustain. And don't give us the "livening up the newsgroup" excuse. The only reason people use newsgroups like this for their political posturing is analogous to a football player bursting into a chess club and claiming superiority in his own sport over those whose pastime has been interrupted: he knows that in a more suitable venue, his inadequacy would quickly be revealed by active practitioners of the discipline. Take your material elsewhere - maybe then the historians, linguists and sociologists will give you the tuition you so richly deserve! Paul From piet at cs.uu.nl Mon Aug 31 06:04:01 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 31 Aug 2009 12:04:01 +0200 Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> Message-ID: >>>>> Derek Martin (DM) wrote: >DM> On Sun, Aug 30, 2009 at 03:42:06AM -0700, Paul McGuire wrote: >>> Is it any odder that 3 is an object than that the string literal >>> "Hello, World!" is an object? >DM> Yes. Because 3 is a fundamental bit of data that the hardware knows >DM> how to deal with, requiring no higher level abstractions for the >DM> programmer to use it (though certainly, a programming language can >DM> provide them, if it is convenient). "Hello, World!" is not. They are >DM> fundamentally different in that way. How the semantics of Python is defined is not dependent of the hardware. You could imagine a computer where strings are as much built into the hardware as ints are. On the other hand you could also imagine a computer that only knows about bits and where int arithmetic has to be done in software. In fact early microprocessors only could operate directly on bytes and arithmetic of larger ints was in software. And even nowadays there are processors in use that don't have built-in floating point hardware. Would you say that considering whether 3.14 is an object in Python or whether that is to be considered strange should depend on the availability of a floating point unit in the hardware where the program runs? Would that make floating point numbers "fundamentally different" from ints in the sense described above? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From jacopo.pecci at gmail.com Mon Aug 31 06:08:04 2009 From: jacopo.pecci at gmail.com (jacopo) Date: Mon, 31 Aug 2009 03:08:04 -0700 (PDT) Subject: starting a client remotely References: <7013f2ee-3076-4abf-b609-18c023d3e28a@f33g2000vbm.googlegroups.com> <7g1ki0F2nifhkU1@mid.uni-berlin.de> Message-ID: <7a3cbeba-7338-45b3-aff8-7840a322b185@r33g2000vbp.googlegroups.com> thank you Diez, unfortunatelly I am on Windows NT. Did you use SSH in a python script? Isn't multiprocessing.managers already doing something like Pyro? thanks Jacopo On Aug 31, 12:47?pm, "Diez B. Roggisch" wrote: > jacopo wrote: > > I am playing with multiprocessing and I would like to have a python > > script on one machine which initialize my whole system, in other > > words, this script should start the server (a python script) on my > > local machine and the clients (python scripts) on the other machines > > in my local network. > > > Would you have any suggestion? > > This isn't possible witout some kind of service running on the remote > machine. You don't write what OS you are using, on unix'ish machines this > can be easily accomplished using SSH to invoke a remote-command that starts > your server. I've used that + Pyro in the past to create distributed > systems. > > Diez From xi at gamma.dn.ua Mon Aug 31 06:14:18 2009 From: xi at gamma.dn.ua (Kirill Simonov) Date: Mon, 31 Aug 2009 13:14:18 +0300 Subject: [ANN] PyYAML-3.09: YAML parser and emitter for Python Message-ID: <4A9BA27A.10507@gamma.dn.ua> ======================== Announcing PyYAML-3.09 ======================== A new bug fix release of PyYAML is now available: http://pyyaml.org/wiki/PyYAML Note that PyYAML supports both Python 2 and Python 3. For compatibility notes, please see http://pyyaml.org/wiki/PyYAMLDocumentation#Python3support Changes ======= * Fixed compatibility issues with Python 3.1. * Fixed use of uninitialized memory when emitting anchors with LibYAML bindings (Thank to cegner(at)yahoo-inc(dot)com). * Fixed emitting incorrect BOM characters for UTF-16 (Thank to Valentin Nechayev) * Fixed the emitter for folded scalars not respecting the preferred line width (Thank to Ingy). * Fixed a subtle ordering issue with emitting '%TAG' directives (Thank to Andrey Somov). * Fixed performance regression with LibYAML bindings. Resources ========= PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.09.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.09.zip Windows installers: http://pyyaml.org/download/pyyaml/PyYAML-3.09.win32-py2.3.exe http://pyyaml.org/download/pyyaml/PyYAML-3.09.win32-py2.4.exe http://pyyaml.org/download/pyyaml/PyYAML-3.09.win32-py2.5.exe http://pyyaml.org/download/pyyaml/PyYAML-3.09.win32-py2.6.exe http://pyyaml.org/download/pyyaml/PyYAML-3.09.win32-py3.0.exe http://pyyaml.org/download/pyyaml/PyYAML-3.09.win32-py3.1.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core About PyYAML ============ YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. Example ======= >>> import yaml >>> yaml.load(""" ... name: PyYAML ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... """) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} >>> print yaml.dump(_) name: PyYAML homepage: http://pyyaml.org/wiki/PyYAML description: YAML parser and emitter for Python keywords: [YAML, serialization, configuration, persistance, pickle] Copyright ========= The PyYAML module is written by Kirill Simonov . PyYAML is released under the MIT license. From deets at nospam.web.de Mon Aug 31 06:35:44 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 31 Aug 2009 12:35:44 +0200 Subject: starting a client remotely References: <7013f2ee-3076-4abf-b609-18c023d3e28a@f33g2000vbm.googlegroups.com> <7g1ki0F2nifhkU1@mid.uni-berlin.de> <7a3cbeba-7338-45b3-aff8-7840a322b185@r33g2000vbp.googlegroups.com> Message-ID: <7g1nc0F2mjpocU1@mid.uni-berlin.de> jacopo wrote: > thank you Diez, > unfortunatelly I am on Windows NT. > Did you use SSH in a python script? Via subprocess, yes. Paramiko would be a way, too. > Isn't multiprocessing.managers already doing something like Pyro? I never used it, so I don't know - but it appears to be, yes. Doesn't change the overall problem though - without an inroad to another server, you can't spawn processes on remote machines. Diez From gagsl-py2 at yahoo.com.ar Mon Aug 31 06:46:06 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Aug 2009 07:46:06 -0300 Subject: starting a client remotely References: <7013f2ee-3076-4abf-b609-18c023d3e28a@f33g2000vbm.googlegroups.com> <7g1ki0F2nifhkU1@mid.uni-berlin.de> <7a3cbeba-7338-45b3-aff8-7840a322b185@r33g2000vbp.googlegroups.com> Message-ID: > On Aug 31, 12:47?pm, "Diez B. Roggisch" wrote: >> jacopo wrote: >> > I am playing with multiprocessing and I would like to have a python >> > script on one machine which initialize my whole system, in other >> > words, this script should start the server (a python script) on my >> > local machine and the clients (python scripts) on the other machines >> > in my local network. En Mon, 31 Aug 2009 07:08:04 -0300, jacopo escribi?: > thank you Diez, > unfortunatelly I am on Windows NT. NT 4.0??? I was going to say "use the rexec command" but I think it's posterior to the Triasic-Jurasic extinction event :) -- Gabriel Genellina From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 31 07:25:12 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 31 Aug 2009 13:25:12 +0200 Subject: Object's nesting scope In-Reply-To: <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> Message-ID: <4a9bb2ee$0$10244$426a74cc@news.free.fr> zaur a ?crit : > On 28 ???, 16:07, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> zaur a ?crit : >> >> >> >>> On 26 ???, 17:13, "Diez B. Roggisch" wrote: >>>> Whom am we to judge? Sure if you propose this, you have some usecases in >>>> mind - how about you present these >>> Ok. Here is a use case: object initialization. >>> For example, >>> person = Person(): >>> name = "john" >>> age = 30 >>> address = Address(): >>> street = "Green Street" >>> no = 12 >>> vs. >>> person = Person() >>> person.name = "john" >>> person.age = 30 >>> address = person.address = Address() >>> address.street = "Green Street" >>> address.no = 12 >> Err... Looks like you really should read the FineManual(tm) - >> specifically, the parts on the __init__ method. >> >> class Person(object): >> def __init__(self, name, age, address): >> self.name = name >> self.age = age >> self.address = address >> >> class Address(object): >> def __init__(self, street, no): >> self.no = no >> self.street = street >> >> person = Person( >> name="john", >> age=30, >> address = Address( >> street="Green Street", >> no=12 >> ) >> ) > > What are you doing if 1) classes Person and Address imported from > foreign module 2) __init__ method is not defined as you want? Either 1/write an alternate initializer and bind it to the appropriate classes or 2/write factory functions: 1/ from foreign_module import Person, Address def my_init(self, **kw): for k, v in kw.items(): setattr(self, k, v) return self Person.init = my_init Address.init = my_init person = Person().init( name="john", age=30, address = Address().init( street="Green Street", no=12 ) ) 2/ from functools import partial import foreign_module def my_factory(cls, **kw): obj = cls() for k, v in kw.items(): setattr(obj, k, v) return obj Person = partial(my_factory, foreign_module.Person) Address = partial(my_factory, foreign_module.Address) person = Person( name="john", age=30, address = Address( street="Green Street", no=12 ) ) From steve at REMOVE-THIS-cybersource.com.au Mon Aug 31 08:16:57 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Aug 2009 12:16:57 GMT Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: <002542bb$0$2930$c3e8da3@news.astraweb.com> On Mon, 31 Aug 2009 10:43:07 +0200, Hendrik van Rooyen wrote: > Here is some heretical advice: > > Do not use stuff like map and reduce unless they fit what you want to do > perfectly, and "JustWorks" the first time. > > You have a very clear idea of what you want to do, so why do you not > just simply write something to do it? That's not heretical advice -- that's pretty standard, vanilla, boring advice. It's probably good advice, if you care more about Getting the Job Done than about learning the language. > And the advantage is that you do not have to remember what map does... map() is probably the simplest, most straightforward of the functional tools in Python. It's harder for me to remember it's name than to remember what it does: it applies a function to each element of a list, instead of two the entire list as a single argument. Easy-peasy. > *ducks away from the inevitable flames* You'll have to try harder than that to get flamed :) -- Steven From hendrik at microcorp.co.za Mon Aug 31 09:44:30 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 31 Aug 2009 15:44:30 +0200 Subject: map In-Reply-To: References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: <200908311544.30746.hendrik@microcorp.co.za> On Monday 31 August 2009 11:31:34 Piet van Oostrum wrote: > But ultimately it is also very much a matter of taste, preference and > habit. This is true, but there is another reason that I posted - I have noticed that there seems to be a tendency amongst newcomers to the group to go to great lengths to find something that will do exactly what they want, irrespective of the inherent complexity or lack thereof of that which they are trying to do. Now I cannot understand why this is - one could say that it is caused by an eagerness to understand all the corners of the tool that is python, but somehow it does not feel like that to me - I see it almost as a crisis of confidence - as if the newbie lacks the self confidence to believe that he or she is capable of doing anything independently. So whenever I can, I try to encourage people to just do it their way, and to see what happens, and to hack using the interactive interpreter, to build confidence by experimenting and making mistakes, and realizing that when you have made a mistake, it is not the end of the world, - you can fix it and move on. Don't know if this rant makes any sense... - Hendrik From kw at codebykevin.com Mon Aug 31 09:52:13 2009 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 31 Aug 2009 09:52:13 -0400 Subject: An assessment of Tkinter and IDLE In-Reply-To: <827effaa-d0f7-4142-b4b9-6f9f8e0e7963@e34g2000vbm.googlegroups.com> References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> <827effaa-d0f7-4142-b4b9-6f9f8e0e7963@e34g2000vbm.googlegroups.com> Message-ID: <4A9BD58D.3060808@codebykevin.com> On 8/28/09 8:11 PM, r wrote: > On Aug 28, 5:48 pm, Mark Roseman wrote: > (snip) >> Thewww.tkdocs.comsite is 'language neutral' - currently the tutorial >> covers Tcl, Perl, Ruby and yes Python, and allows you to switch between >> any of those languages (or show all of them). > > True, however the coverage is incomplete. I would back this site if we > can get a complete coverage of all widgets in the Python language. > > +0.1 Are you certain the site is incomplete? Its coverage of the basic Tk and Ttk widgets is spectacular. . Its coverage of layout techinques and best practices for organizing complex interfaces with Tk is also extremely valuable. I wish this site had been around when I was learning Tk five years ago. I've looked at just about every Tk and Tkinter tutorial site out there, and this one surpasses them all. Mark Roseman--a professional, independent software developer whose commercial products almost all incorporate Tk into their GUI's--has spent a couple of years putting together this site with input from various users and developers (myself included). It's now an absolutely indispensible resource for beginners and more experienced developers. The reason the site does not cover 'all widgets in the Python language' is threefold: 1. It's a site about Tk, a tookit that has Python bindings and bindings to other languages also (Ruby, Perl, Tcl, etc.). 2. It omits additional Python-specific, Tkinter-based widget sets such as PMW, Tix, etc. because once you understand the basics of Tk, then grokking these other megawidget sets (which all build on top of Tk) should be pretty straightforward. 3. Finally, 'all widgets in the Python language' gets into other tookits as well, which is obviously unfeasible for a website. If the site by itself isn't enough for you, or is a bit too basic in its coverage of Python techniques, then there are other options. Couple the TkDocs site with effbot's more advanced walk through the various Tkinter classes, and perhaps one or two of the other Tkinter-specific tutorials, and you'll have learned a lot. But I think the TkDocs site is essential, especially in its more advanced discussion of how to put together an attractive, polished user interface with Tk. Tk has a long-standing reputation of being the toolkit of choice for quick, simple, ugly interfaces, and the other resources I've mentioned do nothing to to change this. The practices that Mark Roseman discusses will allow one to eventually put together a UI that matches anything that the other big toolkits (wxPython, PyQt, PyObjC, PyGtk, etc.) can do. Hope this helps, Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From xahlee at gmail.com Mon Aug 31 10:00:43 2009 From: xahlee at gmail.com (Xah Lee) Date: Mon, 31 Aug 2009 07:00:43 -0700 (PDT) Subject: =?windows-1252?Q?Math_Notations=2C_Computer_Languages=2C_and_the_=93Form?= =?windows-1252?Q?=94_in_Formalism?= Message-ID: <8f621b1f-a259-44dd-a6c4-231fa708ace7@j9g2000prh.googlegroups.com> ? Math Notations, Computer Languages, and the ?Form? in Formalism http://xahlee.org/cmaci/notation/index.html plain text version follows. (lacks links) ----------------------------- Math Notations, Computer Languages, and the ?Form? in Formalism Xah Lee, 2009-08-31 This page is a collection of essays and expositions on the subjects of nomenclature and notations in math and computer languages, in the context of facilitating human communication and theorem proving systems. Most of these essays here are originally from email, blogs, or rants. They are not of publication quality, and they are not a coherent exposition the subject. Here's a very brief summary of of these essays's central thesis: ? Traditional math notations are very inconsistent. Edsger Dijkstra is a leader in a movement of what's called Calculational Proofs. That is, using a notation that is consistent and facilitates the calculation aspects when doing math by humans. ? Today, especially since 1990s, tremendous advances are made in computer algebra systems and theorem proving systems. In these languages, a coherent syntax, grammar, are needed for math expressions. ? In computer algebra or theorem proving systems, they are intimately tied to the math philosophies of formalism and logicism. In a sense, formalism and logicism today are tied together as a single subject, and using computer languages as foundation. ? Math expressions/syntax in computer languages are intimately tied to math notations for human reading. (e.g. Mathematical, MathML are technologies that combine the two.) ? The syntax and grammar of today's computer languages, such as Java, C, Python, SQL, Lisp, are ad-hoc and their communities have little understanding of the knowledge gained in math related fields such as computer algebra or theorem proving languages. (This applies to functional langs such as Haskell as well, but to a lesser degree.) On the other hand, mathematicians in general are illiterate about programing or using computer languages. All of the above considered together, computer language designers and mathematicians, should be made aware of these issues, so that when they design or use computer languages, may it be math oriented or not, the language's syntax and grammar can move towards a consistent syntax system with solid foundation (as opposed to ad-hoc), and such language should have build-in markup or simple mapping to 2-dimensional notations for human reading (such as done with Mathematica or Semantic MathML), and this computer language should be in fact as a basis of theorem prover or computer algebra system (as in OCaml, Haskell, Mathematica). The languages of computer algebra and theorem prover would in fact merge together into one single subject if it is not already slowly happening today. Progress in the above issues are made in different fields but there are little unification going on. For example, there's Edsger Dijkstra's Calculational Proofs movement. It improves math notations towards consistency and formalism. However, people in Calculational Proofs movement are mostly math pedagogy community i think. They are not programers interested in computer languages, nor logicians interested in math formalism, or industrial and commercial organizations interested in math notation representation systems. There's the computer algebra community, such as Mathematica, Maple, Matlab, which requires a syntax and grammar for mathematical concepts. There's the theorem proving community, such as OCaml, Coq, HOL, which not only requires a syntax for math concepts, but also made major understanding about math as a system of forms, i.e. formal systems. Both computer algebra and theorem proving systems require math notations and computer language syntax that are consistent and can represent math concepts. However, the 2 camps are largely separate communities. For example, there is as far as i know no tool that is both a practical computer algebra system as well as a theorem proving language. Common computer languages, such as C, Java, Python, requires a good syntax, parsers, and compilers, but their community, including computer scientists and programers, are usually illiterate in typical topics of of mathematics proper. Functional languages, such as Scheme Lisp, APL, OCaml, Haskell, are more based on logic foundations (lambda calculus) but their syntax and grammar has little to do with the math notations as a logic or formal system. (these languages do not have a formal spec in the sense of Formlism, i.e. transformation of forms. In fact, almost no languages has a formal spec, formalism or not.) There's math notation representation needs, such as TeX, MathCAD, MathML, Mathematica. These are typically commercial organizations in the computing industry. They can render math notations. In the case of MathML and Mathematica, the language also represent the semantic content of math notations. These two made major understanding about the relation of math notations and computer languages, but they in general have little to do with formalism or theorem proving. (with some exception of Mathematica) Calculational proof notational system, Computer algebra systems, theorem prover languages, formalism and logicism as foundation of mathematics, functional languages, and computer languages in general, mathematics and its notations, all are in fact can be considered as a single subject with a unified goal. All the technologies and movements exist, but today they have mostly not come together. For example, Microsoft Equaton Editor, TeX, and various other tools does well with math notation rendering. MathML has both representational and semantic aspects (OpenMath is a new group that focus on semantic aspects), for the purpose of rendering as well semantic representation. Mathematica is a computer algebra system for solving arbitrary math equations, that is also able to represent math notation as a computer language, so that computation can be done with math notation directly. However, the system lacks a foundation as a theorem prover. Theorem provers such as OCaml (HOL, Coq), Mizar does math formalism as a foundation, also function as a generic computer language, but lacks abilities as a computer algebra system or math notation representation. Notations * The Codification of Mathematics * State Of Theorem Proving Systems 2008 * The Problems of Traditional Math Notation * A Notation for Plane Geometry * the Moronicity of the Expositions of Common Mathematicians (rant) * Fundamental Problems of Lisp (see section 1, on the importance for regularity of syntax) * The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations * The Moronicities of Typography Jargons Math * Math Terminology and Naming of Things * Math Jargons Explained * Politics and the English Language, 1946, by George Orwell. Harm Of Bad Terminologies In Computing Languages * The Importance of Terminology's Quality In A Computer Language * What are OOP's Jargons and Complexities? * Java's Abuse of the Jargon ?Interface? and API * Jargons of Info Tech Industry * The Term Currying In Computer Science * Function Application is not Currying * Why You should Not Use The Jargon Lisp1 and Lisp2 * The Jargon ?Tail Recursion? * What Is Closure In A Programing Language * Jargons And High Level Languages (unpolished essay) * Why You Should Avoid The Jargon ?Tail Recursion? * I Can Not Find A Word Better Than ?CAR? Harm of Mixing Concept of Syntax and Formatting * The TeX Pestilence * The Harm of hard-wrapping Lines (harm of confusing syntax with formatting) * Tabs versus Spaces in Source Code (harm of treating syntax as formatting instead of syntax) Applications of Regular Syntax * A Text Editor Feature: Syntax Tree Walk (application of syntax) * A Simple Lisp Code Formatter (application of syntax regularity) References * ?Mathematica Notation: Past and Future? (2000-10-20), by Stephen Wolfram, at http://www.stephenwolfram.com/publications/recent/mathml/index.html. * Functional Mathematics, by Raymond Boute, 2006. http://www.funmath.be/ * Formalized Mathematics, by John Harrison, 1996-08-13. http://www.rbjones.com/rbjpub/logic/jrh0100.htm * ?How Computing Science created a new mathematical style?. (1990) By Edsger W Dijkstra. EWD1073 * ?Under the spell of Leibniz's dream? (2000) By Edsger W Dijkstra. EWD1298 * Abuse of notation * Formal system From nitebirdz at sacredchaos.com Mon Aug 31 10:21:11 2009 From: nitebirdz at sacredchaos.com (Nitebirdz) Date: Mon, 31 Aug 2009 16:21:11 +0200 Subject: Suggestion In-Reply-To: <7aa29e790908290212h17d27593u52d1a90b3e785386@mail.gmail.com> References: <7aa29e790908290212h17d27593u52d1a90b3e785386@mail.gmail.com> Message-ID: <20090831142109.GA7611@sevilla.sacredchaos.com> On Sat, Aug 29, 2009 at 02:42:36PM +0530, Thangappan.M wrote: > Dear all, > > I am in the process of learning Python programming language. I know > Perl,PHP. Compare to both the language Python impressed me because here > there is no lexical variables and all.Now I need suggestion saying that , > What online book can I follow? > > I have not yet learnt any advanced programming stuffs in Python. > Please suggest some book? or tutorial. net net my goal is that I will be > able to do the project in any languages(Python,Perl,PHP).So I need to learn > more depth knowledge of Python. > > So Please help me? > Thangappan, I'm no expert, but perhaps the following book will be of some help: http://diveintopython.org/ There are plenty of tutorials on the web too. Just do a quick search for something like "python tutorial". From wiggly at wiggly.org Mon Aug 31 10:36:46 2009 From: wiggly at wiggly.org (Nigel Rantor) Date: Mon, 31 Aug 2009 15:36:46 +0100 Subject: An assessment of the Unicode standard In-Reply-To: <200908311019.58029.hendrik@microcorp.co.za> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <3e9ddb9b-8f61-4d8d-a25c-7e95e8a25c06@g1g2000vbr.googlegroups.com> <200908311019.58029.hendrik@microcorp.co.za> Message-ID: <4A9BDFFE.2040402@wiggly.org> Hendrik van Rooyen wrote: > On Sunday 30 August 2009 22:46:49 Dennis Lee Bieber wrote: > >> Rather elitist viewpoint... Why don't we just drop nukes on some 60% >> of populated landmasses that don't have a "western" culture and avoid >> the whole problem? > > Now yer talking, boyo! It will surely help with the basic problem which is > the heavy infestation of people on the planet! > :-) On two conditions: 1) We drop some "test" bombs on Slough to satisfy Betjeman. 2) We strap both Xah and r to aforementioned bombs. Also, I'm surprised no-one has mentioned Esperanto yet. Sounds like something r and Xah would *love*. Slightly off-topic - does anyone have a good recipe for getting thunderbird to kill whole threads for good? Either based on a rule or just some extension I can use? The Xah/r threads are like car crashes, I can't help but watch but my time could be better spent and I don't want to unsub the whole list. Cheers, n From nitebirdz at sacredchaos.com Mon Aug 31 10:40:50 2009 From: nitebirdz at sacredchaos.com (Nitebirdz) Date: Mon, 31 Aug 2009 16:40:50 +0200 Subject: a popen command line question In-Reply-To: <964997.10840.qm@web36907.mail.mud.yahoo.com> References: <964997.10840.qm@web36907.mail.mud.yahoo.com> Message-ID: <20090831144049.GB7611@sevilla.sacredchaos.com> On Sat, Aug 29, 2009 at 01:13:12PM -0700, Joni Lee wrote: > Hi all, > > I write a small script > > status = os.popen('top').readlines() > print status > > It calls the command line "top" and will print out the status. > But I have to press the keyboard "q" to quit "top", then the status > will be printed, otherwise it just stands by with blank. > > Question is. Do you know how to give "q" into my python script so that > "top" is automatically quit immediately or maybe after 1s (for > gathering information) > Why not run the actual 'top' command in batch mode with only one iteration? It's in the man page. I'm referring to this: status = os.popen('top -b -n 1').readlines() Also, the following approach seems to display a nicer output: ------------------------------------------------- #!/usr/bin/env python import os status=os.popen('top -b -n 1') for i in status.readlines(): print i ------------------------------------------------- Or how about the following? ------------------------------------------------- #!/usr/bin/env python import commands status=commands.getoutput('top -b -n 1') print status ------------------------------------------------- Mind you, I'm just suggesting different approaches. I'm new to Python and don't necessarily know what I'm doing. Other more experienced people may be able to suggest something better. From kyosohma at gmail.com Mon Aug 31 10:53:27 2009 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Aug 2009 07:53:27 -0700 (PDT) Subject: IDE for Python References: Message-ID: On Aug 29, 1:08?pm, ivanko.... at gmail.com wrote: > 29.08.2009 4:14 ???????????? "Thangappan.M" ? > ???????: > > > Dear all, > > Please suggest some good IDE for python.I am working in linux platform. > > -- > > Regards, > > Thangappan.M > > You can use Eclipse + PyDev or Emacs+PythonMode . Also there are Anjuta and ? > Code:Blocks, but they are designed mainly for C++ (but still can be used). Don't forget Wingware IDE. Admittedly, it's not free (except for a limited version), but it's pretty good. There's also SPE (Stani's Python Editor). If you want a nigh-complete list, check the Python wiki: http://wiki.python.org/moin/PythonEditors ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org From cmpython at gmail.com Mon Aug 31 11:32:19 2009 From: cmpython at gmail.com (Che M) Date: Mon, 31 Aug 2009 08:32:19 -0700 (PDT) Subject: IDE for Python References: Message-ID: <0f5f01d3-220e-4ef8-b55b-0f88f58a0afd@b18g2000vbl.googlegroups.com> On Aug 31, 10:53?am, Mike Driscoll wrote: > On Aug 29, 1:08?pm, ivanko.... at gmail.com wrote: > > > 29.08.2009 4:14 ???????????? "Thangappan.M" ? > > ???????: > > > > Dear all, > > > Please suggest some good IDE for python.I am working in linux platform. > > > -- > > > Regards, > > > Thangappan.M > > > You can use Eclipse + PyDev or Emacs+PythonMode . Also there are Anjuta and ? > > Code:Blocks, but they are designed mainly for C++ (but still can be used). > > Don't forget Wingware IDE. Admittedly, it's not free (except for a > limited version), but it's pretty good. There's also SPE (Stani's > Python Editor). If you want a nigh-complete list, check the Python > wiki: > > http://wiki.python.org/moin/PythonEditors Not sure when an editor gets to be called an IDE, but while on the site that OP should check out this related page: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments From tjreedy at udel.edu Mon Aug 31 11:36:03 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 Aug 2009 11:36:03 -0400 Subject: An assessment of Tkinter and IDLE In-Reply-To: <4A9BD58D.3060808@codebykevin.com> References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> <827effaa-d0f7-4142-b4b9-6f9f8e0e7963@e34g2000vbm.googlegroups.com> <4A9BD58D.3060808@codebykevin.com> Message-ID: Kevin Walzer wrote: www.tkdocs.com [snip] > and you'll have learned a lot. But I think the TkDocs site is essential, > especially in its more advanced discussion of how to put together an > attractive, polished user interface with Tk. Tk has a long-standing > reputation of being the toolkit of choice for quick, simple, ugly > interfaces, and the other resources I've mentioned do nothing to to > change this. The practices that Mark Roseman discusses will allow one to > eventually put together a UI that matches anything that the other big > toolkits (wxPython, PyQt, PyObjC, PyGtk, etc.) can do. > > Hope this helps, It persuaded me to go and start reading. A couple of things of interest. "It would be a great help if you could have a look around, provide any comments, corrections or suggestions, or even help fill in some of the missing pieces. " so no pretense of completeness yet. "In the near future, the plan is to continue refining the tutorial, mainly finishing up the rest of the Perl and Python examples." And from the linked blog "July 09, 2009 Python material in progress. While not yet complete, I've managed to add a very hefty chunk of Python material to the tutorial. I should be able to complete the rest over the next week or so. Would definitely appreciate feedback from any Pythonistas on the existing material. While I hadn't used it before, I think Tkinter may very well be the nicest interface to Tk next to Tcl's (for which Tk was originally designed of course, so you'd expect a bit of an advantage). For people unfamiliar with either language, I think Python's more conventional use of parentheses for functions, the "option=value" syntax, plus other language features it takes advantage of are very attractive and win out over Tcl. The two main parts that I think Tcl does in a nicer way are event bindings and the fact you can create and geometry manage a widget in one statement, while still keeping a handle to a widget around. UPDATE July 17/2009: Most of the rest of the Python examples and code snippets have been added. " tjr From http Mon Aug 31 11:46:42 2009 From: http (Paul Rubin) Date: 31 Aug 2009 08:46:42 -0700 Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: <7xzl9gkmu5.fsf@ruckus.brouhaha.com> elsa writes: > map(myFunc(b='booHoo'), myList) > > Why doesn't this work? is there a way to make it work? You can use functools.partial but a listcomp might be simpler: list(myfunc(a, b='booHoo') for a in myList) There is another listcomp syntax with square brackets, but I try to avoid it because it has broken behavior (leaks the index variable) in Python 2.x. From http Mon Aug 31 11:48:14 2009 From: http (Paul Rubin) Date: 31 Aug 2009 08:48:14 -0700 Subject: lambda functions References: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> Message-ID: <7xvdk4kmrl.fsf@ruckus.brouhaha.com> Pierre writes: > s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s > [index]-1 What are you trying to do here anyway? That looks broken. Maybe you want the list.insert method. From koranthala at gmail.com Mon Aug 31 12:03:13 2009 From: koranthala at gmail.com (koranthala) Date: Mon, 31 Aug 2009 09:03:13 -0700 (PDT) Subject: executable path finding Message-ID: <9d71d0bd-5109-45b6-bce7-114607386063@y10g2000prf.googlegroups.com> Hi, I am creating a python application using py2exe. I am facing a problem which I am not sure how to solve. The application contains many other files associated with it - like icons, config files etc. The executable can be in any directory. If the user creates a shortcut to the executable to run in desktop, the program fails - saying that the icon image cannot be found. But I can run the application properly, if I run it from application directory - where all the other icons, config files etc are kept. How is such issues usually solved? I do not want to hardcode the paths of icons and store the icons in those paths. I guess, we can change the directory to the application directory before running the application. (in __init__.py ???) But how do we find the current directory in that case? I am completely at sea in solving this. This looks to be a very common issue. How is this usually solved? From deets at nospam.web.de Mon Aug 31 12:07:20 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 31 Aug 2009 18:07:20 +0200 Subject: executable path finding References: <9d71d0bd-5109-45b6-bce7-114607386063@y10g2000prf.googlegroups.com> Message-ID: <7g2apoF2nipofU2@mid.uni-berlin.de> koranthala wrote: > Hi, > I am creating a python application using py2exe. I am facing a > problem which I am not sure how to solve. > The application contains many other files associated with it - > like icons, config files etc. The executable can be in any directory. > If the user creates a shortcut to the executable to run in desktop, > the program fails - saying that the icon image cannot be found. But I > can run the application properly, if I run it from application > directory - where all the other icons, config files etc are kept. > How is such issues usually solved? I do not want to hardcode the > paths of icons and store the icons in those paths. I guess, we can > change the directory to the application directory before running the > application. (in __init__.py ???) But how do we find the current > directory in that case? I am completely at sea in solving this. > This looks to be a very common issue. How is this usually solved? You can get the location of a module via module.__file__ This can be used to find a file relative to e.g. the toplevel module/package of your application. The pkg_resources-module of setuptools encapsulates that even into a stream and file-name api. Diez From daniel.watrous at gmail.com Mon Aug 31 12:11:46 2009 From: daniel.watrous at gmail.com (Daniel) Date: Mon, 31 Aug 2009 09:11:46 -0700 (PDT) Subject: find free hard disk space remote windows host Message-ID: <6070a0b2-23db-4824-851b-4920a31bd38e@q14g2000vbi.googlegroups.com> Hello, I'm trying to determine the amount of free hard disk space on a remote windows host. Seems like this should be simple, but it's giving me grief. Here's what I've tried: >>> mystat = os.stat('//remotehost/share/') >>> mystat (16895, 0L, 0, 0, 0, 0, 0L, 1251731920, 1251731289, 1249399952) For some reason it doesn't show the details about space on the remote path. Next I tried this: subprocess.call('dir //remotehost/share/ | find "bytes free"', shell=True) But this only returns the status, not the output, which is what I need. How can I determine the amount of free hard drive space on a remote windows host using python? Thanks From vicente.soler at gmail.com Mon Aug 31 12:19:28 2009 From: vicente.soler at gmail.com (vsoler) Date: Mon, 31 Aug 2009 09:19:28 -0700 (PDT) Subject: Efficient way to sum a product of numbers... Message-ID: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> Hi, After simplifying my problem, I can say that I want to get the sum of the product of two culumns: Say m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] r={'a':4, 'b':5, 'c':6} What I need is the calculation 1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 That is, for each row list in variable 'm' look for its first element in variable 'r' and multiply the value found by the second element in row 'm'. After that, sum all the products. What's an efficient way to do it? I have thousands of these calculations to make on a big data file. Thank you. From python.list at tim.thechases.com Mon Aug 31 12:30:27 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 31 Aug 2009 11:30:27 -0500 Subject: Efficient way to sum a product of numbers... In-Reply-To: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> Message-ID: <4A9BFAA3.3000308@tim.thechases.com> > After simplifying my problem, I can say that I want to get the sum of > the product of two culumns: > > Say > m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] assuming you meant ['c', 3] here... ^ > r={'a':4, 'b':5, 'c':6} > > What I need is the calculation > > 1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 and you mean "3*6" here instead of "3*4", which is 18 instead of 12, making the whole sum 4+10+18=32 Then it sounds like you could do something like result = sum(v * r[k] for k,v in m) where "m" is any arbitrary iterable of tuples. If the keys (the letters) aren't guaranteed to be in "r", then you can use defaults (in this case "0", but could just as likely be "1" depending on your intent): result = sum(v * r.get(k,0) for k,v in m) If the conditions above don't hold, you'll have to introduce me to your new math. ;-) -tkc From rami.chowdhury at gmail.com Mon Aug 31 12:31:25 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Mon, 31 Aug 2009 09:31:25 -0700 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: No need to feed the troll by actually trying to engage in the discussion, but just FYI: > Sanskrit is mostly written in Devanagari these days which is also > useful for selling things to people who speak Hindi and other Indian > languages. Devanagari is what's used for Hindi and a handful of other languages, yes, but most Indian languages (Gujarati, Punjabi, Bengali, and Tamil just to name a few) use different scripts. On Sat, 29 Aug 2009 20:07:17 -0700, Neil Hodgson wrote: > Benjamin Peterson: > >> Like Sanskrit or Snowman language? > > Sanskrit is mostly written in Devanagari these days which is also > useful for selling things to people who speak Hindi and other Indian > languages. > > Not sure if you are referring to the ? snowman character or Arctic > region languages like Canadian Aboriginal syllabic writing like ????? > which were added to Unicode 8 years after the initial version. I'd guess > that was added from political rather than marketing motives. ? was > required since it was present in Japanese character sets. > > Neil -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From koranthala at gmail.com Mon Aug 31 12:37:24 2009 From: koranthala at gmail.com (koranthala) Date: Mon, 31 Aug 2009 09:37:24 -0700 (PDT) Subject: executable path finding References: <9d71d0bd-5109-45b6-bce7-114607386063@y10g2000prf.googlegroups.com> <7g2apoF2nipofU2@mid.uni-berlin.de> Message-ID: <40dd30b5-c65c-4fb2-9a3a-c9264f333018@m7g2000prd.googlegroups.com> On Aug 31, 9:07?pm, "Diez B. Roggisch" wrote: > koranthala wrote: > > Hi, > > ? ? I am creating a python application using py2exe. I am facing a > > problem which I am not sure how to solve. > > ? ? The application contains many other files associated with it - > > like icons, config files etc. The executable can be in any directory. > > If the user creates a shortcut to the executable to run in desktop, > > the program fails - saying that the icon image cannot be found. But I > > can run the application properly, if I run it from application > > directory - where all the other icons, config files etc are kept. > > ? ? How is such issues usually solved? I do not want to hardcode the > > paths of icons and store the icons in those paths. I guess, we can > > change the directory to the application directory before running the > > application. (in __init__.py ???) But how do we find the current > > directory in that case? I am completely at sea in solving this. > > ? ? This looks to be a very common issue. How is this usually solved? > > You can get the location of a module via > > ?module.__file__ > > This can be used to find a file relative to e.g. the toplevel module/package > of your application. > > The pkg_resources-module of setuptools encapsulates that even into a stream > and file-name api. > > Diez Thank you Diez. It was what I was looking for. From robert.kern at gmail.com Mon Aug 31 12:43:30 2009 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 31 Aug 2009 11:43:30 -0500 Subject: rcond in numpy : In-Reply-To: References: Message-ID: On 2009-08-31 04:02 AM, Pierre wrote: > > Hello, > > Anyone knows the numpy equivalent of the matlab function : rcond > (Matrix reciprocal condition number estimate) ? You will want to ask numpy questions on the numpy mailing list: http://www.scipy.org/Mailing_Lists numpy.linalg.cond() will give you the condition number of the matrix. Invert it to get the reciprocal. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From vicente.soler at gmail.com Mon Aug 31 12:43:45 2009 From: vicente.soler at gmail.com (vsoler) Date: Mon, 31 Aug 2009 09:43:45 -0700 (PDT) Subject: Efficient way to sum a product of numbers... References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> Message-ID: <26d7f803-ec2d-4195-a48b-d34c0cbedc84@h30g2000vbr.googlegroups.com> On Aug 31, 6:30?pm, Tim Chase wrote: > > After simplifying my problem, I can say that I want to get the sum of > > the product of two culumns: > > > Say > > ? ? ? ? ?m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] > > assuming you meant ['c', 3] here... ? ?^> ? ? ? ? ?r={'a':4, 'b':5, 'c':6} > > > What I need is the calculation > > > ? ? ? ? ?1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 > > and you mean "3*6" here instead of "3*4", which is 18 instead of > 12, making the whole sum 4+10+18=32 > > Then it sounds like you could do something like > > ? result = sum(v * r[k] for k,v in m) > > where "m" is any arbitrary iterable of tuples. ?If the keys (the > letters) aren't guaranteed to be in "r", then you can use > defaults (in this case "0", but could just as likely be "1" > depending on your intent): > > ? result = sum(v * r.get(k,0) for k,v in m) > > If the conditions above don't hold, you'll have to introduce me > to your new math. ;-) > > -tkc Hello Tim, There is no mistake in my original post, so I really meant [ 'a', 3] Imagine that m contains time sheets of suppliers supplier 'a' has worked for you 1 hour supplier 'b' has worked for you 2 hour supplier 'a' has worked for you 3 hour Now supplier 'a' charges $4 per hour supplier 'b' charges $5 per hour supplier 'c' charges $6 per hour I want to know how much I will be charged this month by my pannel of suppliers. 1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 This is what I am after. I expect all my suppliers to have handed me in advance the per hour fee. If at least one hasn't, I must know that the result is undefined. Hope this helps Vicente Soler From python.list at tim.thechases.com Mon Aug 31 12:59:01 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 31 Aug 2009 11:59:01 -0500 Subject: Efficient way to sum a product of numbers... In-Reply-To: <26d7f803-ec2d-4195-a48b-d34c0cbedc84@h30g2000vbr.googlegroups.com> References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> <26d7f803-ec2d-4195-a48b-d34c0cbedc84@h30g2000vbr.googlegroups.com> Message-ID: <4A9C0155.2090505@tim.thechases.com> vsoler wrote: > On Aug 31, 6:30 pm, Tim Chase wrote: >>> After simplifying my problem, I can say that I want to get the sum of >>> the product of two culumns: >>> Say >>> m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] >> assuming you meant ['c', 3] here... ^> r={'a':4, 'b':5, 'c':6} >> >>> What I need is the calculation >>> 1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 >> and you mean "3*6" here instead of "3*4", which is 18 instead of >> 12, making the whole sum 4+10+18=32 >> >> Then it sounds like you could do something like >> >> result = sum(v * r[k] for k,v in m) >> >> where "m" is any arbitrary iterable of tuples. If the keys (the >> letters) aren't guaranteed to be in "r", then you can use >> defaults (in this case "0", but could just as likely be "1" >> depending on your intent): >> >> result = sum(v * r.get(k,0) for k,v in m) >> >> If the conditions above don't hold, you'll have to introduce me >> to your new math. ;-) > There is no mistake in my original post, so I really meant [ 'a', 3] Ah...that makes more sense of the data. My answer still holds then. Use the r[k] version instead of the r.get(...) version, and it will throw an exception if the rate doesn't exist in your mapping. (a KeyError if you want to catch it) -tkc From rt8396 at gmail.com Mon Aug 31 13:00:01 2009 From: rt8396 at gmail.com (r) Date: Mon, 31 Aug 2009 10:00:01 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> <827effaa-d0f7-4142-b4b9-6f9f8e0e7963@e34g2000vbm.googlegroups.com> <4A9BD58D.3060808@codebykevin.com> Message-ID: Kevin and Terry, Kevin. I respectfully disagree that the site is ready for prime time *However* i do not wish to undermine the great work that Mark Roseman has done here and i thank him for his contribution. He has put much work into covering all the major languages and i think this site *could* turn out to be the best one-stop-shop for Tk coding no matter what language you come use. And Actually of all the sites that i know of, his is by far the most professional/modern looking of all! My only beef with Mark's site is lack of detailed information OR a reference manual of sorts in the Python language. We have too many places around the net one must go to get this information when starting the road to Tkinter. The Effbot site is great with much detail but is not a good reference. John's NMT site is a great reference but lacks the extensive tutorial style details of effbot. Mark's site is the shiny new corvette, however the engine is on back order? We need to compile this info into one beautiful orgy of Tkinter learning material. Here are the three sites that i mentioned above, they would compress well into one... http://effbot.org/tkinterbook/ http://infohost.nmt.edu/tcc/help/pubs/tkinter/ http://www.tkdocs.com/ [TERRY SAID..] While I hadn't used it before, I think Tkinter may very well be the nicest interface to Tk next to Tcl's (for which Tk was originally designed of course, so you'd expect a bit of an advantage). For people unfamiliar with either language, I think Python's more conventional use of parentheses for functions, the "option=value" syntax, plus other language features it takes advantage of are very attractive and win out over Tcl. [/TERRY] Well put Terry! I could not agree more with this assessment! Pythons wrapping of Tk is so beautiful next to the other languages i can bet a lot of Ruby, Tcl, and Perl guys are going to feel like ugly ducklings at a Ms america pageant! (but i may be partial to Python code... just a little) ;-) When it comes to using Tkinter I think a lot of people let ego get in the way. Yes the name may sound synonymous with "Tinker Toys" however, TEE-KAY-ENTER is a great (albeit simple) GUI toolkit. I use it quite often and reach for the power of wx only when i need the extra functionality -- which the gap is starting to close. Anyhow, welcome to Tkinter Terry, i only wished you would had dropped by sooner...??? :) psst: maybe you can use your influence and convince others that Tk is not so bad? From vicente.soler at gmail.com Mon Aug 31 13:13:34 2009 From: vicente.soler at gmail.com (vsoler) Date: Mon, 31 Aug 2009 10:13:34 -0700 (PDT) Subject: Efficient way to sum a product of numbers... References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> <26d7f803-ec2d-4195-a48b-d34c0cbedc84@h30g2000vbr.googlegroups.com> Message-ID: On Aug 31, 6:59?pm, Tim Chase wrote: > vsoler wrote: > > On Aug 31, 6:30 pm, Tim Chase wrote: > >>> After simplifying my problem, I can say that I want to get the sum of > >>> the product of two culumns: > >>> Say > >>> ? ? ? ? ?m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] > >> assuming you meant ['c', 3] here... ? ?^> ? ? ? ? ?r={'a':4, 'b':5, 'c':6} > > >>> What I need is the calculation > >>> ? ? ? ? ?1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 > >> and you mean "3*6" here instead of "3*4", which is 18 instead of > >> 12, making the whole sum 4+10+18=32 > > >> Then it sounds like you could do something like > > >> ? result = sum(v * r[k] for k,v in m) > > >> where "m" is any arbitrary iterable of tuples. ?If the keys (the > >> letters) aren't guaranteed to be in "r", then you can use > >> defaults (in this case "0", but could just as likely be "1" > >> depending on your intent): > > >> ? result = sum(v * r.get(k,0) for k,v in m) > > >> If the conditions above don't hold, you'll have to introduce me > >> to your new math. ;-) > > There is no mistake in my original post, so I really meant [ 'a', 3] > > Ah...that makes more sense of the data. ?My answer still holds > then. ?Use the r[k] version instead of the r.get(...) version, > and it will throw an exception if the rate doesn't exist in your > mapping. ?(a KeyError if you want to catch it) > > -tkc It works!!! Thank you From szport at gmail.com Mon Aug 31 13:21:22 2009 From: szport at gmail.com (zaur) Date: Mon, 31 Aug 2009 10:21:22 -0700 (PDT) Subject: Is behavior of += intentional for int? References: Message-ID: On 29 ???, 16:45, zaur wrote: > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin > Type "copyright", "credits" or "license()" for more information.>>> a=1 > >>> x=[a] > >>> id(a)==id(x[0]) > True > >>> a+=1 > >>> a > 2 > >>> x[0] > > 1 > > I thought that += should only change the value of the int object. But > += create new. > Is this intentional? As a result of this debate is not whether we should conclude that there should be two types of integers in python: 1) immutable numbers, which behave as constant value; 2) mutable numbers, which behave as variable value? From ajoys123 at gmail.com Mon Aug 31 13:23:48 2009 From: ajoys123 at gmail.com (devaru) Date: Mon, 31 Aug 2009 10:23:48 -0700 (PDT) Subject: Logging contents of IRC channel Message-ID: I am new to Python. I want to log the activities in an IRC channel. Any pointers regarding this would be of great help. From rt8396 at gmail.com Mon Aug 31 13:29:22 2009 From: rt8396 at gmail.com (r) Date: Mon, 31 Aug 2009 10:29:22 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> Message-ID: <799b8346-dc43-48be-aee0-bc5b1b235e1e@e34g2000vbm.googlegroups.com> On Aug 28, 11:12?am, Mark Roseman wrote: > Would it be useful to link to this from the main Python Tkinter > documentation? > > Mark Sorry Mark, i did not realize when i replied to you that YOU are the Mark of tkdoc.com. For some reason i only saw Tcl code when i visted the site, and that prompted my slightly grumpy rant. After looking a second time (and actually reading more) i see this site has much promise. I hope my post did not seem condescending of your efforts. I think your site is beautiful and just wish we could add MORE Python specific info to it like i covered in my last post. And also I would like to see a complete coverage of all the widgets. We more experienced guys already know how and where to find the thousand or so sites for this or that Python info, but the new users are going to be lost in the wilderness. I love that Python has so much info out there, i just hate that is so spread out! We must do something about this in a way that all doc/tut creators can be happy. PS: and i would like to contribute to your site. From pavlovevidence at gmail.com Mon Aug 31 13:59:41 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 31 Aug 2009 10:59:41 -0700 (PDT) Subject: Is behavior of += intentional for int? References: Message-ID: On Aug 31, 10:21?am, zaur wrote: > On 29 ???, 16:45, zaur wrote: > > > > > > > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) > > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin > > Type "copyright", "credits" or "license()" for more information.>>> a=1 > > >>> x=[a] > > >>> id(a)==id(x[0]) > > True > > >>> a+=1 > > >>> a > > 2 > > >>> x[0] > > > 1 > > > I thought that += should only change the value of the int object. But > > += create new. > > Is this intentional? > > As a result of this debate is not whether we should conclude that > there should be two types of integers in python: 1) immutable numbers, > which behave as constant value; 2) mutable numbers, which behave as > variable value? You are free to use third-party modules (such as numpy) which provide mutable numbers. I see no reason to include any mutable number type standard library, as not many people will require the performance benefits and/or indirection of mutable numbers, and those who do are free to use third- party modules that provide them. Carl Banks From sccolbert at gmail.com Mon Aug 31 14:15:20 2009 From: sccolbert at gmail.com (Chris Colbert) Date: Mon, 31 Aug 2009 14:15:20 -0400 Subject: IDE for Python In-Reply-To: <0f5f01d3-220e-4ef8-b55b-0f88f58a0afd@b18g2000vbl.googlegroups.com> References: <0f5f01d3-220e-4ef8-b55b-0f88f58a0afd@b18g2000vbl.googlegroups.com> Message-ID: <7f014ea60908311115s33f32d63v39706acba8fad9b3@mail.gmail.com> I'm a big fan of wing. Pay for the non-free version and you get all the goodies, plus PHENOMENAL support. Really. They answer support emails within a few minutes. Its has the best code completion i've seen in any python editor/ide and is also the most stable, fastest (for ide's), and customizable. I am not affiliated with Wingware or their parent company in any way. On Mon, Aug 31, 2009 at 11:32 AM, Che M wrote: > On Aug 31, 10:53?am, Mike Driscoll wrote: >> On Aug 29, 1:08?pm, ivanko.... at gmail.com wrote: >> >> > 29.08.2009 4:14 ???????????? "Thangappan.M" ? >> > ???????: >> >> > > Dear all, >> > > Please suggest some good IDE for python.I am working in linux platform. >> > > -- >> > > Regards, >> > > Thangappan.M >> >> > You can use Eclipse + PyDev or Emacs+PythonMode . Also there are Anjuta and ? >> > Code:Blocks, but they are designed mainly for C++ (but still can be used). >> >> Don't forget Wingware IDE. Admittedly, it's not free (except for a >> limited version), but it's pretty good. There's also SPE (Stani's >> Python Editor). If you want a nigh-complete list, check the Python >> wiki: >> >> http://wiki.python.org/moin/PythonEditors > > Not sure when an editor gets to be called an IDE, but while on the > site > that OP should check out this related page: > > http://wiki.python.org/moin/IntegratedDevelopmentEnvironments > > -- > http://mail.python.org/mailman/listinfo/python-list > From http Mon Aug 31 14:27:03 2009 From: http (Paul Rubin) Date: 31 Aug 2009 11:27:03 -0700 Subject: Efficient way to sum a product of numbers... References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> Message-ID: <7xab1f2614.fsf@ruckus.brouhaha.com> vsoler writes: > m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] > r={'a':4, 'b':5, 'c':6} > > What I need is the calculation > > 1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 sum(r[k]*w for k,w in m) From http Mon Aug 31 14:30:13 2009 From: http (Paul Rubin) Date: 31 Aug 2009 11:30:13 -0700 Subject: Logging contents of IRC channel References: Message-ID: <7x63c325vu.fsf@ruckus.brouhaha.com> devaru writes: > I am new to Python. I want to log the activities in an IRC channel. > Any pointers regarding this would be of great help. http://science.slashdot.org/science/04/04/13/1356216.shtml From mail at timgolden.me.uk Mon Aug 31 14:39:56 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 31 Aug 2009 19:39:56 +0100 Subject: find free hard disk space remote windows host In-Reply-To: <6070a0b2-23db-4824-851b-4920a31bd38e@q14g2000vbi.googlegroups.com> References: <6070a0b2-23db-4824-851b-4920a31bd38e@q14g2000vbi.googlegroups.com> Message-ID: <4A9C18FC.2050702@timgolden.me.uk> Daniel wrote: > Hello, > > I'm trying to determine the amount of free hard disk space on a remote > windows host. Seems like this should be simple, but it's giving me > grief. Here's what I've tried: > >>>> mystat = os.stat('//remotehost/share/') >>>> mystat > (16895, 0L, 0, 0, 0, 0, 0L, 1251731920, 1251731289, 1249399952) Assuming you have the necessary security levels, WMI's quite good at this kind of thing. See this example: http://timgolden.me.uk/python/wmi_cookbook.html#percentage_free and just add "remotehost" as the first parameter to the wmi.WMI () call. (And I recommend find_classes=False) for speed. TJG From jgardner at jonathangardner.net Mon Aug 31 14:56:29 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 31 Aug 2009 11:56:29 -0700 (PDT) Subject: Logging contents of IRC channel References: Message-ID: <395c130e-3269-453f-b8e5-379aea2de7d8@i18g2000pro.googlegroups.com> On Aug 31, 10:23?am, devaru wrote: > I am new to Python. I want to log the activities in an IRC channel. > Any pointers regarding this would be of great help. How are you going to plug into the chat server to obtain the data? How will you store the data? The in between parts are really easy. From 71david at libero.it Mon Aug 31 15:04:27 2009 From: 71david at libero.it (David) Date: Mon, 31 Aug 2009 21:04:27 +0200 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> Message-ID: <171zfm8mhuokq.1e4ltdmqqfp01.dlg@40tude.net> Il Sun, 30 Aug 2009 16:08:46 -0700 (PDT), r ha scritto: > Yes i agree but your logic is flawed. If someone cuts my brake lines > and i cannot stop who is to blame? Or if someone throws nails on the > highway and i crash, who is to blame? Obviously you cannot blame the > car owner. However if i let my brake pads wear out until they are > metal on metal and run over some poor old lady crossing the street -- > well now you got me! ;) > > But you cannot apply this logic when a hacker compromises someones > computer, it the same as cutting their brake lines. How can you > honestly expect that Joe computer user will know of this infection? I expect that user makes periodical and hopefully frequent checks to his computer. Today most of the people simply does absolutely nothing. Obvioulsy there is a vulnerability time between two check, but Perfection does not belongs to human beings so we must accept the risk of being cracked and being aware that we will charged for our computer actions, even if we are not directly responsible. It's a question of point of view: in italy if a thief steals a car and causes an accident the car's owner's assurance (having a car assurance is mandatory) must refund the victims. That's because protections of victims is first priority. Obviously the owner can not be charged >Do > you even know where your brake lines are? Even hackers can be hacked > without ever knowing it! The only sure fire way is VM's or system re- > installs. That's a problem of the computer owner. Why should the rest of the world be charged of *his* problem while keeping him safe from suffering any consequence? >[...] >> I think it's time to switch to responsible computing and the mail-tax would >> charge each person of its own costs and annoyances without affectig the rest >> of the world. > > What, this is madness! If you have terrorist terrorizing your country > you don't tax the public when they blow up a shopping mall so you can > rebuild it! No you kill the terrorist in a harsh and painful manner > and make an example of them, then you seize there monies. You should > direct your anger to the proper internet security authorities(and more > importantly to the perpetrator's) and not the innocent victims of such > attacks. I want you to sit back and think very deeply about your > proposal here because it is horribly wrong. Madness, you say? Let's examine the situation a bit moore deeply. First, the mail-tax would is not for rebuilding the destroyed building after the attack but, at the opposite, to prevent the attack. Wouldn't you pay a small tax to prevent terrorist's attacks? The mail-tax would be really small, if you send 1000 mails at month (a real huge traffic, for a non spammer!) the bill would be about 10 cents. Do you really think this is too much to get rid of most of the spam? Second, today we *are* paying that tax to repair building destroyed by terrorists. We are paying and hidden tax in terms of HW and human resources needed by ISPs to manage that huge (~90%) useless/malicius traffic. (I don't mention const related to dalays, denial of services, theft of informations...) Those costs are obviously charged by ISPs on our montly subscription bill. By the mail-tax we achive 3 results: 1. stopping forever direct spammers. 2. make each owner aware that his computer is compromised when the montly bill is higher than usual. 3. make that owner aware that *he* must pay for *his* problem and the rest of the world (included, I hope, you) is no more willing to be charged for this. The mail-tax may not be Final Solution against spam, but helps a lot. > > It is so easy to just slap a tax on something, yes that will solve > everything. *sarcasm* You should reconsider your position because you are actually blaming the present situation, not my proposal. Finally a little criticims: spam and related malware is a problem growing day by day. I am proposing a solution and if somebody doest't like it, well, he should propose a better one. Just saying "NO!" and turning head aside hoping that the problem will solve by itsef is no more acceptable. > >>> If you want to avoid usenet spam and don't want to filter it yourself, >>> find a provider with more aggressive spam filter. >> >> This is not the solution. You are saying that if your neighbour makes loud >> noises you can not call police to impose him to cease but you can only make >> your home soundproof. > > or you could go over and punch him in the nose, works every time for > me ;-) In italy we say: "preventing is better than treating" (a disease). Regards David From zuo at chopin.edu.pl Mon Aug 31 15:22:20 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Mon, 31 Aug 2009 21:22:20 +0200 Subject: map In-Reply-To: <7xzl9gkmu5.fsf@ruckus.brouhaha.com> References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> <7xzl9gkmu5.fsf@ruckus.brouhaha.com> Message-ID: Another possibilities, if you really *desire* to use map() and not list-comprehension (I'd prefer the latter), are: # Python 2.x: map(func, mylist, itertools.repeat('booHoo', len(mylist))) # Python 3.x, where map() works like Py2.x's itertools.imap(): list(map(func, mylist, itertools.repeat('booHoo'))) Cheers, *j -- Jan Kaliszewski (zuo) From mcravitz at att.net Mon Aug 31 15:43:04 2009 From: mcravitz at att.net (MikeC) Date: Mon, 31 Aug 2009 12:43:04 -0700 (PDT) Subject: win32ui DLL Load Failed Message-ID: I have a python executable that's failing to load on a user's machine running Windows XP. My developer machine is also running Windows XP. I have determined that it is failing when it attempts to load win32ui. I have Python 2.6 on my developer machine and am using the pywin support (Mark Hammonds???) for Python 2.6. In order to make the problem smaller and more managable I created an executable (with pytoexe) of a 1 one-line python script which does the following: import win32ui Running the one-line script on my machine from python source as well as from the executable created from the one-line source works fine on my machine. But when I attempt to run the executable on a target Windows/XP user machine (without Python) it fails with the following traceback Traceback (most recent call last): File "CheckScan.py", line 7, in File "PrintImage.pyc", line 1, in File "win32ui.pyc", line 12, in File "win32ui.pyc", line 10, in __load ImportError: DLL load failed: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. The only thing I can think of regarding the difference between my machine and the target machine is that I have the .NET framework on my machine. Is it possible that that is the problem? Running Depends didn't get me anywhere. I would appreciate any help you can offer. From gordon at panix.com Mon Aug 31 15:44:03 2009 From: gordon at panix.com (John Gordon) Date: Mon, 31 Aug 2009 19:44:03 +0000 (UTC) Subject: Unexpected 411 error response using httplib Message-ID: I'm writing some code that queries a Microsoft Exchange Web Services server. The server is responding with a 411 Length Required error, which is strange because I am definitely sending a Content-Length header. Here's the code: ----------------------------------------------------- import httplib import base64 SoapMessage = """\ Default \ """ host = "some.host.com" username = "myUsername" password = "myPassword" auth = base64.encodestring(username + ":" + password) conn = httplib.HTTPSConnection(host) conn.set_debuglevel(5) conn.putrequest("POST", "/EWS/Exchange.asmx") conn.putheader("Content-type", "text/xml; charset=\"UTF-8\"") conn.putheader("Proxy-Authorization", "Basic %s" % auth) conn.putheader("Content-Length", "%d" % len(SoapMessage)) conn.putheader("User-Agent", "Python post") conn.endheaders() conn.send(SoapMessage) resp = conn.getresponse() body = resp.read() headers = resp.msg version = resp.version status = resp.status reason = resp.reason conn.close() print "Response: ", status, reason print "Headers: ", headers print body ----------------------------------------------------- As you can see, I am including the call to putheader() for Content-Length, and the debugging output confirms that the header is present in the outgoing message. So why am I getting a 411 Length Required error? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From no.email at please.post Mon Aug 31 15:46:37 2009 From: no.email at please.post (kj) Date: Mon, 31 Aug 2009 19:46:37 +0000 (UTC) Subject: pyjamas in action? Message-ID: At work we want to implement a webapp using Google's GWT, and we're debating whether to use the standard GWT approach with Java, or to try Pyjamas. There's no great love here for Java, but there's the concern that Pyjamas will not be able to deliver the full power and/or convenience of standard Java-based GWT. (Why-oh-why did Google pick Java for this? Couldn't Guido twist some arms? Just kidding.) Are there any examples of real production websites implemented with Pyjamas? TIA! kynn From emile at fenx.com Mon Aug 31 15:48:08 2009 From: emile at fenx.com (Emile van Sebille) Date: Mon, 31 Aug 2009 12:48:08 -0700 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <3e9ddb9b-8f61-4d8d-a25c-7e95e8a25c06@g1g2000vbr.googlegroups.com> <200908311019.58029.hendrik@microcorp.co.za> <4A9BDFFE.2040402@wiggly.org> Message-ID: On 8/31/2009 10:41 AM Dennis Lee Bieber said... > On Mon, 31 Aug 2009 15:36:46 +0100, Nigel Rantor >> Also, I'm surprised no-one has mentioned Esperanto yet. Sounds like >> something r and Xah would *love*. >> > Hmmm, thought I had mentioned Esperanto (and Klingon) Just curious -- has anyone mentioned autocoding? :) Emile From kyosohma at gmail.com Mon Aug 31 15:48:37 2009 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Aug 2009 12:48:37 -0700 (PDT) Subject: win32ui DLL Load Failed References: Message-ID: <591c8c0d-8134-4bd6-923f-7b05066c92ad@m20g2000vbp.googlegroups.com> On Aug 31, 2:43?pm, MikeC wrote: > I have a python executable that's failing to load on a user's machine > running Windows XP. My developer machine is also running Windows XP. I > have determined that it is failing when it attempts to load win32ui. > > I have Python 2.6 on my developer machine and am using the pywin > support (Mark Hammonds???) for Python 2.6. > > In order to make the problem smaller and more managable I created an > executable (with pytoexe) of a 1 one-line python script which does the > following: > > import win32ui > > Running the one-line script on my machine from python source as well > as from the executable created from the one-line source works fine on > my machine. But when I attempt to run the executable on a target > Windows/XP user machine (without Python) it fails with the following > traceback > > Traceback (most recent call last): > ? File "CheckScan.py", line 7, in > ? File "PrintImage.pyc", line 1, in > ? File "win32ui.pyc", line 12, in > ? File "win32ui.pyc", line 10, in __load > ImportError: DLL load failed: This application has failed to start > because the application configuration is incorrect. Reinstalling the > application may fix this problem. > > The only thing I can think of regarding the difference between my > machine and the target machine is that I have the .NET framework on my > machine. Is it possible that that is the problem? Running Depends > didn't get me anywhere. I would appreciate any help you can offer. Did you install PyWin32? If so, which version? Here's a link: http://sourceforge.net/projects/pywin32/ - Mike From ckaynor at zindagigames.com Mon Aug 31 15:51:59 2009 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Mon, 31 Aug 2009 12:51:59 -0700 Subject: win32ui DLL Load Failed In-Reply-To: References: Message-ID: You likely need to install the Microsoft Visual C++ 2008 SP1 Redistributable Package on the target machine. If you search Google for this, you should find it (make sure to grab the correct version of x86 or x64 depending upon the Python version). Chris On Mon, Aug 31, 2009 at 12:43 PM, MikeC wrote: > I have a python executable that's failing to load on a user's machine > running Windows XP. My developer machine is also running Windows XP. I > have determined that it is failing when it attempts to load win32ui. > > I have Python 2.6 on my developer machine and am using the pywin > support (Mark Hammonds???) for Python 2.6. > > In order to make the problem smaller and more managable I created an > executable (with pytoexe) of a 1 one-line python script which does the > following: > > import win32ui > > Running the one-line script on my machine from python source as well > as from the executable created from the one-line source works fine on > my machine. But when I attempt to run the executable on a target > Windows/XP user machine (without Python) it fails with the following > traceback > > Traceback (most recent call last): > File "CheckScan.py", line 7, in > File "PrintImage.pyc", line 1, in > File "win32ui.pyc", line 12, in > File "win32ui.pyc", line 10, in __load > ImportError: DLL load failed: This application has failed to start > because the application configuration is incorrect. Reinstalling the > application may fix this problem. > > The only thing I can think of regarding the difference between my > machine and the target machine is that I have the .NET framework on my > machine. Is it possible that that is the problem? Running Depends > didn't get me anywhere. I would appreciate any help you can offer. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nobody at nowhere.com Mon Aug 31 16:20:55 2009 From: nobody at nowhere.com (Nobody) Date: Mon, 31 Aug 2009 21:20:55 +0100 Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: On Sun, 30 Aug 2009 21:55:52 -0700, elsa wrote: > say I have a list, myList. Now say I have a function with more than > one argument: > > myFunc(a, b='None') > > now, say I want to map myFunc onto myList, with always the same > argument for b, but iterating over a: > > map(myFunc(b='booHoo'), myList) > > Why doesn't this work? You're passing the result of (incorrectly) calling myFunc to map(), but you need to pass a function. > is there a way to make it work? If you need to construct a simple function on-the-fly, you can use a lambda form: map(lambda x: myFunc(x, b='booHoo'), myList) Or you could use a list comprehension: [myFunc(x, b='booHoo') for x in myList] From zuo at chopin.edu.pl Mon Aug 31 16:28:56 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Mon, 31 Aug 2009 22:28:56 +0200 Subject: Efficient way to sum a product of numbers... In-Reply-To: <4A9BFAA3.3000308@tim.thechases.com> References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> <4A9BFAA3.3000308@tim.thechases.com> Message-ID: 31-08-2009 o 18:19:28 vsoler wrote: > Say > m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] > r={'a':4, 'b':5, 'c':6} > > What I need is the calculation > > 1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 > > That is, for each row list in variable 'm' look for its first element > in variable 'r' and multiply the value found by the second element in > row 'm'. After that, sum all the products. > > What's an efficient way to do it? I have thousands of these > calculations to make on a big data file. 31-08-2009 o 18:30:27 Tim Chase wrote: > result = sum(v * r[k] for k,v in m) You can also check if this isn't more efficient: from itertools import starmap from operator import mul result = sum(starmap(mul, ((r[name], hour) for name, hour in m))) Or, if you had m in form of two lists: names = ['a', 'b', 'a'] hours = [1, 2, 3] ...then you could do: from itertools import imap as map # <- remove if you use Py3.x from operator import mul result = sum(map(mul, map(r.__getitem__, names), hours)) Cheers, *j PS. I've done a quick test on my computer (Pentium 4, 2.4Ghz, Linux): >>> setup = "from itertools import starmap, imap ; from operator import >>> mul; import random, string; names = >>> [rndom.choice(string.ascii_letters) for x in xrange(10000)]; hours = >>> [random.randint(1, 12) for x in xrange(1000)]; m = zip(names, hours); >>> workers = set(names); r = dict(zip(workers, (random.randint(1, 10) for >>> x in xrange(en(workers)))))" >>> tests = ( ... 'sum(v * r[k] for k,v in m)', ... 'sum(starmap(mul, ((r[name], hour) for name, hour in m)))', ... 'sum(imap(mul, imap(r.__getitem__, names), hours))', ... ) >>> for t in tests: ... print t ... timeit.repeat(t, setup, number=1000) ... print ... sum(v * r[k] for k,v in m) [6.2493009567260742, 6.1892399787902832, 6.2634339332580566] sum(starmap(mul, ((r[name], hour) for name, hour in m))) [9.3293819427490234, 10.280816078186035, 9.2766909599304199] sum(imap(mul, imap(r.__getitem__, names), hours)) [5.7341709136962891, 5.5898380279541016, 5.7318859100341797] -- Jan Kaliszewski (zuo) From andre.roberge at gmail.com Mon Aug 31 16:35:25 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 31 Aug 2009 13:35:25 -0700 (PDT) Subject: pyjamas in action? References: Message-ID: <09fc970b-febe-4c73-9443-e10550bca916@j19g2000vbp.googlegroups.com> On Aug 31, 4:46?pm, kj wrote: > At work we want to implement a webapp using Google's GWT, and we're > debating whether to use the standard GWT approach with Java, or to > try Pyjamas. ?There's no great love here for Java, but there's the > concern that Pyjamas will not be able to deliver the full power > and/or convenience of standard Java-based GWT. ?(Why-oh-why did > Google pick Java for this? ?Couldn't Guido twist some arms? ?Just > kidding.) > > Are there any examples of real production websites implemented with > Pyjamas? > > TIA! > > kynn Perhaps you might get answers faster if you posted to the pyjamas group: http://groups.google.com/group/pyjamas-dev Andr? From mcravitz at att.net Mon Aug 31 16:36:25 2009 From: mcravitz at att.net (MikeC) Date: Mon, 31 Aug 2009 13:36:25 -0700 (PDT) Subject: win32ui DLL Load Failed References: Message-ID: <19449021-bcd4-4917-867f-882b9b586467@p36g2000prn.googlegroups.com> On Aug 31, 12:43?pm, MikeC wrote: > I have a python executable that's failing to load on a user's machine > running Windows XP. My developer machine is also running Windows XP. I > have determined that it is failing when it attempts to load win32ui. > > I have Python 2.6 on my developer machine and am using the pywin > support (Mark Hammonds???) for Python 2.6. > > In order to make the problem smaller and more managable I created an > executable (with pytoexe) of a 1 one-line python script which does the > following: > > import win32ui > > Running the one-line script on my machine from python source as well > as from the executable created from the one-line source works fine on > my machine. But when I attempt to run the executable on a target > Windows/XP user machine (without Python) it fails with the following > traceback > > Traceback (most recent call last): > ? File "CheckScan.py", line 7, in > ? File "PrintImage.pyc", line 1, in > ? File "win32ui.pyc", line 12, in > ? File "win32ui.pyc", line 10, in __load > ImportError: DLL load failed: This application has failed to start > because the application configuration is incorrect. Reinstalling the > application may fix this problem. > > The only thing I can think of regarding the difference between my > machine and the target machine is that I have the .NET framework on my > machine. Is it possible that that is the problem? Running Depends > didn't get me anywhere. I would appreciate any help you can offer. I assume you're asking about my development machine. Yes I have it installed. When I bring up PythonWin.exe, here is what is displayed at the top of the main dialog. PythonWin 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. From zuo at chopin.edu.pl Mon Aug 31 16:40:51 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Mon, 31 Aug 2009 22:40:51 +0200 Subject: Efficient way to sum a product of numbers... In-Reply-To: References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> <4A9BFAA3.3000308@tim.thechases.com> Message-ID: 31-08-2009 o 22:28:56 Jan Kaliszewski wrote: > >>> setup = "from itertools import starmap, imap ; from operator > import mul; import random, string; names = [rndom.choice(string. > ascii_letters) for x in xrange(10000)]; hours = [random.randint( > 1, 12) for x in xrange(1000)]; m = zip(names, hours); workers = > set(names); r = dict(zip(workers, (random.randint(1, 10) for x i > n xrange(en(workers)))))" Erratum -- should be: >>> setup = ( ... 'from itertools import starmap, imap;' ... 'from operator import mul;' ... 'import random, string; names' ... ' = [random.choice(string.ascii_letters)' ... ' for x in xrange(10000)];' ... 'hours = [random.randint(1, 12)' ... for x in xrange(10000)];' ... 'm = zip(names, hours);' ... 'workers = set(names);' ... 'r = dict(zip(workers, (random.randint(1, 10)' ... ' for x in xrange(len(workers)))))' ... ) -- Jan Kaliszewski (zuo) From ethan at stoneleaf.us Mon Aug 31 18:07:02 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 31 Aug 2009 15:07:02 -0700 Subject: Object Reference question In-Reply-To: References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <9feee13c-117e-4806-b238-e4152a68adfb@18g2000yqa.googlegroups.com> Message-ID: <4A9C4986.3010405@stoneleaf.us> josef wrote: > On Aug 27, 1:35 pm, Ethan Furman wrote: > >>josef wrote: >> >>>Thanks to everyone who responded. >> >>>I will be going with some sort of a = MyClass(name = 'a') format. It's >>>the Python way. >> >>>For me, it was very hard to accept that EVERYTHING is an object >>>reference. And that there are no object reference names, just string >>>entries in dictionaries. But I think it all makes sense now. >> >>>Thanks again, >> >>>Josef >> >>My apologies if I missed it, but what *exactly* are you planning on >>doing with your 'name' attribute? From the posts I've seen so far, I >>think you are only setting yourself up for failure. >> >>~Ethan~ > > > I'm going to use it for printing purposes. dk = MyClass(name='dk') > When I need a name dk.name. There will only ever be one dk defined. > > Does that read like I'm setting myself up for failure? I was hoping someone with more expertise than myself would answer that. :) Oh well. The best answer I can give is that you do not want to use 'name' to reference the object itself, but only for printing/debugging purposes. 'name' is just a label for your object, and not necessarily the only label; that particular label may also be lost... Consider: In [5]: class MyClass(object): ...: def __init__(self, name): ...: self.name = name ...: def __repr__(self): ...: return "MyClass(name='%s')" % self.name ...: In [6]: dk = MyClass(name='dk') In [7]: dk Out[7]: MyClass(name='dk') In [8]: se = dk In [9]: del dk In [10]: se Out[10]: MyClass(name='dk') In [11]: dk ------------------------------------------------------------------- NameError Traceback (most recent call last) C:\pythonlib\ in () NameError: name 'dk' is not defined As you can see, just because you have saved the original name does not gaurantee that same name will always reference that same object, or any object. Hope this helps! ~Ethan~ From rhodri at wildebst.demon.co.uk Mon Aug 31 18:40:12 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 31 Aug 2009 23:40:12 +0100 Subject: lambda functions In-Reply-To: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> References: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> Message-ID: On Mon, 31 Aug 2009 08:41:57 +0100, Pierre wrote: > Hello, > > I would like to know if it is possible to define a loop in a lambda > function.... > > How to manage the indents ? Example : > s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s > [index]-1 You can't use commands in a lambda function, only expressions. The nearest thing I can think of to what you want here is to use a list comprehension: s_minus_1 = lambda s : [i-1 for i in s] my_list = s_minus_1(my_list) On the other hand, giving a name to an anonymous function rather defeats the point of it being an *anonymous* function! What are you actually trying to do here? There's almost certainly a better way to do it than this. -- Rhodri James *-* Wildebeest Herder to the Masses From bh at izb.knu.ac.kr Mon Aug 31 19:15:53 2009 From: bh at izb.knu.ac.kr (Byung-Hee HWANG) Date: Tue, 01 Sep 2009 08:15:53 +0900 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <3e9ddb9b-8f61-4d8d-a25c-7e95e8a25c06@g1g2000vbr.googlegroups.com> <200908311019.58029.hendrik@microcorp.co.za> Message-ID: <86tyzninh2.fsf@betla.izb.knu.ac.kr> Nigel Rantor writes: > Hendrik van Rooyen wrote: >> On Sunday 30 August 2009 22:46:49 Dennis Lee Bieber wrote: >> >>> Rather elitist viewpoint... Why don't we just drop nukes on some 60% >>> of populated landmasses that don't have a "western" culture and avoid >>> the whole problem? >> >> Now yer talking, boyo! It will surely help with the basic problem >> which is the heavy infestation of people on the planet! >> :-) > > > On two conditions: > > 1) We drop some "test" bombs on Slough to satisfy Betjeman. > > 2) We strap both Xah and r to aforementioned bombs. > > > > Also, I'm surprised no-one has mentioned Esperanto yet. Sounds like > something r and Xah would *love*. > > Slightly off-topic - does anyone have a good recipe for getting > thunderbird to kill whole threads for good? Either based on a rule or > just some extension I can use? > > The Xah/r threads are like car crashes, I can't help but watch but my > time could be better spent and I don't want to unsub the whole list. > Please do not insult Xah. He spoke nothing in this threads. -- "After the divorce I gave Ginny and the kids more than the courts said I should." -- Johnny Fontane, "Chapter 1", page 36 From ecir.hana at gmail.com Mon Aug 31 19:29:45 2009 From: ecir.hana at gmail.com (Ecir Hana) Date: Mon, 31 Aug 2009 16:29:45 -0700 (PDT) Subject: Executing python script stored as a string Message-ID: <720b423c-7058-4605-96a0-b62f56aec791@s6g2000vbp.googlegroups.com> Hello, please, how to execute a python script stored as a string? But let me impose several limitations, so simple "exec" wont work: - if I understood it correctly defining a function in the string and exec-ing it created the function in current scope. This is something I really don't want - simple exec also blocks the rest of the program - I also would like the string to be able to use and return some parts of the caller So to give an example what I try to achieve: result = [] def up(s): result.append(s.upper()) code = ''' up("abc") print 'hello' i = i + 3 def x(s): up(s) x('def') print i ''' somehow_execute(code) Couple of points: - the script in string should behave just like any other ordinary python script executed in separate process, except it should also know about a function caller "up". Nothing else. (I read that something similar is possible while embedding python into your C project - that you could invoke the VM and provide some default "imports") - if the other script runs in separate process how should it call the remote function? And how to pass its arguments? I really hope I don't have to serialize every communication, maybe I should use threading instead of process? All I want is that running it wont block the caller and that it cannot modify callers code/variables/scope (apart from calling the predefined callers' functions). Or maybe even better, let it block the caller but provide a way to stop its execution? - how to know that the script finished? I was thinking about atexit() - could it work here? Think of it as a text editor with a special ability to execute its content, while providing access of some of its functionality to the script. The reason I *think* I cannot just simple import the "editor" module into the script is that the"editor" is GUI application and script should have access to just this instance of editor. Anyway, I hope I was not too confusing. Thanks for any help! From steve at REMOVE-THIS-cybersource.com.au Mon Aug 31 19:31:14 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Aug 2009 23:31:14 GMT Subject: Is behavior of += intentional for int? References: Message-ID: <0025e0c6$0$2930$c3e8da3@news.astraweb.com> On Mon, 31 Aug 2009 10:21:22 -0700, zaur wrote: > As a result of this debate is not whether we should conclude that there > should be two types of integers in python: 1) immutable numbers, which > behave as constant value; 2) mutable numbers, which behave as variable > value? What can you do with mutable numbers that you can't do with immutable ones, and why do you want to do it? -- Steven From aahz at pythoncraft.com Mon Aug 31 19:52:35 2009 From: aahz at pythoncraft.com (Aahz) Date: 31 Aug 2009 16:52:35 -0700 Subject: a popen question. Please help References: <473423.84282.qm@web36903.mail.mud.yahoo.com> <4A9A65D7.4020308@tim.thechases.com> <50697b2c0908300449i65d22994ra6d63b0bbdb1d201@mail.gmail.com> Message-ID: In article , Tim Chase wrote: > >Darn "standards" :-/ The wonderful thing about standards is that there are so many to choose from. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From aahz at pythoncraft.com Mon Aug 31 20:00:31 2009 From: aahz at pythoncraft.com (Aahz) Date: 31 Aug 2009 17:00:31 -0700 Subject: Overriding iadd for dictionary like objects References: Message-ID: In article , RunThePun wrote: >On Aug 30, 10:33=A0pm, a... at pythoncraft.com (Aahz) wrote: >> In article .com>, >> RunThePun =A0 wrote: >>> >>>I made a DictMixin where the keys are filenames and the values are the >>>file contents. It was very simple and easy to do thanks to DictMixin. >>> >>>For example this code writes "abc" in a file named "temp.txt" and >>>prints the contents of the file named "swallow", these files are >>>looked up/created/deleted in the directory "spam": >>>>>> d =3D3D FilesDict('spam') >>>>>> d['temp.txt'] =3D3D 'abc' >>>>>> print(d['swallow']) >>> >>>My problem arose when I wanted to append a string to a file which >>>using open(..., 'ab') would have been miles more efficient because I >>>wouldn't have to read the entire file (__getitem__) and then write the >>>entire file back (__setitem__). The files are expected to be as big as >>>600 KB which will be appended 30 bytes at a time about 3 times a >>>second. Performance-wise the system would probably work without open >>>(..., 'ab') but it would be a real thrashing so the current solution >>>uses a method "AddTo" as Robert suggested, sacrificing the neat >>>getitem/setitem syntax. >> >> You can do mostly what you want, I think, by having __setitem__() >> convert string values into FileProxy() objects that have an appropriate >> __iadd__() method. =A0That brings a whole new set of problems, of course. > >I'm guessing you meant __getitem__, which is what Jan Kaliszewski >suggested, but as you noted, would be a bit cumbersome in this case. Actually, what I meant was __setitem__. The idea is that you create the proxy item when you add the data to the dict (wrapping the original data), and the proxy has an __iadd__ method, which would allow you to do the file append. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From trinh.vo at jpl.nasa.gov Mon Aug 31 21:32:26 2009 From: trinh.vo at jpl.nasa.gov (Vo, Trinh (388C)) Date: Mon, 31 Aug 2009 18:32:26 -0700 Subject: Python installation Message-ID: <63E24D720DCE7246ABAA722B52D23CDF0153D3073233@ALTPHYEMBEVSP10.RES.AD.JPL> Hello Python Users, I am new to Python. I have errors message when I installed Python. I appreciate if you can help. I download Python-2.6-2. I then did the following steps: ./configure make In the second step "make", I had the following message: Failed to find the necessary bits to build these modules: _bsddb _curses _curses_panel _hashlib _sqlite3 _ssl _tkinter bsddb185 bz2 dbm dl gdbm imageop readline sunaudiodev To find the necessary bits, look in setup.py in detect_modules() for the module's name. I however still saw the binary python was installed in /usr/local/Python-2.6.2. I tested, and it till run OK. However, I am worried if the above message can cause any problem in the future. I have on my cluster: X86_64 GCC version 4.1.2 (Red Hat 4.1.2-42) Thank you, Trinh Vo -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Mon Aug 31 22:26:26 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 31 Aug 2009 22:26:26 -0400 Subject: Python installation In-Reply-To: <63E24D720DCE7246ABAA722B52D23CDF0153D3073233@ALTPHYEMBEVSP10.RES.AD.JPL> References: <63E24D720DCE7246ABAA722B52D23CDF0153D3073233@ALTPHYEMBEVSP10.RES.AD.JPL> Message-ID: On Mon, Aug 31, 2009 at 9:32 PM, Vo, Trinh (388C) wrote: > Hello Python Users, > > > > I am new to Python.? I have errors message when I installed Python.? I > appreciate if you can help. > > > > I download Python-2.6-2.? I then did the following steps: > > ./configure > > make > > > > In the second step ?make?, I had the following message: > > > > > > Failed to find the necessary bits to build these modules: > > _bsddb???????????? _curses??????????? _curses_panel > > _hashlib?????????? _sqlite3?????????? _ssl > > _tkinter?????????? bsddb185?????????? bz2 > > dbm??????????????? dl???????????????? gdbm > > imageop??????????? readline?????????? sunaudiodev > > To find the necessary bits, look in setup.py in detect_modules() for the > module's name. > > I however still saw the binary python was installed in > /usr/local/Python-2.6.2.? I tested, and it till run OK.? However, I am > worried if the above message can cause any problem in ?the future.? I have > on my cluster: > > X86_64 > > GCC version 4.1.2 ?(Red Hat 4.1.2-42) > It's only a problem if you want to use those modules. Personally, I would rebuild it with some more of those (just install those libraries and the dev versions if red hat keeps them separate) but Python can run fine without them. > > > Thank you, > > > > Trinh Vo > > -- > http://mail.python.org/mailman/listinfo/python-list > > From terry.yinzhe at gmail.com Mon Aug 31 22:37:10 2009 From: terry.yinzhe at gmail.com (Terry) Date: Mon, 31 Aug 2009 19:37:10 -0700 (PDT) Subject: Return value of multiprocessing manager registerred function References: <4337084f-cf9b-4b9c-a0cc-ba8f0821f31a@v15g2000prn.googlegroups.com> Message-ID: <69078aec-d556-4a7b-963e-373fe0b39c9e@b18g2000vbl.googlegroups.com> On Aug 31, 5:58?pm, jacopo wrote: > Hi Terry, > I have just started working on similar things and I am strugling to > find examples or documentations. So far I have found only the official > documentation of the multiprocessing package. Would you be able to > recommend me some good reference or a book. I dont want to overwhelm > this newsgroup with questions... yet :) > Regards, Jacopo > > On Aug 26, 4:22?am, Terry wrote: > > > > > Hi, > > > I'm using the multiprocessing.manager to run proceduresremotely. It > > all worked fine except I hope to have a different return value type. > > > The remote function calls always return a proxy, which when I need to > > get the value it need to connect to the manager again to fetch it. But > > I just need the value, not the proxy. > > > Can I just return the value instead of a proxy from a manager? > > > br, Terry Hi Jacopo, Well, I also have had a hard time to find any examples or document except the official document. I had to read the multiprocessing source code (they are all in python except the network connection parts). And I found I need to hack it a little to get it work. You can share your questions, and maybe it's common to most of us. br, Terry From terry.yinzhe at gmail.com Mon Aug 31 22:41:26 2009 From: terry.yinzhe at gmail.com (Terry) Date: Mon, 31 Aug 2009 19:41:26 -0700 (PDT) Subject: multiprocessing managers and socket connection. References: <722664f1-81af-45da-ae40-070bca8f3ee0@k6g2000yqn.googlegroups.com> <0af6687a-e36d-47c3-af5e-7e66eacbb3ce@v23g2000pro.googlegroups.com> <7d8f3f17-3cd7-4eb1-b049-2990d638cc46@o6g2000yqj.googlegroups.com> Message-ID: <6be90391-085f-4ba1-9ed4-88f77ad11c2d@e18g2000vbe.googlegroups.com> On Aug 26, 7:25?pm, Chris wrote: > On Aug 25, 9:11?pm, Terry wrote: > > > > > > > On Aug 25, 10:14?pm, Chris wrote: > > > > I've been using multiprocessing managers and I really like the > > > functionality. > > > > I have a question about reconnecting to a manager. I have a situation > > > where I start on one machine (A) a manager that is listening and then > > > on another machine (B) connects to that manager and uses its proxy > > > object to call functions on the manager's computer; this all works as > > > expected. But, if the manager from A shuts down, B's application won't > > > notice because in the MP code it ignores socket error > > > errno.ECONNREFUSED. If A becomes available again or is restarted, B > > > doesn't automatically reconnect either and continue its operation. > > > It's function is basically stopped. > > > > Here is the code from connection.py: > > > while 1: > > > ? ? ? ? try: > > > ? ? ? ? ? ? s.connect(address) > > > ? ? ? ? except socket.error, e: > > > ? ? ? ? ? ? if e.args[0] != errno.ECONNREFUSED: # connection refused > > > ? ? ? ? ? ? ? ? debug('failed to connect to address %s', address) > > > ? ? ? ? ? ? ? ? raise > > > ? ? ? ? ? ? time.sleep(0.01) > > > ? ? ? ? else: > > > ? ? ? ? ? ? break > > > > How can I have B automatically reconnect to A and continue its work > > > once A is available again? > > > I think you need to retry repeatedly until successfully connected. > > > br, Terry > > I'm having issue after once connected. If the server goes down during > a long-running connection. I would want to be notified so I could try > to reconnect. I'm doing more experimenting now and will try to post an > example. Hi Chris, Are you sure that the proxy object keeps a permanent connection to the server? br, Terry From 71david at libero.it Mon Aug 31 23:06:14 2009 From: 71david at libero.it (David) Date: Tue, 1 Sep 2009 05:06:14 +0200 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> <171zfm8mhuokq.1e4ltdmqqfp01.dlg@40tude.net> Message-ID: <121ziuuxjq6wq$.1vey8y61a3y3s$.dlg@40tude.net> Il Mon, 31 Aug 2009 21:04:27 +0200, David ha scritto: > Obviously the owner can not be charged I mean: can not be jailed for crimes made by the thief using his car. D. From rt8396 at gmail.com Mon Aug 31 23:06:54 2009 From: rt8396 at gmail.com (r) Date: Mon, 31 Aug 2009 20:06:54 -0700 (PDT) Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> <171zfm8mhuokq.1e4ltdmqqfp01.dlg@40tude.net> Message-ID: On Aug 31, 2:04?pm, David <71da... at libero.it> wrote: (snip) > It's a question of point of view: in italy if a thief steals a car and > causes an accident the car's owner's assurance (having a car assurance is > mandatory) must refund the victims. That's because protections of victims is > first priority. > Obviously the owner can not be charged Is the car owner not a victim too? :). i am ok with the filthy insurance company paying as long as the owners rates don't increase. But why can't we force the criminal into hard labor to pay back the lost monies? Seems like that would serve justice to all parties... > That's a problem of the computer owner. Why should the rest of the world be > charged of *his* problem while keeping him safe from suffering any > consequence? No, why should spammers feel safe while doing their crimes? I say put the pressure on criminals, and NOT the victims. I really doubt much is being done to fight spam now that is why it is so prevalent. Two FBI hackers can't keep up with billions of spams. > Madness, you say? Let's examine the situation a bit moore deeply. > > First, the mail-tax would is not for rebuilding the destroyed building after > the attack but, at the opposite, to prevent the attack. Wouldn't you pay a > small tax to prevent terrorist's attacks? Only if that tax was given to highly trained US Marines who where given a green light to use any and all methods to brutally kill the enemy and make an example of him with no worry of prosecution by their own government. > The mail-tax would be really small, if you send 1000 mails at month (a real > huge traffic, for a non spammer!) the bill would be about 10 cents. > Do you really think this is too much to get rid of most of the spam? I don't think that will stop most spammers since they must be making more that a 10c a month profit or they would starve to death! I say why not put a 1000.00 fine on any idiot that responds to a spam! What about that? > We are paying and hidden tax in terms of HW and human resources needed by > ISPs to manage that huge (~90%) useless/malicius traffic. (I don't mention > const related to dalays, denial of services, theft of informations...) (...snip) The system is definitely flawed. I am no internet expert so i don't really know what we could do to fix it. I do fear goverment or corporations taking over of the internet and robbing use of our freedom of speech under the pretense that they will *somehow* save us from the spammers. Something must be done however. I *do* know however that M$ windows ships with its back doors wide open and you could put a lot of blame of M$ for this stupidity! And since their product is meant for computing morons why do they still ship it in such a vulnerable state... complete madness! > Finally a little criticims: spam and related malware is a problem growing > day by day. I am proposing a solution and if somebody doest't like it, well, > he should propose a better one. Just saying "NO!" and turning head aside > hoping that the problem will solve by itsef is no more acceptable. (snip) I agree with you, we must do something... From steven at REMOVE.THIS.cybersource.com.au Mon Aug 31 23:31:35 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 01 Sep 2009 03:31:35 GMT Subject: Executing python script stored as a string References: <720b423c-7058-4605-96a0-b62f56aec791@s6g2000vbp.googlegroups.com> Message-ID: On Mon, 31 Aug 2009 16:29:45 -0700, Ecir Hana wrote: > Hello, > > please, how to execute a python script stored as a string? But let me > impose several limitations, so simple "exec" wont work: > > - if I understood it correctly defining a function in the string and > exec-ing it created the function in current scope. This is something I > really don't want You can pass in a global and local namespaces to exec as arguments: >>> x = 4 >>> ns = {'x': 4} >>> exec "x += 1" in ns >>> x 4 >>> ns['x'] 5 See the docs for details. > - simple exec also blocks the rest of the program Run it in a thread. > - I also would like the string to be able to use and return some parts > of the caller You can copy the parts of the current scope into the namespace you pass to exec, then later copy the revised values out again. But are you sure you really want to take this approach? exec is up to ten times slower than just executing the code directly. And if the string is coming from an untrusted source, it is a *huge* security risk. > Couple of points: > > - the script in string should behave just like any other ordinary python > script executed in separate process, except it should also know about a > function caller "up". Nothing else. (I read that something similar is > possible while embedding python into your C project - that you could > invoke the VM and provide some default "imports") If you want it to execute in a separate *process*, that's a whole different question. If you do that, you get separation of code for free, as well as separate namespaces. My approach would be to have a special module "common" which subprocesses can import, to get access to the shared functions. You will probably need to create some sort of message passing infrastructure to get results out of the subprocess into the parent process. > - if the other script runs in separate process how should it call the > remote function? And how to pass its arguments? I really hope I don't > have to serialize every communication, maybe I should use threading > instead of process? If you want separate processes, they're *separate*. Threads are not. > All I want is that running it wont block the caller > and that it cannot modify callers code/variables/scope (apart from > calling the predefined callers' functions). Or maybe even better, let it > block the caller but provide a way to stop its execution? As far as I know, you can't kill threads, you can only ask them to kill themselves. > - how to know that the script finished? I was thinking about atexit() - > could it work here? I doubt it. You would need to poll each thread to see if it has completed. > Think of it as a text editor with a special ability to execute its > content, while providing access of some of its functionality to the > script. Something like this? In the text editor, you have contents: text goes here and more text # Python script starts here x = 'a' up(x) print "foo" # Python script stops here more text again and the user selects lines 4 and 5 and chooses the command "Execute". The script executes, and its output (foo) is appended to the end of the file: text goes here and more text # Python script starts here x = 'a' up(x) print "foo" # Python script stops here more text again foo Is this what you mean? If so, I think you are making this much too complicated for such a simple use-case. Just publish an API which the script can use, and have the main text editor application specify a "script" namespace containing only that API. That could be a module: >>> import math # pretend this is your API shared module >>> exec "myvalue = 42" in math.__dict__ >>> math.myvalue 42 Then execute the text using exec, but don't bother about putting it into a thread or subprocess. That just makes it harder to implement, and you have to worry about concurrency issues. -- Steven From gagsl-py2 at yahoo.com.ar Sat Aug 1 00:04:27 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 01 Aug 2009 01:04:27 -0300 Subject: problem on socket programming References: <3de0863c-15ef-4153-8d0f-6b7a438b98f5@c2g2000yqi.googlegroups.com> <67ec3e6d-0995-459a-a7a5-3bc296729664@b15g2000yqd.googlegroups.com> <7dg2niF2bue0tU2@mid.uni-berlin.de> <5dbf451d-a289-40d1-83db-ce655d47f698@r38g2000yqn.googlegroups.com> <7dg55pF2bfubpU1@mid.uni-berlin.de> <72f851f9-a2d4-4448-900d-3fe20e4ebeb0@w41g2000yqb.googlegroups.com> Message-ID: En Fri, 31 Jul 2009 10:43:49 -0300, MalC0de escribi?: > none of you can't interpret it ? do you have errors like me !? Have you tried Diez B. Roggisch suggestion? : >> Can you ping and telnet to the port on the desired server? >> Firewalls can be an issue here. The official doc page for the socket module contains a working example of an echo client/server program like yours: http://docs.python.org/library/socket.html#example -- Gabriel Genellina From emmanuel.surleau at gmail.com Sat Aug 1 00:20:28 2009 From: emmanuel.surleau at gmail.com (Emmanuel Surleau) Date: Sat, 1 Aug 2009 06:20:28 +0200 Subject: Confessions of a Python fanboy In-Reply-To: <008f7990$0$9756$c3e8da3@news.astraweb.com> References: <008f7990$0$9756$c3e8da3@news.astraweb.com> Message-ID: <200908010620.28665.emmanuel.surleau@gmail.com> On Saturday 01 August 2009 03:46:12 Steven D'Aprano wrote: > On Fri, 31 Jul 2009 20:41:12 +0200, Emmanuel Surleau wrote: > >> We don't actually *declare* that something is constant and then have > >> that declaration ignored. Python doesn't lie to us, although (as in any > >> language) a programmer might. > > > > You could say that Ruby doesn't either, > > Well you could say a lot of things. Admittedly you don't need a separate > "constant" declaration, but creating a variable name with an initial > uppercase letter is sufficient to make it a (supposed) constant: *shrugs* I see it as a way to encourage (but not force) people to follow a coding convention. Is this such a bad thing? > irb(main):049:0* Thing = 5 > => 5 > irb(main):050:0> Thing = 7 > (irb):50: warning: already initialized constant Thing > => 7 > > As you can see, Ruby (well, irb at least) considers that Thing is a > constant, and then goes ahead and changes it anyway. I'm quite aware of how constants work in Ruby, yes :) > Apart from the use of an arbitrary naming convention instead of an > explicit "make this constant" declaration, and the feeble way Ruby > capitulates when you change it, I think having actual write-once > constants is actually a plus. Nothing wrong with naming conventions. This encourages a uniform coding style, something which Python could really use. > > you just need to read the > > documentation. Ruby's unwritten motto is "flexibility ?ber alles". In > > this regard, it is consistent (1). > > "It's consistent in its inconsistency" sort of thing perhaps? No, just consistent. > > Not much is really bolted down in > > Ruby. You get encapsulation, but it's so easy to break that it's mostly > > symbolic. > > Out of curiosity, can you read/write class and instance attributes from > outside the class without using a getter/setter? If you have an instance f class with a attribute @foo which doesn't have an accessor, you could do: f.instance_eval("@foo='bar'") And yes, instance_eval is evil. Cheers, Emm From gagsl-py2 at yahoo.com.ar Sat Aug 1 00:48:50 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 01 Aug 2009 01:48:50 -0300 Subject: Newbie Question regarding __init__() References: Message-ID: En Sat, 01 Aug 2009 00:13:05 -0300, Nat Williams escribi?: > One other thing. I'm a little confused by the first line of > dcObject.__init__: > > self.init_Pre() and self.init_Exec() > > I suspect this does not do what you think it does. init_Pre and > init_Exec > will both be called by this expression (unless init_Pre throws an > exception, > of course). You're not getting anything here that you wouldn't by just > calling each method on a separate line, except just making it harder to > read. Well, perhaps Simon didn't grasp Python's syntax and semantics very well yet, but his code would work as designed after fixing obvious errors: class dcObject(object): """Base Object""" def __init__(self): """default init method has the form of init_Pre() and init_Exec init_Post()""" self.init_Pre() and self.init_Exec() self.init_Post() def init_Pre(self): """Always called before init_Exec() if it returns false init_Exec is not executed""" return True def init_Exec(self): """Base __init__ code goes here and this is only executed if init_Pre() returns true""" return True def init_Post(self): """Always called after the init_Pre() and init_Exec()""" return True init_Pre might return False, in that case init_Exec would not be executed. init_Post is always called. And that's exactly what the docstrings say. I would use an `if` statement instead: if self.init_Pre(): self.init_Exec() and make init_Exec and init_Post not return anything if they have no intrinsic meaning. And probably use better names. But basically the structure is OK. -- Gabriel Genellina From nad at acm.org Sat Aug 1 00:55:34 2009 From: nad at acm.org (Ned Deily) Date: Fri, 31 Jul 2009 21:55:34 -0700 Subject: Python docs disappointing References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: In article , Terry Reedy wrote: > This is one area where Windows users seems to have an advantage. The > standard installer includes the doc set as a Windows help file. I often > keep that open in one window while programming in others. I only later > discovered that this was a copy of the online docs ;-), which I only use > to check the in-development version before submitting a doc bug. The python.org Mac OS X installers include the complete documentation set for that version in HTML; the IDLE Help menu will open the front page in a browser (from where you can bookmark it for later use). -- Ned Deily, nad at acm.org From riaz.ahmadskh at gmail.com Sat Aug 1 03:02:51 2009 From: riaz.ahmadskh at gmail.com (Riaz Ahmad) Date: Sat, 1 Aug 2009 00:02:51 -0700 (PDT) Subject: "ADMISSION IN FA FSC" "ADMISSION IN FA/FSC" "ADMISSION IN GC UNIVERSITY LAHORE" "ADMISSION IN SCIENCE COLLEGE LAHORE" "ADMISSION IN KIPS LAHORE" "ADMISSION IN LEADERSHIP COLLEGE LAHORE" "ADMISSION IN BAHAUDDIN ZAKARIYA UNIVERSITY MULTAN" Message-ID: <38954c7f-1af5-4739-8982-6193b280d4da@d36g2000prb.googlegroups.com> "ADMISSION IN FA FSC" www.admissionspk.blogspot.com "ADMISSION IN FA/FSC" www.admissionspk.blogspot.com "ADMISSION IN GC UNIVERSITY LAHORE" www.admissionspk.blogspot.com "ADMISSION IN SCIENCE COLLEGE LAHORE" www.admissionspk.blogspot.com "ADMISSION IN KIPS LAHORE" www.admissionspk.blogspot.com "ADMISSION IN LEADERSHIP COLLEGE LAHORE" www.admissionspk.blogspot.com "ADMISSION IN BAHAUDDIN ZAKARIYA UNIVERSITY MULTAN" www.admissionspk.blogspot.com www.admissionspk.blogspot.com From robertrobert93 at yahoo.com Sat Aug 1 03:34:58 2009 From: robertrobert93 at yahoo.com (Robert Robert) Date: Sat, 1 Aug 2009 00:34:58 -0700 (PDT) Subject: fil open close very slow Message-ID: <950181.91001.qm@web59306.mail.re1.yahoo.com> hiya all, I have a "large" script written in python. There is in that big script at a certain point a loop in which I create a lots of simple small text files. Each text file just contain I think 4 or 5 short lines. When I simply run it in IDLE, it runs fast. But when?I compile it to binary files, it becomes very slow. I turned on the profiler and discorvered it was slow at the open() and close() calls. I removed those calls to confirm this, and yes my program runs very fast then. Does anyone has an idea or suggestion why this can be possible. I only compile them to .pyc files, which as what I see, when I normally run in IDLe these files are created as well, so I really got no clue. rh. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Sat Aug 1 03:53:51 2009 From: rt8396 at gmail.com (r) Date: Sat, 1 Aug 2009 00:53:51 -0700 (PDT) Subject: possible to round number and convert to string? References: <24763821.post@talk.nabble.com> <4a737350$0$28514$4fafbaef@reader2.news.tin.it> Message-ID: <4e60ee41-44a2-4e23-b3dd-70a8549026e0@a13g2000yqc.googlegroups.com> On Jul 31, 7:42?pm, "Dr. Phillip M. Feldman" wrote: > This was very close to what I wanted. ?Thanks! ?My final code looks like > this: > > def num2str(x,f=4): > ? ?"""Convert x (int or float) to a string with f digits to right of > ? ?the decimal point. ?f may be zero or negative, in which case the decimal > ? ?point is suppressed.""" > ? ?s= str(round(x,f)) > ? ?if f<=0: > ? ? ? # Delete decimal point: > ? ? ? i= s.find('.') > ? ? ? if i>0: s= s[:i] > ? ?return s Is it *really* necessary to create a named function for something as trivial as this? >>> import math >>> '%0.3f' %math.pi '3.142' >>> '%d' %math.pi '3' Seems string formatting is more "pythonic" -- opps, now why did i have to go and say that... :) From dickinsm at gmail.com Sat Aug 1 04:36:11 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 1 Aug 2009 01:36:11 -0700 (PDT) Subject: possible to round number and convert to string? References: Message-ID: On Jul 31, 11:17?pm, "Dr. Phillip M. Feldman" wrote: > I'd like to be able to convert a float to a string representation in which > the number is rounded to a specified number of digits. ?If num2str is a > hypothetical function that does this, then num2str(pi,3) would be '3.142' > (not '3.141'). Python's string formatting does exactly this. Python 2.6.2 (r262:71600, Jul 8 2009, 09:56:31) [GCC 4.0.1 (Apple Inc. build 5490)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> num2str = '{0:.{1}f}'.format >>> num2str(3.14159, 3) '3.142' (In Python 3.1, num2str = '{:.{}f}'.format is enough.) Mark From john_re at fastmail.us Sat Aug 1 04:52:28 2009 From: john_re at fastmail.us (john_re) Date: Sat, 01 Aug 2009 01:52:28 -0700 Subject: Aug 1 & 16- Global VOIP Free SW HW Culture meeting, BerkeleyTIP, For Forwarding Message-ID: <1249116748.25769.1327808157@webmail.messagingengine.com> Interested in joining the friendly global Free SW HW & Culture communities in a global Voice meeting? You?re invited. :) You can join from your home, or better: get a local meeting together. Tip: a college WiFi cafe could be a great local meeting place. Make sure you have a VOIP headset! For all details, see the website (I?m leaving out many sublinks to make this email smaller). http://sites.google.com/site/berkeleytip Start by joining #berkeleytip on IRC freenode.net. We?ll help you get your VOIP connection working. :) ===== MARK YOUR CALENDARS: 1st Sat & 3rd Sunday each month. August 1 & 16. 10A - 6P Pacific US time (+7H GMT, IIRC) = 1P-9P Eastern US time = 5P - 1A GMT ? Or, come to the local meeting on the UC Berkeley campus. NOTE: SPECIAL LOCATION AUG 1: SEE BTIP WEBSITE FOR LOCATION, & RSVP TO ME OR THE BTIP LISTS. AUG 1 MEETING WILL BE 12N - 3P AT THE BTIP VOIP SERVER LOCATION ON THE UCB CAMPUS. SEE THE WEBSITE FOR ROOM LOCATION. We?ll hack on the new BTIP Asterisk VOIP server, in its presence. PLEASE RSVP TO ME (John) OR THE LIST IF YOU WANT TO MEET AT OUR USUAL LOCATION, THE FREE SPEECH CAFE, 10A-12n, 3-6PM, (otherwise i might not be there). ===== MEETING TOPICS FOR AUGUST: 1) Whatever _you_ want to work on - Email the BTIPGlobal list & let us know what your interests are. 2) Our VOIP conference server, using Asterisk. 3) Planning for year 2. ===== JOIN FOR THE START OF YEAR 2 GLOBAL MEETINGs: We had a great first year. We had local attendees from around the San Francisco Bay Area & Northern California. High School, College, Grad Students, & working & retired people attended. >From the US, people joined the meeting (IRC or VOIP) from Hawaii to Virgina, Washington to Michigan to Florida. (+ California & other states.) Globally, Sweden, Germany, England, Ireland, Iran & India (& maybe others I don?t recall right now.) :) In May Richard Stallman joined the global meeting for Q & A about free SW & HW. == YEAR 2 FOCUS: COLLEGE LOCAL MEETINGS, & AMERICAS? ANNOUNCEMENTS. Two main things I?ll focus on this year: 1) Inviting groups to join at colleges & universities - BTIP is educational. My hope: if more students learn about free SW hw & culture, some of them will then go on to become _contributors_. :) 2) I?ll try to get monthly announcements out to the biggest LUGs in the 10 largest countries in the Americas. == What would _YOU_ like to accomplish this year? Email the BTIP mail list, say ?hi?, tell us about your interests, projects & desires. ===== FOR FORWARDING - You are invited to forward this announcement wherever you think it might be appreciated. From hitechpundir at gmail.com Sat Aug 1 05:22:28 2009 From: hitechpundir at gmail.com (sirjee) Date: Sat, 1 Aug 2009 02:22:28 -0700 (PDT) Subject: problem in event handling on change of variable value. Message-ID: <9c0d7a31-0310-4499-9974-92afc588f315@d15g2000prc.googlegroups.com> hello; i m facing a problem in handling events on change of value of environment variable in a tool CANoe. class CANoeEvents: def OnChange(self,value): print "value of environment variable has changed" def OnOpen(self,App): print "opening Application" App_Event = DispatchWithEvents('CANoe.Application',CANoeEvents) time.sleep(2) App_Event.Open("C:\projectConfig.cfg") # printd "opening Application" and event handled properly. .......(now a code file runs in the canoe in which value of environment variable called dummy is changed during execution. Just like OnOpen; OnChange is defined in specification which should be called on change of environment variable.But it is not happening.) while (): myenvVar = App_Event.Environment.GetVariable("dummy") The VB does it very easily and defines a subroutine called : Sub myenvVar _OnChange(value) print "value of environment variable has changed" End Sub //////////////////////////////////////////////////however the alternative for subroutine for OnOpen in VB (defined below) works fine as shown above in python. Sub AppEvent_OnOpen(App) print "opening Application" End Sub for VB; all this stuff is cake work.... object_eventname subroutine and done.....what in python? From paul at subsignal.org Sat Aug 1 05:28:32 2009 From: paul at subsignal.org (paul) Date: Sat, 01 Aug 2009 11:28:32 +0200 Subject: socket policy flash help In-Reply-To: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> Message-ID: NighterNet schrieb: > I need help on the policy to able to let access to user to the server > once the policy access is finish. I been trying to find a good > example, but I got no luck. Using python version 3.1. > > Here the code I tested but it not working. > > if str(buff) == str("b\'\\x00\'"): > print ('policy FOUND >>> sending...') > rawinput = str(' access-from domain=\"*\" to-ports=\"*\" />') > print (rawinput) > b = bytes ( ord(c) for c in rawinput) > self.sockfd.send(b); And the error is? Doesn't Flash use http as transport? cheers Paul From davea at ieee.org Sat Aug 1 05:52:11 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 01 Aug 2009 05:52:11 -0400 Subject: Newbie Question regarding __init__() In-Reply-To: References: Message-ID: <4A74104B.7080403@ieee.org> Nat Williams wrote: > As MRAB described, ALL instance methods need to accept 'self' as a first > parameter, as that will be passed to them implicitly when they are called. > This includes __init__. The name 'self' is just a commonly accepted > convention for the name of the instance object passed to methods. You don't > have to call it that, but you really should. > > Take a look at http://docs.python.org/tutorial/classes.html#class-objects > It might help shed some light on how methods and instances work. > > One other thing. I'm a little confused by the first line of > dcObject.__init__: > > self.init_Pre() and self.init_Exec() > > I suspect this does not do what you think it does. init_Pre and init_Exec > will both be called by this expression (unless init_Pre throws an exception, > of course). You're not getting anything here that you wouldn't by just > calling each method on a separate line, except just making it harder to > read. > > Read the doc-string for init_Pre() and for init_Exec(). The final version of init_Pre() will return False in some circumstances, and in those circumstances Simon doesn't want init_Exec() to be called. He's deliberately using the short-circuit evaluation of 'and' to accomplish that. > > On Fri, Jul 31, 2009 at 8:53 PM, Simon wrote: > > >> Hi >> >> So should the dcObject class include the "self" as well since I have >> not defined an __init__ method in dcCursor? >> >> Simon >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > Every one of those methods in both of those classes need a "self" first argument. As others have said, all instance methods need a 'self.' From vinay_sajip at yahoo.co.uk Sat Aug 1 05:57:13 2009 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: Sat, 1 Aug 2009 02:57:13 -0700 (PDT) Subject: Confused About Python Loggin References: <534A6695-37D9-4200-9872-9E844AE50681@cs.ucl.ac.uk> <14CCA71D-F575-4B8A-8C99-67BDAAC2C6E0@cs.ucl.ac.uk> Message-ID: On Jul 31, 2:04?pm, Jean-Michel Pichavant wrote: > Jannik Sund? wrote: > > Hi all. I think I fixed this problem by setting fileLogger.propagate = > > 0. Otherwise it will propagate up to the root logger, which outputs to > > stdout, as far as I can understand. > > > On 31 Jul 2009, at 01:17, Jannik Sund? wrote: > > >> Dear all, I am quite confused about the Pythonlogging. I have read > >> and re-read the Python documentation for the Pythonloggingmodule > >> and googled, but to no avail. I simply want one logger to log to a > >> file and another logger to log to the console. Neither should log the > >> other's messages. The code below causes fileLogger to log to BOTH a > >> file and the console, how come? It seems to me that a call such as > >> "consoleHandler =logging.StreamHandler()" affects other loggers, > >> which I do not want. Also, if I do not do > >>logging.basicConfig(level=logging.INFO) in one of the classes of my > >> application, theloggingdoes not work. Any ideas how come? > > >> Thanks a lot for any help! :) > > >> fileHandler =logging.FileHandler('../../logs/log.txt') > >> fileLogger =logging.getLogger('TESTHARNESSFILE') > >> fileLogger.addHandler(fileHandler) > >> fileLogger.setLevel(logging.INFO) > >> consoleHandler =logging.StreamHandler() > >> logger =logging.getLogger('TESTHARNESS') > >> logger.addHandler(consoleHandler) > >> logger.setLevel(logging.INFO) > > > --http://mail.python.org/mailman/listinfo/python-list > > Please do not top post :o) > > Are sure you have used the code provided above ? > Loggers only propagate events to its parent. > > fileLogger =logging.getLogger('TESTHARNESSFILE" > logger =logging.getLogger('TESTHARNESS') > Those one have no parent relationship. > > However these one have parent relationship: > fileLogger =logging.getLogger('TESTHARNESS.FILE") # note the dotted name > logger =logging.getLogger('TESTHARNESS') > > Or maybe you have added a handler to the root logger... > > Using the propagate attribute is correct only between 2 loggers that are > meant to be parents. > > JM What you say is true, Jean-Michel, but the OP might be meaning the parent-child relationship both his loggers have with the mother of all loggers - the root logger ;-) Regards, Vinay Sajip From piet at cs.uu.nl Sat Aug 1 07:52:16 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 01 Aug 2009 13:52:16 +0200 Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> Message-ID: >>>>> NighterNet (N) wrote: >N> I need help on the policy to able to let access to user to the server >N> once the policy access is finish. I been trying to find a good >N> example, but I got no luck. Using python version 3.1. >N> Here the code I tested but it not working. >N> if str(buff) == str("b\'\\x00\'"): What is buff supposed to contain here? I assume a byte sequence? Do you reaaly mean that buff[0] contains the byte 'b' and buff[1] contains a single quote? And the last byte also a single quote? And the four bytes with \ x 0 0 before that instead of a null byte? In total 29 bytes? Or did you mean just the 23 bytes long b'\x00'? Maybe it should be if buff == b'\x00': >N> print ('policy FOUND >>> sending...') >N> rawinput = str('') The str here is unnecessary as you have already a string. >N> print (rawinput) >N> b = bytes ( ord(c) for c in rawinput) Why not b = b'' ? >N> self.sockfd.send(b); -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From tarundevnani at gmail.com Sat Aug 1 09:32:53 2009 From: tarundevnani at gmail.com (tarun) Date: Sat, 1 Aug 2009 19:02:53 +0530 Subject: How to read webpage Message-ID: Dear All,I want to read a webpage and copy the contents of it in word file. I tried to write following code: import urllib2 urllib2.urlopen("http://www.rediff .com/") *Error:-* urllib2.urlopen("http://www.icicibank.com/") File "C:\Python25\lib\urllib2.py", line 121, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 374, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 392, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1100, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1075, in do_open raise URLError(err) urllib2.URLError: -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sat Aug 1 09:52:17 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 01 Aug 2009 14:52:17 +0100 Subject: How to read webpage In-Reply-To: References: Message-ID: <4A744891.7050808@mrabarnett.plus.com> tarun wrote: > Dear All, > I want to read a webpage and copy the contents of it in word file. I > tried to write following code: > > import urllib2 > urllib2.urlopen("http://www.rediff.com/") > > *Error:-* > > urllib2.urlopen("http://www.icicibank.com/") > File "C:\Python25\lib\urllib2.py", line 121, in urlopen > return _opener.open(url, data) > File "C:\Python25\lib\urllib2.py", line 374, in open > response = self._open(req, data) > File "C:\Python25\lib\urllib2.py", line 392, in _open > '_open', req) > File "C:\Python25\lib\urllib2.py", line 353, in _call_chain > result = func(*args) > File "C:\Python25\lib\urllib2.py", line 1100, in http_open > return self.do_open(httplib.HTTPConnection, req) > File "C:\Python25\lib\urllib2.py", line 1075, in do_open > raise URLError(err) > urllib2.URLError: > I've just tried it. I didn't get an exception, so your problem must be elsewhere. From koranthala at gmail.com Sat Aug 1 11:19:28 2009 From: koranthala at gmail.com (koranthala) Date: Sat, 1 Aug 2009 08:19:28 -0700 (PDT) Subject: How to read webpage References: Message-ID: <67de4ef0-0da7-47e6-8e2e-23be4a6b452c@t11g2000prh.googlegroups.com> On Aug 1, 6:52?pm, MRAB wrote: > tarun wrote: > > Dear All, > > I want to read a webpage and copy the contents of it in word file. I > > tried to write following code: > > > import urllib2 > > urllib2.urlopen("http://www.rediff.com/") > > > *Error:-* > > > ? ? urllib2.urlopen("http://www.icicibank.com/") > > ? File "C:\Python25\lib\urllib2.py", line 121, in urlopen > > ? ? return _opener.open(url, data) > > ? File "C:\Python25\lib\urllib2.py", line 374, in open > > ? ? response = self._open(req, data) > > ? File "C:\Python25\lib\urllib2.py", line 392, in _open > > ? ? '_open', req) > > ? File "C:\Python25\lib\urllib2.py", line 353, in _call_chain > > ? ? result = func(*args) > > ? File "C:\Python25\lib\urllib2.py", line 1100, in http_open > > ? ? return self.do_open(httplib.HTTPConnection, req) > > ? File "C:\Python25\lib\urllib2.py", line 1075, in do_open > > ? ? raise URLError(err) > > urllib2.URLError: > > I've just tried it. I didn't get an exception, so your problem must be > elsewhere. Is it that the website expects a valid browser? In that case, spoof a browser and try to get the site. From joncle at googlemail.com Sat Aug 1 11:31:09 2009 From: joncle at googlemail.com (Jon Clements) Date: Sat, 1 Aug 2009 08:31:09 -0700 (PDT) Subject: How to read webpage References: Message-ID: <7690d42e-ea99-4aec-9029-5cfae119ffcf@o32g2000yqm.googlegroups.com> On 1 Aug, 14:52, MRAB wrote: > tarun wrote: > > Dear All, > > I want to read a webpage and copy the contents of it in word file. I > > tried to write following code: > > > import urllib2 > > urllib2.urlopen("http://www.rediff.com/") > > > *Error:-* > > > ? ? urllib2.urlopen("http://www.icicibank.com/") > > ? File "C:\Python25\lib\urllib2.py", line 121, in urlopen > > ? ? return _opener.open(url, data) > > ? File "C:\Python25\lib\urllib2.py", line 374, in open > > ? ? response = self._open(req, data) > > ? File "C:\Python25\lib\urllib2.py", line 392, in _open > > ? ? '_open', req) > > ? File "C:\Python25\lib\urllib2.py", line 353, in _call_chain > > ? ? result = func(*args) > > ? File "C:\Python25\lib\urllib2.py", line 1100, in http_open > > ? ? return self.do_open(httplib.HTTPConnection, req) > > ? File "C:\Python25\lib\urllib2.py", line 1075, in do_open > > ? ? raise URLError(err) > > urllib2.URLError: > > I've just tried it. I didn't get an exception, so your problem must be > elsewhere. I'm hoping this adds to MRAB's reply; it is intended however for the OP. Jeeze -- been a while since I've had to deal with Sockets (directly anyway). If memory serves correctly, it's where the system can't name resolve the required address. So best guess is it's either a temporary glitch, or an issue with your routing. Jon. Jon. From darkneter at gmail.com Sat Aug 1 11:34:57 2009 From: darkneter at gmail.com (NighterNet) Date: Sat, 1 Aug 2009 08:34:57 -0700 (PDT) Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> Message-ID: <8bede581-f260-4c69-abf0-1e8071380b76@z4g2000prh.googlegroups.com> On Aug 1, 4:52?am, Piet van Oostrum wrote: > >>>>> NighterNet (N) wrote: > >N> I need help on the policy to able to let access to user to the server > >N> once the policy access is finish. I been trying to find a good > >N> example, but I got no luck. Using python version 3.1. > >N> Here the code I tested but it not working. > >N> if str(buff) == str("b\'\\x00\'"): > > What is buff supposed to contain here? I assume a byte sequence? > Do you reaaly mean that buff[0] contains the byte 'b' and buff[1] > contains a single quote? And the last byte also a single quote? And the > four bytes with \ x 0 0 before that instead of a null byte? In total 29 bytes? > > Or did you mean just the 23 bytes long b'\x00'? > > Maybe it should be if buff == b'\x00': > > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ('policy FOUND >>> sending...') > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? rawinput = str('') > > The str here is unnecessary as you have already a string. > > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print (rawinput) > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? b = bytes ( ord(c) for c in rawinput) > > Why not > b = b'' ? > > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.sockfd.send(b); > > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org I try that method and flash socket is not getting the policy. b = b'' self.sockfd.send(b); server = socket.socket( socket.AF_INET, socket.SOCK_STREAM) When it able to read the policy it send it but it fail to send to flash some reason and send it again and then d/c. From marcusw at cox.net Sat Aug 1 11:43:15 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sat, 01 Aug 2009 11:43:15 -0400 Subject: How to read webpage In-Reply-To: <7690d42e-ea99-4aec-9029-5cfae119ffcf@o32g2000yqm.googlegroups.com> References: <7690d42e-ea99-4aec-9029-5cfae119ffcf@o32g2000yqm.googlegroups.com> Message-ID: On 8/1/2009 11:31 AM, Jon Clements wrote: > On 1 Aug, 14:52, MRAB wrote: >> tarun wrote: >>> Dear All, >>> I want to read a webpage and copy the contents of it in word file. I >>> tried to write following code: >>> import urllib2 >>> urllib2.urlopen("http://www.rediff.com/") >>> *Error:-* >>> urllib2.urlopen("http://www.icicibank.com/") >>> File "C:\Python25\lib\urllib2.py", line 121, in urlopen >>> return _opener.open(url, data) >>> File "C:\Python25\lib\urllib2.py", line 374, in open >>> response = self._open(req, data) >>> File "C:\Python25\lib\urllib2.py", line 392, in _open >>> '_open', req) >>> File "C:\Python25\lib\urllib2.py", line 353, in _call_chain >>> result = func(*args) >>> File "C:\Python25\lib\urllib2.py", line 1100, in http_open >>> return self.do_open(httplib.HTTPConnection, req) >>> File "C:\Python25\lib\urllib2.py", line 1075, in do_open >>> raise URLError(err) >>> urllib2.URLError: >> I've just tried it. I didn't get an exception, so your problem must be >> elsewhere. > > I'm hoping this adds to MRAB's reply; it is intended however for the > OP. > > Jeeze -- been a while since I've had to deal with Sockets (directly > anyway). > If memory serves correctly, it's where the system can't name resolve > the required address. > So best guess is it's either a temporary glitch, or an issue with your > routing. > > Jon. > Jon. 'getaddrinfo failed' means that the nameserver can't be found, or that it has no records of that address (I'm 90% sure of that). Marcus From nobody at nowhere.com Sat Aug 1 13:11:18 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 01 Aug 2009 18:11:18 +0100 Subject: Python docs disappointing References: Message-ID: On Fri, 31 Jul 2009 20:10:45 +0000, kj wrote: > I'm pretty new to Python, and I like a lot overall, but I find the > documentation for Python rather poor, overall. FWIW, I find the module documentation to be mostly adequate. What's missing is a human-readable language *manual*. The tutorial omits too much; the language reference may be fine for language lawyering, but it's not much use otherwise. From MatzeGuentert at gmx.de Sat Aug 1 13:16:14 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Sat, 01 Aug 2009 19:16:14 +0200 Subject: M2Crypto: AttributeError: 'CSR' object has no attribute 'pkey' Message-ID: <1249146974.3330.1.camel@celsius> Hello python-guys I am trying to build a python based certificate authority using m2crypto. I am quite new to python and I am asking myself why my code snippets below throw the following Traceback: $ python csr.py ...++++++++++++ ...............++++++++++++ Traceback (most recent call last): File "csr.py", line 48, in csr.create_cert_signing_request(pubkey, cert_name) File "csr.py", line 17, in create_cert_signing_request cert_request.set_pubkey(keypair) File "/usr/lib64/python2.6/site-packages/M2Crypto/X509.py", line 926, in set_pubkey return m2.x509_req_set_pubkey( self.req, pkey.pkey ) AttributeError: 'CSR' object has no attribute 'pkey' Bellow are my modules containing two classes CSR and Keypair. There seems to be something wrong in the way I am calling csr.create_cert_signing_request(), because if I directly add the key generation part to the create_cert_singing_request function it works... http://www.heikkitoivonen.net/m2crypto/api/M2Crypto.X509.Request-class.html#set_pubkey This link states out, that the instance function set_pubkey takes an EVP_KEY object as argument, and thats what I am passing to it, or not? I really would be happy if someone could give me a helping hand on this and maybe could comment every style / ... mistake I made to accelerate my learning experience. Thanks, Matthias $ cat csr.py from config import * from keypair import * from M2Crypto import X509, EVP class CSR(object): def __init__(self): pass def create_cert_signing_request(keypair, cert_name, cert_extension_stack=None): # create a certificate signing request object cert_request = X509.Request() # set certificate version to 3 cert_request.set_version(3) # which rsa public key should be used? cert_request.set_pubkey(keypair) # create an subject for the certificate request cert_request.set_subject_name(cert_name) if cert_extension_stack != None: # add the extensions to the request cert_request.add_extensions(cert_extension_stack) # sign the request using the RSA key pair cert_request.sign(keypair, 'sha1') return cert_request if __name__ == "__main__": csr = CSR() cert_name = X509.X509_Name() keyp = Keypair() keyp.create_keypair() keyp.save_keypair("host.key") pubkey = keyp.get_keypair() cert_name.C = "GB" cert_name.ST = "Greater Manchester" cert_name.L = "Salford" cert_name.O = "COMODO CA Limited" cert_name.CN = "COMODO Certification Authority" cert_name.OU = "Information Technology" cert_name.Email = "contact at comodo.com" csr.create_cert_signing_request(pubkey, cert_name) $ cat keypair.py from M2Crypto import X509, m2, RSA, EVP from config import * class Keypair(object): def __init__(self): self.config = Config() self.keypair = EVP.PKey() def create_keypair(self): # generate an RSA key pair # OpenSSL book page 232 # second argument should be a constant RSA_F4 or RSA_3 rsa_key_pair = RSA.gen_key(int(self.config.get_attribute('CA','key_size')), m2.RSA_F4) # check if RSA key pair is usable # OpenSSL book page 232 if rsa_key_pair.check_key() != 1: print 'error while generating key!' sys.exit() # EVP object which can hold either a DSA or an RSA object # OpenSSL book page 236 evp_key_container = EVP.PKey() evp_key_container.assign_rsa(rsa_key_pair) self.keypair = evp_key_container def save_keypair(self, filename): self.keypair.save_key(filename, None) def load_keypair(self, filename): self.keypair = EVP.load_key(filename) def get_keypair(self): return self.keypair def get_public_key(self): return self.keypair.pkey def print_keypair(self): print self.keypair.as_pem(None) if __name__ == "__main__": key = Keypair() key.create_keypair() key.save_keypair("test.key") print key.get_keypair() print key.get_public_key() From enleverLesX_XXmcX at XmclavXeauX.com Sat Aug 1 13:20:35 2009 From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP) Date: Sat, 01 Aug 2009 19:20:35 +0200 Subject: os.path.exists() and Samba shares References: Message-ID: <4a747965$0$23487$ba4acef3@news.orange.fr> Hi! > SAMBA is a Linux implementation of the SMB protocol, natively supported on Windows. Right. But, with Vista or Seven, only recents releases of Samba are supported. And, Samba know only NTLM release 2 (in register: HKLM\SYSTEM\CurrentControlSet\Control\Lsa value LMCompatibilityLevel ; set 1 or 0. ) @-salutations -- Michel Claveau From justindecell at gmail.com Sat Aug 1 14:07:15 2009 From: justindecell at gmail.com (Justin DeCell) Date: Sat, 1 Aug 2009 11:07:15 -0700 Subject: Queryable Daemon Message-ID: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Hi All, I was hoping for a little help with a project I'm working on. I'm writing a daemon in python that I want to be queryable (i.e. I should be able to run foo -s and it will report some internal information about the foo daemon if it's running) but I can't figure out a way get information from that process from an external process. I was thinking that there should be a way to open a file descriptor, have the daemon write to that every so often and then have the query process just read from that fd but it looks like on the process reading from an fd has to be a child of the daemon for this to work. The only other way I thought of would be to write to a file on disk every so often from the daemon and just read the from the query process but it seems like there should be a more elegant way to do this... By the way I'm writing this for unix only so there's no need to worry about compatibility with other os'. Thanks, -Justin -------------- next part -------------- An HTML attachment was scrubbed... URL: From luke.leighton at googlemail.com Sat Aug 1 14:07:51 2009 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 1 Aug 2009 11:07:51 -0700 (PDT) Subject: JavaScript toolkits (was Re: ANN: Porcupine Web Application Server 0.6 is released!) References: Message-ID: <01133210-f03b-4a71-aa9e-d69fe44ac9a5@r38g2000yqn.googlegroups.com> On Jul 20, 4:00 pm, a... at pythoncraft.com (Aahz) wrote: > Out of curiosity, are there anyJavaScripttoolkits or python-to-javascript compilers > that generate code > that degrades gracefully whenJavaScriptis disabled? http://advogato.org/article/981.html you'll need to do a little bit of work - use a state-machine-based framework (such as twisted, from what i can gather), or use fastcgi, or solve the problem of storing the state of the pyjamas application "in between" web requests - but yes, pyjamas-web is a port of pyjamas to the web server. so, by writing an app that conforms to the pyjamas API, you get to compile it to native javascript, to run in the web browser; you get to run it as pure python using pyjamas-desktop (python-hulahop underneath or pywebkitgtk) and then, if you want to finish off the experiment that i started, you get to run the _same_ python app server-side on behalf of the users. all quite quite mad, to be honest :) l. From luke.leighton at googlemail.com Sat Aug 1 14:11:02 2009 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 1 Aug 2009 11:11:02 -0700 (PDT) Subject: JavaScript toolkits (was Re: ANN: Porcupine Web Application Server 0.6 is released!) References: <1c994086-8c58-488f-b3b3-6161c4b2ba05@k30g2000yqf.googlegroups.com> Message-ID: <2a2f05af-a87e-44bf-8d36-774697dbd794@c29g2000yqd.googlegroups.com> On Jul 21, 12:55 pm, Paul Boddie wrote: > On 20 Jul, 18:00, a... at pythoncraft.com (Aahz) wrote: > > > > > Out of curiosity, are there anyJavaScripttoolkits that generate code > > that degrades gracefully whenJavaScriptis disabled? > > You mean "Web toolkits which useJavaScript", I presume. I have > written (and use myself) a toolkit/framework called XSLForms (part of > the XSLTools distribution) which supports in-page updates (AJAX, > effectively) that degrade to vanilla whole-page requests ifJavaScript > is switched off: yeahhh.... i remember doing something like that. each portion of the page i did as a separate AJAX load, and then there was some loader- infrastructure where you could, if javascript was switched off, do a tree-walk-reconstruction of the page. if anyone's interested i can provide source code. l. From hjtoi-better-remove-before-reply at comcast.net Sat Aug 1 14:19:13 2009 From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen) Date: Sat, 01 Aug 2009 11:19:13 -0700 Subject: M2Crypto: AttributeError: 'CSR' object has no attribute 'pkey' References: Message-ID: Matthias G?ntert wrote: > class CSR(object): > def __init__(self): > pass > > def create_cert_signing_request(keypair, cert_name, > cert_extension_stack=None): You missed self. Although this method does not seem to be using any instance data so there isn't actually much reason to have a CSR object unless you intend to expand it in ways that require it. > if cert_extension_stack != None: A word of advice: always check equality/inequality to None with 'is', because that way it is a straight pointer conversion which is faster and won't cause any surprises. In other words, write the above as: if cert_extension_stack is not None: -- Heikki Toivonen - http://heikkitoivonen.net From jkn_gg at nicorp.f9.co.uk Sat Aug 1 15:01:32 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Sat, 1 Aug 2009 12:01:32 -0700 (PDT) Subject: Python docs disappointing References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: On Aug 1, 4:18?am, Terry Reedy wrote: > This is one area where Windows users seems to have an advantage. The > standard installer includes the doc set as a Windows help file. I often > keep that open in one window while programming in others. I only later > discovered that this was a copy of the online docs ;-), which I only use > to check the in-development version before submitting a doc bug. The ActiveState distribution also includes the doc set as a CHM file (the canonical version didn't used to; one reason why I've used ActiveState in the past). I run a dual-boot system and have used a CHM (Windows Compiled help file format) viewer under Linux to read the Windows help file. This has been pretty handy in the past. Unfortunately, the combination of the python 2.6 CHM helpfile style, and the KChmViewer application gives me body text which is almost unreadable (black text on dark blue background). I'm not sure if this a bug in KChmViewer but it's pretty annoying. Anyone else see this? J^n From python at mrabarnett.plus.com Sat Aug 1 15:32:21 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 01 Aug 2009 20:32:21 +0100 Subject: Queryable Daemon In-Reply-To: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> References: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Message-ID: <4A749845.4020208@mrabarnett.plus.com> Justin DeCell wrote: > Hi All, > > I was hoping for a little help with a project I'm working on. I'm > writing a daemon in python that I want to be queryable (i.e. I should > be able to run foo -s and it will report some internal information about > the foo daemon if it's running) but I can't figure out a way get > information from that process from an external process. I was thinking > that there should be a way to open a file descriptor, have the daemon > write to that every so often and then have the query process just read > from that fd but it looks like on the process reading from an fd has to > be a child of the daemon for this to work. The only other way I thought > of would be to write to a file on disk every so often from the daemon > and just read the from the query process but it seems like there should > be a more elegant way to do this... > > By the way I'm writing this for unix only so there's no need to worry > about compatibility with other os'. > Instead of a file descriptor, how about a socket? A certain port at "127.0.0.1"? From mail at timgolden.me.uk Sat Aug 1 15:32:31 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 01 Aug 2009 20:32:31 +0100 Subject: Python docs disappointing In-Reply-To: References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: <4A74984F.9010805@timgolden.me.uk> jkn wrote: > The ActiveState distribution also includes the doc set as a CHM file > (the canonical version didn't used to; one reason why I've used > ActiveState in the past). It has done for quite some while now: Python 2.3 was the first and that was released, what, six years ago. Still, you're right; it used to use plain HTML. > Unfortunately, the combination of the python 2.6 CHM helpfile style, > and the KChmViewer application gives me body text which is almost > unreadable (black text on dark blue background). I'm not sure if this > a bug in KChmViewer but it's pretty annoying. Anyone else see this? This was noised about when the new-style docs were first released. Somehow (I don't run Linux usually) I had the impression it had been fixed; presumably not. However, rebuilding the docs is not at all hard: you just need a Python installation and the HTMLHelp Workshop. Then you can fiddle about with the CSS to your heart's content. TJG From geomajor56 at gmail.com Sat Aug 1 15:39:12 2009 From: geomajor56 at gmail.com (Michael Savarese) Date: Sat, 1 Aug 2009 15:39:12 -0400 Subject: iterate lines with regex Message-ID: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> I'm a python newbie and I'm trying to test several regular expressions on the same line before moving on to next line. it seems to move on to next line before trying all regular expressions which is my goal. it only returns true for first regular expression does the curser have to be rest to beginning of line? If so, how would I do that. remember I'm new thanks in advance to any advice Mike S. the following is part of my code, readThis=open('c:/9320.txt','r') for line in readThis: try: thisKey = key.search(line).group(1) thisMap = map.search(line).group(1) thisParcel = parcel.search(line).group(1) except: continue -------------- next part -------------- An HTML attachment was scrubbed... URL: From jkn_gg at nicorp.f9.co.uk Sat Aug 1 15:44:14 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Sat, 1 Aug 2009 12:44:14 -0700 (PDT) Subject: Python docs disappointing References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: Hi Tim On Aug 1, 8:32?pm, Tim Golden wrote: > > > Unfortunately, the combination of the python 2.6 CHM helpfile style, > > and the KChmViewer application gives me body text which is almost > > unreadable (black text on dark blue background). I'm not sure if this > > a bug in KChmViewer but it's pretty annoying. Anyone else see this? > > This was noised about when the new-style docs were first released. > Somehow (I don't run Linux usually) I had the impression it had > been fixed; presumably not. However, rebuilding the docs is not > at all hard: you just need a Python installation and the > HTMLHelp Workshop. Then you can fiddle about with the CSS to > your heart's content. > The HTML form of the documents (on python.org) seem fine (dark text on a light background, with a 'light blue on dark blue' sidebar). I was guessing that the .CHM was intended to have the same style, and therefore there was a problem with either my viwer, or with the conversion. Is this not the case then? I've just checked using xchm, and this displays OK - but I don't think it's taking any notice of any styles. FWIW I'm running 4.0-r1; there is a later release but it's not yet available for my Gentoo distribution. Can you point me at any references to this bug in the Python release world please? Thanks J^n From jkn_gg at nicorp.f9.co.uk Sat Aug 1 15:47:50 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Sat, 1 Aug 2009 12:47:50 -0700 (PDT) Subject: Python docs disappointing References: <4A73AAE3.1050209@tim.thechases.com> Message-ID: <5cdcdc4a-5dd5-4c0a-a7cd-cdd078f8c262@a13g2000yqc.googlegroups.com> update: if I set 'use KHTMLPart-based widget' instead of 'QTextBrowser- based Widget' to display HTML content in the application settings of KchmViewer, all is readable. Hurrah! I wonder if it is picing up some QT stylesheet I have lying around in an over-clever way... J^n From ml at well-adjusted.de Sat Aug 1 15:55:31 2009 From: ml at well-adjusted.de (Jochen Schulz) Date: Sat, 1 Aug 2009 21:55:31 +0200 Subject: iterate lines with regex In-Reply-To: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> Message-ID: <20090801195531.GH15902@wasteland.homelinux.net> Michael Savarese: > > for line in readThis: > try: > thisKey = key.search(line).group(1) > thisMap = map.search(line).group(1) > thisParcel = parcel.search(line).group(1) > except: > continue Why do you catch all exceptions in that loop? Remove the try-except clause including the 'continue' and a stacktrace will probybably tell you why your loop appears to do nothing. J. -- A passionate argument means more to me than a blockbuster movie. [Agree] [Disagree] -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 204 bytes Desc: Digital signature URL: From breamoreboy at yahoo.co.uk Sat Aug 1 16:08:14 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 01 Aug 2009 21:08:14 +0100 Subject: iterate lines with regex In-Reply-To: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> Message-ID: Michael Savarese wrote: > I'm a python newbie and I'm trying to test several regular expressions on > the same line before moving on to next line. > it seems to move on to next line before trying all regular expressions which > is my goal. > it only returns true for first regular expression > does the curser have to be rest to beginning of line? If so, how would I do > that. > remember I'm new > thanks in advance to any advice > Mike S. > > the following is part of my code, > readThis=open('c:/9320.txt','r') > > for line in readThis: > try: > thisKey = key.search(line).group(1) > thisMap = map.search(line).group(1) > thisParcel = parcel.search(line).group(1) > except: > continue > > The bare except will hide any errors in the lines above it. Either catch errors that you expect or take the try-except out. -- Kindest regards. Mark Lawrence. From workitharder at gmail.com Sat Aug 1 16:42:16 2009 From: workitharder at gmail.com (Buck) Date: Sat, 1 Aug 2009 13:42:16 -0700 (PDT) Subject: Module updating plans for Python 3.1: feedparser, MySQLdb References: <4a739a96$0$1615$742ec2ed@news.sonic.net> Message-ID: I use MySQLdb quite a bit in my work. I could volunteer to help update it. Are there any particular bugs we're talking about or just a straight port to 3.0? --Buck On Jul 31, 6:32?pm, John Nagle wrote: > ? ? Any progress on updating feedparser and MySQLdb for Python 3.x in the > foreseeable future? > > ? ? Feedparser shouldn't be that hard; it's just that nobody is working on it. > MySQLdb is known to be hard, and that may be a while. > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle From garabik-news-2005-05 at kassiopeia.juls.savba.sk Sat Aug 1 17:14:59 2009 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Sat, 1 Aug 2009 21:14:59 +0000 (UTC) Subject: Queryable Daemon References: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Message-ID: MRAB wrote: > Justin DeCell wrote: >> Hi All, >> ... >> The only other way I thought >> of would be to write to a file on disk every so often from the daemon >> and just read the from the query process but it seems like there should >> be a more elegant way to do this... >> >> By the way I'm writing this for unix only so there's no need to worry >> about compatibility with other os'. >> > Instead of a file descriptor, how about a socket? A certain port at > "127.0.0.1"? Or a Unix domain socket. Or let the demon catch signal, say SIGUSR1 and dump its state to a file. A bit easier programming that a socket, a bit less elegant. -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From saimapk81 at gmail.com Sat Aug 1 17:29:25 2009 From: saimapk81 at gmail.com (saima81) Date: Sat, 1 Aug 2009 14:29:25 -0700 (PDT) Subject: "PAK WEB PAGES" "PAK WEB SITES" "PAK WEB PAGES" "PAK WEB SITES" "PAK WEB PAGES" "PAK WEB SITES" ON www.pak-web-pages.blogspot.com Message-ID: "PAK WEB PAGES" www.pak-web-pages.blogspot.com "PAK WEB SITES" www.pak-web-pages.blogspot.com "PAK WEB PAGES" www.pak-web-pages.blogspot.com "PAK WEB SITES" www.pak-web-pages.blogspot.com "PAK WEB PAGES" www.pak-web-pages.blogspot.com "PAK WEB SITES" www.pak-web-pages.blogspot.com ON www.pak-web-pages.blogspot.com www.pak-web-pages.blogspot.com From michael at altra-optics.co.uk Sat Aug 1 17:58:53 2009 From: michael at altra-optics.co.uk (Michael M Mason) Date: Sat, 1 Aug 2009 22:58:53 +0100 Subject: Newbie thwarted by sys.path on Vista Message-ID: <7djs50F2bsubuU1@mid.individual.net> I'm running Python 3.1 on Vista and I can't figure out how to add my own directory to sys.path. The docs suggest that I can either add it to the PYTHONPATH environment variable or to the PythonPath key in the registry. However, PYTHONPATH doesn't exist, and updating the registry key has no effect (and in any case the contents aren't the same as sys.path). So where does sys.path get its value from, and how do I change it? -- Michael From nytrokiss at gmail.com Sat Aug 1 19:01:45 2009 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 2 Aug 2009 02:01:45 +0300 Subject: How to read webpage In-Reply-To: References: <7690d42e-ea99-4aec-9029-5cfae119ffcf@o32g2000yqm.googlegroups.com> Message-ID: <8a6b8e350908011601v4d2ab86bp5618c6171cfb9a98@mail.gmail.com> Check your connection to the internet. On Sat, Aug 1, 2009 at 6:43 PM, Marcus Wanner wrote: > On 8/1/2009 11:31 AM, Jon Clements wrote: > >> On 1 Aug, 14:52, MRAB wrote: >> >>> tarun wrote: >>> >>>> Dear All, >>>> I want to read a webpage and copy the contents of it in word file. I >>>> tried to write following code: >>>> import urllib2 >>>> urllib2.urlopen("http://www.rediff.com/") >>>> *Error:-* >>>> urllib2.urlopen("http://www.icicibank.com/") >>>> File "C:\Python25\lib\urllib2.py", line 121, in urlopen >>>> return _opener.open(url, data) >>>> File "C:\Python25\lib\urllib2.py", line 374, in open >>>> response = self._open(req, data) >>>> File "C:\Python25\lib\urllib2.py", line 392, in _open >>>> '_open', req) >>>> File "C:\Python25\lib\urllib2.py", line 353, in _call_chain >>>> result = func(*args) >>>> File "C:\Python25\lib\urllib2.py", line 1100, in http_open >>>> return self.do_open(httplib.HTTPConnection, req) >>>> File "C:\Python25\lib\urllib2.py", line 1075, in do_open >>>> raise URLError(err) >>>> urllib2.URLError: >>>> >>> I've just tried it. I didn't get an exception, so your problem must be >>> elsewhere. >>> >> >> I'm hoping this adds to MRAB's reply; it is intended however for the >> OP. >> >> Jeeze -- been a while since I've had to deal with Sockets (directly >> anyway). >> If memory serves correctly, it's where the system can't name resolve >> the required address. >> So best guess is it's either a temporary glitch, or an issue with your >> routing. >> >> Jon. >> Jon. >> > > 'getaddrinfo failed' means that the nameserver can't be found, or that it > has no records of that address (I'm 90% sure of that). > > Marcus > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From luke.leighton at googlemail.com Sat Aug 1 19:19:55 2009 From: luke.leighton at googlemail.com (lkcl) Date: Sat, 1 Aug 2009 16:19:55 -0700 (PDT) Subject: Calling functions: Why this complicated ? References: <89dd3da60907141340i46a6d913mb333788e85507128@mail.gmail.com> Message-ID: <5e089462-dbc1-4764-a57c-86c94cb0ae14@u16g2000yqe.googlegroups.com> On Jul 14, 11:31 pm, Chris Rebert wrote: > On Tue, Jul 14, 2009 at 1:40 PM, Mohan Parthasarathy wrote: > > Hi, > > I am a newbie. I am reading > >http://www.network-theory.co.uk/docs/pytut/KeywordArguments.html > > Defining a function with "N" arguments and calling them in "M" different > > ways. Why does it have to be this complicated ? I like the idea of calling > > the function by explicitly naming the arguments, but there are so many other > > ways here that is very confusing. Do people really use all these features ? > > Perhaps, there is a equivalent book to "Javascript: Good Parts" for Python ? > > Oh $DEITY, don't even compare Python toJavaScript. At least in > Python, when you try to access a non-existent attribute, a proper > NameError exception is thrown rather than silently getting back > "undefined"... (*has traumatic horror story flashback*) yehh, that's what i thought, originally, but after talking it over with the people doing the EMCAScript Harmony spec, they explained that nooo, there _are_ exceptions thrown (two if the browser implements it properly, which IE of course doesn't). you can try it by installing the spidermonkey js compiler, which is the exact same js engine that's in firefox. in the python-to-javascript compiler, http://pyjs.org, however, we've taken to adding a double-check (the equivalent of getattr) when you specify the --strict option, juuust to make sure. and yes, there was a talk at europython 2009, pretty much called "javascript, the good parts, for python programmers", you can look it up, the talk audio is online by now. http://europython.eu l. From joncle at googlemail.com Sat Aug 1 19:32:21 2009 From: joncle at googlemail.com (Jon Clements) Date: Sat, 1 Aug 2009 16:32:21 -0700 (PDT) Subject: Newbie thwarted by sys.path on Vista References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: <105eaa91-e751-4b25-a2c9-94cd075b60c7@s15g2000yqs.googlegroups.com> On 1 Aug, 22:58, "Michael M Mason" wrote: > I'm running Python 3.1 on Vista and I can't figure out how to add my own > directory to ?sys.path. > > The docs suggest that I can either add it to the PYTHONPATH environment > variable or to the PythonPath key in the registry. ?However, PYTHONPATH > doesn't exist, and updating the registry key has no effect (and in any case > the contents aren't the same as sys.path). > > So where does sys.path get its value from, and how do I change it? > > -- > Michael sys.path is just a list. So in your 'main' module where you do most of your imports, just append or prepend the path you desire (the search order is left to right). Although, I believe under Windows creating a system level or user level PYTHONPATH environment variable will enable Windows to pick it up. Not 100% sure as I don't have a Windows machine handy. From piet at cs.uu.nl Sat Aug 1 19:36:18 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 01:36:18 +0200 Subject: Newbie thwarted by sys.path on Vista References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: >>>>> "Michael M Mason" (MMM) wrote: >MMM> I'm running Python 3.1 on Vista and I can't figure out how to add my own >MMM> directory to sys.path. >MMM> The docs suggest that I can either add it to the PYTHONPATH environment >MMM> variable or to the PythonPath key in the registry. However, PYTHONPATH >MMM> doesn't exist, Then create it. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From aahz at pythoncraft.com Sat Aug 1 19:36:58 2009 From: aahz at pythoncraft.com (Aahz) Date: 1 Aug 2009 16:36:58 -0700 Subject: string.Template issue References: Message-ID: In article , Javier Collado wrote: > >In the string.Template documentation >(http://docs.python.org/library/string.html) it's explained that if a >custom regular expression for pattern substitution is needed, it's >possible to override idpattern class attribute (whose default value is >[_a-z][_a-z0-9]*). > >However, if the custom pattern that is needed is just uppercase >letters something like [A-Z]+ won't work because of the following line >in the _TemplateMetaclass class __init__ method: >cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) > >I would say that this is an error (IGNORECASE just shouldn't be there) Good point! I don't have an answer for you, but please file a report at bugs.python.org to make sure it doesn't get lost. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Many customs in this life persist because they ease friction and promote productivity as a result of universal agreement, and whether they are precisely the optimal choices is much less important." --Henry Spencer From david.lyon at preisshare.net Sat Aug 1 20:26:19 2009 From: david.lyon at preisshare.net (David Lyon) Date: Sat, 01 Aug 2009 20:26:19 -0400 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7djs50F2bsubuU1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: <73ddb9b5d0110a42e2831eb6c150d2a8@preisshare.net> On Sat, 1 Aug 2009 22:58:53 +0100, "Michael M Mason" wrote: > I'm running Python 3.1 on Vista and I can't figure out how to add my own > directory to sys.path. > > The docs suggest that I can either add it to the PYTHONPATH environment > variable or to the PythonPath key in the registry. However, PYTHONPATH > doesn't exist, and updating the registry key has no effect > > So where does sys.path get its value from, and how do I change it? The simplest hack (worst - but most direct) is that sys.path is a list and you can use it like any other list. (add, delete, change items in it) It gets loaded from site.py (in the standardard library) at startup. Anything else you'll have to ask somebody else. David From davea at ieee.org Sat Aug 1 20:29:12 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 01 Aug 2009 20:29:12 -0400 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7djs50F2bsubuU1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: <4A74DDD8.7020304@ieee.org> Michael M Mason wrote: >
I'm > running Python 3.1 on Vista and I can't figure out how to add my own > directory to sys.path. > > The docs suggest that I can either add it to the PYTHONPATH > environment variable or to the PythonPath key in the registry. > However, PYTHONPATH doesn't exist, and updating the registry key has > no effect (and in any case the contents aren't the same as sys.path). > > So where does sys.path get its value from, and how do I change it? > sys.path gets its values from several places. The ones I think I know of are: current directory (which uses "" rather than the expected ".") directories listed in PythonPath environment variable Windows-system directory relative to the executable (python.exe or pythonw.exe) that's actually running relative to the user directory (docs&settings/username/Application Data .... If there's no PythonPath variable, it just uses those other items. I have no idea what it gets from the registry entries. Anyway, I'd suggest adding it to PythonPath, and if it's empty, just create it with the directory you need. I'm hoping you know you can also add to sys.path directly during script initialization. It's just a list, and is writeable. From joongkoo.cho at gmail.com Sat Aug 1 20:43:57 2009 From: joongkoo.cho at gmail.com (Joongkoo Cho) Date: Sat, 1 Aug 2009 17:43:57 -0700 Subject: Shortest path code on real map Message-ID: Dear All, I'm trying to calculate shortest paths on US highway map. I understand how shortest path algorithms work in Python but I need helps to do it on real maps. How can I make link-node information? Best, John -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Aug 1 21:06:47 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 01:06:47 GMT Subject: Custom namespaces Message-ID: <0284d760$0$20667$c3e8da3@news.astraweb.com> I was playing around with a custom mapping type, and I wanted to use it as a namespace, so I tried to use it as my module __dict__: >>> import __main__ >>> __main__.__dict__ = MyNamespace() Traceback (most recent call last): File "", line 1, in TypeError: readonly attribute Why is __dict__ made read-only? I next thought I could change the type of the namespace to my class: >>> __main__.__dict__.__class__ = MyNamespace Traceback (most recent call last): File "", line 1, in TypeError: __class__ assignment: only for heap types Drat, foiled again!!! Okay, if I can't do this at the module level, can I at least install a custom namespace at the class level? >>> class MyNamespace(dict): ... def __getitem__(self, key): ... print "Looking up key '%s'" % key ... return super(MyNamespace, self).__getitem__(key) ... >>> namespace = MyNamespace(x=1, y=2, z=3) >>> namespace['x'] Looking up key 'x' 1 >>> C = new.classobj("C", (object,), namespace) >>> C.x 1 Apparently not. It looks like the namespace provided to the class constructor gets copied when the class is made. Interestingly enough, the namespace argument gets modified *before* it gets copied, which has an unwanted side-effect: >>> namespace {'y': 2, 'x': 1, '__module__': '__main__', 'z': 3, '__doc__': None} Is there any way to install a custom type as a namespace? -- Steven From redforks at gmail.com Sat Aug 1 21:11:45 2009 From: redforks at gmail.com (Red Forks) Date: Sun, 2 Aug 2009 09:11:45 +0800 Subject: string.Template issue In-Reply-To: References: Message-ID: <3f18b3f10908011811t6947fbf2t335370c676889062@mail.gmail.com> On Thu, Jul 30, 2009 at 4:17 PM, Javier Collado wrote: > Hello, > > In the string.Template documentation > (http://docs.python.org/library/string.html) it's explained that if a > custom regular expression for pattern substitution is needed, it's > possible to override idpattern class attribute (whose default value is > [_a-z][_a-z0-9]*). > > However, if the custom pattern that is needed is just uppercase > letters something like [A-Z]+ won't work because of the following line > in the _TemplateMetaclass class __init__ method: > cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) derive a new class, and replace __init__ method, or replace _TemplateMetaclass.__init__() method. > > > I would say that this is an error (IGNORECASE just shouldn't be there) > and that the line above should be: > cls.pattern = _re.compile(pattern, _re.VERBOSE) > and the default value for idpattern: > [_a-zA-Z][_a-zA-Z0-9]* > > Do you agree on this? Is there any reason for the IGNORECASE option to > be passed to re.compile? > > Best regards, > Javier > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From redforks at gmail.com Sat Aug 1 21:18:58 2009 From: redforks at gmail.com (Red Forks) Date: Sun, 2 Aug 2009 09:18:58 +0800 Subject: Custom namespaces In-Reply-To: <0284d760$0$20667$c3e8da3@news.astraweb.com> References: <0284d760$0$20667$c3e8da3@news.astraweb.com> Message-ID: <3f18b3f10908011818x711e49ccg575eb4eb7363f261@mail.gmail.com> On Sun, Aug 2, 2009 at 9:06 AM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > I was playing around with a custom mapping type, and I wanted to use it > as a namespace, so I tried to use it as my module __dict__: > > >>> import __main__ > >>> __main__.__dict__ = MyNamespace() > Traceback (most recent call last): > File "", line 1, in > TypeError: readonly attribute > > Why is __dict__ made read-only? to protect module type? Use .update() method: __main.__.__dict__.update(MyNamespace()) You can create your own Module instance: from types import ModuleType m = ModuleType('modulename') and make a sub class of ModuleType is also OK > > > I next thought I could change the type of the namespace to my class: > > >>> __main__.__dict__.__class__ = MyNamespace > Traceback (most recent call last): > File "", line 1, in > TypeError: __class__ assignment: only for heap types > > Drat, foiled again!!! > > Okay, if I can't do this at the module level, can I at least install a > custom namespace at the class level? > > >>> class MyNamespace(dict): > ... def __getitem__(self, key): > ... print "Looking up key '%s'" % key > ... return super(MyNamespace, self).__getitem__(key) > ... > >>> namespace = MyNamespace(x=1, y=2, z=3) > >>> namespace['x'] > Looking up key 'x' > 1 > >>> C = new.classobj("C", (object,), namespace) > >>> C.x > 1 > > Apparently not. It looks like the namespace provided to the class > constructor gets copied when the class is made. > > Interestingly enough, the namespace argument gets modified *before* it > gets copied, which has an unwanted side-effect: > > >>> namespace > {'y': 2, 'x': 1, '__module__': '__main__', 'z': 3, '__doc__': None} > > > Is there any way to install a custom type as a namespace? > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From dciphercomputing at gmail.com Sat Aug 1 21:25:10 2009 From: dciphercomputing at gmail.com (Simon) Date: Sat, 1 Aug 2009 18:25:10 -0700 (PDT) Subject: Newbie Question regarding __init__() References: Message-ID: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> Okay I will fix my code and include "self" and see what happens. I know I tried that before and got another error which I suspect was another newbie error. The idea behind the init_Pre is that I can put custom code here to customize the __init__ instead of creating a new subclass. This kind of hook pattern allows you to flatten your inheritance hierarchy. I can choose in the init_Pre method to execute code before the init_exec (which contains the default __init__ code) and still execute the init_Exec method or I can completely customize the entire __init__ by returning False from init_Pre and prevent the init_Exec from being called. I use this type of pattern with almost all my methods. In this way I can create a less complicated inheritance chain but still have have custom code when needed without sub-classing. I am use to Visual FoxPro which where you can do =This.init_Pre().And.This.init_Exec() and the result is discarded so that is why it looks the way it does. In this form init_Exec has to return a value. However, If self.init_Pre(): self.init_Exec() would work the same and then I could avoid returning a value. Thanks, Simon On Aug 1, 5:52?am, Dave Angel wrote: > Nat Williams wrote: > > As MRAB described, ALL instance methods need to accept 'self' as a first > > parameter, as that will be passed to them implicitly when they are called. > > This includes __init__. ?The name 'self' is just a commonly accepted > > convention for the name of the instance object passed to methods. ?You don't > > have to call it that, but you really should. > > > Take a look athttp://docs.python.org/tutorial/classes.html#class-objects > > It might help shed some light on how methods and instances work. > > > One other thing. ?I'm a little confused by the first line of > > dcObject.__init__: > > > self.init_Pre() and self.init_Exec() > > > I suspect this does not do what you think it does. ?init_Pre and init_Exec > > will both be called by this expression (unless init_Pre throws an exception, > > of course). ?You're not getting anything here that you wouldn't by just > > calling each method on a separate line, except just making it harder to > > read. > > Read the doc-string for init_Pre() and for init_Exec(). ?The final > version of init_Pre() will return False in some circumstances, and in > those circumstances Simon doesn't want init_Exec() to be called. ?He's > deliberately using the short-circuit evaluation of ?'and' ?to accomplish > that. > > > > > > > > > On Fri, Jul 31, 2009 at 8:53 PM, Simon wrote: > > >> Hi > > >> So should the dcObject class include the "self" as well since I have > >> not defined an __init__ method in dcCursor? > > >> Simon > > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > Every one of those methods in both of those classes need a "self" first > argument. ?As others have said, all instance methods need a 'self.' From sturlamolden at yahoo.no Sat Aug 1 21:31:15 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 18:31:15 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: Message-ID: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> On 20 Jul, 18:27, Phillip B Oldham wrote: > We're not looking to start any arguments or religious wars and we're > not asking that python be changed into something its not. We'd simply > like to understand the decision behind the lists and tuple structures. > We feel that in not "getting" the difference between the two types we > may be missing out on using these data structures to their full > potential. A crude simplification would be: - A Python programmer will use a tuple where a C programmer will use a struct. - Python and C programmers use lists and arrays similarly. Tuples are used for passing arguments to and from a function. Common use of tuples include multiple return values and optional arguments (*args). It has already been mentioned that tuples are immutable and can be used as dictionary keys. From skip at pobox.com Sat Aug 1 21:38:46 2009 From: skip at pobox.com (Skip Montanaro) Date: Sun, 2 Aug 2009 01:38:46 +0000 (UTC) Subject: Wrapping prstat on Solaris References: <1bce2ffd-85cb-4860-8b3e-92d8e1619a46@k19g2000yqn.googlegroups.com> Message-ID: > You haven't told us how you are actually reading from prstat's output > pipe, which may be the cause. For instance, if you are doing > > for line in pipe: > print line > ... > > then this could cause your buffering issue. > > Instead try using readline(): > > while True: > line = pipe.readline() > ... Yes, I've been using for line in pipe. Switching to your construct seems to work like a charm. Thanks, Skip From fatkinson at mishmash.com Sat Aug 1 21:50:48 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sat, 01 Aug 2009 18:50:48 -0700 Subject: Get Cliet IP Address Message-ID: What is the function to obtain the client browser's IP address? Fred From fatkinson at mishmash.com Sat Aug 1 21:56:33 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sat, 01 Aug 2009 18:56:33 -0700 Subject: Predefined Variables References: <7cr6siF28oinaU2@mid.uni-berlin.de> Message-ID: <4gs9755f299j7ueitf422hh2vna32f358o@4ax.com> On Thu, 23 Jul 2009 15:28:50 +0200, "Diez B. Roggisch" wrote: >Fred Atkinson wrote: > >> Is there a pre-defined variable that returns the GET line >> (http://www.php.net/index.php?everythingafterthequestionmark) as a >> single variable (rather than individual variables)? > >Variables don't return things. Functions do. And additionally the answer >depends on what and with what you actually do. > >Diez I want to display the client browser's IP address on the Web page. I'd like to create a variable like this: ip = somefunction(). Then I can print the IP address on the Web page and/or log it in an error file. Fred From sturlamolden at yahoo.no Sat Aug 1 22:19:43 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 19:19:43 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: <86b332b3-2da0-44e0-b29f-d930136635df@u16g2000pru.googlegroups.com> <4677d753-364f-4d29-9091-e55008daec83@12g2000pri.googlegroups.com> Message-ID: <78d2801f-790c-475b-8953-23094482637f@h21g2000yqa.googlegroups.com> On 31 Jul, 23:43, Raymond Hettinger wrote: >?More than one person here has > observed that the time to learn to program Pythonically is inversely > proportional to their experience in Java. I believe it is opposite. The longer the Java experience, the longer it takes to program pythonically. The correlation is not inverse. In particular, programmers accustomed to Java or C++ seem to use for- loops awfully lot. And when they do, they always loop over a sequence of integers, and use these as array indices. They consequently use a class where a tuple would be more appropriate, never return multiple values from functions, etc. Due to their coding style, they produce programs that are notoriously inefficient, and blame this on 'Python being slow'. Unlearning the idioms from Java takes a while. Python is not Java and should not be programmed as such. On the other hand, I found that my experience with MATLAB helped me a lot on picking up a pythonical style quickly. From greg at cosc.canterbury.ac.nz Sat Aug 1 22:19:45 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 02 Aug 2009 14:19:45 +1200 Subject: Python processors? : WAS Re: Does python have the capability for driver development ? In-Reply-To: <2d8298b9-b857-4b3d-ae63-2056d80cdf7f@d4g2000yqa.googlegroups.com> References: <4a7151b2$0$17782$ba4acef3@news.orange.fr> <2d8298b9-b857-4b3d-ae63-2056d80cdf7f@d4g2000yqa.googlegroups.com> Message-ID: <7dkbcqF2c6aqgU1@mid.individual.net> Francesco Bochicchio wrote: > I wonder: has anybody thought of making a python-machine, or at least > a processor able to directly execute high-level bytecode (LLVM-like?). In some of my idle moments I've speculated on what such a machine might be like. One of my ideas for potential future projects is to flesh out the design and maybe even build an FPGA prototype. It would purely be for fun, though. It's unlikely that such a processor would be able to compete speed-wise with a general-purpose CPU running a Python interpreter with critical libraries written in C. That's what killed things like the Lisp machine. Their developers couldn't keep up with the huge resources that people like Intel and Motorola had to throw at CPU development, so eventually a general-purpose CPU could run Lisp faster than a Lisp machine. -- Greg From sturlamolden at yahoo.no Sat Aug 1 22:44:17 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 19:44:17 -0700 (PDT) Subject: fast video encoding References: <570097d0-2b2a-4705-892f-0d0154d69d63@b14g2000yqd.googlegroups.com> Message-ID: <0c8cfac7-0a70-4e1f-90ec-19e9c45cae89@h21g2000yqa.googlegroups.com> On 29 Jul, 10:14, gregorth wrote: > for a scientific application I need to save a video stream to disc for > further post processing. I have worked a bit on this as well. There are two things that make scientific applications different form common video encoding: First, a scientific video stream is often very different from a 'movie': There are usually very little 'movement'. For example, when I have filmed a mouse swimming in a water maze (a pool of milky white water), the only thing that moves is the rat. So I could achieve excellent compression just by saving the pixels that changed. Second, scientific data should be stored with lossless compression if possible. Common video codecs are aimed at films and home video, not scientific video streams. I don't know how your data are, but I would be very picky about the codec. And chances are you will be better off home-brewing your own domain specific compression. If you need to store large amounts of scientific data, consider using something like a HDF5 database for storage. There are two Python wrappers for HDF5 that I know of (h5py and PyTables). From nobody at nowhere.com Sat Aug 1 22:47:59 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 02 Aug 2009 03:47:59 +0100 Subject: Help understanding the decisions *behind* python? References: <86b332b3-2da0-44e0-b29f-d930136635df@u16g2000pru.googlegroups.com> <4677d753-364f-4d29-9091-e55008daec83@12g2000pri.googlegroups.com> <78d2801f-790c-475b-8953-23094482637f@h21g2000yqa.googlegroups.com> Message-ID: On Sat, 01 Aug 2009 19:19:43 -0700, sturlamolden wrote: >>?More than one person here has >> observed that the time to learn to program Pythonically is inversely >> proportional to their experience in Java. > > I believe it is opposite. The longer the Java experience, the longer > it takes to program pythonically. The correlation is not inverse. In > particular, programmers accustomed to Java or C++ seem to use for- > loops awfully lot. And when they do, they always loop over a sequence > of integers, and use these as array indices. It would be more accurate to say that of programmers who are *only* accustomed to Java or C++. I've been using C for 80-90% of my code for 25 years, and I wouldn't normally loop over the indices. But then the other 10-20% is Lisp, Tcl, Haskell, PostScript and, more recently, Python. OTOH, using a "for" loop when you could use a generator means less work when you need to make a minor change and a generator is no longer sufficient. From sturlamolden at yahoo.no Sat Aug 1 23:00:32 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 20:00:32 -0700 (PDT) Subject: Does python have the capability for driver development ? References: <87skgf83ua.fsf@rsw.digi.com.br> <94abbddc-dac7-4215-84d1-d4eb3f82724d@h21g2000yqa.googlegroups.com> Message-ID: On 30 Jul, 02:19, MalC0de wrote: > actually I mean driver programming under Windows operating system, if > you know, there's A kit name DDK available at microsoft's website for > developing device drivers under C / C++ environment, Actually, Microsoft has replaced DDK with a new kit called WDK for Vista. The funny thing about WDK is that there are a lot of illegal C and C++ in the headers, which even Microsoft's own compiler refuse to accept. So good luck on getting anything to compile. From darkneter at gmail.com Sat Aug 1 23:04:05 2009 From: darkneter at gmail.com (NighterNet) Date: Sat, 1 Aug 2009 20:04:05 -0700 (PDT) Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> <8bede581-f260-4c69-abf0-1e8071380b76@z4g2000prh.googlegroups.com> Message-ID: <7e6cdc26-bcc0-4503-b7b4-9ad80b1041f6@v37g2000prg.googlegroups.com> Here the full code. flashpolicy.xml [[[ ]]] flashpolicytest_server3x.py [[[ #!/usr/local/bin/python ''' Still under testing... python version 3.x.x ''' import socket import threading import sys import os file_name = 'flashpolicy.xml' fh = open(file_name, "r") policy = fh.read(10001) host = ''; #out side network port = 5555; print ("# ------------- Init... ------------- #"); class ClientThread (threading.Thread): global policy; allClients = []; vlock = threading.Lock(); id = 0 # next available thread number def __init__(self,clientSocket): threading.Thread.__init__(self) self.sockfd = clientSocket; #socket client self.name = ''; ClientThread.id += 1 self.id = ClientThread.id self.nickName = ''; self.allClients.append(self.sockfd); def sendAll(self,buff): for index,clientSock in enumerate(self.allClients): try: clientSock.send(buff); except (socket.error): print ('error socket %s\n',index,"| clean"); clientSock.close() del self.allClients[index] def run(self): while True: buff = self.sockfd.recv(1028); if not buff: print ("connect close...(client side)"); self.sockfd.close(); break #incase it loop infinite if str(buff) == str("b\'\\x00\'"): print ('policy FOUND >>> sending...') print(buff) b = b'' print (b) self.sockfd.send(b); self.sockfd.sendall(b); print(buff); self.sendAll(buff) self.sockfd.close() print ("# ------------- Init... Listen Client ------------- #\n"); try: server = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) except AttributeError: # AttributeError catches Python built without IPv6 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) except socket.error: # socket.error catches OS with IPv6 disabled server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server.bind((host,port)) server.listen(5) print ("Server Up Listen!",host,":",port," Bind!"); while True: (clientSocket, address) = server.accept(); print("client connect from :",address); ct = ClientThread(clientSocket); print(ct.id); ct.start(); ]]] Some odd reason I can't send flash policy from python to flash socket to agrees with the connection. From fatkinson at mishmash.com Sat Aug 1 23:07:21 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sat, 01 Aug 2009 20:07:21 -0700 Subject: Predefined Variables References: <7cr6siF28oinaU2@mid.uni-berlin.de> <4gs9755f299j7ueitf422hh2vna32f358o@4ax.com> Message-ID: On Sat, 01 Aug 2009 18:56:33 -0700, Fred Atkinson wrote: >On Thu, 23 Jul 2009 15:28:50 +0200, "Diez B. Roggisch" > wrote: > >>Fred Atkinson wrote: >> >>> Is there a pre-defined variable that returns the GET line >>> (http://www.php.net/index.php?everythingafterthequestionmark) as a >>> single variable (rather than individual variables)? >> >>Variables don't return things. Functions do. And additionally the answer >>depends on what and with what you actually do. >> >>Diez > > I want to display the client browser's IP address on the Web >page. > > I'd like to create a variable like this: ip = somefunction(). > Then I can print the IP address on the Web page and/or log it >in an error file. > > > > Fred I replied to the wrong post. Sorry. I want to do something like this: string = os.environment('QUERY_STRING') If this is the string in the URL: http://www.someurl.com/cgi-bin/somescript.cgi?anythingafterthequestionmark 'string' should now contain the value 'everythingafterthequestionmark' When I use the os.environment('QUERY_STRING'), it doesn't work. Is there something I should import to make this function work? Or what else is wrong? Fred From sturlamolden at yahoo.no Sat Aug 1 23:10:00 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 20:10:00 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: <86b332b3-2da0-44e0-b29f-d930136635df@u16g2000pru.googlegroups.com> <4677d753-364f-4d29-9091-e55008daec83@12g2000pri.googlegroups.com> <78d2801f-790c-475b-8953-23094482637f@h21g2000yqa.googlegroups.com> Message-ID: <8a15492e-c9ab-47be-afea-cde3065413b1@e27g2000yqm.googlegroups.com> On 2 Aug, 04:47, Nobody wrote: > OTOH, using a "for" loop when you could use a generator means less work > when you need to make a minor change and a generator is no longer > sufficient. It's not just that. It is e.g. using a for loop and indexes instead of a slice. E.g. for i in range(10): # Java idiom a[i] = b[i+1] instead of a[:10] = b[1:11] # Pythonic From sturlamolden at yahoo.no Sat Aug 1 23:24:11 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sat, 1 Aug 2009 20:24:11 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: <86b332b3-2da0-44e0-b29f-d930136635df@u16g2000pru.googlegroups.com> <200907312048.03922.emmanuel.surleau@gmail.com> Message-ID: <2ff11bfc-9101-4b29-8b71-1627d85f799e@18g2000yqa.googlegroups.com> On 31 Jul, 21:31, Masklinn wrote: > It's intuitive if you come to Python knowing other languages with ? > tuples (which are mostly functional, and in which tuples are *never* ? > sequences/iterables). At the end of the day, and if Guido's intention ? > truly was what Raymond says, implementing tuples as immutable sequence ? > was a mistake. And the documentation is to blame as well: in it, ? > tuples are clearly described as a *sequence* type, not a *structure* ? > type. That depends on the readers' preconceptions: Only when the reader have knowledge of C structs, Pascal records, or Java classes should this matter. The na?ve reader will not have preconceptions about a difference between "structure types" and "sequence types". A more advanced C programmer will also know that a struct is a form of a sequence in C: you can e.g. memcpy any struct to a char array. From zooko at zooko.com Sun Aug 2 00:14:49 2009 From: zooko at zooko.com (Zooko Wilcox-O'Hearn) Date: Sat, 1 Aug 2009 22:14:49 -0600 Subject: ANNOUNCING Tahoe, the Lofty-Atmospheric Filesystem, v1.5 Message-ID: <9CE7ACE7-219C-4097-8543-928E05651387@zooko.com> Dear people of python-list: Python is our preferred programming language for the Tahoe-LAFS project. We use C/C++ extension modules for the CPU-intensive parts, and we interoperate with many languages through the RESTful web API, but the core code is 100% Python. Regards, Zooko --- The Tahoe-LAFS team is pleased to announce the immediate availability of version 1.5 of Tahoe, the Lofty Atmospheric File System. Tahoe-LAFS is the first cloud storage technology which offers security and privacy in the sense that the cloud storage service provider itself can't read or alter your data. Here is the one-page explanation of its unique security and fault-tolerance properties: http://allmydata.org/source/tahoe/trunk/docs/about.html This release is the successor to v1.4.1, which was released April 13, 2009 [1]. This is a major new release, improving the user interface and performance and fixing a few bugs, and adding ports to OpenBSD, NetBSD, ArchLinux, NixOS, and embedded systems built on ARM CPUs. See the NEWS file [2] for more information. In addition to the functionality of Tahoe-LAFS itself, a crop of related projects have sprung up to extend it and to integrate it into operating systems and applications. These include frontends for Windows, Macintosh, JavaScript, and iPhone, and plugins for duplicity, bzr, Hadoop, and TiddlyWiki, and more. See the Related Projects page on the wiki [3]. COMPATIBILITY Version 1.5 is fully compatible with the version 1 series of Tahoe-LAFS. Files written by v1.5 clients can be read by clients of all versions back to v1.0. v1.5 clients can read files produced by clients of all versions since v1.0. v1.5 servers can serve clients of all versions back to v1.0 and v1.5 clients can use servers of all versions back to v1.0. This is the sixth release in the version 1 series. The version 1 series of Tahoe-LAFS will be actively supported and maintained for the forseeable future, and future versions of Tahoe-LAFS will retain the ability to read and write files compatible with Tahoe-LAFS v1. The version 1 series of Tahoe-LAFS is the basis of the consumer backup product from Allmydata, Inc. -- http://allmydata.com . WHAT IS IT GOOD FOR? With Tahoe-LAFS, you can distribute your filesystem across a set of servers, such that if some of them fail or even turn out to be malicious, the entire filesystem continues to be available. You can share your files with other users, using a simple and flexible access control scheme. We believe that the combination of erasure coding, strong encryption, Free/Open Source Software and careful engineering make Tahoe-LAFS safer than RAID, removable drive, tape, on-line backup or other Cloud storage systems. This software comes with extensive tests, and there are no known security flaws which would compromise confidentiality or data integrity in typical use. (For all currently known issues please see the known_issues.txt file [4].) LICENCE You may use this package under the GNU General Public License, version 2 or, at your option, any later version. See the file "COPYING.GPL" [5] for the terms of the GNU General Public License, version 2. You may use this package under the Transitive Grace Period Public Licence, version 1 or, at your option, any later version. (The Transitive Grace Period Public Licence has requirements similar to the GPL except that it allows you to wait for up to twelve months after you redistribute a derived work before releasing the source code of your derived work.) See the file "COPYING.TGPPL.html" [6] for the terms of the Transitive Grace Period Public Licence, version 1. (You may choose to use this package under the terms of either licence, at your option.) INSTALLATION Tahoe-LAFS works on Linux, Mac OS X, Windows, Cygwin, Solaris, *BSD, and probably most other systems. Start with "docs/install.html" [7]. HACKING AND COMMUNITY Please join us on the mailing list [8]. Patches are gratefully accepted -- the RoadMap page [9] shows the next improvements that we plan to make and CREDITS [10] lists the names of people who've contributed to the project. The Dev page [11] contains resources for hackers. SPONSORSHIP Tahoe-LAFS was originally developed thanks to the sponsorship of Allmydata, Inc. [12], a provider of commercial backup services. Allmydata, Inc. created the Tahoe-LAFS project and contributed hardware, software, ideas, bug reports, suggestions, demands, and money (employing several Tahoe-LAFS hackers and instructing them to spend part of their work time on this Free Software project). Also they awarded customized t-shirts to hackers who found security flaws in Tahoe-LAFS (see http://hacktahoe.org ). After discontinuing funding of Tahoe-LAFS R&D in early 2009, Allmydata, Inc. has continued to provide servers, co-lo space and bandwidth to the open source project. Thank you to Allmydata, Inc. for their generous and public-spirited support. This is the second release of Tahoe-LAFS which was created solely as a labor of love by volunteers; developer time is no longer funded by allmydata.com (see [13] for details). Zooko Wilcox-O'Hearn on behalf of the Tahoe-LAFS team Special acknowledgment goes to Brian Warner, whose superb engineering skills and dedication are primarily responsible for the Tahoe implementation, and significantly responsible for the Tahoe design as well, not to mention most of the docs and tests. Tahoe-LAFS wouldn't exist without him. August 1, 2009 Boulder, Colorado, USA P.S. Just kidding about that acronym. "LAFS" actually stands for "Lightweight Authorization File System". Or possibly for "Least-Authority File System". There is no truth to the rumour that it actually stands for "Long-lived Axe-tolerant File System". [1] http://allmydata.org/trac/tahoe/browser/relnotes.txt?rev=3853 [2] http://allmydata.org/trac/tahoe/browser/NEWS?rev=4033 [3] http://allmydata.org/trac/tahoe/wiki/RelatedProjects [4] http://allmydata.org/trac/tahoe/browser/docs/known_issues.txt [5] http://allmydata.org/trac/tahoe/browser/COPYING.GPL [6] http://allmydata.org/source/tahoe/trunk/COPYING.TGPPL.html [7] http://allmydata.org/source/tahoe/trunk/docs/install.html [8] http://allmydata.org/cgi-bin/mailman/listinfo/tahoe-dev [9] http://allmydata.org/trac/tahoe/roadmap [10] http://allmydata.org/trac/tahoe/browser/CREDITS?rev=4035 [11] http://allmydata.org/trac/tahoe/wiki/Dev [12] http://allmydata.com [13] http://allmydata.org/pipermail/tahoe-dev/2009-March/001461.html From clp2 at rebertia.com Sun Aug 2 00:46:35 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 1 Aug 2009 21:46:35 -0700 Subject: Custom namespaces In-Reply-To: <0284d760$0$20667$c3e8da3@news.astraweb.com> References: <0284d760$0$20667$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0908012146p11c58419s7d33aa9a2a048f46@mail.gmail.com> On Sat, Aug 1, 2009 at 6:06 PM, Steven D'Aprano wrote: > I was playing around with a custom mapping type, and I wanted to use it > as a namespace, so I tried to use it as my module __dict__: > >>>> import __main__ >>>> __main__.__dict__ = MyNamespace() > Traceback (most recent call last): > ?File "", line 1, in > TypeError: readonly attribute > > Why is __dict__ made read-only? > > I next thought I could change the type of the namespace to my class: > >>>> __main__.__dict__.__class__ = MyNamespace > Traceback (most recent call last): > ?File "", line 1, in > TypeError: __class__ assignment: only for heap types > > Drat, foiled again!!! > > Okay, if I can't do this at the module level, can I at least install a > custom namespace at the class level? > Apparently not. It looks like the namespace provided to the class > constructor gets copied when the class is made. > Is there any way to install a custom type as a namespace? For classes/objects, yes, using metaclasses. See the __prepare__() method in PEP 3115: http://www.python.org/dev/peps/pep-3115/ Cheers, Chris -- http://blog.rebertia.com From bhardwajjayesh7 at gmail.com Sun Aug 2 02:11:43 2009 From: bhardwajjayesh7 at gmail.com (golu) Date: Sat, 1 Aug 2009 23:11:43 -0700 (PDT) Subject: cgi script Message-ID: Hi, i started learning cgi few days ago in python and everything went fine until i started getting the follwing error " The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there was an error in a CGI script. If you think this is a server error, please contact the webmaster. " i am using apache on xampp. plz help From michael at altra-optics.co.uk Sun Aug 2 02:34:56 2009 From: michael at altra-optics.co.uk (Michael M Mason) Date: Sun, 2 Aug 2009 07:34:56 +0100 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: <7dks7jF2ccjstU1@mid.individual.net> "Dave Angel" wrote in message news:mailman.4120.1249172970.8015.python-list at python.org... > Michael M Mason wrote: >>
I'm running >> Python 3.1 on Vista and I can't figure out how to add my own directory to >> sys.path. Thanks to Jon, Piet, David and Dave for the responses. > sys.path gets its values from several places. Ah, I'd misunderstood the docs: I thought it came from just one place (which I couldn't find). > Anyway, I'd suggest adding it to PythonPath, and if it's empty, just > create it with the directory you need. Thanks--that worked! > I'm hoping you know you can also add to sys.path directly during script > initialization. It's just a list, and is writeable. Yes, but I'm mainly playing in IDLE and I was getting a bit fed up of repeatedly typing import sys sys.path.append('C:/Users/Michael/Code/Python') import mystuff -- Michael From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 02:47:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 06:47:41 GMT Subject: Python processors? : WAS Re: Does python have the capability for driver development ? References: <4a7151b2$0$17782$ba4acef3@news.orange.fr> <2d8298b9-b857-4b3d-ae63-2056d80cdf7f@d4g2000yqa.googlegroups.com> <7dkbcqF2c6aqgU1@mid.individual.net> Message-ID: <02852746$0$20667$c3e8da3@news.astraweb.com> On Sun, 02 Aug 2009 14:19:45 +1200, greg wrote: > That's what killed things like the Lisp machine. Their developers > couldn't keep up with the huge resources that people like Intel and > Motorola had to throw at CPU development, so eventually a > general-purpose CPU could run Lisp faster than a Lisp machine. When you say "eventually", I think you mean "decades ago". I recall a collaboration between Apple and Texas Instruments to build a Macintosh with a Lisp Machine in the late 1980s. From the one box, you could run two computers simultaneously, with two operating systems, one running the Motorola 68020 and the other a Lisp Machine processor. I don't think it sold very well -- by memory, benchmarks showed that for half (or less) of the price, you could run Lisp in software on a vanilla Mac and the software would be faster than running it on the Lisp Machine. TI also had at least one Nubus card for the Mac running a Lisp Machine: http://en.wikipedia.org/wiki/TI_Explorer On a similar note, there were Forth machines also available for the Apple Macintosh. Unlike Lisp, I think they suffered from the general lack of popularity of Forth rather than lack of speed. -- Steven From efotinis at oohay.com Sun Aug 2 02:59:41 2009 From: efotinis at oohay.com (eliasf) Date: Sun, 2 Aug 2009 09:59:41 +0300 Subject: Get Cliet IP Address In-Reply-To: References: Message-ID: <1249196395.629238@athprx04> "Fred Atkinson" wrote: > What is the function to obtain the client browser's IP > address? Do you mean the external public IP to the Internet? When I wanted to log the dynamic IP that my ADSL connection gets, I used whatismyip.com like this: import urllib2 QUERY_URL = 'http://www.whatismyip.com/automation/n09230945.asp' def query(): """Get IP as a string. As per the whatismyip.com automation rules, this function should not be called more ofter than every 5 minutes. """ return urllib2.urlopen(QUERY_URL).read() There's probably a better way, but I'm not very good with networking. :o) From pavlovevidence at gmail.com Sun Aug 2 03:14:41 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 Aug 2009 00:14:41 -0700 (PDT) Subject: cgi script References: Message-ID: <007247ae-53b8-4ce7-ad85-eb332b455f41@2g2000prl.googlegroups.com> On Aug 1, 11:11?pm, golu wrote: > Hi, > i started learning cgi few days ago in python and everything went > fine ?until i started getting the follwing error > " > The server encountered an internal error and was unable to complete > your request. Either the server is overloaded or there was an error in > a CGI script. Your script has a syntax error. (You forgot a colon or something like that.) If you can, try to run the file directly from a Python interpreter to see where the error is. Carl Banks From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 03:18:53 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 07:18:53 GMT Subject: Custom namespaces References: <0284d760$0$20667$c3e8da3@news.astraweb.com> Message-ID: <02852e95$0$20667$c3e8da3@news.astraweb.com> On Sat, 01 Aug 2009 21:46:35 -0700, Chris Rebert wrote: >> Is there any way to install a custom type as a namespace? > > For classes/objects, yes, using metaclasses. See the __prepare__() > method in PEP 3115: http://www.python.org/dev/peps/pep-3115/ Looks good, but that's Python 3 only, yes? At least, I can't get the metaclass to change the __dict__ in Python 2.6. There's obviously no __prepare__ before 3.0, but I tried the following, and still __dict__ ends up as a regular dict. Am I missing something? class VerboseDict(dict): def __getitem__(self, item): print ("Looking up key '%s'..." % item) return super(VerboseDict, self).__getitem__(item) class Meta(type): def __new__(cls, name, bases, namespace): namespace = VerboseDict(namespace) obj = super(Meta, cls).__new__(cls, name, bases, namespace) return obj MyClass = Meta('MyClass', (object,), dict(x=1, y=2)) -- Steven From clp2 at rebertia.com Sun Aug 2 03:31:05 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 Aug 2009 00:31:05 -0700 Subject: Custom namespaces In-Reply-To: <02852e95$0$20667$c3e8da3@news.astraweb.com> References: <0284d760$0$20667$c3e8da3@news.astraweb.com> <02852e95$0$20667$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0908020031h32fadb65ye7e306138205a751@mail.gmail.com> On Sun, Aug 2, 2009 at 12:18 AM, Steven D'Aprano wrote: > On Sat, 01 Aug 2009 21:46:35 -0700, Chris Rebert wrote: > >>> Is there any way to install a custom type as a namespace? >> >> For classes/objects, yes, using metaclasses. See the __prepare__() >> method in PEP 3115: http://www.python.org/dev/peps/pep-3115/ > > Looks good, but that's Python 3 only, yes? Correct. > At least, I can't get the metaclass to change the __dict__ in Python 2.6. > There's obviously no __prepare__ before 3.0, but I tried the following, > and still __dict__ ends up as a regular dict. Am I missing something? > > > class VerboseDict(dict): > ? ?def __getitem__(self, item): > ? ? ? ?print ("Looking up key '%s'..." % item) > ? ? ? ?return super(VerboseDict, self).__getitem__(item) > > class Meta(type): > ? ?def __new__(cls, name, bases, namespace): > ? ? ? ?namespace = VerboseDict(namespace) > ? ? ? ?obj = super(Meta, cls).__new__(cls, name, bases, namespace) > ? ? ? ?return obj I would /guess/ that type.__new__() is internally doing the equivalent of dict(namespace). Hence why the addition of __prepare__() was necessary; it's probably impossible to accomplish what you want in earlier Python versions. Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 03:35:08 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 07:35:08 GMT Subject: Generate a new object each time a name is imported Message-ID: <02853264$0$20667$c3e8da3@news.astraweb.com> I would like to generate a new object each time I import a name from a module, rather than getting the same object each time. For example, currently I might do something like this: # Module count = 0 def factory(): # Generate a unique object each time this is called global count count += 1 return "Object #%d" % count # Calling module from Module import factory a = factory() # a == "Object #1" b = factory() # b == "Object #2" del factory I'm looking for a way to hide the generation of objects from the caller, so I could do something like this: from Module import factory() as a # a == "Object #1" from Module import factory() as b # b == "Object #2" except of course that syntax is illegal. -- Steven From jgardner at jonathangardner.net Sun Aug 2 03:38:22 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Sun, 2 Aug 2009 00:38:22 -0700 (PDT) Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: On Aug 2, 12:35?am, Steven D'Aprano wrote: > > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a ?# a == "Object #1" > from Module import factory() as b ?# b == "Object #2" > Explicit is better than implicit. In other words, I don't see why you need to hide this. Just import the factory function and call it. from Module import factory a = factory() From hniksic at xemacs.org Sun Aug 2 04:23:51 2009 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Sun, 02 Aug 2009 10:23:51 +0200 Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <87tz0qei94.fsf@busola.homelinux.net> Steven D'Aprano writes: > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a # a == "Object #1" > from Module import factory() as b # b == "Object #2" > > except of course that syntax is illegal. That sounds reasonable (zen quotes aside), but it's just not possible in current Python. It would require for any use of "a" in subsequent code to not only refer to an object, but also to automagically call it. I know of no mechanism to do that. While Python allows intricate customization of access to objects, simply referring to a name remains fixed in meaning, probably intentionally. (The "cell" mechanism used to implement closures sounds like it could help, but a cell only stores a single value, not a factory, and it doesn't apply to global variables anyway.) From Ron.Barak at lsi.com Sun Aug 2 04:45:09 2009 From: Ron.Barak at lsi.com (Barak, Ron) Date: Sun, 2 Aug 2009 09:45:09 +0100 Subject: Run pyc file without specifying python path ? In-Reply-To: <4A71D35F.3090800@dejaviewphoto.com> References: <7F0503CD69378F49BE0DC30661C6CCF6701A26C4@enbmail01.lsi.com> <4A708F68.1010505@ieee.org> <7F0503CD69378F49BE0DC30661C6CCF6701A26C7@enbmail01.lsi.com> <4A7199FF.8010202@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF6701A26D2@enbmail01.lsi.com> <4A71D35F.3090800@dejaviewphoto.com> Message-ID: <7F0503CD69378F49BE0DC30661C6CCF67D49D30E@enbmail01.lsi.com> > -----Original Message----- > From: Dave Angel [mailto:davea at dejaviewphoto.com] > Sent: Thursday, July 30, 2009 20:08 > To: Barak, Ron > Cc: 'python-list at python.org' > Subject: Re: Run pyc file without specifying python path ? > > Barak, Ron wrote: > > Hi Dave, > > > > On second thoughts, I may have a problem implementing the > wrapper solution, because my actual test_pyc.pyc, needs to > parse its command line. > > Namely, the actual call to test_pyc.pyc looks something like this: > > > > $ python test_pyc.py -U dave -PpasswoRD -C CreateMcGroupOnVolume > > --SVMs_IPs '10.1.1.1 , 10.1.1.2' -n "host1,host2" -g gn -j > jn -s svn > > -t tvn -p pool1 -l -c > > > > And I don't know of a way to add these parameters to the "import > > test_pyc" in wrapper > > > > Is there a way to pass information to an imported module ? > (Sorry if there's an obvious answer, I just cannot figure it out). > > > > Bye, > > Ron. > > > > > >> -----Original Message----- > >> From: Dave Angel [mailto:davea at dejaviewphoto.com] > >> Sent: Thursday, July 30, 2009 16:03 > >> To: Barak, Ron > >> Cc: 'Dave Angel'; 'python-list at python.org' > >> Subject: RE: Run pyc file without specifying python path ? > >> > >> Barak, Ron wrote: > >> > >>>> -----Original Message----- > >>>> From: Dave Angel [mailto:davea at ieee.org] > >>>> Sent: Wednesday, July 29, 2009 21:05 > >>>> To: Barak, Ron > >>>> Cc: 'python-list at python.org' > >>>> Subject: Re: Run pyc file without specifying python path ? > >>>> > >>>> Barak, Ron wrote: > >>>> > >>>> > >>>>> Hi, > >>>>> > >>>>> I wanted to make a python byte-code file executable, > >>>>> > >>>>> > >>>> expecting to be able to run it without specifying > "python" on the > >>>> (Linux bash) command line. > >>>> > >>>> > >>>>> So, I wrote the following: > >>>>> > >>>>> [root at VMLinux1 python]# cat test_pyc.py #!/usr/bin/env python > >>>>> > >>>>> print "hello" > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> and made its pyc file executable: > >>>>> > >>>>> [root at VMLinux1 python]# ls -ls test_pyc.pyc > >>>>> 4 -rwxr-xr-x 1 root root 106 Jul 29 14:22 test_pyc.pyc > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> So, I see: > >>>>> > >>>>> [root at VMLinux1 python]# file test_pyc.py* > >>>>> test_pyc.py: a python script text executable > >>>>> test_pyc.pyc: python 2.3 byte-compiled > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> If I try to do the following, no problem: > >>>>> > >>>>> [root at VMLinux1 python]# python test_pyc.pyc hello > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> However, the following fails: > >>>>> > >>>>> [root at VMLinux1 python]# ./test_pyc.pyc > >>>>> -bash: ./test_pyc.pyc: cannot execute binary file > >>>>> [root at VMLinux1 python]# > >>>>> > >>>>> Is there a way to run a pyc file without specifying the > >>>>> > >>>>> > >>>> python path ? > >>>> > >>>> > >>>>> Bye, > >>>>> Ron. > >>>>> > >>>>> > >>>>> > >>>>> > >>>> I don't currently run Unix, but I think I know the problem. > >>>> > >>>> In a text file, the shell examines the first line, and if > >>>> > >> it begins > >> > >>>> #! > >>>> it's assumed to point to the executable of an > interpreter for that > >>>> text file. Presumably the same trick doesn't work for a > .pyc file. > >>>> > >>>> Why not write a trivial wrapper.py file, don't compile > it, and let > >>>> that invoke the main code in the .pyc file? > >>>> > >>>> Then make wrapper.py executable, and you're ready to go. > >>>> > >>>> DaveA > >>>> > >>>> > >>>> > >>>> > >>> Hi Dave, > >>> Your solution sort of defeats my intended purpose (sorry > >>> > >> for not divulging my 'hidden agenda'). > >> > >>> I wanted my application to "hide" the fact that it's a > >>> > >> python script, and look as much as possible like it's a compiled > >> program. > >> > >>> The reason I don't just give my user a py file, is that I > >>> > >> don't want a cleaver user to change the innards of the script. > >> > >>> On the other hand, I don't want to make a compiled > >>> > >> (freezed?) version of the application, because it'll grow the > >> resulting file significantly, and I don't have the > experience to know > >> how it will run on different Linuxes. > >> > >>> Bye, > >>> Ron. > >>> > >>> > >> Most of the other answers basically paraphrased my suggestion of > >> making a wrapper file, not compiling it, and making it > executable. > >> With that > >> approach, the user just types "wrapper.py" on his command line. > >> > >> And wrapper.py only needs two lines, a shebang, and an > import, no big > >> deal if the user modifies it. The rest of your code can be .pyc > >> files. > >> > >> Steven makes some good points. You have to define what level of > >> clever you're protecting from. A determined hacker will get in no > >> matter what you do, unless you want to ship the program in a > >> proprietary embedded system, encased in epoxy. > >> Further, if you have an extension of .py or .pyc, a knowledgeable > >> hacker will know it's probably python. > >> > >> You imply you want it to run unmodifed on multiple unknown Linux > >> versions. I think that lets out binfmt solutions. > >> That means you need to test and support not only multiple Linux > >> implementations, but multiple Python versions, because who > knows what > >> the user may have installed. I think you need to rethink your > >> support strategy. And maybe concentrate on being able to detect > >> change, rather than prevent it. > >> > >> DaveA > >> > >> > >> > >> > (Please don't top-post. It puts responses out of order) > > You don't have to do anything special. Any module can import > sys, and parse sys.argv, as long as it wasn't yet modified. > > DaveA > Hi Dave, It seems like I don't understand your solution. I use the (appatched) soapAPI.py as the wrapper to parsing.pyc. However, if I do (for instance): $ python -u parsing.pyc -U aaa The last line of the output is (as expected): return_code: 12 ; params: {'username': 'aaa'} But, if I try the following: $ soapAPI.py -U aaa I don't get this line. Only the output to stderr gets printed to the screen. Bye, Ron. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: soapAPI.py Type: application/octet-stream Size: 65 bytes Desc: soapAPI.py URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: parsing.py Type: application/octet-stream Size: 9542 bytes Desc: parsing.py URL: From breamoreboy at yahoo.co.uk Sun Aug 2 04:55:04 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Aug 2009 09:55:04 +0100 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7dks7jF2ccjstU1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> <7dks7jF2ccjstU1@mid.individual.net> Message-ID: Michael M Mason wrote: > > "Dave Angel" wrote in message > news:mailman.4120.1249172970.8015.python-list at python.org... >> Michael M Mason wrote: >>>
I'm >>> running Python 3.1 on Vista and I can't figure out how to add my own >>> directory to sys.path. > > Thanks to Jon, Piet, David and Dave for the responses. > >> sys.path gets its values from several places. > > Ah, I'd misunderstood the docs: I thought it came from just one place > (which I couldn't find). > >> Anyway, I'd suggest adding it to PythonPath, and if it's empty, just >> create it with the directory you need. > > Thanks--that worked! Be careful, I'm screwed things up on several occasions by placing a file on PYTHONPATH that overrides a file in the standard library, test.py being my favourite! > >> I'm hoping you know you can also add to sys.path directly during >> script initialization. It's just a list, and is writeable. > > Yes, but I'm mainly playing in IDLE and I was getting a bit fed up of > repeatedly typing > import sys > sys.path.append('C:/Users/Michael/Code/Python') > import mystuff > -- Kindest regards. Mark Lawrence. From michael at altra-optics.co.uk Sun Aug 2 05:15:25 2009 From: michael at altra-optics.co.uk (Michael M Mason) Date: Sun, 2 Aug 2009 10:15:25 +0100 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: References: <7djs50F2bsubuU1@mid.individual.net> <7dks7jF2ccjstU1@mid.individual.net> Message-ID: <7dl3pkF2cnqf5U1@mid.individual.net> "Mark Lawrence" wrote in message news:mailman.4130.1249203322.8015.python-list at python.org... > Be careful, I'm screwed things up on several occasions by placing a file > on PYTHONPATH that overrides a file in the standard library, test.py being > my favourite! Thanks. Sure enough, I've already got my own test.py but I hadn't discovered it was a problem yet... -- Michael From davea at ieee.org Sun Aug 2 05:35:34 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 02 Aug 2009 05:35:34 -0400 Subject: Run pyc file without specifying python path ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF67D49D30E@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6701A26C4@enbmail01.lsi.com> <4A708F68.1010505@ieee.org> <7F0503CD69378F49BE0DC30661C6CCF6701A26C7@enbmail01.lsi.com> <4A7199FF.8010202@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF6701A26D2@enbmail01.lsi.com> <4A71D35F.3090800@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF67D49D30E@enbmail01.lsi.com> Message-ID: <4A755DE6.1000906@ieee.org> Barak, Ron wrote: > Hi Dave, > > It seems like I don't understand your solution. > I use the (appatched) soapAPI.py as the wrapper to parsing.pyc. > However, if I do (for instance): > > $ python -u parsing.pyc -U aaa > > The last line of the output is (as expected): > > return_code: 12 ; params: {'username': 'aaa'} > > But, if I try the following: > > $ soapAPI.py -U aaa > > I don't get this line. Only the output to stderr gets printed to the screen. > > Bye, > Ron. > > Hi Ron, To make it easier for anybody following this thread, let me post the minimum equivalent source files, inline. parsing.py: ------------------------------ #!/usr/bin/env python import sys def main(): print >> sys.stderr, "This is stderr output" return 5, sys.argv if __name__ == "__main__": return_code, params = main() print "return_code:",return_code,"; params:",params sys.exit(return_code) ------------------------------- soapapi.py: ------------------------------- #!/usr/bin/env python import sys import parsing parsing.main() ------------------------------ When I run soapapi.;py, it indeed prints only the stderr output. The solution is to move (most or all) of the top-level code of parsing.py into a main() function. Since you already have a main(), I'll rename that, and make a new one that calls it. new parsing.py: ------------------------------- #!/usr/bin/env python import sys def innermain(): print >> sys.stderr, "This is stderr output" return 5, sys.argv def main(): return_code, params = innermain() print "return_code:",return_code,"; params:",params sys.exit(return_code) if __name__ == "__main__": main() ------------------------------- The output is now two lines, one from innermain(), and one from main(). And it's the same whether the user runs parsing.py or soapAPI.py To clarify what happened, realize that when the user invokes parsing.py, the module is considered a script, and gets a pseudo-name of "__main__" When that same module is imported by another one, it is considered a library module, and gets its own name "parsing" So any logic that explicitly checks for "__main__" has to change, because we want identical behavior in the two cases. DaveA From davea at ieee.org Sun Aug 2 05:51:45 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 02 Aug 2009 05:51:45 -0400 Subject: Newbie Question regarding __init__() In-Reply-To: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> Message-ID: <4A7561B1.9060808@ieee.org> Simon wrote: > Okay I will fix my code and include "self" and see what happens. I > know I tried that before and got another error which I suspect was > another newbie error. > > The idea behind the init_Pre is that I can put custom code here to > customize the __init__ instead of creating a new subclass. This kind > of hook pattern allows you to flatten your inheritance hierarchy. I > can choose in the init_Pre method to execute code before the init_exec > (which contains the default __init__ code) and still execute the > init_Exec method or I can completely customize the entire __init__ by > returning False from init_Pre and prevent the init_Exec from being > called. I use this type of pattern with almost all my methods. In > this way I can create a less complicated inheritance chain but still > have have custom code when needed without sub-classing. > > I am use to Visual FoxPro which where you can do > > =is.init_Pre().And.This.init_Exec() and the result is discarded so > that is why it looks the way it does. In this form init_Exec has to > return a value. However, If self.init_Pre(): self.init_Exec() would > work the same and then I could avoid returning a value. > > Thanks, > Simon > > > On Aug 1, 5:52 am, Dave Angel wrote: > >> Nat Williams wrote: >> >>> As MRAB described, ALL instance methods need to accept 'self' as a first >>> parameter, as that will be passed to them implicitly when they are called. >>> This includes __init__. The name 'self' is just a commonly accepted >>> convention for the name of the instance object passed to methods. You don't >>> have to call it that, but you really should. >>> >>> Take a look athttp://docs.python.org/tutorial/classes.html#class-objects >>> It might help shed some light on how methods and instances work. >>> >>> One other thing. I'm a little confused by the first line of >>> dcObject.__init__: >>> >>> self.init_Pre() and self.init_Exec() >>> >>> I suspect this does not do what you think it does. init_Pre and init_Exec >>> will both be called by this expression (unless init_Pre throws an exception, >>> of course). You're not getting anything here that you wouldn't by just >>> calling each method on a separate line, except just making it harder to >>> read. >>> >> Read the doc-string for init_Pre() and for init_Exec(). The final >> version of init_Pre() will return False in some circumstances, and in >> those circumstances Simon doesn't want init_Exec() to be called. He's >> deliberately using the short-circuit evaluation of 'and' to accomplish >> that. >> >> >> >> >> >> >> >> >>> On Fri, Jul 31, 2009 at 8:53 PM, Simon wrote: >>> >>>> Hi >>>> >>>> So should the dcObject class include the "self" as well since I have >>>> not defined an __init__ method in dcCursor? >>>> >>>> Simon >>>> >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>>> >> Every one of those methods in both of those classes need a "self" first >> argument. As others have said, all instance methods need a 'self.' >> > > (Please don't top-post. You should put new responses at the end of quoted text, or sometimes inline if that's clearer.) I don't understand your comparison to Foxpro. read on. As your code was last posted, you don't need a return value from init_Exec() Every function that doesn't have an explicit return will return None. And None is interpreted as False in an "and" expression. If you had an "if" around the whole thing, then you'd care. DaveA From davea at ieee.org Sun Aug 2 06:00:28 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 02 Aug 2009 06:00:28 -0400 Subject: Help understanding the decisions *behind* python? In-Reply-To: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> Message-ID: <4A7563BC.2040406@ieee.org> sturlamolden wrote: > On 20 Jul, 18:27, Phillip B Oldham wrote: > > >> We're not looking to start any arguments or religious wars and we're >> not asking that python be changed into something its not. We'd simply >> like to understand the decision behind the lists and tuple structures. >> We feel that in not "getting" the difference between the two types we >> may be missing out on using these data structures to their full >> potential. >> > > A crude simplification would be: > > - A Python programmer will use a tuple where a C programmer will use a > struct. > > - Python and C programmers use lists and arrays similarly. > > Tuples are used for passing arguments to and from a function. Common > use of tuples include multiple return values and optional arguments > (*args). > > It has already been mentioned that tuples are immutable and can be > used as dictionary keys. > > > I think collections.namedtuple, introduced in Python 2.6, might help bridge the gap between a traditional tuple and a C struct. From __peter__ at web.de Sun Aug 2 06:33:03 2009 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Aug 2009 12:33:03 +0200 Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I would like to generate a new object each time I import a name from a > module, rather than getting the same object each time. For example, > currently I might do something like this: > > # Module > count = 0 > def factory(): > # Generate a unique object each time this is called > global count > count += 1 > return "Object #%d" % count > > > # Calling module > from Module import factory > a = factory() # a == "Object #1" > b = factory() # b == "Object #2" > del factory > > > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a # a == "Object #1" > from Module import factory() as b # b == "Object #2" > > except of course that syntax is illegal. How about >>> class A(object): ... def __init__(self): ... self._n = 0 ... @property ... def a(self): ... try: ... return self._n ... finally: ... self._n += 1 ... >>> import sys >>> sys.modules["yadda"] = A() >>> from yadda import a >>> from yadda import a as b >>> a, b (0, 1) Peter From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 06:49:33 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 10:49:33 GMT Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <02855ff5$0$20667$c3e8da3@news.astraweb.com> On Sun, 02 Aug 2009 12:33:03 +0200, Peter Otten wrote: > How about [snip] >>>> import sys >>>> sys.modules["yadda"] = A() Perfect! That's exactly the sort of thing I'm looking for. Thanks for everyone who answered. -- Steven From breamoreboy at yahoo.co.uk Sun Aug 2 07:04:25 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 02 Aug 2009 12:04:25 +0100 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7dl3pkF2cnqf5U1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> <7dks7jF2ccjstU1@mid.individual.net> <7dl3pkF2cnqf5U1@mid.individual.net> Message-ID: Michael M Mason wrote: > "Mark Lawrence" wrote in message > news:mailman.4130.1249203322.8015.python-list at python.org... >> Be careful, I'm screwed things up on several occasions by placing a >> file on PYTHONPATH that overrides a file in the standard library, >> test.py being my favourite! > > Thanks. Sure enough, I've already got my own test.py but I hadn't > discovered it was a problem yet... > Typical, tried to reproduce it and can't! Still at least you've been warned. -- Kindest regards. Mark Lawrence. From http Sun Aug 2 07:18:34 2009 From: http (Paul Rubin) Date: 02 Aug 2009 04:18:34 -0700 Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <7x63d631md.fsf@ruckus.brouhaha.com> Peter Otten <__peter__ at web.de> writes: > >>> import sys > >>> sys.modules["yadda"] = A() OMG.... wow. I bow to you. But I'm not sure whether that's bowing in awe or in terror. From marcusw at cox.net Sun Aug 2 08:08:34 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sun, 02 Aug 2009 08:08:34 -0400 Subject: Help understanding the decisions *behind* python? In-Reply-To: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> Message-ID: On 8/1/2009 9:31 PM, sturlamolden wrote: > - Python and C programmers use lists and arrays similarly. I'm guessing that's because of the brackets... Marcus From __peter__ at web.de Sun Aug 2 08:19:01 2009 From: __peter__ at web.de (Peter Otten) Date: Sun, 02 Aug 2009 14:19:01 +0200 Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> <7x63d631md.fsf@ruckus.brouhaha.com> Message-ID: wrote: KNode cannot parse your From-string correctly. Strange. > Peter Otten <__peter__ at web.de> writes: >> >>> import sys >> >>> sys.modules["yadda"] = A() > > OMG.... wow. I bow to you. But I'm not sure whether that's bowing in > awe or in terror. I don't know who invented it, but it's an old trick. It even made it into the standard library (email.LazyImporter). For the record: I don't recommend it. Peter From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 08:36:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 12:36:41 GMT Subject: Skipping a superclass Message-ID: <02857910$0$20667$c3e8da3@news.astraweb.com> I have a series of subclasses like this: class A(object): def method(self, *args): print "Lots of work gets done here in the base class" class B(A): def method(self, *args): print "A little bit of work gets done in B" super(B, self).method(*args) class C(B): def method(self, *args): print "A little bit of work gets done in C" super(C, self).method(*args) However, the work done in C.method() makes the work done in B.method() obsolete: I want one to run, or the other, but not both. C does need to inherit from B, for the sake of the other methods, so I want C.method() *only* to skip B while still inheriting from A. (All other methods have to inherit from B as normal.) So what I have done is change the call to super in C to super(B, self) instead of super(C, self). It seems to work, but is this safe to do? Or are there strange side-effects I haven't seen yet? -- Steven From clp2 at rebertia.com Sun Aug 2 09:02:10 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 Aug 2009 06:02:10 -0700 Subject: Skipping a superclass In-Reply-To: <02857910$0$20667$c3e8da3@news.astraweb.com> References: <02857910$0$20667$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0908020602u37fee362i35019d16b857f755@mail.gmail.com> On Sun, Aug 2, 2009 at 5:36 AM, Steven D'Aprano wrote: > I have a series of subclasses like this: > > class A(object): > ? ?def method(self, *args): > ? ? ? ?print "Lots of work gets done here in the base class" > > class B(A): > ? ?def method(self, *args): > ? ? ? ?print "A little bit of work gets done in B" > ? ? ? ?super(B, self).method(*args) > > class C(B): > ? ?def method(self, *args): > ? ? ? ?print "A little bit of work gets done in C" > ? ? ? ?super(C, self).method(*args) > > > However, the work done in C.method() makes the work done in B.method() > obsolete: I want one to run, or the other, but not both. C does need to > inherit from B, for the sake of the other methods, so I want C.method() > *only* to skip B while still inheriting from A. (All other methods have > to inherit from B as normal.) > > So what I have done is change the call to super in C to super(B, self) > instead of super(C, self). It seems to work, but is this safe to do? Or > are there strange side-effects I haven't seen yet? Barring some true weirdness in super(), I don't /think/ so. It obviously works fine in the single-inheritance case, and (after some brute-force testing) the only permitted multiple inheritances involving C and (A or B) always have C ahead of B in the MRO (method resolution order). The fact that you're wanting to bypass a superclass method might suggest however, that your hierarchy could be structured better. Have you considered moving B.method() into another, new class (e.g. newB) which subclasses B? Then C can inherit from B without inheriting the unwanted method, while B's functionality still exists, just under a new name (newB). Cheers, Chris -- http://blog.rebertia.com From lists at cheimes.de Sun Aug 2 09:08:25 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 02 Aug 2009 15:08:25 +0200 Subject: Newbie thwarted by sys.path on Vista In-Reply-To: <7djs50F2bsubuU1@mid.individual.net> References: <7djs50F2bsubuU1@mid.individual.net> Message-ID: Michael M Mason wrote: > I'm running Python 3.1 on Vista and I can't figure out how to add my own > directory to sys.path. > > The docs suggest that I can either add it to the PYTHONPATH environment > variable or to the PythonPath key in the registry. However, PYTHONPATH > doesn't exist, and updating the registry key has no effect (and in any case > the contents aren't the same as sys.path). > > So where does sys.path get its value from, and how do I change it? You can use my PEP 370 (http://python.org/dev/peps/pep-0370/) and a .pth file to extend the search path for modules. >>> import os >>> import site >>> site.USER_SITE '/home/heimes/.local/lib/python2.6/site-packages' >>> if not os.path.isdir(site.USER_SITE): ... os.makedirs(site.USER_SITE) ... >>> pth = open(os.path.join(site.USER_SITE, "michal.pth"), "w") >>> pth.write("C:/Users/Michael/Code/Python\n") >>> pth.close() Restart Python, your custom search path should be in sys.path. Christian From ifl2009 at shu.edu Sun Aug 2 09:34:37 2009 From: ifl2009 at shu.edu (IFL 2009) Date: Sun, 2 Aug 2009 09:34:37 -0400 Subject: IFL 2009: Call for Papers and Participation Message-ID: An HTML attachment was scrubbed... URL: From fatkinson at mishmash.com Sun Aug 2 09:42:52 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sun, 02 Aug 2009 06:42:52 -0700 Subject: Seeding the rand() Generator Message-ID: How does one seed the rand() generator when retrieving random recordings in MySQL? Regards, Fred From jizzai at gmail.com Sun Aug 2 09:50:14 2009 From: jizzai at gmail.com (Jizzai) Date: Sun, 02 Aug 2009 13:50:14 GMT Subject: Is python buffer overflow proof? Message-ID: Is a _pure_ python program buffer overflow proof? For example in C++ you can declare a char[9] to hold user input. If the user inputs 10+ chars a buffer overflow occurs. In python, I cannot seem to find a way to define/restrict a string length. This is probably by design and raises the topic in question. Am curious to see the opinions of people who know. TIA. From albert at spenarnc.xs4all.nl Sun Aug 2 09:54:04 2009 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 02 Aug 2009 13:54:04 GMT Subject: Colour of output text References: <03c4ceed-c49b-4dd0-a585-e6169b02e0eb@26g2000yqk.googlegroups.com> Message-ID: In article , Jean-Michel Pichavant wrote: >Nobody wrote: >> On Fri, 10 Jul 2009 09:23:54 +0000, garabik-news-2005-05 wrote: >> >> >>>>> I would like to learn a way of changing the colour of a particular >>>>> part of the output text. I've tried the following >>>>> >>>> On Unix operating systems this would be done through the curses interface: >>>> >>>> http://docs.python.org/library/curses.html >>>> >>> Or using ANSI colour codes: >>> >>> colours = { >>> 'none' : "", >>> 'default' : "\033[0m", >>> 'bold' : "\033[1m", >>> >> >> [snip] >> >> >>> # non-standard attributes, supported by some terminals >>> >> >> This comment should have appeared immediately after "none" ;) >> >> Hard-coding control/escape sequences is just lame. Use the curses modules >> to obtain the correct sequences for the terminal. >> >> >As the OP I'm really interested in doing so. I currently have all my >colors hard-coded. >Now It may be lame but as soon as I call curses.initscr(), it's just >messing up with my terminal, moreover I didn't figure out how to "print >'hello'" using curses color codes. >Anyone has an example ? I'm pretty sure it may fit in one line. In general initscr() ought to work. It fails if it has no/a wrong idea of what your terminal is. In the same shell as you run run your program type set | grep -i term Now some entry should show up, e.g. TERM=xterm infocmp $TERM should fetch information about your terminal, from the same source as curses does. Possible problems are: - your operating system/configurations lies to curses about the terminal or your terminal is not specified at all - curses has not been properly installed and cannot find the database Groetjes Albert > >JM > > -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From lob8682 at gmail.com Sun Aug 2 09:58:47 2009 From: lob8682 at gmail.com (Kamal Kamal) Date: Sun, 2 Aug 2009 06:58:47 -0700 (PDT) Subject: "PAK WEB" "PAK WEB TV" "PAK WEBSITES" "PAK WEB DIRECTORY" "PAK WEB HOSTING" "PAK WEB HOST" "PAK WEB HOSTING" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" on www.pak-web-pages.blogspot.com Message-ID: "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB TV" www.pak-web-pages.blogspot.com "PAK WEBSITES" www.pak-web-pages.blogspot.com "PAK WEB DIRECTORY" www.pak-web-pages.blogspot.com "PAK WEB HOSTING" www.pak-web-pages.blogspot.com "PAK WEB HOST" www.pak-web-pages.blogspot.com "PAK WEB HOSTING" www.pak-web-pages.blogspot.com "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" "PAK WEB" "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" on www.pak-web-pages.blogspot.com From albert at spenarnc.xs4all.nl Sun Aug 2 10:14:53 2009 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 02 Aug 2009 14:14:53 GMT Subject: A Bug By Any Other Name ... References: Message-ID: In article , J. Cliff Dyer wrote: >On Fri, 2009-07-17 at 20:53 +0000, Albert van der Horst wrote: >> Because unlike in algol 68 in python whitespace is relevant, >> we could get by with requiring whitespace: >> x= -q # okay >> a> 8 ** -2 # okay > >This is actually quite thoroughly untrue. In python, *indentation* is >significant. Whitespace (internal to a line) is not. You can even call >methods like this if you want: You totally don't get it. You describe how python is now. I propose a change to be made to python. Small wonder that that is different from what it is now. > >>>> s = 'abc' >>>> s . upper() >ABC You prove nothing by giving examples. You can disprove by giving one counter example, here it goes. Whitespace (internal to a line) is significant. In Python you cannot change xleftgoing = 123000000 to x left going = 123 000 000 (You can in Algol68) >Obviously, that's A Bad Idea(tm), but python's parser won't stop you. What is a bad idea? Apparently you are not talking about my idea of changing the parser. ("Pythons parser won't stop you from changing the parser" doesn't make sense.) >The ++ operator gotcha is so minor that I can't remember anyone actually >asking about it on the list (who was actually facing it as a >problem--this thread was started by idle speculation). Can we not >change the language syntax to address non-issues? As other languages have an Eleventh Commandment against concatenating operators, the larger issue is hardly futile. > >Practicality beats purity, a.k.a. don't you have something better to do? I'm having a great time, thank you! >Cheers, >Cliff Groetjes Albert -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From marcusw at cox.net Sun Aug 2 10:32:39 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sun, 02 Aug 2009 10:32:39 -0400 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: On 8/2/2009 9:50 AM, Jizzai wrote: > Is a _pure_ python program buffer overflow proof? > > For example in C++ you can declare a char[9] to hold user input. > If the user inputs 10+ chars a buffer overflow occurs. > > In python, I cannot seem to find a way to define/restrict a string length. > This is probably by design and raises the topic in question. > > Am curious to see the opinions of people who know. > > TIA. I believe that python is buffer overflow proof. In fact, I think that even ctypes is overflow proof... Marcus From marcusw at cox.net Sun Aug 2 10:36:18 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sun, 02 Aug 2009 10:36:18 -0400 Subject: Seeding the rand() Generator In-Reply-To: References: Message-ID: On 8/2/2009 9:42 AM, Fred Atkinson wrote: > How does one seed the rand() generator when retrieving random > recordings in MySQL? > > Regards, > > > > Fred something like: import random, time random.seed(time.time()) #not actual record access code: sqlite3.recordaccessfuction(recordid = random.rand()) Marcus From lists at cheimes.de Sun Aug 2 10:43:25 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 02 Aug 2009 16:43:25 +0200 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: Marcus Wanner wrote: > I believe that python is buffer overflow proof. In fact, I think that > even ctypes is overflow proof... No, ctypes isn't buffer overflow proof. ctypes can break and crash a Python interpreter easily. Christian From matt.urry at googlemail.com Sun Aug 2 10:45:39 2009 From: matt.urry at googlemail.com (ma3mju) Date: Sun, 2 Aug 2009 07:45:39 -0700 (PDT) Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> Message-ID: <206a63e2-9159-44f0-ac5c-a14055448b47@h21g2000yqa.googlegroups.com> On 31 July, 11:27, Piet van Oostrum wrote: > >>>>> ma3mju (m) wrote: > >m> Hi all, > >m> I'm having trouble with multiprocessing I'm using it to speed up some > >m> simulations, I find for large queues when the process reaches the > >m> poison pill it does not exit whereas for smaller queues it works > >m> without any problems. Has anyone else had this trouble? Can anyone > >m> tell me a way around it? The code is in two files below. > > How do you know it doesn't exit. You haven't shown any of your output. > > I did discover a problem in your code, but it should cause an exception: > > >m> #set off some of the easy workers on the hard work (maybe double > >m> number of hard) > >m> for i in range(0,num_hard_workers): > >m> ? ? hard_work_queue.put(None) > >m> ? ? hard_workers.append(multiprocessing.Process > >m> (target=GP.RandomWalkGeneralizationErrorParallel,args= > >m> (hard_work_queue,result_queue,))) > >m> #wait for all hard workers to finish > >m> for worker in hard_workers: > >m> ? ? worker.join() > > Here you create new hard workers, but you never start them. The join > should then give an exception when it reaches these. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org Ok thanks I'll change that In a sec, It never reaches that bit of code because the easy_workers don't exit so it never gets past the join(). As far as running it goes I get the datapt and number of points printed to the list for everything in both queues. When it reaches the end of either queue I get "Poison" on the screen then "here" for each process but I don't get "worker joined" and as expected don't get "this should not appear". If I have a look at the processes running after all queues are supposed to have finished I see all of them running taking little or no resources. This is running on Ubuntu Jaunty at home and the same happens on the Debian machine at uni. The weird thing is that if I run them with less points the processes do manage to exit. Thanks Matt From matt.urry at googlemail.com Sun Aug 2 10:48:44 2009 From: matt.urry at googlemail.com (ma3mju) Date: Sun, 2 Aug 2009 07:48:44 -0700 (PDT) Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> Message-ID: <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> On 31 July, 11:34, MRAB wrote: > ma3mju wrote: > > Hi all, > > > I'm having trouble with multiprocessing I'm using it to speed up some > > simulations, I find for large queues when the process reaches the > > poison pill it does not exit whereas for smaller queues it works > > without any problems. Has anyone else had this trouble? Can anyone > > tell me a way around it? The code is in two files below. > > [snip] > > > #get number of cores and set the number on concurrent processes > > num_hard_workers = 2 > > num_workers = multiprocessing.cpu_count()*1.5 > > easy_workers = [] > > hard_workers = [] > > #add poison pill for each worker and create the worker > > for i in range(0,num_workers-num_hard_workers): > > ? ? easy_work_queue.put(None) > > ? ? easy_workers.append(multiprocessing.Process > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > (easy_work_queue,result_queue,))) > > for i in range(0,num_hard_workers): > > ? ? hard_work_queue.put(None) > > ? ? hard_workers.append(multiprocessing.Process > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > (hard_work_queue,result_queue,))) > > You have 2 hard workers and ceil(CPU_count * 1.5) - 2 easy workers. > What if the number of CPUs was 1? That would give 2 hard and 0 easy! > > Also, I recommend that you put only 1 'poison pill' in each queue and > have the workers put it back when they see it. I'll give that a go in a sec and see if it helps. The processes quit out for smaller queues though so it should in theory be alright. I'm not too fussed about the CPU's it's only there because I change between a uni PC and home one with a different number of cores in each but both greater than one. From Scott.Daniels at Acm.Org Sun Aug 2 11:11:22 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 02 Aug 2009 08:11:22 -0700 Subject: Predefined Variables In-Reply-To: References: Message-ID: Piet van Oostrum wrote: >>>>>> Scott David Daniels (SDD) wrote: >> SDD> Stephen Cuppett (should have written in this order): >>>> "Fred Atkinson" wrote ... >>>>> Is there a pre-defined variable that returns the GET line... >>>> os.environment('QUERY_STRING') >> SDD> Maybe you mean: >> SDD> os.environ['USER'] > Let's take the best of both: > os.environ['QUERY_STRING'] Sorry about that. I was testing expression before posting, and I don't do that much cgi stuff. I forgot to restore the variable name. --Scott David Daniels Scott.Daniels at Acm.Org From steve at REMOVE-THIS-cybersource.com.au Sun Aug 2 11:18:27 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 02 Aug 2009 15:18:27 GMT Subject: Is python buffer overflow proof? References: Message-ID: <02859ef9$0$20667$c3e8da3@news.astraweb.com> On Sun, 02 Aug 2009 13:50:14 +0000, Jizzai wrote: > Is a _pure_ python program buffer overflow proof? It's supposed to be. > For example in C++ you can declare a char[9] to hold user input. If the > user inputs 10+ chars a buffer overflow occurs. > > In python, I cannot seem to find a way to define/restrict a string > length. This is probably by design and raises the topic in question. That's a separate issue from being buffer overflow proof. You can't specify that a string have a maximum of N characters except by slicing the string after it's formed: s = "x"*10000 # Make a big string. s = s[:100] # Limit it to 100 characters. But Python won't overflow any buffers even if you try to create a truly huge string: s = "x"*(1024**4) # Try to create a 1 TB string. Your PC will run slow while Python and the OS tries to allocate 1TB of memory, then it will safely raise MemoryError. Pure Python should never dump core. -- Steven From Scott.Daniels at Acm.Org Sun Aug 2 11:53:50 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 02 Aug 2009 08:53:50 -0700 Subject: Seeding the rand() Generator In-Reply-To: References: Message-ID: Fred Atkinson wrote: > How does one seed the rand() generator when retrieving random > recordings in MySQL? It is not entirely clear what you are asking. If you are talking about MySQL's random number generator, you are talking in the wrong newsgroup. If you are talking about Python's, does this work? import random random.seed(123542552) I'm not quite sure how you came to believe that Python controls MySQL, as opposed to using its services. --Scott David Daniels Scott.Daniels at Acm.Org From matt.urry at googlemail.com Sun Aug 2 12:57:44 2009 From: matt.urry at googlemail.com (ma3mju) Date: Sun, 2 Aug 2009 09:57:44 -0700 (PDT) Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> Message-ID: <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> On 2 Aug, 15:48, ma3mju wrote: > On 31 July, 11:34, MRAB wrote: > > > > > ma3mju wrote: > > > Hi all, > > > > I'm having trouble with multiprocessing I'm using it to speed up some > > > simulations, I find for large queues when the process reaches the > > > poison pill it does not exit whereas for smaller queues it works > > > without any problems. Has anyone else had this trouble? Can anyone > > > tell me a way around it? The code is in two files below. > > > [snip] > > > > #get number of cores and set the number on concurrent processes > > > num_hard_workers = 2 > > > num_workers = multiprocessing.cpu_count()*1.5 > > > easy_workers = [] > > > hard_workers = [] > > > #add poison pill for each worker and create the worker > > > for i in range(0,num_workers-num_hard_workers): > > > ? ? easy_work_queue.put(None) > > > ? ? easy_workers.append(multiprocessing.Process > > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > > (easy_work_queue,result_queue,))) > > > for i in range(0,num_hard_workers): > > > ? ? hard_work_queue.put(None) > > > ? ? hard_workers.append(multiprocessing.Process > > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > > (hard_work_queue,result_queue,))) > > > You have 2 hard workers and ceil(CPU_count * 1.5) - 2 easy workers. > > What if the number of CPUs was 1? That would give 2 hard and 0 easy! > > > Also, I recommend that you put only 1 'poison pill' in each queue and > > have the workers put it back when they see it. > > I'll give that a go in a sec and see if it helps. The processes quit > out for smaller queues though so it should in theory be alright. I'm > not too fussed about the CPU's it's only there because I change > between a uni PC and home one with a different number of cores in each > but both greater than one. Just tried changing the poison pill part to no avail sadly From tjreedy at udel.edu Sun Aug 2 14:07:44 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 02 Aug 2009 14:07:44 -0400 Subject: Generate a new object each time a name is imported In-Reply-To: References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: Peter Otten wrote: > Steven D'Aprano wrote: >> I'm looking for a way to hide the generation of objects from the caller, >> so I could do something like this: >> >> from Module import factory() as a # a == "Object #1" >> from Module import factory() as b # b == "Object #2" >> >> except of course that syntax is illegal. > > How about For newbies who do not get how the following works, but would like to know, I am adding some explanation. >>>> class A(object): > ... def __init__(self): > ... self._n = 0 > ... @property > ... def a(self): > ... try: > ... return self._n > ... finally: > ... self._n += 1 The @property decorator turns the 'a' function into the hidden getter function for what looks to the outside world like a simple instance attribute named 'a'. >>>> import sys >>>> sys.modules["yadda"] = A() sys.modules is a system namespace that normally associates names with modules. It is used by import statements to find existing modules. However, there is no requirement that the associated object actually be a module. A module is simply a collection of objects accessed as attributes. One can get and set attributes of a module, and but hardly anyhing else. Other attribute collection objects will do as well as far as imports are concerned. 'If it quack like a duck (module in this case)...' The above sets the 'module' to an *instance* of class A. >>>> from yadda import a This looks for the 'module' named 'yadda'. It finds one - the instance of A. It then requests attribute 'a' (of that instance). That request is routed to the getter function. This import statement could be in any module, not just the one that set A() as a module surrogate. >>>> from yadda import a as b >>>> a, b > (0, 1) As Peter mentioned in his followup, module surrogates were intended for lazy imports of expensive-to-compute attributes that might never be needed, so their creation could be delayed to whenever needed, if ever. Tricks like the above are not recommended for normal usage, but do illstrate some aspects of the language. Terry Jan Reedy From catalinfest at gmail.com Sun Aug 2 14:13:13 2009 From: catalinfest at gmail.com (catafest) Date: Sun, 2 Aug 2009 11:13:13 -0700 (PDT) Subject: How to read webpage References: Message-ID: <44c17767-e08e-4c8c-ae1f-0e11e54d3485@o6g2000yqj.googlegroups.com> Maybe your python2.5 not working good!? But, I use python 2.6 , and i use this for your problem: import urllib html = urllib.urlopen("http://www.rediff.com/").read() print html If you want use authenticate then... You make working urllib2 and use this >>>auth = urllib2.Request(auth_uri, authreq_data) On Aug 1, 4:52?pm, MRAB wrote: > tarun wrote: > > Dear All, > > I want to read a webpage and copy the contents of it in word file. I > > tried to write following code: > > > import urllib2 > > urllib2.urlopen("http://www.rediff.com/") > > > *Error:-* > > > ? ? urllib2.urlopen("http://www.icicibank.com/") > > ? File "C:\Python25\lib\urllib2.py", line 121, in urlopen > > ? ? return _opener.open(url, data) > > ? File "C:\Python25\lib\urllib2.py", line 374, in open > > ? ? response = self._open(req, data) > > ? File "C:\Python25\lib\urllib2.py", line 392, in _open > > ? ? '_open', req) > > ? File "C:\Python25\lib\urllib2.py", line 353, in _call_chain > > ? ? result = func(*args) > > ? File "C:\Python25\lib\urllib2.py", line 1100, in http_open > > ? ? return self.do_open(httplib.HTTPConnection, req) > > ? File "C:\Python25\lib\urllib2.py", line 1075, in do_open > > ? ? raise URLError(err) > > urllib2.URLError: > > I've just tried it. I didn't get an exception, so your problem must be > elsewhere. From python at mrabarnett.plus.com Sun Aug 2 14:25:36 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 02 Aug 2009 19:25:36 +0100 Subject: Processes not exiting In-Reply-To: <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> Message-ID: <4A75DA20.7050209@mrabarnett.plus.com> ma3mju wrote: > On 2 Aug, 15:48, ma3mju wrote: >> On 31 July, 11:34, MRAB wrote: >> >> >> >>> ma3mju wrote: >>>> Hi all, >>>> I'm having trouble with multiprocessing I'm using it to speed up some >>>> simulations, I find for large queues when the process reaches the >>>> poison pill it does not exit whereas for smaller queues it works >>>> without any problems. Has anyone else had this trouble? Can anyone >>>> tell me a way around it? The code is in two files below. >>> [snip] >>>> #get number of cores and set the number on concurrent processes >>>> num_hard_workers = 2 >>>> num_workers = multiprocessing.cpu_count()*1.5 >>>> easy_workers = [] >>>> hard_workers = [] >>>> #add poison pill for each worker and create the worker >>>> for i in range(0,num_workers-num_hard_workers): >>>> easy_work_queue.put(None) >>>> easy_workers.append(multiprocessing.Process >>>> (target=GP.RandomWalkGeneralizationErrorParallel,args= >>>> (easy_work_queue,result_queue,))) >>>> for i in range(0,num_hard_workers): >>>> hard_work_queue.put(None) >>>> hard_workers.append(multiprocessing.Process >>>> (target=GP.RandomWalkGeneralizationErrorParallel,args= >>>> (hard_work_queue,result_queue,))) >>> You have 2 hard workers and ceil(CPU_count * 1.5) - 2 easy workers. >>> What if the number of CPUs was 1? That would give 2 hard and 0 easy! >>> Also, I recommend that you put only 1 'poison pill' in each queue and >>> have the workers put it back when they see it. >> I'll give that a go in a sec and see if it helps. The processes quit >> out for smaller queues though so it should in theory be alright. I'm >> not too fussed about the CPU's it's only there because I change >> between a uni PC and home one with a different number of cores in each >> but both greater than one. > > Just tried changing the poison pill part to no avail sadly I wonder whether one of the workers is raising an exception, perhaps due to lack of memory, when there are large number of jobs to process. Another question: why are you distinguishing between easy and hard jobs? Do you actually get a measurable improvement in performance from doing it this way instead of having just a single queue of jobs and a single pool of workers? From piet at cs.uu.nl Sun Aug 2 14:26:55 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 20:26:55 +0200 Subject: Get Cliet IP Address References: Message-ID: >>>>> Fred Atkinson (FA) wrote: >FA> What is the function to obtain the client browser's IP >FA> address? You mean in a web server? The following should work (and was posted by me not long ago): from os import getenv ip = (getenv("HTTP_CLIENT_IP") or getenv("HTTP_X_FORWARDED_FOR") or getenv("HTTP_X_FORWARDED_FOR") or getenv("REMOTE_ADDR") or "UNKNOWN") I use getenv() rather than environ[] to avoid exceptions. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From piet at cs.uu.nl Sun Aug 2 14:31:07 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 20:31:07 +0200 Subject: cgi script References: Message-ID: >>>>> golu (g) wrote: >g> Hi, >g> i started learning cgi few days ago in python and everything went >g> fine until i started getting the follwing error >g> " >g> The server encountered an internal error and was unable to complete >g> your request. Either the server is overloaded or there was an error in >g> a CGI script. >g> If you think this is a server error, please contact the webmaster. " >g> i am using apache on xampp. plz help Putting the following in your script might help as it will show the exception trace in your browser (if it gets that far, that is). import cgitb cgitb.enable() -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From REMpeteOVE at petezilla.co.uk Sun Aug 2 15:21:06 2009 From: REMpeteOVE at petezilla.co.uk (Peter Chant) Date: Sun, 02 Aug 2009 20:21:06 +0100 Subject: Building / making an application Message-ID: <2i5hk6-8gh.ln1@phoenix.fire> What is a good way to do this? There are instructions on making modules at: http://docs.python.org/distutils/setupscript.html however, what do you do if you don't want a module? I'm thinking of where I'd like to split the code into several files and have a build / setup script put it together and install it somewhere such as /usr/local/bin. I'm interested in what the standard way of doing this is. Thanks, Pete -- http://www.petezilla.co.uk From piet at cs.uu.nl Sun Aug 2 15:25:02 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 21:25:02 +0200 Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> <8bede581-f260-4c69-abf0-1e8071380b76@z4g2000prh.googlegroups.com> <7e6cdc26-bcc0-4503-b7b4-9ad80b1041f6@v37g2000prg.googlegroups.com> Message-ID: >>>>> NighterNet (N) wrote: >N> Here the full code. >N> flashpolicy.xml >N> [[[ >N> >N> >N> >N> >N> ]]] >N> flashpolicytest_server3x.py >N> [[[ >N> #!/usr/local/bin/python >N> ''' >N> Still under testing... >N> python version 3.x.x >N> ''' >N> import socket >N> import threading >N> import sys >N> import os >N> file_name = 'flashpolicy.xml' >N> fh = open(file_name, "r") >N> policy = fh.read(10001) You never use that variable. >N> host = ''; #out side network >N> port = 5555; >N> print ("# ------------- Init... ------------- #"); >N> class ClientThread (threading.Thread): >N> global policy; >N> allClients = []; >N> vlock = threading.Lock(); >N> id = 0 # next available thread number >N> def __init__(self,clientSocket): >N> threading.Thread.__init__(self) >N> self.sockfd = clientSocket; #socket client >N> self.name = ''; >N> ClientThread.id += 1 >N> self.id = ClientThread.id >N> self.nickName = ''; >N> self.allClients.append(self.sockfd); >N> def sendAll(self,buff): >N> for index,clientSock in enumerate(self.allClients): >N> try: >N> clientSock.send(buff); There is no guarantee that send will indeed transmit all of buff. It is better to use clientSock.sendall(buff). Or you should check the return value of send and check if it is equal to the length of buff. And repeat if not. (But sendall is easier). Also don't use ; at the end of the statement. It's not pythonic. >N> except (socket.error): >N> print ('error socket %s\n',index,"| clean"); >N> clientSock.close() >N> del self.allClients[index] >N> def run(self): >N> while True: >N> buff = self.sockfd.recv(1028); There is no guarantee that recv will get the whole message. It may even get as little as 1 byte. So you should check the return value of recv. The official way is to keep reading until you have enough input or until you hit end of file. >N> if not buff: >N> print ("connect close...(client side)"); >N> self.sockfd.close(); >N> break #incase it loop infinite >N> if str(buff) == str("b\'\\x00\'"): What you check here is whether buff contains the byte sequence that starts with a b, then a ' ... and ending with the 5 bytes \ x 0 0 ' which is wrong. Actually it should be: if buff == b\'\x00': or if buff == b\'\0': >N> print ('policy FOUND >>> sending...') >N> print(buff) >N> b = b'N> from domain=\"*\" to-ports=\"*\" />' >N> print (b) >N> self.sockfd.send(b); >N> self.sockfd.sendall(b); Only self.sockfd.sendall; delete the line with self.sockfd.send(b). And remove the semicolons for esthetical reasons. >N> Some odd reason I can't send flash policy from python to flash socket >N> to agrees with the connection. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From hackingkk at gmail.com Sun Aug 2 15:32:10 2009 From: hackingkk at gmail.com (Krishnakant) Date: Mon, 03 Aug 2009 01:02:10 +0530 Subject: Building / making an application In-Reply-To: <2i5hk6-8gh.ln1@phoenix.fire> References: <2i5hk6-8gh.ln1@phoenix.fire> Message-ID: <1249241530.4541.12.camel@krishna-laptop> On Sun, 2009-08-02 at 20:21 +0100, Peter Chant wrote: > What is a good way to do this? There are instructions on making modules at: > > http://docs.python.org/distutils/setupscript.html > > however, what do you do if you don't want a module? I'm thinking of where > I'd like to split the code into several files and have a build / setup > script put it together and install it somewhere such as /usr/local/bin. > I'm interested in what the standard way of doing this is. > Have you considered creating a deb or rpm package for your application? Most of the documentation for deb or rpm will talk about make files. But even a distutil based python package (with a setup.py) can be made into a deb package. Then the your requirement will be satisfied at least for most gnu/linux based distros. happy hacking. Krishnakant. From REMpeteOVE at petezilla.co.uk Sun Aug 2 16:00:15 2009 From: REMpeteOVE at petezilla.co.uk (Peter Chant) Date: Sun, 02 Aug 2009 21:00:15 +0100 Subject: Building / making an application References: <2i5hk6-8gh.ln1@phoenix.fire> Message-ID: Krishnakant wrote: > Have you considered creating a deb or rpm package for your application? > Most of the documentation for deb or rpm will talk about make files. > But even a distutil based python package (with a setup.py) can be made > into a deb package. > Then the your requirement will be satisfied at least for most gnu/linux > based distros. I'm a slacker, so what I would do would be to make a slack build, the slackbuild would take the source and build that. The stage I am at is the "how to build the source" stage. Don't really intend to get as far as distribution specific packages. What I could do is create a script in the source root directory (that sounds a bit overblown) that simply concatenates together all the python files in the right order and perhaps copies the result to /usr/local/bin or /usr/bin as appropriate. Is that the right way to go? It looks like distutils is appropriate only for modules. OTOH it might be appropriate to put the bulk of an application in a module and have a function calling it the only part of the main script. Pete -- http://www.petezilla.co.uk From deets at nospam.web.de Sun Aug 2 16:08:00 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 02 Aug 2009 22:08:00 +0200 Subject: Building / making an application In-Reply-To: References: <2i5hk6-8gh.ln1@phoenix.fire> Message-ID: <7dma10F2cd7tnU1@mid.uni-berlin.de> Peter Chant schrieb: > Krishnakant wrote: > > >> Have you considered creating a deb or rpm package for your application? >> Most of the documentation for deb or rpm will talk about make files. >> But even a distutil based python package (with a setup.py) can be made >> into a deb package. >> Then the your requirement will be satisfied at least for most gnu/linux >> based distros. > > I'm a slacker, so what I would do would be to make a slack build, the > slackbuild would take the source and build that. The stage I am at is > the "how to build the source" stage. Don't really intend to get as far as > distribution specific packages. > > What I could do is create a script in the source root directory (that sounds > a bit overblown) that simply concatenates together all the python files in > the right order and perhaps copies the result to /usr/local/bin or /usr/bin > as appropriate. Is that the right way to go? It looks like distutils is > appropriate only for modules. > > OTOH it might be appropriate to put the bulk of an application in a module > and have a function calling it the only part of the main script. You should consider using setuptools. Then you get an egg that people can install, and you can define "console_scripts"-entry-points which will be installed into /usr/local/bin or similar locations. Diez From aahz at pythoncraft.com Sun Aug 2 16:15:00 2009 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2009 13:15:00 -0700 Subject: Help with Regex for domain names References: <0422bf8f-ce59-4de2-a1a4-b16a32e5f152@o15g2000yqm.googlegroups.com> Message-ID: In article , MRAB wrote: >Nobody wrote: >> On Thu, 30 Jul 2009 10:29:09 -0700, rurpy wrote: >> >>>> regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)') >>> You might also want to consider that some country >>> codes such as "co" for Columbia might match more than >>> you want, for example: >>> >>> re.match(r'[\w\-\.]+\.(?:us|au|de|co)', 'foo.boo.com') >>> >>> will match. >> >> ... so put \b at the end, i.e.: >> >> regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)\b') >> >It would still match "www.bbc.co.uk", so you might need: > >regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)\b(?!\.\b)') If it's a string containing just the candidate domain, you can do regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)$') -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Many customs in this life persist because they ease friction and promote productivity as a result of universal agreement, and whether they are precisely the optimal choices is much less important." --Henry Spencer From piet at cs.uu.nl Sun Aug 2 16:49:05 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sun, 02 Aug 2009 22:49:05 +0200 Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> Message-ID: >>>>> MRAB (M) wrote: >M> I wonder whether one of the workers is raising an exception, perhaps due >M> to lack of memory, when there are large number of jobs to process. But that wouldn't prevent the join. And you would probably get an exception traceback printed. I wonder if something fishy is happening in the multiprocessing infrastructure. Or maybe the Fortran code goes wrong because it has no protection against buffer overruns and similar problems, I think. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From fatkinson at mishmash.com Sun Aug 2 17:18:28 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sun, 02 Aug 2009 14:18:28 -0700 Subject: Seeding the rand() Generator References: Message-ID: On Sun, 02 Aug 2009 08:53:50 -0700, Scott David Daniels wrote: >Fred Atkinson wrote: >> How does one seed the rand() generator when retrieving random >> recordings in MySQL? > >It is not entirely clear what you are asking. If you are talking about >MySQL's random number generator, you are talking in the wrong newsgroup. >If you are talking about Python's, does this work? > import random > random.seed(123542552) >I'm not quite sure how you came to believe that Python controls MySQL, >as opposed to using its services. > >--Scott David Daniels >Scott.Daniels at Acm.Org I am coding in Python. I am accessing a MySQL database. I have a string to instruct the MySQL database to use the 'rand()' function to randomly choose one of the records in the database. I know how to seed it in PHP. Does anyone know how to see it from with Python? Regards, Fred From fatkinson at mishmash.com Sun Aug 2 17:20:02 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Sun, 02 Aug 2009 14:20:02 -0700 Subject: Predefined Variables References: Message-ID: On Sun, 02 Aug 2009 08:11:22 -0700, Scott David Daniels wrote: >Piet van Oostrum wrote: >>>>>>> Scott David Daniels (SDD) wrote: >>> SDD> Stephen Cuppett (should have written in this order): >>>>> "Fred Atkinson" wrote ... >>>>>> Is there a pre-defined variable that returns the GET line... >>>>> os.environment('QUERY_STRING') >>> SDD> Maybe you mean: >>> SDD> os.environ['USER'] >> Let's take the best of both: >> os.environ['QUERY_STRING'] > >Sorry about that. I was testing expression before posting, and I don't >do that much cgi stuff. I forgot to restore the variable name. > >--Scott David Daniels >Scott.Daniels at Acm.Org I finally got it to work with x =getenv('QUERY_STRING') Regards, Fred From victorsubervi at gmail.com Sun Aug 2 17:22:20 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 2 Aug 2009 16:22:20 -0500 Subject: RE Question Message-ID: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> Hi; How do I search and replace something like this: aLine = re.sub('[<]?[p]?[>]?[<]?[b]?[>]?', '', aLine) where RE *only* looks for the possibility of "

" at the beginning of the string; that is, not the individual components as I have it coded above, but the entire 3-character block? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcusw at cox.net Sun Aug 2 17:51:11 2009 From: marcusw at cox.net (Marcus Wanner) Date: Sun, 02 Aug 2009 17:51:11 -0400 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: On 8/2/2009 10:43 AM, Christian Heimes wrote: > Marcus Wanner wrote: >> I believe that python is buffer overflow proof. In fact, I think that >> even ctypes is overflow proof... > > No, ctypes isn't buffer overflow proof. ctypes can break and crash a > Python interpreter easily. > > Christian > I see. I thought that it said "invalid array index" when you try to read/write outside of an array's bounds, though... Marcus From REMpeteOVE at petezilla.co.uk Sun Aug 2 18:26:08 2009 From: REMpeteOVE at petezilla.co.uk (Peter Chant) Date: Sun, 02 Aug 2009 23:26:08 +0100 Subject: Building / making an application References: <2i5hk6-8gh.ln1@phoenix.fire> <7dma10F2cd7tnU1@mid.uni-berlin.de> Message-ID: <0dghk6-12j.ln1@phoenix.fire> Diez B. Roggisch wrote: > You should consider using setuptools. Then you get an egg that people > can install, and you can define "console_scripts"-entry-points which > will be installed into /usr/local/bin or similar locations. Interesting, I think I need to have a play with that. The cross platform bit could be useful as well. Pete -- http://www.petezilla.co.uk From missive at hotmail.com Sun Aug 2 18:27:49 2009 From: missive at hotmail.com (Lee Harr) Date: Mon, 3 Aug 2009 02:57:49 +0430 Subject: [ANNC] pybotwar-0.3 Message-ID: pybotwar is a fun and educational game where players create computer programs to control simulated robots to compete in a battle arena. http://pybotwar.googlecode.com/ pybotwar uses pybox2d for the physical simulation, and uses pygame and pygsear for the visualization. pybotwar is released under GPLv3. Changes in pybotwar-0.3: - make tarball extract in to versioned directory _________________________________________________________________ With Windows Live, you can organize, edit, and share your photos. http://www.microsoft.com/middleeast/windows/windowslive/products/photo-gallery-edit.aspx From suruti94 at gmail.com Sun Aug 2 19:22:45 2009 From: suruti94 at gmail.com (Mohan Parthasarathy) Date: Sun, 2 Aug 2009 16:22:45 -0700 Subject: Python docs disappointing In-Reply-To: References: Message-ID: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> I am a newbie and about a month old with Python. There is a wealth of material about Python and I am really enjoying learning Python. One thing that could have helped Python documentation is that instead of the very "raw" doc string, it could have used something like PythonDoc (java doc style) so that the functions/classes are documented better. At least I am planning to use PythonDoc for the code that I am going to write. Let me know if there is a better one.. -mohan On Fri, Jul 31, 2009 at 1:10 PM, kj wrote: > > > > I'm pretty new to Python, and I like a lot overall, but I find the > documentation for Python rather poor, overall. > > I'm sure that Python experts don't have this problem: they have > internalized some good ways to access the documentation, are > productive with it, and therefore have lost the ability to see why > the Python documentations is deficient for beginners. This explains > why a suboptimal situation can persist like this: those who are > most able fix it are also the least able to perceive it. > > I've heard similar complaints from other experienced programmers > who are trying out Python for the first time: poor documentation. > > Here is an *entirely typical* example: on some Unix, try > > % pydoc urllib > > The displayed documentation mention the optional parameter "data" > in practically every function listed (a few dozen of them). This > parameter is not documented *anywhere* on that page. All that we > are told is that its default value is always None. > > I'm sure that I can find a full description of this parameter if > I fire up Google, and search online. In fact, more likely than > not, I'll find far more documentation than I want. But my point > is that a programmer should not need to do this. The full > documentation should be readily accessible directly through a few > keystrokes. > > I would love to know how experienced Python programmers quickly > zero in on the Python documentation they need. > > TIA! > > kynn > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Aug 2 19:40:20 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 2 Aug 2009 16:40:20 -0700 Subject: Python docs disappointing In-Reply-To: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> References: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> Message-ID: <50697b2c0908021640o38f1de9fnd778da4d985c4672@mail.gmail.com> > On Fri, Jul 31, 2009 at 1:10 PM, kj wrote: >> I'm pretty new to Python, and I like a lot overall, but I find the >> documentation for Python rather poor, overall. >> >> I'm sure that Python experts don't have this problem: they have >> internalized some good ways to access the documentation, are >> productive with it, and therefore have lost the ability to see why >> the Python documentations is deficient for beginners. ?This explains >> why a suboptimal situation can persist like this: those who are >> most able fix it are also the least able to perceive it. >> >> I've heard similar complaints from other experienced programmers >> who are trying out Python for the first time: poor documentation. >> >> Here is an *entirely typical* example: on some Unix, try >> >> % pydoc urllib >> >> The displayed documentation mention the optional parameter "data" >> in practically every function listed (a few dozen of them). ?This >> parameter is not documented *anywhere* on that page. ?All that we >> are told is that its default value is always None. >> >> I'm sure that I can find a full description of this parameter if >> I fire up Google, and search online. ?In fact, more likely than >> not, I'll find far more documentation than I want. ?But my point >> is that a programmer should not need to do this. ?The full >> documentation should be readily accessible directly through a few >> keystrokes. >> >> I would love to know how experienced Python programmers quickly >> zero in on the Python documentation they need. On Sun, Aug 2, 2009 at 4:22 PM, Mohan Parthasarathy wrote: > I am a newbie and about a month old with Python. There is a wealth of > material about Python and I am really enjoying learning Python. > > One thing that could have helped Python documentation is that instead of the > very "raw" doc string, it could have used something like PythonDoc (java doc > style) so that the functions/classes are documented better. At least I am > planning to use PythonDoc for the code that I am going to write. Let me know > if there is a better one.. If you use reStructuredText (http://docutils.sf.net/rst.html), you can leverage Sphinx (http://sphinx.pocoo.org/), which generates the superb-looking official Python docs. Cheers, Chris P.S. Please don't top-post (http://en.wikipedia.org/wiki/Top-post) in the future. -- http://blog.rebertia.com From pavlovevidence at gmail.com Sun Aug 2 20:00:40 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 2 Aug 2009 17:00:40 -0700 (PDT) Subject: Seeding the rand() Generator References: Message-ID: On Aug 2, 2:18?pm, Fred Atkinson wrote: > On Sun, 02 Aug 2009 08:53:50 -0700, Scott David Daniels > > wrote: > >Fred Atkinson wrote: > >> ? ? ? ?How does one seed the rand() generator when retrieving random > >> recordings in MySQL? ? > > >It is not entirely clear what you are asking. ?If you are talking about > >MySQL's random number generator, you are talking in the wrong newsgroup. > >If you are talking about Python's, does this work? > > ? ? import random > > ? ? random.seed(123542552) > >I'm not quite sure how you came to believe that Python controls MySQL, > >as opposed to using its services. > > >--Scott David Daniels > >Scott.Dani... at Acm.Org > > ? ? ? ? I am coding in Python. ? > > ? ? ? ? I am accessing a MySQL database. ? > > ? ? ? ? I have a string to instruct the MySQL database to use the > 'rand()' function to randomly choose one of the records in the > database. ? > > ? ? ? ? I know how to seed it in PHP. ?Does anyone know how to see it > from with Python? ? It sounds like you are using MySQL's rand() function, which means that whatever SQL command you used to seed it in PHP is the same command you would use to seed it in Python. You'll have to give us more information if you want a better answer than that. Carl Banks From lists at cheimes.de Sun Aug 2 20:39:34 2009 From: lists at cheimes.de (Christian Heimes) Date: Mon, 03 Aug 2009 02:39:34 +0200 Subject: Python docs disappointing In-Reply-To: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> References: <89dd3da60908021622k9967c90raa98afff1881bcc4@mail.gmail.com> Message-ID: Mohan Parthasarathy schrieb: > I am a newbie and about a month old with Python. There is a wealth of > material about Python and I am really enjoying learning Python. > > One thing that could have helped Python documentation is that instead of the > very "raw" doc string, it could have used something like PythonDoc (java doc > style) so that the functions/classes are documented better. At least I am > planning to use PythonDoc for the code that I am going to write. Let me know > if there is a better one.. Several projects are trying to improve the doc strings with an extended syntax. Personally I prefer the epytext syntax from epydoc [1]. It's a JavaDoc like markup language that extends the raw doc strings with useful information. Christian [1] http://epydoc.sourceforge.net/manual-epytext.html From r1chardj0n3s at gmail.com Sun Aug 2 21:07:55 2009 From: r1chardj0n3s at gmail.com (Richard Jones) Date: Mon, 3 Aug 2009 11:07:55 +1000 Subject: Registation is open for the 9th PyWeek game programming challenge! Message-ID: <3A356906-89BE-47A4-9ECE-4C87A7EA89BE@gmail.com> The ninth PyWeek challenge will run between: Sunday 30th August to Sunday 6th September (00:00UTC to 00:00UTC) The PyWeek challenge invites entrants to write a game in one week from scratch either as an individual or in a team. Entries must be developed in Python, during the challenge, and must incorporate some theme chosen at the start of the challenge. REGISTRATION IS NOW OPEN -- Visit the challenge website to sign up, join discussions in the message board or read the timetable and rules: http://www.pyweek.org/9/ PLANNING FOR THE CHALLENGE -- Make sure you have working versions of the libraries you're going to use. The rules page has a list of libraries and other resources. Make sure you can build packages to submit as your final submission (if you're going to use py2exe, make sure you know how to use it and that it works). If you don't have access to Linux, Windows or a Mac to test on, contact friends, family or other competitors to find someone who is able to test for you. From milesck at umich.edu Sun Aug 2 21:15:10 2009 From: milesck at umich.edu (Miles Kaufmann) Date: Sun, 2 Aug 2009 18:15:10 -0700 Subject: Skipping a superclass In-Reply-To: <02857910$0$20667$c3e8da3@news.astraweb.com> References: <02857910$0$20667$c3e8da3@news.astraweb.com> Message-ID: <3597BCD2-E6D1-4A76-85A2-6C1CA3D8B40B@umich.edu> On Aug 2, 2009, at 5:36 AM, Steven D'Aprano wrote: > I have a series of subclasses like this: > > class A(object): > def method(self, *args): > print "Lots of work gets done here in the base class" > > class B(A): > def method(self, *args): > print "A little bit of work gets done in B" > super(B, self).method(*args) > > class C(B): > def method(self, *args): > print "A little bit of work gets done in C" > super(C, self).method(*args) > > > However, the work done in C.method() makes the work done in B.method() > obsolete: I want one to run, or the other, but not both. C does need > to > inherit from B, for the sake of the other methods, so I want > C.method() > *only* to skip B while still inheriting from A. (All other methods > have > to inherit from B as normal.) This might not be applicable to the larger problem you're trying to solve, but for this sample, I would write it as: class A(object): def method(self, *args): self._method(*args) print "Lots of work gets done here in the base class" def _method(self, *args): pass # or perhaps raise NotImplemented class B(A): def _method(self, *args): print "A little bit of work gets done in B" class C(B): def _method(self, *args): print "A little bit of work gets done in C" > So what I have done is change the call to super in C to super(B, self) > instead of super(C, self). It seems to work, but is this safe to do? > Or > are there strange side-effects I haven't seen yet? In a diamond-inheritance situation, you may end up skipping methods besides just B.method(). -Miles From wuwei23 at gmail.com Sun Aug 2 21:23:39 2009 From: wuwei23 at gmail.com (alex23) Date: Sun, 2 Aug 2009 18:23:39 -0700 (PDT) Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <182b3193-d249-4887-ad23-b9c5a3b6dcd8@y4g2000prf.googlegroups.com> On Aug 3, 4:07?am, Terry Reedy wrote: > Peter Otten wrote: > > Steven D'Aprano wrote: [...] Fantastic question, answer & explanation, guys. Well done. From torriem at gmail.com Sun Aug 2 21:36:08 2009 From: torriem at gmail.com (Michael Torrie) Date: Sun, 02 Aug 2009 19:36:08 -0600 Subject: Queryable Daemon In-Reply-To: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> References: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Message-ID: <4A763F08.3000504@gmail.com> Justin DeCell wrote: > I was hoping for a little help with a project I'm working on. I'm > writing a daemon in python that I want to be queryable (i.e. I should > be able to run foo -s and it will report some internal information > about the foo daemon if it's running) but I can't figure out a way get > information from that process from an external process. I was thinking > that there should be a way to open a file descriptor, have the daemon > write to that every so often and then have the query process just read > from that fd but it looks like on the process reading from an fd has > to be a child of the daemon for this to work. The only other way I > thought of would be to write to a file on disk every so often from the > daemon and just read the from the query process but it seems like > there should be a more elegant way to do this... Most daemon programs I know of that do this use unix sockets. The socket is typically put in /tmp, or probably better in /var/run, or some other appropriate place. Often this is configurable in a config file that both the daemon and the program or instance that checks the daemon read. Another possibility is shared memory segments. I'm not sure how security is done in this case. Anyway, shared memory is a common IPC mechanism. From steve at nospam.au Sun Aug 2 22:27:22 2009 From: steve at nospam.au (steve) Date: Mon, 3 Aug 2009 12:27:22 +1000 Subject: Test for Pythonwin? References: <4a728aac$0$9744$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <4a764b0a$0$22840$5a62ac22@per-qv1-newsreader-01.iinet.net.au> "steve" wrote in message news:4a728aac$0$9744$5a62ac22 at per-qv1-newsreader-01.iinet.net.au... > Is there a good way to check if a script is running inside Pythonwin? > Perhaps a property or method that is exposed by that environment? > > or, alternatively, is there a better place to ask :-) > > Steven > > 'pywin' in sys.modules Didn't want to check for redirection because my redirection code is in a different thread, and I'd have to think about thread synchronization as well. Thanks guys, Steven From icebergwtf at gmail.com Sun Aug 2 22:33:53 2009 From: icebergwtf at gmail.com (tiefeng wu) Date: Mon, 3 Aug 2009 10:33:53 +0800 Subject: RE Question In-Reply-To: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> References: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> Message-ID: <4314c1f70908021933o68857e6fia8a99f039ea9f1d9@mail.gmail.com> 2009/8/3 Victor Subervi : -> Hi; -> How do I search and replace something like this: > aLine = re.sub('[<]?[p]?[>]? a-zA-Z0-9"\'=:]*>[<]?[b]?[>]?', '', aLine) > where RE *only* looks for the possibility of "

" at the beginning of the > string; that is, not the individual components as I have it coded above, but > the entire 3-character block? > TIA, > Victor I'm not sure I totally understand your problem, try this: aLine = re.sub(r'(?:

)?]*>(?:)'.format(str(x)), '', aLine) tiefeng wu 2009-08-03 From aahz at pythoncraft.com Sun Aug 2 22:52:14 2009 From: aahz at pythoncraft.com (Aahz) Date: 2 Aug 2009 19:52:14 -0700 Subject: Printing with colors in a portable way References: <33e19169-19b4-497a-b262-2bcf7b5637d5@r38g2000yqn.googlegroups.com> Message-ID: In article <33e19169-19b4-497a-b262-2bcf7b5637d5 at r38g2000yqn.googlegroups.com>, Robert Dailey wrote: > >Anyone know of a way to print text in Python 3.1 with colors in a >portable way? In other words, I should be able to do something like >this: > >print_color( "This is my text", COLOR_BLUE ) > >And this should be portable (i.e. it should work on Linux, Mac, >Windows). Much as I hate to say, use a cross-platform GUI -- Tkinter comes with Python, and you can also use SDL via PyGame, wxWindows, pyQT, PyOpenGL, and so on. If that's not an option, you should have said "command-line program". ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From joshua at azariah.com Sun Aug 2 23:18:43 2009 From: joshua at azariah.com (Joshua J. Kugler) Date: Sun, 2 Aug 2009 19:18:43 -0800 Subject: ANNOUNCE: AwstatsReader 0.01 Message-ID: <200908021918.44365.joshua@azariah.com> ABOUT THE MODULE ================ AwstatsReader is an attempt at a pythonic interface to AWStats data cache files. ?Using it, you can access year, month, and individual data points via dictionary-like accessors. Download here: http://azariah.com/open_source.html ABOUT THE AUTHOR ================ Joshua Kugler (joshua at azariah.com) is a programmer and system administrator with over 10 years of industry experience. ?He is currently looking for a job. ?Happen to have one you could offer him? :) Resume at: http://jjncj.com/papers/KuglerAll.pdf DISCLAIMER ========== This is a "release early, release often" release, codnamed Joshua-hopes- somebody-downloads-this-and-likes-code-quality-and-hires-him. This is an early release...probably pre-alpha. ?There are no tests yet (haven't generated cache files I can release publically), not much documentation, and the interface may change (but I hope not too much). And I haven't even put this in a public repository, as the name might (but probably won't) change. I wrote this via examples from an AWStats cache file, so I'm sure there are sections for which I do not have definitions. ?If you would send me those sections, I'll be sure to add them. The error handling is probably a little light. ?Certainly could be improved. Right now, this will parse and display cache files from AWStats 6.5. I've not tested other versions yet, as 6.5 is the only version I've had access to so far. INSTALLATION ============ See INSTALL LICENSE ======= See COPYING EXAMPLE ======= import AwstatsReader obj ?= AwstatsReader.AwstatsReader('/path/to/awstats_logs', 'example.com') print obj[2007] print obj[2008][6] m = obj[2009][7] print m['general'] # Access like a dictionary... print m['general']['LastLine'] #...or like an object attribute print m['general'].LastLine print m.general.LastLine FEEDBACK ======== Please send questions/comments/suggestions to awstatsreader at azariah.com For now, you can find the latest version here: http://azariah.com/open_source.html From gagsl-py2 at yahoo.com.ar Mon Aug 3 00:13:17 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 01:13:17 -0300 Subject: RE Question References: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> Message-ID: En Sun, 02 Aug 2009 18:22:20 -0300, Victor Subervi escribi?: > How do I search and replace something like this: > aLine = re.sub('[<]?[p]?[>]? a-zA-Z0-9"\'=:]*>[<]?[b]?[>]?', '', aLine) > where RE *only* looks for the possibility of "

" at the beginning of > the > string; that is, not the individual components as I have it coded above, > but > the entire 3-character block? An example would make it more clear; I think you want to match either "

" is optional. Use a normal group or a non-capturing group: r'(

)? Message-ID: <19e16923-b200-498b-9ab2-f7d316b568a6@d32g2000yqh.googlegroups.com> On Aug 2, 9:52?pm, a... at pythoncraft.com (Aahz) wrote: [snip] > Much as I hate to say, use a cross-platform GUI -- Tkinter comes with > Python, [snip] Why is Tkinter such a whipping boy of the Python community? I know it's very simple and does not have all the bells and whistles of wx, but i think the gentle learning curve is very important for those struggling to learn GUI's. Even today I always use Tkinter first, and then only reach for wx when absolutely necessary. Seems to me the relativity small footprint(GUI wise) compared to the payoffs are worth the inclusion. I think if Tkinter where ever removed from Python it would be not only a disservice to the language but also a detriment to the *new* users of the language. Just my humble opinion From anthra.norell at bluewin.ch Mon Aug 3 03:40:00 2009 From: anthra.norell at bluewin.ch (Anthra Norell) Date: Mon, 03 Aug 2009 09:40:00 +0200 Subject: Compiling regex inside function? Message-ID: <4A769450.5080702@bluewin.ch> Hi all, I have a regex that has no use outside of a particular function. From an encapsulation point of view it should be scoped as restrictively as possible. Defining it inside the function certainly works, but if re.compile () is run every time the function is called, it isn't such a good idea after all. E.g. def entries (l): r = re.compile ('([0-9]+) entr(y|ies)') match = r.search (l) if match: return match.group (1) So the question is: does "r" get regex-compiled once at py-compile time or repeatedly at entries() run time? Frederic From greg.ewing at canterbury.ac.nz Mon Aug 3 03:40:41 2009 From: greg.ewing at canterbury.ac.nz (Greg Ewing) Date: Mon, 03 Aug 2009 19:40:41 +1200 Subject: Registation is open for the 9th PyWeek game programming challenge! In-Reply-To: <3A356906-89BE-47A4-9ECE-4C87A7EA89BE@gmail.com> References: <3A356906-89BE-47A4-9ECE-4C87A7EA89BE@gmail.com> Message-ID: <4A769479.9080707@canterbury.ac.nz> Richard Jones wrote: > The ninth PyWeek challenge will run between: > > Sunday 30th August to Sunday 6th September (00:00UTC to 00:00UTC) Yow, hard on the heels of Pyggy! I'd hoped there might be a bit more breathing room, sorry about that! Hope the Pyggy entrants aren't feeling too burned out to participate. -- Greg From deets at nospam.web.de Mon Aug 3 03:45:32 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Aug 2009 09:45:32 +0200 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: <7dnissF2bthr0U1@mid.uni-berlin.de> Marcus Wanner schrieb: > On 8/2/2009 10:43 AM, Christian Heimes wrote: >> Marcus Wanner wrote: >>> I believe that python is buffer overflow proof. In fact, I think that >>> even ctypes is overflow proof... >> >> No, ctypes isn't buffer overflow proof. ctypes can break and crash a >> Python interpreter easily. >> >> Christian >> > I see. I thought that it said "invalid array index" when you try to > read/write outside of an array's bounds, though... But you can cast the resulting pointer to an array of larger size, and there you are. Diez From davea at ieee.org Mon Aug 3 04:04:04 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Aug 2009 04:04:04 -0400 Subject: Run pyc file without specifying python path ? In-Reply-To: <7F0503CD69378F49BE0DC30661C6CCF67D49D318@enbmail01.lsi.com> References: <7F0503CD69378F49BE0DC30661C6CCF6701A26C4@enbmail01.lsi.com> <4A708F68.1010505@ieee.org> <7F0503CD69378F49BE0DC30661C6CCF6701A26C7@enbmail01.lsi.com> <4A7199FF.8010202@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF6701A26D2@enbmail01.lsi.com> <4A71D35F.3090800@dejaviewphoto.com> <7F0503CD69378F49BE0DC30661C6CCF67D49D30E@enbmail01.lsi.com> <4A755DE6.1000906@ieee.org> <7F0503CD69378F49BE0DC30661C6CCF67D49D318@enbmail01.lsi.com> Message-ID: <4A7699F4.1050400@ieee.org> Barak, Ron wrote: > >> -----Original Message----- >> From: Dave Angel [mailto:davea at ieee.org] >> Sent: Sunday, August 02, 2009 12:36 >> To: Barak, Ron >> Cc: 'python-list at python.org' >> Subject: Re: Run pyc file without specifying python path ? >> >> Barak, Ron wrote: >> >>> Hi Dave, >>> >>> It seems like I don't understand your solution. >>> I use the (attached) soapAPI.py as the wrapper to parsing.pyc. >>> However, if I do (for instance): >>> >>> $ python -u parsing.pyc -U aaa >>> >>> The last line of the output is (as expected): >>> >>> return_code: 12 ; params: {'username': 'aaa'} >>> >>> But, if I try the following: >>> >>> $ soapAPI.py -U aaa >>> >>> I don't get this line. Only the output to stderr gets >>> >> printed to the screen. >> >>> Bye, >>> Ron. >>> >>> >>> >> Hi Ron, >> >> To make it easier for anybody following this thread, let me >> post the minimum equivalent source files, inline. >> >> parsing.py: >> ------------------------------ >> #!/usr/bin/env python >> >> import sys >> >> def main(): >> print >> sys.stderr, "This is stderr output" >> return 5, sys.argv >> >> if __name__ == "__main__": >> return_code, params = main() >> print "return_code:",return_code,"; params:",params >> sys.exit(return_code) >> ------------------------------- >> soapapi.py: >> ------------------------------- >> #!/usr/bin/env python >> >> import sys >> import parsing >> >> parsing.main() >> ------------------------------ >> >> >> When I run soapapi.;py, it indeed prints only the stderr output. >> >> The solution is to move (most or all) of the top-level code >> of parsing.py into a main() function. Since you already have >> a main(), I'll rename that, and make a new one that calls it. >> >> new parsing.py: >> ------------------------------- >> #!/usr/bin/env python >> >> import sys >> >> def innermain(): >> print >> sys.stderr, "This is stderr output" >> return 5, sys.argv >> >> def main(): >> return_code, params = innermain() >> print "return_code:",return_code,"; params:",params >> sys.exit(return_code) >> >> if __name__ == "__main__": >> main() >> ------------------------------- >> >> The output is now two lines, one from innermain(), and one >> from main(). >> And it's the same whether the user runs parsing.py or soapAPI.py >> >> To clarify what happened, realize that when the user invokes >> parsing.py, the module is considered a script, and gets a >> pseudo-name of >> "__main__" When that same module is imported by another one, it is >> considered a library module, and gets its own name "parsing" >> >> So any logic that explicitly checks for "__main__" has to >> change, because we want identical behavior in the two cases. >> >> DaveA >> >> >> > > Hi Dave, > > Trying your above scripts, I get other results than you do. E.g.: > > $ python parsing.py --help > return_code: 5 ; params: ['parsing.py', '--help'] > This is stderr output > > $ python soapapi.py --help > This is stderr output > > $ > > So, in my environment (cygwin on win xp, python Python 2.5.2) I'm getting different results than you get, namely - soapapi.py on my environment does not show the stdout output. > On which environment did you get identical results from your parsing.py and soapapi.py ? > > Bye, > Ron. > > $ cat parsing.py > #!/usr/bin/env python > > import sys > > def main(): > print >> sys.stderr, "This is stderr output" > return 5, sys.argv > > if __name__ == "__main__": > return_code, params = main() > print "return_code:",return_code,"; params:",params > sys.exit(return_code) > > $ cat soapapi.py > #!/usr/bin/env python > > import sys > import parsing > > parsing.main() > > > > Please read my message again, especially starting with the words "the solution is." I showed two versions of parsing.py, and you're still using the broken version. I posted both versions, with descriptions of what I changed and why, so that you could see why the change was important. I'm using sys.version == 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] Running on XP Sp3. And 2.5 will give identical results, though I don't have it installed any more. DaveA From matt.urry at googlemail.com Mon Aug 3 04:36:41 2009 From: matt.urry at googlemail.com (ma3mju) Date: Mon, 3 Aug 2009 01:36:41 -0700 (PDT) Subject: Processes not exiting References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com> <61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com> <01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> Message-ID: <996e50f5-c126-4ac2-ae8d-458d22a26ee1@v20g2000yqm.googlegroups.com> On 2 Aug, 21:49, Piet van Oostrum wrote: > >>>>> MRAB (M) wrote: > >M> I wonder whether one of the workers is raising an exception, perhaps due > >M> to lack of memory, when there are large number of jobs to process. > > But that wouldn't prevent the join. And you would probably get an > exception traceback printed. > > I wonder if something fishy is happening in the multiprocessing > infrastructure. Or maybe the Fortran code goes wrong because it has no > protection against buffer overruns and similar problems, I think. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org I don't think it's a memory problem, the reason for the hard and easy queue is because for larger examples it uses far more RAM. If I run all of workers with harder problems I do begin to run out of RAM and end up spending all my time switching in and out of swap so I limit the number of harder problems I run at the same time. I've watched it run to the end (a very boring couple of hours) and it stays out of my swap space and everything appears to be staying in RAM. Just hangs after all "poison" has been printed for each process. The other thing is that I get the message "here" telling me I broke out of the loop after seeing the poison pill in the process and I get all the things queued listed as output surely if I were to run out of memory I wouldn't expect all of the jobs to be listed as output. I have a serial script that works fine so I know individually for each example the fortran code works. Thanks Matt From MatzeGuentert at gmx.de Mon Aug 3 04:46:29 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Mon, 03 Aug 2009 08:46:29 +0000 Subject: M2Crypto: X509.X509_Extension_Stack() throws AssertionError Message-ID: <1249289189.3205.5.camel@celsius> Hello python-list members Why is the following code snippet throwing an AssertionError? Is that behavior a bug within X509.X509_Extension_Stack()? How would you suggest popping every element from the stack? Regards, Matthias G?ntert ------------------------------------------------- from M2Crypto import X509 if __name__ == '__main__': cert_extension_stack = X509.X509_Extension_Stack() cert_extension_1 = X509.new_extension("basicConstraints", "CA:FALSE") cert_extension_1.set_critical() cert_extension_2 = X509.new_extension("keyUsage", "101000000") cert_extension_2.set_critical() cert_extension_3 = X509.new_extension("subjectAlternativeName", "DNS:www.mydomain.tld") print cert_extension_stack.push(cert_extension_1) print cert_extension_stack.push(cert_extension_2) print cert_extension_stack.push(cert_extension_3) print cert_extension_stack.pop() ------------------------------------------------- ------------------------------------------------- Traceback (most recent call last): File "test.py", line 18, in print cert_extension_stack.pop() File "/usr/lib64/python2.6/site-packages/M2Crypto/X509.py", line 159, in pop assert len(self.pystack) == 0 AssertionError 1 2 3 ------------------------------------------------- From zdenekmaxa at yahoo.co.uk Mon Aug 3 05:19:11 2009 From: zdenekmaxa at yahoo.co.uk (Zdenek Maxa) Date: Mon, 03 Aug 2009 11:19:11 +0200 Subject: urllib2.urlopen timeout Message-ID: <4A76AB8F.5090403@yahoo.co.uk> Hi, I would like to ask how I should set timeout for a call: f = urllib2.urlopen(url) I am using Python 2.5. I have already tried socket.setdefaulttimeout(3). However, this adversely affects other connections the application makes, since it seems to affect all socket connections. I know that Python 2.6 offers urllib2.urlopen(url[, data][, timeout]) which would elegantly solved my problem, but I have to stick to Python 2.5. I am doing urlopen in a thread so I want to avoid really long hanging on this call, which happens at times, until some default timeout ticks out. All hints appreciated. Thanks, Zdenek From jeanmichel at sequans.com Mon Aug 3 06:46:45 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 03 Aug 2009 12:46:45 +0200 Subject: Printing with colors in a portable way In-Reply-To: References: <33e19169-19b4-497a-b262-2bcf7b5637d5@r38g2000yqn.googlegroups.com> Message-ID: <4A76C015.5010600@sequans.com> Nobody wrote: > On Thu, 30 Jul 2009 15:40:37 -0700, Robert Dailey wrote: > > >> Anyone know of a way to print text in Python 3.1 with colors in a >> portable way? In other words, I should be able to do something like >> this: >> >> print_color( "This is my text", COLOR_BLUE ) >> >> And this should be portable (i.e. it should work on Linux, Mac, >> Windows). >> > > The way that terminals (and emulators) handle colour is fundamentally > different from the DOS/Windows console. If you want something which will > work on both, you will have write separate implementations for terminals > and the DOS/Windows console. > > For terminals, you can use the "curses" package, e.g.: > > import curses > > curses.setupterm() > setaf = curses.tigetstr('setaf') > setab = curses.tigetstr('setab') > > def foreground(num): > if setaf: > sys.stdout.write(curses.tparm(setaf, num)) > > def background(num): > if setab: > sys.stdout.write(curses.tparm(setab, num)) > > For the Windows console, you'll need to use ctypes to interface to the > SetConsoleTextAttribute() function from Kernel32.dll. > > FYI http://github.com/jbowes/markymark/blob/59511b36a752b40243cc18fb0fb9800c74549ac1/markymark.py If the URL ever becomes invalid, then google for markymark.py You can use it either to color your Linux/Unix terms, or you can just look at the python code to see how to set colors and attributes. JM From hitechpundir at gmail.com Mon Aug 3 07:12:15 2009 From: hitechpundir at gmail.com (sirjee) Date: Mon, 3 Aug 2009 04:12:15 -0700 (PDT) Subject: problem in event handling on change of variable value. References: <9c0d7a31-0310-4499-9974-92afc588f315@d15g2000prc.googlegroups.com> Message-ID: <27a8e24c-7f58-4952-b45a-439601223199@13g2000prl.googlegroups.com> On Aug 1, 2:22?pm, sirjee wrote: > hello; > > i m facing a problem in handling events on change of value of > environment variable in a toolCANoe. > > class CANoeEvents: > ? ? def OnChange(self,value): > ? ? ? ? print "value of environment variable has changed" > ? ? def OnOpen(self,App): > ? ? ? ? print "opening Application" > > App_Event = DispatchWithEvents('CANoe.Application',CANoeEvents) > time.sleep(2) > App_Event.Open("C:\projectConfig.cfg") ?# printd "opening Application" > and event handled properly. > .......(now a code file runs in thecanoein which value of > environment variable called dummy is changed during execution. Just > like OnOpen; OnChange is defined in specification which should be > called on change of environment variable.But it is not happening.) > while (): > ? ? ? ? ? ? ? ? myenvVar = App_Event.Environment.GetVariable("dummy") > > The VB does it very easily and defines a subroutine called : > Sub myenvVar _OnChange(value) > ? ?print "value of environment variable has changed" > End Sub > //////////////////////////////////////////////////however the > alternative for subroutine for OnOpen in VB (defined below) works fine > as shown above in python. > Sub AppEvent_OnOpen(App) > ? ? ? ? print "opening Application" > End Sub > > for VB; all this stuff is cake work.... object_eventname subroutine > and done.....what in python? hi all; strange !!!! i got answer to the problem posted by me only. now I have very good control of CANoe tool from python.... if anybody faces any problem wrt automation of CANoe tool using python; do contact me. here actual problem lied in analysing and implementing com heirarchy. ( which is really bit cumbersome) onChange event is associated with App_Event.Environment.GetVariable ("dummy") object. So we need to associate separate class with this object and then write onChange function: class evtClass: def __init__(self): print "initializing event class" def OnChange(self,value): print "value of environment variable changing" print "changed value of environment variable is" print value see = App_Event.Environment.GetVariable("dummy") see_temp=DispatchWithEvents(see,evtClass) this will solve problem. So we need to create separate classes for events associated with separate objects. regards sirjee From marcusw at cox.net Mon Aug 3 08:01:00 2009 From: marcusw at cox.net (Marcus Wanner) Date: Mon, 03 Aug 2009 08:01:00 -0400 Subject: Is python buffer overflow proof? In-Reply-To: <7dnissF2bthr0U1@mid.uni-berlin.de> References: <7dnissF2bthr0U1@mid.uni-berlin.de> Message-ID: On 8/3/2009 3:45 AM, Diez B. Roggisch wrote: > Marcus Wanner schrieb: >> On 8/2/2009 10:43 AM, Christian Heimes wrote: >>> Marcus Wanner wrote: >>>> I believe that python is buffer overflow proof. In fact, I think >>>> that even ctypes is overflow proof... >>> >>> No, ctypes isn't buffer overflow proof. ctypes can break and crash a >>> Python interpreter easily. >>> >>> Christian >>> >> I see. I thought that it said "invalid array index" when you try to >> read/write outside of an array's bounds, though... > > > But you can cast the resulting pointer to an array of larger size, and > there you are. > > Diez Ah, that makes sense. I had forgotten about ctypes.cast(). Marcus From riaz.ahmadskh at gmail.com Mon Aug 3 08:03:46 2009 From: riaz.ahmadskh at gmail.com (Riaz Ahmad) Date: Mon, 3 Aug 2009 05:03:46 -0700 (PDT) Subject: "PAKISTAN NEWS" "PAKISTANI NEWSPAPERS" "MAGAZINES ON LINE" "URDU LANGUAGE SOFTWARES" "URDU POETRY PAKISTAN" "PAKISTANI WEB SITE DIRECTOR" "PAKISTANI NEWSPAPERS" "PAKISTAN" "PAKISTAN" on www.pak-web-pages.blogspot.com Message-ID: "PAKISTAN NEWS" www.pak-web-pages.blogspot.com "PAKISTANI NEWSPAPERS" www.pak-web-pages.blogspot.com "MAGAZINES ON LINE" www.pak-web-pages.blogspot.com "URDU LANGUAGE SOFTWARES" www.pak-web-pages.blogspot.com "URDU POETRY PAKISTAN" www.pak-web-pages.blogspot.com "PAKISTANI WEB SITE DIRECTOR" www.pak-web-pages.blogspot.com "PAKISTANI NEWSPAPERS" www.pak-web-pages.blogspot.com "PAKISTAN" www.pak-web-pages.blogspot.com "PAKISTAN" www.pak-web-pages.blogspot.com on www.pak-web-pages.blogspot.com From hubaghdadi at gmail.com Mon Aug 3 08:14:35 2009 From: hubaghdadi at gmail.com (Hussein B) Date: Mon, 3 Aug 2009 05:14:35 -0700 (PDT) Subject: Executing remote command with paramiko Message-ID: Hey, I'm trying to run a sudo guarded command over SSH using paramiko +++++++++++++++++++ s = paramiko.SSHClient() s.load_system_host_keys() s.connect(hostname, port, username, passwd) stdin, stdout, stderr = s.exec_command('sudo -s') stdin.write('password\n') stdin.flush() print 'Flushing' stdin, stdout, stderr = s.exec_command('harvester') print stdout.read() s.close() +++++++++++++++++++ It seems to me that the sudo -s isn't getting executed at all. I commented the sudo -s code lines and no error is shown. Thanks for help and time. From duncan.booth at invalid.invalid Mon Aug 3 08:34:28 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Aug 2009 12:34:28 GMT Subject: heapq "key" arguments References: <97932d10-8601-401f-bb69-a98db9036929@p15g2000vbl.googlegroups.com> <1582f82e-34aa-4b66-b989-c9f8351a5f1c@o9g2000prg.googlegroups.com> <4f096546-36a1-4633-9a24-1265ce0929ce@q14g2000vbi.googlegroups.com> Message-ID: "Gabriel Genellina" wrote: > Ok, it's not strictly the same, but usually it doesn't hurt. The heaqp > module doesn't promise anything about equal elements: it may keep the > original order, rearrange them at will, reverse them, whatever. The documentation doesn't say anything directly about stability, but the implementation is actually stable. You can probably assume it must be at least for nlargest and nsmallest otherwise the stated equivalence wouldn't hold: e.g. nsmallest documentation says: Equivalent to: sorted(iterable, key=key)[:n] -- Duncan Booth http://kupuguy.blogspot.com From sjmachin at lexicon.net Mon Aug 3 09:00:33 2009 From: sjmachin at lexicon.net (John Machin) Date: Mon, 3 Aug 2009 06:00:33 -0700 (PDT) Subject: New implementation of re module References: Message-ID: On Jul 28, 2:34?am, MRAB wrote: > Hi all, > > I've been working on a new implementation of the re module. The details > are athttp://bugs.python.org/issue2636, specifically fromhttp://bugs.python.org/issue2636#msg90954. I've included a .pyd file for > Python 2.6 on Windows if you want to try it out. > Where/how should we report perceived bugs: On that bugs.python.org issue? Here? Private e-mail? From ram.rachum at gmail.com Mon Aug 3 09:18:29 2009 From: ram.rachum at gmail.com (cool-RR) Date: Mon, 3 Aug 2009 06:18:29 -0700 (PDT) Subject: Announcing PythonTurtle Message-ID: Hello, I wanted to announce that I have just released my little side project, PythonTurtle. Here is its website: http://pythonturtle.com Its goal is to be the lowest-threshold way to learn (or teach) Python. You can read more about it and download it on the website. Ram. From mydevforums at gmail.com Mon Aug 3 10:04:07 2009 From: mydevforums at gmail.com (IronyOfLife) Date: Mon, 3 Aug 2009 07:04:07 -0700 (PDT) Subject: Python configuration question when python scripts are executed using Appweb as web server. Message-ID: Hi All I have installed python 2.6.2 in windows xp professional machine. I have set the following environment variables -- PYTHONPATH. It points to following windows folders: python root folder, the lib folder and lib-tk folder. I have configured IIS to execute python scripts. I do not have any issues executing python scripts from the python interpreter window or from the browser using IIS as the web server. However, when I use the open source Appweb web browser to execute python scripts. It is able to execute only simple script without issues. For example, hello.py executes fine. hello.py -------------------------------------------------------- #!/usr/bin/env python print "Content-type: text/html\n\n" print "Hello world!" However I am not able to execute python scripts that contain import statements. I need to point out here that i do not have issue with using os or sys packages. When I tried to execute the sample client script that came with the gnutls wrapper for python, I got error. I narrowed it down to the "from ... import" line in the example. from gnutls.crypto import * from gnutls.connection import * Next I modified it to the functions used in the client python scripts (NOTE: I have added some additional functions to connection and crypto python scripts). from gnutls.crypto import X509Certificate, X509PrivateKey, X509CRL from gnutls.connection import AnonClientCred Next step, in order to debug, I used the module finder to see what is happening. To being with I used the module finder to find out the modules loaded for the simple script hello.py. hello2.py -------------------------------------------------------- #!/usr/bin/env python import modulefinder import pdb pdb.set_trace() finder = modulefinder.ModuleFinder() finder.run_script('hello.py') print "Content-type: text/html\n\n" print "" print sys.exc_info() print 'Loaded modules:' for name, mod in finder.modules.iteritems(): print '%s: ' % name, print ','.join(mod.globalnames.keys()[:3]) print '-'*50 print 'Modules not imported:' print '\n'.join(finder.badmodules.iterkeys()) print "" I got the error. Please see below for error as captured from Appweb logs. See lines 3 to 5. cgi:5 main 356: CGI Response: read 89 bytes cgi:6 main 356: Data is: > c:\appweb\web\hello2.py(9)() -> finder = modulefinder.ModuleFinder() (Pdb) cgi:5 main 356: CGI Response: read 0 bytes cmd:7 main getExitCode: process 0, code 1 default:1 main Error: 503 "Service Unavailable" for "/hello2.py", file "c:/appweb/web/hello2.py": CGI process /hello2.py: exited abnormally with exit code: 1 request:5 main 356: flushOutput: background 0 Once again, let me stress that this issue is happening only when I use appweb as the web server. Some details on Appweb that I found out: Appweb opens up a new console process and executes the python scripts. See sample below: cmd:5 pool.0 Running: C:\Dev\Ironic\Tools\Python26\python.exe c:/ appweb/web/hello2.py When python scripts are executed in this fashion, should there be additional command line arguments be passed? Am I missing any additional settings. Also can you help with improving the debugging lines in hello2.py so that I can identify the issue. Please help. Thanks. Ram G. From jeanmichel at sequans.com Mon Aug 3 10:38:43 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 03 Aug 2009 16:38:43 +0200 Subject: Generate a new object each time a name is imported In-Reply-To: <02853264$0$20667$c3e8da3@news.astraweb.com> References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: <4A76F673.9010701@sequans.com> Steven D'Aprano wrote: > I would like to generate a new object each time I import a name from a > module, rather than getting the same object each time. For example, > currently I might do something like this: > > # Module > count = 0 > def factory(): > # Generate a unique object each time this is called > global count > count += 1 > return "Object #%d" % count > > > # Calling module > from Module import factory > a = factory() # a == "Object #1" > b = factory() # b == "Object #2" > del factory > > > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a # a == "Object #1" > from Module import factory() as b # b == "Object #2" > > except of course that syntax is illegal. > > > Why making standard statements do what they're not meant to do ? You could write >import Module > >a = factory() >b = factory() But you already know that. So what's the purpose of making >from Module import factory as a >from Module import factory as b return 2 different objects ? If I had to write this code I would expect 'a is b' to return 'True'. This is no "don't do that" answer, it's a sincere question: what is the benefit of your /new/ syntax ? JM From andre.roberge at gmail.com Mon Aug 3 10:53:43 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 3 Aug 2009 07:53:43 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: <44a7457e-4dc7-4ad4-be80-3585ce693bc9@f37g2000yqn.googlegroups.com> On Aug 3, 10:18?am, cool-RR wrote: > Hello, > > I wanted to announce that I have just released my little side project, > PythonTurtle. > Here is its website:http://pythonturtle.com > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > You can read more about it and download it on the website. > > Ram. Why not make the source available? At the very least, people that do not run windows could try it too. Andr? From jcd at sdf.lonestar.org Mon Aug 3 10:54:05 2009 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Mon, 03 Aug 2009 10:54:05 -0400 Subject: A Bug By Any Other Name ... In-Reply-To: References: Message-ID: <1249311245.8865.11.camel@aalcdl07> On Sun, 2009-08-02 at 14:14 +0000, Albert van der Horst wrote: > >This is actually quite thoroughly untrue. In python, *indentation* > is > >significant. Whitespace (internal to a line) is not. You can even > call > >methods like this if you want: > > You totally don't get it. You describe how python is now. > I propose a change to be made to python. Small wonder that that is > different from what it is now. > > > > >>>> s = 'abc' > >>>> s . upper() > >ABC > > You prove nothing by giving examples. > You can disprove by giving one counter example, > here it goes. > > Whitespace (internal to a line) is significant. > In Python you cannot change > xleftgoing = 123000000 > to > x left going = 123 000 000 > > (You can in Algol68) I had a feeling that counterexample would be coming sooner or later. However, it doesn't really address the change you're looking for. Internal whitespace *is* irrelevant, except insofar as it can be used to delimit different tokens in parsing. If tokens are separate, they are separate, and no more or less whitespace is going to make any difference. Again, I'm describing how python is now. Which is not to say it couldn't be changed, I just want to make sure you understand how deep into the heart of python you are trying to cut. You make it sound like a small change, but it is not. You are proposing changing the parsing rules, which completely changes the scope of what is possible and what isn't with python syntax. All to solve a problem that, so far, hasn't been proven to exist in anything other than a speculative way. You're trying to turn an ocean liner around because you left your sunscreen on the dock. Cheers, Cliff From newsgroup at silveraxe.de Mon Aug 3 10:56:17 2009 From: newsgroup at silveraxe.de (Hilmar Bunjes) Date: Mon, 03 Aug 2009 16:56:17 +0200 Subject: Announcing PythonTurtle In-Reply-To: <44a7457e-4dc7-4ad4-be80-3585ce693bc9@f37g2000yqn.googlegroups.com> References: <44a7457e-4dc7-4ad4-be80-3585ce693bc9@f37g2000yqn.googlegroups.com> Message-ID: <4a76fa98$0$31327$9b4e6d93@newsspool4.arcor-online.net> Andr? schrieb: >> I wanted to announce that I have just released my little side project, >> PythonTurtle. >> Here is its website:http://pythonturtle.com >> >> Its goal is to be the lowest-threshold way to learn (or teach) Python. >> You can read more about it and download it on the website. >> >> Ram. > > Why not make the source available? At the very least, people that do > not run windows could try it too. Isn't this the source: http://github.com/cool-RR/PythonTurtle/tree/master ? Linked at the bottom of the page. Best, Hilmar From sandhyaprabhakaran at gmail.com Mon Aug 3 11:17:53 2009 From: sandhyaprabhakaran at gmail.com (Sandhya Prabhakaran) Date: Mon, 3 Aug 2009 08:17:53 -0700 (PDT) Subject: Extract the numeric and alphabetic part from an alphanumeric string Message-ID: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Hi, I have a string as str='123ACTGAAC'. I need to extract the numeric part from the alphabetic part which I did using >>>numer=re.findall(r'\d+',str) >>>numer 123 To get the alphabetic part, I could do >>>alpha=str.replace('123','') >>>alpha ACTGAAC But when I give >>>alpha=str.replace(numer,'') Traceback (most recent call last): File "", line 1, in TypeError: expected a character buffer object How do I blank out the initial numeric part so as to get just the alphabetic part. The string is always in the same format. Please help. Regards, Sandhya From ram.rachum at gmail.com Mon Aug 3 11:22:50 2009 From: ram.rachum at gmail.com (cool-RR) Date: Mon, 3 Aug 2009 08:22:50 -0700 (PDT) Subject: Announcing PythonTurtle References: <44a7457e-4dc7-4ad4-be80-3585ce693bc9@f37g2000yqn.googlegroups.com> Message-ID: On Aug 3, 5:53?pm, Andr? wrote: > On Aug 3, 10:18?am, cool-RR wrote: > > > Hello, > > > I wanted to announce that I have just released my little side project, > > PythonTurtle. > > Here is its website:http://pythonturtle.com > > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > > You can read more about it and download it on the website. > > > Ram. > > Why not make the source available? ?At the very least, people that do > not run windows could try it too. > > Andr? Sorry that the link is obscure like that. I'll change it so it's easier to see. From peter at peter-b.co.uk Mon Aug 3 11:31:09 2009 From: peter at peter-b.co.uk (Peter Brett) Date: Mon, 03 Aug 2009 16:31:09 +0100 Subject: Extract the numeric and alphabetic part from an alphanumeric string References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: Sandhya Prabhakaran writes: > Hi, > > I have a string as str='123ACTGAAC'. > > I need to extract the numeric part from the alphabetic part which I > did using >>>>numer=re.findall(r'\d+',str) >>>>numer > 123 > > To get the alphabetic part, I could do >>>>alpha=str.replace('123','') >>>>alpha > ACTGAAC > But when I give >>>>alpha=str.replace(numer,'') > Traceback (most recent call last): > File "", line 1, in > TypeError: expected a character buffer object > > How do I blank out the initial numeric part so as to get just the > alphabetic part. The string is always in the same format. Firstly, you really should read the Regular Expression HOWTO: http://docs.python.org/howto/regex.html#regex-howto Secondly, is this what you wanted to do? >>> p = re.compile(r'^\d+') >>> p.sub('', '123ACTGAAC') 'ACTGAAC' Regards, Peter -- Peter Brett Remote Sensing Research Group Surrey Space Centre From andreas.tawn at ubisoft.com Mon Aug 3 11:33:00 2009 From: andreas.tawn at ubisoft.com (Andreas Tawn) Date: Mon, 3 Aug 2009 17:33:00 +0200 Subject: Extract the numeric and alphabetic part from an alphanumeric string In-Reply-To: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: <8AEDA5E3386EA742B8C24C95FF0C758007C8ACF4@PDC-MAIL3.ubisoft.org> > Hi, > > I have a string as str='123ACTGAAC'. > > I need to extract the numeric part from the alphabetic part which I > did using > >>>numer=re.findall(r'\d+',str) > >>>numer > 123 > > To get the alphabetic part, I could do > >>>alpha=str.replace('123','') > >>>alpha > ACTGAAC > But when I give > >>>alpha=str.replace(numer,'') > Traceback (most recent call last): > File "", line 1, in > TypeError: expected a character buffer object > > How do I blank out the initial numeric part so as to get just the > alphabetic part. The string is always in the same format. > > Please help. > > Regards, > Sandhya If the format's always the same, you could use slicing instead. >>> s = '123ACTGAAC' >>> s[:3] '123' >>> s[3:] 'ACTGAAC' BTW, you should avoid using built-ins like str for variable names. Bad things will happen. Cheers, Drea From python at mrabarnett.plus.com Mon Aug 3 11:43:30 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 03 Aug 2009 16:43:30 +0100 Subject: Extract the numeric and alphabetic part from an alphanumeric string In-Reply-To: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: <4A7705A2.2010301@mrabarnett.plus.com> Sandhya Prabhakaran wrote: > Hi, > > I have a string as str='123ACTGAAC'. > > I need to extract the numeric part from the alphabetic part which I > did using >>>> numer=re.findall(r'\d+',str) >>>> numer > 123 > [snip] I get: ['123'] which is a _list_ of the strings found. From kushal.kumaran+python at gmail.com Mon Aug 3 11:49:15 2009 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Mon, 3 Aug 2009 21:19:15 +0530 Subject: Extract the numeric and alphabetic part from an alphanumeric string In-Reply-To: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: <1e364c4e0908030849u7583637h9c8d688f8520b904@mail.gmail.com> On Mon, Aug 3, 2009 at 8:47 PM, Sandhya Prabhakaran wrote: > Hi, > > I have a string as str='123ACTGAAC'. > > I need to extract the numeric part from the alphabetic part which I > did using >>>>numer=re.findall(r'\d+',str) >>>>numer > 123 > The docs for re.findall say that it returns a list of matches. So '123' will be numer[0]. > To get the alphabetic part, I could do >>>>alpha=str.replace('123','') >>>>alpha > ACTGAAC > But when I give >>>>alpha=str.replace(numer,'') > Traceback (most recent call last): > ?File "", line 1, in > TypeError: expected a character buffer object > That's what would happen if you pass in a list instead of a string to replace. > How do I blank out the initial numeric part so as to get just the > alphabetic part. The string is always in the same format. > > Please help. > -- kushal From python at mrabarnett.plus.com Mon Aug 3 12:00:05 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 03 Aug 2009 17:00:05 +0100 Subject: New implementation of re module In-Reply-To: References: Message-ID: <4A770985.5020900@mrabarnett.plus.com> John Machin wrote: > On Jul 28, 2:34 am, MRAB wrote: >> Hi all, >> >> I've been working on a new implementation of the re module. The details >> are athttp://bugs.python.org/issue2636, specifically fromhttp://bugs.python.org/issue2636#msg90954. I've included a .pyd file for >> Python 2.6 on Windows if you want to try it out. >> > > Where/how should we report perceived bugs: On that bugs.python.org > issue? Here? Private e-mail? > Probably on http://bugs.python.org/issue2636. From ethan at stoneleaf.us Mon Aug 3 12:00:43 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 03 Aug 2009 09:00:43 -0700 Subject: Python docs disappointing In-Reply-To: <7bb4df03-f09a-40b0-83f8-1c6d0c9800a8@j21g2000vbn.googlegroups.com> References: <7bb4df03-f09a-40b0-83f8-1c6d0c9800a8@j21g2000vbn.googlegroups.com> Message-ID: <4A7709AB.4060105@stoneleaf.us> Carl Banks wrote: > On Jul 31, 1:55 pm, Mark Lawrence wrote: > >>Apart from that what have the Pythonistas ever done for us? Nothing!:) > > > > Please don't feed the trolls. > > And if you do feed the trolls don't smile at them. > > > Carl Banks And if you do smile at them, don't show your teeth! ~Ethan~ From deets at nospam.web.de Mon Aug 3 12:01:14 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Aug 2009 18:01:14 +0200 Subject: Compiling regex inside function? References: Message-ID: <7dofubF2crctpU1@mid.uni-berlin.de> Anthra Norell wrote: > Hi all, > > I have a regex that has no use outside of a particular function. From > an encapsulation point of view it should be scoped as restrictively as > possible. Defining it inside the function certainly works, but if > re.compile () is run every time the function is called, it isn't such a > good idea after all. E.g. > > def entries (l): > r = re.compile ('([0-9]+) entr(y|ies)') > match = r.search (l) > if match: return match.group (1) > > So the question is: does "r" get regex-compiled once at py-compile time > or repeatedly at entries() run time? This can't be answered as simple yes/no-question. While the statement is executed each time, the resulting pattern-object isn't re-created, instead there is a caching-mechanism inside the module - so unless you create a situation where that cache's limits are exceeded and pattern objects are removed from it, you are essentially having the overhead of one function-call & a dict-lookup. Certainly worth it. As an additional note: r"" has *nothing* todo with this, that's just so-called raw string literals which have a different escaping-behavior - thus it's easier to write regexes in them. Diez From cjw at ncf.ca Mon Aug 3 12:04:50 2009 From: cjw at ncf.ca (Colin J. Williams) Date: Mon, 03 Aug 2009 12:04:50 -0400 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: cool-RR wrote: > Hello, > > I wanted to announce that I have just released my little side project, > PythonTurtle. > Here is its website: > http://pythonturtle.com > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > You can read more about it and download it on the website. > > Ram. It looks neat but it's not yet ready for prime time. Colin W. From robert.kern at gmail.com Mon Aug 3 12:24:19 2009 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Aug 2009 11:24:19 -0500 Subject: iterate lines with regex In-Reply-To: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> Message-ID: On 2009-08-01 14:39, Michael Savarese wrote: > > I'm a python newbie and I'm trying to test several regular expressions > on the same line before moving on to next line. > it seems to move on to next line before trying all regular expressions > which is my goal. > it only returns true for first regular expression > does the curser have to be rest to beginning of line? If so, how would I > do that. > remember I'm new > thanks in advance to any advice > Mike S. > > the following is part of my code, > readThis=open('c:/9320.txt','r') > > for line in readThis: > try: > thisKey = key.search(line).group(1) > thisMap = map.search(line).group(1) > thisParcel = parcel.search(line).group(1) > except: > continue What is happening is that either key or map fails to match and trying to get a group raises an exception. This is caught, and the "continue" statement tells the for-loop to go to the next line in readThis. The "continue" statement does not mean "go back to where the error was raised and continue executing as if no error happened". The key to using try: except: properly is to surround as little code as possible. Also, to explicitly state which exceptions you are going to catch. In this case, though, you don't want to use exceptions. You should deal with the match objects that are the result of the .search() method. for line in readThis: key_match = key.search(line) if key_match is not None: this_key = key_match.group(1) # ... do something with this_key map_match = map.search(line) if map_match is not None: this_map = map_match.group(1) # ... do something with this_map parcel_match = parcel.search(line) if parcel_match is not None: this_parcel = parcel_match.group(1) # ... do something with this_parcel -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From wuwei23 at gmail.com Mon Aug 3 12:40:02 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 09:40:02 -0700 (PDT) Subject: Extract the numeric and alphabetic part from an alphanumeric string References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> Message-ID: <3fc2ad25-8af7-452e-aab5-5716064d758f@y28g2000prd.googlegroups.com> Sandhya Prabhakaran wrote: > I have a string as str='123ACTGAAC'. You shouldn't use 'str' as a label like that, it prevents you from using the str() function in the same body of code. > How do I blank out the initial numeric part so as to get just the > alphabetic part. The string is always in the same format. >>> sample = '123ACTGAAC' >>> numer = ''.join(s for s in sample if s.isdigit()) >>> alpha = ''.join(s for s in sample if s.isalpha()) >>> numer, alpha ('123', 'ACTGAAC') If by 'always in the same format' you mean the positions of the numbers & alphas, you could slightly abuse the struct module: >>> import struct >>> sample = '123ACTGAAC' >>> format = '3s7s' # a string of 3 + a string of 7 >>> struct.unpack(format, sample) ('123', 'ACTGAAC') But seriously, you should use slicing: >>> sample = '123ACTGAAC' >>> sample[0:3], sample[3:] ('123', 'CTGAAC') You can also label the slices, which can be handy for self-documenting your code: >>> num = slice(3) >>> alp = slice(4,10) >>> sample[num], sample[alp] ('123', 'CTGAAC') From ram.rachum at gmail.com Mon Aug 3 12:47:43 2009 From: ram.rachum at gmail.com (cool-RR) Date: Mon, 3 Aug 2009 09:47:43 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> On Aug 3, 7:04?pm, "Colin J. Williams" wrote: > cool-RR wrote: > > Hello, > > > I wanted to announce that I have just released my little side project, > > PythonTurtle. > > Here is its website: > >http://pythonturtle.com > > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > > You can read more about it and download it on the website. > > > Ram. > > It looks neat but it's not yet ready for prime time. > > Colin W. I agree there's a lot that can be improved - I wanted to put it out there so I could get feedback and fix the important things first. So I'd appreciate you telling me what you think needs improvement. Ram. From sandhyaprabhakaran at gmail.com Mon Aug 3 12:52:48 2009 From: sandhyaprabhakaran at gmail.com (Sandhya Prabhakaran) Date: Mon, 3 Aug 2009 18:52:48 +0200 Subject: Extract the numeric and alphabetic part from an alphanumeric string In-Reply-To: <1e364c4e0908030849u7583637h9c8d688f8520b904@mail.gmail.com> References: <984623a6-1bfb-4a82-8ec4-000fa68878d6@o32g2000yqm.googlegroups.com> <1e364c4e0908030849u7583637h9c8d688f8520b904@mail.gmail.com> Message-ID: Oh yes indeed........! Now that works :D Thanks a lot !! 2009/8/3 Kushal Kumaran > > On Mon, Aug 3, 2009 at 8:47 PM, Sandhya > Prabhakaran wrote: > > Hi, > > > > I have a string as str='123ACTGAAC'. > > > > I need to extract the numeric part from the alphabetic part which I > > did using > >>>>numer=re.findall(r'\d+',str) > >>>>numer > > 123 > > > > The docs for re.findall say that it returns a list of matches. So > '123' will be numer[0]. > > > To get the alphabetic part, I could do > >>>>alpha=str.replace('123','') > >>>>alpha > > ACTGAAC > > But when I give > >>>>alpha=str.replace(numer,'') > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: expected a character buffer object > > > > That's what would happen if you pass in a list instead of a string to > replace. > > > How do I blank out the initial numeric part so as to get just the > > alphabetic part. The string is always in the same format. > > > > Please help. > > > > -- > kushal > -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at rcn.com Mon Aug 3 12:55:06 2009 From: python at rcn.com (Raymond Hettinger) Date: Mon, 3 Aug 2009 09:55:06 -0700 (PDT) Subject: heapq "key" arguments References: <97932d10-8601-401f-bb69-a98db9036929@p15g2000vbl.googlegroups.com> <1582f82e-34aa-4b66-b989-c9f8351a5f1c@o9g2000prg.googlegroups.com> <4f096546-36a1-4633-9a24-1265ce0929ce@q14g2000vbi.googlegroups.com> Message-ID: <3d2f5ff5-201e-4451-b9e7-fb33652b44a7@d9g2000prh.googlegroups.com> [Duncan Booth] > The documentation doesn't say anything directly about stability, but the > implementation is actually stable. You can probably assume it must be at > least for nlargest and nsmallest otherwise the stated equivalence wouldn't > hold: > > e.g. nsmallest documentation says: > > ? ? ? ? Equivalent to: sorted(iterable, key=key)[:n] Yes. The code for nsmallest and nlargest preserves stability so that the equivalence is maintained. Raymond From wuwei23 at gmail.com Mon Aug 3 12:56:02 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 09:56:02 -0700 (PDT) Subject: Compiling regex inside function? References: Message-ID: Anthra Norell wrote: > def entries (l): > ? ? ? ? r = re.compile ('([0-9]+) entr(y|ies)') > ? ? ? ? match = r.search (l) > ? ? ? ? if match: return match.group (1) > > So the question is: does "r" get regex-compiled once at py-compile time > or repeatedly at entries() run time? The docs say: The compiled versions of the most recent patterns passed to re.match (), re.search() or re.compile() are cached, so programs that use only a few regular expressions at a time needn?t worry about compiling regular expressions. (But they don't say how few is 'only a few'...) If you're concerned about it, you could always set the compiled pattern to a default value in the function's argspec, as that _is_ only executed the once: def entries(line, regex = re.compile('([0-9]+) entr(y|ies)'): match = regex.search(line) ... From nagle at animats.com Mon Aug 3 12:57:08 2009 From: nagle at animats.com (John Nagle) Date: Mon, 03 Aug 2009 09:57:08 -0700 Subject: Help understanding the decisions *behind* python? In-Reply-To: References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> Message-ID: <4a7715ff$0$1641$742ec2ed@news.sonic.net> Dave Angel wrote: > sturlamolden wrote: >> On 20 Jul, 18:27, Phillip B Oldham wrote: >> Tuples are used for passing arguments to and from a function. Common >> use of tuples include multiple return values and optional arguments >> (*args). That's from Mesa, the Xerox PARC language of the 1970s. Mesa used tuples for subroutine arguments in a very straightforward way. Every function took one tuple as an argument, written as parameters in parentheses separated by commas. Every function returned a tuple as an argument. This had a nice symmetry; function outputs and function inputs had the same form. Mesa was the first language to break through the "single return value" syntax problem. Python doesn't go that far. John Nagle From wuwei23 at gmail.com Mon Aug 3 13:02:57 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 10:02:57 -0700 (PDT) Subject: Help understanding the decisions *behind* python? References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> <4a7715ff$0$1641$742ec2ed@news.sonic.net> Message-ID: <686a0fac-b746-488f-9514-a1849fbda94d@g1g2000pra.googlegroups.com> John Nagle wrote: > Every function returned a tuple as an argument. This had a nice > symmetry; function outputs and function inputs had the same form. ? > Mesa was the first language to break through the "single return > value" syntax problem. > > ? ? Python doesn't go that far. I assume here you're referring to the former point and not the latter? From nobody at nowhere.com Mon Aug 3 13:23:06 2009 From: nobody at nowhere.com (Nobody) Date: Mon, 03 Aug 2009 18:23:06 +0100 Subject: Queryable Daemon References: <81F5E933-9140-4269-AA13-FDB34CB9E895@gmail.com> Message-ID: On Sun, 02 Aug 2009 19:36:08 -0600, Michael Torrie wrote: > Another possibility is shared memory segments. I'm not sure how > security is done in this case. Shared memory segments have an owner, group, and the standard ugo=rwx permissions (execute permission is present but ignored); see the shmget(2) and shmctl(2) manpages. But Unix-domain sockets are supported by the standard library, while shared memory would require a separate library, e.g.: http://semanchuk.com/philip/PythonIpc/ Also, there is unlikely to be an advantage to using shared memory in Python. In most cases, you would have to explicitly serialise Python objects into the shared memory region. It's more useful in C, where you can treat the region as a struct which is accessed directly from the program. From python at mrabarnett.plus.com Mon Aug 3 13:29:56 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 03 Aug 2009 18:29:56 +0100 Subject: iterate lines with regex In-Reply-To: References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> Message-ID: <4A771E94.70805@mrabarnett.plus.com> Robert Kern wrote: [snip] > > for line in readThis: > key_match = key.search(line) > if key_match is not None: > this_key = key_match.group(1) > # ... do something with this_key > map_match = map.search(line) > if map_match is not None: > this_map = map_match.group(1) > # ... do something with this_map > parcel_match = parcel.search(line) > if parcel_match is not None: > this_parcel = parcel_match.group(1) > # ... do something with this_parcel > re.search and re.match will return a MatchObject if successful or None if unsuccessful. A MatchObject is always true, so you can simplify to: ... if key_match: this_key = key_match.group(1) # ... do something with this_key ... From python at rcn.com Mon Aug 3 13:36:28 2009 From: python at rcn.com (Raymond Hettinger) Date: Mon, 3 Aug 2009 10:36:28 -0700 (PDT) Subject: heapq "key" arguments References: <97932d10-8601-401f-bb69-a98db9036929@p15g2000vbl.googlegroups.com> Message-ID: [Joshua Bronson]: > According tohttp://docs.python.org/library/heapq.html, Python 2.5 > added an optional "key" argument to heapq.nsmallest and > heapq.nlargest. I could never understand why they didn't also add a > "key" argument to the other relevant functions (heapify, heappush, > etc). The problem is that heapq acts on regular lists, so it does not have exclusive access to the structure. So, there is no reliable way for it to maintain a separate list of keys. Since the keys can't be saved in the structure (without possibly breaking other code), the fine grained heapq functions (like heappop and heappush) would need to call key functions every time they are invoked. This is at odds with the implicit guarantee of the key function that it will be called no more than once per key. The overall problem is one of granularity. A key function should be applied once in an initial pass, not on every call to a push/pop function. The everyday solution that most people use is to operate on a list of (key, record) tuples and let tuple comparison do the work for you. Another solution is to build a Heap class that does have exclusive access to the structure, but the API sugar often isn't worth the slightly weaker performance. One other thought. Heaps are a lazy evaluation structure, so their fined-grained mutation functions only work well with just a single ordering function, so there is not need to have (and every reason to avoid) changing key functions in mid-stream. IOW, the key function needs to be constant across all accesses. Contrast this with other uses of key functions where it makes perfect sense to run minage=min(data, key=attrgetter('age')) and then running minsal=min(data, key=attrgetter('salary')). The flexibility to change key functions just doesn't make sense in the context of the fine-grained heap functions. Accordingly, this is why I put key functions in nlargest() and nsmallest() but not in heappush() and friends. The former can guarantee no more than one key function call per entry and they evaluate immediately instead of lazily. Raymond From duncan.booth at invalid.invalid Mon Aug 3 13:47:05 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Aug 2009 17:47:05 GMT Subject: Compiling regex inside function? References: Message-ID: alex23 wrote: > The docs say: > The compiled versions of the most recent patterns passed to re.match > (), re.search() or re.compile() are cached, so programs that use only > a few regular expressions at a time needn?t worry about compiling > regular expressions. > > (But they don't say how few is 'only a few'...) If you're interested then it isn't all that hard to open up re.py in an editor and see that the cache holds up to 100 items. Of course that's just an implementation detail so other versions might have a different size cache. Also implementation dependant, but it might be worth knowing that when you hit that limit the cache is simply cleared: there's no gradual clearing of the oldest or least used entries. From bcharrow at csail.mit.edu Mon Aug 3 14:26:38 2009 From: bcharrow at csail.mit.edu (Ben Charrow) Date: Mon, 03 Aug 2009 14:26:38 -0400 Subject: urllib2.urlopen timeout In-Reply-To: <4A76AB8F.5090403@yahoo.co.uk> References: <4A76AB8F.5090403@yahoo.co.uk> Message-ID: <4A772BDE.4020602@csail.mit.edu> Zdenek Maxa wrote: > Hi, > > I would like to ask how I should set timeout for a call: > > f = urllib2.urlopen(url) > > > I know that Python 2.6 offers > urllib2.urlopen(url[, data][, timeout]) > which would elegantly solved my problem, but I have to stick to Python 2.5. > There are three solutions that I know about: 1) Make your own little HTTP library and set timeouts for each of your sockets. 2) The same as the above, except use asynchronous sockets and the the select module. 3) If you're on a Unix style system, use the signal module (the example is helpful http://docs.python.org/library/signal.html#example) Here's some code: import urllib2 import signal class TimeoutException(Exception): """SIGALARM was sent to the process""" pass def raise_timeout(signum, frame): raise TimeoutException("Timeout!") signal.signal(signal.SIGALRM, raise_timeout) try: signal.alarm(5) # raise alarm in 5 seconds data = urllib2.urlopen("http://www.google.com").readlines() except TimeoutException, ex: data = None finally: signal.alarm(0) # disable alarm HTH, Ben From sakradevanamindra at gmail.com Mon Aug 3 14:39:24 2009 From: sakradevanamindra at gmail.com (Leo Brugud) Date: Mon, 3 Aug 2009 11:39:24 -0700 (PDT) Subject: Can python do something like the onclick events in javascript ? Message-ID: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> I'm trying to use python to build a simple web page that make use of the onclick behavior, instead of requiring users to click the 'submit' button. I realize in javascript there are onclick, onchange events. Is python capable of doing the same? Thanks in Advance From robert.kern at gmail.com Mon Aug 3 14:44:07 2009 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 03 Aug 2009 13:44:07 -0500 Subject: iterate lines with regex In-Reply-To: <4A771E94.70805@mrabarnett.plus.com> References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> <4A771E94.70805@mrabarnett.plus.com> Message-ID: On 2009-08-03 12:29, MRAB wrote: > Robert Kern wrote: > [snip] >> >> for line in readThis: >> key_match = key.search(line) >> if key_match is not None: >> this_key = key_match.group(1) >> # ... do something with this_key >> map_match = map.search(line) >> if map_match is not None: >> this_map = map_match.group(1) >> # ... do something with this_map >> parcel_match = parcel.search(line) >> if parcel_match is not None: >> this_parcel = parcel_match.group(1) >> # ... do something with this_parcel >> > re.search and re.match will return a MatchObject if successful or None > if unsuccessful. A MatchObject is always true, so you can simplify to: > > ... > if key_match: > this_key = key_match.group(1) > # ... do something with this_key > ... True, but I prefer to maintain a consistent style for None-testing regardless of whether or not I am sure the not-None type will have a suitable __nonzero__ implementation. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From deets at nospam.web.de Mon Aug 3 14:45:14 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 03 Aug 2009 20:45:14 +0200 Subject: Can python do something like the onclick events in javascript ? In-Reply-To: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> References: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> Message-ID: <7dophqF2crpcqU1@mid.uni-berlin.de> Leo Brugud schrieb: > I'm trying to use python to build a simple web page that make use of > the onclick behavior, instead of requiring users > to click the 'submit' button. If that's the only reason, don't use JS for that, it's annoying. > I realize in javascript there are onclick, onchange events. Is python > capable of doing the same? Somewhat, through a python-2-javascript-translation: http://pyjs.org/ Diez From benjamin.kaplan at case.edu Mon Aug 3 14:54:58 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 3 Aug 2009 14:54:58 -0400 Subject: Can python do something like the onclick events in javascript ? In-Reply-To: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> References: <68e15376-75b5-4ad7-afe4-e058e33a427a@p23g2000vbl.googlegroups.com> Message-ID: On Mon, Aug 3, 2009 at 2:39 PM, Leo Brugud wrote: > I'm trying to use python to build a simple web page that make use of > the onclick behavior, instead of requiring users > to click the 'submit' button. > > I realize in javascript there are onclick, onchange events. Is python > capable of doing the same? > It depends. Python is usually used as a server-side language while Javascript is client-side. The client's web browser requests a web page, your program processes that request and sends the client a web page. That web page can contain anything you want, including Javascript. Your python program never hears from that client again until the *client* initiates contact, be it through a submit button or a javascript event that submits an HTTP request. You'll have to add the onclick and onchange code to the resulting web page, using Javascript, because Python never handles sending the request, jsut receiving it. Of course, this isn't the case if you are using something like pyjs, which compiles Python code to Javascript, your code will be running as Javascript code and not Python code. > > Thanks in Advance > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From saimapk81 at gmail.com Mon Aug 3 15:01:51 2009 From: saimapk81 at gmail.com (saima81) Date: Mon, 3 Aug 2009 12:01:51 -0700 (PDT) Subject: "MAGZINES IN URDU" "PAKISTANI MAGZINES" PAKISTAN" "PAKISTAN" "PAKISTANI NEWSPAPERS" "tHE eXPRTESS" "JANG NEWS" "WAQT" "DAWN" ON www.pak-web-pages.blogspot.com Message-ID: <054ce11f-597a-4c6e-b130-68a3bee4ad1b@i18g2000pro.googlegroups.com> "MAGZINES IN URDU" "PAKISTANI MAGZINES" PAKISTAN" "PAKISTAN" "PAKISTANI NEWSPAPERS" "tHE eXPRTESS" "JANG NEWS" "WAQT" "DAWN" ON www.pak-web-pages.blogspot.com From sam at tregar.com Mon Aug 3 15:11:38 2009 From: sam at tregar.com (Sam Tregar) Date: Mon, 3 Aug 2009 15:11:38 -0400 Subject: Online payment module Message-ID: Hello all. I'm considering building a module to provide a cross-payment-gatewat API for making online payments. In the Perl world we have a module like this called Business::OnlinePayment ( http://search.cpan.org/~jasonk/Business-OnlinePayment-2.01/OnlinePayment.pm). Is there anything like this in Python? My searches so far haven't turned up anything. If I don't find one I'll probably build one, covering PayPal and Authorize.net to start. If anyone is interested in discussing the project and/or getting involved shoot me an email. Thanks, -sam -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Mon Aug 3 15:21:57 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 03 Aug 2009 12:21:57 -0700 Subject: .dbf tables and Null In-Reply-To: <2f4d5719-6ca8-4ef2-8734-420b3044b1dc@l35g2000pra.googlegroups.com> References: <2f4d5719-6ca8-4ef2-8734-420b3044b1dc@l35g2000pra.googlegroups.com> Message-ID: <4A7738D5.3010009@stoneleaf.us> John Machin wrote: > On Aug 1, 3:41 am, Ethan Furman wrote: > >>Mornin'! and a good one, too, I hope. >> >>Question for you... >> >>First part of the question: What is the general value in having Null >>capability for fields? > > > In general, in any database system, so that one can distinguish > between "the customer has no 'middle name'" ('') and "the customer's > 'middle name' is unknown" (NULL). > > >>Second part: Is there a tangible difference between Null, and the >>nothing of 0, '', False, etc, in python? > > > 0 is the zero thing, it is not nothing. False is not nothing. > > > >>Third part: If there is a tangible difference, do those of us who use >>python and these old, refuse-to-die, .dbf files actually have need of, >>or have tables including, Null values? >> >>P.S. part (for John Machin, if he sees this ;) >>Will the dbf package you are working on support Null values? > > > My philosophy when digging stuff out of arcane storages is to expose > what is found and leave any kludging/sanitising to the next layer. > > For example, None is returned for an N (Number) field that's all > spaces; it's up to the caller to decide whether to treat None as zero, > raise an exception, pop up a data-collection dialogue box, ... > > If you mean specifically the Visual Foxpro v3 _NullFlags hack, yes, it > already supports that, as well as the VFP9 abuse of that hack for > Varchar and Varbinary fields :-) Thank you. It's been an interesting journey learning Python. Probably the two most difficult concepts for me to really internalize have been "batteries included" (thank you for the pointer to struct!) (I finally 'found' and incorporated array into my dbf module), and "everything is an object, even functions!". The unittest module worked wonderfully in making sure everything still worked after switching over to array as well, and the 30+% speed-up is also nice! :) All in all, I *love* Python! ~Ethan~ From no.email at please.post Mon Aug 3 15:59:23 2009 From: no.email at please.post (kj) Date: Mon, 3 Aug 2009 19:59:23 +0000 (UTC) Subject: kw param question Message-ID: I want to write a decorator that, among other things, returns a function that has one additional keyword parameter, say foo=None. When I try def my_decorator(f): # blah, blah def wrapper(*p, foo=None, **kw): x = f(*p, **kw) if (foo): # blah, blah else # blah blah return wrapper ...i get a syntax error where it says "foo=None". I get similar errors with everything else I've tried. Is is possible to do this in Python? TIA! kynn From hjtoi-better-remove-before-reply at comcast.net Mon Aug 3 16:08:37 2009 From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen) Date: Mon, 03 Aug 2009 13:08:37 -0700 Subject: M2Crypto: X509.X509_Extension_Stack() throws AssertionError References: Message-ID: Matthias G?ntert wrote: > Why is the following code snippet throwing an AssertionError? Is that > behavior a bug within X509.X509_Extension_Stack()? How would you suggest > popping every element from the stack? > > cert_extension_2 = X509.new_extension("keyUsage", "101000000") Maybe your OpenSSL is too old. keyUsage needs to be defined in OpenSSL obj_dat.h file for this to work. > cert_extension_3 = X509.new_extension("subjectAlternativeName", > "DNS:www.mydomain.tld") And I believe you mispelled this, try subjectAltName. With the change in spelling for subjectAltName your test passes for me using OpenSSL 1.0.0beta3 and M2Crypto 0.20beta with the (still incomplete) patch to make M2Crypto work with OpenSSL 1.0: https://bugzilla.osafoundation.org/show_bug.cgi?id=12855 -- Heikki Toivonen - http://heikkitoivonen.net From marduk at letterboxes.org Mon Aug 3 16:27:34 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Mon, 03 Aug 2009 16:27:34 -0400 Subject: kw param question In-Reply-To: References: Message-ID: <1249331254.1179.7.camel@brotherus.corp.redhat.com> On Mon, 2009-08-03 at 19:59 +0000, kj wrote: > > I want to write a decorator that, among other things, returns a > function that has one additional keyword parameter, say foo=None. > > When I try > > def my_decorator(f): > # blah, blah > def wrapper(*p, foo=None, **kw): > x = f(*p, **kw) > if (foo): > # blah, blah > else > # blah blah > return wrapper > > ...i get a syntax error where it says "foo=None". I get similar > errors with everything else I've tried. > Not exactly sure what you're trying to do.. but, regular arguments must be used *before* positional and keyword arguments so the definition: def wrapper(*p, foo=None, **kw): is syntactically incorrect whereby the following is correct: def wrapper(foo=None, *p, **kw): But if what you are wanting is to actually add 'foo' to kw then I would do this: def my_decorator(f): # blah, blah def wrapper(*p, **kw): if 'foo' not in kw: kw['foo'] = None x = f(*p, **kw) if kw['foo']: # blah blah else: # blah blah return wrapper From rt8396 at gmail.com Mon Aug 3 16:35:51 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 13:35:51 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> Message-ID: Hello, I wanted to announce that I have just released my little side project, PythonTurtle. [snip] I think it looks great --haven't download the source yet-- but i really like the screenshot. This will be more "inviting" to the new, inexperianced users. I like the idea of packaging up the command prompt and the canvas into one very friendly interface. I especially like that you are using a "real" turtle. I can remember the first time i used turtle (in python stdlib) and i kept saying to myself... "Were the heck is this damn turtle?!?!" (>_<) :-) From bartsmeets86 at gmail.com Mon Aug 3 16:39:44 2009 From: bartsmeets86 at gmail.com (Bart Smeets) Date: Mon, 3 Aug 2009 22:39:44 +0200 Subject: easy_install: unresolved external symbol Message-ID: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> Hello, I keep getting errors when trying to use easy_install to install bbfreeze or cxfreeze (same errors). This is the output: http://pastebin.com/m65ba474d The error message unresolved external symbol keeps popping up. I have no idea how to solve this. Can anyone give me a hint? Thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From wells at submute.net Mon Aug 3 16:47:23 2009 From: wells at submute.net (Wells Oliver) Date: Mon, 3 Aug 2009 15:47:23 -0500 Subject: Ordering of dict keys & values Message-ID: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> I understand that the keys in a dictionary are ordered not randomly but something practically close to it, but if I create a SQL query like so: query = 'INSERT INTO Batting (%s) VALUES(%s)' % (','.join(stats.keys()), ','.join(stats.values())) Can I at least rely on the value being in the same index as its corresponding key? -- Wells Oliver wells at submute.net -------------- next part -------------- An HTML attachment was scrubbed... URL: From dciphercomputing at gmail.com Mon Aug 3 16:55:13 2009 From: dciphercomputing at gmail.com (Simon) Date: Mon, 3 Aug 2009 13:55:13 -0700 (PDT) Subject: Newbie Question regarding __init__() References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> Message-ID: <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> On Aug 2, 5:51?am, Dave Angel wrote: > Simon wrote: > > Okay I will fix my code and include "self" and see what happens. ?I > > know I tried that before and got another error which I suspect was > > another newbie error. > > > The idea behind the init_Pre is that I can put custom code here to > > customize the __init__ instead of creating a new subclass. ?This kind > > of hook pattern allows you to flatten your inheritance hierarchy. ?I > > can choose in the init_Pre method to execute code before the init_exec > > (which contains the default __init__ code) and still execute the > > init_Exec method or I can completely customize the entire __init__ by > > returning False from init_Pre and prevent the init_Exec from being > > called. ?I use this type of pattern with almost all my methods. ?In > > this way I can create a less complicated inheritance chain but still > > have have custom code when needed without sub-classing. > > > I am use to Visual FoxPro which where you can do > > > =is.init_Pre().And.This.init_Exec() and the result is discarded so > > that is why it looks the way it does. ?In this form init_Exec has to > > return a value. ?However, If self.init_Pre(): self.init_Exec() would > > work the same and then I could avoid returning a value. > > > Thanks, > > Simon > > > On Aug 1, 5:52 am, Dave Angel wrote: > > >> Nat Williams wrote: > > >>> As MRAB described, ALL instance methods need to accept 'self' as a first > >>> parameter, as that will be passed to them implicitly when they are called. > >>> This includes __init__. ?The name 'self' is just a commonly accepted > >>> convention for the name of the instance object passed to methods. ?You don't > >>> have to call it that, but you really should. > > >>> Take a look athttp://docs.python.org/tutorial/classes.html#class-objects > >>> It might help shed some light on how methods and instances work. > > >>> One other thing. ?I'm a little confused by the first line of > >>> dcObject.__init__: > > >>> self.init_Pre() and self.init_Exec() > > >>> I suspect this does not do what you think it does. ?init_Pre and init_Exec > >>> will both be called by this expression (unless init_Pre throws an exception, > >>> of course). ?You're not getting anything here that you wouldn't by just > >>> calling each method on a separate line, except just making it harder to > >>> read. > > >> Read the doc-string for init_Pre() and for init_Exec(). ?The final > >> version of init_Pre() will return False in some circumstances, and in > >> those circumstances Simon doesn't want init_Exec() to be called. ?He's > >> deliberately using the short-circuit evaluation of ?'and' ?to accomplish > >> that. > > >>> On Fri, Jul 31, 2009 at 8:53 PM, Simon wrote: > > >>>> Hi > > >>>> So should the dcObject class include the "self" as well since I have > >>>> not defined an __init__ method in dcCursor? > > >>>> Simon > > >>>> -- > >>>>http://mail.python.org/mailman/listinfo/python-list > > >> Every one of those methods in both of those classes need a "self" first > >> argument. ?As others have said, all instance methods need a 'self.' > > (Please don't top-post. ?You should put new responses at the end of > quoted text, or sometimes inline if that's clearer.) > > I don't understand your comparison to Foxpro. ?read on. > > As your code was last posted, you don't need a return value from > init_Exec() ?Every function that doesn't have an explicit return will > return None. ?And None is interpreted as False in an "and" expression. ? > If you had an "if" around the whole thing, then you'd care. > > DaveA All I meant by the FoxPro comment was the idea of using the equal sign without a variable to throw away the result. Also in FoxPro there is no such thing as automatically returning None. If there is no explicit return then True is returned. Thanks I did not know that None is interpreted as False. Simon From no.email at please.post Mon Aug 3 16:58:46 2009 From: no.email at please.post (kj) Date: Mon, 3 Aug 2009 20:58:46 +0000 (UTC) Subject: kw param question References: Message-ID: In Albert Hopkins writes: >On Mon, 2009-08-03 at 19:59 +0000, kj wrote: >> >> I want to write a decorator that, among other things, returns a >> function that has one additional keyword parameter, say foo=None. >> >> When I try >> >> def my_decorator(f): >> # blah, blah >> def wrapper(*p, foo=None, **kw): >> x = f(*p, **kw) >> if (foo): >> # blah, blah >> else >> # blah blah >> return wrapper >> >> ...i get a syntax error where it says "foo=None". I get similar >> errors with everything else I've tried. >> >Not exactly sure what you're trying to do.. Yeah, I wasn't too clear. I figured out how to do what I wanted to do: def my_decorator(f): # blah, blah def wrapper(*p, **kw): foo = kw.pop('force', None) x = f(*p, **kw) if (foo): # blah, blah else # blah blah return wrapper Now the definitions of the original functions do not include the foo=None argument, but "actual" functions (i.e. the ones generated by the decorator) all accept the optional foo parameter. The only remaining problem is how to document this... I don't see how pydoc could possibly figure this one out. I guess this is sufficient argument to abandon this idea. Bummer. kynn From pavlovevidence at gmail.com Mon Aug 3 17:04:12 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Aug 2009 14:04:12 -0700 (PDT) Subject: iterate lines with regex References: <75c8645a0908011239q54292379tb02ff4de364839af@mail.gmail.com> <4A771E94.70805@mrabarnett.plus.com> Message-ID: <463f3ea4-c8a4-405b-9eab-95a878684db0@a13g2000yqc.googlegroups.com> On Aug 3, 11:44?am, Robert Kern wrote: > On 2009-08-03 12:29, MRAB wrote: > > > > > > > Robert Kern wrote: > > [snip] > > >> for line in readThis: > >> key_match = key.search(line) > >> if key_match is not None: > >> this_key = key_match.group(1) > >> # ... do something with this_key > >> map_match = map.search(line) > >> if map_match is not None: > >> this_map = map_match.group(1) > >> # ... do something with this_map > >> parcel_match = parcel.search(line) > >> if parcel_match is not None: > >> this_parcel = parcel_match.group(1) > >> # ... do something with this_parcel > > > re.search and re.match will return a MatchObject if successful or None > > if unsuccessful. A MatchObject is always true, so you can simplify to: > > > ... > > if key_match: > > this_key = key_match.group(1) > > # ... do something with this_key > > ... > > True, but I prefer to maintain a consistent style for None-testing regardless of > whether or not I am sure the not-None type will have a suitable __nonzero__ > implementation. There's one thing to keep in mind. In the unknown future, it's possible that re.match could be changed to return an object with a false value that contains some information about the reason for failure, or partial match information, or something like that. If that happens, code like: if m: will continue to work, while code like if m is not None: will suddenly fail. Granted, it's not likely to happen for regexps but it could happen in similar situations in other places. I am one of the biggest critics of implicit boolean values, but given that Python has it, I think it is best to adhere strongly idiomatic uses like regexps. Carl Banks From sturlamolden at yahoo.no Mon Aug 3 17:04:53 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 3 Aug 2009 14:04:53 -0700 (PDT) Subject: Is python buffer overflow proof? References: Message-ID: On 2 Aug, 15:50, Jizzai wrote: > Is a _pure_ python program buffer overflow proof? > > For example in C++ you can declare a char[9] to hold user input. > If the user inputs 10+ chars a buffer overflow occurs. Short answer: NO Bounds checking on sequence types is a protection against buffer overflow, but is certainly not sufficient. The Python interpreter is written in C. Python extension modules are written in C (or something similar). If you find an unprotected buffer in this C code, you can possibly overflow this buffer. This can be used for nasty things like corrupting the stack and injecting malicious code. There is a reason why the Python sandbox (rexec and Bastion modules) was disabled in Python 2.3. IronPython and Jython provides better protection against buffer overflow than CPython, as these interpreters are written in safer languages (C# and Java). You thus get an extra layer of protection between the Python code and the unsafe C (used in JVM and .NET runtimes). From no.email at please.post Mon Aug 3 17:07:32 2009 From: no.email at please.post (kj) Date: Mon, 3 Aug 2009 21:07:32 +0000 (UTC) Subject: no-clobber dicts? Message-ID: I use the term "no-clobber dict" to refer to a dictionary D with the especial property that if K is in D, then D[K] = V will raise an exception unless V == D[K]. In other words, D[K] can be set if K doesn't exist already among D's keys, or if the assigned value is equal to the current value of D[K]. All other assignments to D[K] trigger an exception. The idea here is to detect inconsistencies in the data. This is a data structure I often need. Before I re-invent the wheel, I thought I'd ask: is it already available? TIA! kynn From aurele.tux at gmail.com Mon Aug 3 17:11:20 2009 From: aurele.tux at gmail.com (aurelien) Date: Mon, 03 Aug 2009 23:11:20 +0200 Subject: Hello to the community Message-ID: <1249333880.7712.20.camel@r2d2> Hello to the Python community ! I'm a totaly newbbie in this langage. I hope i will learn a lot with you. Thanks. aurelien From boris.arloff at yahoo.com Mon Aug 3 17:25:06 2009 From: boris.arloff at yahoo.com (Boris Arloff) Date: Mon, 3 Aug 2009 14:25:06 -0700 (PDT) Subject: Trying to get ABC to work Message-ID: <358094.5069.qm@web65302.mail.ac2.yahoo.com> Hi, ? Looking for ideas on getting Abstract Base Classes to work as intended within a metaclass. ? I was wondering if I could use an abc method within a metaclass to force a reimplementation when a class is instantiated from the metaclass.? It seems like I cannot do so.? I implemented the following test case: ? import abc class MetaExample(type): ? def __init__(cls, name, bases, ns): ??? setattr(cls, 'cls_meth', cls.cls_meth)??? # cls method as instance method ??? setattr(cls, 'cls_abc', cls.cls_abc)????????# abc cls method as instance method ? ? def cls_meth(cls): ??? print('Class method defined stub') ? ? @abc.abstractmethod ? def cls_abc(cls): ??? try: ????? print('Class-Abstract method defined stub') ??? except NotImplementedError, err: ????? print('Must implement cls_abc.') ??? except: ????? print('General exception at cls_abc method.') ? Then I create class MyKlass from the metaclass and instantiate it as myklass: MyKlass(object): __metaclass__ = MetaExample myklass = MyKlass() myklass.cls_meth()?? --> prints "Class method defined stub" myklass.cls_abc()???? --> prints "Class-Abstract method defined stub" ? I was hopping for myklass.cls_abc() to print "Must implement cls_abc." ? However, this makes sense since?MyKlass implements from the metaclass the cls_abc method and?there will never be an abstraction?of this method. ? Any ideas on how to get this done?? Any way I could define an abstract method within a metaclass and have it behave?with abstraction when the class is created off the metaclass? ? I other words, I want to force an implementation of cls_abc() method when MyKlass(object): __metaclass__ = MetaExample is declared, or else get NotImplementedError exception. ? Thanks, Boris Arloff ? -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Mon Aug 3 17:25:18 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 Aug 2009 14:25:18 -0700 Subject: Ordering of dict keys & values In-Reply-To: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> References: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> Message-ID: <50697b2c0908031425i22fd02ffjde3e41a697eb1c30@mail.gmail.com> On Mon, Aug 3, 2009 at 1:47 PM, Wells Oliver wrote: > I understand that the keys in a dictionary are ordered not randomly but > something practically close to it, but if I create a SQL query like so: > > query = 'INSERT INTO Batting (%s) VALUES(%s)' % (','.join(stats.keys()), > ','.join(stats.values())) > > Can I at least rely on the value being in the same index as its > corresponding key? Yes. Per http://docs.python.org/library/stdtypes.html#dict.items : """ Note: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary?s history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): pairs = zip(d.values(), d.keys()). """ Cheers, Chris -- http://blog.rebertia.com From Samnsparky at gmail.com Mon Aug 3 17:29:05 2009 From: Samnsparky at gmail.com (Sparky) Date: Mon, 3 Aug 2009 14:29:05 -0700 (PDT) Subject: WindowsError: exception: access violation writing 0x00000000 Message-ID: <73c6c4f5-a00b-4f95-a85d-0f257b2f001a@c2g2000yqi.googlegroups.com> Hello! I am using cTypes on Windows to interface with a dll and I keep getting an error when I execute this method: def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0): """ Name: U12.eAnalogIn(channel, idNum = None, demo = 0, readD=0) Args: See section 4.4 of the User's Guide Desc: This is a simplified version of Counter. Reads & resets the counter (CNT). """ if idNum is None: idNum = self.id ljid = ctypes.c_long(idNum) state = ctypes.c_long(999) ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, readD, ctypes.byref(state)) if ecode != 0: raise LabJackException(ecode) if ljid == -1: raise LabJackException(-1, "LabJack not found.") return {"idnum":ljid.value, "state":state.value} Here is the error message: Traceback (most recent call last): File "", line 1, in device.eDigitalIn(0) File "C:\Documents and Settings\All Users\Documents\Python \LabJackPython_new\u12.py", line 118, in eDigitalIn ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, readD, ctypes.byref(state)) WindowsError: exception: access violation writing 0x00000000 Here is the signature of the method (which is known to work with C++ programs): long _stdcall EDigitalIn(long *idnum, long demo, long channel, long readD, long *state); staticLib is declared with staticLib = ctypes.windll.LoadLibrary ("ljackuw"). Any ideas? Thanks, Sam From rt8396 at gmail.com Mon Aug 3 17:47:54 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 14:47:54 -0700 (PDT) Subject: no-clobber dicts? References: Message-ID: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> On Aug 3, 4:07?pm, kj wrote: > I use the term "no-clobber dict" to refer to a dictionary D with > the especial property that if K is in D, then > > ? D[K] = V > > will raise an exception unless V == D[K]. ?In other words, D[K] > can be set if K doesn't exist already among D's keys, or if the > assigned value is equal to the current value of D[K]. ?All other > assignments to D[K] trigger an exception. > > The idea here is to detect inconsistencies in the data. > > This is a data structure I often need. ?Before I re-invent the > wheel, I thought I'd ask: is it already available? > > TIA! > > kynn Not sure if something like this already exists, but it would be trivial to implement by overriding dict.__setitem__() badda-bing baby! From clp2 at rebertia.com Mon Aug 3 18:00:14 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 3 Aug 2009 15:00:14 -0700 Subject: no-clobber dicts? In-Reply-To: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: <50697b2c0908031500w23af3271y49ef3aab49a67695@mail.gmail.com> On Mon, Aug 3, 2009 at 2:47 PM, r wrote: > On Aug 3, 4:07?pm, kj wrote: >> I use the term "no-clobber dict" to refer to a dictionary D with >> the especial property that if K is in D, then >> >> ? D[K] = V >> >> will raise an exception unless V == D[K]. ?In other words, D[K] >> can be set if K doesn't exist already among D's keys, or if the >> assigned value is equal to the current value of D[K]. ?All other >> assignments to D[K] trigger an exception. >> >> The idea here is to detect inconsistencies in the data. >> >> This is a data structure I often need. ?Before I re-invent the >> wheel, I thought I'd ask: is it already available? >> >> TIA! >> >> kynn > > Not sure if something like this already exists, but it would be > trivial to implement by overriding dict.__setitem__() That is, if you don't care about .update() not preserving the invariant. Otherwise, one will need to look at the UserDict module. Cheers, Chris -- http://blog.rebertia.com From ram.rachum at gmail.com Mon Aug 3 18:03:31 2009 From: ram.rachum at gmail.com (cool-RR) Date: Mon, 3 Aug 2009 15:03:31 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> Message-ID: On Aug 3, 11:35?pm, r wrote: > Hello, > I wanted to announce that I have just released my little side > project, > PythonTurtle. > [snip] > > I think it looks great --haven't download the source yet-- but i > really like the screenshot. This will be more "inviting" to the new, > inexperianced users. I like the idea of packaging up the command > prompt and the canvas into one very friendly interface. ?I especially > like that you are using a "real" turtle. > > I can remember the first time i used turtle (in python stdlib) and i > kept saying to myself... > > ? ? "Were the heck is this damn turtle?!?!" (>_<) > > :-) Thanks for the compliments; The things you mentioned you liked are all things that I was specifically thinking about when I decided to make PythonTurtle. Well, maybe minus the screenshot :) From victorsubervi at gmail.com Mon Aug 3 18:05:13 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 3 Aug 2009 18:05:13 -0400 Subject: RE Question In-Reply-To: References: <4dc0cfea0908021422x43972682ra58c53a2a43351ee@mail.gmail.com> Message-ID: <4dc0cfea0908031505t571b8d4cqa28579ae14c9209a@mail.gmail.com> That worked. Thank you again :) Victor On Mon, Aug 3, 2009 at 12:13 AM, Gabriel Genellina wrote: > En Sun, 02 Aug 2009 18:22:20 -0300, Victor Subervi < > victorsubervi at gmail.com> escribi?: > > > How do I search and replace something like this: >> aLine = re.sub('[<]?[p]?[>]?> a-zA-Z0-9"\'=:]*>[<]?[b]?[>]?', '', aLine) >> where RE *only* looks for the possibility of "

" at the beginning of the >> string; that is, not the individual components as I have it coded above, >> but >> the entire 3-character block? >> > > An example would make it more clear; I think you want to match either > "

" is > optional. Use a normal group or a non-capturing group: > r'(

)? > That said, using regular expressions to parse HTML or XML is terribly > fragile; I'd use a specific tool (like BeautifulSoup, ElementTree, or lxml) > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From darkneter at gmail.com Mon Aug 3 18:14:41 2009 From: darkneter at gmail.com (NighterNet) Date: Mon, 3 Aug 2009 15:14:41 -0700 (PDT) Subject: socket policy flash help References: <04e26f53-5f51-476d-823e-47bfeed9b2a8@m7g2000prd.googlegroups.com> <8bede581-f260-4c69-abf0-1e8071380b76@z4g2000prh.googlegroups.com> <7e6cdc26-bcc0-4503-b7b4-9ad80b1041f6@v37g2000prg.googlegroups.com> Message-ID: On Aug 2, 12:25?pm, Piet van Oostrum wrote: > >>>>> NighterNet (N) wrote: > >N> Here the full code. > >N> flashpolicy.xml > >N> [[[ > >N> > >N> > >N> ? ? > >N> > >N> ]]] > >N> flashpolicytest_server3x.py > >N> [[[ > >N> #!/usr/local/bin/python > >N> ''' > >N> Still under testing... > >N> python version 3.x.x > >N> ''' > >N> importsocket > >N> import threading > >N> import sys > >N> import os > >N> file_name = 'flashpolicy.xml' > >N> fh = open(file_name, "r") > >N> policy = fh.read(10001) > > You never use that variable. > > > > >N> host = ''; #out side network > >N> port = 5555; > >N> print ("# ?------------- Init... ------------- ?#"); > >N> class ClientThread (threading.Thread): > >N> ? ? ? global policy; > >N> ? ? ? allClients = []; > >N> ? ? ? vlock = threading.Lock(); > >N> ? ? ? id = 0 # next available thread number > >N> ? ? ? def __init__(self,clientSocket): > >N> ? ? ? ? ? ? ? threading.Thread.__init__(self) > >N> ? ? ? ? ? ? ? self.sockfd = clientSocket; #socketclient > >N> ? ? ? ? ? ? ? self.name = ''; > >N> ? ? ? ? ? ? ? ClientThread.id += 1 > >N> ? ? ? ? ? ? ? self.id = ClientThread.id > >N> ? ? ? ? ? ? ? self.nickName = ''; > >N> ? ? ? ? ? ? ? self.allClients.append(self.sockfd); > >N> ? ? ? def sendAll(self,buff): > >N> ? ? ? ? ? ? ? for index,clientSock in enumerate(self.allClients): > >N> ? ? ? ? ? ? ? ? ? ? ? try: > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? clientSock.send(buff); > > There is no guarantee that send will indeed transmit all of buff. It is > better to use clientSock.sendall(buff). Or you should check the return > value of send and check if it is equal to the length of buff. And repeat > if not. (But sendall is easier). > > Also don't use ; at the end of the statement. It's not pythonic. > > >N> ? ? ? ? ? ? ? ? ? ? ? except (socket.error): > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ('errorsocket%s\n',index,"| clean"); > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? clientSock.close() > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? del self.allClients[index] > >N> ? ? ? def run(self): > >N> ? ? ? ? ? ? ? while True: > >N> ? ? ? ? ? ? ? ? ? ? ? buff = self.sockfd.recv(1028); > > There is no guarantee that recv will get the whole message. It may even > get as little as 1 byte. So you should check the return value of recv. > The official way is to keep reading until you have enough input or until > you hit end of file. > > >N> ? ? ? ? ? ? ? ? ? ? ? if not buff: > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ("connect close...(client side)"); > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.sockfd.close(); > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? break #incase it loop infinite > >N> ? ? ? ? ? ? ? ? ? ? ? if str(buff) == str("b\'\\x00\'"): > > What you check here is whether buff contains the byte sequence that starts with a > b, then a ' ... and ending with the 5 bytes \ x 0 0 ' which is wrong. > > Actually it should be: > > if buff == b\'\x00': > or > if buff == b\'\0': > > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ('policy FOUND >>> sending...') > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print(buff) > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? b = b' >N> from domain=\"*\" to-ports=\"*\" />' > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print (b) > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.sockfd.send(b); > >N> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? self.sockfd.sendall(b); > > Only self.sockfd.sendall; delete the line with self.sockfd.send(b). And > remove the semicolons for esthetical reasons. > > >N> Some odd reason I can't send flash policy from python to flashsocket > >N> to agrees with the connection. > > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org thanks it help. I was not sure about the format most the time. From nagle at animats.com Mon Aug 3 18:19:22 2009 From: nagle at animats.com (John Nagle) Date: Mon, 03 Aug 2009 15:19:22 -0700 Subject: Obtaining Python version Message-ID: <4a776184$0$1611$742ec2ed@news.sonic.net> This works, but it seems too cute: >>> pyver = map(int,sys.version.split()[0].split('.')) >>> print(pyver) [2, 6, 1] Is it guaranteed that the Python version string will be in a form suitable for that? In other words, does "sys.version" begin N.N.N other stuff in all versions, and will it stay that way? Are there ever non-numeric versions, like "3.2.rc1"? John Nagle From rhodri at wildebst.demon.co.uk Mon Aug 3 18:24:04 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 03 Aug 2009 23:24:04 +0100 Subject: fast video encoding In-Reply-To: <0c8cfac7-0a70-4e1f-90ec-19e9c45cae89@h21g2000yqa.googlegroups.com> References: <570097d0-2b2a-4705-892f-0d0154d69d63@b14g2000yqd.googlegroups.com> <0c8cfac7-0a70-4e1f-90ec-19e9c45cae89@h21g2000yqa.googlegroups.com> Message-ID: On Sun, 02 Aug 2009 03:44:17 +0100, sturlamolden wrote: > On 29 Jul, 10:14, gregorth wrote: > >> for a scientific application I need to save a video stream to disc for >> further post processing. > > I have worked a bit on this as well. There are two things that make > scientific applications different form common video encoding: > > First, a scientific video stream is often very different from a > 'movie': There are usually very little 'movement'. For example, when I > have filmed a mouse swimming in a water maze (a pool of milky white > water), the only thing that moves is the rat. So I could achieve > excellent compression just by saving the pixels that changed. These are referred to as P-frames; any encoder that gets further than the most basic version of any video protocol will do this for you. Unfortunately, water pixels change a lot from frame to frame, even when the camera is static, so it doesn't gain you as much as you might hope in cases like you mention. > Second, scientific data should be stored with lossless compression if > possible. If data storage is no object, be my guest. Of course, you're going to have to write your own codecs for this, since pretty much every video protocol in existence is lossy. In reality, lossless compression isn't necessary. As long as your quantisation isn't completely up the spout, the added precision isn't actually going to gain you anything unless you're working in very specialised situations; even then, if it does make a significant difference then you needed greater resolution anyway. -- Rhodri James *-* Wildebeest Herder to the Masses From andre.roberge at gmail.com Mon Aug 3 18:32:10 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 3 Aug 2009 15:32:10 -0700 (PDT) Subject: Obtaining Python version References: <4a776184$0$1611$742ec2ed@news.sonic.net> Message-ID: <680573fa-6d5a-46eb-b48e-461841b8d887@c1g2000yqi.googlegroups.com> On Aug 3, 7:19?pm, John Nagle wrote: > This works, but it seems too cute: > > ?>>> pyver = map(int,sys.version.split()[0].split('.')) > ?>>> print(pyver) > [2, 6, 1] > You can also do: >>> import sys >>> sys.version_info (2, 5, 2, 'final', 0) or >>> sys.version_info[:3] (2, 5, 2) > Is it guaranteed that the Python version string will be in a form > suitable for that? ?In other words, does "sys.version" begin > > N.N.N other stuff > > in all versions, and will it stay that way? ?Are there ever > non-numeric versions, like "3.2.rc1"? > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle I strongly suspect that sys.version_info would never change... Andr? From rt8396 at gmail.com Mon Aug 3 18:34:53 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 15:34:53 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> Message-ID: <491ed6e7-08dd-4b26-acb8-38da475491ed@b14g2000yqd.googlegroups.com> On Aug 3, 5:03?pm, cool-RR wrote: [snip] > Thanks for the compliments; The things you mentioned you liked are all > things that I was specifically thinking about when I decided to make > PythonTurtle. Well, maybe minus the screenshot :) I *may* get roasted for this comment, but i think a turtle module along the lines of what you have here would better serve the stdlib. The current implementation is great, but the whole purpose of turtle is to help children or non-programmers get a feel of the language in a very, very, simple and fun way. Your app is presented in much the same way as any over-the-counter windows app any non-programmer has seen before making them *feel* a little more comfortable. [warning wild speculations ahead!!] I just guessing here, but i'll bet many of these *noobs* have found the current turtle just a wee-bit more advanced than they can handle, and *some* have been scared off. I would also venture to say a key-map of sorts that is available thru the help menu where one could push an "Up" button, or a "rotate" button, and have the proper command inserted in the prompt, and then have the command execute, may also help make the connections here, a sort of *real* Visual Basic programming -- sorry Microsoft :P From zuo at chopin.edu.pl Mon Aug 3 18:35:50 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 04 Aug 2009 00:35:50 +0200 Subject: Obtaining Python version In-Reply-To: <4a776184$0$1611$742ec2ed@news.sonic.net> References: <4a776184$0$1611$742ec2ed@news.sonic.net> Message-ID: 04-08-2009 o 00:19:22 John Nagle wrote: > This works, but it seems too cute: > > >>> pyver = map(int,sys.version.split()[0].split('.')) > >>> print(pyver) > [2, 6, 1] > > Is it guaranteed that the Python version string will be in a form > suitable for that? In other words, does "sys.version" begin > > N.N.N other stuff > > in all versions, and will it stay that way? Are there ever > non-numeric versions, like "3.2.rc1"? Why not to use: sys.version_info "A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial. All values except releaselevel are integers; the release level is 'alpha', 'beta', 'candidate', or 'final'. The version_info value corresponding to the Python version 2.0 is (2, 0, 0, 'final', 0)." http://docs.python.org/library/sys.html#sys.version_info Cheers, *j -- Jan Kaliszewski (zuo) From keith at nekotaku.com Mon Aug 3 18:54:15 2009 From: keith at nekotaku.com (KB) Date: Mon, 3 Aug 2009 15:54:15 -0700 (PDT) Subject: Problem with reading CSV file from URL, last record truncated. Message-ID: <0996356d-ee7d-4a5e-9c0c-9f9502c01892@l5g2000pra.googlegroups.com> Hi, I am trying to download from a URL, a CSV using the following: import re import urllib, urllib2, cookielib import mechanize import csv import numpy import os def return_ranking(): cj = mechanize.MSIECookieJar(delayload=True) cj.load_from_registry() # finds cookie index file from registry # set things up for cookies opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) reply = opener.open('http://ichart.finance.yahoo.com/table.csv? s=CSCO&a=00&b=01&c=2009&d=01&e=2&f=2010&g=d&ignore=.csv').read() fout=open('csco.csv','wb') fout.write(reply) fout.close fin=open('csco.csv','rb') table = csv.reader(fin) fin.close for row in table: print row return_ranking() I need to use cookies etc (mechanize/urllib2) for a different, more complex URL but since it wasn't working, I went back to a simple Yahoo example (above) which I have working with urllib (not urllib2). The behaviour I am seeing is that the last record is being truncated: (sample output) ['2009-04-08', '17.29', '17.33', '16.94', '17.13', '45389100', '17.13'] ['2009-04-07', '17.20', '17.25', '16.58', '16.85', '59902600', '16.85'] ['200'] A friend said I should do the above writing out to a file and have csvreader read in the file, but as you can see, to no avail! Any help greatly appreciated! Note that urllib.urlretrieve works perfectly but I give up the ability to import cookies from my registry which is all important (AFAIK anyway mechanize requires urllib2). Any help greatly appreciated. From keith at nekotaku.com Mon Aug 3 19:21:02 2009 From: keith at nekotaku.com (KB) Date: Mon, 3 Aug 2009 16:21:02 -0700 (PDT) Subject: Problem with reading CSV file from URL, last record truncated. References: <0996356d-ee7d-4a5e-9c0c-9f9502c01892@l5g2000pra.googlegroups.com> Message-ID: On Aug 3, 3:54?pm, KB wrote: > Hi, > > I am trying to download from a URL, a CSV using the following: > > import re > import urllib, urllib2, cookielib > import mechanize > import csv > import numpy > import os > > def return_ranking(): > > ? ? ? ? cj = mechanize.MSIECookieJar(delayload=True) > ? ? ? ? cj.load_from_registry() ?# finds cookie index file from registry > > ? ? ? ? # set things up for cookies > > ? ? ? ? opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > > ? ? ? ? urllib2.install_opener(opener) > > ? ? ? ? reply = opener.open('http://ichart.finance.yahoo.com/table.csv? > s=CSCO&a=00&b=01&c=2009&d=01&e=2&f=2010&g=d&ignore=.csv').read() > > ? ? ? ? fout=open('csco.csv','wb') > ? ? ? ? fout.write(reply) > ? ? ? ? fout.close > > > return_ranking() > > I need to use cookies etc (mechanize/urllib2) for a different, more > complex URL but since it wasn't working, I went back to a simple Yahoo > example (above) which I have working with urllib (not urllib2). > > The behaviour I am seeing is that the last record is being truncated: > > (sample output) > ['2009-04-08', '17.29', '17.33', '16.94', '17.13', '45389100', > '17.13'] > ['2009-04-07', '17.20', '17.25', '16.58', '16.85', '59902600', > '16.85'] > ['200'] > > A friend said I should do the above writing out to a file and have > csvreader read in the file, but as you can see, to no avail! > > Any help greatly appreciated! Note that urllib.urlretrieve works > perfectly but I give up the ability to import cookies from my registry > which is all important (AFAIK anyway mechanize requires urllib2). > > Any help greatly appreciated. By moving: > fin=open('csco.csv','rb') > table = csv.reader(fin) > fin.close > > for row in table: > print row outside of the routine and into the mainline, it works like a charm. Would like to know why though, so would love to hear any clues! From piet at cs.uu.nl Mon Aug 3 19:26:58 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 04 Aug 2009 01:26:58 +0200 Subject: Executing remote command with paramiko References: Message-ID: >>>>> Hussein B (HB) wrote: >HB> Hey, >HB> I'm trying to run a sudo guarded command over SSH using paramiko >HB> +++++++++++++++++++ >HB> s = paramiko.SSHClient() >HB> s.load_system_host_keys() >HB> s.connect(hostname, port, username, passwd) >HB> stdin, stdout, stderr = s.exec_command('sudo -s') >HB> stdin.write('password\n') >HB> stdin.flush() >HB> print 'Flushing' >HB> stdin, stdout, stderr = s.exec_command('harvester') >HB> print stdout.read() >HB> s.close() >HB> +++++++++++++++++++ >HB> It seems to me that the sudo -s isn't getting executed at all. >HB> I commented the sudo -s code lines and no error is shown. >HB> Thanks for help and time. Your command 'harvester' is not run in the sudo shell, but separately in a new session. so it will run under 'username', not under 'root'. You could use stdin, stdout, stderr = s.exec_command('sudo harvester') instead. Or use the lower-level constructs: s = paramiko.SSHClient() s.load_system_host_keys() s.connect(hostname, port, username, password) t = s.get_transport() chan = t.open_session() chan.exec_command('sudo -s') print 'writing password' chan.send(password + '\n') print 'write command' chan.send('whoami\n') print "try to read" print chan.recv(9999) For more control you can use chan.recv_ready() to see if output is available. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From greg at cosc.canterbury.ac.nz Mon Aug 3 19:35:12 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 04 Aug 2009 11:35:12 +1200 Subject: Help understanding the decisions *behind* python? In-Reply-To: <4a7715ff$0$1641$742ec2ed@news.sonic.net> References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> <4a7715ff$0$1641$742ec2ed@news.sonic.net> Message-ID: <7dpagaF2cu16mU1@mid.individual.net> John Nagle wrote: > Mesa used tuples for subroutine arguments in a very straightforward > way. Every function took one tuple as an argument > > Python doesn't go that far. I believe that a very early version of Python did do something like that, but it was found to be a bad idea, because there was an ambiguity between multiple args and a single arg that happened to be a tuple. This was before keyword arguments existed -- they would have been hard to incorporate into the old scheme. -- Greg From rt8396 at gmail.com Mon Aug 3 19:39:25 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 16:39:25 -0700 (PDT) Subject: no-clobber dicts? References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: <1d95f706-71f4-487e-a920-a31643b76c10@w6g2000yqw.googlegroups.com> On Aug 3, 5:00?pm, Chris Rebert wrote: > On Mon, Aug 3, 2009 at 2:47 PM, r wrote: [snip] > > Not sure if something like this already exists, but it would be > > trivial to implement by overriding dict.__setitem__() > > That is, if you don't care about .update() not preserving the > invariant. Otherwise, one will need to look at the UserDict module. > > Cheers, > Chris > --http://blog.rebertia.com Good catch Chris. However since the OP said this was for testing purposes, i just *assumed* he would be smart enough *not* to call update() on the dict at hand ;-). But sometimes i need to be protected from myself too -- at least thats what my therapist keeps telling me :-) From greg at cosc.canterbury.ac.nz Mon Aug 3 19:40:06 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 04 Aug 2009 11:40:06 +1200 Subject: fast video encoding In-Reply-To: References: <570097d0-2b2a-4705-892f-0d0154d69d63@b14g2000yqd.googlegroups.com> <0c8cfac7-0a70-4e1f-90ec-19e9c45cae89@h21g2000yqa.googlegroups.com> Message-ID: <7dpapgF2ckro4U1@mid.individual.net> Rhodri James wrote: > Unfortunately, water pixels change a lot from frame to frame, even > when the camera is static, so it doesn't gain you as much as you might > hope in cases like you mention. In the case mentioned, the water is of no interest, so it could be removed altogether by a suitable custom compressor. -- Greg From python at mrabarnett.plus.com Mon Aug 3 19:47:23 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Aug 2009 00:47:23 +0100 Subject: Problem with reading CSV file from URL, last record truncated. In-Reply-To: References: <0996356d-ee7d-4a5e-9c0c-9f9502c01892@l5g2000pra.googlegroups.com> Message-ID: <4A77770B.2070008@mrabarnett.plus.com> KB wrote: > On Aug 3, 3:54 pm, KB wrote: >> Hi, >> >> I am trying to download from a URL, a CSV using the following: >> >> import re >> import urllib, urllib2, cookielib >> import mechanize >> import csv >> import numpy >> import os >> >> def return_ranking(): >> >> cj = mechanize.MSIECookieJar(delayload=True) >> cj.load_from_registry() # finds cookie index file from registry >> >> # set things up for cookies >> >> opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) >> >> urllib2.install_opener(opener) >> >> reply = opener.open('http://ichart.finance.yahoo.com/table.csv? >> s=CSCO&a=00&b=01&c=2009&d=01&e=2&f=2010&g=d&ignore=.csv').read() >> >> fout=open('csco.csv','wb') >> fout.write(reply) >> fout.close This should be: fout.close() >> > >> return_ranking() >> [snip] > By moving: >> fin=open('csco.csv','rb') >> table = csv.reader(fin) >> fin.close This should be: fin.close() >> >> for row in table: >> print row > > outside of the routine and into the mainline, it works like a charm. > > Would like to know why though, so would love to hear any clues! > The parentheses aren't optional; without them you're just referring to the method, not calling it. Because you weren't closing the file the text wasn't all written to disk. When it returns from return_ranking() there's no longer any reference to 'fout', so the file object is available for collection by the garbage collector. When the file object is collected it writes the remaining text to disk. In CPython the file object is collected as soon as there's no reference to it, but in other implementations that might not be the case. From mensanator at aol.com Mon Aug 3 20:32:03 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 3 Aug 2009 17:32:03 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: On Aug 3, 8:18?am, cool-RR wrote: > Hello, > > I wanted to announce that I have just released my little side project, > PythonTurtle. > Here is its website:http://pythonturtle.com > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > You can read more about it and download it on the website. I dunno, looks kind of worthless to me. http://www.mensanator.com/mensanator/PythonTurtle/PythonTurtle.htm > > Ram. From van.lindberg at gmail.com Mon Aug 3 20:42:14 2009 From: van.lindberg at gmail.com (VanL) Date: Mon, 03 Aug 2009 19:42:14 -0500 Subject: Extracting text from html Message-ID: Hello all, Does anyone know of a good tool to get a minimally-formatted text document out of an html document? Something along the lines of what you would get with a lynx -dump, but in Python. I have lxml installed, so I can roll my own if I need to. However, this seemed like the sort of thing that someone would have solved already. Thanks, Van From gagsl-py2 at yahoo.com.ar Mon Aug 3 20:42:47 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 21:42:47 -0300 Subject: Python configuration question when python scripts are executed using Appweb as web server. References: Message-ID: En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife escribi?: > I have installed python 2.6.2 in windows xp professional machine. I > have set the following environment variables -- PYTHONPATH. It points > to following windows folders: python root folder, the lib folder and > lib-tk folder. Why? Did you read it somewhere? Usually there is no need to set the PYTHONPATH variable at all; remove it. > I have configured IIS to execute python scripts. > > I do not have any issues executing python scripts from the python > interpreter window or from the browser using IIS as the web server. Try again after PYTHONPATH is removed, and make sure you can import all the required modules from the Python console. Only then try to run the cgi scripts. > However, when I use the open source Appweb web browser to execute > python scripts. It is able to execute only simple script without > issues. [...]However I am not able to execute python scripts that > contain import > statements. I need to point out here that i do not have issue with > using os or sys packages. When I tried to execute the sample client > script that came with the gnutls wrapper for python, I got error. I > narrowed it down to the "from ... import" line in the example. > > from gnutls.crypto import * > from gnutls.connection import * Check that the above lines work fine from inside the Python console. If not, something went wrong when you installed the gnutls Python package. > Next step, in order to debug, I used the module finder to see what is > happening. To being with I used the module finder to find out the > modules loaded for the simple script hello.py. Debugging cgi scripts isn't easy sometimes; try adding this line at the start of your script: import cgitb;cgitb.enable() You should get a nicely formatted stack trace whenever an exception is raised. If you get an HTTP error instead (like 500 Internal Server Error) it's likely a syntax error, you must fix it before continuing. Then, you may find that modulefinder is no more needed. > import pdb > pdb.set_trace() pdb cannot work inside a CGI script; remove that. > Once again, let me stress that this issue is happening only when I use > appweb as the web server. I don't know appweb, but if you first make sure the script works from the command line, it should be much easier to make it work in the web server. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Aug 3 21:10:57 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 22:10:57 -0300 Subject: easy_install: unresolved external symbol References: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> Message-ID: En Mon, 03 Aug 2009 17:39:44 -0300, Bart Smeets escribi?: > I keep getting errors when trying to use easy_install to install > bbfreeze or > cxfreeze (same errors). > This is the output: > http://pastebin.com/m65ba474d Can't you use the binary packages? -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Aug 3 21:18:08 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 22:18:08 -0300 Subject: Ordering of dict keys & values References: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> Message-ID: En Mon, 03 Aug 2009 17:47:23 -0300, Wells Oliver escribi?: > I understand that the keys in a dictionary are ordered not randomly but > something practically close to it, but if I create a SQL query like so: > > query = 'INSERT INTO Batting (%s) VALUES(%s)' % (','.join(stats.keys()), > ','.join(stats.values())) > > Can I at least rely on the value being in the same index as its > corresponding key? You already got the answer you wanted, but note that building a SQL statement that way is unsafe [1]. I prefer this way: query= 'INSERT INTO Batting (%s) VALUES(%s)' % ( ','.join(stats.keys()), ','.join(['?']*len(stats))) cursor.execute(query, stats.values()) [1] If you don't know what "SQL injection" means, see http://xkcd.com/327/ -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Mon Aug 3 21:39:50 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 03 Aug 2009 22:39:50 -0300 Subject: Is python buffer overflow proof? References: Message-ID: En Mon, 03 Aug 2009 18:04:53 -0300, sturlamolden escribi?: > On 2 Aug, 15:50, Jizzai wrote: > >> Is a _pure_ python program buffer overflow proof? >> >> For example in C++ you can declare a char[9] to hold user input. >> If the user inputs 10+ chars a buffer overflow occurs. > > Short answer: NO > > Bounds checking on sequence types is a protection against buffer > overflow, but is certainly not sufficient. > > The Python interpreter is written in C. Python extension modules are > written in C (or something similar). If you find an unprotected buffer > in this C code, you can possibly overflow this buffer. This can be > used for nasty things like corrupting the stack and injecting > malicious code. There is a reason why the Python sandbox (rexec and > Bastion modules) was disabled in Python 2.3. (I think the reason rexec and bastion were disabled has nothing to do with the possibility of buffer overflows in extension modules) > IronPython and Jython provides better protection against buffer > overflow than CPython, as these interpreters are written in safer > languages (C# and Java). You thus get an extra layer of protection > between the Python code and the unsafe C (used in JVM and .NET > runtimes). I disagree. You've just translated the responsability to check for buffer overflows, from the Python VM, to the Java VM or the .Net runtime (and all three suffered from buffer overruns and other problems in some way or another). Also, Python extensions written in C are equivalent to using JNI in Java or unmanaged code in C#: all three are likely to have hidden problems. It's always the same story: a *language* may declare that such things are impossible, but a particular *implementation* may have bugs and fail to comply with the specification. -- Gabriel Genellina From cocobear.cn at gmail.com Mon Aug 3 21:44:49 2009 From: cocobear.cn at gmail.com (cocobear) Date: Mon, 3 Aug 2009 18:44:49 -0700 (PDT) Subject: merge two png pic References: Message-ID: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> On Jul 31, 2:52?pm, Peter Otten <__pete... at web.de> wrote: > cocobear wrote: > > On Jul 29, 9:20 am, cocobear wrote: > >> Thistwopngfile has their own palette > > >> >>> im1.mode > >> 'P' > >> >>> im.mode > >> 'P' > >> >>> im.getpalette == im1.getpalette > > >> False > > >> I can use this code tomergetwopngpictogether: > > >> Map = Image.new("RGB", (x,y)) > >> Map.paste(im, box) > >> Map.paste(im1,box) > > >> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE) > > >> But if thetwopngpicis too big , or if I have tomergemorepic > >> together, I will get MemoryError: > > >> >>> Image.new("RGB",(44544,38656)) > > As a workaround you could split the image into tiles that fit into your > machine's RAM. Or you could try to do the rendering on a 64-bit system. > You'll need at least > > >>> 3*44544*38656./(2**30) > > 4.8109130859375 > > 5 gigabytes for the target image plus memory for the biggest source image. > Alternatively there are probably tools that can keep parts of the image on > disk (imagemagick, maybe? you'll have to check yourself or ask in a > specialized forum). As a last resort you should be able to write such a tool > yourself. I don't know how hard it would be to generate the PNG, but the RGB > pasting should be trivial. > Thanks for you reply. Map = Image.new("RGB", ((x2-x1+1)*256, (y2-y1+1)*256)) for x in range(x1,x2+1): for y in range(y1,y2+1): #print x,y filename = "v=cn1.11&hl=zh-CN&x=%d&y=%d&z=%d&s=Galile" % (x,y,z) # box = ((x-x1)*256, (y-y1)*256, (x-x1)*256+256, (y-y1) *256+256) #print box im = Image.open(filename+".png") Map.paste(im, box) temp = "temp_map.png" Map.save(temp) del Map print "converting" Map = Image.open(temp) Map = Map.convert("P", palette=Image.ADAPTIVE) Now I use code above, the problem is when I create a RGB image, I need four times spaces then a 'P' mode image. Can I directly create a 'P' mode image, and paste those images on? (NOTICE: this small image has different palette) > >> Traceback (most recent call last): > >> File "", line 1, in > >> File "/usr/lib/python2.5/site-packages/PIL/Image.py", line 1710, in > >> new > >> return Image()._new(core.fill(mode, size, color)) > >> MemoryError > > >> How can I directlymergetwopicto a ?P' modepngwith palette. > > > Nobody replied. > > What do you want to do with such a big image? You will run into the same > limitation when you are trying to display it. > I want to download a map from google map with high precision > Peter From afriere at yahoo.co.uk Mon Aug 3 21:53:02 2009 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 3 Aug 2009 18:53:02 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> Message-ID: <1d144bd0-8829-4449-8935-60bf6f66a5d6@l5g2000pra.googlegroups.com> On Aug 4, 6:35?am, r wrote: [snip] > > I can remember the first time i used turtle (in python stdlib) and i > kept saying to myself... > > ? ? "Were the heck is this damn turtle?!?!" (>_<) > > :-) In Python2.6, try this: >>> turtle.shape('turtle') From benjamin.kaplan at case.edu Mon Aug 3 22:15:03 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 3 Aug 2009 22:15:03 -0400 Subject: [OT] Re: Ordering of dict keys & values In-Reply-To: References: <3f1a902d0908031347g6e5dbbb7v832b0abc924a020@mail.gmail.com> Message-ID: On Mon, Aug 3, 2009 at 9:18 PM, Gabriel Genellina wrote: > > [1] If you don't know what "SQL injection" means, see http://xkcd.com/327/ I love how XKCD is one of the preferred learning tools (along with Wikipeida) for people on this list. I think Randall Munroe should make a comic about it. :) From justin.mailinglists at gmail.com Mon Aug 3 22:32:22 2009 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Mon, 3 Aug 2009 19:32:22 -0700 (PDT) Subject: Extracting text from html References: Message-ID: <44201d0e-87fe-457e-a7e2-26b2c5027d76@b25g2000prb.googlegroups.com> http://tinyurl.com/kpoweq From fft1976 at gmail.com Mon Aug 3 22:51:36 2009 From: fft1976 at gmail.com (fft1976) Date: Mon, 3 Aug 2009 19:51:36 -0700 (PDT) Subject: RUBY vs COMMON LISP References: <389503e4-eb6a-48c2-af76-cebe1dc7141c@h30g2000vbr.googlegroups.com> <87my6ic1k5.fsf@galatea.local> <1a40c8fe-83e4-4c50-90e2-b72ef86a6ac4@m7g2000prd.googlegroups.com> <87hbwp9umw.fsf@galatea.local> Message-ID: <04aef600-150d-44fa-a0cd-d88a4b17e836@m7g2000prd.googlegroups.com> On Aug 3, 1:19?am, p... at informatimago.com (Pascal J. Bourguignon) wrote: > fft1976 writes: > > By the way, here is in 1 line of BF, a complete BF reader that is able > > to > > read all the BF syntax needed to write it: > > > ,+[-.,+] > > > Here's how to try it: > > > $ sudo apt-get install bf > > $ cat > reader.bf > > ,+[-.,+] > > $ bf reader.bf < reader.bf > > > Your 150 lines don't look very impressive now, do they? > > > Ruby < Lisp <<< BF! > > I specified a syntactic reader. ?Not just a reader. It is a syntactic reader. BF's syntax is just a sequence of characters. If you throw in illegal characters, the behavior is "undefined". Lisp's syntax is more complicated: it's a tree of identifiers (in its idealized form; of course, Common Lisp had to fuck it up). Ruby's and Python's syntaxes are even more complicated. The above was to illustrate the wrongness of your argument that the length of a self-parser determines the usefulness of the language. Hell, I know that BF can be a little *too* awesome. By the way, Python's syntax is much better than Ruby's. Dollar signs in front of variables? WTF were the designers smoking? That's like Perl! Haven't you learned your lesson? Python's syntax might even be better than Lisp's, but it's certainly harder to parse. From pavlovevidence at gmail.com Mon Aug 3 23:00:08 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Aug 2009 20:00:08 -0700 (PDT) Subject: Seeding the rand() Generator References: Message-ID: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> On Aug 3, 8:12?pm, Fred Atkinson wrote: > On Sun, 2 Aug 2009 17:00:40 -0700 (PDT), Carl Banks > > wrote: > > ? ? ? ? I appreciate the response. ? > > ? ? ? ? I am executing a statement to retrieve one record at random. ? > > ? ? ? ? An example would be: SELECT first, second, third, fourth, > fifth, sixth from sometable order by rand() limit 1 > > ? ? ? ? It would be contained as: stmt = "SELECT first, second, third, > fourth, fifth, sixth from sometable order by rand() limit 1" > > ? ? ? ? Then I would execute it with the command: cursor.execute(stmt) > > ? ? ? ? How would I correctly seed the random generator in the MySQL > statement from within Python? ? You apparently know how to run MySQL statements from Python, correct? You also apparently know how to run a particular MySQL statement from PHP that seeds the random number generator, correct? Given those two apparent facts, you should be able run whatever statement you ran in PHP to seed the RNG in Python. So I don't see what the problem is. Your question is a MySQL question, not a Python question. I don't know off hand how to seed the RNG in MySQL, and, since this is a Python group and not a MySQL group, I don't care to look it up. But if you were able to produce the MySQL statement in PHP that does it you shouldn't need to ask. If you don't "get" why this is a MySQL question and not a Python question, then you need to learn more about what you are doing. Carl Banks From davea at ieee.org Mon Aug 3 23:00:13 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Aug 2009 23:00:13 -0400 Subject: Newbie Question regarding __init__() In-Reply-To: <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> Message-ID: <4A77A43D.4000709@ieee.org> Simon wrote: > On Aug 2, 5:51 am, Dave Angel wrote: > >> >> I don't understand your comparison to Foxpro. read on. >> >> As your code was last posted, you don't need a return value from >> init_Exec() Every function that doesn't have an explicit return will >> return None. And None is interpreted as False in an "and" expression. >> If you had an "if" around the whole thing, then you'd care. >> >> DaveA >> > > All I meant by the FoxPro comment was the idea of using the equal sign > without a variable to throw away the result. Also in FoxPro there is > no such thing as automatically returning None. If there is no > explicit return then True is returned. > > Thanks I did not know that None is interpreted as False. > > Simon > > > To throw away the result of an expression in Python is even easier. Just don't use it. func1() and func2() is a valid expression whose result is not used. And func2()'s result is therefore irrelevant. But shortcircuiting means that func2() is only called if func1() returned False (or something equivalent to it, like 0 or an empty list) From pavlovevidence at gmail.com Mon Aug 3 23:02:26 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 3 Aug 2009 20:02:26 -0700 (PDT) Subject: RUBY vs COMMON LISP References: <389503e4-eb6a-48c2-af76-cebe1dc7141c@h30g2000vbr.googlegroups.com> <87my6ic1k5.fsf@galatea.local> <1a40c8fe-83e4-4c50-90e2-b72ef86a6ac4@m7g2000prd.googlegroups.com> <87hbwp9umw.fsf@galatea.local> <04aef600-150d-44fa-a0cd-d88a4b17e836@m7g2000prd.googlegroups.com> Message-ID: <3755ae21-b7b0-4f82-99d4-1095ec953c39@s6g2000vbp.googlegroups.com> On Aug 3, 7:51?pm, fft1976 wrote: > On Aug 3, 1:19?am, p... at informatimago.com (Pascal J. Bourguignon) > wrote: > > > > > > > fft1976 writes: > > > By the way, here is in 1 line of BF, a complete BF reader that is able > > > to > > > read all the BF syntax needed to write it: > > > > ,+[-.,+] > > > > Here's how to try it: > > > > $ sudo apt-get install bf > > > $ cat > reader.bf > > > ,+[-.,+] > > > $ bf reader.bf < reader.bf > > > > Your 150 lines don't look very impressive now, do they? > > > > Ruby < Lisp <<< BF! > > > I specified a syntactic reader. ?Not just a reader. > > It is a syntactic reader. BF's syntax is just a sequence of > characters. If you throw in illegal characters, the behavior is > "undefined". Lisp's syntax is more complicated: it's a tree of > identifiers (in its idealized form; of course, Common Lisp had to fuck > it up). Ruby's and Python's syntaxes are even more complicated. > > The above was to illustrate the wrongness of your argument that the > length of a self-parser determines the usefulness of the language. > Hell, I know that BF can be a little *too* awesome. > > By the way, Python's syntax is much better than Ruby's. Dollar signs > in front of variables? WTF were the designers smoking? That's like > Perl! Haven't you learned your lesson? > > Python's syntax might even be better than Lisp's, but it's certainly > harder to parse.- Hide quoted text - Go away, troll. [This is cross-posted; I recommend that no one else follow up.] Carl Banks From fft1976 at gmail.com Mon Aug 3 23:06:58 2009 From: fft1976 at gmail.com (fft1976) Date: Mon, 3 Aug 2009 20:06:58 -0700 (PDT) Subject: RUBY vs COMMON LISP References: <389503e4-eb6a-48c2-af76-cebe1dc7141c@h30g2000vbr.googlegroups.com> <87my6ic1k5.fsf@galatea.local> <1a40c8fe-83e4-4c50-90e2-b72ef86a6ac4@m7g2000prd.googlegroups.com> <87hbwp9umw.fsf@galatea.local> <04aef600-150d-44fa-a0cd-d88a4b17e836@m7g2000prd.googlegroups.com> <3755ae21-b7b0-4f82-99d4-1095ec953c39@s6g2000vbp.googlegroups.com> Message-ID: On Aug 3, 8:02?pm, Carl Banks wrote: > On Aug 3, 7:51?pm, fft1976 wrote: > > > > > On Aug 3, 1:19?am, p... at informatimago.com (Pascal J. Bourguignon) > > wrote: > > > > fft1976 writes: > > > > By the way, here is in 1 line of BF, a complete BF reader that is able > > > > to > > > > read all the BF syntax needed to write it: > > > > > ,+[-.,+] > > > > > Here's how to try it: > > > > > $ sudo apt-get install bf > > > > $ cat > reader.bf > > > > ,+[-.,+] > > > > $ bf reader.bf < reader.bf > > > > > Your 150 lines don't look very impressive now, do they? > > > > > Ruby < Lisp <<< BF! > > > > I specified a syntactic reader. ?Not just a reader. > > > It is a syntactic reader. BF's syntax is just a sequence of > > characters. If you throw in illegal characters, the behavior is > > "undefined". Lisp's syntax is more complicated: it's a tree of > > identifiers (in its idealized form; of course, Common Lisp had to fuck > > it up). Ruby's and Python's syntaxes are even more complicated. > > > The above was to illustrate the wrongness of your argument that the > > length of a self-parser determines the usefulness of the language. > > Hell, I know that BF can be a little *too* awesome. > > > By the way, Python's syntax is much better than Ruby's. Dollar signs > > in front of variables? WTF were the designers smoking? That's like > > Perl! Haven't you learned your lesson? > > > Python's syntax might even be better than Lisp's, but it's certainly > > harder to parse.- Hide quoted text - > > Go away, troll. > > [This is cross-posted; I recommend that no one else follow up.] > > Carl Banks Lispers were having fun badmouthing other languages for no good reason: """ Don't you realize how ugly Ruby syntax is? Here is in 150 lines of lisp, a simplified lisp reader that is able to read all the lisp syntax needed to write it. Try to parse Ruby syntax in Ruby and see how useless a language it is. """ http://groups.google.com/group/comp.lang.lisp/msg/52dde974d504ad54 Of course you don't like it when I point out just how wrong you are. From fatkinson at mishmash.com Mon Aug 3 23:12:49 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Mon, 03 Aug 2009 20:12:49 -0700 Subject: Seeding the rand() Generator References: Message-ID: On Sun, 2 Aug 2009 17:00:40 -0700 (PDT), Carl Banks wrote: I appreciate the response. I am executing a statement to retrieve one record at random. An example would be: SELECT first, second, third, fourth, fifth, sixth from sometable order by rand() limit 1 It would be contained as: stmt = "SELECT first, second, third, fourth, fifth, sixth from sometable order by rand() limit 1" Then I would execute it with the command: cursor.execute(stmt) How would I correctly seed the random generator in the MySQL statement from within Python? Regards, Fred From steven at REMOVE.THIS.cybersource.com.au Mon Aug 3 23:23:20 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 03:23:20 GMT Subject: no-clobber dicts? References: Message-ID: On Mon, 03 Aug 2009 21:07:32 +0000, kj wrote: > I use the term "no-clobber dict" to refer to a dictionary D with the > especial property that if K is in D, then > > D[K] = V > > will raise an exception unless V == D[K]. In other words, D[K] can be > set if K doesn't exist already among D's keys, or if the assigned value > is equal to the current value of D[K]. All other assignments to D[K] > trigger an exception. Coincidentally, I just built something very close to what you ask. Here it is: class ConstantNamespace(dict): """Dictionary with write-once keys.""" def __delitem__(self, key): raise TypeError("can't unbind constants") def __setitem__(self, key, value): if key in self: raise TypeError("can't rebind constants") super(ConstantNamespace, self).__setitem__(key, value) def clear(self): raise TypeError('cannot unbind constants') def pop(self, key, *args): raise TypeError("cannot pop constants") def popitem(self): raise TypeError("cannot pop constants") def update(self, other): for key in other: if key in self: raise TypeError('cannot update constants') # If we get here, then we're not modifying anything, # so okay to proceed. super(ConstantNamespace, self).update(other) def copy(self): c = self.__class__(**self) return c I also have a series of unit tests for it if you're interested in them. -- Steven From davea at ieee.org Mon Aug 3 23:23:38 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 03 Aug 2009 23:23:38 -0400 Subject: file comparison In-Reply-To: <29a34bc20908031748j11280ab0mb4303da4156db54b@mail.gmail.com> References: <29a34bc20907310225n50b35fe2m322872af2058a465@mail.gmail.com> <200907311247.30793.hendrik@microcorp.co.za> <4A72E9BF.3080808@ieee.org> <29a34bc20908031748j11280ab0mb4303da4156db54b@mail.gmail.com> Message-ID: <4A77A9BA.4090104@ieee.org> learner learner wrote: > Firstly thanks for showing the interest. I shall elobarate more on the > problem: > > file-1.txt > -------------- > hai > how > r > u > > file-2.txt > --------------- > r > hai > u > > > The two files have some lines in common. > > For eg: File-1.txt-first line-"hai" does not match with File-2.txt-first > line-"r" but surely matches with File-2.txt -second > > line -"hai". On having an iterative search the file-1.txt should finally be > left out with mismatched string "how", which is > > to be dumped into a third file say file3.txt or rewritten to > file-1.txt/file-2.txt with this single word "how" in line 1. > > some facts to remember: > ------------------------ > > the srings in the files will be same including case sentiveness if at all > present, else will be pronounced as a mismatch. > > this is bascically an iterative string search amongst the files and > isolating the mismatched strings into a text file > > (By replying off-list, you are ignoring the intent of public mailing lists. So I'm copying your message to the list, along with my response.) As I said before: If the text files are each a list of items, with order and duplication irrelevant, then your best bet is probably to build a set from each, and difference the sets. Sets are case-sensitive, and your example above indicates that order is at least partially irrelevant to you. So read each file, converting the lines into a set. Then do a set difference of those two sets. Then build a list from the result, and write that to a file. If it doesn't work, post the code you tried, along with sample data and expected output for that sample data. DaveA From steven at REMOVE.THIS.cybersource.com.au Mon Aug 3 23:30:35 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 03:30:35 GMT Subject: Generate a new object each time a name is imported References: <02853264$0$20667$c3e8da3@news.astraweb.com> Message-ID: On Mon, 03 Aug 2009 16:38:43 +0200, Jean-Michel Pichavant wrote: > So what's the purpose of making > >>from Module import factory as a >>from Module import factory as b > > return 2 different objects ? If I had to write this code I would expect > 'a is b' to return 'True'. > > This is no "don't do that" answer, it's a sincere question: what is the > benefit of your /new/ syntax ? Consider it "properties for modules": a = obj.factory b = obj.factory doesn't promise that a is b, because factory might be a property that returns a new object each time. Actually, this behaviour pre-dates properties. If obj has a __getattr__ or __getattribute__ method, then it could do the same thing. -- Steven From steven at REMOVE.THIS.cybersource.com.au Mon Aug 3 23:44:54 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 03:44:54 GMT Subject: Is python buffer overflow proof? References: Message-ID: On Mon, 03 Aug 2009 14:04:53 -0700, sturlamolden wrote: > On 2 Aug, 15:50, Jizzai wrote: > >> Is a _pure_ python program buffer overflow proof? >> >> For example in C++ you can declare a char[9] to hold user input. If the >> user inputs 10+ chars a buffer overflow occurs. > > Short answer: NO > > Bounds checking on sequence types is a protection against buffer > overflow, but is certainly not sufficient. > > The Python interpreter is written in C. Python extension modules are > written in C (or something similar). If you find an unprotected buffer > in this C code, you can possibly overflow this buffer. How are C extension modules "_pure_ python"? -- Steven From thangappan143 at gmail.com Mon Aug 3 23:45:47 2009 From: thangappan143 at gmail.com (Thangappan.M) Date: Tue, 4 Aug 2009 09:15:47 +0530 Subject: Problem in installing PyGreSQL Message-ID: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> Dear all, I want to access the database related stuffs in python.So I found the PyGreSQL module in net. Then I tried to download the module.But I am not able to download it. I am not a super user. I am using Linux debian machine Python version is 2.4.4 -- Regards, Thangappan.M -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Tue Aug 4 00:06:15 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 04:06:15 GMT Subject: kw param question References: Message-ID: On Mon, 03 Aug 2009 19:59:23 +0000, kj wrote: > I want to write a decorator that, among other things, returns a function > that has one additional keyword parameter, say foo=None. > > When I try > > def my_decorator(f): > # blah, blah > def wrapper(*p, foo=None, **kw): > x = f(*p, **kw) > if (foo): > # blah, blah > else > # blah blah > return wrapper > > ...i get a syntax error where it says "foo=None". I get similar errors > with everything else I've tried. > > Is is possible to do this in Python? Have you tried this under Python 2.6 or 3.0? I've run into similar issues, because you can't have keyword-only arguments in Python 2.5 :( My solution was to create a decorator that faked them. The docstring is longer than the decorator itself. from functools import wraps def keywords(**defaults): """Return a decorator which decorates a function to accept keyword arguments. Python 2.5 and earlier don't allow keyword-only arguments for non-builtin functions. The obvious syntax: def func(x, *args, key=None, word='parrot'): is not permitted. As a work-around, write your function something like the following example: >>> @keywords(key=None, word='parrot') ... def func(x, y=0, *args, **kwargs): ... # Inside the function, we can guarantee that kwargs['key'] and ... # kwargs['word'] both exist, and no other keys. ... print "x=%s, y=%s, args=%s" % (x, y, args) ... if kwargs['key'] is None: msg = "kwargs['key'] is None" ... else: msg = "kwargs['key'] is something else" ... msg += " and kwargs['word'] is %r" % kwargs['word'] ... print msg ... When you call func, if you don't provide a keyword-only argument, the default will be substituted: >>> func(1, 2, 3, 4) x=1, y=2, args=(3, 4) kwargs['key'] is None and kwargs['word'] is 'parrot' >>> func(1) x=1, y=0, args=() kwargs['key'] is None and kwargs['word'] is 'parrot' Naturally you can provide your own values for keyword-only arguments: >>> func(1, 2, 3, word='spam') x=1, y=2, args=(3,) kwargs['key'] is None and kwargs['word'] is 'spam' >>> func(1, 2, 3, word='spam', key=len) x=1, y=2, args=(3,) kwargs['key'] is something else and kwargs['word'] is 'spam' If you pass an unexpected keyword argument, TypeError is raised: >>> #doctest:+IGNORE_EXCEPTION_DETAIL ... func(1, 2, 3, 4, keyword='something') Traceback (most recent call last): ... TypeError: ... """ def decorator(func): """Decorate func to allow keyword-only arguments.""" @wraps(func) def f(*args, **kwargs): for key in kwargs: if key not in defaults: raise TypeError( "'%s' is an invalid keyword argument for " \ "this function" % key ) d = defaults.copy() d.update(kwargs) return func(*args, **d) return f return decorator (Copy and pasted from working code, but I make no guarantee that it will have survived the process in working order!) -- Steven From rt8396 at gmail.com Tue Aug 4 00:08:52 2009 From: rt8396 at gmail.com (r) Date: Mon, 3 Aug 2009 21:08:52 -0700 (PDT) Subject: Announcing PythonTurtle References: <729a6652-cdfa-49b8-8013-6d7861b8020e@d4g2000yqa.googlegroups.com> <1d144bd0-8829-4449-8935-60bf6f66a5d6@l5g2000pra.googlegroups.com> Message-ID: <02ad1097-bf09-4980-8d1d-18cdbf50cb5a@24g2000yqm.googlegroups.com> On Aug 3, 8:53?pm, Asun Friere wrote: > On Aug 4, 6:35?am, r wrote: > > [snip] > > > > > I can remember the first time i used turtle (in python stdlib) and i > > kept saying to myself... > > > ? ? "Were the heck is this damn turtle?!?!" (>_<) > > > :-) > > In Python2.6, try this: > > > > >>> turtle.shape('turtle') Thanks Asun, now i don't have anything to complain about! :-# From koranthala at gmail.com Tue Aug 4 00:09:05 2009 From: koranthala at gmail.com (koranthala) Date: Mon, 3 Aug 2009 21:09:05 -0700 (PDT) Subject: Which GUI framework to use? Message-ID: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> Hi, I am creating a very minimal application (a networking app). I have written the application using Twisted. Now, I need to put a GUI wrapper on the application. The application needs a login screen and also it needs to be minimized to system tray. If I right click the image on system tray, I should be able to close it. It uses some legacy code, so the whole app is written in Python 2.4. Also, my company requires that I use permissive licenses (no GPL - MIT, BSD, LGPL etc ok) Which GUI framework is best for this? I tried using Tkinter, but it does not support minimize to system tray (or I couldnt find it). This is my first foray to GUI programming, so other issues that I am worried about - 1. GUI needs a loop, Twisted needs a loop. How can both go ahead without messing each other? Thank You very much K From jjposner at optimum.net Tue Aug 4 00:12:34 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 04 Aug 2009 00:12:34 -0400 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: <4A77B532.5020906@optimum.net> > ... I would also venture to say a key-map > of sorts that is available thru the help menu where one could push an > "Up" button, or a "rotate" button, and have the proper command > inserted in the prompt, and then have the command execute, may also > help make the connections here, a sort of *real* Visual Basic > programming -- sorry Microsoft :P > Along these lines, see my "ClixTur" application at www.jjposner.net. It's a point-and-click front end to the standard Python turtle module, implementing only a very small subset of the turtle commands. As you click, the "real turtle commands" appear in a transcript window. You can then save (and maybe edit) and replay the transcript. Ram, I like a lot of what you've done. Could you talk about your decision to embed the standard turtle module (which is implemented in Tkinter) in a wxPython application? -John From philip at semanchuk.com Tue Aug 4 00:34:10 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 Aug 2009 00:34:10 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> Message-ID: <4B1B10B5-24D5-44D0-B16F-6308D8D8FAD2@semanchuk.com> On Aug 3, 2009, at 11:45 PM, Thangappan.M wrote: > Dear all, > > I want to access the database related stuffs in python.So I found the > PyGreSQL module in net. > Then I tried to download the module.But I am not able to download it. > > I am not a super user. > I am using Linux debian machine > Python version is 2.4.4 Hi Thangappan, If you want us to be able to help you, you'll need to give more information. For instance, why are you not able to download PyGreSQL? You might want to try psycopg2 which also gives you access to PostgreSQL from Python. You can download it from this site: http://initd.org/ Hope this helps Philip From http Tue Aug 4 00:34:15 2009 From: http (Paul Rubin) Date: 03 Aug 2009 21:34:15 -0700 Subject: Is python buffer overflow proof? References: Message-ID: <7x1vnsmc3c.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > > The Python interpreter is written in C. Python extension modules are > > written in C (or something similar). If you find an unprotected buffer > > in this C code, you can possibly overflow this buffer. > > How are C extension modules "_pure_ python"? A lot of basic Python constructs (like numbers and dictionaries) are implemented as C extension modules. It is reasonable to consider "pure Python" to include the contents of the Python standard library. From david.lyon at preisshare.net Tue Aug 4 00:42:25 2009 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 04 Aug 2009 00:42:25 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> Message-ID: <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> On Tue, 4 Aug 2009 09:15:47 +0530, "Thangappan.M" wrote: > I want to access the database related stuffs in python.So I found the > PyGreSQL module in net. > Then I tried to download the module.But I am not able to download it. Did none of the links here work? http://www.pygresql.org/readme.html#where-to-get > I am not a super user. > I am using Linux debian machine > Python version is 2.4.4 Try building it from source. Otherwise try getting it from pypi http://pypi.python.org/pypi/PyGreSQL/ David From nagle at animats.com Tue Aug 4 01:06:06 2009 From: nagle at animats.com (John Nagle) Date: Mon, 03 Aug 2009 22:06:06 -0700 Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: <4a77c0d9$0$1584$742ec2ed@news.sonic.net> Gabriel Genellina wrote: > En Mon, 03 Aug 2009 18:04:53 -0300, sturlamolden > escribi?: > >> On 2 Aug, 15:50, Jizzai wrote: >> >>> Is a _pure_ python program buffer overflow proof? >>> >>> For example in C++ you can declare a char[9] to hold user input. >>> If the user inputs 10+ chars a buffer overflow occurs. >> >> Short answer: NO > I disagree. You've just translated the responsability to check for > buffer overflows, from the Python VM, to the Java VM or the .Net runtime > (and all three suffered from buffer overruns and other problems in some > way or another). A more useful question is whether the standard libraries are being run through any of the commercial static checkers for possible buffer overflows. John Nagle From wuwei23 at gmail.com Tue Aug 4 01:33:33 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 22:33:33 -0700 (PDT) Subject: no-clobber dicts? References: Message-ID: Steven D'Aprano wrote: > I also have a series of unit tests for it if you're interested in them. That's several times today that kj has asked a question and you've responded with ready-to-go code. If this was Stackoverflow, I'd accuse you of reputation-whoring... You _can_ just post your cool code without the double act, y'know! :) From david.lyon at preisshare.net Tue Aug 4 01:55:20 2009 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 04 Aug 2009 01:55:20 -0400 Subject: Python docs disappointing - group effort to hire =?UTF-8?Q?writers=3F?= In-Reply-To: <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> References: <09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com> <109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com> <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> Message-ID: It isn't totally about the writers... Peoples egos are also at stake - it seems. If "Fred X wrote Doc Y".. they don't want their name taken off.. So they generally speaking don't want the docs changed. If you talk too much about docs.. you can be told you're OT.. even in a thread about docs... On Fri, 31 Jul 2009 17:12:43 -0700, Kee Nethery wrote: > I too find the Python docs not very useful and it really slows down my > learning curve. > > I wonder if it would make sense to find good tech writers, get a > quotes, and get some professionally written documentation WITH LOTS OF > EXAMPLES added to the standard Python documentation tree. > > I'd chip in money for that task. I've certainly spent enough buying > Python books to where it would be very reasonable to chip in the cost > of one book towards this project. Get enough people ... could be a > great thing. > > Even though it is not the version I use, I would suggest that the > really detailed docs with lots of examples be written against the > latest python version. > > Just a thought. > > Kee Nethery From steven at REMOVE.THIS.cybersource.com.au Tue Aug 4 02:09:52 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 06:09:52 GMT Subject: Is python buffer overflow proof? References: <7x1vnsmc3c.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 03 Aug 2009 21:34:15 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> > The Python interpreter is written in C. Python extension modules are >> > written in C (or something similar). If you find an unprotected >> > buffer in this C code, you can possibly overflow this buffer. >> >> How are C extension modules "_pure_ python"? > > A lot of basic Python constructs (like numbers and dictionaries) are > implemented as C extension modules. It is reasonable to consider "pure > Python" to include the contents of the Python standard library. Well, yes, but we're not saying that Python is bug-free. There could be bugs in the Python VM for that matter. The point is that code you write yourself can rely on "pure Python" to be free of buffer-overflows (for some definition of "rely") rather than having to worry about managing memory yourself. If you do this: buffer = [0]*1024 buffer[:] = [1]*1025 you don't over-write some random piece of memory, the list object resizes to accommodate, or fails with an exception instead. No special action is needed to avoid buffer overflows. You can't make that claim about C extensions. It's interesting to contrast that with DoS vulnerabilities in pure Python code. Python won't stop you from trying to calculate a googolplex: googol = 10**100 googolplex = 10**googol and doing so will be a moderately effective denial of service against your Python application. If you're concerned with that, you need to code defensively in the Python layer. Protecting against time-consuming operations is not part of Python's design. -- Steven From wuwei23 at gmail.com Tue Aug 4 02:21:20 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 3 Aug 2009 23:21:20 -0700 (PDT) Subject: Python docs disappointing - group effort to hire writers? References: <09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com> <109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com> <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> Message-ID: <95ea30c4-a5e5-458e-a8e4-4398c376e52d@13g2000prl.googlegroups.com> On Aug 4, 3:55?pm, David Lyon wrote: > It isn't totally about the writers... > Peoples egos are also at stake - it seems. Citation please. > If "Fred X wrote Doc Y".. they don't want their name taken off.. So > they generally speaking don't want the docs changed. Ditto. > If you talk too much about docs.. you can be told you're OT.. > even in a thread about docs... And again. All I've _ever_ seen (on this group at least) is the much repeated phrase "All patches to the docs are welcomed". If you'd like to cast aspersions on the characters of those doing the work over actually contributing yourself, you're certainly free to do so, just don't expect your claims to be taken seriously. Other people's refusal to do the work that _you_ consider to be necessary isn't "ego". From deets at nospam.web.de Tue Aug 4 02:48:31 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 04 Aug 2009 08:48:31 +0200 Subject: Which GUI framework to use? In-Reply-To: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> References: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> Message-ID: <7dq3tvF2d74reU1@mid.uni-berlin.de> koranthala schrieb: > Hi, > I am creating a very minimal application (a networking app). > I have written the application using Twisted. > Now, I need to put a GUI wrapper on the application. > The application needs a login screen and also it needs to be > minimized to system tray. If I right click the image on system tray, I > should be able to close it. > It uses some legacy code, so the whole app is written in Python > 2.4. Also, my company requires that I use permissive licenses (no GPL > - MIT, BSD, LGPL etc ok) Google this group. The discussions are abundant about this. Keep in mind that while Qt changed licenses to LGPL, PyQt didn't and thus you can't use it. > Which GUI framework is best for this? I tried using Tkinter, but it > does not support minimize to system tray (or I couldnt find it). > > This is my first foray to GUI programming, so other issues that I > am worried about - > 1. GUI needs a loop, Twisted needs a loop. How can both go ahead > without messing each other? Google is your friend here, too: http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html Diez From contact at xavierho.com Tue Aug 4 02:59:50 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 4 Aug 2009 16:59:50 +1000 Subject: Seeding the rand() Generator In-Reply-To: References: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> Message-ID: <2d56febf0908032359k4d3abf63i97bb4883a75b2a15@mail.gmail.com> On Tue, Aug 4, 2009 at 5:48 PM, Fred Atkinson wrote: > I tried using the same command I used when I did this in PHP. > That command was: mt_srand(date("w")) > > It was a PHP command that seeds the MySQL random function, > according to the folks on the PHP newsgroup. Well, some people have suggested to use that inside Python. That would work, right? Although, if you're just trying to find the Python-equivalent, fair enough. Regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From torppa at staff.megabaud.fi Tue Aug 4 03:12:30 2009 From: torppa at staff.megabaud.fi (Jarkko Torppa) Date: Tue, 04 Aug 2009 07:12:30 GMT Subject: Seeding the rand() Generator References: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> Message-ID: On 2009-08-04, Fred Atkinson wrote: > On Mon, 3 Aug 2009 20:00:08 -0700 (PDT), Carl Banks > wrote: >> >>If you don't "get" why this is a MySQL question and not a Python >>question, then you need to learn more about what you are doing. > > I wouldn't agree. > > I tried using the same command I used when I did this in PHP. > That command was: mt_srand(date("w")) > > It was a PHP command that seeds the MySQL random function, > according to the folks on the PHP newsgroup. It seems that they lied to you. Did you actually try that ? > I'm trying to figure out what the Python equivalent of that > is. Python equivalent of that is random.seed(x), if PHP docs are to be believed. > Now do you see? What you acutally want is "select *,rand(3) as rand from table order by rand" or something like that. That 3 is the seed in there. -- Jarkko Torppa From news123 at free.fr Tue Aug 4 03:24:57 2009 From: news123 at free.fr (News123) Date: Tue, 04 Aug 2009 09:24:57 +0200 Subject: merge two png pic In-Reply-To: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> References: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> Message-ID: <4a77e249$0$2449$426a74cc@news.free.fr> Hi, cocobear wrote: >> > >> Map = Image.new("RGB", (x,y)) >> > >> Map.paste(im, box) >> > >> Map.paste(im1,box) > >> > >> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE) > >> > >> But if thetwopngpicis too big , or if I have tomergemorepic >> > >> together, I will get MemoryError: > >>>>> > >> >>> Image.new("RGB",(44544,38656)) >> >> What do you want to do with such a big image? You will run into the same >> limitation when you are trying to display it. >> > > I want to download a map from google map with high precision > For me it sounds strange to handle such big files. Is the map you download from Google really that big? Mostly Google maps uses normally tiles of sizes 256x256 pixel, wich you have to compose to get the big image. If your problem is to combine tiles with different palettes, then you should pobably look at a way to 'unify' the palette of all tiles befor combining them. Being no expert of PIL I don't know whether this is easily possible though? bye N From contact at xavierho.com Tue Aug 4 03:31:29 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 4 Aug 2009 17:31:29 +1000 Subject: merge two png pic In-Reply-To: <4a77e249$0$2449$426a74cc@news.free.fr> References: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> <4a77e249$0$2449$426a74cc@news.free.fr> Message-ID: <2d56febf0908040031j2aabe2f8xa5c69be943030783@mail.gmail.com> Strange, I did reply but you didn't see it? >>>>> > >> >>> Image.new("RGB",(44544,38656)) > >> > >> What do you want to do with such a big image? You will run into the same > >> limitation when you are trying to display it. > >> > > > > I want to download a map from google map with high precision > Download several maps instead. Streaming if you have to. I'm not sure how you're going to avoid that MemoryError by trying to aggregate everything at once. Might have to make it a dynamic loader, and only load pictures as relevant (i.e: visible, and next to visible) Think how Google Maps do it. They can't possibly upload 5GB of pictures every time you access Maps - that wouldn't have worked. They work with the only visible areas. If you could tell us exactly what your program is trying to achieve, maybe we'll have a better solution for you. Best regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From lkrzysiak at gmail.com Tue Aug 4 03:33:49 2009 From: lkrzysiak at gmail.com (=?UTF-8?Q?=C5=81ukasz?=) Date: Tue, 4 Aug 2009 00:33:49 -0700 (PDT) Subject: Strange python script behaviour Message-ID: Hi, I have a problem with one of my python scripts. When I run this script from command line it works correctly, but if I set up cron to run this script on specified hour it works for a while and then "[Errno 32] Broken pipe" error occures (always). The strangest thing is that if I change command in CRON from python /home/xxx/script.py to python /home/xxx/script.py > /tmp/script.log 2>&1 the script always works correctly!!! The question is WHY? Any ideas? From electronixtar at gmail.com Tue Aug 4 03:38:27 2009 From: electronixtar at gmail.com (est) Date: Tue, 4 Aug 2009 00:38:27 -0700 (PDT) Subject: modify a exe's RT_ACCELERATOR table using pefile module Message-ID: Hi list, I need to modify a exe's RT_ACCELERATOR table, rename F1 to Ctrl+F1, and assign hotkey F1 to another function Is there a way to do it with pefile/python? A sample code is appreciated. Thanks! From ram.rachum at gmail.com Tue Aug 4 03:44:59 2009 From: ram.rachum at gmail.com (cool-RR) Date: Tue, 4 Aug 2009 00:44:59 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: <9e3b0c86-3a2a-4bc4-91f3-1b01a05d6b86@f37g2000yqn.googlegroups.com> On Aug 4, 7:12?am, John Posner wrote: > > ... I would also venture to say a key-map > > of sorts that is available thru the help menu where one could push an > > "Up" button, or a "rotate" button, and have the proper command > > inserted in the prompt, and then have the command execute, may also > > help make the connections here, a sort of *real* Visual Basic > > programming -- sorry Microsoft :P > > Along these lines, see my "ClixTur" application atwww.jjposner.net. > It's a point-and-click front end to the standard Python turtle module, > implementing only a very small subset of the turtle commands. As you > click, the "real turtle commands" appear in a transcript window. You can > then save (and maybe edit) and replay the transcript. > > Ram, I like a lot of what you've done. Could you talk about your > decision to embed the standard turtle module (which is implemented in > Tkinter) in a wxPython application? > > -John Certainly John- although I have not embedded the turtle module at all, I just wrote my own. This was actually quite a short process - What took the most time was developing the shell, which is a fork of PyShell. The original PyShell controls the same process it is run on, but my fork controls a different process (created by the multiprocessing package.) That took a lot of time. I actually created an independent package for it, called "shelltoprocess", which is a subfolder in PythonTurtle's source, so now anyone can use it for their own project. I am proud to say that this shell has some features that IDLE should envy. If you're asking WHY I put it in a wxPython application, the answer is pretty much what "r" said: To make it like any other "over the counter" Windows application, making people feel more comfortable with it. Also, not requiring them to install Python+packages, but just PythonTurtle. Ram. From fatkinson at mishmash.com Tue Aug 4 03:48:42 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Tue, 04 Aug 2009 00:48:42 -0700 Subject: Seeding the rand() Generator References: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> Message-ID: On Mon, 3 Aug 2009 20:00:08 -0700 (PDT), Carl Banks wrote: >Your question is a MySQL question, not a Python question. I don't >know off hand how to seed the RNG in MySQL, and, since this is a >Python group and not a MySQL group, I don't care to look it up. But >if you were able to produce the MySQL statement in PHP that does it >you shouldn't need to ask. > >If you don't "get" why this is a MySQL question and not a Python >question, then you need to learn more about what you are doing. I wouldn't agree. I tried using the same command I used when I did this in PHP. That command was: mt_srand(date("w")) It was a PHP command that seeds the MySQL random function, according to the folks on the PHP newsgroup. I'm trying to figure out what the Python equivalent of that is. Now do you see? Fred From http Tue Aug 4 03:56:05 2009 From: http (Paul Rubin) Date: 04 Aug 2009 00:56:05 -0700 Subject: Is python buffer overflow proof? References: <7x1vnsmc3c.fsf@ruckus.brouhaha.com> Message-ID: <7x4osoypuy.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > The point is that code you write yourself can rely on "pure Python" to be > free of buffer-overflows (for some definition of "rely") rather than > having to worry about managing memory yourself. Right. Basically the Python interpreter protects you reasonably well from silly errors. The interpreter hasn't had anywhere near the level of hardening required to claim to protect you from diabolically clever malicious code running in the same interpreter as your sensitive application. The Rexec/Bastion modules were basically swiss cheese. From loic.domaigne at googlemail.com Tue Aug 4 04:02:04 2009 From: loic.domaigne at googlemail.com (=?ISO-8859-1?Q?Lo=EFc_Domaign=E9?=) Date: Tue, 4 Aug 2009 01:02:04 -0700 (PDT) Subject: Strange python script behaviour References: Message-ID: Hi, > I have a problem with one of my python scripts. When I run this script > from command line it works correctly, but if I set up cron to run this > script on specified hour it works for a while and then "[Errno 32] > Broken pipe" error occures (always). > > The strangest thing is that if I change command in CRON > > from > python /home/xxx/script.py > to > python /home/xxx/script.py ?> /tmp/script.log 2>&1 > > the script always works correctly!!! > > The question is WHY? Any ideas? This is a cron issue, and has little with python to do. By default, cron will email the output produced by your script, unless you redirect. It does so by pipe to a "mail" program. Your error seems to indicate a problem with the latter (perhaps you don't have any "mail" program installed). HTH, Lo?c -- My Blog: http://www.domaigne.com/blog "To err is human, but to really foul things up you need a computer." -- Paul Ehrlich From anthra.norell at bluewin.ch Tue Aug 4 04:02:31 2009 From: anthra.norell at bluewin.ch (Anthra Norell) Date: Tue, 04 Aug 2009 10:02:31 +0200 Subject: Compiling regex inside function? In-Reply-To: References: Message-ID: <4A77EB17.2050308@bluewin.ch> alex23 wrote: > Anthra Norell wrote: > >> def entries (l): >> r = re.compile ('([0-9]+) entr(y|ies)') >> match = r.search (l) >> if match: return match.group (1) >> >> So the question is: does "r" get regex-compiled once at py-compile time >> or repeatedly at entries() run time? >> > The docs say: > The compiled versions of the most recent patterns passed to re.match > (), re.search() or re.compile() are cached, so programs that use only > a few regular expressions at a time needn?t worry about compiling > regular expressions. > > (But they don't say how few is 'only a few'...) > > If you're concerned about it, you could always set the compiled > pattern to a default value in the function's argspec, as that _is_ > only executed the once: > > def entries(line, regex = re.compile('([0-9]+) entr(y|ies)'): > match = regex.search(line) > ... > Excellent idea! Thank you all for the tips. Frederic From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 4 04:03:53 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 04 Aug 2009 10:03:53 +0200 Subject: Confessions of a Python fanboy In-Reply-To: <008eef29$0$9756$c3e8da3@news.astraweb.com> References: <008e82e8$0$9756$c3e8da3@news.astraweb.com> <4a72d7cf$0$25239$426a34cc@news.free.fr> <008eef29$0$9756$c3e8da3@news.astraweb.com> Message-ID: <4a77eb69$0$22600$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Fri, 31 Jul 2009 13:38:56 +0200, Bruno Desthuilliers wrote: > >>> On the other hand, we don't have to prefix names with @ and @@, >> Nope, we have to prefix them with 'self' or 'cls' (or even >> 'self.__class__'). > > Incorrect. Correct for all relevant cases, except this one: >>>> class K: > ... class_attribute = 'No @@ required.' > ... >>>> K().class_attribute > 'No @@ required.' Once again: Ruby's attributes are *private*, so you can't access an attribute (class or instance) from outside a method. IOW, the above example is irrelevant. (snip) > Disadvantages: your code is filled with line noise. It's an arbitrary > choice between @@ meaning instance attribute and @@ meaning class > attribute -- there's no logical reason for choosing one over the other, > so you have to memorise which is which. It's easy to get it wrong. So far that's something I have no difficulty living with. >>> and we >>> don't have the compiler trying to *guess* whether we're calling a >>> function or referring to a variable. >> Please re-read a bit more carefully - it's *all* method call. > > What did I misread from here? Nowhere - it's me that got it wrong here, sorry. (snip) >>> Somebody who knows more Ruby than me should try writing the Zen of >>> Ruby. Something like: >> (snip childish parody of Python Zen) >> >> Steven, is that any useful ? > > It made me feel good. Why ??? You don't like Ruby ? Fine, don't use it. Period. I can't see the point of all these pissing contests. > But seriously, while I admit that I have very little Ruby experience, and > so aren't in a great position to judge, it seems to me that Ruby doesn't > have anything like Python's over-riding design principles (the Zen). If > there is a design principle to Ruby, I can't see what it is. Fullfill the tastes of Matz ?-) (snip) >>> Although I'm sure Ruby has its good points. I'm not convinced anonymous >>> code blocks are one of them though. >> Ruby's code blocks come from Smalltalk, where they are an absolute >> necessity since message passing (which code blocks are part of) is the >> *only* builtin control flow in Smalltalk - so you just *need* this >> construction to provide branching and iterations. > > Just because Smalltalk had a particular (mis?)feature You can drop the 'mis' part IMHO. The point of code blocks in Smalltalk is that once you have something as powerful as the message+code blocks combo, you just don't need any other 'special form' for control flow. > doesn't mean that > other languages should copy it. Nope. But OTHO, Python is famous for all the features it copied from other languages !-) From spam.buster at web.de Tue Aug 4 04:08:23 2009 From: spam.buster at web.de (Lars Behrens) Date: Tue, 04 Aug 2009 10:08:23 +0200 Subject: Strange python script behaviour References: Message-ID: ?ukasz wrote: > The strangest thing is that if I change command in CRON > > from > python /home/xxx/script.py > to > python /home/xxx/script.py > /tmp/script.log 2>&1 > > the script always works correctly!!! > > The question is WHY? Any ideas? Seems to me that this is more of a shell thing... First of all, it is always a good idea to call applications with their full path from cronjobs: /usr/bin/python /home/xxx/script.py or whatever the output of your "which python" may be. How did you create the cronjob? Dependending on the editor you used, maybe there is a missing newline... -- Cheerz Lars From lkrzysiak at gmail.com Tue Aug 4 04:30:29 2009 From: lkrzysiak at gmail.com (=?UTF-8?Q?=C5=81ukasz?=) Date: Tue, 4 Aug 2009 01:30:29 -0700 (PDT) Subject: Strange python script behaviour References: Message-ID: <4cfffc2c-1923-4fc6-be0b-07ee4c4aae2b@h21g2000yqa.googlegroups.com> On 4 Sie, 10:02, Lo?c Domaign? wrote: > Hi, > > > I have a problem with one of my python scripts. When I run this script > > from command line it works correctly, but if I set up cron to run this > > script on specified hour it works for a while and then "[Errno 32] > > Broken pipe" error occures (always). > > > The strangest thing is that if I change command in CRON > > > from > > python /home/xxx/script.py > > to > > python /home/xxx/script.py ?> /tmp/script.log 2>&1 > > > the script always works correctly!!! > > > The question is WHY? Any ideas? > > This is a cron issue, and has little with python to do. > > By default, cron will email the output produced by your script, unless > you redirect. It does so by pipe to a "mail" program. Your error seems > to indicate a problem with the latter (perhaps you don't have any > "mail" program installed). > Hmm... interesting, but logical explanation. Cron has its weird issues. I guess I have to redirect outputs of all my scripts to /dev/ null in order to prevent them from this kind of error. Thanks for help :) From lkrzysiak at gmail.com Tue Aug 4 04:33:17 2009 From: lkrzysiak at gmail.com (=?UTF-8?Q?=C5=81ukasz?=) Date: Tue, 4 Aug 2009 01:33:17 -0700 (PDT) Subject: Strange python script behaviour References: Message-ID: <7e430558-f029-450e-bb06-2b273a7a2fe1@s31g2000yqs.googlegroups.com> On 4 Sie, 10:08, Lars Behrens wrote: > ?ukasz wrote: > > The strangest thing is that if I change command in CRON > > > from > > python /home/xxx/script.py > > to > > python /home/xxx/script.py ?> /tmp/script.log 2>&1 > > > the script always works correctly!!! > > > The question is WHY? Any ideas? > > Seems to me that this is more of a shell thing... > > First of all, it is always a good idea to call applications with their full > path from cronjobs: > > /usr/bin/python /home/xxx/script.py or whatever the output of your "which > python" may be. > > How did you create the cronjob? Dependending on the editor you used, maybe > there is a missing newline... > No, I've just simplified cron entries to not mess the example :) The key thing was redirecting stdin & stderr to file. But thanks anyway... :) From gagsl-py2 at yahoo.com.ar Tue Aug 4 04:48:15 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 04 Aug 2009 05:48:15 -0300 Subject: Is python buffer overflow proof? References: <4a77c0d9$0$1584$742ec2ed@news.sonic.net> Message-ID: En Tue, 04 Aug 2009 02:06:06 -0300, John Nagle escribi?: > Gabriel Genellina wrote: >> En Mon, 03 Aug 2009 18:04:53 -0300, sturlamolden >> escribi?: >> >>> On 2 Aug, 15:50, Jizzai wrote: >>> >>>> Is a _pure_ python program buffer overflow proof? >>>> For example in C++ you can declare a char[9] to hold user input. >>>> If the user inputs 10+ chars a buffer overflow occurs. > A more useful question is whether the standard libraries are being > run through any of the commercial static checkers for possible buffer > overflows. In the past the Python source code was checked with valgrind and some coverity tools; I don't know the current status. -- Gabriel Genellina From bartsmeets86 at gmail.com Tue Aug 4 04:52:20 2009 From: bartsmeets86 at gmail.com (Bart Smeets) Date: Tue, 4 Aug 2009 10:52:20 +0200 Subject: easy_install: unresolved external symbol In-Reply-To: References: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> Message-ID: <2119ee90908040152k5a744f98l7d5bc7da755948a2@mail.gmail.com> I could ofcourse use cxfreeze's binary package. But bbfreeze is not available as a binary. I would love to get easy_install to work. But I have no idea what's going wrong here. 2009/8/4 Gabriel Genellina > En Mon, 03 Aug 2009 17:39:44 -0300, Bart Smeets > escribi?: > > I keep getting errors when trying to use easy_install to install bbfreeze >> or >> cxfreeze (same errors). >> This is the output: >> http://pastebin.com/m65ba474d >> > > Can't you use the binary packages? > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From loic.domaigne at googlemail.com Tue Aug 4 05:11:21 2009 From: loic.domaigne at googlemail.com (=?ISO-8859-1?Q?Lo=EFc_Domaign=E9?=) Date: Tue, 4 Aug 2009 02:11:21 -0700 (PDT) Subject: Strange python script behaviour References: <4cfffc2c-1923-4fc6-be0b-07ee4c4aae2b@h21g2000yqa.googlegroups.com> Message-ID: <328af145-daaa-4239-bb42-dbf0a379540e@f37g2000yqn.googlegroups.com> > > > I have a problem with one of my python scripts. When I run this script > > > from command line it works correctly, but if I set up cron to run this > > > script on specified hour it works for a while and then "[Errno 32] > > > Broken pipe" error occures (always). > > > > The strangest thing is that if I change command in CRON > > > > from > > > python /home/xxx/script.py > > > to > > > python /home/xxx/script.py ?> /tmp/script.log 2>&1 > > > > the script always works correctly!!! > > > > The question is WHY? Any ideas? > > > This is a cron issue, and has little with python to do. > > > By default, cron will email the output produced by your script, unless > > you redirect. It does so by pipe to a "mail" program. Your error seems > > to indicate a problem with the latter (perhaps you don't have any > > "mail" program installed). > > Hmm... interesting, but logical explanation. Cron has its weird > issues. I guess I have to redirect outputs of all my scripts to /dev/ > null in order to prevent them from this kind of error. You could also set the MAILTO variable to "". HTH, Lo?c -- My Blog: http://www.domaigne.com/blog "Hardware: The parts of a computer system that can be kicked." -- Jeff Pesis. From david.lyon at preisshare.net Tue Aug 4 05:12:07 2009 From: david.lyon at preisshare.net (David Lyon) Date: Tue, 04 Aug 2009 05:12:07 -0400 Subject: =?UTF-8?Q?easy=5Finstall=3A=20unresolved=20external=20symbol?= In-Reply-To: <2119ee90908040152k5a744f98l7d5bc7da755948a2@mail.gmail.com> References: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> <2119ee90908040152k5a744f98l7d5bc7da755948a2@mail.gmail.com> Message-ID: <87f2eede5ce0f1391994db66153e3c96@preisshare.net> On Tue, 4 Aug 2009 10:52:20 +0200, Bart Smeets wrote: > I could ofcourse use cxfreeze's binary package. But bbfreeze is not > available as a binary. I would love to get easy_install to work. But I have > no idea what's going wrong here. What is going on is that setuptools does some very 'advanced' things. The best you can do is give the option to link to the ez_setup.py install script and let the users install it them themselves... David From steven at REMOVE.THIS.cybersource.com.au Tue Aug 4 05:28:50 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 04 Aug 2009 09:28:50 GMT Subject: Confessions of a Python fanboy References: <008e82e8$0$9756$c3e8da3@news.astraweb.com> <4a72d7cf$0$25239$426a34cc@news.free.fr> <008eef29$0$9756$c3e8da3@news.astraweb.com> <4a77eb69$0$22600$426a74cc@news.free.fr> Message-ID: On Tue, 04 Aug 2009 10:03:53 +0200, Bruno Desthuilliers wrote: >> Disadvantages: your code is filled with line noise. It's an arbitrary >> choice between @@ meaning instance attribute and @@ meaning class >> attribute -- there's no logical reason for choosing one over the other, >> so you have to memorise which is which. It's easy to get it wrong. > > So far that's something I have no difficulty living with. I don't like arbitrary symbols. Most people don't -- that's why "line noise" is unpopular. It's hard to read, hard to write, hard to maintain, and hard to talk about. The more line-noise, the worse the language. Of course, *ultimately* every symbol is arbitrary. There's no reason why "2" should mean the integer two, or "list" should mean a sequence type, but some symbols have such a long history, or have some other connection (say, with human languages), that the arbitrariness is lost. For instance, "+" is the obvious, non-arbitrary choice for the addition operator in any programming language using Latin symbols, and probably any programming language on Earth. (Not the *only* choice, but the obvious one.) I have a similar dislike for decorator syntax, because "@" ("at" in English) has nothing to do with decorations. It's an arbitrary symbol. One might argue that "$" would have been a more logical choice, because we turn numerals into currency by decorating it with a $ sign. (At least in the US, Canada, Australia, and a few other countries.) I use decorators all the time, and they are a fantastic invention, but the arbitrariness of the @ syntax is a negative. Oh well, one negative out of a whole lot of positives isn't too bad. At least I only have to deal with *one* such arbitrary symbol that needs memorizing. There's no need to distinguish between @@function_decorator and @class_decorator (or should it be the other way around?). Similarly, Python's choice of syntax for attributes is consistent: object.attribute works for everything, whether object is a class, an instance, a module, and whether attribute is callable or not. You can even use it on ints, provided you are clever about it: >>> 42 .__class__ >>>> Somebody who knows more Ruby than me should try writing the Zen of >>>> Ruby. Something like: >>> (snip childish parody of Python Zen) >>> >>> Steven, is that any useful ? >> >> It made me feel good. > > Why ??? > > You don't like Ruby ? Fine, don't use it. Period. I can't see the point > of all these pissing contests. Criticism of a language is a pissing contest? Yeah, okay, I was a tad dismissive. I un-apologetically jump to strong impressions about languages based on minimal use -- but I'm also willing to change my mind. Ruby certainly looks to me like it has some nice features. Syntax that looks like Perl isn't one of them though. >> Just because Smalltalk had a particular (mis?)feature > > You can drop the 'mis' part IMHO. The point of code blocks in Smalltalk > is that once you have something as powerful as the message+code blocks > combo, you just don't need any other 'special form' for control flow. Well, maybe, but remember, programming languages are only partly for communication to the compiler. They also have the requirement to communicate with human programmers as well, and that's even more important, because (1) humans spent a lot more time working with code than compilers do; (2) human programmers charge much more money than compilers do; (3) and you can modify the compiler to suit human needs much more easily than you can modify programmers to suit the compiler's needs. So I'd ask, does Smalltalk's message passing model match the way human beings think? If not, then that's a good sign it might be a misfeature. >> doesn't mean that >> other languages should copy it. > > Nope. But OTHO, Python is famous for all the features it copied from > other languages !-) Absolutely! There's nothing wrong with copying *good* features :) -- Steven From gregor.lingl at aon.at Tue Aug 4 05:30:23 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 11:30:23 +0200 Subject: ANN: Python's turtle module: collection of examples + demoViewer Message-ID: <4a77ffb2$0$1552$91cee783@newsreader04.highway.telekom.at> Hi all, A few days ago I've created a repository of turtle graphics demos/applications, that use Python's new turtle module. You can find it at at google code: http://python-turtle-demo.googlecode.com There are two versions of the collection: one for use with Python 3.1 and one for use with Python 2.5 / 2.6. The latter contains a *** backport of version 1.1 of the turtle module *** *** (from Python 3.1) to Python 2.5 / 2.6 *** Among others it contains all the examples I have demonstrated at Pycon 2009 and at EuroPython 2009. Moreover it contains the demoViewer (which is also in the source distribution of CPython) that lets you select the examples via a menu, display their source code and execute them in parallel. If you are interested to amend some of these examples, add some explanatory material or contribute additional examples, please tell me so I could add you as a committer to the project. I'd be glad to expand the repository whith interesting examples and applications using the turtle module. If you have questions concerning the examples, feel free to ask here or ask me directly via my email-address. I hope this collection will prove to be useful. Best regards, Gregor P.S.: I tried to announce it at comp.lang.python.announce but for some unknown reason it was not accepted there From bruno.42.desthuilliers at websiteburo.invalid Tue Aug 4 06:01:06 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Tue, 04 Aug 2009 12:01:06 +0200 Subject: Confessions of a Python fanboy In-Reply-To: References: <008e82e8$0$9756$c3e8da3@news.astraweb.com> <4a72d7cf$0$25239$426a34cc@news.free.fr> <008eef29$0$9756$c3e8da3@news.astraweb.com> <4a77eb69$0$22600$426a74cc@news.free.fr> Message-ID: <4a7806e2$0$438$426a34cc@news.free.fr> Steven D'Aprano a ?crit : > On Tue, 04 Aug 2009 10:03:53 +0200, Bruno Desthuilliers wrote: > >>> Disadvantages: your code is filled with line noise. It's an arbitrary >>> choice between @@ meaning instance attribute and @@ meaning class >>> attribute -- there's no logical reason for choosing one over the other, >>> so you have to memorise which is which. It's easy to get it wrong. >> So far that's something I have no difficulty living with. > > I don't like arbitrary symbols. Neither do I - when there are too many at least. But I can certainly live with a couple ones. Now the point wasn't about my personal tastes, but about the fact that this particular pair of "arbitrary symbols" was IMHO still usable - IOW, I wouldn't dismiss Ruby on this sole point. > Most people don't -- that's why "line > noise" is unpopular. It's hard to read, hard to write, hard to maintain, > and hard to talk about. The more line-noise, the worse the language. OTHO, too much verbosity is a pain too. Ever programmed in AppleScript ? "set the attribute XXX of object YYY of collection ZZZ to SomeValue"... Yuck. I bet you prefer "zzz[yyy].xxx = SomeValue" - which uses three arbitrary symbols. (snip) > Oh well, one negative out of > a whole lot of positives isn't too bad. Indeed. You could perhaps learn a bit more about Ruby's positives if you don't block on what you perceive (rightfully or not) as negative points ?-) (snip) >>>>> Somebody who knows more Ruby than me should try writing the Zen of >>>>> Ruby. Something like: >>>> (snip childish parody of Python Zen) >>>> >>>> Steven, is that any useful ? >>> It made me feel good. >> Why ??? >> >> You don't like Ruby ? Fine, don't use it. Period. I can't see the point >> of all these pissing contests. > > Criticism of a language is a pissing contest? Not necessarily. But: > Yeah, okay, I was a tad dismissive. I un-apologetically jump to strong > impressions about languages based on minimal use Possibly, yes. > -- but I'm also willing > to change my mind. Ruby certainly looks to me like it has some nice > features. Syntax that looks like Perl isn't one of them though. Not my cup of tea neither FWIW. But Ruby is nowhere near Perl in terms of "line noise". > >>> Just because Smalltalk had a particular (mis?)feature >> You can drop the 'mis' part IMHO. The point of code blocks in Smalltalk >> is that once you have something as powerful as the message+code blocks >> combo, you just don't need any other 'special form' for control flow. > > Well, maybe, but remember, programming languages are only partly for > communication to the compiler. They also have the requirement to > communicate with human programmers as well, and that's even more > important, because > > (1) humans spent a lot more time working with code than compilers do; > > (2) human programmers charge much more money than compilers do; > > (3) and you can modify the compiler to suit human needs much more easily > than you can modify programmers to suit the compiler's needs. > > So I'd ask, does Smalltalk's message passing model match the way human > beings think? Does all human beings think the same way ? And aren't human beings able to learn new ways ? Smalltalk's only control flow construct might seem a bit weird at first when all you've been exposed to so far are more "traditional" special constructs, but it's not hard to learn and is way more uniform and flexible than having special constructs for each and any possible situation. One could ask if functional programming or OO "matches the way human beings think". From experience, some of us just find FP and / or OO just obvious, and some won't never get it. FWIW, there are quite a few features and idioms in Python that I _now_ find readable and obvious, but that would have puzzled me ten years ago. This reminds me of a shop where the CTO had forbidden using any OO feature of the main language used there because "nobody would understand it" (needless to say, I only stayed there a couple weeks...). > >>> doesn't mean that >>> other languages should copy it. >> Nope. But OTHO, Python is famous for all the features it copied from >> other languages !-) > > Absolutely! There's nothing wrong with copying *good* features :) Well... at least when they make sense and integrate smoothly into the target language. From masklinn at masklinn.net Tue Aug 4 06:15:19 2009 From: masklinn at masklinn.net (Masklinn) Date: Tue, 4 Aug 2009 12:15:19 +0200 Subject: Help understanding the decisions *behind* python? In-Reply-To: <4a7715ff$0$1641$742ec2ed@news.sonic.net> References: <988a5f49-7907-4351-bfd0-7bb05e821795@o6g2000yqj.googlegroups.com> <4a7715ff$0$1641$742ec2ed@news.sonic.net> Message-ID: <80C5CBFA-5547-4675-B60E-033C5C60DEDB@masklinn.net> On 3 Aug 2009, at 18:57 , John Nagle wrote: > Dave Angel wrote: >> sturlamolden wrote: >>> On 20 Jul, 18:27, Phillip B Oldham wrote: >>> Tuples are used for passing arguments to and from a function. Common >>> use of tuples include multiple return values and optional arguments >>> (*args). > > That's from Mesa, the Xerox PARC language of the 1970s. > > Mesa used tuples for subroutine arguments in a very straightforward > way. Every function took one tuple as an argument, written as > parameters > in parentheses separated by commas. Most statically typed functional languages seem to do pretty much the same: uncurried functions really take a tuple as single argument rather than multiple arguments, using pattern matching to make it look like multiple arguments. Then again, most of them seem to default to curried functions these days, which is nice. From masklinn at masklinn.net Tue Aug 4 06:21:01 2009 From: masklinn at masklinn.net (Masklinn) Date: Tue, 4 Aug 2009 12:21:01 +0200 Subject: Confessions of a Python fanboy In-Reply-To: References: <008e82e8$0$9756$c3e8da3@news.astraweb.com> <4a72d7cf$0$25239$426a34cc@news.free.fr> <008eef29$0$9756$c3e8da3@news.astraweb.com> <4a77eb69$0$22600$426a74cc@news.free.fr> Message-ID: <6FE460F1-7484-4234-9D41-72AAE26AB06E@masklinn.net> On 4 Aug 2009, at 11:28 , Steven D'Aprano wrote: > So I'd ask, does Smalltalk's message passing model match the way human > beings think? Yes. From yinon.me at gmail.com Tue Aug 4 06:30:52 2009 From: yinon.me at gmail.com (Yinon Ehrlich) Date: Tue, 4 Aug 2009 03:30:52 -0700 (PDT) Subject: Obtaining Python version References: <4a776184$0$1611$742ec2ed@news.sonic.net> Message-ID: <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> On Aug 4, 1:19?am, John Nagle wrote: > This works, but it seems too cute: > > ?>>> pyver = map(int,sys.version.split()[0].split('.')) > ?>>> print(pyver) > [2, 6, 1] > > Is it guaranteed that the Python version string will be in a form > suitable for that? ?In other words, does "sys.version" begin > > N.N.N other stuff > > in all versions, and will it stay that way? ?Are there ever > non-numeric versions, like "3.2.rc1"? > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle Hi, Easy way to test for Python version: if sys.hexversion >= 0x2060100: pass -- Yinon From koranthala at gmail.com Tue Aug 4 06:32:51 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 03:32:51 -0700 (PDT) Subject: Which GUI framework to use? References: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> <7dq3tvF2d74reU1@mid.uni-berlin.de> Message-ID: On Aug 4, 11:48?am, "Diez B. Roggisch" wrote: > koranthala schrieb: > > > Hi, > > ? ?I am creating a very minimal application (a networking app). > > ? ?I have written the application using Twisted. > > ? ?Now, I need to put a GUI wrapper on the application. > > ? ?The application needs a login screen and also it needs to be > > minimized to system tray. If I right click the image on system tray, I > > should be able to close it. > > ? ?It uses some legacy code, so the whole app is written in Python > > 2.4. Also, my company requires that I use permissive licenses (no GPL > > - MIT, BSD, LGPL etc ok) > > Google this group. The discussions are abundant about this. Keep in mind > that while Qt changed licenses to LGPL, PyQt didn't and thus you can't > use it. > > > ? ?Which GUI framework is best for this? I tried using Tkinter, but it > > does not support minimize to system tray (or I couldnt find it). > > > ? ?This is my first foray to GUI programming, so other issues that I > > am worried about - > > ? ?1. GUI needs a loop, Twisted needs a loop. How can both go ahead > > without messing each other? > > Google is your friend here, too: > > http://twistedmatrix.com/projects/core/documentation/howto/choosing-r... > > Diez Sorry about it. I should have done the homework better. From lists at cheimes.de Tue Aug 4 06:58:03 2009 From: lists at cheimes.de (Christian Heimes) Date: Tue, 04 Aug 2009 12:58:03 +0200 Subject: Is python buffer overflow proof? In-Reply-To: <4a77c0d9$0$1584$742ec2ed@news.sonic.net> References: <4a77c0d9$0$1584$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > A more useful question is whether the standard libraries are being > run through any of the commercial static checkers for possible buffer > overflows. The CPython interpreter is constantly checked with http://www.coverity.com/. Although Python is used for critical stuff at large companies like Apple, Google and NASA, only a few critical bugs in the C code have been found in the last couple of years. From gregor.lingl at aon.at Tue Aug 4 07:19:48 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 13:19:48 +0200 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: <4a781958$0$1552$91cee783@newsreader04.highway.telekom.at> cool-RR schrieb: > Hello, > > I wanted to announce that I have just released my little side project, > PythonTurtle. > Here is its website: > http://pythonturtle.com > > Its goal is to be the lowest-threshold way to learn (or teach) Python. > You can read more about it and download it on the website. > > Ram. Hi Ram, that's indeed a nice starting point for kids to doing turtle graphics, although currently it seems to implement only a very small subset of Python's turtle module's capabilities, even less than those of the old turtle module (that shipped with Python upto 2.5). Moreover I have to complain that you decided to use different commands for the turtle's actions - go instead of forward, turn instead of left and right etc. First I think left and right are more intuitive than turn as they do not need negative angles as arguments, which might matter for young children. Also I cannot see the advantage of cammands like visible() or invisible() over showturtle() and hideturtle() But second even kids - when learning how to program - will arrive at a point where it's no more problem to use an editor like IDLE so they could easily switch to Python's turtle module. That would be even easier if they had not to learn a new command set. Moreover a learning environment like PythonTurtle needs something like an editor - at least a simple one - in order to create programs that can be run repeatedly. Coding, that's creating programs - not only issuing a sequence of cammands interactively. It would be certainly a good thing if one had a similar environment using Tkinter, preferably also as part of the standard distribution of Python accompanying the turtle module. I think it should not be that difficult to create a GUI of this sort combining IDLE's shell window, its editor and turtle.py. Alas, at the moment I'm too busy with some othr work to start a project like this. Perhaps someone else might be interested? I'd enjoy to join a team doing it. Finally I'd like to stress, that the aims of PythonTurtle and Python's turtle module are quite different - as one could grasp easily by trying out the collection of examples at python-turtle-demo.googlecode.com that I posted in another posting. Anyway they could very well complement one another in some more mature state of development. Best regards, Gregor From thorsten at thorstenkampe.de Tue Aug 4 07:23:12 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Tue, 4 Aug 2009 13:23:12 +0200 Subject: Is python buffer overflow proof? References: Message-ID: * Jizzai (Sun, 02 Aug 2009 13:50:14 GMT) > Is a _pure_ python program buffer overflow proof? You cannot create "your own" buffer overflow in Python as you can in C and C++ but your code could still be vulnerable if the underlying Python construct is written in C. See [1] for instance. Thorsten [1] http://www.gentoo.org/security/en/glsa/glsa-200610-07.xml From IDOL at il.ibm.com Tue Aug 4 07:25:17 2009 From: IDOL at il.ibm.com (Ido Levy) Date: Tue, 4 Aug 2009 14:25:17 +0300 Subject: How to fetch an XML file using an HTTPS query Message-ID: Hello All I am quite new to Python and I would appreciate your advice on the following issue. I am trying to fetch an XML file from a remote server using an HTTPS query. When testing the HTTPS query from the browser after I entered the URL I got a pop-up box asking me if I want to "save a file" or "open with". >From a Python script I tried using urllib but it fails. I validated that my Python release support https request by using the following code and a different URL: import urllib print urllib.urlopen('https://...').read() and got the expected result. When I tried the above code or the following one with the URL that should return an XML file import sys import urllib import urllib2 headers = {'User-Agent': 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.12) Gecko/20050923 Firefox/1.0.7', 'Cookie': 'JSESSIONID=000000000000000000000000000:111111111;Path=/',} url = "https://..." req = urllib2.Request(url, None, headers) urlFH = urllib2.urlopen(req) headers = urlFH.info() page_content = urlFH.readlines() urlFH.close() for line in page_content: print 'line: %s' % line I got the following result in both cases: Invalid filter passed. Thanks in Advance Ido Levy -------------- next part -------------- An HTML attachment was scrubbed... URL: From sibtey.mehndi at genpact.com Tue Aug 4 07:31:42 2009 From: sibtey.mehndi at genpact.com (Mehndi, Sibtey) Date: Tue, 4 Aug 2009 04:31:42 -0700 Subject: how to create a Com object of Picalo Module Message-ID: <1A343A98C8DAE44A8D9D1BF310F90D5E0140E41E62@GCPWINGGN2EVS11.IND.CORP.AD> Hi I want to use the picalo module in to VB.NET so I have tried to create the COM object of picalo module but I am unable to create. Anyone can help me out to create the picalo com object. Thanks, Sibtey This e-mail (and any attachments), is confidential and may be privileged. It may be read, copied and used only by intended recipients. Unauthorized access to this e-mail (or attachments) and disclosure or copying of its contents or any action taken in reliance on it is unlawful. Unintended recipients must notify the sender immediately by e-mail/phone & delete it from their system without making any copies or disclosing it to a third person. -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Tue Aug 4 07:34:44 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 4 Aug 2009 21:34:44 +1000 Subject: Obtaining Python version In-Reply-To: <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> Message-ID: <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> On Tue, Aug 4, 2009 at 8:30 PM, Yinon Ehrlich wrote: > Hi, > Easy way to test for Python version: > if sys.hexversion >= 0x2060100: > pass > Great suggestion. I just tested it on my newly installed Python 3.1 (as of 3.1r31) >>> import sys >>> "%X" % sys.hexversion '30100F0' That's genius - '301' for Python 3.1, and '00F0' is r31! I'm definitely going to use this more often in the future. Cheers, Xavier -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Tue Aug 4 07:37:11 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 4 Aug 2009 21:37:11 +1000 Subject: Obtaining Python version In-Reply-To: <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> Message-ID: <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> On Tue, Aug 4, 2009 at 9:34 PM, Xavier Ho wrote: > ... and '00F0' is r31! > Actually, 00F0 is 576 in decimal. Maybe it's the subversion? Anyhow, it's still good! -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregor.lingl at aon.at Tue Aug 4 07:37:23 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 13:37:23 +0200 Subject: Announcing PythonTurtle In-Reply-To: <9e3b0c86-3a2a-4bc4-91f3-1b01a05d6b86@f37g2000yqn.googlegroups.com> References: <9e3b0c86-3a2a-4bc4-91f3-1b01a05d6b86@f37g2000yqn.googlegroups.com> Message-ID: <4a781d85$0$2311$91cee783@newsreader02.highway.telekom.at> cool-RR schrieb: > On Aug 4, 7:12 am, John Posner wrote: >>> ... I would also venture to say a key-map >>> ... > If you're asking WHY I put it in a wxPython application, the answer is > pretty much what "r" said: To make it like any other "over the > counter" Windows application, making people feel more comfortable with > it. > Also, not requiring them to install Python+packages, but just > PythonTurtle. Fortunately it's not necessary to install 'packages' to use Python's turtle module as it is one of it's 'batteries included'. And I think it's not so a bad idea to install Python if one want's to learn it, anyway. Regards, Gregor > > Ram. From cocobear.cn at gmail.com Tue Aug 4 08:01:47 2009 From: cocobear.cn at gmail.com (cocobear) Date: Tue, 4 Aug 2009 05:01:47 -0700 (PDT) Subject: merge two png pic References: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> <4a77e249$0$2449$426a74cc@news.free.fr> Message-ID: <72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com> On Aug 4, 3:24?pm, News123 wrote: > Hi, > > > > > > cocobear wrote: > >> > >> Map = Image.new("RGB", (x,y)) > >> > >> Map.paste(im, box) > >> > >> Map.paste(im1,box) > > >> > >> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE) > > >> > >> But if thetwopngpicis too big , or if I have tomergemorepic > >> > >> together, I will get MemoryError: > > >>>>> > >> >>> Image.new("RGB",(44544,38656)) > > >> What do you want to do with such a big image? You will run into the same > >> limitation when you are trying to display it. > > > I want to download a map from google map with high precision > > For me it sounds strange to handle such big files. > > Is the map you download from Google really that big? > Mostly Google maps uses normally tiles of sizes 256x256 pixel, wich you > have to compose to get the ?big image. > The map I downloaded from Google is small(256x256). These small maps will compose a big image. > If your problem is to combine tiles with different palettes, then you > should pobably look at a way to ?'unify' the palette of all tiles befor > combining them. > I think it is impossible to 'unify' all this tiles. > Being no expert of PIL I don't know whether this is easily possible though? > > bye > > N From hendrik at microcorp.co.za Tue Aug 4 08:14:40 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 4 Aug 2009 14:14:40 +0200 Subject: Which GUI framework to use? In-Reply-To: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> References: <43a2d0a9-7166-4f7c-9fb8-13a23980c1d7@y10g2000prf.googlegroups.com> Message-ID: <200908041414.41026.hendrik@microcorp.co.za> On Tuesday 04 August 2009 06:09:05 koranthala wrote: > Hi, > I am creating a very minimal application (a networking app). > I have written the application using Twisted. > Now, I need to put a GUI wrapper on the application. > The application needs a login screen and also it needs to be > minimized to system tray. If I right click the image on system tray, I > should be able to close it. > It uses some legacy code, so the whole app is written in Python > 2.4. Also, my company requires that I use permissive licenses (no GPL > - MIT, BSD, LGPL etc ok) > > Which GUI framework is best for this? I tried using Tkinter, but it > does not support minimize to system tray (or I couldnt find it). look at iconify, and at withdraw - Hendrik From ram.rachum at gmail.com Tue Aug 4 08:19:48 2009 From: ram.rachum at gmail.com (cool-RR) Date: Tue, 4 Aug 2009 05:19:48 -0700 (PDT) Subject: Announcing PythonTurtle References: <4a781958$0$1552$91cee783@newsreader04.highway.telekom.at> Message-ID: <766a3973-6960-4500-9c7c-88d5261b823c@24g2000yqm.googlegroups.com> > Hi Ram, > > that's indeed a nice starting point for kids to doing turtle graphics, > although currently it seems to implement only a very small subset of > Python's turtle module's capabilities, even less than those of the old > turtle module (that shipped with Python upto 2.5). > I agree - an undo feature for example would be nice and it's something I would like to do in a future version. Other than that though, I don't think having many turtle-functions is so important. I think the important thing is for the student to build complex things from simple building blocks. > Moreover I have to complain that you decided to use different commands > for the turtle's actions - go instead of forward, turn instead of left > and right etc. First I think left and right are more intuitive than turn > as they do not need negative angles as arguments, which might matter for > young children. Also I cannot see the advantage of cammands like > visible() or invisible() over showturtle() and hideturtle() > But second even kids - when learning how to program - will arrive at a > point where it's no more problem to use an editor like IDLE so they > could easily switch to Python's turtle module. That would be even easier > if they had not to learn a new command set. > Moreover a learning environment like PythonTurtle needs something like > an editor - at least a simple one - in order to create programs that can > be run repeatedly. Coding, that's creating programs - not only issuing > a sequence of cammands interactively. > A text editor would be a good feature for future versions. Regarding the naming of functions: I named them in the way that seemed best to me. You seem not to agree, you like the way your functions are named better, and there's little point in arguing over which convention is truly better. The convention I chose is the one that seemed ideal to me. I did consider naming the functions the same way you did for consistency, but I decided not to compromise the quality of PythonTurtle just to be compatible with a module that my users may not even use. > It would be certainly a good thing if one had a similar environment > using Tkinter, preferably also as part of the standard distribution of > Python accompanying the turtle module. I think it should not be that > difficult to create a GUI of this sort combining IDLE's shell window, > its editor and turtle.py. Alas, at the moment I'm too busy with some > othr work to start a project like this. Perhaps someone else might be > interested? I'd enjoy to join a team doing it. I agree that it shouldn't be difficult; The question is whether someone will step up and do it. > Finally I'd like to stress, that the aims of PythonTurtle and Python's > turtle module are quite different - as one could grasp easily by trying > out the collection of examples at python-turtle-demo.googlecode.com that > I posted in another posting. Anyway they could very well complement one > another in some more mature state of development. > > Best regards, > Gregor Thank you for your feedback Gregor. Ram Rachum. From thangappan143 at gmail.com Tue Aug 4 08:25:30 2009 From: thangappan143 at gmail.com (Thangappan.M) Date: Tue, 4 Aug 2009 17:55:30 +0530 Subject: Problem in Installing PyGreSQL Message-ID: <7aa29e790908040525p562245c8v95d5a5d875fe606f@mail.gmail.com> Dear all, While installing PyGreSQl module in my machine I got the error as pg_config command not found. I am not a super user. how can I install this pg_config tool. -- Regards, Thangappan.M -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Tue Aug 4 08:27:27 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 04 Aug 2009 07:27:27 -0500 Subject: Is python buffer overflow proof? In-Reply-To: References: <7dnissF2bthr0U1@mid.uni-berlin.de> Message-ID: <4A78292F.8040907@tim.thechases.com> Marcus Wanner wrote: > On 8/3/2009 3:45 AM, Diez B. Roggisch wrote: >> But you can cast the resulting pointer to an array of larger size, and >> there you are. > > Ah, that makes sense. I had forgotten about ctypes.cast(). You *can* shoot yourself in the foot with Python, you just have to aim much more carefully than you do with C/C++. -tkc From gregor.lingl at aon.at Tue Aug 4 08:45:47 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 14:45:47 +0200 Subject: Announcing PythonTurtle In-Reply-To: <766a3973-6960-4500-9c7c-88d5261b823c@24g2000yqm.googlegroups.com> References: <4a781958$0$1552$91cee783@newsreader04.highway.telekom.at> <766a3973-6960-4500-9c7c-88d5261b823c@24g2000yqm.googlegroups.com> Message-ID: <4a782d7b$0$1549$91cee783@newsreader04.highway.telekom.at> cool-RR schrieb: >> Hi Ram, >> >> that's indeed a nice starting point for kids to doing turtle graphics, >> although currently it seems to implement only a very small subset of >> Python's turtle module's capabilities, even less than those of the old >> turtle module (that shipped with Python upto 2.5). ... > A text editor would be a good feature for future versions. > Regarding the naming of functions: I named them in the way that seemed > best to me. You seem not to agree, you like the way your functions are > named better, and there's little point in arguing over which > convention is truly better. The convention I chose is the one that > seemed ideal to me. > I did consider naming the functions the same way you did for > consistency, but I decided not to compromise the quality of > PythonTurtle just to be compatible with a module that my users may not > even use. That's the advantage of not developing for the standard library. In fact those elementary commands you use were present already in the old turtle module. When I decided to extend the old turtle module a primary requirement was that it remains 100% compatible to the old one. New versions of a module in the standard library must not break code of previous users of that module. In short: I did not name these functions but I had to use the names that already were there. Nevertheless I'd prefer left and right over turn even today, especially for kids as I argued before. Regards, Gregor > >> It would be certainly a good thing if one had a similar environment >> using Tkinter, preferably also as part of the standard distribution of >> Python accompanying the turtle module. I think it should not be that >> difficult to create a GUI of this sort combining IDLE's shell window, >> its editor and turtle.py. Alas, at the moment I'm too busy with some >> othr work to start a project like this. Perhaps someone else might be >> interested? I'd enjoy to join a team doing it. > > I agree that it shouldn't be difficult; The question is whether > someone will step up and do it. > >> Finally I'd like to stress, that the aims of PythonTurtle and Python's >> turtle module are quite different - as one could grasp easily by trying >> out the collection of examples at python-turtle-demo.googlecode.com that >> I posted in another posting. Anyway they could very well complement one >> another in some more mature state of development. >> >> Best regards, >> Gregor > > Thank you for your feedback Gregor. > > Ram Rachum. From darcy at druid.net Tue Aug 4 08:48:56 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 08:48:56 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> Message-ID: <20090804084856.b825967a.darcy@druid.net> On Tue, 04 Aug 2009 00:42:25 -0400 David Lyon wrote: > > Then I tried to download the module.But I am not able to download it. > > Did none of the links here work? > > http://www.pygresql.org/readme.html#where-to-get The RPM seems to be missing. I am currently trying to find one. I don't run Linux myself and sometimes forget to check that we have a working RPM. > > I am not a super user. > > I am using Linux debian machine > > Python version is 2.4.4 > > Try building it from source. That will work of course and it is a small enough package that it should build painlessly. There is a working setup.py. > Otherwise try getting it from pypi It is also missing the RPM. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From fatkinson at mishmash.com Tue Aug 4 08:58:46 2009 From: fatkinson at mishmash.com (Fred Atkinson) Date: Tue, 04 Aug 2009 05:58:46 -0700 Subject: Seeding the rand() Generator References: <0b7c702f-5775-418e-8fc5-2f9df7487867@c2g2000yqi.googlegroups.com> Message-ID: <52cg759c3kg732ikns1emlgb5c3joom4md@4ax.com> On Tue, 04 Aug 2009 07:12:30 GMT, Jarkko Torppa wrote: >On 2009-08-04, Fred Atkinson wrote: >> On Mon, 3 Aug 2009 20:00:08 -0700 (PDT), Carl Banks >> wrote: >>> >>>If you don't "get" why this is a MySQL question and not a Python >>>question, then you need to learn more about what you are doing. >> >> I wouldn't agree. >> >> I tried using the same command I used when I did this in PHP. >> That command was: mt_srand(date("w")) >> >> It was a PHP command that seeds the MySQL random function, >> according to the folks on the PHP newsgroup. > >It seems that they lied to you. Did you actually try that ? > >> I'm trying to figure out what the Python equivalent of that >> is. > >Python equivalent of that is random.seed(x), if PHP docs are to be believed. > >> Now do you see? > >What you acutally want is "select *,rand(3) as rand from table >order by rand" or something like that. That 3 is the seed in there. Yes, I actually tried that and it worked. Things got much more random after I started using it. Regards, Fred From benjamin.kaplan at case.edu Tue Aug 4 09:03:55 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 4 Aug 2009 09:03:55 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <20090804084856.b825967a.darcy@druid.net> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> Message-ID: On Tue, Aug 4, 2009 at 8:48 AM, D'Arcy J.M. Cain wrote: > On Tue, 04 Aug 2009 00:42:25 -0400 > David Lyon wrote: >> > Then I tried to download the module.But I am not able to download it. >> >> Did none of the links here work? >> >> http://www.pygresql.org/readme.html#where-to-get > > The RPM seems to be missing. ?I am currently trying to find one. ?I > don't run Linux myself and sometimes forget to check that we have a > working RPM. > >> > I am not a super user. >> > I am using Linux debian machine >> > Python version is 2.4.4 >> >> Try building it from source. > > That will work of course and it is a small enough package that it > should build painlessly. ?There is a working setup.py. > >> Otherwise try getting it from pypi > > It is also missing the RPM. Doesn't matter here. Debians use DEBs (DEBian packages), not RPMs (for the Red Hat Package Manager). Either way, the OP can't install system level packages. That's what the comment about not being a super user meant. > > -- > D'Arcy J.M. Cain ? ? ? ? | ?Democracy is three wolves > http://www.druid.net/darcy/ ? ? ? ? ? ? ? ?| ?and a sheep voting on > +1 416 425 1212 ? ? (DoD#0082) ? ?(eNTP) ? | ?what's for dinner. > -- > http://mail.python.org/mailman/listinfo/python-list > From mydevforums at gmail.com Tue Aug 4 09:15:24 2009 From: mydevforums at gmail.com (IronyOfLife) Date: Tue, 4 Aug 2009 06:15:24 -0700 (PDT) Subject: Python configuration question when python scripts are executed using Appweb as web server. References: Message-ID: On Aug 3, 8:42?pm, "Gabriel Genellina" wrote: > En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife ? > escribi?: > > > I have installed python 2.6.2 in windows xp professional machine. I > > have set the following environment variables -- PYTHONPATH. It points > > to following windows folders: python root folder, the lib folder and > > lib-tk folder. > > Why? Did you read it somewhere? Usually there is no need to set the ? > PYTHONPATH variable at all; remove it. > > > I have configured IIS to execute python scripts. > > > I do not have any issues executing python scripts from the python > > interpreter window or from the browser using IIS as the web server. > > Try again after PYTHONPATH is removed, and make sure you can import all ? > the required modules from the Python console. Only then try to run the cgi ? > scripts. > > > However, when I use the open source Appweb web browser to execute > > python scripts. It is able to execute only simple script without > > issues. [...]However I am not able to execute python scripts that ? > > contain import > > statements. I need to point out here that i do not have issue with > > using os or sys packages. When I tried to execute the sample client > > script that came with the gnutls wrapper for python, I got error. I > > narrowed it down to the "from ... import" line in the example. > > > from gnutls.crypto import * > > from gnutls.connection import * > > Check that the above lines work fine from inside the Python console. > If not, something went wrong when you installed the gnutls Python package. > > > Next step, in order to debug, I used the module finder to see what is > > happening. To being with I used the module finder to find out the > > modules loaded for the simple script hello.py. > > Debugging cgi scripts isn't easy sometimes; try adding this line at the ? > start of your script: > > import cgitb;cgitb.enable() > > You should get a nicely formatted stack trace whenever an exception is ? > raised. If you get an HTTP error instead (like 500 Internal Server Error) ? > it's likely a syntax error, you must fix it before continuing. > Then, you may find that modulefinder is no more needed. > > > import pdb > > pdb.set_trace() > > pdb cannot work inside a CGI script; remove that. > > > Once again, let me stress that this issue is happening only when I use > > appweb as the web server. > > I don't know appweb, but if you first make sure the script works from the ? > command line, it should be much easier to make it work in the web server. > > -- > Gabriel Genellina Hi Gabriel Thanks for your reply. As I had mentioned in my original post, I am able to successfully execute gnutls client python script while using python interpreter and from the web browser while using IIS as web server. The scripts were not executing successfully only when I used AppWeb as web server. Setting PYTHONPATH environment variables is mentioned in Python docs. I figured out how to get the debug statements to write to Appweb logs and from there I found out the issue to be ImportError. Python does provide a very cryptic error message. "(, ImportError('DLL load failed: The specified module could not be found.',), )" I then downloaded filemon (as suggested in another forum) utility tool for windows environment. Using the tool I found that python.exe is trying to load gnutls related dlls from system path and a list of folders (I dont know why it didnt try to pick up the dlls from all the path provided in PATH environment variable) none of which contain the gnutls related dlls. I solved the issue temporarily by copying the gnutls related dlls to the path searched by python.exe Now my gnutls client python script executes successfully when i use Appweb as the web server, NOTE: When I use python interpreter or IIS as webserver the path where python.exe looks for gnutls related dll's are different. In this scenario python.exe is able to successfully load the required dlls. From davea at ieee.org Tue Aug 4 09:29:35 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 04 Aug 2009 09:29:35 -0400 Subject: Newbie Question regarding __init__() In-Reply-To: References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> <4A77A43D.4000709@ieee.org> Message-ID: <4A7837BF.6070903@ieee.org> Dennis Lee Bieber wrote: > On Mon, 03 Aug 2009 23:00:13 -0400, Dave Angel > declaimed the following in gmane.comp.python.general: > > >> To throw away the result of an expression in Python is even easier. >> Just don't use it. >> func1() and func2() >> is a valid expression whose result is not used. And func2()'s result is >> therefore irrelevant. But shortcircuiting means that func2() is only >> called if func1() returned False (or something equivalent to it, like 0 >> or an empty list) >> > > Backwards... > > When using "and", the RHS is only evaluated if the LHS evaluates to > TRUE (if the LHS is FALSE, why go further, since False and anything -> > False). > > Conversely, when using "or", the RHS is only evaluated if the LHS is > FALSE. > You're right of course. Slip of the keyboard. DaveA From nyamatongwe+thunder at gmail.com Tue Aug 4 09:32:55 2009 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 04 Aug 2009 13:32:55 GMT Subject: Is python buffer overflow proof? In-Reply-To: References: Message-ID: Thorsten Kampe: > You cannot create "your own" buffer overflow in Python as you can in C > and C++ but your code could still be vulnerable if the underlying Python > construct is written in C. Python's standard library does now include unsafe constructs. import ctypes x = '1234' # Munging byte 1 OK ctypes.memset(x, 1, 1) print(x) # Next line writes beyond end of variable and crashes ctypes.memset(x, 1, 20000) print(x) Neil From philip at semanchuk.com Tue Aug 4 09:34:17 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 Aug 2009 09:34:17 -0400 Subject: Problem in Installing PyGreSQL In-Reply-To: <7aa29e790908040525p562245c8v95d5a5d875fe606f@mail.gmail.com> References: <7aa29e790908040525p562245c8v95d5a5d875fe606f@mail.gmail.com> Message-ID: On Aug 4, 2009, at 8:25 AM, Thangappan.M wrote: > Dear all, > > While installing PyGreSQl module in my machine I got the error as > pg_config > command not found. > I am not a super user. > how can I install this pg_config tool. Thangappan, pg_config is part of PostgreSQL. It reports various pieces of information about the Postgres installation, like the BINDIR, INCLUDEDIR, compile flags, version etc. If PostgreSQL is installed on your machine, then I'll bet that pg_config is also installed, but it isn't on your path so the PyGreSQl installer can't find it. When you're having trouble installing a specific package like PyGreSQl, you'll probably get better answers by posting your questions to a specific mailing list: http://mailman.vex.net/mailman/listinfo/pygresql By searching the archives you might even find that your question has been answered already. Good luck Philip From tycho at tycho.ws Tue Aug 4 09:41:30 2009 From: tycho at tycho.ws (Tycho Andersen) Date: Tue, 4 Aug 2009 08:41:30 -0500 Subject: How to fetch an XML file using an HTTPS query In-Reply-To: <49b3a7400908040638h46d4e4dcxe5cd4120e9c2c7a1@mail.gmail.com> References: <49b3a7400908040638h46d4e4dcxe5cd4120e9c2c7a1@mail.gmail.com> Message-ID: <49b3a7400908040641l5f5daaa8v374041b7fbac442a@mail.gmail.com> Blah, forgot to include the list. When is python-list going to get Reply-To? \t On Tue, Aug 4, 2009 at 8:38 AM, Tycho Andersen wrote: > Hi Ido, > > On Tue, Aug 4, 2009 at 6:25 AM, Ido Levy wrote: >> [snip] >> I got the following result in both cases: >> ? ? ? ? >> ? ? ? ? >> ? ? ? ? Invalid filter passed. >> ? ? ? ? > > To me, this doesn't look like a python problem: the application was > successfully connected to and returned a result. The problem you're > experiencing is that it wasn't the result you expected. Are you sure > you're setting the right headers, posting the right form values, etc. > and giving the app exactly what it wants? > > \t > From darcy at druid.net Tue Aug 4 09:53:40 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 09:53:40 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> Message-ID: <20090804095340.67e2de0f.darcy@druid.net> On Tue, 4 Aug 2009 09:03:55 -0400 Benjamin Kaplan wrote: > Doesn't matter here. Debians use DEBs (DEBian packages), not RPMs (for > the Red Hat Package Manager). Either way, the OP can't install system > level packages. That's what the comment about not being a super user > meant. Urk! I thought that all the Linux distros used RPMs. Maybe I should just remove that link and let each distro provide their own package. As long as it was just one I could take some steps to make sure that I wasn't distributing malware but the more packages I supply that I can't personally test, the more uncomfortable I get. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From darcy at druid.net Tue Aug 4 09:55:47 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 09:55:47 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> Message-ID: <20090804095547.a5274e22.darcy@druid.net> On Tue, 4 Aug 2009 09:03:55 -0400 Benjamin Kaplan wrote: > Doesn't matter here. Debians use DEBs (DEBian packages), not RPMs (for > the Red Hat Package Manager). Either way, the OP can't install system > level packages. That's what the comment about not being a super user > meant. By the way, you don't have to be super user to install PyGreSQL. You just need SU if you want to install it system wide. PyGreSQL doesn't require any special privileges to run. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From benjamin.kaplan at case.edu Tue Aug 4 10:02:23 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 4 Aug 2009 10:02:23 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: <20090804095547.a5274e22.darcy@druid.net> References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> <20090804095547.a5274e22.darcy@druid.net> Message-ID: On Tue, Aug 4, 2009 at 9:55 AM, D'Arcy J.M. Cain wrote: > On Tue, 4 Aug 2009 09:03:55 -0400 > Benjamin Kaplan wrote: >> Doesn't matter here. Debians use DEBs (DEBian packages), not RPMs (for >> the Red Hat Package Manager). Either way, the OP can't install system >> level packages. That's what the comment about not being a super user >> meant. > > By the way, you don't have to be super user to install PyGreSQL. ?You > just need SU if you want to install it system wide. ?PyGreSQL doesn't > require any special privileges to run. Right, but the packages install system-wide. That's why he could compile it himself but not use the package. > > -- > D'Arcy J.M. Cain ? ? ? ? | ?Democracy is three wolves > http://www.druid.net/darcy/ ? ? ? ? ? ? ? ?| ?and a sheep voting on > +1 416 425 1212 ? ? (DoD#0082) ? ?(eNTP) ? | ?what's for dinner. > -- > http://mail.python.org/mailman/listinfo/python-list > From darcy at druid.net Tue Aug 4 10:14:49 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 10:14:49 -0400 Subject: Problem in installing PyGreSQL In-Reply-To: References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> <20090804095547.a5274e22.darcy@druid.net> Message-ID: <20090804101449.79cd4522.darcy@druid.net> On Tue, 4 Aug 2009 10:02:23 -0400 Benjamin Kaplan wrote: > > By the way, you don't have to be super user to install PyGreSQL. ?You > > just need SU if you want to install it system wide. ?PyGreSQL doesn't > > require any special privileges to run. > > Right, but the packages install system-wide. That's why he could > compile it himself but not use the package. Exactly so don't install the package. Do "python setup.py build" and put the three files that are built (_pg.so, pg.py and pgdb.py) into any directory and point PYTHONPATH to it. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From python at mrabarnett.plus.com Tue Aug 4 10:17:39 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Aug 2009 15:17:39 +0100 Subject: Obtaining Python version In-Reply-To: <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> Message-ID: <4A784303.2070804@mrabarnett.plus.com> Xavier Ho wrote: > On Tue, Aug 4, 2009 at 9:34 PM, Xavier Ho > wrote: > > ... > and '00F0' is r31! > > > Actually, 00F0 is 576 in decimal. Maybe it's the subversion? > 0x00F0 is 240. > Anyhow, it's still good! > From contact at xavierho.com Tue Aug 4 10:39:56 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 5 Aug 2009 00:39:56 +1000 Subject: Obtaining Python version In-Reply-To: <4A784303.2070804@mrabarnett.plus.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> <4A784303.2070804@mrabarnett.plus.com> Message-ID: <2d56febf0908040739i79d4bcc9o461d6641c68f5fb9@mail.gmail.com> On Wed, Aug 5, 2009 at 12:17 AM, MRAB wrote: > 0x00F0 is 240. ... Right. I wonder where my brain is. *searches pocket* So, what am I doing wrong here? >>> int(str(0x00F0), 16) 576 Cheers, -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From darcy at druid.net Tue Aug 4 10:44:43 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Tue, 4 Aug 2009 10:44:43 -0400 Subject: Obtaining Python version In-Reply-To: <2d56febf0908040739i79d4bcc9o461d6641c68f5fb9@mail.gmail.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> <4A784303.2070804@mrabarnett.plus.com> <2d56febf0908040739i79d4bcc9o461d6641c68f5fb9@mail.gmail.com> Message-ID: <20090804104443.72ebffba.darcy@druid.net> On Wed, 5 Aug 2009 00:39:56 +1000 Xavier Ho wrote: > So, what am I doing wrong here? > > >>> int(str(0x00F0), 16) Look at the output of str(0x00F0) for a clue. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From jjposner at optimum.net Tue Aug 4 10:45:24 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 04 Aug 2009 10:45:24 -0400 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: <4A784984.6000903@optimum.net> > Certainly John- although I have not embedded the turtle module at all, > I just wrote my own. OK, then why the statements "from turtle import *" in the modules turtleprocess.py and turtlewidget.py? Tx, John From contact at xavierho.com Tue Aug 4 10:48:39 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 5 Aug 2009 00:48:39 +1000 Subject: Obtaining Python version In-Reply-To: <2d56febf0908040747s1a02f975ke383323e68732e6e@mail.gmail.com> References: <4a776184$0$1611$742ec2ed@news.sonic.net> <9c92f02f-eefb-4983-80ce-e5c060adbba6@j21g2000yqe.googlegroups.com> <2d56febf0908040434t118a389by1c1132dd82a2700@mail.gmail.com> <2d56febf0908040437n52b906e1w471727b39775d3ea@mail.gmail.com> <4A784303.2070804@mrabarnett.plus.com> <2d56febf0908040739i79d4bcc9o461d6641c68f5fb9@mail.gmail.com> <20090804104443.72ebffba.darcy@druid.net> <2d56febf0908040747s1a02f975ke383323e68732e6e@mail.gmail.com> Message-ID: <2d56febf0908040748y41c977c3k96d4437ed35edad@mail.gmail.com> On Wed, Aug 5, 2009 at 12:44 AM, D'Arcy J.M. Cain wrote: > On Wed, 5 Aug 2009 00:39:56 +1000 >> Xavier Ho wrote: >> > So, what am I doing wrong here? >> > >> > >>> int(str(0x00F0), 16) >> >> Look at the output of str(0x00F0) for a clue. >> > > ... Wow. I *am* slow tonight. Thanks. > > >>> int('00F0', 16) > 240 > (oops.) I was mixing the hex literals and the string literals. Thanks a bunch. -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From Samnsparky at gmail.com Tue Aug 4 11:25:28 2009 From: Samnsparky at gmail.com (Sparky) Date: Tue, 4 Aug 2009 08:25:28 -0700 (PDT) Subject: WindowsError: exception: access violation writing 0x00000000 References: <73c6c4f5-a00b-4f95-a85d-0f257b2f001a@c2g2000yqi.googlegroups.com> Message-ID: On Aug 3, 3:29?pm, Sparky wrote: > Hello! I am using cTypes on Windows to interface with a dll and I keep > getting an error when I execute this method: > > def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0): > ? ? ? ? """ > ? ? ? ? Name: U12.eAnalogIn(channel, idNum = None, demo = 0, readD=0) > ? ? ? ? Args: See section 4.4 of the User's Guide > ? ? ? ? Desc: This is a simplified version of Counter. Reads & resets > the counter (CNT). > ? ? ? ? """ > > ? ? ? ? if idNum is None: > ? ? ? ? ? ? idNum = self.id > > ? ? ? ? ljid = ctypes.c_long(idNum) > ? ? ? ? state = ctypes.c_long(999) > > ? ? ? ? ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, > readD, ctypes.byref(state)) > > ? ? ? ? if ecode != 0: raise LabJackException(ecode) > ? ? ? ? if ljid == -1: raise LabJackException(-1, "LabJack not > found.") > > ? ? ? ? return {"idnum":ljid.value, "state":state.value} > > Here is the error message: > Traceback (most recent call last): > ? File "", line 1, in > ? ? device.eDigitalIn(0) > ? File "C:\Documents and Settings\All Users\Documents\Python > \LabJackPython_new\u12.py", line 118, in eDigitalIn > ? ? ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, readD, > ctypes.byref(state)) > WindowsError: exception: access violation writing 0x00000000 > > Here is the signature of the method (which is known to work with C++ > programs): > > long _stdcall EDigitalIn(long *idnum, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long demo, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long channel, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long readD, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long *state); > > staticLib is declared with staticLib = ctypes.windll.LoadLibrary > ("ljackuw"). > > Any ideas? > > Thanks, > Sam One more thing, I seem to be getting back incorrect values for doubles passed by reference. Any suggestions? I am on a 64-bit machine but I should think that should not make a difference. Thanks again, Sam From philip at semanchuk.com Tue Aug 4 11:47:31 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 Aug 2009 11:47:31 -0400 Subject: WindowsError: exception: access violation writing 0x00000000 In-Reply-To: References: <73c6c4f5-a00b-4f95-a85d-0f257b2f001a@c2g2000yqi.googlegroups.com> Message-ID: <2231CCC9-1EDA-4923-8110-20015F3BDA6E@semanchuk.com> On Aug 4, 2009, at 11:25 AM, Sparky wrote: > On Aug 3, 3:29 pm, Sparky wrote: >> Hello! I am using cTypes on Windows to interface with a dll and I >> keep >> getting an error when I execute this method: >> >> def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0): >> """ >> Name: U12.eAnalogIn(channel, idNum = None, demo = 0, readD=0) >> Args: See section 4.4 of the User's Guide >> Desc: This is a simplified version of Counter. Reads & resets >> the counter (CNT). >> """ >> >> if idNum is None: >> idNum = self.id >> >> ljid = ctypes.c_long(idNum) >> state = ctypes.c_long(999) >> >> ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, >> readD, ctypes.byref(state)) >> >> if ecode != 0: raise LabJackException(ecode) >> if ljid == -1: raise LabJackException(-1, "LabJack not >> found.") >> >> return {"idnum":ljid.value, "state":state.value} >> >> Here is the error message: >> Traceback (most recent call last): >> File "", line 1, in >> device.eDigitalIn(0) >> File "C:\Documents and Settings\All Users\Documents\Python >> \LabJackPython_new\u12.py", line 118, in eDigitalIn >> ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, >> readD, >> ctypes.byref(state)) >> WindowsError: exception: access violation writing 0x00000000 >> >> Here is the signature of the method (which is known to work with C++ >> programs): >> >> long _stdcall EDigitalIn(long *idnum, >> long demo, >> long channel, >> long readD, >> long *state); >> >> staticLib is declared with staticLib = ctypes.windll.LoadLibrary >> ("ljackuw"). >> >> Any ideas? >> >> Thanks, >> Sam > > One more thing, I seem to be getting back incorrect values for doubles > passed by reference. Any suggestions? I am on a 64-bit machine but I > should think that should not make a difference. Hi Sam, ctypes is pretty straightforward, and I wouldn't expect it to break on something simple. I looked over your code (warning -- I am a ctypes novice) and it looks OK to me. If you're getting null pointer writes I'd suspect that the call signature isn't what you think it is, perhaps due to a lack of an extern "C" declaration or something like that. In short, I don't think this is a problem in your Python code or in ctypes. But since your Python code is the easiest to change, why not do a quick test of a minimal example? def eDigitalIn_test_version(self, channel, idNum = None, demo = 0, readD=0): ljid = ctypes.c_long(42) state = ctypes.c_long(999) ecode = staticLib.ECount(ctypes.byref(ljid), 0, 0, 0, ctypes.byref(state)) print ecode Does that work any better? You could also try replacing the byref() calls with pointers created by ctypes.pointer(). But I suspect that all this will do is give you confidence that it isn't your Python code that's wrong. You might want to write a minimal C program that invokes ECount. That would help you to prove whether or not you have a working C (not C++!) interface for your function. HTH Philip From cool-rr at cool-rr.com Tue Aug 4 12:04:17 2009 From: cool-rr at cool-rr.com (cool-RR) Date: Tue, 4 Aug 2009 19:04:17 +0300 Subject: Announcing PythonTurtle In-Reply-To: <4A784984.6000903@optimum.net> References: <4A784984.6000903@optimum.net> Message-ID: On Tue, Aug 4, 2009 at 5:45 PM, John Posner wrote: > > Certainly John- although I have not embedded the turtle module at all, >> I just wrote my own. >> > > OK, then why the statements "from turtle import *" in the modules > turtleprocess.py and turtlewidget.py? > > Tx, > John > > It's from a module turtle.py in my own PythonTurtle package. -- Sincerely, Ram Rachum -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at please.post Tue Aug 4 12:07:34 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 16:07:34 +0000 (UTC) Subject: kw param question References: Message-ID: In Steven D'Aprano writes: >On Mon, 03 Aug 2009 19:59:23 +0000, kj wrote: >> I want to write a decorator that, among other things, returns a function >> that has one additional keyword parameter, say foo=None. >> >> When I try >> >> def my_decorator(f): >> # blah, blah >> def wrapper(*p, foo=None, **kw): >> x = f(*p, **kw) >> if (foo): >> # blah, blah >> else >> # blah blah >> return wrapper >> >> ...i get a syntax error where it says "foo=None". I get similar errors >> with everything else I've tried. >> >> Is is possible to do this in Python? >Have you tried this under Python 2.6 or 3.0? >I've run into similar issues, because you can't have keyword-only >arguments in Python 2.5 :( >My solution was to create a decorator that faked them. The docstring is >longer than the decorator itself. >from functools import wraps >def keywords(**defaults): > """Return a decorator which decorates a function to accept keyword > arguments. > Python 2.5 and earlier don't allow keyword-only arguments for > non-builtin functions. The obvious syntax: > def func(x, *args, key=None, word='parrot'): > is not permitted. As a work-around, write your function something > like the following example: > >>> @keywords(key=None, word='parrot') > ... def func(x, y=0, *args, **kwargs): > ... # Inside the function, we can guarantee that kwargs['key'] and > ... # kwargs['word'] both exist, and no other keys. > ... print "x=%s, y=%s, args=%s" % (x, y, args) > ... if kwargs['key'] is None: msg = "kwargs['key'] is None" > ... else: msg = "kwargs['key'] is something else" > ... msg += " and kwargs['word'] is %r" % kwargs['word'] > ... print msg > ... > When you call func, if you don't provide a keyword-only argument, the > default will be substituted: > >>> func(1, 2, 3, 4) > x=1, y=2, args=(3, 4) > kwargs['key'] is None and kwargs['word'] is 'parrot' > >>> func(1) > x=1, y=0, args=() > kwargs['key'] is None and kwargs['word'] is 'parrot' > Naturally you can provide your own values for keyword-only arguments: > >>> func(1, 2, 3, word='spam') > x=1, y=2, args=(3,) > kwargs['key'] is None and kwargs['word'] is 'spam' > >>> func(1, 2, 3, word='spam', key=len) > x=1, y=2, args=(3,) > kwargs['key'] is something else and kwargs['word'] is 'spam' > If you pass an unexpected keyword argument, TypeError is raised: > >>> #doctest:+IGNORE_EXCEPTION_DETAIL > ... func(1, 2, 3, 4, keyword='something') > Traceback (most recent call last): > ... > TypeError: ... > """ > def decorator(func): > """Decorate func to allow keyword-only arguments.""" > @wraps(func) > def f(*args, **kwargs): > for key in kwargs: > if key not in defaults: > raise TypeError( > "'%s' is an invalid keyword argument for " \ > "this function" % key > ) > d = defaults.copy() > d.update(kwargs) > return func(*args, **d) > return f > return decorator Thanks for this. It's very useful. A lot of stuff for me to chew on. kynn From MatzeGuentert at gmx.de Tue Aug 4 12:27:40 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Tue, 04 Aug 2009 18:27:40 +0200 Subject: M2Crypto: X509.X509_Extension_Stack() throws AssertionError In-Reply-To: References: Message-ID: <1249403260.3396.6.camel@celsius> > > cert_extension_2 = X509.new_extension("keyUsage", "101000000") > > Maybe your OpenSSL is too old. keyUsage needs to be defined in OpenSSL > obj_dat.h file for this to work. I am using OpenSSL version 0.9.8k-fips which is the latest version. I replaced: cert_extension_2 = X509.new_extension("keyUsage", "101000000") with: cert_extension_2 = X509.new_extension("keyUsage", "keyCertSign, cRLSign") which worked for me. Also I found an easy way to iterate through the extension stack using: cert = X509.X509() for e in cert_extension_stack: cert.add_ext(e) > > cert_extension_3 = X509.new_extension("subjectAlternativeName", > > "DNS:www.mydomain.tld") > And I believe you mispelled this, try subjectAltName. Changing "subjectAlternativeName" to "subjectAltName" did the trick. Thank you! From MatzeGuentert at gmx.de Tue Aug 4 12:51:39 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Tue, 04 Aug 2009 18:51:39 +0200 Subject: M2Crypto: How to generate subjectKeyIdentifier / authorityKeyIdentifier Message-ID: <1249404699.3396.30.camel@celsius> Hello I am trying to add the extensions "subjectKeyIdentifier" and "authorityKeyIdentifier" to a x509v3 certificate. Regarding rfc5280, section 4.2.1.2 the key identifier is composed of the 160-bit SHA-1 hash of the BIT STRING subjectPublicKey http://tools.ietf.org/html/rfc5280#section-4.2.1.2 I don't know how or which function to use from EVP.PKey() to compose a fingerprint from the public key, as you can see below I was playing around with some functions, which simply returned nonsense (at least for me) I would be happy if someone could provide some example code on how to generate a fingerprint from the public key. "print keyp.final()" nor "print keyp.sign_final() on the last line does return anything... -------------------------------------------------------- from M2Crypto import X509, m2, RSA, EVP from config import * import os.path class Keypair(object): def __init__(self): self.config = Config() self.keypair = EVP.PKey() def create_keypair(self, key_size=1024): # generate an RSA key pair # OpenSSL book page 232 # second argument should be a constant RSA_F4 or RSA_3 rsa_key_pair = RSA.gen_key(key_size, m2.RSA_F4) # check if RSA key pair is usable # OpenSSL book page 232 if rsa_key_pair.check_key() != 1: print 'error while generating key!' sys.exit() # EVP object which can hold either a DSA or an RSA object # OpenSSL book page 236 evp_key_container = EVP.PKey() evp_key_container.assign_rsa(rsa_key_pair) self.keypair = evp_key_container def save_keypair(self, filename): if not os.path.exists(filename): self.keypair.save_key(filename, None) else: print "error in save_keypair(): cannot save key, it already exists" def load_keypair(self, filename): try: self.keypair = EVP.load_key(filename) except TypeError: print "error in load_keypair(): maybe file does not exist?" def get_keypair(self): return self.keypair def get_public_key(self): return self.keypair.pkey def print_keypair(self): print self.keypair.as_pem(None) if __name__ == "__main__": keypair = Keypair() keypair.create_keypair() # keypair.save_keypair("test.keys") keyp = keypair.get_keypair() print keyp.final() print keyp.sign_final() --------------------------------------------------------- And this maybe some OT question but how can I use OpenSSL to generate some fingerprint for testing and comparison purpose? For example I have got a certificate client.crt and the keys client.key $ openssl x509 -noout -text -in client.crt [...] X509v3 Subject Key Identifier: D2:C0:39:37:45:F6:A3:BF:D8:91:A2:F5:C7:43:42:80:6A:3C:38:AF X509v3 Authority Key Identifier: A7:E2:2E:59:F8:53:1F:68:F2:59:34:32:42:F6:21:20:C0:D1:3A:89 [...] But openssl provides me different fingerprint... so whats wrong here? $ openssl rsa -pubout -in client_1.key | openssl sha1 -c writing RSA key cc:d2:ab:16:1f:a1:23:3e:fe:45:03:ab:4f:86:57:65:52:16:b2:1a From bartsmeets86 at gmail.com Tue Aug 4 12:52:05 2009 From: bartsmeets86 at gmail.com (Bart Smeets) Date: Tue, 4 Aug 2009 18:52:05 +0200 Subject: easy_install: unresolved external symbol In-Reply-To: <87f2eede5ce0f1391994db66153e3c96@preisshare.net> References: <2119ee90908031339o71e19624qa815241b446d739d@mail.gmail.com> <2119ee90908040152k5a744f98l7d5bc7da755948a2@mail.gmail.com> <87f2eede5ce0f1391994db66153e3c96@preisshare.net> Message-ID: <2119ee90908040952p6233d28ek99584bcd4f5f6f42@mail.gmail.com> How do I give the option to link to the ez_setup.py? 2009/8/4 David Lyon > On Tue, 4 Aug 2009 10:52:20 +0200, Bart Smeets > wrote: > > I could ofcourse use cxfreeze's binary package. But bbfreeze is not > > available as a binary. I would love to get easy_install to work. But I > have > > no idea what's going wrong here. > > What is going on is that setuptools does some very 'advanced' things. > > The best you can do is give the option to link to the ez_setup.py > install script and let the users install it them themselves... > > David > -------------- next part -------------- An HTML attachment was scrubbed... URL: From r.a.teterin at gmail.com Tue Aug 4 13:08:45 2009 From: r.a.teterin at gmail.com (Roman) Date: Tue, 4 Aug 2009 21:08:45 +0400 Subject: Trying to get ABC to work In-Reply-To: <358094.5069.qm@web65302.mail.ac2.yahoo.com> References: <358094.5069.qm@web65302.mail.ac2.yahoo.com> Message-ID: <20090804170845.GA3092@localhost> Following code works, although I'm not sure that it's exactly what you want: import abc class MetaExample(abc.ABCMeta): def __new__(mcs, name, bases, ns): ns['cls_meth'] = mcs.cls_meth if not 'cls_abc' in ns: ns['cls_abc'] = mcs.cls_abc return super().__new__(mcs, name, bases, ns) def cls_meth(cls): print('Class method defined stub') @abc.abstractmethod def cls_abc(cls): try: print('Class-Abstract method defined stub') except NotImplementedError as err: print('Must implement cls_abc') except: print('General exception at cls_abc method') That's how I've tested it: class Test1(object, metaclass=MetaExample): def cls_abc(self): print("method of", self) class Test2(object, metaclass=MetaExample): pass test1 = Test1() test1.cls_meth() test1.cls_abc() test2 = Test2() Output: Class method defined stub method of <__main__.Test1 object at 0xb7b5f52c> Traceback (most recent call last): File "/tmp/test.py", line 32, in test2 = Test2() TypeError: Can't instantiate abstract class Test2 with abstract methods cls_abc According to the documentation, @abstractmethod "requires that the metaclass is ABCMeta or derived from it", so I've changed base class from type to ABCMeta. Also I don't think that using try/except inside the abstract method will work, maybe it would be better to check presence of all required methods directly inside the metaclass, without @abstractmethod decorator. From holger at merlinux.eu Tue Aug 4 13:19:16 2009 From: holger at merlinux.eu (holger krekel) Date: Tue, 4 Aug 2009 19:19:16 +0200 Subject: pylib/py.test 1.0.0 released Message-ID: <20090804171915.GS31589@trillke.net> Hello everyone, i am happy to announce pylib/py.test 1.0.0, a MIT-licensed library geared towards advanced testing and elastic distributed programming with Python. It features the mature cross-project py.test automated testing tool with many new features, aiming to: * allow writing zero-boilerplate automated tests in Python * offer strong debugging and reporting of test failures * rapidly run and ad-hoc distribute tests to multiple CPUs/platforms * support unit-, functional and integration testing * be easy to extend and tackle growing testing needs, (current prime example oejskit, a live-browser javascript unittesting 3rd party plugin) Please check things out at: http://pytest.org or read the blogged release announcement: http://tetamap.wordpress.com/2009/08/04/pylib-1-0-0 or read on for some ... Distinctive new features shipping with py.test 1.0.0 ------------------------------------------------------ For those already knowing about the older 0.9.2 release or being experienced with other testing approaches i'll try to give a summary of the distinctive testing features shipping with 1.0.0: * test function arguments ("funcargs"): With this, python test functions can name arguments and one writes factory functions to provide instances for such "fixture" arguments. This page http://codespeak.net/py/dist/test/funcargs.html contains reference info and tutorial examples. Test function arguments also allow for natural test parametrization - one provides several different argument values, no changes to the test function needed, no magic "yield" for generating tests anymore - although 1.0 still allows them and of course still supports traditional xUnit-style setup_module/class/function or (new) direct runs of unittest.TestCase style tests. * distributed testing: distributing test runs among Linux/OSX/Windows hosts and across python-2.4 till python-2.6 interpreters works reasonably stable now. This means that you can easily iron out test-module/function specific problems across a variety of platforms, accelerating the change & test feedback cycle. * xfail: a new way to mark tests as "expected to fail" which means they run normally but are reported/counted specially. This "xfail" mark is meant to mark missing / wrong implementation rather than missing dependencies / wrong platforms for which one uses "skip". Especially for larger test suites making this distinction is very helpful. * IO-capturing: output of test functions is captured per-test, by default including any output from sub processes. This works on all platforms and also (now) interacts well with the logging module without importing/using it itself so there are no interferences. * pastebin: new command line option "--pastebin" to send your test session output or individual test failures to the Pocoo pastebin service and prints out URLs. Convenient for quick IRC/messaging communication. * plugins: it is now easy to write plugins by implementing one or more of the 37 hooks which py.test calls to implement the testing process. There are many examples, among them the "oejskit" plugin which integrates testing of javascript code in real-life browsers into a regular test run. Apart from such separately distributed "cross-project" plugins you can also write per-project plugins/extensions that lives with your testing code. cheers & have fun, holger -- Metaprogramming, Python, Testing: http://tetamap.wordpress.com Python, PyPy, pytest contracting: http://merlinux.eu From Samnsparky at gmail.com Tue Aug 4 13:23:10 2009 From: Samnsparky at gmail.com (Sparky) Date: Tue, 4 Aug 2009 10:23:10 -0700 (PDT) Subject: WindowsError: exception: access violation writing 0x00000000 References: <73c6c4f5-a00b-4f95-a85d-0f257b2f001a@c2g2000yqi.googlegroups.com> Message-ID: <26927cc2-2134-46b6-873a-02be9cf829f2@h21g2000yqa.googlegroups.com> On Aug 4, 9:47?am, Philip Semanchuk wrote: > On Aug 4, 2009, at 11:25 AM, Sparky wrote: > > > > > > > On Aug 3, 3:29 pm, Sparky wrote: > >> Hello! I am using cTypes on Windows to interface with a dll and I ? > >> keep > >> getting an error when I execute this method: > > >> def eDigitalIn(self, channel, idNum = None, demo = 0, readD=0): > >> ? ? ? ? """ > >> ? ? ? ? Name: U12.eAnalogIn(channel, idNum = None, demo = 0, readD=0) > >> ? ? ? ? Args: See section 4.4 of the User's Guide > >> ? ? ? ? Desc: This is a simplified version of Counter. Reads & resets > >> the counter (CNT). > >> ? ? ? ? """ > > >> ? ? ? ? if idNum is None: > >> ? ? ? ? ? ? idNum = self.id > > >> ? ? ? ? ljid = ctypes.c_long(idNum) > >> ? ? ? ? state = ctypes.c_long(999) > > >> ? ? ? ? ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, > >> readD, ctypes.byref(state)) > > >> ? ? ? ? if ecode != 0: raise LabJackException(ecode) > >> ? ? ? ? if ljid == -1: raise LabJackException(-1, "LabJack not > >> found.") > > >> ? ? ? ? return {"idnum":ljid.value, "state":state.value} > > >> Here is the error message: > >> Traceback (most recent call last): > >> ? File "", line 1, in > >> ? ? device.eDigitalIn(0) > >> ? File "C:\Documents and Settings\All Users\Documents\Python > >> \LabJackPython_new\u12.py", line 118, in eDigitalIn > >> ? ? ecode = staticLib.ECount(ctypes.byref(ljid), demo, channel, ? > >> readD, > >> ctypes.byref(state)) > >> WindowsError: exception: access violation writing 0x00000000 > > >> Here is the signature of the method (which is known to work with C++ > >> programs): > > >> long _stdcall EDigitalIn(long *idnum, > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long demo, > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long channel, > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long readD, > >> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?long *state); > > >> staticLib is declared with staticLib = ctypes.windll.LoadLibrary > >> ("ljackuw"). > > >> Any ideas? > > >> Thanks, > >> Sam > > > One more thing, I seem to be getting back incorrect values for doubles > > passed by reference. Any suggestions? I am on a 64-bit machine but I > > should think that should not make a difference. > > Hi Sam, > ctypes is pretty straightforward, and I wouldn't expect it to break on ? > something simple. I looked over your code (warning -- I am a ctypes ? > novice) and it looks OK to me. If you're getting null pointer writes ? > I'd suspect that the call signature isn't what you think it is, ? > perhaps due to a lack of an extern "C" declaration or something like ? > that. In short, I don't think this is a problem in your Python code or ? > in ctypes. > > But since your Python code is the easiest to change, why not do a ? > quick test of a minimal example? > > def eDigitalIn_test_version(self, channel, idNum = None, demo = 0, ? > readD=0): > ? ? ? ? ?ljid = ctypes.c_long(42) > ? ? ? ? ?state = ctypes.c_long(999) > > ? ? ? ? ?ecode = staticLib.ECount(ctypes.byref(ljid), 0, 0, 0, ? > ctypes.byref(state)) > > ? ? ? ? ?print ecode > > Does that work any better? > > You could also try replacing the byref() calls with pointers created ? > by ctypes.pointer(). But I suspect that all this will do is give you ? > confidence that it isn't your Python code that's wrong. > > You might want to write a minimal C program that invokes ECount. That ? > would help you to prove whether or not you have a working C (not C++!) ? > interface for your function. > > HTH > Philip Hey Philip, Thank you for your response. It turns out I was calling a function that I was not intending on calling, so it was not a Python problem. Thanks, Sam From jay.bird0804 at gmail.com Tue Aug 4 14:15:47 2009 From: jay.bird0804 at gmail.com (Jay Bird) Date: Tue, 4 Aug 2009 11:15:47 -0700 (PDT) Subject: Overlap in python Message-ID: Hi everyone, I've been trying to figure out a simple algorithm on how to combine a list of parts that have 1D locations that overlap into a non- overlapping list. For example, here would be my input: part name location a 5-9 b 7-10 c 3-6 d 15-20 e 18-23 And here is what I need for an output: part name location c.a.b 3-10 d.e 15-23 I've tried various methods, which all fail. Does anyone have an idea how to do this? Thank you very much! Jay From marcusw at cox.net Tue Aug 4 14:31:49 2009 From: marcusw at cox.net (Marcus Wanner) Date: Tue, 4 Aug 2009 11:31:49 -0700 (PDT) Subject: Overlap in python References: Message-ID: <3f11f316-5e9e-4786-8757-edf9ab234bb7@j32g2000yqh.googlegroups.com> On Aug 4, 2:15?pm, Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. ?For example, here would be my input: > > part name ? location > a ? ? ? ? ? ? ? ? ?5-9 > b ? ? ? ? ? ? ? ? ?7-10 > c ? ? ? ? ? ? ? ? ?3-6 > d ? ? ? ? ? ? ? ? ?15-20 > e ? ? ? ? ? ? ? ? ?18-23 > > And here is what I need for an output: > part name ? location > c.a.b ? ? ? ? ? ?3-10 > d.e ? ? ? ? ? ? ? 15-23 > > I've tried various methods, which all fail. ?Does anyone have an idea > how to do this? > > Thank you very much! > Jay Just take all the values, put them in a list, and use min() and max(). For example: import string def makelist(values): values = string.replace(values, ' ', '') listofvaluepairs = string.split(values, ',') listofvalues = [] for pair in listofvaluepairs: twovalues = string.split(pair, '-') listofvalues.append(int(twovalues[0])) listofvalues.append(int(twovalues[1])) return listofvalues values = '5-9, 7-10, 3-6' values = makelist(values) print('Values: %d-%d' %(min(values), max(values)) ) Marcus From anna.konstorum at gmail.com Tue Aug 4 14:46:14 2009 From: anna.konstorum at gmail.com (Ann) Date: Tue, 4 Aug 2009 11:46:14 -0700 (PDT) Subject: Overlap in python References: <3f11f316-5e9e-4786-8757-edf9ab234bb7@j32g2000yqh.googlegroups.com> Message-ID: On Aug 4, 11:31?am, Marcus Wanner wrote: > On Aug 4, 2:15?pm, Jay Bird wrote: > > > > > Hi everyone, > > > I've been trying to figure out a simple algorithm on how to combine a > > list of parts that have 1D locations that overlap into a non- > > overlapping list. ?For example, here would be my input: > > > part name ? location > > a ? ? ? ? ? ? ? ? ?5-9 > > b ? ? ? ? ? ? ? ? ?7-10 > > c ? ? ? ? ? ? ? ? ?3-6 > > d ? ? ? ? ? ? ? ? ?15-20 > > e ? ? ? ? ? ? ? ? ?18-23 > > > And here is what I need for an output: > > part name ? location > > c.a.b ? ? ? ? ? ?3-10 > > d.e ? ? ? ? ? ? ? 15-23 > > > I've tried various methods, which all fail. ?Does anyone have an idea > > how to do this? > > > Thank you very much! > > Jay > > Just take all the values, put them in a list, and use min() and max(). > For example: > > import string > > def makelist(values): > ? ? values = string.replace(values, ' ', '') > ? ? listofvaluepairs = string.split(values, ',') > ? ? listofvalues = [] > ? ? for pair in listofvaluepairs: > ? ? ? ? twovalues = string.split(pair, '-') > ? ? ? ? listofvalues.append(int(twovalues[0])) > ? ? ? ? listofvalues.append(int(twovalues[1])) > ? ? return listofvalues > > values = '5-9, 7-10, 3-6' > values = makelist(values) > print('Values: %d-%d' %(min(values), max(values)) ) > > Marcus Thank you for your help, this is a very nice program but it does not address the issue that I have values that do not overlap, for example 'c' and 'd' do not overlap in the above example and thus I would not want to output 3-20 but the individual positions instead. In addition, my inputs are not ordered from smallest to largest, thus I could have a situation where a=5-9, b=15-20, c=7-10, etc., and I would still want an output of: a.c = 5-10, b=15-20. I apologize for the complication. Thank you again! Jay From aurele.tux at gmail.com Tue Aug 4 14:53:56 2009 From: aurele.tux at gmail.com (aurelien) Date: Tue, 04 Aug 2009 20:53:56 +0200 Subject: Is it possible to have the python color in the terminal ? Message-ID: <1249412036.5765.20.camel@r2d2> Hello, I am under gNewSense, i am a newbbie on Python, i look for how change the color terminal when python run. at the step >>> all is in black and white. Is it possible to have the python color in the terminal ? Thanks for your help. aurelien From marcusw at cox.net Tue Aug 4 14:55:22 2009 From: marcusw at cox.net (Marcus Wanner) Date: Tue, 04 Aug 2009 14:55:22 -0400 Subject: Overlap in python In-Reply-To: References: <3f11f316-5e9e-4786-8757-edf9ab234bb7@j32g2000yqh.googlegroups.com> Message-ID: On 8/4/2009 2:46 PM, Ann wrote: > On Aug 4, 11:31 am, Marcus Wanner wrote: >> On Aug 4, 2:15 pm, Jay Bird wrote: >> >> >> >>> Hi everyone, >>> I've been trying to figure out a simple algorithm on how to combine a >>> list of parts that have 1D locations that overlap into a non- >>> overlapping list. For example, here would be my input: >>> part name location >>> a 5-9 >>> b 7-10 >>> c 3-6 >>> d 15-20 >>> e 18-23 >>> And here is what I need for an output: >>> part name location >>> c.a.b 3-10 >>> d.e 15-23 >>> I've tried various methods, which all fail. Does anyone have an idea >>> how to do this? >>> Thank you very much! >>> Jay >> Just take all the values, put them in a list, and use min() and max(). >> For example: >> >> import string >> >> def makelist(values): >> values = string.replace(values, ' ', '') >> listofvaluepairs = string.split(values, ',') >> listofvalues = [] >> for pair in listofvaluepairs: >> twovalues = string.split(pair, '-') >> listofvalues.append(int(twovalues[0])) >> listofvalues.append(int(twovalues[1])) >> return listofvalues >> >> values = '5-9, 7-10, 3-6' >> values = makelist(values) >> print('Values: %d-%d' %(min(values), max(values)) ) >> >> Marcus > > Thank you for your help, this is a very nice program but it does not > address the issue that I have values that do not overlap, for example > 'c' and 'd' do not overlap in the above example and thus I would not > want to output 3-20 but the individual positions instead. In > addition, my inputs are not ordered from smallest to largest, thus I > could have a situation where a=5-9, b=15-20, c=7-10, etc., and I would > still want an output of: a.c = 5-10, b=15-20. I apologize for the > complication. > > Thank you again! > > Jay That would be a bit more complicated...you might try using tuples of values in a list, or writing your own class for the data handling. Unfortunately that's not something I can just sit down and code in 5 minutes, it would take some careful thought and planning. Marcus From marcusw at cox.net Tue Aug 4 15:00:32 2009 From: marcusw at cox.net (Marcus Wanner) Date: Tue, 04 Aug 2009 15:00:32 -0400 Subject: Is it possible to have the python color in the terminal ? In-Reply-To: <1249412036.5765.20.camel@r2d2> References: <1249412036.5765.20.camel@r2d2> Message-ID: On 8/4/2009 2:53 PM, aurelien wrote: > Hello, > > I am under gNewSense, i am a newbbie on Python, i look for how change > the color terminal when python run. > at the step >>> all is in black and white. > Is it possible to have the python color in the terminal ? > > Thanks for your help. > > aurelien > You might try posting to this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/58df7b77394e4666/f4c13766a1e09380 I don't know much about the question myself, though. Marcus From breamoreboy at yahoo.co.uk Tue Aug 4 15:10:52 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 04 Aug 2009 20:10:52 +0100 Subject: Overlap in python In-Reply-To: References: Message-ID: Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 > > I've tried various methods, which all fail. Does anyone have an idea > how to do this? > > Thank you very much! > Jay I haven't tried but could you adapt this:- data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] for k, g in groupby(enumerate(data), lambda (i,x):i-x): print map(itemgetter(1), g) found here http://www.python.org/doc/2.6.2/library/itertools.html#module-itertools -- Kindest regards. Mark Lawrence. From kosta.koeman at gmail.com Tue Aug 4 15:13:10 2009 From: kosta.koeman at gmail.com (Kosta) Date: Tue, 4 Aug 2009 12:13:10 -0700 (PDT) Subject: Using Python to automate builds Message-ID: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> I am a Python newbie, tasked with automating (researching) building Windows drivers using the WDK build environment. I've been looking into Python for this (instead of writing a bunch of batch files). What I would like to do, is to open a cmd window, and start a Python script. This script would then (based upon input arguments), build different flavors of the driver (fre, chk, x86, x64) and do some post processing (create cat files, sign, etc.). I was hoping to take advantage as much as possible of exisiting infrastructure from the WDK. I am able to call setenv.bat and provide all the input parameters. One of the things setenv.bat does is change the path environment variable. However, this is not captured by Python. I could duplicate the functionality, but I'd rather not. Is there a way to capture all enviroment variable changes being made by a batch file from Python? Thanks! From aurele.tux at gmail.com Tue Aug 4 15:20:03 2009 From: aurele.tux at gmail.com (aurelien) Date: Tue, 4 Aug 2009 12:20:03 -0700 (PDT) Subject: Is it possible to have the python color in the terminal ? Message-ID: Hello, I am under gNewSense, i am a newbbie on Python, i look for how change the color terminal when python run. at the step >>> all is in black and white. Is it possible to have the python color in the terminal ? Thanks for your help aurelien From aurele.tux at gmail.com Tue Aug 4 15:23:24 2009 From: aurele.tux at gmail.com (aurelien) Date: Tue, 04 Aug 2009 21:23:24 +0200 Subject: Is it possible to have the python color in the terminal ? In-Reply-To: References: <1249412036.5765.20.camel@r2d2> Message-ID: <1249413804.5765.24.camel@r2d2> > You might try posting to this thread: > http://groups.google.com/group/comp.lang.python/browse_thread/thread/58df7b77394e4666/f4c13766a1e09380 > I don't know much about the question myself, though. > > Marcus Thanks for your help ! aurelien From no.email at please.post Tue Aug 4 15:29:00 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 19:29:00 +0000 (UTC) Subject: no-clobber dicts? References: Message-ID: In Steven D'Aprano writes: >On Mon, 03 Aug 2009 21:07:32 +0000, kj wrote: >> I use the term "no-clobber dict" to refer to a dictionary D with the >> especial property that if K is in D, then >> >> D[K] = V >> >> will raise an exception unless V == D[K]. In other words, D[K] can be >> set if K doesn't exist already among D's keys, or if the assigned value >> is equal to the current value of D[K]. All other assignments to D[K] >> trigger an exception. >Coincidentally, I just built something very close to what you ask. Here >it is: >class ConstantNamespace(dict): > """Dictionary with write-once keys.""" > def __delitem__(self, key): > raise TypeError("can't unbind constants") > def __setitem__(self, key, value): > if key in self: > raise TypeError("can't rebind constants") > super(ConstantNamespace, self).__setitem__(key, value) > def clear(self): > raise TypeError('cannot unbind constants') > def pop(self, key, *args): > raise TypeError("cannot pop constants") > def popitem(self): > raise TypeError("cannot pop constants") > def update(self, other): > for key in other: > if key in self: > raise TypeError('cannot update constants') > # If we get here, then we're not modifying anything, > # so okay to proceed. > super(ConstantNamespace, self).update(other) > def copy(self): > c = self.__class__(**self) > return c Thanks. As you note this not quite what I'm looking for, but it's a good template for it. kynn From no.email at please.post Tue Aug 4 15:30:51 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 19:30:51 +0000 (UTC) Subject: no-clobber dicts? References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: In Chris Rebert writes: >On Mon, Aug 3, 2009 at 2:47 PM, r wrote: >> On Aug 3, 4:07=C2=A0pm, kj wrote: >>> I use the term "no-clobber dict" to refer to a dictionary D with >>> the especial property that if K is in D, then >>> >>> =C2=A0 D[K] =3D V >>> >>> will raise an exception unless V =3D=3D D[K]. =C2=A0In other words, D[K] >>> can be set if K doesn't exist already among D's keys, or if the >>> assigned value is equal to the current value of D[K]. =C2=A0All other >>> assignments to D[K] trigger an exception. >>> >>> The idea here is to detect inconsistencies in the data. >>> >>> This is a data structure I often need. =C2=A0Before I re-invent the >>> wheel, I thought I'd ask: is it already available? >>> >>> TIA! >>> >>> kynn >> >> Not sure if something like this already exists, but it would be >> trivial to implement by overriding dict.__setitem__() >That is, if you don't care about .update() not preserving the >invariant. The implication here is that .update() does not in turn use .__setitem__(), which I find a bit surprising. kynn From r.a.teterin at gmail.com Tue Aug 4 15:54:10 2009 From: r.a.teterin at gmail.com (Roman) Date: Tue, 4 Aug 2009 23:54:10 +0400 Subject: Is it possible to have the python color in the terminal ? In-Reply-To: References: Message-ID: <20090804195410.GA3247@localhost> On 04/08/09 12:20, aurelien wrote: > Hello, > > I am under gNewSense, i am a newbbie on Python, i look for how change > the color terminal when python run. > at the step >>> all is in black and white. > Is it possible to have the python color in the terminal ? > > Thanks for your help > > aurelien > -- > http://mail.python.org/mailman/listinfo/python-list > If you want to get colourful output, you can use IPython (http://ipython.scipy.org/moin/FrontPage), it is an enhanced Python shell. You may also change colour of text by printing appropriate escape sequences (e.g. executing print("\033[0;32m") in Python interpreter should change foreground colour to green. From gregor.lingl at aon.at Tue Aug 4 15:57:40 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 21:57:40 +0200 Subject: Overlap in python In-Reply-To: References: Message-ID: <4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> Jay Bird schrieb: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 > Suppose you have your data given as a dictionary: data = {'a':(5,9), 'b':(7,10), 'c':(3,6), 'd':(15,20), 'e':(18,23)} Then the following not particularly elegant but very simple and straight forward algorithm will solve your problem: def values(key): return set(range(data[key][0], data[key][1]+1)) keys = list(data.keys()) result = [] while keys: k = [keys[0]] keys = keys[1:] v = values(k[0]) for l in keys[:]: if v.intersection(values(l)): v.update(values(l)) k.append(l) keys.remove(l) result.append((k,v)) # print(result) ## if you like for k, v in result: print(".".join(sorted(k)), "%d-%d" % (min(v), max(v))) Regards, Gregor > I've tried various methods, which all fail. Does anyone have an idea > how to do this? > > Thank you very much! > Jay From info at egenix.com Tue Aug 4 15:58:40 2009 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Tue, 04 Aug 2009 21:58:40 +0200 Subject: ANN: eGenix pyOpenSSL Distribution 0.9.0-0.9.8k now also in .egg format Message-ID: <4A7892F0.3080805@egenix.com> ________________________________________________________________________ ANNOUNCING eGenix.com pyOpenSSL Distribution Version 0.9.0-0.9.8k An easy to install and use repackaged distribution of the pyOpenSSL Python interface for OpenSSL - available on Windows, Mac OS X and Unix platforms This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/eGenix-pyOpenSSL-Distribution-0.9.0-0.9.8k-1-Update.html ________________________________________________________________________ INTRODUCTION The eGenix.com pyOpenSSL Distribution includes everything you need to get started with SSL in Python. It comes with an easy to use installer that includes the most recent OpenSSL library versions in pre-compiled form. pyOpenSSL is an open-source Python add-on (http://pyopenssl.sf.net/) that allows writing SSL aware networking applications as well as certificate management tools. OpenSSL is an open-source implementation of the SSL protocol (http://www.openssl.org/). For more information, please see the product page: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ NEWS Due to popular demand, we've added .egg file versions for Windows and Linux to the available download options. This should make things easier for people using e.g. zc.buildout and other egg-file based installers. As always, binaries include both pyOpenSSL and the necessary OpenSSL libraries. ________________________________________________________________________ DOWNLOADS The download archives and instructions for installing the package can be found at: http://www.egenix.com/products/python/pyOpenSSL/ ________________________________________________________________________ UPGRADING Before installing this version of pyOpenSSL, please make sure that you uninstall any previously installed pyOpenSSL version. Otherwise, you could end up not using the included OpenSSL libs. _______________________________________________________________________ SUPPORT Commercial support for these packages is available from eGenix.com. Please see http://www.egenix.com/services/support/ for details about our support offerings. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Aug 04 2009) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ ::: Try our new mxODBC.Connect Python Database Interface for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 http://www.egenix.com/company/contact/ From no.email at please.post Tue Aug 4 16:01:12 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 20:01:12 +0000 (UTC) Subject: no-clobber dicts? References: Message-ID: In Steven D'Aprano writes: >class ConstantNamespace(dict): >I also have a series of unit tests for it if you're interested in them. Actually, come to think of it, I think I'll take you up on this. I'd love to see those tests. Unit testing in Python is in area I need to work on. TIA! kynn From dickinsm at gmail.com Tue Aug 4 16:03:00 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 4 Aug 2009 13:03:00 -0700 (PDT) Subject: Overlap in python References: Message-ID: <78d86d92-d373-4163-a418-600a3eb36ab3@o15g2000yqm.googlegroups.com> On Aug 4, 7:15?pm, Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. ?For example, here would be my input: > > part name ? location > a ? ? ? ? ? ? ? ? ?5-9 > b ? ? ? ? ? ? ? ? ?7-10 > c ? ? ? ? ? ? ? ? ?3-6 > d ? ? ? ? ? ? ? ? ?15-20 > e ? ? ? ? ? ? ? ? ?18-23 > > And here is what I need for an output: > part name ? location > c.a.b ? ? ? ? ? ?3-10 > d.e ? ? ? ? ? ? ? 15-23 > > I've tried various methods, which all fail. ?Does anyone have an idea > how to do this? Here's an approach that might work. Turning it into a sensible function and parsing input/massaging output properly are left as an exercise. Blocks that just touch (e.g. (3, 6) then (6, 9)) are amalgamated; if this isn't what you want, and they should be treated as separate instead, then replace 'Stop' with 'Finish' (or any other string that sorts before 'Start'). input = [ ('a', (5, 9)), ('b', (7, 10)), ('c', (3, 6)), ('d', (15, 20)), ('e', (18, 23)), ] # create sorted list of points where an interval is entered or left transitions = [] for name, (start, stop) in input: transitions.extend([(start, 'Start', name), (stop, 'Stop', name)]) transitions.sort() # scan list, accumulating blocks along the way. count = 0 for i, (pt, startend, name) in enumerate(transitions): if startend == 'Start': if not count: start = pt names = [] count += 1 names.append(name) else: count -= 1 if not count: print '.'.join(names), "%s--%s" % (start, pt) The output that I get from this under Python 2.6 is: c.a.b 3--10 d.e 15--23 -- Mark From clp2 at rebertia.com Tue Aug 4 16:03:08 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 Aug 2009 13:03:08 -0700 Subject: no-clobber dicts? In-Reply-To: References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: <50697b2c0908041303ycf7a2f2g47b2b2eebf723d32@mail.gmail.com> On Tue, Aug 4, 2009 at 12:30 PM, kj wrote: > In Chris Rebert writes: > >>On Mon, Aug 3, 2009 at 2:47 PM, r wrote: >>> On Aug 3, 4:07=C2=A0pm, kj wrote: >>>> I use the term "no-clobber dict" to refer to a dictionary D with >>>> the especial property that if K is in D, then >>>> >>>> =C2=A0 D[K] =3D V >>>> >>>> will raise an exception unless V =3D=3D D[K]. =C2=A0In other words, D[K] >>>> can be set if K doesn't exist already among D's keys, or if the >>>> assigned value is equal to the current value of D[K]. =C2=A0All other >>>> assignments to D[K] trigger an exception. >>>> >>>> The idea here is to detect inconsistencies in the data. >>>> >>>> This is a data structure I often need. =C2=A0Before I re-invent the >>>> wheel, I thought I'd ask: is it already available? >>>> >>>> TIA! >>>> >>>> kynn >>> >>> Not sure if something like this already exists, but it would be >>> trivial to implement by overriding dict.__setitem__() > >>That is, if you don't care about .update() not preserving the >>invariant. > > The implication here is that .update() does not in turn use > .__setitem__(), which I find a bit surprising. The builtin types are allowed to take such shortcuts for performance reasons. Cheers, Chris -- http://blog.rebertia.com From dciphercomputing at gmail.com Tue Aug 4 16:05:10 2009 From: dciphercomputing at gmail.com (Simon) Date: Tue, 4 Aug 2009 13:05:10 -0700 (PDT) Subject: Newbie Question regarding __init__() References: <6ccf5dbe-4b71-4159-88bb-c6a14aa785a9@k26g2000vbp.googlegroups.com> <01bcf8b8-687c-4bf4-acbb-b059a480d382@f33g2000vbm.googlegroups.com> Message-ID: <20295b74-b630-47bd-b48d-9881bc6453a7@g6g2000vbr.googlegroups.com> On Aug 3, 11:00?pm, Dave Angel wrote: > Simon wrote: > > On Aug 2, 5:51 am, Dave Angel wrote: > > >> > >> I don't understand your comparison to Foxpro. ?read on. > > >> As your code was last posted, you don't need a return value from > >> init_Exec() ?Every function that doesn't have an explicit return will > >> return None. ?And None is interpreted as False in an "and" expression. ? > >> If you had an "if" around the whole thing, then you'd care. > > >> DaveA > > > All I meant by the FoxPro comment was the idea of using the equal sign > > without a variable to throw away the result. ?Also in FoxPro there is > > no such thing as automatically returning None. ?If there is no > > explicit return then True is returned. > > > Thanks I did not know that None is interpreted as False. > > > Simon > > To throw away the result of an expression in Python is even easier. ? > Just don't use it. > ? ? ? ?func1() and func2() > is a valid expression whose result is not used. ?And func2()'s result is > therefore irrelevant. ?But shortcircuiting means that func2() is only > called if func1() returned False (or something equivalent to it, like 0 > or an empty list) Thanks for telling me how Python throws away the result. Secondly my code works perfectly now that I am properly defining my methods using "self". From 1x7y2z9 at gmail.com Tue Aug 4 16:11:18 2009 From: 1x7y2z9 at gmail.com (1x7y2z9) Date: Tue, 4 Aug 2009 13:11:18 -0700 (PDT) Subject: boolean OR gotcha Message-ID: >>> 0 or None is None True >>> None or 0 is None False >>> None or 0 is 0 True Yes, this is explained in the docs: The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned. Another one (also explainable): >>> 0 or None == None or 0 True # Above is same as (operator precedence): >>> 0 or (None == None) or 0 True # Here is something different: >>> (0 or None) == (None or 0) False From python at rcn.com Tue Aug 4 16:14:29 2009 From: python at rcn.com (Raymond Hettinger) Date: Tue, 4 Aug 2009 13:14:29 -0700 (PDT) Subject: no-clobber dicts? References: <28309a6c-f6f2-4f11-852f-6e3f570253e7@a26g2000yqn.googlegroups.com> Message-ID: <435e2e2c-6f83-48e0-870e-febdc37c4c5c@x6g2000prc.googlegroups.com> [kj] > The implication here is that .update() does not in turn use > .__setitem__(), which I find a bit surprising. It's never wise to make assumptions about this sort of thing. Every method in a class or type is allowed to directly access or modify its private, internal data. The implementation is free to choose whether to limit that access to a few accessors (i.e. getitem, setitem, delitem, len) or to let all of the methods have direct access to the underlying data structure. Even if accessors were used, the choice would be arbitrary (perhaps delitem() gets implemented in terms of pop() or somesuch). This is a basic for OO programming. Unless the class documentation promises to use particular hooks, the implementation is free to change in any way that doesn't violate the published API (this is one of the benefits of encapsulation and abstract data types). In general, if a subclass is overriding, rather than extending, then it should override *every* method that could be affected. Raymond From mensanator at aol.com Tue Aug 4 16:21:30 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Aug 2009 13:21:30 -0700 (PDT) Subject: Is it possible to have the python color in the terminal ? References: Message-ID: On Aug 4, 1:53?pm, aurelien wrote: > Hello, > > I am under gNewSense, i am a newbbie on Python, i look for how change > the color terminal when python run. > at the step >>> all is in black and white. > Is it possible to have the python color in the terminal ? Depends on whether your terminal supports ANSI codes. For example, Windows does not, but the Cygwin terminal does. So, from Cygwin I can do >>> a = "\x1b[32m" >>> a '\x1b[32m' >>> print a >>> >>> >>> print b Traceback (most recent call last): File "", line 1, in NameError: name 'b' is not defined >>> And everything from the "print a" statement onwards is green. An ANSI code: an escape character (ESC, ASCII value 27, \x1b in hex) followed by the appropriate code sequence: Code: Meaning: \x1b[0m reset; clears all colors and styles (to white on black) \x1b[1m bold on (see below) \x1b[3m italics on \x1b[4m underline on \x1b[7m inverse on; reverses foreground & background colors \x1b[9m strikethrough on \x1b[22m bold off (see below) \x1b[23m italics off \x1b[24m underline off \x1b[27m inverse off \x1b[29m strikethrough off \x1b[30m set foreground color to black \x1b[31m set foreground color to red \x1b[32m set foreground color to green \x1b[33m set foreground color to yellow \x1b[34m set foreground color to blue \x1b[35m set foreground color to magenta (purple) \x1b[36m set foreground color to cyan \x1b[37m set foreground color to white \x1b[39m set foreground color to default (white) \x1b[40m set background color to black \x1b[41m set background color to red \x1b[42m set background color to green \x1b[43m set background color to yellow \x1b[44m set background color to blue \x1b[45m set background color to magenta (purple) \x1b[46m set background color to cyan \x1b[47m set background color to white \x1b[49m set background color to default (black) > > Thanks for your help. > > aurelien From apt.shansen at gmail.com Tue Aug 4 16:24:46 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Tue, 4 Aug 2009 13:24:46 -0700 Subject: boolean OR gotcha In-Reply-To: References: Message-ID: <7a9c25c20908041324l1a589c54q2f0f9666ab4ddd67@mail.gmail.com> > > > # Here is something different: > >>> (0 or None) == (None or 0) > False What is the actual problem? You quoted the docs, it seems very clear. (0 or None) would return None. (None or 0) would return 0. None is not equal to 0, of course. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From zuo at chopin.edu.pl Tue Aug 4 16:25:09 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 04 Aug 2009 22:25:09 +0200 Subject: boolean OR gotcha In-Reply-To: References: Message-ID: 04-08-2009 o 22:11:18 1x7y2z9 <1x7y2z9 at gmail.com> wrote: > Another one (also explainable): >>>> 0 or None == None or 0 > True > # Above is same as (operator precedence): >>>> 0 or (None == None) or 0 > True > # Here is something different: >>>> (0 or None) == (None or 0) > False I don't see any problem here. The last is ok: None != 0. *j -- Jan Kaliszewski (zuo) From kushal.kumaran+python at gmail.com Tue Aug 4 16:25:55 2009 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Wed, 5 Aug 2009 01:55:55 +0530 Subject: Online payment module In-Reply-To: References: Message-ID: <1e364c4e0908041325h5be577dq2363fba4c39af05b@mail.gmail.com> On Tue, Aug 4, 2009 at 12:41 AM, Sam Tregar wrote: > Hello all.? I'm considering building a module to provide a > cross-payment-gatewat API for making online payments.? In the Perl world we > have a module like this called Business::OnlinePayment > (http://search.cpan.org/~jasonk/Business-OnlinePayment-2.01/OnlinePayment.pm). > > Is there anything like this in Python?? My searches so far haven't turned up > anything.? If I don't find one I'll probably build one, covering PayPal and > Authorize.net to start.? If anyone is interested in discussing the project > and/or getting involved shoot me an email. > Not really familiar with this area, but have you seen these? http://code.google.com/p/pypaypal/ http://www.geteasyshop.com/front-page -- kushal From duane.kaufman at gmail.com Tue Aug 4 16:32:32 2009 From: duane.kaufman at gmail.com (DuaneKaufman) Date: Tue, 4 Aug 2009 13:32:32 -0700 (PDT) Subject: Overlap in python References: Message-ID: <2e475887-0e8d-4b34-a918-1af720c166bf@r38g2000yqn.googlegroups.com> On Aug 4, 1:15?pm, Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. ?For example, here would be my input: > > part name ? location > a ? ? ? ? ? ? ? ? ?5-9 > b ? ? ? ? ? ? ? ? ?7-10 > c ? ? ? ? ? ? ? ? ?3-6 > d ? ? ? ? ? ? ? ? ?15-20 > e ? ? ? ? ? ? ? ? ?18-23 > > And here is what I need for an output: > part name ? location > c.a.b ? ? ? ? ? ?3-10 > d.e ? ? ? ? ? ? ? 15-23 > > I've tried various methods, which all fail. ?Does anyone have an idea > how to do this? > > Thank you very much! > Jay Hi, You have gotten some excellent feedback (all without installing anything extra to your Python install), but might I suggest the use of an interval arithmetic package to aid in this? For instance the interval module found at: http://members.cox.net/apoco/interval/ can be put to use: Given your data above: > part name location > a 5-9 > b 7-10 > c 3-6 from interval import Interval >>> a_int=Interval(5,9) >>> b_int=Interval(7,10) >>> c_int=Interval(3,6) >>> a_int.overlaps(b_int) True >>> a_int.overlaps(c_int) True >>> b_int.overlaps(c_int) False Duane From 1x7y2z9 at gmail.com Tue Aug 4 16:35:02 2009 From: 1x7y2z9 at gmail.com (1x7y2z9) Date: Tue, 4 Aug 2009 13:35:02 -0700 (PDT) Subject: boolean OR gotcha References: Message-ID: Did not intend that there was a problem. Just a gotcha or a fun little titbit ... maybe. :) On Aug 4, 1:25?pm, "Jan Kaliszewski" wrote: > 04-08-2009 o 22:11:18 1x7y2z9 <1x7y... at gmail.com> wrote: > > > Another one (also explainable): > >>>> 0 or None == None or 0 > > True > > # Above is same as (operator precedence): > >>>> 0 or (None == None) or 0 > > True > > # Here is something different: > >>>> (0 or None) == (None or 0) > > False > > I don't see any problem here. > > The last is ok: None != 0. > > *j > -- > Jan Kaliszewski (zuo) From maxkhesin at gmail.com Tue Aug 4 16:45:10 2009 From: maxkhesin at gmail.com (xamdam) Date: Tue, 4 Aug 2009 13:45:10 -0700 (PDT) Subject: SDMX format Message-ID: Does anyone know of python libs for writing SDMX XML format? http://www.SDMX.org/resources/SDMXML/schemas/v2_0/common thanks, max. From bearophileHUGS at lycos.com Tue Aug 4 16:54:16 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Tue, 4 Aug 2009 13:54:16 -0700 (PDT) Subject: Overlap in python References: Message-ID: Jay Bird: > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 That's sometimes known as "The Set Union Problem on Intervals". Knowing the name of a problem is sometimes half the work :-) People have written papers on this. This is a O(N^2) force-brute algorithm, you can try it on your data: data = """part name location a 5-9 b 7-10 c 3-6 d 15-20 e 18-23""" pairs = map(str.split, data.splitlines()[1:]) triples = [map(int, i.split("-")) + [name] for (name, i) in pairs] overlap = lambda x1,y1, x2,y2: y1 >= x2 and x1 <= y2 results = [] for (x1,y1,name) in triples: for i, res in enumerate(results): if overlap(x1,y1, res[0],res[1]): results[i].append(name) results[i][0] = min(x1, res[0]) results[i][1] = max(y1, res[1]) break else: results.append([x1, y1, name]) print results # Output: [[3, 10, 'a', 'b', 'c'], [15, 23, 'd', 'e']] If you have have a lot of data then it will be too much slow, and you have to use a more complex algorithm. If your intervals are many, they are small, and they are spread in a not too much large range of possible values, you can create an integer array of indexes, and you can "paint" intervals on it. Bye, bearophile From gregor.lingl at aon.at Tue Aug 4 16:54:16 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 22:54:16 +0200 Subject: Overlap in python In-Reply-To: <2e475887-0e8d-4b34-a918-1af720c166bf@r38g2000yqn.googlegroups.com> References: <2e475887-0e8d-4b34-a918-1af720c166bf@r38g2000yqn.googlegroups.com> Message-ID: <4a78a005$0$2301$91cee783@newsreader02.highway.telekom.at> DuaneKaufman schrieb: > On Aug 4, 1:15 pm, Jay Bird wrote: ... > For instance the interval module found at: http://members.cox.net/apoco/interval/ > can be put to use: > > Given your data above: >> part name location >> a 5-9 >> b 7-10 >> c 3-6 > > from interval import Interval >>>> a_int=Interval(5,9) >>>> b_int=Interval(7,10) >>>> c_int=Interval(3,6) >>>> a_int.overlaps(b_int) > True >>>> a_int.overlaps(c_int) > True >>>> b_int.overlaps(c_int) > False As my proposed solution shows this approach can be done with on board means of Python (namely the set type). This would be quite different though, if you had floating point boundaries of the intervals. Regards, Gregor > > Duane From gregor.lingl at aon.at Tue Aug 4 16:57:59 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 04 Aug 2009 22:57:59 +0200 Subject: Overlap in python In-Reply-To: <4a78a005$0$2301$91cee783@newsreader02.highway.telekom.at> References: <2e475887-0e8d-4b34-a918-1af720c166bf@r38g2000yqn.googlegroups.com> <4a78a005$0$2301$91cee783@newsreader02.highway.telekom.at> Message-ID: <4a78a0e5$0$2301$91cee783@newsreader02.highway.telekom.at> Gregor Lingl schrieb: > > As my proposed solution shows this approach can > be done with on board means of Python (namely > the set type). This would be quite different though, > if you had floating point boundaries of the intervals. > ... or if the intgers involved were very big :-( > Regards, > Gregor > >> >> Duane From bearophileHUGS at lycos.com Tue Aug 4 17:00:37 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Tue, 4 Aug 2009 14:00:37 -0700 (PDT) Subject: Overlap in python References: <78d86d92-d373-4163-a418-600a3eb36ab3@o15g2000yqm.googlegroups.com> Message-ID: <1f284d33-256e-4a61-a59a-3c84a2cf00e6@18g2000yqa.googlegroups.com> Mark Dickinson: > # create sorted list of points where an interval is entered or left > transitions = [] > for name, (start, stop) in input: > ? ? transitions.extend([(start, 'Start', name), (stop, 'Stop', name)]) > transitions.sort() > > # scan list, accumulating blocks along the way. Oh, right, that's the usual simple solution. Silly me for showing the dumb quadratic solution :-) The "pixelmap" approach may be faster if you have tons of small intervals in a not too much large range. Bye, bearophile From dickinsm at gmail.com Tue Aug 4 17:22:01 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Tue, 4 Aug 2009 14:22:01 -0700 (PDT) Subject: Overlap in python References: <78d86d92-d373-4163-a418-600a3eb36ab3@o15g2000yqm.googlegroups.com> Message-ID: <0bf0707a-d053-4481-af26-b2a524ab0964@k19g2000yqn.googlegroups.com> On Aug 4, 9:03?pm, Mark Dickinson wrote: > for i, (pt, startend, name) in enumerate(transitions): Whoops. That line should just be: for pt, startend, name in transitions: The enumerate was accidentally left-over from a more complicated version. -- Mark From davea at ieee.org Tue Aug 4 17:34:23 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 04 Aug 2009 17:34:23 -0400 Subject: Using Python to automate builds In-Reply-To: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> Message-ID: <4A78A95F.9080209@ieee.org> Kosta wrote: > I am a Python newbie, tasked with automating (researching) building > Windows drivers using the WDK build environment. I've been looking > into Python for this (instead of writing a bunch of batch files). > > What I would like to do, is to open a cmd window, and start a Python > script. This script would then (based upon input arguments), build > different flavors of the driver (fre, chk, x86, x64) and do some post > processing (create cat files, sign, etc.). > > I was hoping to take advantage as much as possible of exisiting > infrastructure from the WDK. I am able to call setenv.bat and provide > all the input parameters. One of the things setenv.bat does is change > the path environment variable. However, this is not captured by > Python. I could duplicate the functionality, but I'd rather not. Is > there a way to capture all enviroment variable changes being made by a > batch file from Python? > > Thanks! > > An excellent question. It's been a few years, but last time I remember looking, setenv.bat only changed environment variables, and didn't change current directory, or run any external programs.. If that's still true, I figure you have three options. I don't know of any way to capture them explicitly. So here are the three choices I can come up with: 1) have the first python program invoke a new shell which runs setenv, then runs another python program. This second python program would be where all the work is done, invoking compilers, linkers etc. So the first python program invokes a batch file which looks something like: call setenv.bat arg1 python second.py arg2 arg3 arg4 arg5 This batch file could even be generated on the fly, just to simplify complex argument passing. 2) Have the python program invoke a batch file something like the following, and then analyze the resulting text file call setenv.bat arg1 set > tempfile.txt The contents of that tempfile could then be loaded into a dict similar to the usual environment. Now the Python script can continue, and just use these environment variable instead of the original set 3) Have the python program parse the setenv.bat instead of running it. There was a post on this newsgroup announcing pyKook. It's still in early form, but you might get ideas from it. I haven't looked, I just pasted the announcement to look at later. + I have released pyKook 0.0.2. + http://pypi.python.org/pypi/Kook/0.0.2 + http://www.kuwata-lab.com/kook/ + http://www.kuwata-lab.com/kook/pykook-users-guide.html Other possibilities: + http://pypi.python.org/pypi/vellum/ flexible small 'make' alternative + http://code.google.com/p/waf/ + http://code.google.com/p/fabricate/ DaveA From gdamjan at gmail.com Tue Aug 4 17:40:17 2009 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Tue, 04 Aug 2009 23:40:17 +0200 Subject: Problem in installing PyGreSQL References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com> <7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net> <20090804084856.b825967a.darcy@druid.net> <20090804095547.a5274e22.darcy@druid.net> Message-ID: <1fmmk6-htc.ln1@archaeopteryx.softver.org.mk> >> > By the way, you don't have to be super user to install PyGreSQL. >> > You just need SU if you want to install it system wide. PyGreSQL >> > doesn't require any special privileges to run. >> >> Right, but the packages install system-wide. That's why he could >> compile it himself but not use the package. > > Exactly so don't install the package. Do "python setup.py build" and > put the three files that are built (_pg.so, pg.py and pgdb.py) into > any directory and point PYTHONPATH to it. Or.. with Python 2.6 and up, you can do: python setup.py install --user and it will install the package in users own ~/.local/lib/python2.6/site-packages/ BTW that path is configurable with the PYTHONUSERBASE environment variable. see: http://www.python.org/dev/peps/pep-0370/ -- ?????? ( http://softver.org.mk/damjan/ ) Spammers scratch here with a diamond to find my address: ||||||||||||||||||||||||||||||||||||||||||||||| From kosta.koeman at gmail.com Tue Aug 4 17:40:46 2009 From: kosta.koeman at gmail.com (Kosta) Date: Tue, 4 Aug 2009 14:40:46 -0700 (PDT) Subject: Using Python to automate builds References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> Message-ID: <48e9dcba-5309-4de6-b833-7abec18120e1@d9g2000prh.googlegroups.com> On Aug 4, 2:34?pm, Dave Angel wrote: > Kosta wrote: > > I am a Python newbie, tasked with automating (researching) building > > Windows drivers using the WDK build environment. ?I've been looking > > into Python for this (instead of writing a bunch of batch files). > > > What I would like to do, is to open a cmd window, and start a Python > > script. ?This script would then (based upon input arguments), build > > different flavors of the driver (fre, chk, x86, x64) and do some post > > processing (create cat files, sign, etc.). > > > I was hoping to take advantage as much as possible of exisiting > > infrastructure from the WDK. ?I am able to call setenv.bat and provide > > all the input parameters. ?One of the things setenv.bat does is change > > the path environment variable. ?However, this is not captured by > > Python. ?I could duplicate the functionality, but I'd rather not. ?Is > > there a way to capture all enviroment variable changes being made by a > > batch file from Python? > > > Thanks! > > An excellent question. ?It's been a few years, but last time I remember > looking, setenv.bat only changed environment variables, and didn't > change current directory, or run any external programs.. ?If that's > still true, I figure you have three options. > > I don't know of any way to capture them explicitly. ?So here are the > three choices I can come up with: > > 1) have the first python program invoke a new shell which runs setenv, > then runs another python program. ?This second python program would be > where all the work is done, invoking compilers, linkers etc. ?So the > first python program invokes a batch file which looks something like: > ? ? ? ? ? call setenv.bat ?arg1 > ? ? ? ? ? python second.py ? ?arg2 arg3 ?arg4 ?arg5 > > ?This batch file could even be generated on the fly, just to simplify > complex argument passing. > > 2) Have the python program invoke a batch file something like the > following, and then analyze the resulting text file > ? ? ? ? ? ?call setenv.bat ? arg1 > ? ? ? ? ? ?set > tempfile.txt > > The contents of that tempfile could then be loaded into a dict similar > to the usual environment. ?Now the Python script can continue, and just > use these environment variable instead of the original set > > 3) Have the python program parse the setenv.bat instead of running it. > > There was a post on this newsgroup announcing pyKook. ?It's still in > early form, but you might get ideas from it. ?I haven't looked, I just > pasted the announcement to look at later. > > + I have released pyKook 0.0.2. > +http://pypi.python.org/pypi/Kook/0.0.2 > +http://www.kuwata-lab.com/kook/ > +http://www.kuwata-lab.com/kook/pykook-users-guide.html > > Other possibilities: > + ?http://pypi.python.org/pypi/vellum/? ? ? flexible small 'make' > alternative > > + ?http://code.google.com/p/waf/ > > + ?http://code.google.com/p/fabricate/ > > DaveA- Hide quoted text - > > - Show quoted text - Thanks Dave. I had thought about those three options, and was honestly hoping for a foruth (I know, some people are never satisfied ;). I'll look into pyKook. Thank you for your help. From philip at semanchuk.com Tue Aug 4 17:52:48 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 4 Aug 2009 17:52:48 -0400 Subject: Using Python to automate builds In-Reply-To: <48e9dcba-5309-4de6-b833-7abec18120e1@d9g2000prh.googlegroups.com> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <48e9dcba-5309-4de6-b833-7abec18120e1@d9g2000prh.googlegroups.com> Message-ID: On Aug 4, 2009, at 5:40 PM, Kosta wrote: > On Aug 4, 2:34 pm, Dave Angel wrote: >> >> + I have released pyKook 0.0.2. >> +http://pypi.python.org/pypi/Kook/0.0.2 >> +http://www.kuwata-lab.com/kook/ >> +http://www.kuwata-lab.com/kook/pykook-users-guide.html >> >> Other possibilities: >> + http://pypi.python.org/pypi/vellum/ flexible small 'make' >> alternative >> >> + http://code.google.com/p/waf/ >> >> + http://code.google.com/p/fabricate/ >> >> DaveA- Hide quoted text - >> >> - Show quoted text - > > Thanks Dave. I had thought about those three options, and was > honestly hoping for a foruth (I know, some people are never > satisfied ;). I'll look into pyKook. Thank you for your help. Poof! Your wish is granted! =) http://www.scons.org/ Dunno if you'll find it better, worse or different than the alternatives, but there it is. have fun P From no.email at please.post Tue Aug 4 17:57:25 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 21:57:25 +0000 (UTC) Subject: Overlap in python References: Message-ID: In Jay Bird writes: >Hi everyone, >I've been trying to figure out a simple algorithm on how to combine a >list of parts that have 1D locations that overlap into a non- >overlapping list. For example, here would be my input: >part name location >a 5-9 >b 7-10 >c 3-6 >d 15-20 >e 18-23 >And here is what I need for an output: >part name location >c.a.b 3-10 >d.e 15-23 >I've tried various methods, which all fail. Does anyone have an idea >how to do this? This problem is basically isomorphic to the problem of finding connected components in an undirected graph. If your parts are nodes in a graph, there's an edge between them if they overlap. The following is probably overkill, but it works. It uses the module pygraph, which you can download from http://code.google.com/p/python-graph/ The real work is done by its connected_components function. import pygraph from pygraph.algorithms.accessibility import connected_components class Part(object): def __init__(self, name, start, finish): self.name = name if start >= finish: raise ValueError("start must be strictly less than finish") self.start = start self.finish = finish def __str__(self): return self.name def combine_parts(parts): gr = pygraph.graph() gr.add_nodes(parts) # connect the nodes for i in range(len(parts) - 1): part_i = parts[i] for j in range(i + 1, len(parts)): part_j = parts[j] if (part_j.start <= part_i.finish <= part_j.finish or part_i.start <= part_j.finish <= part_i.finish): gr.add_edge(part_i, part_j) cc = connected_components(gr) c2n = {} # build connected components as lists for k, v in cc.items(): c2n.setdefault(v, []).append(k) ret = [] for nodes in c2n.values(): nodes.sort(key=lambda x: x.start) name = '.'.join(x.name for x in nodes) start = min(x.start for x in nodes) finish = max(x.finish for x in nodes) ret.append((name, start, finish)) return ret if __name__ == '__main__': data = [Part('a', 5, 9), Part('b', 7, 10), Part('c', 3, 6), Part('d', 15, 20), Part('e', 18, 23)] print combine_parts(data) When you run the script above, the output is [('c.a.b', 3, 10), ('d.e', 15, 23)] HTH, kynn From python at mrabarnett.plus.com Tue Aug 4 18:09:33 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Aug 2009 23:09:33 +0100 Subject: Overlap in python In-Reply-To: References: Message-ID: <4A78B19D.4020306@mrabarnett.plus.com> Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 > > I've tried various methods, which all fail. Does anyone have an idea > how to do this? > >>> parts = [(5, 9, "a"), (7, 10, "b"), (3, 6, "c"), (15, 20, "d"), (18, 23, "e")] >>> parts.sort() >>> parts [(3, 6, 'c'), (5, 9, 'a'), (7, 10, 'b'), (15, 20, 'd'), (18, 23, 'e')] >>> # Merge overlapping intervals. >>> pos = 1 >>> while pos < len(parts): # Merge the pair in parts[pos - 1 : pos + 1] if they overlap. p, q = parts[pos - 1 : pos + 1] if p[1] >= q[0]: parts[pos - 1 : pos + 1] = [(p[0], max(p[1], q[1]), p[2] + "." + q[2])] else: # They don't overlap, so try the next pair. pos += 1 >>> parts [(3, 10, 'c.a.b'), (15, 23, 'd.e')] From no.email at please.post Tue Aug 4 18:10:18 2009 From: no.email at please.post (kj) Date: Tue, 4 Aug 2009 22:10:18 +0000 (UTC) Subject: Overlap in python References: <78d86d92-d373-4163-a418-600a3eb36ab3@o15g2000yqm.googlegroups.com> Message-ID: In <78d86d92-d373-4163-a418-600a3eb36ab3 at o15g2000yqm.googlegroups.com> Mark Dickinson writes: >On Aug 4, 7:15=A0pm, Jay Bird wrote: >> Hi everyone, >> >> I've been trying to figure out a simple algorithm on how to combine a >> list of parts that have 1D locations that overlap into a non- >> overlapping list. =A0For example, here would be my input: >> >> part name =A0 location >> a =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A05-9 >> b =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A07-10 >> c =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A03-6 >> d =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A015-20 >> e =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A0 =A018-23 >> >> And here is what I need for an output: >> part name =A0 location >> c.a.b =A0 =A0 =A0 =A0 =A0 =A03-10 >> d.e =A0 =A0 =A0 =A0 =A0 =A0 =A0 15-23 >> >> I've tried various methods, which all fail. =A0Does anyone have an idea >> how to do this? >Here's an approach that might work. Turning it into a sensible >function and parsing input/massaging output properly are left >as an exercise. Blocks that just touch (e.g. (3, 6) then (6, 9)) >are amalgamated; if this isn't what you want, and they should >be treated as separate instead, then replace 'Stop' with 'Finish' >(or any other string that sorts before 'Start'). >input =3D [ > ('a', (5, 9)), > ('b', (7, 10)), > ('c', (3, 6)), > ('d', (15, 20)), > ('e', (18, 23)), > ] ># create sorted list of points where an interval is entered or left >transitions =3D [] >for name, (start, stop) in input: > transitions.extend([(start, 'Start', name), (stop, 'Stop', name)]) >transitions.sort() ># scan list, accumulating blocks along the way. >count =3D 0 >for i, (pt, startend, name) in enumerate(transitions): > if startend =3D=3D 'Start': > if not count: > start =3D pt > names =3D [] > count +=3D 1 > names.append(name) > else: > count -=3D 1 > if not count: > print '.'.join(names), "%s--%s" % (start, pt) Very cool. kynn From bearophileHUGS at lycos.com Tue Aug 4 18:10:33 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Tue, 4 Aug 2009 15:10:33 -0700 (PDT) Subject: Overlap in python References: Message-ID: kj: > ? ? # connect the nodes > ? ? for i in range(len(parts) - 1): > ? ? ? ? part_i = parts[i] > ? ? ? ? for j in range(i + 1, len(parts)): Note that's O(N^2), see the O(sort) standard solution by Mark Dickinson. Bye, bearophile From ryniek90 at gmail.com Tue Aug 4 18:20:21 2009 From: ryniek90 at gmail.com (ryniek90) Date: Wed, 05 Aug 2009 00:20:21 +0200 Subject: How to write replace string for object which will be substituted? [regexp] In-Reply-To: References: Message-ID: <4A78B425.2010604@gmail.com> Hi. I started learning regexp, and some things goes well, but most of them still not. I've got problem with some regexp. Better post code here: " >>> import re >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> mail '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> print mail name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = re.sub('^\n|$\n', '', mail) >>> print maail name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = re.sub(' ', '', maail) >>> print maail name at mail.com name1[at]mail[dot]com name2[$at$]mail[$dot$]com >>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) >>> print maail name at mail.com name1 at mail[dot]com name2 at mail[$dot$]com >>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) >>> print maail name at mail.com name1 at mail.com name2 at mail.com >>> #How must i write the replace string to replace all this regexp's with just ONE command, in string 'mail' ? >>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', *?*, mail) " How must i write that replace pattern (look at question mark), to maek that substituion work? I didn't saw anything helpful while reading Re doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but something gone wrong - didn't wrote it right. Is there more user friendly HowTo for Python Re, than this? I'm new to programming an regexp, sorry for inconvenience. From jay.bird0804 at gmail.com Tue Aug 4 18:21:13 2009 From: jay.bird0804 at gmail.com (Jay Bird) Date: Tue, 4 Aug 2009 15:21:13 -0700 (PDT) Subject: Overlap in python References: <4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> Message-ID: Hi everyone, I wanted to thank you all for your help and *excellent* discussion. I was able to utilize and embed the script by Grigor Lingl in the 6th post of this discussion to get my program to work very quickly (I had to do about 20 comparisons per data bin, with over 40K bins in total). I am involved in genomic analysis research and this problem comes up a lot and I was surprised to not have been able to find a clear way to solve it. I will also look through all the tips in this thread, I have a feeling they may come in handy for future use! Thank you again, Jay From mensanator at aol.com Tue Aug 4 18:47:16 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Aug 2009 15:47:16 -0700 (PDT) Subject: Overlap in python References: <4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> Message-ID: <99c721fe-57fa-4508-9acb-2399ac81b9bf@k19g2000yqn.googlegroups.com> On Aug 4, 2:57?pm, Gregor Lingl wrote: > Jay Bird schrieb: > > > > > > > Hi everyone, > > > I've been trying to figure out a simple algorithm on how to combine a > > list of parts that have 1D locations that overlap into a non- > > overlapping list. ?For example, here would be my input: > > > part name ? location > > a ? ? ? ? ? ? ? ? ?5-9 > > b ? ? ? ? ? ? ? ? ?7-10 > > c ? ? ? ? ? ? ? ? ?3-6 > > d ? ? ? ? ? ? ? ? ?15-20 > > e ? ? ? ? ? ? ? ? ?18-23 > > > And here is what I need for an output: > > part name ? location > > c.a.b ? ? ? ? ? ?3-10 > > d.e ? ? ? ? ? ? ? 15-23 > > Suppose you have your data given as a dictionary: > > data = {'a':(5,9), > ? ? ? ? ?'b':(7,10), > ? ? ? ? ?'c':(3,6), > ? ? ? ? ?'d':(15,20), > ? ? ? ? ?'e':(18,23)} > > Then the following not particularly elegant > but very simple and straight forward > algorithm will solve your problem: > > def values(key): > ? ? ?return set(range(data[key][0], data[key][1]+1)) > > keys = list(data.keys()) > result = [] > while keys: > ? ? ?k = [keys[0]] > ? ? ?keys = keys[1:] > ? ? ?v = values(k[0]) > ? ? ?for l in keys[:]: > ? ? ? ? ?if v.intersection(values(l)): > ? ? ? ? ? ? ?v.update(values(l)) > ? ? ? ? ? ? ?k.append(l) > ? ? ? ? ? ? ?keys.remove(l) > ? ? ?result.append((k,v)) > > # print(result) ## if you like > > for k, v in result: > ? ? ?print(".".join(sorted(k)), "%d-%d" % (min(v), max(v))) > > Regards, > Gregor > > > > > I've tried various methods, which all fail. ?Does anyone have an idea > > how to do this? > > > Thank you very much! > > Jay I was thinking sets, too. import random def overlap(): merge_count = 0 datam.append(data.pop(0)) while len(data)>0: d0 = data.pop(0) dmi = 0 dmtemp = datam[:] while d0: dmtest = d0[1].intersection(dmtemp[dmi][1]) #print(d0,dmtemp[dmi],dmtest) if len(dmtest)>0: # overlap dmtest = d0[1].union(dmtemp[dmi][1]) datam[dmi] = (d0[0]+dmtemp[dmi][0],dmtest) d0 = None dmi = 0 merge_count += 1 else: dmi += 1 if dmi == len(dmtemp): datam.append(d0) d0 = None return merge_count # repeat until 0 returned ## OP data ##data=[] ##data.append(('a',set([i for i in range(5,9+1)]))) ##data.append(('b',set([i for i in range(7,10+1)]))) ##data.append(('c',set([i for i in range(3,6+1)]))) ##data.append(('d',set([i for i in range(15,20+1)]))) ##data.append(('e',set([i for i in range(18,23+1)]))) ##datam = [] ## ##print() ##for j in data: print(j) ##print() ## ## ##overlap() ## ##for i in datam: ## print(i[0],min(i[1]),max(i[1])) ## ## ('a', {8, 9, 5, 6, 7}) ## ('b', {8, 9, 10, 7}) ## ('c', {3, 4, 5, 6}) ## ('d', {15, 16, 17, 18, 19, 20}) ## ('e', {18, 19, 20, 21, 22, 23}) ## ## cba 3 10 ## ed 15 23 ## special case - repeat overlap test until no merges data = [('A', {79, 80, 81, 82, 83, 84, 85, 86}), ('B', {96, 89, 90, 91, 92, 93, 94, 95}), ('C', {21, 22, 23, 24, 25, 26, 27, 28}), ('D', {64, 65, 66, 67, 68, 69, 62, 63}), ('E', {72, 73, 74, 75, 76, 77, 78, 79}), ('F', {65, 66, 67, 68, 69, 70, 71, 72}), ('G', {11, 12, 13, 14, 15, 16, 17, 18}), ('H', {24, 25, 26, 27, 28, 29, 30, 31}), ('I', {32, 33, 34, 35, 36, 37, 38, 31}), ('J', {81, 82, 83, 84, 85, 86, 87, 88})] datam = [] ## ('A', {55, 56, 57, 58, 59, 60, 61, 62}) ## ('B', {64, 57, 58, 59, 60, 61, 62, 63}) ## ('C', {10, 11, 12, 13, 14, 15, 16, 17}) ## ('D', {32, 25, 26, 27, 28, 29, 30, 31}) ## ('E', {54, 55, 56, 57, 58, 59, 60, 61}) ## ('F', {64, 65, 66, 59, 60, 61, 62, 63}) ## ('G', {41, 42, 43, 44, 45, 46, 47, 48}) ## ('H', {67, 68, 69, 70, 71, 72, 73, 74}) ## ('I', {55, 56, 57, 58, 59, 60, 61, 62}) ## ('J', {64, 65, 66, 67, 68, 69, 62, 63}) ## ## JIFEBA 54 69 ## C 10 17 ## D 25 32 ## G 41 48 ## H 67 74 <--- NFG overlaps JIFEBA print() for j in data: print(j) print() merges = 1 # corrects above while merges > 0: merges = overlap() print(merges) if merges>0: data = datam[:] datam = [] for i in datam: print(i[0],min(i[1]),max(i[1])) ## corrected ## ## ('A', {79, 80, 81, 82, 83, 84, 85, 86}) ## ('B', {96, 89, 90, 91, 92, 93, 94, 95}) ## ('C', {21, 22, 23, 24, 25, 26, 27, 28}) ## ('D', {64, 65, 66, 67, 68, 69, 62, 63}) ## ('E', {72, 73, 74, 75, 76, 77, 78, 79}) ## ('F', {65, 66, 67, 68, 69, 70, 71, 72}) ## ('G', {11, 12, 13, 14, 15, 16, 17, 18}) ## ('H', {24, 25, 26, 27, 28, 29, 30, 31}) ## ('I', {32, 33, 34, 35, 36, 37, 38, 31}) ## ('J', {81, 82, 83, 84, 85, 86, 87, 88}) ## ## 5 ## 1 ## 0 ## DJFEA 62 88 ## B 89 96 ## IHC 21 38 ## G 11 18 # random sequences data = [] for j in range(12): q = random.randint(0,90) r = q+12 data.append((chr(j+65),set([x for x in range(q,r)]))) datam = [] print() for j in data: print(j) print() merges = 1 # corrects above while merges > 0: merges = overlap() print(merges) if merges>0: data = datam[:] datam = [] for i in datam: print(i[0],min(i[1]),max(i[1])) ## ('A', {3, 4, 5, 6, 7, 8, 9, 10}) ## ('B', {76, 77, 78, 79, 80, 81, 82, 83}) ## ('C', {43, 44, 45, 46, 47, 48, 49, 50}) ## ('D', {42, 43, 44, 45, 46, 47, 48, 49}) ## ('E', {23, 24, 25, 26, 27, 28, 29, 30}) ## ('F', {49, 50, 51, 52, 53, 54, 55, 56}) ## ('G', {76, 77, 78, 79, 80, 81, 82, 83}) ## ('H', {1, 2, 3, 4, 5, 6, 7, 8}) ## ('I', {37, 38, 39, 40, 41, 42, 43, 44}) ## ('J', {83, 84, 85, 86, 87, 88, 89, 90}) ## ## 6 ## 0 ## HA 1 10 ## JGB 76 90 ## IFDC 37 56 ## E 23 30 ## ('A', {64, 65, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63}) ## ('B', {34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45}) ## ('C', {16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27}) ## ('D', {70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81}) ## ('E', {64, 65, 66, 67, 56, 57, 58, 59, 60, 61, 62, 63}) ## ('F', {34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45}) ## ('G', {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}) ## ('H', {64, 65, 66, 55, 56, 57, 58, 59, 60, 61, 62, 63}) ## ('I', {44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55}) ## ('J', {64, 65, 66, 67, 68, 57, 58, 59, 60, 61, 62, 63}) ## ('K', {96, 97, 98, 99, 88, 89, 90, 91, 92, 93, 94, 95}) ## ('L', {96, 97, 98, 99, 100, 89, 90, 91, 92, 93, 94, 95}) ## ## 6 ## 1 ## 0 ## FBJIHEA 34 68 ## C 16 27 ## D 70 81 ## G 0 11 ## LK 88 100 From python at mrabarnett.plus.com Tue Aug 4 18:55:36 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 04 Aug 2009 23:55:36 +0100 Subject: How to write replace string for object which will be substituted? [regexp] In-Reply-To: <4A78B425.2010604@gmail.com> References: <4A78B425.2010604@gmail.com> Message-ID: <4A78BC68.2020601@mrabarnett.plus.com> ryniek90 wrote: > Hi. > I started learning regexp, and some things goes well, but most of them > still not. > > I've got problem with some regexp. Better post code here: > > " > >>> import re > >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > mail [$dot$] com\n' > >>> mail > '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > >>> print mail > > name at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > >>> maail = re.sub('^\n|$\n', '', mail) > >>> print maail > name at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > >>> maail = re.sub(' ', '', maail) > >>> print maail > name at mail.com > name1[at]mail[dot]com > name2[$at$]mail[$dot$]com > >>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > >>> print maail > name at mail.com > name1 at mail[dot]com > name2 at mail[$dot$]com > >>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > >>> print maail > name at mail.com > name1 at mail.com > name2 at mail.com > >>> #How must i write the replace string to replace all this regexp's > with just ONE command, in string 'mail' ? > >>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', > *?*, mail) > " > > How must i write that replace pattern (look at question mark), to maek > that substituion work? I didn't saw anything helpful while reading Re > doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but > something gone wrong - didn't wrote it right. > Is there more user friendly HowTo for Python Re, than this? > > I'm new to programming an regexp, sorry for inconvenience. > I don't think you can do it in one regex, nor would I want to. Just use the string's replace() method. >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> mail '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> print mail name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = mail.strip() name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = maail.replace(' ', '') >>> print maail name at mail.com name1[at]mail[dot]com name2[$at$]mail[$dot$]com >>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') >>> print maail name at mail.com name1 at mail[dot]com name2 at mail[$dot$]com >>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') >>> print maail name at mail.com name1 at mail.com name2 at mail.com From sam at tregar.com Tue Aug 4 19:50:29 2009 From: sam at tregar.com (Sam Tregar) Date: Tue, 4 Aug 2009 19:50:29 -0400 Subject: Online payment module In-Reply-To: <1e364c4e0908041325h5be577dq2363fba4c39af05b@mail.gmail.com> References: <1e364c4e0908041325h5be577dq2363fba4c39af05b@mail.gmail.com> Message-ID: On Tue, Aug 4, 2009 at 4:25 PM, Kushal Kumaran < kushal.kumaran+python at gmail.com > wrote: > > Not really familiar with this area, but have you seen these? > > http://code.google.com/p/pypaypal/ > http://www.geteasyshop.com/front-page > Thanks, but neither of these are remotely what I'm looking for! The first is an API for accessing PayPal, but not the one I'll be using - this one has only one release and hasn't been updated in over a year, looks basically useless. The other is a full-fledged e-commerce application, not a code library. -sam -------------- next part -------------- An HTML attachment was scrubbed... URL: From alex at moreati.org.uk Tue Aug 4 20:30:05 2009 From: alex at moreati.org.uk (Alex Willmer) Date: Tue, 4 Aug 2009 17:30:05 -0700 (PDT) Subject: New implementation of re module References: Message-ID: <380ee69c-b498-4f99-8bca-2f680dd0171b@b14g2000yqd.googlegroups.com> On Jul 27, 5:34?pm, MRAB wrote: > Hi all, > > I've been working on a new implementation of the re module. The details > are athttp://bugs.python.org/issue2636, specifically fromhttp://bugs.python.org/issue2636#msg90954. I've included a .pyd file for > Python 2.6 on Windows if you want to try it out. Firstly Matthew, thank you for all your work on this. It brings some very nice regex features to Python. I've used Christopher Arndt's post as a basis and created a package from you latest upload (issue2636-20090804.zip), which builds for Python 2.5 and 2.6. I'd like to see this on PyPI, so it's easier to install the module and your work gets wider exposure. Would this be alright and would you prefer to have control of the upload, as this is your work? Below is the setup.py, the unicodedata_db.h files are taken from the appropriate branches on svn.python.org #!/usr/bin/env python import shutil import sys from distutils.core import setup, Extension MAJOR, MINOR = sys.version_info[:2] # Copy appropriate unicodedata_db.h, not found in published includes if (MAJOR, MINOR) == (2, 6): shutil.copy('Python26/unicodedata_db.h', './') elif (MAJOR, MINOR) == (2, 5): shutil.copy('Python25/unicodedata_db.h', './') else: print "WARNING: No unicodedata_db.h prepared." setup( name='regex', version='20080804', description='Alternate regular expression module, to replace re.', author='Matthew Barnett', author_email='python at mrabarnett.nospam.plus.com', # Obsfucated url='http://bugs.python.org/issue2636', py_modules = ['regex'], ext_modules=[Extension('_regex', ['_regex.c'])], ) Sincerely, Alex Willmer From missive at hotmail.com Tue Aug 4 21:01:14 2009 From: missive at hotmail.com (Lee Harr) Date: Wed, 5 Aug 2009 05:31:14 +0430 Subject: [ANNC] pybotwar-0.4 Message-ID: pybotwar is a fun and educational game where players create computer programs to control simulated robots to compete in a battle arena. http://pybotwar.googlecode.com/ pybotwar uses pybox2d for the physical simulation, and uses pygame and pygsear for the visualization. pybotwar is released under GPLv3. Changes in pybotwar-0.4: - added display of robot status - added configuration file for easier testing of various options - remove / don't remove dead robots - robot max health - physics values (force, torque, mass, bullet speed) - add non graphics mode (for much faster resolution of battles) - fixed cannon heating going below zero _________________________________________________________________ Drag n? drop?Get easy photo sharing with Windows Live? Photos. http://www.microsoft.com/windows/windowslive/products/photos.aspx From koranthala at gmail.com Tue Aug 4 21:29:17 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 18:29:17 -0700 (PDT) Subject: My first wxPython App with Twisted Message-ID: Hi, I am creating the first GUI app (wxPython based) using Twisted. I am facing an issue which I cannot seem to solve/understand due to lack of trace or anything. I had a big app written on twisted and now I am creating a login screen to the app. The app used to work without any issues. I added the login screen and the login screen comes up. But then everything freezes up. I have to force quit the python application to get anything back. Can anyone help me solve it? The code is as follows: import wx import os import logging from twisted.internet import wxreactor wxreactor.install() from twisted.internet import reactor #Called only after wxreactor.install() from twisted.internet.task import LoopingCall import clientapp def opj(path): """ Convert paths to the platform-specific separator """ st = apply(os.path.join, tuple(path.split('/'))) if path.startswith('/'): st = '/' + st return st class APPApp(wx.App): def OnInit(self): self.frame = APPFrame(None, -1, " APP Login", size=(200, 150)) self.panel = APPPanel(self.frame,-1) #client.run method does the verification etc along with other items client = clientapp.setup_app() call = LoopingCall(client.run) call.start(.51) return True def main(): app = APPApp(0) reactor.registerWxApp(app) try: reactor.run() except StandardError: raise class APPPanel(wx.Panel): """ APP GUI PANEL The panel in which the user name and password is typed. @var ID_LOGIN: Login buttons id. When this button is clicked, the data is stored for logging. """ ID_LOGIN = wx.NewId() def __init__(self, parent, id): self.parent = parent wx.Panel.__init__(self, parent, id, size=(200,150)) self.quote = wx.StaticText(self, -1, "APP Login",wx.Point(60, 10)) wx.StaticText(self, wx.ID_ANY, "User Name ", wx.Point(20, 33)) wx.StaticText(self, wx.ID_ANY, "Password ", wx.Point(20, 58)) self.usernameBox = wx.TextCtrl(self, wx.ID_ANY, "", wx.Point(80, 31), wx.Size(100, wx.ID_ANY)) self.usernameBox.SetFocus() self.passwordBox = wx.TextCtrl(self, wx.ID_ANY, "", wx.Point(80, 56), wx.Size(100, wx.ID_ANY), style=wx.TE_PASSWORD) self.button =wx.Button(self, self.ID_LOGIN, "Login", wx.Point (60, 88)) wx.EVT_BUTTON(parent, self.ID_LOGIN, self.on_login) def on_login(self, event): username = self.usernameBox.GetString(0, 128) password = self.passwordBox.GetString(0, 128) if username and password: self.parent.on_login_click(username, password) class APPTaskBarIcon(wx.TaskBarIcon): ''' TaskBar Icon So that the application is always alive on the taskbar. 3 operations are possible, DoubleClick on the taskbar would bring up the window, right click will bring up options to restore or exit the tool. ''' TBMENU_RESTORE = wx.NewId() TBMENU_CLOSE = wx.NewId() def __init__(self, frame): wx.TaskBarIcon.__init__(self) self.frame = frame # Set the image icon = self.MakeIcon(self.frame.get_image()) self.SetIcon(icon, "APP") self.imgidx = 1 # bind some events self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarActivate) self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, id=self.TBMENU_RESTORE) self.Bind(wx.EVT_MENU, self.OnTaskBarClose, id=self.TBMENU_CLOSE) def CreatePopupMenu(self): """ Right Click Popup Menu This method is called by the base class when it needs to popup the menu for the default EVT_RIGHT_DOWN event. """ menu = wx.Menu() menu.Append(self.TBMENU_RESTORE, "Restore Window") menu.Append(self.TBMENU_CLOSE, "Exit APP") return menu def MakeIcon(self, img): """ Return the generated Icon. This function is required because various platforms have different requirements for the icon size. """ if "wxMSW" in wx.PlatformInfo: img = img.Scale(16, 16) elif "wxGTK" in wx.PlatformInfo: img = img.Scale(22, 22) icon = wx.IconFromBitmap(img.ConvertToBitmap() ) return icon def OnTaskBarActivate(self, evt): ''' Activation code - say DoubleClick etc. It raises the window ''' if self.frame.IsIconized(): self.frame.Iconize(False) if not self.frame.IsShown(): self.frame.Show(True) self.frame.Raise() def OnTaskBarClose(self, evt): ''' On right click and close, the frame itself is closed ''' wx.CallAfter(self.frame.Close) class APPFrame(wx.Frame): def __init__(self, parent, id, title, size=None): wx.Frame.__init__(self, parent, id, title, size=size, pos=wx.Point(400, 300)) icon = self.get_icon() self.SetIcon(icon) self.tbicon = APPTaskBarIcon(self) self.Show(True) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.Bind(wx.EVT_ICONIZE, self.OnIconify) def on_login_click(self, username, password): self.Hide() def OnCloseWindow(self, event): if self.tbicon is not None: self.tbicon.Destroy() event.Skip() def OnIconify(self, event): self.Hide() def get_image(self): img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO) return img def get_icon(self): img = self.get_image() icon = wx.IconFromBitmap(img.ConvertToBitmap() ) return icon if __name__ == '__main__': main() -------------- If somebody can help me out, I would be much obliged. From koranthala at gmail.com Tue Aug 4 21:39:49 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 18:39:49 -0700 (PDT) Subject: My first wxPython App with Twisted References: Message-ID: <15ec22f4-7bcf-4a7f-81e0-ad98004adde4@p36g2000prn.googlegroups.com> On Aug 5, 6:29?am, koranthala wrote: > Hi, > ? ?I am creating the first GUI app (wxPython based) using Twisted. > ? ?I am facing an issue which I cannot seem to solve/understand due > to lack of trace or anything. > > ? ?I had a big app written on twisted and now I am creating a login > screen to the app. > ? ?The app used to work without any issues. I added the login screen > and the login screen comes up. > ? ? But then everything freezes up. I have to force quit the python > application to get anything back. Can anyone help me solve it? > > ? ?The code is as follows: > > import wx > import os > import logging > > from twisted.internet import wxreactor > wxreactor.install() > from twisted.internet import reactor #Called only after > wxreactor.install() > from twisted.internet.task import LoopingCall > > import clientapp > > def opj(path): > ? ?""" Convert paths to the platform-specific separator """ > ? ?st = apply(os.path.join, tuple(path.split('/'))) > ? ?if path.startswith('/'): > ? ? ? ?st = '/' + st > ? ?return st > > class APPApp(wx.App): > ? ?def OnInit(self): > ? ? ? ?self.frame = APPFrame(None, -1, " APP Login", size=(200, 150)) > ? ? ? ?self.panel = APPPanel(self.frame,-1) > ? ? ? ?#client.run method does the verification etc along with other > items > ? ? ? ?client = clientapp.setup_app() > ? ? ? ?call = LoopingCall(client.run) > ? ? ? ?call.start(.51) > ? ? ? ?return True > > def main(): > ? ?app = APPApp(0) > ? ?reactor.registerWxApp(app) > ? ?try: > ? ? ? ?reactor.run() > ? ?except StandardError: > ? ? ? ?raise > > class APPPanel(wx.Panel): > ? ?""" APP GUI PANEL > > ? ?The panel in which the user name and password is typed. > ? ?@var ID_LOGIN: Login buttons id. When this button is clicked, the > data > ? ? ? ?is stored for logging. > > ? ?""" > ? ?ID_LOGIN = wx.NewId() > > ? ?def __init__(self, parent, id): > ? ? ? ?self.parent = parent > ? ? ? ?wx.Panel.__init__(self, parent, id, size=(200,150)) > ? ? ? ?self.quote = wx.StaticText(self, -1, "APP Login",wx.Point(60, > 10)) > ? ? ? ?wx.StaticText(self, wx.ID_ANY, "User Name ", wx.Point(20, 33)) > ? ? ? ?wx.StaticText(self, wx.ID_ANY, "Password ", wx.Point(20, 58)) > ? ? ? ?self.usernameBox = wx.TextCtrl(self, wx.ID_ANY, "", > wx.Point(80, 31), wx.Size(100, wx.ID_ANY)) > ? ? ? ?self.usernameBox.SetFocus() > ? ? ? ?self.passwordBox = wx.TextCtrl(self, wx.ID_ANY, "", > wx.Point(80, 56), wx.Size(100, wx.ID_ANY), style=wx.TE_PASSWORD) > ? ? ? ?self.button =wx.Button(self, self.ID_LOGIN, "Login", wx.Point > (60, 88)) > ? ? ? ?wx.EVT_BUTTON(parent, self.ID_LOGIN, self.on_login) > > ? ?def on_login(self, event): > ? ? ? ?username = self.usernameBox.GetString(0, 128) > ? ? ? ?password = self.passwordBox.GetString(0, 128) > ? ? ? ?if username and password: > ? ? ? ? ? ?self.parent.on_login_click(username, password) > > class APPTaskBarIcon(wx.TaskBarIcon): > ? ?''' TaskBar Icon > > ? ?So that the application is always alive on the taskbar. > ? ?3 operations are possible, DoubleClick on the taskbar would bring > up the > ? ?window, right click will bring up options to restore or exit the > tool. > > ? ?''' > ? ?TBMENU_RESTORE = wx.NewId() > ? ?TBMENU_CLOSE ? = wx.NewId() > > ? ?def __init__(self, frame): > ? ? ? ?wx.TaskBarIcon.__init__(self) > ? ? ? ?self.frame = frame > ? ? ? ?# Set the image > ? ? ? ?icon = self.MakeIcon(self.frame.get_image()) > ? ? ? ?self.SetIcon(icon, "APP") > ? ? ? ?self.imgidx = 1 > ? ? ? ?# bind some events > ? ? ? ?self.Bind(wx.EVT_TASKBAR_LEFT_DCLICK, self.OnTaskBarActivate) > ? ? ? ?self.Bind(wx.EVT_MENU, self.OnTaskBarActivate, > id=self.TBMENU_RESTORE) > ? ? ? ?self.Bind(wx.EVT_MENU, self.OnTaskBarClose, > id=self.TBMENU_CLOSE) > > ? ?def CreatePopupMenu(self): > ? ? ? ?""" Right Click Popup Menu > > ? ? ? ?This method is called by the base class when it needs to popup > ? ? ? ?the menu for the default EVT_RIGHT_DOWN event. > > ? ? ? ?""" > ? ? ? ?menu = wx.Menu() > ? ? ? ?menu.Append(self.TBMENU_RESTORE, "Restore Window") > ? ? ? ?menu.Append(self.TBMENU_CLOSE, "Exit APP") > ? ? ? ?return menu > > ? ?def MakeIcon(self, img): > ? ? ? ?""" Return the generated Icon. > > ? ? ? ?This function is required because various platforms have > different > ? ? ? ?requirements for the icon size. > > ? ? ? ?""" > ? ? ? ?if "wxMSW" in wx.PlatformInfo: > ? ? ? ? ? ?img = img.Scale(16, 16) > ? ? ? ?elif "wxGTK" in wx.PlatformInfo: > ? ? ? ? ? ?img = img.Scale(22, 22) > ? ? ? ?icon = wx.IconFromBitmap(img.ConvertToBitmap() ) > ? ? ? ?return icon > > ? ?def OnTaskBarActivate(self, evt): > ? ? ? ?''' Activation code - say DoubleClick etc. It raises the window > ''' > ? ? ? ?if self.frame.IsIconized(): > ? ? ? ? ? ?self.frame.Iconize(False) > ? ? ? ?if not self.frame.IsShown(): > ? ? ? ? ? ?self.frame.Show(True) > ? ? ? ?self.frame.Raise() > > ? ?def OnTaskBarClose(self, evt): > ? ? ? ?''' On right click and close, the frame itself is closed ''' > ? ? ? ?wx.CallAfter(self.frame.Close) > > class APPFrame(wx.Frame): > ? ?def __init__(self, parent, id, title, size=None): > ? ? ? ?wx.Frame.__init__(self, parent, id, title, > ? ? ? ? ? ? ? ? ? ? ? ? ?size=size, pos=wx.Point(400, 300)) > ? ? ? ?icon = self.get_icon() > ? ? ? ?self.SetIcon(icon) > ? ? ? ?self.tbicon = APPTaskBarIcon(self) > ? ? ? ?self.Show(True) > ? ? ? ?self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) > ? ? ? ?self.Bind(wx.EVT_ICONIZE, self.OnIconify) > > ? ?def on_login_click(self, username, password): > ? ? ? ?self.Hide() > > ? ?def OnCloseWindow(self, event): > ? ? ? ?if self.tbicon is not None: > ? ? ? ? ? ?self.tbicon.Destroy() > ? ? ? ?event.Skip() > > ? ?def OnIconify(self, event): > ? ? ? ?self.Hide() > > ? ?def get_image(self): > ? ? ? ?img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO) > ? ? ? ?return img > > ? ?def get_icon(self): > ? ? ? ?img = self.get_image() > ? ? ? ?icon = wx.IconFromBitmap(img.ConvertToBitmap() ) > ? ? ? ?return icon > > if __name__ == '__main__': > ? ?main() > > -------------- > If somebody can help me out, I would be much obliged. Please disregard this mail. I will post a barebones version separately. From koranthala at gmail.com Tue Aug 4 21:41:40 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 18:41:40 -0700 (PDT) Subject: My first wxPython App with Twisted - barebones version Message-ID: <735ece44-08f5-4120-966f-28489299c443@o9g2000prg.googlegroups.com> Hi, I am creating the first GUI app (wxPython based) using Twisted. I am facing an issue which I cannot seem to solve/understand due to lack of trace or anything. I had a big app written on twisted and now I am creating a login screen to the app. The app used to work without any issues. I added the login screen and the login screen comes up. But then everything freezes up. I have to force quit the python application to get anything back. Can anyone help me solve it? The code is as follows: import wx import os import logging from twisted.internet import wxreactor wxreactor.install() from twisted.internet import reactor #Called only after wxreactor.install() from twisted.internet.task import LoopingCall import clientapp def opj(path): """ Convert paths to the platform-specific separator """ st = apply(os.path.join, tuple(path.split('/'))) if path.startswith('/'): st = '/' + st return st class APPApp(wx.App): def OnInit(self): self.frame = APPFrame(None, -1, " APP Login", size=(200, 150)) self.panel = APPPanel(self.frame,-1) client = clientapp.setup_app() call = LoopingCall(client.run) call.start(.51) return True def main(): app = APPApp(0) reactor.registerWxApp(app) try: reactor.run() except StandardError: raise class APPFrame(wx.Frame): def __init__(self, parent, id, title, size=None): wx.Frame.__init__(self, parent, id, title, size=size, pos=wx.Point(400, 300)) icon = self.get_icon() self.SetIcon(icon) self.Show(True) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) self.Bind(wx.EVT_ICONIZE, self.OnIconify) def on_login_click(self, username, password): self.Hide() def OnCloseWindow(self, event): event.Skip() def OnIconify(self, event): self.Hide() def get_image(self): img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO) return img def get_icon(self): img = self.get_image() icon = wx.IconFromBitmap(img.ConvertToBitmap() ) return icon if __name__ == '__main__': main() From geomajor56 at gmail.com Tue Aug 4 22:06:27 2009 From: geomajor56 at gmail.com (Michael Savarese) Date: Tue, 4 Aug 2009 22:06:27 -0400 Subject: os.walk() Message-ID: <75c8645a0908041906s138c1499k59cd57d569a5c83e@mail.gmail.com> Greetings Python newbie here, and thanks to all who have helped me previously. Is there a way of grabbing file attributes while traversing with os.walk()? It would be advantageous to have date modified and file size along with the file name. If anyone can point me in the right direction, I'd appreciate it. Thanks in advance Mike S -------------- next part -------------- An HTML attachment was scrubbed... URL: From erikwickstrom at gmail.com Tue Aug 4 22:37:32 2009 From: erikwickstrom at gmail.com (erikcw) Date: Tue, 4 Aug 2009 19:37:32 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? Message-ID: Hi, I'm trying to get multiprocessing to working consistently with my script. I keep getting random tracebacks with no helpful information. Sometimes it works, sometimes it doesn't. Traceback (most recent call last): File "scraper.py", line 144, in print pool.map(scrape, range(10)) File "/usr/lib/python2.6/multiprocessing/pool.py", line 148, in map return self.map_async(func, iterable, chunksize).get() File "/usr/lib/python2.6/multiprocessing/pool.py", line 422, in get raise self._value TypeError: expected string or buffer It's not always the same traceback, but they are always short like this. I'm running Python 2.6.2 on Ubuntu 9.04. Any idea how I can debug this? Thanks! Erik From clp2 at rebertia.com Tue Aug 4 22:48:45 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 4 Aug 2009 19:48:45 -0700 Subject: os.walk() In-Reply-To: <75c8645a0908041906s138c1499k59cd57d569a5c83e@mail.gmail.com> References: <75c8645a0908041906s138c1499k59cd57d569a5c83e@mail.gmail.com> Message-ID: <50697b2c0908041948q31a30819g29e3d7f196e94074@mail.gmail.com> On Tue, Aug 4, 2009 at 7:06 PM, Michael Savarese wrote: > Greetings > Python newbie here, and thanks to all who have helped me previously. > Is there a way of grabbing file attributes while traversing with os.walk()? > It would be advantageous to have date modified and file size along with the > file name. > If anyone can point me in the right direction, I'd appreciate it. Feed the path to os.stat(), and then use the `stat` module on the result: http://docs.python.org/library/os.html#os.stat http://docs.python.org/library/stat.html#module-stat Cheers, Chris -- http://blog.rebertia.com From koranthala at gmail.com Tue Aug 4 22:51:55 2009 From: koranthala at gmail.com (koranthala) Date: Tue, 4 Aug 2009 19:51:55 -0700 (PDT) Subject: My first wxPython App with Twisted - barebones version References: <735ece44-08f5-4120-966f-28489299c443@o9g2000prg.googlegroups.com> Message-ID: <6b487c43-814f-4130-b104-2b80795ed389@t11g2000prh.googlegroups.com> On Aug 5, 6:41?am, koranthala wrote: > Hi, > ? ?I am creating the first GUI app (wxPython based) using Twisted. > ? ?I am facing an issue which I cannot seem to solve/understand due > to lack of trace or anything. > ? ?I had a big app written on twisted and now I am creating a login > screen to the app. > ? ?The app used to work without any issues. I added the login screen > and the login screen comes up. > ? ? But then everything freezes up. I have to force quit the python > application to get anything back. Can anyone help me solve it? > ? ?The code is as follows: > > import wx > import os > import logging > > from twisted.internet import wxreactor > wxreactor.install() > from twisted.internet import reactor #Called only after > wxreactor.install() > from twisted.internet.task import LoopingCall > > import clientapp > > def opj(path): > ? ? """ Convert paths to the platform-specific separator """ > ? ? st = apply(os.path.join, tuple(path.split('/'))) > ? ? if path.startswith('/'): > ? ? ? ? st = '/' + st > ? ? return st > > class APPApp(wx.App): > ? ? def OnInit(self): > ? ? ? ? self.frame = APPFrame(None, -1, " APP Login", size=(200, 150)) > ? ? ? ? self.panel = APPPanel(self.frame,-1) > ? ? ? ? client = clientapp.setup_app() > ? ? ? ? call = LoopingCall(client.run) > ? ? ? ? call.start(.51) > ? ? ? ? return True > > def main(): > ? ? app = APPApp(0) > ? ? reactor.registerWxApp(app) > ? ? try: > ? ? ? ? reactor.run() > ? ? except StandardError: > ? ? ? ? raise > > class APPFrame(wx.Frame): > ? ? def __init__(self, parent, id, title, size=None): > ? ? ? ? wx.Frame.__init__(self, parent, id, title, > ? ? ? ? ? ? ? ? ? ? ? ? ? size=size, pos=wx.Point(400, 300)) > ? ? ? ? icon = self.get_icon() > ? ? ? ? self.SetIcon(icon) > ? ? ? ? self.Show(True) > ? ? ? ? self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) > ? ? ? ? self.Bind(wx.EVT_ICONIZE, self.OnIconify) > > ? ? def on_login_click(self, username, password): > ? ? ? ? self.Hide() > > ? ? def OnCloseWindow(self, event): > ? ? ? ? event.Skip() > > ? ? def OnIconify(self, event): > ? ? ? ? self.Hide() > > ? ? def get_image(self): > ? ? ? ? img= wx.Image(opj('client.ico'), wx.BITMAP_TYPE_ICO) > ? ? ? ? return img > > ? ? def get_icon(self): > ? ? ? ? img = self.get_image() > ? ? ? ? icon = wx.IconFromBitmap(img.ConvertToBitmap() ) > ? ? ? ? return icon > > if __name__ == '__main__': > ? ? main() Sorry for spamming this group. I found that this was due to a interaction with pyHook and the wxPython GUI. I havent solved it, but atleast it is not due to twisted and wxPython. From steve at REMOVE-THIS-cybersource.com.au Tue Aug 4 23:07:26 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Aug 2009 13:07:26 +1000 Subject: no-clobber dicts? References: Message-ID: <00027aa9$0$2969$c3e8da3@news.astraweb.com> On Wed, 5 Aug 2009 06:01 am kj wrote: > In Steven > D'Aprano writes: > >>class ConstantNamespace(dict): > > >>I also have a series of unit tests for it if you're interested in them. > > Actually, come to think of it, I think I'll take you up on this. > I'd love to see those tests. Unit testing in Python is in area I > need to work on. No problem. Here you go: http://www.cybersource.com.au/users/steve/python/constants.py Comments welcome. -- Steven From sturlamolden at yahoo.no Tue Aug 4 23:46:30 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 4 Aug 2009 20:46:30 -0700 (PDT) Subject: Is python buffer overflow proof? References: <7dnissF2bthr0U1@mid.uni-berlin.de> Message-ID: On Aug 4, 2:27?pm, Tim Chase wrote: > You *can* shoot yourself in the foot with Python, you just have > to aim much more carefully than you do with C/C++. You can e.g. define a class with a __del__ method and make some circular references. That should give you a nice memory leak. From IDOL at il.ibm.com Wed Aug 5 00:24:48 2009 From: IDOL at il.ibm.com (Ido Levy) Date: Wed, 5 Aug 2009 07:24:48 +0300 Subject: How to fetch an XML file using an HTTPS query In-Reply-To: <49b3a7400908040641l5f5daaa8v374041b7fbac442a@mail.gmail.com> References: <49b3a7400908040638h46d4e4dcxe5cd4120e9c2c7a1@mail.gmail.com> <49b3a7400908040641l5f5daaa8v374041b7fbac442a@mail.gmail.com> Message-ID: Hi Tycho, Thank you for your advice. My problem was in the query itself, I replaced every space character with '%20' and it works. You are right, the Python code below does do the work. Ido From: Tycho Andersen To: python-list at python.org Date: 04/08/2009 04:42 PM Subject: Re: How to fetch an XML file using an HTTPS query Blah, forgot to include the list. When is python-list going to get Reply-To? \t On Tue, Aug 4, 2009 at 8:38 AM, Tycho Andersen wrote: > Hi Ido, > > On Tue, Aug 4, 2009 at 6:25 AM, Ido Levy wrote: >> [snip] >> I got the following result in both cases: >> >> >> Invalid filter passed. >> > > To me, this doesn't look like a python problem: the application was > successfully connected to and returned a result. The problem you're > experiencing is that it wasn't the result you expected. Are you sure > you're setting the right headers, posting the right form values, etc. > and giving the app exactly what it wants? > > \t > -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From hjtoi-better-remove-before-reply at comcast.net Wed Aug 5 00:50:31 2009 From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen) Date: Tue, 04 Aug 2009 21:50:31 -0700 Subject: M2Crypto: How to generate subjectKeyIdentifier / authorityKeyIdentifier References: Message-ID: Matthias G?ntert wrote: > I am trying to add the extensions "subjectKeyIdentifier" and > "authorityKeyIdentifier" to a x509v3 certificate. M2Crypto has a couple of bugs open related that, with potential workarounds that I haven't yet deemed polished enough to checkin, but which might help you out: https://bugzilla.osafoundation.org/show_bug.cgi?id=7530 https://bugzilla.osafoundation.org/show_bug.cgi?id=12151 -- Heikki Toivonen - http://heikkitoivonen.net From nick.m.daly at gmail.com Wed Aug 5 01:06:45 2009 From: nick.m.daly at gmail.com (Nick Daly) Date: Wed, 05 Aug 2009 00:06:45 -0500 Subject: The Perils of PyContract (and Generators) Message-ID: <4A791365.50905@gmail.com> So, just in case any body else runs into this strange, strange happening, I thought I might as well document it somewhere Google can find it. Contracts for Python[0] and generators don't necessarily play well together. This mail comes in three parts, first, the example code that didn't work at all, second, a more in-depth view of the situation while you mull over the solution, and third, the answer. The trouble with this example is that even with all the (2 lines of) boilerplate code required to make PyContract work, the entire example is all of about a dozen lines long. The lines after the "post:" directive are executed every time the function returns, and if any one of them is false, PyContract raises an exception, preventing the calling code from acting on bad data: import os def find_files(name, directory="."): """Finds files with the sub-string name in the name. post: forall(__return__, lambda filename: name in filename) """ for root, dirs, files in os.walk(directory): for the_file in files: if name in the_file: yield the_file import contract contract.checkmod(__name__) That's it. We're just walking the directory and returning the next matching item in the generator when it's called. However, if we try executing this simple function in ipy (Interactive Python, not Iron Python), nothing works as you'd expect: In a directory containing 4 files: ["one fish", "two fish", "red fish", "blue fish"] >>> find_files("fish") >>> z = find_files("fish") >>> z.next() StopIteration: ... Apparently our generator object is empty whenever it's returned. When adding a print statement right before the yield, we see: >>> z = find_files("o") "one fish" "two fish" >>> z.next() StopIteration: ... Why are they printing during the function? Why is everything printing before the function even returns?? Has my python croaked? (How actors and serpents could both behave like amphibians is beyond me) The trouble is that when the yield statement is replaced with a return statement, everything works exactly as you might expect. It's perfect. Unit tests don't fail, doctests are happy, and dependent code works exactly as advertised. When you turn it back into a generator though, well, generating empty lists for everything isn't helpful. Getting irritated at it, I eventually just decided to comment out and remove as many lines as possible (11) without actually breaking the example, at which point it started working... What? The problem actually lies in the contract. Generally, the PyContract shouldn't affect the return values or in any way modify the code, which it doesn't, as long as the function returns a list values (the way the code had in fact originally been written). However, the contract mentioned above is actually quite wrong for a generator. PyContract's forall function checks every value in the list (exhausting the list) before returning it, and actually operates on the actual return value, and not a copy. Thus, when the forall function verifies all the values in the list, it's generating every value in the list, emptying the generator before it's returned. Correcting the above example involves doing nothing more than simplifying the contract: post: name in __return__ So, in conclusion, generators and PyContract's forall() function don't mix, and PyContract doesn't operate off of a copy of your parameters unless you explicitly tell it so (I don't think it ever operates off a copy of your return value). Nick 0: http://www.wayforward.net/pycontract/ From sturlamolden at yahoo.no Wed Aug 5 01:21:20 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 4 Aug 2009 22:21:20 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: Message-ID: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> On Aug 5, 4:37 am, erikcw wrote: > It's not always the same traceback, but they are always short like > this. I'm running Python 2.6.2 on Ubuntu 9.04. > > Any idea how I can debug this? In my experience, multiprocessing is fragile. Scripts tend fo fail for no obvious reason, case processes to be orphaned and linger, system- wide resource leaks, etc. For example, multiprocessing uses os._exit to stop a spawned process, even though it inevitably results in resource leaks on Linux (it should use sys.exit). Ga?l Varoquaux and I noticed this when we implemented shared memory ndarrays for numpy; we consistently got memory leaks with System V IPC for no obvious reason. Even after Jesse Noller was informed of the problem (about half a year ago), the bug still lingers. It is easy edit multiprocessing's forking.py file on you own, but bugs like this is a pain in the ass, and I suspect multiprocessing has many of them. Of course unless you show us you whole script, identifying the source of your bug will be impossible. But it may very likely be in multiprocessing as well. The quality of this module is not impressing. I am beginning to think that multiprocessing should never have made it into the Python standard library. The GIL cannot be that bad! If you can't stand the GIL, get a Unix (or Mac, Linux, Cygwin) and use os.fork. Or simply switch to a non-GIL Python: IronPython or Jython. Allow me to show you something better. With os.fork we can write code like this: class parallel(object): def __enter__(self): # call os.fork def __exit__(self, exc_type, exc_value, traceback): # call sys.exit in the child processes and # os.waitpid in the parent def __call__(self, iterable): # return different sub-subsequences depending on # child or parent status with parallel() as p: # parallel block starts here for item in p(iterable): # whatever # parallel block ends here This makes parallel code a lot cleaner than anything you can do with multiprocessing, allowing you to use constructs similar to OpenMP. Further, if you make 'parallel' a dummy context manager, you can develop and test the algorithms serially. The only drawback is that you have to use Cygwin to get os.fork on Windows, and forking will be less efficient (no copy-on-write optimization). Well, this is just one example of why Windows sucks from the perspective of the programmer. But it also shows that you can do much better by not using multiprocessing at all. The only case I can think of where multiprocessing would be usesful, is I/O bound code on Windows. But here you will almost always resort to C extension modules. For I/O bound code, Python tends to give you a 200x speed penalty over C. If you are resorting to C anyway, you can just use OpenMP in C for your parallel processing. We can thus forget about multiprocessing here as well, given that we have access to the C code. If we don't, it is still very likely that the C code releases the GIL, and we can get away with using Python threads instead of multiprocessing. IMHO, if you are using multiprocessing, you are very likely to have a design problem. Regards, Sturla From wuwei23 at gmail.com Wed Aug 5 01:45:50 2009 From: wuwei23 at gmail.com (alex23) Date: Tue, 4 Aug 2009 22:45:50 -0700 (PDT) Subject: Announcing PythonTurtle References: Message-ID: <80f475f8-e6ea-4960-bdb8-86a90c60d656@y10g2000prf.googlegroups.com> John Posner wrote: > OK, then why the statements "from turtle import *" in the modules > turtleprocess.py and turtlewidget.py? Looking in the source I'd say it's because there's a local turtle.py. From mensanator at aol.com Wed Aug 5 01:49:16 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 4 Aug 2009 22:49:16 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy Message-ID: I hadn't noticed this before, but the overhaul of Turtle Graphics dating back to 2.6 has been broken as far as gmpy is concerned. I hadn't noticed because I usually have tracing turned off (tracing off takes 3-4 seconds, tracing on takes 6-7 minutes). In 3.1, tracing is now a screen attribute, not a turtle atribute. I have no idea why tooter = turtle.Turtle() tooter.tracer(False) doesn't give me an error (I thought silent errors were a bad thing). Had to change to tooter = turtle.Turtle() tooter.screen.tracer(False) # tracer now a screen attribute to turn tracing off in 3.1. Naturally, having tracing on caused my program to crash. The 2.6 version seemed to work, but only because turning off tracing as a turtle attribute works in 2.6. So I turned it back on and it crashed too. 2.5 worked okay. The reason is that code in turtle.py was chabged from v2.5 if self._drawing: if self._tracing: dx = float(x1 - x0) dy = float(y1 - y0) distance = hypot(dx, dy) nhops = int(distance) to v3.1 if self._speed and screen._tracing == 1: diff = (end-start) diffsq = (diff[0]*screen.xscale)**2 + (diff[1] *screen.yscale)**2 nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed) *self._speed)) Unfortunately, that calculation of nhops is illegal if diffsq is an .mpf (gmpy floating point). Otherwise, you get Traceback (most recent call last): File "K:\user_python26\turtle\turtle_xy_Py3.py", line 95, in tooter.goto(the_coord) File "C:\Python31\lib\turtle.py", line 1771, in goto self._goto(Vec2D(*x)) File "C:\Python31\lib\turtle.py", line 3165, in _goto nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed)) ValueError: mpq.pow fractional exponent, inexact-root So when using gmpy, you have to convert the .mpz to int before calling turtle functions. (if tracing is on). demo code (fixed code commented out) import gmpy ## (even) hi----| ## | ## lo (odd) ## or ## ## (even) lo ## | ## | ## ----hi (odd) ## ## ## ## import turtle tooter = turtle.Turtle() tooter.hideturtle() tooter.speed('fast') turtle.update() # make tracer false and it works #tooter.screen.tracer(False) # tracer now a screen attribute tooter.penup() tooter.color('black') s = ['1','0'] while len(s[0])<10000: s = [''.join(s), s[0]] origin = [0,0] if s[0] == '0': tooter.goto(origin) tooter.dot(1) if s[1] == '0': tooter.goto([1,0]) tooter.dot(1) print(len(s[0])) for i,j in enumerate(s[0]): the_coord=[] cur_root = gmpy.sqrt(i) lo__root = gmpy.sqrt(i)**2 hi__root = ((gmpy.sqrt(i)+1)**2) ## cur_root = int(gmpy.sqrt(i)) ## lo__root = int(gmpy.sqrt(i)**2) ## hi__root = int(((gmpy.sqrt(i)+1)**2)) if hi__root%2==0: side = 'northeast' else: side = 'southwest' elbow = (hi__root - lo__root)//2 + lo__root + 1 if i>= elbow: side_len = i - elbow elbow_plus = True else: side_len = elbow - i elbow_plus = False if side == 'northeast': elbow_offset = [(gmpy.sqrt(elbow)-1)//2 +1,-((gmpy.sqrt(elbow)-1)// 2) +1] else: elbow_offset = [-((gmpy.sqrt(elbow)-1)//2 +1),((gmpy.sqrt (elbow)-1)//2 +1)] ## if side == 'northeast': ## elbow_offset = [int((gmpy.sqrt(elbow)-1)//2 +1),-int(((gmpy.sqrt (elbow)-1)//2) +1)] ## else: ## elbow_offset = [-int(((gmpy.sqrt(elbow)-1)//2 +1)),int (((gmpy.sqrt(elbow)-1)//2 +1))] elbow_coord = [origin[0]+elbow_offset[0],origin[1]+elbow_offset[1]] if i != hi__root and i != lo__root: if i == elbow: the_coord = elbow_coord else: if elbow_plus: if side == 'northeast': the_coord = [elbow_coord[0]-side_len,elbow_coord[1]] else: the_coord = [elbow_coord[0]+side_len,elbow_coord[1]] else: if side == 'northeast': the_coord = [elbow_coord[0],elbow_coord[1]+side_len] else: the_coord = [elbow_coord[0],elbow_coord[1]-side_len] else: if i % 2 == 0: # even square n = gmpy.sqrt(i)//2 - 1 ## n = int(gmpy.sqrt(i)//2) - 1 the_coord = [-n, -n-1] else: n = (gmpy.sqrt(i)-1)//2 - 1 ## n = int((gmpy.sqrt(i)-1)//2) - 1 the_coord = [1+n, 1+n] if j == '0': tooter.goto(the_coord) tooter.dot(2) print('done') turtle.update() turtle.done() print('done') From pfeldman at verizon.net Wed Aug 5 02:28:29 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Tue, 4 Aug 2009 23:28:29 -0700 (PDT) Subject: trouble with complex numbers Message-ID: <24821423.post@talk.nabble.com> When I try to compute the phase of a complex number, I get an error message: In [3]: from cmath import * In [4]: x=1+1J In [5]: phase(x) NameError: name 'phase' is not defined AttributeError: 'complex' object has no attribute 'phase' Any advice will be appreciated. -- View this message in context: http://www.nabble.com/trouble-with-complex-numbers-tp24821423p24821423.html Sent from the Python - python-list mailing list archive at Nabble.com. From ryniek90 at gmail.com Wed Aug 5 02:50:08 2009 From: ryniek90 at gmail.com (ryniek) Date: Tue, 4 Aug 2009 23:50:08 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> Message-ID: <581a0c92-3117-4712-bfac-a3b9c4f6eb97@26g2000yqk.googlegroups.com> On 5 Sie, 00:55, MRAB wrote: > ryniek90 wrote: > > Hi. > > I started learning regexp, and some things goes well, but most of them > > still not. > > > I've got problem with some regexp. Better post code here: > > > " > > ?>>> import re > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > ?>>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > ?>>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = re.sub('^\n|$\n', '', mail) > > ?>>> print maail > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > ?>>> maail = re.sub(' ', '', maail) > > ?>>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > > ?>>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > > ?>>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > ?>>> #How must i write the replace string to replace all this regexp's > > with just ONE command, in string 'mail' ? > > ?>>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', > > *?*, mail) > > " > > > How must i write that replace pattern (look at question mark), to maek > > that substituion work? I didn't saw anything helpful while reading Re > > doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but > > something gone wrong - didn't wrote it right. > > Is there more user friendly HowTo for Python Re, than this? > > > I'm new to programming an regexp, sorry for inconvenience. > > I don't think you can do it in one regex, nor would I want to. Just use > the string's replace() method. > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > mail [$dot$] com\n' > ?>>> mail > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > ?>>> print mail > > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > ?>>> maail = mail.strip() > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > ?>>> maail = maail.replace(' ', '') > ?>>> print maail > n... at mail.com > name1[at]mail[dot]com > name2[$at$]mail[$dot$]com > ?>>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > ?>>> print maail > n... at mail.com > name1 at mail[dot]com > name2 at mail[$dot$]com > ?>>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > ?>>> print maail > n... at mail.com > na... at mail.com > na... at mail.com Too bad, I thought that the almighty re module could do anything, but it failed with this (or maybe re can do what i want, but only few people knows how to force him to that? :P). But with help of MRAB, i choose The 3rd Point of Python's Zen - "Simple is better than complex." " >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> mail '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> print mail name at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = mail.lstrip().rstrip().replace(' ', '').replace('[dot]', '.').replace('[$dot$]', '.').replace('[at]', '@').replace('[$at$]', '@') >>> print maail name at mail.com name1 at mail.com name2 at mail.com >>> #Did it :) " Thanks again :) From ryniek90 at gmail.com Wed Aug 5 02:53:56 2009 From: ryniek90 at gmail.com (ryniek) Date: Tue, 4 Aug 2009 23:53:56 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> Message-ID: <45b7bc73-9c60-4da5-beda-1c2536add738@c1g2000yqi.googlegroups.com> On 5 Sie, 00:55, MRAB wrote: > ryniek90 wrote: > > Hi. > > I started learning regexp, and some things goes well, but most of them > > still not. > > > I've got problem with some regexp. Better post code here: > > > " > > ?>>> import re > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > ?>>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > ?>>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = re.sub('^\n|$\n', '', mail) > > ?>>> print maail > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > ?>>> maail = re.sub(' ', '', maail) > > ?>>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > > ?>>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > > ?>>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > ?>>> #How must i write the replace string to replace all this regexp's > > with just ONE command, in string 'mail' ? > > ?>>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', > > *?*, mail) > > " > > > How must i write that replace pattern (look at question mark), to maek > > that substituion work? I didn't saw anything helpful while reading Re > > doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but > > something gone wrong - didn't wrote it right. > > Is there more user friendly HowTo for Python Re, than this? > > > I'm new to programming an regexp, sorry for inconvenience. > > I don't think you can do it in one regex, nor would I want to. Just use > the string's replace() method. > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > mail [$dot$] com\n' > ?>>> mail > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > ?>>> print mail > > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > ?>>> maail = mail.strip() > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > ?>>> maail = maail.replace(' ', '') > ?>>> print maail > n... at mail.com > name1[at]mail[dot]com > name2[$at$]mail[$dot$]com > ?>>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > ?>>> print maail > n... at mail.com > name1 at mail[dot]com > name2 at mail[$dot$]com > ?>>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > ?>>> print maail > n... at mail.com > na... at mail.com > na... at mail.com Too bad, I thought that the almighty re module could do anything, but it failed with this (or maybe re can do what i want, but only few people knows how to force him to that? :P). But with help of MRAB, i choose The 3rd Point of Python's Zen - "Simple is better than complex." " >>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> mail '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' >>> print mail n... at mail.com name1 [at] mail [dot] com name2 [$at$] mail [$dot$] com >>> maail = mail.lstrip().rstrip().replace(' ', '').replace('[dot]', '.').replace('[$dot$]', '.').replace('[at]', '@').replace('[$at$]', '@') >>> print maail n... at mail.com na... at mail.com na... at mail.com >>> #Did it :) " Thanks again :) From casevh at gmail.com Wed Aug 5 02:54:12 2009 From: casevh at gmail.com (casevh) Date: Tue, 4 Aug 2009 23:54:12 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: Message-ID: On Aug 4, 10:49?pm, Mensanator wrote: > I hadn't noticed this before, but the overhaul of Turtle Graphics > dating > back to 2.6 has been broken as far as gmpy is concerned. > The reason is that code in turtle.py was chabged from > > v2.5 > ? ? ? ? if self._drawing: > ? ? ? ? ? ? if self._tracing: > ? ? ? ? ? ? ? ? dx = float(x1 - x0) > ? ? ? ? ? ? ? ? dy = float(y1 - y0) > ? ? ? ? ? ? ? ? distance = hypot(dx, dy) > ? ? ? ? ? ? ? ? nhops = int(distance) > > to > > v3.1 > ? ? ? ?if self._speed and screen._tracing == 1: > ? ? ? ? ? ? diff = (end-start) > ? ? ? ? ? ? diffsq = (diff[0]*screen.xscale)**2 + (diff[1] > *screen.yscale)**2 > ? ? ? ? ? ? nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed) > *self._speed)) > > Unfortunately, that calculation of nhops is illegal if diffsq is > an .mpf (gmpy > floating point). Otherwise, you get > > Traceback (most recent call last): > ? File "K:\user_python26\turtle\turtle_xy_Py3.py", line 95, in > > ? ? tooter.goto(the_coord) > ? File "C:\Python31\lib\turtle.py", line 1771, in goto > ? ? self._goto(Vec2D(*x)) > ? File "C:\Python31\lib\turtle.py", line 3165, in _goto > ? ? nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed)) > ValueError: mpq.pow fractional exponent, inexact-root > Warning: Completely untested fix ahead! What happens if you change turtle.py to use nhops=1+int((math.sqrt(diffsq)/(3*math.pow(1.1, self._speed) *self._speed)) casevh From steve at REMOVE-THIS-cybersource.com.au Wed Aug 5 03:19:52 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Aug 2009 17:19:52 +1000 Subject: Turtle Graphics are incompatible with gmpy References: Message-ID: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> On Wed, 5 Aug 2009 03:49 pm Mensanator wrote: > In 3.1, tracing is now a screen attribute, not a turtle atribute. > I have no idea why > > tooter = turtle.Turtle() > tooter.tracer(False) > > doesn't give me an error (I thought silent errors were a bad thing). What makes it an error? Do you consider the following an error? >>> class Test: ... pass ... >>> t = Test() >>> t.tracer = 5 >>> Perhaps you mean, it's an API change you didn't know about, and you wish to protest that Turtle Graphics made an incompatible API change without telling you? > Naturally, having tracing on caused my program to crash. It seg faulted or raised an exception? [...] > Unfortunately, that calculation of nhops is illegal if diffsq is > an .mpf (gmpy floating point). Otherwise, you get How does diffsq get to be a mpf? Are gmpy floats supposed to be supported? -- Steven From gregor.lingl at aon.at Wed Aug 5 03:21:44 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Wed, 05 Aug 2009 09:21:44 +0200 Subject: Turtle Graphics are incompatible with gmpy In-Reply-To: References: Message-ID: <4a793315$0$2305$91cee783@newsreader02.highway.telekom.at> Mensanator schrieb: > I hadn't noticed this before, but the overhaul of Turtle Graphics > dating > back to 2.6 has been broken as far as gmpy is concerned. > > I hadn't noticed because I usually have tracing turned off (tracing > off > takes 3-4 seconds, tracing on takes 6-7 minutes). > > In 3.1, tracing is now a screen attribute, not a turtle atribute. > I have no idea why > > tooter = turtle.Turtle() > tooter.tracer(False) > > doesn't give me an error (I thought silent errors were a bad thing). > Hi, on my machine I get: Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import turtle >>> tooter = turtle.Turtle() >>> tooter.tracer(False) Traceback (most recent call last): File "", line 1, in tooter.tracer(False) AttributeError: 'Turtle' object has no attribute 'tracer' >>> I'd like to help with your problem but I'd much better be able to analyze it, if I had a version of your script, which works as you intended with Python 2.5 and the old turtle module. Could you please post it? (The one you posted below uses some commands of the turtle 2.6 module which are not present in 2.5, so it doesn't run with Python 2.5) Regards, Gregor > Had to change to > > tooter = turtle.Turtle() > tooter.screen.tracer(False) # tracer now a screen attribute > > to turn tracing off in 3.1. > > Naturally, having tracing on caused my program to crash. The 2.6 > version > seemed to work, but only because turning off tracing as a turtle > attribute > works in 2.6. > > So I turned it back on and it crashed too. > > 2.5 worked okay. > > The reason is that code in turtle.py was chabged from > > v2.5 > if self._drawing: > if self._tracing: > dx = float(x1 - x0) > dy = float(y1 - y0) > distance = hypot(dx, dy) > nhops = int(distance) > > to > > v3.1 > if self._speed and screen._tracing == 1: > diff = (end-start) > diffsq = (diff[0]*screen.xscale)**2 + (diff[1] > *screen.yscale)**2 > nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed) > *self._speed)) > > Unfortunately, that calculation of nhops is illegal if diffsq is > an .mpf (gmpy > floating point). Otherwise, you get > > Traceback (most recent call last): > File "K:\user_python26\turtle\turtle_xy_Py3.py", line 95, in > > tooter.goto(the_coord) > File "C:\Python31\lib\turtle.py", line 1771, in goto > self._goto(Vec2D(*x)) > File "C:\Python31\lib\turtle.py", line 3165, in _goto > nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed)) > ValueError: mpq.pow fractional exponent, inexact-root > > So when using gmpy, you have to convert the .mpz to int before calling > turtle > functions. (if tracing is on). > > demo code (fixed code commented out) > > import gmpy > > ## (even) hi----| > ## | > ## lo (odd) > ## or > ## > ## (even) lo > ## | > ## | > ## ----hi (odd) > ## > ## > ## > ## > > import turtle > > tooter = turtle.Turtle() > > tooter.hideturtle() > tooter.speed('fast') > turtle.update() > # make tracer false and it works > #tooter.screen.tracer(False) # tracer now a screen attribute > tooter.penup() > tooter.color('black') > > s = ['1','0'] > while len(s[0])<10000: > s = [''.join(s), s[0]] > > > origin = [0,0] > if s[0] == '0': > tooter.goto(origin) > tooter.dot(1) > if s[1] == '0': > tooter.goto([1,0]) > tooter.dot(1) > > print(len(s[0])) > > for i,j in enumerate(s[0]): > the_coord=[] > cur_root = gmpy.sqrt(i) > lo__root = gmpy.sqrt(i)**2 > hi__root = ((gmpy.sqrt(i)+1)**2) > ## cur_root = int(gmpy.sqrt(i)) > ## lo__root = int(gmpy.sqrt(i)**2) > ## hi__root = int(((gmpy.sqrt(i)+1)**2)) > > if hi__root%2==0: > side = 'northeast' > else: > side = 'southwest' > > elbow = (hi__root - lo__root)//2 + lo__root + 1 > > if i>= elbow: > > side_len = i - elbow > elbow_plus = True > else: > side_len = elbow - i > elbow_plus = False > > if side == 'northeast': > elbow_offset = [(gmpy.sqrt(elbow)-1)//2 +1,-((gmpy.sqrt(elbow)-1)// > 2) +1] > else: > elbow_offset = [-((gmpy.sqrt(elbow)-1)//2 +1),((gmpy.sqrt > (elbow)-1)//2 +1)] > ## if side == 'northeast': > ## elbow_offset = [int((gmpy.sqrt(elbow)-1)//2 +1),-int(((gmpy.sqrt > (elbow)-1)//2) +1)] > ## else: > ## elbow_offset = [-int(((gmpy.sqrt(elbow)-1)//2 +1)),int > (((gmpy.sqrt(elbow)-1)//2 +1))] > > elbow_coord = [origin[0]+elbow_offset[0],origin[1]+elbow_offset[1]] > > if i != hi__root and i != lo__root: > if i == elbow: > the_coord = elbow_coord > else: > if elbow_plus: > if side == 'northeast': > the_coord = [elbow_coord[0]-side_len,elbow_coord[1]] > else: > the_coord = [elbow_coord[0]+side_len,elbow_coord[1]] > else: > if side == 'northeast': > the_coord = [elbow_coord[0],elbow_coord[1]+side_len] > else: > the_coord = [elbow_coord[0],elbow_coord[1]-side_len] > else: > if i % 2 == 0: # even square > n = gmpy.sqrt(i)//2 - 1 > ## n = int(gmpy.sqrt(i)//2) - 1 > the_coord = [-n, -n-1] > else: > n = (gmpy.sqrt(i)-1)//2 - 1 > ## n = int((gmpy.sqrt(i)-1)//2) - 1 > the_coord = [1+n, 1+n] > if j == '0': > tooter.goto(the_coord) > tooter.dot(2) > print('done') > > turtle.update() > turtle.done() > print('done') From steve at REMOVE-THIS-cybersource.com.au Wed Aug 5 03:23:29 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: Wed, 05 Aug 2009 17:23:29 +1000 Subject: The Perils of PyContract (and Generators) References: Message-ID: <0002b6ac$0$2970$c3e8da3@news.astraweb.com> On Wed, 5 Aug 2009 03:06 pm Nick Daly wrote: > The problem actually lies in the contract. Generally, the PyContract > shouldn't affect the return values or in any way modify the code, which > it doesn't, as long as the function returns a list values (the way the > code had in fact originally been written). However, the contract > mentioned above is actually quite wrong for a generator. Yes, because you are conflating the items yielded from the generator with the generator object returned from the generator function "find_files". You can't look inside the generator object without using up whichever items you look at. [...] > Correcting the above example involves doing nothing more than > simplifying the contract: > > post: > name in __return__ That can't be right, not unless PyContract is doing something I don't expect. I expect that would be equivalent of: 'fish' in which should fail: >>> __return__ = find_files('fish') # a generator object >>> 'fish' in __return__ False >>> >>> __return__ = find_files('fish') >>> __return__ = list(__return__) >>> 'fish' in __return__ False >>> __return__ ['one fish', 'two fish', 'red fish', 'blue fish'] Of course, I may be mistaking what PyContract is doing. -- Steven From rays at blue-cove.com Wed Aug 5 03:25:03 2009 From: rays at blue-cove.com (RayS) Date: Wed, 05 Aug 2009 00:25:03 -0700 Subject: Cypress FX2 - py libusb code? Message-ID: <5.2.1.1.2.20090804224315.01c22b60@pop-server.san.rr.com> An HTML attachment was scrubbed... URL: From gregor.lingl at aon.at Wed Aug 5 03:37:08 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Wed, 05 Aug 2009 09:37:08 +0200 Subject: Turtle Graphics are incompatible with gmpy In-Reply-To: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: <4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> Steven D'Aprano schrieb: > On Wed, 5 Aug 2009 03:49 pm Mensanator wrote: > >> In 3.1, tracing is now a screen attribute, not a turtle atribute. >> I have no idea why >> >> tooter = turtle.Turtle() >> tooter.tracer(False) >> >> doesn't give me an error (I thought silent errors were a bad thing). > > What makes it an error? Do you consider the following an error? > >>>> class Test: > ... pass > ... >>>> t = Test() >>>> t.tracer = 5 >>>> > > Perhaps you mean, it's an API change you didn't know about, and you wish to > protest that Turtle Graphics made an incompatible API change without > telling you? > It didn't form 2.5 to 2.6 (at least not intentionally). But with the indroduction of the TurtleScreen class and the Screen class/object (singleton) a few of the turtle methods were also implemented as screen methods and as turtle methods declared deprecated (see docs of Python 2.6). These deprecated turtle methods do not occur as turtle methods any more in Python 3.x. Among them is the tracer method, which in fact does not control single turtle objects but all the turtles on a given screen. So there is an icompatibility beween 2.6 and 3.x But as far as I have understood, this doesn't concern the problem reported by mensator. Regards, Gregor > >> Naturally, having tracing on caused my program to crash. > > It seg faulted or raised an exception? > > > [...] >> Unfortunately, that calculation of nhops is illegal if diffsq is >> an .mpf (gmpy floating point). Otherwise, you get > > How does diffsq get to be a mpf? Are gmpy floats supposed to be supported? > > > From news123 at free.fr Wed Aug 5 03:44:18 2009 From: news123 at free.fr (News123) Date: Wed, 05 Aug 2009 09:44:18 +0200 Subject: merge two png pic In-Reply-To: <72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com> References: <006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com> <4a77e249$0$2449$426a74cc@news.free.fr> <72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com> Message-ID: <4a793852$0$19598$426a74cc@news.free.fr> You didn't really tell us why you need one big file, which contains more pixel, than you can probably store in RAM Is it for printing? Not knwoing your goal makes it difficult to suggest solutions. Can't you use other image formats like raw RGB or What other image formats are supported? tiff? Raw? PPM ( http://en.wikipedia.org/wiki/Portable_pixmap )? concatenating raw/ppm files with the same width would be really trivial. so you could use python to create horizontal raw/ppm stripes. then you could concatenate them without having to have the whole image in RAM. Perhaps there's even converters from ppm to png, that don't need the whole image in RAM. cocobear wrote: > On Aug 4, 3:24 pm, News123 wrote: >> Hi, >> >> >> >> >> >> cocobear wrote: >>>>>>> Map = Image.new("RGB", (x,y)) >>>>>>> Map.paste(im, box) >>>>>>> Map.paste(im1,box) >>>>>>> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE) >>>>>>> But if thetwopngpicis too big , or if I have tomergemorepic >>>>>>> together, I will get MemoryError: >>>>>>>>>>>>> Image.new("RGB",(44544,38656)) >>>> What do you want to do with such a big image? You will run into the same >>>> limitation when you are trying to display it. >>> I want to download a map from google map with high precision >> For me it sounds strange to handle such big files. >> >> Is the map you download from Google really that big? >> Mostly Google maps uses normally tiles of sizes 256x256 pixel, wich you >> have to compose to get the big image. >> > > The map I downloaded from Google is small(256x256). These small maps > will compose a big image. > > > >> If your problem is to combine tiles with different palettes, then you >> should pobably look at a way to 'unify' the palette of all tiles befor >> combining them. >> > > I think it is impossible to 'unify' all this tiles. > > >> Being no expert of PIL I don't know whether this is easily possible though? >> >> bye >> >> N > From hendrik at microcorp.co.za Wed Aug 5 03:56:33 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 5 Aug 2009 09:56:33 +0200 Subject: Using Python to automate builds In-Reply-To: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> Message-ID: <200908050956.33995.hendrik@microcorp.co.za> On Tuesday 04 August 2009 21:13:10 Kosta wrote: > I am a Python newbie, tasked with automating (researching) building > Windows drivers using the WDK build environment. I've been looking > into Python for this (instead of writing a bunch of batch files). > Why do you not use make and a makefile - it was designed to do exactly this. - Hendrik From fafounet at gmail.com Wed Aug 5 04:08:14 2009 From: fafounet at gmail.com (Fafounet) Date: Wed, 5 Aug 2009 01:08:14 -0700 (PDT) Subject: Special chars with HTMLParser Message-ID: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com> Hello, I am parsing a web page with special chars such as é (which stands for ?). I know I can have the unicode character ? from unicode ("\xe9","iso-8859-1") but with those extra characters I don' t know. I tried to implement handle_charref within HTMLParser without success. Furthermore, if I have the data abécd, handle_data will get "ab", handle_charref will get xe9 and then handle_data doesn't have the end of the string ("cd"). Thank you for your help, Fabien From clp2 at rebertia.com Wed Aug 5 04:40:59 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 5 Aug 2009 01:40:59 -0700 Subject: trouble with complex numbers In-Reply-To: <24821423.post@talk.nabble.com> References: <24821423.post@talk.nabble.com> Message-ID: <50697b2c0908050140g3acd8a8cx9fc87af12ea77c31@mail.gmail.com> On Tue, Aug 4, 2009 at 11:28 PM, Dr. Phillip M. Feldman wrote: > > When I try to compute the phase of a complex number, I get an error message: > > In [3]: from cmath import * > In [4]: x=1+1J > In [5]: phase(x) > > NameError: name 'phase' is not defined > > AttributeError: 'complex' object has no attribute 'phase' I suspect the problem lies in what you snipped away: In [1]: from cmath import phase In [2]: x=1+1J In [3]: phase(x) Out[3]: 0.78539816339744828 Cheers, Chris -- http://blog.rebertia.com From wuwei23 at gmail.com Wed Aug 5 04:43:13 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Aug 2009 01:43:13 -0700 (PDT) Subject: trouble with complex numbers References: Message-ID: On Aug 5, 4:28?pm, "Dr. Phillip M. Feldman" wrote: > When I try to compute the phase of a complex number, I get an error message: > [...] > Any advice will be appreciated. 1. What version of Python are you using, and on what platform? 2. What you snipped is necessary to help debug your problem. 3. Do you have a cmath.py in the folder you're running the interpreter in? From sanu1267 at gmail.com Wed Aug 5 05:03:51 2009 From: sanu1267 at gmail.com (sanju ps) Date: Wed, 5 Aug 2009 14:33:51 +0530 Subject: Launch my application if its not running Message-ID: <2b76be80908050203o5d002a8draf4c8bed564eef2b@mail.gmail.com> How to check whether my gui application is running or not.If its already running i have to quit my program other wise i need to launch my program. Can anybody suggest a solution to this Regards Sanju -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Aug 5 05:07:14 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 5 Aug 2009 02:07:14 -0700 Subject: Launch my application if its not running In-Reply-To: <2b76be80908050203o5d002a8draf4c8bed564eef2b@mail.gmail.com> References: <2b76be80908050203o5d002a8draf4c8bed564eef2b@mail.gmail.com> Message-ID: <50697b2c0908050207h7f2a866fuf63e843a66a7030d@mail.gmail.com> On Wed, Aug 5, 2009 at 2:03 AM, sanju ps wrote: > How to check whether my gui application is running or not.If its already > running i have to quit my program other wise i need to launch my program. > Can anybody suggest a solution to this Use a lock file? http://en.wikipedia.org/wiki/Lock_file#Lock_files Cheers, Chris -- http://blog.rebertia.com From smpoojary at gmail.com Wed Aug 5 05:11:38 2009 From: smpoojary at gmail.com (Mahesh Poojary S) Date: Wed, 5 Aug 2009 02:11:38 -0700 (PDT) Subject: socket.inet_ntop, and pton question In-Reply-To: <12rpns1tkp0e34@corp.supernews.com> References: <12rpns1tkp0e34@corp.supernews.com> Message-ID: <24823395.post@talk.nabble.com> Martin-298 wrote: > > Hi > > Are these functions (inet_ntop(), inet_pton()) from the socket library > supported on Windows. > > If not is there an equivalent for them using Windows > > Ive seen mention of people creating their own in order to use them > > Appreciate the help > > ty > -- > http://mail.python.org/mailman/listinfo/python-list > > You can use the below code: def inet_ntop(address_family, packed_ip): if address_family != AF_INET: raise socket.error, (97, 'Address family not supported by protocol') lIP = [] for ch in packed_ip: lIP.append(str(ord(ch))) strIP = string.join(lIP,'.') return strIP def inet_pton(address_family, ip_string): if address_family != AF_INET: raise socket.error, (97, 'Address family not supported by protocol') lIP = ip_string.split('.') strHexIP = "" for i in lIP: if i == '': continue strHex = "%x" % int(i) strHex = strHex.zfill(2) strHexIP += "\\x"+strHex return strHexIP -- View this message in context: http://www.nabble.com/socket.inet_ntop%2C-and-pton-question-tp8677935p24823395.html Sent from the Python - python-list mailing list archive at Nabble.com. From lists at cheimes.de Wed Aug 5 05:21:18 2009 From: lists at cheimes.de (Christian Heimes) Date: Wed, 05 Aug 2009 11:21:18 +0200 Subject: trouble with complex numbers In-Reply-To: <24821423.post@talk.nabble.com> References: <24821423.post@talk.nabble.com> Message-ID: Dr. Phillip M. Feldman wrote: > When I try to compute the phase of a complex number, I get an error message: > > In [3]: from cmath import * > In [4]: x=1+1J > In [5]: phase(x) > > NameError: name 'phase' is not defined > > AttributeError: 'complex' object has no attribute 'phase' > > Any advice will be appreciated. phase() has been added to Python 2.6 and 3.0. It's not available in Python 2.5 and earlier. If you'd used cmath.phase() instead of the ugly "from cmath import *" statement you'd have seen the correct error message. You can write your own phase() function. This function is mostly correct unless either the real and/or the imag part is NaN or INF. from math import atan2 def phase(z): z += 1j # convert int, long, float to complex return atan2(z.imag, z.real) From Tribulations at Paralleles.invalid Wed Aug 5 06:13:00 2009 From: Tribulations at Paralleles.invalid (TP) Date: Wed, 05 Aug 2009 12:13:00 +0200 Subject: intricated functions: how to share a variable Message-ID: Hi everybody, See the following example: ######### def tutu(): def toto(): print a a = 4 print a a=2 toto() tutu() ########## I obtain the following error: "UnboundLocalError: local variable 'a' referenced before assignment" This is because Python looks in the local context before looking in the global context. The use of "global a" in toto() does not help because global allows to force Python to look for the variable at the module level. So, how to share a variable between intricated functions? Thanks a lot Julien -- python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\ 9&1+,\'Z4(55l4('])" "When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong." (first law of AC Clarke) From albert at spenarnc.xs4all.nl Wed Aug 5 06:35:18 2009 From: albert at spenarnc.xs4all.nl (Albert van der Horst) Date: 05 Aug 2009 10:35:18 GMT Subject: Overlap in python References: Message-ID: In article , Jay Bird wrote: >Hi everyone, > >I've been trying to figure out a simple algorithm on how to combine a >list of parts that have 1D locations that overlap into a non- >overlapping list. For example, here would be my input: > >part name location >a 5-9 >b 7-10 >c 3-6 >d 15-20 >e 18-23 > >And here is what I need for an output: >part name location >c.a.b 3-10 >d.e 15-23 > >I've tried various methods, which all fail. Does anyone have an idea >how to do this? That is an algorithmic question and has little to do with Python. You could proceed as follows: - Order your data by the lower limit - Combine everything with the same lower limit. - Then combine every pair of consecutive entries that overlap. (In you case the second step is not needed.) > >Thank you very much! >Jay -- -- Albert van der Horst, UTRECHT,THE NETHERLANDS Economic growth -- being exponential -- ultimately falters. albert at spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst From deets at nospam.web.de Wed Aug 5 06:39:54 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Aug 2009 12:39:54 +0200 Subject: intricated functions: how to share a variable References: Message-ID: <7dt5rqF2crv46U1@mid.uni-berlin.de> TP wrote: > Hi everybody, > > See the following example: > > ######### > def tutu(): > > def toto(): > > print a > a = 4 > print a > > a=2 > toto() > > tutu() > ########## > > I obtain the following error: > "UnboundLocalError: local variable 'a' referenced before assignment" > > This is because Python looks in the local context before looking in the > global context. > > The use of "global a" in toto() does not help because global allows to > force Python to look for the variable at the module level. > > So, how to share a variable between intricated functions? You could use a class :) Another often used trick is to have a mutable container-object, like this: def tutu(): a = [2] def toto(): a[0] = 4 toto() Diez From clp2 at rebertia.com Wed Aug 5 06:42:23 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 5 Aug 2009 03:42:23 -0700 Subject: intricated functions: how to share a variable In-Reply-To: References: Message-ID: <50697b2c0908050342t5ae6feaauc757021a71521b2a@mail.gmail.com> On Wed, Aug 5, 2009 at 3:13 AM, TP wrote: > Hi everybody, > > See the following example: > > ######### > def tutu(): > > ? ?def toto(): > nonlocal a #note: this requires a rather recent version of python > ? ? ? ?print a > ? ? ? ?a = 4 > ? ? ? ?print a > > ? ?a=2 > ? ?toto() > > tutu() > ########## > > I obtain the following error: > "UnboundLocalError: local variable 'a' referenced before assignment" > > This is because Python looks in the local context before looking in the > global context. > > The use of "global a" in toto() does not help because global allows to force > Python to look for the variable at the module level. > > So, how to share a variable between intricated functions? Details: http://www.python.org/dev/peps/pep-3104/ Cheers, Chris -- http://blog.rebertia.com From bearophileHUGS at lycos.com Wed Aug 5 06:42:58 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Wed, 5 Aug 2009 03:42:58 -0700 (PDT) Subject: Overlap in python References: Message-ID: <4f5f1301-d160-4b61-926d-782277b064e9@r38g2000yqn.googlegroups.com> Albert van der Horst: >That is an algorithmic question and has little to do with Python.< Yes, but comp.lang.python isn't comp.lang.c, that kind of questions are perfectly fine here. They help keep this place from becoming boring. Bye, bearophile From __peter__ at web.de Wed Aug 5 06:46:28 2009 From: __peter__ at web.de (Peter Otten) Date: Wed, 05 Aug 2009 12:46:28 +0200 Subject: intricated functions: how to share a variable References: Message-ID: TP wrote: > Hi everybody, > > See the following example: > > ######### > def tutu(): > > def toto(): > > print a > a = 4 > print a > > a=2 > toto() > > tutu() > ########## > > I obtain the following error: > "UnboundLocalError: local variable 'a' referenced before assignment" > > This is because Python looks in the local context before looking in the > global context. > > The use of "global a" in toto() does not help because global allows to > force Python to look for the variable at the module level. > > So, how to share a variable between intricated functions? This limitation is removed in Python 3 with the 'nonlocal' statement: >>> def outer(): ... def inner(): ... nonlocal a ... print(a) ... a = 4 ... print(a) ... a = 2 ... inner() ... print(a) ... >>> outer() 2 4 4 Peter From bearophileHUGS at lycos.com Wed Aug 5 06:47:19 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Wed, 5 Aug 2009 03:47:19 -0700 (PDT) Subject: intricated functions: how to share a variable References: Message-ID: <9a937d26-2375-4836-9824-d34d9f92d284@o15g2000yqm.googlegroups.com> TP: > def tutu(): > > ? ? def toto(): > > ? ? ? ? print a > ? ? ? ? a = 4 > ? ? ? ? print a > > ? ? a=2 > ? ? toto() > > tutu() > ########## > > I obtain the following error: > "UnboundLocalError: local variable 'a' referenced before assignment" > > This is because Python looks in the local context before looking in the > global context. > > The use of "global a" in toto() does not help because global allows to force > Python to look for the variable at the module level. > > So, how to share a variable between intricated functions? Generally your purpose as a programmer is to write the least intricate code. Because the less tricky it is, the more readable it becomes and also the bug count decreases. So probably a better solution is to just use the normal function semantics: you pass them an argument and you take an argument as return value. Such return value will be the new version of the value you talk about. Python3+ has the "nonlocal" statement that may do what you ask for. But as many other things in Python it must be used with judgment, to avoid writing intricate code. Bye, bearophile From marcusw at cox.net Wed Aug 5 07:13:23 2009 From: marcusw at cox.net (Marcus Wanner) Date: Wed, 05 Aug 2009 07:13:23 -0400 Subject: Overlap in python In-Reply-To: <4A78B19D.4020306@mrabarnett.plus.com> References: <4A78B19D.4020306@mrabarnett.plus.com> Message-ID: On 8/4/2009 6:09 PM, MRAB wrote: > >>> parts = [(5, 9, "a"), (7, 10, "b"), (3, 6, "c"), (15, 20, "d"), > (18, 23, "e")] > >>> parts.sort() > >>> parts > [(3, 6, 'c'), (5, 9, 'a'), (7, 10, 'b'), (15, 20, 'd'), (18, 23, 'e')] > >>> # Merge overlapping intervals. > >>> pos = 1 > >>> while pos < len(parts): > # Merge the pair in parts[pos - 1 : pos + 1] if they overlap. > p, q = parts[pos - 1 : pos + 1] > if p[1] >= q[0]: > parts[pos - 1 : pos + 1] = [(p[0], max(p[1], q[1]), p[2] > + "." + q[2])] > else: > # They don't overlap, so try the next pair. > pos += 1 > > > >>> parts > [(3, 10, 'c.a.b'), (15, 23, 'd.e')] > That's the best solution I've seen so far. It even has input/output formatted as close as is reasonably possible to the format specified. As we would say in googlecode, +1. Marcus From marcusw at cox.net Wed Aug 5 07:21:55 2009 From: marcusw at cox.net (Marcus Wanner) Date: Wed, 05 Aug 2009 07:21:55 -0400 Subject: Using Python to automate builds In-Reply-To: References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <48e9dcba-5309-4de6-b833-7abec18120e1@d9g2000prh.googlegroups.com> Message-ID: On 8/4/2009 5:52 PM, Philip Semanchuk wrote: > > On Aug 4, 2009, at 5:40 PM, Kosta wrote: > >> On Aug 4, 2:34 pm, Dave Angel wrote: >>> >>> + I have released pyKook 0.0.2. >>> +http://pypi.python.org/pypi/Kook/0.0.2 >>> +http://www.kuwata-lab.com/kook/ >>> +http://www.kuwata-lab.com/kook/pykook-users-guide.html >>> >>> Other possibilities: >>> + http://pypi.python.org/pypi/vellum/ flexible small 'make' >>> alternative >>> >>> + http://code.google.com/p/waf/ >>> >>> + http://code.google.com/p/fabricate/ >>> >>> DaveA- Hide quoted text - >>> >>> - Show quoted text - >> >> Thanks Dave. I had thought about those three options, and was >> honestly hoping for a foruth (I know, some people are never >> satisfied ;). I'll look into pyKook. Thank you for your help. > > Poof! Your wish is granted! =) > > http://www.scons.org/ > > Dunno if you'll find it better, worse or different than the > alternatives, but there it is. > > have fun > P > > I can highly recommend scons. At dolphin-emu, we use it to daily compile a project containing over 500,000 lines of c/c++ code, which is modified very frequently. It works like a charm, and is seamlessly cross- platform (in my experience). However, it might not be exactly the thing you're looking for. Marcus From anthra.norell at bluewin.ch Wed Aug 5 07:28:18 2009 From: anthra.norell at bluewin.ch (Anthra Norell) Date: Wed, 05 Aug 2009 13:28:18 +0200 Subject: How to write replace string for object which will be substituted? [regexp] In-Reply-To: <4A78BC68.2020601@mrabarnett.plus.com> References: <4A78B425.2010604@gmail.com> <4A78BC68.2020601@mrabarnett.plus.com> Message-ID: <4A796CD2.7050009@bluewin.ch> MRAB wrote: > ryniek90 wrote: >> Hi. >> I started learning regexp, and some things goes well, but most of >> them still not. >> >> I've got problem with some regexp. Better post code here: >> >> " >> >>> import re >> >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] >> mail [$dot$] com\n' >> >>> mail >> '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail >> [$dot$] com\n' >> >>> print mail >> >> name at mail.com >> name1 [at] mail [dot] com >> name2 [$at$] mail [$dot$] com >> >> >>> maail = re.sub('^\n|$\n', '', mail) >> >>> print maail >> name at mail.com >> name1 [at] mail [dot] com >> name2 [$at$] mail [$dot$] com >> >>> maail = re.sub(' ', '', maail) >> >>> print maail >> name at mail.com >> name1[at]mail[dot]com >> name2[$at$]mail[$dot$]com >> >>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) >> >>> print maail >> name at mail.com >> name1 at mail[dot]com >> name2 at mail[$dot$]com >> >>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) >> >>> print maail >> name at mail.com >> name1 at mail.com >> name2 at mail.com >> >>> #How must i write the replace string to replace all this >> regexp's with just ONE command, in string 'mail' ? >> >>> maail = re.sub('^\n|$\n| >> |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', *?*, mail) >> " >> >> How must i write that replace pattern (look at question mark), to >> maek that substituion work? I didn't saw anything helpful while >> reading Re doc and HowTo (from Python Doc). I tried with >> 'MatchObject.group()' but something gone wrong - didn't wrote it right. >> Is there more user friendly HowTo for Python Re, than this? >> >> I'm new to programming an regexp, sorry for inconvenience. >> > I don't think you can do it in one regex, nor would I want to. Just use > the string's replace() method. > > >>> mail = '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > mail [$dot$] com\n' > >>> mail > '\nname at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > >>> print mail > > name at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > >>> maail = mail.strip() > name at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > >>> maail = maail.replace(' ', '') > >>> print maail > name at mail.com > name1[at]mail[dot]com > name2[$at$]mail[$dot$]com > >>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > >>> print maail > name at mail.com > name1 at mail[dot]com > name2 at mail[$dot$]com > >>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > >>> print maail > name at mail.com > name1 at mail.com > name2 at mail.com This is a good learning exercise demonstrating the impracticality of regular expressions in a given situation. In the light of the fascination regular expressions seem to exert in general, one might conclude that knowing regular expressions in essence is knowing when not to use them. There is nothing wrong with cascading substitutions through multiple expressions. The OP's solution wrapped up in a function and streamlined for needless regex overkill might look something like this: def translate (s): s1 = s.strip () # Instead of: s1 = re.sub ('^\n|$\n', '', s) s2 = s1.replace (' ', '') # Instead of: s2 = re.sub (' ', '', s1) s3 = re.sub ('\[at\]|\[\$at\$\]', '@', s2) s4 = re.sub ('\[dot\]|\[\$dot\$\]', '.', s3) return s4 print translate (mail) # Tested MRAB's solution using replace () avoids needless regex complexity, but doesn't simplify tedious coding if the number of substitutions is significant. Some time ago I proposed a little module I made to alleviate the tedium. It would handle this case like this: import SE Translator = SE.SE ( ' (32)= [at]=@ [$at$]=@ [dot]=. [$dot$]=. ' ) print Translator (mail.strip ()) # Tested So SE.SE compiles a string composed of any number of substitution definitions into an object that translates anything given it. In a running speed contest it would surely come in last, although in most cases the disadvantage would be imperceptible. Another matter is coding speed. Here the advantage is obvious, even with a set of substitutions as small as this one, let alone with sets in the tens or even hundreds. One inconspicuous but significant feature of SE is that it handles precedence correctly if targets overlap (upstream over downstream and long over short). As far as I know there's nothing in the Python system handling substitution precedence. It always needs to be hand-coded from one case to the next and that isn't exactly trivial. SE can be downloaded from http://pypi.python.org/pypi/SE/2.3. Frederic From joncle at googlemail.com Wed Aug 5 07:40:05 2009 From: joncle at googlemail.com (Jon Clements) Date: Wed, 5 Aug 2009 04:40:05 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> <45b7bc73-9c60-4da5-beda-1c2536add738@c1g2000yqi.googlegroups.com> Message-ID: On 5 Aug, 07:53, ryniek wrote: > On 5 Sie, 00:55, MRAB wrote: > > > > > ryniek90 wrote: > > > Hi. > > > I started learning regexp, and some things goes well, but most of them > > > still not. > > > > I've got problem with some regexp. Better post code here: > > > > " > > > ?>>> import re > > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > > mail [$dot$] com\n' > > > ?>>> mail > > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > > com\n' > > > ?>>> print mail > > > > n... at mail.com > > > name1 [at] mail [dot] com > > > name2 [$at$] mail [$dot$] com > > > > ?>>> maail = re.sub('^\n|$\n', '', mail) > > > ?>>> print maail > > > n... at mail.com > > > name1 [at] mail [dot] com > > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = re.sub(' ', '', maail) > > > ?>>> print maail > > > n... at mail.com > > > name1[at]mail[dot]com > > > name2[$at$]mail[$dot$]com > > > ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > > > ?>>> print maail > > > n... at mail.com > > > name1 at mail[dot]com > > > name2 at mail[$dot$]com > > > ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > > > ?>>> print maail > > > n... at mail.com > > > na... at mail.com > > > na... at mail.com > > > ?>>> #How must i write the replace string to replace all this regexp's > > > with just ONE command, in string 'mail' ? > > > ?>>> maail = re.sub('^\n|$\n| |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', > > > *?*, mail) > > > " > > > > How must i write that replace pattern (look at question mark), to maek > > > that substituion work? I didn't saw anything helpful while reading Re > > > doc and HowTo (from Python Doc). I tried with 'MatchObject.group()' but > > > something gone wrong - didn't wrote it right. > > > Is there more user friendly HowTo for Python Re, than this? > > > > I'm new to programming an regexp, sorry for inconvenience. > > > I don't think you can do it in one regex, nor would I want to. Just use > > the string's replace() method. > > > ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > ?>>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > ?>>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = mail.strip() > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > ?>>> maail = maail.replace(' ', '') > > ?>>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > ?>>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > > ?>>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > ?>>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > > ?>>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > Too bad, I thought that the almighty re module could do anything, but > it failed with this (or maybe re can do what i want, but only few > people knows how to force him to that? ?:P). > But with help of MRAB, i choose The 3rd Point of Python's Zen - > "Simple is better than complex." > > " > > >>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] com\n' > >>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > com\n' > > >>> print mail > > n... at mail.com > name1 [at] mail [dot] com > name2 [$at$] mail [$dot$] com > > >>> maail = mail.lstrip().rstrip().replace(' ', '').replace('[dot]', '.').replace('[$dot$]', '.').replace('[at]', '@').replace('[$at$]', '@') > >>> print maail > > n... at mail.com > na... at mail.com > na... at mail.com > > >>> #Did it ?:) > > " > > Thanks again ? :) Short of writing a dedicated function I might be tempted to write this as: EMAIL_REPLACEMENTS = ( ('[at]', '@'), ('[dot]', '.'), ... ) for src, dest in EMAIL_REPLACEMENTS: mail = mail.replace(src, dest) Apart from taste reasons, it keeps the replaces more obvious (and accessible via a variable rather than embedded in the code), enables swapping the order or adding/removing easier. Jon From cournape at gmail.com Wed Aug 5 08:08:18 2009 From: cournape at gmail.com (David Cournapeau) Date: Wed, 5 Aug 2009 21:08:18 +0900 Subject: Using Python to automate builds In-Reply-To: <200908050956.33995.hendrik@microcorp.co.za> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <200908050956.33995.hendrik@microcorp.co.za> Message-ID: <5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> On Wed, Aug 5, 2009 at 4:56 PM, Hendrik van Rooyen wrote: > On Tuesday 04 August 2009 21:13:10 Kosta wrote: >> I am a Python newbie, tasked with automating (researching) building >> Windows drivers using the WDK build environment. ?I've been looking >> into Python for this (instead of writing a bunch of batch files). >> > Why do you not use make and a makefile - it was designed to > do exactly this. Because make is a pain on windows (lack of a proper shell) ? cheers, David From jfine at pytex.org Wed Aug 5 08:17:44 2009 From: jfine at pytex.org (Jonathan Fine) Date: Wed, 05 Aug 2009 13:17:44 +0100 Subject: Do anyone here use Python *embedded* in a database? Message-ID: Hi I'm writing a talk that compares embed and extend, and wondered if anyone here ever used the Python *embedded* in a database server. http://twistedmatrix.com/users/glyph/rant/extendit.html Web frameworks (such as Django) use extend, to import an extension module that makes a connection to a database. If you have used embed, you might have consulted a page such as: http://www.postgresql.org/docs/8.3/interactive/plpython-funcs.html -- Jonathan From ryniek90 at gmail.com Wed Aug 5 08:21:43 2009 From: ryniek90 at gmail.com (ryniek) Date: Wed, 5 Aug 2009 05:21:43 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> <4A78BC68.2020601@mrabarnett.plus.com> Message-ID: <0cde7cf6-0365-44da-b044-9066d522fa2d@w41g2000yqb.googlegroups.com> On 5 Sie, 13:28, Anthra Norell wrote: > MRAB wrote: > > ryniek90 wrote: > >> Hi. > >> I started learning regexp, and some things goes well, but most of > >> them still not. > > >> I've got problem with some regexp. Better post code here: > > >> " > >> ?>>> import re > >> ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > >> mail [$dot$] com\n' > >> ?>>> mail > >> '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail > >> [$dot$] com\n' > >> ?>>> print mail > > >> n... at mail.com > >> name1 [at] mail [dot] com > >> name2 [$at$] mail [$dot$] com > > >> ?>>> maail = re.sub('^\n|$\n', '', mail) > >> ?>>> print maail > >> n... at mail.com > >> name1 [at] mail [dot] com > >> name2 [$at$] mail [$dot$] com > >> ?>>> maail = re.sub(' ', '', maail) > >> ?>>> print maail > >> n... at mail.com > >> name1[at]mail[dot]com > >> name2[$at$]mail[$dot$]com > >> ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > >> ?>>> print maail > >> n... at mail.com > >> name1 at mail[dot]com > >> name2 at mail[$dot$]com > >> ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > >> ?>>> print maail > >> n... at mail.com > >> na... at mail.com > >> na... at mail.com > >> ?>>> #How must i write the replace string to replace all this > >> regexp's with just ONE command, in string 'mail' ? > >> ?>>> maail = re.sub('^\n|$\n| > >> |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', *?*, mail) > >> " > > >> How must i write that replace pattern (look at question mark), to > >> maek that substituion work? I didn't saw anything helpful while > >> reading Re doc and HowTo (from Python Doc). I tried with > >> 'MatchObject.group()' but something gone wrong - didn't wrote it right. > >> Is there more user friendly HowTo for Python Re, than this? > > >> I'm new to programming an regexp, sorry for inconvenience. > > > I don't think you can do it in one regex, nor would I want to. Just use > > the string's replace() method. > > > >>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > >>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > >>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > >>> maail = mail.strip() > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > >>> maail = maail.replace(' ', '') > > >>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > >>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > > >>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > >>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > > >>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > This is a good learning exercise demonstrating the impracticality of > regular expressions in a given situation. In the light of the > fascination regular expressions seem to exert in general, one might > conclude that knowing regular expressions in essence is knowing when not > to use them. > > There is nothing wrong with cascading substitutions through multiple > expressions. The OP's solution wrapped up in a function and streamlined > for needless regex overkill might look something like this: > > def translate (s): > ? ?s1 = s.strip () ? ? # Instead of: s1 = re.sub ('^\n|$\n', '', s) > ? ?s2 = s1.replace (' ', '') ? ?# Instead of: s2 = re.sub (' ', '', s1) > ? ?s3 = re.sub ('\[at\]|\[\$at\$\]', '@', s2) > ? ?s4 = re.sub ('\[dot\]|\[\$dot\$\]', '.', s3) > ? ?return s4 > > print translate (mail) ? # Tested > > MRAB's solution using replace () avoids needless regex complexity, but > doesn't simplify tedious coding if the number of substitutions is > significant. Some time ago I proposed a little module I made to > alleviate the tedium. It would handle this case like this: > > import SE > Translator = SE.SE ( ' (32)= [at]=@ [$at$]=@ [dot]=. [$dot$]=. ' ) > print Translator (mail.strip ()) ? # Tested > > So SE.SE compiles a string composed of any number of substitution > definitions into an object that translates anything given it. In a > running speed contest it would surely come in last, although in most > cases the disadvantage would be imperceptible. Another matter is coding > speed. Here the advantage is obvious, even with a set of substitutions > as small as this one, let alone with sets in the tens or even hundreds. > One inconspicuous but significant feature of SE is that it handles > precedence correctly if targets overlap (upstream over downstream and > long over short). As far as I know there's nothing in the Python system > handling substitution precedence. It always needs to be hand-coded from > one case to the next and that isn't exactly trivial. > > SE can be downloaded fromhttp://pypi.python.org/pypi/SE/2.3. > > Frederic Thanks again. :) I saw that MRAB is actively developing new implementation of re module. MRAB: You think it'd be good idea adding to Your project some best features of SE module? I didn't seen yet features of Your re module but will try to find time even today, to see what's going on. Greets From ryniek90 at gmail.com Wed Aug 5 08:21:56 2009 From: ryniek90 at gmail.com (ryniek) Date: Wed, 5 Aug 2009 05:21:56 -0700 (PDT) Subject: How to write replace string for object which will be substituted? [regexp] References: <4A78B425.2010604@gmail.com> <4A78BC68.2020601@mrabarnett.plus.com> Message-ID: On 5 Sie, 13:28, Anthra Norell wrote: > MRAB wrote: > > ryniek90 wrote: > >> Hi. > >> I started learning regexp, and some things goes well, but most of > >> them still not. > > >> I've got problem with some regexp. Better post code here: > > >> " > >> ?>>> import re > >> ?>>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > >> mail [$dot$] com\n' > >> ?>>> mail > >> '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail > >> [$dot$] com\n' > >> ?>>> print mail > > >> n... at mail.com > >> name1 [at] mail [dot] com > >> name2 [$at$] mail [$dot$] com > > >> ?>>> maail = re.sub('^\n|$\n', '', mail) > >> ?>>> print maail > >> n... at mail.com > >> name1 [at] mail [dot] com > >> name2 [$at$] mail [$dot$] com > >> ?>>> maail = re.sub(' ', '', maail) > >> ?>>> print maail > >> n... at mail.com > >> name1[at]mail[dot]com > >> name2[$at$]mail[$dot$]com > >> ?>>> maail = re.sub('\[at\]|\[\$at\$\]', '@', maail) > >> ?>>> print maail > >> n... at mail.com > >> name1 at mail[dot]com > >> name2 at mail[$dot$]com > >> ?>>> maail = re.sub('\[dot\]|\[\$dot\$\]', '.', maail) > >> ?>>> print maail > >> n... at mail.com > >> na... at mail.com > >> na... at mail.com > >> ?>>> #How must i write the replace string to replace all this > >> regexp's with just ONE command, in string 'mail' ? > >> ?>>> maail = re.sub('^\n|$\n| > >> |\[at\]|\[\$at\$\]|\[dot\]|\[\$dot\$\]', *?*, mail) > >> " > > >> How must i write that replace pattern (look at question mark), to > >> maek that substituion work? I didn't saw anything helpful while > >> reading Re doc and HowTo (from Python Doc). I tried with > >> 'MatchObject.group()' but something gone wrong - didn't wrote it right. > >> Is there more user friendly HowTo for Python Re, than this? > > >> I'm new to programming an regexp, sorry for inconvenience. > > > I don't think you can do it in one regex, nor would I want to. Just use > > the string's replace() method. > > > >>> mail = '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] > > mail [$dot$] com\n' > > >>> mail > > '\nn... at mail.com\nname1 [at] mail [dot] com\nname2 [$at$] mail [$dot$] > > com\n' > > >>> print mail > > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > >>> maail = mail.strip() > > n... at mail.com > > name1 [at] mail [dot] com > > name2 [$at$] mail [$dot$] com > > > >>> maail = maail.replace(' ', '') > > >>> print maail > > n... at mail.com > > name1[at]mail[dot]com > > name2[$at$]mail[$dot$]com > > >>> maail = maail.replace('[at]', '@').replace('[$at$]', '@') > > >>> print maail > > n... at mail.com > > name1 at mail[dot]com > > name2 at mail[$dot$]com > > >>> maail = maail.replace('[dot]', '.').replace('[$dot$]', '.') > > >>> print maail > > n... at mail.com > > na... at mail.com > > na... at mail.com > > This is a good learning exercise demonstrating the impracticality of > regular expressions in a given situation. In the light of the > fascination regular expressions seem to exert in general, one might > conclude that knowing regular expressions in essence is knowing when not > to use them. > > There is nothing wrong with cascading substitutions through multiple > expressions. The OP's solution wrapped up in a function and streamlined > for needless regex overkill might look something like this: > > def translate (s): > ? ?s1 = s.strip () ? ? # Instead of: s1 = re.sub ('^\n|$\n', '', s) > ? ?s2 = s1.replace (' ', '') ? ?# Instead of: s2 = re.sub (' ', '', s1) > ? ?s3 = re.sub ('\[at\]|\[\$at\$\]', '@', s2) > ? ?s4 = re.sub ('\[dot\]|\[\$dot\$\]', '.', s3) > ? ?return s4 > > print translate (mail) ? # Tested > > MRAB's solution using replace () avoids needless regex complexity, but > doesn't simplify tedious coding if the number of substitutions is > significant. Some time ago I proposed a little module I made to > alleviate the tedium. It would handle this case like this: > > import SE > Translator = SE.SE ( ' (32)= [at]=@ [$at$]=@ [dot]=. [$dot$]=. ' ) > print Translator (mail.strip ()) ? # Tested > > So SE.SE compiles a string composed of any number of substitution > definitions into an object that translates anything given it. In a > running speed contest it would surely come in last, although in most > cases the disadvantage would be imperceptible. Another matter is coding > speed. Here the advantage is obvious, even with a set of substitutions > as small as this one, let alone with sets in the tens or even hundreds. > One inconspicuous but significant feature of SE is that it handles > precedence correctly if targets overlap (upstream over downstream and > long over short). As far as I know there's nothing in the Python system > handling substitution precedence. It always needs to be hand-coded from > one case to the next and that isn't exactly trivial. > > SE can be downloaded fromhttp://pypi.python.org/pypi/SE/2.3. > > Frederic Thanks again. :) I saw that MRAB is actively developing new implementation of re module. MRAB: You think it'd be good idea adding to Your project some best features of SE module? I didn't seen yet features of Your re module but will try to find time even today, to see what's going on. Greets From piet at cs.uu.nl Wed Aug 5 08:28:15 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 14:28:15 +0200 Subject: Special chars with HTMLParser References: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com> Message-ID: >>>>> Fafounet (F) wrote: >F> Hello, >F> I am parsing a web page with special chars such as é (which >F> stands for ?). >F> I know I can have the unicode character ? from unicode >F> ("\xe9","iso-8859-1") >F> but with those extra characters I don' t know. >F> I tried to implement handle_charref within HTMLParser without success. >F> Furthermore, if I have the data abécd, handle_data will get "ab", >F> handle_charref will get xe9 and then handle_data doesn't have the end >F> of the string ("cd"). The character references indicate Unicode ordinals, not iso-8859-1 characters. In your example it will give the proper character because iso-8859-1 coincides with the first part of the Unicode ordinals, but for character outside of iso-8859-1 it will fail. This should give you an idea: from htmlentitydefs import name2codepoint ... def handle_charref(self, name): if name.startswith('x'): num = int(name[1:], 16) else: num = int(name, 10) print 'char:', repr(unichr(num)) def handle_entityref(self, name): print 'char:', unichr(name2codepoint[name]) If your HTML may be illegal you should add some exception handling. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From Tribulations at Paralleles.invalid Wed Aug 5 08:33:03 2009 From: Tribulations at Paralleles.invalid (TP) Date: Wed, 05 Aug 2009 14:33:03 +0200 Subject: intricated functions: how to share a variable References: <9a937d26-2375-4836-9824-d34d9f92d284@o15g2000yqm.googlegroups.com> Message-ID: Bearophile wrote: > So probably a better solution is to just use the normal function > semantics: you pass them an argument and you take an argument as > return value. Such return value will be the new version of the value > you talk about. Thanks for your answer. Yes, it is better like this. My problem is that I cannot get the return values of the function and affect it to some variable, because the function is called via a "signal-slot" connection of PyQt4, not by an explicit inline function call. For example: ######### def tutu(): def toto(): print a a = 4 print a a=2 # ... # definition of some graphical QPushButton "button" # ... # ... self.connect( button, SIGNAL( "clicked" ), toto ) tutu() ########## Then, as advised Diez, perhaps the best solution is to have "true" global variables by using a class and defining the variable a as a member self.a of the class. By doing like this, a will be known everywhere. Julien -- python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\ 9&1+,\'Z4(55l4('])" "When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong." (first law of AC Clarke) From piet at cs.uu.nl Wed Aug 5 08:34:31 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 14:34:31 +0200 Subject: trouble with complex numbers References: <24821423.post@talk.nabble.com> Message-ID: >>>>> Christian Heimes (CH) wrote: >CH> You can write your own phase() function. This function is mostly correct >CH> unless either the real and/or the imag part is NaN or INF. >CH> from math import atan2 >CH> def phase(z): >CH> z += 1j # convert int, long, float to complex That should be z += 0j >CH> return atan2(z.imag, z.real) -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From kpalamartchouk at gmail.com Wed Aug 5 08:50:04 2009 From: kpalamartchouk at gmail.com (kpal) Date: Wed, 5 Aug 2009 05:50:04 -0700 (PDT) Subject: Datetime with float seconds Message-ID: Hello Everybody, The standard datetime has 1 microsecond granularity. My application needs finer time resolution, preferably float seconds. Is there an alternative to the out-of-the-box datetime? Timezone support is not essential. Thanks, From nick.m.daly at gmail.com Wed Aug 5 08:56:14 2009 From: nick.m.daly at gmail.com (Nick Daly) Date: Wed, 05 Aug 2009 07:56:14 -0500 Subject: The Perils of PyContract (and Generators) Message-ID: <4A79816E.5050106@gmail.com> On Wed, 5 Aug 2009 03:06 pm Nick Daly wrote: > The problem actually lies in the contract. Generally, the PyContract > shouldn't affect the return values or in any way modify the code, which > it doesn't, as long as the function returns a list values (the way the > code had in fact originally been written). However, the contract > mentioned above is actually quite wrong for a generator. Yes, because you are conflating the items yielded from the generator with the generator object returned from the generator function "find_files". You can't look inside the generator object without using up whichever items you look at. [...] > Correcting the above example involves doing nothing more than > simplifying the contract: > > post: > name in __return__ That can't be right, not unless PyContract is doing something I don't expect. I expect that would be equivalent of: 'fish' in which should fail: >>> __return__ = find_files('fish') # a generator object >>> 'fish' in __return__ False >>> >>> __return__ = find_files('fish') >>> __return__ = list(__return__) >>> 'fish' in __return__ False >>> __return__ ['one fish', 'two fish', 'red fish', 'blue fish'] Of course, I may be mistaking what PyContract is doing. ----- No, you're absolutely right, I realized the error in my email moments after sending it, I was just hoping no one was paying enough attention to notice. I'm essentially asking PyContract to operate outside of the generator (it needs to check the return value of a generator, without changing its internal state), which doesn't seem to have an easy solution unless generators have some fantastic reverse_states function that I haven't heard about. I suppose one could be built, saving off the values of all local variables for later restoration, but that would still be dependent on the state of the rest of the machine and could not guarantee giving the same answer twice in a row. So, the moral of the story seems to be that PyContract's post-return value checking doesn't mix with generators at all. Sort of sad, because they're two neat flavors that would go great together but are instead technically incompatible. A decent set of unit-tests would accomplish the same thing much less destructively anyway. Nick From fafounet at gmail.com Wed Aug 5 09:03:46 2009 From: fafounet at gmail.com (Fafounet) Date: Wed, 5 Aug 2009 06:03:46 -0700 (PDT) Subject: Special chars with HTMLParser References: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com> Message-ID: <69835fa3-c6a0-44d3-bba2-5e3117102590@k30g2000yqf.googlegroups.com> Thank you, now I can get the correct character. Now when I have the string abécd I can get ab then ? thanks to your function and then cd. But how is it possible to know that cd is still the same word ? Fabien > The character references indicate Unicode ordinals, not iso-8859-1 > characters. In your example it will give the proper character because > iso-8859-1 coincides with the first part of the Unicode ordinals, but > for character outside of iso-8859-1 it will fail. > > This should give you an idea: > > from htmlentitydefs import name2codepoint > ... > ? ? def handle_charref(self, name): > ? ? ? ? if name.startswith('x'): > ? ? ? ? ? ? num = int(name[1:], 16) > ? ? ? ? else: > ? ? ? ? ? ? num = int(name, 10) > ? ? ? ? print 'char:', repr(unichr(num)) > > ? ? def handle_entityref(self, name): > ? ? ? ? print 'char:', unichr(name2codepoint[name]) > > If your HTML may be illegal you should add some exception handling. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org From contact at xavierho.com Wed Aug 5 09:15:53 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 5 Aug 2009 23:15:53 +1000 Subject: Datetime with float seconds In-Reply-To: References: Message-ID: <2d56febf0908050615i1d8f5137v3295c1ab574067c5@mail.gmail.com> On Wed, Aug 5, 2009 at 10:50 PM, kpal wrote: > Hello Everybody, > > The standard datetime has 1 microsecond granularity. My application > needs finer time resolution, preferably float seconds. Is there an > alternative to the out-of-the-box datetime? Timezone support is not > essential. This is a little outdated, but: >>>from time import time Usually gets me things like #output Run time: 0.0279998779297 seconds. So... that might be what you want. - Xavier -------------- next part -------------- An HTML attachment was scrubbed... URL: From wuwei23 at gmail.com Wed Aug 5 09:35:19 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Aug 2009 06:35:19 -0700 (PDT) Subject: intricated functions: how to share a variable References: <9a937d26-2375-4836-9824-d34d9f92d284@o15g2000yqm.googlegroups.com> Message-ID: TP wrote: > Then, as advised Diez, perhaps the best solution is to have "true" global > variables by using a class and defining the variable a as a member self.a > of the class. By doing like this, a will be known everywhere. Or, as Bearophile suggested, you could use the standard way of passing arguments into a function: >>> def tutu(): ... a = 2 ... def toto(a=a): ... print 'toto', a ... a = 4 ... print 'toto', a ... print 'tutu', a ... toto() ... print 'tutu', a ... >>> tutu() tutu 2 toto 2 toto 4 tutu 2 You could also just do 'toto(a)', but as you're trying to create a closure here, binding the external scope 'a' to toto via the default argument will (probably) do what you need. From jnoller at gmail.com Wed Aug 5 09:40:57 2009 From: jnoller at gmail.com (Jesse Noller) Date: Wed, 5 Aug 2009 06:40:57 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> Message-ID: <74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> On Aug 5, 1:21?am, sturlamolden wrote: > On Aug 5, 4:37 am, erikcw wrote: > > > It's not always the same traceback, but they are always short like > > this. ?I'm running Python 2.6.2 on Ubuntu 9.04. > > > Any idea how I can debug this? > > In my experience,multiprocessingis fragile. Scripts tend fo fail for > no obvious reason, case processes to be orphaned and linger, system- > wide resource leaks, etc. For example,multiprocessinguses os._exit > to stop a spawned process, even though it inevitably results in > resource leaks on Linux (it should use sys.exit). Ga?l Varoquaux and I > noticed this when we implemented shared memory ndarrays for numpy; we > consistently got memory leaks with System V IPC for no obvious reason. > Even after Jesse Noller was informed of the problem (about half a year > ago), the bug still lingers. It is easy editmultiprocessing's > forking.py file on you own, but bugs like this is a pain in the ass, > and I suspectmultiprocessinghas many of them. Of course unless you > show us you whole script, identifying the source of your bug will be > impossible. But it may very likely be inmultiprocessingas well. The > quality of this module is not impressing. I am beginning to think thatmultiprocessingshould never have made it into the Python standard > library. The GIL cannot be that bad! If you can't stand the GIL, get a > Unix (or Mac, Linux, Cygwin) and use os.fork. Or simply switch to a > non-GIL Python: IronPython or Jython. > > Allow me to show you something better. With os.fork we can write code > like this: > > class parallel(object): > > ? ?def __enter__(self): > ? ? ? ?# call os.fork > > ? ?def __exit__(self, exc_type, exc_value, traceback): > ? ? ? ?# call sys.exit in the child processes and > ? ? ? ?# os.waitpid in the parent > > ? ?def __call__(self, iterable): > ? ? ? ?# return different sub-subsequences depending on > ? ? ? ?# child or parent status > > with parallel() as p: > ? ? # parallel block starts here > > ? ? for item in p(iterable): > ? ? ? ? # whatever > > ? ? # parallel block ends here > > This makes parallel code a lot cleaner than anything you can do withmultiprocessing, allowing you to use constructs similar to OpenMP. > Further, if you make 'parallel' a dummy context manager, you can > develop and test the algorithms serially. The only drawback is that > you have to use Cygwin to get os.fork on Windows, and forking will be > less efficient (no copy-on-write optimization). Well, this is just one > example of why Windows sucks from the perspective of the programmer. > But it also shows that you can do much better by notusingmultiprocessingat all. > > The only case I can think of wheremultiprocessingwould be usesful, > is I/O bound code on Windows. But here you will almost always resort > to C extension modules. For I/O bound code, Python tends to give you a > 200x speed penalty over C. If you are resorting to C anyway, you can > just use OpenMP in C for your parallel processing. We can thus forget > aboutmultiprocessinghere as well, given that we have access to the C > code. If we don't, it is still very likely that the C code releases > the GIL, and we can get away withusingPython threads instead ofmultiprocessing. > > IMHO, if you areusingmultiprocessing, you are very likely to have a > design problem. > > Regards, > Sturla Sturla; That bug was fixed unless I'm missing something. Also, patches and continued bug reports are welcome. jesse From wuwei23 at gmail.com Wed Aug 5 09:41:56 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Aug 2009 06:41:56 -0700 (PDT) Subject: trouble with complex numbers References: <24821423.post@talk.nabble.com> Message-ID: Piet van Oostrum wrote: > That should be z += 0j Pardon my ignorance, but could anyone explain the rationale behind using 'j' to indicate the imaginary number (as opposed to the more intuitive 'i')? (Not that I've had much call to use complex numbers but I'm curious....) From jjposner at optimum.net Wed Aug 5 09:46:16 2009 From: jjposner at optimum.net (John Posner) Date: Wed, 05 Aug 2009 09:46:16 -0400 Subject: Announcing PythonTurtle In-Reply-To: References: Message-ID: <4A798D28.5060004@optimum.net> >> OK, then why the statements "from turtle import *" in the modules >> turtleprocess.py and turtlewidget.py? >> Yes, I see that now (he said meekly, too sheepish to complain about being misled by an unfortunate naming choice). Tx, John From casevh at gmail.com Wed Aug 5 09:50:17 2009 From: casevh at gmail.com (casevh) Date: Wed, 5 Aug 2009 06:50:17 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: <5a4ab236-4cbf-4895-935a-5fdc712f0d08@u38g2000pro.googlegroups.com> On Aug 5, 12:19?am, Steven D'Aprano wrote: > On Wed, 5 Aug 2009 03:49 pm Mensanator wrote: > > > In 3.1, tracing is now a screen attribute, not a turtle atribute. > > I have no idea why > > > ? tooter = turtle.Turtle() > > ? tooter.tracer(False) > > > doesn't give me an error (I thought silent errors were a bad thing). > > What makes it an error? Do you consider the following an error? > > >>> class Test: > > ... ? ? pass > ... > > >>> t = Test() > >>> t.tracer = 5 > > Perhaps you mean, it's an API change you didn't know about, and you wish to > protest that Turtle Graphics made an incompatible API change without > telling you? > > > Naturally, having tracing on caused my program to crash. > > It seg faulted or raised an exception? > > [...] > > > Unfortunately, that calculation of nhops is illegal if diffsq is > > an .mpf (gmpy floating point). Otherwise, you get > > How does diffsq get to be a mpf? Are gmpy floats supposed to be supported? > > -- > Steven The root cause of the error is that GMP, the underlying library for gmpy, provides only the basic floating point operations. gmpy implements a very limited exponentiation function. Python's math library will convert an mpf to a float automatically so I think the revised calculation for nhops should work with either any numerical type that supports __float__. casevh From hendrik at microcorp.co.za Wed Aug 5 10:29:39 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 5 Aug 2009 16:29:39 +0200 Subject: Using Python to automate builds In-Reply-To: <5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <200908050956.33995.hendrik@microcorp.co.za> <5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> Message-ID: <200908051629.39417.hendrik@microcorp.co.za> On Wednesday 05 August 2009 14:08:18 David Cournapeau wrote: > On Wed, Aug 5, 2009 at 4:56 PM, Hendrik van > > Rooyen wrote: > > On Tuesday 04 August 2009 21:13:10 Kosta wrote: > >> I am a Python newbie, tasked with automating (researching) building > >> Windows drivers using the WDK build environment. ?I've been looking > >> into Python for this (instead of writing a bunch of batch files). > > > > Why do you not use make and a makefile - it was designed to > > do exactly this. > > Because make is a pain on windows (lack of a proper shell) ? Well, you could always use Dosbox - I am doing exactly that on Linux to be able to run some old DOS based assembler tools. It will run on windows too, they claim. And it is very simple to use too - no fancy fidgeting, all you have to do is to point it at a directory that becomes your "C" drive. Bit slow - but hey, nobody's perfect. - Hendrik From contact at xavierho.com Wed Aug 5 10:32:15 2009 From: contact at xavierho.com (Xavier Ho) Date: Thu, 6 Aug 2009 00:32:15 +1000 Subject: Subclassing Python's dict In-Reply-To: References: Message-ID: <2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com> On Thu, Aug 6, 2009 at 11:51 AM, Sergey Simonenko wrote: > I subclass builtin 'dict' in my application and experience some problems > with it. > You should subclass collections.UserDict, and not the default dict class. Refer to the collections module. Also, the ABC MutableMapping might be of your interest. > Another guy have reported me that he experiences similar problems with > subclassing builtin 'list'. Similarly, UserList is what you should subclass. HTH, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From joncle at googlemail.com Wed Aug 5 10:32:37 2009 From: joncle at googlemail.com (Jon Clements) Date: Wed, 5 Aug 2009 07:32:37 -0700 (PDT) Subject: Do anyone here use Python *embedded* in a database? References: Message-ID: <767b6862-065f-480a-82f5-ed3aa35bf84d@n11g2000yqb.googlegroups.com> On 5 Aug, 13:17, Jonathan Fine wrote: > Hi > > I'm writing a talk that compares embed and extend, and wondered if > anyone here ever used the Python *embedded* in a database server. > ? ? ?http://twistedmatrix.com/users/glyph/rant/extendit.html > > Web frameworks (such as Django) use extend, to import an extension > module that makes a connection to a database. > > If you have used embed, you might have consulted a page such as: > ? ? ?http://www.postgresql.org/docs/8.3/interactive/plpython-funcs.html > > -- > Jonathan Yup, have used plpythonu within postgres without too many problems. Although I do recall once that using the CSV module to load and filter external data, did consume a massive amount of memory. Even though the entire procedure was iterator based -- never did work out if it was postgres caching, or some other weird stuff. [That was about 2 years ago though] Jon. From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 5 10:39:52 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 05 Aug 2009 16:39:52 +0200 Subject: Subclassing Python's dict In-Reply-To: References: Message-ID: <4a7999b1$0$306$426a74cc@news.free.fr> Sergey Simonenko a ?crit : > Hi, > > I subclass builtin 'dict' in my application and experience some problems > with it. > > The whole issue is that I should redefine 'setdefault' and 'update' > methods after redefining '__setitem__' or/and '__delitem__', > otherwise 'update' and 'setdefault' ignore redefined '__setitem__' and > use builtin dict's one so dict looks kinda like a black box. > > Another guy have reported me that he experiences similar problems with > subclassing builtin 'list'. I indeed notice this behaviour here (Python 2.6.2). I'm afraid it has to do with some optimization tricks (dict being the very fundamental data structure in Python, it has to be higly optimized). From af1ing at seznam.cz Wed Aug 5 10:41:05 2009 From: af1ing at seznam.cz (Rog) Date: Wed, 5 Aug 2009 07:41:05 -0700 (PDT) Subject: http access produces 503 Message-ID: <3b5ab07c-7b0b-4d23-965b-192dc86cf6ff@a26g2000yqn.googlegroups.com> I am porting a simple code from Perl, the website asks for usr/pwd and the server's side Perl script makes atemp ftp dir for file upload. The original Perl script connects okay, does its job. The same URL stuffed into FF3 performs the same way. My Python script I am sweating out for past four days (noob!) gets consistently "503", even with user agen set to: Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11. Snippets of relevant code below. Please, help me understand how this same code lets me log in into my router usr/pwd running .asp, but this !@#$% perl script returns to me w/503 c*ap? Thank you. Do I need to set any proxy? The server is on intranet and the FF3 is set to proxy. The original Perl script did not use any proxy setting.


url = http://example.com/ftpsetup.pl?username=boofa&nodeid=42
#########################################################
# create a password manager
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
    password_mgr.add_password(None, url, uid, pcode)
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
    class Mopener(URLopener): version = "Mozilla/5.0 (Windows; U;
Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

    opener = Mopener()

# create "opener" (OpenerDirector instance)

    opener = urllib2.build_opener(handler)
    opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U;
Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11')]

    opener.version = "Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:
1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

    print opener.version
# timeout in seconds
    timeout = 10
    socket.setdefaulttimeout(timeout)

# Install the opener all calls to urllib2.urlopen use our opener.
    urllib2.install_opener(opener)

    try:
        response = opener.open(url)
        # "http://www.useragent.org/" tested okay!!!
        print"ok = 1"
    except:
        print "error 1"
#####################################################################################

output from the above:

Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/
20071127 Firefox/2.0.0.11
error 1
Error code:  503
('Service Unavailable', 'The server cannot process the request due to
a high load')
From michael at stroeder.com Wed Aug 5 10:43:09 2009 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 05 Aug 2009 16:43:09 +0200 Subject: unicode() vs. s.decode() Message-ID: HI! These both expressions are equivalent but which is faster or should be used for any reason? u = unicode(s,'utf-8') u = s.decode('utf-8') # looks nicer Ciao, Michael. From martin.hellwig at dcuktec.org Wed Aug 5 10:46:13 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 Aug 2009 15:46:13 +0100 Subject: Parsing Binary Structures; Is there a better way / What is your way? Message-ID: Hi List, On several occasions I have needed (and build) a parser that reads a binary piece of data with custom structure. For example (bogus one): BE +---------+---------+-------------+-------------+------+--------+ | Version | Command | Instruction | Data Length | Data | Filler | +---------+---------+-------------+-------------+------+--------+ Version: 6 bits Command: 4 bits Instruction: 5 bits Data Length: 5 bits Data: 0-31 bits Filler: filling 0 bits to make the packet dividable by 8 what I usually do is read the packet in binary mode, convert the output to a concatenated 'binary string'(i.e. '0101011000110') and then use slice indeces to get the right data portions. Depending on what I need to do with these portions I convert them to whatever is handy (usually an integer). This works out fine for me. Most of the time I also put the ASCII art diagram of this 'protocol' as a comment in the code, making it more readable/understandable. Though there are a couple of things that bothers me with my approach: - This seems such a general problem that I think that there must be already a general pythonic solution. - Using a string for binary representation takes at least 8 times more memory for the packet than strictly necessary. - Seems to need a lot of prep work before doing the actual parsing. Any suggestion is greatly appreciated. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From dp_pearce at hotmail.com Wed Aug 5 10:51:44 2009 From: dp_pearce at hotmail.com (dp_pearce) Date: Wed, 5 Aug 2009 07:51:44 -0700 (PDT) Subject: Is it possible to produce spider plots? Message-ID: I want to be able to use Python to produce Spider plots (perhaps you know them as radar plots or star plots). Does anyone know how to achieve this? Are there existing libraries? Direction to any examples, especially those with tutorials, would be greatly appreciated. Cheers, Dan http://www.answers.com/topic/spider-plot From pruebauno at latinmail.com Wed Aug 5 10:56:35 2009 From: pruebauno at latinmail.com (nn) Date: Wed, 5 Aug 2009 07:56:35 -0700 (PDT) Subject: Overlap in python References: <4A78B19D.4020306@mrabarnett.plus.com> Message-ID: <4c9f81a5-51b9-4487-9df9-d458b327d286@s15g2000yqs.googlegroups.com> On Aug 5, 7:13?am, Marcus Wanner wrote: > On 8/4/2009 6:09 PM, MRAB wrote: > > > ?>>> parts = [(5, 9, "a"), (7, 10, "b"), (3, 6, "c"), (15, 20, "d"), > > (18, 23, "e")] > > ?>>> parts.sort() > > ?>>> parts > > [(3, 6, 'c'), (5, 9, 'a'), (7, 10, 'b'), (15, 20, 'd'), (18, 23, 'e')] > > ?>>> # Merge overlapping intervals. > > ?>>> pos = 1 > > ?>>> while pos < len(parts): > > ? ? ? ? # Merge the pair in parts[pos - 1 : pos + 1] if they overlap. > > ? ? ? ? p, q = parts[pos - 1 : pos + 1] > > ? ? ? ? if p[1] >= q[0]: > > ? ? ? ? ? ? ? ? parts[pos - 1 : pos + 1] = [(p[0], max(p[1], q[1]), p[2] > > + "." + q[2])] > > ? ? ? ? else: > > ? ? ? ? ? ? ? ? # They don't overlap, so try the next pair. > > ? ? ? ? ? ? ? ? pos += 1 > > > ?>>> parts > > [(3, 10, 'c.a.b'), (15, 23, 'd.e')] > > That's the best solution I've seen so far. It even has input/output > formatted as close as is reasonably possible to the format specified. > > As we would say in googlecode, +1. > > Marcus How does it compare to this one? http://groups.google.com/group/comp.lang.python/browse_frm/thread/1a1d2ed9d05d11d0/56684b795fc527cc#56684b795fc527cc From roger_lynx at yahoo.com Wed Aug 5 11:05:38 2009 From: roger_lynx at yahoo.com (roger_lynx) Date: Wed, 05 Aug 2009 15:05:38 -0000 Subject: web access yields "503" Message-ID: Hi, I am porting a simple code from Perl, the website asks for usr/pwd and the server's side Perl script makes a temp ftp dir for a file upload. The original Perl script connects okay, does its job. The same URL stuffed into FF3 performs the same way. My Python script I am sweating over for past four days (noob!) gets consistently "503", even with user agent set to: Mozilla/5.0 (Windows;U; Windows NT 5.1; it; rv:1.8.1.11)Gecko/20071127 Firefox/2.0.0.11. Snippets of relevant code below, heavily copied from this author: http://www.voidspace.org.uk/python/articles/urllib2.shtml Please, help me understand how this same code lets me log in into my router usr/pwd running .asp, but this !@#$% perl script returns to me w/503 c*ap? Thank you. Do I need to set any proxy? The server is on intranet and the FF3 is set to proxy. The original Perl script did not use any proxy setting! LWP::

url = http://bad_example.com/ftpsetup.pl?username=boofa&nodeid=42
#########################################################
# create a password manager
    password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
    password_mgr.add_password(None, url, uid, pcode)
    handler = urllib2.HTTPBasicAuthHandler(password_mgr)
    class Mopener(URLopener): version = "Mozilla/5.0 (Windows; U;
Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

    opener = Mopener()

# create "opener" (OpenerDirector instance)

    opener = urllib2.build_opener(handler)
    opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U;
Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11')]

    opener.version = "Mozilla/5.0 (Windows; U; 
Windows NT 5.1; it; rv:
1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

    print opener.version
# timeout in seconds
    timeout = 10
    socket.setdefaulttimeout(timeout)

# Install the opener all calls to urllib2.urlopen use our opener.
    urllib2.install_opener(opener)

    try:
        response = opener.open(url)
        # "http://www.useragent.org/" tested okay!!!
        print"ok = 1"
    except:
        print "error 1"
#####################################################################################

output from the above:

Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/
20071127 Firefox/2.0.0.11
error 1
Error code: 503
('Service Unavailable', 'The server cannot process the request due to
a high load')
From Scott.Daniels at Acm.Org Wed Aug 5 11:12:48 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 05 Aug 2009 08:12:48 -0700 Subject: Overlap in python In-Reply-To: References: Message-ID: Jay Bird wrote: > Hi everyone, > > I've been trying to figure out a simple algorithm on how to combine a > list of parts that have 1D locations that overlap into a non- > overlapping list. For example, here would be my input: > > part name location > a 5-9 > b 7-10 > c 3-6 > d 15-20 > e 18-23 > > And here is what I need for an output: > part name location > c.a.b 3-10 > d.e 15-23 > > I've tried various methods, which all fail. Does anyone have an idea > how to do this? > > Thank you very much! > Jay I once had to do this for finding nested block structure. The key for me was a sort order: start, -final. Having not seen it here (though I looked a bit), here's one: class Entry(object): '''An entry is a name and range''' def __init__(self, line): self.name, startstop = line.split() start, stop = startstop.split('-') self.start, self.stop = int(start), int(stop) def combined_ranges(lines): '''Create Entries in "magic order", and produce ranges. The "magic order" makes least element with longest range first, so overlaps show up in head order, with final tail first among equals. ''' # Fill in our table (ignoring blank lines), then sort by magic order elements = [Entry(line) for line in lines if line.strip()] elements.sort(key=lambda e: (e.start, -e.stop)) # Now produce resolved ranges. Grab the start gen = iter(elements) first = gen.next() # For the remainder, combine or produce for v in gen: if v.start <= first.stop: # on overlap, merge in new element (may update stop) first.name += '.' + v.name if first.stop < v.stop: first.stop = v.stop else: yield first first = v # And now produce the last element we covered yield first # Demo: sample = '''part name location a 5-9 b 7-10 c 3-6 d 15-20 e 18-23 ''' source = iter(sample.split('\n')) # source of lines, opened file? ignored = source.next() # discard heading for interval in combined_range(source): print '%s %s-%s' % (interval.name, interval.start, interval.stop) Prints: c.a.b 3-10 d.e 15-23 --Scott David Daniels Scott.Daniels at Acm.Org From wuwei23 at gmail.com Wed Aug 5 11:17:34 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 5 Aug 2009 08:17:34 -0700 (PDT) Subject: trouble with complex numbers References: <24821423.post@talk.nabble.com> Message-ID: <37b97967-ec2e-4c37-a4b9-46e56a6de7bd@p36g2000prn.googlegroups.com> On Aug 6, 1:18?am, Scott David Daniels wrote: > I think it explained in the complex math area, but basically EE types > use j, math types use i for exactly the same thing. ?Since i is so > frequently and index in CS, and there is another strong convention, > why not let the EE types win? That 'i' tends to be used as index did occur to me, I just wasn't aware of what conventions were used in other contexts. Thanks, Scott, much appreciated. From rustompmody at gmail.com Wed Aug 5 11:18:05 2009 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 5 Aug 2009 20:48:05 +0530 Subject: error return from urlopen Message-ID: When I direct urlopen to a non-existent server process I get IOError: [Errno socket error] (10061, 'Connection refused') The connection refused is as expected but whats the 10061? strerror(10061) says 'unknown error' So its like an errno but not quite an errno? Can I find out more about this number like I can about errno? From Scott.Daniels at Acm.Org Wed Aug 5 11:18:55 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Wed, 05 Aug 2009 08:18:55 -0700 Subject: trouble with complex numbers In-Reply-To: References: <24821423.post@talk.nabble.com> Message-ID: alex23 wrote: > Piet van Oostrum wrote: >> That should be z += 0j > > Pardon my ignorance, but could anyone explain the rationale behind > using 'j' to indicate the imaginary number (as opposed to the more > intuitive 'i')? > > (Not that I've had much call to use complex numbers but I'm > curious....) I think it explained in the complex math area, but basically EE types use j, math types use i for exactly the same thing. Since i is so frequently and index in CS, and there is another strong convention, why not let the EE types win? --Scott David Daniels Scott.Daniels at Acm.Org From robin at reportlab.com Wed Aug 5 11:18:55 2009 From: robin at reportlab.com (Robin Becker) Date: Wed, 05 Aug 2009 16:18:55 +0100 Subject: Is it possible to produce spider plots? In-Reply-To: References: Message-ID: <4A79A2DF.5010908@chamonix.reportlab.co.uk> dp_pearce wrote: > I want to be able to use Python to produce Spider plots (perhaps you > know them as radar plots or star plots). Does anyone know how to > achieve this? Are there existing libraries? > > Direction to any examples, especially those with tutorials, would be > greatly appreciated. > > Cheers, ...... reportlab has a spider chart in reportlab/graphics/charts/spider.py -- Robin Becker From marduk at letterboxes.org Wed Aug 5 11:28:22 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Wed, 05 Aug 2009 11:28:22 -0400 Subject: error return from urlopen In-Reply-To: References: Message-ID: <1249486102.23428.3.camel@brotherus.corp.redhat.com> On Wed, 2009-08-05 at 20:48 +0530, Rustom Mody wrote: > When I direct urlopen to a non-existent server process I get > > IOError: [Errno socket error] (10061, 'Connection refused') > The connection refused is as expected but whats the 10061? > strerror(10061) says 'unknown error' > > So its like an errno but not quite an errno? > Can I find out more about this number like I can about errno? http://msdn.microsoft.com/en-us/library/ms740668(VS.85).aspx From tim.arnold at sas.com Wed Aug 5 11:30:07 2009 From: tim.arnold at sas.com (Tim Arnold) Date: Wed, 5 Aug 2009 11:30:07 -0400 Subject: oNVDL validation docbook 5 Message-ID: Hi, I'm using the oNVDL java validator for my DocBook 5.0 documents. Otherwise, my doc system is python. I wonder if there is any work going on (or perhaps something I'm missing) to use python to validate DocBook 5 (using the rng files bundled with the DocBook5 distribution) I think the catch with DocBook 5 rng is that it has embedded Schematron rules, which makes lxml not able to validate. I'm out of my depth here, but that's what I've heard. Anyway, I'd sure like to streamline this using python rather than a subprocess call out to that java validator. Any suggestions or pointers welcome. thanks, --Tim Arnold From jkn_gg at nicorp.f9.co.uk Wed Aug 5 11:33:48 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Wed, 5 Aug 2009 08:33:48 -0700 (PDT) Subject: Is it possible to produce spider plots? References: Message-ID: On Aug 5, 3:51?pm, dp_pearce wrote: > I want to be able to use Python to produce Spider plots (perhaps you > know them as radar plots or star plots). Does anyone know how to > achieve this? Are there existing libraries? > The 'wxPython in Action' book has some simple example code which produces this sort of graphic. If you are after a GUI application rather than creating a paper copy it might be worth checking this out. HTH J^n From tack at urandom.ca Wed Aug 5 11:38:13 2009 From: tack at urandom.ca (Jason Tackaberry) Date: Wed, 05 Aug 2009 11:38:13 -0400 Subject: intricated functions: how to share a variable In-Reply-To: <7dt5rqF2crv46U1@mid.uni-berlin.de> References: <7dt5rqF2crv46U1@mid.uni-berlin.de> Message-ID: <1249486693.7120.789.camel@arrakis> On Wed, 2009-08-05 at 12:39 +0200, Diez B. Roggisch wrote: > Another often used trick is to have a mutable container-object, like this: > > def tutu(): > a = [2] > > def toto(): > a[0] = 4 > > toto() When you need a writable bound variable inside a closure, I prefer this idiom: def foo(): def bar(): print bar.a bar.a = 4 print bar.a bar.a = 2 bar() Python 3's nonlocal is obviously much more elegant. Cheers, Jason. From joncle at googlemail.com Wed Aug 5 11:39:07 2009 From: joncle at googlemail.com (Jon Clements) Date: Wed, 5 Aug 2009 08:39:07 -0700 (PDT) Subject: Parsing Binary Structures; Is there a better way / What is your way? References: Message-ID: <9bca27b8-e71d-4b71-a792-d9ca7be18ab3@24g2000yqm.googlegroups.com> On 5 Aug, 15:46, "Martin P. Hellwig" wrote: > Hi List, > > On several occasions I have needed (and build) a parser that reads a > binary piece of data with custom structure. For example (bogus one): > > BE > +---------+---------+-------------+-------------+------+--------+ > | Version | Command | Instruction | Data Length | Data | Filler | > +---------+---------+-------------+-------------+------+--------+ > Version: 6 bits > Command: 4 bits > Instruction: 5 bits > Data Length: 5 bits > Data: 0-31 bits > Filler: filling 0 bits to make the packet dividable by 8 > > what I usually do is read the packet in binary mode, convert the output > to a concatenated 'binary string'(i.e. '0101011000110') and then use > slice indeces to get the right data portions. > Depending on what I need to do with these portions I convert them to > whatever is handy (usually an integer). > > This works out fine for me. Most of the time I also put the ASCII art > diagram of this 'protocol' as a comment in the code, making it more > readable/understandable. > > Though there are a couple of things that bothers me with my approach: > - This seems such a general problem that I think that there must be > already a general pythonic solution. > - Using a string for binary representation takes at least 8 times more > memory for the packet than strictly necessary. > - Seems to need a lot of prep work before doing the actual parsing. > > Any suggestion is greatly appreciated. > > -- > MPHhttp://blog.dcuktec.com > 'If consumed, best digested with added seasoning to own preference.' IIRC (and I have my doubts) the BitVector module may be of use, but it's been about 3 years since I had to look at it. I think it used the C equiv. of short ints to do its work. Otherwise, maybe the array module, the struct module or even possibly ctypes. Not much use, but might give a few pointers. Jon. From kosta.koeman at gmail.com Wed Aug 5 11:39:15 2009 From: kosta.koeman at gmail.com (Kosta) Date: Wed, 5 Aug 2009 08:39:15 -0700 (PDT) Subject: Using Python to automate builds References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> <200908050956.33995.hendrik@microcorp.co.za> <5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> Message-ID: On Aug 5, 7:29?am, Hendrik van Rooyen wrote: > On Wednesday 05 August 2009 14:08:18 David Cournapeau wrote: > > > On Wed, Aug 5, 2009 at 4:56 PM, Hendrik van > > > Rooyen wrote: > > > On Tuesday 04 August 2009 21:13:10 Kosta wrote: > > >> I am a Python newbie, tasked with automating (researching) building > > >> Windows drivers using the WDK build environment. ?I've been looking > > >> into Python for this (instead of writing a bunch of batch files). > > > > Why do you not use make and a makefile - it was designed to > > > do exactly this. > > > Because make is a pain on windows (lack of a proper shell) ? > > Well, you could always use Dosbox - I am doing exactly that > on Linux to be able to run some old DOS based assembler > tools. ?It will run on windows too, they claim. > > And it is very simple to use too - no fancy fidgeting, all you have > to do is to point it at a directory that becomes your "C" drive. > > Bit slow - but hey, nobody's perfect. > > - Hendrik Sorry for not being more clear. The WDK provides build.exe, a utility that calls the compiler & linker with the approprite switches. In essence, it manages all the nmake details away from the developer. For some, this is a bad thing in terms of loss of control. But in reality, this is a great thing, as this is the way Microsoft builds Windows. As far as I can tell, the WDK build environment is dervied from the Microsoft Windows build environment, which is great for developing kernel components in the similar enviornment in which Microsoft builds its OS. It is a requirement to use the WDK. Setenv.bat sets up the path and other environment variables build.exe needs to compile and link (and even binplace) its utilities. So building itself is not the issue. The problem is that if I call setenv.bat from Python and then build.exe, but the modifications to the path (and other environment settings) are not seen by Python, so the attempt to build without a specified path fails. Now I can open up a build window that targets a build type (check or release), an architecture target (x86 or x64) and an OS target (which will be Windows Xp except if in the future, the driver(s) uses some infrastructure introduced in later versions of WDM. However, what I was hoping to do was to have a python script that would allow me to build 4 versions of the driver: x86 check, x86 release, x64 check, and x64 release. I may have to resort to using batch files, but I was hoping as much as possible to use Python. Thanks, Kosta From breamoreboy at yahoo.co.uk Wed Aug 5 11:52:08 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 05 Aug 2009 16:52:08 +0100 Subject: Overlap in python In-Reply-To: References: <4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> Message-ID: Jay Bird wrote: > Hi everyone, > > I wanted to thank you all for your help and *excellent* discussion. I > was able to utilize and embed the script by Grigor Lingl in the 6th > post of this discussion to get my program to work very quickly (I had > to do about 20 comparisons per data bin, with over 40K bins in > total). I am involved in genomic analysis research and this problem > comes up a lot and I was surprised to not have been able to find a > clear way to solve it. I will also look through all the tips in this > thread, I have a feeling they may come in handy for future use! > > Thank you again, > Jay I don't know if this is relevant, but http://planet.python.org/ has an entry dated this morning which points here http://www.logarithmic.net/pfh/blog/01249470842. HTH. -- Kindest regards. Mark Lawrence. From tack at urandom.ca Wed Aug 5 11:53:56 2009 From: tack at urandom.ca (Jason Tackaberry) Date: Wed, 05 Aug 2009 11:53:56 -0400 Subject: unicode() vs. s.decode() In-Reply-To: References: Message-ID: <1249487636.7120.798.camel@arrakis> On Wed, 2009-08-05 at 16:43 +0200, Michael Str?der wrote: > These both expressions are equivalent but which is faster or should be used > for any reason? > > u = unicode(s,'utf-8') > > u = s.decode('utf-8') # looks nicer It is sometimes non-obvious which constructs are faster than others in Python. I also regularly have these questions, but it's pretty easy to run quick (albeit naive) benchmarks to see. The first thing to try is to have a look at the bytecode for each: >>> import dis >>> dis.dis(lambda s: s.decode('utf-8')) 1 0 LOAD_FAST 0 (s) 3 LOAD_ATTR 0 (decode) 6 LOAD_CONST 0 ('utf-8') 9 CALL_FUNCTION 1 12 RETURN_VALUE >>> dis.dis(lambda s: unicode(s, 'utf-8')) 1 0 LOAD_GLOBAL 0 (unicode) 3 LOAD_FAST 0 (s) 6 LOAD_CONST 0 ('utf-8') 9 CALL_FUNCTION 2 12 RETURN_VALUE The presence of LOAD_ATTR in the first form hints that this is probably going to be slower. Next, actually try it: >>> import timeit >>> timeit.timeit('"foobarbaz".decode("utf-8")') 1.698289155960083 >>> timeit.timeit('unicode("foobarbaz", "utf-8")') 0.53305888175964355 So indeed, uncode(s, 'utf-8') is faster by a fair margin. On the other hand, unless you need to do this in a tight loop several tens of thousands of times, I'd prefer the slower form s.decode('utf-8') because it's, as you pointed out, cleaner and more readable code. Cheers, Jason. From J.Fine at open.ac.uk Wed Aug 5 12:03:13 2009 From: J.Fine at open.ac.uk (Jonathan Fine) Date: Wed, 05 Aug 2009 17:03:13 +0100 Subject: Do anyone here use Python *embedded* in a database? In-Reply-To: <767b6862-065f-480a-82f5-ed3aa35bf84d@n11g2000yqb.googlegroups.com> References: <767b6862-065f-480a-82f5-ed3aa35bf84d@n11g2000yqb.googlegroups.com> Message-ID: Jon Clements wrote: > On 5 Aug, 13:17, Jonathan Fine wrote: >> Hi >> >> I'm writing a talk that compares embed and extend, and wondered if >> anyone here ever used the Python *embedded* in a database server. >> http://twistedmatrix.com/users/glyph/rant/extendit.html >> >> Web frameworks (such as Django) use extend, to import an extension >> module that makes a connection to a database. >> >> If you have used embed, you might have consulted a page such as: >> http://www.postgresql.org/docs/8.3/interactive/plpython-funcs.html >> >> -- >> Jonathan > > Yup, have used plpythonu within postgres without too many problems. > Although I do recall once that using the CSV module to load and filter > external data, did consume a massive amount of memory. Even though the > entire procedure was iterator based -- never did work out if it was > postgres caching, or some other weird stuff. [That was about 2 years > ago though] Thanks, Jon, for that. -- Jonathan From lawrencew00 at hotmail.com Wed Aug 5 12:07:39 2009 From: lawrencew00 at hotmail.com (Lawrence Wong) Date: Wed, 5 Aug 2009 16:07:39 +0000 Subject: os.system in a service Message-ID: Hi, I wrote a program which runs a .bat file using os.system like: 'os.system(pathToBatFile)' and everything was good. Then I decided to turn my program into a service as opposed to being run with the command prompt showing. When my program became a service, I noticed that the os.system command to run my .bat file was no longer working. By 'not working' I mean no exception is thrown, but it was as if the line with os.system(pathToBatFile) did not exist. I was wondering why this is and if there is a way to fix this or what an alternative to using os.system to run my .bat file was? LW . . . Lawrence _________________________________________________________________ Send and receive email from all of your webmail accounts. http://go.microsoft.com/?linkid=9671356 -------------- next part -------------- An HTML attachment was scrubbed... URL: From rays at blue-cove.com Wed Aug 5 12:21:35 2009 From: rays at blue-cove.com (RayS) Date: Wed, 05 Aug 2009 09:21:35 -0700 Subject: Cypress FX2 - py libusb code? In-Reply-To: <5.2.1.1.2.20090804224315.01c22b60@pop-server.san.rr.com> Message-ID: <5.2.1.1.2.20090805091843.01c76cc8@blue-cove.com> An HTML attachment was scrubbed... URL: -------------- next part -------------- """ To run the single C file USB bulk read program properly, you must provide a source of data to the CY7C68013 FIFO bus, like the Simple dual channel A/D system, otherwise the reading call will time out in one second, you will get a bunch of zeros, and the ninth status number will be something negative instead of 512. """ import sys import os import time import usb def PrintDevInfo(dev): """Print device information.""" print "Device:", dev.filename print " Device class:",dev.deviceClass print " Device sub class:",dev.deviceSubClass print " Device protocol:",dev.deviceProtocol print " Max packet size:",dev.maxPacketSize print " idVendor:",dev.idVendor print " idProduct:",dev.idProduct print " Device Version:",dev.deviceVersion print " Device SerialNumber:",dev.iSerialNumber for config in dev.configurations: print " Configuration:", config.value print " Total length:", config.totalLength print " selfPowered:", config.selfPowered print " remoteWakeup:", config.remoteWakeup print " maxPower:", config.maxPower for intf in config.interfaces: print " Interface:",intf[0].interfaceNumber for alt in intf: print " Alternate Setting:",alt.alternateSetting print " Interface class:",alt.interfaceClass print " Interface sub class:",alt.interfaceSubClass print " Interface protocol:",alt.interfaceProtocol for ep in alt.endpoints: print " Endpoint:",hex(ep.address) print " Type:",ep.type print " Max packet size:",ep.maxPacketSize print " Interval:",ep.interval firmware = [0x90, 0xE6, 0x0B, 0x74, 0x03, 0xF0, ##REVCTL = 0x03 0x90, 0xE6, 0x04, 0x74, 0x80, 0xF0, ##FIFORESET = 0x80 0x74, 0x08, 0xF0, ##FIFORESET = 0x08 0xE4, 0xF0, ##FIFORESET = 0x00 0x90, 0xE6, 0x01, 0x74, 0xCB, 0xF0, ##IFCONFIG = 0xCB 0x90, 0xE6, 0x1B, 0x74, 0x0D, 0xF0, ##EP8FIFOCFG = 0x0D #0x90, 0xE6, 0x09, 0x74, 0x10, 0xF0, ##FIFOPINPOLAR = 0x10 TRUST!!! 0x80, 0xFE] ##while (1) {} reset = 0x01 er = [] endpoint = 8 # find all of the USB busses busses = usb.busses() #print busses # Find one device rdev = None for bus in busses: for dev in bus.devices: if dev.idVendor == 0x04B4 and dev.idProduct == 0x8613: rdev = dev if rdev==None: print "Could not find a CY7C68013\ndev.idVendor == 0x04B4 and dev.idProduct == 0x8613" sys.exit() else: dev = rdev #PrintDevInfo(dev) endpoint=8 current_handle = dev.open() requestType = 0x40 request = 0xa0 #buffer = ''.zfill(4096) value=0 index=0 timeout=1000 er.append(('RESET', current_handle.controlMsg(requestType, request, reset, value, index, timeout) ))##RESET time.sleep(0.1) for i in range(len(firmware)): #er.append(('ctrlMsg', i, current_handle.controlMsg(0x40, 0xa0, firmware[i], value=i, index=0))) er.append(('ctrlMsg', i, len(current_handle.controlMsg(0x40, 0xa0, firmware[i], value=i, index=0)))) er.append(('UNRESET', current_handle.controlMsg(requestType, request, reset+1, value, index, timeout))) ##UNRESET time.sleep(0.1) # we know that there's one config, one interface, and one endpoint conf = dev.configurations[0] er.append(( "confs", len(dev.configurations))) er.append(conf.interfaces.count(0))#, conf.interfaces.index(1) iface = conf.interfaces[0][1] er.append( ("ifaces[0]", len(conf.interfaces[0]))) endpoint = iface.endpoints[1] er.append(( "endpoints", len(iface.endpoints))) er.append(( "iin", iface.interfaceNumber)) er.append( current_handle.setConfiguration(conf)) er.append( current_handle.claimInterface(iface)) er.append( current_handle.setAltInterface(iface)) try: er.append( current_handle.bulkRead(endpoint.address, 512, 1000)) except usb.USBError, e: print ' bulkRead error: ', e.args print ' return data:' for e in er: print ' ', e PrintDevInfo(dev) sys.exit() for i in range(512): print " %02x " % buffer[i], current_handle.releaseInterface(0) dev.close() print "\n status: ", er[-1] From breamoreboy at yahoo.co.uk Wed Aug 5 12:30:24 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 05 Aug 2009 17:30:24 +0100 Subject: Is it possible to produce spider plots? In-Reply-To: References: Message-ID: dp_pearce wrote: > I want to be able to use Python to produce Spider plots (perhaps you > know them as radar plots or star plots). Does anyone know how to > achieve this? Are there existing libraries? > > Direction to any examples, especially those with tutorials, would be > greatly appreciated. > > Cheers, > Dan > > http://www.answers.com/topic/spider-plot How about http://matplotlib.sourceforge.net/examples/api/radar_chart.html?highlight=spider -- Kindest regards. Mark Lawrence. From tim.arnold at sas.com Wed Aug 5 12:34:18 2009 From: tim.arnold at sas.com (Tim Arnold) Date: Wed, 5 Aug 2009 12:34:18 -0400 Subject: Using Python to automate builds References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com> Message-ID: "Kosta" wrote in message news:84d9ae10-3aee-40a8-97ac-05799da0de64 at f18g2000prf.googlegroups.com... >I am a Python newbie, tasked with automating (researching) building > Windows drivers using the WDK build environment. I've been looking > into Python for this (instead of writing a bunch of batch files). > > What I would like to do, is to open a cmd window, and start a Python > script. This script would then (based upon input arguments), build > different flavors of the driver (fre, chk, x86, x64) and do some post > processing (create cat files, sign, etc.). > > I was hoping to take advantage as much as possible of exisiting > infrastructure from the WDK. I am able to call setenv.bat and provide > all the input parameters. One of the things setenv.bat does is change > the path environment variable. However, this is not captured by > Python. I could duplicate the functionality, but I'd rather not. Is > there a way to capture all enviroment variable changes being made by a > batch file from Python? > > Thanks! It sounds like you know what you're doing. I just wanted to point out that you can specify environment dictionaries in the subprocess.Popen module. You can set a different dictionary for each call you make to the system. Not sure if that helps, --Tim From martin.hellwig at dcuktec.org Wed Aug 5 13:05:08 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 Aug 2009 18:05:08 +0100 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: <9bca27b8-e71d-4b71-a792-d9ca7be18ab3@24g2000yqm.googlegroups.com> References: <9bca27b8-e71d-4b71-a792-d9ca7be18ab3@24g2000yqm.googlegroups.com> Message-ID: Jon Clements wrote: > IIRC (and I have my doubts) the BitVector module may be of use, but > it's been about 3 years since I had to look at it. I think it used the > C equiv. of short ints to do its work. Otherwise, maybe the array > module, the struct module or even possibly ctypes. > > Not much use, but might give a few pointers. > > Jon. I tried struct before (it seemed logical) but it didn't really do what I expected: >>> import struct >>> struct.unpack('?','x') (True,) I expected a list like (False, True, True, True, True, False, False, False). But it is (actually I hope) just an error of my side, so if somebody knows how to achieve what I want, with this module, please enlighten me :-) The array module doesn't seem to have an option for boolean values. BitVector does look very promising, but after peeking in the source it does more or less the same as what I do with converting back and forth of 'bitstrings'. I haven't thought about using ctypes for this, excellent suggestion! Thank you for your feedback. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From deets at nospam.web.de Wed Aug 5 13:16:54 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 05 Aug 2009 19:16:54 +0200 Subject: access string data from within cython Message-ID: <7dtt46F2e5osvU1@mid.uni-berlin.de> Hi, I'm trying to wrap a C-API which has a call that takes a void* and a size_t as arguments. void foo(void *data, size_t length) The wrapper is supposed to be called with a python (byte)string instance, which might contain more than one '\0'-character. So how do I access the raw data of a string? I tried looking into the buffer-protocol, but to be honest - that's beyond me, I don't see where that is actually giving me access to the real data. Diez From bearophileHUGS at lycos.com Wed Aug 5 13:17:29 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Wed, 5 Aug 2009 10:17:29 -0700 (PDT) Subject: Parsing Binary Structures; Is there a better way / What is your way? References: Message-ID: <50e27473-926b-458a-84f2-927ad02a0ed8@c14g2000yqm.googlegroups.com> Martin P. Hellwig: > On several occasions I have needed (and build) a parser that reads a > binary piece of data with custom structure. For example (bogus one): > > BE > +---------+---------+-------------+-------------+------+--------+ > | Version | Command | Instruction | Data Length | Data | Filler | > +---------+---------+-------------+-------------+------+--------+ > Version: 6 bits > Command: 4 bits > Instruction: 5 bits > Data Length: 5 bits > Data: 0-31 bits > Filler: filling 0 bits to make the packet dividable by 8 Have you tried Hachoir? (I think its name may be changed to Fusil, I don't know). Bye, bearophile From masklinn at masklinn.net Wed Aug 5 13:22:42 2009 From: masklinn at masklinn.net (Masklinn) Date: Wed, 5 Aug 2009 19:22:42 +0200 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: References: Message-ID: <934952CA-AC59-415C-A5D8-AEF74A0033FD@masklinn.net> On 5 Aug 2009, at 16:46 , Martin P. Hellwig wrote: > Hi List, > > On several occasions I have needed (and build) a parser that reads a > binary piece of data with custom structure. For example (bogus one): > > BE > +---------+---------+-------------+-------------+------+--------+ > | Version | Command | Instruction | Data Length | Data | Filler | > +---------+---------+-------------+-------------+------+--------+ > Version: 6 bits > Command: 4 bits > Instruction: 5 bits > Data Length: 5 bits > Data: 0-31 bits > Filler: filling 0 bits to make the packet dividable by 8 > > what I usually do is read the packet in binary mode, convert the > output to a concatenated 'binary string'(i.e. '0101011000110') and > then use slice indeces to get the right data portions. > Depending on what I need to do with these portions I convert them to > whatever is handy (usually an integer). > > This works out fine for me. Most of the time I also put the ASCII > art diagram of this 'protocol' as a comment in the code, making it > more readable/understandable. > > Though there are a couple of things that bothers me with my approach: > - This seems such a general problem that I think that there must be > already a general pythonic solution. > - Using a string for binary representation takes at least 8 times > more memory for the packet than strictly necessary. > - Seems to need a lot of prep work before doing the actual parsing. > > Any suggestion is greatly appreciated. The gold standard for binary parsing (and serialization) is probably Erlang's bit syntax, but as far as Python goes you might be interested by Hachoir (http://hachoir.org/ but it seems down right now). It's not going to match your second point, but it can probably help with the rest (caveat: I haven't used hachoir personally). From masklinn at masklinn.net Wed Aug 5 13:26:53 2009 From: masklinn at masklinn.net (Masklinn) Date: Wed, 5 Aug 2009 19:26:53 +0200 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: <50e27473-926b-458a-84f2-927ad02a0ed8@c14g2000yqm.googlegroups.com> References: <50e27473-926b-458a-84f2-927ad02a0ed8@c14g2000yqm.googlegroups.com> Message-ID: <7120B941-0C12-47ED-9505-08914EBD9CFB@masklinn.net> On 5 Aug 2009, at 19:17 , Bearophile wrote: > Have you tried Hachoir? (I think its name may be changed to Fusil, I > don't know). Name hasn't been changed (I think fusil is a subproject, something like that) on the other hand the hachoir.org site is dead. But apparently Hachoir was moved to bitbucket (http://bitbucket.org/haypo/hachoir/wiki/Home ) just in time so? From mensanator at aol.com Wed Aug 5 13:33:07 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 5 Aug 2009 10:33:07 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> <4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> Message-ID: > It didn't form 2.5 to 2.6 (at least not intentionally). But with the > indroduction of the TurtleScreen class and the Screen class/object > (singleton) a few of the turtle methods were also implemented as screen > methods and as turtle methods declared deprecated (see docs of Python > 2.6). These deprecated turtle methods do not occur as turtle methods any > more in Python 3.x. More info. Yes, there is no tracer attribute...when the object is created. But watch this (Python 3.1): >>> import turtle >>> tooter = turtle.Turtle() >>> tooter.tracer Traceback (most recent call last): File "", line 1, in tooter.tracer AttributeError: 'Turtle' object has no attribute 'tracer' >>> tooter.hideturtle() >>> tooter.speed('fast') >>> turtle.update() >>> turtle.tracer Now, after setting hide, speed, update, a tracer exists. Is that supposed to happen? That explains why there was no error when I set the turtle attribute instead of the screen attribute. And, of course, setting the turtle attribute accomplishes nothing, as actual tracing is controlled by the screen attribute as you say. > > Among them is the tracer method, which in fact does not control single > turtle objects but all the turtles on a given screen. > > So there is an icompatibility beween 2.6 and 3.x > > But as far as I have understood, this doesn't concern the problem > reported by mensator. Only that the problem is hidden when tracing is off, as the nhops variable is never evaluated when trace is off. > > Regards, > Gregor From gregor.lingl at aon.at Wed Aug 5 13:56:50 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Wed, 05 Aug 2009 19:56:50 +0200 Subject: Turtle Graphics are incompatible with gmpy In-Reply-To: References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> <4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> Message-ID: <4A79C7E2.3000406@aon.at> Mensanator schrieb: >> It didn't form 2.5 to 2.6 (at least not intentionally). But with the >> indroduction of the TurtleScreen class and the Screen class/object >> (singleton) a few of the turtle methods were also implemented as screen >> methods and as turtle methods declared deprecated (see docs of Python >> 2.6). These deprecated turtle methods do not occur as turtle methods any >> more in Python 3.x. > > More info. > > Yes, there is no tracer attribute...when the object is created. > > But watch this (Python 3.1): > >>>> import turtle >>>> tooter = turtle.Turtle() >>>> tooter.tracer > Traceback (most recent call last): > File "", line 1, in > tooter.tracer > AttributeError: 'Turtle' object has no attribute 'tracer' >>>> tooter.hideturtle() >>>> tooter.speed('fast') >>>> turtle.update() >>>> turtle.tracer > > > Now, after setting hide, speed, update, a tracer exists. No, >>> import turtle >>> turtle.tracer >>> help(turtle.tracer) Help on function tracer in module turtle: tracer(n=None, delay=None) Turns turtle animation on/off and set delay for update drawings. Optional arguments: n -- nonnegative integer delay -- nonnegative integer If n is given, only each n-th regular screen update is really performed. (Can be used to accelerate the drawing of complex graphics.) Second arguments sets delay value.) Example: >>> tracer(8, 25) >>> dist = 2 >>> for i in range(200): fd(dist) rt(90) dist += 2 >>> The reason for this is, that the turtle module (the new one as well as the old one) has a vers special design: The methods of class Turtle are also available as functions (which are in fact methods calls of an anonymous turtle). The same holds for the methods of TurtleScreen. The intention behind this design is that you can use the module in an OOP way as well as with procedural programming (especially for beginners). When using objects I normally use from turtle import Turtle, Screen screen = Screen() # that creates singleton object, the screen the turtle acts on and I create as many turtles as I need from the Turtle class So turtle.tracer() doesn't make sense anymore > Is that supposed to happen? That explains why there was no error > when I set the turtle attribute instead of the screen attribute. You do not 'set the turtle attribute', you call the tracer function of the turtle module > And, of course, setting the turtle attribute accomplishes nothing, > as actual tracing is controlled by the screen attribute as you say. > >> Among them is the tracer method, which in fact does not control single >> turtle objects but all the turtles on a given screen. >> >> So there is an icompatibility beween 2.6 and 3.x >> >> But as far as I have understood, this doesn't concern the problem >> reported by mensator. > > Only that the problem is hidden when tracing is off, as the nhops > variable is never evaluated when trace is off. Nevertheless I'd like to see a working Python 2.5 version of your script. Regards, Gregor From http Wed Aug 5 14:12:05 2009 From: http (Paul Rubin) Date: 05 Aug 2009 11:12:05 -0700 Subject: Parsing Binary Structures; Is there a better way / What is your way? References: Message-ID: <7x3a86gmfe.fsf@ruckus.brouhaha.com> "Martin P. Hellwig" writes: > what I usually do is read the packet in binary mode, convert the > output to a concatenated 'binary string'(i.e. '0101011000110') and Something wrong with reading the data words as an integer and using old fashioned shifts and masks to get at the bit fields? From 1x7y2z9 at gmail.com Wed Aug 5 14:12:45 2009 From: 1x7y2z9 at gmail.com (1x7y2z9) Date: Wed, 5 Aug 2009 11:12:45 -0700 (PDT) Subject: unicode() vs. s.decode() References: Message-ID: unicode() has LOAD_GLOBAL which s.decode() does not. Is it generally the case that LOAD_ATTR is slower than LOAD_GLOBAL that lead to your intuition that the former would probably be slower? Or some other intuition? Of course, the results from timeit are a different thing - I ask about the intuition in the disassembler output. Thanks. > > The presence of LOAD_ATTR in the first form hints that this is probably > going to be slower. ? Next, actually try it: > From piet at cs.uu.nl Wed Aug 5 14:20:47 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 20:20:47 +0200 Subject: Special chars with HTMLParser References: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com> <69835fa3-c6a0-44d3-bba2-5e3117102590@k30g2000yqf.googlegroups.com> Message-ID: >>>>> Fafounet (F) wrote: >F> Thank you, now I can get the correct character. >F> Now when I have the string abécd I can get ab then ? thanks to >F> your function and then cd. But how is it possible to know that cd is >F> still the same word ? That depends on your definition of `word'. And that is language-dependent. What you normally do is collect the text in a (unicode) string variable. This happens in handle_data, handle_charref and handle_entityref. Then you check that the previously collected stuff was a word (e.g. consisting of Unicode letters), and that the new stuff also consists of letters. If your language has additional word constituents like - or ' you have to add this. You can do this with unicodedata.category or with a regular expression. If your locale is correct \w in a regular expression may be helpful. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From dp_pearce at hotmail.com Wed Aug 5 14:21:50 2009 From: dp_pearce at hotmail.com (Devon_Dan) Date: Wed, 5 Aug 2009 11:21:50 -0700 (PDT) Subject: Is it possible to produce spider plots? References: Message-ID: <2481d12e-6af9-4dbb-991d-fb636c3b6831@k6g2000yqn.googlegroups.com> > reportlab has a spider chart in reportlab/graphics/charts/spider.py > How about > http://matplotlib.sourceforge.net/examples/api/radar_chart.html?highl... Both exactly what I was after. Thanks very much. > The 'wxPython in Action' book has some simple example code which > produces this sort of graphic. If you are after a GUI application > rather than creating a paper copy it might be worth checking this out. Thanks for this one jkn. I actually have this book and went through it looking to see if it had an answer before posting. Completely missed it! Clearly I need to RTFM more closely next time. From philip at semanchuk.com Wed Aug 5 14:25:27 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 5 Aug 2009 14:25:27 -0400 Subject: access string data from within cython In-Reply-To: <7dtt46F2e5osvU1@mid.uni-berlin.de> References: <7dtt46F2e5osvU1@mid.uni-berlin.de> Message-ID: On Aug 5, 2009, at 1:16 PM, Diez B. Roggisch wrote: > Hi, > > I'm trying to wrap a C-API which has a call that takes a void* and a > size_t > as arguments. > > void foo(void *data, size_t length) > > > The wrapper is supposed to be called with a python (byte)string > instance, > which might contain more than one '\0'-character. > > So how do I access the raw data of a string? I tried looking into the > buffer-protocol, but to be honest - that's beyond me, I don't see > where > that is actually giving me access to the real data. Hi Diez, Would ctypes.create_string_buffer() work for you? bye P From jeremy.cowles at gmail.com Wed Aug 5 14:31:38 2009 From: jeremy.cowles at gmail.com (Jeremy Cowles) Date: Wed, 5 Aug 2009 11:31:38 -0700 Subject: Install setup tools for 2.6 Message-ID: <373cf0740908051131gacaf77apba48fa40e929f491@mail.gmail.com> Ok, I feel like this is a really stupid question, but how do you install setup tools for Python 2.6 under windows? The only format is .egg which requires setup tools to install, doesn't it? Thanks, Jeremy -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin.hellwig at dcuktec.org Wed Aug 5 14:46:12 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 Aug 2009 19:46:12 +0100 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: <7x3a86gmfe.fsf@ruckus.brouhaha.com> References: <7x3a86gmfe.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Martin P. Hellwig" writes: >> what I usually do is read the packet in binary mode, convert the >> output to a concatenated 'binary string'(i.e. '0101011000110') and > > Something wrong with reading the data words as an integer and using > old fashioned shifts and masks to get at the bit fields? No not at all of course, I just found it more readable to slice it instead of shifting and masking; i.e. if the ASCII art schematics of the protocol are included as a comment it is almost an 1 to 1 implementation. Is there an advantage using shifts and masks over my kitchen type solution? -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From ihatespam at hotmail.com Wed Aug 5 14:47:58 2009 From: ihatespam at hotmail.com (Just Another Victim of the Ambient Morality) Date: Wed, 5 Aug 2009 14:47:58 -0400 Subject: Confessions of a Python fanboy References: <008e82e8$0$9756$c3e8da3@news.astraweb.com><4a72d7cf$0$25239$426a34cc@news.free.fr><008eef29$0$9756$c3e8da3@news.astraweb.com><4a77eb69$0$22600$426a74cc@news.free.fr> Message-ID: "Steven D'Aprano" wrote in message news:pan.2009.08.04.09.28.49 at REMOVE.THIS.cybersource.com.au... > On Tue, 04 Aug 2009 10:03:53 +0200, Bruno Desthuilliers wrote: > >>> Disadvantages: your code is filled with line noise. It's an arbitrary >>> choice between @@ meaning instance attribute and @@ meaning class >>> attribute -- there's no logical reason for choosing one over the other, >>> so you have to memorise which is which. It's easy to get it wrong. >> >> So far that's something I have no difficulty living with. > > I don't like arbitrary symbols. Most people don't -- that's why "line > noise" is unpopular. It's hard to read, hard to write, hard to maintain, > and hard to talk about. The more line-noise, the worse the language. It's not "line noise" if it conveys information... > Of course, *ultimately* every symbol is arbitrary. There's no reason why > "2" should mean the integer two, or "list" should mean a sequence type, > but some symbols have such a long history, or have some other connection > (say, with human languages), that the arbitrariness is lost. For > instance, "+" is the obvious, non-arbitrary choice for the addition > operator in any programming language using Latin symbols, and probably > any programming language on Earth. (Not the *only* choice, but the > obvious one.) > > I have a similar dislike for decorator syntax, because "@" ("at" in > English) has nothing to do with decorations. It's an arbitrary symbol. > One might argue that "$" would have been a more logical choice, because > we turn numerals into currency by decorating it with a $ sign. (At least > in the US, Canada, Australia, and a few other countries.) I use > decorators all the time, and they are a fantastic invention, but the > arbitrariness of the @ syntax is a negative. Oh well, one negative out of > a whole lot of positives isn't too bad. You can think of "@" as describing something being "at" the instance or the class. "$" is totally arbitrary to me 'cause I don't thnk of my code as currency... > At least I only have to deal with *one* such arbitrary symbol that needs > memorizing. There's no need to distinguish between @@function_decorator > and @class_decorator (or should it be the other way around?). Similarly, > Python's choice of syntax for attributes is consistent: object.attribute > works for everything, whether object is a class, an instance, a module, > and whether attribute is callable or not. You can even use it on ints, > provided you are clever about it: You can think of "@" as being at an instance or "@@" to be more emphatically (as the Japanese do in their language) integrated with a class, being available to all instances... or you can simply understand that instance vairables are more common than class variables so the shorter notation is used for the more common case... You want to talk about arbitrariness? Why is len() a function you pass objects into while objects can have methods that describe themselves to you? At least Ruby defines operators using the actual name of the operator instead of you having to remember an arbitrary magic incantation that corresponds to the operator... class Test attr_reader :data def initialize(data) @data = data end # This is the operator part... def + right Test.new @data + right.data end end >>>>> Somebody who knows more Ruby than me should try writing the Zen of >>>>> Ruby. Something like: >>>> (snip childish parody of Python Zen) >>>> >>>> Steven, is that any useful ? >>> >>> It made me feel good. >> >> Why ??? >> >> You don't like Ruby ? Fine, don't use it. Period. I can't see the point >> of all these pissing contests. > > Criticism of a language is a pissing contest? > > Yeah, okay, I was a tad dismissive. I un-apologetically jump to strong > impressions about languages based on minimal use -- but I'm also willing > to change my mind. Ruby certainly looks to me like it has some nice > features. Syntax that looks like Perl isn't one of them though. Yeah, that would be the "pissing contest" part. You could simply have gone to the Ruby newsgroup and posted some criticisms to see what was behind those decisions. However, that would have avoided the pissing contest and perhaps you wanted one... >>> Just because Smalltalk had a particular (mis?)feature >> >> You can drop the 'mis' part IMHO. The point of code blocks in Smalltalk >> is that once you have something as powerful as the message+code blocks >> combo, you just don't need any other 'special form' for control flow. > > Well, maybe, but remember, programming languages are only partly for > communication to the compiler. They also have the requirement to > communicate with human programmers as well, and that's even more > important, because > > (1) humans spent a lot more time working with code than compilers do; > > (2) human programmers charge much more money than compilers do; > > (3) and you can modify the compiler to suit human needs much more easily > than you can modify programmers to suit the compiler's needs. > > So I'd ask, does Smalltalk's message passing model match the way human > beings think? If not, then that's a good sign it might be a misfeature. I think this is overstated. Not all humans think in exactly the same way so it's very presumptuous. It also ignores our intellect. We can change the way we think and we can use this versatility to our advantage. We can increase our productivity in certain tasks by changing the way we think to some other paradigm that better serves a given purpose... >>> doesn't mean that >>> other languages should copy it. >> >> Nope. But OTHO, Python is famous for all the features it copied from >> other languages !-) > > Absolutely! There's nothing wrong with copying *good* features :) The trick, of course, is figuring out which features are good! From http Wed Aug 5 14:51:06 2009 From: http (Paul Rubin) Date: 05 Aug 2009 11:51:06 -0700 Subject: Parsing Binary Structures; Is there a better way / What is your way? References: <7x3a86gmfe.fsf@ruckus.brouhaha.com> Message-ID: <7xr5vqw0v9.fsf@ruckus.brouhaha.com> "Martin P. Hellwig" writes: > Is there an advantage using shifts and masks over my kitchen type solution? Weren't you complaining about the 8-to-1 expansion from turning each bit to an ascii char? From gdamjan at gmail.com Wed Aug 5 15:05:30 2009 From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=) Date: Wed, 05 Aug 2009 21:05:30 +0200 Subject: String to valid Python identifier Message-ID: Is there any easy function in the stdlib to convert any random string in a valid Python identifier .. possibly by replacing non-valid characters with _ ? Python 2.x only, so no need to do Unicode. -- ?????? ( http://softver.org.mk/damjan/ ) Religion ends and philosophy begins, just as alchemy ends and chemistry begins and astrology ends, and astronomy begins. From pdlemper at earthlink.net Wed Aug 5 15:18:26 2009 From: pdlemper at earthlink.net (pdlemper at earthlink.net) Date: Wed, 05 Aug 2009 14:18:26 -0500 Subject: trouble with complex numbers References: <24821423.post@talk.nabble.com> Message-ID: <7gmj75lbijq2k8d8lk6kff7itt76n8ij13@4ax.com> On Wed, 05 Aug 2009 08:18:55 -0700, Scott David Daniels wrote: >I think it explained in the complex math area, but basically EE types >use j, math types use i for exactly the same thing. Since i is so >frequently and index in CS, and there is another strong convention, >why not let the EE types win? > >--Scott David Daniels >Scott.Daniels at Acm.Org i represents current Dave WB3DWE From sturlamolden at yahoo.no Wed Aug 5 15:23:16 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 5 Aug 2009 12:23:16 -0700 (PDT) Subject: access string data from within cython References: <7dtt46F2e5osvU1@mid.uni-berlin.de> Message-ID: <88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com> On 5 Aug, 19:16, "Diez B. Roggisch" wrote: > void foo(void *data, size_t length) > > The wrapper is supposed to be called with a python (byte)string instance, > which might contain more than one '\0'-character. > > So how do I access the raw data of a string? cdef extern void foo(void *data, int length) cdef char *data cdef int length bytestring = ... #whatever rawdata = bytestring length = len(bytestring) foo(data, length) From joshua at joshuakugler.com Wed Aug 5 15:23:31 2009 From: joshua at joshuakugler.com (Joshua Kugler) Date: Wed, 05 Aug 2009 11:23:31 -0800 Subject: Subclassing Python's dict References: <2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com> Message-ID: Xavier Ho wrote: > On Thu, Aug 6, 2009 at 11:51 AM, Sergey Simonenko > wrote: > >> I subclass builtin 'dict' in my application and experience some problems >> with it. >> > > You should subclass collections.UserDict, and not the default dict class. > Refer to the collections module. Are you referring to Python 3.0? Python 2.6 does not have collections.UserDict j From sturlamolden at yahoo.no Wed Aug 5 15:25:42 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 5 Aug 2009 12:25:42 -0700 (PDT) Subject: access string data from within cython References: <7dtt46F2e5osvU1@mid.uni-berlin.de> <88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com> Message-ID: <99c677b4-75eb-4a33-a1be-eecbc61c14fc@k19g2000yqn.googlegroups.com> On 5 Aug, 21:23, sturlamolden wrote: > foo(data, length) Oops, that would be foo( data, length) From joshua at joshuakugler.com Wed Aug 5 15:26:48 2009 From: joshua at joshuakugler.com (Joshua Kugler) Date: Wed, 05 Aug 2009 11:26:48 -0800 Subject: Do anyone here use Python *embedded* in a database? References: Message-ID: Jonathan Fine wrote: > Hi > > I'm writing a talk that compares embed and extend, and wondered if > anyone here ever used the Python *embedded* in a database server. > http://twistedmatrix.com/users/glyph/rant/extendit.html > > Web frameworks (such as Django) use extend, to import an extension > module that makes a connection to a database. > > If you have used embed, you might have consulted a page such as: > http://www.postgresql.org/docs/8.3/interactive/plpython-funcs.html > Yes, I've used plpython. We had a web application that had account creation logic with salting, encryption, etc, on the passwords. We then wanted to use the same accounts to log in to a Drupal site. Instead of trying to replicate the logic in PHP, I just created a stored procedure with plpython, and we overrode the drupal login check to call something like "SELECT check_account(user, pass)" which would return 1 or 0 on success or failure, respectively. Worked great. j From mensanator at aol.com Wed Aug 5 15:31:05 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 5 Aug 2009 12:31:05 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: On Aug 5, 2:19?am, Steven D'Aprano wrote: > On Wed, 5 Aug 2009 03:49 pm Mensanator wrote: > > > In 3.1, tracing is now a screen attribute, not a turtle atribute. > > I have no idea why > > > ? tooter = turtle.Turtle() > > ? tooter.tracer(False) > > > doesn't give me an error (I thought silent errors were a bad thing). > > What makes it an error? Do you consider the following an error? > > >>> class Test: > > ... ? ? pass > ... > > >>> t = Test() > >>> t.tracer = 5 Come on, even _I_ know this: >>> class Test: pass >>> t = Test() >>> t.tracer Traceback (most recent call last): File "", line 1, in t.tracer AttributeError: 'Test' object has no attribute 'tracer' >>> t.tracer = False >>> t.tracer False > > Perhaps you mean, it's an API change you didn't know about, and you wish to > protest that Turtle Graphics made an incompatible API change without > telling you? What does this mean? >>> import turtle >>> tooter = turtle.Turtle() >>> tooter.tracer Traceback (most recent call last): File "", line 1, in tooter.tracer AttributeError: 'Turtle' object has no attribute 'tracer' >>> tooter.hideturtle() >>> tooter.speed('fast') >>> turtle.update() >>> turtle.tracer How did the tracer attribute appear out of thin air? And more importantly, why, if has been deprecated and dropped from 3.x? > > > Naturally, having tracing on caused my program to crash. > > It seg faulted or raised an exception? Why did you snip it? Should I not refer to this as a crash? Traceback (most recent call last): File "K:\user_python26\turtle\turtle_xy_Py3.py", line 95, in tooter.goto(the_coord) File "C:\Python31\lib\turtle.py", line 1771, in goto self._goto(Vec2D(*x)) File "C:\Python31\lib\turtle.py", line 3165, in _goto nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed)) ValueError: mpq.pow fractional exponent, inexact-root > > [...] > > > Unfortunately, that calculation of nhops is illegal if diffsq is > > an .mpf (gmpy floating point). Otherwise, you get > > How does diffsq get to be a mpf? No idea. I neglected to mention I'm using the new gmpy 1.10. Don't know if that has any bearing. > Are gmpy floats supposed to be supported? Apparently not, as gmpy has only limited exponential capability. Looks like I need to change turtle.py to use math.sqrt(diffsq) or float(diffsq)**0.5. Or not pass turtle.py any .mpz since it can't handle them. > > -- > Steven From sturlamolden at yahoo.no Wed Aug 5 15:36:11 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 5 Aug 2009 12:36:11 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> <74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> Message-ID: <6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> On 5 Aug, 15:40, Jesse Noller wrote: > Sturla; > > That bug was fixed unless I'm missing something. It is still in SVN. Change every call to os._exit to sys.exit please. :) http://svn.python.org/view/python/branches/release26-maint/Lib/multiprocessing/forking.py?revision=66717&view=markup http://svn.python.org/view/python/branches/release31-maint/Lib/multiprocessing/forking.py?revision=73579&view=markup From sturlamolden at yahoo.no Wed Aug 5 15:40:40 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 5 Aug 2009 12:40:40 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> <74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> <6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> Message-ID: On 5 Aug, 21:36, sturlamolden wrote: > http://svn.python.org/view/python/branches/release26-maint/Lib/multip... > > http://svn.python.org/view/python/branches/release31-maint/Lib/multip... http://svn.python.org/view/python/trunk/Lib/multiprocessing/forking.py?revision=65864&view=markup From martin.hellwig at dcuktec.org Wed Aug 5 15:41:26 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 05 Aug 2009 20:41:26 +0100 Subject: Parsing Binary Structures; Is there a better way / What is your way? In-Reply-To: <7xr5vqw0v9.fsf@ruckus.brouhaha.com> References: <7x3a86gmfe.fsf@ruckus.brouhaha.com> <7xr5vqw0v9.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Martin P. Hellwig" writes: >> Is there an advantage using shifts and masks over my kitchen type solution? > > Weren't you complaining about the 8-to-1 expansion from turning each bit > to an ascii char? Yes you are (of course) right, my 'dream' solution would be something that accepts slice indeces on bit level. Your reasoning did reveal some flaws in my approach though ;-) -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From rylesny at gmail.com Wed Aug 5 15:48:24 2009 From: rylesny at gmail.com (ryles) Date: Wed, 5 Aug 2009 12:48:24 -0700 (PDT) Subject: Is this a bug in multiprocessing or in my script? References: Message-ID: On Aug 4, 10:37?pm, erikcw wrote: > Traceback (most recent call last): > ? File "scraper.py", line 144, in > ? ? print pool.map(scrape, range(10)) > ? File "/usr/lib/python2.6/multiprocessing/pool.py", line 148, in map > ? ? return self.map_async(func, iterable, chunksize).get() > ? File "/usr/lib/python2.6/multiprocessing/pool.py", line 422, in get > ? ? raise self._value > TypeError: expected string or buffer This is almost certainly due to your scrape call raising an exception. In the parent process, multiprocessing will detect if one of its workers have terminated with an exception and then re-raise it. However, only the exception and not the original traceback is made available, which is making debugging more difficult for you. Here's a simple example which demonstrates this behavior: *** from multiprocessing import Pool *** def evil_on_8(x): ... if x == 8: raise ValueError("I DONT LIKE THE NUMBER 8") ... return x + 1 ... *** pool = Pool(processes=4) >>> pool.map(evil_on_8, range(5)) [1, 2, 3, 4, 5] *** pool.map(evil_on_8, range(10)) # 8 will cause evilness. Traceback (most recent call last): File "", line 1, in File "/bb/real/3ps/lib/python2.6/multiprocessing/pool.py", line 148, in map return self.map_async(func, iterable, chunksize).get() File "/bb/real/3ps/lib/python2.6/multiprocessing/pool.py", line 422, in get raise self._value ValueError: I DONT LIKE THE NUMBER 8 *** My recommendation is that you wrap your scrape code inside a try/ except and log any exception. I usually do this with logging.exception (), or if logging is not in use, the traceback module. After that you can simply re-raise it. From no.email at please.post Wed Aug 5 15:58:39 2009 From: no.email at please.post (kj) Date: Wed, 5 Aug 2009 19:58:39 +0000 (UTC) Subject: no-clobber dicts? References: <00027aa9$0$2969$c3e8da3@news.astraweb.com> Message-ID: In <00027aa9$0$2969$c3e8da3 at news.astraweb.com> Steven D'Aprano writes: >No problem. Here you go: >http://www.cybersource.com.au/users/steve/python/constants.py Extremely helpful. Thanks! kynn From wolfram.hinderer at googlemail.com Wed Aug 5 16:00:07 2009 From: wolfram.hinderer at googlemail.com (Wolfram Hinderer) Date: Wed, 5 Aug 2009 13:00:07 -0700 (PDT) Subject: Turtle Graphics are incompatible with gmpy References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: <214e2b0a-15c9-4d2b-a836-9ad75a13fc6c@r38g2000yqn.googlegroups.com> On 5 Aug., 21:31, Mensanator wrote: > > >>> import turtle > >>> tooter = turtle.Turtle() > >>> tooter.tracer > > Traceback (most recent call last): > ? File "", line 1, in > ? ? tooter.tracer > AttributeError: 'Turtle' object has no attribute 'tracer'>>> tooter.hideturtle() > >>> tooter.speed('fast') > >>> turtle.update() > >>> turtle.tracer > > > > How did the tracer attribute appear out of thin air? You seem to confuse the "tooter" Turtle object and the "turtle" module when talking about "the tracer attribute". From piet at cs.uu.nl Wed Aug 5 16:07:29 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 22:07:29 +0200 Subject: Is this a bug in multiprocessing or in my script? References: <2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> <74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> <6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> Message-ID: >>>>> sturlamolden (s) wrote: >s> On 5 Aug, 15:40, Jesse Noller wrote: >>> Sturla; >>> >>> That bug was fixed unless I'm missing something. >s> It is still in SVN. Change every call to os._exit to sys.exit >s> please. :) Calling os.exit in a child process may be dangerous. It can cause unflushed buffers to be flushed twice: once in the parent and once in the child. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From ethan at stoneleaf.us Wed Aug 5 16:08:00 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 05 Aug 2009 13:08:00 -0700 Subject: Turtle Graphics are incompatible with gmpy In-Reply-To: References: <0002b5d3$0$2970$c3e8da3@news.astraweb.com> Message-ID: <4A79E6A0.5040404@stoneleaf.us> Mensanator wrote: > > What does this mean? > > >>>>import turtle >>>>tooter = turtle.Turtle() >>>>*tooter*.tracer > > Traceback (most recent call last): > File "", line 1, in > tooter.tracer > AttributeError: 'Turtle' object has no attribute 'tracer' > >>>>tooter.hideturtle() >>>>tooter.speed('fast') >>>>turtle.update() >>>>*turtle*.tracer > > > > How did the tracer attribute appear out of thin air? Perhaps I am missing something (wouldn't surprise me!) but it seems that the first time you are looking for a tracer on 'tooter', and the second time you are looking for a tracer on 'turtle'. After *turtle.tracer* succeeds, does *tooter.tracer*? ~Ethan~ From no.email at please.post Wed Aug 5 16:09:25 2009 From: no.email at please.post (kj) Date: Wed, 5 Aug 2009 20:09:25 +0000 (UTC) Subject: How to combine regexps? Message-ID: One of the nice things one can do with Perl's regexp's is illustrated in the following example: my $gly = qr/gg[ucag]/i my $ala = qr/gc[ucag]/i; my $val = qr/gu[ucag]/i; my $leu = qr/uu[ag]|cu[ucag]/i; my $ile = qr/au[uca]/i; my $aliphatic = qr/$gly|$ala|$val|$leu|$ile/; In other words, one can build regular expressions by re-combining other regular expressions. Is there a way to do this with Python's regexps? TIA! kynn From aahz at pythoncraft.com Wed Aug 5 16:11:37 2009 From: aahz at pythoncraft.com (Aahz) Date: 5 Aug 2009 13:11:37 -0700 Subject: Printing with colors in a portable way References: <33e19169-19b4-497a-b262-2bcf7b5637d5@r38g2000yqn.googlegroups.com> <19e16923-b200-498b-9ab2-f7d316b568a6@d32g2000yqh.googlegroups.com> Message-ID: In article <19e16923-b200-498b-9ab2-f7d316b568a6 at d32g2000yqh.googlegroups.com>, r wrote: >On Aug 2, 9:52=A0pm, a... at pythoncraft.com (Aahz) wrote: > >> Much as I hate to say, use a cross-platform GUI -- Tkinter comes with >> Python, > >Why is Tkinter such a whipping boy of the Python community? Can you explain what the connection is between my post and yours? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From piet at cs.uu.nl Wed Aug 5 16:14:04 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 05 Aug 2009 22:14:04 +0200 Subject: http access produces 503 References: <3b5ab07c-7b0b-4d23-965b-192dc86cf6ff@a26g2000yqn.googlegroups.com> Message-ID: >>>>> Rog (R) wrote: >R> I am porting a simple code from Perl, the website asks for usr/pwd and >R> the server's side Perl script makes atemp ftp dir for file upload. >R> The original Perl script connects okay, does its job. The same URL >R> stuffed into FF3 performs the same way. >R> My Python script I am sweating out for past four days (noob!) gets >R> consistently "503", even with user agen set to: Mozilla/5.0 (Windows; >R> U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11. >R> Snippets of relevant code below. >R> Please, help me understand how this same code lets me log in into my >R> router usr/pwd running .asp, but this !@#$% perl script returns to me >R> w/503 c*ap? >R> Thank you. Which perl script? >R> Do I need to set any proxy? The server is on intranet and the FF3 is >R> set to proxy. The original Perl script did not use any proxy setting. >R>

>R> url = http://example.com/ftpsetup.pl?username=boofa&nodeid=42
>R> #########################################################
>R> # create a password manager
>R>     password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
>R> # Add the username and password.
>R> # If we knew the realm, we could use it instead of ``None``.
>R>     password_mgr.add_password(None, url, uid, pcode)
>R>     handler = urllib2.HTTPBasicAuthHandler(password_mgr)
>R>     class Mopener(URLopener): version = "Mozilla/5.0 (Windows; U;
>R> Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

>R>     opener = Mopener()

>R> # create "opener" (OpenerDirector instance)

>R>     opener = urllib2.build_opener(handler)
>R>     opener.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U;
>R> Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11')]

>R>     opener.version = "Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:
>R> 1.8.1.11) Gecko/20071127 Firefox/2.0.0.11"

>R>     print opener.version
>R> # timeout in seconds
>R>     timeout = 10
>R>     socket.setdefaulttimeout(timeout)

>R> # Install the opener all calls to urllib2.urlopen use our opener.
>R>     urllib2.install_opener(opener)

>R>     try:
>R>         response = opener.open(url)
>R>         # "http://www.useragent.org/" tested okay!!!
>R>         print"ok = 1"
>R>     except:
>R>         print "error 1"
>R> #####################################################################################

This code is a mess. The indentation is wrong so it can't be your real
code. Imports are missing. And there is a lot of garbage that doen't do
anything. E.g. The Mopener business is not used. install_opener is not
used.

Please make a minimal examples and check if that fails to. Like:

import urllib2
import socket

url = 'http://example.com/ftpsetup.pl?username=boofa&nodeid=42'
uid = ...
pcode = ...

# create a password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
# Add the username and password.
# If we knew the realm, we could use it instead of ``None``.
password_mgr.add_password(None, url, uid, pcode)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)

# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)

try:
    response = opener.open(url)
    print response.read()
    print"ok = 1"
except:
    print "error 1"



>R> output from the above:

>R> Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/
>R> 20071127 Firefox/2.0.0.11
>R> error 1
>R> Error code:  503
>R> ('Service Unavailable', 'The server cannot process the request due to
>R> a high load')

That suggests that there is a real problem in the server. Or that your
url causes some problems.

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From pfeldman at verizon.net  Wed Aug  5 16:16:31 2009
From: pfeldman at verizon.net (Dr. Phillip M. Feldman)
Date: Wed, 5 Aug 2009 13:16:31 -0700 (PDT)
Subject: trouble with complex numbers
In-Reply-To: 
References: <24821423.post@talk.nabble.com> 
Message-ID: <24835436.post@talk.nabble.com>


I am using Python 2.5, and most of the cmath functions are not yet available
in this version.  Thanks!

Phillip

P.S. In your code, that should be x+= 0J

P.P.S. I wish that the documentation indicated anything that is new.


Christian Heimes-2 wrote:
> 
> 
> 
> phase() has been added to Python 2.6 and 3.0. It's not available in 
> Python 2.5 and earlier. If you'd used cmath.phase() instead of the ugly 
> "from cmath import *" statement you'd have seen the correct error message.
> 
> You can write your own phase() function. This function is mostly correct 
> unless either the real and/or the imag part is NaN or INF.
> 
> from math import atan2
> 
> def phase(z):
>      z += 1j # convert int, long, float to complex
>      return atan2(z.imag, z.real)
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

-- 
View this message in context: http://www.nabble.com/trouble-with-complex-numbers-tp24821423p24835436.html
Sent from the Python - python-list mailing list archive at Nabble.com.



From gagsl-py2 at yahoo.com.ar  Wed Aug  5 16:18:02 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 05 Aug 2009 17:18:02 -0300
Subject: Python configuration question when python scripts are executed
	using Appweb as web server.
References: 
	
	
Message-ID: 

En Tue, 04 Aug 2009 10:15:24 -0300, IronyOfLife 
escribi?:
> On Aug 3, 8:42?pm, "Gabriel Genellina"  wrote:
>> En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife   
>> escribi?:
>>
>> > I have installed python 2.6.2 in windows xp professional machine. I
>> > have set the following environment variables -- PYTHONPATH. It points
>> > to following windows folders: python root folder, the lib folder and
>> > lib-tk folder.
>>
>> Why? Did you read it somewhere? Usually there is no need to set the ?
>> PYTHONPATH variable at all; remove it.
>
> Setting PYTHONPATH environment variables is mentioned in Python docs.

Could you provide a link please? Setting PYTHONPATH should not be
necesary, and in fact it's a very bad idea. Environment variables are
global, but Python modules may depend on the Python version, architecture,
install location... By example, you may install a 64 bits Python 3.1
version *and* a 32 bits Python 2.5 version and they both can coexist
peacefully - but an extension module compiled for the former cannot be
used in the later version. You must build a separate library for each
version, and install them in two separate directories. But since the
PYTHONPATH variable is shared by all installations, which directory should
contain?
It's best not to use PYTHONPATH at all and rely on other alternatives
(like .pth files, that are searched relative to the current Python
executable, so different versions use different configuration files)

> I solved the issue temporarily by copying the gnutls related dlls to
> the path searched by python.exe

Glad to see you could finally fix it!

-- 
Gabriel Genellina



From robert.kern at gmail.com  Wed Aug  5 16:27:51 2009
From: robert.kern at gmail.com (Robert Kern)
Date: Wed, 05 Aug 2009 15:27:51 -0500
Subject: trouble with complex numbers
In-Reply-To: <24835436.post@talk.nabble.com>
References: <24821423.post@talk.nabble.com> 
	<24835436.post@talk.nabble.com>
Message-ID: 

On 2009-08-05 15:16, Dr. Phillip M. Feldman wrote:
> I am using Python 2.5, and most of the cmath functions are not yet available
> in this version.  Thanks!
>
> Phillip
>
> P.S. In your code, that should be x+= 0J
>
> P.P.S. I wish that the documentation indicated anything that is new.

It does.

http://docs.python.org/library/cmath#cmath.phase

"New in version 2.6."

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From malc0de.encrypt at gmail.com  Wed Aug  5 16:28:30 2009
From: malc0de.encrypt at gmail.com (MalC0de)
Date: Wed, 5 Aug 2009 13:28:30 -0700 (PDT)
Subject: Error on Attaching to the process while debugging
Message-ID: <21dbc649-2f82-4e4c-9777-c8a58c25a9e0@r2g2000yqm.googlegroups.com>

Hello there, I'm writting a debugger,
the problem is there no good interpretation ...

here's the codes:

my_debugger.py :

#!/usr/bin/env python
from ctypes import *
from my_debugger_defines import *
kernel32 = windll.kernel32
class debugger():
    def __init__(self):
	  self.h_process = None
	  self.pid = None
	  self.debugger_active = False
          pass
    def load(self,path_to_exe):
        creation_flags = DEBUG_PROCESS
        startupinfo = STARTUPINFO()
        process_information = PROCESSINFORMATION()
        startupinfo.dwFlags = 0x1
        startupinfo.wShowWindow = 0x0
        startupinfo.cb = sizeof(startupinfo)
        if kernel32.CreateProcessA(path_to_exe,
                                    None,
                                    None,
                                    None,
                                    None,
                                    creation_flags,
                                    None,
                                    None,
                                    byref(startupinfo),
                                    byref(process_information)):
                  print "[*]we have sucessfully launched the process"
                  print "[*]PID %d" % process_information.dwProcessId
                  self.h_process = self.open_process
(process_information.dwProcessId)
        else:
            print"[*]Error 0x%08x." % kernel32.GetLastError()

def Open_process(self,pid):
    h_process = kernel32.OpenProcess(PROCESS_ALL_ACCESS,pid,False)
    return h_process
def attach(self,pid):
        self.h_process = self.open_process(pid)
        # We attempt to attach to the process
        # if this fails we exit the call
        if kernel32.DebugActiveProcess(pid):
            self.debugger_active = True
            self.pid             = int(pid)

        else:
            print "[*] Unable to attach to the process."

def run(self):
    while self.debugger_active == True:
        self.get_debug_event()
def get_debug_event(self):
    debug_event = DEBUG_EVENT()
    continue_status = DBG_CONTINUE
    if kernel32.WaitForDebugEvent(byref(debug_event),INFINITE):
        raw_input("Press a key to continue ...")
    self.debugger_active = False
    kernel32.ContinueDebugEvent
(debug_event.dwProdcessid,debug_event.dwThreadId,continue_status)
    def detach(self):
        if kernel32.DeugActiveProcessStop(self.pid):
            print "[*]Finished debugging. exiting ..."
            return True
        else:
            print "there was an error"
            return false

it's already have a method named : Attach ...

ok, the next source ,
my_test.py which lead python to launching the calc.exe for testing
purpose .

my_test.py :

#!/usr/bin/python
import my_debugger
debugger = my_debugger.debugger()
pid = raw_input("Enter the PID of the process to attach to :")
debugger.attach(int(pid))
debugger.detach()

and finally the essential definitions into my_debugger_defines.py

#!/usr/bin/env python
from ctypes import *
WORD = c_ushort
DWORD = c_ulong
LPBYTE = POINTER(c_ubyte)
LPTSTR = POINTER(c_char)
HANDLE = c_void_p
DEBUG_PROCESS = 0x00000001
CREATE_NEW_CONSOLE = 0x00000010
class STARTUPINFO(Structure):
    _fielnds_ = [
        ("cb",                                  DWORD),
        ("lpReserved",                          LPTSTR),
        ("lpDesktop",                           LPTSTR),
        ("lpTitle",                             LPTSTR),
        ("dwX",                                 DWORD),
        ("dwY",                                 DWORD),
        ("dwXSize",                             DWORD),
        ("dwYSize",                             DWORD),
        ("dwXCountChars",                       DWORD),
        ("dwFillAttribute",                     DWORD),
        ("dwFlags",                             DWORD),
        ("wShowWindow",                          WORD),
        ("cbReserved2",                          WORD),
        ("lpReserved2",                        LPBYTE),
        ("hStdInput",                          HANDLE),
        ("hStdOutput",                         HANDLE),
        ("hStdError",                          HANDLE),
    ]
class PROCESSINFORMATION(Structure):
    _fields_ = [
        ("hProcess",                           HANDLE),
        ("hThread",                            HANDLE),
        ("dwProcessId",                         DWORD),
        ("dwThreadId",                          DWORD),
    ]

when you type : python my_test.py it must run without any problem, but
seems errors occures while interpretation :

Enter the PID of the process to attach to :212
Traceback (most recent call last):
  File "C:\python25\2\my_Test.py", line 5, in 
    debugger.attach(int(pid))
AttributeError: debugger instance has no attribute 'attach'

it's nasty shit !
the my_debugger is already has a definition for attach() ,

please help me up,

thanks ...


From jnoller at gmail.com  Wed Aug  5 16:28:45 2009
From: jnoller at gmail.com (Jesse Noller)
Date: Wed, 5 Aug 2009 13:28:45 -0700 (PDT)
Subject: Is this a bug in multiprocessing or in my script?
References: 
	<2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> 
	<74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> 
	<6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> 
	
Message-ID: <4a238650-45b0-4478-884f-257fa2d3e9ba@o32g2000yqm.googlegroups.com>

On Aug 5, 3:40?pm, sturlamolden  wrote:
> On 5 Aug, 21:36, sturlamolden  wrote:
>
> >http://svn.python.org/view/python/branches/release26-maint/Lib/multip...
>
> >http://svn.python.org/view/python/branches/release31-maint/Lib/multip...
>
> http://svn.python.org/view/python/trunk/Lib/multiprocessing/forking.p...

Since the bug was never filed in the tracker (it was sent to my
personal mail box, and I dropped it - sorry), I've filed a new one:

http://bugs.python.org/issue6653

In the future please use the bug tracker to file and track bugs with,
so things are not as lossy.

jesse


From massi_srb at msn.com  Wed Aug  5 16:30:27 2009
From: massi_srb at msn.com (Massi)
Date: Wed, 5 Aug 2009 13:30:27 -0700 (PDT)
Subject: Web page data and urllib2.urlopen
Message-ID: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>

Hi everyone, I'm using the urllib2 library to get the html source code
of web pages. In general it works great, but I'm having to do with a
financial web site which does not provide the souce code I expect. As
a matter of fact if you try:

import urllib2
res = urllib2.urlopen("http://www.marketwatch.com/story/mondays-
biggest-gaining-and-declining-stocks-2009-07-27")
page = res.read()
print page

you will see that the printed code is very different from the one
given, for example, by mozilla. Since I have really little knowledge
in html I can't even understand if this is a python or html problem.
Can anyone give me some help?
Thanks in advance.


From sturlamolden at yahoo.no  Wed Aug  5 16:35:02 2009
From: sturlamolden at yahoo.no (sturlamolden)
Date: Wed, 5 Aug 2009 13:35:02 -0700 (PDT)
Subject: Is this a bug in multiprocessing or in my script?
References: 
	<2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> 
	<74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> 
	<6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> 
	
Message-ID: <8d19bdd2-ac70-4fd0-bea3-56ab520048de@z31g2000yqd.googlegroups.com>

On 5 Aug, 22:07, Piet van Oostrum  wrote:

> Calling os.exit in a child process may be dangerous. It can cause
> unflushed buffers to be flushed twice: once in the parent and once in
> the child.

I assume you mean sys.exit. If this is the case, multiprocessing needs
a mechanism to chose between os._exit and sys.exit for child
processes. Calling os._exit might also be dangerous because it could
prevent necessary clean-up code from executing  (e.g. in C
extensions). I had a case where shared memory on Linux (System V IPC)
leaked due to os._exit. The deallocator for my extension type never
got to execute in child processes. The deallocator was needed to
release the shared segment when its reference count dropped to 0.
Changing to sys.exit solved the problem. On Windows there was no leak,
because the kernel did the reference counting.




From pavlovevidence at gmail.com  Wed Aug  5 16:35:23 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Wed, 5 Aug 2009 13:35:23 -0700 (PDT)
Subject: How to combine regexps?
References: 
Message-ID: 

On Aug 5, 1:09?pm, kj  wrote:
> One of the nice things one can do with Perl's regexp's is illustrated
> in the following example:
>
> my $gly = qr/gg[ucag]/i
> my $ala = qr/gc[ucag]/i;
> my $val = qr/gu[ucag]/i;
> my $leu = qr/uu[ag]|cu[ucag]/i;
> my $ile = qr/au[uca]/i;
>
> my $aliphatic = qr/$gly|$ala|$val|$leu|$ile/;
>
> In other words, one can build regular expressions by re-combining
> other regular expressions.
>
> Is there a way to do this with Python's regexps?

Your example is just string manipulation.

You're not combining regexps here, you are combining strings which you
(evidently) will soon use to create a regexp.

Yes, you can do that in Python as well, in exactly the same way, using
Python's string manipulation capabilities.


Carl Banks


From no.email at please.post  Wed Aug  5 16:36:07 2009
From: no.email at please.post (kj)
Date: Wed, 5 Aug 2009 20:36:07 +0000 (UTC)
Subject: How to combine regexps?
References: 
Message-ID: 

In  kj  writes:



>One of the nice things one can do with Perl's regexp's is illustrated
>in the following example:

>my $gly = qr/gg[ucag]/i
>my $ala = qr/gc[ucag]/i;
>my $val = qr/gu[ucag]/i;
>my $leu = qr/uu[ag]|cu[ucag]/i;
>my $ile = qr/au[uca]/i;

>my $aliphatic = qr/$gly|$ala|$val|$leu|$ile/;


>In other words, one can build regular expressions by re-combining
>other regular expressions.

>Is there a way to do this with Python's regexps?


OK, answering my own question here, it looks like the only way to
do this is to leave the "component" expressions as regular strings,
and combine those, before compiling them into regexps.

Easy enough.

kynn


From joncle at googlemail.com  Wed Aug  5 16:39:33 2009
From: joncle at googlemail.com (Jon Clements)
Date: Wed, 5 Aug 2009 13:39:33 -0700 (PDT)
Subject: Parsing Binary Structures; Is there a better way / What is your 
	way?
References: 
	<7x3a86gmfe.fsf@ruckus.brouhaha.com> 
	
	<7xr5vqw0v9.fsf@ruckus.brouhaha.com> 
	
Message-ID: <1211ccf7-1147-42de-ab62-3e5b33b09011@k19g2000yqn.googlegroups.com>

On 5 Aug, 20:41, "Martin P. Hellwig" 
wrote:
> Paul Rubin wrote:
> > "Martin P. Hellwig"  writes:
> >> Is there an advantage using shifts and masks over my kitchen type solution?
>
> > Weren't you complaining about the 8-to-1 expansion from turning each bit
> > to an ascii char?
>
> Yes you are (of course) right, my 'dream' solution would be something
> that accepts slice indeces on bit level. Your reasoning did reveal some
> flaws in my approach though ;-)
>
> --
> MPHhttp://blog.dcuktec.com
> 'If consumed, best digested with added seasoning to own preference.'

Ahh huh -- found it...

ID: DLT119
Desc: datasyzygy misc. development, production and accounts.
Date: 2008-12-09
File: pybits.py
"""
Implements a python level interface to reading bit fields with an
associated type. Fields are accessed via __getitem__ and must be a
valid python name. eg:

class MyStructure:
    a = BitField(4, int)
    b = BitField(6, int)
    c = BitField(2, int)
    d = BitField(36, str)
"""

Ummm, seems I left the rest pretty vague, but I'm guessing that's what
you're after, and I'm fairly curious to see what I wrote... mind you,
not too hard to write again now that's jogged my memory! (although
after a couple at the pub, not going to do it tonight!)

Cheers,

Jon.



From mensanator at aol.com  Wed Aug  5 16:40:28 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 13:40:28 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	
	
Message-ID: <87b655e8-937b-4f62-ad1e-5165d547a7bd@v20g2000yqm.googlegroups.com>

On Aug 5, 3:08?pm, Ethan Furman  wrote:
> Mensanator wrote:
>
> 
>
>
>
>
>
>
>
> > What does this mean?
>
> >>>>import turtle
> >>>>tooter = turtle.Turtle()
> >>>>*tooter*.tracer
>
> > Traceback (most recent call last):
> > ? File "", line 1, in 
> > ? ? tooter.tracer
> > AttributeError: 'Turtle' object has no attribute 'tracer'
>
> >>>>tooter.hideturtle()
> >>>>tooter.speed('fast')
> >>>>turtle.update()
> >>>>*turtle*.tracer
>
> > 
>
> > How did the tracer attribute appear out of thin air?
>
> Perhaps I am missing something (wouldn't surprise me!) but it seems that
> the first time you are looking for a tracer on 'tooter', and the second
> time you are looking for a tracer on 'turtle'. ?

Duh. I could have looked at that from now til the sun don't shine and
not seen it. And I even retyped it, no cut/paste.

> After *turtle.tracer*
> succeeds, does *tooter.tracer*?

No, that was my mistake. Too late now as the record is gone, but I
could have sworn I had the math exception first. That's what made
me go realize the tracing wasn't off which led me to add .screen.

Sounds like I should have gotten the attribute error first.

Maybe I did and am mis-remembering it. Usually, I don't start keeping
notes at first because I'm not expecting failure.

>
> ~Ethan~



From sturlamolden at yahoo.no  Wed Aug  5 16:41:53 2009
From: sturlamolden at yahoo.no (sturlamolden)
Date: Wed, 5 Aug 2009 13:41:53 -0700 (PDT)
Subject: Is this a bug in multiprocessing or in my script?
References: 
	<2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> 
	<74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> 
	<6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> 
	 
	<4a238650-45b0-4478-884f-257fa2d3e9ba@o32g2000yqm.googlegroups.com>
Message-ID: <54cdf823-7b2c-4ff8-b1f2-b8091a7daeb8@d32g2000yqh.googlegroups.com>

On 5 Aug, 22:28, Jesse Noller  wrote:

> http://bugs.python.org/issue6653
>
> In the future please use the bug tracker to file and track bugs with,
> so things are not as lossy.

Ok, sorry :)

Also see Piet's comment here. He has a valid case against sys.exit in
some cases. Thus it appears that both ways of shutting down child
processes might be dangerous: If we don't want buffers to flush we
have to use os._exit. If we want clean-up code to execute we have to
use sys.exit. If we want both we are screwed. :(






From netgraviton at gmail.com  Wed Aug  5 16:42:40 2009
From: netgraviton at gmail.com (WordStream)
Date: Wed, 5 Aug 2009 13:42:40 -0700 (PDT)
Subject: [ATTN] Sr. Software Development Engineer
Message-ID: 

Postion Title - Sr. Software Development Engineer

Job Responsibilities
The Sr. Software Development Engineer will be responsible for the
design, development and implementation of the award-winning WordStream
suite of products.

Development is presently done primarily using Python on the server and
Adobe Flex/HTML/AJAX as a Rich Internet Application (RIA) frontend.
However, like everything in the computing industry, we're constantly
evolving how we work.  We're always on the lookout for newer and
better technologies, and as a result, the technologies we use tomorrow
are likely to be different.

This is a full-time telecommute position.  The Sr. Software
Development Engineer can choose to work in our Boston office, or they
can choose to work from at home or from any location in the world.

Qualifications
The Sr. Software Development Engineer will be an individual who has
top-notch coding skills, and can demonstrate an aptitude to learn new
technologies.

Prior experience with any specific technologies (e.g., Python or Adobe
Flex) is not a requirement; we're looking for people with a history of
leveraging any technology to create masterpieces.

Prior experience working on web analytics applications, search
engines, content management systems or other Web publishing systems is
a plus.

Please note, only candidates with a bachelor's degree in computer
science or engineering, or, a very substantial amount of related
technical coursework and work experience in a related field will be
considered.

Related Skills
Python, Adobe Flex, Structured Query Language (SQL), Object-Oriented
Programming, SQLite, Open-Source software development, Git, Object-
Relational Mapping (ORM), Postgres SQL, AJAX, HTML, Search Engine
Optimization (SEO) or Search Engine Marketing (SEM)

Compensation
?	Full-time salaried position, with competitive salary.
?	Position includes equity participation and comprehensive benefits
(healthcare, vision and dental).
?	Flexibility to work from any location, worldwide.

About WordStream
Founded in August 2008 by experienced search marketers and software
experts, WordStream has developed the first database-driven Keyword
Management Software solution for pay-per-click advertisers and
agencies. With the decline in print and traditional media, companies
of every size are flocking to the Internet, search engine marketing
and, specifically, Google AdWords to advertise their products and
services. But mastering even the basics of search engine marketing
isn?t easy ? until now! From keyword discovery to ad group creation,
WordStream helps pay-per-click advertisers build the solid keyword
foundation required for PPC success. WordStream is backed by Sigma +
Partners. For more information please visit: http://www.wordstream.com

How To Apply
To apply for the Sr. Software Development Engineer position, send a
resume to jobs at WordStream dot com.


From rogerb at rogerbinns.com  Wed Aug  5 16:45:09 2009
From: rogerb at rogerbinns.com (Roger Binns)
Date: Wed, 05 Aug 2009 13:45:09 -0700
Subject: Do anyone here use Python *embedded* in a database?
In-Reply-To: 
References: 
Message-ID: 

Jonathan Fine wrote:
> anyone here ever used the Python *embedded* in a database server.

There is also the case of using SQLite where it shares the same process as
your Python code (and nothing else) and is a standard part of the Python
library.

You can add your own functions and collations and if using APSW then you can
also go way further than a regular database and add virtual tables and
virtual storage.

SQLite generally outperforms database servers since there is no cross
process or network communication until you get to larger workloads and/or
concurrent database access which database servers are more tuned for.

Roger



From jnoller at gmail.com  Wed Aug  5 16:50:03 2009
From: jnoller at gmail.com (Jesse Noller)
Date: Wed, 5 Aug 2009 13:50:03 -0700 (PDT)
Subject: Is this a bug in multiprocessing or in my script?
References: 
	<2f26a239-2f06-40f8-b0f0-d2e55edbe5e5@g31g2000yqc.googlegroups.com> 
	<74bd61ff-c666-4f78-9441-5422e858ea0b@z31g2000yqd.googlegroups.com> 
	<6e700877-2723-4cae-a5b1-708475860b98@g31g2000yqc.googlegroups.com> 
	 
	<4a238650-45b0-4478-884f-257fa2d3e9ba@o32g2000yqm.googlegroups.com> 
	<54cdf823-7b2c-4ff8-b1f2-b8091a7daeb8@d32g2000yqh.googlegroups.com>
Message-ID: 

On Aug 5, 4:41?pm, sturlamolden  wrote:
> On 5 Aug, 22:28, Jesse Noller  wrote:
>
> >http://bugs.python.org/issue6653
>
> > In the future please use the bug tracker to file and track bugs with,
> > so things are not as lossy.
>
> Ok, sorry :)
>
> Also see Piet's comment here. He has a valid case against sys.exit in
> some cases. Thus it appears that both ways of shutting down child
> processes might be dangerous: If we don't want buffers to flush we
> have to use os._exit. If we want clean-up code to execute we have to
> use sys.exit. If we want both we are screwed. :(

Comments around this bug should go in the bug report - again, so we
don't loose them. I do not personally subscribe to this group , so
it's very easy to miss things.

jesse


From mensanator at aol.com  Wed Aug  5 17:03:05 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 14:03:05 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
Message-ID: 

On Aug 5, 12:56?pm, Gregor Lingl  wrote:
> Mensanator schrieb:
>
>
>
>
>
> >> It didn't form 2.5 to 2.6 (at least not intentionally). But with the
> >> indroduction of the TurtleScreen class and the Screen class/object
> >> (singleton) a few of the turtle methods were also implemented as screen
> >> methods and as turtle methods declared deprecated (see docs of Python
> >> 2.6). These deprecated turtle methods do not occur as turtle methods any
> >> more in Python 3.x.
>
> > More info.
>
> > Yes, there is no tracer attribute...when the object is created.
>
> > But watch this (Python 3.1):
>
> >>>> import turtle
> >>>> tooter = turtle.Turtle()
> >>>> tooter.tracer
> > Traceback (most recent call last):
> > ? File "", line 1, in 
> > ? ? tooter.tracer
> > AttributeError: 'Turtle' object has no attribute 'tracer'
> >>>> tooter.hideturtle()
> >>>> tooter.speed('fast')
> >>>> turtle.update()
> >>>> turtle.tracer
> > 
>
> > Now, after setting hide, speed, update, a tracer exists.
>
> No,

Yeah, I mistyped my example, sorry about that. I thought sure
it was the math error that lead me to the tracer issue, but that
might have been a mistake.

>
> Nevertheless I'd like to see a working Python 2.5 version of your script.

I've commented out the parts that v2.5 doesn't have.
So the pen is still down and I have no .dot function,
but the gotos appear to still work as evidenced by
the large black square it now draws.

With tracing on in 2.5, I see the turtle move around
the square. With tracing off, I still the the square
outined, but without a turtle and much faster.

With 3.1, the screen is completely blank for 3-4 seconds and appears
all at once when it's done.

import gmpy

##   (even) hi----|
##                |
##                lo (odd)
## or
##
##   (even) lo
##           |
##           |
##           ----hi (odd)
##
##
##
##

import turtle

tooter = turtle.Turtle()

#tooter.hideturtle()
tooter.speed('fast')
#turtle.update()
tooter.tracer(False)
#tooter.penup()
tooter.color('black')

s = ['1','0']
while len(s[0])<10000:
    s = [''.join(s), s[0]]


origin = [0,0]
if s[0] == '0':
  tooter.goto(origin)
  #tooter.dot(1)
if s[1] == '0':
  tooter.goto([1,0])
  #tooter.dot(1)

print len(s[0])

for i,j in enumerate(s[0]):
  the_coord=[]
  cur_root = gmpy.sqrt(i)
  lo__root = gmpy.sqrt(i)**2
  hi__root = (gmpy.sqrt(i)+1)**2

  if hi__root%2==0:
    side = 'northeast'
  else:
    side = 'southwest'

  elbow = (hi__root - lo__root)/2 + lo__root + 1

  if i>= elbow:
    side_len = i - elbow
    elbow_plus = True
  else:
    side_len = elbow - i
    elbow_plus = False

  if side == 'northeast':
    elbow_offset = [(gmpy.sqrt(elbow)-1)/2 +1,-((gmpy.sqrt(elbow)-1)/2
+1)]
  else:
    elbow_offset = [-((gmpy.sqrt(elbow)-1)/2 +1),((gmpy.sqrt(elbow)-1)/
2 +1)]

  elbow_coord = [origin[0]+elbow_offset[0],origin[1]+elbow_offset[1]]

  if i != hi__root and i != lo__root:
    if i == elbow:
      the_coord = elbow_coord
    else:
      if elbow_plus:
        if side == 'northeast':
          the_coord = [elbow_coord[0]-side_len,elbow_coord[1]]
        else:
          the_coord = [elbow_coord[0]+side_len,elbow_coord[1]]
      else:
        if side == 'northeast':
          the_coord = [elbow_coord[0],elbow_coord[1]+side_len]
        else:
          the_coord = [elbow_coord[0],elbow_coord[1]-side_len]
  else:
    if i % 2 == 0:  # even square
      n = gmpy.sqrt(i)/2 - 1
      the_coord = [-n, -n-1]
    else:
      n = (gmpy.sqrt(i)-1)/2 - 1
      the_coord = [1+n, 1+n]
  if j == '0':
    tooter.goto(the_coord)
    #tooter.dot(2)
print 'done'

#turtle.update()
turtle.done()
print 'done'


>
> Regards,
> Gregor


From deets at nospam.web.de  Wed Aug  5 17:19:20 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Wed, 05 Aug 2009 23:19:20 +0200
Subject: access string data from within cython
In-Reply-To: 
References: <7dtt46F2e5osvU1@mid.uni-berlin.de>
	
Message-ID: <7dubaoF2e96rfU2@mid.uni-berlin.de>

Philip Semanchuk schrieb:
> 
> On Aug 5, 2009, at 1:16 PM, Diez B. Roggisch wrote:
> 
>> Hi,
>>
>> I'm trying to wrap a C-API which has a call that takes a void* and a 
>> size_t
>> as arguments.
>>
>> void foo(void *data, size_t length)
>>
>>
>> The wrapper is supposed to be called with a python (byte)string instance,
>> which might contain more than one '\0'-character.
>>
>> So how do I access the raw data of a string? I tried looking into the
>> buffer-protocol, but to be honest - that's beyond me, I don't see where
>> that is actually giving me access to the real data.
> 
> Hi Diez,
> Would ctypes.create_string_buffer() work for you?

I'm not using ctypes because I want a distributable egg with static 
linkage. ctypes can't help there afaik.

Diez


From contact at xavierho.com  Wed Aug  5 17:22:44 2009
From: contact at xavierho.com (Xavier Ho)
Date: Thu, 6 Aug 2009 07:22:44 +1000
Subject: Subclassing Python's dict
In-Reply-To: 
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com>
	
Message-ID: <2d56febf0908051422h2cd0e58p1afce376895d5d1e@mail.gmail.com>

On Thu, Aug 6, 2009 at 5:23 AM, Joshua Kugler wrote:

> Are you referring to Python 3.0?  Python 2.6 does not have
> collections.UserDict
>
> j
>

Yes, I was.... sometimes it's hard to keep track what's not in 2.6 and in
3.1 for me, sorry. And thanks.

The ABC MutableMapping is still valid, though. I hope he gets it sorted out.


With a morning yawn,
Xavier
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From deets at nospam.web.de  Wed Aug  5 17:22:56 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Wed, 05 Aug 2009 23:22:56 +0200
Subject: access string data from within cython
In-Reply-To: <88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com>
References: <7dtt46F2e5osvU1@mid.uni-berlin.de>
	<88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com>
Message-ID: <7dubhgF2e96rfU3@mid.uni-berlin.de>

sturlamolden schrieb:
> On 5 Aug, 19:16, "Diez B. Roggisch"  wrote:
> 
>> void foo(void *data, size_t length)
>>
>> The wrapper is supposed to be called with a python (byte)string instance,
>> which might contain more than one '\0'-character.
>>
>> So how do I access the raw data of a string?
> 
> cdef extern void foo(void *data, int length)
> cdef char *data
> cdef int length
> bytestring = ... #whatever
> 
> rawdata =  bytestring
> length =  len(bytestring)

And that gives me the *full* bytestring, not only until the first zero? 
I can't try that right now (not at work anymore), but if it's that easy, 
that would be great.

Diez


From philip at semanchuk.com  Wed Aug  5 17:30:22 2009
From: philip at semanchuk.com (Philip Semanchuk)
Date: Wed, 5 Aug 2009 17:30:22 -0400
Subject: access string data from within cython
In-Reply-To: <7dubaoF2e96rfU2@mid.uni-berlin.de>
References: <7dtt46F2e5osvU1@mid.uni-berlin.de>
	
	<7dubaoF2e96rfU2@mid.uni-berlin.de>
Message-ID: <84411DCB-CD09-4EE1-B50E-51D005748BE1@semanchuk.com>


On Aug 5, 2009, at 5:19 PM, Diez B. Roggisch wrote:

> Philip Semanchuk schrieb:
>> On Aug 5, 2009, at 1:16 PM, Diez B. Roggisch wrote:
>>> Hi,
>>>
>>> I'm trying to wrap a C-API which has a call that takes a void* and  
>>> a size_t
>>> as arguments.
>>>
>>> void foo(void *data, size_t length)
>>>
>>>
>>> The wrapper is supposed to be called with a python (byte)string  
>>> instance,
>>> which might contain more than one '\0'-character.
>>>
>>> So how do I access the raw data of a string? I tried looking into  
>>> the
>>> buffer-protocol, but to be honest - that's beyond me, I don't see  
>>> where
>>> that is actually giving me access to the real data.
>> Hi Diez,
>> Would ctypes.create_string_buffer() work for you?
>
> I'm not using ctypes because I want a distributable egg with static  
> linkage. ctypes can't help there afaik.

Sorry, I read cython as CPython.




From xahlee at gmail.com  Wed Aug  5 17:44:49 2009
From: xahlee at gmail.com (Xah Lee)
Date: Wed, 5 Aug 2009 14:44:49 -0700 (PDT)
Subject: Google sitemap generator in python gone?
Message-ID: <5982ba4d-668c-460f-a666-5d7cbe697883@x25g2000prf.googlegroups.com>

google used to have a sitemap generator written in python, at:
 https://www.google.com/webmasters/tools/docs/en/sitemap-generator.html

but the url is gone. It seems the current version is moved here:
http://code.google.com/p/googlesitemapgenerator/
and is written in JavaScript.

is the old python version still available? or is there some official
doc about this change?

thanks.

  Xah
? http://xahlee.org/

?


From sturlamolden at yahoo.no  Wed Aug  5 17:51:12 2009
From: sturlamolden at yahoo.no (sturlamolden)
Date: Wed, 5 Aug 2009 14:51:12 -0700 (PDT)
Subject: access string data from within cython
References: <7dtt46F2e5osvU1@mid.uni-berlin.de>
	<88384285-0147-470d-943f-14cfaa79219f@t13g2000yqt.googlegroups.com>
	<7dubhgF2e96rfU3@mid.uni-berlin.de>
Message-ID: <71adfa33-faee-48d7-adb0-1403d8af4fd5@c14g2000yqm.googlegroups.com>

On 5 Aug, 23:22, "Diez B. Roggisch"  wrote:

> And that gives me the *full* bytestring, not only until the first zero?
> I can't try that right now (not at work anymore), but if it's that easy,
> that would be great.

It should, and if it does not it is a bug in Cython. The len()
function should work similarly in Python and Cython: It should just
call the object's __len__ method. Cython has no idea that your Python
object bytestring is a byte string, nor does Cython care.

>>> bs = '\x00'*10 # bytes string with 10 zeros
>>> len(bs)
10
>>> bs.__len__()
10



From joncle at googlemail.com  Wed Aug  5 17:55:02 2009
From: joncle at googlemail.com (Jon Clements)
Date: Wed, 5 Aug 2009 14:55:02 -0700 (PDT)
Subject: Google sitemap generator in python gone?
References: <5982ba4d-668c-460f-a666-5d7cbe697883@x25g2000prf.googlegroups.com>
Message-ID: <631e148d-9e26-4779-b76a-bd405f4525c8@c34g2000yqi.googlegroups.com>

On 5 Aug, 22:44, Xah Lee  wrote:
> google used to have a sitemap generator written in python, at:
> ?https://www.google.com/webmasters/tools/docs/en/sitemap-generator.html
>
> but the url is gone. It seems the current version is moved here:http://code.google.com/p/googlesitemapgenerator/
> and is written in JavaScript.
>
> is the old python version still available? or is there some official
> doc about this change?
>
> thanks.
>
> ? Xah
> ?http://xahlee.org/
>
> ?

How about asking Google, and not this list?

It's always good to see a funny troll on this list though...

Now please piddle off...


From martin.hellwig at dcuktec.org  Wed Aug  5 17:59:18 2009
From: martin.hellwig at dcuktec.org (Martin P. Hellwig)
Date: Wed, 05 Aug 2009 22:59:18 +0100
Subject: Google sitemap generator in python gone?
In-Reply-To: <631e148d-9e26-4779-b76a-bd405f4525c8@c34g2000yqi.googlegroups.com>
References: <5982ba4d-668c-460f-a666-5d7cbe697883@x25g2000prf.googlegroups.com>
	<631e148d-9e26-4779-b76a-bd405f4525c8@c34g2000yqi.googlegroups.com>
Message-ID: 

Jon Clements wrote:

> Now please piddle off...

I am guessing west-midlands? :-)

-- 
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'


From python at mrabarnett.plus.com  Wed Aug  5 18:03:11 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Wed, 05 Aug 2009 23:03:11 +0100
Subject: How to combine regexps?
In-Reply-To: 
References:  
Message-ID: <4A7A019F.3070205@mrabarnett.plus.com>

kj wrote:
> In  kj  writes:
> 
> 
> 
>> One of the nice things one can do with Perl's regexp's is illustrated
>> in the following example:
> 
>> my $gly = qr/gg[ucag]/i
>> my $ala = qr/gc[ucag]/i;
>> my $val = qr/gu[ucag]/i;
>> my $leu = qr/uu[ag]|cu[ucag]/i;
>> my $ile = qr/au[uca]/i;
> 
>> my $aliphatic = qr/$gly|$ala|$val|$leu|$ile/;
> 
> 
>> In other words, one can build regular expressions by re-combining
>> other regular expressions.
> 
>> Is there a way to do this with Python's regexps?
> 
> 
> OK, answering my own question here, it looks like the only way to
> do this is to leave the "component" expressions as regular strings,
> and combine those, before compiling them into regexps.
> 
> Easy enough.
> 
A compiled regular expression has 'pattern' and 'flags' attributes, so
you can get the original parameters which were used to create it if a
function is given just the compiled regular expression. Might be useful.


From mensanator at aol.com  Wed Aug  5 18:31:17 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 15:31:17 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
	
Message-ID: 

I fixed this to produce the actual image I'm looking
for instead of that stupid black square. All I did was
use up() & dowm() in place of penup(), pendown() and
replace dot(2) with forward(1).

I'll be posting a followup report later.


import gmpy

##   (even) hi----|
##                |
##                lo (odd)
## or
##
##   (even) lo
##           |
##           |
##           ----hi (odd)
##
##
##
##

import turtle

tooter = turtle.Turtle()

#tooter.hideturtle()
tooter.speed('fast')
#turtle.update()
tooter.tracer(False)
#tooter.penup()
tooter.up()
tooter.color('black')

s = ['1','0']
while len(s[0])<10000:
    s = [''.join(s), s[0]]


origin = [0,0]
if s[0] == '0':
  tooter.goto(origin)
  #tooter.dot(1)
  tooter.down()
  tooter.forward(1)
  tooter.up()
if s[1] == '0':
  tooter.goto([1,0])
  #tooter.dot(1)
  tooter.down()
  tooter.forward(1)
  tooter.up()

print len(s[0])

for i,j in enumerate(s[0]):
  the_coord=[]
  cur_root = gmpy.sqrt(i)
  lo__root = gmpy.sqrt(i)**2
  hi__root = (gmpy.sqrt(i)+1)**2

  if hi__root%2==0:
    side = 'northeast'
  else:
    side = 'southwest'

  elbow = (hi__root - lo__root)/2 + lo__root + 1

  if i>= elbow:
    side_len = i - elbow
    elbow_plus = True
  else:
    side_len = elbow - i
    elbow_plus = False

  if side == 'northeast':
    elbow_offset = [(gmpy.sqrt(elbow)-1)/2 +1,-((gmpy.sqrt(elbow)-1)/2
+1)]
  else:
    elbow_offset = [-((gmpy.sqrt(elbow)-1)/2 +1),((gmpy.sqrt(elbow)-1)/
2 +1)]

  elbow_coord = [origin[0]+elbow_offset[0],origin[1]+elbow_offset[1]]

  if i != hi__root and i != lo__root:
    if i == elbow:
      the_coord = elbow_coord
    else:
      if elbow_plus:
        if side == 'northeast':
          the_coord = [elbow_coord[0]-side_len,elbow_coord[1]]
        else:
          the_coord = [elbow_coord[0]+side_len,elbow_coord[1]]
      else:
        if side == 'northeast':
          the_coord = [elbow_coord[0],elbow_coord[1]+side_len]
        else:
          the_coord = [elbow_coord[0],elbow_coord[1]-side_len]
  else:
    if i % 2 == 0:  # even square
      n = gmpy.sqrt(i)/2 - 1
      the_coord = [-n, -n-1]
    else:
      n = (gmpy.sqrt(i)-1)/2 - 1
      the_coord = [1+n, 1+n]
  if j == '0':
    tooter.goto(the_coord)
    #tooter.dot(2)
    tooter.down()
    tooter.forward(1)
    tooter.up()
print 'done'

#turtle.update()
turtle.done()
print 'done'


From ryan at rfk.id.au  Wed Aug  5 18:33:14 2009
From: ryan at rfk.id.au (Ryan Kelly)
Date: Thu, 06 Aug 2009 08:33:14 +1000
Subject: ANN:  extprot 0.1.1
Message-ID: <1249511594.4180.9.camel@durian>


Hi All,


Sorry if you get this twice, it seems to have gotten lost on its way
through python-announce.

I'm pleased to announce the first release of the "extprot" python
module.  Extprot implements a compact, efficient, extensible and
language-neutral object serialisation protocol.

License:      MIT
Downloads:    http://pypi.python.org/pypi/extprot/
Source code:  http://github.com/rfk/extprot/tree/master


You can think of extprot as something akin to Google's protocol buffers,
with a few extra bytes of serialisation overhead and a Python binding
that doesn't have nearly as many rough edges.  For example:

      * It's a stand-alone python module, packaged and distributed in
        the standard fashion.
      * It's friendly to dynamic package management tools like pip.
      * It works exclusively with standard Python objects. Declared a
        list field? It's a native list object.
      * You don't need to compile your protocol definitions.


More on the extprot format itself is here:

   http://eigenclass.org/R2/writings/extprot-extensible-protocols-intro

More on my motivations for this package here, if you're interested:

    http://www.rfk.id.au/blog/entry/new-python-module-extprot


Enjoy!


    Ryan

-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
ryan at rfk.id.au        |  http://www.rfk.id.au/ramblings/gpg/ for details

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 204 bytes
Desc: This is a digitally signed message part
URL: 

From steve at REMOVE-THIS-cybersource.com.au  Wed Aug  5 19:04:55 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 05 Aug 2009 23:04:55 GMT
Subject: trouble with complex numbers
References: <24821423.post@talk.nabble.com> 
	<24835436.post@talk.nabble.com>
	
Message-ID: <028a00b4$0$5185$c3e8da3@news.astraweb.com>

On Wed, 05 Aug 2009 15:27:51 -0500, Robert Kern wrote:

> On 2009-08-05 15:16, Dr. Phillip M. Feldman wrote:
>> I am using Python 2.5, and most of the cmath functions are not yet
>> available in this version.  Thanks!
>>
>> Phillip
>>
>> P.S. In your code, that should be x+= 0J
>>
>> P.P.S. I wish that the documentation indicated anything that is new.
> 
> It does.
> 
> http://docs.python.org/library/cmath#cmath.phase
> 
> "New in version 2.6."


Furthermore, every release comes with a What's New document:

http://docs.python.org/whatsnew/index.html




-- 
Steven


From lanyjie at yahoo.com  Wed Aug  5 19:05:41 2009
From: lanyjie at yahoo.com (Yingjie Lan)
Date: Wed, 5 Aug 2009 16:05:41 -0700 (PDT)
Subject: using expy to extend python
Message-ID: <871540.68601.qm@web54204.mail.re2.yahoo.com>


Hi,

The expy project provides an express way to extend Python. After some careful considerations, I came up with some reasons for expy (this is not an exhaustive list):

(I). WYSIWYG. The expy project enables you to write your module in Python the way your extension would be (WYSIWYG), and meanwhile write your implementation in pure C. You specify your modules, functions, methods, classes, and even their documentations the usual way of writing your Python correspondences. Then your provide your implementation to the functions/methods by returning a multi-line string. By such an arrangement, everything falls in its right place, and your extension code becomes easy to read and maintain. Also, the generated code is very human-friendly.

(II). You only provide minimal information to indicate your intension of how your module/class would function in Python. So your extension is largely independent from the Python extension API. As your interaction with the Python extension API is reduced to minimal (you only care about the functionality and logic), it is then possible that your module written in expy can be independent of changes in the extension API.

(III). The building and setup of your project can be automatically done with the distutil tool. In the tutorial, there are ample examples on how easily this is achieved.

(IV). Very light weight. The expy tool is surprisingly light weight dispite of its powerful ability, as it is written in pure Python. There is no parser or compiler for code generation, but rather the powerful reflexion mechanism of Python is exploited in a clever way to generate human-friendly codes. Currently, generating code in C is supported, however, the implementation is well modularized and code generation in other languages such as Java and C++ should be easy.

While there are already a couple of other projects trying to simply this task with different strategies, such as Cython, Pyrex and modulator, this project is unique and charming in its own way. All you need is the WYSIWYG Python file for your module extension, then expy takes care of everything else. What follows in this documentation is on how to extend Python in C using expy-cxpy: the module expy helps define your module, while module cxpy helps generate C codes for your defined module.

For more information about expy, please visit its homepage at: http://expy.sf.net/

Cheers,

Yingjie



      


From Samnsparky at gmail.com  Wed Aug  5 19:12:09 2009
From: Samnsparky at gmail.com (Sparky)
Date: Wed, 5 Aug 2009 16:12:09 -0700 (PDT)
Subject: Two Dimensional Array + ctypes
Message-ID: <79d2b3e3-b049-4d70-a56b-6e7f3ea2fa86@e27g2000yqm.googlegroups.com>

Hello! I am trying to call this method:

long _stdcall AIBurst(long *idnum,
			 long demo,
			 long stateIOin,
			 long updateIO,
			 long ledOn,
			 long numChannels,
			 long *channels,
			 long *gains,
			 float *scanRate,
			 long disableCal,
			 long triggerIO,
			 long triggerState,
			 long numScans,
			 long timeout,
			 float (*voltages)[4],
			 long *stateIOout,
			 long *overVoltage,
			 long transferMode);

I am having some problems with that  float (*voltages)[4]. Here is
what I tried:

def aiBurst(self, channels, scanRate, numScans, idNum=None, demo=0,
stateIOin=[0, 0, 0, 0], updateIO=0, ledOn=0, gains=[0, 0, 0, 0],
disableCal=0, triggerIO=0, triggerState=0, timeout=1, transferMode=0):

        if idNum is None:
            idNum = self.id

        idNum = ctypes.c_long(idNum)

        numChannels = len(channels)

        stateIOArray = listToCArray(stateIOin, ctypes.c_long)
        channelsArray = listToCArray(channels, ctypes.c_long)
        gainsArray = listToCArray(gains, ctypes.c_long)
        scanRate = ctypes.c_float(scanRate)
        pointerArray = (ctypes.c_void_p * 4)
        voltages = pointerArray(ctypes.cast(ctypes.pointer
((ctypes.c_long * 4096)()), ctypes.c_void_p), ctypes.cast
(ctypes.pointer((ctypes.c_long * 4096)()), ctypes.c_void_p),
ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)()),
ctypes.c_void_p), ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)
()), ctypes.c_void_p))
        stateIOout = (ctypes.c_long * 4096)()
        overVoltage = ctypes.c_long(999)

        staticLib.AIBurst(ctypes.byref(idNum), demo, stateIOArray,
updateIO, ledOn, numChannels, ctypes.byref(channelsArray), ctypes.byref
(gainsArray), ctypes.byref(scanRate), disableCal, triggerIO,
triggerState, numScans, timeout, ctypes.byref(voltages), ctypes.byref
(stateIOout), ctypes.byref(overVoltage), transferMode)

The program runs but the values that come back in the array are not
right. However, I am not sure if I am passing the array or if I am
just not reading them well afterwards. What is the best way to put
this in and what is the best way to cast it and read it back?

Thanks,
Sam


From nad at acm.org  Wed Aug  5 19:12:10 2009
From: nad at acm.org (Ned Deily)
Date: Wed, 05 Aug 2009 16:12:10 -0700
Subject: Install setup tools for 2.6
References: <373cf0740908051131gacaf77apba48fa40e929f491@mail.gmail.com>
Message-ID: 

In article 
<373cf0740908051131gacaf77apba48fa40e929f491 at mail.gmail.com>,
 Jeremy Cowles  wrote:
> Ok, I feel like this is a really stupid question, but how do you install
> setup tools for Python 2.6 under windows?
> The only format is .egg which requires setup tools to install, doesn't it?

http://pypi.python.org/pypi/setuptools#id1

-- 
 Ned Deily,
 nad at acm.org



From mensanator at aol.com  Wed Aug  5 19:16:10 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 16:16:10 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
	
	
Message-ID: <49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com>

On Aug 5, 5:31?pm, Mensanator  wrote:
> I fixed this to produce the actual image I'm looking
> for instead of that stupid black square. All I did was
> use up() & dowm() in place of penup(), pendown() and
> replace dot(2) with forward(1).
>
> I'll be posting a followup report later.
>

http://www.mensanator.com/mensanator/PythonTurtle/turtle.htm


From ethan at stoneleaf.us  Wed Aug  5 19:29:17 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Wed, 05 Aug 2009 16:29:17 -0700
Subject: Programming by Contract
Message-ID: <4A7A15CD.9090306@stoneleaf.us>

Greetings!

I have seen posts about the assert statement and PbC (or maybe it was 
DbC), and I just took a very brief look at pycontract 
(http://www.wayforward.net/pycontract/) and now I have at least one 
question:  Is this basically another way of thinking about unit testing, 
or is the idea of PbC more along the lines of *always* checking the 
input/output of functions to ensure they are correct?  (*Contstant 
vigilance!* as Prof Moody would say ;)

I know asserts can be turned off, so they obviously won't work for the 
latter case, and having seen the sample of pycontract it seems it only 
does its thing during debugging.

So is Design (Programming) by Contract a fancy way of saying "Document 
your inputs/outputs!" or is there more to it?

~Ethan~


From wolfgang at rohdewald.de  Wed Aug  5 19:48:36 2009
From: wolfgang at rohdewald.de (Wolfgang Rohdewald)
Date: Thu, 6 Aug 2009 01:48:36 +0200
Subject: using expy to extend python
In-Reply-To: <871540.68601.qm@web54204.mail.re2.yahoo.com>
References: <871540.68601.qm@web54204.mail.re2.yahoo.com>
Message-ID: <200908060148.36696.wolfgang@rohdewald.de>

On Thursday 06 August 2009, Yingjie Lan wrote:
> For more information about expy, please visit its homepage at:
> http://expy.sf.net/

looks very interesting, bookmarked.

In your example class mate, def rename looks wrong:
if malloc fails, the previous name should probably not
be replaced by an empty string?

-- 
Wolfgang


From macmanes at gmail.com  Wed Aug  5 19:54:46 2009
From: macmanes at gmail.com (PeroMHC)
Date: Wed, 5 Aug 2009 16:54:46 -0700 (PDT)
Subject: remove last 76 letters from string
Message-ID: 

Hi All, So here is the problem... I have a FASTA file (used for DNA
analyses) that looks like this:

...
>gnl|SRA|SRR019045.10.1 SL-XAY_956090708:2:1:0:1028.1 length=152
NCTTTTTTTATTTTTTGTATAAATGAAGTTTCACTATATCGGACGAGCGGTTCAGCAGTCATTCCGAGAC
CGATATAGTGAAACTTCATTTCTACAAAAANTACCAAACGTCGCTCGGCAGAGCGTCGTGTTGGGCAAGA
GAGTAGCACTCG
>gnl|SRA|SRR019045.11.1 SL-XAY_956090708:2:1:0:1151.1 length=152
NGGTNTGGNNNNCNCCNTNCTNCNNCNTCANCCTCCNGTCNCANNCCNCNTNNNNNCNNNNNCNNTNCTT
CTNCNNTCTCCATTCCTTCTTNATAGCCTGCTCCANCGCACGTTGAACCTTCTGCACCACGAACGCACTC
ACACCACTCATC
>gnl|SRA|SRR019045.12.1 SL-XAY_956090708:2:1:0:1197.1 length=152
NGTCGGGTCTTCGCTATCACTGGACTGCTCCCATCAGCTATAGGTCCTCCCCGCCACACCCCATGCCCAC
CGCCTATCCACGTCTGTCACAACCTCATACATCAGACAGTCACACTTACCAACATATCCAAGCACCTCAA
GCAACACATCAT
...

This snippet represents 3 individual DNA sequences. Each sequences is
identified by the line starting with >
The complete file has about 10 million individual sequences.

A simple enough problem, I want to read in this data, and cut out the
last 76 letters (nucleotides) from each individual sequence and send
them to a new txt file with a similar format.

Any help on how to do this would be appreciated.
Thanks!


From zuo at chopin.edu.pl  Wed Aug  5 20:23:06 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Thu, 06 Aug 2009 02:23:06 +0200
Subject: remove last 76 letters from string
In-Reply-To: 
References: 
Message-ID: 

Dnia 06-08-2009 o 01:54:46 PeroMHC  wrote:

> This snippet represents 3 individual DNA sequences. Each sequences is
> identified by the line starting with >
> The complete file has about 10 million individual sequences.
>
> A simple enough problem, I want to read in this data, and cut out the
> last 76 letters (nucleotides) from each individual sequence and send
> them to a new txt file with a similar format.

If I understand correctly you want sth like this:


with open(path_to_the_input_file) as fasta:
     with open(path_to_the_input_file) as nucleotides:
	for seq in fasta:
             print >>nucleotides, '> foo bar length=76'
             print >>nucleotides, seq[-76]


Cheers,
*j

-- 
Jan Kaliszewski (zuo) 


From zuo at chopin.edu.pl  Wed Aug  5 20:24:22 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Thu, 06 Aug 2009 02:24:22 +0200
Subject: remove last 76 letters from string [sorry, errata]
In-Reply-To: 
References: 
Message-ID: 

Dnia 06-08-2009 o 01:54:46 PeroMHC  wrote:

> This snippet represents 3 individual DNA sequences. Each sequences is
> identified by the line starting with >
> The complete file has about 10 million individual sequences.
>
> A simple enough problem, I want to read in this data, and cut out the
> last 76 letters (nucleotides) from each individual sequence and send
> them to a new txt file with a similar format.

If I understand correctly you want sth like this:


with open(path_to_the_input_file) as fasta:
       with open(path_to_the_output_file) as nucleotides:
	for seq in fasta:
               print >>nucleotides, '> foo bar length=76'
               print >>nucleotides, seq[-76]


Cheers,
*j

-- 
Jan Kaliszewski (zuo) 


From python at mrabarnett.plus.com  Wed Aug  5 20:26:22 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 01:26:22 +0100
Subject: String to valid Python identifier
In-Reply-To: 
References: 
Message-ID: <4A7A232E.1060402@mrabarnett.plus.com>

?????? ??????????? wrote:
> Is there any easy function in the stdlib to convert any random string in 
> a valid Python identifier .. possibly by replacing non-valid characters 
> with _ ?
> 
> Python 2.x only, so no need to do Unicode.
> 
Lookup the 'maketrans' function in the 'string' module and the
'translate' method of the 'str' class.


From python at mrabarnett.plus.com  Wed Aug  5 20:32:22 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 01:32:22 +0100
Subject: remove last 76 letters from string
In-Reply-To: 
References: 
Message-ID: <4A7A2496.4080808@mrabarnett.plus.com>

PeroMHC wrote:
> Hi All, So here is the problem... I have a FASTA file (used for DNA
> analyses) that looks like this:
> 
> ...
>> gnl|SRA|SRR019045.10.1 SL-XAY_956090708:2:1:0:1028.1 length=152
> NCTTTTTTTATTTTTTGTATAAATGAAGTTTCACTATATCGGACGAGCGGTTCAGCAGTCATTCCGAGAC
> CGATATAGTGAAACTTCATTTCTACAAAAANTACCAAACGTCGCTCGGCAGAGCGTCGTGTTGGGCAAGA
> GAGTAGCACTCG
>> gnl|SRA|SRR019045.11.1 SL-XAY_956090708:2:1:0:1151.1 length=152
> NGGTNTGGNNNNCNCCNTNCTNCNNCNTCANCCTCCNGTCNCANNCCNCNTNNNNNCNNNNNCNNTNCTT
> CTNCNNTCTCCATTCCTTCTTNATAGCCTGCTCCANCGCACGTTGAACCTTCTGCACCACGAACGCACTC
> ACACCACTCATC
>> gnl|SRA|SRR019045.12.1 SL-XAY_956090708:2:1:0:1197.1 length=152
> NGTCGGGTCTTCGCTATCACTGGACTGCTCCCATCAGCTATAGGTCCTCCCCGCCACACCCCATGCCCAC
> CGCCTATCCACGTCTGTCACAACCTCATACATCAGACAGTCACACTTACCAACATATCCAAGCACCTCAA
> GCAACACATCAT
> ...
> 
> This snippet represents 3 individual DNA sequences. Each sequences is
> identified by the line starting with >
> The complete file has about 10 million individual sequences.
> 
> A simple enough problem, I want to read in this data, and cut out the
> last 76 letters (nucleotides) from each individual sequence and send
> them to a new txt file with a similar format.
> 
> Any help on how to do this would be appreciated.
> Thanks!

If the input file is large then you can reduce the amount of memory
needed by reading the input file a line at a time by iterating over the
file object:

     input_file = open(input_path)
     for line in input_file:
         ...
     input_file.close()

Each line will end with '\n', so use the 'rstrip' method to remove it,
and then slice the last 76 characters:

     last_part = line.rstrip()[-76 : ]


From darkneter at gmail.com  Wed Aug  5 20:39:52 2009
From: darkneter at gmail.com (NighterNet)
Date: Wed, 5 Aug 2009 17:39:52 -0700 (PDT)
Subject: sqlite3 gui
Message-ID: <3d2c4f7a-9d9b-4aff-9de1-141ecf4327de@x6g2000prc.googlegroups.com>

This took a while to get a gui working. I am new at this coding.

This work with sqlite3 Python Version: 3.1.0. The older version
doesn't work.

#!/usr/local/bin/python
'''
    This is for basic database access to view the information.
Python version: 3.1.0

Features:
-view database.
-run script
-update row
-delete row
-insert row

To do list:
-delete table
-create table
-export database
-import database
-primary id need to able to insert to the table
-delete table row
-refresh data

Note:
-It doesn't remove the GUI
-It bit buggy.
-Python version: 3.0.1 -Doesn't support the gui

execute script without '"' ->  INSERT INTO member (user, password)
VALUES( "admin", "admin")
'''

from tkinter import *
from tkinter import ttk
from tkinter import tix
import sqlite3 as sqlite
import re

DATABASE = 'nameofdatabasefile.db'
title = "Sqlite3 Database";

db = sqlite.connect(DATABASE);
cur = db.cursor();

print("#==============================#")
print("# Python Version: 3.1.0        #")
print("# sqlite3                      #")
print("#==============================#")

class Application(Frame):
    #label_serverstatus = Label()
    table = []
    tablename = ''
    tablerowid = ''
    tablecolid = '0'
    tablerowname = ''
    tablevarinput = []
    tablevartext = []
    tableentrywidgetrow = []
    tablelabelwidgetrow = []

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master.grid_columnconfigure(0, weight=1)
        self.master.grid_rowconfigure(0, weight=1)
        self.master.title(title)
        self.listtable()#Make a list table
        self.createWidgets()
        self.master.geometry("800x600")
        self.pack()
    def listtable(self):
        self.table = []
        cur.execute("select * from sqlite_master WHERE type='table'");
        for t in cur:
            #print (t[1])
            self.table.append(t[1])

    #Create Widgets
    def createWidgets(self):
        #Schema
        self.Schemaframe = ttk.Labelframe(self, text='Schema',
width=600, height=100)
        self.Schemaframe.grid(column=1, row=1, sticky=W)
        self.text_database = Label(self.Schemaframe)
        self.text_database["text"] = "Schema Database:" + DATABASE
        self.text_database.grid(column=1, row=1, sticky=W)

        #Table
        self.tableframe = ttk.Labelframe(self, text='Schema Table',
width=600, height=100)
        self.tableframe.grid(column=1, row=2, sticky=W)
        self.text_table = Label(self.tableframe)
        self.text_table["text"] = "table:"
        self.text_table.grid(column=1, row=1, sticky=W)

        self.combobox = ttk.Combobox(self.tableframe)
        self.combobox.grid(column=2, row=1, sticky=W)
        self.combobox["values"] = self.table
        self.combobox.bind('<>', self.table_click)
        self.combobox.current(1)

        self.button_deletetable = Button(self.tableframe)
        self.button_deletetable["text"] = "Delete Table"
        self.button_deletetable.grid(column=3, row=1, sticky=W)

        self.button_createtable = Button(self.tableframe)
        self.button_createtable["text"] = "Create Table"
        self.button_createtable.grid(column=4, row=1, sticky=W)

        #Table
        self.scriptframe = ttk.Labelframe(self, text='Schema Script',
width=600, height=100)
        self.scriptframe.grid(column=1, row=3, sticky=W)

        self.button_script = Button(self.scriptframe)
        self.button_script["text"] = "Exeute script"
        self.button_script["command"] = self.executescript
        self.button_script.grid(column=1, row=1, sticky=W)

        self.button_commit = Button(self.scriptframe)
        self.button_commit["text"] = "Commit"
        self.button_commit["command"] = self.commit_save
        self.button_commit.grid(column=2, row=1, sticky=W)

        #TEXT BOX
        self.textbox = Text(self.scriptframe, width=40, height=10)
        self.textbox.grid(column=1, row=2, sticky=W,columnspan=6)

        #TABLE FRAME LIST
        self.tablerowframe = ttk.Labelframe(self, text='Table Rows',
width=600, height=100)
        self.tablerowframe.grid(column=2, row=1, sticky=W,rowspan=3)

        #TABLE ROW LIST
        self.listbox = Listbox(self.tablerowframe, exportselection=0,
background="white")
        self.listbox.bind("<>",self.listselect_click)
        self.listbox.grid(column=1, row=1, sticky=W)

        #vbar
        self.vbar = Scrollbar(self.tablerowframe, name="vbar")
        self.vbar.grid(column=1, row=1, sticky=E)
        self.vbar.configure(orient=VERTICAL,
command=self.listbox.yview)
        self.listbox.configure(yscrollcommand=self.vbar.set)

        self.button_createrow = Button(self.tablerowframe)
        self.button_createrow["text"] = "Create Table Row"
        self.button_createrow["command"] = self.commit_save
        self.button_createrow.grid(column=1, row=2, sticky=W)

        #TABLE FRAME ROW EDIT
        self.tablerowframe = ttk.Labelframe(self, text='Table Rows
EDIT', width=256, height=480)
        self.tablerowframe.grid(column=1, row=4, sticky=W)

    #SELECT TABLE FROM COMBOBOX
    def table_click(self,event):
        #print("click")
        self.tablename = str(self.combobox.selection_get())
        print(self.tablename)
        self.tableselected(self.tablename);
        return "break"

    #SHOW TABLE ROWS IN THE LIST BOX
    def tableselected(self,name):
        #print("TABLE SELECT ->" + str(name))
        cur.execute("select * from " + name);
        self.listbox.delete(0, "end")
        for t in cur:
            #print (t)
            #print (t[1])#table
            #spreadsheet.append(t[1])
            self.listbox.insert("end", str(t[0]))
        #self.listbox["listvariable"] = spreadsheet

    #CLICK TABLE ROW SELECTED ID OR ROW NAME
    def listselect_click(self,event):
        rowid = self.listbox.curselection()
        rowid = self.listbox.index(rowid)
        #print(self.listbox.get(rowid))
        self.tablerowid = rowid
        self.tablerowname = self.listbox.get(rowid)
        self.selecttablerow()
        return "break"

    #TABLE ROW INFORMATION
    def selecttablerow(self):
        #print ("TABLE ROW ->")
        self.tablevartext = []
        self.tablevarinput = []

        cur.execute("select * from sqlite_master WHERE type='table'");
        for t in cur:
            if self.tablename == t[1]:
                #print (t)
                tablestr = t[4].replace("CREATE TABLE "
+self.tablename + " ",'')
                tablestr = tablestr.replace("(","")
                tablestr = tablestr.replace(")","")
                comumndata = tablestr.split(',')

                for col in comumndata:
                    col = col.strip()
                    m = re.match(r"(^(\w+))",col)
                    #print (m.group(0))#column name of the table
current selected.
                    self.tablevartext.append(m.group(0))
                break

        query = str('SELECT * FROM ' + self.tablename + " WHERE id=\'"
+ self.tablerowname + "\'")
        #print(query)
        cur.execute(query);
        #table row out put
        for t in cur:
            #print (t)
            for vardata in t:
                #print(vardata)
                self.tablevarinput.append(vardata)
        self.deletetablerowinput
        self.createtablerowinput()

    def createtablerowinput(self):
        self.deletetablerowinput()
        rowcount = 0
        #self.button_destroy = Button(self.tablerowframe)
        #self.button_destroy["text"] = "delete rows"
        #self.button_destroy["command"] = self.deletetablerowinput
        #self.button_destroy.grid(column=1, row=1, sticky=W)

        self.button_deleterowtable = Button(self.tablerowframe)
        self.button_deleterowtable["text"] = "Delete Table Row"
        self.button_deleterowtable["command"] = self.deletetablerow
        self.button_deleterowtable.grid(column=1, row=1, sticky=W)

        self.button_updatetablerow = Button(self.tablerowframe)
        self.button_updatetablerow["text"] = "Update Table Row"
        self.button_updatetablerow["command"] = self.updatetablerow
        self.button_updatetablerow.grid(column=2, row=1, sticky=W)

        self.button_inserttablerow = Button(self.tablerowframe)
        self.button_inserttablerow["text"] = "Insert Table Row"
        self.button_inserttablerow["command"] = self.inserttablerow
        self.button_inserttablerow.grid(column=3, row=1, sticky=W)

        for columnname in self.tablevartext:
            #print(columnname)
            self.entry_tablevarrow = Entry(self.tablerowframe,
width=30, textvariable=columnname)
            self.entry_tablevarrow.delete(0,"end")
            self.entry_tablevarrow.insert(0,str(self.tablevarinput
[rowcount]))
            self.entry_tablevarrow.grid(column=2, row=rowcount+2,
sticky=W)
            self.tableentrywidgetrow.append(self.entry_tablevarrow)

            self.label_var = Label(self.tablerowframe, width=16)
            self.label_var['text'] = columnname
            self.label_var.grid(column=1, row=rowcount+2, sticky=W)
            self.tablelabelwidgetrow.append(self.label_var)
            #print(rowcount)
            rowcount += 1
    def updatetablerow(self):
        count = 0;
        #mysql_query("UPDATE  $db_table SET imageid='{$hashname}'
WHERE idhash='{$IDIMAGE}'")
        query = "UPDATE " + self.tablename
        set = " SET "
        where = "WHERE"
        for x in self.tableentrywidgetrow:
            if count == 0:
                where = where + " " + x["textvariable"] + "=\'" + x.get
() + "\' "
            else:
                if count == len(self.tableentrywidgetrow)-1:
                    set = set + "" + x["textvariable"] + "=\'" + x.get
() + "\' "
                else:
                    set = set + "" + x["textvariable"] + "=\'" + x.get
() + "\', "

            print ( x["textvariable"] + "->" +  x.get())
            count += 1
        print (query + set + where)
        querystring = query + set + where
        self.applydata(querystring)
        #print (len(self.tableentrywidgetrow))
    def deletetablerow(self):
        count = 0;
        query = "DELETE FROM " + self.tablename + " WHERE "
        delete = ""
        for x in self.tableentrywidgetrow:
            if count == len(self.tableentrywidgetrow)-1:
                delete = delete + "" + x["textvariable"] + "=\'" +
x.get() + "\' "
            else:
                delete = delete + "" + x["textvariable"] + "=\'" +
x.get() + "\' AND "
            count += 1
        print (query + delete)
        querystring = query + delete
        self.applydata(querystring)
        #print (len(self.tableentrywidgetrow))
    def inserttablerow(self):
        #cur.execute('INSERT INTO member (user, password) VALUES
( "admin", "admin")')
        count = 0;
        query = "INSERT INTO " + self.tablename + "("
        values = ""
        insert = ""
        #be sure it not the primary key else it will give error
        for x in self.tableentrywidgetrow:
            if count == len(self.tableentrywidgetrow)-1:
                values = values + x["textvariable"] + ''
                insert = insert + '\"' + x.get() + '\"'
            else:
                if count == 0:
                    print ("PRIMARY KEY")
                else:
                    values = values + x["textvariable"] + ','
                    insert = insert + '\"' + x.get() + '\",'

            count += 1

        querystring = query + values + ") VALUES(" + insert + ")"
        print (querystring)
        self.applydata(querystring)
        #print (len(self.tableentrywidgetrow))

    def deletetablerowinput(self):
        for x in self.tableentrywidgetrow:
            x.destroy()
        self.tableentrywidgetrow = []
        for y in self.tablelabelwidgetrow:
            x.destroy()
        self.tablelabelwidgetrow = []

    #SCRIPTS ++++++
    def executescript(self):
        print("Execute Script...")
        scripttext = self.textbox.get('1.0', 'end')
        self.applydata(scripttext)
        print(scripttext)
    #COMMIT +++++++
    def commit_save(self):
        print("Sqlite3 Commit")
        db.commit()
    def applydata(self,querystr):
        print("Sqlite3 Commit")
        db = sqlite.connect(DATABASE);
        cur = db.cursor()
        cur.execute(querystr)
        db.commit()

root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()

Not sure what you guys think about this. Still working on it. I can't
hard code this well. Still learning it. >.<


From lanyjie at yahoo.com  Wed Aug  5 20:40:18 2009
From: lanyjie at yahoo.com (Yingjie Lan)
Date: Wed, 5 Aug 2009 17:40:18 -0700 (PDT)
Subject: using expy to extend python
In-Reply-To: <200908060148.36696.wolfgang@rohdewald.de>
Message-ID: <870509.8482.qm@web54208.mail.re2.yahoo.com>


> From: Wolfgang Rohdewald 
> Subject: Re: using expy to extend python
> To: python-list at python.org
> Date: Thursday, August 6, 2009, 3:48 AM
> On Thursday 06 August 2009, Yingjie
> Lan wrote:
> > For more information about expy, please visit its
> homepage at:
> > http://expy.sf.net/
> 
> looks very interesting, bookmarked.
> 

Glad to hear that! Thanks.

> In your example class mate, def rename looks wrong:
> if malloc fails, the previous name should probably not
> be replaced by an empty string?
> 

Thanks for pointing that out. Probably should throw an exception if malloc fails. 

Yingjie


      


From gregor.lingl at aon.at  Wed Aug  5 20:49:44 2009
From: gregor.lingl at aon.at (Gregor Lingl)
Date: Thu, 06 Aug 2009 02:49:44 +0200
Subject: Turtle Graphics are incompatible with gmpy
In-Reply-To: <49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com>
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at>
	
	<4A79C7E2.3000406@aon.at>
	
	
	<49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com>
Message-ID: <4a7a28b3$0$2303$91cee783@newsreader01.highway.telekom.at>

Mensanator schrieb:
> On Aug 5, 5:31 pm, Mensanator  wrote:
>> I fixed this to produce the actual image I'm looking
>> for instead of that stupid black square. All I did was
>> use up() & dowm() in place of penup(), pendown() and
>> replace dot(2) with forward(1).
>>
>> I'll be posting a followup report later.
>>
> 
> http://www.mensanator.com/mensanator/PythonTurtle/turtle.htm

Hi Mansanator,

Thanks for that thorough investigations.
I hope I'll soon find time to study it in detail.

I've just one idea, but I don't know if you might
be intersted in it or if it's rewarding at all:

What would be the results when using the old turtle
module with Python 3.1 (it will certainly not run
out of the box, but perhaps 2to3 might do it?)

That would clarify the question if there is some
impact of new division or some changes in Tkinter.

Best regards,
Gregor


From gagsl-py2 at yahoo.com.ar  Wed Aug  5 20:54:07 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 05 Aug 2009 21:54:07 -0300
Subject: Datetime with float seconds
References: 
Message-ID: 

En Wed, 05 Aug 2009 09:50:04 -0300, kpal 
escribi?:

> The standard datetime has 1 microsecond granularity.

Note that this is the finest granularity a datetime object can store, NOT
the precision of datetime.now() by example.

> My application
> needs finer time resolution, preferably float seconds.

"float seconds" doesn't mean much. time.time returns float seconds, but
its precision is around 15ms on Windows.

> Is there an
> alternative to the out-of-the-box datetime? Timezone support is not
> essential.

On Windows, use time.clock(), which internally uses
QueryPerformanceCounter. The resolution depends on your hardware, but it's
typically better than 1 microsecond. If you want to know the actual value:

py> from ctypes import *
py> kernel32=windll.kernel32
py> QueryPerformanceCounter=kernel32.QueryPerformanceCounter
py> QueryPerformanceFrequency=kernel32.QueryPerformanceFrequency
py> plonglong = POINTER(c_longlong)
py> QueryPerformanceFrequency.argtypes = [plonglong]
py> freq = c_longlong()
py> QueryPerformanceFrequency(byref(freq))
1
py> freq
c_longlong(3579545L)

That is, on my system the resolution is 1/3579545s, or better than 300ns

-- 
Gabriel Genellina



From gagsl-py2 at yahoo.com.ar  Wed Aug  5 20:54:16 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 05 Aug 2009 21:54:16 -0300
Subject: Install setup tools for 2.6
References: <373cf0740908051131gacaf77apba48fa40e929f491@mail.gmail.com>
Message-ID: 

En Wed, 05 Aug 2009 15:31:38 -0300, Jeremy Cowles
 escribi?:

> Ok, I feel like this is a really stupid question, but how do you install
> setup tools for Python 2.6 under windows?
> The only format is .egg which requires setup tools to install, doesn't  
> it?

I have no idea, and I try to stay as far away from setuptools/ez_setup as
I can. I think they solve some kind of problems for some kind of people
(else the tool would be defunct by now), but haven't worked for me.
Perhaps you don't need setuptools either?

-- 
Gabriel Genellina



From mensanator at aol.com  Wed Aug  5 21:31:00 2009
From: mensanator at aol.com (Mensanator)
Date: Wed, 5 Aug 2009 18:31:00 -0700 (PDT)
Subject: Turtle Graphics are incompatible with gmpy
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
	
	 
	<49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com> 
	<4a7a28b3$0$2303$91cee783@newsreader01.highway.telekom.at>
Message-ID: 

On Aug 5, 7:49?pm, Gregor Lingl  wrote:
> Mensanator schrieb:
>
> > On Aug 5, 5:31 pm, Mensanator  wrote:
> >> I fixed this to produce the actual image I'm looking
> >> for instead of that stupid black square. All I did was
> >> use up() & dowm() in place of penup(), pendown() and
> >> replace dot(2) with forward(1).
>
> >> I'll be posting a followup report later.
>
> >http://www.mensanator.com/mensanator/PythonTurtle/turtle.htm
>
> Hi Mansanator,
>
> Thanks for that thorough investigations.
> I hope I'll soon find time to study it in detail.
>
> I've just one idea, but I don't know if you might
> be intersted in it or if it's rewarding at all:

Sure, not tonight, of course, but I can give it try.

>
> What would be the results when using the old turtle
> module with Python 3.1 (it will certainly not run
> out of the box, but perhaps 2to3 might do it?)

I would just need to copy turtle.py to 3.1 Lib (renamed,
of course)?

>
> That would clarify the question if there is some
> impact of new division or some changes in Tkinter.

I had a quick glance through the code. Not too many divisions
and most of them seemd to already be forcing float division
by constructs such as mutiplying by 1.0 (which I assume isn't
strictly neccessary as long as / and // are used correctly.

It seemed a lot of floats were used in the 2.5 code as I saw
such stuff as int(difference), so I really don't know why
.mpz would be a problem since they are integers also and a
Python int ought to be the same thing when coerced to a float
(at least in the range used by Turtle graphics.

>
> Best regards,
> Gregor



From sjmachin at lexicon.net  Wed Aug  5 21:31:56 2009
From: sjmachin at lexicon.net (John Machin)
Date: Thu, 6 Aug 2009 01:31:56 +0000 (UTC)
Subject: unicode() vs. s.decode()
References: 
	<1249487636.7120.798.camel@arrakis>
Message-ID: 

Jason Tackaberry  urandom.ca> writes:
> On Wed, 2009-08-05 at 16:43 +0200, Michael Str?der wrote:
> > These both expressions are equivalent but which is faster or should be used
> > for any reason?
> > u = unicode(s,'utf-8')
> > u = s.decode('utf-8') # looks nicer
> 
> It is sometimes non-obvious which constructs are faster than others in
> Python.  I also regularly have these questions, but it's pretty easy to
> run quick (albeit naive) benchmarks to see.
> 
> The first thing to try is to have a look at the bytecode for each:
[snip] 
> The presence of LOAD_ATTR in the first form hints that this is probably
> going to be slower.   Next, actually try it:
> 
>         >>> import timeit
>         >>> timeit.timeit('"foobarbaz".decode("utf-8")')
>         1.698289155960083
>         >>> timeit.timeit('unicode("foobarbaz", "utf-8")')
>         0.53305888175964355
> 
> So indeed, uncode(s, 'utf-8') is faster by a fair margin.

Faster by an enormous margin; attributing this to the cost of attribute lookup
seems implausible.

Suggested further avenues of investigation:

(1) Try the timing again with "cp1252" and "utf8" and "utf_8"

(2) grep "utf-8" /Objects/unicodeobject.c

HTH,
John



From digitalhillbilly at hotmail.com  Wed Aug  5 21:40:57 2009
From: digitalhillbilly at hotmail.com (DH)
Date: Wed, 5 Aug 2009 18:40:57 -0700 (PDT)
Subject: access read / write violation with ctypes
Message-ID: 

Hi all,

I'm quite new to cytpes and am having some troubles I was hoping I
could get a little help with. Before I get into the details this is
what I'm trying to accomplish - I would like to read a dng with python
pass it through either libraw.dll or dcraw.dll (notes on dcraw.dll
version at the end) for initial processing then to MagickWand for some
light enhancement and final jpeg output. After I get these working I
will see how I can add LittleCMS into the fray. I'm not doing
something correctly but don't know what. I've read a lot of documents
over the past couple days and though I've learned quite a lot I just
can't get past this access violation error.

I very grateful for anything that can be offered.

dh

...

I am currently working out MagickWand and dcraw separately but am
having similar troubles with both resulting in either 'Windows Error:
exception: access violation reading 0x00000000' or alternatively
'Windows Error: ... writing'

1 - MagickWand (read violation):

I'm using popen to capture dcraw stdout and want to pass it to
magickwand. If I instead write the dcraw output to a file then read it
with magickwand I get the same error. But if I comment out the dcraw
protion and read the dcraw output file from the previous attempt,
MagickWand opens the file fine and I can manipulate it to my hearts
content. The basics:

proc = subprocess.Popen("dcraw -c -4 -T image.dng", shell=True,
close_fds=False, stdout=subprocess.PIPE).communicate()[0]

magickWandLib = 'C:\\Program Files (x86)\\ImageMagick-6.5.3-Q16\
\CORE_RL_wand_.dll'
Magick = cdll.LoadLibrary(magickWandLib)

Magick.MagickWandGenesis()
wand = Magick.NewMagickWand()

Magick.MagickReadImageFile(proc)
-> access violation reading

2 - DCRaw (write violation):

I've been bouncing between libraw.dll and dcraw.dll. The dcraw version
I'm using is found at
http://translate.google.com/translate?hl=en&sl=es&tl=en&u=http://www.ojodigital.com/foro/perfectraw-perfectblend/206898-perfectraw-0-5-a.html
. Libraw is limited in the sence that it is mainly suited to loading
and unpacking raw images. Actual processing is done only in emulation
mode which I have not yet been able to access throught the library.
PerfectRaw uses a tweaked and librarised version of dcraw with thier
GUI + some enhanced functions. I'm only interesed in the dll though

2.1 - libraw.dll

I won't go into great detail as I can get it to work but only open,
unpack and write out a tiff or ppm. No process settings

2.2 - dcraw.dll

I can load the library but cannot initialise an instance. Each attempt
in a variety or methods always returns an 'access violation writing
0x00000000'. The parameters I use to initialise are taken from a test
program provided by the authors.

test app:
	int w,h;
	printf("Resultado de leer el RAW: %i\n",DCRAW_Init("c:\\test\
\IMG_4118.CR2",&w,&h)

python:
	dcraw_lib = 'C:\\programs\\PerfectRaw\\dcraw.dll'
	dcraw = ctypes.cdll.LoadLibrary(dcraw_lib)

	img = 'C:\\programs\\PerfectRaw\\image.dng'
	dcraw.DCRAW_Init(img,4000,3000) # canon G9 converted to dng
	-> access violation writing



From gforgx at lavabit.com  Wed Aug  5 21:51:52 2009
From: gforgx at lavabit.com (Sergey Simonenko)
Date: Wed, 05 Aug 2009 19:51:52 -0600
Subject: Subclassing Python's dict
Message-ID: 

Hi,

I subclass builtin 'dict' in my application and experience some problems  
with it.

The whole issue is that I should redefine 'setdefault' and 'update'  
methods after redefining '__setitem__' or/and '__delitem__',
otherwise 'update' and 'setdefault' ignore redefined '__setitem__' and use  
builtin dict's one so dict looks kinda like a black box.

Another guy have reported me that he experiences similar problems with  
subclassing builtin 'list'.

Kind regards, Sergey.

-- 
???????? ? ???????? ??????? ???????? Opera: http://www.opera.com/mail/



From cocobear.cn at gmail.com  Wed Aug  5 22:17:53 2009
From: cocobear.cn at gmail.com (cocobear)
Date: Wed, 5 Aug 2009 19:17:53 -0700 (PDT)
Subject: merge two png pic
References: 
	 
	
	<006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com>
	<4a77e249$0$2449$426a74cc@news.free.fr>
	<72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com>
	<4a793852$0$19598$426a74cc@news.free.fr>
Message-ID: <69579cfc-9151-43df-a5ef-a6b05f1bd718@13g2000prl.googlegroups.com>

On Aug 5, 3:44?pm, News123  wrote:
> You didn't really tell us why you need one big file, which contains more
> pixel, than you can probably store in RAM
>

In fact I do not need such a big image.
I just want to know the solution.


> Is it for printing?
> Not knwoing your goal makes it difficult to suggest solutions.
>
> Can't you use other image formats like raw RGB or
> What other image formats are supported?
> tiff? Raw? PPM (http://en.wikipedia.org/wiki/Portable_pixmap)?
>

I want to view image use Windows Pic View.

I don't familiar with PPM? photoshop don't support PPM, does PIL
support this format?


> concatenating raw/ppm files with the same width would be really trivial.
>
> so you could use python to create horizontal raw/ppm stripes.
>
> then you could concatenate them without having to have the whole image
> in RAM.
>
> Perhaps there's even converters from ppm to png, that don't need the
> whole image in RAM.
>
>
>
> cocobear wrote:
> > On Aug 4, 3:24 pm, News123  wrote:
> >> Hi,
>
> >> cocobear wrote:
> >>>>>>> Map = Image.new("RGB", (x,y))
> >>>>>>> Map.paste(im, box)
> >>>>>>> Map.paste(im1,box)
> >>>>>>> Map = Map.convert("L", optimize=True, palette=Image.ADAPTIVE)
> >>>>>>> But if thetwopngpicis too big , or if I have tomergemorepic
> >>>>>>> together, I will get MemoryError:
> >>>>>>>>>>>>> Image.new("RGB",(44544,38656))
> >>>> What do you want to do with such a big image? You will run into the same
> >>>> limitation when you are trying to display it.
> >>> I want to download a map from google map with high precision
> >> For me it sounds strange to handle such big files.
>
> >> Is the map you download from Google really that big?
> >> Mostly Google maps uses normally tiles of sizes 256x256 pixel, wich you
> >> have to compose to get the ?big image.
>
> > The map I downloaded from Google is small(256x256). These small maps
> > will compose a big image.
>
> >> If your problem is to combine tiles with different palettes, then you
> >> should pobably look at a way to ?'unify' the palette of all tiles befor
> >> combining them.
>
> > I think it is impossible to 'unify' all this tiles.
>
> >> Being no expert of PIL I don't know whether this is easily possible though?
>
> >> bye
>
> >> N



From wuwei23 at gmail.com  Wed Aug  5 23:19:37 2009
From: wuwei23 at gmail.com (alex23)
Date: Wed, 5 Aug 2009 20:19:37 -0700 (PDT)
Subject: Subclassing Python's dict
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com> 
	
Message-ID: 

Xavier Ho wrote:
> You should subclass collections.UserDict, and not the default dict class.
> Refer to the collections module.

Xavier, why do you think that is the correct approach? The docs say
"The need for this class has been largely supplanted by the ability to
subclass directly from dict (a feature that became available starting
with Python version 2.2)."

If you mean that Sergey should subclass _in this instance_ could you
please explain why? (Sorry if you already have, I never saw your
original post...)




From rt8396 at gmail.com  Wed Aug  5 23:35:43 2009
From: rt8396 at gmail.com (r)
Date: Wed, 5 Aug 2009 20:35:43 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
Message-ID: <93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegroups.com>

On Aug 4, 12:55?am, David Lyon  wrote:
> It isn't totally about the writers...
> Peoples egos are also at stake - it seems.
> If "Fred X wrote Doc Y".. they don't want their name taken off.. So
> they generally speaking don't want the docs changed.
> If you talk too much about docs.. you can be told you're OT..
> even in a thread about docs...

This is the most honest post within this thread. Yes i believe --
although it does not make me happy-- that many within this community
are hostile, vulgar, and viscous towards any notion of change if it
comes from outside the "insiders" group (and even sometimes from the
inside). Which is very sad.

Yes sometimes people are just trolling, but this tread has nothing to
do with trolling. kj has a legitimate complaint. Do i believe the docs
are a complete waste of bytes, No! Many people have invested tons of
hard work into them (and i thank them for their hard work). But i do
believe --like all things in this word-- perfection is always just out
of hands reach, we must constantly seek perfection because we can
never attain it. Like any group effort, eventually it will adopt the
idioms of self indulgence. Python dev needs the input of those who are
not experts in the language --especially in the realm of docs.

It is so easy to forget the struggles we face when learning something
new. The accessibility and appeal of Python to new users is in the
best interest of this community. If you don't believe that, you are
pissing on all the years of hard work that has been put in here. You
might as well just tell Guido to "close up shop"

I have posted this once before but i will post it again. Please read
Christopher's words carefully because they apply to this community in
a big way...Don't fall into the trap of narcissism.

Christopher Lasch referring to the pitfalls of Narcissistic societies:

"""In such a society of constant competition, there can be no allies,
and little transparency. The threats to
acquisitions of social symbols are so numerous, varied and frequently
incomprehensible, that defensiveness, as well as competitiveness,
becomes a way of life. Any real sense of community is undermined -- or
even destroyed -- to be replaced by virtual equivalents that strive,
unsuccessfully, to synthesize a sense of community."""

While I agree that some narcissism is vital to an individuals ego in
competitive atmospheres, I do not believe the Python community
warrants this need.


From rays at blue-cove.com  Thu Aug  6 00:21:13 2009
From: rays at blue-cove.com (RayS)
Date: Wed, 05 Aug 2009 21:21:13 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com>
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
Message-ID: <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>

An HTML attachment was scrubbed...
URL: 

From davea at ieee.org  Thu Aug  6 00:51:19 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 00:51:19 -0400
Subject: Error on Attaching to the process while debugging
In-Reply-To: <21dbc649-2f82-4e4c-9777-c8a58c25a9e0@r2g2000yqm.googlegroups.com>
References: <21dbc649-2f82-4e4c-9777-c8a58c25a9e0@r2g2000yqm.googlegroups.com>
Message-ID: <4A7A6147.5030901@ieee.org>


MalC0de wrote:
> Hello there, I'm writting a debugger,
> the problem is there no good interpretation ...
>
> here's the codes:
>
> my_debugger.py :
>
> #!/usr/bin/env python
> from ctypes import *
> from my_debugger_defines import *
> kernel32 = windll.kernel32
> class debugger():
>     def __init__(self):
> 	  self.h_process = None
> 	  self.pid = None
> 	  self.debugger_active = False
>           pass
>     def load(self,path_to_exe):
>         creation_flags = DEBUG_PROCESS
>         startupinfo = STARTUPINFO()
>         process_information = PROCESSINFORMATION()
>         startupinfo.dwFlags = 0x1
>         startupinfo.wShowWindow = 0x0
>         startupinfo.cb = sizeof(startupinfo)
>         if kernel32.CreateProcessA(path_to_exe,
>                                     None,
>                                     None,
>                                     None,
>                                     None,
>                                     creation_flags,
>                                     None,
>                                     None,
>                                     byref(startupinfo),
>                                     byref(process_information)):
>                   print "[*]we have sucessfully launched the process"
>                   print "[*]PID %d" % process_information.dwProcessId
>                   self.h_process = self.open_process
> (process_information.dwProcessId)
>         else:
>             print"[*]Error 0x%08x." % kernel32.GetLastError()
>
> def Open_process(self,pid):
>     h_process = kernel32.OpenProcess(PROCESS_ALL_ACCESS,pid,False)
>     return h_process
> def attach(self,pid):
>         self.h_process = self.open_process(pid)
>         # We attempt to attach to the process
>         # if this fails we exit the call
>         if kernel32.DebugActiveProcess(pid):
>             self.debugger_active = True
>             self.pid             = int(pid)
>
>         else:
>             print "[*] Unable to attach to the process."
>
> def run(self):
>     while self.debugger_active == True:
>         self.get_debug_event()
> def get_debug_event(self):
>     debug_event = DEBUG_EVENT()
>     continue_status = DBG_CONTINUE
>     if kernel32.WaitForDebugEvent(byref(debug_event),INFINITE):
>         raw_input("Press a key to continue ...")
>     self.debugger_active = False
>     kernel32.ContinueDebugEvent
> (debug_event.dwProdcessid,debug_event.dwThreadId,continue_status)
>     def detach(self):
>         if kernel32.DeugActiveProcessStop(self.pid):
>             print "[*]Finished debugging. exiting ..."
>             return True
>         else:
>             print "there was an error"
>             return false
>
> it's already have a method named : Attach ...
> 
>   
Indentation is critical.  You have defined functions ( Open_process() 
attach(), run(), etc. ) that have formal parameters named self, but are 
indented outside of the class definition.  Indentation trumps, so these 
are not attributes of the class.  They're functions, not methods.

It looks like you have other indentation problems, but I'll let you run 
with this much.

Incidentally, following naming conventions could also help here.  
debugger is a class, but it's not capitalized.  Open_process() is 
intended to be a method, but it is capitalized.  And your comments refer 
to attach() as Attach...  Another convention you're breaking is using    
"from ctypes import * "   That's a dangerous way to do imports, as it 
mixes those names with the ones in this module.  I prefer a simple 
import, and use the module name as a prefix when you reference those 
symbols.  If there are a few symbols you do want to have directly 
included, then import them one at a time, without the * notation.  (just 
my opinion)

DaveA



From gagsl-py2 at yahoo.com.ar  Thu Aug  6 01:19:24 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 02:19:24 -0300
Subject: Two Dimensional Array + ctypes
References: <79d2b3e3-b049-4d70-a56b-6e7f3ea2fa86@e27g2000yqm.googlegroups.com>
Message-ID: 

En Wed, 05 Aug 2009 20:12:09 -0300, Sparky  escribi?:

> Hello! I am trying to call this method:
>
> long _stdcall AIBurst(long *idnum, [...]
> 			 long timeout,
> 			 float (*voltages)[4],
> 			 long *stateIOout,
> 			 long *overVoltage,
> 			 long transferMode);
>
> I am having some problems with that  float (*voltages)[4].

>         pointerArray = (ctypes.c_void_p * 4)
>         voltages = pointerArray(ctypes.cast(ctypes.pointer
> ((ctypes.c_long * 4096)()), ctypes.c_void_p), ctypes.cast
> (ctypes.pointer((ctypes.c_long * 4096)()), ctypes.c_void_p),
> ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)()),
> ctypes.c_void_p), ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)

Why c_long and not c_float?
Anyway, this way looks much more clear to me (and doesn't require a cast):

arr4096_type = ctypes.c_float * 4096
voltages_type = arr4096_type * 4
voltages = voltages_type()

> The program runs but the values that come back in the array are not
> right.

Thay might be due to the long/float confusion.

-- 
Gabriel Genellina



From davea at ieee.org  Thu Aug  6 01:25:48 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 01:25:48 -0400
Subject: Web page data and urllib2.urlopen
In-Reply-To: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
Message-ID: <4A7A695C.4010403@ieee.org>

Massi wrote:
> Hi everyone, I'm using the urllib2 library to get the html source code
> of web pages. In general it works great, but I'm having to do with a
> financial web site which does not provide the souce code I expect. As
> a matter of fact if you try:
>
> import urllib2
> res = urllib2.urlopen("http://www.marketwatch.com/story/mondays-
> biggest-gaining-and-declining-stocks-2009-07-27")
> page = res.read()
> print page
>
> you will see that the printed code is very different from the one
> given, for example, by mozilla. Since I have really little knowledge
> in html I can't even understand if this is a python or html problem.
> Can anyone give me some help?
> Thanks in advance.
>
>   
I don't think this is a Python issue, but a "raw read" versus an 
interactive interpretation of a page.  The browser does lots more than a 
single roundtrip defined by urlopen/read.

I also would love to see some explanation of what happens here, or a 
pointer to a reference that would help me understand it.

I took the output of the read(), and formatted it, roughly, as html.  I 
expected to find a refresh, which is the simplest way that one page can 
cause a very different one to be loaded.
      

If Mozilla had seen a page with this line in an appropriate place, it'd 
immediately begin loading the other page, at "someotherurl"  But there's 
no such line.

Next, I looked for javascript.  The Mozilla page contains lots of 
javascript, but there's none in the raw page.  So I can't explain 
Mozilla's differences that way.

I did notice the link to /m/Content/mobile2.css, but I don' t know any 
way a CSS file could cause the content to change, just the display.

All I can guess is that it has something to do with "browser type" or 
cookies.  And that would make lots of sense if this was a cgi page.  But 
the URL doesn't look like that, as it doesn't end in pl, py, asp, or any 
of another dozen special suffixes.

Any hints, anybody???

DaveA



From MatzeGuentert at gmx.de  Thu Aug  6 01:26:31 2009
From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=)
Date: Thu, 06 Aug 2009 07:26:31 +0200
Subject: M2Crypto: How to generate subjectKeyIdentifier /
	authorityKeyIdentifier
In-Reply-To: 
References: 
	
Message-ID: <1249536391.3348.35.camel@celsius>

> M2Crypto has a couple of bugs open related that, with potential
> workarounds that I haven't yet deemed polished enough to checkin, but
> which might help you out:
> 
> https://bugzilla.osafoundation.org/show_bug.cgi?id=7530
> https://bugzilla.osafoundation.org/show_bug.cgi?id=12151

Thanks, that helped me a lot. Generating the 'subjectKeyIdentifier' now
works for me using the following procedure:

----------------------------------------------------------
import hashlib 

def get_public_key_fingerprint(self):
	h = hashlib.new('sha1')
    	h.update(self.keypair.as_der())
    	client_serial = h.hexdigest().upper()
    	client_serial_hex = ''
    	
    	for byte in xrange(20):
    	 client_serial_hex += client_serial[byte*2] + client_serial[byte*2
+1]
    		if byte < 19:
    			client_serial_hex += ':'
    
        return client_serial_hex 

[...]
cert_extension_4 = X509.new_extension("subjectKeyIdentifier",
keys_ca.get_public_key_fingerprint()) 
----------------------------------------------------------

However I don't understand the way the hash gets build. Comparing the
output from a given keypair and certificate build via OpenVPNs easy-rsa
scripts shows different subjectKeyIdentifiers. As stated out by rfc5280
there is no right or wrong way in creating the unique hash, so this
should be fine. 

But setting the 'authorityKeyIdentifier' extension gives me some
headache here. The following code snippet produces a segmentation fault
on my python interpreter (version 2.6)  

----------------------------------------------------------
cert_extension = X509.new_extension("authorityKeyIdentifier",
keys_ca.get_public_key_fingerprint())

cert_extension_stack.push(cert_extension)
----------------------------------------------------------

Same on this:
----------------------------------------------------------
cert_extension = 

X509.new_extension("authorityKeyIdentifier",
"keyid:1C:88:E1:8E:F1:5F:9D:1C:2B:6C:41:D4:3D:BB:79:0D:33:4A:E3:9A,
DirName:/C=US/ST=CA/L=SanFrancisco/O=Fort-Funston/CN=Fort-Funston
CA/emailAddress=me at myhost.mydomain, serial:B1:82:B1:E4:23:78:F1:12")

cert_extension_stack.push(cert_extension)
----------------------------------------------------------

So the question is: Is there another workaround to set this extension?
How can I provide more information to get this fixed? Working with the
latest SVN version is no option for me at the moment. 

Thanks in advance,
Matthias 




From gagsl-py2 at yahoo.com.ar  Thu Aug  6 01:30:58 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 02:30:58 -0300
Subject: os.system in a service
References: 
Message-ID: 

En Wed, 05 Aug 2009 13:07:39 -0300, Lawrence Wong  
 escribi?:

> I wrote a program which runs a .bat file using os.system like:  
> 'os.system(pathToBatFile)' and everything was good.  Then I decided to  
> turn my program into a service as opposed to being run with the command  
> prompt showing.  When my program became a service, I noticed that the  
> os.system command to run my .bat file was no longer working.  By 'not  
> working' I mean no exception is thrown, but it was as if the line with  
> os.system(pathToBatFile) did not exist.  I was wondering why this is and  
> if there is a way to fix this or what an alternative to using os.system  
> to run my .bat file was?

Capture stdout and stderr and you'll probably see the error message:

some_command >logfile.txt 2>&1

-- 
Gabriel Genellina



From pfeldman at verizon.net  Thu Aug  6 01:42:26 2009
From: pfeldman at verizon.net (Dr. Phillip M. Feldman)
Date: Wed, 5 Aug 2009 22:42:26 -0700 (PDT)
Subject: How to comment on a Python PEP?
Message-ID: <24840417.post@talk.nabble.com>


Is there a mechanism for submitting comments on a Python PEP?
-- 
View this message in context: http://www.nabble.com/How-to-comment-on-a-Python-PEP--tp24840417p24840417.html
Sent from the Python - python-list mailing list archive at Nabble.com.



From mlm2winnet at gmail.com  Thu Aug  6 01:49:42 2009
From: mlm2winnet at gmail.com (Chris Harris)
Date: Wed, 5 Aug 2009 22:49:42 -0700 (PDT)
Subject: Hi everyone
Message-ID: <150d41dd-018a-48a0-8dda-43e7832d6434@r38g2000yqn.googlegroups.com>

I'm happy to be a part of this group, i'd liek to say hi and invite
everyone to join my group =D Have a great night i look forward to
being an active member of this group

http://groups.google.com/group/mlm-2-win


From gagsl-py2 at yahoo.com.ar  Thu Aug  6 01:50:01 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 02:50:01 -0300
Subject: Parsing Binary Structures; Is there a better way / What is your
	way?
References: 
Message-ID: 

En Wed, 05 Aug 2009 11:46:13 -0300, Martin P. Hellwig  
 escribi?:

> On several occasions I have needed (and build) a parser that reads a  
> binary piece of data with custom structure. For example (bogus one):
>
> BE
> +---------+---------+-------------+-------------+------+--------+
> | Version | Command | Instruction | Data Length | Data | Filler |
> +---------+---------+-------------+-------------+------+--------+
> Version: 6 bits
> Command: 4 bits
> Instruction: 5 bits
> Data Length: 5 bits
> Data: 0-31 bits
> Filler: filling 0 bits to make the packet dividable by 8

> - Using a string for binary representation takes at least 8 times more  
> memory for the packet than strictly necessary.

The size difference isn't so big; an integer takes 12 bytes and a string  
takes 24+len bytes. "Data" above would take 56 bytes max when stored as a  
string '0110001...' vs. 12 bytes when using a plain integer (sizes  
computed on Windows 32bits). Plus, doing bitwise operations in Python  
isn't a fast operation as it is in C, by example -- so your current  
implementation might be a quite good one (in pure Python, I mean).

-- 
Gabriel Genellina



From davea at ieee.org  Thu Aug  6 02:30:47 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 02:30:47 -0400
Subject: access read / write violation with ctypes
In-Reply-To: 
References: 
Message-ID: <4A7A7897.1030207@ieee.org>

DH wrote:
> 
>
> I'm using popen to capture dcraw stdout and want to pass it to
> magickwand. If I instead write the dcraw output to a file then read it
> with magickwand I get the same error. But if I comment out the dcraw
> protion and read the dcraw output file from the previous attempt,
> MagickWand opens the file fine and I can manipulate it to my hearts
> content. The basics:
>
> 
>   
Just a quick guess, based only on this paragraph.  But I'd guess the 
dcraw output file is buffered, and is not fully written when you're 
trying to read it back.

You could do some checking by comparing sizes, when you get it from the 
pipe, and when you see it finally written in the directory.

DaveA


From hendrik at microcorp.co.za  Thu Aug  6 02:43:58 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Thu, 6 Aug 2009 08:43:58 +0200
Subject: Datetime with float seconds
In-Reply-To: 
References: 
Message-ID: <200908060843.58925.hendrik@microcorp.co.za>

On Wednesday 05 August 2009 14:50:04 kpal wrote:
> Hello Everybody,
>
> The standard datetime has 1 microsecond granularity. My application
> needs finer time resolution, preferably float seconds. Is there an
> alternative to the out-of-the-box datetime? Timezone support is not
> essential.

I am curious as to what would require less than microsecond
timing - about the only thing I can think of would be something
involving measuring the speed of light, where nanoseconds
or better would be nice.

- Hendrik



From davea at ieee.org  Thu Aug  6 02:45:01 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 02:45:01 -0400
Subject: Parsing Binary Structures;	Is there a better way / What is
	your way?
In-Reply-To: <7xr5vqw0v9.fsf@ruckus.brouhaha.com>
References: 	<7x3a86gmfe.fsf@ruckus.brouhaha.com>	
	<7xr5vqw0v9.fsf@ruckus.brouhaha.com>
Message-ID: <4A7A7BED.4030105@ieee.org>

Paul Rubin wrote:
> "Martin P. Hellwig"  writes:
>   
>> Is there an advantage using shifts and masks over my kitchen type solution?
>>     
>
> Weren't you complaining about the 8-to-1 expansion from turning each bit
> to an ascii char?
>
>   
One warning to Martin:

If you want your code portable across systems, watch out for 
big-endian/little-endian  issues, as well as alignment ones.  Shift & 
mask code tends to be highly specific to a particular endian-ness, 
especially if trying to get multiple bits that cross a byte or word 
boundary.

Over the years, I know I've seen at least three endian versions for the 
same 32bit word.  Something like abcd, dcba, and cdab.

One advantage of converting first to bitstrings, is that there's just 
the two places to fix, for portability, the conversion from byte array 
to bitstring, and the conversion back.

DaveA



From deets at nospam.web.de  Thu Aug  6 02:59:13 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Thu, 06 Aug 2009 08:59:13 +0200
Subject: os.system in a service
In-Reply-To: 
References: 
	
Message-ID: <7dvda1F2c4s7kU1@mid.uni-berlin.de>

Gabriel Genellina schrieb:
> En Wed, 05 Aug 2009 13:07:39 -0300, Lawrence Wong 
>  escribi?:
> 
>> I wrote a program which runs a .bat file using os.system like: 
>> 'os.system(pathToBatFile)' and everything was good.  Then I decided to 
>> turn my program into a service as opposed to being run with the 
>> command prompt showing.  When my program became a service, I noticed 
>> that the os.system command to run my .bat file was no longer working.  
>> By 'not working' I mean no exception is thrown, but it was as if the 
>> line with os.system(pathToBatFile) did not exist.  I was wondering why 
>> this is and if there is a way to fix this or what an alternative to 
>> using os.system to run my .bat file was?
> 
> Capture stdout and stderr and you'll probably see the error message:
> 
> some_command >logfile.txt 2>&1

Which isn't possible as a service.

The OP might consider using suprocess istead of os.system, and establish 
pipes to read the output of the command into a file he can analyze.

Diez


From hendrik at microcorp.co.za  Thu Aug  6 03:39:33 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Thu, 6 Aug 2009 09:39:33 +0200
Subject: Parsing Binary Structures;
	Is there a better way / What is your way?
In-Reply-To: 
References: 
Message-ID: <200908060939.33365.hendrik@microcorp.co.za>

On Wednesday 05 August 2009 16:46:13 Martin P. Hellwig wrote:
> Hi List,
>
> On several occasions I have needed (and build) a parser that reads a
> binary piece of data with custom structure. For example (bogus one):
>
> BE
> +---------+---------+-------------+-------------+------+--------+
>
> | Version | Command | Instruction | Data Length | Data | Filler |
>
> +---------+---------+-------------+-------------+------+--------+
> Version: 6 bits
> Command: 4 bits
> Instruction: 5 bits
> Data Length: 5 bits
> Data: 0-31 bits
> Filler: filling 0 bits to make the packet dividable by 8
>
> what I usually do is read the packet in binary mode, convert the output
> to a concatenated 'binary string'(i.e. '0101011000110') and then use
> slice indeces to get the right data portions.
> Depending on what I need to do with these portions I convert them to
> whatever is handy (usually an integer).

This bit banging stuff is a PITA, no matter what you do.
Python does not have bit fields like C.
And C bit fields are implementation dependent.
Write an extension?

Some time ago I asked a similar question, and
Castironpi came up with what was essentially an
indexed integer, with named bits.

It stores the bits natively, but I suspect that the
price paid is access time.

I enclose a module that you can adapt.
It talks about bytes but they are integers really.
It is different from what you are doing, as it
was aimed at reading and writing bits in 
a hardware context.

If you get your head around the concept,
then it may give you some ideas.  It should
be possible to extend the concept to
pass name,length tuples at construction time
instead of just a name with an implied length 
of one bit, and it may make sense to change
the underlying type from an integer to an 
array of one byte integers.

It is nice to be able to say:
val = bitname() 
to read, and 
bitname(1)
or
bitname(0)
to write.

I can also write:
outputbits[3] = 1
or
val = inputbits[5]

If you can successfully generalise it
to field names It should be very useful.

I cannot think of a way though, to not
have the "in" and "out" split, but you can
program your way around that - you do not
have to update "in place".

- Hendrik

-------------- next part --------------
A non-text attachment was scrubbed...
Name: bits.py
Type: application/x-python
Size: 4379 bytes
Desc: not available
URL: 

From kpalamartchouk at gmail.com  Thu Aug  6 03:46:58 2009
From: kpalamartchouk at gmail.com (kpal)
Date: Thu, 6 Aug 2009 00:46:58 -0700 (PDT)
Subject: Datetime with float seconds
References: 
	
Message-ID: <0819ae46-767f-4256-81d9-f265b7552cd8@h31g2000yqd.googlegroups.com>

On Aug 6, 7:43?am, Hendrik van Rooyen  wrote:

> I am curious as to what would require less than microsecond
> timing - about the only thing I can think of would be something
> involving measuring the speed of light, where nanoseconds
> or better would be nice.

You are right :-) I am trying to write a scientific software that does
some satellite geodesy computations (involving the speed of light),
and I would prefer to keep all the times float, while retaining the
time and time interval arithmetics and format transformation
capabilities of datetime. The system time granularity, that is of
cause limited, is not a problem at all, as the data are to be
initialized by constructing instances from external data.

Thanks


From hendrik at microcorp.co.za  Thu Aug  6 03:58:30 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Thu, 6 Aug 2009 09:58:30 +0200
Subject: Parsing Binary Structures;
	Is there a better way / What is your way?
In-Reply-To: <7x3a86gmfe.fsf@ruckus.brouhaha.com>
References: 
	<7x3a86gmfe.fsf@ruckus.brouhaha.com>
Message-ID: <200908060958.30882.hendrik@microcorp.co.za>

On Wednesday 05 August 2009 20:12:05 Paul Rubin wrote:
> "Martin P. Hellwig"  writes:
> > what I usually do is read the packet in binary mode, convert the
> > output to a concatenated 'binary string'(i.e. '0101011000110') and
>
> Something wrong with reading the data words as an integer and using
> old fashioned shifts and masks to get at the bit fields?

There is nothing wrong with that, and in the final analysis, it is what
is used - however, I can sympathize with the OP, as it is much nicer
to just call a named thing than to juggle a bunch of hard coded
shifts and masks.

I think the real point here is sort of meta programming - what
is needed is a way to describe and name the elements of the
structure so that useful python objects are created.

The code I posted for bits does that, and I use it all the
time - it is almost as good as being back in 8031 assembler
with direct named bit access.

- Hendrik


From contact at xavierho.com  Thu Aug  6 04:05:52 2009
From: contact at xavierho.com (Xavier Ho)
Date: Thu, 6 Aug 2009 18:05:52 +1000
Subject: merge two png pic
In-Reply-To: <69579cfc-9151-43df-a5ef-a6b05f1bd718@13g2000prl.googlegroups.com>
References: 
	
	
	<006617e3-6630-4f04-bff1-99c58dbb6cb5@l5g2000pra.googlegroups.com>
	<4a77e249$0$2449$426a74cc@news.free.fr>
	<72d7aad1-1fb7-4b32-a87f-636505b0faa2@v15g2000prn.googlegroups.com>
	<4a793852$0$19598$426a74cc@news.free.fr>
	<69579cfc-9151-43df-a5ef-a6b05f1bd718@13g2000prl.googlegroups.com>
Message-ID: <2d56febf0908060105p1604f02u57128d23172b3d67@mail.gmail.com>

On Thu, Aug 6, 2009 at 12:17 PM, cocobear  wrote:

>
> I want to view image use Windows Pic View.
>
> If you run out of memory trying to combining those images into a 30k by 40k
pixels image, the Windows Pic View isn't going to be able to display it
either.

Regards,

Ching-Yun "Xavier" Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: contact at xavierho.com
Website: http://xavierho.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From hendrik at microcorp.co.za  Thu Aug  6 04:06:04 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Thu, 6 Aug 2009 10:06:04 +0200
Subject: Parsing Binary Structures;
	Is there a better way / What is your way?
In-Reply-To: 
References: 
	<7xr5vqw0v9.fsf@ruckus.brouhaha.com>
	
Message-ID: <200908061006.04437.hendrik@microcorp.co.za>

On Wednesday 05 August 2009 21:41:26 Martin P. Hellwig wrote:

> Yes you are (of course) right, my 'dream' solution would be something
> that accepts slice indeces on bit level. Your reasoning did reveal some
> flaws in my approach though ;-)

This is the first time I have been compared to the sandman...

:-)

- Hendrik



From martin at v.loewis.de  Thu Aug  6 04:24:08 2009
From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=)
Date: Thu, 06 Aug 2009 10:24:08 +0200
Subject: String to valid Python identifier
In-Reply-To: 
References: 
Message-ID: <4a7a9328$0$2355$9b622d9e@news.freenet.de>

> Is there any easy function in the stdlib to convert any random string in 
> a valid Python identifier .. possibly by replacing non-valid characters 
> with _ ?

I think this is fairly underspecified as a problem statement. A solution
that would meet your specification would be

def mkident(s):
    return "foo"

It returns a valid Python identifier for any random string.

If you now complain that this gives too many collisions, I propose

def mkident(s):
    return "foo%d" % (hash(s) & 0x7fffffff)

Regards,
Martin


From contact at xavierho.com  Thu Aug  6 04:26:22 2009
From: contact at xavierho.com (Xavier Ho)
Date: Thu, 6 Aug 2009 18:26:22 +1000
Subject: Subclassing Python's dict
In-Reply-To: 
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com>
	
	
Message-ID: <2d56febf0908060126i323d499fla4b7a22c934c5e7@mail.gmail.com>

On Thu, Aug 6, 2009 at 1:19 PM, alex23  wrote:

> Xavier Ho wrote:
> > You should subclass collections.UserDict, and not the default dict class.
> > Refer to the collections module.
>
> Xavier, why do you think that is the correct approach?


I'll be honest first and say that I do not completely understand how dict is
implemented in the underlying C structure. But as Bruno had already
mentioned, dict has a slightly different behaviour then we'd expect. For
example, the __getitem__() function isn't actually used by the interpreter
(which, you know, *can* be a problem.)

http://www.python.org/download/releases/2.2.3/descrintro/#subclassing
(I don't know if 2.6.2 changed anything since 2.2.3, but there are some
references you can look at, and sample code.)

To answer your question, it's really not "the correct approach", but I think
(meaning: untested) UserDict doesn't have the same implementation, which
might free up some restrictions Sergey encountered.

The docs say
> "The need for this class has been largely supplanted by the ability to
> subclass directly from dict (a feature that became available starting
> with Python version 2.2)."


I didn't realise they took UserDict out in later versions (2.6, for
example), and put it back in Python 3.0. Does anyone know why?

So, I do not actually know.

> If you mean that Sergey should subclass _in this instance_ could you
> please explain why? (Sorry if you already have, I never saw your
> original post...)
>

It was really more or less an educated guess. He didn't tell us what he is
trying to achieve, so _in this instance_ I can't give more advice than
saying "well, if this doesn't work, here are you other options that I know
of/just found. Try these and let us know if you got it to work." *winks*

-

Sometimes I do answer a little too quickly, I apologise for that.

- Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From iainking at gmail.com  Thu Aug  6 04:28:29 2009
From: iainking at gmail.com (Iain King)
Date: Thu, 6 Aug 2009 01:28:29 -0700 (PDT)
Subject: remove last 76 letters from string
References: 
	
Message-ID: 

>      print >>nucleotides, seq[-76]

> ? ? ?last_part = line.rstrip()[-76 : ]

You all mean:   seq[:-76]   , right? (assuming you've already stripped
any junk off the end of the string)

Iain


From gagsl-py2 at yahoo.com.ar  Thu Aug  6 04:35:57 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 05:35:57 -0300
Subject: os.system in a service
References: 
	
	<7dvda1F2c4s7kU1@mid.uni-berlin.de>
Message-ID: 

En Thu, 06 Aug 2009 03:59:13 -0300, Diez B. Roggisch   
escribi?:
> Gabriel Genellina schrieb:
>> En Wed, 05 Aug 2009 13:07:39 -0300, Lawrence Wong  
>>  escribi?:

>>> I wrote a program which runs a .bat file using os.system like:  
>>> 'os.system(pathToBatFile)' and everything was good.  Then I decided to  
>>> turn my program into a service as opposed to being run with the  
>>> command prompt showing.  When my program became a service, I noticed  
>>> that the os.system command to run my .bat file was no longer working.  
>>> [...]

>>  Capture stdout and stderr and you'll probably see the error message:
>>  some_command >logfile.txt 2>&1
>
> Which isn't possible as a service.

Why you say so? One should avoid using mapped drive letters and network  
shares -- that probably aren't defined for the account under which the  
service runs. And always use absolute paths. And ensure the account has  
write permissions for the output file... But other than that, os.system  
should work fine. Do I miss something?

> The OP might consider using suprocess istead of os.system, and establish  
> pipes to read the output of the command into a file he can analyze.

That's a good idea, although overkill for simple cases I'd say.

-- 
Gabriel Genellina



From martin at v.loewis.de  Thu Aug  6 04:42:33 2009
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Thu, 06 Aug 2009 10:42:33 +0200
Subject: How to comment on a Python PEP?
In-Reply-To: 
References: 
Message-ID: <4a7a9779$0$2384$9b622d9e@news.freenet.de>

> Is there a mechanism for submitting comments on a Python PEP?

You post to python-dev or comp.lang.python, and you CC the author.

Regards,
Martin


From dr.scottgriffiths at gmail.com  Thu Aug  6 04:44:19 2009
From: dr.scottgriffiths at gmail.com (sgriffiths)
Date: Thu, 6 Aug 2009 01:44:19 -0700 (PDT)
Subject: Parsing Binary Structures; Is there a better way / What is your 
	way?
References: 
Message-ID: 

On Aug 5, 3:46?pm, "Martin P. Hellwig" 
wrote:
> Hi List,
>
> On several occasions I have needed (and build) a parser that reads a
> binary piece of data with custom structure. For example (bogus one):
>
> BE
> +---------+---------+-------------+-------------+------+--------+
> | Version | Command | Instruction | Data Length | Data | Filler |
> +---------+---------+-------------+-------------+------+--------+
> Version: 6 bits
> Command: 4 bits
> Instruction: 5 bits
> Data Length: 5 bits
> Data: 0-31 bits
> Filler: filling 0 bits to make the packet dividable by 8
>
> what I usually do is read the packet in binary mode, convert the output
> to a concatenated 'binary string'(i.e. '0101011000110') and then use
> slice indeces to get the right data portions.
> Depending on what I need to do with these portions I convert them to
> whatever is handy (usually an integer).
>
> This works out fine for me. Most of the time I also put the ASCII art
> diagram of this 'protocol' as a comment in the code, making it more
> readable/understandable.
>
> Though there are a couple of things that bothers me with my approach:
> - This seems such a general problem that I think that there must be
> already a general pythonic solution.
> - Using a string for binary representation takes at least 8 times more
> memory for the packet than strictly necessary.
> - Seems to need a lot of prep work before doing the actual parsing.
>
> Any suggestion is greatly appreciated.
>
> --
> MPHhttp://blog.dcuktec.com
> 'If consumed, best digested with added seasoning to own preference.'

Take a look at the bitstring module (in pypi or google code). It's
designed to help make this sort of thing easy and it's more fully
featured than BitVector or BitSet. Internally the data is stored as a
byte array, so memory isn't wasted. It will also do all the dirty work
of bit masking and shifting so that you can concentrate on the real
problems. For example:

>>> s = BitString('0x1232432312')  # just to give us some data to play with
>>> ver, comm, instr, bitlen = s.read('uint6, bin4, bin5, uint5')
>>> data = s.readbits(bitlen)

Different interpretations of the binary data are given using Python
properties (e.g. s.hex, s.oct, s.uint, etc.) and it supports bit-wise
slicing, modification, finding, replacing and more. It is also still
in active development (full disclosure: I'm the author :-)).



From contact at xavierho.com  Thu Aug  6 04:44:45 2009
From: contact at xavierho.com (Xavier Ho)
Date: Thu, 6 Aug 2009 18:44:45 +1000
Subject: remove last 76 letters from string
In-Reply-To: 
References: 
	
	
Message-ID: <2d56febf0908060144g4201d152mbf981c9273d5915f@mail.gmail.com>

On Thu, Aug 6, 2009 at 6:28 PM, Iain King  wrote:

> >      print >>nucleotides, seq[-76]
>
> >      last_part = line.rstrip()[-76 : ]
>
> You all mean:   seq[:-76]   , right? (assuming you've already stripped
> any junk off the end of the string)
>

I think so, probably both of them typo'd. (What are the probabilities of
that?)

It looks to me like you have two lines per DNA sequence. What you could do
instead, is to alternate the line reading with a with statement, as
suggested by Jan. Although I don't know why he's nesting two of them.
(explanation would be neat.)

Here's my version of approach, given the sample data the OP posted:

with open('NodeList.txt', 'r') as file:
    for line in file.readlines():
        line = line.rstrip()
        if line[0] == '>':
            # Do for New DNA Sequence
            # ...
        else:
            line = line[:-76]
            # ...

Should do what you need.

Best regards,

Ching-Yun "Xavier" Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: contact at xavierho.com
Website: http://xavierho.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From sanu1267 at gmail.com  Thu Aug  6 05:25:58 2009
From: sanu1267 at gmail.com (sanju ps)
Date: Thu, 6 Aug 2009 14:55:58 +0530
Subject: handling kill signal
Message-ID: <2b76be80908060225n674cbea5x6511d768c2828be6@mail.gmail.com>

I want to handle a kill signal..In my program i wrote like this

def handler(signum, frame):
    print "Signal",signum
    delete_temp_file()
    exit(1)
signal.signal(signal.SIGTERM, handler)

And when i tried pkill processid .program is exited but not deleting the
temp file
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From thangappan143 at gmail.com  Thu Aug  6 06:30:15 2009
From: thangappan143 at gmail.com (Thangappan.M)
Date: Thu, 6 Aug 2009 16:00:15 +0530
Subject: Problem in installing PyGreSQL
In-Reply-To: 
References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com>
	<7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net>
	<20090804084856.b825967a.darcy@druid.net>
	
	<20090804095547.a5274e22.darcy@druid.net> 
Message-ID: <7aa29e790908060330x67d900a9rfb4677eaf0eddeb@mail.gmail.com>

I have downloaded the  psycopg2 tar file from the following link.
http://initd.org/tracker/psycopg

I have done the following things.
         * Extracting the files from the tar file
         * tried to execute python ./setup.py build

It gives the following error.

#python ./setup.py build

running build
running build_py
running build_ext
Traceback (most recent call last):
  File "./setup.py", line 410, in ?
    ext_modules=ext)
  File "distutils/core.py", line 149, in setup
  File "distutils/dist.py", line 946, in run_commands
  File "distutils/dist.py", line 966, in run_command
  File "distutils/command/build.py", line 112, in run
  File "/usr/lib/python2.4/cmd.py", line 333, in run_command
    del help[cmd]
  File "distutils/dist.py", line 965, in run_command
  File "/usr/lib/python2.4/cmd.py", line 117, in ensure_finalized
    pass
  File "./setup.py", line 219, in finalize_options
    except (Warning, w):
NameError: global name 'w' is not defined

What would be the solution?
Otherwise can you tell how to install DB-API in debian machine.

On Wed, Aug 5, 2009 at 10:43 AM, Dennis Lee Bieber wrote:

> On Tue, 4 Aug 2009 09:55:47 -0400, "D'Arcy J.M. Cain" 
> declaimed the following in gmane.comp.python.general:
>
> >
> > By the way, you don't have to be super user to install PyGreSQL.  You
> > just need SU if you want to install it system wide.  PyGreSQL doesn't
> > require any special privileges to run.
> >
>         Potentially silly question:
>
>        While the DB-API module may be installable in a user mode... Do we
> know if the original querant even has PostgreSQL running and accessible?
>
> The statement
>
> OP> I want to access the database related stuffs in python.So I found
> the
> OP> PyGreSQL module in net.
>
> doesn't leave me with any confidence that they realize this is just an
> access module for one specific server -- and that they still need a
> server to which they can connect.
>
>        If they don't have a PostgreSQL server, it may be better just to
> direct them to SQLite3...
> --
>        Wulfraed        Dennis Lee Bieber               KD6MOG
>        wlfraed at ix.netcom.com           wulfraed at bestiaria.com
>                HTTP://wlfraed.home.netcom.com/
>        (Bestiaria Support Staff:               web-asst at bestiaria.com)
>                HTTP://www.bestiaria.com/
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Regards,
Thangappan.M
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From python at mrabarnett.plus.com  Thu Aug  6 06:34:24 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 11:34:24 +0100
Subject: remove last 76 letters from string
In-Reply-To: 
References: 	
	
Message-ID: <4A7AB1B0.7090606@mrabarnett.plus.com>

Iain King wrote:
>>      print >>nucleotides, seq[-76]
> 
>>      last_part = line.rstrip()[-76 : ]
> 
> You all mean:   seq[:-76]   , right? (assuming you've already stripped
> any junk off the end of the string)
> 
The OP said "cut out the last 76 letters (nucleotides) from each
individual sequence and send them to a new txt file with a similar 
format.", ie extract the last 76 letters (in the same format) to a file.


From deets at nospam.web.de  Thu Aug  6 06:38:39 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Thu, 06 Aug 2009 12:38:39 +0200
Subject: Cython + setuptools not working with .pyx,only with .c-files
Message-ID: <7dvq5fF2e21b7U1@mid.uni-berlin.de>

Hi,


I'm trying to build a Cython-extension as Egg.

However, this doesn't work - I can either use distutils to build the
extension, creating a myextension.c-file on the way.

If that's there, I can use setuptools to build the egg.

But when I remove the .c-file, the .pyx-file isn't used to re-generate it.

This is my setup.py:

----
import os
import glob
from setuptools import setup, Extension
#from distutils.core import setup
#from distutils.extension import Extension

from Cython.Distutils import build_ext


objs = [...] # a static lib I want to wrap

setup(
    name='MyExtension',
    version="0.1",
    description='',
    author='Diez B. Roggisch',
    author_email='...',
    cmdclass = {'build_ext': build_ext},
    ext_modules = [Extension("myextension", ["myextension.pyx"],
                             libraries=["crypto"],
                             extra_objects = objs)],

-----


I can of course check in the myextension.c-file , and then when actually
working on the extension create it new by uncommenting the above lines.

But I guess that's not really the way things should work...

Diez


From pavlovevidence at gmail.com  Thu Aug  6 06:38:53 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Thu, 6 Aug 2009 03:38:53 -0700 (PDT)
Subject: Subclassing Python's dict
References:  
	<4a7999b1$0$306$426a74cc@news.free.fr>
Message-ID: <2c161a54-fade-4753-aa3f-3fee67632056@l5g2000pra.googlegroups.com>

On Aug 5, 7:39?am, Bruno Desthuilliers  wrote:
> Sergey Simonenko a ?crit :
>
> > Hi,
>
> > I subclass builtin 'dict' in my application and experience some problems
> > with it.
>
> > The whole issue is that I should redefine 'setdefault' and 'update'
> > methods after redefining '__setitem__' or/and '__delitem__',
> > otherwise 'update' and 'setdefault' ignore redefined '__setitem__' and
> > use builtin dict's one so dict looks kinda like a black box.
>
> > Another guy have reported me that he experiences similar problems with
> > subclassing builtin 'list'.
>
> I indeed notice this behaviour here (Python 2.6.2). I'm afraid it has to
> do with some optimization tricks (dict being the very fundamental data
> structure in Python, it has to be higly optimized).

You can ultimately blame it on optimization in this case, but in
general there isn't any way (in Python) to require that __setitem__ be
the common point for all modifications.

In fact this is an example of a general condition of OOP.  A "high-
level" method may or may not call a "low-level" method to do its dirty
work, and there is no way to know this simply from the class's
interface.  You need to have knowledge of the implementation to know
whether you need to override "high-level" or "low-level" methods.  In
general you can't safely subclass based on the interface alone; you
have to know what you're subclassing.

(As an aside: this intuitively is the reason why I never cared much
for some of the arguments against inheritance.  Many arguments against
inheritance go like this: "Inheritance is bad because X can happen if
you're not careful".  Doesn't mean anything to me because you have be
careful anyway.)

Because of the care required when subclassing, I tend to use
inheritance only when the intended base class is A. also under my
control, or B. specifically designed to be subclassed.  Examples of B
in the standard Python library are Queue and Thread.  list and dict
are allowed to be subclassed but aren't specifically designed for it,
so I tend not to subclass those.  (It is occasionally indispensible,
though.)


Carl Banks


From cournape at gmail.com  Thu Aug  6 06:57:11 2009
From: cournape at gmail.com (David Cournapeau)
Date: Thu, 6 Aug 2009 19:57:11 +0900
Subject: Using Python to automate builds
In-Reply-To: 
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com>
	
	
Message-ID: <5b8d13220908060357rb2fa7bp519809ce73455c28@mail.gmail.com>

On Thu, Aug 6, 2009 at 12:39 AM, Kosta wrote:

>
> Setenv.bat sets up the path and other environment variables build.exe
> needs to compile and link (and even binplace) its utilities. ?So
> building itself is not the issue. ?The problem is that if I call
> setenv.bat from Python and then build.exe, but the modifications to
> the path (and other environment settings) are not seen by Python, so
> the attempt to build without a specified path fails.

It sounds like you do not propagate the environment when calling
setenv.bat from python. There is an option to do so in
subprocess.Popen init method, or you can define your own environment
if you do not want to propagate the whole environment (but this is
often difficult to avoid for build environment in my experience,
expecially if you don't have access to the sources of the whole system
to check which variables are necessary).

David


From lawrencew00 at hotmail.com  Thu Aug  6 06:58:03 2009
From: lawrencew00 at hotmail.com (Lawrence Wong)
Date: Thu, 6 Aug 2009 10:58:03 +0000
Subject: os.system in a service
In-Reply-To: 
References: 
	
	<7dvda1F2c4s7kU1@mid.uni-berlin.de> 
	
Message-ID: 


I actually found the solution.  I was trying to copy a file from another computer to the current one.  My 'access was denied'.  So I had to go to my service at Admin Tools --> Services and 'Log on as' the Administrator.  Was ok after that.  Thanks for your responses everyone.  

> To: python-list at python.org
> From: gagsl-py2 at yahoo.com.ar
> Subject: Re: os.system in a service
> Date: Thu, 6 Aug 2009 05:35:57 -0300
> 
> En Thu, 06 Aug 2009 03:59:13 -0300, Diez B. Roggisch   
> escribi?:
> > Gabriel Genellina schrieb:
> >> En Wed, 05 Aug 2009 13:07:39 -0300, Lawrence Wong  
> >>  escribi?:
> 
> >>> I wrote a program which runs a .bat file using os.system like:  
> >>> 'os.system(pathToBatFile)' and everything was good.  Then I decided to  
> >>> turn my program into a service as opposed to being run with the  
> >>> command prompt showing.  When my program became a service, I noticed  
> >>> that the os.system command to run my .bat file was no longer working.  
> >>> [...]
> 
> >>  Capture stdout and stderr and you'll probably see the error message:
> >>  some_command >logfile.txt 2>&1
> >
> > Which isn't possible as a service.
> 
> Why you say so? One should avoid using mapped drive letters and network  
> shares -- that probably aren't defined for the account under which the  
> service runs. And always use absolute paths. And ensure the account has  
> write permissions for the output file... But other than that, os.system  
> should work fine. Do I miss something?
> 
> > The OP might consider using suprocess istead of os.system, and establish  
> > pipes to read the output of the command into a file he can analyze.
> 
> That's a good idea, although overkill for simple cases I'd say.
> 
> -- 
> Gabriel Genellina
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

_________________________________________________________________
More storage. Better anti-spam and antivirus protection. Hotmail makes it simple.
http://go.microsoft.com/?linkid=9671357
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From cournape at gmail.com  Thu Aug  6 07:00:09 2009
From: cournape at gmail.com (David Cournapeau)
Date: Thu, 6 Aug 2009 20:00:09 +0900
Subject: Cython + setuptools not working with .pyx,only with .c-files
In-Reply-To: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
References: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
Message-ID: <5b8d13220908060400m4d096726i6d929fb0e32a0327@mail.gmail.com>

On Thu, Aug 6, 2009 at 7:38 PM, Diez B. Roggisch wrote:
> Hi,
>
>
> I'm trying to build a Cython-extension as Egg.
>
> However, this doesn't work - I can either use distutils to build the
> extension, creating a myextension.c-file on the way.
>
> If that's there, I can use setuptools to build the egg.
>
> But when I remove the .c-file, the .pyx-file isn't used to re-generate it.
>
> This is my setup.py:
>
> ----
> import os
> import glob
> from setuptools import setup, Extension
> #from distutils.core import setup
> #from distutils.extension import Extension
>
> from Cython.Distutils import build_ext

What happens if you import setuptools *after* Cython.distutils ? My
guess - I could be wrong - is that both Cython.distutils and
setuptools monkey-patch distutils, and that setuptools does not "see"
Cython.Distutils. It could also be an incompatibility between
Cython.Distutils and setuptools (the design of distutils forces you to
take into account the details of things modified by every distutils
extension).

cheers,

David


From doron.tal.list at gmail.com  Thu Aug  6 08:00:45 2009
From: doron.tal.list at gmail.com (Doron Tal)
Date: Thu, 6 Aug 2009 15:00:45 +0300
Subject: inspect.stack() performance
Message-ID: <2a8674c60908060500k1c77b556la70d06d5feaaef0e@mail.gmail.com>

I use inspect.stack() to extract some info, such as file name, function name
and line number, for the sake of logging (home brew logger).
I tested to see how much time it takes to execute the command:

Python 2.4.3 (#1, Jan 21 2009, 01:11:33)
[GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> t = timeit.Timer('inspect.stack()', 'import inspect')
>>> t.repeat(3,1000)
[0.28500604629516602, 0.28315305709838867, 0.29169297218322754]
>>>

About 280uSec per call.

If I log 1000 times per seconds than I get to spend 28% of the process time
on inspect.stack()
Is there a better/quicker way of retrieving the same info?

Thanks,
--doron
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From Michalek.Jan at uhul.cz  Thu Aug  6 08:37:55 2009
From: Michalek.Jan at uhul.cz (=?iso-8859-2?Q?MICH=C1LEK_Jan_Mgr=2E?=)
Date: Thu, 6 Aug 2009 14:37:55 +0200
Subject: one method of COM object needs a variant type variable
Message-ID: <913F77222E913C49A057FDD7BBDEAAA30192B846@br-dc.uhul.wan>

How i can use this type in win32.com? One method of com object (geomedia storage service) needs this variable for storage geometry of geometry object (this variable will be writen into blob in DB). Is possible make this variable in py??
Thanks Jelen/Stack
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From marcusw at cox.net  Thu Aug  6 09:24:33 2009
From: marcusw at cox.net (Marcus Wanner)
Date: Thu, 06 Aug 2009 09:24:33 -0400
Subject: Overlap in python
In-Reply-To: <4c9f81a5-51b9-4487-9df9-d458b327d286@s15g2000yqs.googlegroups.com>
References: 	<4A78B19D.4020306@mrabarnett.plus.com>	
	<4c9f81a5-51b9-4487-9df9-d458b327d286@s15g2000yqs.googlegroups.com>
Message-ID: 

On 8/5/2009 10:56 AM, nn wrote:
> On Aug 5, 7:13 am, Marcus Wanner  wrote:
>> On 8/4/2009 6:09 PM, MRAB wrote:
>>
>>>  >>> parts = [(5, 9, "a"), (7, 10, "b"), (3, 6, "c"), (15, 20, "d"),
>>> (18, 23, "e")]
>>>  >>> parts.sort()
>>>  >>> parts
>>> [(3, 6, 'c'), (5, 9, 'a'), (7, 10, 'b'), (15, 20, 'd'), (18, 23, 'e')]
>>>  >>> # Merge overlapping intervals.
>>>  >>> pos = 1
>>>  >>> while pos < len(parts):
>>>         # Merge the pair in parts[pos - 1 : pos + 1] if they overlap.
>>>         p, q = parts[pos - 1 : pos + 1]
>>>         if p[1] >= q[0]:
>>>                 parts[pos - 1 : pos + 1] = [(p[0], max(p[1], q[1]), p[2]
>>> + "." + q[2])]
>>>         else:
>>>                 # They don't overlap, so try the next pair.
>>>                 pos += 1
>>>  >>> parts
>>> [(3, 10, 'c.a.b'), (15, 23, 'd.e')]
>> That's the best solution I've seen so far. It even has input/output
>> formatted as close as is reasonably possible to the format specified.
>>
>> As we would say in googlecode, +1.
>>
>> Marcus
> 
> How does it compare to this one?
> 
> http://groups.google.com/group/comp.lang.python/browse_frm/thread/1a1d2ed9d05d11d0/56684b795fc527cc#56684b795fc527cc
That is a different problem, and the solution is more complex.
I am not going to try to judge which is better.

Marcus

-- 
print ''.join([chr(((ord(z)+(ord("I'M/THE"[3])+sum(
     [ord(x)for x in 'CRYPTOR'])))%(4*ord('8')+ord(
     ' ')))) for z in ''.join(([(('\xca\x10\x03\t'+
     '\x01\xff\xe6\xbe\x0c\r\x06\x12\x17\xee\xbe'+
     '\x10\x03\x06\x12\r\x0c\xdf\xbe\x12\x11\x13'+
     '\xe8')[13*2-y]) for y in range(int(6.5*4)+1)]
     ))])



From tjreedy at udel.edu  Thu Aug  6 09:55:04 2009
From: tjreedy at udel.edu (Terry Reedy)
Date: Thu, 06 Aug 2009 22:55:04 +0900
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
Message-ID: 

RayS wrote:
> At 08:35 PM 8/5/2009 -0700, r wrote:
>> """... Any real sense of community is undermined -- or
>> even destroyed -- to be replaced by virtual equivalents that strive,
>> unsuccessfully, to synthesize a sense of community."""
> 
> I've brought up the idea of the quasi-community doc that PHP uses to 
> good effect.

And what have you done about setting up such a project?

> http://www.php.net/manual/en/language.types.array.php is a prime example 
> where 2/3 of the "doc" is user-contributed comments and code.

I consider consider this to an unreadable mishmash. If you and others 
want something like that, do it.  And quite bitching about the work of 
those of us who have done something compact and readable. We are all 
volunteers here.

tjr



From iainking at gmail.com  Thu Aug  6 09:58:13 2009
From: iainking at gmail.com (Iain King)
Date: Thu, 6 Aug 2009 06:58:13 -0700 (PDT)
Subject: remove last 76 letters from string
References: 
	
	
	
Message-ID: <938fdab5-65c5-47a0-8386-95edc470da9e@a26g2000yqn.googlegroups.com>

On Aug 6, 11:34?am, MRAB  wrote:
> Iain King wrote:
> >> ? ? ?print >>nucleotides, seq[-76]
>
> >> ? ? ?last_part = line.rstrip()[-76 : ]
>
> > You all mean: ? seq[:-76] ? , right? (assuming you've already stripped
> > any junk off the end of the string)
>
> The OP said "cut out the last 76 letters (nucleotides) from each
> individual sequence and send them to a new txt file with a similar
> format.", ie extract the last 76 letters (in the same format) to a file.

So he did.  Excuse me while I go eat my other foot.


From tack at urandom.ca  Thu Aug  6 10:15:41 2009
From: tack at urandom.ca (Jason Tackaberry)
Date: Thu, 06 Aug 2009 10:15:41 -0400
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 
	<1249487636.7120.798.camel@arrakis>
	
Message-ID: <1249568141.10840.37.camel@arrakis>

On Thu, 2009-08-06 at 01:31 +0000, John Machin wrote:
> Faster by an enormous margin; attributing this to the cost of attribute lookup
> seems implausible.

Ok, fair point.  I don't think the time difference fully registered when
I composed that message.

Testing a global access (LOAD_GLOBAL) versus an attribute access on a
global object (LOAD_GLOBAL + LOAD_ATTR) shows that the latter is about
40% slower than the former.  So that certainly doesn't account for the
difference.


> Suggested further avenues of investigation:
> 
> (1) Try the timing again with "cp1252" and "utf8" and "utf_8"
> 
> (2) grep "utf-8" /Objects/unicodeobject.c

Very pedagogical of you. :)  Indeed, it looks like bigger player in the
performance difference is the fact that the code path for unicode(s,
enc) short-circuits the codec registry for common encodings (which
includes 'utf-8' specifically), whereas s.decode('utf-8') necessarily
consults the codec registry.

Cheers,
Jason.



From thorsten at thorstenkampe.de  Thu Aug  6 10:32:34 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Thu, 6 Aug 2009 16:32:34 +0200
Subject: unicode() vs. s.decode()
References: 
Message-ID: 

* Michael Str?der (Wed, 05 Aug 2009 16:43:09 +0200)
> These both expressions are equivalent but which is faster or should be
> used for any reason?
> 
> u = unicode(s,'utf-8')
> 
> u = s.decode('utf-8') # looks nicer

"decode" was added in Python 2.2 for the sake of symmetry to encode(). 
It's essentially the same as unicode() and I wouldn't be surprised if it 
is exactly the same. I don't think any measurable speed increase will be 
noticeable between those two.

Thorsten


From sbassi at clubdelarazon.org  Thu Aug  6 10:35:36 2009
From: sbassi at clubdelarazon.org (Sebastian Bassi)
Date: Thu, 6 Aug 2009 11:35:36 -0300
Subject: ANN: Python for Bioinformatics book
Message-ID: <9e2f512b0908060735w7d270238y773275d45c46a954@mail.gmail.com>

"Python for Bioinformatics"
ISBN 1584889292
Amazon: http://www.tinyurl.com/biopython
Publisher: http://www.crcpress.com/product/isbn/9781584889298

This book introduces programming concepts to life science researchers,
bioinformaticians, support staff, students, and everyone who is
interested in applying programming to solve biologically-related
problems. Python is the chosen programming language for this task
because it is both powerful and easy-to-use.

It begins with the basic aspects of the language (like data types and
control structures) up to essential skills on today's bioinformatics
tasks like building web applications, using relational database
management systems, XML and version control. There is a chapter
devoted to Biopython (www.biopython.org) since it can be used for most
of the tasks related to bioinformatics data processing.

There is a section with applications with source code, featuring
sequence manipulation, filtering vector contamination, calculating DNA
melting temperature, parsing a genbank file, inferring splicing sites,
and more.

There are questions at the end of every chapter and odd numbered
questiona are answered in an appendix making this text suitable for
classroom use.

This book can be used also as a reference material as it includes
Richard Gruet's Python Quick Reference, and the Python Style Guide.

DVD: The included DVD features a virtual machine with a special
edition of DNALinux, with all the programs and complementary files
required to run the scripts commented in the book. All scripts can be
tweaked to fit a particular configuration. By using a pre-configured
virtual machine the reader has access to the same development
environment than the author, so he can focus on learning Python. All
code is also available at the http://py3.us/## where ## is the code
number, for example: http://py3.us/57

I've been working on this book for more than two years testing the
examples under different setups and working to make the code
compatible for most versions of Python, Biopython and operating
systems. Where there is code that only works with a particular
dependency, this is clearly noted.

Finally, I want to highlight that non-bioinformaticians out there can
use this book as an introduction to bioinformatics by starting with
the included "Diving into the Gene Pool with BioPython" (by Zachary
Voase and published originally in Python Magazine).


-- 
Sebasti?n Bassi. Diplomado en Ciencia y Tecnolog?a.

Non standard disclaimer: READ CAREFULLY. By reading this email,
you agree, on behalf of your employer, to release me from all
obligations and waivers arising from any and all NON-NEGOTIATED
agreements, licenses, terms-of-service, shrinkwrap, clickwrap,
browsewrap, confidentiality, non-disclosure, non-compete and
acceptable use policies ("BOGUS AGREEMENTS") that I have
entered into with your employer, its partners, licensors, agents and
assigns, in perpetuity, without prejudice to my ongoing rights and
privileges. You further represent that you have the authority to release
me from any BOGUS AGREEMENTS on behalf of your employer.


From kee at kagi.com  Thu Aug  6 10:39:10 2009
From: kee at kagi.com (Kee Nethery)
Date: Thu, 6 Aug 2009 07:39:10 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
Message-ID: <701EC8AD-A151-46F9-A393-31B3960CE2FC@kagi.com>


On Aug 6, 2009, at 6:55 AM, Terry Reedy wrote:

> RayS wrote:
>> At 08:35 PM 8/5/2009 -0700, r wrote:
>>> """... Any real sense of community is undermined -- or
>>> even destroyed -- to be replaced by virtual equivalents that strive,
>>> unsuccessfully, to synthesize a sense of community."""
>> I've brought up the idea of the quasi-community doc that PHP uses  
>> to good effect.
>
> And what have you done about setting up such a project?
>
>> http://www.php.net/manual/en/language.types.array.php is a prime  
>> example where 2/3 of the "doc" is user-contributed comments and code.
>
> I consider consider this to an unreadable mishmash. If you and  
> others want something like that, do it.  And quite bitching about  
> the work of those of us who have done something compact and  
> readable. We are all volunteers here.

As I struggle through trying to figure out how to make python do  
simple stuff for me, I frequently generate samples. If some volunteer  
here would point me towards the documentation that would tell me how I  
can alter the existing Python docs to include sample code, I'd be more  
than happy to do so.

I would like to "do it". Please point me to the docs that tell me how  
to "do it" so that we people with newbie questions and a need for  
examples can get out of your way and "do it" ourselves.

Thanks,
Kee Nethery





From jakecjacobson at gmail.com  Thu Aug  6 10:50:07 2009
From: jakecjacobson at gmail.com (jakecjacobson)
Date: Thu, 6 Aug 2009 07:50:07 -0700 (PDT)
Subject: Help making this script better
Message-ID: <2f8e34ec-01aa-4ec4-9636-a8ec1f87c68c@o6g2000yqj.googlegroups.com>

Hi,

After much Google searching and trial & error, I was able to write a
Python script that posts XML files to a REST API using HTTPS and
passing PEM cert & key file.  It seems to be working but would like
some pointers on how to handle errors.  I am using Python 2.4, I don't
have the capability to upgrade even though I would like to.  I am very
new to Python so help will be greatly appreciated and I hope others
can use this script.

#!/usr/bin/python
#################################################################
# catalog_feeder.py
#################################################################
# This sciript will process a directory of XML files and push them to
the Enterprise Catalog.
#  You configure this script by using a configuration file that
describes the required variables.
#  The path to this file is either passed into the script as a command
line argument or hard coded
#  in the script.  The script will terminate with an error if it can't
process the XML file.
#################################################################

# IMPORT STATEMENTS
import httplib
import mimetypes
import os
import sys
import shutil
import time
from urllib import *
from time import strftime
from xml.dom import minidom

def main(c):
	start_time = time.time()
	# Set configuration parameters
	try:
		# Process the XML conf file ....
		xmldoc = minidom.parse(c)
		catalog_host = readConfFile(xmldoc, 'catalog_host')
		catalog_port = int(readConfFile(xmldoc, 'catalog_port'))
		catalog_path = readConfFile(xmldoc, 'catalog_path')
		collection_name = readConfFile(xmldoc, 'collection_name')
		cert_file = readConfFile(xmldoc, 'cert_file')
		key_file = readConfFile(xmldoc, 'key_file')
		log_file = readConfFile(xmldoc, 'log_file')
		input_dir = readConfFile(xmldoc, 'input_dir')
		archive_dir = readConfFile(xmldoc, 'archive_dir')
		hold_dir = readConfFile(xmldoc, 'hold_dir')
	except Exception, inst:
		# I had an error so report it and exit script
		print "Unexpected error opening %s: %s" % (c, inst)
		sys.exit(1)
	# Log Starting
	logOut = verifyLogging(log_file)
	if logOut:
		log(logOut, "Processing Started ...")
	# Get list of XML files to process
	if os.path.exists(input_dir):
		files = getFiles2Post(input_dir)
	else:
		if logOut:
			log(logOut, "WARNING!!! Couldn't find input directory: " +
input_dir)
			cleanup(logOut)
		else:
			print "Dir doen't exist: " + input_dir
			sys.exit(1)
	try:
		# Process each file to the catalog
		connection = httplib.HTTPSConnection(catalog_host, catalog_port,
key_file, cert_file)
		for file in files:
			log(logOut, "Processing " + file + " ...")
			try:
				response = post2Catalog(connection, catalog_path, os.path.join
(input_dir, file), collection_name)
				if response.status == 200:
					msg = "Succesfully posted " +  file + " to cataloge ..."
					print msg
					log(logOut, msg)
					# Move file to done directory
					shutil.move(os.path.join(input_dir, file), os.path.join
(archive_dir, file))
				else:
					msg = "Error posting " +  file + " to cataloge [" + response.read
() + "] ..."
					print msg
					log(logOut, response.read())
					# Move file to error dir
					shutil.move(os.path.join(input_dir, file), os.path.join(hold_dir,
file))
			except IOError, (errno):
				print "%s" % (errno)

	except httplib.HTTPException, (e):
		print "Unexpected error %s " % (e)

	run_time = time.time() - start_time
	print 'Run time: %f seconds' % run_time

	# Clean up
	connection.close()
	cleanup(logOut)

# Get an arry of files from the input_dir
def getFiles2Post(d):
	return (os.listdir(d))

# Read out the conf file and set the needed global variable
def readConfFile(xmldoc, tag):
	return (xmldoc.getElementsByTagName(tag)[0].firstChild.data)

# Write out the message to log file
def log(f, m):
	f.write(strftime("%Y-%m-%d %H:%M:%S") + " : " + m + '\n')

# Clean up and exit
def cleanup(logOut):
	if logOut:
		log(logOut, "Processing Ended ...\n")
		logOut.close()
	sys.exit(0)

# Verify if we can write to the log file and return a file handle if
we can
def verifyLogging(l):
	fh=''  # No logging default behavior
	if os.path.exists(os.path.dirname(l)):
		fh = open(l, 'a')
	return(fh)

# Print out the usage of this script
def printusage():
	print""
	print
"**************************************************************************************************"
	print " Must provide the path to the configuration file when calling
this script ..."
	print " Example: " + sys.argv[0] + " /path_2_configuration_file/
conf.xml"
	print
"**************************************************************************************************"
	print ""
	sys.exit(1)

#############################
# Posting XML file to the Catelog Service
#############################
def post2Catalog(connection, path, file, collection):
	head = {"Content-Type" : "application/x-www-form-urlencoded",
"Accept" : "text/plain"}
	parameters = urlencode({"collection" : collection, "entryxml" : open
(file,'r').read()})
	connection.request('POST', path, parameters, head)
	response = connection.getresponse()
	# To reuse the connection, I have to read the response.  I really
don't care about it so I do nothing with it.
	body = response.read()
	return response

# Main
if __name__ == "__main__":
	_pathname = os.path.dirname(sys.argv[0])
	total=len(sys.argv)
	if len(sys.argv) > 1:
		main(sys.argv[1])
	else:
		printusage()


From bearophileHUGS at lycos.com  Thu Aug  6 10:52:44 2009
From: bearophileHUGS at lycos.com (Bearophile)
Date: Thu, 6 Aug 2009 07:52:44 -0700 (PDT)
Subject: ANN: Python for Bioinformatics book
References: 
Message-ID: 

Sebastian Bassi:

> All code is also available at thehttp://py3.us/##where ## is the code number, for example:http://py3.us/57<

The book looks interesting, but that doesn't look like a good way to
show/offer the code. I suggest to also put it into a zip that can be
downloaded.

Bye,
bearophile


From josepharmbruster at gmail.com  Thu Aug  6 11:05:20 2009
From: josepharmbruster at gmail.com (joseph armbruster)
Date: Thu, 6 Aug 2009 08:05:20 -0700 (PDT)
Subject: FCC Amateur Radio database -> SQLite
Message-ID: <1b304bef-150f-405d-a66a-6ec2979a1f2c@a1g2000yqn.googlegroups.com>

Here is a quick way to get the amateur radio database from the FCC put
into sqlite.  If anyone has insight into a pure-python import, please
comment.

http://libjoe.blogspot.com/2009/08/loading-up-fcc-license-database.html

Joseph Armbruster
http://www.joevial.com


From kuchunwah01 at yahoo.com  Thu Aug  6 11:19:20 2009
From: kuchunwah01 at yahoo.com (John)
Date: Thu, 6 Aug 2009 08:19:20 -0700 (PDT)
Subject: convert non-delimited to delimited
Message-ID: <768586.94351.qm@web65602.mail.ac4.yahoo.com>

I am not really a CS person, but I have a task to import a non-delimited text to an access database.? After some research, I *think* the best way to do this is by first converting the non-delimited text to delimited text, and then import it to the database.? Is this the best way to approach this?? Or is there easier way?

Example:
---------------------------------------------------------------------------
Test , BTS
0800000532
05/MAY/1945 00:00
Female
858327
AB Pos
�

CMV Neg Req'd
IgA Deficient




Wr(a+)
S-


>> OCT/23/07 08:18:00 TRETHEWEYD >>>>>>>>>>>>>>>>> Please fax to:
>> OCT/22/07 09:37:00 [COMBINE] [Combine from person_id 924598 to person_id 858327]
[Following comments for to person_id 924598]
>> OCT/18/07 15:53:00 TRETHEWEYD 2007/10/18 15:52

-----------------------------------------------------------------------------------
Basically there are 2 portions to this.? The first portion consist of 7 lines (Full Name, Medical record number, birth date, gender, internal ID, blood group, phenotype).? The second portion list the different list of requirements, denote by  and .? In the sample shown above, the patient do not have information on phenotype, thus there is the � symbol.? 
?
I am really stump on where to go from here.? Any help would be appreciated it.? I have also include a text file which gives several more examples.
?
Thanks so much!


      __________________________________________________________________
Looking for the perfect gift? Give the gift of Flickr! 

http://www.flickr.com/gift/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: samplepatient.txt
Type: application/octet-stream
Size: 48996 bytes
Desc: not available
URL: 

From sbassi at clubdelarazon.org  Thu Aug  6 11:34:35 2009
From: sbassi at clubdelarazon.org (Sebastian Bassi)
Date: Thu, 6 Aug 2009 12:34:35 -0300
Subject: ANN: Python for Bioinformatics book
In-Reply-To: 
References: 
	
Message-ID: <9e2f512b0908060834g5ad2ce34vbc2df78d16a24f69@mail.gmail.com>

On Thu, Aug 6, 2009 at 11:52 AM, Bearophile wrote:
> The book looks interesting, but that doesn't look like a good way to
> show/offer the code. I suggest to also put it into a zip that can be
> downloaded.

Code is also in a directory in the DVD and also inside the virtual
machine. Anyway I think it wouldn't hurt to make a zip and put it
online, so i will do it. Thanks.
Best,
SB.


From rcdailey at gmail.com  Thu Aug  6 11:35:57 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 08:35:57 -0700 (PDT)
Subject: Help with regex
Message-ID: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>

Hey guys,

I'm creating a python script that is going to try to search a text
file for any text that matches my regular expression. The thing it is
looking for is:

FILEVERSION #,#,#,#

The # symbol represents any number that can be any length 1 or
greater. Example:

FILEVERSION 1,45,10082,3

The regex should only match the exact above. So far here's what I have
come up with:

re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )

This works, but I was hoping for something a bit cleaner. I'm having
to create a special case portion of the regex for the last of the 4
numbers simply because it doesn't end with a comma like the first 3.
Is there a better, more compact, way to write this regex?


From mydevforums at gmail.com  Thu Aug  6 11:49:30 2009
From: mydevforums at gmail.com (IronyOfLife)
Date: Thu, 6 Aug 2009 08:49:30 -0700 (PDT)
Subject: Python configuration question when python scripts are executed 
	using Appweb as web server.
References: 
	
	
	
Message-ID: 

Hi Gabriel

On Aug 5, 4:18?pm, "Gabriel Genellina"  wrote:
> En Tue, 04 Aug 2009 10:15:24 -0300, IronyOfLife 
> escribi?:
>
> > On Aug 3, 8:42?pm, "Gabriel Genellina"  wrote:
> >> En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife  ?
> >> escribi?:
>
> >> > I have installed python 2.6.2 in windows xp professional machine. I
> >> > have set the following environment variables -- PYTHONPATH. It points
> >> > to following windows folders: python root folder, the lib folder and
> >> > lib-tk folder.
>
> >> Why? Did you read it somewhere? Usually there is no need to set the ?
> >> PYTHONPATH variable at all; remove it.
>
> > Setting PYTHONPATH environment variables is mentioned in Python docs.
>
> Could you provide a link please? Setting PYTHONPATH should not be

Here are couple of links that discusses setting PYTHONPATH environment
variable.
http://docs.python.org/using/windows.html
http://www.daimi.au.dk/~chili/PBI/pythonpath.html

> necesary, and in fact it's a very bad idea. Environment variables are
> global, but Python modules may depend on the Python version, architecture,
> install location... By example, you may install a 64 bits Python 3.1
> version *and* a 32 bits Python 2.5 version and they both can coexist
> peacefully - but an extension module compiled for the former cannot be
> used in the later version. You must build a separate library for each
> version, and install them in two separate directories. But since the
> PYTHONPATH variable is shared by all installations, which directory should
> contain?
> It's best not to use PYTHONPATH at all and rely on other alternatives
> (like .pth files, that are searched relative to the current Python
> executable, so different versions use different configuration files)

I understand your concerns regarding setting of PYTHONPATH while
multiple versions of Python are installed on the same machine. My fix
however does not use PYTHONPATH. The GNUTLS wrapper module for PYTHON
loads the GNUTLS dll's and it was not able to find them. Using FileMon
(win tool) I found out the paths that are scanned and I copied the
dlls to one of such paths. I still do not like this fix. This is a
temporary solution.

Can you explain maybe with some sample how to set .pth files? Maybe
this will resolve my issue.
>
> > I solved the issue temporarily by copying the gnutls related dlls to
> > the path searched by python.exe
>
> Glad to see you could finally fix it!
>
> --
> Gabriel Genellina

Thanks very much for your reply.


From wuwei23 at gmail.com  Thu Aug  6 11:52:51 2009
From: wuwei23 at gmail.com (alex23)
Date: Thu, 6 Aug 2009 08:52:51 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
Message-ID: <96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>

Kee Nethery wrote:
> As I struggle through trying to figure out how to make python do ?
> simple stuff for me, I frequently generate samples. If some volunteer ?
> here would point me towards the documentation that would tell me how I ?
> can alter the existing Python docs to include sample code, I'd be more ?
> than happy to do so.

No offence, but the last thing the official documentation needs is
example code written by people learning how to code. Suggest changes,
request clarifications, submit samples for review, sure, but direct
modification by users? I've seen the PHP docs; thanks but no thanks.

> I would like to "do it". Please point me to the docs that tell me how ?
> to "do it" so that we people with newbie questions and a need for ?
> examples can get out of your way and "do it" ourselves.

You start by reading this: http://docs.python.org/documenting/index.html
And this: http://www.python.org/dev/contributing/
And this: http://wiki.python.org/moin/WikiGuidelines

The first link, which directly answers your question, is clearly
listed on the doc contents page as "Documenting Python". I'm uncertain
how the docs could be made any _more_ helpful if people aren't
prepared to put effort into reading them. We're a long way away from
direct upload to the brain, unfortunately.

If you're learning the language, you should also consider using more
appropriate resources:
http://mail.python.org/mailman/listinfo/tutor
http://www.doughellmann.com/PyMOTW/
http://diveintopython.org/

The documentation cannot be all things to all people, and it most
certainly can't be a guide to general programming, which is what often
seems to be the issue with novice users. Python's a great language to
learn how to program in, sure, but I would hate to see that become the
focus of the docs.


From python at mrabarnett.plus.com  Thu Aug  6 12:02:44 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 17:02:44 +0100
Subject: Help with regex
In-Reply-To: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
Message-ID: <4A7AFEA4.4050800@mrabarnett.plus.com>

Robert Dailey wrote:
> Hey guys,
> 
> I'm creating a python script that is going to try to search a text
> file for any text that matches my regular expression. The thing it is
> looking for is:
> 
> FILEVERSION #,#,#,#
> 
> The # symbol represents any number that can be any length 1 or
> greater. Example:
> 
> FILEVERSION 1,45,10082,3
> 
> The regex should only match the exact above. So far here's what I have
> come up with:
> 
> re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
> 
> This works, but I was hoping for something a bit cleaner. I'm having
> to create a special case portion of the regex for the last of the 4
> numbers simply because it doesn't end with a comma like the first 3.
> Is there a better, more compact, way to write this regex?

The character class \d is equivalent to [0-9], and ',' isn't a special
character so it doesn't need to be escaped:

     re.compile(r'FILEVERSION (?:\d+,){3}\d+')


From wuwei23 at gmail.com  Thu Aug  6 12:07:51 2009
From: wuwei23 at gmail.com (alex23)
Date: Thu, 6 Aug 2009 09:07:51 -0700 (PDT)
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
Message-ID: <2b20f8fe-86e7-452e-ae94-e9179627fc74@y4g2000prf.googlegroups.com>

On Aug 7, 1:35?am, Robert Dailey  wrote:
> I'm creating a python script that is going to try to search a text
> file for any text that matches my regular expression. The thing it is
> looking for is:
>
> FILEVERSION 1,45,10082,3

Would it be easier to do it without regex? The following is untested
but I would probably do it more like this:

TOKEN = 'FILEVERSION '
for line in file:
  if line.startswith(TOKEN):
    version = line[len(TOKEN):]
    maj, min, rev, other = version.split(',')
    break # if there's only one occurance, otherwise do stuff here


From sion at viridian.paintbox  Thu Aug  6 12:11:24 2009
From: sion at viridian.paintbox (Sion Arrowsmith)
Date: Thu, 06 Aug 2009 16:11:24 GMT
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
Message-ID: 

Terry Reedy   wrote:
>RayS wrote:
>> http://www.php.net/manual/en/language.types.array.php is a prime example 
>> [ ... ]
>I consider consider this to an unreadable mishmash.
[compared to]
> something compact and readable.

Are you talking about the language or the documentation? 9-)

(Actually, that might be a serious point: does the approach to
documentation reflect language design?)

-- 
\S

   under construction



From atragor at gmail.com  Thu Aug  6 12:12:53 2009
From: atragor at gmail.com (Roman)
Date: Thu, 6 Aug 2009 20:12:53 +0400
Subject: Help with regex
In-Reply-To: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
Message-ID: <20090806161253.GA6789@localhost>

On 06/08/09 08:35, Robert Dailey wrote:
> Hey guys,
> 
> I'm creating a python script that is going to try to search a text
> file for any text that matches my regular expression. The thing it is
> looking for is:
> 
> FILEVERSION #,#,#,#
> 
> The # symbol represents any number that can be any length 1 or
> greater. Example:
> 
> FILEVERSION 1,45,10082,3
> 
> The regex should only match the exact above. So far here's what I have
> come up with:
> 
> re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
> 
> This works, but I was hoping for something a bit cleaner. I'm having
> to create a special case portion of the regex for the last of the 4
> numbers simply because it doesn't end with a comma like the first 3.
> Is there a better, more compact, way to write this regex?
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

Since there cannot be more than one "end of string" you can try this
expression:
re.compile( r'FILEVERSION (?:[0-9]+(,|$)){4}' )


From rcdailey at gmail.com  Thu Aug  6 12:14:08 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 09:14:08 -0700 (PDT)
Subject: Character encoding & the copyright symbol
Message-ID: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>

Hello,

I'm loading a file via open() in Python 3.1 and I'm getting the
following error when I try to print the contents of the file that I
obtained through a call to read():

UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
position 1650: character maps to 

The file is defined as ASCII and the copyright symbol shows up just
fine in Notepad++. However, Python will not print this symbol. How can
I get this to work? And no, I won't replace it with "(c)". Thanks!


From robert.kern at gmail.com  Thu Aug  6 12:14:51 2009
From: robert.kern at gmail.com (Robert Kern)
Date: Thu, 06 Aug 2009 11:14:51 -0500
Subject: How to comment on a Python PEP?
In-Reply-To: <4a7a9779$0$2384$9b622d9e@news.freenet.de>
References: 
	<4a7a9779$0$2384$9b622d9e@news.freenet.de>
Message-ID: 

On 2009-08-06 03:42, "Martin v. L?wis" wrote:
>> Is there a mechanism for submitting comments on a Python PEP?
>
> You post to python-dev or comp.lang.python, and you CC the author.

And be sure to put the PEP number in the Subject: line.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From rcdailey at gmail.com  Thu Aug  6 12:17:10 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 09:17:10 -0700 (PDT)
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
Message-ID: <64c96ebc-ce6f-4657-968e-4cbe77a8303d@t13g2000yqt.googlegroups.com>

On Aug 6, 11:02?am, MRAB  wrote:
> Robert Dailey wrote:
> > Hey guys,
>
> > I'm creating a python script that is going to try to search a text
> > file for any text that matches my regular expression. The thing it is
> > looking for is:
>
> > FILEVERSION #,#,#,#
>
> > The # symbol represents any number that can be any length 1 or
> > greater. Example:
>
> > FILEVERSION 1,45,10082,3
>
> > The regex should only match the exact above. So far here's what I have
> > come up with:
>
> > re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
>
> > This works, but I was hoping for something a bit cleaner. I'm having
> > to create a special case portion of the regex for the last of the 4
> > numbers simply because it doesn't end with a comma like the first 3.
> > Is there a better, more compact, way to write this regex?
>
> The character class \d is equivalent to [0-9], and ',' isn't a special
> character so it doesn't need to be escaped:
>
> ? ? ?re.compile(r'FILEVERSION (?:\d+,){3}\d+')

But ',' is a special symbol It's used in this way:
{0,3}

This will match the previous regex 0-3 times. Are you sure commas need
not be escaped?

In any case, your suggestions help to clean it up a bit!


From rylesny at gmail.com  Thu Aug  6 12:20:28 2009
From: rylesny at gmail.com (ryles)
Date: Thu, 6 Aug 2009 09:20:28 -0700 (PDT)
Subject: Web page data and urllib2.urlopen
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
Message-ID: <923ea664-5da0-480b-a114-e83c831a44c8@f10g2000vbf.googlegroups.com>

On Aug 5, 4:30?pm, Massi  wrote:
> Hi everyone, I'm using the urllib2 library to get the html source code
> of web pages. In general it works great, but I'm having to do with a
> financial web site which does not provide the souce code I expect. As
> a matter of fact if you try:
>
> import urllib2
> res = urllib2.urlopen("http://www.marketwatch.com/story/mondays-
> biggest-gaining-and-declining-stocks-2009-07-27")
> page = res.read()
> print page
>
> you will see that the printed code is very different from the one
> given, for example, by mozilla. Since I have really little knowledge
> in html I can't even understand if this is a python or html problem.
> Can anyone give me some help?
> Thanks in advance.

Check if setting your user agent to Mozilla results in a different
page:

http://diveintopython.org/http_web_services/user_agent.html


From http  Thu Aug  6 12:20:33 2009
From: http (Paul Rubin)
Date: 06 Aug 2009 09:20:33 -0700
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
Message-ID: <7xab2c52y6.fsf@ruckus.brouhaha.com>

alex23  writes:
> No offence, but the last thing the official documentation needs is
> example code written by people learning how to code. Suggest changes,
> request clarifications, submit samples for review, sure, but direct
> modification by users? I've seen the PHP docs; thanks but no thanks.

The PHP docs as I remember are sort of regular (non-publically
editable) doc pages, each of which has a public discussion thread
where people can post questions and answers about the topic of that
doc page.  I thought it worked really well.  The main thing is that
the good stuff from the comment section gets folded into the actual
doc now and then.

There is something similar with the PostgreSQL docs.  There is also
Real World Haskell (http://book.realworld.haskell.org) which has a lot
of interspersed user comments.  It would be cool if Python's doc site
did something like it too.


From michael at stroeder.com  Thu Aug  6 12:26:09 2009
From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=)
Date: Thu, 06 Aug 2009 18:26:09 +0200
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 
	
Message-ID: <2qcrk6-doj.ln1@nb2.stroeder.com>

Thorsten Kampe wrote:
> * Michael Str?der (Wed, 05 Aug 2009 16:43:09 +0200)
>> These both expressions are equivalent but which is faster or should be
>> used for any reason?
>>
>> u = unicode(s,'utf-8')
>>
>> u = s.decode('utf-8') # looks nicer
> 
> "decode" was added in Python 2.2 for the sake of symmetry to encode(). 

Yes, and I like the style. But...

> It's essentially the same as unicode() and I wouldn't be surprised if it 
> is exactly the same.

Did you try?

> I don't think any measurable speed increase will be noticeable between
> those two.

Well, seems not to be true. Try yourself. I did (my console has UTF-8 as charset):

Python 2.6 (r26:66714, Feb  3 2009, 20:52:03)
[GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer("'???????'.decode('utf-8')").timeit(1000000)
7.2721178531646729
>>> timeit.Timer("'???????'.decode('utf8')").timeit(1000000)
7.1302499771118164
>>> timeit.Timer("unicode('???????','utf8')").timeit(1000000)
8.3726329803466797
>>> timeit.Timer("unicode('???????','utf-8')").timeit(1000000)
1.8622009754180908
>>> timeit.Timer("unicode('???????','utf8')").timeit(1000000)
8.651669979095459
>>>

Comparing again the two best combinations:

>>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
17.23644495010376
>>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
72.087096929550171

That is significant! So the winner is:

unicode('???????','utf-8')

Ciao, Michael.


From philip at semanchuk.com  Thu Aug  6 12:31:27 2009
From: philip at semanchuk.com (Philip Semanchuk)
Date: Thu, 6 Aug 2009 12:31:27 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: 


On Aug 6, 2009, at 12:14 PM, Robert Dailey wrote:

> Hello,
>
> I'm loading a file via open() in Python 3.1 and I'm getting the
> following error when I try to print the contents of the file that I
> obtained through a call to read():
>
> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
>
> The file is defined as ASCII and the copyright symbol shows up just
> fine in Notepad++. However, Python will not print this symbol. How can
> I get this to work? And no, I won't replace it with "(c)". Thanks!

If the file is defined as ASCII and it contains 0xa9, then the file  
was written incorrectly or you were told the wrong encoding. There is  
no such character in ASCII which runs from 0x00 - 0x7f.

The copyright symbol == 0xa9 if the encoding is ISO-8859-1 or  
windows-1252, and since you're on Windows the latter is a likely bet.

http://en.wikipedia.org/wiki/Ascii
http://en.wikipedia.org/wiki/Iso-8859-1
http://en.wikipedia.org/wiki/Windows-1252


Bottom line is that your file is not in ASCII. Try specifying  
windows-1252 as the encoding. Without seeing your code I can't tell  
you where you need to specify the encoding, but the Python docs should  
help you out.


HTH
Philip



From R.Brodie at rl.ac.uk  Thu Aug  6 12:31:58 2009
From: R.Brodie at rl.ac.uk (Richard Brodie)
Date: Thu, 6 Aug 2009 17:31:58 +0100
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: 


"Robert Dailey"  wrote in message 
news:29ab0981-b95d-4435-91bd-a7a520419ada at b15g2000yqd.googlegroups.com...

> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
>
> The file is defined as ASCII.

That's the problem: ASCII is a seven bit code. What you have is
actually ISO-8859-1 (or possibly Windows-1252).

The different ISO-8859-n variants assign various characters to
to '\xa9'. Rather than being Western-European centric and assuming
ISO-8859-1 by default, Python throws an error when you stray
outside of strict ASCII. 




From python at mrabarnett.plus.com  Thu Aug  6 12:34:59 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 17:34:59 +0100
Subject: Help with regex
In-Reply-To: <64c96ebc-ce6f-4657-968e-4cbe77a8303d@t13g2000yqt.googlegroups.com>
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>	
	<64c96ebc-ce6f-4657-968e-4cbe77a8303d@t13g2000yqt.googlegroups.com>
Message-ID: <4A7B0633.2030106@mrabarnett.plus.com>

Robert Dailey wrote:
> On Aug 6, 11:02 am, MRAB  wrote:
>> Robert Dailey wrote:
>>> Hey guys,
>>> I'm creating a python script that is going to try to search a text
>>> file for any text that matches my regular expression. The thing it is
>>> looking for is:
>>> FILEVERSION #,#,#,#
>>> The # symbol represents any number that can be any length 1 or
>>> greater. Example:
>>> FILEVERSION 1,45,10082,3
>>> The regex should only match the exact above. So far here's what I have
>>> come up with:
>>> re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
>>> This works, but I was hoping for something a bit cleaner. I'm having
>>> to create a special case portion of the regex for the last of the 4
>>> numbers simply because it doesn't end with a comma like the first 3.
>>> Is there a better, more compact, way to write this regex?
>> The character class \d is equivalent to [0-9], and ',' isn't a special
>> character so it doesn't need to be escaped:
>>
>>      re.compile(r'FILEVERSION (?:\d+,){3}\d+')
> 
> But ',' is a special symbol It's used in this way:
> {0,3}
> 
> This will match the previous regex 0-3 times. Are you sure commas need
> not be escaped?
> 
> In any case, your suggestions help to clean it up a bit!

By 'special' I mean ones like '?', '*', '(', etc. ',' isn't special in
that sense.

In fact, the {...} quantifier is special only if it's syntactically
correct, otherwise it's just a literal, eg "a{," and a{} are just
literals.


From Samnsparky at gmail.com  Thu Aug  6 12:40:23 2009
From: Samnsparky at gmail.com (Sparky)
Date: Thu, 6 Aug 2009 09:40:23 -0700 (PDT)
Subject: Two Dimensional Array + ctypes
References: <79d2b3e3-b049-4d70-a56b-6e7f3ea2fa86@e27g2000yqm.googlegroups.com>
	
Message-ID: <6a218894-54d3-48d4-8a91-74e02ceefecb@g23g2000vbr.googlegroups.com>

On Aug 5, 11:19?pm, "Gabriel Genellina" 
wrote:
> En Wed, 05 Aug 2009 20:12:09 -0300, Sparky  escribi?:
>
>
>
>
>
> > Hello! I am trying to call this method:
>
> > long _stdcall AIBurst(long *idnum, [...]
> > ? ? ? ? ? ? ? ? ? ? long timeout,
> > ? ? ? ? ? ? ? ? ? ? float (*voltages)[4],
> > ? ? ? ? ? ? ? ? ? ? long *stateIOout,
> > ? ? ? ? ? ? ? ? ? ? long *overVoltage,
> > ? ? ? ? ? ? ? ? ? ? long transferMode);
>
> > I am having some problems with that ?float (*voltages)[4].
> > ? ? ? ? pointerArray = (ctypes.c_void_p * 4)
> > ? ? ? ? voltages = pointerArray(ctypes.cast(ctypes.pointer
> > ((ctypes.c_long * 4096)()), ctypes.c_void_p), ctypes.cast
> > (ctypes.pointer((ctypes.c_long * 4096)()), ctypes.c_void_p),
> > ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)()),
> > ctypes.c_void_p), ctypes.cast(ctypes.pointer((ctypes.c_long * 4096)
>
> Why c_long and not c_float?
> Anyway, this way looks much more clear to me (and doesn't require a cast):
>
> arr4096_type = ctypes.c_float * 4096
> voltages_type = arr4096_type * 4
> voltages = voltages_type()
>
> > The program runs but the values that come back in the array are not
> > right.
>
> Thay might be due to the long/float confusion.
>
> --
> Gabriel Genellina

Brilliant! Your code is much cleaner and the problem must have been
float vs long.

Thanks,
Sam


From arockinit at gmail.com  Thu Aug  6 12:41:06 2009
From: arockinit at gmail.com (Adam N)
Date: Thu, 6 Aug 2009 09:41:06 -0700 (PDT)
Subject: Using easy_install, reduncant?
References:  
	
Message-ID: <671c5d83-650b-4a20-9504-b430b1ee8318@d4g2000vbm.googlegroups.com>

On Jul 27, 7:53?pm, David Lyon  wrote:
> On Mon, 27 Jul 2009 09:42:06 -0700 (PDT), ray 
> wrote:
>
> > I am working on a Trac installation. ?I am new to Python. ?To install
> > packages, it is suggested to use setuptools. ?I have not understood
> > the directions.
>
> > I execute ez_install.py.
>
> > Then I attempt to execute easy_install.py setuptools-0.6c9-py2.6.egg.
> > There response that setuptools is already the active version in easy-
> > install.pth. ?Then:
> > Installing easy_install.exe script to C:\Python26\Scripts error: ?C:
> > \Python26\Scripts\Easy_install.exe: Permission denied.
>
> > I have compared the file entries before and after this attempt and
> > there are no new files. ?Is there any problems here? ?What did I miss?
>
> Try using python package manager :http://sourceforge.net/projects/pythonpkgmgr/
>
> You might find it a lot simpler. It will download and install setuptools
> for you if you are still having problems.
>
> David

Is there any solution within the easy_install world?  I'm trying to
run a script (pinax) that calls it specifically so I'd have to do all
sorts of hacking to use pythonpkgmgr.


From rcdailey at gmail.com  Thu Aug  6 12:41:07 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 09:41:07 -0700 (PDT)
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
Message-ID: 

On Aug 6, 11:31?am, "Richard Brodie"  wrote:
> "Robert Dailey"  wrote in message
>
> news:29ab0981-b95d-4435-91bd-a7a520419ada at b15g2000yqd.googlegroups.com...
>
> > UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> > position 1650: character maps to 
>
> > The file is defined as ASCII.
>
> That's the problem: ASCII is a seven bit code. What you have is
> actually ISO-8859-1 (or possibly Windows-1252).
>
> The different ISO-8859-n variants assign various characters to
> to '\xa9'. Rather than being Western-European centric and assuming
> ISO-8859-1 by default, Python throws an error when you stray
> outside of strict ASCII.

Thanks for the help guys. Sorry I left out code, I wasn't sure at the
time if it would be helpful. Below is my code:


#========================================================
def GetFileContentsAsString( file ):
   f = open( file, mode='r', encoding='cp1252' )
   contents = f.read()
   f.close()
   return contents

#========================================================
def ReplaceVersion( file, version, regExps ):
   #match = regExps[0].search( 'FILEVERSION 1,45332,2100,32,' )
   #print( match.group() )
   text = GetFileContentsAsString( file )
   print( text )


As you can see, I am trying to load the file with encoding 'cp1252'
which, according to the python 3.1 docs, translates to windows-1252. I
also tried 'latin_1', which translates to ISO-8859-1, but this did not
work either. Am I doing something else wrong?


From rcdailey at gmail.com  Thu Aug  6 12:43:42 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 6 Aug 2009 09:43:42 -0700 (PDT)
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
Message-ID: <35f72d0f-d659-423a-bea0-955092e02d15@d34g2000vbm.googlegroups.com>

On Aug 6, 11:12?am, Roman  wrote:
> On 06/08/09 08:35, Robert Dailey wrote:
>
>
>
>
>
> > Hey guys,
>
> > I'm creating a python script that is going to try to search a text
> > file for any text that matches my regular expression. The thing it is
> > looking for is:
>
> > FILEVERSION #,#,#,#
>
> > The # symbol represents any number that can be any length 1 or
> > greater. Example:
>
> > FILEVERSION 1,45,10082,3
>
> > The regex should only match the exact above. So far here's what I have
> > come up with:
>
> > re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
>
> > This works, but I was hoping for something a bit cleaner. I'm having
> > to create a special case portion of the regex for the last of the 4
> > numbers simply because it doesn't end with a comma like the first 3.
> > Is there a better, more compact, way to write this regex?
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> Since there cannot be more than one "end of string" you can try this
> expression:
> re.compile( r'FILEVERSION (?:[0-9]+(,|$)){4}' )

I had thought of this but I can't use that either. I have to assume
that someone was silly and put text at the end somewhere, perhaps a
comment. Like so:

FILEVERSION 1,2,3,4     // This is the file version

It would be nice if there was a type of counter for regex. So you
could say 'match only 1 [^,]' or something like that...


From marduk at letterboxes.org  Thu Aug  6 12:45:43 2009
From: marduk at letterboxes.org (Albert Hopkins)
Date: Thu, 06 Aug 2009 12:45:43 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: <1249577143.6168.14.camel@centar>

On Thu, 2009-08-06 at 09:14 -0700, Robert Dailey wrote:
> Hello,
> 
> I'm loading a file via open() in Python 3.1 and I'm getting the
> following error when I try to print the contents of the file that I
> obtained through a call to read():
> 
> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
> 
> The file is defined as ASCII and the copyright symbol shows up just
> fine in Notepad++. However, Python will not print this symbol. How can
> I get this to work? And no, I won't replace it with "(c)". Thanks!

It's not actually ASCII but Windows-1252 extended ASCII-like.  So with
that information you can do either of 2 things: You can open it in text
mode and specify the encoding:

>>> fp = open(filename, 'r', encoding='windows-1252')
>>> s = fp.read()
>>> print(s)

or you can open it in binary mode and decode it later:

>>> fp = open(filename, 'rb')
>>> b = fp.read()
>>> print(str(b, encoding='windows-1252'))

Or you may be able to set the default encoding to windows-1252 but I
don't know how to do that (in Windows).

p.s.

Next time it might be helpful to paste a code snippet else we have to
make assumptions about what you are actually doing.



From R.Brodie at rl.ac.uk  Thu Aug  6 13:02:01 2009
From: R.Brodie at rl.ac.uk (Richard Brodie)
Date: Thu, 6 Aug 2009 18:02:01 +0100
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
	
Message-ID: 


"Robert Dailey"  wrote in message 
news:f64f9830-c416-41b1-a510-c1e486271b4e at g19g2000vbi.googlegroups.com...

> As you can see, I am trying to load the file with encoding 'cp1252'
> which, according to the python 3.1 docs, translates to windows-1252. I
> also tried 'latin_1', which translates to ISO-8859-1, but this did not
> work either. Am I doing something else wrong?

Probably it's just the debugging print that has a problem, and if you
opened an output file with an encoding specified it would be fine.
When you get a UnicodeEncodingError, it's conversion _from_
Unicode that has failed. 




From philip at semanchuk.com  Thu Aug  6 13:02:14 2009
From: philip at semanchuk.com (Philip Semanchuk)
Date: Thu, 6 Aug 2009 13:02:14 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: 
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
	
Message-ID: <1886EEEC-CFDA-40BD-8BAC-64015C4D3672@semanchuk.com>


On Aug 6, 2009, at 12:41 PM, Robert Dailey wrote:

> On Aug 6, 11:31 am, "Richard Brodie"  wrote:
>> "Robert Dailey"  wrote in message
>>
>> news:29ab0981-b95d-4435-91bd-a7a520419ada at b15g2000yqd.googlegroups.com 
>> ...
>>
>>> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
>>> position 1650: character maps to 
>>
>>> The file is defined as ASCII.
>>
>> That's the problem: ASCII is a seven bit code. What you have is
>> actually ISO-8859-1 (or possibly Windows-1252).
>>
>> The different ISO-8859-n variants assign various characters to
>> to '\xa9'. Rather than being Western-European centric and assuming
>> ISO-8859-1 by default, Python throws an error when you stray
>> outside of strict ASCII.
>
> Thanks for the help guys. Sorry I left out code, I wasn't sure at the
> time if it would be helpful. Below is my code:
>
>
> #========================================================
> def GetFileContentsAsString( file ):
>   f = open( file, mode='r', encoding='cp1252' )
>   contents = f.read()
>   f.close()
>   return contents
>
> #========================================================
> def ReplaceVersion( file, version, regExps ):
>   #match = regExps[0].search( 'FILEVERSION 1,45332,2100,32,' )
>   #print( match.group() )
>   text = GetFileContentsAsString( file )
>   print( text )
>
>
> As you can see, I am trying to load the file with encoding 'cp1252'
> which, according to the python 3.1 docs, translates to windows-1252. I
> also tried 'latin_1', which translates to ISO-8859-1, but this did not
> work either. Am I doing something else wrong?


Are you getting the error when you read the file or when you  
print(text)?

As a side note, you should probably use something other than "file"  
for the parameter name in GetFileContentsAsString() since file() is a  
Python function.






From kosta.koeman at gmail.com  Thu Aug  6 13:27:56 2009
From: kosta.koeman at gmail.com (Kosta)
Date: Thu, 6 Aug 2009 10:27:56 -0700 (PDT)
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> 
	
	
	
Message-ID: <1a236d86-72de-4b43-bc7b-cf0c9bdab615@u38g2000pro.googlegroups.com>

On Aug 6, 3:57?am, David Cournapeau  wrote:
> On Thu, Aug 6, 2009 at 12:39 AM, Kosta wrote:
>
> > Setenv.bat sets up the path and other environment variables build.exe
> > needs to compile and link (and even binplace) its utilities. ?So
> > building itself is not the issue. ?The problem is that if I call
> > setenv.bat from Python and then build.exe, but the modifications to
> > the path (and other environment settings) are not seen by Python, so
> > the attempt to build without a specified path fails.
>
> It sounds like you do not propagate the environment when calling
> setenv.bat from python. There is an option to do so in
> subprocess.Popen init method, or you can define your own environment
> if you do not want to propagate the whole environment (but this is
> often difficult to avoid for build environment in my experience,
> expecially if you don't have access to the sources of the whole system
> to check which variables are necessary).
>
> David

David,

Thanks you.  I looked up the docs on Popen (http://docs.python.org/
library/subprocess.html) where I read:

On Windows: the Popen class uses CreateProcess() to execute the child
program, which operates on strings. If args is a sequence, it will be
converted to a string using the list2cmdline() method. Please note
that not all MS Windows applications interpret the command line the
same way: list2cmdline() is designed for applications using the same
rules as the MS C runtime.

My interpretation of the above (and your email) is that using Popen
allows one to pass the Python environment to a child processs (in my
case, setenv.bat).   I need the reverse, to propagate from the child
to the parent.

Thanks,
Kosta



From ladasky at my-deja.com  Thu Aug  6 13:36:40 2009
From: ladasky at my-deja.com (John Ladasky)
Date: Thu, 6 Aug 2009 10:36:40 -0700 (PDT)
Subject: Overlap in python
References: 
	<4a7892c2$0$2297$91cee783@newsreader02.highway.telekom.at> 
	
Message-ID: <900c8420-fc28-41d2-8720-518fc48763db@v15g2000prn.googlegroups.com>

On Aug 4, 3:21?pm, Jay Bird  wrote:
> Hi everyone,
>
> I wanted to thank you all for your help and *excellent* discussion. ?I
> was able to utilize and embed the script by Grigor Lingl in the 6th
> post of this discussion to get my program to work very quickly (I had
> to do about 20 comparisons per data bin, with over 40K bins in
> total). ?I am involved in genomic analysis research and this problem
> comes up a lot and I was surprised to not have been able to find a
> clear way to solve it. ?I will also look through all the tips in this
> thread, I have a feeling they may come in handy for future use!
>
> Thank you again,
> Jay

Hi Jay,

I know this is a bit off-topic, but how does this pertain to genomic
analysis?  Are you counting the lengths of microsatellite repeats or
something?


From steve at REMOVE-THIS-cybersource.com.au  Thu Aug  6 13:39:10 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 06 Aug 2009 17:39:10 GMT
Subject: Unexpected side-effects of assigning to sys.modules[__name__]
Message-ID: <028b05d5$0$5185$c3e8da3@news.astraweb.com>

Given this module:

#funny.py
import sys
print "Before:"
print "  __name__ =", __name__
print "  sys.modules[__name__] =", sys.modules[__name__]
sys.modules[__name__] = 123
print "After:"
print "  __name__ =", __name__
print "  sys =", sys


when I run it I get these results:


[steve at sylar python]$ python2.6 funny.py
Before:
  __name__ = __main__
  sys.modules[__name__] = 
After:
  __name__ = None
  sys = None



I'm completely perplexed by this behaviour. sys.modules() seems to be a 
regular dict, at least according to type(), and yet assigning to an item 
of it seems to have unexpected, and rather weird, side-effects.

What am I missing?



-- 
Steven


From nobody at nowhere.com  Thu Aug  6 13:50:23 2009
From: nobody at nowhere.com (Nobody)
Date: Thu, 06 Aug 2009 18:50:23 +0100
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
Message-ID: 

On Thu, 06 Aug 2009 17:02:44 +0100, MRAB wrote:

> The character class \d is equivalent to [0-9]

Not for Unicode, which is the default in 3.x.



From nobody at nowhere.com  Thu Aug  6 13:58:10 2009
From: nobody at nowhere.com (Nobody)
Date: Thu, 06 Aug 2009 18:58:10 +0100
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
Message-ID: 

On Thu, 06 Aug 2009 08:35:57 -0700, Robert Dailey wrote:

> I'm creating a python script that is going to try to search a text
> file for any text that matches my regular expression. The thing it is
> looking for is:
> 
> FILEVERSION #,#,#,#
> 
> The # symbol represents any number that can be any length 1 or
> greater. Example:
> 
> FILEVERSION 1,45,10082,3
> 
> The regex should only match the exact above. So far here's what I have
> come up with:
> 
> re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )

[0-9]+ allows any number of leading zeros, which is sometimes undesirable.
Using:

	(0|[1-9][0-9]*)

is more robust.



From jeanmichel at sequans.com  Thu Aug  6 14:01:42 2009
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Thu, 06 Aug 2009 20:01:42 +0200
Subject: Unexpected side-effects of assigning to sys.modules[__name__]
In-Reply-To: <028b05d5$0$5185$c3e8da3@news.astraweb.com>
References: <028b05d5$0$5185$c3e8da3@news.astraweb.com>
Message-ID: <4A7B1A86.8040609@sequans.com>

Steven D'Aprano wrote:
> Given this module:
>
> #funny.py
> import sys
> print "Before:"
> print "  __name__ =", __name__
> print "  sys.modules[__name__] =", sys.modules[__name__]
> sys.modules[__name__] = 123
> print "After:"
> print "  __name__ =", __name__
> print "  sys =", sys
>
>
> when I run it I get these results:
>
>
> [steve at sylar python]$ python2.6 funny.py
> Before:
>   __name__ = __main__
>   sys.modules[__name__] = 
> After:
>   __name__ = None
>   sys = None
>
>
>
> I'm completely perplexed by this behaviour. sys.modules() seems to be a 
> regular dict, at least according to type(), and yet assigning to an item 
> of it seems to have unexpected, and rather weird, side-effects.
>
> What am I missing?
>
>
>
>   
Maybe when you assign 123 to sys.modules[__name__], you've removed the 
last reference on  and it is 
garbaged. You are then loosing all your initial namespace.


try this one:
#funny.py
import sys
print "Before:"
print "  __name__ =", __name__
print "  sys.modules[__name__] =", sys.modules[__name__]
foo = sys.modules[__name__] # backup ref for the garbage collector
sys.modules[__name__] = 123
print "After:"
print "  __name__ =", __name__
print "  sys =", sys

Jean-Michel




From thorsten at thorstenkampe.de  Thu Aug  6 14:05:52 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Thu, 6 Aug 2009 20:05:52 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
Message-ID: 

* Michael Str?der (Thu, 06 Aug 2009 18:26:09 +0200)
> Thorsten Kampe wrote:
> > * Michael Str?der (Wed, 05 Aug 2009 16:43:09 +0200)
> > I don't think any measurable speed increase will be noticeable
> > between those two.
> 
> Well, seems not to be true. Try yourself. I did (my console has UTF-8 as charset):
> 
> Python 2.6 (r26:66714, Feb  3 2009, 20:52:03)
> [GCC 4.3.2 [gcc-4_3-branch revision 141291]] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import timeit
> >>> timeit.Timer("'???????'.decode('utf-8')").timeit(1000000)
> 7.2721178531646729
> >>> timeit.Timer("'???????'.decode('utf8')").timeit(1000000)
> 7.1302499771118164
> >>> timeit.Timer("unicode('???????','utf8')").timeit(1000000)
> 8.3726329803466797
> >>> timeit.Timer("unicode('???????','utf-8')").timeit(1000000)
> 1.8622009754180908
> >>> timeit.Timer("unicode('???????','utf8')").timeit(1000000)
> 8.651669979095459
> >>>
> 
> Comparing again the two best combinations:
> 
> >>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
> 17.23644495010376
> >>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
> 72.087096929550171
> 
> That is significant! So the winner is:
> 
> unicode('???????','utf-8')

Unless you are planning to write a loop that decodes "???????" one 
million times, these benchmarks are meaningless.

Thorsten


From nobody at nowhere.com  Thu Aug  6 14:08:26 2009
From: nobody at nowhere.com (Nobody)
Date: Thu, 06 Aug 2009 19:08:26 +0100
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: 

On Thu, 06 Aug 2009 09:14:08 -0700, Robert Dailey wrote:

> I'm loading a file via open() in Python 3.1 and I'm getting the
> following error when I try to print the contents of the file that I
> obtained through a call to read():
> 
> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
> 
> The file is defined as ASCII and the copyright symbol shows up just
> fine in Notepad++. However, Python will not print this symbol. How can
> I get this to work? And no, I won't replace it with "(c)". Thanks!

1. As others have said, your file *isn't* ASCII, but that isn't the
problem.

2. The problem is that the encoding which your standard output
stream uses doesn't have the copyright symbol. You need to use something
like:

sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'iso-8859-1')
sys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'iso-8859-1')

to fix the encoding of the stdout and stderr streams.



From python-url at phaseit.net  Thu Aug  6 14:21:58 2009
From: python-url at phaseit.net (Gabriel Genellina)
Date: Thu, 6 Aug 2009 18:21:58 +0000 (UTC)
Subject: Python-URL! - weekly Python news and links (Aug  6)
Message-ID: 

QOTW:  "The economy rises and falls, money comes and goes, but a great
conference has permanent good effects.  Well, a lot more permanent than
government fiscal policy, anyway." - Python Software Foundation Director
"bitter-in-victory-gracious-in-defeat-ly y'rs" timbot

    
    Is python free of "buffer overflow" errors?
        http://groups.google.com/group/comp.lang.python/t/a31faac6feced289/

    Lessons learned in implementation of a write-once dict:
        http://groups.google.com/group/comp.lang.python/t/bc8b91669257e246/

    Methods, attributes, iterators, lambdas, and how Ruby handles them:
        http://groups.google.com/group/comp.lang.python/t/6e4fc61946513405/

    Python 3 allows for custom types to be used as a class namespace 
    not just dicts):
        http://groups.google.com/group/comp.lang.python/t/50caadd10d2cca16/

    Could Python be used to write a device driver?
        http://groups.google.com/group/comp.lang.python/t/4efc28f9fe45b69e/

    The various meanings of the underscore character '_' in identifiers:
        http://groups.google.com/group/comp.lang.python/t/e32d577ad3d5a208/

    Generate a new object each time a name is imported:
        http://groups.google.com/group/comp.lang.python/t/b7112f74e2efa8bd/

    heapq.nlargest takes a "key" argument - why not the other functions in
    the same module?
        http://groups.google.com/group/comp.lang.python/t/a5095d3f4b54f79b/

    Immutable objects and how they could improve concurrency [old thread,
    still alive]:
        http://groups.google.com/group/comp.lang.python/t/cb0cf56c52321ccc/5c82cd09767ba85a?#5c82cd09767ba85a

    How to modify a variable in an outer (non global) scope:
        http://groups.google.com/group/comp.lang.python/t/e0e64250bd82825f/

    Best way to add "private" directories to sys.path:
        http://groups.google.com/group/comp.lang.python/t/cb43cf90d72f6833/

    Interval arithmetic:
        http://groups.google.com/group/comp.lang.python/t/71f050d8f5987244/

    Ensure that no more than three instances of the same program are
    running at the same time:
        http://groups.google.com/group/comp.lang.python/t/af7ae6429c2bda1e/

    Some people don't like the way Python documentation is managed/presented:
        http://groups.google.com/group/comp.lang.python/t/a52b22cd90b15ef8/
    
    
========================================================================
Everything Python-related you want is probably one or two clicks away in
these pages:

    Python.org's Python Language Website is the traditional
    center of Pythonia
        http://www.python.org
    Notice especially the master FAQ
        http://www.python.org/doc/FAQ.html

    PythonWare complements the digest you're reading with the
    marvelous daily python url
         http://www.pythonware.com/daily

    Just beginning with Python?  This page is a great place to start:
	http://wiki.python.org/moin/BeginnersGuide/Programmers

    The Python Papers aims to publish "the efforts of Python enthusiasts":
	http://pythonpapers.org/
    The Python Magazine is a technical monthly devoted to Python:
	http://pythonmagazine.com

    Readers have recommended the "Planet" sites:
	http://planetpython.org
	http://planet.python.org

    comp.lang.python.announce announces new Python software.  Be
    sure to scan this newsgroup weekly.
        http://groups.google.com/group/comp.lang.python.announce/topics

    Python411 indexes "podcasts ... to help people learn Python ..."
    Updates appear more-than-weekly:
        http://www.awaretek.com/python/index.html

    The Python Package Index catalogues packages.
        http://www.python.org/pypi/

    Much of Python's real work takes place on Special-Interest Group
    mailing lists
        http://www.python.org/sigs/

    Python Success Stories--from air-traffic control to on-line
    match-making--can inspire you or decision-makers to whom you're
    subject with a vision of what the language makes practical.
        http://www.pythonology.com/success

    The Python Software Foundation (PSF) has replaced the Python
    Consortium as an independent nexus of activity.  It has official
    responsibility for Python's development and maintenance.
        http://www.python.org/psf/
    Among the ways you can support PSF is with a donation.
        http://www.python.org/psf/donations/

    The Summary of Python Tracker Issues is an automatically generated
    report summarizing new bugs, closed ones, and patch submissions. 
        http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date

    Although unmaintained since 2002, the Cetus collection of Python
    hyperlinks retains a few gems.
        http://www.cetus-links.org/oo_python.html

    Python FAQTS
        http://python.faqts.com/

    The Cookbook is a collaborative effort to capture useful and
    interesting recipes.
	http://code.activestate.com/recipes/langs/python/

    Many Python conferences around the world are in preparation.
    Watch this space for links to them.

    Among several Python-oriented RSS/RDF feeds available, see:
        http://www.python.org/channews.rdf
    For more, see:
        http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all
    The old Python "To-Do List" now lives principally in a
    SourceForge reincarnation.
        http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse
	http://www.python.org/dev/peps/pep-0042/

    del.icio.us presents an intriguing approach to reference commentary.
    It already aggregates quite a bit of Python intelligence.
        http://del.icio.us/tag/python

    Enjoy the *Python Magazine*.
	http://pymag.phparch.com/

    *Py: the Journal of the Python Language*
        http://www.pyzine.com

    Dr.Dobb's Portal is another source of Python news and articles:
        http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python
    and Python articles regularly appear at IBM DeveloperWorks:
        http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8

Previous - (U)se the (R)esource, (L)uke! - messages are listed here:
  http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date
  http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d&
  http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes

There is *not* an RSS for "Python-URL!"--at least not yet.  Arguments
for and against are occasionally entertained.


Suggestions/corrections for next week's posting are always welcome.
E-mail to  should get through.

To receive a new issue of this posting in e-mail each Monday morning
(approximately), ask  to subscribe.  Mention
"Python-URL!".  Write to the same address to unsubscribe.


-- The Python-URL! Team--

Phaseit, Inc. (http://phaseit.net) is pleased to participate in and
sponsor the "Python-URL!" project.  Watch this space for upcoming
news about posting archives.


From rt8396 at gmail.com  Thu Aug  6 14:33:06 2009
From: rt8396 at gmail.com (r)
Date: Thu, 6 Aug 2009 11:33:06 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
Message-ID: <2eaf5b79-dc0a-4762-9f06-5de7e22381a2@r38g2000yqn.googlegroups.com>

On Aug 6, 11:20?am, Paul Rubin  wrote:
...(snip)
> There is something similar with the PostgreSQL docs. ?There is also
> Real World Haskell (http://book.realworld.haskell.org) which has a lot
> of interspersed user comments. ?It would be cool if Python's doc site
> did something like it too.

hear! hear!


From kee at kagi.com  Thu Aug  6 14:36:31 2009
From: kee at kagi.com (Kee Nethery)
Date: Thu, 6 Aug 2009 11:36:31 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
Message-ID: 

As someone trying to learn the language I want to say that the tone on  
this list towards people who are trying to learn Python  feels like it  
has become anti-newbies.

Learning a new language is difficult enough without seeing other  
newbies getting shamed for not knowing everything there is to know  
about Python before asking their questions.

For example, the guy who was looking for Python sample code for the  
Google Map API, calling him a troll was harsh. Suggesting he broach  
the question to Google was a reasonable answer. By the same token, his  
asking this list about the missing Python examples seems reasonable  
also. Seems to me that people on a Python list might have some  
background knowledge or even samples of the Google Python code that  
was no longer on the Google web site.

There seems to be a general consensus among the newbies that other  
languages have a user contributions resource tied to the main official  
docs to allow newbies to teach each other what they have learned. The  
desire is for python.org to have the same kind of support resource so  
that us newbies can self support each other.

Kee Nethery


From dioxide.software at gmail.com  Thu Aug  6 14:49:26 2009
From: dioxide.software at gmail.com (KK)
Date: Thu, 6 Aug 2009 11:49:26 -0700 (PDT)
Subject: pylucene installation problem on Ubuntu 9.04
Message-ID: 

hi all,
I've trying to install pylucene on my linux box from last 2 days but
not able to do so. first i tried to install it using apt-get like
this,
kk-laptop$ sudo apt-get install pylucene
and it did install python2.5, python2.5-minimal and pylucene. I must
mention one thing that I already had python2.6 on my box as the
default python i.e /usr/bin/python is linked to python2.6. Anyway s,
now i started the python interpreter using "python" command from cli
and then to make sure pylucene has been installed i tried to import
the module and to my surprise it said "module pylucene not found".
I thought I should enter the python2.6 env and do the same , so i
tried starting the python2.6 interpreter using "python2.6" as the
command and tried importing the same module and again it failed giving
the same irritating message.
 As a final try i pulled the source code of pylucene and as per the
comments given there in the README file, copied the mentioned files to
site-packages directory of python2.6 and then tried importing the
module and then got the same error message saying no module name
pylucene is present. I'm sick of this error !
Can someone point me what is the issue? If it is due to multiple
version of python running on box, can someone tell me which one to
remove or someone tell me how to get the whole thing running? I'll
very much thankful to you guys.

Thanks,
KK.


From martin.hellwig at dcuktec.org  Thu Aug  6 14:50:30 2009
From: martin.hellwig at dcuktec.org (Martin P. Hellwig)
Date: Thu, 06 Aug 2009 19:50:30 +0100
Subject: Parsing Binary Structures; Is there a better way / What is your
	way?
In-Reply-To: 
References: 
Message-ID: 

Thanks all for your insights and suggestions.
It seems to me that there are a couple of ways to this bit manipulation 
and a couple of foreign modules to assist you with that.

Would it be worth the while to do a PEP on this?
Personally I think that it would be nice to have a standard module in 
Python for this but perhaps there is a good reason that there isn't 
already one.

-- 
MPH
http://blog.dcuktec.com
'If consumed, best digested with added seasoning to own preference.'


From piet at cs.uu.nl  Thu Aug  6 14:58:13 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Thu, 06 Aug 2009 20:58:13 +0200
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com>
	
	
	
	<1a236d86-72de-4b43-bc7b-cf0c9bdab615@u38g2000pro.googlegroups.com>
Message-ID: 

>>>>> Kosta  (K) wrote:

>K> My interpretation of the above (and your email) is that using Popen
>K> allows one to pass the Python environment to a child processs (in my
>K> case, setenv.bat).   I need the reverse, to propagate from the child
>K> to the parent.

I don't think there is any modern OS that allows that. Unless you use
your own protocol of course, like letting the child write the
environment to its stdout and reading and interpreting it in the parent.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From wescpy at gmail.com  Thu Aug  6 15:14:21 2009
From: wescpy at gmail.com (Wesley Chun)
Date: Thu, 6 Aug 2009 12:14:21 -0700 (PDT)
Subject: Python docs disappointing
References: 
Message-ID: <1fcc79a2-692a-4744-a3e4-122394e3dad9@a39g2000pre.googlegroups.com>

On Jul 31, 1:10?pm, kj  wrote:
> I'm pretty new to Python, and I like a lot overall, but I find the
> documentation for Python rather poor, overall.
>
> I'm sure that Python experts don't have this problem:


kj,

welcome to Python! i'm sorry that you find the documentation lacking.
the one thing about the docs is that they're just pointers to get you
started and aren't very comprehensive. there are plenty of good online
tutorials out there as well as books. in fact, one of my main
motivations for writing "Core Python Programming" was because when i
learned Python 13 years ago, the online docs were enough to get me
started but did not have enough info to help me become an intermediate
Python programmer. there were only *2*(!) Python books out there, and
they were special-topic oriented, not ones to learn the language from.
it took almost a year and a half to write, but from what i hear from
readers and what has been said in reviews, it's pretty comprehensive,
and is a good book to learn Python from. i only wish that *i* had it
when i was learning!

Most "Python experts" do not have the entire language memorized, so
everyone has to look at the docs from time-to-time, not just
beginners. i'll either hit up http://docs.python.org/library/MODULE.html
or flip open my Nutshell or PER references, and finally, i'll google
if i have to (rare). the Python docs are the language manuals and not
necessarily full reference texts, so you have to just take them for
what they are.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


From martin at v.loewis.de  Thu Aug  6 15:14:41 2009
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Thu, 06 Aug 2009 21:14:41 +0200
Subject: Character encoding & the copyright symbol
In-Reply-To: 
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>		
	
Message-ID: <4A7B2BA1.2020002@v.loewis.de>

> As a side note, you should probably use something other than "file" for
> the parameter name in GetFileContentsAsString() since file() is a Python
> function.

Python 3.1.1a0 (py3k:74094, Jul 19 2009, 13:39:42)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
py> file
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'file' is not defined

Regards,
Martin



From piet at cs.uu.nl  Thu Aug  6 15:17:16 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Thu, 06 Aug 2009 21:17:16 +0200
Subject: Web page data and urllib2.urlopen
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
	
Message-ID: 

>>>>> Dave Angel  (DA) wrote:

>DA> Massi wrote:
>>> Hi everyone, I'm using the urllib2 library to get the html source code
>>> of web pages. In general it works great, but I'm having to do with a
>>> financial web site which does not provide the souce code I expect. As
>>> a matter of fact if you try:
>>> 
>>> import urllib2
>>> res = urllib2.urlopen("http://www.marketwatch.com/story/mondays-
>>> biggest-gaining-and-declining-stocks-2009-07-27")
>>> page = res.read()
>>> print page
>>> 
>>> you will see that the printed code is very different from the one
>>> given, for example, by mozilla. Since I have really little knowledge
>>> in html I can't even understand if this is a python or html problem.
>>> Can anyone give me some help?
>>> Thanks in advance.
>>> 
>>> 
>DA> I don't think this is a Python issue, but a "raw read" versus an
>DA> interactive interpretation of a page.  The browser does lots more than a
>DA> single roundtrip defined by urlopen/read.

>DA> I also would love to see some explanation of what happens here, or a
>DA> pointer to a reference that would help me understand it.

>DA> I took the output of the read(), and formatted it, roughly, as html.  I
>DA> expected to find a refresh, which is the simplest way that one page can
>DA> cause a very different one to be loaded.
>DA>      

>DA> If Mozilla had seen a page with this line in an appropriate place, it'd
>DA> immediately begin loading the other page, at "someotherurl"  But there's no
>DA> such line.

>DA> Next, I looked for javascript.  The Mozilla page contains lots of
>DA> javascript, but there's none in the raw page.  So I can't explain Mozilla's
>DA> differences that way.

>DA> I did notice the link to /m/Content/mobile2.css, but I don' t know any way
>DA> a CSS file could cause the content to change, just the display.

>DA> All I can guess is that it has something to do with "browser type" or
>DA> cookies.  And that would make lots of sense if this was a cgi page.  But
>DA> the URL doesn't look like that, as it doesn't end in pl, py, asp, or any of
>DA> another dozen special suffixes.

>DA> Any hints, anybody???

If you look into the HTML that Firefox gets, there is a lot of
javascript in it.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From steve at REMOVE-THIS-cybersource.com.au  Thu Aug  6 15:17:30 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 06 Aug 2009 19:17:30 GMT
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
Message-ID: <028b1ce0$0$5185$c3e8da3@news.astraweb.com>

On Thu, 06 Aug 2009 20:05:52 +0200, Thorsten Kampe wrote:

> > That is significant! So the winner is:
> > 
> > unicode('???????','utf-8')
> 
> Unless you are planning to write a loop that decodes "???????" one
> million times, these benchmarks are meaningless.

What if you're writing a loop which takes one million different lines of 
text and decodes them once each?


>>> setup = 'L = ["abc"*(n%100) for n in xrange(1000000)]'
>>> t1 = timeit.Timer('for line in L: line.decode("utf-8")', setup)
>>> t2 = timeit.Timer('for line in L: unicode(line, "utf-8")', setup)
>>> t1.timeit(number=1)
5.6751680374145508
>>> t2.timeit(number=1)
2.6822888851165771


Seems like a pretty meaningful difference to me.



-- 
Steven


From philip at semanchuk.com  Thu Aug  6 15:20:48 2009
From: philip at semanchuk.com (Philip Semanchuk)
Date: Thu, 6 Aug 2009 15:20:48 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: <4A7B2BA1.2020002@v.loewis.de>
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>		
	
	<4A7B2BA1.2020002@v.loewis.de>
Message-ID: <45B3614D-01A3-4CC2-BB78-5B488BC74841@semanchuk.com>


On Aug 6, 2009, at 3:14 PM, Martin v. L?wis wrote:

>> As a side note, you should probably use something other than "file"  
>> for
>> the parameter name in GetFileContentsAsString() since file() is a  
>> Python
>> function.
>
> Python 3.1.1a0 (py3k:74094, Jul 19 2009, 13:39:42)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> py> file
> Traceback (most recent call last):
>  File "", line 1, in 
> NameError: name 'file' is not defined


Whooops, didn't know about that change from 2.x to 3.x. Thanks.



From joncle at googlemail.com  Thu Aug  6 15:38:48 2009
From: joncle at googlemail.com (Jon Clements)
Date: Thu, 6 Aug 2009 12:38:48 -0700 (PDT)
Subject: pylucene installation problem on Ubuntu 9.04
References: 
Message-ID: 

On 6 Aug, 19:49, KK  wrote:
> hi all,
> I've trying to install pylucene on my linux box from last 2 days but
> not able to do so. first i tried to install it using apt-get like
> this,
> kk-laptop$ sudo apt-get install pylucene
> and it did install python2.5, python2.5-minimal and pylucene. I must
> mention one thing that I already had python2.6 on my box as the
> default python i.e /usr/bin/python is linked to python2.6. Anyway s,
> now i started the python interpreter using "python" command from cli
> and then to make sure pylucene has been installed i tried to import
> the module and to my surprise it said "module pylucene not found".
> I thought I should enter the python2.6 env and do the same , so i
> tried starting the python2.6 interpreter using "python2.6" as the
> command and tried importing the same module and again it failed giving
> the same irritating message.
> ?As a final try i pulled the source code of pylucene and as per the
> comments given there in the README file, copied the mentioned files to
> site-packages directory of python2.6 and then tried importing the
> module and then got the same error message saying no module name
> pylucene is present. I'm sick of this error !
> Can someone point me what is the issue? If it is due to multiple
> version of python running on box, can someone tell me which one to
> remove or someone tell me how to get the whole thing running? I'll
> very much thankful to you guys.
>
> Thanks,
> KK.

If you installed using apt, have you a pylucene directory under /usr/
local/lib/python2.6/dist-packages/?

Also, if you run python, and import sys; print sys.path
whats it show?

Jon.


From benjamin.kaplan at case.edu  Thu Aug  6 15:48:27 2009
From: benjamin.kaplan at case.edu (Benjamin Kaplan)
Date: Thu, 6 Aug 2009 15:48:27 -0400
Subject: pylucene installation problem on Ubuntu 9.04
In-Reply-To: 
References: 
Message-ID: 

On Thu, Aug 6, 2009 at 2:49 PM, KK wrote:
>
> kk-laptop$ sudo apt-get install pylucene
> and it did install python2.5, python2.5-minimal and pylucene. I must
> mention one thing that I already had python2.6 on my box as the
> default python i.e /usr/bin/python is linked to python2.6. Anyway s,
> now i started the python interpreter using "python" command from cli
> and then to make sure pylucene has been installed i tried to import
> the module and to my surprise it said "module pylucene not found".
> I thought I should enter the python2.6 env and do the same , so i
> tried starting the python2.6 interpreter using "python2.6" as the
> command and tried importing the same module and again it failed giving
> the same irritating message.

Pylucene seems to have installed under Python 2.5. Python extensions
are only installed for one version of python and extensions that use C
may only work under one particular version. If you want to use that
package, run python2.5 from the command line and try importing it.


From benjamin.kaplan at case.edu  Thu Aug  6 15:54:26 2009
From: benjamin.kaplan at case.edu (Benjamin Kaplan)
Date: Thu, 6 Aug 2009 15:54:26 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: 
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
	
Message-ID: 

On Thu, Aug 6, 2009 at 12:41 PM, Robert Dailey wrote:
> On Aug 6, 11:31?am, "Richard Brodie"  wrote:
>> "Robert Dailey"  wrote in message
>>
>> news:29ab0981-b95d-4435-91bd-a7a520419ada at b15g2000yqd.googlegroups.com...
>>
>> > UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
>> > position 1650: character maps to 
>>
>> > The file is defined as ASCII.
>>
>> That's the problem: ASCII is a seven bit code. What you have is
>> actually ISO-8859-1 (or possibly Windows-1252).
>>
>> The different ISO-8859-n variants assign various characters to
>> to '\xa9'. Rather than being Western-European centric and assuming
>> ISO-8859-1 by default, Python throws an error when you stray
>> outside of strict ASCII.
>
> Thanks for the help guys. Sorry I left out code, I wasn't sure at the
> time if it would be helpful. Below is my code:
>
>
> #========================================================
> def GetFileContentsAsString( file ):
> ? f = open( file, mode='r', encoding='cp1252' )
> ? contents = f.read()
> ? f.close()
> ? return contents
>
> #========================================================
> def ReplaceVersion( file, version, regExps ):
> ? #match = regExps[0].search( 'FILEVERSION 1,45332,2100,32,' )
> ? #print( match.group() )
> ? text = GetFileContentsAsString( file )
> ? print( text )
>
>
> As you can see, I am trying to load the file with encoding 'cp1252'
> which, according to the python 3.1 docs, translates to windows-1252. I
> also tried 'latin_1', which translates to ISO-8859-1, but this did not
> work either. Am I doing something else wrong?

This is why we need code and full tracebacks. There's a good chance
that your error is on the print(text) line. That's because sys.stdout
is probably a byte stream without an encoding defined. When you try to
print your unicode string, Python has to convert it to a stream of
bytes. Python refuses to guess on the console encoding and just falls
back to ascii, the conversion fails, and you get your error. Try using
print( text.encode( 'cp1252' ) ) instead.
> --
> http://mail.python.org/mailman/listinfo/python-list
>


From aahz at pythoncraft.com  Thu Aug  6 15:55:57 2009
From: aahz at pythoncraft.com (Aahz)
Date: 6 Aug 2009 12:55:57 -0700
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com>
	
Message-ID: 

In article ,
Hendrik van Rooyen   wrote:
>
>Bit slow - but hey, nobody's perfect.

YM "pobody's nerfect" HTH HAND
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz


From aahz at pythoncraft.com  Thu Aug  6 16:16:33 2009
From: aahz at pythoncraft.com (Aahz)
Date: 6 Aug 2009 13:16:33 -0700
Subject: How to write replace string for object which will be substituted?
	[regexp]
References: 
	
Message-ID: 

In article ,
ryniek90   wrote:
>
>I started learning regexp, and some things goes well, but most of them 
>still not.

1) 'Some people, when confronted with a problem, think "I know, I'll use
regular expressions."  Now they have two problems.'
--Jamie Zawinski, comp.emacs.xemacs, 8/1997

2) If you really want to learn regexes, get a copy of _Mastering Regular
Expressions_ by Friedl (either 2nd or 3rd edition)
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz


From kosta.koeman at gmail.com  Thu Aug  6 16:19:31 2009
From: kosta.koeman at gmail.com (Kosta)
Date: Thu, 6 Aug 2009 13:19:31 -0700 (PDT)
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com> 
	
	
	
	<1a236d86-72de-4b43-bc7b-cf0c9bdab615@u38g2000pro.googlegroups.com>
	
Message-ID: <4703dc01-a41a-4bcd-b225-9ef819105144@a39g2000pre.googlegroups.com>

On Aug 6, 11:58?am, Piet van Oostrum  wrote:
> >>>>> Kosta  (K) wrote:
> >K> My interpretation of the above (and your email) is that using Popen
> >K> allows one to pass the Python environment to a child processs (in my
> >K> case, setenv.bat). ? I need the reverse, to propagate from the child
> >K> to the parent.
>
> I don't think there is any modern OS that allows that. Unless you use
> your own protocol of course, like letting the child write the
> environment to its stdout and reading and interpreting it in the parent.
> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: p... at vanoostrum.org

Piet,

Yes you are correct.  Thinking more about parent/child processes and
what I am doing: opening a cmd window (its own process), starting up
Python (a child process), and then attempting to run setenv.bat (a
child process to Python), and yes I'm out of luck.


From davea at ieee.org  Thu Aug  6 16:26:11 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 16:26:11 -0400
Subject: Character encoding & the copyright symbol
In-Reply-To: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
Message-ID: <4A7B3C63.2050307@ieee.org>

Robert Dailey wrote:
> Hello,
>
> I'm loading a file via open() in Python 3.1 and I'm getting the
> following error when I try to print the contents of the file that I
> obtained through a call to read():
>
> UnicodeEncodeError: 'charmap' codec can't encode character '\xa9' in
> position 1650: character maps to 
>
> The file is defined as ASCII and the copyright symbol shows up just
> fine in Notepad++. However, Python will not print this symbol. How can
> I get this to work? And no, I won't replace it with "(c)". Thanks!
>
>   
I see others have alerted you to changes needed in stdout, which is 
ASCII coded by default.

But I wanted to comment on the (c) remark.  If you're in the US, that's 
the wrong abbreviation for copyright.  The only recognized abbreviation 
is (copr).

DaveA


From python at rcn.com  Thu Aug  6 16:47:13 2009
From: python at rcn.com (Raymond Hettinger)
Date: Thu, 6 Aug 2009 13:47:13 -0700 (PDT)
Subject: Subclassing Python's dict
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com> 
	
Message-ID: 

> Are you referring to Python 3.0? ?Python 2.6 does not have
> collections.UserDict

In Python2.6, it is in its own module.

    >>> from UserDict import UserDict


Raymond


From ryniek90 at gmail.com  Thu Aug  6 17:03:54 2009
From: ryniek90 at gmail.com (Ryniek90)
Date: Thu, 06 Aug 2009 23:03:54 +0200
Subject: How to write replace string for object which will be substituted?
	[regexp]
In-Reply-To: 
References: 
Message-ID: <4A7B453A.4050501@gmail.com>


> 2) If you really want to learn regexes, get a copy of _Mastering Regular
> Expressions_ by Friedl (either 2nd or 3rd edition)
>   

I made preview of that book, but some pages are disabled from preview. 
Has that book topics about Python regexp's?
If so, i must buy it.


From clp2 at rebertia.com  Thu Aug  6 17:08:15 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Thu, 6 Aug 2009 14:08:15 -0700
Subject: os.walk()
In-Reply-To: <75c8645a0908050849ua654ec1q6e9c8c83f412d7aa@mail.gmail.com>
References: <75c8645a0908041906s138c1499k59cd57d569a5c83e@mail.gmail.com>
	<50697b2c0908041948q31a30819g29e3d7f196e94074@mail.gmail.com>
	<75c8645a0908050849ua654ec1q6e9c8c83f412d7aa@mail.gmail.com>
Message-ID: <50697b2c0908061408p79316e22mc5a93f4b1ef17f04@mail.gmail.com>

> On Tue, Aug 4, 2009 at 10:48 PM, Chris Rebert  wrote:
>> On Tue, Aug 4, 2009 at 7:06 PM, Michael Savarese wrote:
>> > Greetings
>> > Python newbie here, and thanks to all who have helped me previously.
>> > Is there a way of grabbing file attributes while traversing with os.walk()?
>> > It would be advantageous to have date modified and file size along with the
>> > file name.
>> > If anyone can point me in the right direction, I'd appreciate it.
>>
>> Feed the path to os.stat(), and then use the `stat` module on the result:
>> http://docs.python.org/library/os.html#os.stat
>> http://docs.python.org/library/stat.html#module-stat

2009/8/5 Michael Savarese :
> Chris, thanks for the info.
> I'm a bit stuck here.
>
> am i close?

Yes, you just need to plug some more bricks together (as it were).

> import os, sys
> import os.path
>
> for root, dirs, files in os.walk('c:/Temp'):
>     for name in files:
>         statinfo=os.stat(name)
#see http://docs.python.org/library/os.path.html#os.path.join
        filepath = os.path.join(root, name)
        statinfo = os.stat(filepath)
>
>           print root,dirs,name,statinfo.st_size ; it gets stuck here, i guess it needs the full path.
>                                                                  is this where i use the join function to bring root, dirs, and filename together?
>                                                                  I kinda suck at that too, can you point me in the right direction?
>
> also:
>>>> statinfo.st_mtime
> 1247778166.6563497  can i have a hint on how to convert this?

That is the time represented in seconds since the (UNIX) epoch.
Use the functions in the `time` module to convert it to something more
palatable:
http://docs.python.org/library/time.html

Cheers,
Chris
-- 
http://blog.rebertia.com


From clp2 at rebertia.com  Thu Aug  6 17:09:28 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Thu, 6 Aug 2009 14:09:28 -0700
Subject: How to write replace string for object which will be substituted?
	[regexp]
In-Reply-To: <4A7B453A.4050501@gmail.com>
References: 
	<4A7B453A.4050501@gmail.com>
Message-ID: <50697b2c0908061409u2295f111l808f1eafc9142668@mail.gmail.com>

On Thu, Aug 6, 2009 at 2:03 PM, Ryniek90 wrote:
>> 2) If you really want to learn regexes, get a copy of _Mastering Regular
>> Expressions_ by Friedl (either 2nd or 3rd edition)
>>
>
> I made preview of that book, but some pages are disabled from preview. Has
> that book topics about Python regexp's?
> If so, i must buy it.

Yes, Python is among the language APIs covered.

Cheers,
Chris
-- 
http://blog.rebertia.com


From python at rcn.com  Thu Aug  6 17:18:14 2009
From: python at rcn.com (Raymond Hettinger)
Date: Thu, 6 Aug 2009 14:18:14 -0700 (PDT)
Subject: Subclassing Python's dict
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com> 
	
	
Message-ID: <3fadb25e-6457-4c2e-96a0-6d917ebba08b@2g2000prl.googlegroups.com>

> Xavier Ho wrote:
> > You should subclass collections.UserDict, and not the default dict class.
> > Refer to the collections module.
>
> Xavier, why do you think that is the correct approach? The docs say
> "The need for this class has been largely supplanted by the ability to
> subclass directly from dict (a feature that became available starting
> with Python version 2.2)."

UserDict can be a good choice because the pure python source makes
it clear exactly what needs to be overridden (you can see which
methods are implemented in terms of lower level methods and which
ones access the underlying dict directly.

Another choice is to use DictMixin or MutableMapping and fill-in just
the required abstract methods.  This approach is simple and
flexible.
It allows you to wrap a mapping interface around many different
classes
(a dbm for example).  The disadvantage is that it can be slow.

Subclassing a dict is typically done when the new class has to be
substitutable for real dicts (perhaps an API enforces a check
for instance(x, dict) or somesuch).  As the OP found out, the
dict methods all access the underlying structure directly, so
you will need to override *all* methods that need to have a new
behavior.  The remaining methods are inherited and run at C speed,
so performance may dictate this approach.

So, there you have three ways to do it.  In Py3.1, we used the latter
approach for collections.Counter() -- that gives a high speed on the
inherited methods.  For collections.OrderedDict, a hybrid approach
was used (subclassing from both dict and MutableMapping).  Most of
the work is done by MutableMapping and the dict is inherited so that
the OrderedDict objects would be substitutable anywhere regular
dicts are expected.  And IIRC, there are still some cases of UserDict
being used in the python source (situations where subclassing from
dict wouldn't work as well).


Raymond



From ethan at stoneleaf.us  Thu Aug  6 17:23:47 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Thu, 06 Aug 2009 14:23:47 -0700
Subject: Help with regex
In-Reply-To: 
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
Message-ID: <4A7B49E3.3000908@stoneleaf.us>

Nobody wrote:
> On Thu, 06 Aug 2009 08:35:57 -0700, Robert Dailey wrote:
> 
> 
>>I'm creating a python script that is going to try to search a text
>>file for any text that matches my regular expression. The thing it is
>>looking for is:
>>
>>FILEVERSION #,#,#,#
>>
>>The # symbol represents any number that can be any length 1 or
>>greater. Example:
>>
>>FILEVERSION 1,45,10082,3
>>
>>The regex should only match the exact above. So far here's what I have
>>come up with:
>>
>>re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
> 
> 
> [0-9]+ allows any number of leading zeros, which is sometimes undesirable.
> Using:
> 
> 	(0|[1-9][0-9]*)
> 
> is more robust.

You make a good point about possibly being undesirable, but I question 
the assertion that your solution is /more robust/.  If the OP 
wants/needs to match numbers even with leading zeroes your /more robust/ 
version fails.

~Ethan~



From nils at ccsg.de  Thu Aug  6 17:28:29 2009
From: nils at ccsg.de (Nils Ruettershoff)
Date: Thu, 06 Aug 2009 23:28:29 +0200
Subject: Seeding the rand() Generator
In-Reply-To: 
References: 			
	
Message-ID: <4A7B4AFD.9030808@ccsg.de>

Hi Fred,

I just saw your SQL Statement
> 	An example would be: SELECT first, second, third, fourth,
> fifth, sixth from sometable order by rand() limit 1
>
>   
and I feel  me  constrained to give you an advice. Don't use this SQL 
statement to pick up a random row, your user and maybe DBA would much 
appreciate it.
You are certainly asking why. Lets have a brief look what you are asking 
your mysql DB:

Fetch all rows from 'sometable', but only with attribute 'first, 
second,...' sort them all starting at 'random row' and afterward through 
anything away you did before, but the first line

If you have a table with 100000 rows you would fetch and sort up to 
100000 rows, pick up one row and discard up to 99999 rows. That sounds 
not very clever, right?

So please take a look at this site to get a better alternate way for 
that approach:

http://jan.kneschke.de/projects/mysql/order-by-rand/

if you want to know more please check this article too:

http://jan.kneschke.de/2007/2/22/analyzing-complex-queries

regards,

Nils



From bdezonia at wisc.edu  Thu Aug  6 17:57:00 2009
From: bdezonia at wisc.edu (BDZ)
Date: Thu, 6 Aug 2009 14:57:00 -0700 (PDT)
Subject: os.path.exists() and Samba shares
References: <42f0c423-657f-45fb-bec5-67dcdda9f4ad@a13g2000yqc.googlegroups.com>
	<3fdc924a-75ad-477a-be2e-6e42ce7bff0c@s15g2000yqs.googlegroups.com> 
	<337482f9-8ad9-4600-9cf4-39911f5368ac@h31g2000yqd.googlegroups.com> 
	
Message-ID: 

On Jul 31, 10:56?pm, "Gabriel Genellina" 
wrote:
> En Fri, 31 Jul 2009 13:33:45 -0300, BDZ  escribi?:
>
>
>
> > On Jul 30, 4:41?pm, Lo?c Domaign? 
> > wrote:
> >> > Hello. I have written a Python 3.1 script running on Windows that uses
> >> > os.path.exists() to connect to network shares. If the various network
> >> > shares require different user account and password combos than the
> >> > account the script is running under the routine returns false. I need
> >> > something like os.samba.path.exists(username,password,path). Does
> >> > anyone have a suggestion on how I can accomplish what I need to do in
> >> > Python?
>
> >> Could the Python Samba module PySamba be interesting for ?
> >> you?http://sourceforge.net/projects/pysamba/
>
> > Unfortunately, although it has the calls I'd want, pysamba appears to
> > be *nix only. I need something that will work under Windows. Is there
> > a set of Python Windows functions (official or contributed) that might
> > do what I need? (I'm new to Python)
>
> SAMBA is a Linux implementation of the SMB protocol, natively supported on
> Windows. You may use the pywin32 package (available on sourceforge.net) to
> call the WNetAddConnection2 Windows function:http://msdn.microsoft.com/en-us/library/aa385413(VS.85).aspx
>
> --
> Gabriel Genellina

The WNetAddConnection2 function under pywin32 seems to work. I am able
to make connections to various SMB network resources hosted by
Windows, Mac, and Linux boxes. It has the annoying side effect of
opening a connection.

There is a Win32 function called NetShareCheck. It sounds perfect. It
just checks that the share exists (no connection left open) and does
not require username or password. Unfortunately it fails for Mac and
Linux SMB resources. Just FYI.

I understand Samba and Windows SMB are not the same thing. What I was
hoping for when I investigated pySamba was to find a python module/
extension that supported a simple SMB interface and would run from any
host platform.


From python at mrabarnett.plus.com  Thu Aug  6 18:05:24 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Thu, 06 Aug 2009 23:05:24 +0100
Subject: XML flaw
Message-ID: <4A7B53A4.2000508@mrabarnett.plus.com>

Hi all,

I've just read this article, which mentions Python:

XML flaw threatens millions of apps with DoS attacks
http://infoworld.com/print/86340

Something to worry about?


From steve at REMOVE-THIS-cybersource.com.au  Thu Aug  6 18:09:14 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 06 Aug 2009 22:09:14 GMT
Subject: Unexpected side-effects of assigning to sys.modules[__name__]
References: <028b05d5$0$5185$c3e8da3@news.astraweb.com>
	
Message-ID: <0004d7c9$0$2895$c3e8da3@news.astraweb.com>

On Thu, 06 Aug 2009 20:01:42 +0200, Jean-Michel Pichavant wrote:


> > I'm completely perplexed by this behaviour. sys.modules() seems to be
> > a regular dict, at least according to type(), and yet assigning to an
> > item of it seems to have unexpected, and rather weird, side-effects.
> >
> > What am I missing?
> >
> >
> >
> >
> Maybe when you assign 123 to sys.modules[__name__], you've removed the
> last reference on  and it is
> garbaged. You are then loosing all your initial namespace.

By Jove, I think you've got it! How obvious in hindsight. Thank you.





-- 
Steven


From davea at ieee.org  Thu Aug  6 18:17:02 2009
From: davea at ieee.org (Dave Angel)
Date: Thu, 06 Aug 2009 18:17:02 -0400
Subject: Web page data and urllib2.urlopen
In-Reply-To: 
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>	
	
Message-ID: <4A7B565E.9000508@ieee.org>



Piet van Oostrum wrote:
> 
>> DA> If Mozilla had seen a page with this line in an appropriate place, it'd
>> DA> immediately begin loading the other page, at "someotherurl"  But there's no
>> DA> such line.
>>     
>
>   
>> DA> Next, I looked for javascript.  The Mozilla page contains lots of
>> DA> javascript, but there's none in the raw page.  So I can't explain Mozilla's
>> DA> differences that way.
>>     
>
>   
>> DA> I did notice the link to /m/Content/mobile2.css, but I don' t know any way
>> DA> a CSS file could cause the content to change, just the display.
>>     
>
>   
>> DA> All I can guess is that it has something to do with "browser type" or
>> DA> cookies.  And that would make lots of sense if this was a cgi page.  But
>> DA> the URL doesn't look like that, as it doesn't end in pl, py, asp, or any of
>> DA> another dozen special suffixes.
>>     
>
>   
>> DA> Any hints, anybody???
>>     
>
> If you look into the HTML that Firefox gets, there is a lot of
> javascript in it.
>   

But the raw page didn't have any javascript.  So what about that 
original raw page triggered additional stuff to be loaded?
Is it "user agent", as someone else brought out?  And is there somewhere 
I can read more about that aspect of things?  I've mostly built very 
static html pages, where the server yields the same page to everybody.  
And some form stuff, where the  user clicks on a 'submit" button to 
trigger a script that's not shown on the URL line.





From clp2 at rebertia.com  Thu Aug  6 18:23:16 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Thu, 6 Aug 2009 15:23:16 -0700
Subject: XML flaw
In-Reply-To: <4A7B53A4.2000508@mrabarnett.plus.com>
References: <4A7B53A4.2000508@mrabarnett.plus.com>
Message-ID: <50697b2c0908061523k5ce10b8eldccd4089e6f70e63@mail.gmail.com>

On Thu, Aug 6, 2009 at 3:05 PM, MRAB wrote:
> Hi all,
>
> I've just read this article, which mentions Python:
>
> XML flaw threatens millions of apps with DoS attacks
> http://infoworld.com/print/86340
>
> Something to worry about?

More detailed article:
http://blogs.zdnet.com/open-source/?p=4609

Quote:
"If you own any of the following libraries you need to be alert and
ready to patch:
    * Python libexpat"
AKA xml.parsers.expat AKA pyexpat

The good news: "[a patch] is in process for Python."

Cheers,
Chris
-- 
http://blog.rebertia.com


From breamoreboy at yahoo.co.uk  Thu Aug  6 18:23:16 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Thu, 06 Aug 2009 23:23:16 +0100
Subject: XML flaw
In-Reply-To: <4A7B53A4.2000508@mrabarnett.plus.com>
References: <4A7B53A4.2000508@mrabarnett.plus.com>
Message-ID: 

MRAB wrote:
> Hi all,
> 
> I've just read this article, which mentions Python:
> 
> XML flaw threatens millions of apps with DoS attacks
> http://infoworld.com/print/86340
> 
> Something to worry about?
No.  Discussing letting Tom, Dick and Harriet loose on the Python 
documentaion is far more important than trivial issues like Denial of 
Service atacks via XML.

Sorry, just couldn't resist.

-- 
Kindest regards.

Mark Lawrence.



From REMpeteOVE at petezilla.co.uk  Thu Aug  6 19:04:46 2009
From: REMpeteOVE at petezilla.co.uk (Peter Chant)
Date: Fri, 07 Aug 2009 00:04:46 +0100
Subject: Setuptools - help!
Message-ID: 

Chaps,

any ideas, I'm floundering - I don't quite get it.  I have the following
files, setup.py and main.py in a directory pphoto:

# more setup.py
from setuptools import setup, find_packages
setup(
    name = "Pphoto",
    version = "0.1",
    packages = find_packages(),

    # other arguments here...
    entry_points = {'console_scripts': ['foo = pphoto.main:HelloWorld',]}


)

bash-3.1# more main.py


def HelloWorld():
    print "Hello World!"

print "Odd world"


>From various websites that should produce a script foo that runs HelloWorld. 
It does produce a script that simply crashes.

bash-3.1# foo
Traceback (most recent call last):
  File "/usr/bin/foo", line 8, in 
    load_entry_point('Pphoto==0.1', 'console_scripts', 'foo')()
  File "build/bdist.linux-i686/egg/pkg_resources.py", line 277, in
load_entry_point
  File "build/bdist.linux-i686/egg/pkg_resources.py", line 2098, in
load_entry_point
  File "build/bdist.linux-i686/egg/pkg_resources.py", line 1831, in load
ImportError: No module named pphoto.main
bash-3.1#            


Note, doing this as root as it seems not to do anything usefull at all if I
run python setup develop as a user. 

Any ideas?  I must be missing something fundamental?

Pete


-- 
http://www.petezilla.co.uk


From robert.kern at gmail.com  Thu Aug  6 19:17:26 2009
From: robert.kern at gmail.com (Robert Kern)
Date: Thu, 06 Aug 2009 18:17:26 -0500
Subject: Setuptools - help!
In-Reply-To: 
References: 
Message-ID: 

On 2009-08-06 18:04, Peter Chant wrote:
> Chaps,
>
> any ideas, I'm floundering - I don't quite get it.  I have the following
> files, setup.py and main.py in a directory pphoto:
>
> # more setup.py
> from setuptools import setup, find_packages
> setup(
>      name = "Pphoto",
>      version = "0.1",
>      packages = find_packages(),
>
>      # other arguments here...
>      entry_points = {'console_scripts': ['foo = pphoto.main:HelloWorld',]}
>
>
> )
>
> bash-3.1# more main.py
>
>
> def HelloWorld():
>      print "Hello World!"
>
> print "Odd world"
>
>
>> From various websites that should produce a script foo that runs HelloWorld.
> It does produce a script that simply crashes.
>
> bash-3.1# foo
> Traceback (most recent call last):
>    File "/usr/bin/foo", line 8, in
>      load_entry_point('Pphoto==0.1', 'console_scripts', 'foo')()
>    File "build/bdist.linux-i686/egg/pkg_resources.py", line 277, in
> load_entry_point
>    File "build/bdist.linux-i686/egg/pkg_resources.py", line 2098, in
> load_entry_point
>    File "build/bdist.linux-i686/egg/pkg_resources.py", line 1831, in load
> ImportError: No module named pphoto.main
> bash-3.1#
>
>
> Note, doing this as root as it seems not to do anything usefull at all if I
> run python setup develop as a user.
>
> Any ideas?  I must be missing something fundamental?

You need to put main.py into the pphoto package.

$ mkdir pphoto/
$ mv main.py pphoto/
$ touch pphoto/__init__.py

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From dfnsonfsduifb at gmx.de  Thu Aug  6 20:55:27 2009
From: dfnsonfsduifb at gmx.de (Johannes Bauer)
Date: Fri, 07 Aug 2009 02:55:27 +0200
Subject: Python3: Using sorted(key=...)
Message-ID: <7e1cbuF2dfhtoU1@mid.dfncis.de>

Hello list,

I'm having trouble with a incredibly simple sort of a list containing
ints and tuples:

def myorder(x):
	if type(x) == int:
		return x
	else:
		return x[0]

odata = sorted([ (a, b) for (a, b) in data["description"].items() ],
key=myorder)

still says:

Traceback (most recent call last):
  File "./genproto.py", line 81, in 
    odata = sorted([ (a, b) for (a, b) in data["description"].items() ],
key=myorder)
TypeError: unorderable types: tuple() < int()

Why is that? Am I missing something very obvious?

Kind regards,
Johannes

-- 
"Du bist einfach nur l?cherlich! Mit solchen albernen und hohlen S?tzen
kannst du mir nicht impr?gnieren."
-- Hobbycholeriker Jens Fittig aka Wolfgang Gerber in de.sci.electronics
                             <4a6f44d0$0$12481$9b622d9e at news.freenet.de>


From jabronson at gmail.com  Thu Aug  6 21:10:39 2009
From: jabronson at gmail.com (Joshua Bronson)
Date: Thu, 6 Aug 2009 18:10:39 -0700 (PDT)
Subject: heapq "key" arguments
References: <97932d10-8601-401f-bb69-a98db9036929@p15g2000vbl.googlegroups.com>
	
Message-ID: 

On Aug 3, 1:36?pm, Raymond Hettinger  wrote:
> [Joshua Bronson]:
>
> > According tohttp://docs.python.org/library/heapq.html, Python 2.5
> > added an optional "key" argument to heapq.nsmallest and
> > heapq.nlargest. I could never understand why they didn't also add a
> > "key" argument to the other relevant functions (heapify, heappush,
> > etc).
>
> The problem is that heapq acts on regular lists, so it does not
> have exclusive access to the structure. ?So, there is no reliable
> way for it to maintain a separate list of keys. ?Since the keys
> can't be saved in the structure (without possibly breaking other
> code), the fine grained heapq functions (like heappop and heappush)
> would need to call key functions every time they are invoked.
> This is at odds with the implicit guarantee of the key function
> that it will be called no more than once per key.
>
> The overall problem is one of granularity. ?A key function should
> be applied once in an initial pass, not on every call to a push/pop
> function. ?The everyday solution that most people use is to operate
> on a list of (key, record) tuples and let tuple comparison do the
> work for you. ?Another solution is to build a Heap class that does
> have exclusive access to the structure, but the API sugar often
> isn't worth the slightly weaker performance.
>
> One other thought. ?Heaps are a lazy evaluation structure, so their
> fined-grained mutation functions only work well with just a single
> ordering function, so there is not need to have (and every reason
> to avoid) changing key functions in mid-stream. ?IOW, the key
> function needs to be constant across all accesses. ?Contrast this
> with other uses of key functions where it makes perfect sense
> to run minage=min(data, key=attrgetter('age')) and then running
> minsal=min(data, key=attrgetter('salary')). ?The flexibility to
> change key functions just doesn't make sense in the context of
> the fine-grained heap functions.
>
> Accordingly, this is why I put key functions in nlargest() and
> nsmallest() but not in heappush() and friends. ?The former can
> guarantee no more than one key function call per entry and they
> evaluate immediately instead of lazily.
>
> Raymond


I see, that makes sense. Thanks for the great explanation.

Josh


From gagsl-py2 at yahoo.com.ar  Thu Aug  6 21:24:22 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 22:24:22 -0300
Subject: Help making this script better
References: <2f8e34ec-01aa-4ec4-9636-a8ec1f87c68c@o6g2000yqj.googlegroups.com>
Message-ID: 

En Thu, 06 Aug 2009 11:50:07 -0300, jakecjacobson  
 escribi?:

> After much Google searching and trial & error, I was able to write a
> Python script that posts XML files to a REST API using HTTPS and
> passing PEM cert & key file.  It seems to be working but would like
> some pointers on how to handle errors.  I am using Python 2.4, I don't
> have the capability to upgrade even though I would like to.  I am very
> new to Python so help will be greatly appreciated and I hope others
> can use this script.

Just a few remarks, mostly on style rather than functionality:

> #!/usr/bin/python
> #################################################################
> # catalog_feeder.py
> #################################################################
> # This sciript will process a directory of XML files and push them to
> the Enterprise Catalog.
> #  You configure this script by using a configuration file that
> describes the required variables.
> #  The path to this file is either passed into the script as a command
> line argument or hard coded
> #  in the script.  The script will terminate with an error if it can't
> process the XML file.
> #################################################################

Note that Python has "docstrings" - the __doc__ attribute attached to  
every module, class and function. The very first string in the  
module/function/class becomes its docstring. The interactive help system  
-and other tools like pydoc- can inspect and show such info.
The above comment could serve perfectly as this module's docstring - just  
remove all the #'s and enclose the whole text in """triple quotes"""  
(required as it spawns many lines).
By example, in that case you could print the text in your usage() function  
like this:
print __doc__

> 	try:
> 		# Process the XML conf file ....
> 		xmldoc = minidom.parse(c)
> 		catalog_host = readConfFile(xmldoc, 'catalog_host')
> 		catalog_port = int(readConfFile(xmldoc, 'catalog_port'))
> 		catalog_path = readConfFile(xmldoc, 'catalog_path')
> 		collection_name = readConfFile(xmldoc, 'collection_name')
> 		cert_file = readConfFile(xmldoc, 'cert_file')
> 		key_file = readConfFile(xmldoc, 'key_file')
> 		log_file = readConfFile(xmldoc, 'log_file')
> 		input_dir = readConfFile(xmldoc, 'input_dir')
> 		archive_dir = readConfFile(xmldoc, 'archive_dir')
> 		hold_dir = readConfFile(xmldoc, 'hold_dir')
> 	except Exception, inst:
> 		# I had an error so report it and exit script
> 		print "Unexpected error opening %s: %s" % (c, inst)
> 		sys.exit(1)

Ok, an unexpected error: but *which* one? doing exactly *what*? You're  
hiding important information (the error type, the full traceback, the  
source line that raised the error...) that's very valuable when something  
goes wrong and you have to determine what happened.
In this case, you're adding a bit of information: the name of the file  
being processed. That's good. But at the same time, hiding all the other  
info, and that's not so good. What about this:

	except Exception:
		print >>sys.stderr, "Unexpected error opening %s" % c
		raise

The final raise will propagate the exception; by default, Python will  
print the exception type, the exception value, the full traceback  
including source lines, and exit the script with a status code of 1. The  
same effect that you intended, but more complete.

In other cases, where you don't have anything to add to the default  
exception handling, the best thing to do is: nothing. That is, don't catch  
an exception unless you have something good to do with it. (Exceptions  
aren't Pok?mon: you don't have to "catch 'em all!")

> 	# Log Starting
> 	logOut = verifyLogging(log_file)
> 	if logOut:
> 		log(logOut, "Processing Started ...")

I would move the decision into the log function (that is, just write  
log("something") and make the log function decide whether to write to file  
or not). For your next script, look at the logging module:  
http://docs.python.org/library/logging.html

> # Get an arry of files from the input_dir
> def getFiles2Post(d):
> 	return (os.listdir(d))

Note that return isn't a function but a statement. You don't need the  
outer (). Also, using a docstring instead of a comment:

def getFiles2Post(input_dir):
     "Return the list of files in input_dir to process"
     return os.listdir(input_dir)

> # Read out the conf file and set the needed global variable
> def readConfFile(xmldoc, tag):
> 	return (xmldoc.getElementsByTagName(tag)[0].firstChild.data)

Same as above. Which "needed global variable"?

> def cleanup(logOut):
>       [...]	sys.exit(0)

Exiting the script from everywhere makes it harder to reuse some of its  
functions later. Just return the desired status code to the caller, which  
in turn will return to main(), until it gets to the outermost level, which  
is the only place I'd use sys.exit()

-- 
Gabriel Genellina



From michael at stroeder.com  Thu Aug  6 21:25:03 2009
From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=)
Date: Fri, 07 Aug 2009 03:25:03 +0200
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
Message-ID: 

Thorsten Kampe wrote:
> * Michael Str?der (Thu, 06 Aug 2009 18:26:09 +0200)
>>>>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
>> 17.23644495010376
>>>>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
>> 72.087096929550171
>>
>> That is significant! So the winner is:
>>
>> unicode('???????','utf-8')
> 
> Unless you are planning to write a loop that decodes "???????" one 
> million times, these benchmarks are meaningless.

Well, I can tell you I would not have posted this here and checked it if it
would be meaningless for me. You don't have to read and answer this thread if
it's meaningless to you.

Ciao, Michael.


From sjmachin at lexicon.net  Thu Aug  6 21:27:51 2009
From: sjmachin at lexicon.net (John Machin)
Date: Thu, 6 Aug 2009 18:27:51 -0700 (PDT)
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
	
Message-ID: 

On Aug 7, 7:23?am, Ethan Furman  wrote:
> Nobody wrote:
> > On Thu, 06 Aug 2009 08:35:57 -0700, Robert Dailey wrote:
>
> >>I'm creating a python script that is going to try to search a text
> >>file for any text that matches my regular expression. The thing it is
> >>looking for is:
>
> >>FILEVERSION #,#,#,#
>
> >>The # symbol represents any number that can be any length 1 or
> >>greater. Example:
>
> >>FILEVERSION 1,45,10082,3
>
> >>The regex should only match the exact above. So far here's what I have
> >>come up with:
>
> >>re.compile( r'FILEVERSION (?:[0-9]+\,){3}[0-9]+' )
>
> > [0-9]+ allows any number of leading zeros, which is sometimes undesirable.
> > Using:
>
> > ? ?(0|[1-9][0-9]*)
>
> > is more robust.
>
> You make a good point about possibly being undesirable, but I question
> the assertion that your solution is /more robust/. ?If the OP
> wants/needs to match numbers even with leading zeroes your /more robust/
> version fails.

I'd go further: the OP would probably be better off matching anything
that looked vaguely like an attempt to produce what he wanted e.g.
r"FILEVERSION\s*[0-9,]{3,}" and then taking appropriate action based
on whether that matched a "strictly correct" regex.



From gagsl-py2 at yahoo.com.ar  Thu Aug  6 21:29:19 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 06 Aug 2009 22:29:19 -0300
Subject: Subclassing Python's dict
References: 
	<2d56febf0908050732i7792bf7ft32accf1bc1157421@mail.gmail.com>
	
	
	<2d56febf0908060126i323d499fla4b7a22c934c5e7@mail.gmail.com>
Message-ID: 

En Thu, 06 Aug 2009 05:26:22 -0300, Xavier Ho 
escribi?:
> On Thu, Aug 6, 2009 at 1:19 PM, alex23  wrote:
>> Xavier Ho wrote:
>> > You should subclass collections.UserDict, and not the default dict  
>> class.
>>
>> Xavier, why do you think that is the correct approach?
>
> I'll be honest first and say that I do not completely understand how  
> dict is
> implemented in the underlying C structure. But as Bruno had already
> mentioned, dict has a slightly different behaviour then we'd expect. For
> example, the __getitem__() function isn't actually used by the  
> interpreter
> (which, you know, *can* be a problem.)

Thinks have evolved...
Before Python 2.2, builtin types were not subclassable. You could not
inherit from dict. In order to write another mapping class, you had to
write the complete interface - or inherit from UserDict, that was a
concrete class implementing the mapping protocol.

Later, DictMixin was added (in 2.3) and it made easier to write other
mapping classes: one had to write the most basic methods (__getitem__ /
__setitem__ / __delitem__ / keys) and the DictMixin provided the remaining
functionality (e.g. values() is built from keys() plus __getitem__). Later
releases allowed an even more modular approach, and until 2.5 DictMixin
was the recommended approach.

Then came 3.0/2.6 and PEP3119 defining a rich hierarchy of abstract base
classes; a normal dictionary implements the MutableMapping ABC and this is
the preferred approach now (the MutableMapping implementation is very
similar to the original DictMixin, but builds on the other base classes
like Sized, Iterable...)

> I didn't realise they took UserDict out in later versions (2.6, for
> example), and put it back in Python 3.0. Does anyone know why?

UserDict still exists on both releases (collections.UserDict on 3.x), but
it's not the preferred approach to implement a new mapping class anymore.

-- 
Gabriel Genellina



From python at mrabarnett.plus.com  Thu Aug  6 21:33:27 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Fri, 07 Aug 2009 02:33:27 +0100
Subject: Python3: Using sorted(key=...)
In-Reply-To: <7e1cbuF2dfhtoU1@mid.dfncis.de>
References: <7e1cbuF2dfhtoU1@mid.dfncis.de>
Message-ID: <4A7B8467.8060101@mrabarnett.plus.com>

Johannes Bauer wrote:
> Hello list,
> 
> I'm having trouble with a incredibly simple sort of a list containing
> ints and tuples:
> 
> def myorder(x):
> 	if type(x) == int:
> 		return x
> 	else:
> 		return x[0]
> 
> odata = sorted([ (a, b) for (a, b) in data["description"].items() ],
> key=myorder)
> 
You're sorting a list of tuples (key/value pairs), so 'myorder' is
always given a tuple.

> still says:
> 
> Traceback (most recent call last):
>   File "./genproto.py", line 81, in 
>     odata = sorted([ (a, b) for (a, b) in data["description"].items() ],
> key=myorder)
> TypeError: unorderable types: tuple() < int()
> 
> Why is that? Am I missing something very obvious?
> 
Are some keys 'int' and others 'tuple'? In Python 3.x you can't compare
them except for equality:


Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> (1, ) < 1
False


Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> (1, ) < 1
Traceback (most recent call last):
   File "", line 1, in 
TypeError: unorderable types: tuple() < int()


From sjmachin at lexicon.net  Thu Aug  6 22:01:24 2009
From: sjmachin at lexicon.net (John Machin)
Date: Fri, 7 Aug 2009 02:01:24 +0000 (UTC)
Subject: unicode() vs. s.decode()
References: 
	<1249487636.7120.798.camel@arrakis>
	
	<1249568141.10840.37.camel@arrakis>
Message-ID: 

Jason Tackaberry  urandom.ca> writes:

> On Thu, 2009-08-06 at 01:31 +0000, John Machin wrote:

> > Suggested further avenues of investigation:
> > 
> > (1) Try the timing again with "cp1252" and "utf8" and "utf_8"
> > 
> > (2) grep "utf-8" /Objects/unicodeobject.c
> 
> Very pedagogical of you. :)  Indeed, it looks like bigger player in the
> performance difference is the fact that the code path for unicode(s,
> enc) short-circuits the codec registry for common encodings (which
> includes 'utf-8' specifically), whereas s.decode('utf-8') necessarily
> consults the codec registry.

So the next question (the answer to which may benefit all users
of .encode() and .decode()) is:

    Why does consulting the codec registry take so long,
    and can this be improved?





From dfnsonfsduifb at gmx.de  Thu Aug  6 22:15:52 2009
From: dfnsonfsduifb at gmx.de (Johannes Bauer)
Date: Fri, 07 Aug 2009 04:15:52 +0200
Subject: Python3: Using sorted(key=...)
In-Reply-To: 
References: <7e1cbuF2dfhtoU1@mid.dfncis.de>
	
Message-ID: <7e1h2oF2dlhvjU1@mid.dfncis.de>

MRAB schrieb:
> Johannes Bauer wrote:
>> Hello list,
>>
>> I'm having trouble with a incredibly simple sort of a list containing
>> ints and tuples:
>>
>> def myorder(x):
>>     if type(x) == int:
>>         return x
>>     else:
>>         return x[0]
>>
>> odata = sorted([ (a, b) for (a, b) in data["description"].items() ],
>> key=myorder)
>>
> You're sorting a list of tuples (key/value pairs), so 'myorder' is
> always given a tuple.

Oh good lord! You're right... I meant

def myorder(x):
     if type(x[0]) == int:
         return x[0]
     else:
         return x[0][0]

Thanks for your help,
Kind regards,
Johannes

-- 
"Du bist einfach nur l?cherlich! Mit solchen albernen und hohlen S?tzen
kannst du mir nicht impr?gnieren."
-- Hobbycholeriker Jens Fittig aka Wolfgang Gerber in de.sci.electronics
                             <4a6f44d0$0$12481$9b622d9e at news.freenet.de>


From michaelmossey at gmail.com  Thu Aug  6 23:02:10 2009
From: michaelmossey at gmail.com (Michael Mossey)
Date: Thu, 6 Aug 2009 20:02:10 -0700 (PDT)
Subject: help with threads
Message-ID: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>

Hello,

I have a simple application that needs one thread to manage networking
in addition to the main "thread" that does the main job. It's not
working right. I know hardly anything about threads, so I was hoping
someone could point me in the right direction to research this.

Basically, I have a program that does some computational work, and
also conveys its status to a monitor program elsewhere on the network
via sockets. I wanted to use a thread to manage the networking so that
the main program can run without regard to networking (i.e. they would
be asynchronous). So the network thread loops and calls select.

My problem is that in some cases, the network thread appears to stop,
while the main thread is doing a long computation.

I'm hoping someone can give me a general idea what to read about. For
example, under what conditions does a thread stop running? Can other
threads "take priority"? Are there certain operations that block other
threads (such as disk access)?

Thanks,
Mike


From jsrat10 at gmail.com  Thu Aug  6 23:13:01 2009
From: jsrat10 at gmail.com (jo)
Date: Thu, 6 Aug 2009 20:13:01 -0700 (PDT)
Subject: need help with an egg
Message-ID: <4d881767-ebe3-432c-bc9b-683b80626c97@y4g2000prf.googlegroups.com>

Hi,

I am very new to python....

I created an egg on a machine.  The Python version on that  is 2.5.
Copied that egg to a machine which has Python 2.6.

unzip -t Myproj-0.1-py2.5.egg
The above command shows all the files I need

When I run the easy_install, I get the foll. error.  Is it because of
the version?  Or am I doing something wrong?  Or the way I understand
the egg works is wrong.  Can anyone please help?
If it's the version issue, does that mean I cannot use that egg on my
machine with 2.6 version?

Installed /usr/local/lib/python2.6/dist-packages/Myproj-0.1-py2.5.egg
Processing dependencies for Myproj==0.1
Searching for Myproj==0.1
Reading http://pypi.python.org/simple/Myproj/
Couldn't find index page for 'Myproj' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
No local packages or download links found for Myproj==0.1
error: Could not find suitable distribution for Requirement.parse
('Myproj==0.1')

Thank you
Jo


From nate at binkert.org  Thu Aug  6 23:19:24 2009
From: nate at binkert.org (nathan binkert)
Date: Thu, 6 Aug 2009 20:19:24 -0700
Subject: Pure python implementation of string.format?
Message-ID: <217accd40908062019hb57a3d1n711316c21f9436bf@mail.gmail.com>

I was wondering if there was a pure python version of string.format
anywhere that could be used with python 2.4 and python 2.5.  Searching
has only turned up an early implementation done for pep 3101, but it
seems that it didn't get that far.

Thanks,

  Nate


From sgeorge at coe.neu.edu  Thu Aug  6 23:21:34 2009
From: sgeorge at coe.neu.edu (Sarmad George)
Date: Thu,  6 Aug 2009 23:21:34 -0400
Subject: SMTP
Message-ID: <1249615294.4a7b9dbe3a900@www.coe.neu.edu>

Good day all
I am new to the Python list
My question is here not Python as much as it is in servers

I have a code to send an email through my SMTP server - comcast Boston
fromaddrs = "******"
toaddrs = "sgeorge at coe.neu.edu"
msg = "Hello World"

server = smtplib.SMTP ('76.96.30.117', '25') #COMCAST BOSTON
server.set_debuglevel(1)
try:
    server.sendmail(fromaddrs, toaddrs, msg)
finally:
    server.quit()

Which basically sends a hello world message
Debugging gives me an indication of acceptance as seen below (and I as googled
it)
I tried the same from the University server, and I got the same results almost!
However, no emails in my Inbox when I log in - PLS can you explain the trouble?
Is it a firewall blocker?
Thanks alot


send: 'ehlo [127.0.1.1]\r\n'
reply: '250-OMTA03.emeryville.ca.mail.comcast.net hello [98.216.11.39], pleased
to meet you\r\n'
reply: '250-HELP\r\n'
reply: '250-AUTH LOGIN PLAIN CRAM-MD5\r\n'
reply: '250-SIZE 15728640\r\n'
reply: '250-ENHANCEDSTATUSCODES\r\n'
reply: '250-8BITMIME\r\n'
reply: '250-STARTTLS\r\n'
reply: '250 OK\r\n'
reply: retcode (250); Msg: OMTA03.emeryville.ca.mail.comcast.net hello
[98.216.11.39], pleased to meet you
HELP
AUTH LOGIN PLAIN CRAM-MD5
SIZE 15728640
ENHANCEDSTATUSCODES
8BITMIME
STARTTLS
OK
send: 'mail FROM: size=11\r\n'
reply: '250 2.1.0  sender ok\r\n'
reply: retcode (250); Msg: 2.1.0  sender ok
send: 'rcpt TO:\r\n'
reply: '250 2.1.5  recipient ok\r\n'
reply: retcode (250); Msg: 2.1.5  recipient ok
send: 'data\r\n'
reply: '354 enter mail, end with "." on a line by itself\r\n'
reply: retcode (354); Msg: enter mail, end with "." on a line by itself
data: (354, 'enter mail, end with "." on a line by itself')
send: 'Hello World\r\n.\r\n'
reply: '250 2.0.0 REQK1c0070qYooa8PEQKQA mail accepted for delivery\r\n'
reply: retcode (250); Msg: 2.0.0 REQK1c0070qYooa8PEQKQA mail accepted for
delivery
data: (250, '2.0.0 REQK1c0070qYooa8PEQKQA mail accepted for delivery')
send: 'quit\r\n'
reply: '221 2.0.0 OMTA03.emeryville.ca.mail.comcast.net comcast closing
connection\r\n'
reply: retcode (221); Msg: 2.0.0 OMTA03.emeryville.ca.mail.comcast.net comcast
closing connection

Sarmad Edward George
Electrical Computer Eng
Northeastern Uni
Boston MA - USA



From gagsl-py2 at yahoo.com.ar  Thu Aug  6 23:21:38 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 00:21:38 -0300
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
	<200908050956.33995.hendrik@microcorp.co.za>
	<5b8d13220908050508n32f05bep4c275cec14914588@mail.gmail.com>
	
	
	
	<1a236d86-72de-4b43-bc7b-cf0c9bdab615@u38g2000pro.googlegroups.com>
Message-ID: 

En Thu, 06 Aug 2009 14:27:56 -0300, Kosta   
escribi?:
> On Aug 6, 3:57?am, David Cournapeau  wrote:
>> On Thu, Aug 6, 2009 at 12:39 AM, Kosta wrote:
>>
>> > Setenv.bat sets up the path and other environment variables build.exe
>> > needs to compile and link (and even binplace) its utilities. ?So
>> > building itself is not the issue. ?The problem is that if I call
>> > setenv.bat from Python and then build.exe, but the modifications to
>> > the path (and other environment settings) are not seen by Python, so
>> > the attempt to build without a specified path fails.
>>
>> It sounds like you do not propagate the environment when calling
>> setenv.bat from python. There is an option to do so in
>> subprocess.Popen init method, or you can define your own environment
>
> My interpretation of the above (and your email) is that using Popen
> allows one to pass the Python environment to a child processs (in my
> case, setenv.bat).   I need the reverse, to propagate from the child
> to the parent.

In addition to just calling setenv, dump the modified environment. Parse  
the output into a dictionary that you can use as the env argument to later  
subprocess calls:

py> import subprocess
py> cmdline = '(call setenv >nul 2>&1 & set)'
py> p = subprocess.Popen(cmdline, stdout=subprocess.PIPE, shell=True)
py> env = dict(line.rstrip().split("=",1) for line in p.stdout)
py> p.wait()
0
py> env
{'TMP': 'D:\\USERDATA\\Gabriel\\CONFIG~1\\Temp', 'COMPUTERNAME': 'LEPTON',  
'HOMEDRIVE': 'D:', ...
py> env['FOO']='Salta Violeta!'
py> subprocess.call("echo %FOO%", shell=True, env=env)
Salta Violeta!
0

-- 
Gabriel Genellina



From dioxide.software at gmail.com  Thu Aug  6 23:22:57 2009
From: dioxide.software at gmail.com (KK)
Date: Thu, 6 Aug 2009 20:22:57 -0700 (PDT)
Subject: pylucene installation problem on Ubuntu 9.04
References: 
	
Message-ID: 

On Aug 7, 12:38?am, Jon Clements  wrote:
> On 6 Aug, 19:49, KK  wrote:
>
>
>
> > hi all,
> > I've trying to install pylucene on my linux box from last 2 days but
> > not able to do so. first i tried to install it using apt-get like
> > this,
> > kk-laptop$ sudo apt-get install pylucene
> > and it did install python2.5, python2.5-minimal and pylucene. I must
> > mention one thing that I already had python2.6 on my box as the
> > default python i.e /usr/bin/python is linked to python2.6. Anyway s,
> > now i started the python interpreter using "python" command from cli
> > and then to make sure pylucene has been installed i tried to import
> > the module and to my surprise it said "module pylucene not found".
> > I thought I should enter the python2.6 env and do the same , so i
> > tried starting the python2.6 interpreter using "python2.6" as the
> > command and tried importing the same module and again it failed giving
> > the same irritating message.
> > ?As a final try i pulled the source code of pylucene and as per the
> > comments given there in the README file, copied the mentioned files to
> > site-packages directory of python2.6 and then tried importing the
> > module and then got the same error message saying no module name
> > pylucene is present. I'm sick of this error !
> > Can someone point me what is the issue? If it is due to multiple
> > version of python running on box, can someone tell me which one to
> > remove or someone tell me how to get the whole thing running? I'll
> > very much thankful to you guys.
>
> > Thanks,
> > KK.
>
> If you installed using apt, have you a pylucene directory under /usr/
> local/lib/python2.6/dist-packages/?
>
> Also, if you run python, and import sys; print sys.path
> whats it show?
>
> Jon.

Yes I've a dirctory called dist-packages under python2.6 but that
doesn't contain anything on pylucene [it has lupyne, which i installed
day before yesterday and importing lupyne doesn't give any error msg,
but again it is dependent on pylucene]
# for python the output is :
------------------------------
kk-laptop$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print sys.path
['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/
python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/
lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/
dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/var/
lib/python-support/python2.6', '/usr/lib/python2.6/dist-packages/
gtk-2.0', '/var/lib/python-support/python2.6/gtk-2.0', '/usr/local/lib/
python2.6/dist-packages']
>>>
-------------------------------

for python2.5 this is the output:
kk-laptop$ python2.5
Python 2.5.4 (r254:67916, Apr  4 2009, 17:55:16)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print sys.path
['', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/
python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/
python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/
lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/
gst-0.10', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/
site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0']
>>>
--------------------------------

and for python2.6 the output is this:
kk-laptop$ python2.6
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print sys.path
['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/
python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/
lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/
dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/var/
lib/python-support/python2.6', '/usr/lib/python2.6/dist-packages/
gtk-2.0', '/var/lib/python-support/python2.6/gtk-2.0', '/usr/local/lib/
python2.6/dist-packages']


>From all of the above what I can see is we don't have any directory
named dist-packages under python2.5 but we've one under 2.6, then
where did all those pylucene files got installed to after i installed
it using apt-get? Any ideas?

Thanks
KK


From michele.simionato at gmail.com  Thu Aug  6 23:29:35 2009
From: michele.simionato at gmail.com (Michele Simionato)
Date: Thu, 6 Aug 2009 20:29:35 -0700 (PDT)
Subject: Custom namespaces
References: <0284d760$0$20667$c3e8da3@news.astraweb.com>
	
Message-ID: <271ecd46-b684-49a0-b7ce-a0c0a4be519f@z28g2000vbl.googlegroups.com>

On Aug 2, 6:46?am, Chris Rebert  wrote:
> > Is there any way to install a custom type as a namespace?
>
> For classes/objects, yes, using metaclasses.
> See the __prepare__() method in PEP 3115:http://www.python.org/dev/peps/pep-3115/

Here is an example of usage:

http://www.artima.com/weblogs/viewpost.jsp?thread=236234
http://www.artima.com/weblogs/viewpost.jsp?thread=236260
(yes, it only works for Python 3+)


From loic.domaigne at googlemail.com  Fri Aug  7 00:04:40 2009
From: loic.domaigne at googlemail.com (=?ISO-8859-1?Q?Lo=EFc_Domaign=E9?=)
Date: Thu, 6 Aug 2009 21:04:40 -0700 (PDT)
Subject: help with threads
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
Message-ID: <949b87d5-8cff-444a-b6ba-23d49610d130@p36g2000vbn.googlegroups.com>

Hallo Michael,

> I have a simple application that needs one thread to manage networking
> in addition to the main "thread" that does the main job. It's not
> working right. I know hardly anything about threads, so I was hoping
> someone could point me in the right direction to research this.
>
> Basically, I have a program that does some computational work, and
> also conveys its status to a monitor program elsewhere on the network
> via sockets. I wanted to use a thread to manage the networking so that
> the main program can run without regard to networking (i.e. they would
> be asynchronous). So the network thread loops and calls select.
>
> My problem is that in some cases, the network thread appears to stop,
> while the main thread is doing a long computation.
>
> I'm hoping someone can give me a general idea what to read about. For
> example, under what conditions does a thread stop running? Can other
> threads "take priority"? Are there certain operations that block other
> threads (such as disk access)?

May I suggest:
http://www.dabeaz.com/python/GIL.pdf

HTH,
Lo?c
--
My Blog: http://www.domaigne.com/blog

"There is only one problem with common sense; it?s not very common."
-- Milt Bryce


From gagsl-py2 at yahoo.com.ar  Fri Aug  7 00:21:23 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 01:21:23 -0300
Subject: SMTP
References: <1249615294.4a7b9dbe3a900@www.coe.neu.edu>
Message-ID: 

En Fri, 07 Aug 2009 00:21:34 -0300, Sarmad George   
escribi?:

> Good day all
> I am new to the Python list

Welcome!

> My question is here not Python as much as it is in servers
>
> I have a code to send an email through my SMTP server - comcast Boston
> fromaddrs = "******"
> toaddrs = "sgeorge at coe.neu.edu"
> msg = "Hello World"
>
> server = smtplib.SMTP ('76.96.30.117', '25') #COMCAST BOSTON
> server.set_debuglevel(1)
> try:
>     server.sendmail(fromaddrs, toaddrs, msg)
> finally:
>     server.quit()
>
> Which basically sends a hello world message
> Debugging gives me an indication of acceptance as seen below (and I as  
> googled
> it)
> I tried the same from the University server, and I got the same results  
> almost!
> However, no emails in my Inbox when I log in - PLS can you explain the  
> trouble?
> Is it a firewall blocker?

It's probably a spam filter in action: you claim to be someone at Yahoo  
but you're not using a Yahoo server to send mail. Try using the Yahoo smtp  
mail servers to deliver your message, or use your ISP address as the  
sender if you use their SMTP. In any case, you should log in first with  
the adequate username+password.

-- 
Gabriel Genellina



From http  Fri Aug  7 00:42:04 2009
From: http (Paul Rubin)
Date: 06 Aug 2009 21:42:04 -0700
Subject: Python3: Using sorted(key=...)
References: <7e1cbuF2dfhtoU1@mid.dfncis.de>
	
	<7e1h2oF2dlhvjU1@mid.dfncis.de>
Message-ID: <7xvdl0xmjn.fsf@ruckus.brouhaha.com>

Johannes Bauer  writes:
> def myorder(x):
>      if type(x[0]) == int:
>          return x[0]
>      else:
>          return x[0][0]

I used to write code like that pretty regularly, but over time I found
that it's better to stay consistent and use the same container format
(in this case, tuples) for everything, rather than having special
cases for the singleton and non-singleton case.


From michele.simionato at gmail.com  Fri Aug  7 00:54:25 2009
From: michele.simionato at gmail.com (Michele Simionato)
Date: Thu, 6 Aug 2009 21:54:25 -0700 (PDT)
Subject: Generate a new object each time a name is imported
References: <02853264$0$20667$c3e8da3@news.astraweb.com>
	 
	<7x63d631md.fsf@ruckus.brouhaha.com>
Message-ID: 

On Aug 2, 1:18?pm, Paul Rubin  wrote:
> Peter Otten <__pete... at web.de> writes:
> > >>> import sys
> > >>> sys.modules["yadda"] = A()
>
> OMG.... wow. ?I bow to you. ?But I'm not sure whether that's bowing in
> awe or in terror.

I had to play this kind of tricks on our production code, not so long
ago. Not that I am pride of it, but it was the lesser evil to cope
with a wrong design. The scenario: a large legacy code base
based on the idea of using a Python module to keep configuration
parameters. The idea is fine as long as the parameters are
immutable, but in our case the parameters could be changed.
In theory the parameters should have been set only once,
however in practice this was not guaranteed: every piece
of code could change the parameters at some moment, and things
could get "interesting" to debug.
Throwing away the configuration system was not an option, because
it would have involved changing hundreds of modules, so I set out
for a compromise: the parameters are still mutable, but they
can be changed only once. This was implemented by replacing
the module with a configuration object using custom
descriptors. Here is the code:

$ echo config.py
import sys

class WriteOnce(object):
    "WriteOnce descriptor"
    def __init__(self, default):
        self.default = self.value = default
        self.already_set = False
    def __get__(self, obj, objcls):
        return self.value
    def __set__(self, obj, value):
        if value != self.value and self.already_set:
            raise TypeError('You cannot set twice a write-once
attribute!')
        self.value = value
        self.already_set = True

class Config(object):
    "A singleton to be used as a module"
    parameter = WriteOnce(0)

sys.modules['config'] = Config()

The usage is

>>> import config
>>> config.parameter = 42
>>> config.parameter = 43
Traceback (most recent call last):
   ...
TypeError: You cannot set twice a write-once attribute!

Just to say that there are use cases where replacing modules with
objects may have sense.
Still, a better design would just have passed immutable configuration
objects around
(changing the configuration would mean to create a new object).
Unfortunately there are still a lot a people without a functional
mindset :-(


From gagsl-py2 at yahoo.com.ar  Fri Aug  7 01:37:13 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 02:37:13 -0300
Subject: Python configuration question when python scripts are executed
	using Appweb as web server.
References: 
	
	
	
	
Message-ID: 

En Thu, 06 Aug 2009 12:49:30 -0300, IronyOfLife   
escribi?:
> On Aug 5, 4:18?pm, "Gabriel Genellina"  wrote:
>> En Tue, 04 Aug 2009 10:15:24 -0300, IronyOfLife 
>> escribi?:
>> > On Aug 3, 8:42?pm, "Gabriel Genellina"  wrote:
>> >> En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife  
>>  ?
>> >> escribi?:
>>
>> >> > I have installed python 2.6.2 in windows xp professional machine. I
>> >> > have set the following environment variables -- PYTHONPATH. It  
>> points
>> >> > to following windows folders: python root folder, the lib folder  
>> and
>> >> > lib-tk folder.
>>
>> >> Why? Did you read it somewhere? Usually there is no need to set the ?
>> >> PYTHONPATH variable at all; remove it.
>>
>> > Setting PYTHONPATH environment variables is mentioned in Python docs.
>>
>> Could you provide a link please? Setting PYTHONPATH should not be
>
> Here are couple of links that discusses setting PYTHONPATH environment
> variable.
> http://docs.python.org/using/windows.html

Ouch, that document should be reworked and updated!

> http://www.daimi.au.dk/~chili/PBI/pythonpath.html

That's mostly obsolete for current versions. Since PEP370 [0] was  
implemented, a per-user private directory is already in sys.path now, so  
there is no need to play with PYTHONPATH.

> I understand your concerns regarding setting of PYTHONPATH while
> multiple versions of Python are installed on the same machine. My fix
> however does not use PYTHONPATH. The GNUTLS wrapper module for PYTHON
> loads the GNUTLS dll's and it was not able to find them. Using FileMon
> (win tool) I found out the paths that are scanned and I copied the
> dlls to one of such paths. I still do not like this fix. This is a
> temporary solution.

Note that this cannot be fixed from inside Python. When you import a  
module, the interpreter scans the directories in ITS search path  
(sys.path) looking for a matching module. Once the module is found:
- if it is a Python file, it's executed
- if it is an extension module (a .pyd file, in fact a .dll renamed) it's  
loaded using LoadLibraryEx (a Windows function), and finally its  
initialization routine is executed.

For LoadLibrary to successfully load the module, all its external  
references must be resolved. That is, Windows must locate and load all  
other DLLs that this module depends on, using its own search strategy [1],  
taking into account the PATH environment variable and many other places.

It is at this stage that you get the error: when the gnutls wrapper  
attempts to load the gnutls DLL. That search is done by Windows, not by  
Python, and PYTHONPATH has nothing to do with it.

Why different results in IIS and appweb? Note that there exist several  
search strategies, they depend on the application home directory, the  
location of the .exe, whether SetDllDirectory was called or not, whether  
the application has a manifest or not, a .local file or not... Hard to  
tell with so many variables.

> Can you explain maybe with some sample how to set .pth files? Maybe
> this will resolve my issue.

Yes, but I don't think this will actually help with your issue.

pth files are described here [2]. Suppose you want to add c:\foo\bar to  
sys.path, then write a file whatever.pth containing this single line:

c:\foo\bar

and place it on c:\your_python_installation\lib\site-packages
When the interpreter starts, it will find the .pth file, read it, and add  
any directory it finds (that actually exists) to sys.path

Note that another Python installation will use a diferent site-packages  
directory and won't find this particular .pth file, so different Python  
versions don't interfere.

---

[0] http://python.org/dev/peps/pep-0370/
[1] http://msdn.microsoft.com/en-us/library/ms682586(VS.85).aspx
[2] http://docs.python.org/library/site.html

-- 
Gabriel Genellina



From wuwei23 at gmail.com  Fri Aug  7 01:41:17 2009
From: wuwei23 at gmail.com (alex23)
Date: Thu, 6 Aug 2009 22:41:17 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
Message-ID: <3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>

Paul Rubin  wrote:
> The PHP docs as I remember are sort of regular (non-publically
> editable) doc pages, each of which has a public discussion thread
> where people can post questions and answers about the topic of that
> doc page. ?I thought it worked really well. ?The main thing is that
> the good stuff from the comment section gets folded into the actual
> doc now and then.

I'd still like to see this kept out of the official docs as much as
possible, mostly for reasons of brevity & clarity. I think the
official docs should be considered definitive and not require a
hermeneutic evaluation against user comments to ensure they're still
correct...

How about a secondary site that embeds the docs and provides
commenting functionality around it? That's certainly a finitely scoped
project that those with issues about the docs could establish and
contribute to, with the possibility of it gaining official support
later once it gains traction.





From nobody at nowhere.com  Fri Aug  7 01:42:29 2009
From: nobody at nowhere.com (Nobody)
Date: Fri, 07 Aug 2009 06:42:29 +0100
Subject: Help with regex
References: <39e84c94-0054-4a60-b890-65e00cafabfe@w41g2000yqb.googlegroups.com>
	
	
Message-ID: 

On Thu, 06 Aug 2009 14:23:47 -0700, Ethan Furman wrote:

>> [0-9]+ allows any number of leading zeros, which is sometimes undesirable.
>> Using:
>> 
>> 	(0|[1-9][0-9]*)
>> 
>> is more robust.
> 
> You make a good point about possibly being undesirable, but I question 
> the assertion that your solution is /more robust/.  If the OP 
> wants/needs to match numbers even with leading zeroes your /more robust/ 
> version fails.

Well, the OP did say:

> The regex should only match the exact above.

I suppose that it depends upon the definition of "exact" ;)

More seriously: failing to produce an error when one is called for is also
a bug.

Personally, unless I knew for certain that the rest of the program would
handle leading zeros correctly (e.g. *not* interpreting the number as
octal), I would try to reject it in the parser. It's usually much easier
to determine the cause of an error raised by the parser than if you allow
bogus data to propagate deep into the program.



From mark.v.weber at gmail.com  Fri Aug  7 01:42:42 2009
From: mark.v.weber at gmail.com (mark.v.weber at gmail.com)
Date: Thu, 6 Aug 2009 22:42:42 -0700 (PDT)
Subject: how to kill subprocess when Python process is killed?
Message-ID: <0feaa2a3-5b73-43e4-9b24-11f157ff6d18@l34g2000vba.googlegroups.com>

I am writing a Python program that launches a subprocess (using
Popen).
I am reading stdout of the subprocess, doing some filtering, and
writing to
stdout of the main process.

When I kill the main process (cntl-C) the subprocess keeps running.
How do I kill the subprocess too? The subprocess is likey to run a
long time.

Context:
I'm launching only one subprocess at a time, I'm filtering its stdout.
The user might decide to interrupt to try something else; the user
wants the process and all subprocesses to go away in response
to a cntl-C

I'm new to python; solution must be for Python 2.5 (windows) to help
me.

Any help and/or pointers appreciated.




From gagsl-py2 at yahoo.com.ar  Fri Aug  7 01:49:59 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 02:49:59 -0300
Subject: one method of COM object needs a variant type variable
References: <913F77222E913C49A057FDD7BBDEAAA30192B846@br-dc.uhul.wan>
Message-ID: 

En Thu, 06 Aug 2009 09:37:55 -0300, MICH?LEK Jan Mgr.  
 escribi?:

> How i can use this type in win32.com? One method of com object (geomedia  
> storage service) needs this variable for storage geometry of geometry  
> object (this variable will be writen into blob in DB). Is possible make  
> this variable in py??

Any compatible object may be used on the Python side, the pywin32 library  
manages the conversion automatically.

See  
http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/PythonCOM.html

-- 
Gabriel Genellina



From wuwei23 at gmail.com  Fri Aug  7 01:57:34 2009
From: wuwei23 at gmail.com (alex23)
Date: Thu, 6 Aug 2009 22:57:34 -0700 (PDT)
Subject: how to kill subprocess when Python process is killed?
References: <0feaa2a3-5b73-43e4-9b24-11f157ff6d18@l34g2000vba.googlegroups.com>
Message-ID: <3733148e-c03d-42ef-88f7-855c516e6564@d9g2000prh.googlegroups.com>

On Aug 7, 3:42?pm, "mark.v.we... at gmail.com" 
wrote:
> When I kill the main process (cntl-C) the subprocess keeps running.
> How do I kill the subprocess too? The subprocess is likey to run a
> long time.

You can register functions to run when the Python process ends by
using the atexit[1] module.

The following has been tested & works under Python 2.6 on Windows XP:

    import atexit

    def cleanup():
        print 'stop the subprocess in here'

    atexit.register(cleanup)

    while True:
        pass


[1]: http://docs.python.org/library/atexit.html


From stefan_ml at behnel.de  Fri Aug  7 02:07:37 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 07 Aug 2009 08:07:37 +0200
Subject: SDMX format
In-Reply-To: 
References: 
Message-ID: <4a7bc4a8$0$31337$9b4e6d93@newsspool4.arcor-online.net>

xamdam wrote:
> Does anyone know of python libs for writing SDMX XML format?
> http://www.SDMX.org/resources/SDMXML/schemas/v2_0/common

Looks like the page behind that link is broken, but in general, working
with XML formats in Python isn't hard at all when you use ElementTree or
lxml. The latter also has support for XML-Schema validation, and you might
be interested in lxml.objectify for handling data centric XML formats
(assuming that's the case here).

Stefan


From stefan_ml at behnel.de  Fri Aug  7 02:23:32 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 07 Aug 2009 08:23:32 +0200
Subject: How to fetch an XML file using an HTTPS query
In-Reply-To: 
References: 	<49b3a7400908040638h46d4e4dcxe5cd4120e9c2c7a1@mail.gmail.com>
	
Message-ID: <4a7bc863$0$31334$9b4e6d93@newsspool4.arcor-online.net>

Tycho Andersen wrote:
> Blah, forgot to include the list. When is python-list going to get Reply-To?

Hopefully never.

Stefan


From stefan_ml at behnel.de  Fri Aug  7 02:40:35 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 07 Aug 2009 08:40:35 +0200
Subject: How to force SAX parser to ignore encoding problems
In-Reply-To: <89c214a4-e846-4101-b0b3-8078eec15114@w41g2000yqb.googlegroups.com>
References: <89c214a4-e846-4101-b0b3-8078eec15114@w41g2000yqb.googlegroups.com>
Message-ID: <4a7bcc64$0$31330$9b4e6d93@newsspool4.arcor-online.net>

?ukasz wrote:
> I have a problem with my XML parser (created with libraries from
> xml.sax package). When parser finds a invalid character (in CDATA
> section) for example ?, throws an exception SAXParseException.
> 
> Is there any way to just ignore this kind of problem. Maybe there is a
> way to set up parser in less strict mode?
> 
> I know that I can catch this exception and determine if this is this
> kind of problem and then ignore this, but I am asking about any global
> setting.

The parser from libxml2 that lxml provides has a recovery option, i.e. it
can keep parsing regardless of errors and will drop the broken content.

However, it is *always* better to fix the input, if you get any hand on it.
Broken XML is *not* XML at all. If you can't fix the source, you can never
be sure that the data you received is in any way complete or even usable.

Stefan


From michaelmossey at gmail.com  Fri Aug  7 02:40:53 2009
From: michaelmossey at gmail.com (Michael Mossey)
Date: Thu, 6 Aug 2009 23:40:53 -0700 (PDT)
Subject: help with threads
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
	<949b87d5-8cff-444a-b6ba-23d49610d130@p36g2000vbn.googlegroups.com>
Message-ID: 

Ah yes, that explains it. Some of these long computations are done in
pure C, so I'm sure the GIL is not being released.
Thanks.


From stefan_ml at behnel.de  Fri Aug  7 02:46:38 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 07 Aug 2009 08:46:38 +0200
Subject: Generators through the C API
In-Reply-To: 
References: 
	
Message-ID: <4a7bcdce$0$31330$9b4e6d93@newsspool4.arcor-online.net>

Duncan Booth schrieb:
> Lucas P Melo  wrote:
> 
>> Hello, I'm a total noob about the C API. Is there any way to create a 
>> generator function using the C API? I couldn't find anything like the 
>> 'yield' keyword in it.
>>
>> Thanks in advance.
> 
> You define a new type with tp_flags including Py_TPFLAGS_HAVE_ITER. 
> Anything that would be a local variable in your generator needs to become 
> an attribute in the type.
> 
> The tp_init initialization function should contain all the code up to the 
> first yield, tp_iter should return self and tp_iternext should execute code 
> up to the next yield.

This is pretty easy to do in Cython (or Pyrex), BTW. Just write a class
with an __iter__ and __next__ method, and Cython will generate the C-API
code as expected.

http://docs.cython.org/docs/special_methods.html#iterators

Note that Cython doesn't currently support the "yield" statement, but
that's certainly on the ToDo list.

http://trac.cython.org/cython_trac/ticket/83

Stefan


From kushal.kumaran+python at gmail.com  Fri Aug  7 02:52:31 2009
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Fri, 7 Aug 2009 12:22:31 +0530
Subject: Web page data and urllib2.urlopen
In-Reply-To: <4A7B565E.9000508@ieee.org>
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
	
	 <4A7B565E.9000508@ieee.org>
Message-ID: <1e364c4e0908062352w33ae8914q7436743d3256e1d5@mail.gmail.com>

On Fri, Aug 7, 2009 at 3:47 AM, Dave Angel wrote:
>
>
> Piet van Oostrum wrote:
>>
>> 
>>>
>>> DA> All I can guess is that it has something to do with "browser type" or
>>> DA> cookies. ?And that would make lots of sense if this was a cgi page.
>>> ?But
>>> DA> the URL doesn't look like that, as it doesn't end in pl, py, asp, or
>>> any of
>>> DA> another dozen special suffixes.
>>>

Note that the URL does not have to have any special suffix for it to
be dynamically generated.  See any page at wikipedia, for example.
Mediawiki, the software running the site, is a php application.

>>
>>
>>>
>>> DA> Any hints, anybody???
>>>
>>
>> If you look into the HTML that Firefox gets, there is a lot of
>> javascript in it.
>>
>
> But the raw page didn't have any javascript. ?So what about that original
> raw page triggered additional stuff to be loaded?

FWIW, I'm getting a ton of javascript in the page downloaded using
your code fragment.

> Is it "user agent", as someone else brought out? ?And is there somewhere I
> can read more about that aspect of things? ?I've mostly built very static
> html pages, where the server yields the same page to everybody. ?And some
> form stuff, where the ?user clicks on a 'submit" button to trigger a script
> that's not shown on the URL line.
>

-- 
kushal


From stefan_ml at behnel.de  Fri Aug  7 02:53:38 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 07 Aug 2009 08:53:38 +0200
Subject: Special chars with HTMLParser
In-Reply-To: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com>
References: <5c6941f8-c53e-4518-8ce5-83be64689307@a26g2000yqn.googlegroups.com>
Message-ID: <4a7bcf71$0$31330$9b4e6d93@newsspool4.arcor-online.net>

Fafounet wrote:
> I am parsing a web page with special chars such as é (which
> stands for ?).
> I know I can have the unicode character ? from unicode
> ("\xe9","iso-8859-1")
> but with those extra characters I don' t know.
> 
> I tried to implement handle_charref within HTMLParser without success.
> Furthermore, if I have the data abécd, handle_data will get "ab",
> handle_charref will get xe9 and then handle_data doesn't have the end
> of the string ("cd").

Any reason you can't use a tree based HTML parser like the one in
lxml.html? That would eliminate this kind of problem altogether, as you'd
always get a well-decoded unicode string from the tree content.

Stefan


From breamoreboy at yahoo.co.uk  Fri Aug  7 03:04:51 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Fri, 07 Aug 2009 08:04:51 +0100
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 		<2qcrk6-doj.ln1@nb2.stroeder.com>	
	
Message-ID: 

Michael Str?der wrote:
> Thorsten Kampe wrote:
>> * Michael Str?der (Thu, 06 Aug 2009 18:26:09 +0200)
>>>>>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
>>> 17.23644495010376
>>>>>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
>>> 72.087096929550171
>>>
>>> That is significant! So the winner is:
>>>
>>> unicode('???????','utf-8')
>> Unless you are planning to write a loop that decodes "???????" one 
>> million times, these benchmarks are meaningless.
> 
> Well, I can tell you I would not have posted this here and checked it if it
> would be meaningless for me. You don't have to read and answer this thread if
> it's meaningless to you.
> 
> Ciao, Michael.
I believe that the comment "these benchmarks are meaningless" refers to 
the length of the strings being used in the tests.  Surely something 
involving thousands or millions of characters is more meaningful? Or to 
go the other way, you are unlikely to write
for c in '???????':
     u = unicode(c, 'utf-8')
     ...
Yes?

-- 
Kindest regards.

Mark Lawrence.



From python at lists.wgwh.ch  Fri Aug  7 03:13:04 2009
From: python at lists.wgwh.ch (Oli Schacher)
Date: Fri, 07 Aug 2009 09:13:04 +0200
Subject: SMTP
In-Reply-To: <1249615294.4a7b9dbe3a900@www.coe.neu.edu>
References: <1249615294.4a7b9dbe3a900@www.coe.neu.edu>
Message-ID: <4A7BD400.1020404@lists.wgwh.ch>

Sarmad George schrieb:

> msg = "Hello World"

Your sending your message without any headers (no subject etc). So
probably your message lands in the recipients spam folder.

Try:
msg = """To: recipient at example.com
Subject: hello world

Hello there"""


The blank line between the headers and the body is important!

Also make sure to use a sender address that is allowed to send through
your smtp relay. yahoo.com sender is probably a bad idea. Check your
Yahoo Inbox, you might even have a bounce message there telling you that
the final mail server didn't accept your message.



From hendrik at microcorp.co.za  Fri Aug  7 03:15:34 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Fri, 7 Aug 2009 09:15:34 +0200
Subject: Parsing Binary Structures;
	Is there a better way / What is your way?
In-Reply-To: 
References: 
	
Message-ID: <200908070915.34564.hendrik@microcorp.co.za>

On Thursday 06 August 2009 20:50:30 Martin P. Hellwig wrote:
> Thanks all for your insights and suggestions.
> It seems to me that there are a couple of ways to this bit manipulation
> and a couple of foreign modules to assist you with that.
>
> Would it be worth the while to do a PEP on this?
> Personally I think that it would be nice to have a standard module in
> Python for this but perhaps there is a good reason that there isn't
> already one.

I agree that it would be nice - I think it would be nice if something
like this is added to the struct module to give a "this is the obvious
way that python handles foreign data" module

- Hendrik




From Michalek.Jan at uhul.cz  Fri Aug  7 03:21:03 2009
From: Michalek.Jan at uhul.cz (=?iso-8859-2?Q?MICH=C1LEK_Jan_Mgr=2E?=)
Date: Fri, 7 Aug 2009 09:21:03 +0200
Subject: one method of COM object needs a variant type variable
Message-ID: <913F77222E913C49A057FDD7BBDEAAA30192B8A0@br-dc.uhul.wan>

Thanks Gabriel,
I seen this before, but I don't know, what's mean 'compatible object'. I need create object who will like as an variant type.
Je.
it looks lieke this:
...
obj=win32com.client.Dispatch('Geomedia.PointGeometry') #geometry object
gss=win32com.client.Dispatch('Geomedia.GeometryStorageService')#geometry strorage object
....
gss.GeometryToStorage(obj, out) #out must be a variant type variable
.....
oRS.Fields("Geometry").Value = out # writing blob into recordset via ADO
 
 
En Thu, 06 Aug 2009 09:37:55 -0300, MICH?LEK Jan Mgr.  

 > escribi?:



> How i can use this type in win32.com? One method of com object (geomedia  

> storage service) needs this variable for storage geometry of geometry  

> object (this variable will be writen into blob in DB). Is possible make  

> this variable in py??



Any compatible object may be used on the Python side, the pywin32 library  

manages the conversion automatically.



See  

http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/PythonCOM.html



-- 

Gabriel Genellina
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at REMOVE-THIS-cybersource.com.au  Fri Aug  7 03:25:44 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 07 Aug 2009 07:25:44 GMT
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	
	
Message-ID: <00055a38$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 08:04:51 +0100, Mark Lawrence wrote:

> I believe that the comment "these benchmarks are meaningless" refers to
> the length of the strings being used in the tests.  Surely something
> involving thousands or millions of characters is more meaningful? Or to
> go the other way, you are unlikely to write for c in '???????':
>      u = unicode(c, 'utf-8')
>      ...
> Yes?

There are all sorts of potential use-cases. A day or two ago, somebody 
posted a question involving tens of thousands of lines of tens of 
thousands of characters each (don't quote me, I'm going by memory). On 
the other hand, it doesn't require much imagination to think of a use-
case where there are millions of lines each of a dozen or so characters, 
and you want to process it line by line:


noun: cat
noun: dog
verb: caf?
...


As always, before optimizing, you should profile to be sure you are 
actually optimizing and not wasting your time.



-- 
Steven


From hendrik at microcorp.co.za  Fri Aug  7 03:38:54 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Fri, 7 Aug 2009 09:38:54 +0200
Subject: help with threads
In-Reply-To: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
Message-ID: <200908070938.54928.hendrik@microcorp.co.za>

On Friday 07 August 2009 05:02:10 Michael Mossey wrote:
> Hello,

> My problem is that in some cases, the network thread appears to stop,
> while the main thread is doing a long computation.

Is this computation done in pure python or are you calling some
underlying thing in C?

I would be surprised if a pure python computation thread were to hog
the cpu  - have you been able to figure out what the computation thread is
actually doing when the hogging occurs?

> I'm hoping someone can give me a general idea what to read about. For
> example, under what conditions does a thread stop running? Can other
> threads "take priority"? Are there certain operations that block other
> threads (such as disk access)?

AFAIK python threads are all at the same level of priority, and the running
thread is interrupted every N python bytecode instructions, so what you are
experiencing should not happen.

Try to figure out, if you can, where the computation thread is spending
its time.

- Hendrik


From lists at digital.ktu.lt  Fri Aug  7 03:46:20 2009
From: lists at digital.ktu.lt (Algirdas Brazas)
Date: Fri, 7 Aug 2009 10:46:20 +0300
Subject: Pywin32 @ windows 7
Message-ID: <004a01ca1733$a9768c10$4605a8c0@btsc1>

Hi all,

Did anyone manage to get windows extensions installet on windows 7 64 bit? As 
far as I try I get only "Setup program invalid or damaged".

Al. 




From sumit.jha50 at gmail.com  Fri Aug  7 04:22:14 2009
From: sumit.jha50 at gmail.com (sumit)
Date: Fri, 7 Aug 2009 01:22:14 -0700 (PDT)
Subject: problem
Message-ID: <207a84d7-fb45-46c5-a2fb-e34c564c09f8@v37g2000prg.googlegroups.com>

i want 2 hav the header files for regular expression to non
deterministin autometa
so whr should i find it?plz help


From jeanmichel at sequans.com  Fri Aug  7 04:47:55 2009
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Fri, 07 Aug 2009 10:47:55 +0200
Subject: help with threads
In-Reply-To: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
Message-ID: <4A7BEA3B.4090000@sequans.com>

Michael Mossey wrote:
> Hello,
>
> I have a simple application that needs one thread to manage networking
> in addition to the main "thread" that does the main job. It's not
> working right. I know hardly anything about threads, so I was hoping
> someone could point me in the right direction to research this.
>
> Basically, I have a program that does some computational work, and
> also conveys its status to a monitor program elsewhere on the network
> via sockets. I wanted to use a thread to manage the networking so that
> the main program can run without regard to networking (i.e. they would
> be asynchronous). So the network thread loops and calls select.
>
> My problem is that in some cases, the network thread appears to stop,
> while the main thread is doing a long computation.
>
> I'm hoping someone can give me a general idea what to read about. For
> example, under what conditions does a thread stop running? Can other
> threads "take priority"? Are there certain operations that block other
> threads (such as disk access)?
>
> Thanks,
> Mike
>   
I may be a little out of subject, anyway *if* you are writing also the 
server side program, you should really take a look at
http://docs.python.org/library/xmlrpclib.html
or
http://pyro.sourceforge.net/

... and forget about network coding :o)

To help you for your initial question, exceptions in thread are not 
propagated to the main thread, so when an unhanded exception occurs in 
your thread, it will just stop. Maybe this is what is happening.

A quick workaround is to embed all you threaded code in a try except 
clause and log the exception before re-raising it. You should only do 
that for debugging purpose.

JM


From jeanmichel at sequans.com  Fri Aug  7 04:55:51 2009
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Fri, 07 Aug 2009 10:55:51 +0200
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>	
		<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
Message-ID: <4A7BEC17.6040602@sequans.com>

alex23 wrote:
> Paul Rubin  wrote:
>   
>> The PHP docs as I remember are sort of regular (non-publically
>> editable) doc pages, each of which has a public discussion thread
>> where people can post questions and answers about the topic of that
>> doc page.  I thought it worked really well.  The main thing is that
>> the good stuff from the comment section gets folded into the actual
>> doc now and then.
>>     
>
> I'd still like to see this kept out of the official docs as much as
> possible, mostly for reasons of brevity & clarity. I think the
> official docs should be considered definitive and not require a
> hermeneutic evaluation against user comments to ensure they're still
> correct...
>
> How about a secondary site that embeds the docs and provides
> commenting functionality around it? That's certainly a finitely scoped
> project that those with issues about the docs could establish and
> contribute to, with the possibility of it gaining official support
> later once it gains traction.
>
>
>
>   
Very good Idea. I'd like to get a commented/user improved python 
documentation site with examples and I also love the current python 
documentation.

JM


From piet at cs.uu.nl  Fri Aug  7 05:14:30 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Fri, 07 Aug 2009 11:14:30 +0200
Subject: Web page data and urllib2.urlopen
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
	
	
	
Message-ID: 

>>>>> Dave Angel  (DA) wrote:

>DA> Piet van Oostrum wrote:
>>> 
>DA> If Mozilla had seen a page with this line in an appropriate place, it'd
>DA> immediately begin loading the other page, at "someotherurl"  But there's no
>DA> such line.
>>>> 
>>> 
>>> 
>DA> Next, I looked for javascript.  The Mozilla page contains lots of
>DA> javascript, but there's none in the raw page.  So I can't explain Mozilla's
>DA> differences that way.
>>>> 
>>> 
>>> 
>DA> I did notice the link to /m/Content/mobile2.css, but I don' t know any way
>DA> a CSS file could cause the content to change, just the display.
>>>> 
>>> 
>>> 
>DA> All I can guess is that it has something to do with "browser type" or
>DA> cookies.  And that would make lots of sense if this was a cgi page.  But
>DA> the URL doesn't look like that, as it doesn't end in pl, py, asp, or any of
>DA> another dozen special suffixes.
>>>> 
>>> 
>>> 
>DA> Any hints, anybody???
>>>> 
>>> 
>>> If you look into the HTML that Firefox gets, there is a lot of
>>> javascript in it.
>>> 

>DA> But the raw page didn't have any javascript.  So what about that original
>DA> raw page triggered additional stuff to be loaded?
>DA> Is it "user agent", as someone else brought out?  And is there somewhere I
>DA> can read more about that aspect of things?  I've mostly built very static
>DA> html pages, where the server yields the same page to everybody.  And some
>DA> form stuff, where the  user clicks on a 'submit" button to trigger a script
>DA> that's not shown on the URL line.

Yes, if you specify a 'normal' web browser as user agent you do get the
Javascript:

import urllib2

request = urllib2.Request('http://www.marketwatch.com/story/mondays-biggest-gaining-and-declining-stocks-2009-07-27')
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13')

opener = urllib2.build_opener() 
page = opener.open(request).read()
print page

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From rt8396 at gmail.com  Fri Aug  7 05:22:50 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 02:22:50 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
Message-ID: <0067d0ed-95b7-4a97-b2f8-7f35f13c6304@f10g2000vbf.googlegroups.com>

On Aug 7, 12:41?am, alex23  wrote:
...(snip)
> How about a secondary site that embeds the docs and provides
> commenting functionality around it? That's certainly a finitely scoped
> project that those with issues about the docs could establish and
> contribute to, with the possibility of it gaining official support
> later once it gains traction.

This is by far the most helpful and honest post i have ever seen by
our friend alex23. I have a new found respect for you sir, thanks

-R


From piet at cs.uu.nl  Fri Aug  7 05:33:24 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Fri, 07 Aug 2009 11:33:24 +0200
Subject: problem
References: <207a84d7-fb45-46c5-a2fb-e34c564c09f8@v37g2000prg.googlegroups.com>
Message-ID: 

>>>>> sumit  (s) wrote:

>s> i want 2 hav the header files for regular expression to non
>s> deterministin autometa
>s> so whr should i find it?plz help

What header files? C? You can find lots of header files by googling. But
the header files contain only the interface, not the implementation. And
conversion from regular expression to non-deterministic automaton is an
implementation matter, so the header file will not help you there. You
will need the C or C++ file.

And then, do you want Python's implementation or any implementation.
Please be specific when you ask something.

Start by googling for regex.h for general software.
Python header file is in
http://svn.python.org/view/python/trunk/Modules/sre.h and the
implementation in http://svn.python.org/view/python/trunk/Modules/_sre.c
but I don't think it goes non deterministic. For that you can better
look into the general 'grep'-like software. For example start here:
http://arglist.com/regex/ 
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From anand at esi-india.com  Fri Aug  7 05:54:06 2009
From: anand at esi-india.com (Anand K Rayudu)
Date: Fri, 07 Aug 2009 15:24:06 +0530
Subject: How to reset document  string
Message-ID: <4A7BF9BE.2080702@esi-india.com>

Dear All,

We have extended and embedded python into my our application.
We exposed few APIs to python using

 Py_InitModule("myModuleName", myMethods);
where my methods are

static PyMethodDef VistaDbMethods[] = {
   { (char *)"myAPI",_myAPICFunctionPtr ,METH_VARARGS,"usage: MyHelp)" }


Now problem is ml_doc (Document string). Most of the time the strings 
given by development team is not descriptive enough, so support team 
want to enhance these docstring on need basis and supply to customer
The idea is we will provide get latest help option from application, 
which will contact our webserver or allow user to pick new help 
document,  which will re apply the help on fly.
 From then on our script editors will show the new enhanced help.
How do I achieve this.

I tried to change ..__doc__ = "My new doc"

This failles as it is read only attribute.

Another approach could be calling  Py_InitModule("myModuleName", 
myMethods); with new help string. But It is not working,
So I am not sure what is the right way to do it

Thanks in advance for  all your kind help

Regards,
Anand





From thorsten at thorstenkampe.de  Fri Aug  7 06:00:42 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Fri, 7 Aug 2009 12:00:42 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
Message-ID: 

* Steven D'Aprano (06 Aug 2009 19:17:30 GMT)
> On Thu, 06 Aug 2009 20:05:52 +0200, Thorsten Kampe wrote:
> > > That is significant! So the winner is:
> > > 
> > > unicode('???????','utf-8')
> > 
> > Unless you are planning to write a loop that decodes "???????" one
> > million times, these benchmarks are meaningless.
> 
> What if you're writing a loop which takes one million different lines of 
> text and decodes them once each?
> 
> >>> setup = 'L = ["abc"*(n%100) for n in xrange(1000000)]'
> >>> t1 = timeit.Timer('for line in L: line.decode("utf-8")', setup)
> >>> t2 = timeit.Timer('for line in L: unicode(line, "utf-8")', setup)
> >>> t1.timeit(number=1)
> 5.6751680374145508
> >>> t2.timeit(number=1)
> 2.6822888851165771
> 
> Seems like a pretty meaningful difference to me.

Bollocks. No one will even notice whether a code sequence runs 2.7 or 
5.7 seconds. That's completely artificial benchmarking.

Thorsten


From deets at nospam.web.de  Fri Aug  7 06:09:34 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 07 Aug 2009 12:09:34 +0200
Subject: Cython + setuptools not working with .pyx,only with .c-files
In-Reply-To: 
References: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
	
Message-ID: <7e2cquF2c8kj0U1@mid.uni-berlin.de>

David Cournapeau schrieb:
> On Thu, Aug 6, 2009 at 7:38 PM, Diez B. Roggisch wrote:
>> Hi,
>>
>>
>> I'm trying to build a Cython-extension as Egg.
>>
>> However, this doesn't work - I can either use distutils to build the
>> extension, creating a myextension.c-file on the way.
>>
>> If that's there, I can use setuptools to build the egg.
>>
>> But when I remove the .c-file, the .pyx-file isn't used to re-generate it.
>>
>> This is my setup.py:
>>
>> ----
>> import os
>> import glob
>> from setuptools import setup, Extension
>> #from distutils.core import setup
>> #from distutils.extension import Extension
>>
>> from Cython.Distutils import build_ext
> 
> What happens if you import setuptools *after* Cython.distutils ? My
> guess - I could be wrong - is that both Cython.distutils and
> setuptools monkey-patch distutils, and that setuptools does not "see"
> Cython.Distutils. It could also be an incompatibility between
> Cython.Distutils and setuptools (the design of distutils forces you to
> take into account the details of things modified by every distutils
> extension).

Tried that, nothing changed :(

Diez


From deets at nospam.web.de  Fri Aug  7 06:12:23 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 07 Aug 2009 12:12:23 +0200
Subject: need help with an egg
In-Reply-To: <4d881767-ebe3-432c-bc9b-683b80626c97@y4g2000prf.googlegroups.com>
References: <4d881767-ebe3-432c-bc9b-683b80626c97@y4g2000prf.googlegroups.com>
Message-ID: <7e2d07F2c8kj0U2@mid.uni-berlin.de>

jo schrieb:
> Hi,
> 
> I am very new to python....
> 
> I created an egg on a machine.  The Python version on that  is 2.5.
> Copied that egg to a machine which has Python 2.6.
> 
> unzip -t Myproj-0.1-py2.5.egg
> The above command shows all the files I need
> 
> When I run the easy_install, I get the foll. error.  Is it because of
> the version?  Or am I doing something wrong?  Or the way I understand
> the egg works is wrong.  Can anyone please help?
> If it's the version issue, does that mean I cannot use that egg on my
> machine with 2.6 version?
> 
> Installed /usr/local/lib/python2.6/dist-packages/Myproj-0.1-py2.5.egg
> Processing dependencies for Myproj==0.1
> Searching for Myproj==0.1
> Reading http://pypi.python.org/simple/Myproj/
> Couldn't find index page for 'Myproj' (maybe misspelled?)
> Scanning index of all packages (this may take a while)
> Reading http://pypi.python.org/simple/
> No local packages or download links found for Myproj==0.1
> error: Could not find suitable distribution for Requirement.parse
> ('Myproj==0.1')

Yes, eggs are (at least) python version specific. They can even be 
OS-specific.


Diez


From thorsten at thorstenkampe.de  Fri Aug  7 06:12:32 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Fri, 7 Aug 2009 12:12:32 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	
Message-ID: 

* Michael Str?der (Fri, 07 Aug 2009 03:25:03 +0200)
> Thorsten Kampe wrote:
> > * Michael Str?der (Thu, 06 Aug 2009 18:26:09 +0200)
> >>>>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
> >> 17.23644495010376
> >>>>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
> >> 72.087096929550171
> >>
> >> That is significant! So the winner is:
> >>
> >> unicode('???????','utf-8')
> > 
> > Unless you are planning to write a loop that decodes "???????" one 
> > million times, these benchmarks are meaningless.
> 
> Well, I can tell you I would not have posted this here and checked it if it
> would be meaningless for me. You don't have to read and answer this thread if
> it's meaningless to you.

Again: if you think decoding "???????" one million times is a real world 
use case for your module then go for unicode(). Otherwise the time you 
spent benchmarking artificial cases like this is just wasted time. In 
real life people won't even notice whether an application takes one or 
two minutes to complete.

Use whatever you prefer (decode() or unicode()). If you experience 
performance bottlenecks when you're done, test whether changing decode() 
to unicode() makes a difference. /That/ is relevant.

Thorsten


From deets at nospam.web.de  Fri Aug  7 06:17:50 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 07 Aug 2009 12:17:50 +0200
Subject: How to reset document  string
In-Reply-To: 
References: 
Message-ID: <7e2daiF2da4u8U1@mid.uni-berlin.de>

Anand K Rayudu schrieb:
> Dear All,
> 
> We have extended and embedded python into my our application.
> We exposed few APIs to python using
> 
> Py_InitModule("myModuleName", myMethods);
> where my methods are
> 
> static PyMethodDef VistaDbMethods[] = {
>   { (char *)"myAPI",_myAPICFunctionPtr ,METH_VARARGS,"usage: MyHelp)" }
> 
> 
> Now problem is ml_doc (Document string). Most of the time the strings 
> given by development team is not descriptive enough, so support team 
> want to enhance these docstring on need basis and supply to customer
> The idea is we will provide get latest help option from application, 
> which will contact our webserver or allow user to pick new help 
> document,  which will re apply the help on fly.
>  From then on our script editors will show the new enhanced help.
> How do I achieve this.
> 
> I tried to change ..__doc__ = "My new doc"
> 
> This failles as it is read only attribute.
> 
> Another approach could be calling  Py_InitModule("myModuleName", 
> myMethods); with new help string. But It is not working,
> So I am not sure what is the right way to do it

To put the right docstrings into the embedded interpreter. I don't know 
about your processes, but either the support just suggests better 
strings & developers put them in there, or maybe some sort of shared 
header-file could be used that the developers use & support enhances. 
Something like this:


--- docstrings.h ---

#define VistaDbMethods__doc__ "usage: MyHelp"


And if that's enhanced over time by the support-staff, docs will get 
better. Hopefully.

Alternatives are:

  - beating your developers with a clue-stick into submission that good 
docs are important
  - write a usage-guide using e.g. sphinx and release that as add-on-docs.

Diez


From http  Fri Aug  7 06:43:48 2009
From: http (Paul Rubin)
Date: 07 Aug 2009 03:43:48 -0700
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
Message-ID: <7xk51fgazf.fsf@ruckus.brouhaha.com>

alex23  writes:
> I'd still like to see this kept out of the official docs as much as
> possible, mostly for reasons of brevity & clarity. I think the
> official docs should be considered definitive and not require a
> hermeneutic evaluation against user comments to ensure they're still
> correct...

Such evaluation would only do them good.  The official docs are full
of errors and omissions, which is why we have this thread going on
here in the newsgroup.


From dioxide.software at gmail.com  Fri Aug  7 07:09:25 2009
From: dioxide.software at gmail.com (KK)
Date: Fri, 7 Aug 2009 04:09:25 -0700 (PDT)
Subject: pylucene installation problem on Ubuntu 9.04
References: 
	 
	
Message-ID: 

I tried doing something silly.
I went to the directory "/usr/local/lib/python2.6/site-packages" and
then tried to compile/run the file called PyLucene.py the way we
compile/run python scripts, then from there i started the python
interpreter by typing python ( which is actually python2.6), then i
tried to import that module, [un]fortunately it din't give that error
message but something else, you can see below:

kk-laptop:/usr/local/lib/python2.6/site-packages$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> indexDir = '/opt/lucene/index'
>>> import PyLucene
WARNING: could not properly read security provider files:
         file:///usr/local/gcc-3.4.6/lib/security/libgcj.security
         file:///usr/local/gcc-3.4.6/lib/security/classpath.security
         Falling back to standard GNU security provider
>>>

then tried to copy and paste my sample code for indexing data to
lucene, this way:


>>> writer = IndexWriter(indexDir, StandardAnalyzer(), True)
>>> title = "this is sample page title"
>>> content = "This is sample page content for testing pylucene tool"
>>>
>>> doc = Document()
>>> doc.add(Field("title", title, Field.Store.YES, Field.Index.TOKENIZED))
>>> doc.add(Field("content", content, Field.Store.YES, Field.Index.TOKENIZED))
>>> writer.addDocument(doc)
>>> writer.optimize()
>>>

----------------------------
and surprisingly it din't give any other error. to crosscheck things i
went to the lucene index directory and fired LUKE and luckily found
that doc being indexed by lucene, even i tried searching for some
words and found they are working fine. So Pylucene seems to be working
partially, in my case. But I think python is not able to load the
PyLucene module (btw, i din't see any __init__ scripts which, i guess,
are used for bootstrapping external modules, right?). Then what is the
fix for this? do we have to add some __init__ scripts to make python
load PyLucene module when it starts? do i sound silly? What is the
best/easiest way to get this working? I've spend quite a lot of time
jsut to make PyLucene running but to no avail.
BTW, I tried to start the python interpreter from other locations and
tried imporitn this PyLucene module but got the same irritating error
message saying "module not found".
Also trying to run my sample indexer from cli using the normal way[kk-
laptop$ python indexer.py] gave the same error message.

Any help/advice is highly appreciated.
Thanks,
KK

On Aug 7, 8:22?am, KK  wrote:
> On Aug 7, 12:38?am, Jon Clements  wrote:
>
>
>
> > On 6 Aug, 19:49, KK  wrote:
>
> > > hi all,
> > > I've trying to install pylucene on my linux box from last 2 days but
> > > not able to do so. first i tried to install it using apt-get like
> > > this,
> > > kk-laptop$ sudo apt-get install pylucene
> > > and it did install python2.5, python2.5-minimal and pylucene. I must
> > > mention one thing that I already had python2.6 on my box as the
> > > default python i.e /usr/bin/python is linked to python2.6. Anyway s,
> > > now i started the python interpreter using "python" command from cli
> > > and then to make sure pylucene has been installed i tried to import
> > > the module and to my surprise it said "module pylucene not found".
> > > I thought I should enter the python2.6 env and do the same , so i
> > > tried starting the python2.6 interpreter using "python2.6" as the
> > > command and tried importing the same module and again it failed giving
> > > the same irritating message.
> > > ?As a final try i pulled the source code of pylucene and as per the
> > > comments given there in the README file, copied the mentioned files to
> > > site-packages directory of python2.6 and then tried importing the
> > > module and then got the same error message saying no module name
> > > pylucene is present. I'm sick of this error !
> > > Can someone point me what is the issue? If it is due to multiple
> > > version of python running on box, can someone tell me which one to
> > > remove or someone tell me how to get the whole thing running? I'll
> > > very much thankful to you guys.
>
> > > Thanks,
> > > KK.
>
> > If you installed using apt, have you a pylucene directory under /usr/
> > local/lib/python2.6/dist-packages/?
>
> > Also, if you run python, and import sys; print sys.path
> > whats it show?
>
> > Jon.
>
> Yes I've a dirctory called dist-packages under python2.6 but that
> doesn't contain anything on pylucene [it has lupyne, which i installed
> day before yesterday and importing lupyne doesn't give any error msg,
> but again it is dependent on pylucene]
> # for python the output is :
> ------------------------------
> kk-laptop$ python
> Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> import sys
> >>> print sys.path
>
> ['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/
> python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/
> lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/
> dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/var/
> lib/python-support/python2.6', '/usr/lib/python2.6/dist-packages/
> gtk-2.0', '/var/lib/python-support/python2.6/gtk-2.0', '/usr/local/lib/
> python2.6/dist-packages']
>
> -------------------------------
>
> for python2.5 this is the output:
> kk-laptop$ python2.5
> Python 2.5.4 (r254:67916, Apr ?4 2009, 17:55:16)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> import sys
> >>> print sys.path
>
> ['', '/usr/lib/python2.5', '/usr/lib/python2.5/plat-linux2', '/usr/lib/
> python2.5/lib-tk', '/usr/lib/python2.5/lib-dynload', '/usr/local/lib/
> python2.5/site-packages', '/usr/lib/python2.5/site-packages', '/usr/
> lib/python2.5/site-packages/PIL', '/usr/lib/python2.5/site-packages/
> gst-0.10', '/var/lib/python-support/python2.5', '/usr/lib/python2.5/
> site-packages/gtk-2.0', '/var/lib/python-support/python2.5/gtk-2.0']
>
> --------------------------------
>
> and for python2.6 the output is this:
> kk-laptop$ python2.6
> Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
> [GCC 4.3.3] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> import sys
> >>> print sys.path
>
> ['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/
> python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/
> lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/lib/python2.6/
> dist-packages/PIL', '/usr/lib/python2.6/dist-packages/gst-0.10', '/var/
> lib/python-support/python2.6', '/usr/lib/python2.6/dist-packages/
> gtk-2.0', '/var/lib/python-support/python2.6/gtk-2.0', '/usr/local/lib/
> python2.6/dist-packages']
>
> From all of the above what I can see is we don't have any directory
> named dist-packages under python2.5 but we've one under 2.6, then
> where did all those pylucene files got installed to after i installed
> it using apt-get? Any ideas?
>
> Thanks
> KK



From andrew at acooke.org  Fri Aug  7 07:29:13 2009
From: andrew at acooke.org (andrew cooke)
Date: Fri, 7 Aug 2009 04:29:13 -0700 (PDT)
Subject: Parsing Binary Structures; Is there a better way / What is your 
	way?
References: 
Message-ID: <4c436221-7f6e-43ca-9ece-6b05afac540a@g1g2000vbr.googlegroups.com>

On Aug 5, 10:46?am, "Martin P. Hellwig" 
wrote:
> Hi List,
>
> On several occasions I have needed (and build) a parser that reads a
> binary piece of data with custom structure. For example (bogus one):
>
> BE
> +---------+---------+-------------+-------------+------+--------+
> | Version | Command | Instruction | Data Length | Data | Filler |
> +---------+---------+-------------+-------------+------+--------+
> Version: 6 bits
> Command: 4 bits
> Instruction: 5 bits
> Data Length: 5 bits
> Data: 0-31 bits
> Filler: filling 0 bits to make the packet dividable by 8

hi,

sorry i'm a bit late here, but lepl does exactly this.  also, as you
asked for in another post, the BitString class allows arbitrary
indexing into a sequence of bits.  and because it's part of a
recursive descent parser you can match "anything" (lepl will handle -
although less efficiently - left recursive and ambiguous grammars).

see the example at http://www.acooke.org/lepl/binary.html#matching
which constructs an ethernet frame and then parses it, extracting the
source and destination addresses.

feel free to email me with more questions.

disclaimer: this is quite new and i don't know of anyone that actually
uses it; it is also Python3 only (because it uses bytes()).

andrew




From cournape at gmail.com  Fri Aug  7 07:35:24 2009
From: cournape at gmail.com (David Cournapeau)
Date: Fri, 7 Aug 2009 20:35:24 +0900
Subject: Cython + setuptools not working with .pyx,only with .c-files
In-Reply-To: <7e2cquF2c8kj0U1@mid.uni-berlin.de>
References: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
	
	<7e2cquF2c8kj0U1@mid.uni-berlin.de>
Message-ID: <5b8d13220908070435i2ee17e9cgb183ee11791d401b@mail.gmail.com>

On Fri, Aug 7, 2009 at 7:09 PM, Diez B. Roggisch wrote:

>
> Tried that, nothing changed :(

Then you will have to modify Cython.Distutils to be aware of
setuptools, I think (and soon Distribute... ).

David


From garabik-news-2005-05 at kassiopeia.juls.savba.sk  Fri Aug  7 07:49:05 2009
From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk)
Date: Fri, 7 Aug 2009 11:49:05 +0000 (UTC)
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
Message-ID: 

Thorsten Kampe  wrote:
> * Steven D'Aprano (06 Aug 2009 19:17:30 GMT)
>> What if you're writing a loop which takes one million different lines of 
>> text and decodes them once each?
>> 
>> >>> setup = 'L = ["abc"*(n%100) for n in xrange(1000000)]'
>> >>> t1 = timeit.Timer('for line in L: line.decode("utf-8")', setup)
>> >>> t2 = timeit.Timer('for line in L: unicode(line, "utf-8")', setup)
>> >>> t1.timeit(number=1)
>> 5.6751680374145508
>> >>> t2.timeit(number=1)
>> 2.6822888851165771
>> 
>> Seems like a pretty meaningful difference to me.
> 
> Bollocks. No one will even notice whether a code sequence runs 2.7 or 
> 5.7 seconds. That's completely artificial benchmarking.
>

For a real-life example, I have often a file with one word per line, and
I run python scripts to apply some (sometimes fairy trivial)
transformation over it. REAL example, reading lines with word, lemma,
tag separated by tabs from stdin and writing word into stdout, unless it
starts with '<' (~6e5 lines, python2.5, user times, warm cache, I hope
the comments are self-explanatory)

no unicode
user    0m2.380s

decode('utf-8'), encode('utf-8')
user    0m3.560s

sys.stdout = codecs.getwriter('utf-8')(sys.stdout);sys.stdin = codecs.getreader('utf-8')(sys.stdin)
user    0m6.180s

unicode(line, 'utf8'), encode('utf-8')
user    0m3.820s

unicode(line, 'utf-8'), encode('utf-8')
user    0m2.880sa

python3.1
user    0m1.560s

Since I have something like 18 million words in my currenct project (and
 > 600 million overall) and I often tweak some parameters and re-run the
 > transformations, the differences are pretty significant.

Personally, I have been surprised by:
1) bad performance of the codecs wrapper (I expected it to be on par with 
   unicode(x,'utf-8'), mayble slightly better due to less function calls
2) good performance of python3.1 (utf-8 locale)


-- 
 -----------------------------------------------------------
| Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__    garabik @ kassiopeia.juls.savba.sk     |
 -----------------------------------------------------------
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!


From dmitrey.kroshko at scipy.org  Fri Aug  7 08:00:40 2009
From: dmitrey.kroshko at scipy.org (dmitrey)
Date: Fri, 7 Aug 2009 05:00:40 -0700 (PDT)
Subject: how to overload operator "<  <" (a < x < b)?
Message-ID: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>

hi all,
is it possible to overload operator "<  <"? (And other like this one,
eg "<=  <=", ">  >", ">=  >=")
Any URL/example?
Thank you in advance, D.


From davea at ieee.org  Fri Aug  7 08:15:11 2009
From: davea at ieee.org (Dave Angel)
Date: Fri, 07 Aug 2009 08:15:11 -0400
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>	
		<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
Message-ID: <4A7C1ACF.80505@ieee.org>

alex23 wrote:
> Paul Rubin  wrote:
>   
>> The PHP docs as I remember are sort of regular (non-publically
>> editable) doc pages, each of which has a public discussion thread
>> where people can post questions and answers about the topic of that
>> doc page.  I thought it worked really well.  The main thing is that
>> the good stuff from the comment section gets folded into the actual
>> doc now and then.
>>     
>
> I'd still like to see this kept out of the official docs as much as
> possible, mostly for reasons of brevity & clarity. I think the
> official docs should be considered definitive and not require a
> hermeneutic evaluation against user comments to ensure they're still
> correct...
>
> How about a secondary site that embeds the docs and provides
> commenting functionality around it? That's certainly a finitely scoped
> project that those with issues about the docs could establish and
> contribute to, with the possibility of it gaining official support
> later once it gains traction.
>
>
>   
I share your concern about unmonitored comments.  However, it seems a 
useful possibility would be for the "official" pages to each have 
specially-marked links that possibly lead to such user comments.  
Clearly they'd have to marked carefully, so that naive users don't 
confuse the two.  But otherwise, it feels like a good idea.

In my case, I usually access the docs via the Windows help file.  So 
it'd be quite easy for me to recognize that once I've gotten to a 
browser page, I'm not in Kansas any more.  But that could be also 
accomplished by having a very different stylesheet for the user comments 
page.

DaveA



From deets at nospam.web.de  Fri Aug  7 08:16:22 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 07 Aug 2009 14:16:22 +0200
Subject: how to overload operator "<  <" (a < x < b)?
In-Reply-To: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
Message-ID: <7e2k8mF2djd57U1@mid.uni-berlin.de>

dmitrey schrieb:
> hi all,
> is it possible to overload operator "<  <"? (And other like this one,
> eg "<=  <=", ">  >", ">=  >=")
> Any URL/example?
> Thank you in advance, D.

http://docs.python.org/reference/datamodel.html#object.__lt__

Diez


From __peter__ at web.de  Fri Aug  7 08:21:31 2009
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Aug 2009 14:21:31 +0200
Subject: how to overload operator "<  <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
Message-ID: 

dmitrey wrote:

> is it possible to overload operator "<  <"? (And other like this one,
> eg "<=  <=", ">  >", ">=  >=")

No. 

a < x < b 

is a shortcut for 

a < x and x < b

where x is of course evaluated only once.

Peter




From durumdara at gmail.com  Fri Aug  7 08:31:10 2009
From: durumdara at gmail.com (durumdara)
Date: Fri, 7 Aug 2009 05:31:10 -0700 (PDT)
Subject: Bug or feature: double strings as one
Message-ID: 

Hi!

I found an interesting thing in Python.
Today one of my "def"s got wrong result.

When I checked the code I saw that I miss a "," from the list.

l = ['?' '?']

Interesting, that Python handle them as one string.

print ['?' '?']
['\xf3\xd3']

I wanna ask that is a bug or is it a feature?

In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
must concatenate the strings with some sign, like "+" or "||".

This technic is avoid the mistyping, like today. But in python I can
miss the concat sign, and I got wrong result...

Thanks for your help and for your answer:
   dd




From pavlovevidence at gmail.com  Fri Aug  7 08:33:25 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 7 Aug 2009 05:33:25 -0700 (PDT)
Subject: How to reset document string
References: 
Message-ID: 

On Aug 7, 2:54?am, Anand K Rayudu  wrote:
> Dear All,
>
> We have extended and embedded python into my our application.
> We exposed few APIs to python using
>
> ?Py_InitModule("myModuleName", myMethods);
> where my methods are
>
> static PyMethodDef VistaDbMethods[] = {
> ? ?{ (char *)"myAPI",_myAPICFunctionPtr ,METH_VARARGS,"usage: MyHelp)" }
>
> Now problem is ml_doc (Document string). Most of the time the strings
> given by development team is not descriptive enough, so support team
> want to enhance these docstring on need basis and supply to customer
> The idea is we will provide get latest help option from application,
> which will contact our webserver or allow user to pick new help
> document, ?which will re apply the help on fly.
> ?From then on our script editors will show the new enhanced help.
> How do I achieve this.

Sounds very cool.  I have a few ideas.

1. Since you say you are embedding Python in your application, the
most direct way might be to modify the Python interpreter to allow the
__doc__ attribute to be changed.  You'd have to modify the PyCFunction
type (defined in methodobject.h and methodobject.c) to allow
overriding the compiled-in doc field.

2. Instead of replacing the __doc__ attribute of the function, just
replace the whole function with a wrapper.  So, for instance, if your
application decides to update the docstring for myModuleName.myAPI(),
instead of running code like this:

    myModuleName.myAPI.__doc__ = 'new docstring'

run code like this:

    def create_wrapper(func,docstring):
        def wrapper(*args):
            return func(*args)
        wrapper.__doc__ = doc
        return wrapper
    myModuleName.myAPI = create_wrapper(
                 myModuleName.myAPI,'new docstring')

So now myApi is a Python function with the new docstring that calls
the old function.  (Note: if you are concerned with efficiency, it's
possible to write a wrapper in C that has very little overhead.)

This approach has minor disadvantages (such as if any code write from
myModuleName import myAPI--it won't see the new version) but it may be
the easiest approach.

3. Instead of customizing the __doc__ attribute, store any custom
docstrings in a dictionary keyed by the function.

    custom_doc[myModuleName.myApi] = 'new docstring'

Your script editor, when looking for documentation, will first search
in this custom area to see if the docstring has been overridden; if
so, use that; if not, use the docstring.  Something like this:

    def documentation_to_use_in_script_editor(func):
        try:
            return custom_doc[func]
        except KeyError:
            return func.__doc__

That has the negative of the special docstring not being visible at an
interactive prompt.


I have given you some fairly vague answers, hopefully that'll give you
some idea.  It sounds like you have an ambitious project, suggesting
that you are probably good enough to implement the suggestions.


Carl Banks


From davea at ieee.org  Fri Aug  7 08:34:00 2009
From: davea at ieee.org (Dave Angel)
Date: Fri, 07 Aug 2009 08:34:00 -0400
Subject: Web page data and urllib2.urlopen
In-Reply-To: 
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>			
	
Message-ID: <4A7C1F38.8010701@ieee.org>


Piet van Oostrum wrote:
>>>>>> 
>>>>>>             
> 
>> DA> But the raw page didn't have any javascript.  So what about that original
>> DA> raw page triggered additional stuff to be loaded?
>> DA> Is it "user agent", as someone else brought out?  And is there somewhere I
>> DA> can read more about that aspect of things?  I've mostly built very static
>> DA> html pages, where the server yields the same page to everybody.  And some
>> DA> form stuff, where the  user clicks on a 'submit" button to trigger a script
>> DA> that's not shown on the URL line.
>>     
>
> Yes, if you specify a 'normal' web browser as user agent you do get the
> Javascript:
>
> import urllib2
>
> request = urllib2.Request('http://www.marketwatch.com/story/mondays-biggest-gaining-and-declining-stocks-2009-07-27')
> request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13')
>
> opener = urllib2.build_opener() 
> page = opener.open(request).read()
> print page
>
>   
Thanks much.  That's a key I didn't understand.

DaveA


From deets at nospam.web.de  Fri Aug  7 08:37:48 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 07 Aug 2009 14:37:48 +0200
Subject: Bug or feature: double strings as one
In-Reply-To: 
References: 
Message-ID: <7e2lgtF2bpusmU1@mid.uni-berlin.de>

durumdara schrieb:
> Hi!
> 
> I found an interesting thing in Python.
> Today one of my "def"s got wrong result.
> 
> When I checked the code I saw that I miss a "," from the list.
> 
> l = ['?' '?']
> 
> Interesting, that Python handle them as one string.
> 
> print ['?' '?']
> ['\xf3\xd3']
> 
> I wanna ask that is a bug or is it a feature?
> 
> In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
> must concatenate the strings with some sign, like "+" or "||".
> 
> This technic is avoid the mistyping, like today. But in python I can
> miss the concat sign, and I got wrong result...

It's a feature. It is sometimes used in cases where you want to split a 
longer text into several lines, but without introducing newlines.

like this (the parentheses are there for the parser not to puke):


foo = ("foobarbaz"
        "padamm")

It has the potential to produce errors as you have seen them, though.

Diez


From s.selvamsiva at gmail.com  Fri Aug  7 08:40:49 2009
From: s.selvamsiva at gmail.com (S.Selvam)
Date: Fri, 7 Aug 2009 18:10:49 +0530
Subject: pulldom extracting records from recordset
Message-ID: 

Hi all,

I am using pulldom to handle large xml files.It works fine, but i do not
know how to store a particular set of  records(as xml) out of the recordset.
-----------------code---------
from xml.dom import pulldom
hamlet_file = open("input_xml/inp_test.xml")
events = pulldom.parse(hamlet_file)
for (event, node) in events:
  if event == pulldom.START_ELEMENT:
    if node.tagName == "Record":
     events.expandNode(node)
     print node  #this does not work as it is a object
------------------------------

Whenever the node name is a Record,i process it. I want to store the all the
nodes meeting my requirement.
  For eg,i need output as below,

         
            
                 hi
           
           
            ---
           
        

         
            
                 hello
           .
           .
Where input xml might contain 'n' number of Records.
I have been struggling to figure it out.I would be happy to get a solution
for this.

-- 
Yours,
S.Selvam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From __peter__ at web.de  Fri Aug  7 08:41:36 2009
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Aug 2009 14:41:36 +0200
Subject: Bug or feature: double strings as one
References: 
Message-ID: 

durumdara wrote:

> I found an interesting thing in Python.
> Today one of my "def"s got wrong result.
> 
> When I checked the code I saw that I miss a "," from the list.
> 
> l = ['?' '?']
> 
> Interesting, that Python handle them as one string.
> 
> print ['?' '?']
> ['\xf3\xd3']
> 
> I wanna ask that is a bug or is it a feature?

Feature:

http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation

Peter



From benjamin.kaplan at case.edu  Fri Aug  7 08:50:52 2009
From: benjamin.kaplan at case.edu (Benjamin Kaplan)
Date: Fri, 7 Aug 2009 08:50:52 -0400
Subject: how to overload operator "< <" (a < x < b)?
In-Reply-To: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
Message-ID: 

On Fri, Aug 7, 2009 at 8:00 AM, dmitrey wrote:
> hi all,
> is it possible to overload operator "< ?<"? (And other like this one,
> eg "<= ?<=", "> ?>", ">= ?>=")
> Any URL/example?
> Thank you in advance, D.

That isn't an operator at all. Python does not support compound
comparisons like that. You have to do "a > b and b > c".
> --
> http://mail.python.org/mailman/listinfo/python-list
>


From piet at cs.uu.nl  Fri Aug  7 08:54:31 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Fri, 07 Aug 2009 14:54:31 +0200
Subject: Web page data and urllib2.urlopen
References: <469a6df4-92da-4fd1-bffd-5fefa8cdf3ed@w41g2000yqb.googlegroups.com>
	
	
	
	
	
Message-ID: 

>>>>> Dave Angel  (DA) wrote:

>DA> Piet van Oostrum wrote:
>>>>>>>> 
>>>>>>>> 
>>> 
>DA> But the raw page didn't have any javascript.  So what about that original
>DA> raw page triggered additional stuff to be loaded?
>DA> Is it "user agent", as someone else brought out?  And is there somewhere I
>DA> can read more about that aspect of things?  I've mostly built very static
>DA> html pages, where the server yields the same page to everybody.  And some
>DA> form stuff, where the  user clicks on a 'submit" button to trigger a script
>DA> that's not shown on the URL line.
>>>> 
>>> 
>>> Yes, if you specify a 'normal' web browser as user agent you do get the
>>> Javascript:
>>> 
>>> import urllib2
>>> 
>>> request = urllib2.Request('http://www.marketwatch.com/story/mondays-biggest-gaining-and-declining-stocks-2009-07-27')
>>> request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13')
>>> 
>>> opener = urllib2.build_opener() page = opener.open(request).read()
>>> print page
>>> 
>>> 
>DA> Thanks much.  That's a key I didn't understand.

You can even specify the headers in the Request constructor:


url = 'http://www.marketwatch.com/story/mondays-biggest-gaining-and-declining-stocks-2009-07-27'
hdr = {'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13'}
request = urllib2.Request(url = url, headers = hdr)

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From s.selvamsiva at gmail.com  Fri Aug  7 09:04:01 2009
From: s.selvamsiva at gmail.com (S.Selvam)
Date: Fri, 7 Aug 2009 18:34:01 +0530
Subject: pulldom extracting records from recordset
In-Reply-To: 
References: 
Message-ID: 

On Fri, Aug 7, 2009 at 6:10 PM, S.Selvam  wrote:

> Hi all,
>
> I am using pulldom to handle large xml files.It works fine, but i do not
> know how to store a particular set of  records(as xml) out of the recordset.
> -----------------code---------
> from xml.dom import pulldom
> hamlet_file = open("input_xml/inp_test.xml")
> events = pulldom.parse(hamlet_file)
> for (event, node) in events:
>   if event == pulldom.START_ELEMENT:
>     if node.tagName == "Record":
>      events.expandNode(node)
>      print node  #this does not work as it is a object
> ------------------------------
>
> Whenever the node name is a Record,i process it. I want to store the all
> the nodes meeting my requirement.
>   For eg,i need output as below,
>
>          
>             
>                  hi
>            
>            
>             ---
>            
>         
>
>          
>             
>                  hello
>            .
>            .
> Where input xml might contain 'n' number of Records.
> I have been struggling to figure it out.I would be happy to get a solution
> for this.
>
> --
> Yours,
> S.Selvam
>

Hi all,
   I just found the solution,
         *node.toprettyxml()*
     has done it.



-- 
Yours,
S.Selvam
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From piet at cs.uu.nl  Fri Aug  7 09:09:29 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Fri, 07 Aug 2009 15:09:29 +0200
Subject: how to kill subprocess when Python process is killed?
References: <0feaa2a3-5b73-43e4-9b24-11f157ff6d18@l34g2000vba.googlegroups.com>
Message-ID: 

>>>>> "mark.v.weber at gmail.com"  (M) wrote:

>M> I am writing a Python program that launches a subprocess (using
>M> Popen).
>M> I am reading stdout of the subprocess, doing some filtering, and
>M> writing to
>M> stdout of the main process.

>M> When I kill the main process (cntl-C) the subprocess keeps running.
>M> How do I kill the subprocess too? The subprocess is likey to run a
>M> long time.

>M> Context:
>M> I'm launching only one subprocess at a time, I'm filtering its stdout.
>M> The user might decide to interrupt to try something else; the user
>M> wants the process and all subprocesses to go away in response
>M> to a cntl-C

>M> I'm new to python; solution must be for Python 2.5 (windows) to help
>M> me.

>M> Any help and/or pointers appreciated.

When the parent dies, the child should die when it's writing on the
broken pipe. At least that's how it works in Unix systems. I don't know
about Windows, however.

To let the dying be fast you should make sure that stdout in the child
is unbuffered.

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From thorsten at thorstenkampe.de  Fri Aug  7 09:10:29 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Fri, 7 Aug 2009 15:10:29 +0200
Subject: Is python buffer overflow proof?
References: 
	
	
Message-ID: 

* Neil Hodgson (Tue, 04 Aug 2009 13:32:55 GMT)
> Thorsten Kampe:
> > You cannot create "your own" buffer overflow in Python as you can in 
C 
> > and C++ but your code could still be vulnerable if the underlying Python 
> > construct is written in C.
> 
>    Python's standard library does now include unsafe constructs.

I don't doubt that. If Python contains a buffer overflow vulnerability 
your code will also be susceptible to that. Please read the link I 
provided as an example.

Thorsten


From wuwei23 at gmail.com  Fri Aug  7 09:48:20 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 06:48:20 -0700 (PDT)
Subject: how to overload operator "< <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
Message-ID: 

On Aug 7, 10:50?pm, Benjamin Kaplan  wrote:
> That isn't an operator at all. Python does not support compound
> comparisons like that. You have to do "a > b and b > c".

You know, it costs nothing to open up a python interpreter and check
your certainty:

>>> x = 10
>>> 1 < x < 20
True

This is a _very_ common pattern.

>>> class X(object):
...   def __lt__(self, other):
...     print 'in lt'
...     return True
...   def __gt__(self, other):
...     print 'in gt'
...     return True
...
>>> x = X()
>>> 1 < x < 20
in gt
in lt
True
>>> 20 < x < 1
in gt
in lt
True

dmitrey: Diez' advice was the best you received.


From kdawg44 at gmail.com  Fri Aug  7 09:52:16 2009
From: kdawg44 at gmail.com (Kevin Holleran)
Date: Fri, 7 Aug 2009 09:52:16 -0400
Subject: Changing Remote Registry
Message-ID: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>

Good morning,

I fear the answer to this is that I just cannot do this....

I wrote a python script that goes out to a bunch of remote machines and
queries the registry for some values.  Effectively, there have been some
software upgrades that have been done as the need arose but we need to do
them across the organization now.  There are three, and the script checks
all three and returns the values.  One of these just needs to be a registry
change as it is a client server application that the server was upgraded and
the clients need a change to a registry value to work.

Long story short, I am using _winreg to do this.

hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
value,type = _winreg.QueryValueEx(hKey, item)
if (value == wrongValue):
       _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)


When I do this I receive the error:

_winreg.SetValue WindowsError: [Error 5] Access Denied


I am running this from my machine as a domain admin, connecting to the
remote machine which is also on the domain.
I am connecting to the remote registry with:

keyPath = _winreg.ConnectRegistry(r"\\" +
ipAddress,_winreg.HKEY_LOCAL_MACHINE)


Thanks for any help.

--
Kevin Holleran
Master of Science, Computer Information Systems
Grand Valley State University
Master of Business Administration
Western Michigan University
Completion December 2009
CCNA, ISA, MCSA, MCDST, MCP

"We are what we repeatedly do. Excellence, then, is not an act, but a
habit." - Aristotle

"A man flattened by an opponent can get up again. A man flattened by
conformity stays down for good. " - Thomas J. Watson
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From wuwei23 at gmail.com  Fri Aug  7 09:53:22 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 06:53:22 -0700 (PDT)
Subject: unicode() vs. s.decode()
References: 
	 
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	 
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
Message-ID: <556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>

Thorsten Kampe  wrote:
> Bollocks. No one will even notice whether a code sequence runs 2.7 or
> 5.7 seconds. That's completely artificial benchmarking.

But that's not what you first claimed:

> I don't think any measurable speed increase will be
> noticeable between those two.

But please, keep changing your argument so you don't have to admit you
were wrong.


From stargaming at gmail.com  Fri Aug  7 09:59:45 2009
From: stargaming at gmail.com (Robert Lehmann)
Date: Fri, 7 Aug 2009 13:59:45 +0000 (UTC)
Subject: how to overload operator "< <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
Message-ID: 

On Fri, 07 Aug 2009 08:50:52 -0400, Benjamin Kaplan wrote:

> On Fri, Aug 7, 2009 at 8:00 AM, dmitrey
> wrote:
>> hi all,
>> is it possible to overload operator "< ?<"? (And other like this one,
>> eg "<= ?<=", "> ?>", ">= ?>=")
>> Any URL/example?
>> Thank you in advance, D.
> 
> That isn't an operator at all. Python does not support compound
> comparisons like that. You have to do "a > b and b > c".

Python actually allows you to chain comparison operators, automatically 
unpacking ``a > b > c`` to ``a > b and b > c``::

>>> class C(object):
...   def __lt__(self, other):
...     print self, "LESS-THAN", other
...     return True
... 
>>> a = C(); b = C(); x = C()
>>> a < x < b
<__main__.C object...> LESS-THAN <__main__.C object...>
<__main__.C object...> LESS-THAN <__main__.C object...>
True

>>> x = 42
>>> 40 < x < 50 # between 40 and 50
True
>>> 50 < x < 60 # between 50 and 60
False
>>> 1 == True < 2 == 2.0 < 3 < 4 != 5 > 0 # yikes, unreadable! but legal.
True
>>> # same as: (1 == True) and (True < 2) and (2 == 2.0) ...

HTH,

-- 
Robert "Stargaming" Lehmann



From wuwei23 at gmail.com  Fri Aug  7 10:05:20 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 07:05:20 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
Message-ID: 

Paul Rubin  wrote:
> Such evaluation would only do them good. ?The official docs are full
> of errors and omissions, which is why we have this thread going on
> here in the newsgroup.

And there is a process for reporting and correcting such errors and
omissions, which is what I pointed out in my post.


From Scott.Daniels at Acm.Org  Fri Aug  7 10:08:59 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Fri, 07 Aug 2009 07:08:59 -0700
Subject: Problem in installing PyGreSQL
In-Reply-To: 
References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com>	<7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net>	<20090804084856.b825967a.darcy@druid.net>		<20090804095547.a5274e22.darcy@druid.net>		<7aa29e790908060330x67d900a9rfb4677eaf0eddeb@mail.gmail.com>
	
Message-ID: 

Dennis Lee Bieber wrote:
> On Thu, 6 Aug 2009 16:00:15 +0530, "Thangappan.M"
>  declaimed the following in
> gmane.comp.python.general:
>>   File "./setup.py", line 219, in finalize_options
>>     except (Warning, w):
>> NameError: global name 'w' is not defined
>>
>> What would be the solution?
>> Otherwise can you tell how to install DB-API in debian machine.
> 	Sorry... 1) I run on WinXP; 2) I don't build packages, relying on
> pre-built binaries; 3) I run MySQL.
> 
> 	However, based upon the examples in the Tutorial, that line should
> not have the (, ). A parenthesised (tuple) is suppose to contain a list
> of exceptions, and the parameter to catch the exception specifics has to
> be outside the list.
> 
> 	Best I can suggest is editing that particular line and removing the
> (, ) -- then try rebuilding.
> 
> 	I'll also re-ask: All you are installing is the Python adapter to
> the database. DO YOU HAVE A RUNNING PostgreSQL server that you can
> connect to?

Just to be a bit more explict:
Change file setup.py's line 219 from:
 >>     except (Warning, w):
to either (OK in Python 2.6 and greater):
        except Warning as w:
or (works for Python 2.X):
        except Warning, w:


--Scott David Daniels
Scott.Daniels at Acm.Org


From python at mrabarnett.plus.com  Fri Aug  7 10:11:47 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Fri, 07 Aug 2009 15:11:47 +0100
Subject: Changing Remote Registry
In-Reply-To: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
Message-ID: <4A7C3623.5020702@mrabarnett.plus.com>

Kevin Holleran wrote:
> Good morning,
> 
> I fear the answer to this is that I just cannot do this....
> 
> I wrote a python script that goes out to a bunch of remote machines and 
> queries the registry for some values.  Effectively, there have been some 
> software upgrades that have been done as the need arose but we need to 
> do them across the organization now.  There are three, and the script 
> checks all three and returns the values.  One of these just needs to be 
> a registry change as it is a client server application that the server 
> was upgraded and the clients need a change to a registry value to work.
> 
> Long story short, I am using _winreg to do this.
> 
> hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
> value,type = _winreg.QueryValueEx(hKey, item)
> if (value == wrongValue):
>        _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
>                
> 
> When I do this I receive the error:
> 
> _winreg.SetValue WindowsError: [Error 5] Access Denied
> 
> 
> I am running this from my machine as a domain admin, connecting to the 
> remote machine which is also on the domain.
> I am connecting to the remote registry with:
> 
> keyPath = _winreg.ConnectRegistry(r"\\" + 
> ipAddress,_winreg.HKEY_LOCAL_MACHINE)
> 
> 
> Thanks for any help. 
> 
What is 'ipAddress'? Is it an actual IP address? The documentation says
it should be the computer name.


From invalid at invalid  Fri Aug  7 10:13:33 2009
From: invalid at invalid (Grant Edwards)
Date: Fri, 07 Aug 2009 09:13:33 -0500
Subject: Bug or feature: double strings as one
References: 
Message-ID: 

On 2009-08-07, durumdara  wrote:
> Hi!
>
> I found an interesting thing in Python.
> Today one of my "def"s got wrong result.
>
> When I checked the code I saw that I miss a "," from the list.
>
> l = ['?' '?']
>
> Interesting, that Python handle them as one string.
>
> print ['?' '?']
> ['\xf3\xd3']
>
> I wanna ask that is a bug or is it a feature?

You "wanna"?

> In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
> must concatenate the strings with some sign, like "+" or "||".

In other languages like Ruby, awk, C, C++, etc. adjacent string
constants are concatenated.

-- 
Grant Edwards                   grante             Yow! Is it clean in other
                                  at               dimensions?
                               visi.com            


From deets at nospam.web.de  Fri Aug  7 10:18:55 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Fri, 07 Aug 2009 16:18:55 +0200
Subject: how to overload operator "< <" (a < x < b)?
In-Reply-To: 
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
	
Message-ID: <7e2regF2eqbabU1@mid.uni-berlin.de>

alex23 schrieb:
> On Aug 7, 10:50 pm, Benjamin Kaplan  wrote:
>> That isn't an operator at all. Python does not support compound
>> comparisons like that. You have to do "a > b and b > c".
> 
> You know, it costs nothing to open up a python interpreter and check
> your certainty:
> 
>>>> x = 10
>>>> 1 < x < 20
> True
> 
> This is a _very_ common pattern.
> 
>>>> class X(object):
> ...   def __lt__(self, other):
> ...     print 'in lt'
> ...     return True
> ...   def __gt__(self, other):
> ...     print 'in gt'
> ...     return True
> ...
>>>> x = X()
>>>> 1 < x < 20
> in gt
> in lt
> True
>>>> 20 < x < 1
> in gt
> in lt
> True
> 
> dmitrey: Diez' advice was the best you received.

Not really. I didn't get the chaining, and Peter is right that for that 
there is no real overloading.

Diez


From matt.urry at googlemail.com  Fri Aug  7 10:29:46 2009
From: matt.urry at googlemail.com (ma3mju)
Date: Fri, 7 Aug 2009 07:29:46 -0700 (PDT)
Subject: Processes not exiting
References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com>
	
	<61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com>
	<01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> 
	
	 
	<996e50f5-c126-4ac2-ae8d-458d22a26ee1@v20g2000yqm.googlegroups.com>
Message-ID: <4b564f49-712c-408a-b8bd-9cff5af4a4fe@h30g2000vbr.googlegroups.com>

On 3 Aug, 09:36, ma3mju  wrote:
> On 2 Aug, 21:49, Piet van Oostrum  wrote:
>
> > >>>>> MRAB  (M) wrote:
> > >M> I wonder whether one of the workers is raising an exception, perhaps due
> > >M> to lack of memory, when there are large number of jobs to process.
>
> > But that wouldn't prevent the join. And you would probably get an
> > exception traceback printed.
>
> > I wonder if something fishy is happening in the multiprocessing
> > infrastructure. Or maybe the Fortran code goes wrong because it has no
> > protection against buffer overruns and similar problems, I think.
> > --
> > Piet van Oostrum 
> > URL:http://pietvanoostrum.com[PGP8DAE142BE17999C4]
> > Private email: p... at vanoostrum.org
>
> I don't think it's a memory problem, the reason for the hard and easy
> queue is because for larger examples it uses far more RAM. If I run
> all of workers with harder problems I do begin to run out of RAM and
> end up spending all my time switching in and out of swap so I limit
> the number of harder problems I run at the same time. I've watched it
> run to the end (a very boring couple of hours) and it stays out of my
> swap space and everything appears to be staying in RAM. Just hangs
> after all "poison" has been printed for each process.
>
> The other thing is that I get the message "here" telling me I broke
> out of the loop after seeing the poison pill in the process and I get
> all the things queued listed as output surely if I were to run out of
> memory I wouldn't expect all of the jobs to be listed as output.
>
> I have a serial script that works fine so I know individually for each
> example the fortran code works.
>
> Thanks
>
> Matt

Any ideas for a solution?


From kdawg44 at gmail.com  Fri Aug  7 10:30:37 2009
From: kdawg44 at gmail.com (Kevin Holleran)
Date: Fri, 7 Aug 2009 10:30:37 -0400
Subject: Changing Remote Registry
In-Reply-To: <5caea3690908070730g620e4fe5j90219702c5cf5a90@mail.gmail.com>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
	<4A7C3623.5020702@mrabarnett.plus.com>
	<5caea3690908070730g620e4fe5j90219702c5cf5a90@mail.gmail.com>
Message-ID: <5caea3690908070730i1030e8fdgdb108e88588c043c@mail.gmail.com>

>
>  Good morning,
>>
>> I fear the answer to this is that I just cannot do this....
>>
>> I wrote a python script that goes out to a bunch of remote machines and
>> queries the registry for some values.  Effectively, there have been some
>> software upgrades that have been done as the need arose but we need to do
>> them across the organization now.  There are three, and the script checks
>> all three and returns the values.  One of these just needs to be a registry
>> change as it is a client server application that the server was upgraded and
>> the clients need a change to a registry value to work.
>>
>> Long story short, I am using _winreg to do this.
>>
>> hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
>> value,type = _winreg.QueryValueEx(hKey, item)
>> if (value == wrongValue):
>>       _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
>>
>> When I do this I receive the error:
>>
>> _winreg.SetValue WindowsError: [Error 5] Access Denied
>>
>>
>> I am running this from my machine as a domain admin, connecting to the
>> remote machine which is also on the domain.
>> I am connecting to the remote registry with:
>>
>> keyPath = _winreg.ConnectRegistry(r"\\" +
>> ipAddress,_winreg.HKEY_LOCAL_MACHINE)
>>
>>
>> Thanks for any help.
>>
> What is 'ipAddress'? Is it an actual IP address? The documentation says
> it should be the computer name.
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Thanks for the response.  From my experience that does not matter.  It is an
actual IP address.  I can connect to the registry fine, its just the
writing.  I read that value and other values.  It errors on the
_winreg.KEY_SET_VALUE.  I am wondering if Windows just will not let the
registry be changed remotely in this way or if there is something else I
have to do.

Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From matt.urry at googlemail.com  Fri Aug  7 10:31:48 2009
From: matt.urry at googlemail.com (ma3mju)
Date: Fri, 7 Aug 2009 07:31:48 -0700 (PDT)
Subject: Processes not exiting
References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com>
	
	<61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com>
	<01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> 
	
	 
	<996e50f5-c126-4ac2-ae8d-458d22a26ee1@v20g2000yqm.googlegroups.com>
Message-ID: <1a890fc6-e014-45e7-9eee-2595202b9571@e4g2000vbe.googlegroups.com>

On 3 Aug, 09:36, ma3mju  wrote:
> On 2 Aug, 21:49, Piet van Oostrum  wrote:
>
> > >>>>> MRAB  (M) wrote:
> > >M> I wonder whether one of the workers is raising an exception, perhaps due
> > >M> to lack of memory, when there are large number of jobs to process.
>
> > But that wouldn't prevent the join. And you would probably get an
> > exception traceback printed.
>
> > I wonder if something fishy is happening in the multiprocessing
> > infrastructure. Or maybe the Fortran code goes wrong because it has no
> > protection against buffer overruns and similar problems, I think.
> > --
> > Piet van Oostrum 
> > URL:http://pietvanoostrum.com[PGP8DAE142BE17999C4]
> > Private email: p... at vanoostrum.org
>
> I don't think it's a memory problem, the reason for the hard and easy
> queue is because for larger examples it uses far more RAM. If I run
> all of workers with harder problems I do begin to run out of RAM and
> end up spending all my time switching in and out of swap so I limit
> the number of harder problems I run at the same time. I've watched it
> run to the end (a very boring couple of hours) and it stays out of my
> swap space and everything appears to be staying in RAM. Just hangs
> after all "poison" has been printed for each process.
>
> The other thing is that I get the message "here" telling me I broke
> out of the loop after seeing the poison pill in the process and I get
> all the things queued listed as output surely if I were to run out of
> memory I wouldn't expect all of the jobs to be listed as output.
>
> I have a serial script that works fine so I know individually for each
> example the fortran code works.
>
> Thanks
>
> Matt

Any ideas?


From wuwei23 at gmail.com  Fri Aug  7 10:32:10 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 07:32:10 -0700 (PDT)
Subject: how to overload operator "< <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
	
	<7e2regF2eqbabU1@mid.uni-berlin.de>
Message-ID: <90f46cdb-84cc-47aa-90f4-da0e09472eda@o9g2000prg.googlegroups.com>

"Diez B. Roggisch"  wrote:
> Not really. I didn't get the chaining, and Peter is right that for that
> there is no real overloading.

I'm sorry, I don't really get why overloading lt & gt isn't an answer
to the OP's question... His terminology may not have been correct but
I'm not sure why it's not a sufficient response.

(then again it is a Friday night and I have been out drinking...)


From Scott.Daniels at Acm.Org  Fri Aug  7 10:37:37 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Fri, 07 Aug 2009 07:37:37 -0700
Subject: M2Crypto: How to generate subjectKeyIdentifier /
	authorityKeyIdentifier
In-Reply-To: 
References: 	
	
Message-ID: 

Matthias G?ntert wrote:
>> M2Crypto has a couple of bugs open related that, with potential
>> workarounds that I haven't yet deemed polished enough to checkin, but
>> which might help you out:
>>
>> https://bugzilla.osafoundation.org/show_bug.cgi?id=7530
>> https://bugzilla.osafoundation.org/show_bug.cgi?id=12151
> 
> ... Generating the 'subjectKeyIdentifier':
 > ...
> def get_public_key_fingerprint(self):
> 	h = hashlib.new('sha1')
>     	h.update(self.keypair.as_der())
>     	client_serial = h.hexdigest().upper()
>     	client_serial_hex = ''
>     	for byte in xrange(20):
>     	 client_serial_hex += client_serial[byte*2] + client_serial[byte*2
> +1]
>     		if byte < 19:
>     			client_serial_hex += ':'
>         return client_serial_hex 
> ...

More tersely (code golf?):

     def get_public_key_fingerprint(self):
	digest = hashlib.sha1(self.keypair.as_der()).hexdigest().upper()
	return ':'.join(digest[pos : pos+2] for pos in range(0, 40, 2))

--Scott David Daniels
Scott.Daniels at Acm.Org


--Scott David Daniels
Scott.Daniels at Acm.Org


From python at mrabarnett.plus.com  Fri Aug  7 10:46:56 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Fri, 07 Aug 2009 15:46:56 +0100
Subject: Changing Remote Registry
In-Reply-To: <5caea3690908070730g620e4fe5j90219702c5cf5a90@mail.gmail.com>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>	
	<4A7C3623.5020702@mrabarnett.plus.com>
	<5caea3690908070730g620e4fe5j90219702c5cf5a90@mail.gmail.com>
Message-ID: <4A7C3E60.3060809@mrabarnett.plus.com>

Kevin Holleran wrote:
> 
> On Fri, Aug 7, 2009 at 10:11 AM, MRAB  > wrote:
> 
>     Kevin Holleran wrote:
> 
>         Good morning,
> 
>         I fear the answer to this is that I just cannot do this....
> 
>         I wrote a python script that goes out to a bunch of remote
>         machines and queries the registry for some values.  Effectively,
>         there have been some software upgrades that have been done as
>         the need arose but we need to do them across the organization
>         now.  There are three, and the script checks all three and
>         returns the values.  One of these just needs to be a registry
>         change as it is a client server application that the server was
>         upgraded and the clients need a change to a registry value to work.
> 
>         Long story short, I am using _winreg to do this.
> 
>         hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
>         value,type = _winreg.QueryValueEx(hKey, item)
>         if (value == wrongValue):
>               _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
>            
Hmm. If you're querying with (hKey, item), shouldn't you also be setting
with (hKey, item), not (hKey,'')?

>         When I do this I receive the error:
> 
>         _winreg.SetValue WindowsError: [Error 5] Access Denied
> 
> 
>         I am running this from my machine as a domain admin, connecting
>         to the remote machine which is also on the domain.
>         I am connecting to the remote registry with:
> 
>         keyPath = _winreg.ConnectRegistry(r"\\" +
>         ipAddress,_winreg.HKEY_LOCAL_MACHINE)
> 
> 
>         Thanks for any help.
> 
>     What is 'ipAddress'? Is it an actual IP address? The documentation says
>     it should be the computer name.
>     -- 
>     http://mail.python.org/mailman/listinfo/python-list
> 
> 
> 
> Thanks for the response.  From my experience that does not matter.  It 
> is an actual IP address.  I can connect to the registry fine, its just 
> the writing.  I read that value and other values.  It errors on the 
> _winreg.KEY_SET_VALUE.  I am wondering if Windows just will not let the 
> registry be changed remotely in this way or if there is something else I 
> have to do.
> 


From python at mrabarnett.plus.com  Fri Aug  7 11:02:09 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Fri, 07 Aug 2009 16:02:09 +0100
Subject: Processes not exiting
In-Reply-To: <4b564f49-712c-408a-b8bd-9cff5af4a4fe@h30g2000vbr.googlegroups.com>
References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com>		<61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com>	<01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com>
		
	<996e50f5-c126-4ac2-ae8d-458d22a26ee1@v20g2000yqm.googlegroups.com>
	<4b564f49-712c-408a-b8bd-9cff5af4a4fe@h30g2000vbr.googlegroups.com>
Message-ID: <4A7C41F1.3080303@mrabarnett.plus.com>

ma3mju wrote:
> On 3 Aug, 09:36, ma3mju  wrote:
>> On 2 Aug, 21:49, Piet van Oostrum  wrote:
>>
>>>>>>>> MRAB  (M) wrote:
>>>> M> I wonder whether one of the workers is raising an exception, perhaps due
>>>> M> to lack of memory, when there are large number of jobs to process.
>>> But that wouldn't prevent the join. And you would probably get an
>>> exception traceback printed.
>>> I wonder if something fishy is happening in the multiprocessing
>>> infrastructure. Or maybe the Fortran code goes wrong because it has no
>>> protection against buffer overruns and similar problems, I think.
>>> --
>>> Piet van Oostrum 
>>> URL:http://pietvanoostrum.com[PGP8DAE142BE17999C4]
>>> Private email: p... at vanoostrum.org
>> I don't think it's a memory problem, the reason for the hard and easy
>> queue is because for larger examples it uses far more RAM. If I run
>> all of workers with harder problems I do begin to run out of RAM and
>> end up spending all my time switching in and out of swap so I limit
>> the number of harder problems I run at the same time. I've watched it
>> run to the end (a very boring couple of hours) and it stays out of my
>> swap space and everything appears to be staying in RAM. Just hangs
>> after all "poison" has been printed for each process.
>>
>> The other thing is that I get the message "here" telling me I broke
>> out of the loop after seeing the poison pill in the process and I get
>> all the things queued listed as output surely if I were to run out of
>> memory I wouldn't expect all of the jobs to be listed as output.
>>
>> I have a serial script that works fine so I know individually for each
>> example the fortran code works.
>>
>> Thanks
>>
>> Matt
> 
> Any ideas for a solution?

A workaround is to do them in small batches.

You could put each job in a queue with a flag to say whether it's hard 
or easy, then:

     while have more jobs:
         move up to BATCH_SIZE jobs into worker queues
         create and start workers
         wait for workers to finish
         discard workers


From exarkun at twistedmatrix.com  Fri Aug  7 11:02:13 2009
From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com)
Date: Fri, 07 Aug 2009 15:02:13 -0000
Subject: how to overload operator "< <" (a < x < b)?
In-Reply-To: 
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
Message-ID: <20090807150213.13038.275088682.divmod.xquotient.2@localhost.localdomain>

On 12:50 pm, benjamin.kaplan at case.edu wrote:
>On Fri, Aug 7, 2009 at 8:00 AM, dmitrey 
>wrote:
>>hi all,
>>is it possible to overload operator "< ?<"? (And other like this one,
>>eg "<= ?<=", "> ?>", ">= ?>=")
>>Any URL/example?
>>Thank you in advance, D.
>
>That isn't an operator at all. Python does not support compound
>comparisons like that. You have to do "a > b and b > c".

That's partially correct.  There is no "compound less than operator", or
whatever you want to call that.  However, Python does support "compound
comparisons" like that:

  >>> 1 < 2 < 3
  True
  >>> 1 < 3 < 2
  False
  >>> 1 == 2 == 3
  False
  >>> 2 == 2 == 2
  True
  >>>
Jean-Paul


From Scott.Daniels at Acm.Org  Fri Aug  7 11:04:22 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Fri, 07 Aug 2009 08:04:22 -0700
Subject: how to overload operator "< <" (a < x < b)?
In-Reply-To: 
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
Message-ID: 

Benjamin Kaplan wrote:
> .... Python does not support compound
> comparisons like that. You have to do "a > b and b > c".

Funny, my python does.  This has been around a long time.
I am not certain whether 1.5.2 did it, but "chained comparisons"
have been around for a long time.

     >>> 'a'< 'd' <'z'
     True
     >>> 'a'< 'D' <'z'
     False

--Scott David Daniels
Scott.Daniels at Acm.Org


From kdawg44 at gmail.com  Fri Aug  7 11:05:01 2009
From: kdawg44 at gmail.com (Kevin Holleran)
Date: Fri, 7 Aug 2009 11:05:01 -0400
Subject: Changing Remote Registry
In-Reply-To: <4A7C3E60.3060809@mrabarnett.plus.com>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
	<4A7C3623.5020702@mrabarnett.plus.com>
	<5caea3690908070730g620e4fe5j90219702c5cf5a90@mail.gmail.com>
	<4A7C3E60.3060809@mrabarnett.plus.com>
Message-ID: <5caea3690908070805q3ff8f208r37a50a670c9f1bc9@mail.gmail.com>

 On Fri, Aug 7, 2009 at 10:46 AM, MRAB  wrote:

> Kevin Holleran wrote:
>
>>
>> On Fri, Aug 7, 2009 at 10:11 AM, MRAB > python at mrabarnett.plus.com>> wrote:
>>
>>    Kevin Holleran wrote:
>>
>>        Good morning,
>>
>>        I fear the answer to this is that I just cannot do this....
>>
>>        I wrote a python script that goes out to a bunch of remote
>>        machines and queries the registry for some values.  Effectively,
>>        there have been some software upgrades that have been done as
>>        the need arose but we need to do them across the organization
>>        now.  There are three, and the script checks all three and
>>        returns the values.  One of these just needs to be a registry
>>        change as it is a client server application that the server was
>>        upgraded and the clients need a change to a registry value to work.
>>
>>        Long story short, I am using _winreg to do this.
>>
>>        hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
>>        value,type = _winreg.QueryValueEx(hKey, item)
>>        if (value == wrongValue):
>>              _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
>>
>>
> Hmm. If you're querying with (hKey, item), shouldn't you also be setting
> with (hKey, item), not (hKey,'')?
>
>
>         When I do this I receive the error:
>>
>>        _winreg.SetValue WindowsError: [Error 5] Access Denied
>>
>>
>>        I am running this from my machine as a domain admin, connecting
>>        to the remote machine which is also on the domain.
>>        I am connecting to the remote registry with:
>>
>>        keyPath = _winreg.ConnectRegistry(r"\\" +
>>        ipAddress,_winreg.HKEY_LOCAL_MACHINE)
>>
>>
>>        Thanks for any help.
>>
>>    What is 'ipAddress'? Is it an actual IP address? The documentation says
>>    it should be the computer name.
>>    --    http://mail.python.org/mailman/listinfo/python-list
>>
>>
>>
>> Thanks for the response.  From my experience that does not matter.  It is
>> an actual IP address.  I can connect to the registry fine, its just the
>> writing.  I read that value and other values.  It errors on the
>> _winreg.KEY_SET_VALUE.  I am wondering if Windows just will not let the
>> registry be changed remotely in this way or if there is something else I
>> have to do.
>>
>>  --
> http://mail.python.org/mailman/listinfo/python-list
>

Sorry, that line is correct, I was removing specific information relevant to
our infrastructure.  That is the valuename.  The error I am getting is:


Traceback (most recent call last):
  File "script.py", line 53, in 
    value,type = _winreg.QueryValueEx(hKey,item)
WindowsError: [Error 5] Access is denied

But the real error is here I believe:

       hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)

When I just do a:

       hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_READ)

I receive no errors.

Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From thorsten at thorstenkampe.de  Fri Aug  7 11:13:07 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Fri, 7 Aug 2009 17:13:07 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
Message-ID: 

* alex23 (Fri, 7 Aug 2009 06:53:22 -0700 (PDT))
> Thorsten Kampe  wrote:
> > Bollocks. No one will even notice whether a code sequence runs 2.7 or
> > 5.7 seconds. That's completely artificial benchmarking.
> 
> But that's not what you first claimed:
> 
> > I don't think any measurable speed increase will be
> > noticeable between those two.
> 
> But please, keep changing your argument so you don't have to admit you
> were wrong.

Bollocks. Please note the word "noticeable". "noticeable" as in 
recognisable as in reasonably experiencable or as in whatever.

One guy claims he has times between 2.7 and 5.7 seconds when 
benchmarking more or less randomly generated "one million different 
lines". That *is* *exactly* nothing.

Another guy claims he gets times between 2.9 and 6.2 seconds when 
running decode/unicode in various manifestations over "18 million 
words" (or is it 600 million?) and says "the differences are pretty 
significant". I think I don't have to comment on that.

If you increase the number of loops to one million or one billion or 
whatever even the slightest completely negligible difference will occur. 
The same thing will happen if you just increase the corpus of words to a 
million, trillion or whatever. The performance implications of that are 
exactly none.

Thorsten


From manu3d at gmail.com  Fri Aug  7 11:15:08 2009
From: manu3d at gmail.com (Emanuele D'Arrigo)
Date: Fri, 7 Aug 2009 08:15:08 -0700 (PDT)
Subject: Executing untrusted code
Message-ID: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com>

Greetings everybody,

I've been reading and mulling about python and security, specifically
in terms of executing code that may or may not be trustworthy. I
understand that libraries such as Rexec and Bastion are now deprecated
because they have known vulnerabilities that may be exploited to
circumvent the restrictions imposed.

So, am I right in understanding that is not possible to execute a
piece of code in a way that limits the objects and attributes that it
can access or that limits its access to file system and sockets? Are
there best practices to at least minimize some of the risks associated
with untrusted code execution?

And whatever happened to this:

http://sayspy.blogspot.com/2007/05/i-have-finished-securing-python.html

seemed to be a step forward in the right direction!

Manu


From gert.cuykens at gmail.com  Fri Aug  7 11:23:52 2009
From: gert.cuykens at gmail.com (gert)
Date: Fri, 7 Aug 2009 08:23:52 -0700 (PDT)
Subject: HTTP_RANGE
Message-ID: <72a8588f-ea26-489a-936d-29462e57c917@p28g2000vbn.googlegroups.com>

def application(environ, response):
    range=environ.get('HTTP_RANGE','bytes=0-').replace
('bytes=','').split(',')
    offset=[]
    for r in range: offset.append(r.split('-'))
    out='0123456789'
    lengthF=len(out)
    lengthC=str(lengthF-int(offset[0][0]))
    bitS=int(offset[0][0])
    bitE=lengthF-1
    bytes='bytes '+str(bitS)+'-'+str(bitE)+'/'+str(lengthF)
    response('200 OK', [('Content-Length', lengthC), ('Content-
Range',bytes)])
    return [out[bitS:]]

C:\Users\gert\Desktop>curl http://127.0.0.1/appwsgi/wsgi/download.wsgi
-v
* About to connect() to 127.0.0.1 port 80 (#0)
*   Trying 127.0.0.1... connected
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)
> GET /appwsgi/wsgi/download.wsgi HTTP/1.1
> User-Agent: curl/7.19.4 (amd64-pc-win32) libcurl/7.19.4 OpenSSL/0.9.8j zlib/1.2.3
> Host: 127.0.0.1
> Accept: */*

* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Date: Thu, 06 Aug 2009 19:05:09 GMT
< Server: WSGIServer/0.1 Python/3.1
< Content-Length: 10
< Content-Range: bytes 0-9/10
<
0123456789* Closing connection #0

C:\Users\gert\Desktop>curl -C 2 http://127.0.0.1/appwsgi/wsgi/download.wsgi
-v
* About to connect() to 127.0.0.1 port 80 (#0)
*   Trying 127.0.0.1... connected
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)
> GET /appwsgi/wsgi/download.wsgi HTTP/1.1
> Range: bytes=2-
> User-Agent: curl/7.19.4 (amd64-pc-win32) libcurl/7.19.4 OpenSSL/0.9.8j zlib/1.2.3
> Host: 127.0.0.1
> Accept: */*

* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Date: Thu, 06 Aug 2009 19:06:52 GMT
< Server: WSGIServer/0.1 Python/3.1
< Content-Length: 8
< Content-Range: bytes 2-9/10
<
23456789* Closing connection #0

Why does it use HTTP 1.0 ? Can I force it to use HTTP 1.1 ?


From python at mrabarnett.plus.com  Fri Aug  7 11:28:24 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Fri, 07 Aug 2009 16:28:24 +0100
Subject: Changing Remote Registry
In-Reply-To: <5caea3690908070805q3ff8f208r37a50a670c9f1bc9@mail.gmail.com>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>	<4A7C3623.5020702@mrabarnett.plus.com>	<5caea3690908070730g620e4fe5j90219702c5cf5a90@mail.gmail.com>	<4A7C3E60.3060809@mrabarnett.plus.com>
	<5caea3690908070805q3ff8f208r37a50a670c9f1bc9@mail.gmail.com>
Message-ID: <4A7C4818.10709@mrabarnett.plus.com>

Kevin Holleran wrote:
> On Fri, Aug 7, 2009 at 10:46 AM, MRAB  > wrote:
> 
>     Kevin Holleran wrote:
> 
> 
>         On Fri, Aug 7, 2009 at 10:11 AM, MRAB
>         
>                  >> wrote:
> 
>            Kevin Holleran wrote:
> 
>                Good morning,
> 
>                I fear the answer to this is that I just cannot do this....
> 
>                I wrote a python script that goes out to a bunch of remote
>                machines and queries the registry for some values.
>          Effectively,
>                there have been some software upgrades that have been done as
>                the need arose but we need to do them across the organization
>                now.  There are three, and the script checks all three and
>                returns the values.  One of these just needs to be a registry
>                change as it is a client server application that the
>         server was
>                upgraded and the clients need a change to a registry
>         value to work.
> 
>                Long story short, I am using _winreg to do this.
> 
>                hKey = _winreg.OpenKey (keyPath, path, 0,
>         _winreg.KEY_SET_VALUE)
>                value,type = _winreg.QueryValueEx(hKey, item)
>                if (value == wrongValue):
>                      _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
>                  
> 
>     Hmm. If you're querying with (hKey, item), shouldn't you also be setting
>     with (hKey, item), not (hKey,'')?
> 
> 
>                When I do this I receive the error:
> 
>                _winreg.SetValue WindowsError: [Error 5] Access Denied
> 
> 
>                I am running this from my machine as a domain admin,
>         connecting
>                to the remote machine which is also on the domain.
>                I am connecting to the remote registry with:
> 
>                keyPath = _winreg.ConnectRegistry(r"\\" +
>                ipAddress,_winreg.HKEY_LOCAL_MACHINE)
> 
> 
>                Thanks for any help.
> 
>            What is 'ipAddress'? Is it an actual IP address? The
>         documentation says
>            it should be the computer name.
>            --    http://mail.python.org/mailman/listinfo/python-list
> 
> 
> 
>         Thanks for the response.  From my experience that does not
>         matter.  It is an actual IP address.  I can connect to the
>         registry fine, its just the writing.  I read that value and
>         other values.  It errors on the _winreg.KEY_SET_VALUE.  I am
>         wondering if Windows just will not let the registry be changed
>         remotely in this way or if there is something else I have to do.
> 
>     -- 
>     http://mail.python.org/mailman/listinfo/python-list
> 
> 
> Sorry, that line is correct, I was removing specific information 
> relevant to our infrastructure.  That is the valuename.  The error I am 
> getting is:
> 
> 
> Traceback (most recent call last):
>   File "script.py", line 53, in 
>     value,type = _winreg.QueryValueEx(hKey,item)
> WindowsError: [Error 5] Access is denied
> 
> But the real error is here I believe:
> 
>        hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
> 
> When I just do a:
> 
>        hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_READ)
> 
> I receive no errors.
> 
> Thanks.
> 
If it's complaining _as soon as_ you request write permission then I'd
say that was a permissions problem, not an error! :-)


From mark.v.weber at gmail.com  Fri Aug  7 11:51:48 2009
From: mark.v.weber at gmail.com (mark.v.weber at gmail.com)
Date: Fri, 7 Aug 2009 08:51:48 -0700 (PDT)
Subject: how to kill subprocess when Python process is killed?
References: <0feaa2a3-5b73-43e4-9b24-11f157ff6d18@l34g2000vba.googlegroups.com>
	<3733148e-c03d-42ef-88f7-855c516e6564@d9g2000prh.googlegroups.com>
Message-ID: <63d1512c-4018-467d-a439-25dd76975e5e@g19g2000vbi.googlegroups.com>

On Aug 7, 12:57?am, alex23  wrote:
> On Aug 7, 3:42?pm, "mark.v.we... at gmail.com" 
> wrote:
>
> > When I kill the main process (cntl-C) the subprocess keeps running.
> > How do I kill the subprocess too? The subprocess is likely to run a
> > long time.
>
> You can register functions to run when the Python process ends by
> using the atexit[1] module.
>
> The following has been tested & works under Python 2.6 on Windows XP:
>
> ? ? import atexit
>
> ? ? def cleanup():
> ? ? ? ? print 'stop thesubprocessin here'
>
> ? ? atexit.register(cleanup)
>
> ? ? while True:
> ? ? ? ? pass
>
> [1]:http://docs.python.org/library/atexit.html

Works perfectly. Thanks!


From kee at kagi.com  Fri Aug  7 12:03:37 2009
From: kee at kagi.com (Kee Nethery)
Date: Fri, 7 Aug 2009 09:03:37 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
Message-ID: <690C5186-1666-4EF4-B223-AF8880B0C21C@kagi.com>

During all this conversation there was a ticket posted in the bug  
tracking system with the suggestion of each section in the official  
docs linking to a fixed wiki page that can contain user contributions.

The ticket has been closed because this addition to the official docs  
is already in the works.

So ... to everyone who thinks there needs to be a place for user  
comments to augment the official docs, it's supposed to happen. Same  
with corrections to the docs, there is supposed to be a place per  
section where people can post corrections to the docs.

I'm looking forward to the acceleration of improvements to the  
official docs based upon easy to provide user feedback. Glad to see  
that the bug tracking system is going to not be the primary means for  
documentation changes.

Kee



From Scott.Daniels at Acm.Org  Fri Aug  7 12:05:00 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Fri, 07 Aug 2009 09:05:00 -0700
Subject: Bug or feature: double strings as one
In-Reply-To: 
References: 
	
Message-ID: <5Y2dnfnYAdsl0-HXnZ2dnUVZ_j9i4p2d@pdx.net>

Grant Edwards wrote:
> On 2009-08-07, durumdara  wrote:
>> In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
>> must concatenate the strings with some sign, like "+" or "||".
> 
> In other languages like Ruby, awk, C, C++, etc. adjacent string
> constants are concatenated.

I must learn this "etc." language, I hear it mentioned all the time :-)

--Scott David Daniels
Scott.Daniels at Acm.Org



From rickbking at comcast.net  Fri Aug  7 12:19:21 2009
From: rickbking at comcast.net (Rick King)
Date: Fri, 07 Aug 2009 12:19:21 -0400
Subject: py2exe-created exe results in "application failed to initialize"
Message-ID: <4A7C5409.5020807@comcast.net>

Hi everyone,
I want to package up an application into an exe using py2exe but the 
result produces the dreaded

"application failed to initialize 0x....142" error.

I'm using wxPython and basically just took the sample for wxpython GUI 
that came with py2exe and changed the name. My setup is python 2.6, 
wxpython 2.8. My setup.py looks like the following.

from distutils.core import setup
import py2exe
import sys

class Target:
    def __init__(self, **kw):
        self.__dict__.update(kw)
        # for the versioninfo resources
        self.version = "0.1"
        self.company_name = "OWDC"
        self.copyright = "no copyright"
        self.name = "FileTool"

manifest_template = '''

.... etc.
'''

RT_MANIFEST = 24

FileTool = Target(
    description = "FileTool",
    script = "filetoolGUI.py",
    other_resources = [(RT_MANIFEST, 1, manifest_template % 
dict(prog="FileTool"))],
    dest_base = "FileTool")

setup(
    options = {"py2exe": {"compressed": 1,"optimize": 2,"ascii": 
1,"bundle_files": 1}},
    zipfile = None,
    windows = [FileTool],
    )

Any help will be greatly appreciated!

Rick King
Southfield MI USA



From bbarbero at inescporto.pt  Fri Aug  7 12:19:28 2009
From: bbarbero at inescporto.pt (bbarbero at inescporto.pt)
Date: Fri, 07 Aug 2009 18:19:28 +0200
Subject: Extracting matrix from a text file
Message-ID: <20090807181928.10784usha588i2a8@horde.inescporto.pt>

Hello to all!!

I am new in python, and I am running it on Mac with Smultron editor. I  
need to read a textfile that includes numbers (in a matrix form),  
indexes, and strings, like this:

Marsyas-kea distance matrix for MIREX 2007 Audio Similarity Exchange
Q/R	1	2	3	4	5
1	0	4.54592	4.36685	5.29463	3.85728
2	4.54592	0	3.97667	5.02151	4.64284
3	4.36685	3.97667	0	4.98743	4.83683
4	5.29463	5.02151	4.98743	0	6.04393
5	3.85728	4.64284	4.83683	6.04393	0



So I just want to keep the matrix in the "middle" for math computations.

	0       4.54592	4.36685	5.29463	3.85728
	4.54592	0	3.97667	5.02151	4.64284
	4.36685	3.97667	0	4.98743	4.83683
	5.29463	5.02151	4.98743	0	6.04393
	3.85728	4.64284	4.83683	6.04393	0

I've seen and tried a lot of ways, like split or isinstance.. but  
never get the wanted result.... does anyone have an idea, or hint?  
Thank you once more for your help!

Best Regards,
Bea

----------------------------------------------------------------
This message was sent using IMP, the Internet Messaging Program.


From stefan_ml at behnel.de  Fri Aug  7 12:31:27 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Fri, 07 Aug 2009 18:31:27 +0200
Subject: Cython + setuptools not working with .pyx,only with .c-files
In-Reply-To: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
References: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
Message-ID: <4a7c56e0$0$31871$9b4e6d93@newsspool3.arcor-online.net>

Diez B. Roggisch wrote:
> I'm trying to build a Cython-extension as Egg.
> 
> However, this doesn't work - I can either use distutils to build the
> extension, creating a myextension.c-file on the way.
> 
> If that's there, I can use setuptools to build the egg.
> 
> But when I remove the .c-file, the .pyx-file isn't used to re-generate it.

setuptools monkeypatch into distutils to support Pyrex if it's installed,
but most non-bleeding-edge versions do not know about Cython and thus break
the Cython distutils support when Pyrex isn't there as well.

What helps is to put a fake Pyrex installation into your sys.path, like

http://codespeak.net/svn/lxml/trunk/fake_pyrex/

as done at the top of

http://codespeak.net/svn/lxml/trunk/setup.py

I haven't tried if newer setuptools versions have been fixed yet.

Stefan


From sandorl at gmail.com  Fri Aug  7 12:32:53 2009
From: sandorl at gmail.com (=?UTF-8?B?TMOhc3psw7MgU8OhbmRvcg==?=)
Date: Fri, 7 Aug 2009 12:32:53 -0400
Subject: question: why isn't a byte of a hash more uniform? how could I 
	improve my code to cure that?
Message-ID: 

Hi all,
I am a Python novice, and right now I would be happy to simply get my job
done with it, but I could appreciate some thoughts on the issue below.

I need to assign one of four numbers to names in a list. The assignment
should be pseudo-random: no pattern whatsoever, but deterministic,
reproducible, and close to uniform. My understanding was that hash functions
would do the job. As I only needed 2 bits of treatment, I picked a byte of
the hashes generated, and even taken mod 4 of it. See the code below.

After I have written a short Python script that hashes my textfile line by
line and collects the numbers next to the original, I checked what I got.
Instead of getting around 25% in each treatment, the range is 17.8%-31.3%. I
understand that the pseudo-randomness means that the treatments should not
be neat and symmetric. Still, this variation is unacceptable for my purpose.
My understanding was that good hash functions generate numbers that look
completely random, and picking only a byte should not change that. I thought
the promise was also to get close to uniformity:
http://en.wikipedia.org/wiki/Hash_function#Uniformity. I tried all the
hashes in the hashlib module, and picked bytes from the beginning and the
end of the hashes, but treatments never were close to uniform (curiously,
always the last treatment seems to be too rare).

Maybe it is an obvious CS puzzle, I'm looking forward to standing corrected.

Thanks!

Laszlo

The script:

#! /usr/bin/python

f = open('names.txt', 'r')
g = open('nameshashed.txt', 'a')

import hashlib

for line in f:
    line = line.rstrip()
    h = str(hashlib.sha512(line).hexdigest())
    s = line + ',' + str(ord(h[64])%4) + '\n'
    g.write(s),
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From wuwei23 at gmail.com  Fri Aug  7 12:39:15 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 09:39:15 -0700 (PDT)
Subject: Extracting matrix from a text file
References: 
Message-ID: 

On Aug 8, 2:19?am, bbarb... at inescporto.pt wrote:
> I am new in python, and I am running it on Mac with Smultron editor. I ?
> need to read a textfile that includes numbers (in a matrix form), ?
> indexes, and strings, like this:
>
> Marsyas-kea distance matrix for MIREX 2007 Audio Similarity Exchange
> Q/R ? ? 1 ? ? ? 2 ? ? ? 3 ? ? ? 4 ? ? ? 5
> 1 ? ? ? 0 ? ? ? 4.54592 4.36685 5.29463 3.85728
> 2 ? ? ? 4.54592 0 ? ? ? 3.97667 5.02151 4.64284
> 3 ? ? ? 4.36685 3.97667 0 ? ? ? 4.98743 4.83683
> 4 ? ? ? 5.29463 5.02151 4.98743 0 ? ? ? 6.04393
> 5 ? ? ? 3.85728 4.64284 4.83683 6.04393 0
>
> So I just want to keep the matrix in the "middle" for math computations.
>
> ? ? ? ? 0 ? ? ? 4.54592 4.36685 5.29463 3.85728
> ? ? ? ? 4.54592 0 ? ? ? 3.97667 5.02151 4.64284
> ? ? ? ? 4.36685 3.97667 0 ? ? ? 4.98743 4.83683
> ? ? ? ? 5.29463 5.02151 4.98743 0 ? ? ? 6.04393
> ? ? ? ? 3.85728 4.64284 4.83683 6.04393 0
>
> I've seen and tried a lot of ways, like split or isinstance.. but ?
> never get the wanted result.... does anyone have an idea, or hint? ?
> Thank you once more for your help!


isinstance? Are you just randomly trying functions hoping they'll
work? :)

Untested code follows:

with open(,'r') as textfile:
    header = textfile.next() # skip the header
    col_0_size = 8 # cos it does
    for line in textfile:
        newline = line[col_0_size:] # strip off the index column
        columns = newline.split(' ') # will give you a tuple of
strings
        one, two, three, four, five = map(float, columns) # turns the
strings into floats
        # do whatever you want to those values here

This is fairly standard text handling with Python, if you haven't
already you should really work through the Python tutorial[1],
especially the section on strings [2], and if you have, perhaps David
Mertz's 'Text Processing in Python'[3] may be of use.

1: http://docs.python.org/tutorial/
2: http://docs.python.org/tutorial/introduction.html#strings
3: http://gnosis.cx/TPiP/


From no.email at please.post  Fri Aug  7 12:50:12 2009
From: no.email at please.post (kj)
Date: Fri, 7 Aug 2009 16:50:12 +0000 (UTC)
Subject: PEP 8 exegetics: conditional imports?
Message-ID: 



Conditional imports make sense to me, as in the following example:

def foobar(filename):
    if os.path.splitext(filename)[1] == '.gz':
        import gzip
        f = gzip.open(filename)
    else:
        f = file(filename)
    # etc.

And yet, quoth PEP 8:

    - Imports are always put at the top of the file, just after any module
      comments and docstrings, and before module globals and constants.

...which seems to condemn conditional imports unequivocally. 

Then again, the PEP 8 scriptures do not explicitly mention conditional
imports at all, as far as I can tell, which leaves open the
possibility that they are still righteous. 

In fact, venerable passages in the Python standard library source
code, if properly interpreted, can be seen to carry out conditional
imports, such as this fragment recovered from random.py:

        if a is None:
            try:
                a = long(_hexlify(_urandom(16)), 16)
            except NotImplementedError:
                import time
                a = long(time.time() * 256) # use fractional seconds

Or even more clearly, this one from test/pystone.py:

if __name__ == '__main__':
    import sys



I seek the wisdom of the elders.  Is there a consensus on the matter
of conditional imports?  Are they righteous?  Or are they the way
of the wicked?

kynn


From invalid at invalid  Fri Aug  7 13:00:47 2009
From: invalid at invalid (Grant Edwards)
Date: Fri, 07 Aug 2009 12:00:47 -0500
Subject: Bug or feature: double strings as one
References: 
	
	<5Y2dnfnYAdsl0-HXnZ2dnUVZ_j9i4p2d@pdx.net>
Message-ID: 

On 2009-08-07, Scott David Daniels  wrote:
> Grant Edwards wrote:
>> On 2009-08-07, durumdara  wrote:
>>> In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
>>> must concatenate the strings with some sign, like "+" or "||".
>> 
>> In other languages like Ruby, awk, C, C++, etc. adjacent string
>> constants are concatenated.
>
> I must learn this "etc." language, I hear it mentioned all the time :-)

Definitely.  Not only does it have _all_ the features, it even
manages to simultaneously have several mutually-exclusive
features.

-- 
Grant Edwards                   grante             Yow! I'm meditating on
                                  at               the FORMALDEHYDE and the
                               visi.com            ASBESTOS leaking into my
                                                   PERSONAL SPACE!!


From python.list at tim.thechases.com  Fri Aug  7 13:19:47 2009
From: python.list at tim.thechases.com (Tim Chase)
Date: Fri, 07 Aug 2009 12:19:47 -0500
Subject: question: why isn't a byte of a hash more uniform? how could
	I    improve my code to cure that?
In-Reply-To: 
References: 
Message-ID: <4A7C6233.4050105@tim.thechases.com>

> After I have written a short Python script that hashes my textfile line by
> line and collects the numbers next to the original, I checked what I got.
> Instead of getting around 25% in each treatment, the range is 17.8%-31.3%.

That sounds suspiciously like 25% with a +/- 7% fluctuation one 
might expect to see from non-random source data.

Remember that your outputs are driven purely by your inputs in a 
deterministic fashion -- if your inputs are purely random, then 
your outputs should more closely match your expected bin'ing.  If 
your inputs aren't random, you get a taste of your own medicine 
("my file has just the number 42 on every line...why isn't my 
output random?").  And randomness-of-hash-output is a red herring 
since hashing is *not* random.

Your input is also finite -- an aspect which leaves you a far cry 
from the full hash-space.  If an md5 has 32 bytes (256 bits) of 
data, your input would have to cover 2**256 possible inputs to 
see the full profile of your outputs.  That's a lot of input :)

-tkc






From python at mrabarnett.plus.com  Fri Aug  7 13:29:23 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Fri, 07 Aug 2009 18:29:23 +0100
Subject: Extracting matrix from a text file
In-Reply-To: 
References: 
	
Message-ID: <4A7C6473.8050602@mrabarnett.plus.com>

alex23 wrote:
> On Aug 8, 2:19 am, bbarb... at inescporto.pt wrote:
>> I am new in python, and I am running it on Mac with Smultron editor. I  
>> need to read a textfile that includes numbers (in a matrix form),  
>> indexes, and strings, like this:
>>
>> Marsyas-kea distance matrix for MIREX 2007 Audio Similarity Exchange
>> Q/R     1       2       3       4       5
>> 1       0       4.54592 4.36685 5.29463 3.85728
>> 2       4.54592 0       3.97667 5.02151 4.64284
>> 3       4.36685 3.97667 0       4.98743 4.83683
>> 4       5.29463 5.02151 4.98743 0       6.04393
>> 5       3.85728 4.64284 4.83683 6.04393 0
>>
>> So I just want to keep the matrix in the "middle" for math computations.
>>
>>         0       4.54592 4.36685 5.29463 3.85728
>>         4.54592 0       3.97667 5.02151 4.64284
>>         4.36685 3.97667 0       4.98743 4.83683
>>         5.29463 5.02151 4.98743 0       6.04393
>>         3.85728 4.64284 4.83683 6.04393 0
>>
>> I've seen and tried a lot of ways, like split or isinstance.. but  
>> never get the wanted result.... does anyone have an idea, or hint?  
>> Thank you once more for your help!
> 
> 
> isinstance? Are you just randomly trying functions hoping they'll
> work? :)
> 
> Untested code follows:
> 
> with open(,'r') as textfile:
>     header = textfile.next() # skip the header
>     col_0_size = 8 # cos it does
>     for line in textfile:
>         newline = line[col_0_size:] # strip off the index column
>         columns = newline.split(' ') # will give you a tuple of
> strings
[snip]
Or:
         columns = line.split(' ')[1 : ]


From wuwei23 at gmail.com  Fri Aug  7 13:29:55 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 10:29:55 -0700 (PDT)
Subject: PEP 8 exegetics: conditional imports?
References: 
Message-ID: <3d84c940-faea-4b3b-af3c-73059b3eaf96@v23g2000pro.googlegroups.com>

On Aug 8, 2:50?am, kj  wrote:
> Conditional imports make sense to me, as in the following example[...]
> And yet, quoth PEP 8:
>
> ? ? - Imports are always put at the top of the file, just after any module
> ? ? ? comments and docstrings, and before module globals and constants.
>
> ...which seems to condemn conditional imports unequivocally.

Really? It doesn't mention conditionals at all, it simply says that
imports should occur before globals and constants, not before
conditions. If you want to put conditions around your imports, then
that's the place to do it.

> I seek the wisdom of the elders. ?Is there a consensus on the matter
> of conditional imports? ?Are they righteous? ?Or are they the way
> of the wicked?

Bear in mind that PEP 8 primarily applies to submissions to the
standard library, in order to provide a standard that aids in
understanding them. If a module is used throughout a body of code,
it's helpful to list these modules at the top of the code, for
clarity. However, if a module is only required under exceptional
conditions, you'll often see it imported at the point which it's
required: as the import occurs near the code, this mitigates the
initial requirement somewhat, and reduces the startup time of the
code.

The style guide also states:
    But most importantly: know when to be inconsistent -- sometimes
the style
    guide just doesn't apply.  When in doubt, use your best judgment.
Look
    at other examples and decide what looks best.  And don't hesitate
to ask!

Checks around imports are often used to provide cross-version
compatibility. Embedded imports are often used when the code relying
on them is barely used. These are all very common uses.

pystone is a good example. Nothing within the modular code of pystone
requires sys, it's only imported if the module is executed, primarily
for error reporting & argument handling.


From no.email at please.post  Fri Aug  7 13:35:28 2009
From: no.email at please.post (kj)
Date: Fri, 7 Aug 2009 17:35:28 +0000 (UTC)
Subject: Bug or feature: double strings as one
References: 
	
Message-ID: 

In  Peter Otten <__peter__ at web.de> writes:

>durumdara wrote:

>> I found an interesting thing in Python.
>> Today one of my "def"s got wrong result.
>> 
>> When I checked the code I saw that I miss a "," from the list.
>> 
>> l = ['??' '??']
>> 
>> Interesting, that Python handle them as one string.
>> 
>> print ['??' '??']
>> ['\xf3\xd3']
>> 
>> I wanna ask that is a bug or is it a feature?

Feature, as others have pointed out, though I fail to see the need
for it, given that Python's general syntax for string (as opposed
to string literal) concatenation is already so convenient.  I.e.,
I fail to see why

x = ("first part of a very long string "
     "second part of a very long string")

is so much better than

x = ("first part of a very long string " +
     "second part of a very long string")

FWIW, C has the same concatenation feature for string literals.
E.g., the following is valid C:

printf("first part of a very long string "
       "second part of a very long string\n");

kynn



From wuwei23 at gmail.com  Fri Aug  7 13:37:02 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 10:37:02 -0700 (PDT)
Subject: Extracting matrix from a text file
References:  
	 
	
Message-ID: 

MRAB  wrote:
> Or:
> ? ? ? ? ?columns = line.split(' ')[1 : ]

Even better, well spotted.


From garabik-news-2005-05 at kassiopeia.juls.savba.sk  Fri Aug  7 13:41:38 2009
From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk)
Date: Fri, 7 Aug 2009 17:41:38 +0000 (UTC)
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
Message-ID: 

Thorsten Kampe  wrote:
 
> lines". That *is* *exactly* nothing.
> 
> Another guy claims he gets times between 2.9 and 6.2 seconds when 
> running decode/unicode in various manifestations over "18 million 


over a sample of 600000 words (sorry for not being able to explain
myself clear enough so that everyone understands)
while my current project is 18e6 words, that is the overall running time
will be 87 vs. 186 seconds, which is fairly noticeable.

> words" (or is it 600 million?) and says "the differences are pretty 
> significant". 

600 million is the size of the whole corpus, that translates to
48 minutes vs. 1h43min. That already is a huge difference (going to
lunch during noon or waiting another hour until it runs over - and 
you can bet it is _very_ noticeable when I am hungry :-)).

With 9 different versions of the corpus (that is, what we are really
using now) that goes to 7.2 hours (or even less with python3.1!) vs. 15
hours. Being able to re-run the whole corpus generation in one working
day (and then go on with the next issues) vs. working overtime or
delivering the corpus one day later is a huge difference. Like, being
one day behind the schedule.

> I think I don't have to comment on that.

Indeed, the numbers are self-explanatory.

> 
> If you increase the number of loops to one million or one billion or 
> whatever even the slightest completely negligible difference will occur. 
> The same thing will happen if you just increase the corpus of words to a 
> million, trillion or whatever. The performance implications of that are 
> exactly none.
> 

I am not sure I understood that. Must be my English :-)

-- 
 -----------------------------------------------------------
| Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__    garabik @ kassiopeia.juls.savba.sk     |
 -----------------------------------------------------------
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!


From rt8396 at gmail.com  Fri Aug  7 13:43:05 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 10:43:05 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
Message-ID: 

On Aug 7, 11:03?am, Kee Nethery  wrote:
...(snip)
> I'm looking forward to the acceleration of improvements to the ?
> official docs based upon easy to provide user feedback. Glad to see ?
> that the bug tracking system is going to not be the primary means for ?
> documentation changes.

+1



From wuwei23 at gmail.com  Fri Aug  7 13:43:13 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 10:43:13 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	 
Message-ID: <1de1eadf-6a2a-414c-a7cf-cf235edadcfb@a39g2000pre.googlegroups.com>

kj  wrote:
> Feature, as others have pointed out, though I fail to see the need
> for it, given that Python's general syntax for string (as opposed
> to string literal) concatenation is already so convenient. ?I.e.,
> I fail to see why
>
> x = ("first part of a very long string "
> ? ? ?"second part of a very long string")
>
> is so much better than
>
> x = ("first part of a very long string " +
> ? ? ?"second part of a very long string")

My impression is it's mostly for one of clarity. It's especially
useful with regular expressions, as it allows for comments to document
each element of the regex (following example shamelessly taken from
the docs (albeit with personal preferences on formatting))):

re.compile(
    "[A-Za-z_]"       # letter or underscore
    "[A-Za-z0-9_]*"   # letter, digit or underscore
)

Not having the plus sign present does assist (IMO) in the ease of
parsing the regex.
re.compile(


From wuwei23 at gmail.com  Fri Aug  7 13:45:29 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 10:45:29 -0700 (PDT)
Subject: unicode() vs. s.decode()
References: 
	 
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	 
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	 
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com> 
	 
Message-ID: <006e7808-74e7-4d29-a7bc-01492d14de65@v15g2000prn.googlegroups.com>

garabik-news-2005... at kassiopeia.juls.savba.sk wrote:
> I am not sure I understood that. Must be my English :-)

I just parsed it as "blah blah blah I won't admit I'm wrong" and
didn't miss anything substantive.




From wuwei23 at gmail.com  Fri Aug  7 13:48:22 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 10:48:22 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
Message-ID: 

Kee Nethery  wrote:
> I'm looking forward to the acceleration of improvements to the ?
> official docs based upon easy to provide user feedback. Glad to see ?
> that the bug tracking system is going to not be the primary means for ?
> documentation changes.

I'm not sure what you see as being fundamentally different between
open access to a bug tracker & open access to a wiki, other than it
being a lot more difficult to have threaded discussion on a wiki.

Why exactly is posting an open comment on a bug tracker somehow
inferior to posting an open comment on a wiki?


From abecedarian314159 at yahoo.com  Fri Aug  7 13:51:17 2009
From: abecedarian314159 at yahoo.com (William)
Date: Fri, 7 Aug 2009 10:51:17 -0700 (PDT)
Subject: questions about object references
Message-ID: <786181.46665.qm@web110610.mail.gq1.yahoo.com>

I have a question.? Suppose I do the following:

def myfunc(a,b):
? return a+b

myfunc2=myfunc

is there anyway to find all of the references to myfunc?? That is, can I find out all of the functions that may be aliased to myfunc?

second question:



class MyClass(object):
?def __init__(a,b):
?? self.a=a
?? self.b=b
? def myfunc(self):
??? return self.a+self.b

myclass=MyClass(3,4)
myclass.myfunc2=myclass.myfunc

Is there any way to find all the references to myclass.myfunc--in this case,
myclass.myfunc2?

Thanks,
William

is there a way to 





      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From drobinow at gmail.com  Fri Aug  7 14:05:35 2009
From: drobinow at gmail.com (David Robinow)
Date: Fri, 7 Aug 2009 14:05:35 -0400
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References:  
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
Message-ID: <4eb0089f0908071105i5180b861rea513c70bf8f9655@mail.gmail.com>

On Fri, Aug 7, 2009 at 1:48 PM, alex23 wrote:
> Why exactly is posting an open comment on a bug tracker somehow
> inferior to posting an open comment on a wiki?
 When one believes that development is controlled by a cabal which is
jealous of outsiders and actively prevents improvements to the docs,
any change, even if only in perception, helps to weaken the hold of
the evil forces holding back the success of Python.


From mail at timgolden.me.uk  Fri Aug  7 14:08:22 2009
From: mail at timgolden.me.uk (Tim Golden)
Date: Fri, 07 Aug 2009 19:08:22 +0100
Subject: Changing Remote Registry
In-Reply-To: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
Message-ID: <4A7C6D96.3000201@timgolden.me.uk>

Kevin Holleran wrote:
> Long story short, I am using _winreg to do this.
> 
> hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
> value,type = _winreg.QueryValueEx(hKey, item)
> if (value == wrongValue):
>        _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
> 
> 
> When I do this I receive the error:
> 
> _winreg.SetValue WindowsError: [Error 5] Access Denied

As an alternative, try using WMI instead. You'll have to look up the docs
a bit, but to get you started:


import wmi

reg = wmi.WMI ("remote-machine", namespace="default").StdRegProv

print reg.methods.keys ()



TJG


From vorticitywolfe at gmail.com  Fri Aug  7 14:17:28 2009
From: vorticitywolfe at gmail.com (J Wolfe)
Date: Fri, 7 Aug 2009 11:17:28 -0700 (PDT)
Subject: passing menu label to function
Message-ID: <44f84fe8-0dce-463f-b37f-b02f241bf93a@e34g2000vbm.googlegroups.com>

Hi,

I would like to pass the label name of a menu to the command it is
calling, is that possible?

self.menuitem.menu.add_command(label="pass this",command = lambda i =
self.self.menuitem.menu.cget("label"): self.function(i))

def function(self, i)
     print i   # print the label name


Any help would be appreciated!
Thanks!
Jonathan


From marduk at letterboxes.org  Fri Aug  7 14:18:51 2009
From: marduk at letterboxes.org (Albert Hopkins)
Date: Fri, 07 Aug 2009 14:18:51 -0400
Subject: PEP 8 exegetics: conditional imports?
In-Reply-To: 
References: 
Message-ID: <1249669131.8286.32.camel@centar>

On Fri, 2009-08-07 at 16:50 +0000, kj wrote:
> 
> Conditional imports make sense to me, as in the following example:
> 
> def foobar(filename):
>     if os.path.splitext(filename)[1] == '.gz':
>         import gzip
>         f = gzip.open(filename)
>     else:
>         f = file(filename)
>     # etc.
> 
> And yet, quoth PEP 8:
> 
>     - Imports are always put at the top of the file, just after any module
>       comments and docstrings, and before module globals and constants.
> 
> ...which seems to condemn conditional imports unequivocally. 
> 
> Then again, the PEP 8 scriptures do not explicitly mention conditional
> imports at all, as far as I can tell, which leaves open the
> possibility that they are still righteous. 
> 
> In fact, venerable passages in the Python standard library source
> code, if properly interpreted, can be seen to carry out conditional
> imports, such as this fragment recovered from random.py:
> 
>         if a is None:
>             try:
>                 a = long(_hexlify(_urandom(16)), 16)
>             except NotImplementedError:
>                 import time
>                 a = long(time.time() * 256) # use fractional seconds
> 
> Or even more clearly, this one from test/pystone.py:
> 
> if __name__ == '__main__':
>     import sys
> 
> 

I can't speak for others... but generally you can "tell" when an import
belongs at the top of a module and when you need to make exceptions.  I
would say that, as a general rule, they go up top (easier to identify
what external dependencies a module have).  There are, of course,
exceptions:

      * Exceptions and other not-often-executed blocks
      * Inside test functions (where the imported modules are only used
        by tests
      * Inside main() functions where the imported modules are only used
        if the module is run as a script
      * When startup-time is important. Often it's necessary to have you
        module up and running in an instant and import "expensive"
        modules as-needed.
      * "Dynamic" import such as plugins, etc.

Of course, like everything else in PEP 8, it's meant as a "guide" and
not as an "order".  YMMV.

-a




From wuwei23 at gmail.com  Fri Aug  7 14:30:41 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 11:30:41 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References:   
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
Message-ID: <56e513e5-63cd-479d-94b2-0f10f617d4a0@d4g2000prc.googlegroups.com>

David Robinow  wrote:
> ?When one believes that development is controlled by a cabal which is
> jealous of outsiders and actively prevents improvements to the docs,
> any change, even if only in perception, helps to weaken the hold of
> the evil forces holding back the success of Python.

Yeah, it's clearly all ego and assholes that's preventing Python from
being the enochian equivalent of programming languages :)


From marduk at letterboxes.org  Fri Aug  7 14:35:52 2009
From: marduk at letterboxes.org (Albert Hopkins)
Date: Fri, 07 Aug 2009 14:35:52 -0400
Subject: PEP 8 exegetics: conditional imports?
In-Reply-To: 
References: 
Message-ID: <1249670152.8286.43.camel@centar>

On Fri, 2009-08-07 at 16:50 +0000, kj wrote:
> 
> Conditional imports make sense to me, as in the following example:
> 
> def foobar(filename):
>     if os.path.splitext(filename)[1] == '.gz':
>         import gzip
>         f = gzip.open(filename)
>     else:
>         f = file(filename)
>     # etc.
> 

I should add that in your example I would probably still put the import
at the top, e.g.:

import gzip
[...]

def foobar(filename):
    if os.path.splitext(filename)[1] == '.gz':
        f = gzip.open(filename)
    else:
        f = open(filename)

Reason being is that if later on I decide I want to write another
function inside my module that does the same thing I don't have to do
the same conditional import.

Even better, if this is something you find yourself doing often you can
create your own "smart" open and put it in a library:

# file anyfile

import __builtin__
import gzip

def open(filename, ...):
    if filename.endswith('.gz'):
        f = gzip.open(filename, ...)
    else:
        f = __builtin__.open(f, ...)

    return f

Then:

>>> import anyfile
>>> f = anyfile.open(filename, ...)

-a




From keith.hughitt at gmail.com  Fri Aug  7 14:42:42 2009
From: keith.hughitt at gmail.com (pwnedd)
Date: Fri, 7 Aug 2009 11:42:42 -0700 (PDT)
Subject: Database query execution times in Python?
Message-ID: <24870050.post@talk.nabble.com>


Hi all,

I've been writing some code using libraries based on the Python Database API
2.0 (MySQLdb & pg), and so far things are working really well. There is one
thing that I have not been able to figure out how to do, however: 

Retrieve the time is took a given query to execute.

Does anyone know if this is possible?

Any help would be greatly appreciated.

Thanks!
Keith


-- 
View this message in context: http://www.nabble.com/Database-query-execution-times-in-Python--tp24870050p24870050.html
Sent from the Python - python-list mailing list archive at Nabble.com.



From SandorL at gmail.com  Fri Aug  7 14:48:16 2009
From: SandorL at gmail.com (=?ISO-8859-1?Q?L=E1szl=F3_S=E1ndor?=)
Date: Fri, 7 Aug 2009 14:48:16 -0400
Subject: question: why isn't a byte of a hash more uniform? how could I
	improve my code to cure that?
References: 
Message-ID: 

Thank you, Tim. My comments are below.

On 2009-08-07 13:19:47 -0400, Tim Chase  said:

>> After I have written a short Python script that hashes my textfile line by
>> line and collects the numbers next to the original, I checked what I got.
>> Instead of getting around 25% in each treatment, the range is 17.8%-31.3%.
> 
> That sounds suspiciously like 25% with a +/- 7% fluctuation one might 
> expect to see from non-random source data.

Could you help me where this range comes from? (If all my lines were 
"42", I wouldn't hit this range. So it cannot be a rule. Right?)

> 
> Remember that your outputs are driven purely by your inputs in a 
> deterministic fashion -- if your inputs are purely random, then your 
> outputs should more closely match your expected bin'ing.  If your 
> inputs aren't random, you get a taste of your own medicine ("my file 
> has just the number 42 on every line...why isn't my output random?").  
> And randomness-of-hash-output is a red herring since hashing is *not* 
> random.

Thanks, I tried to be correct with "pseudo-random". I understand that 
everything is dependent on input. I want it to be the case. However, I 
hoped that good hashes produce random-looking output from input with 
very little variation. It would be strange if I could not get more than 
18% of lines with a remainder of 3 (after division by 4), whatever hash 
I try just because these are names of people.

> 
> Your input is also finite -- an aspect which leaves you a far cry from 
> the full hash-space.  If an md5 has 32 bytes (256 bits) of data, your 
> input would have to cover 2**256 possible inputs to see the full 
> profile of your outputs.  That's a lot of input :)
> 
> -tkc

OK, I understand. Could anyone suggest a better way to do this, then?

(Recap: random-looking, close-to uniform assignment of one number out 
of four possibilities to strings.)

Thanks, everyone.

Laszlo



From REMpeteOVE at petezilla.co.uk  Fri Aug  7 15:04:41 2009
From: REMpeteOVE at petezilla.co.uk (Peter Chant)
Date: Fri, 07 Aug 2009 20:04:41 +0100
Subject: Setuptools - help!
References: 
	
Message-ID: <9fauk6-t24.ln1@phoenix.fire>

Robert Kern wrote:

> You need to put main.py into the pphoto package.
> 
> $ mkdir pphoto/
> $ mv main.py pphoto/
> $ touch pphoto/__init__.py
> 

Thanks, it worked.  Any ideas how to run the resulting scripts without
installing or running as root?

Pete


-- 
http://www.petezilla.co.uk


From nagle at animats.com  Fri Aug  7 15:06:47 2009
From: nagle at animats.com (John Nagle)
Date: Fri, 07 Aug 2009 12:06:47 -0700
Subject: Module updating plans for Python 3.1: feedparser, MySQLdb
In-Reply-To: 
References: <4a739a96$0$1615$742ec2ed@news.sonic.net>
	
Message-ID: <4a7c7a50$0$1586$742ec2ed@news.sonic.net>

Buck wrote:
> I use MySQLdb quite a bit in my work. I could volunteer to help update
> it. Are there any particular bugs we're talking about or just a
> straight port to 3.0?

    It's a non-trivial port.  There's a release candidate for Python 2.6;
see

https://sourceforge.net/project/shownotes.php?release_id=672239

but that was back in March and hasn't advanced since then.

There's an unofficial port of MySQLdb to
Python 2.6 for Windows.  See

https://sourceforge.net/forum/forum.php?thread_id=3108914&forum_id=70460

The MySQLdb developer says that conversion to 3.0 is hard, and he's busy
doing other things.

					John Nagle


From nagle at animats.com  Fri Aug  7 15:07:48 2009
From: nagle at animats.com (John Nagle)
Date: Fri, 07 Aug 2009 12:07:48 -0700
Subject: Is "feedparser" deprecated?
Message-ID: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>

   Feedparser requires SGMLlib, which has been removed from Python 3.0.
Feedparser hasn't been updated since 2007. Does this mean Feedparser
is dead?

				John Nagle


From van.lindberg at gmail.com  Fri Aug  7 15:15:55 2009
From: van.lindberg at gmail.com (VanL)
Date: Fri, 07 Aug 2009 14:15:55 -0500
Subject: Survey: Does your company use Python? Do you know a company that
	uses Python?
Message-ID: 

This is a survey to find as many companies using Python as we can. You 
can see the survey below:



You don't need to work at the company to add it to this list! We will 
filter for duplicates.

The answers to this survey will be kept private. If you still don't want 
to identify yourself, no problem! We just want to know where Python is 
being used.




From ethan at stoneleaf.us  Fri Aug  7 15:15:56 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Fri, 07 Aug 2009 12:15:56 -0700
Subject: question: why isn't a byte of a hash more uniform? how could
	I	improve my code to cure that?
In-Reply-To: 
References: 
	
Message-ID: <4A7C7D6C.4020904@stoneleaf.us>

L?szl? S?ndor wrote:
> Thank you, Tim. My comments are below.
> 
> On 2009-08-07 13:19:47 -0400, Tim Chase  
> said:
> 
>>> After I have written a short Python script that hashes my textfile 
>>> line by
>>> line and collects the numbers next to the original, I checked what I 
>>> got.
>>> Instead of getting around 25% in each treatment, the range is 
>>> 17.8%-31.3%.
>>
>>
>> That sounds suspiciously like 25% with a +/- 7% fluctuation one might 
>> expect to see from non-random source data.
> 
> 
> Could you help me where this range comes from? (If all my lines were 
> "42", I wouldn't hit this range. So it cannot be a rule. Right?)
> 
>>
>> Remember that your outputs are driven purely by your inputs in a 
>> deterministic fashion -- if your inputs are purely random, then your 
>> outputs should more closely match your expected bin'ing.  If your 
>> inputs aren't random, you get a taste of your own medicine ("my file 
>> has just the number 42 on every line...why isn't my output random?").  
>> And randomness-of-hash-output is a red herring since hashing is *not* 
>> random.
> 
> 
> Thanks, I tried to be correct with "pseudo-random". I understand that 
> everything is dependent on input. I want it to be the case. However, I 
> hoped that good hashes produce random-looking output from input with 
> very little variation. It would be strange if I could not get more than 
> 18% of lines with a remainder of 3 (after division by 4), whatever hash 
> I try just because these are names of people.
> 
>>
>> Your input is also finite -- an aspect which leaves you a far cry from 
>> the full hash-space.  If an md5 has 32 bytes (256 bits) of data, your 
>> input would have to cover 2**256 possible inputs to see the full 
>> profile of your outputs.  That's a lot of input :)
>>
>> -tkc
> 
> 
> OK, I understand. Could anyone suggest a better way to do this, then?
> 
> (Recap: random-looking, close-to uniform assignment of one number out of 
> four possibilities to strings.)
> 
> Thanks, everyone.
> 
> Laszlo
> 

Well,  a very simplistic method is to use the length of the input string 
modulus four.  If the names have decently "random" lengths, that may work.

~Ethan~


From __peter__ at web.de  Fri Aug  7 15:26:13 2009
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Aug 2009 21:26:13 +0200
Subject: passing menu label to function
References: <44f84fe8-0dce-463f-b37f-b02f241bf93a@e34g2000vbm.googlegroups.com>
Message-ID: 

J Wolfe wrote:

> I would like to pass the label name of a menu to the command it is
> calling, is that possible?
> 
> self.menuitem.menu.add_command(label="pass this",command = lambda i =
> self.self.menuitem.menu.cget("label"): self.function(i))
> 
> def function(self, i)
>      print i   # print the label name

A simple pure-python approach:

def add_command_with_label(menu, label, command):
    menu.add_command(label=label, command=lambda: command(label))

# ...

function = self.function
menu = self.menuitem.menu
add_command_with_label(menu, "pass this", function)

Alternatively, if you plan to change the labels during runtime:

index = 1 # indices start at 1, not 0
menu.add_command(label="whatever", command=lambda index=index, menu=menu: 
function(menu.entrycget(index, "label")))

(all untested, likely to contain typos)

Peter



From __peter__ at web.de  Fri Aug  7 15:42:16 2009
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Aug 2009 21:42:16 +0200
Subject: PEP 8 exegetics: conditional imports?
References: 
Message-ID: 

kj wrote:

> Conditional imports make sense to me, as in the following example:
> 
> def foobar(filename):
>     if os.path.splitext(filename)[1] == '.gz':
>         import gzip
>         f = gzip.open(filename)
>     else:
>         f = file(filename)
>     # etc.
> 
> And yet, quoth PEP 8:
> 
>     - Imports are always put at the top of the file, just after any module
>       comments and docstrings, and before module globals and constants.
> 
> ...which seems to condemn conditional imports unequivocally.
> 
> Then again, the PEP 8 scriptures do not explicitly mention conditional
> imports at all, as far as I can tell, which leaves open the
> possibility that they are still righteous.
> 
> In fact, venerable passages in the Python standard library source
> code, if properly interpreted, can be seen to carry out conditional
> imports, such as this fragment recovered from random.py:
> 
>         if a is None:
>             try:
>                 a = long(_hexlify(_urandom(16)), 16)
>             except NotImplementedError:
>                 import time
>                 a = long(time.time() * 256) # use fractional seconds
> 
> Or even more clearly, this one from test/pystone.py:
> 
> if __name__ == '__main__':
>     import sys
> 
> 
> 
> I seek the wisdom of the elders.  Is there a consensus on the matter
> of conditional imports?  Are they righteous?  Or are they the way
> of the wicked?

If you want to take a rational approach measure speed and memory footprint 
of your program both with the conditional and unconditional imports. Then go 
with the conditional imports only if you can demonstrate a noticeable 
benefit.

This criterion is unlikely to be met for the examples you give above. time 
is a built-in module, and gzip a thin wrapper around zlib which is also 
built-in.

Peter



From lists at cheimes.de  Fri Aug  7 15:44:57 2009
From: lists at cheimes.de (Christian Heimes)
Date: Fri, 07 Aug 2009 21:44:57 +0200
Subject: PEP 8 exegetics: conditional imports?
In-Reply-To: 
References: 
Message-ID: 

kj wrote:
> I seek the wisdom of the elders.  Is there a consensus on the matter
> of conditional imports?  Are they righteous?  Or are they the way
> of the wicked?

imports in functions are dangerous and may lead to dead locks if they 
are mixed with threads. An import should never start a thread and you 
should avoid to import code in threads.

Christian



From wuwei23 at gmail.com  Fri Aug  7 15:57:11 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 12:57:11 -0700 (PDT)
Subject: Is "feedparser" deprecated?
References: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
Message-ID: <61d0b767-144b-4e3b-96dd-afe71904d619@t11g2000prh.googlegroups.com>

John Nagle  wrote:
> ? ?Feedparser requires SGMLlib, which has been removed from Python 3.0.
> Feedparser hasn't been updated since 2007. Does this mean Feedparser
> is dead?

Wouldn't you be better served asking this on the feedparser bug
tracker?

http://code.google.com/p/feedparser/issues/list


From vorticitywolfe at gmail.com  Fri Aug  7 16:00:11 2009
From: vorticitywolfe at gmail.com (J Wolfe)
Date: Fri, 7 Aug 2009 13:00:11 -0700 (PDT)
Subject: passing menu label to function
References: <44f84fe8-0dce-463f-b37f-b02f241bf93a@e34g2000vbm.googlegroups.com>
	
Message-ID: <0ac769de-3a7c-4973-a333-d06b7b14d540@q35g2000vbi.googlegroups.com>

Thanks Peter,

I figured out an alternative just as you posted your response,

I just looped through the buttons I wanted to add and used the loop
variable to label the item and then passed it to the function, though
your way seems much more robust.

Thanks a lot!


From wuwei23 at gmail.com  Fri Aug  7 16:00:17 2009
From: wuwei23 at gmail.com (alex23)
Date: Fri, 7 Aug 2009 13:00:17 -0700 (PDT)
Subject: PEP 8 exegetics: conditional imports?
References: 
	
Message-ID: 

Peter Otten <__pete... at web.de> wrote:
> This criterion is unlikely to be met for the examples you give above. time
> is a built-in module, and gzip a thin wrapper around zlib which is also
> built-in.

This is something I was _utterly_ unaware of. Is there a list of what
modules are built-in readily available?

The only reference[1] I could find via Google doesn't list zlib at
all.

[1]: http://www.vldb.informatik.hu-berlin.de/Themen/manuals/python/python-texinfo/built-in_modules.html


From davea at ieee.org  Fri Aug  7 16:00:59 2009
From: davea at ieee.org (Dave Angel)
Date: Fri, 07 Aug 2009 16:00:59 -0400
Subject: question: why isn't a byte of a hash more uniform? how could
	I 	improve my code to cure that?
In-Reply-To: 
References: 
Message-ID: <4A7C87FB.40106@ieee.org>

L???????????????????????????????? wrote:
> Hi all,
> I am a Python novice, and right now I would be happy to simply get my job
> done with it, but I could appreciate some thoughts on the issue below.
>
> I need to assign one of four numbers to names in a list. The assignment
> should be pseudo-random: no pattern whatsoever, but deterministic,
> reproducible, and close to uniform. My understanding was that hash functions
> would do the job. As I only needed 2 bits of treatment, I picked a byte of
> the hashes generated, and even taken mod 4 of it. See the code below.
>
> After I have written a short Python script that hashes my textfile line by
> line and collects the numbers next to the original, I checked what I got.
> Instead of getting around 25% in each treatment, the range is 17.8%-31.3%. I
> understand that the pseudo-randomness means that the treatments should not
> be neat and symmetric. Still, this variation is unacceptable for my purpose.
> My understanding was that good hash functions generate numbers that look
> completely random, and picking only a byte should not change that. I thought
> the promise was also to get close to uniformity:
> http://en.wikipedia.org/wiki/Hash_function#Uniformity. I tried all the
> hashes in the hashlib module, and picked bytes from the beginning and the
> end of the hashes, but treatments never were close to uniform (curiously,
> always the last treatment seems to be too rare).
>
> Maybe it is an obvious CS puzzle, I'm looking forward to standing corrected.
>
> Thanks!
>
> Laszlo
>
> The script:
>
> #! /usr/bin/python
>
> f = open('names.txt', 'r')
> g = open('nameshashed.txt', 'a')
>
> import hashlib
>
> for line in f:
>     line = line.rstrip()
>     h = str(hashlib.sha512(line).hexdigest())
>     s = line + ',' + str(ord(h[64])%4) + '\n'
>     g.write(s),
>
>   
The problem is indeed simple, but really nothing to do with Python.  
You're using a single character from a hexdigest, so the only 
possibilities are 0,1,2,...9,A,B, C, D,E, and F

Taking the ords of each of those, and moduloing with 4, you get
     4 - 0
     5 - 1
     4 - 2
     3 - 3

In other words, there's a greater than expected likelihood of 1, and 
less than expected likelihood of 3.  I'd figure the distribution ought 
to be:
     25%,  31%, 25%, and 19%

I'd use digest() instead of hexdigest(), and of course reduce the 
subscript  to 63 or less.

DaveA


From davea at ieee.org  Fri Aug  7 16:16:01 2009
From: davea at ieee.org (Dave Angel)
Date: Fri, 07 Aug 2009 16:16:01 -0400
Subject: PEP 8 exegetics: conditional imports?
In-Reply-To: <1249669131.8286.32.camel@centar>
References:  <1249669131.8286.32.camel@centar>
Message-ID: <4A7C8B81.1010901@ieee.org>

Albert Hopkins wrote:
> On Fri, 2009-08-07 at 16:50 +0000, kj wrote:
>   
>> Conditional imports make sense to me, as in the following example:
>>
>> def foobar(filename):
>>     if os.path.splitext(filename)[1] == '.gz':
>>         import gzip
>>         f = gzip.open(filename)
>>     else:
>>         f = file(filename)
>>     # etc.
>>
>> And yet, quoth PEP 8:
>>
>>     - Imports are always put at the top of the file, just after any module
>>       comments and docstrings, and before module globals and constants.
>>
>> ...which seems to condemn conditional imports unequivocally. 
>>
>> Then again, the PEP 8 scriptures do not explicitly mention conditional
>> imports at all, as far as I can tell, which leaves open the
>> possibility that they are still righteous. 
>>
>> In fact, venerable passages in the Python standard library source
>> code, if properly interpreted, can be seen to carry out conditional
>> imports, such as this fragment recovered from random.py:
>>
>>         if a is None:
>>             try:
>>                 a = long(_hexlify(_urandom(16)), 16)
>>             except NotImplementedError:
>>                 import time
>>                 a = long(time.time() * 256) # use fractional seconds
>>
>> Or even more clearly, this one from test/pystone.py:
>>
>> if __name__ == '__main__':
>>     import sys
>>
>>
>>     
>
> I can't speak for others... but generally you can "tell" when an import
> belongs at the top of a module and when you need to make exceptions.  I
> would say that, as a general rule, they go up top (easier to identify
> what external dependencies a module have).  There are, of course,
> exceptions:
>
>       * Exceptions and other not-often-executed blocks
>       * Inside test functions (where the imported modules are only used
>         by tests
>       * Inside main() functions where the imported modules are only used
>         if the module is run as a script
>       * When startup-time is important. Often it's necessary to have you
>         module up and running in an instant and import "expensive"
>         modules as-needed.
>       * "Dynamic" import such as plugins, etc.
>
> Of course, like everything else in PEP 8, it's meant as a "guide" and
> not as an "order".  YMMV.
>
> -a
>
>
>   
Excellent points.  I'd add a couple more, one pro, and two con:

You need conditionals when you're doing things that are 
environment-specific.  For example, you might use Win32 stuff when on 
Windows, and something else when on Linux.  So you might have a pair of 
modules which encapsulate the non-portable aspects, and conditionally 
import one of those.

You usually want any imports to be complete before starting 
multithreading.  As somebody else has recently pointed out, there's an 
import-lock that's active during imports,

If two modules do mutual imports (not a good idea, but it is sometimes 
practically unavoidable), the earlier in the file that the import 
happens, the less likely for a problem to crop up.  So try to put them 
at the top.




From gnewsg at gmail.com  Fri Aug  7 16:22:58 2009
From: gnewsg at gmail.com (Giampaolo Rodola')
Date: Fri, 7 Aug 2009 13:22:58 -0700 (PDT)
Subject: Survey: Does your company use Python? Do you know a company that 
	uses Python?
References: 
Message-ID: 

On 7 Ago, 21:15, VanL  wrote:
> This is a survey to find as many companies using Python as we can. You
> can see the survey below:
>
> 
>
> You don't need to work at the company to add it to this list! We will
> filter for duplicates.
>
> The answers to this survey will be kept private. If you still don't want
> to identify yourself, no problem! We just want to know where Python is
> being used.

...you accidentally forgot to mention the *reason*.


--- Giampaolo
http://code.google.com/p/pyftpdlib
http://code.google.com/p/psutil


From __peter__ at web.de  Fri Aug  7 16:27:26 2009
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Aug 2009 22:27:26 +0200
Subject: question: why isn't a byte of a hash more uniform? how could I
	improve my code to cure that?
References: 
	
Message-ID: 

Dave Angel wrote:

[clever analysis snipped]

> I'd use digest() instead of hexdigest(), and of course reduce the
> subscript  to 63 or less.

OP: You could also try

hash(line) % 4

While AFAIK it doesn't make promises about randomness it might still be good 
enough in practice.

Peter




From horos11 at gmail.com  Fri Aug  7 16:29:28 2009
From: horos11 at gmail.com (horos11)
Date: Fri, 7 Aug 2009 13:29:28 -0700 (PDT)
Subject: importing fully qualified scripts to check syntax
Message-ID: 

hey all,

I'm trying to make a syntax checker, where I say:

python -c "import /path/to/script"

to check the syntax of the script named '/path/to/script' (note: no py
extension needed). Of course this doesn't work because the
functionality for import is bundled up with the environment..

So - is there any simple, generic way in python to import a python
file without worrying about naming convention or environment? Sort of
like require in perl?

Ed



From __peter__ at web.de  Fri Aug  7 16:33:08 2009
From: __peter__ at web.de (Peter Otten)
Date: Fri, 07 Aug 2009 22:33:08 +0200
Subject: PEP 8 exegetics: conditional imports?
References: 
	
	
Message-ID: 

alex23 wrote:

> This is something I was _utterly_ unaware of. Is there a list of what
> modules are built-in readily available?

>> sys.builtin_module_names
('__builtin__', '__main__', '_ast', '_bisect', '_codecs', '_collections', 
'_functools', '_locale', '_random', '_socket', '_sre', '_struct', 
'_symtable', '_warnings', '_weakref', 'array', 'binascii', 'cPickle', 
'cStringIO', 'errno', 'exceptions', 'fcntl', 'gc', 'grp', 'imp', 
'itertools', 'marshal', 'math', 'operator', 'posix', 'pwd', 'select', 
'signal', 'spwd', 'strop', 'sys', 'syslog', 'thread', 'time', 'unicodedata', 
'xxsubtype', 'zipimport', 'zlib')

Peter




From kee at kagi.com  Fri Aug  7 16:35:26 2009
From: kee at kagi.com (Kee Nethery)
Date: Fri, 7 Aug 2009 13:35:26 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References: 
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
Message-ID: <93DD1DF1-1614-47A6-A512-F7EFEE6B0642@kagi.com>


On Aug 7, 2009, at 10:48 AM, alex23 wrote:

> Kee Nethery  wrote:
>> I'm looking forward to the acceleration of improvements to the
>> official docs based upon easy to provide user feedback. Glad to see
>> that the bug tracking system is going to not be the primary means for
>> documentation changes.
>
> I'm not sure what you see as being fundamentally different between
> open access to a bug tracker & open access to a wiki, other than it
> being a lot more difficult to have threaded discussion on a wiki.
>
> Why exactly is posting an open comment on a bug tracker somehow
> inferior to posting an open comment on a wiki?

It's a good question and deserves a good answer.

* Fewer Steps
* Immediate
* Does not need to be formally reviewed
* Easier to search

For all these comments, assume the starting point is the section in a  
web page that documents a specific python function. Assume the user is  
using the documentation for the first time in attempt to convert to  
Python. Thus, this is the only official Python page they have ever  
seen, they found it via Google and went directly to it. For example  
purposes, I'll use the following page:
http://docs.python.org/reference/lexical_analysis.html
Lets say the user is in section 2.1.3 Comments

Here's the scenario: The user wanted to include "#" in one of their  
strings and the IDE kept interpreting it as a comment. But they really  
need to use that character in the string. Eventually they find out  
that they can escape the character in their string so that Python  
stops thinking it is the beginning of a comment. They want other users  
to not suffer through the same thing, and they want to contribute to  
the betterment of Python, so they want this information saved so that  
others can avoid the mistake they were making.

* Fewer Steps:

With the bug tracking system, their only option is to lobby to get the  
documentation changed. Lets assume that Python experts all agree that  
the docs should get updated with this gotcha (which as a newbie, they  
are not sure that is a valid assumption and would probably just halt  
in their quest to get the docs updated). But assuming everyone agrees  
this is a valuable addition to the docs so that others can avoid the  
same error, where on this page dues the user submit this bug? There is  
no link on this page to the bug tracking system.

Lets assume they find the bug tracking system through determined  
efforts because they believe there has to be such a thing and they are  
absolutely sure the powers that be want their input. When they find  
the bug tracking system ... they have to create a user account. Then  
they have to wait for the confirming email. Finally they get access to  
the bug tracking system and being a good citizen, they want to make  
sure that they are not duplicating a previously entered bug. What do  
they search on? Do they search for 2.1.3? Do they search for "#"?  
Chances are, even if they do a whole set of searches, and if there  
really is already another bug entered for the exact same issue, they  
are unlikely to find it.

So they create a bug and now they need to go back and reference the  
link (find the page from their browser history) and type up why they  
think their modification to the documentation is worthy. Then once the  
bug is submitted ... you get the picture, there are a gazillion steps  
just to submit a bug. Most people do not bother to submit little  
helpful hints to the docs because it is too much of a pain to do so  
and there is zero confidence that as a newbie, anyone cares about what  
they found confusing, after all, they are just a newbie and not worthy  
of altering the documentation. (Certainly that opinion has been  
expressed several times on this mailing list).

With a wiki article tied to each section in the docs, they click on  
the link and are taken directly to the wiki page of user contributions  
for this specific  2.1.3 section of the docs. They scan the user  
comments and see that no one else entered a note about this gotcha.  
They click on the edit button, enter their gotcha, save, and they are  
done.

* Immediate:

With the bug tracking system, they struggle to find a place to  
contribute and then once they make their contribution, they have no  
idea whether anyone will ever see it and whether they have just wasted  
a bunch of time.

With the wiki link for that section, in less than a minute, they can  
see the comments they have left attached to that specific section so  
that others can see them too and perhaps avoid the same mistake they  
made. A wiki link encourages new users to be contributors. New users  
are the absolute best source of what is confusing to a new user.

* Does not need to be formally reviewed:

With the bug tracking system, each bug has to be reviewed by a  
volunteer, analyzed, commented on, dealt with.

With a wiki, no one has to look at user comments. They can just leave  
them there and ignore them. Other users can police the content and add  
additional comments or examples. All the while none of the official  
volunteers have to get in the loop. If some official volunteer wants  
to improve the docs, they can scan the wiki contributions and use that  
as the source for official changes to the docs.

* Easier to search:

Very few people would think to search the bug tracking system for help  
with some specific function. If someone is having trouble with the #  
sign in their strings, the bug tracking system is not going to be at  
the top of their list for search locations, especially when the bug  
tracking system is not mentioned and when found requires a confirmed  
login.

With a wiki link, the first thing someone will do is click on that to  
see if anyone else left notes about the specific problem. If there was  
no answer there, they'd search Google and try bunches of different  
wordings looking for some clue as to what is happening. I doubt most  
users (except for expert users) would ever search the bug tracking  
system for hints on why their code is not doing what they expect.

My 2 cents,
Kee



From horos11 at gmail.com  Fri Aug  7 16:39:22 2009
From: horos11 at gmail.com (horos11)
Date: Fri, 7 Aug 2009 13:39:22 -0700 (PDT)
Subject: syntax checker in python
Message-ID: 

ps - I just realized that it isn't enough to do:

python -c 'import /path/to/script'

since that actually executes any statement inside of the script
(wheras all I want to do is check syntax)

So - let me reprhase that - exactly how can you do a syntax check in
python? Something like perl's -c:

     perl -c script_name.p

Ed


From nad at acm.org  Fri Aug  7 16:41:53 2009
From: nad at acm.org (Ned Deily)
Date: Fri, 07 Aug 2009 13:41:53 -0700
Subject: questions about object references
References: <786181.46665.qm@web110610.mail.gq1.yahoo.com>
Message-ID: 

In article <786181.46665.qm at web110610.mail.gq1.yahoo.com>,
 William  wrote:

> I have a question.? Suppose I do the following:
> 
> def myfunc(a,b):
> ? return a+b
> 
> myfunc2=myfunc
> 
> is there anyway to find all of the references to myfunc?? That is, can I find 
> out all of the functions that may be aliased to myfunc?

The general idea is to search the appropriate namespaces and check for 
object identity, so something like:

>>> def myfunc(a,b):
...     return a+b
... 
>>> myfunc2 = myfunc
>>> 
>>> name = None
>>> namespace = globals()
>>> 
>>> for name in namespace:
...     if namespace[name] is myfunc:
...         print " %s = %s" % (name, namespace[name])
... 
 myfunc = 
 myfunc2 = 

> second question:
> 
> class MyClass(object):
> ?def __init__(a,b):
> ?? self.a=a
> ?? self.b=b
> ? def myfunc(self):
> ??? return self.a+self.b
> 
> myclass=MyClass(3,4)
> myclass.myfunc2=myclass.myfunc
> 
> Is there any way to find all the references to myclass.myfunc--in this case,
> myclass.myfunc2?

This is a little trickier since the object you are searching for is a 
bound method; while it might seem like it should, testing for object 
identity doesn't work.  (You'd could test for identity of the function 
objects pointed to by the bound methods' __func__ attributes.)  However, 
plain old test for equality works, so, for example, to search the 
instance object's attribute space:

>>> class MyClass(object):
...     def __init__(self,a,b):
...         self.a=a
...         self.b=b
...     def myfunc(self):
...         return self.a+self.b
... 
>>> myclass = MyClass(3,4)
>>> myclass.myfunc2 = myclass.myfunc
>>> 
>>> for name in dir(myclass):
...     obj = getattr(myclass, name)  
...     if obj == myclass.myfunc:
...         print " %s is %s" % (name, obj)
... 
 myfunc is >
 myfunc2 is >

-- 
 Ned Deily,
 nad at acm.org



From ivlenin at gmail.com  Fri Aug  7 16:42:42 2009
From: ivlenin at gmail.com (I V)
Date: 7 Aug 2009 22:42:42 +0200
Subject: Is "feedparser" deprecated?
References: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
	<61d0b767-144b-4e3b-96dd-afe71904d619@t11g2000prh.googlegroups.com>
Message-ID: <4a7c91c2$1@news.x-privat.org>

On Fri, 07 Aug 2009 12:57:11 -0700, alex23 wrote:
> John Nagle  wrote:
>> Feedparser hasn't been updated since 2007. Does this mean Feedparser is
>> dead?
> 
> Wouldn't you be better served asking this on the feedparser bug tracker?
> 
> http://code.google.com/p/feedparser/issues/list

But if the project _is_ dead, one would be unlikely to get a response on 
the bug tracker; as seems, in fact, to have happened already:

http://code.google.com/p/feedparser/issues/detail?id=160&start=100

I take it that the lack of response to this issue means the answer is 
"yes."


From gagsl-py2 at yahoo.com.ar  Fri Aug  7 16:42:51 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 17:42:51 -0300
Subject: one method of COM object needs a variant type variable
References: <913F77222E913C49A057FDD7BBDEAAA30192B8A0@br-dc.uhul.wan>
Message-ID: 

En Fri, 07 Aug 2009 04:21:03 -0300, MICH?LEK Jan Mgr.
 escribi?:

> Thanks Gabriel,
> I seen this before, but I don't know, what's mean 'compatible object'. I  
> need create object who will like as an variant type.

A variant is like a giant union contaning almost every basic type. See
http://msdn.microsoft.com/en-us/library/ms221627.aspx
A variant can hold simple Python objects as integer, float, string... but
not complex ones as, say, DocXMLRPCServer. The conversion to/from variant
types is done automatically.
I think you'll get more help in the python-win32 at python.org list.

-- 
Gabriel Genellina



From fuzzyman at gmail.com  Fri Aug  7 16:52:03 2009
From: fuzzyman at gmail.com (Fuzzyman)
Date: Fri, 7 Aug 2009 13:52:03 -0700 (PDT)
Subject: Is python buffer overflow proof?
References:  
	
Message-ID: 

On Aug 3, 10:04?pm, sturlamolden  wrote:
> On 2 Aug, 15:50, Jizzai  wrote:
>
> > Is a _pure_ python program buffer overflow proof?
>
> > For example in C++ you can declare a char[9] to hold user input.
> > If the user inputs 10+ chars a buffer overflow occurs.
>
> Short answer: NO
>
> Bounds checking on sequence types is a protection against buffer
> overflow, but is certainly not sufficient.
>
> The Python interpreter is written in C. Python extension modules are
> written in C (or something similar). If you find an unprotected buffer
> in this C code, you can possibly overflow this buffer. This can be
> used for nasty things like corrupting the stack and injecting
> malicious code. There is a reason why the Python sandbox (rexec and
> Bastion modules) was disabled in Python 2.3.
>
> IronPython and Jython provides better protection against buffer
> overflow than CPython, as these interpreters are written in safer
> languages (C# and Java). You thus get an extra layer of protection
> between the Python code and the unsafe C (used in JVM and .NET
> runtimes).

Well, both Java and .NET both have their own FFI that let you do
whatever you want (more or less).

Michael Foord
--
http://www.ironpythoninaction.com/


From no.email at please.post  Fri Aug  7 16:53:10 2009
From: no.email at please.post (kj)
Date: Fri, 7 Aug 2009 20:53:10 +0000 (UTC)
Subject: unique-ifying a list
Message-ID: 



Suppose that x is some list.  To produce a version of the list with
duplicate elements removed one could, I suppose, do this:

    x = list(set(x))

but I expect that this will not preserve the original order of
elements.

I suppose that I could write something like

def uniquify(items):
    seen = set()
    ret = []
    for i in items:
        if not i in seen:
            ret.append(i)
            seen.add(i)
    return ret

But this seems to me like such a commonly needed operation that I
find it hard to believe one would need to resort to such self-rolled
solutions.  Isn't there some more standard (and hopefully more
efficient, as in "C-coded"/built-in) approach?

TIA!

kynn


From fuzzyman at gmail.com  Fri Aug  7 16:54:05 2009
From: fuzzyman at gmail.com (Fuzzyman)
Date: Fri, 7 Aug 2009 13:54:05 -0700 (PDT)
Subject: Is python buffer overflow proof?
References:  
	 
	
	<4a77c0d9$0$1584$742ec2ed@news.sonic.net>
Message-ID: <95f33050-4f3b-42e8-97f3-9caf3e36292f@g19g2000vbi.googlegroups.com>

On Aug 4, 6:06?am, John Nagle  wrote:
> Gabriel Genellina wrote:
> > En Mon, 03 Aug 2009 18:04:53 -0300, sturlamolden 
> > escribi?:
>
> >> On 2 Aug, 15:50, Jizzai  wrote:
>
> >>> Is a _pure_ python program buffer overflow proof?
>
> >>> For example in C++ you can declare a char[9] to hold user input.
> >>> If the user inputs 10+ chars a buffer overflow occurs.
>
> >> Short answer: NO
> > I disagree. You've just translated the responsability to check for
> > buffer overflows, from the Python VM, to the Java VM or the .Net runtime
> > (and all three suffered from buffer overruns and other problems in some
> > way or another).
>
> ? ? A more useful question is whether the standard libraries are being
> run through any of the commercial static checkers for possible buffer
> overflows.
>
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? John Nagle

Python has been run through valgrind which did expose (and result in
the fixing) of several theoretical problems.

Pure Python can be crashed (cause segfaults) in various ways - there
is even a directory of tests that do this in the test suite. I don't
think any are due to buffer overflows.

Michael Foord
--
http://www.ironpythoninaction.com/


From mensanator at aol.com  Fri Aug  7 17:01:06 2009
From: mensanator at aol.com (Mensanator)
Date: Fri, 7 Aug 2009 14:01:06 -0700 (PDT)
Subject: Good news & bad news (was: Turtle Graphics are incompatible with 
	gmpy)
References: 
	<0002b5d3$0$2970$c3e8da3@news.astraweb.com>
	<4a7936a4$0$1552$91cee783@newsreader03.highway.telekom.at> 
	 
	<4A79C7E2.3000406@aon.at>
	
	 
	<49395cf2-c2fb-4fd9-b2f2-7f462abe8250@f37g2000yqn.googlegroups.com> 
	<4a7a28b3$0$2303$91cee783@newsreader01.highway.telekom.at> 
	
Message-ID: 

Bad news:

I ran the 2.5 turtle.py through the 2to3 refactorer but the
result would not run in 3.1, some kind of type mismatch between
ints and NoneType. So I set it aside.

Good news:

I tracked down the actual cause of the image discrepencies in my
report.

http://www.mensanator.com/mensanator/PythonTurtle/turtle.htm

These are completely bogus as it turns out. I had thought I was
essentially executing the same code (aside from changing 3.1
turtle functions that don't exist in 2.5 to their equivalent).

But in my mucking about tracking down the gmpy problem, a bug
crept in when I converted back from Python ints

  if side == 'northeast':
    elbow_offset = [int((gmpy.sqrt(elbow)-1)//2 +1),
                    -int(((gmpy.sqrt(elbow)-1)//2) +1)]
  else:
    elbow_offset = [-int(((gmpy.sqrt(elbow)-1)//2 +1)),
                    int(((gmpy.sqrt(elbow)-1)//2 +1))]

to gmpy ints.

  if side == 'northeast':
    elbow_offset = [(gmpy.sqrt(elbow)-1)//2 +1,
                    -((gmpy.sqrt(elbow)-1)//2) +1]
  else:
    elbow_offset = [-((gmpy.sqrt(elbow)-1)//2 +1),
                    ((gmpy.sqrt(elbow)-1)//2 +1)]

A ")" is mislocated in -((gmpy.sqrt(elbow)-1)//2) +1], the one
after "//2" should have been placed after the "+1". There were
still three matching sets, but the +1 was now happening after
the negation instead or prior to it. And, of course, this lead
to discrepencies in the calls to the turtle goto function.
And, luckily, the code chain for 2.5 originated from the version
prior to the introduction of this error, otherwise, if the same
error was in both, the images would have been identicle albeit
wrong.

So it looks like there is NO practical difference between the
2.5 algorithm and the 3.1 algorithm. I'm no longer going to try
to get the 2.5 turtle.py to work in 3.1.

And with the nhops calculation changed to

 nhops = 1+int((float(diffsq)**0.5)/(3*(1.1**self._speed)
*self._speed))

it no longer crashes in trace mode.

This was probably originally provoked by gmpy 1.10 and probably
isn't a problem in 2.6 with gmpy 1.04. I had upgraded my 2.6 gmpy
to 1.10 where it also crashed. I may have run the test code in
2.6 when I had 1.04 installed but it's unlikely I would have done
so with tracing on since it's 100 times slower. But I expect it
would not have failed due to this:


Changes in gmpy 1.10

Number conversion rules have changed.
-------------------------------------
The arguments in operations involving mixed types are converted
using the following rules:

   Integer --> Rational   --> Floating-point
    'int'       'Fraction'     'float'
    'long'      'mpq'          'Decimal'
    'mpz'                      'mpf'

   Old behavior:
     mpz(1) + float(1.2)     --> float(2.2)
     mpz(1) + Decimal('1.2') --> mpz(2)

   New behavior:
     mpz(1) + float(1.2)     --> mpf(2.2)
     mpz(1) + Decimal('1.2') --> mpf(2.2)


Apparently, as I painfully found out, that rule change can cause
applications to fail due to an mpf result from a mixed type function
instead of a float when they subsequently use fractional
exponentiation.



From duncan.booth at invalid.invalid  Fri Aug  7 17:04:15 2009
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 7 Aug 2009 21:04:15 GMT
Subject: Bug or feature: double strings as one
References: 
	
	<5Y2dnfnYAdsl0-HXnZ2dnUVZ_j9i4p2d@pdx.net>
	
Message-ID: 

Grant Edwards  wrote:

> Definitely.  Not only does it have _all_ the features, it even
> manages to simultaneously have several mutually-exclusive
> features.

Sounds a bit like Perl.


From jgardner at jonathangardner.net  Fri Aug  7 17:41:07 2009
From: jgardner at jonathangardner.net (Jonathan Gardner)
Date: Fri, 7 Aug 2009 14:41:07 -0700 (PDT)
Subject: unique-ifying a list
References: 
Message-ID: 

On Aug 7, 1:53?pm, kj  wrote:
> Suppose that x is some list. ?To produce a version of the list with
> duplicate elements removed one could, I suppose, do this:
>
> ? ? x = list(set(x))
>
> but I expect that this will not preserve the original order of
> elements.
>
> I suppose that I could write something like
>
> def uniquify(items):
> ? ? seen = set()
> ? ? ret = []
> ? ? for i in items:
> ? ? ? ? if not i in seen:
> ? ? ? ? ? ? ret.append(i)
> ? ? ? ? ? ? seen.add(i)
> ? ? return ret
>
> But this seems to me like such a commonly needed operation that I
> find it hard to believe one would need to resort to such self-rolled
> solutions. ?Isn't there some more standard (and hopefully more
> efficient, as in "C-coded"/built-in) approach?
>

Honestly, doing unique operations is pretty rare in the application
level. Unless you're writing some kind of database, I don't see why
you'd do it. (My recommendation is not to write databases.)

If you want unique elements, use a set. If you want to order them,
sort a list of the items in the set.

If you want to preserve the order, then using a dict may be even
better.

    orig_order = dict(reversed([reversed(i) for i in enumerate
(items)])
    unique_ordered = sorted(orig_order.keys(), key=lambda k: orig_order
[k])

Hints to understanding:
* enumerate generates (index, item) pairs.
* We reverse each pair so that we get an item -> index mapping.
* We reverse it so that the first ones appear last. Later pairs
override earlier ones in dict().


From jgardner at jonathangardner.net  Fri Aug  7 17:48:51 2009
From: jgardner at jonathangardner.net (Jonathan Gardner)
Date: Fri, 7 Aug 2009 14:48:51 -0700 (PDT)
Subject: syntax checker in python
References: 
Message-ID: <675fb1c7-1747-4a22-8d74-42affc1929bc@i4g2000prm.googlegroups.com>

On Aug 7, 1:39?pm, horos11  wrote:
> ps - I just realized that it isn't enough to do:
>
> python -c 'import /path/to/script'
>
> since that actually executes any statement inside of the script
> (wheras all I want to do is check syntax)
>
> So - let me reprhase that - exactly how can you do a syntax check in
> python? Something like perl's -c:
>
> ? ? ?perl -c script_name.p
>

You may want to read the sections under "Python Language Services" in
the Python Library Reference. There may be something you are looking
for there.


From no.email at please.post  Fri Aug  7 17:51:39 2009
From: no.email at please.post (kj)
Date: Fri, 7 Aug 2009 21:51:39 +0000 (UTC)
Subject: Why all the __double_underscored_vars__?
Message-ID: 



Python is chock-full of identifiers beginning and ending with double
underscores, such as __builtin__, __contains__, and __coerce__.

Using underscores to signal that an identifier is somehow "private"
to an implementation is pretty common in languages other than
Python.  But in these cases the understanding is that the use of
these variables in external code amounts to "going behind the API",
and is therefore unwise.

But as far as I can tell, Python's double-underscore variables are
very much part of Python's API.  E.g., programmers are specifically
instructed to override "double-underscore methods" to achieve
certain functionalities.

In this case, I wonder: what justifiies the double-underscore
convention?  For example, what would be the problem with changing
the name of the complex.__gt__ method to complex.gt?

TIA!

kynn


From hjtoi-better-remove-before-reply at comcast.net  Fri Aug  7 18:02:15 2009
From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen)
Date: Fri, 07 Aug 2009 15:02:15 -0700
Subject: Setuptools - help!
References: 
	
	<9fauk6-t24.ln1@phoenix.fire>
Message-ID: 

Peter Chant wrote:
> Thanks, it worked.  Any ideas how to run the resulting scripts without
> installing or running as root?

If you install as root, you should be able to run the scripts as normal
user. However, I don't recommend this approach since it could conflict
with your system Python packages.

I like using virtualenv to create isolated Python environments. I can
easily install whatever Python packages I want into each environment,
delete them when I am done with them or messed up etc.

http://pypi.python.org/pypi/virtualenv

-- 
  Heikki Toivonen - http://heikkitoivonen.net


From clp2 at rebertia.com  Fri Aug  7 18:13:41 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Fri, 7 Aug 2009 18:13:41 -0400
Subject: Why all the __double_underscored_vars__?
In-Reply-To: 
References: 
Message-ID: <50697b2c0908071513m2e25009dv7bd61e7b20a9094a@mail.gmail.com>

On Fri, Aug 7, 2009 at 5:51 PM, kj wrote:
> Python is chock-full of identifiers beginning and ending with double
> underscores, such as __builtin__, __contains__, and __coerce__.
>
> Using underscores to signal that an identifier is somehow "private"
> to an implementation is pretty common in languages other than
> Python. ?But in these cases the understanding is that the use of
> these variables in external code amounts to "going behind the API",
> and is therefore unwise.
>
> But as far as I can tell, Python's double-underscore variables are
> very much part of Python's API. ?E.g., programmers are specifically
> instructed to override "double-underscore methods" to achieve
> certain functionalities.

Right, but the *users* of the functionality provided by __methods__
typically should not invoke such methods directly.
For example, one should write `a > b`, not `a.__gt__(b)`. The lack of
underscores in just plain `gt` would suggest that it's a normal method
that could/should be called directly. Also, if the underscore
requirement were removed, then people might unknowingly overload an
operator without knowing it.
The double-underscores indicate that the Python interpreter itself
usually is the caller of the method, and as such some level of "magic"
may be associated with it. Other languages have you do the equivalent
of `def +():` or `def operator +()` to override an operator, the
keyword or symbol serving a similar warning that "here be magic". To
avoid adding another keyword and the confusion of having punctuation
as method names, Python uses a different convention, double leading
and trailing underscores.

Cheers,
Chris
-- 
http://blog.rebertia.com


From labjacksupport at gmail.com  Fri Aug  7 18:16:57 2009
From: labjacksupport at gmail.com (LabJack Support)
Date: Fri, 7 Aug 2009 15:16:57 -0700 (PDT)
Subject: ValueError: Procedure probably called with not enough arguments (8 
	bytes missing)
Message-ID: 

Hello! I am chasing around a problem that I am having with ctypes and
I am hoping someone can help out. Here is the Python code:

    def asynch(self, baudrate, data, idNum=None, demo=0, portB=0,
enableTE=0, enableTO=0, enableDel=0, numWrite=0, numRead=0):
        """
        Name: U12.asynchConfig(fullA, fullB, fullC, halfA, halfB,
halfC, idNum=None, demo=None, timeoutMult=1, configA=0, configB=0,
configTE=0)
        Args: See section 4.12 of the User's Guide
        Desc: Requires firmware V1.1 or higher. This function writes
to the asynch registers and sets the direction of the D lines (input/
output) as needed.

        >>> dev = U12()
        >>> dev.asynchConfig(96,1,1,22,2,1)
        >>> {'idNum': 1}
        """

        #Check id number
        if idNum is None:
            idNum = self.id
        idNum = ctypes.c_long(idNum)

        # Check size of data
        if len(data) > 18: raise ValueError("data can not be larger
than 18 elements")

        # Make data 18 elements large
        dataArray = [0] * 18
        for i in range(0, len(data)):
            dataArray[i] = data[i]
        print dataArray
        dataArray = listToCArray(dataArray, ctypes.c_long)

        ecode = staticLib.AsynchConfig(ctypes.byref(idNum), demo,
portB, enableTE, enableTO, enableDel, baudrate, numWrite, numRead,
ctypes.byref(dataArray))

        if ecode != 0:print ecode # TODO: Switch this out for
exception

        return {"idnum":long, "data":dataArray}

Here is the method signature of the c function:

long Asynch(	long *idnum,
				long demo,
				long portB,
				long enableTE,
				long enableTO,
				long enableDel,
				long baudrate,
				long numWrite,
				long numRead,
				long *data)

Thank you in advance,
Sam


From labjacksupport at gmail.com  Fri Aug  7 18:17:52 2009
From: labjacksupport at gmail.com (LabJack Support)
Date: Fri, 7 Aug 2009 15:17:52 -0700 (PDT)
Subject: ValueError: Procedure probably called with not enough arguments 
	(8 bytes missing)
References: eb8393e4-d923-4c27-a98c-1c370522c510@p28g2000vbn.googlegroups.com
Message-ID: <38bd8e73-77cb-49e2-8014-42dad28fc987@d21g2000vbm.googlegroups.com>

On Aug 7, 4:16?pm, LabJack Support  wrote:
> Hello! I am chasing around a problem that I am having with ctypes and
> I am hoping someone can help out. Here is the Python code:
>
> ? ? def asynch(self, baudrate, data, idNum=None, demo=0, portB=0,
> enableTE=0, enableTO=0, enableDel=0, numWrite=0, numRead=0):
> ? ? ? ? """
> ? ? ? ? Name: U12.asynchConfig(fullA, fullB, fullC, halfA, halfB,
> halfC, idNum=None, demo=None, timeoutMult=1, configA=0, configB=0,
> configTE=0)
> ? ? ? ? Args: See section 4.12 of the User's Guide
> ? ? ? ? Desc: Requires firmware V1.1 or higher. This function writes
> to the asynch registers and sets the direction of the D lines (input/
> output) as needed.
>
> ? ? ? ? >>> dev = U12()
> ? ? ? ? >>> dev.asynchConfig(96,1,1,22,2,1)
> ? ? ? ? >>> {'idNum': 1}
> ? ? ? ? """
>
> ? ? ? ? #Check id number
> ? ? ? ? if idNum is None:
> ? ? ? ? ? ? idNum = self.id
> ? ? ? ? idNum = ctypes.c_long(idNum)
>
> ? ? ? ? # Check size of data
> ? ? ? ? if len(data) > 18: raise ValueError("data can not be larger
> than 18 elements")
>
> ? ? ? ? # Make data 18 elements large
> ? ? ? ? dataArray = [0] * 18
> ? ? ? ? for i in range(0, len(data)):
> ? ? ? ? ? ? dataArray[i] = data[i]
> ? ? ? ? print dataArray
> ? ? ? ? dataArray = listToCArray(dataArray, ctypes.c_long)
>
> ? ? ? ? ecode = staticLib.AsynchConfig(ctypes.byref(idNum), demo,
> portB, enableTE, enableTO, enableDel, baudrate, numWrite, numRead,
> ctypes.byref(dataArray))
>
> ? ? ? ? if ecode != 0:print ecode # TODO: Switch this out for
> exception
>
> ? ? ? ? return {"idnum":long, "data":dataArray}
>
> Here is the method signature of the c function:
>
> long Asynch( ? ?long *idnum,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long demo,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long portB,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long enableTE,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long enableTO,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long enableDel,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long baudrate,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long numWrite,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long numRead,
> ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? long *data)
>
> Thank you in advance,
> Sam

Whoops I am sorry. The problem was due to a typo.


From bearophileHUGS at lycos.com  Fri Aug  7 19:04:19 2009
From: bearophileHUGS at lycos.com (Bearophile)
Date: Fri, 7 Aug 2009 16:04:19 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
Message-ID: 

durumdara:
> I wanna ask that is a bug or is it a feature?

For me it's a bug-prone antifeature.

Bye,
bearophile


From rt8396 at gmail.com  Fri Aug  7 19:40:14 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 16:40:14 -0700 (PDT)
Subject: Why all the __double_underscored_vars__?
References: 
	
Message-ID: 

On Aug 7, 5:13?pm, Chris Rebert  wrote:
> On Fri, Aug 7, 2009 at 5:51 PM, kj wrote:
> > Python is chock-full of identifiers beginning and ending with double
> > underscores, such as __builtin__, __contains__, and __coerce__.
...(snip)
> Right, but the *users* of the functionality provided by __methods__
...(snip)
> Cheers,
> Chris

Yes and Python's way is by-far the proper way to handle such
functionailty. Don't thank god, thank Guido


From sjmachin at lexicon.net  Fri Aug  7 19:46:03 2009
From: sjmachin at lexicon.net (John Machin)
Date: Fri, 7 Aug 2009 16:46:03 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	  
	<1de1eadf-6a2a-414c-a7cf-cf235edadcfb@a39g2000pre.googlegroups.com>
Message-ID: 

On Aug 8, 3:43?am, alex23  wrote:
> kj  wrote:
> > Feature, as others have pointed out, though I fail to see the need
> > for it, given that Python's general syntax for string (as opposed
> > to string literal) concatenation is already so convenient. ?I.e.,
> > I fail to see why
>
> > x = ("first part of a very long string "
> > ? ? ?"second part of a very long string")
>
> > is so much better than
>
> > x = ("first part of a very long string " +
> > ? ? ?"second part of a very long string")
>
> My impression is it's mostly for one of clarity. It's especially
> useful with regular expressions, as it allows for comments to document
> each element of the regex (following example shamelessly taken from
> the docs (albeit with personal preferences on formatting))):
>
> re.compile(
> ? ? "[A-Za-z_]" ? ? ? # letter or underscore
> ? ? "[A-Za-z0-9_]*" ? # letter, digit or underscore
> )
>
> Not having the plus sign present does assist (IMO) in the ease of
> parsing the regex.
> re.compile(

re.VERBOSE?


From piet at cs.uu.nl  Fri Aug  7 20:03:54 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Sat, 08 Aug 2009 02:03:54 +0200
Subject: help with threads
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
	<949b87d5-8cff-444a-b6ba-23d49610d130@p36g2000vbn.googlegroups.com>
	
Message-ID: 

>>>>> Michael Mossey  (MM) wrote:

>MM> Ah yes, that explains it. Some of these long computations are done in
>MM> pure C, so I'm sure the GIL is not being released.

Is that C code under your own control? Or at least the glue from Python
to C? In that case, and if the C code is not manipulating Python objects
or something in the Python interpreter, it could be changed to release
the GIL during the computation. That's also how Numpy does it, IIRC.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From rt8396 at gmail.com  Fri Aug  7 20:11:01 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 17:11:01 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
Message-ID: <5ba3a8f0-bdff-4ae7-bff4-abacf559d3a6@p23g2000vbl.googlegroups.com>

On Aug 7, 7:31?am, durumdara  wrote:
> Hi!
>
> I found an interesting thing in Python.
> Today one of my "def"s got wrong result.
...(snip)

I think it's a completely useless feature and i have never used it
even once! This so-called "feature" seems a direct  contridiction to
the zen...

"""There should be one-- and preferably only one --obvious way to do
it. """


From deets at nospam.web.de  Fri Aug  7 20:31:48 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sat, 08 Aug 2009 02:31:48 +0200
Subject: syntax checker in python
In-Reply-To: 
References: 
Message-ID: <7e3vblF2ea3orU1@mid.uni-berlin.de>

horos11 schrieb:
> ps - I just realized that it isn't enough to do:
> 
> python -c 'import /path/to/script'
> 
> since that actually executes any statement inside of the script
> (wheras all I want to do is check syntax)
> 
> So - let me reprhase that - exactly how can you do a syntax check in
> python? Something like perl's -c:

See pylint & pychecker.

Diez



From rt8396 at gmail.com  Fri Aug  7 20:33:09 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 17:33:09 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> 
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro 
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com> 
	
	 
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com> 
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
Message-ID: <0242fc66-2b78-4494-a133-43aff6a86353@p9g2000vbl.googlegroups.com>

On Aug 7, 3:35?pm, Kee Nethery  wrote:
(snip)

Kee,
that was an eloquent and enlighting post and i think it speaks volumes
to the lack of inclusion of all Pythoneers in this community. Not to
mention the viscous attitudes and self indulgence we have around here.

For those of you with ADD, Kee was speaking to the hurdles one must
overcome to change even the most minor things within this community.
Change around here almost parallels an act-of-congress with it's de-
motivating burdens that beset a new python user who may wish to add
his or her 2 pennies to the Python wishing well. And i believe like
Kee, most of them just give up and say
   """Oh Well, F### it!"""

Not to mention the never ending droves of naysayers, bullies, smart-
arses, and egomaniacs with their minions and sock-puppets ready at
moments notice to pounce on (and utterly destroy) any feeble noob who
dares to try and enhance the user experience in Python for all of us.



From nobody at nowhere.com  Fri Aug  7 20:40:51 2009
From: nobody at nowhere.com (Nobody)
Date: Sat, 08 Aug 2009 01:40:51 +0100
Subject: Executing untrusted code
References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com>
Message-ID: 

On Fri, 07 Aug 2009 08:15:08 -0700, Emanuele D'Arrigo wrote:

> Are
> there best practices to at least minimize some of the risks associated
> with untrusted code execution?

Yes: don't execute it. Failing that, run the Python interpreter within a
sandbox.

If you want to support restricted execution within a language, it has to
be built into the language from day one. Trying to bolt it on later is a
fool's errand.



From rt8396 at gmail.com  Fri Aug  7 20:54:40 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 17:54:40 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	<5ba3a8f0-bdff-4ae7-bff4-abacf559d3a6@p23g2000vbl.googlegroups.com>
Message-ID: 

It sure doesn't get any more obivous than...
  "string1" + "string2"

Although i much prefer string formatting to concatenation for almost
all cases except the most simple. This auto-magic conacatenation of
strings is unintuitive and completely moronic if you ask my opinion. I
blow chunks when i see this type of code, and the result from it, and
so should my interpretor!
  "string1" "string2" --> syntax error you moron!

If you are wanting to create shortcuts, do them where they make sense
and can serve a useful purpose...

t = ('1' "word" 33.3)
l = [1 2 3 (4 5)]
d = {keyname:value keyname:value etc...}

KISS people!


From gagsl-py2 at yahoo.com.ar  Fri Aug  7 21:10:33 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 22:10:33 -0300
Subject: unique-ifying a list
References: 
Message-ID: 

En Fri, 07 Aug 2009 17:53:10 -0300, kj  escribi?:

> Suppose that x is some list.  To produce a version of the list with
> duplicate elements removed one could, I suppose, do this:
>
>     x = list(set(x))
>
> but I expect that this will not preserve the original order of
> elements.
>
> I suppose that I could write something like
>
> def uniquify(items):
>     seen = set()
>     ret = []
>     for i in items:
>         if not i in seen:
>             ret.append(i)
>             seen.add(i)
>     return ret

Assuming the elements are hashable, yes, that's the fastest way (minus
some microoptimizations like using local names for ret.append and
seen.add, or the 'not in' operator).

See bearophile's recipe [1], another one [2] by Tim Peters (quite old but
worths reading the comment section), and this thread [3]

[1] http://code.activestate.com/recipes/438599/
[2] http://code.activestate.com/recipes/52560/
[3] http://groups.google.com/group/comp.lang.python/t/40c6c455f4fd5154/

-- 
Gabriel Genellina



From gagsl-py2 at yahoo.com.ar  Fri Aug  7 21:10:39 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 22:10:39 -0300
Subject: Is "feedparser" deprecated?
References: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
Message-ID: 

En Fri, 07 Aug 2009 16:07:48 -0300, John Nagle 
escribi?:

>    Feedparser requires SGMLlib, which has been removed from Python 3.0.
> Feedparser hasn't been updated since 2007. Does this mean Feedparser
> is dead?

Since we have generic and easy of use XML parsers like ElementTree and
lxml,  specialized rss parsers like feedparser are not so much required.
I've used ElementTree when I had to parse an rss feed in the past (not so
many times).

-- 
Gabriel Genellina



From gagsl-py2 at yahoo.com.ar  Fri Aug  7 21:16:06 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 07 Aug 2009 22:16:06 -0300
Subject: importing fully qualified scripts to check syntax
References: 
Message-ID: 

En Fri, 07 Aug 2009 17:29:28 -0300, horos11  escribi?:

> I'm trying to make a syntax checker, where I say:
>
> python -c "import /path/to/script"
>
> to check the syntax of the script named '/path/to/script' (note: no py
> extension needed). Of course this doesn't work because the
> functionality for import is bundled up with the environment..

Try the py_compile module in the standard library:
http://docs.python.org/library/

The import statement does more than just checking syntax. You may want to  
start the interpreter with the -tt option also.

-- 
Gabriel Genellina



From steve at REMOVE-THIS-cybersource.com.au  Fri Aug  7 22:04:58 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 08 Aug 2009 02:04:58 GMT
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
Message-ID: <0006608d$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 12:00:42 +0200, Thorsten Kampe wrote:

> Bollocks. No one will even notice whether a code sequence runs 2.7 or
> 5.7 seconds. That's completely artificial benchmarking.

You think users won't notice a doubling of execution time? Well, that 
explains some of the apps I'm forced to use...

A two-second running time for (say) a command-line tool is already 
noticeable. A five-second one is *very* noticeable -- long enough to be a 
drag, short enough that you aren't tempted to go off and do something 
else while you're waiting for it to finish.


-- 
Steven


From Dave  Fri Aug  7 23:05:20 2009
From: Dave (Dave)
Date: Fri, 07 Aug 2009 22:05:20 -0500
Subject: Windows 7 : any problems installing or running Python ?
Message-ID: 

Anybody tried it ? 
Is anything broken, ie is the whole shootin' match good to go ?
I'm esp interested in WConio for 3.0/3.1 which I use heavily.
Thanks                              Dave     pdlemper at earthlink.net

                               " I saw the number 4 in silver "  Guido
                                   ( apologies to Wm Carlos Williams )


From n179911 at gmail.com  Fri Aug  7 23:29:06 2009
From: n179911 at gmail.com (n179911)
Date: Fri, 7 Aug 2009 20:29:06 -0700 (PDT)
Subject: How to address a global variable in a function
Message-ID: <82c2f2e7-ed3e-482b-9318-d5539a2a9da8@y10g2000prg.googlegroups.com>

HI,

I have a global variable

// line 8
tx  = 0

and then I have this function (start in line 12):
def handleTranslate(result):
	print line
	txStr, tyStr = result.group(1), result.group(2)
	print txStr, tyStr

	tx += int(txStr)
	ty += int(tyStr)

	return

But I am getting this error:
    handleTranslate(result)
  File "buildsvg.py", line 22, in handleTranslate
    tx += int(txStr)
UnboundLocalError: local variable 'tx' referenced before assignment

How can I fix it?
I have assigned 'tx' to 0 in line 8. I don't understand why i get this
error.

Thank you for any help.



From steve at REMOVE-THIS-cybersource.com.au  Fri Aug  7 23:29:43 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 08 Aug 2009 03:29:43 GMT
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
Message-ID: <0006746a$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 17:13:07 +0200, Thorsten Kampe wrote:

> One guy claims he has times between 2.7 and 5.7 seconds when
> benchmarking more or less randomly generated "one million different
> lines". That *is* *exactly* nothing.


We agree that in the grand scheme of things, a difference of 2.7 seconds 
versus 5.7 seconds is a trivial difference if your entire program takes 
(say) 8 minutes to run. You won't even notice it.

But why assume that the program takes 8 minutes to run? Perhaps it takes 
8 seconds to run, and 6 seconds of that is the decoding. Then halving 
that reduces the total runtime from 8 seconds to 5, which is a noticeable 
speed increase to the user, and significant if you then run that program 
tens of thousands of times.

The Python dev team spend significant time and effort to get improvements 
of the order of 10%, and you're pooh-poohing an improvement of the order 
of 100%. By all means, reminding people that pre-mature optimization is a 
waste of time, but it's possible to take that attitude too far to Planet 
Bizarro. At the point that you start insisting, and emphasising, that a 
three second time difference is "*exactly*" zero, it seems to me that 
this is about you winning rather than you giving good advice.



-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Fri Aug  7 23:29:59 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 08 Aug 2009 03:29:59 GMT
Subject: PEP 8 exegetics: conditional imports?
References: 
Message-ID: <0006747a$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 16:50:12 +0000, kj wrote:

> I seek the wisdom of the elders.  Is there a consensus on the matter of
> conditional imports?  Are they righteous?  Or are they the way of the
> wicked?

Being an elder doesn't grant you wisdom. It just might mean you've been 
stupid and ignorant for a long time.

For what it's worth, you can take my conditional imports when you've 
pried them from my cold, dead hands.



-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Fri Aug  7 23:31:31 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 08 Aug 2009 03:31:31 GMT
Subject: Bug or feature: double strings as one
References: 
	 
Message-ID: <000674d6$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 17:35:28 +0000, kj wrote:

> I fail to see why
> 
> x = ("first part of a very long string "
>      "second part of a very long string")

That's done by the compiler at compile time and is fast.

> is so much better than
> 
> x = ("first part of a very long string " +
>      "second part of a very long string")

That's done by the Python virtual machine at runtime and creates two 
strings, then passes them to a method, which creates a third string, then 
(usually) disposes of the first two strings.

Except for some versions of the CPython implementation, which has a 
keyhole compiler which folds constants at runtime. But it's a simple 
optimizer, easy to defeat:

>>> import dis
>>> dis.dis(compile("s = ''; s + 'a' + 'b'", '', 'exec'))
  1           0 LOAD_CONST               0 ('')
              3 STORE_NAME               0 (s)
              6 LOAD_NAME                0 (s)
              9 LOAD_CONST               1 ('a')
             12 BINARY_ADD
             13 LOAD_CONST               2 ('b')
             16 BINARY_ADD
             17 POP_TOP
             18 LOAD_CONST               3 (None)
             21 RETURN_VALUE
>>>
>>> dis.dis(compile("s = ''; s + 'a' 'b'", '', 'exec'))
  1           0 LOAD_CONST               0 ('')
              3 STORE_NAME               0 (s)
              6 LOAD_NAME                0 (s)
              9 LOAD_CONST               1 ('ab')
             12 BINARY_ADD
             13 POP_TOP
             14 LOAD_CONST               2 (None)
             17 RETURN_VALUE



-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Fri Aug  7 23:31:46 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 08 Aug 2009 03:31:46 GMT
Subject: how to overload operator "< <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
	
Message-ID: <000674e5$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 08:04:22 -0700, Scott David Daniels wrote:

> Benjamin Kaplan wrote:
>> .... Python does not support compound comparisons like that. You have
>> to do "a > b and b > c".
> 
> Funny, my python does.  This has been around a long time. I am not
> certain whether 1.5.2 did it, but "chained comparisons" have been around
> for a long time.

Yes it does:

$ python1.5
Python 1.5.2 (#1, Apr  1 2009, 22:55:54)  [GCC 4.1.2 20070925 (Red Hat 
4.1.2-27)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>>
>>> 2 < 3 < 4
1


Remembering that back then, 0 and 1 were used instead of False and True.


-- 
Steven


From pavlovevidence at gmail.com  Sat Aug  8 00:01:47 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 7 Aug 2009 21:01:47 -0700 (PDT)
Subject: how to overload operator "< <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
	
	<7e2regF2eqbabU1@mid.uni-berlin.de>
Message-ID: <429efe93-afd0-4d46-973c-0df0d4f42c0c@p9g2000vbl.googlegroups.com>

On Aug 7, 7:18?am, "Diez B. Roggisch"  wrote:
> alex23 schrieb:
>
>
>
>
>
> > On Aug 7, 10:50 pm, Benjamin Kaplan  wrote:
> >> That isn't an operator at all. Python does not support compound
> >> comparisons like that. You have to do "a > b and b > c".
>
> > You know, it costs nothing to open up a python interpreter and check
> > your certainty:
>
> >>>> x = 10
> >>>> 1 < x < 20
> > True
>
> > This is a _very_ common pattern.
>
> >>>> class X(object):
> > ... ? def __lt__(self, other):
> > ... ? ? print 'in lt'
> > ... ? ? return True
> > ... ? def __gt__(self, other):
> > ... ? ? print 'in gt'
> > ... ? ? return True
> > ...
> >>>> x = X()
> >>>> 1 < x < 20
> > in gt
> > in lt
> > True
> >>>> 20 < x < 1
> > in gt
> > in lt
> > True
>
> > dmitrey: Diez' advice was the best you received.
>
> Not really. I didn't get the chaining, and Peter is right that for that
> there is no real overloading.

You can program __lt__, __gt__, and friends to return a closure with a
boolean value.  See my upcoming reply to the author.


Carl Banks


From pavlovevidence at gmail.com  Sat Aug  8 00:10:35 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 7 Aug 2009 21:10:35 -0700 (PDT)
Subject: how to overload operator "< <" (a < x < b)?
References: <53eb4291-9a78-489a-9a5d-396ec8a9c2af@l31g2000vbp.googlegroups.com>
	
	
	<7e2regF2eqbabU1@mid.uni-berlin.de>
	<429efe93-afd0-4d46-973c-0df0d4f42c0c@p9g2000vbl.googlegroups.com>
Message-ID: <241f44f0-cd5c-48cd-a5ac-7a51954809fe@p23g2000vbl.googlegroups.com>

On Aug 7, 9:01?pm, Carl Banks  wrote:
> On Aug 7, 7:18?am, "Diez B. Roggisch"  wrote:
>
>
>
>
>
> > alex23 schrieb:
>
> > > On Aug 7, 10:50 pm, Benjamin Kaplan  wrote:
> > >> That isn't an operator at all. Python does not support compound
> > >> comparisons like that. You have to do "a > b and b > c".
>
> > > You know, it costs nothing to open up a python interpreter and check
> > > your certainty:
>
> > >>>> x = 10
> > >>>> 1 < x < 20
> > > True
>
> > > This is a _very_ common pattern.
>
> > >>>> class X(object):
> > > ... ? def __lt__(self, other):
> > > ... ? ? print 'in lt'
> > > ... ? ? return True
> > > ... ? def __gt__(self, other):
> > > ... ? ? print 'in gt'
> > > ... ? ? return True
> > > ...
> > >>>> x = X()
> > >>>> 1 < x < 20
> > > in gt
> > > in lt
> > > True
> > >>>> 20 < x < 1
> > > in gt
> > > in lt
> > > True
>
> > > dmitrey: Diez' advice was the best you received.
>
> > Not really. I didn't get the chaining, and Peter is right that for that
> > there is no real overloading.
>
> You can program __lt__, __gt__, and friends to return a closure with a
> boolean value. ?See my upcoming reply to the author.

Actually, scratch that.  It won't work because the chained comparison
short-circuits.  If you have __lt__ return a closure then a < b won't
work unless a < b is always true, which means it'll cause ordinary
binary comparison to fail.  Oh well.


Carl Banks


From n179911 at gmail.com  Sat Aug  8 00:14:37 2009
From: n179911 at gmail.com (n179911)
Date: Fri, 7 Aug 2009 21:14:37 -0700 (PDT)
Subject: How to address a global variable in a function
References: <82c2f2e7-ed3e-482b-9318-d5539a2a9da8@y10g2000prg.googlegroups.com>
Message-ID: 

On Aug 7, 8:29?pm, n179911  wrote:
> HI,
>
> I have a global variable
>
> // line 8
> tx ?= 0
>
> and then I have this function (start in line 12):
> def handleTranslate(result):
> ? ? ? ? print line
> ? ? ? ? txStr, tyStr = result.group(1), result.group(2)
> ? ? ? ? print txStr, tyStr
>
> ? ? ? ? tx += int(txStr)
> ? ? ? ? ty += int(tyStr)
>
> ? ? ? ? return
>
> But I am getting this error:
> ? ? handleTranslate(result)
> ? File "buildsvg.py", line 22, in handleTranslate
> ? ? tx += int(txStr)
> UnboundLocalError: local variable 'tx' referenced before assignment
>
> How can I fix it?
> I have assigned 'tx' to 0 in line 8. I don't understand why i get this
> error.
>
> Thank you for any help.

I figure out my problem

put this in my function:
global tx


From clp2 at rebertia.com  Sat Aug  8 00:14:58 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Sat, 8 Aug 2009 00:14:58 -0400
Subject: How to address a global variable in a function
In-Reply-To: <82c2f2e7-ed3e-482b-9318-d5539a2a9da8@y10g2000prg.googlegroups.com>
References: <82c2f2e7-ed3e-482b-9318-d5539a2a9da8@y10g2000prg.googlegroups.com>
Message-ID: <50697b2c0908072114y2676738fm48461973a03e472b@mail.gmail.com>

On Fri, Aug 7, 2009 at 11:29 PM, n179911 wrote:
> HI,
>
> I have a global variable
>
> // line 8
> tx ?= 0
>
> and then I have this function (start in line 12):
> def handleTranslate(result):
> ? ? ? ?print line
> ? ? ? ?txStr, tyStr = result.group(1), result.group(2)
> ? ? ? ?print txStr, tyStr
>
> ? ? ? ?tx += int(txStr)
> ? ? ? ?ty += int(tyStr)
>
> ? ? ? ?return
>
> But I am getting this error:
> ? ?handleTranslate(result)
> ?File "buildsvg.py", line 22, in handleTranslate
> ? ?tx += int(txStr)
> UnboundLocalError: local variable 'tx' referenced before assignment
>
> How can I fix it?
> I have assigned 'tx' to 0 in line 8. I don't understand why i get this
> error.

By default, Python assumes that any variables assigned to in a
function are local variables. To change this assumption, you need to
declare that you want to reference a global variable. This is done by
putting a `global` statement at the start of the function (i.e.
`global tx`).

In the future, you might STFW (in this case, for "UnboundLocalError")
before posting to the newsgroup, as you would have found several
explanations of this common newbie-biter.

Cheers,
Chris
-- 
http://blog.rebertia.com


From steve at REMOVE-THIS-cybersource.com.au  Sat Aug  8 00:25:31 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 08 Aug 2009 04:25:31 GMT
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
Message-ID: <0006817d$0$2895$c3e8da3@news.astraweb.com>

On Fri, 07 Aug 2009 13:35:26 -0700, Kee Nethery wrote:


> > Why exactly is posting an open comment on a bug tracker somehow
> > inferior to posting an open comment on a wiki?
> 
> It's a good question and deserves a good answer.
> 
> * Fewer Steps
> * Immediate
> * Does not need to be formally reviewed
> * Easier to search

The last one is actually wrong, because the Python bug tracker is indexed 
by Google.

As for the rest, you're right that the current bug-tracker puts up 
barriers to people submitting comments and bugs. That's actually a good 
thing. The only thing worse than not enough information is too much 
information, and the current situation does a good job of discouraging 
the sorts of people who submit bad bug reports (e.g. duplicates of bug 
reports, bug reports for things fixed years ago, bug reports that are due 
to mistakes in their code, etc.).


> For example  
> purposes, I'll use the following page:
> http://docs.python.org/reference/lexical_analysis.html
> Lets say the user is in section 2.1.3 Comments

Disclaimer: python.org is down at the moment, so I can't check that page 
to see precisely what you're talking about.


> Here's the scenario: The user wanted to include "#" in one of their
> strings and the IDE kept interpreting it as a comment. But they really
> need to use that character in the string. Eventually they find out that
> they can escape the character in their string so that Python stops
> thinking it is the beginning of a comment.

Er, that would be a bug in the IDE, surely? Inside strings, # is an 
ordinary character with no special meaning.


>>> s = "this is a string with an unescaped # in it"
>>> s
'this is a string with an unescaped # in it'


The Python docs are supposed to be about Python the language, not work-
arounds for IDE bugs.


[...]
> Lets assume that Python experts all agree that  
> the docs should get updated with this gotcha (which as a newbie, they  
> are not sure that is a valid assumption and would probably just halt  
> in their quest to get the docs updated).

Good.

As a newbie, you SHOULD assume that anything you think is a bug is 
probably a bug in YOUR code, not Python, and the same goes for 
documentation bugs. If you don't understand something in the docs, 
chances are that it's a problem with you, not the docs. Your first port 
of call should be the tutor list, or here, and not to "fix" the docs by 
putting in noise that just gets in the way of the intended audience, 
namely experienced developers.


> and there is zero confidence that as a newbie, anyone cares about what  
> they found confusing, after all, they are just a newbie and not worthy  
> of altering the documentation. (Certainly that opinion has been  
> expressed several times on this mailing list).

No, we care. We just don't want to have the docs filled with all the hand-
holding and introductory stuff which the newbie needs. As a developer, 
you will outgrow the need for training wheels. Why force training wheels 
on the docs that you will be referring to for your entire career as a 
programmer, when you only need them for the first few months? There are 
plenty of docs aimed at newbies, and mailing lists where you can ask 
questions.

Putting user-comments on a separate page separates the noisy, low-value 
comments from the good stuff, but it increases the efforts needed by the 
webpage admin (who is going to deal with the comment spam? who is going 
to go through the user-comments stripping out the total nonsense put in 
by helpful ignoramuses?). It works for Wikipedia, because there are tens 
of thousands of users contributing small amounts of effort, and hundreds 
putting in a lot of effort, but even there there is a major problem with 
vandalism. We don't have those resources.

By the way, if a person wants to contribute, and can demonstrate 
competence, reliability, good-sense and trustworthiness, there's no 
reason why he or she couldn't get a check-in account for the Python docs. 
(All the Python docs are written by volunteers.) A good way to 
demonstrate these things is by submitting good-quality doc improvements 
to the bug-tracker. If a person can't be bothered to do so, because it 
requires effort to get an account, that goes a long way to demonstrating 
the *lack* of reliability which will disqualify them from the job.


> Very few people would think to search the bug tracking system for help  
> with some specific function. If someone is having trouble with the #  
> sign in their strings, the bug tracking system is not going to be at  
> the top of their list for search locations, especially when the bug  
> tracking system is not mentioned and when found requires a confirmed  
> login.

You don't need a login to view bug reports, only to modify them.

If you want an open-access documentation system go right ahead and build 
one. There are plenty of wikis available to use, and the Python docs are 
freely available as your starting point. I might even contribute myself. 
I just don't want it mixed in with the official docs: I want a clear 
separation between what's officially sanctioned and what's not.


-- 
Steven


From pavlovevidence at gmail.com  Sat Aug  8 00:46:51 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 7 Aug 2009 21:46:51 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> 
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro 
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com> 
	
	 
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com> 
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com>
Message-ID: 

On Aug 7, 9:25?pm, Steven D'Aprano  wrote:
> If you want an open-access documentation system go right ahead and build
> one. There are plenty of wikis available to use, and the Python docs are
> freely available as your starting point. I might even contribute myself.
> I just don't want it mixed in with the official docs: I want a clear
> separation between what's officially sanctioned and what's not.

The PyGame documentation has a "Click to view comments" box.  That
would be A. low profile, and B. distinct from official documentation
enough for me.

It'd probably be useful, but might also attract spam and lots of
useless fluff, because it's likely to be much higher volume than
documentation on other projects.


Carl Banks


From http  Sat Aug  8 01:06:23 2009
From: http (Paul Rubin)
Date: 07 Aug 2009 22:06:23 -0700
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com>
Message-ID: <7xd476rj1s.fsf@ruckus.brouhaha.com>

Steven D'Aprano  writes:
> As for the rest, you're right that the current bug-tracker puts up 
> barriers to people submitting comments and bugs. That's actually a good 
> thing. The only thing worse than not enough information is too much 
> information, and the current situation does a good job of discouraging 
> the sorts of people who submit bad bug reports (e.g. duplicates of bug 
> reports, bug reports for things fixed years ago, bug reports that are due 
> to mistakes in their code, etc.).

Stephen, Alex, etc.: have you actually used the php.net doc system?
Don't knock it til you've tried it.  IMO it is superior to Python's
system.  I don't use PHP much these days.


From http  Sat Aug  8 01:09:23 2009
From: http (Paul Rubin)
Date: 07 Aug 2009 22:09:23 -0700
Subject: question: why isn't a byte of a hash more uniform? how could I
	improve my code to cure that?
References: 
	
Message-ID: <7x8whuriws.fsf@ruckus.brouhaha.com>

L?szl? S?ndor  writes:
> OK, I understand. Could anyone suggest a better way to do this, then?
> 
> (Recap: random-looking, close-to uniform assignment of one number out
> of four possibilities to strings.)

Use a cryptographic hash function like md5 (deprecated for security
purposes but should be ok for this application).  The built-in Python
hash function is made for hashing symbols and is designed to avoid
collisions when you have a bunch of sequential identifiers (a,b,c...).
That is, it deliberately does NOT resemble a random function, which
would have a certain number of collisions by chance.


From rt8396 at gmail.com  Sat Aug  8 01:10:32 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 22:10:32 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	  
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
Message-ID: <14b5efce-e0b8-4455-ba9e-43b4b0df5e20@g6g2000vbr.googlegroups.com>

On Aug 7, 10:31?pm, Steven D'Aprano  wrote:
...(snip excessive showmanship) :-)

Ah Steven thats a real nice "snappy comeback" and some may get blinded
by the "black magic" but basically all you are saying is that "version
a" takes less overhead than "version b", compilation wise... but let's
dig a little deeper shall we?

First of all, i don't know about you but i don't set around all day
hard coding string data into my programs so the nano second difference
gained between auto-magic-string-concatination and "s1"+"s2"+"sN"
really doesn't justify a feature(bug??) like this that breaks the Zen
wide open. Sadly all it serves is to confuse new comers and contribute
line noise to the tutorial -- of which there is too much already!

Sure it's a nice parlor trick, but not much more...

Q: Steven, how often do you actually use this feature, i mean *really*
use it?


From pavlovevidence at gmail.com  Sat Aug  8 01:50:24 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Fri, 7 Aug 2009 22:50:24 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	
	<5Y2dnfnYAdsl0-HXnZ2dnUVZ_j9i4p2d@pdx.net> 
	
Message-ID: <8723453a-2836-4e9b-ac98-1fc4886da074@f10g2000vbf.googlegroups.com>

On Aug 7, 10:00?am, Grant Edwards  wrote:
> On 2009-08-07, Scott David Daniels  wrote:
>
> > Grant Edwards wrote:
> >> On 2009-08-07, durumdara  wrote:
> >>> In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
> >>> must concatenate the strings with some sign, like "+" or "||".
>
> >> In other languages like Ruby, awk, C, C++, etc. adjacent string
> >> constants are concatenated.
>
> > I must learn this "etc." language, I hear it mentioned all the time :-)
>
> Definitely. ?Not only does it have _all_ the features, it even
> manages to simultaneously have several mutually-exclusive
> features.

http://www.geocities.com/connorbd/tarpit/magentaaarm.html


(It's on Geocities, yikes, someone better archive that....)

Carl Banks


From rt8396 at gmail.com  Sat Aug  8 01:52:19 2009
From: rt8396 at gmail.com (r)
Date: Fri, 7 Aug 2009 22:52:19 -0700 (PDT)
Subject: Windows 7 : any problems installing or running Python ?
References: 
Message-ID: 

On Aug 7, 10:05?pm, Dave WB3DWE wrote:
...(snip)

Oh God, windows 7 is here :(.  What great functionality has M$
bestowed on the weary peasants now? More importantly why the heck am i
still using windows in 2009? i think i will dump my winders os for
good this year and go linux from here on out (can i get a hell yea?).
Sorry Dave i don't think i'll ever try windows 7 but i hope you find a
solution because i do want you to use Python.

Oh and Google, the masses are ready for the windows replacement....
Google? ....Goooooooogle!!!



From rschroev_nospam_ml at fastmail.fm  Sat Aug  8 02:39:49 2009
From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven)
Date: Sat, 08 Aug 2009 08:39:49 +0200
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <7xd476rj1s.fsf@ruckus.brouhaha.com>
References: 
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com>
	<7xd476rj1s.fsf@ruckus.brouhaha.com>
Message-ID: 

Paul Rubin schreef:
> Steven D'Aprano  writes:
>> As for the rest, you're right that the current bug-tracker puts up 
>> barriers to people submitting comments and bugs. That's actually a good 
>> thing. The only thing worse than not enough information is too much 
>> information, and the current situation does a good job of discouraging 
>> the sorts of people who submit bad bug reports (e.g. duplicates of bug 
>> reports, bug reports for things fixed years ago, bug reports that are due 
>> to mistakes in their code, etc.).
> 
> Stephen, Alex, etc.: have you actually used the php.net doc system?
> Don't knock it til you've tried it.  IMO it is superior to Python's
> system.  I don't use PHP much these days.

I have to use PHP from time to time, in which cases I often have to use
the manual on php.net. I don't like it at all.

The official documentation is often incomplete, leaving out the details
I need and forcing me to read the comments.

Which I don't want to do, since many comments show a lack of
understanding of the subject matter. I have to read all of them, trying
to find out which ones are correct and which ones are wrong (or
misleading) to get the complete picture.


I like Python's documentation, where I can be confident that the
documentation is correct (except in the case of the very exceptional
bug) and mostly clear, much better.

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
  -- Isaac Asimov

Roel Schroeven


From koranthala at gmail.com  Sat Aug  8 03:26:50 2009
From: koranthala at gmail.com (koranthala)
Date: Sat, 8 Aug 2009 00:26:50 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	
Message-ID: <40ed2690-3c6d-4413-a8a9-6bce7a304077@m7g2000prd.googlegroups.com>

On Aug 7, 5:15?pm, Dave Angel  wrote:
> alex23 wrote:
> > Paul Rubin  wrote:
>
> >> The PHP docs as I remember are sort of regular (non-publically
> >> editable) doc pages, each of which has a public discussion thread
> >> where people can post questions and answers about the topic of that
> >> doc page. ?I thought it worked really well. ?The main thing is that
> >> the good stuff from the comment section gets folded into the actual
> >> doc now and then.
>
> > I'd still like to see this kept out of the official docs as much as
> > possible, mostly for reasons of brevity & clarity. I think the
> > official docs should be considered definitive and not require a
> > hermeneutic evaluation against user comments to ensure they're still
> > correct...
>
> > How about a secondary site that embeds the docs and provides
> > commenting functionality around it? That's certainly a finitely scoped
> > project that those with issues about the docs could establish and
> > contribute to, with the possibility of it gaining official support
> > later once it gains traction.
>
> I share your concern about unmonitored comments. ?However, it seems a
> useful possibility would be for the "official" pages to each have
> specially-marked links that possibly lead to such user comments. ?
> Clearly they'd have to marked carefully, so that naive users don't
> confuse the two. ?But otherwise, it feels like a good idea.
>
> In my case, I usually access the docs via the Windows help file. ?So
> it'd be quite easy for me to recognize that once I've gotten to a
> browser page, I'm not in Kansas any more. ?But that could be also
> accomplished by having a very different stylesheet for the user comments
> page.
>
> DaveA

The best example that I have seen is djangobook.
The comment system in it is quite exquisite.
It would be good for the Python docs to have such a mechanism.


From pavlovevidence at gmail.com  Sat Aug  8 03:30:06 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sat, 8 Aug 2009 00:30:06 -0700 (PDT)
Subject: syntax checker in python
References: 
Message-ID: 

On Aug 7, 1:39?pm, horos11  wrote:
> ps - I just realized that it isn't enough to do:
>
> python -c 'import /path/to/script'
>
> since that actually executes any statement inside of the script
> (wheras all I want to do is check syntax)
>
> So - let me reprhase that - exactly how can you do a syntax check in
> python? Something like perl's -c:
>
> ? ? ?perl -c script_name.p

A quick and dirty way would be to use the py_compile:

python -m py_compile /path/to/script

Warning: this simply appends "c" to the filename and writes out the
compiled file (kind of dumb behavior, actually), so if it's a script
you probably want to delete it afterwards:

python -m py_compile /path/to/script ; rm -f /path/to/scriptc


A little better might be to write a little Python helper script that
directs output to nowhere (something like this, feel free to
embellish):

import py_compile
py_compile.compile(sys.argv[1],'/dev/null',None,False)



Carl Banks


From dmitrey.kroshko at scipy.org  Sat Aug  8 04:50:27 2009
From: dmitrey.kroshko at scipy.org (dmitrey)
Date: Sat, 8 Aug 2009 01:50:27 -0700 (PDT)
Subject: is it possible to overload operator "^"?
Message-ID: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>

hi all,
is it possible to overload operator "^"? (AFAIK __pow__ overloads **
instead of ^)
Thank you in advance, D.


From efotinis at y  Sat Aug  8 04:53:28 2009
From: efotinis at y (Elias Fotinis (eliasf))
Date: Sat, 8 Aug 2009 11:53:28 +0300
Subject: unique-ifying a list
In-Reply-To: 
References: 
Message-ID: <1249721637.162236@athprx03>

"kj" wrote:
> I suppose that I could write something like
>
> def uniquify(items):
>    seen = set()
>    ret = []
>    for i in items:
>        if not i in seen:
>            ret.append(i)
>            seen.add(i)
>    return ret
>
> But this seems to me like such a commonly needed operation that I
> find it hard to believe one would need to resort to such self-rolled
> solutions.  Isn't there some more standard (and hopefully more
> efficient, as in "C-coded"/built-in) approach?

The most "standard" way is a recipe from the itertools docs (I'd give a 
link, but python.org is down at the moment):

    def unique_everseen(iterable, key=None):
        "List unique elements, preserving order. Remember all elements ever 
seen."
        # unique_everseen('AAAABBBCCDAABBB') --> A B C D
        # unique_everseen('ABBCcAD', str.lower) --> A B C D
        seen = set()
        seen_add = seen.add
        if key is None:
            for element in iterable:
                if element not in seen:
                    seen_add(element)
                    yield element
        else:
            for element in iterable:
                k = key(element)
                if k not in seen:
                    seen_add(k)
                    yield element

All the recipes mentioned there are pretty handy, so I've made a module 
(iterutil.py) out of them.



From gherron at islandtraining.com  Sat Aug  8 05:02:19 2009
From: gherron at islandtraining.com (Gary Herron)
Date: Sat, 08 Aug 2009 02:02:19 -0700
Subject: is it possible to overload operator "^"?
In-Reply-To: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
References: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
Message-ID: <4A7D3F1B.5070100@islandtraining.com>

dmitrey wrote:
> hi all,
> is it possible to overload operator "^"? (AFAIK __pow__ overloads **
> instead of ^)
> Thank you in advance, D.
>   

The ^ operator is not an exponentiation, but rather the xor operator.  
Thus you can override it with the __xor__ method.

Beware, if you are thinking of ^ as an exponentiation like operator, the 
operator precedence will seem wrong.



From deets at nospam.web.de  Sat Aug  8 05:06:13 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sat, 08 Aug 2009 11:06:13 +0200
Subject: is it possible to overload operator "^"?
In-Reply-To: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
References: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
Message-ID: <7e4tg5F2eirarU1@mid.uni-berlin.de>

dmitrey schrieb:
> hi all,
> is it possible to overload operator "^"? (AFAIK __pow__ overloads **
> instead of ^)
> Thank you in advance, D.

Did you read the link I gave you for your last question?

It shows __xor__ as special method.

Diez


From efotinis at y  Sat Aug  8 05:44:16 2009
From: efotinis at y (Elias Fotinis (eliasf))
Date: Sat, 8 Aug 2009 12:44:16 +0300
Subject: Pywin32 @ windows 7
In-Reply-To: 
References: <004a01ca1733$a9768c10$4605a8c0@btsc1>
	
Message-ID: <1249724885.215365@athprx03>

"Dennis Lee Bieber" wrote:
> Ever consider that the name has WIN32 in, and not WIN64, for a
> reason?

Win32 is a misnomer; it just means "non-Win16". The same API exists in 
Windows x64 (with pointers expanded to 64-bit, of course). 



From efotinis at y  Sat Aug  8 05:46:59 2009
From: efotinis at y (Elias Fotinis (eliasf))
Date: Sat, 8 Aug 2009 12:46:59 +0300
Subject: Pywin32 @ windows 7
In-Reply-To: 
References: 
Message-ID: <1249724885.744992@athprx03>

"Algirdas Brazas" wrote:
> Did anyone manage to get windows extensions installet on windows 7 64 bit?
> As far as I try I get only "Setup program invalid or damaged".

Try downloading the installer again. It should work then.

I haven't tested it on Win7, but my Vista machine has Python and pywin32 
x64. 



From breamoreboy at yahoo.co.uk  Sat Aug  8 06:01:55 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 08 Aug 2009 11:01:55 +0100
Subject: Bug or feature: double strings as one
In-Reply-To: 
References: 		<5Y2dnfnYAdsl0-HXnZ2dnUVZ_j9i4p2d@pdx.net>
	
Message-ID: 

Unknown wrote:
> On 2009-08-07, Scott David Daniels  wrote:
>> Grant Edwards wrote:
>>> On 2009-08-07, durumdara  wrote:
>>>> In other languages, like Delphi (Pascal), Javascript, SQL, etc., I
>>>> must concatenate the strings with some sign, like "+" or "||".
>>> In other languages like Ruby, awk, C, C++, etc. adjacent string
>>> constants are concatenated.
>> I must learn this "etc." language, I hear it mentioned all the time :-)
> 
> Definitely.  Not only does it have _all_ the features, it even
> manages to simultaneously have several mutually-exclusive
> features.
> 
I have tried google for this "etc." language but failed dismally.  Does 
it belong here? http://www.thefreecountry.com/compilers/esoteric.shtml

-- 
Kindest regards.

Mark Lawrence.



From efotinis at y  Sat Aug  8 06:02:45 2009
From: efotinis at y (Elias Fotinis (eliasf))
Date: Sat, 8 Aug 2009 13:02:45 +0300
Subject: Bug or feature: double strings as one
In-Reply-To: <8723453a-2836-4e9b-ac98-1fc4886da074@f10g2000vbf.googlegroups.com>
References: 
	
	<5Y2dnfnYAdsl0-HXnZ2dnUVZ_j9i4p2d@pdx.net>
	
	<8723453a-2836-4e9b-ac98-1fc4886da074@f10g2000vbf.googlegroups.com>
Message-ID: <1249725805.853806@athprx03>

"Carl Banks" wrote:
> http://www.geocities.com/connorbd/tarpit/magentaaarm.html
> (It's on Geocities, yikes, someone better archive that....)

http://web.archive.org/web/*/http://www.geocities.com/connorbd/tarpit/magentaaarm.html

:)



From dmitrey.kroshko at scipy.org  Sat Aug  8 06:04:11 2009
From: dmitrey.kroshko at scipy.org (dmitrey)
Date: Sat, 8 Aug 2009 03:04:11 -0700 (PDT)
Subject: is it possible to overload operator "^"?
References: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
	<7e4tg5F2eirarU1@mid.uni-berlin.de>
Message-ID: 

> the operator precedence will seem wrong
So, are there any ways to change operator precedence (for my class)?

To Diez:
yes, but I haven't paid attention to xor. BTW the url is currently
unavailable (Network Timeout. The server at docs.python.org is taking
too long to respond.).

On Aug 8, 12:06 pm, "Diez B. Roggisch"  wrote:
> Did you read the link I gave you for your last question?
> It shows __xor__ as special method.
> Diez


From deets at nospam.web.de  Sat Aug  8 06:08:20 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sat, 08 Aug 2009 12:08:20 +0200
Subject: is it possible to overload operator "^"?
In-Reply-To: 
References: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
	<7e4tg5F2eirarU1@mid.uni-berlin.de>
	
Message-ID: <7e514kF2ekgqfU1@mid.uni-berlin.de>

dmitrey schrieb:
>> the operator precedence will seem wrong
> So, are there any ways to change operator precedence (for my class)?

No. Those are built-in.

Diez 
 
 


From enleverLesX_XXmcX at XmclavXeauX.com  Sat Aug  8 06:39:14 2009
From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP)
Date: Sat, 08 Aug 2009 12:39:14 +0200
Subject: Windows 7 : any problems installing or running Python ?
References: 
Message-ID: <4a7d55d4$0$12642$ba4acef3@news.orange.fr>

Hi! 

I use, all days, Python 2.6 + Pywin32 on Win-7-64 bits. Without problem
(I confirm : pywin 32 on 64 bits).

@-salutations
-- 
Michel Claveau 


From rylesny at gmail.com  Sat Aug  8 06:58:03 2009
From: rylesny at gmail.com (ryles)
Date: Sat, 8 Aug 2009 03:58:03 -0700 (PDT)
Subject: unique-ifying a list
References: 
Message-ID: 

On Aug 7, 4:53?pm, kj  wrote:
> Suppose that x is some list. ?To produce a version of the list with
> duplicate elements removed one could, I suppose, do this:
>
> ? ? x = list(set(x))
>
> but I expect that this will not preserve the original order of
> elements.
>

OrderedSet is most likely on the way, but for now Python 3.1 and 2.7
have OrderedDict. For 3.0 and 2.6 the recipe is here:

http://code.activestate.com/recipes/576669

With OrderedDict you can do:

OrderedDict.fromkeys(x).keys()  # Returns an iterator in 3.x, a list
in 2.x.


From thorsten at thorstenkampe.de  Sat Aug  8 07:16:12 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Sat, 8 Aug 2009 13:16:12 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	<0006746a$0$2895$c3e8da3@news.astraweb.com>
Message-ID: 

* Steven D'Aprano (08 Aug 2009 03:29:43 GMT)
> On Fri, 07 Aug 2009 17:13:07 +0200, Thorsten Kampe wrote:
> > One guy claims he has times between 2.7 and 5.7 seconds when
> > benchmarking more or less randomly generated "one million different
> > lines". That *is* *exactly* nothing.
> 
> We agree that in the grand scheme of things, a difference of 2.7 seconds 
> versus 5.7 seconds is a trivial difference if your entire program takes 
> (say) 8 minutes to run. You won't even notice it.

Exactly.

> But why assume that the program takes 8 minutes to run? Perhaps it takes 
> 8 seconds to run, and 6 seconds of that is the decoding. Then halving 
> that reduces the total runtime from 8 seconds to 5, which is a noticeable 
> speed increase to the user, and significant if you then run that program 
> tens of thousands of times.

Exactly. That's why it doesn't make sense to benchmark decode()/unicode
() isolated - meaning out of the context of your actual program.

> By all means, reminding people that pre-mature optimization is a 
> waste of time, but it's possible to take that attitude too far to Planet 
> Bizarro. At the point that you start insisting, and emphasising, that a 
> three second time difference is "*exactly*" zero,

Exactly. Because it was not generated in a real world use case but by 
running a simple loop one millions times. Why one million times? Because 
by running it "only" one hundred thousand times the difference would 
have seen even less relevant.

> it seems to me that this is about you winning rather than you giving
> good advice.

I already gave good advice:
1. don't benchmark
2. don't benchmark until you have an actual performance issue
3. if you benchmark then the whole application and not single commands

It's really easy: Michael has working code. With that he can easily 
write two versions - one that uses decode() and one that uses unicode(). 
He can benchmark these with some real world input he often uses by 
running it a hundred or a thousand times (even a million if he likes). 
Then he can compare the results. I doubt that there will be any 
noticeable difference.

Thorsten


From vinay_sajip at yahoo.co.uk  Sat Aug  8 07:38:13 2009
From: vinay_sajip at yahoo.co.uk (Vinay Sajip)
Date: Sat, 8 Aug 2009 04:38:13 -0700 (PDT)
Subject: ANN: gnupg v0.2.1 released
Message-ID: 

A new version of the Python module which wraps GnuPG has been
released.

What Changed?
=============
This is a minor bug-fix release. See the project website (
http://code.google.com/p/python-gnupg/ ) for more information.

The current version passes all tests on Windows (Python 2.4, 2.5, 2.6,
3.1, Jython 2.5.0) and Ubuntu (Python 2.4, 2.5, 2.6, 3.0, Jython
2.5.0).

What Does It Do?
================
The gnupg module allows Python programs to make use of the
functionality provided by the Gnu Privacy Guard (abbreviated GPG or
GnuPG). Using this module, Python programs can encrypt and decrypt
data, digitally sign documents and verify digital signatures, manage
(generate, list and delete) encryption keys, using proven Public Key
Infrastructure (PKI) encryption technology based on OpenPGP.

This module is expected to be used with Python versions >= 2.4, as it
makes use of the subprocess module which appeared in that version of
Python. This module is a newer version derived from earlier work by
Andrew Kuchling, Richard Jones and Steve Traugott.

A test suite using unittest is included with the source distribution.

Simple usage:

>>> import gnupg
>>> gpg = gnupg.GPG(gnupghome='/path/to/keyring/directory')
>>> gpg.list_keys()
[{
  ...
  'fingerprint': 'F819EE7705497D73E3CCEE65197D5DAC68F1AAB2',
  'keyid': '197D5DAC68F1AAB2',
  'length': '1024',
  'type': 'pub',
  'uids': ['', 'Gary Gross (A test user) ']},
 {
  ...
  'fingerprint': '37F24DD4B918CC264D4F31D60C5FEFA7A921FC4A',
  'keyid': '0C5FEFA7A921FC4A',
  'length': '1024',
  ...
  'uids': ['', 'Danny Davis (A test user) ']}]
>>> encrypted = gpg.encrypt("Hello, world!", ['0C5FEFA7A921FC4A'])
>>> str(encrypted)
'-----BEGIN PGP MESSAGE-----\nVersion: GnuPG v1.4.9 (GNU/Linux)\n
\nhQIOA/6NHMDTXUwcEAf
...
-----END PGP MESSAGE-----\n'
>>> decrypted = gpg.decrypt(str(encrypted), passphrase='secret')
>>> str(decrypted)
'Hello, world!'
>>> signed = gpg.sign("Goodbye, world!", passphrase='secret')
>>> verified = verified = gpg.verify(str(signed))
>>> print "Verified" if verified else "Not verified"
'Verified'

For more information, visit http://code.google.com/p/python-gnupg/ -
as always, your feedback is most welcome (especially bug reports,
patches and suggestions for improvement). Enjoy!

Cheers

Vinay Sajip
Red Dove Consultants Ltd.


From kushal.kumaran+python at gmail.com  Sat Aug  8 07:47:50 2009
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Sat, 8 Aug 2009 17:17:50 +0530
Subject: Database query execution times in Python?
In-Reply-To: <24870050.post@talk.nabble.com>
References: <24870050.post@talk.nabble.com>
Message-ID: <1e364c4e0908080447s1496e40bkbf60f80020be863b@mail.gmail.com>

On Sat, Aug 8, 2009 at 12:12 AM, pwnedd wrote:
>
> Hi all,
>
> I've been writing some code using libraries based on the Python Database API
> 2.0 (MySQLdb & pg), and so far things are working really well. There is one
> thing that I have not been able to figure out how to do, however:
>
> Retrieve the time is took a given query to execute.
>
> Does anyone know if this is possible?
>

If nothing else, you could always use the time.time() function for
timing sections of code.  This will also include the time it took to
transport the result from the database to your application, though.

-- 
kushal


From no.email at please.post  Sat Aug  8 08:11:19 2009
From: no.email at please.post (kj)
Date: Sat, 8 Aug 2009 12:11:19 +0000 (UTC)
Subject: Why all the __double_underscored_vars__?
References: 
	
Message-ID: 

In  Chris Rebert  writes:

>The double-underscores indicate that the Python interpreter itself
>usually is the caller of the method, and as such some level of "magic"
>may be associated with it. Other languages have you do the equivalent
>of `def +():` or `def operator +()` to override an operator, the
>keyword or symbol serving a similar warning that "here be magic".

In this case, then I hope that some of these __items__ get demoted
to a more mundane level, so that the notion of "magic" doesn't get
trivialized by everyday idioms like:

if __name__ == '__main__':
    # etc

There are a few in this category...  I figure that they are cases
of "atavistic magic".

I bring this up because I find it quite difficult to explain to my
students (who are complete newcomers to programming) all the
__underscored__ stuff that even rank noobs like them have to deal
with.  (Trust me, to most of them your reply to my post would be
as clear as mud.)  This suggests to me that there's something a
bit unnatural about some of these __items__.

Anyway, thanks for your post.  I see your point.

kynn


From thorsten at thorstenkampe.de  Sat Aug  8 08:19:44 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Sat, 8 Aug 2009 14:19:44 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	
	<006e7808-74e7-4d29-a7bc-01492d14de65@v15g2000prn.googlegroups.com>
Message-ID: 

* alex23 (Fri, 7 Aug 2009 10:45:29 -0700 (PDT))
> garabik-news-2005... at kassiopeia.juls.savba.sk wrote:
> > I am not sure I understood that. Must be my English :-)
> 
> I just parsed it as "blah blah blah I won't admit I'm wrong" and
> didn't miss anything substantive.

Alex, there are still a number of performance optimizations that require 
a thorough optimizer like you. Like using short identifiers instead of 
long ones. I guess you could easily prove that by comparing "a = 0" to 
"a_long_identifier = 0" and running it one hundred trillion times. The 
performance gain could easily add up to *days*. Keep us updated.

Thorsten


From gdamjan at gmail.com  Sat Aug  8 08:25:40 2009
From: gdamjan at gmail.com (=?UTF-8?B?0JTQsNC80ZjQsNC9INCT0LXQvtGA0LPQuNC10LLRgdC60Lg=?=)
Date: Sat, 08 Aug 2009 14:25:40 +0200
Subject: String to valid Python identifier
References: 
	<4a7a9328$0$2355$9b622d9e@news.freenet.de>
Message-ID: <5f70l6-70h.ln1@archaeopteryx.softver.org.mk>



>> Is there any easy function in the stdlib to convert any random string
>> in a valid Python identifier .. possibly by replacing non-valid
>> characters with _ ?
> 
> I think this is fairly underspecified as a problem statement. A
> solution that would meet your specification would be

True, I was thinking that if there was an obvious solution I'd get the 
answer right away.. so it seems there's not.

I did try the string.maketrans way... it was a bit ugly so I decided to 
ask here if I'm missing something... maybe I'll try maketrans again.


ps.
by "convert" I didn't mean a full transformation... I was more hoping 
for the least intrusive transformation that would still leave 
discernible resemblance of the original string. 



-- 
?????? ( http://softver.org.mk/damjan/ )

When you do things right, people won't be sure if you did anything at 
all.


From thorsten at thorstenkampe.de  Sat Aug  8 08:28:54 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Sat, 8 Aug 2009 14:28:54 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	
Message-ID: 

* garabik-news-2005-05 at kassiopeia.juls.savba.sk (Fri, 7 Aug 2009 
17:41:38 +0000 (UTC))
> Thorsten Kampe  wrote:
> > If you increase the number of loops to one million or one billion or
> > whatever even the slightest completely negligible difference will
> > occur. The same thing will happen if you just increase the corpus of
> > words to a million, trillion or whatever. The performance
> > implications of that are exactly none.
> 
> I am not sure I understood that. Must be my English :-)

I guess you understand me very well and I understand you very well. If 
the performance gain you want to prove doesn't show with 600,000 words, 
you test again with 18,000,000 words and if that is not impressive 
enough with 600,000,000 words. Great.

Or if a million repetitions of your "improved" code don't show the 
expected "performance advantage" you run it a billion times. Even 
greater. Keep on optimzing.

Thorsten


From cournape at gmail.com  Sat Aug  8 09:02:37 2009
From: cournape at gmail.com (David Cournapeau)
Date: Sat, 8 Aug 2009 22:02:37 +0900
Subject: Why all the __double_underscored_vars__?
In-Reply-To: 
References: 
	
	
Message-ID: <5b8d13220908080602y65815858yda25ddbfd3a05031@mail.gmail.com>

On Sat, Aug 8, 2009 at 9:11 PM, kj wrote:
> In  Chris Rebert  writes:
>
>>The double-underscores indicate that the Python interpreter itself
>>usually is the caller of the method, and as such some level of "magic"
>>may be associated with it. Other languages have you do the equivalent
>>of `def +():` or `def operator +()` to override an operator, the
>>keyword or symbol serving a similar warning that "here be magic".
>
> In this case, then I hope that some of these __items__ get demoted
> to a more mundane level, so that the notion of "magic" doesn't get
> trivialized by everyday idioms like:
>
> if __name__ == '__main__':
> ? ?# etc
>
> There are a few in this category... ?I figure that they are cases
> of "atavistic magic".
>
> I bring this up because I find it quite difficult to explain to my
> students (who are complete newcomers to programming) all the
> __underscored__ stuff that even rank noobs like them have to deal
> with. ?(Trust me, to most of them your reply to my post would be
> as clear as mud.)

Maybe your students do not need to know about it, at least at the
beginning ? I heavily use python, and do not use the underscore
methods so much most of the time, except for __init__,

cheers,

David


From michael at stroeder.com  Sat Aug  8 09:09:23 2009
From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=)
Date: Sat, 08 Aug 2009 15:09:23 +0200
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	<0006746a$0$2895$c3e8da3@news.astraweb.com>
	
Message-ID: <41a0l6-2u4.ln1@nb2.stroeder.com>

Thorsten Kampe wrote:
> * Steven D'Aprano (08 Aug 2009 03:29:43 GMT)
>> But why assume that the program takes 8 minutes to run? Perhaps it takes 
>> 8 seconds to run, and 6 seconds of that is the decoding. Then halving 
>> that reduces the total runtime from 8 seconds to 5, which is a noticeable 
>> speed increase to the user, and significant if you then run that program 
>> tens of thousands of times.
> 
> Exactly. That's why it doesn't make sense to benchmark decode()/unicode
> () isolated - meaning out of the context of your actual program.

Thorsten, the point is you're too arrogant to admit that making such a general
statement like you did without knowing *anything* about the context is simply
false. So this is not a technial matter. It's mainly an issue with your attitude.

>> By all means, reminding people that pre-mature optimization is a 
>> waste of time, but it's possible to take that attitude too far to Planet 
>> Bizarro. At the point that you start insisting, and emphasising, that a 
>> three second time difference is "*exactly*" zero,
> 
> Exactly. Because it was not generated in a real world use case but by 
> running a simple loop one millions times. Why one million times? Because 
> by running it "only" one hundred thousand times the difference would 
> have seen even less relevant.

I was running it one million times to mitigate influences on the timing by
other background processes which is a common technique when benchmarking. I
was mainly interested in the percentage which is indeed significant. The
absolute times also strongly depend on the hardware where the software is
running. So your comment about the absolute times are complete nonsense. I'm
eager that this software should also run with acceptable response times on
hardware much slower than my development machine.

> I already gave good advice:
> 1. don't benchmark
> 2. don't benchmark until you have an actual performance issue
> 3. if you benchmark then the whole application and not single commands

You don't know anything about what I'm doing and what my aim is. So your
general rules don't apply.

> It's really easy: Michael has working code. With that he can easily 
> write two versions - one that uses decode() and one that uses unicode().

Yes, I have working code which was originally written before .decode() being
added in Python 2.2. Therefore I wondered whether it would be nice for
readability to replace unicode() by s.decode() since the software does not
support Python versions prior 2.3 anymore anyway. But one aspect is also
performance and hence my question and testing.

Ciao, Michael.


From vlastimil.brom at gmail.com  Sat Aug  8 09:21:38 2009
From: vlastimil.brom at gmail.com (Vlastimil Brom)
Date: Sat, 8 Aug 2009 15:21:38 +0200
Subject: String to valid Python identifier
In-Reply-To: <5f70l6-70h.ln1@archaeopteryx.softver.org.mk>
References: 
	<4a7a9328$0$2355$9b622d9e@news.freenet.de>
	<5f70l6-70h.ln1@archaeopteryx.softver.org.mk>
Message-ID: <9fdb569a0908080621w116dd3e7qbdb4019bbb0f691a@mail.gmail.com>

2009/8/8 ?????? ??????????? :
>
>
>>> Is there any easy function in the stdlib to convert any random string
>>> in a valid Python identifier .. possibly by replacing non-valid
>>> characters with _ ?
...
>
> ps.
> by "convert" I didn't mean a full transformation... I was more hoping
> for the least intrusive transformation that would still leave
> discernible resemblance of the original string.
>
>
>
> --
> ?????? ( http://softver.org.mk/damjan/ )
>
> When you do things right, people won't be sure if you did anything at
> all.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Depending on the needs (speed, readability ...), the regular
expression replacement might be viable too:
>>> import re
>>> print re.sub(r"[^a-zA-Z0-9_]", r"_", u"a?bc d:e?_123's - foo?!var")
a_bc_d_e__123_s___foo__var
>>> print re.sub(r"\W", r"_", u"a?bc d:e?_123's - foo?!var") # equivalent
a_bc_d_e__123_s___foo__var
>>>

Additionally, as with the other approaches, you also have to check for
the (illegal) starting digit and replace it or prepend some valid
prefix.
hth
 vbr


From lcazarre at gmail.com  Sat Aug  8 09:31:02 2009
From: lcazarre at gmail.com (Caezar)
Date: Sat, 8 Aug 2009 06:31:02 -0700 (PDT)
Subject: www.python.org website is down?
Message-ID: 

I cannot connect to the official Python website. I get the following
error message:

"Connection Interrupted
The connection to the server was reset while the page was loading.
The network link was interrupted while negotiating a connection.
Please try again."

Are you experiencing the same problem?


From breamoreboy at yahoo.co.uk  Sat Aug  8 09:41:57 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 08 Aug 2009 14:41:57 +0100
Subject: www.python.org website is down?
In-Reply-To: 
References: 
Message-ID: 

Caezar wrote:
> I cannot connect to the official Python website. I get the following
> error message:
> 
> "Connection Interrupted
> The connection to the server was reset while the page was loading.
> The network link was interrupted while negotiating a connection.
> Please try again."
> 
> Are you experiencing the same problem?
Yes, it's been down for several hours.

-- 
Kindest regards.

Mark Lawrence.



From fasteliteprogrammer at yahoo.com  Sat Aug  8 09:48:04 2009
From: fasteliteprogrammer at yahoo.com (Craig)
Date: Sat, 8 Aug 2009 06:48:04 -0700 (PDT)
Subject: www.python.org website is down?
In-Reply-To: 
Message-ID: <314905.49987.qm@web36501.mail.mud.yahoo.com>

Yes the same prob.

--- On Sat, 8/8/09, Mark Lawrence  wrote:

> From: Mark Lawrence 
> Subject: Re: www.python.org website is down?
> To: python-list at python.org
> Date: Saturday, August 8, 2009, 8:41 AM
> Caezar wrote:
> > I cannot connect to the official Python website. I get
> the following
> > error message:
> > 
> > "Connection Interrupted
> > The connection to the server was reset while the page
> was loading.
> > The network link was interrupted while negotiating a
> connection.
> > Please try again."
> > 
> > Are you experiencing the same problem?
> Yes, it's been down for several hours.
> 
> -- Kindest regards.
> 
> Mark Lawrence.
> 
> -- http://mail.python.org/mailman/listinfo/python-list
> 


      


From python at mrabarnett.plus.com  Sat Aug  8 09:48:16 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Sat, 08 Aug 2009 14:48:16 +0100
Subject: www.python.org website is down?
In-Reply-To: 
References: 
Message-ID: <4A7D8220.90806@mrabarnett.plus.com>

Caezar wrote:
> I cannot connect to the official Python website. I get the following
> error message:
> 
> "Connection Interrupted
> The connection to the server was reset while the page was loading.
> The network link was interrupted while negotiating a connection.
> Please try again."
> 
> Are you experiencing the same problem?

A.M. Kuchling said:

"""
Both www.python.org and svn.python.org are down.  They're hosted on
the same machine, and it seems to have run into disk problems and
hasn't rebooted even after power-cycling.  Thomas Wouters will be
visiting the machine physically tomorrow to try to diagnose the
problem.

(The machine also hosts planet.python.org and hg.python.org.)
"""


From bh at izb.knu.ac.kr  Sat Aug  8 10:26:53 2009
From: bh at izb.knu.ac.kr (Byung-Hee HWANG)
Date: Sat, 08 Aug 2009 23:26:53 +0900
Subject: www.python.org website is down?
References: 
Message-ID: <86ab2a4c0i.fsf@betla.izb.knu.ac.kr>

Caezar  writes:

> I cannot connect to the official Python website. I get the following
> error message:
>
> "Connection Interrupted
> The connection to the server was reset while the page was loading.
> The network link was interrupted while negotiating a connection.
> Please try again."
>
> Are you experiencing the same problem?

Yes, me, too. Now i can't open the URL www.python.org ;;

-- 
"But there's a little more. Don Corleone is too modest."
		-- Emilio Barzini, "Chapter 20", page 286


From danielwong at berkeley.edu  Sat Aug  8 11:15:24 2009
From: danielwong at berkeley.edu (Daniel Wong)
Date: Sat, 8 Aug 2009 08:15:24 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
Message-ID: 

>
> A.M. Kuchling said:
>
> """
> Bothwww.python.organd svn.python.org are down. ?They're hosted on
> the same machine, and it seems to have run into disk problems and
> hasn't rebooted even after power-cycling. ?Thomas Wouters will be
> visiting the machine physically tomorrow to try to diagnose the
> problem.
>
> (The machine also hosts planet.python.org and hg.python.org.)
> """

This is probably a stupid question, but Is there going to be any data
loss if it turns out that the disk has died completely? I assume there
are backups of the repo that are geographically distributed.


From efotinis at y  Sat Aug  8 11:43:34 2009
From: efotinis at y (Elias Fotinis (eliasf))
Date: Sat, 8 Aug 2009 18:43:34 +0300
Subject: www.python.org website is down?
In-Reply-To: 
References: 
Message-ID: <1249746242.50676@athprx03>

"Caezar" wrote:
> I cannot connect to the official Python website.
[snip]
> Are you experiencing the same problem?

Yes, it's been down for a while.

A useful site to check in such occasions is 
http://downforeveryoneorjustme.com/. 



From foetsch at yahoo.com  Sat Aug  8 12:02:48 2009
From: foetsch at yahoo.com (=?UTF-8?B?TWljaGFlbCBGw7Z0c2No?=)
Date: Sat, 08 Aug 2009 18:02:48 +0200
Subject: unicode() vs. s.decode()
In-Reply-To: <2qcrk6-doj.ln1@nb2.stroeder.com>
References: 	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
Message-ID: <4A7DA1A8.4020603@yahoo.com>

Michael Str?der wrote:
 > >>> timeit.Timer("unicode('???????','utf-8')").timeit(10000000)
 > 17.23644495010376
 > >>> timeit.Timer("'???????'.decode('utf8')").timeit(10000000)
 > 72.087096929550171
 >
 > That is significant! So the winner is:
 >
 > unicode('???????','utf-8')

Which proves that benchmark results can be misleading sometimes. :-)

unicode() becomes *slower* when you try "UTF-8" in uppercase, or an 
entirely different codec, say "cp1252":

   >>> timeit.Timer("unicode('???????','UTF-8')").timeit(1000000)
   2.5777881145477295
   >>> timeit.Timer("'???????'.decode('UTF-8')").timeit(1000000)
   1.8430399894714355
   >>> timeit.Timer("unicode('???????','cp1252')").timeit(1000000)
   2.3622498512268066
   >>> timeit.Timer("'???????'.decode('cp1252')").timeit(1000000)
   1.7812771797180176

The reason seems to be that unicode() bypasses codecs.lookup() if the 
encoding is one of "utf-8", "latin-1", "mbcs", or "ascii". OTOH, 
str.decode() always calls codecs.lookup().

If speed is your primary concern, this will give you even better 
performance than unicode():

   decoder = codecs.lookup("utf-8").decode
   for i in xrange(1000000):
       decoder("???????")[0]


However, there's also a functional difference between unicode() and 
str.decode():

unicode() always raises an exception when you try to decode a unicode 
object. str.decode() will first try to encode a unicode object using the 
default encoding (usually "ascii"), which might or might not work.

Kind Regards,
M.F.



From garabik-news-2005-05 at kassiopeia.juls.savba.sk  Sat Aug  8 12:16:49 2009
From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk)
Date: Sat, 8 Aug 2009 16:16:49 +0000 (UTC)
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	
	
Message-ID: 

Thorsten Kampe  wrote:
> * garabik-news-2005-05 at kassiopeia.juls.savba.sk (Fri, 7 Aug 2009 
> 17:41:38 +0000 (UTC))
>> Thorsten Kampe  wrote:
>> > If you increase the number of loops to one million or one billion or
>> > whatever even the slightest completely negligible difference will
>> > occur. The same thing will happen if you just increase the corpus of
>> > words to a million, trillion or whatever. The performance
>> > implications of that are exactly none.
>> 
>> I am not sure I understood that. Must be my English :-)
> 
> I guess you understand me very well and I understand you very well. If 

I did not. Really. But then it has been explained to me, so I think I do
now :-)

> the performance gain you want to prove doesn't show with 600,000 words, 
> you test again with 18,000,000 words and if that is not impressive 
> enough with 600,000,000 words. Great.
> 

Huh? 
18e6 words is what I am working with _now_. Most of the data is already
collected, there are going to be few more books, but that's all. And the
optimization I was talking about means going home from work one hour
later or earlier. Quite noticeable for me.
600e6 words is the main corpus. Data is already there and wait to be
processed in some time. Once we finih our current project. That is 
real life, no thought experiment.


> Or if a million repetitions of your "improved" code don't show the 
> expected "performance advantage" you run it a billion times. Even 
> greater. Keep on optimzing.

No, we do not have one billion words (yet - I assume you are talking
about American billion - if you are talking about European billion, we
would be masters of the world with a billion word corpus!).
However, that might change once we start collecting www data (which is a
separate project, to be started in a year or two)
Then, we'll do some more optimiation because the time differences will
be more noticeable. Easy as that.


-- 
 -----------------------------------------------------------
| Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__    garabik @ kassiopeia.juls.savba.sk     |
 -----------------------------------------------------------
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!


From nipunreddevil at gmail.com  Sat Aug  8 12:34:02 2009
From: nipunreddevil at gmail.com (nipun batra)
Date: Sat, 8 Aug 2009 12:34:02 -0400
Subject: Serial port access
Message-ID: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>

Hi,
How can we access serial port using usb-serial converters,using python in
linux.I want to further use pyGTK for Gui development after accessing serial
data.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rogerpack2005 at gmail.com  Sat Aug  8 12:34:05 2009
From: rogerpack2005 at gmail.com (rogerdpack)
Date: Sat, 8 Aug 2009 09:34:05 -0700 (PDT)
Subject: .h files?
Message-ID: <50c453d9-d455-4f08-959c-e225149495fb@i18g2000pro.googlegroups.com>

Question.  Seems that with python distributions you have the option to
include either "external facing, public" *.h files, and make them
available, or include the whole kit and kaboodle [all *.h files].  Any
word on how python does this currently?  Just wondering as ruby runs
into the same question.
Thanks!
-roger


From jimxu at google.com  Sat Aug  8 12:47:14 2009
From: jimxu at google.com (Yongjian Xu)
Date: Sat, 8 Aug 2009 09:47:14 -0700
Subject: Why all the __double_underscored_vars__?
In-Reply-To: 
References: 
	 
	
Message-ID: <9c09a1210908080947t6d955beaxa495502b95ce9c1@mail.gmail.com>

These "special" methods are not meant to be used or known to beginners. They
aren't even meant to be called directly (in most cases). They are either
operator overloading methods or behavior customization methods. In my
opinion, in the meta programming realm. Should probably in advanced topic or
something.


On Sat, Aug 8, 2009 at 5:11 AM, kj  wrote:

> In  Chris Rebert <
> clp2 at rebertia.com> writes:
>
> >The double-underscores indicate that the Python interpreter itself
> >usually is the caller of the method, and as such some level of "magic"
> >may be associated with it. Other languages have you do the equivalent
> >of `def +():` or `def operator +()` to override an operator, the
> >keyword or symbol serving a similar warning that "here be magic".
>
> In this case, then I hope that some of these __items__ get demoted
> to a more mundane level, so that the notion of "magic" doesn't get
> trivialized by everyday idioms like:
>
> if __name__ == '__main__':
>    # etc
>
> There are a few in this category...  I figure that they are cases
> of "atavistic magic".
>
> I bring this up because I find it quite difficult to explain to my
> students (who are complete newcomers to programming) all the
> __underscored__ stuff that even rank noobs like them have to deal
> with.  (Trust me, to most of them your reply to my post would be
> as clear as mud.)  This suggests to me that there's something a
> bit unnatural about some of these __items__.
>
> Anyway, thanks for your post.  I see your point.
>
> kynn
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From n179911 at gmail.com  Sat Aug  8 12:47:38 2009
From: n179911 at gmail.com (n179911)
Date: Sat, 8 Aug 2009 09:47:38 -0700 (PDT)
Subject: Need help in refactoring my python script
Message-ID: <10d392bc-0a41-4a12-a863-f5fcb296d40c@a37g2000prf.googlegroups.com>

I have a python script which process a file line by line, if the line
matches a regex, it calls a function to handle it.

My question is is there a better write to refactor my script. The
script works, but as it is, i need to keep indent to the right of the
editor as I add more and more regex for my file.

Thank you for any idea.
Now my code end up like this:

for line in fi.readlines():

	result= reg1.match(line)

	if result:
		handleReg1(result)

	else:
		result = reg2.match(line)

		if result:
			handleReg2(result)
		else:
			result = reg3.match(line)

			if result:
				handleReg3(result)
			else:
				result = reg4.match(line)

				if result:
					handleReg4(result)
				else:
					result = reg5.match(line)

					if result:
                                               handleReg5(result)


From exarkun at twistedmatrix.com  Sat Aug  8 12:54:51 2009
From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com)
Date: Sat, 08 Aug 2009 16:54:51 -0000
Subject: Serial port access
In-Reply-To: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
References: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
Message-ID: <20090808165451.7171.1497184396.divmod.xquotient.112@localhost.localdomain>

On 04:34 pm, nipunreddevil at gmail.com wrote:
>Hi,
>How can we access serial port using usb-serial converters,using python 
>in
>linux.I want to further use pyGTK for Gui development after accessing 
>serial
>data.

Twisted supports serial ports and has good Gtk integration.

http://twistedmatrix.com/projects/core/documentation/examples/ has some
examples of each of these things (take a look at mouse.py for the serial
port example).

Jean-Paul


From hatbabe at gmail.com  Sat Aug  8 12:57:32 2009
From: hatbabe at gmail.com (the hatter)
Date: Sat, 8 Aug 2009 09:57:32 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
Message-ID: 

> A.M. Kuchling said:
>
> """
> Bothwww.python.organd svn.python.org are down. ?They're hosted on
> the same machine, and it seems to have run into disk problems and
> hasn't rebooted even after power-cycling. ?Thomas Wouters will be
> visiting the machine physically tomorrow to try to diagnose the
> problem.
>
> (The machine also hosts planet.python.org and hg.python.org.)
> """

I was hoping to find an official mirror to grab source from when I
couldn't connect, but all i found were notices saying the python board
had decided they didn't want any ?  Seems a bit short-sighted if the
main site isn't some kind of fairly bulletproof, diverse/redundant/
intrinsically mirroring setup.


the hatter


From thorsten at thorstenkampe.de  Sat Aug  8 13:00:11 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Sat, 8 Aug 2009 19:00:11 +0200
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	<0006746a$0$2895$c3e8da3@news.astraweb.com>
	
	<41a0l6-2u4.ln1@nb2.stroeder.com>
Message-ID: 

* Michael Str?der (Sat, 08 Aug 2009 15:09:23 +0200)
> Thorsten Kampe wrote:
> > * Steven D'Aprano (08 Aug 2009 03:29:43 GMT)
> >> But why assume that the program takes 8 minutes to run? Perhaps it takes 
> >> 8 seconds to run, and 6 seconds of that is the decoding. Then halving 
> >> that reduces the total runtime from 8 seconds to 5, which is a noticeable 
> >> speed increase to the user, and significant if you then run that program 
> >> tens of thousands of times.
> > 
> > Exactly. That's why it doesn't make sense to benchmark decode()/unicode
> > () isolated - meaning out of the context of your actual program.
> 
> Thorsten, the point is you're too arrogant to admit that making such a general
> statement like you did without knowing *anything* about the context is simply
> false.

I made a general statement to a very general question ("These both 
expressions are equivalent but which is faster or should be used for any 
reason?"). If you have specific needs or reasons then you obviously 
failed to provide that specific "context" in your question.
 
> >> By all means, reminding people that pre-mature optimization is a 
> >> waste of time, but it's possible to take that attitude too far to Planet 
> >> Bizarro. At the point that you start insisting, and emphasising, that a 
> >> three second time difference is "*exactly*" zero,
> > 
> > Exactly. Because it was not generated in a real world use case but by 
> > running a simple loop one millions times. Why one million times? Because 
> > by running it "only" one hundred thousand times the difference would 
> > have seen even less relevant.
> 
> I was running it one million times to mitigate influences on the timing by
> other background processes which is a common technique when benchmarking.

Err, no. That is what "repeat" is for and it defaults to 3 ("This means 
that other processes running on the same computer may interfere with the 
timing. The best thing to do when accurate timing is necessary is to 
repeat the timing a few times and use the best time. [...] the default 
of 3 repetitions is probably enough in most cases.")

Three times - not one million times. You choose one million times (for 
the loop) when the thing you're testing is very fast (like decoding) and 
you don't want results in the 0.00000n range. Which is what you asked 
for and what you got.

> > I already gave good advice:
> > 1. don't benchmark
> > 2. don't benchmark until you have an actual performance issue
> > 3. if you benchmark then the whole application and not single commands
> 
> You don't know anything about what I'm doing and what my aim is. So your
> general rules don't apply.

See above. You asked a general question, you got a general answer.
 
> > It's really easy: Michael has working code. With that he can easily 
> > write two versions - one that uses decode() and one that uses unicode().
> 
> Yes, I have working code which was originally written before .decode() being
> added in Python 2.2. Therefore I wondered whether it would be nice for
> readability to replace unicode() by s.decode() since the software does not
> support Python versions prior 2.3 anymore anyway. But one aspect is also
> performance and hence my question and testing.

You haven't done any testing yet. Running decode/unicode one million 
times in a loop is not testing. If you don't believe me then read at 
least Martelli's Optimization chapter in Python in a nutshell (the 
chapter is available via Google books).

Thorsten


From __peter__ at web.de  Sat Aug  8 13:02:09 2009
From: __peter__ at web.de (Peter Otten)
Date: Sat, 08 Aug 2009 19:02:09 +0200
Subject: Need help in refactoring my python script
References: <10d392bc-0a41-4a12-a863-f5fcb296d40c@a37g2000prf.googlegroups.com>
Message-ID: 

n179911 wrote:

> I have a python script which process a file line by line, if the line
> matches a regex, it calls a function to handle it.
> 
> My question is is there a better write to refactor my script. The
> script works, but as it is, i need to keep indent to the right of the
> editor as I add more and more regex for my file.
> 
> Thank you for any idea.
> Now my code end up like this:
> 
> for line in fi.readlines():
> 
>         result= reg1.match(line)
> 
>         if result:
>                 handleReg1(result)
> 
>         else:
>                 result = reg2.match(line)
> 
>                 if result:
>                         handleReg2(result)
>                 else:
>                         result = reg3.match(line)
> 
>                         if result:
>                                 handleReg3(result)
>                         else:
>                                 result = reg4.match(line)
> 
>                                 if result:
>                                         handleReg4(result)
>                                 else:
>                                         result = reg5.match(line)
> 
>                                         if result:
>                                                handleReg5(result)
> 

If the handlers are indeed functions you can put them into a list:

match_handler_pairs = [
    (reg1.match, handleReg1),
    (reg2.match, handleReg2),
    ...
    ]

for line in fi: # look Ma, no readlines()
    for match, handler in match_handler_pairs:
        result = match(line)
        if result:
            handler(result)
            break
        
 Peter



From python at mrabarnett.plus.com  Sat Aug  8 13:09:47 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Sat, 08 Aug 2009 18:09:47 +0100
Subject: Need help in refactoring my python script
In-Reply-To: <10d392bc-0a41-4a12-a863-f5fcb296d40c@a37g2000prf.googlegroups.com>
References: <10d392bc-0a41-4a12-a863-f5fcb296d40c@a37g2000prf.googlegroups.com>
Message-ID: <4A7DB15B.3090804@mrabarnett.plus.com>

n179911 wrote:
> I have a python script which process a file line by line, if the line
> matches a regex, it calls a function to handle it.
> 
> My question is is there a better write to refactor my script. The
> script works, but as it is, i need to keep indent to the right of the
> editor as I add more and more regex for my file.
> 
> Thank you for any idea.
> Now my code end up like this:
> 
> for line in fi.readlines():

This will read all the lines and then iterate through them. You can 
iterate through the file line by line directly with:

     for line in fi:
         ...

> 	result= reg1.match(line)
> 	if result:
> 		handleReg1(result)
> 	else:
> 		result = reg2.match(line)
> 		if result:
> 			handleReg2(result)
> 		else:
> 			result = reg3.match(line)
> 			if result:
> 				handleReg3(result)
> 			else:
> 				result = reg4.match(line)
> 				if result:
> 					handleReg4(result)
> 				else:
> 					result = reg5.match(line)
> 					if result:
>                                                handleReg5(result)

Build a list of the regexes and their functions:

actions = []
actions.append((reg1, handleReg1))
actions.append((reg2, handleReg2))
actions.append((reg3, handleReg3))
actions.append((reg4, handleReg4))
actions.append((reg5, handleReg5))

for line in fi:
     for reg, func in actions:
         result = reg.match(line)
         if result:
             func(result)
             break


From rcdailey at gmail.com  Sat Aug  8 13:12:30 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Sat, 8 Aug 2009 10:12:30 -0700 (PDT)
Subject: Subclass dynamically
Message-ID: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com>

Hey,

I have a class that I want to have a different base class depending on
a parameter that I pass to its __init__method. For example
(pseudocode):

class MyDerived( self.base ):
  def __init__( self, base ):
    self.base = base


Something like that... and then I would do this:

foo = MyDerived( MyBase() )

Note I'm using Python 3.1 on Windows. Thanks in advance.


From gherron at islandtraining.com  Sat Aug  8 13:31:41 2009
From: gherron at islandtraining.com (Gary Herron)
Date: Sat, 08 Aug 2009 10:31:41 -0700
Subject: Subclass dynamically
In-Reply-To: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com>
References: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com>
Message-ID: <4A7DB67D.9070208@islandtraining.com>

Robert Dailey wrote:
> Hey,
>
> I have a class that I want to have a different base class depending on
> a parameter that I pass to its __init__method. For example
> (pseudocode):
>
> class MyDerived( self.base ):
>   def __init__( self, base ):
>     self.base = base
>
>
> Something like that... and then I would do this:
>
> foo = MyDerived( MyBase() )
>
> Note I'm using Python 3.1 on Windows. Thanks in advance.
>   
Python makes it possible to change base classes, but that doesn't mean 
it ever a good idea.

Moreover, the assignment is at the class level, not the instance level:

    MyDerived.__bases__ = (base,) #A tuple of bases

would change the base class for the class MyDerived, and all instances 
past, present, or future.

Better (but still not good) might be a factory function that derives a 
class with the desired base class:

def Derive(base):
    class Derived(base):
        pass
    return Derived

DerivedClass = Derive(MyBase)
foo = DerivedClass(...)

I believe that will produce what you were looking for.

Gary Herron



From zuo at chopin.edu.pl  Sat Aug  8 13:43:30 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Sat, 08 Aug 2009 19:43:30 +0200
Subject: Bug or feature: double strings as one
In-Reply-To: <000674d6$0$2895$c3e8da3@news.astraweb.com>
References: 
	
	
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
Message-ID: 

08-08-2009 Steven D'Aprano  wrote:

> On Fri, 07 Aug 2009 17:35:28 +0000, kj wrote:
>
>> I fail to see why
>>
>> x = ("first part of a very long string "
>>      "second part of a very long string")
>
> That's done by the compiler at compile time and is fast.

Moreover, it's also more readable, when you use str calling its
methods or using formatting on it.

I use it very often, e.g.:

         afunction('quite long string %s quite long string '
                   'quite long string quite long string %s '
                   'quite %s long string quite long string'
                   % (variable1, variable2, variable3))

It seems nicer to me than:

         afunction(('quite long string %s quite long string '
                    + 'quite long string quite long string %s '
                    + 'quite %s long string quite long string')
                   % (variable1, variable2, variable3))

(Note that multiline-'''-strings are usless in such cases).

*j

-- 
Jan Kaliszewski (zuo) 


From python at mrabarnett.plus.com  Sat Aug  8 14:14:40 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Sat, 08 Aug 2009 19:14:40 +0100
Subject: convert non-delimited to delimited
In-Reply-To: <768586.94351.qm@web65602.mail.ac4.yahoo.com>
References: <768586.94351.qm@web65602.mail.ac4.yahoo.com>
Message-ID: <4A7DC090.8020109@mrabarnett.plus.com>

John wrote:
> I am not really a CS person, but I have a task to import a non-delimited 
> text to an access database.  After some research, I *think* the best way 
> to do this is by first converting the non-delimited text to delimited 
> text, and then import it to the database.  Is this the best way to 
> approach this?  Or is there easier way?
>  
[snip]
> 
> I am really stump on where to go from here.  Any help would be 
> appreciated it.  I have also include a text file which gives several 
> more examples.
> 
You'll need to see what types of file the database can import. A brief
search of the web says that it can import tab-separated text files (a
line is a record and the fields are separated by tab characters).

Be sure to test it first before trying it on the real database! :-)


From rami.chowdhury at gmail.com  Sat Aug  8 14:15:20 2009
From: rami.chowdhury at gmail.com (Rami Chowdhury)
Date: Sat, 8 Aug 2009 11:15:20 -0700
Subject: [Diversity] Language note
In-Reply-To: <12470af00908080943g1e559273sdd5e4fc92336a5eb@mail.gmail.com>
References: <20090807143826.GA19246@panix.com>
	<7528bcdd0908070753t7533d6ddw2321a462ed7036e3@mail.gmail.com>
	
	
	<12470af00908080755y717036b2j3d2ac7bf98838fc@mail.gmail.com>
	
	<12470af00908080943g1e559273sdd5e4fc92336a5eb@mail.gmail.com>
Message-ID: 


> Most indian languages have a different
> grammer (compared to English). So i'm curious to see how that would be
> implemented in a parser

+1 -- I'd be interested in seeing this too, although we have drifted  
OT here and perhaps this conversation would be better had on Python- 
list. The closest I've seen to a language being able to support  
different grammatical structures is Perligata (http:// 
www.csse.monash.edu.au/~damian/papers/HTML/Perligata.html), does  
Python have anything similar?

-------------
Rami Chowdhury
"Never assume malice when stupidity will suffice." -- Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)




On Aug 8, 2009, at 09:43 , vid wrote:

> On Sat, Aug 8, 2009 at 21:19, Rami  
> Chowdhury wrote:
>> I suppose the Chinese Python project that Brianna linked to
>> (http://www.chinesepython.org/cgi_bin/cgb.cgi/english/ 
>> english.html) must
>> take Unicode input...
>
> That was interesting but i dont know chinese and IIUC my requirement
> is slightly different -- Most indian languages have a different
> grammer (compared to English). So i'm curious to see how that would be
> implemented in a parser, especially because it brings in a lot more
> ambiguity.
>
> -- 
> thanks
> || vid || http://www.svaksha.com ||
> _______________________________________________
> Diversity mailing list
> Diversity at python.org
> http://mail.python.org/mailman/listinfo/diversity



From martin at v.loewis.de  Sat Aug  8 14:17:37 2009
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Sat, 08 Aug 2009 20:17:37 +0200
Subject: www.python.org website is down?
In-Reply-To: 
References: 
	
	
Message-ID: <4A7DC141.9070207@v.loewis.de>

> This is probably a stupid question, but Is there going to be any data
> loss if it turns out that the disk has died completely? I assume there
> are backups of the repo that are geographically distributed.

Yes, we have backups, and are restoring them at the moment. However,
we still haven't given up on the original disks: they are (probably)
fine; it's just the RAID controller that has failed (and we can't buy a
replacement before Monday).

Regards,
Martin


From kpouya at gmail.com  Sat Aug  8 14:33:57 2009
From: kpouya at gmail.com (Pouya Khankhanian)
Date: Sat, 8 Aug 2009 11:33:57 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
	
	<4A7DC141.9070207@v.loewis.de>
Message-ID: <54581bf3-c9a1-4bbf-945c-28d436ffda2a@k13g2000prh.googlegroups.com>

On Aug 8, 11:17?am, "Martin v. L?wis"  wrote:
> > This is probably a stupid question, but Is there going to be any data
> > loss if it turns out that the disk has died completely? I assume there
> > are backups of the repo that are geographically distributed.
>
> Yes, we have backups, and are restoring them at the moment. However,
> we still haven't given up on the original disks: they are (probably)
> fine; it's just the RAID controller that has failed (and we can't buy a
> replacement before Monday).
>
> Regards,
> Martin

Is there a mirror site to download the latest python installer? Every
mirror I have found on the web redirects me to python.org.
Best
Peter


From sharath20284 at gmail.com  Sat Aug  8 14:49:13 2009
From: sharath20284 at gmail.com (Sharath)
Date: Sat, 8 Aug 2009 11:49:13 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
	
	<4A7DC141.9070207@v.loewis.de>
	<54581bf3-c9a1-4bbf-945c-28d436ffda2a@k13g2000prh.googlegroups.com>
Message-ID: <4cea29ee-cc89-4494-aef9-0f46f8dd11b9@2g2000prl.googlegroups.com>

On Aug 8, 11:33?am, Pouya Khankhanian  wrote:
> On Aug 8, 11:17?am, "Martin v. L?wis"  wrote:
>
> > > This is probably a stupid question, but Is there going to be any data
> > > loss if it turns out that the disk has died completely? I assume there
> > > are backups of the repo that are geographically distributed.
>
> > Yes, we have backups, and are restoring them at the moment. However,
> > we still haven't given up on the original disks: they are (probably)
> > fine; it's just the RAID controller that has failed (and we can't buy a
> > replacement before Monday).
>
> > Regards,
> > Martin
>
> Is there a mirror site to download the latest python installer? Every
> mirror I have found on the web redirects me to python.org.
> Best
> Peter


Python FTP mirror sites also have the same problem. They are not being
mirrored for some require a password. Is there any other way to get a
copy?

Sharath Venkatesha


From no.email at please.post  Sat Aug  8 14:49:28 2009
From: no.email at please.post (kj)
Date: Sat, 8 Aug 2009 18:49:28 +0000 (UTC)
Subject: Why all the __double_underscored_vars__?
References: 
	
	
	
Message-ID: 

In  David Cournapeau  writes:

>On Sat, Aug 8, 2009 at 9:11 PM, kj wrote:
>> In  Chris Rebert p2 at rebertia.com> writes:
>>
>>>The double-underscores indicate that the Python interpreter itself
>>>usually is the caller of the method, and as such some level of "magic"
>>>may be associated with it. Other languages have you do the equivalent
>>>of `def +():` or `def operator +()` to override an operator, the
>>>keyword or symbol serving a similar warning that "here be magic".
>>
>> In this case, then I hope that some of these __items__ get demoted
>> to a more mundane level, so that the notion of "magic" doesn't get
>> trivialized by everyday idioms like:
>>
>> if __name__ =3D=3D '__main__':
>> =C2=A0 =C2=A0# etc
>>
>> There are a few in this category... =C2=A0I figure that they are cases
>> of "atavistic magic".
>>
>> I bring this up because I find it quite difficult to explain to my
>> students (who are complete newcomers to programming) all the
>> __underscored__ stuff that even rank noobs like them have to deal
>> with. =C2=A0(Trust me, to most of them your reply to my post would be
>> as clear as mud.)

>Maybe your students do not need to know about it, at least at the
>beginning ? I heavily use python, and do not use the underscore
>methods so much most of the time, except for __init__,

Believe me, it's not me who's bringing this stuff up: *they*
specifically ask.  That's precisely my point: it is *they* who
somehow feel they can't avoid finding out about this stuff; they
must run into such __arcana__ often enough to cause them to wonder.
If at least some rank beginners (i.e. some of my students) feel
this way, I suggest that some of this alleged __arcana__ should be
demoted to a more mundane everyday status, without the scare-underscores.
E.g. maybe there should be a built-in is_main(), or some such, so
that beginners don't have to venture into the dark underworld of
__name__ and "__main__".

kynn


From kyrie at uh.cu  Sat Aug  8 15:13:04 2009
From: kyrie at uh.cu (Luis Alberto Zarrabeitia Gomez)
Date: Sat, 08 Aug 2009 15:13:04 -0400
Subject: Subclass dynamically
In-Reply-To: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com>
References: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com>
Message-ID: <1249758784.4a7dce40af627@mail.uh.cu>


Quoting Robert Dailey :

> Hey,
> 
> I have a class that I want to have a different base class depending on
> a parameter that I pass to its __init__method. For example
> (pseudocode):

1- Are you sure that you want that behavior? Given that in python, a class is
just a particular case of invocable object, you could just write a function
instead, and the code may be more robust.

2- If you are /sure/ that is the behavior you want, take a look at the __new__
method. The __new__ can decide which instance to return (you could even define a
new class inside of it, instantiate it, and return the instance).

3- You may want to take a look at metaclasses. But without more details about
why you want it, I can't give you more precise answers.

Regards,

-- 
Luis Zarrabeitia
Facultad de Matem?tica y Computaci?n, UH
http://profesores.matcom.uh.cu/~kyrie



-- 
Participe en Universidad 2010, del 8 al 12 de febrero de 2010
La Habana, Cuba 
http://www.universidad2010.cu



From breamoreboy at yahoo.co.uk  Sat Aug  8 15:27:49 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Sat, 08 Aug 2009 20:27:49 +0100
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>		<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>			<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
Message-ID: 

Kee Nethery wrote:
> As someone trying to learn the language I want to say that the tone on 
> this list towards people who are trying to learn Python  feels like it 
> has become anti-newbies.
> 
[snip]
> 
> Kee Nethery
My gut feeling (which could of course be wrong) is that many hard core 
Pythonistas are cheesed off with newbies who refuse to help themselves.
No evidence that that they've tried any Python tutorial.  No evidence 
that that they've searched anywhere in an attempt to resolve the problem 
before posting.  "This code doesn't work, please fix it".  Response 
often "Please post your actual code, or a snippet that gives the same 
exception, and give the complete exception details".

Show that you have made an attempt to help yourself, and the response 
here is almost certainly 100% helpful.

Further, I have seen many requests here which are nothing really to do 
with Python, say a query about which algorithm to use.  Response "Not 
really a Python question, but try ...".  Put the same question on (say) 
the C ng and you'd be told in no uncertain terms to Foxtrot Oscar.

-- 
Kindest regards.

Mark Lawrence.



From http  Sat Aug  8 15:37:01 2009
From: http (Paul Rubin)
Date: 08 Aug 2009 12:37:01 -0700
Subject: unique-ifying a list
References: 
	
Message-ID: <7x8whum71e.fsf@ruckus.brouhaha.com>

Dennis Lee Bieber  writes:
> 	Why bother with	seen	?

The version with seen runs in linear time because of the O(1) set
lookup.  Your version runs in quadratic time.


From contact at xavierho.com  Sat Aug  8 16:35:42 2009
From: contact at xavierho.com (Xavier Ho)
Date: Sun, 9 Aug 2009 06:35:42 +1000
Subject: www.python.org website is down?
In-Reply-To: <4cea29ee-cc89-4494-aef9-0f46f8dd11b9@2g2000prl.googlegroups.com>
References: 
	
	
	<4A7DC141.9070207@v.loewis.de>
	<54581bf3-c9a1-4bbf-945c-28d436ffda2a@k13g2000prh.googlegroups.com>
	<4cea29ee-cc89-4494-aef9-0f46f8dd11b9@2g2000prl.googlegroups.com>
Message-ID: <2d56febf0908081335r23a03895i16bf3b5551a7823a@mail.gmail.com>

Well, it's back up now.

At least for me. ;)

Ching-Yun "Xavier" Ho, Technical Artist

Contact Information
Mobile: (+61) 04 3335 4748
Skype ID: SpaXe85
Email: contact at xavierho.com
Website: http://xavierho.com/


On Sun, Aug 9, 2009 at 4:49 AM, Sharath  wrote:

> On Aug 8, 11:33 am, Pouya Khankhanian  wrote:
> > On Aug 8, 11:17 am, "Martin v. L?wis"  wrote:
> >
> > > > This is probably a stupid question, but Is there going to be any data
> > > > loss if it turns out that the disk has died completely? I assume
> there
> > > > are backups of the repo that are geographically distributed.
> >
> > > Yes, we have backups, and are restoring them at the moment. However,
> > > we still haven't given up on the original disks: they are (probably)
> > > fine; it's just the RAID controller that has failed (and we can't buy a
> > > replacement before Monday).
> >
> > > Regards,
> > > Martin
> >
> > Is there a mirror site to download the latest python installer? Every
> > mirror I have found on the web redirects me to python.org.
> > Best
> > Peter
>
>
> Python FTP mirror sites also have the same problem. They are not being
> mirrored for some require a password. Is there any other way to get a
> copy?
>
> Sharath Venkatesha
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From aahz at pythoncraft.com  Sat Aug  8 16:37:21 2009
From: aahz at pythoncraft.com (Aahz)
Date: 8 Aug 2009 13:37:21 -0700
Subject: python.org downtime (was Re: is it possible to overload operator "^"?)
References: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
	<7e4tg5F2eirarU1@mid.uni-berlin.de>
	
Message-ID: 

In article ,
dmitrey   wrote:
>
>To Diez:
>yes, but I haven't paid attention to xor. BTW the url is currently
>unavailable (Network Timeout. The server at docs.python.org is taking
>too long to respond.).

www.python.org is currently having hardware problems
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz


From clp2 at rebertia.com  Sat Aug  8 16:41:42 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Sat, 8 Aug 2009 16:41:42 -0400
Subject: Serial port access
In-Reply-To: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
References: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
Message-ID: <50697b2c0908081341o63636f36i99b5971fdb0bbb57@mail.gmail.com>

On Sat, Aug 8, 2009 at 12:34 PM, nipun batra wrote:
> Hi,
> How can we access serial port using usb-serial converters,using python in
> linux.

PySerial might also be an option:
http://pyserial.sourceforge.net/index.html

Cheers,
Chris
-- 
http://blog.rebertia.com


From contact at xavierho.com  Sat Aug  8 16:44:09 2009
From: contact at xavierho.com (Xavier Ho)
Date: Sun, 9 Aug 2009 06:44:09 +1000
Subject: python.org downtime (was Re: is it possible to overload operator 
	"^"?)
In-Reply-To: 
References: <89523a6b-c609-4b3f-9f01-4aa219dfd916@g6g2000vbr.googlegroups.com>
	<7e4tg5F2eirarU1@mid.uni-berlin.de>
	
	
Message-ID: <2d56febf0908081344n10fb56eo1fe108cbb824901f@mail.gmail.com>

On Sun, Aug 9, 2009 at 6:37 AM, Aahz  wrote:

> www.python.org is currently having hardware problems
>

So what I'm seeing is an illusion? It works as of now.

- Xavier
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From Scott.Daniels at Acm.Org  Sat Aug  8 17:50:32 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Sat, 08 Aug 2009 14:50:32 -0700
Subject: Why all the __double_underscored_vars__?
In-Reply-To: 
References: 
	
	
	
	
Message-ID: 

kj wrote:
>>> ... I find it quite difficult to explain to my
>>> students (who are complete newcomers to programming) all the
>>> __underscored__ stuff that even rank noobs like them have to deal
>>> with. =C2=A0(Trust me, to most of them your reply to my post would be
>>> as clear as mud.)
> Believe me, it's not me who's bringing this stuff up: *they*
> specifically ask.  That's precisely my point: it is *they* who
> somehow feel they can't avoid finding out about this stuff; they
> must run into such __arcana__ often enough to cause them to wonder.
> If at least some rank beginners (i.e. some of my students) feel
> this way, I suggest that some of this alleged __arcana__ should be
> demoted to a more mundane everyday status, without the scare-underscores.
> E.g. maybe there should be a built-in is_main(), or some such, so
> that beginners don't have to venture into the dark underworld of
> __name__ and "__main__".

Do you know about Kirby Urner's technique of calling such symbols,
"ribs," -- the access to the "stuff" Python is built from?  One nice
thing about Python is that you can experiment with what these
"__ribs__" do without having to learn yet another language.

It seems nice to me that you can use a rule that says, "stick to
normal names and you don't have to worry about mucking with the
way Python itself works, but if you are curious, looks for those
things and fiddle with them."

--Scott David Daniels
Scott.Daniels at Acm.Org


From kpouya at gmail.com  Sat Aug  8 17:50:34 2009
From: kpouya at gmail.com (Pouya Khankhanian)
Date: Sat, 8 Aug 2009 14:50:34 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
	
	<4A7DC141.9070207@v.loewis.de>
	<54581bf3-c9a1-4bbf-945c-28d436ffda2a@k13g2000prh.googlegroups.com>
	<4cea29ee-cc89-4494-aef9-0f46f8dd11b9@2g2000prl.googlegroups.com>
Message-ID: <80c46b94-9df2-43f5-9182-37c2413db783@b25g2000prb.googlegroups.com>

On Aug 8, 11:49?am, Sharath  wrote:
> On Aug 8, 11:33?am, Pouya Khankhanian  wrote:
>
>
>
> > On Aug 8, 11:17?am, "Martin v. L?wis"  wrote:
>
> > > > This is probably a stupid question, but Is there going to be any data
> > > > loss if it turns out that the disk has died completely? I assume there
> > > > are backups of the repo that are geographically distributed.
>
> > > Yes, we have backups, and are restoring them at the moment. However,
> > > we still haven't given up on the original disks: they are (probably)
> > > fine; it's just the RAID controller that has failed (and we can't buy a
> > > replacement before Monday).
>
> > > Regards,
> > > Martin
>
> > Is there a mirror site to download the latest python installer? Every
> > mirror I have found on the web redirects me to python.org.
> > Best
> > Peter
>
> Python FTP mirror sites also have the same problem. They are not being
> mirrored for some require a password. Is there any other way to get a
> copy?
>
> Sharath Venkatesha

Website is back up! Thanks for all the hard work


From efotinis at y  Sat Aug  8 18:05:01 2009
From: efotinis at y (Elias Fotinis (eliasf))
Date: Sun, 9 Aug 2009 01:05:01 +0300
Subject: Pywin32 @ windows 7
In-Reply-To: 
References: <004a01ca1733$a9768c10$4605a8c0@btsc1><1249724885.215365@athprx03>
	
Message-ID: <1249769137.332546@athprx03>

"Dennis Lee Bieber" wrote:
> Has it been built under a 64-bit OS though? (I'll confess I've not
> looked -- I always install the ActiveState binary for my WinXP (32bit)
> system, and that library is part of the install)

Yes, both Python x64 and pywin32 x64 are native 64-bit applications -- they 
can't even be installed on a 32-bit system. 



From pavlovevidence at gmail.com  Sat Aug  8 18:39:16 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sat, 8 Aug 2009 15:39:16 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
Message-ID: <47b58ea9-d199-41f7-8d7b-8de382f85396@m7g2000prd.googlegroups.com>

On Aug 6, 11:36?am, Kee Nethery  wrote:
> As someone trying to learn the language I want to say that the tone on ?
> this list towards people who are trying to learn Python ?feels like it ?
> has become anti-newbies.

I don't think this NG is anti-newbie so much as anti-whining-loser.

Unfortunately, some newbies might see this and perceive it to be abuse
of newbies in general.  It is not so.  People who have chips on their
shoulder, who make loaded, emotionally-provocative comments, who make
no effort on their own, who expect us to do their homework and/or job
for them, etc., there are the people who going to get an unfavorable
tone.

Newbies who ask respectable questions without having an attitude will
generally get respectable answers.


> For example, the guy who was looking for Python sample code for the ?
> Google Map API, calling him a troll was harsh.

No it wasn't, that guy is Xah Lee, a person who's been trolling Usenet
for a long time.  He is best ignored, but I don't blame someone for
snapping at him.


Carl Banks


From pavlovevidence at gmail.com  Sat Aug  8 19:10:20 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sat, 8 Aug 2009 16:10:20 -0700 (PDT)
Subject: Subclass dynamically
References: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com>
	
Message-ID: <478f321d-3d88-4074-af17-1bc3d509e6b3@x25g2000prf.googlegroups.com>

On Aug 8, 12:13?pm, Luis Alberto Zarrabeitia Gomez 
wrote:
> Quoting Robert Dailey :
>
> > Hey,
>
> > I have a class that I want to have a different base class depending on
> > a parameter that I pass to its __init__method. For example
> > (pseudocode):
>
> 1- Are you sure that you want that behavior? Given that in python, a class is
> just a particular case of invocable object, you could just write a function
> instead, and the code may be more robust.
>
> 2- If you are /sure/ that is the behavior you want, take a look at the __new__
> method. The __new__ can decide which instance to return (you could even define a
> new class inside of it, instantiate it, and return the instance).
>
> 3- You may want to take a look at metaclasses. But without more details about
> why you want it, I can't give you more precise answers.

One could accomplish this using methods 2 and 3, but it would go
against so many common expectations I have to recommend never doing
it.  If you call a type, it should return an object of that type (or,
at worst, a subtype or "null" type) or raise an exception.

The factory function is the way to do this.

Another alternative is to forego inheritance and simply call method on
the passed "base" object.  Given that the OP posted code that almost
literally works in that case, this might be the best way to go for his
case.

So instead of this hypothetical code:

class MyDerived(self.base):
    def __init__(self,base)
        self.base = base
    # MyDerived inherits a_method() from self.base

He could go with this real code:

class MyClass(object):
    def __init__(self,base)
        self.base = base
    def a_method(self):
        return self.base.a_method()

where, instead of inheriting self.base's a_method, it simply defines
a_method() to call self.base.a_method() directly.


Carl Banks


From michael at stroeder.com  Sat Aug  8 19:42:14 2009
From: michael at stroeder.com (=?UTF-8?B?TWljaGFlbCBTdHLDtmRlcg==?=)
Date: Sun, 09 Aug 2009 01:42:14 +0200
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 		<2qcrk6-doj.ln1@nb2.stroeder.com>
	
Message-ID: 

Michael F?tsch wrote:
> If speed is your primary concern, this will give you even better
> performance than unicode():
> 
>   decoder = codecs.lookup("utf-8").decode
>   for i in xrange(1000000):
>       decoder("???????")[0]

Hmm, that could be interesting. I will give it a try.

> However, there's also a functional difference between unicode() and
> str.decode():
> 
> unicode() always raises an exception when you try to decode a unicode
> object. str.decode() will first try to encode a unicode object using the
> default encoding (usually "ascii"), which might or might not work.

Thanks for pointing that out. So in my case I'd consider that also a plus for
using unicode().

Ciao, Michael.


From BrianVanderburg2 at aim.com  Sat Aug  8 21:08:38 2009
From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II)
Date: Sat, 08 Aug 2009 21:08:38 -0400
Subject: How to do relpath implementation on 2.5
Message-ID: <4A7E2196.2080403@aim.com>

I've coded my own 'relpath' implementation for 2.5 (shown below) and I 
want to make sure it follows as closely as it should to 2.6 and later.  
I've got a question regarding that.  When attempting to convert to a 
relative path and it is not possible for some reason (different drive or 
UNC share), should that be an error or should it return the absolute 
path of the target?  I'm using Debian so I don't have 2.6 available 
right now for testing.

This is what I've got so far

import os
from os import path


def relpath(target, origin=os.curdir):
    """
    Determine relative path of target to origin or
    """

    target = path.normcase(path.abspath(path.normpath(target)))
    origin = path.normcase(path.abspath(path.normpath(origin)))

    # Same?
    if target == origin:
        return '.'

    original_target = target

    # Check drive (for Windows)
    (tdrive, target) = path.splitdrive(target)
    (odrive, origin) = path.splitdrive(origin)
    if tdrive != odrive:
        return original_target

    # Check UNC path (for Windows)
    # If they are on different shares, we want an absolute path
    if not tdrive and not odrive and hasattr(path, 'splitunc'):
        (tunc, target) = path.splitunc(target)
        (ounc, origin) = path.splitunc(origin)
        if tunc != ounc:
            return original_target

    # Split into lists
    target_list = target.split(os.sep)
    origin_list = origin.split(os.sep)

    # Remove beginning empty parts
    # Helps to handle when one item may be in the root
    while target_list and not target_list[0]:
        del target_list[0]
    while origin_list and not origin_list[0]:
        del origin_list[0]

    # Remove common items
    while origin_list and target_list:
        if origin_list[0] == target_list[0]:
            del origin_list[0]
            del target_list[0]
        else:
            break

    # Combine and return the result
    relative_list = [os.pardir] * len(origin_list) + target_list
    if not relative_list:
        return os.curdir
    return os.sep.join(relative_list)


Currently I just return the target if it can not be made relative.

Brian A. Vanderburg II


From nipunreddevil at gmail.com  Sat Aug  8 21:20:12 2009
From: nipunreddevil at gmail.com (nipun batra)
Date: Sun, 9 Aug 2009 06:50:12 +0530
Subject: Serial port access
In-Reply-To: <50697b2c0908081341o63636f36i99b5971fdb0bbb57@mail.gmail.com>
References: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
	<50697b2c0908081341o63636f36i99b5971fdb0bbb57@mail.gmail.com>
Message-ID: <1e61b3260908081820r702a4e24s6599fa724c97344a@mail.gmail.com>

On Sun, Aug 9, 2009 at 2:11 AM, Chris Rebert  wrote:

> On Sat, Aug 8, 2009 at 12:34 PM, nipun batra
> wrote:
> > Hi,
> > How can we access serial port using usb-serial converters,using python in
> > linux.
>
> PySerial might also be an option:
> http://pyserial.sourceforge.net/index.html
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>


pySerial mentions about serial ports but not about usb-serial.Can i do
something like convert my usb-serial to act as serial port and then use
pySerial
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From thudfoo at opensuse.us  Sat Aug  8 21:41:23 2009
From: thudfoo at opensuse.us (member thudfoo)
Date: Sat, 8 Aug 2009 18:41:23 -0700
Subject: Is "feedparser" deprecated?
In-Reply-To: 
References: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
	
Message-ID: <3d881a310908081841x17235cf1rd38418b119dd7b4d@mail.gmail.com>

On Fri, Aug 7, 2009 at 6:10 PM, Gabriel Genellina wrote:

> En Fri, 07 Aug 2009 16:07:48 -0300, John Nagle 
> escribi?:
>
>    Feedparser requires SGMLlib, which has been removed from Python 3.0.
>> Feedparser hasn't been updated since 2007. Does this mean Feedparser
>> is dead?
>>
>
> Since we have generic and easy of use XML parsers like ElementTree and
> lxml,  specialized rss parsers like feedparser are not so much required.
> I've used ElementTree when I had to parse an rss feed in the past (not so
> many times).
>
> --
> Gabriel Genellina
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

feedparser is much more than than an just  another xml
 parser.

Read its documetion.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From zac256 at gmail.com  Sat Aug  8 21:52:17 2009
From: zac256 at gmail.com (Zac Burns)
Date: Sat, 8 Aug 2009 18:52:17 -0700
Subject: Why all the __double_underscored_vars__?
In-Reply-To: 
References: 
	
	
	
	
	
Message-ID: <333edbe80908081852i4fd753er5656216cbb1b06e2@mail.gmail.com>

As I understand it, the double underscores is to create a namespace
"reserved for python's internal use". That way python can add more
variables and methods in the future and as long as people respect the
namespace their code will not break with future revisions.

--
Zachary Burns
(407)590-4814
Aim - Zac256FL
Production Engineer (Digital Overlord)
Zindagi Games


From dstanek at dstanek.com  Sat Aug  8 23:15:36 2009
From: dstanek at dstanek.com (David Stanek)
Date: Sat, 8 Aug 2009 23:15:36 -0400
Subject: Is "feedparser" deprecated?
In-Reply-To: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
References: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
Message-ID: 

On Fri, Aug 7, 2009 at 3:07 PM, John Nagle wrote:
> ?Feedparser requires SGMLlib, which has been removed from Python 3.0.
> Feedparser hasn't been updated since 2007. Does this mean Feedparser
> is dead?
>

The release is from 2007, but there are several recent commits.

http://code.google.com/p/feedparser/source/list


-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek


From michaelmossey at gmail.com  Sun Aug  9 00:43:32 2009
From: michaelmossey at gmail.com (Michael Mossey)
Date: Sat, 8 Aug 2009 21:43:32 -0700 (PDT)
Subject: help with threads
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
	<949b87d5-8cff-444a-b6ba-23d49610d130@p36g2000vbn.googlegroups.com> 
	 
	
Message-ID: 

On Aug 7, 5:03?pm, Piet van Oostrum  wrote:
> >>>>> Michael Mossey  (MM) wrote:
> >MM> Ah yes, that explains it. Some of these long computations are done in
> >MM> pure C, so I'm sure the GIL is not being released.
>
> Is that C code under your own control? Or at least the glue from Python
> to C? In that case, and if the C code is not manipulating Python objects
> or something in the Python interpreter, it could be changed to release
> the GIL during the computation. That's also how Numpy does it, IIRC.
> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: p... at vanoostrum.org

I don't have any control over this code, and it's easier to solve my
problem in other ways. I just put a sleep() call between calls to the
C library, and that gives the network thread enough responsiveness for
my particular task. I am grateful, anyway, to understand why this kind
of thing happens.


From martin at v.loewis.de  Sun Aug  9 00:49:08 2009
From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
Date: Sun, 09 Aug 2009 06:49:08 +0200
Subject: .h files?
In-Reply-To: <50c453d9-d455-4f08-959c-e225149495fb@i18g2000pro.googlegroups.com>
References: <50c453d9-d455-4f08-959c-e225149495fb@i18g2000pro.googlegroups.com>
Message-ID: <4a7e5544$0$2550$9b622d9e@news.freenet.de>

> Question.  Seems that with python distributions you have the option to
> include either "external facing, public" *.h files, and make them
> available, or include the whole kit and kaboodle [all *.h files].

What python distributions are you referring to? The ones I know don't
make this distinction; there is only a single set of header files that
you can choose to install.

Regards,
Martin


From nipunreddevil at gmail.com  Sun Aug  9 00:51:20 2009
From: nipunreddevil at gmail.com (nipun batra)
Date: Sun, 9 Aug 2009 10:21:20 +0530
Subject: Serial port access
In-Reply-To: <1e61b3260908081820r702a4e24s6599fa724c97344a@mail.gmail.com>
References: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
	<50697b2c0908081341o63636f36i99b5971fdb0bbb57@mail.gmail.com>
	<1e61b3260908081820r702a4e24s6599fa724c97344a@mail.gmail.com>
Message-ID: <1e61b3260908082151l1fed2afena6db9bc239da5c6a@mail.gmail.com>

Ok i managed to comunicate serially using pySerial,but only using Idle. but
when i use it within Geany or Gedit,i get following errors
Traceback most recent call last
File "serial.py",line 3,in module
import serial
File"/home/nipun/serial.py",line 5,in module
ser=serial.Serial()
Attribute error:module object has no attribute Serial

how can i make it work?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From wuwei23 at gmail.com  Sun Aug  9 01:16:53 2009
From: wuwei23 at gmail.com (alex23)
Date: Sat, 8 Aug 2009 22:16:53 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com> 
	<7xd476rj1s.fsf@ruckus.brouhaha.com>
Message-ID: 

Paul Rubin  wrote:
> Stephen, Alex, etc.: have you actually used the php.net doc system?
> Don't knock it til you've tried it. ?IMO it is superior to Python's
> system. ?

I've tried it, a lot. Is it okay for me to keep criticising it now, or
would you like some time to find some other allusion to ignorance with
which to wave away my opinion?


From kwatch at gmail.com  Sun Aug  9 01:37:03 2009
From: kwatch at gmail.com (kwatch)
Date: Sat, 8 Aug 2009 22:37:03 -0700 (PDT)
Subject: [ANN] pyKook 0.0.3 - a smart build tool similar to Make, Rake, or Ant
Message-ID: <06fbfe63-2ee2-4669-91cc-2df12ea4bd86@i4g2000prm.googlegroups.com>

Hi,

I have released pyKook 0.0.3.
http://pypi.python.org/pypi/Kook/0.0.3
http://www.kuwata-lab.com/kook/
http://www.kuwata-lab.com/kook/pykook-users-guide.html

In this release, recipe syntax is changed (see below).


Overview
========

pyKook is a smart build tool similar to Make, Rake, Ant, or Cook.
pyKook regards software project as cooking.
Terms used in pyKook are cooking terms.
For example:

    cookbook    -  Makefile
    product     -  target file
    ingredient  -  source file
    recipe      -  how to create target from source
    spices      -  command-line options for recipe


Cookbook (= Makefile) is written in pure Python.
You can write any statements or expressions in cookbook.

NOTICE: pyKook is under alpha release. Spec and features may be
changed
in the future without previous announcement.


Example
=======

Example of cookbook (Kookbook.py):

    --------------------------------------------------
    ##
    ## properties
    ##
    cc     = prop('cc',     'gcc')
    cflags = prop('cflags', '-g -Wall')


    ##
    ## recipes
    ##
    @recipe
    @ingreds("hello")
    def all(c):        # or task_all(c)
        pass

    @recipe
    @product("hello")
    @ingreds("hello.o")
    def file_command(c):
        """generates hello command"""
        system(c%"$(cc) $(cflags) -o $(product) $(ingred)")

    @recipe
    @product("*.o")
    @ingreds("$(1).c", if_exists("$(1).h"))
    def file_ext_o(c):
        """compile '*.c' and '*.h'"""
        system(c%"$(cc) $(cflags) -c $(1).c")

    @recipe
    def clean(c):
        rm_f("*.o")
    --------------------------------------------------


Exampe of result:

    --------------------------------------------------
    bash> ls
    Kookbook.py   hello.c    hello.h

    bash> pykook -l
    Properties:
      cc                  : 'gcc'
      cflags              : '-g -Wall'

    Task recipes:
      all                 : cook all products
      clean               : remove by-products

    File recipes:
      hello               : generates hello command
      *.o                 : compile '*.c' and '*.h'

    (Tips: you can set 'kook_default_product' variable in your
kookbook.)

    bash> pykook all           # or, pykook --cc=gcc4 all
    ### *** hello.o (func=file_ext_o)
    $ gcc -g -Wall -c hello.c
    ### ** hello (func=file_command)
    $ gcc -g -Wall -o hello hello.o
    ### * all (func=task_all)
    --------------------------------------------------


See users-guide for more details.
http://www.kuwata-lab.com/kook/pykook-users-guide.html


Enhancements, Changes, Bug fixes sice 0.0.2
===========================================


Changes
-------

  - IMPORTANT!!
    New '@recipe' decorator is required for each recipe function.
    If function is decorated by '@recipe', 'task_' prefix is not
necessary.

    ex:
      ## previous version
  	  def task_clean(c):    # 'task_' prefix is required
  	    rm_rf("*.o")

      ## since this release
  	  @release              # @release decorator is required
  	  def clean(c):         # 'task_' prefix is not necessary
  	    rm_rf("*.o")

    See http://www.kuwata-lab.com/kook/pykook-users-guide.html#cookbook-recipekind
  	for details.

  - Library codes are much refactored.


Enhancements
------------

  - IMPORTANT!!
    New feature to support command-line script framework.
    You can convert Kookbook.py into command-line script.
	See http://www.kuwata-lab.com/kook/pykook-users-guide.html#topic-framework
	for details.

  - New command-line option '-n' (no exec) supported.
    If you specify '-n', commands such as 'cp()' or 'rm()' are not
executed.
	In other words, '-n' means 'dry-run'.

  - Add a lot of test scripts.


Bug fixes
---------

  - A bug related timestamp detection is now fixed.
    There was a case that product file was not updated even when
    ingredient files were updated.

  - A bug about recipe tree is fixed. There was a case that the same
recipe
    can be invoke more than once when an intermediate recipe was
required
    from several recipes.



Have fun!

--
regards,
makoto kuwata


From rylesny at gmail.com  Sun Aug  9 03:49:42 2009
From: rylesny at gmail.com (ryles)
Date: Sun, 9 Aug 2009 00:49:42 -0700 (PDT)
Subject: How to do relpath implementation on 2.5
References: 
Message-ID: 

On Aug 8, 9:08?pm, Brian Allen Vanderburg II
 wrote:
> I've coded my own 'relpath' implementation for 2.5 (shown below) and I
> want to make sure it follows as closely as it should to 2.6 and later. ?
> I've got a question regarding that. ?When attempting to convert to a
> relative path and it is not possible for some reason (different drive or
> UNC share), should that be an error or should it return the absolute
> path of the target? ?I'm using Debian so I don't have 2.6 available
> right now for testing.

Usually Python source code is easily browsed at:

http://svn.python.org/view/

Unfortunately the server is down right now.

The implementation in 2.6 raises a ValueError exception. Here is the
function from ntpath.py:

def relpath(path, start=curdir):
    """Return a relative version of a path"""

    if not path:
        raise ValueError("no path specified")
    start_list = abspath(start).split(sep)
    path_list = abspath(path).split(sep)
    if start_list[0].lower() != path_list[0].lower():
        unc_path, rest = splitunc(path)
        unc_start, rest = splitunc(start)
        if bool(unc_path) ^ bool(unc_start):
            raise ValueError("Cannot mix UNC and non-UNC paths (%s and
%s)"
                                                                %
(path, start))
        else:
            raise ValueError("path is on drive %s, start on drive %s"
                                                % (path_list[0],
start_list[0]))
    # Work out how much of the filepath is shared by start and path.
    for i in range(min(len(start_list), len(path_list))):
        if start_list[i].lower() != path_list[i].lower():
            break
    else:
        i += 1

    rel_list = [pardir] * (len(start_list)-i) + path_list[i:]
    if not rel_list:
        return curdir
    return join(*rel_list)


From asmodai at in-nomine.org  Sun Aug  9 04:41:11 2009
From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven)
Date: Sun, 9 Aug 2009 10:41:11 +0200
Subject: unicode() vs. s.decode()
In-Reply-To: 
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	
	
Message-ID: <20090809084111.GB30241@nexus.in-nomine.org>

-On [20090808 20:07], Thorsten Kampe (thorsten at thorstenkampe.de) wrote:
>In real life people won't even notice whether an application takes one or
>two minutes to complete.

I think you are quite wrong here.

I have worked with optical engineers who needed to calculate grating numbers
for their lenses. If they can have a calculation program that runs in 1
minute instead of 2 they can effectively double their output during the day
(since they run calculations hundreds to thousand times a day to get the
most optimal results with minor tweaks).

I think you are being a bit too easy on hand waving here that mere minute
runtimes are not noticeable.

-- 
Jeroen Ruigrok van der Werven  / asmodai
????? ?????? ??? ?? ??????
http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B
When we have not what we like, we must like what we have...


From steve at REMOVE-THIS-cybersource.com.au  Sun Aug  9 04:48:16 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 09 Aug 2009 08:48:16 GMT
Subject: Why all the __double_underscored_vars__?
References: 
	
	
Message-ID: <00081096$0$2954$c3e8da3@news.astraweb.com>

On Sat, 08 Aug 2009 12:11:19 +0000, kj wrote:

> In  Chris Rebert
>  writes:
> 
>>The double-underscores indicate that the Python interpreter itself
>>usually is the caller of the method, and as such some level of "magic"
>>may be associated with it. Other languages have you do the equivalent of
>>`def +():` or `def operator +()` to override an operator, the keyword or
>>symbol serving a similar warning that "here be magic".
> 
> In this case, then I hope that some of these __items__ get demoted to a
> more mundane level, so that the notion of "magic" doesn't get
> trivialized by everyday idioms like:
> 
> if __name__ == '__main__':
>     # etc

But that is magic, and just because it's magic doesn't mean it's not 
useful every day.

I don't see what's so difficult about telling your students that double 
underscore names have special meaning to the Python interpreter. That 
doesn't mean you're forbidden from using them, or that you have to use 
them, it just means that they have a special meaning to the interpreter, 
and you usually don't call them directly.



-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Sun Aug  9 05:07:31 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 09 Aug 2009 09:07:31 GMT
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	
Message-ID: <00081519$0$2954$c3e8da3@news.astraweb.com>

On Sat, 08 Aug 2009 20:27:49 +0100, Mark Lawrence wrote:

> Further, I have seen many requests here which are nothing really to do
> with Python, say a query about which algorithm to use.  Response "Not
> really a Python question, but try ...".  Put the same question on (say)
> the C ng and you'd be told in no uncertain terms to Foxtrot Oscar.

We're a lot friendlier than the C newsgroup.

Personally, I think knowing the right algorithm to use is as much a part 
of Python programming as knowing whether to call mystring.upper() or 
string.upper(mystring).


-- 
Steven


From mh at pixar.com  Sun Aug  9 05:37:52 2009
From: mh at pixar.com (mh at pixar.com)
Date: 09 Aug 2009 09:37:52 GMT
Subject: tracing openurl input and output?
Message-ID: <4a7e98f0$0$9288$386e9d2@news.usenetserver.com>

How can I watch the messages being sent back and for on urllib shttp
requests?  If it were simple http I would just watch the socket traffic
but of course that won't work for https.  Is there a debug flag I can
set that will do this?

context:  I am dealing with a web service bug and I want to tell
the provider exactly what is going back and forth to his server,
eliminating the "maybe there's a bug in your library" chat.

    import urllib
    params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
    f = urllib.urlopen("https://example.com/cgi-bin/query", params)

Many TIA!

-- 
Mark Harrison
Pixar Animation Studios


From steve at REMOVE-THIS-cybersource.com.au  Sun Aug  9 06:01:25 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 09 Aug 2009 10:01:25 GMT
Subject: unicode() vs. s.decode()
References: 
	
	<2qcrk6-doj.ln1@nb2.stroeder.com>
	
	<028b1ce0$0$5185$c3e8da3@news.astraweb.com>
	
	<556b00a3-bbbf-4076-a300-d20839a313c8@v23g2000pro.googlegroups.com>
	
	<0006746a$0$2895$c3e8da3@news.astraweb.com>
	
	<41a0l6-2u4.ln1@nb2.stroeder.com>
	
Message-ID: <000821ba$0$2954$c3e8da3@news.astraweb.com>

On Sat, 08 Aug 2009 19:00:11 +0200, Thorsten Kampe wrote:

>> I was running it one million times to mitigate influences on the timing
>> by other background processes which is a common technique when
>> benchmarking.
> 
> Err, no. That is what "repeat" is for and it defaults to 3 ("This means
> that other processes running on the same computer may interfere with the
> timing. The best thing to do when accurate timing is necessary is to
> repeat the timing a few times and use the best time. [...] the default
> of 3 repetitions is probably enough in most cases.")


It's useful to look at the timeit module to see what the author(s) think.

Let's start with the repeat() method. In the Timer docstring:

"The repeat() method is a convenience to call timeit() multiple times and 
return a list of results."

and the repeat() method's own docstring:

"This is a convenience function that calls the timeit() repeatedly, 
returning a list of results.  The first argument specifies how many times 
to call timeit(), defaulting to 3; the second argument specifies the 
timer argument, defaulting to one million."

So it's quite obvious that the module author(s), and possibly even Tim 
Peters himself, consider repeat() to be a mere convenience method. 
There's nothing you can do with repeat() that can't be done with the 
timeit() method itself.

Notice that both repeat() and timeit() methods take an argument to 
specify how many times to execute the code snippet. Why not just execute 
it once? The module doesn't say, but the answer is a basic measurement 
technique: if your clock is accurate to (say) a millisecond, and you 
measure a single event as taking a millisecond, then your relative error 
is roughly 100%. But if you time 1000 events, and measure the total time 
as 1 second, the relative error is now 0.1%.

The authors of the timeit module obvious considered this an important 
factor: not only did they allow you to specify the number of times to 
execute the code snippet (defaulting to one million, not to one) but they 
had this to say:

[quote]
Command line usage:
    python timeit.py [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement]

Options:
  -n/--number N: how many times to execute 'statement'
 [...]

If -n is not given, a suitable number of loops is calculated by trying
successive powers of 10 until the total time is at least 0.2 seconds.
[end quote]

In other words, when calling the timeit module from the command line, by 
default it will choose a value for n that gives a sufficiently small 
relative error.

It's not an accident that timeit gives you two "count" parameters: the 
number of times to execute the code snippet per timing, and the number of 
timings. They control (partly) for different sources of error.



-- 
Steven


From duncan.booth at invalid.invalid  Sun Aug  9 06:47:15 2009
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 9 Aug 2009 10:47:15 GMT
Subject: tracing openurl input and output?
References: <4a7e98f0$0$9288$386e9d2@news.usenetserver.com>
Message-ID: 

mh at pixar.com wrote:

> How can I watch the messages being sent back and for on urllib shttp
> requests?  If it were simple http I would just watch the socket traffic
> but of course that won't work for https.  Is there a debug flag I can
> set that will do this?
> 
> context:  I am dealing with a web service bug and I want to tell
> the provider exactly what is going back and forth to his server,
> eliminating the "maybe there's a bug in your library" chat.
> 
>     import urllib
>     params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
>     f = urllib.urlopen("https://example.com/cgi-bin/query", params)
> 
> Many TIA!
> 
If you are running on Windows then I'd say get hold of a copy of fiddler2 
(http://www.fiddler2.com/fiddler2/) and tell your code to use it as a 
proxy. It does an excellent job of capturing and decoding web traffic and 
even lets you modify packets as they go past. The only thing to watch for 
with https is that your code will see an invalid certificate as of course 
it sees fiddler's own self signed certificate instead of the original.

I'm not sure what Linux or Mac equivalents there might be (though in a 
pinch you can always run your code on one system and Fiddler on a different 
one).


From nipunreddevil at gmail.com  Sun Aug  9 07:03:04 2009
From: nipunreddevil at gmail.com (nipun batra)
Date: Sun, 9 Aug 2009 16:33:04 +0530
Subject: String algo
Message-ID: <1e61b3260908090403o1b6c5a66w7c59a2bd29e193a1@mail.gmail.com>

I will be receiving data serially from another pc,.i can use any sort of
marker between two packets,i will be the person sending data as well after
reading it from some devices.But packet length is not constant.
each packet has this format:
201.535a56.65b4.56c89.565d
another packet could be :
4a5b6c7d
What i need is a program to store variables such as:var_a has value 4,var_b
has value 5,for second string.
I have to read and write data continuosly using serial port.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From lokeshmaremalla at gmail.com  Sun Aug  9 07:43:33 2009
From: lokeshmaremalla at gmail.com (Lokesh)
Date: Sun, 9 Aug 2009 04:43:33 -0700 (PDT)
Subject: Need help in configuration for TimedRotatingFileHandler
Message-ID: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>

Hi,

Need help in configure the TimedRotatingFileHandler from configuration
file

I have tried with the below code and ended up with the error, code is
pasted below
Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
\logs\rotate_test'
[loggers]
keys=root,simpleExample

[handlers]
keys=consoleHandler,timedRotatingFileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[logger_simpleExample]
level=DEBUG
handlers=timedRotatingFileHandler
qualname=simpleExample
propagate=0

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[handler_timedRotatingFileHandler]
class=handlers.TimedRotatingFileHandler
level=DEBUG
formatter=simpleFormatter
args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt='%Y-%m-%d %H:%M:%S'


Thanks or your time
Regards,
Lokesh


From gert.cuykens at gmail.com  Sun Aug  9 08:14:33 2009
From: gert.cuykens at gmail.com (gert)
Date: Sun, 9 Aug 2009 05:14:33 -0700 (PDT)
Subject: resume upload wsgi script
Message-ID: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>

I working on a resume upload script and encountered the following
problems

sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
'\ufffd\ufff
d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
Content-Disposition: form-data; name="Filename"

DSC00013.JPG
------------Ef1

when I dont use SUBSTR or  COALESCE and || it works

def application(environ, response):
    range=environ.get('HTTP_RANGE','bytes=0-').replace
('bytes=','').split(',')
    offset=[]
    for r in range: offset.append(r.split('-'))
    db.execute('UPDATE users SET picture=SUBSTR(picture,?) WHERE
uid=?', (offset[0][0],s.UID))

    chunk=environ['wsgi.input'].read(int(environ
['CONTENT_LENGTH'])).decode('latin1')
    db.execute('UPDATE users SET picture=COALESCE(picture,?)||? WHERE
uid=?', (''.encode('latin1'),chunk.encode('latin1'), s.UID))

    #while True:
    #      chunk=environ['wsgi.input'].read(8192).decode('latin1')
    #      if not chunk: break
    #      db.execute("UPDATE users SET picture=COALESCE
(picture,'')||? WHERE uid=?", (chunk, s.UID))

the following is the POST clean up when PUT is not used, does anyone
know how to do this without loading the complete blob into memory ?

    db.execute('SELECT picture FROM users WHERE uid=?',(s.UID,))
    f=db.fetch()
    b=environ['CONTENT_TYPE'].split('boundary=')[1]
    p=search(b+r'.*?Content-Type: application/octet-stream\r\n\r\n(.*?)
\r\n--'+b,f[0][0].decode('latin1'),DOTALL).group(1)
    db.execute('UPDATE users SET picture=? WHERE uid=?', (p.encode
('latin1'), s.UID))



From manu3d at gmail.com  Sun Aug  9 08:32:46 2009
From: manu3d at gmail.com (Emanuele D'Arrigo)
Date: Sun, 9 Aug 2009 05:32:46 -0700 (PDT)
Subject: exec("dir()",d)
Message-ID: <9adbf402-3e7e-44a4-adb3-afc36d5d88ba@33g2000vbe.googlegroups.com>

Greetings everybody,

I don't quite understand why if I do this:

>>> d = {}
>>> exec("dir()", d)

1) d is no longer empty
2) the content of d now looks like __builtins__.__dict__ but isn't
quite it d == __builtins__.__dict__ returns false.

Can anybody shed some light?

Manu


From mwilson at the-wire.com  Sun Aug  9 08:50:41 2009
From: mwilson at the-wire.com (Mel)
Date: Sun, 09 Aug 2009 08:50:41 -0400
Subject: exec("dir()",d)
References: <9adbf402-3e7e-44a4-adb3-afc36d5d88ba@33g2000vbe.googlegroups.com>
Message-ID: 

Emanuele D'Arrigo wrote:

> Greetings everybody,
> 
> I don't quite understand why if I do this:
> 
>>>> d = {}
>>>> exec("dir()", d)
> 
> 1) d is no longer empty
> 2) the content of d now looks like __builtins__.__dict__ but isn't
> quite it d == __builtins__.__dict__ returns false.
> 
> Can anybody shed some light?

You should check up on what exec does.  In this case it runs a string 
containing code using dictionary `d` as its global namespace, and so `d` has 
to contain the usual global namespace symbols -- otherwise `dict` can't 
work.  `__builtins__.__dict__ is one of the elements in the global 
namespace, not the namespace itself.  Another example:


Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) 
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a=7
>>> d={'b':a}
>>> exec ("print b", d)
7
>>> d
{'__builtins__': {'bytearray': , 'IndexError': , 'all': , 'help': Type 
help() for interactive help, or help(object) for help about object., 'vars': 
, 'SyntaxError': , 
'unicode': , 'UnicodeDecodeError': , 'isinstance': , 'copyright': Copyright (c) 2001-2009 Python Software 
Foundation.
[ ... ]
'AssertionError': , 'classmethod': , 'UnboundLocalError': , 
'NotImplementedError': , 
'AttributeError': , 'OverflowError': }, 'b': 7}
>>> 

To get rid of the name error, you'd need
d={}
d['d'] = d
exec ("dir (d)", d)


	Mel.



From lists at cheimes.de  Sun Aug  9 09:01:48 2009
From: lists at cheimes.de (Christian Heimes)
Date: Sun, 09 Aug 2009 15:01:48 +0200
Subject: exec("dir()",d)
In-Reply-To: <9adbf402-3e7e-44a4-adb3-afc36d5d88ba@33g2000vbe.googlegroups.com>
References: <9adbf402-3e7e-44a4-adb3-afc36d5d88ba@33g2000vbe.googlegroups.com>
Message-ID: 

Emanuele D'Arrigo schrieb:
> Greetings everybody,
> 
> I don't quite understand why if I do this:
> 
>>>> d = {}
>>>> exec("dir()", d)
> 
> 1) d is no longer empty
> 2) the content of d now looks like __builtins__.__dict__ but isn't
> quite it d == __builtins__.__dict__ returns false.
> 
> Can anybody shed some light?

RTFM helps ;) http://docs.python.org/reference/simple_stmts.html#exec

As a side effect, an implementation may insert additional keys into the 
dictionaries given besides those corresponding to variable names set by 
the executed code. For example, the current implementation may add a 
reference to the dictionary of the built-in module __builtin__ under the 
key __builtins__ (!).

Christian



From samwyse at gmail.com  Sun Aug  9 09:13:38 2009
From: samwyse at gmail.com (samwyse)
Date: Sun, 9 Aug 2009 06:13:38 -0700 (PDT)
Subject: setting Referer for urllib.urlretrieve
Message-ID: <1668f798-0a73-47a5-9f87-34312109c67c@v2g2000vbb.googlegroups.com>

Here's what I have so far:

import urllib

class AppURLopener(urllib.FancyURLopener):
    version = "App/1.7"
    referrer = None
    def __init__(self, *args):
        urllib.FancyURLopener.__init__(self, *args)
        if self.referrer:
            addheader('Referer', self.referrer)

urllib._urlopener = AppURLopener()

Unfortunately, the 'Referer' header potentially varies for each url
that I retrieve, and the way the module is written, I can't change the
calls to __init__ or open. The best idea I've had is to assign a new
value to my class variable just before calling urllib.urlretrieve(),
but that just seems ugly.  Any ideas?  Thanks.

PS for anyone not familiar with the RFCs:  Yes, I'm spelling
"referrer" correctly everywhere in my code.


From hendrik at microcorp.co.za  Sun Aug  9 09:14:20 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Sun, 9 Aug 2009 15:14:20 +0200
Subject: Serial port access
In-Reply-To: <1e61b3260908081820r702a4e24s6599fa724c97344a@mail.gmail.com>
References: <1e61b3260908080934g1ff65580k5836648db436b336@mail.gmail.com>
	<50697b2c0908081341o63636f36i99b5971fdb0bbb57@mail.gmail.com>
	<1e61b3260908081820r702a4e24s6599fa724c97344a@mail.gmail.com>
Message-ID: <200908091514.20684.hendrik@microcorp.co.za>

On Sunday 09 August 2009 03:20:12 nipun batra wrote:
> On Sun, Aug 9, 2009 at 2:11 AM, Chris Rebert  wrote:
> > On Sat, Aug 8, 2009 at 12:34 PM, nipun batra
> >
> > wrote:
> > > Hi,
> > > How can we access serial port using usb-serial converters,using python
> > > in linux.
> >
> > PySerial might also be an option:
> > http://pyserial.sourceforge.net/index.html
> >
> > Cheers,
> > Chris
> > --
> > http://blog.rebertia.com
>
> pySerial mentions about serial ports but not about usb-serial.Can i do
> something like convert my usb-serial to act as serial port and then use
> pySerial

You can also look in the /dev directory to see which tty is created when you
plug in the usb to serial converter, and use that /dev/ttySx as a file, 
reading and writing to it directly.

You will need this information whatever you do, as you will need to specify
which port to use, to whatever software you choose to use.

- Hendrik


From deets at nospam.web.de  Sun Aug  9 09:17:39 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sun, 09 Aug 2009 15:17:39 +0200
Subject: resume upload wsgi script
In-Reply-To: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
Message-ID: <7e80jlF2etv0kU1@mid.uni-berlin.de>

gert schrieb:
> I working on a resume upload script and encountered the following
> problems
> 
> sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
> '\ufffd\ufff
> d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
> Content-Disposition: form-data; name="Filename"

You are treating a binary data column as if it were a string. That's 
bogus, you need to use a blob column.

Also I wouldn't combine the uplodaded chunks until the full upload is 
finished - and even then only if I actually need the data.

Diez


From gert.cuykens at gmail.com  Sun Aug  9 09:31:12 2009
From: gert.cuykens at gmail.com (gert)
Date: Sun, 9 Aug 2009 06:31:12 -0700 (PDT)
Subject: resume upload wsgi script
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
Message-ID: 

On Aug 9, 3:17?pm, "Diez B. Roggisch"  wrote:
> gert schrieb:
>
> > I working on a resume upload script and encountered the following
> > problems
>
> > sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
> > '\ufffd\ufff
> > d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
> > Content-Disposition: form-data; name="Filename"
>
> You are treating a binary data column as if it were a string. That's
> bogus, you need to use a blob column.
>
> Also I wouldn't combine the uplodaded chunks until the full upload is
> finished - and even then only if I actually need the data.
>
> Diez

And the best solution would be to use TEXT instead or some sort of
SUBBIN that i do not know of in sqlite ?



From steve at REMOVE-THIS-cybersource.com.au  Sun Aug  9 10:41:05 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 09 Aug 2009 14:41:05 GMT
Subject: setting Referer for urllib.urlretrieve
References: <1668f798-0a73-47a5-9f87-34312109c67c@v2g2000vbb.googlegroups.com>
Message-ID: <028ed082$0$20617$c3e8da3@news.astraweb.com>

On Sun, 09 Aug 2009 06:13:38 -0700, samwyse wrote:

> Here's what I have so far:
> 
> import urllib
> 
> class AppURLopener(urllib.FancyURLopener):
>     version = "App/1.7"
>     referrer = None
>     def __init__(self, *args):
>         urllib.FancyURLopener.__init__(self, *args)
>         if self.referrer:
>             addheader('Referer', self.referrer)
> 
> urllib._urlopener = AppURLopener()
> 
> Unfortunately, the 'Referer' header potentially varies for each url that
> I retrieve, and the way the module is written, I can't change the calls
> to __init__ or open. The best idea I've had is to assign a new value to
> my class variable just before calling urllib.urlretrieve(), but that
> just seems ugly.  Any ideas?  Thanks.

[Aside: an int variable is an int. A str variable is a str. A list 
variable is a list. A class variable is a class. You probably mean a 
class attribute, not a variable. If other languages want to call it a 
variable, or a sausage, that's their problem.]

If you're prepared for a bit of extra work, you could take over all the 
URL handling instead of relying on automatic openers. This will give you 
much finer control, but it will also require more effort on your part. 
The basic idea is, instead of installing openers, and then ask the urllib 
module to handle the connection, you handle the connection yourself:

make a Request object using urllib2.Request
make an Opener object using urllib2.build_opener
call opener.open(request) to connect to the server
deal with the connection (retry, fail or read)

Essentially, you use the Request object instead of a URL, and you would 
add the appropriate referer header to the Request object.

Another approach, perhaps a more minimal change than the above, would be 
something like this:

# untested
class AppURLopener(urllib.FancyURLopener):
    version = "App/1.7"
    def __init__(self, *args):
        urllib.FancyURLopener.__init__(self, *args)
    def add_referrer(self, url=None):
        if url:
            addheader('Referer', url)

urllib._urlopener = AppURLopener()
urllib._urlopener.add_referrer("http://example.com/")



-- 
Steven


From deets at nospam.web.de  Sun Aug  9 10:42:11 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sun, 09 Aug 2009 16:42:11 +0200
Subject: resume upload wsgi script
In-Reply-To: 
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
	
Message-ID: <7e85i3F2fdc1eU1@mid.uni-berlin.de>

gert schrieb:
> On Aug 9, 3:17 pm, "Diez B. Roggisch"  wrote:
>> gert schrieb:
>>
>>> I working on a resume upload script and encountered the following
>>> problems
>>> sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
>>> '\ufffd\ufff
>>> d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
>>> Content-Disposition: form-data; name="Filename"
>> You are treating a binary data column as if it were a string. That's
>> bogus, you need to use a blob column.
>>
>> Also I wouldn't combine the uplodaded chunks until the full upload is
>> finished - and even then only if I actually need the data.
>>
>> Diez
> 
> And the best solution would be to use TEXT instead or some sort of
> SUBBIN that i do not know of in sqlite ?
> 

No, the best solution would be to use "BLOB", and no SUB*-stuff, but 
instead a 1:n-relation of chunks, that when the upload is finished you 
can easily combine in python to one large blob, storing that in the DB 
again.

Diez


From kushal.kumaran+python at gmail.com  Sun Aug  9 10:58:14 2009
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Sun, 9 Aug 2009 20:28:14 +0530
Subject: Need help in configuration for TimedRotatingFileHandler
In-Reply-To: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
Message-ID: <1e364c4e0908090758m5daa8ec2td7109498d96569b7@mail.gmail.com>

On Sun, Aug 9, 2009 at 5:13 PM, Lokesh wrote:
> Hi,
>
> Need help in configure the TimedRotatingFileHandler from configuration
> file
>
> I have tried with the below code and ended up with the error, code is
> pasted below
> Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
> \logs\rotate_test'

Does the directory G:\\lok_sib\\logs exist?

> 

-- 
kushal


From zuo at chopin.edu.pl  Sun Aug  9 11:15:32 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Sun, 09 Aug 2009 17:15:32 +0200
Subject: Need help in configuration for TimedRotatingFileHandler
In-Reply-To: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
Message-ID: 

09-08-2009 Lokesh  wrote:

> I have tried with the below code and ended up with the error, code is
> pasted below
> Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
> \logs\rotate_test'

Note that: '\r' is listed (interpreted by Python as 'carriage return'
special character) and not '\\r' (which would mean '\' char + 'r' char).

Regards,
*j

-- 
Jan Kaliszewski (zuo) 


From koranthala at gmail.com  Sun Aug  9 11:35:55 2009
From: koranthala at gmail.com (koranthala)
Date: Sun, 9 Aug 2009 08:35:55 -0700 (PDT)
Subject: Twisted - how to get text for HTTP error responses
Message-ID: <3ae722aa-4e65-475c-b345-73b394779db8@13g2000prl.googlegroups.com>

Hi,
   I am writing a HTTP client in Twisted. The client contacts the
server, and any errors in the sent messages will be returned back to
the client in 400 message. The reason for failure at the server is
sent as the text in the 400 message. I tried the same using the
browser, and I can see the error text (the text might be like - 'Item
X not found in DB').
   The client is supposed to use this text and calculate the next
messages to be sent to the server. But, I cannot seem to find a
mechanism to get the response text from the errback. I went through
failure.py, but I couldnt find a way to do it.
   Ex:
I send a data to the server as so
d = defer.waitForDeferred(getPage(url, method='POST', headers=hdr,
postdata=form))
yield d
try:
   reply = d.getResult()
   success(reply)
except Error, failure:
   failure(failure)

Now, inside failure method, I was unable to print the text out - say
'Item X not found in DB'.
Is it possible using Twisted? If so, how can it be done?

Thanks in Advance
K



From rt8396 at gmail.com  Sun Aug  9 12:04:48 2009
From: rt8396 at gmail.com (r)
Date: Sun, 9 Aug 2009 09:04:48 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	  
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
	
Message-ID: <7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com>

On Aug 8, 12:43?pm, "Jan Kaliszewski"  wrote:
> 08-08-2009 Steven D'Aprano  wrote:
...(snip)
> I use it very often, e.g.:
>
> ? ? ? ? ?afunction('quite long string %s quite long string '
> ? ? ? ? ? ? ? ? ? ?'quite long string quite long string %s '
> ? ? ? ? ? ? ? ? ? ?'quite %s long string quite long string'
> ? ? ? ? ? ? ? ? ? ?% (variable1, variable2, variable3))
>
> It seems nicer to me than:
>
> ? ? ? ? ?afunction(('quite long string %s quite long string '
> ? ? ? ? ? ? ? ? ? ? + 'quite long string quite long string %s '
> ? ? ? ? ? ? ? ? ? ? + 'quite %s long string quite long string')
> ? ? ? ? ? ? ? ? ? ?% (variable1, variable2, variable3))
>
> (Note that multiline-'''-strings are usless in such cases).
>

uhh? A much better way to handle such a problem is like this...

prompt1 = '''
Some people like to use %s
ways of doing things just
so they can support their %s
way of coding
'''

afunction(prompt1 %(var1, var2))

WOW!, that just somehow looks more professional to me? I hate to long
strings in the middle of a code block. Please be smart when writing
code people!!



From julien.chevalier at gmail.com  Sun Aug  9 12:22:40 2009
From: julien.chevalier at gmail.com (Kiki)
Date: Sun, 9 Aug 2009 09:22:40 -0700 (PDT)
Subject: Client/Server based on SocketServer and Windows
Message-ID: 

Hello list,

I've written a small Client/server system.
Basically, i'm expecting something like : The client sends every once
and a while a small data chunk (not more than 50 bytes) the server
receive it and print it.

Here is the server request handler :

class ThreadedTCPRequestHandlerFoo(SocketServer.BaseRequestHandler):

    def handle(self):
	    data = self.request.recv(1024)
	    cur_thread = threading.currentThread()
            response = "%s: %s from Foo" % (cur_thread.getName(),
data)
            print response

and this is the client :

def clientPrompt(ip, port, message):
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((ip, port))
	while(1):
		k=raw_input('#>')
		sock.send(k)
		print "%s\n" % k
		if k == 'quit': break
        sock.close()

My problem comes from that I can't send data from client more than
once without having the following Winsock error : 10053 Software
caused connection abort.
I have to restart the client each time I want to send a new message.

Could anyboy explain me why ?

Regards


From exarkun at twistedmatrix.com  Sun Aug  9 12:23:34 2009
From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com)
Date: Sun, 09 Aug 2009 16:23:34 -0000
Subject: Twisted - how to get text for HTTP error responses
In-Reply-To: <3ae722aa-4e65-475c-b345-73b394779db8@13g2000prl.googlegroups.com>
References: <3ae722aa-4e65-475c-b345-73b394779db8@13g2000prl.googlegroups.com>
Message-ID: <20090809162334.7171.12739707.divmod.xquotient.199@localhost.localdomain>

On 03:35 pm, koranthala at gmail.com wrote:
>Hi,
>   I am writing a HTTP client in Twisted. The client contacts the
>server, and any errors in the sent messages will be returned back to
>the client in 400 message. The reason for failure at the server is
>sent as the text in the 400 message. I tried the same using the
>browser, and I can see the error text (the text might be like - 'Item
>X not found in DB').
>   The client is supposed to use this text and calculate the next
>messages to be sent to the server. But, I cannot seem to find a
>mechanism to get the response text from the errback. I went through
>failure.py, but I couldnt find a way to do it.
>   Ex:
>I send a data to the server as so
>d = defer.waitForDeferred(getPage(url, method='POST', headers=hdr,
>postdata=form))
>yield d
>try:
>   reply = d.getResult()
>   success(reply)
>except Error, failure:
>   failure(failure)
>
>Now, inside failure method, I was unable to print the text out - say
>'Item X not found in DB'.
>Is it possible using Twisted? If so, how can it be done?

The Error instance which the local "failure" is bound to in your example 
above has a number of attributes, one of which is "status" which may be 
what you're looking for.  If not, take a look at its other attributes.

Jean-Paul


From python.list at tim.thechases.com  Sun Aug  9 12:47:26 2009
From: python.list at tim.thechases.com (Tim Chase)
Date: Sun, 09 Aug 2009 11:47:26 -0500
Subject: String algo
In-Reply-To: <1e61b3260908090403o1b6c5a66w7c59a2bd29e193a1@mail.gmail.com>
References: <1e61b3260908090403o1b6c5a66w7c59a2bd29e193a1@mail.gmail.com>
Message-ID: <4A7EFD9E.50805@tim.thechases.com>

nipun batra wrote:
> I will be receiving data serially from another pc,.i can use any sort of
> marker between two packets,i will be the person sending data as well after
> reading it from some devices.But packet length is not constant.
> each packet has this format:
> 201.535a56.65b4.56c89.565d
> another packet could be :
> 4a5b6c7d
> What i need is a program to store variables such as:var_a has value 4,var_b
> has value 5,for second string.
> I have to read and write data continuosly using serial port.

Sounds like you want to break apart your string at the 
non-numeric bits, and then create a mapping from them:

 >>> import re
 >>> s = "201.535a56.65b4.56c89.565d"
 >>> r = re.compile(r"(\d+(?:\.\d+)?)([a-z]+)", re.I)
 >>> r.findall(s)
[('201.535', 'a'), ('56.65', 'b'), ('4.56', 'c'), ('89.565', 'd')]
 >>> d = dict((k,float(v)) for v,k in r.findall(s))
 >>> print d['a']
201.535
 >>> print d['c']
4.56
 >>> print 'z' in d
False
 >>> print 'b' in d
True

Adjust the regexp accordingly if there are +/- signs, 
exponentiation, limits on the splitting-characters, etc.


-tkc









From b1540457 at tyldd.com  Sun Aug  9 13:02:03 2009
From: b1540457 at tyldd.com (Anny Mous)
Date: Mon, 10 Aug 2009 03:02:03 +1000
Subject: Bug or feature: double strings as one
References: 
	
	
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
	
	<7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com>
Message-ID: 

r wrote:

> On Aug 8, 12:43?pm, "Jan Kaliszewski"  wrote:

>> (Note that multiline-'''-strings are usless in such cases).
>>
> 
> uhh? A much better way to handle such a problem is like this...
> 
> prompt1 = '''
> Some people like to use %s
> ways of doing things just
> so they can support their %s
> way of coding
> '''

Oh wow, you so need to work on your reading comprehension skills! Didn't you
notice Jan's comment that multiline ''' strings are useless??? They add
extra newlines into the string which aren't wanted.

> WOW!, that just somehow looks more professional to me? I hate to long
> strings in the middle of a code block. Please be smart when writing
> code people!!

Because totally failing to pay attention to the requirements is "smart".





From zuo at chopin.edu.pl  Sun Aug  9 13:10:52 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Sun, 09 Aug 2009 19:10:52 +0200
Subject: Bug or feature: double strings as one
In-Reply-To: <7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com>
References: 
	
	
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
	
	<7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com>
Message-ID: 

09-08-2009 r  wrote:

> On Aug 8, 12:43?pm, "Jan Kaliszewski"  wrote:
>> 08-08-2009 Steven D'Aprano  wrote:
> ...(snip)
>> I use it very often, e.g.:
>>
>> ? ? ? ? ?afunction('quite long string %s quite long string '
>> ? ? ? ? ? ? ? ? ? ?'quite long string quite long string %s '
>> ? ? ? ? ? ? ? ? ? ?'quite %s long string quite long string'
>> ? ? ? ? ? ? ? ? ? ?% (variable1, variable2, variable3))
>>
>> It seems nicer to me than:
>>
>> ? ? ? ? ?afunction(('quite long string %s quite long string '
>> ? ? ? ? ? ? ? ? ? ? + 'quite long string quite long string %s '
>> ? ? ? ? ? ? ? ? ? ? + 'quite %s long string quite long string')
>> ? ? ? ? ? ? ? ? ? ?% (variable1, variable2, variable3))
>>
>> (Note that multiline-'''-strings are usless in such cases).
>>
>
> uhh? A much better way to handle such a problem is like this...
>
> prompt1 = '''
> Some people like to use %s
> ways of doing things just
> so they can support their %s
> way of coding
> '''

Sorry, you are wrong, '''-way would be usefull only if:

     * you want to have '\n' in each place where you wrap the
       literal in your code,

and

     * you use '''-literal at a module (non-indented) level

       or you need not only '\n'-s but also indentations
          (dependent on indentation of your code),

       or such ugly indentation is ok for you:

           some indentated code...
  ? ? ? ? ?prompt = '''quite long string %s quite long string
''' quite long string quite long string %s
''' quite %s long string quite long string
'''
           some indentated code...


That's why I wrote it's "useless in such cases."

Regards,
*j

-- 
Jan Kaliszewski (zuo) 


From no.i.dont at want.mail.from.spammers.com  Sun Aug  9 13:16:50 2009
From: no.i.dont at want.mail.from.spammers.com (Fencer)
Date: Sun, 09 Aug 2009 19:16:50 +0200
Subject: Problem with join in__str__() in class (newbie)
Message-ID: <7e8ek2F2dre5lU1@mid.individual.net>

Hello, I've written two classes. One class describes experts: experts 
has a unique ID and a name. An expert knows topics and other experts. A 
topic is described by my other class and includes a unique ID and a 
name. Now I have a problem with the __str__ method in my Expert class:

def __str__(self):
     output = '%s:%s' % (self.expert_id, self.name)
     output += '\nKnown topics: %s' % (', '.join(str(self.topics)))
#   print 'Known experts: '
#   for e in self.known_experts:
#       print '%s:%s' % (e.expert_id, e.name)
     return output

self.topics is a list of objects of type Topic.
self.known_experts is a list of objects of type Expert, specifically the 
experts known by the given expert.

When I print an object of type Expert, the output is not what I want. If 
the expert knows only one topic, say polemics, the output is:
e2:Carla
Known topics: t, 5, :, P, o, l, e, m, i, c, s
If the expert knows two topics, say Polemics and The Parthenon, then the 
  output is:
e2:Carla
Known topics: [, <, _, _, m, a, i, n, _, _, ., T, o, p, i, c,  , i, n, 
s, t, a, n, c, e,  , a, t,  , 0, x, 0, 2, 2, 2, D, 0, 8, 0, >, ]

This is not what I want. :) I want the output like this:
e2:Carla
Known topics: t5:Polemics, t6:The Parthenon

Also, notice the code I've commented out. If I can get the join above to 
work (with your help) my next question is how to present the known 
experts in a comma separated list with only expert_id and name? I can't 
use the normal __str__() method (the one I'm writing here) because it 
prints too much information. Does that mean a join is out of the question?

Thanks for any replies!

- Fencer


From jonrascal at gmail.com  Sun Aug  9 13:28:13 2009
From: jonrascal at gmail.com (jon rascal)
Date: Sun, 9 Aug 2009 10:28:13 -0700 (PDT)
Subject: Problem with join in__str__() in class (newbie)
References: <7e8ek2F2dre5lU1@mid.individual.net>
Message-ID: 


> def __str__(self):
> ? ? ?output = '%s:%s' % (self.expert_id, self.name)
> ? ? ?output += '\nKnown topics: %s' % (', '.join(str(self.topics)))

You're turning your list into a string -- try this:
', '.join([str(x) for x in self.topics])


From apt.shansen at gmail.com  Sun Aug  9 13:37:08 2009
From: apt.shansen at gmail.com (Stephen Hansen)
Date: Sun, 9 Aug 2009 10:37:08 -0700
Subject: Problem with join in__str__() in class (newbie)
In-Reply-To: <7e8ek2F2dre5lU1@mid.individual.net>
References: <7e8ek2F2dre5lU1@mid.individual.net>
Message-ID: <7a9c25c20908091037l2db51049v74b2e18efc927c25@mail.gmail.com>

   output += '\nKnown topics: %s' % (', '.join(str(self.topics)))


Your problem is here.

self.topics is a list of topic instances: but you're calling str() on the
list itself to turn the LIST itself into a string. Compare:

>>> x = [1,2,3]
>>> x
[1, 2, 3]
>>> str(x)
'[1, 2, 3]'

Now, after str(self.topics) is done, you have one big string. A string is a
sequence of characters (mostly). Calling ",".join(string) will do just what
you see there-- return a string with a comma between each character.

What you want to do, I assume, is call str() on each item in self.topics,
and join them.

That would be:

output += '\nKnown topics: %s' % ( ','.join(str(item) for item in
self.topics) )

That's a generator expression which will do what you want, I believe.
Provided your topic instances have a __str__ method that returns a string of
the form "t:".

Also, notice the code I've commented out. If I can get the join above to
> work (with your help) my next question is how to present the known experts
> in a comma separated list with only expert_id and name? I can't use the
> normal __str__() method (the one I'm writing here) because it prints too
> much information. Does that mean a join is out of the question?


Honestly, I think you are putting too much into the Expert class's __str__
method. I would make it do basically:

return "%s:%s" % (self.expert_id, self.name)

And then put the __str__ you're working on above in a different method which
does -- more. Call it 'dump' or something. That way you CAN just use the
normal str/__str__ from within this 'dump' and get what you want. str()
should return that object in its stringified form. Another method is a
better way to dump 'that object' and things 'around' it and that it 'knows'.

But if you really must have just str(expert) and have it return the big
chunk of information, your commented code looks about right. You'll have to
use your knowledge of how the internal expert class works instead of relying
on the experts just returning a str() of themselves. That's slightly bad.
But not horrible.

HTH,

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From no.i.dont at want.mail.from.spammers.com  Sun Aug  9 13:42:23 2009
From: no.i.dont at want.mail.from.spammers.com (Fencer)
Date: Sun, 09 Aug 2009 19:42:23 +0200
Subject: Problem with join in__str__() in class (newbie)
In-Reply-To: 
References: <7e8ek2F2dre5lU1@mid.individual.net>
	
Message-ID: <7e8g3vF2etertU1@mid.individual.net>

jon rascal wrote:
> 
> You're turning your list into a string -- try this:
> ', '.join([str(x) for x in self.topics])

Thanks for your quick reply, unfortunately it didn't quite work for me.
Say topics contain two topics: polemics, and the parthenon I get this 
output:
e2:Carla
Known topics: t5:Polemics

only the first topic is printed. If topics only contain a single topic I 
get this error:
Traceback (most recent call last):
   File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 
57, in 
     print experts[1]
   File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 
21, in __str__
     output += '\nKnown topics: %s' % (', '.join([str(x) for x in 
self.topics]))
TypeError: iteration over non-sequence

What did I do wrong?

- Fencer


From gert.cuykens at gmail.com  Sun Aug  9 13:51:25 2009
From: gert.cuykens at gmail.com (gert)
Date: Sun, 9 Aug 2009 10:51:25 -0700 (PDT)
Subject: resume upload wsgi script
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
	
	<7e85i3F2fdc1eU1@mid.uni-berlin.de>
Message-ID: <9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com>

On Aug 9, 4:42?pm, "Diez B. Roggisch"  wrote:
> gert schrieb:
>
>
>
> > On Aug 9, 3:17 pm, "Diez B. Roggisch"  wrote:
> >> gert schrieb:
>
> >>> I working on a resume upload script and encountered the following
> >>> problems
> >>> sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
> >>> '\ufffd\ufff
> >>> d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
> >>> Content-Disposition: form-data; name="Filename"
> >> You are treating a binary data column as if it were a string. That's
> >> bogus, you need to use a blob column.
>
> >> Also I wouldn't combine the uplodaded chunks until the full upload is
> >> finished - and even then only if I actually need the data.
>
> >> Diez
>
> > And the best solution would be to use TEXT instead or some sort of
> > SUBBIN that i do not know of in sqlite ?
>
> No, the best solution would be to use "BLOB", and no SUB*-stuff, but
> instead a 1:n-relation of chunks, that when the upload is finished you
> can easily combine in python to one large blob, storing that in the DB
> again.
>
> Diez

so one table of chunks

CREATE TABLE temp (
    file_id  VARCHAR(64),
    chunK_id  INTEGER,
    chunk BLOB,
    PRIMARY KEY(file_id,chunk_id)
);

SELECT chunk FROM temp WHERE file_id = 'file'
concatenating result in python
update blob
delete temp

How do I concatenate results that do not fit into memory ?


From apt.shansen at gmail.com  Sun Aug  9 14:06:44 2009
From: apt.shansen at gmail.com (Stephen Hansen)
Date: Sun, 9 Aug 2009 11:06:44 -0700
Subject: Problem with join in__str__() in class (newbie)
In-Reply-To: <7e8g3vF2etertU1@mid.individual.net>
References: <7e8ek2F2dre5lU1@mid.individual.net>
	
	<7e8g3vF2etertU1@mid.individual.net>
Message-ID: <7a9c25c20908091106u7a5464dey625220f211e69d58@mail.gmail.com>

>
> only the first topic is printed. If topics only contain a single topic I
> get this error:
> Traceback (most recent call last):
>  File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 57,
> in 
>    print experts[1]
>  File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 21,
> in __str__
>    output += '\nKnown topics: %s' % (', '.join([str(x) for x in
> self.topics]))
> TypeError: iteration over non-sequence
>
> What did I do wrong?
>

It looks like, "if topics contains only a single topic", means:

    self.topics = MyTopic

was done at some point. What you should do is make self.topics ALWAYS be a
list: even if it's only a list of one item.

So you do

    self.topics.append(MyTopic)

when you add that one topic. That way self.topics is always a list.
Sometimes empty, sometimes containing one element, sometimes containing
many.

--S
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From python at mrabarnett.plus.com  Sun Aug  9 14:10:08 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Sun, 09 Aug 2009 19:10:08 +0100
Subject: Problem with join in__str__() in class (newbie)
In-Reply-To: <7e8g3vF2etertU1@mid.individual.net>
References: <7e8ek2F2dre5lU1@mid.individual.net>	
	<7e8g3vF2etertU1@mid.individual.net>
Message-ID: <4A7F1100.5040203@mrabarnett.plus.com>

Fencer wrote:
> jon rascal wrote:
>>
>> You're turning your list into a string -- try this:
>> ', '.join([str(x) for x in self.topics])
> 
> Thanks for your quick reply, unfortunately it didn't quite work for me.
> Say topics contain two topics: polemics, and the parthenon I get this 
> output:
> e2:Carla
> Known topics: t5:Polemics
> 
> only the first topic is printed. If topics only contain a single topic I 
> get this error:
> Traceback (most recent call last):
>   File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 
> 57, in 
>     print experts[1]
>   File "C:\Users\fencer\workspace\Find Expert\src\find_expert.py", line 
> 21, in __str__
>     output += '\nKnown topics: %s' % (', '.join([str(x) for x in 
> self.topics]))
> TypeError: iteration over non-sequence
> 
> What did I do wrong?
> 
Try printing self.topics. It should always be a list of topics.


From deets at nospam.web.de  Sun Aug  9 14:25:47 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sun, 09 Aug 2009 20:25:47 +0200
Subject: resume upload wsgi script
In-Reply-To: <9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com>
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
	
	<7e85i3F2fdc1eU1@mid.uni-berlin.de>
	<9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com>
Message-ID: <7e8ildF2f1hcpU1@mid.uni-berlin.de>

gert schrieb:
> On Aug 9, 4:42 pm, "Diez B. Roggisch"  wrote:
>> gert schrieb:
>>
>>
>>
>>> On Aug 9, 3:17 pm, "Diez B. Roggisch"  wrote:
>>>> gert schrieb:
>>>>> I working on a resume upload script and encountered the following
>>>>> problems
>>>>> sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
>>>>> '\ufffd\ufff
>>>>> d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
>>>>> Content-Disposition: form-data; name="Filename"
>>>> You are treating a binary data column as if it were a string. That's
>>>> bogus, you need to use a blob column.
>>>> Also I wouldn't combine the uplodaded chunks until the full upload is
>>>> finished - and even then only if I actually need the data.
>>>> Diez
>>> And the best solution would be to use TEXT instead or some sort of
>>> SUBBIN that i do not know of in sqlite ?
>> No, the best solution would be to use "BLOB", and no SUB*-stuff, but
>> instead a 1:n-relation of chunks, that when the upload is finished you
>> can easily combine in python to one large blob, storing that in the DB
>> again.
>>
>> Diez
> 
> so one table of chunks
> 
> CREATE TABLE temp (
>     file_id  VARCHAR(64),
>     chunK_id  INTEGER,
>     chunk BLOB,
>     PRIMARY KEY(file_id,chunk_id)
> );
> 
> SELECT chunk FROM temp WHERE file_id = 'file'
> concatenating result in python
> update blob
> delete temp
> 
> How do I concatenate results that do not fit into memory ?

By writing them into one file? If files were to large for your memory, 
all the substring-stuff wouldn't help either - the sqlite works in the 
same memory as your program...

But how many gigabytes of uploads do you expect?

Diez


From no.i.dont at want.mail.from.spammers.com  Sun Aug  9 14:56:26 2009
From: no.i.dont at want.mail.from.spammers.com (Fencer)
Date: Sun, 09 Aug 2009 20:56:26 +0200
Subject: Problem with join in__str__() in class (newbie)
In-Reply-To: 
References: <7e8ek2F2dre5lU1@mid.individual.net>		<7e8g3vF2etertU1@mid.individual.net>
	
Message-ID: <7e8keqF2eib0lU1@mid.individual.net>

MRAB wrote:
> Try printing self.topics. It should always be a list of topics.

Ah, yes, that made me find a bug when I was creating the Expert objects: 
the lists of known topics were not created properly. I should have 
posted more code I suppose! Thanks for the help, this problem has now 
been solved. I guess I can't use a join to print the known experts as I 
described in my first post.

- Fencer


From Nikolaus at rath.org  Sun Aug  9 15:02:57 2009
From: Nikolaus at rath.org (Nikolaus Rath)
Date: Sun, 09 Aug 2009 15:02:57 -0400
Subject: Monkeypatching an object to become callable
Message-ID: <87hbwgu7xa.fsf@vostro.rath.org>

Hi,

I want to monkeypatch an object so that it becomes callable, although
originally it is not meant to be. (Yes, I think I do have a good reason
to do so).

But simply adding a __call__ attribute to the object apparently isn't
enough, and I do not want to touch the class object (since it would
modify all the instances):

>>> class foo(object):
...   pass
... 
>>> t = foo()
>>> def test():
...   print 'bar'
... 
>>> t()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'foo' object is not callable
>>> t.__call__ = test
>>> t()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'foo' object is not callable
>>> t.__call__()
bar


Is there an additional trick to get it to work?


Best,

   -Nikolaus

-- 
 ?Time flies like an arrow, fruit flies like a Banana.?

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C


From darkwater42 at gmail.com  Sun Aug  9 15:26:54 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Sun, 9 Aug 2009 12:26:54 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
Message-ID: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>

A friend of mine is just learning Python, and he's a bit tweaked about
how unrecognized escape sequences are treated in Python. This is from
the Python 3.0 reference manual:

     Unlike Standard C, all unrecognized escape sequences are left in
the string unchanged, i.e.,
     the backslash is left in the string. (This behavior is useful
when debugging: if an escape
     sequence is mistyped, the resulting output is more easily
recognized as broken.) It is also
     important to note that the escape sequences only recognized in
string literals fall into the
     category of unrecognized escapes for bytes literals.

My friend begs to differ with the above. It would be much better for
debugging if Python generated a parsing error for unrecognized escape
sequences, rather than leaving them unchanged. g++ outputs a warning
for such escape sequences, for instance. This is what I would consider
to be the correct behavior. (Actually, I think it should just generate
a fatal parsing error, but a warning is okay too.)

In any case, I think my friend should mellow out a bit, but we both
consider this something of a wart. He's just more wart-phobic than I
am. Is there any way that this behavior can be considered anything
other than a wart? Other than the unconvincing claim that you can use
this "feature" to save you a bit of typing sometimes when you actually
want a backslash to be in your string?

|>ouglas


From piet at cs.uu.nl  Sun Aug  9 16:15:22 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Sun, 09 Aug 2009 22:15:22 +0200
Subject: Problem with join in__str__() in class (newbie)
References: <7e8ek2F2dre5lU1@mid.individual.net>
	
	<7e8g3vF2etertU1@mid.individual.net>
	
	<7e8keqF2eib0lU1@mid.individual.net>
Message-ID: 

>>>>> Fencer  (F) wrote:

>F> Also, notice the code I've commented out. If I can get the join above to
>F> work (with your help) my next question is how to present the known experts
>F> in a comma separated list with only expert_id and name? I can't use the
>F> normal __str__() method (the one I'm writing here) because it prints too
>F> much information. Does that mean a join is out of the question?

>F> MRAB wrote:
>>> Try printing self.topics. It should always be a list of topics.

>F> Ah, yes, that made me find a bug when I was creating the Expert objects:
>F> the lists of known topics were not created properly. I should have posted
>F> more code I suppose! Thanks for the help, this problem has now been solved.
>F> I guess I can't use a join to print the known experts as I described in my
>F> first post.

Yes, you can. But you need an additional method that gives only the id
and name. Like this:

------------------------------------------------------------------------
class Expert:
    '''An expert'''
    def __init__(self, id, name, topics):
        self.expert_id = id
        self.name = name
        self.topics = topics
        self.known_experts = []
        
    def add_expert(self, expert):
        self.known_experts.append(expert)

    def __str__(self):
        output = (self.brief_str() +
                  '\nKnown topics: %s' % (', '.join(map(str, self.topics))) +
                  ('\nKnown experts: %s' %
                   (', '.join(exp.brief_str() for exp in self.known_experts))))
        return output

    def brief_str(self):
        '''Gives a brief description of the expert: just the id and name.'''
        return '%s:%s' % (self.expert_id, self.name)
    
class Topic:
    '''A topic'''
    def __init__(self, id, name):
        self.topic_id = id
        self.name = name

    def __str__(self):
        return '%s:%s' % (self.topic_id, self.name)

topic1 = Topic('t1', 'Relativity')
topic2 = Topic('t2', 'Math')
topic5 = Topic('t5', 'Polemics')
topic6 = Topic('t6', 'The Parthenon')

expert1 = Expert('e1', 'Albert', [topic1])
expert2 = Expert('e2', 'Leonhard', [topic2])

expert1.add_expert(expert2)

expert5 = Expert('e5', 'Carla', [topic5, topic6])
expert5.add_expert(expert1)
expert5.add_expert(expert2)

for ex in expert1, expert2, expert5:
    print ex
------------------------------------------------------------------------

(I prefer to use map instead of a list/iterator comprehension in this
particular case. With the known_experts that isn't possible, unless
brief_str is made into a static method)
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From victorsubervi at gmail.com  Sun Aug  9 16:21:43 2009
From: victorsubervi at gmail.com (Victor Subervi)
Date: Sun, 9 Aug 2009 15:21:43 -0500
Subject: Surpressing Warnings
Message-ID: <4dc0cfea0908091321y54156d30sc0c4dc3a564eecab@mail.gmail.com>

Hi:
I get a ton of warnings like this from a program I run:

Warning (from warnings module):
  File "C:\Python25\read.py", line 67
    cursor.execute(sqlKWDrop)
Warning: Unknown table 'judaism_128'

How do I surpress them?
TIA,
Victor
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From missive at hotmail.com  Sun Aug  9 16:26:31 2009
From: missive at hotmail.com (Lee Harr)
Date: Mon, 10 Aug 2009 00:56:31 +0430
Subject: [ANNC] pybotwar-0.5
Message-ID: 


pybotwar is a fun and educational game where players
create computer programs to control simulated robots
to compete in a battle arena.

http://pybotwar.googlecode.com/


pybotwar uses pybox2d for the physical simulation,
and uses pygame and pygsear for the visualization.

pybotwar is released under GPLv3.


Changes in pybotwar-0.5:
    - added tournament mode
    - added explosive shells
    - robots are now damaged by colliding with walls or other robots
    - added damage sensor
    - added gyro sensor
    - added configurable cannon reload time
    - added robot statistics database
    - added time limit for robot startup/ initialization
    - health bar changes color below 30% health
    - fixed force/ torque possibly going over 100%
    - fixed problem with non-integer force/ torque values
    - each robot gets its own log file in test mode
    - send robot errors to log file
    - use optparse for cmd line options


_________________________________________________________________
More than messages?check out the rest of the Windows Live?.
http://www.microsoft.com/windows/windowslive/


From deets at nospam.web.de  Sun Aug  9 16:28:29 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sun, 09 Aug 2009 22:28:29 +0200
Subject: Monkeypatching an object to become callable
In-Reply-To: <87hbwgu7xa.fsf@vostro.rath.org>
References: <87hbwgu7xa.fsf@vostro.rath.org>
Message-ID: <7e8preF2d6adsU1@mid.uni-berlin.de>

Nikolaus Rath schrieb:
> Hi,
> 
> I want to monkeypatch an object so that it becomes callable, although
> originally it is not meant to be. (Yes, I think I do have a good reason
> to do so).
> 
> But simply adding a __call__ attribute to the object apparently isn't
> enough, and I do not want to touch the class object (since it would
> modify all the instances):
> 
>>>> class foo(object):
> ...   pass
> ... 
>>>> t = foo()
>>>> def test():
> ...   print 'bar'
> ... 
>>>> t()
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'foo' object is not callable
>>>> t.__call__ = test
>>>> t()
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: 'foo' object is not callable
>>>> t.__call__()
> bar
> 
> 
> Is there an additional trick to get it to work?

AFAIK special methods are always only evaluated on the class. But this 
works:

class Foo(object):

     pass

f = Foo()

def make_callable(f):
     class Callable(f.__class__):

         def __call__(self):
             print "foobar"

     f.__class__ = Callable

make_callable(f)
f()

Diez


From rt8396 at gmail.com  Sun Aug  9 16:34:12 2009
From: rt8396 at gmail.com (r)
Date: Sun, 9 Aug 2009 13:34:12 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	  
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
	 
	<7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com> 
	
Message-ID: <21131b4b-67d3-4ddf-b061-60327d670ca7@l31g2000vbp.googlegroups.com>

On Aug 9, 12:10?pm, "Jan Kaliszewski"  wrote:
..(snip)
> Sorry, you are wrong, '''-way would be usefull only if:
>
> ? ? ?* you want to have '\n' in each place where you wrap the
> ? ? ? ?literal in your code,
>
> and
>
> ? ? ?* you use '''-literal at a module (non-indented) level
>
> ? ? ? ?or you need not only '\n'-s but also indentations
> ? ? ? ? ? (dependent on indentation of your code),
>
> ? ? ? ?or such ugly indentation is ok for you:
>
> ? ? ? ? ? ?some indentated code...
> ? ? ? ? ? ?prompt = '''quite long string %s quite long string
> ''' quite long string quite long string %s
> ''' quite %s long string quite long string
> '''
> ? ? ? ? ? ?some indentated code...
>
> That's why I wrote it's "useless in such cases."

@ Jan & Anny

No, of course putting a multi-line string inside a block does not
solve anything. What i meant for you to do is to declare the string
outside the block or as a module level Constant. i typically declare
all multi-line strings (ig for dialog prompts etc..) right after my
globals at the top of my modules or within an imported module like...

from thisModuleConstants import *




From sajmikins at gmail.com  Sun Aug  9 17:02:51 2009
From: sajmikins at gmail.com (Simon Forman)
Date: Sun, 9 Aug 2009 14:02:51 -0700 (PDT)
Subject: unique-ifying a list
References: 
Message-ID: 

On Aug 7, 4:53?pm, kj  wrote:
> Suppose that x is some list. ?To produce a version of the list with
> duplicate elements removed one could, I suppose, do this:
>
> ? ? x = list(set(x))
>
> but I expect that this will not preserve the original order of
> elements.
>
> I suppose that I could write something like
>
> def uniquify(items):
> ? ? seen = set()
> ? ? ret = []
> ? ? for i in items:
> ? ? ? ? if not i in seen:
> ? ? ? ? ? ? ret.append(i)
> ? ? ? ? ? ? seen.add(i)
> ? ? return ret
>
> But this seems to me like such a commonly needed operation that I
> find it hard to believe one would need to resort to such self-rolled
> solutions. ?Isn't there some more standard (and hopefully more
> efficient, as in "C-coded"/built-in) approach?
>
> TIA!
>
> kynn


Unique items in a list, in the same order as in the list:

x = sorted(set(x), key=x.index)

;]


From davea at ieee.org  Sun Aug  9 17:15:47 2009
From: davea at ieee.org (Dave Angel)
Date: Sun, 09 Aug 2009 17:15:47 -0400
Subject: Need help in configuration for TimedRotatingFileHandler
In-Reply-To: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
Message-ID: <4A7F3C83.1040607@ieee.org>

Lokesh wrote:
> Hi,
>
> Need help in configure the TimedRotatingFileHandler from configuration
> file
>
> I have tried with the below code and ended up with the error, code is
> pasted below
> Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
> \logs\rotate_test'
> [loggers]
> keys=root,simpleExample
>
> [handlers]
> keys=consoleHandler,timedRotatingFileHandler
>
> [formatters]
> keys=simpleFormatter
>
> [logger_root]
> level=DEBUG
> handlers=consoleHandler
>
> [logger_simpleExample]
> level=DEBUG
> handlers=timedRotatingFileHandler
> qualname=simpleExample
> propagate=0
>
> [handler_consoleHandler]
> class=StreamHandler
> level=DEBUG
> formatter=simpleFormatter
> args=(sys.stdout,)
>
> [handler_timedRotatingFileHandler]
> class=handlers.TimedRotatingFileHandler
> level=DEBUG
> formatter=simpleFormatter
> args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)
>
> [formatter_simpleFormatter]
> format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
> datefmt='%Y-%m-%d %H:%M:%S'
>
>
> Thanks or your time
> Regards,
> Lokesh
>
>   
I don't see code there, I see lots of config data, presumably in an .ini 
file.   So I don't know how you're reading it in, and converting it to 
Python variables, but I know where I'd look, based on your error message.

The following line:

args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)

seems to contain a Python string.  But there are unescaped backslashes 
within it.  You can get away with it in two cases, because \l  isn't a 
valid escape sequence.  But in the case of \r, it looks like a newline 
character.

Anyway, all three of those backslashes probably need to be doubled.

args=("G:\\lok_sib\\logs\\rotate_test", 'midnight', 1)

Two other cures that may work, depending on context:   change the backslashes to forward slashes, or use a raw string.

But as I said earlier, you don't show in any way what code is interpreting this line, so it's all just guesswork.

DaveA



From rt8396 at gmail.com  Sun Aug  9 17:43:14 2009
From: rt8396 at gmail.com (r)
Date: Sun, 9 Aug 2009 14:43:14 -0700 (PDT)
Subject: Bug or feature: double strings as one
References: 
	  
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
	 
	<7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com> 
	
	<21131b4b-67d3-4ddf-b061-60327d670ca7@l31g2000vbp.googlegroups.com>
Message-ID: <6cdaacf6-a560-483e-a14d-26396173e3bd@o35g2000vbi.googlegroups.com>


#-- el bueno --#
"hello i am a very long string that\
does not like newlines so please \
escape me, Thank you!"

#-- el malo --#
"hello i am a very long string that"+
"does not like newlines but i have no"+
"idea what to do with myself"

#-- el feo --#
"hello i am a very long string that"
"does not like newlines but i have no"
"idea what to do with myself"


just ideas people!


From mail at johannes-janssen.de  Sun Aug  9 18:06:44 2009
From: mail at johannes-janssen.de (Johannes Janssen)
Date: Mon, 10 Aug 2009 00:06:44 +0200
Subject: How to find out in which module an instance of a class is created?
Message-ID: <4A7F4874.8030008@johannes-janssen.de>

Hi
I like to know in which module an instance of a class was initialized. 
Using __module__ or __name__ within a class only gives me the module in 
which the class was defined not the instance of the class. Is there some 
(simple) way to do this?
For better understanding I'll give an example how I want to use this. 
Okay let's say I've got a module *foo,* in which class A is defined as 
the following:

 > class A(object):
 >     def __init__(self, mod):
 >         self.mod = mod

In a module called *bar* I do the following:

 > import foo
 > a = A(__name__)

Then a.mod should be "bar". But I don't like to pass the value of a.mod 
manually rather than having it default to the module the instance a of A 
was created in (here "bar").
Unfortunately something like this ...

 > class A(object):
 >     def __init__(self, mod=__name__):
 >         self.mod = mod

... won't work. In this case mod would always be "foo".

Kind regards
johannes


From gert.cuykens at gmail.com  Sun Aug  9 18:22:17 2009
From: gert.cuykens at gmail.com (gert)
Date: Sun, 9 Aug 2009 15:22:17 -0700 (PDT)
Subject: resume upload wsgi script
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
	
	<7e85i3F2fdc1eU1@mid.uni-berlin.de>
	<9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com>
	<7e8ildF2f1hcpU1@mid.uni-berlin.de>
Message-ID: <49e41062-9e0d-4c5e-beca-edb02d3ce6e8@e34g2000vbm.googlegroups.com>

On Aug 9, 8:25?pm, "Diez B. Roggisch"  wrote:
> gert schrieb:
>
>
>
> > On Aug 9, 4:42 pm, "Diez B. Roggisch"  wrote:
> >> gert schrieb:
>
> >>> On Aug 9, 3:17 pm, "Diez B. Roggisch"  wrote:
> >>>> gert schrieb:
> >>>>> I working on a resume upload script and encountered the following
> >>>>> problems
> >>>>> sql: Could not decode to UTF-8 column 'SUBSTR(picture,?)' with text
> >>>>> '\ufffd\ufff
> >>>>> d\ufffd\ufffd?!Exif------------Ef1gL6KM7Ij5ae0gL6KM7cH2cH2GI3
> >>>>> Content-Disposition: form-data; name="Filename"
> >>>> You are treating a binary data column as if it were a string. That's
> >>>> bogus, you need to use a blob column.
> >>>> Also I wouldn't combine the uplodaded chunks until the full upload is
> >>>> finished - and even then only if I actually need the data.
> >>>> Diez
> >>> And the best solution would be to use TEXT instead or some sort of
> >>> SUBBIN that i do not know of in sqlite ?
> >> No, the best solution would be to use "BLOB", and no SUB*-stuff, but
> >> instead a 1:n-relation of chunks, that when the upload is finished you
> >> can easily combine in python to one large blob, storing that in the DB
> >> again.
>
> >> Diez
>
> > so one table of chunks
>
> > CREATE TABLE temp (
> > ? ? file_id ?VARCHAR(64),
> > ? ? chunK_id ?INTEGER,
> > ? ? chunk BLOB,
> > ? ? PRIMARY KEY(file_id,chunk_id)
> > );
>
> > SELECT chunk FROM temp WHERE file_id = 'file'
> > concatenating result in python
> > update blob
> > delete temp
>
> > How do I concatenate results that do not fit into memory ?
>
> By writing them into one file? If files were to large for your memory,
> all the substring-stuff wouldn't help either - the sqlite works in the
> same memory as your program...
>
> But how many gigabytes of uploads do you expect?
>

250KB :)
Its just HTTP1.1 has everything for making ftp like file transfers
possible.
When I write it to a file then I am back at square one because I still
need to load it completely to get it into a blob.
So there is no way to concatenate BLOB's without loading it completely
into memory ?


From pavlovevidence at gmail.com  Sun Aug  9 18:24:53 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sun, 9 Aug 2009 15:24:53 -0700 (PDT)
Subject: Monkeypatching an object to become callable
References: <87hbwgu7xa.fsf@vostro.rath.org>
Message-ID: 

On Aug 9, 12:02?pm, Nikolaus Rath  wrote:
> Hi,
>
> I want to monkeypatch an object so that it becomes callable, although
> originally it is not meant to be. (Yes, I think I do have a good reason
> to do so).
>
> But simply adding a __call__ attribute to the object apparently isn't
> enough, and I do not want to touch the class object (since it would
> modify all the instances):


Override the class's __call__, and program it to call a certain method
(say _instancecall) on the object.  Catch AttributeError and raise
TypeError so that it matches the behavior when no __call__ is defined.


def __call__(self,*args,**kwargs):
    try:
        func = self._instancecall
    except AttributeError:
        raise TypeError("'%s' object not callable" % self.__class__)
    return func(*args,**kwargs)


Note: don't call _instancecall inside the try clause; you don't want
to catch attribute errors raised inside the _instancecall method.

Then set _instancecall on any objects you want to be callable.


Carl Banks


From clp2 at rebertia.com  Sun Aug  9 18:47:58 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Sun, 9 Aug 2009 18:47:58 -0400
Subject: Surpressing Warnings
In-Reply-To: <4dc0cfea0908091321y54156d30sc0c4dc3a564eecab@mail.gmail.com>
References: <4dc0cfea0908091321y54156d30sc0c4dc3a564eecab@mail.gmail.com>
Message-ID: <50697b2c0908091547q6f63b0d1v2b70ffa0a9352b24@mail.gmail.com>

On Sun, Aug 9, 2009 at 4:21 PM, Victor Subervi wrote:
> Hi:
> I get a ton of warnings like this from a program I run:
>
> Warning (from warnings module):
> ? File "C:\Python25\read.py", line 67
> ??? cursor.execute(sqlKWDrop)
> Warning: Unknown table 'judaism_128'
>
> How do I surpress them?

import warnings
with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    cursor.execute(sqlKWDrop)
#repeat for every call that's causing warnings

or to just silence all warnings from anywhere:

import warnings
warnings.simplefilter("ignore")

Cheers,
Chris
-- 
http://blog.rebertia.com


From zuo at chopin.edu.pl  Sun Aug  9 19:26:00 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Mon, 10 Aug 2009 01:26:00 +0200
Subject: Bug or feature: double strings as one
In-Reply-To: <6cdaacf6-a560-483e-a14d-26396173e3bd@o35g2000vbi.googlegroups.com>
References: 
	
	
	<000674d6$0$2895$c3e8da3@news.astraweb.com>
	
	<7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com>
	
	<21131b4b-67d3-4ddf-b061-60327d670ca7@l31g2000vbp.googlegroups.com>
	<6cdaacf6-a560-483e-a14d-26396173e3bd@o35g2000vbi.googlegroups.com>
Message-ID: 

09-08-2009 o 23:43:14 r  wrote:

> #-- el bueno --#
> "hello i am a very long string that\
> does not like newlines so please \
> escape me, Thank you!"

You probably ment: """hello i am... [etc.]

Anyway... You're right that generally it's good idea to define
dialog prompts and such stuff separately rather that to hardcode
it, especially in big projects. Then certainly multiline
string literals are useful (though, if you need to get rid of
newlines, IMHO "el feo" method is more elegant and less error
prone than your "el bueno" [possible invisible space after '\']).

But there are plenty of other situations when it's better
(in practice) to have strings (even long) together with your
code, e.g. log information for debugging, or

Cheers,

*j


From lists at cheimes.de  Sun Aug  9 19:47:34 2009
From: lists at cheimes.de (Christian Heimes)
Date: Mon, 10 Aug 2009 01:47:34 +0200
Subject: How to find out in which module an instance of a class is created?
In-Reply-To: <4A7F4874.8030008@johannes-janssen.de>
References: <4A7F4874.8030008@johannes-janssen.de>
Message-ID: <4A7F6016.2060408@cheimes.de>

Johannes Janssen wrote:
>  > class A(object):
>  >     def __init__(self, mod=__name__):
>  >         self.mod = mod
> 
> .... won't work. In this case mod would always be "foo".

You have to inspect the stack in order to get the module of the caller. 
The implementation of warnings.warn() gives you some examples how to get 
the module name.

Christian


From nagle at animats.com  Sun Aug  9 19:51:41 2009
From: nagle at animats.com (John Nagle)
Date: Sun, 09 Aug 2009 16:51:41 -0700
Subject: Does python have the capability for driver development ? Maybe
	with ShedSkin
In-Reply-To: 
References: 
Message-ID: <4a7f6018$0$1642$742ec2ed@news.sonic.net>

MalC0de wrote:
> hello there, I've a question :
> I want to know does python have any capability for using Ring0 and
> kernel functions for driver and device development stuff .
> if there's such a feature it is very good, and if there something for
> this kind that you know please refer me to some reference and show me
> some snippet .
> 
> thanks
> 
> - Malc0de

     With the CPython interpretive system, it's not likely to work. But
using ShedSkin, which generates hard machine code, it might be possible.
The main problem is that Shed Skin uses a garbage-collected environment,
which few kernels have.

     Under QNX, which is a a real message-passing operating system with
all drivers in user space, it should be possible to write a driver in
Python.  There's Python for QNX.  It would probably be too slow to
be useful, though.

     I've actually written a handler for Baudot Teletype machines in
Python.  See

     https://sourceforge.net/projects/baudotrss/

Those machines are so slow (45.45 baud) that Python isn't the bottleneck.

					John Nagle


From python at mrabarnett.plus.com  Sun Aug  9 19:51:48 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Mon, 10 Aug 2009 00:51:48 +0100
Subject: Bug or feature: double strings as one
In-Reply-To: 
References: 			<000674d6$0$2895$c3e8da3@news.astraweb.com>		<7c15f7b0-49f2-4210-bc7a-e82941e9ddd9@g6g2000vbr.googlegroups.com>		<21131b4b-67d3-4ddf-b061-60327d670ca7@l31g2000vbp.googlegroups.com>	<6cdaacf6-a560-483e-a14d-26396173e3bd@o35g2000vbi.googlegroups.com>
	
Message-ID: <4A7F6114.9020402@mrabarnett.plus.com>

Jan Kaliszewski wrote:
> 09-08-2009 o 23:43:14 r  wrote:
> 
>> #-- el bueno --#
>> "hello i am a very long string that\
>> does not like newlines so please \
>> escape me, Thank you!"
> 
> You probably ment: """hello i am... [etc.]
> 
> Anyway... You're right that generally it's good idea to define
> dialog prompts and such stuff separately rather that to hardcode
> it, especially in big projects. Then certainly multiline
> string literals are useful (though, if you need to get rid of
> newlines, IMHO "el feo" method is more elegant and less error
> prone than your "el bueno" [possible invisible space after '\']).
> 
> But there are plenty of other situations when it's better
> (in practice) to have strings (even long) together with your
> code, e.g. log information for debugging, or
> 
Here's an idea that you're probably going to hate: indented strings. :-)

A string prefixed with 'i' would be an 'indented' string. Leading space
and tab characters at the start of the string (just after the quote) or
the start of each line within a multiline string would be ignored.

 >>> """Line 1
        Line 2
"""
'Line 1\n       Line 2\n'
 >>> i"""Line 1
        Line 2
"""
'Line 1\nLine 2\n'

An additional feature could be to make '\ ' == ' ', perhaps only for
indented strings if you're worried that it could breaking existing code:

 >>> i"""Line 1
\       Line 2
"""
'Line 1\n       Line 2\n'

This would save you having to write '\x20'.


From steve at REMOVE-THIS-cybersource.com.au  Sun Aug  9 20:06:18 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 00:06:18 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
Message-ID: <0008e7c1$0$2880$c3e8da3@news.astraweb.com>

On Sun, 09 Aug 2009 12:26:54 -0700, Douglas Alan wrote:

> A friend of mine is just learning Python, and he's a bit tweaked about
> how unrecognized escape sequences are treated in Python.
...
> In any case, I think my friend should mellow out a bit, but we both
> consider this something of a wart. He's just more wart-phobic than I am.
> Is there any way that this behavior can be considered anything other
> than a wart? Other than the unconvincing claim that you can use this
> "feature" to save you a bit of typing sometimes when you actually want a
> backslash to be in your string?

I'd put it this way: a backslash is just an ordinary character, except 
when it needs to be special. So Python's behaviour is "treat backslash as 
a normal character, except for these exceptions" while the behaviour your 
friend wants is "treat a backslash as an error, except for these 
exceptions".

Why should a backslash in a string literal be an error?



-- 
Steven


From bouncyinc at gmail.com  Sun Aug  9 20:42:26 2009
From: bouncyinc at gmail.com (John Haggerty)
Date: Sun, 9 Aug 2009 18:42:26 -0600
Subject: getting a "simple" program to work
Message-ID: 

ok so I know this is one of those "weird" requests but here me out.
So far I have an issue with a package for python called "libgmail" which is
basically a gmail interface for python to send messages remoetly.

Works ok except that the 'sendMessage' routine is bad.

This is included in the above attachment

it's used in a program called "ogss" which is an sms interface to gmail to
basically read gmail and then have a command done on a remote machine and
then spat out on the local machine to a log file that's opened and then
emailed back

problem is that the sending back routine fails.

Now I've found a program that will more or less do what is requied but it's
not really exactly what would be used in that it doesn't use the libgmail
routine.

So far the maintainer of both packages seem to be afk or not having their
routines fixed and so far debian/Unbuntu claim that the last version of the
package has been fixed :(

Is there a recommendatin of how to combine/alter so that ogss can transmit?
My main issue is that python is lesser known to me than Chinese (which I
also don't know).

My idea of this is to have a remote email timeclock program which could then
be scripted with any language or just "echo >>blah" if necessary.

Thanks in advance :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: libgmail.py
Type: text/x-python
Size: 54655 bytes
Desc: not available
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: ogss.py
Type: text/x-python
Size: 6241 bytes
Desc: not available
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: send2.py
Type: text/x-python
Size: 2088 bytes
Desc: not available
URL: 

From bbxx789_05ss at yahoo.com  Sun Aug  9 20:55:26 2009
From: bbxx789_05ss at yahoo.com (7stud)
Date: Sun, 9 Aug 2009 17:55:26 -0700 (PDT)
Subject: Monkeypatching an object to become callable
References: <87hbwgu7xa.fsf@vostro.rath.org>
Message-ID: <0aa46ece-64b9-4c28-b690-5ac5937ce3f2@f20g2000prn.googlegroups.com>

On Aug 9, 1:02?pm, Nikolaus Rath  wrote:
> Hi,
>
> I want to monkeypatch an object so that it becomes callable, although
> originally it is not meant to be. (Yes, I think I do have a good reason
> to do so).
>
> But simply adding a __call__ attribute to the object apparently isn't
> enough, and I do not want to touch the class object (since it would
> modify all the instances):
>
> >>> class foo(object):
>
> ... ? pass
> ...>>> t = foo()
> >>> def test():
>
> ... ? print 'bar'
> ...>>> t()
>
> Traceback (most recent call last):
> ? File "", line 1, in 
> TypeError: 'foo' object is not callable>>> t.__call__ = test
> >>> t()
>
> Traceback (most recent call last):
> ? File "", line 1, in 
> TypeError: 'foo' object is not callable>>> t.__call__()
>
> bar
>
> Is there an additional trick to get it to work?
>
> Best,
>
> ? ?-Nikolaus
>
> --
> ??Time flies like an arrow, fruit flies like a Banana.?
>
> ? PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6 ?02CF A9AD B7F8 AE4E 425C


With an old-style class your code will work:

class A:
    pass

def test():
    print "test"

a = A()
a.__call__ = test

a()

--output:--
test


a2 = A()
a2()

--output:--

    a2()
AttributeError: A instance has no __call__ method



Another option is to use the *decorator pattern*.  The decorator
pattern can be used when you want to add additional methods and
attributes to an object, and you don't want to disturb the original
class:

class A(object):
    def __init__(self, x):
        self.x = x

    def sayhi(self):
        print "hi"


class Wrapper(object):
    def __init__(self, obj, func):
        self.obj = obj
        self.func = func

    def __call__(self, *args):
        return self.func(*args)

    def __getattr__(self, name):
        return object.__getattribute__(self.obj, name)


def test():
    print "test"

a = A(10)
w = Wrapper(a, test)
w()
print w.x
w.sayhi()

--output:--
test
10
hi



From darkwater42 at gmail.com  Sun Aug  9 20:56:55 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Sun, 9 Aug 2009 17:56:55 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
Message-ID: 

Steven D'Aprano wrote:

> Why should a backslash in a string literal be an error?

Because in Python, if my friend sees the string "foo\xbar\n", he has
no idea whether the "\x" is an escape sequence, or if it is just the
characters "\x", unless he looks it up in the manual, or tries it out
in the REPL, or what have you. My friend is adamant that it would be
better if he could just look at the string literal and know. He
doesn't want to be bothered to have to store stuff like that in his
head. He wants to be able to figure out programs just by looking at
them, to the maximum degree that that is feasible.

In comparison to Python, in C++, he can just look "foo\xbar\n" and
know that "\x" is a special character. (As long as it compiles without
warnings under g++.)

He's particularly annoyed too, that if he types "foo\xbar" at the
REPL, it echoes back as "foo\\xbar". He finds that to be some sort of
annoying DWIM feature, and if Python is going to have DWIM features,
then it should, for example, figure out what he means by "\" and not
bother him with a syntax error in that case.

Another reason that Python should not behave the way that it does, is
that it pegs Python into a corner where it can't add new escape
sequences in the future, as doing so will break existing code.
Generating a syntax error instead for unknown escape sequences would
allow for future extensions.

Now not to pick on Python unfairly, most other languages have similar
issues with escape sequences. (Except for the Bourne Shell and bash,
where "\x" always just means "x", no matter what character "x" happens
to be.) But I've been telling my friend for years to switch to Python
because of how wonderful and consistent Python is in comparison to
most other languages, and now he seems disappointed and seems to think
that Python is just more of the same.

Of course I think that he's overreacting a bit. My point of view is
that every language has *some* warts; Python just has a bit fewer than
most. It would have been nice, I should think, if this wart had been
"fixed" in Python 3, as I do consider it to be a minor wart.

|>ouglas



From pavlovevidence at gmail.com  Sun Aug  9 21:34:14 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Sun, 9 Aug 2009 18:34:14 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
Message-ID: 

On Aug 9, 5:06?pm, Steven D'Aprano  wrote:
> On Sun, 09 Aug 2009 12:26:54 -0700, Douglas Alan wrote:
> > A friend of mine is just learning Python, and he's a bit tweaked about
> > how unrecognized escape sequences are treated in Python.
> ...
> > In any case, I think my friend should mellow out a bit, but we both
> > consider this something of a wart. He's just more wart-phobic than I am.
> > Is there any way that this behavior can be considered anything other
> > than a wart? Other than the unconvincing claim that you can use this
> > "feature" to save you a bit of typing sometimes when you actually want a
> > backslash to be in your string?
>
> I'd put it this way: a backslash is just an ordinary character, except
> when it needs to be special. So Python's behaviour is "treat backslash as
> a normal character, except for these exceptions" while the behaviour your
> friend wants is "treat a backslash as an error, except for these
> exceptions".
>
> Why should a backslash in a string literal be an error?

Because the behavior of \ in a string is context-dependent, which
means a reader can't know if \ is a literal character or escape
character without knowing the context, and it means an innocuous
change in context can cause a rather significant change in \.

IOW it's an error-prone mess.  It would be better if Python (like C)
treated \ consistently as an escape character.  (And in raw strings,
consistently as a literal.)

It's kind of a minor issue in terms of overall real-world importance,
but in terms of raw unPythonicness this might be the worst offense the
language makes.


Carl Banks


From darkwater42 at gmail.com  Sun Aug  9 22:42:56 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Sun, 9 Aug 2009 19:42:56 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
Message-ID: <1cf80e77-416b-43be-8491-0b7b7494aa92@s6g2000vbp.googlegroups.com>

On Aug 9, 8:06?pm, Steven D'Aprano wrote:

> while the behaviour your
> friend wants is "treat a backslash as an error, except for these
> exceptions".

Besides, can't all error situations be described as, "treat the error
situation as an error, except for the exception of when the situation
isn't an error"???

The behavior my friend wants isn't any more exceptional than that!

|>ouglas


From mensanator at aol.com  Sun Aug  9 22:46:52 2009
From: mensanator at aol.com (Mensanator)
Date: Sun, 9 Aug 2009 19:46:52 -0700 (PDT)
Subject: pybotwar-0.5
References: 
Message-ID: <3e9c5fcd-4047-4edd-b2ec-d892c77e3a69@f33g2000vbm.googlegroups.com>

On Aug 9, 3:26?pm, Lee Harr  wrote:
> pybotwar is a fun and educational game where players
> create computer programs to control simulated robots
> to compete in a battle arena.
>
> http://pybotwar.googlecode.com/

Why is the doc folder empty?

Shouldn't you supply some hint on how the games works
and at least a rudimentary guide to robot design?

What version to you expect that will be in? 1.0? 10.0?

Could you inform us when you have something worth looking
at and not before so we don't have to waste our time?


>
> pybotwar uses pybox2d for the physical simulation,
> and uses pygame and pygsear for the visualization.
>
> pybotwar is released under GPLv3.
>
> Changes in pybotwar-0.5:
> ? ? - added tournament mode
> ? ? - added explosive shells
> ? ? - robots are now damaged by colliding with walls or other robots
> ? ? - added damage sensor
> ? ? - added gyro sensor
> ? ? - added configurable cannon reload time
> ? ? - added robot statistics database
> ? ? - added time limit for robot startup/ initialization
> ? ? - health bar changes color below 30% health
> ? ? - fixed force/ torque possibly going over 100%
> ? ? - fixed problem with non-integer force/ torque values
> ? ? - each robot gets its own log file in test mode
> ? ? - send robot errors to log file
> ? ? - use optparse for cmd line options
>
> _________________________________________________________________
> More than messages?check out the rest of the Windows Live?.http://www.microsoft.com/windows/windowslive/



From xahlee at gmail.com  Sun Aug  9 23:04:43 2009
From: xahlee at gmail.com (Xah Lee)
Date: Sun, 9 Aug 2009 20:04:43 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
Message-ID: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>

The prob with python docs is with the python priests.

there are frequent posts about python doc's poor quality, and some
efforts to improve the doc (such as wiki or seggestions), about few
times a year (in so much as i've seen), the typical response is
pissing fight, with python priests to tell them not to start another
wiki, or ?you should apply in our church first and formulate a PEP
proposal first or kindly donate or otherwise fuckoff?, and so on.

i've wrote several articles about this issue, total time spend on this
is probably more than 2 months full-time work. See:

? Python Documentation Problems
  http://xahlee.org/perl-python/python_doc_index.html

just about each article above generates a thread of flames.

I also have re-wrote the entire python regex doc in 2005:

? Pyhton Regex Documentation: String Pattern Matching
  http://xahlee.org/perl-python/python_re-write/lib/module-re.html

there are some positive reviews, but most are drawn out by nay-sayers.

I often receive thank you emails for 2 particular articles, which are
most frequently google searched as indicated by my weblog:

? Python Doc Problem Example: gzip
  http://xahlee.org/perl-python/python_doc_gzip.html

? Python Doc Problem Example: sort()
  http://xahlee.org/perl-python/python_doc_sort.html

? Sorting in Python and Perl
  http://xahlee.org/perl-python/sort_list.html

See also:

? Language, Purity, Cult, and Deception
  http://xahlee.org/UnixResource_dir/writ/lang_purity_cult_deception.html

  Xah
? http://xahlee.org/

?

On Jul 31, 1:10 pm, kj  wrote:
> I'm pretty new to Python, and I like a lot overall, but I find the
> documentation for Python rather poor, overall.
>
> I'm sure that Python experts don't have this problem: they have
> internalized some good ways to access the documentation, are
> productive with it, and therefore have lost the ability to see why
> the Python documentations is deficient for beginners.  This explains
> why a suboptimal situation can persist like this: those who are
> most able fix it are also the least able to perceive it.
>
> I've heard similar complaints from other experienced programmers
> who are trying out Python for the first time: poor documentation.
>
> Here is an *entirely typical* example: on some Unix, try
>
> % pydoc urllib
>
> The displayed documentation mention the optional parameter "data"
> in practically every function listed (a few dozen of them).  This
> parameter is not documented *anywhere* on that page.  All that we
> are told is that its default value is always None.
>
> I'm sure that I can find a full description of this parameter if
> I fire up Google, and search online.  In fact, more likely than
> not, I'll find far more documentation than I want.  But my point
> is that a programmer should not need to do this.  The full
> documentation should be readily accessible directly through a few
> keystrokes.
>
> I would love to know how experienced Python programmers quickly
> zero in on the Python documentation they need.
>
> TIA!
>
> kynn



From spamgrinder.trylater at ggmail.com  Sun Aug  9 23:43:41 2009
From: spamgrinder.trylater at ggmail.com (AlF)
Date: Sun, 09 Aug 2009 20:43:41 -0700
Subject: reloading the module imported as 'from ... import ...'
Message-ID: <4A7F976D.7090600@ggmail.com>

Hi,

what is the best way to reload the module imported using 'from ... 
import ...'

Is following a way to do so?


 >>> from email.charset import Charset
 >>> reload(email.charset)
Traceback (most recent call last):
   File "", line 1, in 
NameError: name 'email' is not defined
 >>>
 >>>
 >>> import email.charset
 >>> reload(email.charset)

References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
Message-ID: <1bcfbcd867677baf95b4ab8d685dbe44@preisshare.net>


Since you're talking about documentation, which is a part of python,
don't you think you should be discussing it on python-dev ?

That's where discussions about the documentation should be held.

haha - I'm just curious to see how long it will for them to
shut the discussion down. 

Before you do that, you should clearly work out in your own mind
how you think things need to improve. It's not good enough just
saying this or that is bad without having specific ideas on what
needs to change.

Good luck fellow sinner and blasphemer...

How dare you suggest that things could be improved...


On Sun, 9 Aug 2009 20:04:43 -0700 (PDT), Xah Lee  wrote:
> The prob with python docs is with the python priests.
> 
> there are frequent posts about python doc's poor quality, and some
> efforts to improve the doc (such as wiki or seggestions), about few
> times a year (in so much as i've seen), the typical response is
> pissing fight, with python priests to tell them not to start another
> wiki, or ?you should apply in our church first and formulate a PEP
> proposal first or kindly donate or otherwise fuckoff?, and so on.
> 
> i've wrote several articles about this issue, total time spend on this
> is probably more than 2 months full-time work. See:
> 
> ? Python Documentation Problems
>   http://xahlee.org/perl-python/python_doc_index.html
> 
> just about each article above generates a thread of flames.
> 
> I also have re-wrote the entire python regex doc in 2005:
> 
> ? Pyhton Regex Documentation: String Pattern Matching
>   http://xahlee.org/perl-python/python_re-write/lib/module-re.html
> 
> there are some positive reviews, but most are drawn out by nay-sayers.
> 
> I often receive thank you emails for 2 particular articles, which are
> most frequently google searched as indicated by my weblog:
> 
> ? Python Doc Problem Example: gzip
>   http://xahlee.org/perl-python/python_doc_gzip.html
> 
> ? Python Doc Problem Example: sort()
>   http://xahlee.org/perl-python/python_doc_sort.html
> 
> ? Sorting in Python and Perl
>   http://xahlee.org/perl-python/sort_list.html
> 
> See also:
> 
> ? Language, Purity, Cult, and Deception
>   http://xahlee.org/UnixResource_dir/writ/lang_purity_cult_deception.html
> 
>   Xah
> ? http://xahlee.org/
> 
> ?
> 
> On Jul 31, 1:10 pm, kj  wrote:
>> I'm pretty new to Python, and I like a lot overall, but I find the
>> documentation for Python rather poor, overall.
>>
>> I'm sure that Python experts don't have this problem: they have
>> internalized some good ways to access the documentation, are
>> productive with it, and therefore have lost the ability to see why
>> the Python documentations is deficient for beginners.  This explains
>> why a suboptimal situation can persist like this: those who are
>> most able fix it are also the least able to perceive it.
>>
>> I've heard similar complaints from other experienced programmers
>> who are trying out Python for the first time: poor documentation.
>>
>> Here is an *entirely typical* example: on some Unix, try
>>
>> % pydoc urllib
>>
>> The displayed documentation mention the optional parameter "data"
>> in practically every function listed (a few dozen of them).  This
>> parameter is not documented *anywhere* on that page.  All that we
>> are told is that its default value is always None.
>>
>> I'm sure that I can find a full description of this parameter if
>> I fire up Google, and search online.  In fact, more likely than
>> not, I'll find far more documentation than I want.  But my point
>> is that a programmer should not need to do this.  The full
>> documentation should be readily accessible directly through a few
>> keystrokes.
>>
>> I would love to know how experienced Python programmers quickly
>> zero in on the Python documentation they need.
>>
>> TIA!
>>
>> kynn


From lokeshmaremalla at gmail.com  Mon Aug 10 01:07:37 2009
From: lokeshmaremalla at gmail.com (Lokesh Maremalla)
Date: Mon, 10 Aug 2009 10:37:37 +0530
Subject: Need help in configuration for TimedRotatingFileHandler
In-Reply-To: <4A7F3C83.1040607@ieee.org>
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
	<4A7F3C83.1040607@ieee.org>
Message-ID: 

Hi Dave,

I have modified the code as mentioned in reply and is working fine. But
still i am facing an issue and the issue is described below.

In configuration file i have coded the TimedRotatingFileHandler like
args=("G:\\lok_sib\\logs\\rotate_test", 'D', 1)

step1: Executed the code and got the log file with the information
step2: Modified the system time from current day to next day
step3: End up with the error and the error is pasted below

Traceback (most recent call last):
  File "c:\Python25\lib\logging\handlers.py", line 74, in emit
    self.doRollover()
  File "c:\Python25\lib\logging\handlers.py", line 274, in doRollover
    os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is
being used by another process

Python version - 2.5.4

Thanks for your time.

Regards,
Lokesh


On Mon, Aug 10, 2009 at 2:45 AM, Dave Angel  wrote:

> Lokesh wrote:
>
>> Hi,
>>
>> Need help in configure the TimedRotatingFileHandler from configuration
>> file
>>
>> I have tried with the below code and ended up with the error, code is
>> pasted below
>> Error - IOError: [Errno 2] No such file or directory: 'G:\\lok_sib\
>> \logs\rotate_test'
>> [loggers]
>> keys=root,simpleExample
>>
>> [handlers]
>> keys=consoleHandler,timedRotatingFileHandler
>>
>> [formatters]
>> keys=simpleFormatter
>>
>> [logger_root]
>> level=DEBUG
>> handlers=consoleHandler
>>
>> [logger_simpleExample]
>> level=DEBUG
>> handlers=timedRotatingFileHandler
>> qualname=simpleExample
>> propagate=0
>>
>> [handler_consoleHandler]
>> class=StreamHandler
>> level=DEBUG
>> formatter=simpleFormatter
>> args=(sys.stdout,)
>>
>> [handler_timedRotatingFileHandler]
>> class=handlers.TimedRotatingFileHandler
>> level=DEBUG
>> formatter=simpleFormatter
>> args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)
>>
>> [formatter_simpleFormatter]
>> format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
>> datefmt='%Y-%m-%d %H:%M:%S'
>>
>>
>> Thanks or your time
>> Regards,
>> Lokesh
>>
>>
>>
> I don't see code there, I see lots of config data, presumably in an .ini
> file.   So I don't know how you're reading it in, and converting it to
> Python variables, but I know where I'd look, based on your error message.
>
> The following line:
>
> args=("G:\lok_sib\logs\rotate_test", 'midnight', 1)
>
> seems to contain a Python string.  But there are unescaped backslashes
> within it.  You can get away with it in two cases, because \l  isn't a valid
> escape sequence.  But in the case of \r, it looks like a newline character.
>
> Anyway, all three of those backslashes probably need to be doubled.
>
> args=("G:\\lok_sib\\logs\\rotate_test", 'midnight', 1)
>
> Two other cures that may work, depending on context:   change the
> backslashes to forward slashes, or use a raw string.
>
> But as I said earlier, you don't show in any way what code is interpreting
> this line, so it's all just guesswork.
>
> DaveA
>
>


-- 
Thanks & Regards,
Lokesh.
lokeshmaremalla at gmail.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From lokeshmaremalla at gmail.com  Mon Aug 10 01:21:09 2009
From: lokeshmaremalla at gmail.com (Lokesh Maremalla)
Date: Mon, 10 Aug 2009 10:51:09 +0530
Subject: Need help in configuration for TimedRotatingFileHandler
In-Reply-To: 
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
	<4A7F3C83.1040607@ieee.org>
	
Message-ID: 

Hi Dave,

I forgot to provide the information about the code how I am using logger
Here is the complete scenario

I have modified the code as mentioned in reply and is working fine. But
still I am facing an issue and the issue is described below.

In configuration file i have coded the TimedRotatingFileHandler like
args=("G:\\lok_sib\\logs\\rotate_test", 'D', 1)

Code:
mlogger = logging.getLogger("simpleExample")
def a_view(request):
    mlogger.debug("a_view called")
    if request.method== "POST" :
        mlogger.debug("post function")
    else:
        mlogger.debug("serve function")

Execution:
step1: Executed the code and got the log file with the information
step2: Modified the system time from current day to next day
step3: End up with the error and the error is pasted below

Traceback (most recent call last):
  File "c:\Python25\lib\logging\handlers.py", line 74, in emit
    self.doRollover()
  File "c:\Python25\lib\logging\handlers.py", line 274, in doRollover
    os.rename(self.baseFilename, dfn)
WindowsError: [Error 32] The process cannot access the file because it is
being used by another process

Python version - 2.5.4

I guess my output should be like this for the next day
-a new log file rotate_test. should generate in the respective
location

Please correct me if I am wrong.


Thanks for your time.

Regards,
Lokesh
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From timr at probo.com  Mon Aug 10 01:31:27 2009
From: timr at probo.com (Tim Roberts)
Date: Sun, 09 Aug 2009 22:31:27 -0700
Subject: Using Python to automate builds
References: <84d9ae10-3aee-40a8-97ac-05799da0de64@f18g2000prf.googlegroups.com>
Message-ID: 

Kosta  wrote:
>
>
>What I would like to do, is to open a cmd window, and start a Python
>script.  This script would then (based upon input arguments), build
>different flavors of the driver (fre, chk, x86, x64) and do some post
>processing (create cat files, sign, etc.).
>
>I was hoping to take advantage as much as possible of exisiting
>infrastructure from the WDK.  I am able to call setenv.bat and provide
>all the input parameters.  One of the things setenv.bat does is change
>the path environment variable.  However, this is not captured by
>Python.  I could duplicate the functionality, but I'd rather not.  Is
>there a way to capture all enviroment variable changes being made by a
>batch file from Python?

My suggestion is that you just call "setenv" again every time you start a
new process.  My "build everything" batch file has a series of sections
something like this:

  setlocal
  set LAST=%CD%
  call %DDK%\bin\setenv %DDK% chk WXP no_oacr
  @echo on
  set USERNAME=timr
  cd %LAST%
  build %BLD%
  endlocal

  setlocal
  set LAST=%CD%
  call %DDK%\bin\setenv %DDK% fre WXP no_oacr
  @echo on
  set USERNAME=timr
  cd %LAST%
  build %BLD%
  endlocal

  setlocal
  set LAST=%CD%
  call %DDK%\bin\setenv %DDK% chk WLH x64 no_oacr
  @echo on
  set USERNAME=timr
  cd %LAST%
  build %BLD%
  endlocal
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 01:32:36 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 05:32:36 GMT
Subject: reloading the module imported as 'from ... import ...'
References: <4A7F976D.7090600@ggmail.com>
Message-ID: 

On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:

> Hi,
> 
> what is the best way to reload the module imported using 'from ...
> import ...'


Have you tried "from ... import ..." again?



-- 
Steven


From timr at probo.com  Mon Aug 10 01:34:41 2009
From: timr at probo.com (Tim Roberts)
Date: Sun, 09 Aug 2009 22:34:41 -0700
Subject: Pywin32 @ windows 7
References: 
Message-ID: 

"Algirdas Brazas"  wrote:
>
>Did anyone manage to get windows extensions installet on windows 7 64 bit? As 
>far as I try I get only "Setup program invalid or damaged".

I've been running 32-bit Python 2.5 and the 32-bit versions of PyWin32 and
wxPython on Windows 7 64-bit for many months.  No problems.

I have not tried the 64-bit Python and PyWin32 builds yet.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.


From timr at probo.com  Mon Aug 10 01:42:45 2009
From: timr at probo.com (Tim Roberts)
Date: Sun, 09 Aug 2009 22:42:45 -0700
Subject: Windows 7 : any problems installing or running Python ?
References: 
Message-ID: 

Dave WB3DWE wrote:
>
>Anybody tried it ? 
>Is anything broken, ie is the whole shootin' match good to go ?
>I'm esp interested in WConio for 3.0/3.1 which I use heavily.

I've been running the 32-bit builds of Python 2.5, PyWin32, and wxPython on
Windows 7 64-bit for many months.  No problems at all.

I hated Vista; I would only run it if my clients insisted on having their
drivers tested on it.  Vista SP1 was somewhat better, but I don't mind
Windows 7 at all.  I might even upgrade my primary development machine from
XP.  A number of the usually cranky driver developers have expressed the
same opinion.  Microsoft might actually have a winner here.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.


From spamgrinder.trylater at ggmail.com  Mon Aug 10 01:48:31 2009
From: spamgrinder.trylater at ggmail.com (AlF)
Date: Sun, 09 Aug 2009 22:48:31 -0700
Subject: reloading the module imported as 'from ... import ...'
In-Reply-To: 
References: <4A7F976D.7090600@ggmail.com>
	
Message-ID: <4A7FB4AF.7060107@ggmail.com>

Steven D'Aprano wrote:
> On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:
> 
>> Hi,
>>
>> what is the best way to reload the module imported using 'from ...
>> import ...'
> 
> 
> Have you tried "from ... import ..." again?
> 

I have not because of an assumption that "import" imports the module 
just once. In fact this still works that way:

here is a terminal 1:

$ cat > a.py
a=1
$ cat > a.py
a=2
$


and terminal 2:

 >>> from a import a
 >>> a
1
 >>> a
1
 >>> from a import a
 >>> a
1
 >>>

In spite of changing a.py in fly, the imported a is still 1




From julien.chevalier at gmail.com  Mon Aug 10 01:58:31 2009
From: julien.chevalier at gmail.com (Kiki)
Date: Sun, 9 Aug 2009 22:58:31 -0700 (PDT)
Subject: Client/Server based on SocketServer and Windows
References: 
	
Message-ID: <979ad93c-0257-4add-8fb7-b56e253e3fb7@h30g2000vbr.googlegroups.com>

Thank you Dennis

I'm using 2 differents editor, which may be the cause of such a mess
in the indentation.

I must admitt that I lazily rely on those (not so bad indeed) editors.

"If indentation whas bad they would have tell me"

Too bad am i

Won't post misindeted code anymore.


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 02:03:05 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 06:03:05 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
Message-ID: 

On Sun, 09 Aug 2009 17:56:55 -0700, Douglas Alan wrote:

> Steven D'Aprano wrote:
> 
>> Why should a backslash in a string literal be an error?
> 
> Because in Python, if my friend sees the string "foo\xbar\n", he has no
> idea whether the "\x" is an escape sequence, or if it is just the
> characters "\x", unless he looks it up in the manual, or tries it out in
> the REPL, or what have you. 

Fair enough, but isn't that just another way of saying that if you look 
at a piece of code and don't know what it does, you don't know what it 
does unless you look it up or try it out?


> My friend is adamant that it would be better
> if he could just look at the string literal and know. He doesn't want to
> be bothered to have to store stuff like that in his head. He wants to be
> able to figure out programs just by looking at them, to the maximum
> degree that that is feasible.

I actually sympathize strongly with that attitude. But, honestly, your 
friend is a programmer (or at least pretends to be one *wink*). You can't 
be a programmer without memorizing stuff: syntax, function calls, modules 
to import, quoting rules, blah blah blah. Take C as an example -- there's 
absolutely nothing about () that says "group expressions or call a 
function" and {} that says "group a code block". You just have to 
memorize it. If you don't know what a backslash escape is going to do, 
why would you use it? I'm sure your friend isn't in the habit of randomly 
adding backslashes to strings just to see whether it will still compile.

This is especially important when reading (as opposed to writing) code. 
You read somebody else's code, and see "foo\xbar\n". Let's say you know 
it compiles without warning. Big deal -- you don't know what the escape 
codes do unless you've memorized them. What does \n resolve to? chr(13) 
or chr(97) or chr(0)? Who knows? 

Unless you know the rules, you have no idea what is in the string. 
Allowing \y to resolve to a literal backslash followed by y doesn't 
change that. All it means is that some \c combinations return a single 
character, and some return two.



> In comparison to Python, in C++, he can just look "foo\xbar\n" and know
> that "\x" is a special character. (As long as it compiles without
> warnings under g++.)

So what you mean is, he can just look at "foo\xbar\n" AND COMPILE IT 
USING g++, and know whether or not \x is a special character.

[sarcasm] Gosh. That's an enormous difference from Python, where you have 
to print the string at the REPL to know what it does. [/sarcasm]

Aside:
\x isn't a special character:

>>> "\x"
ValueError: invalid \x escape

However, \xba is:

>>> "\xba"
'\xba'
>>> len("\xba")
1
>>> ord("\xba")
186



> He's particularly annoyed too, that if he types "foo\xbar" at the REPL,
> it echoes back as "foo\\xbar". He finds that to be some sort of annoying
> DWIM feature, and if Python is going to have DWIM features, then it
> should, for example, figure out what he means by "\" and not bother him
> with a syntax error in that case.

Now your friend is confused. This is a good thing. Any backslash you see 
in Python's default string output is *always* an escape:

>>> "a string with a 'proper' escape \t (tab)"
"a string with a 'proper' escape \t (tab)"
>>> "a string with an 'improper' escape \y (backslash-y)"
"a string with an 'improper' escape \\y (backslash-y)"

The REPL is actually doing him a favour. It always escapes backslashes, 
so there is no ambiguity. A backslash is displayed as \\, any other \c is 
a special character.


> Of course I think that he's overreacting a bit. 

:)


> My point of view is that
> every language has *some* warts; Python just has a bit fewer than most.
> It would have been nice, I should think, if this wart had been "fixed"
> in Python 3, as I do consider it to be a minor wart.

And if anyone had cared enough to raise it a couple of years back, it 
possibly might have been.


-- 
Steven


From nagle at animats.com  Mon Aug 10 02:03:14 2009
From: nagle at animats.com (John Nagle)
Date: Sun, 09 Aug 2009 23:03:14 -0700
Subject: Unrecognized escape sequences in string literals
In-Reply-To: 
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
Message-ID: <4a7fb72d$0$1589$742ec2ed@news.sonic.net>

Carl Banks wrote:
> IOW it's an error-prone mess.  It would be better if Python (like C)
> treated \ consistently as an escape character.  (And in raw strings,
> consistently as a literal.)

    Agreed.  For one thing, if another escape character ever has to be
added to the language, that may change the semantics of previously
correct strings.  If "\" followed by a non-special character is treated
as an error, that doesn't happen.

					John Nagle


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 02:10:53 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 06:10:53 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
Message-ID: 

On Sun, 09 Aug 2009 18:34:14 -0700, Carl Banks wrote:

>> Why should a backslash in a string literal be an error?
> 
> Because the behavior of \ in a string is context-dependent, which means
> a reader can't know if \ is a literal character or escape character
> without knowing the context, and it means an innocuous change in context
> can cause a rather significant change in \.

*Any* change in context is significant with escapes.

"this \nhas two lines"

If you change the \n to a \t you get a significant difference. If you 
change the \n to a \y you get a significant difference. Why is the first 
one acceptable but the second not?


> IOW it's an error-prone mess.

I've never had any errors caused by this. I've never seen anyone write to 
this newsgroup confused over escape behaviour, or asking for help with an 
error caused by it, and until this thread, never seen anyone complain 
about it either.

Excuse my cynicism, but I believe that you are using "error-prone" to 
mean "I don't like this behaviour" rather than "it causes lots of errors".



-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 02:21:36 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 06:21:36 GMT
Subject: reloading the module imported as 'from ... import ...'
References: <4A7F976D.7090600@ggmail.com>
	
	<4A7FB4AF.7060107@ggmail.com>
Message-ID: 

On Sun, 09 Aug 2009 22:48:31 -0700, AlF wrote:

> Steven D'Aprano wrote:
>> On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:
>> 
>>> Hi,
>>>
>>> what is the best way to reload the module imported using 'from ...
>>> import ...'
>> 
>> 
>> Have you tried "from ... import ..." again?
>> 
>> 
> I have not because of an assumption that "import" imports the module
> just once. 

Ah, of course the cached module will still reflect the older version. 
Sorry, I was thinking about solving a different problem:

- In module "main" call "from A import a"
- Some other part of your code modifies A.a
- You want to have the imported a be refreshed with the value of A.a


No, my suggestion won't help in this situation.

Instead, you can:

(1) Delete the module from sys.modules, forcing Python to re-read it from 
disk:

import sys
del sys.modules['A']
from A import a

or

(2) Recognize that Python doesn't specifically support what you're trying 
to do. reload() is a convenience function, and you probably should stick 
to the "import A; A.a" form.


-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 02:23:20 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 06:23:20 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	<4a7fb72d$0$1589$742ec2ed@news.sonic.net>
Message-ID: 

On Sun, 09 Aug 2009 23:03:14 -0700, John Nagle wrote:

> if another escape character ever has to be
> added to the language, that may change the semantics of previously
> correct strings.

And that's the only argument in favour of prohibiting non-special 
backslash sequences I've seen yet that is even close to convincing.


-- 
Steven


From darkwater42 at gmail.com  Mon Aug 10 03:32:30 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Mon, 10 Aug 2009 00:32:30 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
Message-ID: <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>

On Aug 10, 2:03 am, Steven D'Aprano
 wrote:

> On Sun, 09 Aug 2009 17:56:55 -0700, Douglas Alan wrote:

> > Because in Python, if my friend sees the string "foo\xbar\n", he has no
> > idea whether the "\x" is an escape sequence, or if it is just the
> > characters "\x", unless he looks it up in the manual, or tries it out in
> > the REPL, or what have you.
>
> Fair enough, but isn't that just another way of saying that if you look
> at a piece of code and don't know what it does, you don't know what it
> does unless you look it up or try it out?

Not really. It's more like saying that easy things should be easy, and
hard things should possible. But in this case, Python is making
something that should be really easy, a bit harder and more error
prone than it should be.

In C++, if I know that the code I'm looking at compiles, then I never
need worry that I've misinterpreted what a string literal means. At
least not if it doesn't have any escape characters in it that I'm not
familiar with. But in Python, if I see, "\f\o\o\b\a\z", I'm not really
sure what I'm seeing, as I surely don't have committed to memory some
of the more obscure escape sequences. If I saw this in C++, and I knew
that it was in code that compiled, then I'd at least know that there
are some strange escape codes that I have to look up. Unlike with
Python, it would never be the case in C++ code that the programmer who
wrote the code was just too lazy to type in "\\f\\o\\o\\b\\a\\z"
instead.

> > My friend is adamant that it would be better
> > if he could just look at the string literal and know. He doesn't want to
> > be bothered to have to store stuff like that in his head. He wants to be
> > able to figure out programs just by looking at them, to the maximum
> > degree that that is feasible.
>
> I actually sympathize strongly with that attitude. But, honestly, your
> friend is a programmer (or at least pretends to be one *wink*).

Actually, he's probably written more code than you, me, and ten other
random decent programmers put together. As he can slap out massive
amounts of code very quickly, he'd prefer not to have crap getting in
his way. In the time it takes him to look something up, he might have
written another page of code.

He's perfectly capable of dealing with crap, as years of writing large
programs in Perl and PHP quickly proves, but his whole reason for
learning Python, I take it, is so that he will be bothered with less
crap and therefore write code even faster.

> You can't be a programmer without memorizing stuff: syntax, function
> calls, modules to import, quoting rules, blah blah blah. Take C as
> an example -- there's absolutely nothing about () that says "group
> expressions or call a function" and {} that says "group a code
> block".

I don't really think that this is a good analogy. It's like the
difference between remembering rules of grammar and remembering
English spelling. As a kid, I was the best in my school at grammar,
and one of the worst at speling.

> You just have to memorize it. If you don't know what a backslash
> escape is going to do, why would you use it?

(1) You're looking at code that someone else wrote, or (2) you forget
to type "\\" instead of "\" in your code (or get lazy sometimes), as
that is okay most of the time, and you inadvertently get a subtle bug.

> This is especially important when reading (as opposed to writing) code.
> You read somebody else's code, and see "foo\xbar\n". Let's say you know
> it compiles without warning. Big deal -- you don't know what the escape
> codes do unless you've memorized them. What does \n resolve to? chr(13)
> or chr(97) or chr(0)? Who knows?

It *is* a big deal. Or at least a non-trivial deal. It means that you
can tell just by looking at the code that there are funny characters
in the string, and not just a backslashes. You don't have to go
running for the manual every time you see code with backslashes, where
the upshot might be that the programmer was merely saving themselves
some typing.

> > In comparison to Python, in C++, he can just look "foo\xbar\n" and know
> > that "\x" is a special character. (As long as it compiles without
> > warnings under g++.)
>
> So what you mean is, he can just look at "foo\xbar\n" AND COMPILE IT
> USING g++, and know whether or not \x is a special character.

I'm not sure that your comments are paying due diligence to full
life-cycle software development issues that involve multiple
programmers (or even just your own program that you wrote a year ago,
and you don't remember all the details of what you did) combined with
maintaining and modifying existing code, etc.

> Aside:
> \x isn't a special character:
>
> >>> "\x"
>
> ValueError: invalid \x escape

I think that this all just goes to prove my friend's point! Here I've
been programming in Python for more than a decade (not full time, mind
you, as I also program in other languages, like C++), and even I
didn't know that "\xba" was an escape sequence, and I inadvertently
introduced a subtle bug into my argument because it just so happens
that the first two characters of "bar" are legal hexadecimal! If I did
the very same thing in a real program, it might take me a lot of time
to track down the bug.

Also, it seems that Python is being inconsistent here. Python knows
that
the string "\x" doesn't contain a full escape sequence, so why doesn't
it
treat the string "\x" the same way that it treats the string "\z"?
After all, if you're a Python programmer, you should know that "\x"
doesn't contain a complete escape sequence, and therefore, you would
not be surprised if Python were so kind as to just leave it alone,
rather than raising a ValueError.

I.e., "\z" is not a legal escape sequence, so it gets left as
"\\z". "\x" is not a legal escape sequence. Shouldn't it also get left
as "\\x"?

> > He's particularly annoyed too, that if he types "foo\xbar" at the REPL,
> > it echoes back as "foo\\xbar". He finds that to be some sort of annoying
> > DWIM feature, and if Python is going to have DWIM features, then it
> > should, for example, figure out what he means by "\" and not bother him
> > with a syntax error in that case.
>
> Now your friend is confused. This is a good thing. Any backslash you see
> in Python's default string output is *always* an escape:

Well, I think he's more annoyed that if Python is going to be so
helpful as to put in the missing "\" for you in "foo\zbar", then it
should put in the missing "\" for you in "\". He considers this to be
an
inconsistency.

Me, I'd never, ever, EVER want a language to special-case something at
the end of a string, but I can see that from his new-to-Python
perspective, Python seems to be DWIMing in one place and not the
other, and he thinks that it should either do no DWIMing at all, or
consistently DWIM. To not be consistent in this regard is "inelegant",
says he.

And I can see his point that allowing "foo\zbar" and "foo\\zbar" to be
synonymous is a form of DWIMing.

> > My point of view is that every language has *some* warts; Python
> > just has a bit fewer than most.  It would have been nice, I should
> > think, if this wart had been "fixed" in Python 3, as I do consider
> > it to be a minor wart.

> And if anyone had cared enough to raise it a couple of years back, it
> possibly might have been.

So, now if only my friend had learned Python years ago, when I told
him to, he possibly might be happy with Python by now!

|>ouglas


From pavlovevidence at gmail.com  Mon Aug 10 03:37:33 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Mon, 10 Aug 2009 00:37:33 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
Message-ID: 

On Aug 9, 11:10?pm, Steven D'Aprano
 wrote:
> On Sun, 09 Aug 2009 18:34:14 -0700, Carl Banks wrote:
> >> Why should a backslash in a string literal be an error?
>
> > Because the behavior of \ in a string is context-dependent, which means
> > a reader can't know if \ is a literal character or escape character
> > without knowing the context, and it means an innocuous change in context
> > can cause a rather significant change in \.
>
> *Any* change in context is significant with escapes.
>
> "this \nhas two lines"
>
> If you change the \n to a \t you get a significant difference. If you
> change the \n to a \y you get a significant difference. Why is the first
> one acceptable but the second not?

Because when you change \n to \t, you've haven't changed the meaning
of the \ character; but when you change \n to \y, you have, and you
did so without even touching the backslash.


> > IOW it's an error-prone mess.
>
> I've never had any errors caused by this.

Thank you for your anecdotal evidence.  Here's mine: This has gotten
me at least twice, and a compiler complaint would have reduced my bug-
hunting time from tens of minutes to ones of seconds.  [Aside: it was
when I was using Python on Windows for the first time]


> I've never seen anyone write to
> this newsgroup confused over escape behaviour, or asking for help with an
> error caused by it, and until this thread, never seen anyone complain
> about it either.

More anecdotal evidence.  Here's mine: I have.


> Excuse my cynicism, but I believe that you are using "error-prone" to
> mean "I don't like this behaviour" rather than "it causes lots of errors".

No, I'm using error-prone to mean error-prone.

Someone (obviously not you because you're have perfect knowledge of
the language and 100% situation awareness at all times) might have a
string like "abcd\stuv"  and change it to "abcd\tuvw" without even
thinking about the fact that the s comes after the backslash.

Worst of all: they might not even notice the error, because the repr
of this string is:

'abcd\tuwv'

They might not notice that the backslash is single, because (unlike
you) mortal fallible human beings don't always register tiny details
like a backslash being single when it should be double.

Point is, this is a very bad inconsistency.  It makes the behavior of
\ impossible to learn by analogy, now you have to memorize a list of
situations where it behaves one way or another.


Carl Banks


From darkwater42 at gmail.com  Mon Aug 10 03:57:18 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Mon, 10 Aug 2009 00:57:18 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
Message-ID: <246b6a1d-7e83-4ad3-9978-c2a55b884a6c@o13g2000vbl.googlegroups.com>

On Aug 10, 2:10?am, Steven D'Aprano

> I've never had any errors caused by this.

But you've seen an error caused by this, in this very discussion.
I.e., "foo\xbar".

"\xba" isn't an escape sequence in any other language that I've used,
which is one reason I made this error... Oh, wait a minute -- it *is*
an escape sequence in JavaScript. But in JavaScript, while "\xba" is a
special character, "\xb" is synonymous with "xb".

The fact that every language seems to treat these things similarly but
differently, is yet another reason why they should just be treated
utterly consistently by all of the languages: I.e., escape sequences
that don't have a special meaning should be an error!

> I've never seen anyone write to
> this newsgroup confused over escape behaviour,

My friend objects strongly the claim that he is "confused" by it, so I
guess you are right that no one is confused. He just thinks that it
violates the beautiful sense of aesthetics that he was sworn over and
over again Python to have.

But aesthetics is a non-negligible issue with practical ramifications.
(Not that anything can be done about this wart at this point,
however.)

> or asking for help with an error caused by it, and until
> this thread, never seen anyone complain about it either.

Oh, this bothered me too when I first learned Python, and I thought it
was stupid. It just didn't bother me enough to complain publicly.

Besides, the vast majority of Python noobs don't come here, despite
appearance sometimes, and by the time most people get here, they've
probably got bigger fish to fry.

|>ouglas




From bruno.42.desthuilliers at websiteburo.invalid  Mon Aug 10 04:08:32 2009
From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers)
Date: Mon, 10 Aug 2009 10:08:32 +0200
Subject: Monkeypatching an object to become callable
In-Reply-To: <0aa46ece-64b9-4c28-b690-5ac5937ce3f2@f20g2000prn.googlegroups.com>
References: <87hbwgu7xa.fsf@vostro.rath.org>
	<0aa46ece-64b9-4c28-b690-5ac5937ce3f2@f20g2000prn.googlegroups.com>
Message-ID: <4a7fd55e$0$32765$426a74cc@news.free.fr>

7stud a ?crit :
(snip)
> class Wrapper(object):
>     def __init__(self, obj, func):
>         self.obj = obj
>         self.func = func
> 
>     def __call__(self, *args):
>         return self.func(*args)
> 
>     def __getattr__(self, name):
>         return object.__getattribute__(self.obj, name)

This should be

           return getattr(self.obj, name)

directly calling object.__getattribute__ might skip redefinition of 
__getattribute__ in self.obj.__class__ or it's mro.



From frederic.leger at contactoffice.net  Mon Aug 10 04:35:54 2009
From: frederic.leger at contactoffice.net (=?iso-8859-1?Q?Fr=E9d=E9ric_L=E9ger?=)
Date: Mon, 10 Aug 2009 10:35:54 +0200 (CEST)
Subject: install tarball package Python on Debian, necessary modules not found
Message-ID: <16266394.6699.1249893354154.JavaMail.root@orville>

I use Debian Lenny and I tried to install the tarball packaging of the lastest python realease (http://www.python.org/download/, release 3.1). After read README file I launch standard Makefile commands. But at the end of "make" command, I have got this message:

"...
Python build finished, but the necessary bits to build these modules were not found:
_curses            _curses_panel      _dbm
_gdbm              _hashlib           _sqlite3
_ssl               _tkinter           bz2
readline
To find the necessary bits, look in setup.py in detect_modules() for the module's name.
..."

Solution:

So I installed these Debian packages to correct the problem:

_curses, _curses_panel = libncurses-dev
zlib = libbz2-dev
bz2 = libzip-dev
_dbm, _gdbm = libgdbm-dev 
_hashlib, _ssl = libssl-dev 
_sqlite3 = libsqlite3-dev 
_tkinter = tk8.4-dev 
readline = libreadline5-dev 

I use on command line "apt-get install libncurses-dev libbz2-dev ..."
After that, I retry to compile python "make clean ; make ...". And all modules are good.

Good work with Python 3.1 ;)


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 04:37:48 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 08:37:48 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
Message-ID: 

On Mon, 10 Aug 2009 00:37:33 -0700, Carl Banks wrote:

> On Aug 9, 11:10?pm, Steven D'Aprano
>  wrote:
>> On Sun, 09 Aug 2009 18:34:14 -0700, Carl Banks wrote:
>> >> Why should a backslash in a string literal be an error?
>>
>> > Because the behavior of \ in a string is context-dependent, which
>> > means a reader can't know if \ is a literal character or escape
>> > character without knowing the context, and it means an innocuous
>> > change in context can cause a rather significant change in \.
>>
>> *Any* change in context is significant with escapes.
>>
>> "this \nhas two lines"
>>
>> If you change the \n to a \t you get a significant difference. If you
>> change the \n to a \y you get a significant difference. Why is the
>> first one acceptable but the second not?
> 
> Because when you change \n to \t, you've haven't changed the meaning of
> the \ character; 

I assume you mean the \ character in the literal, not the (non-existent) 
\ character in the string.


> but when you change \n to \y, you have, and you did so
> without even touching the backslash.

Not at all.

'\n' maps to the string chr(10).
'\y' maps to the string chr(92) + chr(121).

In both cases the backslash in the literal have the same meaning: grab 
the next token (usually a single character, but not always), look it up 
in a mapping somewhere, and insert the result in the string object being 
built.

(I don't know if the *implementation* is precisely as described, but 
that's irrelevant. It's still functionally a mapping.) 



>> > IOW it's an error-prone mess.
>>
>> I've never had any errors caused by this.
> 
> Thank you for your anecdotal evidence.  Here's mine: This has gotten me
> at least twice, and a compiler complaint would have reduced my bug-
> hunting time from tens of minutes to ones of seconds.  [Aside: it was
> when I was using Python on Windows for the first time]

Okay, that's twice in, how many years have you been programming?

I've mistyped "xrange" as "xrnage" two or three times. Does that make 
xrange() "an error-prone mess" too? Probably not. Why is my mistake my 
mistake, but your mistake the language's fault?


[...]

Oh, wait, no, I tell I lie -- I *have* seen people reporting "bugs" here 
caused by backslashes. They're invariably Windows programmers writing 
pathnames using backslashes, so I'll give you that one: if you don't know 
that Python treats backslashes as special in string literals, you will 
screw up your Windows pathnames.

Interestingly, the problem there is not that \y resolves to literal 
backslash followed by y, but that \t DOESN'T resolve to the expected 
backslash-t. So it seems to me that the problem for Windows coders is not 
that \y doesn't raise an error, but the mere existence of backslash 
escapes.



> Someone (obviously not you because you're have perfect knowledge of the
> language and 100% situation awareness at all times) might have a string
> like "abcd\stuv"  and change it to "abcd\tuvw" without even thinking
> about the fact that the s comes after the backslash.

Deary me. And they might type "4+15" instead of "4*51", and now 
arithmetic is an "error-prone mess" too. If you know of a programming 
language which can prevent you making semantic errors, please let us all 
know what it is.

If you edit code without thinking, you will be burnt, and you get *zero* 
sympathy from me.


> Worst of all: they might not even notice the error, because the repr of
> this string is:
> 
> 'abcd\tuwv'
> 
> They might not notice that the backslash is single, because (unlike you)
> mortal fallible human beings don't always register tiny details like a
> backslash being single when it should be double.

"Help help, 123145 looks too similar to 1231145, and now I calculated my 
taxes wrong and will go to jail!!!"


> Point is, this is a very bad inconsistency.  It makes the behavior of \
> impossible to learn by analogy, now you have to memorize a list of
> situations where it behaves one way or another.

No, you don't "have" to memorize anything, you can go right ahead and 
escape every backslash, as I did for years. Your code will still work 
fine.

You already have to memorize what escape codes return special characters. 
The only difference is whether you learn "...and everything else raises 
an exception" or "...and everything else is returned unchanged". 

There is at least one good reason for preferring an error, namely that it 
allows Python to introduce new escape codes without going through a long, 
slow process. But the rest of these complaints are terribly unconvincing.



-- 
Steven


From deets at nospam.web.de  Mon Aug 10 04:39:19 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Mon, 10 Aug 2009 10:39:19 +0200
Subject: resume upload wsgi script
In-Reply-To: <49e41062-9e0d-4c5e-beca-edb02d3ce6e8@e34g2000vbm.googlegroups.com>
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
	
	<7e85i3F2fdc1eU1@mid.uni-berlin.de>
	<9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com>
	<7e8ildF2f1hcpU1@mid.uni-berlin.de>
	<49e41062-9e0d-4c5e-beca-edb02d3ce6e8@e34g2000vbm.googlegroups.com>
Message-ID: <7ea4lpF2dvr5cU1@mid.uni-berlin.de>

> 
> 250KB :)

So why do you bother?

> Its just HTTP1.1 has everything for making ftp like file transfers
> possible.
> When I write it to a file then I am back at square one because I still
> need to load it completely to get it into a blob.

Well, the blob is nothing but datat in the file-system. If you are 
*really* concerned about that, then don't use the db, but use the 
filesystem, appending to the file until it's finished - and storing a 
reference to it to the DB. We do that as well, because otherwise the db 
will become unmanagable anyway (dumping, backups).

> So there is no way to concatenate BLOB's without loading it completely
> into memory ?

In theory, the DB might offer special stream-based methods for these 
kinds of tasks, but the db-api lacks them. Some DB-adapters might offer 
some non-standard-extensions, but I don't think sqlite does.

Diez


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 04:49:20 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 08:49:20 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<246b6a1d-7e83-4ad3-9978-c2a55b884a6c@o13g2000vbl.googlegroups.com>
Message-ID: 

On Mon, 10 Aug 2009 00:57:18 -0700, Douglas Alan wrote:

> On Aug 10, 2:10?am, Steven D'Aprano
> 
>> I've never had any errors caused by this.
> 
> But you've seen an error caused by this, in this very discussion. I.e.,
> "foo\xbar".


Your complaint is that "invalid" escapes like \y resolve to a literal 
backslash-y instead of raising an error. But \xbar doesn't contain an 
invalid escape, it contains a valid hex escape. Your ignorance that \xHH 
is a valid hex escape (for suitable hex digits) isn't an example of an 
error caused by "invalid" escapes like \y.



> "\xba" isn't an escape sequence in any other language that I've used,
> which is one reason I made this error... Oh, wait a minute -- it *is* an
> escape sequence in JavaScript. But in JavaScript, while "\xba" is a
> special character, "\xb" is synonymous with "xb".
> 
> The fact that every language seems to treat these things similarly but
> differently, is yet another reason why they should just be treated
> utterly consistently by all of the languages: I.e., escape sequences
> that don't have a special meaning should be an error!

Perhaps all the other languages should follow Python's lead instead?

Or perhaps they should follow bash's lead, and map \C to C for every 
character. If there were no special escapes at all, Windows programmers 
wouldn't keep getting burnt when they write "C:\\Documents\today\foo" and 
end up with something completely unexpected.

Oh wait, no, that still wouldn't work, because they'd end up with 
C:\Documentstodayfoo. So copying bash doesn't work.

But copying C will upset the bash coders, because they'll write 
"some\ file\ with\ spaces" and suddenly their code won't even compile!!!

Seems like no matter what you do, you're going to upset *somebody*.



>> I've never seen anyone write to
>> this newsgroup confused over escape behaviour,
> 
> My friend objects strongly the claim that he is "confused" by it, so I
> guess you are right that no one is confused. He just thinks that it
> violates the beautiful sense of aesthetics that he was sworn over and
> over again Python to have.

Fair enough.



-- 
Steven


From no.i.dont at want.mail.from.spammers.com  Mon Aug 10 05:23:57 2009
From: no.i.dont at want.mail.from.spammers.com (Fencer)
Date: Mon, 10 Aug 2009 11:23:57 +0200
Subject: Problem with join in__str__() in class (newbie)
In-Reply-To: 
References: <7e8ek2F2dre5lU1@mid.individual.net>
	
	<7e8g3vF2etertU1@mid.individual.net>
	
	<7e8keqF2eib0lU1@mid.individual.net> 
Message-ID: <7ea79eF2esi87U1@mid.individual.net>

Piet van Oostrum wrote:
[snip]

Thanks for your detailed reply!

- Fencer


From duncan.booth at invalid.invalid  Mon Aug 10 05:34:38 2009
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 10 Aug 2009 09:34:38 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<246b6a1d-7e83-4ad3-9978-c2a55b884a6c@o13g2000vbl.googlegroups.com>
Message-ID: 

Douglas Alan  wrote:

> "\xba" isn't an escape sequence in any other language that I've used,
> which is one reason I made this error... Oh, wait a minute -- it *is*
> an escape sequence in JavaScript. But in JavaScript, while "\xba" is a
> special character, "\xb" is synonymous with "xb".
> 

"\xba" is an escape sequence in c, c++, c#, python, javascript, perl and 
probably many others.

"\xb" is an escape sequence in c, c++, c# but not in Python, Javascript, or 
Perl. Python will throw ValueError if you try to use "\xb" in a string, 
Javascript simply ignores the backslash.

> The fact that every language seems to treat these things similarly but
> differently, is yet another reason why they should just be treated
> utterly consistently by all of the languages: I.e., escape sequences
> that don't have a special meaning should be an error!

It would be nice if these things were treated consistently, but they aren't 
and it seems unlikely to change.



-- 
Duncan Booth http://kupuguy.blogspot.com


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 05:40:24 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 10 Aug 2009 09:40:24 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
Message-ID: 

On Mon, 10 Aug 2009 00:32:30 -0700, Douglas Alan wrote:

> In C++, if I know that the code I'm looking at compiles, then I never
> need worry that I've misinterpreted what a string literal means.

If you don't know what your string literals are, you don't know what your 
program does. You can't expect the compiler to save you from semantic 
errors. Adding escape codes into the string literal doesn't change this 
basic truth.

Semantics matters, and unlike syntax, the compiler can't check it. 
There's a difference between a program that does the equivalent of:

    os.system("cp myfile myfile~")

and one which does this

    os.system("rm myfile myfile~")


The compiler can't save you from typing 1234 instead of 11234, or 31.45 
instead of 3.145, or "My darling Ho" instead of "My darling Jo", so why 
do you expect it to save you from typing "abc\d" instead of "abc\\d"?

Perhaps it can catch *some* errors of that type, but only at the cost of 
extra effort required to defeat the compiler (forcing the programmer to 
type \\d to prevent the compiler complaining about \d). I don't think the 
benefit is worth the cost. You and your friend do. Who is to say you're 
right?



> At
> least not if it doesn't have any escape characters in it that I'm not
> familiar with. But in Python, if I see, "\f\o\o\b\a\z", I'm not really
> sure what I'm seeing, as I surely don't have committed to memory some of
> the more obscure escape sequences. If I saw this in C++, and I knew that
> it was in code that compiled, then I'd at least know that there are some
> strange escape codes that I have to look up. 

And if you saw that in Python, you'd also know that there are some 
strange escape codes that you have to look up. Fortunately, in Python, 
that's really simple:

>>> "\f\o\o\b\a\z"
'\x0c\\o\\o\x08\x07\\z'

Immediately you can see that the \o and \z sequences resolve to 
themselves, and the \f \b and \a don't.



> Unlike with Python, it
> would never be the case in C++ code that the programmer who wrote the
> code was just too lazy to type in "\\f\\o\\o\\b\\a\\z" instead.

But if you see "abc\n", you can't be sure whether the lazy programmer 
intended "abc"+newline, or "abc"+backslash+"n". Either way, the compiler 
won't complain.


 
>> You just have to memorize it. If you don't know what a backslash escape
>> is going to do, why would you use it?
> 
> (1) You're looking at code that someone else wrote, or (2) you forget to
> type "\\" instead of "\" in your code (or get lazy sometimes), as that
> is okay most of the time, and you inadvertently get a subtle bug.

The same error can occur in C++, if you intend \\n but type \n by 
mistake. Or vice versa. The compiler won't save you from that.



>> This is especially important when reading (as opposed to writing) code.
>> You read somebody else's code, and see "foo\xbar\n". Let's say you know
>> it compiles without warning. Big deal -- you don't know what the escape
>> codes do unless you've memorized them. What does \n resolve to? chr(13)
>> or chr(97) or chr(0)? Who knows?
> 
> It *is* a big deal. Or at least a non-trivial deal. It means that you
> can tell just by looking at the code that there are funny characters in
> the string, and not just a backslashes. 

I'm not entirely sure why you think that's a big deal. Strictly speaking, 
there are no "funny characters", not even \0, in Python. They're all just 
characters. Perhaps the closest is newline (which is pretty obvious).



> You don't have to go running for
> the manual every time you see code with backslashes, where the upshot
> might be that the programmer was merely saving themselves some typing.

Why do you care if there are "funny characters"?

In C++, if you see an escape you don't recognize, do you care? Do you go 
running for the manual? If the answer is No, then why do it in Python?

And if the answer is Yes, then how is Python worse than C++?


[...]
> Also, it seems that Python is being inconsistent here. Python knows that
> the string "\x" doesn't contain a full escape sequence, so why doesn't
> it
> treat the string "\x" the same way that it treats the string "\z"?
[...]
> I.e., "\z" is not a legal escape sequence, so it gets left as "\\z".

No. \z *is* a legal escape sequence, it just happens to map to \z.

If you stop thinking of \z as an illegal escape sequence that Python 
refuses to raise an error for, the problem goes away. It's a legal escape 
sequence that maps to backslash + z.



> "\x" is not a legal escape sequence. Shouldn't it also get left as
> "\\x"?

No, because it actually is an illegal escape sequence.



>> > He's particularly annoyed too, that if he types "foo\xbar" at the
>> > REPL, it echoes back as "foo\\xbar". He finds that to be some sort of
>> > annoying DWIM feature, and if Python is going to have DWIM features,
>> > then it should, for example, figure out what he means by "\" and not
>> > bother him with a syntax error in that case.
>>
>> Now your friend is confused. This is a good thing. Any backslash you
>> see in Python's default string output is *always* an escape:
> 
> Well, I think he's more annoyed that if Python is going to be so helpful
> as to put in the missing "\" for you in "foo\zbar", then it should put
> in the missing "\" for you in "\". He considers this to be an
> inconsistency.

(1) There is no missing \ in "foo\zbar".

(2) The problem with "\" isn't a missing backslash, but a missing end-
quote.





> Me, I'd never, ever, EVER want a language to special-case something at
> the end of a string, but I can see that from his new-to-Python
> perspective, Python seems to be DWIMing in one place and not the other,
> and he thinks that it should either do no DWIMing at all, or
> consistently DWIM. To not be consistent in this regard is "inelegant",
> says he.

Python isn't DWIMing here. The rules are simple and straightforward, 
there's no mind-reading or guessing required. There is no heuristic 
trying to predict what the user intends. It's a simple rule:

When parsing a string literal (apart from raw strings), if you see a 
backslash, then grab the next token (usually a single character, but for 
\x and \0 it could be multiple characters). If there is a mapping 
available for that token, insert that in the string being built, and if 
not, insert the backslash and the token.

(As I said earlier, this may not be precisely how it is implemented, but 
functionally, it is what Python does.)


> And I can see his point that allowing "foo\zbar" and "foo\\zbar" to be
> synonymous is a form of DWIMing.

Is it "a form of DWIMing" to consider 1.234e1 and 12.34  synonymous?

What about 86 and 0x44? Is that DWIMing?

I'm sure both you and your friend are excellent programmers, but you're 
tossing around DWIM as a meaningless term of opprobrium without any 
apparent understand of what DWIM actually is.




-- 
Steven



From duncan.booth at invalid.invalid  Mon Aug 10 05:41:52 2009
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 10 Aug 2009 09:41:52 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<246b6a1d-7e83-4ad3-9978-c2a55b884a6c@o13g2000vbl.googlegroups.com>
	
Message-ID: 

Steven D'Aprano  wrote:

> Or perhaps they should follow bash's lead, and map \C to C for every 
> character. If there were no special escapes at all, Windows
> programmers wouldn't keep getting burnt when they write
> "C:\\Documents\today\foo" and end up with something completely
> unexpected. 
> 
> Oh wait, no, that still wouldn't work, because they'd end up with 
> C:\Documentstodayfoo. So copying bash doesn't work.
> 

There is of course no problem at all so long as you stick to writing your 
paths as MS intended them to be written: 8.3 and UPPERCASE

>>> "C:\DOCUME~1\TODAY\FOO"
'C:\\DOCUME~1\\TODAY\\FOO'

:^)


-- 
Duncan Booth http://kupuguy.blogspot.com


From garabik-news-2005-05 at kassiopeia.juls.savba.sk  Mon Aug 10 05:43:08 2009
From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk)
Date: Mon, 10 Aug 2009 09:43:08 +0000 (UTC)
Subject: install tarball package Python on Debian,
	necessary modules not found
References: 
Message-ID: 

Fr?d?ric L?ger  wrote:

> I use Debian Lenny and I tried to install the tarball packaging of the
> lastest python realease (http://www.python.org/download/, release
> 3.1). After read README file I launch standard Makefile commands. But
> at the end of "make" command, I have got this message:
> 

Maybe you know, but there is python3.1 deb in experimental. Works with
testing like a charm. It is also possible to install ubuntu's 3.X into
debian.

-- 
 -----------------------------------------------------------
| Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__    garabik @ kassiopeia.juls.savba.sk     |
 -----------------------------------------------------------
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!


From thangappan143 at gmail.com  Mon Aug 10 05:45:07 2009
From: thangappan143 at gmail.com (Thangappan.M)
Date: Mon, 10 Aug 2009 15:15:07 +0530
Subject: Problem in installing PyGreSQL
In-Reply-To: 
References: <7aa29e790908032045p3b52a633m8d0e366a0f648b@mail.gmail.com>
	<7f0b4d2b1d5bd3f3057ead3b029059b9@preisshare.net>
	<20090804084856.b825967a.darcy@druid.net>
	
	<20090804095547.a5274e22.darcy@druid.net> 
	<7aa29e790908060330x67d900a9rfb4677eaf0eddeb@mail.gmail.com>
	
	
Message-ID: <7aa29e790908100245k3c08dc36mcebbfa48a0d6bdc4@mail.gmail.com>

Here I attached the setup.py and setup.cfg file.This is for your reference.
I have changed the exception line.
Even though I got the following error while running the python setup.py
build
running build
running build_py
running build_ext
error: No such file or directory

===========================================

On Fri, Aug 7, 2009 at 7:38 PM, Scott David Daniels
wrote:

> Dennis Lee Bieber wrote:
>
>> On Thu, 6 Aug 2009 16:00:15 +0530, "Thangappan.M"
>>  declaimed the following in
>> gmane.comp.python.general:
>>
>>>  File "./setup.py", line 219, in finalize_options
>>>    except (Warning, w):
>>> NameError: global name 'w' is not defined
>>>
>>> What would be the solution?
>>> Otherwise can you tell how to install DB-API in debian machine.
>>>
>>        Sorry... 1) I run on WinXP; 2) I don't build packages, relying on
>> pre-built binaries; 3) I run MySQL.
>>
>>        However, based upon the examples in the Tutorial, that line should
>> not have the (, ). A parenthesised (tuple) is suppose to contain a list
>> of exceptions, and the parameter to catch the exception specifics has to
>> be outside the list.
>>
>>        Best I can suggest is editing that particular line and removing the
>> (, ) -- then try rebuilding.
>>
>>        I'll also re-ask: All you are installing is the Python adapter to
>> the database. DO YOU HAVE A RUNNING PostgreSQL server that you can
>> connect to?
>>
>
> Just to be a bit more explict:
> Change file setup.py's line 219 from:
> >>     except (Warning, w):
> to either (OK in Python 2.6 and greater):
>       except Warning as w:
> or (works for Python 2.X):
>       except Warning, w:
>
>
> --Scott David Daniels
> Scott.Daniels at Acm.Org
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Regards,
Thangappan.M
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: setup.cfg
Type: application/octet-stream
Size: 2041 bytes
Desc: not available
URL: 
-------------- next part --------------
A non-text attachment was scrubbed...
Name: setup.py
Type: text/x-python
Size: 15479 bytes
Desc: not available
URL: 

From manu3d at gmail.com  Mon Aug 10 06:01:30 2009
From: manu3d at gmail.com (Emanuele D'Arrigo)
Date: Mon, 10 Aug 2009 03:01:30 -0700 (PDT)
Subject: exec("dir()",d)
References: <9adbf402-3e7e-44a4-adb3-afc36d5d88ba@33g2000vbe.googlegroups.com>
	
Message-ID: <138a15c5-a39b-427a-91c6-47ce7dd52a78@f33g2000vbm.googlegroups.com>

Thank you both for the explanation.

As a matter of fact RTFM doesn't -always- help. Sometimes I'm just
thick and I can read the manual 10 times and still not understand, as
it happened on this particular matter. Your contribution focused my
attention on the right bit of the manual which I somehow didn't manage
to ingest before. Now I understand.

Thank you.

Manu


From deets at nospam.web.de  Mon Aug 10 06:52:26 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Mon, 10 Aug 2009 12:52:26 +0200
Subject: Cython + setuptools not working with .pyx,only with .c-files
References: <7dvq5fF2e21b7U1@mid.uni-berlin.de>
	<4a7c56e0$0$31871$9b4e6d93@newsspool3.arcor-online.net>
Message-ID: <7eacfaF2fi1s2U1@mid.uni-berlin.de>

Stefan Behnel wrote:

> Diez B. Roggisch wrote:
>> I'm trying to build a Cython-extension as Egg.
>> 
>> However, this doesn't work - I can either use distutils to build the
>> extension, creating a myextension.c-file on the way.
>> 
>> If that's there, I can use setuptools to build the egg.
>> 
>> But when I remove the .c-file, the .pyx-file isn't used to re-generate
>> it.
> 
> setuptools monkeypatch into distutils to support Pyrex if it's installed,
> but most non-bleeding-edge versions do not know about Cython and thus
> break the Cython distutils support when Pyrex isn't there as well.
> 
> What helps is to put a fake Pyrex installation into your sys.path, like
> 
> http://codespeak.net/svn/lxml/trunk/fake_pyrex/
> 
> as done at the top of
> 
> http://codespeak.net/svn/lxml/trunk/setup.py

Thanks, that did the trick for us.

Diez


From subhakolkata1234 at gmail.com  Mon Aug 10 07:26:57 2009
From: subhakolkata1234 at gmail.com (joy99)
Date: Mon, 10 Aug 2009 04:26:57 -0700 (PDT)
Subject: Problem Regarding Handling of Unicode string
Message-ID: <9ac0e194-9e25-468a-9807-957ef3142dd3@i18g2000pro.googlegroups.com>

Dear Group,

I am using Python26 on WindowsXP with service pack2. My GUI is IDLE.
I am using Hindi resources and get nice output like:
??
where I can use all the re functions and other functions without doing
any transliteration,etc.
I was trying to use Bengali but it is giving me output like:
'\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95'
I wanted to see Bengali output as
????
and I like to use all functions including re.
If any one can help me on that.
Best Regards,
Subhabrata.


From nair.jitendra at gmail.com  Mon Aug 10 07:39:03 2009
From: nair.jitendra at gmail.com (jitu)
Date: Mon, 10 Aug 2009 04:39:03 -0700 (PDT)
Subject: Problem when fetching page using urllib2.urlopen
Message-ID: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>

Hi,

A html page  contains 'anchor' elements with 'href' attribute  having
a semicolon  in the url , while fetching the page using
urllib2.urlopen, all such href's  containing  'semicolons' are
truncated.


For example the href http://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt=AlWSqpkpqhICp1lMgChtJkCdGWoL
get truncated to http://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i

The page I am talking about can be fetched from
http://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_ylc=X3oDMTFka28zOGNuBF9TAzI3NjY2NzkEX3MDOTY5NTUzMjUEc2VjA3NzcC1kZXN0BHNsawN0aXRsZQ--

Thanks a Lot
Regards
jitu



From eckhardt at satorlaser.com  Mon Aug 10 07:41:01 2009
From: eckhardt at satorlaser.com (Ulrich Eckhardt)
Date: Mon, 10 Aug 2009 13:41:01 +0200
Subject: Problem Regarding Handling of Unicode string
References: <9ac0e194-9e25-468a-9807-957ef3142dd3@i18g2000pro.googlegroups.com>
Message-ID: 

joy99 wrote:
> [...] it is giving me output like:
> '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95'
   ^^^^^^^^^^^^

These three bytes encode the byte-order marker (BOM, Unicode uFEFF) as
UTF-8, followed by codepoint u09a8 (look it up on unicode.org what that
is).

In any case, if this is produced as output, there is some missing
encoding/decoding going on. You mentioned that it works in one case but
doesn't in another. Since you didn't provide any information how to
reproduce what you saw, any further help is at most guesswork.

Uli

-- 
Sator Laser GmbH
Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932



From python at mrabarnett.plus.com  Mon Aug 10 07:41:08 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Mon, 10 Aug 2009 12:41:08 +0100
Subject: Unrecognized escape sequences in string literals
In-Reply-To: 
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>	
	
Message-ID: <4A800754.20907@mrabarnett.plus.com>

Steven D'Aprano wrote:
> On Sun, 09 Aug 2009 17:56:55 -0700, Douglas Alan wrote:
> 
[snip]
>> My point of view is that
>> every language has *some* warts; Python just has a bit fewer than most.
>> It would have been nice, I should think, if this wart had been "fixed"
>> in Python 3, as I do consider it to be a minor wart.
> 
> And if anyone had cared enough to raise it a couple of years back, it 
> possibly might have been.
> 
My preference would've been that a backslash followed by A-Z, a-z, or
0-9 is special, but a backslash followed by any other character is just
the character, except for backslash followed by a newline, which
suppresses the newline.

I would also have preferred a backslash in a raw string to always be a
literal.

Ah well, something for Python 4.x. :-)


From nair.jitendra at gmail.com  Mon Aug 10 07:43:12 2009
From: nair.jitendra at gmail.com (jitu)
Date: Mon, 10 Aug 2009 04:43:12 -0700 (PDT)
Subject: Problem when fetching page using urllib2.urlopen
References: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>
Message-ID: <0579ebc0-2542-4f96-af3e-9861ad646b13@d9g2000prh.googlegroups.com>

On Aug 10, 4:39?pm, jitu  wrote:
> Hi,
>
> A html page ?contains 'anchor' elements with 'href' attribute ?having
> a semicolon ?in the url , while fetching the page using
> urllib2.urlopen, all such href's ?containing ?'semicolons' are
> truncated.
>
> For example the hrefhttp://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt...
> get truncated tohttp://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i
>
> The page I am talking about can be fetched fromhttp://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_...
>
> Thanks a Lot
> Regards
> jitu

Hi

   Sorry, the question what I wanted to ask was, whether is this the
correct behaviour or a bug ?


Thanks A Lot.
Regards
jitu


From sibtey.mehndi at genpact.com  Mon Aug 10 08:23:56 2009
From: sibtey.mehndi at genpact.com (Mehndi, Sibtey)
Date: Mon, 10 Aug 2009 17:53:56 +0530
Subject: [Errno 9] Bad file descriptor
Message-ID: <1A343A98C8DAE44A8D9D1BF310F90D5E0141163674@GCPWINGGN2EVS11.IND.CORP.AD>

Hi
I am trying to create a COM object of picalo functionalities so that I can use it into my VB application but I am getting the following error "[Errno 9] bad file descriptor".
Can you please suggest me what is supposed to do to avoid this problem?

This is my code

class Test(object):
    _reg_progid_ = "test"
    _reg_clsid_ = "{D2EFAAC0-797A-471A-AA07-ECEACFE33A08}"
    _public_methods_ = ['dbconnect']


    def dbconnect(self, dbName, dbUserName, dbPWD, dbHost, dbPort):
        try:
            self.conn = Database.MySQLConnection(dbName, username=dbUserName, password=dbPWD, host=dbHost, port=dbPort)
            self.table = self.conn.table( "SELECT * FROM test_flag_data")
            return  "connected"
        except Exception,e:
            return str(e)

Thanks,
Sibty



This e-mail (and any attachments), is confidential and may be privileged. It may be read, copied and used only
by intended recipients. Unauthorized access to this e-mail (or attachments) and disclosure or copying of its 
contents or any action taken in reliance on it is unlawful. Unintended recipients must notify the sender immediately 
by e-mail/phone & delete it from their system without making any copies or disclosing it to a third person.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nadiasvertex at gmail.com  Mon Aug 10 08:41:28 2009
From: nadiasvertex at gmail.com (Christopher)
Date: Mon, 10 Aug 2009 05:41:28 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
	
	<4A7DC141.9070207@v.loewis.de>
	<54581bf3-c9a1-4bbf-945c-28d436ffda2a@k13g2000prh.googlegroups.com>
	<4cea29ee-cc89-4494-aef9-0f46f8dd11b9@2g2000prl.googlegroups.com> 
	<80c46b94-9df2-43f5-9182-37c2413db783@b25g2000prb.googlegroups.com>
Message-ID: 

On Aug 8, 5:50?pm, Pouya Khankhanian  wrote:
> On Aug 8, 11:49?am, Sharath  wrote:
>
>
>
> > On Aug 8, 11:33?am, Pouya Khankhanian  wrote:
>
> > > On Aug 8, 11:17?am, "Martin v. L?wis"  wrote:
>
> > > > > This is probably a stupid question, but Is there going to be any data
> > > > > loss if it turns out that the disk has died completely? I assume there
> > > > > are backups of the repo that are geographically distributed.
>
> > > > Yes, we have backups, and are restoring them at the moment. However,
> > > > we still haven't given up on the original disks: they are (probably)
> > > > fine; it's just the RAID controller that has failed (and we can't buy a
> > > > replacement before Monday).
>
> > > > Regards,
> > > > Martin
>
> > > Is there a mirror site to download the latest python installer? Every
> > > mirror I have found on the web redirects me to python.org.
> > > Best
> > > Peter
>
> > Python FTP mirror sites also have the same problem. They are not being
> > mirrored for some require a password. Is there any other way to get a
> > copy?
>
> > Sharath Venkatesha
>
> Website is back up! Thanks for all the hard work

Actually, it appears to be down again.


From kdawg44 at gmail.com  Mon Aug 10 08:47:19 2009
From: kdawg44 at gmail.com (Kevin Holleran)
Date: Mon, 10 Aug 2009 08:47:19 -0400
Subject: Changing Remote Registry
In-Reply-To: <4A7C6D96.3000201@timgolden.me.uk>
References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com>
	<4A7C6D96.3000201@timgolden.me.uk>
Message-ID: <5caea3690908100547l65394e65le111d8f3dda9e903@mail.gmail.com>

On Fri, Aug 7, 2009 at 2:08 PM, Tim Golden  wrote:

> Kevin Holleran wrote:
>
>> Long story short, I am using _winreg to do this.
>>
>> hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE)
>> value,type = _winreg.QueryValueEx(hKey, item)
>> if (value == wrongValue):
>>       _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue)
>>
>>
>> When I do this I receive the error:
>>
>> _winreg.SetValue WindowsError: [Error 5] Access Denied
>>
>
> As an alternative, try using WMI instead. You'll have to look up the docs
> a bit, but to get you started:
>
> 
> import wmi
>
> reg = wmi.WMI ("remote-machine", namespace="default").StdRegProv
>
> print reg.methods.keys ()
>
> 
>
> TJG
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Thank you for your response.

I actually started with the WMI wrapper but isn't that just a wrapper that
utilizes (in this case) the _winreg module?

I guess my question is will Windows let me change the registry remotely?
The error is a Windows permission error on the KEY_SET_VALUE.  I am running
this as a domain admin on a machine on the domain.  Does the connection
inherit the credentials I am running it under or will I need to pass those
in?  Or does Windows simply not let me change the registry?

To me its not worth too much trouble.  If I can change it in place it saves
me just a little bit of work because I have to touch each machine anyway for
other reasons.  The big difference is that I can change all the machines I
have to touch right now and get them fixed up or these folks are just going
to have to wait until I get to each one.

Thanks for all your help and support.

Kevin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From ebonak at hotmail.com  Mon Aug 10 08:50:21 2009
From: ebonak at hotmail.com (Esmail)
Date: Mon, 10 Aug 2009 08:50:21 -0400
Subject: compression level with tarfile (w:gz) ?
Message-ID: 

Hello,

I was wondering if it possible to specify a compression level when I
tar/gzip a file in Python using the tarfile module. I would like to
specify the highest (9) compression level for gzip.

Ideally:

    t = tarfile.open(tar_file_name+'.tar.gz', mode='w:gz:9')

When I create a simple tar and then gzip it 'manually' with compression
level 9, I get a smaller archive than when I have this code execute with
the w:gz option.

Is the only way to accomplish the higher rate to create a tar file
and then use a different module to gzip it (assuming I can specify
the compression level there)?

Thanks,
Esmail

-----------------
My current code:
-----------------

def tar_it_up(target_dir_name, tar_file_name=None):
     '''
     tar up target_dir_name directory and create a
     tar/zip file with base name tar_file_name

     appends a date/timestamp to tar_file_name
     '''

     time_string = time.strftime("_%b_%d_%Y_%a_%H_%M")

     if tar_file_name is None:
         tar_file_name = target_dir_name

     tar_file_name += time_string

     print ('Creating archive of %s ...' % target_dir_name),

     t = tarfile.open(tar_file_name+'.tar.gz', mode='w:gz')
#   t = tarfile.open(tar_file_name+'.tar', mode='w')
     t.add(target_dir_name)
     t.close()

     print ('saved to %s.tar.gz' % tar_file_name)



From contact at xavierho.com  Mon Aug 10 08:51:21 2009
From: contact at xavierho.com (Xavier Ho)
Date: Mon, 10 Aug 2009 22:51:21 +1000
Subject: www.python.org website is down?
In-Reply-To: 
References: 
	
	
	<4A7DC141.9070207@v.loewis.de>
	<54581bf3-c9a1-4bbf-945c-28d436ffda2a@k13g2000prh.googlegroups.com>
	<4cea29ee-cc89-4494-aef9-0f46f8dd11b9@2g2000prl.googlegroups.com>
	<80c46b94-9df2-43f5-9182-37c2413db783@b25g2000prb.googlegroups.com>
	
Message-ID: <2d56febf0908100551v6ad45fb3u5b77adc0149051d8@mail.gmail.com>

On Mon, Aug 10, 2009 at 10:41 PM, Christopher wrote:

>
> Actually, it appears to be down again.
>

Nope, works for me, just a little slow.

-Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From benjamin.kaplan at case.edu  Mon Aug 10 09:19:43 2009
From: benjamin.kaplan at case.edu (Benjamin Kaplan)
Date: Mon, 10 Aug 2009 09:19:43 -0400
Subject: compression level with tarfile (w:gz) ?
In-Reply-To: 
References: 
Message-ID: 

On Mon, Aug 10, 2009 at 8:50 AM, Esmail wrote:
> Hello,
>
> I was wondering if it possible to specify a compression level when I
> tar/gzip a file in Python using the tarfile module. I would like to
> specify the highest (9) compression level for gzip.
>
> Ideally:
>
> ? t = tarfile.open(tar_file_name+'.tar.gz', mode='w:gz:9')
>
> When I create a simple tar and then gzip it 'manually' with compression
> level 9, I get a smaller archive than when I have this code execute with
> the w:gz option.
>

Looking at the tarfile docs, it seems that there are tarfile.gzopen
and tarfile.bz2open functions that have a compresslevel parameter that
defaults to 9. You can't append using those functions but you can read
and write.

> Is the only way to accomplish the higher rate to create a tar file
> and then use a different module to gzip it (assuming I can specify
> the compression level there)?
>
> Thanks,
> Esmail
>
> -----------------
> My current code:
> -----------------
>
> def tar_it_up(target_dir_name, tar_file_name=None):
> ? ?'''
> ? ?tar up target_dir_name directory and create a
> ? ?tar/zip file with base name tar_file_name
>
> ? ?appends a date/timestamp to tar_file_name
> ? ?'''
>
> ? ?time_string = time.strftime("_%b_%d_%Y_%a_%H_%M")
>
> ? ?if tar_file_name is None:
> ? ? ? ?tar_file_name = target_dir_name
>
> ? ?tar_file_name += time_string
>
> ? ?print ('Creating archive of %s ...' % target_dir_name),
>
> ? ?t = tarfile.open(tar_file_name+'.tar.gz', mode='w:gz')
> # ? t = tarfile.open(tar_file_name+'.tar', mode='w')
> ? ?t.add(target_dir_name)
> ? ?t.close()
>
> ? ?print ('saved to %s.tar.gz' % tar_file_name)
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


From ebonak at hotmail.com  Mon Aug 10 09:37:14 2009
From: ebonak at hotmail.com (Esmail)
Date: Mon, 10 Aug 2009 09:37:14 -0400
Subject: compression level with tarfile (w:gz) ?
In-Reply-To: 
References: 
	
Message-ID: 

Benjamin Kaplan wrote:
> On Mon, Aug 10, 2009 at 8:50 AM, Esmail wrote:
>>
>> I was wondering if it possible to specify a compression level when I
>> tar/gzip a file in Python using the tarfile module. I would like to
>> specify the highest (9) compression level for gzip.
>>
>> Ideally:
>>
>>   t = tarfile.open(tar_file_name+'.tar.gz', mode='w:gz:9')
<..>
> 
> Looking at the tarfile docs, it seems that there are tarfile.gzopen
> and tarfile.bz2open functions that have a compresslevel parameter that
> defaults to 9. You can't append using those functions but you can read
> and write.

Hi Benjamin,

I can't find tarfile.gzopen  in the tarfile docs, I'm looking here:

     http://docs.python.org/library/tarfile.html

Am I looking at the wrong page?

Thanks,

Esmail



From lars at gustaebel.de  Mon Aug 10 09:41:08 2009
From: lars at gustaebel.de (Lars =?iso-8859-1?Q?Gust=E4bel?=)
Date: Mon, 10 Aug 2009 15:41:08 +0200
Subject: compression level with tarfile (w:gz) ?
In-Reply-To: 
References: 
Message-ID: <20090810134108.GA7790@axis.g33x.de>

On Mon, Aug 10, 2009 at 08:50:21AM -0400, Esmail wrote:
> I was wondering if it possible to specify a compression level when I
> tar/gzip a file in Python using the tarfile module. I would like to
> specify the highest (9) compression level for gzip.

tarfile uses gzip.GzipFile() internally, GzipFile()'s default compression level
is 9.

> When I create a simple tar and then gzip it 'manually' with compression
> level 9, I get a smaller archive than when I have this code execute with
> the w:gz option.

How much smaller is it? I did a test with a recent Linux kernel source tree
which made an archive of 337MB. Command-line gzip was ahead of Python's
GzipFile() by just 20200 bytes(!) with an archive of about 74MB.

> Is the only way to accomplish the higher rate to create a tar file
> and then use a different module to gzip it (assuming I can specify
> the compression level there)?

If you need the disk space that badly, the alternative would be to pipe
tarfile's output to command-line gzip somehow:

fobj = open("result.tar.gz", "w")
proc = subprocess.Popen(["gzip", "-9"], stdin=subprocess.PIPE, stdout=fobj)
tar = tarfile.open(fileobj=proc.stdin, mode="w|")
tar.add(...)
tar.close()
proc.stdin.close()
fobj.close()

Cheers,

-- 
Lars Gust?bel
lars at gustaebel.de

A physicist is an atom's way of knowing about atoms.
(George Wald)


From benjamin.kaplan at case.edu  Mon Aug 10 09:55:06 2009
From: benjamin.kaplan at case.edu (Benjamin Kaplan)
Date: Mon, 10 Aug 2009 09:55:06 -0400
Subject: compression level with tarfile (w:gz) ?
In-Reply-To: 
References: 
	
	
Message-ID: 

On Mon, Aug 10, 2009 at 9:37 AM, Esmail wrote:
> Benjamin Kaplan wrote:
>>
>> On Mon, Aug 10, 2009 at 8:50 AM, Esmail wrote:
>>>
>>> I was wondering if it possible to specify a compression level when I
>>> tar/gzip a file in Python using the tarfile module. I would like to
>>> specify the highest (9) compression level for gzip.
>>>
>>> Ideally:
>>>
>>> ?t = tarfile.open(tar_file_name+'.tar.gz', mode='w:gz:9')
>
> <..>
>>
>> Looking at the tarfile docs, it seems that there are tarfile.gzopen
>> and tarfile.bz2open functions that have a compresslevel parameter that
>> defaults to 9. You can't append using those functions but you can read
>> and write.
>
> Hi Benjamin,
>
> I can't find tarfile.gzopen ?in the tarfile docs, I'm looking here:
>
> ? ?http://docs.python.org/library/tarfile.html
>
> Am I looking at the wrong page?
>

My mistake. It isn't a function of the tarfile module, it's a class
method of tarfile.TarFile. I was looking at the help in the
interactive interpreter. It doesn't seem to be in the official docs,
but you can use pydoc to view the docstrings.

> Thanks,
>
> Esmail
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


From rt8396 at gmail.com  Mon Aug 10 09:57:43 2009
From: rt8396 at gmail.com (r)
Date: Mon, 10 Aug 2009 06:57:43 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
Message-ID: <1d952f0b-9552-48ef-ad2e-a7b8e06ea8eb@n2g2000vba.googlegroups.com>

On Aug 8, 8:48?am, MRAB  wrote:
...(snip)
> Bothwww.python.organd svn.python.org are down. ?They're hosted on
> the same machine, and it seems to have run into disk problems and
> hasn't rebooted even after power-cycling. ?Thomas Wouters will be
> visiting the machine physically tomorrow to try to diagnose the
> problem.

Oh stop lying MRAB, everybody knows Guido hosts Python.org from his
attic on an old Linux box :-)


From rurpy at yahoo.com  Mon Aug 10 10:01:04 2009
From: rurpy at yahoo.com (rurpy at yahoo.com)
Date: Mon, 10 Aug 2009 07:01:04 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
Message-ID: <616c058c-2595-42fc-b80d-e599d5d6ad66@o36g2000vbl.googlegroups.com>

On Aug 9, 10:02?pm, David Lyon  wrote:
...
> Before you do that, you should clearly work out in your own mind
> how you think things need to improve. It's not good enough just
> saying this or that is bad without having specific ideas on what
> needs to change.
'''

He did.  Did you read, for example, the critique of the gzip
docs for which he gave the url

   http://xahlee.org/perl-python/python_doc_gzip.html

There were some things I might not completely agree with
there, but basically, I thought it was right on, including
his suggestions on how to improve it.


From darkwater42 at gmail.com  Mon Aug 10 10:11:33 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Mon, 10 Aug 2009 07:11:33 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
Message-ID: 

On Aug 10, 4:37?am, Steven D'Aprano

> There is at least one good reason for preferring an error, namely that it
> allows Python to introduce new escape codes without going through a long,
> slow process. But the rest of these complaints are terribly unconvincing.


What about:

   o Beautiful is better than ugly
   o Explicit is better than implicit
   o Simple is better than complex
   o Readability counts
   o Special cases aren't special enough to break the rules
   o Errors should never pass silently

?

And most importantly:

   o In the face of ambiguity, refuse the temptation to guess.
   o There should be one -- and preferably only one -- obvious way to
do it.

?

So, what's the one obvious right way to express "foo\zbar"? Is it

   "foo\zbar"

or

   "foo\\zbar"

And if it's the latter, what possible benefit is there in allowing the
former?  And if it's the former, why does Python echo the latter?

|>ouglas


From python at mrabarnett.plus.com  Mon Aug 10 10:13:12 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Mon, 10 Aug 2009 15:13:12 +0100
Subject: www.python.org website is down?
In-Reply-To: <1d952f0b-9552-48ef-ad2e-a7b8e06ea8eb@n2g2000vba.googlegroups.com>
References: 	
	<1d952f0b-9552-48ef-ad2e-a7b8e06ea8eb@n2g2000vba.googlegroups.com>
Message-ID: <4A802AF8.1000407@mrabarnett.plus.com>

r wrote:
> On Aug 8, 8:48 am, MRAB  wrote:
> ...(snip)
>> Bothwww.python.organd svn.python.org are down.  They're hosted on
>> the same machine, and it seems to have run into disk problems and
>> hasn't rebooted even after power-cycling.  Thomas Wouters will be
>> visiting the machine physically tomorrow to try to diagnose the
>> problem.
> 
> Oh stop lying MRAB, everybody knows Guido hosts Python.org from his
> attic on an old Linux box :-)

That was a quote from A.M. Kuchling.

It's actually hosted on a matchbox-sized multi-core multi-terabyte
wifi-enabled Linux machine that Guido brought back from 2050.
Unfortunately, the dog ate it, so he's had to go and buy another one!
:-)


From pruebauno at latinmail.com  Mon Aug 10 10:17:22 2009
From: pruebauno at latinmail.com (nn)
Date: Mon, 10 Aug 2009 07:17:22 -0700 (PDT)
Subject: syntax checker in python
References: 
Message-ID: <8bcca8f4-673c-4478-a2ad-fc292c761062@m20g2000vbp.googlegroups.com>

On Aug 7, 4:39?pm, horos11  wrote:
> ps - I just realized that it isn't enough to do:
>
> python -c 'import /path/to/script'
>
> since that actually executes any statement inside of the script
> (wheras all I want to do is check syntax)
>
> So - let me reprhase that - exactly how can you do a syntax check in
> python? Something like perl's -c:
>
> ? ? ?perl -c script_name.p
>
> Ed

You might want to check PyFlakes; it doesn't execute scripts unlike
the others.

http://www.divmod.org/trac/wiki/DivmodPyflakes


From eckhardt at satorlaser.com  Mon Aug 10 10:37:25 2009
From: eckhardt at satorlaser.com (Ulrich Eckhardt)
Date: Mon, 10 Aug 2009 16:37:25 +0200
Subject: With or without leading underscore...
Message-ID: <5un5l6-fvn.ln1@satorlaser.homedns.org>

...that is the question!

I have a module which exports a type. It also exports a function that
returns instances of that type. Now, the reason for my question is that
while users will directly use instances of the type, they will not create
instances of the type themselves.

So, the type is a part of the public API, but its constructor is not. Should
I mark the type as private (with a leading underscore) or not?

Thanks!

Uli

-- 
Sator Laser GmbH
Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932



From mydevforums at gmail.com  Mon Aug 10 10:48:31 2009
From: mydevforums at gmail.com (IronyOfLife)
Date: Mon, 10 Aug 2009 07:48:31 -0700 (PDT)
Subject: Python configuration question when python scripts are executed 
	using Appweb as web server.
References: 
	
	
	
	
	
Message-ID: 

Hi Gabriel

Thanks for the detailed and useful reply.


On Aug 7, 1:37?am, "Gabriel Genellina"  wrote:
> En Thu, 06 Aug 2009 12:49:30 -0300, IronyOfLife  ?
> escribi?:
>
>
>
>
>
> > On Aug 5, 4:18?pm, "Gabriel Genellina"  wrote:
> >> En Tue, 04 Aug 2009 10:15:24 -0300, IronyOfLife 
> >> escribi?:
> >> > On Aug 3, 8:42?pm, "Gabriel Genellina"  wrote:
> >> >> En Mon, 03 Aug 2009 11:04:07 -0300, IronyOfLife ?
> >>  ?
> >> >> escribi?:
>
> >> >> > I have installed python 2.6.2 in windows xp professional machine. I
> >> >> > have set the following environment variables -- PYTHONPATH. It ?
> >> points
> >> >> > to following windows folders: python root folder, the lib folder ?
> >> and
> >> >> > lib-tk folder.
>
> >> >> Why? Did you read it somewhere? Usually there is no need to set the ?
> >> >> PYTHONPATH variable at all; remove it.
>
> >> > Setting PYTHONPATH environment variables is mentioned in Python docs.
>
> >> Could you provide a link please? Setting PYTHONPATH should not be
>
> > Here are couple of links that discusses setting PYTHONPATH environment
> > variable.
> >http://docs.python.org/using/windows.html
>
> Ouch, that document should be reworked and updated!
>
> >http://www.daimi.au.dk/~chili/PBI/pythonpath.html
>
> That's mostly obsolete for current versions. Since PEP370 [0] was ?
> implemented, a per-user private directory is already in sys.path now, so ?
> there is no need to play with PYTHONPATH.

Thanks for the clarification on PYTHONPATH.
>
> > I understand your concerns regarding setting of PYTHONPATH while
> > multiple versions of Python are installed on the same machine. My fix
> > however does not use PYTHONPATH. The GNUTLS wrapper module for PYTHON
> > loads the GNUTLS dll's and it was not able to find them. Using FileMon
> > (win tool) I found out the paths that are scanned and I copied the
> > dlls to one of such paths. I still do not like this fix. This is a
> > temporary solution.
>
> Note that this cannot be fixed from inside Python. When you import a ?
> module, the interpreter scans the directories in ITS search path ?
> (sys.path) looking for a matching module. Once the module is found:
> - if it is a Python file, it's executed
> - if it is an extension module (a .pyd file, in fact a .dll renamed) it's ?
> loaded using LoadLibraryEx (a Windows function), and finally its ?
> initialization routine is executed.
>
> For LoadLibrary to successfully load the module, all its external ?
> references must be resolved. That is, Windows must locate and load all ?
> other DLLs that this module depends on, using its own search strategy [1], ?
> taking into account the PATH environment variable and many other places.
>
> It is at this stage that you get the error: when the gnutls wrapper ?
> attempts to load the gnutls DLL. That search is done by Windows, not by ?
> Python, and PYTHONPATH has nothing to do with it.
>
> Why different results in IIS and appweb? Note that there exist several ?
> search strategies, they depend on the application home directory, the ?
> location of the .exe, whether SetDllDirectory was called or not, whether ?
> the application has a manifest or not, a .local file or not... Hard to ?
> tell with so many variables.

This is fairly easy to explain. When I configured IIS to execute
python scripts, as per the documentation I pass two command line
arguments. Appweb works this way. It opens up a new command process
and in the function parameter for environment it sets only SYSTEMROOT.
It does not set the PATH variable (A BUG IN APPWEB which I have passed
on to them. They have not commented or provided any work around) for
Windows platform.

So while loading the gnutls client script is loaded, the following
path is searched
1. gnutls\library
2. C:\windows
3. C:\WIndows\system
4. C:\WIndows\system32
5. Folder where pyhton.exe is present.

And when I use IIS, the PATH variable is also set. So in this case all
the folders in the PATH are also searched and LoadLibrary is able to
successfully find the GNUTLS related Dlls without any issues.

You were mentioning about .local file or manifest file to specify the
path. I used the python's build command to build the wrapper. Is there
a way to mention in setup.py to generate the .manifest file? I wold
very much appreciate if you can help me with that.

I will also look for answers for how to modify setup.py to generate
manifest file or .local file etc..

>
> > Can you explain maybe with some sample how to set .pth files? Maybe
> > this will resolve my issue.
>
> Yes, but I don't think this will actually help with your issue.
>
> pth files are described here [2]. Suppose you want to add c:\foo\bar to ?
> sys.path, then write a file whatever.pth containing this single line:
>
> c:\foo\bar
>
> and place it on c:\your_python_installation\lib\site-packages
> When the interpreter starts, it will find the .pth file, read it, and add ?
> any directory it finds (that actually exists) to sys.path
>
> Note that another Python installation will use a diferent site-packages ?
> directory and won't find this particular .pth file, so different Python ?
> versions don't interfere.
>
> ---
>
> [0]http://python.org/dev/peps/pep-0370/
> [1]http://msdn.microsoft.com/en-us/library/ms682586(VS.85).aspx
> [2]http://docs.python.org/library/site.html
>
> --
> Gabriel Genellina



From ebonak at hotmail.com  Mon Aug 10 10:52:35 2009
From: ebonak at hotmail.com (Esmail)
Date: Mon, 10 Aug 2009 10:52:35 -0400
Subject: compression level with tarfile (w:gz) ?
In-Reply-To: 
References: 		
	
Message-ID: 

Benjamin Kaplan wrote:
> 
>> I can't find tarfile.gzopen  in the tarfile docs, I'm looking here:
>>
>>    http://docs.python.org/library/tarfile.html
>>
>> Am I looking at the wrong page?
>>
> 
> My mistake. It isn't a function of the tarfile module, it's a class
> method of tarfile.TarFile. I was looking at the help in the
> interactive interpreter. It doesn't seem to be in the official docs,
> but you can use pydoc to view the docstrings.

Thanks for the additional information,

Esmail



From davea at ieee.org  Mon Aug 10 10:52:55 2009
From: davea at ieee.org (Dave Angel)
Date: Mon, 10 Aug 2009 10:52:55 -0400
Subject: Need help in configuration for TimedRotatingFileHandler
In-Reply-To: 
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>	<4A7F3C83.1040607@ieee.org>	
	
Message-ID: <4A803447.70607@ieee.org>

Lokesh Maremalla wrote:
> 
> Code:
> mlogger = logging.getLogger("simpleExample")
> def a_view(request):
>     mlogger.debug("a_view called")
>     if request.method== "POST" :
>         mlogger.debug("post function")
>     else:
>         mlogger.debug("serve function")
>
> Execution:
> step1: Executed the code and got the log file with the information
> step2: Modified the system time from current day to next day
> step3: End up with the error and the error is pasted below
>
> Traceback (most recent call last):
>   File "c:\Python25\lib\logging\handlers.py", line 74, in emit
>     self.doRollover()
>   File "c:\Python25\lib\logging\handlers.py", line 274, in doRollover
>     os.rename(self.baseFilename, dfn)
> WindowsError: [Error 32] The process cannot access the file because it is
> being used by another process
>
> Python version - 2.5.4
>
> I guess my output should be like this for the next day
> -a new log file rotate_test. should generate in the respective
> location
>
> Please correct me if I am wrong.
>
>
> Thanks for your time.
>
> Regards,
> Lokesh
>
>   
Generally speaking, this error on os.rename() will occur if you haven't 
properly closed the file first, and if I recall correctly, Unix would 
have permitted a rename on an open file.  You're on Windows.  However, I 
don't know how that works with the logging package.  If the program has 
terminated, and you run it a second time on the following day (or after 
changing the system time), then I'd expect no trouble.  But I'm guessing 
your program is still running, and you just want to change from logging 
to yesterday's file to logging to today's file.

If I had to guess, I'd say that you have two instances of the logger 
running, and the second one is still holding the handle open.  But 
that's just a wild guess.

Could someone else who is familiar with logging, and with 
TimedRotatingFileHandler in particular, jump in here?  Preferably a 
Windows person?

DaveA


From matt.urry at googlemail.com  Mon Aug 10 10:54:38 2009
From: matt.urry at googlemail.com (ma3mju)
Date: Mon, 10 Aug 2009 07:54:38 -0700 (PDT)
Subject: Processes not exiting
References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com>
	
	<61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com>
	<01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com> 
	
	 
	<996e50f5-c126-4ac2-ae8d-458d22a26ee1@v20g2000yqm.googlegroups.com> 
	<4b564f49-712c-408a-b8bd-9cff5af4a4fe@h30g2000vbr.googlegroups.com> 
	
Message-ID: <049e9160-5a92-47b9-9ac6-8e01573d5689@p15g2000vbl.googlegroups.com>

On 7 Aug, 16:02, MRAB  wrote:
> ma3mju wrote:
> > On 3 Aug, 09:36, ma3mju  wrote:
> >> On 2 Aug, 21:49, Piet van Oostrum  wrote:
>
> >>>>>>>> MRAB  (M) wrote:
> >>>> M> I wonder whether one of the workers is raising an exception, perhaps due
> >>>> M> to lack of memory, when there are large number of jobs to process.
> >>> But that wouldn't prevent the join. And you would probably get an
> >>> exception traceback printed.
> >>> I wonder if something fishy is happening in the multiprocessing
> >>> infrastructure. Or maybe the Fortran code goes wrong because it has no
> >>> protection against buffer overruns and similar problems, I think.
> >>> --
> >>> Piet van Oostrum 
> >>> URL:http://pietvanoostrum.com[PGP8DAE142BE17999C4]
> >>> Private email: p... at vanoostrum.org
> >> I don't think it's a memory problem, the reason for the hard and easy
> >> queue is because for larger examples it uses far more RAM. If I run
> >> all of workers with harder problems I do begin to run out of RAM and
> >> end up spending all my time switching in and out of swap so I limit
> >> the number of harder problems I run at the same time. I've watched it
> >> run to the end (a very boring couple of hours) and it stays out of my
> >> swap space and everything appears to be staying in RAM. Just hangs
> >> after all "poison" has been printed for each process.
>
> >> The other thing is that I get the message "here" telling me I broke
> >> out of the loop after seeing the poison pill in the process and I get
> >> all the things queued listed as output surely if I were to run out of
> >> memory I wouldn't expect all of the jobs to be listed as output.
>
> >> I have a serial script that works fine so I know individually for each
> >> example the fortran code works.
>
> >> Thanks
>
> >> Matt
>
> > Any ideas for a solution?
>
> A workaround is to do them in small batches.
>
> You could put each job in a queue with a flag to say whether it's hard
> or easy, then:
>
> ? ? ?while have more jobs:
> ? ? ? ? ?move up to BATCH_SIZE jobs into worker queues
> ? ? ? ? ?create and start workers
> ? ? ? ? ?wait for workers to finish
> ? ? ? ? ?discard workers

Yeah, I was hoping for something with a bit more finesse. In the end I
used pool instead with a callback function and that has solved the
problem. I did today find this snippet;

Joining processes that use queues

    Bear in mind that a process that has put items in a queue will
wait before terminating until all the buffered items are fed by the
?feeder? thread to the underlying pipe. (The child process can call
the Queue.cancel_join_thread() method of the queue to avoid this
behaviour.)

    This means that whenever you use a queue you need to make sure
that all items which have been put on the queue will eventually be
removed before the process is joined. Otherwise you cannot be sure
that processes which have put items on the queue will terminate.
Remember also that non-daemonic processes will be automatically be
joined.


I don't know (not a computer scientist) but could it have been the
pipe getting full?

In case anyway else is effected by this I've attached the new code to
see the changes I made to fix it.

Thanks for all your help

Matt

============================================================================================================================
parallel.py
============================================================================================================================
import GaussianProcessRegression as GP
import numpy as np
import networkx as nx
import pickle
from multiprocessing import Pool

global result

def cb(r):
    global result
    print r
    result[r[0]] = r[1]


############################################################################################
# Things You Can Change
############################################################################################
#savefiles
savefile = "powerlaw"
graphfile = "powerlawgraph"
#sample sizes
num_graphs = 5
num_sets_of_data = 10
#other things...
intervals = np.ceil(np.logspace(-2,1,50)*500)
noise = [np.sqrt(0.1),np.sqrt(0.01),np.sqrt(0.001),np.sqrt(0.0001)]
num_hard_workers = 5
hard_work_threshold = 4000
############################################################################################
#generate graphs
graphs  = []
for i in range(0,num_graphs):
    graphs.append(nx.powerlaw_cluster_graph(500,0.1,0.05))
#save them for later reference
filehandler = open(graphfile,'w')
pickle.dump(graphs,filehandler,-1)
filehandler.close()

#queues
easy_work = []
hard_work = []

#construct the items in the hard queue
l=0
for j in range(0,len(intervals)):
    for i in range(0,len(noise)):
        for k in range(0,num_graphs):
            if int(intervals[j]) <=hard_work_threshold:
                easy_work.append({'datapt': l,'graph': graphs
[k],'noise': noise[i],'number_of_sets_of_data':
num_sets_of_data,'number_of_data_points':int(intervals[j])})
            else:
                hard_work.append({'datapt': l,'graph': graphs
[k],'noise': noise[i],'number_of_sets_of_data':
num_sets_of_data,'number_of_data_points':int(intervals[j])})
            l+=1

result = np.zeros(l)

#create pool with all cores possible
worker_pool = Pool()

for i in xrange(0,len(easy_work)):
    worker_pool.apply_async(GP.RandomWalkGeneralizationErrorParallel,
(easy_work[i],),callback=cb)

worker_pool.close()
worker_pool.join()

#create hard work queue
worker_pool = Pool(processes = num_hard_workers)

for i in xrange(0,len(hard_work)):
    worker_pool.apply_async(GP.RandomWalkGeneralizationErrorParallel,
(hard_work[i],),callback=cb)

worker_pool.close()
worker_pool.join()


finaldata = result.reshape((len(intervals),len(noise),num_graphs))
np.save(savefile,finaldata)

================================================================================================================================================
GaussianProcessRegression.py
================================================================================================================================================
import CovarianceFunction as CF
import networkx as nx
import numpy as np
import scipy.linalg as sp
#fortran code from lapack-blas (hopefully when scipy updated this wont
be needed)
import dtrsv

#Currently we assume Gaussian noise TODO change to general noise
#Assume 0 mean TODO change to general mean Gaussian Process
class GaussianProcessRegression:
    def __init__(self,covariance_function,sigma):
        #a covariance function object defined in CovarianceFunction
class
        #note this uses the parent class but any children can be used
        self.C = covariance_function
        #a list of pts that are known and their values
        self.pts = []
        self.vals = []
        #the inverse of K as defined in
        #@book{coolen05:theoryofneural,
	    #ISBN = {0-19-853024-2},
	    #publisher = {Oxford University Press, USA},
	    #author = {Coolen, A. C. C. and K{\"{u}}hn, R. and Sollich, P.},
	    #title = {Theory of neural information processing systems},
	    #year = {2005},
        #}
        self.K = np.array([])
        #gaussian noise variable
        self.sigma = float(sigma)
        self.cholL = np.array([])


    def add_data_points(self,points,vals):
       #add all points to list
       self.pts += points
       self.vals += vals
       arraysize = len(self.pts)
       #construct K
       K = np.zeros((arraysize,arraysize))
       #for speed
       pts = self.pts
       between_points = self.C.between_points
       if len(self.K):
            K[:-1,:-1] = self.K
       for i in xrange(0,arraysize):
           for j in xrange(arraysize-len(points),arraysize):
                 K[i,j] = between_points(pts[i],pts[j])
                 K[j,i] = K[i,j]
       K[arraysize-len(points):arraysize,arraysize-len
(points):arraysize] =  K[arraysize-len(points):arraysize,arraysize-len
(points):arraysize] + self.sigma**2 * np.eye(len(points))
       self.K = K

    #calculate the prediction of a point based on data previously
given
    def point_prediction(self,points):
        mean = []
        variance =[]
        arraysize = len(self.pts)
        #cholesky
        #if self.cholL.shape[0] < arraysize:
        L=np.linalg.cholesky(self.K)
        #    self.cholL = L
        #else:
        #    L = self.cholL

        alpha = sp.cho_solve((L,1),self.vals)
        #create L in banded form
        k=np.zeros((arraysize,len(points)))
 
##################################################################
        #for speed get ref to functions im going to use and save them
        between_points = self.C.between_points
        pts = self.pts
        dot = np.dot
 
##################################################################
        for j in xrange(0,len(points)):
            #create k
            for i in xrange(0,arraysize):
                k[i,j] = between_points(pts[i],points[j])

        #calculate mean and variance
        #call the command for forward substitution
        ###############fortran
call#######################################
        v = dtrsv.dtrsv('L','N',arraysize,L,k)
 
##################################################################

        #result
        mean=dot(alpha,k)
        for i in xrange(0,len(points)):
            variance.append(between_points(points[i],points[i]) - dot(v
[:,i],v[:,i]))
        #return it in dictionary form
        return {'mean':mean,'variance':variance}


    # calculate the error for data given, where function is a vector
    # of the function evaluated at a sufficiently large number of
points
    # that the GPregression has been trying to learn
    def error(self,function):
        total = 0
        #sum up variances
        result = self.point_prediction(function[::2])
        total = np.sum(result['variance'])
        total = (1/float(len(function)/2))*total
        return total

    #clear what has been learnt so far
    def clear(self):
        self.pts = []
        self.vals = []
        self.K = np.array([])

    #calculate the average error for a function defined in function
when give
    #number_of_examples examples
    def average_error_over_samples(self,function, sample_size,
number_of_examples):
        avg = 0
        numberofpoints = len(function)/2
        for i in range(0,sample_size):
            self.clear()
            #generate points of the function
            permpts = np.random.randint
(0,numberofpoints,number_of_examples)
            #create the vectors
            pts = []
            vals = []
            for j in range(0,number_of_examples):
                pts.append(function[permpts[j]*2])
                vals.append(function[permpts[j]*2+1])

            #learn these points
            self.add_data_points(pts,vals)
            #print("points added")
            avg = avg + self.error(function)
        avg = avg/sample_size
        return avg





From jura.grozni at gmail.com  Mon Aug 10 10:55:42 2009
From: jura.grozni at gmail.com (azrael)
Date: Mon, 10 Aug 2009 07:55:42 -0700 (PDT)
Subject: wxpython question
Message-ID: <11f24035-bd42-4df8-879a-2e2558ee45ee@d23g2000vbm.googlegroups.com>

Is there maybe a method bounded to the class SpinCtrl() that could
hide the widget. One that is maybe also implemented in any other
control.

self.spcKvadDo = wx.SpinCtrl(id=-1, initial=0, max=1000000, min=0,
name='spcKvadDo', parent=self.pnlFilteri, pos=wx.Point(10, 10),
size=wx.Size(118, 21), style=wx.SP_ARROW_KEYS)

self.spcKvadOd.XXX()

I tried it with the SetTransparent() method but it did not work. Has
anyone any Idea?


From ebonak at hotmail.com  Mon Aug 10 10:55:42 2009
From: ebonak at hotmail.com (Esmail)
Date: Mon, 10 Aug 2009 10:55:42 -0400
Subject: compression level with tarfile (w:gz) ?
In-Reply-To: <20090810134108.GA7790@axis.g33x.de>
References:  <20090810134108.GA7790@axis.g33x.de>
Message-ID: 

Hi Lars,

Lars Gust?bel wrote:
> 
> How much smaller is it? I did a test with a recent Linux kernel source tree
> which made an archive of 337MB. Command-line gzip was ahead of Python's
> GzipFile() by just 20200 bytes(!) with an archive of about 74MB.
> 
>> Is the only way to accomplish the higher rate to create a tar file
>> and then use a different module to gzip it (assuming I can specify
>> the compression level there)?
> 
> If you need the disk space that badly, the alternative would be to pipe
> tarfile's output to command-line gzip somehow:

Thanks for the additional info and the workaround. I was mostly just
curious if there was a way to specify the compression level, so far
I'm ok with the generated file sizes, but it's good to know that there
are other options to specify my own compression level.

Thanks again,

Esmail



From zuo at chopin.edu.pl  Mon Aug 10 10:55:51 2009
From: zuo at chopin.edu.pl (Jan Kaliszewski)
Date: Mon, 10 Aug 2009 16:55:51 +0200
Subject: With or without leading underscore...
In-Reply-To: <5un5l6-fvn.ln1@satorlaser.homedns.org>
References: <5un5l6-fvn.ln1@satorlaser.homedns.org>
Message-ID: 

10-08-2009 Ulrich Eckhardt  wrote:

> So, the type is a part of the public API, but its constructor is not.  
> Should
> I mark the type as private (with a leading underscore) or not?

IMHO you shouldn't (i.e. name should be marked "public") because of
possible usage of e.g. "isinstance(foo, YourType)".

Cheers,
*j

-- 
Jan Kaliszewski (zuo) 


From lutz at rmi.net  Mon Aug 10 10:58:11 2009
From: lutz at rmi.net (Mark Lutz)
Date: Mon, 10 Aug 2009 07:58:11 -0700 (PDT)
Subject: Florida Python training in October
Message-ID: 

We're pleased to announce a new venue for our Python classes.
Python author and trainer Mark Lutz will be teaching a 3-day
Python class on October 20-22, in Sarasota, Florida.  Come
spend 3 days mastering Python, and enjoy all that Florida and
its Gulf Coast have to offer while you're here.

This is a public training session open to individual enrollments,
and covers the same topics and hands-on lab work as the over 200
onsite sessions that Mark has taught.  The class provides an
in-depth introduction to both Python and its common applications,
and parallels the instructor's best-selling Python books.

This class is also newly retooled to cover recent changes in
both Python 2.6 and 3.1.  Whether you're using 2.X, using 3.X,
or stuck somewhere between them, you'll find that our class is
aimed at your needs.  For more information on this session,
please visit its web page:

http://home.earthlink.net/~python-training/2009-public-classes.htm

For additional background on the class itself, as well as a
preview of our 2010 Florida class schedule, see our home page:

http://home.earthlink.net/~python-training

Thanks for your interest,
--Mark Lutz's Python Training Services


From Scott.Daniels at Acm.Org  Mon Aug 10 10:58:47 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Mon, 10 Aug 2009 07:58:47 -0700
Subject: Unrecognized escape sequences in string literals
In-Reply-To: 
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
	
Message-ID: 

Douglas Alan wrote:
> So, what's the one obvious right way to express "foo\zbar"? Is it
>    "foo\zbar"
> or
>    "foo\\zbar"
> And if it's the latter, what possible benefit is there in allowing the
> former?  And if it's the former, why does Python echo the latter?

Actually, if we were designing from fresh (with no C behind us), I might
advocate for "\s" to be the escape sequence for a backslash.  I don't
particularly like that it is hard to see if the following string
contains a tab:   "abc\\\\\\\\\table".  The string rules reflect C's
rules, and I see little excuse for trying to change them now.

--Scott David Daniels
Scott.Daniels at Acm.Org


From piet at cs.uu.nl  Mon Aug 10 11:00:34 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Mon, 10 Aug 2009 17:00:34 +0200
Subject: reloading the module imported as 'from ... import ...'
References: <4A7F976D.7090600@ggmail.com>
	
	<4A7FB4AF.7060107@ggmail.com>
	
Message-ID: 

>>>>> Steven D'Aprano  (SD) wrote:

>SD> On Sun, 09 Aug 2009 22:48:31 -0700, AlF wrote:
>>> Steven D'Aprano wrote:
>>>> On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:
>>>> 
>>>>> Hi,
>>>>> 
>>>>> what is the best way to reload the module imported using 'from ...
>>>>> import ...'
>>>> 
>>>> 
>>>> Have you tried "from ... import ..." again?
>>>> 
>>>> 
>>> I have not because of an assumption that "import" imports the module
>>> just once. 

>SD> Ah, of course the cached module will still reflect the older version. 
>SD> Sorry, I was thinking about solving a different problem:

If you do a reload in between the cached version is replaced by the new
version. However, objects from the old module that have references
before the reload will still lie around. This could cause very subtle
bugs.

Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) 
[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import testmod
>>> from testmod import TestClass
>>> a = TestClass()
>>> b = TestClass()
>>> a.__class__ is b.__class__
True
>>> reload(testmod)

>>> c = TestClass()
>>> c.__class__ is a.__class__
True
>>> from testmod import TestClass
>>> d = TestClass()
>>> d.__class__ is a.__class__
False

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From cornelius.keller at googlemail.com  Mon Aug 10 11:07:28 2009
From: cornelius.keller at googlemail.com (Cornelius Keller)
Date: Mon, 10 Aug 2009 08:07:28 -0700 (PDT)
Subject: variable & scoping question.
Message-ID: 

Hi,

I'm a quite fresh python programmer, (6 Month python experience).
Today I found something I absolotly don'nt understand:

given the following function:

def test_effect(class_id=None,class_ids=[]):
    if class_id is not None:
        if class_id not in class_ids:
            class_ids.append(int(class_id))

    print class_ids

I observe that the class_ids array is growing when it is called with
different class id's.

I expected class_ids to be [] if the keyword argument is not set, but
it seems to beahve like a static variable if not set.

example:


In [3]: test.test_effect(class_id=1)
[1]

In [4]: test.test_effect(class_id=1)
[1]

In [5]: test.test_effect(class_id=2)
[1, 2]

In [6]: test.test_effect(class_id=2)
[1, 2]

In [7]: test.test_effect(class_id=3)
[1, 2, 3]

Is this an intended python beahviour?

sincerly
- Cornelius






From deets at nospam.web.de  Mon Aug 10 11:12:29 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Mon, 10 Aug 2009 17:12:29 +0200
Subject: variable & scoping question.
References: 
Message-ID: <7earmtF2f4tvnU1@mid.uni-berlin.de>

Cornelius Keller wrote:

> Hi,
> 
> I'm a quite fresh python programmer, (6 Month python experience).
> Today I found something I absolotly don'nt understand:
> 
> given the following function:
> 
> def test_effect(class_id=None,class_ids=[]):
> ? ? if class_id is not None:
> ? ? ? ? if class_id not in class_ids:
> ? ? ? ? ? ? class_ids.append(int(class_id))
> 
> ? ? print class_ids
> 
> I observe that the class_ids array is growing when it is called with
> different class id's.
> 
> I expected class_ids to be [] if the keyword argument is not set, but
> it seems to beahve like a static variable if not set.

http://effbot.org/zone/default-values.htm

Diez


From rt8396 at gmail.com  Mon Aug 10 11:13:05 2009
From: rt8396 at gmail.com (r)
Date: Mon, 10 Aug 2009 08:13:05 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
Message-ID: <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>

On Aug 9, 11:02?pm, David Lyon  wrote:
> Since you're talking about documentation, which is a part of python,
> don't you think you should be discussing it on python-dev ?

Yea, them's be a friendly bunch to noob ideas ;). Hey i got a better
idea, lets go to the IRS and see if we can persuade them to stop
taxing us...

> That's where discussions about the documentation should be held.
> haha - I'm just curious to see how long it will for them to
> shut the discussion down.

Yea, probably not long at all, of course not before the troll calling,
bulling, defamation of character, etc, has lost it's fun.

> Before you do that, you should clearly work out in your own mind
> how you think things need to improve. It's not good enough just
> saying this or that is bad without having specific ideas on what
> needs to change.

see links that xah posted, and there is more he did not post.

> Good luck fellow sinner and blasphemer...
> How dare you suggest that things could be improved...

how dare YOU suggest they NOT be improved!!!


From darkwater42 at gmail.com  Mon Aug 10 11:21:03 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Mon, 10 Aug 2009 08:21:03 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
	
	
Message-ID: <86e09602-7eb1-4397-a77f-fb1e3c5b34b9@k26g2000vbp.googlegroups.com>

On Aug 10, 10:58?am, Scott David Daniels 
wrote:

>?The string rules reflect C's rules, and I see little
> excuse for trying to change them now.

No they don't. Or at least not C++'s rules. C++ behaves exactly as I
should like.

(Or at least g++ does. Or rather *almost* as I would like, as by
default it generates a warning for "foo\zbar", while I think that an
error would be somewhat preferable.)

But you're right, it's too late to change this now.

|>ouglas



From samwyse at gmail.com  Mon Aug 10 11:21:49 2009
From: samwyse at gmail.com (samwyse)
Date: Mon, 10 Aug 2009 08:21:49 -0700 (PDT)
Subject: setting Referer for urllib.urlretrieve
References: <1668f798-0a73-47a5-9f87-34312109c67c@v2g2000vbb.googlegroups.com>
	<028ed082$0$20617$c3e8da3@news.astraweb.com>
Message-ID: <73d9e384-30a0-4927-ac73-722d11c06d15@g6g2000vbr.googlegroups.com>

On Aug 9, 9:41?am, Steven D'Aprano  wrote:
> On Sun, 09 Aug 2009 06:13:38 -0700,samwysewrote:
> > Here's what I have so far:
>
> > import urllib
>
> > class AppURLopener(urllib.FancyURLopener):
> > ? ? version = "App/1.7"
> > ? ? referrer = None
> > ? ? def __init__(self, *args):
> > ? ? ? ? urllib.FancyURLopener.__init__(self, *args)
> > ? ? ? ? if self.referrer:
> > ? ? ? ? ? ? addheader('Referer', self.referrer)
>
> > urllib._urlopener = AppURLopener()
>
> > Unfortunately, the 'Referer' header potentially varies for each url that
> > I retrieve, and the way the module is written, I can't change the calls
> > to __init__ or open. The best idea I've had is to assign a new value to
> > my class variable just before calling urllib.urlretrieve(), but that
> > just seems ugly. ?Any ideas? ?Thanks.
>
> [Aside: an int variable is an int. A str variable is a str. A list
> variable is a list. A class variable is a class. You probably mean a
> class attribute, not a variable. If other languages want to call it a
> variable, or a sausage, that's their problem.]
>
> If you're prepared for a bit of extra work, you could take over all the
> URL handling instead of relying on automatic openers. This will give you
> much finer control, but it will also require more effort on your part.
> The basic idea is, instead of installing openers, and then ask the urllib
> module to handle the connection, you handle the connection yourself:
>
> make a Request object using urllib2.Request
> make an Opener object using urllib2.build_opener
> call opener.open(request) to connect to the server
> deal with the connection (retry, fail or read)
>
> Essentially, you use the Request object instead of a URL, and you would
> add the appropriate referer header to the Request object.
>
> Another approach, perhaps a more minimal change than the above, would be
> something like this:
>
> # untested
> class AppURLopener(urllib.FancyURLopener):
> ? ? version = "App/1.7"
> ? ? def __init__(self, *args):
> ? ? ? ? urllib.FancyURLopener.__init__(self, *args)
> ? ? def add_referrer(self, url=None):
> ? ? ? ? if url:
> ? ? ? ? ? ? addheader('Referer', url)
>
> urllib._urlopener = AppURLopener()
> urllib._urlopener.add_referrer("http://example.com/")

Thanks for the ideas.  I'd briefly considered something similar to
your first idea, implementing my own version of urlretrieve to accept
a Request object, but it does seem like a good bit of work.  Maybe
over Labor Day.  :)

The second idea is pretty much what I'm going to go with for now.  The
program that I'm writing is almost a clone of wget, but it fixes some
personal dislikes with the way recursive retrievals are done.  (Or
maybe I just don't understand wget's full array of options well
enough.)  This means that my referrer changes as I bounce up and down
the hierarchy, which makes this less convenient.  Still, it does seem
more convenient that re-writing the module from scratch.


From python at mrabarnett.plus.com  Mon Aug 10 11:25:20 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Mon, 10 Aug 2009 16:25:20 +0100
Subject: Processes not exiting
In-Reply-To: <049e9160-5a92-47b9-9ac6-8e01573d5689@p15g2000vbl.googlegroups.com>
References: <6cfb2f39-c6d6-4d2a-882c-18f21addf206@a13g2000yqc.googlegroups.com>		<61d7fcbb-17f8-4314-90b6-0a6db22abd6d@w41g2000yqb.googlegroups.com>	<01b55c48-3252-4cec-8781-98487a9071ae@b15g2000yqd.googlegroups.com>
		
	<996e50f5-c126-4ac2-ae8d-458d22a26ee1@v20g2000yqm.googlegroups.com>
	<4b564f49-712c-408a-b8bd-9cff5af4a4fe@h30g2000vbr.googlegroups.com>
	
	<049e9160-5a92-47b9-9ac6-8e01573d5689@p15g2000vbl.googlegroups.com>
Message-ID: <4A803BE0.3090902@mrabarnett.plus.com>

ma3mju wrote:
> On 7 Aug, 16:02, MRAB  wrote:
>> ma3mju wrote:
>>> On 3 Aug, 09:36, ma3mju  wrote:
>>>> On 2 Aug, 21:49, Piet van Oostrum  wrote:
>>>>>>>>>> MRAB  (M) wrote:
>>>>>> M> I wonder whether one of the workers is raising an exception, perhaps due
>>>>>> M> to lack of memory, when there are large number of jobs to process.
>>>>> But that wouldn't prevent the join. And you would probably get an
>>>>> exception traceback printed.
>>>>> I wonder if something fishy is happening in the multiprocessing
>>>>> infrastructure. Or maybe the Fortran code goes wrong because it has no
>>>>> protection against buffer overruns and similar problems, I think.
>>>>> --
>>>>> Piet van Oostrum 
>>>>> URL:http://pietvanoostrum.com[PGP8DAE142BE17999C4]
>>>>> Private email: p... at vanoostrum.org
>>>> I don't think it's a memory problem, the reason for the hard and easy
>>>> queue is because for larger examples it uses far more RAM. If I run
>>>> all of workers with harder problems I do begin to run out of RAM and
>>>> end up spending all my time switching in and out of swap so I limit
>>>> the number of harder problems I run at the same time. I've watched it
>>>> run to the end (a very boring couple of hours) and it stays out of my
>>>> swap space and everything appears to be staying in RAM. Just hangs
>>>> after all "poison" has been printed for each process.
>>>> The other thing is that I get the message "here" telling me I broke
>>>> out of the loop after seeing the poison pill in the process and I get
>>>> all the things queued listed as output surely if I were to run out of
>>>> memory I wouldn't expect all of the jobs to be listed as output.
>>>> I have a serial script that works fine so I know individually for each
>>>> example the fortran code works.
>>>> Thanks
>>>> Matt
>>> Any ideas for a solution?
>> A workaround is to do them in small batches.
>>
>> You could put each job in a queue with a flag to say whether it's hard
>> or easy, then:
>>
>>      while have more jobs:
>>          move up to BATCH_SIZE jobs into worker queues
>>          create and start workers
>>          wait for workers to finish
>>          discard workers
> 
> Yeah, I was hoping for something with a bit more finesse. In the end I
> used pool instead with a callback function and that has solved the
> problem. I did today find this snippet;
> 
> Joining processes that use queues
> 
>     Bear in mind that a process that has put items in a queue will
> wait before terminating until all the buffered items are fed by the
> ?feeder? thread to the underlying pipe. (The child process can call
> the Queue.cancel_join_thread() method of the queue to avoid this
> behaviour.)
> 
>     This means that whenever you use a queue you need to make sure
> that all items which have been put on the queue will eventually be
> removed before the process is joined. Otherwise you cannot be sure
> that processes which have put items on the queue will terminate.
> Remember also that non-daemonic processes will be automatically be
> joined.
> 
> 
> I don't know (not a computer scientist) but could it have been the
> pipe getting full?
> 
> In case anyway else is effected by this I've attached the new code to
> see the changes I made to fix it.
> 
[snip]
Maybe the reason is this:

Threads share an address space, so putting data into a queue simply
involves putting a reference there, but processes don't share an address
space, so a sender must continue to exist until the data itself has been
copied into the pipe that connects the processes. This pipe has a
limited capacity.

In your code you were waiting for the easy workers to terminate and you
weren't reading from the queue, and maybe, therefore, the pipe either,
so with a large number of jobs the pipe was becoming full.

In summary: the worker didn't terminate because the pipe was full; the
pipe was full because you weren't reading the results; you weren't
reading the results because the worker hadn't terminated.


From bieffe62 at gmail.com  Mon Aug 10 11:36:52 2009
From: bieffe62 at gmail.com (Francesco Bochicchio)
Date: Mon, 10 Aug 2009 08:36:52 -0700 (PDT)
Subject: variable & scoping question.
References: 
	<7earmtF2f4tvnU1@mid.uni-berlin.de>
Message-ID: 

On Aug 10, 5:12?pm, "Diez B. Roggisch"  wrote:
> Cornelius Keller wrote:
> > Hi,
>
> > I'm a quite fresh python programmer, (6 Month python experience).
> > Today I found something I absolotly don'nt understand:
>
> > given the following function:
>
> > def test_effect(class_id=None,class_ids=[]):
> > ? ? if class_id is not None:
> > ? ? ? ? if class_id not in class_ids:
> > ? ? ? ? ? ? class_ids.append(int(class_id))
>
> > ? ? print class_ids
>
> > I observe that the class_ids array is growing when it is called with
> > different class id's.
>
> > I expected class_ids to be [] if the keyword argument is not set, but
> > it seems to beahve like a static variable if not set.
>
> http://effbot.org/zone/default-values.htm
>
> Diez

Maybe on the first page of python.org there should be a 'python
gotchas' link to a page listing these few
non-intuituive peculiarities of our beloved snake ... same goes for
the official python tutorial ...

Ciao
-----
FB



From cornelius.keller at googlemail.com  Mon Aug 10 11:46:17 2009
From: cornelius.keller at googlemail.com (Cornelius Keller)
Date: Mon, 10 Aug 2009 08:46:17 -0700 (PDT)
Subject: variable & scoping question.
References: 
	<7earmtF2f4tvnU1@mid.uni-berlin.de>
Message-ID: <93c50fc3-2cf9-4fc6-9919-cde7cfd273e6@o35g2000vbi.googlegroups.com>

On 10 Aug., 17:12, "Diez B. Roggisch"  wrote:
> Cornelius Keller wrote:
[snip]
>
> http://effbot.org/zone/default-values.htm
>
> Diez

Ok thank you.
I' understand now why.
I still think this is very confusing, because default values don't
behave like most people would expect without reading the docs.

- Cornelius


From MatzeGuentert at gmx.de  Mon Aug 10 11:55:06 2009
From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=)
Date: Mon, 10 Aug 2009 17:55:06 +0200
Subject: M2Crypto: How to generate subjectKeyIdentifier /
	authorityKeyIdentifier
In-Reply-To: 
References: 
	
	
	
Message-ID: <1249919706.3267.239.camel@celsius>

Now I have this patch applied to the M2Crypto SVN branch 




From piet at cs.uu.nl  Mon Aug 10 11:58:27 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Mon, 10 Aug 2009 17:58:27 +0200
Subject: Problem Regarding Handling of Unicode string
References: <9ac0e194-9e25-468a-9807-957ef3142dd3@i18g2000pro.googlegroups.com>
Message-ID: 

>>>>> joy99  (j) wrote:

>j> Dear Group,
>j> I am using Python26 on WindowsXP with service pack2. My GUI is IDLE.
>j> I am using Hindi resources and get nice output like:
>j> ??
>j> where I can use all the re functions and other functions without doing
>j> any transliteration,etc.
>j> I was trying to use Bengali but it is giving me output like:
>j> '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95'
>j> I wanted to see Bengali output as
>j> ????
>j> and I like to use all functions including re.
>j> If any one can help me on that.
>j> Best Regards,
>j> Subhabrata.

Make sure your stdout (in case you use print) has utf-8 encoding. This
might be problematic on Windows, however.

>>> print '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95'
????

Or if you write to a file, open it with utf-8 encoding.

I take utf-8 because in general this is the preferred encoding for
non-ASCII text. It could be that Bengali has a different preferred encoding.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From davea at ieee.org  Mon Aug 10 12:03:19 2009
From: davea at ieee.org (Dave Angel)
Date: Mon, 10 Aug 2009 12:03:19 -0400
Subject: Client/Server based on SocketServer and Windows
In-Reply-To: <979ad93c-0257-4add-8fb7-b56e253e3fb7@h30g2000vbr.googlegroups.com>
References: 	
	<979ad93c-0257-4add-8fb7-b56e253e3fb7@h30g2000vbr.googlegroups.com>
Message-ID: <4A8044C7.1080203@ieee.org>

Kiki wrote:
> Thank you Dennis
>
> I'm using 2 differents editor, which may be the cause of such a mess
> in the indentation.
>
> I must admitt that I lazily rely on those (not so bad indeed) editors.
>
> "If indentation whas bad they would have tell me"
>
> Too bad am i
>
> Won't post misindeted code anymore.
>
>   
No problem using multiple editors.  But you need to configure each one 
to *never* put tabs in the file (it should use spaces exclusively).  If 
you can't do that in one of the editors, then use the other editor 
exclusively.

Other useful but not mandatory features -
    - when tab is pressed, it should indent using spaces, to a multiple 
of 4 columns.
    - by default, indent a new line the same as the previous, or even 
based on the previous plus some syntax rules.
    - make tabs and/or spaces visible, so you can tell if the file has a 
mixture.

DaveA
  


From rt8396 at gmail.com  Mon Aug 10 12:09:17 2009
From: rt8396 at gmail.com (r)
Date: Mon, 10 Aug 2009 09:09:17 -0700 (PDT)
Subject: www.python.org website is down?
References: 
	
	<1d952f0b-9552-48ef-ad2e-a7b8e06ea8eb@n2g2000vba.googlegroups.com>
	
Message-ID: <6f54e63f-9f98-46a6-aff2-7b93a78b683b@e18g2000vbe.googlegroups.com>

On Aug 10, 9:13?am, MRAB  wrote:
> r wrote:
> > On Aug 8, 8:48 am, MRAB  wrote:
> > ...(snip)
> >> Bothwww.python.organdsvn.python.org are down. ?They're hosted on
> >> the same machine, and it seems to have run into disk problems and
> >> hasn't rebooted even after power-cycling. ?Thomas Wouters will be
> >> visiting the machine physically tomorrow to try to diagnose the
> >> problem.
>
> > Oh stop lying MRAB, everybody knows Guido hosts Python.org from his
> > attic on an old Linux box :-)
>
> That was a quote from A.M. Kuchling.
>
> It's actually hosted on a matchbox-sized multi-core multi-terabyte
> wifi-enabled Linux machine that Guido brought back from 2050.
> Unfortunately, the dog ate it, so he's had to go and buy another one!
> :-)

i just hope he gets one that has supported wifi drivers available! :-)


From ethan at stoneleaf.us  Mon Aug 10 12:13:34 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Mon, 10 Aug 2009 09:13:34 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>		<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>			<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
Message-ID: <4A80472E.4090108@stoneleaf.us>

Kee Nethery wrote:
> As someone trying to learn the language I want to say that the tone on  
> this list towards people who are trying to learn Python  feels like it  
> has become anti-newbies.
> 
> Learning a new language is difficult enough without seeing other  
> newbies getting shamed for not knowing everything there is to know  
> about Python before asking their questions.
> 
> For example, the guy who was looking for Python sample code for the  
> Google Map API, calling him a troll was harsh. Suggesting he broach  the 
> question to Google was a reasonable answer. By the same token, his  
> asking this list about the missing Python examples seems reasonable  
> also. Seems to me that people on a Python list might have some  
> background knowledge or even samples of the Google Python code that  was 
> no longer on the Google web site.
> 
> There seems to be a general consensus among the newbies that other  
> languages have a user contributions resource tied to the main official  
> docs to allow newbies to teach each other what they have learned. The  
> desire is for python.org to have the same kind of support resource so  
> that us newbies can self support each other.
> 
> Kee Nethery

As someone who is (hopefully!) leaving newbieness I can say I have had 
no problem with the helpfullness of this list.  I will also say that 
before I ever posted any questions I had devoured Dive Into Python and 
How To Think Like a Computer Scientist Using Python (both excellent), 
and I try to put as much detail into my questions as I can so nobody has 
to guess what I'm trying to do.

As someone who relies heavily on the docs I will also say that the idea 
of giving the ability to modify the official documentation to somebody 
who is /learning/ the language is, quite frankly, terrifying.  I have no 
issues with a seperate system, some of which have been suggested, but 
good reference documentation is crucial.  If you find examples lacking, 
there are plenty of web-sites, or even (dare I say it?) actual hard-copy 
books!  ;)  My bookshelf currently has Learning Python, Programming 
Python, Python Cookbook, Python Programming on Win32, and Regular 
Expressions.  All great books, and not too pricey if you can get them used.

My $0.02.

~Ethan~


From dorzey at googlemail.com  Mon Aug 10 12:15:07 2009
From: dorzey at googlemail.com (dorzey)
Date: Mon, 10 Aug 2009 09:15:07 -0700 (PDT)
Subject: Problem when fetching page using urllib2.urlopen
References: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>
	<0579ebc0-2542-4f96-af3e-9861ad646b13@d9g2000prh.googlegroups.com>
Message-ID: 

"geturl - this returns the real URL of the page fetched. This is
useful because urlopen (or the opener object used) may have followed a
redirect. The URL of the page fetched may not be the same as the URL
requested." from http://www.voidspace.org.uk/python/articles/urllib2.shtml#info-and-geturl

It might be worth checking that you are actually getting the page you
want; I seem to remember that semicolons need to be encoded, similar
to '&'.

Dorzey

On Aug 10, 12:43?pm, jitu  wrote:
> On Aug 10, 4:39?pm, jitu  wrote:
>
> > Hi,
>
> > A html page ?contains 'anchor' elements with 'href' attribute ?having
> > a semicolon ?in the url , while fetching the page using
> > urllib2.urlopen, all such href's ?containing ?'semicolons' are
> > truncated.
>
> > For example the hrefhttp://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt...
> > get truncated tohttp://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i
>
> > The page I am talking about can be fetched fromhttp://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_...
>
> > Thanks a Lot
> > Regards
> > jitu
>
> Hi
>
> ? ?Sorry, the question what I wanted to ask was, whether is this the
> correct behaviour or a bug ?
>
> Thanks A Lot.
> Regards
> jitu



From MatzeGuentert at gmx.de  Mon Aug 10 12:19:17 2009
From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=)
Date: Mon, 10 Aug 2009 16:19:17 +0000
Subject: M2Crypto: How to generate subjectKeyIdentifier /
	authorityKeyIdentifier
In-Reply-To: 
References: 
	
	
	
Message-ID: <1249921157.3267.263.camel@celsius>

Hello once again

Now I have the extension-patch [0] applied to the M2Crypto SVN branch
(revision 704). Creating a root and an subRoot CA certificate now works
great including the SKID/AKID extensions. 

I am also able to verify those created certificates using:

$ openssl verify -CAfile rootCA.crt rootCA.crt 
rootCA.crt: OK

$ openssl verify -CAfile rootCA.crt subRootCA.crt 
subRootCA.crt: OK

But having a closer look onto the generated key ID's shows that there is
either something wrong in the way I am adding the subjectKeyIdentifier
extension or the way the hash gets calculated in the background. 

This are the hashes:

__rootCA__			
SKID F4:EF:64:5F:7A:A2:2A:14:14:F9:AE:6E:DB:04:78:0A:8C:6E:02:9F -: A
--> OKAY
AKID F4:EF:64:5F:7A:A2:2A:14:14:F9:AE:6E:DB:04:78:0A:8C:6E:02:9F -: A
--> OKAY

__subRootCA (signed by rootCA)__ 	
SKID DA:39:A3:EE:5E:6B:4B:0D:32:55:BF:EF:95:60:18:90:AF:D8:07:09 -: B
--> OKAY
AKID F4:EF:64:5F:7A:A2:2A:14:14:F9:AE:6E:DB:04:78:0A:8C:6E:02:9F -: A
--> OKAY

__client (signed by rootCA)__
SKID DA:39:A3:EE:5E:6B:4B:0D:32:55:BF:EF:95:60:18:90:AF:D8:07:09 -: B
--> NOT OKAY, should be different from RootCA
AKID F4:EF:64:5F:7A:A2:2A:14:14:F9:AE:6E:DB:04:78:0A:8C:6E:02:9F -: A
--> OKAY

__client (signed by subRootCA)__
SKID DA:39:A3:EE:5E:6B:4B:0D:32:55:BF:EF:95:60:18:90:AF:D8:07:09 -: B
--> NOT OKAY, should be different from subRootCA
AKID DA:39:A3:EE:5E:6B:4B:0D:32:55:BF:EF:95:60:18:90:AF:D8:07:09 -: B
--> OKAY

I really would be happy if someone could have a look at my code [1] as
this extensions are important for verifying the trust chain. Please let
me know if there is anything I can do with my limited knowledge about
OpenSSL to get this working... 

Regards, Matthias 

[0] https://bugzilla.osafoundation.org/attachment.cgi?id=5106
[1] http://code.google.com/p/webca/source/browse/trunk/src/ca.py




From gert.cuykens at gmail.com  Mon Aug 10 12:41:19 2009
From: gert.cuykens at gmail.com (gert)
Date: Mon, 10 Aug 2009 09:41:19 -0700 (PDT)
Subject: resume upload wsgi script
References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com>
	<7e80jlF2etv0kU1@mid.uni-berlin.de>
	
	<7e85i3F2fdc1eU1@mid.uni-berlin.de>
	<9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com>
	<7e8ildF2f1hcpU1@mid.uni-berlin.de>
	<49e41062-9e0d-4c5e-beca-edb02d3ce6e8@e34g2000vbm.googlegroups.com>
	<7ea4lpF2dvr5cU1@mid.uni-berlin.de>
Message-ID: 

On Aug 10, 10:39?am, "Diez B. Roggisch"  wrote:
> > 250KB :)
>
> So why do you bother?
>
> > Its just HTTP1.1 has everything for making ftp like file transfers
> > possible.
> > When I write it to a file then I am back at square one because I still
> > need to load it completely to get it into a blob.
>
> Well, the blob is nothing but datat in the file-system. If you are
> *really* concerned about that, then don't use the db, but use the
> filesystem, appending to the file until it's finished - and storing a
> reference to it to the DB. We do that as well, because otherwise the db
> will become unmanagable anyway (dumping, backups).
>

I also hate debugging sql that contains blob data. So if using files
how do you clean the http post stuff?
(b+r'.*?Content-Type: application/octet-stream\r\n\r\n(.*?)\r
\n--'+b,file,DOTALL)
using as litlle memory as possible ?
I can not use PUT upload only because flash does not support PUT.


From python at mrabarnett.plus.com  Mon Aug 10 12:42:50 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Mon, 10 Aug 2009 17:42:50 +0100
Subject: variable & scoping question.
In-Reply-To: 
References: 	<7earmtF2f4tvnU1@mid.uni-berlin.de>
	
Message-ID: <4A804E0A.2090202@mrabarnett.plus.com>

Francesco Bochicchio wrote:
> On Aug 10, 5:12 pm, "Diez B. Roggisch"  wrote:
>> Cornelius Keller wrote:
>>> Hi,
>>> I'm a quite fresh python programmer, (6 Month python experience).
>>> Today I found something I absolotly don'nt understand:
>>> given the following function:
>>> def test_effect(class_id=None,class_ids=[]):
>>>     if class_id is not None:
>>>         if class_id not in class_ids:
>>>             class_ids.append(int(class_id))
>>>     print class_ids
>>> I observe that the class_ids array is growing when it is called with
>>> different class id's.
>>> I expected class_ids to be [] if the keyword argument is not set, but
>>> it seems to beahve like a static variable if not set.
>> http://effbot.org/zone/default-values.htm
>>
>> Diez
> 
> Maybe on the first page of python.org there should be a 'python
> gotchas' link to a page listing these few
> non-intuituive peculiarities of our beloved snake ... same goes for
> the official python tutorial ...
> 
Should they be called 'snake bites'? Well, pythons are constrictors, not
biters, but if Python is being non-intuitive... :-)


From ethan at stoneleaf.us  Mon Aug 10 12:55:46 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Mon, 10 Aug 2009 09:55:46 -0700
Subject: variable & scoping question.
In-Reply-To: <93c50fc3-2cf9-4fc6-9919-cde7cfd273e6@o35g2000vbi.googlegroups.com>
References: 	<7earmtF2f4tvnU1@mid.uni-berlin.de>
	<93c50fc3-2cf9-4fc6-9919-cde7cfd273e6@o35g2000vbi.googlegroups.com>
Message-ID: <4A805112.8020308@stoneleaf.us>

Cornelius Keller wrote:
[snip]

> I still think this is very confusing, because default values don't
> behave like most people would expect without reading the docs.
> 
> - Cornelius

Why would you expect to become a good programmer of _any_ language 
without reading its docs?

~Ethan~


From deets at nospam.web.de  Mon Aug 10 13:11:12 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Mon, 10 Aug 2009 19:11:12 +0200
Subject: Problem when fetching page using urllib2.urlopen
References: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>
	<0579ebc0-2542-4f96-af3e-9861ad646b13@d9g2000prh.googlegroups.com>
	
Message-ID: <7eb2lgF2ec7u9U1@mid.uni-berlin.de>

dorzey wrote:

> "geturl - this returns the real URL of the page fetched. This is
> useful because urlopen (or the opener object used) may have followed a
> redirect. The URL of the page fetched may not be the same as the URL
> requested." from
> http://www.voidspace.org.uk/python/articles/urllib2.shtml#info-and-geturl
> 
> It might be worth checking that you are actually getting the page you
> want; I seem to remember that semicolons need to be encoded, similar
> to '&'.

You remember wrong.

http://www.faqs.org/rfcs/rfc2396.html

See Section 3.3, path-components.

Diez


From abecedarian314159 at yahoo.com  Mon Aug 10 13:19:31 2009
From: abecedarian314159 at yahoo.com (William)
Date: Mon, 10 Aug 2009 10:19:31 -0700 (PDT)
Subject: reloading the module imported as 'from ... import ...'
In-Reply-To: <4A7FB4AF.7060107@ggmail.com>
References: <4A7F976D.7090600@ggmail.com>
	
	<4A7FB4AF.7060107@ggmail.com>
Message-ID: <208933.60826.qm@web110606.mail.gq1.yahoo.com>

What about using the reimport library?

http://code.google.com/p/reimport/

Cheers,
William



________________________________
From: AlF 
To: python-list at python.org
Sent: Monday, August 10, 2009 1:48:31 AM
Subject: Re: reloading the module imported as 'from ... import ...'

Steven D'Aprano wrote:
> On Sun, 09 Aug 2009 20:43:41 -0700, AlF wrote:
> 
>> Hi,
>> 
>> what is the best way to reload the module imported using 'from ...
>> import ...'
> 
> 
> Have you tried "from ... import ..." again?
> 

I have not because of an assumption that "import" imports the module just once. In fact this still works that way:

here is a terminal 1:

$ cat > a.py
a=1
$ cat > a.py
a=2
$


and terminal 2:

>>> from a import a
>>> a
1
>>> a
1
>>> from a import a
>>> a
1
>>>

In spite of changing a.py in fly, the imported a is still 1


-- http://mail.python.org/mailman/listinfo/python-list



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From pavlovevidence at gmail.com  Mon Aug 10 13:28:25 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Mon, 10 Aug 2009 10:28:25 -0700 (PDT)
Subject: With or without leading underscore...
References: <5un5l6-fvn.ln1@satorlaser.homedns.org>
Message-ID: <4d6719e4-217a-4921-bd26-228fd4944eb7@r24g2000vbn.googlegroups.com>

On Aug 10, 7:37?am, Ulrich Eckhardt  wrote:
> ...that is the question!
>
> I have a module which exports a type. It also exports a function that
> returns instances of that type. Now, the reason for my question is that
> while users will directly use instances of the type, they will not create
> instances of the type themselves.
>
> So, the type is a part of the public API, but its constructor is not. Should
> I mark the type as private (with a leading underscore) or not?


I would not use the underscore.

If the initializer is private you might consider dispensing with
__init__ (have it raise TypeError), and initialize it from a "private"
method or classmethod, or even directly from the factory function.
And if you're wondering how the hell you're going to create the object
of type A when you've disabled __init__, see the example classmethod
below.


class A(object):
    def __init__(self,*args,**kwargs):
        raise TypeError('Type not callable; use factory function
instead')

    @classmethod
    def _create_object(cls,initial_value):
        self = object.__new__(cls) # avoid __init__
        self.value = initial_value



Carl Banks


From dorzey at googlemail.com  Mon Aug 10 13:28:51 2009
From: dorzey at googlemail.com (dorzey)
Date: Mon, 10 Aug 2009 10:28:51 -0700 (PDT)
Subject: Problem when fetching page using urllib2.urlopen
References: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>
	<0579ebc0-2542-4f96-af3e-9861ad646b13@d9g2000prh.googlegroups.com> 
	 
	<7eb2lgF2ec7u9U1@mid.uni-berlin.de>
Message-ID: <474e7cc0-f563-4e62-ab9e-61b16451a9bf@q14g2000vbi.googlegroups.com>

On 10 Aug, 18:11, "Diez B. Roggisch"  wrote:
> dorzey wrote:
> > "geturl - this returns the real URL of the page fetched. This is
> > useful because urlopen (or the opener object used) may have followed a
> > redirect. The URL of the page fetched may not be the same as the URL
> > requested." from
> >http://www.voidspace.org.uk/python/articles/urllib2.shtml#info-and-ge...
>
> > It might be worth checking that you are actually getting the page you
> > want; I seem to remember that semicolons need to be encoded, similar
> > to '&'.
>
> You remember wrong.
>
> http://www.faqs.org/rfcs/rfc2396.html
>
> See Section 3.3, path-components.
>
> Diez

My memory has been known to let me down on occasions ;) Thank you for
correcting my mistake.


From pavlovevidence at gmail.com  Mon Aug 10 13:29:27 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Mon, 10 Aug 2009 10:29:27 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
Message-ID: 

On Aug 10, 4:41?am, MRAB  wrote:
> Steven D'Aprano wrote:
> > On Sun, 09 Aug 2009 17:56:55 -0700, Douglas Alan wrote:
>
> [snip]
> >> My point of view is that
> >> every language has *some* warts; Python just has a bit fewer than most.
> >> It would have been nice, I should think, if this wart had been "fixed"
> >> in Python 3, as I do consider it to be a minor wart.
>
> > And if anyone had cared enough to raise it a couple of years back, it
> > possibly might have been.
>
> My preference would've been that a backslash followed by A-Z, a-z, or
> 0-9 is special, but a backslash followed by any other character is just
> the character, except for backslash followed by a newline, which
> suppresses the newline.

That would be reasonable; it'd match the behavior of regexps.


Carl Banks



From pavlovevidence at gmail.com  Mon Aug 10 13:43:08 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Mon, 10 Aug 2009 10:43:08 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
Message-ID: <0702d438-253e-4c8c-a26f-9247d824010a@e4g2000vbe.googlegroups.com>

On Aug 10, 1:37?am, Steven D'Aprano
 wrote:
> On Mon, 10 Aug 2009 00:37:33 -0700, Carl Banks wrote:
> > On Aug 9, 11:10?pm, Steven D'Aprano
> >  wrote:
> >> On Sun, 09 Aug 2009 18:34:14 -0700, Carl Banks wrote:
> >> >> Why should a backslash in a string literal be an error?
>
> >> > Because the behavior of \ in a string is context-dependent, which
> >> > means a reader can't know if \ is a literal character or escape
> >> > character without knowing the context, and it means an innocuous
> >> > change in context can cause a rather significant change in \.
>
> >> *Any* change in context is significant with escapes.
>
> >> "this \nhas two lines"
>
> >> If you change the \n to a \t you get a significant difference. If you
> >> change the \n to a \y you get a significant difference. Why is the
> >> first one acceptable but the second not?
>
> > Because when you change \n to \t, you've haven't changed the meaning of
> > the \ character;
>
> I assume you mean the \ character in the literal, not the (non-existent)
> \ character in the string.
>
> > but when you change \n to \y, you have, and you did so
> > without even touching the backslash.
>
> Not at all.
>
> '\n' maps to the string chr(10).
> '\y' maps to the string chr(92) + chr(121).
>
> In both cases the backslash in the literal have the same meaning: grab
> the next token (usually a single character, but not always), look it up
> in a mapping somewhere, and insert the result in the string object being
> built.

That is a ridiculous rationalization.  Nobody sees "\y" in a string
and thinks "it's an escape sequence that returns the bytes '\y'".


[snip rest, because an argument in favor inconsistent, context-
dependent behavior doesn't need any further refutation than to point
out that it is an argument in favor of inconsistent, context-dependent
behavior]


Carl Banks


From rickbking at comcast.net  Mon Aug 10 13:44:17 2009
From: rickbking at comcast.net (Rick King)
Date: Mon, 10 Aug 2009 13:44:17 -0400
Subject: how to use "exec" stmt to get input from user 
Message-ID: <4A805C71.4010809@comcast.net>

I have a cmd.py-derived program (with a wxPython GUI) and want to 
execute python statements for lines that are not my own special commands.

So basically it's either:

    def do_somecommand(self,arg):
        ...

or

    def default(self,arg):
        exec arg in globals(),self.cmdlocals

(where cmdlocals is a my local dictionary)

in default() I'd like to be able to execute any python statement 
including something like

    "x = raw_input('>')"

when I do this though it goes to the command window and so any user of 
the program would be confused, which also means I have to have a command 
window.

If I add this:

    self.stdin = self.edt_console_input   (where self.edt_console_input 
is a wxPython text control)

it just gets an EOF right away.

Is there any way to do what I want to do? This might be better posted on 
the wxpython list.

Thanks for any help!

Rick King
Southfield MI




From darkwater42 at gmail.com  Mon Aug 10 13:52:05 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Mon, 10 Aug 2009 10:52:05 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
	
	
	<86e09602-7eb1-4397-a77f-fb1e3c5b34b9@k26g2000vbp.googlegroups.com>
Message-ID: <274a2d6a-a154-4d22-a093-c1c29457f71f@z34g2000vbl.googlegroups.com>

I wrote:

> But you're right, it's too late to change this now.

P.S. But if it weren't too late, I think that your idea to have "\s"
be the escape sequence for a backslash instead of "\\" might be a good
one.

|>ouglas


From starsareblueandfaraway at gmail.com  Mon Aug 10 13:53:13 2009
From: starsareblueandfaraway at gmail.com (Roy Hyunjin Han)
Date: Mon, 10 Aug 2009 13:53:13 -0400
Subject: Python documentation servers
Message-ID: <6a5569ec0908101053x53e8070escae5e6535325afb@mail.gmail.com>

Are there issues with the python documentation servers?
http://docs.python.org/
The site has been really slow to respond all weekend.


From 71david at libero.it  Mon Aug 10 14:00:06 2009
From: 71david at libero.it (David)
Date: Mon, 10 Aug 2009 20:00:06 +0200
Subject: wxpython question
References: <11f24035-bd42-4df8-879a-2e2558ee45ee@d23g2000vbm.googlegroups.com>
Message-ID: 

Il Mon, 10 Aug 2009 07:55:42 -0700 (PDT), azrael ha scritto:

> Is there maybe a method bounded to the class SpinCtrl() that could
> hide the widget. One that is maybe also implemented in any other
> control.

AFAIK, any widget can be made invisibile calling the .Show(False) method of
the container sizer.
http://docs.wxwidgets.org/stable/wx_wxsizer.html#wxsizershow

David


From dullrich at sprynet.com  Mon Aug 10 14:10:14 2009
From: dullrich at sprynet.com (David C Ullrich)
Date: Mon, 10 Aug 2009 13:10:14 -0500
Subject: how to use "exec" stmt to get input from user
References: 
Message-ID: 

What you're trying to do and what's not working isn't 
entirely clear to me.

But if I had a wxPython application and I wanted to
execute user input (note the _if_) I'd just pop up a window
(I forget how "ShowModal" is spelled in wx right now)
with a text box and an Execute button and a Cancel
button - if the user hits the Execute button I'd
attempt to execute what he'd typed in the box.

There are reasons you want to be very careful about
this...

On Mon, 10 Aug 2009 13:44:17 -0400, Rick King wrote:

> I have a cmd.py-derived program (with a wxPython GUI) and want to
> execute python statements for lines that are not my own special
> commands.
> 
> So basically it's either:
> 
>     def do_somecommand(self,arg):
>         ...
> 
> or
> 
>     def default(self,arg):
>         exec arg in globals(),self.cmdlocals
> 
> (where cmdlocals is a my local dictionary)
> 
> in default() I'd like to be able to execute any python statement
> including something like
> 
>     "x = raw_input('>')"
> 
> when I do this though it goes to the command window and so any user of
> the program would be confused, which also means I have to have a command
> window.
> 
> If I add this:
> 
>     self.stdin = self.edt_console_input   (where self.edt_console_input
> is a wxPython text control)
> 
> it just gets an EOF right away.
> 
> Is there any way to do what I want to do? This might be better posted on
> the wxpython list.
> 
> Thanks for any help!
> 
> Rick King
> Southfield MI



From rt8396 at gmail.com  Mon Aug 10 14:35:39 2009
From: rt8396 at gmail.com (r)
Date: Mon, 10 Aug 2009 11:35:39 -0700 (PDT)
Subject: pybotwar-0.5
References:  
	<3e9c5fcd-4047-4edd-b2ec-d892c77e3a69@f33g2000vbm.googlegroups.com>
Message-ID: 

On Aug 9, 9:46?pm, Mensanator  wrote:
> On Aug 9, 3:26?pm, Lee Harr  wrote:
>
> > pybotwar is a fun and educational game where players
> > create computer programs to control simulated robots
> > to compete in a battle arena.
>
> >http://pybotwar.googlecode.com/
>
> Why is the doc folder empty?
>
> Shouldn't you supply some hint on how the games works
> and at least a rudimentary guide to robot design?
>
> What version to you expect that will be in? 1.0? 10.0?
>
> Could you inform us when you have something worth looking
> at and not before so we don't have to waste our time?

What a bombastically stupid thing to say even for you "Menstrual
cycle". Sure, there is no documentation but maybe the creator meant
for this module to be used only by experienced Python programmers and
not script kiddies like yourself who need a four page tut just to code
up a hello world.py. If you are anything more than an amateur the
source code should be all the documentation you need to use this
module. If not, get on with your pathetic life!

Next time before you open your mouth, try to use those two brain cells
you have left up there and put together a reasonable and responsible
response that is more than just a cowardly put down. Now run along
little spam bot, i am sure one of the other thousands of groups you
post to can't wait for your triumphant return!

r "slayer of the galactic-ly stupid!"


From jcd at sdf.lonestar.org  Mon Aug 10 14:47:19 2009
From: jcd at sdf.lonestar.org (J. Cliff Dyer)
Date: Mon, 10 Aug 2009 14:47:19 -0400
Subject: variable & scoping question.
In-Reply-To: <93c50fc3-2cf9-4fc6-9919-cde7cfd273e6@o35g2000vbi.googlegroups.com>
References: 
	<7earmtF2f4tvnU1@mid.uni-berlin.de>
	<93c50fc3-2cf9-4fc6-9919-cde7cfd273e6@o35g2000vbi.googlegroups.com>
Message-ID: <1249930039.17682.5.camel@aalcdl07>

On Mon, 2009-08-10 at 08:46 -0700, Cornelius Keller wrote:
> On 10 Aug., 17:12, "Diez B. Roggisch"  wrote:
> > Cornelius Keller wrote:
> [snip]
> >
> > http://effbot.org/zone/default-values.htm
> >
> > Diez
> 
> Ok thank you.
> I' understand now why.
> I still think this is very confusing, because default values don't
> behave like most people would expect without reading the docs.
> 
> - Cornelius

You are correct.  This is confusing at first blush.  The important thing
to remember is: *don't do that.*  Learn the pythonic workaround of using
None in your parameters whenever you want a default empty list, and
don't let it bother you too much.  Overall, python is a remarkably well
designed language.  This is one of the relatively rare warts that crept
in because it enables a broader cleanliness of design.

Cheers,
Cliff




From rt8396 at gmail.com  Mon Aug 10 15:10:08 2009
From: rt8396 at gmail.com (r)
Date: Mon, 10 Aug 2009 12:10:08 -0700 (PDT)
Subject: Python documentation servers
References: 
Message-ID: 

On Aug 10, 12:53?pm, Roy Hyunjin Han
 wrote:
> Are there issues with the python documentation servers?http://docs.python.org/
> The site has been really slow to respond all weekend.

try this thread
http://groups.google.com/group/comp.lang.python/browse_thread/thread/052368a71f2a8ad2/929bd74bd203c6e8?hl=en&lnk=raot8

PS Just ignore the OT humor near the bottom ;)


From breamoreboy at yahoo.co.uk  Mon Aug 10 15:11:53 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Mon, 10 Aug 2009 20:11:53 +0100
Subject: pybotwar-0.5
In-Reply-To: 
References: 
	<3e9c5fcd-4047-4edd-b2ec-d892c77e3a69@f33g2000vbm.googlegroups.com>
	
Message-ID: 

[snip]
> r "slayer of the galactic-ly stupid!"
Can I assume from this that you intend killing yourself, on the grounds 
that some 10 days ago you couldn't successfully use a windows compiled 
help file?
-- 
Kindest regards.

Mark Lawrence.



From piet at cs.uu.nl  Mon Aug 10 15:36:55 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Mon, 10 Aug 2009 21:36:55 +0200
Subject: Problem when fetching page using urllib2.urlopen
References: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>
Message-ID: 

>>>>> jitu  (j) wrote:

>j> Hi,
>j> A html page  contains 'anchor' elements with 'href' attribute  having
>j> a semicolon  in the url , while fetching the page using
>j> urllib2.urlopen, all such href's  containing  'semicolons' are
>j> truncated.


>j> For example the href http://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt=AlWSqpkpqhICp1lMgChtJkCdGWoL
>j> get truncated to http://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i

>j> The page I am talking about can be fetched from
>j> http://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_ylc=X3oDMTFka28zOGNuBF9TAzI3NjY2NzkEX3MDOTY5NTUzMjUEc2VjA3NzcC1kZXN0BHNsawN0aXRsZQ--

It's not python that causes this. It is the server that sends you the
URLs without these parameters (that's what they are).

To get them you have to tell the server that you are a respectable
browser. E.g.

import urllib2

url = 'http://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt=AlWSqpkpqhICp1lMgChtJkCdGWoL'

url = 'http://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_ylc=X3oDMTFka28zOGNuBF9TAzI3NjY2NzkEX3MDOTY5NTUzMjUEc2VjA3NzcC1kZXN0BHNsawN0aXRsZQ--'

hdrs = {'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13',
       'Accept': 'image/*'}

request = urllib2.Request(url = url, headers = hdrs)
page = urllib2.urlopen(request).read()

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From piet at cs.uu.nl  Mon Aug 10 15:38:39 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Mon, 10 Aug 2009 21:38:39 +0200
Subject: www.python.org website is down?
References: 
	
	<1d952f0b-9552-48ef-ad2e-a7b8e06ea8eb@n2g2000vba.googlegroups.com>
	
Message-ID: 

>>>>> MRAB  (M) wrote:

>M> r wrote:
>>> On Aug 8, 8:48 am, MRAB  wrote:
>>> ...(snip)
>>>> Bothwww.python.organd svn.python.org are down.  They're hosted on
>>>> the same machine, and it seems to have run into disk problems and
>>>> hasn't rebooted even after power-cycling.  Thomas Wouters will be
>>>> visiting the machine physically tomorrow to try to diagnose the
>>>> problem.
>>> 
>>> Oh stop lying MRAB, everybody knows Guido hosts Python.org from his
>>> attic on an old Linux box :-)

>M> That was a quote from A.M. Kuchling.

>M> It's actually hosted on a matchbox-sized multi-core multi-terabyte
>M> wifi-enabled Linux machine that Guido brought back from 2050.
>M> Unfortunately, the dog ate it, so he's had to go and buy another one!

The 2050 models can run on the internal heat of a dog !!
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From rt8396 at gmail.com  Mon Aug 10 16:56:57 2009
From: rt8396 at gmail.com (r)
Date: Mon, 10 Aug 2009 13:56:57 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	
Message-ID: <081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com>

On Aug 10, 11:13?am, Ethan Furman  wrote:
(snip)
> As someone who relies heavily on the docs I will also say that the idea
> of giving the ability to modify the official documentation to somebody
> who is /learning/ the language is, quite frankly, terrifying.
(snip)

Ethan,
I think what you and a few others seem to miss is ... Of course nobody
wants Joe-Noob writing the Python docs -- thats lunacy, would you give
your 12 year old the keys to a shiny new corvette? -- No! What people
are asking for is the ability for a noobs input on the official docs,
and for that input to be taken seriously. Sure some of the suggestions
will be nothing more than "helpful ignoramuses" with unhelpful
suggestions as some have said, but the input channels need to be
there. Currently Python dev seems to be more output than input,
however i could be wrong? We some real I/O going on here.

Also the Python tut is full of fluff (sorry Guido) and it contributes
to late learning of the language. Luckily however Python has many
users who really love the language and have taken the time to write
beautiful tutorials that start at various levels of entry. Read xah's
take on the official tutorial, it's spot on baby!

A little note for tutorial writers:
==================================

Dear Expert,
Whilst writing any tutorial on any subject matter please remember, you
may be an expert, but mostly *non-experts* will be reading your
material... pssft, this may come as a surprise, but tutorials are
meant for *NON-EXPERTS*!

Please refrain from stroking your own ego by obstrufcation of the very
ideas you wish to convey to these influential minds. Sure exposing
your huge intelligence to the world may give you warm-fuzzies-in-your-
tummy, but believe me your poor students will be rendered as helpless
as Paris Hilton at a "panties required" spelling bee.

Please try, and i know this is a lot to ask, to use the most simple
explanation to convey the point -- and *only* the point at hand! Take
for example the introduction of functions. You could go with your gut
instinct, "shoot from the hip" and pop off something like this that
prints a Fibonacci series up to n...

def fib(n):
    a, b = 0, 1
    while b < n:
        print b,
        a, b = b, a+b

>>> fib(2000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

And all you would have accomplished was to blow holes thru the
students mind! Now like the next guy, i love calculating series of
numbers all day, but this is a piss poor example of functions for the
new student, or anybody for that matter!  While your student is
racking his brain trying to figure out what "a" and "b" stand for,
much less n, and not to mention what the heck a "Fibonacci" series is
in the first place (Google can help though) , he (the student) has
forgotten that this example is simply how to write and call a
function. A much better example would be the following...

def add(x, y):
    print x+y

>>> add(1, 2)
3

WOW,  with that small piece of code you have just transported three
main principals of a function in a very simple and strait forward way
smack-dab into the cerebral cortex of the student, and your fingers
did not even break a sweat!

 1. function names should describe exactly what they do
 2. functions take arguments
 3. functions do something with those arguments(like mini programs!)

You could followup with this fine example that extents on the
first...

def add(x, y=2)
    return x+y

>>> add(1,2)

>>> print add(1, 2)
3
>>> print add(1)
3
>>> print add(100, 5.5)
100.5
>>> print add()
error...


However Ethan (and Co.),  not everybody who downloads Python the first
time knows about this. Also the Python website is filled to the brim
with a hodgepodge of "links-here" "links-there", "links-every-freaking-
where" (are we getting paid by the link people?) causing most noobs
brain to start blowing chunks just while tring to find a good
alternative to the official tut!

Really, it's bloat on a proportion that only elephant sized bloat
wares like M$, M$-Office, Adobe-PDF, and the like, can hold a candle
to. Python really needs and enema, and thats no joke!


From mensanator at aol.com  Mon Aug 10 17:01:58 2009
From: mensanator at aol.com (Mensanator)
Date: Mon, 10 Aug 2009 14:01:58 -0700 (PDT)
Subject: pybotwar-0.5
References:  
	<3e9c5fcd-4047-4edd-b2ec-d892c77e3a69@f33g2000vbm.googlegroups.com> 
	
Message-ID: 

On Aug 10, 1:35?pm, r  wrote:
>
> Sure, there is no documentation

http://www.mensanator.com/mensanator/PythonTurtle/paper.htm



From rickbking at comcast.net  Mon Aug 10 17:36:27 2009
From: rickbking at comcast.net (Rick King)
Date: Mon, 10 Aug 2009 17:36:27 -0400
Subject: how to use "exec" stmt to get input from user
In-Reply-To: 
References: 
	
Message-ID: <4A8092DB.3090703@comcast.net>

Thanks for your comment.

The purpose of the application is to automate the manipulation of large 
numbers of files. For automation I want to be able to have scripts that 
I can use for various purposes.

On input, cmd.py handles calling "do_...." methods for known commands; 
for the rest I want to "exec" the lines with my own dictionary. This 
allows me to use python statements, so I can do things like 
concatenating variables to form directory names, and so on. I'd like to 
be able to use any python statement, including "x=raw_input('>')", but 
this currently brings everything to a halt.

One thing this app does is execute processes using wxPythons wx.Process 
object and wx.Execute function. wxPython makes it easy to redirect stdin 
and stdout. I'm trying to do a similar thing for individual python 
statements. I'm not sure that makes sense.

I hope that's clear.

Rick


David C Ullrich wrote:
> What you're trying to do and what's not working isn't 
> entirely clear to me.
>
> But if I had a wxPython application and I wanted to
> execute user input (note the _if_) I'd just pop up a window
> (I forget how "ShowModal" is spelled in wx right now)
> with a text box and an Execute button and a Cancel
> button - if the user hits the Execute button I'd
> attempt to execute what he'd typed in the box.
>
> There are reasons you want to be very careful about
> this...
>
> On Mon, 10 Aug 2009 13:44:17 -0400, Rick King wrote:
>
>   
>> I have a cmd.py-derived program (with a wxPython GUI) and want to
>> execute python statements for lines that are not my own special
>> commands.
>>
>> So basically it's either:
>>
>>     def do_somecommand(self,arg):
>>         ...
>>
>> or
>>
>>     def default(self,arg):
>>         exec arg in globals(),self.cmdlocals
>>
>> (where cmdlocals is a my local dictionary)
>>
>> in default() I'd like to be able to execute any python statement
>> including something like
>>
>>     "x = raw_input('>')"
>>
>> when I do this though it goes to the command window and so any user of
>> the program would be confused, which also means I have to have a command
>> window.
>>
>> If I add this:
>>
>>     self.stdin = self.edt_console_input   (where self.edt_console_input
>> is a wxPython text control)
>>
>> it just gets an EOF right away.
>>
>> Is there any way to do what I want to do? This might be better posted on
>> the wxpython list.
>>
>> Thanks for any help!
>>
>> Rick King
>> Southfield MI
>>     
>
>   
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From longbotham at gmail.com  Mon Aug 10 17:38:08 2009
From: longbotham at gmail.com (Nathan)
Date: Mon, 10 Aug 2009 14:38:08 -0700 (PDT)
Subject: numpy array merge
Message-ID: <427654ff-5455-4198-bc86-d810ef3fafd6@t11g2000prh.googlegroups.com>

Is there an easy way to merge two numpy arrays with different rank
sizes (terminology?).  I want to make a single array by concatenating
two arrays along a given direction and filling the excess cells with a
dummy variable.  numpy concatenate works well as long as the two
arrays have the same dimension, but I want to do this on two array
with a matching dimension size.  An example:

import numpy as np
a = np.array([[1,2,3],[4,5,6]])
b = np.array([[1,2],[3,4],[5,6]])
np.concatenate((a,a),axis=1)  #This works fine, but isn't what I need.
Out:  array([[1, 2, 3, 1, 2, 3],
       [4, 5, 6, 4, 5, 6]])
np.concatenate((a,b),axis=1)  #This doesn't work, but this is what I
need.

I want to fill the third row of array "a" with a dummy variable (99999
or NaN) and concatenate with "b" to make:
[1,2,3,1,2]
[4,5,6,4,5]
[99999,99999,99999,5,6]

This just seems like it would be relatively common.  So I thought I'd
check if I'm missing something before I go write the logic.  Thanks!


From mail at johannes-janssen.de  Mon Aug 10 17:51:59 2009
From: mail at johannes-janssen.de (Johannes Janssen)
Date: Mon, 10 Aug 2009 23:51:59 +0200
Subject: How to find out in which module an instance of a class is created?
In-Reply-To: <4A7F6016.2060408@cheimes.de>
References: <4A7F4874.8030008@johannes-janssen.de>
	<4A7F6016.2060408@cheimes.de>
Message-ID: <4A80967F.9030604@johannes-janssen.de>

Christian Heimes schrieb:
> Johannes Janssen wrote:
>>  > class A(object):
>>  >     def __init__(self, mod=__name__):
>>  >         self.mod = mod
>>
>> .... won't work. In this case mod would always be "foo".
>
> You have to inspect the stack in order to get the module of the 
> caller. The implementation of warnings.warn() gives you some examples 
> how to get the module name.
>
> Christian
>
Thanks for the quick and very helpful reply. Basically just copying from 
warnings.warn(), I came up with this:

import sys

class A(object):
    def __init__(self, mod=None):
        if mod is None:
            self.mod = sys._getframe(1).f_globals['__name__']
        else:
            self.mod = mod

In warnings.warn() they used try around sys._getframe(1). As far as I 
understand what is done in warnings, there it is not sure what object 
caused the warning and therefore it is not sure whether you can or 
cannot use sys._getframe(1). Though in my case it should be quite clear. 
Can I be sure that my code will always work?

Johannes


From aahz at pythoncraft.com  Mon Aug 10 18:02:00 2009
From: aahz at pythoncraft.com (Aahz)
Date: 10 Aug 2009 15:02:00 -0700
Subject: help with threads
References: <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c@l5g2000pra.googlegroups.com>
Message-ID: 

In article <5a744bd6-6b9a-4f46-97c1-bb7fd65b8f4c at l5g2000pra.googlegroups.com>,
Michael Mossey   wrote:
>
>I have a simple application that needs one thread to manage networking
>in addition to the main "thread" that does the main job. It's not
>working right. I know hardly anything about threads, so I was hoping
>someone could point me in the right direction to research this.

You might also consider the multiprocessing module.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz


From patx44 at gmail.com  Mon Aug 10 18:12:43 2009
From: patx44 at gmail.com (patx)
Date: Mon, 10 Aug 2009 18:12:43 -0400
Subject: fastPATX (a new and simple web browser)
Message-ID: <699f51260908101512n42fa053bj41646f816f8c3f9b@mail.gmail.com>

There was a new release of fastPATX today. However the code and the program
itself will not be available to the public untill Tuesday the 11th. This is
due to me not having the proper tools I need to publish it (I am not at my
"main comp."). This is a bit of an over statement it will probably be
published near midnight Florida time. There are many different places you
can get fastPATX. I will cover them below:
http://bitbucket.org/patx/fastpatx/
http://patx44.appspot.com/
http://www.hawkee.com/snippet/6429/

More places may be out there (mirrors) but I do not know, they are NOT
official but I do 100% support them, and encourage many to mirror fastPATX.

fastPATX official wiki - http://bitbucket.org/patx/fastpatx

JJTComputing have given a great review of fastPATX and it has been linked to
on many site (Tuxmachines). I strongly wish that if you use fastPATX to blog
or tweet (include an @h_erd ???) about, even if you did not like it! Also if
you do like it please follow the project on bitbucket.org >>
http://bitbucket.org/patx/fastpatx/follow/

If you have any questions or suggestions please email me.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From darkwater42 at gmail.com  Mon Aug 10 18:17:24 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Mon, 10 Aug 2009 15:17:24 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
Message-ID: <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>

From: Steven D'Aprano  wrote:

> On Mon, 10 Aug 2009 00:32:30 -0700, Douglas Alan wrote:

> > In C++, if I know that the code I'm looking at compiles,
> > then I never need worry that I've misinterpreted what a
> > string literal means.

> If you don't know what your string literals are, you don't
> know what your program does. You can't expect the compiler
> to save you from semantic errors. Adding escape codes into
> the string literal doesn't change this basic truth.

I grow weary of these semantic debates. The bottom line is
that C++'s strategy here catches bugs early on that Python's
approach doesn't. It does so at no additional cost.

>From a purely practical point of view, why would any
language not want to adopt a zero-cost approach to catching
bugs, even if they are relatively rare, as early as
possible?

(Other than the reason that adopting it *now* is sadly too
late.)

Furthermore, Python's strategy here is SPECIFICALLY
DESIGNED, according to the reference manual to catch bugs.
I.e., from the original posting on this issue:

     Unlike Standard C, all unrecognized escape sequences
     are left in the string unchanged, i.e., the backslash
     is left in the string. (This behavior is useful when
     debugging: if an escape sequence is mistyped, the
     resulting output is more easily recognized as broken.)

If this "feature" is designed to catch bugs, why be
half-assed about it? Especially since there seems to be
little valid use case for allowing programmers to be lazy in
their typing here.

> The compiler can't save you from typing 1234 instead of
> 11234, or 31.45 instead of 3.145, or "My darling Ho"
> instead of "My darling Jo", so why do you expect it to
> save you from typing "abc\d" instead of "abc\\d"?

Because in the former cases it can't catch the the bug, and
in the latter case, it can.

> Perhaps it can catch *some* errors of that type, but only
> at the cost of extra effort required to defeat the
> compiler (forcing the programmer to type \\d to prevent
> the compiler complaining about \d). I don't think the
> benefit is worth the cost. You and your friend do. Who is
> to say you're right?

Well, Bjarne Stroustrup, for one.

All of these are value judgments, of course, but I truly
doubt that anyone would have been bothered if Python from
day one had behaved the way that C++ does. Additionally, I
expect that if Python had always behaved the way that C++
does, and then today someone came along and proposed the
behavior that Python currently implements, so that the
programmer could sometimes get away with typing a bit less,
such a person would be chided for not understanding the Zen
of Python.

> > You don't have to go running for the manual every time
> > you see code with backslashes, where the upshot might be
> > that the programmer was merely saving themselves some
> > typing.

> Why do you care if there are "funny characters"?

Because, of course, "funny characters" often have
interesting consequences when output. Furthermore, their
consequences aren't always immediately obvious from looking
at the source code, unless you are intimately familiar with
the function of the special characters in question.

For instance, sometimes in the wrong combination, they wedge
your xterm. Etc.

I'm surprised that this needs to be spelled out.

> In C++, if you see an escape you don't recognize, do you
> care?

Yes, of course I do. If I need to know what the program
does.

> Do you go running for the manual? If the answer is No,
> then why do it in Python?

The answer is that I do in both cases.

> No. \z *is* a legal escape sequence, it just happens to map to \z.

> If you stop thinking of \z as an illegal escape sequence
> that Python refuses to raise an error for, the problem
> goes away. It's a legal escape sequence that maps to
> backslash + z.

(1) I already used that argument on my friend, and he wasn't
buying it. (Personally, I find the argument technically
valid, but commonsensically invalid. It's a language-lawyer
kind of argument, rather than one that appeals to any notion
of real aesthetics.)

(2) That argument disagrees with the Python reference
manual, which explicitly states that "unrecognized escape
sequences are left in the string unchanged", and that the
purpose for doing so is because it "is useful when
debugging".

> > "\x" is not a legal escape sequence. Shouldn't it also
> > get left as "\\x"?
>
> No, because it actually is an illegal escape sequence.

What makes it "illegal". As far as I can tell, it's just
another "unrecognized escape sequence". JavaScript treats it
that way. Are you going to be the one to tell all the
JavaScript programmers that their language can't tell a
legal escape sequence from an illegal one?

> > Well, I think he's more annoyed that if Python is going
> > to be so helpful as to put in the missing "\" for you in
> > "foo\zbar", then it should put in the missing "\" for
> > you in "\". He considers this to be an inconsistency.
>
> (1) There is no missing \ in "foo\zbar".
>
> (2) The problem with "\" isn't a missing backslash, but a
> missing end- quote.

Says who? All of this really depends on your point of
view. The whole morass goes away completely if one adopts
C++'s approach here.

> Python isn't DWIMing here. The rules are simple and straightforward,
> there's no mind-reading or guessing required.

It may not be a complex form of DWIMing, but it's still
DWIMing a bit. Python is figuring that if I typed "\z", then
either I must have really meant to type "\\z", or that I
want to see the backslash when I'm debugging because I made
a mistake, or that I'm just too lazy to type "\\z".

> Is it "a form of DWIMing" to consider 1.234e1 and 12.34
> synonymous?

That's a very different issue, as (1) there are very
significant use cases for both kinds of numerical
representations, and (2) there's often only one obvious way
way that the number should be entered, depending on the
coding situation.

> What about 86 and 0x44? Is that DWIMing?

See previous comment.

> I'm sure both you and your friend are excellent
> programmers, but you're tossing around DWIM as a
> meaningless term of opprobrium without any apparent
> understand of what DWIM actually is.

I don't know if my friend even knows the term DWIM, other
than me paraphrasing him, but I certainly understand all
about the term. It comes from InterLisp. When DWIM was
enabled, your program would run until it hit an error, and
for certain kinds of errors, it would wait a few seconds for
the user to notice the error message, and if the user didn't
tell the program to stop, it would try to figure out what
the user most likely meant, and then continue running using
the computer-generated "fix".

I.e., more or less like continuing on in the face of what
the Python Reference manual refers to as an "unrecognized
escape sequence".

|>ouglas


From 7of77 at web.de  Mon Aug 10 18:24:21 2009
From: 7of77 at web.de (bernd)
Date: Mon, 10 Aug 2009 15:24:21 -0700 (PDT)
Subject: illegal geld machen , schnell geld verdienen in , schnell geld im 
	internet , geld 2.0 geld verdienen im web 2.0 ,
	novoline american poker 
	online spielen , sofort geld im internet , mehr geld verdienen ,
	roulette geld machen ,
References: <692f7f6b-2235-429f-be42-c3d04cdcb134@r37g2000yqd.googlegroups.com>
	<7350a4df-0ba2-4cb4-ab39-f7fda00bc729@t13g2000yqt.googlegroups.com>
Message-ID: 

On 25 Jul., 00:50, entr... at web.de wrote:
> On 7 Jun., 19:48, swirler... at googlemail.com wrote:
> , schnell geld verdienenwww.novocasinos.de
> http://www.novocasinos.de
> http://casino-pirat.de
> www.casino-pirat.de
> www.novocasinos.de
> http://www.novocasinos.de
> > *www.novocasinos.de
> > *http://www.novocasinos.de
> > *
> > +++ SOFORT GEWINN +++ REICH WERDEN +++
> > *http://WWW.novolinecasinos.de
> > *http://www.novocasinos.de
> > *www.casino-pirat.de
> > *www.novocasinos.de
>
> > geld im internet verdienen mit geld verdienen mit online umfragen
> > damit geld machen blog geld verdienen
> > schnell geld verdiehnen geld sparen leicht
> > jetzt sofort schnelles geld drakensang geld verdienen
> > www schnell geld im internet verdienen forum
> > geld sparen leicht gemacht ebook geld verdienen im internet
> > wie kann ich online geld verdienen man schnell geld machen
> > gewinn24 jetzt sofort reunion schnell geld
> > wo kann ich geld gewinn online spielen und geld
> > schnell geld zu verdienen einfach und schnell geld
> > viel geld verdienen im internet online poker echtes geld
> > geld seite geld verdienen mit internet
> > ich schnelles geld machen geld im internet verdienen ohne
> > internet geld vedienen geld machen von
> > internet geld verdient geld online gewinnen
> > schnell zu geld man online geld verdienen
> > geld machen wenn geld verdienen mit web
> > http://novocasinos.de
> > geld verdienen mit homepage geld verdienen durch online- Zitierten Text ausblenden -
>
> - Zitierten Text anzeigen -



From david.lyon at preisshare.net  Mon Aug 10 19:56:21 2009
From: david.lyon at preisshare.net (David Lyon)
Date: Mon, 10 Aug 2009 19:56:21 -0400
Subject: wxpython question
In-Reply-To: <11f24035-bd42-4df8-879a-2e2558ee45ee@d23g2000vbm.googlegroups.com>
References: <11f24035-bd42-4df8-879a-2e2558ee45ee@d23g2000vbm.googlegroups.com>
Message-ID: 


is there a method/property called Show/Shown ?

On Mon, 10 Aug 2009 07:55:42 -0700 (PDT), azrael 
wrote:
> Is there maybe a method bounded to the class SpinCtrl() that could
> hide the widget. One that is maybe also implemented in any other
> control.
> 
> self.spcKvadDo = wx.SpinCtrl(id=-1, initial=0, max=1000000, min=0,
> name='spcKvadDo', parent=self.pnlFilteri, pos=wx.Point(10, 10),
> size=wx.Size(118, 21), style=wx.SP_ARROW_KEYS)
> 
> self.spcKvadOd.XXX()
> 
> I tried it with the SetTransparent() method but it did not work. Has
> anyone any Idea?


From david.lyon at preisshare.net  Mon Aug 10 20:05:00 2009
From: david.lyon at preisshare.net (David Lyon)
Date: Mon, 10 Aug 2009 20:05:00 -0400
Subject: Python docs disappointing - group effort to hire
	=?UTF-8?Q?writers=3F?=
In-Reply-To: <4A80472E.4090108@stoneleaf.us>
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>		<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>			<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	<4A80472E.4090108@stoneleaf.us>
Message-ID: <0985e0fe54bf41fa3736cd6697d42bf4@preisshare.net>

On Mon, 10 Aug 2009 09:13:34 -0700, Ethan Furman 
wrote:
> As someone who relies heavily on the docs I will also say that the idea 
> of giving the ability to modify the official documentation to somebody 
> who is /learning/ the language is, quite frankly, terrifying.  

What is more terrifying is the way feedback from newbies is handled.

Your statement implies that the only way feedback can be handled is
to throw the keys down in discust and walk away. That's primative
behaviour. And misleading, because that isn't going to happen.

> My bookshelf currently has Learning Python, Programming 
> Python, Python Cookbook, Python Programming on Win32, and Regular 
> Expressions.  All great books, and not too pricey if you can get them
used.

So, what you're advocating is let things stay how they are...

Ignore feedback... tell people to freak off...




From http  Mon Aug 10 21:28:47 2009
From: http (Paul Rubin)
Date: 10 Aug 2009 18:28:47 -0700
Subject: Python docs disappointing - group effort to hire writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	
	<081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com>
Message-ID: <7xr5vj9m0g.fsf@ruckus.brouhaha.com>

r  writes:
> Whilst writing any tutorial on any subject matter please remember, you
> may be an expert, but mostly *non-experts* will be reading your
> material... pssft, this may come as a surprise, but tutorials are
> meant for *NON-EXPERTS*!

I think the Python tutorial is aimed at users who are newbies to
Python but not newbies to programming.  Writing a tutorial for total
newbies is a completely different problem, that would result in a much
different document that's less useful to the existing tutorial's
intended audience.


From pacificik at warnell.uga.edu  Mon Aug 10 22:11:04 2009
From: pacificik at warnell.uga.edu (Krishna Pacifici)
Date: Mon, 10 Aug 2009 22:11:04 -0400
Subject: dictionary help
Message-ID: <4A809AF80200008C000149EC@redhorse.forestry.uga.edu>

Hi,
kind of a newbie here, but I have two questions that are probably pretty simple.

1.  I need to get rid of duplicate values that are associated with different keys in a dictionary.  For example I have the following code.
s={}
s[0]=[10,2,3]
 s[10]=[22,23,24]
 s[20]=[45,5]
s[30]=[2,4]
s[40]=[6,7,8]

Now I want to be able to loop through the primary keys and get rid of duplicates (both in keys and values) so that I would have either a new dictionary or the same dictionary but with the following values:

s[0]=[3]
 s[10]=[22,23,24]
 s[20]=[45,5]
s[30]=[2,4]
s[40]=[6,7,8]

It doesn't matter which value gets removed as long as there is only one remaining, so in this example it doesn't matter that 2 got removed from s[0] or from s[30] as long as there is only one 2 in the dictionary.

2.  I need to be able to loop over the values in the dictionary when there are multiple values assigned to each key like above and assign new values to those values.  Taking the above example I would want to assign a new value so that when you called s[0] it would equal [3,4] say if 4 was the new value.  I think this should be as simple as adding a value, but I kept on having difficulty.

Any suggestions would be greatly appreciated.

Thank you very much,
Krishna

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From gagsl-py2 at yahoo.com.ar  Mon Aug 10 22:15:03 2009
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Mon, 10 Aug 2009 23:15:03 -0300
Subject: Python configuration question when python scripts are executed
	using Appweb as web server.
References: 
	
	
	
	
	
	
Message-ID: 

En Mon, 10 Aug 2009 11:48:31 -0300, IronyOfLife 
escribi?:

>> Why different results in IIS and appweb? [...]
> This is fairly easy to explain. When I configured IIS to execute
> python scripts, as per the documentation I pass two command line
> arguments. Appweb works this way. It opens up a new command process
> and in the function parameter for environment it sets only SYSTEMROOT.
> It does not set the PATH variable (A BUG IN APPWEB which I have passed
> on to them. They have not commented or provided any work around) for
> Windows platform.

Perhaps you could configure appweb to call a .bat file like this, instead
of directly invoking python?

set path=%path%;other;directories;added
c:\path\to\python.exe %*

(this is slightly off topic now...)

> You were mentioning about .local file or manifest file to specify the
> path. I used the python's build command to build the wrapper. Is there
> a way to mention in setup.py to generate the .manifest file? I wold
> very much appreciate if you can help me with that.
>
> I will also look for answers for how to modify setup.py to generate
> manifest file or .local file etc..

The last part is easy: foo.exe.local is just an empty file in the same
directory as foo.exe - when it exists, DLLs are searched first on the
directory containing the application [1]

With manifest files I can't help. I suggest you create a new thread with
that question, perhaps in the distutils-SIG mailing list [2]

[1] http://msdn.microsoft.com/en-us/library/ms682600(VS.85).aspx
[2] http://mail.python.org/mailman/listinfo/distutils-sig

-- 
Gabriel Genellina



From jcd at sdf.lonestar.org  Mon Aug 10 23:07:49 2009
From: jcd at sdf.lonestar.org (J. Cliff Dyer)
Date: Mon, 10 Aug 2009 23:07:49 -0400
Subject: dictionary help
In-Reply-To: <4A809AF80200008C000149EC@redhorse.forestry.uga.edu>
References: <4A809AF80200008C000149EC@redhorse.forestry.uga.edu>
Message-ID: <1249960069.5675.8.camel@webb>

On Mon, 2009-08-10 at 22:11 -0400, Krishna Pacifici wrote:
> Hi,
> kind of a newbie here, but I have two questions that are probably
> pretty simple.
> 
> 1.  I need to get rid of duplicate values that are associated with
> different keys in a dictionary.  For example I have the following
> code.
> s={}
> s[0]=[10,2,3]
> s[10]=[22,23,24]
> s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
> 
> Now I want to be able to loop through the primary keys and get rid of
> duplicates (both in keys and values) so that I would have either a new
> dictionary or the same dictionary but with the following values:
> 
> s[0]=[3]
> s[10]=[22,23,24]
> s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
> 
> It doesn't matter which value gets removed as long as there is only
> one remaining, so in this example it doesn't matter that 2 got removed
> from s[0] or from s[30] as long as there is only one 2 in the
> dictionary.
> 
So if the number is a key, you want to keep the key, and delete all
matching values, and if the number is not a key, you want to keep one
(any one) instance of that number?  I'm not sure that what you are
looking for is best represented by a dict.  You might want to consider
creating your own class and overriding __getitem__.


> 2.  I need to be able to loop over the values in the dictionary when
> there are multiple values assigned to each key like above and assign
> new values to those values.  Taking the above example I would want to
> assign a new value so that when you called s[0] it would equal [3,4]
> say if 4 was the new value.  I think this should be as simple as
> adding a value, but I kept on having difficulty.
> 
Here you might want to either use the append() method on the lists of
each entry.

> Any suggestions would be greatly appreciated.
> 
I'm not sure what you are doing maps cleanly to currently existing
datastructures, which means that there might not be a quick shortcut for
you.  Hammer out the specs of what you want your class to be able to do,
and what the API will be for performing each of those functions.  Then
you should be able to begin implementing it, or at least come up with
some more specific questions.



> Thank you very much,
> Krishna

Cheers,
Cliff




From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 23:27:59 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 03:27:59 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
	
	
	<86e09602-7eb1-4397-a77f-fb1e3c5b34b9@k26g2000vbp.googlegroups.com>
Message-ID: 

On Mon, 10 Aug 2009 08:21:03 -0700, Douglas Alan wrote:

> But you're right, it's too late to change this now.

Not really. There is a procedure for making non-backwards compatible 
changes. If you care deeply enough about this, you could agitate for 
Python 3.2 to raise a PendingDepreciation warning for "unexpected" escape 
sequences like \z, Python 3.3 to raise a Depreciation warning, and Python 
3.4 to treat it as an error.

It may even be possible to skip the PendingDepreciation warning and go 
straight for Depreciation warning in 3.2.


-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Mon Aug 10 23:29:20 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 03:29:20 GMT
Subject: With or without leading underscore...
References: <5un5l6-fvn.ln1@satorlaser.homedns.org>
Message-ID: 

On Mon, 10 Aug 2009 16:37:25 +0200, Ulrich Eckhardt wrote:

> ...that is the question!
> 
> I have a module which exports a type. It also exports a function that
> returns instances of that type. Now, the reason for my question is that
> while users will directly use instances of the type, they will not
> create instances of the type themselves.
> 
> So, the type is a part of the public API, but its constructor is not.
> Should I mark the type as private (with a leading underscore) or not?

My opinion is that if you have to ask the question "Should this class be 
private?", then the answer is No.

Only make objects private if you have specific reasons for doing so. I 
know this goes against the advice given by other languages (namely, make 
everything private unless you need it to be public) but Python encourages 
openness and transparency.



-- 
Steven


From hjtoi-better-remove-before-reply at comcast.net  Tue Aug 11 00:25:21 2009
From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen)
Date: Mon, 10 Aug 2009 21:25:21 -0700
Subject: ANN: M2Crypto 0.20
Message-ID: 

I am please to announce the M2Crypto 0.20 release, which was in
development for over nine months. Over 30 bugs fixed by more than ten
people. Download links and bug filing instructions on the homepage at
http://chandlerproject.org/Projects/MeTooCrypto.

M2Crypto is the most complete Python wrapper for OpenSSL featuring RSA,
DSA, DH, HMACs, message digests, symmetric ciphers (including AES); SSL
functionality to implement clients and servers; HTTPS extensions to
Python's httplib, urllib, and xmlrpclib; unforgeable HMAC'ing
AuthCookies for web session management; FTP/TLS client and server;
S/MIME; ZServerSSL: A HTTPS server for Zope and ZSmime: An S/MIME
messenger for Zope. Smartcards supported with the Engine interface.

Changelog:

- Deprecated M2Crypto.PGP subpackage since nobody seems to be using it
nor is it being maintained (if you do use it, please let me know)
- Added fedora_setup.sh to help work around differences on Fedora Core
-based distributions (RedHat, CentOS, ...); thanks to Miloslav Trmac
- Added X509.load_request_bio and load_request_string, by Hartmut Goebel
and Pavel Shramov
- Added alias X509.Request.set_subject for set_subject_name to match
X509.X509, by Pavel Shramov
- OBJ_* wrappers did not work properly with OpenSSL 0.9.8a and earlier,
fix by Pavel Shramov
- Added ASN1_UTCTIME.get_datetime and set_datetime, by Pavel Shramov
- Fixed obj_obj2txt, which returned nonsense, fix by Barney Stratford
- m2urllib did not close sockets properly, fix by Miloslav Trmac
- Allow SSL peer certificate to have subjectAltName without dNSName and
use commonName for hostname check, fix by Miloslav Trmac
- threading_locking_callback did not block on a lock when the lock
  was held by another thread, by Miloslav Trmac
- Allow more blocking OpenSSL functions to run without GIL, by Miloslav
Trmac
- Fixed httpslib to send only the path+query+fragment part of the URL
when using CONNECT proxy, by James Bowes
- SSLServer.__init__ now takes optional bind_and_activate parameter and
  initializes by calling SocketServer.BaseServer.__init__, which
  are Python 2.6 compatibility fixes, by Christian
- ftpslib now works with Python 2.6, by Theodore A. Roth
- httpslib.ProxyHTTPSConnection needs to cast port into integer,
  by John M. Schanck
- Added support for RSASSA-PSS signing and verifying, by Chris Collis
- Added support for disabling padding when using RSA encryption,
  by Chris Collis
- ASN1_INTEGERs can now be larger than fits in an int, for example to
support X509 certificates with large serial numbers, patch by Mikhail
Vorozhtsov and testcase by Barry G.
- Reverted a change done in 0.17 to m2urllib2 which changed urls to
include host when it should stay as it was
- httpslib no longer uses urllib; instead it uses urlparse for url parsing
- SMIME.text_crlf and text_crlf_bio were always raising TypeError; fixed
- EVP.load_key and load_key_bio fixed to raise EVP.EVPError and
BIO.BIOError instead of str (str exceptions not allowed in Python 2.6
and later)
- SSL.Session.load_session fixed to raise SSL.SSLError instead of str
- SMIME.load_pkcs7, load_pkcs7_bio, smime_load_pkcs7,
smime_load_pkcs7_bio, text_crlf, text_crlf_bio fixed to raise
BIO.BIOError, SMIME.PKCS7_Error and SMIME.SMIME_Error as appropriate
instead of str
- Added FIPS mode to unit tests, and used FIPS-compliant key sizes in
other tests, by Miloslav Trmac. Note that tests run much slower because
of this!
- Unit tests cover 80% of the code

-- 
  Heikki Toivonen - http://heikkitoivonen.net


From robert.kern at gmail.com  Tue Aug 11 00:33:03 2009
From: robert.kern at gmail.com (Robert Kern)
Date: Tue, 11 Aug 2009 00:33:03 -0400
Subject: numpy array merge
In-Reply-To: <427654ff-5455-4198-bc86-d810ef3fafd6@t11g2000prh.googlegroups.com>
References: <427654ff-5455-4198-bc86-d810ef3fafd6@t11g2000prh.googlegroups.com>
Message-ID: 

On 2009-08-10 17:38, Nathan wrote:
> Is there an easy way to merge two numpy arrays with different rank
> sizes (terminology?).

You will want to ask numpy questions on the numpy mailing list.

   http://www.scipy.org/Mailing_Lists

I believe that "shape" is the term you are looking for.

> I want to make a single array by concatenating
> two arrays along a given direction and filling the excess cells with a
> dummy variable.  numpy concatenate works well as long as the two
> arrays have the same dimension, but I want to do this on two array
> with a matching dimension size.  An example:
>
> import numpy as np
> a = np.array([[1,2,3],[4,5,6]])
> b = np.array([[1,2],[3,4],[5,6]])
> np.concatenate((a,a),axis=1)  #This works fine, but isn't what I need.
> Out:  array([[1, 2, 3, 1, 2, 3],
>         [4, 5, 6, 4, 5, 6]])
> np.concatenate((a,b),axis=1)  #This doesn't work, but this is what I
> need.
>
> I want to fill the third row of array "a" with a dummy variable (99999
> or NaN) and concatenate with "b" to make:
> [1,2,3,1,2]
> [4,5,6,4,5]
> [99999,99999,99999,5,6]
>
> This just seems like it would be relatively common.  So I thought I'd
> check if I'm missing something before I go write the logic.  Thanks!

I don't believe there is anything that does what you want out-of-box. You will 
probably want to determine the appropriate shape for the final array, use 
empty() to create it, use .fill(nan) (or whatever) to supply the default value, 
then assign the input arrays into the appropriate locations.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco



From nair.jitendra at gmail.com  Tue Aug 11 01:15:31 2009
From: nair.jitendra at gmail.com (jitu)
Date: Mon, 10 Aug 2009 22:15:31 -0700 (PDT)
Subject: Problem when fetching page using urllib2.urlopen
References: <2f1086ba-26ba-42a8-b5de-27581fa853e3@12g2000pri.googlegroups.com>
	
Message-ID: <1002806e-cab7-4e9b-80e4-ab46dff20cdf@b25g2000prb.googlegroups.com>


Yes Piet you were right this works. But seems does not work on google
app engine, since  it appends it own agent info as seen below

'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US;
rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13 AppEngine-Google;
(+http://code.google.com/appengine)'

Any way Thanks . Good to know about the User-Agent field.

Jitu


On Aug 11, 12:36?am, Piet van Oostrum  wrote:
> >>>>> jitu  (j) wrote:
> >j> Hi,
> >j> A html page ?contains 'anchor' elements with 'href' attribute ?having
> >j> a semicolon ?in the url , while fetching the page using
> >j> urllib2.urlopen, all such href's ?containing ?'semicolons' are
> >j> truncated.
> >j> For example the hrefhttp://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt...
> >j> get truncated tohttp://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i
> >j> The page I am talking about can be fetched from
> >j>http://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_...
>
> It's not python that causes this. It is the server that sends you the
> URLs without these parameters (that's what they are).
>
> To get them you have to tell the server that you are a respectable
> browser. E.g.
>
> import urllib2
>
> url = 'http://travel.yahoo.com/p-travelguide-6901959-pune_restaurants-i;_ylt...
>
> url = 'http://travel.yahoo.com/p-travelguide-485468-pune_india_vacations-i;_...
>
> hdrs = {'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.13) Gecko/2009073021 Firefox/3.0.13',
> ? ? ? ?'Accept': 'image/*'}
>
> request = urllib2.Request(url = url, headers = hdrs)
> page = urllib2.urlopen(request).read()
>
> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: p... at vanoostrum.org



From arshakrishnamtech at gmail.com  Tue Aug 11 01:29:29 2009
From: arshakrishnamtech at gmail.com (ArshaKrishna)
Date: Mon, 10 Aug 2009 22:29:29 -0700 (PDT)
Subject: Nltk with python
Message-ID: <82c9f923-1098-4b7e-8f9d-9504c1a8962c@12g2000pri.googlegroups.com>

How can I resolve scope ambiguity using nltk toolkit with python


From cmalmqui at gmail.com  Tue Aug 11 01:54:38 2009
From: cmalmqui at gmail.com (cmalmqui)
Date: Mon, 10 Aug 2009 22:54:38 -0700 (PDT)
Subject: ElementTree - Howto access text within XML tag element...
Message-ID: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>

Hi,

I am writing on a small XML parser and are currently stuck as I am not
able to get the whole element name in ElementTree.

Please see the below example where "print root[0][0]" returns
""

Is there a way to get hold of the "Running" string in the tag using
elementTree?


    
      2009-07-10T14:48:00Z
      
      .........

For those of you that know how to program XML I have another
question:
I am currently "hardcoding" my XML parser using brackets, is this a
good approach or should I build it using a "search on tag" approach.

Thank you for any answers!


From terry.yinzhe at gmail.com  Tue Aug 11 01:59:13 2009
From: terry.yinzhe at gmail.com (Terry)
Date: Mon, 10 Aug 2009 22:59:13 -0700 (PDT)
Subject: How to pickle a lambda function?
Message-ID: <37c55108-083f-4d60-b8a3-9b2b10833ac3@r18g2000yqd.googlegroups.com>

Hi,

I'm trying to implement something like:

remote_map(fun, list)

to execute the function on a remove machine. But the problem is I
cannot pickle a lambda function and send it to the remote machine.

Is there any possible way to pickle (or other method) any functions
including lambda?

br, Terry


From steven at REMOVE.THIS.cybersource.com.au  Tue Aug 11 02:47:32 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 06:47:32 GMT
Subject: Python docs disappointing - group effort to hire	writers?
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	<4A80472E.4090108@stoneleaf.us>
	
Message-ID: 

On Mon, 10 Aug 2009 20:05:00 -0400, David Lyon wrote:

> So, what you're advocating is let things stay how they are...

If it's not broken, don't fix it.


> Ignore feedback... tell people to freak off...

Only useless feedback.


-- 
Steven




From steven at REMOVE.THIS.cybersource.com.au  Tue Aug 11 02:51:28 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 06:51:28 GMT
Subject: variable & scoping question.
References: 
	<7earmtF2f4tvnU1@mid.uni-berlin.de>
	<93c50fc3-2cf9-4fc6-9919-cde7cfd273e6@o35g2000vbi.googlegroups.com>
Message-ID: 

On Mon, 10 Aug 2009 08:46:17 -0700, Cornelius Keller wrote:

> On 10 Aug., 17:12, "Diez B. Roggisch"  wrote:
>> Cornelius Keller wrote:
> [snip]
>>
>> http://effbot.org/zone/default-values.htm
>>
>> Diez
> 
> Ok thank you.
> I' understand now why.
> I still think this is very confusing, because default values don't
> behave like most people would expect without reading the docs.


Really? How do you expect the default value to behave in this example?

>>> import time
>>> def test(x=time.time()):
...     print x
...
>>>
>>> test()
1249972984.33
>>> time.sleep(30)
>>> test()
1249972984.33

You get the same default object each time you call the function, NOT a 
fresh one created. I'm sure I'd be terribly confused if Python re-
evaluated the default value each time I called the function.

There's no difference between this and the case x=[], except that lists 
are mutable and floats aren't. You get the same default list each time, 
it just has different stuff in it. The alternative would be to get a 
different list each time, and that would require re-evaluating the 
default each time the function was called, which is horrible.




-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Tue Aug 11 03:07:13 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 07:07:13 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
Message-ID: 

On Mon, 10 Aug 2009 15:17:24 -0700, Douglas Alan wrote:

> From: Steven D'Aprano  wrote:
> 
>> On Mon, 10 Aug 2009 00:32:30 -0700, Douglas Alan wrote:
> 
>> > In C++, if I know that the code I'm looking at compiles, then I never
>> > need worry that I've misinterpreted what a string literal means.
> 
>> If you don't know what your string literals are, you don't know what
>> your program does. You can't expect the compiler to save you from
>> semantic errors. Adding escape codes into the string literal doesn't
>> change this basic truth.
> 
> I grow weary of these semantic debates. The bottom line is that C++'s
> strategy here catches bugs early on that Python's approach doesn't. It
> does so at no additional cost.
>
> From a purely practical point of view, why would any language not want
> to adopt a zero-cost approach to catching bugs, even if they are
> relatively rare, as early as possible?

Because the cost isn't zero. Needing to write \\ in a string literal when 
you want \ is a cost, and having to read \\ in source code and mentally 
translate that to \ is also a cost. By all means argue that it's a cost 
that is worth paying, but please stop pretending that it's not a cost.

Having to remember that \n is a "special" escape and \y isn't is also a 
cost, but that's a cost you pay in C++ too, if you want your code to 
compile.


By the way, you've stated repeatedly that \y will compile with a warning 
in g++. So what precisely do you get if you ignore the warning? What do 
other C++ compilers do? Apart from the lack of warning, what actually is 
the difference between Python's behaviour and C++'s behaviour?



> (Other than the reason that adopting it *now* is sadly too late.)
> 
> Furthermore, Python's strategy here is SPECIFICALLY DESIGNED, according
> to the reference manual to catch bugs. I.e., from the original posting
> on this issue:
> 
>      Unlike Standard C, all unrecognized escape sequences are left in
>      the string unchanged, i.e., the backslash is left in the string.
>      (This behavior is useful when debugging: if an escape sequence is
>      mistyped, the resulting output is more easily recognized as
>      broken.)

You need to work on your reading comprehension. It doesn't say anything 
about the motivation for this behaviour, let alone that it was 
"SPECIFICALLY DESIGNED" to catch bugs. It says it is useful for 
debugging. My shoe is useful for squashing poisonous spiders, but it 
wasn't designed as a poisonous-spider squashing device.



>> The compiler can't save you from typing 1234 instead of 11234, or 31.45
>> instead of 3.145, or "My darling Ho" instead of "My darling Jo", so why
>> do you expect it to save you from typing "abc\d" instead of "abc\\d"?
> 
> Because in the former cases it can't catch the the bug, and in the
> latter case, it can.

I'm not convinced this is a bug that needs catching, but if you think it 
is, then that's a reasonable argument.



>> Perhaps it can catch *some* errors of that type, but only at the cost
>> of extra effort required to defeat the compiler (forcing the programmer
>> to type \\d to prevent the compiler complaining about \d). I don't
>> think the benefit is worth the cost. You and your friend do. Who is to
>> say you're right?
> 
> Well, Bjarne Stroustrup, for one.

Then let him design his own language *wink*


> All of these are value judgments, of course, but I truly doubt that
> anyone would have been bothered if Python from day one had behaved the
> way that C++ does. 

If I'm reading this page correctly, Python does behave as C++ does. Or at 
least as Larch/C++ does:

http://www.cs.ucf.edu/~leavens/larchc++manual/lcpp_47.html




>> In C++, if you see an escape you don't recognize, do you care?
> 
> Yes, of course I do. If I need to know what the program does.

Precisely the same as in Python.


>> Do you go running for the manual? If the answer is No, then why do it
>> in Python?
> 
> The answer is that I do in both cases.

You deleted without answer my next question:

"And if the answer is Yes, then how is Python worse than C++?"

Seems to me that the answer is "It's not worse than C++, it's the same" 
-- in both cases, you have to memorize the "special" escape sequences, 
and in both cases, if you see an escape you don't recognize, you need to 
look it up.



>> No. \z *is* a legal escape sequence, it just happens to map to \z.
> 
>> If you stop thinking of \z as an illegal escape sequence that Python
>> refuses to raise an error for, the problem goes away. It's a legal
>> escape sequence that maps to backslash + z.
> 
> (1) I already used that argument on my friend, and he wasn't buying it.
> (Personally, I find the argument technically valid, but commonsensically
> invalid. It's a language-lawyer kind of argument, rather than one that
> appeals to any notion of real aesthetics.)

I disagree with your sense of aesthetics. I think that having to write 
\\y when I want \y just to satisfy a bondage-and-discipline compiler is 
ugly. That's not to deny that B&D isn't useful on occasion, but in this 
case I believe the benefit is negligible, and so even a tiny cost is not 
worth the pain.

The sweet sweet pain... oh wait, sorry, wrong newsgroup...



> (2) That argument disagrees with the Python reference manual, which
> explicitly states that "unrecognized escape sequences are left in the
> string unchanged", and that the purpose for doing so is because it "is
> useful when debugging".

How does it disagree? \y in the source code mapping to \y in the string 
object is the sequence being left unchanged. And the usefulness of doing 
so is hardly a disagreement over the fact that it does so.



>> > "\x" is not a legal escape sequence. Shouldn't it also get left as
>> > "\\x"?
>>
>> No, because it actually is an illegal escape sequence.
> 
> What makes it "illegal". As far as I can tell, it's just another
> "unrecognized escape sequence". 

No, it's recognized, because \x is the prefix for an hexadecimal escape 
code. And it's illegal, because it's missing the actual hexadecimal 
digits.


> JavaScript treats it that way. Are you
> going to be the one to tell all the JavaScript programmers that their
> language can't tell a legal escape sequence from an illegal one?

Well, it is Javascript... 

All joking aside, syntax varies from one language to another. What counts 
as a legal escape sequence in Javascript and what counts as a legal 
escape sequence in Python are different. What makes you think I'm talking 
about Javascript?


>> > Well, I think he's more annoyed that if Python is going to be so
>> > helpful as to put in the missing "\" for you in "foo\zbar", then it
>> > should put in the missing "\" for you in "\". He considers this to be
>> > an inconsistency.
>>
>> (1) There is no missing \ in "foo\zbar".
>>
>> (2) The problem with "\" isn't a missing backslash, but a missing end-
>> quote.
> 
> Says who? All of this really depends on your point of view. The whole
> morass goes away completely if one adopts C++'s approach here.

But the morass only exists in the first place because you have adopted 
C++'s approach instead of Python's approach -- and (possibly) not even a 
standard part of the C++ approach, but a non-standard warning provided by 
one compiler out of many.


Even if you disagree about (1), it's easy enough to prove that (2) is 
correct:

>>> "\"
  File "", line 1
    "\"
      ^
SyntaxError: EOL while scanning single-quoted string


This is the exact same error you get here:


>>> "a
  File "", line 1
    "a
     ^
SyntaxError: EOL while scanning single-quoted string



>> Python isn't DWIMing here. The rules are simple and straightforward,
>> there's no mind-reading or guessing required.
> 
> It may not be a complex form of DWIMing, but it's still DWIMing a bit.
> Python is figuring that if I typed "\z", then either I must have really
> meant to type "\\z", 

Nope, not in the least. Python NEVER EVER EVER tries to guess what you 
mean.

If you type "xyz", it assumes you want "xyz".

If you type "xyz\n", it assumes you want "xyz\n".

If you type "xyz\\n", it assumes you want "xyz\\n".

If you type "xyz\y", it assumes you want "xyz\y".

If you type "xyz\\y", it assumes you want "xyz\\y".

This is *exactly* like C++, except that in Python the semantics of \y and 
\\y are identical. Python doesn't guess what you mean, it *imposes* a 
meaning on the escape sequence. You just don't like that meaning.



> or that I want to see the backslash when I'm
> debugging because I made a mistake, or that I'm just too lazy to type
> "\\z".

Oh jeez, if you're going to define DWIM so broadly, then *everything* is 
DWIM. "If I type '1+2', then the C++ compiler figures out that I must 
have wanted to add 1 and 2..."


> I don't know if my friend even knows the term DWIM, other than me
> paraphrasing him, but I certainly understand all about the term. It
> comes from InterLisp. When DWIM was enabled, your program would run
> until it hit an error, and for certain kinds of errors, it would wait a
> few seconds for the user to notice the error message, and if the user
> didn't tell the program to stop, it would try to figure out what the
> user most likely meant, and then continue running using the
> computer-generated "fix".

Right. And Python isn't doing anything even remotely similar to that.



> I.e., more or less like continuing on in the face of what the Python
> Reference manual refers to as an "unrecognized escape sequence".

The wording could be better, I accept. It would be better to talk about 
"special escapes" (e.g. \n) and "any non-special escape" (e.g. \y).




-- 
Steven


From nad at acm.org  Tue Aug 11 03:13:07 2009
From: nad at acm.org (Ned Deily)
Date: Tue, 11 Aug 2009 00:13:07 -0700
Subject: ElementTree - Howto access text within XML tag element...
References: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
Message-ID: 

In article 
<1ad8dac1-8fff-493a-a197-d847e7b6a761 at c2g2000yqi.googlegroups.com>,
 cmalmqui  wrote:
> I am writing on a small XML parser and are currently stuck as I am not
> able to get the whole element name in ElementTree.
> 
> Please see the below example where "print root[0][0]" returns
> ""
> 
> Is there a way to get hold of the "Running" string in the tag using
> elementTree?
> 
> 
>     
>       2009-07-10T14:48:00Z
>       
>       .........

"Running" is the value of the "Sport" attribute of the "Activity" 
element.  The documentation for the Element interface lists several ways 
to access element attributes; in your example,

>>> elem = root[0][0]
>>> elem.get("Sport")
'Running'
>>> elem.attrib
{'Sport': 'Running'}
>>> elem.items()
[('Sport', 'Running')]

See http://docs.python.org/library/xml.etree.elementtree.html

-- 
 Ned Deily,
 nad at acm.org



From duncan.booth at invalid.invalid  Tue Aug 11 03:42:06 2009
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 11 Aug 2009 07:42:06 GMT
Subject: How to pickle a lambda function?
References: <37c55108-083f-4d60-b8a3-9b2b10833ac3@r18g2000yqd.googlegroups.com>
Message-ID: 

Terry  wrote:

> I'm trying to implement something like:
> 
> remote_map(fun, list)
> 
> to execute the function on a remove machine. But the problem is I
> cannot pickle a lambda function and send it to the remote machine.
> 
> Is there any possible way to pickle (or other method) any functions
> including lambda?
> 

You can pickle any named functions that are declared at module scope.

You cannot pickle anonymous functions, methods, or functions declared 
nested inside other functions. The function must be present in the same 
module when you unpickle it, and if the definition has changed between 
pickling and unpickling the new definition will be used (just as other 
instances will use the current class definition not the one they were 
pickled with).

You probably could pickle some of the components needed to create your 
lambda and construct a new function from it when unpickling: try the code 
object, the name of the module to be used for the globals, and default 
arguments. I don't think you can pickle the closure so better make sure 
your lambda doesn't need one, and be very careful to ensure that you 
restore the pickle in the same version of Python otherwise the code object 
might break. Best just avoid this and use named functions for anything that 
needs pickling.

-- 
Duncan Booth http://kupuguy.blogspot.com


From solipsis at pitrou.net  Tue Aug 11 03:47:39 2009
From: solipsis at pitrou.net (Antoine Pitrou)
Date: Tue, 11 Aug 2009 07:47:39 +0000 (UTC)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
Message-ID: 

r  gmail.com> writes:
> 
> On Aug 9, 11:02?pm, David Lyon  wrote:
> > Since you're talking about documentation, which is a part of python,
> > don't you think you should be discussing it on python-dev ?
> 
> Yea, them's be a friendly bunch to noob ideas ;). Hey i got a better
> idea, lets go to the IRS and see if we can persuade them to stop
> taxing us...

You know, the most interesting thing in this thread is certainly its title :
? Social problems of Python doc ?

Yes, the little social problem here should be clear: if you have complaints to
voice or improvements to suggest to the Python docs, you should do so on the
issue tracker (*). For most topics, this is the only reasonable way to signal
problems to the Python developers community, and so it is in most free software
/ open source projects.

Just because you are able to write tongue-in-cheek (**) comments on python-list
or, even worse, on a third party website, and generate a long thread about how
Python doc (supposedly) s*cks
1) doesn't mean there is a legitimate issue (we all know how people can quickly
inflame about empty subjects)
2) even though there can be a legitimate issue, doesn't mean Python developers
will go out of their way and parse the entirety of the messages to find
potentially useful data in them. The bug tracker is the place for this, and it's
your task, if you want to help, to submit suggestions in it.

FYI, the Python doc is very actively maintained nowadays, and bug reports /are/
taken into account. If you think you've got a lot of time for ranting about how
the doc sucks, but don't want to spend the couple of minutes needed to post
issues on the bug tracker, it speaks a lot about your motivation. Admittedly, in
every successful community, there are attention seekers who are not interested
in actual participation.

(*) http://bugs.python.org

(**) yes, humour is fine, but it doesn't replace actual, informational content


Antoine.




From deets at nospam.web.de  Tue Aug 11 03:51:02 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Tue, 11 Aug 2009 09:51:02 +0200
Subject: ElementTree - Howto access text within XML tag element...
In-Reply-To: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
References: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
Message-ID: <7ecm77F2fbf71U1@mid.uni-berlin.de>

cmalmqui schrieb:
> Hi,
> 
> I am writing on a small XML parser and are currently stuck as I am not
> able to get the whole element name in ElementTree.
> 
> Please see the below example where "print root[0][0]" returns
> ""
> 
> Is there a way to get hold of the "Running" string in the tag using
> elementTree?
> 
> 
>     
>       2009-07-10T14:48:00Z
>       
>       .........
> 
> For those of you that know how to program XML I have another
> question:
> I am currently "hardcoding" my XML parser using brackets, is this a
> good approach or should I build it using a "search on tag" approach.

What do you mean by that - hardcoding by brackets?

Diez


From breamoreboy at yahoo.co.uk  Tue Aug 11 03:56:39 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 08:56:39 +0100
Subject: Social problems of Python doc [was Re: Python docs disappointing]
In-Reply-To: 
References: 	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>		<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
Message-ID: 

Antoine Pitrou wrote:
> r  gmail.com> writes:
>> On Aug 9, 11:02 pm, David Lyon  wrote:
>>> Since you're talking about documentation, which is a part of python,
>>> don't you think you should be discussing it on python-dev ?
>> Yea, them's be a friendly bunch to noob ideas ;). Hey i got a better
>> idea, lets go to the IRS and see if we can persuade them to stop
>> taxing us...
> 
> You know, the most interesting thing in this thread is certainly its title :
> ? Social problems of Python doc ?
> 
> Yes, the little social problem here should be clear: if you have complaints to
> voice or improvements to suggest to the Python docs, you should do so on the
> issue tracker (*). For most topics, this is the only reasonable way to signal
> problems to the Python developers community, and so it is in most free software
> / open source projects.
> 
> Just because you are able to write tongue-in-cheek (**) comments on python-list
> or, even worse, on a third party website, and generate a long thread about how
> Python doc (supposedly) s*cks
> 1) doesn't mean there is a legitimate issue (we all know how people can quickly
> inflame about empty subjects)
> 2) even though there can be a legitimate issue, doesn't mean Python developers
> will go out of their way and parse the entirety of the messages to find
> potentially useful data in them. The bug tracker is the place for this, and it's
> your task, if you want to help, to submit suggestions in it.
> 
> FYI, the Python doc is very actively maintained nowadays, and bug reports /are/
> taken into account. If you think you've got a lot of time for ranting about how
> the doc sucks, but don't want to spend the couple of minutes needed to post
> issues on the bug tracker, it speaks a lot about your motivation. Admittedly, in
> every successful community, there are attention seekers who are not interested
> in actual participation.
> 
> (*) http://bugs.python.org
> 
> (**) yes, humour is fine, but it doesn't replace actual, informational content
> 
> 
> Antoine.
> 
> 
Thank you for this fine, cultured, reasonable response.  Seriously!!!

-- 
Kindest regards.

Mark Lawrence.



From terry.yinzhe at gmail.com  Tue Aug 11 04:16:14 2009
From: terry.yinzhe at gmail.com (Terry)
Date: Tue, 11 Aug 2009 01:16:14 -0700 (PDT)
Subject: How to pickle a lambda function?
References: <37c55108-083f-4d60-b8a3-9b2b10833ac3@r18g2000yqd.googlegroups.com>
	
Message-ID: 

On Aug 11, 3:42?pm, Duncan Booth  wrote:
> Terry  wrote:
> > I'm trying to implement something like:
>
> > remote_map(fun, list)
>
> > to execute the function on a remove machine. But the problem is I
> > cannot pickle a lambda function and send it to the remote machine.
>
> > Is there any possible way to pickle (or other method) any functions
> > including lambda?
>
> You can pickle any named functions that are declared at module scope.
>
> You cannot pickle anonymous functions, methods, or functions declared
> nested inside other functions. The function must be present in the same
> module when you unpickle it, and if the definition has changed between
> pickling and unpickling the new definition will be used (just as other
> instances will use the current class definition not the one they were
> pickled with).
>
> You probably could pickle some of the components needed to create your
> lambda and construct a new function from it when unpickling: try the code
> object, the name of the module to be used for the globals, and default
> arguments. I don't think you can pickle the closure so better make sure
> your lambda doesn't need one, and be very careful to ensure that you
> restore the pickle in the same version of Python otherwise the code object
> might break. Best just avoid this and use named functions for anything that
> needs pickling.
>
> --
> Duncan Boothhttp://kupuguy.blogspot.com

Yes, I'm think of pickle (actually marshal) the code object. Otherwise
I have to use string and eval:-(

The reason I need to be able to pickle any function is because I want
my remote machine knows nothing about the function before receiving
it, so I don't need to update the source code in the remote machine
very often.

br, terry


From sjmachin at lexicon.net  Tue Aug 11 04:17:00 2009
From: sjmachin at lexicon.net (John Machin)
Date: Tue, 11 Aug 2009 01:17:00 -0700 (PDT)
Subject: Problem Regarding Handling of Unicode string
References: <9ac0e194-9e25-468a-9807-957ef3142dd3@i18g2000pro.googlegroups.com>
Message-ID: <47b265c5-e71f-4018-815a-0bfbea927a4a@y28g2000prd.googlegroups.com>

On Aug 10, 9:26?pm, joy99  wrote:
> Dear Group,
>
> I am using Python26 on WindowsXP with service pack2. My GUI is IDLE.
> I am using Hindi resources and get nice output like:
> ??
> where I can use all the re functions and other functions without doing
> any transliteration,etc.
> I was trying to use Bengali but it is giving me output like:

WHAT is giving you this output?

> '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95'

In a very ordinary IDLE session (Win XP SP3, Python 2.6.2, locale:
Australia/English, no "Hindi resources"):

>>> x = '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95'
>>> ux = x.decode('utf-8')
>>> ux
u'\ufeff\u0985\u09a8\u09c7\u0995'
>>> print ux
????? # looks like what you wanted; please confirm
>>> import unicodedata
>>> for c in ux:
	print unicodedata.name(c)


ZERO WIDTH NO-BREAK SPACE # this is a BOM
BENGALI LETTER A
BENGALI LETTER NA
BENGALI VOWEL SIGN E
BENGALI LETTER KA
>>>

> I wanted to see Bengali output as
> ????
> and I like to use all functions including re.
> If any one can help me on that.

"I am using Hindi resources" doesn't tell us much ... except to prompt
the comment that perhaps if you want to display Bengali script, you
may need Bengali resources. However it looks like I can display your
Bengali data without any special resources.

It seems like you are not doing the same with Bengali as you are doing
with Hindi. We can't help you very much if you don't show exactly what
you are doing.

Have you considered asking in an Indian Python forum? Note: you will
still need to say what you are doing that works with Hindi but not
with Bengali.

Cheers,
John


From bruno.42.desthuilliers at websiteburo.invalid  Tue Aug 11 04:41:25 2009
From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers)
Date: Tue, 11 Aug 2009 10:41:25 +0200
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com>
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	
	<081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com>
Message-ID: <4a812e8d$0$27778$426a74cc@news.free.fr>

r a ?crit :
(snip)
> 
> A little note for tutorial writers:
> ==================================
> 
> Dear Expert,
> Whilst writing any tutorial on any subject matter please remember, you
> may be an expert, but mostly *non-experts* will be reading your
> material... 

I can only second Paul on this : just like the K&R, Python's official 
tutorial targets experienced programmers, not total noobies.



From bruno.42.desthuilliers at websiteburo.invalid  Tue Aug 11 04:46:19 2009
From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers)
Date: Tue, 11 Aug 2009 10:46:19 +0200
Subject: With or without leading underscore...
In-Reply-To: <4d6719e4-217a-4921-bd26-228fd4944eb7@r24g2000vbn.googlegroups.com>
References: <5un5l6-fvn.ln1@satorlaser.homedns.org>
	<4d6719e4-217a-4921-bd26-228fd4944eb7@r24g2000vbn.googlegroups.com>
Message-ID: <4a812fb2$0$27778$426a74cc@news.free.fr>

Carl Banks a ?crit :
(snip)


> class A(object):
>     def __init__(self,*args,**kwargs):
>         raise TypeError('Type not callable; use factory function
> instead')
> 
>     @classmethod
>     def _create_object(cls,initial_value):
>         self = object.__new__(cls) # avoid __init__
>         self.value = initial_value

I assume there's a missing "return self" line here ?-)


From Brian.Mingus at colorado.edu  Tue Aug 11 04:49:01 2009
From: Brian.Mingus at colorado.edu (Brian)
Date: Tue, 11 Aug 2009 02:49:01 -0600
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
References: 
	
	
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
Message-ID: <9839a05c0908110149paa2eddbue3880037e0fded3f@mail.gmail.com>

On Fri, Jul 31, 2009 at 6:12 PM, Kee Nethery  wrote:

> I too find the Python docs not very useful and it really slows down my
> learning curve.
>
> I wonder if it would make sense to find good tech writers, get a quotes,
> and get some professionally written documentation WITH LOTS OF EXAMPLES
> added to the standard Python documentation tree.
>
> I'd chip in money for that task. I've certainly spent enough buying Python
> books to where it would be very reasonable to chip in the cost of one book
> towards this project. Get enough people ... could be a great thing.
>
> Even though it is not the version I use, I would suggest that the really
> detailed docs with lots of examples be written against the latest python
> version.
>
> Just a thought.
>
> Kee Nethery
> --
> http://mail.python.org/mailman/listinfo/python-list
>

One thing I really like about the PHP docs is the built in forums. User
feedback on documentation is invaluable.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From zhongshq at gmail.com  Tue Aug 11 04:49:40 2009
From: zhongshq at gmail.com (zhongshq)
Date: Tue, 11 Aug 2009 01:49:40 -0700 (PDT)
Subject: Is there any package implanation the following arithmetics?
Message-ID: 

Hi,

I wonder if there has any package can check whether two rectangles are
overlap, is a dot inside or outside a polygon, etc.

Thanks a lot!


From vinay_sajip at yahoo.co.uk  Tue Aug 11 06:23:00 2009
From: vinay_sajip at yahoo.co.uk (Vinay Sajip)
Date: Tue, 11 Aug 2009 03:23:00 -0700 (PDT)
Subject: Need help in configuration for TimedRotatingFileHandler
References: <7e6938ce-91c9-4b65-980f-46d76bf69220@d36g2000prb.googlegroups.com>
	<4A7F3C83.1040607@ieee.org>
	 
	 
	
Message-ID: 

On Aug 10, 3:52?pm, Dave Angel  wrote:
> Lokesh Maremalla wrote:
> > Traceback (most recent call last):
> > ? File "c:\Python25\lib\logging\handlers.py", line 74, in emit
> > ? ? self.doRollover()
> > ? File "c:\Python25\lib\logging\handlers.py", line 274, in doRollover
> > ? ? os.rename(self.baseFilename, dfn)
> > WindowsError: [Error 32] The process cannot access the file because it is
> > being used by another process
>
> Generally speaking, this error on os.rename() will occur if you haven't
> properly closed the file first, and if I recall correctly, Unix would
> have permitted a rename on an open file. ?You're on Windows. ?However, I
> don't know how that works with theloggingpackage. ?If the program has
> terminated, and you run it a second time on the following day (or after
> changing the system time), then I'd expect no trouble. ?But I'm guessing
> your program is still running, and you just want to change fromlogging
> to yesterday's file tologgingto today's file.
>
> If I had to guess, I'd say that you have two instances of the logger
> running, and the second one is still holding the handle open. ?But
> that's just a wild guess.
>

It's certainly possible that there are two instances of the handler,
which would cause this problem. Other things which might cause this
problem are the file handle inherited by a child process, an anti-
virus scanner having the file open for scanning (anti-virus scanners
often scan files which have just been written, like log files) and
indexing software such as Google Desktop or Windows' own indexing
service.

I would advise using sysinternals tools such as FileMon and Handle to
see what's holding the file open.

Regards,


Vinay Sajip


From scholz.lothar at gmail.com  Tue Aug 11 06:45:10 2009
From: scholz.lothar at gmail.com (llothar)
Date: Tue, 11 Aug 2009 03:45:10 -0700 (PDT)
Subject: UML for Python or some other Graphical Notation Language
Message-ID: <2eabd7a9-2517-41b3-a3be-183171c04372@2g2000prl.googlegroups.com>

This is more an academic question right now but was there ever some
work in progress how UML could be made better for Python or script
languages in general.

It is so extremely deep interwoven with Java/C++ language
implementations that there are a lot of modified notiations necessary.

Or is there anything else then UML?
Eiffel still has BON for example.


From helvinlui at gmail.com  Tue Aug 11 07:22:13 2009
From: helvinlui at gmail.com (Helvin)
Date: Tue, 11 Aug 2009 04:22:13 -0700 (PDT)
Subject: Search and write to .txt file
Message-ID: 

Hi everyone,

I am writing some python script that should find a line which contains
'1' in the data.txt file, then be able to move a certain number of
lines down, before replacing a line. At the moment, I am able to find
the line '1', but when I use f.seek to move, and then rewrite, what I
write goes to the end of the .txt file, instead of being adjusted by
my f.seek.

Do you know what way I should take?

Data.txt is a file of 3 lines:
   line1
   line2
   line3

Code:

   with open('data.txt', 'r+') as f:
       firstread = f.readlines()   # Take a snapshot of initial file

       f.seek(0,0)    # Go back to beginning and search
       for line in f:
           print line
           if line.find('1'):
               print 'line matched'
               f.seek(1,1)       # Move one space along
               f.write('house\n')     # f.write overwrites the exact
number of bytes.
               break                    # leave loop once '1' is found

       f.seek(0,0)              # Go back to beginning, and read
data.txt again
       lastread = f.readlines()

       print 'firstread is', firstread
       print 'lastread is', lastread

This shouldn't be too difficult, but I don't know how. > <
Help appreciated!


From lujan at ceam.es  Tue Aug 11 07:26:42 2009
From: lujan at ceam.es (=?ISO-8859-1?Q?Alonso_Luj=E1n_Torres_Ta=F1o?=)
Date: Tue, 11 Aug 2009 13:26:42 +0200
Subject: add fields in a existing dbf
Message-ID: <4A815572.1020905@ceam.es>

Hi!

I'm trying to modify a dbf adding a new field in a python script, but I 
can't.

Just I can add a field in new dbf created in the same script.

I tryed with:

    db = dbf.Dbf("../filesource.dbf",new =False, readOnly=False)
    ...
    db.addField(("PESO","N",32,8))

and return error:

    Traceback (most recent call last):
      File "script.py", line 34, in 
        db.addField(("PESO","N",32,8))
      File "/usr/lib/python2.5/site-packages/dbfpy/dbf.py", line 229, in
    addField
        "structure can't be changed")
    TypeError: ('At least one record was added, ', "structure can't be
    changed")


I have not idea of what error I make.

If someone can help me, I'll so gratefull.

Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From kushal.kumaran+python at gmail.com  Tue Aug 11 07:34:35 2009
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Tue, 11 Aug 2009 17:04:35 +0530
Subject: Search and write to .txt file
In-Reply-To: 
References: 
Message-ID: <1e364c4e0908110434m52701b64vebca82dbbec8d300@mail.gmail.com>

On Tue, Aug 11, 2009 at 4:52 PM, Helvin wrote:
> Hi everyone,
>
> I am writing some python script that should find a line which contains
> '1' in the data.txt file, then be able to move a certain number of
> lines down, before replacing a line. At the moment, I am able to find
> the line '1', but when I use f.seek to move, and then rewrite, what I
> write goes to the end of the .txt file, instead of being adjusted by
> my f.seek.
>
> Do you know what way I should take?
>

It might be easier to read the file into a list of lines (using
readlines, as you do in your code already), make your change there and
write it back to a file.  If your file is indeed as small as you
indicate below, that should be significantly easier.

> Data.txt is a file of 3 lines:
> ? line1
> ? line2
> ? line3
>
> Code:
>
> ? with open('data.txt', 'r+') as f:
> ? ? ? firstread = f.readlines() ? # Take a snapshot of initial file
>
> ? ? ? f.seek(0,0) ? ?# Go back to beginning and search
> ? ? ? for line in f:
> ? ? ? ? ? print line
> ? ? ? ? ? if line.find('1'):
> ? ? ? ? ? ? ? print 'line matched'
> ? ? ? ? ? ? ? f.seek(1,1) ? ? ? # Move one space along
> ? ? ? ? ? ? ? f.write('house\n') ? ? # f.write overwrites the exact
> number of bytes.
> ? ? ? ? ? ? ? break ? ? ? ? ? ? ? ? ? ?# leave loop once '1' is found
>
> ? ? ? f.seek(0,0) ? ? ? ? ? ? ?# Go back to beginning, and read
> data.txt again
> ? ? ? lastread = f.readlines()
>
> ? ? ? print 'firstread is', firstread
> ? ? ? print 'lastread is', lastread
>
> This shouldn't be too difficult, but I don't know how. > <
> Help appreciated!


From davea at ieee.org  Tue Aug 11 07:37:25 2009
From: davea at ieee.org (Dave Angel)
Date: Tue, 11 Aug 2009 07:37:25 -0400
Subject: dictionary help
In-Reply-To: <4A809AF80200008C000149EC@redhorse.forestry.uga.edu>
References: <4A809AF80200008C000149EC@redhorse.forestry.uga.edu>
Message-ID: <4A8157F5.1010103@ieee.org>

Krishna Pacifici wrote:
> Hi,
> kind of a newbie here, but I have two questions that are probably pretty simple.
>
> 1.  I need to get rid of duplicate values that are associated with different keys in a dictionary.  For example I have the following code.
> s={}
> s[0]=[10,2,3]
>  s[10]=[22,23,24]
>  s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
>
> Now I want to be able to loop through the primary keys and get rid of duplicates (both in keys and values) so that I would have either a new dictionary or the same dictionary but with the following values:
>
> s[0]=[3]
>  s[10]=[22,23,24]
>  s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
>
> It doesn't matter which value gets removed as long as there is only one remaining, so in this example it doesn't matter that 2 got removed from s[0] or from s[30] as long as there is only one 2 in the dictionary.
>
> 2.  I need to be able to loop over the values in the dictionary when there are multiple values assigned to each key like above and assign new values to those values.  Taking the above example I would want to assign a new value so that when you called s[0] it would equal [3,4] say if 4 was the new value.  I think this should be as simple as adding a value, but I kept on having difficulty.
>
> Any suggestions would be greatly appreciated.
>
> Thank you very much,
> Krishna
>
>
>   
Sounds like homework.  If it was for an unconstrained project, I'd 
design a different data structure, one that directly enforced the data 
constraints.  So far, I can't imagine a useful reason for this 
particular set of constraints.

Let's break the problems down.

1a)   Do you know how to write a loop that visits all the keys of a 
dictionary?
1b)  Do you know how to safely check if a particular key exists?     
e.g.      if   key in s:
1c)  Do you know how to collect a set of values, so that when a 
duplicate is found, it can be recognized as such?
1d) Do you know how to remove an item from a list?

2a)  Like 1a)
2b) Do you know how to append a value to the end of a list?  Is s[key] a 
list?


DaveA



From deets at nospam.web.de  Tue Aug 11 07:49:04 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Tue, 11 Aug 2009 13:49:04 +0200
Subject: UML for Python or some other Graphical Notation Language
References: <2eabd7a9-2517-41b3-a3be-183171c04372@2g2000prl.googlegroups.com>
Message-ID: <7ed45gF2evk04U1@mid.uni-berlin.de>

llothar wrote:

> This is more an academic question right now but was there ever some
> work in progress how UML could be made better for Python or script
> languages in general.
> 
> It is so extremely deep interwoven with Java/C++ language
> implementations that there are a lot of modified notiations necessary.
> 
> Or is there anything else then UML?
> Eiffel still has BON for example.

http://fptiny.blogspot.com/2008/03/rad-with-tiny-erp.html

Diez


From skip at pobox.com  Tue Aug 11 08:40:31 2009
From: skip at pobox.com (skip at pobox.com)
Date: Tue, 11 Aug 2009 07:40:31 -0500 (CDT)
Subject: test message
Message-ID: <20090811124031.4B11911ACFB4@montanaro.dyndns.org>

Sorry for the low content email.  Testing the mail-to-news gateway on
mail.python.org.  Don't flame me for not using a test newsgroup. ;-)

-- 
Skip Montanaro - skip at pobox.com - http://www.smontanaro.net/
    Getting old sucks, but it beats dying young


From skip.montanaro at gmail.com  Tue Aug 11 09:00:54 2009
From: skip.montanaro at gmail.com (Skip Montanaro)
Date: Tue, 11 Aug 2009 06:00:54 -0700 (PDT)
Subject: test message
References: 
Message-ID: <7e0b6c26-b95d-48a5-a16e-bbbc7361f240@c34g2000yqi.googlegroups.com>

On Aug 11, 7:40?am, s... at pobox.com wrote:
> Sorry for the low content email. ?Testing the mail-to-news gateway on
> mail.python.org. ?Don't flame me for not using a test newsgroup. ;-)

Posting a followup to test the return path (news-to-mail).

S


From piet at cs.uu.nl  Tue Aug 11 09:30:12 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Tue, 11 Aug 2009 15:30:12 +0200
Subject: Search and write to .txt file
References: 
Message-ID: 

>>>>> Helvin  (H) wrote:

>H> Hi everyone,
>H> I am writing some python script that should find a line which contains
>H> '1' in the data.txt file, then be able to move a certain number of
>H> lines down, before replacing a line. At the moment, I am able to find
>H> the line '1', but when I use f.seek to move, and then rewrite, what I
>H> write goes to the end of the .txt file, instead of being adjusted by
>H> my f.seek.

>H> Do you know what way I should take?

>H> Data.txt is a file of 3 lines:
>H>    line1
>H>    line2
>H>    line3

>H> Code:

>H>    with open('data.txt', 'r+') as f:
>H>        firstread = f.readlines()   # Take a snapshot of initial file

>H>        f.seek(0,0)    # Go back to beginning and search
>H>        for line in f:
>H>            print line
>H>            if line.find('1'):
>H>                print 'line matched'
>H>                f.seek(1,1)       # Move one space along
>H>                f.write('house\n')     # f.write overwrites the exact
>H> number of bytes.
>H>                break                    # leave loop once '1' is found

Mixing an iterator on the file with direct calls (seek/write) isn't
going to work. The iterator does read ahead which causes the file
position not to be what you think it is.

See:

>>> with open('data.txt', 'r+') as f:
...   for line in f:
...       print line, f.tell()
... 
line1
18
line2
18
line3
18

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From bmorab at gmail.com  Tue Aug 11 09:49:58 2009
From: bmorab at gmail.com (telekab1@hotmail.com)
Date: Tue, 11 Aug 2009 06:49:58 -0700 (PDT)
Subject: Extracting matrix from a text file
Message-ID: 

Hello to all!!

I am new in python, and I am running it on Mac with Smultron editor. I
need to read a textfile that includes numbers (in a matrix form),
indexes, and strings, like this:

Marsyas-kea distance matrix for MIREX 2007 Audio Similarity Exchange
Q/R        1                   2                   3
4                5
1        0                  4.54592        4.36685
5.29463        3.85728
2        4.54592        0                  3.97667
5.02151        4.64284
3        4.36685        3.97667        0
4.98743        4.83683
4        5.29463        5.02151        4.98743
0                  6.04393
5        3.85728        4.64284        4.83683        6.04393        0

My code to get this information is:

matrix = open("dmatrix_5.txt");

while 1:
    mat = matrix.readline()
    if not mat:
    	break
    pass # do something
    print mat



So I just want to keep the matrix in the "middle" for math
computations.

        0                  4.54592        4.36685
5.29463        3.85728
        4.54592        0                  3.97667
5.02151        4.64284
        4.36685        3.97667        0
4.98743        4.83683
        5.29463        5.02151        4.98743
0                  6.04393
        3.85728        4.64284        4.83683        6.04393        0


I've seen and tried a lot of ways, like split or isinstance.. but
never get the wanted result.... does anyone have an idea, or hint?
Thank you once more for your help!

Best Regards,
Bea


From piet at cs.uu.nl  Tue Aug 11 09:50:01 2009
From: piet at cs.uu.nl (Piet van Oostrum)
Date: Tue, 11 Aug 2009 15:50:01 +0200
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
Message-ID: 

>>>>> Steven D'Aprano  (SD) wrote:

>SD> If I'm reading this page correctly, Python does behave as C++ does. Or at 
>SD> least as Larch/C++ does:

>SD> http://www.cs.ucf.edu/~leavens/larchc++manual/lcpp_47.html

They call them `non-standard escape sequences' for a reason: that they
are not in standard C++.

test.cpp:
char* temp = "abc\yz";

TEMP> g++ -c test.cpp
test.cpp:1:1: warning: unknown escape sequence '\y'

-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org


From breamoreboy at yahoo.co.uk  Tue Aug 11 09:52:29 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 14:52:29 +0100
Subject: Search and write to .txt file
In-Reply-To: 
References: 
Message-ID: 

Helvin wrote:
> Hi everyone,
> 
> I am writing some python script that should find a line which contains
> '1' in the data.txt file, then be able to move a certain number of
> lines down, before replacing a line. At the moment, I am able to find
> the line '1', but when I use f.seek to move, and then rewrite, what I
> write goes to the end of the .txt file, instead of being adjusted by
> my f.seek.
> 
> Do you know what way I should take?
> 
> Data.txt is a file of 3 lines:
>    line1
>    line2
>    line3
> 
> Code:
> 
>    with open('data.txt', 'r+') as f:
>        firstread = f.readlines()   # Take a snapshot of initial file
> 
>        f.seek(0,0)    # Go back to beginning and search
>        for line in f:
>            print line
>            if line.find('1'):
>                print 'line matched'
>                f.seek(1,1)       # Move one space along
>                f.write('house\n')     # f.write overwrites the exact
> number of bytes.
>                break                    # leave loop once '1' is found
> 
>        f.seek(0,0)              # Go back to beginning, and read
> data.txt again
>        lastread = f.readlines()
> 
>        print 'firstread is', firstread
>        print 'lastread is', lastread
> 
> This shouldn't be too difficult, but I don't know how. > <
> Help appreciated!
You can't mix and match the file iterator "for line in f" with the seek 
method.  You already have the data in firstread, why not process it from 
there, i.e. "for line in firstread".  Also look at the docs for the find 
method, it doesn't return what you think it does.

-- 
Kindest regards.

Mark Lawrence.



From breamoreboy at yahoo.co.uk  Tue Aug 11 10:04:31 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 15:04:31 +0100
Subject: Extracting matrix from a text file
In-Reply-To: 
References: 
Message-ID: 

telekab1 at hotmail.com wrote:
> Hello to all!!
> 
> I am new in python, and I am running it on Mac with Smultron editor. I
> need to read a textfile that includes numbers (in a matrix form),
> indexes, and strings, like this:
> 
> Marsyas-kea distance matrix for MIREX 2007 Audio Similarity Exchange
> Q/R        1                   2                   3
> 4                5
> 1        0                  4.54592        4.36685
> 5.29463        3.85728
> 2        4.54592        0                  3.97667
> 5.02151        4.64284
> 3        4.36685        3.97667        0
> 4.98743        4.83683
> 4        5.29463        5.02151        4.98743
> 0                  6.04393
> 5        3.85728        4.64284        4.83683        6.04393        0
> 
> My code to get this information is:
> 
> matrix = open("dmatrix_5.txt");
> 
> while 1:
>     mat = matrix.readline()
>     if not mat:
>     	break
>     pass # do something
>     print mat
> 
> 
> 
> So I just want to keep the matrix in the "middle" for math
> computations.
> 
>         0                  4.54592        4.36685
> 5.29463        3.85728
>         4.54592        0                  3.97667
> 5.02151        4.64284
>         4.36685        3.97667        0
> 4.98743        4.83683
>         5.29463        5.02151        4.98743
> 0                  6.04393
>         3.85728        4.64284        4.83683        6.04393        0
> 
> 
> I've seen and tried a lot of ways, like split or isinstance.. but
> never get the wanted result.... does anyone have an idea, or hint?
> Thank you once more for your help!
> 
> Best Regards,
> Bea
I think your best bet is to read and action the responses you got to 
your original email from three days ago.  If these have got lost in the 
post simply search online, they're bound to be archived somewhere.

-- 
Kindest regards.

Mark Lawrence.



From ethan at stoneleaf.us  Tue Aug 11 10:12:17 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Tue, 11 Aug 2009 07:12:17 -0700
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <0985e0fe54bf41fa3736cd6697d42bf4@preisshare.net>
References: 			<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>		<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>			<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	<4A80472E.4090108@stoneleaf.us>
	<0985e0fe54bf41fa3736cd6697d42bf4@preisshare.net>
Message-ID: <4A817C41.2050607@stoneleaf.us>

David Lyon wrote:
> On Mon, 10 Aug 2009 09:13:34 -0700, Ethan Furman 
> wrote:
> 
>>As someone who relies heavily on the docs I will also say that the idea 
>>of giving the ability to modify the official documentation to somebody 
>>who is /learning/ the language is, quite frankly, terrifying.  
> 
> 
> What is more terrifying is the way feedback from newbies is handled.
> 
> Your statement implies that the only way feedback can be handled is
> to throw the keys down in discust and walk away. That's primative
> behaviour. And misleading, because that isn't going to happen.
> 

Allow me to put back the sentence you unfairly snipped:
> I have no issues with a seperate system, some of which have been 
> suggested, but good reference documentation is crucial.  If you find 
> examples lacking, there are plenty of web-sites, or even (dare I say
> it?) actual hard-copy books!  ;)

To be clear, what I am advocating is that *official documentation not be 
opened up to everybody,* _especially not people who don't yet grok the 
language_.

> 
>>My bookshelf currently has Learning Python, Programming 
>>Python, Python Cookbook, Python Programming on Win32, and Regular 
>>Expressions.  All great books, and not too pricey if you can get them
> 
> used.
> 
> So, what you're advocating is let things stay how they are...
> 
> Ignore feedback... tell people to freak off...
> 
> 

I had not addressed feedback before, but I shall do so now:  Discuss 
concern on the Python list first to make sure it is not a lack of 
understanding, then, if a legitimate issue with the docs exists, use the 
bug tracker.  If one can't be bothered to take the time to be a 
Responsible Citizen, I am not going to be bothered by lacking that one's 
comments/concerns/feed-back.

~Ethan~


From davea at ieee.org  Tue Aug 11 10:22:49 2009
From: davea at ieee.org (Dave Angel)
Date: Tue, 11 Aug 2009 10:22:49 -0400
Subject: Search and write to .txt file
In-Reply-To: 
References: 
	
Message-ID: <4A817EB9.9040807@ieee.org>

Piet van Oostrum wrote:
>>>>>> Helvin  (H) wrote:
>>>>>>             
>
>   
>> H> Hi everyone,
>> H> I am writing some python script that should find a line which contains
>> H> '1' in the data.txt file, then be able to move a certain number of
>> H> lines down, before replacing a line. At the moment, I am able to find
>> H> the line '1', but when I use f.seek to move, and then rewrite, what I
>> H> write goes to the end of the .txt file, instead of being adjusted by
>> H> my f.seek.
>>     
>
>   
>> H> Do you know what way I should take?
>>     
>
>   
>> H> Data.txt is a file of 3 lines:
>> H>    line1
>> H>    line2
>> H>    line3
>>     
>
>   
>> H> Code:
>>     
>
>   
>> H>    with open('data.txt', 'r+') as f:
>> H>        firstread = f.readlines()   # Take a snapshot of initial file
>>     
>
>   
>> H>        f.seek(0,0)    # Go back to beginning and search
>> H>        for line in f:
>> H>            print line
>> H>            if line.find('1'):
>> H>                print 'line matched'
>> H>                f.seek(1,1)       # Move one space along
>> H>                f.write('house\n')     # f.write overwrites the exact
>> H> number of bytes.
>> H>                break                    # leave loop once '1' is found
>>     
>
> Mixing an iterator on the file with direct calls (seek/write) isn't
> going to work. The iterator does read ahead which causes the file
> position not to be what you think it is.
>
> See:
>
>   
>>>> with open('data.txt', 'r+') as f:
>>>>         
> ...   for line in f:
> ...       print line, f.tell()
> ... 
> line1
> 18
> line2
> 18
> line3
> 18
>
>   
In addition to the buffering involved in the read loop, trying to 
position ahead some number of lines would be rather error prone, since 
this is a text file, with varying length lines, and the \n character 
might occupy one byte on some OS, and two bytes on others (Windows).  If 
you feel you must do it in-place, then switch the file mode to binary, 
and use read(), not readline(), keeping track of your own position at 
all times.

As was already suggested by Kushal, if the file is small enough to just 
use readlines() and manipulate that list, I'd do that.  If not, I'd scan 
through the file, creating a new one, creating a new one as you go, then 
rename the new one back when finished.  Actually, I'd create a new one 
even in the first case, in case of a crash while rewriting the file.


DaveA


From ethan at stoneleaf.us  Tue Aug 11 10:35:54 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Tue, 11 Aug 2009 07:35:54 -0700
Subject: Unrecognized escape sequences in string literals
In-Reply-To: 
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>							<86e09602-7eb1-4397-a77f-fb1e3c5b34b9@k26g2000vbp.googlegroups.com>
	
Message-ID: <4A8181CA.9050200@stoneleaf.us>

Steven D'Aprano wrote:
> On Mon, 10 Aug 2009 08:21:03 -0700, Douglas Alan wrote:
> 
> 
>>But you're right, it's too late to change this now.
> 
> 
> Not really. There is a procedure for making non-backwards compatible 
> changes. If you care deeply enough about this, you could agitate for 
> Python 3.2 to raise a PendingDepreciation warning for "unexpected" escape 
> sequences like \z, Python 3.3 to raise a Depreciation warning, and Python 
> 3.4 to treat it as an error.
> 
> It may even be possible to skip the PendingDepreciation warning and go 
> straight for Depreciation warning in 3.2.
> 
> 

And once it's fully depreciated you have to stop writing it off on your 
taxes.  *wink*

~Ethan~


From Nikolaus at rath.org  Tue Aug 11 10:44:11 2009
From: Nikolaus at rath.org (Nikolaus Rath)
Date: Tue, 11 Aug 2009 10:44:11 -0400
Subject: Profiling a Callback Function
Message-ID: <1250001851.3970.15.camel@inspiron.ap.columbia.edu>

Hello,

I am trying to profile a Python program that primarily calls a C
extension. From within the C extension, a callback Python function is
then called concurrently in several threads.

When I tried to profile this application with

  import c_extension
  def callback_fn(args):
      # Do all sorts of complicated, time consuming stuff
      pass

  def main():
      c_extension.call_me_back(callback_fn, some_random_args)

  cProfile.run('main', 'profile.dat')

I only got results for main(), but no information at all about
callback_fn.


What is the proper way to profile such an application? 


I already thought about this:

  import c_extension

  def callback_fn(args):
      # Do all sorts of complicated, time consuming stuff
      pass
  
  def callback_wrapper(args):
       def doit():
           callback_fn(args)

       cProfile.run('doit', 'profile.dat')

  c_extension.call_me_back(callback_wrapper, some_random_args)


but that probably overwrites the profiling information whenever
callback_wrapper is called, instead of accumulating them over several
calls (with different arguments).


Best,


   -Nikolaus

-- 
 ?Time flies like an arrow, fruit flies like a Banana.?

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C




From cjw at ncf.ca  Tue Aug 11 10:45:28 2009
From: cjw at ncf.ca (Colin J. Williams)
Date: Tue, 11 Aug 2009 10:45:28 -0400
Subject: Extracting matrix from a text file
In-Reply-To: 
References: 
Message-ID: <4A818408.6080506@ncf.ca>

telekab1 at hotmail.com wrote:
> Hello to all!!
> 
> I am new in python, and I am running it on Mac with Smultron editor. I
> need to read a textfile that includes numbers (in a matrix form),
> indexes, and strings, like this:
> 
> Marsyas-kea distance matrix for MIREX 2007 Audio Similarity Exchange
> Q/R        1                   2                   3
> 4                5
> 1        0                  4.54592        4.36685
> 5.29463        3.85728
> 2        4.54592        0                  3.97667
> 5.02151        4.64284
> 3        4.36685        3.97667        0
> 4.98743        4.83683
> 4        5.29463        5.02151        4.98743
> 0                  6.04393
> 5        3.85728        4.64284        4.83683        6.04393        0
> 
> My code to get this information is:
> 
> matrix = open("dmatrix_5.txt");
> 
> while 1:
>     mat = matrix.readline()
>     if not mat:
>     	break
>     pass # do something
>     print mat
> 
> 
> 
> So I just want to keep the matrix in the "middle" for math
> computations.
> 
>         0                  4.54592        4.36685
> 5.29463        3.85728
>         4.54592        0                  3.97667
> 5.02151        4.64284
>         4.36685        3.97667        0
> 4.98743        4.83683
>         5.29463        5.02151        4.98743
> 0                  6.04393
>         3.85728        4.64284        4.83683        6.04393        0
> 
> 
> I've seen and tried a lot of ways, like split or isinstance.. but
> never get the wanted result.... does anyone have an idea, or hint?
> Thank you once more for your help!
> 
> Best Regards,
> Bea

numpy provides an answer.  See the little script below:

import numpy as _n
import string as _s
a=  "0       4.54592 4.36685 5.29463 3.85728 " + \
   "4.54592 0       3.97667 5.02151 4.64284 "   + \
   '4.36685 3.97667 0       4.98743 4.83683 '   + \
   '5.29463 5.02151 4.98743 0       6.04393 '   + \
   '3.85728 4.64284 4.83683 6.04393 0'

d= _n.mat(_n.reshape(_n.array(a.split(), dtype= _n.float), (5, 5)))
print repr(d)
print 'Default printoptions:', _n.get_printoptions()

for p in range(9):
   _n.set_printoptions(precision= p)
   print 'precision= ', p, '\n', d

When you run this, you'll see that there is a numpy glitch for precisions > 5.

Colin W.


From rurpy at yahoo.com  Tue Aug 11 10:57:28 2009
From: rurpy at yahoo.com (rurpy at yahoo.com)
Date: Tue, 11 Aug 2009 07:57:28 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
Message-ID: <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>

On 08/11/2009 01:47 AM, Antoine Pitrou wrote:
> r  gmail.com>  writes:
>> On Aug 9, 11:02 pm, David Lyon  wrote:
>>> Since you're talking about documentation, which is a part of python,
>>> don't you think you should be discussing it on python-dev ?
>> Yea, them's be a friendly bunch to noob ideas ;). Hey i got a better
>> idea, lets go to the IRS and see if we can persuade them to stop
>> taxing us...
>
> You know, the most interesting thing in this thread is certainly its title :
> ? Social problems of Python doc ?
>
> Yes, the little social problem here should be clear: if you have complaints to
> voice or improvements to suggest to the Python docs, you should do so on the
> issue tracker (*). For most topics, this is the only reasonable way to signal
> problems to the Python developers community, and so it is in most free software
> / open source projects.

"the *only* reasonable way"?  That's clearly wrong (unless you
want to wiggle in the room provided by "reasonable" or "most").
There is discussion on the dev list, there is discussion here.

The issue tracker is fine for many things, but the process it
provides is equivalent to peep-hole optimization.  How does one
submit a tracker issue for something like the overall organization
of the docs (for example, the mis-placement of things like data-
types in the library manual rather than the language manual)?

The big problem with the docs is poor writing (this includes
not using examples when they can help explain something more
clearly than verbiage alone).  It is understandable why this
should be so -- most programmers are good at and enjoy
programming, not writing and the python community is, say,
about 99.9% programmers.

This is why all the attempts (at least that I've noticed) are
programming focused -- build a wiki, write a new doc processing
framework, etc.  Unfortunately none of those addresses the real
problem -- the need for clear, well written, well organized
*content*.  I don't see how telling people to submit tracker
issues will solve this problem.  I can rewrite some section so
it sounds good to me, but likely it will be just as bad (perhaps
in different ways) that what is there.

The post that started this thread proposed something like paying
professional writers to improve the docs.  This may or may not
be a practical suggestion.  But the immediate response it
engendered was an auto-immune-like group response: the docs
are great already, don't complain, fix them yourself, yada, yada;
the same response that any criticism of free software produces.

It's really too bad the the python community can't seriously
discuss ways to improves the docs.  There are other possibilities
for instance the Fedora Docs project (can't say I'm impressed
by what they've produced but that doesn't mean their model
is useless).  There is a need for an approval process managed
by someone who actually understands what good technical writing
is.  And perhaps editors who can polish or work with programmers
who provide the raw technical description of some module.

Some kind of higher level more global process is the only
way I can see that the docs will be improved to any sort
or professional standard.  I don't see how issues like this
will be addressed by submitting tracker items.

Personally, I have given up on this issue.  The social factors
involved really pretty much determine that the Python docs
will never reach a very high quality -- that's just the way
it is and I've come to accept that.


From pacificik at warnell.uga.edu  Tue Aug 11 11:13:28 2009
From: pacificik at warnell.uga.edu (Krishna Pacifici)
Date: Tue, 11 Aug 2009 11:13:28 -0400
Subject: dictionary help
Message-ID: <4A8152580200008C00014A44@redhorse.forestry.uga.edu>

Thanks for the help.

Actually this is part of a much larger project, but I have unfortunately pigeon-holed myself into needing to do these things without a whole lot of flexibility.

To give a specific example I have the following dictionary where I need to remove values that are duplicated with other values and remove values that are duplicates of the keys, but still retain it as a dictionary.  Each value is itself a class with many attributes that I need to call later on in the program, but I cannot have duplicates because it would mess up some estimation part of my model.

d =
{36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11, 31], 22: [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}

So I want a new dictionary that would get rid of the duplicate values of 21, 22, 36 and 20 and give me back a dictionary that looked like this:

new_d=
{36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23, 12, 32], 26: [25, 27, 16], 30: [40]}

I understand that a dictionary may not be the best approach, but like I said I have sort of pigeon-holed myself by the way that I am simulating my data and the estimation model that I am using.  Any suggestions or comments about the above problem would be greatly appreciated.

Thanks again,
Krishna



>>> Dave Angel  08/11/09 7:38 AM >>>
Krishna Pacifici wrote:
> Hi,
> kind of a newbie here, but I have two questions that are probably pretty simple.
>
> 1.  I need to get rid of duplicate values that are associated with different keys in a dictionary.  For example I have the following code.
> s={}
> s[0]=[10,2,3]
>  s[10]=[22,23,24]
>  s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
>
> Now I want to be able to loop through the primary keys and get rid of duplicates (both in keys and values) so that I would have either a new dictionary or the same dictionary but with the following values:
>
> s[0]=[3]
>  s[10]=[22,23,24]
>  s[20]=[45,5]
> s[30]=[2,4]
> s[40]=[6,7,8]
>
> It doesn't matter which value gets removed as long as there is only one remaining, so in this example it doesn't matter that 2 got removed from s[0] or from s[30] as long as there is only one 2 in the dictionary.
>
> 2.  I need to be able to loop over the values in the dictionary when there are multiple values assigned to each key like above and assign new values to those values.  Taking the above example I would want to assign a new value so that when you called s[0] it would equal [3,4] say if 4 was the new value.  I think this should be as simple as adding a value, but I kept on having difficulty.
>
> Any suggestions would be greatly appreciated.
>
> Thank you very much,
> Krishna
>
>
>   
Sounds like homework.  If it was for an unconstrained project, I'd 
design a different data structure, one that directly enforced the data 
constraints.  So far, I can't imagine a useful reason for this 
particular set of constraints.

Let's break the problems down.

1a)   Do you know how to write a loop that visits all the keys of a 
dictionary?
1b)  Do you know how to safely check if a particular key exists?     
e.g.      if   key in s:
1c)  Do you know how to collect a set of values, so that when a 
duplicate is found, it can be recognized as such?
1d) Do you know how to remove an item from a list?

2a)  Like 1a)
2b) Do you know how to append a value to the end of a list?  Is s[key] a 
list?


DaveA


-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From sajmikins at gmail.com  Tue Aug 11 11:44:04 2009
From: sajmikins at gmail.com (Simon Forman)
Date: Tue, 11 Aug 2009 08:44:04 -0700 (PDT)
Subject: Search and write to .txt file
References: 
Message-ID: 

On Aug 11, 7:22?am, Helvin  wrote:
> Hi everyone,
>
> I am writing some python script that should find a line which contains
> '1' in the data.txt file, then be able to move a certain number of
> lines down, before replacing a line. At the moment, I am able to find
> the line '1', but when I use f.seek to move, and then rewrite, what I
> write goes to the end of the .txt file, instead of being adjusted by
> my f.seek.
>
> Do you know what way I should take?
>
> Data.txt is a file of 3 lines:
> ? ?line1
> ? ?line2
> ? ?line3
>
> Code:
>
> ? ?with open('data.txt', 'r+') as f:
> ? ? ? ?firstread = f.readlines() ? # Take a snapshot of initial file
>
> ? ? ? ?f.seek(0,0) ? ?# Go back to beginning and search
> ? ? ? ?for line in f:
> ? ? ? ? ? ?print line
> ? ? ? ? ? ?if line.find('1'):
> ? ? ? ? ? ? ? ?print 'line matched'
> ? ? ? ? ? ? ? ?f.seek(1,1) ? ? ? # Move one space along
> ? ? ? ? ? ? ? ?f.write('house\n') ? ? # f.write overwrites the exact
> number of bytes.
> ? ? ? ? ? ? ? ?break ? ? ? ? ? ? ? ? ? ?# leave loop once '1' is found
>
> ? ? ? ?f.seek(0,0) ? ? ? ? ? ? ?# Go back to beginning, and read
> data.txt again
> ? ? ? ?lastread = f.readlines()
>
> ? ? ? ?print 'firstread is', firstread
> ? ? ? ?print 'lastread is', lastread
>
> This shouldn't be too difficult, but I don't know how. > <
> Help appreciated!

There's a bug in this line:

if line.find('1'):

the string find() method returns an integer, which will be -1 if the
substring is not found. In python -1 is treated as True (only 0 is
False) so your if statement will always succeed unless '1' is the
first character on the line.

HTH,
~Simon


P.S. you can use the help() command in the python interpreter to get
docs on most things:

>>> help(str.find)

Help on method_descriptor:

find(...)
    S.find(sub [,start [,end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within s[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.



From python at mrabarnett.plus.com  Tue Aug 11 11:51:42 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Tue, 11 Aug 2009 16:51:42 +0100
Subject: dictionary help
In-Reply-To: <4A8152580200008C00014A44@redhorse.forestry.uga.edu>
References: <4A8152580200008C00014A44@redhorse.forestry.uga.edu>
Message-ID: <4A81938E.3070509@mrabarnett.plus.com>

Krishna Pacifici wrote:
> Thanks for the help.
> 
> Actually this is part of a much larger project, but I have unfortunately 
> pigeon-holed myself into needing to do these things without a whole lot 
> of flexibility.
> 
> To give a specific example I have the following dictionary where I need 
> to remove values that are duplicated with other values and remove values 
> that are duplicates of the keys, but still retain it as a dictionary.  
> Each value is itself a class with many attributes that I need to call 
> later on in the program, but I cannot have duplicates because it would 
> mess up some estimation part of my model.
> 
> d =
> {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11, 31], 22: 
> [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}
> 
> So I want a new dictionary that would get rid of the duplicate values of 
> 21, 22, 36 and 20 and give me back a dictionary that looked like this:
> 
> new_d=
> {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23, 
> 12, 32], 26: [25, 27, 16], 30: [40]}
> 
> I understand that a dictionary may not be the best approach, but like I 
> said I have sort of pigeon-holed myself by the way that I am simulating 
> my data and the estimation model that I am using.  Any suggestions or 
> comments about the above problem would be greatly appreciated.
> 
 >>> d = {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11,
31], 22: [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}
 >>> new_d = {}
 >>> seen = set(d.keys())
 >>> for k, v in d.items():
...     new_d[k] = [x for x in v if x not in seen]
...     seen |= set(new_d[k])
...
 >>> new_d
{36: [35, 37, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23, 12,
32], 26: [25, 27, 16], 30: [40]}



From sajmikins at gmail.com  Tue Aug 11 12:10:10 2009
From: sajmikins at gmail.com (Simon Forman)
Date: Tue, 11 Aug 2009 09:10:10 -0700 (PDT)
Subject: dictionary help
References: <4A8152580200008C00014A44@redhorse.forestry.uga.edu> 
	
Message-ID: 

On Aug 11, 11:51?am, MRAB  wrote:
> Krishna Pacifici wrote:
> > Thanks for the help.
>
> > Actually this is part of a much larger project, but I have unfortunately
> > pigeon-holed myself into needing to do these things without a whole lot
> > of flexibility.
>
> > To give a specific example I have the following dictionary where I need
> > to remove values that are duplicated with other values and remove values
> > that are duplicates of the keys, but still retain it as a dictionary. ?
> > Each value is itself a class with many attributes that I need to call
> > later on in the program, but I cannot have duplicates because it would
> > mess up some estimation part of my model.
>
> > d =
> > {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11, 31], 22:
> > [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}
>
> > So I want a new dictionary that would get rid of the duplicate values of
> > 21, 22, 36 and 20 and give me back a dictionary that looked like this:
>
> > new_d=
> > {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23,
> > 12, 32], 26: [25, 27, 16], 30: [40]}
>
> > I understand that a dictionary may not be the best approach, but like I
> > said I have sort of pigeon-holed myself by the way that I am simulating
> > my data and the estimation model that I am using. ?Any suggestions or
> > comments about the above problem would be greatly appreciated.
>
> ?>>> d = {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11,
> 31], 22: [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}
> ?>>> new_d = {}
> ?>>> seen = set(d.keys())
> ?>>> for k, v in d.items():
> ... ? ? new_d[k] = [x for x in v if x not in seen]
> ... ? ? seen |= set(new_d[k])
> ...
> ?>>> new_d
> {36: [35, 37, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23, 12,
> 32], 26: [25, 27, 16], 30: [40]}

Ha ha, MRAB beat me to it:

d = {
    36: [35, 37, 26, 46],
    75: [74, 76, 65, 85],
    21: [20, 22, 11, 31],
    22: [21, 23, 12, 32],
    26: [25, 27, 16, 36],
    30: [20, 31, 40],
    }


new_d = { # Given, and apparently incorrect.
    36: [35, 37, 26, 46], # 26 is a key and should be gone.
    75: [74, 76, 65, 85],
    21: [20, 11, 31],
    22: [23, 12, 32],
    26: [25, 27, 16],
    30: [40],
    }


expected = {
    36: [35, 37, 46],
    75: [74, 76, 65, 85],
    21: [20, 11, 31],
    22: [23, 12, 32],
    26: [25, 27, 16],
    30: [40],
    }


def removeDuplicates(D):
    '''
    Remove values that are duplicated with other values
    and remove values that are duplicates of the keys.

    Assumes that values in the lists are already unique within
    each list.  I.e. duplicates are only in the keys or in other
    lists.

    This function works "in place" on D, so it doesn't return
    anything.  Caller must keep a reference to D.
    '''

    seen = set(D) # Get a set of the keys.

    for key, values_list in D.iteritems():

        # Filter out values that have already been seen.
        filtered_values = [
            value
            for value in values_list
            if not value in seen
            ]

        # Remember newly seen values.
        seen.update(filtered_values)

        D[key] = filtered_values


## Example:
##
##    >>> d == expected
##    False
##    >>> removeDuplicates(d)
##    >>> d == expected
##    True


From ethan at stoneleaf.us  Tue Aug 11 12:12:44 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Tue, 11 Aug 2009 09:12:44 -0700
Subject: add fields in a existing dbf
In-Reply-To: <4A815572.1020905@ceam.es>
References: <4A815572.1020905@ceam.es>
Message-ID: <4A81987C.4080800@stoneleaf.us>

Alonso Luj?n Torres Ta?o wrote:
> Hi!
> 
> I'm trying to modify a dbf adding a new field in a python script, but I 
> can't.
> 
> Just I can add a field in new dbf created in the same script.
> 
> I tryed with:
> 
>     db = dbf.Dbf("../filesource.dbf",new =False, readOnly=False)
>     ...
>     db.addField(("PESO","N",32,8))
> 
> and return error:
> 
>     Traceback (most recent call last):
>       File "script.py", line 34, in 
>         db.addField(("PESO","N",32,8))
>       File "/usr/lib/python2.5/site-packages/dbfpy/dbf.py", line 229, in
>     addField
>         "structure can't be changed")
>     TypeError: ('At least one record was added, ', "structure can't be
>     changed")
> 
> 
> I have not idea of what error I make.
> 
> If someone can help me, I'll so gratefull.
> 
> Thanks!
> 

I am not familiar with dbfpy, but the dbf files I am familiar with do 
not support 32 digit Numerics.  Did you mean 12?

At any rate, if you use http://groups.google.com/group/python-dbase

the commands would be:

import dbf
db = dbf.Table("../filesource.dbf")
db.add_fields("peso N(12.8)")
db.close()

and you'll have your field -- assuming, of course, you have write 
priveleges, etc.

Hope this helps!

~Ethan~

Disclaimer:  I am the author of python-dbase.


From petshmidt at googlemail.com  Tue Aug 11 12:33:52 2009
From: petshmidt at googlemail.com (someone)
Date: Tue, 11 Aug 2009 09:33:52 -0700 (PDT)
Subject: better way?
Message-ID: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>

Hello,

I'd like to make insert into db if record not exist otherwise update.
to save typing list of columns in both statements I do following

query = "SELECT location FROM table WHERE location = %s AND id = %s;"
result = self._getResult(db, query, [location,id])

fields = ['id', 'location', 'wl', 'modified', 'counter', 'name']
if result:
    t = map(lambda s: s + ' = %s', fields)
    temp = ", ".join(t)
    query = "UPDATE table SET " + temp + " WHERE location = %s AND id
= %s;"
    self._execQuery(db, query, [id, location, self.wl, 'NOW()', 1,
name, location, id])
else:
    f = ", ".join(fields)
    query = """
        INSERT INTO table
        (""" + f + """)
        VALUES
        (%s,%s,%s,NOW()- interval '1 day', 1, %s)
    """
    self._execQuery(db, query, [id, location, self.wl, name])



is there better or more readable way to do it?

Pet


From bthate at gmail.com  Tue Aug 11 12:41:37 2009
From: bthate at gmail.com (Bart Thate)
Date: Tue, 11 Aug 2009 09:41:37 -0700 (PDT)
Subject: GOZERBOT 0.9.1 released
Message-ID: <0fefbd87-efa2-4eaa-afe1-9e5b7ec5ad86@z31g2000yqd.googlegroups.com>

here it is .. GOZERBOT 0.9.1 !!

Main change this time is the distribution method, we now provide a
tar.gz with all the dependencies included. This means that you can run
the bot locally without any root required. Python 2.5 or higher
needed, see http://gozerbot.org

Enjoy !

about GOZERBOT:

GOZERBOT is a channel bot that aids with conversation in irc channels
and
jabber conference rooms. its mainly used to serve rss feeds and to
have
custom commands made for the channel. More then just a channel bot
GOZERBOT
aims to provide a platform for the user to program his own bot and
make it
into something thats usefull. This is done with a plugin structure
that
makes it easy to program your own. But GOZERBOT comes with some
batteries
included, there are now over 100 plugins already written and ready for
use.


From emile at fenx.com  Tue Aug 11 12:49:19 2009
From: emile at fenx.com (Emile van Sebille)
Date: Tue, 11 Aug 2009 09:49:19 -0700
Subject: Is there any package implanation the following arithmetics?
In-Reply-To: 
References: 
Message-ID: 

On 8/11/2009 1:49 AM zhongshq said...
> Hi,
> 
> I wonder if there has any package can check whether two rectangles are
> overlap, is a dot inside or outside a polygon, etc.

PythonCad at http://sourceforge.net/projects/pythoncad/ has 
intersections built in.

Emile



From rt8396 at gmail.com  Tue Aug 11 12:49:31 2009
From: rt8396 at gmail.com (r)
Date: Tue, 11 Aug 2009 09:49:31 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References:   
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	<4A80472E.4090108@stoneleaf.us> 
	
	
Message-ID: <63f2b657-c646-4a69-9a05-1da5975bb6d2@z31g2000yqd.googlegroups.com>

On Aug 11, 1:47?am, Steven D'Aprano
 wrote:
> On Mon, 10 Aug 2009 20:05:00 -0400, David Lyon wrote:
> > Ignore feedback... tell people to freak off...
>
> Only useless feedback.

And who decides what is useless and what isn't Steven?. You?, alex23?,
Bruno?, Paul? Carl? Who makes these decisions and do *they* make them
without pride or prejudice? Do they approve an idea by someone they
hate because it it good, or do they toss it in the trash just to spite
them, because they have the power to do so? As we can see much
resistace exists against even the ideas of change. How will change
ever take place with such defiance!

I am sorry but i feel many here would not judge fairly based on the
merits of an idea without allowing "buddy-systems" or "pecking-orders"
to get in the way. Sad really, only Python suffers in the end.

Some say the tutorial is not meant for non-programmers, but for
programmers with no Python experience. So! How does that justify
obstruction of the tut? Why not present the same information in a way
both can easily understand? I thought Pythons original vision was to
allow easy entry into programming for anybody -- experienced or not!
Anybody remember "CP4E"?

Is this an ivory tower thing? i dunno, but it seems to be...???



From pacificik at warnell.uga.edu  Tue Aug 11 12:55:28 2009
From: pacificik at warnell.uga.edu (Krishna Pacifici)
Date: Tue, 11 Aug 2009 12:55:28 -0400
Subject: dictionary help
Message-ID: <4A816A400200008C00014A70@redhorse.forestry.uga.edu>

Wow, thanks MRAB and Simon, you guys are good.

I guess I will go ahead and ask the next question that has also stumped me for awhile now.

So basically I need to loop through the values in the new dictionary and append attributes of a class object.  Each of the values (and keys) represent a block in a grid with a specific location (e.g. 35 is the block in row 3 col 5) and each block is an object with several attributes associated with it.  I want to call that block and append two separate attributes to the dictionary within that same key.

So again it would look something like this:

block 35 has 2 attributes, say a and b, a=2, b=5 
block 37 has a=1, b=3
block 46 has a=3, b=8

the two attributes come from two different definitions within the class statement, 
def detections
...
return a

def abundance
...
return b

so I would want to append to key 36 those two attributes for each block so that the resulting dictionary item would look like this:
                         a           b   
{36:[35,37,46], [2,1,3], [5,3,8] ...}

Any help with this would be greatly appreciated.  And thank you so much for all of your help thus far, I'm still pretty new to python and am enjoying all of the flexibility associated with a scripting and programming language.

Thanks again,
Krishna

>>> Simon Forman  08/11/09 12:15 PM >>>
On Aug 11, 11:51 am, MRAB  wrote:
> Krishna Pacifici wrote:
> > Thanks for the help.
>
> > Actually this is part of a much larger project, but I have unfortunately
> > pigeon-holed myself into needing to do these things without a whole lot
> > of flexibility.
>
> > To give a specific example I have the following dictionary where I need
> > to remove values that are duplicated with other values and remove values
> > that are duplicates of the keys, but still retain it as a dictionary.  
> > Each value is itself a class with many attributes that I need to call
> > later on in the program, but I cannot have duplicates because it would
> > mess up some estimation part of my model.
>
> > d =
> > {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11, 31], 22:
> > [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}
>
> > So I want a new dictionary that would get rid of the duplicate values of
> > 21, 22, 36 and 20 and give me back a dictionary that looked like this:
>
> > new_d=
> > {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23,
> > 12, 32], 26: [25, 27, 16], 30: [40]}
>
> > I understand that a dictionary may not be the best approach, but like I
> > said I have sort of pigeon-holed myself by the way that I am simulating
> > my data and the estimation model that I am using.  Any suggestions or
> > comments about the above problem would be greatly appreciated.
>
>  >>> d = {36: [35, 37, 26, 46], 75: [74, 76, 65, 85], 21: [20, 22, 11,
> 31], 22: [21, 23, 12, 32], 26: [25, 27, 16, 36], 30: [20, 31, 40]}
>  >>> new_d = {}
>  >>> seen = set(d.keys())
>  >>> for k, v in d.items():
> ...     new_d[k] = [x for x in v if x not in seen]
> ...     seen |= set(new_d[k])
> ...
>  >>> new_d
> {36: [35, 37, 46], 75: [74, 76, 65, 85], 21: [20, 11, 31], 22: [23, 12,
> 32], 26: [25, 27, 16], 30: [40]}

Ha ha, MRAB beat me to it:

d = {
    36: [35, 37, 26, 46],
    75: [74, 76, 65, 85],
    21: [20, 22, 11, 31],
    22: [21, 23, 12, 32],
    26: [25, 27, 16, 36],
    30: [20, 31, 40],
    }


new_d = { # Given, and apparently incorrect.
    36: [35, 37, 26, 46], # 26 is a key and should be gone.
    75: [74, 76, 65, 85],
    21: [20, 11, 31],
    22: [23, 12, 32],
    26: [25, 27, 16],
    30: [40],
    }


expected = {
    36: [35, 37, 46],
    75: [74, 76, 65, 85],
    21: [20, 11, 31],
    22: [23, 12, 32],
    26: [25, 27, 16],
    30: [40],
    }


def removeDuplicates(D):
    '''
    Remove values that are duplicated with other values
    and remove values that are duplicates of the keys.

    Assumes that values in the lists are already unique within
    each list.  I.e. duplicates are only in the keys or in other
    lists.

    This function works "in place" on D, so it doesn't return
    anything.  Caller must keep a reference to D.
    '''

    seen = set(D) # Get a set of the keys.

    for key, values_list in D.iteritems():

        # Filter out values that have already been seen.
        filtered_values = [
            value
            for value in values_list
            if not value in seen
            ]

        # Remember newly seen values.
        seen.update(filtered_values)

        D[key] = filtered_values


## Example:
##
##    >>> d == expected
##    False
##    >>> removeDuplicates(d)
##    >>> d == expected
##    True
-- 
http://mail.python.org/mailman/listinfo/python-list

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From liukis at usc.edu  Tue Aug 11 13:29:42 2009
From: liukis at usc.edu (Maria Liukis)
Date: Tue, 11 Aug 2009 10:29:42 -0700
Subject: Any built-in function for smallest positive floating point number?
Message-ID: 

Hello everybody,

Is somebody aware of built-in Python's function that would return a  
value for smallest positive double precision floating point number  
(analogous to 'realmin' in Matlab). Python has built-in sys.maxint  
but I could not find anything for float.

Any help would be greatly appreciated.

Thanks,
Masha
--------------------
liukis at usc.edu



-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From dotancohen at gmail.com  Tue Aug 11 13:33:39 2009
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 11 Aug 2009 20:33:39 +0300
Subject: Scraping Wikipedia with Python
Message-ID: <880dece00908111033n2a9f8e5et937d1f4bbcb2df89@mail.gmail.com>

I plan on making a geography-learning Anki [1] deck, and Wikipedia has
the information that I need in nicely formatted tables on the side of
each country's page. Has someone already invented a wheel to parse and
store that data (scrape)? It is probably not difficult to code, and
within the Wikipedia license, but if that wheel has already been
invented then I don't want to redo it. I tried googling for a
Wikipedia-specific solution but found none, is there a general purpose
solution that I could use?

Note that I am a regular Wikipedia contributor and plan on staying
within the realm of Wikipedia's rules.


[1] http://ichi2.net/anki/

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il


From Francis.Brissette at autodesk.com  Tue Aug 11 13:39:49 2009
From: Francis.Brissette at autodesk.com (Francis Brissette)
Date: Tue, 11 Aug 2009 10:39:49 -0700
Subject: Unsigned char array to an unsigned longlong array
Message-ID: 

Hello,

I'm using Python 2.6.2.
Is there a way to have an Array of unsigned longlong (C Type: unsigned longlong, Minimum size if bytes: 8) ?
I found a page on the internet (http://mail.python.org/pipermail/patches/2005-April/017430.html), but I'm not quite sure if it is available.


What I want to do is to store an array of bytes in an array of longlongs.
To workaround this issue, I have tried to use the double array (TypeCode 'd'), since the size in bytes is the same (8 for instance).
But it gives me strange result. Please look at the example:

import array
myByteArray = array.array('B', [1,2,3,4,5,6,7,8])
>> myByteArray = array('B', [1, 2, 3, 4, 5, 6, 7, 8])

myLongArray = array.array('L', myByteArray.tostring() )
myLongArray = array('L', [67305985L, 134678021L])

myDoubleArray = array.array('d', myByteArray.tostring() )
myDoubleArray = array('d', [5.447603722011605e-270])

If we convert the byte array to an hex form, we will get for the long array: [04030201, 08070605].
If we convert this hex array to decimal, we then get the Long Array: [67305985, 134678021].

Now, if we do the same exercise for the double array, the hex form will look like: [0807060504030201].
And the decimal value would be: [5.784376957523072e+17].

Where does the 5.447603722011605e-270 value comes from ?


Thanks for your help,
Francis
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From breamoreboy at yahoo.co.uk  Tue Aug 11 13:41:48 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 18:41:48 +0100
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <63f2b657-c646-4a69-9a05-1da5975bb6d2@z31g2000yqd.googlegroups.com>
References:  
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>		<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>	
		<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>		<4A80472E.4090108@stoneleaf.us>
		
	<63f2b657-c646-4a69-9a05-1da5975bb6d2@z31g2000yqd.googlegroups.com>
Message-ID: 

r wrote:
> On Aug 11, 1:47 am, Steven D'Aprano
>  wrote:
>> On Mon, 10 Aug 2009 20:05:00 -0400, David Lyon wrote:
>>> Ignore feedback... tell people to freak off...
>> Only useless feedback.
> 
[snip]
> 
> I am sorry but i feel many here would not judge fairly based on the
> merits of an idea without allowing "buddy-systems" or "pecking-orders"
> to get in the way. Sad really, only Python suffers in the end.
I disagree with these comments.  I do not believe that Python has a 
buddy system or a pecking order getting in the way of anything.  As you 
are making thsse accusations, either provide hard evidence that can 
persuade me that your perspective on this is correct or shut up.
> 
[snip]
> 

-- 
Kindest regards.

Mark Lawrence.



From nagle at animats.com  Tue Aug 11 13:48:17 2009
From: nagle at animats.com (John Nagle)
Date: Tue, 11 Aug 2009 10:48:17 -0700
Subject: Is "feedparser" deprecated?
In-Reply-To: 
References: <4a7c7a8d$0$1661$742ec2ed@news.sonic.net>
	
Message-ID: <4a81adee$0$1654$742ec2ed@news.sonic.net>

Gabriel Genellina wrote:
> En Fri, 07 Aug 2009 16:07:48 -0300, John Nagle 
> escribi?:
> 
>>    Feedparser requires SGMLlib, which has been removed from Python 3.0.
>> Feedparser hasn't been updated since 2007. Does this mean Feedparser
>> is dead?
> 
> Since we have generic and easy of use XML parsers like ElementTree and
> lxml,  specialized rss parsers like feedparser are not so much required.
> I've used ElementTree when I had to parse an rss feed in the past (not so
> many times).

    Take a look at what Feedparser has to do to deal with real-world RSS
feeds.  There are several hundred lines of code just to figure out the
source encoding.  There's gzip support, Atom support, base 64 encoding
support... Then there's the RSS polling protocol, which also requires
some support.  A basic XML parser only does part of the job.

					John Nagle


From liukis at usc.edu  Tue Aug 11 13:48:55 2009
From: liukis at usc.edu (Maria Liukis)
Date: Tue, 11 Aug 2009 10:48:55 -0700
Subject: Any built-in function for smallest positive floating point number?
In-Reply-To: 
References: 
Message-ID: <3E85703A-28AF-4626-8BFB-786C85810BCD@usc.edu>

A bit more of googling gave me an answer:

 >>> import numpy as np
 >>> np.finfo(np.double).tiny
array(2.2250738585072014e-308)
 >>>

Thanks,
Masha
--------------------
liukis at usc.edu



On Aug 11, 2009, at 10:29 AM, Maria Liukis wrote:

> Hello everybody,
>
> Is somebody aware of built-in Python's function that would return a  
> value for smallest positive double precision floating point number  
> (analogous to 'realmin' in Matlab). Python has built-in sys.maxint  
> but I could not find anything for float.
>
> Any help would be greatly appreciated.
>
> Thanks,
> Masha
> --------------------
> liukis at usc.edu
>
>
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at REMOVE-THIS-cybersource.com.au  Tue Aug 11 13:53:16 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 17:53:16 GMT
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
Message-ID: <0291a07d$0$20639$c3e8da3@news.astraweb.com>

On Tue, 11 Aug 2009 07:57:28 -0700, rurpy wrote:

> On 08/11/2009 01:47 AM, Antoine Pitrou wrote:
>> r  gmail.com>  writes:
>>> On Aug 9, 11:02 pm, David Lyon  wrote:
>>>> Since you're talking about documentation, which is a part of python,
>>>> don't you think you should be discussing it on python-dev ?
>>> Yea, them's be a friendly bunch to noob ideas ;). Hey i got a better
>>> idea, lets go to the IRS and see if we can persuade them to stop
>>> taxing us...
>>
>> You know, the most interesting thing in this thread is certainly its
>> title : ? Social problems of Python doc ?
>>
>> Yes, the little social problem here should be clear: if you have
>> complaints to voice or improvements to suggest to the Python docs, you
>> should do so on the issue tracker (*). For most topics, this is the
>> only reasonable way to signal problems to the Python developers
>> community, and so it is in most free software / open source projects.
> 
> "the *only* reasonable way"?  That's clearly wrong (unless you want to
> wiggle in the room provided by "reasonable" or "most"). There is
> discussion on the dev list, there is discussion here.

Discussion here is spitting into the wind. The noise-to-signal ratio is 
high enough that the people who can fix an issue aren't likely to see it 
here. Unless somebody raises a report in the bug tracker, it will go 
nowhere, fast.

The same happens for issues on the dev list: I can't count how many times 
people there have said "put it in the bug tracker, or it will be 
forgotten".


> The issue tracker is fine for many things, but the process it provides
> is equivalent to peep-hole optimization.  How does one submit a tracker
> issue for something like the overall organization of the docs (for
> example, the mis-placement of things like data- types in the library
> manual rather than the language manual)?

The same way you would submit a tracker issue for anything.

"Documentation bug: Data types are misplaced in the library manual 
instead of the language manual.

Suggested alternative: move page docs.python.org/xyz.html to abc.html"



> The big problem with the docs is poor writing (this includes not using
> examples when they can help explain something more clearly than verbiage
> alone).

There's a difference between insufficiently good writing and poor 
writing: think of grading the docs, where 100 is "perfect in every way" 
and -100 is "perfectly awful in every possible way". (It's not a linear 
scale.) A score of 0 is "mediocre, just barely acceptable". Poor writing 
has a negative score. In my opinion, Python's docs are perhaps a 40 or 
50, significantly better than most technical docs I've seen.


[...]
>  I can rewrite some section so it sounds good to me, but likely it will
> be just as bad (perhaps in different ways) that what is there.

Bug reports are valuable even if you don't have the skills to provide a 
patch. Bug reports with patches are even more valuable, but that doesn't 
mean that the failure to provide a patch *necessarily* dooms your report 
to oblivion.


> The post that started this thread proposed something like paying
> professional writers to improve the docs.  This may or may not be a
> practical suggestion.  But the immediate response it engendered was an
> auto-immune-like group response: the docs are great already, don't
> complain, fix them yourself, yada, yada; the same response that any
> criticism of free software produces.

I haven't seen any such knee-jerk responses. What I've seen is a set of 
sensible, *practical* advice:

- complaining on its own, especially here, is pointless;

- Python is a community effort, if you see something that needs fixing, 
do something about it;

- many of us DON'T want arbitrary people "correcting" the official docs 
without oversight, and believe that would be a disaster (arbitrary people 
aren't give check-in privileges to add code to Python's standard library, 
nor should they be given check-in privileges to add docs);

- if people are keen on a Python wiki, then by all means publish one, 
just don't expect the Python dev team to build and manage it for you;

- bug reports and patches to the docs are ALWAYS welcome, even if they 
are rejected;

- if you don't have the skills to fix a bug (including doc bugs), an 
alternative is to pay somebody else to do so instead.

 
> It's really too bad the the python community can't seriously discuss
> ways to improves the docs.  There are other possibilities for instance
> the Fedora Docs project (can't say I'm impressed by what they've
> produced but that doesn't mean their model is useless).  There is a need
> for an approval process managed by someone who actually understands what
> good technical writing is.  And perhaps editors who can polish or work
> with programmers who provide the raw technical description of some
> module.

Yes, you're correct. 

[sarcasm] Now that we've agreed on what needs to be done, the problem is 
solved!!! [end sarcasm]



> Some kind of higher level more global process is the only way I can see
> that the docs will be improved to any sort or professional standard.  I
> don't see how issues like this will be addressed by submitting tracker
> items.

You want community input into the docs, but you're not willing to give 
that input except to bitch and moan and sook that the tracker is no good.

Even if the PSF had a full-time team of professional documentation 
writers and editors, guess what, you would STILL need to submit issues to 
the bug tracker, because otherwise THEY WON'T BE TRACKED.


> Personally, I have given up on this issue.  The social factors involved
> really pretty much determine that the Python docs will never reach a
> very high quality -- that's just the way it is and I've come to accept
> that.

Ultimately it boils down to two factors:

Money.

Effort.

If you won't put in the effort, and you won't put in the money, then it 
won't happen. Moaning that other people aren't putting in the money to 
hire team of professional writers isn't productive, and moaning that 
other people aren't putting in the effort to improve the docs isn't 
either.



-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Tue Aug 11 14:00:08 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 11 Aug 2009 18:00:08 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
	
Message-ID: <0291a21a$0$20639$c3e8da3@news.astraweb.com>

On Tue, 11 Aug 2009 15:50:01 +0200, Piet van Oostrum wrote:

>>>>>> Steven D'Aprano  (SD) wrote:
> 
>>SD> If I'm reading this page correctly, Python does behave as C++ does.
>>Or at SD> least as Larch/C++ does:
> 
>>SD> http://www.cs.ucf.edu/~leavens/larchc++manual/lcpp_47.html
> 
> They call them `non-standard escape sequences' for a reason: that they
> are not in standard C++.
> 
> test.cpp:
> char* temp = "abc\yz";
> 
> TEMP> g++ -c test.cpp
> test.cpp:1:1: warning: unknown escape sequence '\y'


Isn't that a warning, not a fatal error? So what does temp contain?



-- 
Steven


From squishywaffle at gmail.com  Tue Aug 11 14:14:14 2009
From: squishywaffle at gmail.com (squishywaffle at gmail.com)
Date: Tue, 11 Aug 2009 11:14:14 -0700 (PDT)
Subject: Networked Broadcast Messaging
Message-ID: <37ea826b-708d-48f4-a64a-42f58fec5325@c2g2000yqi.googlegroups.com>

I'm not exactly sure what the term for this would be, but I was
wondering if there were any Python packages that supported some kind
of ad-hoc message broadcasting. What I'd like to do is something like
this:

* On a number of workhorse machines, a process listens for network
messages from our broadcast service. It subscribes to a certain sub-
set of them and will only respond to the messaging events that it is
subscribed to.
* Any machine can broadcast a message out to the network of machines
without specifying an IP address.
* Machines can come and go. Since messages are not directly sent to a
specific IP address from our Python script, the messages are simply
broadcasted to those who are there to listen. If nobody is subscribed
to the message type being sent, nothing happens.

I know XML-RPC and other friends are an option, but I'm looking for
something that doesn't require managing a set of IP addresses or
hostnames. I'm not sure what to Google for such a package/module, any
direction would be greatly appreciated.


From pacificik at warnell.uga.edu  Tue Aug 11 14:17:15 2009
From: pacificik at warnell.uga.edu (Krishna Pacifici)
Date: Tue, 11 Aug 2009 14:17:15 -0400
Subject: looping through values in a dictionary and appending to a
	 list
Message-ID: <4A817D6B0200008C00014A9B@redhorse.forestry.uga.edu>

Nevermind,
got it.

Sorry.

>>> Krishna Pacifici 08/11/09 2:12 PM >>>
Hi,
I want to append the values of a dictionary to a list.  I have a dictionary sec_dict_clean and I want to append the values to a list, but am having a hard time looping through the values in the dictionary.

I have tried something like this:
lista=[]
for i in sec_dict_clean.values():
    for j in sec_dict_clean.values()[i]:
        lista.append(sec_dict_clean.values()[i])

But I keep on getting an error:
TypeError: list indices must be integers

Any ideas on how to loop through values in a dictionary?

Thanks,
Krishna

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nagle at animats.com  Tue Aug 11 14:26:44 2009
From: nagle at animats.com (John Nagle)
Date: Tue, 11 Aug 2009 11:26:44 -0700
Subject: Scraping Wikipedia with Python
In-Reply-To: 
References: 
Message-ID: <4a81b6f0$0$1590$742ec2ed@news.sonic.net>

Dotan Cohen wrote:
> I plan on making a geography-learning Anki [1] deck, and Wikipedia has
> the information that I need in nicely formatted tables on the side of
> each country's page. Has someone already invented a wheel to parse and
> store that data (scrape)? 

     Wikipedia has an API for computer access.  See

	http://www.mediawiki.org/wiki/API

				John Nagle


From dotancohen at gmail.com  Tue Aug 11 14:29:40 2009
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 11 Aug 2009 21:29:40 +0300
Subject: Scraping Wikipedia with Python
In-Reply-To: <4a81b6f0$0$1590$742ec2ed@news.sonic.net>
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
Message-ID: <880dece00908111129k525a0614td4c59a7a9371a7ba@mail.gmail.com>

> ? ?Wikipedia has an API for computer access. ?See
>
> ? ? ? ?http://www.mediawiki.org/wiki/API
>

Yes, I am aware of this as well. Does anyone know of a python class
for easily interacting with it, or do I need to roll my own.

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il


From greg.kujawa at gmail.com  Tue Aug 11 14:34:54 2009
From: greg.kujawa at gmail.com (gregarican)
Date: Tue, 11 Aug 2009 11:34:54 -0700 (PDT)
Subject: Networked Broadcast Messaging
References: <37ea826b-708d-48f4-a64a-42f58fec5325@c2g2000yqi.googlegroups.com>
Message-ID: <889a2a1d-e791-479e-8e41-4387e1b258fd@z31g2000yqd.googlegroups.com>

On Aug 11, 2:14?pm, "squishywaf... at gmail.com"
 wrote:
> I'm not exactly sure what the term for this would be, but I was
> wondering if there were any Python packages that supported some kind
> of ad-hoc message broadcasting. What I'd like to do is something like
> this:
>
> * On a number of workhorse machines, a process listens for network
> messages from our broadcast service. It subscribes to a certain sub-
> set of them and will only respond to the messaging events that it is
> subscribed to.
> * Any machine can broadcast a message out to the network of machines
> without specifying an IP address.
> * Machines can come and go. Since messages are not directly sent to a
> specific IP address from our Python script, the messages are simply
> broadcasted to those who are there to listen. If nobody is subscribed
> to the message type being sent, nothing happens.
>
> I know XML-RPC and other friends are an option, but I'm looking for
> something that doesn't require managing a set of IP addresses or
> hostnames. I'm not sure what to Google for such a package/module, any
> direction would be greatly appreciated.

Offhand I'd suggest binding a specific UDP port on the listening
workstations. Then the broadcasting workstation(s) could just pull a
standard list of IP's based on its own subnet. Then there'd be no hard-
coded machine names or IP addresses to manage. Just send the message
to all hosts on the same subnet as the broadcaster(s). Plus the UDP
connection would be stateless and not care if the receivers actually
got the message or not...


From kushal.kumaran+python at gmail.com  Tue Aug 11 14:39:30 2009
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Wed, 12 Aug 2009 00:09:30 +0530
Subject: better way?
In-Reply-To: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
Message-ID: <1e364c4e0908111139r5c4536d6s90be6cf5aef2d26a@mail.gmail.com>

On Tue, Aug 11, 2009 at 10:03 PM, someone wrote:
> Hello,
>
> I'd like to make insert into db if record not exist otherwise update.
> to save typing list of columns in both statements I do following
>
> 
>
>
> is there better or more readable way to do it?
>

Well, mysql, in particular, offers an "on duplicate key update" clause
that you can take a look at.  Don't know about about other databases.

-- 
kushal


From http  Tue Aug 11 14:40:46 2009
From: http (Paul Rubin)
Date: 11 Aug 2009 11:40:46 -0700
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
Message-ID: <7xk51anqhd.fsf@ruckus.brouhaha.com>

Steven D'Aprano  writes:
> - if people are keen on a Python wiki, then by all means publish one, 
> just don't expect the Python dev team to build and manage it for you;

There are already some nice ones at:

   http://en.wikibooks.org/wiki/Python


From python at rcn.com  Tue Aug 11 14:43:29 2009
From: python at rcn.com (Raymond Hettinger)
Date: Tue, 11 Aug 2009 11:43:29 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References:   
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	 
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> 
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	 
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	 
	<081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com> 
	<7xr5vj9m0g.fsf@ruckus.brouhaha.com>
Message-ID: <2fd432c7-00e2-4bb6-9192-e9f7aa96c4d7@m3g2000pri.googlegroups.com>

[Paul Rubin]
> I think the Python tutorial is aimed at users who are newbies to
> Python but not newbies to programming. ?Writing a tutorial for total
> newbies is a completely different problem, that would result in a much
> different document that's less useful to the existing tutorial's
> intended audience.

There is more than one right answer to "what is the best tutorial
for different people".  The www.python.org website lists a number
of tutorials.  Here is the page specifically marked for those
who are new to programming:

 http://wiki.python.org/moin/BeginnersGuide


Raymond





From petshmidt at googlemail.com  Tue Aug 11 14:45:50 2009
From: petshmidt at googlemail.com (Pet)
Date: Tue, 11 Aug 2009 11:45:50 -0700 (PDT)
Subject: better way?
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
Message-ID: <78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>

On 11 Aug., 20:39, Kushal Kumaran 
wrote:
> On Tue, Aug 11, 2009 at 10:03 PM, someone wrote:
> > Hello,
>
> > I'd like to make insert into db if record not exist otherwise update.
> > to save typing list of columns in both statements I do following
>
> > 
>
> > is there better or more readable way to do it?
>
> Well, mysql, in particular, offers an "on duplicate key update" clause
> that you can take a look at. ?Don't know about about other databases.
>
> --
> kushal

Oh, forgotten to mention. It's PostGres


From http  Tue Aug 11 14:52:46 2009
From: http (Paul Rubin)
Date: 11 Aug 2009 11:52:46 -0700
Subject: Python docs disappointing - group effort to hire writers?
References:  
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	<4A80472E.4090108@stoneleaf.us>
	
	
	<63f2b657-c646-4a69-9a05-1da5975bb6d2@z31g2000yqd.googlegroups.com>
Message-ID: <7xfxbynpxd.fsf@ruckus.brouhaha.com>

r  writes:
> Some say the tutorial is not meant for non-programmers, but for
> programmers with no Python experience. So! How does that justify
> obstruction of the tut? Why not present the same information in a way
> both can easily understand? 

I agree that a tutorial for non-programmers would be useful, but it's
better to have it as a separate document.  The existing tutorial helps
experienced programmers get started with Python very quickly, by
checking off familiar features from other languages and saying how
Python implements them.  Someone familiar with (say) Java or C++ can
read it in a few minutes and start contributing to a Python project.
Pitching it to complete beginners would require covering a lot of
ground that is already well known to someone who programs in other
languages, and would slow it down too much. 


From dullrich at sprynet.com  Tue Aug 11 14:53:03 2009
From: dullrich at sprynet.com (David C Ullrich)
Date: Tue, 11 Aug 2009 13:53:03 -0500
Subject: Scraping Wikipedia with Python
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	
Message-ID: <6YidncRAiJ6SIxzXRVn_vwA@giganews.com>

On Tue, 11 Aug 2009 21:29:40 +0300, Dotan Cohen wrote:

>> ? ?Wikipedia has an API for computer access. ?See
>>
>> ? ? ? ?http://www.mediawiki.org/wiki/API
>>
>>
> Yes, I am aware of this as well. Does anyone know of a python class for
> easily interacting with it, or do I need to roll my own.

Try reading a little there! Starting there I went to

http://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot

where I found a section on existing bots, comments on how the "scraping"
is not what you want, and even a Python section with a link to something 
labelled  PyWikipediaBot...






From http  Tue Aug 11 14:54:16 2009
From: http (Paul Rubin)
Date: 11 Aug 2009 11:54:16 -0700
Subject: Python docs disappointing - group effort to hire writers?
References:  
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro
	ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	
	<081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com>
	<7xr5vj9m0g.fsf@ruckus.brouhaha.com>
	<2fd432c7-00e2-4bb6-9192-e9f7aa96c4d7@m3g2000pri.googlegroups.com>
Message-ID: <7xab266v1j.fsf@ruckus.brouhaha.com>

Raymond Hettinger  writes:
> Here is the page specifically marked for those who are new to programming:
>  http://wiki.python.org/moin/BeginnersGuide

Oh cool, I didn't know about that one.


From kushal.kumaran+python at gmail.com  Tue Aug 11 15:00:37 2009
From: kushal.kumaran+python at gmail.com (Kushal Kumaran)
Date: Wed, 12 Aug 2009 00:30:37 +0530
Subject: Networked Broadcast Messaging
In-Reply-To: <889a2a1d-e791-479e-8e41-4387e1b258fd@z31g2000yqd.googlegroups.com>
References: <37ea826b-708d-48f4-a64a-42f58fec5325@c2g2000yqi.googlegroups.com>
	<889a2a1d-e791-479e-8e41-4387e1b258fd@z31g2000yqd.googlegroups.com>
Message-ID: <1e364c4e0908111200j5d83b5d4o6ab950b82265189c@mail.gmail.com>

On Wed, Aug 12, 2009 at 12:04 AM, gregarican wrote:
> On Aug 11, 2:14?pm, "squishywaf... at gmail.com"
>  wrote:
>> I'm not exactly sure what the term for this would be, but I was
>> wondering if there were any Python packages that supported some kind
>> of ad-hoc message broadcasting. What I'd like to do is something like
>> this:
>>
>> * On a number of workhorse machines, a process listens for network
>> messages from our broadcast service. It subscribes to a certain sub-
>> set of them and will only respond to the messaging events that it is
>> subscribed to.
>> * Any machine can broadcast a message out to the network of machines
>> without specifying an IP address.
>> * Machines can come and go. Since messages are not directly sent to a
>> specific IP address from our Python script, the messages are simply
>> broadcasted to those who are there to listen. If nobody is subscribed
>> to the message type being sent, nothing happens.
>>
>> I know XML-RPC and other friends are an option, but I'm looking for
>> something that doesn't require managing a set of IP addresses or
>> hostnames. I'm not sure what to Google for such a package/module, any
>> direction would be greatly appreciated.
>
> Offhand I'd suggest binding a specific UDP port on the listening
> workstations. Then the broadcasting workstation(s) could just pull a
> standard list of IP's based on its own subnet. Then there'd be no hard-
> coded machine names or IP addresses to manage. Just send the message
> to all hosts on the same subnet as the broadcaster(s). Plus the UDP
> connection would be stateless and not care if the receivers actually
> got the message or not...

You could use the socket module to broadcast.  Using INADDR_BROADCAST
as the destination should do it.  I fail to recollect whether that
will need root privileges...

-- 
kushal


From maximilianbianco at gmail.com  Tue Aug 11 15:01:00 2009
From: maximilianbianco at gmail.com (max bianco)
Date: Tue, 11 Aug 2009 15:01:00 -0400
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <0006817d$0$2895$c3e8da3@news.astraweb.com>
References: 
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com>
Message-ID: 

On Sat, Aug 8, 2009 at 12:25 AM, Steven
D'Aprano wrote:
> On Fri, 07 Aug 2009 13:35:26 -0700, Kee Nethery wrote:
>
>
>> > Why exactly is posting an open comment on a bug tracker somehow
>> > inferior to posting an open comment on a wiki?
>>
>> It's a good question and deserves a good answer.
>>
>> * Fewer Steps
>> * Immediate
>> * Does not need to be formally reviewed
>> * Easier to search
>
> The last one is actually wrong, because the Python bug tracker is indexed
> by Google.
>
> As for the rest, you're right that the current bug-tracker puts up
> barriers to people submitting comments and bugs. That's actually a good
> thing. The only thing worse than not enough information is too much
> information, and the current situation does a good job of discouraging
> the sorts of people who submit bad bug reports (e.g. duplicates of bug
> reports, bug reports for things fixed years ago, bug reports that are due
> to mistakes in their code, etc.).
>
>
>> For example
>> purposes, I'll use the following page:
>> http://docs.python.org/reference/lexical_analysis.html
>> Lets say the user is in section 2.1.3 Comments
>
> Disclaimer: python.org is down at the moment, so I can't check that page
> to see precisely what you're talking about.
>
>
>> Here's the scenario: The user wanted to include "#" in one of their
>> strings and the IDE kept interpreting it as a comment. But they really
>> need to use that character in the string. Eventually they find out that
>> they can escape the character in their string so that Python stops
>> thinking it is the beginning of a comment.
>
> Er, that would be a bug in the IDE, surely? Inside strings, # is an
> ordinary character with no special meaning.
>
>
>>>> s = "this is a string with an unescaped # in it"
>>>> s
> 'this is a string with an unescaped # in it'
>
>
> The Python docs are supposed to be about Python the language, not work-
> arounds for IDE bugs.
>
>
> [...]
>> Lets assume that Python experts all agree that
>> the docs should get updated with this gotcha (which as a newbie, they
>> are not sure that is a valid assumption and would probably just halt
>> in their quest to get the docs updated).
>
> Good.
>
> As a newbie, you SHOULD assume that anything you think is a bug is
> probably a bug in YOUR code, not Python, and the same goes for
> documentation bugs. If you don't understand something in the docs,
> chances are that it's a problem with you, not the docs. Your first port
> of call should be the tutor list, or here, and not to "fix" the docs by
> putting in noise that just gets in the way of the intended audience,
> namely experienced developers.
>
I assume I am misunderstanding you here and you meant something else?
Python is paraded as a good language for beginners. Is this a false
statement or a secondary objective? Or are the docs only meant for
experienced developers? That just doesn't sound right.


From invalid at invalid  Tue Aug 11 15:01:35 2009
From: invalid at invalid (Grant Edwards)
Date: Tue, 11 Aug 2009 14:01:35 -0500
Subject: Python docs disappointing - group effort to hire writers?
References:  
	<09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com>
	
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com>
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	<4A80472E.4090108@stoneleaf.us>
	
	
	<63f2b657-c646-4a69-9a05-1da5975bb6d2@z31g2000yqd.googlegroups.com>
	<7xfxbynpxd.fsf@ruckus.brouhaha.com>
Message-ID: 

On 2009-08-11, Paul Rubin  wrote:
> r  writes:
>> Some say the tutorial is not meant for non-programmers, but for
>> programmers with no Python experience. So! How does that justify
>> obstruction of the tut? Why not present the same information in a way
>> both can easily understand? 
>
> I agree that a tutorial for non-programmers would be useful, but it's
> better to have it as a separate document.

There are plenty of docs aimed at non-programmers.  I've heard
this one recommended many times:

http://www.greenteapress.com/thinkpython/

-- 
Grant Edwards                   grante             Yow! Am I having fun yet?
                                  at               
                               visi.com            


From maximilianbianco at gmail.com  Tue Aug 11 15:03:09 2009
From: maximilianbianco at gmail.com (max bianco)
Date: Tue, 11 Aug 2009 15:03:09 -0400
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References:  
	<109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com>
	<756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com>
	
	<5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
Message-ID: 

On Thu, Aug 6, 2009 at 2:36 PM, Kee Nethery wrote:
> As someone trying to learn the language I want to say that the tone on this
> list towards people who are trying to learn Python ?feels like it has become
> anti-newbies.
>
> Learning a new language is difficult enough without seeing other newbies
> getting shamed for not knowing everything there is to know about Python
> before asking their questions.

Well I have to say your right about the tone but using google before
you ask is not an unreasonable expectation. I have of course broken
this golden rule myself on mailing lists myself , however a response
like use google is totally acceptable to me.


From squishywaffle at gmail.com  Tue Aug 11 15:06:41 2009
From: squishywaffle at gmail.com (Greg Taylor)
Date: Tue, 11 Aug 2009 12:06:41 -0700 (PDT)
Subject: Networked Broadcast Messaging
References: <37ea826b-708d-48f4-a64a-42f58fec5325@c2g2000yqi.googlegroups.com>
	<889a2a1d-e791-479e-8e41-4387e1b258fd@z31g2000yqd.googlegroups.com> 
	
Message-ID: <4dc5c63e-55d6-4758-b2e6-f405571347df@g31g2000yqc.googlegroups.com>

On Aug 11, 3:00?pm, Kushal Kumaran 
wrote:
> You could use the socket module to broadcast. ?Using INADDR_BROADCAST
> as the destination should do it. ?I fail to recollect whether that
> will need root privileges...

Awesome, I think this is exactly what I'm looking for. Much
appreciated!

Greg


From invalid at invalid  Tue Aug 11 15:11:37 2009
From: invalid at invalid (Grant Edwards)
Date: Tue, 11 Aug 2009 14:11:37 -0500
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com>
	
Message-ID: 

On 2009-08-11, max bianco  wrote:

> I assume I am misunderstanding you here and you meant something else?
> Python is paraded as a good language for beginners.

I believe it is a good language for beginners.

> Is this a false statement or a secondary objective?

Objective of what?

> Or are the docs only meant for experienced developers?

Some are, some aren't.  The "standard" docs (most of the docs
you can reach directly from http://www.python.org/doc/ --
including the tutorial) aren't intended to teach somebody how
to program and assume the reader has a basic grounding in
programming and language theory.

There are plenty of books and tutorials that are aimed at
teaching programming and Python at the same time.  You can find
some of via the links listed under "Additional documentation"
at http://www.python.org/doc/ -- particularly here:

 http://wiki.python.org/moin/BeginnersGuide/NonProgrammers

> That just doesn't sound right.

-- 
Grant Edwards                   grante             Yow! My mind is making
                                  at               ashtrays in Dayton ...
                               visi.com            


From dotancohen at gmail.com  Tue Aug 11 15:14:07 2009
From: dotancohen at gmail.com (Dotan Cohen)
Date: Tue, 11 Aug 2009 22:14:07 +0300
Subject: Scraping Wikipedia with Python
In-Reply-To: <6YidncRAiJ6SIxzXRVn_vwA@giganews.com>
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	
	<6YidncRAiJ6SIxzXRVn_vwA@giganews.com>
Message-ID: <880dece00908111214y5def00afqe1e8849edd73d7e7@mail.gmail.com>

> Try reading a little there! Starting there I went to
>
> http://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot
>
> where I found a section on existing bots, comments on how the "scraping"
> is not what you want, and even a Python section with a link to something
> labelled ?PyWikipediaBot...
>

Thanks. I read the first bit of that page, but did not finish it.
Grepping it for Python led to to what I need.

Sorry for the noise.


-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il


From dmitrey.kroshko at scipy.org  Tue Aug 11 15:15:13 2009
From: dmitrey.kroshko at scipy.org (dmitrey)
Date: Tue, 11 Aug 2009 12:15:13 -0700 (PDT)
Subject: for key, value in dict.() - how to get? (which func)
Message-ID: 

hi all,
which method should I use to get iterator over (key, value) pairs for
Python dict, Python v 2.6 and above?

Of course I could use

for key in myDict.keys():
    value = myDict.values()
    # do something with the pair key, value

but searching each time for the value take some cputime that is
serious for the task involved

IIRC in python 2.5 I have something like keyvalues(), but I don't see
something like that in current dir(myDict).

Thank you in advance, D.


From rami.chowdhury at gmail.com  Tue Aug 11 15:23:46 2009
From: rami.chowdhury at gmail.com (Rami Chowdhury)
Date: Tue, 11 Aug 2009 12:23:46 -0700
Subject: better way?
In-Reply-To: <78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
Message-ID: 

IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than  
MySQL...

On Tue, 11 Aug 2009 11:45:50 -0700, Pet  wrote:

> On 11 Aug., 20:39, Kushal Kumaran 
> wrote:
>> On Tue, Aug 11, 2009 at 10:03 PM, someone  
>> wrote:
>> > Hello,
>>
>> > I'd like to make insert into db if record not exist otherwise update.
>> > to save typing list of columns in both statements I do following
>>
>> > 
>>
>> > is there better or more readable way to do it?
>>
>> Well, mysql, in particular, offers an "on duplicate key update" clause
>> that you can take a look at. ?Don't know about about other databases.
>>
>> --
>> kushal
>
> Oh, forgotten to mention. It's PostGres



-- 
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)


From rami.chowdhury at gmail.com  Tue Aug 11 15:26:05 2009
From: rami.chowdhury at gmail.com (Rami Chowdhury)
Date: Tue, 11 Aug 2009 12:26:05 -0700
Subject: for key, value in dict.() - how to get? (which func)
In-Reply-To: 
References: 
Message-ID: 

Hi Dmitrey,

I think what you're looking for is myDict.items(), or myDict.iteritems().

Cheers,
Rami

On Tue, 11 Aug 2009 12:15:13 -0700, dmitrey   
wrote:

> hi all,
> which method should I use to get iterator over (key, value) pairs for
> Python dict, Python v 2.6 and above?
>
> Of course I could use
>
> for key in myDict.keys():
>     value = myDict.values()
>     # do something with the pair key, value
>
> but searching each time for the value take some cputime that is
> serious for the task involved
>
> IIRC in python 2.5 I have something like keyvalues(), but I don't see
> something like that in current dir(myDict).
>
> Thank you in advance, D.



-- 
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)


From ethan at stoneleaf.us  Tue Aug 11 15:30:00 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Tue, 11 Aug 2009 12:30:00 -0700
Subject: Programming by Contract
In-Reply-To: <4A7A15CD.9090306@stoneleaf.us>
References: <4A7A15CD.9090306@stoneleaf.us>
Message-ID: <4A81C6B8.7010605@stoneleaf.us>

Ethan Furman wrote:
> Greetings!
> 
> I have seen posts about the assert statement and PbC (or maybe it was 
> DbC), and I just took a very brief look at pycontract 
> (http://www.wayforward.net/pycontract/) and now I have at least one 
> question:  Is this basically another way of thinking about unit testing, 
> or is the idea of PbC more along the lines of *always* checking the 
> input/output of functions to ensure they are correct?  (*Contstant 
> vigilance!* as Prof Moody would say ;)
> 
> I know asserts can be turned off, so they obviously won't work for the 
> latter case, and having seen the sample of pycontract it seems it only 
> does its thing during debugging.
> 
> So is Design (Programming) by Contract a fancy way of saying "Document 
> your inputs/outputs!" or is there more to it?
> 
> ~Ethan~

Hmmm...

Well, from the (apparently) complete lack of interest, I shall take away 
the (better?) documentation ideas and unit testing ideas, and not worry 
about the rest.  :)

~Ethan~


From dmitrey.kroshko at scipy.org  Tue Aug 11 15:31:27 2009
From: dmitrey.kroshko at scipy.org (dmitrey)
Date: Tue, 11 Aug 2009 12:31:27 -0700 (PDT)
Subject: for key, value in dict.() - how to get? (which func)
References: 
	
Message-ID: 

Yes, thank you, items() is the correct approach, on the other hand I
have already get rid of the cycle.
Regards, D.

On Aug 11, 10:26?pm, "Rami Chowdhury" 
wrote:
> Hi Dmitrey,
>
> I think what you're looking for is myDict.items(), or myDict.iteritems().
>
> Cheers,
> Rami
>
> On Tue, 11 Aug 2009 12:15:13 -0700, dmitrey  ?
> wrote:
>
>
>
> > hi all,
> > which method should I use to get iterator over (key, value) pairs for
> > Python dict, Python v 2.6 and above?
>
> > Of course I could use
>
> > for key in myDict.keys():
> > ? ? value = myDict.values()
> > ? ? # do something with the pair key, value
>
> > but searching each time for the value take some cputime that is
> > serious for the task involved
>
> > IIRC in python 2.5 I have something like keyvalues(), but I don't see
> > something like that in current dir(myDict).
>
> > Thank you in advance, D.
>
> --
> Rami Chowdhury
> "Never attribute to malice that which can be attributed to stupidity" -- ?
> Hanlon's Razor
> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)



From Brian.Mingus at colorado.edu  Tue Aug 11 15:39:50 2009
From: Brian.Mingus at colorado.edu (Brian)
Date: Tue, 11 Aug 2009 13:39:50 -0600
Subject: Scraping Wikipedia with Python
In-Reply-To: <880dece00908111129k525a0614td4c59a7a9371a7ba@mail.gmail.com>
References:  
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	<880dece00908111129k525a0614td4c59a7a9371a7ba@mail.gmail.com>
Message-ID: <9839a05c0908111239w64e507beud9492d58dee8f0a5@mail.gmail.com>

On Tue, Aug 11, 2009 at 12:29 PM, Dotan Cohen  wrote:

> >    Wikipedia has an API for computer access.  See
> >
> >        http://www.mediawiki.org/wiki/API
> >
>
> Yes, I am aware of this as well. Does anyone know of a python class
> for easily interacting with it, or do I need to roll my own.
>
> --
> Dotan Cohen
>

https://mwclient.svn.sourceforge.net/svnroot/mwclient/trunk/mwclient/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From petshmidt at googlemail.com  Tue Aug 11 15:40:22 2009
From: petshmidt at googlemail.com (Pet)
Date: Tue, 11 Aug 2009 12:40:22 -0700 (PDT)
Subject: better way?
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
Message-ID: <7b9a2a26-3b6a-48b9-bb63-da05e24c9b39@c1g2000yqi.googlegroups.com>

On 11 Aug., 21:23, "Rami Chowdhury"  wrote:
> IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than ?
> MySQL...
>

Ok, I've completely failed here :)

Thanks, man

>
>
>
>
> On Tue, 11 Aug 2009 11:45:50 -0700, Pet  wrote:
> > On 11 Aug., 20:39, Kushal Kumaran 
> > wrote:
> >> On Tue, Aug 11, 2009 at 10:03 PM, someone ?
> >> wrote:
> >> > Hello,
>
> >> > I'd like to make insert into db if record not exist otherwise update.
> >> > to save typing list of columns in both statements I do following
>
> >> > 
>
> >> > is there better or more readable way to do it?
>
> >> Well, mysql, in particular, offers an "on duplicate key update" clause
> >> that you can take a look at. ?Don't know about about other databases.
>
> >> --
> >> kushal
>
> > Oh, forgotten to mention. It's PostGres
>
> --
> Rami Chowdhury
> "Never attribute to malice that which can be attributed to stupidity" -- ?
> Hanlon's Razor
> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)



From mgi820 at motorola.com  Tue Aug 11 15:44:49 2009
From: mgi820 at motorola.com (Gary Duzan)
Date: Tue, 11 Aug 2009 19:44:49 +0000 (UTC)
Subject: for key, value in dict.() - how to get? (which func)
References: 
Message-ID: 

In article ,
dmitrey   wrote:
>hi all,
>which method should I use to get iterator over (key, value) pairs for
>Python dict, Python v 2.6 and above?

   dict.iteritems()

>>> import sys
>>> for (key, value) in sys.modules.iteritems(): print key, value

					Gary Duzan
					Motorola H&NM




From pacificik at warnell.uga.edu  Tue Aug 11 15:47:47 2009
From: pacificik at warnell.uga.edu (Krishna Pacifici)
Date: Tue, 11 Aug 2009 15:47:47 -0400
Subject: adding multiple new values to the same key in a dictionary
Message-ID: <4A8192A30200008C00014AB9@redhorse.forestry.uga.edu>

Hi,
I want to be able to add multiple new values to a key in a dictionary.

I have tried the following:

sec_dict_clean=
{88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85]}

for i in range(len(sec_dict_clean.values())):
    for j in range(len(sec_dict_clean.values()[i])):
        sec_dict_clean.setdefault(key,[]).append(blocks[sec_dict_clean.values()[i][j]].abundance)

where blocks[...].abundance gives me a single value from an object,

but this gives me the following:

sec_dict_clean=
{88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85, 4, 12, 11, 6, 9, 12, 11, 7, 10, 10, 12, 9, 6, 12, 15, 9, 8, 12, 15, 12, 12]}

instead I want each abundance (starts with 4, 12...) to be associated with each of the values so that it would look like this:

sec_dict_clean=
{88: ([87, 89, 78, 98], [4,12,11,6]), 58: ([57, 59, 48, 68], [9,12,11,7]), 69: ([79], [10])...}

You can see there are several errors here (I have more things being appended than there are values in the dictionary), but I really just want to know how to add multiple values to the same key in a dictionary.

Thanks for any help,
Krishna


-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rt8396 at gmail.com  Tue Aug 11 15:55:27 2009
From: rt8396 at gmail.com (r)
Date: Tue, 11 Aug 2009 12:55:27 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com> 
	
	
Message-ID: <6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com>

Ok people follow me here. Open your winders help file and click the
"Tutorial" link. What is this FLUFF doing here!?!?! Where is the damn
index? Where is the damn tutorial? I want to learn Python not read the
HISTORY OF THE WORLD.

Upon clicking the "Tutorial" link pre 2.6, a nice menu was placed
before your eyes, WHERE IS IT!?!??? Good thing i know the language or
i would have given up already!!!!


From rcdailey at gmail.com  Tue Aug 11 16:08:19 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Tue, 11 Aug 2009 13:08:19 -0700 (PDT)
Subject: Need cleanup advice for multiline string
Message-ID: 

Hey guys. Being a C++ programmer, I like to keep variable definitions
close to the location in which they will be used. This improves
readability in many ways. However, when I have a multi-line string
definition at function level scope, things get tricky because of the
indents. In this case indents are serving two purposes: For syntax and
actual text output. The tabs for function scope should not be included
in the contents of the string. Below is the code I am trying to
improve. Notice how it looks ugly/unreadable because of the way the
string contents are shifted all the way to the left edge of the
document. This breaks the flow of scope. Would you guys solve this
problem by moving failMsg into global scope? Perhaps through some
other type of syntax?

Help is appreciated!

def RunCommand( commandList ):
   commandString =
   print( 'Running Command:',  )
   cmd = subprocess.Popen( commandList )
   returnCode = cmd.wait()
   if returnCode:
      failMsg = '''\
*************************************************
The following command returned exit code [{:#x}].
This represents failure of some form. Please review
the command output for more details on the issue.
------------
{}
*************************************************
'''
      commandString = ' '.join( commandList )
      raise CommandFailure( failMsg.format( returnCode,
commandString ) )


From matthew at woodcraft.me.uk  Tue Aug 11 16:10:03 2009
From: matthew at woodcraft.me.uk (Matthew Woodcraft)
Date: Tue, 11 Aug 2009 20:10:03 GMT
Subject: better way?
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
Message-ID: <87skfyjen8.fsf@golux.woodcraft.me.uk>

"Rami Chowdhury"  writes:

> IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than
> MySQL...

PostgreSQL does not have ON DUPLICATE KEY UPDATE.

The SQL standard way to do what the OP wants is MERGE. PostgreSQL
doesn't have that either.

-M-


From breamoreboy at yahoo.co.uk  Tue Aug 11 16:12:29 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 21:12:29 +0100
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com>
References: 	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>	<7xab2c52y6.fsf@ruckus.brouhaha.com>	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>	<7xk51fgazf.fsf@ruckus.brouhaha.com>					<0006817d$0$2895$c3e8da3@news.astraweb.com>
		
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com>
Message-ID: 

r wrote:
> Ok people follow me here. Open your winders help file and click the
> "Tutorial" link. What is this FLUFF doing here!?!?! Where is the damn
> index? Where is the damn tutorial? I want to learn Python not read the
> HISTORY OF THE WORLD.
> 
> Upon clicking the "Tutorial" link pre 2.6, a nice menu was placed
> before your eyes, WHERE IS IT!?!??? Good thing i know the language or
> i would have given up already!!!!
As I keep on repeating, my version works perfectly.  Perhaps this is 
because I have a computing IQ of approximately 2**32, so realised that 
something was wrong, went here and downloaded the corrected version of 
the file, which has presumably been available for months!!!!!

http://www.python.org/download/releases/2.6.2/

And you want newbies let loose on the python docs.  As good ole Santa 
would say, ho, ho, ho!
-- 
Kindest regards.

Mark Lawrence.



From rcdailey at gmail.com  Tue Aug 11 16:16:58 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Tue, 11 Aug 2009 13:16:58 -0700 (PDT)
Subject: Need cleanup advice for multiline string
References: 
Message-ID: <30eb6e66-1d5c-4a76-b80d-54d11bafbdb3@h31g2000yqd.googlegroups.com>

On Aug 11, 3:08?pm, Robert Dailey  wrote:
> Hey guys. Being a C++ programmer, I like to keep variable definitions
> close to the location in which they will be used. This improves
> readability in many ways. However, when I have a multi-line string
> definition at function level scope, things get tricky because of the
> indents. In this case indents are serving two purposes: For syntax and
> actual text output. The tabs for function scope should not be included
> in the contents of the string. Below is the code I am trying to
> improve. Notice how it looks ugly/unreadable because of the way the
> string contents are shifted all the way to the left edge of the
> document. This breaks the flow of scope. Would you guys solve this
> problem by moving failMsg into global scope? Perhaps through some
> other type of syntax?
>
> Help is appreciated!
>
> def RunCommand( commandList ):
> ? ?commandString =
> ? ?print( 'Running Command:', ?)
> ? ?cmd = subprocess.Popen( commandList )
> ? ?returnCode = cmd.wait()
> ? ?if returnCode:
> ? ? ? failMsg = '''\
> *************************************************
> The following command returned exit code [{:#x}].
> This represents failure of some form. Please review
> the command output for more details on the issue.
> ------------
> {}
> *************************************************
> '''
> ? ? ? commandString = ' '.join( commandList )
> ? ? ? raise CommandFailure( failMsg.format( returnCode,
> commandString ) )

And yes, I recognize there are syntax errors. Ignore those for now.


From rami.chowdhury at gmail.com  Tue Aug 11 16:19:00 2009
From: rami.chowdhury at gmail.com (Rami Chowdhury)
Date: Tue, 11 Aug 2009 13:19:00 -0700
Subject: better way?
In-Reply-To: <87skfyjen8.fsf@golux.woodcraft.me.uk>
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
	<87skfyjen8.fsf@golux.woodcraft.me.uk>
Message-ID: 

Ah, my apologies, I must have been getting it confused with ON UPDATE  
[things]. Thanks for correcting me.

On Tue, 11 Aug 2009 13:10:03 -0700, Matthew Woodcraft  
 wrote:

> "Rami Chowdhury"  writes:
>
>> IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than
>> MySQL...
>
> PostgreSQL does not have ON DUPLICATE KEY UPDATE.
>
> The SQL standard way to do what the OP wants is MERGE. PostgreSQL
> doesn't have that either.
>
> -M-



-- 
Rami Chowdhury
"Never attribute to malice that which can be attributed to stupidity" --  
Hanlon's Razor
408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)


From cmalmqui at gmail.com  Tue Aug 11 16:20:35 2009
From: cmalmqui at gmail.com (cmalmqui)
Date: Tue, 11 Aug 2009 13:20:35 -0700 (PDT)
Subject: ElementTree - Howto access text within XML tag element...
References: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
	<7ecm77F2fbf71U1@mid.uni-berlin.de>
Message-ID: 

On Aug 11, 9:51?am, "Diez B. Roggisch"  wrote:
> cmalmqui schrieb:
> > Hi,
>
> > I am writing on a small XML parser and are currently stuck as I am not
> > able to get the whole element name in ElementTree.
>
> > Please see the below example where "print root[0][0]" returns
> > ""
>
> > Is there a way to get hold of the "Running" string in the tag using
> > elementTree?
>
> > 
> > ? ? 
> > ? ? ? 2009-07-10T14:48:00Z
> > ? ? ? 
> > ? ? ? .........
>
> > For those of you that know how to program XML I have another
> > question:
> > I am currently "hardcoding" my XML parser using brackets, is this a
> > good approach or should I build it using a "search on tag" approach.
>
> What do you mean by that - hardcoding by brackets?
>
> Diez

Indeed, my current approach has been to hardcode the XML parser using
brackets. Is there a more elegant way?

I am parsing a garmin xml file from a handheld GPS and as you can see
in the below script, I am hardcoding each node:

import xml.etree.cElementTree as etree

def gettext(elem):
    text = elem.text or ""
    for e in elem:
        text += gettext(e)
        if e.tail:
            text += e.tail
    return text

tree = etree.parse('10_07_2009 16_48_00_history.tcx')
root = tree.getroot()

elem = root[0][0]

# ID Tag
print "type of exercise    : " + elem.get("Sport")
print "excercise starttime : " + gettext(elem[0])

# iterate over all laps
for i in range(1, len(elem)-1):

    # LAP TAG
    print "\nlap number          : " + str(i)
    print "lap start time      : " + str(elem[i].get("StartTime"))
    print "lap duration (s)    : " + gettext(elem[i][0])
    print "lap length (m)      : " + gettext(elem[i][1])
    print "max speed (km/h)    : " + gettext(elem[i][2])
    print "number of calories  : " + gettext(elem[i][3])
    print "average heartbeat   : " + gettext(elem[i][4][0])
    print "max     heartbeat   : " + gettext(elem[i][5][0])
    print "number of records   : " + str(len(elem[i][8])-1)
    for j in range(1, len(elem[i][8])-1):
        time = gettext(elem[i][8][j][0])    #time
        lat  = gettext(elem[i][8][j][1][0]) #lat
        lon  = gettext(elem[i][8][j][1][1]) #lon
        alt  = gettext(elem[i][8][j][2])    #alt
        dist = gettext(elem[i][8][j][3])    #distance from start
        bpm  = gettext(elem[i][8][j][4][0]) #beats per minute
        #print time + " " + lat + " " + lon + " " + alt + " " + dist +
" " + bpm

print "\nReceiver Info       : " + gettext(elem[len(elem)-1][0])


From darkwater42 at gmail.com  Tue Aug 11 16:20:52 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Tue, 11 Aug 2009 13:20:52 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
	 
	<0291a21a$0$20639$c3e8da3@news.astraweb.com>
Message-ID: <8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com>

On Aug 11, 2:00?pm, Steven D'Aprano  wrote:

> > test.cpp:1:1: warning: unknown escape sequence '\y'
>
> Isn't that a warning, not a fatal error? So what does temp contain?

My "Annotated C++ Reference Manual" is packed, and surprisingly in
Stroustrup's Third Edition, there is no mention of the issue in the
entire 1,000 pages. But Microsoft to the rescue:

     If you want a backslash character to appear within a string,
     you must type two backslashes (\\)

(From http://msdn.microsoft.com/en-us/library/69ze775t.aspx)

The question of what any specific C++ does if you ignore the warning
is irrelevant, as such behavior in C++ is almost *always* undefined.
Hence the warning.

|>ouglas


From cmalmqui at gmail.com  Tue Aug 11 16:21:20 2009
From: cmalmqui at gmail.com (cmalmqui)
Date: Tue, 11 Aug 2009 13:21:20 -0700 (PDT)
Subject: ElementTree - Howto access text within XML tag element...
References: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
	
Message-ID: <512cde86-d758-48b7-b474-eac48ef56c54@26g2000yqk.googlegroups.com>

On Aug 11, 9:13?am, Ned Deily  wrote:
> In article
> <1ad8dac1-8fff-493a-a197-d847e7b6a... at c2g2000yqi.googlegroups.com>,
>
> ?cmalmqui  wrote:
> > I am writing on a small XML parser and are currently stuck as I am not
> > able to get the whole element name in ElementTree.
>
> > Please see the below example where "print root[0][0]" returns
> > ""
>
> > Is there a way to get hold of the "Running" string in the tag using
> > elementTree?
>
> > 
> > ? ? 
> > ? ? ? 2009-07-10T14:48:00Z
> > ? ? ? 
> > ? ? ? .........
>
> "Running" is the value of the "Sport" attribute of the "Activity"
> element. ?The documentation for the Element interface lists several ways
> to access element attributes; in your example,
>
> >>> elem = root[0][0]
> >>> elem.get("Sport")
> 'Running'
> >>> elem.attrib
>
> {'Sport': 'Running'}>>> elem.items()
>
> [('Sport', 'Running')]
>
> Seehttp://docs.python.org/library/xml.etree.elementtree.html
>
> --
> ?Ned Deily,
> ?n... at acm.org

Excellent!
Thanks!
The XML magic is getting there slowly...


From chris at simplistix.co.uk  Tue Aug 11 16:25:47 2009
From: chris at simplistix.co.uk (Chris Withers)
Date: Tue, 11 Aug 2009 21:25:47 +0100
Subject: httplib incredibly slow :-(
Message-ID: <4A81D3CB.7080209@simplistix.co.uk>

Hi All,

I'm using the following script to download a 150Mb file:

from base64 import encodestring
from httplib import HTTPConnection
from datetime import datetime

conn = HTTPSConnection('localhost')
headers = {}
auth = 'Basic '+encodestring('username:password').strip()
headers['Authorization']=auth
t = datetime.now()
print t
conn.request('GET','/somefile.zip',None,headers)
print 'request:',datetime.now()-t
response = conn.getresponse()
print 'response:',datetime.now()-t
data = response.read()
print 'read:',datetime.now()-t

The output shows it takes over 20 minutes to do this.
However, this is on a local network, and downloading the same file in IE 
takes under 3 seconds!

I saw this issue:

http://bugs.python.org/issue2576

I tried changing the buffer size to 4096 in a subclass as the issue 
suggested, but I didn't see the reported speed improvement.
I'm using Python 2.6.2.

Does anyone know of an alternative library for creating http requests 
and getting their responses that's faster but hopefully has a similar 
interface?

Chris

-- 
Simplistix - Content Management, Batch Processing & Python Consulting
            - http://www.simplistix.co.uk


From rcdailey at gmail.com  Tue Aug 11 16:28:57 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Tue, 11 Aug 2009 13:28:57 -0700 (PDT)
Subject: Bug in format specification in Python 3?
Message-ID: 

Hello,

According to the Python 3.1 documentation, I can have a format
specification like so:

print( 'This is a hex number: {:#08x}'.format( 4 ) )

This will print:

This is a hex number: 0x000004

I notice that the '0x' portion is counted in the width, which was
specified as 8. This seems wrong to me. Is this by design? If so, why?
I expect that the width portion to only apply to the input + padding
only. I don't consider the '0x' portion part of the padding. But maybe
it is...


From http  Tue Aug 11 16:31:34 2009
From: http (Paul Rubin)
Date: 11 Aug 2009 13:31:34 -0700
Subject: Scraping Wikipedia with Python
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	
	<6YidncRAiJ6SIxzXRVn_vwA@giganews.com>
	
Message-ID: <7xd472hz2x.fsf@ruckus.brouhaha.com>

Dotan Cohen  writes:
> Thanks. I read the first bit of that page, but did not finish it.
> Grepping it for Python led to to what I need.

maybe you want dbpedia.


From breamoreboy at yahoo.co.uk  Tue Aug 11 16:32:56 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 21:32:56 +0100
Subject: Need cleanup advice for multiline string
In-Reply-To: <30eb6e66-1d5c-4a76-b80d-54d11bafbdb3@h31g2000yqd.googlegroups.com>
References: 
	<30eb6e66-1d5c-4a76-b80d-54d11bafbdb3@h31g2000yqd.googlegroups.com>
Message-ID: 

Robert Dailey wrote:
> On Aug 11, 3:08 pm, Robert Dailey  wrote:
>> Hey guys. Being a C++ programmer, I like to keep variable definitions
>> close to the location in which they will be used. This improves
>> readability in many ways. However, when I have a multi-line string
>> definition at function level scope, things get tricky because of the
>> indents. In this case indents are serving two purposes: For syntax and
>> actual text output. The tabs for function scope should not be included
>> in the contents of the string. Below is the code I am trying to
>> improve. Notice how it looks ugly/unreadable because of the way the
>> string contents are shifted all the way to the left edge of the
>> document. This breaks the flow of scope. Would you guys solve this
>> problem by moving failMsg into global scope? Perhaps through some
>> other type of syntax?
>>
>> Help is appreciated!
>>
>> def RunCommand( commandList ):
>>    commandString =
>>    print( 'Running Command:',  )
>>    cmd = subprocess.Popen( commandList )
>>    returnCode = cmd.wait()
>>    if returnCode:
>>       failMsg = '''\
>> *************************************************
>> The following command returned exit code [{:#x}].
>> This represents failure of some form. Please review
>> the command output for more details on the issue.
>> ------------
>> {}
>> *************************************************
>> '''
>>       commandString = ' '.join( commandList )
>>       raise CommandFailure( failMsg.format( returnCode,
>> commandString ) )
> 
> And yes, I recognize there are syntax errors. Ignore those for now.
For starters take a look at http://tinyurl.com/o2o8r8 , just about every 
combination of string concatenation going there.  I assume that one of 
these will let you leave failMsg where it belongs.

-- 
Kindest regards.

Mark Lawrence.



From rt8396 at gmail.com  Tue Aug 11 16:36:18 2009
From: rt8396 at gmail.com (r)
Date: Tue, 11 Aug 2009 13:36:18 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com> 
	
	 
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com> 
	
Message-ID: <875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>

Ah Ha! the docs are broken and i was right all along! Are the good
folks at Python dev rolling a new installer as we speak, or we must
wait for new version?


From ethan at stoneleaf.us  Tue Aug 11 16:38:37 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Tue, 11 Aug 2009 13:38:37 -0700
Subject: Unrecognized escape sequences in string literals
In-Reply-To: <8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com>
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>			<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>		<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>		
	<0291a21a$0$20639$c3e8da3@news.astraweb.com>
	<8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com>
Message-ID: <4A81D6CD.1060903@stoneleaf.us>

Douglas Alan wrote:
> On Aug 11, 2:00 pm, Steven D'Aprano  cybersource.com.au> wrote:
> 
> 
>>>test.cpp:1:1: warning: unknown escape sequence '\y'
>>
>>Isn't that a warning, not a fatal error? So what does temp contain?
> 
> 
> My "Annotated C++ Reference Manual" is packed, and surprisingly in
> Stroustrup's Third Edition, there is no mention of the issue in the
> entire 1,000 pages. But Microsoft to the rescue:
> 
>      If you want a backslash character to appear within a string,
>      you must type two backslashes (\\)
> 
> (From http://msdn.microsoft.com/en-us/library/69ze775t.aspx)
> 
> The question of what any specific C++ does if you ignore the warning
> is irrelevant, as such behavior in C++ is almost *always* undefined.
> Hence the warning.
> 
> |>ouglas

Almost always undefined?  Whereas with Python, and some memorization or 
a small table/list nearby, you can easily *know* what you will get.

Mind you, I'm not really vested in how Python *should* handle 
backslashes one way or the other, but I am glad it has rules that it 
follows for consitent results, and I don't have to break out a byte-code 
editor to find out what's in my string literal.

~Ethan~


From bearophileHUGS at lycos.com  Tue Aug 11 16:40:24 2009
From: bearophileHUGS at lycos.com (Bearophile)
Date: Tue, 11 Aug 2009 13:40:24 -0700 (PDT)
Subject: Need cleanup advice for multiline string
References: 
Message-ID: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>

Robert Dailey:
> This breaks the flow of scope. Would you guys solve this
> problem by moving failMsg into global scope?
> Perhaps through some other type of syntax?

There are gals too here.
This may help:
http://docs.python.org/library/textwrap.html#textwrap.dedent

Bye,
bearophile


From breamoreboy at yahoo.co.uk  Tue Aug 11 16:46:12 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 21:46:12 +0100
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: <875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>
References: 	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>	<7xab2c52y6.fsf@ruckus.brouhaha.com>	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>	<7xk51fgazf.fsf@ruckus.brouhaha.com>					<0006817d$0$2895$c3e8da3@news.astraweb.com>
		
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com>
	
	<875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>
Message-ID: 

r wrote:
> Ah Ha! the docs are broken and i was right all along! Are the good
> folks at Python dev rolling a new installer as we speak, or we must
> wait for new version?
As I pointed out a few minutes ago thicko, the new version has been 
available for months.

-- 
Kindest regards.

Mark Lawrence.



From rays at blue-cove.com  Tue Aug 11 16:52:04 2009
From: rays at blue-cove.com (RJ)
Date: Tue, 11 Aug 2009 13:52:04 -0700
Subject: New 2.6 and wx install => DLL load failed: The specified
	procedure could not be found
Message-ID: <6.2.3.4.2.20090811134337.04a210d8@blue-cove.com>

I just installed python-2.6.2.msi from Python.org and 
wxPython2.8-win32-ansi-2.8.10.1-py26.exe and now can't import this 
wx. (I had 2.4, but uninstalled)
This reminds me of a basic question I had before: what are the 
compilers used for the Win32 binaries? Is this a compiler 
compatibility issue? a wx bug?

C:\projects>python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> import wx
Traceback (most recent call last):
   File "", line 1, in 
   File 
"C:\Python26\lib\site-packages\wx-2.8-msw-ansi\wx\__init__.py", line 45,
in 
     from wx._core import *
   File "C:\Python26\lib\site-packages\wx-2.8-msw-ansi\wx\_core.py", 
line 4, in <
module>
     import _core_
ImportError: DLL load failed: The specified procedure could not be found.
 >>> 
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rcdailey at gmail.com  Tue Aug 11 16:52:34 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Tue, 11 Aug 2009 13:52:34 -0700 (PDT)
Subject: Need cleanup advice for multiline string
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>
Message-ID: <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>

On Aug 11, 3:40?pm, Bearophile  wrote:
> Robert Dailey:
>
> > This breaks the flow of scope. Would you guys solve this
> > problem by moving failMsg into global scope?
> > Perhaps through some other type of syntax?
>
> There are gals too here.
> This may help:http://docs.python.org/library/textwrap.html#textwrap.dedent
>
> Bye,
> bearophile

It's a figure of speech. And besides, why would I want programming
advice from a woman? lol. Thanks for the help.


From charles at declareSub.com  Tue Aug 11 16:53:41 2009
From: charles at declareSub.com (Charles Yeomans)
Date: Tue, 11 Aug 2009 16:53:41 -0400
Subject: Programming by Contract
In-Reply-To: <4A81C6B8.7010605@stoneleaf.us>
References: <4A7A15CD.9090306@stoneleaf.us> <4A81C6B8.7010605@stoneleaf.us>
Message-ID: <18F0FD2E-7C01-4B1C-85DF-28433C23D886@declareSub.com>


On Aug 11, 2009, at 3:30 PM, Ethan Furman wrote:

> Ethan Furman wrote:
>> Greetings!
>> I have seen posts about the assert statement and PbC (or maybe it  
>> was DbC), and I just took a very brief look at pycontract (http://www.wayforward.net/pycontract/ 
>> ) and now I have at least one question:  Is this basically another  
>> way of thinking about unit testing, or is the idea of PbC more  
>> along the lines of *always* checking the input/output of functions  
>> to ensure they are correct?  (*Contstant vigilance!* as Prof Moody  
>> would say ;)
>> I know asserts can be turned off, so they obviously won't work for  
>> the latter case, and having seen the sample of pycontract it seems  
>> it only does its thing during debugging.
>> So is Design (Programming) by Contract a fancy way of saying  
>> "Document your inputs/outputs!" or is there more to it?
>> ~Ethan~
>
> Hmmm...
>
> Well, from the (apparently) complete lack of interest, I shall take  
> away the (better?) documentation ideas and unit testing ideas, and  
> not worry about the rest.  :)
>
>




Design by contract is complementary to unit testing (I notice that the  
author of PEP 316 appears confused about this).  DbC is, roughly  
speaking, about explicit allocation of responsibility.  Consider this  
contrived example.

def foo(s):
     require(s is not None)
     //code
     ensure(hasattr(returnValue, '__iter__'))


The require condition tells you that it's the caller's responsibility  
to pass a non-nil argument to foo.  The ensure condition is a  
guarantee that foo will return something suitable for iteration, if  
the precondition in the require condition is satisfied.  These  
conditions can be enforced at runtime, but may not be, for reasons of  
performance.

DbC is in fact about not *always* checking the input/output of  
functions; on the contrary, Bertrand Meyer, the inventor of DbC,  
claims that DbC allows one to eliminate such redundancy, and the  
resulting overhead.

Charles Yeomans


From python at mrabarnett.plus.com  Tue Aug 11 17:04:43 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Tue, 11 Aug 2009 22:04:43 +0100
Subject: Bug in format specification in Python 3?
In-Reply-To: 
References: 
Message-ID: <4A81DCEB.8020805@mrabarnett.plus.com>

Robert Dailey wrote:
> Hello,
> 
> According to the Python 3.1 documentation, I can have a format
> specification like so:
> 
> print( 'This is a hex number: {:#08x}'.format( 4 ) )
> 
> This will print:
> 
> This is a hex number: 0x000004
> 
> I notice that the '0x' portion is counted in the width, which was
> specified as 8. This seems wrong to me. Is this by design? If so, why?
> I expect that the width portion to only apply to the input + padding
> only. I don't consider the '0x' portion part of the padding. But maybe
> it is...

The width portion is the width of what is produced by the specification.
The '#' tells it to add '0x', so that's part of what's produced. If you
don't want the '0x' to be counted then don't include '#' in the
specification. It makes perfect sense! :-)


From python at mrabarnett.plus.com  Tue Aug 11 17:11:57 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Tue, 11 Aug 2009 22:11:57 +0100
Subject: dictionary help
In-Reply-To: <4A816A400200008C00014A70@redhorse.forestry.uga.edu>
References: <4A816A400200008C00014A70@redhorse.forestry.uga.edu>
Message-ID: <4A81DE9D.1000505@mrabarnett.plus.com>

Krishna Pacifici wrote:
> Wow, thanks MRAB and Simon, you guys are good.
> 
> I guess I will go ahead and ask the next question that has also stumped 
> me for awhile now.
> 
> So basically I need to loop through the values in the new dictionary and 
> append attributes of a class object.  Each of the values (and keys) 
> represent a block in a grid with a specific location (e.g. 35 is the 
> block in row 3 col 5) and each block is an object with several 
> attributes associated with it.  I want to call that block and append two 
> separate attributes to the dictionary within that same key.
> 
> So again it would look something like this:
> 
> block 35 has 2 attributes, say a and b, a=2, b=5
> block 37 has a=1, b=3
> block 46 has a=3, b=8
> 
> the two attributes come from two different definitions within the class 
> statement,
> def detections
> ...
> return a
> 
> def abundance
> ...
> return b
> 
> so I would want to append to key 36 those two attributes for each block 
> so that the resulting dictionary item would look like this:
>                          a           b  
> {36:[35,37,46], [2,1,3], [5,3,8] ...}
> 
That doesn't look like a dictionary. Perhaps want you want is for the
value to be a list of lists:

     {36: [[35,37,46], [2,1,3], [5,3,8]] ...}

although you'd have parallel lists, ie a list of blocks, a list of 'a',
and a list of 'b'. A better format might be to keep a block's attributes
with the block itself.

     {36: [[35,2,5], [37,1,3], [46,3,8]] ...}

> Any help with this would be greatly appreciated.  And thank you so much 
> for all of your help thus far, I'm still pretty new to python and am 
> enjoying all of the flexibility associated with a scripting and 
> programming language.
> 
[snip]



From guthrie at mum.edu  Tue Aug 11 17:12:01 2009
From: guthrie at mum.edu (guthrie)
Date: Tue, 11 Aug 2009 14:12:01 -0700 (PDT)
Subject: run all scripts in sub-directory as subroutines?
Message-ID: 

I want to have a program which will form a list of all *.py scripts in
a sub-directory, and then call some standard messages on them. So I
can add a new data source modularly by just dropping a new file into
the sources directory with the appropriate methods in it.

For example:

path = sys.path[0]
print "Starting Directory:: " + path

getDir=path + "\Sources"            # point to directory of data
sources
for name in os.listdir(getDir):     # run collection from each source
    src = imp.load_source("data",getDir,open(getDir+"\\"+name, 'rb'))
    src.getData()
    src.doGraph()

This works fine, but in the sub-modules the sys.path appropriately
returns the same as from the parent, I want them to know their own
file names. How?? I can pass it to them, but wondered if there is a
more self-sufficient way for a module to know from where it was
invoked.


From ethan at stoneleaf.us  Tue Aug 11 17:20:18 2009
From: ethan at stoneleaf.us (Ethan Furman)
Date: Tue, 11 Aug 2009 14:20:18 -0700
Subject: Programming by Contract
In-Reply-To: <18F0FD2E-7C01-4B1C-85DF-28433C23D886@declareSub.com>
References: <4A7A15CD.9090306@stoneleaf.us> <4A81C6B8.7010605@stoneleaf.us>
	<18F0FD2E-7C01-4B1C-85DF-28433C23D886@declareSub.com>
Message-ID: <4A81E092.1070303@stoneleaf.us>

Charles Yeomans wrote:
> 
> On Aug 11, 2009, at 3:30 PM, Ethan Furman wrote:
> 
>> Ethan Furman wrote:
>>
>>> Greetings!
>>> I have seen posts about the assert statement and PbC (or maybe it  
>>> was DbC), and I just took a very brief look at pycontract 
>>> (http://www.wayforward.net/pycontract/ ) and now I have at least one 
>>> question:  Is this basically another  way of thinking about unit 
>>> testing, or is the idea of PbC more  along the lines of *always* 
>>> checking the input/output of functions  to ensure they are correct?  
>>> (*Contstant vigilance!* as Prof Moody  would say ;)
>>> I know asserts can be turned off, so they obviously won't work for  
>>> the latter case, and having seen the sample of pycontract it seems  
>>> it only does its thing during debugging.
>>> So is Design (Programming) by Contract a fancy way of saying  
>>> "Document your inputs/outputs!" or is there more to it?
>>> ~Ethan~
>>
>>
>> Hmmm...
>>
>> Well, from the (apparently) complete lack of interest, I shall take  
>> away the (better?) documentation ideas and unit testing ideas, and  
>> not worry about the rest.  :)
>>
>>
> 
> 
> 
> 
> Design by contract is complementary to unit testing (I notice that the  
> author of PEP 316 appears confused about this).  DbC is, roughly  
> speaking, about explicit allocation of responsibility.  Consider this  
> contrived example.
> 
> def foo(s):
>     require(s is not None)
>     //code
>     ensure(hasattr(returnValue, '__iter__'))
> 
> 
> The require condition tells you that it's the caller's responsibility  
> to pass a non-nil argument to foo.  The ensure condition is a  guarantee 
> that foo will return something suitable for iteration, if  the 
> precondition in the require condition is satisfied.  These  conditions 
> can be enforced at runtime, but may not be, for reasons of  performance.
> 
> DbC is in fact about not *always* checking the input/output of  
> functions; on the contrary, Bertrand Meyer, the inventor of DbC,  claims 
> that DbC allows one to eliminate such redundancy, and the  resulting 
> overhead.
> 
> Charles Yeomans

Many thanks!

So if I understand -- Python's EAFP fits well with DbC, as DbC seems 
well suited to say, "This is your responsibility, and this is mine," 
stated in programming terms (who needs comments? ;)  Combined with unit 
testing (which should be easier to design correctly given the DbC code), 
healthy code seems more attainable.

Interesting.  Thank you for the information.

~Ethan~


From darkwater42 at gmail.com  Tue Aug 11 17:29:43 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Tue, 11 Aug 2009 14:29:43 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
Message-ID: <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com>

Steven D'Aprano wrote:

> Because the cost isn't zero. Needing to write \\ in a string
> literal when you want \ is a cost,

I need to preface this entire post with the fact that I've
already used ALL of the arguments that you've provided on my
friend before I ever even came here with the topic, and my
own arguments on why Python can be considered to be doing
the right thing on this issue didn't even convince ME, much
less him. When I can't even convince myself with an argument
I'm making, then you know there's a problem with it!

Now back the our regularly scheduled debate:

I think that the total cost of all of that extra typing for
all the Python programmers in the entire world is now
significantly less than the time it took to have this
debate. Which would have never happened if Python did things
the right way on this issue to begin with. Meaning that
we're now at LESS than zero cost for doing things right!

And we haven't even yet included all the useless heat that
is going to be generated during code reviews and in-house coding
standard debates.

That's why I stand by Python's motto:

   THERE SHOULD BE ONE-- AND PREFERABLY ONLY ONE --OBVIOUS
   WAY TO DO IT.

> and having to read \\ in source code and mentally
> translate that to \ is also a cost.

For me that has no mental cost. What does have a mental cost
is remembering whether "\b" is an "unrecognized escape
sequence" or not.

> By all means argue that it's a cost that is worth paying,
> but please stop pretending that it's not a cost.

I'm not "pretending". I'm pwning you with logic and common
sense!

> Having to remember that \n is a "special" escape and \y
> isn't is also a cost, but that's a cost you pay in C++ too,
> if you want your code to compile.

Ummm, no I don't! I just always use "\\" when I want a
backslash to appear, and I only think about the more obscure
escape sequences if I actually need them, or some code that
I am reading has used them.

> By the way, you've stated repeatedly that \y will compile
> with a warning in g++. So what precisely do you get if you
> ignore the warning?

A program with undefined behavior. That's typically what a
warning means from a C++ compiler. (Sometimes it means
use of a deprecated feature, though.)

> What do other C++ compilers do?

The Microsoft compilers also consider it to be incorrect
code, as I documented in a different post.

> Apart from the lack of warning, what actually is the
> difference between Python's behavior and C++'s behavior?

That question makes just about as much sense as, "Apart
from the lack of a fatal error, what actually is the
difference between Python's behavior and C++'s?"

Sure, warnings aren't fatal errors, but if you ignore them,
then you are almost always doing something very
wrong. (Unless you're building legacy code.)

> > Furthermore, Python's strategy here is SPECIFICALLY
> > DESIGNED, according to the reference manual to catch
> > bugs. I.e., from the original posting on this issue:
>
> >      Unlike Standard C, all unrecognized escape sequences
> >      are left in the string unchanged, i.e., the backslash
> >      is left in the string.  (This behavior is useful when
> >      debugging: if an escape sequence is mistyped, the
> >      resulting output is more easily recognized as
> >      broken.)
>
> You need to work on your reading comprehension. It doesn't
> say anything about the motivation for this behaviour, let
> alone that it was "SPECIFICALLY DESIGNED" to catch bugs. It
> says it is useful for debugging. My shoe is useful for
> squashing poisonous spiders, but it wasn't designed as a
> poisonous-spider squashing device.

As I have a BS from MIT in BS-ology, I can readily set aside
your aspersions to my intellect, and point out the gross
errors of your ways: Natural language does not work the way
you claim. It is is much more practical, implicit, and
elliptical.

More specifically, if your shoe came with a reference manual
claiming that it was useful for squashing poisonous spiders,
then you may now validly assume poisonous spider squashing
was a design requirement of the shoe. (Or at least it has
become one, even if ipso facto.) Furthermore, if it turns out
that the shoe is deficient at poisonous spider squashing,
and consequently causes you to get bitten by a poisonous
spider, then you now have grounds for a lawsuit.

> > Because in the former cases it can't catch the the bug,
> > and in the latter case, it can.
>
> I'm not convinced this is a bug that needs catching, but if
> you think it is, then that's a reasonable argument.

All my arguments are reasonable.

> >> Perhaps it can catch *some* errors of that type, but
> >> only at the cost of extra effort required to defeat the
> >> compiler (forcing the programmer to type \\d to prevent
> >> the compiler complaining about \d). I don't think the
> >> benefit is worth the cost. You and your friend do. Who
> >> is to say you're right?
>
> > Well, Bjarne Stroustrup, for one.
>
> Then let him design his own language *wink*

Oh, I'm not sure that's such a good idea. He might come up
with a language as crazy as C++.

> >> In C++, if you see an escape you don't recognize, do you
> >> care?
>
> > Yes, of course I do. If I need to know what the program
> > does.
>
> Precisely the same as in Python.

Not so at all!

In C++ I only have to run for the manual only when someone
actually puts a *real* escape sequence in their code. With
Python, I have to run for the manual (or at least the REPL),
every time some lame-brained person who thinks they should be
allowed near a keyboard programs using "unrecognized escape
sequences" because they can't be bothered to hit the "\" key
twice.

> Seems to me that the answer is "It's not worse than C++,
> it's the same" -- in both cases, you have to memorize the
> "special" escape sequences, and in both cases, if you see
> an escape you don't recognize, you need to look it up.

The answer is that in this particular case, C++ causes me
far fewer woes! And if C++ is causing me fewer woes than
Language X, then you've got to know that Language X has a
problem.

> I disagree with your sense of aesthetics. I think that
> having to write \\y when I want \y just to satisfy a
> bondage-and-discipline compiler is ugly. That's not to deny
> that B&D isn't useful on occasion, but in this case I
> believe the benefit is negligible, and so even a tiny cost
> is not worth the pain.

EXPLICIT IS BETTER THAN IMPLICIT.

> > (2) That argument disagrees with the Python reference
> > manual, which explicitly states that "unrecognized escape
> > sequences are left in the string unchanged", and that the
> > purpose for doing so is because it "is useful when
> > debugging".
>
> How does it disagree? \y in the source code mapping to \y in
> the string object is the sequence being left unchanged. And
> the usefulness of doing so is hardly a disagreement over the
> fact that it does so.

Because you've stated that "\y" is a legal escape sequence,
while the Python Reference Manual explicitly states that it
is an "unrecognized escape sequence", and that such
"unrecognized escape sequences" are sources of bugs.

> > What makes it "illegal". As far as I can tell, it's just
> > another "unrecognized escape sequence".
>
> No, it's recognized, because \x is the prefix for an
> hexadecimal escape code. And it's illegal, because it's
> missing the actual hexadecimal digits.

So? Why does that make it "illegal" rather than merely
"unrecognized?"

SIMPLE IS BETTER THAN COMPLEX.

> All joking aside, syntax varies from one language to
> another. What counts as a legal escape sequence in
> Javascript and what counts as a legal escape sequence in
> Python are different. What makes you think I'm talking
> about Javascript?

Because anyone with common sense will agree that "\y" is an
illegal escape sequence. The only disagreement should then
be how illegal escape sequences should be handled. Python is
not currently handling them in a way that makes the most
sense.

ERRORS SHOULD NEVER PASS SILENTLY.

> But the morass only exists in the first place because you
> have adopted C++'s approach instead of Python's approach --
> and (possibly) not even a standard part of the C++ approach,
> but a non-standard warning provided by one compiler out of
> many.

Them's fighting words! I rarely adopt the C++ approach to
anything! In this case, (1) C++ just coincidentally happens
to be right, and (2) as far as I can tell, g++ implements
the C++ standard correctly here.

> > It may not be a complex form of DWIMing, but it's still
> > DWIMing a bit.  Python is figuring that if I typed "\z",
> > then either I must have really meant to type "\\z",
>
> Nope, not in the least. Python NEVER EVER EVER tries to
> guess what you mean.

Neither does Perl. That doesn't mean that Perl isn't often
DWIMy.

> This is *exactly* like C++, except that in Python the
> semantics of \y and \\y are identical. Python doesn't
> guess what you mean, it *imposes* a meaning on the escape
> sequence. You just don't like that meaning.

That's because I don't like things that are ill-conceived.

> > I.e., more or less like continuing on in the face of
> > what the Python Reference manual refers to as an
> > "unrecognized escape sequence".

> The wording could be better, I accept. It would be better
> to talk about "special escapes" (e.g. \n) and "any
> non-special escape" (e.g. \y).

Or maybe the wording is just fine, and it's the treatment of
unrecognized escape sequences that could be better.

|>ouglas




From no.email at please.post  Tue Aug 11 17:30:24 2009
From: no.email at please.post (kj)
Date: Tue, 11 Aug 2009 21:30:24 +0000 (UTC)
Subject: How to access a function's formal signature?
Message-ID: 



In the standard Python interactive interpreter, the string printed
by the help command when applied to a function includes the function's
formal signature.  E.g.:

>>> def foo(bar, *baz, **frobozz):
...   pass
... 
>>> help(foo)
Help on function foo in module __main__:

foo(bar, *baz, **frobozz)


Here by "signature" I'm referring to the substring "bar, *baz,
**frobozz" shown above (or, equivalently, any other object from
which this string could be deduced).  (I figured out that I can
retrieve this signature using methods in the inspect module.)

OK, now, is there a way to modify a function so that pydoc (and
presumably also the interactive interpreter's help function, etc.)
will print out a desired specific signature for this function?

For example, is there some way that I can modify foo above so that
help(foo) will print out

foo(x, y=None)

I tried mucking with foo.func_code's co_argcount, co_varnames, and
co_flags attributes, but as it turns out, they are read-only,
unfortunately.

The context here is the problem of writing a signature-changing
decorator in such a way that documentation facilities like help
and pydoc will print out the signature of the *original* undecorated
code (with some modifications), rather than the signature of the
decorated method.

TIA!

kynn


From darkwater42 at gmail.com  Tue Aug 11 17:39:30 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Tue, 11 Aug 2009 14:39:30 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	
	
	
	
	<86e09602-7eb1-4397-a77f-fb1e3c5b34b9@k26g2000vbp.googlegroups.com>
	
Message-ID: <6cca7095-cd11-4961-a44c-78da1b4ddf6b@g10g2000yqh.googlegroups.com>

On Aug 10, 11:27?pm, Steven D'Aprano
 wrote:
> On Mon, 10 Aug 2009 08:21:03 -0700, Douglas Alan wrote:
> > But you're right, it's too late to change this now.
>
> Not really. There is a procedure for making non-backwards compatible
> changes. If you care deeply enough about this, you could agitate for
> Python 3.2 to raise a PendingDepreciation warning for "unexpected" escape
> sequences like \z,

How does one do this?

Not that I necessarily think that it is important enough a nit to
break a lot of existing code.

Also, if I "agitate for change", then in the future people might
actually accurately accuse me of agitating for change, when typically
I just come here for a good argument, and I provide a connected series
of statements intended to establish a proposition, but in return I
receive merely the automatic gainsaying of any statement I make.

|>ouglas



From pavlovevidence at gmail.com  Tue Aug 11 17:42:02 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Tue, 11 Aug 2009 14:42:02 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<7xab2c52y6.fsf@ruckus.brouhaha.com> 
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com> 
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com> 
	
	 
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com> 
	
	<875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>
	
Message-ID: 

On Aug 11, 1:46?pm, Mark Lawrence  wrote:
> r wrote:
> > Ah Ha! the docs are broken and i was right all along! Are the good
> > folks at Python dev rolling a new installer as we speak, or we must
> > wait for new version?
>
> As I pointed out a few minutes ago thicko, the new version has been
> available for months.


Hello,

I'm mailing you to kindly request, again, that you please stop
validating "r"'s disruptiveness by responding to him on
comp.lang.python.  Thank you.

Carl Banks


From deets at nospam.web.de  Tue Aug 11 17:42:42 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Tue, 11 Aug 2009 23:42:42 +0200
Subject: ElementTree - Howto access text within XML tag element...
In-Reply-To: 
References: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
	<7ecm77F2fbf71U1@mid.uni-berlin.de>
	
Message-ID: <7ee6ukF2fo0t8U1@mid.uni-berlin.de>

cmalmqui schrieb:
> On Aug 11, 9:51 am, "Diez B. Roggisch"  wrote:
>> cmalmqui schrieb:
>>> Hi,
>>> I am writing on a small XML parser and are currently stuck as I am not
>>> able to get the whole element name in ElementTree.
>>> Please see the below example where "print root[0][0]" returns
>>> ""
>>> Is there a way to get hold of the "Running" string in the tag using
>>> elementTree?
>>> 
>>>     
>>>       2009-07-10T14:48:00Z
>>>       
>>>       .........
>>> For those of you that know how to program XML I have another
>>> question:
>>> I am currently "hardcoding" my XML parser using brackets, is this a
>>> good approach or should I build it using a "search on tag" approach.
>> What do you mean by that - hardcoding by brackets?
>>
>> Diez
> 
> Indeed, my current approach has been to hardcode the XML parser using
> brackets. Is there a more elegant way?
> 
> I am parsing a garmin xml file from a handheld GPS and as you can see
> in the below script, I am hardcoding each node:

As you don't give an actual example of how the XML looks like, it's hard 
to tell. But under the assumption that the tag-names are not generic, 
I'd certainly go for

   root.find("tagname")

instead. That's much clearer, and you don't rely on an actual order of 
elements.

Diez


From darkwater42 at gmail.com  Tue Aug 11 17:48:24 2009
From: darkwater42 at gmail.com (Douglas Alan)
Date: Tue, 11 Aug 2009 14:48:24 -0700 (PDT)
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
	 
	<0291a21a$0$20639$c3e8da3@news.astraweb.com>
	<8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com>
	
Message-ID: <1a0e1e6d-d902-4df7-8d35-850c4f62cc9c@e27g2000yqm.googlegroups.com>

On Aug 11, 4:38?pm, Ethan Furman  wrote:

> Mind you, I'm not really vested in how Python *should* handle
> backslashes one way or the other, but I am glad it has rules that it
> follows for consitent results, and I don't have to break out a byte-code
> editor to find out what's in my string literal.

I don't understand your comment. C++ generates a warning if you use an
undefined escape sequence, which indicates that your program should be
fixed. If the escape sequence isn't undefined, then C++ does the same
thing as Python.

It would be *even* better if C++ generated a fatal error in this
situation. (g++ probably has an option to make warnings fatal, but I
don't happen to know what that option is.) g++ might not generate an
error so that you can compile legacy C code with it.

In any case, my argument has consistently been that Python should have
treated undefined escape sequences consistently as fatal errors, not
as warnings.

|>ouglas



From rurpy at yahoo.com  Tue Aug 11 17:50:51 2009
From: rurpy at yahoo.com (rurpy at yahoo.com)
Date: Tue, 11 Aug 2009 14:50:51 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
Message-ID: <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>

On 08/11/2009 11:53 AM, Steven D'Aprano wrote:
> On Tue, 11 Aug 2009 07:57:28 -0700, rurpy wrote:
>
>> On 08/11/2009 01:47 AM, Antoine Pitrou wrote:
>>> r   gmail.com>   writes:
>>>> On Aug 9, 11:02 pm, David Lyon   wrote:
>>>>> Since you're talking about documentation, which is a part of python,
>>>>> don't you think you should be discussing it on python-dev ?
>>>> Yea, them's be a friendly bunch to noob ideas ;). Hey i got a better
>>>> idea, lets go to the IRS and see if we can persuade them to stop
>>>> taxing us...
>>> You know, the most interesting thing in this thread is certainly its
>>> title : ? Social problems of Python doc ?
>>>
>>> Yes, the little social problem here should be clear: if you have
>>> complaints to voice or improvements to suggest to the Python docs, you
>>> should do so on the issue tracker (*). For most topics, this is the
>>> only reasonable way to signal problems to the Python developers
>>> community, and so it is in most free software / open source projects.
>> "the *only* reasonable way"?  That's clearly wrong (unless you want to
>> wiggle in the room provided by "reasonable" or "most"). There is
>> discussion on the dev list, there is discussion here.
>
> Discussion here is spitting into the wind. The noise-to-signal ratio is
> high enough that the people who can fix an issue aren't likely to see it
> here. Unless somebody raises a report in the bug tracker, it will go
> nowhere, fast.

The point isn't always to gain a core developer's attention --
sometimes it is to figure out a good approach before proposing
something concrete.

> The same happens for issues on the dev list: I can't count how many times
> people there have said "put it in the bug tracker, or it will be
> forgotten".

On the contrary, there are many issues raised there that are
discussed there or result in the response, "take it to python-
ideas".  Not every issue to so well-baked that it is ready for
a tracker issue with patch.  There are some things that need
discussion before investing a lot of effort in them.

>> The issue tracker is fine for many things, but the process it provides
>> is equivalent to peep-hole optimization.  How does one submit a tracker
>> issue for something like the overall organization of the docs (for
>> example, the mis-placement of things like data- types in the library
>> manual rather than the language manual)?
>
> The same way you would submit a tracker issue for anything.
>
> "Documentation bug: Data types are misplaced in the library manual
> instead of the language manual.
>
> Suggested alternative: move page docs.python.org/xyz.html to abc.html"

But that's the problem.  Such a reorg is not a simple matter
of moving a file from here to there.  It will require a lot
moving about of sections and a lot of word-smithing to glue
them back together again in a coherent way.

A tracker issue, even one that was fairly specific about
how things should be reorganized but which did not provide
all the needed changes (a large patch) would almost certainly
be ignored or rejected.  But providing a large patch raises
two questions.  How likely is it to be be accepted?
(Something anyone would want to know before investing the time.)
And how to actually do the work needed to generate it (it could
be a very large amount of work for an individual and I don't
think it can be broken down into small independent issues.)
How is one to test the waters as to acceptability, or solicit
help, if one simply submits a tracker issue?

>> The big problem with the docs is poor writing (this includes not using
>> examples when they can help explain something more clearly than verbiage
>> alone).
>
> There's a difference between insufficiently good writing and poor
> writing: think of grading the docs, where 100 is "perfect in every way"
> and -100 is "perfectly awful in every possible way". (It's not a linear
> scale.) A score of 0 is "mediocre, just barely acceptable". Poor writing
> has a negative score. In my opinion, Python's docs are perhaps a 40 or
> 50, significantly better than most technical docs I've seen.

There is no objective way of rating docs.  My evaluation results
in part from the fact that I was able to learn Perl using only
the man pages.  I seriously attempted the same with the supposedly
easier-to-learn Python but was not able to and had to resort to
other web resources and buying Beazly's book.

Before you reply that tutorials are for learning, not reference
manuals, I will disagree.  A well written reference manual will
provide all the information needed to understand a language (albeit
arranged differently than the linear form of a tutorial), and I
have learned several languages in addition to Perl from their
reference materials.  Which is why I attribute my failure to do
so with Python to be the docs' fault.

> [...]
>>   I can rewrite some section so it sounds good to me, but likely it will
>> be just as bad (perhaps in different ways) that what is there.
>
> Bug reports are valuable even if you don't have the skills to provide a
> patch. Bug reports with patches are even more valuable, but that doesn't
> mean that the failure to provide a patch *necessarily* dooms your report
> to oblivion.
>
>
>> The post that started this thread proposed something like paying
>> professional writers to improve the docs.  This may or may not be a
>> practical suggestion.  But the immediate response it engendered was an
>> auto-immune-like group response: the docs are great already, don't
>> complain, fix them yourself, yada, yada; the same response that any
>> criticism of free software produces.
>
> I haven't seen any such knee-jerk responses. What I've seen is a set of
> sensible, *practical* advice:
>
> - complaining on its own, especially here, is pointless;

I don't think that is true.  (Or rather, the extent that it is true
is determined by the attitudes here.)

> - Python is a community effort, if you see something that needs fixing,
> do something about it;

Pointing out something that needs fixing *is* doing something
about it.  Maybe not as much as you'd like but from each according
to his ability...

> - many of us DON'T want arbitrary people "correcting" the official docs
> without oversight, and believe that would be a disaster (arbitrary people
> aren't give check-in privileges to add code to Python's standard library,
> nor should they be given check-in privileges to add docs);

Agreed.  I hope that was clear from my earlier post.

> - if people are keen on a Python wiki, then by all means publish one,
> just don't expect the Python dev team to build and manage it for you;

As luminous a Pythoneer as Fredrik Lundh set up a documentation
wiki to collect user contributions but it has faded away.  If
he couldn't pull it off then I'd say most other attempts without
the backing of python.org are almost certainly doomed to failure.
However, were the Python docs site to provide a wiki, along
with a mechanism to migrate suggestions developed on the wiki
into the docs, it might well be a viable (and easier because of
the wysiwyg effect) way of improving the docs.  As other have
pointed out, Postgresql, PHP, and Haskell have done so.
Now maybe there are good reasons not to do that.  But your hand-
waving is not one of them.

> - bug reports and patches to the docs are ALWAYS welcome, even if they
> are rejected;

Of course.  The cost for briefly looking at a report before
rejecting it is very low.  However the cost for producing it
can be much higher.  I'm not saying that that is what happens,
just that your statement considers only the pov of the issue
handlers, not the submitters.

> - if you don't have the skills to fix a bug (including doc bugs), an
> alternative is to pay somebody else to do so instead.

That there are alternatives was not my point.  My point was
that there are perhaps *other* alternatives too, but anyone
who tries to explore them here usually gets buried under a
mass of negativity.

>> It's really too bad the the python community can't seriously discuss
>> ways to improves the docs.  There are other possibilities for instance
>> the Fedora Docs project (can't say I'm impressed by what they've
>> produced but that doesn't mean their model is useless).  There is a need
>> for an approval process managed by someone who actually understands what
>> good technical writing is.  And perhaps editors who can polish or work
>> with programmers who provide the raw technical description of some
>> module.
>
> Yes, you're correct.
>
> [sarcasm] Now that we've agreed on what needs to be done, the problem is
> solved!!! [end sarcasm]

Anyone who's ever been to AA knows that the first step to
solving a problem is to acknowledge the problem exists.
As long as every "the docs sux" complaint is met here with
the standard responses that I've mentioned, rather than, "yes,
they do have some problems, what do you think we should do
about them?", the docs will continue to sux.  But as I said
maybe that's just the way it is.

>> Some kind of higher level more global process is the only way I can see
>> that the docs will be improved to any sort or professional standard.  I
>> don't see how issues like this will be addressed by submitting tracker
>> items.
>
> You want community input into the docs, but you're not willing to give
> that input except to bitch and moan and sook that the tracker is no good.

I have not done any "bitching and moaning".  I tried to
explain a group reaction that affects python negatively
(IMO) by rejecting any consideration of ways of improving
the docs other than submitting tracker issues.
That you pejoratively label it "bitching and moaning"
I count as evidence supporting my view.

> Even if the PSF had a full-time team of professional documentation
> writers and editors, guess what, you would STILL need to submit issues to
> the bug tracker, because otherwise THEY WON'T BE TRACKED.

Maybe, maybe not.  Depends on what development process the
(hypothetical) doc team chooses to use is.

>> Personally, I have given up on this issue.  The social factors involved
>> really pretty much determine that the Python docs will never reach a
>> very high quality -- that's just the way it is and I've come to accept
>> that.
>
> Ultimately it boils down to two factors:
>
> Money.
>
> Effort.
>
> If you won't put in the effort, and you won't put in the money, then it
> won't happen. Moaning that other people aren't putting in the money to
> hire team of professional writers isn't productive, and moaning that
> other people aren't putting in the effort to improve the docs isn't
> either.

Eh?  I have a computer filled with software that I put no
money or effort into, yet there it is.  So clearly you are
wrong in the general sense.  Before you call me a free-loading
ingratiate consider the software you use and how much of it you
have made substantive contributions to.  We all have limited
time and resources and we all have to choose where to invest that
time.  That some of us choose to invest it somewhere other than
Python does not deprive of of our right to point out problems
in Python when we note them.



From breamoreboy at yahoo.co.uk  Tue Aug 11 18:06:35 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Tue, 11 Aug 2009 23:06:35 +0100
Subject: Python docs disappointing - group effort to hire writers?
In-Reply-To: 
References: 	<7xab2c52y6.fsf@ruckus.brouhaha.com>
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com>
	<7xk51fgazf.fsf@ruckus.brouhaha.com>					<0006817d$0$2895$c3e8da3@news.astraweb.com>
		
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com>
		<875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>	
	
Message-ID: 

Carl Banks wrote:
> On Aug 11, 1:46 pm, Mark Lawrence  wrote:
>> r wrote:
>>> Ah Ha! the docs are broken and i was right all along! Are the good
>>> folks at Python dev rolling a new installer as we speak, or we must
>>> wait for new version?
>> As I pointed out a few minutes ago thicko, the new version has been
>> available for months.
> 
> 
> Hello,
> 
> I'm mailing you to kindly request, again, that you please stop
> validating "r"'s disruptiveness by responding to him on
> comp.lang.python.  Thank you.
> 
> Carl Banks
I hereby apologise.  My only feeble excuse is that my mammary glands are 
getting crushed.

-- 
Kindest regards.

Mark Lawrence.



From paul at boddie.org.uk  Tue Aug 11 18:08:59 2009
From: paul at boddie.org.uk (Paul Boddie)
Date: Tue, 11 Aug 2009 15:08:59 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
Message-ID: <9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegroups.com>

On 11 Aug, 23:50, ru... at yahoo.com wrote:
>
> However, were the Python docs site to provide a wiki, along
> with a mechanism to migrate suggestions developed on the wiki
> into the docs, it might well be a viable (and easier because of
> the wysiwyg effect) way of improving the docs. ?As other have
> pointed out, Postgresql, PHP, and Haskell have done so.
> Now maybe there are good reasons not to do that. ?But your hand-
> waving is not one of them.

I think you make some good points, although I don't have time to
respond to all of them. Certainly, the documentation situation with
Python is not ideal; otherwise, people would not be complaining about
it so frequently.

I recommend going to the existing Wiki and looking at what there is
already:

http://wiki.python.org/moin/Documentation
http://wiki.python.org/moin/CategoryDocumentation

Sadly, I don't think you'll find much to work with, apart from the
occasional attempt to make an annotated version of the existing
documentation:

http://wiki.python.org/moin/PythonLibraryReference

So my next recommendation is to either use the existing Wiki
infrastructure or to ask for a separate Wiki for the purpose of
reworking the documentation. You could either take the existing
documentation, which I believe is now restructured text, and just drop
that into the Wiki with the appropriate format directives (for later
reworking in Wiki format, perhaps), or you could start afresh and
tackle some of the more serious issues head on.

I can see benefits to just starting from scratch. Perhaps the
licensing should be more explicit than the existing material on the
Wiki so that the documentation produced could be freely distributed
without uncertainty, but the outcome would hopefully be something that
stands on its own as an alternative or a replacement to the
conventional documentation.

Paul


From joelriv at gmail.com  Tue Aug 11 18:09:37 2009
From: joelriv at gmail.com (Joel Juvenal Rivera Rivera)
Date: Tue, 11 Aug 2009 17:09:37 -0500
Subject: create shell history with python
Message-ID: <1250028577.1453.46.camel@localhost>

I been thinking how to make a 'bash like history shell' in python,
i don't know if with stdin and stdout i can accomplish this or do i
need something like curses and stuff like that, anyway im start to
figure this out.
Does any body has try this? or have any interesting idea?

--Joel Rivera




From clp2 at rebertia.com  Tue Aug 11 18:15:02 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Tue, 11 Aug 2009 18:15:02 -0400
Subject: create shell history with python
In-Reply-To: <1250028577.1453.46.camel@localhost>
References: <1250028577.1453.46.camel@localhost>
Message-ID: <50697b2c0908111515t386f7ee7w6fcebd1326c77263@mail.gmail.com>

On Tue, Aug 11, 2009 at 6:09 PM, Joel Juvenal Rivera
Rivera wrote:
> I been thinking how to make a 'bash like history shell' in python,
> i don't know if with stdin and stdout i can accomplish this or do i
> need something like curses and stuff like that, anyway im start to
> figure this out.
> Does any body has try this? or have any interesting idea?

http://docs.python.org/library/readline.html

Cheers,
Chris
-- 
http://blog.rebertia.com


From deets at nospam.web.de  Tue Aug 11 18:15:38 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Wed, 12 Aug 2009 00:15:38 +0200
Subject: create shell history with python
In-Reply-To: 
References: 
Message-ID: <7ee8saF2e47vaU1@mid.uni-berlin.de>

Joel Juvenal Rivera Rivera schrieb:
> I been thinking how to make a 'bash like history shell' in python,
> i don't know if with stdin and stdout i can accomplish this or do i
> need something like curses and stuff like that, anyway im start to
> figure this out.
> Does any body has try this? or have any interesting idea?

Don't waste your time, use IPython :)

http://ipython.scipy.org/moin/

Diez


From joelriv at gmail.com  Tue Aug 11 18:18:55 2009
From: joelriv at gmail.com (Joel Juvenal Rivera Rivera)
Date: Tue, 11 Aug 2009 17:18:55 -0500
Subject: create shell history with python
In-Reply-To: <50697b2c0908111515t386f7ee7w6fcebd1326c77263@mail.gmail.com>
References: <1250028577.1453.46.camel@localhost>
	<50697b2c0908111515t386f7ee7w6fcebd1326c77263@mail.gmail.com>
Message-ID: <1250029135.1453.48.camel@localhost>

Wow i didn't  know that module this solves everything... i guess python
has a lot more  batteries than i thought .
Thank you Chris

El mar, 11-08-2009 a las 18:15 -0400, Chris Rebert escribi?:
> On Tue, Aug 11, 2009 at 6:09 PM, Joel Juvenal Rivera
> Rivera wrote:
> > I been thinking how to make a 'bash like history shell' in python,
> > i don't know if with stdin and stdout i can accomplish this or do i
> > need something like curses and stuff like that, anyway im start to
> > figure this out.
> > Does any body has try this? or have any interesting idea?
> 
> http://docs.python.org/library/readline.html
> 
> Cheers,
> Chris



From deets at nospam.web.de  Tue Aug 11 18:23:39 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Wed, 12 Aug 2009 00:23:39 +0200
Subject: for key, value in dict.() - how to get? (which func)
In-Reply-To: 
References: 
	
	
Message-ID: <7ee9beF2gr846U1@mid.uni-berlin.de>

dmitrey schrieb:
> Yes, thank you, items() is the correct approach, on the other hand I
> have already get rid of the cycle.

Most certainly items() is *not* the correct approach if you are 
concerned so much with performance, because items() first creates a list 
of key/value-pairs, where iteritems() will be an effective iterator.

so if you are (IMHO wrongly) concerned about performance of an O(1) 
lookup, items() certainly costs more.

And the following program proves it:

import time

d = dict(zip(xrange(100000), xrange(100000)))

start = time.time()
for loops in xrange(100):
     for key in d:
         value = d[key]

print "lookup: ", time.time() - start

start = time.time()

for loops in xrange(100):
     for key, value in d.items():
         value = d[key]


print "items: ", time.time() - start

start = time.time()

for loops in xrange(100):
     for key, value in d.iteritems():
         value = d[key]


print "items: ", time.time() - start


The result on my machine is:

deets$ python /tmp/test.py

lookup:  2.78633999825
items:  7.42830610275
items:  3.69960308075

So actually your condemed approach seems to be the fastest, where the 
items() call by far is the slowest approch.

"In the face of ambiguity, refuse the temptation to guess."


Diez


From aahz at pythoncraft.com  Tue Aug 11 18:25:27 2009
From: aahz at pythoncraft.com (Aahz)
Date: 11 Aug 2009 15:25:27 -0700
Subject: httplib incredibly slow :-(
References: 
Message-ID: 

In article ,
Chris Withers   wrote:
>
>Does anyone know of an alternative library for creating http requests 
>and getting their responses that's faster but hopefully has a similar 
>interface?

PyCurl
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...string iteration isn't about treating strings as sequences of strings, 
it's about treating strings as sequences of characters.  The fact that
characters are also strings is the reason we have problems, but characters 
are strings for other good reasons."  --Aahz


From rt8396 at gmail.com  Tue Aug 11 19:12:42 2009
From: rt8396 at gmail.com (r)
Date: Tue, 11 Aug 2009 16:12:42 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<7xk51fgazf.fsf@ruckus.brouhaha.com> 
	 
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com> 
	
	 
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com> 
	
	<875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>
	
	
	
Message-ID: 

...(Carl Banks doing what he does best)
> > I'm mailing you to kindly request, again, that you please stop
> > validating "r"'s disruptiveness by responding to him on
> > comp.lang.python. ?Thank you.

Carl,
You have no right to tell people when where and how they should speak
to anyone. And how dare you think you can! If you spent even a
fraction of the time you spend manipulating the direction of this list
and instead, actually contributing to the problem at hand, (discussion
or otherwise) we would be much closer to solving this problem today.

You (and your conspirators) are the reason most people find the c.l.py
list so disturbing and wish not to participate. Get a life you moron
and stop trying to control the world.

PS: GET STUFFED!


From rays at blue-cove.com  Tue Aug 11 19:13:37 2009
From: rays at blue-cove.com (RJ)
Date: Tue, 11 Aug 2009 16:13:37 -0700
Subject: Social problems of Python doc [was Re: Python docs disappointing]
In-Reply-To: <9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegro
	ups.com>
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	<9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegroups.com>
Message-ID: <6.2.3.4.2.20090811160723.04a40580@blue-cove.com>

At 03:08 PM 8/11/2009, you wrote:
>I recommend going to the existing Wiki and looking at what there is
>already:
>
>http://wiki.python.org/moin/Documentation
>http://wiki.python.org/moin/CategoryDocumentation

I also can't see how to get 
from  http://wiki.python.org/moin/Documentation to 
http://wiki.python.org/moin/CategoryDocumentation, for one...

>Sadly, I don't think you'll find much to work with, apart from the
>occasional attempt to make an annotated version of the existing
>documentation:
>
>http://wiki.python.org/moin/PythonLibraryReference

The library reference above needs a link to Modules (and the link to 
Andrew's pages are now dead - 
http://pydoc.amk.ca/frame.html)

What I've always looked for and Google constantly for, is a main 
language version of the features of http://www.scipy.org/Cookbook and 
http://code.activestate.com/recipes/langs/python/, with module level 
organization. At least users can submit something at Activestate. The 
issue there (and at Scipy) is that I usually want an example 
illustrating some method, and that's not how it's organized (but is 
at those Other language sites), so I still need to search at Scipy, or do
http://www.google.com/search?q=site%3Ascipy.org+foo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From cjns1989 at gmail.com  Tue Aug 11 19:16:55 2009
From: cjns1989 at gmail.com (Chris Jones)
Date: Tue, 11 Aug 2009 19:16:55 -0400
Subject: [OT] From: header - WAS: Python docs disappointing - group effort	to
	hire writers?
In-Reply-To: <7xab266v1j.fsf@ruckus.brouhaha.com>
References: <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com>
	
	
	<96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com>
	
	
	<081115fd-8014-4e6b-8d7b-76d6fcf6a59d@e27g2000yqm.googlegroups.com>
	<7xr5vj9m0g.fsf@ruckus.brouhaha.com>
	<2fd432c7-00e2-4bb6-9192-e9f7aa96c4d7@m3g2000pri.googlegroups.com>
	<7xab266v1j.fsf@ruckus.brouhaha.com>
Message-ID: <20090811231655.GA3491@turki.gavron.org>

Hello Paul,

This is strictly OT, but when you get a chance, could you contact me off
list at the above address?

I need your help with the From: email address specified in your posts to
the list. 

Thanks,

CJ


From Nikolaus at rath.org  Tue Aug 11 19:21:16 2009
From: Nikolaus at rath.org (Nikolaus Rath)
Date: Tue, 11 Aug 2009 19:21:16 -0400
Subject: Monkeypatching an object to become callable
References: <87hbwgu7xa.fsf@vostro.rath.org>
	<0aa46ece-64b9-4c28-b690-5ac5937ce3f2@f20g2000prn.googlegroups.com>
	<4a7fd55e$0$32765$426a74cc@news.free.fr>
Message-ID: <87iqguey37.fsf@vostro.rath.org>

Bruno Desthuilliers  writes:
> 7stud a ?crit :
> (snip)
>> class Wrapper(object):
>>     def __init__(self, obj, func):
>>         self.obj = obj
>>         self.func = func
>>
>>     def __call__(self, *args):
>>         return self.func(*args)
>>
>>     def __getattr__(self, name):
>>         return object.__getattribute__(self.obj, name)
>
> This should be
>
>           return getattr(self.obj, name)
>
> directly calling object.__getattribute__ might skip redefinition of
> __getattribute__ in self.obj.__class__ or it's mro.

Works nicely, thanks. I came up with the following shorter version which
modifies the object in-place:

class Modifier(obj.__class__):
     def __call__(self):
         return fn()

obj.__class__ = Modifier


To me this seems a bit more elegant (less code, less underscores). Or
are there some cases where the above would fail?


Best,

   -Nikolaus

-- 
 ?Time flies like an arrow, fruit flies like a Banana.?

  PGP fingerprint: 5B93 61F8 4EA2 E279 ABF6  02CF A9AD B7F8 AE4E 425C


From chris at simplistix.co.uk  Tue Aug 11 19:25:41 2009
From: chris at simplistix.co.uk (Chris Withers)
Date: Wed, 12 Aug 2009 00:25:41 +0100
Subject: httplib incredibly slow :-(
In-Reply-To: 
References: 
	
Message-ID: <4A81FDF5.6010508@simplistix.co.uk>

Aahz wrote:
> In article ,
> Chris Withers   wrote:
>> Does anyone know of an alternative library for creating http requests 
>> and getting their responses that's faster but hopefully has a similar 
>> interface?
> 
> PyCurl

This seems to be a wrapper around libcurl.

Does it work on Windows?
If so, where can I find some decent examples?
(the ones listed on the pycurl website are not what I'd call decent :-S)

Chris


-- 
Simplistix - Content Management, Batch Processing & Python Consulting
            - http://www.simplistix.co.uk


From pavlovevidence at gmail.com  Tue Aug 11 19:37:51 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Tue, 11 Aug 2009 16:37:51 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	<9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegroups.com>
Message-ID: 

On Aug 11, 3:08?pm, Paul Boddie  wrote:
> Certainly, the documentation situation with
> Python is not ideal; otherwise, people would not be complaining about
> it so frequently.

I will not take an opinion on whether Python's documentation is ideal
(more on why below) but I will opine that the conclusion doesn't
follow from your premise.  People's expectations of what documentation
should be are too different, there will always be people who aren't
pleased.  IOW, there is no "ideal".

For example, kj (who started this mess of thread) complained that
pydoc didn't give exhaustive usage documentation.  In contrast, I
think pydoc gives too much information.  I would rather have only the
bare minimum; I don't want to pan through ten paragraphs just to see
what the fifth argument is.

So who's right?

No one, there is no "right".  Unfortunately some people can't or won't
respect that opinions differ; they have to take perceived defects in
the docs personally.


Carl Banks


From pavlovevidence at gmail.com  Tue Aug 11 19:47:38 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Tue, 11 Aug 2009 16:47:38 -0700 (PDT)
Subject: How to access a function's formal signature?
References: 
Message-ID: <9c025b8e-9602-48cf-be77-f67e9ed3953c@26g2000yqk.googlegroups.com>

On Aug 11, 2:30?pm, kj  wrote:
> In the standard Python interactive interpreter, the string printed
> by the help command when applied to a function includes the function's
> formal signature. ?E.g.:
>
> >>> def foo(bar, *baz, **frobozz):
>
> ... ? pass
> ...>>> help(foo)
>
> Help on function foo in module __main__:
>
> foo(bar, *baz, **frobozz)
>
> Here by "signature" I'm referring to the substring "bar, *baz,
> **frobozz" shown above (or, equivalently, any other object from
> which this string could be deduced). ?(I figured out that I can
> retrieve this signature using methods in the inspect module.)
>
> OK, now, is there a way to modify a function so that pydoc (and
> presumably also the interactive interpreter's help function, etc.)
> will print out a desired specific signature for this function?

I think you'd have to modify pydoc.  pydoc pulls this information out
from the function's attributes (and maybe also it's underlying code
object) which are read-only.


Carl Banks


From danb_83 at yahoo.com  Tue Aug 11 20:08:01 2009
From: danb_83 at yahoo.com (AggieDan04)
Date: Tue, 11 Aug 2009 17:08:01 -0700 (PDT)
Subject: Bug in format specification in Python 3?
References: 
Message-ID: <8ae626c7-1f21-4ab6-b299-2e5633755fbf@g31g2000yqc.googlegroups.com>

On Aug 11, 3:28?pm, Robert Dailey  wrote:
> Hello,
>
> According to the Python 3.1 documentation, I can have a format
> specification like so:
>
> print( 'This is a hex number: {:#08x}'.format( 4 ) )
>
> This will print:
>
> This is a hex number: 0x000004
>
> I notice that the '0x' portion is counted in the width, which was
> specified as 8. This seems wrong to me. Is this by design? If so, why?
> I expect that the width portion to only apply to the input + padding
> only. I don't consider the '0x' portion part of the padding. But maybe
> it is...

It's unintuitive to me, too, but it's the same thing that Python 2.x
did:

>>> print '%#08x' % 4
0x000004



From skippy.hammond at gmail.com  Tue Aug 11 20:10:18 2009
From: skippy.hammond at gmail.com (Mark Hammond)
Date: Tue, 11 Aug 2009 17:10:18 -0700
Subject: Windows 7 : any problems installing or running Python ?
In-Reply-To: 
References: 
	
Message-ID: <4A82086A.4060606@gmail.com>

On 9/08/2009 10:42 PM, Tim Roberts wrote:
> Dave WB3DWE wrote:
>>
>> Anybody tried it ?
>> Is anything broken, ie is the whole shootin' match good to go ?
>> I'm esp interested in WConio for 3.0/3.1 which I use heavily.
>
> I've been running the 32-bit builds of Python 2.5, PyWin32, and wxPython on
> Windows 7 64-bit for many months.  No problems at all.
>
> I hated Vista; I would only run it if my clients insisted on having their
> drivers tested on it.  Vista SP1 was somewhat better, but I don't mind
> Windows 7 at all.  I might even upgrade my primary development machine from
> XP.  A number of the usually cranky driver developers have expressed the
> same opinion.  Microsoft might actually have a winner here.

"Me too" :)

Mark


From exarkun at twistedmatrix.com  Tue Aug 11 20:19:28 2009
From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com)
Date: Wed, 12 Aug 2009 00:19:28 -0000
Subject: Social problems of Python doc [was Re: Python docs disappointing]
In-Reply-To: 
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	<9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegroups.com>
	
Message-ID: <20090812001928.10431.2043769776.divmod.xquotient.0@localhost.localdomain>

On 11 Aug, 11:37 pm, pavlovevidence at gmail.com wrote:
>
>I will not take an opinion on whether Python's documentation is ideal
>(more on why below) but I will opine that the conclusion doesn't
>follow from your premise.  People's expectations of what documentation
>should be are too different, there will always be people who aren't
>pleased.  IOW, there is no "ideal".
>
>For example, kj (who started this mess of thread) complained that
>pydoc didn't give exhaustive usage documentation.  In contrast, I
>think pydoc gives too much information.  I would rather have only the
>bare minimum; I don't want to pan through ten paragraphs just to see
>what the fifth argument is.
>
>So who's right?
>
>No one, there is no "right".  Unfortunately some people can't or won't
>respect that opinions differ; they have to take perceived defects in
>the docs personally.

This is right on.  Excellent point, Carl.

Jean-Paul


From rurpy at yahoo.com  Tue Aug 11 20:46:39 2009
From: rurpy at yahoo.com (rurpy at yahoo.com)
Date: Tue, 11 Aug 2009 17:46:39 -0700 (PDT)
Subject: Python docs disappointing - group effort to hire writers?
References: 
	<7xab2c52y6.fsf@ruckus.brouhaha.com> 
	<3ef3f447-af32-4c1d-858c-9b7031f08b46@l5g2000pra.googlegroups.com> 
	<7xk51fgazf.fsf@ruckus.brouhaha.com>
	
	
	
	
	<0006817d$0$2895$c3e8da3@news.astraweb.com> 
	
	 
	<6790fee9-3374-4fd4-86d5-e7bfa0439ea5@b14g2000yqd.googlegroups.com> 
	
	<875f7a34-b270-4a8c-835b-790e19c12afa@g31g2000yqc.googlegroups.com>
	
Message-ID: 

On Aug 11, 2:46 pm, Mark Lawrence  wrote:
> r wrote:
> > Ah Ha! the docs are broken and i was right all along! Are the good
> > folks at Python dev rolling a new installer as we speak, or we must
> > wait for new version?
>
> As I pointed out a few minutes ago thicko, the new version has been
> available for months.

Now hold on here...

I too was bitten by this.  I thought the chm docs were so unusable
that I went to the issue tracker, extremely annoyed, to submit a
rather caustic bug report.  Only after looking through the doc bugs
did I find that it was already recognised, that a corrected chm
file was available, and that there were no plans to do any more
than that.  (This is from memory since the python tracker is down).

On the main download page is a link to the 2.6.2 msi file with not
a word about the help file.  Only if you follow the "python-2.6.2"
link to a second page, is there a link to the corrected help file,
and even that says only, "Updated Windows help file" with no
indication that it is supposed to replace a broken one in the
distribution.

If "r" is a "thicko", I'd say the handling of this issue was done
by some who are considerably thicker.

It may also be yet another example of how documentation (using
the word loosely) is produced without sufficient attention to its
usefulness to its intended audience.


From jstroud at mbi.ucla.edu  Tue Aug 11 20:54:36 2009
From: jstroud at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 17:54:36 -0700
Subject: hashability
Message-ID: 

Hello All,

I wrote the function to test hashability of arbitrary objects. My reason 
is that the built-in python (2.5) hashing is too permissive for some 
uses. A symptom of this permissiveness comes from the ability to 
successfully hash() arbitrary objects:

   py> class C(object): pass
   ...
   py> {C():4}[C()]
   ------------------------------------------------------------
   Traceback (most recent call last):
     File "", line 1, in 
   : <__main__.C object at 0xe21610>

The basis for the exception is that the two instances do not have the 
same hash() although conceptually they might seem equal to the 
unitiated. Were I to re-design python, I'd throw an exception in this 
case because of the ill-defined behavior one might expect if a C() 
serves as a key for a dict.

To prevent users of one of my libraries from falling into this and 
similar traps (which have potentially problematic consequences), I came 
up with this test for hashability:

def hashable(k):
   try:
     hash(k)
   except TypeError:
     good = False
   else:
     good = (hasattr(k, '__hash__') and
             (hasattr(k, '__eq__') or hasattr(k, '__cmp__')))
   return good

It works as I would like for most of the cases I can invent:

   py> all(map(hashable, [1,1.0,"",(1,2,3)]))
   True
   py> any(map(hashable, [None, [1,2], {}, C(), __import__('sys')]))
   False

Can anyone think of boundary cases I might be missing with this approach?


James


From db3l.net at gmail.com  Tue Aug 11 21:18:43 2009
From: db3l.net at gmail.com (David Bolen)
Date: Tue, 11 Aug 2009 21:18:43 -0400
Subject: Networked Broadcast Messaging
References: <37ea826b-708d-48f4-a64a-42f58fec5325@c2g2000yqi.googlegroups.com>
Message-ID: 

"squishywaffle at gmail.com"  writes:

> * Machines can come and go. Since messages are not directly sent to a
> specific IP address from our Python script, the messages are simply
> broadcasted to those who are there to listen. If nobody is subscribed
> to the message type being sent, nothing happens.

What sort of delivery guarantees are you looking for if there is in
fact a machine that is trying to listen to a particular message or
message group?  Is it ok if someone is listening for a certain type of
message, is it ok if it misses one that is sent?

If you do simple direct broadcasting (e.g., UDP), you'd need your own
reliability layer above that if you cared if the message actually got
to an intended destination if that destination was present.

If you want better guarantees, you might look into a distributed
message bus like Spread (http://www.spread.org/) or perhaps a
messaging protocol like XMPP (http://xmpp.org/) through its PubSub
extension.  Both have Python interfaces, though I have no personal
experience with either.  But perhaps that will also give you some
terms or starting points for searching for other options.

-- David


From contact at xavierho.com  Tue Aug 11 21:38:08 2009
From: contact at xavierho.com (Xavier Ho)
Date: Wed, 12 Aug 2009 11:38:08 +1000
Subject: Any built-in function for smallest positive floating point 
	number?
In-Reply-To: 
References: 
Message-ID: <2d56febf0908111838n602c52fbu2d7754733b6246@mail.gmail.com>

On Wed, Aug 12, 2009 at 3:29 AM, Maria Liukis  wrote:

> Hello everybody,
> Is somebody aware of built-in Python's function that would return
> a value for smallest positive double precision floating point number
> (analogous to 'realmin' in Matlab). Python has built-in sys.maxint but I
> could not find anything for float.
>

I'm not sure if this helps, but here you go:
http://drj11.wordpress.com/2007/07/05/the-smallest-number/

I couldn't get it to work on Python 2.6.2 or 3.1 myself, however it seems
pretty small.

- Xav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From pavlovevidence at gmail.com  Tue Aug 11 21:40:15 2009
From: pavlovevidence at gmail.com (Carl Banks)
Date: Tue, 11 Aug 2009 18:40:15 -0700 (PDT)
Subject: hashability
References: 
Message-ID: <3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>

On Aug 11, 5:54?pm, James Stroud  wrote:
> Hello All,
>
> I wrote the function to test hashability of arbitrary objects. My reason
> is that the built-in python (2.5) hashing is too permissive for some
> uses. A symptom of this permissiveness comes from the ability to
> successfully hash() arbitrary objects:
>
> ? ?py> class C(object): pass
> ? ?...
> ? ?py> {C():4}[C()]
> ? ?------------------------------------------------------------
> ? ?Traceback (most recent call last):
> ? ? ?File "", line 1, in 
> ? ?: <__main__.C object at 0xe21610>
>
> The basis for the exception is that the two instances do not have the
> same hash() although conceptually they might seem equal to the
> unitiated. Were I to re-design python, I'd throw an exception in this
> case because of the ill-defined behavior one might expect if a C()
> serves as a key for a dict.

That's arguably the right thing to do.

Personally I've found that being able to use class instances as
hashable objects to be terribly useful (these objects are hashed and
compared by identity, of course), so I don't mind it.  But I can
definitely see how this straddles the line between "practicality" and
"face of ambiguity".  And if Python didn't do it by default, it would
be little trouble to add the appropriate __eq__ and __hash__ methods.


> To prevent users of one of my libraries from falling into this and
> similar traps (which have potentially problematic consequences),

Even so, I would consider whether some of your users might, like me,
also find this terribly useful, and if so (probably a few will unless
they are all novices), allow them to disable or disregard this check.

> I came
> up with this test for hashability:
>
> def hashable(k):
> ? ?try:
> ? ? ?hash(k)
> ? ?except TypeError:
> ? ? ?good = False
> ? ?else:
> ? ? ?good = (hasattr(k, '__hash__') and
> ? ? ? ? ? ? ?(hasattr(k, '__eq__') or hasattr(k, '__cmp__')))
> ? ?return good

I wouldn't call the function "hashable".  Class instances like C() are
hashable whether you approve or not.  Something like
"deliberately_hashable" would be a better name.


> It works as I would like for most of the cases I can invent:
>
> ? ?py> all(map(hashable, [1,1.0,"",(1,2,3)]))
> ? ?True
> ? ?py> any(map(hashable, [None, [1,2], {}, C(), __import__('sys')]))
> ? ?False
>
> Can anyone think of boundary cases I might be missing with this approach?

It is possible to redefine == operator by defining __ne__ instead of
__eq__, at least on Python 2.5, so you should keep that in mind.


Carl Banks


From contact at xavierho.com  Tue Aug 11 21:42:36 2009
From: contact at xavierho.com (Xavier Ho)
Date: Wed, 12 Aug 2009 11:42:36 +1000
Subject: Any built-in function for smallest positive floating point 
	number?
In-Reply-To: <2d56febf0908111838n602c52fbu2d7754733b6246@mail.gmail.com>
References: 
	<2d56febf0908111838n602c52fbu2d7754733b6246@mail.gmail.com>
Message-ID: <2d56febf0908111842g11ff8f49w7c96a8bbbb929d83@mail.gmail.com>

I got it to work with Python 2.6.2.

>>> import struct
>>> struct.unpack('d', struct.pack('Q', 1))[0]
4.9406564584124654e-324

Python 3.1 will print 5e-324, which is fair enough.

Cheers,
Xavier
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From contact at xavierho.com  Tue Aug 11 21:49:00 2009
From: contact at xavierho.com (Xavier Ho)
Date: Wed, 12 Aug 2009 11:49:00 +1000
Subject: Any built-in function for smallest positive floating point 
	number?
In-Reply-To: <2d56febf0908111842g11ff8f49w7c96a8bbbb929d83@mail.gmail.com>
References: 
	<2d56febf0908111838n602c52fbu2d7754733b6246@mail.gmail.com>
	<2d56febf0908111842g11ff8f49w7c96a8bbbb929d83@mail.gmail.com>
Message-ID: <2d56febf0908111849y393a65fk609e787eee9bd6f3@mail.gmail.com>

Actually, that was double precision. You asked for float precision.

>>> struct.unpack('f', struct.pack('L', 1))[0]
1.4012984643248171e-45

which is the same as:
>>> 2**-149
1.4012984643248171e-45

I think that's it. Sorry for posting to the list three times in a row.
corrections welcome.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rurpy at yahoo.com  Tue Aug 11 21:50:39 2009
From: rurpy at yahoo.com (rurpy at yahoo.com)
Date: Tue, 11 Aug 2009 18:50:39 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	<9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegroups.com>
Message-ID: <56a1d77e-0379-49e4-99c1-2d0de1378bc2@v36g2000yqv.googlegroups.com>

On Aug 11, 4:08?pm, Paul Boddie  wrote:
> On 11 Aug, 23:50, ru... at yahoo.com wrote:
> > However, were the Python docs site to provide a wiki, along
> > with a mechanism to migrate suggestions developed on the wiki
> > into the docs, it might well be a viable (and easier because of
> > the wysiwyg effect) way of improving the docs. ?As other have
> > pointed out, Postgresql, PHP, and Haskell have done so.
> > Now maybe there are good reasons not to do that. ?But your hand-
> > waving is not one of them.
>[...]
> I can see benefits to just starting from scratch. Perhaps the
> licensing should be more explicit than the existing material on the
> Wiki so that the documentation produced could be freely distributed
> without uncertainty, but the outcome would hopefully be something that
> stands on its own as an alternative or a replacement to the
> conventional documentation.

A couple years ago I actually did give a half-assed try to rewriting
the doc.  I got the doc source downloaded and buildable with the
intent
of rewriting in bits and pieces as I had occasion to use (and find
problems with) various parts.  Not knowing latex, I stupidly got side-
tracked trying to convert it to docbook which I was more interested
in.
After I gave up on that and went back to latex, I found merging
changes
from Python into my source (a little of which was heavily modified by
this time) to be very time consuming.  And eventually the Python side
was changed to REST putting an end to my effort which by that time
were already pretty minimal.  I concluded that the rewrite I was
trying
to do was comparable to writing a Python book, and too ambitious for
one person working on it <5 hrs/week.

And of course I am not any better writer (probably worse) than the
average Python programmer.  Which is the problem with using a wiki --
unless good writers contribute, I see no reason to expect much
better results than already exist.  But maybe I am too pessimistic...



From http  Tue Aug 11 21:51:03 2009
From: http (Paul Rubin)
Date: 11 Aug 2009 18:51:03 -0700
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	<9811a980-af7f-4f4b-a0f9-d3f8e565b8ac@g10g2000yqh.googlegroups.com>
	
Message-ID: <7xocqler5k.fsf@ruckus.brouhaha.com>

Carl Banks  writes:
> On> For example, kj (who started this mess of thread) complained that
> pydoc didn't give exhaustive usage documentation.  In contrast, I
> think pydoc gives too much information.  I would rather have only the
> bare minimum; I don't want to pan through ten paragraphs just to see
> what the fifth argument is.

The problem is that it doesn't sufficiently separate the carefully
written useful stuff from the automatically generated useless stuff.


From afriere at yahoo.co.uk  Tue Aug 11 22:06:54 2009
From: afriere at yahoo.co.uk (Asun Friere)
Date: Tue, 11 Aug 2009 19:06:54 -0700 (PDT)
Subject: hashability
References: 
Message-ID: <77eda964-a6ee-496b-9c5f-5391663099e0@b14g2000yqd.googlegroups.com>

On Aug 12, 10:54?am, James Stroud  wrote:

> I wrote the function to test hashability of arbitrary objects. My reason
> is that the built-in python (2.5) hashing is too permissive for some
> uses. A symptom of this permissiveness comes from the ability to
> successfully hash() arbitrary objects:

Arbitrary, or anonymous objects and some uses or some users?  I'm
can't see why anyone would expect different instance of a class to be
equivalent keys.

> The basis for the exception is that the two instances do not have the
> same hash() although conceptually they might seem equal to the
> unitiated.

Perhaps the best solution would be for the unitiated to correct their
misaprehensions?  If you don't understand that you are instantiating a
number of anonymous instances of a class you are missing something
very fundamental.

> Were I to re-design python, I'd throw an exception in this
> case because of the ill-defined behavior one might expect if a C()
> serves as a key for a dict.

Then you couldn't to this:

d = {C():1, C():2, C():3}
a,b,c = d.keys()
d[c]

Anonymous instances are a GoodThing(tm) and they can usually be de-
anonymised if need be.


From andrew at acooke.org  Tue Aug 11 22:13:39 2009
From: andrew at acooke.org (andrew cooke)
Date: Tue, 11 Aug 2009 19:13:39 -0700 (PDT)
Subject: Frustrated with scopes
Message-ID: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>


Is there a way to make this work (currently scope and join are
undefined at runtime when the inner class attributes are defined):

class _StreamFactory(object):

    @staticmethod
    def __call__(lines, source, join=''.join):

        class Line(object):

            __source = source
            __join = join
[...]

I can get something working by bouncing through global values, but it
looks awful and I think it's a source of a bug due too values being
redefined.

Thanks,
Andrew


From andrew at acooke.org  Tue Aug 11 22:14:27 2009
From: andrew at acooke.org (andrew cooke)
Date: Tue, 11 Aug 2009 19:14:27 -0700 (PDT)
Subject: Frustrated with scopes
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
Message-ID: 

correction: "source" and "join" are undefined.  Sorry, Andrew



From jstroud at mbi.ucla.edu  Tue Aug 11 22:15:07 2009
From: jstroud at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 19:15:07 -0700
Subject: hashability
In-Reply-To: <3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
Message-ID: 

Carl Banks wrote:
> On Aug 11, 5:54 pm, James Stroud  wrote:
> 
>> To prevent users of one of my libraries from falling into this and
>> similar traps (which have potentially problematic consequences),
> 
> Even so, I would consider whether some of your users might, like me,
> also find this terribly useful, and if so (probably a few will unless
> they are all novices), allow them to disable or disregard this check.

I realize I left out my use. The intent of the function is to flag 
objects that will make useful keys for a persistent dictionary. The 
{C():4}[C()] example demonstrates why I want to avoid certain types of 
keys--I don't want users to do things like {C():4, C():4}, which python 
happily allows but falls apart at the level of persistence.

However, I also want to avoid isinstance() and/or type checking in order 
to allow maximal flexibility so that users don't have to work too hard 
to make their keys.

> I wouldn't call the function "hashable".  Class instances like C() are
> hashable whether you approve or not.  Something like
> "deliberately_hashable" would be a better name.

I chose "keyable".

>> Can anyone think of boundary cases I might be missing with this approach?
> 
> It is possible to redefine == operator by defining __ne__ instead of
> __eq__, at least on Python 2.5, so you should keep that in mind.

Thanks for this hint. I've already put it in.

James


From jus__ at hotmail.com  Tue Aug 11 22:22:27 2009
From: jus__ at hotmail.com (Jus)
Date: Tue, 11 Aug 2009 22:22:27 -0400
Subject: Unsigned char array to an unsigned longlong array
Message-ID: 

Hello,

 

I'm using Python 2.6.2.

Is there a way to have an Array of unsigned longlong (C Type: unsigned
longlong, Minimum size if bytes: 8) ?

I found a page on the internet
(http://mail.python.org/pipermail/patches/2005-April/017430.html
 ), but I'm not quite sure if it is available.

 

 

What I want to do is to store an array of bytes in an array of longlongs.

To workaround this issue, I have tried to use the double array (TypeCode
'd'), since the size in bytes is the same (8 for instance).

But it gives me strange result. Please look at the example:

 

import array

myByteArray = array.array('B', [1,2,3,4,5,6,7,8])

>> myByteArray = array('B', [1, 2, 3, 4, 5, 6, 7, 8])

 

myLongArray = array.array('L', myByteArray.tostring() )

>> myLongArray = array('L', [67305985L, 134678021L])

 

myDoubleArray = array.array('d', myByteArray.tostring() )

>> myDoubleArray = array('d', [5.447603722011605e-270])

 

If we convert the byte array to an hex form, we will get for the long array:
[04030201, 08070605].

If we convert this hex array to decimal, we then get the Long Array:
[67305985, 134678021].

 

Now, if we do the same exercise for the double array, the hex form will look
like: [0807060504030201].

And the decimal value would be: [5.784376957523072e+17].

 

Where does the 5.447603722011605e-270 value comes from ?

 

 

Thanks for your help,

Francis

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From afriere at yahoo.co.uk  Tue Aug 11 22:24:39 2009
From: afriere at yahoo.co.uk (Asun Friere)
Date: Tue, 11 Aug 2009 19:24:39 -0700 (PDT)
Subject: hashability
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
Message-ID: <62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>

On Aug 12, 12:15?pm, James Stroud  wrote:

> I realize I left out my use. The intent of the function is to flag
> objects that will make useful keys for a persistent dictionary. The
> {C():4}[C()] example demonstrates why I want to avoid certain types of
> keys--I don't want users to do things like {C():4, C():4}, which python
> happily allows but falls apart at the level of persistence.

What am I missing here?  How, in terms of persistence, is {C():4, C():
4} conceptually different from {'spam':4, 'ham':4}?


From davea at ieee.org  Tue Aug 11 22:29:20 2009
From: davea at ieee.org (Dave Angel)
Date: Tue, 11 Aug 2009 22:29:20 -0400
Subject: adding multiple new values to the same key in a dictionary
In-Reply-To: <4A8192A30200008C00014AB9@redhorse.forestry.uga.edu>
References: <4A8192A30200008C00014AB9@redhorse.forestry.uga.edu>
Message-ID: <4A822900.7030008@ieee.org>

Krishna Pacifici wrote:
> Hi,
> I want to be able to add multiple new values to a key in a dictionary.
>
> I have tried the following:
>
> sec_dict_clean=
> {88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85]}
>
> for i in range(len(sec_dict_clean.values())):
>     for j in range(len(sec_dict_clean.values()[i])):
>         sec_dict_clean.setdefault(key,[]).append(blocks[sec_dict_clean.values()[i][j]].abundance)
>
> where blocks[...].abundance gives me a single value from an object,
>
> but this gives me the following:
>
> sec_dict_clean=
> {88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85, 4, 12, 11, 6, 9, 12, 11, 7, 10, 10, 12, 9, 6, 12, 15, 9, 8, 12, 15, 12, 12]}
>
> instead I want each abundance (starts with 4, 12...) to be associated with each of the values so that it would look like this:
>
> sec_dict_clean=
> {88: ([87, 89, 78, 98], [4,12,11,6]), 58: ([57, 59, 48, 68], [9,12,11,7]), 69: ([79], [10])...}
>
> You can see there are several errors here (I have more things being appended than there are values in the dictionary), but I really just want to know how to add multiple values to the same key in a dictionary.
>
> Thanks for any help,
> Krishna
>
>
>
>   
You're really distorting the purposes of both dictionary and list here.  
It makes your code totally unreadable, which makes it hard to write, and 
hard to debug.

A dictionary is a mapping between key and value, where each key has 
exactly one value.  You cannot add another one to it.   All you can do 
is make the value something which is itself a collection.  Now, your 
desired dictionary looks achievable, almost.  If you change the parens 
(tuple) to square brackets (list), then it'll work.
    So key 88 has a single value, which is a list of two items.  Each of 
those items is itself a list with 4 items.  And each of those items are 
integers.

But then I got bogged down in your sample code.  I tried to simplify it, 
replacing the first two lines with these three:

for i, key in enumerate(sec_dict_clean):
    val = sec_dict_clean[key]
    for j, xxx in enumerate(val):
        
???sec_dict_clean.setdefault(key,[]).append(blocks[sec_dict_clean.values()[i][j]].abundance)

But I can't make head nor tail of the third line.  You didn't have a 
variable key, so I don't know if I'm using the same one..  Since I can't 
figure out what you were trying to do, I can't see how to fix it.

I think the problem here is you're trying to reorganize the data as well 
as adding to it, in a single pass.  So is some previous code generating 
the dictionary incorrectly, and instead of fixing that, you're trying to 
reorganize it here?

To make each dictionary value a list of lists:

sec_dict_clean=
{88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85]}

for key in sec_dict_clean:
    sec_dict_clean[key] = [sec_dict_clean[key]]

now,  the dict looks like:
{88: [[87, 89, 78, 98, 3]], 58: [[57, 59, 48, 68]], 69: [[79]], 95: 
[[94, 96, 85]]}

At this point, if you have some interesting data to add to it, you can 
just append a new list to
     dict[key]

In an earlier message, you mentioned fields a and b, and assuming this 
is a similar problem, it would seem that 87 is somehow associated with 
4, and 89 with 12, and so on.  If that's the case, perhaps your desired 
final structure might look more like:

{88: [[87,4], [89,12], [78, 11],[98, 6],   58: [[57, 9], [59, 12], [48, 11], [68, 7]],   69: ...}


In this case, the structure is entirely different.  But the approach is 
the same.  And at least you'd be getting closer to the object approach 
where  [87,4] is replaced by an object of some type.

BTW, please don't top-post.  When you reply to this one, put your reply 
at the end, or sometimes interspersed.  But if you put it at the 
beginning, it's out of order.

DaveA



From davea at ieee.org  Tue Aug 11 22:54:49 2009
From: davea at ieee.org (Dave Angel)
Date: Tue, 11 Aug 2009 22:54:49 -0400
Subject: Need cleanup advice for multiline string
In-Reply-To: 
References: 
Message-ID: <4A822EF9.2090907@ieee.org>

Robert Dailey wrote:
> Hey guys. Being a C++ programmer, I like to keep variable definitions
> close to the location in which they will be used. This improves
> readability in many ways. However, when I have a multi-line string
> definition at function level scope, things get tricky because of the
> indents. In this case indents are serving two purposes: For syntax and
> actual text output. The tabs for function scope should not be included
> in the contents of the string. Below is the code I am trying to
> improve. Notice how it looks ugly/unreadable because of the way the
> string contents are shifted all the way to the left edge of the
> document. This breaks the flow of scope. Would you guys solve this
> problem by moving failMsg into global scope? Perhaps through some
> other type of syntax?
>
> Help is appreciated!
>
> def RunCommand( commandList ):
>    commandString =
>    print( 'Running Command:',  )
>    cmd = subprocess.Popen( commandList )
>    returnCode = cmd.wait()
>    if returnCode:
>       failMsg = '''\
> *************************************************
> The following command returned exit code [{:#x}].
> This represents failure of some form. Please review
> the command output for more details on the issue.
> ------------
> {}
> *************************************************
> '''
>       commandString = ' '.join( commandList )
>       raise CommandFailure( failMsg.format( returnCode,
> commandString ) )
>
>   
No, don't put it in global scope.  Put it externally, so it can be 
readily localized for international markets.

DaveA


From abecedarian314159 at yahoo.com  Tue Aug 11 23:22:56 2009
From: abecedarian314159 at yahoo.com (William)
Date: Tue, 11 Aug 2009 20:22:56 -0700 (PDT)
Subject: Is there any package implanation the following arithmetics?
In-Reply-To: 
References: 
	
Message-ID: <904309.72680.qm@web110602.mail.gq1.yahoo.com>

What you want is:
http://www.cgal.org/

I believe it has python bindings.

Cheers,
William



________________________________
From: Emile van Sebille 
To: python-list at python.org
Sent: Tuesday, August 11, 2009 12:49:19 PM
Subject: Re: Is there any package implanation the following arithmetics?

On 8/11/2009 1:49 AM zhongshq said...
> Hi,
> 
> I wonder if there has any package can check whether two rectangles are
> overlap, is a dot inside or outside a polygon, etc.

PythonCad at http://sourceforge.net/projects/pythoncad/ has intersections built in.

Emile

-- http://mail.python.org/mailman/listinfo/python-list



      
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From lanyjie at yahoo.com  Wed Aug 12 00:15:39 2009
From: lanyjie at yahoo.com (Yingjie Lan)
Date: Tue, 11 Aug 2009 21:15:39 -0700 (PDT)
Subject: releasing expy 0.1.1
Message-ID: <932447.5519.qm@web54201.mail.re2.yahoo.com>


Hi all,

This is to announce the release of expy 0.1.1 for those who are interested. Thanks a lot for the interest from this list. For more information, please see 

http://expy.sf.net/

Note: expy is an express way to extend Python. Why consider expy? Here are some good reasons:

(I). WYSIWYG. The expy project enables you to write your module in Python the way your extension would be (WYSIWYG), and meanwhile write your implementation in pure C. You specify your modules, functions, methods, classes, and even their documentations the usual way of writing your Python correspondences. Then your provide your implementation to the functions/methods by returning a multi-line string. By such an arrangement, everything falls in its right place, and your extension code becomes easy to read and maintain. Also, the generated code is very human-friendly.

(II). You only provide minimal information to indicate your intension of how your module/class would function in Python. So your extension is largely independent from the Python extension API. As your interaction with the Python extension API is reduced to minimal (you only care about the functionality and logic), it is then possible that your module written in expy can be independent of changes in the extension API.

(III). The building and setup of your project can be automatically done with the distutil tool. In the tutorial, there are ample examples on how easily this is achieved.

(IV). Very light weight. The expy tool is surprisingly light weight dispite of its powerful ability, as it is written in pure Python. There is no parser or compiler for code generation, but rather the powerful reflexion mechanism of Python is exploited in a clever way to generate human-friendly codes. Currently, generating code in C is supported, however, the implementation is well modularized and code generation in other languages such as Java and C++ should be easy.

While there are already a couple of other projects trying to simply this task with different strategies, such as Cython, Pyrex and modulator, this project is unique and charming in its own way. All you need is the WYSIWYG Python file for your module extension, then expy takes care of everything else. What follows in this documentation is on how to extend Python in C using expy-cxpy: the module expy helps define your module, while module cxpy helps generate C codes for your defined module.

regards,

Yingjie


      


From arphaksad at gmail.com  Wed Aug 12 00:27:47 2009
From: arphaksad at gmail.com (naaman)
Date: Tue, 11 Aug 2009 21:27:47 -0700 (PDT)
Subject: fileinput
Message-ID: 

I'm writing my first Python script and
I want to use fileinput to open a file in r+ mode.
Tried fileinput.input(sys.argv[1:],"r+") but that didn't work.
ANy ideas?

Need to find and overwrite a line in a file several times.
I can do it using open and seek() etc. but was wondering if I can use
fileinput.

thanks;



From bouncyinc at gmail.com  Wed Aug 12 00:28:22 2009
From: bouncyinc at gmail.com (John Haggerty)
Date: Tue, 11 Aug 2009 22:28:22 -0600
Subject: getting a "simple" program to work
In-Reply-To: 
References: 
Message-ID: 

just checking to see if there is any input that may have been misdirected to
a spam filter.
Would love to see some feedback if I may

On Sun, Aug 9, 2009 at 6:42 PM, John Haggerty  wrote:

> ok so I know this is one of those "weird" requests but here me out.
> So far I have an issue with a package for python called "libgmail" which is
> basically a gmail interface for python to send messages remoetly.
>
> Works ok except that the 'sendMessage' routine is bad.
>
> This is included in the above attachment
>
> it's used in a program called "ogss" which is an sms interface to gmail to
> basically read gmail and then have a command done on a remote machine and
> then spat out on the local machine to a log file that's opened and then
> emailed back
>
> problem is that the sending back routine fails.
>
> Now I've found a program that will more or less do what is requied but it's
> not really exactly what would be used in that it doesn't use the libgmail
> routine.
>
> So far the maintainer of both packages seem to be afk or not having their
> routines fixed and so far debian/Unbuntu claim that the last version of the
> package has been fixed :(
>
> Is there a recommendatin of how to combine/alter so that ogss can transmit?
> My main issue is that python is lesser known to me than Chinese (which I
> also don't know).
>
> My idea of this is to have a remote email timeclock program which could
> then be scripted with any language or just "echo >>blah" if necessary.
>
> Thanks in advance :)
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From clp2 at rebertia.com  Wed Aug 12 00:46:49 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Wed, 12 Aug 2009 00:46:49 -0400
Subject: getting a "simple" program to work
In-Reply-To: 
References: 
Message-ID: <50697b2c0908112146q6e12650dt914518166b4fae72@mail.gmail.com>

On Sun, Aug 9, 2009 at 8:42 PM, John Haggerty wrote:
> ok so I know this is one of those "weird" requests but here me out.
> So far I have an issue with a package for python called "libgmail" which is
> basically a gmail interface for python to send messages remoetly.
> Works ok except that the 'sendMessage' routine is bad.

How is it "bad" precisely? Be specific (e.g. error message(s),
description of observed incorrect behavior).

> This is included in the above attachment
> it's used in a program called "ogss" which is an sms interface to gmail to
> basically read gmail and then have a command done on a remote machine and
> then spat out on the local machine to a log file that's opened and then
> emailed back
> problem is that the sending back routine fails.

Which routine is that exactly? Please also specify exactly how it is
failing (e.g. error message(s), description of observed incorrect
behavior).

I apologize if these questions are answered in comments in the
attachments, but to be honest, the fact that you didn't (or couldn't)
put the specific problematic sections of code (and/or error messages)
inline in your message makes it less likely that people (such as
myself) will try to help you due to the volume of code you're making
people wade through (i.e. people tend not to read large code dumps,
/especially/ in attachments).

Cheers,
Chris
-- 
http://blog.rebertia.com


From bouncyinc at gmail.com  Wed Aug 12 01:02:57 2009
From: bouncyinc at gmail.com (John Haggerty)
Date: Tue, 11 Aug 2009 23:02:57 -0600
Subject: getting a "simple" program to work
In-Reply-To: <50697b2c0908112146q6e12650dt914518166b4fae72@mail.gmail.com>
References: 
	<50697b2c0908112146q6e12650dt914518166b4fae72@mail.gmail.com>
Message-ID: 

On Tue, Aug 11, 2009 at 10:46 PM, Chris Rebert  wrote:

> On Sun, Aug 9, 2009 at 8:42 PM, John Haggerty wrote:
> > ok so I know this is one of those "weird" requests but here me out.
> > So far I have an issue with a package for python called "libgmail" which
> is
> > basically a gmail interface for python to send messages remoetly.
> > Works ok except that the 'sendMessage' routine is bad.
>
> How is it "bad" precisely? Be specific (e.g. error message(s),
> description of observed incorrect behavior).
>

In regards to bad would be failing to transmit claiming that the submittal
is wrong for the transmit string.

(where username is my gmail username and "password" is my gmail password to
the test account, 6666666969 is the mobile number in question '00' is my
"carrier id" from the ogss code example which is just an array location from
a preformatted part of the string [probably from wikipedia on mobile carrier
email addresses to cell phones], I actually got desperate and commented out
the first attempt to transmit which I located in the code as just the
"instructions" the code fails on re-transmission, I later on looked at the
file and located that it was a zero byte file of no content. The program
itself looks for a command from the user's cell phone directly from mms sent
to the target gmail account prefaced by "Ogss" and anything else is treated
as a command but since the command failed on the first transmit I don't
think it's the command per se).

owner at bouncyinc:~/Desktop/OGSS$ python ogss.py username password 6666666969
00
Starting ogss
Logfile at:/home/owner/ogss.log
Opening log file for reading
Parsing user input
Connecting to Gmail
Logging into Gmail
Opening log file for writing
Listening for commands
Processing Command
ls: unrecognized option `---------------------------------------------'
Try `ls --help' for more information.
Seding back results
Traceback (most recent call last):
  File "ogss.py", line 127, in 
    main(sys.argv)
  File "ogss.py", line 110, in main
    account.sendMessage(tosend)
  File "/usr/lib/python2.5/site-packages/libgmail.py", line 615, in
sendMessage
    raise GmailSendError, resultInfo[SM_MSG]
libgmail.GmailSendError: Please try again.

I traced the result to the sendMessage routine and noted that anytime it
tries to send anything it fails this also fails with the standard "docs"
package for libgmail 0.30 docs from the maintainer's site.

Now the part where it *does* fail is where it has an issue with looking at
the trailing info but then it would have logged the info to the file and
emailed me back junk (which it didn't)

I assume this could be done on any system just replace 'ls' with 'dir' or
the equivalent.


>
> > This is included in the above attachment
> > it's used in a program called "ogss" which is an sms interface to gmail
> to
> > basically read gmail and then have a command done on a remote machine and
> > then spat out on the local machine to a log file that's opened and then
> > emailed back
> > problem is that the sending back routine fails.
>
> Which routine is that exactly? Please also specify exactly how it is
> failing (e.g. error message(s), description of observed incorrect
> behavior).
>
> I apologize if these questions are answered in comments in the
> attachments, but to be honest, the fact that you didn't (or couldn't)
> put the specific problematic sections of code (and/or error messages)
> inline in your message makes it less likely that people (such as
> myself) will try to help you due to the volume of code you're making
> people wade through (i.e. people tend not to read large code dumps,
> /especially/ in attachments).
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com
>
That's ok I understand I hope that helps at least in part.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From ben+python at benfinney.id.au  Wed Aug 12 01:11:22 2009
From: ben+python at benfinney.id.au (Ben Finney)
Date: Wed, 12 Aug 2009 15:11:22 +1000
Subject: Character encoding & the copyright symbol
References: <29ab0981-b95d-4435-91bd-a7a520419ada@b15g2000yqd.googlegroups.com>
	
Message-ID: <87skfxehvp.fsf@benfinney.id.au>

Dave Angel  writes:

> But I wanted to comment on the (c) remark.  If you're in the US,
> that's the wrong abbreviation for copyright.  The only recognized
> abbreviation is (copr).

More reading on this:

    
    

In brief: To be a legally-recognised copyright notice under US law, it
must begin with ?Copyright?, or one of the abbreviations ?Copr.? or the
exact symbol ???. As you rightly point out, neither ?(c)? nor ?(C)? have
any legal status as a copyright marker.

The Berne Convention, by making copyright active on *every* creative
work of expression, even in the total *absence* of a copyright notice,
essentially undermines the force of this and makes it exceedingly
difficult to divest a work of copyright. But that's a whole 'nother
depressing mess.

-- 
 \         ?A politician is an animal which can sit on a fence and yet |
  `\                  keep both ears to the ground.? ?Henry L. Mencken |
_o__)                                                                  |
Ben Finney


From nospamjstroudmapson at mbi.ucla.edu  Wed Aug 12 01:32:50 2009
From: nospamjstroudmapson at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 22:32:50 -0700
Subject: hashability
In-Reply-To: <62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
Message-ID: 

Asun Friere wrote:
> On Aug 12, 12:15 pm, James Stroud  wrote:
> 
>> I realize I left out my use. The intent of the function is to flag
>> objects that will make useful keys for a persistent dictionary. The
>> {C():4}[C()] example demonstrates why I want to avoid certain types of
>> keys--I don't want users to do things like {C():4, C():4}, which python
>> happily allows but falls apart at the level of persistence.
> 
> What am I missing here?  How, in terms of persistence, is {C():4, C():
> 4} conceptually different from {'spam':4, 'ham':4}?

You should be more imaginative.


From nospamjstroudmapson at mbi.ucla.edu  Wed Aug 12 01:33:50 2009
From: nospamjstroudmapson at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 22:33:50 -0700
Subject: hashability
In-Reply-To: <77eda964-a6ee-496b-9c5f-5391663099e0@b14g2000yqd.googlegroups.com>
References: 
	<77eda964-a6ee-496b-9c5f-5391663099e0@b14g2000yqd.googlegroups.com>
Message-ID: 

Asun Friere wrote:
> Perhaps the best solution would be for the unitiated to correct their
> misaprehensions

Can you come give a class to my users?


From nospamjstroudmapson at mbi.ucla.edu  Wed Aug 12 01:51:12 2009
From: nospamjstroudmapson at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 22:51:12 -0700
Subject: Frustrated with scopes
In-Reply-To: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
Message-ID: 

andrew cooke wrote:
> Is there a way to make this work (currently scope and join are
> undefined at runtime when the inner class attributes are defined):
> 
> class _StreamFactory(object):
> 
>     @staticmethod
>     def __call__(lines, source, join=''.join):
> 
>         class Line(object):
> 
>             __source = source
>             __join = join
> [...]


It would be helpful if you were to describe the type of behavior you expect.

I assume you will return the newly created Line class when you call an 
instance of _StreamFactory? There may be some things about the above 
that you might be overlooking:

1. __call__ does not supersede the __init__ constructor of _StreamFactory.
2. __source and __join are name-mangled in later versions of python. 
They will be attributes of the returned Line class named _Line_source 
and _Line_join respectively.

Rather than make _StreamFactory a class, you will probably get the 
behavior you desire if you simply make it a function:

def stream_factory:
   class Line(object):
     __source = source
     __join = join
   # etc.
   return Line

And then don't forget that double underscores produce name mangling and 
you'll be set.

James




From petshmidt at googlemail.com  Wed Aug 12 01:52:50 2009
From: petshmidt at googlemail.com (Pet)
Date: Tue, 11 Aug 2009 22:52:50 -0700 (PDT)
Subject: better way?
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
	<87skfyjen8.fsf@golux.woodcraft.me.uk> 
	
Message-ID: <6733c8fe-9ef8-4010-9b23-27538e19d8ff@c29g2000yqd.googlegroups.com>

On 11 Aug., 22:19, "Rami Chowdhury"  wrote:
> Ah, my apologies, I must have been getting it confused with ON UPDATE ?
> [things]. Thanks for correcting me.
>
> On Tue, 11 Aug 2009 13:10:03 -0700, Matthew Woodcraft ?
>
>  wrote:
> > "Rami Chowdhury"  writes:
>
> >> IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than
> >> MySQL...
>
> > PostgreSQL does not have ON DUPLICATE KEY UPDATE.
>
> > The SQL standard way to do what the OP wants is MERGE. PostgreSQL
> > doesn't have that either.
>
> > -M-
>
> --
> Rami Chowdhury
> "Never attribute to malice that which can be attributed to stupidity" -- ?
> Hanlon's Razor
> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD)

So, I'm doing it in right way?
What about building columns? map(lambda s: s + ' = %s', fields)
Is that o.k.?

thanks


From chris at rebertia.com  Wed Aug 12 01:52:51 2009
From: chris at rebertia.com (Chris Rebert)
Date: Wed, 12 Aug 2009 01:52:51 -0400
Subject: hashability
In-Reply-To: <62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
Message-ID: <50697b2c0908112252l758c32b9u701daf09a7810a09@mail.gmail.com>

2009/8/11 Asun Friere :
> On Aug 12, 12:15?pm, James Stroud  wrote:
>
>> I realize I left out my use. The intent of the function is to flag
>> objects that will make useful keys for a persistent dictionary. The
>> {C():4}[C()] example demonstrates why I want to avoid certain types of
>> keys--I don't want users to do things like {C():4, C():4}, which python
>> happily allows but falls apart at the level of persistence.
>
> What am I missing here? ?How, in terms of persistence, is {C():4, C():
> 4} conceptually different from {'spam':4, 'ham':4}?

Thought Experiment:
Consider, for each dict, the case of pickling it twice to 2 separate files.
When loaded from both files into the same program, the spam-ham dicts
will work as expected between each other.
The dicts with C()s will not. For example, assuming the unpickled
dicts are `cs1` and `cs2`, cs1[cs2.keys()[0]] will raise KeyError.

Cheers,
Chris
-- 
http://blog.rebertia.com


From greg at cosc.canterbury.ac.nz  Wed Aug 12 02:06:13 2009
From: greg at cosc.canterbury.ac.nz (greg)
Date: Wed, 12 Aug 2009 18:06:13 +1200
Subject: Bug in format specification in Python 3?
In-Reply-To: 
References: 
Message-ID: <7ef4dkF26f4duU1@mid.individual.net>

Robert Dailey wrote:

> I notice that the '0x' portion is counted in the width, which was
> specified as 8. This seems wrong to me. Is this by design? If so, why?

Yes, it's the total field width. This is consistent with
the other formats, in which it includes decimal points,
signs, etc.

If you don't want that, then write the format string as

   'This is a hex number: 0x{:08x}'

-- 
Greg


From greg at cosc.canterbury.ac.nz  Wed Aug 12 02:17:06 2009
From: greg at cosc.canterbury.ac.nz (greg)
Date: Wed, 12 Aug 2009 18:17:06 +1200
Subject: Social problems of Python doc [was Re: Python docs disappointing]
In-Reply-To: <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
Message-ID: <7ef51uF2g36t5U1@mid.individual.net>

rurpy at yahoo.com wrote:
> Such a reorg is not a simple matter
> of moving a file from here to there.  It will require a lot
> moving about of sections and a lot of word-smithing to glue
> them back together again in a coherent way.

Concerning this particular issue, not everyone would
agree that the doc sections in question are misplaced.

In Python the distinction between builtin and library
types is fairly blurry. There are advantages to having
them all documented in one place -- when looking for
info about a type, you don't have to try to guess
whether it's considered built-in or not to know which
manual to look in.

-- 
Greg


From nospamjstroudmapson at mbi.ucla.edu  Wed Aug 12 02:17:08 2009
From: nospamjstroudmapson at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 23:17:08 -0700
Subject: Frustrated with scopes
In-Reply-To: 
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
	
Message-ID: 

James Stroud wrote:
 > def stream_factory:
 >   class Line(object):
 >     __source = source
 >     __join = join
 >   # etc.
 >   return Line
 >

of course I meant "def stream_factory(lines, source, join=''.join):"

James



From afriere at yahoo.co.uk  Wed Aug 12 02:18:59 2009
From: afriere at yahoo.co.uk (Asun Friere)
Date: Tue, 11 Aug 2009 23:18:59 -0700 (PDT)
Subject: hashability
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
	
Message-ID: 

On Aug 12, 3:32?pm, James Stroud 
wrote:

> You should be more imaginative.

I'm by no means discounting that there might be some actual problem
you're trying to solve here, but I honestly can't see it.

There really is no need to get personal about this, so rather than
asking for a level of imagination from me, (which I apparently lack),
please just explain to me how {one_instance_of_a_hashable_class : val,
another_instance_of_a_hashable_class :val} is conceptually different
{one_instance_of_class_str: val, another_instance_of_class_str: val},
in terms of persistence.

If I am missing something here, I would actually like to know.  If on
the other hand, I'm not, then rather at taking umbrage, you might want
instead to save yourself the effort of solving a non-existent problem?

> Can you come give a class to my users?

No.

However, I think it's fairly central to the notion of a class that it
is a template for creating different instances which themselves have a
unique identity.  And that subsequent calls to a class' constructor
ought to create unique instances of that class (subject perhaps to
implementation tricks such as interning).  If it is not obvious that {C
():4}[C()] invovles subsequent calls to C's constructor, then that
very example is itself didactic.


From clp2 at rebertia.com  Wed Aug 12 02:25:04 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Wed, 12 Aug 2009 02:25:04 -0400
Subject: hashability
In-Reply-To: <62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
Message-ID: <50697b2c0908112325h2610d261x487dd62caed57172@mail.gmail.com>

2009/8/11 Asun Friere :
> On Aug 12, 12:15?pm, James Stroud  wrote:
>
>> I realize I left out my use. The intent of the function is to flag
>> objects that will make useful keys for a persistent dictionary. The
>> {C():4}[C()] example demonstrates why I want to avoid certain types of
>> keys--I don't want users to do things like {C():4, C():4}, which python
>> happily allows but falls apart at the level of persistence.
>
> What am I missing here? ?How, in terms of persistence, is {C():4, C():
> 4} conceptually different from {'spam':4, 'ham':4}?

Consider the case of pickling the data twice to 2 separate files.
When loaded from both files into the same program, the spam-ham dicts
will work as expected.
The C()s will not. For cs1[cs2.keys()[0]] will raise KeyError.

Cheers,
Chris
-- 
http://blog.rebertia.com


From clp2 at rebertia.com  Wed Aug 12 02:26:31 2009
From: clp2 at rebertia.com (Chris Rebert)
Date: Wed, 12 Aug 2009 02:26:31 -0400
Subject: hashability
In-Reply-To: <50697b2c0908112325h2610d261x487dd62caed57172@mail.gmail.com>
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
	<50697b2c0908112325h2610d261x487dd62caed57172@mail.gmail.com>
Message-ID: <50697b2c0908112326q7908190btff3352979a02dc4f@mail.gmail.com>

On Wed, Aug 12, 2009 at 2:25 AM, Chris Rebert wrote:
> 2009/8/11 Asun Friere :
>> On Aug 12, 12:15?pm, James Stroud  wrote:

Apologies for the possible repeated post. Gmail failed to mark the
draft as sent for some reason.

- Chris


From afriere at yahoo.co.uk  Wed Aug 12 02:29:41 2009
From: afriere at yahoo.co.uk (Asun Friere)
Date: Tue, 11 Aug 2009 23:29:41 -0700 (PDT)
Subject: hashability
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
	
Message-ID: <3a07642d-7876-4939-9c05-f09545afd41a@b15g2000yqd.googlegroups.com>

On Aug 12, 3:52?pm, Chris Rebert  wrote:

> Thought Experiment:
> Consider, for each dict, the case of pickling it twice to 2 separate files.
> When loaded from both files into the same program, the spam-ham dicts
> will work as expected between each other.
> The dicts with C()s will not. For example, assuming the unpickled
> dicts are `cs1` and `cs2`, cs1[cs2.keys()[0]] will raise KeyError.
>

Aha!

cheers.



From dstanek at dstanek.com  Wed Aug 12 02:31:55 2009
From: dstanek at dstanek.com (David Stanek)
Date: Wed, 12 Aug 2009 02:31:55 -0400
Subject: hashability
In-Reply-To: 
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
	
	
Message-ID: 

On Wed, Aug 12, 2009 at 2:18 AM, Asun Friere wrote:
> On Aug 12, 3:32?pm, James Stroud 
> wrote:
>
>> You should be more imaginative.
>
> I'm by no means discounting that there might be some actual problem
> you're trying to solve here, but I honestly can't see it.

How about a cache? Hashing by id means nothing across machines or even
process runs on the same machine.

-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek


From nospamjstroudmapson at mbi.ucla.edu  Wed Aug 12 02:52:17 2009
From: nospamjstroudmapson at mbi.ucla.edu (James Stroud)
Date: Tue, 11 Aug 2009 23:52:17 -0700
Subject: hashability
In-Reply-To: 
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
	
	
Message-ID: 

Asun Friere wrote:
> On Aug 12, 3:32 pm, James Stroud 
> wrote:
> 
>> You should be more imaginative.
> 
> I'm by no means discounting that there might be some actual problem
> you're trying to solve here, but I honestly can't see it.
> 
> There really is no need to get personal about this, so rather than
> asking for a level of imagination from me, (which I apparently lack),
> please just explain to me how {one_instance_of_a_hashable_class : val,
> another_instance_of_a_hashable_class :val} is conceptually different
> {one_instance_of_class_str: val, another_instance_of_class_str: val},
> in terms of persistence.

Sorry for being a twit. This list used to be quite nice but some people 
on this list got pretty abrasive. I couldn't tell you weren't one of 
these abrasive people from your post. I stopped giving the benefit of 
the doubt many moons ago and promptly enter attack mode at the slightest 
hint of abrasiveness. My attitude probably exacerbates the problem--but 
it sure does make me feel better.


Anyway, I think the problem has been described better than I'm able, but 
once an object goes to the file system, one can not take its hash value 
for granted. It is not possible to rely on the ability to recreate any 
arbitrary object de-novo and use the recreation as a key in proxy for 
the original object. I'm after this "je ne sais pas que l'appeler" 
quality of objects to use as keys (or to generate keys) for persistent 
dictionaries. Carl Banks suggested that this quality should not be 
called "hashable", so I'm calling it "keyable".


From garabik-news-2005-05 at kassiopeia.juls.savba.sk  Wed Aug 12 02:58:43 2009
From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk)
Date: Wed, 12 Aug 2009 06:58:43 +0000 (UTC)
Subject: create shell history with python
References: 
	<7ee8saF2e47vaU1@mid.uni-berlin.de>
Message-ID: 

Diez B. Roggisch  wrote:
> Joel Juvenal Rivera Rivera schrieb:
>> I been thinking how to make a 'bash like history shell' in python,
>> i don't know if with stdin and stdout i can accomplish this or do i
>> need something like curses and stuff like that, anyway im start to
>> figure this out.
>> Does any body has try this? or have any interesting idea?
> 
> Don't waste your time, use IPython :)
> 
> http://ipython.scipy.org/moin/
> 

for python 2.x only, unfortunately

-- 
 -----------------------------------------------------------
| Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__    garabik @ kassiopeia.juls.savba.sk     |
 -----------------------------------------------------------
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!


From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 03:08:06 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 07:08:06 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
	 <0291a21a$0$20639$c3e8da3@news.astraweb.com>
	<8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com>
	
	<1a0e1e6d-d902-4df7-8d35-850c4f62cc9c@e27g2000yqm.googlegroups.com>
Message-ID: 

On Tue, 11 Aug 2009 14:48:24 -0700, Douglas Alan wrote:

> In any case, my argument has consistently been that Python should have
> treated undefined escape sequences consistently as fatal errors, 

A reasonable position to take. I disagree with it, but it is certainly 
reasonable.


> not as warnings.

I don't know what language you're talking about here, because non-special 
escape sequences in Python aren't either errors or warnings:

>>> print "ab\cd"
ab\cd

No warning is made, because it's not considered an error that requires a 
warning. This matches the behaviour of other languages, including C and 
bash.



-- 
Steven


From afriere at yahoo.co.uk  Wed Aug 12 03:13:50 2009
From: afriere at yahoo.co.uk (Asun Friere)
Date: Wed, 12 Aug 2009 00:13:50 -0700 (PDT)
Subject: hashability
References: 
	<3c01fa6b-b6b7-4c02-aaf8-34e005355f31@a37g2000prf.googlegroups.com>
	
	<62618e10-44f0-406d-8446-efe78a9c101c@s31g2000yqs.googlegroups.com>
	
	
	
Message-ID: <108fe8d0-ec3c-49f4-b825-9303ac6aa8a9@32g2000yqj.googlegroups.com>

On Aug 12, 4:52?pm, James Stroud 
wrote:

> Sorry for being a twit.

Don't be ridiculous.  You haven't been a twit, I have!

I've just had a complete "blonde" moment here (with apologies to any
real blondes out there.  My only excuse is that I've been up to 02:30
for the last three nights running (or maybe it's the ageing process, a
cerebrovascular accident or something).

I just checked a class I recently wrote specifically for the purposes
of hashing a dict (in case I had made this error IRL).  Wouldn't you
know it, it's subclassed to tuple, and defines both __eq__ and
__cmp__.  Luckily when I write production code the guy who knows what
he's doing takes over.  And this in an app which compares keys from
different pickled files (representing DB holdings)?!  Of all things.

I can't believe how unfathomably stupid I've been.  I'm extremely
embarassed.  I think I'll just go out and shoot myself now.  Or get
some sleep.


From stefan_ml at behnel.de  Wed Aug 12 03:18:03 2009
From: stefan_ml at behnel.de (Stefan Behnel)
Date: Wed, 12 Aug 2009 09:18:03 +0200
Subject: ElementTree - Howto access text within XML tag element...
In-Reply-To: 
References: <1ad8dac1-8fff-493a-a197-d847e7b6a761@c2g2000yqi.googlegroups.com>
	<7ecm77F2fbf71U1@mid.uni-berlin.de>
	
Message-ID: <4a826cac$0$31870$9b4e6d93@newsspool3.arcor-online.net>

cmalmqui wrote:
> tree = etree.parse('10_07_2009 16_48_00_history.tcx')
> root = tree.getroot()
> 
> elem = root[0][0]
> 
> # iterate over all laps
> for i in range(1, len(elem)-1):

Note that you can iterate over elements as in

	for lap_element in elem:
	    # ...

Then use

	record = lap.find("recordtagname")

to find things inside the subtree. You can also use XPath-like expressions
such as

	all_intersting_elements =
		lap.findall("sometag/somechild//somedescendant")

Stefan


From afriere at yahoo.co.uk  Wed Aug 12 03:25:06 2009
From: afriere at yahoo.co.uk (Asun Friere)
Date: Wed, 12 Aug 2009 00:25:06 -0700 (PDT)
Subject: hashability
References: 
	
Message-ID: <25e7ee06-233d-4c8d-b5a9-384a4f5f1694@s15g2000yqs.googlegroups.com>

On Aug 12, 5:14?pm, Dennis Lee Bieber  wrote:

> c1 = C()
> c2 = C()
>
> {c1:4}[c2]
>
> to behave? That IS the equivalent of your statement -- two instances are
> two distinctly different entities...
>

Thankyou, that is EXACTLY the mistake I made that sent me off into
lunacy.

At the risk of further embarassment, the answer is that one would
expect it to behave analogously to:

c1 = int(x)
c2 = int(x)

{c1:4}[c2]

Or is my brain still on vacation?


From nospamjstroudmapson at mbi.ucla.edu  Wed Aug 12 03:33:01 2009
From: nospamjstroudmapson at mbi.ucla.edu (James Stroud)
Date: Wed, 12 Aug 2009 00:33:01 -0700
Subject: hashability
In-Reply-To: 
References: 
	
Message-ID: 

Dennis Lee Bieber wrote:
> On Tue, 11 Aug 2009 17:54:36 -0700, James Stroud 
> declaimed the following in gmane.comp.python.general:
> 
>>    ...
>>    py> {C():4}[C()]
>>    ------------------------------------------------------------
>>    Traceback (most recent call last):
>>      File "", line 1, in 
>>    : <__main__.C object at 0xe21610>
>>
>> The basis for the exception is that the two instances do not have the 
>> same hash() although conceptually they might seem equal to the 
>> unitiated. Were I to re-design python, I'd throw an exception in this 
>> case because of the ill-defined behavior one might expect if a C() 
>> serves as a key for a dict.
>>
> 	"A" C()... How would you expect
> 
> c1 = C()
> c2 = C()
> 
> {c1:4}[c2] 
> 
> to behave?


This seems like a subjective question. I think I demonstrated how it 
*does* behave, which is purely objective--and I know I can't do anything 
about that. But the subjective answer to the subjective question is that 
I would like an exception to be raised when the dictionary is 
constructed. I know an exception doesn't get thrown in the current 
incarnation of the python language. That is the objective reality of the 
situation which affronts my subjective notions of how reality should be.

That IS the equivalent of your statement -- two instances are
> two distinctly different entities...

Tell that to two different machines on two different days. Then bet the 
life of yourself and your nearest and dearest family on that fact and 
see whether you really want to take a hash value for granted. If a 
property of the python language fails the "bet the lives of your nearest 
and dearest on a consistent result" test, I call it "ill defined" and, 
subjectively speaking, I prefer exceptions to be thrown--And, by damned, 
I'll throw them myself if I have to.

"If it saves one life, it's worth it all."

James




From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 03:34:33 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 07:34:33 GMT
Subject: hashability
References: 
Message-ID: 

On Tue, 11 Aug 2009 17:54:36 -0700, James Stroud wrote:

> Hello All,
> 
> I wrote the function to test hashability of arbitrary objects. My reason
> is that the built-in python (2.5) hashing is too permissive for some
> uses. A symptom of this permissiveness comes from the ability to
> successfully hash() arbitrary objects:

No it doesn't.


>>> hash([])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: list objects are unhashable

Python successfully hashes *non*-arbitrary objects, including those that 
inherit from object.



>    py> class C(object): pass
>    ...
>    py> {C():4}[C()]
>    ------------------------------------------------------------
>    Traceback (most recent call last):
>      File "", line 1, in 
>    : <__main__.C object at 0xe21610>

Why would you expect that to succeed? The object you are using as the key 
is a different instance than the object you are looking up. Since your 
instances don't even compare equal, why would you expect them to hash 
equal?

>>> C() == C()
False



> The basis for the exception is that the two instances do not have the
> same hash() although conceptually they might seem equal to the
> unitiated. 

Yes, well, the ignorant and uninitiated frequently make mistakes. I feel 
your pain.



> Were I to re-design python, I'd throw an exception in this
> case because of the ill-defined behavior one might expect if a C()
> serves as a key for a dict.

It's not ill-defined, it's a perfectly reasonable design you just don't 
happen to like. It's quite useful for some.


> To prevent users of one of my libraries from falling into this and
> similar traps (which have potentially problematic consequences), I came
> up with this test for hashability:

That's not a test for hashability. That's a test for hashability and 
equality testing together.


> def hashable(k):
>    try:
>      hash(k)
>    except TypeError:
>      good = False
>    else:
>      good = (hasattr(k, '__hash__') and
>              (hasattr(k, '__eq__') or hasattr(k, '__cmp__')))
>    return good

The test for __hash__ is redundant, given that hash() has already 
succeeded.

It will wrongly reject classes that deliberately don't define equality, 
for whatever reason, and that *expect* the behaviour you are treating as 
an error.



> It works as I would like for most of the cases I can invent:
> 
>    py> all(map(hashable, [1,1.0,"",(1,2,3)])) True
>    py> any(map(hashable, [None, [1,2], {}, C(), __import__('sys')]))
>    False

Well there you go -- why on earth would you prohibit None as a dictionary 
key??? That's a serious failure.



-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 03:36:56 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 07:36:56 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
	 <0291a21a$0$20639$c3e8da3@news.astraweb.com>
	<8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com>
Message-ID: 

On Tue, 11 Aug 2009 13:20:52 -0700, Douglas Alan wrote:

> On Aug 11, 2:00?pm, Steven D'Aprano  cybersource.com.au> wrote:
> 
>> > test.cpp:1:1: warning: unknown escape sequence '\y'
>>
>> Isn't that a warning, not a fatal error? So what does temp contain?
> 
> My "Annotated C++ Reference Manual" is packed, and surprisingly in
> Stroustrup's Third Edition, there is no mention of the issue in the
> entire 1,000 pages. But Microsoft to the rescue:
> 
>      If you want a backslash character to appear within a string, you
>      must type two backslashes (\\)
> 
> (From http://msdn.microsoft.com/en-us/library/69ze775t.aspx)

Should I assume that Microsoft's C++ compiler treats it as an error, not 
a warning? Or is is this *still* undefined behaviour, and MS C++ compiler 
will happily compile "ab\cd" whatever it feels like?

 
> The question of what any specific C++ does if you ignore the warning is
> irrelevant, as such behavior in C++ is almost *always* undefined. Hence
> the warning.

So a C++ compiler which follows Python's behaviour would be behaving 
within the language specifications.

I note that the bash shell, which claims to follow C semantics, also does 
what Python does:

$ echo $'a s\trin\g with escapes'
a s     rin\g with escapes


Explain to me again why we're treating underspecified C++ semantics, 
which may or may not do *exactly* what Python does, as if it were the One 
True Way of treating escape sequences?


-- 
Steven


From petshmidt at googlemail.com  Wed Aug 12 03:49:50 2009
From: petshmidt at googlemail.com (Pet)
Date: Wed, 12 Aug 2009 00:49:50 -0700 (PDT)
Subject: better way?
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
Message-ID: <6126d193-5715-492f-8054-d9212bc6b87f@o32g2000yqm.googlegroups.com>

On 12 Aug., 09:14, Dennis Lee Bieber  wrote:
> On Tue, 11 Aug 2009 11:45:50 -0700 (PDT), Pet 
> declaimed the following in gmane.comp.python.general:
>
> > Oh, forgotten to mention. It's PostGres
>
> ? ? ? ? Really? There are still installations of an RDBMS that predates the
> commonalization of SQL?
>
> ? ? ? ? I suspect you mean PostgreSQL -- it IS a different beast from the
> older Postgres.

O, yeah. Of course it is PostgreSQL

>
> ? ? ? ? In either event -- my old books don't show an "all in one" solution.
>
> ? ? ? ? Best answer is probably to create some stored procedures which you
> call instead of plain INSERT; the stored procedure could then do
> whatever is needed to check for a duplicate (actually the easiest, I'd
> think, would be: if primary key is supplied, it is an UPDATE; if primary
> key is NULL or not supplied, it is an insert and the primary key will be
> auto-generated).

I don't really like the idea of stored procedure, because query would
depend on existence of it then. On the other side, it looks like best
option.

>
> --
> ? ? ? ? Wulfraed ? ? ? ? Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG
> ? ? ? ? wlfr... at ix.netcom.com ? ? HTTP://wlfraed.home.netcom.com/



From chris at simplistix.co.uk  Wed Aug 12 03:52:09 2009
From: chris at simplistix.co.uk (Chris Withers)
Date: Wed, 12 Aug 2009 08:52:09 +0100
Subject: httplib incredibly slow :-(
In-Reply-To: <4A81FDF5.6010508@simplistix.co.uk>
References: 	
	<4A81FDF5.6010508@simplistix.co.uk>
Message-ID: <4A8274A9.7000905@simplistix.co.uk>

Answering myself...

Chris Withers wrote:
>> In article ,
>> Chris Withers   wrote:
>>> Does anyone know of an alternative library for creating http requests 
>>> and getting their responses that's faster but hopefully has a similar 
>>> interface?
>>
>> PyCurl
> 
> This seems to be a wrapper around libcurl.
> 
> Does it work on Windows?

Not by my definition of work:

- there are no windows binaries for libcurl

- getting https support on windows seems pretty hit'n'miss:
http://stackoverflow.com/questions/197444/building-libcurl-with-ssl-support-on-windows

I'm still reeling from what seems to be such a huge problem with httplib 
that seem to be largely ignored :-(

Chris

-- 
Simplistix - Content Management, Batch Processing & Python Consulting
            - http://www.simplistix.co.uk


From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 03:58:59 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 07:58:59 GMT
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
Message-ID: 

On Tue, 11 Aug 2009 14:50:51 -0700, rurpy wrote:

>>> The issue tracker is fine for many things, but the process it provides
>>> is equivalent to peep-hole optimization.  How does one submit a
>>> tracker issue for something like the overall organization of the docs
>>> (for example, the mis-placement of things like data- types in the
>>> library manual rather than the language manual)?
>>
>> The same way you would submit a tracker issue for anything.
>>
>> "Documentation bug: Data types are misplaced in the library manual
>> instead of the language manual.
>>
>> Suggested alternative: move page docs.python.org/xyz.html to abc.html"
> 
> But that's the problem.  Such a reorg is not a simple matter of moving a
> file from here to there.  It will require a lot moving about of sections
> and a lot of word-smithing to glue them back together again in a
> coherent way.

That's no different from *any* major refactoring. The exact same problem 
exists for code as well as documentation. It's a solved problem for code, 
and it's a solved problem for documentation.

In some order:

Consensus that there is a problem that needs solving;
Volunteer(s) to do the work;
Somebody to take responsibility to check the changes in.


Sometimes, in the face of apathy or disagreement (which may very well be 
justified), you have to at least partly solve the problem *before* people 
will agree that it needed to be solved. Welcome to the real world.



> A tracker issue, even one that was fairly specific about how things
> should be reorganized but which did not provide all the needed changes
> (a large patch) would almost certainly be ignored or rejected.

Yes it would. Most patches are ignored, because the dev team are 
overworked, and if they don't see the need for a patch, they won't 
approve it.



> But
> providing a large patch raises two questions.  How likely is it to be be
> accepted? (Something anyone would want to know before investing the
> time.) And how to actually do the work needed to generate it (it could
> be a very large amount of work for an individual and I don't think it
> can be broken down into small independent issues.) How is one to test
> the waters as to acceptability, or solicit help, if one simply submits a
> tracker issue?

No, submitting a tracker issue is a necessary but not sufficient step. 
Without a tracker issue, you're very unlikely to have people agree to 
replace the existing docs with your docs, although a PEP would probably 
do it. (A PEP is significantly more effort than raising a tracker issue.)

You also have to get attention from those with check-in privileges. If 
they approve your patches, you're done. If they don't approve them, or 
fail to respond, you can try convincing them, or taking it to the Python-
Dev list and request somebody review your patches.

If you have no patches, perhaps because you're unwilling to invest the 
effort without a guarantee that it will be treated seriously, then you 
need to get some sort of consensus among the relevant people that the 
problem is worth solving.

Guess what? Sometimes others will disagree with you. What you see as the 
Worst. Docs. EVAR. may be seen as perfectly adequate, even excellent, by 
others. If this is the case, remember, Python isn't your product, you 
don't have veto over what goes into it. Feel free to publish your 
alternatives. Write a book. Go home and cry into your beer over it. 
Whatever. Sometimes you win, and sometimes you don't.

This is the same process whether dealing with code or documentation.


>> - if people are keen on a Python wiki, then by all means publish one,
>> just don't expect the Python dev team to build and manage it for you;
> 
> As luminous a Pythoneer as Fredrik Lundh set up a documentation wiki to
> collect user contributions but it has faded away.  If he couldn't pull
> it off then I'd say most other attempts without the backing of
> python.org are almost certainly doomed to failure.

Perhaps that's a good indication that a Python wiki *doesn't* fulfill a 
need in the community, and that despite what a few squeaky wheels think, 
the docs *are* doing a good job?



> As long as every "the docs
> sux" complaint is met here with the standard responses that I've
> mentioned, 

But they aren't met with such a so-called "standard response".


> rather than, "yes, they do have some problems, what do you
> think we should do about them?", 

We know that there are problems. We've said repeatedly that corrections 
and patches are welcome. We've repeatedly told you how to communicate 
your answer to the question of what should be done. None of this is good 
enough for you. I don't know what else you expect.


>> If you won't put in the effort, and you won't put in the money, then it
>> won't happen. Moaning that other people aren't putting in the money to
>> hire team of professional writers isn't productive, and moaning that
>> other people aren't putting in the effort to improve the docs isn't
>> either.
> 
> Eh?  I have a computer filled with software that I put no money or
> effort into, yet there it is.  

Ah yes, I'm sorry, I missed one other alternative: sit around and wait 
for somebody else to put in the money and/or effort.

> That some of us choose to
> invest it somewhere other than Python does not deprive of of our right
> to point out problems in Python when we note them.

Of course not. But it does mean that you won't be taken seriously, and 
you have no right to be taken seriously.



-- 
Steven


From jai_dgl at yahoo.co.in  Wed Aug 12 04:15:01 2009
From: jai_dgl at yahoo.co.in (Jey Simhan)
Date: Wed, 12 Aug 2009 01:15:01 -0700 (PDT)
Subject: Invitation to connect on LinkedIn
Message-ID: <1144938511.2842753.1250064901163.JavaMail.app@ech3-cdn13.prod>

LinkedIn
------------



   
I'd like to add you to my professional network on LinkedIn.

- Jey

Learn more:
https://www.linkedin.com/e/isd/682391381/2q9uIjvU/


 
------
(c) 2009, LinkedIn Corporation

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From simon at brunningonline.net  Wed Aug 12 04:21:24 2009
From: simon at brunningonline.net (Simon Brunning)
Date: Wed, 12 Aug 2009 09:21:24 +0100
Subject: Need cleanup advice for multiline string
In-Reply-To: <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> 
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
Message-ID: <8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com>

2009/8/11 Robert Dailey :
> On Aug 11, 3:40?pm, Bearophile  wrote:
>> There are gals too here.
>
> It's a figure of speech. And besides, why would I want programming
> advice from a woman? lol. Thanks for the help.

Give the attitudes still prevalent in our industry (cf
 and many more), I'm sorry to say that I
don't think this is funny.

-- 
Cheers,
Simon B.


From thorsten at thorstenkampe.de  Wed Aug 12 04:43:09 2009
From: thorsten at thorstenkampe.de (Thorsten Kampe)
Date: Wed, 12 Aug 2009 10:43:09 +0200
Subject: Scraping Wikipedia with Python
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	
Message-ID: 

* Dotan Cohen (Tue, 11 Aug 2009 21:29:40 +0300)
> > ? ?Wikipedia has an API for computer access. ?See
> >
> > ? ? ? ?http://www.mediawiki.org/wiki/API
> >
> 
> Yes, I am aware of this as well. Does anyone know of a python class
> for easily interacting with it, or do I need to roll my own.

http://pypi.python.org/pypi?%3Aaction=search&term=wikipedia ?

Thorsten 


From hendrik at microcorp.co.za  Wed Aug 12 04:45:51 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Wed, 12 Aug 2009 10:45:51 +0200
Subject: Social problems of Python doc [was Re: Python docs disappointing]
In-Reply-To: <0291a07d$0$20639$c3e8da3@news.astraweb.com>
References: 
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
Message-ID: <200908121045.51808.hendrik@microcorp.co.za>

On Tuesday 11 August 2009 19:53:16 Steven D'Aprano wrote:

> You want community input into the docs, but you're not willing to give
> that input except to bitch and moan and sook that the tracker is no good.

wtf does the verb  "sook" mean?

I find:

sook
??/s?k/ Show Spelled Pronunciation [sook] Show IPA
Use sook in a Sentence
?noun
1. 	Australia and New Zealand. a timid, cowardly person, esp. a young person; 
crybaby.
?interjection
2. 	Midland U.S. (used to summon cows from the pasture).
Origin:
1890?95; prob. from earlier sense ?calf reared by hand,? perh. suck(-calf), 
with sp. repr. N England, Scots pron. of suck (but earliest cited pron. of 
sook is (so?o?k))

Sometimes English drives me crazy.

- Hendrik


From andreengels at gmail.com  Wed Aug 12 04:54:05 2009
From: andreengels at gmail.com (Andre Engels)
Date: Wed, 12 Aug 2009 10:54:05 +0200
Subject: looping through values in a dictionary and appending to a list
In-Reply-To: <4A817D6B0200008C00014A9B@redhorse.forestry.uga.edu>
References: <4A817D6B0200008C00014A9B@redhorse.forestry.uga.edu>
Message-ID: <6faf39c90908120154p41ac5211p64d7378d7e908190@mail.gmail.com>

On Tue, Aug 11, 2009 at 8:17 PM, Krishna
Pacifici wrote:
> Nevermind,
> got it.
>
> Sorry.
>
>>>> Krishna Pacifici 08/11/09 2:12 PM >>>
> Hi,
> I want to append the values of a dictionary to a list.? I have a dictionary
> sec_dict_clean and I want to append the values to a list, but am having a
> hard time looping through the values in the dictionary.
>
> I have tried something like this:
> lista=[]
> for i in sec_dict_clean.values():
> ??? for j in sec_dict_clean.values()[i]:
> ??? ??? lista.append(sec_dict_clean.values()[i])
>
> But I keep on getting an error:
> TypeError: list indices must be integers
>
> Any ideas on how to loop through values in a dictionary?

lista=[]
for value in sec_dict_clean.values():
    lista.append(value)

but even simpler would be:

lista = sec_dict_clean.values()


-- 
Andr? Engels, andreengels at gmail.com


From hendrik at microcorp.co.za  Wed Aug 12 05:04:35 2009
From: hendrik at microcorp.co.za (Hendrik van Rooyen)
Date: Wed, 12 Aug 2009 11:04:35 +0200
Subject: Need cleanup advice for multiline string
In-Reply-To: <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
Message-ID: <200908121104.35744.hendrik@microcorp.co.za>

On Tuesday 11 August 2009 22:52:34 Robert Dailey wrote:
> On Aug 11, 3:40?pm, Bearophile  wrote:
> > Robert Dailey:
> > > This breaks the flow of scope. Would you guys solve this
> > > problem by moving failMsg into global scope?
> > > Perhaps through some other type of syntax?
> >
> > There are gals too here.
> > This may
> > help:http://docs.python.org/library/textwrap.html#textwrap.dedent
> >
> > Bye,
> > bearophile
>
> It's a figure of speech. And besides, why would I want programming
> advice from a woman? lol. Thanks for the help.

Well it may come as a surprise to you, but it was a woman who
wrote one of the first compilers.

She became an Admiral in the US navy as a result.

If I recall correctly, her name was Grace Hooper.

How many compilers have you written from scratch,
without a compiler to help you?

:-)

- Hendrik



From fzgillani at live.com  Wed Aug 12 05:29:58 2009
From: fzgillani at live.com (fakhar Gillani)
Date: Wed, 12 Aug 2009 11:29:58 +0200
Subject: loops for ffmpeg CLI in python
Message-ID: 


 

Hi,

 

I am a begineer in Python. Actually I am encoding video files with different bitrates using ffmpeg CLI. I wanted to ask you that how can I make loops so that I can vary the bitrates in the CLI of ffmpeg??

 

I want to bulid a loop for the command below where i just want to vary the -vb parameter i.e. 10M. 

 

ffmpeg.exe -i sample.avi -y -f h264 -vb 10M -r 25 encoded_1000_0-05.h264

 

I have tried to make simple loops but it doest work:(

 

Can anyone here help me out?

 

Regards,

Gillani

 

 

_________________________________________________________________
Share your memories online with anyone you want.
http://www.microsoft.com/middleeast/windows/windowslive/products/photos-share.aspx?tab=1
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 05:32:01 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 09:32:01 GMT
Subject: Unrecognized escape sequences in string literals
References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com>
	<0008e7c1$0$2880$c3e8da3@news.astraweb.com>
	
	
	<3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com>
	
	<0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com>
	
	<494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com>
Message-ID: 

On Tue, 11 Aug 2009 14:29:43 -0700, Douglas Alan wrote:

> I need to preface this entire post with the fact that I've already used
> ALL of the arguments that you've provided on my friend before I ever
> even came here with the topic, and my own arguments on why Python can be
> considered to be doing the right thing on this issue didn't even
> convince ME, much less him. When I can't even convince myself with an
> argument I'm making, then you know there's a problem with it!


I hear all your arguments, and to play Devil's Advocate I repeat them, 
and they don't convince me either. So by your logic, there's obviously a 
problem with your arguments as well!

That problem basically boils down to a deep-seated philosophical 
disagreement over which philosophy a language should follow in regard to 
backslash escapes:

"Anything not explicitly permitted is forbidden"

versus  

"Anything not explicitly forbidden is permitted"

Python explicitly permits all escape sequences, with well-defined 
behaviour, with the only ones forbidden being those explicitly forbidden:

* hex escapes with invalid hex digits;

* oct escapes with invalid oct digits;

* Unicode named escapes with unknown names;

* 16- and 32-bit Unicode escapes with invalid hex digits.

C++ apparently forbids all escape sequences, with unspecified behaviour 
if you use a forbidden sequence, except for a handful of explicitly 
permitted sequences.

That's not better, it's merely different.

Actually, that's not true -- that the C++ standard forbids a thing, but 
leaves the consequences of doing that thing unspecified, is clearly a Bad 
Thing.



[...]

>> Apart from the lack of warning, what actually is the difference between
>> Python's behavior and C++'s behavior?
> 
> That question makes just about as much sense as, "Apart from the lack of
> a fatal error, what actually is the difference between Python's behavior
> and C++'s?"

This is what I get:

[steve ~]$ cat test.cc
#include 
int main(int argc, char* argv[])
{
std::cout << "x\yz" << std::endl;
return 0;
}
[steve ~]$ g++ test.cc -o test
test.cc:4:14: warning: unknown escape sequence '\y'
[steve at soy ~]$ ./test
xyz


So on at least one machine in the world, C++ simply strips out 
backslashes that it doesn't recognise, leaving the suffix. Unfortunately, 
we can't rely on that, because C++ is underspecified. Fortunately this is 
not a problem with Python, which does completely specify the behaviour of 
escape sequences so there are no surprises. 



[...]

>> I disagree with your sense of aesthetics. I think that having to write
>> \\y when I want \y just to satisfy a bondage-and-discipline compiler is
>> ugly. That's not to deny that B&D isn't useful on occasion, but in this
>> case I believe the benefit is negligible, and so even a tiny cost is
>> not worth the pain.
> 
> EXPLICIT IS BETTER THAN IMPLICIT.

Quoting the Zen without understanding (especially shouting) doesn't 
impress anyone. There's nothing implicit about escape sequences. \y is 
perfectly explicit. Look Ma, there's a backslash, and a y, it gives a 
backslash and a y!

Implicit has an actual meaning. You shouldn't use it as a mere term of 
opprobrium for anything you don't like.



>> > (2) That argument disagrees with the Python reference manual, which
>> > explicitly states that "unrecognized escape sequences are left in the
>> > string unchanged", and that the purpose for doing so is because it
>> > "is useful when debugging".
>>
>> How does it disagree? \y in the source code mapping to \y in the string
>> object is the sequence being left unchanged. And the usefulness of
>> doing so is hardly a disagreement over the fact that it does so.
> 
> Because you've stated that "\y" is a legal escape sequence, while the
> Python Reference Manual explicitly states that it is an "unrecognized
> escape sequence", and that such "unrecognized escape sequences" are
> sources of bugs.

There's that reading comprehension problem again.

Unrecognised != illegal.

"Useful for debugging" != "source of bugs". If they were equal, we could 
fix an awful lot of bugs by throwing away our debugging tools.

Here's the URL to the relevant page:
http://www.python.org/doc/2.5.2/ref/strings.html

It seems to me that the behaviour the Python designers were looking to 
avoid was the case where the coder accidentally inserted a backslash in 
the wrong place, and the language stripped the backslash out, e.g.:

Wanted "a\bcd" but accidentally typed "ab\cd" instead, and got "abcd".

(This is what Bash does by design, and at least some C/C++ compilers do, 
perhaps by accident, perhaps by design.)

In that case, with no obvious backslash, the user may not even be aware 
that there was a problem:

s = "ab\cd"  # assume the backslash is silently discarded
assert len(s) == 4
assert s[3] == 'c'
assert '\\' not in s

All of these tests would wrongly pass, but with Python's behaviour of 
leaving the backslash in, they would all fail, and the string is visually 
distinctive (it has an obvious backslash in it).

Now, if you consider that \c should be an error, then obviously it would 
be even better if "ab\cd" would raise a SyntaxError. But why consider \c 
to be an error?



[invalid hex escape sequences]

>> > What makes it "illegal". As far as I can tell, it's just another
>> > "unrecognized escape sequence".
>>
>> No, it's recognized, because \x is the prefix for an hexadecimal escape
>> code. And it's illegal, because it's missing the actual hexadecimal
>> digits.
> 
> So? Why does that make it "illegal" rather than merely "unrecognized?"

Because the empty string is not a legal pair of hex digits.

In '\y', the suffix y is a legal character, but it isn't recognized as a 
"special" character.

In '\x', the suffix '' is not a pair of hex digits. Since hex-escapes are 
documented as requiring a pair of hex digits, this is an error.


[...]
> Because anyone with common sense will agree that "\y" is an illegal
> escape sequence. 

"No True Scotsman would design a language that behaves like that!!!!"

Why should it be illegal? It seems like a perfectly valid escape sequence 
to me, so long as the semantics are specified explicitly.



[...]

>> > It may not be a complex form of DWIMing, but it's still DWIMing a
>> > bit.  Python is figuring that if I typed "\z", then either I must
>> > have really meant to type "\\z",
>>
>> Nope, not in the least. Python NEVER EVER EVER tries to guess what you
>> mean.
> 
> Neither does Perl. That doesn't mean that Perl isn't often DWIMy.

Fine, but we're not discussing Perl, we're discussing Python. Perl's DWIM-
iness is irrelevant.



>> This is *exactly* like C++, except that in Python the semantics of \y
>> and \\y are identical. Python doesn't guess what you mean, it *imposes*
>> a meaning on the escape sequence. You just don't like that meaning.
> 
> That's because I don't like things that are ill-conceived.

And yet you like C++... go figure *wink*


-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 05:39:16 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 09:39:16 GMT
Subject: hashability
References: 
	
	
Message-ID: 

On Wed, 12 Aug 2009 00:33:01 -0700, James Stroud wrote:

> Tell that to two different machines on two different days. Then bet the
> life of yourself and your nearest and dearest family on that fact and
> see whether you really want to take a hash value for granted. 

As far as I know, Python doesn't make any guarantees about hashes being 
repeatable on different machines, different versions, or even different 
runs of the interpreter.


> If a
> property of the python language fails the "bet the lives of your nearest
> and dearest on a consistent result" test, I call it "ill defined" and,
> subjectively speaking, I prefer exceptions to be thrown--And, by damned,
> I'll throw them myself if I have to.
> 
> "If it saves one life, it's worth it all."

Depends on the life, and the cost. Would you pay a million dollars from 
your own pocket to save the life of a 119 year old with advanced lung 
cancer, a bad heart, and a raging infection of Ebola, from choking on a 
fish bone?

What if the effort of saving that one life kills two lives? Opportunity 
costs are costs too.




-- 
Steven


From steven at REMOVE.THIS.cybersource.com.au  Wed Aug 12 05:40:25 2009
From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 09:40:25 GMT
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	
Message-ID: 

On Wed, 12 Aug 2009 10:45:51 +0200, Hendrik van Rooyen wrote:

> On Tuesday 11 August 2009 19:53:16 Steven D'Aprano wrote:
> 
>> You want community input into the docs, but you're not willing to give
>> that input except to bitch and moan and sook that the tracker is no
>> good.
> 
> wtf does the verb  "sook" mean?
> 
> I find:
> 
> sook
> ??/s?k/ Show Spelled Pronunciation [sook] Show IPA
> Use sook in a Sentence
> ?noun
> 1. 	Australia and New Zealand. a timid, cowardly person, esp. a young
> person; crybaby.


That's the one. It's also used as a verb.




-- 
Steven


From python at mrabarnett.plus.com  Wed Aug 12 06:01:55 2009
From: python at mrabarnett.plus.com (MRAB)
Date: Wed, 12 Aug 2009 11:01:55 +0100
Subject: Need cleanup advice for multiline string
In-Reply-To: <200908121104.35744.hendrik@microcorp.co.za>
References: 	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
	<200908121104.35744.hendrik@microcorp.co.za>
Message-ID: <4A829313.5010709@mrabarnett.plus.com>

Hendrik van Rooyen wrote:
> On Tuesday 11 August 2009 22:52:34 Robert Dailey wrote:
>> On Aug 11, 3:40 pm, Bearophile  wrote:
>>> Robert Dailey:
>>>> This breaks the flow of scope. Would you guys solve this
>>>> problem by moving failMsg into global scope?
>>>> Perhaps through some other type of syntax?
>>> There are gals too here.
>>> This may
>>> help:http://docs.python.org/library/textwrap.html#textwrap.dedent
>>>
>>> Bye,
>>> bearophile
>> It's a figure of speech. And besides, why would I want programming
>> advice from a woman? lol. Thanks for the help.
> 
> Well it may come as a surprise to you, but it was a woman who
> wrote one of the first compilers.
> 
> She became an Admiral in the US navy as a result.
> 
> If I recall correctly, her name was Grace Hooper.
> 
Grace Hopper. The saying "It's easier to ask forgiveness than it is to
get permission" is attributed to her.

> How many compilers have you written from scratch,
> without a compiler to help you?
> 
> :-)
> 



From mdekauwe at gmail.com  Wed Aug 12 06:15:30 2009
From: mdekauwe at gmail.com (Martin)
Date: Wed, 12 Aug 2009 03:15:30 -0700 (PDT)
Subject: matching patterns after regex?
Message-ID: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com>

Hi,

I have a string (see below) and ideally I would like to pull out the
decimal number which follows the bounding coordinate information. For
example ideal from this string I would return...

s = '\nGROUP                  = ARCHIVEDMETADATA\n
GROUPTYPE            = MASTERGROUP\n\n  GROUP                  =
BOUNDINGRECTANGLE\n\n    OBJECT                 =
NORTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
VALUE                = 19.9999999982039\n    END_OBJECT             =
NORTHBOUNDINGCOORDINATE\n\n    OBJECT                 =
SOUTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
VALUE                = 9.99999999910197\n    END_OBJECT             =
SOUTHBOUNDINGCOORDINATE\n\n    OBJECT                 =
EASTBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
VALUE                = 10.6506458717851\n    END_OBJECT             =
EASTBOUNDINGCOORDINATE\n\n    OBJECT                 =
WESTBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
VALUE                = 4.3188348375893e-15\n    END_OBJECT
= WESTBOUNDINGCOORDINATE\n\n  END_GROUP


NORTHBOUNDINGCOORDINATE = 19.9999999982039
SOUTHBOUNDINGCOORDINATE = 9.99999999910197
EASTBOUNDINGCOORDINATE = 10.6506458717851
WESTBOUNDINGCOORDINATE = 4.3188348375893e-15

so far I have only managed to extract the numbers by doing re.findall
("[\d.]*\d", s), which returns

['1',
 '19.9999999982039',
 '1',
 '9.99999999910197',
 '1',
 '10.6506458717851',
 '1',
 '4.3188348375893',
 '15',
etc.

Now the first problem that I can see is that my string match chops off
the "e-15" part and I am not sure how to incorporate the potential for
that in my pattern match. Does anyone have any suggestions as to how I
could also match this? Ideally I would have a statement which printed
the number between the two bounding coordinate strings for example

NORTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
VALUE                = 19.9999999982039\n    END_OBJECT             =
NORTHBOUNDINGCOORDINATE\n\n

Something that matched "NORTHBOUNDINGCOORDINATE" and printed the
decimal number before it hit the next string
"NORTHBOUNDINGCOORDINATE". But I am not sure how to do this. any
suggestions would be appreciated.

Many thanks

Martin


From phd at phd.pp.ru  Wed Aug 12 06:24:53 2009
From: phd at phd.pp.ru (Oleg Broytmann)
Date: Wed, 12 Aug 2009 14:24:53 +0400
Subject: SQLObject 0.11.0
Message-ID: <20090812102452.GE5602@phd.pp.ru>

Hello!

I'm pleased to announce version 0.11.0, the first stable release of 0.11 branch
of SQLObject.


What is SQLObject
=================

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite,
Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB).


Where is SQLObject
==================

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.11.0

News and changes:
http://sqlobject.org/News.html


What's New
==========

News since 0.10
-----------------

Features & Interface
~~~~~~~~~~~~~~~~~~~~

* Dropped support for Python 2.3. The minimal version of Python for
  SQLObject is 2.4 now.

* Dropped support for PostgreSQL 7.2. The minimal supported version of
  PostgreSQL is 7.3 now.

* New magic attribute 'j' similar to 'q' was added that automagically does
  join with the other table in MultipleJoin or RelatedJoin.

* SQLObject can now create and drop a database in MySQL, PostgreSQL, SQLite
  and Firebird/Interbase.

* Added some support for schemas in PostgreSQL.

* Added DecimalStringCol - similar to DecimalCol but stores data as strings
  to work around problems in some drivers and type affinity problem in
  SQLite.

* Added sqlobject.include.hashcol.HashCol - a column type that automatically
  hashes anything going into it, and returns out an object that hashes
  anything being compared to itself. Basically, it's good for really simple
  one-way password fields, and it even supports the assignment of None to
  indicate no password set. By default, it uses the md5 library for
  hashing, but this can be changed in a HashCol definition.

* RowDestroyedSignal and RowUpdatedSignal were added.

Minor features
~~~~~~~~~~~~~~

* Use reversed() in manager/command.py instead of .__reversed__().

* Minor change in logging to console - logger no longer stores the output
  file, it gets the file from module sys every time by name; this means
  logging will use new sys.stdout (or stderr) in case the user changed
  them.

* Changed the order of testing of SQLite modules - look for external
  PySQLite2 before sqlite3.

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
     Oleg Broytmann            http://phd.pp.ru/            phd at phd.pp.ru
           Programmers don't die, they just GOSUB without RETURN.


From paul at boddie.org.uk  Wed Aug 12 06:32:08 2009
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 Aug 2009 03:32:08 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	
Message-ID: <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>

On 12 Aug, 09:58, Steven D'Aprano
 wrote:
>
> We know that there are problems. We've said repeatedly that corrections
> and patches are welcome. We've repeatedly told you how to communicate
> your answer to the question of what should be done. None of this is good
> enough for you. I don't know what else you expect.

Maybe the problem is that although everyone welcomes contributions and
changes (or says that they do), the mechanisms remain largely beyond
criticism. Consequently, one sees occasional laments about there not
being enough people contributing to Python core development and soul-
searching about the reasons this might be so. If it were insisted that
changes to, say, Wikipedia were to be proposed by submitting a patch
or report for perusal by the editors and for future inclusion in some
version of the project, the whole project would most likely be a
shadow of its current self, and ambitions of large-scale collaborative
editing in general would still be ridiculed.

A free-for-all isn't likely to be the best solution for more actively
edited Python documentation, but Wiki solutions undeniably provide a
superior "fast path" for edits by trusted users to be incorporated and
published in accessible end-user documentation. Almost every analysis
of the current (and previous) documentation mechanisms has identified
the editorial workflow as a bottleneck and then proceeded to replicate
such a bottleneck in any proposed solution. I'm starting to believe
that there's a certain snobbery about Wiki solutions which lead many
people to develop all sorts of short-term, arcane solutions under the
illusion that something super-special and customised is necessary and
that they have to start virtually from scratch in order to cater to
the ultra-special needs of the target audience; by the time they're
done, no-one's interested any more, except to propose the next legacy
system in the making.

[...]

> > That some of us choose to
> > invest it somewhere other than Python does not deprive of of our right
> > to point out problems in Python when we note them.
>
> Of course not. But it does mean that you won't be taken seriously, and
> you have no right to be taken seriously.

That's an absurd position that has soured the reputation of numerous
projects. When someone spends the time to write a bug report, they are
often investing as much time and effort in something that they are
able to in any productive sense. I make a habit of submitting bug
reports to software distributions, typically so that the people who
are responsible for the components involved can investigate the
problem effectively. When the maintainers just close such reports or
mark them with a number of different labels which mostly indicate that
they consider those reports not worth their time, it sends the message
that they consider their time to be vastly more important than their
users, even though their users might have set aside an hour of their
potentially busy schedule which might have meant sacrificing something
else that should have taken higher priority (like time for sleeping,
in my own personal experience). Thus, I've had the impression with
some projects that I should be maintaining all sorts of stuff - the
bootloader, the kernel, various desktop applications, Mozilla - all so
that stuff actually gets fixed and that I'm not perceived as just
another user whose bug reports aren't welcome. I don't find this
reasonable at all when in many cases there *are* people getting paid
to do these jobs.

The Python core developers seem more attentive than in various other
projects, but please let us not establish the "delicate genius"
mentality that has infested other projects to the point that any
criticism is automatically labelled as ungrateful whining by people
who supposedly don't use the software, have an axe to grind, and who
are apparent simpletons who don't understand the revolutionary vision
of the project leadership. If you think throwing away goodwill is an
acceptable way of silencing complaints, please take a look at just
about any article about KDE 4 that permits reader comments to see how
much goodwill can be lost and what effect that has on a project's
reputation.

Paul


From davea at ieee.org  Wed Aug 12 07:05:39 2009
From: davea at ieee.org (Dave Angel)
Date: Wed, 12 Aug 2009 07:05:39 -0400
Subject: adding multiple new values to the same key in a dictionary
In-Reply-To: <4A822900.7030008@ieee.org>
References: <4A8192A30200008C00014AB9@redhorse.forestry.uga.edu>
	<4A822900.7030008@ieee.org>
Message-ID: <4A82A203.6030408@ieee.org>

Dave Angel wrote:
> Krishna Pacifici wrote:
>> Hi,
>> I want to be able to add multiple new values to a key in a dictionary.
>>
>> I have tried the following:
>>
>> sec_dict_clean=
>> {88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85]}
>>
>> for i in range(len(sec_dict_clean.values())):
>>     for j in range(len(sec_dict_clean.values()[i])):
>>         
>> sec_dict_clean.setdefault(key,[]).append(blocks[sec_dict_clean.values()[i][j]].abundance) 
>>
>>
>> where blocks[...].abundance gives me a single value from an object,
>>
>> but this gives me the following:
>>
>> sec_dict_clean=
>> {88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 
>> 85, 4, 12, 11, 6, 9, 12, 11, 7, 10, 10, 12, 9, 6, 12, 15, 9, 8, 12, 
>> 15, 12, 12]}
>>
>> instead I want each abundance (starts with 4, 12...) to be associated 
>> with each of the values so that it would look like this:
>>
>> sec_dict_clean=
>> {88: ([87, 89, 78, 98], [4,12,11,6]), 58: ([57, 59, 48, 68], 
>> [9,12,11,7]), 69: ([79], [10])...}
>>
>> You can see there are several errors here (I have more things being 
>> appended than there are values in the dictionary), but I really just 
>> want to know how to add multiple values to the same key in a dictionary.
>>
>> Thanks for any help,
>> Krishna
>>
>>
>>
>>   
> You're really distorting the purposes of both dictionary and list 
> here.  It makes your code totally unreadable, which makes it hard to 
> write, and hard to debug.
>
> A dictionary is a mapping between key and value, where each key has 
> exactly one value.  You cannot add another one to it.   All you can do 
> is make the value something which is itself a collection.  Now, your 
> desired dictionary looks achievable, almost.  If you change the parens 
> (tuple) to square brackets (list), then it'll work.
>    So key 88 has a single value, which is a list of two items.  Each 
> of those items is itself a list with 4 items.  And each of those items 
> are integers.
>
> But then I got bogged down in your sample code.  I tried to simplify 
> it, replacing the first two lines with these three:
>
> for i, key in enumerate(sec_dict_clean):
>    val = sec_dict_clean[key]
>    for j, xxx in enumerate(val):
>        
> ???sec_dict_clean.setdefault(key,[]).append(blocks[sec_dict_clean.values()[i][j]].abundance) 
>
>
> But I can't make head nor tail of the third line.  You didn't have a 
> variable key, so I don't know if I'm using the same one..  Since I 
> can't figure out what you were trying to do, I can't see how to fix it.
>
> I think the problem here is you're trying to reorganize the data as 
> well as adding to it, in a single pass.  So is some previous code 
> generating the dictionary incorrectly, and instead of fixing that, 
> you're trying to reorganize it here?
>
> To make each dictionary value a list of lists:
>
> sec_dict_clean=
> {88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85]}
>
> for key in sec_dict_clean:
>    sec_dict_clean[key] = [sec_dict_clean[key]]
>
> now,  the dict looks like:
> {88: [[87, 89, 78, 98, 3]], 58: [[57, 59, 48, 68]], 69: [[79]], 95: 
> [[94, 96, 85]]}
>
> At this point, if you have some interesting data to add to it, you can 
> just append a new list to
>     dict[key]
>
> In an earlier message, you mentioned fields a and b, and assuming this 
> is a similar problem, it would seem that 87 is somehow associated with 
> 4, and 89 with 12, and so on.  If that's the case, perhaps your 
> desired final structure might look more like:
>
> {88: [[87,4], [89,12], [78, 11],[98, 6],   58: [[57, 9], [59, 12], 
> [48, 11], [68, 7]],   69: ...}
>
>
> In this case, the structure is entirely different.  But the approach 
> is the same.  And at least you'd be getting closer to the object 
> approach where  [87,4] is replaced by an object of some type.
>
> BTW, please don't top-post.  When you reply to this one, put your 
> reply at the end, or sometimes interspersed.  But if you put it at the 
> beginning, it's out of order.
>
> DaveA
>
>
>
>
Look at the following (tested in Python 2.6.2).,  There are a number of 
things that could be cleaner, mainly the names of things.  I should 
never be calling something "value" unless it's a very generic routine.


class Sample(object):
    def __init__(self, mainval):
        self.mainval = mainval
        self.a = self.b = None
    def set_tags(self, a, b):
        self.a = a
        self.b = b
    def __repr__(self):
        return "<" + str(self.mainval) + " a=" + str(self.a) + " b=" + 
str(self.b) + ">"


diction2 = {88: [Sample(87), Sample(89), Sample(98), Sample(3)],
            58: [Sample(57), Sample(59), Sample(48), Sample(68)],
            69: [Sample(79)]
                 }

print diction2

for key, valuelist in diction2.iteritems():
    for item in valuelist:
        item.set_tags(12, 106)             #here's where you'd be using 
that mysterious blocks dictionary

print diction2



DaveA


From andrew at acooke.org  Wed Aug 12 07:49:06 2009
From: andrew at acooke.org (andrew cooke)
Date: Wed, 12 Aug 2009 04:49:06 -0700 (PDT)
Subject: Frustrated with scopes
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
	
Message-ID: 

On Aug 12, 1:51?am, James Stroud 
wrote:
> andrew cooke wrote:
> > Is there a way to make this work (currently scope and join are
> > undefined at runtime when the inner class attributes are defined):
>
> > class _StreamFactory(object):
>
> > ? ? @staticmethod
> > ? ? def __call__(lines, source, join=''.join):
>
> > ? ? ? ? class Line(object):
>
> > ? ? ? ? ? ? __source = source
> > ? ? ? ? ? ? __join = join
> > [...]
>
> It would be helpful if you were to describe the type of behavior you expect.

Sorry, I didn't make myself clear.  When run the code gives
 NameError: name 'source' is not defined
because the class namespace blocks the function namespace (or
something...).

Andrew


From andrew at acooke.org  Wed Aug 12 07:51:37 2009
From: andrew at acooke.org (andrew cooke)
Date: Wed, 12 Aug 2009 04:51:37 -0700 (PDT)
Subject: Frustrated with scopes
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
	
	
Message-ID: <4288a429-c7be-47a5-be06-7a53879d1767@w6g2000yqw.googlegroups.com>

On Aug 12, 7:49?am, andrew cooke  wrote:
> On Aug 12, 1:51?am, James Stroud 
> wrote:
>
>
>
> > andrew cooke wrote:
> > > Is there a way to make this work (currently scope and join are
> > > undefined at runtime when the inner class attributes are defined):
>
> > > class _StreamFactory(object):
>
> > > ? ? @staticmethod
> > > ? ? def __call__(lines, source, join=''.join):
>
> > > ? ? ? ? class Line(object):
>
> > > ? ? ? ? ? ? __source = source
> > > ? ? ? ? ? ? __join = join
> > > [...]
>
> > It would be helpful if you were to describe the type of behavior you expect.
>
> Sorry, I didn't make myself clear. ?When run the code gives
> ?NameError: name 'source' is not defined
> because the class namespace blocks the function namespace (or
> something...).

ie when the __call__ method is invoked on an instance of
_StreamFactory.

> Andrew



From bernard.chhun at gmail.com  Wed Aug 12 07:53:19 2009
From: bernard.chhun at gmail.com (Bernard)
Date: Wed, 12 Aug 2009 04:53:19 -0700 (PDT)
Subject: matching patterns after regex?
References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com>
Message-ID: <2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com>

On 12 ao?t, 06:15, Martin  wrote:
> Hi,
>
> I have a string (see below) and ideally I would like to pull out the
> decimal number which follows the bounding coordinate information. For
> example ideal from this string I would return...
>
> s = '\nGROUP ? ? ? ? ? ? ? ? ?= ARCHIVEDMETADATA\n
> GROUPTYPE ? ? ? ? ? ?= MASTERGROUP\n\n ?GROUP ? ? ? ? ? ? ? ? ?=
> BOUNDINGRECTANGLE\n\n ? ?OBJECT ? ? ? ? ? ? ? ? =
> NORTHBOUNDINGCOORDINATE\n ? ? ?NUM_VAL ? ? ? ? ? ? ?= 1\n
> VALUE ? ? ? ? ? ? ? ?= 19.9999999982039\n ? ?END_OBJECT ? ? ? ? ? ? =
> NORTHBOUNDINGCOORDINATE\n\n ? ?OBJECT ? ? ? ? ? ? ? ? =
> SOUTHBOUNDINGCOORDINATE\n ? ? ?NUM_VAL ? ? ? ? ? ? ?= 1\n
> VALUE ? ? ? ? ? ? ? ?= 9.99999999910197\n ? ?END_OBJECT ? ? ? ? ? ? =
> SOUTHBOUNDINGCOORDINATE\n\n ? ?OBJECT ? ? ? ? ? ? ? ? =
> EASTBOUNDINGCOORDINATE\n ? ? ?NUM_VAL ? ? ? ? ? ? ?= 1\n
> VALUE ? ? ? ? ? ? ? ?= 10.6506458717851\n ? ?END_OBJECT ? ? ? ? ? ? =
> EASTBOUNDINGCOORDINATE\n\n ? ?OBJECT ? ? ? ? ? ? ? ? =
> WESTBOUNDINGCOORDINATE\n ? ? ?NUM_VAL ? ? ? ? ? ? ?= 1\n
> VALUE ? ? ? ? ? ? ? ?= 4.3188348375893e-15\n ? ?END_OBJECT
> = WESTBOUNDINGCOORDINATE\n\n ?END_GROUP
>
> NORTHBOUNDINGCOORDINATE = 19.9999999982039
> SOUTHBOUNDINGCOORDINATE = 9.99999999910197
> EASTBOUNDINGCOORDINATE = 10.6506458717851
> WESTBOUNDINGCOORDINATE = 4.3188348375893e-15
>
> so far I have only managed to extract the numbers by doing re.findall
> ("[\d.]*\d", s), which returns
>
> ['1',
> ?'19.9999999982039',
> ?'1',
> ?'9.99999999910197',
> ?'1',
> ?'10.6506458717851',
> ?'1',
> ?'4.3188348375893',
> ?'15',
> etc.
>
> Now the first problem that I can see is that my string match chops off
> the "e-15" part and I am not sure how to incorporate the potential for
> that in my pattern match. Does anyone have any suggestions as to how I
> could also match this? Ideally I would have a statement which printed
> the number between the two bounding coordinate strings for example
>
> NORTHBOUNDINGCOORDINATE\n ? ? ?NUM_VAL ? ? ? ? ? ? ?= 1\n
> VALUE ? ? ? ? ? ? ? ?= 19.9999999982039\n ? ?END_OBJECT ? ? ? ? ? ? =
> NORTHBOUNDINGCOORDINATE\n\n
>
> Something that matched "NORTHBOUNDINGCOORDINATE" and printed the
> decimal number before it hit the next string
> "NORTHBOUNDINGCOORDINATE". But I am not sure how to do this. any
> suggestions would be appreciated.
>
> Many thanks
>
> Martin

Hey Martin,

here's a regex I've just tested : (\w+COORDINATE).*\s+VALUE\s+=\s([\d\.
\w-]+)

the first match corresponds to the whateverBOUNDINGCOORDINATE and the
second match is the value.

please provide some more entries if you'd like me to test my regex
some more :)

cheers

Bernard


From steve at REMOVE-THIS-cybersource.com.au  Wed Aug 12 08:08:40 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 12:08:40 GMT
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	
	<7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>
Message-ID: <0292a134$0$20647$c3e8da3@news.astraweb.com>

On Wed, 12 Aug 2009 03:32:08 -0700, Paul Boddie wrote:

> On 12 Aug, 09:58, Steven D'Aprano
>  wrote:
>>
>> We know that there are problems. We've said repeatedly that corrections
>> and patches are welcome. We've repeatedly told you how to communicate
>> your answer to the question of what should be done. None of this is
>> good enough for you. I don't know what else you expect.
> 
> Maybe the problem is that although everyone welcomes contributions and
> changes (or says that they do), the mechanisms remain largely beyond
> criticism. Consequently, one sees occasional laments about there not
> being enough people contributing to Python core development and soul-
> searching about the reasons this might be so. If it were insisted that
> changes to, say, Wikipedia were to be proposed by submitting a patch or
> report for perusal by the editors and for future inclusion in some
> version of the project, the whole project would most likely be a shadow
> of its current self, and ambitions of large-scale collaborative editing
> in general would still be ridiculed.

If Python had the tens of thousands of users, and hundreds of trusted 
(for some definition of trusted) editors, then Python could run using the 
same model as Wikipedia. The Wikipedia model is great, and I contribute 
to it myself.

But Wikipedia gets its users from the entire population of web-users, 
because there's something of interest to everyone in Wikipedia. 
Interested in movies? There are Wikipedia pages for you to contribute to. 
Interested in medicine? There are pages you can help with. Interested in 
the history and development of the mechanical pencil? There's probably 
even a page for you. And if there isn't, you can create one.

With tens of millions of web users, it's no surprise that Wikipedia can 
attract thousands of editors. But this does not apply to Python, which 
starts from a comparatively tiny population, primarily those interested 
in Python. Have a look at the Wikipedia page for Python. The Talk Page 
has comments from no more than *eight* people. The History stats suggest 
that, over seven years, only sixty-nine people have made more than a 
single edit to the page, most of them having made just two edits. Just 36 
people have made more than two edits, and some of those are bots. Only 
one user, Lulu of the Lotus-Eaters (David Mertz), has made more than 100 
edits.


> A free-for-all isn't likely to be the best solution for more actively
> edited Python documentation, but Wiki solutions undeniably provide a
> superior "fast path" for edits by trusted users to be incorporated and
> published in accessible end-user documentation. 

And the Python time-machine strikes again:

http://wiki.python.org/moin/


>> > That some of us choose to
>> > invest it somewhere other than Python does not deprive of of our
>> > right to point out problems in Python when we note them.
>>
>> Of course not. But it does mean that you won't be taken seriously, and
>> you have no right to be taken seriously.
> 
> That's an absurd position that has soured the reputation of numerous
> projects. When someone spends the time to write a bug report, they are
> often investing as much time and effort in something that they are able
> to in any productive sense. 

Firstly, in context, I wasn't talking to somebody who had made bug 
reports. I was talking to somebody whose only contribution, as near as I 
can tell, was to loudly complain that there are flaws in the Python 
documentation and insist that somebody else should fix them just the way 
he wants them fixed -- without being willing to even explain how he wants 
them fixed. Possibly the developers are expected to intuit from first 
principles what he wants.

Secondly, the world is full of complainers who won't lift a finger to 
help but demand others help them. It may be unfair to tar everybody with 
the same brush, but life is to short and time to valuable to avoid making 
judgements as to who to pay attention to. Those who invest a lot of 
effort into providing patches get listened to closely; so do those who 
make good quality detailed bug reports. Those who just say "It's broken, 
fix it" don't. Sometimes that will mean that someone with genuinely good 
ideas will be ignored, but that's the price one pays for avoiding being 
drowned by a chorus of trivial, contradictory, vague and insubstantial 
complaints.

If the Python Dev team paid attention to every post here claiming that 
Python "has a bug" when the bug was actually in the complainant's own 
code, we'd probably still be running Python 1.5.


> I make a habit of submitting bug reports to
> software distributions, typically so that the people who are responsible
> for the components involved can investigate the problem effectively.
> When the maintainers just close such reports or mark them with a number
> of different labels which mostly indicate that they consider those
> reports not worth their time, it sends the message that they consider
> their time to be vastly more important than their users, even though
> their users might have set aside an hour of their potentially busy
> schedule which might have meant sacrificing something else that should
> have taken higher priority (like time for sleeping, in my own personal
> experience).

Oh dear me. You mean that they don't agree that YOUR time is more 
important than theirs??? What horrible people they must be, to expect you 
to sacrifice some of your sleep time just so *they* can get some sleep 
themselves!!! Who do they think they are???



-- 
Steven


From deets at nospam.web.de  Wed Aug 12 08:12:14 2009
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Wed, 12 Aug 2009 14:12:14 +0200
Subject: Frustrated with scopes
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
	
	
	<4288a429-c7be-47a5-be06-7a53879d1767@w6g2000yqw.googlegroups.com>
Message-ID: <7efpsuF2fvcq5U1@mid.uni-berlin.de>

andrew cooke wrote:

> On Aug 12, 7:49?am, andrew cooke  wrote:
>> On Aug 12, 1:51?am, James Stroud 
>> wrote:
>>
>>
>>
>> > andrew cooke wrote:
>> > > Is there a way to make this work (currently scope and join are
>> > > undefined at runtime when the inner class attributes are defined):
>>
>> > > class _StreamFactory(object):
>>
>> > > @staticmethod
>> > > def __call__(lines, source, join=''.join):
>>
>> > > class Line(object):
>>
>> > > __source = source
>> > > __join = join
>> > > [...]
>>
>> > It would be helpful if you were to describe the type of behavior you
>> > expect.
>>
>> Sorry, I didn't make myself clear. ?When run the code gives
>> NameError: name 'source' is not defined
>> because the class namespace blocks the function namespace (or
>> something...).
> 
> ie when the __call__ method is invoked on an instance of
> _StreamFactory.

But you can refer to the arguments if you don't insist on setting them as
class-attributes:




def factory(foo, bar):

    class A(object):

        def do_something(self):
            print foo, bar

    return A()

a = factory(10, 20)
a.do_something()



Diez


From mdekauwe at gmail.com  Wed Aug 12 08:12:22 2009
From: mdekauwe at gmail.com (Martin)
Date: Wed, 12 Aug 2009 05:12:22 -0700 (PDT)
Subject: matching patterns after regex?
References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com>
	<2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com>
Message-ID: 

On Aug 12, 12:53 pm, Bernard  wrote:
> On 12 ao?t, 06:15, Martin  wrote:
>
>
>
> > Hi,
>
> > I have a string (see below) and ideally I would like to pull out the
> > decimal number which follows the bounding coordinate information. For
> > example ideal from this string I would return...
>
> > s = '\nGROUP                  = ARCHIVEDMETADATA\n
> > GROUPTYPE            = MASTERGROUP\n\n  GROUP                  =
> > BOUNDINGRECTANGLE\n\n    OBJECT                 =
> > NORTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> > VALUE                = 19.9999999982039\n    END_OBJECT             =
> > NORTHBOUNDINGCOORDINATE\n\n    OBJECT                 =
> > SOUTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> > VALUE                = 9.99999999910197\n    END_OBJECT             =
> > SOUTHBOUNDINGCOORDINATE\n\n    OBJECT                 =
> > EASTBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> > VALUE                = 10.6506458717851\n    END_OBJECT             =
> > EASTBOUNDINGCOORDINATE\n\n    OBJECT                 =
> > WESTBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> > VALUE                = 4.3188348375893e-15\n    END_OBJECT
> > = WESTBOUNDINGCOORDINATE\n\n  END_GROUP
>
> > NORTHBOUNDINGCOORDINATE = 19.9999999982039
> > SOUTHBOUNDINGCOORDINATE = 9.99999999910197
> > EASTBOUNDINGCOORDINATE = 10.6506458717851
> > WESTBOUNDINGCOORDINATE = 4.3188348375893e-15
>
> > so far I have only managed to extract the numbers by doing re.findall
> > ("[\d.]*\d", s), which returns
>
> > ['1',
> >  '19.9999999982039',
> >  '1',
> >  '9.99999999910197',
> >  '1',
> >  '10.6506458717851',
> >  '1',
> >  '4.3188348375893',
> >  '15',
> > etc.
>
> > Now the first problem that I can see is that my string match chops off
> > the "e-15" part and I am not sure how to incorporate the potential for
> > that in my pattern match. Does anyone have any suggestions as to how I
> > could also match this? Ideally I would have a statement which printed
> > the number between the two bounding coordinate strings for example
>
> > NORTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> > VALUE                = 19.9999999982039\n    END_OBJECT             =
> > NORTHBOUNDINGCOORDINATE\n\n
>
> > Something that matched "NORTHBOUNDINGCOORDINATE" and printed the
> > decimal number before it hit the next string
> > "NORTHBOUNDINGCOORDINATE". But I am not sure how to do this. any
> > suggestions would be appreciated.
>
> > Many thanks
>
> > Martin
>
> Hey Martin,
>
> here's a regex I've just tested : (\w+COORDINATE).*\s+VALUE\s+=\s([\d\.
> \w-]+)
>
> the first match corresponds to the whateverBOUNDINGCOORDINATE and the
> second match is the value.
>
> please provide some more entries if you'd like me to test my regex
> some more :)
>
> cheers
>
> Bernard

Thanks Bernard it doesn't seem to be working for me...

I tried

re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)

is that what you meant? Apologies if not, that results in a syntax
error:

In [557]: re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)
------------------------------------------------------------
   File "", line 1
     re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)
                                                              ^
SyntaxError: unexpected character after line continuation character

Thanks





From steve at REMOVE-THIS-cybersource.com.au  Wed Aug 12 08:20:26 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 12:20:26 GMT
Subject: Frustrated with scopes
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
	
	
Message-ID: <0292a3f6$0$20647$c3e8da3@news.astraweb.com>

On Wed, 12 Aug 2009 04:49:06 -0700, andrew cooke wrote:

>> It would be helpful if you were to describe the type of behavior you
>> expect.
> 
> Sorry, I didn't make myself clear.  When run the code gives
>  NameError: name 'source' is not defined
> because the class namespace blocks the function namespace (or
> something...).

James asked you to describe the behaviour you expect. Please explain what 
you expect, and what you actually get. Post the ACTUAL error message, not 
a summary, not a paraphrase, but an actual copy and paste.


In any case, your code snippet works for me:


>>> class _StreamFactory(object):
...     @staticmethod
...     def __call__(lines, source, join=''.join):
...         class Line(object):
...             __source = source
...             __join = join
...
>>> obj = _StreamFactory()
>>> obj(['a', 'b'], "ab")
>>>

No errors. Of course it doesn't return anything, because your code 
snippet doesn't return anything either. Here's a modified version which 
returns the inner class:

>>> class _StreamFactory2(object):
...     @staticmethod
...     def __call__(lines, source, join=''.join):
...         class Line(object):
...             __source = source
...             __join = join
...         return Line
...
>>> obj = _StreamFactory2()
>>> K = obj(['a', 'b'], "ab")
>>> K

>>> K._Line__source
'ab'


Works perfectly. I suspect your error is probably something like you have 
misspelled "source" somewhere.


-- 
Steven


From steve at REMOVE-THIS-cybersource.com.au  Wed Aug 12 08:23:25 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 12:23:25 GMT
Subject: matching patterns after regex?
References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com>
	<2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com>
	
Message-ID: <0292a4a9$0$20647$c3e8da3@news.astraweb.com>

On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote:

> I tried
> 
> re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)

You need to put quotes around strings.

In this case, because you're using regular expressions, you should use a 
raw string:

re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)

will probably work.





-- 
Steven


From solipsis at pitrou.net  Wed Aug 12 08:37:15 2009
From: solipsis at pitrou.net (Antoine Pitrou)
Date: Wed, 12 Aug 2009 12:37:15 +0000 (UTC)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	
	<7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>
Message-ID: 

Paul Boddie  boddie.org.uk> writes:
> 
> A free-for-all isn't likely to be the best solution for more actively
> edited Python documentation, but Wiki solutions undeniably provide a
> superior "fast path" for edits by trusted users to be incorporated and
> published in accessible end-user documentation.

Agreed.

> I'm starting to believe
> that there's a certain snobbery about Wiki solutions which lead many
> people to develop all sorts of short-term, arcane solutions under the
> illusion that something super-special and customised is necessary and
> that they have to start virtually from scratch in order to cater to
> the ultra-special needs of the target audience; by the time they're
> done, no-one's interested any more, except to propose the next legacy
> system in the making.

Not sure why you think it's snobbery... There are certain tacit expectations
regarding the docs:
- that they are versioned with the source tree (because, often, changes in
documentation will be synchronized with changes in behaviour / functionality, 
because we must maintain documentation for several versions at once, because you
want to use the same kind of merging that is used between different branches)
- that they can be used offline, rebuilt in different formats, etc.
- that you don't need a Web server (even locally) to navigate through them
- that proposed changes are to be reviewed by maintainers (core developers)
before they get actually committed

I'm not sure of any existing wiki system which fits the bill. So, while I agree
that the current situation can present a high threshold for occasional doc-only
contributions, there doesn't seem to be a simple solution to improve things.




From mdekauwe at gmail.com  Wed Aug 12 08:42:52 2009
From: mdekauwe at gmail.com (Martin)
Date: Wed, 12 Aug 2009 05:42:52 -0700 (PDT)
Subject: matching patterns after regex?
References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com>
	<2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com> 
	 
	<0292a4a9$0$20647$c3e8da3@news.astraweb.com>
Message-ID: <18d5d342-b678-4101-a284-24d6176ac856@v20g2000yqm.googlegroups.com>

On Aug 12, 1:23 pm, Steven D'Aprano  wrote:
> On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote:
> > I tried
>
> > re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)
>
> You need to put quotes around strings.
>
> In this case, because you're using regular expressions, you should use a
> raw string:
>
> re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)
>
> will probably work.
>
> --
> Steven

Thanks I see.

so I tried it and if I use it as it is, it matches the first instance:
I
n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)
Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')]

So I adjusted the first part of the regex, on the basis I could sub
NORTH for SOUTH etc.

In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\.
\w-]+)",s)
Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')]

But in both cases it doesn't return the decimal value rather the value
that comes after NUM_VAL = , rather than VALUE = ?




From davea at ieee.org  Wed Aug 12 08:52:50 2009
From: davea at ieee.org (Dave Angel)
Date: Wed, 12 Aug 2009 08:52:50 -0400
Subject: Frustrated with scopes
In-Reply-To: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
Message-ID: <4A82BB22.3080709@ieee.org>

andrew cooke wrote:
> Is there a way to make this work (currently scope and join are
> undefined at runtime when the inner class attributes are defined):
>
> class _StreamFactory(object):
>
>     @staticmethod
>     def __call__(lines, source, join=''.join):
>
>         class Line(object):
>
>             __source = source
>             __join = join
> [...]
>
> I can get something working by bouncing through global values, but it
> looks awful and I think it's a source of a bug due too values being
> redefined.
>
> Thanks,
> Andrew
>
>   
Supply us with just enough source code to actually try it, give the full 
error message including traceback, and tell us what you expected to 
see.  Also tell us Python version   (sys.version)

So far you've done none of these.  When I try the following, I get no 
errors, using Python 2.6.2


class _StreamFactory(object):

    @staticmethod
    def __call__(lines, source, join=''.join):

        class Line(object):

            __source = source
            __join = join
        return Line()


fact = _StreamFactory()
obj = fact(43, "name.txt")
print obj




From davea at ieee.org  Wed Aug 12 08:52:50 2009
From: davea at ieee.org (Dave Angel)
Date: Wed, 12 Aug 2009 08:52:50 -0400
Subject: Frustrated with scopes
In-Reply-To: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
Message-ID: <4A82BB22.3080709@ieee.org>

andrew cooke wrote:
> Is there a way to make this work (currently scope and join are
> undefined at runtime when the inner class attributes are defined):
>
> class _StreamFactory(object):
>
>     @staticmethod
>     def __call__(lines, source, join=''.join):
>
>         class Line(object):
>
>             __source = source
>             __join = join
> [...]
>
> I can get something working by bouncing through global values, but it
> looks awful and I think it's a source of a bug due too values being
> redefined.
>
> Thanks,
> Andrew
>
>   
Supply us with just enough source code to actually try it, give the full 
error message including traceback, and tell us what you expected to 
see.  Also tell us Python version   (sys.version)

So far you've done none of these.  When I try the following, I get no 
errors, using Python 2.6.2


class _StreamFactory(object):

    @staticmethod
    def __call__(lines, source, join=''.join):

        class Line(object):

            __source = source
            __join = join
        return Line()


fact = _StreamFactory()
obj = fact(43, "name.txt")
print obj




From paul at boddie.org.uk  Wed Aug 12 09:24:18 2009
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 Aug 2009 06:24:18 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	
	<7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>
	<0292a134$0$20647$c3e8da3@news.astraweb.com>
Message-ID: <3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com>

On 12 Aug, 14:08, Steven D'Aprano  wrote:
>
> With tens of millions of web users, it's no surprise that Wikipedia can
> attract thousands of editors. But this does not apply to Python, which
> starts from a comparatively tiny population, primarily those interested
> in Python. Have a look at the Wikipedia page for Python.

What does the Python entry on Wikipedia have to do with editing the
Python documentation in a Wiki? Once everyone has agreed that the
description of Python on Wikipedia is reasonable, there's not much
point in editing it, is there? In contrast, there's a continuous
stream of people who don't think Python's documentation is that great.

[...]

> > A free-for-all isn't likely to be the best solution for more actively
> > edited Python documentation, but Wiki solutions undeniably provide a
> > superior "fast path" for edits by trusted users to be incorporated and
> > published in accessible end-user documentation.
>
> And the Python time-machine strikes again:
>
> http://wiki.python.org/moin/

And I suggested that the complainants use it as a starting point.

[...]

> Oh dear me. You mean that they don't agree that YOUR time is more
> important than theirs??? What horrible people they must be, to expect you
> to sacrifice some of your sleep time just so *they* can get some sleep
> themselves!!! Who do they think they are???

That's quite an attempt to make my position more extreme than it
actually is. I get people asking me to improve my own software, you
know, and even if I don't have the time or inclination to do what they
ask, I do spend time discussing it with them. Such people, including
myself when I'm on the other side of the fence, appreciate more than
just a brush-off and no: they don't insist that their own time be
valued above anyone else's (as you would have me misrepresented); they
just ask that their own efforts aren't treated as having no value
because they're not part of the "elite" development team. You get
various projects doing soul-searching about embracing the efforts of
non-programmers, and the first port of call on that particular voyage
is to not treat them like idiot consumers whose remarks can only be
considered as mere heckling while the visionaries act out their
flawless production.

Paul

P.S. The mention of "social problems" ties in with other remarks made
recently, and I've increasingly found it more trouble than has been
worthwhile to pursue Python-related matters of late. When one tries to
encourage people to participate in improving various things, which
usually means the community having to accept a degree of criticism,
people claim that it's encouraging "undesirable" influences to point
such critics in the right direction instead of showing them the door.
When one tries to pursue such improvement matters oneself, people
always have something to say about the choice of technology or whether
they like the particular background colour being used or indeed have
an opinion, typically shallow and negative, about anything but the
task at hand, and there'll always be someone queuing up to dismantle
anything that does get done at the first opportunity. In contrast,
I've found other groups of people to be grateful for even modest
technical assistance, and I know that such people are much more likely
to get my support and input in the future than those who think that
it's some kind of advantage to have potential contributors run the
gauntlet of denial (that there are structural problems in their
project), skepticism (that newcomers can have anything to contribute),
discouragement (because any solution which doesn't validate someone's
technology preferences must be criticised) and, indeed, outright
hostility.

One can always spend one's time doing something which isn't 100%
enjoyable or 100% rewarding if one feels that the time is still being
spent on something worthwhile. I'm getting the feeling that lots of
Python-related stuff doesn't quite satisfy such criteria any more.


From jeanmichel at sequans.com  Wed Aug 12 09:27:49 2009
From: jeanmichel at sequans.com (Jean-Michel Pichavant)
Date: Wed, 12 Aug 2009 15:27:49 +0200
Subject: Need cleanup advice for multiline string
In-Reply-To: <8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com>
References: 	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com>
Message-ID: <4A82C355.8080304@sequans.com>

Simon Brunning wrote:
> 2009/8/11 Robert Dailey :
>   
>> On Aug 11, 3:40 pm, Bearophile  wrote:
>>     
>>> There are gals too here.
>>>       
>> It's a figure of speech. And besides, why would I want programming
>> advice from a woman? lol. Thanks for the help.
>>     
>
> Give the attitudes still prevalent in our industry (cf
>  and many more), I'm sorry to say that I
> don't think this is funny.
>
>   
Having someone present technical informations with porn content cannot 
be qualified as "prevalent in our industry". I would even dare to say 
this is the opposite, it is almost unique.
I would also add that Robert was very far from this attitude, I consider 
his joke as a friendly tickle, not a male chauvinist aggression. I'm no 
women, but I'm sure they are as capable as me, not to say more, of 
making the distinction.

It has been said this list is not very friendly to newbies, let's not 
make it hostile to gentle jokes (even those not funny) when thanking 
helpers.

JM




From andrew at acooke.org  Wed Aug 12 09:47:38 2009
From: andrew at acooke.org (andrew cooke)
Date: Wed, 12 Aug 2009 06:47:38 -0700 (PDT)
Subject: Frustrated with scopes
References: <28f6f8e1-2689-4ff3-b453-e6c8859d2c43@26g2000yqk.googlegroups.com>
	
Message-ID: <3bf15201-afc3-4fb4-9a99-ee2966c4da61@g31g2000yqc.googlegroups.com>

On Aug 12, 8:52?am, Dave Angel  wrote:
> Supply us with just enough source code to actually try it, give the full
> error message including traceback, and tell us what you expected to
> see. ?Also tell us Python version ? (sys.version)
>
> So far you've done none of these. ?When I try the following, I get no
> errors, using Python 2.6.2
>
> class _StreamFactory(object):
>
> ? ? @staticmethod
> ? ? def __call__(lines, source, join=''.join):
>
> ? ? ? ? class Line(object):
>
> ? ? ? ? ? ? __source = source
> ? ? ? ? ? ? __join = join
> ? ? ? ? return Line()
>
> fact = _StreamFactory()
> obj = fact(43, "name.txt")
> print obj

Ah!  OK, thanks for that.  I need to look at this again.  I'll post
again if necessary, but if it works for you then I clearly don't
understand what the issue is myself.

Andrew


From ebonak at hotmail.com  Wed Aug 12 09:58:09 2009
From: ebonak at hotmail.com (Esmail)
Date: Wed, 12 Aug 2009 09:58:09 -0400
Subject: best practice for documenting a project? pydoc?
Message-ID: 

Hello,

A project that I have been working on is getting larger
and more complex, and I would like to unload some of the
information from my memory/head to some other media (a
set of web pages?). I am primarily interested in documenting
the classes/methods.

This documentation is primarily for my use only - as I can't
continuously work on this project and have to come back to it
after some time, it would be nice to have some documentation
available to help jog my memory.

What is the best way to do this in an automated way? I have
been documenting my code as I've gone along.

Is pydoc still the way to go, or should I use something else?

Thanks,
Esmail



From exarkun at twistedmatrix.com  Wed Aug 12 10:09:56 2009
From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com)
Date: Wed, 12 Aug 2009 14:09:56 -0000
Subject: Need cleanup advice for multiline string
In-Reply-To: <4A82C355.8080304@sequans.com>
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com>
	<4A82C355.8080304@sequans.com>
Message-ID: <20090812140956.10431.1919444081.divmod.xquotient.60@localhost.localdomain>

On 01:27 pm, jeanmichel at sequans.com wrote:
>Simon Brunning wrote:
>>2009/8/11 Robert Dailey :
>>>On Aug 11, 3:40 pm, Bearophile  wrote:
>>>>There are gals too here.
>>>It's a figure of speech. And besides, why would I want programming
>>>advice from a woman? lol. Thanks for the help.
>>
>>Give the attitudes still prevalent in our industry (cf
>> and many more), I'm sorry to say that I
>>don't think this is funny.
>Having someone present technical informations with porn content cannot 
>be qualified as "prevalent in our industry". I would even dare to say 
>this is the opposite, it is almost unique.
>I would also add that Robert was very far from this attitude, I 
>consider his joke as a friendly tickle, not a male chauvinist 
>aggression. I'm no women, but I'm sure they are as capable as me, not 
>to say more, of making the distinction.
>
>It has been said this list is not very friendly to newbies, let's not 
>make it hostile to gentle jokes (even those not funny) when thanking 
>helpers.

It's lots of little things like this which combine to create an 
environment which is less friendly towards women than it is towards 
others.  You might read it as a joke, others might not.  Even if it is a 
joke, it's in poor taste and doesn't really belong on python-list.

There's a difference between pointing out inappropriate behavior and 
being unfriendly.  Hopefully Robert got help with his problem.  That's 
what the list is here for.  Having accomplished that, it is not 
unfriendly to ask him not to make disparaging comments, "jokes" or 
otherwise, about groups of people.

Jean-Paul


From breamoreboy at yahoo.co.uk  Wed Aug 12 10:10:47 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Wed, 12 Aug 2009 15:10:47 +0100
Subject: Social problems of Python doc [was Re: Python docs disappointing]
In-Reply-To: <3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com>
References: 	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>		<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>		<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>	<0291a07d$0$20639$c3e8da3@news.astraweb.com>	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>		<7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>	<0292a134$0$20647$c3e8da3@news.astraweb.com>
	<3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com>
Message-ID: 

Paul Boddie wrote:
[snip]
> One can always spend one's time doing something which isn't 100%
> enjoyable or 100% rewarding if one feels that the time is still being
> spent on something worthwhile. I'm getting the feeling that lots of
> Python-related stuff doesn't quite satisfy such criteria any more.

I've been strongly considering volunteering to do Python work but this 
thread has put me off completely.  I've time to spare as I only work 
part time due to long term health problems. However I don't feel that 
the time would be well spent on Python work, as I get the impression 
that a lot of it would go on cleaning some people's snotty noses, and on 
wiping other people's bottoms.

I'll just wait until my normal voluntary work starts again next month 
after the summer break.  Working with an extremely pleasant bunch of 
people hacking foreigners to death, that's more like it.  See the 
following links should anyone be interested.

http://www.dorsetforyou.com/index.jsp?articleid=386553
http://www.dorsetforyou.com/index.jsp?articleid=386598

-- 
Kindest regards.

Mark Lawrence.



From maxerickson at gmail.com  Wed Aug 12 10:14:46 2009
From: maxerickson at gmail.com (Max Erickson)
Date: Wed, 12 Aug 2009 14:14:46 +0000 (UTC)
Subject: httplib incredibly slow :-(
References: <4A81FDF5.6010508@simplistix.co.uk>
	<4A8274A9.7000905@simplistix.co.uk>
Message-ID: 

Chris Withers  wrote:
> 
> I'm still reeling from what seems to be such a huge problem with
> httplib that seem to be largely ignored :-(
> 
> Chris
> 

There is an httplib2 (but I don't know anything further about it...):

http://code.google.com/p/httplib2/

Calling wget or curl using a subprocess is probably as easy as it is 
ugly, I use the wget build from here:

http://gnuwin32.sourceforge.net/packages/wget.htm


max



From Scott.Daniels at Acm.Org  Wed Aug 12 10:29:37 2009
From: Scott.Daniels at Acm.Org (Scott David Daniels)
Date: Wed, 12 Aug 2009 07:29:37 -0700
Subject: better way?
In-Reply-To: <6733c8fe-9ef8-4010-9b23-27538e19d8ff@c29g2000yqd.googlegroups.com>
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
	<87skfyjen8.fsf@golux.woodcraft.me.uk>
	
	<6733c8fe-9ef8-4010-9b23-27538e19d8ff@c29g2000yqd.googlegroups.com>
Message-ID: <3tSdnTBlOchPUh_XnZ2dnUVZ_oGdnZ2d@pdx.net>

Pet wrote:
> On 11 Aug., 22:19, "Rami Chowdhury"  wrote:
>> Ah, my apologies, I must have been getting it confused with ON UPDATE  
>> [things]. Thanks for correcting me.
>>
>> On Tue, 11 Aug 2009 13:10:03 -0700, Matthew Woodcraft  
>>
>>  wrote:
>>> "Rami Chowdhury"  writes:
>>>> IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than
>>>> MySQL...
>>> PostgreSQL does not have ON DUPLICATE KEY UPDATE.
>>> The SQL standard way to do what the OP wants is MERGE. PostgreSQL
>>> doesn't have that either.
> 
> So, I'm doing it in right way?
> What about building columns? map(lambda s: s + ' = %s', fields)
> Is that o.k.?
Isn't
     t = [field + ' = %s' for field in fields]
clearer than
     t = map(lambda s: s + ' = %s', fields)
? your call of course.

I don't quite understand why you are building the SQL from data
but constructing the arguments in source.  I'd actually set the
SQL up directly as a string, making both the SQL and Python more
readable. To the original question, you could unconditionally
perform a queries vaguely like:

UPDATE_SQL = '''UPDATE table ...
      WHERE id = %s AND location = %s;'''
INSERT_SQL = '''INSERT INTO table(...
      WHERE NOT EXISTS(SELECT * FROM table
                       WHERE id = %s AND location = %s;);'''
I'd put the NOW() and constant args (like the 1) in the SQL itself.
then your code might become:
     row = (self.wl, name, location, id)
     self._execQuery(db, UPDATE_SQL, [row])
     self._execQuery(db, INSERT_SQL, [row + (location, id)])
if _execQuery is like the standard Python DB interfaces.  Having
the SQL do the checking means you allows the DB to check its
index and use that result to control the operation, simplifying
the Python code without significantly affecting the the DB work
needed.  The "SELECT *" form in the EXIST test is something DB
optimizers look for, so don't fret about wasted data movement.



--Scott David Daniels
Scott.Daniels at Acm.Org


From rcdailey at gmail.com  Wed Aug 12 10:41:52 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Wed, 12 Aug 2009 07:41:52 -0700 (PDT)
Subject: Need cleanup advice for multiline string
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> 
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> 
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com> 
	<4A82C355.8080304@sequans.com>
	
Message-ID: <77a10bad-e0fe-4d50-95b2-f2f92a665001@h21g2000yqa.googlegroups.com>

On Aug 12, 9:09?am, exar... at twistedmatrix.com wrote:
> On 01:27 pm, jeanmic... at sequans.com wrote:
>
>
>
>
>
> >Simon Brunning wrote:
> >>2009/8/11 Robert Dailey :
> >>>On Aug 11, 3:40 pm, Bearophile  wrote:
> >>>>There are gals too here.
> >>>It's a figure of speech. And besides, why would I want programming
> >>>advice from a woman? lol. Thanks for the help.
>
> >>Give the attitudes still prevalent in our industry (cf
> >> and many more), I'm sorry to say that I
> >>don't think this is funny.
> >Having someone present technical informations with porn content cannot
> >be qualified as "prevalent in our industry". I would even dare to say
> >this is the opposite, it is almost unique.
> >I would also add that Robert was very far from this attitude, I
> >consider his joke as a friendly tickle, not a male chauvinist
> >aggression. I'm no women, but I'm sure they are as capable as me, not
> >to say more, of making the distinction.
>
> >It has been said this list is not very friendly to newbies, let's not
> >make it hostile to gentle jokes (even those not funny) when thanking
> >helpers.
>
> It's lots of little things like this which combine to create an
> environment which is less friendly towards women than it is towards
> others. ?You might read it as a joke, others might not. ?Even if it is a
> joke, it's in poor taste and doesn't really belong on python-list.
>
> There's a difference between pointing out inappropriate behavior and
> being unfriendly. ?Hopefully Robert got help with his problem. ?That's
> what the list is here for. ?Having accomplished that, it is not
> unfriendly to ask him not to make disparaging comments, "jokes" or
> otherwise, about groups of people.
>
> Jean-Paul

Hey everyone,

I was actually joking about my remark, I was making fun of the fact
that Bearophile took my figure of speech literally. I have worked with
a lot of women in the past and they even use "guys" to refer to
everyone in a room (When there were obviously other females in that
room as well).

On a more serious note, I do apologize to those offended by my remark.
I realize that these things can be a touchy subject for some people. I
expected more of a laid-back attitude from everyone. No need to be so
serious all the time. I cannot completely doubt that there are logical
women out there. I just haven't seen one yet. But that doesn't mean
I'm a sexist.

With my apology presented, I would like to propose that we end the
discussion here. As I said, this is a very sensitive subject and this
thread could spin way out of control if we don't just ignore the
issue. For those that took it as a friendly, harmless joke, hopefully
you had a laugh. For those that took it seriously or as an offense,
please take my apology to heart. Thanks once again to everyone for
your help. I've long been a member of this community and I really
appreciate the continuous support I've been receiving!

Take care everyone!


From rcdailey at gmail.com  Wed Aug 12 10:47:58 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Wed, 12 Aug 2009 07:47:58 -0700 (PDT)
Subject: Need cleanup advice for multiline string
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> 
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> 
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com> 
	<4A82C355.8080304@sequans.com>
	 
	<77a10bad-e0fe-4d50-95b2-f2f92a665001@h21g2000yqa.googlegroups.com>
Message-ID: <1b527b08-8b49-4bff-a192-215565feacf3@s15g2000yqs.googlegroups.com>

On Aug 12, 9:41?am, Robert Dailey  wrote:
> On Aug 12, 9:09?am, exar... at twistedmatrix.com wrote:
>
>
>
>
>
> > On 01:27 pm, jeanmic... at sequans.com wrote:
>
> > >Simon Brunning wrote:
> > >>2009/8/11 Robert Dailey :
> > >>>On Aug 11, 3:40 pm, Bearophile  wrote:
> > >>>>There are gals too here.
> > >>>It's a figure of speech. And besides, why would I want programming
> > >>>advice from a woman? lol. Thanks for the help.
>
> > >>Give the attitudes still prevalent in our industry (cf
> > >> and many more), I'm sorry to say that I
> > >>don't think this is funny.
> > >Having someone present technical informations with porn content cannot
> > >be qualified as "prevalent in our industry". I would even dare to say
> > >this is the opposite, it is almost unique.
> > >I would also add that Robert was very far from this attitude, I
> > >consider his joke as a friendly tickle, not a male chauvinist
> > >aggression. I'm no women, but I'm sure they are as capable as me, not
> > >to say more, of making the distinction.
>
> > >It has been said this list is not very friendly to newbies, let's not
> > >make it hostile to gentle jokes (even those not funny) when thanking
> > >helpers.
>
> > It's lots of little things like this which combine to create an
> > environment which is less friendly towards women than it is towards
> > others. ?You might read it as a joke, others might not. ?Even if it is a
> > joke, it's in poor taste and doesn't really belong on python-list.
>
> > There's a difference between pointing out inappropriate behavior and
> > being unfriendly. ?Hopefully Robert got help with his problem. ?That's
> > what the list is here for. ?Having accomplished that, it is not
> > unfriendly to ask him not to make disparaging comments, "jokes" or
> > otherwise, about groups of people.
>
> > Jean-Paul
>
> Hey everyone,
>
> I was actually joking about my remark, I was making fun of the fact
> that Bearophile took my figure of speech literally. I have worked with
> a lot of women in the past and they even use "guys" to refer to
> everyone in a room (When there were obviously other females in that
> room as well).
>
> On a more serious note, I do apologize to those offended by my remark.
> I realize that these things can be a touchy subject for some people. I
> expected more of a laid-back attitude from everyone. No need to be so
> serious all the time. I cannot completely doubt that there are logical
> women out there. I just haven't seen one yet. But that doesn't mean
> I'm a sexist.
>
> With my apology presented, I would like to propose that we end the
> discussion here. As I said, this is a very sensitive subject and this
> thread could spin way out of control if we don't just ignore the
> issue. For those that took it as a friendly, harmless joke, hopefully
> you had a laugh. For those that took it seriously or as an offense,
> please take my apology to heart. Thanks once again to everyone for
> your help. I've long been a member of this community and I really
> appreciate the continuous support I've been receiving!
>
> Take care everyone!

Oh, one last thing... So everyone knows, I chose the following
formatting solution to multiline strings:

def MyFunction():
   multilineString = (
      'This is a string that spans '
      'multiple lines.'
      )
   print( multilineString )

I think this is as good as it is going to get for my personal needs.
However, I do not like having to put a space at the end of each
string. I've also done this in the past, which is slightly more ugly:

  multilineString = (
     'This is a string that spans',
     'multiple lines.'
     )
  print( ' '.join( multilineString ) )

This will add the spaces between lines for you. However, in a
production quality application I would always have strings external to
the scripts and have an advanced localization system. However this is
useful for quick little scripts that I want to keep tidy.


From breamoreboy at yahoo.co.uk  Wed Aug 12 10:49:51 2009
From: breamoreboy at yahoo.co.uk (Mark Lawrence)
Date: Wed, 12 Aug 2009 15:49:51 +0100
Subject: best practice for documenting a project? pydoc?
In-Reply-To: 
References: 
Message-ID: 

Esmail wrote:
> Hello,
> 
> A project that I have been working on is getting larger
> and more complex, and I would like to unload some of the
> information from my memory/head to some other media (a
> set of web pages?). I am primarily interested in documenting
> the classes/methods.
> 
> This documentation is primarily for my use only - as I can't
> continuously work on this project and have to come back to it
> after some time, it would be nice to have some documentation
> available to help jog my memory.
> 
> What is the best way to do this in an automated way? I have
> been documenting my code as I've gone along.
> 
> Is pydoc still the way to go, or should I use something else?
> 
> Thanks,
> Esmail
> 
The docs for the constraint package look good, see
http://labix.org/python-constraint and http://labix.org/doc/constraint.
I think they've been produced with epydoc see http://epydoc.sourceforge.net/

-- 
Kindest regards.

Mark Lawrence.



From steve at REMOVE-THIS-cybersource.com.au  Wed Aug 12 11:08:32 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 15:08:32 GMT
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	
	<7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>
	<0292a134$0$20647$c3e8da3@news.astraweb.com>
	<3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com>
Message-ID: <0292cb5a$0$20647$c3e8da3@news.astraweb.com>

On Wed, 12 Aug 2009 06:24:18 -0700, Paul Boddie wrote:

> On 12 Aug, 14:08, Steven D'Aprano  cybersource.com.au> wrote:
>>
>> With tens of millions of web users, it's no surprise that Wikipedia can
>> attract thousands of editors. But this does not apply to Python, which
>> starts from a comparatively tiny population, primarily those interested
>> in Python. Have a look at the Wikipedia page for Python.
> 
> What does the Python entry on Wikipedia have to do with editing the
> Python documentation in a Wiki? 

Good question. I was responding to you mentioning Wikipedia as a possible 
role model for the Python docs.


> Once everyone has agreed that the
> description of Python on Wikipedia is reasonable, there's not much point
> in editing it, is there? 

And once we're all fabulously wealthy, there won't be any point in anyone 
working any more either!

The problem for your argument is, even if it were correct, not everyone 
agrees the Python article is "reasonable" -- there were three edits made 
since the 7th of this month. And before that, there was a stream of 22 
edits on the 5th, and another 25 edits since the  8th of July. Obviously 
the Python article is still in active development.

Some of those edits were, apparently, vandalism, which gives yet another 
reason why the Wikipedia model is not necessarily the right model to 
follow.


> In contrast, there's a continuous stream of
> people who don't think Python's documentation is that great.

And a great flood of those who think it's pretty good and gets the job 
done adequately, and a trickle of those who think it's perfect just the 
way it is.

It's not the people who suggest improvements to the docs that are the 
problem, but the ones who insist that the docs are terrible, but aren't 
willing to do anything but complain. Oh, and trolls like ... I hesitate 
to mention his name in case he has a bot monitoring the list ... first 
name starts with "X" followed by "ah", second name sounds like "Mee" ... 
who even if they make a few good points, they're lost in a sea of insults 
to others, arrogance and self-aggrandisement.


>> And the Python time-machine strikes again:
>>
>> http://wiki.python.org/moin/
> 
> And I suggested that the complainants use it as a starting point.

Sorry, I seem to have missed that.


> [...]
> 
>> Oh dear me. You mean that they don't agree that YOUR time is more
>> important than theirs??? What horrible people they must be, to expect
>> you to sacrifice some of your sleep time just so *they* can get some
>> sleep themselves!!! Who do they think they are???
> 
> That's quite an attempt to make my position more extreme than it
> actually is. 

Well, you did raise the issue of the sacrifices you were making to report 
these bugs. All I did was exaggerate the attitude a tad.


> I get people asking me to improve my own software, you
> know, and even if I don't have the time or inclination to do what they
> ask, I do spend time discussing it with them. Such people, including
> myself when I'm on the other side of the fence, appreciate more than
> just a brush-off and no: they don't insist that their own time be valued
> above anyone else's 

Then you're incredibly lucky to attract a better class of end-users. In 
my experience, most end-users won't even spend the effort to describe the 
problem they're having beyond "it doesn't work". And they usually 
misspell that.



> (as you would have me misrepresented); they just ask
> that their own efforts aren't treated as having no value because they're
> not part of the "elite" development team. You get various projects doing
> soul-searching about embracing the efforts of non-programmers, and the
> first port of call on that particular voyage is to not treat them like
> idiot consumers whose remarks can only be considered as mere heckling
> while the visionaries act out their flawless production.

A noble vision, but wait until the idiot heckling consumers discover your 
software, then we'll see how much time you're prepared to give them.



> 
> Paul
> 
> P.S. The mention of "social problems" ties in with other remarks made
> recently, and I've increasingly found it more trouble than has been
> worthwhile to pursue Python-related matters of late. When one tries to
> encourage people to participate in improving various things, which
> usually means the community having to accept a degree of criticism,
> people claim that it's encouraging "undesirable" influences to point
> such critics in the right direction instead of showing them the door.

Can you point me to a discussion where this has happened?


> When one tries to pursue such improvement matters oneself, people always
> have something to say about the choice of technology or whether they
> like the particular background colour being used 

You've discovered bike-shedding.

> or indeed have an
> opinion, typically shallow and negative, about anything but the task at
> hand, 

When you're agitating for change, anyone defending the status quo has 
opinions which are shallow and negative. When you're happy with the 
status quo, possibly even for good, rational reasons and not just because 
you're a shallow-minded, ignorant, know-nothing nay-sayer, it's those 
agitating for change who have shallow and negative opinions. It's such a 
bother trying to determine who is right, so I prefer to just accuse the 
other guy of being shallow and negative rather than try to understand his 
point of view. I find it saves time in the long run.


> and there'll always be someone queuing up to dismantle anything
> that does get done at the first opportunity. In contrast, I've found
> other groups of people to be grateful for even modest technical
> assistance, and I know that such people are much more likely to get my
> support and input in the future than those who think that it's some kind
> of advantage to have potential contributors run the gauntlet of denial
> (that there are structural problems in their project), skepticism (that
> newcomers can have anything to contribute), discouragement (because any
> solution which doesn't validate someone's technology preferences must be
> criticised) and, indeed, outright hostility.

I'm having trouble parsing the semantics of that sentence, so please 
excuse me for any misunderstandings.

There seems to be a hidden assumption in your sentence that there *are* 
structural problems in the project. Now obviously no project is 
"perfect", and we all know of cases where a group of people immersed in a 
project will become so close to it that they can't see the rotten trees 
for the wood, so to speak. But generally, the people in the project have 
a very good understanding of the project's strengths and weaknesses, 
because they've been living with it for a long, long time, and it's new-
comers, who don't know the tools, don't know the libraries, aren't 
familiar with the conventions, and don't know the reasons for the 
decisions made, who can't see the trees for the wood.

It's not experienced Python developers who write really slow Java code in 
Python, it's Java developers. And I'm sure the opposite occurs too: 
Python developers learning Java for the first time will struggle to write 
idiomatic Java code, and will criticise *the wrong things* because 
they're thinking like Python developers.

You're expecting outsiders to bring in fresh insights that the jaded, 
stuck-in-a-rut locals can't see. Well, it happens. But for every time it 
happens, there's a hundred outsiders who come along and say the 
equivalent of "What, no GOTO? Well this sucks."




-- 
Steven


From petshmidt at googlemail.com  Wed Aug 12 11:09:02 2009
From: petshmidt at googlemail.com (Pet)
Date: Wed, 12 Aug 2009 08:09:02 -0700 (PDT)
Subject: better way?
References: <9899e909-509e-47d4-a8e5-f9d70e0b8827@e27g2000yqm.googlegroups.com>
	
	<78a18b9b-f29e-432f-9fe4-8c250cb08edb@o32g2000yqm.googlegroups.com>
	
	<87skfyjen8.fsf@golux.woodcraft.me.uk> 
	
	<6733c8fe-9ef8-4010-9b23-27538e19d8ff@c29g2000yqd.googlegroups.com>
	<3tSdnTBlOchPUh_XnZ2dnUVZ_oGdnZ2d@pdx.net>
Message-ID: 

On Aug 12, 4:29?pm, Scott David Daniels  wrote:
> Pet wrote:
> > On 11 Aug., 22:19, "Rami Chowdhury"  wrote:
> >> Ah, my apologies, I must have been getting it confused with ON UPDATE ?
> >> [things]. Thanks for correcting me.
>
> >> On Tue, 11 Aug 2009 13:10:03 -0700, Matthew Woodcraft ?
>
> >>  wrote:
> >>> "Rami Chowdhury"  writes:
> >>>> IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than
> >>>> MySQL...
> >>> PostgreSQL does not have ON DUPLICATE KEY UPDATE.
> >>> The SQL standard way to do what the OP wants is MERGE. PostgreSQL
> >>> doesn't have that either.
>
> > So, I'm doing it in right way?
> > What about building columns? map(lambda s: s + ' = %s', fields)
> > Is that o.k.?
>
> Isn't
> ? ? ?t = [field + ' = %s' for field in fields]
> clearer than
> ? ? ?t = map(lambda s: s + ' = %s', fields)
> ? your call of course.

Yes, I think so

> I don't quite understand why you are building the SQL from data
> but constructing the arguments in source. ?I'd actually set the
> SQL up directly as a string, making both the SQL and Python more

Sometimes, column list could be long, besides I keep column list in
sync for both update and insert query

> readable. To the original question, you could unconditionally
> perform a queries vaguely like:
>
> UPDATE_SQL = '''UPDATE table ...
> ? ? ? WHERE id = %s AND location = %s;'''
> INSERT_SQL = '''INSERT INTO table(...
> ? ? ? WHERE NOT EXISTS(SELECT * FROM table
> ? ? ? ? ? ? ? ? ? ? ? ?WHERE id = %s AND location = %s;);'''
> I'd put the NOW() and constant args (like the 1) in the SQL itself.

yes, but I'm building both UPDATE in INSERT from same list of columns,
so I didn't found better way as this one


> then your code might become:
> ? ? ?row = (self.wl, name, location, id)
> ? ? ?self._execQuery(db, UPDATE_SQL, [row])
> ? ? ?self._execQuery(db, INSERT_SQL, [row + (location, id)])

I'm going to rebuild my queries like that.

Thank you very much!


> if _execQuery is like the standard Python DB interfaces. ?Having
> the SQL do the checking means you allows the DB to check its
> index and use that result to control the operation, simplifying
> the Python code without significantly affecting the the DB work
> needed. ?The "SELECT *" form in the EXIST test is something DB
> optimizers look for, so don't fret about wasted data movement.
>
> --Scott David Daniels
> Scott.Dani... at Acm.Org



From sajmikins at gmail.com  Wed Aug 12 11:11:43 2009
From: sajmikins at gmail.com (Simon Forman)
Date: Wed, 12 Aug 2009 08:11:43 -0700 (PDT)
Subject: Need cleanup advice for multiline string
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> 
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> 
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com> 
	<4A82C355.8080304@sequans.com>
	 
	<77a10bad-e0fe-4d50-95b2-f2f92a665001@h21g2000yqa.googlegroups.com>
Message-ID: 

On Aug 12, 10:41?am, Robert Dailey  wrote:
> On Aug 12, 9:09?am, exar... at twistedmatrix.com wrote:
>
>
>
> > On 01:27 pm, jeanmic... at sequans.com wrote:
>
> > >Simon Brunning wrote:
> > >>2009/8/11 Robert Dailey :
> > >>>On Aug 11, 3:40 pm, Bearophile  wrote:
> > >>>>There are gals too here.
> > >>>It's a figure of speech. And besides, why would I want programming
> > >>>advice from a woman? lol. Thanks for the help.
>
> > >>Give the attitudes still prevalent in our industry (cf
> > >> and many more), I'm sorry to say that I
> > >>don't think this is funny.
> > >Having someone present technical informations with porn content cannot
> > >be qualified as "prevalent in our industry". I would even dare to say
> > >this is the opposite, it is almost unique.
> > >I would also add that Robert was very far from this attitude, I
> > >consider his joke as a friendly tickle, not a male chauvinist
> > >aggression. I'm no women, but I'm sure they are as capable as me, not
> > >to say more, of making the distinction.
>
> > >It has been said this list is not very friendly to newbies, let's not
> > >make it hostile to gentle jokes (even those not funny) when thanking
> > >helpers.
>
> > It's lots of little things like this which combine to create an
> > environment which is less friendly towards women than it is towards
> > others. ?You might read it as a joke, others might not. ?Even if it is a
> > joke, it's in poor taste and doesn't really belong on python-list.
>
> > There's a difference between pointing out inappropriate behavior and
> > being unfriendly. ?Hopefully Robert got help with his problem. ?That's
> > what the list is here for. ?Having accomplished that, it is not
> > unfriendly to ask him not to make disparaging comments, "jokes" or
> > otherwise, about groups of people.
>
> > Jean-Paul
>
> Hey everyone,
>
> I was actually joking about my remark, I was making fun of the fact
> that Bearophile took my figure of speech literally. I have worked with
> a lot of women in the past and they even use "guys" to refer to
> everyone in a room (When there were obviously other females in that
> room as well).
>
> On a more serious note, I do apologize to those offended by my remark.
> I realize that these things can be a touchy subject for some people. I
> expected more of a laid-back attitude from everyone. No need to be so
> serious all the time. I cannot completely doubt that there are logical
> women out there. I just haven't seen one yet. But that doesn't mean
> I'm a sexist.

Oh my.  And you were doing so well.  You haven't seen a logical
woman?  Perhaps you're blind because your eyes were torn out by a
raging marmoset?

Guess what?  Thinking (or just saying) that /does/ mean you're a
sexist.  (Even if it was just another "friendly, harmless joke".)




> With my apology presented, I would like to propose that we end the
> discussion here. As I said, this is a very sensitive subject and this
> thread could spin way out of control if we don't just ignore the
> issue. For those that took it as a friendly, harmless joke, hopefully
> you had a laugh. For those that took it seriously or as an offense,
> please take my apology to heart. Thanks once again to everyone for
> your help. I've long been a member of this community and I really
> appreciate the continuous support I've been receiving!
>
> Take care everyone!



From steve at REMOVE-THIS-cybersource.com.au  Wed Aug 12 11:26:12 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 15:26:12 GMT
Subject: Need cleanup advice for multiline string
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com>
	<4A82C355.8080304@sequans.com>
	
	<77a10bad-e0fe-4d50-95b2-f2f92a665001@h21g2000yqa.googlegroups.com>
	<1b527b08-8b49-4bff-a192-215565feacf3@s15g2000yqs.googlegroups.com>
Message-ID: <0292cf7e$0$20647$c3e8da3@news.astraweb.com>

On Wed, 12 Aug 2009 07:47:58 -0700, Robert Dailey wrote:

> On Aug 12, 9:41?am, Robert Dailey  wrote:
... 
> > I was actually joking about my remark, I was making fun of the fact
> > that Bearophile took my figure of speech literally. 

Keep in mind that the Internet is a global forum, and not everyone here 
speaks English as a first language. I believe Bearophile is one of those. 
Although his, or possibly her, English is excellent, it wouldn't surprise 
me that (s)he would misinterpret "guys" as just referring to men. I'm a 
native English speaker, and I would have done the same.


> > I have worked with
> > a lot of women in the past and they even use "guys" to refer to
> > everyone in a room (When there were obviously other females in that
> > room as well).

Yes, I've seen this myself, but it's still uncommon enough to surprise me 
every time I see it.


> > On a more serious note, I do apologize to those offended by my remark.
> > I realize that these things can be a touchy subject for some people. I
> > expected more of a laid-back attitude from everyone. No need to be so
> > serious all the time. I cannot completely doubt that there are logical
> > women out there. I just haven't seen one yet. 

That's okay, I haven't seen terribly many logical men out there either.


> Oh, one last thing... So everyone knows, I chose the following
> formatting solution to multiline strings:
> 
> def MyFunction():
>    multilineString = (
>       'This is a string that spans '
>       'multiple lines.'
>       )
>    print( multilineString )
> 
> I think this is as good as it is going to get for my personal needs.
> However, I do not like having to put a space at the end of each
> string. 

So put them at the beginning of the next line. It makes the space more 
obvious, so it's clearer what you have done. That's what I sometimes do.


> I've also done this in the past, which is slightly more ugly:
> 
>   multilineString = (
>      'This is a string that spans',
>      'multiple lines.'
>      )
>   print( ' '.join( multilineString ) )


It's also less efficient, as it does the concatenation at runtime instead 
of compile time. But for a small script, that's not likely to be a 
problem worth worrying about.
 


-- 
Steven


From shaileshk at gmail.com  Wed Aug 12 11:33:55 2009
From: shaileshk at gmail.com (shaileshkumar)
Date: Wed, 12 Aug 2009 08:33:55 -0700 (PDT)
Subject: best practice for documenting a project? pydoc?
References: 
	
Message-ID: 

Hello,

EPYDOC is very good for automatic generation of documentation from
source code.

You may also consider Sphinx http://sphinx.pocoo.org/ which is used
for many
projects including the official Python documentation, documentation of
Zope (http://docs.zope.org/).
See the full list of projects using Sphinx at http://sphinx.pocoo.org/examples.html

- Shailesh


On Aug 12, 7:49?pm, Mark Lawrence  wrote:
> Esmail wrote:
> > Hello,
>
> > A project that I have been working on is getting larger
> > and more complex, and I would like to unload some of the
> > information from my memory/head to some other media (a
> > set of web pages?). I am primarily interested in documenting
> > the classes/methods.
>
> > This documentation is primarily for my use only - as I can't
> > continuously work on this project and have to come back to it
> > after some time, it would be nice to have some documentation
> > available to help jog my memory.
>
> > What is the best way to do this in an automated way? I have
> > been documenting my code as I've gone along.
>
> > Is pydoc still the way to go, or should I use something else?
>
> > Thanks,
> > Esmail
>
> The docs for the constraint package look good, seehttp://labix.org/python-constraintandhttp://labix.org/doc/constraint.
> I think they've been produced with epydoc seehttp://epydoc.sourceforge.net/
>
> --
> Kindest regards.
>
> Mark Lawrence.



From shaileshk at gmail.com  Wed Aug 12 11:50:14 2009
From: shaileshk at gmail.com (shaileshkumar)
Date: Wed, 12 Aug 2009 08:50:14 -0700 (PDT)
Subject: httplib incredibly slow :-(
References: <4A81FDF5.6010508@simplistix.co.uk>
	<4A8274A9.7000905@simplistix.co.uk> 
	
Message-ID: 

We use PyCURL on Windows. http://pycurl.sourceforge.net/ provides pre-
built versions for Windows and it works out of the box.

- Shailesh



On Aug 12, 7:14?pm, Max Erickson  wrote:
> Chris Withers  wrote:
>
> > I'm still reeling from what seems to be such a huge problem with
> > httplib that seem to be largely ignored :-(
>
> > Chris
>
> There is an httplib2 (but I don't know anything further about it...):
>
> http://code.google.com/p/httplib2/
>
> Calling wget or curl using a subprocess is probably as easy as it is
> ugly, I use the wget build from here:
>
> http://gnuwin32.sourceforge.net/packages/wget.htm
>
> max



From shaileshk at gmail.com  Wed Aug 12 11:56:03 2009
From: shaileshk at gmail.com (shaileshkumar)
Date: Wed, 12 Aug 2009 08:56:03 -0700 (PDT)
Subject: Programming by Contract
References: <4A7A15CD.9090306@stoneleaf.us> <4A81C6B8.7010605@stoneleaf.us> 
	<18F0FD2E-7C01-4B1C-85DF-28433C23D886@declareSub.com>
	
Message-ID: <78b17cf4-1e7b-4134-8626-2c352107ac27@f20g2000prn.googlegroups.com>

zope.interface provides extensive support for design by contract.
http://pypi.python.org/pypi/zope.interface.
This package can be used independently of zope in other projects.
- Shailesh

On Aug 12, 2:20?am, Ethan Furman  wrote:
> Charles Yeomans wrote:
>
> > On Aug 11, 2009, at 3:30 PM, Ethan Furman wrote:
>
> >> Ethan Furman wrote:
>
> >>> Greetings!
> >>> I have seen posts about the assert statement and PbC (or maybe it ?
> >>> was DbC), and I just took a very brief look at pycontract
> >>> (http://www.wayforward.net/pycontract/) and now I have at least one
> >>> question: ?Is this basically another ?way of thinking about unit
> >>> testing, or is the idea of PbC more ?along the lines of *always*
> >>> checking the input/output of functions ?to ensure they are correct? ?
> >>> (*Contstant vigilance!* as Prof Moody ?would say ;)
> >>> I know asserts can be turned off, so they obviously won't work for ?
> >>> the latter case, and having seen the sample of pycontract it seems ?
> >>> it only does its thing during debugging.
> >>> So is Design (Programming) by Contract a fancy way of saying ?
> >>> "Document your inputs/outputs!" or is there more to it?
> >>> ~Ethan~
>
> >> Hmmm...
>
> >> Well, from the (apparently) complete lack of interest, I shall take ?
> >> away the (better?) documentation ideas and unit testing ideas, and ?
> >> not worry about the rest. ?:)
>
> > Design by contract is complementary to unit testing (I notice that the ?
> > author of PEP 316 appears confused about this). ?DbC is, roughly ?
> > speaking, about explicit allocation of responsibility. ?Consider this ?
> > contrived example.
>
> > def foo(s):
> > ? ? require(s is not None)
> > ? ? //code
> > ? ? ensure(hasattr(returnValue, '__iter__'))
>
> > The require condition tells you that it's the caller's responsibility ?
> > to pass a non-nil argument to foo. ?The ensure condition is a ?guarantee
> > that foo will return something suitable for iteration, if ?the
> > precondition in the require condition is satisfied. ?These ?conditions
> > can be enforced at runtime, but may not be, for reasons of ?performance.
>
> > DbC is in fact about not *always* checking the input/output of ?
> > functions; on the contrary, Bertrand Meyer, the inventor of DbC, ?claims
> > that DbC allows one to eliminate such redundancy, and the ?resulting
> > overhead.
>
> > Charles Yeomans
>
> Many thanks!
>
> So if I understand -- Python's EAFP fits well with DbC, as DbC seems
> well suited to say, "This is your responsibility, and this is mine,"
> stated in programming terms (who needs comments? ;) ?Combined with unit
> testing (which should be easier to design correctly given the DbC code),
> healthy code seems more attainable.
>
> Interesting. ?Thank you for the information.
>
> ~Ethan~



From steve at REMOVE-THIS-cybersource.com.au  Wed Aug 12 11:58:28 2009
From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano)
Date: 12 Aug 2009 15:58:28 GMT
Subject: Need cleanup advice for multiline string
References: 
	<5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com>
	<461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com>
	<8c7f10c60908120121v4bbf9040h9da68a650ef48566@mail.gmail.com>
	<4A82C355.8080304@sequans.com>
	
	<77a10bad-e0fe-4d50-95b2-f2f92a665001@h21g2000yqa.googlegroups.com>
	
Message-ID: <0292d70e$0$20647$c3e8da3@news.astraweb.com>

On Wed, 12 Aug 2009 08:11:43 -0700, Simon Forman wrote:

[quoting Robert Dailey]
>> I cannot completely doubt that there are logical
>> women out there. I just haven't seen one yet. But that doesn't mean I'm
>> a sexist.
> 
> Oh my.  And you were doing so well.  You haven't seen a logical woman? 
> Perhaps you're blind because your eyes were torn out by a raging
> marmoset?
> 
> Guess what?  Thinking (or just saying) that /does/ mean you're a sexist.
>  (Even if it was just another "friendly, harmless joke".)

It was an incredibly insensitive thing for Robert to say, having just 
been slapped for a previous insensitive "joke" about women. But still, 
most people, male or female, *aren't* logical. I know I've never met 
somebody who is entirely logical, of either sex, and I'm pretty sure I've 
not met very many people who are even mostly logical. Vulcans we are not. 
Does this mean I'm equally sexist against men *and* women? ("I'm not 
biased, I hate everyone equally!" *wink*)

Hell, here I am, at 2am, defending somebody I don't know, for saying 
something I don't approve of, against somebody who is saying something I 
agree with, out of some sort of misguided sense of fairness. Logic? Ha, 
what's logic got to do with it?



-- 
Steven


From db3l.net at gmail.com  Wed Aug 12 12:04:45 2009
From: db3l.net at gmail.com (David Bolen)
Date: Wed, 12 Aug 2009 12:04:45 -0400
Subject: Need cleanup advice for multiline string
References: 
Message-ID: 

Robert Dailey  writes:

> Hey guys. Being a C++ programmer, I like to keep variable definitions
> close to the location in which they will be used. This improves
> readability in many ways. However, when I have a multi-line string
> definition at function level scope, things get tricky because of the
> indents. In this case indents are serving two purposes: For syntax and
> actual text output. The tabs for function scope should not be included
> in the contents of the string. (...)

Personally I'm in the camp that something like this should be hoisted
out of the code path (whether to global scope, a dedicated message
module or configuration file is a design choice).

But if it's going to stay inline, one approach that can maintain some
of the attractive qualities of a triple quoted string is to make use
of the textwrap module:

    import textwrap

    def RunCommand( commandList ):
       # ...
       if returnCode:
           failMsg = textwrap.dedent('''\
                     *************************************************
                     The following command returned exit code [{:#x}].
                     This represents failure of some form. Please review
                     the command output for more details on the issue.
                     ------------
                     {}
                     *************************************************
                     ''')

which removes any common leading whitespace (must be identical in terms
of any tabs/spaces).

This is still additional run-time processing, and most likely less
efficient than the joining of individual strings, but it does permit a
clean triple-quoted string so IMO is easier to read/maintain in the
source - providing the code indentation level doesn't get in the way
of the desired line length of the string.  You can also choose to
dedent the string a bit (say to the level of "failMsg") if needed
without being forced all the way back to the left margin.

You can also combine textwrap.dedent with some of the other options if
where the strings are defined makes it nicer if they still have some
indentation (say in a global Python module).  In that case, you'd most
likely just process them once when the module was imported, so any
inefficiency in textwrap.dedent is far less important.

-- David


From paul at boddie.org.uk  Wed Aug 12 12:06:30 2009
From: paul at boddie.org.uk (Paul Boddie)
Date: Wed, 12 Aug 2009 09:06:30 -0700 (PDT)
Subject: Social problems of Python doc [was Re: Python docs disappointing]
References: 
	<6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com>
	
	<20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com>
	
	<6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com>
	<0291a07d$0$20639$c3e8da3@news.astraweb.com>
	<83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com>
	
	<7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com>
	<0292a134$0$20647$c3e8da3@news.astraweb.com>
	<3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com>
	<0292cb5a$0$20647$c3e8da3@news.astraweb.com>
Message-ID: 

On 12 Aug, 17:08, Steven D'Aprano  wrote:
> On Wed, 12 Aug 2009 06:24:18 -0700, Paul Boddie wrote:
>
> > What does the Python entry on Wikipedia have to do with editing the
> > Python documentation in a Wiki?
>
> Good question. I was responding to you mentioning Wikipedia as a possible
> role model for the Python docs.

Yes, but claiming that only a few people want to edit a single entry
on one site (admittedly a popular one) isn't the same as saying that
few people would edit a documentation Wiki covering numerous different
things. A bunch of people edit the existing Python Wiki now, although
there's not that much direction behind it.

[...]

> It's not the people who suggest improvements to the docs that are the
> problem, but the ones who insist that the docs are terrible, but aren't
> willing to do anything but complain. Oh, and trolls like ... I hesitate
> to mention his name in case he has a bot monitoring the list ... first
> name starts with "X" followed by "ah", second name sounds like "Mee" ...
> who even if they make a few good points, they're lost in a sea of insults
> to others, arrogance and self-aggrandisement.

Right, but those good points are still worth taking on board. There
have been Xah Lee posts which have been relatively constructive, but
when the only responses are from people who see the name and can't be
bothered reading the message before issuing a stock "he's a troll"
response, the tone is likely to remain vulgar from that point onwards.
Xah Lee can be quite coherent and rational on comp.lang.lisp, which is
more than can be said for a number of regulars on that group.

[...]

> > P.S. The mention of "social problems" ties in with other remarks made
> > recently, and I've increasingly found it more trouble than has been
> > worthwhile to pursue Python-related matters of late. When one tries to
> > encourage people to participate in improving various things, which
> > usually means the community having to accept a degree of criticism,
> > people claim that it's encouraging "undesirable" influences to point
> > such critics in the right direction instead of showing them the door.
>
> Can you point me to a discussion where this has happened?

I won't name names as in some cases I've corresponded privately with
various people who have been perceived to be "trolls" (as you put it
above) and who have had the "don't talk to them" responses from
various regulars. Some people criticise in apparently unacceptable
ways for their own amusement, but most critics do so because they are
unaware of any better way and aren't aware of the most effective
methods to fix the issues that bother them, and this latter group is
clearly invested in finding solutions because they could quite easily
go and use something else. Certainly, I wouldn't spend my time
repeatedly enumerating the problems with a piece of technology if no-
one were interested in helping me do something about them.

> > When one tries to pursue such improvement matters oneself, people always
> > have something to say about the choice of technology or whether they
> > like the particular background colour being used
>
> You've discovered bike-shedding.
>
> > or indeed have an
> > opinion, typically shallow and negative, about anything but the task at
> > hand,
>
> When you're agitating for change, anyone defending the status quo has
> opinions which are shallow and negative. When you're happy with the
> status quo, possibly even for good, rational reasons and not just because
> you're a shallow-minded, ignorant, know-nothing nay-sayer, it's those
> agitating for change who have shallow and negative opinions. It's such a
> bother trying to determine who is right, so I prefer to just accuse the
> other guy of being shallow and negative rather than try to understand his
> point of view. I find it saves time in the long run.

I can expand what I've written to just about any project,
"improvement" or otherwise, where there may not be an existing
solution that anyone actually supports or is willing to use. And
still, if you give people something they could use (which is better
than effectively nothing), my experience is that in some communities
your work, however trivial, will be appreciated. But I get the
impression that in Python-related communities, it's all "Why didn't
you use XYZ?" or "What a toy!" instead.

[...]

> There seems to be a hidden assumption in your sentence that there *are*
> structural problems in the project.

Let me assume that maybe the barriers aren't really that bad for
Python documentation; that anyone who is really going to care about
submitting something will jump through the hoops and deliver something
that can be merged by the core developers. Even then, there's going to
be a whole class of improvements that won't get made by outsiders and
will fall on the editors to make. Now, more often than not, the people
who are already the most overworked are precisely those in the
position of reviewing and merging changes (as well as making their
own), and surely they will want to delegate some of that work, but
it's the classic pitfall of "delegation failure": they don't have the
capacity to delegate because that just means even more work for them
as a result. Shower such people with trivial change requests or bug
reports about documentation errors, and it's clear that the processes
aren't helping the editors to do more or for an increased number of
people to usefully collaborate.

I'm almost past caring about the documentation - it's useful for most
of what I want it for - because the bulk of the documentation that I
do use concerns the standard library which looks more and more
antiquated and disorganised every time I look at its contents. I don't
see any top-down remedy for this situation - Python 3 didn't even
bother with it properly - and maybe the solution will ultimately
involve a completely independent standard library developed by people
under their own steam who will then be criticised for not choosing the
most permissive licence possible and/or being technologically
backwards in some aspect of what they've done. That would, after all,
be the "Pythonic" response I'd most expect to see.

Paul


From rcdailey at gmail.com  Wed Aug 12 12:13:21 2009
From: rcdailey at gmail.com (Robert Dailey)
Date: Wed, 12 Aug 2009 09:13:21 -0700 (PDT)
Subject: Multithreaded library for Python?
Message-ID: 

Hey guys,

I realize the python library has multithreading support in it, but not
the kind I'm really looking for. I want something like Intel's TBB,
but for Python 3.1. I need to be able to spawn off "Tasks" that
operate until completed and then end by themselves. I could create my
own framework for this, but why bother if a solution already exists?
Anyone know of any libraries out there that would work?


From dotancohen at gmail.com  Wed Aug 12 12:18:43 2009
From: dotancohen at gmail.com (Dotan Cohen)
Date: Wed, 12 Aug 2009 19:18:43 +0300
Subject: Scraping Wikipedia with Python
In-Reply-To: <7xd472hz2x.fsf@ruckus.brouhaha.com>
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	
	<6YidncRAiJ6SIxzXRVn_vwA@giganews.com>
	
	<7xd472hz2x.fsf@ruckus.brouhaha.com>
Message-ID: <880dece00908120918u37b30c46w62a6edc850c644a9@mail.gmail.com>

> maybe you want dbpedia.

I did not know about this. Thanks!

That is the reason why I ask. This list has an unbelievable collective
knowledge and I am certain that asking "how much is 2+2" would net an
insightful answer that would teach me something.

Thank you, Paul, and thank you to the entire Python list!

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il


From dotancohen at gmail.com  Wed Aug 12 12:19:59 2009
From: dotancohen at gmail.com (Dotan Cohen)
Date: Wed, 12 Aug 2009 19:19:59 +0300
Subject: Scraping Wikipedia with Python
In-Reply-To: 
References: 
	<4a81b6f0$0$1590$742ec2ed@news.sonic.net>
	
	
Message-ID: <880dece00908120919n1fb8a74cj55641eae6654040f@mail.gmail.com>

> http://pypi.python.org/pypi?%3Aaction=search&term=wikipedia ?
>

Thanks, Thorsten, I will go through those. I did not know about that
resource, I am not a regular coder. One more resource to add to the
toolbox!


-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il


From dstanek at dstanek.com  Wed Aug 12 12:28:25 2009
From: dstanek at dstanek.com (David Stanek)
Date: Wed, 12 Aug 2009 12:28:25 -0400
Subject: httplib incredibly slow :-(
In-Reply-To: <4A81D3CB.7080209@simplistix.co.uk>
References: <4A81D3CB.7080209@simplistix.co.uk>
Message-ID: 

On Tue, Aug 11, 2009 at 4:25 PM, Chris Withers wrote:
> Hi All,
>
> I'm using the following script to download a 150Mb file:
>
> from base64 import encodestring
> from httplib import HTTPConnection
> from datetime import datetime
>
> conn = HTTPSConnection('localhost')
> headers = {}
> auth = 'Basic '+encodestring('username:password').strip()
> headers['Authorization']=auth
> t = datetime.now()
> print t
> conn.request('GET','/somefile.zip',None,headers)
> print 'request:',datetime.now()-t
> response = conn.getresponse()
> print 'response:',datetime.now()-t
> data = response.read()
> print 'read:',datetime.now()-t
>
> The output shows it takes over 20 minutes to do this.
> However, this is on a local network, and downloading the same file in IE
> takes under 3 seconds!
>
> I saw this issue:
>
> http://bugs.python.org/issue2576
>
> I tried changing the buffer size to 4096 in a subclass as the issue
> suggested, but I didn't see the reported speed improvement.
> I'm using Python 2.6.2.
>
> Does anyone know of an alternative library for creating http requests and
> getting their responses that's faster but hopefully has a similar interface?
>

I tried to reproduce this, but I could not. Could you paste in the
output of your script? Also on the same box where you run this script
can you test with curl or wget?

-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek


From hobesh at gmail.com  Wed Aug 12 12:30:48 2009
From: hobesh at gmail.com (Zach Hobesh)
Date: Wed, 12 Aug 2009 09:30:48 -0700
Subject: Mimicing an HTML form
Message-ID: 

Hi all,
I'm having alot of trouble automating the submitting of form.  I have an
HTML page that works and it looks like this:




When I put valid values for the handling script an app ID, this page works. Now I'm trying to turn this same functionality into a script. Here's my code: import urllib import os import urllib2 appID = *value here* video = os.path.normpath(os.getcwd() + '/news.wmv') title = 'News' desc = 'Here is a sample News video' uploader = *script here* print "Encoding url..." data = urllib.urlencode({"FileUploadedVideo": video, "hdnADCID" : appID, "txtTitle" : title, "txtDescription": desc}) user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' headers = { 'User-Agent' : user_agent } print "Calling url..." req = urllib2.Request(uploader, data, headers) response = urllib2.urlopen(req) s = response.read() response.close() print "Writing results..." result = open('result.html','w') result.write(s) result.close() Does anybody have any suggestions? I keep on getting bad request, so I'm assuming that the html page is passing something that my script is not. Is there some way to scrape the POST request from the html form? Thanks, Zach -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at simplistix.co.uk Wed Aug 12 12:37:48 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Wed, 12 Aug 2009 17:37:48 +0100 Subject: httplib incredibly slow :-( In-Reply-To: References: <4A81D3CB.7080209@simplistix.co.uk> Message-ID: <4A82EFDC.70502@simplistix.co.uk> David Stanek wrote: > I tried to reproduce this, but I could not. Could you paste in the > output of your script? Not sure how that'll help, but sure: 2009-08-11 21:27:59.153000 request: 0:00:00.109000 response: 0:00:00.109000 read: 0:24:31.266000 > Also on the same box where you run this script > can you test with curl or wget? It's a Windows box, so no :-( But it really does download in a few seconds with IE, and 20min+ using the script I included... Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From ebonak at hotmail.com Wed Aug 12 12:42:17 2009 From: ebonak at hotmail.com (Esmail) Date: Wed, 12 Aug 2009 12:42:17 -0400 Subject: best practice for documenting a project? pydoc? In-Reply-To: References: Message-ID: shaileshkumar wrote: > Hello, > > EPYDOC is very good for automatic generation of documentation from > source code. > > You may also consider Sphinx http://sphinx.pocoo.org/ which is used > for many > projects including the official Python documentation, documentation of > Zope (http://docs.zope.org/). > See the full list of projects using Sphinx at http://sphinx.pocoo.org/examples.html > > - Shailesh Hi, Thanks for the links. Have you heard of something called HappyDoc? I just came across it by looking for info on epydoc. Thanks, Esmail From ebonak at hotmail.com Wed Aug 12 12:43:04 2009 From: ebonak at hotmail.com (Esmail) Date: Wed, 12 Aug 2009 12:43:04 -0400 Subject: best practice for documenting a project? pydoc? In-Reply-To: References: Message-ID: Mark Lawrence wrote: Hi Mark, > The docs for the constraint package look good, see > http://labix.org/python-constraint and http://labix.org/doc/constraint. > I think they've been produced with epydoc see > http://epydoc.sourceforge.net/ Thanks for the links, I'll take a look. Any experience with something called HappyDoc? Just came across it. Esmail From mdekauwe at gmail.com Wed Aug 12 12:43:11 2009 From: mdekauwe at gmail.com (Martin) Date: Wed, 12 Aug 2009 09:43:11 -0700 (PDT) Subject: matching patterns after regex? References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com> <2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com> <0292a4a9$0$20647$c3e8da3@news.astraweb.com> <18d5d342-b678-4101-a284-24d6176ac856@v20g2000yqm.googlegroups.com> Message-ID: On Aug 12, 1:42 pm, Martin wrote: > On Aug 12, 1:23 pm, Steven D'Aprano > > > cybersource.com.au> wrote: > > On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote: > > > I tried > > > > re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s) > > > You need to put quotes around strings. > > > In this case, because you're using regular expressions, you should use a > > raw string: > > > re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) > > > will probably work. > > > -- > > Steven > > Thanks I see. > > so I tried it and if I use it as it is, it matches the first instance: > I > n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) > Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')] > > So I adjusted the first part of the regex, on the basis I could sub > NORTH for SOUTH etc. > > In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\. > \w-]+)",s) > Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')] > > But in both cases it doesn't return the decimal value rather the value > that comes after NUM_VAL = , rather than VALUE = ? I think I kind of got that to work...but I am clearly not quite understanding how it works as I tried to use it again to match something else. In this case I want to print the values 0.000000 and 2223901.039333 from a string like this... YDim=1200\n\t\tUpperLeftPointMtrs=(0.000000,2223901.039333)\n\t\t I tried which I though was matching the statement and printing the decimal number after the equals sign?? re.findall(r"(\w+UpperLeftPointMtrs)*=\s([\d\.\w-]+)", s) where s is the string Many thanks for the help From ethan at stoneleaf.us Wed Aug 12 12:46:32 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 12 Aug 2009 09:46:32 -0700 Subject: Social problems of Python doc [was Re: Python docs disappointing] In-Reply-To: References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <0292a134$0$20647$c3e8da3@news.astraweb.com> <3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com> <0292cb5a$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A82F1E8.3090105@stoneleaf.us> Paul Boddie wrote: > On 12 Aug, 17:08, Steven D'Aprano cybersource.com.au> wrote: >>It's not the people who suggest improvements to the docs that are the >>problem, but the ones who insist that the docs are terrible, but aren't >>willing to do anything but complain. Oh, and trolls like ... I hesitate >>to mention his name in case he has a bot monitoring the list ... first >>name starts with "X" followed by "ah", second name sounds like "Mee" ... >>who even if they make a few good points, they're lost in a sea of insults >>to others, arrogance and self-aggrandisement. > > > Right, but those good points are still worth taking on board. The responsibility for communication is shared. How much to each party varies by circumstance (employer/employee, rank, volunteer, etc.). For myself, his posts are automatically deleted -- my time is precious to me. ~Ethan~ From chris at simplistix.co.uk Wed Aug 12 12:53:56 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Wed, 12 Aug 2009 17:53:56 +0100 Subject: httplib incredibly slow :-( In-Reply-To: References: <4A81FDF5.6010508@simplistix.co.uk> <4A8274A9.7000905@simplistix.co.uk> Message-ID: <4A82F3A4.8020903@simplistix.co.uk> shaileshkumar wrote: > We use PyCURL on Windows. http://pycurl.sourceforge.net/ provides pre- > built versions for Windows and it works out of the box. Does it include libcurl? Are these builds available for Python 2.6? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From chris at simplistix.co.uk Wed Aug 12 12:57:16 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Wed, 12 Aug 2009 17:57:16 +0100 Subject: httplib incredibly slow :-( In-Reply-To: References: <4A81FDF5.6010508@simplistix.co.uk> <4A8274A9.7000905@simplistix.co.uk> Message-ID: <4A82F46C.4080105@simplistix.co.uk> Max Erickson wrote: > There is an httplib2 (but I don't know anything further about it...): > > http://code.google.com/p/httplib2/ I had a look, it uses httplib, so will likely suffer from the same problems... > Calling wget or curl using a subprocess is probably as easy as it is > ugly, I use the wget build from here: > > http://gnuwin32.sourceforge.net/packages/wget.htm Yeah, no ;-) Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From shaileshk at gmail.com Wed Aug 12 13:00:08 2009 From: shaileshk at gmail.com (Shailesh Kumar) Date: Wed, 12 Aug 2009 22:30:08 +0530 Subject: httplib incredibly slow :-( In-Reply-To: <4A82F3A4.8020903@simplistix.co.uk> References: <4A81FDF5.6010508@simplistix.co.uk> <4A8274A9.7000905@simplistix.co.uk> <4A82F3A4.8020903@simplistix.co.uk> Message-ID: <92e4c3710908121000y3bcc8de6w56f767d78aa34ba6@mail.gmail.com> Yes it includes libcurl. I didn't have to install it separately. I still continue to use Python 2.4. So cannot say about Python 2.6. - Shailesh On Wed, Aug 12, 2009 at 10:23 PM, Chris Withers wrote: > shaileshkumar wrote: > >> We use PyCURL on Windows. http://pycurl.sourceforge.net/ provides pre- >> built versions for Windows and it works out of the box. >> > > Does it include libcurl? Are these builds available for Python 2.6? > > Chris > > -- > Simplistix - Content Management, Batch Processing & Python Consulting > - http://www.simplistix.co.uk > -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.email at please.post Wed Aug 12 13:01:01 2009 From: no.email at please.post (kj) Date: Wed, 12 Aug 2009 17:01:01 +0000 (UTC) Subject: How to find all possibly overlapping matches? Message-ID: re.findall finds all non-overlapping matches, but what if one wants all (maximal) matches, even those that overlap? All the solutions I can come up involve calling re.search iteratively, each time giving it a pos parameter starting just after the start of the previous match. Is there a built-in solution to such a task? TIA! kynn From python at mrabarnett.plus.com Wed Aug 12 13:23:21 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 12 Aug 2009 18:23:21 +0100 Subject: How to find all possibly overlapping matches? In-Reply-To: References: Message-ID: <4A82FA89.1040503@mrabarnett.plus.com> kj wrote: > > re.findall finds all non-overlapping matches, but what if one wants > all (maximal) matches, even those that overlap? > > All the solutions I can come up involve calling re.search iteratively, > each time giving it a pos parameter starting just after the start > of the previous match. > > Is there a built-in solution to such a task? > Not in the re module. It has been requested and is in my regex implementation at http://bugs.python.org/issue2636 if you want to try that. From darkwater42 at gmail.com Wed Aug 12 13:23:50 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Wed, 12 Aug 2009 10:23:50 -0700 (PDT) Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <0291a21a$0$20639$c3e8da3@news.astraweb.com> <8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com> <1a0e1e6d-d902-4df7-8d35-850c4f62cc9c@e27g2000yqm.googlegroups.com> Message-ID: On Aug 12, 3:08?am, Steven D'Aprano wrote: > On Tue, 11 Aug 2009 14:48:24 -0700, Douglas Alan wrote: > > In any case, my argument has consistently been that Python should have > > treated undefined escape sequences consistently as fatal errors, > > A reasonable position to take. I disagree with it, but it is certainly > reasonable. > > > not as warnings. > > I don't know what language you're talking about here, because non-special > escape sequences in Python aren't either errors or warnings: > > >>> print "ab\cd" > > ab\cd I was talking about C++, whose compilers tend to generate warnings for this usage. I think that the C++ compilers I've used take the right approach, only ideally they should be *even* more emphatic, and elevate the problem from a warning to an error. I assume, however, that the warning is a middle ground between doing the completely right thing, and, I assume, maintaining backward compatibility with common C implementations. As Python never had to worry about backward compatibility with C, Python didn't have to walk such a middle ground. On the other hand, *now* it has to worry about backward compatibility with itself. |>ouglas From breamoreboy at yahoo.co.uk Wed Aug 12 13:31:12 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Aug 2009 18:31:12 +0100 Subject: best practice for documenting a project? pydoc? In-Reply-To: References: Message-ID: Esmail wrote: > Mark Lawrence wrote: > Hi Mark, > >> The docs for the constraint package look good, see >> http://labix.org/python-constraint and http://labix.org/doc/constraint. >> I think they've been produced with epydoc see >> http://epydoc.sourceforge.net/ > > Thanks for the links, I'll take a look. > > Any experience with something called HappyDoc? Just came across it. > > Esmail > > Sorry never heard of it, or if I had I've forgotten it. -- Kindest regards. Mark Lawrence. From davea at ieee.org Wed Aug 12 13:35:45 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 12 Aug 2009 13:35:45 -0400 Subject: fileinput In-Reply-To: References: Message-ID: <4A82FD71.70501@ieee.org> naaman wrote: > I'm writing my first Python script and > I want to use fileinput to open a file in r+ mode. > Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > ANy ideas? > > Need to find and overwrite a line in a file several times. > I can do it using open and seek() etc. but was wondering if I can use > fileinput. > > thanks; > > > I haven't used it, but check out the 'inplace' keyword parameter. DaveA From jstroud at mbi.ucla.edu Wed Aug 12 13:37:45 2009 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 12 Aug 2009 10:37:45 -0700 Subject: hashability In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > Well there you go -- why on earth would you prohibit None as a dictionary > key??? That's a serious failure. roentgen 1% python Python 2.5 (r25:51908, Sep 20 2006, 17:36:21) [GCC 3.4.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. py> hash(None) 135543872 mbi136-176 98% /usr/bin/python Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. py> hash(None) 2030240 That's why. Read the whole thread. You are one of the abrasive ones. From darkwater42 at gmail.com Wed Aug 12 13:47:55 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Wed, 12 Aug 2009 10:47:55 -0700 (PDT) Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <0291a21a$0$20639$c3e8da3@news.astraweb.com> <8152546e-1f6f-4ea5-9b10-e1d9b5ffdab8@t13g2000yqt.googlegroups.com> Message-ID: On Aug 12, 3:36?am, Steven D'Aprano wrote: > On Tue, 11 Aug 2009 13:20:52 -0700, Douglas Alan wrote: > > My "Annotated C++ Reference Manual" is packed, and surprisingly in > > Stroustrup's Third Edition, there is no mention of the issue in the > > entire 1,000 pages. But Microsoft to the rescue: > > > ? ? ?If you want a backslash character to appear within a string, you > > ? ? ?must type two backslashes (\\) > > > (From http://msdn.microsoft.com/en-us/library/69ze775t.aspx) > > Should I assume that Microsoft's C++ compiler treats it as an error, not > a warning? In my experience, C++ compilers generally generate warnings for such situations, where they can. (Clearly, they often can't generate warnings for running off the end of an array, which is also undefined, though a really smart C++ compiler might be able to generate a warning in certain such circumstances.) > Or is is this *still* undefined behaviour, and MS C++ compiler > will happily compile "ab\cd" whatever it feels like? If it's a decent compiler, it will generate a warning. Who can say with Microsoft, however. It's clearly documented as illegal code, however. > > The question of what any specific C++ does if you ignore the warning is > > irrelevant, as such behavior in C++ is almost *always* undefined. Hence > > the warning. > > So a C++ compiler which follows Python's behaviour would be behaving > within the language specifications. It might be, but there are also *recommendations* in the C++ standard about what to do in such situations, and the recommendations say, I am pretty sure, not to do that, unless the particular compiler in question has to meet some very specific backward compatibility needs. > I note that the bash shell, which claims to follow C semantics, also does > what Python does: > > $ echo $'a s\trin\g with escapes' > a s ? ? rin\g with escapes Really? Not on my computers. (One is a Mac, and the other is a Fedora Core Linux box.) On my computers, bash doesn't seem to have *any* escape sequences, other than \\, \", \$, and \`. It seems to treat unknown escape sequences the same as Python does, but as there are only four known escape sequences, and they are all meant merely to guard against string interpolation, and the like, it's pretty darn easy to keep straight. > Explain to me again why we're treating underspecified C++ semantics, > which may or may not do *exactly* what Python does, as if it were the One > True Way of treating escape sequences? I'm not saying that C++ does it right for Python. The right thing for Python to do is to generate an error, as Python doesn't have to deal with all the crazy complexities that C++ has to. |>ouglas From clp2 at rebertia.com Wed Aug 12 13:50:33 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 12 Aug 2009 13:50:33 -0400 Subject: hashability In-Reply-To: References: Message-ID: <50697b2c0908121050w6fe89277n9f9b76b28f937f83@mail.gmail.com> On Wed, Aug 12, 2009 at 1:37 PM, James Stroud wrote: > Steven D'Aprano wrote: >> >> Well there you go -- why on earth would you prohibit None as a dictionary >> key??? That's a serious failure. > > > roentgen 1% python > Python 2.5 (r25:51908, Sep 20 2006, 17:36:21) [GCC 3.4.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > py> hash(None) > 135543872 > > > mbi136-176 98% /usr/bin/python > Python 2.5.1 (r251:54863, Feb ?6 2009, 19:02:12) [GCC 4.0.1 (Apple Inc. > build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > py> hash(None) > 2030240 Actually, None is a special-case as a built-in singleton value -- there's only ever *exactly one* instance of it in a given interpreter session. And I'm reasonably sure dict pickles don't store the hash code of items (the dict gets recreated from scratch), so there's no problem. Cheers, Chris -- http://blog.rebertia.com From no.email at please.post Wed Aug 12 14:00:16 2009 From: no.email at please.post (kj) Date: Wed, 12 Aug 2009 18:00:16 +0000 (UTC) Subject: How to find all possibly overlapping matches? References: Message-ID: In MRAB writes: >kj wrote: >> >> re.findall finds all non-overlapping matches, but what if one wants >> all (maximal) matches, even those that overlap? >> >> All the solutions I can come up involve calling re.search iteratively, >> each time giving it a pos parameter starting just after the start >> of the previous match. >> >> Is there a built-in solution to such a task? >> >Not in the re module. >It has been requested and is in my regex implementation at >http://bugs.python.org/issue2636 if you want to try that. Cool. Thanks! kynn From abecedarian314159 at yahoo.com Wed Aug 12 14:08:17 2009 From: abecedarian314159 at yahoo.com (William) Date: Wed, 12 Aug 2009 11:08:17 -0700 (PDT) Subject: SQLObject 0.11.0 In-Reply-To: <20090812102452.GE5602@phd.pp.ru> References: <20090812102452.GE5602@phd.pp.ru> Message-ID: <630942.37631.qm@web110607.mail.gq1.yahoo.com> I don't want to start a flame war and would just like some information before diving in-- What are some the advantages and disadvantages of SQLObject compared to SQLAlchemy? Thanks, William ________________________________ From: Oleg Broytmann To: Python Mailing List ; Python Announce Mailing List Sent: Wednesday, August 12, 2009 6:24:53 AM Subject: SQLObject 0.11.0 Hello! I'm pleased to announce version 0.11.0, the first stable release of 0.11 branch of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.11.0 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.10 ----------------- Features & Interface ~~~~~~~~~~~~~~~~~~~~ * Dropped support for Python 2.3. The minimal version of Python for SQLObject is 2.4 now. * Dropped support for PostgreSQL 7.2. The minimal supported version of PostgreSQL is 7.3 now. * New magic attribute 'j' similar to 'q' was added that automagically does join with the other table in MultipleJoin or RelatedJoin. * SQLObject can now create and drop a database in MySQL, PostgreSQL, SQLite and Firebird/Interbase. * Added some support for schemas in PostgreSQL. * Added DecimalStringCol - similar to DecimalCol but stores data as strings to work around problems in some drivers and type affinity problem in SQLite. * Added sqlobject.include.hashcol.HashCol - a column type that automatically hashes anything going into it, and returns out an object that hashes anything being compared to itself. Basically, it's good for really simple one-way password fields, and it even supports the assignment of None to indicate no password set. By default, it uses the md5 library for hashing, but this can be changed in a HashCol definition. * RowDestroyedSignal and RowUpdatedSignal were added. Minor features ~~~~~~~~~~~~~~ * Use reversed() in manager/command.py instead of .__reversed__(). * Minor change in logging to console - logger no longer stores the output file, it gets the file from module sys every time by name; this means logging will use new sys.stdout (or stderr) in case the user changed them. * Changed the order of testing of SQLite modules - look for external PySQLite2 before sqlite3. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Wed Aug 12 14:11:40 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Aug 2009 18:11:40 GMT Subject: hashability References: Message-ID: <0292f646$0$20647$c3e8da3@news.astraweb.com> On Wed, 12 Aug 2009 10:37:45 -0700, James Stroud wrote: > Steven D'Aprano wrote: >> Well there you go -- why on earth would you prohibit None as a >> dictionary key??? That's a serious failure. > > > roentgen 1% python > Python 2.5 (r25:51908, Sep 20 2006, 17:36:21) [GCC 3.4.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > py> hash(None) > 135543872 > > > mbi136-176 98% /usr/bin/python > Python 2.5.1 (r251:54863, Feb 6 2009, 19:02:12) [GCC 4.0.1 (Apple Inc. > build 5465)] on darwin Type "help", "copyright", "credits" or "license" > for more information. py> hash(None) > 2030240 > > > > That's why. Read the whole thread. You are one of the abrasive ones. I've read the whole thread. Pay close attention: [steve at ando ~]$ python Python 2.4.3 (#1, Mar 14 2007, 18:51:08) [GCC 4.1.1 20070105 (Red Hat 4.1.1-52)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pickle >>> d = {None: 42} >>> f = open('pickled_dict', 'w') >>> pickle.dump(d, f) >>> f.close() >>> [steve at ando ~]$ ssh sylar steve at sylar's password: Last login: Wed Aug 12 21:44:47 2009 [steve at sylar ~]$ python2.6 Python 2.6.1 (r261:67515, Dec 24 2008, 00:33:13) [GCC 4.1.2 20070502 (Red Hat 4.1.2-12)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import pickle >>> f = open('pickled_dict', 'r') >>> d = pickle.load(f) >>> d {None: 42} I have successfully pickled a dict using None as a key on one machine using Python 2.4, and unpickled it on a completely different machine running Python 2.6. Still think that pickling None is a problem? -- Steven From schwehr at gmail.com Wed Aug 12 14:11:49 2009 From: schwehr at gmail.com (Kurt Schwehr) Date: Wed, 12 Aug 2009 11:11:49 -0700 (PDT) Subject: Pulling arrays from database for plotting Message-ID: <64fa9d35-a08b-4112-ba84-131f0f29c0f4@o15g2000yqm.googlegroups.com> Hi all, What's the best way to pull arrays from a database for plotting? Right now, this is what I do, but can it be done simpler / more efficiently? ipython -pylab import sqlite3 cx = sqlite3.connect('20080407.decimated.db3') a = array( [tuple(row) for row in cx.execute('SELECT cg_offset, delta_t_sec FROM bs_time WHERE recvr=2;')] ) x = a[:,0] y = a[:,1] plot(x,y) However, if I try to plot it directly using transpose, it hangs: import sqlite3 cx = sqlite3.connect('20080407.decimated.db3') plot(array( [tuple(row) for row in cx.execute('SELECT cg_offset, delta_t_sec FROM bs_time WHERE recvr=2;')] ).transpose()) It is that plot just doesn't know what to do with a 2D array? Then I tried this and it works, but is long and confusing to the uninitiated. plot(*array( [tuple(row) for row in cx.execute('SELECT cg_offset, delta_t_sec FROM bs_time WHERE recvr=2;')] ).T) In [4]: a Out[4]: array([[ 2.40000000e+01, 0.00000000e+00], [ 2.50000000e+01, -1.00000000e+00], [ 3.40000000e+01, 0.00000000e+00], ..., [ 8.63840000e+04, 2.00000000e+01], [ 8.63940000e+04, 2.00000000e+01], [ 8.64040000e+04, 2.00000000e+01]]) In [5]: a.transpose() Out[5]: array([[ 2.40000000e+01, 2.50000000e+01, 3.40000000e+01, ..., 8.63840000e+04, 8.63940000e+04, 8.64040000e+04], [ 0.00000000e+00, -1.00000000e+00, 0.00000000e+00, ..., 2.00000000e+01, 2.00000000e+01, 2.00000000e+01]]) From python at rcn.com Wed Aug 12 14:27:42 2009 From: python at rcn.com (Raymond Hettinger) Date: Wed, 12 Aug 2009 11:27:42 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> Message-ID: <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> On Aug 12, 3:32?am, Paul Boddie wrote: > Maybe the problem is that although everyone welcomes contributions and > changes (or says that they do), the mechanisms remain largely beyond > criticism. FWIW, I support the idea the regular docs incorporating links to freely editable wiki pages. That will at least make it easier for people to make changes or add notes. That being said, I would like to add a few thoughts about the current process. ISTM that important corrections (when the docs are clearly in error) tend to get made right away. What is more interesting are the doc requests that get rejected and why: * Many doc requests come from people just learning the language (that makes sense because the learning process involves reading the docs). Unfortunately, a fair number of those requests are flat-out wrong or represent a profound misunderstanding of the feature in question. That may be an indicator that the docs need to be improved, but the specific suggestion can be inane. * Some doc requests come from people who simply do not like the feature in question. It is natural for tastes, styles, and preferences to vary; however, we do have a firm rule that Guido's tastes, styles, and preferences are the ones that go into the language. So the doc writers need to try to channel Guido instead of fighting him. So, if you think eval() is evil (I don't but many do), we're not going to document that eval() should *never* be used. If you hate super(), that's too bad -- the docs need to describe what it does and how it was intended to be used -- the docs are no place for diatribes on why inheritance is over-used and why you think the world would be a better place without mixins or multiple inheritance. * Then, there is a matter of where to put a particular piece of documentation (how many times do you repeat a concept that pervades the language). Hashing is a good example. The docs can discuss how some objects hash to their object id and that object ids can change from run-to-run, but if someone gets tripped-up by the idea (hey, my set reprs changed between runs, wtf!), they want the docs updated in the specific place that tripped them up (i.e. you must put big red warnings in the set documentation, and the dict documentation, and everywhere else a hash gets used ...). The core problem is that the docs are interrelated -- the one place you're looking for documentation of a specific builtin or function can't contain every concept in the language. * Some behaviors are intentionally left unspecified. For the longest time, Tim did not want to guarantee sort stability. This left him free to continue to search for algorithmic improvements that did not have stability. Later, the property was deemed so important that it did become a guaranteed behavior. Also, some things are unspecified to make things easier for other implementations (IronPython, PyPy, Jython, etc.) We need to make sure that some one doesn't casually go through the docs making doc promises that are hard to keep. * Some things are just plain difficult to fully explain in English and not misrepresent that actual behavior. For example, the str.split () docs have been continuously tweaked over the years. Even now, I think there are corner cases that are not fully captured by the docs. Casual edits to str.split() docs are more likely than not to take them farther away from the truth. * Then, there is the problem of talking too much. A book could be written about super(), but that shouldn't all go into the docs for the super builtin. Beginners often want to master all the builtins and they try to read the doc page on builtin functions. It used to be that you could read through the builtin descriptions in a few minutes. Now, it takes a concerted effort to get through. It is hard to take a sip of water from a firehose. Too much information has make a function harder to understand. * My biggest pet peeve are requests to fill the docs with big red warnings. I do not want the docs to look like a mine field. The warnings should be reserved for a handful of security or data corruption risks. For the most part, the docs should be matter-of-fact, explaining what a function or method does and how it was intended to be used. Preferred: "The value str.letters is locale dependent" Not preferred: "Caution, the str.letters value can be adversely affected by the locale setting (it could even change length!); use this only when you are certain the locale setting will not violate any of your program invariants; consider using a string literal instead; I hate string.letters and think Guido was smoking crack when it was introduced." * Another category of rejected doc requests come from people looking for absolution from one of their programming bugs. It typically takes the form of, "I made an assumption that the language did X, but it did Y and my program didn't do what I wanted; therefore, the docs must be to blame and they must change ...". The suggestion is "I was suprised" implies "the docs are hosed". The fact is that people with diffferent backgrounds are going to have different expectations and someone is going to get "surprised". The docs need to say what functions do, but they don't need to be changed everytime someone writes a buggy program. In short, most doc requests that get rejected are requests that didn't actually improve the documentation. I do support links from the regular docs to an external wiki but the main docs should continue to go through the regular process using the tracker. Raymond From fetchinson at googlemail.com Wed Aug 12 14:40:01 2009 From: fetchinson at googlemail.com (Daniel Fetchinson) Date: Wed, 12 Aug 2009 11:40:01 -0700 Subject: SQLObject 0.11.0 In-Reply-To: <630942.37631.qm@web110607.mail.gq1.yahoo.com> References: <20090812102452.GE5602@phd.pp.ru> <630942.37631.qm@web110607.mail.gq1.yahoo.com> Message-ID: > I don't want to start a flame war and would just like some information > before diving in-- > What are some the advantages and disadvantages of SQLObject compared to > SQLAlchemy? In short: sqlobject is much simpler (to use, to understand, etc) than sqlalchemy and so I prefer it in small projects. This advantage is also a disadvantage when you have large and complex projects in mind. Cheers, Daniel -- Psss, psss, put it down! - http://www.cafepress.com/putitdown From pavlovevidence at gmail.com Wed Aug 12 14:41:51 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Aug 2009 11:41:51 -0700 (PDT) Subject: hashability References: Message-ID: <1797a24d-7437-4a5c-bb67-9a81abb095c0@p10g2000prm.googlegroups.com> On Aug 12, 10:37?am, James Stroud wrote: > Steven D'Aprano wrote: > > Well there you go -- why on earth would you prohibit None as a dictionary > > key??? That's a serious failure. > > roentgen 1% python > Python 2.5 (r25:51908, Sep 20 2006, 17:36:21) > [GCC 3.4.2] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > py> hash(None) > 135543872 > > mbi136-176 98% /usr/bin/python > Python 2.5.1 (r251:54863, Feb ?6 2009, 19:02:12) > [GCC 4.0.1 (Apple Inc. build 5465)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > py> hash(None) > 2030240 > > That's why. Read the whole thread. You are one of the abrasive ones. FYI: If you need the actual hash value to be consistent across versions of Python the built hash function won't suffice. The language doesn't guanrantee they will persist across versions. (IIRC, there was a change to the hash value of longs at one point related to int/long unification issues.) Now, when I saw your explanation I assumed that your persistence mechanism merely doesn't preserve identity (unlike, say, simple pickling, which does), meaning that objects that were once identical might be reconstituted as non-identical (or vice versa), which would be an issue if these objects are stored in dicts or sets. Equality must be preserved for dict keys and set members to continue to work property. However, the actual hash code doesn't need to be preserved. As was mentioned already, None is guaranteed by the language to be equal to itself, so equality is preserved and there should be no issue with it, even if the hash code changes across invocations. Now, if you are doing something weird with the hash value itself-- which I highly discourage--then all bets are off. Carl Banks From python at rcn.com Wed Aug 12 15:15:07 2009 From: python at rcn.com (Raymond Hettinger) Date: Wed, 12 Aug 2009 12:15:07 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> Message-ID: <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> [Xah Lee] > i've wrote several articles about this issue, total time spend on this > is probably more than 2 months full-time work. See: > > ? Python Documentation Problems > ?http://xahlee.org/perl-python/python_doc_index.html I just read you post. You did devote a substantial amount of time to the project. Some of your criticisms are valid. Wish you had posted patches, I think many of them would have been accepted. Since you wrote this a few years ago, many examples have been added to the docs and more are forthcoming. > I often receive thank you emails for 2 particular articles, which are > most frequently google searched as indicated by my weblog: > > ? Python Doc Problem Example: gzip > ?http://xahlee.org/perl-python/python_doc_gzip.html > > ? Python Doc Problem Example: sort() > ?http://xahlee.org/perl-python/python_doc_sort.html > > ? Sorting in Python and Perl > ?http://xahlee.org/perl-python/sort_list.html Some are the criticisms are valid; others seem off-base. Here are a few thoughts on list.sort() for those who are interested: * The key= and reversed= parameters are not intended for special cases, leaving cmp= for the general case. They were intended to be full replacements. In Python3.x, the cmp function is gone. * The interaction of the key= and cmp= functions can be made to interact (the key function is first applied to every element and the cmp function then gets applied to the results of the key function). This isn't a normal or intended use case, so the docs don't delve into the subject. * The reversed parameter does more than list.sort() followed by list.reverse(). It also preserves stability in the event of equal keys: >>> sorted([(1,2), (1,3)], key=itemgetter(0), reverse=True) [(1,2), (1,3)] So it was not correct to say that the following are equivalent: li.sort(lambda x, y: cmp(x[1],y[1]), reverse=True) li.sort(lambda x, y: cmp(y[1],x[1])) * We should link the sorted() and list.sort() docs to the sorting how-to (with a fuller discussion on the art of sorting including a discussion of operator.itemgetter() and operator.attrgetter() which were designed to work with the key= parameter. Raymond From mwkohout at gmail.com Wed Aug 12 15:44:51 2009 From: mwkohout at gmail.com (Michael Kohout) Date: Wed, 12 Aug 2009 12:44:51 -0700 (PDT) Subject: Extending embedded python-can extensions be local to a dictionary? Message-ID: <9d65250a-d4fa-440d-83ac-b22430284dab@24g2000yqm.googlegroups.com> Hello all- I've got a multithreaded server-based application that I'd like to use python to provide plugin support for. At execution time I would like each call to the plugin/plugins to have their own implementation of these extension methods. Looking at http://docs.python.org/extending/embedding.html#extending-embedded-python, I see how to add functions, but it looks like they are added at a global scope-not in a particular environment. Is there any way to add an extension to a local environment but not pollute the global env? FYI, I'm embedding python 2.6, but I'm more than open to embedding something newer. thanks Mike Kohout From rt8396 at gmail.com Wed Aug 12 16:14:51 2009 From: rt8396 at gmail.com (r) Date: Wed, 12 Aug 2009 13:14:51 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> Message-ID: <2fe731f6-8640-4e5c-bf39-62b22d635003@32g2000yqj.googlegroups.com> On Aug 12, 1:27?pm, Raymond Hettinger wrote: (snip) > * Many doc requests come from people just learning the language > (that makes sense because the learning process involves reading > the docs). ?Unfortunately, a fair number of those requests are > flat-out wrong or represent a profound misunderstanding of the > feature in question. ?That may be an indicator that the docs > need to be improved... Yes, if many people have problems with the docs then that must be a *clue* to some underling problem in the way the docs are presented. Whether its from misinfomation, misguidance, or just plain misunderstanding on the reader's part that does not matter. There are problems and we need the feedback from everybody noob-to-pro on how to fix this conundrum. One thing that some naysayers may forget is the fact that these noobs most likely have no idea *how*, *when*, or *where* to voice a complaint so they just move on to the next language or suffer with an incomplete understanding of the language and/or proper python idioms. I would say the complaints that this list has seen concerning docs only scratches the surface of the huge underling issues that face us here! > So, if you think eval() is evil (I don't but many > do), we're not going to document that eval() should *never* be used. > If you hate super(), that's too bad -- the docs need to describe > what it does and how it was intended to be used -- the docs are no > place for diatribes on why inheritance is over-used and why you > think the world would be a better place without mixins or > multiple inheritance. Eloquent and beautiful a paragraph that was Raymond. Why, because common sense is just so damn beautiful. Keep the docs clean of personal opinions and just give us the facts people. Who cares about the history of OOP --Google it!-- i want to read about using Python. Give me the nitty-gritty-down-and-dirty-facts that relate to Python syntax and structure, and only the facts, in the most strait forward and common sense way so i can get on to actually writing some code! If you seek self gratification visit c.l.py and vent away, everyone else seems to. From jschwab at gmail.com Wed Aug 12 16:34:19 2009 From: jschwab at gmail.com (jschwab) Date: Wed, 12 Aug 2009 13:34:19 -0700 (PDT) Subject: Format Code Repeat Counts? Message-ID: Are repeat counts supported Python's str.format() in some fashion? In Fortran my format strings can have repeat counts. write(*, fmt="3F8.3") [1, 2, 3] 1.000 2.000 3.000 I don't think printf-style format codes, which is what'd I'd previously used in Python, allow for repeat counts. As a more concrete example, say I have several sets of letters in a list of strings letters = ["aeiou", "hnopty", "egs", "amsp"] and I wanted to build a regular expression string out of them like re_str <==> "[aeiou][hnopty][egs][amsp]" Right now, the best I've got that doesn't require an explicit string like "[{1}][{2}][{3}][{4}]" is re_str = "".join(map(lambda x: "[{0}]".format(x), letters)) Is there a better way? Thanks, Josiah From alan.isaac at gmail.com Wed Aug 12 16:45:43 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Wed, 12 Aug 2009 20:45:43 GMT Subject: csv.DictWriter.write_header() Message-ID: Given a csv.DictWriter instance `dw` I think it would be nice to be able to say dw.write_header() instead of dw.writer.writerow(dw.fieldnames) Good idea? Alan Isaac From bernard.chhun at gmail.com Wed Aug 12 16:53:41 2009 From: bernard.chhun at gmail.com (Bernard) Date: Wed, 12 Aug 2009 13:53:41 -0700 (PDT) Subject: matching patterns after regex? References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com> <2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com> <0292a4a9$0$20647$c3e8da3@news.astraweb.com> <18d5d342-b678-4101-a284-24d6176ac856@v20g2000yqm.googlegroups.com> Message-ID: <85652297-16e7-489f-9e36-5092941df002@c34g2000yqi.googlegroups.com> On 12 ao?t, 12:43, Martin wrote: > On Aug 12, 1:42 pm, Martin wrote: > > > > > > > On Aug 12, 1:23 pm, Steven D'Aprano > > cybersource.com.au> wrote: > > > On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote: > > > > I tried > > > > > re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s) > > > > You need to put quotes around strings. > > > > In this case, because you're using regular expressions, you should use a > > > raw string: > > > > re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) > > > > will probably work. > > > > -- > > > Steven > > > Thanks I see. > > > so I tried it and if I use it as it is, it matches the first instance: > > I > > n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) > > Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')] > > > So I adjusted the first part of the regex, on the basis I could sub > > NORTH for SOUTH etc. > > > In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\. > > \w-]+)",s) > > Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')] > > > But in both cases it doesn't return the decimal value rather the value > > that comes after NUM_VAL = , rather than VALUE = ? > > I think I kind of got that to work...but I am clearly not quite > understanding how it works as I tried to use it again to match > something else. > > In this case I want to print the values 0.000000 and 2223901.039333 > from a string like this... > > YDim=1200\n\t\tUpperLeftPointMtrs=(0.000000,2223901.039333)\n\t\t > > I tried which I though was matching the statement and printing the > decimal number after the equals sign?? > > re.findall(r"(\w+UpperLeftPointMtrs)*=\s([\d\.\w-]+)", s) > > where s is the string > > Many thanks for the help You have to do it with 2 matches in the same regex: regex = r"UpperLeftPointMtrs=\(([\d\.]+),([\d\.]+)" The first match is before the , and the second one is after the , :) You should probably learn how to play with regexes. I personnaly use a visual tool called RX Toolkit[1] that comes with Komodo IDE. [1] http://docs.activestate.com/komodo/4.4/regex.html From pavlovevidence at gmail.com Wed Aug 12 16:57:53 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 12 Aug 2009 13:57:53 -0700 (PDT) Subject: Extending embedded python-can extensions be local to a dictionary? References: <9d65250a-d4fa-440d-83ac-b22430284dab@24g2000yqm.googlegroups.com> Message-ID: <56b8b9d3-9166-4dc3-8166-1e60861d00b0@k26g2000vbp.googlegroups.com> On Aug 12, 12:44?pm, Michael Kohout wrote: > Hello all- > > I've got a multithreaded server-based application that I'd like to use > python to provide plugin support for. ?At execution time I would like > each call to the plugin/plugins to have their own implementation of > these extension methods. I am guessing that what you really want is each call to have its own data. There isn't much reason for each call to have its own methods. If that's not correct you will have to elaborate. > Looking athttp://docs.python.org/extending/embedding.html#extending-embedded-py..., > I see how to add functions, but it looks like they are added at a > global scope-not in a particular environment. ?Is there any way to add > an extension to a local environment but not pollute the global env? A couple things. They're not in a global scope, "globals" in Python have a scope local to a module (global is a misnomer, at best it means "globally accessible"). So you don't have to worry about a function defined on one module clashing with a function defined in another modules. However, even if name-clashes aren't an issue there isn't much point to defining the same function mulitple times for multiple calls. What you probably want is to define a new type that contains all the data extension code would need. For each call to the plugin, you would create an object of this type, then pass it to the appropriate plugin function. I have given you a vague answer because your question was vague; if you want a better answer please rephrase to be more specific. Include details like what you would like the code of a Python plugin to look like. Carl Banks From davigier at googlemail.com Wed Aug 12 17:09:29 2009 From: davigier at googlemail.com (David) Date: Wed, 12 Aug 2009 14:09:29 -0700 (PDT) Subject: How to launch a function at regular time intervals ? Message-ID: Hi all, I'm trying to launch a function at regular time intervals but cannot find the way to do it. Here is the code I wrote (time_interval is a user defined variable in seconds): while(1) timestamp=datetime.now() timestamp_seconds=timestamp.hour*3600+timestamp.minute*60+timestamp.second if timestamp_seconds % time_interval == 0: ****Call Function**** This does not work because during the second at which the condition holds true, there is time to call the function several times. Since I want to have this function called only once every x seconds, I tried to add the following condition: if timestamp_seconds % time_interval ==0 & timestamp.microsecond == 0 But it seems this second condition hardly ever happens (i.e. the timestamp variable is not updated every microsecond, therefore it can be 9998 then jump directly to 0003 for instance). Has anyone run into a similar problem (and solved it) ? Thanks for your help From darkwater42 at gmail.com Wed Aug 12 17:21:34 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Wed, 12 Aug 2009 14:21:34 -0700 (PDT) Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com> Message-ID: <7877b03a-09da-4836-804c-502b6f78003c@h21g2000yqa.googlegroups.com> On Aug 12, 5:32 am, Steven D'Aprano wrote: > That problem basically boils down to a deep-seated > philosophical disagreement over which philosophy a > language should follow in regard to backslash escapes: > > "Anything not explicitly permitted is forbidden" > > versus > > "Anything not explicitly forbidden is permitted" No, it doesn't. It boils down to whether a language should: (1) Try it's best to detect errors as early as possible, especially when the cost of doing so is low. (2) Make code as readable as possible, in part by making code as self-evident as possible by mere inspection and by reducing the amount of stuff that you have to memorize. Perl fails miserably in this regard, for instance. (3) To quote Einstein, make everything as simple as possible, and no simpler. (4) Take innately ambiguous things and not force them to be unambiguous by mere fiat. Allowing a programmer to program using a completely arbitrary resolution of "unrecognized escape sequences" violates all of the above principles. The fact that the meanings of unrecognized escape sequences are ambiguous is proved by the fact that every language seems to treat them somewhat differently, demonstrating that there is no natural intuitive meaning for them. Furthermore, allowing programmers to use "unrecognized escape sequences" without raising an error violates: (1) Explicit is better than implicit: Python provides a way to explicitly specify that you want a backslash. Every programmer should be encouraged to use Python's explicit mechanism here. (2) Simple is better than complex: Python currently has two classes of ambiguously interpretable escape sequences: "unrecognized ones", and "illegal" ones. Making a single class (i.e. just illegal ones) is simpler. Also, not having to memorize escape sequences that you rarely have need to use is simpler. (3) Readability counts: See above comments on readability. (4) Errors should never pass silently: Even the Python Reference Manual indicates that unrecognized escape sequences are a source of bugs. (See more comments on this below.) (5) In the face of ambiguity, refuse the temptation to guess. Every language, other than C++, is taking a guess at what the programmer would find to be most useful expansion for unrecognized escape sequences, and each of the languages is guessing differently. This temptation should be refused! You can argue that once it is in the Reference Manual it is no longer a guess, but that is patently specious, as Perl proves. For instance, the fact that Perl will quietly convert an array into a scalar for you, if you assign the array to a scalar variable is certainly a "guess" of the sort that this Python koan is referring to. Likewise for an arbitrary interpretation of unrecognized escape sequences. (6) There should be one-- and preferably only one --obvious way to do it. What is the one obvious way to express "\\y"? It is "\\y" or "\y"? Python can easily make one of these ways the "one obvious way" by making the other one raise an error. (7) Namespaces are one honking great idea -- let's do more of those! Allowing "\y" to self-expand is intruding into the namespace for special characters that require an escape sequence. > C++ apparently forbids all escape sequences, with > unspecified behaviour if you use a forbidden sequence, > except for a handful of explicitly permitted sequences. > > That's not better, it's merely different. It *is* better, as it catches errors early on at little cost, and for all the other reasons listed above. > Actually, that's not true -- that the C++ standard forbids > a thing, but leaves the consequences of doing that thing > unspecified, is clearly a Bad Thing. Indeed. But C++ has backward compatibly issues that make any that Python has to deal with, pale in comparison. The recommended behavior for a C++ compiler, however, is to flag the problem as an error or as a warning. > So on at least one machine in the world, C++ simply strips > out backslashes that it doesn't recognize, leaving the > suffix. Unfortunately, we can't rely on that, because C++ > is underspecified. No, *fortunately* you can't rely on it, forcing you to go fix your code. > Fortunately this is not a problem with > Python, which does completely specify the behaviour of > escape sequences so there are no surprises. It's not a surprise when the C++ compiler issues a warning to you. If you ignore the warning, then you have no one to blame but yourself. > Implicit has an actual meaning. You shouldn't use it as a > mere term of opprobrium for anything you don't like. Pardon me, but I'm using "implicit" to mean "implicit", and nothing more. Python's behavior here is "implicit" in the very same way that Perl implicitly converts an array into a scalar for you. (Though that particular Perl behavior is a far bigger wart than Python's behavior is here!) > > Because you've stated that "\y" is a legal escape > > sequence, while the Python Reference Manual explicitly > > states that it is an "unrecognized escape sequence", and > > that such "unrecognized escape sequences" are sources of > > bugs. > > There's that reading comprehension problem again. > > Unrecognised != illegal. This is reasoning that only a lawyer could love. The right thing for a programming language to do, when handed something that is syntactically "unrecognized" is to raise an error. > It seems to me that the behaviour the Python designers > were looking to avoid was the case where the coder > accidentally inserted a backslash in the wrong place, and > the language stripped the backslash out, e.g.: > > Wanted "a\bcd" but accidentally typed "ab\cd" instead, and > got "abcd". The moral of the story is that *any* arbitrary interpretation of unrecognized escape sequences is a potential source of bugs. In Python, you just end up with a converse issue, where one might understandably assume that "foo\bar" has a backslash in it, because "foo\yar" and *most* other similar strings do. But then it doesn't. > >> This is *exactly* like C++, except that in Python the > >> semantics of \y and \\y are identical. Python doesn't > >> guess what you mean, it *imposes* a meaning on the > >> escape sequence. You just don't like that meaning. > > That's because I don't like things that are > > ill-conceived. > And yet you like C++... go figure *wink* Now that's a bold assertion! I think that "tolerate C++" is more like it. But C++ does have its moments. |>ouglas From python at rcn.com Wed Aug 12 17:24:29 2009 From: python at rcn.com (Raymond Hettinger) Date: Wed, 12 Aug 2009 14:24:29 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> Message-ID: <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> [Raymond Hettinger] > Here are a few thoughts on list.sort() for those who are interested: After one more reading of Xah Lee's posts on the documentation for sort, here are couple more thoughts: * The reason that list.sort() allows None for the cmp parameter is not so that you can write list.sort(None). It was put there to make it easier for people writing function definitions where the cmp function is a possible argument: def sort_and_chop(seq, maxlen, cmp=None): s = seq[:] s.sort(cmp) # needs to accept None as a possible argument return s[:maxlen] * The reason for implementing the key= parameter had nothing to do with limitations of Python's compiler. Instead, it was inspired by the decorate-sort-undecorate pattern. Raymond From senad.ibraimoski at gmail.com Wed Aug 12 17:27:54 2009 From: senad.ibraimoski at gmail.com (Senad Ibraimoski -student-Mathematical Institute Belgrade) Date: Wed, 12 Aug 2009 14:27:54 -0700 (PDT) Subject: Plotting Quadratic Functions, pygame Message-ID: Hello, I'm a new guy to this group, my professor recommend this group to me, because I was boring him with questions.I'm new to python, and I have problem plotting Quadratic Functions. Using module pygame. Here is the code: #!/usr/bin/env python import pygame def main(): import sys import math from math import sqrt #Input equation coefficients screen=pygame.display.set_mode((400,400)) pygame.display.set_caption( ' Ploting ' ) screen.fill((255,255,255)) pen=((0,0,255)) dark=(0,0,0) ox=200 oy=200 a= int(raw_input('Input coefficient a ' )) b= int(raw_input('Input coefficient b ' )) c= int(raw_input('Input coefficient c ' )) pygame.draw.aaline(screen,((255,0,0)),((200,0)) ,((200,400))) pygame.draw.aaline(screen,((255,0,0)),((0,200)), ((400,200))) if a==0: if b==0: print 'No solutions' else: x= -c/b print x else: d=b*b-4*a*c if d<0: num=complex(-b/(2*a),sqrt(-d)/(2*a)) print num else: x1=(-b+sqrt(d))/(2*a) x2=(-b-sqrt(d))/(2*a) print 'x1= ' ,x1 print 'x2= ' ,x2 while 1: for event in pygame.event.get(): if event ==pygame.QUIT: print ' Quitting' pygame.quit() sys.exit(1) x=-50; while x<=50: y=(a*(x**2) + b*x + c) *(-1) screen.set_at(((x+ox),(y+oy)),dark) pygame.display.flip() x=x+1; return 0 if __name__ == '__main__': main() For now I'm plotting function only when Determinant >0. Or in other words, when equation has two solutions, x1,x2 e R... Now if you start my program you will see where problem is. It's with function, It so bad drawn. When I try to increment x in loop by 0.1 for every pass, I get problems because method set_at() Which sets pixel requires integer... Also I see I have problems with event handling here: while 1: for event in pygame.event.get(): if event ==pygame.QUIT: print ' Quitting' pygame.quit() sys.exit(1) When I click X, or exit on windows it doesn't exit. What do you suggest I do...? I don't have in this year Computer Graphics on my faculty. So this are my first steps in this area of CS. Regards, S.I From breamoreboy at yahoo.co.uk Wed Aug 12 17:29:11 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Wed, 12 Aug 2009 22:29:11 +0100 Subject: matching patterns after regex? In-Reply-To: <85652297-16e7-489f-9e36-5092941df002@c34g2000yqi.googlegroups.com> References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com> <2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com> <0292a4a9$0$20647$c3e8da3@news.astraweb.com> <18d5d342-b678-4101-a284-24d6176ac856@v20g2000yqm.googlegroups.com> <85652297-16e7-489f-9e36-5092941df002@c34g2000yqi.googlegroups.com> Message-ID: Bernard wrote: > On 12 ao?t, 12:43, Martin wrote: >> On Aug 12, 1:42 pm, Martin wrote: >> >> >> >> >> >>> On Aug 12, 1:23 pm, Steven D'Aprano >> cybersource.com.au> wrote: >>>> On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote: >>>>> I tried >>>>> re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s) >>>> You need to put quotes around strings. >>>> In this case, because you're using regular expressions, you should use a >>>> raw string: >>>> re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) >>>> will probably work. >>>> -- >>>> Steven >>> Thanks I see. >>> so I tried it and if I use it as it is, it matches the first instance: >>> I >>> n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) >>> Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')] >>> So I adjusted the first part of the regex, on the basis I could sub >>> NORTH for SOUTH etc. >>> In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\. >>> \w-]+)",s) >>> Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')] >>> But in both cases it doesn't return the decimal value rather the value >>> that comes after NUM_VAL = , rather than VALUE = ? >> I think I kind of got that to work...but I am clearly not quite >> understanding how it works as I tried to use it again to match >> something else. >> >> In this case I want to print the values 0.000000 and 2223901.039333 >> from a string like this... >> >> YDim=1200\n\t\tUpperLeftPointMtrs=(0.000000,2223901.039333)\n\t\t >> >> I tried which I though was matching the statement and printing the >> decimal number after the equals sign?? >> >> re.findall(r"(\w+UpperLeftPointMtrs)*=\s([\d\.\w-]+)", s) >> >> where s is the string >> >> Many thanks for the help > > You have to do it with 2 matches in the same regex: > > regex = r"UpperLeftPointMtrs=\(([\d\.]+),([\d\.]+)" > > The first match is before the , and the second one is after the , :) > > You should probably learn how to play with regexes. > I personnaly use a visual tool called RX Toolkit[1] that comes with > Komodo IDE. > > [1] http://docs.activestate.com/komodo/4.4/regex.html Haven't tried it myself but how about this? http://re-try.appspot.com/ -- Kindest regards. Mark Lawrence. From no.email at please.post Wed Aug 12 17:41:38 2009 From: no.email at please.post (kj) Date: Wed, 12 Aug 2009 21:41:38 +0000 (UTC) Subject: How to page output in >>> ? Message-ID: How does one tell the python interactive interpreter to run the next output to stdout through the default pager? Basically, I'm looking for Python's equivalent of Perl's debugger's "|" prefix, as in DB<1> |print $long_output TIA! kynn From i3dmaster at gmail.com Wed Aug 12 17:56:27 2009 From: i3dmaster at gmail.com (i3dmaster) Date: Wed, 12 Aug 2009 14:56:27 -0700 (PDT) Subject: httplib incredibly slow :-( References: <4A81D3CB.7080209@simplistix.co.uk> Message-ID: On Aug 12, 9:37?am, Chris Withers wrote: > David Stanek wrote: > > I tried to reproduce this, but I could not. Could you paste in the > > output of your script? > > Not sure how that'll help, but sure: > > 2009-08-11 21:27:59.153000 > request: 0:00:00.109000 > response: 0:00:00.109000 > read: 0:24:31.266000 > > ?> Also on the same box where you run this script > > > can you test with curl or wget? > > It's a Windows box, so no :-( > But it really does download in a few seconds with IE, and 20min+ using > the script I included... > > Chris > > -- > Simplistix - Content Management, Batch Processing & Python Consulting > ? ? ? ? ? ? -http://www.simplistix.co.uk Just wanted to check if you can try turning on the debug mode for httplib and see if you can read a bit more debug info on where the calls get hung. In your example, it would be conn.set_debuglevel(1) From lists at cheimes.de Wed Aug 12 18:01:44 2009 From: lists at cheimes.de (Christian Heimes) Date: Thu, 13 Aug 2009 00:01:44 +0200 Subject: How to launch a function at regular time intervals ? In-Reply-To: References: Message-ID: <4A833BC8.1000801@cheimes.de> David wrote: > Has anyone run into a similar problem (and solved it) ? Yeah, here is my implementation as a perpetual timer based some cherrypy code and threading timer. import threading class PerpetualTimer(threading._Timer): """A subclass of threading._Timer whose run() method repeats. Based on cherrpy.process.plugins.PerpetualTimer """ def __init__(self, interval, function, name=None, daemon=False, args=(), kwargs={}): super(PerpetualTimer, self).__init__(interval, function, args, kwargs) self.setName(name) self.setDaemon(daemon) def run(self): while True: self.finished.wait(self.interval) if self.finished.isSet(): return self.function(*self.args, **self.kwargs) def stop(self, timeout=None): self.cancel() self.join(timeout) def callback(egg): egg.cook() timer = PerpetualTimer(100, callback, name="EggTimer", args=(somegg,)) timer.start() ... timer.stop() Christian From user at tld.invalid Wed Aug 12 18:07:23 2009 From: user at tld.invalid (Bartosz Wroblewski) Date: 12 Aug 2009 22:07:23 GMT Subject: How to launch a function at regular time intervals ? References: Message-ID: On Wed, 12 Aug 2009 14:09:29 -0700, David wrote: > > Hi all, I'm trying to launch a function at regular time intervals but > cannot find the way to do it. > For what it's worth, here's how I do it: ---------------8<--------------- #!/usr/bin/env python from time import sleep interval = 25 #seconds while not sleep(interval): f(spam, eggs, knight) ---------------8<--------------- You might want to put the sleep inside an *obviously* infinite loop. Note that this works best (most accurately) for longer periods. If you need to account for the time spent in the actual f() calls, plug in a time.time() call where appropriate. -- | <")-, | ''The good-enough is the enemy of the excellent.'' - John Miles | (_==/ |-----------,----------------------------------------------------- | ='- | Bartosz Wroblewski | bawr from holyhandgrenade.info or int8.org From python at mrabarnett.plus.com Wed Aug 12 18:19:18 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 12 Aug 2009 23:19:18 +0100 Subject: Format Code Repeat Counts? In-Reply-To: References: Message-ID: <4A833FE6.5030700@mrabarnett.plus.com> jschwab wrote: > Are repeat counts supported Python's str.format() in some fashion? > > In Fortran my format strings can have repeat counts. > > > write(*, fmt="3F8.3") [1, 2, 3] > 1.000 2.000 3.000 > > > I don't think printf-style format codes, which is what'd I'd > previously used in Python, allow for repeat counts. > > As a more concrete example, say I have several sets of letters in a > list of strings > letters = ["aeiou", "hnopty", "egs", "amsp"] > and I wanted to build a regular expression string out of them like > re_str <==> "[aeiou][hnopty][egs][amsp]" > Right now, the best I've got that doesn't require an explicit string > like "[{1}][{2}][{3}][{4}]" is > re_str = "".join(map(lambda x: "[{0}]".format(x), letters)) > > Is there a better way? > The shortest I can come up with is: "[" + "][".join(letters) + "]" From clp2 at rebertia.com Wed Aug 12 18:23:32 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 12 Aug 2009 18:23:32 -0400 Subject: Format Code Repeat Counts? In-Reply-To: References: Message-ID: <50697b2c0908121523jc495a65y1957a503b4f10566@mail.gmail.com> On Wed, Aug 12, 2009 at 4:34 PM, jschwab wrote: > As a more concrete example, say I have several sets of letters in a > list of strings > ? ? letters = ["aeiou", "hnopty", "egs", "amsp"] > and I wanted to build a regular expression string out of them like > ? ? re_str <==> "[aeiou][hnopty][egs][amsp]" > Right now, the best I've got that doesn't require an explicit string > like "[{1}][{2}][{3}][{4}]" is > ? ? re_str = "".join(map(lambda x: "[{0}]".format(x), letters)) > > Is there a better way? Slightly better, by using a generator expression instead of map() and lambda: re_str = "".join("[{0}]".format(x) for x in letters) Though obviously MRAB's is shorter (and a good show of lateral thinking). Cheers, Chris -- http://blog.rebertia.com From jgardner at jonathangardner.net Wed Aug 12 18:34:34 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Wed, 12 Aug 2009 15:34:34 -0700 (PDT) Subject: Plotting Quadratic Functions, pygame References: Message-ID: <14363c28-482a-40fe-bbdf-e727fb68dce6@i18g2000pro.googlegroups.com> Before we get into fixing your code, let's talk about style. A lot of bugs are solved when you fix the style, and the remaining bugs are much easier to find and fix. (Comments inline) On Aug 12, 2:27?pm, Senad Ibraimoski -student-Mathematical Institute Belgrade wrote: > Hello, I'm a new guy to this group, my professor recommend this group > to me, because I was boring him with questions.I'm new to python, and > I have problem plotting Quadratic Functions. Using module pygame. > Here is the code: > > #!/usr/bin/env python Vertical whitespace is very useful for separating different parts of your code, just like you do when you write paragraphs. > import pygame vertical whitespeace. > def main(): Throwing everything into one function is rarely a good idea. I'll identify ways you can separate out the code below into functions. For now, your code can share data between functions with global variables. Down the road, you may want to encapsulate the shared data in objects. > ? ? ? ? import sys > ? ? ? ? import math > ? ? ? ? from math import sqrt Put all the import statements at the top, as much as you can. > ? ? ? ? #Input equation coefficients > ? ? ? ? screen=pygame.display.set_mode((400,400)) > ? ? ? ? pygame.display.set_caption( ' Ploting ' ) > ? ? ? ? screen.fill((255,255,255)) > ? ? ? ? pen=((0,0,255)) > ? ? ? ? dark=(0,0,0) > ? ? ? ? ox=200 > ? ? ? ? oy=200 There are really two parts here: Getting the screen setup and drawing. Both should be separated into two functions. > ? ? ? ? a= int(raw_input('Input coefficient a ' )) > ? ? ? ? b= int(raw_input('Input coefficient b ' )) > ? ? ? ? c= int(raw_input('Input coefficient c ' )) Another part deals with collecting user input. Note that you shouldn't be collecting ints but floats. (Ideally, you would collect real numbers, but representing that in a computer is difficult.) > ? ? ? ? pygame.draw.aaline(screen,((255,0,0)),((200,0)) ,((200,400))) > ? ? ? ? pygame.draw.aaline(screen,((255,0,0)),((0,200)), ((400,200))) This draws the coordinate axes. This belongs in another function. > ? ? ? ? if a==0: > ? ? ? ? ? ? ? ? if b==0: > ? ? ? ? ? ? ? ? ? ? ? ? print 'No solutions' > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? x= -c/b > ? ? ? ? ? ? ? ? ? ? ? ? print x > ? ? ? ? else: > ? ? ? ? ? ? ? ? d=b*b-4*a*c > ? ? ? ? ? ? ? ? if d<0: > ? ? ? ? ? ? ? ? ? ? ? ? num=complex(-b/(2*a),sqrt(-d)/(2*a)) > ? ? ? ? ? ? ? ? ? ? ? ? print num > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? x1=(-b+sqrt(d))/(2*a) > ? ? ? ? ? ? ? ? ? ? ? ? x2=(-b-sqrt(d))/(2*a) > ? ? ? ? ? ? ? ? ? ? ? ? print 'x1= ' ,x1 > ? ? ? ? ? ? ? ? ? ? ? ? print 'x2= ' ,x2 The solver belongs in another function. I would have the solver take a representation of the equation (simply a tuple of (a, b, c)) and return a list of solutions. If there are no solutions, then return an empty list. > ? ? ? ? ? ? ? ? ? ? ? ? while 1: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? for event in pygame.event.get(): > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? if event ==pygame.QUIT: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? print ' Quitting' > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? pygame.quit() > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? sys.exit(1) > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? x=-50; > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? while x<=50: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? y=(a*(x**2) + b*x + c) *(-1) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? screen.set_at(((x+ox),(y+oy)),dark) > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? pygame.display.flip() > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? x=x+1; The main loop belongs in another function. The drawing bit belongs in another function. > > ? ? ? ? return 0 > > if __name__ == '__main__': main() > > For now I'm plotting function only when Determinant >0. Or in other > words, when equation has two solutions, > x1,x2 e R... Now if you start my program you will see where problem > is. It's with function, It so bad drawn. > When I try to increment x in loop by 0.1 for every pass, I get > problems because method set_at() Which sets pixel requires integer... > Your drawing function that you write should take a scaling factor in addition to the equation it is trying to draw. You'll have to round the floats to the nearest integer. This is pretty easy to do: number_as_int = int(number_as_float + 0.5) Rather than step between arbitrary numbers, step through every point on the graph. For this equation, y = a x^2 + b x + c, right? So walk from left-to-right over all visible values of x (0 to 400, or rather -200 to 200) and find y. > I don't have in this year Computer Graphics on my faculty. So this are > my first steps in this area of CS. > This is a very good first step. You have a bright future in programming and perhaps in computer graphics. From python at mrabarnett.plus.com Wed Aug 12 18:38:44 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 12 Aug 2009 23:38:44 +0100 Subject: Format Code Repeat Counts? In-Reply-To: <50697b2c0908121523jc495a65y1957a503b4f10566@mail.gmail.com> References: <50697b2c0908121523jc495a65y1957a503b4f10566@mail.gmail.com> Message-ID: <4A834474.9000304@mrabarnett.plus.com> Chris Rebert wrote: > On Wed, Aug 12, 2009 at 4:34 PM, jschwab wrote: > >> As a more concrete example, say I have several sets of letters in a >> list of strings >> letters = ["aeiou", "hnopty", "egs", "amsp"] >> and I wanted to build a regular expression string out of them like >> re_str <==> "[aeiou][hnopty][egs][amsp]" >> Right now, the best I've got that doesn't require an explicit string >> like "[{1}][{2}][{3}][{4}]" is >> re_str = "".join(map(lambda x: "[{0}]".format(x), letters)) >> >> Is there a better way? > > Slightly better, by using a generator expression instead of map() and lambda: > re_str = "".join("[{0}]".format(x) for x in letters) > > Though obviously MRAB's is shorter (and a good show of lateral thinking). > Python 3.1 supports auto-numbered placeholders "[{}]", so: re_str = ("[{}]" * len(letters)).format(*letters) From emile at fenx.com Wed Aug 12 18:45:00 2009 From: emile at fenx.com (Emile van Sebille) Date: Wed, 12 Aug 2009 15:45:00 -0700 Subject: Format Code Repeat Counts? In-Reply-To: References: Message-ID: On 8/12/2009 1:34 PM jschwab said... > Are repeat counts supported Python's str.format() in some fashion? > > In Fortran my format strings can have repeat counts. > > > write(*, fmt="3F8.3") [1, 2, 3] > 1.000 2.000 3.000 > > > I don't think printf-style format codes, which is what'd I'd > previously used in Python, allow for repeat counts. > > As a more concrete example, say I have several sets of letters in a > list of strings > letters = ["aeiou", "hnopty", "egs", "amsp"] > and I wanted to build a regular expression string out of them like > re_str <==> "[aeiou][hnopty][egs][amsp]" > Right now, the best I've got that doesn't require an explicit string > like "[{1}][{2}][{3}][{4}]" is > re_str = "".join(map(lambda x: "[{0}]".format(x), letters)) > > Is there a better way? > I don't know. I often end up at something like: "[%s]"*len(letters) % tuple(letters) Emile From gb345 at invalid.com Wed Aug 12 18:57:33 2009 From: gb345 at invalid.com (gb345) Date: Wed, 12 Aug 2009 22:57:33 +0000 (UTC) Subject: Need feedback on ORF-extracting code Message-ID: Hi everyone. I'm relatively new to Python, and could use your feedback on the code below. First some nomenclature. A "nucleotide" is one of A, C, G, T, or U. (In practice, a sequence of such nucleotides never contains both T and U, but this fact is not important in what follows.) A "codon" is a sequence of 3 of these. A "stop codon" is any one of UAA, UAG, UGA, TAA, TAG, or TGA. Two codons are said to be "in frame" in a containing sequence of nucleotides if their positions differ by a multiple of 3. An "open reading frame," or ORF, is defined as a maximal subsequence of nucleotides whose length is a multiple of 3, begins with either AUG or ATG, terminates right before a stop codon in the original sequence, and contains no stop codons that are in frame with the initial codon (AUG or ATG). The fact that ORFs have lengths that are multiples of 3 means that there are three possible "registers" for ORFs (depending the modulo 3 of their starting positions), and that ORFs in different registers can overlap. I'll refer to these registers as 0, 1, and 2, because they contain ORFs that are in frame with the codons at positions 0, 1, and 2 of the original sequence, respectively. In the code below, routine extract_orfs takes as input a string, assumed to be a sequence of nucleotides, and returns a tuple of tuples, describing ORFs. These ORFs can overlap. The helper routine _xo takes as input a string (a sequence of nucleotides), and an offset, and returns a tuple of tuples, again representing ORFs, but this time all in the same register, since they are all in frame with the position passed as the second argument to the function. I would appreciate your comments on this code. I feel that it is not as clear as it could be, but I don't know how to make it any clearer. (NOTE: I realize that, in all likelihood, publicly available Python code already exists for this. At the moment I'm more interested in improving my Python skills.) Many thanks in advance! Gabe # BEGINNING OF CODE import sys import re _start = r'A[TU]G' _stop = r'(?:[TU]A[AG]|[TU]GA)' _nonstop = r'(?:[CAG][TUCAG]{2}|[TU](?:[TUC][TUCAG]|[AG][TUC])|[TU]GG)' _codon = r'(?:[TUCAG]{3})' _orf_re = re.compile('(' + _codon + r'*?)(A[TU]G' + _nonstop + '*)(' + _stop + ')', flags=re.I) _lead_re = re.compile(r'[TUCAG]*?A[TU]G', flags=re.I) def _xo(seq, pos): """ Helper routine that finds all the non-overlapping in-frame orfs starting from a specific position in the input sequence. input: a string of letters in the set 'tucagTUCAG', and a starting position; output: a tuple of tuples; each internal tuple consists of a starting position, an orf, and the stop codon that terminates it. """ ret = [] while True: m = _orf_re.match(seq, pos) if not m: break orf = m.group(2) stop = m.group(3) assert len(orf) % 3 == 0 ret.append((m.start() + len(m.group(1)), orf, stop)) pos = m.end() return ret def extract_orfs(seq): """ Extracts all (possibly overlapping) maximal open reading frames, defined as sequences beginning with AUG (or ATG), ending with an in-frame stop codon, and containing no in-frame stop codons in-between. input: a string of letters in the set 'tucagTUCAG'; output: a tuple of tuples; each internal tuple consists of a starting position, an orf, and the stop codon that terminates it. """ m = _lead_re.match(seq) if not m: return () pos = m.start() ret = [] for i in range(min(3, len(seq))): ret.extend(_xo(seq, pos + i)) ret.sort() return tuple(ret) # END OF CODE From steve at REMOVE-THIS-cybersource.com.au Wed Aug 12 19:19:20 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 12 Aug 2009 23:19:20 GMT Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com> <7877b03a-09da-4836-804c-502b6f78003c@h21g2000yqa.googlegroups.com> Message-ID: <02933e60$0$20647$c3e8da3@news.astraweb.com> On Wed, 12 Aug 2009 14:21:34 -0700, Douglas Alan wrote: > On Aug 12, 5:32 am, Steven D'Aprano > wrote: > >> That problem basically boils down to a deep-seated philosophical >> disagreement over which philosophy a language should follow in regard >> to backslash escapes: >> >> "Anything not explicitly permitted is forbidden" >> >> versus >> >> "Anything not explicitly forbidden is permitted" > > No, it doesn't. It boils down to whether a language should: > > (1) Try it's best to detect errors as early as possible, especially when > the cost of doing so is low. You are making an unjustified assumption: \y is not an error. It is only an error if you think that anything not explicitly permitted is forbidden. While I'm amused that you've made my own point for me, I'm less amused that you seem to be totally incapable of seeing past your parochial language assumptions, even when those assumptions are explicitly pointed out to you. Am I wasting my time engaging you in discussion? There's a lot more I could say, but time is short, so let me just summarise: I disagree with nearly everything you say in this post. I think that a few points you make have some validity, but the vast majority are based on a superficial and confused understanding of language design principles. (I won't justify that claim now, perhaps later, time permitting.) Nevertheless, I think that your ultimate wish -- for \y etc to be considered an error -- is a reasonable design choice, given your assumptions. But it's not the only reasonable design choice, and Bash has made a different choice, and Python has made yet a third reasonable choice, and Pascal made yet a fourth reasonable choice. These are all reasonable choices, all have some good points and some bad points, but ultimately the differences between them are mostly arbitrary personal preference, like the colour of a car. Disagreements over preferences I can live with. One party insisting that red is the only logical colour for a car, and that anybody who prefers white or black or blue is illogical, is unacceptable. -- Steven From nobody at nowhere.com Wed Aug 12 19:23:10 2009 From: nobody at nowhere.com (Nobody) Date: Thu, 13 Aug 2009 00:23:10 +0100 Subject: How to page output in >>> ? References: Message-ID: On Wed, 12 Aug 2009 21:41:38 +0000, kj wrote: > How does one tell the python interactive interpreter to run the > next output to stdout through the default pager? Basically, I'm > looking for Python's equivalent of Perl's debugger's "|" prefix, > as in > > DB<1> |print $long_output Something like: sys.stdout.flush() p = subprocess.Popen([os.environ['PAGER']], stdin = subprocess.PIPE) sys.stdout = p.stdin ... sys.stdout.flush() sys.stdout = sys.__stdout__ p.stdin.close() p.wait() but with error and exception handling. But personally, I'd write the data to the child process explicitly if that's possible. From mdekauwe at gmail.com Wed Aug 12 19:29:38 2009 From: mdekauwe at gmail.com (Martin) Date: Wed, 12 Aug 2009 16:29:38 -0700 (PDT) Subject: matching patterns after regex? References: <61bef795-f146-4bdd-b5b3-a212e6d9197c@w6g2000yqw.googlegroups.com> <2387d409-110a-451d-b301-6d7fe4abc793@c34g2000yqi.googlegroups.com> <0292a4a9$0$20647$c3e8da3@news.astraweb.com> <18d5d342-b678-4101-a284-24d6176ac856@v20g2000yqm.googlegroups.com> <85652297-16e7-489f-9e36-5092941df002@c34g2000yqi.googlegroups.com> Message-ID: On Aug 12, 10:29?pm, Mark Lawrence wrote: > Bernard wrote: > > On 12 ao?t, 12:43, Martin wrote: > >> On Aug 12, 1:42 pm, Martin wrote: > > >>> On Aug 12, 1:23 pm, Steven D'Aprano >>> cybersource.com.au> wrote: > >>>> On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote: > >>>>> I tried > >>>>> re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s) > >>>> You need to put quotes around strings. > >>>> In this case, because you're using regular expressions, you should use a > >>>> raw string: > >>>> re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) > >>>> will probably work. > >>>> -- > >>>> Steven > >>> Thanks I see. > >>> so I tried it and if I use it as it is, it matches the first instance: > >>> I > >>> n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s) > >>> Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')] > >>> So I adjusted the first part of the regex, on the basis I could sub > >>> NORTH for SOUTH etc. > >>> In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\. > >>> \w-]+)",s) > >>> Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')] > >>> But in both cases it doesn't return the decimal value rather the value > >>> that comes after NUM_VAL = , rather than VALUE = ? > >> I think I kind of got that to work...but I am clearly not quite > >> understanding how it works as I tried to use it again to match > >> something else. > > >> In this case I want to print the values 0.000000 and 2223901.039333 > >> from a string like this... > > >> YDim=1200\n\t\tUpperLeftPointMtrs=(0.000000,2223901.039333)\n\t\t > > >> I tried which I though was matching the statement and printing the > >> decimal number after the equals sign?? > > >> re.findall(r"(\w+UpperLeftPointMtrs)*=\s([\d\.\w-]+)", s) > > >> where s is the string > > >> Many thanks for the help > > > You have to do it with 2 matches in the same regex: > > > regex = r"UpperLeftPointMtrs=\(([\d\.]+),([\d\.]+)" > > > The first match ?is before the , and the second one is after the , :) > > > You should probably learn how to play with regexes. > > I personnaly use a visual tool called RX Toolkit[1] that comes with > > Komodo IDE. > > > [1]http://docs.activestate.com/komodo/4.4/regex.html > > Haven't tried it myself but how about this?http://re-try.appspot.com/ > > -- > Kindest regards. > > Mark Lawrence. Thanks Mark and Bernard. I have managed to get it working and I appreciate the help with understanding the syntax. The web links are also very useful, I'll give them a go. Martin From python at mrabarnett.plus.com Wed Aug 12 19:40:03 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 13 Aug 2009 00:40:03 +0100 Subject: Unrecognized escape sequences in string literals In-Reply-To: <02933e60$0$20647$c3e8da3@news.astraweb.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com> <7877b03a-09da-4836-804c-502b6f78003c@h21g2000yqa.googlegroups.com> <02933e60$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A8352D3.3070003@mrabarnett.plus.com> Steven D'Aprano wrote: > On Wed, 12 Aug 2009 14:21:34 -0700, Douglas Alan wrote: > >> On Aug 12, 5:32 am, Steven D'Aprano >> wrote: >> >>> That problem basically boils down to a deep-seated philosophical >>> disagreement over which philosophy a language should follow in regard >>> to backslash escapes: >>> >>> "Anything not explicitly permitted is forbidden" >>> >>> versus >>> >>> "Anything not explicitly forbidden is permitted" >> No, it doesn't. It boils down to whether a language should: >> >> (1) Try it's best to detect errors as early as possible, especially when >> the cost of doing so is low. > > You are making an unjustified assumption: \y is not an error. It is only > an error if you think that anything not explicitly permitted is forbidden. > > While I'm amused that you've made my own point for me, I'm less amused > that you seem to be totally incapable of seeing past your parochial > language assumptions, even when those assumptions are explicitly pointed > out to you. Am I wasting my time engaging you in discussion? > > There's a lot more I could say, but time is short, so let me just > summarise: > > I disagree with nearly everything you say in this post. I think that a > few points you make have some validity, but the vast majority are based > on a superficial and confused understanding of language design > principles. (I won't justify that claim now, perhaps later, time > permitting.) Nevertheless, I think that your ultimate wish -- for \y etc > to be considered an error -- is a reasonable design choice, given your > assumptions. But it's not the only reasonable design choice, and Bash has > made a different choice, and Python has made yet a third reasonable > choice, and Pascal made yet a fourth reasonable choice. > IHMO, it would've been simpler in the long run to say that backslash followed by one of [0-9A-Za-z] is an escape sequence, backslash followed by newline is ignored, and backslash followed by anything else is that something. That way there would be a way to introduce additional escape sequences without breaking existing code. From davea at ieee.org Wed Aug 12 20:30:16 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 12 Aug 2009 20:30:16 -0400 Subject: How to launch a function at regular time intervals ? In-Reply-To: References: Message-ID: <4A835E98.2070507@ieee.org> David wrote: > Hi all, I'm trying to launch a function at regular time intervals but > cannot find the way to do it. Here is the code I wrote (time_interval > is a user defined variable in seconds): > > while(1) > timestamp=datetime.now() > > timestamp_seconds=timestamp.hour*3600+timestamp.minute*60+timestamp.second > if timestamp_seconds % time_interval == 0: ****Call Function**** > > This does not work because during the second at which the condition > holds true, there is time to call the function several times. Since I > want to have this function called only once every x seconds, I tried > to add the following condition: > > if timestamp_seconds % time_interval ==0 & timestamp.microsecond == 0 > > But it seems this second condition hardly ever happens (i.e. the > timestamp variable is not updated every microsecond, therefore it can > be 9998 then jump directly to 0003 for instance). > > Has anyone run into a similar problem (and solved it) ? > > Thanks for your help > > I'm assuming you want to call it every time_interval seconds, on average, with a little jitter allowed on each call, but keeping correct long term. In other words, if one call is a little late, you want the next one to still happen as close to on-time as possible. The general outline is something like (untested): times_called = 0 #number of times function has been called start_time = now while True: elapsed = now - start_time int_elapsed = int(elapsed/time_interval) for times_called in range(times_called, int_elapsed): call_the_function() sleep(time_interval/10) #this might give us 10% jitter, which is usually fine DaveA From drobinow at gmail.com Wed Aug 12 20:53:43 2009 From: drobinow at gmail.com (David Robinow) Date: Wed, 12 Aug 2009 20:53:43 -0400 Subject: httplib incredibly slow :-( In-Reply-To: <4A82EFDC.70502@simplistix.co.uk> References: <4A81D3CB.7080209@simplistix.co.uk> <4A82EFDC.70502@simplistix.co.uk> Message-ID: <4eb0089f0908121753o5ecf141dj304b21c3df0d3d6b@mail.gmail.com> On Wed, Aug 12, 2009 at 12:37 PM, Chris Withers wrote: > David Stanek wrote: >> Also on the same box where you run this script >> can you test with curl or wget? > It's a Windows box, so no :-( Why not? http://users.ugent.be/~bpuype/wget/ http://curl.haxx.se/download.html From arphaksad at gmail.com Wed Aug 12 21:15:42 2009 From: arphaksad at gmail.com (naaman) Date: Wed, 12 Aug 2009 18:15:42 -0700 (PDT) Subject: fileinput References: Message-ID: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> On Aug 12, 1:35?pm, Dave Angel wrote: > naaman wrote: > > I'm writing my first Python script and > > I want to use fileinput to open a file in r+ mode. > > Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > > ANy ideas? > > > Need to find and overwrite a line in a file several times. > > I can do it using open and seek() etc. but was wondering if I can use > > fileinput. > > > thanks; > > I haven't used it, but check out the 'inplace' keyword parameter. > > DaveA I've only Python for a week so I'm not sure what inplace does From rylesny at gmail.com Wed Aug 12 21:25:40 2009 From: rylesny at gmail.com (ryles) Date: Wed, 12 Aug 2009 18:25:40 -0700 (PDT) Subject: run all scripts in sub-directory as subroutines? References: Message-ID: <0639e183-5c38-42b6-8411-3fd53e5ec01d@r34g2000vba.googlegroups.com> On Aug 11, 5:12?pm, guthrie wrote: > This works fine, but in the sub-modules the sys.path appropriately > returns the same as from the parent, I want them to know their own > file names. How?? I can pass it to them, but wondered if there is a > more self-sufficient way for a module to know from where it was > invoked. Instead of sys.path, you may be interested in the __file__ attribute will give you a module's filename: http://docs.python.org/reference/simple_stmts.html#index-1031 You could also be more explicit in matching *.py files in your subdirectory by using glob: http://docs.python.org/library/glob.html From cousinstanley at gmail.com Wed Aug 12 22:21:25 2009 From: cousinstanley at gmail.com (Cousin Stanley) Date: Thu, 13 Aug 2009 02:21:25 +0000 (UTC) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> Message-ID: > FWIW, I support the idea the regular docs incorporating links > to freely editable wiki pages. That will at least make it > easier for people to make changes or add notes. > > That being said, I would like to add a few thoughts about the > current process. ISTM that important corrections (when the > docs are clearly in error) tend to get made right away. What > is more interesting are the doc requests that get rejected > and why: > .... > In short, most doc requests that get rejected are requests > that didn't actually improve the documentation. > .... Raymond .... Thanks for your very eloquent and cohernt response that in my opinion helps to explain many of the problems, either real or perceived, with the Python documentation .... -- Stanley C. Kitching Human Being Phoenix, Arizona From sjmachin at lexicon.net Wed Aug 12 22:24:19 2009 From: sjmachin at lexicon.net (John Machin) Date: Wed, 12 Aug 2009 19:24:19 -0700 (PDT) Subject: csv.DictWriter.write_header() References: Message-ID: On Aug 13, 6:45?am, Alan G Isaac wrote: > Given a csv.DictWriter instance `dw` > I think it would be nice to be able to > say dw.write_header() > instead of > dw.writer.writerow(dw.fieldnames) > > Good idea? Yes, it's a brilliant idea. All you have to do is insert the following lines in your code after importing csv: csv.DictWriter.write_header = ( lambda dw: dw.writer.writerow(dw.fieldnames) ) From saptarshi.guha at gmail.com Wed Aug 12 22:32:26 2009 From: saptarshi.guha at gmail.com (sapsi) Date: Wed, 12 Aug 2009 19:32:26 -0700 (PDT) Subject: Write binary data to standard error? Message-ID: <9514cb7a-2962-484a-9669-c39533de138b@w41g2000yqb.googlegroups.com> Hello, This is probably a basic question, but how does one write binary data to standard error e.g int as network order (4 bytes)? Much thanks Saptarshi From saptarshi.guha at gmail.com Wed Aug 12 22:44:38 2009 From: saptarshi.guha at gmail.com (Saptarshi) Date: Wed, 12 Aug 2009 19:44:38 -0700 (PDT) Subject: Write binary data to standard error? References: <9514cb7a-2962-484a-9669-c39533de138b@w41g2000yqb.googlegroups.com> Message-ID: <765589c3-98da-45b9-ab35-475ca5c76250@g10g2000yqh.googlegroups.com> On Aug 12, 10:32?pm, sapsi wrote: > Hello, > This is probably a basic question, but how does one write binary data > to standard error e.g int as network order (4 bytes)? > > Much thanks > Saptarshi Solved: import sys import os from struct import * d=os.fdopen(sys.stderr.fileno(),"wb") d.write("\x00") d.write(pack(">i",5)) From alan.isaac at gmail.com Wed Aug 12 23:15:51 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Thu, 13 Aug 2009 03:15:51 GMT Subject: csv.DictWriter.write_header() In-Reply-To: References: Message-ID: > On Aug 13, 6:45 am, Alan G Isaac wrote: >> Given a csv.DictWriter instance `dw` >> I think it would be nice to be able to >> say dw.write_header() >> instead of >> dw.writer.writerow(dw.fieldnames) >> >> Good idea? On 8/12/2009 10:24 PM John Machin apparently wrote: > Yes, it's a brilliant idea. All you have to do is insert the following > lines in your code after importing csv: > > csv.DictWriter.write_header = ( > lambda dw: dw.writer.writerow(dw.fieldnames) > ) I do not understand the reason for your silly, sarcastic response. I already showed you how to achieve the result, so obviously I am not just asking for my own personal gain. I take it you do not realize that many users do not see a simple way to get this often needed functionality. (For example, see the gymnatics suggested by Shai Vaingast in his otherwise excellent and useful book.) And indeed, there is no reason to expect them to. So my question was, would this improve the class from a usability perspective? Do you have a useful response? Alan Isaac From rurpy at yahoo.com Wed Aug 12 23:23:27 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Wed, 12 Aug 2009 20:23:27 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> Message-ID: <65053f02-0e64-4070-90c8-e04394be90ad@d32g2000yqh.googlegroups.com> On 08/12/2009 01:58 AM, Steven D'Aprano wrote: > On Tue, 11 Aug 2009 14:50:51 -0700, rurpy wrote: > >>>> The issue tracker is fine for many things, but the process it provides >>>> is equivalent to peep-hole optimization. How does one submit a >>>> tracker issue for something like the overall organization of the docs >>>> (for example, the mis-placement of things like data- types in the >>>> library manual rather than the language manual)? >>> The same way you would submit a tracker issue for anything. >>> >>> "Documentation bug: Data types are misplaced in the library manual >>> instead of the language manual. >>> >>> Suggested alternative: move page docs.python.org/xyz.html to abc.html" >> But that's the problem. Such a reorg is not a simple matter of moving a >> file from here to there. It will require a lot moving about of sections >> and a lot of word-smithing to glue them back together again in a >> coherent way. > > That's no different from *any* major refactoring. The exact same problem > exists for code as well as documentation. It's a solved problem for code, > and it's a solved problem for documentation. Huh? I don't buy this at all. Code refactoring doesn't change the semantics of the program at all -- it simplifies the code that implements behavior without changing behavior. How does this apply to revising documentation? It may be true that some of the same techniques applicable to maintaining code are applicable to documentation but I need a lot more than your assertion to believe they are as equivalent as you seem to be claiming. > In some order: > > Consensus that there is a problem that needs solving; > Volunteer(s) to do the work; > Somebody to take responsibility to check the changes in. That's not refactoring as I understand it -- that is making a large change. I don't see that that addresses the problem of getting a large patch approved or the other issues I mentioned. > Sometimes, in the face of apathy or disagreement (which may very well be > justified), you have to at least partly solve the problem *before* people > will agree that it needed to be solved. Welcome to the real world. > >> A tracker issue, even one that was fairly specific about how things >> should be reorganized but which did not provide all the needed changes >> (a large patch) would almost certainly be ignored or rejected. > > Yes it would. Most patches are ignored, because the dev team are > overworked, and if they don't see the need for a patch, they won't > approve it. I'm confused. If they weren't overworked, then they would approve patches they didn't see a need for? Or are you saying because they are overworked they fail to approve patches that should be approved? I am not sure how either supports the argument that the tracker is the best method of improving the docs. >> But >> providing a large patch raises two questions. How likely is it to be be >> accepted? (Something anyone would want to know before investing the >> time.) And how to actually do the work needed to generate it (it could >> be a very large amount of work for an individual and I don't think it >> can be broken down into small independent issues.) How is one to test >> the waters as to acceptability, or solicit help, if one simply submits a >> tracker issue? > > No, submitting a tracker issue is a necessary but not sufficient step. > Without a tracker issue, you're very unlikely to have people agree to > replace the existing docs with your docs, although a PEP would probably > do it. (A PEP is significantly more effort than raising a tracker issue.) Has there ever been a PEP for a doc change? Are you making a serious suggestion? > You also have to get attention from those with check-in privileges. If > they approve your patches, you're done. If they don't approve them, or > fail to respond, you can try convincing them, or taking it to the Python- > Dev list and request somebody review your patches. > > If you have no patches, perhaps because you're unwilling to invest the > effort without a guarantee that it will be treated seriously, then you > need to get some sort of consensus among the relevant people that the > problem is worth solving. You are again describing the current process, not the issue of whether the current process is the optimal one or not. And while I would never expect a guarantee that a particular submission would be accepted, I think I would need, if not a guarantee, at least a high expectation that a submission would be treated seriously before I invested a large amount of work in it. > Guess what? Sometimes others will disagree with you. What you see as the > Worst. Docs. EVAR. may be seen as perfectly adequate, even excellent, by > others. If this is the case, remember, Python isn't your product, you > don't have veto over what goes into it. Feel free to publish your > alternatives. Write a book. Go home and cry into your beer over it. > Whatever. Sometimes you win, and sometimes you don't. Right, this is obvious. But the other side of that coin is that if people who see problems with the docs perceive that those who control access to the docs have no interest in changing them, then the first group will likely post their complaints on this newsgroup. If you don't like that then you have the same choices you listed above. Of course if the docs really are that good, there will relatively few complaints and the vast majority of readers will recognize the few complaints as invalid and ignore them, so if you are right that the docs are good enough, there should be no problem. > This is the same process whether dealing with code or documentation. > >>> - if people are keen on a Python wiki, then by all means publish one, >>> just don't expect the Python dev team to build and manage it for you; >> As luminous a Pythoneer as Fredrik Lundh set up a documentation wiki to >> collect user contributions but it has faded away. If he couldn't pull >> it off then I'd say most other attempts without the backing of >> python.org are almost certainly doomed to failure. > > Perhaps that's a good indication that a Python wiki *doesn't* fulfill a > need in the community, and that despite what a few squeaky wheels think, > the docs *are* doing a good job? That fails to explain the repeated criticisms of the docs here and in blogs. Of course this argument is not likely to convince you since there is no reliable quantitative support for the claim that there are more complaints about the docs than other aspects of Python -- it relies on each individual's powers of observation. But you also have to explain away very specific criticisms of the docs such as Xah Lee's as invalid or exceptions. >> As long as every "the docs >> sux" complaint is met here with the standard responses that I've >> mentioned, > > But they aren't met with such a so-called "standard response". I just looked through the first 70 or so messages in this thread and in this case I have agree with you, most of the responses were not what I called "standard responses". There was one guy, a Steven D'Aprano early on that trotted out the, "it's free software, fix it if you don't like it" line, and the troll epithet was used a time or two, but the vast majority were in fact reasonable and thoughtful responses. I will try to find some examples from other past threads. >> rather than, "yes, they do have some problems, what do you >> think we should do about them?", > > We know that there are problems. We've said repeatedly that corrections > and patches are welcome. We've repeatedly told you how to communicate > your answer to the question of what should be done. None of this is good > enough for you. I don't know what else you expect. You have been told repeatedly why your insistence that the tracker must be the only channel, is wrong. I don't understand why you can't understand that. (Generally only those in authority, bosses, parents, police, and the like, "tell" others what a situation is and have a right to demand that the subject accept it without question. I think you could find a more respectful and less authoritarian way of phrasing what you said above since you are not in a position of authority over me.) And who exactly is this "we" that you are a member of? >>> If you won't put in the effort, and you won't put in the money, then it >>> won't happen. Moaning that other people aren't putting in the money to >>> hire team of professional writers isn't productive, and moaning that >>> other people aren't putting in the effort to improve the docs isn't >>> either. >> Eh? I have a computer filled with software that I put no money or >> effort into, yet there it is. > > Ah yes, I'm sorry, I missed one other alternative: sit around and wait > for somebody else to put in the money and/or effort. > >> That some of us choose to >> invest it somewhere other than Python does not deprive of of our right >> to point out problems in Python when we note them. > > Of course not. But it does mean that you won't be taken seriously, and > you have no right to be taken seriously. On usenet no one has a right to anything. You can take my posts however you wish. I've tried to make reasonable arguments to support my view (with the understanding that these are usenet posts, not a doctoral thesis). But you (and the unnamed "we" above) seem to feel that public complaints or discussion about better alternatives to the current doc improvement process are somehow out-of-bounds. I'm sorry, I disagree. From http Thu Aug 13 00:11:12 2009 From: http (Paul Rubin) Date: 12 Aug 2009 21:11:12 -0700 Subject: Scraping Wikipedia with Python References: <4a81b6f0$0$1590$742ec2ed@news.sonic.net> <6YidncRAiJ6SIxzXRVn_vwA@giganews.com> <7xd472hz2x.fsf@ruckus.brouhaha.com> Message-ID: <7xtz0c8ian.fsf@ruckus.brouhaha.com> Dotan Cohen writes: > > maybe you want dbpedia. > I did not know about this. Thanks! You might also like freebase/metaweb. From walkraft at gmail.com Thu Aug 13 00:15:02 2009 From: walkraft at gmail.com (casebash) Date: Wed, 12 Aug 2009 21:15:02 -0700 (PDT) Subject: Nice copy in interactive terminal Message-ID: Hello fellow Python Users, I've been wondering for a while if there exists an interactive terminal which has nice copy feature (ie. I can copy code without getting the >>> in front of every line). Thanks, Chris PS. apologies if I am posting this in the wrong group. I am unsure of the exact scope of this group. From frank at chagford.com Thu Aug 13 00:20:05 2009 From: frank at chagford.com (Frank Millman) Date: Thu, 13 Aug 2009 06:20:05 +0200 Subject: How to launch a function at regular time intervals ? References: Message-ID: On Aug 12, 11:09 pm, David wrote: > Hi all, I'm trying to launch a function at regular time intervals but > cannot find the way to do it. I assume you want your main program to continue running, while launching the function to run in the background. If you need this as a general capability, Christian's approach is probably the way to go. In my case I had one specific requirement, and found it easier to write a dedicated solution, as follows - import threading class MyFunction(threading.Thread): """Perform function every 30 seconds in separate thread""" def __init__(self): threading.Thread.__init__(self) self.event = threading.Event() def run(self): while not self.event.is_set(): # either call your function here, # or put the body of the function here self.event.wait(30) # wait for 30 seconds def stop(self): self.event.set() At the start of the main program, I have the following - func = MyFunction() func.start() When closing the main program, I have - func.stop() func.join() It is trivial to modify this to pass the interval, plus any other parameters required, as arguments. HTH Frank Millman From gagsl-py2 at yahoo.com.ar Thu Aug 13 00:39:40 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 01:39:40 -0300 Subject: Changing Remote Registry References: <5caea3690908070652v2ccb3ac8s4336266afe71dcb5@mail.gmail.com> <4A7C6D96.3000201@timgolden.me.uk> <5caea3690908100547l65394e65le111d8f3dda9e903@mail.gmail.com> Message-ID: En Mon, 10 Aug 2009 09:47:19 -0300, Kevin Holleran escribi?: > On Fri, Aug 7, 2009 at 2:08 PM, Tim Golden wrote: >> Kevin Holleran wrote: >> >>> hKey = _winreg.OpenKey (keyPath, path, 0, _winreg.KEY_SET_VALUE) >>> value,type = _winreg.QueryValueEx(hKey, item) >>> if (value == wrongValue): >>> _winreg.SetValue(hKey,'',_winreg.REG_SZ,correctValue) >>> >>> >>> When I do this I receive the error: >>> >>> _winreg.SetValue WindowsError: [Error 5] Access Denied >>> > I guess my question is will Windows let me change the registry remotely? > The error is a Windows permission error on the KEY_SET_VALUE. I am > running > this as a domain admin on a machine on the domain. Does the connection > inherit the credentials I am running it under or will I need to pass > those > in? Or does Windows simply not let me change the registry? Try doing the same interactively with regedt32.exe (logged as the same user). You can check your actual permissions under the Edit menu. Also, try using KEY_WRITE instead of KEY_SET_VALUE. -- Gabriel Genellina From bouncyinc at gmail.com Thu Aug 13 00:41:47 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Wed, 12 Aug 2009 22:41:47 -0600 Subject: getting a "simple" program to work In-Reply-To: References: <50697b2c0908112146q6e12650dt914518166b4fae72@mail.gmail.com> Message-ID: Just checking to see if this is more adequate to what you would have wanted to see I didn't get any feedback so I wasn't quite sure of this at the present time. On Tue, Aug 11, 2009 at 11:02 PM, John Haggerty wrote: > > > On Tue, Aug 11, 2009 at 10:46 PM, Chris Rebert wrote: > >> On Sun, Aug 9, 2009 at 8:42 PM, John Haggerty wrote: >> > ok so I know this is one of those "weird" requests but here me out. >> > So far I have an issue with a package for python called "libgmail" which >> is >> > basically a gmail interface for python to send messages remoetly. >> > Works ok except that the 'sendMessage' routine is bad. >> >> How is it "bad" precisely? Be specific (e.g. error message(s), >> description of observed incorrect behavior). >> > > In regards to bad would be failing to transmit claiming that the submittal > is wrong for the transmit string. > > (where username is my gmail username and "password" is my gmail password to > the test account, 6666666969 is the mobile number in question '00' is my > "carrier id" from the ogss code example which is just an array location from > a preformatted part of the string [probably from wikipedia on mobile carrier > email addresses to cell phones], I actually got desperate and commented out > the first attempt to transmit which I located in the code as just the > "instructions" the code fails on re-transmission, I later on looked at the > file and located that it was a zero byte file of no content. The program > itself looks for a command from the user's cell phone directly from mms sent > to the target gmail account prefaced by "Ogss" and anything else is treated > as a command but since the command failed on the first transmit I don't > think it's the command per se). > > owner at bouncyinc:~/Desktop/OGSS$ python ogss.py username password > 6666666969 00 > Starting ogss > Logfile at:/home/owner/ogss.log > Opening log file for reading > Parsing user input > Connecting to Gmail > Logging into Gmail > Opening log file for writing > Listening for commands > Processing Command > ls: unrecognized option `---------------------------------------------' > Try `ls --help' for more information. > Seding back results > Traceback (most recent call last): > File "ogss.py", line 127, in > main(sys.argv) > File "ogss.py", line 110, in main > account.sendMessage(tosend) > File "/usr/lib/python2.5/site-packages/libgmail.py", line 615, in > sendMessage > raise GmailSendError, resultInfo[SM_MSG] > libgmail.GmailSendError: Please try again. > > I traced the result to the sendMessage routine and noted that anytime it > tries to send anything it fails this also fails with the standard "docs" > package for libgmail 0.30 docs from the maintainer's site. > > Now the part where it *does* fail is where it has an issue with looking at > the trailing info but then it would have logged the info to the file and > emailed me back junk (which it didn't) > > I assume this could be done on any system just replace 'ls' with 'dir' or > the equivalent. > > >> >> > This is included in the above attachment >> > it's used in a program called "ogss" which is an sms interface to gmail >> to >> > basically read gmail and then have a command done on a remote machine >> and >> > then spat out on the local machine to a log file that's opened and then >> > emailed back >> > problem is that the sending back routine fails. >> >> Which routine is that exactly? Please also specify exactly how it is >> failing (e.g. error message(s), description of observed incorrect >> behavior). >> >> I apologize if these questions are answered in comments in the >> attachments, but to be honest, the fact that you didn't (or couldn't) >> put the specific problematic sections of code (and/or error messages) >> inline in your message makes it less likely that people (such as >> myself) will try to help you due to the volume of code you're making >> people wade through (i.e. people tend not to read large code dumps, >> /especially/ in attachments). >> >> Cheers, >> Chris >> -- >> http://blog.rebertia.com >> > That's ok I understand I hope that helps at least in part. -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Thu Aug 13 00:42:15 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 13 Aug 2009 00:42:15 -0400 Subject: Nice copy in interactive terminal In-Reply-To: References: Message-ID: <50697b2c0908122142r34f9c386hf8292f59ffa9edf2@mail.gmail.com> On Thu, Aug 13, 2009 at 12:15 AM, casebash wrote: > Hello fellow Python Users, > > I've been wondering for a while if there exists an interactive > terminal which has nice copy feature (ie. I can copy code without > getting the >>> in front of every line). Not quite answering your exact question, but: - You can control the text of the prompt by modifying sys.ps1 - IPython (http://ipython.scipy.org/moin/) has powerful history features that are handy if you want a transcript of a REPL session Cheers, Chris -- http://blog.rebertia.com From gagsl-py2 at yahoo.com.ar Thu Aug 13 01:20:00 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 02:20:00 -0300 Subject: fileinput References: Message-ID: En Wed, 12 Aug 2009 01:27:47 -0300, naaman escribi?: > I'm writing my first Python script and > I want to use fileinput to open a file in r+ mode. > Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > ANy ideas? Don't use fileinput, it can't handle r+, only sequencial access. Even if you could use it, the documentation says [1]: fileinput.input([files[, inplace[, backup[, mode[, openhook]]]]]) "r+" corresponds to the `inplace` parameter (behaving like inplace=True) instead of `mode`. You could write fileinput.input(sys.argv[1:], mode="r+") instead - but again from the docs: "mode... must be one of 'r', 'rU', 'U' and 'rb'" > Need to find and overwrite a line in a file several times. > I can do it using open and seek() etc. but was wondering if I can use > fileinput. open+seek is the way to do that (assuming you don't alter the line length) [1] http://docs.python.org/library/fileinput.html#fileinput.input -- Gabriel Genellina From tjreedy at udel.edu Thu Aug 13 01:34:14 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Aug 2009 14:34:14 +0900 Subject: Social problems of Python doc [was Re: Python docs disappointing] In-Reply-To: <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> Message-ID: Raymond Hettinger wrote: > On Aug 12, 3:32 am, Paul Boddie wrote: >> Maybe the problem is that although everyone welcomes contributions and >> changes (or says that they do), the mechanisms remain largely beyond >> criticism. > > FWIW, I support the idea the regular docs incorporating links to > freely editable wiki pages. That will at least make it easier for > people to make changes or add notes. > > That being said, I would like to add a few thoughts about the > current process. The summary that follows accords with my experiences and observations. Perhaps you could add it to the Wiki. ISTM that important corrections (when the > docs are clearly in error) tend to get made right away. Many within a day. I have seen this with both some of my suggestions and others. What > is more interesting are the doc requests that get rejected > and why: One of my suggestions was postponed pending discussion on PyDev of the underlying issue, which I have not initiated yet. Another Georg accepted in principle but awaits me taking the time to write a fleshed out replacement text. > * Many doc requests come from people just learning the language > (that makes sense because the learning process involves reading > the docs). Unfortunately, a fair number of those requests are > flat-out wrong or represent a profound misunderstanding of the > feature in question. That may be an indicator that the docs > need to be improved, but the specific suggestion can be inane. > > * Some doc requests come from people who simply do not like the > feature in question. It is natural for tastes, styles, and > preferences to vary; however, we do have a firm rule that Guido's > tastes, styles, and preferences are the ones that go into the > language. So the doc writers need to try to channel Guido instead > of fighting him. So, if you think eval() is evil (I don't but many > do), we're not going to document that eval() should *never* be used. > If you hate super(), that's too bad -- the docs need to describe > what it does and how it was intended to be used -- the docs are no > place for diatribes on why inheritance is over-used and why you > think the world would be a better place without mixins or > multiple inheritance. > > * Then, there is a matter of where to put a particular piece of > documentation (how many times do you repeat a concept that pervades > the language). I doubt anyone can *really* understand the problem of organizing a book's worth in technical information into coherent order until they have actually tried to do so. > Hashing is a good example. The docs can discuss how > some objects hash to their object id and that object ids can change > from run-to-run, but if someone gets tripped-up by the idea (hey, > my set reprs changed between runs, wtf!), they want the docs updated > in the specific place that tripped them up (i.e. you must put big > red warnings in the set documentation, and the dict documentation, > and everywhere else a hash gets used ...). The core problem is that > the docs are interrelated -- the one place you're looking for > documentation of a specific builtin or function can't contain > every concept in the language. > > * Some behaviors are intentionally left unspecified. For the longest > time, Tim did not want to guarantee sort stability. This left him > free to continue to search for algorithmic improvements that did not > have stability. Later, the property was deemed so important that it > did become a guaranteed behavior. Also, some things are unspecified > to make things easier for other implementations (IronPython, PyPy, > Jython, etc.) We need to make sure that some one doesn't casually > go through the docs making doc promises that are hard to keep. > > * Some things are just plain difficult to fully explain in English > and not misrepresent that actual behavior. For example, the str.split > () > docs have been continuously tweaked over the years. Even now, I think > there are corner cases that are not fully captured by the docs. > Casual > edits to str.split() docs are more likely than not to take them > farther > away from the truth. > > * Then, there is the problem of talking too much. A book could be > written about super(), but that shouldn't all go into the docs for > the super builtin. Beginners often want to master all the builtins > and they try to read the doc page on builtin functions. It used to be > that you could read through the builtin descriptions in a few minutes. > Now, it takes a concerted effort to get through. It is hard to take > a sip of water from a firehose. Too much information has make a > function harder to understand. > > * My biggest pet peeve are requests to fill the docs with big red > warnings. I do not want the docs to look like a mine field. The > warnings > should be reserved for a handful of security or data corruption risks. > For the most part, the docs should be matter-of-fact, explaining what > a function or method does and how it was intended to be used. > > Preferred: "The value str.letters is locale dependent" > > Not preferred: "Caution, the str.letters value can be adversely > affected by the locale setting (it could even change length!); use > this > only when you are certain the locale setting will not violate any of > your program invariants; consider using a string literal instead; I > hate > string.letters and think Guido was smoking crack when it was > introduced." > > * Another category of rejected doc requests come from people looking > for > absolution from one of their programming bugs. It typically takes the > form of, "I made an assumption that the language did X, but it did Y > and my program didn't do what I wanted; therefore, the docs must be > to blame and they must change ...". The suggestion is "I was > suprised" > implies "the docs are hosed". The fact is that people with diffferent > backgrounds are going to have different expectations and someone is > going to get "surprised". The docs need to say what functions do, but > they don't need to be changed everytime someone writes a buggy > program. > > In short, most doc requests that get rejected are requests that didn't > actually improve the documentation. > > I do support links from the regular docs to an external wiki but the > main docs should continue to go through the regular process using the > tracker. Agreed Terry Jan Reedy From gagsl-py2 at yahoo.com.ar Thu Aug 13 01:36:07 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 02:36:07 -0300 Subject: Format Code Repeat Counts? References: <50697b2c0908121523jc495a65y1957a503b4f10566@mail.gmail.com> Message-ID: En Wed, 12 Aug 2009 19:23:32 -0300, Chris Rebert escribi?: > On Wed, Aug 12, 2009 at 4:34 PM, jschwab wrote: > >> As a more concrete example, say I have several sets of letters in a >> list of strings >> ? ? letters = ["aeiou", "hnopty", "egs", "amsp"] >> and I wanted to build a regular expression string out of them like >> ? ? re_str <==> "[aeiou][hnopty][egs][amsp]" >> Right now, the best I've got that doesn't require an explicit string >> like "[{1}][{2}][{3}][{4}]" is >> ? ? re_str = "".join(map(lambda x: "[{0}]".format(x), letters)) >> >> Is there a better way? > > Slightly better, by using a generator expression instead of map() and > lambda: > re_str = "".join("[{0}]".format(x) for x in letters) > > Though obviously MRAB's is shorter (and a good show of lateral thinking). Another way, using {} auto-numbering (requires Python 3.1 or the future 2.7) p3> letters = ["aeiou", "hnopty", "egs", "amsp"] p3> ("[{}]"*len(letters)).format(*letters) '[aeiou][hnopty][egs][amsp]' -- Gabriel Genellina From tjreedy at udel.edu Thu Aug 13 01:49:51 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Aug 2009 14:49:51 +0900 Subject: Social problems of Python doc [was Re: Python docs disappointing] In-Reply-To: References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <0292a134$0$20647$c3e8da3@news.astraweb.com> <3a15345c-9d01-48ab-8f15-dd6053ea70a0@b15g2000yqd.googlegroups.com> <0292cb5a$0$20647$c3e8da3@news.astraweb.com> Message-ID: Paul Boddie wrote: > Right, but those good points are still worth taking on board. There > have been Xah Lee posts which have been relatively constructive, The last time that he did do so that I read, I responded rationally like I would with any other normal post. He responded with foul insults. End of discussion. > when the only responses are from people who see the name and can't be > bothered reading the message before issuing a stock "he's a troll" False premise. > response, the tone is likely to remain vulgar from that point onwards. He was vulgar even when I did ignore the name and did bother to read and write (not 'issue') a specific response. He has also 'blown' opportunities on the py-dev list. tjr From tjreedy at udel.edu Thu Aug 13 02:02:45 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 13 Aug 2009 15:02:45 +0900 Subject: Need feedback on ORF-extracting code In-Reply-To: References: Message-ID: gb345 wrote: > > Hi everyone. I'm relatively new to Python, and could use your > feedback on the code below. > > First some nomenclature. A "nucleotide" is one of A, C, G, T, or > U. (In practice, a sequence of such nucleotides never contains > both T and U, but this fact is not important in what follows.) A > "codon" is a sequence of 3 of these. A "stop codon" is any one of > UAA, UAG, UGA, TAA, TAG, or TGA. Two codons are said to be "in > frame" in a containing sequence of nucleotides if their positions > differ by a multiple of 3. An "open reading frame," or ORF, is > defined as a maximal subsequence of nucleotides whose length is a > multiple of 3, begins with either AUG or ATG, terminates right > before a stop codon in the original sequence, and contains no stop > codons that are in frame with the initial codon (AUG or ATG). > > The fact that ORFs have lengths that are multiples of 3 means that > there are three possible "registers" for ORFs (depending the modulo > 3 of their starting positions), and that ORFs in different registers > can overlap. I'll refer to these registers as 0, 1, and 2, because > they contain ORFs that are in frame with the codons at positions > 0, 1, and 2 of the original sequence, respectively. > > In the code below, routine extract_orfs takes as input a string, > assumed to be a sequence of nucleotides, and returns a tuple of > tuples, describing ORFs. These ORFs can overlap. > > The helper routine _xo takes as input a string (a sequence of > nucleotides), and an offset, and returns a tuple of tuples, again > representing ORFs, but this time all in the same register, since > they are all in frame with the position passed as the second argument > to the function. > > I would appreciate your comments on this code. I feel that it is > not as clear as it could be, but I don't know how to make it any > clearer. > > (NOTE: I realize that, in all likelihood, publicly available Python > code already exists for this. At the moment I'm more interested > in improving my Python skills.) > > > Many thanks in advance! > > Gabe > > > > # BEGINNING OF CODE > import sys > import re > > _start = r'A[TU]G' > _stop = r'(?:[TU]A[AG]|[TU]GA)' > _nonstop = r'(?:[CAG][TUCAG]{2}|[TU](?:[TUC][TUCAG]|[AG][TUC])|[TU]GG)' > _codon = r'(?:[TUCAG]{3})' > _orf_re = re.compile('(' + _codon + r'*?)(A[TU]G' + > _nonstop + '*)(' + _stop + ')', flags=re.I) > _lead_re = re.compile(r'[TUCAG]*?A[TU]G', flags=re.I) > > def _xo(seq, pos): > """ > Helper routine that finds all the non-overlapping in-frame orfs > starting from a specific position in the input sequence. > > input: a string of letters in the set 'tucagTUCAG', and a starting > position; > output: a tuple of tuples; each internal tuple consists of a > starting position, an orf, and the stop codon that > terminates it. > """ > > ret = [] > while True: > m = _orf_re.match(seq, pos) > if not m: > break > orf = m.group(2) > stop = m.group(3) > assert len(orf) % 3 == 0 I am not currently familiar with the re module so I cannot comment in detail. The assert should be a claim that the re should *never* match anything other than a multiple of 3, so that it is a program bug if it ever do so. If this is not true, you should use an if statement. tjr > ret.append((m.start() + len(m.group(1)), orf, stop)) > pos = m.end() > return ret > > def extract_orfs(seq): > """ > Extracts all (possibly overlapping) maximal open reading frames, > defined as sequences beginning with AUG (or ATG), ending with an > in-frame stop codon, and containing no in-frame stop codons > in-between. > > input: a string of letters in the set 'tucagTUCAG'; > output: a tuple of tuples; each internal tuple consists of a > starting position, an orf, and the stop codon that > terminates it. > """ > > m = _lead_re.match(seq) > if not m: > return () > pos = m.start() > ret = [] > > for i in range(min(3, len(seq))): > ret.extend(_xo(seq, pos + i)) > ret.sort() > return tuple(ret) > > # END OF CODE From gagsl-py2 at yahoo.com.ar Thu Aug 13 02:16:15 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 03:16:15 -0300 Subject: How to find out in which module an instance of a class is created? References: <4A7F4874.8030008@johannes-janssen.de> <4A7F6016.2060408@cheimes.de> <4A80967F.9030604@johannes-janssen.de> Message-ID: En Mon, 10 Aug 2009 18:51:59 -0300, Johannes Janssen escribi?: > class A(object): > def __init__(self, mod=None): > if mod is None: > self.mod = sys._getframe(1).f_globals['__name__'] > else: > self.mod = mod > > In warnings.warn() they used try around sys._getframe(1). As far as I > understand what is done in warnings, there it is not sure what object > caused the warning and therefore it is not sure whether you can or > cannot use sys._getframe(1). Though in my case it should be quite clear. > Can I be sure that my code will always work? The try/except around sys._getframe(1) is because that function is not mandatory/available on all Python implementations (that's the case for jython which doesn't provide it). -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Thu Aug 13 02:28:53 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 03:28:53 -0300 Subject: How to page output in >>> ? References: Message-ID: En Wed, 12 Aug 2009 18:41:38 -0300, kj escribi?: > How does one tell the python interactive interpreter to run the > next output to stdout through the default pager? Basically, I'm > looking for Python's equivalent of Perl's debugger's "|" prefix, > as in > > DB<1> |print $long_output Try using pydoc.pager - read the source -- Gabriel Genellina From jeanmichel at sequans.com Thu Aug 13 02:36:59 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 13 Aug 2009 08:36:59 +0200 Subject: best practice for documenting a project? pydoc? In-Reply-To: References: Message-ID: <4A83B48B.1080307@sequans.com> Esmail wrote: > shaileshkumar wrote: >> Hello, >> >> EPYDOC is very good for automatic generation of documentation from >> source code. >> >> You may also consider Sphinx http://sphinx.pocoo.org/ which is used >> for many >> projects including the official Python documentation, documentation of >> Zope (http://docs.zope.org/). >> See the full list of projects using Sphinx at >> http://sphinx.pocoo.org/examples.html >> >> - Shailesh > > Hi, > > Thanks for the links. Have you heard of something called HappyDoc? I just > came across it by looking for info on epydoc. > > Thanks, > Esmail > I've never used Happydoc. I am using Epydoc, which is very efficient. Sphinx is very good as well, but its scope is much larger than documenting python code and will not provide the "click and run" effect of epydoc, for which you don't have to write any additional documentation. Epydoc supports restructured text, so you'll be able to switch to Sphinx later on without additional work. But if I remember well, your documentation is for personal use, so I guess you'll stick with epydoc. JM From gagsl-py2 at yahoo.com.ar Thu Aug 13 02:53:12 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 03:53:12 -0300 Subject: inspect.stack() performance References: <2a8674c60908060500k1c77b556la70d06d5feaaef0e@mail.gmail.com> Message-ID: En Thu, 06 Aug 2009 09:00:45 -0300, Doron Tal escribi?: > I use inspect.stack() to extract some info, such as file name, function > name > and line number, for the sake of logging (home brew logger). > I tested to see how much time it takes to execute the command: > > Python 2.4.3 (#1, Jan 21 2009, 01:11:33) > [GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import timeit >>>> t = timeit.Timer('inspect.stack()', 'import inspect') >>>> t.repeat(3,1000) > [0.28500604629516602, 0.28315305709838867, 0.29169297218322754] >>>> > > About 280uSec per call. > > If I log 1000 times per seconds than I get to spend 28% of the process > time > on inspect.stack() > Is there a better/quicker way of retrieving the same info? inspect loads the whole source code of every module in the stack (using linecache). If all you want is module name + line number, use this: f = sys._getframe() print f.f_globals['__name__'], f.f_lineno (see a recent post about warnings.warn too) -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Thu Aug 13 03:19:05 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 04:19:05 -0300 Subject: Monkeypatching an object to become callable References: <87hbwgu7xa.fsf@vostro.rath.org> <0aa46ece-64b9-4c28-b690-5ac5937ce3f2@f20g2000prn.googlegroups.com> <4a7fd55e$0$32765$426a74cc@news.free.fr> <87iqguey37.fsf@vostro.rath.org> Message-ID: En Tue, 11 Aug 2009 20:21:16 -0300, Nikolaus Rath escribi?: > Bruno Desthuilliers writes: >> 7stud a ?crit : >> (snip) >>> class Wrapper(object): >>> def __init__(self, obj, func): >>> self.obj = obj >>> self.func = func >>> >>> def __call__(self, *args): >>> return self.func(*args) >>> >>> def __getattr__(self, name): >>> return object.__getattribute__(self.obj, name) >> >> This should be >> >> return getattr(self.obj, name) >> >> directly calling object.__getattribute__ might skip redefinition of >> __getattribute__ in self.obj.__class__ or it's mro. > > Works nicely, thanks. I came up with the following shorter version which > modifies the object in-place: > > class Modifier(obj.__class__): > def __call__(self): > return fn() > > obj.__class__ = Modifier > > > To me this seems a bit more elegant (less code, less underscores). Or > are there some cases where the above would fail? I assume the above code is inside a function like make_callable(obj, fn) Then, a new class is created for every instance you make callable; you may want to cache all those classes (classes aren't cheap). Might fail: when obj is not a new-style class, or its __class__ isn't writable (e.g. builtin types). -- Gabriel Genellina From chris at simplistix.co.uk Thu Aug 13 03:20:37 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Thu, 13 Aug 2009 08:20:37 +0100 Subject: httplib incredibly slow :-( In-Reply-To: <4eb0089f0908121753o5ecf141dj304b21c3df0d3d6b@mail.gmail.com> References: <4A81D3CB.7080209@simplistix.co.uk> <4A82EFDC.70502@simplistix.co.uk> <4eb0089f0908121753o5ecf141dj304b21c3df0d3d6b@mail.gmail.com> Message-ID: <4A83BEC5.40101@simplistix.co.uk> David Robinow wrote: > On Wed, Aug 12, 2009 at 12:37 PM, Chris Withers wrote: >> David Stanek wrote: >>> Also on the same box where you run this script >>> can you test with curl or wget? >> It's a Windows box, so no :-( > > Why not? > > http://users.ugent.be/~bpuype/wget/ > http://curl.haxx.se/download.html Fair point, but I don't see what this will achieve... I've already established that the file downloads in seconds with [something else], so I'd like to understand why python isn't doing the same and fix the problem... Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From darkwater42 at gmail.com Thu Aug 13 03:37:42 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Thu, 13 Aug 2009 00:37:42 -0700 (PDT) Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com> <7877b03a-09da-4836-804c-502b6f78003c@h21g2000yqa.googlegroups.com> <02933e60$0$20647$c3e8da3@news.astraweb.com> Message-ID: <2cdc3f88-1952-4ca2-9754-5b7583fb5fd8@z31g2000yqd.googlegroups.com> On Aug 12, 7:19?pm, Steven D'Aprano wrote: > You are making an unjustified assumption: \y is not an error. You are making in an unjustified assumption that I ever made such an assumption! My claim is and has always been NOT that \y is inately an error, but rather that treating unrecognized escape sequences as legal escape sequences is error PRONE. > While I'm amused that you've made my own point for me, I'm less > amused that you seem to be totally incapable of seeing past your > parochial language assumptions, Where do you get the notion that my assumptions are in any sense "parochial"? They come from (1) a great deal of experience programming very reliable software, and (2) having learned at least two dozen different programming languages in my life. > I disagree with nearly everything you say in this post. I think > that a few points you make have some validity, but the vast > majority are based on a superficial and confused understanding > of language design principles. Whatever. I've taken two graduate level classes at MIT on programming languages design, and got an A in both classes, and designed my own programming language as a final project, and received an A+. But I guess I don't really know anything about the topic at all. > But it's not the only reasonable design choice, and Bash has > made a different choice, and Python has made yet a third > reasonable choice, and Pascal made yet a fourth reasonable choice. And so did Perl and PHP, and whatever other programming language you happen to mention. In fact, all programming languages are equally good, so we might as well just freeze all language design as it is now. Clearly we can do no better. > One party insisting that red is the only logical colour for a > car, and that anybody who prefers white or black or blue is > illogical, is unacceptable. If having all cars be red saved a lot of lives, or increased gas mileage significantly, then it might very well be the best color for a car. But of course, that is not the case. With programming languages, there is much more likely to be an actual fact of the matter on which sorts of language design decisions make programmers more productive on average, and which ones result in more reliable software. I will certainly admit that obtaining objective data on such things is very difficult, but it's a completely different thing that one's color preference for their car. |>ouglas From deets at nospam.web.de Thu Aug 13 04:01:53 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 13 Aug 2009 10:01:53 +0200 Subject: resume upload wsgi script In-Reply-To: References: <36993141-188c-4b13-8819-e60516d27437@o36g2000vbl.googlegroups.com> <7e80jlF2etv0kU1@mid.uni-berlin.de> <7e85i3F2fdc1eU1@mid.uni-berlin.de> <9cd75067-8839-44dd-9b42-4ffb15488b66@r27g2000vbn.googlegroups.com> <7e8ildF2f1hcpU1@mid.uni-berlin.de> <49e41062-9e0d-4c5e-beca-edb02d3ce6e8@e34g2000vbm.googlegroups.com> <7ea4lpF2dvr5cU1@mid.uni-berlin.de> Message-ID: <7ehvjhF2ghuo2U1@mid.uni-berlin.de> gert schrieb: > On Aug 10, 10:39 am, "Diez B. Roggisch" wrote: >>> 250KB :) >> So why do you bother? >> >>> Its just HTTP1.1 has everything for making ftp like file transfers >>> possible. >>> When I write it to a file then I am back at square one because I still >>> need to load it completely to get it into a blob. >> Well, the blob is nothing but datat in the file-system. If you are >> *really* concerned about that, then don't use the db, but use the >> filesystem, appending to the file until it's finished - and storing a >> reference to it to the DB. We do that as well, because otherwise the db >> will become unmanagable anyway (dumping, backups). >> > > I also hate debugging sql that contains blob data. So if using files > how do you clean the http post stuff? > (b+r'.*?Content-Type: application/octet-stream\r\n\r\n(.*?)\r > \n--'+b,file,DOTALL) > using as litlle memory as possible ? > I can not use PUT upload only because flash does not support PUT. PUT or POST has nothing todo with that. It's the question if you need formencoded data or not. If not, you can simply upload the data directly, no nead to cleanup anything. For decoding formencoded data, you will need to write your own parser if you insist on these very debatable memory-constraints of yours. Diez From efotinis at y Thu Aug 13 04:56:04 2009 From: efotinis at y (Elias Fotinis (eliasf)) Date: Thu, 13 Aug 2009 11:56:04 +0300 Subject: Nice copy in interactive terminal In-Reply-To: References: Message-ID: <1250153823.228153@athprx03> "casebash" wrote: > I've been wondering for a while if there exists an interactive > terminal which has nice copy feature (ie. I can copy code without > getting the >>> in front of every line). It would help if we knew what platform you're interested in -- your User-Agent is G2/1.0, but I don't know what that is. :o) On Windows, PythonWin can copy from the interactive window without the prompts. From gagsl-py2 at yahoo.com.ar Thu Aug 13 05:28:25 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 13 Aug 2009 06:28:25 -0300 Subject: Unsigned char array to an unsigned longlong array References: Message-ID: En Tue, 11 Aug 2009 23:22:27 -0300, Jus escribi?: > Is there a way to have an Array of unsigned longlong (C Type: unsigned > longlong, Minimum size if bytes: 8) ? > > What I want to do is to store an array of bytes in an array of longlongs. > > To workaround this issue, I have tried to use the double array (TypeCode > 'd'), since the size in bytes is the same (8 for instance). Do you want to operate on it from inside Python, or manage it in some way? If not, use whatever format you like, even bytes. It's just a contiguous memory block with a known size. > But it gives me strange result. Please look at the example: > > > import array > > myByteArray = array.array('B', [1,2,3,4,5,6,7,8]) > myLongArray = array.array('L', myByteArray.tostring() ) >>> myLongArray = array('L', [67305985L, 134678021L]) > myDoubleArray = array.array('d', myByteArray.tostring() ) >>> myDoubleArray = array('d', [5.447603722011605e-270]) > > If we convert the byte array to an hex form, we will get for the long > array: > [04030201, 08070605]. What do you mean "convert the byte array to an hex form"? > If we convert this hex array to decimal, we then get the Long Array: > [67305985, 134678021]. > > > Now, if we do the same exercise for the double array, the hex form will > look > like: [0807060504030201]. > > And the decimal value would be: [5.784376957523072e+17]. How did you got that? > Where does the 5.447603722011605e-270 value comes from ? The struct module agrees: py> s=struct.pack('q', 0x0807060504030201) py> struct.unpack('d', s) (5.447603722011605e-270,) And looking at the hex representation: py> (5.447603722011605e-270).hex() '0x1.7060504030201p-895' The 1. is implied, 7060504030201 are visible (52 bits), and the exponent is: py> hex(-895+1023) '0x80' So that value seems OK to me, at least with IEEE 754 hardware... -- Gabriel Genellina From erik.bernoth at googlemail.com Thu Aug 13 05:32:53 2009 From: erik.bernoth at googlemail.com (Erik Bernoth) Date: Thu, 13 Aug 2009 11:32:53 +0200 Subject: what is it, that I don't understand about python and lazy evaluation? Message-ID: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Hi List, look at the following code: def evens(): # iterator returning even numbers i = 0 while True: yield i i += 2 # now get all the even numbers up to 15 L = [n for n in evens() if n < 15] Isn't it strange, that this code runs (in a lazy language) for eternity? I would expect python to to spit out (in no time): >> L [0, 2, 4, 6, 8, 10, 12, 14] after 14 it is not nessesary to evaluate evens() any further. I really started to ask myself if python really is lazy, but everything else I wrote in lazy style still worked. Example: >> def test(txt, retval): .. print(txt) .. return retval .. >>> test(1, True) or test(2, True) 1 True >>> test(1, True) and test(2, True) 1 2 True Can anybody explain what happens with evens()? best regards Erik Bernoth PS: The code comes from a list post from 2006. You find it here: http://mail.python.org/pipermail/python-list/2006-November/585783.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From andreengels at gmail.com Thu Aug 13 05:58:15 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 13 Aug 2009 11:58:15 +0200 Subject: Scraping Wikipedia with Python In-Reply-To: <6YidncRAiJ6SIxzXRVn_vwA@giganews.com> References: <4a81b6f0$0$1590$742ec2ed@news.sonic.net> <6YidncRAiJ6SIxzXRVn_vwA@giganews.com> Message-ID: <6faf39c90908130258q21f9c45cqca0c0a0db0a55b6e@mail.gmail.com> On Tue, Aug 11, 2009 at 8:53 PM, David C Ullrich wrote: > Try reading a little there! Starting there I went to > > http://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot > > where I found a section on existing bots, comments on how the "scraping" > is not what you want, and even a Python section with a link to something > labelled ?PyWikipediaBot... Some information on using the PyWikipediaBot for scraping from someone who used to program on the bot (and occasionally still does): To make the framework work, you need to add a file user-config.py with the following contents: family = 'wikipedia' mylang = 'en' If you want to use the bot to also edit pages on wikipedia, you will have to add: usernames['wikipedia']['en'] = If you work on another language of course you use that language's abbreviation instead of en. The heart of the framework is the file wikipedia.py, you need to import that one. It contains two important classes: Page and Site, which represent a wikipedia page and the site as a whole, respectively. It is best to put your code in a try like this: try: mysite = wikipedia.getSite() finally: wikipedia.stopme() The stopme() functionality has to do with the bot's behaviour to avoid over-feeding the server with requests. It has a certain time (default is 10 seconds) between two requests, but if you have several bots running, it will lengthen this time. stopme() tells that the bot is not running any more, so other runs are not delayed by it. wikipedia.getSite() gets the site object for your default site (if the settings above are chosen it is the English language Wikipedia). Still with me? Good, because now we get into the real programming. The Page class has as its __init__: def __init__(self, site, title, insite=None, defaultNamespace=0): site is here the wiki on which the page exists (usually this will be mysite, which is why I defined it above), title the title of the page. The optional parameters are for special usage. The Page class has a number of methods, which you can find in the file, but some of the most important are: page.title() - the title of the page page.site() - the wiki the page is on page.get() - the (wiki) text of the page page.put(text) - saves the page with 'text' as its new content. An important optional parameter is 'comment', which specifies the summary that is given with the change page.exists() - a boolean, true if the page exists, false otherwise page.linkedPages() - a list of Page objects, being the pages the page links to However, instead of page.get() it is advisable to use: wikipedia.getall(site,pages) with 'site' being a Site object (e.g. mysite) and pages a list (or more generally, iterable) of Page objects. It will get all pages in the list using a single call to the wiki, thus speeding up your bot and at the same time reducing its load on the wiki. Once a page has been loaded (either through get or through getall), subsequent calls to page.get() will not reload it. Thus, the normal way of working is to create a list of pages one is interested in, use getall (in groups of 60 or so) to load them, then use get to work with them. Another useful file in the framework is pagegenerators. It provides a number of generators that yield Page objects. Some interesting ones (check the code for the exact parameters): AllpagesPageGenerator: generates all pages of the wiki, alphabetically from a specified begin ReferringPageGenerator: all pages linking to a given page CategorizedPageGenerator: all pages in a given directory LinkedPageGenerator: all pages linked to from a given page Other generators are used by 'wrapping them around' a given generator. The most important of these is the PreloadingGenerator, which ensures that the page are preloaded (using wikipedia.getall) in groups. A simple way to use the bot framework to scrape all pages of the English Wikipedia (warning: This takes a few days!) would be: import wikipedia import pagegenerators basicgen = pagegenerators.AllpagesPageGenerator(includeredirects = False) generator = pagegenerators.PreloadingGenerator(basicgen, 200) for page in generator: title = page.title() text = page.get() -- Andr? Engels, andreengels at gmail.com From ben+python at benfinney.id.au Thu Aug 13 06:00:17 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Thu, 13 Aug 2009 20:00:17 +1000 Subject: subprocess + python-daemon - bug/problem? References: <699d22bd-e912-4ea3-92b0-c352a64611fb@n11g2000yqb.googlegroups.com> <828acd8d-a9bd-4506-b695-e537af4587d8@l31g2000yqb.googlegroups.com> <873a94ojvi.fsf@benfinney.id.au> Message-ID: <87hbwc58zy.fsf@benfinney.id.au> Ben Finney writes: > My first thought was perhaps it's related to the fact that the process > has no stdout? But setting ?stdout? and ?stderr? to the same file:: > > #! /usr/bin/python > > import daemon > import subprocess > > fake_console = open("fake_console.txt", "w+") > daemon.DaemonContext(stdout=fake_console, stderr=fake_console).open() > subprocess.Popen(['echo', '1']).wait() For newcomers to this thread: the ?daemon? module is provided by the ?python-daemon? distribution, of which I am the maintainer. > still gives the same error:: > > 1 > Traceback (most recent call last): > File "/home/bignose/Projects/python/python-daemon/bin/andy-clegg-test", line 8, in > subprocess.Popen(['echo', '1']).wait() > File "/usr/lib/python2.5/subprocess.py", line 1184, in wait > pid, sts = self._waitpid_no_intr(self.pid, 0) > File "/usr/lib/python2.5/subprocess.py", line 1014, in _waitpid_no_intr > return os.waitpid(pid, options) > OSError: [Errno 10] No child processes > > I'm not familiar enough with the nuances of the ?subprocess? module to > know what might be going wrong here. I'd like to know whether it might > be a problem in the ?python-daemon? library. I am no closer to a solution on this one. I don't have enough experience or knowledge of the ?subprocess? module to know whether it's a bug in ?subprocess?, a bug in ?python-daemon?, or a hard-to-track interaction between the two. Any narrowing of the problem would be appreciated. -- \ ?I bought a dog the other day. I named him Stay. It's fun to | `\ call him. ?Come here, Stay! Come here, Stay!? He went insane. | _o__) Now he just ignores me and keeps typing.? ?Steven Wright | Ben Finney From BrianVanderburg2 at aim.com Thu Aug 13 06:07:11 2009 From: BrianVanderburg2 at aim.com (Brian Allen Vanderburg II) Date: Thu, 13 Aug 2009 06:07:11 -0400 Subject: what is it, that I don't understand about python and lazy evaluation? In-Reply-To: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Message-ID: <4A83E5CF.7080208@aim.com> Erik Bernoth wrote: > Hi List, > > look at the following code: > > def evens(): > # iterator returning even numbers > i = 0 > while True: > yield i > i += 2 > > # now get all the even numbers up to 15 > L = [n for n in evens() if n < 15] > > Isn't it strange, that this code runs (in a lazy language) for > eternity? I would expect python to to spit out (in no time): > >> L > [0, 2, 4, 6, 8, 10, 12, 14] > > after 14 it is not nessesary to evaluate evens() any further. > > I really started to ask myself if python really is lazy, but > everything else I wrote in lazy style still worked. Example: > >> def test(txt, retval): > .. print(txt) > .. return retval > .. > >>> test(1, True) or test(2, True) > 1 > True > >>> test(1, True) and test(2, True) > 1 > 2 > True > > > Can anybody explain what happens with evens()? > > best regards > Erik Bernoth > > PS: The code comes from a list post from 2006. You find it here: > http://mail.python.org/pipermail/python-list/2006-November/585783.html In the list comprehension, it goes over all the items from the generator until the generator is done, and any item that is less than 15 becomes part of the list. The "if n < 15" does not control when the generator terminates, only which results from it are selected to be part of the list. You can pass the maximum desired value to make it terminate: def evens(max): i = 0 while i <= max: yield i i += 2 L = list(evens(15)) L: [0, 2, 4, 6, 8, 10, 12, 14] L = [n for n in evens(15)] L: [0, 2, 4, 6, 8, 10, 12, 14] Brian Vanderburg II From dmhouse at gmail.com Thu Aug 13 07:11:18 2009 From: dmhouse at gmail.com (David House) Date: Thu, 13 Aug 2009 12:11:18 +0100 Subject: what is it, that I don't understand about python and lazy evaluation? In-Reply-To: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Message-ID: 2009/8/13 Erik Bernoth : > after 14 it is not nessesary to evaluate evens() any further. How does Python know this? I.e. how does it know that evens() will always yield things in ascending order? For example, I could write an iterator like this: def my_iter(): for i in [0,2,4,6,8,10,12,14,16,18,1,3,5]: yield i Now, imagine I do [i for i in my_iter() if i < 15]. If you quit iterating after `i' becomes 16, you'll miss the valid numbers 1, 3, 5 at the end of the list! -- -David From python at mrabarnett.plus.com Thu Aug 13 07:23:50 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 13 Aug 2009 12:23:50 +0100 Subject: what is it, that I don't understand about python and lazy evaluation? In-Reply-To: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Message-ID: <4A83F7C6.2060301@mrabarnett.plus.com> Erik Bernoth wrote: > Hi List, > > look at the following code: > > def evens(): > # iterator returning even numbers > i = 0 > while True: > yield i > i += 2 > > # now get all the even numbers up to 15 > L = [n for n in evens() if n < 15] > > Isn't it strange, that this code runs (in a lazy language) for eternity? > I would expect python to to spit out (in no time): > >> L > [0, 2, 4, 6, 8, 10, 12, 14] > > after 14 it is not nessesary to evaluate evens() any further. > It's equivalent to: L = [] for n in evens(): if n < 15 L.append(n) From davea at ieee.org Thu Aug 13 07:50:30 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 07:50:30 -0400 Subject: fileinput In-Reply-To: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> References: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> Message-ID: <4A83FE06.90305@ieee.org> naaman wrote: > On Aug 12, 1:35 pm, Dave Angel wrote: > >> naaman wrote: >> >>> I'm writing my first Python script and >>> I want to use fileinput to open a file in r+ mode. >>> Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. >>> ANy ideas? >>> >>> Need to find and overwrite a line in a file several times. >>> I can do it using open and seek() etc. but was wondering if I can use >>> fileinput. >>> >>> thanks; >>> >> I haven't used it, but check out the 'inplace' keyword parameter. >> >> DaveA >> > > I've only Python for a week so I'm not sure what inplace does > > You should read the docs for it ( http://www.python.org/doc/2.6.2/library/fileinput.html ), but it's not very clear to me either So I dug up an example on the web: (ref: http://effbot.org/librarybook/fileinput.htm ) import fileinput, sys for line in fileinput.input(inplace=1): # /convert Windows/DOS text files to Unix files/ if line[-2:] == "\r\n": line = line[:-2] + "\n" sys.stdout.write(line) The inplace argument tells it to create a new file with the same name as the original (doing all the necessary nonsense with using a scratch file, and renaming/deleting) for each file processed. Stdout is pointed to that new version of the file. Notice that you have to explicitly write everything you want to wind up in the file -- if a given line is to remain unchanged, you just write "line" directly. If you're new to Python, I do not recommend trying to do open/seek to update a text file in place, especially if you're in DOS. There are lots of traps. the inplace method of fileinput avoids these by implicitly creating temp files and handling the details for you, which probably works great if you're dealing with text, in order. DaveA From sjmachin at lexicon.net Thu Aug 13 07:58:33 2009 From: sjmachin at lexicon.net (John Machin) Date: Thu, 13 Aug 2009 04:58:33 -0700 (PDT) Subject: csv.DictWriter.write_header() References: Message-ID: <68b9136d-fa0b-42dc-addf-02d338da34cd@z4g2000prh.googlegroups.com> On Aug 13, 1:15?pm, Alan G Isaac wrote: > > On Aug 13, 6:45 am, Alan G Isaac wrote: > >> Given a csv.DictWriter instance `dw` > >> I think it would be nice to be able to > >> say dw.write_header() > >> instead of > >> dw.writer.writerow(dw.fieldnames) > > >> Good idea? > > On 8/12/2009 10:24 PM John Machin apparently wrote: > > > Yes, it's a brilliant idea. All you have to do is insert the following > > lines in your code after importing csv: > > > csv.DictWriter.write_header = ( > > ? ? lambda dw: dw.writer.writerow(dw.fieldnames) > > ? ? ) > > I do not understand the reason for your silly, sarcastic response. Duck typing: ask a silly question, get a silly answer. > I already showed you how to achieve the result, What result? You said (in effect) "I think it would be nice to be able to write A instead of B". You didn't show any way of setting things up so that one could write A instead of B. I showed one way. Other possibilities are a 2-line patch to the users own csv.py, and submitting a patch to the dev team. The second is kludgy, and there could be a wait until e.g. 2.7 before the third happens. So back to the first way; everybody should have a utility module that they import to do little fixes like that ... here is a slightly more robust version: import csv try: csv.DictWriter.write_header except AttributeError: csv.DictWriter.write_header = ( lambda dw: dw.writer.writerow(dw.fieldnames) ) > so obviously > I am not just asking for my own personal gain. ??? > I take it you do not realize that many users do not see > a simple way to get this often needed functionality. No, I don't. How did you come to that realisation? AFAICT they don't ask in this forum or on StackOverflow. > (For example, see the gymnatics suggested by Shai Vaingast > in his otherwise excellent and useful book.) I can imagine that one might (without reading the source) make do with the published APIs: dw = csv.DictWriter(open(...), my_field_names dw.writerow(dict((fn, fn) for fn in my_field_names)) > And indeed, > there is no reason to expect them to. Indeed not, as for somebody who otherwise sees utility in the DictWriter class not having a writer_headers method is a glaring deficiency. Note that there is a difference between "expecting C to do X" and "expecting C to be able to do X". I really hope you don't mean that people should not be encouraged to be able to write a trivial class like csv.DictWriter and add trivial functionality themselves ... or to be able to just write the required functionality inline: wtr = csv.writer(open(...), ...) wtr.writerow(my_field_names) for adict in source_of_dicts(): wtr.writerow(adict[fn] for fn in my_field_names) or even: for obj in source_of_objects(): wtr.writerow(getattr(obj, fn) for fn in my_field_names) > So my question was, would this improve the class from > a usability perspective? Of course. > ?Do you have a useful response? See above. Also, the csv module appears to be in two minds about underscores in attribute names (field_size_limit, skipinitialspace, writerow, writerows) -- it may cause less confusion if it were called writeheader (consistent with writerow). From ebonak at hotmail.com Thu Aug 13 08:29:48 2009 From: ebonak at hotmail.com (Esmail) Date: Thu, 13 Aug 2009 08:29:48 -0400 Subject: best practice for documenting a project? pydoc? In-Reply-To: <4A83B48B.1080307@sequans.com> References: <4A83B48B.1080307@sequans.com> Message-ID: Hello Jean-Michel, Thanks for your post. Based on it, and the ones received so far I will give epydoc a closer look. I don't need something superfancy (at least at the moment), just something that helps me document my code more in an organized way and helps me sift through the various classes/methods more easily once I come back to the project after some lengthy interruptions. Best, Esmail Jean-Michel Pichavant wrote: > > > I've never used Happydoc. I am using Epydoc, which is very efficient. > Sphinx is very good as well, but its scope is much larger than > documenting python code and will not provide the "click and run" > effect of epydoc, for which you don't have to write any additional > documentation. Epydoc supports restructured text, so you'll be able to > switch to Sphinx later on without additional work. > But if I remember well, your documentation is for personal use, so I > guess you'll stick with epydoc. From drobinow at gmail.com Thu Aug 13 08:44:12 2009 From: drobinow at gmail.com (David Robinow) Date: Thu, 13 Aug 2009 08:44:12 -0400 Subject: httplib incredibly slow :-( In-Reply-To: <4A83BEC5.40101@simplistix.co.uk> References: <4A81D3CB.7080209@simplistix.co.uk> <4A82EFDC.70502@simplistix.co.uk> <4eb0089f0908121753o5ecf141dj304b21c3df0d3d6b@mail.gmail.com> <4A83BEC5.40101@simplistix.co.uk> Message-ID: <4eb0089f0908130544t72affa8ep7aa364806a94f9bb@mail.gmail.com> On Thu, Aug 13, 2009 at 3:20 AM, Chris Withers wrote: > David Robinow wrote: >> >> On Wed, Aug 12, 2009 at 12:37 PM, Chris Withers >> wrote: >>> >>> David Stanek wrote: >>>> >>>> Also on the same box where you run this script >>>> can you test with curl or wget? >>> >>> It's a Windows box, so no :-( >> >> Why not? >> >> http://users.ugent.be/~bpuype/wget/ >> http://curl.haxx.se/download.html > > Fair point, but I don't see what this will achieve... > > I've already established that the file downloads in seconds with [something > else], so I'd like to understand why python isn't doing the same and fix the > problem... My post was simply to correct the implication that curl and wget can not be used on Windows. It's up to you whether you want to use one or the other. I'm not the OP, and this is not my area of expertise, but ... You've got two data points. You've jumped to the conclusion that there's something wrong with Python or your code. You're probably right. However, if you try wget, for example, and it's as slow as your code, you cqn look elsewhere. If, on the other hand, wget is as fast as IE, you'll have more proof that your code is the problem. Then, since wget is open source you can look at the source code and see what wget is doing right that you (or httplib) is doing wrong. From catalinfest at gmail.com Thu Aug 13 08:55:56 2009 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Thu, 13 Aug 2009 05:55:56 -0700 (PDT) Subject: PIL and Python Message-ID: Hello ! I want use python to change the "note" from .jpeg files . What is the functions on PIL how make this ? Thank you ! From invalid at invalid Thu Aug 13 09:24:07 2009 From: invalid at invalid (Grant Edwards) Date: Thu, 13 Aug 2009 08:24:07 -0500 Subject: How to launch a function at regular time intervals ? References: Message-ID: On 2009-08-13, Dave Angel wrote: > I'm assuming you want to call it every time_interval seconds, on > average, with a little jitter allowed on each call, but keeping correct > long term. In other words, if one call is a little late, you want the > next one to still happen as close to on-time as possible. > > The general outline is something like (untested): > > times_called = 0 #number of times function has been called > start_time = now > while True: > elapsed = now - start_time > int_elapsed = int(elapsed/time_interval) > for times_called in range(times_called, int_elapsed): > call_the_function() > sleep(time_interval/10) #this might give us 10% jitter, which is usually fine I don't understand the reasoning behind the above loop -- specifically the sleeping of smaller intervals than needed. Why not something like this: interval = 5.0 # interval in seconds next = time.time() while True: now = time.time() if now < next: time.sleep(now-next) print "call_the_function()" next += interval That will be accurate over the long term with minimal jitter. From squishywaffle at gmail.com Thu Aug 13 09:31:25 2009 From: squishywaffle at gmail.com (Greg Taylor) Date: Thu, 13 Aug 2009 06:31:25 -0700 (PDT) Subject: Networked Broadcast Messaging References: <37ea826b-708d-48f4-a64a-42f58fec5325@c2g2000yqi.googlegroups.com> Message-ID: <859b8238-a730-4699-a94f-618f7311f58f@a13g2000yqc.googlegroups.com> On Aug 11, 9:18?pm, David Bolen wrote: > > If you want better guarantees, you might look into a distributed > message bus like Spread (http://www.spread.org/) or perhaps a > messaging protocol like XMPP (http://xmpp.org/) through its PubSub > extension. ?Both have Python interfaces, though I have no personal > experience with either. ?But perhaps that will also give you some > terms or starting points for searching for other options. This is also very helpful. In particular Spread, looks very attractive. Thanks for the tip, Greg From solipsis at pitrou.net Thu Aug 13 09:32:29 2009 From: solipsis at pitrou.net (Antoine Pitrou) Date: Thu, 13 Aug 2009 13:32:29 +0000 (UTC) Subject: what is it, that I don't understand about python and lazy evaluation? References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Message-ID: Erik Bernoth googlemail.com> writes: > > Isn't it strange, that this code runs (in a lazy language) for eternity? Python is a not a lazy language. `and` and `or` are particular, they are language constructs (*), not operators, that's why they can decide whether or not to evaluate their second term. It's a feature, but this feature is not general to Python. (*) by this I mean they have similar status as, for example, `if` and `else` From ebonak at hotmail.com Thu Aug 13 09:43:12 2009 From: ebonak at hotmail.com (Esmail) Date: Thu, 13 Aug 2009 09:43:12 -0400 Subject: Plotting Quadratic Functions, pygame In-Reply-To: References: Message-ID: Hello Senad, You might find this style guide useful too in your toolbox of Python skills & tricks. http://www.python.org/dev/peps/pep-0008/ This is a great and helpful group of people here, we are lucky to have access to groups like this. Best, Esmail From rurpy at yahoo.com Thu Aug 13 10:05:18 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Thu, 13 Aug 2009 07:05:18 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> Message-ID: <3d808272-6e56-4cf1-90df-8e5201df02df@c34g2000yqi.googlegroups.com> On 08/12/2009 12:27 PM, Raymond Hettinger wrote: > On Aug 12, 3:32 am, Paul Boddie wrote: >> Maybe the problem is that although everyone welcomes contributions and >> changes (or says that they do), the mechanisms remain largely beyond >> criticism. > > FWIW, I support the idea the regular docs incorporating links to > freely editable wiki pages. That will at least make it easier for > people to make changes or add notes. > > That being said, I would like to add a few thoughts about the > current process. ISTM that important corrections (when the > docs are clearly in error) tend to get made right away. What > is more interesting are the doc requests that get rejected > and why: [...snip interesting categorization of "bad" doc enhancement suggestions...] > In short, most doc requests that get rejected are requests that didn't > actually improve the documentation. > > I do support links from the regular docs to an external wiki but the > main docs should continue to go through the regular process using the > tracker. What is the purpose of such a wiki? 1. To provide hopefully useful adjunct information for each doc page? 2. To provide a source of input for improving the next version of the docs? In general I have a low opinion of wikis. Nearly all the ones I've seen are trash heaps of out-dated and wrong information, atrocious writing, and comments that look like the middle of some arcane usenet thread. They lack organization making it very difficult to find the needles of good information in the haystack of junk. The only one that seems to work is Wikipedia and it "works" because it has a very heavy-weight process controlling contributions. (And even then, my biggest complaint with Wikipedia is the poor writing quality in a lot of articles.) I'm not trying to be negative, only pointing out that to serve either of the goals I asked about above, a wiki will probably require a considerable management effort that should be faced up front. To simply set up a wiki and "wait for it to self-organize" (as I here read once) is a pipe-dream. How will it be managed? Anything written stays? If not what standards are used to remove junk entries? Wrong entries? Questionable entries? Who will do this? Will they act based on their own judgment or some documented formal standards? What happens to comments when a new doc version is released? What happens when entries become obsolete? What happens when comments are disputed? If the goal is (2) what kind of wiki contributions are being solicited ("I don't understand what this sentence means"? a complete rewrite of a section?) and how is that communicated? Who will take a long string of wiki comments constituting a discussion and condense them into something that can be submitted as a doc patch? (This I suspect is where the work is, where someone with good writing skills is needed.) Will this process be sufficient to raise the quality of the docs significantly, or are other steps also needed such as an attitude shift in what the core committers consider acceptable? If the goal is (1) above, it could potentially have a deleterious effect on the docs in that it will be easier to respond to requests to expand some description with, "there's no need since that is covered in (or belongs in) the wiki comments". All the above not withstanding, I too think a wiki is worth trying. But without doing a lot more than just "setting up a wiki", I sadly believe even a python.org supported wiki is doomed to failure. From ifl2009 at shu.edu Thu Aug 13 10:16:45 2009 From: ifl2009 at shu.edu (IFL 2009) Date: Thu, 13 Aug 2009 10:16:45 -0400 Subject: IFL 2009: Final Call for Papers and Participation Message-ID: An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Thu Aug 13 10:46:15 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 13 Aug 2009 07:46:15 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> <3d808272-6e56-4cf1-90df-8e5201df02df@c34g2000yqi.googlegroups.com> Message-ID: <13be5a11-612b-4fc5-a220-cc9aba2e4f8c@z31g2000yqd.googlegroups.com> On 13 Aug, 16:05, ru... at yahoo.com wrote: > > All the above not withstanding, I too think a wiki is worth > trying. ?But without doing a lot more than just "setting up > a wiki", I sadly believe even a python.org supported wiki > is doomed to failure. The ones on python.org seem to function reasonably well. I accept that they could be more aggressively edited, but this isn't done because there's a compromise between letting people contribute and keeping things moderately coherent, with the former being favoured. For other purposes, it would be quite acceptable to favour editorial control. I won't argue that providing infrastructure solves a problem - that's precisely the kind of thing I was criticising when I noted that some people will readily criticise the choice of tools to do a job instead of focusing on the job that has to be done - and you need people who are reasonably competent editors, but Wiki solutions remove a lot of technical barriers. I'm not arguing for the flavour of Wiki which implies unfettered, anonymous access from everyone on the Internet, either: the kind of Wiki that detractors portray all Wiki solutions as being in order to further their super-special "it has to fit like a glove or it's totally unusable" software agenda. It's quite possible to have people with somewhat more privileges than others in order to keep the peace, and they don't all need to have an entrenched editorial interest: on the current python.org Wiki sites, most of the administrators don't have an active interest in most of the content, but they are able to exercise control when it's clear that some contributors aren't particularly interested in actually improving the content. As well as having an active community effort around the existing python.org Wiki sites, there are also people who are interested in improving these offerings. What worries me is that despite such activity and such interest, many people will continue to lament the lack of vitality (or whatever other metric) of the general python.org offering, whilst retaining a blind spot for the obvious contribution that the Wikis can make to such improvement efforts. I encourage people to use wiki.python.org a lot more, should they be looking to improve the wealth of information provided by the community. Paul From ethan at stoneleaf.us Thu Aug 13 10:47:56 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Aug 2009 07:47:56 -0700 Subject: what is it, that I don't understand about python and lazy evaluation? In-Reply-To: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Message-ID: <4A84279C.2030504@stoneleaf.us> Erik Bernoth wrote: > Hi List, > > look at the following code: > > def evens(): > # iterator returning even numbers > i = 0 > while True: > yield i > i += 2 > > # now get all the even numbers up to 15 > L = [n for n in evens() if n < 15] > > Isn't it strange, that this code runs (in a lazy language) for eternity? > I would expect python to to spit out (in no time): > >> L > [0, 2, 4, 6, 8, 10, 12, 14] > > after 14 it is not nessesary to evaluate evens() any further. > > I really started to ask myself if python really is lazy, but everything > else I wrote in lazy style still worked. Example: > >> def test(txt, retval): > .. print(txt) > .. return retval > .. > >>> test(1, True) or test(2, True) > 1 > True > >>> test(1, True) and test(2, True) > 1 > 2 > True > > > Can anybody explain what happens with evens()? > > best regards > Erik Bernoth > > PS: The code comes from a list post from 2006. You find it here: > http://mail.python.org/pipermail/python-list/2006-November/585783.html > As MRAB pointed out, the issue is not with evens, it's with the list comprehension. The list comprehension doesn't know when to stop, only which numbers to include. ~Ethan~ From jschwab at gmail.com Thu Aug 13 11:01:20 2009 From: jschwab at gmail.com (jschwab) Date: Thu, 13 Aug 2009 08:01:20 -0700 (PDT) Subject: Format Code Repeat Counts? References: Message-ID: Thanks all! That was most helpful and informative. Best, Josiah From Samnsparky at gmail.com Thu Aug 13 11:30:55 2009 From: Samnsparky at gmail.com (Sparky) Date: Thu, 13 Aug 2009 08:30:55 -0700 (PDT) Subject: Tkinter Menu in Frame Message-ID: <37d94fb6-5afd-4a9e-a45b-49c08776cd82@r18g2000yqd.googlegroups.com> Hello! I am trying to figure out if it is possible to place a Tkinter menu within a frame. This would be instead of having the menu-bar at the top of the window. Thanks, Sam From davea at ieee.org Thu Aug 13 11:34:23 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 11:34:23 -0400 Subject: what is it, that I don't understand about python and lazy evaluation? In-Reply-To: References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> Message-ID: <4A84327F.6040006@ieee.org> Antoine Pitrou wrote: > Erik Bernoth googlemail.com> writes: > >> Isn't it strange, that this code runs (in a lazy language) for eternity? >> > > Python is a not a lazy language. > `and` and `or` are particular, they are language constructs (*), not operators, > that's why they can decide whether or not to evaluate their second term. It's a > feature, but this feature is not general to Python. > > (*) by this I mean they have similar status as, for example, `if` and `else` > > > > Agreed. In fact, I don't know of any aspect of Python which I'd call lazy, although the word appears in the docs in a few places. I've seen, but not used, languages which had lazy evaluations. Simplest example would be an infinite precision math package, where the actual precision is not actually used till something external to the program got visibility to the value. So the constant PI might really be a generator, which would generate enough precision for whatever the value was being used for. If you did a free-form print of PI, the console would never terminate (in principle), but in practice, it'd get slower and slower printing out the digits till the machine ran out of memory, or the user lost patience. Python, on the other hand has at least three short-circuit operations, in which parts of the expression are defined not to be evaluated at all, if other parts meet certain conditions. These are the 'and' and 'or' keywords mentioned above, the chained comparison construct, and the conditional expression, added recently. In each of these, the semantics of the language require that those parts not be evaluated. val = (42 < x < function()) val = 19 if i<12 else function() val = x or function() In each example, the function() may or may not be actually called, depending on the other values of the expression. DaveA From marduk at letterboxes.org Thu Aug 13 11:42:42 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Thu, 13 Aug 2009 11:42:42 -0400 Subject: loops for ffmpeg CLI in python In-Reply-To: References: Message-ID: <1250178162.16478.0.camel@brotherus.corp.redhat.com> On Wed, 2009-08-12 at 11:29 +0200, fakhar Gillani wrote: > > Hi, > > I am a begineer in Python. Actually I am encoding video files with > different bitrates using ffmpeg CLI. I wanted to ask you that how can > I make loops so that I can vary the bitrates in the CLI of ffmpeg?? > > I want to bulid a loop for the command below where i just want to vary > the -vb parameter i.e. 10M. > > ffmpeg.exe -i sample.avi -y -f h264 -vb 10M -r 25 > encoded_1000_0-05.h264 > > I have tried to make simple loops but it doest work:( > > Can anyone here help me out? It might help if you specify what you tried and why it didn't work (for you). -a From breamoreboy at yahoo.co.uk Thu Aug 13 11:45:31 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 13 Aug 2009 16:45:31 +0100 Subject: Python configuration question when python scripts are executed using Appweb as web server. In-Reply-To: References: Message-ID: Gabriel Genellina wrote: [snip] >> Here are couple of links that discusses setting PYTHONPATH environment >> variable. >> http://docs.python.org/using/windows.html > > Ouch, that document should be reworked and updated! I don't understand this comment, given that the PEP370 Implementation section 2nd paragraph quite specifically refers to the use of PYTHONPATH, I quote. "The user site directory is added before the system site directories but after Python's search paths and PYTHONPATH. This setup allows the user to install a different version of a package than the system administrator but it prevents the user from accidently overwriting a stdlib module. Stdlib modules can still be overwritten with PYTHONPATH." What am I missing? > >> http://www.daimi.au.dk/~chili/PBI/pythonpath.html > [snip] -- Kindest regards. Mark Lawrence. From e.kroske at gmail.com Thu Aug 13 11:50:47 2009 From: e.kroske at gmail.com (Evan Kroske) Date: Thu, 13 Aug 2009 11:50:47 -0400 Subject: Delegate attribute requests to object Message-ID: <1a78d23f0908130850v3f013b37rd1a7bce23041eedc@mail.gmail.com> I'm trying to use the decorator pattern in a program I'm developing. I want to create a decorator object that works like the object it's decorating except for a few functions. However, I'd rather not hard-code all the identical functionality from the decorated object into the decorator object. Is there a way I can intercept all the attribute and function requests for the decorator and delegate them to the decorated object? Here's some example code: class Decorator: > def __init__(): > self.decorated = Decorated() > > def newFunction(): > # Do something > pass > > def interceptRequests(request): > return self.decorated.request() > > class Decorated: > def __init__(): > self.variable = 10 > > def oldFunction(): > # Do something > pass I want to be able to do something like this: objectA = Decorator() > objectB = Decorated() > assert objectA.oldFunction() == objectB.oldFunction() # No error > Is it possible (without inheritance)? -- Evan Kroske http://welcome2obscurity.blogspot.com/ The code, comments, and challenges of a novice software developer desperate for attention. -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Aug 13 11:52:45 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 11:52:45 -0400 Subject: How to launch a function at regular time intervals ? In-Reply-To: References: Message-ID: <4A8436CD.9040308@ieee.org> Grant Edwards wrote: > On 2009-08-13, Dave Angel wrote: > > >> I'm assuming you want to call it every time_interval seconds, on >> average, with a little jitter allowed on each call, but keeping correct >> long term. In other words, if one call is a little late, you want the >> next one to still happen as close to on-time as possible. >> >> The general outline is something like (untested): >> >> times_called = 0 #number of times function has been called >> start_time = now >> while True: >> elapsed = now - start_time >> int_elapsed = int(elapsed/time_interval) >> for times_called in range(times_called, int_elapsed): >> call_the_function() >> sleep(time_interval/10) #this might give us 10% jitter, which is usually fine >> > > I don't understand the reasoning behind the above loop -- > specifically the sleeping of smaller intervals than needed. > > Why not something like this: > > interval = 5.0 # interval in seconds > next = time.time() > > while True: > now = time.time() > if now < next: > time.sleep(now-next) > print "call_the_function()" > next += interval > > That will be accurate over the long term with minimal jitter. > > > > Two reasons I didn't take an approach like that one. 1) I frequently need to do something else while waiting, so I tend to do multiple smaller sleeps. As long as each sleep is at least 100ms, the overhead cost is pretty small. 2) If (occasionally) the function takes longer than the specified interval time, my approach does catch-up calls so the average remains the same. My loop was only a rough outline, and if neither of these considerations applies, yours is much nicer. DaveA From gordon at panix.com Thu Aug 13 12:00:40 2009 From: gordon at panix.com (John Gordon) Date: Thu, 13 Aug 2009 16:00:40 +0000 (UTC) Subject: Interface to Exchange Calendar via web services Message-ID: I have a python app that needs to look up a person's Exchage Calendar entries to see if they are currently available. Does anyone have any code examples for communicating with EWS (Exchange Web Services)? I've found some code in Java and CSharp to do this, but none in python so far. Thanks! -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From rami.chowdhury at gmail.com Thu Aug 13 12:07:41 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 13 Aug 2009 09:07:41 -0700 Subject: Delegate attribute requests to object In-Reply-To: <1a78d23f0908130850v3f013b37rd1a7bce23041eedc@mail.gmail.com> References: <1a78d23f0908130850v3f013b37rd1a7bce23041eedc@mail.gmail.com> Message-ID: Perhaps I'm misunderstanding something, but I don't think that's really typical decorator behavior? Typically decorators, as I understand them, take an instance argument -- so you wouldn't be saying def __init__(self): self.decorated = Decorated() you'd be saying def __init__(self, decorated): self.decorated = decorated As for the attribute access, I believe you can override __getattr__ to do what you want: > class Decorator: > [snip] > def __getattr__(self, request): > return self.decorated.__getattr__(request) The same thing should work for methods, although you may want to pass arguments through as well. Is there a reason why, for this use, just making Decorator a subclass of Decorated (and only overriding the methods you need to be different) wouldn't work? On Thu, 13 Aug 2009 08:50:47 -0700, Evan Kroske wrote: > I'm trying to use the decorator pattern in a program I'm developing. I > want > to create a decorator object that works like the object it's decorating > except for a few functions. However, I'd rather not hard-code all the > identical functionality from the decorated object into the decorator > object. > Is there a way I can intercept all the attribute and function requests > for > the decorator and delegate them to the decorated object? Here's some > example > code: > > class Decorator: >> def __init__(): >> self.decorated = Decorated() >> >> def newFunction(): >> # Do something >> pass >> >> def interceptRequests(request): >> return self.decorated.request() >> >> class Decorated: >> def __init__(): >> self.variable = 10 >> >> def oldFunction(): >> # Do something >> pass > > > I want to be able to do something like this: > > objectA = Decorator() >> objectB = Decorated() >> assert objectA.oldFunction() == objectB.oldFunction() # No error >> > > Is it possible (without inheritance)? > > -- > Evan Kroske > http://welcome2obscurity.blogspot.com/ > The code, comments, and challenges of a novice > software developer desperate for attention. -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From ethan at stoneleaf.us Thu Aug 13 12:22:23 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 13 Aug 2009 09:22:23 -0700 Subject: what is it, that I don't understand about python and lazy evaluation? In-Reply-To: <4A84279C.2030504@stoneleaf.us> References: <46ae62fe0908130232x22241399pdf7a845d9d142962@mail.gmail.com> <4A84279C.2030504@stoneleaf.us> Message-ID: <4A843DBF.6050808@stoneleaf.us> Ethan Furman wrote: > Erik Bernoth wrote: > >> Hi List, >> >> look at the following code: >> >> def evens(): >> # iterator returning even numbers >> i = 0 >> while True: >> yield i >> i += 2 >> >> # now get all the even numbers up to 15 >> L = [n for n in evens() if n < 15] >> >> Isn't it strange, that this code runs (in a lazy language) for >> eternity? I would expect python to to spit out (in no time): >> >> L >> [0, 2, 4, 6, 8, 10, 12, 14] >> >> after 14 it is not nessesary to evaluate evens() any further. >> >> I really started to ask myself if python really is lazy, but >> everything else I wrote in lazy style still worked. Example: >> >> def test(txt, retval): >> .. print(txt) >> .. return retval >> .. >> >>> test(1, True) or test(2, True) >> 1 >> True >> >>> test(1, True) and test(2, True) >> 1 >> 2 >> True >> >> >> Can anybody explain what happens with evens()? >> >> best regards >> Erik Bernoth >> >> PS: The code comes from a list post from 2006. You find it here: >> http://mail.python.org/pipermail/python-list/2006-November/585783.html >> > > As MRAB pointed out, the issue is not with evens, it's with the list > comprehension. The list comprehension doesn't know when to stop, only > which numbers to include. > > ~Ethan~ > Actually, I am mistaken (gasp! shock! ;). A list comprehension will run until the iterator(s) it's based on end, and even() runs forever. ~Ethan~ From davigier at googlemail.com Thu Aug 13 12:25:58 2009 From: davigier at googlemail.com (David) Date: Thu, 13 Aug 2009 09:25:58 -0700 (PDT) Subject: How to launch a function at regular time intervals ? References: Message-ID: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> Thanks all for your answers. As suggested by Dave and Frank, I am indeed looking for the main program to continue running in the background (I have several functions I want to launch, each at a predefined time interval). I like Frank's solution, on the paper it seems it would do what I am looking for, but I cannot succeed in having it working. I guess I've been stuck with this problem for too long and can't succeed in using my brain accurately anymore... ;-) I defined the class as defined by Frank, and I then inserted the following code in a While True loop, without any other code (the idea is just to test Frank's solution before really using it in my program): func = MyFunction() func.start() func.stop() func.join() However I'm not getting the expected behavior. It's not taking into account the 30 sec wait, the function is called again and again without any time interval... Any idea ? Again, thanks a lot. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 13 12:33:55 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 13 Aug 2009 16:33:55 GMT Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <65053f02-0e64-4070-90c8-e04394be90ad@d32g2000yqh.googlegroups.com> Message-ID: <029430d5$0$20647$c3e8da3@news.astraweb.com> On Wed, 12 Aug 2009 20:23:27 -0700, rurpy wrote: >> That's no different from *any* major refactoring. The exact same >> problem exists for code as well as documentation. It's a solved problem >> for code, and it's a solved problem for documentation. > > Huh? I don't buy this at all. Code refactoring doesn't change the > semantics of the program at all -- it simplifies the code that > implements behavior without changing behavior. How does this apply to > revising documentation? My apologies, I mis-wrote. Of course refactoring is inappropriate in this context. What I meant was a major redesign where the API may change. Except of course that documentation changes don't need to be concerned with backwards compatibility, except possibly to avoid breaking old links. [...] >> Yes it would. Most patches are ignored, because the dev team are >> overworked, and if they don't see the need for a patch, they won't >> approve it. > > I'm confused. If they weren't overworked, then they would approve > patches they didn't see a need for? No. If they're overworked, they're less likely to spend time investigating patches which aren't immediately obvious that they're needed. And additionally, if the patch doesn't appear to be useful, it's unlikely to be approved. Why would it be? > Or are you saying because they are > overworked they fail to approve patches that should be approved? Invariably there will be good patches missed because they haven't been noticed. > I am > not sure how either supports the argument that the tracker is the best > method of improving the docs. These are not arguments in favour of the tracker, these are realistic issues that any project of non-trivial size have to deal with. Virtually every project (not just software projects either) have to deal with the fact that there will be more things to do than resources to do them with. [...] >> No, submitting a tracker issue is a necessary but not sufficient step. >> Without a tracker issue, you're very unlikely to have people agree to >> replace the existing docs with your docs, although a PEP would probably >> do it. (A PEP is significantly more effort than raising a tracker >> issue.) > > Has there ever been a PEP for a doc change? Are you making a serious > suggestion? I don't know if there ever has been, but as far as I know, there are two ways to get changes approved to Python: informal approval by somebody with check-in privileges, or formal approval on the basis of a PEP. If you can't get the first, then the second is an option, albeit unlikely. >>> As long as every "the docs >>> sux" complaint is met here with the standard responses that I've >>> mentioned, >> >> But they aren't met with such a so-called "standard response". > > I just looked through the first 70 or so messages in this thread and in > this case I have agree with you, most of the responses were not what I > called "standard responses". There was one guy, a Steven D'Aprano early > on that trotted out the, "it's free software, fix it if you don't like > it" line, And I stand by it. If you're not helping to solve the problem, then what exactly are you doing? Even if you can't provide a patch, provide a bug report. What specifically is wrong with the docs? Be specific. Give examples. Explain why it is wrong. State your assumptions, e.g. what audience do you represent? If you do these things, you're helping. If you're just complaining, then you're not. >> We know that there are problems. We've said repeatedly that corrections >> and patches are welcome. We've repeatedly told you how to communicate >> your answer to the question of what should be done. None of this is >> good enough for you. I don't know what else you expect. > > You have been told repeatedly why your insistence that the tracker must > be the only channel, is wrong. I don't understand why you can't > understand that. > > (Generally only those in authority, bosses, parents, police, and the > like, "tell" others what a situation is and have a right to demand that > the subject accept it without question. I think you could find a more > respectful and less authoritarian way of phrasing what you said above > since you are not in a position of authority over me.) "You're not my real dad!!!" In the words of Jesse "The Body" Venture, I'm just telling it like it is. The tracker is the only practical way of getting doc changes accepted, for those without check-in privileges or the ear of someone with them. Me telling you this is no more an expression of authority than me telling you that the USA has 50 states. Of course I could be wrong. My understanding of the facts might be wrong, or I may not be in full possession of all the relevant facts. If so, I welcome correction. So please tell me, what other practical ways are there for an unprivileged person to get the official Python docs modified? -- Steven From invalid at invalid Thu Aug 13 12:40:06 2009 From: invalid at invalid (Grant Edwards) Date: Thu, 13 Aug 2009 11:40:06 -0500 Subject: How to launch a function at regular time intervals ? References: Message-ID: On 2009-08-13, Dave Angel wrote: > Grant Edwards wrote: >> On 2009-08-13, Dave Angel wrote: >>> The general outline is something like (untested): >>> >>> times_called = 0 #number of times function has been called >>> start_time = now >>> while True: >>> elapsed = now - start_time >>> int_elapsed = int(elapsed/time_interval) >>> for times_called in range(times_called, int_elapsed): >>> call_the_function() >>> sleep(time_interval/10) #this might give us 10% jitter, which is usually fine >> >> I don't understand the reasoning behind the above loop -- >> specifically the sleeping of smaller intervals than needed. >> >> Why not something like this: >> >> interval = 5.0 # interval in seconds >> next = time.time() >> >> while True: >> now = time.time() >> if now < next: >> time.sleep(now-next) >> print "call_the_function()" >> next += interval >> >> That will be accurate over the long term with minimal jitter. >> > Two reasons I didn't take an approach like that one. > > 1) I frequently need to do something else while waiting, so I > tend to do multiple smaller sleeps. As long as each sleep > is at least 100ms, the overhead cost is pretty small. I guess I always use a separate thread for cases like that. > 2) If (occasionally) the function takes longer than the > specified interval time, my approach does catch-up calls so > the average remains the same. I'm still confused -- doesn't mine do that as well? -- Grant Edwards grante Yow! Are you the at self-frying president? visi.com From tim.arnold at sas.com Thu Aug 13 12:57:17 2009 From: tim.arnold at sas.com (Tim Arnold) Date: Thu, 13 Aug 2009 12:57:17 -0400 Subject: coding for multiple versions of python Message-ID: Hi, I've got a python based system that has to run on hp unix and red hat linux. The Python version on the HP is 2.4 and the version on the Linux box is 2.6. There's nothing I can do about that. I think that means I must have two different libraries since the pyc files are not cross-version compatible. No problem for the libs like PIL or lxml. But for the part of the system I actually code every day, I'd rather not do dual maintenance, having two copies of my code for each platform/version. I'm guessing I need to configure cvs to copy files to both locations whenever I commit. Does that sound right? Is there a better way I'm not thinking of? thanks, --Tim From aahz at pythoncraft.com Thu Aug 13 12:58:52 2009 From: aahz at pythoncraft.com (Aahz) Date: 13 Aug 2009 09:58:52 -0700 Subject: Database query execution times in Python? References: Message-ID: In article , pwnedd wrote: > >I've been writing some code using libraries based on the Python Database API >2.0 (MySQLdb & pg), and so far things are working really well. There is one >thing that I have not been able to figure out how to do, however: > >Retrieve the time is took a given query to execute. Look up EXPLAIN -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From aahz at pythoncraft.com Thu Aug 13 13:04:54 2009 From: aahz at pythoncraft.com (Aahz) Date: 13 Aug 2009 10:04:54 -0700 Subject: httplib incredibly slow :-( References: Message-ID: In article , Chris Withers wrote: >Aahz wrote: >> In article , >> Chris Withers wrote: >>> >>> Does anyone know of an alternative library for creating http requests >>> and getting their responses that's faster but hopefully has a similar >>> interface? >> >> PyCurl > >This seems to be a wrapper around libcurl. >Does it work on Windows? Yes. >If so, where can I find some decent examples? >(the ones listed on the pycurl website are not what I'd call decent :-S) Sorry, I mostly have been working on our Mac port, so I'm not sure what's needed to make this work on Windows. Did you try downloading the PyCurl binary? Maybe it statically links libcurl on Windows. What do you need to know for a decent example? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From rays at blue-cove.com Thu Aug 13 13:13:54 2009 From: rays at blue-cove.com (RJ) Date: Thu, 13 Aug 2009 10:13:54 -0700 Subject: Social problems of Python doc [was Re: Python docs disappointing] In-Reply-To: <029430d5$0$20647$c3e8da3@news.astraweb.com> References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <65053f02-0e64-4070-90c8-e04394be90ad@d32g2000yqh.googlegroups.com> <029430d5$0$20647$c3e8da3@news.astraweb.com> Message-ID: <6.2.3.4.2.20090813100638.04a00478@blue-cove.com> A basic question in this thread is: Who will host the doc-wiki/whatever and how will it be linked to? If not hosted at python.org it can still be linked to from their docs, if allowed, possibly with 3rd level domain and re-direct. I host a number of commercial servers but I don't expect Guido to bless them with said links. If hosted at python.org it will require resources from the existing admins. If elsewhere then trusted admins and organization. If not linked to from python.org then it may well expire from lack of interest, as other seemingly nice attempts did. Ray Schumacher From python at mrabarnett.plus.com Thu Aug 13 13:16:21 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 13 Aug 2009 18:16:21 +0100 Subject: How to launch a function at regular time intervals ? In-Reply-To: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> Message-ID: <4A844A65.7080906@mrabarnett.plus.com> David wrote: > Thanks all for your answers. As suggested by Dave and Frank, I am > indeed looking for the main program to continue running in the > background (I have several functions I want to launch, each at a > predefined time interval). I like Frank's solution, on the paper it > seems it would do what I am looking for, but I cannot succeed in > having it working. I guess I've been stuck with this problem for too > long and can't succeed in using my brain accurately anymore... ;-) > > I defined the class as defined by Frank, and I then inserted the > following code in a While True loop, without any other code (the idea > is just to test Frank's solution before really using it in my > program): > > func = MyFunction() > func.start() > > func.stop() > func.join() > > However I'm not getting the expected behavior. It's not taking into > account the 30 sec wait, the function is called again and again > without any time interval... Any idea ? > > Again, thanks a lot. > What exactly do you mean by "I then inserted the following code in a While True loop"? Do you mean you put all four lines in it? If yes, then you're repeatedly starting then stopping the function. From rami.chowdhury at gmail.com Thu Aug 13 13:18:05 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 13 Aug 2009 10:18:05 -0700 Subject: Delegate attribute requests to object In-Reply-To: <1a78d23f0908131013x25feee2fwe6b907045e87b6f5@mail.gmail.com> References: <1a78d23f0908130850v3f013b37rd1a7bce23041eedc@mail.gmail.com> <1a78d23f0908131013x25feee2fwe6b907045e87b6f5@mail.gmail.com> Message-ID: More information at http://www.python.org/doc/2.5.2/ref/attribute-access.html if you need it :-) On Thu, 13 Aug 2009 10:13:47 -0700, Evan Kroske wrote: > I don't want to inherit from the classes I'm decorating because they > have a > common superclass. I can make a generic decorator that I can use on all > its > sibling classes. I'll try your getattr method to see if it works. > > On Thu, Aug 13, 2009 at 12:07 PM, Rami Chowdhury > wrote: > >> Perhaps I'm misunderstanding something, but I don't think that's really >> typical decorator behavior? Typically decorators, as I understand them, >> take >> an instance argument -- so you wouldn't be saying >> >> def __init__(self): >> self.decorated = Decorated() >> >> you'd be saying >> >> def __init__(self, decorated): >> self.decorated = decorated >> >> As for the attribute access, I believe you can override __getattr__ to >> do >> what you want: >> >> class Decorator: >>> [snip] >>> def __getattr__(self, request): >>> return self.decorated.__getattr__(request) >>> >> >> The same thing should work for methods, although you may want to pass >> arguments through as well. >> >> Is there a reason why, for this use, just making Decorator a subclass of >> Decorated (and only overriding the methods you need to be different) >> wouldn't work? >> >> >> On Thu, 13 Aug 2009 08:50:47 -0700, Evan Kroske >> wrote: >> >> I'm trying to use the decorator pattern in a program I'm developing. I >>> want >>> to create a decorator object that works like the object it's decorating >>> except for a few functions. However, I'd rather not hard-code all the >>> identical functionality from the decorated object into the decorator >>> object. >>> Is there a way I can intercept all the attribute and function requests >>> for >>> the decorator and delegate them to the decorated object? Here's some >>> example >>> code: >>> >>> class Decorator: >>> >>>> def __init__(): >>>> self.decorated = Decorated() >>>> >>>> def newFunction(): >>>> # Do something >>>> pass >>>> >>>> def interceptRequests(request): >>>> return self.decorated.request() >>>> >>>> class Decorated: >>>> def __init__(): >>>> self.variable = 10 >>>> >>>> def oldFunction(): >>>> # Do something >>>> pass >>>> >>> >>> >>> I want to be able to do something like this: >>> >>> objectA = Decorator() >>> >>>> objectB = Decorated() >>>> assert objectA.oldFunction() == objectB.oldFunction() # No error >>>> >>>> >>> Is it possible (without inheritance)? >>> >>> -- >>> Evan Kroske >>> http://welcome2obscurity.blogspot.com/ >>> The code, comments, and challenges of a novice >>> software developer desperate for attention. >>> >> >> >> >> -- >> Rami Chowdhury >> "Never attribute to malice that which can be attributed to stupidity" -- >> Hanlon's Razor >> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) >> > > > -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From webcokies at yahoo.com Thu Aug 13 13:52:46 2009 From: webcokies at yahoo.com (Joni Lee) Date: Thu, 13 Aug 2009 10:52:46 -0700 (PDT) Subject: Help newbie with how to call a source command Message-ID: <901009.79843.qm@web36903.mail.mud.yahoo.com> Hi all, ? I'm landing here because I need some help that I couldn't get through it. Question 1. I want to call a source command from python script. It will source some?variables enviroment for further commands. I tried the following which did not work os.sys('source '+source_text) call(['source',source_text], shell=True) commands.getoutput('source '+source_text) ? Anyone have experiences with this? Because I'm very new to this world so a details reply is really appreciated!!! thank you very much ? Question 2. I call a shell command from python, this time it runs a script which runs some ruby scripts. And the error returns: "ruby: command not found" ? Thank you again -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Thu Aug 13 14:12:07 2009 From: aahz at pythoncraft.com (Aahz) Date: 13 Aug 2009 11:12:07 -0700 Subject: How to address a global variable in a function References: <82c2f2e7-ed3e-482b-9318-d5539a2a9da8@y10g2000prg.googlegroups.com> Message-ID: In article <82c2f2e7-ed3e-482b-9318-d5539a2a9da8 at y10g2000prg.googlegroups.com>, n179911 wrote: > >I have a global variable > >// line 8 >tx = 0 > >and then I have this function (start in line 12): >def handleTranslate(result): > print line > txStr, tyStr = result.group(1), result.group(2) > print txStr, tyStr > > tx += int(txStr) > ty += int(tyStr) > > return BTW, you probably want to learn why global names are a bad idea, I don't have time to explain that here (or point you at references). Going through some of the online tutorials should address this. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From rami.chowdhury at gmail.com Thu Aug 13 14:29:04 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 13 Aug 2009 11:29:04 -0700 Subject: Delegate attribute requests to object In-Reply-To: <1a78d23f0908131100p75520be4oe7572aae00bf2f13@mail.gmail.com> References: <1a78d23f0908130850v3f013b37rd1a7bce23041eedc@mail.gmail.com> <1a78d23f0908131013x25feee2fwe6b907045e87b6f5@mail.gmail.com> <1a78d23f0908131100p75520be4oe7572aae00bf2f13@mail.gmail.com> Message-ID: Oops, my apologies, it's the __getattribute__ method you want to call on self.decorated (because __getattr__ won't be there unless you define it specifically) So it should go: def __getattr__(self, request): return self.decorated.__getattribute__(request) On Thu, 13 Aug 2009 11:00:28 -0700, Evan Kroske wrote: > Unfortunately, __getattr__ didn't work. When I try to use your code > > class Decorator: >> [snip] >> def __getattr__(self, request): >> return self.decorated.__getattr__(request) >> > > I get this error: > > AttributeError: 'Decorated' object has no attribute '__getattr__' >> > > Is that a private method, or am I simply using it wrong? Thanks for the > help. > > On Thu, Aug 13, 2009 at 1:18 PM, Rami Chowdhury > wrote: > >> More information at >> http://www.python.org/doc/2.5.2/ref/attribute-access.html if you need it >> :-) >> >> >> On Thu, 13 Aug 2009 10:13:47 -0700, Evan Kroske >> wrote: >> >> I don't want to inherit from the classes I'm decorating because they >> have >>> a >>> common superclass. I can make a generic decorator that I can use on all >>> its >>> sibling classes. I'll try your getattr method to see if it works. >>> >>> On Thu, Aug 13, 2009 at 12:07 PM, Rami Chowdhury >>> wrote: >>> >>> Perhaps I'm misunderstanding something, but I don't think that's >>> really >>>> typical decorator behavior? Typically decorators, as I understand >>>> them, >>>> take >>>> an instance argument -- so you wouldn't be saying >>>> >>>> def __init__(self): >>>> self.decorated = Decorated() >>>> >>>> you'd be saying >>>> >>>> def __init__(self, decorated): >>>> self.decorated = decorated >>>> >>>> As for the attribute access, I believe you can override __getattr__ >>>> to do >>>> what you want: >>>> >>>> class Decorator: >>>> >>>>> [snip] >>>>> def __getattr__(self, request): >>>>> return self.decorated.__getattr__(request) >>>>> >>>>> >>>> The same thing should work for methods, although you may want to pass >>>> arguments through as well. >>>> >>>> Is there a reason why, for this use, just making Decorator a subclass >>>> of >>>> Decorated (and only overriding the methods you need to be different) >>>> wouldn't work? >>>> >>>> >>>> On Thu, 13 Aug 2009 08:50:47 -0700, Evan Kroske >>>> wrote: >>>> >>>> I'm trying to use the decorator pattern in a program I'm developing. >>>> I >>>> >>>>> want >>>>> to create a decorator object that works like the object it's >>>>> decorating >>>>> except for a few functions. However, I'd rather not hard-code all the >>>>> identical functionality from the decorated object into the decorator >>>>> object. >>>>> Is there a way I can intercept all the attribute and function >>>>> requests >>>>> for >>>>> the decorator and delegate them to the decorated object? Here's some >>>>> example >>>>> code: >>>>> >>>>> class Decorator: >>>>> >>>>> def __init__(): >>>>>> self.decorated = Decorated() >>>>>> >>>>>> def newFunction(): >>>>>> # Do something >>>>>> pass >>>>>> >>>>>> def interceptRequests(request): >>>>>> return self.decorated.request() >>>>>> >>>>>> class Decorated: >>>>>> def __init__(): >>>>>> self.variable = 10 >>>>>> >>>>>> def oldFunction(): >>>>>> # Do something >>>>>> pass >>>>>> >>>>>> >>>>> >>>>> I want to be able to do something like this: >>>>> >>>>> objectA = Decorator() >>>>> >>>>> objectB = Decorated() >>>>>> assert objectA.oldFunction() == objectB.oldFunction() # No error >>>>>> >>>>>> >>>>>> Is it possible (without inheritance)? >>>>> >>>>> -- >>>>> Evan Kroske >>>>> http://welcome2obscurity.blogspot.com/ >>>>> The code, comments, and challenges of a novice >>>>> software developer desperate for attention. >>>>> >>>>> >>>> >>>> >>>> -- >>>> Rami Chowdhury >>>> "Never attribute to malice that which can be attributed to stupidity" >>>> -- >>>> Hanlon's Razor >>>> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) >>>> >>>> >>> >>> >>> >> >> >> -- >> Rami Chowdhury >> "Never attribute to malice that which can be attributed to stupidity" -- >> Hanlon's Razor >> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) >> > > > -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From jura.grozni at gmail.com Thu Aug 13 14:56:49 2009 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Aug 2009 11:56:49 -0700 (PDT) Subject: i Don't get why it makes trouble Message-ID: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> >>> j [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] >>> len(j) 5 >>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s'""" % (j) Traceback (most recent call last): File "", line 1, in TypeError: not enough arguments for format string I want to format the string. the list has five elements and the string has five placeholder but it wont format the string From lkcl at lkcl.net Thu Aug 13 15:01:41 2009 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Thu, 13 Aug 2009 19:01:41 +0000 Subject: [ANN] pyjamas 0.6pre3 released Message-ID: much as we'd very much like to declare a 0.6 stable release, really really soon and move forward, the ChangeLog just keeps growing (133 and counting) with the bugfixes, testing and contributions since 0.5p1. pyjamas is a port of GWT to python, and includes a python-to-javascript compiler and a widget UI toolkit that is similar to pyqt4, pygtk2 etc. applications can either be run as javascript (in a web browser) or on the desktop (using pyjamas-desktop) as python. conceptually therefore, pyjamas is similar to adobe AIR - except that it's python, not ActionScript, and it's entirely free software. hurrah! key changes: * the python-to-javascript has been significantly reworked, and now includes a --strict option which adds "python strict" features at the expense of speed. to disable these, and obtain speed instead, use "-O" * pyjamas-desktop has been merged into the pyjamas distribution, which includes support for one stable browser engine (XULrunner, the same engine behind firefox); pywebkitgtk (the engine behind safari and the iphone) and MSHTML (IE's engine). pywebkitgtk is useable (but unfriendly - no DOM exception handling); MSHTML is even less friendly - COM gets in the way at present, and eats even python exceptions). there's a lot more that could be said, but you've probably noticed all the other prerelease notices so 'nuff said, other than: thank you to the people who've been helping and contributing with testing, patches and more. downloads and more information: http://pypi.python.org/pypi/Pyjamas http://sf.net/projects/pyjamas http://code.google.com/p/pyjamas http://pyjs.org From pfeldman at verizon.net Thu Aug 13 15:05:26 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Thu, 13 Aug 2009 12:05:26 -0700 (PDT) Subject: trouble with reload Message-ID: <24956946.post@talk.nabble.com> According to the Python documentation, 'reload' reloads a previously imported module (so that changes made via an external editor will be effective). But, when I try to use this command, I get the following error message: TypeError: reload() argument must be module Any suggestions will be appreciated. -- View this message in context: http://www.nabble.com/trouble-with-reload-tp24956946p24956946.html Sent from the Python - python-list mailing list archive at Nabble.com. From zuo at chopin.edu.pl Thu Aug 13 15:06:47 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 13 Aug 2009 21:06:47 +0200 Subject: i Don't get why it makes trouble In-Reply-To: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: 13-08-2009 azrael wrote: >>>> j > [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] >>>> len(j) > 5 >>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, >>>> d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as >>>> z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' >>>> AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s'""" % (j) > Traceback (most recent call last): > File "", line 1, in > TypeError: not enough arguments for format string > > > I want to format the string. the list has five elements and the string > has five placeholder but it wont format the string j must be a tuple -- so either define it as (u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna') or when using it, wrap it with tuple() constructor: h = """...........""" % tuple(j) -- Jan Kaliszewski (zuo) From rami.chowdhury at gmail.com Thu Aug 13 15:07:36 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 13 Aug 2009 12:07:36 -0700 Subject: trouble with reload In-Reply-To: <24956946.post@talk.nabble.com> References: <24956946.post@talk.nabble.com> Message-ID: Could you please clarify how you're calling it? E.g. reload('foo') or reload(foo) ? On Thu, 13 Aug 2009 12:05:26 -0700, Dr. Phillip M. Feldman wrote: > According to the Python documentation, 'reload' reloads a previously > imported > module (so that changes made via an external editor will be effective). > But, when I try to use this command, I get the following error message: > > TypeError: reload() argument must be module > > Any suggestions will be appreciated. -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From zuo at chopin.edu.pl Thu Aug 13 15:12:50 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 13 Aug 2009 21:12:50 +0200 Subject: i Don't get why it makes trouble In-Reply-To: References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: Me wrote: > 13-08-2009 azrael wrote: > >>>>> j >> [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] >>>>> len(j) >> 5 >>>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, >>>>> d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as >>>>> z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = >>>>> '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s'""" % >>>>> (j) >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: not enough arguments for format string >> >> >> I want to format the string. the list has five elements and the string >> has five placeholder but it wont format the string > > j must be a tuple -- so either define it as [snip] PS. If you use Python 2.6 or newer, better use .format() method (then you can use also a list): >>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, \ ... d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as \ ... z, drzava as d, valuta as v WHERE u.naziv = '{0}' AND o.naziv = \ ... '{1}' AND z.naziv = '{2}' AND d.naziv = '{3}' AND v.naziv = '{4}'\ ... """.format(*j) Cheers, *j -- Jan Kaliszewski (zuo) From davea at ieee.org Thu Aug 13 15:17:00 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 15:17:00 -0400 Subject: How to launch a function at regular time intervals ? In-Reply-To: References: Message-ID: <4A8466AC.6080509@ieee.org> Grant Edwards wrote: > On 2009-08-13, Dave Angel wrote: > >> Grant Edwards wrote: >> >>> >>> interval = 5.0 # interval in seconds >>> next = time.time() >>> >>> while True: >>> now = time.time() >>> if now < next: >>> time.sleep(now-next) >>> print "call_the_function()" >>> next += interval >>> >>> That will be accurate over the long term with minimal jitter. >>> >>> >> >> 2) If (occasionally) the function takes longer than the >> specified interval time, my approach does catch-up calls so >> the average remains the same. >> > > I'm still confused -- doesn't mine do that as well? > > Yep. I missed it again. Clearly it does the catchup the next time around the while loop. DaveA From dullrich at sprynet.com Thu Aug 13 15:20:13 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Thu, 13 Aug 2009 14:20:13 -0500 Subject: trouble with reload References: Message-ID: On Thu, 13 Aug 2009 12:05:26 -0700, Dr. Phillip M. Feldman wrote: > According to the Python documentation, 'reload' reloads a previously > imported module (so that changes made via an external editor will be > effective). But, when I try to use this command, I get the following > error message: > > TypeError: reload() argument must be module That would mean that you're trying to reload something other than a module. Of course you think you're reloading a module. The problem is that... oops, since you don't show the code that leads to this error it's hard to say what the problem is. > Any suggestions will be appreciated. From garrickp at gmail.com Thu Aug 13 15:21:13 2009 From: garrickp at gmail.com (Falcolas) Date: Thu, 13 Aug 2009 12:21:13 -0700 (PDT) Subject: How to launch a function at regular time intervals ? References: Message-ID: On Aug 12, 3:09?pm, David wrote: > Hi all, I'm trying to launch a function at regular time intervals but > cannot find the way to do it. Here is the code I wrote (time_interval > is a user defined variable in seconds): > [snip] > Has anyone run into a similar problem (and solved it) ? > > Thanks for your help I did - as part of a script where I needed to send load into a system at a steady rate. I ended up using threading to do the function calls, since they were not guaranteed to complete before the next interval. duration_start = time.time() interval_counter = 0 while time.time() - duration_start < duration: for thread_count in xrange(numthreads): threading.Thread(target=exec_thread, kwargs={#snip unimportant#}).start() interval_counter += 1 time.sleep((duration_start + (interval * interval_counter)) - time.time()) Executing this loop with a simple echo and time print showed that there was no creep over time, and the deviation between intervals was around 1/100th of a second. I'm fairly sure I'm creating some gnarly memory leaks and such by not joining spent threads, but it's been a non-issue in my usage. Adding a list to keep track of the threads and join on complete threads would be fairly trivial to implement. I think for simpler applications, using threading.Timer to kick off the function would work just as well. ~G From jura.grozni at gmail.com Thu Aug 13 15:26:07 2009 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Aug 2009 12:26:07 -0700 (PDT) Subject: i Don't get why it makes trouble References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: <189e10f1-771a-4631-a907-56d450b5e493@c2g2000yqi.googlegroups.com> On 13 kol, 21:12, "Jan Kaliszewski" wrote: > Me wrote: > > 13-08-2009 azrael wrote: > > >>>>> j > >> [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] > >>>>> len(j) > >> 5 > >>>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, ? > >>>>> d.id_drzava, v.id_valuta FROM ? ulica as u, opcina as o, zupanija as ? > >>>>> z, drzava as d, valuta as v ?WHERE ?u.naziv = '%s' AND o.naziv = ? > >>>>> '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s'""" % ? > >>>>> (j) > >> Traceback (most recent call last): > >> ? File "", line 1, in > >> TypeError: not enough arguments for format string > > >> I want to format the string. the list has five elements and the string > >> has five placeholder but it wont format the string > > > j must be a tuple -- so either define it as > > [snip] > > PS. If you use Python 2.6 or newer, better use .format() method > (then you can use also a list): > > >>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, \ > > ... d.id_drzava, v.id_valuta FROM ? ulica as u, opcina as o, zupanija as \ > ... z, drzava as d, valuta as v ?WHERE ?u.naziv = '{0}' AND o.naziv = \ > ... '{1}' AND z.naziv = '{2}' AND d.naziv = '{3}' AND v.naziv = '{4}'\ > ... """.format(*j) > > Cheers, > *j > > -- > Jan Kaliszewski (zuo) Thanks Worked fine for me. I was a freakin idiot. I forgot about using a tuple. damn lists :D Thanks for the debuginig of my thoughts and actions. thnx From davea at ieee.org Thu Aug 13 15:28:02 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 15:28:02 -0400 Subject: How to launch a function at regular time intervals ? In-Reply-To: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> Message-ID: <4A846942.3020708@ieee.org> David wrote: > Thanks all for your answers. As suggested by Dave and Frank, I am > indeed looking for the main program to continue running in the > background (I have several functions I want to launch, each at a > predefined time interval). I like Frank's solution, on the paper it > seems it would do what I am looking for, but I cannot succeed in > having it working. I guess I've been stuck with this problem for too > long and can't succeed in using my brain accurately anymore... ;-) > > I defined the class as defined by Frank, and I then inserted the > following code in a While True loop, without any other code (the idea > is just to test Frank's solution before really using it in my > program): > > func = MyFunction() > func.start() > > func.stop() > func.join() > > However I'm not getting the expected behavior. It's not taking into > account the 30 sec wait, the function is called again and again > without any time interval... Any idea ? > > Again, thanks a lot. > > > Why don't you include the code you're actually trying, instead of just trying to describe it. Frank's class didn't call any function, it just had a place to do it. So we really don't know what you're running, nor what about it is wrong. Perhaps a few well placed print statements? DaveA From ebonak at hotmail.com Thu Aug 13 15:28:44 2009 From: ebonak at hotmail.com (Esmail) Date: Thu, 13 Aug 2009 15:28:44 -0400 Subject: get output of du / ls command - currently ugly code ... Message-ID: Hi all, Essentially all I want to know the size of a directory, and the size of a zipped tarball so that I can compute/report the compression ratio. The code I have seems hideous, but it seems to work. Surely there is an easier,more elegant way to do this? dir_size = os.popen('du -sk somename') data = dir_size.readlines() dir_size = int(data[0].split()[0]) print 'dir size: ', dir_size tar_size = os.popen('ls -s somename.tar.gz') data = tar_size.readlines() tar_size = int(data[0].split()[0]) print 'tar size: ', tar_size Thanks Esmail From rebfj at yahoo.co.uk Thu Aug 13 15:48:18 2009 From: rebfj at yahoo.co.uk (rebfj at yahoo.co.uk) Date: Thu, 13 Aug 2009 12:48:18 -0700 (PDT) Subject: get output of du / ls command - currently ugly code ... References: Message-ID: <6d501dbf-bbed-4b38-afc1-f956c9ff3ab6@h21g2000yqa.googlegroups.com> On Aug 13, 8:28?pm, Esmail wrote: > Hi all, > > Essentially all I want to know the size of a directory, and the size > of a zipped tarball so that I can compute/report the compression ratio. > > The code I have seems hideous, but it seems to work. Surely there is an > easier,more elegant way to do this? > > ? ? ?dir_size = os.popen('du -sk somename') > ? ? ?data = dir_size.readlines() > ? ? ?dir_size = int(data[0].split()[0]) > ? ? ?print 'dir size: ', dir_size > > ? ? ?tar_size = os.popen('ls -s somename.tar.gz') > ? ? ?data = tar_size.readlines() > ? ? ?tar_size = int(data[0].split()[0]) > ? ? ?print 'tar size: ', tar_size > > Thanks > Esmail Try using os.path.getsize(somename.tar.gz) From davea at ieee.org Thu Aug 13 15:48:55 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 15:48:55 -0400 Subject: Help newbie with how to call a source command In-Reply-To: <901009.79843.qm@web36903.mail.mud.yahoo.com> References: <901009.79843.qm@web36903.mail.mud.yahoo.com> Message-ID: <4A846E27.9090502@ieee.org> Joni Lee wrote: > Hi all, > > I'm landing here because I need some help that I couldn't get through it. > Question 1. > I want to call a source command from python script. It will source some variables enviroment for further commands. I tried the following which did not work > os.sys('source '+source_text) > call(['source',source_text], shell=True) > commands.getoutput('source '+source_text) > > Anyone have experiences with this? Because I'm very new to this world so a details reply is really appreciated!!! thank you very much > > Question 2. > I call a shell command from python, this time it runs a script which runs some ruby scripts. And the error returns: "ruby: command not found" > > Thank you again > > > 1) You cannot do "source" from Python. It's a shell command whose very nature is to remember some environment variables for the duration of that particular shell. So once it returns to your python program, they're lost. However, if you just need those variables for invocations of the same shell, you have a couple of choices. You can parse the file yourself, and set up an environment dictionary, and pass that when you invoke subsequent shells. Or you can build a script on the fly, prepending whatever script you're planning to run with that source_text file. 2) In this question, and in general, you need to specify the Python version, the OS environment, the particular Python code you used to launch the shell, the contents of the script, and the results you saw. Use copy and paste, don't just paraphrase. And in a case like this one, somebody familiar with the environment (Ruby on Unix?) will probably have other questions: environment dictionary passed to the shell, did you get a Ruby startup prompt? Or whatever. DaveA From philip at semanchuk.com Thu Aug 13 16:09:04 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 13 Aug 2009 16:09:04 -0400 Subject: i Don't get why it makes trouble In-Reply-To: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: On Aug 13, 2009, at 2:56 PM, azrael wrote: >>>> j > [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] >>>> len(j) > 5 >>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, >>>> d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija >>>> as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv >>>> = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = >>>> '%s'""" % (j) > Traceback (most recent call last): > File "", line 1, in > TypeError: not enough arguments for format string Hi azrael, You already have an answer to your question so I won't address that. I want to point out that this is a dangerous way to build SQL statements. For instance, what happens if someone enters a city name of L'viv? Your SQL will break due to mismatched single quotes. This kind of code is vulnerable to SQL injection attacks: http://en.wikipedia.org/wiki/SQL_injection Parameterized SQL is safer. Googling for 'parameterized SQL Python' should find some examples for you. Good luck Philip From ebonak at hotmail.com Thu Aug 13 16:13:51 2009 From: ebonak at hotmail.com (Esmail) Date: Thu, 13 Aug 2009 16:13:51 -0400 Subject: get output of du / ls command - currently ugly code ... In-Reply-To: <6d501dbf-bbed-4b38-afc1-f956c9ff3ab6@h21g2000yqa.googlegroups.com> References: <6d501dbf-bbed-4b38-afc1-f956c9ff3ab6@h21g2000yqa.googlegroups.com> Message-ID: <4A8473FF.7050701@hotmail.com> rebfj at yahoo.co.uk wrote: > On Aug 13, 8:28 pm, Esmail wrote: >> Hi all, >> >> Essentially all I want to know the size of a directory, and the size >> of a zipped tarball so that I can compute/report the compression ratio. >> >> dir_size = os.popen('du -sk somename') >> data = dir_size.readlines() >> dir_size = int(data[0].split()[0]) >> print 'dir size: ', dir_size >> Hi, > Try using os.path.getsize(somename.tar.gz) Beautiful! .. that takes care of the tarball .. but it doesn't seem to work for reporting the total size of the directory. Any suggestions how to do that in a nicer way? I just looked through os.path.* and there doesn't seem to be a function to report what "du -sb" would. Thanks for your help, Esmail From marduk at letterboxes.org Thu Aug 13 16:16:29 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Thu, 13 Aug 2009 16:16:29 -0400 Subject: get output of du / ls command - currently ugly code ... In-Reply-To: References: Message-ID: <1250194589.19760.4.camel@brotherus.corp.redhat.com> On Thu, 2009-08-13 at 15:28 -0400, Esmail wrote: > Hi all, > > Essentially all I want to know the size of a directory, and the size > of a zipped tarball so that I can compute/report the compression ratio. > > The code I have seems hideous, but it seems to work. Surely there is an > easier,more elegant way to do this? > > dir_size = os.popen('du -sk somename') > data = dir_size.readlines() > dir_size = int(data[0].split()[0]) > print 'dir size: ', dir_size > > tar_size = os.popen('ls -s somename.tar.gz') > data = tar_size.readlines() > tar_size = int(data[0].split()[0]) > print 'tar size: ', tar_size > I don't know about "easier", but a more elegant way is to not use os.popen() and to use Python's functions os.path.getsize (or os.stat) and os.walk (or os.path.walk) to achieve this. In fact if you look at the docstring for os.walk there is an example that almost does what you're doing with du, but is cross-platform and not dependent on shelling a process and scraping its stdout. -a From benjamin.kaplan at case.edu Thu Aug 13 17:05:37 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 13 Aug 2009 17:05:37 -0400 Subject: i Don't get why it makes trouble In-Reply-To: References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: On Thu, Aug 13, 2009 at 4:09 PM, Philip Semanchuk wrote: > > On Aug 13, 2009, at 2:56 PM, azrael wrote: > > j >>>>> >>>> [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] >> >>> len(j) >>>>> >>>> 5 >> >>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, >>>>> d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija as z, >>>>> drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv = '%s' AND >>>>> z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = '%s'""" % (j) >>>>> >>>> Traceback (most recent call last): >> File "", line 1, in >> TypeError: not enough arguments for format string >> > > Hi azrael, > You already have an answer to your question so I won't address that. I want > to point out that this is a dangerous way to build SQL statements. > > For instance, what happens if someone enters a city name of L'viv? Your > SQL will break due to mismatched single quotes. This kind of code is > vulnerable to SQL injection attacks: > http://en.wikipedia.org/wiki/SQL_injection > No explanation of SQL injection is complete without a link to the relevant XKCD. http://xkcd.com/327/ > > Parameterized SQL is safer. Googling for 'parameterized SQL Python' should > find some examples for you. > > Good luck > Philip > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin at python.org Thu Aug 13 17:12:50 2009 From: benjamin at python.org (Benjamin Peterson) Date: Thu, 13 Aug 2009 16:12:50 -0500 Subject: [RELEASED] Python 3.1.1 Release Candidate Message-ID: <1afaf6160908131412i3b6f6636wc3fc166db0b9d5ce@mail.gmail.com> On behalf of the Python development team, I'm pleased to announce the first release candidate of Python 3.1.1. This bug fix release fixes many normal bugs and several critical ones including potential data corruption in the io library. The final version should be out within the next week. Python 3.1 focuses on the stabilization and optimization of the features and changes that Python 3.0 introduced. For example, the new I/O system has been rewritten in C for speed. File system APIs that use unicode strings now handle paths with undecodable bytes in them. Other features include an ordered dictionary implementation, a condensed syntax for nested with statements, and support for ttk Tile in Tkinter. For a more extensive list of changes in 3.1, see http://doc.python.org/3.1/whatsnew/3.1.html or Misc/NEWS in the Python distribution. To download Python 3.1.1 visit: http://www.python.org/download/releases/3.1/ The 3.1 documentation can be found at: http://docs.python.org/3.1 Bugs can always be reported to: http://bugs.python.org Enjoy! -- Benjamin Peterson Release Manager benjamin at python.org (on behalf of the entire python-dev team and 3.1.1's contributors) From petermoeller at gmail.com Thu Aug 13 17:26:54 2009 From: petermoeller at gmail.com (PeteDK) Date: Thu, 13 Aug 2009 14:26:54 -0700 (PDT) Subject: need help calculating point between two coordinates. Message-ID: <2d059a29-933e-4e2c-8730-f1f2688af26c@24g2000yqm.googlegroups.com> Hi there I'am working on a route comparison tool for carpools. The route comparison is based on 'steps' retrieved from google maps GDirection. These steps vary in length and i use the coordinates at the beginning of each "step". However, sometimes the distance of these steps is too long(ex. driving 30-40 km. on the freeway). Therefore i would like to calculate/find the coordinate located in between two given coordinates. Lets say one step starts at: 56.043185,9.922714 and ends at: 56.234287,9.864521 I would then like to calculate the point right in the middle of these coordinates. I use the haversine form to calculate the distance between coordinates, but im not sure whether or not this can be used for the same purpose. http://www.mpi.nl/world/persons/private ... versine.py I apologize if this thread has been posted the wrong place:) any help is greatly appreciated! kind regards. Pete From ebonak at hotmail.com Thu Aug 13 17:31:55 2009 From: ebonak at hotmail.com (Esmail) Date: Thu, 13 Aug 2009 17:31:55 -0400 Subject: Plotting Quadratic Functions, pygame In-Reply-To: References: Message-ID: Hello Senad, You might find this style guide useful too in your toolbox of Python skills & tricks. http://www.python.org/dev/peps/pep-0008/ This is a great and helpful group of people here, we are lucky to have access to groups like this. Best, Esmail From ebonak at hotmail.com Thu Aug 13 17:32:34 2009 From: ebonak at hotmail.com (Esmail) Date: Thu, 13 Aug 2009 17:32:34 -0400 Subject: get output of du / ls command - currently ugly code ... In-Reply-To: <1250194589.19760.4.camel@brotherus.corp.redhat.com> References: <1250194589.19760.4.camel@brotherus.corp.redhat.com> Message-ID: Albert Hopkins wrote: > > I don't know about "easier", but a more elegant way is to not use > os.popen() and to use Python's functions os.path.getsize (or os.stat) > and os.walk (or os.path.walk) to achieve this. > > In fact if you look at the docstring for os.walk there is an example > that almost does what you're doing with du, but is cross-platform and > not dependent on shelling a process and scraping its stdout. Thanks Albert, I'll take a look, Esmail From jura.grozni at gmail.com Thu Aug 13 18:00:19 2009 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Aug 2009 15:00:19 -0700 (PDT) Subject: i Don't get why it makes trouble References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: On 13 kol, 22:09, Philip Semanchuk wrote: > On Aug 13, 2009, at 2:56 PM, azrael wrote: > > >>>> j > > [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] > >>>> len(j) > > 5 > >>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, ? > >>>> d.id_drzava, v.id_valuta FROM ? ulica as u, opcina as o, zupanija ? > >>>> as z, drzava as d, valuta as v ?WHERE ?u.naziv = '%s' AND o.naziv ? > >>>> = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = ? > >>>> '%s'""" % (j) > > Traceback (most recent call last): > > ?File "", line 1, in > > TypeError: not enough arguments for format string > > Hi azrael, > You already have an answer to your question so I won't address that. I ? > want to point out that this is a dangerous way to build SQL statements. > > For instance, what happens if someone enters a city name of L'viv? ? > Your SQL will break due to mismatched single quotes. This kind of code ? > is vulnerable to SQL injection attacks:http://en.wikipedia.org/wiki/SQL_injection > > Parameterized SQL is safer. Googling for 'parameterized SQL Python' ? > should find some examples for you. > > Good luck > Philip I know Already. This is sopussed to be a small office application connecting on a LAN mysql server with no web connection. Thank you anyway From goldtech at worldpost.com Thu Aug 13 18:04:35 2009 From: goldtech at worldpost.com (goldtech) Date: Thu, 13 Aug 2009 15:04:35 -0700 (PDT) Subject: Idle text wrap Message-ID: <4e59f80c-e812-4273-9ebf-2c711ae35663@b25g2000prb.googlegroups.com> Hi, I'm using Idle interactive shell. Actually Idle-Spoon which has a few nice extensions and Python 2.6 on Linux. When I print str_value + "\n" Where str_value is for example a string of 120 chars. I notice that the lines seem to get hard wrapped at around 80. Is there a way I can config it to either wrap to the window, or for a higher amount before wrapping? Thanks. From philip at semanchuk.com Thu Aug 13 18:14:02 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Thu, 13 Aug 2009 18:14:02 -0400 Subject: i Don't get why it makes trouble In-Reply-To: References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: <59821D8E-7130-421E-84E4-72B55E339702@semanchuk.com> On Aug 13, 2009, at 6:00 PM, azrael wrote: > On 13 kol, 22:09, Philip Semanchuk wrote: >> On Aug 13, 2009, at 2:56 PM, azrael wrote: >> >>>>>> j >>> [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] >>>>>> len(j) >>> 5 >>>>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, >>>>>> d.id_drzava, v.id_valuta FROM ulica as u, opcina as o, zupanija >>>>>> as z, drzava as d, valuta as v WHERE u.naziv = '%s' AND o.naziv >>>>>> = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = >>>>>> '%s'""" % (j) >>> Traceback (most recent call last): >>> File "", line 1, in >>> TypeError: not enough arguments for format string >> >> Hi azrael, >> You already have an answer to your question so I won't address >> that. I >> want to point out that this is a dangerous way to build SQL >> statements. >> >> For instance, what happens if someone enters a city name of L'viv? >> Your SQL will break due to mismatched single quotes. This kind of >> code >> is vulnerable to SQL injection attacks:http://en.wikipedia.org/wiki/SQL_injection >> >> Parameterized SQL is safer. Googling for 'parameterized SQL Python' >> should find some examples for you. >> >> Good luck >> Philip > > I know Already. This is sopussed to be a small office application > connecting on a LAN mysql server with no web connection. Thank you > anyway You're welcome. I'm glad you are aware. You're ahead of a lot of developers out there. I encourage you to at least think about using parameterized SQL anyway because you never know when someone (maybe even you!) will copy & paste your code, or use your library without realizing that it was "internal use only". It's usually just as easy as building SQL strings anyway. And besides, what about L'viv? =) Good luck with whatever choice you make Philip From david.mcwright at usbfmi.com Thu Aug 13 18:17:56 2009 From: david.mcwright at usbfmi.com (dippim) Date: Thu, 13 Aug 2009 15:17:56 -0700 (PDT) Subject: implementing descriptors Message-ID: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> I am new to Python and I have a question about descriptors. If I have a class as written below, is there a way to use descriptors to be certain that the datetime in start is always before the one in end? class foo(object): def __init__(self,a = None,b = None) self.start = a self.end = b from datetime import datetime c = datetime(2009,8,13,6,15,0) d = datetime(2009,8,14,12,0,0) afoo = foo(c,d) For instance, if the following code were run, I would like to instance of foo to switch the start and end times. afoo.start = datetime(2010,8,13,6,15,0) I was thinking of using the __set__ descriptor to catch the assignment and reverse the values if necessary, but I can't figure out how to determine which values is being set. Thanks for the help! David From davigier at googlemail.com Thu Aug 13 18:52:52 2009 From: davigier at googlemail.com (David) Date: Thu, 13 Aug 2009 15:52:52 -0700 (PDT) Subject: How to launch a function at regular time intervals ? References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> Message-ID: <18ac9f9a-0cf2-409c-82b3-ea068f21dbf7@k19g2000yqn.googlegroups.com> On 13 ao?t, 21:28, Dave Angel wrote: > David wrote: > > Thanks all for your answers. As suggested by Dave and Frank, I am > > indeed looking for the main program to continue running in the > > background (I have several functions I want to launch, each at a > > predefined time interval). I like Frank's solution, on the paper it > > seems it would do what I am looking for, but I cannot succeed in > > having it working. I guess I've been stuck with this problem for too > > long and can't succeed in using my brain accurately anymore... ;-) > > > I defined the class as defined by Frank, and I then inserted the > > following code in a While True loop, without any other code (the idea > > is just to test Frank's solution before really using it in my > > program): > > > ? ? func = MyFunction() > > ? ? func.start() > > > ? ? func.stop() > > ? ? func.join() > > > However I'm not getting the expected behavior. It's not taking into > > account the 30 sec wait, the function is called again and again > > without any time interval... Any idea ? > > > Again, thanks a lot. > > Why don't you include the code you're actually trying, instead of just > trying to describe it. ?Frank's class didn't call any function, it just > had a place to do it. ?So we really don't know what you're running, nor > what about it is wrong. > > Perhaps a few well placed print statements? > > DaveA Yes, I guess it would be more simple. Here is really what I am trying to do. I simplified the functions, but the purpose is to write some text in a local file every x seconds (here, I'm just writing the timestamp, i.e. a string representing the date & time, every 10 seconds) and to transfer this file to a distant server via FTP every y seconds (20 seconds in the example below). My code is a little bit more complicated because each time I transfer the file, I delete the local file which is then recreated when data is written, but for simplicity I left this out in the code below. So, here is the code I've been using to test Frank's code. I've been struggling with using or not a While True loop or not, and everything I try seems to run into issues. import threading from datetime import datetime import ftplib class CFtpConnection: """FTP Connection parameters""" def __init__(self, host, port, timeout, user, passwd): self.host = "" self.port = 21 self.timeout = 60 self.user = "" self.passwd = "" class CStoreData(threading.Thread): """Write timestamp in a file every 10 seconds in separate thread""" def __init__(self, timestamp): threading.Thread.__init__(self) self.event = threading.Event() self.timestamp = timestamp def run(self): while not self.event.is_set(): file_handler = open("Test.txt", 'a') file_handler.write(self.timestamp.strftime("%y%m%d%H%M%S \n")) file_handler.close() self.event.wait(10) def stop(self): self.event.set() class CTransferData(threading.Thread): """Transfer timestamp file every 20 seconds in separate thread""" def __init__(self, ftp_connection): threading.Thread.__init__(self) self.event = threading.Event() self.ftp_connection = ftp_connection def run(self): while not self.event.is_set(): file_handler = open("Test.txt", 'r') Ftp_handler = ftplib.FTP('') Ftp_handler.connect(self.ftp_connection.host, self.ftp_connection.port, self.ftp_connection.timeout) Ftp_handler.login(self.ftp_connection.user, self.ftp_connection.passwd) Ftp_handler.storbinary("STOR Test.txt", file_handler) file_handler.close() Ftp_handler.close() self.event.wait(20) def stop(self): self.event.set() ftp_connection = CFtpConnection("", 21, 60, "", "") ftp_connection.host = '127.0.0.1' ftp_connection.user = "admin" ftp_connection.passwd = "admin" while(1): timestamp = datetime.now() func_store_data = CStoreData(timestamp) func_store_data.start() func_transfer_data = CTransferData(ftp_connection) func_transfer_data.start() func_store_data.stop() func_store_data.join() func_transfer_data.stop() func_transfer_data.join() From breamoreboy at yahoo.co.uk Thu Aug 13 19:19:29 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 14 Aug 2009 00:19:29 +0100 Subject: implementing descriptors In-Reply-To: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: dippim wrote: > I am new to Python and I have a question about descriptors. If I have > a class as written below, is there a way to use descriptors to be > certain that the datetime in start is always before the one in end? > > class foo(object): > def __init__(self,a = None,b = None) > self.start = a > self.end = b > > from datetime import datetime > c = datetime(2009,8,13,6,15,0) > d = datetime(2009,8,14,12,0,0) > afoo = foo(c,d) > > For instance, if the following code were run, I would like to instance > of foo to switch the start and end times. > > afoo.start = datetime(2010,8,13,6,15,0) > > I was thinking of using the __set__ descriptor to catch the assignment > and reverse the values if necessary, but I can't figure out how to > determine which values is being set. > > Thanks for the help! > > David Take a look at the example given here. http://users.rcn.com/python/download/Descriptor.htm -- Kindest regards. Mark Lawrence. From mdekauwe at gmail.com Thu Aug 13 19:38:07 2009 From: mdekauwe at gmail.com (Martin) Date: Thu, 13 Aug 2009 16:38:07 -0700 (PDT) Subject: PIL and Python References: Message-ID: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> On Aug 13, 1:55?pm, "catalinf... at gmail.com" wrote: > Hello ! > I want use python to change the "note" from .jpeg files . > What is the functions on PIL how make this ? > Thank you ! What do u mean by the note? From emile at fenx.com Thu Aug 13 19:57:21 2009 From: emile at fenx.com (Emile van Sebille) Date: Thu, 13 Aug 2009 16:57:21 -0700 Subject: implementing descriptors In-Reply-To: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: On 8/13/2009 3:17 PM dippim said... > I am new to Python and I have a question about descriptors. If I have > a class as written below, is there a way to use descriptors to be > certain that the datetime in start is always before the one in end? > > class foo(object): > def __init__(self,a = None,b = None) > self.start = a > self.end = b > > from datetime import datetime > c = datetime(2009,8,13,6,15,0) > d = datetime(2009,8,14,12,0,0) > afoo = foo(c,d) > > For instance, if the following code were run, I would like to instance > of foo to switch the start and end times. > > afoo.start = datetime(2010,8,13,6,15,0) > > I was thinking of using the __set__ descriptor to catch the assignment > and reverse the values if necessary, why not... class foo(object): def __init__(self,a = None,b = None) self.start = min(a,b) self.end = max(a,b) Emile From davea at ieee.org Thu Aug 13 20:06:56 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 13 Aug 2009 20:06:56 -0400 Subject: need help calculating point between two coordinates. In-Reply-To: <2d059a29-933e-4e2c-8730-f1f2688af26c@24g2000yqm.googlegroups.com> References: <2d059a29-933e-4e2c-8730-f1f2688af26c@24g2000yqm.googlegroups.com> Message-ID: <4A84AAA0.6060105@ieee.org> PeteDK wrote: > Hi there > > I'am working on a route comparison tool for carpools. > > The route comparison is based on 'steps' retrieved from google maps > GDirection. These steps vary in length and i use the coordinates at > the beginning of each "step". However, sometimes the distance of these > steps is too long(ex. driving 30-40 km. on the freeway). Therefore i > would like to calculate/find the coordinate located in between two > given coordinates. > Lets say one step starts at: > 56.043185,9.922714 > and ends at: > 56.234287,9.864521 > > I would then like to calculate the point right in the middle of these > coordinates. > > I use the haversine form to calculate the distance between > coordinates, but im not sure whether or not this can be used for the > same purpose. > http://www.mpi.nl/world/persons/private ... versine.py > > I apologize if this thread has been posted the wrong place:) > > any help is greatly appreciated! > > kind regards. > > Pete > > For the distances you're talking about, those coordinates are very close to linear. So to find the midpoint, just average the coordinates. You might be off by half a km, but roads bend more than that. DaveA From goldtech at worldpost.com Thu Aug 13 20:36:59 2009 From: goldtech at worldpost.com (goldtech) Date: Thu, 13 Aug 2009 17:36:59 -0700 (PDT) Subject: Python "and" behavior Message-ID: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> Could you explain or link me to an explanation of this? Been using Python for a while but not sure I understand what's happening below. Thanks. >>> ss=1 and "fffff" >>> ss 'fffff' >>> ss=0 and "fffff" >>> ss 0 >>> From gherron at islandtraining.com Thu Aug 13 20:50:42 2009 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 13 Aug 2009 17:50:42 -0700 Subject: Python "and" behavior In-Reply-To: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> Message-ID: <4A84B4E2.9080300@islandtraining.com> goldtech wrote: > Could you explain or link me to an explanation of this? Been using > Python for a while but not sure I understand what's happening below. > Thanks. > > > >>>> ss=1 and "fffff" >>>> ss >>>> > 'fffff' > >>>> ss=0 and "fffff" >>>> ss >>>> > 0 > Python's Boolean operators don't turn arbitrary values into True and False values. If you use it in any conditional, you'll get the same result as if it did, but it is occasionally it's nice to get the actual values used in the "and" instead of having the value distilled down to a True/False. From the Python manual: These are the Boolean operations, ordered by ascending priority: Operation Result Notes |x or y| if x is false, then y, else x (1) |x and y| if x is false, then x, else y (1) |not x| if x is false, then |True|, else |False| (2) Notes: *(1)* These only evaluate their second argument if needed for their outcome. *(2)* "not" has a lower priority than non-Boolean operators, so |not a == b| is interpreted as |not (a == b)|, and |a == not b| is a syntax error. ------------------------------------------------------------------------ -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Thu Aug 13 20:52:40 2009 From: mensanator at aol.com (Mensanator) Date: Thu, 13 Aug 2009 17:52:40 -0700 (PDT) Subject: Python "and" behavior References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> Message-ID: <44940d04-6378-4a32-b470-d4709aab1ada@b14g2000yqd.googlegroups.com> On Aug 13, 7:36?pm, goldtech wrote: > Could you explain or link me to an explanation of this? Been using > Python for a while but not sure I understand what's happening below. > Thanks. > > > > > > >>> ss=1 and "fffff" > >>> ss > 'fffff' > >>> ss=0 and "fffff" > >>> ss > 0 Does this help? >>> ss = True and 'fffff' >>> ss 'fffff' >>> ss = False and 'eeeee' >>> ss False From apt.shansen at gmail.com Thu Aug 13 21:02:38 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Thu, 13 Aug 2009 18:02:38 -0700 Subject: Python "and" behavior In-Reply-To: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> Message-ID: <7a9c25c20908131802v2295b18ev12af2ac830c24669@mail.gmail.com> > > Could you explain or link me to an explanation of this? Been using > Python for a while but not sure I understand what's happening below. > Thanks. > > >>> ss=1 and "fffff" > >>> ss > 'fffff' > >>> ss=0 and "fffff" > >>> ss > 0 > >>> The "and" and "or" operators in Python are actually not true boolean operators: they operate on the more fundamental interpretation of Truth that Python uses (and that 'if' for example uses) that goes back before Python got actual boolean True/False values. "x and y" evaluates first x; if it is false, its value is returned. Otherwise, the value of y is returned. "x or y" evaluates first x; if it is true, its value is returned. Otherwise, the value of y is returned. Python's idea of "true" verses "false" isn't the same as True and False. It's been described as "something" verses "nothing", as in Python the following are considered false: False, None, numeric 0 (in all types of numbers), empty strings, empty containers (lists, tuples, dictionaries, sets). Everything else is True. Instances of any class are True by default, but they can have a __nonzero__ operation on them to override that. So, every value has an innate 'truthfulness' about it: the 'if' statement bases its decision on that truthfulness. In the context of truthfulness, the string "hello" is just as true as the singleton True. So, if you do "x and y", if 'x' is a false value... then 'x' is returned-- as 'x' is just as false as the singleton False. Both are different ways of saying 'false' in logical operations. Lots of people don't like this. Lots of people do. Some people want it to be pure-true boolean algebra, have them return True/False always-- some people have even argued for "if" only branching on True/False values. The fact of the matter is, this is all just a fundamental part of Python that pre-dates it ever having true boolean values, and is never gonna go away. There's some useful properties to it, like: value = opt or "default" In this case, if opt was set to a something, it'll end up in value. Otherwise, "default" will. Of course that's only useful where a opt would never have a blank string or 0 or such in it naturally. The poor-man's ternary operator was commonly used before Python got a proper one: value = x and "Yes" or "No" The construct had some limits(namely, the value in the "Yes" part of the expression must be truthy), but is still useful in a lot of situations. If "x" would evaluate true, then value would be set to "Yes". Otherwise, it'd be set to "No". HTH, --Stephen -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Thu Aug 13 21:09:09 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 02:09:09 +0100 Subject: Python "and" behavior In-Reply-To: <4A84B4E2.9080300@islandtraining.com> References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> <4A84B4E2.9080300@islandtraining.com> Message-ID: <4A84B935.8080809@mrabarnett.plus.com> Gary Herron wrote: > goldtech wrote: >> Could you explain or link me to an explanation of this? Been using >> Python for a while but not sure I understand what's happening below. >> Thanks. >> >> >> >>>>> ss=1 and "fffff" >>>>> ss >>>>> >> 'fffff' >> >>>>> ss=0 and "fffff" >>>>> ss >>>>> >> 0 >> > > Python's Boolean operators don't turn arbitrary values into True and > False values. If you use it in any conditional, you'll get the same > result as if it did, but it is occasionally it's nice to get the actual > values used in the "and" instead of having the value distilled down to a > True/False. > > > >From the Python manual: > > These are the Boolean operations, ordered by ascending priority: > > Operation Result Notes > |x or y| if x is false, then y, else x (1) > |x and y| if x is false, then x, else y (1) > |not x| if x is false, then |True|, else |False| (2) > The Pythonic table would be: Operation Result |x or y| x if x else y |x and y| y if x else x |not x| False if x else False :-) From arphaksad at gmail.com Thu Aug 13 21:21:39 2009 From: arphaksad at gmail.com (naaman) Date: Thu, 13 Aug 2009 18:21:39 -0700 (PDT) Subject: fileinput References: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> Message-ID: <31f257a9-8949-47d7-a0ae-0b4ab7822eb6@q23g2000yqn.googlegroups.com> On Aug 13, 7:50?am, Dave Angel wrote: > naaman wrote: > > On Aug 12, 1:35 pm, Dave Angel wrote: > > >> naaman wrote: > > >>> I'm writing my first Python script and > >>> I want to use fileinput to open a file in r+ mode. > >>> Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > >>> ANy ideas? > > >>> Need to find and overwrite a line in a file several times. > >>> I can do it using open and seek() etc. but was wondering if I can use > >>> fileinput. > > >>> thanks; > > >> I haven't used it, but check out the 'inplace' keyword parameter. > > >> DaveA > > > I've only Python for a week so I'm not sure what inplace does > > You should read the docs for it > ? ? (http://www.python.org/doc/2.6.2/library/fileinput.html?), > but it's not very clear to me either ?So I dug up an example on the web: > ? ? ?(ref: ?http://effbot.org/librarybook/fileinput.htm) > > import fileinput, sys > > for line in fileinput.input(inplace=1): > ? ? # /convert Windows/DOS text files to Unix files/ > ? ? if line[-2:] == "\r\n": > ? ? ? ? line = line[:-2] + "\n" > ? ? sys.stdout.write(line) > > The inplace argument tells it to create a new file with the same name as > the original (doing all the necessary nonsense with using a scratch > file, and renaming/deleting) for each file processed. ?Stdout is pointed > to that new version of the file. ?Notice that you have to explicitly > write everything you want to wind up in the file -- if a given line is > to remain unchanged, you just write "line" directly. > > If you're new to Python, I do not recommend trying to do open/seek to > update a text file in place, especially if you're in DOS. ?There are > lots of traps. ?the inplace method of fileinput avoids these by > implicitly creating temp files and handling the details for you, which > probably works great if you're dealing with text, in order. > > DaveA Thanks Dave. I'll check that out From xahlee at gmail.com Thu Aug 13 21:36:04 2009 From: xahlee at gmail.com (Xah Lee) Date: Thu, 13 Aug 2009 18:36:04 -0700 (PDT) Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode Message-ID: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> ? A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode http://xahlee.org/UnixResource_dir/writ/emacs_whitespace-mode_problems.html plane text version follows: -------------------------------------------------- A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode Xah Lee, 2009-08-13 Just wanted to express some frustration with whitespace-mode. Emacs 23, just released, has this whitespace-mode feature. It renders spaces, tabs, newlines characters with a visible glyph. This feature, is in Microsoft Word since about 1992. This feature is important in practical ways. For example, when you work with ?tab separated line? files (CSV) that's a common format for importing/exporting address books or spreadsheets. It's also important in whitespace-significant langs such as Python. Or, in text processing when placement of space and tabs matters in the output. All i wanted, is to make Space and Tab and Newline chars visible. However, the emacs whitespace-mode does much more than that. It is designed for tech geeking control freaks to tune every aspect of white space in his source code. The mode is filled with bells and whistles. It distinguishes tabs mixed with spaces, EOLs mixed with spaces, EOLs at beginning of file, EOLs at end of file, run on spaces at end of line, lines that has nothing to do with white spaces but is simply longer than 80 chars, etc. Each of these is rendered with different foreground, background, colors, so that they cannot possibly escape the notices of control freaks. By default, most of these are on, so that, when you turn on the mode, most reasonable clean source code become this colorful rainbow unreadable fuck. I tried to tune it, with my 10 years of emacs of fucking 16 hours of using per day, and 3 years of elisp coding experience. But, after a hour, it's confusion hell sans avail. O, that Alex idiot with his emacswiki, refused to lead emacswiki into any readable state. All he can think about is my social skills. (See: Problems of Emacswiki.) What the fuck motherfuck. Hi tech geekers, coding freaks, social science ignoramus fucks, basic economics illiterate FSF fucks, freedom abusing selfish ideologists fucks, Richard Stallman propagandist fuck, we-try-to-be-easy-to-use linuxer idioting fucks, FUCK U. Xah ? http://xahlee.org/ ? From timinganalyzer at gmail.com Thu Aug 13 21:43:27 2009 From: timinganalyzer at gmail.com (timinganalyzer) Date: Thu, 13 Aug 2009 18:43:27 -0700 (PDT) Subject: new version TimingAnalyzer Message-ID: <55314c4f-24e0-4c2c-8016-3d004b622d21@j9g2000vbp.googlegroups.com> Hi All, 1.Added a new User Delay and Constraint Editor panel. You can add, delete, or update User Delays or Constraints. 2 .These User Delays and User Constraints are saved at the top of the .tim file. 3.Changing a User Delay or User Constraint updates every one of the same type in the diagram. 4.Files created with previous versions are converted to this new format when saved. 5.Added Python Interpreter, Jython 2.5. Now you can write scripts in Python. 6.Execute Python scripts using the same script dialog for the beanshell scripts or from Jython command line window. 7.Included start_app.py script in the install directory that will start the TimingAnalyzer from a Jython command line window. 8.Updated spice_pwl.bsh. This beanshell script generates spice piece wise linear test vectors for DigitalBus. 9.Included dff.py. This Python script shows how to generate a timing diagram for a D Flip Flop. Anyone interested in helping convert the Java scripts (in the scripts dir) to Python should let me know. Dan Fabrizio www.timing-diagrams.com From jura.grozni at gmail.com Thu Aug 13 21:51:10 2009 From: jura.grozni at gmail.com (azrael) Date: Thu, 13 Aug 2009 18:51:10 -0700 (PDT) Subject: i Don't get why it makes trouble References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: On 14 kol, 00:14, Philip Semanchuk wrote: > On Aug 13, 2009, at 6:00 PM, azrael wrote: > > > > > > > On 13 kol, 22:09, Philip Semanchuk wrote: > >> On Aug 13, 2009, at 2:56 PM, azrael wrote: > > >>>>>> j > >>> [u'Tata', u'Oriovac', u'PrimorskoGoranska', u'hrvatska', u'Kuna'] > >>>>>> len(j) > >>> 5 > >>>>>> h = """SELECT distinct u.id_ulica, o.id_opcina, z.id_zupanija, > >>>>>> d.id_drzava, v.id_valuta FROM ? ulica as u, opcina as o, zupanija > >>>>>> as z, drzava as d, valuta as v ?WHERE ?u.naziv = '%s' AND o.naziv > >>>>>> = '%s' AND z.naziv = '%s' AND d.naziv = '%s' AND v.naziv = > >>>>>> '%s'""" % (j) > >>> Traceback (most recent call last): > >>> ?File "", line 1, in > >>> TypeError: not enough arguments for format string > > >> Hi azrael, > >> You already have an answer to your question so I won't address ? > >> that. I > >> want to point out that this is a dangerous way to build SQL ? > >> statements. > > >> For instance, what happens if someone enters a city name of L'viv? > >> Your SQL will break due to mismatched single quotes. This kind of ? > >> code > >> is vulnerable to SQL injection attacks:http://en.wikipedia.org/wiki/SQL_injection > > >> Parameterized SQL is safer. Googling for 'parameterized SQL Python' > >> should find some examples for you. > > >> Good luck > >> Philip > > > I know Already. This is sopussed to be a small office application > > connecting on a LAN mysql server with no web connection. Thank you > > anyway > > You're welcome. I'm glad you are aware. You're ahead of a lot of ? > developers out there. > > I encourage you to at least think about using parameterized SQL anyway ? > because you never know when someone (maybe even you!) will copy & ? > paste your code, or use your library without realizing that it was ? > "internal use only". It's usually just as easy as building SQL strings ? > anyway. > > And besides, what about L'viv? =) > > Good luck with whatever choice you make > Philip Currently I am working on just a prototype to show what is possible to be done to get me some fundings for my future work. after that I will get over to an SQL Alchemy. It's ORM will take over this business for me. A lot of people a not aware of SQL injection. My friend from college asked me and a couple of other guys for Pen testing of an website. His SQL injection mistake made him an epic fail. Thanks From clp2 at rebertia.com Thu Aug 13 22:20:18 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 13 Aug 2009 22:20:18 -0400 Subject: csv.DictWriter.write_header() In-Reply-To: References: Message-ID: <50697b2c0908131920r14862573j6bdbfc7a486d5b26@mail.gmail.com> On Wed, Aug 12, 2009 at 4:45 PM, Alan G Isaac wrote: > Given a csv.DictWriter instance `dw` > I think it would be nice to be able to > say dw.write_header() > instead of > dw.writer.writerow(dw.fieldnames) > > Good idea? Maybe. You could file a bug: http://bugs.python.org/ Cheers, Chris -- http://blog.rebertia.com From akonsu at gmail.com Thu Aug 13 22:32:03 2009 From: akonsu at gmail.com (akonsu) Date: Thu, 13 Aug 2009 19:32:03 -0700 (PDT) Subject: something like perl's Mail::GPG ? Message-ID: <4365602b-e174-4419-a1f7-44dde1b66b0c@w41g2000yqb.googlegroups.com> hello, i am looking for a module with functionality similar to that of the Perl's Mail::GPG package. I need to verify multipart emails that are PGP-signed. thanks for any advice konstantin From arphaksad at gmail.com Thu Aug 13 22:33:32 2009 From: arphaksad at gmail.com (naaman) Date: Thu, 13 Aug 2009 19:33:32 -0700 (PDT) Subject: fileinput References: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> Message-ID: <5d11458b-322d-4851-98a8-13c4cee4f5aa@o13g2000vbl.googlegroups.com> On Aug 13, 7:50?am, Dave Angel wrote: > naaman wrote: > > On Aug 12, 1:35 pm, Dave Angel wrote: > > >> naaman wrote: > > >>> I'm writing my first Python script and > >>> I want to use fileinput to open a file in r+ mode. > >>> Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > >>> ANy ideas? > > >>> Need to find and overwrite a line in a file several times. > >>> I can do it using open and seek() etc. but was wondering if I can use > >>> fileinput. > > >>> thanks; > > >> I haven't used it, but check out the 'inplace' keyword parameter. > > >> DaveA > > > I've only Python for a week so I'm not sure what inplace does > > You should read the docs for it > ? ? (http://www.python.org/doc/2.6.2/library/fileinput.html?), > but it's not very clear to me either ?So I dug up an example on the web: > ? ? ?(ref: ?http://effbot.org/librarybook/fileinput.htm) > > import fileinput, sys > > for line in fileinput.input(inplace=1): > ? ? # /convert Windows/DOS text files to Unix files/ > ? ? if line[-2:] == "\r\n": > ? ? ? ? line = line[:-2] + "\n" > ? ? sys.stdout.write(line) > > The inplace argument tells it to create a new file with the same name as > the original (doing all the necessary nonsense with using a scratch > file, and renaming/deleting) for each file processed. ?Stdout is pointed > to that new version of the file. ?Notice that you have to explicitly > write everything you want to wind up in the file -- if a given line is > to remain unchanged, you just write "line" directly. > > If you're new to Python, I do not recommend trying to do open/seek to > update a text file in place, especially if you're in DOS. ?There are > lots of traps. ?the inplace method of fileinput avoids these by > implicitly creating temp files and handling the details for you, which > probably works great if you're dealing with text, in order. > > DaveA I wonder if inline creates an empty file and then the text from the processed file gets written to it. If that's what is going on then it's perfect solution. It will eliminate all the tell() and seek() and overwriting a shorter line with a longer one. I'll try it over the weekend. thanks From gagsl-py2 at yahoo.com.ar Thu Aug 13 23:15:14 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Aug 2009 00:15:14 -0300 Subject: Delegate attribute requests to object References: <1a78d23f0908130850v3f013b37rd1a7bce23041eedc@mail.gmail.com> <1a78d23f0908131013x25feee2fwe6b907045e87b6f5@mail.gmail.com> <1a78d23f0908131100p75520be4oe7572aae00bf2f13@mail.gmail.com> Message-ID: En Thu, 13 Aug 2009 12:50:47 -0300, Evan Kroske escribi?: > I'm trying to use the decorator pattern in a program I'm developing. I > want > to create a decorator object that works like the object it's decorating > except for a few functions. However, I'd rather not hard-code all the > identical functionality from the decorated object into the decorator > object. > Is there a way I can intercept all the attribute and function requests > for > the decorator and delegate them to the decorated object? You may search the list archives for references to "proxy" and "delegation". The term "decorator" has a very specific meaning in Python (as a syntax construct), don't use it in the search. > Is it possible (without inheritance)? Yes, using delegation. See below. En Thu, 13 Aug 2009 15:29:04 -0300, Rami Chowdhury escribi?: > Oops, my apologies, it's the __getattribute__ method you want to call on > self.decorated (because __getattr__ won't be there unless you define it > specifically) > So it should go: > > def __getattr__(self, request): > return self.decorated.__getattribute__(request) __getattribute__ doesn't exist on old-style classes either. Also, note that very rarely one has to *call* __special__ methods; the code should read: def __getattr__(self, request): return getattr(self.decorated, request) but that works *only* for old-style classes, as discussed here [1]. [3] is another approach for new-style classes (maybe not production-ready yet). And this recipe [2] shows how to make the decorated object keep calling methods on the decorator itself. [1] http://code.activestate.com/recipes/252151/ [2] http://code.activestate.com/recipes/519639/ [3] http://code.activestate.com/recipes/496741/ -- Gabriel Genellina From nirvana117 at gmail.com Thu Aug 13 23:16:18 2009 From: nirvana117 at gmail.com (dou dou) Date: Fri, 14 Aug 2009 11:16:18 +0800 Subject: problem with interface of operator.itemgetter Message-ID: <19b355330908132016y49f2679u631c3123fcfc920a@mail.gmail.com> I have a function to do some thing like LEFT JOIN in SQL, the function use the itemgetter to get the "ON" and "SELECT" parameters of the two table(list of list), the problem is that itemgetter may return a value or a tuple of values, because of the inconsistent return type of itemgetter, I have to do 2^3 IF check, the function like this: def left_join(table1, on_index1, table2, on_index2, getter1, getter2): """do thing like: SELECT on1(table1), g1(table1), g2(table2) FROM table1 LEFT JOIN table2 ON on1(table1) == on2(table2) """ on1 = itemgetter(*on_index1) on2 = itemgetter(*on_index2) g1 = itemgetter(*getter1) g2 = itemgetter(*getter2) d2 = {} d2 = dict((on2(r2), r2) for r2 in table2) #if itemgetter always return tuple, below could simple as one line #return [ list(on1(r1) + g1(r1) + g2(d2.get(on1(r1)))) for r1 in table1 ] len_on = len(on_index1) len_g1 = len(getter1) len_g2 = len(getter2) if len_on == 1: if len_g1 == 1 and len_g2 == 1: return [ [on1(r1), g1(r1), g2(d2.get(on1(r1)))] for r1 in table1 ] elif len_g1 == 1 and len_g2 > 1: return [ list((on1(r1),g1(r1))+g2(d2.get(on1(r1)))) for r1 in table1 ] elif len_g1 > 1 and len_g2 == 1: return [ list((on1(r1),)+g1(r1)+(g2(d2.get(on1(r1))),)) for r1 in table1 ] else: #len_g1 > 1 and len_g2 > 1: return [ list((on1(r1),)+g1(r1)+g2(d2.get(on1(r1)))) for r1 in table1 ] else: # len_on > 1 if len_g1 == 1 and len_g2 == 1: return [ list(on1(r1))+[g1(r1),g2(d2.get(on1(r1)))] for r1 in table1 ] elif len_g1 == 1 and len_g2 > 1: return [ list(on1(r1)+(g1(r1),)+g2(d2.get(on1(r1)))) for r1 in table1 ] elif len_g1 > 1 and len_g2 == 1: return [ list(on1(r1)+g1(r1)+(g2(d2.get(on1(r1))),)) for r1 in table1 ] else: #len_g1 > 1 and len_g2 > 1: return [ list(on1(r1)+g1(r1)+g2(d2.get(on1(r1)))) for r1 in table1 ] so is there a way to force itemgetter to return tuple even when itemgetter(only_have_one_argument)? or some other function to do this? Thanks. -------------- next part -------------- An HTML attachment was scrubbed... URL: From arphaksad at gmail.com Thu Aug 13 23:25:02 2009 From: arphaksad at gmail.com (naaman) Date: Thu, 13 Aug 2009 20:25:02 -0700 (PDT) Subject: fileinput References: Message-ID: <88cecdd5-4a7f-40ee-ad2d-1b481d5db03d@g1g2000vbr.googlegroups.com> On Aug 13, 1:20?am, "Gabriel Genellina" wrote: > En Wed, 12 Aug 2009 01:27:47 -0300, naaman escribi?: > > > I'm writing my first Python script and > > I want to use fileinput to open a file in r+ mode. > > Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > > ANy ideas? > > Don't use fileinput, it can't handle r+, only sequencial access. > Even if you could use it, the documentation says [1]: > fileinput.input([files[, inplace[, backup[, mode[, openhook]]]]]) > > "r+" corresponds to the `inplace` parameter (behaving like inplace=True) ? > instead of `mode`. You could write fileinput.input(sys.argv[1:], ? > mode="r+") instead - but again from the docs: "mode... must be one of 'r', ? > 'rU', 'U' and 'rb'" > > > Need to find and overwrite a line in a file several times. > > I can do it using open and seek() etc. but was wondering if I can use > > fileinput. > > open+seek is the way to do that (assuming you don't alter the line length) > > [1]http://docs.python.org/library/fileinput.html#fileinput.input > > -- > Gabriel Genellina unfortunately, I am overwriting shorter with longer From arphaksad at gmail.com Thu Aug 13 23:41:41 2009 From: arphaksad at gmail.com (naaman) Date: Thu, 13 Aug 2009 20:41:41 -0700 (PDT) Subject: fileinput References: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> Message-ID: On Aug 13, 7:50?am, Dave Angel wrote: > naaman wrote: > > On Aug 12, 1:35 pm, Dave Angel wrote: > > >> naaman wrote: > > >>> I'm writing my first Python script and > >>> I want to use fileinput to open a file in r+ mode. > >>> Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > >>> ANy ideas? > > >>> Need to find and overwrite a line in a file several times. > >>> I can do it using open and seek() etc. but was wondering if I can use > >>> fileinput. > > >>> thanks; > > >> I haven't used it, but check out the 'inplace' keyword parameter. > > >> DaveA > > > I've only Python for a week so I'm not sure what inplace does > > You should read the docs for it > ? ? (http://www.python.org/doc/2.6.2/library/fileinput.html?), > but it's not very clear to me either ?So I dug up an example on the web: > ? ? ?(ref: ?http://effbot.org/librarybook/fileinput.htm) > > import fileinput, sys > > for line in fileinput.input(inplace=1): > ? ? # /convert Windows/DOS text files to Unix files/ > ? ? if line[-2:] == "\r\n": > ? ? ? ? line = line[:-2] + "\n" > ? ? sys.stdout.write(line) > > The inplace argument tells it to create a new file with the same name as > the original (doing all the necessary nonsense with using a scratch > file, and renaming/deleting) for each file processed. ?Stdout is pointed > to that new version of the file. ?Notice that you have to explicitly > write everything you want to wind up in the file -- if a given line is > to remain unchanged, you just write "line" directly. > > If you're new to Python, I do not recommend trying to do open/seek to > update a text file in place, especially if you're in DOS. ?There are > lots of traps. ?the inplace method of fileinput avoids these by > implicitly creating temp files and handling the details for you, which > probably works great if you're dealing with text, in order. > > DaveA here's the solution import fileinput, sys for line in fileinput.input(sys.argv[1],inplace=1): if (line[:-1]==r'drew'): line=line.replace(line,"fancy dog") sys.stdout.write(line) I want to replace drew in my input file with fancy dog. Tested with this input file angel heaven flying monkees lazy dogs drew blue sky veritas and got this angel heaven flying monkees lazy dogs fancy dog blue sky veritas So drew was replaced with fancy dog. Thanks to your inputs I got this solved. :-)) From Scott.Daniels at Acm.Org Fri Aug 14 00:09:45 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 13 Aug 2009 21:09:45 -0700 Subject: Programming by Contract In-Reply-To: References: <4A7A15CD.9090306@stoneleaf.us> <4A81C6B8.7010605@stoneleaf.us> Message-ID: Charles Yeomans wrote: > > On Aug 11, 2009, at 3:30 PM, Ethan Furman wrote: > >> Ethan Furman wrote: >>> Greetings! >>> I have seen posts about the assert statement and PbC (or maybe it was >>> DbC), and I just took a very brief look at pycontract >>> (http://www.wayforward.net/pycontract/) and now I have at least one >>> question: Is this basically another way of thinking about unit >>> testing, or is the idea of PbC more along the lines of *always* >>> checking the input/output of functions to ensure they are correct? >>> (*Contstant vigilance!* as Prof Moody would say ;) >>> I know asserts can be turned off, so they obviously won't work for >>> the latter case, and having seen the sample of pycontract it seems it >>> only does its thing during debugging. >>> So is Design (Programming) by Contract a fancy way of saying >>> "Document your inputs/outputs!" or is there more to it? >>> ~Ethan~ >> >> Hmmm... >> >> Well, from the (apparently) complete lack of interest, I shall take >> away the (better?) documentation ideas and unit testing ideas, and not >> worry about the rest. :) >> >> > > > > > Design by contract is complementary to unit testing (I notice that the > author of PEP 316 appears confused about this). DbC is, roughly > speaking, about explicit allocation of responsibility. Consider this > contrived example. > > def foo(s): > require(s is not None) > //code > ensure(hasattr(returnValue, '__iter__')) yo might want two flags, REQUIRE_OFF, and ENSURE_ON that control testing, and change the code above to: require(REQUIRE_OFF or s is not None) //code ensure(ENSURE_OFF or hasattr(returnValue, '__iter__')) Python has no good way to turn off argument calculation by manipulating function definition (at least that I know of). --Scott David Daniels Scott.Daniels at Acm.Org From akonsu at gmail.com Fri Aug 14 00:22:45 2009 From: akonsu at gmail.com (akonsu) Date: Thu, 13 Aug 2009 21:22:45 -0700 (PDT) Subject: coding for multiple versions of python References: Message-ID: <57f07ff6-282c-4ac1-b03a-b26321a02f70@g31g2000yqc.googlegroups.com> On Aug 13, 12:57?pm, "Tim Arnold" wrote: > Hi, > I've got a python based system that has to run on hp unix and red hat linux. > The Python version on the HP is 2.4 and the version on the Linux box is 2.6. > There's nothing I can do about that. > > I think that means I must have two different libraries since the pyc files > are not cross-version compatible. No problem for the libs like PIL or lxml. > But for the part of the system I actually code every day, I'd rather not do > dual maintenance, having two copies of my code for each platform/version. > > I'm guessing I need to configure cvs to copy files to both locations > whenever I commit. Does that sound right? Is there a better way I'm not > thinking of? > > thanks, > --Tim hello, why would you need to maintain pyc files at all? is having just source files enough? or am i missing something? konstantin From clp2 at rebertia.com Fri Aug 14 00:29:58 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 14 Aug 2009 00:29:58 -0400 Subject: coding for multiple versions of python In-Reply-To: References: Message-ID: <50697b2c0908132129p24b1f5e2y586d8d30648e0cd8@mail.gmail.com> On Thu, Aug 13, 2009 at 12:57 PM, Tim Arnold wrote: > Hi, > I've got a python based system that has to run on hp unix and red hat linux. > The Python version on the HP is 2.4 and the version on the Linux box is 2.6. > There's nothing I can do about that. > > I think that means I must have two different libraries since the pyc files > are not cross-version compatible. Why would the .pyc-s matter? They're just an optimization, which fall back to the .py files. It only matters if the .py sourcecode files are compatible with both versions. > But for the part of the system I actually code every day, I'd rather not do > dual maintenance, having two copies of my code for each platform/version. > > I'm guessing I need to configure cvs to copy files to both locations > whenever I commit. Does that sound right? Is there a better way I'm not > thinking of? Put your code's directory in the PYTHONPATH / sys.path of both Python versions. You will still have to write code that works in both versions though. Essentially, don't use any new syntax that's not present in the older version, and you'll have to work around any new/changed functions you use. Cheers, Chris -- http://blog.rebertia.com From tjreedy at udel.edu Fri Aug 14 00:45:23 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Aug 2009 13:45:23 +0900 Subject: i Don't get why it makes trouble In-Reply-To: <189e10f1-771a-4631-a907-56d450b5e493@c2g2000yqi.googlegroups.com> References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> <189e10f1-771a-4631-a907-56d450b5e493@c2g2000yqi.googlegroups.com> Message-ID: azrael wrote: > Thanks Worked fine for me. I was a freakin idiot. I forgot about using > a tuple. damn lists :D The special casing of tuples versus other sequence objects with % formatting, and the forgetting and mistake making of multiple people is one of the reasons for the new .format system. Any sequence can either be passed and printed as a single object or *unrolled as multiple objects. tjr From tjreedy at udel.edu Fri Aug 14 00:49:19 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 14 Aug 2009 13:49:19 +0900 Subject: trouble with reload In-Reply-To: <24956946.post@talk.nabble.com> References: <24956946.post@talk.nabble.com> Message-ID: Dr. Phillip M. Feldman wrote: > According to the Python documentation, 'reload' reloads a previously imported > module (so that changes made via an external editor will be effective). > But, when I try to use this command, I get the following error message: > > TypeError: reload() argument must be module > > Any suggestions will be appreciated. Besides the other answers, do not use reload. It is removed in Py3 because it cannot be made to work as people reasonably expect. tjr From nobody at nowhere.com Fri Aug 14 00:52:24 2009 From: nobody at nowhere.com (Nobody) Date: Fri, 14 Aug 2009 05:52:24 +0100 Subject: PIL and Python References: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> Message-ID: On Thu, 13 Aug 2009 16:38:07 -0700, Martin wrote: >> I want use python to change the "note" from .jpeg files . >> What is the functions on PIL how make this ? > > What do u mean by the note? I think he means the EXIF data. From apt.shansen at gmail.com Fri Aug 14 00:59:19 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Thu, 13 Aug 2009 21:59:19 -0700 Subject: i Don't get why it makes trouble In-Reply-To: References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: <7a9c25c20908132159t113e339x2bd27b333c8f5f19@mail.gmail.com> > > Currently I am working on just a prototype to show what is possible to > be done to get me some fundings for my future work. after that I will > get over to an SQL Alchemy. It's ORM will take over this business for > me. > > A lot of people a not aware of SQL injection. My friend from college > asked me and a couple of other guys for Pen testing of an website. His > SQL injection mistake made him an epic fail. > You don't really need to go the full ORM route to do this safely -- constructing SQL from user input is not only wrong from a security point of view, but it's actually just harder to do it that way then use the mechanisms provided in PEP-249 compliant DB-API modules. Life's easier if you use parameterized queries, really :) You're probably connecting to your database via a DB-API compatible library, I assume? Most are. If so, it's simply a matter of: cur = con.cursor() cur.execute("SELECT name FROM blah WHERE id = ? AND zone = ?", (my_id, my_zone)) All DB-API compliant modules support this, though some mark the parameters differently. That's qmark, some alternates are numeric (:1, :2, etc), some named (:id, :zone), some format (%s, %d, etc), some pyformat, (%(id)d, %(zone)s). The module should provide a 'paramstyle' stating what is supported. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From Scott.Daniels at Acm.Org Fri Aug 14 01:17:57 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 13 Aug 2009 22:17:57 -0700 Subject: Format Code Repeat Counts? In-Reply-To: References: Message-ID: MRAB wrote: > The shortest I can come up with is: > "[" + "][".join(letters) + "]" Maybe a golf shot: "][".join(letters).join("[]") --Scott David Daniels Scott.Daniels at Acm.Org From Scott.Daniels at Acm.Org Fri Aug 14 01:36:12 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Thu, 13 Aug 2009 22:36:12 -0700 Subject: i Don't get why it makes trouble In-Reply-To: References: <5ddbbf79-a448-4cb0-96e8-427ab8160a78@q23g2000yqn.googlegroups.com> Message-ID: azrael wrote: > ... A lot of people a not aware of SQL injection. My friend from college > asked me and a couple of other guys for Pen testing of an website. His > SQL injection mistake made him an epic fail. And some people are unaware of the unofficial official Python citation for SQL injection explanations: http://xkcd.com/327/ --Scott David Daniels Scott.Daniels at Acm.Org From pfeldman at verizon.net Fri Aug 14 01:36:37 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Thu, 13 Aug 2009 22:36:37 -0700 (PDT) Subject: trouble with reload In-Reply-To: References: <24956946.post@talk.nabble.com> Message-ID: <24965811.post@talk.nabble.com> Actually, I've tried both of these, and I get (different) errors in both cases: In [1]: from mymath import * In [2]: reload(mymath) NameError: name 'mymath' is not defined In [3]: reload('mymath') TypeError: reload() argument must be module Rami Chowdhury wrote: > > Could you please clarify how you're calling it? E.g. > reload('foo') > or > reload(foo) > > ? > > On Thu, 13 Aug 2009 12:05:26 -0700, Dr. Phillip M. Feldman > wrote: > >> According to the Python documentation, 'reload' reloads a previously >> imported >> module (so that changes made via an external editor will be effective). >> But, when I try to use this command, I get the following error message: >> >> TypeError: reload() argument must be module >> >> Any suggestions will be appreciated. > > > > -- > Rami Chowdhury > "Never attribute to malice that which can be attributed to stupidity" -- > Hanlon's Razor > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/trouble-with-reload-tp24956946p24965811.html Sent from the Python - python-list mailing list archive at Nabble.com. From martin at v.loewis.de Fri Aug 14 01:41:39 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 14 Aug 2009 07:41:39 +0200 Subject: coding for multiple versions of python In-Reply-To: References: Message-ID: <4A84F913.9090901@v.loewis.de> > I'm guessing I need to configure cvs to copy files to both locations > whenever I commit. Does that sound right? Is there a better way I'm not > thinking of? If the set of files doesn't change too often, you can use symlinks. That's how Debian currently installs Python packages for multiple versions on a single system. Specifically, put the source code into /net/source/python/foo/*.py. Then, on each system, put symlinks to all .py files into lib/site-packages/foo. Then Python will place the .pyc files next to the symlinks, not next to the actual .py files. HTH, Martin From narkewoody at gmail.com Fri Aug 14 02:22:49 2009 From: narkewoody at gmail.com (Steven Woody) Date: Fri, 14 Aug 2009 14:22:49 +0800 Subject: OptionParser How to: prog [options] [arguments] Message-ID: Hi, I am using OptionParser, but I've not managed figure out a way to support what I wanted command line format "prog [options] [arguments]". E.g., "svn ls -r123 http://hello.world". Can I do this using OptionParser? Thanks. -- Life is the only flaw in an otherwise perfect nonexistence -- Schopenhauer narke public key at http://subkeys.pgp.net:11371 (narkewoody at gmail.com) -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Fri Aug 14 02:31:19 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 13 Aug 2009 23:31:19 -0700 (PDT) Subject: trouble with reload References: <24956946.post@talk.nabble.com> Message-ID: On Aug 13, 10:36?pm, "Dr. Phillip M. Feldman" wrote: > Actually, I've tried both of these, and I get (different) errors in both > cases: > > In [1]: from mymath import * > > In [2]: reload(mymath) > NameError: name 'mymath' is not defined > > In [3]: reload('mymath') > TypeError: reload() argument must be module Two problems here. 1. You have to call reload on an actual module object. When you write "from mymath import *" you are not actually binding the mytmath module to the mymath symbol. So, if you were to then write "print mymath" Python would raise a NameError exception. OTOH, if you were to write "import mymath", then the symbol mymath would bound to the mymath module. If you then write "print mymath", Python would output , the module object. Only then can you pass it to reload. 2. If you use "from mymath import *", even if you were to reload the mymath module (say, by importing it directly and calling reload on that), you will find that the functions you had originally imported will not be updated. They will still refer to the old functions. Why? Because when you reload a module, it only affects that's module's namespace. When you import a function from a module, you are now referencing the function from your own namespace. Even if the function in the module is replaced, the reference to that function in your own namespace hasn't been replaced. So, what do you do? My advice is to dispense with importing functions altogether; only import modules. It's more typing and a bit less efficient, but it makes everything more straightforward and consistent. Carl Banks From python at rcn.com Fri Aug 14 02:34:16 2009 From: python at rcn.com (Raymond Hettinger) Date: Thu, 13 Aug 2009 23:34:16 -0700 (PDT) Subject: implementing descriptors References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: [David] > I am new to Python and I have a question about descriptors. ?If I have > a class as written below, is there a way to use descriptors to be > certain that the datetime in start is always before the one in end? > > class foo(object): > ? ?def __init__(self,a = None,b = None) > ? ? ? self.start = a > ? ? ? self.end = b > > from datetime import datetime > c = datetime(2009,8,13,6,15,0) > d = datetime(2009,8,14,12,0,0) > afoo = foo(c,d) > > For instance, if the following code were run, I would like to instance > of foo to switch the start and end times. > > afoo.start = datetime(2010,8,13,6,15,0) > > I was thinking of using the __set__ descriptor to catch the assignment > and reverse the values if necessary, but I can't figure out how to > determine which values is being set. You're on the right track, but it is easier to use property() than to write your own custom descriptor with __get__ and __set__. class foo(object): def __init__(self,a = None,b = None): self._start = a self._end = b def get_start(self): return self._start def set_start(self, value): if self._end is None or value < self._end: self._start = value else: self._end = value start = property(get_start, set_start) def get_end(self): return self._end def set_end(self, value): if self._start is None or value > self._start: self._end = value else: self._start = value end = property(get_end, set_end) Raymond From frank at chagford.com Fri Aug 14 03:04:37 2009 From: frank at chagford.com (Frank Millman) Date: Fri, 14 Aug 2009 09:04:37 +0200 Subject: How to launch a function at regular time intervals ? References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> <18ac9f9a-0cf2-409c-82b3-ea068f21dbf7@k19g2000yqn.googlegroups.com> Message-ID: On Aug 14, 12:52 am, David wrote: > > Yes, I guess it would be more simple. Here is really what I am trying > to do. I simplified the functions, but the purpose is to write some > text in a local file every x seconds (here, I'm just writing the > timestamp, i.e. a string representing the date & time, every 10 > seconds) and to transfer this file to a distant server via FTP every y > seconds (20 seconds in the example below). My code is a little bit > more complicated because each time I transfer the file, I delete the > local file which is then recreated when data is written, but for > simplicity I left this out in the code below. So, here is the code > I've been using to test Frank's code. I've been struggling with using > or not a While True loop or not, and everything I try seems to run > into issues. > > import threading > from datetime import datetime > import ftplib > > class CFtpConnection: > """FTP Connection parameters""" > def __init__(self, host, port, timeout, user, passwd): > self.host = "" > self.port = 21 > self.timeout = 60 > self.user = "" > self.passwd = "" > > class CStoreData(threading.Thread): > """Write timestamp in a file every 10 seconds in separate > thread""" > > def __init__(self, timestamp): > threading.Thread.__init__(self) > self.event = threading.Event() > self.timestamp = timestamp > > def run(self): > while not self.event.is_set(): > file_handler = open("Test.txt", 'a') > file_handler.write(self.timestamp.strftime("%y%m%d%H%M%S > \n")) > file_handler.close() > self.event.wait(10) > > def stop(self): > self.event.set() > > class CTransferData(threading.Thread): > """Transfer timestamp file every 20 seconds in separate thread""" > > def __init__(self, ftp_connection): > threading.Thread.__init__(self) > self.event = threading.Event() > self.ftp_connection = ftp_connection > > def run(self): > while not self.event.is_set(): > file_handler = open("Test.txt", 'r') > Ftp_handler = ftplib.FTP('') > Ftp_handler.connect(self.ftp_connection.host, > self.ftp_connection.port, self.ftp_connection.timeout) > Ftp_handler.login(self.ftp_connection.user, > self.ftp_connection.passwd) > Ftp_handler.storbinary("STOR Test.txt", file_handler) > file_handler.close() > Ftp_handler.close() > self.event.wait(20) > > def stop(self): > self.event.set() > > ftp_connection = CFtpConnection("", 21, 60, "", "") > ftp_connection.host = '127.0.0.1' > ftp_connection.user = "admin" > ftp_connection.passwd = "admin" > > while(1): > timestamp = datetime.now() > func_store_data = CStoreData(timestamp) > func_store_data.start() > > func_transfer_data = CTransferData(ftp_connection) > func_transfer_data.start() > > func_store_data.stop() > func_store_data.join() > > func_transfer_data.stop() > func_transfer_data.join() Hi David I think that the main problem is your use of while(1) (usually written as 'while 1' BTW). The effect is that you create multiple copies of CStoreData and CTransferData, each running simultaneously. As you bind them to the same name each time, the previous one presumably gets garbage collected. I don't know if this effectively kills the running thread or not. Either way, this is not what you want to happen. Here are some initial thoughts - 1. You say that you want the main program to continue running in the background. Personally I find it easier to think of the main program running in the foreground, and each of the functions running in the background. 2. As you speak of launching several functions, you may want to keep a list of them to make it easier to stop them at the end. 3. Instead of passing 'timestamp' as an argument to each function, it is probably better to call datatime.now() within the function itself. Based on these thoughts, maybe your program should look something like this - running_functions = [] while 1: if some_condition: # start function to store data func = CStoreData() func.start() running_functions.append(func) if some_other_condition: # start function to transfer data func = CTransferData() func.start() running_functions.append(func) if end_condition: # terminate program break # break out of while loop time.sleep(0.1) # to avoid hogging the cpu # stop all running functions at end for func in running_functions: func.stop() func.join() I hope this gives you some ideas. Frank From walkraft at gmail.com Fri Aug 14 03:05:18 2009 From: walkraft at gmail.com (casebash) Date: Fri, 14 Aug 2009 00:05:18 -0700 (PDT) Subject: Nice copy in interactive terminal References: <1250153823.228153@athprx03> Message-ID: <0dac8bc9-8f00-4f4e-bc29-b475bade7685@y10g2000prg.googlegroups.com> I mainly develop on Linux these days, but if I ever end up doing anything on windows I'll make sure to look at that. On Aug 13, 6:56?pm, "Elias Fotinis \(eliasf\)" wrote: > "casebash" wrote: > > I've been wondering for a while if there exists an interactive > > terminal which has nice copy feature (ie. I can copy code without > > getting the >>> in front of every line). > > It would help if we knew what platform you're interested in -- your > User-Agent is G2/1.0, but I don't know what that is. ?:o) > > On Windows, PythonWin can copy from the interactive window without the > prompts. From gabriel.rossetti at arimaz.com Fri Aug 14 03:15:34 2009 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Fri, 14 Aug 2009 09:15:34 +0200 Subject: socket.send : (11, 'Resource temporarily unavailable') Message-ID: <4A850F16.4010309@arimaz.com> Hello everyone, I get a (11, 'Resource temporarily unavailable') error when I try to send a file using a socket. Is there s size limit? I tried sending a smaller file and ii poses no problem. Am I doing something wrong? Here is the code: def sendMessage(host, port, msg): if isinstance(msg, unicode): msg = msg.encode("utf-8") sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.setblocking(0) totalsent = 0 while totalsent < len(msg): sent = sock.send(msg[totalsent:]) if sent == 0: raise RuntimeError, "socket connection broken" totalsent = totalsent + sent sock.close() Thank you, Gabriel From javier.collado at gmail.com Fri Aug 14 03:18:45 2009 From: javier.collado at gmail.com (Javier Collado) Date: Fri, 14 Aug 2009 09:18:45 +0200 Subject: OptionParser How to: prog [options] [arguments] In-Reply-To: References: Message-ID: Hello, I think that this isn't possible with optparse library. However, it's possible with argparse (http://code.google.com/p/argparse/): http://argparse.googlecode.com/svn/trunk/doc/other-methods.html#sub-commands It's not a standard library, but it's worth to take a look at it. Best regards, Javier 2009/8/14 Steven Woody : > Hi, > I am using OptionParser, but I've not managed figure out a way to support > what I wanted command line format "prog [options] [arguments]". > E.g., "svn ls -r123 http://hello.world".???Can?I?do?this?using?OptionParser? > Thanks. > -- > Life is the only flaw in an otherwise perfect nonexistence > ? ?-- Schopenhauer > > narke > public key at http://subkeys.pgp.net:11371 (narkewoody at gmail.com) > > -- > http://mail.python.org/mailman/listinfo/python-list > > From durumdara at gmail.com Fri Aug 14 03:43:02 2009 From: durumdara at gmail.com (durumdara) Date: Fri, 14 Aug 2009 00:43:02 -0700 (PDT) Subject: Pygresql, and query meta informations Message-ID: <55aceb1c-b3d9-4f9b-b8cf-d9833edb2660@c29g2000yqd.googlegroups.com> Hi! Pygresql, DB-API. I search for a solution to get meta information about last query, because I must export these infos to Delphi. Delphi have TDataSet, and it have meta structure that must be defined before I create it. For char/varchar fields I must define their sizes! Pygresql is not retreive the field sizes. Ok, it have solution that CHAR fields values have full size; but varchars are not. Ok, secondary I can calc all field lengths before I export, and I can set THIS CALCULATED size to the field, but this is data dependent. If I have NULL only, the field size = 0. Next query get 71 to the field len. Next query is 234... So I wanna ask that a.) have I some special way in Pygresql to retreive the char/varchar field's length? b.) if not, how to I realize this (other ways)? Thanks for your help: dd From gabriel.rossetti at arimaz.com Fri Aug 14 03:47:50 2009 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Fri, 14 Aug 2009 09:47:50 +0200 Subject: socket.send : (11, 'Resource temporarily unavailable') In-Reply-To: <4A850F16.4010309@arimaz.com> References: <4A850F16.4010309@arimaz.com> Message-ID: <4A8516A6.7010309@arimaz.com> Gabriel Rossetti wrote: > Hello everyone, > > I get a (11, 'Resource temporarily unavailable') error when I try to > send a file using a socket. Is there s size limit? I tried sending a > smaller file and ii poses no problem. Am I doing something wrong? Here > is the code: > > def sendMessage(host, port, msg): > > if isinstance(msg, unicode): > msg = msg.encode("utf-8") > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.connect((host, port)) > sock.setblocking(0) > totalsent = 0 > while totalsent < len(msg): > sent = sock.send(msg[totalsent:]) > if sent == 0: > raise RuntimeError, "socket connection broken" > totalsent = totalsent + sent > sock.close() > > Thank you, > Gabriel Actually, the original code didn't have the sock.setblocking(0), the problem I am trying to find is that the server does have sock.setblocking(0) (I can't change that) and it is getting the same error as my client has with the sock.setblocking(0), except it gets it on the accept() call. I tried modifying my code to be like this : def sendMessage(host, port, msg): if isinstance(msg, unicode): msg = msg.encode("utf-8") burstSize = 4096 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) while msg: sent = sock.send(msg[:burstSize]) print "Sending %d bytes..." % sent if sent == 0: raise RuntimeError, "socket connection broken" msg = msg[burstSize:] sock.close() thinking maybe if I send small parts it would work better but this does not seem to change anything. How are large msgs sent w/ a socket in python to a non-blocking server? The msg I'm trying to send is 175213 bytes long. Thank, Gabriel From hendrik at microcorp.co.za Fri Aug 14 04:11:34 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 14 Aug 2009 10:11:34 +0200 Subject: socket.send : (11, 'Resource temporarily unavailable') In-Reply-To: <4A850F16.4010309@arimaz.com> References: <4A850F16.4010309@arimaz.com> Message-ID: <200908141011.34272.hendrik@microcorp.co.za> On Friday 14 August 2009 09:15:34 Gabriel Rossetti wrote: > Hello everyone, > > I get a (11, 'Resource temporarily unavailable') error when I try to > send a file using a socket. Is there s size limit? I tried sending a > smaller file and ii poses no problem. Am I doing something wrong? Here > is the code: > > def sendMessage(host, port, msg): > > if isinstance(msg, unicode): > msg = msg.encode("utf-8") > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.connect((host, port)) > sock.setblocking(0) This is the problem - if the socket does not block, it will return the " temporarily unavailable" error when it is busy. If you want to use it non blocking then you have to handle the error in a try except, and loop. - Hendrik From hendrik at microcorp.co.za Fri Aug 14 04:16:21 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 14 Aug 2009 10:16:21 +0200 Subject: socket.send : (11, 'Resource temporarily unavailable') In-Reply-To: <4A8516A6.7010309@arimaz.com> References: <4A850F16.4010309@arimaz.com> <4A8516A6.7010309@arimaz.com> Message-ID: <200908141016.21579.hendrik@microcorp.co.za> On Friday 14 August 2009 09:47:50 Gabriel Rossetti wrote: > Gabriel Rossetti wrote: 8< ------------------------------------------ > > Actually, the original code didn't have the sock.setblocking(0), the > problem I am trying to find is that the server does have > sock.setblocking(0) (I can't change that) and it is getting the same > error as my client has with the sock.setblocking(0), except it gets it > on the accept() call. I tried modifying my code to be like this : > > def sendMessage(host, port, msg): > > if isinstance(msg, unicode): > msg = msg.encode("utf-8") > > burstSize = 4096 > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.connect((host, port)) > while msg: > sent = sock.send(msg[:burstSize]) > print "Sending %d bytes..." % sent > if sent == 0: > raise RuntimeError, "socket connection broken" > msg = msg[burstSize:] > sock.close() > > thinking maybe if I send small parts it would work better but this does > not seem to change anything. > How are large msgs sent w/ a socket in python to a non-blocking server? > The msg I'm trying to send is 175213 bytes long. Google for netstring, and also look at sock.sendall instead of send. - Hendrik From bearophileHUGS at lycos.com Fri Aug 14 04:24:20 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Fri, 14 Aug 2009 01:24:20 -0700 (PDT) Subject: Plotting Quadratic Functions, pygame References: Message-ID: Senad Ibraimoski Of Belgrade: > Hello, I'm a new guy to this group, my professor recommend this group > to me, because I was boring him with questions.I'm new to python, and > I have problem plotting Quadratic Functions. Using module pygame. Python is a tool you use to learn something else, but tools are important, they also help shape the way you think. So tell your teacher that questions about tools are important enough. If your purpose is to learn something then using Pygame to plot functions is OK. If your purpose is just to plot them, and you don't have strange needs, then MatPlotLib can be better. Bye, bearophile From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 04:34:52 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 08:34:52 GMT Subject: trouble with reload References: <24956946.post@talk.nabble.com> Message-ID: <0295120a$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 13:49:19 +0900, Terry Reedy wrote: > Dr. Phillip M. Feldman wrote: >> According to the Python documentation, 'reload' reloads a previously >> imported module (so that changes made via an external editor will be >> effective). But, when I try to use this command, I get the following >> error message: >> >> TypeError: reload() argument must be module >> >> Any suggestions will be appreciated. > > Besides the other answers, do not use reload. It is removed in Py3 > because it cannot be made to work as people reasonably expect. That's a damn shame, because it is very useful for interactive use once you get it's quirks. Is it gone-gone or just removed from built-ins? If the former, would the following be a reasonable replacement? def reload(module): if type(module) is not type(__builtins__): raise TypeError("reload() argument must be module") name = module.__name__ del globals()[name] del sys.modules[name] globals()[name] = __import__(name) It seems to work for me, but I'm not sure if I've missed something. -- Steven From rylesny at gmail.com Fri Aug 14 04:38:57 2009 From: rylesny at gmail.com (ryles) Date: Fri, 14 Aug 2009 01:38:57 -0700 (PDT) Subject: Python "and" behavior References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> Message-ID: <55453c36-d789-4710-8a9a-ce5dd306c7c1@h31g2000yqd.googlegroups.com> On Aug 13, 8:36?pm, goldtech wrote: > Could you explain or link me to an explanation of this? http://docs.python.org/tutorial/datastructures.html#more-on-conditions Give the whole tutorial a good read. From hendrik at microcorp.co.za Fri Aug 14 05:04:07 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 14 Aug 2009 11:04:07 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? Message-ID: <200908141104.07641.hendrik@microcorp.co.za> In the past, on this group, I have made statements that said that on Linux, the serial port handling somehow does not allow transmitting and receiving at the same time, and nobody contradicted me. I am running into the self same issue again. What I normally do is to open the port like this: port = open("/dev/ttyS0","r+b",0) and then I unblock it with: def unblock(f): """Given file 'f', sets its unblock flag to true.""" fcntl.fcntl(f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) Then I can write a loop that uses a try-except to see if there are characters available, and that examines a queue to see if there is something to transmit, to give the appearance of full duplex functionality. What I would really like is to have two threads - one that does blocking input waiting for a character, and one that examines an output queue and transmits the stuff it finds. When I try to do this, it does not seem to work - as far as I can see, it is as if the underlying implementation is somehow single threaded - if it is waiting for a received character, it waits until something comes in before it will transmit anything. So if you are talking to a device that does not respond, the whole thing freezes up waiting for a character that never comes, and nothing is transmitted either, despite the call to port.write(somestring). The write blocks, and everything stops, waiting for the receipt to finish. Is there a way to get full duplex, so that the transmit and receive are independent of each other? Or are we stuck with a disk-like model that forces a sequence on reads and writes? - Hendrik From jeanmichel at sequans.com Fri Aug 14 05:27:39 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 11:27:39 +0200 Subject: trouble with reload In-Reply-To: <24965811.post@talk.nabble.com> References: <24956946.post@talk.nabble.com> <24965811.post@talk.nabble.com> Message-ID: <4A852E0B.4070309@sequans.com> Dr. Phillip M. Feldman wrote: > Actually, I've tried both of these, and I get (different) errors in both > cases: > > In [1]: from mymath import * > > In [2]: reload(mymath) > NameError: name 'mymath' is not defined > > In [3]: reload('mymath') > TypeError: reload() argument must be module > > Please don't top post :o) 1/ Do not use the 'from import *' form, unless you don't have any other choice, it will set in your namespace an undefined number of symbols, you may get some name collisions which usually lead to very nasty bugs. import mymath reload(mymath) will do the trick. If you are of those lazy coders you can write import mymath as mm reload(mm) mm.aFunction() If you are using a few functions and don't what to prefix them with the module name you can also write import mymath from mymath import func1, func2, func3 # reload the functions reload(mymath) func1 = mymath.func1 func2 = mymath.func2 func3 = mymath.func3 JM From gagsl-py2 at yahoo.com.ar Fri Aug 14 05:32:25 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Aug 2009 06:32:25 -0300 Subject: trouble with reload References: <24956946.post@talk.nabble.com> <0295120a$0$20647$c3e8da3@news.astraweb.com> Message-ID: En Fri, 14 Aug 2009 05:34:52 -0300, Steven D'Aprano escribi?: > On Fri, 14 Aug 2009 13:49:19 +0900, Terry Reedy wrote: >> Besides the other answers, do not use reload. It is removed in Py3 >> because it cannot be made to work as people reasonably expect. > > That's a damn shame, because it is very useful for interactive use once > you get it's quirks. Is it gone-gone or just removed from built-ins? Just relocated: p3> import imp p3> imp.reload -- Gabriel Genellina From pavlovevidence at gmail.com Fri Aug 14 05:38:28 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 14 Aug 2009 02:38:28 -0700 (PDT) Subject: OptionParser How to: prog [options] [arguments] References: Message-ID: On Aug 14, 12:18?am, Javier Collado wrote: > 2009/8/14 Steven Woody : > > > Hi, > > I am using OptionParser, but I've not managed figure out a way to support > > what I wanted command line format "prog [options] [arguments]". > > E.g., "svn ls -r123http://hello.world". Can I do this using OptionParser? > > Thanks. > > Hello, > > I think that this isn't possible with optparse library. It's possible if you remove sys.argv[1] before invoking optparse. But... > However, it's possible with argparse (http://code.google.com/p/argparse/): > ?http://argparse.googlecode.com/svn/trunk/doc/other-methods.html#sub-c... > > It's not a standard library, but it's worth to take a look at it. It's more than worth looking at, it's a slam dunk. It's superior to optparse in every way I can think of. Unless you don't want the third- party dependency there is no reason to use optparse instead of argparse. Carl Banks From gagsl-py2 at yahoo.com.ar Fri Aug 14 05:45:57 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Aug 2009 06:45:57 -0300 Subject: OptionParser How to: prog [options] [arguments] References: Message-ID: En Fri, 14 Aug 2009 03:22:49 -0300, Steven Woody escribi?: > I am using OptionParser, but I've not managed figure out a way to support > what I wanted command line format "prog [options] [arguments]". > E.g., "svn ls -r123 http://hello.world". Can I do this using > OptionParser? Extract the yourself, and pass the remaining arguments (that is, sys.argv[2:]) to parser.parse_args() -- Gabriel Genellina From jeanmichel at sequans.com Fri Aug 14 05:45:58 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 11:45:58 +0200 Subject: implementing descriptors In-Reply-To: References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: <4A853256.9070806@sequans.com> Emile van Sebille wrote: > On 8/13/2009 3:17 PM dippim said... >> I am new to Python and I have a question about descriptors. If I have >> a class as written below, is there a way to use descriptors to be >> certain that the datetime in start is always before the one in end? >> >> class foo(object): >> def __init__(self,a = None,b = None) >> self.start = a >> self.end = b >> >> from datetime import datetime >> c = datetime(2009,8,13,6,15,0) >> d = datetime(2009,8,14,12,0,0) >> afoo = foo(c,d) >> >> For instance, if the following code were run, I would like to instance >> of foo to switch the start and end times. >> >> afoo.start = datetime(2010,8,13,6,15,0) >> >> I was thinking of using the __set__ descriptor to catch the assignment >> and reverse the values if necessary, > > why not... > > > class foo(object): > def __init__(self,a = None,b = None) > self.start = min(a,b) > self.end = max(a,b) > > > Emile > or class foo(object): def __init__(self, start, end) self.start = start self.end = end Problem solved by design :o) JM From sleepy at cabbage.co.uk Fri Aug 14 05:48:34 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Fri, 14 Aug 2009 09:48:34 GMT Subject: get the pause status from amarok 2.1 Message-ID: As the title says, I'm trying to find a way to get the pause status from amarok 2.1. I'm running kubuntu 9.04 with kde 4.2.2, python 2.6.2. Thanks in advance. From martin.hellwig at dcuktec.org Fri Aug 14 05:51:52 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 14 Aug 2009 10:51:52 +0100 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode In-Reply-To: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: Sounds like a bad case of STRIS http://blog.dcuktec.com/2009/08/stris.html From duncan.booth at invalid.invalid Fri Aug 14 06:26:55 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Aug 2009 10:26:55 GMT Subject: Python "and" behavior References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> <4A84B4E2.9080300@islandtraining.com> Message-ID: MRAB wrote: > Operation Result >|x or y| x if x else y >|x and y| y if x else x >|not x| False if x else False > >:-) > That's not a terribly good definition for the 'not' operator. Try: |not x| False if x else True -- Duncan Booth http://kupuguy.blogspot.com From deets at nospam.web.de Fri Aug 14 06:54:32 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 12:54:32 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <7eku38F2gtku3U1@mid.uni-berlin.de> Hendrik van Rooyen schrieb: > In the past, on this group, I have made statements that said that on Linux, > the serial port handling somehow does not allow transmitting and receiving at > the same time, and nobody contradicted me. > > I am running into the self same issue again. > > What I normally do is to open the port like this: > > port = open("/dev/ttyS0","r+b",0) How about using pyserial? With that, I never had any problems accessing the the serial ports, and AFAIK no duplex-problems as well. And I seriously doubt that these are a python-related problem - python only has a very thin, direct layer above the posix-calls, and doesn't do anything that would explain your observed behavior. The GIL is not the issue here either - it won't interfer with blocking IO. Diez From deets at nospam.web.de Fri Aug 14 06:55:07 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 12:55:07 +0200 Subject: get the pause status from amarok 2.1 In-Reply-To: References: Message-ID: <7eku4bF2gtku3U2@mid.uni-berlin.de> Sleepy Cabbage schrieb: > As the title says, I'm trying to find a way to get the pause status from > amarok 2.1. > > I'm running kubuntu 9.04 with kde 4.2.2, python 2.6.2. > > Thanks in advance. Not at my linux-system right now, but dcop and the respective python-module should help. Diez From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 06:58:30 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 10:58:30 GMT Subject: need help calculating point between two coordinates. References: <2d059a29-933e-4e2c-8730-f1f2688af26c@24g2000yqm.googlegroups.com> Message-ID: <029533b3$0$20647$c3e8da3@news.astraweb.com> On Thu, 13 Aug 2009 14:26:54 -0700, PeteDK wrote: > Hi there > > I'am working on a route comparison tool for carpools. > > The route comparison is based on 'steps' retrieved from google maps > GDirection. These steps vary in length and i use the coordinates at the > beginning of each "step". However, sometimes the distance of these steps > is too long(ex. driving 30-40 km. on the freeway). Therefore i would > like to calculate/find the coordinate located in between two given > coordinates. > Lets say one step starts at: > 56.043185,9.922714 > and ends at: > 56.234287,9.864521 > > I would then like to calculate the point right in the middle of these > coordinates. Can you assume that the coordinate system is virtually flat between those points? That is, are the distances small enough that the curvature of the earth isn't relevant? If so, the following should be close enough: def midpoint(a, b): """Return the two-dimensional point midway between points a and b.""" x = (a[0] + b[0])/2.0 y = (a[1] + b[1])/2.0 return (x, y) Otherwise, you can probably start here: http://www.geomidpoint.com/methods.html http://mathforum.org/library/drmath/results.html?contexts=drmath&levels=college&passed_id=51416&passed_title=College+Physics&search_cats=no&textsearch=spherical&textsearch_bool_type=and&topics=physics -- Steven From keith.hughitt at gmail.com Fri Aug 14 07:01:09 2009 From: keith.hughitt at gmail.com (pwnedd) Date: Fri, 14 Aug 2009 04:01:09 -0700 (PDT) Subject: Database query execution times in Python? In-Reply-To: References: <24870050.post@talk.nabble.com> Message-ID: <24969867.post@talk.nabble.com> > Look up EXPLAIN Thanks for the suggestion. I don't see any option to have EXPLAIN display the query time though? -- View this message in context: http://www.nabble.com/Database-query-execution-times-in-Python--tp24870050p24969867.html Sent from the Python - python-list mailing list archive at Nabble.com. From anand at esi-india.com Fri Aug 14 07:01:21 2009 From: anand at esi-india.com (Anand K Rayudu) Date: Fri, 14 Aug 2009 16:31:21 +0530 Subject: How to reset document string In-Reply-To: References: Message-ID: <4A854401.9070500@esi-india.com> Dear Carl, Your ideas are extremely good, and I liked idea 2 especially, based on that I am considering following approach. Eg: let us say I have module named myModule and exposing myModule.myAPI So I will now rename myModule as _myModule and write a python layer with myModule So my python layer will look like this file name myModule.py import _myModule def myAPI(arg1, arg2): """ @param arg1 help string @param arg2 help string """" _myModule.myAPI(arg1,arg2) # actual API So I will provide mechanism which reads the help files and generates this binding python file and reload the module, So now my python editor has the new python strings. Also another advantages of this approach is if customer choses his own IDE he will still get the documentation of our APIs, by just ensuring these python files are in PYTHON_PATH I think this is better approach, kindly please let me know your comments Regards, Anand > On Aug 7, 2:54 am, Anand K Rayudu wrote: > >> Dear All, >> >> We have extended and embedded python into my our application. >> We exposed few APIs to python using >> >> Py_InitModule("myModuleName", myMethods); >> where my methods are >> >> static PyMethodDef VistaDbMethods[] = { >> { (char *)"myAPI",_myAPICFunctionPtr ,METH_VARARGS,"usage: MyHelp)" } >> >> Now problem is ml_doc (Document string). Most of the time the strings >> given by development team is not descriptive enough, so support team >> want to enhance these docstring on need basis and supply to customer >> The idea is we will provide get latest help option from application, >> which will contact our webserver or allow user to pick new help >> document, which will re apply the help on fly. >> From then on our script editors will show the new enhanced help. >> How do I achieve this. >> > > Sounds very cool. I have a few ideas. > > 1. Since you say you are embedding Python in your application, the > most direct way might be to modify the Python interpreter to allow the > __doc__ attribute to be changed. You'd have to modify the PyCFunction > type (defined in methodobject.h and methodobject.c) to allow > overriding the compiled-in doc field. > > 2. Instead of replacing the __doc__ attribute of the function, just > replace the whole function with a wrapper. So, for instance, if your > application decides to update the docstring for myModuleName.myAPI(), > instead of running code like this: > > myModuleName.myAPI.__doc__ = 'new docstring' > > run code like this: > > def create_wrapper(func,docstring): > def wrapper(*args): > return func(*args) > wrapper.__doc__ = doc > return wrapper > myModuleName.myAPI = create_wrapper( > myModuleName.myAPI,'new docstring') > > So now myApi is a Python function with the new docstring that calls > the old function. (Note: if you are concerned with efficiency, it's > possible to write a wrapper in C that has very little overhead.) > > This approach has minor disadvantages (such as if any code write from > myModuleName import myAPI--it won't see the new version) but it may be > the easiest approach. > > 3. Instead of customizing the __doc__ attribute, store any custom > docstrings in a dictionary keyed by the function. > > custom_doc[myModuleName.myApi] = 'new docstring' > > Your script editor, when looking for documentation, will first search > in this custom area to see if the docstring has been overridden; if > so, use that; if not, use the docstring. Something like this: > > def documentation_to_use_in_script_editor(func): > try: > return custom_doc[func] > except KeyError: > return func.__doc__ > > That has the negative of the special docstring not being visible at an > interactive prompt. > > > I have given you some fairly vague answers, hopefully that'll give you > some idea. It sounds like you have an ambitious project, suggesting > that you are probably good enough to implement the suggestions. > > > Carl Banks > -------------- next part -------------- An HTML attachment was scrubbed... URL: From matiassurdi at gmail.com Fri Aug 14 07:30:39 2009 From: matiassurdi at gmail.com (Matias) Date: Fri, 14 Aug 2009 13:30:39 +0200 Subject: python-ldap and encodings Message-ID: Hi! I'm using python-ldap to create some entries on my openldap server. The problem is that some of those entries have accented characters and unicode text in general. I'm wondering if there is any example or documentation on how to add or modify ldap objects whose values contains non-ascii characters, such as accents, and so on. As far as I understand, those values should be encoded using base64, but if I do that, I don't know how to indicate in the modlist that this is the encoded value and not the value itself. Any help will be bery appreciated. Matias. From python at mrabarnett.plus.com Fri Aug 14 07:39:50 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 12:39:50 +0100 Subject: Format Code Repeat Counts? In-Reply-To: References: Message-ID: <4A854D06.1010503@mrabarnett.plus.com> Scott David Daniels wrote: > MRAB wrote: >> The shortest I can come up with is: >> "[" + "][".join(letters) + "]" > > Maybe a golf shot: > "][".join(letters).join("[]") > Even shorter: "["+"][".join(letters)+"]" :-) From matiassurdi at gmail.com Fri Aug 14 07:45:09 2009 From: matiassurdi at gmail.com (Matias) Date: Fri, 14 Aug 2009 13:45:09 +0200 Subject: python-ldap and encodings In-Reply-To: References: Message-ID: Matias wrote: > Hi! > > I'm using python-ldap to create some entries on my openldap server. > > The problem is that some of those entries have accented characters and > unicode text in general. > > I'm wondering if there is any example or documentation on how to add > or modify ldap objects whose values contains non-ascii characters, > such as accents, and so on. As far as I understand, those values > should be encoded using base64, but if I do that, I don't know how to > indicate in the modlist that this is the encoded value and not the > value itself. > > Any help will be bery appreciated. > > > Matias. > Nevermind.... I was doing something really stupid.Don't ask please :-) From greg at cosc.canterbury.ac.nz Fri Aug 14 08:13:46 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 15 Aug 2009 00:13:46 +1200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <7el2mqF2gi53eU1@mid.individual.net> Hendrik van Rooyen wrote: > port = open("/dev/ttyS0","r+b",0) > > What I would really like is to have two threads - one that does blocking input > waiting for a character, and one that examines an output queue and transmits > the stuff it finds. You can't read and write with the same stdio file object at the same time. Odd things tend to happen if you try. You need to open *two* file objects, one for reading and one for writing: fr = open("/dev/ttyS0","rb",0) fw = open("/dev/ttyS0","wb",0) and give fr to the reading thread and fw to the writing thread. You could also try avoiding file objects altogether and use the raw system calls in the os module. Since you're not using any buffering, there's little reason to use the stdio layer. If you do that, you should be able to use the same file descriptor for reading and writing without any trouble. -- Greg From t.gkikopoulos at dundee.ac.uk Fri Aug 14 08:52:11 2009 From: t.gkikopoulos at dundee.ac.uk (trias) Date: Fri, 14 Aug 2009 05:52:11 -0700 (PDT) Subject: anyone with genomewide microarray analysis experience ? Message-ID: <24971224.post@talk.nabble.com> Hi, I am trying to analyse some biological data from microarray experiments. Different experiments have been stored in a SQL database. One of the things I would like to do is to fetch all data from a certain distance from gene ATGs say 100+/- bp and calculate the bp average over all genes over this region. The microarray data has been normalised over each bp Does anyone have some scripts I could use for this purpose. I work with S.cerevisiae Thank you -- View this message in context: http://www.nabble.com/anyone-with-genomewide-microarray-analysis-experience---tp24971224p24971224.html Sent from the Python - python-list mailing list archive at Nabble.com. From istvan.albert at gmail.com Fri Aug 14 09:13:38 2009 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 14 Aug 2009 06:13:38 -0700 (PDT) Subject: anyone with genomewide microarray analysis experience ? References: Message-ID: <10e21ef1-0c13-4810-bbe2-79349099c85b@c29g2000yqd.googlegroups.com> On Aug 14, 8:52?am, trias wrote: > Does anyone have some scripts I could use for this purpose. I work with > S.cerevisiae Since the largest chromosome on the yeast genome is around 4 million bp, the easiest way to accomplish your goal is to create a list of the same size as the chromosome, then populate this list by mapping the genomic index to the list index. After doing this your problem simplifies to slicing the list around the coordinates of interest. You'll be done in minutes. i. From ml at well-adjusted.de Fri Aug 14 09:17:22 2009 From: ml at well-adjusted.de (Jochen Schulz) Date: Fri, 14 Aug 2009 15:17:22 +0200 Subject: anyone with genomewide microarray analysis experience ? In-Reply-To: <24971224.post@talk.nabble.com> References: <24971224.post@talk.nabble.com> Message-ID: <20090814131721.GM19479@wasteland.homelinux.net> trias: > > One of the things I would like to do is to fetch all data from a certain > distance from gene ATGs say 100+/- bp and calculate the bp average over all > genes over this region. I know absolutely nothing about your problem domain, but if your distance function is metric, you can use this: http://well-adjusted.de/mspace.py or that: http://code.activestate.com/recipes/572156/ The latter (by Baerophile) is fast, the former (by me) has more features. Baerophile has even faster implementations (non-Python) as well. J. -- I am worried that my dreams pale in comparison beside TV docu-soaps. [Agree] [Disagree] -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 204 bytes Desc: Digital signature URL: From cjw at ncf.ca Fri Aug 14 09:23:17 2009 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 14 Aug 2009 09:23:17 -0400 Subject: trouble with reload In-Reply-To: References: <24956946.post@talk.nabble.com> Message-ID: Terry Reedy wrote: > Dr. Phillip M. Feldman wrote: >> According to the Python documentation, 'reload' reloads a previously >> imported >> module (so that changes made via an external editor will be >> effective). But, when I try to use this command, I get the following >> error message: >> >> TypeError: reload() argument must be module >> >> Any suggestions will be appreciated. > > Besides the other answers, do not use reload. It is removed in Py3 > because it cannot be made to work as people reasonably expect. > > tjr > It's typically a user module that needs to be reloaded. It seems that del sys.modules['moduleName'] has no effect. Is there some other way of ensuring that any import goes to moduleName.py, instead of moduleName.pyc? Colin W. From alan.isaac at gmail.com Fri Aug 14 09:26:02 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Fri, 14 Aug 2009 13:26:02 GMT Subject: csv.DictWriter.write_header() In-Reply-To: <68b9136d-fa0b-42dc-addf-02d338da34cd@z4g2000prh.googlegroups.com> References: <68b9136d-fa0b-42dc-addf-02d338da34cd@z4g2000prh.googlegroups.com> Message-ID: > On Aug 13, 1:15 pm, Alan G Isaac wrote: >> I do not understand the reason for your silly, sarcastic response. On 8/13/2009 7:58 AM John Machin apparently wrote: > Duck typing: ask a silly question, get a silly answer. Maybe if you learned to be a more generous reader, fewer questions would look "silly" to you. On 8/13/2009 7:58 AM John Machin apparently wrote: > I can imagine that one might (without reading the source) make do with > the published APIs: Now you get it. > On Aug 13, 1:15 pm, Alan G Isaac wrote: >> So my question was, would this improve the class from >> a usability perspective? On 8/13/2009 7:58 AM John Machin apparently wrote: > Of course. Thank you, Alan From david.mcwright at usbfmi.com Fri Aug 14 09:29:22 2009 From: david.mcwright at usbfmi.com (dippim) Date: Fri, 14 Aug 2009 06:29:22 -0700 (PDT) Subject: implementing descriptors References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: <564bdae4-8b2c-440b-bc18-f76a5fdc60c2@r27g2000vbn.googlegroups.com> On Aug 14, 5:45?am, Jean-Michel Pichavant wrote: > Emile van Sebille wrote: > > On 8/13/2009 3:17 PM dippim said... > >> I am new to Python and I have a question about descriptors. ?If I have > >> a class as written below, is there a way to use descriptors to be > >> certain that the datetime in start is always before the one in end? > > >> class foo(object): > >> ? ?def __init__(self,a = None,b = None) > >> ? ? ? self.start = a > >> ? ? ? self.end = b > > >> from datetime import datetime > >> c = datetime(2009,8,13,6,15,0) > >> d = datetime(2009,8,14,12,0,0) > >> afoo = foo(c,d) > > >> For instance, if the following code were run, I would like to instance > >> of foo to switch the start and end times. > > >> afoo.start = datetime(2010,8,13,6,15,0) > > >> I was thinking of using the __set__ descriptor to catch the assignment > >> and reverse the values if necessary, > > > why not... > > > class foo(object): > > ? ?def __init__(self,a = None,b = None) > > ? ? ? self.start = min(a,b) > > ? ? ? self.end = max(a,b) > > > Emile > > or > > class foo(object): > ? ? def __init__(self, start, end) > ? ? ? ?self.start = start > ? ? ? ?self.end = end > > Problem solved by design :o) > > JM Emile and JM, Thanks for the response. However, these solution only work at instantiation. If I change the value of start or end after instantiation, then I can make start or end whatever I like without regard to order. From hendrik at microcorp.co.za Fri Aug 14 09:38:15 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 14 Aug 2009 15:38:15 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <7eku38F2gtku3U1@mid.uni-berlin.de> References: <7eku38F2gtku3U1@mid.uni-berlin.de> Message-ID: <200908141538.15798.hendrik@microcorp.co.za> On Friday 14 August 2009 12:54:32 Diez B. Roggisch wrote: > > How about using pyserial? With that, I never had any problems accessing > the the serial ports, and AFAIK no duplex-problems as well. And I > seriously doubt that these are a python-related problem - python only > has a very thin, direct layer above the posix-calls, and doesn't do > anything that would explain your observed behavior. The GIL is not the > issue here either - it won't interfer with blocking IO. I will have a look at pyserial - have never used it before. I agree that it is probably not a Python issue, and that the GIL is irelevant - I was hoping that someone had already travelled the road and could give me a signpost. In the meantime I have had another idea which I have also not tried yet, namely to do independent opens for reading and writing, to give me two file instances instead of one, and to try with that. I have no idea if it would make any difference, or even work at all. My normal stuff works, but I do not like it as it is essentially busy looping with short sleeps in between. In the eBox, it uses most of the processor just to move a few bytes of I/O in and out between the serial port and the TCP/IP, and struggles to do that better than five times a second, while the message time on the 115200 baud port is only about 2 milliseconds. - Hendrik From deets at nospam.web.de Fri Aug 14 09:39:31 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 15:39:31 +0200 Subject: implementing descriptors In-Reply-To: <564bdae4-8b2c-440b-bc18-f76a5fdc60c2@r27g2000vbn.googlegroups.com> References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> <564bdae4-8b2c-440b-bc18-f76a5fdc60c2@r27g2000vbn.googlegroups.com> Message-ID: <7el7ojF2gggrvU1@mid.uni-berlin.de> dippim schrieb: > On Aug 14, 5:45 am, Jean-Michel Pichavant > wrote: >> Emile van Sebille wrote: >>> On 8/13/2009 3:17 PM dippim said... >>>> I am new to Python and I have a question about descriptors. If I have >>>> a class as written below, is there a way to use descriptors to be >>>> certain that the datetime in start is always before the one in end? >>>> class foo(object): >>>> def __init__(self,a = None,b = None) >>>> self.start = a >>>> self.end = b >>>> from datetime import datetime >>>> c = datetime(2009,8,13,6,15,0) >>>> d = datetime(2009,8,14,12,0,0) >>>> afoo = foo(c,d) >>>> For instance, if the following code were run, I would like to instance >>>> of foo to switch the start and end times. >>>> afoo.start = datetime(2010,8,13,6,15,0) >>>> I was thinking of using the __set__ descriptor to catch the assignment >>>> and reverse the values if necessary, >>> why not... >>> class foo(object): >>> def __init__(self,a = None,b = None) >>> self.start = min(a,b) >>> self.end = max(a,b) >>> Emile >> or >> >> class foo(object): >> def __init__(self, start, end) >> self.start = start >> self.end = end >> >> Problem solved by design :o) >> >> JM > > Emile and JM, > > Thanks for the response. However, these solution only work at > instantiation. If I change the value of start or end after > instantiation, then I can make start or end whatever I like without > regard to order. > But for that, you don't need descriptors. All you need is a property: class Foo(object): def __init__(self, start, end): self._start = start self._end = end @property def start(self): return start @start.setter def start(self, value): if value >= self._end: raise ValueError, "Tried to set a value greater than end!" self._start = value # repeat for end, switch relational op Diez From hendrik at microcorp.co.za Fri Aug 14 09:48:08 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 14 Aug 2009 15:48:08 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <7el2mqF2gi53eU1@mid.individual.net> References: <7el2mqF2gi53eU1@mid.individual.net> Message-ID: <200908141548.08235.hendrik@microcorp.co.za> On Friday 14 August 2009 14:13:46 greg wrote: > You can't read and write with the same stdio file object > at the same time. Odd things tend to happen if you try. > > You need to open *two* file objects, one for reading > and one for writing: > > fr = open("/dev/ttyS0","rb",0) > fw = open("/dev/ttyS0","wb",0) > > and give fr to the reading thread and fw to the > writing thread. Does this actually work without somehow falling foul of the fact that the /dev/ttyS0 is only one thing? - I know that there is no physical reason for not being able to go in and out at the same time - in my embedded stuff I do that routinely - but that is all assembler running on bare metal so it is under my own control. > > You could also try avoiding file objects altogether > and use the raw system calls in the os module. Since > you're not using any buffering, there's little reason > to use the stdio layer. If you do that, you should be > able to use the same file descriptor for reading and > writing without any trouble. Thanks for this - I now have my weekend cut out for me... - Hendrik From david.mcwright at usbfmi.com Fri Aug 14 09:48:11 2009 From: david.mcwright at usbfmi.com (dippim) Date: Fri, 14 Aug 2009 06:48:11 -0700 (PDT) Subject: implementing descriptors References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: On Aug 14, 2:34?am, Raymond Hettinger wrote: > [David] > > > > > I am new to Python and I have a question about descriptors. ?If I have > > a class as written below, is there a way to use descriptors to be > > certain that the datetime in start is always before the one in end? > > > class foo(object): > > ? ?def __init__(self,a = None,b = None) > > ? ? ? self.start = a > > ? ? ? self.end = b > > > from datetime import datetime > > c = datetime(2009,8,13,6,15,0) > > d = datetime(2009,8,14,12,0,0) > > afoo = foo(c,d) > > > For instance, if the following code were run, I would like to instance > > of foo to switch the start and end times. > > > afoo.start = datetime(2010,8,13,6,15,0) > > > I was thinking of using the __set__ descriptor to catch the assignment > > and reverse the values if necessary, but I can't figure out how to > > determine which values is being set. > > You're on the right track, but it is easier to use property() than to > write your own custom descriptor with __get__ and __set__. > > class foo(object): > ? ? def __init__(self,a = None,b = None): > ? ? ? ? self._start = a > ? ? ? ? self._end = b > ? ? def get_start(self): > ? ? ? ? return self._start > ? ? def set_start(self, value): > ? ? ? ? if self._end is None or value < self._end: > ? ? ? ? ? ? self._start = value > ? ? ? ? else: > ? ? ? ? ? ? self._end = value > ? ? start = property(get_start, set_start) > ? ? def get_end(self): > ? ? ? ? return self._end > ? ? def set_end(self, value): > ? ? ? ? if self._start is None or value > self._start: > ? ? ? ? ? ? self._end = value > ? ? ? ? else: > ? ? ? ? ? ? self._start = value > ? ? end = property(get_end, set_end) > > Raymond Raymond, This functionality is exactly what I was looking for. Thanks! I'll be using this to solve my problem. Now that I'm on the right track, I'm still a bit confused about how __get__ and __set__ are useful. Admittedly, I don't need to understand them to solve this problem, but perhaps they may be useful in the future. If I wanted to solve this problem using __get__ and __set__ could it be done? Thanks Again! From exarkun at twistedmatrix.com Fri Aug 14 09:58:37 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Fri, 14 Aug 2009 13:58:37 -0000 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <200908141538.15798.hendrik@microcorp.co.za> References: <7eku38F2gtku3U1@mid.uni-berlin.de> <200908141538.15798.hendrik@microcorp.co.za> Message-ID: <20090814135837.11286.700809778.divmod.xquotient.174@localhost.localdomain> On 01:38 pm, hendrik at microcorp.co.za wrote: >On Friday 14 August 2009 12:54:32 Diez B. Roggisch wrote: >> >>How about using pyserial? With that, I never had any problems >>accessing >>the the serial ports, and AFAIK no duplex-problems as well. And I >>seriously doubt that these are a python-related problem - python only >>has a very thin, direct layer above the posix-calls, and doesn't do >>anything that would explain your observed behavior. The GIL is not the >>issue here either - it won't interfer with blocking IO. > >I will have a look at pyserial - have never used it before. > >I agree that it is probably not a Python issue, and that the GIL is >irelevant - I was hoping that someone had already travelled the road >and >could give me a signpost. > >In the meantime I have had another idea which I have also not tried >yet, >namely to do independent opens for reading and writing, to give me two >file >instances instead of one, and to try with that. I have no idea if it >would >make any difference, or even work at all. > >My normal stuff works, but I do not like it as it is essentially busy >looping >with short sleeps in between. In the eBox, it uses most of the >processor just >to move a few bytes of I/O in and out between the serial port and the >TCP/IP, >and struggles to do that better than five times a second, while the >message >time on the 115200 baud port is only about 2 milliseconds. One strategy you might employ to get rid of the busy looping is to use Twisted and its serial port support. This also addresses the full- duplex issue you've raised. Jean-Paul From deets at nospam.web.de Fri Aug 14 10:03:22 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 16:03:22 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: <7el2mqF2gi53eU1@mid.individual.net> Message-ID: <7el95aF2h0d12U1@mid.uni-berlin.de> Hendrik van Rooyen schrieb: > On Friday 14 August 2009 14:13:46 greg wrote: > >> You can't read and write with the same stdio file object >> at the same time. Odd things tend to happen if you try. >> >> You need to open *two* file objects, one for reading >> and one for writing: >> >> fr = open("/dev/ttyS0","rb",0) >> fw = open("/dev/ttyS0","wb",0) >> >> and give fr to the reading thread and fw to the >> writing thread. > > Does this actually work without somehow falling foul of the fact that > the /dev/ttyS0 is only one thing? - I know that there is no physical reason > for not being able to go in and out at the same time - in my embedded stuff I > do that routinely - but that is all assembler running on bare metal so it is > under my own control. > >> You could also try avoiding file objects altogether >> and use the raw system calls in the os module. Since >> you're not using any buffering, there's little reason >> to use the stdio layer. If you do that, you should be >> able to use the same file descriptor for reading and >> writing without any trouble. > > Thanks for this - I now have my weekend cut out for me... You should *really* just use pyserial. No hassle, instant satisfaction. Diez From ethan at stoneleaf.us Fri Aug 14 10:04:14 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Aug 2009 07:04:14 -0700 Subject: Python "and" behavior In-Reply-To: <4A84B935.8080809@mrabarnett.plus.com> References: <10da5db0-ba83-42a1-8ce8-95d13b513ca1@v15g2000prn.googlegroups.com> <4A84B4E2.9080300@islandtraining.com> <4A84B935.8080809@mrabarnett.plus.com> Message-ID: <4A856EDE.6010205@stoneleaf.us> MRAB wrote: > Gary Herron wrote: > >> goldtech wrote: >> >>> Could you explain or link me to an explanation of this? Been using >>> Python for a while but not sure I understand what's happening below. >>> Thanks. >>> >>> >>> >>> >>>>>> ss=1 and "fffff" >>>>>> ss >>>>>> >>> >>> 'fffff' >>> >>> >>>>>> ss=0 and "fffff" >>>>>> ss >>>>>> >>> >>> 0 >>> >> >> >> Python's Boolean operators don't turn arbitrary values into True and >> False values. If you use it in any conditional, you'll get the same >> result as if it did, but it is occasionally it's nice to get the >> actual values used in the "and" instead of having the value distilled >> down to a True/False. >> >> >> >From the Python manual: >> These are the Boolean operations, ordered by ascending priority: >> >> Operation Result Notes >> |x or y| if x is false, then y, else x (1) >> |x and y| if x is false, then x, else y (1) >> |not x| if x is false, then |True|, else |False| (2) >> > The Pythonic table would be: > > Operation Result > |x or y| x if x else y > |x and y| y if x else x > |not x| False if x else False > > :-) That last should be |not x| False if x else True ~Ethan~ From aahz at pythoncraft.com Fri Aug 14 10:07:31 2009 From: aahz at pythoncraft.com (Aahz) Date: 14 Aug 2009 07:07:31 -0700 Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> Message-ID: In article <6e13754c-1fa6-4d1b-8861-146bffec8656 at h30g2000vbr.googlegroups.com>, Douglas Alan wrote: > >My friend begs to differ with the above. It would be much better for >debugging if Python generated a parsing error for unrecognized escape >sequences, rather than leaving them unchanged. g++ outputs a warning >for such escape sequences, for instance. This is what I would consider >to be the correct behavior. (Actually, I think it should just generate >a fatal parsing error, but a warning is okay too.) Well, then, the usual response applies: create a patch, discuss it on python-ideas, and see what happens. (That is, nobody has previously complained so vociferously IIRC, and adding a warning is certainly within the bounds of what's theoretically acceptable.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From invalid at invalid Fri Aug 14 10:09:35 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 09:09:35 -0500 Subject: coding for multiple versions of python References: <4A84F913.9090901@v.loewis.de> Message-ID: On 2009-08-14, Martin v. L?wis wrote: >> I'm guessing I need to configure cvs to copy files to both >> locations whenever I commit. Does that sound right? Is there a >> better way I'm not thinking of? Just use one set of source files. > If the set of files doesn't change too often, you can use symlinks. > That's how Debian currently installs Python packages for multiple > versions on a single system. > > Specifically, put the source code into /net/source/python/foo/*.py. > Then, on each system, put symlinks to all .py files into > lib/site-packages/foo. Then Python will place the .pyc files next > to the symlinks, not next to the actual .py files. Why would he need two sets of .py files? -- Grant Edwards grante Yow! I'm EMOTIONAL at now because I have visi.com MERCHANDISING CLOUT!! From invalid at invalid Fri Aug 14 10:12:20 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 09:12:20 -0500 Subject: socket.send : (11, 'Resource temporarily unavailable') References: Message-ID: On 2009-08-14, Gabriel Rossetti wrote: > I get a (11, 'Resource temporarily unavailable') error when I > try to send a file using a socket. Is there s size limit? No, there's no size limit. However, there is a bandwidth limit. You can't shove bytes into the pipe faster than they come out the other end (at least not over the long term). > I tried sending a smaller file and ii poses no problem. Am I > doing something wrong? Yes. If you want to have the socket in non-blocking mode, then you have to catch EAGAIN and retry the operation. > def sendMessage(host, port, msg): > > if isinstance(msg, unicode): > msg = msg.encode("utf-8") > > sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > sock.connect((host, port)) > sock.setblocking(0) > totalsent = 0 > while totalsent < len(msg): > sent = sock.send(msg[totalsent:]) > if sent == 0: > raise RuntimeError, "socket connection broken" > totalsent = totalsent + sent > sock.close() -- Grant Edwards grante Yow! I didn't order any at WOO-WOO ... Maybe a YUBBA visi.com ... But no WOO-WOO! From invalid at invalid Fri Aug 14 10:17:35 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 09:17:35 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: Message-ID: On 2009-08-14, Hendrik van Rooyen wrote: > In the past, on this group, I have made statements that said > that on Linux, the serial port handling somehow does not allow > transmitting and receiving at the same time, That's not true. Linux/Unix does and always has supported full-duplex communications on serial ports. > and nobody contradicted me. Um, sorry, I guess. > What I would really like is to have two threads - one that > does blocking input waiting for a character, and one that > examines an output queue and transmits the stuff it finds. That's the traditional way of doing full-duplex serial IO on Unix back in the day before the select/poll system calls were available. > When I try to do this, it does not seem to work - as far as I > can see, it is as if the underlying implementation is somehow > single threaded - if it is waiting for a received character, > it waits until something comes in before it will transmit > anything. Nope. I'll try to dig up an example, but that approach has always worked for me. > So if you are talking to a device that does not respond, the > whole thing freezes up waiting for a character that never > comes, and nothing is transmitted either, despite the call to > port.write(somestring). The write blocks, and everything > stops, waiting for the receipt to finish. I've never observed that behavior. > Is there a way to get full duplex, so that the transmit and > receive are independent of each other? That's the way serial ports work on Unix. > Or are we stuck with a disk-like model that forces a sequence > on reads and writes? No. -- Grant Edwards grante Yow! Like I always say at -- nothing can beat visi.com the BRATWURST here in DUSSELDORF!! From invalid at invalid Fri Aug 14 10:19:04 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 09:19:04 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: <7eku38F2gtku3U1@mid.uni-berlin.de> Message-ID: On 2009-08-14, Hendrik van Rooyen wrote: > In the meantime I have had another idea which I have also not tried yet, > namely to do independent opens for reading and writing, to give me two file > instances instead of one, and to try with that. I have no idea if it would > make any difference, or even work at all. That should work (and shouldn't make any difference) > My normal stuff works, but I do not like it as it is > essentially busy looping with short sleeps in between. In the > eBox, it uses most of the processor just to move a few bytes > of I/O in and out between the serial port and the TCP/IP, and > struggles to do that better than five times a second, while > the message time on the 115200 baud port is only about 2 > milliseconds. What platform are you using? I suppose it's possible that there's something broken in the serial driver for that particular hardware. -- Grant Edwards grante Yow! I feel ... JUGULAR ... at visi.com From invalid at invalid Fri Aug 14 10:19:36 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 09:19:36 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: <7eku38F2gtku3U1@mid.uni-berlin.de> <200908141538.15798.hendrik@microcorp.co.za> Message-ID: On 2009-08-14, exarkun at twistedmatrix.com wrote: > One strategy you might employ to get rid of the busy looping > is to use Twisted and its serial port support. This also > addresses the full- duplex issue you've raised. There are no such full-dulex issues. -- Grant Edwards grante Yow! The PINK SOCKS were at ORIGINALLY from 1952!! visi.com But they went to MARS around 1953!! From despen at verizon.net Fri Aug 14 10:20:12 2009 From: despen at verizon.net (despen at verizon.net) Date: Fri, 14 Aug 2009 14:20:12 GMT Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: "Martin P. Hellwig" writes: > Sounds like a bad case of STRIS > http://blog.dcuktec.com/2009/08/stris.html I believe the correct technical term for it is potty mouth. From invalid at invalid Fri Aug 14 10:28:26 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 09:28:26 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: <7el2mqF2gi53eU1@mid.individual.net> Message-ID: <1aGdnessDpUX6RjXnZ2dnUVZ_gCdnZ2d@posted.visi> On 2009-08-14, greg wrote: > Hendrik van Rooyen wrote: > >> port = open("/dev/ttyS0","r+b",0) >> >> What I would really like is to have two threads - one that >> does blocking input waiting for a character, and one that >> examines an output queue and transmits the stuff it finds. > > You can't read and write with the same stdio file object at > the same time. Odd things tend to happen if you try. > > You need to open *two* file objects, one for reading and one > for writing: > > fr = open("/dev/ttyS0","rb",0) > fw = open("/dev/ttyS0","wb",0) Doh! It didn't even occur to me that somebody would use python "file" objects for serial ports, and I completely overlooked the fact that the OP was doing that. In short: don't do that -- it just messes things up. > and give fr to the reading thread and fw to the writing > thread. > > You could also try avoiding file objects altogether and use > the raw system calls in the os module. That's definitely the way you should do serial port I/O. > Since you're not using any buffering, there's little reason to > use the stdio layer. If you do that, you should be able to use > the same file descriptor for reading and writing without any > trouble. Do not use Python file objects. Use the underlying file descriptors: os.open(), os.read(), os.write(). That will almost certainly solve your problems. If you want examples of os.xxxxx() usage, below is the PosixSerial.py module that I use for Linux-only applications. For cross-platform work, use pyserial (whose Posix support is based on the code below). ---------------------------------PosixSerial.py------------------------------ # Posix serial port class # Copyright 2001-2009 Grant B. Edwards # You may use this code in any way you like so long as you # leave this copyright notice. # Though you are not required to, it would be nice if you send # me a copy of bufixes or enhancements and allowed me to # incorporate and distribute them. import sys import fcntl import os import struct import termios import string import select if string.split(sys.version)[0] > '2': TERMIOS = termios else: import TERMIOS # construct dictionaries for baud rate lookups baudEnumToInt = {} baudIntToEnum = {} for rate in (0,50,75,110,134,150,200,300,600,1200,1800,2400,4800,9600,19200,38400,57600,115200,230400,460800,500000,576000,921600,1000000,1152000,1500000,2000000,2500000,3000000,3500000,4000000): try: i = eval('TERMIOS.B'+str(rate)) baudEnumToInt[i]=rate baudIntToEnum[rate] = i except: pass # Do not know if these are right for anything except Linux if sys.platform[:5] == 'linux': TIOCMGET = 0x5415 TIOCMBIS = 0x5416 TIOCMBIC = 0x5417 TIOCMSET = 0x5418 TIOCM_LE = 0x001 TIOCM_DTR = 0x002 TIOCM_RTS = 0x004 TIOCM_ST = 0x008 TIOCM_SR = 0x010 TIOCM_CTS = 0x020 TIOCM_CAR = 0x040 TIOCM_RNG = 0x080 TIOCM_DSR = 0x100 TIOCM_CD = TIOCM_CAR TIOCM_RI = TIOCM_RNG TIOCM_OUT1 = 0x2000 TIOCM_OUT2 = 0x4000 TIOCM_zero_str = struct.pack('I',0) TIOCM_one_str = struct.pack('I',1) TIOCM_RTS_str = struct.pack('I',TIOCM_RTS) TIOCM_DTR_str = struct.pack('I',TIOCM_DTR) portNotOpenError = ValueError('port not open') class Port: """ An object wrapper for Posix serial ports """ def __init__(self,path=None,noinit=False): self.fd = None if path: self.open(path,noinit) def __tcsetattr(self): termios.tcsetattr(self.fd,TERMIOS.TCSANOW,[self.iflag,self.oflag,self.cflag,self.lflag,self.ispeed,self.ospeed,self.cc]) def __tcgetattr(self): self.iflag,self.oflag,self.cflag,self.lflag,self.ispeed,self.ospeed,self.cc = termios.tcgetattr(self.fd) def open(self,path,noinit): if self.fd: self.close() self.path = path self.fd = os.open(path,os.O_RDWR) self.__tcgetattr() if not noinit: self.iflag = 0 self.oflag = 0 self.lflag = 0 self.__tcsetattr() def close(self): if self.fd: os.close(self.fd) self.fd = None def fileno(self): return self.fd; def _write(self,data): if not self.fd: raise portNotOpenError return os.write(self.fd,data) def write(self,data): if not self.fd: raise portNotOpenError t = len(data) d = data while t>0: n = os.write(self.fd,d) d = d[n:] t = t - n def read(self,size=1024,timeout=None): if not self.fd: raise portNotOpenError if timeout is None: return os.read(self.fd,size) else: r,w,e = select.select([self.fd],[],[self.fd],timeout) if r: return os.read(self.fd,size) else: raise "timeout" def baud(self,rate=None): if not self.fd: raise portNotOpenError if not (rate is None): try: b = baudIntToEnum[rate] except: raise ValueError,'invalid baud rate: '+str(rate) self.ispeed = b self.ospeed = b self.__tcsetattr() return baudEnumToInt[self.ispeed] def charLen(self,clen=None): if not self.fd: raise portNotOpenError if not clen is None: self.cflag = self.cflag & ~TERMIOS.CSIZE if clen == 8: self.cflag = self.cflag | TERMIOS.CS8 elif clen == 7: self.cflag = self.cflag | TERMIOS.CS7 elif clen == 6: self.cflag = self.cflag | TERMIOS.CS6 elif clen == 5: self.cflag = self.cflag | TERMIOS.CS5 else: raise ValueError,'invalid char len: '+str(clen) self.__tcsetattr() cs = self.cflag & TERMIOS.CSIZE if cs == TERMIOS.CS8: return 8 elif cs == TERMIOS.CS7: return 7 elif cs == TERMIOS.CS6: return 6 elif cs == TERMIOS.CS5: return 5 else: raise ValueError,'char len invalid' def parity(self,par=None): if not self.fd: raise portNotOpenError if not par is None: self.cflag = self.cflag & ~(TERMIOS.PARENB|TERMIOS.PARODD) if par == 'none': pass elif par == 'even': self.cflag = self.cflag | (TERMIOS.PARENB) elif par == 'odd': self.cflag = self.cflag | (TERMIOS.PARENB|TERMIOS.PARODD) else: raise ValueError,'invalid parity: '+str(par) self.__tcsetattr() if (self.cflag & TERMIOS.PARENB) == 0: return 'none' elif self.cflag & TERMIOS.PARODD: return 'odd' else: return 'even' def xonxoff(self,enable=None): if not self.fd: raise portNotOpenError if not enable is None: if enable: self.iflag = self.iflag | (TERMIOS.IXON|TERMIOS.IXOFF) else: self.iflag = self.iflag & ~(TERMIOS.IXON|TERMIOS.IXOFF) self.__tcsetattr() return (self.iflag & (TERMIOS.IXON|TERMIOS.IXOFF)) == (TERMIOS.IXON|TERMIOS.IXOFF) def rtscts(self,enable=None): if not self.fd: raise portNotOpenError if not enable is None: if enable: self.cflag = self.cflag | TERMIOS.CRTSCTS else: self.cflag = self.cflag & ~TERMIOS.CRTSCTS self.__tcsetattr() return (self.cflag & TERMIOS.CRTSCTS) != 0 def cook(self,enable=None): if not self.fd: raise portNotOpenError if not enable is None: self.iflag = 0 self.oflag = 0 if enable: self.lflag = self.lflag | TERMIOS.ICANON else: self.lflag = self.lflag & ~TERMIOS.ICANON self.__tcsetattr() return (self.lflag & TERMIOS.ICANON) != 0 def echo(self,enable=None): if not self.fd: raise portNotOpenError if not enable is None: self.iflag = 0 self.oflag = 0 if enable: self.lflag = self.lflag | TERMIOS.ECHO else: self.lflag = self.lflag & ~TERMIOS.ECHO self.__tcsetattr() return (self.lflag & TERMIOS.ECHO) != 0 def __handleiflag(self,enable,mask): if not self.fd: raise portNotOpenError if not enable is None: if enable: self.iflag |= mask else: self.iflag &= ~mask self.__tcsetattr() return (self.iflag & mask) != 0 def ignbrk(self,enable=None): return self.__handleiflag(enable,TERMIOS.IGNBRK) def parmrk(self,enable=None): return self.__handleiflag(enable,TERMIOS.PARMRK) def ignpar(self,enable=None): return self.__handleiflag(enable,TERMIOS.IGNPAR) def brkint(self,enable=None): return self.__handleiflag(enable,TERMIOS.BRKINT) def flushInput(self): if not self.fd: raise portNotOpenError termios.tcflush(self.fd,TERMIOS.TCIFLUSH) def flushOutput(self): if not self.fd: raise portNotOpenError termios.tcflush(self.fd,TERMIOS.TCOFLUSH) def flushAll(self): self.flushInput() self.flushOutput() def sendBreak(self,howlong=0): if not self.fd: raise portNotOpenError termios.tcsendbreak(self.fd,howlong) def drainOutput(self): if not self.fd: raise portNotOpenError termios.tcdrain(self.fd) def vmin(self,vm=None): if not self.fd: raise portNotOpenError if not vm is None: if vm<0 or vm>255: raise ValueError,'invalid vmin: '+str(vm) self.cc[TERMIOS.VMIN] = vm self.__tcsetattr() return self.cc[TERMIOS.VMIN] def vtime(self,vt=None): if not self.fd: raise portNotOpenError if not vt is None: if vt<0 or vt>255: raise ValueError,'invalid vtime: '+str(vt) self.cc[TERMIOS.VTIME] = vt self.__tcsetattr() return self.cc[TERMIOS.VTIME] def nonblocking(self): if not self.fd: raise portNotOpenError fcntl.fcntl(self.fd,fcntl.F_SETFL,os.O_NONBLOCK) def txCount(self): s = fcntl.ioctl(self.fd,termios.TIOCOUTQ,TIOCM_zero_str) return struct.unpack('I',s)[0] def rxCount(self): s = fcntl.ioctl(self.fd,termios.TIOCINQ,TIOCM_zero_str) return struct.unpack('I',s)[0] def resetRM(self,value): if value: v = TIOCM_one_str else: v = TIOCM_zero_str fcntl.ioctl(self.fd,0x525005,v) if sys.platform[:5] == 'linux': def DSR(self): if not self.fd: raise portNotOpenError s = fcntl.ioctl(self.fd,TIOCMGET,TIOCM_zero_str) return bool(struct.unpack('I',s)[0] & TIOCM_DSR) def CD(self): if not self.fd: raise portNotOpenError s = fcntl.ioctl(self.fd,TIOCMGET,TIOCM_zero_str) return bool(struct.unpack('I',s)[0] & TIOCM_CD) def RI(self): if not self.fd: raise portNotOpenError s = fcntl.ioctl(self.fd,TIOCMGET,TIOCM_zero_str) return bool(struct.unpack('I',s)[0] & TIOCM_RI) def CTS(self): if not self.fd: raise portNotOpenError s = fcntl.ioctl(self.fd,TIOCMGET,TIOCM_zero_str) return bool(struct.unpack('I',s)[0] & TIOCM_CTS) def DTR(self,on=None): if not self.fd: raise portNotOpenError if not on is None: if on: fcntl.ioctl(self.fd,TIOCMBIS,TIOCM_DTR_str) else: fcntl.ioctl(self.fd,TIOCMBIC,TIOCM_DTR_str) s = fcntl.ioctl(self.fd,TIOCMGET,TIOCM_zero_str) return bool(struct.unpack('I',s)[0] & TIOCM_DTR) def RTS(self,on=None): if not self.fd: raise portNotOpenError if not on is None: if on: fcntl.ioctl(self.fd,TIOCMBIS,TIOCM_RTS_str) else: fcntl.ioctl(self.fd,TIOCMBIC,TIOCM_RTS_str) s = fcntl.ioctl(self.fd,TIOCMGET,TIOCM_zero_str) return bool(struct.unpack('I',s)[0] & TIOCM_RTS) ----------------------------------------------------------------------------- -- Grant Edwards grante Yow! Maybe I should have at asked for my Neutron Bomb visi.com in PAISLEY -- From exarkun at twistedmatrix.com Fri Aug 14 10:40:06 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Fri, 14 Aug 2009 14:40:06 -0000 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: <7eku38F2gtku3U1@mid.uni-berlin.de> <200908141538.15798.hendrik@microcorp.co.za> Message-ID: <20090814144006.11286.1931874476.divmod.xquotient.178@localhost.localdomain> On 02:19 pm, invalid at invalid wrote: >On 2009-08-14, exarkun at twistedmatrix.com >wrote: >>One strategy you might employ to get rid of the busy looping >>is to use Twisted and its serial port support. This also >>addresses the full- duplex issue you've raised. > >There are no such full-dulex issues. There was a perceived issues. Obviously it's possible to do full-duplex with Linux's serial port support (and all the other major platforms too, as far as I know), as long as you know how. :) Twisted makes the how a lot simpler. Jean-Paul From davea at ieee.org Fri Aug 14 10:48:00 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 10:48:00 -0400 Subject: implementing descriptors In-Reply-To: References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: <4A857920.1000008@ieee.org> dippim wrote: > On Aug 14, 2:34 am, Raymond Hettinger wrote: > >> [David] >> >> >> >> >>> I am new to Python and I have a question about descriptors. If I have >>> a class as written below, is there a way to use descriptors to be >>> certain that the datetime in start is always before the one in end? >>> >>> class foo(object): >>> def __init__(self,a =one,b = None) >>> self.start = >>> self.end = >>> >>> from datetime import datetime >>> c =atetime(2009,8,13,6,15,0) >>> d =atetime(2009,8,14,12,0,0) >>> afoo =oo(c,d) >>> >>> For instance, if the following code were run, I would like to instance >>> of foo to switch the start and end times. >>> >>> afoo.start =atetime(2010,8,13,6,15,0) >>> >>> I was thinking of using the __set__ descriptor to catch the assignment >>> and reverse the values if necessary, but I can't figure out how to >>> determine which values is being set. >>> >> You're on the right track, but it is easier to use property() than to >> write your own custom descriptor with __get__ and __set__. >> >> class foo(object): >> def __init__(self,a =one,b = None): >> self._start = >> self._end = >> def get_start(self): >> return self._start >> def set_start(self, value): >> if self._end is None or value < self._end: >> self._start =alue >> else: >> self._end =alue >> start =roperty(get_start, set_start) >> def get_end(self): >> return self._end >> def set_end(self, value): >> if self._start is None or value > self._start: >> self._end =alue >> else: >> self._start =alue >> end =roperty(get_end, set_end) >> >> Raymond >> > > Raymond, > This functionality is exactly what I was looking for. Thanks! I'll > be using this to solve my problem. > > Now that I'm on the right track, I'm still a bit confused about how > __get__ and __set__ are useful. Admittedly, I don't need to > understand them to solve this problem, but perhaps they may be useful > in the future. If I wanted to solve this problem using __get__ and > __set__ could it be done? > > Thanks Again! > > DANGER- WILL ROBINSON! Don't use this code as-is. There is a nasty surprise waiting for the caller when he sets start and end, and discovers that one of them gets thrown out, and an old value still remains. obj= foo(3, 5) obj.start = 8 obj.end = 12 print obj.start, obj.end will print out 3, 12. Not what the caller expected. Four fixes, in order of preference: 0) Trust your user to read and obey your docstrings. This was what JM was implying, by changing the names of the formal parameters. 1) make a new method that sets both values, making these two properties readonly. That new method would make sure the two parameters are self-consistent. Making the actual values readonly can be done with a descriptor as well, or even a decorator. 2) Raise an exception in the getter methods if they're out of order 3) do the min/max logic on the getter methods, but I don't like that one at all. DaveA From jeanmichel at sequans.com Fri Aug 14 10:49:47 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 16:49:47 +0200 Subject: callable virtual method Message-ID: <4A85798B.6020501@sequans.com> Hi fellows, Does anyone know a way to write virtual methods (in one virtual class) that will raise an exception only if called without being overridden ? Currently in the virtual method I'm checking that the class of the instance calling the method has defined that method as well. Example: class Stream(object): """Interface of all stream objects""" def resetStats(self): """Reset the stream statistics. All values a zeroed except the date.""" _log.info('Reset statistics of %s' % self) if self.__class__.resetStats == Stream.resetStats: raise NotImplementedError() It works but it's tedious, I have to add these 2 lines to every virtual method, changing the content of the 2 lines. Maybe there is a nice/builtin way to do so (python 2.4) JM From davea at ieee.org Fri Aug 14 10:53:35 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 10:53:35 -0400 Subject: coding for multiple versions of python In-Reply-To: References: <4A84F913.9090901@v.loewis.de> Message-ID: <4A857A6F.5010401@ieee.org> Grant Edwards wrote: > On 2009-08-14, Martin v. L?wis wrote: > > >>> I'm guessing I need to configure cvs to copy files to both >>> locations whenever I commit. Does that sound right? Is there a >>> better way I'm not thinking of? >>> > > Just use one set of source files. > > >> If the set of files doesn't change too often, you can use symlinks. >> That's how Debian currently installs Python packages for multiple >> versions on a single system. >> >> Specifically, put the source code into /net/source/python/foo/*.py. >> Then, on each system, put symlinks to all .py files into >> lib/site-packages/foo. Then Python will place the .pyc files next >> to the symlinks, not next to the actual .py files. >> > > Why would he need two sets of .py files? > > I can't speak for Martin, but his description doesn't have two sets of .py files, but two sets of symlinks pointing to the same .py files. It's the .pyc files that exist in two forms, since those are version dependent. He's assuming: 1) an OS that supports symlinks 2) two versions of Python on same system 3) one set of pure-python sources that want to stay in synch for both versions. From Scott.Daniels at Acm.Org Fri Aug 14 11:04:26 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Fri, 14 Aug 2009 08:04:26 -0700 Subject: Format Code Repeat Counts? In-Reply-To: References: Message-ID: <8YGdnWA4YPxq5xjXnZ2dnUVZ_hti4p2d@pdx.net> MRAB wrote: > Scott David Daniels wrote: >> MRAB wrote: >>> The shortest I can come up with is: >>> "[" + "][".join(letters) + "]" >> >> Maybe a golf shot: >> "][".join(letters).join("[]") >> > Even shorter: > > "["+"][".join(letters)+"]" > > :-) I was going by PEP8 rules. ;-) --Scott David Daniels Scott David Daniels at Acm.Org From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 11:24:42 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 15:24:42 GMT Subject: trouble with reload References: <24956946.post@talk.nabble.com> Message-ID: <02957215$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 09:23:17 -0400, Colin J. Williams wrote: > It's typically a user module that needs to be reloaded. What's a user module? > It seems that del sys.modules['moduleName'] has no effect. sys.modules is just a dictionary, I find it hard to believe that deleting from it has no effect. It works for me: >>> import sys >>> import math >>> 'math' in sys.modules True >>> del sys.modules['math'] >>> 'math' in sys.modules False What behaviour do you get? Of course deleting the math module from the cache doesn't do anything to the math module in your namespace: >>> math >>> del math >>> math Traceback (most recent call last): File "", line 1, in NameError: name 'math' is not defined Of course deleting the module (or reloading it) doesn't have any effect on any objects you already have: >>> import math >>> func = math.sin >>> del sys.modules['math'] >>> del math >>> math.sin(1.2) Traceback (most recent call last): File "", line 1, in NameError: name 'math' is not defined >>> func(1.2) 0.93203908596722629 > Is there some other way of ensuring that any import goes to > moduleName.py, instead of moduleName.pyc? Delete moduleName.pyc. Make sure the .pyc file doesn't exist in the first place. Make sure the last modification date of the .py file is newer than the modification date of the .pyc file. -- Steven From charles at declareSub.com Fri Aug 14 11:26:09 2009 From: charles at declareSub.com (Charles Yeomans) Date: Fri, 14 Aug 2009 11:26:09 -0400 Subject: Programming by Contract In-Reply-To: References: <4A7A15CD.9090306@stoneleaf.us> <4A81C6B8.7010605@stoneleaf.us> Message-ID: On Aug 14, 2009, at 12:09 AM, Scott David Daniels wrote: > Charles Yeomans wrote: >> On Aug 11, 2009, at 3:30 PM, Ethan Furman wrote: >>> Ethan Furman wrote: >>>> Greetings! >>>> I have seen posts about the assert statement and PbC (or maybe it >>>> was DbC), and I just took a very brief look at pycontract (http://www.wayforward.net/pycontract/ >>>> ) and now I have at least one question: Is this basically >>>> another way of thinking about unit testing, or is the idea of PbC >>>> more along the lines of *always* checking the input/output of >>>> functions to ensure they are correct? (*Contstant vigilance!* as >>>> Prof Moody would say ;) >>>> I know asserts can be turned off, so they obviously won't work >>>> for the latter case, and having seen the sample of pycontract it >>>> seems it only does its thing during debugging. >>>> So is Design (Programming) by Contract a fancy way of saying >>>> "Document your inputs/outputs!" or is there more to it? >>>> ~Ethan~ >>> >>> Hmmm... >>> >>> Well, from the (apparently) complete lack of interest, I shall >>> take away the (better?) documentation ideas and unit testing >>> ideas, and not worry about the rest. :) >>> >>> >> Design by contract is complementary to unit testing (I notice that >> the author of PEP 316 appears confused about this). DbC is, >> roughly speaking, about explicit allocation of responsibility. >> Consider this contrived example. >> def foo(s): >> require(s is not None) >> //code >> ensure(hasattr(returnValue, '__iter__')) > > yo might want two flags, REQUIRE_OFF, and ENSURE_ON that control > testing, and change the code above to: > require(REQUIRE_OFF or s is not None) > //code > ensure(ENSURE_OFF or hasattr(returnValue, '__iter__')) > > Python has no good way to turn off argument calculation by > manipulating function definition (at least that I know of). > For this purpose, it had occurred to me to do something like the following. def require(condition): if condition: return True else: raise PreconditionFailure def foo(s): assert require(s is not None) Then it occurred to me to actually read the assert documentation, where I learned that one can pass a second expression to assert. So instead one might write assert precondition, "PreconditionFailure" though I think I prefer the former. Charles Yeomans -------------- next part -------------- An HTML attachment was scrubbed... URL: From david.mcwright at usbfmi.com Fri Aug 14 11:39:25 2009 From: david.mcwright at usbfmi.com (dippim) Date: Fri, 14 Aug 2009 08:39:25 -0700 (PDT) Subject: implementing descriptors References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: On Aug 14, 10:48?am, Dave Angel wrote: > dippim wrote: > > On Aug 14, 2:34 am, Raymond Hettinger wrote: > > >> [David] > > >>> I am new to Python and I have a question about descriptors. ?If I have > >>> a class as written below, is there a way to use descriptors to be > >>> certain that the datetime in start is always before the one in end? > > >>> class foo(object): > >>> ? ?def __init__(self,a =one,b = None) > >>> ? ? ? self.start = > >>> ? ? ? self.end = > > >>> from datetime import datetime > >>> c =atetime(2009,8,13,6,15,0) > >>> d =atetime(2009,8,14,12,0,0) > >>> afoo =oo(c,d) > > >>> For instance, if the following code were run, I would like to instance > >>> of foo to switch the start and end times. > > >>> afoo.start =atetime(2010,8,13,6,15,0) > > >>> I was thinking of using the __set__ descriptor to catch the assignment > >>> and reverse the values if necessary, but I can't figure out how to > >>> determine which values is being set. > > >> You're on the right track, but it is easier to use property() than to > >> write your own custom descriptor with __get__ and __set__. > > >> class foo(object): > >> ? ? def __init__(self,a =one,b = None): > >> ? ? ? ? self._start = > >> ? ? ? ? self._end = > >> ? ? def get_start(self): > >> ? ? ? ? return self._start > >> ? ? def set_start(self, value): > >> ? ? ? ? if self._end is None or value < self._end: > >> ? ? ? ? ? ? self._start =alue > >> ? ? ? ? else: > >> ? ? ? ? ? ? self._end =alue > >> ? ? start =roperty(get_start, set_start) > >> ? ? def get_end(self): > >> ? ? ? ? return self._end > >> ? ? def set_end(self, value): > >> ? ? ? ? if self._start is None or value > self._start: > >> ? ? ? ? ? ? self._end =alue > >> ? ? ? ? else: > >> ? ? ? ? ? ? self._start =alue > >> ? ? end =roperty(get_end, set_end) > > >> Raymond > > > Raymond, > > ? ?This functionality is exactly what I was looking for. Thanks! ?I'll > > be using this to solve my problem. > > > ? ?Now that I'm on the right track, I'm still a bit confused about how > > __get__ and __set__ are useful. ?Admittedly, I don't need to > > understand them to solve this problem, but perhaps they may be useful > > in the future. ?If I wanted to solve this problem using __get__ and > > __set__ could it be done? > > > Thanks Again! > > DANGER- WILL ROBINSON! > > Don't use this code as-is. ?There is a nasty surprise waiting for the > caller when he sets start and end, and discovers that one of them gets > thrown out, and an old value still remains. > > obj= foo(3, 5) > obj.start = 8 > obj.end = 12 > print obj.start, obj.end > > will print out ?3, 12. ? ?Not what the caller expected. You're right about this and I appreciate the warning, but I think what Raymond was going for was directional accuracy without a great deal of his time wasted on details. The explanation served the purpose of moving me forward using property() and I'm thankful for it. > > Four fixes, in order of preference: > 0) Trust your user to read and obey your docstrings. ?This was what JM > was implying, by changing the names of the formal parameters. Considering I am not the sharpest knife in the drawer, I don't wish to start a philosophical discussion about the relative aptitude and capabilities of the people who might use a class I build. However, I will say that as this particular requirement is imposed on this class by the writer, shouldn't it be the writer's responsibility to enforce it, especially, when the cost of enforcement is so low? > 1) ?make a new method that sets both values, making these two properties > readonly. ?That new method would make sure the two parameters are > self-consistent. ?Making the actual values readonly can be done with a > descriptor as well, or even a decorator. > 2) Raise an exception in the getter methods if they're out of order > 3) do the min/max logic on the getter methods, but I don't like that one > at all. > > DaveA From david.mcwright at usbfmi.com Fri Aug 14 11:41:28 2009 From: david.mcwright at usbfmi.com (dippim) Date: Fri, 14 Aug 2009 08:41:28 -0700 (PDT) Subject: implementing descriptors References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> On Aug 14, 10:48?am, Dave Angel wrote: > dippim wrote: > > On Aug 14, 2:34 am, Raymond Hettinger wrote: > > >> [David] > > >>> I am new to Python and I have a question about descriptors. ?If I have > >>> a class as written below, is there a way to use descriptors to be > >>> certain that the datetime in start is always before the one in end? > > >>> class foo(object): > >>> ? ?def __init__(self,a =one,b = None) > >>> ? ? ? self.start = > >>> ? ? ? self.end = > > >>> from datetime import datetime > >>> c =atetime(2009,8,13,6,15,0) > >>> d =atetime(2009,8,14,12,0,0) > >>> afoo =oo(c,d) > > >>> For instance, if the following code were run, I would like to instance > >>> of foo to switch the start and end times. > > >>> afoo.start =atetime(2010,8,13,6,15,0) > > >>> I was thinking of using the __set__ descriptor to catch the assignment > >>> and reverse the values if necessary, but I can't figure out how to > >>> determine which values is being set. > > >> You're on the right track, but it is easier to use property() than to > >> write your own custom descriptor with __get__ and __set__. > > >> class foo(object): > >> ? ? def __init__(self,a =one,b = None): > >> ? ? ? ? self._start = > >> ? ? ? ? self._end = > >> ? ? def get_start(self): > >> ? ? ? ? return self._start > >> ? ? def set_start(self, value): > >> ? ? ? ? if self._end is None or value < self._end: > >> ? ? ? ? ? ? self._start =alue > >> ? ? ? ? else: > >> ? ? ? ? ? ? self._end =alue > >> ? ? start =roperty(get_start, set_start) > >> ? ? def get_end(self): > >> ? ? ? ? return self._end > >> ? ? def set_end(self, value): > >> ? ? ? ? if self._start is None or value > self._start: > >> ? ? ? ? ? ? self._end =alue > >> ? ? ? ? else: > >> ? ? ? ? ? ? self._start =alue > >> ? ? end =roperty(get_end, set_end) > > >> Raymond > > > Raymond, > > ? ?This functionality is exactly what I was looking for. Thanks! ?I'll > > be using this to solve my problem. > > > ? ?Now that I'm on the right track, I'm still a bit confused about how > > __get__ and __set__ are useful. ?Admittedly, I don't need to > > understand them to solve this problem, but perhaps they may be useful > > in the future. ?If I wanted to solve this problem using __get__ and > > __set__ could it be done? > > > Thanks Again! > > DANGER- WILL ROBINSON! > > Don't use this code as-is. ?There is a nasty surprise waiting for the > caller when he sets start and end, and discovers that one of them gets > thrown out, and an old value still remains. > > obj= foo(3, 5) > obj.start = 8 > obj.end = 12 > print obj.start, obj.end > > will print out ?3, 12. ? ?Not what the caller expected. You're right about this and I appreciate the warning, but I think what Raymond was going for was directional accuracy without a great deal of his time wasted on details. The explanation served the purpose of moving me forward using property() and I'm thankful for it. > > Four fixes, in order of preference: > 0) Trust your user to read and obey your docstrings. ?This was what JM > was implying, by changing the names of the formal parameters. Considering I am not the sharpest knife in the drawer, I don't wish to start a philosophical discussion about the relative aptitude and capabilities of the people who might use a class I build. However, I will say that as this particular requirement is imposed on this class by the writer, shouldn't it be the writer's responsibility to enforce it, especially, when the cost of enforcement is so low? > 1) ?make a new method that sets both values, making these two properties > readonly. ?That new method would make sure the two parameters are > self-consistent. ?Making the actual values readonly can be done with a > descriptor as well, or even a decorator. > 2) Raise an exception in the getter methods if they're out of order > 3) do the min/max logic on the getter methods, but I don't like that one > at all. > > DaveA From python at mrabarnett.plus.com Fri Aug 14 11:49:52 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 16:49:52 +0100 Subject: callable virtual method In-Reply-To: <4A85798B.6020501@sequans.com> References: <4A85798B.6020501@sequans.com> Message-ID: <4A8587A0.6040008@mrabarnett.plus.com> Jean-Michel Pichavant wrote: > Hi fellows, > > Does anyone know a way to write virtual methods (in one virtual class) > that will raise an exception only if called without being overridden ? > Currently in the virtual method I'm checking that the class of the > instance calling the method has defined that method as well. > > Example: > > class Stream(object): > """Interface of all stream objects""" > def resetStats(self): > """Reset the stream statistics. All values a zeroed except the > date.""" > _log.info('Reset statistics of %s' % self) > if self.__class__.resetStats == Stream.resetStats: > raise NotImplementedError() > > It works but it's tedious, I have to add these 2 lines to every virtual > method, changing the content of the 2 lines. > > Maybe there is a nice/builtin way to do so (python 2.4) > Why are you checking which class it's in? The method in the base class will be called only if it hasn't been overridden in the subclass. From deets at nospam.web.de Fri Aug 14 11:50:47 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 17:50:47 +0200 Subject: callable virtual method In-Reply-To: References: Message-ID: <7elfenF2gmdggU1@mid.uni-berlin.de> Jean-Michel Pichavant schrieb: > Hi fellows, > > Does anyone know a way to write virtual methods (in one virtual class) > that will raise an exception only if called without being overridden ? > Currently in the virtual method I'm checking that the class of the > instance calling the method has defined that method as well. > > Example: > > class Stream(object): > """Interface of all stream objects""" > def resetStats(self): > """Reset the stream statistics. All values a zeroed except the > date.""" > _log.info('Reset statistics of %s' % self) > if self.__class__.resetStats == Stream.resetStats: > raise NotImplementedError() > > It works but it's tedious, I have to add these 2 lines to every virtual > method, changing the content of the 2 lines. > > Maybe there is a nice/builtin way to do so (python 2.4) Python has no concept of "virtual" methods. A simple class Stream(object): def resetStats(self): raise NotImplemented is all you need. Once a subclass overrides resetStats, that implementatino is used. Additionally, there are modules such as zope.interface out there, that let you define more formally what an interface is, and declare who's implementing it. I don't used this myself though, so I can't really comment to which extend it e.g. warns you if you subclass *without* implementing. Diez From alan.isaac at gmail.com Fri Aug 14 11:54:54 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Fri, 14 Aug 2009 15:54:54 GMT Subject: retrieve item from nested list given index tuple Message-ID: `lst` is a nested list `tpl` is the indexes for an item in the list What is the nice way to retrieve the item? (Speedy access is nice.) I don't want to use NumPy, but I'd like somehow to avoid an explicit loop. I did consider using eval. E.g., eval('lst' + '[%d]'*len(tpl)%tpl). It works but seems rather ugly. I kind of like reduce(list.__getitem__, tpl, lst) but the reliance on reduce remains controversial enough to see i removed from the Python 3 built-ins ... Thanks, Alan Isaac From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 11:56:27 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 15:56:27 GMT Subject: callable virtual method References: Message-ID: <02957986$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 16:49:47 +0200, Jean-Michel Pichavant wrote: > Hi fellows, > > Does anyone know a way to write virtual methods (in one virtual class) > that will raise an exception only if called without being overridden ? > Currently in the virtual method I'm checking that the class of the > instance calling the method has defined that method as well. I'm not entirely sure of the terminology -- is this the same as an abstract base class? Googling has not enlightened me. Given your example, it seems to be. > Example: > > class Stream(object): > """Interface of all stream objects""" > def resetStats(self): > """Reset the stream statistics. All values a zeroed except the > date.""" > _log.info('Reset statistics of %s' % self) > if self.__class__.resetStats == Stream.resetStats: > raise NotImplementedError() The usual idiom I've seen for abstract methods is to simplify the check, and to put it *before* any work is done: class Stream(object): """Interface of all stream objects""" def resetStats(self): if self.__class__ is Stream: raise NotImplementedError() _log.info('Reset statistics of %s' % self) Even simpler is to just put the check in __init__, so to prevent the caller from creating an instance of the class: class AbstractStream(object): def __init__(self): if self.__class__ is Stream: raise NotImplementedError('abstract class') def resetStats(self): # This does not need to be over-ridden. _log.info('Reset statistics of %s' % self) def whatever(self): # This *must* be over-ridden, and *cannot* be called raise NotImplementedError('abstract method') If you have a lot of methods, you can probably reduce the boilerplate with decorators: # Untested from functools import wraps def abstract(func): # Abstract methods don't have to be over-ridden, so long as they # are called from a subclass of the abstract class. @functools.wraps(func) def inner(self, *args, **kwargs): if self.__class__ is Stream: raise NotImplementedError() return func(self, *args, **kwargs) return inner def virtual(func): # Virtual methods must be over-ridden, and must not be called by # inheritance. @functools.wraps(func) def inner(self, *args, **kwargs): raise NotImplementedError() return inner class Stream(object): @abstract def __init__(self): pass def resetStats(self): _log.info('Reset statistics of %s' % self) @virtual def whatever(self): pass -- Steven From maymunbeyin at gmail.com Fri Aug 14 12:03:27 2009 From: maymunbeyin at gmail.com (kk) Date: Fri, 14 Aug 2009 09:03:27 -0700 (PDT) Subject: Why does my ftp script quit after couple of hours? Message-ID: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> Hi This way the first time I did something with ftp stuff. I think that generally it works but it stops working(quits or disappears) after couple of hours of running. This was a personal test-trial script for my own needs which was to get my dynamic ip and broadcast to a client(I have a client script on another computer). I sure could use something like DynDns for the same purpose with easier management but I just wanted to give it a try to see if i could even make it work . Basically this script parses my ip from DynDns ip check page and uploads it to the given ftp site. It works fine initially, it does upload, it updates the Ip every hour but the problem is that after couple of hours the Python console window disappears, I assume it crashes. I know it does upload at least couple times(works for couple hours). it might be something to do with ftp connection. I will investigate that but I just wanted to see if I have any logic or some kind of contextual problem in the script. Here is the link to Pastie page http://pastie.org/584152 Thanks From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 12:11:52 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 16:11:52 GMT Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> Message-ID: <02957d23$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: > "I saw `cout' being shifted "Hello world" times to the left and stopped > right there." --Steve Gonedes Assuming that's something real, and not invented for humour, I presume that's describing something possible in C++. Am I correct? What the hell would it actually do??? -- Steven From invalid at invalid Fri Aug 14 12:17:36 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 11:17:36 -0500 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: On 2009-08-14, Steven D'Aprano wrote: > On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: > >> "I saw `cout' being shifted "Hello world" times to the left and stopped >> right there." --Steve Gonedes > > Assuming that's something real, and not invented for humour, I presume > that's describing something possible in C++. Am I correct? Yes. In C++, the "<<" operator is overloaded. Judging by the context in which I've seen it used, it does something like write strings to a stream. > What the hell > would it actually do??? IIRC in C++, cout << "Hello world"; is equivalent to this in C: printf("Hellow world"); or this in Python: print "hellow world" -- Grant Edwards grante Yow! Bo Derek ruined at my life! visi.com From deets at nospam.web.de Fri Aug 14 12:17:57 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 18:17:57 +0200 Subject: Why does my ftp script quit after couple of hours? In-Reply-To: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> References: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> Message-ID: <7elh1lF2h1rl0U1@mid.uni-berlin.de> kk schrieb: > Hi > This way the first time I did something with ftp stuff. I think that > generally it works but it stops working(quits or disappears) after > couple of hours of running. > > This was a personal test-trial script for my own needs which was to > get my dynamic ip and broadcast to a client(I have a client script on > another computer). I sure could use something like DynDns for the same > purpose with easier management but I just wanted to give it a try to > see if i could even make it work . > > Basically this script parses my ip from DynDns ip check page and > uploads it to the given ftp site. It works fine initially, it does > upload, it updates the Ip every hour but the problem is that after > couple of hours the Python console window disappears, I assume it > crashes. I know it does upload at least couple times(works for couple > hours). it might be something to do with ftp connection. I will > investigate that but I just wanted to see if I have any logic or some > kind of contextual problem in the script. > > > Here is the link to Pastie page > http://pastie.org/584152 The code isn't very robust if anything happens retrieving the IP-website - if for some reason the connection is broken, it won't catch any ensuing IO-exception. Also your way of extracing the IP is rather awkward, a simple re (often not the right tool, but here certainl yes) would help: >>> m = re.search(r"(([0-9]+\.){3}[0-9]+)", body) >>> m.group(1) '85.177.92.101' >>> Diez From maymunbeyin at gmail.com Fri Aug 14 12:25:50 2009 From: maymunbeyin at gmail.com (kk) Date: Fri, 14 Aug 2009 09:25:50 -0700 (PDT) Subject: Why does my ftp script quit after couple of hours? References: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> <7elh1lF2h1rl0U1@mid.uni-berlin.de> Message-ID: <337951bf-4d0d-4dde-95de-8e6d7d68a7f5@a13g2000yqc.googlegroups.com> Hi Diez Thanks for your insight. The reason I chose the awkward method to parse the ip digits is that I was not familiar with the regex module and the Dyndns Ip page is pretty simple page. I guess it is time to learn more about the Re module. As far as robustness, I agree with your assestment. I guess my main confusion with my result is that the console window just disappears. I wonder if I can make the window stay even if it crashesor if there are connection issues? I will createa seperate log file to see if I can catch any issues in a log file. From bieffe62 at gmail.com Fri Aug 14 12:27:30 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Fri, 14 Aug 2009 09:27:30 -0700 (PDT) Subject: Why does my ftp script quit after couple of hours? References: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> Message-ID: <84991768-4ab5-45fa-8e99-c8910280c81f@d32g2000yqh.googlegroups.com> On 14 Ago, 18:03, kk wrote: > Hi > This way the first time I did something with ftp stuff. I think that > generally it works but it stops working(quits or disappears) after > couple of hours of running. > > This was a personal test-trial script for my own needs which was to > get my dynamic ip and broadcast to a client(I have a client script on > another computer). I sure could use something like DynDns for the same > purpose with easier management but I just wanted to give it a try to > see if i could even make it work . > > Basically this script parses my ip from DynDns ip check page and > uploads it to the given ftp site. It works fine initially, it does > upload, it updates the Ip every hour but the problem is that after > couple of hours the Python console window disappears, I assume it > crashes. ?I know it does upload at least couple times(works for couple > hours). it might be something to do with ftp connection. I will > investigate that but I just wanted to see if I have any logic or some > kind of contextual problem in the script. > > Here is the link to Pastie pagehttp://pastie.org/584152 > > Thanks Try catching the exception inside the main loop, to prevent your program to exit in case of failure: if __name__=='__main__': while True: try: writeExtFile(FILE_PATH,FILE_NAME) uploadFile (FTP_NAME,FTP_USER_NAME,FTP_PASSWD,FTP_FOLDER,FILE_NAME) time.sleep(TIME_DELAY) except: err, det, tb = sys.exc_info() print "ERROR =>", err, det # gives you a description of the occurred failure traceback.print_tb(tb) # this might be needed only for debug Ciao ---- FB From wasala at gmail.com Fri Aug 14 12:28:34 2009 From: wasala at gmail.com (Asanka Wasala) Date: Fri, 14 Aug 2009 09:28:34 -0700 (PDT) Subject: Python Permutations Problem Message-ID: Hi I am developing a spell checker for my language, and I came across solving an interesing problem. It would be great if you can suggest me an optimized solution for the problem described below: I have certain group of letters like these: Group #1: c,r,b Group #2: a,z,k Group #3: h,t . . Letters within the same group can be substituted/replaced with the rest of the letters in that group. (ie. Group #1 means letter 'c' can be replaced with either 'r' or 'b', and letter r can be replaced with either c or b, and letter b can be replaced with either r or c) A group can have upto 3 letters, and letters do not overlap between groups. There can be upto 25 such groups. Given a word containing above letters, (e.g. 'cat'.) I want to generate all possible words by subsituting letters in the groups. eg. expected output: cat rat bat czt rzt bzt ckt rkt bkt cah rah bah czh rzh bzh ckh rkh bkh My code is given below. But for complex words like 'cccccccccczzk' it thows the 'maximum recursion depth exceeded' error. Therefore, can you suggest me an optimized solution to achive the above task? Thanks in advance. -------------------------- CODE------------------------------------------- #-*- coding: UTF-8 -*- import re def getPermutations(word): def getSimilarLetters(letter): pattern=u"|c,r,b|a,z,k|h,t|" list=[] ptrn=re.compile("(?P\|(.?,)*?"+letter+"(,.)*?\|)") k=ptrn.search(pattern) if k: letterlist=k.group("grp")[1:-1] list=letterlist.split(",") list.remove(letter) return list else: return letter list=[] def perm(word): posi=0 wrd=word for w in word: posi=posi+1 lst=getSimilarLetters(w) if len(lst)>0: for l in lst: newwrd=wrd[:posi-1]+l+wrd[posi:] if not (newwrd in list): list.append(newwrd) perm(newwrd) try: perm(word) except RuntimeError: list=[] list.append("error") return list list=getPermutations(u"cat") for i in list: print i.encode('utf-8') --------------------------------------------END of CODE----------------------------------------------------------------------------- From prateekkakirwar at gmail.com Fri Aug 14 12:31:43 2009 From: prateekkakirwar at gmail.com (Prateek) Date: Fri, 14 Aug 2009 09:31:43 -0700 (PDT) Subject: Natural Language Processing in Python Message-ID: Hi, Can somebody please provide me link to a good online resource or e- book for doing natural language processing programming in Python. Thanks, Prateek From deets at nospam.web.de Fri Aug 14 12:38:12 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 18:38:12 +0200 Subject: Why does my ftp script quit after couple of hours? In-Reply-To: <337951bf-4d0d-4dde-95de-8e6d7d68a7f5@a13g2000yqc.googlegroups.com> References: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> <7elh1lF2h1rl0U1@mid.uni-berlin.de> <337951bf-4d0d-4dde-95de-8e6d7d68a7f5@a13g2000yqc.googlegroups.com> Message-ID: <7eli7kF2gdbanU2@mid.uni-berlin.de> kk schrieb: > Hi Diez > > Thanks for your insight. The reason I chose the awkward method to > parse the ip digits is that I was not familiar with the regex module > and the Dyndns Ip page is pretty simple page. I guess it is time to > learn more about the Re module. > > As far as robustness, I agree with your assestment. I guess my main > confusion with my result is that the console window just disappears. I > wonder if I can make the window stay even if it crashesor if there are > connection issues? I will createa seperate log file to see if I can > catch any issues in a log file. I'm not a Windows-user, but even there it should be possible to *first* open the console, and then start the script in it. That will keep it open & you can see the stacktrace. Diez From tim.arnold at sas.com Fri Aug 14 12:39:10 2009 From: tim.arnold at sas.com (Tim Arnold) Date: Fri, 14 Aug 2009 12:39:10 -0400 Subject: coding for multiple versions of python References: Message-ID: "Tim Arnold" wrote in message news:h61gld$it2$1 at foggy.unx.sas.com... > Hi, > I've got a python based system that has to run on hp unix and red hat > linux. The Python version on the HP is 2.4 and the version on the Linux > box is 2.6. There's nothing I can do about that. > > I think that means I must have two different libraries since the pyc files > are not cross-version compatible. No problem for the libs like PIL or > lxml. But for the part of the system I actually code every day, I'd rather > not do dual maintenance, having two copies of my code for each > platform/version. > > I'm guessing I need to configure cvs to copy files to both locations > whenever I commit. Does that sound right? Is there a better way I'm not > thinking of? > > thanks, > --Tim > Thanks everyone. I assumed wrongly that I would run into problems if a pyc file generated for 2.4 was available when 2.6 was running the code. I see now that if the pyc is incompatible, python falls back to the py file. Makes sense, I was trying to solve a problem I didn't actually have. On the other hand, Martin's solution looks great for this situation. I'll keep my single set of python files and link to them from the different platform/python version dirs, so I can still get the optimization of the pyc files. I really love this group. thanks again, --Tim Arnold From python at mrabarnett.plus.com Fri Aug 14 12:40:04 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 17:40:04 +0100 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A859364.3060203@mrabarnett.plus.com> Grant Edwards wrote: > On 2009-08-14, Steven D'Aprano wrote: >> On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: >> >>> "I saw `cout' being shifted "Hello world" times to the left and stopped >>> right there." --Steve Gonedes >> Assuming that's something real, and not invented for humour, I presume >> that's describing something possible in C++. Am I correct? > > Yes. In C++, the "<<" operator is overloaded. Judging by the > context in which I've seen it used, it does something like > write strings to a stream. > >> What the hell >> would it actually do??? > > IIRC in C++, > > cout << "Hello world"; > It also returns cout, so you can chain them: cout << "Hello, " << name << '\n'; > is equivalent to this in C: > > printf("Hellow world"); > > or this in Python: > > print "hellow world" > From maymunbeyin at gmail.com Fri Aug 14 12:40:08 2009 From: maymunbeyin at gmail.com (kk) Date: Fri, 14 Aug 2009 09:40:08 -0700 (PDT) Subject: Why does my ftp script quit after couple of hours? References: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> <7elh1lF2h1rl0U1@mid.uni-berlin.de> <337951bf-4d0d-4dde-95de-8e6d7d68a7f5@a13g2000yqc.googlegroups.com> <7eli7kF2gdbanU2@mid.uni-berlin.de> Message-ID: <0b60c6a7-d950-4c3c-890d-908bb25b239b@w41g2000yqb.googlegroups.com> Awesome stuff, thank you so much for all the help. The Pcomp.lang.python is the most helpful list I have encountered so far :) From a0046088 at airmail.net Fri Aug 14 12:41:36 2009 From: a0046088 at airmail.net (wwwayne) Date: Fri, 14 Aug 2009 10:41:36 -0600 Subject: Natural Language Processing in Python References: Message-ID: On Fri, 14 Aug 2009 09:31:43 -0700 (PDT), Prateek wrote: >Hi, > >Can somebody please provide me link to a good online resource or e- >book for doing natural language processing programming in Python. > >Thanks, >Prateek http://www.nltk.org/book From darkwater42 at gmail.com Fri Aug 14 12:42:15 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Fri, 14 Aug 2009 09:42:15 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: On Aug 14, 12:17?pm, Grant Edwards wrote: > On 2009-08-14, Steven D'Aprano wrote: > > On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: > >> "I saw `cout' being shifted "Hello world" times to the left and stopped > >> right there." ?--Steve Gonedes > > > Assuming that's something real, and not invented for humour, I presume > > that's describing something possible in C++. Am I correct? > > Yes. ?In C++, the "<<" operator is overloaded. ?Judging by the > context in which I've seen it used, it does something like > write strings to a stream. There's a persistent rumor that it is *this* very "abuse" of overloading that caused Java to avoid operator overloading all together. But then then Java went and used "+" as the string concatenation operator. Go figure! |>ouglas P.S. Overloading "left shift" to mean "output" does indeed seem a bit sketchy, but in 15 years of C++ programming, I've never seen it cause any confusion or bugs. From skiaec04 at gmail.com Fri Aug 14 12:49:21 2009 From: skiaec04 at gmail.com (Alejandro E. Ciniglio) Date: Fri, 14 Aug 2009 12:49:21 -0400 Subject: Natural Language Processing in Python References: Message-ID: nltk is a good start, we used it in my Computational Linguistics course in school. www.nltk.org --Alejandro From jeanmichel at sequans.com Fri Aug 14 12:49:26 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 18:49:26 +0200 Subject: callable virtual method In-Reply-To: <4A8587A0.6040008@mrabarnett.plus.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> Message-ID: <4A859596.50808@sequans.com> MRAB wrote: > Jean-Michel Pichavant wrote: >> Hi fellows, >> >> Does anyone know a way to write virtual methods (in one virtual >> class) that will raise an exception only if called without being >> overridden ? >> Currently in the virtual method I'm checking that the class of the >> instance calling the method has defined that method as well. >> >> Example: >> >> class Stream(object): >> """Interface of all stream objects""" >> def resetStats(self): >> """Reset the stream statistics. All values a zeroed except the >> date.""" >> _log.info('Reset statistics of %s' % self) >> if self.__class__.resetStats == Stream.resetStats: >> raise NotImplementedError() >> >> It works but it's tedious, I have to add these 2 lines to every >> virtual method, changing the content of the 2 lines. >> >> Maybe there is a nice/builtin way to do so (python 2.4) >> > Why are you checking which class it's in? The method in the base class > will be called only if it hasn't been overridden in the subclass. Sorry guys (means guys *and* gals :op ), I realized I've not been able to describe precisely what I want to do. I'd like the base class to be virtual (aka abstract). However it may be abstract but it does not mean it cannot do some usefull stuff. Here is the schema of my abstract methods : class Interface(object): def method(self): # --------------------- # some common stuff executed here # --------------------- print 'hello world' # --------------------- # here shall stand child specific stuff (empty in the interface method) # --------------------- if self.__class__.method == Interface.method: raise NotImplementedError('You should have read the f****** manual ! You must override this method.') class GoodChild(Interface): def method(self): Interface.method(self) # I want to process the cool stuff done my the base Interface # ------------------------ # Specific GoodChild stuff here # ------------------------ print 'I am a good' return 'perfect' class BadChild(Interface): pass #I'm too lazy good = GoodChild() bad = BadChild() good.method() ...hello world ...I am a good bad.method() ...NotImplementedError: You should have read the f****** manual ! You must override this method. The reason I'd like to do so: I'll be providing the Interface, but child classes will be overridden by others. Having a reliable error RTFM feedback is a time saver, for me and the users. I hope I clarified my issue. JM From deets at nospam.web.de Fri Aug 14 12:56:53 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 14 Aug 2009 18:56:53 +0200 Subject: callable virtual method In-Reply-To: References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> Message-ID: <7eljaoF2fnkqgU1@mid.uni-berlin.de> Jean-Michel Pichavant schrieb: > MRAB wrote: >> Jean-Michel Pichavant wrote: >>> Hi fellows, >>> >>> Does anyone know a way to write virtual methods (in one virtual >>> class) that will raise an exception only if called without being >>> overridden ? >>> Currently in the virtual method I'm checking that the class of the >>> instance calling the method has defined that method as well. >>> >>> Example: >>> >>> class Stream(object): >>> """Interface of all stream objects""" >>> def resetStats(self): >>> """Reset the stream statistics. All values a zeroed except the >>> date.""" >>> _log.info('Reset statistics of %s' % self) >>> if self.__class__.resetStats == Stream.resetStats: >>> raise NotImplementedError() >>> >>> It works but it's tedious, I have to add these 2 lines to every >>> virtual method, changing the content of the 2 lines. >>> >>> Maybe there is a nice/builtin way to do so (python 2.4) >>> >> Why are you checking which class it's in? The method in the base class >> will be called only if it hasn't been overridden in the subclass. > > Sorry guys (means guys *and* gals :op ), I realized I've not been able > to describe precisely what I want to do. > I'd like the base class to be virtual (aka abstract). However it may be > abstract but it does not mean it cannot do some usefull stuff. > > > Here is the schema of my abstract methods : > > class Interface(object): > def method(self): > # --------------------- > # some common stuff executed here > # --------------------- > print 'hello world' > # --------------------- > # here shall stand child specific stuff (empty in the interface > method) > # --------------------- > if self.__class__.method == Interface.method: > raise NotImplementedError('You should have read the f****** > manual ! You must override this method.') > > class GoodChild(Interface): > def method(self): > Interface.method(self) # I want to process the cool stuff done my > the base Interface > # ------------------------ > # Specific GoodChild stuff here > # ------------------------ > print 'I am a good' > return 'perfect' > > class BadChild(Interface): > pass #I'm too lazy > > > good = GoodChild() > bad = BadChild() > > good.method() > ...hello world > ...I am a good > > bad.method() > ...NotImplementedError: You should have read the f****** manual ! You > must override this method. > > > The reason I'd like to do so: I'll be providing the Interface, but child > classes will be overridden by others. Having a reliable error RTFM > feedback is a time saver, for me and the users. > I hope I clarified my issue. First of all, I doubt the above code really yields that output. You are missing a super-call there in GoodChild And the whole problem goes magically away if you start using OO a bit: class Base(object): def method(self): self._do_some_work_for_method() print "some more work" def _do_some_work_for_method(self): raise NotImplemented So your subclasses must implement something else instead of method - and voila, without any hassle things work as expected. Diez From python at mrabarnett.plus.com Fri Aug 14 12:58:33 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 17:58:33 +0100 Subject: Python Permutations Problem In-Reply-To: References: Message-ID: <4A8597B9.2000002@mrabarnett.plus.com> Asanka Wasala wrote: > Hi > I am developing a spell checker for my language, and I came across > solving an interesing problem. It would be great if you can suggest > me an optimized solution for the problem described below: > > I have certain group of letters like these: > > Group #1: c,r,b > Group #2: a,z,k > Group #3: h,t > . > . > > Letters within the same group can be substituted/replaced with the > rest of the letters in that group. > > (ie. Group #1 means letter 'c' can be replaced with either 'r' or 'b', > and letter r can be replaced with either c or b, and letter b can be > replaced with either r or c) > > A group can have upto 3 letters, and letters do not overlap between > groups. There can be upto 25 such groups. > Given a word containing above letters, (e.g. 'cat'.) I want to > generate all possible words by subsituting letters in the groups. > > eg. expected output: > > cat rat bat > czt rzt bzt > ckt rkt bkt > cah rah bah > czh rzh bzh > ckh rkh bkh > > My code is given below. But for complex words like 'cccccccccczzk' it > thows the 'maximum recursion depth exceeded' error. Therefore, can you > suggest me an optimized solution to achive the above task? Thanks in > advance. > -------------------------- [snip] This uses a generator in order: def get_permutations(word, group_dict): if word: for first in group_dict[word[0]]: for rest in get_permutations(word[1 : ], group_dict): yield first + rest else: yield "" def count_permutations(word, group_dict): if word: total = 1 for letter in word: total *= len(group_dict[letter]) return total else: return 0 group_def = u"crb azk ht" group_dict = {} for group in group_def.split(): for letter in group: group_dict[letter] = group word = u"cat" print "There are %d permutations." % count_permutations(word, group_dict) print for perm in get_permutations(word, group_dict): print perm From lanyjie at yahoo.com Fri Aug 14 13:00:49 2009 From: lanyjie at yahoo.com (Yingjie Lan) Date: Fri, 14 Aug 2009 10:00:49 -0700 (PDT) Subject: [Python-Dev] expy: an expressway to extend Python In-Reply-To: Message-ID: <637900.988.qm@web54204.mail.re2.yahoo.com> --- On Sat, 8/8/09, Stefan Behnel wrote: > From: Stefan Behnel > Subject: Re: [Python-Dev] expy: an expressway to extend Python > To: python-dev at python.org > Date: Saturday, August 8, 2009, 4:55 PM > > More details at http://expy.sourceforge.net/ > > I'm clearly biased, but my main concern here is that expy > requires C code > to be written inside of strings. There isn't any good > editor support for > that, so I doubt that expy is good for anything but very > thin wrappers (as > in the examples you presented). Thanks a lot for the input -- I sort of recaptured the advantages of expy and listed four points in the new introduction at http://expy.sf.net/ homepage. Lacking of editor highlight support is quite a problem, but it is possible to create a support. For example, you can use this to indicate the start of embedded code highlight: return """ and then the end mark is of course the enclosing """ > > That said, you might want to look at the argument unpacking > code generated > by Cython. It's highly optimised through specialisation and > has been > benchmarked quite a bit faster than the generic Python > C-API functions for > tuple/keyword extracting. Since argument conversion seems > to be more or > less all that expy really does, maybe you want to reuse > that code. > > Stefan Oh sure, that's nice if that part can be adopted by expy-cxpy. Any help out on this would be very welcomed. Yingjie From vippstar at gmail.com Fri Aug 14 13:01:57 2009 From: vippstar at gmail.com (vippstar) Date: Fri, 14 Aug 2009 10:01:57 -0700 (PDT) Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: On Aug 14, 4:36?am, Xah Lee wrote: > ? A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode > ?http://xahlee.org/UnixResource_dir/writ/emacs_whitespace-mode_problem... Instead of writing a completely useless article you could had asked for help in an emacs newsgroup, or wait until someone else does that for you too (creating and publishing such configuration you desire). Your article, except for the brief description of that mode, is completely useless. Why would you fill your website with junk? Perhaps because you like to write but you're too lazy to write something of value. From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 13:09:42 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 17:09:42 GMT Subject: retrieve item from nested list given index tuple References: Message-ID: <02958ab2$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 15:54:54 +0000, Alan G Isaac wrote: > `lst` is a nested list > > `tpl` is the indexes for an item in the list > What is the nice way to retrieve the item? (Speedy access is nice.) Assuming you want to do this frequently, write a helper function, then use it: # Untested def extract(nested, indexes): for index in indexes: nested = nested[index] return nested > I don't want to use NumPy, but I'd like somehow to avoid an explicit > loop. I did consider using eval. E.g., eval('lst' + > '[%d]'*len(tpl)%tpl). It works but seems rather ugly. And slow. > I kind of like > reduce(list.__getitem__, tpl, lst) but the reliance on reduce remains > controversial enough to see i removed from the Python 3 built-ins ... It's just moved into functools. >>> lst = ['a', 'b', ['aa', ['aaa', 'bbb', 'ccc'], 'cc']] >>> from functools import reduce >>> lst = ['a', 'b', ['aa', ['aaa', 'bbb', 'ccc'], 'cc']] >>> reduce(list.__getitem__, (2, 1, 0), lst) 'aaa' However, it doesn't work too well as soon as you mix sequence types: >>> reduce(list.__getitem__, (2, 1, 0, 0), lst) Traceback (most recent call last): File "", line 1, in TypeError: descriptor '__getitem__' requires a 'list' object but received a 'str' Try this instead: >>> from operator import getitem >>> reduce(getitem, (2, 1, 0), lst) 'aaa' >>> reduce(getitem, (2, 1, 0, 0), lst) 'a' operator.getitem is less ugly too. -- Steven From chris at simplistix.co.uk Fri Aug 14 13:13:05 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 14 Aug 2009 18:13:05 +0100 Subject: csv.DictWriter.write_header() In-Reply-To: References: <68b9136d-fa0b-42dc-addf-02d338da34cd@z4g2000prh.googlegroups.com> Message-ID: <4A859B21.7020603@simplistix.co.uk> Alan G Isaac wrote: > On 8/13/2009 7:58 AM John Machin apparently wrote: >> Duck typing: ask a silly question, get a silly answer. > > Maybe if you learned to be a more generous reader, > fewer questions would look "silly" to you. If you take a look at the crap that John very patiently wades through on the python-excel group, you might consider that a little light hearted sarcasm isn't much to put up with ;-) FWIW, if you're using csv because you think .xls is too hard to generate, try xlwt :-) cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From cjw at ncf.ca Fri Aug 14 13:14:16 2009 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 14 Aug 2009 13:14:16 -0400 Subject: trouble with reload In-Reply-To: <02957215$0$20647$c3e8da3@news.astraweb.com> References: <24956946.post@talk.nabble.com> <02957215$0$20647$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Fri, 14 Aug 2009 09:23:17 -0400, Colin J. Williams wrote: > >> It's typically a user module that needs to be reloaded. > > What's a user module? A module written by a user, as distinguished from a libary > > >> It seems that del sys.modules['moduleName'] has no effect. > > sys.modules is just a dictionary, I find it hard to believe that deleting > from it has no effect. It works for me: > >>>> import sys >>>> import math >>>> 'math' in sys.modules > True >>>> del sys.modules['math'] >>>> 'math' in sys.modules > False > > What behaviour do you get? > > > Of course deleting the math module from the cache doesn't do anything to > the math module in your namespace: > >>>> math > >>>> del math >>>> math > Traceback (most recent call last): > File "", line 1, in > NameError: name 'math' is not defined > > Of course deleting the module (or reloading it) doesn't have any effect > on any objects you already have: > > >>>> import math >>>> func = math.sin >>>> del sys.modules['math'] >>>> del math >>>> math.sin(1.2) > Traceback (most recent call last): > File "", line 1, in > NameError: name 'math' is not defined >>>> func(1.2) > 0.93203908596722629 > > > > >> Is there some other way of ensuring that any import goes to >> moduleName.py, instead of moduleName.pyc? > > Delete moduleName.pyc. > > Make sure the .pyc file doesn't exist in the first place. > > Make sure the last modification date of the .py file is newer than the > modification date of the .pyc file. That's easier said than done, when one is working with an IDE. The cached .pyc file might be different from that in the file. Colin W. > > > From chris at simplistix.co.uk Fri Aug 14 13:16:26 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 14 Aug 2009 18:16:26 +0100 Subject: httplib incredibly slow :-( In-Reply-To: References: Message-ID: <4A859BEA.9070701@simplistix.co.uk> Aahz wrote: > Sorry, I mostly have been working on our Mac port, so I'm not sure what's > needed to make this work on Windows. Did you try downloading the PyCurl > binary? Maybe it statically links libcurl on Windows. Shame it's not available as a bdist_egg, that's what I'm really after... > What do you need to know for a decent example? Simple download of a file from a url with some auth headers added would do me. Other than that, nice to haves would be how to build a http post with fields in a multi-part body, some of which might be files. cheers, Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From nad at acm.org Fri Aug 14 13:21:16 2009 From: nad at acm.org (Ned Deily) Date: Fri, 14 Aug 2009 10:21:16 -0700 Subject: Natural Language Processing in Python References: Message-ID: In article , Prateek wrote: > Can somebody please provide me link to a good online resource or e- > book for doing natural language processing programming in Python. Check out the Natural Language Toolkit: http://www.nltk.org/ -- Ned Deily, nad at acm.org From daniel.eliason at excite.com Fri Aug 14 13:25:17 2009 From: daniel.eliason at excite.com (fortunatus) Date: Fri, 14 Aug 2009 10:25:17 -0700 (PDT) Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: On Aug 14, 1:01?pm, vippstar wrote: > Why would you fill your website with junk? The OP made it clear: >Just wanted to express some frustration with whitespace-mode. From vippstar at gmail.com Fri Aug 14 13:31:39 2009 From: vippstar at gmail.com (vippstar) Date: Fri, 14 Aug 2009 10:31:39 -0700 (PDT) Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: On Aug 14, 8:25?pm, fortunatus wrote: > On Aug 14, 1:01?pm, vippstar wrote: > > > Why would you fill your website with junk? > > The OP made it clear: > > >Just wanted to express some frustration with whitespace-mode. You took my question out of context and answered it. I read the article, it's not like I missed any of it. Plus, it's not a real answer. "Because I wanted to". Why did you? Why would you? From jeanmichel at sequans.com Fri Aug 14 13:43:15 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 19:43:15 +0200 Subject: callable virtual method In-Reply-To: <7eljaoF2fnkqgU1@mid.uni-berlin.de> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> Message-ID: <4A85A233.9030905@sequans.com> Diez B. Roggisch wrote: > Jean-Michel Pichavant schrieb: >> MRAB wrote: >>> Jean-Michel Pichavant wrote: >>>> Hi fellows, >>>> >>>> Does anyone know a way to write virtual methods (in one virtual >>>> class) that will raise an exception only if called without being >>>> overridden ? >>>> Currently in the virtual method I'm checking that the class of the >>>> instance calling the method has defined that method as well. >>>> >>>> Example: >>>> >>>> class Stream(object): >>>> """Interface of all stream objects""" >>>> def resetStats(self): >>>> """Reset the stream statistics. All values a zeroed except >>>> the date.""" >>>> _log.info('Reset statistics of %s' % self) >>>> if self.__class__.resetStats == Stream.resetStats: >>>> raise NotImplementedError() >>>> >>>> It works but it's tedious, I have to add these 2 lines to every >>>> virtual method, changing the content of the 2 lines. >>>> >>>> Maybe there is a nice/builtin way to do so (python 2.4) >>>> >>> Why are you checking which class it's in? The method in the base class >>> will be called only if it hasn't been overridden in the subclass. >> >> Sorry guys (means guys *and* gals :op ), I realized I've not been >> able to describe precisely what I want to do. >> I'd like the base class to be virtual (aka abstract). However it may >> be abstract but it does not mean it cannot do some usefull stuff. >> >> >> Here is the schema of my abstract methods : >> >> class Interface(object): >> def method(self): >> # --------------------- >> # some common stuff executed here >> # --------------------- >> print 'hello world' >> # --------------------- >> # here shall stand child specific stuff (empty in the >> interface method) >> # --------------------- >> if self.__class__.method == Interface.method: >> raise NotImplementedError('You should have read the >> f****** manual ! You must override this method.') >> >> class GoodChild(Interface): >> def method(self): >> Interface.method(self) # I want to process the cool stuff done >> my the base Interface >> # ------------------------ >> # Specific GoodChild stuff here >> # ------------------------ >> print 'I am a good' >> return 'perfect' >> >> class BadChild(Interface): >> pass #I'm too lazy >> >> >> good = GoodChild() >> bad = BadChild() >> >> good.method() >> ...hello world >> ...I am a good >> >> bad.method() >> ...NotImplementedError: You should have read the f****** manual ! You >> must override this method. >> >> >> The reason I'd like to do so: I'll be providing the Interface, but >> child classes will be overridden by others. Having a reliable error >> RTFM feedback is a time saver, for me and the users. >> I hope I clarified my issue. > > First of all, I doubt the above code really yields that output. You > are missing a super-call there in GoodChild > > And the whole problem goes magically away if you start using OO a bit: > > > class Base(object): > > > def method(self): > self._do_some_work_for_method() > print "some more work" > > def _do_some_work_for_method(self): > raise NotImplemented > > > So your subclasses must implement something else instead of method - > and voila, without any hassle things work as expected. > > Diez It does yield that output, there's an unbound call to Interface.method. Your solution will work, for sure. The problem is that it will dumb down the Base class interface, multiplying the number of methods by 2. This would not be an issue in many cases, in mine there's already too much meaningful methods in my class for me to add artificial ones. Thanks for the tip anyway. JM From wiggly at wiggly.org Fri Aug 14 13:53:02 2009 From: wiggly at wiggly.org (Nigel Rantor) Date: Fri, 14 Aug 2009 18:53:02 +0100 Subject: callable virtual method In-Reply-To: <4A85A233.9030905@sequans.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> Message-ID: <4A85A47E.308@wiggly.org> Jean-Michel Pichavant wrote: > > Your solution will work, for sure. The problem is that it will dumb down > the Base class interface, multiplying the number of methods by 2. This > would not be an issue in many cases, in mine there's already too much > meaningful methods in my class for me to add artificial ones. > > Thanks for the tip anyway. I suggest you reconsider. You asked a question and have been given a standard way of achieving the desired outcome. It's common in OO to use a Template pattern like this. If you're not interested in finding out how loads of people have already solved the problem then why ask? The methods that require overriding can be prefixed with an underscore so that people get a hint that they are an implementation detail rather than part of the public interface. I don't see your problem, other than a vague aesthetic unease. Regards, n From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 13:55:59 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 17:55:59 GMT Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com> <7877b03a-09da-4836-804c-502b6f78003c@h21g2000yqa.googlegroups.com> <02933e60$0$20647$c3e8da3@news.astraweb.com> <2cdc3f88-1952-4ca2-9754-5b7583fb5fd8@z31g2000yqd.googlegroups.com> Message-ID: <0295958b$0$20647$c3e8da3@news.astraweb.com> I think I've spent enough time on this discussion, so I won't be directly responding to any of your recent points -- it's clear that I'm not persuading you that there's any justification for any behaviour for escape sequences other than the way C++ deals with them. That's your prerogative, of course, but I've done enough tilting at windmills for this week, so I'll just make one final comment and then withdraw from an unproductive argument. (I will make an effort to read any final comments you wish to make, so feel free to reply. Just don't expect an answer to any questions.) Douglas, you and I clearly have a difference of opinion on this. Neither of us have provided even the tiniest amount of objective, replicable, reliable data on the error-proneness of the C++ approach versus that of Python. The supposed superiority of the C++ approach is entirely subjective and based on personal opinion instead of quantitative facts. I prefer languages that permit anything that isn't explicitly forbidden, so I'm happy that Python treats non-special escape sequences as valid, and your attempts to convince me that this goes against the Zen have entirely failed to convince me. As I've done before, I will admit that one consequence of this design is that it makes it hard to introduce new escape sequences to Python. Given that it's vanishingly rare to want to do so, and that wanting to add backslashes to strings is common, I think that's a reasonable tradeoff. Other languages may make different tradeoffs, and that's fine by me. -- Steven From jeanmichel at sequans.com Fri Aug 14 13:57:17 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 19:57:17 +0200 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode In-Reply-To: References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: <4A85A57D.8030908@sequans.com> vippstar wrote: > On Aug 14, 8:25 pm, fortunatus wrote: > >> On Aug 14, 1:01 pm, vippstar wrote: >> >> >>> Why would you fill your website with junk? >>> >> The OP made it clear: >> >> >>> Just wanted to express some frustration with whitespace-mode. >>> > > You took my question out of context and answered it. I read the > article, it's not like I missed any of it. Plus, it's not a real > answer. "Because I wanted to". Why did you? Why would you? > FYI, Xah Lee is a well known BTFL (Benevolent Troller For Life), you shouldn't argue about one of his post. From cjw at ncf.ca Fri Aug 14 13:57:18 2009 From: cjw at ncf.ca (Colin J. Williams) Date: Fri, 14 Aug 2009 13:57:18 -0400 Subject: retrieve item from nested list given index tuple In-Reply-To: <02958ab2$0$20647$c3e8da3@news.astraweb.com> References: <02958ab2$0$20647$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Fri, 14 Aug 2009 15:54:54 +0000, Alan G Isaac wrote: > >> `lst` is a nested list >> >> `tpl` is the indexes for an item in the list > >> What is the nice way to retrieve the item? (Speedy access is nice.) > > Assuming you want to do this frequently, write a helper function, then > use it: > > # Untested > def extract(nested, indexes): > for index in indexes: > nested = nested[index] > return nested This looks OK for the first level of nesting. We are not told much about tpl but suppose that: lst= [a, [b, [c, d]], [e, f]] and that we wish to retrieve d and f from lst. tpl would need to be something like [[1, 1, 1], [2, 1]]. If that is the requirement, then Untested is only a step along the road, extract could be made recursive. Colin W. > > >> I don't want to use NumPy, but I'd like somehow to avoid an explicit >> loop. I did consider using eval. E.g., eval('lst' + >> '[%d]'*len(tpl)%tpl). It works but seems rather ugly. > > And slow. > > >> I kind of like >> reduce(list.__getitem__, tpl, lst) but the reliance on reduce remains >> controversial enough to see i removed from the Python 3 built-ins ... > > It's just moved into functools. > > >>>> lst = ['a', 'b', ['aa', ['aaa', 'bbb', 'ccc'], 'cc']] >>>> from functools import reduce >>>> lst = ['a', 'b', ['aa', ['aaa', 'bbb', 'ccc'], 'cc']] >>>> reduce(list.__getitem__, (2, 1, 0), lst) > 'aaa' > > > However, it doesn't work too well as soon as you mix sequence types: > >>>> reduce(list.__getitem__, (2, 1, 0, 0), lst) > Traceback (most recent call last): > File "", line 1, in > TypeError: descriptor '__getitem__' requires a 'list' object but received > a 'str' > > Try this instead: > >>>> from operator import getitem >>>> reduce(getitem, (2, 1, 0), lst) > 'aaa' >>>> reduce(getitem, (2, 1, 0, 0), lst) > 'a' > > operator.getitem is less ugly too. > > Colin W. From alan.isaac at gmail.com Fri Aug 14 14:02:58 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Fri, 14 Aug 2009 18:02:58 GMT Subject: retrieve item from nested list given index tuple In-Reply-To: <02958ab2$0$20647$c3e8da3@news.astraweb.com> References: <02958ab2$0$20647$c3e8da3@news.astraweb.com> Message-ID: On 8/14/2009 1:09 PM Steven D'Aprano apparently wrote: > Try this instead: > >>>> from operator import getitem >>>> reduce(getitem, (2, 1, 0), lst) > 'aaa' >>>> reduce(getitem, (2, 1, 0, 0), lst) > 'a' > > operator.getitem is less ugly too. Yes, that's better. Thanks, Alan From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 14:03:27 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 18:03:27 GMT Subject: trouble with reload References: <24956946.post@talk.nabble.com> <02957215$0$20647$c3e8da3@news.astraweb.com> Message-ID: <0295974b$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 13:14:16 -0400, Colin J. Williams wrote: > Steven D'Aprano wrote: >> On Fri, 14 Aug 2009 09:23:17 -0400, Colin J. Williams wrote: >> >>> It's typically a user module that needs to be reloaded. >> >> What's a user module? > A module written by a user, as distinguished from a libary You mean an end-user of the application? Or you mean the application programmer? I'm not sure there is any difference between "user modules" and "library modules" apart from what they do. Perhaps it would help if you could explain the circumstances of when you would reload a module. During application development, for an incremental edit/reload/test cycle? Or while the completed application is being executed? >>> Is there some other way of ensuring that any import goes to >>> moduleName.py, instead of moduleName.pyc? >> >> Delete moduleName.pyc. >> >> Make sure the .pyc file doesn't exist in the first place. >> >> Make sure the last modification date of the .py file is newer than the >> modification date of the .pyc file. > > That's easier said than done, when one is working with an IDE. The > cached .pyc file might be different from that in the file. If the IDE is getting in your way, then don't use it. Or if you tell us what IDE you're using, and precisely what it is doing, somebody can tell you how to defeat the IDE's cache. (That won't be me -- I don't use IDEs.) Or perhaps you're entire approach is wrong, and you shouldn't be using reload() at all. Don't know. -- Steven From dullrich at sprynet.com Fri Aug 14 14:18:35 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Fri, 14 Aug 2009 13:18:35 -0500 Subject: Komodo(!) Message-ID: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> Probably this isn't news to anyone but me, but just in case: Last I heard Komodo was a very highly regarded IDE that unfortunately cost money. Yesterday I discovered that they now have an editor available for free. Doesn't contain all the features of the IDE, but just having glanced at it it seems to contain more than I'll ever use. What I really like about it is that one can write Komodo scripts in Python (using an extensive API allowing various manipulations of the current document). From steve at REMOVE-THIS-cybersource.com.au Fri Aug 14 14:20:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 14 Aug 2009 18:20:41 GMT Subject: callable virtual method References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> Message-ID: <02959b54$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 18:49:26 +0200, Jean-Michel Pichavant wrote: > Sorry guys (means guys *and* gals :op ), I realized I've not been able > to describe precisely what I want to do. I'd like the base class to be > virtual (aka abstract). However it may be abstract but it does not mean > it cannot do some usefull stuff. > > > Here is the schema of my abstract methods : > > class Interface(object): > def method(self): > # --------------------- > # some common stuff executed here > # --------------------- > print 'hello world' > # --------------------- > # here shall stand child specific stuff (empty in the interface > method) > # --------------------- > if self.__class__.method == Interface.method: > raise NotImplementedError('You should have read the f****** > manual ! You must override this method.') Okay, so I want to sub-class your Interface class. As you said, the methods in the abstract class are still useful, so in my class, I don't need any extra functionality for some methods -- I'm happy with just the "common stuff". So I use normal OO techniques and over-ride just the methods I need to over-ride: class GoodChild(Interface): # no need to over-ride method, because it does everything I want # but over-ride other methods that don't def whatever(self): print "Whatever..." return Interface.whatever() But now my class fails, with an insulting error message *wink*, and you force me to write a whole lot of crappy stupid boilerplate code: class VerboseGoodChild(Interface): # forced to over-ride methods for no good reason def method(self): return Interface.method(self) def another_method(self): return Interface.another_method(self) def yet_another_method(self): return Interface.yet_another_method(self) def still_more_methods(self): return Interface.still_more_methods(self) # Whew! That was a waste of effort. Now at last over-ride the # methods I need to: def whatever(self): print "Whatever..." return Interface.whatever() After the fourth such class, I say "Bugger this for a game of soldiers" and dump your Interface class for something else. > The reason I'd like to do so: I'll be providing the Interface, but child > classes will be overridden by others. Having a reliable error RTFM > feedback is a time saver, for me and the users. I hope I clarified my > issue. The usual way of implementing abstract base classes is to simply prohibit instantiation of the class, but allow all other inheritance. Putting useful functionality in methods, but then prohibiting subclasses from using them without jumping through hoops first, seems rather perverse to me. -- Steven From vlastimil.brom at gmail.com Fri Aug 14 14:26:00 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 14 Aug 2009 20:26:00 +0200 Subject: Natural Language Processing in Python In-Reply-To: References: Message-ID: <9fdb569a0908141126x19d2d4c5q6abc99de7e390f94@mail.gmail.com> 2009/8/14 Prateek : > Hi, > > Can somebody please provide me link to a good online resource or e- > book for doing natural language processing programming in Python. > > Thanks, > Prateek > -- > http://mail.python.org/mailman/listinfo/python-list > Maybe you could start with NLTK http://www.nltk.org/ Check the toolkit as well as the documentation. hth vbr From jeanmichel at sequans.com Fri Aug 14 14:29:03 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 20:29:03 +0200 Subject: callable virtual method In-Reply-To: <4A85A47E.308@wiggly.org> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> <4A85A47E.308@wiggly.org> Message-ID: <4A85ACEF.4090901@sequans.com> Nigel Rantor wrote: > Jean-Michel Pichavant wrote: >> >> Your solution will work, for sure. The problem is that it will dumb >> down the Base class interface, multiplying the number of methods by >> 2. This would not be an issue in many cases, in mine there's already >> too much meaningful methods in my class for me to add artificial ones. >> >> Thanks for the tip anyway. > > I suggest you reconsider. > > You asked a question and have been given a standard way of achieving > the desired outcome. > > It's common in OO to use a Template pattern like this. > > If you're not interested in finding out how loads of people have > already solved the problem then why ask? > > The methods that require overriding can be prefixed with an underscore > so that people get a hint that they are an implementation detail > rather than part of the public interface. > > I don't see your problem, other than a vague aesthetic unease. > > Regards, > > n I understand how refuting some obvious solution may look just stupid. You're right, I shouldn't have asked. By the way I'd like to know if I am I alone to find that class Stream: def start def stop def reset is better than class Stream: def start def _start def stop def _stop def reset def _reset (try to figure out with 20+ methods) What you call aesthetic may sometimes fall into readability. JM From invalid at invalid Fri Aug 14 14:38:27 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 13:38:27 -0500 Subject: Any way to adjust difflib algorithm? Message-ID: I'm trying to use difflib to compare two files, and it's not producing very useful results. When comparing two lines where only a few characters have changed, it usually seems to decide that a line was deleted/inserted/replaced rather than changed. Here's how I'm using it: #!/usr/bin/python import sys,difflib fromlines = [l.rstrip('\n') for l in open(sys.argv[1]).readlines()] tolines = [l.rstrip('\n') for l in open(sys.argv[2]).readlines()] print difflib.HtmlDiff().make_file(fromlines,tolines) In my particular usage, no lines have ever been inserted/deleted, so perhaps I should be running diffs on individual lines instead? If I do that, I can't figure out how to generate HTML output. Is there a way to tell the differ to try harder to match lines? -- Grant Edwards grante Yow! I hope something GOOD at came in the mail today so visi.com I have a REASON to live!! From davea at ieee.org Fri Aug 14 14:50:10 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 14:50:10 -0400 Subject: implementing descriptors In-Reply-To: <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> Message-ID: <4A85B1E2.10209@ieee.org> dippim wrote: > On Aug 14, 10:48 am, Dave Angel wrote: > >> dippim wrote: >> >>> On Aug 14, 2:34 am, Raymond Hettinger wrote: >>> >>>> [David] >>>> >>>>> I am new to Python and I have a question about descriptors. If I have >>>>> a class as written below, is there a way to use descriptors to be >>>>> certain that the datetime in start is always before the one in end? >>>>> >>>>> class foo(object): >>>>> def __init__(self,a =e,b = None) >>>>> self.start > >>> self.end > >>>>> from datetime import datetime >>>>> c =etime(2009,8,13,6,15,0) >>>>> d =etime(2009,8,14,12,0,0) >>>>> afoo =(c,d) >>>>> >>>>> For instance, if the following code were run, I would like to instance >>>>> of foo to switch the start and end times. >>>>> >>>>> afoo.start =etime(2010,8,13,6,15,0) >>>>> >>>>> I was thinking of using the __set__ descriptor to catch the assignment >>>>> and reverse the values if necessary, but I can't figure out how to >>>>> determine which values is being set. >>>>> >>>> You're on the right track, but it is easier to use property() than to >>>> write your own custom descriptor with __get__ and __set__. >>>> >>>> class foo(object): >>>> def __init__(self,a =e,b = None): >>>> self._start > >> self._end > >> def get_start(self): >>>> return self._start >>>> def set_start(self, value): >>>> if self._end is None or value < self._end: >>>> self._start =ue >>>> else: >>>> self._end =ue >>>> start =perty(get_start, set_start) >>>> def get_end(self): >>>> return self._end >>>> def set_end(self, value): >>>> if self._start is None or value > self._start: >>>> self._end =ue >>>> else: >>>> self._start =ue >>>> end =perty(get_end, set_end) >>>> >>>> Raymond >>>> >>> Raymond, >>> This functionality is exactly what I was looking for. Thanks! I'll >>> be using this to solve my problem. >>> >>> Now that I'm on the right track, I'm still a bit confused about how >>> __get__ and __set__ are useful. Admittedly, I don't need to >>> understand them to solve this problem, but perhaps they may be useful >>> in the future. If I wanted to solve this problem using __get__ and >>> __set__ could it be done? >>> >>> Thanks Again! >>> >> DANGER- WILL ROBINSON! >> >> Don't use this code as-is. There is a nasty surprise waiting for the >> caller when he sets start and end, and discovers that one of them gets >> thrown out, and an old value still remains. >> >> obj=oo(3, 5) >> obj.start = 8 >> obj.end = 12 >> print obj.start, obj.end >> >> will print out 3, 12. Not what the caller expected. >> > > You're right about this and I appreciate the warning, but I think what > Raymond was going for was directional accuracy without a great deal of > his time wasted on details. The explanation served the purpose of > moving me forward using property() and I'm thankful for it. > > >> Four fixes, in order of preference: >> 0) Trust your user to read and obey your docstrings. This was what JM >> was implying, by changing the names of the formal parameters. >> > > Considering I am not the sharpest knife in the drawer, I don't wish to > start a philosophical discussion about the relative aptitude and > capabilities of the people who might use a class I build. However, I > will say that as this particular requirement is imposed on this class > by the writer, shouldn't it be the writer's responsibility to enforce > it, especially, when the cost of enforcement is so low? > > >> 1) make a new method that sets both values, making these two properties >> readonly. That new method would make sure the two parameters are >> self-consistent. Making the actual values readonly can be done with a >> descriptor as well, or even a decorator. >> > > >> 2) Raise an exception in the getter methods if they're out of order >> 3) do the min/max logic on the getter methods, but I don't like that one >> at all. >> >> DaveA >> > > > I'm going to assume by "writer" you mean yourself? In other words, the interface isn't being forced upon you by someone else? So I'll continue to push for a cleaner/clearer interface. I'm not going to make any judgment about the relative abilities of you and the caller of your class. You make the final judgment call on how much you want to bulletproof your interface. But occasionally the "automatic fix" causes more problems than it solves. Now, this time you use the word "enforce," which is much different than the original implied "fix up." So I'll assume you mean it literally, that you want to detect when the caller has broken the rules, and raise an exception in that case. In either case, you need to define what "the rules" are. And normally this is done by specifying invariants. I think you're declaring an invariant that, at all times, the object has two datetime attributes, and that obj.start is no greater than obj.end. If the attributes are individually writable, and you do the swap at that time, you get into the trouble I described above. On the other hand, if you just do a raise, then your caller would still get into trouble for the same sequence of calls. So the cure is to either make a new method that explicitly changes both, or don't do the actual check for order till he tries to read the values. In that latter case, you're changing the invariant subtly, to say that if the object is temporarily in an invalid state, one cannot call any other methods or fetch values till the state has been corrected. A real pain to describe, but occasionally useful. This problem of an object temporarily being in an invalid state is not an uncommon one. But most of us have fallen into one of the pitfalls at one time or another. DaveA From wiggly at wiggly.org Fri Aug 14 14:53:37 2009 From: wiggly at wiggly.org (Nigel Rantor) Date: Fri, 14 Aug 2009 19:53:37 +0100 Subject: callable virtual method In-Reply-To: <4A85ACEF.4090901@sequans.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> <4A85A47E.308@wiggly.org> <4A85ACEF.4090901@sequans.com> Message-ID: <4A85B2B1.6090906@wiggly.org> Jean-Michel Pichavant wrote: > Nigel Rantor wrote: >> Jean-Michel Pichavant wrote: >>> >>> Your solution will work, for sure. The problem is that it will dumb >>> down the Base class interface, multiplying the number of methods by >>> 2. This would not be an issue in many cases, in mine there's already >>> too much meaningful methods in my class for me to add artificial ones. >>> >>> Thanks for the tip anyway. >> >> I suggest you reconsider. >> >> You asked a question and have been given a standard way of achieving >> the desired outcome. >> >> It's common in OO to use a Template pattern like this. >> >> If you're not interested in finding out how loads of people have >> already solved the problem then why ask? >> >> The methods that require overriding can be prefixed with an underscore >> so that people get a hint that they are an implementation detail >> rather than part of the public interface. >> >> I don't see your problem, other than a vague aesthetic unease. >> >> Regards, >> >> n > I understand how refuting some obvious solution may look just stupid. > You're right, I shouldn't have asked. I never said it seemed stupid. I was merely curious as to why you'd ask a question and ignore solutions. > By the way I'd like to know if I am I alone to find that > > class Stream: > def start > def stop > def reset > > is better than > > class Stream: > def start > def _start > def stop > def _stop > def reset > def _reset > > (try to figure out with 20+ methods) > What you call aesthetic may sometimes fall into readability. Depends on what you mean by "better". Do you mean pleasing to your eye or performs the task you want it to? Assuming you are taking the aesthetic viewpoint I think that in this case it will depend on how you set out your code. Realise that all of the underscore methods for your class are boilerplate, they simply raise an exception. They can all be at the end of the file, commented as an entire block to be left alone. Editing the main body of code is then fairly easy, and uncluttered... e.g. # # Stream class blah blah blah # class Stream: def start def stop def reset # # stubs to be over-ridden in sub-classes, add one for each # method that requires overriding. # def _start def _stop def _reset Regards, Nigel p.s. Please take this in the spirit it is offered. I'm trying to stop you from ignoring a good suggestion, not make you feel like a fool. From clp2 at rebertia.com Fri Aug 14 14:56:58 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 14 Aug 2009 14:56:58 -0400 Subject: Any way to adjust difflib algorithm? In-Reply-To: References: Message-ID: <50697b2c0908141156y2567464aod75aaf1a668c1d33@mail.gmail.com> On Fri, Aug 14, 2009 at 2:38 PM, Grant Edwards wrote: > I'm trying to use difflib to compare two files, and it's not > producing very useful results. ?When comparing two lines where > only a few characters have changed, it usually seems to decide > that a line was deleted/inserted/replaced rather than changed. > Is there a way to tell the differ to try harder to match lines? You could use a wordwise diff instead: http://www.gnu.org/software/wdiff/ Obviously that's not a pure Python solution though. Cheers, Chris -- http://blog.rebertia.com From invalid at invalid Fri Aug 14 15:18:59 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 14:18:59 -0500 Subject: Any way to adjust difflib algorithm? References: Message-ID: On 2009-08-14, Grant Edwards wrote: > I'm trying to use difflib to compare two files, and it's not > producing very useful results. When comparing two lines where > only a few characters have changed, it usually seems to decide > that a line was deleted/inserted/replaced rather than changed. [...] > In my particular usage, no lines have ever been > inserted/deleted, so perhaps I should be running diffs on > individual lines instead? If I do that, I can't figure out > how to generate HTML output. I ended up using the SequenceMatcher on individual pairs of lines and generating my own HTML based on the results of get_matching_blocks(). That produced the desired results. -- Grant Edwards grante Yow! I have a very good at DENTAL PLAN. Thank you. visi.com From davea at ieee.org Fri Aug 14 15:24:39 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 15:24:39 -0400 Subject: callable virtual method In-Reply-To: <4A85ACEF.4090901@sequans.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> <4A85A47E.308@wiggly.org> <4A85ACEF.4090901@sequans.com> Message-ID: <4A85B9F7.4010201@ieee.org> Jean-Michel Pichavant wrote: >
Nigel > Rantor wrote: >> Jean-Michel Pichavant wrote: >>> >>> Your solution will work, for sure. The problem is that it will dumb >>> down the Base class interface, multiplying the number of methods by >>> 2. This would not be an issue in many cases, in mine there's already >>> too much meaningful methods in my class for me to add artificial ones. >>> >>> Thanks for the tip anyway. >> >> I suggest you reconsider. >> >> You asked a question and have been given a standard way of achieving >> the desired outcome. >> >> It's common in OO to use a Template pattern like this. >> >> If you're not interested in finding out how loads of people have >> already solved the problem then why ask? >> >> The methods that require overriding can be prefixed with an >> underscore so that people get a hint that they are an implementation >> detail rather than part of the public interface. >> >> I don't see your problem, other than a vague aesthetic unease. >> >> Regards, >> >> n > I understand how refuting some obvious solution may look just stupid. > You're right, I shouldn't have asked. > > By the way I'd like to know if I am I alone to find that > > class Stream: > def start > def stop > def reset > > is better than > > class Stream: > def start > def _start > def stop > def _stop > def reset > def _reset > > (try to figure out with 20+ methods) > What you call aesthetic may sometimes fall into readability. > > > JM > > >
> Usually when one defines an abstract base class, one expects many people will derive from it, as opposed to only one having to write it. So if the base must be "ugly" according to some definition, so be it. Aesthetics are quite subjective. Nigel's approach has another benefit not stated, which is to keep the child class code simpler. They avoid the need to call any base class method to access the common logic. The downside is it assumes that the common logic will always be either at the beginning or always at the end of the child classes implementation. That's because the base class has hardcoded where in its implementation to call the child class method. Anyway, without arguing for or against either approach, I'd point out that you could have an extra formal parameter in the base method, which is a private signal from the child class that this is the internal call. Missing such a formal parameter would then trigger the "missing method in derived class" error message. You'd check such a parameter the same place as you're now checking the object's type. DaveA From kee at kagi.com Fri Aug 14 15:28:54 2009 From: kee at kagi.com (Kee Nethery) Date: Fri, 14 Aug 2009 12:28:54 -0700 Subject: Komodo(!) In-Reply-To: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> References: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> Message-ID: From the web site it looks like the free version does not include the debugging stuff. I've been using the paid version with the debugger functionality and I find it easy to use and incredibly nice for trying to understand what the code is doing. The built-in debugger has saved me tons of time, especially when troubleshooting CGIs. I'm using a Mac and of the Python IDEs I looked at, Komodo had the easiest to use user interface, in my opinion. Kee From kennyken747 at gmail.com Fri Aug 14 15:29:12 2009 From: kennyken747 at gmail.com (kennyken747) Date: Fri, 14 Aug 2009 12:29:12 -0700 (PDT) Subject: Something like wibiya? Message-ID: <78de82ac-72d2-472f-92ba-d0d3cb2e0b99@s31g2000yqs.googlegroups.com> Would Python be an efficient language to go about coding something like the toolbar from http://www.wibiya.com/index.php ? And then, how would I implement it? -Kenny Ledet Owner of Hotontheblock.com, Urban News Blog From davea at ieee.org Fri Aug 14 15:32:40 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 15:32:40 -0400 Subject: retrieve item from nested list given index tuple In-Reply-To: References: <02958ab2$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A85BBD8.7000409@ieee.org> Colin J. Williams wrote: >
Steven > D'Aprano wrote: >> On Fri, 14 Aug 2009 15:54:54 +0000, Alan G Isaac wrote: >> >>> `lst` is a nested list >>> >>> `tpl` is the indexes for an item in the list >> >>> What is the nice way to retrieve the item? (Speedy access is nice.) >> >> Assuming you want to do this frequently, write a helper function, >> then use it: >> >> # Untested >> def extract(nested, indexes): >> for index in indexes: >> nested = nested[index] >> return nested > > This looks OK for the first level of nesting. We are not told much > about tpl but suppose that: > > lst= [a, [b, [c, d]], [e, f]] and that we wish to retrieve d and f > from lst. tpl would need to be something like [[1, 1, 1], [2, 1]]. > > If that is the requirement, then Untested is only a step along the > road, extract could be made recursive. > > Colin W. > You missed the point: he's retrieving *an* item from a list that's nested arbitrarily. Each item in the tpl (tuple) is a simple integer. DaveA From cjwilliams43 at gmail.com Fri Aug 14 15:55:29 2009 From: cjwilliams43 at gmail.com (Colin J. Williams) Date: Fri, 14 Aug 2009 15:55:29 -0400 Subject: retrieve item from nested list given index tuple In-Reply-To: <4A85BBD8.7000409@ieee.org> References: <02958ab2$0$20647$c3e8da3@news.astraweb.com> <4A85BBD8.7000409@ieee.org> Message-ID: <4A85C131.60905@ncf.ca> Dave Angel wrote: > Colin J. Williams wrote: >>
Steven >> D'Aprano wrote: >>> On Fri, 14 Aug 2009 15:54:54 +0000, Alan G Isaac wrote: >>> >>>> `lst` is a nested list >>>> >>>> `tpl` is the indexes for an item in the list >>> >>>> What is the nice way to retrieve the item? (Speedy access is nice.) >>> >>> Assuming you want to do this frequently, write a helper function, >>> then use it: >>> >>> # Untested >>> def extract(nested, indexes): >>> for index in indexes: >>> nested = nested[index] >>> return nested >> >> This looks OK for the first level of nesting. We are not told much >> about tpl but suppose that: >> >> lst= [a, [b, [c, d]], [e, f]] and that we wish to retrieve d and f >> from lst. tpl would need to be something like [[1, 1, 1], [2, 1]]. >> >> If that is the requirement, then Untested is only a step along the >> road, extract could be made recursive. >> >> Colin W. >> > > You missed the point: he's retrieving *an* item from a list that's > nested arbitrarily. Each item in the tpl (tuple) is a simple integer. > > > DaveA Yes, you are right. Colin W. > > From mensanator at aol.com Fri Aug 14 16:07:40 2009 From: mensanator at aol.com (Mensanator) Date: Fri, 14 Aug 2009 13:07:40 -0700 (PDT) Subject: Python Permutations Problem References: Message-ID: <3ba39961-aec4-4034-beac-9552bb8a7ee6@w6g2000yqw.googlegroups.com> On Aug 14, 11:28?am, Asanka Wasala wrote: > Hi > I am developing a spell checker for my language, and I came across > solving an interesing problem. It would be great if you can suggest > me ?an optimized solution for the problem described below: > > I have certain group of letters like these: > > Group #1: c,r,b > Group #2: a,z,k > Group #3: h,t > . > . > > Letters within the same group can be substituted/replaced with the > rest of the letters in that group. > > (ie. Group #1 means letter 'c' can be replaced with either 'r' or 'b', > and letter r can be replaced with either c or b, and letter b can be > replaced with either r or c) > > A group can have upto 3 letters, and letters do not overlap between > groups. There can be upto 25 such groups. > Given a word containing above letters, (e.g. 'cat'.) I want to > generate all possible words by subsituting letters in the groups. > > eg. expected output: > > cat ? ? rat ? ? bat > czt ? ? rzt ? ? bzt > ckt ? ? rkt ? ? bkt > cah ? ? rah ? ? bah > czh ? ? rzh ? ? bzh > ckh ? ? rkh ? ? bkh > > My code is given below. But for complex words like 'cccccccccczzk' it > thows the 'maximum recursion depth exceeded' error. Therefore, can you > suggest me an optimized solution to achive the above task? Thanks in > advance. > -------------------------- > CODE------------------------------------------- > #-*- coding: UTF-8 -*- > import re > def getPermutations(word): > ? ? def getSimilarLetters(letter): > ? ? ? ? pattern=u"|c,r,b|a,z,k|h,t|" > ? ? ? ? list=[] > ? ? ? ? ptrn=re.compile("(?P\|(.?,)*?"+letter+"(,.)*?\|)") > ? ? ? ? k=ptrn.search(pattern) > ? ? ? ? if k: > ? ? ? ? ? ? letterlist=k.group("grp")[1:-1] > ? ? ? ? ? ? list=letterlist.split(",") > ? ? ? ? ? ? list.remove(letter) > ? ? ? ? ? ? return list > ? ? ? ? else: > ? ? ? ? ? ? return letter > > ? ? list=[] > > ? ? def perm(word): > ? ? ? ? posi=0 > ? ? ? ? wrd=word > ? ? ? ? for w in word: > ? ? ? ? ? ? posi=posi+1 > ? ? ? ? ? ? lst=getSimilarLetters(w) > ? ? ? ? ? ? if len(lst)>0: > ? ? ? ? ? ? ? ? for l in lst: > ? ? ? ? ? ? ? ? ? ? newwrd=wrd[:posi-1]+l+wrd[posi:] > ? ? ? ? ? ? ? ? ? ? if not (newwrd in list): > ? ? ? ? ? ? ? ? ? ? ? ? list.append(newwrd) > ? ? ? ? ? ? ? ? ? ? ? ? perm(newwrd) > > ? ? try: > ? ? ? ? perm(word) > ? ? except RuntimeError: > ? ? ? ? list=[] > ? ? ? ? list.append("error") > ? ? return list > > list=getPermutations(u"cat") > > for i in list: > ? ? print i.encode('utf-8') > --------------------------------------------END of > CODE-----------------------------------------------------------------------?------ IDLE 2.6.1 >>> import itertools as it >>> for i in it.product('crb','azk','ht'): print ''.join(i), cah cat czh czt ckh ckt rah rat rzh rzt rkh rkt bah bat bzh bzt bkh bkt From max at alcyone.com Fri Aug 14 16:10:57 2009 From: max at alcyone.com (Erik Max Francis) Date: Fri, 14 Aug 2009 13:10:57 -0700 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: Grant Edwards wrote: > On 2009-08-14, Steven D'Aprano wrote: >> What the hell >> would it actually do??? > > IIRC in C++, > > cout << "Hello world"; > > is equivalent to this in C: > > printf("Hellow world"); > > or this in Python: > > print "hellow world" Well, plus or minus newlines. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis It's hard to say what I want my legacy to be when I'm long gone. -- Aaliyah From invalid at invalid Fri Aug 14 16:13:31 2009 From: invalid at invalid (Grant Edwards) Date: Fri, 14 Aug 2009 15:13:31 -0500 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: <68-dnWijX7T2WBjXnZ2dnUVZ_t6dnZ2d@posted.visi> On 2009-08-14, Erik Max Francis wrote: > Grant Edwards wrote: >> On 2009-08-14, Steven D'Aprano wrote: >>> What the hell >>> would it actually do??? >> >> IIRC in C++, >> >> cout << "Hello world"; >> >> is equivalent to this in C: >> >> printf("Hellow world"); >> >> or this in Python: >> >> print "hellow world" > > Well, plus or minus newlines. And a few miscellaneous typos... -- Grant Edwards grante Yow! I don't understand at the HUMOUR of the THREE visi.com STOOGES!! From max at alcyone.com Fri Aug 14 16:18:04 2009 From: max at alcyone.com (Erik Max Francis) Date: Fri, 14 Aug 2009 13:18:04 -0700 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <68-dnWijX7T2WBjXnZ2dnUVZ_t6dnZ2d@posted.visi> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <68-dnWijX7T2WBjXnZ2dnUVZ_t6dnZ2d@posted.visi> Message-ID: Grant Edwards wrote: > On 2009-08-14, Erik Max Francis wrote: >> Grant Edwards wrote: >>> On 2009-08-14, Steven D'Aprano wrote: >>>> What the hell >>>> would it actually do??? >>> IIRC in C++, >>> >>> cout << "Hello world"; >>> >>> is equivalent to this in C: >>> >>> printf("Hellow world"); >>> >>> or this in Python: >>> >>> print "hellow world" >> Well, plus or minus newlines. > > And a few miscellaneous typos... ... and includes and namespaces :-). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis It's hard to say what I want my legacy to be when I'm long gone. -- Aaliyah From jeanmichel at sequans.com Fri Aug 14 16:22:10 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 22:22:10 +0200 Subject: callable virtual method In-Reply-To: <02959b54$0$20647$c3e8da3@news.astraweb.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A85C772.504@sequans.com> Steven D'Aprano wrote: > On Fri, 14 Aug 2009 18:49:26 +0200, Jean-Michel Pichavant wrote: > > >> Sorry guys (means guys *and* gals :op ), I realized I've not been able >> to describe precisely what I want to do. I'd like the base class to be >> virtual (aka abstract). However it may be abstract but it does not mean >> it cannot do some usefull stuff. >> >> >> Here is the schema of my abstract methods : >> >> class Interface(object): >> def method(self): >> # --------------------- >> # some common stuff executed here >> # --------------------- >> print 'hello world' >> # --------------------- >> # here shall stand child specific stuff (empty in the interface >> method) >> # --------------------- >> if self.__class__.method == Interface.method: >> raise NotImplementedError('You should have read the f****** >> manual ! You must override this method.') >> > > > Okay, so I want to sub-class your Interface class. As you said, the > methods in the abstract class are still useful, so in my class, I don't > need any extra functionality for some methods -- I'm happy with just the > "common stuff". So I use normal OO techniques and over-ride just the > methods I need to over-ride: > > Sometimes the base is doing cool stuff but incomplete stuff which requires knowledge only hold by the sub class. In my case the interface is a high level interface for a software that can run on multiple hardware platforms. Only the sub class has knowledge on how to operate the hardware, but no matter the hardware it still produces the same effect. Let's say I have 50 different hardwares, I'll have 50 sub classes of Interface with the 'start' method to define. It wouldn't be appropriate (OO programming)to write 50 times '_log.debug('Starting %s' % self)' in each child start method when the simple task of logging the call can be nicely handled by the base class. In the meantime, I must make sure the user, who is not a python guru in this case, has implemented the start method for his hardware, because only him knows how to effectively start this hardware. I don't want him to come to me saying, "I got no error, still my hardware does not start". You can then blame him for not reading the docs, but it will still be less expensive to throw a nice exception with an accurate feedback. [snip] > class VerboseGoodChild(Interface): > # forced to over-ride methods for no good reason > Definitely no !! This is the purpose of an interface class: to force people to write these methods. They *are* required, if they were not, they would not belong to the Interface. JM From no.email at please.post Fri Aug 14 16:23:20 2009 From: no.email at please.post (kj) Date: Fri, 14 Aug 2009 20:23:20 +0000 (UTC) Subject: Splitting on '^' ? Message-ID: Sometimes I want to split a string into lines, preserving the end-of-line markers. In Perl this is really easy to do, by splitting on the beginning-of-line anchor: @lines = split /^/, $string; But I can't figure out how to do the same thing with Python. E.g.: >>> import re >>> re.split('^', 'spam\nham\neggs\n') ['spam\nham\neggs\n'] >>> re.split('(?m)^', 'spam\nham\neggs\n') ['spam\nham\neggs\n'] >>> bol_re = re.compile('^', re.M) >>> bol_re.split('spam\nham\neggs\n') ['spam\nham\neggs\n'] Am I doing something wrong? kynn From guthrie at mum.edu Fri Aug 14 16:25:02 2009 From: guthrie at mum.edu (guthrie) Date: Fri, 14 Aug 2009 13:25:02 -0700 (PDT) Subject: py-rrdTool - install fails Message-ID: I want to do some rrd in a python cgi script, but am having trouble getting an easy install module. py-rrdTool looks good, but is distributed in c source, and is missing a header file in the distribution. Thus the install fails when it tries to reference rrd.h which is not there. Are there better rrd modules to use, or a compiled version of this, or other suggestions? -------------------------------------------------------------------------------------- building 'rrdtool._rrdtool' extension C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo / Ox /MD /W3 /GS- /DNDEBUG -I/usr/local\include "-IE:\PLang\Active Python \include" "-IE:\PLang\Active Python\PC" /Tcsrc/_rrdtoolmodule.c / Fobuild\temp.win32-2.6\Release\src/_rrdtoolmodule.obj _rrdtoolmodule.c src/_rrdtoolmodule.c(34) : fatal error C1083: Cannot open include file: 'rrd.h': No such file or directory error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN \cl.exe"' failed with exit status 2 C:\Documents and Settings\guthrie\Desktop\py-rrdtool-0.2.1> From gherron at islandtraining.com Fri Aug 14 16:36:20 2009 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 14 Aug 2009 13:36:20 -0700 Subject: Splitting on '^' ? In-Reply-To: References: Message-ID: <4A85CAC4.2000401@islandtraining.com> kj wrote: > Sometimes I want to split a string into lines, preserving the > end-of-line markers. In Perl this is really easy to do, by splitting > on the beginning-of-line anchor: > > @lines = split /^/, $string; > > But I can't figure out how to do the same thing with Python. E.g.: > > >>>> import re >>>> re.split('^', 'spam\nham\neggs\n') >>>> > ['spam\nham\neggs\n'] > >>>> re.split('(?m)^', 'spam\nham\neggs\n') >>>> > ['spam\nham\neggs\n'] > >>>> bol_re = re.compile('^', re.M) >>>> bol_re.split('spam\nham\neggs\n') >>>> > ['spam\nham\neggs\n'] > > Am I doing something wrong? > Just split on the EOL character: the "\n": re.split('\n', 'spam\nham\neggs\n') ['spam', 'ham', 'eggs', ''] The "^" and "$" characters do not match END-OF-LINE, but rather the END-OF-STRING, which was doing you no good. Gary Herron > kynn > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tycho at tycho.ws Fri Aug 14 16:38:49 2009 From: tycho at tycho.ws (Tycho Andersen) Date: Fri, 14 Aug 2009 15:38:49 -0500 Subject: Splitting on '^' ? In-Reply-To: References: Message-ID: <49b3a7400908141338v7ef43e19y9b8b813b747dc897@mail.gmail.com> On Fri, Aug 14, 2009 at 3:23 PM, kj wrote: > [snip] >>>> import re >>>> re.split('^', 'spam\nham\neggs\n') > ['spam\nham\neggs\n'] >>>> re.split('(?m)^', 'spam\nham\neggs\n') > ['spam\nham\neggs\n'] >>>> bol_re = re.compile('^', re.M) >>>> bol_re.split('spam\nham\neggs\n') > ['spam\nham\neggs\n'] > > Am I doing something wrong? Why not just: >>> re.split(r'\n', 'spam\nham\neggs') \t From lists at cheimes.de Fri Aug 14 16:39:56 2009 From: lists at cheimes.de (Christian Heimes) Date: Fri, 14 Aug 2009 22:39:56 +0200 Subject: py-rrdTool - install fails In-Reply-To: References: Message-ID: <4A85CB9C.5060305@cheimes.de> guthrie schrieb: > I want to do some rrd in a python cgi script, but am having trouble > getting an easy install module. > > py-rrdTool looks good, but is distributed in c source, and is missing > a header file in the distribution. Thus the install fails when it > tries to reference rrd.h which is not there. > > Are there better rrd modules to use, or a compiled version of this, or > other suggestions? > -------------------------------------------------------------------------------------- > building 'rrdtool._rrdtool' extension > C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo / > Ox /MD /W3 /GS- /DNDEBUG -I/usr/local\include "-IE:\PLang\Active Python > \include" "-IE:\PLang\Active Python\PC" /Tcsrc/_rrdtoolmodule.c / > Fobuild\temp.win32-2.6\Release\src/_rrdtoolmodule.obj > _rrdtoolmodule.c > src/_rrdtoolmodule.c(34) : fatal error C1083: Cannot open include > file: 'rrd.h': No such file or directory > error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN > \cl.exe"' failed with exit status 2 > > C:\Documents and Settings\guthrie\Desktop\py-rrdtool-0.2.1> rrd.h is part of the rrdtools. You need to install rrdtools plus all its dependencies. Have a lot of fun ;) Christian From lists at cheimes.de Fri Aug 14 16:39:56 2009 From: lists at cheimes.de (Christian Heimes) Date: Fri, 14 Aug 2009 22:39:56 +0200 Subject: py-rrdTool - install fails In-Reply-To: References: Message-ID: <4A85CB9C.5060305@cheimes.de> guthrie schrieb: > I want to do some rrd in a python cgi script, but am having trouble > getting an easy install module. > > py-rrdTool looks good, but is distributed in c source, and is missing > a header file in the distribution. Thus the install fails when it > tries to reference rrd.h which is not there. > > Are there better rrd modules to use, or a compiled version of this, or > other suggestions? > -------------------------------------------------------------------------------------- > building 'rrdtool._rrdtool' extension > C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo / > Ox /MD /W3 /GS- /DNDEBUG -I/usr/local\include "-IE:\PLang\Active Python > \include" "-IE:\PLang\Active Python\PC" /Tcsrc/_rrdtoolmodule.c / > Fobuild\temp.win32-2.6\Release\src/_rrdtoolmodule.obj > _rrdtoolmodule.c > src/_rrdtoolmodule.c(34) : fatal error C1083: Cannot open include > file: 'rrd.h': No such file or directory > error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN > \cl.exe"' failed with exit status 2 > > C:\Documents and Settings\guthrie\Desktop\py-rrdtool-0.2.1> rrd.h is part of the rrdtools. You need to install rrdtools plus all its dependencies. Have a lot of fun ;) Christian From gabriel at opensuse.org Fri Aug 14 16:41:36 2009 From: gabriel at opensuse.org (Gabriel) Date: Fri, 14 Aug 2009 17:41:36 -0300 Subject: Splitting on '^' ? In-Reply-To: References: Message-ID: <1adde6890908141341r29644770pc8b57a83369d4546@mail.gmail.com> On Fri, Aug 14, 2009 at 5:23 PM, kj wrote: > >>>> import re >>>> re.split('^', 'spam\nham\neggs\n') > ['spam\nham\neggs\n'] >>>> re.split('(?m)^', 'spam\nham\neggs\n') > ['spam\nham\neggs\n'] >>>> bol_re = re.compile('^', re.M) >>>> bol_re.split('spam\nham\neggs\n') > ['spam\nham\neggs\n'] > > Am I doing something wrong? > Maybe this: >>> import re >>> te = 'spam\nham\neggs\n' >>> pat = '\n' >>> re.split(pat,te) ['spam', 'ham', 'eggs', ''] -- Kind Regards From Brian.Mingus at colorado.edu Fri Aug 14 16:43:45 2009 From: Brian.Mingus at colorado.edu (Brian) Date: Fri, 14 Aug 2009 14:43:45 -0600 Subject: Splitting on '^' ? In-Reply-To: References: Message-ID: <9839a05c0908141343v37520d39i2833470f69528d95@mail.gmail.com> On Fri, Aug 14, 2009 at 2:23 PM, kj wrote: > > > Sometimes I want to split a string into lines, preserving the > end-of-line markers. In Perl this is really easy to do, by splitting > on the beginning-of-line anchor: > > @lines = split /^/, $string; > > But I can't figure out how to do the same thing with Python. E.g.: > > >>> import re > >>> re.split('^', 'spam\nham\neggs\n') > ['spam\nham\neggs\n'] > >>> re.split('(?m)^', 'spam\nham\neggs\n') > ['spam\nham\neggs\n'] > >>> bol_re = re.compile('^', re.M) > >>> bol_re.split('spam\nham\neggs\n') > ['spam\nham\neggs\n'] > > Am I doing something wrong? > > kynn > -- > http://mail.python.org/mailman/listinfo/python-list > You shouldn't use a regular expression for that. >>> from time import time >>> start=time();'spam\nham\neggs\n'.split('\n');print time()-start; ['spam', 'ham', 'eggs', ''] 4.6968460083e-05 >>> import re >>> start=time();re.split(r'\n', 'spam\nham\neggs');print time()-start; ['spam', 'ham', 'eggs'] 0.000284910202026 -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Fri Aug 14 16:44:27 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Fri, 14 Aug 2009 16:44:27 -0400 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: On Fri, Aug 14, 2009 at 12:42 PM, Douglas Alan wrote: > > P.S. Overloading "left shift" to mean "output" does indeed seem a bit > sketchy, but in 15 years of C++ programming, I've never seen it cause > any confusion or bugs. The only reason it hasn't is because people use it in "Hello World". I bet some newbie C++ programmers get confused the first time they see << used to shift. -------------- next part -------------- An HTML attachment was scrubbed... URL: From abecedarian314159 at yahoo.com Fri Aug 14 16:55:16 2009 From: abecedarian314159 at yahoo.com (William) Date: Fri, 14 Aug 2009 13:55:16 -0700 (PDT) Subject: Komodo(!) In-Reply-To: References: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> Message-ID: <553649.43098.qm@web110605.mail.gq1.yahoo.com> Personally, I rather like Wing ________________________________ From: Kee Nethery To: python-list at python.org Sent: Friday, August 14, 2009 3:28:54 PM Subject: Re: Komodo(!) >From the web site it looks like the free version does not include the debugging stuff. I've been using the paid version with the debugger functionality and I find it easy to use and incredibly nice for trying to understand what the code is doing. The built-in debugger has saved me tons of time, especially when troubleshooting CGIs. I'm using a Mac and of the Python IDEs I looked at, Komodo had the easiest to use user interface, in my opinion. Kee --http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Fri Aug 14 17:00:01 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 14 Aug 2009 23:00:01 +0200 Subject: callable virtual method In-Reply-To: <4A85B9F7.4010201@ieee.org> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> <4A85A47E.308@wiggly.org> <4A85ACEF.4090901@sequans.com> <4A85B9F7.4010201@ieee.org> Message-ID: <4A85D051.2080004@sequans.com> Dave Angel wrote: > Jean-Michel Pichavant wrote: >>
Nigel >> Rantor wrote: >>> Jean-Michel Pichavant wrote: >>>> >>>> Your solution will work, for sure. The problem is that it will dumb >>>> down the Base class interface, multiplying the number of methods by >>>> 2. This would not be an issue in many cases, in mine there's >>>> already too much meaningful methods in my class for me to add >>>> artificial ones. >>>> >>>> Thanks for the tip anyway. >>> >>> I suggest you reconsider. >>> >>> You asked a question and have been given a standard way of achieving >>> the desired outcome. >>> >>> It's common in OO to use a Template pattern like this. >>> >>> If you're not interested in finding out how loads of people have >>> already solved the problem then why ask? >>> >>> The methods that require overriding can be prefixed with an >>> underscore so that people get a hint that they are an implementation >>> detail rather than part of the public interface. >>> >>> I don't see your problem, other than a vague aesthetic unease. >>> >>> Regards, >>> >>> n >> I understand how refuting some obvious solution may look just stupid. >> You're right, I shouldn't have asked. >> >> By the way I'd like to know if I am I alone to find that >> >> class Stream: >> def start >> def stop >> def reset >> >> is better than >> >> class Stream: >> def start >> def _start >> def stop >> def _stop >> def reset >> def _reset >> >> (try to figure out with 20+ methods) >> What you call aesthetic may sometimes fall into readability. >> >> >> JM >> >> >>
>> > Usually when one defines an abstract base class, one expects many > people will derive from it, as opposed to only one having to write > it. So if the base must be "ugly" according to some definition, so be > it. Aesthetics are quite subjective. > > Nigel's approach has another benefit not stated, which is to keep the > child class code simpler. They avoid the need to call any base class > method to access the common logic. The downside is it assumes that > the common logic will always be either at the beginning or always at > the end of the child classes implementation. That's because the base > class has hardcoded where in its implementation to call the child > class method. > I think this is a severe issue. You prevent the sub class from writing def foo(self): pre() Base.foo(self) post() > Anyway, without arguing for or against either approach, I'd point out > that you could have an extra formal parameter in the base method, > which is a private signal from the child class that this is the > internal call. Missing such a formal parameter would then trigger the > "missing method in derived class" error message. You'd check such a > parameter the same place as you're now checking the object's type. > > DaveA > > talking about approaches: 1/ class Interface: def foo(self): if self.__class__.foo == Interface.foo: raise NotImplementedError 2/ class Interface: def foo(self): self._foo() def _foo(sef): raise NotImplementedError Are they so different ? They both require about the same amount of extra characters, they're both readable. The second is a very classic OO layout, the first is more flexible for the sub classes and spare some method definition. This thread may live again, I cannot say but I'd like to thanks all who gave me their valuable idea on the subject, I mean it. Please don't take my skepticism as a lack of consideration. JM From lists at sourceillustrated.com Fri Aug 14 17:04:17 2009 From: lists at sourceillustrated.com (John Wells) Date: Fri, 14 Aug 2009 17:04:17 -0400 Subject: Komodo(!) In-Reply-To: References: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> Message-ID: <44dddf400908141404v2ec276bepd6399d3672ed7f49@mail.gmail.com> On Fri, Aug 14, 2009 at 3:28 PM, Kee Nethery wrote: > From the web site it looks like the free version does not include the > debugging stuff. > > I've been using the paid version with the debugger functionality and I find > it easy to use and incredibly nice for trying to understand what the code is > doing. The built-in debugger has saved me tons of time, especially when > troubleshooting CGIs. > > I'm using a Mac and of the Python IDEs I looked at, Komodo had the easiest > to use user interface, in my opinion. I've been using Netbeans with Python support and have enjoyed it. Have you tried it? It has integrated debugging, etc as well, and the price (free) is right. I'm curious how it compares to Komodo.... Thanks, John From ethan at stoneleaf.us Fri Aug 14 17:20:06 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Aug 2009 14:20:06 -0700 Subject: Splitting on '^' ? In-Reply-To: References: Message-ID: <4A85D506.7060104@stoneleaf.us> kj wrote: > > Sometimes I want to split a string into lines, preserving the > end-of-line markers. In Perl this is really easy to do, by splitting > on the beginning-of-line anchor: > > @lines = split /^/, $string; > > But I can't figure out how to do the same thing with Python. E.g.: > > >>>>import re >>>>re.split('^', 'spam\nham\neggs\n') > > ['spam\nham\neggs\n'] > >>>>re.split('(?m)^', 'spam\nham\neggs\n') > > ['spam\nham\neggs\n'] > >>>>bol_re = re.compile('^', re.M) >>>>bol_re.split('spam\nham\neggs\n') > > ['spam\nham\neggs\n'] > > Am I doing something wrong? > > kynn As you probably noticed from the other responses: No, you can't split on _and_ keep the splitby text. Looks like you'll have to roll your own. def splitat(text, sep): result = [line + sep for line in text.split(sep)] if result[-1] == sep: # either remove extra element result.pop() else: # or extra sep from last element result[-1] = result[-1][:-len(sep)] return result From python at mrabarnett.plus.com Fri Aug 14 17:22:05 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 22:22:05 +0100 Subject: Splitting on '^' ? In-Reply-To: <4A85CAC4.2000401@islandtraining.com> References: <4A85CAC4.2000401@islandtraining.com> Message-ID: <4A85D57D.40602@mrabarnett.plus.com> Gary Herron wrote: > kj wrote: >> Sometimes I want to split a string into lines, preserving the >> end-of-line markers. In Perl this is really easy to do, by splitting >> on the beginning-of-line anchor: >> >> @lines = split /^/, $string; >> >> But I can't figure out how to do the same thing with Python. E.g.: >> >> >>>>> import re >>>>> re.split('^', 'spam\nham\neggs\n') >>>>> >> ['spam\nham\neggs\n'] >> >>>>> re.split('(?m)^', 'spam\nham\neggs\n') >>>>> >> ['spam\nham\neggs\n'] >> >>>>> bol_re = re.compile('^', re.M) >>>>> bol_re.split('spam\nham\neggs\n') >>>>> >> ['spam\nham\neggs\n'] >> >> Am I doing something wrong? >> > Just split on the EOL character: the "\n": > re.split('\n', 'spam\nham\neggs\n') > ['spam', 'ham', 'eggs', ''] > > The "^" and "$" characters do not match END-OF-LINE, but rather the > END-OF-STRING, which was doing you no good. > With the MULTLINE flag "^" matches START-OF-LINE and "$" matches END-OF-LINE or END-OF-STRING. The current re module won't split on a zero-width match. From joseph.h.garvin at gmail.com Fri Aug 14 17:22:12 2009 From: joseph.h.garvin at gmail.com (Joseph Garvin) Date: Fri, 14 Aug 2009 16:22:12 -0500 Subject: bug?: python-config --ldflags gives incorrect output Message-ID: On the latest stable ubuntu: $ python-config --ldflags -L/usr/lib/python2.6/config -lpthread -ldl -lutil -lm -lpython2.6 In case the user is statically linking, I believe the -lpython2.6 should go before the other -l's. Also, -lz is missing so whenever you try to link against python you get tons of errors about missing PyZlib references. Am I right in thinking these are bugs? From piet at cs.uu.nl Fri Aug 14 17:30:45 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 14 Aug 2009 23:30:45 +0200 Subject: something like perl's Mail::GPG ? References: <4365602b-e174-4419-a1f7-44dde1b66b0c@w41g2000yqb.googlegroups.com> Message-ID: >>>>> akonsu (a) wrote: >a> hello, >a> i am looking for a module with functionality similar to that of the >a> Perl's Mail::GPG package. I need to verify multipart emails that are >a> PGP-signed. I don't know Perl's GPG package, but to verify PGP-signed stuff you can use gnupg. It doesn't have special code for mail messages, however. It is just a Pythonic wrapper facade around the gpg program. However, it doesn't do the PGP/MIME stuff, so you will have to transform the MIME messages into something that GPG understands. This isn't hard and you can find a short python script that does it on http://domnit.org/2008/03/clearmime. It describes how you can use it as a program and pipe the message through it into gpg --verify. You can also use it as a module if you rename it to clearmime.py, and use it with the recently released gnupg module. It is released under GPL. However it wouldn't be hard to write something similar yourself, for example if you want to feed it existing Message objects rather than strings. Example: import os from gnupg import GPG from clearmime import clarify msgtxt = open('testgpg.msg').read() cl = clarify(msgtxt) gpg=GPG(gnupghome = os.path.join(os.environ['HOME'], '.gnupg')) if gpg.verify(cl): print "Signature correct" else: print "Signature incorrect" -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From asmodai at in-nomine.org Fri Aug 14 17:41:50 2009 From: asmodai at in-nomine.org (Jeroen Ruigrok van der Werven) Date: Fri, 14 Aug 2009 23:41:50 +0200 Subject: Natural Language Processing in Python In-Reply-To: References: Message-ID: <20090814214150.GM30241@nexus.in-nomine.org> -On [20090814 18:39], Prateek (prateekkakirwar at gmail.com) wrote: >Can somebody please provide me link to a good online resource or e- >book for doing natural language processing programming in Python. http://www.nltk.org/ comes to mind. -- Jeroen Ruigrok van der Werven / asmodai ????? ?????? ??? ?? ?????? http://www.in-nomine.org/ | http://www.rangaku.org/ | GPG: 2EAC625B Death comes for us all, we can only choose how to face it when it comes. From piet at cs.uu.nl Fri Aug 14 17:48:43 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 14 Aug 2009 23:48:43 +0200 Subject: Splitting on '^' ? References: Message-ID: >>>>> kj (k) wrote: >k> Sometimes I want to split a string into lines, preserving the >k> end-of-line markers. In Perl this is really easy to do, by splitting >k> on the beginning-of-line anchor: >k> @lines = split /^/, $string; >k> But I can't figure out how to do the same thing with Python. E.g.: >>>>> import re >>>>> re.split('^', 'spam\nham\neggs\n') >k> ['spam\nham\neggs\n'] >>>>> re.split('(?m)^', 'spam\nham\neggs\n') >k> ['spam\nham\neggs\n'] >>>>> bol_re = re.compile('^', re.M) >>>>> bol_re.split('spam\nham\neggs\n') >k> ['spam\nham\neggs\n'] >k> Am I doing something wrong? It says that in the doc of 're': Note that split will never split a string on an empty pattern match. For example: >>> re.split('x*', 'foo') ['foo'] >>> re.split("(?m)^$", "foo\n\nbar\n") ['foo\n\nbar\n'] -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From rurpy at yahoo.com Fri Aug 14 18:01:29 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Fri, 14 Aug 2009 15:01:29 -0700 (PDT) Subject: Splitting on '^' ? References: Message-ID: On Aug 14, 2:23?pm, kj wrote: > Sometimes I want to split a string into lines, preserving the > end-of-line markers. ?In Perl this is really easy to do, by splitting > on the beginning-of-line anchor: > > ? @lines = split /^/, $string; > > But I can't figure out how to do the same thing with Python. ?E.g.: Why not this? >>> lines = 'spam\nham\neggs\n'.splitlines (True) >>> lines ['spam\n', 'ham\n', 'eggs\n'] From pinkisntwell at gmail.com Fri Aug 14 18:24:26 2009 From: pinkisntwell at gmail.com (pinkisntwell) Date: Fri, 14 Aug 2009 15:24:26 -0700 (PDT) Subject: Calling parent constructor with different argument list Message-ID: <174a97e2-5ef4-47dc-9a60-ad7598f276cb@h21g2000yqa.googlegroups.com> class Vertex(tuple): pass class Positioned_Vertex(Vertex): def __init__(self, a, b): Vertex.__init__(a) a=Positioned_Vertex((0,0,0), 1) This gives: TypeError: tuple() takes at most 1 argument (2 given) It looks like the explicit call to Vertex.__init__ is never made and Vertex.__init__ is implicitly called when a Positioned_Vertex is created. Is there a way to work around this and call the constructor with the intended argument list? From lists at cheimes.de Fri Aug 14 18:25:00 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 15 Aug 2009 00:25:00 +0200 Subject: callable virtual method In-Reply-To: <4A85D051.2080004@sequans.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> <4A85A47E.308@wiggly.org> <4A85ACEF.4090901@sequans.com> <4A85B9F7.4010201@ieee.org> <4A85D051.2080004@sequans.com> Message-ID: Jean-Michel Pichavant wrote: > talking about approaches: > > 1/ > class Interface: > def foo(self): > if self.__class__.foo == Interface.foo: > raise NotImplementedError > > 2/ > class Interface: > def foo(self): > self._foo() > > def _foo(sef): > raise NotImplementedError Please don't call it an interface when it's really an abstract base class. And abstract base classes are probably the solution the OP is looking for, http://docs.python.org/library/abc.html Christian From davigier at googlemail.com Fri Aug 14 18:27:40 2009 From: davigier at googlemail.com (David) Date: Fri, 14 Aug 2009 15:27:40 -0700 (PDT) Subject: How to launch a function at regular time intervals ? References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> <18ac9f9a-0cf2-409c-82b3-ea068f21dbf7@k19g2000yqn.googlegroups.com> Message-ID: With your help, Franck, I think I finally got it to work. This is how I did it: # In the main program, launch the 2 threads CStoreData and CTransferData, which will run indefinitely until they are stopped (if the threads were launched inside the while loop, there would be an infinitely growing number of threads CStoreData all doing the same thing, same for CTransferData) func_store_data = CStoreData() func_store_data.start() func_transfer_data = CTransferData() func_transfer_data.start() # While loop, just to keep the threads running until they are stopped at the end of the program. If there wasn't a while loop, the threads would be stopped right after they are launched. The while loop separates the "start" of the threads from the "stop" of the threads while 1 if end_condition: # terminate program break # break out of while loop # Stop all running threads at end func_store_data.stop() func_store_data.join() func_transfer_data.stop() func_transfer_data.join() Again thanks a lot to all of you for your precious help. David From davigier at googlemail.com Fri Aug 14 18:27:55 2009 From: davigier at googlemail.com (David) Date: Fri, 14 Aug 2009 15:27:55 -0700 (PDT) Subject: How to launch a function at regular time intervals ? References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> <18ac9f9a-0cf2-409c-82b3-ea068f21dbf7@k19g2000yqn.googlegroups.com> Message-ID: <7e7f762d-6727-4756-9e5e-72b894f9a9fb@o32g2000yqm.googlegroups.com> With your help, Franck, I think I finally got it to work. This is how I did it: # In the main program, launch the 2 threads CStoreData and CTransferData, which will run indefinitely until they are stopped (if the threads were launched inside the while loop, there would be an infinitely growing number of threads CStoreData all doing the same thing, same for CTransferData) func_store_data = CStoreData() func_store_data.start() func_transfer_data = CTransferData() func_transfer_data.start() # While loop, just to keep the threads running until they are stopped at the end of the program. If there wasn't a while loop, the threads would be stopped right after they are launched. The while loop separates the "start" of the threads from the "stop" of the threads while 1 if end_condition: # terminate program break # break out of while loop # Stop all running threads at end func_store_data.stop() func_store_data.join() func_transfer_data.stop() func_transfer_data.join() Again thanks a lot to all of you for your precious help. David From davigier at googlemail.com Fri Aug 14 18:28:06 2009 From: davigier at googlemail.com (David) Date: Fri, 14 Aug 2009 15:28:06 -0700 (PDT) Subject: How to launch a function at regular time intervals ? References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> <18ac9f9a-0cf2-409c-82b3-ea068f21dbf7@k19g2000yqn.googlegroups.com> Message-ID: <97ddbf4b-0a80-4ef3-88e6-73b02208ef13@w41g2000yqb.googlegroups.com> With your help, Franck, I think I finally got it to work. This is how I did it: # In the main program, launch the 2 threads CStoreData and CTransferData, which will run indefinitely until they are stopped (if the threads were launched inside the while loop, there would be an infinitely growing number of threads CStoreData all doing the same thing, same for CTransferData) func_store_data = CStoreData() func_store_data.start() func_transfer_data = CTransferData() func_transfer_data.start() # While loop, just to keep the threads running until they are stopped at the end of the program. If there wasn't a while loop, the threads would be stopped right after they are launched. The while loop separates the "start" of the threads from the "stop" of the threads while 1 if end_condition: # terminate program break # break out of while loop # Stop all running threads at end func_store_data.stop() func_store_data.join() func_transfer_data.stop() func_transfer_data.join() Again thanks a lot to all of you for your precious help. David From python at mrabarnett.plus.com Fri Aug 14 18:30:52 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 23:30:52 +0100 Subject: Splitting on '^' ? In-Reply-To: <4A85D506.7060104@stoneleaf.us> References: <4A85D506.7060104@stoneleaf.us> Message-ID: <4A85E59C.6020001@mrabarnett.plus.com> Ethan Furman wrote: > kj wrote: >> >> Sometimes I want to split a string into lines, preserving the >> end-of-line markers. In Perl this is really easy to do, by splitting >> on the beginning-of-line anchor: >> >> @lines = split /^/, $string; >> >> But I can't figure out how to do the same thing with Python. E.g.: >> >> >>>>> import re >>>>> re.split('^', 'spam\nham\neggs\n') >> >> ['spam\nham\neggs\n'] >> >>>>> re.split('(?m)^', 'spam\nham\neggs\n') >> >> ['spam\nham\neggs\n'] >> >>>>> bol_re = re.compile('^', re.M) >>>>> bol_re.split('spam\nham\neggs\n') >> >> ['spam\nham\neggs\n'] >> >> Am I doing something wrong? >> >> kynn > > As you probably noticed from the other responses: No, you can't split > on _and_ keep the splitby text. > You _can_ split and keep what you split on: >>> re.split("(x)", "abxcd") ['ab', 'x', 'cd'] You _can't_ split on a zero-width match: >>> re.split("(x*)", "abxcd") ['ab', 'x', 'cd'] but you can use re.sub to replace zero-width matches with something that's not zero-width and then split on that (best with str.split): >>> re.sub("(x*)", "@", "abxcd") '@a at b@c at d@' >>> re.sub("(x*)", "@", "abxcd").split("@") ['', 'a', 'b', 'c', 'd', ''] From martin at v.loewis.de Fri Aug 14 18:40:56 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 15 Aug 2009 00:40:56 +0200 Subject: coding for multiple versions of python In-Reply-To: References: <4A84F913.9090901@v.loewis.de> Message-ID: <4a85e7f8$0$2427$9b622d9e@news.freenet.de> >> Specifically, put the source code into /net/source/python/foo/*.py. >> Then, on each system, put symlinks to all .py files into >> lib/site-packages/foo. Then Python will place the .pyc files next >> to the symlinks, not next to the actual .py files. > > Why would he need two sets of .py files? As Dave explains: So that the Python 2.4 installation on HP can write its own .pyc files on disk next to the source files, and Python 2.6 can write its .pyc files next to the sources on Linux. Regards, Martin From python at mrabarnett.plus.com Fri Aug 14 18:40:59 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 14 Aug 2009 23:40:59 +0100 Subject: How to launch a function at regular time intervals ? In-Reply-To: References: <6ebb8c71-870c-4233-a256-a4061a1ab530@k19g2000yqn.googlegroups.com> <18ac9f9a-0cf2-409c-82b3-ea068f21dbf7@k19g2000yqn.googlegroups.com> Message-ID: <4A85E7FB.4040507@mrabarnett.plus.com> David wrote: > With your help, Franck, I think I finally got it to work. This is how > I did it: > > # In the main program, launch the 2 threads CStoreData and > CTransferData, which will run indefinitely until they are stopped (if > the threads were launched inside the while loop, there would be an > infinitely growing number of threads CStoreData all doing the same > thing, same for CTransferData) > > func_store_data = CStoreData() > func_store_data.start() > > func_transfer_data = CTransferData() > func_transfer_data.start() > > # While loop, just to keep the threads running until they are stopped > at the end of the program. If there wasn't a while loop, the threads > would be stopped right after they are launched. The while loop > separates the "start" of the threads from the "stop" of the threads > > while 1 > if end_condition: # terminate program > break # break out of while loop > You might want to insert a sleep or something in there, otherwise you'll be it'll consume a lot of CPU time doing nothing (a 'busy wait'). > # Stop all running threads at end > > func_store_data.stop() > func_store_data.join() > > func_transfer_data.stop() > func_transfer_data.join() > > > Again thanks a lot to all of you for your precious help. > From martin at v.loewis.de Fri Aug 14 18:42:54 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 15 Aug 2009 00:42:54 +0200 Subject: coding for multiple versions of python In-Reply-To: References: <4A84F913.9090901@v.loewis.de> Message-ID: <4A85E86E.6070805@v.loewis.de> > He's assuming: > 1) an OS that supports symlinks > 2) two versions of Python on same system > 3) one set of pure-python sources that want to stay in synch for both > versions. Actually, the OP said he has HP(-UX, I assume), and Linux, so it would be two versions of Python on different systems - I also assume that he has an NFS server that both can mount (or that one machine can NFS mount the other). Regards, Martin From REMOVEmagicus23THIS at gmail.com Fri Aug 14 18:46:46 2009 From: REMOVEmagicus23THIS at gmail.com (magicus) Date: Fri, 14 Aug 2009 22:46:46 +0000 (UTC) Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: On Fri, 14 Aug 2009 19:57:17 +0200, Jean-Michel Pichavant wrote: > vippstar wrote: >> On Aug 14, 8:25 pm, fortunatus wrote: >> >>> On Aug 14, 1:01 pm, vippstar wrote: >>> >>> >>>> Why would you fill your website with junk? >>>> >>> The OP made it clear: >>> >>> >>>> Just wanted to express some frustration with whitespace-mode. >>>> >>>> >> You took my question out of context and answered it. I read the >> article, it's not like I missed any of it. Plus, it's not a real >> answer. "Because I wanted to". Why did you? Why would you? >> > FYI, Xah Lee is a well known BTFL (Benevolent Troller For Life), you > shouldn't argue about one of his post. Argue??? He is kill filed here wherever I find him. Life is too short to deal w/ idiots. ciao, f -- "Properly read, the Bible is the most potent force for atheism ever conceived." -- Isaac Asimov From Brian.Mingus at colorado.edu Fri Aug 14 18:57:13 2009 From: Brian.Mingus at colorado.edu (Brian) Date: Fri, 14 Aug 2009 16:57:13 -0600 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode In-Reply-To: References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: <9839a05c0908141557s4008e896nc5ddece003469596@mail.gmail.com> On Fri, Aug 14, 2009 at 4:46 PM, magicus wrote: > On Fri, 14 Aug 2009 19:57:17 +0200, Jean-Michel Pichavant > wrote: > > > vippstar wrote: > >> On Aug 14, 8:25 pm, fortunatus wrote: > >> > >>> On Aug 14, 1:01 pm, vippstar wrote: > >>> > >>> > >>>> Why would you fill your website with junk? > >>>> > >>> The OP made it clear: > >>> > >>> > >>>> Just wanted to express some frustration with whitespace-mode. > >>>> > >>>> > >> You took my question out of context and answered it. I read the > >> article, it's not like I missed any of it. Plus, it's not a real > >> answer. "Because I wanted to". Why did you? Why would you? > >> > > FYI, Xah Lee is a well known BTFL (Benevolent Troller For Life), you > > shouldn't argue about one of his post. > > Argue??? He is kill filed here wherever I find him. > > Life is too short to deal w/ idiots. > > ciao, > f > The funny thing about his rant (ie - that it is irrelevant) is that emacs python mode has always notified me that my indentations were inconsistent by highlighting the errant ones in blue. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Fri Aug 14 19:13:56 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Aug 2009 16:13:56 -0700 Subject: Splitting on '^' ? In-Reply-To: <4A85E59C.6020001@mrabarnett.plus.com> References: <4A85D506.7060104@stoneleaf.us> <4A85E59C.6020001@mrabarnett.plus.com> Message-ID: <4A85EFB4.3020008@stoneleaf.us> MRAB wrote: > Ethan Furman wrote: > >> kj wrote: >> >>> >>> Sometimes I want to split a string into lines, preserving the >>> end-of-line markers. In Perl this is really easy to do, by splitting >>> on the beginning-of-line anchor: >>> >>> @lines = split /^/, $string; >>> >>> But I can't figure out how to do the same thing with Python. E.g.: >>> >>> >>>>>> import re >>>>>> re.split('^', 'spam\nham\neggs\n') >>> >>> >>> ['spam\nham\neggs\n'] >>> >>>>>> re.split('(?m)^', 'spam\nham\neggs\n') >>> >>> >>> ['spam\nham\neggs\n'] >>> >>>>>> bol_re = re.compile('^', re.M) >>>>>> bol_re.split('spam\nham\neggs\n') >>> >>> >>> ['spam\nham\neggs\n'] >>> >>> Am I doing something wrong? >>> >>> kynn >> >> >> As you probably noticed from the other responses: No, you can't split >> on _and_ keep the splitby text. >> > You _can_ split and keep what you split on: > > >>> re.split("(x)", "abxcd") > ['ab', 'x', 'cd'] > > You _can't_ split on a zero-width match: > > >>> re.split("(x*)", "abxcd") > ['ab', 'x', 'cd'] > > but you can use re.sub to replace zero-width matches with something > that's not zero-width and then split on that (best with str.split): > > >>> re.sub("(x*)", "@", "abxcd") > '@a at b@c at d@' > >>> re.sub("(x*)", "@", "abxcd").split("@") > ['', 'a', 'b', 'c', 'd', ''] Wow! I stand corrected, although I'm in danger of falling over from the dizziness! :) As impressive as that is, I don't think it does what the OP is looking for. rurpy reminded us (or at least me ;) of .splitlines(), which seems to do exactly what the OP is looking for. I do take some comfort that my little snippet works for more than newlines alone, although I'm not aware of any other use-cases. :( ~Ethan~ Oh, hey, how about this? re.compile('(^[^\n]*\n?)', re.M).findall('text\ntext\ntext) Although this does give me an extra blank segment at the end... oh well. From breamoreboy at yahoo.co.uk Fri Aug 14 19:19:40 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Aug 2009 00:19:40 +0100 Subject: Calling parent constructor with different argument list In-Reply-To: <174a97e2-5ef4-47dc-9a60-ad7598f276cb@h21g2000yqa.googlegroups.com> References: <174a97e2-5ef4-47dc-9a60-ad7598f276cb@h21g2000yqa.googlegroups.com> Message-ID: pinkisntwell wrote: > class Vertex(tuple): > pass > > class Positioned_Vertex(Vertex): > > def __init__(self, a, b): def __init__(self, a): # just take out b > Vertex.__init__(a) > > a=Positioned_Vertex((0,0,0), 1) a=Positioned_Vertex( ( (0,0,0), 1) ) # and add a pair of brackets print a > > This gives: > > TypeError: tuple() takes at most 1 argument (2 given) > > It looks like the explicit call to Vertex.__init__ is never made and > Vertex.__init__ is implicitly called when a Positioned_Vertex is > created. Is there a way to work around this and call the constructor > with the intended argument list? Simplest way to get it to work is above using Python 2.6.2 on Windows. I'm sure there are variations depending on your use case, but I'll leave that to the experts. -- Kindest regards. Mark Lawrence. From arphaksad at gmail.com Fri Aug 14 20:05:40 2009 From: arphaksad at gmail.com (naaman) Date: Fri, 14 Aug 2009 17:05:40 -0700 (PDT) Subject: fileinput References: <521d7322-b8ee-490e-8cde-7e854e8afb7a@r34g2000vba.googlegroups.com> Message-ID: <4a237015-1b6d-418c-9bce-2f8e144e50d1@s15g2000yqs.googlegroups.com> On Aug 13, 11:41?pm, naaman wrote: > On Aug 13, 7:50?am, Dave Angel wrote: > > > > > naaman wrote: > > > On Aug 12, 1:35 pm, Dave Angel wrote: > > > >> naaman wrote: > > > >>> I'm writing my first Python script and > > >>> I want to use fileinput to open a file in r+ mode. > > >>> Tried fileinput.input(sys.argv[1:],"r+") but that didn't work. > > >>> ANy ideas? > > > >>> Need to find and overwrite a line in a file several times. > > >>> I can do it using open and seek() etc. but was wondering if I can use > > >>> fileinput. > > > >>> thanks; > > > >> I haven't used it, but check out the 'inplace' keyword parameter. > > > >> DaveA > > > > I've only Python for a week so I'm not sure what inplace does > > > You should read the docs for it > > ? ? (http://www.python.org/doc/2.6.2/library/fileinput.html?), > > but it's not very clear to me either ?So I dug up an example on the web: > > ? ? ?(ref: ?http://effbot.org/librarybook/fileinput.htm) > > > import fileinput, sys > > > for line in fileinput.input(inplace=1): > > ? ? # /convert Windows/DOS text files to Unix files/ > > ? ? if line[-2:] == "\r\n": > > ? ? ? ? line = line[:-2] + "\n" > > ? ? sys.stdout.write(line) > > > The inplace argument tells it to create a new file with the same name as > > the original (doing all the necessary nonsense with using a scratch > > file, and renaming/deleting) for each file processed. ?Stdout is pointed > > to that new version of the file. ?Notice that you have to explicitly > > write everything you want to wind up in the file -- if a given line is > > to remain unchanged, you just write "line" directly. > > > If you're new to Python, I do not recommend trying to do open/seek to > > update a text file in place, especially if you're in DOS. ?There are > > lots of traps. ?the inplace method of fileinput avoids these by > > implicitly creating temp files and handling the details for you, which > > probably works great if you're dealing with text, in order. > > > DaveA > > here's the solution > > import fileinput, sys > > for line in fileinput.input(sys.argv[1],inplace=1): > ? ? if (line[:-1]==r'drew'): > ? ? ? ? line=line.replace(line,"fancy dog") > ? ? sys.stdout.write(line) > > I want to replace drew in my input file with fancy dog. > Tested with this input file > angel > heaven > flying monkees > lazy dogs > drew > blue sky > veritas > > and got this > angel > heaven > flying monkees > lazy dogs > fancy dog > blue sky > veritas > > So drew was replaced with fancy dog. > Thanks to your inputs I got this solved. :-)) oops there should be a +"\n" after "fancy dog" line=line.replace(line,"fancy dog"+"\n") From gagsl-py2 at yahoo.com.ar Fri Aug 14 20:15:52 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Aug 2009 21:15:52 -0300 Subject: Calling parent constructor with different argument list References: <174a97e2-5ef4-47dc-9a60-ad7598f276cb@h21g2000yqa.googlegroups.com> Message-ID: En Fri, 14 Aug 2009 19:24:26 -0300, pinkisntwell escribi?: > class Vertex(tuple): > pass > > class Positioned_Vertex(Vertex): > > def __init__(self, a, b): > Vertex.__init__(a) > > a=Positioned_Vertex((0,0,0), 1) > > This gives: > > TypeError: tuple() takes at most 1 argument (2 given) > > It looks like the explicit call to Vertex.__init__ is never made and > Vertex.__init__ is implicitly called when a Positioned_Vertex is > created. Is there a way to work around this and call the constructor > with the intended argument list? The tuple constructor (like numbers, strings, and other immutable objects) never calls __init__. You have to override __new__ instead: py> class Point3D(tuple): ... def __new__(cls, x, y, z): ... obj = super(Point3D, cls).__new__(cls, (x,y,z)) ... return obj ... py> a = Point3D(10, 20, 30) py> a (10, 20, 30) py> type(a) See http://docs.python.org/reference/datamodel.html#basic-customization -- Gabriel Genellina From candide at free.invalid Fri Aug 14 20:22:57 2009 From: candide at free.invalid (candide) Date: Sat, 15 Aug 2009 02:22:57 +0200 Subject: Splitting a string into substrings of equal size Message-ID: <4a85ffe2$0$24643$426a34cc@news.free.fr> Suppose you need to split a string into substrings of a given size (except possibly the last substring). I make the hypothesis the first slice is at the end of the string. A typical example is provided by formatting a decimal string with thousands separator. What is the pythonic way to do this ? For my part, i reach to this rather complicated code: # ---------------------- def comaSep(z,k=3, sep=','): z=z[::-1] x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] return sep.join(x) # Test for z in ["75096042068045", "509", "12024", "7", "2009"]: print z+" --> ", comaSep(z) # ---------------------- outputting : 75096042068045 --> 75,096,042,068,045 509 --> 509 12024 --> 12,024 7 --> 7 2009 --> 2,009 Thanks From gagsl-py2 at yahoo.com.ar Fri Aug 14 21:00:52 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 14 Aug 2009 22:00:52 -0300 Subject: Splitting a string into substrings of equal size References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: En Fri, 14 Aug 2009 21:22:57 -0300, candide escribi?: > Suppose you need to split a string into substrings of a given size > (except > possibly the last substring). I make the hypothesis the first slice is > at the > end of the string. > A typical example is provided by formatting a decimal string with > thousands > separator. > > > What is the pythonic way to do this ? py> import locale py> locale.setlocale(locale.LC_ALL, '') 'Spanish_Argentina.1252' py> locale.format("%d", 75096042068045, True) '75.096.042.068.045' :) > For my part, i reach to this rather complicated code: Mine isn't very simple either: py> def genparts(z): ... n = len(z) ... i = n%3 ... if i: yield z[:i] ... for i in xrange(i, n, 3): ... yield z[i:i+3] ... py> ','.join(genparts("75096042068045")) '75,096,042,068,045' -- Gabriel Genellina From pfeldman at verizon.net Fri Aug 14 21:25:45 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Fri, 14 Aug 2009 18:25:45 -0700 (PDT) Subject: Python 'for' loop is memory inefficient Message-ID: <24980842.post@talk.nabble.com> I wrote the following correct but inefficient test of primality for purposes of demonstrating that the simplest algorithm is often not the most efficient. But, when I try to run the following code with a value of n that is large enough to produce a significant amount of running time, I get an out-of-memory error! def is_prime(n): for j in range(2,n): if (n % j) == 0: return False return True It seems as though Python is actually expanding range(2,n) into a list of numbers, even though this is incredibly wasteful of memory. There should be a looping mechanism that generates the index variable values incrementally as they are needed. -- View this message in context: http://www.nabble.com/Python-%27for%27-loop-is-memory-inefficient-tp24980842p24980842.html Sent from the Python - python-list mailing list archive at Nabble.com. From ethan at stoneleaf.us Fri Aug 14 21:30:39 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Aug 2009 18:30:39 -0700 Subject: implementing descriptors In-Reply-To: <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> Message-ID: <4A860FBF.6070709@stoneleaf.us> dippim wrote: > On Aug 14, 10:48 am, Dave Angel wrote: > >>dippim wrote: >> >>>On Aug 14, 2:34 am, Raymond Hettinger wrote: >> >>>>[David] >> >>>>>I am new to Python and I have a question about descriptors. If I have >>>>>a class as written below, is there a way to use descriptors to be >>>>>certain that the datetime in start is always before the one in end? >> >>>>>class foo(object): >>>>> def __init__(self,a =one,b = None) >>>>> self.start = >>>>> self.end = >> >>>>>from datetime import datetime >>>>>c =atetime(2009,8,13,6,15,0) >>>>>d =atetime(2009,8,14,12,0,0) >>>>>afoo =oo(c,d) >> >>>>>For instance, if the following code were run, I would like to instance >>>>>of foo to switch the start and end times. >> >>>>>afoo.start =atetime(2010,8,13,6,15,0) >> >>>>>I was thinking of using the __set__ descriptor to catch the assignment >>>>>and reverse the values if necessary, but I can't figure out how to >>>>>determine which values is being set. >> >>>>You're on the right track, but it is easier to use property() than to >>>>write your own custom descriptor with __get__ and __set__. >> >>>>class foo(object): >>>> def __init__(self,a =one,b = None): >>>> self._start = >>>> self._end = >>>> def get_start(self): >>>> return self._start >>>> def set_start(self, value): >>>> if self._end is None or value < self._end: >>>> self._start =alue >>>> else: >>>> self._end =alue >>>> start =roperty(get_start, set_start) >>>> def get_end(self): >>>> return self._end >>>> def set_end(self, value): >>>> if self._start is None or value > self._start: >>>> self._end =alue >>>> else: >>>> self._start =alue >>>> end =roperty(get_end, set_end) >> >>>>Raymond >> >>>Raymond, >>> This functionality is exactly what I was looking for. Thanks! I'll >>>be using this to solve my problem. >> >>> Now that I'm on the right track, I'm still a bit confused about how >>>__get__ and __set__ are useful. Admittedly, I don't need to >>>understand them to solve this problem, but perhaps they may be useful >>>in the future. If I wanted to solve this problem using __get__ and >>>__set__ could it be done? >> >>>Thanks Again! >> >>DANGER- WILL ROBINSON! >> >>Don't use this code as-is. There is a nasty surprise waiting for the >>caller when he sets start and end, and discovers that one of them gets >>thrown out, and an old value still remains. >> >>obj= foo(3, 5) >>obj.start = 8 >>obj.end = 12 >>print obj.start, obj.end >> >>will print out 3, 12. Not what the caller expected. > > > You're right about this and I appreciate the warning, but I think what > Raymond was going for was directional accuracy without a great deal of > his time wasted on details. The explanation served the purpose of > moving me forward using property() and I'm thankful for it. > > >>Four fixes, in order of preference: >>0) Trust your user to read and obey your docstrings. This was what JM >>was implying, by changing the names of the formal parameters. > > > Considering I am not the sharpest knife in the drawer, I don't wish to > start a philosophical discussion about the relative aptitude and > capabilities of the people who might use a class I build. However, I > will say that as this particular requirement is imposed on this class > by the writer, shouldn't it be the writer's responsibility to enforce > it, especially, when the cost of enforcement is so low? > > >>1) make a new method that sets both values, making these two properties >>readonly. That new method would make sure the two parameters are >>self-consistent. Making the actual values readonly can be done with a >>descriptor as well, or even a decorator. > > >>2) Raise an exception in the getter methods if they're out of order >>3) do the min/max logic on the getter methods, but I don't like that one >>at all. >> >>DaveA > I am in complete agreement with DaveA on this issue -- if you want the invariant, then have a routine that set's both at once. The head-aches it would cause me, at least, to have to gyrate around whether I was making the object later or earlier in time (having to swap the order I assign stand and end, assuming I even know whether I'm going forward or backward without further checking... argh!) would quite possibly cause me to choose some other routine instead. How about something like (untested): def set(self, start=None, end=None): if start is None: start = self.start if end is None: end = self.end if start > end: raise ValueError('blah blah') self.start = start self.end = end This way you could still set only one, but have bounds checking in place. ~Ethan~ From apt.shansen at gmail.com Fri Aug 14 21:30:43 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Fri, 14 Aug 2009 18:30:43 -0700 Subject: Python 'for' loop is memory inefficient In-Reply-To: <24980842.post@talk.nabble.com> References: <24980842.post@talk.nabble.com> Message-ID: <7a9c25c20908141830i5c72e0c1i66343c0e9017f0ca@mail.gmail.com> > > It seems as though Python is actually expanding range(2,n) into a list of > numbers, even though this is incredibly wasteful of memory. There should be > a looping mechanism that generates the index variable values incrementally > as they are needed. This has nothing to do with Python's for loop (and saying the loop construct itself is memory inefficient makes me blink in confusion): but you've isolated the problem precisely all on your own. range() is defined as returning a list. Thus, it constructs the list all at once. xrange() returns an iterator, and generates the values on the fly. In Python 3, this was changed so range returns an iterator, and to get a list you do list(range(2,n)). --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Fri Aug 14 21:36:14 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Aug 2009 18:36:14 -0700 Subject: Programming by Contract In-Reply-To: References: <4A7A15CD.9090306@stoneleaf.us> <4A81C6B8.7010605@stoneleaf.us> Message-ID: <4A86110E.5050201@stoneleaf.us> Charles Yeomans wrote: > > On Aug 14, 2009, at 12:09 AM, Scott David Daniels wrote: > >> Charles Yeomans wrote: >> >>> On Aug 11, 2009, at 3:30 PM, Ethan Furman wrote: >> >>>> Ethan Furman wrote: >> >>>>> Greetings! >> >>>>> I have seen posts about the assert statement and PbC (or maybe it >>>>> was DbC), and I just took a very brief look at pycontract >>>>> (http://www.wayforward.net/pycontract/) and now I have at least one >>>>> question: Is this basically another way of thinking about unit >>>>> testing, or is the idea of PbC more along the lines of *always* >>>>> checking the input/output of functions to ensure they are correct? >>>>> (*Contstant vigilance!* as Prof Moody would say ;) >> >>>>> I know asserts can be turned off, so they obviously won't work for >>>>> the latter case, and having seen the sample of pycontract it seems >>>>> it only does its thing during debugging. >> >>>>> So is Design (Programming) by Contract a fancy way of saying >>>>> "Document your inputs/outputs!" or is there more to it? >> >>>>> ~Ethan~ >> >>>> >>>> Hmmm... >> >>>> >>>> Well, from the (apparently) complete lack of interest, I shall take >>>> away the (better?) documentation ideas and unit testing ideas, and >>>> not worry about the rest. :) >> >>>> >>>> >>> Design by contract is complementary to unit testing (I notice that >>> the author of PEP 316 appears confused about this). DbC is, roughly >>> speaking, about explicit allocation of responsibility. Consider this >>> contrived example. >> >>> def foo(s): >> >>> require(s is not None) >> >>> //code >> >>> ensure(hasattr(returnValue, '__iter__')) >> >> >> yo might want two flags, REQUIRE_OFF, and ENSURE_ON that control >> testing, and change the code above to: >> require(REQUIRE_OFF or s is not None) >> //code >> ensure(ENSURE_OFF or hasattr(returnValue, '__iter__')) >> >> Python has no good way to turn off argument calculation by >> manipulating function definition (at least that I know of). >> > > For this purpose, it had occurred to me to do something like the following. > > def require(condition): > if condition: > return True > else: > raise PreconditionFailure > > > def foo(s): > assert require(s is not None) > > > Then it occurred to me to actually read the assert documentation, where > I learned that one can pass a second expression to assert. So instead > one might write > > assert precondition, "PreconditionFailure" > > though I think I prefer the former. > > > Charles Yeomans > And in either case, since such checks can have a *huge* impact on performance, it is good that asserts can be disabled with the -O optimize switch. So it's also good that the original design for DbC was an _understanding_ of who is responsible for what, as opposed to _code_ to actually enforce it. ~Ethan~ From breamoreboy at yahoo.co.uk Fri Aug 14 21:38:18 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Aug 2009 02:38:18 +0100 Subject: Python 'for' loop is memory inefficient In-Reply-To: <24980842.post@talk.nabble.com> References: <24980842.post@talk.nabble.com> Message-ID: Dr. Phillip M. Feldman wrote: > I wrote the following correct but inefficient test of primality for purposes > of demonstrating that the simplest algorithm is often not the most > efficient. But, when I try to run the following code with a value of n that > is large enough to produce a significant amount of running time, I get an > out-of-memory error! > > def is_prime(n): > for j in range(2,n): > if (n % j) == 0: return False > return True > > It seems as though Python is actually expanding range(2,n) into a list of > numbers, even though this is incredibly wasteful of memory. There should be > a looping mechanism that generates the index variable values incrementally > as they are needed. I have a strong suspicion that you will find hints in the Python documentation that this has already been addressed. Perhaps you could try reading before posting? -- Kindest regards. Mark Lawrence. From ethan at stoneleaf.us Fri Aug 14 21:43:42 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 14 Aug 2009 18:43:42 -0700 Subject: Python 'for' loop is memory inefficient In-Reply-To: <24980842.post@talk.nabble.com> References: <24980842.post@talk.nabble.com> Message-ID: <4A8612CE.7080700@stoneleaf.us> Dr. Phillip M. Feldman wrote: > I wrote the following correct but inefficient test of primality for purposes > of demonstrating that the simplest algorithm is often not the most > efficient. But, when I try to run the following code with a value of n that > is large enough to produce a significant amount of running time, I get an > out-of-memory error! > > def is_prime(n): > for j in range(2,n): > if (n % j) == 0: return False > return True > > It seems as though Python is actually expanding range(2,n) into a list of > numbers, even though this is incredibly wasteful of memory. There should be > a looping mechanism that generates the index variable values incrementally > as they are needed. You already have an answer to the range issue, so I will only add that putting a loop inside another loop is a decent way to expand the time taken. I will also observe that if you were to stop programming whatever language you are more familiar with in Python, and start programming Python in Python, you'll have an easier time of it. The Dive Into Python is an excellent start for that. ~Ethan~ From tjreedy at udel.edu Fri Aug 14 21:53:13 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 15 Aug 2009 10:53:13 +0900 Subject: implementing descriptors In-Reply-To: <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> <85502415-f861-43ab-8827-4184952d8bea@g23g2000vbr.googlegroups.com> Message-ID: dippim wrote: > will say that as this particular requirement is imposed on this class > by the writer, shouldn't it be the writer's responsibility to enforce > it, especially, when the cost of enforcement is so low? I would say that it is the writer's responsibility to set the requirement and be clear as to what it is and define the contract with respect to the requirement. The latter could either be user responsibility -- behavior explicitly undefined if violated -- or writer responsibility -- with either fix or raise exception upon violation detection. Python's duck-typing style tends to put responsibility on callers. Consider def minmidmax(seq): seq.sort() n = len(seq) return seq[0], seq[n//2], seq[n-1] This requires that seq have sane .sort, .__len__, and .__getitem__ methods. Checks could be added, but most Python programs would simply say the the input must be an in-place sortable sequence. Terry Jan Reedy From rt8396 at gmail.com Fri Aug 14 22:01:26 2009 From: rt8396 at gmail.com (r) Date: Fri, 14 Aug 2009 19:01:26 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: Message-ID: On Aug 14, 8:25?pm, "Dr. Phillip M. Feldman" wrote: > I wrote the following correct but inefficient test of primality for purposes > of demonstrating that the simplest algorithm is often not the most > efficient. ?But, when I try to run the following code with a value of n that > is large enough to produce a significant amount of running time, I get an > out-of-memory error! I don't think Python was created to keep mathematician's happy. Although strangely enough, the creator holds a masters degree in mathematics *and* computer science. Just another one of life's little ironies ;) From tjreedy at udel.edu Fri Aug 14 22:03:42 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 15 Aug 2009 11:03:42 +0900 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <7el2mqF2gi53eU1@mid.individual.net> References: <7el2mqF2gi53eU1@mid.individual.net> Message-ID: greg wrote: > You can't read and write with the same stdio file object > at the same time. Odd things tend to happen if you try. I believe the C standard specifies that the behavior of mixed reads and writes is undefined without intervening seek and/or flush, even if the seek is ignored (as it is on some Unix systems). With two threads, the timing is undetermined. From zuo at chopin.edu.pl Fri Aug 14 22:17:35 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 15 Aug 2009 04:17:35 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: <4a85ffe2$0$24643$426a34cc@news.free.fr> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: 15-08-2009 candide wrote: > Suppose you need to split a string into substrings of a given size > (except > possibly the last substring). I make the hypothesis the first slice is > at the end of the string. > A typical example is provided by formatting a decimal string with > thousands separator. I'd use iterators, especially for longer strings... import itertools def separate(text, grouplen=3, sep=','): "separate('12345678') -> '123,456,78'" repeated_iterator = [iter(text)] * grouplen groups = itertools.izip_longest(fillvalue='', *repeated_iterator) strings = (''.join(group) for group in groups) # gen. expr. return sep.join(strings) def back_separate(text, grouplen=3, sep=','): "back_separate('12345678') -> '12,345,678'" repeated_iterator = [reversed(text)] * grouplen groups = itertools.izip_longest(fillvalue='', *repeated_iterator) strings = [''.join(reversed(group)) for group in groups] # list compr. return sep.join(reversed(strings)) print separate('12345678') print back_separate('12345678') # alternate implementation # (without "materializing" 'strings' as a list in back_separate): def separate(text, grouplen=3, sep=','): "separate('12345678') -> '12,345,678'" textlen = len(text) end = textlen - (textlen % grouplen) repeated_iterator = [iter(itertools.islice(text, 0, end))] * grouplen strings = itertools.imap(lambda *chars: ''.join(chars), *repeated_iterator) return sep.join(itertools.chain(strings, (text[end:],))) def back_separate(text, grouplen=3, sep=','): "back_separate('12345678') -> '12,345,678'" beg = len(text) % grouplen repeated_iterator = [iter(itertools.islice(text, beg, None))] * grouplen strings = itertools.imap(lambda *chars: ''.join(chars), *repeated_iterator) return sep.join(itertools.chain((text[:beg],), strings)) print separate('12345678') print back_separate('12345678') http://docs.python.org/library/itertools.html#recipes was the inspiration for me (especially grouper). Cheers, *j -- Jan Kaliszewski (zuo) From davea at ieee.org Fri Aug 14 22:25:18 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 14 Aug 2009 22:25:18 -0400 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A861C8E.4030602@ieee.org> Benjamin Kaplan wrote: > On Fri, Aug 14, 2009 at 12:42 PM, Douglas Alan wrote: > > >> P.S. Overloading "left shift" to mean "output" does indeed seem a bit >> sketchy, but in 15 years of C++ programming, I've never seen it cause >> any confusion or bugs. >> > > > > The only reason it hasn't is because people use it in "Hello World". I bet > some newbie C++ programmers get confused the first time they see << used to > shift. > > Actually, I've seen it cause confusion, because of operator precedence. The logical shift operators have a fairly high level priority, so sometimes you need parentheses that aren't obvious. Fortunately, most of those cases make compile errors. C++ has about 17 levels of precedence, plus some confusing associative rules. And operator overloading does *NOT* change precedence. DaveA From zuo at chopin.edu.pl Fri Aug 14 22:40:05 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 15 Aug 2009 04:40:05 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: 15-08-2009 Jan Kaliszewski wrote: > 15-08-2009 candide wrote: > >> Suppose you need to split a string into substrings of a given size >> (except >> possibly the last substring). I make the hypothesis the first slice is >> at the end of the string. >> A typical example is provided by formatting a decimal string with >> thousands separator. > > I'd use iterators, especially for longer strings... > > > import itertools [snip] Err... It's too late for coding... Now I see obvious and simpler variant: def separate(text, grouplen=3, sep=','): "separate('12345678') -> '123,456,78'" textlen = len(text) end = textlen - (textlen % grouplen) strings = (text[i:i+grouplen] for i in xrange(0, end, grouplen)) return sep.join(itertools.chain(strings, (text[end:],))) def back_separate(text, grouplen=3, sep=','): "back_separate('12345678') -> '12,345,678'" textlen = len(text) beg = textlen % grouplen strings = (text[i:i+grouplen] for i in xrange(beg, textlen, grouplen)) return sep.join(itertools.chain((text[:beg],), strings)) print separate('12345678') print back_separate('12345678') -- Jan Kaliszewski (zuo) From guthrie at mum.edu Fri Aug 14 23:20:34 2009 From: guthrie at mum.edu (guthrie) Date: Fri, 14 Aug 2009 20:20:34 -0700 (PDT) Subject: py-rrdTool - install fails References: Message-ID: On Aug 14, 3:39?pm, Christian Heimes wrote: > guthrie schrieb: > > > > > I want to do some rrd in a python cgi script, but am having trouble > > getting an easy install module. > > > py-rrdTool looks good, but is distributed in c source, and is missing > > a header file in the distribution. Thus the install fails when it > > tries to reference rrd.h which is not there. > > > Are there better rrd modules to use, or a compiled version of this, or > > other suggestions? > > -------------------------------------------------------------------------------------- > > building 'rrdtool._rrdtool' extension > > C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN\cl.exe /c /nologo / > > Ox /MD /W3 /GS- /DNDEBUG -I/usr/local\include "-IE:\PLang\Active Python > > \include" "-IE:\PLang\Active Python\PC" /Tcsrc/_rrdtoolmodule.c / > > Fobuild\temp.win32-2.6\Release\src/_rrdtoolmodule.obj > > _rrdtoolmodule.c > > src/_rrdtoolmodule.c(34) : fatal error C1083: Cannot open include > > file: 'rrd.h': No such file or directory > > error: command '"C:\Program Files\Microsoft Visual Studio 9.0\VC\BIN > > \cl.exe"' failed with exit status 2 > > > C:\Documents and Settings\guthrie\Desktop\py-rrdtool-0.2.1> > > rrd.h is part of the rrdtools. You need to install rrdtools plus all its > dependencies. Have a lot of fun ;) > > Christian Thanks; I got py-rrttool-0.2.1 from sourceforge, but in its src directory it has only 3 files, _rrdtoolmodule.c, rrd_extra.h, and rrd_format.h http://sourceforge.net/projects/py-rrdtool/files/py-rrdtool/0.2.1/ (same for site: http://www.nongnu.org/py-rrdtool/ ) Where should I be looking for other dependencies? I installed rrdtools.exe, and don't see any rrd.h file in that hierarchy. From magawake at gmail.com Fri Aug 14 23:28:32 2009 From: magawake at gmail.com (Mag Gam) Date: Fri, 14 Aug 2009 23:28:32 -0400 Subject: unittest Message-ID: <1cbd6f830908142028v638a4c06jf0f859be712e724c@mail.gmail.com> I am writing an application which has many command line arguments. For example: foo.py -args "bar bee" I would like to create a test suit using unittest so when I add features to "foo.py" I don't want to break other things. I just heard about unittest and would love to use it for this type of thing. so my question is, when I do these tests do I have to code them into foo.py? I prefer having a footest.py which will run the regression tests. Any thoughts about this? TIA From dieter at handshake.de Sat Aug 15 00:41:20 2009 From: dieter at handshake.de (Dieter Maurer) Date: 15 Aug 2009 06:41:20 +0200 Subject: httplib incredibly slow :-( In-Reply-To: References: <4A81D3CB.7080209@simplistix.co.uk> <4A82EFDC.70502@simplistix.co.uk> <4eb0089f0908121753o5ecf141dj304b21c3df0d3d6b@mail.gmail.com> Message-ID: Chris Withers writes on Thu, 13 Aug 2009 08:20:37 +0100: > ... > I've already established that the file downloads in seconds with > [something else], so I'd like to understand why python isn't doing the > same and fix the problem... A profile might help to understand what the time is used for. As almost all operations are not done in Python itself ("httplib" is really a very tiny wrapper above a socket), a C level profile may be necessary to understand the behaviour. Dieter From bouncyinc at gmail.com Sat Aug 15 00:46:19 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Fri, 14 Aug 2009 22:46:19 -0600 Subject: getting a "simple" program to work In-Reply-To: References: <50697b2c0908112146q6e12650dt914518166b4fae72@mail.gmail.com> Message-ID: I'm checking back with some new info. Apparently the maintainer of the ogss package indicated that this is definately an issue with the libgmail package. Now I have already submtted help to the maintainer of libgmail to get some help it making his project work again. I am also interesetd in how roundabout smtp support could be added to that program specifically print "Seding back results" account.sendMessage(tosend) print "Logging..." execd.append(int(maxmessage.id,16)) towrite = str(int(maxmessage.id,16))+"~ " for arg in command: towrite += arg+" " w.write(towrite+"\n") print "Listening for commands" in the code sample from ogss.py to take that subroutine and turn it around to allow the same arguments basically take the above and add ----------------------------------------- gmail_user = "" #Username gmail_pwd = "" #Password gmail_alt = " " #Alias ID gmail_alias = ""+gmail_alt #nickname mailing_list = "" class mailz: def __init__(self): self.files=[""] self.mail = MIMEMultipart() def attach(self,fil): self.files.append(fil) def mailprep(self,to, subject, text): self.to = to self.mail['From'] = gmail_alias self.mail['To'] = to self.mail['Subject'] = subject if (mailtoBcc !="") : self.mail['BCC'] = mailtoBcc text+="\n\n\n_________________________\nMail generated By PyGmS "+ver+"\n - Made By Djays\n http://djsh.net" self.mail.attach(MIMEText(text)) print self.files for attach in self.files: if (attach != "") : part = MIMEBase('application', 'octet-stream') part.set_payload(open(attach, 'rb').read()) Encoders.encode_base64(part) part.add_header('Content-Disposition','attachment; filename="%s"' % os.path.basename(attach)) self.mail.attach(part) def sendmail(self): self.mailServer = smtplib.SMTP("smtp.gmail.com", 587) self.mailServer.ehlo() self.mailServer.starttls() self.mailServer.ehlo() self.mailServer.login(gmail_user, gmail_pwd) self.mailServer.sendmail(gmail_user, self.to, self.mail.as_string()) self.mailServer.close() ---------------------------------------------------------------------------- I hate to sound like a newb but the problem is that I'm running into apathetic maintainers of the software in question which has yet to be redacted as "working" and at the present time I have to deal with multi-server conglomerates like "Request Tracker" or "Roundup" both of which are simply not authenticating into gmail at all. At first I thought this was an issue of the ssl certificates not working but hen how come it's possible to have any of the code working when it's just the sending? And how is it possible that generic but different code can be working when it's all broken? Not to sound in any way belligerent but when this would be my 5th program language to solve a simple problem I think this is solveable w/o having to resort to the equivalent to a half semester of CS I in python imho. On Wed, Aug 12, 2009 at 10:41 PM, John Haggerty wrote: > Just checking to see if this is more adequate to what you would have wanted > to see I didn't get any feedback so I wasn't quite sure of this at the > present time. > > > On Tue, Aug 11, 2009 at 11:02 PM, John Haggerty wrote: > >> >> >> On Tue, Aug 11, 2009 at 10:46 PM, Chris Rebert wrote: >> >>> On Sun, Aug 9, 2009 at 8:42 PM, John Haggerty >>> wrote: >>> > ok so I know this is one of those "weird" requests but here me out. >>> > So far I have an issue with a package for python called "libgmail" >>> which is >>> > basically a gmail interface for python to send messages remoetly. >>> > Works ok except that the 'sendMessage' routine is bad. >>> >>> How is it "bad" precisely? Be specific (e.g. error message(s), >>> description of observed incorrect behavior). >>> >> >> In regards to bad would be failing to transmit claiming that the submittal >> is wrong for the transmit string. >> >> (where username is my gmail username and "password" is my gmail password >> to the test account, 6666666969 is the mobile number in question '00' is my >> "carrier id" from the ogss code example which is just an array location from >> a preformatted part of the string [probably from wikipedia on mobile carrier >> email addresses to cell phones], I actually got desperate and commented out >> the first attempt to transmit which I located in the code as just the >> "instructions" the code fails on re-transmission, I later on looked at the >> file and located that it was a zero byte file of no content. The program >> itself looks for a command from the user's cell phone directly from mms sent >> to the target gmail account prefaced by "Ogss" and anything else is treated >> as a command but since the command failed on the first transmit I don't >> think it's the command per se). >> >> owner at bouncyinc:~/Desktop/OGSS$ python ogss.py username password >> 6666666969 00 >> Starting ogss >> Logfile at:/home/owner/ogss.log >> Opening log file for reading >> Parsing user input >> Connecting to Gmail >> Logging into Gmail >> Opening log file for writing >> Listening for commands >> Processing Command >> ls: unrecognized option `---------------------------------------------' >> Try `ls --help' for more information. >> Seding back results >> Traceback (most recent call last): >> File "ogss.py", line 127, in >> main(sys.argv) >> File "ogss.py", line 110, in main >> account.sendMessage(tosend) >> File "/usr/lib/python2.5/site-packages/libgmail.py", line 615, in >> sendMessage >> raise GmailSendError, resultInfo[SM_MSG] >> libgmail.GmailSendError: Please try again. >> >> I traced the result to the sendMessage routine and noted that anytime it >> tries to send anything it fails this also fails with the standard "docs" >> package for libgmail 0.30 docs from the maintainer's site. >> >> Now the part where it *does* fail is where it has an issue with looking at >> the trailing info but then it would have logged the info to the file and >> emailed me back junk (which it didn't) >> >> I assume this could be done on any system just replace 'ls' with 'dir' or >> the equivalent. >> >> >>> >>> > This is included in the above attachment >>> > it's used in a program called "ogss" which is an sms interface to gmail >>> to >>> > basically read gmail and then have a command done on a remote machine >>> and >>> > then spat out on the local machine to a log file that's opened and then >>> > emailed back >>> > problem is that the sending back routine fails. >>> >>> Which routine is that exactly? Please also specify exactly how it is >>> failing (e.g. error message(s), description of observed incorrect >>> behavior). >>> >>> I apologize if these questions are answered in comments in the >>> attachments, but to be honest, the fact that you didn't (or couldn't) >>> put the specific problematic sections of code (and/or error messages) >>> inline in your message makes it less likely that people (such as >>> myself) will try to help you due to the volume of code you're making >>> people wade through (i.e. people tend not to read large code dumps, >>> /especially/ in attachments). >>> >>> Cheers, >>> Chris >>> -- >>> http://blog.rebertia.com >>> >> That's ok I understand I hope that helps at least in part. > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From oraclebill at gmail.com Sat Aug 15 01:15:36 2009 From: oraclebill at gmail.com (Bill Jones) Date: Fri, 14 Aug 2009 22:15:36 -0700 (PDT) Subject: Python docs disappointing - group effort to hire writers? References: <09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com> <109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com> <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> <93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com> <96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com> Message-ID: On Aug 8, 3:27?pm, Mark Lawrence wrote: > Kee Nethery wrote: > > As someone trying to learn the language I want to say that the tone on > > this list towards people who are trying to learn Python ?feels like it > > has become anti-newbies. > > [snip] > > > Kee Nethery > > My gut feeling (which could of course be wrong) is that many hard core > Pythonistas are cheesed off with newbies who refuse to help themselves. The funny thing is that their response is to shutdown changes that are intended to *help* newbies help themselves. It seems self-defeating to me. From jonrascal at gmail.com Sat Aug 15 01:39:08 2009 From: jonrascal at gmail.com (Rascal) Date: Fri, 14 Aug 2009 22:39:08 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: Message-ID: <04359a4b-9336-4936-8a15-a845ecebe4ba@m7g2000prd.googlegroups.com> look at xrange -- http://docs.python.org/library/functions.html#xrange From jonrascal at gmail.com Sat Aug 15 02:08:14 2009 From: jonrascal at gmail.com (Rascal) Date: Fri, 14 Aug 2009 23:08:14 -0700 (PDT) Subject: Splitting a string into substrings of equal size References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <3842c750-9633-4e8e-84da-4853784bce64@v37g2000prg.googlegroups.com> I'm bored for posting this, but here it is: def add_commas(str): str_list = list(str) str_len = len(str) for i in range(3, str_len, 3): str_list.insert(str_len - i, ',') return ''.join(str_list) From chardster at gmail.com Sat Aug 15 02:24:00 2009 From: chardster at gmail.com (Richard Thomas) Date: Fri, 14 Aug 2009 23:24:00 -0700 (PDT) Subject: unittest References: Message-ID: <75330ab0-329c-4842-a5b0-ddf0ccefe8ea@r18g2000yqd.googlegroups.com> On Aug 15, 4:28?am, Mag Gam wrote: > I am writing an application which has many command line arguments. > For example: foo.py -args "bar bee" > > I would like to create a test suit using unittest so when I add > features to "foo.py" I don't want to break other things. I just heard > about unittest and would love to use it for this type of thing. > > so my question is, when I do these tests do I have to code them into > foo.py? I prefer having a footest.py which will run the regression > tests. Any thoughts about this? > > TIA You should certainly keep your test suite separate. There's a quick example of how to write unit tests in the unittest documentation: http://docs.python.org/library/unittest.html#basic-example Richard. From python at rcn.com Sat Aug 15 03:10:36 2009 From: python at rcn.com (Raymond Hettinger) Date: Sat, 15 Aug 2009 00:10:36 -0700 (PDT) Subject: implementing descriptors References: <39aff5a5-97ec-41f7-ab26-6e4d842b9c5c@r33g2000vbp.googlegroups.com> Message-ID: <8e92d272-ddf8-44ef-9bc9-86b60a5855e5@t11g2000prh.googlegroups.com> > Raymond, > ? ?This functionality is exactly what I was looking for. Thanks! ?I'll > be using this to solve my problem. > > ? ?Now that I'm on the right track, I'm still a bit confused about how > __get__ and __set__ are useful. ?Admittedly, I don't need to > understand them to solve this problem, but perhaps they may be useful > in the future. ?If I wanted to solve this problem using __get__ and > __set__ could it be done? The __get__ and __set__ methods are used to implement property() itself. So, if you didn't have property, you could roll your own version: class MyProperty(object): def __init__(self, fget, fset): self.fget = fget self.fset = fset def __get__(self, obj, objtype=None): return self.fget(obj) def __set__(self, obj, value): self.fset(obj, value) class foo(object): def __init__(self,a = None,b = None): self._start = a self._end = b def get_start(self): return self._start def set_start(self, value): if self._end is None or value < self._end: self._start = value else: self._end = value start = MyProperty(get_start, set_start) def get_end(self): return self._end def set_end(self, value): if self._start is None or value > self._start: self._end = value else: self._start = value end = MyProperty(get_end, set_end) Raymond From mobiledreamers at gmail.com Sat Aug 15 03:12:56 2009 From: mobiledreamers at gmail.com (mobiledreamers at gmail.com) Date: Sat, 15 Aug 2009 00:12:56 -0700 Subject: Natural Language Processing in Python In-Reply-To: <9fdb569a0908141126x19d2d4c5q6abc99de7e390f94@mail.gmail.com> References: <9fdb569a0908141126x19d2d4c5q6abc99de7e390f94@mail.gmail.com> Message-ID: Try this out Fotoroll does term extraction http://bit.ly/HCPDi So to get json output of list of terms post to http://fotoroll.com/findterms?json=true&text=Content+to+extract terms from Hope this helps Fotoroll Term extraction No limit on number of queries per day Yahoo 5000 queries a day Zemanta 1000 queries a day with regn On Fri, Aug 14, 2009 at 11:26 AM, Vlastimil Brom wrote: > 2009/8/14 Prateek : > > Hi, > > > > Can somebody please provide me link to a good online resource or e- > > book for doing natural language processing programming in Python. > > > > Thanks, > > Prateek > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > Maybe you could start with NLTK > http://www.nltk.org/ > Check the toolkit as well as the documentation. > > hth > vbr > -- > http://mail.python.org/mailman/listinfo/python-list > -- Bidegg worlds best auction site http://bidegg.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From dmitrey.kroshko at scipy.org Sat Aug 15 03:17:04 2009 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sat, 15 Aug 2009 00:17:04 -0700 (PDT) Subject: "for" cycle with assigning index Message-ID: <4149f0b2-603d-4c59-aa34-bd0fd826303c@b14g2000yqd.googlegroups.com> Hi all, could you inform me how to do it properly? I have the cycle for i in xrange(len(Funcs2)): # Funcs2 is Python dict Funcs.append(lambda *args, **kwargs: (Funcs2[i](*args, **kwargs) [IndDict[left_arr_indexes[i]]])) So, all the Funcs are initialized with i = last index = len(Funcs2) When I involve for i in xrange(len(Funcs2)): Funcs.append(lambda i=i,*args, **kwargs: (Funcs2[i](*args, **kwargs)[IndDict[left_arr_indexes[i]]])) I get "list indices must be integers, not dict" (and i is equal to Python dictionary, that is Funcs2) So, how to do it correctly? Thank you in advance, D. From hendrik at microcorp.co.za Sat Aug 15 03:29:13 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 09:29:13 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <20090814135837.11286.700809778.divmod.xquotient.174@localhost.localdomain> References: <200908141538.15798.hendrik@microcorp.co.za> <20090814135837.11286.700809778.divmod.xquotient.174@localhost.localdomain> Message-ID: <200908150929.13885.hendrik@microcorp.co.za> On Friday 14 August 2009 15:58:37 exarkun at twistedmatrix.com wrote: > One strategy you might employ to get rid of the busy looping is to use > Twisted and its serial port support. This also addresses the full- > duplex issue you've raised. I know - vaguely - about twisted and I have been dancing around the fire, not really ready to put the time in to understand it properly. Looks like the time has come though - my weekend is really going to hell. I am now going to make a loopback connector and start playing. Thanks to everybody for the feedback. - Hendrik From pavlovevidence at gmail.com Sat Aug 15 03:39:59 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Aug 2009 00:39:59 -0700 (PDT) Subject: "for" cycle with assigning index References: <4149f0b2-603d-4c59-aa34-bd0fd826303c@b14g2000yqd.googlegroups.com> Message-ID: <6a5fd53a-1c29-48d3-b3cc-c48350acc736@a37g2000prf.googlegroups.com> On Aug 15, 12:17?am, dmitrey wrote: > Hi all, > could you inform me how to do it properly? > > I have the cycle > > for i in xrange(len(Funcs2)): # Funcs2 is Python dict > ? ? ?Funcs.append(lambda *args, **kwargs: (Funcs2[i](*args, **kwargs) > [IndDict[left_arr_indexes[i]]])) > > So, all the Funcs are initialized with i = last index = len(Funcs2) > > When I involve > > for i in xrange(len(Funcs2)): > ? ? ?Funcs.append(lambda i=i,*args, **kwargs: (Funcs2[i](*args, > **kwargs)[IndDict[left_arr_indexes[i]]])) > > I get "list indices must be integers, not dict" (and i is equal to > Python dictionary, that is Funcs2) > > So, how to do it correctly? > Thank you in advance, D. Define a helper function to do it: def create_funcs_caller(i): def func(*args,**kwargs): return(Funcs2[i](*args,**kwargs)[IndDict[left_arr_indexes [i]]])) retirm func for i in xrange(len(Funcs2)): Funcs.append(create_funcs_caller(i)) (I prefer to do it this way in any case; never liked the keyword argument hack way of doing it.) Carl Banks From hendrik at microcorp.co.za Sat Aug 15 03:52:21 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 09:52:21 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <200908150952.21825.hendrik@microcorp.co.za> On Friday 14 August 2009 16:19:04 Grant Edwards wrote: > On 2009-08-14, Hendrik van Rooyen wrote: > > In the meantime I have had another idea which I have also not tried yet, > > namely to do independent opens for reading and writing, to give me two > > file instances instead of one, and to try with that. I have no idea if > > it would make any difference, or even work at all. > > That should work (and shouldn't make any difference) > > > My normal stuff works, but I do not like it as it is > > essentially busy looping with short sleeps in between. In the > > eBox, it uses most of the processor just to move a few bytes > > of I/O in and out between the serial port and the TCP/IP, and > > struggles to do that better than five times a second, while > > the message time on the 115200 baud port is only about 2 > > milliseconds. > > What platform are you using? I suppose it's possible that > there's something broken in the serial driver for that > particular hardware. Your experience seems to be exactly the opposite to mine - you are saying it should "just work" and I am seeing half duplex functionality. I have seen this on my development machine which is a dual processor of some gigs running SuSe Linux 10.3, as well as on the other end of a the scale - the eBox (a 400MHz 486 without floating point with 128 Mb of memory) running Slackware. Maybe it is in the way I set the port up, because that is the common thing. What I do is this: reterror = os.system('stty -F /dev/ttyS0 sane 115200 cread clocal raw -echo') It does not seem to make a difference if I do this before or after opening the port. Any comments from a Linux Guru? - Hendrik From hendrik at microcorp.co.za Sat Aug 15 04:09:02 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 10:09:02 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <7el95aF2h0d12U1@mid.uni-berlin.de> References: <7el95aF2h0d12U1@mid.uni-berlin.de> Message-ID: <200908151009.02540.hendrik@microcorp.co.za> On Friday 14 August 2009 16:03:22 Diez B. Roggisch wrote: > You should *really* just use pyserial. No hassle, instant satisfaction. :-) I have downloaded and had a quick look, and I see it is based on the standard library's serial.Serial class - another battery that I have not used before. And I see that serial.Serial looks like it uses os. calls, which is one of the things Greg mentioned. Curioser and Curioser. There was one thing I saw in a quick read of pyserial that I did not like as I cannot understand why it is done - if a timeout is set to less than a tenth of a second, then it is changed to be a tenth. - In a polling protocol that will limit you to poll only ten terminals a second, or less, and is a very long time if a message takes only a couple of millis to send. I am getting there - this time around I want to kill this problem dead because I seem to keep doing something wrong somewhere and I want to understand what it is and stop doing it. - Hendrik From hendrik at microcorp.co.za Sat Aug 15 04:14:39 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 10:14:39 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <200908151014.39683.hendrik@microcorp.co.za> On Friday 14 August 2009 16:19:36 Grant Edwards wrote: > On 2009-08-14, exarkun at twistedmatrix.com wrote: > > One strategy you might employ to get rid of the busy looping > > is to use Twisted and its serial port support. This also > > addresses the full- duplex issue you've raised. > > There are no such full-dulex issues. I will put an example together as soon as I have finished reading and answering the mail - maybe I am crazy and chasing angels. - Hendrik From http Sat Aug 15 04:15:13 2009 From: http (Paul Rubin) Date: 15 Aug 2009 01:15:13 -0700 Subject: "for" cycle with assigning index References: <4149f0b2-603d-4c59-aa34-bd0fd826303c@b14g2000yqd.googlegroups.com> <6a5fd53a-1c29-48d3-b3cc-c48350acc736@a37g2000prf.googlegroups.com> Message-ID: <7x1vndbii6.fsf@ruckus.brouhaha.com> Carl Banks writes: > def create_funcs_caller(i): > def func(*args,**kwargs): > return(Funcs2[i](*args,**kwargs)[IndDict[left_arr_indexes[i]]]) > retirm func > > for i in xrange(len(Funcs2)): > Funcs.append(create_funcs_caller(i)) I prefer to get rid of the index variable: def create_funcs_caller(f,ix): return lambda *args, **kw: f(*args,**kw)[ix] Funcs = list(create_funcs_caller(f,ix) for f,ix in zip(Funcs2, left_arr_indexes)) Or in point-free style: from itertools import starmap Funcs = starmap(create_funcs_caller, zip(Funcs2,left_arr_indexes)) From xahlee at gmail.com Sat Aug 15 04:18:39 2009 From: xahlee at gmail.com (Xah Lee) Date: Sat, 15 Aug 2009 01:18:39 -0700 (PDT) Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: Fresh out of the oven: ? How to use and setup Emacs's whitespace-mode http://xahlee.org/emacs/whitespace-mode.html Xah ? http://xahlee.org/ ? On Aug 13, 6:36 pm, Xah Lee wrote: > ? A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode > http://xahlee.org/UnixResource_dir/writ/emacs_whitespace-mode_problems.html > > plane text version follows: > -------------------------------------------------- > > A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode > > Xah Lee, 2009-08-13 > > Just wanted to express some frustration with whitespace-mode. > > Emacs 23, just released, has this whitespace-mode feature. It renders > spaces, tabs, newlines characters with a visible glyph. This feature, > is in Microsoft Word since about 1992. > > This feature is important in practical ways. For example, when you > work with ?tab separated line? files (CSV) that's a common format for > importing/exporting address books or spreadsheets. It's also important > in whitespace-significant langs such as Python. Or, in text processing > when placement of space and tabs matters in the output. > > All i wanted, is to make Space and Tab and Newline chars visible. > > However, the emacs whitespace-mode does much more than that. It is > designed for tech geeking control freaks to tune every aspect of white > space in his source code. The mode is filled with bells and whistles. > It distinguishes tabs mixed with spaces, EOLs mixed with spaces, EOLs > at beginning of file, EOLs at end of file, run on spaces at end of > line, lines that has nothing to do with white spaces but is simply > longer than 80 chars, etc. Each of these is rendered with different > foreground, background, colors, so that they cannot possibly escape > the notices of control freaks. > > By default, most of these are on, so that, when you turn on the mode, > most reasonable clean source code become this colorful rainbow > unreadable fuck. > > I tried to tune it, with my 10 years of emacs of fucking 16 hours of > using per day, and 3 years of elisp coding experience. But, after a > hour, it's confusion hell sans avail. > > O, that Alex idiot with his emacswiki, refused to lead emacswiki into > any readable state. All he can think about is my social skills. (See: > Problems of Emacswiki.) > > What the fuck motherfuck. Hi tech geekers, coding freaks, social > science ignoramus fucks, basic economics illiterate FSF fucks, freedom > abusing selfish ideologists fucks, Richard Stallman propagandist fuck, > we-try-to-be-easy-to-use linuxer idioting fucks, FUCK U. > > Xah > ? http://xahlee.org/ > > ? From hendrik at microcorp.co.za Sat Aug 15 04:32:17 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 10:32:17 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <1aGdnessDpUX6RjXnZ2dnUVZ_gCdnZ2d@posted.visi> References: <7el2mqF2gi53eU1@mid.individual.net> <1aGdnessDpUX6RjXnZ2dnUVZ_gCdnZ2d@posted.visi> Message-ID: <200908151032.17185.hendrik@microcorp.co.za> On Friday 14 August 2009 16:28:26 Grant Edwards wrote: > On 2009-08-14, greg wrote: > > Hendrik van Rooyen wrote: 8<--------------------------------------------------------------- > Doh! It didn't even occur to me that somebody would use python > "file" objects for serial ports, and I completely overlooked > the fact that the OP was doing that. > > In short: don't do that -- it just messes things up *grin* All right that makes me feel better - you were so adamant that there is no problem that I was starting to doubt my sanity. - So I hereby cancel the promise I have just made to put an example together. - It is no longer needed. > > Do not use Python file objects. Use the underlying file > descriptors: os.open(), os.read(), os.write(). That will > almost certainly solve your problems. > > If you want examples of os.xxxxx() usage, below is the > PosixSerial.py module that I use for Linux-only applications. > For cross-platform work, use pyserial (whose Posix support is > based on the code below). > 8< ---------------------------------PosixSerial.py---------------------------- Thanks that looks, on first inspection, similar to the serialposix.py module in the stdlib, but less cluttered. - Hendrik From pavlovevidence at gmail.com Sat Aug 15 04:41:53 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Aug 2009 01:41:53 -0700 (PDT) Subject: Python docs disappointing - group effort to hire writers? References: <09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com> <109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com> <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> <93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com> <96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com> Message-ID: <9e93859d-cfca-43ff-8bae-65308a8e1c4d@a39g2000pre.googlegroups.com> On Aug 14, 10:15?pm, Bill Jones wrote: > On Aug 8, 3:27?pm, Mark Lawrence wrote: > > My gut feeling (which could of course be wrong) is that many hard core > > Pythonistas are cheesed off with newbies who refuse to help themselves. > > The funny thing is that their response is to shutdown changes that are > intended > to *help* newbies help themselves. It seems self-defeating to me. Intended to help newbies doesn't necessarily mean it actually will help newbies. (Just sayin'.) Carl Banks From hendrik at microcorp.co.za Sat Aug 15 04:47:22 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 10:47:22 +0200 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <02957d23$0$20647$c3e8da3@news.astraweb.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: <200908151047.22231.hendrik@microcorp.co.za> On Friday 14 August 2009 18:11:52 Steven D'Aprano wrote: > On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: > > "I saw `cout' being shifted "Hello world" times to the left and stopped > > right there." --Steve Gonedes > > Assuming that's something real, and not invented for humour, I presume > that's describing something possible in C++. Am I correct? What the hell > would it actually do??? It would shift "cout" left "Hello World" times. It is unclear if the shift wraps around or not. It is similar to a banana *holding his hands apart about a foot* this colour. - Hendrik From clp2 at rebertia.com Sat Aug 15 04:48:30 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 15 Aug 2009 04:48:30 -0400 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <200908151047.22231.hendrik@microcorp.co.za> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <200908151047.22231.hendrik@microcorp.co.za> Message-ID: <50697b2c0908150148o1532b656od0582acf261311ad@mail.gmail.com> On Sat, Aug 15, 2009 at 4:47 AM, Hendrik van Rooyen wrote: > On Friday 14 August 2009 18:11:52 Steven D'Aprano wrote: >> On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: >> > "I saw `cout' being shifted "Hello world" times to the left and stopped >> > right there." ?--Steve Gonedes >> >> Assuming that's something real, and not invented for humour, I presume >> that's describing something possible in C++. Am I correct? What the hell >> would it actually do??? > > It would shift "cout" left "Hello World" times. > It is unclear if the shift wraps around or not. > > It is similar to a banana *holding his hands apart about a foot* this colour. > > - Hendrik I think you managed to successfully dereference the null pointer there... Cheers, Chris From hendrik at microcorp.co.za Sat Aug 15 04:50:43 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 10:50:43 +0200 Subject: Why does my ftp script quit after couple of hours? In-Reply-To: <337951bf-4d0d-4dde-95de-8e6d7d68a7f5@a13g2000yqc.googlegroups.com> References: <6ec34299-107d-48c7-a5bf-6a10d5911411@j9g2000vbp.googlegroups.com> <7elh1lF2h1rl0U1@mid.uni-berlin.de> <337951bf-4d0d-4dde-95de-8e6d7d68a7f5@a13g2000yqc.googlegroups.com> Message-ID: <200908151050.43954.hendrik@microcorp.co.za> On Friday 14 August 2009 18:25:50 kk wrote: > As far as robustness, I agree with your assestment. I guess my main > confusion with my result is that the console window just disappears. I > wonder if I can make the window stay even if it crashesor if there are > connection issues? I will createa seperate log file to see if I can > catch any issues in a log file. try opening python with the -i flag - then the console window hangs around after the script exits and you can examine variables and stuff. - Hendrik From sjmachin at lexicon.net Sat Aug 15 05:20:12 2009 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Aug 2009 02:20:12 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <24980842.post@talk.nabble.com> Message-ID: On Aug 15, 11:38?am, Mark Lawrence wrote: > Dr. Phillip M. Feldman wrote:> I wrote the following correct but inefficient test of primality for purposes > > of demonstrating that the simplest algorithm is often not the most > > efficient. ?But, when I try to run the following code with a value of n that > > is large enough to produce a significant amount of running time, I get an > > out-of-memory error! > > > def is_prime(n): > > ? ?for j in range(2,n): > > ? ? ? if (n % j) == 0: return False > > ? ?return True > > > It seems as though Python is actually expanding range(2,n) into a list of > > numbers, even though this is incredibly wasteful of memory. There should be > > a looping mechanism that generates the index variable values incrementally > > as they are needed. > > I have a strong suspicion that you will find hints in the Python > documentation that this has already been addressed. ?Perhaps you could > try reading before posting? Alternative hypothesis: the good doctor read the Python 3.x documentation but absent-mindedly ran Python 2.x From hendrik at microcorp.co.za Sat Aug 15 05:21:12 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 11:21:12 +0200 Subject: Python 'for' loop is memory inefficient In-Reply-To: <24980842.post@talk.nabble.com> References: <24980842.post@talk.nabble.com> Message-ID: <200908151121.12542.hendrik@microcorp.co.za> On Saturday 15 August 2009 03:25:45 Dr. Phillip M. Feldman wrote: > It seems as though Python is actually expanding range(2,n) into a list of > numbers, even though this is incredibly wasteful of memory. There should be > a looping mechanism that generates the index variable values incrementally > as they are needed. There is. Use xrange instead of range, and try again. And while you are about it, you may as well teach them that it is much better to do a multiplication than a division. -Hendrik From sleepy at cabbage.co.uk Sat Aug 15 05:25:19 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Sat, 15 Aug 2009 09:25:19 GMT Subject: get the pause status from amarok 2.1 References: <7eku4bF2gtku3U2@mid.uni-berlin.de> Message-ID: <3avhm.248709$bA.165466@newsfe16.ams2> On Fri, 14 Aug 2009 12:55:07 +0200, Diez B. Roggisch wrote: > Sleepy Cabbage schrieb: >> As the title says, I'm trying to find a way to get the pause status >> from amarok 2.1. >> >> I'm running kubuntu 9.04 with kde 4.2.2, python 2.6.2. >> >> Thanks in advance. > > Not at my linux-system right now, but dcop and the respective > python-module should help. > > Diez Thanks for you reply Diez. i'm sure that kde4.2 now uses qdbus instead of dcop and not sure whether amarok has the qdbus org.kde.amarok /Player GetStatus as it returns the following: qdbus: I don't know how to display an argument of type '(iiii)' From bh at izb.knu.ac.kr Sat Aug 15 05:34:38 2009 From: bh at izb.knu.ac.kr (Byung-Hee HWANG) Date: Sat, 15 Aug 2009 18:34:38 +0900 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: <861vnda09d.fsf@betla.izb.knu.ac.kr> Xah Lee writes: > ? A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode > http://xahlee.org/UnixResource_dir/writ/emacs_whitespace-mode_problems.html > [... snip 38 lines ...] OK, Xah, thanks for good writing, i'll read it 27 hours later. And i respect for your passion on Elisp, Python and text processing. BTW, i don't agree with your thought that you dislike FSF. FSF is not bad guy. Xah plz... Sincerely, -- "Don Michael." -- Peter Clemenza, "Chapter 31", page 435 From hendrik at microcorp.co.za Sat Aug 15 06:29:28 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 12:29:28 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: <7el2mqF2gi53eU1@mid.individual.net> Message-ID: <200908151229.29027.hendrik@microcorp.co.za> On Saturday 15 August 2009 04:03:42 Terry Reedy wrote: > greg wrote: > > You can't read and write with the same stdio file object > > at the same time. Odd things tend to happen if you try. > > I believe the C standard specifies that the behavior of mixed reads and > writes is undefined without intervening seek and/or flush, even if the > seek is ignored (as it is on some Unix systems). With two threads, the > timing is undetermined. For a serial port, flush on write makes some sense, but seek is complete nonsense because it is undefined, and besides- the point you try to seek to may never come around. So the message I am getting loud and clear is that the basic thing I am doing wrong is to use the ordinary python open() instead of os.open(). As for the timing in two threads - Yes you are right, but there is not a lot one can do about it - The right solution depends to a large extent on what you are doing - for instance, if you are writing a polling protocol (such as Burroughs poll-select, or Uniscope), then you want a loop that transmits something, and waits for an answer or time out. This is essentially half duplex, and in a high level language the natural structure to write this is in one thread. On the other hand, if you are writing a sliding window type protocol that is capable of pouring stuff into a link asynchronously from both ends, then the natural way to do it is to use two threads - one to handle incoming stuff, and the other to squirt out the data that must go out. If, as is true in my case, the source of outgoing data and the sink for incoming data is a TCP/IP socket, then one can accomplish this with blocking I/O quite efficiently, provided you have a third thread looking after overall timing Issues. For such a case, the timing is essentially determined by the flow of the data (provided of course that you can keep up with the link speed). When one introduces another variable into the equation, namely the requirement to do a transmission at least every n milliseconds, (a feel-good keepalive) then you need a time out on the sources, so that you can either do a transmission or raise an alarm because a reporting period was missed. So then you are back at a loop waiting for input or timeout, and doing a transmission afterwards. Only now there are two of them, facing in opposite directions. I think this sort of thing is better written at a lower level where one has access to the interrupts from the ports, as well as a timer interrupt to handle timing and timeout issues. But that is a lot of work, so I make do with python. - Hendrik From magawake at gmail.com Sat Aug 15 07:32:15 2009 From: magawake at gmail.com (Mag Gam) Date: Sat, 15 Aug 2009 07:32:15 -0400 Subject: unittest In-Reply-To: <75330ab0-329c-4842-a5b0-ddf0ccefe8ea@r18g2000yqd.googlegroups.com> References: <75330ab0-329c-4842-a5b0-ddf0ccefe8ea@r18g2000yqd.googlegroups.com> Message-ID: <1cbd6f830908150432v4a88ad86ge9a266b647088fca@mail.gmail.com> So, in this example: "import random" In my case I would do "import foo" ? is there anything I need to do for that? On Sat, Aug 15, 2009 at 2:24 AM, Richard Thomas wrote: > On Aug 15, 4:28?am, Mag Gam wrote: >> I am writing an application which has many command line arguments. >> For example: foo.py -args "bar bee" >> >> I would like to create a test suit using unittest so when I add >> features to "foo.py" I don't want to break other things. I just heard >> about unittest and would love to use it for this type of thing. >> >> so my question is, when I do these tests do I have to code them into >> foo.py? I prefer having a footest.py which will run the regression >> tests. Any thoughts about this? >> >> TIA > > You should certainly keep your test suite separate. There's a quick > example of how to write unit tests in the unittest documentation: > http://docs.python.org/library/unittest.html#basic-example > > Richard. > -- > http://mail.python.org/mailman/listinfo/python-list > From greg at cosc.canterbury.ac.nz Sat Aug 15 07:44:59 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 15 Aug 2009 23:44:59 +1200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: <7el2mqF2gi53eU1@mid.individual.net> Message-ID: <7enlcsF2fqpebU1@mid.individual.net> Terry Reedy wrote: > I believe the C standard specifies that the behavior of mixed reads and > writes is undefined without intervening seek and/or flush, even if the > seek is ignored (as it is on some Unix systems). With two threads, the > timing is undetermined. It's also possible that the stdio object is being locked while one of the threads is using it, which would also account for the observed half-duplex behaviour. Another good reason to steer clear of file objects! -- Greg From chris at simplistix.co.uk Sat Aug 15 07:55:37 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Sat, 15 Aug 2009 12:55:37 +0100 Subject: Python 2.6 still not giving memory back to the OS... Message-ID: <4A86A239.3030404@simplistix.co.uk> Hi All, I thought this was fixed back in Python 2.5, but I guess not? So, I'm playing in an interactive session: >>> from xlrd import open_workbook >>> b = open_workbook('some.xls',pickleable=0,formatting_info=1) At this point, top shows the process usage for python to be about 500Mb. That's okay, I'd expect that, b is big ;-) >>> del b However, it still does now, maybe the garbage collector needs a kick? >>> import gc >>> gc.collect() 702614 Nope, still 500Mb. What gives? How can I make Python give the memory its no longer using back to the OS? Okay, so maybe this is something to do with it being an interactive session? So I wrote this script: from xlrd import open_workbook import gc b = open_workbook('some.xls',pickleable=0,formatting_info=1) print 'opened' raw_input() del b print 'deleted' raw_input() gc.collect() print 'gc' raw_input() The raw inputs are there so I can check the memory usage in top. Even after the gc, Python still hasn't given the memory back to the OS :-( What am I doing wrong? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From contact at xavierho.com Sat Aug 15 08:09:50 2009 From: contact at xavierho.com (Xavier Ho) Date: Sat, 15 Aug 2009 22:09:50 +1000 Subject: What happened to __cmp__() in Python 3.x? Message-ID: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> Hey all, I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in the documentation. Is there a substitution for this special method in 3.1, or do I really have to define all six rich comparison methods to work it out? If this question has already been asked somewhere, I apologise in advance. Already googled around but I didn't find information on this. Any replies appreciated. Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Sat Aug 15 08:16:14 2009 From: contact at xavierho.com (Xavier Ho) Date: Sat, 15 Aug 2009 22:16:14 +1000 Subject: What's a good solution to implement rich comparison for user-defined classes? (was: What happened to __cmp__() in Python 3.x?) Message-ID: <2d56febf0908150516i7fb00b80ub3e9481c8bf3f3f9@mail.gmail.com> Never mind my last email. Google actually found me something at last. I also found this page: http://mail.python.org/pipermail/python-list/2008-November/688591.html That still uses a sloppy way of defining the special methods, and a little chunky. Is there a better way for the lazy me? Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Aug 15 08:25:00 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2009 12:25:00 GMT Subject: Python 'for' loop is memory inefficient References: Message-ID: <02969972$0$20647$c3e8da3@news.astraweb.com> On Fri, 14 Aug 2009 18:25:45 -0700, Dr. Phillip M. Feldman wrote: > It seems as though Python is actually expanding range(2,n) into a list > of numbers, even though this is incredibly wasteful of memory. There > should be a looping mechanism that generates the index variable values > incrementally as they are needed. Others have already pointed out to you that xrange() (for Python 2.x) does what you want. In Python 3.x, the old range() is gone for good, and xrange() renamed to just range(). However, I'd like to point out that your subject line is fundamentally incorrect. What you've discovered has *nothing* to do with for-loops: the for-loop will happily iterate over whatever object you pass to it (or at least try to, because not all objects are iterable). You might be thinking that Python requires you to write for-loops as for i in range(...): but that's not correct. The for-loop doesn't care what object comes after the "in" and before the ":", so long as it can iterate over it one item at a time: for i in [1, 3, 4, 5, 2, 0, -1, 8, 7, 6]: print i for c in "abcd": print c and many other variations will work perfectly fine. The memory-consumption you have discovered is a property of the range() function, not the for-loop: >>> L = range(2, 20) >>> L [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] Compare to xrange: >>> L = xrange(2, 20) >>> L xrange(2, 20) >>> list(L) # expand out into a list [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] By the way, both range() and xrange() take an optional 'stepsize' argument, defaulting to 1: >>> range(3, 20, 2) [3, 5, 7, 9, 11, 13, 15, 17, 19] help(range) and help(xrange) in the interactive interpreter are your friends. -- Steven From candide at free.invalid Sat Aug 15 08:28:27 2009 From: candide at free.invalid (candide) Date: Sat, 15 Aug 2009 14:28:27 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: <4a85ffe2$0$24643$426a34cc@news.free.fr> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <4a86a9eb$0$1557$426a34cc@news.free.fr> Thanks to all for your response. I particularly appreciate Rascal's solution. From steve at REMOVE-THIS-cybersource.com.au Sat Aug 15 08:39:47 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 15 Aug 2009 12:39:47 GMT Subject: unittest References: <75330ab0-329c-4842-a5b0-ddf0ccefe8ea@r18g2000yqd.googlegroups.com> Message-ID: <02969ce9$0$20647$c3e8da3@news.astraweb.com> On Sat, 15 Aug 2009 07:32:15 -0400, Mag Gam wrote: > So, in this example: > > "import random" > > In my case I would do "import foo" ? is there anything I need to do for > that? Suppose you have a file mymodule.py containing your code, and you want some unit tests. If you only have a few, you can probably put them inside mymodule.py, but let's say you have lots and want to keep them in a separate file. So create a new module mymoduletests.py, and start it like this: # mymoduletests.py import unittest import mymodule class MyTests(unittest.TestCase): # Inherit from the TestCase class. # Put your tests inside this class def test_module_has_docstring(self): """Fail if the module has no docstring, or if it is empty.""" docstring = mymodule.__doc__ self.assert_(docstring is not None) self.assert_(docstring.strip() != '') if __name__ == '__main__': # only execute this part when you run the module # not when you import it unittest.main() Now to actually run the tests, from command-line, type: python mymoduletests.py and hit enter. (You do this from the operating system shell, not the Python interactive interpreter.) You should see something like this: . ---------------------------------------------------------------------- Ran 1 tests in 0.001s OK -- Steven From michael at stroeder.com Sat Aug 15 08:40:35 2009 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Sat, 15 Aug 2009 14:40:35 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <4vmil6-ait.ln1@nb2.stroeder.com> Hendrik van Rooyen wrote: > In the past, on this group, I have made statements that said that on Linux, > the serial port handling somehow does not allow transmitting and receiving at > the same time, and nobody contradicted me. Despite all the good comments here by other skilled people I'd recommend to determine whether the transmission line to the devices accessed support full duplex. My knowledge is a bit rusty on this topic. But I vaguely remember having to deal with symmetric two-wire connections (RS-485) which were definitely limited to half-duplex by the wire. So the PC hardware was a normal serial port with the usual UART hardware device but the transmission protocols were limited to half-duplex. Ciao, Michael. From zuo at chopin.edu.pl Sat Aug 15 09:38:53 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 15 Aug 2009 15:38:53 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: <3842c750-9633-4e8e-84da-4853784bce64@v37g2000prg.googlegroups.com> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> <3842c750-9633-4e8e-84da-4853784bce64@v37g2000prg.googlegroups.com> Message-ID: Dnia 15-08-2009 o 08:08:14 Rascal wrote: > I'm bored for posting this, but here it is: > > def add_commas(str): > str_list = list(str) > str_len = len(str) > for i in range(3, str_len, 3): > str_list.insert(str_len - i, ',') > return ''.join(str_list) For short strings (for sure most common case) it's ok: simple and clear. But for huge ones, it's better not to materialize additional list for the string -- then pure-iterator-sollutions would be better (like Gabriel's or mine). Cheers, *j -- Jan Kaliszewski (zuo) From davea at ieee.org Sat Aug 15 09:44:25 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 15 Aug 2009 09:44:25 -0400 Subject: Python 2.6 still not giving memory back to the OS... In-Reply-To: <4A86A239.3030404@simplistix.co.uk> References: <4A86A239.3030404@simplistix.co.uk> Message-ID: <4A86BBB9.5010705@ieee.org> Chris Withers wrote: >
Hi All, > > I thought this was fixed back in Python 2.5, but I guess not? > > So, I'm playing in an interactive session: > > >>> from xlrd import open_workbook > >>> b = open_workbook('some.xls',pickleable=0,formatting_info=1) > > At this point, top shows the process usage for python to be about 500Mb. > That's okay, I'd expect that, b is big ;-) > > >>> del b > > However, it still does now, maybe the garbage collector needs a kick? > > >>> import gc > >>> gc.collect() > 702614 > > Nope, still 500Mb. What gives? How can I make Python give the memory > its no longer using back to the OS? > > Okay, so maybe this is something to do with it being an interactive > session? So I wrote this script: > > from xlrd import open_workbook > import gc > b = open_workbook('some.xls',pickleable=0,formatting_info=1) > print 'opened' > raw_input() > del b > print 'deleted' > raw_input() > gc.collect() > print 'gc' > raw_input() > > The raw inputs are there so I can check the memory usage in top. > Even after the gc, Python still hasn't given the memory back to the OS > :-( > > What am I doing wrong? > > Chris > You're not doing anything wrong. I don't know of any other environment that "gives the memory back" to the OS. I don't know Unix/Linux memory management, but I do know Windows, and I suspect the others are quite similar. There are a few memory allocators within Windows itself, and some more within the MSC runtime library. They work similarly enough that I can safely just choose one to explain. I'll pick on malloc(). When malloc() is called for the first time (long before your module is loaded), it asks the operating system's low-level mapping allocator for a multiple of 64k. The 64k will always be aligned on a 64k boundary, and is in turn divided into 4k pages. The 64k could come from one of three places - the swapfile, an executable (or DLL), or a data file, but there's not much real difference between those. malloc() itself will always use the swapfile. Anyway, at this point my memory is a little bit fuzzy. I think only 4k of the swapfile is actually mapped in, the rest being reserved. But malloc() will then build some data structures for that 64k block, and as memory is requested, get more and more pieces of that 64k, till the whole thing is mapped in. Then, additional multiples of 64k are allocated in the same way, and of course the data structures are chained together. If an application "frees" a block, the data structure is updated, but the memory is not unmapped. Theoretically, if all the blocks within one 64k were freed, malloc() could release the 64k block to the OS, but to the best of my knowledge, malloc() never does. Incidentally, there's a different scheme for large blocks, but that's changed several times, and I have no idea how it's done now. Now, C programmers sometimes write a custom allocator, and in C++, it's not hard to have a custom allocator manage all instances of a particular class. This can be convenient for applications that know how their memory usage patterns are likely to work. Photoshop for example can be configured to use "user swap space" (I forget what they call it) from files that Photoshop explicitly allocates. And space from that allocator is not from the swapfile, so it's not constrained by other running applications, and wouldn't be counted by the Windows equivalent of 'top' (eg. the Windows Task Manager). A custom allocator can also be designed to know when a particular set of allocations are all freed, and release the memory entirely back to the system. For instance, if all temp data for a particular transaction is put into an appropriate custom allocator, then at the end of the transaction, it can safely be released. I would guess that Python doesn't do any custom allocators, and therefore never releases the memory back to the system. It will however reuse it when you allocate more stuff. DaveA (author of the memory tracking subsystem of NuMega's BoundsChecker) From grante at visi.com Sat Aug 15 10:25:03 2009 From: grante at visi.com (Grant Edwards) Date: Sat, 15 Aug 2009 09:25:03 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: Message-ID: On 2009-08-15, Hendrik van Rooyen wrote: > On Friday 14 August 2009 16:19:04 Grant Edwards wrote: > >> What platform are you using? I suppose it's possible that >> there's something broken in the serial driver for that >> particular hardware. > > Your experience seems to be exactly the opposite to mine - you > are saying it should "just work" and I am seeing half duplex > functionality. If you're using Python's normal open()/read()/write() calls, then that introduces all sorts of issues. I always use direct OS calls os.open(), os.read(), os.write(). > Any comments from a Linux Guru? Are you using python file operations open/read/write or OS file-descriptor operations os.open/os.read/os.write? -- Grant From grante at visi.com Sat Aug 15 10:37:42 2009 From: grante at visi.com (Grant Edwards) Date: Sat, 15 Aug 2009 09:37:42 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: <7el95aF2h0d12U1@mid.uni-berlin.de> Message-ID: On 2009-08-15, Hendrik van Rooyen wrote: > On Friday 14 August 2009 16:03:22 Diez B. Roggisch wrote: > >> You should *really* just use pyserial. No hassle, instant satisfaction. > >:-) I have downloaded and had a quick look, and I see it is > based on the standard library's serial.Serial class - another > battery that I have not used before. There is no "serial" module in the standard library. The serial module is provided by pyserial. > And I see that serial.Serial looks like it uses os. calls, > which is one of the things Greg mentioned. Indeed. You shouldn't try to use normal open/read/write calls with serial ports. -- Grant From grante at visi.com Sat Aug 15 10:40:09 2009 From: grante at visi.com (Grant Edwards) Date: Sat, 15 Aug 2009 09:40:09 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: <7el2mqF2gi53eU1@mid.individual.net> <1aGdnessDpUX6RjXnZ2dnUVZ_gCdnZ2d@posted.visi> Message-ID: On 2009-08-15, Hendrik van Rooyen wrote: > 8< ---------------------------------PosixSerial.py---------------------------- > > Thanks that looks, on first inspection, similar to the > serialposix.py module in the stdlib, but less cluttered. pyserial is a bit more complex because it is cross-platform and supports Windows, as well as RFC2272 telnet backends (and OS X?). The Posix support in pyserial is based on an earlier version of PosixSerial. -- Grant From Scott.Daniels at Acm.Org Sat Aug 15 12:11:49 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 15 Aug 2009 09:11:49 -0700 Subject: callable virtual method In-Reply-To: References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> Message-ID: Jean-Michel Pichavant wrote: > Steven D'Aprano wrote: >> On Fri, 14 Aug 2009 18:49:26 +0200, Jean-Michel Pichavant wrote: >> >> >>> Sorry guys (means guys *and* gals :op ), I realized I've not been able >>> to describe precisely what I want to do. I'd like the base class to be >>> virtual (aka abstract). However it may be abstract but it does not mean >>> it cannot do some usefull stuff. >>> >>> >>> Here is the schema of my abstract methods : >>> >>> class Interface(object): >>> def method(self): >>> # --------------------- >>> # some common stuff executed here >>> # --------------------- >>> print 'hello world' >>> # --------------------- >>> # here shall stand child specific stuff (empty in the interface >>> method) >>> # --------------------- >>> if self.__class__.method == Interface.method: >>> raise NotImplementedError('You should have read the f****** >>> manual ! You must override this method.') >>> >> >> >> Okay, so I want to sub-class your Interface class. As you said, the >> methods in the abstract class are still useful, so in my class, I >> don't need any extra functionality for some methods -- I'm happy with >> just the "common stuff". So I use normal OO techniques and over-ride >> just the methods I need to over-ride: >> >> > Sometimes the base is doing cool stuff but incomplete stuff which > requires knowledge only hold by the sub class. In my case the interface > is a high level interface for a software that can run on multiple > hardware platforms. Only the sub class has knowledge on how to operate > the hardware, but no matter the hardware it still produces the same effect. > > Let's say I have 50 different hardwares, I'll have 50 sub classes of > Interface with the 'start' method to define. It wouldn't be appropriate > (OO programming)to write 50 times '_log.debug('Starting %s' % self)' in > each child start method when the simple task of logging the call can be > nicely handled by the base class. > > In the meantime, I must make sure the user, who is not a python guru in > this case, has implemented the start method for his hardware, because > only him knows how to effectively start this hardware. I don't want him > to come to me saying, "I got no error, still my hardware does not > start". You can then blame him for not reading the docs, but it will > still be less expensive to throw a nice exception with an accurate > feedback. > > [snip] >> class VerboseGoodChild(Interface): >> # forced to over-ride methods for no good reason >> > > Definitely no !! This is the purpose of an interface class: to force > people to write these methods. They *are* required, if they were not, > they would not belong to the Interface. > > JM But there _is_ one moment when you can check those things, then avoid checking thereafter: object creation. So you can complicate your __init__ (or __new__) with those checks that make sure you instantiate only fully defined subclasses: # obviously not tested except in concept: class Base(object_or_whatever): def __init__(self, ...): class_ = self.__class__ if class_ is Base: raise TypeError('Attempt to instantiate Base class') for name in 'one two three four': if getattr(Base, name) is not getattr(Base, name): raise NotImplementedError( '%s implementation missing' % name) ... --Scott David Daniels Scott.Daniels at Acm.Org From dickinsm at gmail.com Sat Aug 15 12:41:44 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 15 Aug 2009 09:41:44 -0700 (PDT) Subject: Python 2.6 still not giving memory back to the OS... References: Message-ID: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> On Aug 15, 12:55?pm, Chris Withers wrote: > Hi All, > > I thought this was fixed back in Python 2.5, but I guess not? > > So, I'm playing in an interactive session: > > ?>>> from xlrd import open_workbook > ?>>> b = open_workbook('some.xls',pickleable=0,formatting_info=1) > > At this point, top shows the process usage for python to be about 500Mb. > That's okay, I'd expect that, b is big ;-) > > ?>>> del b > > However, it still does now, maybe the garbage collector needs a kick? > > ?>>> import gc > ?>>> gc.collect() > 702614 > > Nope, still 500Mb. What gives? How can I make Python give the memory its > no longer using back to the OS? > [...] Can you get the same effects without using the xlrd module? I don't have xlrd installed on my system (OS X 10.5/Intel), but I just tried the following: Python 2.6.2 (r262:71600, Jun 17 2009, 09:08:27) [GCC 4.0.1 (Apple Inc. build 5490)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> b = 'x'*(10**9) >>> f = open('testfile.txt', 'w') >>> f.write(b) >>> del b >>> f = open('testfile.txt') >>> b = f.read() >>> del b and got the expected memory usage for my Python process, as displayed by top: memory usage went up to nearly 1Gb after each assignment to b, then dropped down to 19 Mb or so after each 'del b'. I get similar results under Python 2.5. So maybe there's something in xlrd that's hanging on to all that memory? Mark From breamoreboy at yahoo.co.uk Sat Aug 15 12:47:07 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Aug 2009 17:47:07 +0100 Subject: Python docs disappointing - group effort to hire writers? In-Reply-To: References: <09bf4f17-40a5-4bad-81d3-1950545b7570@g6g2000vbr.googlegroups.com> <109f1ff7-8fa9-40d3-80b4-1e90b5fc669c@d34g2000vbm.googlegroups.com> <756580E3-CFFA-404C-B66A-9F4281760C8E@kagi.com> <93b1f0d4-8b15-4b19-99d3-065495e387e6@s31g2000yqs.googlegro ups.com> <5.2.1.1.2.20090805210119.01c7cab8@blue-cove.com> <96ebd700-e48b-47b4-88a4-68b77cc8058d@m7g2000prd.googlegroups.com> Message-ID: Bill Jones wrote: > On Aug 8, 3:27 pm, Mark Lawrence wrote: >> Kee Nethery wrote: >>> As someone trying to learn the language I want to say that the tone on >>> this list towards people who are trying to learn Python feels like it >>> has become anti-newbies. >> [snip] >> >>> Kee Nethery >> My gut feeling (which could of course be wrong) is that many hard core >> Pythonistas are cheesed off with newbies who refuse to help themselves. > > The funny thing is that their response is to shutdown changes that are > intended > to *help* newbies help themselves. It seems self-defeating to me. > And I still do not believe this to be true. Documents are being changed all the time. See the python-dev mailing list "Summary of python tracker issues" dated 17/24/31 July and 07/14 August 2009. The only request I recall being rejected is someone objecting to the use of "weapons" in a piece of sample code. Also see Issue6660 on the bug tracker, it is of particular interest to anyone who's interested in plans for python.org documentation links. -- Kindest regards. Mark Lawrence. From markstahler at gmail.com Sat Aug 15 13:01:15 2009 From: markstahler at gmail.com (kramed) Date: Sat, 15 Aug 2009 10:01:15 -0700 (PDT) Subject: Error: No SSL support included in this Python ? Message-ID: Hi there, I am running Windows on my dev machine and am running into the following error while running Django and my email routines. Exception Type: RuntimeError Exception Value: No SSL support included in this Python Exception Location: C:\Python26\lib\smtplib.py in starttls, line 615 This may sounds stupid but I thought SSL support was baked into Python? I am running Active State Python 2.6.2 and Django 1.1. The code works on my server but emails are not being sent properly so I need to debug the app. Can someone please point out what I am missing. Thanks From breamoreboy at yahoo.co.uk Sat Aug 15 13:06:04 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Aug 2009 18:06:04 +0100 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> Message-ID: Xavier Ho wrote: > Hey all, > > I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in the > documentation. > > Is there a substitution for this special method in 3.1, or do I really have > to define all six rich comparison methods to work it out? > > If this question has already been asked somewhere, I apologise in advance. > Already googled around but I didn't find information on this. > > Any replies appreciated. > > Ching-Yun "Xavier" Ho, Technical Artist > > Contact Information > Mobile: (+61) 04 3335 4748 > Skype ID: SpaXe85 > Email: contact at xavierho.com > Website: http://xavierho.com/ > > http://bytes.com/topic/python/answers/844614-python-3-sorting-comparison-function -- Kindest regards. Mark Lawrence. From Scott.Daniels at Acm.Org Sat Aug 15 13:11:29 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 15 Aug 2009 10:11:29 -0700 Subject: unittest In-Reply-To: References: Message-ID: Mag Gam wrote: > I am writing an application which has many command line arguments. > For example: foo.py -args "bar bee" > > I would like to create a test suit using unittest so when I add > features to "foo.py" I don't want to break other things. I just heard > about unittest and would love to use it for this type of thing. > > so my question is, when I do these tests do I have to code them into > foo.py? I prefer having a footest.py which will run the regression > tests. Any thoughts about this? > > TIA I avoid putting the tests in foo.py, simply because the bulk of my tests would make the code harder to read. So, no, unittest does not require that you code things into foo.py. You will find that you may bend your coding style within foo.py in order to make it more testable, but (if you do it right) that should also make the code clearer. --Scott David Daniels Scott.Daniels at Acm.Org From breamoreboy at yahoo.co.uk Sat Aug 15 13:12:33 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sat, 15 Aug 2009 18:12:33 +0100 Subject: What's a good solution to implement rich comparison for user-defined classes? (was: What happened to __cmp__() in Python 3.x?) In-Reply-To: <2d56febf0908150516i7fb00b80ub3e9481c8bf3f3f9@mail.gmail.com> References: <2d56febf0908150516i7fb00b80ub3e9481c8bf3f3f9@mail.gmail.com> Message-ID: Xavier Ho wrote: > Never mind my last email. Google actually found me something at last. > > I also found this page: > http://mail.python.org/pipermail/python-list/2008-November/688591.html > > That still uses a sloppy way of defining the special methods, and a little > chunky. > > Is there a better way for the lazy me? > > Ching-Yun "Xavier" Ho, Technical Artist > > Contact Information > Mobile: (+61) 04 3335 4748 > Skype ID: SpaXe85 > Email: contact at xavierho.com > Website: http://xavierho.com/ > > Did you follow on to this? http://mail.python.org/pipermail/python-list/2008-November/688661.html I think it's your call as to what to do next. -- Kindest regards. Mark Lawrence. From hendrik at microcorp.co.za Sat Aug 15 13:18:53 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 19:18:53 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: <4vmil6-ait.ln1@nb2.stroeder.com> References: <4vmil6-ait.ln1@nb2.stroeder.com> Message-ID: <200908151918.54065.hendrik@microcorp.co.za> On Saturday 15 August 2009 14:40:35 Michael Str?der wrote: > Hendrik van Rooyen wrote: > > In the past, on this group, I have made statements that said that on > > Linux, the serial port handling somehow does not allow transmitting and > > receiving at the same time, and nobody contradicted me. > > Despite all the good comments here by other skilled people I'd recommend to > determine whether the transmission line to the devices accessed support > full duplex. > > My knowledge is a bit rusty on this topic. But I vaguely remember having to > deal with symmetric two-wire connections (RS-485) which were definitely > limited to half-duplex by the wire. So the PC hardware was a normal serial > port with the usual UART hardware device but the transmission protocols > were limited to half-duplex. You raise a good point, that is probably not well known amongst the youngsters here, as simple serial multidropping has gone out of fashion. There is nothing wrong with your memory as far as RS-485 goes - you have to "turn the line around", same as for *shudder* Burroughs TDI (Two Wire Direct Interface). Otherwise, if two or more parties talk at once you have cacophony. An RS-422 link is to some extent worse, as it is capable of full duplex, but the slaves cannot hear each other, so they have to listen and play very nicely with the master. This instance Is not one of those, thank heaven - I am on both sides of the link - once in the eBox in python, and on the other side there is just one Dallas chip - a fast (30 Mhz single cycle) 8051 lookalike that I programmed in assembler. It is a thing that does discrete I/O that we have made for a customer. The link in between is just RS-232 receive and transmit without hardware flow control or anything fancy. This is why I was so certain that there was something wrong in my python part, because I could use the second port on the Dallas to do monitoring, by spewing stuff out into Hyper Terminal. - Hendrik From python-url at phaseit.net Sat Aug 15 13:23:36 2009 From: python-url at phaseit.net (Gabriel Genellina) Date: Sat, 15 Aug 2009 17:23:36 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Aug 15) Message-ID: QOTW: "They questioned my competence and that made her very sad." - Roger Wallis,expert witness for Pirate Bay, on his wife http://torrentfreak.com/pirate-bay-witness-wife-overwhelmed-with-flowers-090227/ unicode(s) is, surprisingly, MUCH faster (for certain encodings) than s.decode(): http://groups.google.com/group/comp.lang.python/browse_thread/thread/314a3043ea63319f/ It is not possible to overload a compound "< <" operator (as in: a < x < b): http://groups.google.com/group/comp.lang.python/browse_thread/thread/5b931a6417b7829d/ Automatic join of "consecutive" " string " "literals": bug or feature? http://groups.google.com/group/comp.lang.python/browse_thread/thread/174d4e2b7c0203d/ Also, unrecognized escape sequences in string literals stay in the string: bug or feature? http://groups.google.com/group/comp.lang.python/browse_thread/thread/4e1ea6f550a8a1d1/ Restricting dictionary keys to those objects explicitely defining __eq__ / __hash__ may be useful in certain cases: http://groups.google.com/group/comp.lang.python/browse_thread/thread/d35856349110c18c/ How to find out in which module an instance was created? http://groups.google.com/group/comp.lang.python/browse_thread/thread/6acd71c326591325/ Monkey-patching an instance to make it callable (without altering other instances of the same class): http://groups.google.com/group/comp.lang.python/browse_thread/thread/6fdfc6458d82b581/ reload() and the 'from ... import ...' form of the import statement: http://groups.google.com/group/comp.lang.python/browse_thread/thread/994a6af36febabb5/ Several recipes to extract unique elements from a list: http://groups.google.com/group/comp.lang.python/t/e5015c12a57b46b8/ All those __double_underscored__ names are confusing - why do they exist? http://groups.google.com/group/comp.lang.python/t/e75ce772af98aaac/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiasts": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python Enjoy the *Python Magazine*. http://pymag.phparch.com/ *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From emile at fenx.com Sat Aug 15 13:28:00 2009 From: emile at fenx.com (Emile van Sebille) Date: Sat, 15 Aug 2009 10:28:00 -0700 Subject: Splitting a string into substrings of equal size In-Reply-To: <4a85ffe2$0$24643$426a34cc@news.free.fr> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: On 8/14/2009 5:22 PM candide said... > Suppose you need to split a string into substrings of a given size (except > possibly the last substring). I make the hypothesis the first slice is at the > end of the string. > A typical example is provided by formatting a decimal string with thousands > separator. > > > What is the pythonic way to do this ? I like list comps... >>> jj = '1234567890123456789' >>> ",".join([jj[ii:ii+3] for ii in range(0,len(jj),3)]) '123,456,789,012,345,678,9' >>> Emile From hendrik at microcorp.co.za Sat Aug 15 13:33:10 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 15 Aug 2009 19:33:10 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <200908151933.10803.hendrik@microcorp.co.za> On Saturday 15 August 2009 16:25:03 Grant Edwards wrote: > > Are you using python file operations open/read/write or OS > file-descriptor operations os.open/os.read/os.write? The former - that seems to be the source of my trouble. I have now written a little test that uses serial.Serial and it works a treat. I am still confused about pyserial and serial - I found serial in my distribution library, (on the SuSe machine, not on the 2.5 in Slackware) but I had to download pyserial. I see that you were the the original author. Thank you for letting this stuff loose in the wild. - Hendrik From lists at cheimes.de Sat Aug 15 14:05:36 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 15 Aug 2009 20:05:36 +0200 Subject: Python 2.6 still not giving memory back to the OS... In-Reply-To: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> References: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> Message-ID: <4A86F8F0.5060101@cheimes.de> Mark Dickinson wrote: > and got the expected memory usage for my Python process, as > displayed by top: memory usage went up to nearly 1Gb after > each assignment to b, then dropped down to 19 Mb or so after > each 'del b'. I get similar results under Python 2.5. I get the same results on Linux: Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os, psutil >>> pi = psutil.Process(os.getpid()) >>> [mem/1024.**2 for mem in pi.get_memory_info()] [4.71875, 28.2578125] >>> s = 'x' * (10**9) >>> [mem/1024.**2 for mem in pi.get_memory_info()] [958.40234375, 981.93359375] >>> del s >>> [mem/1024.**2 for mem in pi.get_memory_info()] [11.62890625, 55.1875] Christian From lists at cheimes.de Sat Aug 15 14:05:36 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 15 Aug 2009 20:05:36 +0200 Subject: Python 2.6 still not giving memory back to the OS... In-Reply-To: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> References: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> Message-ID: <4A86F8F0.5060101@cheimes.de> Mark Dickinson wrote: > and got the expected memory usage for my Python process, as > displayed by top: memory usage went up to nearly 1Gb after > each assignment to b, then dropped down to 19 Mb or so after > each 'del b'. I get similar results under Python 2.5. I get the same results on Linux: Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os, psutil >>> pi = psutil.Process(os.getpid()) >>> [mem/1024.**2 for mem in pi.get_memory_info()] [4.71875, 28.2578125] >>> s = 'x' * (10**9) >>> [mem/1024.**2 for mem in pi.get_memory_info()] [958.40234375, 981.93359375] >>> del s >>> [mem/1024.**2 for mem in pi.get_memory_info()] [11.62890625, 55.1875] Christian From roy at panix.com Sat Aug 15 14:17:39 2009 From: roy at panix.com (Roy Smith) Date: Sat, 15 Aug 2009 14:17:39 -0400 Subject: getting the fractional part of a real? Message-ID: What's the best way to get the fractional part of a real? The two ways I can see are r % 1 and r = int(r), but both seem a bit hokey. Is there something more straight-forward that I'm missing, like fraction(r)? From lists at cheimes.de Sat Aug 15 14:40:54 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 15 Aug 2009 20:40:54 +0200 Subject: getting the fractional part of a real? In-Reply-To: References: Message-ID: <4A870136.70306@cheimes.de> Roy Smith schrieb: > What's the best way to get the fractional part of a real? The two ways I > can see are r % 1 and r = int(r), but both seem a bit hokey. Is there > something more straight-forward that I'm missing, like fraction(r)? >>> import math >>> math.modf(1.5) (0.5, 1.0) Christian From gregor.lingl at aon.at Sat Aug 15 14:48:51 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sat, 15 Aug 2009 20:48:51 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: <4a85ffe2$0$24643$426a34cc@news.free.fr> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <4A870313.4040702@aon.at> > What is the pythonic way to do this ? > > > For my part, i reach to this rather complicated code: > > > # ---------------------- > > def comaSep(z,k=3, sep=','): > z=z[::-1] > x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] > return sep.join(x) > > # Test > for z in ["75096042068045", "509", "12024", "7", "2009"]: > print z+" --> ", comaSep(z) > Just if you are interested, a recursive solution: >>> def comaSep(z,k=3,sep=","): return comaSep(z[:-3],k,sep)+sep+z[-3:] if len(z)>3 else z >>> comaSep("7") '7' >>> comaSep("2007") '2,007' >>> comaSep("12024") '12,024' >>> comaSep("509") '509' >>> comaSep("75096042068045") '75,096,042,068,045' >>> Gregor From gregor.lingl at aon.at Sat Aug 15 14:49:45 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sat, 15 Aug 2009 20:49:45 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: <4a85ffe2$0$24643$426a34cc@news.free.fr> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <4a870358$0$2292$91cee783@newsreader02.highway.telekom.at> > What is the pythonic way to do this ? > > > For my part, i reach to this rather complicated code: > > > # ---------------------- > > def comaSep(z,k=3, sep=','): > z=z[::-1] > x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] > return sep.join(x) > > # Test > for z in ["75096042068045", "509", "12024", "7", "2009"]: > print z+" --> ", comaSep(z) > Just if you are interested, a recursive solution: >>> def comaSep(z,k=3,sep=","): return comaSep(z[:-3],k,sep)+sep+z[-3:] if len(z)>3 else z >>> comaSep("7") '7' >>> comaSep("2007") '2,007' >>> comaSep("12024") '12,024' >>> comaSep("509") '509' >>> comaSep("75096042068045") '75,096,042,068,045' >>> Gregor From dickinsm at gmail.com Sat Aug 15 14:50:00 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 15 Aug 2009 11:50:00 -0700 (PDT) Subject: getting the fractional part of a real? References: Message-ID: <9e6ce7f2-deba-4538-88f3-2d44ab5ada4b@e27g2000yqm.googlegroups.com> On Aug 15, 7:40?pm, Christian Heimes wrote: > Roy Smith schrieb: > > > What's the best way to get the fractional part of a real? ?The two ways I > > can see are r % 1 and r = int(r), but both seem a bit hokey. ?Is there > > something more straight-forward that I'm missing, like fraction(r)? > >>> import math > >>> math.modf(1.5) > > (0.5, 1.0) What Christian said. math.fmod(r, 1.0) also works. Note that r % 1 and r - int(r) aren't the same thing for negative reals. What sign do you want the result to have when r is negative? Mark From gregor.lingl at aon.at Sat Aug 15 14:50:03 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sat, 15 Aug 2009 20:50:03 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <4a87036a$0$2292$91cee783@newsreader02.highway.telekom.at> Emile van Sebille schrieb: > On 8/14/2009 5:22 PM candide said... ... >> What is the pythonic way to do this ? > > I like list comps... > > >>> jj = '1234567890123456789' > >>> ",".join([jj[ii:ii+3] for ii in range(0,len(jj),3)]) > '123,456,789,012,345,678,9' > >>> > > Emile > Less beautiful but more correct: >>> ",".join([jj[max(ii-3,0):ii] for ii in range(len(jj)%3,len(jj)+3,3)]) '1,234,567,890,123,456,789' Gregor From gregor.lingl at aon.at Sat Aug 15 14:55:55 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sat, 15 Aug 2009 20:55:55 +0200 Subject: getting the fractional part of a real? In-Reply-To: References: Message-ID: <4a8704ca$0$2292$91cee783@newsreader02.highway.telekom.at> Christian Heimes schrieb: > Roy Smith schrieb: >> What's the best way to get the fractional part of a real? The two >> ways I can see are r % 1 and r = int(r), but both seem a bit hokey. >> Is there something more straight-forward that I'm missing, like >> fraction(r)? > >>>> import math >>>> math.modf(1.5) > (0.5, 1.0) > > Christian Or without the need to import something: >>> divmod(1.5, 1) (1.0, 0.5) >>> Gregor From nagle at animats.com Sat Aug 15 15:24:26 2009 From: nagle at animats.com (John Nagle) Date: Sat, 15 Aug 2009 12:24:26 -0700 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode In-Reply-To: References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: <4a870a7b$0$1674$742ec2ed@news.sonic.net> fortunatus wrote: > On Aug 14, 1:01 pm, vippstar wrote: >> Why would you fill your website with junk? > > The OP made it clear: > >> Just wanted to express some frustration with whitespace-mode. Well, it took until Python 3.0 until Python enforced rules that ensured that the indentation the user sees is the same indentation the compiler sees. We finally have a solution that allows both tabs and spaces but disallows the situations which are ambiguous. Until Python 3.0 is fully deployed, there are situations when you need an insane level of tab/space visibility. Blame Python, not EMACS. John Nagle From nagle at animats.com Sat Aug 15 15:34:15 2009 From: nagle at animats.com (John Nagle) Date: Sat, 15 Aug 2009 12:34:15 -0700 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <24980842.post@talk.nabble.com> Message-ID: <4a870cc7$0$1674$742ec2ed@news.sonic.net> Hendrik van Rooyen wrote: > On Saturday 15 August 2009 03:25:45 Dr. Phillip M. Feldman wrote: > And while you are about it, you may as well teach them that it is much better > to do a multiplication than a division. Actually, division speed hasn't been much of an issue in years. Arithmetic has been faster than memory access since CPUs went superscalar. In CPython, with all the interpreter overhead, you'll probably never notice the difference. I'd thought "xrange" had already been obsoleted, and hadn't realized the 2.3 - 2.6 versions of CPython were still doing "range" the hard way, not as a generator. John Nagle From alan.isaac at gmail.com Sat Aug 15 15:49:35 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Sat, 15 Aug 2009 19:49:35 GMT Subject: random.gauss vs. random.normalvariate Message-ID: Quoting http://docs.python.org/3.1/library/random.html#random.gauss: Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the normalvariate() function defined below. So since both are offered and gauss is faster, I assume it must have some offsetting disadvantage. What is it? Thank you, Alan Isaac From roy at panix.com Sat Aug 15 16:01:25 2009 From: roy at panix.com (Roy Smith) Date: Sat, 15 Aug 2009 16:01:25 -0400 Subject: getting the fractional part of a real? References: <4a8704ca$0$2292$91cee783@newsreader02.highway.telekom.at> Message-ID: In article <4a8704ca$0$2292$91cee783 at newsreader02.highway.telekom.at>, Gregor Lingl wrote: > Christian Heimes schrieb: > > Roy Smith schrieb: > >> What's the best way to get the fractional part of a real? The two > >> ways I can see are r % 1 and r = int(r), but both seem a bit hokey. > >> Is there something more straight-forward that I'm missing, like > >> fraction(r)? > > > >>>> import math > >>>> math.modf(1.5) > > (0.5, 1.0) > > > > Christian > > Or without the need to import something: > > >>> divmod(1.5, 1) > (1.0, 0.5) > >>> > > Gregor Thanks. I knew I had to be missing something obvious. Regarding Mark Dickinson's question about what I want for negative reals, for the application I have in mind, r is guaranteed to be positive. From darkwater42 at gmail.com Sat Aug 15 16:01:43 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sat, 15 Aug 2009 13:01:43 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> On Aug 14, 10:25?pm, Dave Angel wrote: > Benjamin Kaplan wrote: > > On Fri, Aug 14, 2009 at 12:42 PM, Douglas Alan wrote: > >> P.S. Overloading "left shift" to mean "output" does indeed seem a bit > >> sketchy, but in 15 years of C++ programming, I've never seen it cause > >> any confusion or bugs. > > The only reason it hasn't is because people use it in "Hello World". I bet > > some newbie C++ programmers get confused the first time they see << used to > > shift. People typically get confused by a *lot* of things when they learn a new language. I think the better metric is how people fare with a language feature once they've grown accustomed to the language, and how long it takes them to acquire this familiarity. > Actually, I've seen it cause confusion, because of operator precedence. ? > The logical shift operators have a fairly high level priority, so > sometimes you need parentheses that aren't obvious. ?Fortunately, most > of those cases make compile errors. I've been programming in C++ so long that for me, if there's any confusion, it's the other way around. I see "<<" or ">>" and I think I/ O. I don't immediately think shifting. Fortunately, shifting is a pretty rare operation to actually use, which is perhaps why C++ reclaimed it for I/O. On the other hand, you are right that the precedence of "<<" is messed up for I/O. I've never seen a real-world case where this causes a bug in C++ code, because the static type-checker always seems to catch the error. In a dynamically typed language, this would be a much more serious problem. |>ouglas P.S. I find it strange, however, that anyone who is not okay with "abusing" operator overloading in this manner, wouldn't also take umbrage at Python's overloading of "+" to work with strings and lists, etc. Numerical addition and sequence concatenation have entirely different semantics. From bouncyinc at gmail.com Sat Aug 15 16:14:17 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 14:14:17 -0600 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <02957d23$0$20647$c3e8da3@news.astraweb.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> Message-ID: I guess the problem is---does it actually matter? On Fri, Aug 14, 2009 at 10:11 AM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > On Fri, 14 Aug 2009 07:07:31 -0700, Aahz wrote: > > > "I saw `cout' being shifted "Hello world" times to the left and stopped > > right there." --Steve Gonedes > > Assuming that's something real, and not invented for humour, I presume > that's describing something possible in C++. Am I correct? What the hell > would it actually do??? > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From wgwinder at gmail.com Sat Aug 15 16:17:02 2009 From: wgwinder at gmail.com (wgw) Date: Sat, 15 Aug 2009 13:17:02 -0700 (PDT) Subject: PyQt4.__file__ gives PyQt4/__init__.py as value Message-ID: <0b3b6163-3fb3-4b1b-9605-bf899f65b9e9@o6g2000yqj.googlegroups.com> I don't understand why the __file__ value in my installation of PyQt would not give a proper, full path. I'm guessing that I did not install pyqt properly (I'm on Ubuntu Hardy, trying to install QT4.5), but before redoing the install, I want to see if there is a quicker fix. Also, though PyQt4/ is in the site-packages directory, and loads properly into the interactive environment. Yolk does not list it. ??? Something strange here! Any suggestions? From metolone+gmane at gmail.com Sat Aug 15 16:22:39 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Sat, 15 Aug 2009 13:22:39 -0700 Subject: Splitting a string into substrings of equal size References: <4a85ffe2$0$24643$426a34cc@news.free.fr> <4a87036a$0$2292$91cee783@newsreader02.highway.telekom.at> Message-ID: "Gregor Lingl" wrote in message news:4a87036a$0$2292$91cee783 at newsreader02.highway.telekom.at... > Emile van Sebille schrieb: >> On 8/14/2009 5:22 PM candide said... > ... >>> What is the pythonic way to do this ? >> >> I like list comps... >> >> >>> jj = '1234567890123456789' >> >>> ",".join([jj[ii:ii+3] for ii in range(0,len(jj),3)]) >> '123,456,789,012,345,678,9' >> >>> >> >> Emile >> > > Less beautiful but more correct: > > >>> ",".join([jj[max(ii-3,0):ii] for ii in > range(len(jj)%3,len(jj)+3,3)]) > '1,234,567,890,123,456,789' > > Gregor Is it? >>> jj = '234567890123456789' >>> ",".join([jj[max(ii-3,0):ii] for ii in range(len(jj)%3,len(jj)+3,3)]) ',234,567,890,123,456,789' At least one other solution in this thread had the same problem. -Mark From bouncyinc at gmail.com Sat Aug 15 16:23:26 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 14:23:26 -0600 Subject: redoing libgmail interface to "smtplib" blah? Message-ID: The following program is theoretically supposed to use a supported library. Issues have come up where the library is not working and now another interface is being requierd to be used. At this point I'm looking at just changing the send commands but don't feel confident in doing so. Wondering specifically what would have to be changed to what. Thanks for your time :) #!/usr/bin/env python # # ogss -- SMS Shell through Gmail and libgmail # # Version 0.2 # # Author: btoews at mastahyeti.com # # License: GPL 2.0 # # NOTE: # You should ensure you are permitted to use this script before using it # to access Google's Gmail servers. # def main(argv): print "Starting ogss" logfile = os.path.join(os.environ["HOME"],"ogss.log") print "Logfile at:"+logfile execd = [] #Checking to see if the logfile already exists #if it doesn't we create it. if not os.path.exists(logfile): print "Creating log file" try: open(logfile,"w").close() except: print "Failed to open create log file. Check permissions" exit() #Opening log file for reading and parseing its contents into a list #Must do this to ensure that we dont execute old commands print "Opening log file for reading" try: r = open(logfile,"r") for line in r: eid = line.split("~") if len(eid)>=2: execd.append(int(eid[0])) r.close() except: print "Failed to open or read log file. Check permissions" exit() clist = [["3 River Wireless","@sms.3rivers.net"],["7-11 Speakout","@ cingularme.com"],["Airtel (Karnataka","India)Alaska Communications Systems"],["Alltel Wireless","@message.alltel.com"],["AT&T Wireless","@ txt.att.net"],["Bell Mobility (Canada)","@txt.bell.ca"],["Boost Mobile","@ myboostmobile.com"],["Cellular One (Dobson)","@mobile.celloneusa.com"],["Cingular (Postpaid)","@cingularme.com"],["Centennial Wireless","@cwemail.com"],["Cingular (GoPhone prepaid)","@cingularme.com"],["Claro (Nicaragua)","@ ideasclaro-ca.com"],["Comcel","@comcel.com.co"],["Cricket","@ sms.mycricket.com"],["CTI","@sms.ctimovil.com.ar"],["Emtel (Mauritius)","@ emtelworld.net"],["Fido (Canada)","@fido.ca"],["General Communications Inc.","@msg.gci.net"],["Globalstar","@msg.globalstarusa.com"],["Helio","@ myhelio.com"],["Illinois Valley Cellular","@ivctext.com"],["i wireless",". iws at iwspcs.net"],["Meteor (Ireland)","@sms.mymeteor.ie"],["Mero Mobile (Nepal)","@sms.spicenepal.com"],["MetroPCS","@mymetropcs.com"],["Movicom","@ movimensaje.com.ar"],["Mobitel (Sri Lanka)","@sms.mobitel.lk"],["Movistar (Colombia)","@movistar.com.co"],["MTN (South Africa)","@sms.co.za"],["MTS (Canada)","@text.mtsmobility.com"],["Nextel (Argentina)","@nextel.net.ar"],["Orange (Poland)","@orange.pl"],["Personal (Argentina)","@personal-net.com.ar"],["Plus GSM (Poland)","@text.plusgsm.pl"],["President\s Choice (Canada)","@ txt.bell.ca"],["Qwest","@qwestmp.com"],["Rogers (Canada)","@pcs.rogers.com"],["Sasktel (Canada)","@sms.sasktel.com"],["Setar Mobile email (Aruba)","@mas.aw"],["Solo Mobile","@txt.bell.ca"],["Sprint (PCS)","@messaging.sprintpcs.com"],["Sprint (Nextel)","@page.nextel.com"],["Suncom","@tms.suncom.com"],["T-Mobile","@ tmomail.net"],["T-Mobile (Austria)","@sms.t-mobile.at"],["Telus Mobility (Canada)","@msg.telus.com"],["Thumb Cellular","@sms.thumbcellular.com"],["Tigo (Formerly Ola)","@sms.tigo.com.co"],["Unicel","@utext.com"],["US Cellular","@email.uscc.net"],["Verizon","@vtext.com"],["Virgin Mobile (Canada)","@vmobile.ca"],["Virgin Mobile (USA)","@vmobl.com"],["YCC","@ sms.ycc.ru"],["Orange (UK)","@orange.net"],["Cincinnati Bell Wireless","@ gocbw.com"],["T-Mobile Germany","@t-mobile-sms.de"],["Vodafone Germany","@ vodafone-sms.de"],["E-Plus","@smsmail.eplus.de"]] print "Parsing user input" if len(argv)<4: if len(argv) == 2: if argv[1] == "-c": counter = 0 for car in clist: print str(counter) + "--" + car[0] counter += 1 exit() else: print "------Useage---------------------------------------------------------------\n\r------Start Service --- ogss.py USERNAME PASSWORD CELL-NUMBER CARRIER-NUMBER\n\r------List carriers --- ogss.py -c" print "------Useage from phone----------------------------------------------------\n\r------Ogss COMMAND" exit() username = argv[1] password = argv[2] number = argv[3] carrier = clist[int(argv[4])] cell_email = number+carrier[1] print "Connecting to Gmail" account = libgmail.GmailAccount(username,password) print "Logging into Gmail" account.login() print "Opening log file for writing" try: w = open(logfile,"a") except: print "Failed to open log file. Check permissions." exit() #If the logfile is empty (if this is the first use) we want to #send instructions to the users cell phone. #if len(execd) < 1: # instructions = libgmail.GmailComposedMessage(cell_email,"OGSS Instructions","To use OGSS reply to this message with an SMS starting with \"Ogss\". Whatever follows \"Ogss\" will be executed on your computer") # account.sendMessage(instructions) print "Listening for commands" while True: try: searchResult = account.getMessagesByQuery("from:"+cell_email,True) maxid = 0 if len(searchResult)>0: #Here we search through the inbox to find the most recent message sent #from the specified phone number for thread in searchResult: for message in thread: if cell_email == message.sender: if int(message.id,16)>maxid: maxid = int(message.id,16) maxmessage = message #Removeing all the garbage from the message to find the command #TODO find a neater way of parsing message ogsssplit = maxmessage.source.split("Ogss") spansplit = ogsssplit[len(ogsssplit)-1].split("") command = spansplit[0] command = command.split() #If the id of the most recent message does not already exist in #the log file, run the command if execd.count(int(maxmessage.id,16))==0: print "Processing Command" cresult = Popen(command,stdout=PIPE) body = cresult.stdout.read() tosend = libgmail.GmailComposedMessage(cell_email,"STDOUT","\n"+body) print "Seding back results" account.sendMessage(tosend) print "Logging..." execd.append(int(maxmessage.id,16)) towrite = str(int(maxmessage.id,16))+"~ " for arg in command: towrite += arg+" " w.write(towrite+"\n") print "Listening for commands" #TODO add ability to choose sleep time time.sleep(2) except (KeyboardInterrupt, SystemExit): w.close() print "Exiting..." exit() if __name__ == "__main__": import os,time,sys,libgmail from subprocess import Popen,PIPE main(sys.argv) -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sat Aug 15 16:26:06 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 15 Aug 2009 13:26:06 -0700 (PDT) Subject: random.gauss vs. random.normalvariate References: Message-ID: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> On Aug 15, 12:49?pm, Alan G Isaac wrote: > Quotinghttp://docs.python.org/3.1/library/random.html#random.gauss: > ? ? Gaussian distribution. mu is the mean, and sigma is the > ? ? standard deviation. This is slightly faster than the > ? ? normalvariate() function defined below. > > So since both are offered and gauss is faster, I assume it > must have some offsetting disadvantage. ?What is it? random.gauss is not thread safe. I'm kind of surprised the html docs don't mention this; the docstring does. Carl Banks From bouncyinc at gmail.com Sat Aug 15 16:34:36 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 14:34:36 -0600 Subject: random.gauss vs. random.normalvariate In-Reply-To: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> Message-ID: What does the term "thread safe" mean exactly. I never had to program with "threads" before On Sat, Aug 15, 2009 at 2:26 PM, Carl Banks wrote: > On Aug 15, 12:49 pm, Alan G Isaac wrote: > > Quotinghttp://docs.python.org/3.1/library/random.html#random.gauss: > > Gaussian distribution. mu is the mean, and sigma is the > > standard deviation. This is slightly faster than the > > normalvariate() function defined below. > > > > So since both are offered and gauss is faster, I assume it > > must have some offsetting disadvantage. What is it? > > random.gauss is not thread safe. > > I'm kind of surprised the html docs don't mention this; the docstring > does. > > > Carl Banks > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Sat Aug 15 16:50:39 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 15 Aug 2009 22:50:39 +0200 Subject: Why is "unpacking" of tuples only allowed when there's 1 tupple ? Message-ID: <4A871F9F.3040904@gmail.com> hello, I'm not sure if "unpacking" is the right term but if I have a tuple of 2 arrays, I can either call a function with: Space_State = tf2ss ( filt[0], filt[1] ) or with Space_State = tf2ss ( *filt ) Now if I've to call a function with more parameters, why can't I use (Polynome is again a tuple of 2 arrays) : (which already gives an error in the IDE) Respons = signal.lfilter ( *Polynome, Signal ) and thus I've to use: Respons = signal.lfilter ( Polynome[0], Polynome[1], Signal ) I use Python 2.5.2 thanks, Stef Mientki From alan.isaac at gmail.com Sat Aug 15 16:54:37 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Sat, 15 Aug 2009 20:54:37 GMT Subject: random.gauss vs. random.normalvariate In-Reply-To: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> Message-ID: > On Aug 15, 12:49 pm, Alan G Isaac wrote: >> Quotinghttp://docs.python.org/3.1/library/random.html#random.gauss: >> Gaussian distribution. mu is the mean, and sigma is the >> standard deviation. This is slightly faster than the >> normalvariate() function defined below. >> >> So since both are offered and gauss is faster, I assume it >> must have some offsetting disadvantage. What is it? On 8/15/2009 4:26 PM Carl Banks apparently wrote: > random.gauss is not thread safe. > > I'm kind of surprised the html docs don't mention this; the docstring > does. Thank you, Alan Isaac From zuo at chopin.edu.pl Sat Aug 15 17:11:43 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 15 Aug 2009 23:11:43 +0200 Subject: Why is "unpacking" of tuples only allowed when there's 1 tupple ? In-Reply-To: <4A871F9F.3040904@gmail.com> References: <4A871F9F.3040904@gmail.com> Message-ID: Dnia 15-08-2009 o 22:50:39 Stef Mientki napisa?(a): > hello, > > I'm not sure if "unpacking" is the right term > but if I have a tuple of 2 arrays, > I can either call a function with: > > Space_State = tf2ss ( filt[0], filt[1] ) > > or with > Space_State = tf2ss ( *filt ) > > Now if I've to call a function with more parameters, > why can't I use (Polynome is again a tuple of 2 arrays) : > (which already gives an error in the IDE) > > Respons = signal.lfilter ( *Polynome, Signal ) > > and thus I've to use: > > Respons = signal.lfilter ( Polynome[0], Polynome[1], Signal ) The content of that tuple or list (filt/Polynome here) doesn't matter. Simply, when calling function, you can't put positional (non-keyword) argument after *something. >>> def nic(*args, **kwargs): pass ... >>> nic(*[1,2,3], 4) File "", line 1 SyntaxError: only named arguments may follow *expression That'd be ok: Respons = signal.lfilter(*Polynome, sig=Signal) # if this method can # receive argument # 'sig' after more # than len(Polynome) # of arguments -- Jan Kaliszewski (zuo) From python at mrabarnett.plus.com Sat Aug 15 17:18:24 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 15 Aug 2009 22:18:24 +0100 Subject: Python 'for' loop is memory inefficient In-Reply-To: <4a870cc7$0$1674$742ec2ed@news.sonic.net> References: <24980842.post@talk.nabble.com> <4a870cc7$0$1674$742ec2ed@news.sonic.net> Message-ID: <4A872620.1070808@mrabarnett.plus.com> John Nagle wrote: > Hendrik van Rooyen wrote: >> On Saturday 15 August 2009 03:25:45 Dr. Phillip M. Feldman wrote: > >> And while you are about it, you may as well teach them that it is much >> better to do a multiplication than a division. > > Actually, division speed hasn't been much of an issue in years. > Arithmetic > has been faster than memory access since CPUs went superscalar. In > CPython, > with all the interpreter overhead, you'll probably never notice the > difference. > > I'd thought "xrange" had already been obsoleted, and hadn't realized the > 2.3 - 2.6 versions of CPython were still doing "range" the hard way, not > as a generator. > It would've broken some existing code, hence it was left until Python 3. From lists at cheimes.de Sat Aug 15 17:19:42 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 15 Aug 2009 23:19:42 +0200 Subject: PyQt4.__file__ gives PyQt4/__init__.py as value In-Reply-To: <0b3b6163-3fb3-4b1b-9605-bf899f65b9e9@o6g2000yqj.googlegroups.com> References: <0b3b6163-3fb3-4b1b-9605-bf899f65b9e9@o6g2000yqj.googlegroups.com> Message-ID: <4A87266E.6080609@cheimes.de> wgw wrote: > I don't understand why the __file__ value in my installation of PyQt > would not give a proper, full path. > > I'm guessing that I did not install pyqt properly (I'm on Ubuntu > Hardy, trying to install QT4.5), but before redoing the install, I > want to see if there is a quicker fix. Some versions of Debian and Ubuntu used to compile Python files with a relative path. Try this: python2.5 /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 python2.5 -o /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 Christian From lists at cheimes.de Sat Aug 15 17:19:42 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 15 Aug 2009 23:19:42 +0200 Subject: PyQt4.__file__ gives PyQt4/__init__.py as value In-Reply-To: <0b3b6163-3fb3-4b1b-9605-bf899f65b9e9@o6g2000yqj.googlegroups.com> References: <0b3b6163-3fb3-4b1b-9605-bf899f65b9e9@o6g2000yqj.googlegroups.com> Message-ID: <4A87266E.6080609@cheimes.de> wgw wrote: > I don't understand why the __file__ value in my installation of PyQt > would not give a proper, full path. > > I'm guessing that I did not install pyqt properly (I'm on Ubuntu > Hardy, trying to install QT4.5), but before redoing the install, I > want to see if there is a quicker fix. Some versions of Debian and Ubuntu used to compile Python files with a relative path. Try this: python2.5 /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 python2.5 -o /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 Christian From stef.mientki at gmail.com Sat Aug 15 17:19:53 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 15 Aug 2009 23:19:53 +0200 Subject: Why is "unpacking" of tuples only allowed when there's 1 tupple ? In-Reply-To: References: <4A871F9F.3040904@gmail.com> Message-ID: <4A872679.4060300@gmail.com> thanks Jan, for the clear explanation. cheers, Stef Jan Kaliszewski wrote: > Dnia 15-08-2009 o 22:50:39 Stef Mientki > napisa?(a): > >> hello, >> >> I'm not sure if "unpacking" is the right term >> but if I have a tuple of 2 arrays, >> I can either call a function with: >> >> Space_State = tf2ss ( filt[0], filt[1] ) >> >> or with >> Space_State = tf2ss ( *filt ) >> >> Now if I've to call a function with more parameters, >> why can't I use (Polynome is again a tuple of 2 arrays) : >> (which already gives an error in the IDE) >> >> Respons = signal.lfilter ( *Polynome, Signal ) >> >> and thus I've to use: >> >> Respons = signal.lfilter ( Polynome[0], Polynome[1], Signal ) > > The content of that tuple or list (filt/Polynome here) doesn't matter. > Simply, when calling function, you can't put positional (non-keyword) > argument after *something. > > >>> def nic(*args, **kwargs): pass > ... > >>> nic(*[1,2,3], 4) > File "", line 1 > SyntaxError: only named arguments may follow *expression > > > That'd be ok: > > Respons = signal.lfilter(*Polynome, sig=Signal) # if this method can > # receive argument > # 'sig' after more > # than len(Polynome) > # of arguments > From jasevv at gmail.com Sat Aug 15 17:32:59 2009 From: jasevv at gmail.com (Jaseem) Date: Sat, 15 Aug 2009 14:32:59 -0700 (PDT) Subject: Python or ActionScript 3.0 Message-ID: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> Hi, Is python similar to actionscript 3.0 Which is better to create a rich gui internet application? Is it AS 3.0 with flex or python with its GUI libs? Is python in demand? Heard that python is similar to lisp. But both python and AS 3.0 is almost identical. Which is more similar to lisp are powerful? Thank You. From rylesny at gmail.com Sat Aug 15 17:54:27 2009 From: rylesny at gmail.com (ryles) Date: Sat, 15 Aug 2009 14:54:27 -0700 (PDT) Subject: Splitting a string into substrings of equal size References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <064c16a8-8a5a-4764-976f-1ee5a46d82bb@n2g2000vba.googlegroups.com> On Aug 14, 8:22?pm, candide wrote: > Suppose you need to split a string into substrings of a given size (except > possibly the last substring). I make the hypothesis the first slice is at the > end of the string. > A typical example is provided by formatting a decimal string with thousands > separator. > > What is the pythonic way to do this ? > > For my part, i reach to this rather complicated code: > > # ---------------------- > > def comaSep(z,k=3, sep=','): > ? ? z=z[::-1] > ? ? x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] > ? ? return sep.join(x) > > # Test > for z in ["75096042068045", "509", "12024", "7", "2009"]: > ? ? print z+" --> ", comaSep(z) > > # ---------------------- > > outputting : > > 75096042068045 --> ?75,096,042,068,045 > 509 --> ?509 > 12024 --> ?12,024 > 7 --> ?7 > 2009 --> ?2,009 > > Thanks py> s='1234567' py> ','.join(_[::-1] for _ in re.findall('.{1,3}',s[::-1])[::-1]) '1,234,567' py> # j/k ;) From wgwinder at gmail.com Sat Aug 15 17:58:48 2009 From: wgwinder at gmail.com (wgw) Date: Sat, 15 Aug 2009 14:58:48 -0700 (PDT) Subject: PyQt4.__file__ gives PyQt4/__init__.py as value References: <0b3b6163-3fb3-4b1b-9605-bf899f65b9e9@o6g2000yqj.googlegroups.com> Message-ID: <2d6a2d94-c1fb-4cd4-a21b-5fd8cf8ee484@g10g2000yqh.googlegroups.com> On Aug 15, 2:19?pm, Christian Heimes wrote: > wgw wrote: > > I don't understand why the __file__ value in my installation of PyQt > > would not give a proper, full path. > > > I'm guessing that I did not install pyqt properly (I'm on Ubuntu > > Hardy, trying to install QT4.5), but before redoing the install, I > > want to see if there is a quicker fix. > > Some versions of Debian and Ubuntu used to compile Python files with a > relative path. Try this: > > python2.5 /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 > python2.5 -o /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 > > Christian python2.5 /usr/lib/python2.5/compileall.py -f /usr/lib/python2.5 didn't change anything, and there is no -o option (-O exists, but would that be useful?) thanks! From python at mrabarnett.plus.com Sat Aug 15 18:06:22 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 15 Aug 2009 23:06:22 +0100 Subject: Splitting a string into substrings of equal size In-Reply-To: <064c16a8-8a5a-4764-976f-1ee5a46d82bb@n2g2000vba.googlegroups.com> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> <064c16a8-8a5a-4764-976f-1ee5a46d82bb@n2g2000vba.googlegroups.com> Message-ID: <4A87315E.7040603@mrabarnett.plus.com> ryles wrote: > On Aug 14, 8:22 pm, candide wrote: >> Suppose you need to split a string into substrings of a given size (except >> possibly the last substring). I make the hypothesis the first slice is at the >> end of the string. >> A typical example is provided by formatting a decimal string with thousands >> separator. >> >> What is the pythonic way to do this ? >> >> For my part, i reach to this rather complicated code: >> >> # ---------------------- >> >> def comaSep(z,k=3, sep=','): >> z=z[::-1] >> x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] >> return sep.join(x) >> >> # Test >> for z in ["75096042068045", "509", "12024", "7", "2009"]: >> print z+" --> ", comaSep(z) >> >> # ---------------------- >> >> outputting : >> >> 75096042068045 --> 75,096,042,068,045 >> 509 --> 509 >> 12024 --> 12,024 >> 7 --> 7 >> 2009 --> 2,009 >> >> Thanks > > py> s='1234567' > py> ','.join(_[::-1] for _ in re.findall('.{1,3}',s[::-1])[::-1]) > '1,234,567' > py> # j/k ;) If you're going to use re, then: >>> for z in ["75096042068045", "509", "12024", "7", "2009"]: print re.sub(r"(?<=.)(?=(?:...)+$)", ",", z) 75,096,042,068,045 509 12,024 7 2,009 From Brian.Mingus at colorado.edu Sat Aug 15 18:11:08 2009 From: Brian.Mingus at colorado.edu (Brian) Date: Sat, 15 Aug 2009 16:11:08 -0600 Subject: Splitting a string into substrings of equal size In-Reply-To: <4A87315E.7040603@mrabarnett.plus.com> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> <064c16a8-8a5a-4764-976f-1ee5a46d82bb@n2g2000vba.googlegroups.com> <4A87315E.7040603@mrabarnett.plus.com> Message-ID: <9839a05c0908151511w38fa4d7eu9926024e1472923f@mail.gmail.com> On Sat, Aug 15, 2009 at 4:06 PM, MRAB wrote: > ryles wrote: > >> On Aug 14, 8:22 pm, candide wrote: >> >>> Suppose you need to split a string into substrings of a given size >>> (except >>> possibly the last substring). I make the hypothesis the first slice is at >>> the >>> end of the string. >>> A typical example is provided by formatting a decimal string with >>> thousands >>> separator. >>> >>> What is the pythonic way to do this ? >>> >>> For my part, i reach to this rather complicated code: >>> >>> # ---------------------- >>> >>> def comaSep(z,k=3, sep=','): >>> z=z[::-1] >>> x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] >>> return sep.join(x) >>> >>> # Test >>> for z in ["75096042068045", "509", "12024", "7", "2009"]: >>> print z+" --> ", comaSep(z) >>> >>> # ---------------------- >>> >>> outputting : >>> >>> 75096042068045 --> 75,096,042,068,045 >>> 509 --> 509 >>> 12024 --> 12,024 >>> 7 --> 7 >>> 2009 --> 2,009 >>> >>> Thanks >>> >> >> py> s='1234567' >> py> ','.join(_[::-1] for _ in re.findall('.{1,3}',s[::-1])[::-1]) >> '1,234,567' >> py> # j/k ;) >> > > If you're going to use re, then: > > >>> for z in ["75096042068045", "509", "12024", "7", "2009"]: > print re.sub(r"(?<=.)(?=(?:...)+$)", ",", z) > > > 75,096,042,068,045 > 509 > 12,024 > 7 > 2,009 > Can you please break down this regex? -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sat Aug 15 18:28:09 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 15 Aug 2009 23:28:09 +0100 Subject: Splitting a string into substrings of equal size In-Reply-To: <9839a05c0908151511w38fa4d7eu9926024e1472923f@mail.gmail.com> References: <4a85ffe2$0$24643$426a34cc@news.free.fr> <064c16a8-8a5a-4764-976f-1ee5a46d82bb@n2g2000vba.googlegroups.com> <4A87315E.7040603@mrabarnett.plus.com> <9839a05c0908151511w38fa4d7eu9926024e1472923f@mail.gmail.com> Message-ID: <4A873679.9010902@mrabarnett.plus.com> Brian wrote: > > > On Sat, Aug 15, 2009 at 4:06 PM, MRAB > wrote: > > ryles wrote: > > On Aug 14, 8:22 pm, candide wrote: > > Suppose you need to split a string into substrings of a > given size (except > possibly the last substring). I make the hypothesis the > first slice is at the > end of the string. > A typical example is provided by formatting a decimal string > with thousands > separator. > > What is the pythonic way to do this ? > > For my part, i reach to this rather complicated code: > > # ---------------------- > > def comaSep(z,k=3, sep=','): > z=z[::-1] > x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] > return sep.join(x) > > # Test > for z in ["75096042068045", "509", "12024", "7", "2009"]: > print z+" --> ", comaSep(z) > > # ---------------------- > > outputting : > > 75096042068045 --> 75,096,042,068,045 > 509 --> 509 > 12024 --> 12,024 > 7 --> 7 > 2009 --> 2,009 > > Thanks > > > py> s='1234567' > py> ','.join(_[::-1] for _ in re.findall('.{1,3}',s[::-1])[::-1]) > '1,234,567' > py> # j/k ;) > > > If you're going to use re, then: > > > >>> for z in ["75096042068045", "509", "12024", "7", "2009"]: > print re.sub(r"(?<=.)(?=(?:...)+$)", ",", z) > > > > 75,096,042,068,045 > 509 > 12,024 > 7 > 2,009 > > > Can you please break down this regex? > The call replaces a zero-width match with a comma, ie inserts a comma, if certain conditions are met: "(?<=.)" Look behind for 1 character. There must be at least one previous character. This ensures that a comma is never inserted at the start of the string. I could also have used "(? <064c16a8-8a5a-4764-976f-1ee5a46d82bb@n2g2000vba.googlegroups.com> <4A87315E.7040603@mrabarnett.plus.com> <9839a05c0908151511w38fa4d7eu9926024e1472923f@mail.gmail.com> Message-ID: On Aug 15, 6:28?pm, MRAB wrote: > > ? ? ?>>> for z in ["75096042068045", "509", "12024", "7", "2009"]: > > ? ? ? ? ? ?print re.sub(r"(?<=.)(?=(?:...)+$)", ",", z) > > > ? ? 75,096,042,068,045 > > ? ? 509 > > ? ? 12,024 > > ? ? 7 > > ? ? 2,009 > > The call replaces a zero-width match with a comma, ie inserts a comma, > if certain conditions are met: > > "(?<=.)" > ? ? ?Look behind for 1 character. There must be at least one previous > character. This ensures that a comma is never inserted at the start of > the string. I could also have used "(? whether the first character is a "-". That's left as an exercise for the > reader. :-) > > "(?=(?:...)+$)" > ? ? ?Look ahead for a multiple of 3 characters, followed by the end of > the string. Wow, well done. An exceptional recipe from Python's unofficial regex guru. And thanks for sharing the explanation. From paul.mike25 at gmail.com Sat Aug 15 20:02:36 2009 From: paul.mike25 at gmail.com (Mike Paul) Date: Sat, 15 Aug 2009 17:02:36 -0700 (PDT) Subject: Python- javascript Message-ID: <985d635f-5784-40a7-a2bb-b76900c200d9@b15g2000yqd.googlegroups.com> I'm trying to scrap a dynamic page with lot of javascript in it. Inorder to get all the data from the page i need to access the javascript. But i've no idea how to do it. Say I'm scraping some site htttp://www.xyz.com/xyz request=urllib2.Request("htttp://www.xyz.com/xyz") response=urllib2.urlopen(request) data=response.read() So i get all the data on the initial page. Now i need to access the javascript on this page to get additional details. I've heard someone telling me to use spidermonkey. But no idea on how to send javscript as request and get the response. How hsuld i be sending the javascript request as ? how can it be sent? This is the script I need to access. Click this to view more items Can anyone tell me how can i do it very clearly. I've been breaking my head into this for the past few days with no progress. Thanks From paul.mike25 at gmail.com Sat Aug 15 20:09:15 2009 From: paul.mike25 at gmail.com (Mike Paul) Date: Sat, 15 Aug 2009 19:09:15 -0500 Subject: Python - scraping - javascript Message-ID: <26ee78500908151709v6a159a95wde98b88f7d2e44bf@mail.gmail.com> I'm trying to scrap a dynamic page with lot of javascript in it. Inorder to get all the data from the page i need to access the javascript. But i've no idea how to do it. Say I'm scraping some site htttp://www.xyz.com/xyz request=urllib2.Request("htttp://www.xyz.com/xyz") response=urllib2.urlopen(request) data=response.read() So i get all the data on the initial page. Now i need to access the javascript on this page to get additional details. I've heard someone telling me to use spidermonkey. But no idea on how to send javscript as request and get the response. How hsuld i be sending the javascript request as ? how can it be sent? This is the script I need to access. Click this to view more items Can anyone tell me how can i do it very clearly. I've been breaking my head into this for the past few days with no progress. Thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From darkwater42 at gmail.com Sat Aug 15 20:57:28 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sat, 15 Aug 2009 17:57:28 -0700 (PDT) Subject: Unrecognized escape sequences in string literals References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <0008e7c1$0$2880$c3e8da3@news.astraweb.com> <3611ca55-79a6-4336-9041-07d0893789f7@n2g2000vba.googlegroups.com> <0447e8a2-508d-45b2-8d15-da0cc2a56b5f@w6g2000yqw.googlegroups.com> <494d80f1-0b47-468c-bdd9-7a087f6d915c@o6g2000yqj.googlegroups.com> <7877b03a-09da-4836-804c-502b6f78003c@h21g2000yqa.googlegroups.com> <02933e60$0$20647$c3e8da3@news.astraweb.com> <2cdc3f88-1952-4ca2-9754-5b7583fb5fd8@z31g2000yqd.googlegroups.com> <0295958b$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4e15b3a9-b3ec-41f0-bb35-15ea5da7c9db@j21g2000yqe.googlegroups.com> On Aug 14, 1:55?pm, Steven D'Aprano wrote: > Douglas, you and I clearly have a difference of opinion on > this. Neither of us have provided even the tiniest amount > of objective, replicable, reliable data on the > error-proneness of the C++ approach versus that of > Python. The supposed superiority of the C++ approach is > entirely subjective and based on personal opinion instead > of quantitative facts. Alas, this is true for nearly any engineering methodology or philosophy, which is why, I suppose, Perl, for instance, still has its proponents. It's virtually impossible to prove any thesis, and these things only get decided by endless debate that rages across decades. > I prefer languages that permit anything that isn't > explicitly forbidden, so I'm happy that Python treats > non-special escape sequences as valid, I don't really understand what you mean by this. If Python were to declare that "unrecognized escape sequences" were forbidden, then they would be "explicitly forbidden". Would you then be happy? If not, why are you not upset that Python won't let me do [3, 4, 5] + 2 Some other programming languages I've used certainly do. > and your attempts to convince me that this goes against > the Zen have entirely failed to convince me. As I've done > before, I will admit that one consequence of this design > is that it makes it hard to introduce new escape sequences > to Python. Given that it's vanishingly rare to want to do > so, I'm not so convinced of that in the days of Unicode. If I see, backslash, and then some Kanji character, what am I supposed to make of that? For all I know, that Kanji character might mean newline, and I'm seeing code for a version of Python that was tweaked to be friendly to the Japanese. And in the days where smart hand-held devices are proliferating like crazy, there might be ever-more demand for easy-to-use i/o that lets you control various aspects of those devices. |>ouglas From sjmachin at lexicon.net Sat Aug 15 21:01:37 2009 From: sjmachin at lexicon.net (John Machin) Date: Sat, 15 Aug 2009 18:01:37 -0700 (PDT) Subject: Python 2.6 still not giving memory back to the OS... References: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> Message-ID: <762603ba-0a4c-4504-94d9-34a8b1e3f9c3@s15g2000yqs.googlegroups.com> On Aug 16, 2:41?am, Mark Dickinson wrote: > and got the expected memory usage for my Python process, as > displayed by top: ?memory usage went up to nearly 1Gb after > each assignment to b, then dropped down to 19 Mb or so after > each 'del b'. ?I get similar results under Python 2.5. > > So maybe there's something in xlrd that's hanging on to all > that memory? News to me, and news to guppy/heapy v0.1.9 -- unless the new Windows support has some deficiencies -- after `del b` heapy can't find any trace of the Book object and its contents. As far as releasing memory back to the OS is concerned, I have dim memories of *x systems where free() would return space to the OS if the block was "large" and it was next to the "break" point ... this effect could be what you are seeing. From terry.yinzhe at gmail.com Sat Aug 15 21:04:29 2009 From: terry.yinzhe at gmail.com (Terry) Date: Sat, 15 Aug 2009 18:04:29 -0700 (PDT) Subject: ignored test cases in unittest Message-ID: Hi, I have some 100s unittest cases with my python program. And sometimes, I did quick-and-dirty work by ignoring some test cases by adding an 'x' (or something else) to the beginning of the case name. As time pass by, it's very hard for me to find which test cases are ignored. It seemed the to me that python unittest module does not support the counting of ignored test cases directly. Is there any ready solution for this? br, Terry From roy at panix.com Sat Aug 15 21:12:14 2009 From: roy at panix.com (Roy Smith) Date: Sat, 15 Aug 2009 21:12:14 -0400 Subject: ignored test cases in unittest References: Message-ID: In article , Terry wrote: > Hi, > > I have some 100s unittest cases with my python program. And sometimes, > I did quick-and-dirty work by ignoring some test cases by adding an > 'x' (or something else) to the beginning of the case name. > As time pass by, it's very hard for me to find which test cases are > ignored. If you are consistent in how you do this (i.e. always add an "x" to the beginning of the name), it should be trivial to find them all. I'm sure I could whip up some introspection based method, but it's easier and faster to just do "grep 'def.*xtest' *.py". From darkwater42 at gmail.com Sat Aug 15 21:29:13 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sat, 15 Aug 2009 18:29:13 -0700 (PDT) Subject: Python or ActionScript 3.0 References: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> Message-ID: <8a14e744-eb6c-4ae2-9bb4-2e32fcb987ae@v20g2000yqm.googlegroups.com> On Aug 15, 5:32?pm, Jaseem wrote: > Is python similar to actionscript 3.0 For some very rough sense of "similar" it might be, but not really. > Which is better to create a rich gui internet application? > Is it AS 3.0 with flex or python with its GUI libs? Python doesn't run in your typical web browser, but it is common to use Python for doing the server-side programming, along with a Python- based web development framework, such as Django. You could use Jython to make a JVM applet that would run in a browser, but JVM applets aren't very popular for a variety of reasons, and I doubt the performance would be very good. > Is python in demand? Yes, it's a popular language. > Heard that python is similar to lisp. Kind of. Not any more so that JavaScript is, though, for instance. > But both python and AS 3.0 is almost identical. No, Python and ActionScript are not "almost identical". > Which is more similar to lisp are powerful? They both have their similarities and differences from Lisp. I think it would be impossible to say which one is more similar to Lisp. In general, Python is in my opinion more pleasant to program in than ActionScript, but Python is not generally used for client-side browser code. I think the future of client-side browser programming is actually JavaScript, not ActionScript, though that future may morph into one that mostly uses JavaScript as a virtual machine. This is the approach that Google Web Toolkit takes. It lets you write your client-side code in Java, and that is then compiled into JavaScript. |>ouglas From narkewoody at gmail.com Sat Aug 15 21:52:47 2009 From: narkewoody at gmail.com (Steven Woody) Date: Sun, 16 Aug 2009 09:52:47 +0800 Subject: OptionParser How to: prog [options] [arguments] In-Reply-To: References: Message-ID: Thanks for all you suggestions! -------------- next part -------------- An HTML attachment was scrubbed... URL: From darkwater42 at gmail.com Sat Aug 15 22:12:06 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sat, 15 Aug 2009 19:12:06 -0700 (PDT) Subject: Python- javascript References: <985d635f-5784-40a7-a2bb-b76900c200d9@b15g2000yqd.googlegroups.com> Message-ID: <54684273-6de7-470e-899e-64e0a191c7e3@w6g2000yqw.googlegroups.com> On Aug 15, 8:02?pm, Mike Paul wrote: > I'm trying to scrap a dynamic page with lot of javascript in it. > Inorder to get all the data from the page i need to access the > javascript. But i've no idea how to do it. I'm not sure exactly what you are trying to do, but scraping websites that use a lot of JavaScript are often very problematic. The last time I did so, I had to write some pretty funky regular expressions to pick data out of the JavaScript. Fortunately, the data was directly in the JavaScript, rather than me having to reproduce the Ajax calling chain. If you need to do that, then you almost certainly want to use a package designed for doing such things. One such package is HtmlUnit. It is a "GUI-less browser" with a built-in JavaScript engine that is design for such scraping tasks. Unfortunately, you have to program it in Java, rather than Python. (You might be able to use Jython instead of Java, but I don't know for sure.) |>ouglas P.S. For scraping tasks, you probably want to use BeautifulSoup rather than urllib2. From ben+python at benfinney.id.au Sat Aug 15 22:15:04 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 16 Aug 2009 12:15:04 +1000 Subject: ignored test cases in unittest References: Message-ID: <873a7so66v.fsf@benfinney.id.au> Terry writes: > It seemed the to me that python unittest module does not support the > counting of ignored test cases directly. Is there any ready solution > for this? One solution I've seen involves: * a custom exception class, ?TestSkipped? * raising that exception at the top of test cases you want to temporarily skip * a custom ?TestResult? class that knows about a ?skipped? result * a custom reporter class that knows how you want to report that result -- \ ?A lot of people are afraid of heights. Not me, I'm afraid of | `\ widths.? ?Steven Wright | _o__) | Ben Finney From steve at REMOVE-THIS-cybersource.com.au Sat Aug 15 22:19:02 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 02:19:02 GMT Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> Message-ID: <02975ce6$0$20634$c3e8da3@news.astraweb.com> On Sat, 15 Aug 2009 13:01:43 -0700, Douglas Alan wrote: > P.S. I find it strange, however, that anyone who is not okay with > "abusing" operator overloading in this manner, wouldn't also take > umbrage at Python's overloading of "+" to work with strings and lists, > etc. Numerical addition and sequence concatenation have entirely > different semantics. Not to English speakers, where we frequently use 'add' to mean concatenate, append, insert, etc.: "add this to the end of the list" "add the prefix 'un-' to the beginning of the word to negate it" "add your voice to the list of those calling for change" "add your name and address to the visitor's book" and even in-place modifications: "after test audiences' luke-warm response, the studio added a completely different ending to the movie". Personally, I would have preferred & for string and list concatenation, but that's entirely for subjective reasons. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sat Aug 15 22:22:38 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 02:22:38 GMT Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> <4a870a7b$0$1674$742ec2ed@news.sonic.net> Message-ID: <02975dbe$0$20634$c3e8da3@news.astraweb.com> On Sat, 15 Aug 2009 12:24:26 -0700, John Nagle wrote: > fortunatus wrote: >> On Aug 14, 1:01 pm, vippstar wrote: >>> Why would you fill your website with junk? >> >> The OP made it clear: >> >>> Just wanted to express some frustration with whitespace-mode. > > Well, it took until Python 3.0 until Python enforced rules that > ensured that the indentation the user sees is the same indentation the > compiler sees. We finally have a solution that allows both tabs and > spaces but disallows the situations which are ambiguous. Until Python > 3.0 is fully deployed, there are situations when you need an insane > level of tab/space visibility. Blame Python, not EMACS. You know, there are situations outside of Python where it is useful to see otherwise invisible characters. I was using Microsoft Word's "Show Invisibles" functionality years before Python even existed. Being able to see a visual glyph in place of whitespace (including line ending characters) is not just useful for editing indentation. -- Steven From bouncyinc at gmail.com Sat Aug 15 22:58:52 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 20:58:52 -0600 Subject: redoing libgmail interface to "smtplib" blah? In-Reply-To: References: Message-ID: On Sat, Aug 15, 2009 at 7:23 PM, Dennis Lee Bieber wrote: > On Sat, 15 Aug 2009 14:23:26 -0600, John Haggerty > declaimed the following in gmane.comp.python.general: > > > The following program is theoretically supposed to use a supported > library. > > Issues have come up where the library is not working and now another > > interface is being requierd to be used. > > > > At this point I'm looking at just changing the send commands but don't > feel > > confident in doing so. Wondering specifically what would have to be > changed > > to what. > > > > Thanks for your time :) > > Ugh... I'm afraid if I attacked this program I'd have to > restructure > the entire thing... There are no signs of any functional decomposition > in that -- if Python had an unstructured GOTO, I'd suspect this would > have been a spaghetti-code program... As it is, the best I can call it > is lasagna-code (interwoven but distinct layers in a linear form > from one end to the other). > > > > if __name__ == "__main__": > > import os,time,sys,libgmail > > from subprocess import Popen,PIPE > > main(sys.argv) > > Given the position of the import statements, this file can NOT be > used as an importable module for use by other programs, so the whole > breakdown of a main() is meaningless; might as well remove that if, the > def main(): line, move the imports to the top, and unindent the rest one > level. > > All those embedded calls to exit() also offend me; I'm from the "one > in, one out" school (though I'll use break and continue in a loop, I > still favor just one usage of them in such) > > Ideally, all the SMS related stuff would be isolated apart from the > email stuff. Would make changing email interface a lot more intuitive. > > Out of a fit of boredom, though it probably doesn't help your real > problem, and it has not been tested at all, this is my restructuring of > the code listing. > > -=-=-=-=-=-=-=- > import os > import time > import sys > import subprocess > > import libgmail > > > CARRIERLIST = [ ("3 River Wireless", "@sms.3rivers.net"), > ("7-11 Speakout","@cingularme.com"), > # ("Airtel (Karnataka","India) Alaska > Communications Systems"), > ("Alltel Wireless","@message.alltel.com"), > ("AT&T Wireless","@txt.att.net"), > ("Bell Mobility (Canada)","@txt.bell.ca"), > ("Boost Mobile","@myboostmobile.com"), > ("Cellular One (Dobson)","@mobile.celloneusa.com"), > ("Cingular (Postpaid)","@cingularme.com"), > ("Centennial Wireless","@cwemail.com"), > ("Cingular (GoPhone prepaid)","@cingularme.com"), > ("Claro (Nicaragua)","@ideasclaro-ca.com"), > ("Comcel","@comcel.com.co"), > ("Cricket","@sms.mycricket.com"), > ("CTI","@sms.ctimovil.com.ar"), > ("Emtel (Mauritius)","@emtelworld.net"), > ("Fido (Canada)","@fido.ca"), > ("General Communications Inc.","@msg.gci.net"), > ("Globalstar","@msg.globalstarusa.com"), > ("Helio","@myhelio.com"), > ("Illinois Valley Cellular","@ivctext.com"), > # ("i wireless",".iws at iwspcs.net"), > ("Meteor (Ireland)","@sms.mymeteor.ie"), > ("Mero Mobile (Nepal)","@sms.spicenepal.com"), > ("MetroPCS","@mymetropcs.com"), > ("Movicom","@movimensaje.com.ar"), > ("Mobitel (Sri Lanka)","@sms.mobitel.lk"), > ("Movistar (Colombia)","@movistar.com.co"), > ("MTN (South Africa)","@sms.co.za"), > ("MTS (Canada)","@text.mtsmobility.com"), > ("Nextel (Argentina)","@nextel.net.ar"), > ("Orange (Poland)","@orange.pl"), > ("Personal (Argentina)","@personal-net.com.ar"), > ("Plus GSM (Poland)","@text.plusgsm.pl"), > ("President's Choice (Canada)","@txt.bell.ca"), > ("Qwest","@qwestmp.com"), > ("Rogers (Canada)","@pcs.rogers.com"), > ("Sasktel (Canada)","@sms.sasktel.com"), > ("Setar Mobile email (Aruba)","@mas.aw"), > ("Solo Mobile","@txt.bell.ca"), > ("Sprint (PCS)","@messaging.sprintpcs.com"), > ("Sprint (Nextel)","@page.nextel.com"), > ("Suncom","@tms.suncom.com"), > ("T-Mobile","@tmomail.net"), > ("T-Mobile (Austria)","@sms.t-mobile.at"), > ("Telus Mobility (Canada)","@msg.telus.com"), > ("Thumb Cellular","@sms.thumbcellular.com"), > ("Tigo (Formerly Ola)","@sms.tigo.com.co"), > ("Unicel","@utext.com"), > ("US Cellular","@email.uscc.net"), > ("Verizon","@vtext.com"), > ("Virgin Mobile (Canada)","@vmobile.ca"), > ("Virgin Mobile (USA)","@vmobl.com"), > ("YCC","@sms.ycc.ru"), > ("Orange (UK)","@orange.net"), > ("Cincinnati Bell Wireless","@gocbw.com"), > ("T-Mobile Germany","@t-mobile-sms.de"), > ("Vodafone Germany","@vodafone-sms.de"), > ("E-Plus","@smsmail.eplus.de") ] > > INSTRUCTIONS = """ > ------Usage--------------------------------------------------------------- > ------Start Service --- > ogss.py USERNAME PASSWORD CELL-NUMBER CARRIER-NUMBER > ------List carriers --- > ogss.py -c > > ------Useage from > phone---------------------------------------------------- > ------Ogss COMMAND > """ > > #odd notation is to split by lines, then join lines with a space > PHONEINSTRUCTIONS = " ".join( > """To use OGSS reply to this message with an SMS starting with > "Ogss". Whatever follows "Ogss" will be executed on your computer > """.split()) > > class Logfile(object): > def __init__(self): > self.logname = os.path.join(os.environ["HOME"], "ogss.log") > if not os.path.exists(self.logname): > try: > self.log = open(logname, "w+") > except: > print "Failure to create log file; check permissions" > self.log = None > else: > try: > print "Opening log file: %s" % self.logname > self.log = open(logname, "r+") > except: > self.log = None > > def opened(self): > return self.log is not None > > def readParse(self): > if self.opened(): > self.log.seek(0, os.SEEK_SET) > retdata = [] > for line in self.log: > eid = line.split("~") > if len(eid) >= 2: > retdata.append(int(eid[0])) > return retdata > > def write(self, ID, commandLine): > if self.opened(): > self.log.seek(0, os.SEEK_END) > self.log.write("%s %s\n" % (ID, commandLine)) > > def close(self): > if self.opened(): > self.log.close() > > class MailConnection(object): > #might have been possible to subclass from libgmail.GmailAccount > #but by incorporating that as a component instead makes it > #a bit easier to replace with something else (SMTP?) > def __init__(self, uname, passwd): > self.uname = uname > self.passwd = passwd > self.account = libgmail.GmailAccount(self.uname, self.passwd) > > def login(self): > self.account.login() > > def sendMessage(self, message): > self.account.sendMessage(message) > > def getMessageByQuery(qstring, flag): #what does flag do? > return self.account.getMessagesByQuery(qstring, flag) > > def composeMessage(self, to, subject, body): > return libgmail.GmailComposedMessage(to, > subject, > body) > > > def parseCommandLine(args): > retdata = None > if len(args) == 1 and args[0] = "-c": > for i, car in enumerate(CARRIERLIST): > print "%5d -- %s" % (i, car[0]) > > elif len(args) > 3: > (username, password, number, carrierID) = tuple(args[:4]) > carrier = CARRIERLIST[int(carrierID)] > cell_email = number + carrier[1] > retdata = { "User" : username, > "Pass" : password, > "Number" : number, > "ID" : carrierID, > "Carrier" : carrier, > "Cell" : cell_email } > > else: > print INSTRUCTIONS > return retdata > > > def main(argv): > print "Starting ogss" > > print "Opening log file" > logfile = Logfile() > if logfile.opened(): > print "Parsing log file" > execd = logfile.readParse() > > print "Parsing command line input" > callee = parseCommandLine(argv[1:]) #strip program name > > if callee is not None: > print "Logging in to mail server" > account = MailConnection(callee["User"], > callee["Pass"]) > account.login() > > ## #if log file contents are empty, send instructions to > ## #user's phone > ## if not len(execd): > ## account.sendMessage( > ## account.composeMessage( > ## callee["Cell"], > ## "OGSS Instructions", > ## PHONEINSTRUCTIONS) ) > > > try: > while True: > print "Listening for commands" > print "Getting mailbox contents" > searchResult = account.getMessagesByQuery( > "from:" + callee["Cell"], > True ) > if searchResult: #presume empty if no messages > maxID = 0 > maxMessage = None > for thread in searchResult: > for message in thread: > if callee["Cell"] == message.sender: > mID = int(message.id, 16) > if mID > maxID: > maxID = mID > maxMessage = message > > if maxID and maxMessage: > if not maxID in execd: > print "Parsing command from message" > ogssSplit = > maxMessage.source.split("Ogss") > command = ogssSplit[-1].split( > "")[0].split() > > result = subprocess.Popen( > command, > stdout = subprocess.PIPE) > body = result.stdout.read() > account.sendMessage( > account.composeMessage( > callee["Cell"], > "STDOUT", > "\n" + body) ) > logfile.write(maxID, " ".join(command)) > > #TODO add ability to choose sleep time > time.sleep(2) > except (KeyboardInterrupt): > pass #exit WHILE loop with or equivalent > ## else: > ## pass #no login data supplied on startup > > logfile.close() > else: > print "Could not open log file, check permissions" > > > if __name__ == "__main__": > main(sys.argv) > -=-=-=-=-=-=-=- > > Everything that needs to be changed for SMTP should be in the class > MailConnection. Note: it appears that this program expects a > bidirectional mail connection -- similar to IMAP, where one connection > access both outgoing mail AND incoming mail that is stored on the remote > system. You'll probably need to use both SMTP to send the messages, and > POP3 to retrieve the mailbox contents -- and what you do about leaving > messages in a POP3 mailbox is up to you; most clients normally delete > them after fetching, but if the query has to fetch all messages just to > process one set, that may be a concern... Or you use something else to > retrieve messages and store them in a local mailbox for subsequent > usage. > > HMMM that does bring up the point -- where is your existing problem? > Reading GMAIL or sending to GMAIL? Sending actually reading worked which was what really surprised me. Especially since python had a ssl for pop and smtp as well. > > > Heh... with a bit of work, I could probably create a Eudora filter > to invoke a Python script on each new fetched email with the proper > subject/content, and then file it away is a different (local) mailbox -- > and do away with that whole log file search and message searching as > messages would be processed as received and never seen again. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From darkwater42 at gmail.com Sat Aug 15 23:00:23 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sat, 15 Aug 2009 20:00:23 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> Message-ID: On Aug 15, 10:19?pm, Steven D'Aprano wrote: > On Sat, 15 Aug 2009 13:01:43 -0700, Douglas Alan wrote: > > P.S. I find it strange, however, that anyone who is not okay with > > "abusing" operator overloading in this manner, wouldn't also take > > umbrage at Python's overloading of "+" to work with strings and lists, > > etc. Numerical addition and sequence concatenation have entirely > > different semantics. > > Not to English speakers, where we frequently use 'add' to mean > concatenate, append, insert, etc.: That is certainly true, but the "+" symbol (pronounced "plus" not "add") isn't exactly synonymous with the English word "add" and is usually used in, technical circles, to refer to a function that at least meets the properties of an abelian group operator. Also, programming languages (other than Perl) should be more precise than English. English words often have many, many meanings, but when we are talking about types and operations on types, the operations should generally have more specific semantics. In any case, let's say we grant that operators should be allowed to be as sloppy as English. Then we should have no problem with C++'s use of "<<" for i/o. Pseudo-code has a long heritage of using "<-" to indicate assignment, and there are a number of programming language (e.g., APL) that use assignment to the output terminal to indicate writing to the terminal. C++'s usage of "<<" for output is clearly designed to be reminiscent of this, and therefore intuitive. And intuitive it is, given the aforementioned background, at least. So, as far as I can tell, Python has no real authority to throw stones at C++ on this little tiny particular issue. |>ouglas From bouncyinc at gmail.com Sat Aug 15 23:18:14 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 21:18:14 -0600 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode In-Reply-To: <02975dbe$0$20634$c3e8da3@news.astraweb.com> References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> <4a870a7b$0$1674$742ec2ed@news.sonic.net> <02975dbe$0$20634$c3e8da3@news.astraweb.com> Message-ID: I would have to agree with that since I've had to work with Word 2007 issues with formatting from some...demanding people in the past. Took at least 1hour plus. On Sat, Aug 15, 2009 at 8:22 PM, Steven D'Aprano < steve at remove-this-cybersource.com.au> wrote: > On Sat, 15 Aug 2009 12:24:26 -0700, John Nagle wrote: > > > fortunatus wrote: > >> On Aug 14, 1:01 pm, vippstar wrote: > >>> Why would you fill your website with junk? > >> > >> The OP made it clear: > >> > >>> Just wanted to express some frustration with whitespace-mode. > > > > Well, it took until Python 3.0 until Python enforced rules that > > ensured that the indentation the user sees is the same indentation the > > compiler sees. We finally have a solution that allows both tabs and > > spaces but disallows the situations which are ambiguous. Until Python > > 3.0 is fully deployed, there are situations when you need an insane > > level of tab/space visibility. Blame Python, not EMACS. > > You know, there are situations outside of Python where it is useful to > see otherwise invisible characters. I was using Microsoft Word's "Show > Invisibles" functionality years before Python even existed. Being able to > see a visual glyph in place of whitespace (including line ending > characters) is not just useful for editing indentation. > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bouncyinc at gmail.com Sat Aug 15 23:37:37 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 21:37:37 -0600 Subject: unittest In-Reply-To: <1cbd6f830908142028v638a4c06jf0f859be712e724c@mail.gmail.com> References: <1cbd6f830908142028v638a4c06jf0f859be712e724c@mail.gmail.com> Message-ID: This is an interesting question. I am just wondering: do you really have that many features that it would be impossible to just have a shell script run specific types of input or tests? When I did programming in the past for education they just had lists of input data and we ran the program against the test data. I just get slightly confused when "test suites" start to have to apply? On Fri, Aug 14, 2009 at 9:28 PM, Mag Gam wrote: > I am writing an application which has many command line arguments. > For example: foo.py -args "bar bee" > > I would like to create a test suit using unittest so when I add > features to "foo.py" I don't want to break other things. I just heard > about unittest and would love to use it for this type of thing. > > so my question is, when I do these tests do I have to code them into > foo.py? I prefer having a footest.py which will run the regression > tests. Any thoughts about this? > > TIA > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bouncyinc at gmail.com Sat Aug 15 23:40:23 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 21:40:23 -0600 Subject: ignored test cases in unittest In-Reply-To: References: Message-ID: So you are saying you have several hundred tests you have to do on your program? On Sat, Aug 15, 2009 at 7:04 PM, Terry wrote: > Hi, > > I have some 100s unittest cases with my python program. And sometimes, > I did quick-and-dirty work by ignoring some test cases by adding an > 'x' (or something else) to the beginning of the case name. > As time pass by, it's very hard for me to find which test cases are > ignored. > > It seemed the to me that python unittest module does not support the > counting of ignored test cases directly. Is there any ready solution > for this? > > br, Terry > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bouncyinc at gmail.com Sat Aug 15 23:44:03 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 21:44:03 -0600 Subject: Python or ActionScript 3.0 In-Reply-To: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> References: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> Message-ID: If it were me I'd go with python at least based on the fact that it's more supported and more popular, enough so that it has o'reiley soruces on it. On Sat, Aug 15, 2009 at 3:32 PM, Jaseem wrote: > Hi, > > Is python similar to actionscript 3.0 > Which is better to create a rich gui internet application? > Is it AS 3.0 with flex or python with its GUI libs? > > Is python in demand? > Heard that python is similar to lisp. But both python and AS 3.0 is > almost identical. Which is more similar to lisp are powerful? > > Thank You. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bouncyinc at gmail.com Sat Aug 15 23:59:09 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 21:59:09 -0600 Subject: random.gauss vs. random.normalvariate In-Reply-To: References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> Message-ID: On Sat, Aug 15, 2009 at 7:23 PM, Dennis Lee Bieber wrote: > On Sat, 15 Aug 2009 14:34:36 -0600, John Haggerty > declaimed the following in gmane.comp.python.general: > > > What does the term "thread safe" mean exactly. I never had to program > with > > "threads" before > > That, part way through the logic of the function, control could be > switched to a different thread which call the same function... This > second call would change some of the internal values and may then be > preempted and control returned to the first thread, which continues the > rest of the function with different values then it had when first > preempted. > > A very contrived example, untested of course, consider it > pseudo-code... > > startt = None > > def atimer(): > global startt > startt = time.time() > time.sleep(5) > print time.time() - startt > > t1 = threading.thread(atimer) > t2 = threading.thread(atimer) > t1.start() > t2.start() > > Say t1 gets all the way up to the sleep call, and (since sleep is a > releasing call), t2 then starts. t2 changes the value of startt; and > sleeps... both sleep and presuming the resolution is fine enough, t1 > resumes, and prints a delta time that is incorrect -- it is printing > the time difference from when t2 started to sleep, not from when t1 > started to sleep. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > Interesting so it seems that the compiler(c/c++)interpreter(perl, python)/vm(java) doesn't do this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From terry.yinzhe at gmail.com Sun Aug 16 00:09:45 2009 From: terry.yinzhe at gmail.com (Terry Yin) Date: Sun, 16 Aug 2009 12:09:45 +0800 Subject: ignored test cases in unittest In-Reply-To: References: Message-ID: Yes, should be more than 200. But now 187+ are running (some are 'ignored').It's a personal project, I just don't feel safe without all the testing as it grows bigger and bigger. On Sun, Aug 16, 2009 at 11:40 AM, John Haggerty wrote: > So you are saying you have several hundred tests you have to do on your > program? > > On Sat, Aug 15, 2009 at 7:04 PM, Terry wrote: > >> Hi, >> >> I have some 100s unittest cases with my python program. And sometimes, >> I did quick-and-dirty work by ignoring some test cases by adding an >> 'x' (or something else) to the beginning of the case name. >> As time pass by, it's very hard for me to find which test cases are >> ignored. >> >> It seemed the to me that python unittest module does not support the >> counting of ignored test cases directly. Is there any ready solution >> for this? >> >> br, Terry >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -- ------------------------- Blog: http://terry-yinzhe.spaces.live.com/ twitter: http://twitter.com/terryyin -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sun Aug 16 00:18:36 2009 From: http (Paul Rubin) Date: 15 Aug 2009 21:18:36 -0700 Subject: random.gauss vs. random.normalvariate References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> Message-ID: <7xd46ws86b.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > No language can guard against independent access of a shared/global > object by multiple threads... Erlang? From bouncyinc at gmail.com Sun Aug 16 00:23:33 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 22:23:33 -0600 Subject: random.gauss vs. random.normalvariate In-Reply-To: <7xd46ws86b.fsf@ruckus.brouhaha.com> References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> <7xd46ws86b.fsf@ruckus.brouhaha.com> Message-ID: Erlang I assume is a computer programming language? On Sat, Aug 15, 2009 at 10:18 PM, Paul Rubin wrote: > Dennis Lee Bieber writes: > > No language can guard against independent access of a shared/global > > object by multiple threads... > > Erlang? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sbassi at clubdelarazon.org Sun Aug 16 00:55:11 2009 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sun, 16 Aug 2009 01:55:11 -0300 Subject: Python or ActionScript 3.0 In-Reply-To: <8a14e744-eb6c-4ae2-9bb4-2e32fcb987ae@v20g2000yqm.googlegroups.com> References: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> <8a14e744-eb6c-4ae2-9bb4-2e32fcb987ae@v20g2000yqm.googlegroups.com> Message-ID: <9e2f512b0908152155w47318f81r866190ee8bcf1b4@mail.gmail.com> On Sat, Aug 15, 2009 at 10:29 PM, Douglas Alan wrote: > Python doesn't run in your typical web browser, but it is common to > use Python for doing the server-side programming, along with a Python- > based web development framework, such as Django. > You could use Jython to make a JVM applet that would run in a browser, > but JVM applets aren't very popular for a variety of reasons, and I > doubt the performance would be very good. There is another way to run Python in a browser: MS Silverlight, it runs IronPython on web browsers. http://www.trypython.org/ From kee at kagi.com Sun Aug 16 01:04:25 2009 From: kee at kagi.com (Kee Nethery) Date: Sat, 15 Aug 2009 22:04:25 -0700 Subject: Komodo(!) In-Reply-To: <553649.43098.qm@web110605.mail.gq1.yahoo.com> References: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> <553649.43098.qm@web110605.mail.gq1.yahoo.com> Message-ID: <5C409E92-2D78-4356-9ED0-34F418CEF2B4@kagi.com> On Aug 14, 2009, at 1:55 PM, William wrote: > Personally, I rather like Wing I tried Wing and basically as a newbie, there were too many setup parameters that I did not know how to set correctly and I could never get it to work for me. It runs under X11 and I guess that was just a bit too techie for me to get it to work properly. It's probably a very nice IDE and they were certainly helpful with their support but after a bunch of back and forths I decided to go back to Komodo. Have not looked at NetBeans. I'm a newbie and I need something that just works. Launch it and use it. Komodo meets that need for me. I've heard there is a nice add-on to Eclipse but Eclipse has even more setup variables than Wings and I've avoided it for that reason. Kee From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 01:05:01 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 05:05:01 GMT Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> Message-ID: <029783cd$0$20634$c3e8da3@news.astraweb.com> On Sat, 15 Aug 2009 20:00:23 -0700, Douglas Alan wrote: > So, as far as I can tell, Python has no real authority to throw stones > at C++ on this little tiny particular issue. I think you're being a tad over-defensive. I asked a genuine question about a quote in somebody's signature. That's a quote which can be found all over the Internet, and the poster using it has (as far as I know) no official capacity to speak for "Python" -- while Aahz is a high-profile, well-respected Pythonista, he's not Guido. Now that I understand what the semantics of cout << "Hello world" are, I don't have any problem with it either. It is a bit weird, "Hello world" >> cout would probably be better, but it's hardly the strangest design in any programming language, and it's probably influenced by input redirection using < in various shells. -- Steven From bouncyinc at gmail.com Sun Aug 16 01:14:39 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 15 Aug 2009 23:14:39 -0600 Subject: redoing libgmail interface to "smtplib" blah? In-Reply-To: References: Message-ID: I did detect one problem thus far File "test.py", line 152 if len(args) == 1 and args[0] = "-c": On Sat, Aug 15, 2009 at 7:23 PM, Dennis Lee Bieber wrote: > On Sat, 15 Aug 2009 14:23:26 -0600, John Haggerty > declaimed the following in gmane.comp.python.general: > > > The following program is theoretically supposed to use a supported > library. > > Issues have come up where the library is not working and now another > > interface is being requierd to be used. > > > > At this point I'm looking at just changing the send commands but don't > feel > > confident in doing so. Wondering specifically what would have to be > changed > > to what. > > > > Thanks for your time :) > > Ugh... I'm afraid if I attacked this program I'd have to > restructure > the entire thing... There are no signs of any functional decomposition > in that -- if Python had an unstructured GOTO, I'd suspect this would > have been a spaghetti-code program... As it is, the best I can call it > is lasagna-code (interwoven but distinct layers in a linear form > from one end to the other). > > > > if __name__ == "__main__": > > import os,time,sys,libgmail > > from subprocess import Popen,PIPE > > main(sys.argv) > > Given the position of the import statements, this file can NOT be > used as an importable module for use by other programs, so the whole > breakdown of a main() is meaningless; might as well remove that if, the > def main(): line, move the imports to the top, and unindent the rest one > level. > > All those embedded calls to exit() also offend me; I'm from the "one > in, one out" school (though I'll use break and continue in a loop, I > still favor just one usage of them in such) > > Ideally, all the SMS related stuff would be isolated apart from the > email stuff. Would make changing email interface a lot more intuitive. > > Out of a fit of boredom, though it probably doesn't help your real > problem, and it has not been tested at all, this is my restructuring of > the code listing. > > -=-=-=-=-=-=-=- > import os > import time > import sys > import subprocess > > import libgmail > > > CARRIERLIST = [ ("3 River Wireless", "@sms.3rivers.net"), > ("7-11 Speakout","@cingularme.com"), > # ("Airtel (Karnataka","India) Alaska > Communications Systems"), > ("Alltel Wireless","@message.alltel.com"), > ("AT&T Wireless","@txt.att.net"), > ("Bell Mobility (Canada)","@txt.bell.ca"), > ("Boost Mobile","@myboostmobile.com"), > ("Cellular One (Dobson)","@mobile.celloneusa.com"), > ("Cingular (Postpaid)","@cingularme.com"), > ("Centennial Wireless","@cwemail.com"), > ("Cingular (GoPhone prepaid)","@cingularme.com"), > ("Claro (Nicaragua)","@ideasclaro-ca.com"), > ("Comcel","@comcel.com.co"), > ("Cricket","@sms.mycricket.com"), > ("CTI","@sms.ctimovil.com.ar"), > ("Emtel (Mauritius)","@emtelworld.net"), > ("Fido (Canada)","@fido.ca"), > ("General Communications Inc.","@msg.gci.net"), > ("Globalstar","@msg.globalstarusa.com"), > ("Helio","@myhelio.com"), > ("Illinois Valley Cellular","@ivctext.com"), > # ("i wireless",".iws at iwspcs.net"), > ("Meteor (Ireland)","@sms.mymeteor.ie"), > ("Mero Mobile (Nepal)","@sms.spicenepal.com"), > ("MetroPCS","@mymetropcs.com"), > ("Movicom","@movimensaje.com.ar"), > ("Mobitel (Sri Lanka)","@sms.mobitel.lk"), > ("Movistar (Colombia)","@movistar.com.co"), > ("MTN (South Africa)","@sms.co.za"), > ("MTS (Canada)","@text.mtsmobility.com"), > ("Nextel (Argentina)","@nextel.net.ar"), > ("Orange (Poland)","@orange.pl"), > ("Personal (Argentina)","@personal-net.com.ar"), > ("Plus GSM (Poland)","@text.plusgsm.pl"), > ("President's Choice (Canada)","@txt.bell.ca"), > ("Qwest","@qwestmp.com"), > ("Rogers (Canada)","@pcs.rogers.com"), > ("Sasktel (Canada)","@sms.sasktel.com"), > ("Setar Mobile email (Aruba)","@mas.aw"), > ("Solo Mobile","@txt.bell.ca"), > ("Sprint (PCS)","@messaging.sprintpcs.com"), > ("Sprint (Nextel)","@page.nextel.com"), > ("Suncom","@tms.suncom.com"), > ("T-Mobile","@tmomail.net"), > ("T-Mobile (Austria)","@sms.t-mobile.at"), > ("Telus Mobility (Canada)","@msg.telus.com"), > ("Thumb Cellular","@sms.thumbcellular.com"), > ("Tigo (Formerly Ola)","@sms.tigo.com.co"), > ("Unicel","@utext.com"), > ("US Cellular","@email.uscc.net"), > ("Verizon","@vtext.com"), > ("Virgin Mobile (Canada)","@vmobile.ca"), > ("Virgin Mobile (USA)","@vmobl.com"), > ("YCC","@sms.ycc.ru"), > ("Orange (UK)","@orange.net"), > ("Cincinnati Bell Wireless","@gocbw.com"), > ("T-Mobile Germany","@t-mobile-sms.de"), > ("Vodafone Germany","@vodafone-sms.de"), > ("E-Plus","@smsmail.eplus.de") ] > > INSTRUCTIONS = """ > ------Usage--------------------------------------------------------------- > ------Start Service --- > ogss.py USERNAME PASSWORD CELL-NUMBER CARRIER-NUMBER > ------List carriers --- > ogss.py -c > > ------Useage from > phone---------------------------------------------------- > ------Ogss COMMAND > """ > > #odd notation is to split by lines, then join lines with a space > PHONEINSTRUCTIONS = " ".join( > """To use OGSS reply to this message with an SMS starting with > "Ogss". Whatever follows "Ogss" will be executed on your computer > """.split()) > > class Logfile(object): > def __init__(self): > self.logname = os.path.join(os.environ["HOME"], "ogss.log") > if not os.path.exists(self.logname): > try: > self.log = open(logname, "w+") > except: > print "Failure to create log file; check permissions" > self.log = None > else: > try: > print "Opening log file: %s" % self.logname > self.log = open(logname, "r+") > except: > self.log = None > > def opened(self): > return self.log is not None > > def readParse(self): > if self.opened(): > self.log.seek(0, os.SEEK_SET) > retdata = [] > for line in self.log: > eid = line.split("~") > if len(eid) >= 2: > retdata.append(int(eid[0])) > return retdata > > def write(self, ID, commandLine): > if self.opened(): > self.log.seek(0, os.SEEK_END) > self.log.write("%s %s\n" % (ID, commandLine)) > > def close(self): > if self.opened(): > self.log.close() > > class MailConnection(object): > #might have been possible to subclass from libgmail.GmailAccount > #but by incorporating that as a component instead makes it > #a bit easier to replace with something else (SMTP?) > def __init__(self, uname, passwd): > self.uname = uname > self.passwd = passwd > self.account = libgmail.GmailAccount(self.uname, self.passwd) > > def login(self): > self.account.login() > > def sendMessage(self, message): > self.account.sendMessage(message) > > def getMessageByQuery(qstring, flag): #what does flag do? > return self.account.getMessagesByQuery(qstring, flag) > > def composeMessage(self, to, subject, body): > return libgmail.GmailComposedMessage(to, > subject, > body) > > > def parseCommandLine(args): > retdata = None > if len(args) == 1 and args[0] = "-c": > for i, car in enumerate(CARRIERLIST): > print "%5d -- %s" % (i, car[0]) > > elif len(args) > 3: > (username, password, number, carrierID) = tuple(args[:4]) > carrier = CARRIERLIST[int(carrierID)] > cell_email = number + carrier[1] > retdata = { "User" : username, > "Pass" : password, > "Number" : number, > "ID" : carrierID, > "Carrier" : carrier, > "Cell" : cell_email } > > else: > print INSTRUCTIONS > return retdata > > > def main(argv): > print "Starting ogss" > > print "Opening log file" > logfile = Logfile() > if logfile.opened(): > print "Parsing log file" > execd = logfile.readParse() > > print "Parsing command line input" > callee = parseCommandLine(argv[1:]) #strip program name > > if callee is not None: > print "Logging in to mail server" > account = MailConnection(callee["User"], > callee["Pass"]) > account.login() > > ## #if log file contents are empty, send instructions to > ## #user's phone > ## if not len(execd): > ## account.sendMessage( > ## account.composeMessage( > ## callee["Cell"], > ## "OGSS Instructions", > ## PHONEINSTRUCTIONS) ) > > > try: > while True: > print "Listening for commands" > print "Getting mailbox contents" > searchResult = account.getMessagesByQuery( > "from:" + callee["Cell"], > True ) > if searchResult: #presume empty if no messages > maxID = 0 > maxMessage = None > for thread in searchResult: > for message in thread: > if callee["Cell"] == message.sender: > mID = int(message.id, 16) > if mID > maxID: > maxID = mID > maxMessage = message > > if maxID and maxMessage: > if not maxID in execd: > print "Parsing command from message" > ogssSplit = > maxMessage.source.split("Ogss") > command = ogssSplit[-1].split( > "")[0].split() > > result = subprocess.Popen( > command, > stdout = subprocess.PIPE) > body = result.stdout.read() > account.sendMessage( > account.composeMessage( > callee["Cell"], > "STDOUT", > "\n" + body) ) > logfile.write(maxID, " ".join(command)) > > #TODO add ability to choose sleep time > time.sleep(2) > except (KeyboardInterrupt): > pass #exit WHILE loop with or equivalent > ## else: > ## pass #no login data supplied on startup > > logfile.close() > else: > print "Could not open log file, check permissions" > > > if __name__ == "__main__": > main(sys.argv) > -=-=-=-=-=-=-=- > > Everything that needs to be changed for SMTP should be in the class > MailConnection. Note: it appears that this program expects a > bidirectional mail connection -- similar to IMAP, where one connection > access both outgoing mail AND incoming mail that is stored on the remote > system. You'll probably need to use both SMTP to send the messages, and > POP3 to retrieve the mailbox contents -- and what you do about leaving > messages in a POP3 mailbox is up to you; most clients normally delete > them after fetching, but if the query has to fetch all messages just to > process one set, that may be a concern... Or you use something else to > retrieve messages and store them in a local mailbox for subsequent > usage. > > HMMM that does bring up the point -- where is your existing problem? > Reading GMAIL or sending to GMAIL? > > Heh... with a bit of work, I could probably create a Eudora filter > to invoke a Python script on each new fetched email with the proper > subject/content, and then file it away is a different (local) mailbox -- > and do away with that whole log file search and message searching as > messages would be processed as received and never seen again. > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From enleverLesX_XXmcX at XmclavXeauX.com Sun Aug 16 01:43:29 2009 From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP) Date: Sun, 16 Aug 2009 07:43:29 +0200 Subject: Python or ActionScript 3.0 References: <8a14e744-eb6c-4ae2-9bb4-2e32fcb987ae@v20g2000yqm.googlegroups.com> Message-ID: <4a879c84$0$17754$ba4acef3@news.orange.fr> Hi! > Python doesn't run in your typical web browser Yes, Python can do it... on Windows. Two (examples) ways: - ActiveScripting (PythonScript), include in PyWin32 - Gestalt (who mix Python, Ruby & Javascript, via Silverlight) And alse, these two solutions run OK in HTA (HTml Application) for use HTML as GUI tool in local applications. @-salutations -- Michel Claveau From enleverLesX_XXmcX at XmclavXeauX.com Sun Aug 16 01:46:45 2009 From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP) Date: Sun, 16 Aug 2009 07:46:45 +0200 Subject: Python- javascript References: <985d635f-5784-40a7-a2bb-b76900c200d9@b15g2000yqd.googlegroups.com> Message-ID: <4a879d47$0$17765$ba4acef3@news.orange.fr> Hi! If you are under Windows, you can drive IE, for indirect drive the web-pages. In this case, you can then interact with pages & the javascript's scripts included. For more, see Pywin32, Pamie, Pxie, etc. @-salutations -- Michel Claveau From darkwater42 at gmail.com Sun Aug 16 01:51:07 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sat, 15 Aug 2009 22:51:07 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> Message-ID: <34dd6e0e-3b47-4761-ad7a-9038b0d36209@v36g2000yqv.googlegroups.com> On Aug 16, 1:05?am, Steven D'Aprano wrote: > On Sat, 15 Aug 2009 20:00:23 -0700, Douglas Alan wrote: > > So, as far as I can tell, Python has no real authority to throw stones > > at C++ on this little tiny particular issue. > I think you're being a tad over-defensive. Defensive? Personally, I prefer Python over C++ by about a factor of 100X. I just find it a bit amusing when someone claims that some programming language has a particular fatal flaw, when their own apparently favorite language has the very same issue in an only slightly different form. > the poster using it has (as far as I know) no official capacity to speak > for "Python" I never thought he did. I wasn't speaking literally, as I'm not under the opinion that any programming language has any literal authority or any literal ability to throw stones. > Now that I understand what the semantics of cout << "Hello world" are, I > don't have any problem with it either. It is a bit weird, "Hello world">> cout > would probably be better, but it's hardly the strangest design in > any programming language, and it's probably influenced by input > redirection using < in various shells. C++ also allows for reading from stdin like so: cin >> myVar; I think the direction of the arrows probably derives from languages like APL, which had notation something like so: myVar <- 3 [] <- myVar "<-" was really a little arrow symbol (APL didn't use ascii), and the first line above would assign the value 3 to myVar. In the second line, the "[]" was really a little box symbol and represented the terminal. Assigning to the box would cause the output to be printed on the terminal, so the above would output "3". If you did this: [] -> myVar It would read a value into myVar from the terminal. APL predates Unix by quite a few years. |>ouglas From xahlee at gmail.com Sun Aug 16 01:54:06 2009 From: xahlee at gmail.com (Xah Lee) Date: Sat, 15 Aug 2009 22:54:06 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. Message-ID: Xah's Edu Corner: The importance of syntax & notations. http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstract.html this article should teach the coding sophomorons and computer ?science? idiotic authors who harbor the notion that syntax is not important, picked up by all the elite i-reddit & twittering & hacker news am-hip dunces. Further readings: ? The TeX Pestilence http://xahlee.org/cmaci/notation/TeX_pestilence.html ? A Notation for Plane Geometry http://xahlee.org/cmaci/notation/plane_geometry_notation.html ? The Concepts and Confusions of Prefix, Infix, Postfix and Fully Nested Notations http://xahlee.org/UnixResource_dir/writ/notations.html ? The Problems of Traditional Math Notation http://xahlee.org/cmaci/notation/trad_math_notation.html Xah ? http://xahlee.org/ ? From timr at probo.com Sun Aug 16 02:07:07 2009 From: timr at probo.com (Tim Roberts) Date: Sat, 15 Aug 2009 23:07:07 -0700 Subject: Pygresql, and query meta informations References: <55aceb1c-b3d9-4f9b-b8cf-d9833edb2660@c29g2000yqd.googlegroups.com> Message-ID: <368f85prhp9d349trtooj5qsqmqmip0qqp@4ax.com> durumdara wrote: > >Pygresql, DB-API. > >I search for a solution to get meta information about last query, >because I must export these infos to Delphi. > >Delphi have TDataSet, and it have meta structure that must be defined >before I create it. >For char/varchar fields I must define their sizes! > >Pygresql is not retreive the field sizes. You should be able to get that information from the .description member of the cursor object. Have you checked it? If not, you will have to use fetch the information from the Postgres-specific tables, pg_class and pg_attribute. pg_class contains information about your tables; when you fetch the class number for your table, you can look up the columns in pg_attribute. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From nagle at animats.com Sun Aug 16 02:20:34 2009 From: nagle at animats.com (John Nagle) Date: Sat, 15 Aug 2009 23:20:34 -0700 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: <4vmil6-ait.ln1@nb2.stroeder.com> Message-ID: <4a87a444$0$1627$742ec2ed@news.sonic.net> Hendrik van Rooyen wrote: > On Saturday 15 August 2009 14:40:35 Michael Str?der wrote: >> Hendrik van Rooyen wrote: >>> In the past, on this group, I have made statements that said that on >>> Linux, the serial port handling somehow does not allow transmitting and >>> receiving at the same time, and nobody contradicted me. Absolutely false. >> Despite all the good comments here by other skilled people I'd recommend to >> determine whether the transmission line to the devices accessed support >> full duplex. All standard PC serial ports are full-duplex devices. Here's a program I wrote which uses "pyserial" to drive Baudot teletypes as full-duplex devices. https://sourceforge.net/projects/baudotrss/ This uses an input thread and an output thread. It reads RSS feeds and prints them on antique Teletype machines. (Reuters RSS feeds produce a classic news ticker. Twitter RSS feeds work but look silly when hammered out on yellow paper at 45.45 baud.) > > You raise a good point, that is probably not well known amongst the youngsters > here, as simple serial multidropping has gone out of fashion. Actually, no. Dynamixel servos as used on the latest Bioloid robots are multidrop serial RS-485. But outside the embedded world, nobody uses that stuff any more. (Embedded is going Ethernet; it's overkill but works fine and is now cheap.) John Nagle From emmanuel.surleau at gmail.com Sun Aug 16 02:30:54 2009 From: emmanuel.surleau at gmail.com (Emmanuel Surleau) Date: Sun, 16 Aug 2009 08:30:54 +0200 Subject: Python 'for' loop is memory inefficient In-Reply-To: <4A8612CE.7080700@stoneleaf.us> References: <24980842.post@talk.nabble.com> <4A8612CE.7080700@stoneleaf.us> Message-ID: <200908160830.55031.emmanuel.surleau@gmail.com> > Dr. Phillip M. Feldman wrote: [snip] > > def is_prime(n): > > for j in range(2,n): > > if (n % j) == 0: return False > > return True > > > > It seems as though Python is actually expanding range(2,n) into a list of > > numbers, even though this is incredibly wasteful of memory. There should > > be a looping mechanism that generates the index variable values > > incrementally as they are needed. > > You already have an answer to the range issue, so I will only add that > putting a loop inside another loop is a decent way to expand the time > taken. > > I will also observe that if you were to stop programming whatever > language you are more familiar with in Python, and start programming > Python in Python, you'll have an easier time of it. I don't see what's particularly un-Pythonic with this code. Not using xrange() is a mistake, certainly, but it remains clear, easily understandable code which correctly demonstrates the naive algorithm for detecting whether n is a prime. It doesn't call for condescension > The Dive Into Python is an excellent start for that. I never read it, but I was under the impression that the tutorial on python.org was geared toward programmers moving to Python from other languages. It was also my impression that Dive Into Python is rather outdated and occasionally inaccurate (based on comments on this mailing list). Cheers, Emm From dmitrey.kroshko at scipy.org Sun Aug 16 02:36:56 2009 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Sat, 15 Aug 2009 23:36:56 -0700 (PDT) Subject: "for" cycle with assigning index References: <4149f0b2-603d-4c59-aa34-bd0fd826303c@b14g2000yqd.googlegroups.com> Message-ID: <7eac79f9-8b38-4aa6-8bd7-4dc042037b31@t13g2000yqt.googlegroups.com> Thanks all, especially Dennis for your detailed answer. left_arr_indexes is list of nonnegative integers, eg [0,0,0,1,1,4] IndDict is a dict like {0: [1,2], 3: [0,1], 10:[0,2,3]}, so that's why I don't use python list instead. The code is taken from OpenOpt framework that I develop. Currently I have implemented another workaround but the solution you proposed can be used in other parts of code. Regards, D. On Aug 16, 4:23?am, Dennis Lee Bieber wrote: > On Sat, 15 Aug 2009 13:22:08 -0700, Dennis Lee Bieber > declaimed the following in > gmane.comp.python.general: > > ? ? ? ? Okay -- my lack of experience with lambda shows... forgot to guard > the intermediates... > > > > for i in xrange(len(Funcs2)): > > > ? ? ?Funcs.append(lambda i=i,*args, **kwargs: (Funcs2[i](*args, > > > **kwargs)[IndDict[left_arr_indexes[i]]])) > > > > I get "list indices must be integers, not dict" (and i is equal to > > > Python dictionary, that is Funcs2) > > ? ? ? ? So... with the following assumptions (and ignoring all the other > respondents )... > > 1) ? ? ?Funcs2 IS a dictionary keyed by sequential integers starting at 0 > 2) ? ? ?Order in Funcs matters; that is, the first element of the list must > align with the element of the dictionary having key "0" > 3) ? ? ?IndDict and left_arr_indexes DO NOT CHANGE CONTENT after the loop > runs > 4) ? ? ?left_arr_indexes is at least as long as Funcs2 > > assert (min(Funcs2.keys()) == 0 > ? ? ? ? ? ? ? ? ? ? ? ? and > ? ? ? ? ? ? ? ? max(Funcs2.keys()) == (len(Funcs2) - 1)) ? ? ? ?#1 > assert len(left_arr_indexes) >= len(Funcs2) ? ? ? ? ?#4 > > Funcs = [None] * len(Funcs2) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?#2a > for ki, fv in Funcs2.items(): ? #ki->key as index; fv->function value > ? ? ? ? ritmp = IndDict[left_arr_indexes[ki]] ? ? ? ? ? ? ? ? ? ? ? ? ? #3 > ? ? ? ? Funcs[ki] = (lambda ri=ritmp, fn=fv, *args, **kwargs: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? (fn(*args, **kwargs)[ri]) ? ? ? ? ? ? ? ? ? ? ? #2b > > ri and fn used to protect the intermediates, ritmp and fv, from changes > > 2a is needed as the order of .items() is undefined, so .append() can not > be used. This presets the result list size permitting direct indexing > (2b) to fill slots in order. > > #1 can still fail itself if a key is NOT an integer (what is the min() > of 0 and "a") > > ? ? ? ? I still don't know if IndDict is really a list or a dictionary, nor > what left_array_indexes contains (by name, it is a list of values to > index into another list -- but could be a list of keys to access a > dictionary) > > ? ? ? ? And I'll reiterate: if you are using dictionaries in which the keys > are sequential integers starting at 0... Replace them with simple > lists... > -- > ? ? ? ? Wulfraed ? ? ? ? Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ?HTTP://wlfraed.home.netcom.com/ From mail at microcorp.co.za Sun Aug 16 03:24:36 2009 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 16 Aug 2009 09:24:36 +0200 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com><02957d23$0$20647$c3e8da3@news.astraweb.com><5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com><02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> Message-ID: <009f01ca1e42$9c833600$0d00a8c0@Hendrik> >"Steven D'Aprano" wrote: >Now that I understand what the semantics of cout << "Hello world" are, I >don't have any problem with it either. It is a bit weird, "Hello world" >>> cout would probably be better, but it's hardly the strangest design in >any programming language, and it's probably influenced by input >redirection using < in various shells. I find it strange that you would prefer: "Hello world" >> cout over: cout << "Hello world" The latter seems to me to be more in line with normal assignment: - Take what is on the right and make the left the same. I suppose it is because we read from left to right that the first one seems better to you. Another instance of how different we all are. It goes down to the assembler - there are two schools: mov a,b - for Intel like languages, this means move b to a mov a,b - for Motorola like languages, this means move a to b Gets confusing sometimes. - Hendrik From jcm1981 at gmail.com Sun Aug 16 03:57:41 2009 From: jcm1981 at gmail.com (Chang Min Jeon) Date: Sun, 16 Aug 2009 16:57:41 +0900 Subject: my recursive function call is wrong? Message-ID: <22a413260908160057t2802d3cci70658278e7322eb8@mail.gmail.com> I'm trying to write program to translate define macro in 'C'. And start_parse has return condition that list's length is 0. At this time return statement invoke start_parse() function. I can't understand do that. I'm using Python 2.6.2 in Windows XP import re import sys comment = ''' #if defined (FEATURE_ONENESTED) # define PYTHON_POWERED # if defined(ANY_LANGUAGE) # error # endif #else # define FEATURE_NONE #endif ''' symbol_table = ['FEATURE_ONENESTED'] valid_area = False p_define = re.compile('^[\t ]*#[\t ]*define[\t ]+([a-zA-Z0-9_]+)[\t ]*') p_if = re.compile('^[\t ]*#[\t ]*if[\t ]+defined[\s]*[\(]*([a-zA-Z0-9_]+)[\)]*[\t ]*') p_elif = re.compile('^[\t ]*#[\t ]*elif[\t ]*') p_else = re.compile('^[\t ]*#[\t ]*else[\t ]*') p_endif = re.compile('^[\t ]*#[\t ]*endif[\t ]*') def start_parse(macro): global valid_area if len(macro) == 0: return if valid_area == True: if p_else.match(macro[0]): valid_area = False macro.pop(0) start_parse(macro) match = p_define.match(macro[0]) if match: symbol_table.append(match.group(1)) macro.pop(0) start_parse(macro) match = p_if.match(macro[0]) if match: for symbol in symbol_table:#print match.group(1) if match.group(1) == symbol: #print match.group(1) valid_area = True else: valid_area = False if p_else.match(macro[0]): macro.pop(0) start_parse(macro) match = p_endif.match(macro[0]) if match: valid_area = False macro.pop(0) start_parse(macro) if __name__ == '__main__': l = comment.splitlines() start_parse(l) print symbol_table -- CashFlow To be rich. -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Aug 16 04:04:59 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 04:04:59 -0400 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> Message-ID: <50697b2c0908160104k7d74ace9jda8f4b927402942@mail.gmail.com> On Sat, Aug 15, 2009 at 8:09 AM, Xavier Ho wrote: > Hey all, > > I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in the > documentation. > > Is there a substitution for this special method in 3.1, or do I really have > to define all six rich comparison methods to work it out? I don't think so. Quoting http://docs.python.org/dev/py3k/reference/datamodel.html "There are no swapped-argument versions of [the comparison] methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other?s reflection, __le__() and __ge__() are each other?s reflection, and __eq__() and __ne__() are their own reflection." I believe this means you only need to define one method from each of the following pairs to get all the operators working: * __eq__ or __ne__ * __lt__ or __gt__ * __ge__ or __le__ Cheers, Chris -- http://blog.rebertia.com From clp2 at rebertia.com Sun Aug 16 04:07:20 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 04:07:20 -0400 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> Message-ID: <50697b2c0908160107k6f31141dt5143071d0ff54c71@mail.gmail.com> On Sat, Aug 15, 2009 at 1:06 PM, Mark Lawrence wrote: > Xavier Ho wrote: >> >> Hey all, >> >> I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in >> the >> documentation. >> >> Is there a substitution for this special method in 3.1, or do I really >> have >> to define all six rich comparison methods to work it out? >> >> If this question has already been asked somewhere, I apologise in advance. >> Already googled around but I didn't find information on this. >> >> Any replies appreciated. >> > http://bytes.com/topic/python/answers/844614-python-3-sorting-comparison-function That seems to be about the built-in function cmp(). The OP was asking about the special method __cmp__ and the related rich comparison special methods (__eq__, __lt__, etc). Cheers, Chris -- http://blog.rebertia.com From clp2 at rebertia.com Sun Aug 16 04:15:43 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 04:15:43 -0400 Subject: random.gauss vs. random.normalvariate In-Reply-To: References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> <7xd46ws86b.fsf@ruckus.brouhaha.com> Message-ID: <50697b2c0908160115l2db5fe2eo4c665a3a83c4a8@mail.gmail.com> > On Sat, Aug 15, 2009 at 10:18 PM, Paul Rubin > wrote: >> >> Dennis Lee Bieber writes: >> > ? ? ? No language can guard against independent access of a >> > shared/global >> > object by multiple threads... >> >> Erlang? On Sun, Aug 16, 2009 at 12:23 AM, John Haggerty wrote: > Erlang I assume is a computer programming language? http://en.wikipedia.org/wiki/Erlang_(programming_language) There's a reason Wikipedia has a search function... :) Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 04:22:58 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 08:22:58 GMT Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> Message-ID: <0297b230$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 09:24:36 +0200, Hendrik van Rooyen wrote: >>"Steven D'Aprano" wrote: > >>Now that I understand what the semantics of cout << "Hello world" are, I >>don't have any problem with it either. It is a bit weird, "Hello world" >>>> cout would probably be better, but it's hardly the strangest design >>>> in >>any programming language, and it's probably influenced by input >>redirection using < in various shells. > > I find it strange that you would prefer: > > "Hello world" >> cout > over: > cout << "Hello world" > > The latter seems to me to be more in line with normal assignment: - Take > what is on the right and make the left the same. I don't like normal assignment. After nearly four decades of mathematics and programming, I'm used to it, but I don't think it is especially good. It confuses beginners to programming: they get one set of behaviour drilled into them in maths class, and then in programming class we use the same notation for something which is almost, but not quite, the same. Consider the difference between: y = 3 + x x = z as a pair of mathematics expressions versus as a pair of assignments. What conclusion can you draw about y and z? Even though it looks funny due to unfamiliarity, I'd love to see the results of a teaching language that used notation like: 3 + x -> y len(alist) -> n Widget(1, 2, 3).magic -> obj etc. for assignment. My prediction is that it would be easier to learn, and just as good for experienced coders. The only downside (apart from unfamiliarity) is that it would be a little bit harder to find the definition of a variable by visually skimming lines of code: your eyes have to zig-zag back and forth to find the end of the line, instead of running straight down the left margin looking for "myvar = ...". But it should be easy enough to search for "-> myvar". > I suppose it is because > we read from left to right that the first one seems better to you. Probably. -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 04:32:35 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 08:32:35 GMT Subject: Python 'for' loop is memory inefficient References: <24980842.post@talk.nabble.com> <4A8612CE.7080700@stoneleaf.us> Message-ID: <0297b471$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 08:30:54 +0200, Emmanuel Surleau wrote: [...] >> I will also observe that if you were to stop programming whatever >> language you are more familiar with in Python, and start programming >> Python in Python, you'll have an easier time of it. > > I don't see what's particularly un-Pythonic with this code. Not using > xrange() is a mistake, certainly, but it remains clear, easily > understandable code which correctly demonstrates the naive algorithm for > detecting whether n is a prime. It doesn't call for condescension It's a particular unfair criticism because the critic (Ethan Furman) appears to have made a knee-jerk reaction. The "some language in Python" behaviour he's reacting to is the common idiom: for i in range(len(seq)): do_something_with(seq[i]) instead of the "Python in Python" idiom: for obj in seq: do_something_with(obj) That's a reasonable criticism, but *not in the case*. Ethan appears to have made the knee-jerk reaction "for i in range() is Bad" without stopping to think about what this specific piece of code is actually doing. (Replace 'obj' with 'j', 'seq' with 'range(2, n)', and 'do_something_with' with 'if (n % j) == 0: return False', and you have the exact same code pattern.) -- Steven From darkwater42 at gmail.com Sun Aug 16 04:41:41 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sun, 16 Aug 2009 01:41:41 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <0297b230$0$20634$c3e8da3@news.astraweb.com> Message-ID: <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> On Aug 16, 4:22?am, Steven D'Aprano wrote: > I don't like normal assignment. After nearly four decades of mathematics > and programming, I'm used to it, but I don't think it is especially good. > It confuses beginners to programming: they get one set of behaviour > drilled into them in maths class, and then in programming class we use > the same notation for something which is almost, but not quite, the same. > Consider the difference between: > > y = 3 + x > x = z > > as a pair of mathematics expressions versus as a pair of assignments. > What conclusion can you draw about y and z? Yeah, the syntax most commonly used for assignment today sucks. In the past, it was common to see languages with syntaxes like y <- y + 1 or y := y + 1 or let y = y + 1 But these languages have mostly fallen out of favor. The popular statistical programming language R still uses the y <- y + 1 syntax, though. Personally, my favorite is Lisp, which looks like (set! y (+ y 1)) or (let ((x 3) (y 4)) (foo x y)) I like to be able to read everything from left to right, and Lisp does that more than any other programming language. I would definitely not like a language that obscures assignment by moving it over to the right side of lines. |>ouglas From max at alcyone.com Sun Aug 16 04:46:11 2009 From: max at alcyone.com (Erik Max Francis) Date: Sun, 16 Aug 2009 01:46:11 -0700 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <0297b230$0$20634$c3e8da3@news.astraweb.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <0297b230$0$20634$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > I don't like normal assignment. After nearly four decades of mathematics > and programming, I'm used to it, but I don't think it is especially good. > It confuses beginners to programming: they get one set of behaviour > drilled into them in maths class, and then in programming class we use > the same notation for something which is almost, but not quite, the same. > Consider the difference between: > > y = 3 + x > x = z > > as a pair of mathematics expressions versus as a pair of assignments. > What conclusion can you draw about y and z? What you're saying is true, but it's still a matter of terminology. The symbol "=" means different things in different contexts, and mathematics and programming are very different ones indeed. The problem is compounded with early languages which lazily confused the two in different context, such as (but not exclusive to) BASIC using = for both assignment and equality testing in what are in esssence totally unrelated contexts. > Even though it looks funny due to unfamiliarity, I'd love to see the > results of a teaching language that used notation like: > > 3 + x -> y > len(alist) -> n > Widget(1, 2, 3).magic -> obj > etc. > > for assignment. My prediction is that it would be easier to learn, and > just as good for experienced coders. This really isn't new at all. Reverse the arrow and the relationship to get:: y <- x + 3 (and use a real arrow rather than ASCII) and that's assignment in APL and a common representation in pseudocode ever since. Change it to := and that's what Pascal used, as well as quite a few mathematical papers dealing with iterative computations, I might add. Once you get past the point of realizing that you really need to make a distinction between assignment and equality testing, then it's just a matter of choosing two different operators for the job. Whether it's <-/= or :=/= or =/== or ->/= (with reversed behavior for assignment) is really academic and a matter of taste at that point. Given the history of programming languages, it doesn't really look like the to-be-assigned variable being at the end of expression is going to get much play, since not a single major one I'm familiar with does it that way, and a lot of them have come up with the same convention independently and haven't seen a need to change. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Get there first with the most men. -- Gen. Nathan Bedford Forrest, 1821-1877 From max at alcyone.com Sun Aug 16 04:48:15 2009 From: max at alcyone.com (Erik Max Francis) Date: Sun, 16 Aug 2009 01:48:15 -0700 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <0297b230$0$20634$c3e8da3@news.astraweb.com> <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> Message-ID: Douglas Alan wrote: > Personally, my favorite is Lisp, which looks like > > (set! y (+ y 1)) For varying values of "Lisp." `set!` is Scheme. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Get there first with the most men. -- Gen. Nathan Bedford Forrest, 1821-1877 From duncan.booth at invalid.invalid Sun Aug 16 05:25:02 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Aug 2009 09:25:02 GMT Subject: ignored test cases in unittest References: <873a7so66v.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Terry writes: > >> It seemed the to me that python unittest module does not support the >> counting of ignored test cases directly. Is there any ready solution >> for this? > > One solution I've seen involves: > > * a custom exception class, ???TestSkipped??? > > * raising that exception at the top of test cases you want to > temporarily skip > > * a custom ???TestResult??? class that knows about a ???skipped??? result > > * a custom reporter class that knows how you want to report that result > I'd add to that a decorator so you can quickly mark a test case as ignored without editing the test itself. Also you could include a reason why it is ignored: @ignore("This test takes too long to run") def test_foo(self): ... That also means you can redefine the decorator easily if you want to try running all the ignored tests. Another decorator useful here is one that asserts that the test will fail. If the test passes then maybe someone fixed whatever was making it fail and if so you want to consider re-enabling it. @fails("Needs the frobnozz module to be updated") def test_whotsit(self): ... From darkwater42 at gmail.com Sun Aug 16 05:31:55 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sun, 16 Aug 2009 02:31:55 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <0297b230$0$20634$c3e8da3@news.astraweb.com> <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> Message-ID: <523a62c0-2c5f-4027-944a-7edb0d4693d8@w41g2000yqb.googlegroups.com> On Aug 16, 4:48?am, Erik Max Francis wrote: > Douglas Alan wrote: > > Personally, my favorite is Lisp, which looks like > > > ? ?(set! y (+ y 1)) > > For varying values of "Lisp." ?`set!` is Scheme. Yes, I'm well aware! There are probably as many different dialects of Lisp as all other programming languages put together. |>ouglas From terry.yinzhe at gmail.com Sun Aug 16 05:38:20 2009 From: terry.yinzhe at gmail.com (Terry) Date: Sun, 16 Aug 2009 02:38:20 -0700 (PDT) Subject: ignored test cases in unittest References: <873a7so66v.fsf@benfinney.id.au> Message-ID: <56527679-4cec-49a1-9b46-c38de8f981c8@g10g2000yqh.googlegroups.com> On Aug 16, 5:25?pm, Duncan Booth wrote: > Ben Finney wrote: > > Terry writes: > > >> It seemed the to me that python unittest module does not support the > >> counting of ignored test cases directly. Is there any ready solution > >> for this? > > > One solution I've seen involves: > > > * a custom exception class, ?TestSkipped? > > > * raising that exception at the top of test cases you want to > > ? temporarily skip > > > * a custom ?TestResult? class that knows about a ?skipped? result > > > * a custom reporter class that knows how you want to report that result > > I'd add to that a decorator so you can quickly mark a test case as ignored > without editing the test itself. Also you could include a reason why it is > ignored: > > ?@ignore("This test takes too long to run") > ?def test_foo(self): > ? ? ... > > That also means you can redefine the decorator easily if you want to try > running all the ignored tests. > > Another decorator useful here is one that asserts that the test will fail. > If the test passes then maybe someone fixed whatever was making it fail and > if so you want to consider re-enabling it. > > ?@fails("Needs the frobnozz module to be updated") > ?def test_whotsit(self): > ? ? ... Thanks for the solutions. I think the decorator idea is what I'm look for:-) From breamoreboy at yahoo.co.uk Sun Aug 16 05:38:50 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 16 Aug 2009 10:38:50 +0100 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: <50697b2c0908160107k6f31141dt5143071d0ff54c71@mail.gmail.com> References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160107k6f31141dt5143071d0ff54c71@mail.gmail.com> Message-ID: Chris Rebert wrote: > On Sat, Aug 15, 2009 at 1:06 PM, Mark Lawrence wrote: >> Xavier Ho wrote: >>> Hey all, >>> >>> I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in >>> the >>> documentation. >>> >>> Is there a substitution for this special method in 3.1, or do I really >>> have >>> to define all six rich comparison methods to work it out? >>> >>> If this question has already been asked somewhere, I apologise in advance. >>> Already googled around but I didn't find information on this. >>> >>> Any replies appreciated. >>> >> http://bytes.com/topic/python/answers/844614-python-3-sorting-comparison-function > > That seems to be about the built-in function cmp(). The OP was asking > about the special method __cmp__ and the related rich comparison > special methods (__eq__, __lt__, etc). > > Cheers, > Chris Blast, I posted the wrong flaming link, sorry everybody. -- Kindest regards. Mark Lawrence. From contact at xavierho.com Sun Aug 16 05:45:42 2009 From: contact at xavierho.com (Xavier Ho) Date: Sun, 16 Aug 2009 19:45:42 +1000 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160107k6f31141dt5143071d0ff54c71@mail.gmail.com> Message-ID: <2d56febf0908160245i5fd0d9f2kba74d112f0826932@mail.gmail.com> On Sun, Aug 16, 2009 at 7:38 PM, Mark Lawrence wrote: > > Blast, I posted the wrong flaming link, sorry everybody. > No, don't be sorry. I found your link very informative, and while it's a little mixed, it could be useful. I'm really looking for a way to set up Python classes' natural ordering for sorting purposes. For example, every object of a class could own an attribute called 'Value'. If I could get Python to sort() a list of classes with that value, would the key=value parameter work, and is there a better way than to redefine 3 or more of the rich comparison special methods, etc. Also, I noticed heapq (the priority queue/heap queue module) doesn't use the natural sorting order like sorted() does. Just saying. Could someone give it a try? Regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregor.lingl at aon.at Sun Aug 16 05:46:19 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Sun, 16 Aug 2009 11:46:19 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: References: <4a85ffe2$0$24643$426a34cc@news.free.fr> <4a87036a$0$2292$91cee783@newsreader02.highway.telekom.at> Message-ID: <4a87d56b$0$1540$91cee783@newsreader04.highway.telekom.at> Mark Tolonen schrieb: > > "Gregor Lingl" wrote in message > news:4a87036a$0$2292$91cee783 at newsreader02.highway.telekom.at... >> Emile van Sebille schrieb: >>> On 8/14/2009 5:22 PM candide said... >> ... >>>> What is the pythonic way to do this ? >>> >>> I like list comps... >>> >>> >>> jj = '1234567890123456789' >>> >>> ",".join([jj[ii:ii+3] for ii in range(0,len(jj),3)]) >>> '123,456,789,012,345,678,9' >>> >>> >>> >>> Emile >>> >> >> Less beautiful but more correct: >> >> >>> ",".join([jj[max(ii-3,0):ii] for ii in >> range(len(jj)%3,len(jj)+3,3)]) >> '1,234,567,890,123,456,789' >> >> Gregor > > Is it? > >>>> jj = '234567890123456789' >>>> ",".join([jj[max(ii-3,0):ii] for ii in range(len(jj)%3,len(jj)+3,3)]) > ',234,567,890,123,456,789' Schluck! Even more ugly: ",".join([jj[max(ii-3,0):ii] for ii in range(len(jj)%3,len(jj)+3,3)]).strip(",") '234,567,890,123,456,789' Gregor > > At least one other solution in this thread had the same problem. > > -Mark > > From terry.yinzhe at gmail.com Sun Aug 16 05:47:42 2009 From: terry.yinzhe at gmail.com (Terry) Date: Sun, 16 Aug 2009 02:47:42 -0700 (PDT) Subject: flatten a list of list Message-ID: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Hi, Is there a simple way (the pythonic way) to flatten a list of list? rather than my current solution: new_list=[] for l in list_of_list: new_list.extend(l) or, new_list=reduce(lambda x,y:x.extend(y), list_of_list) br, Terry From clp2 at rebertia.com Sun Aug 16 05:55:48 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 05:55:48 -0400 Subject: flatten a list of list In-Reply-To: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <50697b2c0908160255v10bfa290jd7ca1ea8635eadbb@mail.gmail.com> On Sun, Aug 16, 2009 at 5:47 AM, Terry wrote: > Hi, > > Is there a simple way (the pythonic way) to flatten a list of list? > rather than my current solution: > > new_list=[] > for l in list_of_list: > ? ?new_list.extend(l) > > or, > > new_list=reduce(lambda x,y:x.extend(y), list_of_list) #only marginally better: from operator import add new_list = reduce(add, list_of_list) #from the itertools recipes: from itertools import chain def flatten(listOfLists): return list(chain.from_iterable(listOfLists)) Cheers, Chris -- http://blog.rebertia.com From foetsch at yahoo.com Sun Aug 16 06:03:53 2009 From: foetsch at yahoo.com (=?ISO-8859-1?Q?Michael_F=F6tsch?=) Date: Sun, 16 Aug 2009 12:03:53 +0200 Subject: flatten a list of list In-Reply-To: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <4A87D989.2030508@yahoo.com> Terry wrote: > Is there a simple way (the pythonic way) to flatten a list of list? This is probably the shortest it can get: sum(list_of_lists, []) Kind Regards, M.F. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 06:18:11 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 10:18:11 GMT Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <0297b230$0$20634$c3e8da3@news.astraweb.com> <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> Message-ID: <0297cd31$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 01:41:41 -0700, Douglas Alan wrote: > I like to be able to read everything from left to right, and Lisp does > that more than any other programming language. > > I would definitely not like a language that obscures assignment by > moving it over to the right side of lines. One could argue that left-assigned-from-right assignment obscures the most important part of the assignment, namely *what* you're assigning, in favour of what you're assigning *to*. In any case, after half a century of left-from-right assignment, I think it's worth the experiment in a teaching language or three to try it the other way. The closest to this I know of is the family of languages derived from Apple's Hypertalk, where you do assignment with: put somevalue into name (Doesn't COBOL do something similar?) Beginners found that *very* easy to understand, and it didn't seem to make coding harder for experienced Hypercard developers. -- Steven From sturlamolden at yahoo.no Sun Aug 16 06:19:51 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Aug 2009 03:19:51 -0700 (PDT) Subject: wxFormBuilder finally supports wxPython Message-ID: Version 3.1 of wxFormBuilder can generate wxPython code. I have previously used wxFormBuilder to generate XRC files for my wxPython projects. Though still in beta, this might be even better. :-) http://wxformbuilder.org/ From mail at johannes-janssen.de Sun Aug 16 06:25:46 2009 From: mail at johannes-janssen.de (Johannes Janssen) Date: Sun, 16 Aug 2009 12:25:46 +0200 Subject: How to find out in which module an instance of a class is created? In-Reply-To: References: <4A7F4874.8030008@johannes-janssen.de> <4A7F6016.2060408@cheimes.de> <4A80967F.9030604@johannes-janssen.de> Message-ID: <4A87DEAA.3020309@johannes-janssen.de> Gabriel Genellina schrieb: > The try/except around sys._getframe(1) is because that function is not > mandatory/available on all Python implementations (that's the case for > jython which doesn't provide it). Thanks, shouldn't such information be part of the python documentation of sys._getframe() (http://docs.python.org/library/sys.html?highlight=sys._getframe#sys._getframe)? Johannes From clp2 at rebertia.com Sun Aug 16 06:30:54 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 06:30:54 -0400 Subject: How to find out in which module an instance of a class is created? In-Reply-To: <4A87DEAA.3020309@johannes-janssen.de> References: <4A7F4874.8030008@johannes-janssen.de> <4A7F6016.2060408@cheimes.de> <4A80967F.9030604@johannes-janssen.de> <4A87DEAA.3020309@johannes-janssen.de> Message-ID: <50697b2c0908160330p43397ac7g86d7e9010cb90d25@mail.gmail.com> On Sun, Aug 16, 2009 at 6:25 AM, Johannes Janssen wrote: > Gabriel Genellina schrieb: >> >> The try/except around sys._getframe(1) is because that function is not >> mandatory/available on all Python implementations (that's the case for >> jython which doesn't provide it). > > Thanks, shouldn't such information be part of the python documentation of > sys._getframe() > (http://docs.python.org/library/sys.html?highlight=sys._getframe#sys._getframe)? The leading underscore kinda indirectly implies it, but yeah, it's worth mentioning. File a bug in the docs: http://bugs.python.org/ Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 06:49:59 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 10:49:59 GMT Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <0297d4a6$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 05:55:48 -0400, Chris Rebert wrote: > On Sun, Aug 16, 2009 at 5:47 AM, Terry wrote: >> Hi, >> >> Is there a simple way (the pythonic way) to flatten a list of list? >> rather than my current solution: >> >> new_list=[] >> for l in list_of_list: >> ? ?new_list.extend(l) >> >> or, >> >> new_list=reduce(lambda x,y:x.extend(y), list_of_list) > > #only marginally better: > from operator import add > new_list = reduce(add, list_of_list) Surely that's going to be O(N**2)? I'd predict that would perform even worse than O(N**2) string concatenation, on account that a string of size N has to allocate space for N bytes, but a list of size N allocates space for N pointers (each 4 bytes, or 8 depending on the system), rounded up to the nearest power of two. Also CPython can optimize string concatenation to O(N) under some circumstances, but not lists. >>> from timeit import Timer >>> setup = """\\ ... L = [ ([None]*5000) for x in xrange(%d) ] ... from operator import add ... """ >>> Timer("reduce(add, L)", setup % 4).repeat(number=1000) [0.53808808326721191, 0.51404905319213867, 0.51157188415527344] >>> Timer("reduce(add, L)", setup % 8).repeat(number=1000) [2.1178171634674072, 3.8830602169036865, 4.72245192527771] >>> Timer("reduce(add, L)", setup % 16).repeat(number=1000) [17.190337896347046, 21.572744131088257, 21.584265947341919] Looks like O(N**2) behaviour to me. -- Steven From mail at johannes-janssen.de Sun Aug 16 06:50:27 2009 From: mail at johannes-janssen.de (Johannes Janssen) Date: Sun, 16 Aug 2009 12:50:27 +0200 Subject: How to find out in which module an instance of a class is created? In-Reply-To: <50697b2c0908160330p43397ac7g86d7e9010cb90d25@mail.gmail.com> References: <4A7F4874.8030008@johannes-janssen.de> <4A7F6016.2060408@cheimes.de> <4A80967F.9030604@johannes-janssen.de> <4A87DEAA.3020309@johannes-janssen.de> <50697b2c0908160330p43397ac7g86d7e9010cb90d25@mail.gmail.com> Message-ID: <4A87E473.7010606@johannes-janssen.de> Chris Rebert schrieb: > On Sun, Aug 16, 2009 at 6:25 AM, Johannes > Janssen wrote: > >> Gabriel Genellina schrieb: >> >>> The try/except around sys._getframe(1) is because that function is not >>> mandatory/available on all Python implementations (that's the case for >>> jython which doesn't provide it). >>> >> Thanks, shouldn't such information be part of the python documentation of >> sys._getframe() >> (http://docs.python.org/library/sys.html?highlight=sys._getframe#sys._getframe)? >> > > The leading underscore kinda indirectly implies it, but yeah, it's > worth mentioning. > File a bug in the docs: http://bugs.python.org/ > > Cheers, > Chris > I filed a bug: http://bugs.python.org/issue6712 . Johannes From clp2 at rebertia.com Sun Aug 16 06:59:52 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 06:59:52 -0400 Subject: flatten a list of list In-Reply-To: <0297d4a6$0$20634$c3e8da3@news.astraweb.com> References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297d4a6$0$20634$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0908160359u6c8cb593r627651a80017394e@mail.gmail.com> On Sun, Aug 16, 2009 at 6:49 AM, Steven D'Aprano wrote: > On Sun, 16 Aug 2009 05:55:48 -0400, Chris Rebert wrote: >> On Sun, Aug 16, 2009 at 5:47 AM, Terry wrote: >>> Hi, >>> >>> Is there a simple way (the pythonic way) to flatten a list of list? >>> rather than my current solution: >>> >>> new_list=[] >>> for l in list_of_list: >>> ? ?new_list.extend(l) >>> >>> or, >>> >>> new_list=reduce(lambda x,y:x.extend(y), list_of_list) >> >> #only marginally better: >> from operator import add >> new_list = reduce(add, list_of_list) > > Surely that's going to be O(N**2)? The OP asked for "simple", not "best", "most proper", or "fastest". My comment was intended to mean that the code was marginally *simpler*, not faster. Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 07:08:09 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 11:08:09 GMT Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <0297d8e8$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 12:03:53 +0200, Michael F?tsch wrote: > Terry wrote: >> Is there a simple way (the pythonic way) to flatten a list of list? > > This is probably the shortest it can get: > > sum(list_of_lists, []) That's also O(N**2). >>> from timeit import Timer >>> setup = "L = [ ([None]*5000) for x in xrange(%d) ]" >>> Timer("sum(L, [])", setup % 4).repeat(number=1000) [0.6070549488067627, 0.54354715347290039, 0.54686999320983887] >>> Timer("sum(L, [])", setup % 8).repeat(number=1000) [2.1285719871520996, 3.6722278594970703, 4.0785009860992432] >>> Timer("sum(L, [])", setup % 16).repeat(number=1000) [18.370341062545776, 20.40509295463562, 21.871708869934082] -- Steven From hendrik at microcorp.co.za Sun Aug 16 07:15:06 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 16 Aug 2009 13:15:06 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? - conclusions In-Reply-To: <4a87a444$0$1627$742ec2ed@news.sonic.net> References: <4a87a444$0$1627$742ec2ed@news.sonic.net> Message-ID: <200908161315.07229.hendrik@microcorp.co.za> On Sunday 16 August 2009 08:20:34 John Nagle wrote: > Hendrik van Rooyen wrote: > > On Saturday 15 August 2009 14:40:35 Michael Str?der wrote: > >> Hendrik van Rooyen wrote: > >>> In the past, on this group, I have made statements that said that on > >>> Linux, the serial port handling somehow does not allow transmitting and > >>> receiving at the same time, and nobody contradicted me. > > Absolutely false. No its true, if you open the serial port with the standard open() instead of os.open(). And it is also true that I was not contradicted in the past. :-) > > >> Despite all the good comments here by other skilled people I'd recommend > >> to determine whether the transmission line to the devices accessed > >> support full duplex. > > All standard PC serial ports are full-duplex devices. > I know this, and I started the thread because they would not work full duplex for me. 8< -------------------- pyserial baudot program link ----------------------- > > You raise a good point, that is probably not well known amongst the > > youngsters here, as simple serial multidropping has gone out of fashion. > > Actually, no. Dynamixel servos as used on the latest Bioloid robots > are multidrop serial RS-485. But outside the embedded world, nobody uses > that stuff any more. (Embedded is going Ethernet; it's overkill but > works fine and is now cheap.) Exactly - it is no longer part of mainstream fashion. We also still use RS-485 because it is cheaper, and we have better control over timing. I enclose two naive test implementations. To run them you will need a loopback connector. One can be made by shorting pin 2 and 3 together on the standard DB9. The results are illuminating - on my development machine, (dual 64 bit, some gigs), the last lines look like this: test.py: The quick brown fox jumps over the lazy dog 1023 That took 3.91238284111 seconds - 3.82068636827 Millisecs per record, 261.733077152 recs per sec hvr at Linuxbox:~/dos/JOBS/sms/lib> test1.py: The quick brown fox jumps over the lazy dog 1023 That took 3.90402388573 seconds - 3.81252332591 Millisecs per record, 262.293477185 recs per sec hvr at Linuxbox:~/dos/JOBS/sms/lib> Almost no difference between the two implementations. This is basically because there is enough processing power to keep the link running at full speed in both instances. On the eBox, (486, 400MHz, 128Mb, no FP), the difference is startling: test.py: The quick brown fox jumps over the lazy dog 1023 That took 69.2863521576 seconds - 67.6624532789 Millisecs per record, 14.7792453797 recs per sec root at ebox:/home/user/sms/lib# About eighteen times slower than the development machine. test1.py: The quick brown fox jumps over the lazy dog 1023 That took 10.391780138 seconds - 10.148222791 Millisecs per record, 98.5394211964 recs per sec root at ebox:/home/user/sms/lib# Less than three times slower than the development machine. The little processor + Slackware + python cannot keep the link busy. Python, as a character handler, well let us say that it is suboptimal, because saying that something sucks, sucks. An almost seven times ratio between the implementations is not to be sneezed at. So the conclusions I have come to are the following: 1) Thou shalt not use ordinary python files for serial ports, on pain of death. 2) Thou shalt strive mightily to minimize python calls, doing all in thy power to move away from character input to string input. 3) Thou shalt expend real treasure for real processing power as there is no such thing as a free lunch. I would like to thank everybody who took the trouble to respond to teach me the error of my ways. - Hendrik -------------- next part -------------- A non-text attachment was scrubbed... Name: test1.py Type: application/x-python Size: 1900 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: test.py Type: application/x-python Size: 1832 bytes Desc: not available URL: From subhakolkata1234 at gmail.com Sun Aug 16 07:19:06 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Sun, 16 Aug 2009 04:19:06 -0700 (PDT) Subject: Problem Regarding Handling of Unicode string References: <9ac0e194-9e25-468a-9807-957ef3142dd3@i18g2000pro.googlegroups.com> <47b265c5-e71f-4018-815a-0bfbea927a4a@y28g2000prd.googlegroups.com> Message-ID: On Aug 11, 1:17?pm, John Machin wrote: > On Aug 10, 9:26?pm, joy99 wrote: > > > Dear Group, > > > I am using Python26 on WindowsXP with service pack2. My GUI is IDLE. > > I am using Hindi resources and get nice output like: > > ?? > > where I can use all the re functions and other functions without doing > > any transliteration,etc. > > I was trying to use Bengali but it is giving me output like: > > WHAT is giving you this output? > > > '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95' > > In a very ordinary IDLE session (Win XP SP3, Python 2.6.2, locale: > Australia/English, no "Hindi resources"): > > >>> x = '\xef\xbb\xbf\xe0\xa6\x85\xe0\xa6\xa8\xe0\xa7\x87\xe0\xa6\x95' > >>> ux = x.decode('utf-8') > >>> ux > > u'\ufeff\u0985\u09a8\u09c7\u0995'>>> print ux > > ????? # looks like what you wanted; please confirm>>> import unicodedata > >>> for c in ux: > > ? ? ? ? print unicodedata.name(c) > > ZERO WIDTH NO-BREAK SPACE # this is a BOM > BENGALI LETTER A > BENGALI LETTER NA > BENGALI VOWEL SIGN E > BENGALI LETTER KA > > > > > I wanted to see Bengali output as > > ???? > > and I like to use all functions including re. > > If any one can help me on that. > > "I am using Hindi resources" doesn't tell us much ... except to prompt > the comment that perhaps if you want to display Bengali script, you > may need Bengali resources. However it looks like I can display your > Bengali data without any special resources. > > It seems like you are not doing the same with Bengali as you are doing > with Hindi. We can't help you very much if you don't show exactly what > you are doing. > > Have you considered asking in an Indian Python forum? Note: you will > still need to say what you are doing that works with Hindi but not > with Bengali. > > Cheers, > John Dear Group, I have already worked out my solution but everyone of yours' answers helped me to see different solutions from different angles. Thank you for the same. I am building some social network program in Bengali. I just gave the transliteration problem which was giving me problem, I thought as you are very expert pythoners so it would be minutes' matter. By your answers I saw I was not wrong. But as I solved the problem so I checked it bit late. Sorry for the same. Best Regards, Subhabrata. From terry.yinzhe at gmail.com Sun Aug 16 07:22:00 2009 From: terry.yinzhe at gmail.com (Terry) Date: Sun, 16 Aug 2009 04:22:00 -0700 (PDT) Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297d4a6$0$20634$c3e8da3@news.astraweb.com> Message-ID: On Aug 16, 6:59?pm, Chris Rebert wrote: > On Sun, Aug 16, 2009 at 6:49 AM, Steven > > > > > > D'Aprano wrote: > > On Sun, 16 Aug 2009 05:55:48 -0400, Chris Rebert wrote: > >> On Sun, Aug 16, 2009 at 5:47 AM, Terry wrote: > >>> Hi, > > >>> Is there a simple way (the pythonic way) to flatten a list of list? > >>> rather than my current solution: > > >>> new_list=[] > >>> for l in list_of_list: > >>> ? ?new_list.extend(l) > > >>> or, > > >>> new_list=reduce(lambda x,y:x.extend(y), list_of_list) > > >> #only marginally better: > >> from operator import add > >> new_list = reduce(add, list_of_list) > > > Surely that's going to be O(N**2)? > > The OP asked for "simple", not "best", "most proper", or "fastest". My > comment was intended to mean that the code was marginally *simpler*, > not faster. > > Cheers, > Chris > --http://blog.rebertia.com Well, if possible, I'd like not only to know a simple solution, but also the 'best', the 'most proper' and the 'fastest':-) If they are not the same. br, Terry From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 07:25:53 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 11:25:53 GMT Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <0297dd0f$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 02:47:42 -0700, Terry wrote: > Hi, > > Is there a simple way (the pythonic way) to flatten a list of list? > rather than my current solution: > > new_list=[] > for l in list_of_list: > new_list.extend(l) I don't think that scales terribly well. In my testing, it performs about as badly as the O(N**2) behaviours others have suggested (using sum or reduce with add) -- perhaps a bit worse for small N, but not quite as badly for large N. > new_list=reduce(lambda x,y:x.extend(y), list_of_list) That doesn't even work. >>> list_of_list = [ [1,2,3], [2, 4, 8] ] >>> new_list=reduce(lambda x,y:x.extend(y), list_of_list) >>> new_list is None True Chris' suggestion using itertools seems pretty good: >>> from timeit import Timer >>> setup = """\\ ... L = [ [None]*5000 for _ in xrange(%d) ] ... from itertools import chain ... """ >>> Timer("list(chain.from_iterable(L))", setup % 4).repeat(number=1000) [0.61839914321899414, 0.61799716949462891, 0.62065696716308594] >>> Timer("list(chain.from_iterable(L))", setup % 8).repeat(number=1000) [1.2618398666381836, 1.3385050296783447, 3.9113419055938721] >>> Timer("list(chain.from_iterable(L))", setup % 16).repeat(number=1000) [3.1349358558654785, 4.8554730415344238, 5.4319999217987061] -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 16 07:31:57 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 16 Aug 2009 11:31:57 GMT Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297d4a6$0$20634$c3e8da3@news.astraweb.com> Message-ID: <0297de7c$0$20634$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 06:59:52 -0400, Chris Rebert wrote: >> Surely that's going to be O(N**2)? > > The OP asked for "simple", not "best", "most proper", or "fastest". My > comment was intended to mean that the code was marginally *simpler*, not > faster. Fair enough, but he also asked for Pythonic, and while some people might argue that "terrible performance" is Pythonic, I hope you wouldn't be one of them! :) If it soothes your ruffled sense of honour *wink*, I think your solution with itertools.chain is probably the best so far. -- Steven From tjreedy at udel.edu Sun Aug 16 07:39:40 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 16 Aug 2009 20:39:40 +0900 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: <2d56febf0908160245i5fd0d9f2kba74d112f0826932@mail.gmail.com> References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160107k6f31141dt5143071d0ff54c71@mail.gmail.com> <2d56febf0908160245i5fd0d9f2kba74d112f0826932@mail.gmail.com> Message-ID: Xavier Ho wrote: > I'm really looking for a way to set up Python classes' natural ordering > for sorting purposes. I believe __lt__ (<) is the only method (operator) used by both .sort and heap module. From hendrik at microcorp.co.za Sun Aug 16 07:42:14 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 16 Aug 2009 13:42:14 +0200 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <0297cd31$0$20634$c3e8da3@news.astraweb.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> <0297cd31$0$20634$c3e8da3@news.astraweb.com> Message-ID: <200908161342.14612.hendrik@microcorp.co.za> On Sunday 16 August 2009 12:18:11 Steven D'Aprano wrote: > In any case, after half a century of left-from-right assignment, I think > it's worth the experiment in a teaching language or three to try it the > other way. The closest to this I know of is the family of languages > derived from Apple's Hypertalk, where you do assignment with: > > put somevalue into name > > (Doesn't COBOL do something similar?) Yup. move banana to pineapple. move accountnum in inrec to accountnum in outrec. move corresponding inrec to outrec. It should all be upper case of course... I cannot quite recall, but I have the feeling that in the second form, "of" was also allowed instead of "in", but it has been a while now so I am probably wrong. The move was powerful - it would do conversions for you based on the types of the operands - it all "just worked". - Hendrik From clp2 at rebertia.com Sun Aug 16 07:43:00 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 16 Aug 2009 07:43:00 -0400 Subject: flatten a list of list In-Reply-To: <0297de7c$0$20634$c3e8da3@news.astraweb.com> References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297d4a6$0$20634$c3e8da3@news.astraweb.com> <0297de7c$0$20634$c3e8da3@news.astraweb.com> Message-ID: <50697b2c0908160443j1608f14dsb9ec1b7f39bd6410@mail.gmail.com> On Sun, Aug 16, 2009 at 7:31 AM, Steven D'Aprano wrote: > On Sun, 16 Aug 2009 06:59:52 -0400, Chris Rebert wrote: >>> Surely that's going to be O(N**2)? >> >> The OP asked for "simple", not "best", "most proper", or "fastest". My >> comment was intended to mean that the code was marginally *simpler*, not >> faster. > > Fair enough, but he also asked for Pythonic, and while some people might > argue that "terrible performance" is Pythonic, I hope you wouldn't be one > of them! :) Indeed not. :) I expected it would be worse performance-wise than the OP's original due to all the intermediate lists that get produced; it shouldn't be used in optimized production code. > If it soothes your ruffled sense of honour *wink*, I think your solution > with itertools.chain is probably the best so far. Except it's not really my solution, it's whoever put it in the itertools docs's. :( But I'm glad to been able to help by pointing the recipe out. :-) Cheers, Chris -- http://blog.rebertia.com From breamoreboy at yahoo.co.uk Sun Aug 16 07:49:16 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 16 Aug 2009 12:49:16 +0100 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: <50697b2c0908160104k7d74ace9jda8f4b927402942@mail.gmail.com> References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160104k7d74ace9jda8f4b927402942@mail.gmail.com> Message-ID: Chris Rebert wrote: > On Sat, Aug 15, 2009 at 8:09 AM, Xavier Ho wrote: >> Hey all, >> >> I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in the >> documentation. >> >> Is there a substitution for this special method in 3.1, or do I really have >> to define all six rich comparison methods to work it out? > > I don't think so. Quoting > http://docs.python.org/dev/py3k/reference/datamodel.html > > "There are no swapped-argument versions of [the comparison] methods > (to be used when the left argument does not support the operation but > the right argument does); rather, __lt__() and __gt__() are each > other?s reflection, __le__() and __ge__() are each other?s reflection, > and __eq__() and __ne__() are their own reflection." > > I believe this means you only need to define one method from each of > the following pairs to get all the operators working: > * __eq__ or __ne__ > * __lt__ or __gt__ > * __ge__ or __le__ > > Cheers, > Chris Unfortunately I don't think it's that easy, see. http://mail.python.org/pipermail/python-list/2008-November/688761.html The issue referenced is still open. This of course assumes that I've posted the correct link this time! -- Kindest regards. Mark Lawrence. From contact at xavierho.com Sun Aug 16 07:58:35 2009 From: contact at xavierho.com (Xavier Ho) Date: Sun, 16 Aug 2009 21:58:35 +1000 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160104k7d74ace9jda8f4b927402942@mail.gmail.com> Message-ID: <2d56febf0908160458k3b5197d8tf1a69e3083ab3146@mail.gmail.com> On Sun, Aug 16, 2009 at 9:49 PM, Mark Lawrence wrote: > > Unfortunately I don't think it's that easy, see. > http://mail.python.org/pipermail/python-list/2008-November/688761.html > The issue referenced is still open. This of course assumes that I've > posted the correct link this time! > I'm not sure what you're referring to here. The link brought me to about __ne__ being automatically determined when __eq__ is defined. Although it is a rich comparison special method, it doesn't entirely cover the usefulness of __cmp__(). Terry: I'll give that a test tomorrow and see what I can come up with. Thanks for the quick info. Regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From luke.leighton at googlemail.com Sun Aug 16 08:08:39 2009 From: luke.leighton at googlemail.com (lkcl) Date: Sun, 16 Aug 2009 05:08:39 -0700 (PDT) Subject: platform-specific overrides of functions and class methods (expanding on imputils demo code) Message-ID: i've just had to put something together for pyjamas-desktop which may prove to be useful to other people, so i'm pointing people in its general direction, for archive purposes. the purpose behind the platform override system is to allow implementations of a common API, in python, to share the majority of their codebase (modules, classes, functions etc.) _but_, for _very_ specific platform implementation purposes, allow for "overrides". example: test.py def test(): print "hello" platform/testOverridingPlatformName.py: def test(): print "this is not kansas any more" code is here: http://pyjamas.svn.sourceforge.net/viewvc/pyjamas/trunk/pyjd/ modules to pay attention to: importers.py (a modified version of Demos/ imputils/importers.py) and modcompile.py. setup/init function is very simple - see __init__py.in last few lines. on reading modcompile.py you may be forgiven for going "wtf????" but basically PlatformParser loads the python source; turns it into an AST; then also the "platform-specific" version is loaded and turned into an AST; then, the two ASTs are handed to the "merge" function which does a top-level "replace" of functions and a top-level "replace" of class methods. _theen_ the resultant "merged" AST is handed to a module which was derived from compiler/pycodegen.py - none of the code in there can cope with being handed an already-compiled AST so it was necessary to make a class that did. looking around on the internet i find quite a few people asking about how to do this, so ... take a look at modcompile.Module, and how it's used. very simple. i've disabled saving and detection of .pyc files for now, because the job of loading code from .pyc should really be done by PlatformParser (which understands the concept of... duh, a platform). the _last_ thing that you want to happen is to run one platform's code, generate some .pyc files, then change a config file to run a different back-end platform, for example (which is possible with pyjamas-desktop) and end up running the _wrong_ platform-specific code. for those people wondering, "why in god's green earth would anyone want to _do_ such a thing???" it's quite simple: the alternative is a complete dog's dinner, in pyjamas: def do_some_DOM_manipulation(document): # heeeere we go... if platform == 'hulahop' # this is for XULrunner do_some_stuff() elif platform == 'pywebkitgtk': do_something_different() elif platform == 'mshtml' # for pywin32 and comtypes.... do_something_dreadful() else: do_the_default_here() now imagine that across an API with ... four hundred functions. i just... couldn't bring myself to do that. not when the pyjs (python- to-javascript) compiler _already_ solved this problem (thanks to james tauber) by deploying the AST merge concept. all i did was merge that with the imputils demo code so that, rather than at compile-time the pyjs compiler goes and generates five platform-specific versions of the same application, pyjamas-desktop at _run_ time can do exactly the same thing. but - it's a generic enough idea to be of value elsewhere - for example, all the loooovely code in e.g. the setup distutils? all those looovely "if os.platform == 'win32'", and "if sys.this = 'posix' " could be replaced with platform-specific overrides that got merged at run-time, thus _dramatically_ simplifying the look and the useability of the code. enjoy. l. From bearophileHUGS at lycos.com Sun Aug 16 08:24:36 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Sun, 16 Aug 2009 05:24:36 -0700 (PDT) Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297d4a6$0$20634$c3e8da3@news.astraweb.com> Message-ID: <218b0a2e-ed83-4675-9942-6297048a4676@c14g2000yqm.googlegroups.com> Chris Rebert: > The OP asked for "simple", not "best", "most proper", or "fastest". My > comment was intended to mean that the code was marginally *simpler*, > not faster. Yep, the OP has asked for simple code. But often this is not the right way to solve this situation. A better way is to create (or copy) a flatten that's efficient and well tested & debugged, put it into some library of utilities, and then use import&use it when it's needed. Bye, bearophile From breamoreboy at yahoo.co.uk Sun Aug 16 08:33:29 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Sun, 16 Aug 2009 13:33:29 +0100 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: <2d56febf0908160458k3b5197d8tf1a69e3083ab3146@mail.gmail.com> References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160104k7d74ace9jda8f4b927402942@mail.gmail.com> <2d56febf0908160458k3b5197d8tf1a69e3083ab3146@mail.gmail.com> Message-ID: Xavier Ho wrote: > On Sun, Aug 16, 2009 at 9:49 PM, Mark Lawrence wrote: > >> Unfortunately I don't think it's that easy, see. >> http://mail.python.org/pipermail/python-list/2008-November/688761.html >> The issue referenced is still open. This of course assumes that I've >> posted the correct link this time! >> > > I'm not sure what you're referring to here. The link brought me to about > __ne__ being automatically determined when __eq__ is defined. Although it is > a rich comparison special method, it doesn't entirely cover the usefulness > of __cmp__(). > > Terry: I'll give that a test tomorrow and see what I can come up with. > Thanks for the quick info. > > Regards, > > Ching-Yun "Xavier" Ho, Technical Artist > > Contact Information > Mobile: (+61) 04 3335 4748 > Skype ID: SpaXe85 > Email: contact at xavierho.com > Website: http://xavierho.com/ > > I wasn't discussing __cmp__, I was referring to the quote by Chris Rebert from the Python docs regarding the rich comparison methods, a discrepancy between the documentation and the implementation as noted in the link that I gave, and an indication that the issue raised on this discrepancy is still open. As Terry Reedy has mentioned __lt__ elsewhere, you should be aware of the discrepancy, otherwise you could go charging off down the wrong track. FWIW it was Terry who raised the issue 4395, I'm sure that he could explain the ramifications of it all far better than I ever could, so I'll sign out. -- Kindest regards. Mark Lawrence. From python at mrabarnett.plus.com Sun Aug 16 08:45:22 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 16 Aug 2009 13:45:22 +0100 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] In-Reply-To: <34dd6e0e-3b47-4761-ad7a-9038b0d36209@v36g2000yqv.googlegroups.com> References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <34dd6e0e-3b47-4761-ad7a-9038b0d36209@v36g2000yqv.googlegroups.com> Message-ID: <4A87FF62.2020508@mrabarnett.plus.com> Douglas Alan wrote: [snip] > C++ also allows for reading from stdin like so: > > cin >> myVar; > > I think the direction of the arrows probably derives from languages > like APL, which had notation something like so: > > myVar <- 3 > [] <- myVar > > "<-" was really a little arrow symbol (APL didn't use ascii), and the > first line above would assign the value 3 to myVar. In the second > line, the "[]" was really a little box symbol and represented the > terminal. Assigning to the box would cause the output to be printed > on the terminal, so the above would output "3". If you did this: > > [] -> myVar > > It would read a value into myVar from the terminal. > > APL predates Unix by quite a few years. > No, APL is strictly right-to-left. -> x means "goto x". Writing to the console is: [] <- myVar Reading from the console is: myVar <- [] From magawake at gmail.com Sun Aug 16 09:25:42 2009 From: magawake at gmail.com (Mag Gam) Date: Sun, 16 Aug 2009 09:25:42 -0400 Subject: unittest In-Reply-To: References: <1cbd6f830908142028v638a4c06jf0f859be712e724c@mail.gmail.com> Message-ID: <1cbd6f830908160625m5a8ffa9er7e34c203f30fca49@mail.gmail.com> John: Well, this is actually a script which wraps around another application. :-) My goal is when I introduce a new feature I don't want to break old stuff so instead of me testing manually I want to build a framework of tests. On Sat, Aug 15, 2009 at 11:37 PM, John Haggerty wrote: > This is an interesting question. I am just wondering: do you really have > that many features that it would be impossible to just have a shell script > run specific types of input or tests? > > When I did programming in the past for education they just had lists of > input data and we ran the program against the test data. > > I just get slightly confused when "test suites" start to have to apply? > > On Fri, Aug 14, 2009 at 9:28 PM, Mag Gam wrote: >> >> I am writing an application which has many command line arguments. >> For example: foo.py -args "bar bee" >> >> I would like to create a test suit using unittest so when I add >> features to "foo.py" I don't want to break other things. I just heard >> about unittest and would love to use it for this type of thing. >> >> so my question is, when I do these tests do I have to code them into >> foo.py? I prefer having a footest.py which will run the regression >> tests. Any thoughts about this? >> >> TIA >> -- >> http://mail.python.org/mailman/listinfo/python-list > > From kevin.p.dwyer at gmail.com Sun Aug 16 09:31:19 2009 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Sun, 16 Aug 2009 13:31:19 +0000 (UTC) Subject: my recursive function call is wrong? References: <22a413260908160057t2802d3cci70658278e7322eb8@mail.gmail.com> Message-ID: On Sun, 16 Aug 2009 16:57:41 +0900, Chang Min Jeon wrote: Hello, You have placed recursive calls to the function in a number of different locations; when len(macro) becomes zero control will return to the calling function, but this calling function may have more code to execute, including further calls to start_parse(), and further attempts to index macro. I like to keep recursive calls at the end of a function, so that there is a clean path back to the top level caller once the terminal condition is reached. You can do it differently, but you need to bear in mind the execution paths through your code. Cheers, Kev From emmanuel.surleau at gmail.com Sun Aug 16 09:34:06 2009 From: emmanuel.surleau at gmail.com (Emmanuel Surleau) Date: Sun, 16 Aug 2009 15:34:06 +0200 Subject: Python 'for' loop is memory inefficient In-Reply-To: <0297b471$0$20634$c3e8da3@news.astraweb.com> References: <24980842.post@talk.nabble.com> <0297b471$0$20634$c3e8da3@news.astraweb.com> Message-ID: <200908161534.06831.emmanuel.surleau@gmail.com> > It's a particular unfair criticism because the critic (Ethan Furman) > appears to have made a knee-jerk reaction. The "some language in Python" > behaviour he's reacting to is the common idiom: > > for i in range(len(seq)): > do_something_with(seq[i]) > > > instead of the "Python in Python" idiom: > > for obj in seq: > do_something_with(obj) > > > That's a reasonable criticism, but *not in the case*. Ethan appears to > have made the knee-jerk reaction "for i in range() is Bad" without > stopping to think about what this specific piece of code is actually > doing. > > (Replace 'obj' with 'j', 'seq' with 'range(2, n)', and > 'do_something_with' with 'if (n % j) == 0: return False', and you have > the exact same code pattern.) Fair enough. But as far as I know, for i in (x)range(num) is the canonical way to iterate over numbers in Python. Another case of lack of RTFM* before answering, I suppose. Cheers, Emm *Read The Fine Mail From grante at visi.com Sun Aug 16 09:55:31 2009 From: grante at visi.com (Grant Edwards) Date: Sun, 16 Aug 2009 08:55:31 -0500 Subject: Is it possible to use python to get True Full Duplex on a Serial port? References: Message-ID: On 2009-08-15, Hendrik van Rooyen wrote: > On Saturday 15 August 2009 16:25:03 Grant Edwards wrote: > >> Are you using python file operations open/read/write or OS >> file-descriptor operations os.open/os.read/os.write? > > The former - that seems to be the source of my trouble. > > I have now written a little test that uses serial.Serial and > it works a treat. Good to hear. > I am still confused about pyserial and serial - I found serial > in my distribution library, (on the SuSe machine, not on the > 2.5 in Slackware) but I had to download pyserial. That's very interesting. Is the pre-existing "serial" a version of pyserial that the packager had pre-installed or is it something else? I didn't know any distributions shipped Python with pyserial installed. In either case, "serial" isn't something that ships with the standard Python library. > I see that you were the the original author. Thank you for > letting this stuff loose in the wild. My pleasure. -- From jeanmichel at sequans.com Sun Aug 16 09:59:18 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Sun, 16 Aug 2009 15:59:18 +0200 Subject: callable virtual method In-Reply-To: References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A8810B6.8080204@sequans.com> Scott David Daniels wrote: > Jean-Michel Pichavant wrote: >> Steven D'Aprano wrote: >>> On Fri, 14 Aug 2009 18:49:26 +0200, Jean-Michel Pichavant wrote: >>> >>> >>>> Sorry guys (means guys *and* gals :op ), I realized I've not been able >>>> to describe precisely what I want to do. I'd like the base class to be >>>> virtual (aka abstract). However it may be abstract but it does not >>>> mean >>>> it cannot do some usefull stuff. >>>> >>>> >>>> Here is the schema of my abstract methods : >>>> >>>> class Interface(object): >>>> def method(self): >>>> # --------------------- >>>> # some common stuff executed here >>>> # --------------------- >>>> print 'hello world' >>>> # --------------------- >>>> # here shall stand child specific stuff (empty in the >>>> interface >>>> method) >>>> # --------------------- >>>> if self.__class__.method == Interface.method: >>>> raise NotImplementedError('You should have read the >>>> f****** >>>> manual ! You must override this method.') >>>> >>> >>> >>> Okay, so I want to sub-class your Interface class. As you said, the >>> methods in the abstract class are still useful, so in my class, I >>> don't need any extra functionality for some methods -- I'm happy >>> with just the "common stuff". So I use normal OO techniques and >>> over-ride just the methods I need to over-ride: >>> >>> >> Sometimes the base is doing cool stuff but incomplete stuff which >> requires knowledge only hold by the sub class. In my case the >> interface is a high level interface for a software that can run on >> multiple hardware platforms. Only the sub class has knowledge on how >> to operate the hardware, but no matter the hardware it still produces >> the same effect. >> >> Let's say I have 50 different hardwares, I'll have 50 sub classes of >> Interface with the 'start' method to define. It wouldn't be >> appropriate (OO programming)to write 50 times '_log.debug('Starting >> %s' % self)' in each child start method when the simple task of >> logging the call can be nicely handled by the base class. >> >> In the meantime, I must make sure the user, who is not a python guru >> in this case, has implemented the start method for his hardware, >> because only him knows how to effectively start this hardware. I >> don't want him to come to me saying, "I got no error, still my >> hardware does not start". You can then blame him for not reading the >> docs, but it will still be less expensive to throw a nice exception >> with an accurate feedback. >> >> [snip] >>> class VerboseGoodChild(Interface): >>> # forced to over-ride methods for no good reason >>> >> >> Definitely no !! This is the purpose of an interface class: to force >> people to write these methods. They *are* required, if they were not, >> they would not belong to the Interface. >> >> JM > > But there _is_ one moment when you can check those things, then avoid > checking thereafter: object creation. So you can complicate your > __init__ (or __new__) with those checks that make sure you instantiate > only fully defined subclasses: > > # obviously not tested except in concept: > > class Base(object_or_whatever): > def __init__(self, ...): > class_ = self.__class__ > if class_ is Base: > raise TypeError('Attempt to instantiate Base class') > for name in 'one two three four': > if getattr(Base, name) is not getattr(Base, name): > raise NotImplementedError( > '%s implementation missing' % name) > ... > > --Scott David Daniels > Scott.Daniels at Acm.Org That could do the trick, sparing me from writing additional code in each methods. Thanks. JM From lists at cheimes.de Sun Aug 16 10:07:13 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 16 Aug 2009 16:07:13 +0200 Subject: callable virtual method In-Reply-To: <4A8810B6.8080204@sequans.com> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> <4A8810B6.8080204@sequans.com> Message-ID: <4A881291.6030805@cheimes.de> Jean-Michel Pichavant wrote: >> Scott.Daniels at Acm.Org > That could do the trick, sparing me from writing additional code in each > methods. Thanks. Why are you trying to reinvent the wheel? Python's abc module already takes care of these details. Christian From jeanmichel at sequans.com Sun Aug 16 10:13:46 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Sun, 16 Aug 2009 16:13:46 +0200 Subject: callable virtual method In-Reply-To: References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <7eljaoF2fnkqgU1@mid.uni-berlin.de> <4A85A233.9030905@sequans.com> <4A85A47E.308@wiggly.org> <4A85ACEF.4090901@sequans.com> <4A85B9F7.4010201@ieee.org> <4A85D051.2080004@sequans.com> Message-ID: <4A88141A.1030201@sequans.com> Christian Heimes wrote: > Jean-Michel Pichavant wrote: >> talking about approaches: >> >> 1/ >> class Interface: >> def foo(self): >> if self.__class__.foo == Interface.foo: >> raise NotImplementedError >> >> 2/ >> class Interface: >> def foo(self): >> self._foo() >> >> def _foo(sef): >> raise NotImplementedError > > Please don't call it an interface when it's really an abstract base > class. And abstract base classes are probably the solution the OP is > looking for, http://docs.python.org/library/abc.html > > Christian > Sadly I'm working with python 2.4. Anyway it's good to hear they've added ABC support to python, didn't know that. I didn't know there was a difference between interface and abstract classes as well. With a little bit of googling, I found out that actually Interface classes do not provide any implementation. What I'm looking for is definitely an abstract class. JM From jeanmichel at sequans.com Sun Aug 16 10:17:39 2009 From: jeanmichel at sequans.com (jean-michel Pichavant) Date: Sun, 16 Aug 2009 16:17:39 +0200 Subject: callable virtual method In-Reply-To: <4A881291.6030805@cheimes.de> References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> <4A8810B6.8080204@sequans.com> <4A881291.6030805@cheimes.de> Message-ID: <4A881503.7010202@sequans.com> Christian Heimes a ?crit : > Jean-Michel Pichavant wrote: >>> Scott.Daniels at Acm.Org >> That could do the trick, sparing me from writing additional code in >> each methods. Thanks. > > Why are you trying to reinvent the wheel? Python's abc module already > takes care of these details. > > Christian I'm working with python 2.4 and don't plan to change. The abc module would have been exactly what I was looking for. I'll keep it mind if I ever upgrade to python 2.6+ JM From victorsubervi at gmail.com Sun Aug 16 11:30:34 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 16 Aug 2009 10:30:34 -0500 Subject: Surpressing Warnings In-Reply-To: References: <4dc0cfea0908091321y54156d30sc0c4dc3a564eecab@mail.gmail.com> Message-ID: <4dc0cfea0908160830n33c4e511t7aa1662884596885@mail.gmail.com> This is strange because I actually had "if exists" in my code: sqlKWDrop = 'DROP TABLE IF EXISTS ' + kwTable + ';' where kwTable, in the instance cited below, becomes "judaism_128". What gives? Victor On Sun, Aug 9, 2009 at 7:57 PM, Dennis Lee Bieber wrote: > On Sun, 9 Aug 2009 15:21:43 -0500, Victor Subervi > declaimed the following in > gmane.comp.python.general: > > > Hi: > > I get a ton of warnings like this from a program I run: > > > > Warning (from warnings module): > > File "C:\Python25\read.py", line 67 > > cursor.execute(sqlKWDrop) > > Warning: Unknown table 'judaism_128' > > > Personally -- I'd suggest fixing the database so that the table > does > exist... > > Ah, but then -- it appears from the name, that the purpose of this > SQL statement is to delete the table... In which case use a database > that supports (for example, current versions of MySQL, SQLite, and > PostgreSQL) "drop table IF EXISTS tbl_name" which suppress the > warning/error message and update the SQL as appropriate. > > Appears that M$ SQL Server does NOT implement that syntax... Nor > could I find it for Firebird. > > If the application is specific for one database engine, it might be > worth it to find out what features permit discovering if a table exists > and bypassing the drop if it doesn't... > > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Sun Aug 16 11:41:21 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 16 Aug 2009 11:41:21 -0400 Subject: Python 'for' loop is memory inefficient In-Reply-To: <200908160830.55031.emmanuel.surleau@gmail.com> References: <24980842.post@talk.nabble.com> <4A8612CE.7080700@stoneleaf.us> <200908160830.55031.emmanuel.surleau@gmail.com> Message-ID: On Sun, Aug 16, 2009 at 2:30 AM, Emmanuel Surleau wrote: > > I don't see what's particularly un-Pythonic with this code. Not using xrange() > is a mistake, certainly, but it remains clear, easily understandable code > which correctly demonstrates the naive algorithm for detecting whether n is a > prime. It doesn't call for condescension It's not that the code is bad, but too many people coming from Java and C keep thinking of for loops like they're using Java or C and therefore that "for i in range(a,b)" is identical to "for(int i = a; i < b; i++)". It's not and, for the most part, you shouldn't code like that. Since you're using numbers, range/xrange is the appropriate idiom but you still have to remember that a for loop in python doesn't loop until a condition is met, it loops through an iterator until the interator says it's done. From psilord at merlin.cs.wisc.edu Sun Aug 16 12:05:01 2009 From: psilord at merlin.cs.wisc.edu (Peter Keller) Date: 16 Aug 2009 16:05:01 GMT Subject: Xah's Edu Corner: The importance of syntax & notations. References: Message-ID: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> In comp.lang.scheme Xah Lee wrote: > Xah's Edu Corner: The importance of syntax & notations. > > http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstract.html > > this article should teach the coding sophomorons and computer > ?science? idiotic authors who harbor the notion that syntax is not > important, picked up by all the elite i-reddit & twittering & hacker > news am-hip dunces. I must have really tweaked you with my "Syntax is not important, ideas are." statement. I read Wolfram's article carefully. He applies an intuitive sense onto why he does or doesn't like a particular notation, but yet can't really elucidate his feelings. I'm surprised that didn't tweak you worse. He also goes so far as to mention that: "But actually we still don't know a clean simple way to represent things like geometrical diagrams in a kind of language-like notation. And my guess is that actually of all the math-like stuff out there, only a comparatively small fraction can actually be represented well with language-like notation." It is simply that the method by which the right brain categorizes and processes visual information is not observable by the left brain. Therefore no language can EVER be constructed by the left brain to represent why the right brain "prefers" some visual layouts for languages over others. I've done enough classical art training in my life to understand the conflict between the powerful spatial/visual processor the right brain has and the (in the context of drawing) meaningless linguistics of trying to describe the process. Only when we as human beings build the observation channels needed (with physical connection between certain areas of the left and right sides of the brain) will any sort of meaningful left brain language be created for the visual understanding/gradation of the spatial relationship and the method by which our right brain performs its processing. If you want to design a better computer language, hire an artist. Most semantic objects in programs stand in some spatio-temporal relation to each other. If you deny that fact, then simply look at the directed acyclic form/SSA form/CPS transform of any of your favorite languages. Compiler go through *great* pains to transform left brain scribblings into large spatio-temporal "2d images" where lots of algorithms are done before converting them into assembly. This is because it is simply easier to visually understand how to do the processing of those elements than not. Thank you. -pete From jcm1981 at gmail.com Sun Aug 16 12:17:42 2009 From: jcm1981 at gmail.com (Chang Min Jeon) Date: Mon, 17 Aug 2009 01:17:42 +0900 Subject: my recursive function call is wrong? In-Reply-To: References: <22a413260908160057t2802d3cci70658278e7322eb8@mail.gmail.com> Message-ID: <22a413260908160917j46b93717hd57889ce26feae6d@mail.gmail.com> Dear Kev Thank you very much. I got it.:) 2009/8/16 Kev Dwyer > On Sun, 16 Aug 2009 16:57:41 +0900, Chang Min Jeon wrote: > > > Hello, > > You have placed recursive calls to the function in a number of different > locations; when len(macro) becomes zero control will return to the > calling function, but this calling function may have more code to > execute, including further calls to start_parse(), and further attempts > to index macro. > > I like to keep recursive calls at the end of a function, so that there is > a clean path back to the top level caller once the terminal condition is > reached. You can do it differently, but you need to bear in mind the > execution paths through your code. > > Cheers, > > Kev > > -- > http://mail.python.org/mailman/listinfo/python-list > -- CashFlow To be rich. -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at subsignal.org Sun Aug 16 12:30:48 2009 From: paul at subsignal.org (paul) Date: Sun, 16 Aug 2009 18:30:48 +0200 Subject: Python or ActionScript 3.0 In-Reply-To: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> References: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> Message-ID: Jaseem schrieb: > Hi, > > Is python similar to actionscript 3.0 Not really. > Which is better to create a rich gui internet application? > Is it AS 3.0 with flex or python with its GUI libs? Flex+AS3 definitely! (it's been designed for that, no surprise here) > > Is python in demand? Depends. It seems quite popular in the scientific community and for system administration these days. > Heard that python is similar to lisp. But both python and AS 3.0 is > almost identical. Which is more similar to lisp are powerful? If python is 100m away from lisp, than it's 102.32m for AS3. cheers Paul > > Thank You. From python at rcn.com Sun Aug 16 12:33:59 2009 From: python at rcn.com (Raymond Hettinger) Date: Sun, 16 Aug 2009 09:33:59 -0700 (PDT) Subject: What happened to __cmp__() in Python 3.x? References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> Message-ID: <561aa2a7-2cf8-4c30-b9a7-e22ad64655b5@g31g2000yqc.googlegroups.com> [Xavier Ho] > > I've recently made my way to Python 3.1 and I'm not seeing __cmp__() in the > > documentation. > > > Is there a substitution for this special method in 3.1, or do I really have > > to define all six rich comparison methods to work it out? FWIW, there is a recipe for expanding the comparison operators: http://code.activestate.com/recipes/576685/ Raymond From jasevv at gmail.com Sun Aug 16 12:39:49 2009 From: jasevv at gmail.com (Jaseem) Date: Sun, 16 Aug 2009 09:39:49 -0700 (PDT) Subject: Python or ActionScript 3.0 References: <0e14ae96-e9f5-41ff-8c2d-72c4ef624345@18g2000yqa.googlegroups.com> Message-ID: <4a889173-f1bf-4661-ae1d-4b0c23c4d586@r18g2000yqd.googlegroups.com> On Aug 16, 9:30?pm, paul wrote: > Jaseem schrieb:> Hi, > > > Is python similar to actionscript 3.0 > > Not really. > > > Which is better to create a rich gui internet application? > > Is it AS 3.0 with flex or python with its GUI libs? > > Flex+AS3 definitely! (it's been designed for that, no surprise here) > > > > > Is python in demand? > > Depends. It seems quite popular in the scientific community and for > system administration these days. > > > Heard that python is similar to lisp. But both python and AS 3.0 is > > almost identical. Which is more similar to lisp are powerful? > > If python is 100m away from lisp, than it's 102.32m for AS3. > > cheers > ? Paul > > > > > Thank You. > > Alright! From Scott.Daniels at Acm.Org Sun Aug 16 12:40:57 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 16 Aug 2009 09:40:57 -0700 Subject: flatten a list of list In-Reply-To: <0297dd0f$0$20634$c3e8da3@news.astraweb.com> References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297dd0f$0$20634$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sun, 16 Aug 2009 02:47:42 -0700, Terry wrote: >> Is there a simple way (the pythonic way) to flatten a list of list? > Chris' suggestion using itertools seems pretty good: > >>>> from timeit import Timer >>>> setup = """\\ > ... L = [ [None]*5000 for _ in xrange(%d) ] > ... from itertools import chain > ... """ >>>> Timer("list(chain.from_iterable(L))", setup % 4).repeat(number=1000) > [0.61839914321899414, 0.61799716949462891, 0.62065696716308594] >>>> Timer("list(chain.from_iterable(L))", setup % 8).repeat(number=1000) > [1.2618398666381836, 1.3385050296783447, 3.9113419055938721] >>>> Timer("list(chain.from_iterable(L))", setup % 16).repeat(number=1000) > [3.1349358558654785, 4.8554730415344238, 5.4319999217987061] OK, it definitely helps to get a size estimate before building: >>> setup = """\\ L = [ [None]*5000 for _ in xrange(%d) ] import itertools class Holder(object): def __init__(self, list_of_lists): self._list = list_of_lists def __iter__(self): return itertools.chain.from_iterable(self._list) def __len__(self): return sum(len(x) for x in self._list) """ >>> timeit.Timer("list(Holder(L))", setup % 4).repeat(number=1000) [0.59912279353940789, 0.59505886921382967, 0.59474989139681611] >>> timeit.Timer("list(Holder(L))", setup % 8).repeat(number=1000) [1.1898235669617208, 1.194797383466323, 1.1945367358141823] >>> timeit.Timer("list(Holder(L))", setup % 16).repeat(number=1000) [2.4244464031043123, 2.4261885239604482, 2.4050011942858589] vs straight chain.from_iterable (on my machine): [0.7828263089303249, 0.79326171343005925, 0.80967664884783019] [1.499510971366476, 1.5263249938190455, 1.5599706107899181] [3.4427520816193109, 3.632409426337702, 3.5290488036887382] --Scott David Daniels Scott.Daniels at Acm.Org From no.email at please.post Sun Aug 16 13:09:32 2009 From: no.email at please.post (kj) Date: Sun, 16 Aug 2009 17:09:32 +0000 (UTC) Subject: Splitting on '^' ? References: Message-ID: In rurpy at yahoo.com writes: >On Aug 14, 2:23=A0pm, kj wrote: >> Sometimes I want to split a string into lines, preserving the >> end-of-line markers. =A0In Perl this is really easy to do, by splitting >> on the beginning-of-line anchor: >> >> =A0 @lines =3D split /^/, $string; >> >> But I can't figure out how to do the same thing with Python. =A0E.g.: >Why not this? >>>> lines =3D 'spam\nham\neggs\n'.splitlines (True) >>>> lines >['spam\n', 'ham\n', 'eggs\n'] That's perfect. And .splitlines seems to be able to handle all "standard" end-of-line markers without any special direction (which, ironically, strikes me as a *little* Perlish, somehow): >>> "spam\015\012ham\015eggs\012".splitlines(True) ['spam\r\n', 'ham\r', 'eggs\n'] Amazing. I'm not sure this is the *best* way to do this in general (I would have preferred it, and IMHO it would have been more Pythonic, if .splitlines accepted an additional optional argument where one could specify the end-of-line sequence to be used for the splitting, defaulting to the OS's conventional sequence, and then it split *strictly* on that sequence). But for now this .splitlines will do nicely. Thanks! kynn From bettini at dsi.unifi.it Sun Aug 16 13:12:11 2009 From: bettini at dsi.unifi.it (Lorenzo Bettini) Date: Sun, 16 Aug 2009 19:12:11 +0200 Subject: Komodo(!) In-Reply-To: References: <-7ydndQXQODmNxjXRVn_vwA@giganews.com> <553649.43098.qm@web110605.mail.gq1.yahoo.com> Message-ID: <4a883df4@news.x-privat.org> Kee Nethery wrote: > I've heard there is a nice add-on to Eclipse but Eclipse has even more > setup variables than Wings and I've avoided it for that reason. > Hi I've just started using python and since I've been an eclipse user for many years I tried http://pydev.sourceforge.net/ and I really enjoyed that! :-) cheers Lorenzo -- Lorenzo Bettini, PhD in Computer Science, DI, Univ. Torino ICQ# lbetto, 16080134 (GNU/Linux User # 158233) HOME: http://www.lorenzobettini.it MUSIC: http://www.purplesucker.com http://www.myspace.com/supertrouperabba BLOGS: http://tronprog.blogspot.com http://longlivemusic.blogspot.com http://www.gnu.org/software/src-highlite http://www.gnu.org/software/gengetopt http://www.gnu.org/software/gengen http://doublecpp.sourceforge.net From bieffe62 at gmail.com Sun Aug 16 13:12:29 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Sun, 16 Aug 2009 10:12:29 -0700 (PDT) Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> <0297dd0f$0$20634$c3e8da3@news.astraweb.com> Message-ID: <65abe4e8-dd82-47f9-b851-028babbcc247@c29g2000yqd.googlegroups.com> On Aug 16, 1:25?pm, Steven D'Aprano wrote: ... > Chris' suggestion using itertools seems pretty good: > > >>> from timeit import Timer > >>> setup = """\\ > > ... L = [ [None]*5000 for _ in xrange(%d) ] > ... from itertools import chain > ... """>>> Timer("list(chain.from_iterable(L))", setup % 4).repeat(number=1000) > > [0.61839914321899414, 0.61799716949462891, 0.62065696716308594]>>> Timer("list(chain.from_iterable(L))", setup % 8).repeat(number=1000) > > [1.2618398666381836, 1.3385050296783447, 3.9113419055938721]>>> Timer("list(chain.from_iterable(L))", setup % 16).repeat(number=1000) > > [3.1349358558654785, 4.8554730415344238, 5.4319999217987061] > > -- > Steven I had a peek at itertools ( which is a C module btw) and realized that chain solves the problem by creating a chain object, which is a sort of generator. Both creating the chain object and converting the chain object to a list seem to be O(N), so the whole is O(N) too ... Then I tried this pure python version: # ----- CODE from timeit import Timer setup = """\\ L = [ [None]*5000 for _ in range(%d) ] def pychain( list_of_list ): for l in list_of_list: for elem in l: yield elem """ print( Timer("list(pychain(L))", setup % 4).repeat(number=1000)) print( Timer("list(pychain(L))", setup % 8).repeat(number=1000)) print( Timer("list(pychain(L))", setup % 16).repeat(number=1000)) # ----- END CODE and got times that seem to confirm it : [2.818755865097046, 2.7880589962005615, 2.79232120513916] [5.588631868362427, 5.588244915008545, 5.587780952453613] [11.620548009872437, 11.39465618133545, 11.40834903717041] For reference, here are the times of the itertools.chain solution on my laptop: [0.6518809795379639, 0.6491332054138184, 0.6483590602874756] [1.3188841342926025, 1.3173959255218506, 1.3207998275756836] [2.7200729846954346, 2.5402050018310547, 2.543621063232422] All this with Python 3.1 compiled from source on Xubuntu 8.10. Ciao ----- FB From martin at v.loewis.de Sun Aug 16 13:22:52 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 16 Aug 2009 19:22:52 +0200 Subject: Python 2.6 still not giving memory back to the OS... In-Reply-To: <762603ba-0a4c-4504-94d9-34a8b1e3f9c3@s15g2000yqs.googlegroups.com> References: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> <762603ba-0a4c-4504-94d9-34a8b1e3f9c3@s15g2000yqs.googlegroups.com> Message-ID: <4A88406C.3060609@v.loewis.de> > As far as releasing memory back to the OS is concerned, I have dim > memories of *x systems where free() would return space to the OS if > the block was "large" and it was next to the "break" point ... this > effect could be what you are seeing. Today, there are two cases when malloc returns memory on a typical Unix system (in particular, in Linux malloc): a) if the malloc block block is small (below page size), it is allocated from the brk heap, where it can only be returned if the last page of that heap is completely free, and b) if the block is large (multiple pages), it gets returned to the system right away. Case b) can only happen if the C malloc uses mmap to allocate large blocks. For Python, case b) is realistic, in the sense that most allocations go to Python's obmalloc, and those allocate from C malloc in chunks of 256kiB (IIRC). So when such an arena is completely free (not a single Python object allocated on it anymore), it can get returned to the system. In some case, Python also allocates smaller blocks from C malloc; in this case, a) will trigger. So as long as something at the end of the heap stays allocated, C malloc will not return anything from the brk heap to the system. Regards, Martin From alan.isaac at gmail.com Sun Aug 16 13:37:04 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Sun, 16 Aug 2009 17:37:04 GMT Subject: flatten a list of list In-Reply-To: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <4A8843BF.1060203@gmail.com> On 8/16/2009 5:47 AM Terry apparently wrote: > Is there a simple way (the pythonic way) to flatten a list of list? > rather than my current solution: > new_list=[] > for l in list_of_list: > new_list.extend(l) new_list = list(xi for lst in list_of_list for xi in lst) hth, Alan Isaac From http Sun Aug 16 13:40:41 2009 From: http (Paul Rubin) Date: 16 Aug 2009 10:40:41 -0700 Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: <7xocqfzmg6.fsf@ruckus.brouhaha.com> Terry writes: > Is there a simple way (the pythonic way) to flatten a list of list? > rather than my current solution: > > new_list=[] > for l in list_of_list: > new_list.extend(l) from itertools import chain new_list = list(chain(list_of_list)) From darkwater42 at gmail.com Sun Aug 16 13:46:37 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sun, 16 Aug 2009 10:46:37 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <34dd6e0e-3b47-4761-ad7a-9038b0d36209@v36g2000yqv.googlegroups.com> Message-ID: On Aug 16, 8:45?am, MRAB wrote: > No, APL is strictly right-to-left. > > ? ? ?-> x > > means "goto x". > > Writing to the console is: > > ? ? ?[] <- myVar > > Reading from the console is: > > ? ? ?myVar <- [] Ah, thanks for the correction. It's been 5,000 years since I used APL! |>ouglas From w_a_x_man at yahoo.com Sun Aug 16 14:03:18 2009 From: w_a_x_man at yahoo.com (w_a_x_man) Date: Sun, 16 Aug 2009 11:03:18 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> Message-ID: <5031edcc-c63e-4a3b-9f12-caba0cc34e92@r18g2000yqd.googlegroups.com> On Aug 16, 11:05?am, Petey Keller wrote: > Compiler go through *great* pains Compiler work real hard. Compiler have heap big trouble. From sajmikins at gmail.com Sun Aug 16 14:33:30 2009 From: sajmikins at gmail.com (Simon Forman) Date: Sun, 16 Aug 2009 14:33:30 -0400 Subject: problem with interface of operator.itemgetter In-Reply-To: <19b355330908132016y49f2679u631c3123fcfc920a@mail.gmail.com> References: <19b355330908132016y49f2679u631c3123fcfc920a@mail.gmail.com> Message-ID: <50f98a4c0908161133hd7587chf7368ab0014dabb2@mail.gmail.com> On Thu, Aug 13, 2009 at 11:16 PM, dou dou wrote: > I have a function to do some thing like LEFT JOIN in SQL, the function use > the itemgetter to get the "ON" and "SELECT" parameters of the two table(list > of list), the problem is that itemgetter may return a value or a tuple of > values, because of the inconsistent return type of itemgetter, I have to do > 2^3 IF check, > the function like this: > > def left_join(table1, on_index1, table2, on_index2, getter1, getter2): > ??? """do thing like: > ??? SELECT on1(table1), g1(table1), g2(table2) FROM table1 > ??? LEFT JOIN table2 > ??? ON on1(table1) == on2(table2) > ??? """ > ??? on1 = itemgetter(*on_index1) > ??? on2 = itemgetter(*on_index2) > ??? g1 = itemgetter(*getter1) > ??? g2 = itemgetter(*getter2) > > ??? d2 = {} > ??? d2 = dict((on2(r2), r2) for r2 in table2) > > ??? #if itemgetter always return tuple, below could simple as one line > ??? #return [ list(on1(r1) + g1(r1) + g2(d2.get(on1(r1)))) for r1 in table1 > ] > > ??? len_on = len(on_index1) > ??? len_g1 = len(getter1) > ??? len_g2 = len(getter2) > > ??? if len_on == 1: > ??????? if len_g1 == 1 and len_g2 == 1: > ??????????? return [ [on1(r1), g1(r1), g2(d2.get(on1(r1)))] for r1 in table1 > ] > ??????? elif len_g1 == 1 and len_g2 > 1: > ??????????? return [ list((on1(r1),g1(r1))+g2(d2.get(on1(r1)))) for r1 in > table1 ] > ??????? elif len_g1 > 1 and len_g2 == 1: > ??????????? return [ list((on1(r1),)+g1(r1)+(g2(d2.get(on1(r1))),))? for r1 > in table1 ] > ??????? else: #len_g1 > 1 and len_g2 > 1: > ??????????? return [ list((on1(r1),)+g1(r1)+g2(d2.get(on1(r1)))) for r1 in > table1 ] > ??? else: # len_on > 1 > ??????? if len_g1 == 1 and len_g2 == 1: > ??????????? return [ list(on1(r1))+[g1(r1),g2(d2.get(on1(r1)))] for r1 in > table1 ] > ??????? elif len_g1 == 1 and len_g2 > 1: > ??????????? return [ list(on1(r1)+(g1(r1),)+g2(d2.get(on1(r1)))) for r1 in > table1 ] > ??????? elif len_g1 > 1 and len_g2 == 1: > ??????????? return [ list(on1(r1)+g1(r1)+(g2(d2.get(on1(r1))),))? for r1 in > table1 ] > ??????? else: #len_g1 > 1 and len_g2 > 1: > ??????????? return [ list(on1(r1)+g1(r1)+g2(d2.get(on1(r1)))) for r1 in > table1 ] > > so is there a way to force itemgetter to return tuple even when > itemgetter(only_have_one_argument)? or some other function to do this? > > Thanks. > You can use a little helper function to create your itemgetter like this: def makeItemGetter(indexes): I = itemgetter(*indexes) if len(indexes) > 1: return I return lambda thing: (I(thing),) If indexes contains only one index the itemgetter is wrapped in a lambda that turns its output into a tuple. HTH, ~Simon From gallium.arsenide at gmail.com Sun Aug 16 14:35:52 2009 From: gallium.arsenide at gmail.com (John Yeung) Date: Sun, 16 Aug 2009 11:35:52 -0700 (PDT) Subject: Splitting on '^' ? References: Message-ID: <96ac83a3-adaf-4d22-ad9c-048a99b46927@o13g2000vbl.googlegroups.com> On Aug 16, 1:09?pm, kj wrote: > And .splitlines seems to be able to handle all > "standard" end-of-line markers without any special > direction (which, ironically, strikes > me as a *little* Perlish, somehow): It's Pythonic. Universal newline-handling for text has been a staple of Python for as long as I can remember (very possibly since the very beginning). > >>> "spam\015\012ham\015eggs\012".splitlines(True) > > ['spam\r\n', 'ham\r', 'eggs\n'] > > Amazing. ?I'm not sure this is the *best* way to do > this in general (I would have preferred it, and IMHO > it would have been more Pythonic, if .splitlines > accepted an additional optional argument [...]). I believe it's the best way. When you can use a string method instead of a regex, it's definitely most Pythonic to use the string method. I would argue that this particular string method is Pythonic in design. Remember, Python strives not only for explicitness, but simplicity and ease of use. When dealing with text, universal newlines are much more often than not simpler and easier for the programmer. John From bartc at freeuk.com Sun Aug 16 14:45:27 2009 From: bartc at freeuk.com (bartc) Date: Sun, 16 Aug 2009 18:45:27 GMT Subject: Python 'for' loop is memory inefficient In-Reply-To: <02969972$0$20647$c3e8da3@news.astraweb.com> References: <02969972$0$20647$c3e8da3@news.astraweb.com> Message-ID: "Steven D'Aprano" wrote in message news:02969972$0$20647$c3e8da3 at news.astraweb.com... > On Fri, 14 Aug 2009 18:25:45 -0700, Dr. Phillip M. Feldman wrote: > >> It seems as though Python is actually expanding range(2,n) into a list >> of numbers, even though this is incredibly wasteful of memory. There >> should be a looping mechanism that generates the index variable values >> incrementally as they are needed. > > > Others have already pointed out to you that xrange() (for Python 2.x) > does what you want. In Python 3.x, the old range() is gone for good, and > xrange() renamed to just range(). It does seem rather worrying that whoever originally thought up Python decided it would be a good idea to implement a simple 1 to N (or 0 to N-1) for-loop by first creating an array of N consecutive integers! They must have known Python was going to be slow anyway, but this wouldn't have helped the speed any. Nor the memory consumption. A for-loop, for iterating over a simple sequence, should be one of the fastest things in the language. [Presumably the internal code that created those consecutive integers used a more conventional looping method...] -- Bartc From apt.shansen at gmail.com Sun Aug 16 14:50:09 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 16 Aug 2009 11:50:09 -0700 Subject: Splitting on '^' ? In-Reply-To: References: Message-ID: <7a9c25c20908161150ma1267b9xecc86a222312c0af@mail.gmail.com> And .splitlines seems to be able to handle all "standard" end-of-line > markers without any special direction (which, ironically, strikes > me as a *little* Perlish, somehow): > > >>> "spam\015\012ham\015eggs\012".splitlines(True) > ['spam\r\n', 'ham\r', 'eggs\n'] > ... actually "working correctly" and robustly is "perlish"? :) The only reason I've ever actually used this method is this very feature of it, that you can't readily reproduce with other methods unless you start getting into regular expressions (and I really believe regular expressions should not be the default place one looks to solve a problem in Python) Then again, as soon as Python started allowing you to open files with mode "rU", I gleefully ran through my codebase and changed every operation to that and made sure to write out with platform-local newlines exclusively, thus finally flipping off those darn files that users kept producing with mixed line endings. > Amazing. I'm not sure this is the *best* way to do this in general > (I would have preferred it, and IMHO it would have been more > Pythonic, if .splitlines accepted an additional optional argument > where one could specify the end-of-line sequence to be used for > the splitting, defaulting to the OS's conventional sequence, and > then it split *strictly* on that sequence). > If you want strict and absolute splitting, you don't need another method; just do mystring.split(os.linesep); I mean sure, it doesn't have the 'keepends' feature -- but I don't actually understand why you want keepends with a strict definition of endings... If you /only/ want to split on \n, you know there's an \n on the end of each line in the returned list and can easily be sure to write it out (for example) :) In the modern world of mixed systems and the internet, and files being flung around willy-nilly, and editors being configured to varying degrees of correctness, and such.... It's Pythonic to be able to handle all these files that anyone made on any system and treat them as they are clearly *meant* to be treated. Since the intention *is* clear that these are all *end of line* markers-- it's explicitly stated, just slightly differently depending on the OS-- Python treats all of the line-endings as equal on read if you want it to. By using either str.splitlines() or opening a text file as "rU". Thank goodness for that :) In some cases you may need a more pedantic approach to line endings. In that case, just use str.split() :) --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Sun Aug 16 14:53:08 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 16 Aug 2009 14:53:08 -0400 Subject: random.gauss vs. random.normalvariate In-Reply-To: References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> Message-ID: <4A885594.1080703@ieee.org> John Haggerty wrote: > On Sat, Aug 15, 2009 at 7:23 PM, Dennis Lee Bieber wrote: > > >> On Sat, 15 Aug 2009 14:34:36 -0600, John Haggerty >> declaimed the following in gmane.comp.python.general: >> >> >>> What does the term "thread safe" mean exactly. I never had to program >>> >> with >> >>> "threads" before >>> >> That, part way through the logic of the function, control could be >> switched to a different thread which call the same function... This >> second call would change some of the internal values and may then be >> preempted and control returned to the first thread, which continues the >> rest of the function with different values then it had when first >> preempted. >> >> A very contrived example, untested of course, consider it >> pseudo-code... >> >> startt = None >> >> def atimer(): >> global startt >> startt = time.time() >> time.sleep(5) >> print time.time() - startt >> >> t1 = threading.thread(atimer) >> t2 = threading.thread(atimer) >> t1.start() >> t2.start() >> >> Say t1 gets all the way up to the sleep call, and (since sleep is a >> releasing call), t2 then starts. t2 changes the value of startt; and >> sleeps... both sleep and presuming the resolution is fine enough, t1 >> resumes, and prints a delta time that is incorrect -- it is printing >> the time difference from when t2 started to sleep, not from when t1 >> started to sleep. >> -- >> Wulfraed Dennis Lee Bieber KD6MOG >> wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> > > Interesting so it seems that the compiler(c/c++)interpreter(perl, > python)/vm(java) doesn't do this? > > It is impossible for a language, vm, or operating system to avoid threading problems without the programmer's help, except by trivial means (eg. preventing you from having them at all). The power of threading is entirely tied up with the features the environment gives to the developer, and those features come with a risk. At one extreme is the CP/M model. You start a new program only when you finish the previous one. So the only communication between them is a file the first one leaves behind, that the second can look at. Next is separate processes. If you launch a second process, by default, they're independent, and not likely to get into trouble. But you can build pipes or shared memory, or sockets between them, and then you have to worry about race conditions. Next is threads, within a single process. At this point, you can share (global) variables between them, or you can have objects known to both when the thread is launched. The system cannot tell which ones are deliberate and which ones are accidental. So a language might give extra keywords to tell the compiler that certain things should be protected in certain ways. Or it might give a way to declare a "per-thread global" that acts like a global to each thread, but is actually two independent variables from the process point of view. The only real reason threads are singled out is it's easier to collide by mistake. But that's also what makes it efficient to "collide" on purpose. DaveA From darkwater42 at gmail.com Sun Aug 16 14:55:31 2009 From: darkwater42 at gmail.com (Douglas Alan) Date: Sun, 16 Aug 2009 11:55:31 -0700 (PDT) Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> <0297b230$0$20634$c3e8da3@news.astraweb.com> <74a3f562-6209-485e-9fbb-145ec00c331c@j21g2000yqe.googlegroups.com> <0297cd31$0$20634$c3e8da3@news.astraweb.com> Message-ID: <0ee729c3-22f0-450c-8fba-39ae74f7535d@d4g2000vbm.googlegroups.com> On Aug 16, 6:18?am, Steven D'Aprano wrote: > On Sun, 16 Aug 2009 01:41:41 -0700, Douglas Alan wrote: > > I would definitely not like a language that obscures assignment by > > moving it over to the right side of lines. > One could argue that left-assigned-from-right assignment obscures the > most important part of the assignment, namely *what* you're assigning, in > favour of what you're assigning *to*. The most important things are always the side-effects and the name- bindings. In a large program, it can be difficult to figure out where a name is defined, or which version of a name a particular line of code is seeing. Consequently languages should always go out of their way to make tracking this as easy as possible. Side effects are also a huge issue, and a source of many bugs. This is one of the reasons that that are many functional languages that prohibit or discourage side-effects. Side effects should be made as obvious as is feasible. This is why, for instance, in Scheme, variable assignment as an exclamation mark in it. E.g., (set! x (+ x 1)) The exclamation mark is to make the fact that a side effect is happening there stand out and be immediately apparent. And C++ provides the "const" declaration for similar reasons. > In any case, after half a century of left-from-right assignment, I think > it's worth the experiment in a teaching language or three to try it the > other way. The closest to this I know of is the family of languages > derived from Apple's Hypertalk, where you do assignment with: > > put somevalue into name That's okay with me, but only because the statement begins with "put", which lets you know at the very beginning of the line that something very important is happening. You don't have to scan all the way to the right before you notice. Still, I would prefer let name = somevalue as the "let" gives me the heads up right away, and then immediately after the "let" is the name that I might want to be able to scan for quickly. |>ouglas From psilord at merlin.cs.wisc.edu Sun Aug 16 15:17:02 2009 From: psilord at merlin.cs.wisc.edu (Peter Keller) Date: 16 Aug 2009 19:17:02 GMT Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> <5031edcc-c63e-4a3b-9f12-caba0cc34e92@r18g2000yqd.googlegroups.com> Message-ID: <4a885b2e$0$9897$80265adb@spool.cs.wisc.edu> In comp.lang.scheme w_a_x_man wrote: > On Aug 16, 11:05?am, Petey Keller wrote: >> Compiler go through *great* pains > > Compiler work real hard. > Compiler have heap big trouble. That's a funny observation in the context of this thread--which I appreciate, since syntax really is the cornerstone of meaning transferal between people. The unintended connotation brought in by what I mistakenly wrote underscores the value of syntax. However, what we don't have is a means of measuring the effectiveness and/or efficiency of expressing meaning for an arbitrary set of syntax rules. Computer Scientists can do this somewhat in that the expressive power of parsing is greater than regular expressions and both can use a syntax to represent them. But in a single complexity class, the "black art" of how to place a metric on a syntax is, at least at this time, relegated to the right brain and how it visually sees (and visually parses) the syntax and how our emotions relate to the syntax. The wolfram article, in fact, never does mention any metric other than "this is hard to understand, this is less hard to understand". In a sense, how is that useful at all? Instead of really trying to find a method by which understanding can be placed upon a metric (or discovering a method *can not* be found, he seems to anecdotally ascribe understanding difficulty upon various syntaxs. The real frustrations of Xah Lee might be explained by his denial of the right brain processing of syntax information. It is to be expected since most industrial cultures suppress right brain advancement (emotional understanding/social interaction, drawing, music, spatial relations) in lieu of left brain processing (language and syntax, symbolic manipulation (part, though not all of the skill set of math), object naming). In fact, his skills of communicating his ideas in a social setting which, in my opinion, are poor and stunted, is a red flag and the epitome of this type of cultural viewpoint. Thank you. -pete From sajmikins at gmail.com Sun Aug 16 15:36:20 2009 From: sajmikins at gmail.com (Simon Forman) Date: Sun, 16 Aug 2009 12:36:20 -0700 (PDT) Subject: Splitting a string into substrings of equal size References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: On Aug 14, 8:22?pm, candide wrote: > Suppose you need to split a string into substrings of a given size (except > possibly the last substring). I make the hypothesis the first slice is at the > end of the string. > A typical example is provided by formatting a decimal string with thousands > separator. > > What is the pythonic way to do this ? > > For my part, i reach to this rather complicated code: > > # ---------------------- > > def comaSep(z,k=3, sep=','): > ? ? z=z[::-1] > ? ? x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1] > ? ? return sep.join(x) > > # Test > for z in ["75096042068045", "509", "12024", "7", "2009"]: > ? ? print z+" --> ", comaSep(z) > > # ---------------------- > > outputting : > > 75096042068045 --> ?75,096,042,068,045 > 509 --> ?509 > 12024 --> ?12,024 > 7 --> ?7 > 2009 --> ?2,009 > > Thanks FWIW: def chunks(s, length=3): stop = len(s) start = stop - length while start > 0: yield s[start:stop] stop, start = start, start - length yield s[:stop] s = '1234567890' print ','.join(reversed(list(chunks(s)))) # prints '1,234,567,890' From python at mrabarnett.plus.com Sun Aug 16 16:00:27 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 16 Aug 2009 21:00:27 +0100 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <02969972$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4A88655B.2070108@mrabarnett.plus.com> bartc wrote: > > "Steven D'Aprano" wrote in > message news:02969972$0$20647$c3e8da3 at news.astraweb.com... >> On Fri, 14 Aug 2009 18:25:45 -0700, Dr. Phillip M. Feldman wrote: >> >>> It seems as though Python is actually expanding range(2,n) into a list >>> of numbers, even though this is incredibly wasteful of memory. There >>> should be a looping mechanism that generates the index variable values >>> incrementally as they are needed. >> >> >> Others have already pointed out to you that xrange() (for Python 2.x) >> does what you want. In Python 3.x, the old range() is gone for good, and >> xrange() renamed to just range(). > > It does seem rather worrying that whoever originally thought up Python > decided it would be a good idea to implement a simple 1 to N (or 0 to > N-1) for-loop by first creating an array of N consecutive integers! > Whoever? I am shocked! ;-) > They must have known Python was going to be slow anyway, but this > wouldn't have helped the speed any. Nor the memory consumption. > > A for-loop, for iterating over a simple sequence, should be one of the > fastest things in the language. > > [Presumably the internal code that created those consecutive integers > used a more conventional looping method...] > From shailen.tuli at gmail.com Sun Aug 16 16:13:32 2009 From: shailen.tuli at gmail.com (Shailen) Date: Sun, 16 Aug 2009 13:13:32 -0700 (PDT) Subject: zip codes Message-ID: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> Is there any Python module that helps with US and foreign zip-code lookups? I'm thinking of something that provides basic mappings of zip to cities, city to zips, etc. Since this kind of information is so often used for basic user-registration, I'm assuming functionality of this sort must be available for Python. Any suggestions will be much appreciated. - Shailen Tuli From no.email at please.post Sun Aug 16 16:29:15 2009 From: no.email at please.post (kj) Date: Sun, 16 Aug 2009 20:29:15 +0000 (UTC) Subject: XPath support? Message-ID: I'm looking for a XML parser that produces an object with full XPath support. What I've been using up to now, xml.etree.ElementTree, fails to support Xpath predicates, as in "spam[@eggs='3']/ham". What I'm trying to do is to read-in a large XML string, and parse it into an object from which I can extract nodes matching selectors that include such predicates. Any suggestions would be greatly appreciated. TIA! kynn From deets at nospam.web.de Sun Aug 16 16:31:24 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 16 Aug 2009 22:31:24 +0200 Subject: XPath support? In-Reply-To: References: Message-ID: <7er8ksF2hmnmqU1@mid.uni-berlin.de> kj schrieb: > I'm looking for a XML parser that produces an object with full > XPath support. What I've been using up to now, xml.etree.ElementTree, > fails to support Xpath predicates, as in "spam[@eggs='3']/ham". > > What I'm trying to do is to read-in a large XML string, and parse > it into an object from which I can extract nodes matching selectors > that include such predicates. > > Any suggestions would be greatly appreciated. Try lxml. It's element-tree compatible, and supports xpath. Diez From kevin.p.dwyer at gmail.com Sun Aug 16 16:37:16 2009 From: kevin.p.dwyer at gmail.com (Kev Dwyer) Date: Sun, 16 Aug 2009 20:37:16 +0000 (UTC) Subject: XPath support? References: Message-ID: On Sun, 16 Aug 2009 20:29:15 +0000, kj wrote: > I'm looking for a XML parser that produces an object with full XPath > support. What I've been using up to now, xml.etree.ElementTree, fails > to support Xpath predicates, as in "spam[@eggs='3']/ham". > > What I'm trying to do is to read-in a large XML string, and parse it > into an object from which I can extract nodes matching selectors that > include such predicates. > > Any suggestions would be greatly appreciated. > > TIA! > > kynn Have you tried lxml (http://codespeak.net/lxml/)? Kev From sturlamolden at yahoo.no Sun Aug 16 16:41:07 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Aug 2009 13:41:07 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> Message-ID: On 16 Aug, 11:45, "bartc" wrote: > A for-loop, for iterating over a simple sequence, should be one of the > fastest things in the language. Anyone experienced with interpreted high-level languages knows this is not true. Not because iterating a sequence is expensive, but because the interpreter is constantly executing the body of the loop. There is a reason why Matlab and Python/NumPy programmers rely heavily on vectorized array expressions for efficient numerics. The only thing more evil than a for-loop is recursive function calls. This does not mean Python is slow. It just means you have to program differently. From http Sun Aug 16 16:42:56 2009 From: http (Paul Rubin) Date: 16 Aug 2009 13:42:56 -0700 Subject: random.gauss vs. random.normalvariate References: <89df98da-cdaf-4422-9bc0-c0b46ebefcda@a13g2000yqc.googlegroups.com> <7xd46ws86b.fsf@ruckus.brouhaha.com> Message-ID: <7xbpmfqylr.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > > > No language can guard against independent access of a shared/global > > > object by multiple threads... > http://en.wikipedia.org/wiki/Erlang_(programming_language) > """ > Like operating system processes (and unlike green threads and operating > system threads) they have NO SHARED STATE between them. > """ > which seems to reinforce my statement, not refute it. Id say Erlang guards against independent access of shared/global objects by not allowing them. > (The Amiga was heavily dependent upon message ports... Having to > copy data buffers between processes would have slowed the system > down drastically [8MHz processor, in those days], It's perfectly ok for Erlang implementation to just pass pointers around, when the processes are on the same machine. Erlang prohibits data mutation so there isn't an issue of a process modifying some structure while another process is using it. From toby at telegraphics.com.au Sun Aug 16 16:51:21 2009 From: toby at telegraphics.com.au (toby) Date: Sun, 16 Aug 2009 13:51:21 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> Message-ID: <4f0af709-527a-47db-8a8a-b0b42c6fe34d@d32g2000yqh.googlegroups.com> On Aug 16, 12:05?pm, Peter Keller wrote: > In comp.lang.scheme Xah Lee wrote: > > > Xah's Edu Corner: The importance of syntax & notations. > > >http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstr... > > > this article should teach the coding sophomorons and computer > > ?science? idiotic authors who harbor the notion that syntax is not > > important, picked up by all the elite i-reddit & twittering & ?hacker > > news am-hip dunces. > > I must have really tweaked you with my "Syntax is not important, ideas are." > statement. > > I read Wolfram's article carefully. He applies an intuitive sense onto > why he does or doesn't like a particular notation, but yet can't really > elucidate his feelings. Exactly; and as far as I can determine, Knuth does the same. He applies standards of *good taste* to his notation. (No surprise that he's also singled out for vituperation by the OP.) In my opinion Knuth believed in the value of literate programming for similar reasons: To try to exploit existing cognitive training. If your user base is familiar with English, or mathematical notation, or some other lexicography, try to exploit the pre-wired associations. Clearly this involves some intuition. > ... > Thank you. > > -pete From fateman at gmail.com Sun Aug 16 17:00:42 2009 From: fateman at gmail.com (rjf) Date: Sun, 16 Aug 2009 14:00:42 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> Message-ID: <75e1deb2-f879-4deb-bd50-56954dfefc64@o6g2000yqj.googlegroups.com> On Aug 16, 9:05?am, Peter Keller wrote: > In comp.lang.scheme Xah Lee wrote: > > > Xah's Edu Corner: The importance of syntax & notations. > > >http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstr... > > > this article should teach the coding sophomorons and computer > > ?science? idiotic authors who harbor the notion that syntax is not > > important, picked up by all the elite i-reddit & twittering & ?hacker > > news am-hip dunces. > > I must have really tweaked you with my "Syntax is not important, ideas are." > statement. > > I read Wolfram's article carefully. He applies an intuitive sense onto > why he does or doesn't like a particular notation, but yet can't really > elucidate his feelings. I'm surprised that didn't tweak you worse. He > also goes so far as to mention that: > > "But actually we still don't know a clean simple way to represent things > like geometrical diagrams in a kind of language-like notation. And > my guess is that actually of all the math-like stuff out there, only > a comparatively small fraction can actually be represented well with > language-like notation." > For someone talking about notation and language, it is amusing that Wolfram refuses to write grammatically correct sentences. Each of the pseudo-sentences quoted above is a dependent clause. Wolfram writes like that. He typically begins sentences with "but" or "and". In the article cited, he also claims to be more-or-less the only person alive to have thought about these issues, and that Mathematica is the solution. This is not surprising,and it is nevertheless clear that Wolfram has spent some time thinking about mathematical notation, and some money developing fonts and such. His self-praise is perhaps not deserved. It is unfortunate that most users of Mathematica labor under a misunderstanding of the meaning of the fundamental algorithmic notation of that system, namely "function definition". f[x_]:=x+1 is not a function definition, although most users think so. In fact, it is a pattern/replacement rule. If you want to write the equivalent of the lisp (defun f(x)(+ x 1)) you can do so in mathematica, but it looks like this: f=#1+1& or alternatively, f=Function[Plus[Slot[1],1]] or alternatively, f= Function[{x},x+1] How do those choices grab you for the Emmy in "Excellence in Notation"? By the way, what is wrong with f[x_]:=x+1? While you might think it maps x->x+1 for all x, it does so only in the absence of other rules involving f. Thus the presence of another definition (actually another rule) ... f[z_]:=z^2/;OddQ[z] changes the definition when the argument is an odd integer. An equivalent definition is f[z_?OddQ]:=z^2 now you could have 2 rules f[x_?Predicate1]:= 123 f[x_?Predicate2]:= 456 and it might not be clear which Predicate is a subset of the other. (It is clear that the blank pattern "_" is a superset of "_?OddQ" ). So how does Mathematica deal with this situation? The predicates are tested in some order until one returns True. What order is that? "Whenever the appropriate ordering is not clear, Mathematica stores rules in the order you give them. " Oh, when is the ordering not clear? Uh, "you should realize that this [ordering] is not always possible". (quotes from mathematica documentation , TheOrderingOfDefinitions.) While Wolfram has provided an admirable summary of the history of notation, his solution is less so. RJF From martin.hellwig at dcuktec.org Sun Aug 16 17:10:05 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Sun, 16 Aug 2009 22:10:05 +0100 Subject: zip codes In-Reply-To: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> Message-ID: Shailen wrote: > Is there any Python module that helps with US and foreign zip-code > lookups? I'm thinking of something that provides basic mappings of zip > to cities, city to zips, etc. Since this kind of information is so > often used for basic user-registration, I'm assuming functionality of > this sort must be available for Python. Any suggestions will be much > appreciated. > There might be an associated can of worms here, for example in the Netherlands zip codes are actually copyrighted and require a license if you want to do something with them, on the other hand you get a nice SQL formatted db to use it. I don't know how this works in other countries but I imagine that it is likely to be generally the same. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From rylesny at gmail.com Sun Aug 16 17:10:25 2009 From: rylesny at gmail.com (ryles) Date: Sun, 16 Aug 2009 14:10:25 -0700 (PDT) Subject: Python 2.6 still not giving memory back to the OS... References: Message-ID: <79bbe86b-0d3b-4f03-b0df-be4b3308d4cd@f10g2000vbf.googlegroups.com> On Aug 15, 7:55?am, Chris Withers wrote: > Hi All, > > I thought this was fixed back in Python 2.5, but I guess not? > > So, I'm playing in an interactive session: > > ?>>> from xlrd import open_workbook > ?>>> b = open_workbook('some.xls',pickleable=0,formatting_info=1) > > At this point, top shows the process usage for python to be about 500Mb. > That's okay, I'd expect that, b is big ;-) > > ?>>> del b > > However, it still does now, maybe the garbage collector needs a kick? > > ?>>> import gc > ?>>> gc.collect() > 702614 > > Nope, still 500Mb. What gives? How can I make Python give the memory its > no longer using back to the OS? > > Okay, so maybe this is something to do with it being an interactive > session? So I wrote this script: > > from xlrd import open_workbook > import gc > b = open_workbook('some.xls',pickleable=0,formatting_info=1) > print 'opened' > raw_input() > del b > print 'deleted' > raw_input() > gc.collect() > print 'gc' > raw_input() > > The raw inputs are there so I can check the memory usage in top. > Even after the gc, Python still hasn't given the memory back to the OS :-( > > What am I doing wrong? > > Chris > > -- > Simplistix - Content Management, Batch Processing & Python Consulting > ? ? ? ? ? ? -http://www.simplistix.co.uk Repeat the 'b = open_workbook ...' line in the interpreter several times and track the memory usage after each execution. I noticed this behavior on linux, but saw that after repeating it a few times memory usage finally stop going up. Probably just the behavior of the allocator. From aahz at pythoncraft.com Sun Aug 16 17:24:17 2009 From: aahz at pythoncraft.com (Aahz) Date: 16 Aug 2009 14:24:17 -0700 Subject: Nltk with python References: <82c9f923-1098-4b7e-8f9d-9504c1a8962c@12g2000pri.googlegroups.com> Message-ID: In article <82c9f923-1098-4b7e-8f9d-9504c1a8962c at 12g2000pri.googlegroups.com>, ArshaKrishna wrote: > >How can I resolve scope ambiguity using nltk toolkit with python Question not clear, please provide more explanation -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From aahz at pythoncraft.com Sun Aug 16 17:25:12 2009 From: aahz at pythoncraft.com (Aahz) Date: 16 Aug 2009 14:25:12 -0700 Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> Message-ID: In article <35833d36-2fdc-4ed8-8142-604af3c88afe at k6g2000yqn.googlegroups.com>, Shailen wrote: > >Is there any Python module that helps with US and foreign zip-code >lookups? I'm thinking of something that provides basic mappings of zip >to cities, city to zips, etc. Since this kind of information is so >often used for basic user-registration, I'm assuming functionality of >this sort must be available for Python. Any suggestions will be much >appreciated. There's no module; you have to purchase the information and then massage it yourself. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From nagle at animats.com Sun Aug 16 17:58:40 2009 From: nagle at animats.com (John Nagle) Date: Sun, 16 Aug 2009 14:58:40 -0700 Subject: Xah's Edu Corner: The importance of syntax & notations. In-Reply-To: References: Message-ID: <4a888022$0$1637$742ec2ed@news.sonic.net> Xah Lee wrote: > Xah's Edu Corner: The importance of syntax & notations. > > http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstract.html > > this article should teach the coding sophomorons and computer > ?science? idiotic authors who harbor the notion that syntax is not > important, picked up by all the elite i-reddit & twittering & hacker > news am-hip dunces. Definitely read Wolfram's paper. He and his people actually had to solve the problem. Wolfram had to face up to the big problem - how do we input traditional mathematics into a computer unambiguously. Version 1 was Mathematica FullForm, which is very wordy but clear, like Ada. This worked, but was too clunky. After a few redesigns, they came up with what he calls StandardForm, which is Mathematica's variant on what he calls "TraditionalForm", or mathematics as currently written in textbooks. The differences are subtle; the main one is that precedence is more explicit, and a "double strike" convention is used to disambiguate certain meta-symbols, like the "d" used in derivatives and "i" used as sqrt(-1). StandardForm is unambiguous. TraditionalForm is not, as anyone who spends too much time reading other people's math publications realizes. Cleverly, the Mathematica people have been able to produce a set of heuristics which, Wolfram claims, allows converting traditional form into the unambiguous StandardForm, getting it right most of the time. (I've been struggling to read a paper on machine learning which has some non-standard operator precedence problems, and I wish the paper was in StandardForm.) Wolfram would, I think, like to make "StandardForm" the standard for publication, and in time, something like that will probably happen. It's useful to be able to get math in and out of symbolic manipulation systems. Anyway, read the paper. John Nagle From shailen.tuli at gmail.com Sun Aug 16 18:26:27 2009 From: shailen.tuli at gmail.com (Shailen) Date: Sun, 16 Aug 2009 15:26:27 -0700 (PDT) Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> Message-ID: <512e67d9-8733-4329-a7d9-c6e21d6a2165@r38g2000yqn.googlegroups.com> Thanks Martin and Aahz. Anyone know if zip code information is copyrighted for the US? Anyone can look up zip codes on usps.gov (and other locations),so the information is readily available. I need zip codes for a handful of cities and could map those myself (or write a script to scrape them for me), but am not sure if they *MUST* be purchased for copyright reasons. Anyone know? - Shailen Tuli From davea at ieee.org Sun Aug 16 18:27:47 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 16 Aug 2009 18:27:47 -0400 Subject: redoing libgmail interface to "smtplib" blah? In-Reply-To: References: Message-ID: <4A8887E3.3050000@ieee.org> Dennis Lee Bieber wrote: > On Sat, 15 Aug 2009 23:14:39 -0600, John Haggerty > declaimed the following in gmane.comp.python.general: > > >> I did detect one problem thus far >> >> File "test.py", line 152 >> if len(args) == 1 and args[0] = "-c": >> >> > Should have been fine, unless my memory of sys.argv contents was > wrong (as I recall, sys.argv, if it behaves like other languages, would > > You missed the actual problem: there's a single '=' in the second part of the if expression. Should be "==" DaveA From sturlamolden at yahoo.no Sun Aug 16 18:35:26 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 16 Aug 2009 15:35:26 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> On 16 Aug, 14:57, Dennis Lee Bieber wrote: > ? ? ? ? Well, the alternative would be to have two keywords for looping: one > for your "simple" incrementing integer loop, and another for a loop that > operates over the elements of some collection type. A compiler could easily recognise a statement like for i in range(n): as a simple integer loop. In fact, Cython is able to do this. From http Sun Aug 16 19:17:59 2009 From: http (Paul Rubin) Date: 16 Aug 2009 16:17:59 -0700 Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> <512e67d9-8733-4329-a7d9-c6e21d6a2165@r38g2000yqn.googlegroups.com> Message-ID: <7x63cnbb6g.fsf@ruckus.brouhaha.com> Shailen writes: > Thanks Martin and Aahz. Anyone know if zip code information is > copyrighted for the US? Anyone can look up zip codes on usps.gov (and > other locations),so the information is readily available. I need zip > codes for a handful of cities and could map those myself (or write a > script to scrape them for me), but am not sure if they *MUST* be > purchased for copyright reasons. Anyone know? I don't think US zip code info is copyrighted. There is a lot of it in the TIGER database: http://www.census.gov/geo/www/tiger/tigerua/ua_tgr2k.html There are also some API's operated by usps.com if you want just a few lookups now and then. It was a long time ago, I don't remember specifics, and the contents are surely out of date by now, but I extracted a bunch of the TIGER geographic coordinates for zip codes here: http://www.nightsong.com/phr/chess/zipcodes.zip From http Sun Aug 16 19:32:31 2009 From: http (Paul Rubin) Date: 16 Aug 2009 16:32:31 -0700 Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> <512e67d9-8733-4329-a7d9-c6e21d6a2165@r38g2000yqn.googlegroups.com> <7x63cnbb6g.fsf@ruckus.brouhaha.com> Message-ID: <7xws539vxs.fsf@ruckus.brouhaha.com> > It was a long time ago, I don't remember specifics, and the contents > are surely out of date by now, but I extracted a bunch of the TIGER > geographic coordinates for zip codes here: > > http://www.nightsong.com/phr/chess/zipcodes.zip That file may have actually come from here: http://www.census.gov/geo/www/tiger/zip1999.html From invalid at invalid Sun Aug 16 20:07:18 2009 From: invalid at invalid (Grant Edwards) Date: Sun, 16 Aug 2009 19:07:18 -0500 Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> <512e67d9-8733-4329-a7d9-c6e21d6a2165@r38g2000yqn.googlegroups.com> Message-ID: On 2009-08-16, Shailen wrote: > Thanks Martin and Aahz. Anyone know if zip code information is > copyrighted for the US? You can't copyright "information" as such. Only concrete expressions of information. A particular publication containing zip code information can be copyrighted. The underlying facts themselve cannot be. -- Grant From benjamin.kaplan at case.edu Sun Aug 16 21:23:20 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Sun, 16 Aug 2009 21:23:20 -0400 Subject: Python 'for' loop is memory inefficient In-Reply-To: <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: On Sun, Aug 16, 2009 at 6:35 PM, sturlamolden wrote: > > A compiler could easily recognise a statement like > > ? for i in range(n): > > as a simple integer loop. In fact, Cython is able to do this. but special cases aren't special enough to break the rules. From sjmachin at lexicon.net Sun Aug 16 21:23:23 2009 From: sjmachin at lexicon.net (John Machin) Date: Sun, 16 Aug 2009 18:23:23 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: On Aug 17, 8:35?am, sturlamolden wrote: > A compiler could easily recognise a statement like > ? ?for i in range(n): > as a simple integer loop. In fact, Cython is able to do this. Extremely easy, once users relinquish the right to replace built-in "range" with their own concoctions ... From exarkun at twistedmatrix.com Sun Aug 16 21:28:40 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 17 Aug 2009 01:28:40 -0000 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: <20090817012840.8740.554583249.divmod.xquotient.17@localhost.localdomain> On 01:23 am, benjamin.kaplan at case.edu wrote: >On Sun, Aug 16, 2009 at 6:35 PM, sturlamolden >wrote: >> >>A compiler could easily recognise a statement like >> >>? for i in range(n): >> >>as a simple integer loop. In fact, Cython is able to do this. > >but special cases aren't special enough to break the rules. Although I think PyPy also recognizes this case and makes it as efficient as using xrange, and does so without breaking any rules. There *are* _some_ legitimate complaints to be made about the CPython runtime. :) Jean-Paul From http Sun Aug 16 21:44:33 2009 From: http (Paul Rubin) Date: 16 Aug 2009 18:44:33 -0700 Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: <7xtz079ptq.fsf@ruckus.brouhaha.com> exarkun at twistedmatrix.com writes: > Although I think PyPy also recognizes this case and makes it as > efficient as using xrange, and does so without breaking any rules. How can pypy possibly know that the user hasn't assigned some other value to "range"? From pavlovevidence at gmail.com Sun Aug 16 21:53:10 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 16 Aug 2009 18:53:10 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: <900c0d5e-a41a-4820-9844-816afa1a33c9@g10g2000yqh.googlegroups.com> On Aug 16, 6:28?pm, exar... at twistedmatrix.com wrote: > On 01:23 am, benjamin.kap... at case.edu wrote: > > >On Sun, Aug 16, 2009 at 6:35 PM, sturlamolden > >wrote: > > >>A compiler could easily recognise a statement like > > >>? for i in range(n): > > >>as a simple integer loop. In fact, Cython is able to do this. > > >but special cases aren't special enough to break the rules. > > Although I think PyPy also recognizes this case and makes it as > efficient as using xrange, and does so without breaking any rules. PyPy uses a JIT compiler (which is still slower than CPython, suggesting that perhaps they should have spent more time optimizing the general case than optimizing for an easily avoided special case). > There *are* _some_ legitimate complaints to be made about the CPython > runtime. :) This isn't one of them. xrange has been part of Python for 10 years. If there are any complaints to be made about this situation it's that there are any 2.x learning materials anythere that continue to use range() and not xrange() in this context. Carl Banks From pavlovevidence at gmail.com Sun Aug 16 22:12:20 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 16 Aug 2009 19:12:20 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> On Aug 16, 3:35?pm, sturlamolden wrote: > On 16 Aug, 14:57, Dennis Lee Bieber wrote: > > > ? ? ? ? Well, the alternative would be to have two keywords for looping: one > > for your "simple" incrementing integer loop, and another for a loop that > > operates over the elements of some collection type. > > A compiler could easily recognise a statement like > > ? ?for i in range(n): > > as a simple integer loop. It would be a simple to do if you were writing it for a different langauge was a lot less dynamic than Python is. It'd be quite a complex hack to add it to CPython's compiler while maintaing the current highly dynamic runtime semantics and backwards compatibility, which is a design constraint of Python whether you like it or not. And all this complaining about an issue that can be worked around by xrange instead of range. Sheesh. > In fact, Cython is able to do this. Cython can do this easily because it is a different language that is a lot less dynamic than Python. If you don't care about the dynamic stuff why don't you just use Cython? Or quit complaining and just use xrange. Carl Banks From nobody at nowhere.com Sun Aug 16 22:21:43 2009 From: nobody at nowhere.com (Nobody) Date: Mon, 17 Aug 2009 03:21:43 +0100 Subject: OT Signature quote [was Re: Unrecognized escape sequences in string literals] References: <6e13754c-1fa6-4d1b-8861-146bffec8656@h30g2000vbr.googlegroups.com> <02957d23$0$20647$c3e8da3@news.astraweb.com> <5fcd454d-14b4-452b-91d3-938e9fa0bd18@r38g2000yqn.googlegroups.com> <02975ce6$0$20634$c3e8da3@news.astraweb.com> <029783cd$0$20634$c3e8da3@news.astraweb.com> Message-ID: On Sun, 16 Aug 2009 05:05:01 +0000, Steven D'Aprano wrote: > Now that I understand what the semantics of cout << "Hello world" are, I > don't have any problem with it either. It is a bit weird, "Hello world" > >> cout would probably be better, Placing the stream on the LHS allows the main forms of << to be implemented as methods of the ostream class. C++ only considers the LHS operand when attempting to resolve an infix operator as a method. Also, << and >> are left-associative, and that cannot be changed by overloading. Having the ostream on the LHS allows the operators to be chained: cout << "Hello" << ", " << "world" << endl equivalent to: (((cout << "Hello") << ", ") << "world") << endl [operator<< returns the ostream as its result.] Even if you could make >> right-associative, the values would have to be written right-to-left: endl >> "world" >> ", " >> "Hello" >> cout i.e.: endl >> ("world" >> (", " >> ("Hello" >> cout))) From benjamin at python.org Sun Aug 16 22:55:14 2009 From: benjamin at python.org (Benjamin Peterson) Date: Sun, 16 Aug 2009 21:55:14 -0500 Subject: [RELEASED] Python 3.1.1 Message-ID: <1afaf6160908161955k6968c378md76ec37cba4865aa@mail.gmail.com> On behalf of the Python development team, I'm happy to announce the first bugfix release of the Python 3.1 series, Python 3.1.1. This bug fix release fixes many normal bugs and several critical ones including potential data corruption in the io library. Python 3.1 focuses on the stabilization and optimization of the features and changes that Python 3.0 introduced. For example, the new I/O system has been rewritten in C for speed. File system APIs that use unicode strings now handle paths with undecodable bytes in them. Other features include an ordered dictionary implementation, a condensed syntax for nested with statements, and support for ttk Tile in Tkinter. For a more extensive list of changes in 3.1, see http://doc.python.org/3.1/whatsnew/3.1.html or Misc/NEWS in the Python distribution. Please note the Windows and Mac binaries are not available yet but will be in the coming days. To download Python 3.1.1 visit: http://www.python.org/download/releases/3.1.1/ The 3.1 documentation can be found at: http://docs.python.org/3.1 Bugs can always be reported to: http://bugs.python.org Enjoy! -- Benjamin Peterson Release Manager benjamin at python.org (on behalf of the entire python-dev team and 3.1.1's contributors) From xahlee at gmail.com Sun Aug 16 23:00:23 2009 From: xahlee at gmail.com (Xah Lee) Date: Sun, 16 Aug 2009 20:00:23 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> Message-ID: Thanks Raymond. I've been out of python community for a couple of years. I've saved your messages and will study it later when next time i work in python. Possibly today and will reply in some of your points. But just wanted to say thanks for improving python. Also, sometimes ago out of the blue i noticed someone has posted a bug on python's gzip doc with acknowledgement. http://bugs.python.org/issue2406 Thank you M.-A. DARCHE (madarche). Also, i noticed python doc now and later has improved a lot since last i looked around python 2.4. For one thing, the html/xhtml is now valid html. Good riddence of the fucking TeX. Also, code examples have syntax coloring on. Xah ? http://xahlee.org/ ? On Aug 12, 12:15 pm, Raymond Hettinger wrote: > [Xah Lee] > > > i've wrote several articles about this issue, total time spend on this > > is probably more than 2 months full-time work. See: > > > ? Python Documentation Problems > > http://xahlee.org/perl-python/python_doc_index.html > > I just read you post. You did devote a substantial amount of time > to the project. Some of your criticisms are valid. Wish you had > posted patches, I think many of them would have been accepted. > > Since you wrote this a few years ago, many examples have > been added to the docs and more are forthcoming. > > > I often receive thank you emails for 2 particular articles, which are > > most frequently google searched as indicated by my weblog: > > > ? Python Doc Problem Example: gzip > > http://xahlee.org/perl-python/python_doc_gzip.html > > > ? Python Doc Problem Example: sort() > > http://xahlee.org/perl-python/python_doc_sort.html > > > ? Sorting in Python and Perl > > http://xahlee.org/perl-python/sort_list.html > > Some are the criticisms are valid; others seem off-base. > > Here are a few thoughts on list.sort() for those who are interested: > > * The key= and reversed= parameters are not intended for special > cases, leaving cmp= for the general case. They were intended to > be full replacements. In Python3.x, the cmp function is gone. > > * The interaction of the key= and cmp= functions can be made to > interact (the key function is first applied to every element and > the cmp function then gets applied to the results of the key > function). This isn't a normal or intended use case, so the docs > don't delve into the subject. > > * The reversed parameter does more than list.sort() followed by > list.reverse(). It also preserves stability in the event of equal > keys: > > >>> sorted([(1,2), (1,3)], key=itemgetter(0), reverse=True) > [(1,2), (1,3)] > > So it was not correct to say that the following are equivalent: > > li.sort(lambda x, y: cmp(x[1],y[1]), reverse=True) > li.sort(lambda x, y: cmp(y[1],x[1])) > > * We should link the sorted() and list.sort() docs to the > sorting how-to (with a fuller discussion on the art of sorting > including a discussion of operator.itemgetter() and > operator.attrgetter() which were designed to work with the key= > parameter. > > Raymond From nobody at nowhere.com Sun Aug 16 23:10:17 2009 From: nobody at nowhere.com (Nobody) Date: Mon, 17 Aug 2009 04:10:17 +0100 Subject: Python 'for' loop is memory inefficient References: <24980842.post@talk.nabble.com> <4A8612CE.7080700@stoneleaf.us> <200908160830.55031.emmanuel.surleau@gmail.com> Message-ID: On Sun, 16 Aug 2009 11:41:21 -0400, Benjamin Kaplan wrote: > It's not that the code is bad, but too many people coming from Java > and C keep thinking of for loops like they're using Java or C and > therefore that "for i in range(a,b)" is identical to "for(int i = a; i > < b; i++)". It's not and, for the most part, you shouldn't code like > that. Since you're using numbers, range/xrange is the appropriate > idiom but you still have to remember that a for loop in python doesn't > loop until a condition is met, it loops through an iterator until the > interator says it's done. Java also has iterators; it's more a case of people coming from C and BASIC. Although, some of those may have come *through* Java without abandoning old habits. You see the same thing with people coming from BASIC to C and writing: #define NUM_DATES 50 int day[NUM_DATES], month[NUM_DATES], year[NUM_DATES]; rather than defining a "struct". Sometimes referred to as "I know ten languages and can write in BASIC in all of them". From nobody at nowhere.com Sun Aug 16 23:32:07 2009 From: nobody at nowhere.com (Nobody) Date: Mon, 17 Aug 2009 04:32:07 +0100 Subject: wxFormBuilder finally supports wxPython References: Message-ID: On Sun, 16 Aug 2009 03:19:51 -0700, sturlamolden wrote: > Version 3.1 of wxFormBuilder can generate wxPython code. I have > previously used wxFormBuilder to generate XRC files for my wxPython > projects. Though still in beta, this might be even better. :-) Is there a reason to prefer code over XRC? From jon at ffconsultancy.com Mon Aug 17 00:05:46 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 17 Aug 2009 05:05:46 +0100 Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> <5031edcc-c63e-4a3b-9f12-caba0cc34e92@r18g2000yqd.googlegroups.com> Message-ID: w_a_x_man wrote: > On Aug 16, 11:05?am, Petey Keller wrote: >> Compiler go through *great* pains > > Compiler work real hard. > Compiler have heap big trouble. ROTFL. :-) -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From xahlee at gmail.com Mon Aug 17 00:43:48 2009 From: xahlee at gmail.com (Xah Lee) Date: Sun, 16 Aug 2009 21:43:48 -0700 (PDT) Subject: python doc available in emacs info format? Message-ID: btw, is there still info format for python doc? i feel kinda sad that emacs info format has pretty much been deprecated over the past decade. About a decade ago, you still will see now and then people asking for emacs info format of docs (was the days of perl). Today, one don't hear of it. Part of this is due to emacs cult problem. See: ? Emacs Modernization http://xahlee.org/emacs/emacs_modernization.html ? Emacs Should Adopt HTML To Replace Texinfo http://xahlee.org/emacs/modernization_html_vs_info.html ? Language, Purity, Cult, and Deception http://xahlee.org/UnixResource_dir/writ/lang_purity_cult_deception.html Xah ? http://xahlee.org/ ? On Dec 11 2008, 6:56 am, Matthias wrote: > Xah Lee writes: > > in programing elisp in emacs, i can press ?Ctrl+h f? to lookup > > the doc for the function under cursor. is there such facility > > when coding in perl, python, php? > > Yes, try C-h S (or similarly S): > > (info-lookup-symbol SYMBOL &optional MODE) Display the > definition of SYMBOL, as found in the relevant manual. When this > command is called interactively, it reads SYMBOL from the > minibuffer. > > Note that `the relevant manual' means an info file. With recent > emacsen on an Ubuntu distro, python arrives with info files and > everything is well configured. It also works with bash, latex, perl, > scheme, elisp, awk, texinfo, makefile, libc, or any info file with an > index. > -- > Matthias From psilord at merlin.cs.wisc.edu Mon Aug 17 01:22:44 2009 From: psilord at merlin.cs.wisc.edu (Peter Keller) Date: 17 Aug 2009 05:22:44 GMT Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> <4f0af709-527a-47db-8a8a-b0b42c6fe34d@d32g2000yqh.googlegroups.com> Message-ID: <4a88e924$0$9895$80265adb@spool.cs.wisc.edu> In comp.lang.scheme toby wrote: > In my opinion Knuth believed in the value of literate programming for > similar reasons: To try to exploit existing cognitive training. If > your user base is familiar with English, or mathematical notation, or > some other lexicography, try to exploit the pre-wired associations. > Clearly this involves some intuition. I've dabbled in the linguistics field a little bit and this thread made me remember a certain topic delineated in this paper: http://complex.upf.es/~ricard/SWPRS.pdf This paper uses a concept that I would say needs more investigation: The mapping of syntax onto metric spaces. In fact, the paper literally makes a statement about how physically close two words are when mapped onto a line of text and language networks build graph topologies based upon the distance of words from each other as they relate in syntactical form. It seems the foundations for being able to construct a metric to "measure" syntax is somewhat available. If you squint at the math in the above paper, you can see how it can apply to multidimensional metric spaces and syntax in different modalities (like the comparison between reading written words and hearing spoken words). For example, here the same semantic idea in a regex defined three ways: english-like: Match the letter "a" followed by one or more letter "p"s followed by the letter "l" then optionaly the letter "e". scheme-like: (regex (char-class \#a) (re+ (char-class \#p)) (char-class \#l) (re? (char-class \#e))) perl-like: /ap+le?/ The perl-like one would be the one chosen by most programmers, but the various reasons why it is chosen will fluctuate. Can we do better? Can we give a predictable measurement of some syntactic quantities that we can optimize and get a predictable answer? Most people would say the perl-like form has the least amount of "syntactic garbage" and is "short". How do we meaningfully define those two terms? One might say "syntactic garbage" is syntax which doesn't relate *at all* to the actual semantic objects, and "short" might mean elimination of redundant syntax and/or transformation of explicit syntax into implicit syntax already available in the metric space. What do I mean by explicit versus implicit? In the scheme-like form, we explicitly denote the evaluation and class of the various semantic objects of the regex before applying the "regex" function across the evaluated arguments. Whitespace is used to separate the morphemes of only the scheme syntax. The embedding metric space of the syntax (meaning the line of text indexed by character position) does nothing to help or hinder the expression of the semantic objects. In the perl-like form, we implicitly denote the evaluation of the regex by using a prototyping-based syntax, meaning the inherent qualities of the embedding metric space are utilized. This specifically means that evaluation happens left to right in reading order and semantic objects evaluate directly to themselves and take as arguments semantic objects as related directly in the embedding metric space. For example, the ? takes as an argument the semantic object at location index[?]-1. Grouping parenthsis act as a VERY simple tokenization system to group multiple objects into one syntactical datum. Given the analysis, it seems the perl-like regex generally auto-quote themselves as an advantageous use of the embeded metric space in which they reside (aka the line of text). The english-like form is the worst for explicit modeling because it abstracts the semantic objects into a meta-space that is then referenced by the syntax in the embedding space of the line itself. In human reasoning, that is what the quotes mean. Out of the three syntax models, only the perl one has no redundant syntax and takes up the smallest amount of the metric space into which it is embedded--clearly seen by observation. Consider if we have quantities "syntactic datums" versus "semantic objects", then one might make an equation like this: semantic objects expressiveness = ---------------- syntactic datums And of course, expressiveness rises as semantic objects begin to outweigh syntactic objects. This seems a very reasonable, although simplistic, model to me and would be a good start in my estimation. I say simplistic because the semantic objects are not taken in relation to themselves on the metric space the syntactic datums are embeded, I'll get to this in a bit. Now, what do we do with the above equation, well, we define what we can, and then optimize the hell out of it. "semantic objects" for a computer language is probably a fixed quantity, there are only so many operators and grouping constructs, and usually very few, meaning one, function description semantic objects. So, we are left with a free variable of "syntactic datums" that we should minimize to be as small as possible. If we don't take into consideration the topological mapping of the semantic objects into the syntactic datum space, then the number of semantic objects at least equals the number of syntactic datums. Expressiveness is simply one in the best case, and this would be pretty poor for sure. It could be worse--just add redundant syntactic datums, now it is worse! If we take into consideration the mapping of the semantic objects onto the metric space, then maybe this becomes the new equation: distance(index[obj1], index[obj2], ..., index[objn]) expressiveness = ---------------------------------------------------- syntactic datums The distance() function in this new model is the centroid of the syntactic datum which represent the semantic object. (Of course, there are other models of expressiveness which would need to be explored based upon this incremental idea I'm presenting.) Larger distances between semantic objects, or larger syntactic constructs, would mean less expressiveness. This is interesting, because it can give a rough number that sorts the three syntactic models I provided for the regex and it would follow conventional wisdom. This is a decriptivist model of syntax measurement. Obviously, the fun is can we search an optimization tree to try find an optimal set of syntactic datums to represent a known and finite set of semantic objects taking into consideration the features of the metric space into which the syntactic datums are embedded? Maybe for another day.... Later, -pete From xahlee at gmail.com Mon Aug 17 01:32:07 2009 From: xahlee at gmail.com (Xah Lee) Date: Sun, 16 Aug 2009 22:32:07 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. References: Message-ID: <25203724-bf60-484f-9ede-e61c45f15e33@s31g2000yqs.googlegroups.com> Personally, particular interesting info i've learned is that, for all my trouble in the past decade expressing problems of traditional math notation, i learned from his article this single-phrase summary: ?traditional math notation lacks a grammar?. The article is somewhat disappointing though. I was expecting he'd go into some details about the science of math notations, or, as he put it aptly: ?linguistics of math notations?. However, he didn't touch the subject, except saying that it haven't been studied. Xah On Aug 15, 10:54?pm, Xah Lee wrote: > Xah's Edu Corner: The importance of syntax & notations. > > http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstr... > > this article should teach the coding sophomorons and computer > ?science? idiotic authors who harbor the notion that syntax is not > important, picked up by all the elite i-reddit & twittering & ?hacker > news am-hip dunces. > > Further readings: > > ? The TeX Pestilence > ?http://xahlee.org/cmaci/notation/TeX_pestilence.html > > ? A Notation for Plane Geometry > ?http://xahlee.org/cmaci/notation/plane_geometry_notation.html > > ? The Concepts and Confusions of Prefix, Infix, Postfix and Fully > Nested Notations > ?http://xahlee.org/UnixResource_dir/writ/notations.html > > ? The Problems of Traditional Math Notation > ?http://xahlee.org/cmaci/notation/trad_math_notation.html > > ? Xah > ?http://xahlee.org/ > > ? From psilord at merlin.cs.wisc.edu Mon Aug 17 01:39:48 2009 From: psilord at merlin.cs.wisc.edu (Peter Keller) Date: 17 Aug 2009 05:39:48 GMT Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> <4f0af709-527a-47db-8a8a-b0b42c6fe34d@d32g2000yqh.googlegroups.com> <4a88e924$0$9895$80265adb@spool.cs.wisc.edu> Message-ID: <4a88ed24$0$9896$80265adb@spool.cs.wisc.edu> In comp.lang.scheme Peter Keller wrote: > The distance() function in this new model is the centroid of the syntactic > datum which represent the semantic object. Oops. I meant to say: "The distance() function in this new model uses the centroid of each individual syntactic datum (which represents the semantic object) as the location for each semantic object." Sorry. -pete From ranjithpmathew at gmail.com Mon Aug 17 01:59:02 2009 From: ranjithpmathew at gmail.com (L@D@n) Date: Sun, 16 Aug 2009 22:59:02 -0700 (PDT) Subject: GUI interface builder for python Message-ID: Which is the best GUI interface builder with drag and drop capabilities. I am using Ubuntu GNU/Linux. Please help me. Thank you. From jasevv at gmail.com Mon Aug 17 02:12:42 2009 From: jasevv at gmail.com (Jaseem) Date: Sun, 16 Aug 2009 23:12:42 -0700 (PDT) Subject: GUI interface builder for python References: Message-ID: <1960c134-b4a0-4b96-bd58-1cf00dab9d72@d32g2000yqh.googlegroups.com> On Aug 17, 10:59?am, "L at D@n" wrote: > Which is the best GUI interface builder with drag and drop > capabilities. > I am using Ubuntu GNU/Linux. > Please help me. > Thank you. There are many GUI builders for python. (Have to deal with the licensing issues.) Qt has a GUI builder. Glade (GTK+) for python is also good. Boa constructor is also nice. From kkylheku at gmail.com Mon Aug 17 02:42:01 2009 From: kkylheku at gmail.com (Kaz Kylheku) Date: Mon, 17 Aug 2009 06:42:01 +0000 (UTC) Subject: Xah's Edu Corner: The importance of syntax & notations. References: <4a882e2d$0$9897$80265adb@spool.cs.wisc.edu> <4f0af709-527a-47db-8a8a-b0b42c6fe34d@d32g2000yqh.googlegroups.com> <4a88e924$0$9895$80265adb@spool.cs.wisc.edu> <4a88ed24$0$9896$80265adb@spool.cs.wisc.edu> Message-ID: <20090826140229.540@gmail.com> ["Followup-To:" header set to comp.lang.lisp.] On 2009-08-17, Peter Keller wrote: > In comp.lang.scheme Peter Keller wrote: >> The distance() function in this new model is the centroid of the syntactic >> datum which represent the semantic object. > > Oops. > > I meant to say: > > "The distance() function in this new model uses the centroid of each > individual syntactic datum (which represents the semantic object) as > the location for each semantic object." Don't sweat it; either way it makes no sense. The rewrite does have a more journal-publishable feel to it, though: the centroid of the whole aromatic diffusion seems to hover more precisely above the site of the bovine waste from which it apparently emanates. From xahlee at gmail.com Mon Aug 17 02:50:27 2009 From: xahlee at gmail.com (Xah Lee) Date: Sun, 16 Aug 2009 23:50:27 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: On Aug 12, 12:15 pm, Raymond Hettinger wrote: > [Xah Lee] > > > i've wrote several articles about this issue, total time spend on this > > is probably more than 2 months full-time work. See: > > > ? Python Documentation Problems > > http://xahlee.org/perl-python/python_doc_index.html > > I just read you post. You did devote a substantial amount of time > to the project. Some of your criticisms are valid. Wish you had > posted patches, I think many of them would have been accepted. > > Since you wrote this a few years ago, many examples have > been added to the docs and more are forthcoming. > > > I often receive thank you emails for 2 particular articles, which are > > most frequently google searched as indicated by my weblog: > > > ? Python Doc Problem Example: gzip > > http://xahlee.org/perl-python/python_doc_gzip.html > > > ? Python Doc Problem Example: sort() > > http://xahlee.org/perl-python/python_doc_sort.html > > > ? Sorting in Python and Perl > > http://xahlee.org/perl-python/sort_list.html > > Some are the criticisms are valid; others seem off-base. > > Here are a few thoughts on list.sort() for those who are interested: > > * The key= and reversed= parameters are not intended for special > cases, leaving cmp= for the general case. They were intended to > be full replacements. In Python3.x, the cmp function is gone. > > * The interaction of the key= and cmp= functions can be made to > interact (the key function is first applied to every element and > the cmp function then gets applied to the results of the key > function). This isn't a normal or intended use case, so the docs > don't delve into the subject. > > * The reversed parameter does more than list.sort() followed by > list.reverse(). It also preserves stability in the event of equal > keys: > > >>> sorted([(1,2), (1,3)], key=itemgetter(0), reverse=True) > [(1,2), (1,3)] > > So it was not correct to say that the following are equivalent: > > li.sort(lambda x, y: cmp(x[1],y[1]), reverse=True) > li.sort(lambda x, y: cmp(y[1],x[1])) > > * We should link the sorted() and list.sort() docs to the > sorting how-to (with a fuller discussion on the art of sorting > including a discussion of operator.itemgetter() and > operator.attrgetter() which were designed to work with the key= > parameter. > > Here are a few thoughts on list.sort() for those who are interested: > > After one more reading of Xah Lee's posts on the documentation for > sort, > here are couple more thoughts: > > * The reason that list.sort() allows None for the cmp parameter is not > so that you can write list.sort(None). It was put there to make it > easier for people writing function definitions where the cmp function > is a possible argument: > > def sort_and_chop(seq, maxlen, cmp=None): > s = seq[:] > s.sort(cmp) # needs to accept None as a possible > argument > return s[:maxlen] > > * The reason for implementing the key= parameter had nothing to do > with limitations of Python's compiler. Instead, it was inspired by > the > decorate-sort-undecorate pattern. Hi Raymond, thanks for the many points. They are informative, some i disagree, but it's getting into detail. I don't know python 3.0, will have to look into its sort in the future. This part i don't particular agree: > * The reason for implementing the key= parameter had nothing to do > with limitations of Python's compiler. Instead, it was inspired by > the > decorate-sort-undecorate pattern. The decorate-sort-undecorate pattern is a compiler limitation, for most of today's langs. I'm not sure, but i think some of the fancy functional langs automatically detect such and optimize it away, to various degrees. ... my criticism is usually written in a style catered to irritate a particular class of coder i call tech geekers (they think of themselfs with their idiotic term ?hackers?). So, parts are exaggerated. It'd be more clear to say, that the reason for python's ?key?, and as a ?solution? or need of the decorate-sort-undecorate issue, can be attributed to the current state of the art of popular imperative language's compilers (induced by such lang's semantics). again, i haven't studied python 3.0 to see what it has changed with sort, and thanks for the informative post. I find it intriguing that it doesn't have ?cmp? anymore as you say.... maybe when i actually study it and i'll come away with rage and rants. LOL. Xah ? http://xahlee.org/ ? From contact at xavierho.com Mon Aug 17 03:09:14 2009 From: contact at xavierho.com (Xavier Ho) Date: Mon, 17 Aug 2009 17:09:14 +1000 Subject: What happened to __cmp__() in Python 3.x? In-Reply-To: References: <2d56febf0908150509k1b6a3b98j7e76ae6596108280@mail.gmail.com> <50697b2c0908160104k7d74ace9jda8f4b927402942@mail.gmail.com> <2d56febf0908160458k3b5197d8tf1a69e3083ab3146@mail.gmail.com> Message-ID: <2d56febf0908170009i7ce4f53tb89ffde60d09a2bc@mail.gmail.com> On Sun, Aug 16, 2009 at 10:33 PM, Mark Lawrence wrote: > > I wasn't discussing __cmp__, I was referring to the quote by Chris Rebert > from the Python docs regarding the rich comparison methods, a discrepancy > between the documentation and the implementation as noted in the link that I > gave, and an indication that the issue raised on this discrepancy is still > open. As Terry Reedy has mentioned __lt__ elsewhere, you should be aware of > the discrepancy, otherwise you could go charging off down the wrong track. > FWIW it was Terry who raised the issue 4395, I'm sure that he could explain > the ramifications of it all far better than I ever could, so I'll sign out. Oh, I see. Thanks for informing then. =) Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From sleepy at cabbage.co.uk Mon Aug 17 03:23:55 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Mon, 17 Aug 2009 07:23:55 GMT Subject: get the pause status from amarok 2.1 References: <7eku4bF2gtku3U2@mid.uni-berlin.de> <3avhm.248709$bA.165466@newsfe16.ams2> Message-ID: On Sat, 15 Aug 2009 09:25:19 +0000, Sleepy Cabbage wrote: > On Fri, 14 Aug 2009 12:55:07 +0200, Diez B. Roggisch wrote: > >> Sleepy Cabbage schrieb: >>> As the title says, I'm trying to find a way to get the pause status >>> from amarok 2.1. >>> >>> I'm running kubuntu 9.04 with kde 4.2.2, python 2.6.2. >>> >>> Thanks in advance. >> >> Not at my linux-system right now, but dcop and the respective >> python-module should help. >> >> Diez > > Thanks for you reply Diez. i'm sure that kde4.2 now uses qdbus instead > of dcop and not sure whether amarok has the qdbus org.kde.amarok /Player > GetStatus as it returns the following: qdbus: I don't know how to > display an argument of type '(iiii)' 'dbus --literal org.kde.amarok /Player org.freedesktop.MediaPlayer.GetStatus' From sleepy at cabbage.co.uk Mon Aug 17 03:25:22 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Mon, 17 Aug 2009 07:25:22 GMT Subject: get the pause status from amarok 2.1 References: <7eku4bF2gtku3U2@mid.uni-berlin.de> <3avhm.248709$bA.165466@newsfe16.ams2> Message-ID: On Mon, 17 Aug 2009 07:23:55 +0000, Sleepy Cabbage wrote: > On Sat, 15 Aug 2009 09:25:19 +0000, Sleepy Cabbage wrote: > >> On Fri, 14 Aug 2009 12:55:07 +0200, Diez B. Roggisch wrote: >> >>> Sleepy Cabbage schrieb: >>>> As the title says, I'm trying to find a way to get the pause status >>>> from amarok 2.1. >>>> >>>> I'm running kubuntu 9.04 with kde 4.2.2, python 2.6.2. >>>> >>>> Thanks in advance. >>> >>> Not at my linux-system right now, but dcop and the respective >>> python-module should help. >>> >>> Diez >> >> Thanks for you reply Diez. i'm sure that kde4.2 now uses qdbus instead >> of dcop and not sure whether amarok has the qdbus org.kde.amarok >> /Player GetStatus as it returns the following: qdbus: I don't know how >> to display an argument of type '(iiii)' > > 'dbus --literal org.kde.amarok /Player > org.freedesktop.MediaPlayer.GetStatus' Ref my last post: This works!! From xahlee at gmail.com Mon Aug 17 03:25:24 2009 From: xahlee at gmail.com (Xah Lee) Date: Mon, 17 Aug 2009 00:25:24 -0700 (PDT) Subject: python doc available in emacs info format? References: Message-ID: <4aba0b60-0aff-419a-877a-cac1e0e448ee@j21g2000yqe.googlegroups.com> info format for Xah Lee writes: > in programing elisp in emacs, i can press ?Ctrl+h f? to lookup > the doc for the function under cursor. is there such facility > when coding in perl, python, php? On Dec 11 2008, 6:56 am, Matthias wrote: > Yes, try C-h S (or similarly S): > (info-lookup-symbol SYMBOL &optional MODE) Display the > definition of SYMBOL, as found in the relevant manual. When this > command is called interactively, it reads SYMBOL from the > minibuffer. > Note that `the relevant manual' means an info file. With recent > emacsen on an Ubuntu distro, python arrives with info files and > everything is well configured. It also works with bash, latex, perl, > scheme, elisp, awk, texinfo, makefile, libc, or any info file with an > index. I noticed that Matthias actually mentioned that info docs is available and bundled out of the box on Ubuntu linux for many popular langs, as of 2008-12. Is that true? Where can i download these info files? As far as i know, a little google search or official doc sites usually don't have a download for info format. I'm interested in getting current version doc for perl, python, php, and ruby. Thanks. Xah ? http://xahlee.org/ ? From sjoerd at acm.org Mon Aug 17 04:29:17 2009 From: sjoerd at acm.org (Sjoerd Mullender) Date: Mon, 17 Aug 2009 10:29:17 +0200 Subject: zip codes In-Reply-To: References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> Message-ID: <4A8914DD.4000307@acm.org> Martin P. Hellwig wrote: > Shailen wrote: >> Is there any Python module that helps with US and foreign zip-code >> lookups? I'm thinking of something that provides basic mappings of zip >> to cities, city to zips, etc. Since this kind of information is so >> often used for basic user-registration, I'm assuming functionality of >> this sort must be available for Python. Any suggestions will be much >> appreciated. >> > There might be an associated can of worms here, for example in the > Netherlands zip codes are actually copyrighted and require a license if > you want to do something with them, on the other hand you get a nice SQL > formatted db to use it. I don't know how this works in other countries > but I imagine that it is likely to be generally the same. > Also in The Netherlands, ZIP codes are much more fine-grained than in some other countries: ZIP code plus house number together are sufficient to uniquely identify an address. I.e. you don't need the street name. E.g., my work address has ZIP code 1098 XG and house number 123, so together they indicate that I work at Science Park 123, Amsterdam. In other words, a simple city <-> ZIP mapping is not sufficient. -- Sjoerd Mullender -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 379 bytes Desc: OpenPGP digital signature URL: From hendrik at microcorp.co.za Mon Aug 17 05:36:18 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 17 Aug 2009 11:36:18 +0200 Subject: Is it possible to use python to get True Full Duplex on a Serial port? In-Reply-To: References: Message-ID: <200908171136.18188.hendrik@microcorp.co.za> On Sunday 16 August 2009 15:55:31 Grant Edwards wrote: > On 2009-08-15, Hendrik van Rooyen wrote: > > I am still confused about pyserial and serial - I found serial > > in my distribution library, (on the SuSe machine, not on the > > 2.5 in Slackware) but I had to download pyserial. > > That's very interesting. Is the pre-existing "serial" a > version of pyserial that the packager had pre-installed or is > it something else? I didn't know any distributions shipped I am not too sure now - when I looked in the packages directory over the weekend it was there. But I am really not sure how it got there - I cannot recall downloading it myself, but that means nothing as I have been using this machine for a while now, so it is possible that I did it some time ago and forgotten about it, without ever using it. Possible, but unlikely. I would like to think that if I downloaded it, I would have tried it, and then I would have remembered. Sorry to be so vague. Does this help? hvr at Linuxbox:~> python Python 2.5.1 (r251:54863, Dec 6 2008, 10:49:39) [GCC 4.2.1 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import serial >>> dir(serial) ['EIGHTBITS', 'FCNTL', 'FIVEBITS', 'FileLike', 'PARITY_EVEN', 'PARITY_NAMES', 'PARITY_NONE', 'PARITY_ODD', 'SEVENBITS', 'SIXBITS', 'STOPBITS_ONE', 'STOPBITS_TWO', 'Serial', 'SerialBase', 'SerialException', 'SerialTimeoutException', 'TERMIOS', 'TIOCINQ', 'TIOCMBIC', 'TIOCMBIS', 'TIOCMGET', 'TIOCMSET', 'TIOCM_CAR', 'TIOCM_CD', 'TIOCM_CTS', 'TIOCM_DSR', 'TIOCM_DTR', 'TIOCM_DTR_str', 'TIOCM_RI', 'TIOCM_RNG', 'TIOCM_RTS', 'TIOCM_RTS_str', 'TIOCM_zero_str', 'VERSION', 'XOFF', 'XON', '__builtins__', '__doc__', '__file__', '__name__', '__path__', 'device', 'errno', 'fcntl', 'os', 'plat', 'portNotOpenError', 'select', 'serialposix', 'serialutil', 'string', 'struct', 'sys', 'termios', 'writeTimeoutError'] >>> serial.VERSION '1.27' - Hendrik From fas at cs.stir.ac.uk Mon Aug 17 05:38:15 2009 From: fas at cs.stir.ac.uk (Farhan Sheikh) Date: Mon, 17 Aug 2009 10:38:15 +0100 Subject: Uninstalling mac python2.5 to install python2.6 Message-ID: <83423F73-83DA-436B-A3BA-E83CD61CD28D@cs.stir.ac.uk> Dear all, i originally had python2.5 on my mac at the univeristy and had to get 2.6 to get NEST and pyNN to work together. however now as those are now installed, i had to install numpy. As i installed numpy, it only installed its directories into the python2.5 folders and as i am new to to mac terminals i don't know how to change its directories to be installed into python2.6. my question is, do i have to uninstall python 2.5 so that only python2.6 is on the machine or is there a way to change the path so it saves into python2.5? Thanking You Farhan -- Academic Excellence at the Heart of Scotland. The University of Stirling is a charity registered in Scotland, number SC 011159. From xahlee at gmail.com Mon Aug 17 05:42:42 2009 From: xahlee at gmail.com (Xah Lee) Date: Mon, 17 Aug 2009 02:42:42 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. References: <25203724-bf60-484f-9ede-e61c45f15e33@s31g2000yqs.googlegroups.com> Message-ID: 2009-08-17 On Aug 16, 10:32 pm, Xah Lee wrote: > Personally, particular interesting info i've learned is that, for all > my trouble in the past decade expressing problems of traditional math > notation, i learned from his article this single-phrase summary: > ?traditional math notation lacks a grammar?. > The article is somewhat disappointing though. I was expecting he'd go > into some details about the science of math notations, or, as he put > it aptly: ?linguistics of math notations?. However, he didn't touch > the subject, except saying that it haven't been studied. upon a more detailed reading of Stephen's article, i discovered some errors. On this page: http://www.stephenwolfram.com/publications/recent/mathml/mathml2.html he mentions the Plimpton 322 tablet. It is widely taught in math history books, that this table is pythagorean triples. On reading his article, i wanted to refresh my understanding of the subject, so i looked up Wikipedia: http://en.wikipedia.org/wiki/Plimpton_322 and behold! apparantly, in recent academic publications, it is suggested that this is not pythagorean triples, but rather: ?a list of regular reciprocal pairs?. Xah ? http://xahlee.org/ ? On Aug 15, 10:54 pm, Xah Lee wrote: > Xah's Edu Corner: The importance of syntax & notations. >http://www.stephenwolfram.com/publications/recent/mathml/mathml_abstr... > this article should teach the coding sophomorons and computer > ?science? idiotic authors who harbor the notion that syntax is not > important, picked up by all the elite i-reddit & twittering & hacker > news am-hip dunces. > Further readings: > ? The TeX Pestilence > http://xahlee.org/cmaci/notation/TeX_pestilence.html > ? A Notation for Plane Geometry > http://xahlee.org/cmaci/notation/plane_geometry_notation.html > ? The Concepts and Confusions of Prefix, Infix, Postfix and Fully > Nested Notations > http://xahlee.org/UnixResource_dir/writ/notations.html > ? The Problems of Traditional Math Notation > http://xahlee.org/cmaci/notation/trad_math_notation.html From pierre.gaillard at gmail.com Mon Aug 17 05:50:03 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Mon, 17 Aug 2009 02:50:03 -0700 (PDT) Subject: sub-list extraction, logical indexation Message-ID: Hello Everyone, I would like to know if it is possible to extract a sub-list from a list ? typically if : L =[[1, 2, 3],[4, 5, 6],[3] ] How to extract easily the elements 0 and 2 of L in order to get : L2 =[[1, 2, 3],[3] ] Moreover, I would like to know if it is possible to use logical indexation such that : index = [ True, False, True] L2 = L or usual indexation, something like index=[0, 2] L2 = L I tried, but failed... Thanks for your help Pierre From indermeet.gandhi at gmail.com Mon Aug 17 05:55:37 2009 From: indermeet.gandhi at gmail.com (inder) Date: Mon, 17 Aug 2009 02:55:37 -0700 (PDT) Subject: XML parsing with python Message-ID: Hi All, I am new to xml . I need to parse the xml file . After reading and browsing on the web , I could get much help . I guess SAX would be better suited for my requirement . Could some juct provide me a sample python code so that I can execute it and see how the parsing actually happens . Lets say my xml file - GLADE xwPython --> wxFormBuilder PyQt --> QtDesigner From exarkun at twistedmatrix.com Mon Aug 17 07:43:15 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 17 Aug 2009 11:43:15 -0000 Subject: Python 'for' loop is memory inefficient In-Reply-To: <900c0d5e-a41a-4820-9844-816afa1a33c9@g10g2000yqh.googlegroups.com> References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <900c0d5e-a41a-4820-9844-816afa1a33c9@g10g2000yqh.googlegroups.com> Message-ID: <20090817114315.8740.284099123.divmod.xquotient.27@localhost.localdomain> On 01:53 am, pavlovevidence at gmail.com wrote: >On Aug 16, 6:28?pm, exar... at twistedmatrix.com wrote: >>On 01:23 am, benjamin.kap... at case.edu wrote: >> >> >On Sun, Aug 16, 2009 at 6:35 PM, sturlamolden >> >wrote: >> >> >>A compiler could easily recognise a statement like >> >> >>? for i in range(n): >> >> >>as a simple integer loop. In fact, Cython is able to do this. >> >> >but special cases aren't special enough to break the rules. >> >>Although I think PyPy also recognizes this case and makes it as >>efficient as using xrange, and does so without breaking any rules. > >PyPy uses a JIT compiler (which is still slower than CPython, >suggesting that perhaps they should have spent more time optimizing >the general case than optimizing for an easily avoided special case). It's true that PyPy has a JIT compiler (which is still slower than CPython). However, this isn't where the range speedup comes from. The range optimization is handled specifically in the implementation of range (or possibly of list, or a combination of the two, I can't remember exactly). It's effective even when the JIT compiler is disabled. > >>There *are* _some_ legitimate complaints to be made about the CPython >>runtime. :) > >This isn't one of them. > >xrange has been part of Python for 10 years. > >If there are any complaints to be made about this situation it's that >there are any 2.x learning materials anythere that continue to use >range() and not xrange() in this context. Jean-Paul From exarkun at twistedmatrix.com Mon Aug 17 07:44:35 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 17 Aug 2009 11:44:35 -0000 Subject: Python 'for' loop is memory inefficient In-Reply-To: <7xtz079ptq.fsf@ruckus.brouhaha.com> References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <7xtz079ptq.fsf@ruckus.brouhaha.com> Message-ID: <20090817114435.8740.1376128107.divmod.xquotient.30@localhost.localdomain> On 01:44 am, http wrote: >exarkun at twistedmatrix.com writes: >>Although I think PyPy also recognizes this case and makes it as >>efficient as using xrange, and does so without breaking any rules. > >How can pypy possibly know that the user hasn't assigned some other >value to "range"? It doesn't really need to. The optimization isn't applied when the compiler sees the name "range" being called. It's applied after the object the default builtin name "range" is bound to is called. Jean-Paul From vlastimil.brom at gmail.com Mon Aug 17 07:58:40 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Mon, 17 Aug 2009 13:58:40 +0200 Subject: sub-list extraction, logical indexation In-Reply-To: <4A893263.2000706@mrabarnett.plus.com> References: <7esoqbF2gnhrcU1@mid.uni-berlin.de> <4A893263.2000706@mrabarnett.plus.com> Message-ID: <9fdb569a0908170458v167d57obf8517704f6e8dc@mail.gmail.com> 2009/8/17 MRAB : > Diez B. Roggisch wrote: >> >> Pierre wrote: >> >>> Hello Everyone, >>> >>> I would like to know if it is possible to extract a sub-list from a >>> list ? >>> >>> typically if : >>> >>> L =[[1, 2, 3],[4, 5, 6],[3] ] >>> >>> How to extract easily the elements 0 and 2 of L in order to get : >>> >>> L2 =[[1, 2, 3],[3] ] >>> >>> Moreover, I would like to know if it is possible to use logical >>> indexation such that : >>> >>> index = [ True, False, True] >>> L2 = L >>> >>> or usual indexation, something like >>> index=[0, 2] >>> L2 = L >>> >>> I tried, but failed... >>> Thanks for your help >> >> >> index = [ True, False, True] >> L2 = [v for i, v in enumerate(L) if index[i]] >> > Or: > > L =[[1, 2, 3],[4, 5, 6],[3] ] > index = [ True, False, True] > > from itertools import izip > L2 = [v for i, v in izip(index, L) if i] > Or in python 3.1 >>> import itertools >>> list(itertools.compress(data=[[1, 2, 3], [4, 5, 6], [3]], selectors=[True, False, True])) [[1, 2, 3], [3]] vbr From dmhouse at gmail.com Mon Aug 17 08:23:47 2009 From: dmhouse at gmail.com (David House) Date: Mon, 17 Aug 2009 13:23:47 +0100 Subject: ignored test cases in unittest In-Reply-To: <56527679-4cec-49a1-9b46-c38de8f981c8@g10g2000yqh.googlegroups.com> References: <873a7so66v.fsf@benfinney.id.au> <56527679-4cec-49a1-9b46-c38de8f981c8@g10g2000yqh.googlegroups.com> Message-ID: 2009/8/16 Terry : > Thanks for the solutions. I think the decorator idea is what I'm look > for:-) Note that the unittest module now supports the `skip' and `expectedFailure' decorators, which seem to describe some of the solutions here. See http://docs.python.org/3.1/library/unittest.html#skipping-tests-and-expected-failures -- -David From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 17 08:33:22 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 17 Aug 2009 14:33:22 +0200 Subject: callable virtual method In-Reply-To: References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4a894e11$0$22902$426a74cc@news.free.fr> Jean-Michel Pichavant a ?crit : (snip) > Sometimes the base is doing cool stuff but incomplete stuff which > requires knowledge only hold by the sub class. In my case the interface > is a high level interface for a software that can run on multiple > hardware platforms. Only the sub class has knowledge on how to operate > the hardware, but no matter the hardware it still produces the same effect. > > Let's say I have 50 different hardwares, I'll have 50 sub classes of > Interface with the 'start' method to define. It wouldn't be appropriate > (OO programming)to write 50 times '_log.debug('Starting %s' % self)' in > each child start method when the simple task of logging the call can be > nicely handled by the base class. Which is exactly one of the use cases for the Template Method pattern in traditional OO design. For the record, Python can offer other solutions to this kind of problem - like a combination of decorators and metaclasses. > In the meantime, I must make sure the user, who is not a python guru in > this case, has implemented the start method for his hardware, whether he has to implement the 'start' or '_start' method doesn't make any difference here. From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 17 08:35:19 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 17 Aug 2009 14:35:19 +0200 Subject: callable virtual method In-Reply-To: References: <4A85798B.6020501@sequans.com> <4A8587A0.6040008@mrabarnett.plus.com> <02959b54$0$20647$c3e8da3@news.astraweb.com> Message-ID: <4a894e85$0$22902$426a74cc@news.free.fr> Jean-Michel Pichavant a ?crit : > Scott David Daniels wrote: (snip) >> But there _is_ one moment when you can check those things, then avoid >> checking thereafter: object creation. So you can complicate your >> __init__ (or __new__) with those checks that make sure you instantiate >> only fully defined subclasses: That's something I'd rather do in a custom metaclass. But YMMV, of course... From sturlamolden at yahoo.no Mon Aug 17 08:37:29 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 17 Aug 2009 05:37:29 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> Message-ID: <60535b0d-dac1-4f4b-a464-eb05a2b3c0a3@h31g2000yqd.googlegroups.com> On 16 Aug, 19:12, Carl Banks wrote: > If you don't care about the dynamic stuff why don't you just use > Cython? ?Or quit complaining and just use xrange. I think you are the only one complaining here. From python at mrabarnett.plus.com Mon Aug 17 09:01:19 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 17 Aug 2009 14:01:19 +0100 Subject: Python 'for' loop is memory inefficient In-Reply-To: <20090817114036.8740.394539460.divmod.xquotient.22@localhost.localdomain> References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> <20090817114036.8740.394539460.divmod.xquotient.22@localhost.localdomain> Message-ID: <4A89549F.6050004@mrabarnett.plus.com> exarkun at twistedmatrix.com wrote: > On 02:12 am, pavlovevidence at gmail.com wrote: >> On Aug 16, 3:35?pm, sturlamolden wrote: >>> On 16 Aug, 14:57, Dennis Lee Bieber wrote: >>> >>> > ? ? ? ? Well, the alternative would be to have two keywords for >>> looping: one >>> > for your "simple" incrementing integer loop, and another for a loop >>> that >>> > operates over the elements of some collection type. >>> >>> A compiler could easily recognise a statement like >>> >>> ? ?for i in range(n): >>> >>> as a simple integer loop. >> >> It would be a simple to do if you were writing it for a different >> langauge was a lot less dynamic than Python is. It'd be quite a >> complex hack to add it to CPython's compiler while maintaing the >> current highly dynamic runtime semantics and backwards compatibility, >> which is a design constraint of Python whether you like it or not. > > In your other message, you said this wasn't a legitimate CPython > complaint. Here, you say that it would be a "complex hack" to implement > this in CPython. "complex hack" has negative connotations in my mind. > This seems contradictory to me. >> >> And all this complaining about an issue that can be worked around by >> xrange instead of range. Sheesh. > > Sure. The specific issue of range vs xrange is quite a small one. There > is a slightly larger one regarding the flexibility (or relative lack > thereof) of the CPython runtime, though. > A possible solution would be to make 'range' return an instance of, say, 'RangeList', a subclass of list which would behave like 'list' externally but create the list of values internally only when needed. From steven.oldner at gmail.com Mon Aug 17 09:03:52 2009 From: steven.oldner at gmail.com (steven.oldner) Date: Mon, 17 Aug 2009 06:03:52 -0700 (PDT) Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> <4A8914DD.4000307@acm.org> Message-ID: <15819238-2a87-47e4-8d5f-1f1714d2dd8c@r38g2000yqn.googlegroups.com> On Aug 17, 5:21?am, MRAB wrote: > Sjoerd Mullender wrote: > > Martin P. Hellwig wrote: > >> Shailen wrote: > >>> Is there any Python module that helps with US and foreign zip-code > >>> lookups? I'm thinking of something that provides basic mappings of zip > >>> to cities, city to zips, etc. Since this kind of information is so > >>> often used for basic user-registration, I'm assuming functionality of > >>> this sort must be available for Python. Any suggestions will be much > >>> appreciated. > > >> There might be an associated can of worms here, for example in the > >> Netherlands zip codes are actually copyrighted and require a license if > >> you want to do something with them, on the other hand you get a nice SQL > >> formatted db to use it. I don't know how this works in other countries > >> but I imagine that it is likely to be generally the same. > > > Also in The Netherlands, ZIP codes are much more fine-grained than in > > some other countries: ZIP code plus house number together are sufficient > > to uniquely identify an address. ?I.e. you don't need the street name. > > E.g., my work address has ZIP code 1098 XG and house number 123, so > > together they indicate that I work at Science Park 123, Amsterdam. > > > In other words, a simple city <-> ZIP mapping is not sufficient. > > The same comment applies to UK postcodes, which are also alphanumeric. > My home postcode, for example, is shared with only 3 other houses, IIRC.- Hide quoted text - > > - Show quoted text - Google for Zip codes. There are some free databases of codes, but they are dated. USPS and 3 party vendors sell zip code databases and lists. The USPS APIs are a joke. They were going to charge me for using them. I ended up using a 2 year old database of ZIP codes for my needs. Hope this helps! From luke.leighton at googlemail.com Mon Aug 17 09:03:57 2009 From: luke.leighton at googlemail.com (lkcl) Date: Mon, 17 Aug 2009 06:03:57 -0700 (PDT) Subject: platform-specific overrides of functions and class methods (expanding on imputils demo code) References: Message-ID: <77715735-2668-43e7-95da-c91d175b35c9@z31g2000yqd.googlegroups.com> thought that people might like to know: i found also that imputil, the standard python module, was lacking the necessary complexity in being a substitute for the standard __import__ function. the additions required were very simple: # note the addition of level=-1 which is ignored def _import_hook(self, fqname, globals=None, locals=None, fromlist=None, level=-1): ..... # Grrr, some people "import os.path" or do "from os.path import ..." if len(parts) == 2 and hasattr(top_module, parts[1]): if fromlist: return getattr(top_module, parts[1]) else: return top_module # assume that the module has already been imported, # walk from top_module to find it. mod = top_module for k in parts[1:]: if not hasattr(mod, k): print "no mod", mod, k, parts mod = None break mod = getattr(mod, k) if mod: return mod # If the importer does not exist, then we have to bail. A missing # importer means that something else imported the module, and we have # no knowledge of how to get sub-modules out of the thing. raise ImportError, 'No module named ' + fqname it's the module-walking that's been added: going from the "top" module, looking for an attribute of the split-parts. this code makes the assumption that if top module already exists, and it has a sub- module, and that has a sub-sub-module, and that has a sub-sub-sub- module etc. then it is perfectly reasonable to return that pre- existing, already-imported [sub-]+ module as the return result. the reason why this had to be added is because comtypes.gen.{some module} auto-generator relies on it, and calls __import__ *direct*. if somebody would like to add this to the python bugtracker, as a contribution, that would be great. alternatively, you might like to have a word with the python developers to get them to remove the censorship on my contributions. l. From stefan_ml at behnel.de Mon Aug 17 09:20:31 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 17 Aug 2009 15:20:31 +0200 Subject: Python 'for' loop is memory inefficient In-Reply-To: <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> Message-ID: <4a895920$0$32674$9b4e6d93@newsspool2.arcor-online.net> Carl Banks wrote: > On Aug 16, 3:35 pm, sturlamolden wrote: >> On 16 Aug, 14:57, Dennis Lee Bieber wrote: >> >>> Well, the alternative would be to have two keywords for looping: one >>> for your "simple" incrementing integer loop, and another for a loop that >>> operates over the elements of some collection type. >> A compiler could easily recognise a statement like >> >> for i in range(n): >> >> as a simple integer loop. >> >> In fact, Cython is able to do this. > > Cython can do this easily because it is a different language that is a > lot less dynamic than Python. Actually, Cython is able to do this because it knows the global scope of a module. The only thing that this optimisation makes impossible when you compile your module using Cython is to inject builtins into the module namespace *after* the compilation, either by assigning module attributes or by importing the module into a custom namespace. Given that both use cases are extremely rare, it was decided that optimisations like this are more important than the ability to redefine the most common builtins (such as 'range' or 'enumerate'). So, in a way, Cython really makes them "builtins". Stefan From steve at REMOVE-THIS-cybersource.com.au Mon Aug 17 09:23:14 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 17 Aug 2009 13:23:14 GMT Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: <0012dd1f$0$2904$c3e8da3@news.astraweb.com> On Sun, 16 Aug 2009 15:35:26 -0700, sturlamolden wrote: > On 16 Aug, 14:57, Dennis Lee Bieber wrote: > >> ? ? ? ? Well, the alternative would be to have two keywords for >> ? ? ? ? looping: one >> for your "simple" incrementing integer loop, and another for a loop >> that operates over the elements of some collection type. > > A compiler could easily recognise a statement like > > for i in range(n): > > as a simple integer loop. "Easily" huh? Would you like to put a small wager on that? Here is an unedited copy-and-paste of the last few lines of an interactive Python session: >>> for i in range(5): ... print i ... 0 1 2 Surprise! 4 >>> __builtins__.range is range True Can you determine how I did this? How would the compiler avoid this? If you can find a method for the compiler to avoid surprises like this, why do you think it would be valuable to add all that extra complexity to the language? (As opposed to an external tool like Cython.) -- Steven From stefan_ml at behnel.de Mon Aug 17 09:24:17 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 17 Aug 2009 15:24:17 +0200 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> Message-ID: <4a895a01$0$32674$9b4e6d93@newsspool2.arcor-online.net> John Machin wrote: > On Aug 17, 8:35 am, sturlamolden wrote: > >> A compiler could easily recognise a statement like >> for i in range(n): >> as a simple integer loop. In fact, Cython is able to do this. > > Extremely easy, once users relinquish the right to replace built-in > "range" with their own concoctions ... Cython allows you to do that. You just have to do it inside the module. If Cython determines that "range" refers the global builtin name, it will enable the loop optimisation. If you assign anything to that global name inside your module (even the range function itself), this will disable the optimisation. Stefan From terry.yinzhe at gmail.com Mon Aug 17 09:38:48 2009 From: terry.yinzhe at gmail.com (Terry Yin) Date: Mon, 17 Aug 2009 21:38:48 +0800 Subject: ignored test cases in unittest In-Reply-To: References: <873a7so66v.fsf@benfinney.id.au> <56527679-4cec-49a1-9b46-c38de8f981c8@g10g2000yqh.googlegroups.com> Message-ID: On Aug 17, 8:23 pm, David House wrote: > > Note that the unittest module now supports the `skip' and > `expectedFailure' decorators, which seem to describe some of the > solutions here. > > Seehttp:// docs.python.org/3.1/library/unittest.html#skipping-tests-and-e... > > -- > -David Yes, indeed! I'm using 2.6 now. It seemed I need to copy untitest.py from 3.1. But the docs.python.org is hell slow from where I am (China), not even working except the title:-( br, Terry On Mon, Aug 17, 2009 at 8:23 PM, David House wrote: > 2009/8/16 Terry : > > Thanks for the solutions. I think the decorator idea is what I'm look > > for:-) > > Note that the unittest module now supports the `skip' and > `expectedFailure' decorators, which seem to describe some of the > solutions here. > > See > http://docs.python.org/3.1/library/unittest.html#skipping-tests-and-expected-failures > > -- > -David > -- ------------------------- Blog: http://terry-yinzhe.spaces.live.com/ twitter: http://twitter.com/terryyin -------------- next part -------------- An HTML attachment was scrubbed... URL: From drobinow at gmail.com Mon Aug 17 10:04:14 2009 From: drobinow at gmail.com (David Robinow) Date: Mon, 17 Aug 2009 10:04:14 -0400 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <24980842.post@talk.nabble.com> <4A8612CE.7080700@stoneleaf.us> <200908160830.55031.emmanuel.surleau@gmail.com> Message-ID: <4eb0089f0908170704y664a3031ufed176ada36cc2c@mail.gmail.com> On Sun, Aug 16, 2009 at 11:10 PM, Nobody wrote: > Java also has iterators; it's more a case of people coming from C and BASIC. > > Although, some of those may have come *through* Java without abandoning > old habits. You see the same thing with people coming from BASIC to C and > writing: > > ? ? ? ?#define NUM_DATES 50 > ? ? ? ?int day[NUM_DATES], month[NUM_DATES], year[NUM_DATES]; > > rather than defining a "struct". > > Sometimes referred to as "I know ten languages and can write in BASIC in > all of them". Ha, ha. I learned that pattern in Fortran. I confess to having written code like that in C. I think I've gotten over it. From invalid at invalid Mon Aug 17 10:04:42 2009 From: invalid at invalid (Grant Edwards) Date: Mon, 17 Aug 2009 09:04:42 -0500 Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> Message-ID: On 2009-08-17, Sjoerd Mullender wrote: > Also in The Netherlands, ZIP codes are much more fine-grained than in > some other countries: ZIP code plus house number together are sufficient > to uniquely identify an address. I.e. you don't need the street name. > E.g., my work address has ZIP code 1098 XG and house number 123, so > together they indicate that I work at Science Park 123, Amsterdam. > > In other words, a simple city <-> ZIP mapping is not sufficient. Same here in the US. A 5-digit zip code narrows it down to a neghborhood within a city, and a full 9-digit zip code is shared with perhaps 5-10 houses -- generally I believe it identifies one side of a one-block section of a street in a single-family-home residential area. In apartment or office buildings a 9-digit zip code generally identifies a specific floor in a specific building. Most companies of any size have their own zip code (or codes). My company only has ~40 employees, and we have our own unique zip code. -- Grant Edwards grante Yow! Here I am at the flea at market but nobody is buying visi.com my urine sample bottles ... From aaron.watters at gmail.com Mon Aug 17 10:05:21 2009 From: aaron.watters at gmail.com (Aaron Watters) Date: Mon, 17 Aug 2009 07:05:21 -0700 (PDT) Subject: off topic: google groups sucks? Message-ID: <087f64b6-0cc7-4a75-a2ba-9ca74d31f1fd@o32g2000yqm.googlegroups.com> Just a note. It seems that google groups is increasing the sucks coefficient. I search for things using "group search" for comp.lang.python and I get no results even though I know there are results from a few months or weeks ago. What is the best alternative for this kind of trawling? gmane? With all the smart people working at google how can they **** up like this? Inquiring minds want to know. -- Aaron Watters === Sisyphus got ripped. From jkn_gg at nicorp.f9.co.uk Mon Aug 17 10:46:14 2009 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: Mon, 17 Aug 2009 07:46:14 -0700 (PDT) Subject: off topic: google groups sucks? References: <087f64b6-0cc7-4a75-a2ba-9ca74d31f1fd@o32g2000yqm.googlegroups.com> Message-ID: On Aug 17, 3:05?pm, Aaron Watters wrote: > Just a note. ?It seems that google groups is increasing the > sucks coefficient. > > I search for things using "group search" for comp.lang.python > and I get no results even though I know there are results from > a few months or weeks ago. There seems to be a problem with Google Searching 'at the moment'. I have seen it with other groups, but not noticed it to date on c.l.p. http://groups.google.com/group/groupsknownissues/browse_thread/thread/d88d02f269a7d20d# J^n From chris at simplistix.co.uk Mon Aug 17 10:53:08 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 17 Aug 2009 15:53:08 +0100 Subject: httplib incredibly slow :-( In-Reply-To: References: <4A81D3CB.7080209@simplistix.co.uk> Message-ID: <4A896ED4.8000509@simplistix.co.uk> i3dmaster wrote: > Just wanted to check if you can try turning on the debug mode for > httplib and see if you can read a bit more debug info on where the > calls get hung. In your example, it would be conn.set_debuglevel(1) I had a look through the code this debug level controls and I don't see any information that this provides which would help here... Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From stefan_ml at behnel.de Mon Aug 17 11:11:10 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 17 Aug 2009 17:11:10 +0200 Subject: off topic: google groups sucks? In-Reply-To: References: <087f64b6-0cc7-4a75-a2ba-9ca74d31f1fd@o32g2000yqm.googlegroups.com> Message-ID: <4a89730e$0$32667$9b4e6d93@newsspool2.arcor-online.net> jkn wrote: > On Aug 17, 3:05 pm, Aaron Watters wrote: >> Just a note. It seems that google groups is increasing the >> sucks coefficient. >> >> I search for things using "group search" for comp.lang.python >> and I get no results even though I know there are results from >> a few months or weeks ago. > > There seems to be a problem with Google Searching 'at the moment'. I > have seen it with other groups, but not noticed it to date on c.l.p. > > http://groups.google.com/group/groupsknownissues/browse_thread/thread/d88d02f269a7d20d# I noticed a problem with Google in general this weekend, not even related to mailing lists. I can't remember getting similarly bad results from a web search for years. Even trivial queries that worked for months returned completely unrelated pages and lacked the "obvious" target page in the result set. Stefan From jjposner at optimum.net Mon Aug 17 11:31:30 2009 From: jjposner at optimum.net (John Posner) Date: Mon, 17 Aug 2009 11:31:30 -0400 Subject: XML parsing with python In-Reply-To: References: Message-ID: <4A8977D2.1020801@optimum.net> > Use the iterparse() function of the xml.etree.ElementTree package. > > http://effbot.org/zone/element-iterparse.htm > http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk > > Stefan > iterparse() is too big a hammer for this purpose, IMO. How about this: from xml.etree.ElementTree import ElementTree tree = ElementTree(None, "myfile.xml") for elem in tree.findall('//book/title'): print elem.text -John From wiggly at wiggly.org Mon Aug 17 11:42:40 2009 From: wiggly at wiggly.org (Nigel Rantor) Date: Mon, 17 Aug 2009 16:42:40 +0100 Subject: zip codes In-Reply-To: <4A892F2B.4020507@mrabarnett.plus.com> References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> <4A8914DD.4000307@acm.org> <4A892F2B.4020507@mrabarnett.plus.com> Message-ID: <4A897A70.3050100@wiggly.org> MRAB wrote: > Sjoerd Mullender wrote: >> Martin P. Hellwig wrote: >>> Shailen wrote: >>>> Is there any Python module that helps with US and foreign zip-code >>>> lookups? I'm thinking of something that provides basic mappings of zip >>>> to cities, city to zips, etc. Since this kind of information is so >>>> often used for basic user-registration, I'm assuming functionality of >>>> this sort must be available for Python. Any suggestions will be much >>>> appreciated. >>>> >>> There might be an associated can of worms here, for example in the >>> Netherlands zip codes are actually copyrighted and require a license if >>> you want to do something with them, on the other hand you get a nice SQL >>> formatted db to use it. I don't know how this works in other countries >>> but I imagine that it is likely to be generally the same. >>> >> >> Also in The Netherlands, ZIP codes are much more fine-grained than in >> some other countries: ZIP code plus house number together are sufficient >> to uniquely identify an address. I.e. you don't need the street name. >> E.g., my work address has ZIP code 1098 XG and house number 123, so >> together they indicate that I work at Science Park 123, Amsterdam. >> >> In other words, a simple city <-> ZIP mapping is not sufficient. >> > The same comment applies to UK postcodes, which are also alphanumeric. > My home postcode, for example, is shared with only 3 other houses, IIRC. Kind of off-topic...but nevertheless... Yes, the UK postcode database (PAF) can be bought from the Royal Mail for a fee. The data cannot be copyright, but the version they maintain and distribute is. As an aside, the PAF has finer grained information than simply the postal code, every letterbox in the UK has (or is meant to) a DPS (delivery point suffix), so that given a post code and DPS you can uniquely identify individual letterbox even when, for example, a house has been split into multiple flats. So, nastily, you *can* identify individual letterboxes, but the Royal Mail does not publicise the fact, so you cannot actually look at a post code on a letter and determine the letterbox it is intended for. Shame really. n From aahz at pythoncraft.com Mon Aug 17 11:44:27 2009 From: aahz at pythoncraft.com (Aahz) Date: 17 Aug 2009 08:44:27 -0700 Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: In article <461cc6f1-fc23-4bc7-a719-6f29babf8bcd at o15g2000yqm.googlegroups.com>, Robert Dailey wrote: > >It's a figure of speech. And besides, why would I want programming >advice from a woman? lol. Thanks for the help. Well, I'm sorry to see this, it means I was wrong about the lack of sexism in the Python community. I encourage anyone who wants to improve the situation to join the new diversity list: http://mail.python.org/mailman/listinfo/diversity -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From ethan at stoneleaf.us Mon Aug 17 12:24:26 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 17 Aug 2009 09:24:26 -0700 Subject: Python 'for' loop is memory inefficient In-Reply-To: <200908160830.55031.emmanuel.surleau@gmail.com> References: <24980842.post@talk.nabble.com> <4A8612CE.7080700@stoneleaf.us> <200908160830.55031.emmanuel.surleau@gmail.com> Message-ID: <4A89843A.6090308@stoneleaf.us> Emmanuel Surleau wrote: >>Dr. Phillip M. Feldman wrote: > > > [snip] > > >>>def is_prime(n): >>> for j in range(2,n): >>> if (n % j) == 0: return False >>> return True >>> >>>It seems as though Python is actually expanding range(2,n) into a list of >>>numbers, even though this is incredibly wasteful of memory. There should >>>be a looping mechanism that generates the index variable values >>>incrementally as they are needed. >> [snip] >> >>I will also observe that if you were to stop programming whatever >>language you are more familiar with in Python, and start programming >>Python in Python, you'll have an easier time of it. > > > I don't see what's particularly un-Pythonic with this code. Not using xrange() > is a mistake, certainly, but it remains clear, easily understandable code > which correctly demonstrates the naive algorithm for detecting whether n is a > prime. It doesn't call for condescension > [snip] > > Cheers, > > Emm My comment about programming Python in Python was geared more towards the subject line than the actual code, and the biases evident in his comments in both this thread and earlier ones. ~Ethan~ From invalid at invalid Mon Aug 17 12:32:08 2009 From: invalid at invalid (Grant Edwards) Date: Mon, 17 Aug 2009 11:32:08 -0500 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> Message-ID: On 2009-08-11, Bearophile wrote: > Robert Dailey: > >> This breaks the flow of scope. Would you guys solve this >> problem by moving failMsg into global scope? Perhaps through >> some other type of syntax? > > There are gals too here. Straying a bit OT, but I find this particular issue rather fascinating. At least in the US, "guys" is now pretty much gender-neutral according to my casual research (mostly just paying attention to informal speach). Oddly, it still seems to be masculine when singular. Though one commonly hears a group of females addressed as "you guys" or refered to as "those guys", one never hears a single female referred to as "a guy" or "that guy". It is a bit tricky, however, since a phrase like "a group of guys" still seems to refer to just males since the word "guys" in that case is being applied individually to a plurality of persons rather being applied collectivelly to a single group -- if that makes any sense. I've actually discussed this with a a number of female friends, and they almost all thought the term "gals" was condescending and actually preferred to be referred to collectively as "guys". -- Grant Edwards grante Yow! You can't hurt me!! at I have an ASSUMABLE visi.com MORTGAGE!! From aaron.watters at gmail.com Mon Aug 17 12:41:14 2009 From: aaron.watters at gmail.com (Aaron Watters) Date: Mon, 17 Aug 2009 09:41:14 -0700 (PDT) Subject: off topic: google groups sucks? References: <087f64b6-0cc7-4a75-a2ba-9ca74d31f1fd@o32g2000yqm.googlegroups.com> Message-ID: <082ae712-a55f-4bd6-aa07-71f6d4c2253b@j21g2000yqe.googlegroups.com> On Aug 17, 10:05?am, Aaron Watters wrote: > Just a note. ?It seems that google groups is increasing the > sucks coefficient. I'm having better luck now using the advanced search option with queries like gadfly group:comp.lang.python which become http://groups.google.com/groups/search?q=gadfly+group:comp.lang.python The "search this group" feature still needs fixing, however. -- Aaron Watters === if you lined up all economists end to end they'd still point in different directions. -- stolen from somewhere From jeanmichel at sequans.com Mon Aug 17 13:03:56 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 17 Aug 2009 19:03:56 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> Message-ID: <4A898D7C.2080709@sequans.com> Grant Edwards wrote: > On 2009-08-11, Bearophile wrote: > >> Robert Dailey: >> >> >>> This breaks the flow of scope. Would you guys solve this >>> problem by moving failMsg into global scope? Perhaps through >>> some other type of syntax? >>> >> There are gals too here. >> > > Straying a bit OT, but I find this particular issue rather > fascinating. > > At least in the US, "guys" is now pretty much gender-neutral > according to my casual research (mostly just paying attention > to informal speach). > > Oddly, it still seems to be masculine when singular. Though one > commonly hears a group of females addressed as "you guys" or > refered to as "those guys", one never hears a single female > referred to as "a guy" or "that guy". > > It is a bit tricky, however, since a phrase like "a group of > guys" still seems to refer to just males since the word "guys" > in that case is being applied individually to a plurality of > persons rather being applied collectivelly to a single group -- > if that makes any sense. > > I've actually discussed this with a a number of female friends, > and they almost all thought the term "gals" was condescending > and actually preferred to be referred to collectively as > "guys". > > I'm no English native, but I already heard women/men referring to a group as "guys", no matter that group gender configuration. It's even used for group composed exclusively of women. Moreover it looks like a *very* friendly form, so there is really nothing to worry about it. Forms like: "Hi guys", "You guys should do something...", "Come on guys..." are very friendly and gender-neutral. JM From piet at cs.uu.nl Mon Aug 17 13:14:42 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 17 Aug 2009 19:14:42 +0200 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: >>>>> Simon Brunning (SB) wrote: >SB> 2009/8/11 Robert Dailey : >>> On Aug 11, 3:40?pm, Bearophile wrote: >>>> There are gals too here. >>> >>> It's a figure of speech. And besides, why would I want programming >>> advice from a woman? lol. Thanks for the help. >SB> Give the attitudes still prevalent in our industry (cf >SB> and many more), I'm sorry to say that I >SB> don't think this is funny. seconded -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From jeanmichel at sequans.com Mon Aug 17 13:23:39 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 17 Aug 2009 19:23:39 +0200 Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <4A89921B.4000603@sequans.com> Aahz wrote: > In article <461cc6f1-fc23-4bc7-a719-6f29babf8bcd at o15g2000yqm.googlegroups.com>, > Robert Dailey wrote: > >> It's a figure of speech. And besides, why would I want programming >> advice from a woman? lol. Thanks for the help. >> > > Well, I'm sorry to see this, it means I was wrong about the lack of > sexism in the Python community. I encourage anyone who wants to improve > the situation to join the new diversity list: > > http://mail.python.org/mailman/listinfo/diversity > Are you suggesting this list reject part of the community regarding its sexual orientation, ethnicity, size, culture? If that was the case I'd like to know about it. I would really want to know how you'd guess my gender (could be some clue somewhere), my sexual orientation, my religion and so on. How can you reject someone regarding informations you don't have ? That's the beauty of this mailing list, it has diversity, by design. We even welcome people that mixes up joke with sexist aggression, not to mention how open minded we are :o) Beside, the day you'll meet a real act of sexism in this list, please know that people talk and act on their own, do not assign their attitude to the whole community. You'll know that Python is sexist the day you'll find the title 'No women allowed' on the python main document page. JM PS : Newbies are not welcome here ! From timothywayne.cook at gmail.com Mon Aug 17 13:30:44 2009 From: timothywayne.cook at gmail.com (Tim Cook) Date: Mon, 17 Aug 2009 10:30:44 -0700 (PDT) Subject: flatten a list of list References: <9c972b02-3c30-4fad-95bd-cf6165913d6b@e27g2000yqm.googlegroups.com> Message-ID: On Aug 16, 6:47?am, Terry wrote: > Hi, > > Is there a simple way (the pythonic way) to flatten a list of list? > rather than my current solution: > > new_list=[] > for l in list_of_list: > ? ? new_list.extend(l) > > or, > > new_list=reduce(lambda x,y:x.extend(y), list_of_list) > > br, Terry Well, This is not simple but it is comprhensive in that it has to do several things. I am using it to decompose deeply nested lists from Pyparsing output that may have strings in a variety of languages. Performance wise I do not know how it stacks up against the other examples but it works for me. :-) def flatten(x): """flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). All strings are converted to unicode. """ result = [] for el in x: #if isinstance(el, (list, tuple)): if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) # all strings must be unicode rtnlist=[] for x in result: if isinstance(x,str): # replace any brackets so Python doesn't think it's a list and we still have a seperator. x=x.replace('[','_') x=x.replace(']','_') try: x=unicode(x, "utf8") # need more decode types here except UnicodeDecodeError: x=unicode(x, "latin1") except UnicodeDecodeError: x=unicode(x,"iso-8859-1") except UnicodeDecodeError: x=unicode(x,"eucJP") rtnlist.append(x) return rtnlist From rami.chowdhury at gmail.com Mon Aug 17 13:33:52 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Mon, 17 Aug 2009 10:33:52 -0700 Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) In-Reply-To: <4A89921B.4000603@sequans.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <4A89921B.4000603@sequans.com> Message-ID: > You'll know that Python is sexist the day you'll find the title 'No > women allowed' on the python main document page. Good God I hope you're being ironic. On Mon, 17 Aug 2009 10:23:39 -0700, Jean-Michel Pichavant wrote: > Aahz wrote: >> In article >> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd at o15g2000yqm.googlegroups.com>, >> Robert Dailey wrote: >> >>> It's a figure of speech. And besides, why would I want programming >>> advice from a woman? lol. Thanks for the help. >>> >> >> Well, I'm sorry to see this, it means I was wrong about the lack of >> sexism in the Python community. I encourage anyone who wants to improve >> the situation to join the new diversity list: >> >> http://mail.python.org/mailman/listinfo/diversity >> > Are you suggesting this list reject part of the community regarding its > sexual orientation, ethnicity, size, culture? If that was the case I'd > like to know about it. > I would really want to know how you'd guess my gender (could be some > clue somewhere), my sexual orientation, my religion and so on. > How can you reject someone regarding informations you don't have ? > > That's the beauty of this mailing list, it has diversity, by design. > We even welcome people that mixes up joke with sexist aggression, not to > mention how open minded we are :o) > > Beside, the day you'll meet a real act of sexism in this list, please > know that people talk and act on their own, do not assign their attitude > to the whole community. > You'll know that Python is sexist the day you'll find the title 'No > women allowed' on the python main document page. > > JM > > PS : Newbies are not welcome here ! > > -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From seldan24 at gmail.com Mon Aug 17 13:43:33 2009 From: seldan24 at gmail.com (seldan24) Date: Mon, 17 Aug 2009 10:43:33 -0700 (PDT) Subject: Using a Callback Function - ftplib Message-ID: <76875cdd-30c4-4a3b-8a16-d0e2061765d7@v2g2000vbb.googlegroups.com> Hello, I'm utterly confused by something which is most likely trivial. I'm attempting to connect to an FTP server, retrieve a list of files, and store than in an array. I.e.: import ftplib ftp = ftplib.FTP(server) ftp.login(user, pass) ftp.cwd(conf['testdir']) ftp.retrlines('NLST ' + "testfile*.txt") ftp.quit() The above example works fine... and would return a list of any files that match "testfile*.txt" to standard out. The issue is I don't want that to go to stdout, I'd rather capture them within an array so I can retrieve them later. If I try something like: my_files = ftp.retrlines('NLST ' + "testfile*.txt") Then, my_files, will just print out the return code of the FTP NLST command. I'm trying to get the file names themselves. Now, I've read through the ftplib module section of the Python documentation and it says that, by default, the output goes to sys.stdout unless a callback function is used. Here is where I get utterly lost. I can certainly see the files being outputted to sys.stdout, but don't know how to capture that output... i.e. testfile1.txt testfile2.txt testfile3.txt Will show to the screen, but I can't catch it! I'm sure this is trivial... any help would be greatly appreciated. From gallium.arsenide at gmail.com Mon Aug 17 13:44:49 2009 From: gallium.arsenide at gmail.com (John Yeung) Date: Mon, 17 Aug 2009 10:44:49 -0700 (PDT) Subject: off topic: google groups sucks? References: <087f64b6-0cc7-4a75-a2ba-9ca74d31f1fd@o32g2000yqm.googlegroups.com> <082ae712-a55f-4bd6-aa07-71f6d4c2253b@j21g2000yqe.googlegroups.com> Message-ID: <784a24a3-066e-45b9-81e7-bed187e9f012@f10g2000vbf.googlegroups.com> On Aug 17, 12:41?pm, Aaron Watters wrote: > I'm having better luck now using the advanced search option > with queries like > > ? ?gadfly group:comp.lang.python > > The "search this group" feature still needs fixing, however. Thanks, Aaron, for confirming that it's not just me! I've been noticing spotty or missing results searching groups for a while now, actually, to the point that I gave up trying. Can't remember exactly when it started, but I do remember that it used to work pretty well and then suddenly got significantly worse. Also, thanks for the tip of trying advanced searches. John From 71david at libero.it Mon Aug 17 13:51:33 2009 From: 71david at libero.it (David) Date: Mon, 17 Aug 2009 19:51:33 +0200 Subject: Using a Callback Function - ftplib References: <76875cdd-30c4-4a3b-8a16-d0e2061765d7@v2g2000vbb.googlegroups.com> Message-ID: <1euafoc8zeh0q.91hedjv5ueuh$.dlg@40tude.net> Il Mon, 17 Aug 2009 10:43:33 -0700 (PDT), seldan24 ha scritto: > Hello, > > I'm utterly confused by something which is most likely trivial. I'm > attempting to connect to an FTP server, retrieve a list of files, and > store than in an array. I.e.: > > import ftplib > > ftp = ftplib.FTP(server) > ftp.login(user, pass) > ftp.cwd(conf['testdir']) Why bother with retrlines? Use the provided higer level fuctions: remotefiles = [] ftp.dir(remotefiles.append) or, if you prefer nlst remotefiles = ftp.nlst() regards david From seldan24 at gmail.com Mon Aug 17 14:10:25 2009 From: seldan24 at gmail.com (seldan24) Date: Mon, 17 Aug 2009 11:10:25 -0700 (PDT) Subject: Using a Callback Function - ftplib References: <76875cdd-30c4-4a3b-8a16-d0e2061765d7@v2g2000vbb.googlegroups.com> <1euafoc8zeh0q.91hedjv5ueuh$.dlg@40tude.net> Message-ID: On Aug 17, 1:51?pm, David <71da... at libero.it> wrote: > Il Mon, 17 Aug 2009 10:43:33 -0700 (PDT), seldan24 ha scritto: > > > Hello, > > > I'm utterly confused by something which is most likely trivial. ?I'm > > attempting to connect to an FTP server, retrieve a list of files, and > > store than in an array. ?I.e.: > > > import ftplib > > > ftp = ftplib.FTP(server) > > ftp.login(user, pass) > > ftp.cwd(conf['testdir']) > > Why bother with retrlines? Use the provided higer level fuctions: > > remotefiles = [] > ftp.dir(remotefiles.append) > > or, if you prefer nlst > > remotefiles = ftp.nlst() > > regards > david I didn't even notice the higher level methods. I changed the retrieval line to: ftp.nlst("testfile*.txt") This works great. The result is even captured in an array. I really have no idea what the difference between a LIST and NLST is within FTP. Never delved that deep into it. I did notice that an NLST will return a specific FTP code if a file doesn't exist, whereas a LIST doesn't. So, I ended up using NLST as that'll generate an ftplib.error_perm exception. Based on if the job cares if a file is not available or not (some do, some don't), I'll either exit, or continue on with the file loop. Anyway, thanks again, works perfectly, next time I'll try to scroll down and read a bit more prior to posting! From nad at acm.org Mon Aug 17 14:25:30 2009 From: nad at acm.org (Ned Deily) Date: Mon, 17 Aug 2009 11:25:30 -0700 Subject: Uninstalling mac python2.5 to install python2.6 References: <83423F73-83DA-436B-A3BA-E83CD61CD28D@cs.stir.ac.uk> Message-ID: In article <83423F73-83DA-436B-A3BA-E83CD61CD28D at cs.stir.ac.uk>, Farhan Sheikh wrote: > i originally had python2.5 on my mac at the univeristy and had to get > 2.6 to get NEST and pyNN to work together. however now as those are > now installed, i had to install numpy. > > As i installed numpy, it only installed its directories into the > python2.5 folders and as i am new to to mac terminals i don't know how > to change its directories to be installed into python2.6. my question > is, do i have to uninstall python 2.5 so that only python2.6 is on the > machine or is there a way to change the path so it saves into python2.5? There appears to be a NumPy installer image for Python 2.6 and OX 10.5 here: http://sourceforge.net/projects/numpy/files/ Multiple versions of python can co-exist on OS X. You definitely should not remove the Apple-supplied python2.5 (linked to from /usr/bin/python) in 10.5. -- Ned Deily, nad at acm.org From fidellira.6 at gmail.com Mon Aug 17 14:26:05 2009 From: fidellira.6 at gmail.com (axl456) Date: Mon, 17 Aug 2009 11:26:05 -0700 (PDT) Subject: GUI interface builder for python References: Message-ID: <21bca3cf-b2c7-47d7-9142-26c9fd015f92@r27g2000vbn.googlegroups.com> On Aug 17, 1:59?am, "L at D@n" wrote: > Which is the best GUI interface builder with drag and drop > capabilities. > I am using Ubuntu GNU/Linux. > Please help me. > Thank you. boa is really nice.. From pavlovevidence at gmail.com Mon Aug 17 14:32:29 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 11:32:29 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> Message-ID: On Aug 17, 4:40?am, exar... at twistedmatrix.com wrote: > On 02:12 am, pavlovevide... at gmail.com wrote: > > > > >On Aug 16, 3:35?pm, sturlamolden wrote: > >>On 16 Aug, 14:57, Dennis Lee Bieber wrote: > > >> > ? ? ? ? Well, the alternative would be to have two keywords for > >>looping: one > >> > for your "simple" incrementing integer loop, and another for a loop > >>that > >> > operates over the elements of some collection type. > > >>A compiler could easily recognise a statement like > > >>? ?for i in range(n): > > >>as a simple integer loop. > > >It would be a simple to do if you were writing it for a different > >langauge was a lot less dynamic than Python is. ?It'd be quite a > >complex hack to add it to CPython's compiler while maintaing the > >current highly dynamic runtime semantics and backwards compatibility, > >which is a design constraint of Python whether you like it or not. > > In your other message, you said this wasn't a legitimate CPython > complaint. ?Here, you say that it would be a "complex hack" to implement > this in CPython. ?"complex hack" has negative connotations in my mind. > This seems contradictory to me. Well, you missed the point, chief. It's not a legitimate complaint because you can use xrange, you don't need compiler magic to recognize and optimize range. Carl Banks From zorigaman at gmail.com Mon Aug 17 14:46:21 2009 From: zorigaman at gmail.com (Zorigaman) Date: Mon, 17 Aug 2009 11:46:21 -0700 (PDT) Subject: Embedding a python console inside a python application Message-ID: Hi, I am starting an application in which I would like to have some scripting functionality. It will obviously be done in Python. The thing is that I would like my scripts to have access to the rest of the application as an object it could manipulate. I made some research and I found the code module, which allows to have a Python interpreter inside an application, but I am not sure if I can access to the "parent" which created this interpreter. A solution could be to launch my application through an interpreter, but the problem there is how to integrate it back into the GUI, redirecting streams ? Another option is the cmd module, but here, same problem, I am not sure if can have access to my application's objects. I am using PyQt with Python 2.6.1, I could switch to Python 3.0 if necessary. I am familiar with programming, but that's my first script-enabled application, tell me if I am missing something obvious. http://docs.python.org/library/code.html http://docs.python.org/library/cmd.html From jurgenex at hotmail.com Mon Aug 17 14:48:43 2009 From: jurgenex at hotmail.com (Jürgen Exner) Date: Mon, 17 Aug 2009 11:48:43 -0700 Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: Jon Harrop wrote: >Xah Lee wrote: [...] Please do not feed this well-known troll. He is known to spew some remotely on-topic junk into a bunch of unrelated NGs and to enjoy the ensuing confusion. jue From no.email at please.post Mon Aug 17 15:05:26 2009 From: no.email at please.post (kj) Date: Mon, 17 Aug 2009 19:05:26 +0000 (UTC) Subject: XPath support? References: Message-ID: In Kev Dwyer writes: >On Sun, 16 Aug 2009 20:29:15 +0000, kj wrote: >> I'm looking for a XML parser that produces an object with full XPath >> support. What I've been using up to now, xml.etree.ElementTree, fails >> to support Xpath predicates, as in "spam[@eggs='3']/ham". >> >> What I'm trying to do is to read-in a large XML string, and parse it >> into an object from which I can extract nodes matching selectors that >> include such predicates. >> >> Any suggestions would be greatly appreciated. >> >> TIA! >> >> kynn >Have you tried lxml (http://codespeak.net/lxml/)? Thanks! (To Diez too!) kynn From no.email at please.post Mon Aug 17 15:10:22 2009 From: no.email at please.post (kj) Date: Mon, 17 Aug 2009 19:10:22 +0000 (UTC) Subject: Data visualization in Python Message-ID: I'm looking for a good Python package for visualizing scientific/statistical data. (FWIW, the OS I'm interested in is Mac OS X). The users of this package will be experimental biologists with little programming experience (but currently learning Python). (I normally visualize data using R or Mathematica, but I don't want to saddle these novices with the task of learning yet another language.) TIA! kynn From bruce at cenderis.demon.co.uk Mon Aug 17 15:13:29 2009 From: bruce at cenderis.demon.co.uk (Bruce Stephens) Date: Mon, 17 Aug 2009 20:13:29 +0100 Subject: python doc available in emacs info format? References: <4a893f9a$0$307$14726298@news.sunsite.dk> Message-ID: <87d46u9rty.fsf@cenderis.demon.co.uk> "Colin S. Miller" writes: [...] > Ubuntu maintains a package search site, it is on > http://packages.ubuntu.com/ > > However, there seems to be no files named > python.*info (regexp) And yet there are info files in python2.5-doc: . [...] From paul at boddie.org.uk Mon Aug 17 15:22:16 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 17 Aug 2009 12:22:16 -0700 (PDT) Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <704d9cc8-fa9a-4e7e-8d7a-bb130935d10a@24g2000yqm.googlegroups.com> On 17 Aug, 19:23, Jean-Michel Pichavant wrote: > > Are you suggesting this list reject part of the community regarding its > sexual orientation, ethnicity, size, culture? If that was the case I'd > like to know about it. Careful: you probably meant to write "rejects", not "reject". That changes the meaning of what you've written somewhat. > I would really want to know how you'd guess my gender (could be some > clue somewhere), my sexual orientation, my religion and so on. > How can you reject someone regarding informations you don't have ? Well, everyone can of course hide their actual identity on the Internet, but when someone references a group of people with a juvenile remark (if we are being charitable about the matter), it has nothing to do with guessing the characteristics of individuals. The whole excuse that anonymity defends against insults and harassment is a bit like saying that slinging mud at everyone is acceptable as long as everyone is encouraged to do it and nobody is wearing their nicest clothes. And unless your idea of a Python-related conference is something close to a fancy-dress event with everyone "in character" - which would obviously limit the effectiveness of such an event - you presumably understand that there is a genuine need for continuity between interactions on and off the Internet. This somewhat undermines your argument. > That's the beauty of this mailing list, it has diversity, by design. An explanation is needed here for this not to sound like conversational padding. > We even welcome people that mixes up joke with sexist aggression, not to > mention how open minded we are :o) Well, jokes actually need an amusing side, regardless of how "edgy" ("juvenile" is typically the more accurate term) the joke- teller is trying to be, and that was completely absent from the remark in question. There's little room for error in communication over a medium like this one, as I pointed out with your opening sentence. And much as it probably upsets the "unfettered free speech" advocates, we should be able to assert that "sexist aggression" is not acceptable behaviour amongst those who seek to participate in our community. Paul From invalid at invalid Mon Aug 17 15:29:36 2009 From: invalid at invalid (Grant Edwards) Date: Mon, 17 Aug 2009 14:29:36 -0500 Subject: Data visualization in Python References: Message-ID: On 2009-08-17, kj wrote: > I'm looking for a good Python package for visualizing > scientific/statistical data. (FWIW, the OS I'm interested in > is Mac OS X). Both matplotlib and gnuplot-py can produce pretty good results with a minimum of effort: http://matplotlib.sourceforge.net/ http://gnuplot-py.sourceforge.net/ I lean more towards gnuplot, but that's probably just a bias from having used Gnuplot for 10+ years before learning Python. Both matplotlib and gnuplot are basically 2D packages with some 3D features. There's also a Python binding for VTK. I found it a bit harder to use for the stuff I did, but sophisticated 3D stuff it's probably the winner: http://www.vtk.org/ [It also has the only Delaunay triangulation module (of the 3 that I tried) that worked reliably, but you probably don't care about that.] -- Grant Edwards grante Yow! Let me do my TRIBUTE at to FISHNET STOCKINGS ... visi.com From invalid at invalid Mon Aug 17 15:36:18 2009 From: invalid at invalid (Grant Edwards) Date: Mon, 17 Aug 2009 14:36:18 -0500 Subject: Data visualization in Python References: Message-ID: On 2009-08-17, Grant Edwards wrote: > On 2009-08-17, kj wrote: > >> I'm looking for a good Python package for visualizing >> scientific/statistical data. (FWIW, the OS I'm interested in >> is Mac OS X). > > Both matplotlib and gnuplot-py can produce pretty good results > with a minimum of effort: Oh, just in case you haven't found them, you might also be interested in the SciPy and Scientific Python projects: http://www.scipy.org/ http://sourcesup.cru.fr/projects/scientific-py/ Though they have deceptively similar names, they're two separate projects. Unfortunately, some rather promenent documentation conflates the two. For example, http://docs.python.org/3.1/tutorial/whatnow.html refers to www.scipy.org as "the Scientific Python" project. -- Grant Edwards grante Yow! I hope the at ``Eurythmics'' practice visi.com birth control ... From exarkun at twistedmatrix.com Mon Aug 17 15:41:55 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Mon, 17 Aug 2009 19:41:55 -0000 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> Message-ID: <20090817194155.8740.902674574.divmod.xquotient.69@localhost.localdomain> On 06:32 pm, pavlovevidence at gmail.com wrote: >On Aug 17, 4:40?am, exar... at twistedmatrix.com wrote: >>On 02:12 am, pavlovevide... at gmail.com wrote: >> >> >> >> >On Aug 16, 3:35?pm, sturlamolden wrote: >> >>On 16 Aug, 14:57, Dennis Lee Bieber wrote: >> >> >> > ? ? ? ? Well, the alternative would be to have two keywords for >> >>looping: one >> >> > for your "simple" incrementing integer loop, and another for a >>loop >> >>that >> >> > operates over the elements of some collection type. >> >> >>A compiler could easily recognise a statement like >> >> >>? ?for i in range(n): >> >> >>as a simple integer loop. >> >> >It would be a simple to do if you were writing it for a different >> >langauge was a lot less dynamic than Python is. ?It'd be quite a >> >complex hack to add it to CPython's compiler while maintaing the >> >current highly dynamic runtime semantics and backwards compatibility, >> >which is a design constraint of Python whether you like it or not. >> >>In your other message, you said this wasn't a legitimate CPython >>complaint. ?Here, you say that it would be a "complex hack" to >>implement >>this in CPython. ?"complex hack" has negative connotations in my mind. >>This seems contradictory to me. > >Well, you missed the point, chief. > >It's not a legitimate complaint because you can use xrange, you don't >need compiler magic to recognize and optimize range. There's a lot of things in Python that I don't strictly *need*. That doesn't mean that they wouldn't be welcome if I could have them. Getting rid of the range/xrange dichotomy would improve things. Yes, I can work around it until the runtime is good enough to let me think about an *interesting* problem instead. That makes it a legitimate complaint in my eyes. You're welcome to disagree, of course, but do you have an argument more compelling than the one you give here? It seems to me one could use it to argue a lot of Python out of existence. Chief. (Seriously, "chief"? What are you going for? It sounds like condescension to me; what's the point of that? I hope I'm just misreading you.) Jean-Paul From jon at ffconsultancy.com Mon Aug 17 15:42:38 2009 From: jon at ffconsultancy.com (Jon Harrop) Date: Mon, 17 Aug 2009 20:42:38 +0100 Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: Xah Lee wrote: > On Aug 12, 12:15 pm, Raymond Hettinger wrote: >> * The reason for implementing the key= parameter had nothing to do >> with limitations of Python's compiler. Instead, it was inspired by >> the >> decorate-sort-undecorate pattern. > > The decorate-sort-undecorate pattern is a compiler limitation, for > most of today's langs. I'm not sure, but i think some of the fancy > functional langs automatically detect such and optimize it away, to > various degrees. You mean people use that pattern as a fast alternative in languages where user-defined functions are very slow, like Python and Mathematica? -- Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u From brochu121 at gmail.com Mon Aug 17 15:51:19 2009 From: brochu121 at gmail.com (David Brochu) Date: Mon, 17 Aug 2009 15:51:19 -0400 Subject: comparing XML files to eachother Message-ID: <9583ed900908171251k50fafaefrd626439bf1bd9a3c@mail.gmail.com> I need to compare one xml document to another to see if the content matches. Unfortunately, the formatting (spacing) and order of elements may change between files from run to run. I have looked into xml dom minidom but can't seem to find how to accomplish this. Does anyone know how I can do a compare between two XML documents using the STL? -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Mon Aug 17 15:59:43 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 12:59:43 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> Message-ID: <6c86d734-61b8-48e2-aa28-a62dfbd2ee75@w6g2000yqw.googlegroups.com> On Aug 17, 12:41?pm, exar... at twistedmatrix.com wrote: > There's a lot of things in Python that I don't strictly *need*. ?That > doesn't mean that they wouldn't be welcome if I could have them. > Getting rid of the range/xrange dichotomy would improve things. ?Yes, I > can work around it until the runtime is good enough to let me think > about an *interesting* problem instead. You don't have to think about using xrange in a for loop, you just always use it. >?That makes it a legitimate > complaint in my eyes. ?You're welcome to disagree, of course, but do you > have an argument more compelling than the one you give here? I am not arguing in favor of range/xrange, I am saying that it's silly to complain that the compiler isn't a whole lot more complex than it is just so it can implemnent a semantically-diconnected special case just so that you can avoid typing an extra "x". The cost doesn't even remotely justify it. Carl Banks From pavlovevidence at gmail.com Mon Aug 17 16:00:44 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 13:00:44 -0700 (PDT) Subject: Python 'for' loop is memory inefficient References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> <6c86d734-61b8-48e2-aa28-a62dfbd2ee75@w6g2000yqw.googlegroups.com> Message-ID: <15810fe6-604b-49e8-8bd6-b3766bf9f993@z31g2000yqd.googlegroups.com> On Aug 17, 12:59?pm, Carl Banks wrote: >?The cost doesn't even remotely justify it. I mean, it doesn't even remotely justify the cost. Carl Banks From piet at cs.uu.nl Mon Aug 17 16:05:13 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 17 Aug 2009 22:05:13 +0200 Subject: zip codes References: <35833d36-2fdc-4ed8-8142-604af3c88afe@k6g2000yqn.googlegroups.com> <512e67d9-8733-4329-a7d9-c6e21d6a2165@r38g2000yqn.googlegroups.com> Message-ID: >>>>> Grant Edwards (GE) wrote: >GE> On 2009-08-16, Shailen wrote: >>> Thanks Martin and Aahz. Anyone know if zip code information is >>> copyrighted for the US? >GE> You can't copyright "information" as such. Only concrete >GE> expressions of information. A particular publication >GE> containing zip code information can be copyrighted. The >GE> underlying facts themselve cannot be. But that doesn't help you if you need that information and the only way to obtain it is from copyrighted sources. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From ronn.ross at gmail.com Mon Aug 17 16:18:17 2009 From: ronn.ross at gmail.com (Ronn Ross) Date: Mon, 17 Aug 2009 16:18:17 -0400 Subject: Barcodes Message-ID: <9c8c445f0908171318x2d9d862bi35ccb398376aceca@mail.gmail.com> My company needs a small inventory management app. Does python have any libraries to help with reading and writing bar codes? -------------- next part -------------- An HTML attachment was scrubbed... URL: From aaron.watters at gmail.com Mon Aug 17 16:35:02 2009 From: aaron.watters at gmail.com (Aaron Watters) Date: Mon, 17 Aug 2009 13:35:02 -0700 (PDT) Subject: off topic: google groups sucks? References: <087f64b6-0cc7-4a75-a2ba-9ca74d31f1fd@o32g2000yqm.googlegroups.com> <082ae712-a55f-4bd6-aa07-71f6d4c2253b@j21g2000yqe.googlegroups.com> <784a24a3-066e-45b9-81e7-bed187e9f012@f10g2000vbf.googlegroups.com> Message-ID: <51877a03-b6de-4131-90d8-13cd618236aa@v20g2000yqm.googlegroups.com> On Aug 17, 1:44?pm, John Yeung wrote: > Thanks, Aaron, for confirming that it's not just me! yea, unfortunately this kind of thing happens in monopolies that have no viable competition anymore... Sometimes I begin to suspect that I'm seeing the results that I should want rather than the results I want. (Lucene has this property too -- you get the results the algorithm wants you to get, rather than the results you want to get.) -- Aaron Watters === In communism the future is certain, but the past is ever changing. From jordilin at gmail.com Mon Aug 17 16:37:13 2009 From: jordilin at gmail.com (jordilin) Date: Mon, 17 Aug 2009 13:37:13 -0700 (PDT) Subject: Data visualization in Python References: Message-ID: On 17 ago, 21:10, kj wrote: > I'm looking for a good Python package for visualizing > scientific/statistical data. ?(FWIW, the OS I'm interested in is > Mac OS X). > > The users of this package will be experimental biologists with > little programming experience (but currently learning Python). > > (I normally visualize data using R or Mathematica, but I don't want > to saddle these novices with the task of learning yet another > language.) > > TIA! > > kynn Matplotlib is the one. There is Google Chart api which seems fairly easy to understand and use thanks to pygooglechart bindings. From emile at fenx.com Mon Aug 17 16:44:52 2009 From: emile at fenx.com (Emile van Sebille) Date: Mon, 17 Aug 2009 13:44:52 -0700 Subject: Barcodes In-Reply-To: <9c8c445f0908171318x2d9d862bi35ccb398376aceca@mail.gmail.com> References: <9c8c445f0908171318x2d9d862bi35ccb398376aceca@mail.gmail.com> Message-ID: On 8/17/2009 1:18 PM Ronn Ross said... > My company needs a small inventory management app. Does python have any > libraries to help with reading and writing bar codes? I've written bar code apps and python really doesn't enter into that part of things. Printers generally have bar code printing capabilities so you just send the right escape sequences and you get the bar codes. To read them, bar code readers scan and translate before sending the values through typically a keyboard wedge or serial port. Emile From hani.mousli at gmail.com Mon Aug 17 16:47:44 2009 From: hani.mousli at gmail.com (=?UTF-8?B?2YfYp9mG2Yog2KfZhNmF2YjYtdmE2Yo=?=) Date: Mon, 17 Aug 2009 13:47:44 -0700 (PDT) Subject: Strongly typed list Message-ID: Hello, I am using eclips for python and i am facing a problem. I have many classes with many properties and want a list of objects from one of my declared classes. The problem is:When i am accessing any item from the list, the IDE does not know it's type because in python we do not declare the variable with it's type, so there is no auto complete and i have to go to the class to copy the attribute name. To make idea more clear: class AutomataBranch(object): def __init__(selfparams): self.Name=""; self.nodes=[]; class LanguageAutomata(object): def __init__(selfparams): self.cfgAutomata=[];#This has AutomaBranch Type Now in any method in LanguageAutomata class if i wrote: cfgAutomata. Then it wont give me the Name attribute Is there any solution for that? Perhaps of there is some thing like C# List cfgAutomata such that the list wont accept items unless they are AutomataBranch will be good. From python.list at tim.thechases.com Mon Aug 17 16:55:23 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 17 Aug 2009 15:55:23 -0500 Subject: Barcodes In-Reply-To: References: <9c8c445f0908171318x2d9d862bi35ccb398376aceca@mail.gmail.com> Message-ID: <4A89C3BB.2030605@tim.thechases.com> >> My company needs a small inventory management app. Does >> python have any libraries to help with reading and writing >> bar codes? > > I've written bar code apps and python really doesn't enter > into that part of things. Printers generally have bar code > printing capabilities so you just send the right escape > sequences and you get the bar codes. To read them, bar code > readers scan and translate before sending the values through > typically a keyboard wedge or serial port. To add to what Emile mentions, most barcode readers present a keyboard-wedge interface, so that scanning a barcode merely appears as if you typed it at the keyboard (USB readers show up as a HID profile). Often they'll have configuration barcodes that you can scan to tweak the profile (such as pressing , or an arrow-key after sending the barcode; controlling beep tone & volume, etc). For printing barcodes, you can use any number of solutions -- the most popular usually just involves installing a "barcode font" and then rendering text in that font to your desired output canvas. I believe there are some native rendering solutions as well, but I've not investigated since the font method was more than sufficient for my wants. -tkc From http Mon Aug 17 16:56:13 2009 From: http (Paul Rubin) Date: 17 Aug 2009 13:56:13 -0700 Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: <7xtz06cg7m.fsf@ruckus.brouhaha.com> Jon Harrop writes: > You mean people use that pattern as a fast alternative in languages where > user-defined functions are very slow, like Python and Mathematica? It really doesn't matter whether the language is fast or slow--there are going to be applications where calling the comparison function multiple times per element is slower than calling it once per element and storing the result. Note the Haskell idiom (sortBy (compare`on`f) xs) is similar to DSU but calls the comparison function multiple times. Python 3.0 went overboard by actually removing the cmp argument and requiring use of the key argument. That requires various kludges if the key is, say, a tree structure that has to be recursively compared with another such structure. Maybe then can bring back cmp someday. From pavlovevidence at gmail.com Mon Aug 17 17:06:04 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 14:06:04 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> Message-ID: <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> On Aug 17, 10:03?am, Jean-Michel Pichavant wrote: > I'm no English native, but I already heard women/men referring to a > group as "guys", no matter that group gender configuration. It's even > used for group composed exclusively of women. Moreover it looks like a > *very* friendly form, so there is really nothing to worry about it. I like how being very friendly means calling people after a guy who tried to blow up the English Parliament. Carl Banks From xahlee at gmail.com Mon Aug 17 17:09:54 2009 From: xahlee at gmail.com (Xah Lee) Date: Mon, 17 Aug 2009 14:09:54 -0700 (PDT) Subject: Xah's Edu Corner: The importance of syntax & notations. References: <25203724-bf60-484f-9ede-e61c45f15e33@s31g2000yqs.googlegroups.com> Message-ID: http://www.stephenwolfram.com/publications/recent/mathml/index.html i was trying to find the publication date and context, but didn't find it last time after a couple min. Yesterday, on rereading, i did. The article in question is: ? Mathematical Notation: Past and Future (2000) Stephen Wolfram October 20, 2000 Transcript of a keynote address presented at MathML and Math on the Web: MathML International Conference 2000 ? so, it's a speech for MathML conf in 2000. so, this explains the error on the plimpton 322. The latest discovery on that is published in 2002 and later. the date of this speech also explains parts of the writings about some mysterious ?fundamental science work?, which now we know is his controversial book A New Kind Of Science (2002). Xah ? http://xahlee.org/ ? ---------------------- Xah Lee wrote: Personally, particular interesting info i've learned is that, for all my trouble in the past decade expressing problems of traditional math notation, i learned from his article this single-phrase summary: ?traditional math notation lacks a grammar?. The article is somewhat disappointing though. I was expecting he'd go into some details about the science of math notations, or, as he put it aptly: ?linguistics of math notations?. However, he didn't touch the subject, except saying that it haven't been studied. upon a more detailed reading of Stephen's article, i discovered some errors. On this page:http://www.stephenwolfram.com/publications/recent/mathml/ mathml2.html he mentions the Plimpton 322 tablet. It is widely taught in math history books, that this table is pythagorean triples. On reading his article, i wanted to refresh my understanding of the subject, so i looked up Wikipedia: http://en.wikipedia.org/wiki/Plimpton_322 and behold! apparantly, in recent academic publications, it is suggested that this is not pythagorean triples, but rather: ?a list of regular reciprocal pairs?. Xah ?http://xahlee.org/ ? From pavlovevidence at gmail.com Mon Aug 17 17:12:51 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 14:12:51 -0700 (PDT) Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: On Aug 17, 8:44?am, a... at pythoncraft.com (Aahz) wrote: > In article <461cc6f1-fc23-4bc7-a719-6f29babf8... at o15g2000yqm.googlegroups.com>, > Robert Dailey ? wrote: > > > > >It's a figure of speech. And besides, why would I want programming > >advice from a woman? lol. Thanks for the help. > > Well, I'm sorry to see this, it means I was wrong about the lack of > sexism in the Python community. Oh come on, one newbie making an off-color joke is not any sort of reflection of the community as a whole. Anyway it's pretty naive to expect what is now a large community to avoid bad eggs altogether. Price you pay for popularity. Carl Banks From fabiofz at gmail.com Mon Aug 17 17:13:10 2009 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 17 Aug 2009 18:13:10 -0300 Subject: Strongly typed list In-Reply-To: References: Message-ID: > Hello, I am using eclips for python and i am facing a problem. I have > many classes with many properties and want a list of objects from one > of my declared classes. The problem is:When i am accessing any item > from the list, the IDE does not know it's type because in python we do > not declare the variable with it's type, so there is no auto complete > and i have to go to the class to copy the attribute name. To make idea > more clear: > > class AutomataBranch(object): > ? ?def __init__(selfparams): > ? ? ? ?self.Name=""; > ? ? ? ?self.nodes=[]; > > class LanguageAutomata(object): > ? ?def __init__(selfparams): > ? ? ? ?self.cfgAutomata=[];#This has AutomaBranch Type > Now in any method in LanguageAutomata class if i wrote: cfgAutomata. > Then it wont give me the Name attribute Is there any solution for > that? > Perhaps of there is some thing like C# List > cfgAutomata such that the list wont accept items unless they are > AutomataBranch will be good. Hello, Unfortunately, right now there is no way to gather that specific code completion in pydev -- because of the dynamic nature of python, that info is very hard to get. Best Regards, Fabio From hani.mousli at gmail.com Mon Aug 17 17:19:01 2009 From: hani.mousli at gmail.com (=?UTF-8?B?2YfYp9mG2Yog2KfZhNmF2YjYtdmE2Yo=?=) Date: Mon, 17 Aug 2009 14:19:01 -0700 (PDT) Subject: Strongly typed list References: Message-ID: <7718922b-c72c-4a7e-90a3-098318063013@n11g2000yqb.googlegroups.com> Please could you lead me to a way or a good IDE that makes developing huge projects in python more easier than what i found.Now i am using eclips. Actually it is very hard to remember all my classes methods and attributes or copy and paste them each time. Thanks very much for your interest Hani Almousli..... From xahlee at gmail.com Mon Aug 17 17:26:32 2009 From: xahlee at gmail.com (Xah Lee) Date: Mon, 17 Aug 2009 14:26:32 -0700 (PDT) Subject: python doc available in emacs info format? References: <4a893f9a$0$307$14726298@news.sunsite.dk> Message-ID: <03e865a3-5789-424c-9851-7567fcf00fa6@z31g2000yqd.googlegroups.com> > Please do not slag off a project if you want people to help; > it tends to put the goat up. a healthy community needs both positive comment as well as negative to grow. emacs's user base has been rotting off from i estimate more than 50% of programers to less that 1% today. the particular observation about info doc in this thread is a specific example. You can help FSF and emacs to improve, by, for example, trying to help it to evolve with the rapidly changing computing industry, In this case, document formats, provided if you see some of my points as valid. Or, at least consider this eroding awareness of the gnu info format among average programers worth discussing. No disrespect to you, but dismissing it as ?troll? or similiar sentiment is not helpful. emacs community is too much cult and pride. FSF and its product the GNU was highly successful in the 1980 and 1990s, with its gcc, emacs, and slew of gnu version of unix tools. A significant part of the reason is because these products at the time is truely better products in comparison to existing ones, that there are almost no substitute. Today, for many variety and complexity of reasons, almost none of this is true, except possiblly a few such as gcc and GPG. The unix shells ways and sed, awk, etc tools has largely been replaced by perl, python, ruby etc, partly due to the changing nature of computing. For GCC itself, and make, yacc, bison etc there are tens of competiting products either commercial or open source. Then there's Java, with its entire suite of tools and libs, and there are tens of truely quality languages out there today other then the ones that GCC can handle. emacs 23, although is fantastic to us emacs fans, but if you look carefully at its feature list, most of it is widely in commericial software about 10 years ago. Xah ? http://xahlee.org/ ? On Aug 17, 4:32 am, "Colin S. Miller" wrote: > Xah Lee wrote: > > btw, is there still info format for python doc? > > > i feel kinda sad that emacs info format has pretty much been > > deprecated over the past decade. About a decade ago, you still will > > see now and then people asking for emacs info format of docs (was the > > days of perl). Today, one don't hear of it. > > > Part of this is due to emacs cult problem. See: > > Xah, > > Please do not slag off a project if you want people to help; > it tends to put the goat up. > > It is not "Emacs Info" format, it is FSF Info format. > There is a stand-alone program to read the Info documentation. > The program is called "info". > > Ubuntu maintains a package search site, it is onhttp://packages.ubuntu.com/ > > However, there seems to be no files named > python.*info (regexp) > > There is a > python-docutils package > which does contain information in several > other formats. > > This package can be found either via the above site > or using "apt-cache search python-doc". > > As "info" is a FSF format, all FSF produced programs > will provide documentation in this format. However Python > is not under the auspices of the FSF, so does not need to use > this format. > > BTW, > HTML versions of INFO documentation can be generated by > info2html or info_to_html on them, or texi2html on the source. > > Have a nice day, > Colin S. Miller From clp2 at rebertia.com Mon Aug 17 17:31:51 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 17 Aug 2009 14:31:51 -0700 Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <50697b2c0908171431i36557d40wc5b85c67e0dc193d@mail.gmail.com> On Mon, Aug 17, 2009 at 2:12 PM, Carl Banks wrote: > On Aug 17, 8:44?am, a... at pythoncraft.com (Aahz) wrote: >> In article <461cc6f1-fc23-4bc7-a719-6f29babf8... at o15g2000yqm.googlegroups.com>, >> Robert Dailey ? wrote: >> >It's a figure of speech. And besides, why would I want programming >> >advice from a woman? lol. Thanks for the help. >> >> Well, I'm sorry to see this, it means I was wrong about the lack of >> sexism in the Python community. > > Oh come on, one newbie making an off-color joke is not any sort of > reflection of the community as a whole. > > Anyway it's pretty naive to expect what is now a large community to > avoid bad eggs altogether. ?Price you pay for popularity. Agreed on both points, but the lack of any reprimanding for making said inappropriate joke /would/ reflect badly on the community. Fortunately, said person's behavior has now been condemned by virtue of this thread; it's a step in the right direction. Cheers, Chris From python at mrabarnett.plus.com Mon Aug 17 17:41:54 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 17 Aug 2009 22:41:54 +0100 Subject: Need cleanup advice for multiline string In-Reply-To: <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> Message-ID: <4A89CEA2.10400@mrabarnett.plus.com> Carl Banks wrote: > On Aug 17, 10:03 am, Jean-Michel Pichavant > wrote: >> I'm no English native, but I already heard women/men referring to a >> group as "guys", no matter that group gender configuration. It's even >> used for group composed exclusively of women. Moreover it looks like a >> *very* friendly form, so there is really nothing to worry about it. > > I like how being very friendly means calling people after a guy who > tried to blow up the English Parliament. > Guy Fawkes adopted the name Guido while fighting for the Spanish in the Low Countries: http://en.wikipedia.org/wiki/Guy_Fawkes From nat.k at gm.ml Mon Aug 17 18:16:56 2009 From: nat.k at gm.ml (Nathan Keel) Date: Mon, 17 Aug 2009 15:16:56 -0700 Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: Jon Harrop wrote: > Xah Lee wrote: >> On Aug 12, 12:15 pm, Raymond Hettinger wrote: >>> * The reason for implementing the key= parameter had nothing to do >>> with limitations of Python's compiler. Instead, it was inspired by >>> the >>> decorate-sort-undecorate pattern. >> >> The decorate-sort-undecorate pattern is a compiler limitation, for >> most of today's langs. I'm not sure, but i think some of the fancy >> functional langs automatically detect such and optimize it away, to >> various degrees. > > You mean people use that pattern as a fast alternative in languages > where user-defined functions are very slow, like Python and > Mathematica? > Do not give this "Xah Lee" idiot any attention. This asshole posts only self-serving nonsense, because he thinks it makes him sound important (when in reality, he is absolutely clueless). This idiot always cross posts to 5 or more different groups that have nothing to do with his attempts to impress people (which always fail). He's incredibly arrogant, yet incredibly clueless. From zorigaman at gmail.com Mon Aug 17 18:26:23 2009 From: zorigaman at gmail.com (Zorigaman) Date: Mon, 17 Aug 2009 15:26:23 -0700 (PDT) Subject: Embedding a python console inside a python application References: Message-ID: <15807e7d-2b96-4f25-8998-7506743c5fea@a26g2000yqn.googlegroups.com> On 17 ao?t, 20:46, Zorigaman wrote: > Hi, > > I am starting an application in which I would like to have some > scripting functionality. It will obviously be done in Python. The > thing is that I would like my scripts to have access to the rest of > the application as an object it could manipulate. > I made some research and I found the code module, which allows to have > a Python interpreter inside an application, but I am not sure if I can > access to the "parent" which created this interpreter. A solution > could be to launch my application through an interpreter, but the > problem there is how to integrate it back into the GUI, redirecting > streams ? > Another option is the cmd module, but here, same problem, I am not > sure if can have access to my application's objects. > I am using PyQt with Python 2.6.1, I could switch to Python 3.0 if > necessary. > I am familiar with programming, but that's my first script-enabled > application, tell me if I am missing something obvious. > > http://docs.python.org/library/code.htmlhttp://docs.python.org/library/cmd.html D'oh. The code module offers exactly what I need, you can specify object in the interpreter's constructor. D'oh. From nospam at nospam.com Mon Aug 17 18:26:47 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 00:26:47 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? Message-ID: Hello, I need to convert DD MM YYYY dates into the MySQL-friendly YYYY-MM-DD, and translate the month name from literal French to its numeric equivalent (eg. "Janvier" into "01"). Here's an example: SELECT dateinscription, dateconnexion FROM membres LIMIT 1; 26 Mai 2007|17 Ao?t 2009 - 09h20 I'd like to update the row into "2007-05-26" and "2009-08-17 09:20", respectively. What is the best way to do this in Python? Thank you. From python at rcn.com Mon Aug 17 18:42:55 2009 From: python at rcn.com (Raymond Hettinger) Date: Mon, 17 Aug 2009 15:42:55 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: [Xah Lee] > This part i don't particular agree: > > > * The reason for implementing the key= parameter had nothing to do > > with limitations of Python's compiler. ?Instead, it was inspired by > > the > > decorate-sort-undecorate pattern. > > The decorate-sort-undecorate pattern is a compiler limitation, for > most of today's langs. I'm not sure, but i think some of the fancy > functional langs automatically detect such and optimize it away, to > various degrees. > > ... my criticism is usually written in a style catered to irritate a > particular class of coder i call tech geekers (they think of themselfs > with their idiotic term ?hackers?). So, parts are exaggerated. It'd be > more clear to say, that the reason for python's ?key?, and as a > ?solution? or need of the decorate-sort-undecorate issue, can be > attributed to the current state of the art of popular imperative > language's compilers (induced by such lang's semantics). I'm not following you here. If you're saying that it is possible for a compiler to automatically transform a cmp argument into a key argument, transforming O(n log n) calls into O(n) calls, then I don't see how that could be done (a cmp argument can be a C function that is not introspectable or an arbitrarily complex python function that may be difficult to analyze and transform programmatically). The key function was introduced as a simpler way for programmers to write the commonly used decorate-sort-undecorate pattern -- compiler limitations had nothing to do with it. In general, key functions are not a terribly new or inflexible concept. The SORT BY clauses in SQL are an example. That being said, it is a fair criticism of Python's compiler that it does not do much in the way of optimizations. It does a handful of basic peephole optimizations but that is about it. Other languages like Haskell fair better in this regard. Raymond From gregor.lingl at aon.at Mon Aug 17 19:14:57 2009 From: gregor.lingl at aon.at (Gregor Lingl) Date: Tue, 18 Aug 2009 01:14:57 +0200 Subject: Splitting a string into substrings of equal size In-Reply-To: References: <4a85ffe2$0$24643$426a34cc@news.free.fr> Message-ID: <4a89e480$0$2302$91cee783@newsreader02.highway.telekom.at> Simon Forman schrieb: > On Aug 14, 8:22 pm, candide wrote: >> Suppose you need to split a string into substrings of a given size (except >> possibly the last substring). I make the hypothesis the first slice is at the >> end of the string. >> A typical example is provided by formatting a decimal string with thousands >> separator. >> >> What is the pythonic way to do this ? >> ... >> Thanks > > FWIW: > > def chunks(s, length=3): > stop = len(s) > start = stop - length > while start > 0: > yield s[start:stop] > stop, start = start, start - length > yield s[:stop] > > > s = '1234567890' > print ','.join(reversed(list(chunks(s)))) > # prints '1,234,567,890' or: >>> def chunks(s, length=3): i, j = 0, len(s) % length or length while i < len(s): yield s[i:j] i, j = j, j + length >>> print(','.join(list(chunks(s)))) 1,234,567,890 >>> print(','.join(list(chunks(s,2)))) 12,34,56,78,90 >>> print(','.join(list(chunks(s,4)))) 12,3456,7890 Regards, Gregor From ben+python at benfinney.id.au Mon Aug 17 19:30:39 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 09:30:39 +1000 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <87ab1ykogw.fsf@benfinney.id.au> Robert Dailey writes: > On Aug 11, 3:40?pm, Bearophile wrote: > > Robert Dailey: > > > This breaks the flow of scope. Would you guys solve this > > > problem by [?] > > There are gals too here. > > It's a figure of speech. Indeed. When I use the term ?guys? as a form of address, it's intended to be gender-neutral. > And besides, why would I want programming advice from a woman? lol. No, that's not worth any laughter, especially because there are still too many people who seriously think that way. It's totally unacceptable. Please don't promote sexist garbage like that here. -- \ ?With Lisp or Forth, a master programmer has unlimited power | `\ and expressiveness. With Python, even a regular guy can reach | _o__) for the stars.? ?Raymond Hettinger | Ben Finney From jearl at notengoamigos.org Mon Aug 17 19:30:59 2009 From: jearl at notengoamigos.org (Jason Earl) Date: Mon, 17 Aug 2009 17:30:59 -0600 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: <87ocqerpak.fsf@notengoamigos.org> Xah Lee writes: > Fresh out of the oven: > > ? How to use and setup Emacs's whitespace-mode > http://xahlee.org/emacs/whitespace-mode.html > > Xah > ? http://xahlee.org/ Xah, I disagree with you about the usefulness of whitespace-mode's defaults, and I certainly disagree with the need to use profanity on your usenet post on the subject, but it is hard to argue against your whitespace-mode.html page. Very well done. Thanks, Jason From jgardner at jonathangardner.net Mon Aug 17 19:55:49 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 17 Aug 2009 16:55:49 -0700 (PDT) Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: <4fa932a9-3f8e-4882-ba53-2715ba15c7cf@32g2000yqj.googlegroups.com> On Aug 17, 3:26?pm, Gilles Ganault wrote: > Hello, > > ? ? ? ? I need to convert DD MM YYYY dates into the MySQL-friendly > YYYY-MM-DD, and translate the month name from literal French to its > numeric equivalent (eg. "Janvier" into "01"). > > Here's an example: > > SELECT dateinscription, dateconnexion FROM membres LIMIT 1; > 26 Mai 2007|17 Ao?t 2009 - 09h20 > > I'd like to update the row into "2007-05-26" and "2009-08-17 09:20", > respectively. > > What is the best way to do this in Python? > > Thank you. From cmpython at gmail.com Mon Aug 17 19:58:28 2009 From: cmpython at gmail.com (Che M) Date: Mon, 17 Aug 2009 16:58:28 -0700 (PDT) Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: On Aug 17, 6:26?pm, Gilles Ganault wrote: > Hello, > > ? ? ? ? I need to convert DD MM YYYY dates into the MySQL-friendly > YYYY-MM-DD, and translate the month name from literal French to its > numeric equivalent (eg. "Janvier" into "01"). > > Here's an example: > > SELECT dateinscription, dateconnexion FROM membres LIMIT 1; > 26 Mai 2007|17 Ao?t 2009 - 09h20 > > I'd like to update the row into "2007-05-26" and "2009-08-17 09:20", > respectively. > > What is the best way to do this in Python? > > Thank you. Likely this is not the best way, but I would do, for the first one (and the same idea for the second): def convert(date): frenchdict = {'Mai':'May'} #etc... day = mystring[:2] month = frenchdict[ mystring[3:6] ] year = mystring[7:11] newdate = year+'-'+month+'-'+day print 'newdate is ', newdate From sjmachin at lexicon.net Mon Aug 17 19:59:21 2009 From: sjmachin at lexicon.net (John Machin) Date: Mon, 17 Aug 2009 16:59:21 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <56159dcf-b27d-418f-a8a4-0e4ebb71faa3@c14g2000yqm.googlegroups.com> On Aug 12, 6:52?am, Robert Dailey wrote: > On Aug 11, 3:40?pm, Bearophile wrote: > > > Robert Dailey: > > > > This breaks the flow of scope. Would you guys solve this > > > problem by moving failMsg into global scope? > > > Perhaps through some other type of syntax? > > > There are gals too here. > > This may help:http://docs.python.org/library/textwrap.html#textwrap.dedent > > > Bye, > > bearophile > > It's a figure of speech. And besides, why would I want programming > advice from a woman? lol. Thanks for the help. Please consider having an attitude transplant. From jgardner at jonathangardner.net Mon Aug 17 20:05:28 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 17 Aug 2009 17:05:28 -0700 (PDT) Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: On Aug 17, 3:26?pm, Gilles Ganault wrote: > ? ? ? ? I need to convert DD MM YYYY dates into the MySQL-friendly > YYYY-MM-DD, and translate the month name from literal French to its > numeric equivalent (eg. "Janvier" into "01"). > > Here's an example: > > SELECT dateinscription, dateconnexion FROM membres LIMIT 1; > 26 Mai 2007|17 Ao?t 2009 - 09h20 > > I'd like to update the row into "2007-05-26" and "2009-08-17 09:20", > respectively. > > What is the best way to do this in Python? > Unfortunately, there isn't any string to date parsers in the built- ins. Not to worry, though, since writing your own is easy, especially if you use regular expressions from the re module. I suggest using an RE such as: r"(?P\d+)\s+(?P\w+)\s+(?P\d+)" If you want to translate month names to month numbers, then you need some sort of dict to do so. Unfortunately, there isn't a terrific standard for this, so your best bet is to put it in some file somewhere, or even hard-code it in your code. (Month names won't change over the lifetime of your program, so it's reasonable to put them in your code somewhere.) month_names_to_numbers = { 'jan':1, ... } Once you have the year, month, and date, formatting it is trivial with the built-in formatter. "%04d-%02d%02d %02d:%02d" % (year, month, date, hour, minute) The variety of date formats out there have prevented a universal, clean solution to this problem. Until we all start sticking to the same conventions, we will always have to write code to translate dates from one format to another. From jgardner at jonathangardner.net Mon Aug 17 20:14:56 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 17 Aug 2009 17:14:56 -0700 (PDT) Subject: Strongly typed list References: <7718922b-c72c-4a7e-90a3-098318063013@n11g2000yqb.googlegroups.com> Message-ID: On Aug 17, 2:19?pm, ???? ??????? wrote: > Please could you lead me to a way or a good IDE that makes developing > huge projects in python more easier than what i found.Now i am using > eclips. Actually it is very hard to remember all my classes methods > and attributes or copy and paste them each time. > Thanks very much for your interest > Hani Almousli..... You're relying on your IDE too much. You should rely on the code and on your own notes. Your project should never get big because there is no reason to throw in a bunch of useless code. Think of the simplest way to get your job done. Then write that in pseudo-code. Finally, run it in Python to see if it actually works. You may be surprised with how far that will get you. If you are having problems remembering the attributes and methods of your instances, you are probably using too many attributes and methods, their names are too long, or you have too many arguments to each method. Keep the interfaces between parts as simple as possible. If you still have a big project, then break it up into several smaller, re-usable, and independent modules. Keep the interfaces as simple as possible, and never write code that does anything but Duck- Typing. From rami.chowdhury at gmail.com Mon Aug 17 20:18:33 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Mon, 17 Aug 2009 17:18:33 -0700 Subject: Converting DD MM YYYY into YYYY-MM-DD? In-Reply-To: References: Message-ID: Correct me if I'm wrong, but doesn't http://docs.python.org/library/datetime.html#datetime.datetime.strptime do this? >>> import locale >>> locale.setlocale(locale.LC_ALL, 'FR') 'French_France.1252' >>> date_str = '05 Mai 2009 - 18h25' >>> fmt = '%d %B %Y - %Hh%M' >>> date_obj = datetime.strptime(date_str, fmt) >>> date_obj datetime.datetime(2009, 5, 5, 18, 25) >>> date_obj.strftime('%Y-%m-%d %H:%M') '2009-05-05 18:25' If you're using a recent enough version of Python (2.5 and up) I'd imagine that's the best way to do it? On Mon, 17 Aug 2009 16:58:28 -0700, Che M wrote: > On Aug 17, 6:26?pm, Gilles Ganault wrote: >> Hello, >> >> ? ? ? ? I need to convert DD MM YYYY dates into the MySQL-friendly >> YYYY-MM-DD, and translate the month name from literal French to its >> numeric equivalent (eg. "Janvier" into "01"). >> >> Here's an example: >> >> SELECT dateinscription, dateconnexion FROM membres LIMIT 1; >> 26 Mai 2007|17 Ao?t 2009 - 09h20 >> >> I'd like to update the row into "2007-05-26" and "2009-08-17 09:20", >> respectively. >> >> What is the best way to do this in Python? >> >> Thank you. > > Likely this is not the best way, but I would do, for > the first one (and the same idea for the second): > > def convert(date): > frenchdict = {'Mai':'May'} #etc... > day = mystring[:2] > month = frenchdict[ mystring[3:6] ] > year = mystring[7:11] > newdate = year+'-'+month+'-'+day > print 'newdate is ', newdate > -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From cmpython at gmail.com Mon Aug 17 20:19:59 2009 From: cmpython at gmail.com (Che M) Date: Mon, 17 Aug 2009 17:19:59 -0700 (PDT) Subject: GUI interface builder for python References: <21bca3cf-b2c7-47d7-9142-26c9fd015f92@r27g2000vbn.googlegroups.com> Message-ID: <02ec7cd9-e749-46d3-8b25-75d85794f292@o35g2000vbi.googlegroups.com> On Aug 17, 2:26?pm, axl456 wrote: > On Aug 17, 1:59?am, "L at D@n" wrote: > > > Which is the best GUI interface builder with drag and drop > > capabilities. > > I am using Ubuntu GNU/Linux. > > Please help me. > > Thank you. > > boa is really nice.. Boa (Boa Constructor) is really nice for wxPython GUI work, but it has some bugs when using Linux that might be dealbreakers for the user. At least I have had problems on Ubuntu 8.10 64 bit (but none or very few with WinXP). For those that might care, they are (as of now, Boa 0.6.1-4) are: - The File -> New option is cut off in the menu. But that can be gotten around by using the Palette to choose the same options. - No gridlines in the Frame Designer (makes it harder to use) - Some problems with the height of the rows in the Inspector, at least with 64 bit Ubuntu, some of which can be fixed with this workaround: https://bugs.launchpad.net/ubuntu/+source/boa-constructor/+bug/313952 and there is a note there saying it has been patched in a 0.6.1-6 version in a Debian repository. Haven't tried. - I have had some random shutdowns, but not many. Che From ben+python at benfinney.id.au Mon Aug 17 20:20:05 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 10:20:05 +1000 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: <8763cmkm6i.fsf@benfinney.id.au> Gilles Ganault writes: > I need to convert DD MM YYYY dates into the MySQL-friendly > YYYY-MM-DD This is not specific to MySQL. It is the common international standard date representation format defined by ISO 8601. > and translate the month name from literal French to its numeric > equivalent (eg. "Janvier" into "01"). The simplest way to do this would be by a mapping from month-name to month-number. An obvious, and wrong, approach to this would be to hard-code the twelve month names into your program data. Instead, you should generate the map based on the standard library (in this case, the underlying C standard library) locale database : >>> import locale >>> locale.setlocale(locale.LC_TIME, "en_AU.UTF-8") >>> months = dict( ... (locale.nl_langinfo(getattr(locale, key)), i) ... for (key, i) in ( ... ('MON_%(i)d' % vars(), i) ... for i in range(1, 12+1))) >>> import pprint >>> pprint.pprint(months) {'April': 4, 'August': 8, 'December': 12, 'February': 2, 'January': 1, 'July': 7, 'June': 6, 'March': 3, 'May': 5, 'November': 11, 'October': 10, 'September': 9} Of course, if you can avoid having to generate this mapping at all in your program, that's best; see below. > Here's an example: > > SELECT dateinscription, dateconnexion FROM membres LIMIT 1; > 26 Mai 2007|17 Ao?t 2009 - 09h20 > > I'd like to update the row into "2007-05-26" and "2009-08-17 09:20", > respectively. Storing a timestamp as a text attribute in a database seems perverse and begging for trouble. Doesn't the database have a timestamp data type? Or perhaps that's what you're trying to achieve? > What is the best way to do this in Python? The ?datetime.strptime? function will create a Python ?datetime? object from a string, parsed according to a format . I don't know whether that function allows for month names in the current locale (as set by ?locale.setlocale(locale.LC_TIME, ?)?). If it does, that's the right way, since it doesn't involve explciitly generating the mapping as shown above. Use your preferred Python-to-database library to feed that ?datetime? object directly to the database and store it in an attribute of the native database timestamp type. Then, format the timestamp value at the point of outputting that value, instead of storing the text representation in the database. -- \ ?To succeed in the world it is not enough to be stupid, you | `\ must also be well-mannered.? ?Voltaire | _o__) | Ben Finney From mensanator at aol.com Mon Aug 17 20:40:42 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 17 Aug 2009 17:40:42 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> Message-ID: <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> On Aug 17, 4:06?pm, Carl Banks wrote: > On Aug 17, 10:03?am, Jean-Michel Pichavant > wrote: > > > I'm no English native, but I already heard women/men referring to a > > group as "guys", no matter that group gender configuration. It's even > > used for group composed exclusively of women. Moreover it looks like a > > *very* friendly form, so there is really nothing to worry about it. > > I like how being very friendly means calling people after a guy who > tried to blow up the English Parliament. So? > > Carl Banks From pavlovevidence at gmail.com Mon Aug 17 21:04:58 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 18:04:58 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> Message-ID: On Aug 17, 5:40?pm, Mensanator wrote: > On Aug 17, 4:06?pm, Carl Banks wrote: > > > On Aug 17, 10:03?am, Jean-Michel Pichavant > > wrote: > > > > I'm no English native, but I already heard women/men referring to a > > > group as "guys", no matter that group gender configuration. It's even > > > used for group composed exclusively of women. Moreover it looks like a > > > *very* friendly form, so there is really nothing to worry about it. > > > I like how being very friendly means calling people after a guy who > > tried to blow up the English Parliament. > > So? I also like how making an amusing pointless observation gets people all huffy. (BTW, lest anyone is not aware, that is the origin of the word "guy", this was not some random association.) Carl Banks From magawake at gmail.com Mon Aug 17 21:33:29 2009 From: magawake at gmail.com (Mag Gam) Date: Mon, 17 Aug 2009 21:33:29 -0400 Subject: unittest In-Reply-To: <1cbd6f830908160625m5a8ffa9er7e34c203f30fca49@mail.gmail.com> References: <1cbd6f830908142028v638a4c06jf0f859be712e724c@mail.gmail.com> <1cbd6f830908160625m5a8ffa9er7e34c203f30fca49@mail.gmail.com> Message-ID: <1cbd6f830908171833p73109091ga612b2ec719d28eb@mail.gmail.com> all, thank you very much!!! Now my question is, how do I simulate a argv? My program has take an argv, like "foo.py File" is necessary. How and where do I put it in my test? I suppose in the setUp(), but I am not sure how. any thoughts or ideas? TIA On Sun, Aug 16, 2009 at 9:25 AM, Mag Gam wrote: > John: > > Well, this is actually a script which wraps around another application. :-) > My goal is when I introduce a new feature I don't want to break old > stuff so instead of me testing manually I want to build a framework of > tests. > > > > On Sat, Aug 15, 2009 at 11:37 PM, John Haggerty wrote: >> This is an interesting question. I am just wondering: do you really have >> that many features that it would be impossible to just have a shell script >> run specific types of input or tests? >> >> When I did programming in the past for education they just had lists of >> input data and we ran the program against the test data. >> >> I just get slightly confused when "test suites" start to have to apply? >> >> On Fri, Aug 14, 2009 at 9:28 PM, Mag Gam wrote: >>> >>> I am writing an application which has many command line arguments. >>> For example: foo.py -args "bar bee" >>> >>> I would like to create a test suit using unittest so when I add >>> features to "foo.py" I don't want to break other things. I just heard >>> about unittest and would love to use it for this type of thing. >>> >>> so my question is, when I do these tests do I have to code them into >>> foo.py? I prefer having a footest.py which will run the regression >>> tests. Any thoughts about this? >>> >>> TIA >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >> >> > From ben+python at benfinney.id.au Mon Aug 17 22:06:37 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 12:06:37 +1000 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: <87skfpkh8y.fsf@benfinney.id.au> Jonathan Gardner writes: > Unfortunately, there isn't any string to date parsers in the built- > ins. Fortunately, Python 2.5 or later has the ?datetime.strptime? function. -- \ ?You could augment an earwig to the point where it understood | `\ nuclear physics, but it would still be a very stupid thing to | _o__) do!? ?The Doctor, _The Two Doctors_ | Ben Finney From jgardner at jonathangardner.net Mon Aug 17 22:31:36 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 17 Aug 2009 19:31:36 -0700 (PDT) Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <8763cmkm6i.fsf@benfinney.id.au> Message-ID: <91da9c54-a152-469b-81b0-65b99a532a1a@d4g2000yqa.googlegroups.com> On Aug 17, 5:20?pm, Ben Finney wrote: > > Instead, you should generate the map based on the standard library (in > this case, the underlying C standard library) locale database > : > Does Windows support POSIX locales? From ben+python at benfinney.id.au Mon Aug 17 22:32:06 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 12:32:06 +1000 Subject: unittest References: <1cbd6f830908142028v638a4c06jf0f859be712e724c@mail.gmail.com> <1cbd6f830908160625m5a8ffa9er7e34c203f30fca49@mail.gmail.com> Message-ID: <87ocqdkg2h.fsf@benfinney.id.au> Mag Gam writes: > all, thank you very much!!! > > Now my question is You would do well to ask more about testing in Python on the focussed forum for that topic, the ?testing-in-python? mailing list . -- \ ?If it ain't bust don't fix it is a very sound principle and | `\ remains so despite the fact that I have slavishly ignored it | _o__) all my life.? ?Douglas Adams | Ben Finney From jgardner at jonathangardner.net Mon Aug 17 22:36:24 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 17 Aug 2009 19:36:24 -0700 (PDT) Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <87skfpkh8y.fsf@benfinney.id.au> Message-ID: On Aug 17, 7:06?pm, Ben Finney wrote: > Jonathan Gardner writes: > > Unfortunately, there isn't any string to date parsers in the built- > > ins. > > Fortunately, Python 2.5 or later has the ?datetime.strptime? function. > Hate to weasel out of this one, but the language that strptime provides is pretty limited. I don't find it useful except in the trivial cases. Same goes for strftime. Also, both of these are very Western European centric. Yes, Asian languages are supported but not naturally. From jgardner at jonathangardner.net Mon Aug 17 22:38:34 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 17 Aug 2009 19:38:34 -0700 (PDT) Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: On Aug 17, 5:18?pm, "Rami Chowdhury" wrote: > > >>> import locale > >>> locale.setlocale(locale.LC_ALL, 'FR') locale is nice when you only have a single thread. Webservers aren't single threaded. You can't serve up one page for one locale and then another in another locale without seeing very, very weird behavior. From ben+python at benfinney.id.au Mon Aug 17 22:46:24 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 12:46:24 +1000 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <8763cmkm6i.fsf@benfinney.id.au> <91da9c54-a152-469b-81b0-65b99a532a1a@d4g2000yqa.googlegroups.com> Message-ID: <87k511kfen.fsf@benfinney.id.au> Jonathan Gardner writes: > On Aug 17, 5:20?pm, Ben Finney wrote: > > Instead, you should generate the map based on the standard library (in > > this case, the underlying C standard library) locale database > > : > > Does Windows support POSIX locales? If it does not, it should :-) since it addresses the problem in one standard place. It would be foolish for Python to re-implement that functionality when presumably the operating system already knows how to map between dates and locale-specific text representations. You'll need to check the operating system documentation for what alternative it might provide. -- \ ?I got fired from my job the other day. They said my | `\ personality was weird. ? That's okay, I have four more.? | _o__) ?Bug-Eyed Earl, _Red Meat_ | Ben Finney From af2012 at gmail.com Mon Aug 17 22:49:31 2009 From: af2012 at gmail.com (Allan Fong) Date: Mon, 17 Aug 2009 22:49:31 -0400 Subject: New to python Message-ID: <62763f750908171949q2d9029ddo1df40b8850f945b6@mail.gmail.com> Hi! I'm fairly new to Python. I understand the basics basics but I'm been trying to write a simple python code that will let me read input data from my USB drive and write it in a text file and I am so lost. Can anyone help or direct me to some resources? Thank you! -------------- next part -------------- An HTML attachment was scrubbed... URL: From rurpy at yahoo.com Mon Aug 17 23:19:16 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 17 Aug 2009 20:19:16 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> <3d808272-6e56-4cf1-90df-8e5201df02df@c34g2000yqi.googlegroups.com> <13be5a11-612b-4fc5-a220-cc9aba2e4f8c@z31g2000yqd.googlegroups.com> Message-ID: <611687df-e755-4910-9042-5dab20de1a7e@c34g2000yqi.googlegroups.com> On 08/13/2009 08:46 AM, Paul Boddie wrote: > On 13 Aug, 16:05, ru... at yahoo.com wrote: >> All the above not withstanding, I too think a wiki is worth >> trying. But without doing a lot more than just "setting up >> a wiki", I sadly believe even a python.org supported wiki >> is doomed to failure. > > The ones on python.org seem to function reasonably well. I accept that > they could be more aggressively edited, but this isn't done because > there's a compromise between letting people contribute and keeping > things moderately coherent, with the former being favoured. For other > purposes, it would be quite acceptable to favour editorial control. Yes, I agree. I should have mentioned this as an exception in my "wikis suck" diatribe. Although it far better than most wiki's I've seen, it is still pretty easy to find signs of typical wiki-ness. On the Documentation page my first click was on AnnotableDocumentation: 404. Second try, DoumentationDiscussion: two very short paragraphs dated 2003. After that I found some useful (in general though not what I was looking for) information but not a good first impression. (Well not exactly first, in fairness I have used other wiki sections such as the Templating page and found them very useful.) > I won't argue that providing infrastructure solves a problem - that's > precisely the kind of thing I was criticising when I noted that some > people will readily criticise the choice of tools to do a job instead > of focusing on the job that has to be done - and you need people who > are reasonably competent editors, but Wiki solutions remove a lot of > technical barriers. I'm not arguing for the flavour of Wiki which > implies unfettered, anonymous access from everyone on the Internet, > either: the kind of Wiki that detractors portray all Wiki solutions as > being in order to further their super-special "it has to fit like a > glove or it's totally unusable" software agenda. It's quite possible > to have people with somewhat more privileges than others in order to > keep the peace, and they don't all need to have an entrenched > editorial interest: on the current python.org Wiki sites, most of the > administrators don't have an active interest in most of the content, > but they are able to exercise control when it's clear that some > contributors aren't particularly interested in actually improving the > content. > > As well as having an active community effort around the existing > python.org Wiki sites, there are also people who are interested in > improving these offerings. What worries me is that despite such > activity and such interest, many people will continue to lament the > lack of vitality (or whatever other metric) of the general python.org > offering, whilst retaining a blind spot for the obvious contribution > that the Wikis can make to such improvement efforts. I encourage > people to use wiki.python.org a lot more, should they be looking to > improve the wealth of information provided by the community. Again, I agree with all of that. But my main interest is in improving the standard docs that are distributed with Python and I question a wiki's role in that. I took a look at the PHP docs last night which seem pretty well done. The User Comments looked rather as I expected, there was useful info but most did not contain documentation quality writing. So if they are used as a source for improving the docs, there clearly must be a pretty large amount of editorial effort required, although much of it is probably just filtering out comments that don't provide any information appropriate for inclusion in the docs. They list 38 names under "User Note Maintainers" (http://www.php.net/manual/en/preface.php) Unfortunately I couldn't find a description of what these people actually do. I don't know how much work was involved in removing the comments that are no longer there. Again, I don't mean to sound like I am dissing the idea of annotatable docs -- I think it is a good idea and will provide useful supplementary information. But I continue to question whether this will result in improvements in the docs themselves (which is my main interest) unless: 1. The purpose of the wiki is clearly "marketed" as soliciting suggestions, rewrites, etc destined ultimately for inclusion in the docs. 2. There is a dedicated core of doc-competent volunteers focused on extracting, condensing and editing the user comments and getting them into the docs, either directly (if the volunteers are committers -- unlikely) or through the existing tracker system. And this still fails to address the problems with the docs that aren't amenable to fixing via the tracker system. At least two of those problems are: 1. Difficultly in making large organizational changes. 2. Prevalent opinion among doc approvers that the current excessively terse style is desirerable. From rami.chowdhury at gmail.com Mon Aug 17 23:22:05 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Mon, 17 Aug 2009 20:22:05 -0700 Subject: Converting DD MM YYYY into YYYY-MM-DD? In-Reply-To: <87k511kfen.fsf@benfinney.id.au> References: <91da9c54-a152-469b-81b0-65b99a532a1a@d4g2000yqa.googlegroups.com> <87k511kfen.fsf@benfinney.id.au> Message-ID: <200908172022.05517.rami.chowdhury@gmail.com> ---- My sample interactive session (locale.setlocale and all) was on a 32-bit Vista install of Python 2.5, so it works on that... --- Rami Chowdhury "A man with a watch knows what time it is. A man with two watches is never sure". -- Segal's Law 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Monday 17 August 2009 19:46:24 Ben Finney wrote: > Jonathan Gardner writes: > > On Aug 17, 5:20 pm, Ben Finney wrote: > > > Instead, you should generate the map based on the standard library (in > > > this case, the underlying C standard library) locale database > > > > >#lo...>: > > > > Does Windows support POSIX locales? > > If it does not, it should :-) since it addresses the problem in one > standard place. It would be foolish for Python to re-implement that > functionality when presumably the operating system already knows how to > map between dates and locale-specific text representations. > > You'll need to check the operating system documentation for what > alternative it might provide. > > -- > \ ?I got fired from my job the other day. They said my | > `\ personality was weird. ? That's okay, I have four more.? | > _o__) ?Bug-Eyed Earl, _Red Meat_ | > Ben Finney From clp2 at rebertia.com Mon Aug 17 23:22:50 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 17 Aug 2009 20:22:50 -0700 Subject: New to python In-Reply-To: <62763f750908171949q2d9029ddo1df40b8850f945b6@mail.gmail.com> References: <62763f750908171949q2d9029ddo1df40b8850f945b6@mail.gmail.com> Message-ID: <50697b2c0908172022ta35e948y8613e70463f28345@mail.gmail.com> On Mon, Aug 17, 2009 at 7:49 PM, Allan Fong wrote: > Hi! I'm fairly new to Python.? I understand the basics basics but I'm been > trying to write a simple python code that will let me read input data from > my USB drive and write it in a text file and I am so lost.? Can anyone help > or direct me to some resources?? Thank you! Working with files: http://docs.python.org/library/stdtypes.html#file-objects Reading+writing common file formats: JSON: http://docs.python.org/library/json.html CSV: http://docs.python.org/library/csv.html Cheers, Chris -- http://blog.rebertia.com From roykty at gmail.com Mon Aug 17 23:45:37 2009 From: roykty at gmail.com (roykty at gmail.com) Date: Mon, 17 Aug 2009 20:45:37 -0700 (PDT) Subject: Text lost when I write file Message-ID: Dear All, I try to write text into a file but some text lost when the size of the text content is over 32K. Is that relate to the buffer of the python and any setting can solve this problem??. Regards Roy From mensanator at aol.com Mon Aug 17 23:49:29 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 17 Aug 2009 20:49:29 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> Message-ID: On Aug 17, 8:04?pm, Carl Banks wrote: > On Aug 17, 5:40?pm, Mensanator wrote: > > > On Aug 17, 4:06?pm, Carl Banks wrote: > > > > On Aug 17, 10:03?am, Jean-Michel Pichavant > > > wrote: > > > > > I'm no English native, but I already heard women/men referring to a > > > > group as "guys", no matter that group gender configuration. It's even > > > > used for group composed exclusively of women. Moreover it looks like a > > > > *very* friendly form, so there is really nothing to worry about it. > > > > I like how being very friendly means calling people after a guy who > > > tried to blow up the English Parliament. > > > So? > > I also like how making an amusing pointless observation Pointless, yes, but what was amusing abot the observation? > gets people all huffy. That wasn't huffy. You want to see huffy, make a wisecrack comparing mothballs to Zyklon B, you'll REALLY get a load of huffy replies. > > (BTW, lest anyone is not aware, that is the origin of the word "guy", It most certainly is not. Maybe the origin of that word's useage as a genric reference to a male, but you didn't say that. > this was not some random association.) Penny for the guy? > > Carl Banks From tjreedy at udel.edu Mon Aug 17 23:56:58 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Aug 2009 12:56:58 +0900 Subject: Python 'for' loop is memory inefficient In-Reply-To: <20090817194155.8740.902674574.divmod.xquotient.69@localhost.localdomain> References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> <20090817194155.8740.902674574.divmod.xquotient.69@localhost.localdomain> Message-ID: exarkun at twistedmatrix.com wrote: > There's a lot of things in Python that I don't strictly *need*. That > doesn't mean that they wouldn't be welcome if I could have them. Getting > rid of the range/xrange dichotomy would improve things. The developers agreed a couple of years ago. Starting using 3.1 if you want this. Since 'range' could refer to a user-defined object, rather than the builtin function, there is no way the interpreter should substitute 'xrange'. tjr From tjreedy at udel.edu Tue Aug 18 00:06:50 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 18 Aug 2009 13:06:50 +0900 Subject: Social problems of Python doc [was Re: Python docs disappointing] In-Reply-To: References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> Message-ID: Nathan Keel wrote: > idiot ... asshole > absolutely clueless ... idiot ...incredibly > arrogant, yet incredibly clueless. To me, such name-calling is as obnoxious as the intended target. tjr From clp2 at rebertia.com Tue Aug 18 00:09:34 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 17 Aug 2009 21:09:34 -0700 Subject: Text lost when I write file In-Reply-To: References: Message-ID: <50697b2c0908172109m906fb7ape3d02a8a0c4bba53@mail.gmail.com> On Mon, Aug 17, 2009 at 8:45 PM, roykty at gmail.com wrote: > Dear All, > > I try to write text into a file but some text lost when the size of > the text content is over 32K. > Is that relate to the buffer of the python and any setting can solve > this problem??. Please show us the code you're using. Cheers, Chris -- http://blog.rebertia.com From ben+python at benfinney.id.au Tue Aug 18 00:23:26 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 14:23:26 +1000 Subject: Text lost when I write file References: Message-ID: <87fxbpkawx.fsf@benfinney.id.au> Chris Rebert writes: > On Mon, Aug 17, 2009 at 8:45 PM, roykty at gmail.com wrote: > > I try to write text into a file but some text lost when the size of > > the text content is over 32K. > > Is that relate to the buffer of the python and any setting can solve > > this problem??. > > Please show us the code you're using. Not the whole danged thing, of course; please show a minimal executable example that demonstrates the behaviour. -- \ ?I do not believe in immortality of the individual, and I | `\ consider ethics to be an exclusively human concern with no | _o__) superhuman authority behind it.? ?Albert Einstein, letter, 1953 | Ben Finney From steven at REMOVE.THIS.cybersource.com.au Tue Aug 18 00:34:57 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 04:34:57 GMT Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: On Mon, 17 Aug 2009 14:31:51 -0700, Chris Rebert wrote: >> Oh come on, one newbie making an off-color joke is not any sort of >> reflection of the community as a whole. >> >> Anyway it's pretty naive to expect what is now a large community to >> avoid bad eggs altogether. ?Price you pay for popularity. > > Agreed on both points, but the lack of any reprimanding for making said > inappropriate joke /would/ reflect badly on the community. Fortunately, > said person's behavior has now been condemned by virtue of this thread; > it's a step in the right direction. Pardon me, but he has been slapped, a number of times. Check the original thread, you'll see that the OP was slapped for his stupid joke, then slapped again for another dismissive comment after the first reprimand. You might argue he wasn't slapped *enough*, but that's another story. Personally, I thought he was either trolling for a reaction, or he was an old-fuddy-duddy (regardless of biological age), and either way reacting to his comments would just draw attention to something which is best dealt with with a cold-shoulder. Reinforce the good behaviour, shun the bad. The comments were made a week ago -- why the sudden flurry of attention? -- Steven From pavlovevidence at gmail.com Tue Aug 18 00:35:48 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 17 Aug 2009 21:35:48 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> Message-ID: <86bb893a-344a-4c7b-9fc6-67d9f42c7607@q14g2000vbi.googlegroups.com> On Aug 17, 8:49?pm, Mensanator wrote: > On Aug 17, 8:04 pm, Carl Banks wrote: > > > > > > > On Aug 17, 5:40 pm, Mensanator wrote: > > > > On Aug 17, 4:06 pm, Carl Banks wrote: > > > > > On Aug 17, 10:03 am, Jean-Michel Pichavant > > > > wrote: > > > > > > I'm no English native, but I already heard women/men referring to a > > > > > group as "guys", no matter that group gender configuration. It's even > > > > > used for group composed exclusively of women. Moreover it looks like a > > > > > *very* friendly form, so there is really nothing to worry about it. > > > > > I like how being very friendly means calling people after a guy who > > > > tried to blow up the English Parliament. > > > > So? > > > I also like how making an amusing pointless observation > > Pointless, yes, but what was amusing abot the observation? The irony that in being friendly that you're calling someone a terrorist. I guess I shouldn't have expected you to get it. > > gets people all huffy. > > That wasn't huffy. You want to see huffy, make a wisecrack > comparing mothballs to Zyklon B, you'll REALLY get a load > of huffy replies. > > > (BTW, lest anyone is not aware, that is the origin of the word "guy", > > It most certainly is not. My dictionary disagrees with you. > Maybe the origin of that > word's useage as a genric reference to a male, but > you didn't say that. > > > this was not some random association.) > > Penny for the guy? Probably that phrase was part of the word's gradual common adoption. Carl Banks From steven at REMOVE.THIS.cybersource.com.au Tue Aug 18 00:37:33 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 04:37:33 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> Message-ID: On Mon, 17 Aug 2009 18:04:58 -0700, Carl Banks wrote: > On Aug 17, 5:40?pm, Mensanator wrote: >> On Aug 17, 4:06?pm, Carl Banks wrote: >> >> > On Aug 17, 10:03?am, Jean-Michel Pichavant >> > wrote: >> >> > > I'm no English native, but I already heard women/men referring to a >> > > group as "guys", no matter that group gender configuration. It's >> > > even used for group composed exclusively of women. Moreover it >> > > looks like a *very* friendly form, so there is really nothing to >> > > worry about it. >> >> > I like how being very friendly means calling people after a guy who >> > tried to blow up the English Parliament. >> >> So? > > I also like how making an amusing pointless observation gets people all > huffy. > > (BTW, lest anyone is not aware, that is the origin of the word "guy", > this was not some random association.) Yes, apparently the slang term "guy" for "man" (and these days, "person") was derived from Guy Fawkes: http://www.worldwidewords.org/weirdwords/ww-guy1.htm but the name itself is much older, and comes from Old German for "wood" or "warrior". In old French, it was "Gy", and in Italian (and presumably Dutch) it is "Guido". http://www.thinkbabynames.com/meaning/1/Guy http://www.blurtit.com/q113276.html You'll also note that "guy" the noun has a number of meanings: http://wordnetweb.princeton.edu/perl/webwn?s=guy I don't know if there's any point to all this, but it's interesting, even if off-topic. -- Steven From steven at REMOVE.THIS.cybersource.com.au Tue Aug 18 00:37:46 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 04:37:46 GMT Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <269572f2-5968-479b-a7e6-d3354a769250@j9g2000prh.googlegroups.com> <60bd3cab-1cab-4677-b640-8d126343615a@d9g2000prh.googlegroups.com> <7xtz06cg7m.fsf@ruckus.brouhaha.com> Message-ID: On Mon, 17 Aug 2009 13:56:13 -0700, Paul Rubin wrote: > Python 3.0 went overboard by actually removing the cmp argument and > requiring use of the key argument. That requires various kludges if the > key is, say, a tree structure that has to be recursively compared with > another such structure. Maybe then can bring back cmp someday. I'm having trouble understanding this, which may be my weakness rather than yours, but could you give an actual (simplified?) example I can run, where cmp would work but key wouldn't? -- Steven From aahz at pythoncraft.com Tue Aug 18 00:45:39 2009 From: aahz at pythoncraft.com (Aahz) Date: 17 Aug 2009 21:45:39 -0700 Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) References: Message-ID: In article , Steven D'Aprano wrote: > >The comments were made a week ago -- why the sudden flurry of attention? Mainly an opportunity to flog the new diversity list. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From naveen.garg at gmail.com Tue Aug 18 00:45:57 2009 From: naveen.garg at gmail.com (naveen) Date: Mon, 17 Aug 2009 21:45:57 -0700 (PDT) Subject: define class over 2 files Message-ID: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> Is it possible to split up a class definition over multiple files? From contact at xavierho.com Tue Aug 18 00:58:58 2009 From: contact at xavierho.com (Xavier Ho) Date: Tue, 18 Aug 2009 14:58:58 +1000 Subject: define class over 2 files In-Reply-To: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> Message-ID: <2d56febf0908172158l760256rc703d7d87f04e509@mail.gmail.com> On Tue, Aug 18, 2009 at 2:45 PM, naveen wrote: > Is it possible to split up a class definition over multiple files? > - Answer in short, I don't think so. Now why would you want to do that? There is another solution - have a main class for shared methods, and have other classes [in different files, perhaps] inherit from it. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Tue Aug 18 01:07:14 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 15:07:14 +1000 Subject: Diversity in Python References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <87bpmdk8vx.fsf@benfinney.id.au> Steven D'Aprano writes: > The comments were made a week ago -- why the sudden flurry of > attention? In my case, it's because I was ignoring the thread in which they were made. The change of subject drew them to my attention, where I saw the community response was (IMO) insufficient at the time, so I acted to correct that. Now that the community response is (IMO) more appropriate, there's no further need to beat on those particular comments. Additional transgressions could warrant additional responses, of course. -- \ ?I got some new underwear the other day. Well, new to me.? ?Emo | `\ Philips | _o__) | Ben Finney From ariel.balter at gmail.com Tue Aug 18 01:27:57 2009 From: ariel.balter at gmail.com (abalter) Date: Mon, 17 Aug 2009 22:27:57 -0700 (PDT) Subject: Data visualization in Python References: Message-ID: <4121b29c-ebac-4f8f-b6af-e9789564cb4d@24g2000yqm.googlegroups.com> On Aug 17, 12:10?pm, kj wrote: > I'm looking for a good Python package for visualizing > scientific/statistical data. ?(FWIW, the OS I'm interested in is > Mac OS X). > > The users of this package will be experimental biologists with > little programming experience (but currently learning Python). > > (I normally visualize data using R or Mathematica, but I don't want > to saddle these novices with the task of learning yet another > language.) > > TIA! > > kynn You might also look into the pythonxy superpackage, http://www.pythonxy.com/foreword.php and http://enthought.com. From indermeet.gandhi at gmail.com Tue Aug 18 01:28:17 2009 From: indermeet.gandhi at gmail.com (inder) Date: Mon, 17 Aug 2009 22:28:17 -0700 (PDT) Subject: XML parsing with python References: Message-ID: On Aug 17, 8:31?pm, John Posner wrote: > > Use the iterparse() function of the xml.etree.ElementTree package. > > >http://effbot.org/zone/element-iterparse.htm > >http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk > > > Stefan > > iterparse() is too big a hammer for this purpose, IMO. How about this: > > ? from xml.etree.ElementTree import ElementTree > ? tree = ElementTree(None, "myfile.xml") > ? for elem in tree.findall('//book/title'): > ? ? ? print elem.text > > -John Thanks for the prompt reply . I feel let me try using iterparse. Will it be slower compared to SAX parsing ... ultimately I will have a huge xml file to parse ? Another question , I will also need to validate my xml against xsd . I would like to do this validation through the parsing tool itself . Does there exist an Unix utility which validates or even a python library call would be fine ? Thanks in advance From steven at REMOVE.THIS.cybersource.com.au Tue Aug 18 01:51:55 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 05:51:55 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> <86bb893a-344a-4c7b-9fc6-67d9f42c7607@q14g2000vbi.googlegroups.com> Message-ID: On Mon, 17 Aug 2009 21:35:48 -0700, Carl Banks wrote: >> > > > I like how being very friendly means calling people after a guy >> > > > who tried to blow up the English Parliament. >> >> > > So? >> >> > I also like how making an amusing pointless observation >> >> Pointless, yes, but what was amusing abot the observation? > > The irony that in being friendly that you're calling someone a > terrorist. Please, the term is Freedom Fighter. > I guess I shouldn't have expected you to get it. Ouch! Nasty! Is there something in the air today? People are short-tempered and grouchy all over the place... -- Steven From steven at REMOVE.THIS.cybersource.com.au Tue Aug 18 01:57:46 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 05:57:46 GMT Subject: define class over 2 files References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> Message-ID: On Mon, 17 Aug 2009 21:45:57 -0700, naveen wrote: > Is it possible to split up a class definition over multiple files? Not exactly, but you can do variations of this: In file A.py, create: class Parent: def method(self): return "Method" In file B.py, do this: import A class Child(B.parent): def another_method(self): return "Another Method" Now your class Child has two methods, method() and another_method(). Similarly, you can do this: # File A.py def function(x, y): return x+y # or something more complicated # File B.py import A def MyClass(object): def func(self, x, y): return A.function(x, y) -- Steven From stefan_ml at behnel.de Tue Aug 18 02:24:24 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 Aug 2009 08:24:24 +0200 Subject: XML parsing with python In-Reply-To: References: Message-ID: <4a8a4918$0$32672$9b4e6d93@newsspool2.arcor-online.net> inder wrote: > On Aug 17, 8:31 pm, John Posner wrote: >>> Use the iterparse() function of the xml.etree.ElementTree package. >>> http://effbot.org/zone/element-iterparse.htm >>> http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk >>> Stefan >> iterparse() is too big a hammer for this purpose, IMO. How about this: >> >> from xml.etree.ElementTree import ElementTree >> tree = ElementTree(None, "myfile.xml") >> for elem in tree.findall('//book/title'): >> print elem.text >> >> -John > > Thanks for the prompt reply . > > I feel let me try using iterparse. Will it be slower compared to SAX > parsing ... ultimately I will have a huge xml file to parse ? If you use the cElementTree module, it may even be faster. > Another question , I will also need to validate my xml against xsd . I > would like to do this validation through the parsing tool itself . In that case, you can use lxml instead of ElementTree. http://codespeak.net/lxml/ Stefan From stefan_ml at behnel.de Tue Aug 18 02:32:59 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 Aug 2009 08:32:59 +0200 Subject: XML parsing with python In-Reply-To: References: Message-ID: <4a8a4b1c$0$32679$9b4e6d93@newsspool2.arcor-online.net> John Posner wrote: >> Use the iterparse() function of the xml.etree.ElementTree package. > > iterparse() is too big a hammer for this purpose, IMO. How about this: > > from xml.etree.ElementTree import ElementTree > tree = ElementTree(None, "myfile.xml") > for elem in tree.findall('//book/title'): > print elem.text Is that really so much better than an iterparse() version? from xml.etree.ElementTree import ElementTree for _, elem in ElementTree.iterparse("myfile.xml"): if elem.tag == 'book': print elem.findtext('title') elem.clear() Stefan From deets at nospam.web.de Tue Aug 18 02:46:10 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 08:46:10 +0200 Subject: Strongly typed list In-Reply-To: <7718922b-c72c-4a7e-90a3-098318063013@n11g2000yqb.googlegroups.com> References: <7718922b-c72c-4a7e-90a3-098318063013@n11g2000yqb.googlegroups.com> Message-ID: <7ev11jF1jj25dU1@mid.uni-berlin.de> ???? ??????? schrieb: > Please could you lead me to a way or a good IDE that makes developing > huge projects in python more easier than what i found.Now i am using > eclips. Actually it is very hard to remember all my classes methods > and attributes or copy and paste them each time. > Thanks very much for your interest > Hani Almousli..... There are many really big projects written in Python - none of them with the aid of intelli-sense. What python lacks in that respect due to it's dynamic typing, it more than compensates by being faster to develop and having to write much less code. Diez From sreejithemk at gmail.com Tue Aug 18 02:46:28 2009 From: sreejithemk at gmail.com (Sreejith K) Date: Mon, 17 Aug 2009 23:46:28 -0700 (PDT) Subject: Changing Python Opcodes Message-ID: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> Hi, I know this is not the best way to do it. But I have to do it at least to make it *hard* to decompile the python bytecode. I want to distribute a software written in Python without the source. So I compiled Python from source changing some opcode values (Taking care of HAVE_ARGUMENT value) and distributed with the .pyc files. It did compile but when I'm installing additional python modules using easy_install, the import fails with a segmentation fault. It worked in a 32 bit Centos 5.2 but not on 64bit Centos 5.2. I am using python 2.5.4 source. I changed only the Include/opcode.py source with my jumbled opcode values. Was I correct here ? I would like to know what all changes to be made as to successfully compile a custom python with different opcode values ? From nospam at nospam.com Tue Aug 18 02:59:57 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 08:59:57 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: <3vjk85hapd0nuigp09qrihm6e7faliompd@4ax.com> Thanks everyone for the help. This script is just a one-shot thingie on my work host, not as a web script or anything professional. On Mon, 17 Aug 2009 17:05:28 -0700 (PDT), Jonathan Gardner wrote: >Unfortunately, there isn't any string to date parsers in the built- >ins. Not to worry, though, since writing your own is easy, especially >if you use regular expressions from the re module. I suggest using an >RE such as: > > r"(?P\d+)\s+(?P\w+)\s+(?P\d+)" I've never seen regexes like this. I'm curious to know what those mean: r = Unicode? (?P = ? means that it shouldn't be greedy, what about P? From naveen.garg at gmail.com Tue Aug 18 03:04:56 2009 From: naveen.garg at gmail.com (naveen) Date: Tue, 18 Aug 2009 00:04:56 -0700 (PDT) Subject: define class over 2 files References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> Message-ID: <6a490ec8-3536-4508-afd4-90a5cf9317b5@g10g2000yqh.googlegroups.com> > > Is it possible to split up a class definition over multiple files? > > Not exactly, but you can do variations of this: ... [subclass a class] > Steven Thanks Steven. I guess I will just preprocess the script: cat partA.py > class.py cat partB >> class.py python class.py From ben+python at benfinney.id.au Tue Aug 18 03:10:50 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 17:10:50 +1000 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <3vjk85hapd0nuigp09qrihm6e7faliompd@4ax.com> Message-ID: <874os5k35x.fsf@benfinney.id.au> Gilles Ganault writes: > Thanks everyone for the help. This script is just a one-shot thingie > on my work host, not as a web script or anything professional. > > On Mon, 17 Aug 2009 17:05:28 -0700 (PDT), Jonathan Gardner > wrote: > > r"(?P\d+)\s+(?P\w+)\s+(?P\d+)" > > I've never seen regexes like this. I'm curious to know what those > mean: Luckily, you have access to the documentation to find out. > r = Unicode? > (?P = ? means that it shouldn't be greedy, what about P? -- \ ?We reserve the right to serve refuse to anyone.? ?restaurant, | `\ Japan | _o__) | Ben Finney From ben+python at benfinney.id.au Tue Aug 18 03:13:17 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 17:13:17 +1000 Subject: define class over 2 files References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> <6a490ec8-3536-4508-afd4-90a5cf9317b5@g10g2000yqh.googlegroups.com> Message-ID: <87zl9xiohe.fsf@benfinney.id.au> naveen writes: > I guess I will just preprocess the script: > > cat partA.py > class.py > cat partB >> class.py > python class.py > This, to me, is a programming smell; not necessarily bad, but an indicator of bad practice. What is the problem you're trying to solve? I'll wager there are better ways to address it. -- \ ?Laugh and the world laughs with you; snore and you sleep | `\ alone.? ?anonymous | _o__) | Ben Finney From deets at nospam.web.de Tue Aug 18 03:19:31 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 09:19:31 +0200 Subject: Changing Python Opcodes In-Reply-To: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> References: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> Message-ID: <7ev303F2ib9r1U1@mid.uni-berlin.de> Sreejith K schrieb: > Hi, > > I know this is not the best way to do it. But I have to do it at least > to make it *hard* to decompile the python bytecode. > > I want to distribute a software written in Python without the source. > So I compiled Python from source changing some opcode values (Taking > care of HAVE_ARGUMENT value) and distributed with the .pyc files. It > did compile but when I'm installing additional python modules using > easy_install, the import fails with a segmentation fault. It worked in > a 32 bit Centos 5.2 but not on 64bit Centos 5.2. I am using python > 2.5.4 source. > > I changed only the Include/opcode.py source with my jumbled opcode > values. Was I correct here ? I would like to know what all changes to > be made as to successfully compile a custom python with different > opcode values ? As you are the one who modified your Python, you are the one responsible for debugging that - noone else can. Did you try installing the egg *without* pyc-files in there? Because naturally those shouldn't work. They shouldn't crash the interpreter either, but then again - you *did* modify it. Diez From sreejithemk at gmail.com Tue Aug 18 03:42:10 2009 From: sreejithemk at gmail.com (Sreejith K) Date: Tue, 18 Aug 2009 00:42:10 -0700 (PDT) Subject: Changing Python Opcodes References: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> <7ev303F2ib9r1U1@mid.uni-berlin.de> Message-ID: <7cfe9433-37a6-456e-8a77-b0a8f17e5f23@e27g2000yqm.googlegroups.com> On Aug 18, 12:19?pm, "Diez B. Roggisch" wrote: > Did you try installing the egg *without* pyc-files in there? Because > naturally those shouldn't work. They shouldn't crash the interpreter > either, but then again - you *did* modify it. Hi Diez, thanks for the immediate reply :) I installed the setuptools using ez_setup.py script. Then I used the easy_install to install additional modules. When importing the installed modules segfault occurs. The module I installed was TurboGears. Then I thought that it happened maybe because the easy_install script is downloading eggs for original python (I'm not sure if it is what easy_install is doing). So I also tried to install the module by downloading all the dependencies (tar.gz files) and building it. Even then segfault occured. Is there any problem in changing only the opcodes.py file ? I did something horribly wrong here. Hope someone will help... From nospam at nospam.com Tue Aug 18 03:49:41 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 09:49:41 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <3vjk85hapd0nuigp09qrihm6e7faliompd@4ax.com> <874os5k35x.fsf@benfinney.id.au> Message-ID: <10nk85le4ghbb22ogjuta10cneir6pcc8p@4ax.com> On Tue, 18 Aug 2009 17:10:50 +1000, Ben Finney wrote: >Luckily, you have access to the documentation to find out. I never used groups before. Thanks for showing me. At this point, the script is almost done, but the regex fails if the month contains accented characters (eg. "Ao?t", but fine if eg. "Jan"). Adding a line to load the French locale doesn't help :-/ Any idea what I could do to keep the regex happy? Thank you. ============== import re import apsw import locale #In case error due to accent in month name, but no soup 4 U locale.setlocale(locale.LC_ALL, 'FR') connection=apsw.Connection("test.sqlite") cursor=connection.cursor() re_inscription = re.compile(r"(?P\d+)\s+(?P\w+)\s+(?P\d+)") sql = 'SELECT id,dateinscription,dateconnexion FROM mytable' rows=list(cursor.execute(sql)) for row in rows: dateinscription = row[1] dateconnexion = row[2] #Prints OK print dateinscription m = re_inscription.search(dateinscription) if m: day = m.group("date") month = m.group("month") year = m.group("year") print "%s-%s-%s" % (year,month,day) else: print "No go" ============== From weinhand at unileoben.ac.at Tue Aug 18 03:59:20 2009 From: weinhand at unileoben.ac.at (Weinhandl Herbert) Date: Tue, 18 Aug 2009 09:59:20 +0200 Subject: Data visualization in Python In-Reply-To: References: Message-ID: <4a8a5f86$0$12126$3b214f66@aconews.univie.ac.at> Am 2009-08-17 21:10, schrieb kj: > I'm looking for a good Python package for visualizing > scientific/statistical data. (FWIW, the OS I'm interested in is > Mac OS X). > > The users of this package will be experimental biologists with > little programming experience (but currently learning Python). SciDAVis is a free application for Scientific Data Analysis and Visualization. http://scidavis.sourceforge.net/ Veusz is a scientific plotting and graphing package written in Python. http://home.gna.org/veusz/ Open source data visualization and analysis for novice and experts. Data mining through visual programming or Python scripting. Extensions for bioinformatics and text mining. Comprehensive, flexible and fast. http://www.ailab.si/orange/ > (I normally visualize data using R or Mathematica, but I don't want > to saddle these novices with the task of learning yet another > language.) hth Herbert From nitebirdz at sacredchaos.com Tue Aug 18 04:07:32 2009 From: nitebirdz at sacredchaos.com (nitebirdz at sacredchaos.com) Date: Tue, 18 Aug 2009 10:07:32 +0200 Subject: Using a Callback Function - ftplib In-Reply-To: References: <76875cdd-30c4-4a3b-8a16-d0e2061765d7@v2g2000vbb.googlegroups.com> <1euafoc8zeh0q.91hedjv5ueuh$.dlg@40tude.net> Message-ID: <20090818080731.GA12396@sevilla.sacredchaos.com> On Mon, Aug 17, 2009 at 11:10:25AM -0700, seldan24 wrote: > > I didn't even notice the higher level methods. I changed the > retrieval line to: > > ftp.nlst("testfile*.txt") > > This works great. The result is even captured in an array. I really > have no idea what the difference between a LIST and NLST is within > FTP. Never delved that deep into it. I did notice that an NLST will > return a specific FTP code if a file doesn't exist, whereas a LIST > doesn't. So, I ended up using NLST as that'll generate an > ftplib.error_perm exception. Based on if the job cares if a file is > not available or not (some do, some don't), I'll either exit, or > continue on with the file loop. > The following thread from a NetBSD mailing list may help clarify this issue: http://mail-index.netbsd.org/netbsd-users/2001/01/30/0016.html NLST returns a machine-readable list of names, while LIST returns a human-readable list. Hene the presence of the FTP code in the case of NLST. From rami.chowdhury at gmail.com Tue Aug 18 04:11:20 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 18 Aug 2009 01:11:20 -0700 Subject: Converting DD MM YYYY into YYYY-MM-DD? In-Reply-To: <10nk85le4ghbb22ogjuta10cneir6pcc8p@4ax.com> References: <874os5k35x.fsf@benfinney.id.au> <10nk85le4ghbb22ogjuta10cneir6pcc8p@4ax.com> Message-ID: <200908180111.20975.rami.chowdhury@gmail.com> Could you let me know which platform this is on (Windows, *nix)? It may be a locale encoding issue -- the locale.setlocale() function allows the second argument to be a tuple of (locale_code, encoding), as below: locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) Since this is for a one-shot (and presumably threading-agnostic) program, and a fairly trivially formatted date-string, I would suggest using datetime.strptime (http://docs.python.org/library/datetime.html#datetime.datetime.strptime) and not regular expressions (which IIRC have Issues with non-ASCII characters). ---- Rami Chowdhury "Ninety percent of everything is crap." -- Sturgeon's Law 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Tuesday 18 August 2009 00:49:41 Gilles Ganault wrote: > On Tue, 18 Aug 2009 17:10:50 +1000, Ben Finney > > wrote: > >Luckily, you have access to the documentation to find out. > > I never used groups before. Thanks for showing me. > > At this point, the script is almost done, but the regex fails if the > month contains accented characters (eg. "Ao?t", but fine if eg. > "Jan"). > > Adding a line to load the French locale doesn't help :-/ > > Any idea what I could do to keep the regex happy? > > Thank you. > > ============== > import re > import apsw > import locale > > #In case error due to accent in month name, but no soup 4 U > locale.setlocale(locale.LC_ALL, 'FR') > > connection=apsw.Connection("test.sqlite") > cursor=connection.cursor() > > re_inscription = > re.compile(r"(?P\d+)\s+(?P\w+)\s+(?P\d+)") > > sql = 'SELECT id,dateinscription,dateconnexion FROM mytable' > rows=list(cursor.execute(sql)) > for row in rows: > dateinscription = row[1] > dateconnexion = row[2] > > #Prints OK > print dateinscription > > m = re_inscription.search(dateinscription) > if m: > day = m.group("date") > month = m.group("month") > year = m.group("year") > print "%s-%s-%s" % (year,month,day) > else: > print "No go" > ============== From martin at v.loewis.de Tue Aug 18 04:12:06 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 18 Aug 2009 10:12:06 +0200 Subject: Mercurial migration: help needed Message-ID: <4A8A6256.1030009@v.loewis.de> This is a repost from two weeks ago. It didn't get much feedback last time. I still keep trying, reposting to python-list also this time. In this thread, I'd like to collect things that ought to be done but where Dirkjan has indicated that he would prefer if somebody else did it. Item 1 ------ The first item is build identification. If you want to work on this, please either provide a patch (for trunk and/or py3k), or (if you are a committer) create a subversion branch. It seems that Barry and I agree that for the maintenance branches, sys.subversion should be frozen, so we need actually two sets of patches: one that removes sys.subversion entirely, and the other that freezes the branch to the respective one, and freezes the subversion revision to None. The patch should consider what Dirkjan proposes as the branching strategy: clones to separate 2.x and 3.x, as well as for features, and branches with the clones for releases and maintenance (see the PEP for details). Anybody working on this should have good knowledge of the Python source code, Mercurial, and either autoconf or Visual Studio (preferably both). Item 2 ------ The second item is line conversion hooks. Dj Gilcrease has posted a solution which he considers a hack himself. Mark Hammond has also volunteered, but it seems some volunteer needs to be "in charge", keeping track of a proposed solution until everybody agrees that it is a good solution. It may be that two solutions are necessary: a short-term one, that operates as a hook and has limitations, and a long-term one, that improves the hook system of Mercurial to implement the proper functionality (which then might get shipped with Mercurial in a cross-platform manner). Regards, Martin From nospam at nospam.com Tue Aug 18 04:19:53 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 10:19:53 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <874os5k35x.fsf@benfinney.id.au> <10nk85le4ghbb22ogjuta10cneir6pcc8p@4ax.com> Message-ID: On Tue, 18 Aug 2009 01:11:20 -0700, Rami Chowdhury wrote: >Could you let me know which platform this is on (Windows, *nix)? It may be a >locale encoding issue -- the locale.setlocale() function allows the second >argument to be a tuple of (locale_code, encoding), as below: > >locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) It's on XP, and I'm using ActivePython 2.5.1.1. http://www.activestate.com/activepython/ Python doesn't like the above: #locale.Error: unsupported locale setting locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) Maybe it was introduced in more recent versions of Python? >Since this is for a one-shot (and presumably threading-agnostic) program, and >a fairly trivially formatted date-string, I would suggest using >datetime.strptime >(http://docs.python.org/library/datetime.html#datetime.datetime.strptime) and >not regular expressions (which IIRC have Issues with non-ASCII characters). If the regex library can only handle basic latin characters, I'll wait until a script I'm running is done, and I'll upgrade to the 2.6.2.2 to see how it goes. Thank you. From dirkjan at ochtman.nl Tue Aug 18 04:20:15 2009 From: dirkjan at ochtman.nl (Dirkjan Ochtman) Date: Tue, 18 Aug 2009 10:20:15 +0200 Subject: [Python-Dev] Mercurial migration: help needed In-Reply-To: <4A8A6256.1030009@v.loewis.de> References: <4A8A6256.1030009@v.loewis.de> Message-ID: On Tue, Aug 18, 2009 at 10:12, "Martin v. L?wis" wrote: > In this thread, I'd like to collect things that ought to be done > but where Dirkjan has indicated that he would prefer if somebody else > did it. I think the most important item here is currently the win32text stuff. Mark Hammond said he would work on this; Mark, when do you have time for this? Then I could set apart some time for it as well. Have stalled a bit on the fine-grained branch processing, hope to move that forward tomorrow. Cheers, Dirkjan From clp2 at rebertia.com Tue Aug 18 04:28:25 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 01:28:25 -0700 Subject: conversion of Python object to perl object In-Reply-To: <229114.26317.qm@web7901.mail.in.yahoo.com> References: <229114.26317.qm@web7901.mail.in.yahoo.com> Message-ID: <50697b2c0908180128i48ac0d77sa04db33a05ab2c7@mail.gmail.com> On Mon, Aug 17, 2009 at 3:47 AM, srinivasan srinivas wrote: > Hi, > I have to call a perl method which takes a hash as its?argument from a python module. Is there a way to convert python dictionary to perl hash ( not hash ref)? How are you calling the Perl method from Python in the first place? Cheers, Chris -- http://blog.rebertia.com From paul at boddie.org.uk Tue Aug 18 04:34:58 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 18 Aug 2009 01:34:58 -0700 (PDT) Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> <3d808272-6e56-4cf1-90df-8e5201df02df@c34g2000yqi.googlegroups.com> <13be5a11-612b-4fc5-a220-cc9aba2e4f8c@z31g2000yqd.googlegroups.com> <611687df-e755-4910-9042-5dab20de1a7e@c34g2000yqi.googlegroups.com> Message-ID: <2f09b257-98c1-432c-8643-3bf1c5bdc875@e27g2000yqm.googlegroups.com> On 18 Aug, 05:19, ru... at yahoo.com wrote: > > Yes, I agree. ?I should have mentioned this as an exception > in my "wikis suck" diatribe. ?Although it far better than > most wiki's I've seen, it is still pretty easy to find signs > of typical wiki-ness. ?On the Documentation page my first > click was on AnnotableDocumentation: 404. Well, "Annotatable Documentation" is an external link. All we can do in such cases is to tidy such stuff up, mark it as invalid, or remove it. >?Second try, DoumentationDiscussion: two very short paragraphs dated 2003. Right. There are parts of the Wiki which were used actively in the past but which have fallen into disrepair. Some pages lack focus - they've been created according to "old school" Wiki conventions which I regard as being somewhat obsolete (just creating new pages all over the place to cover whatever happens to be in the writer's head at the time) - and every now and again, I attempt to rationalise these pages and focus their content. > After that I found some useful (in general though not what I > was looking for) information but not a good first impression. > (Well not exactly first, in fairness I have used other wiki > sections such as the Templating page and found them very > useful.) It needs work, of course. [...] > I took a look at the PHP docs last night which seem > pretty well done. ?The User Comments looked rather as I > expected, there was useful info but most did not contain > documentation quality writing. ?So if they are used as > a source for improving the docs, there clearly must be a > pretty large amount of editorial effort required, although > much of it is probably just filtering out comments that > don't provide any information appropriate for inclusion > in the docs. ?They list 38 names under "User Note Maintainers" > (http://www.php.net/manual/en/preface.php) > Unfortunately I couldn't find a description of what these > people actually do. ?I don't know how much work was involved > in removing the comments that are no longer there. Indeed. There's always the editorial bottleneck unless it's a total free-for-all situation. I've remarked before about how user comments don't necessarily add significantly to documentation, which is an assertion that some people make, and there definitely does need to be a process of integrating the best feedback into the main work. The crucial difference between a Wiki and an annotation system is the combination of the contribution and editorial aspects in a Wiki - you edit the actual work, and people can decide whether it's a good edit or not - in contrast to their separation in most annotation systems. In some cases, strict annotation systems are probably better: the GPLv3 annotation system was oriented towards discussion of the text, and that's not so effectively done in a Wiki. > Again, I don't mean to sound like I am dissing the idea > of annotatable docs -- I think it is a good idea and will > provide useful supplementary information. Where there's a separation of annotation and editing, I worry about the editorial bottleneck. I also worry about "handprint" edits more generally, where people just want to leave their touch on the work without actually contributing anything of substance. > But I continue to question whether this will result in > improvements in the docs themselves (which is my main > interest) unless: > > ? ?1. The purpose of the wiki is clearly "marketed" as > soliciting suggestions, rewrites, etc destined ultimately > for inclusion in the docs. I'm happy to see tangential work rather than stuff which fills exactly the same role as the current documentation. For example, the Python module of the week articles (PyMOTW, [1]) are exactly the kind of tangential work that could be encouraged, even though that is not so much a collaborative work itself. Paul [1] http://www.doughellmann.com/PyMOTW/ From rami.chowdhury at gmail.com Tue Aug 18 04:42:26 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 18 Aug 2009 01:42:26 -0700 Subject: Converting DD MM YYYY into YYYY-MM-DD? In-Reply-To: References: Message-ID: <200908180142.26979.rami.chowdhury@gmail.com> > Python doesn't like the above: > > #locale.Error: unsupported locale setting > locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) > > Maybe it was introduced in more recent versions of Python? Hmm, that's odd. According to the docs (http://docs.python.org/library/locale.html#locale.setlocale) it's been that way since 2.0, but I've just checked this on my Windows (Vista) machine and you're right, it returns an error. This worked for me on 32-bit Vista: locale.setlocale(locale.LC_ALL, 'FR') It uses Windows-1252 for the encoding, but that seems to deal with the circonflexe in 'Ao?t' just fine, so it should work for this purpose. ---- Rami Chowdhury "Never attributed to malice that which can be attributed to stupidity." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Tuesday 18 August 2009 01:19:53 Gilles Ganault wrote: > On Tue, 18 Aug 2009 01:11:20 -0700, Rami Chowdhury > > wrote: > >Could you let me know which platform this is on (Windows, *nix)? It may be > > a locale encoding issue -- the locale.setlocale() function allows the > > second argument to be a tuple of (locale_code, encoding), as below: > > > >locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) > > It's on XP, and I'm using ActivePython 2.5.1.1. > http://www.activestate.com/activepython/ > > Python doesn't like the above: > > #locale.Error: unsupported locale setting > locale.setlocale(locale.LC_ALL, ('FR', 'UTF-8')) > > Maybe it was introduced in more recent versions of Python? > > >Since this is for a one-shot (and presumably threading-agnostic) program, > > and a fairly trivially formatted date-string, I would suggest using > >datetime.strptime > >(http://docs.python.org/library/datetime.html#datetime.datetime.strptime) > > and not regular expressions (which IIRC have Issues with non-ASCII > > characters). > > If the regex library can only handle basic latin characters, I'll wait > until a script I'm running is done, and I'll upgrade to the 2.6.2.2 to > see how it goes. > > Thank you. From nospam at nospam.com Tue Aug 18 04:52:41 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 10:52:41 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: I find it odd that the regex library can't handle European characters :-/ From indermeet.gandhi at gmail.com Tue Aug 18 04:55:35 2009 From: indermeet.gandhi at gmail.com (inder) Date: Tue, 18 Aug 2009 01:55:35 -0700 (PDT) Subject: XML parsing with python References: <4a8a4918$0$32672$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <25838ee3-897a-4979-bd08-c2d0287d02c0@f37g2000yqn.googlegroups.com> On Aug 18, 11:24?am, Stefan Behnel wrote: > inder wrote: > > On Aug 17, 8:31 pm, John Posner wrote: > >>> Use the iterparse() function of the xml.etree.ElementTree package. > >>>http://effbot.org/zone/element-iterparse.htm > >>>http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk > >>> Stefan > >> iterparse() is too big a hammer for this purpose, IMO. How about this: > > >> ? from xml.etree.ElementTree import ElementTree > >> ? tree = ElementTree(None, "myfile.xml") > >> ? for elem in tree.findall('//book/title'): > >> ? ? ? print elem.text > > >> -John > > > Thanks for the prompt reply . > > > I feel let me try using iterparse. Will it be slower compared to SAX > > parsing ... ultimately I will have a huge xml file to parse ? > > If you use the cElementTree module, it may even be faster. > > > Another question , I will also need to validate my xml against xsd . I > > would like to do this validation through the parsing tool ?itself . > > In that case, you can use lxml instead of ElementTree. > > http://codespeak.net/lxml/ > > Stefan Hi , Is lxml part of standard python package ? I am having python 2.5 . I might not be able to use any additional package other than the standard python . Could you please suggest something part of standard python package ? Thanks From deets at nospam.web.de Tue Aug 18 04:57:58 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 10:57:58 +0200 Subject: Changing Python Opcodes References: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> <7ev303F2ib9r1U1@mid.uni-berlin.de> <7cfe9433-37a6-456e-8a77-b0a8f17e5f23@e27g2000yqm.googlegroups.com> Message-ID: <7ev8omF2ffh1jU1@mid.uni-berlin.de> Sreejith K wrote: > On Aug 18, 12:19?pm, "Diez B. Roggisch" wrote: > >> Did you try installing the egg *without* pyc-files in there? Because >> naturally those shouldn't work. They shouldn't crash the interpreter >> either, but then again - you *did* modify it. > > Hi Diez, thanks for the immediate reply :) > > I installed the setuptools using ez_setup.py script. Then I used the > easy_install to install additional modules. When importing the > installed modules segfault occurs. The module I installed was > TurboGears. > > Then I thought that it happened maybe because the easy_install script > is downloading eggs for original python (I'm not sure if it is what > easy_install is doing). Yep, that's actually it's main purpose. > So I also tried to install the module by > downloading all the dependencies (tar.gz files) and building it. Even > then segfault occured. Is there any problem in changing only the > opcodes.py file ? I did something horribly wrong here. Hope someone > will help... I don't know. You modified this yourself. If I were in your situation, what I would have done is to - modify the version-information stored in my PYC-files so that I'm sure I don't accidentally load any "normal" PYC-files. Python does check that through some magic number, make sure you use your own. - fire up the debugger and see where the segfault actually happens. Nobody can be helping you there, because it's *your* code, not Python anymore. And giving others access to it defies somewhat the purpose of the whole exercise.... Diez From nospam at nospam.com Tue Aug 18 05:07:21 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 11:07:21 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: On Tue, 18 Aug 2009 10:52:41 +0200, Gilles Ganault wrote: >I find it odd that the regex library can't handle European characters >:-/ Ha, found it! :-) http://www.regular-expressions.info/python.html ========= # -*- coding: latin-1 -*- import locale import re locale.setlocale(locale.LC_ALL, 'FR') re_inscription = re.compile(r"(?P\d+)\s+(?P\w+)\s+(?P\d+)",re.LOCALE) dateinscription = "11 Ao?t 2008" m = re_inscription.search(dateinscription) if m: day = m.group("date") month = m.group("month") year = m.group("year") print "%s-%s-%s" % (year,month,day) else: print "Yuck" ========= Thanks everyone! From http Tue Aug 18 05:15:51 2009 From: http (Paul Rubin) Date: 18 Aug 2009 02:15:51 -0700 Subject: Social problems of Python doc [was Re: Python docs disappointing] References: <6fa250dc-b7cf-43a6-ab1d-598c2a8e5cc8@v23g2000pro.googlegroups.com> <20c37f24-190a-44c6-82aa-2f90d17c7550@l31g2000vbp.googlegroups.com> <6fb561e8-741c-4466-a3fc-bf2454ede90e@e27g2000yqm.googlegroups.com> <0291a07d$0$20639$c3e8da3@news.astraweb.com> <83e60eed-802c-4218-8394-0e764b962e81@f10g2000vbf.googlegroups.com> <7f7c3e90-6026-411f-8b4a-829798819128@v36g2000yqv.googlegroups.com> <3fdfb992-058b-4017-b1b3-db3a9542b62e@m7g2000prd.googlegroups.com> <3d808272-6e56-4cf1-90df-8e5201df02df@c34g2000yqi.googlegroups.com> <13be5a11-612b-4fc5-a220-cc9aba2e4f8c@z31g2000yqd.googlegroups.com> <611687df-e755-4910-9042-5dab20de1a7e@c34g2000yqi.googlegroups.com> Message-ID: <7xiqgl7a9k.fsf@ruckus.brouhaha.com> rurpy at yahoo.com writes: > I took a look at the PHP docs last night which seem pretty well > done. The User Comments looked rather as I expected, there was > useful info but most did not contain documentation quality writing. > So if they are used as a source for improving the docs, there > clearly must be a pretty large amount of editorial effort required, > although much of it is probably just filtering out comments that > don't provide any information appropriate for inclusion in the docs. The comments section contains questions from users and answers to those questions from other users. What you may be missing is the part of the comments useful to the doc maintainers is primarily the user questions, rather than the user answers. The questions show the doc writer exactly what parts of the official doc are unclear or incomplete. The user-written answers may be wrong or generally crap, but the doc writer now knows what to do to improve the doc. That's why it's such a win to have the comments on the same page as the official docs. See also the user-commented http://book.realworldhaskell.org/read/ where the comments really helped clarify the finished (dead tree) text. From stefan_ml at behnel.de Tue Aug 18 05:26:02 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 Aug 2009 11:26:02 +0200 Subject: XML parsing with python In-Reply-To: <25838ee3-897a-4979-bd08-c2d0287d02c0@f37g2000yqn.googlegroups.com> References: <4a8a4918$0$32672$9b4e6d93@newsspool2.arcor-online.net> <25838ee3-897a-4979-bd08-c2d0287d02c0@f37g2000yqn.googlegroups.com> Message-ID: <4a8a73aa$0$32676$9b4e6d93@newsspool2.arcor-online.net> inder wrote: > Is lxml part of standard python package ? I am having python 2.5 . No, that's why I suggested ElementTree first. > I might not be able to use any additional package other than the > standard python . Could you please suggest something part of standard > python package ? No, there isn't any XMLSchema support in the stdlib. However, you may still be able to use lxml locally for development and with validation enabled, and switch to non-validating ElementTree on distribution/pre-prod-testing/whatever. Just use a conditional import and write a bit of setup code. Stefan From hendrik at microcorp.co.za Tue Aug 18 05:49:12 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 18 Aug 2009 11:49:12 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> References: <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> Message-ID: <200908181149.12382.hendrik@microcorp.co.za> On Monday 17 August 2009 23:06:04 Carl Banks wrote: > On Aug 17, 10:03?am, Jean-Michel Pichavant > > wrote: > > I'm no English native, but I already heard women/men referring to a > > group as "guys", no matter that group gender configuration. It's even > > used for group composed exclusively of women. Moreover it looks like a > > *very* friendly form, so there is really nothing to worry about it. > > I like how being very friendly means calling people after a guy who > tried to blow up the English Parliament. +1 QOTW - Hendrik From __peter__ at web.de Tue Aug 18 05:55:57 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 18 Aug 2009 11:55:57 +0200 Subject: Changing Python Opcodes References: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> <7ev303F2ib9r1U1@mid.uni-berlin.de> <7cfe9433-37a6-456e-8a77-b0a8f17e5f23@e27g2000yqm.googlegroups.com> <7ev8omF2ffh1jU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Sreejith K wrote: >> So I compiled Python from source changing some opcode values > Nobody > can be helping you there, because it's *your* code, not Python anymore. > And giving others access to it defies somewhat the purpose of the whole > exercise.... ...and everyone with the expertise to decompile your application and do something useful with the result will also be able to find this thread. Basically you're trying the security through obscurity stunt without the obscurity... Peter From nitebirdz at sacredchaos.com Tue Aug 18 06:02:44 2009 From: nitebirdz at sacredchaos.com (Nitebirdz) Date: Tue, 18 Aug 2009 12:02:44 +0200 Subject: Using a Callback Function - ftplib In-Reply-To: References: <76875cdd-30c4-4a3b-8a16-d0e2061765d7@v2g2000vbb.googlegroups.com> <1euafoc8zeh0q.91hedjv5ueuh$.dlg@40tude.net> Message-ID: <20090818100243.GB16443@sevilla.sacredchaos.com> On Mon, Aug 17, 2009 at 11:10:25AM -0700, seldan24 wrote: > > I didn't even notice the higher level methods. I changed the > retrieval line to: > > ftp.nlst("testfile*.txt") > > This works great. The result is even captured in an array. I really > have no idea what the difference between a LIST and NLST is within > FTP. Never delved that deep into it. I did notice that an NLST will > return a specific FTP code if a file doesn't exist, whereas a LIST > doesn't. So, I ended up using NLST as that'll generate an > ftplib.error_perm exception. Based on if the job cares if a file is > not available or not (some do, some don't), I'll either exit, or > continue on with the file loop. > The following thread from a NetBSD mailing list may help clarify this issue: http://mail-index.netbsd.org/netbsd-users/2001/01/30/0016.html NLST returns a machine-readable list of names, while LIST returns a human-readable list. Hene the presence of the FTP code in the case of NLST. From ben+python at benfinney.id.au Tue Aug 18 06:03:47 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 20:03:47 +1000 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: <87iqgligl8.fsf@benfinney.id.au> Gilles Ganault writes: > dateinscription = "11 Ao?t 2008" For any text string that's not ASCII, you should specify it as Unicode. (Actually, you should specify text as Unicode anyway.) For a literal text string: dateinscription = u"11 Ao?t 2008" If you're using exclusively Python 3, you will get Unicode text literals by default; but I assume you're using Python 2 based on existing discussion. The principles of handling text in Python: Get it to internal Unicode objects as soon as possible, handle it as Unicode for as long as possible, and only encode it to some byte stream for output as late as possible. -- \ ?When a well-packaged web of lies has been sold to the masses | `\ over generations, the truth will seem utterly preposterous and | _o__) its speaker a raving lunatic.? ?Dresden James | Ben Finney From sleepy at cabbage.co.uk Tue Aug 18 06:05:18 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Tue, 18 Aug 2009 10:05:18 GMT Subject: urlopen errors in script Message-ID: I'm scripting a superkaramba theme using python and have intgrated output from amarok. I have also would like to show the artist and song title from a radio stream i've added to my playlist. If I open a python console and add the following: >>>import urllib2 >>>from urllib2 import urlopen >>>nowplaying = str.split(urlopen('http://www.hearteastmids.co.uk// jsfiles/NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% 2F6854.xml&l=6854&tzc=8&at=HeartEastMids').read(),'>') >>>print test[4][:-3] this works and displays the artist and song title. However, when I add this to my script I get the following errors: ---------------------------------------------------------------------------- superkaramba(28855) ThemesDlg::addThemeToList: addThemeToList() file: "/ home/sleepy/dev/MyTheme/ MyTheme.theme" superkaramba(28855) Karamba::startKaramba: Loading script module: "MyTheme.py" superkaramba(28855) KarambaInterface::initInterpreter: Using "python" script: "/home/sleepy/dev/MyTheme/ MyTheme.py" Kross: "Loading the interpreter library for python" Kross: "Successfully loaded Interpreter instance from library." Kross: "PythonScript::Constructor." Kross: "PythonScript::execute" Kross: "PythonInterpreter::extractException: File "/home/sleepy/dev/MyTheme/MyTheme.py", line 4, in #this import statement allows access to the karamba functions File "/home/sleepy/dev/MyTheme/MyTheme.py", line 9, in import urllib2 File "", line 18, in _import File "/usr/lib/python2.6/urllib2.py", line 92, in import httplib File "", line 18, in _import File "/usr/lib/python2.6/httplib.py", line 1054, in import ssl File "", line 18, in _import File "/usr/lib/python2.6/ssl.py", line 81, in class SSLSocket (socket): " Kross: "Error error=Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) lineno=81 trace= File "/home/sleepy/dev/MyTheme/MyTheme.py", line 4, in #this import statement allows access to the karamba functions File "/home/sleepy/dev/MyTheme/MyTheme.py", line 9, in import urllib2 File "", line 18, in _import File "/usr/lib/python2.6/urllib2.py", line 92, in import httplib File "", line 18, in _import File "/usr/lib/python2.6/httplib.py", line 1054, in import ssl File "", line 18, in _import File "/usr/lib/python2.6/ssl.py", line 81, in class SSLSocket (socket): " TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python2.6/dist-packages/apport_python_hook.py", line 38, in apport_excepthook from apport.packaging_impl import impl as packaging File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/__init__.py", line 1, in from apport.report import Report File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/report.py", line 21, in import fileutils File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/fileutils.py", line 16, in from packaging_impl import impl as packaging File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/packaging_impl.py", line 18, in import apt File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apt/__init__.py", line 7, in from apt.package import Package File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apt/package.py", line 23, in import httplib File "", line 18, in _import File "/usr/lib/python2.6/httplib.py", line 1054, in import ssl File "", line 18, in _import File "/usr/lib/python2.6/ssl.py", line 81, in class SSLSocket (socket): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Original exception was: TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Kross: "PythonScript::Destructor." ------------------------------------------------------------------------ Thanks in advance From sleepy at cabbage.co.uk Tue Aug 18 06:07:41 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Tue, 18 Aug 2009 10:07:41 GMT Subject: urlopen errors in script Message-ID: I'm scripting a superkaramba theme using python and have intgrated output from amarok. I have also would like to show the artist and song title from a radio stream i've added to my playlist. If I open a python console and add the following: ">>>import urllib2" ">>>from urllib2 import urlopen" ">>>nowplaying = str.split(urlopen('http://www.hearteastmids.co.uk// jsfiles/NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% 2F6854.xml&l=6854&tzc=8&at=HeartEastMids').read(),'>')" ">>>print test[4][:-3]" this works and displays the artist and song title. However, when I add this to my script I get the following errors: ---------------------------------------------------------------------------- superkaramba(28855) ThemesDlg::addThemeToList: addThemeToList() file: "/ home/sleepy/dev/MyTheme/ MyTheme.theme" superkaramba(28855) Karamba::startKaramba: Loading script module: "MyTheme.py" superkaramba(28855) KarambaInterface::initInterpreter: Using "python" script: "/home/sleepy/dev/MyTheme/ MyTheme.py" Kross: "Loading the interpreter library for python" Kross: "Successfully loaded Interpreter instance from library." Kross: "PythonScript::Constructor." Kross: "PythonScript::execute" Kross: "PythonInterpreter::extractException: File "/home/sleepy/dev/MyTheme/MyTheme.py", line 4, in #this import statement allows access to the karamba functions File "/home/sleepy/dev/MyTheme/MyTheme.py", line 9, in import urllib2 File "", line 18, in _import File "/usr/lib/python2.6/urllib2.py", line 92, in import httplib File "", line 18, in _import File "/usr/lib/python2.6/httplib.py", line 1054, in import ssl File "", line 18, in _import File "/usr/lib/python2.6/ssl.py", line 81, in class SSLSocket (socket): " Kross: "Error error=Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) lineno=81 trace= File "/home/sleepy/dev/MyTheme/MyTheme.py", line 4, in #this import statement allows access to the karamba functions File "/home/sleepy/dev/MyTheme/MyTheme.py", line 9, in import urllib2 File "", line 18, in _import File "/usr/lib/python2.6/urllib2.py", line 92, in import httplib File "", line 18, in _import File "/usr/lib/python2.6/httplib.py", line 1054, in import ssl File "", line 18, in _import File "/usr/lib/python2.6/ssl.py", line 81, in class SSLSocket (socket): " TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Error in sys.excepthook: Traceback (most recent call last): File "/usr/lib/python2.6/dist-packages/apport_python_hook.py", line 38, in apport_excepthook from apport.packaging_impl import impl as packaging File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/__init__.py", line 1, in from apport.report import Report File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/report.py", line 21, in import fileutils File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/fileutils.py", line 16, in from packaging_impl import impl as packaging File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apport/packaging_impl.py", line 18, in import apt File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apt/__init__.py", line 7, in from apt.package import Package File "", line 18, in _import File "/usr/lib/python2.6/dist-packages/apt/package.py", line 23, in import httplib File "", line 18, in _import File "/usr/lib/python2.6/httplib.py", line 1054, in import ssl File "", line 18, in _import File "/usr/lib/python2.6/ssl.py", line 81, in class SSLSocket (socket): TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Original exception was: TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) Kross: "PythonScript::Destructor." ------------------------------------------------------------------------ Thanks in advance From hendrik at microcorp.co.za Tue Aug 18 06:12:14 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 18 Aug 2009 12:12:14 +0200 Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) In-Reply-To: References: Message-ID: <200908181212.14882.hendrik@microcorp.co.za> On Tuesday 18 August 2009 06:45:39 Aahz wrote: > In article , > > Steven D'Aprano wrote: > >The comments were made a week ago -- why the sudden flurry of attention? > > Mainly an opportunity to flog the new diversity list. Here my English fails me - flog as in "whip", or flog as in "sell"? - Hendrik From nospam at nospam.com Tue Aug 18 06:21:07 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 18 Aug 2009 12:21:07 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <87iqgligl8.fsf@benfinney.id.au> Message-ID: On Tue, 18 Aug 2009 20:03:47 +1000, Ben Finney wrote: >The principles of handling text in Python: Get it to internal Unicode >objects as soon as possible, handle it as Unicode for as long as >possible, and only encode it to some byte stream for output as late as >possible. Thanks much for the tip. I'll keep that in mind when I have strings with accents. From marduk at letterboxes.org Tue Aug 18 06:26:02 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 18 Aug 2009 06:26:02 -0400 Subject: Strongly typed list In-Reply-To: <7ev11jF1jj25dU1@mid.uni-berlin.de> References: <7718922b-c72c-4a7e-90a3-098318063013@n11g2000yqb.googlegroups.com> <7ev11jF1jj25dU1@mid.uni-berlin.de> Message-ID: <1250591162.10348.3.camel@blackwidow.nbk> On Tue, 2009-08-18 at 08:46 +0200, Diez B. Roggisch wrote: > Please could you lead me to a way or a good IDE that makes developing > > huge projects in python more easier than what i found.Now i am using > > eclips. Actually it is very hard to remember all my classes methods > > and attributes or copy and paste them each time. > > Thanks very much for your interest > > Hani Almousli..... > > There are many really big projects written in Python - none of them with > the aid of intelli-sense. > > What python lacks in that respect due to it's dynamic typing, it more > than compensates by being faster to develop and having to write much > less code. But this class can do *anything*! It .slice()s.. It .dice()s... ... sorry, couldn't resist ;-) -a From ben+python at benfinney.id.au Tue Aug 18 06:37:47 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 20:37:47 +1000 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: <87iqgligl8.fsf@benfinney.id.au> Message-ID: <87ab1xif0k.fsf@benfinney.id.au> Gilles Ganault writes: > On Tue, 18 Aug 2009 20:03:47 +1000, Ben Finney > wrote: > >The principles of handling text in Python: Get it to internal Unicode > >objects as soon as possible, handle it as Unicode for as long as > >possible, and only encode it to some byte stream for output as late as > >possible. > > Thanks much for the tip. I'll keep that in mind when I have strings > with accents. Again, note that these recommendations hold for *any* text in Python, with or without accents; once you accept that text is best handled in Unicode, there's little sense in making an exception for the limited subset that happens to be representable in ASCII. -- \ ?The Bermuda Triangle got tired of warm weather. It moved to | `\ Alaska. Now Santa Claus is missing.? ?Steven Wright | _o__) | Ben Finney From rui.maciel at gmail.com Tue Aug 18 06:38:30 2009 From: rui.maciel at gmail.com (Rui Maciel) Date: Tue, 18 Aug 2009 11:38:30 +0100 Subject: A Exhibition Of Tech Geekers Incompetence: Emacs whitespace-mode References: <61ef4451-d6b6-493b-b4a0-1822a901ca8d@m3g2000pri.googlegroups.com> Message-ID: <4a8a84a3$0$27142$a729d347@news.telepac.pt> Xah Lee wrote: > This feature is important in practical ways. For example, when you > work with ?tab separated line? files (CSV) that's a common format for > importing/exporting address books or spreadsheets. CSV stands for "comma separated values" and the import facilities of any spreadsheet application lets the user define the field separator character. Rui Maciel From ben+python at benfinney.id.au Tue Aug 18 06:38:36 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 18 Aug 2009 20:38:36 +1000 Subject: Diversity in Python References: Message-ID: <8763cliez7.fsf@benfinney.id.au> Hendrik van Rooyen writes: > On Tuesday 18 August 2009 06:45:39 Aahz wrote: > > Mainly an opportunity to flog the new diversity list. > > Here my English fails me - flog as in "whip", or flog as in "sell"? Yes :-) -- \ ?The most common of all follies is to believe passionately in | `\ the palpably not true. It is the chief occupation of mankind.? | _o__) ?Henry L. Mencken | Ben Finney From __peter__ at web.de Tue Aug 18 07:21:59 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 18 Aug 2009 13:21:59 +0200 Subject: urlopen errors in script References: Message-ID: Sleepy Cabbage wrote: > I'm scripting a superkaramba theme using python and have intgrated output > from amarok. I have also would like to show the artist and song title from > a radio stream i've added to my playlist. > > If I open a python console and add the following: > > ">>>import urllib2" > ">>>from urllib2 import urlopen" > > ">>>nowplaying = str.split(urlopen('http://www.hearteastmids.co.uk// > jsfiles/NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% > 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% > 2F6854.xml&l=6854&tzc=8&at=HeartEastMids').read(),'>')" > > ">>>print test[4][:-3]" > > this works and displays the artist and song title. > > However, when I add this to my script I get the following errors: Please give a minimal version of your script that produces the error, not some arbitrary excerpt that you ran successfully on the command line. If I were to guess: you are doing something like import socket socket.socket = socket somewhere, thus confusing the socket class with the module of the same name. Peter From mhammond at skippinet.com.au Tue Aug 18 07:32:23 2009 From: mhammond at skippinet.com.au (Mark Hammond) Date: Tue, 18 Aug 2009 21:32:23 +1000 Subject: [Python-Dev] Mercurial migration: help needed In-Reply-To: References: <4A8A6256.1030009@v.loewis.de> Message-ID: <4A8A9147.7070109@skippinet.com.au> On 18/08/2009 6:20 PM, Dirkjan Ochtman wrote: > On Tue, Aug 18, 2009 at 10:12, "Martin v. L?wis" wrote: >> In this thread, I'd like to collect things that ought to be done >> but where Dirkjan has indicated that he would prefer if somebody else >> did it. > > I think the most important item here is currently the win32text stuff. > Mark Hammond said he would work on this; Mark, when do you have time > for this? Then I could set apart some time for it as well. I can make time, somewhat spasmodically, starting fairly soon. Might I suggest that as a first task I can resurrect my old stale patch, and you can arrange to install win32text locally and start experimenting with how mixed line-endings can work for you. Once we are all playing in the same ballpark I think we should be able to make good progress. I-said-ballpark-yet-I-call-myself-an-aussie? ly, Mark From jeanmichel at sequans.com Tue Aug 18 07:36:49 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 18 Aug 2009 13:36:49 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <4A89CEA2.10400@mrabarnett.plus.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <4A89CEA2.10400@mrabarnett.plus.com> Message-ID: <4A8A9251.3080200@sequans.com> MRAB wrote: > Carl Banks wrote: >> On Aug 17, 10:03 am, Jean-Michel Pichavant >> wrote: >>> I'm no English native, but I already heard women/men referring to a >>> group as "guys", no matter that group gender configuration. It's even >>> used for group composed exclusively of women. Moreover it looks like a >>> *very* friendly form, so there is really nothing to worry about it. >> >> I like how being very friendly means calling people after a guy who >> tried to blow up the English Parliament. >> > Guy Fawkes adopted the name Guido while fighting for the Spanish in the > Low Countries: > > http://en.wikipedia.org/wiki/Guy_Fawkes > I didn't get Carl's reference. The only thing I know about blowing the parliament is from the movie V for Vendetta (no comment please !). Now thanks to your link: "In 18th-century England, the term "guy" was used to refer to an effigy of Fawkes, which would be paraded around town by children on the anniversary of the conspiracy" Well, my knowledge is much too low to get this kind of reference from the start. :-/ JM From hani.mousli at gmail.com Tue Aug 18 07:37:54 2009 From: hani.mousli at gmail.com (=?UTF-8?B?2YfYp9mG2Yog2KfZhNmF2YjYtdmE2Yo=?=) Date: Tue, 18 Aug 2009 04:37:54 -0700 (PDT) Subject: Strongly typed list References: Message-ID: <1513faa5-e199-400c-a567-1f7b33aeb547@t13g2000yqt.googlegroups.com> I think i found a good managable solution. Actually it is trivial but may help (I used it now). When i wnat to access the list then i assign the object which i want to access to a variable ex: 1)x=AutomataBranch() 2)x=self.cfgAutomata[i] The first line is used only to make the IDE knows that x is from AutomatBranch type.After that when i press x. then all methods and properties are visualized. I think it is some how good. From exarkun at twistedmatrix.com Tue Aug 18 07:45:18 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Tue, 18 Aug 2009 11:45:18 -0000 Subject: Python 'for' loop is memory inefficient In-Reply-To: References: <02969972$0$20647$c3e8da3@news.astraweb.com> <4434e799-d907-49ca-93ee-a4be3276f9c2@26g2000yqk.googlegroups.com> <3c0abe16-f05a-4c5f-9773-f813bc424f14@s15g2000yqs.googlegroups.com> <20090817194155.8740.902674574.divmod.xquotient.69@localhost.localdomain> Message-ID: <20090818114518.7602.827840579.divmod.xquotient.0@localhost.localdomain> On 03:56 am, tjreedy at udel.edu wrote: >exarkun at twistedmatrix.com wrote: >>There's a lot of things in Python that I don't strictly *need*. That >>doesn't mean that they wouldn't be welcome if I could have them. >>Getting rid of the range/xrange dichotomy would improve things. > >The developers agreed a couple of years ago. Starting using 3.1 if you >want this. And there was much rejoicing, et cetera. >Since 'range' could refer to a user-defined object, rather than the >builtin function, there is no way the interpreter should substitute >'xrange'. See the earlier parts of this thread for the reasons this isn't true. :) Jean-Paul From dirkjan at ochtman.nl Tue Aug 18 07:46:36 2009 From: dirkjan at ochtman.nl (Dirkjan Ochtman) Date: Tue, 18 Aug 2009 13:46:36 +0200 Subject: [Python-Dev] Mercurial migration: help needed In-Reply-To: <4A8A9147.7070109@skippinet.com.au> References: <4A8A6256.1030009@v.loewis.de> <4A8A9147.7070109@skippinet.com.au> Message-ID: On Tue, Aug 18, 2009 at 13:32, Mark Hammond wrote: > I can make time, somewhat spasmodically, starting fairly soon. ?Might I > suggest that as a first task I can resurrect my old stale patch, and you can > arrange to install win32text locally and start experimenting with how mixed > line-endings can work for you. ?Once we are all playing in the same ballpark > I think we should be able to make good progress. Sounds good to me. Cheers, Dirkjan From sleepy at cabbage.co.uk Tue Aug 18 07:48:42 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Tue, 18 Aug 2009 11:48:42 GMT Subject: urlopen errors in script References: Message-ID: On Tue, 18 Aug 2009 13:21:59 +0200, Peter Otten wrote: > Sleepy Cabbage wrote: > >> I'm scripting a superkaramba theme using python and have intgrated >> output from amarok. I have also would like to show the artist and song >> title from a radio stream i've added to my playlist. >> >> If I open a python console and add the following: >> >> ">>>import urllib2" >> ">>>from urllib2 import urlopen" >> >> ">>>nowplaying = str.split(urlopen('http://www.hearteastmids.co.uk// >> jsfiles/NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net% 2Ffeeds% >> 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% >> 2F6854.xml&l=6854&tzc=8&at=HeartEastMids').read(),'>')" >> >> ">>>print test[4][:-3]" >> >> this works and displays the artist and song title. >> >> However, when I add this to my script I get the following errors: > > Please give a minimal version of your script that produces the error, > not some arbitrary excerpt that you ran successfully on the command > line. > > If I were to guess: you are doing something like > > import socket > socket.socket = socket > > somewhere, thus confusing the socket class with the module of the same > name. > > Peter Thanks Peter. This is the script up to where the error seems to fall: "#!/usr/bin/env superkaramba" "# -*- coding: iso-8859-1 -*-" "import karamba" "import subprocess" "from subprocess import Popen, PIPE, STDOUT, call" "import urllib" "from urllib import urlopen" "#this is called when your widget is initialized" "def initWidget(widget):" "clkPause = karamba.createClickArea(widget, 156, 470, 35, 35, "qdbus org.kde.amarok /Player Pause")" "nowplaying = urllib.urlopen('http://www.hearteastmids.co.uk//jsfiles/ NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% 2F6854.xml&l=6854&tzc=8&at=HeartEastMids').read()" Hope this can enlighten things From stefan_ml at behnel.de Tue Aug 18 07:55:06 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 Aug 2009 13:55:06 +0200 Subject: Converting DD MM YYYY into YYYY-MM-DD? In-Reply-To: <87ab1xif0k.fsf@benfinney.id.au> References: <87iqgligl8.fsf@benfinney.id.au> <87ab1xif0k.fsf@benfinney.id.au> Message-ID: <4a8a969b$0$30229$9b4e6d93@newsspool1.arcor-online.net> Ben Finney wrote: >>> The principles of handling text in Python: Get it to internal Unicode >>> objects as soon as possible, handle it as Unicode for as long as >>> possible, and only encode it to some byte stream for output as late as >>> possible. > Again, note that these recommendations hold for *any* text in Python, > with or without accents; once you accept that text is best handled in > Unicode, there's little sense in making an exception for the limited > subset that happens to be representable in ASCII. If the QOTW wasn't meant for fun, I'd vote for this. This is very good advice. Stefan From __peter__ at web.de Tue Aug 18 08:19:52 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 18 Aug 2009 14:19:52 +0200 Subject: urlopen errors in script References: Message-ID: Sleepy Cabbage wrote: > This is the script up to where the error seems to fall: > > "#!/usr/bin/env superkaramba" > "# -*- coding: iso-8859-1 -*-" > > "import karamba" > "import subprocess" > "from subprocess import Popen, PIPE, STDOUT, call" > "import urllib" > "from urllib import urlopen" > > "#this is called when your widget is initialized" > "def initWidget(widget):" > "clkPause = karamba.createClickArea(widget, 156, 470, 35, 35, "qdbus > org.kde.amarok /Player Pause")" > "nowplaying = urllib.urlopen('http://www.hearteastmids.co.uk//jsfiles/ > NowPlayingDisplay.aspx?f=http%3A%2F%2Frope.ccap.fimc.net%2Ffeeds% > 2Fnowplaying%2FGlobal%2FHeart_Network%2FHeart_East_Midlands% > 2F6854.xml&l=6854&tzc=8&at=HeartEastMids').read()" > > Hope this can enlighten things While there isn't any obvious blunder apart from the odd quotes that you wrap around every line there seem to be other files missing to run the script. I'm sorry, but I'm not prepared to invest much more than $ sudo aptitude install superkaramba into the problem. Perhaps an actual user of superkaramba can step in. Peter From steve at REMOVE-THIS-cybersource.com.au Tue Aug 18 08:59:43 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 12:59:43 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <4A89CEA2.10400@mrabarnett.plus.com> Message-ID: <0014291d$0$2963$c3e8da3@news.astraweb.com> On Tue, 18 Aug 2009 13:36:49 +0200, Jean-Michel Pichavant wrote: > MRAB wrote: >> Carl Banks wrote: >>> On Aug 17, 10:03 am, Jean-Michel Pichavant >>> wrote: >>>> I'm no English native, but I already heard women/men referring to a >>>> group as "guys", no matter that group gender configuration. It's even >>>> used for group composed exclusively of women. Moreover it looks like >>>> a *very* friendly form, so there is really nothing to worry about it. >>> >>> I like how being very friendly means calling people after a guy who >>> tried to blow up the English Parliament. >>> >> Guy Fawkes adopted the name Guido while fighting for the Spanish in the >> Low Countries: >> >> http://en.wikipedia.org/wiki/Guy_Fawkes >> > I didn't get Carl's reference. The only thing I know about blowing the > parliament is from the movie V for Vendetta (no comment please !). Now > thanks to your link: > "In 18th-century England, the term "guy" was used to refer to an effigy > of Fawkes, which would be paraded > around town by children on the anniversary of the conspiracy" > > Well, my knowledge is much too low to get this kind of reference from > the start. :-/ "Guy" is an old English name, related to the old French name "Gy" and Italian "Guido". It's originally derived from the Old German for "wood" or "warrior". After Guy Fawkes tried to blow up the English Parliament house, and was executed, the British government encouraged people to burn effigies of him. These became known as "guys", which eventually became slang for an ugly man, which later became slang for any man, and in recent years, any person. So the irony is that the friendly term "guys", referring to a group of people, is derived from the name of an 18th century religious terrorist. One can only wonder whether in 200 years time people will walk into the office and say "Hey you osamas, they're giving away free donuts down stairs, anyone want some?" -- Steven From steve at REMOVE-THIS-cybersource.com.au Tue Aug 18 09:01:53 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 13:01:53 GMT Subject: Diversity in Python (was Re: Need cleanup advice for multiline string) References: Message-ID: <001429a0$0$2963$c3e8da3@news.astraweb.com> On Tue, 18 Aug 2009 12:12:14 +0200, Hendrik van Rooyen wrote: > On Tuesday 18 August 2009 06:45:39 Aahz wrote: >> In article , >> >> Steven D'Aprano wrote: >> >The comments were made a week ago -- why the sudden flurry of >> >attention? >> >> Mainly an opportunity to flog the new diversity list. > > Here my English fails me - flog as in "whip", or flog as in "sell"? Almost certainly "flog" as in sell. But not literally sell, for money, but sell in the sense of convincing others it is a good list to join. -- Steven From sleepy at cabbage.co.uk Tue Aug 18 09:05:03 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Tue, 18 Aug 2009 13:05:03 GMT Subject: urlopen errors in script References: Message-ID: <3Gxim.148238$XK2.30441@newsfe15.ams2> Thanks for the time you've spent anyway Peter. I have superkaramba installed and the rest of the script is running fine, it's only when I put the urlopen part in that it comes back with errors. The quotes are just to make it readable on here as my first attempt at posting muted the text. From deets at nospam.web.de Tue Aug 18 09:15:42 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 15:15:42 +0200 Subject: Strongly typed list References: <1513faa5-e199-400c-a567-1f7b33aeb547@t13g2000yqt.googlegroups.com> Message-ID: <7evnruF2i9sm7U1@mid.uni-berlin.de> ???? ??????? wrote: > I think i found a good managable solution. Actually it is trivial but > may help (I used it now). > When i wnat to access the list then i assign the object which i want > to access to a variable ex: > 1)x=AutomataBranch() > 2)x=self.cfgAutomata[i] > > The first line is used only to make the IDE knows that x is from > AutomatBranch type.After that when i press x. then all methods and > properties are visualized. > > I think it is some how good. Unless x=AutomataBranch() is something that is expensive. And to be honest: changing code (possibly introducing bugs!!!) to work around short-comings in either your IDE or your way you insist to work strikes me as odd. I understand the desire to have autocompletion. But it's not *that* important. Maybe fabrio (who's maintaining the PyDev-eclipse-plugin) could be asked to add something like this: #@x:AutomataBranch to the plugin - so that when pydev reads that comment, it has a hint on what to use for autocompletion. Diez From naveen.garg at gmail.com Tue Aug 18 09:50:56 2009 From: naveen.garg at gmail.com (naveen) Date: Tue, 18 Aug 2009 06:50:56 -0700 (PDT) Subject: define class over 2 files References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> <6a490ec8-3536-4508-afd4-90a5cf9317b5@g10g2000yqh.googlegroups.com> <87zl9xiohe.fsf@benfinney.id.au> Message-ID: > indicator of bad practice. What is the problem you're trying to solve? > Ben Finney No major problem. I was just trying to make some experimental changes to autokey. My repo: http://github.com/tinku99/autokey.git/ Didn't want to subclass or reorganize a class just yet. From brochu121 at gmail.com Tue Aug 18 09:51:45 2009 From: brochu121 at gmail.com (David Brochu) Date: Tue, 18 Aug 2009 09:51:45 -0400 Subject: Compare content of two XML files Message-ID: <9583ed900908180651h270a2218nc1a3c3bab383e897@mail.gmail.com> I need to compare a REST XML response with a 'gold standard' response (one that we have already verified is correct). The problem is, sometimes the REST response comes back and it is logically correct, but the order of attributes and elements is different than what is in the 'gold standard' file. For example: 'Gold Standard': REST Response: Notice how the attributes in and are in different order. The response is correct, but obviously doesn't match the 'gold standard'. Does anyone know how I would be able to compare these two files and verify they match, even though the order of attributes and elements may be different between the two? Is there a module I should be using for this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjposner at optimum.net Tue Aug 18 10:04:36 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 18 Aug 2009 10:04:36 -0400 Subject: Code formatting question: conditional expression Message-ID: <4A8AB4F4.3040805@optimum.net> While refactoring some code, I ran across an opportunity to use a conditional expression. Original: if total > P.BASE: excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) else: excessblk = None Is there any consensus on how to format a conditional expression that is too long for one line? How about this: excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None) The above format separates the values from the if-then-else machinery. Too many lines? Would it be better to line up "if" and "else" vertically? ... excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None) PEP 308 is silent on this topic. -John From lauromoura at gmail.com Tue Aug 18 10:06:47 2009 From: lauromoura at gmail.com (Lauro Moura) Date: Tue, 18 Aug 2009 11:06:47 -0300 Subject: ANN: PySide has been released Message-ID: Hi, The PySide team is pleased to announce the first public release of PySide: Python for Qt! PySide, its documentation, and developer resources are available at the project website, http://www.pyside.org . What is it? ----------- PySide is a project providing an LGPL'd set of Python bindings for the Qt framework. PySide already provides a full set of Qt bindings as well as automated binding generation tools. Since the whole toolset has been made available, the team expects PySide to be valuable not only to Qt software developers, but to people willing to create Python bindings to any Qt-based library, or to any C++ library in general. Although based on a different technical approach, PySide will initially be API-compatible with existing Python bindings for Qt. PySide is still a work in progress, and some work is still required to stabilize the codebase. This being said, the team believes it is already in a usable state, especially if an occasional rough edge and unpainted surface can be tolerated. Due to practical reasons, the initial development efforts have been focused on Linux, but the team hopes people to join in porting the code to other platforms and to further develop the bindings and tools. Regards, PySide team -- Lauro Moura ("lmoura" on Freenode) http://lauro.wordpress.com From tuomas.vesterinen at iki.fi Tue Aug 18 10:08:23 2009 From: tuomas.vesterinen at iki.fi (Tuomas Vesterinen) Date: Tue, 18 Aug 2009 17:08:23 +0300 Subject: ANNOUNCEMENT: Tinybooker accounting released Message-ID: <4a8ab5d7$0$24765$9b536df3@news.fv.fi> Tinybooker 0.2.2 released at http://tinybooker.org/ Tinybooker is an accounting program offering the dual accounting core functionality for moderate size accountings: * Assisted establishing new accountings * Localized scheme templates * Easy entering and saving new entries * Standard reports in plain text or HTML: Income Statement, Balance Sheet, Journal, Nominal Ledger, Final Statement and Scheme * Assisted opening the next financial year * Accounting example as a demo * Open for auditing, all files human readable plain text * All written in pure Python * License GPL3 This early release is for Linux only. Later Tinybooker will be ported to Windows. Developers, more translations wanted, join the project contacting me at https://sourceforge.net/sendmessage.php?touser=2524141. From deets at nospam.web.de Tue Aug 18 10:10:01 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 16:10:01 +0200 Subject: Code formatting question: conditional expression References: Message-ID: <7evr1pF2i4mouU1@mid.uni-berlin.de> John Posner wrote: > While refactoring some code, I ran across an opportunity to use a > conditional expression. Original: > > if total > P.BASE: > excessblk = Block(total - P.BASE, srccol, > carry_button_suppress=True) > else: > excessblk = None > > Is there any consensus on how to format a conditional expression that is > too long for one line? How about this: > > excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) > if total > P.BASE else > None) > > The above format separates the values from the if-then-else machinery. > Too many lines? Would it be better to line up "if" and "else" > vertically? ... > > excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) > if total > P.BASE > else None) My choice would be excessblk = None if total > P.BASE: excessblk = ... You don't lose any vertical space, and it's much more readable IMHO. Diez From vs at it.uu.se Tue Aug 18 10:28:08 2009 From: vs at it.uu.se (Virgil Stokes) Date: Tue, 18 Aug 2009 16:28:08 +0200 Subject: Start-up program Message-ID: <4A8ABA78.8050605@it.uu.se> How difficult is to create a program that will be executed when Windows Vista is started? As Windows Calendar does, for example. I am actually more interested in the Python tools that might be used for this task. I hope that this question is not inappropriate for the list. :-\ --V From jeanmichel at sequans.com Tue Aug 18 10:32:02 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 18 Aug 2009 16:32:02 +0200 Subject: Code formatting question: conditional expression In-Reply-To: <7evr1pF2i4mouU1@mid.uni-berlin.de> References: <7evr1pF2i4mouU1@mid.uni-berlin.de> Message-ID: <4A8ABB62.80702@sequans.com> Diez B. Roggisch wrote: > John Posner wrote: > > >> While refactoring some code, I ran across an opportunity to use a >> conditional expression. Original: >> >> if total > P.BASE: >> excessblk = Block(total - P.BASE, srccol, >> carry_button_suppress=True) >> else: >> excessblk = None >> >> Is there any consensus on how to format a conditional expression that is >> too long for one line? How about this: >> >> excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) >> if total > P.BASE else >> None) >> >> The above format separates the values from the if-then-else machinery. >> Too many lines? Would it be better to line up "if" and "else" >> vertically? ... >> >> excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) >> if total > P.BASE >> else None) >> > > My choice would be > > excessblk = None > if total > P.BASE: > excessblk = ... > > > You don't lose any vertical space, and it's much more readable IMHO. > > Diez > +1, I'm using such layout whenever possible. JM From invalid at invalid Tue Aug 18 10:36:03 2009 From: invalid at invalid (Grant Edwards) Date: Tue, 18 Aug 2009 09:36:03 -0500 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> Message-ID: On 2009-08-17, Carl Banks wrote: > On Aug 17, 10:03?am, Jean-Michel Pichavant > wrote: >> I'm no English native, but I already heard women/men referring to a >> group as "guys", no matter that group gender configuration. It's even >> used for group composed exclusively of women. Moreover it looks like a >> *very* friendly form, so there is really nothing to worry about it. > > I like how being very friendly means calling people after a guy who > tried to blow up the English Parliament. Everybody likes fireworks! -- Grant Edwards grante Yow! Where do your SOCKS at go when you lose them in visi.com th' WASHER? From jliu6302 at yahoo.com Tue Aug 18 10:38:05 2009 From: jliu6302 at yahoo.com (John Liu) Date: Tue, 18 Aug 2009 07:38:05 -0700 (PDT) Subject: listen and receive the stock price from a VPN Message-ID: <685566.50872.qm@web53801.mail.re2.yahoo.com> Hi, My friends ? I am trying a Pyhton script to connect a VPN with (IP address, user ID, and passwrod). ? suppose I need to use Socket to connect the VPN and compare to a list of stock tickers I want to receive. ? Is there any wasy way and fast way to do that? ? Thanks so much in advance. ? Kindly regards, ? John -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Tue Aug 18 10:54:34 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 18 Aug 2009 07:54:34 -0700 (PDT) Subject: GUI interface builder for python References: <21bca3cf-b2c7-47d7-9142-26c9fd015f92@r27g2000vbn.googlegroups.com> <02ec7cd9-e749-46d3-8b25-75d85794f292@o35g2000vbi.googlegroups.com> Message-ID: On 17 Aug, 17:19, Che M wrote: > Boa (Boa Constructor) is really nice for wxPython GUI > work, but it has some bugs when using Linux that might > be dealbreakers for the user. ?At least I have had > problems on Ubuntu 8.10 64 bit (but none or very few > I prefer wxFormBuilder over Boa. From steve at REMOVE-THIS-cybersource.com.au Tue Aug 18 10:54:36 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 14:54:36 GMT Subject: Code formatting question: conditional expression References: Message-ID: <0014440c$0$2963$c3e8da3@news.astraweb.com> On Tue, 18 Aug 2009 10:04:36 -0400, John Posner wrote: > While refactoring some code, I ran across an opportunity to use a > conditional expression. Original: > > if total > P.BASE: > excessblk = Block(total - P.BASE, srccol, > carry_button_suppress=True) > else: > excessblk = None > > Is there any consensus on how to format a conditional expression that is > too long for one line? Er, that defeats the purpose of using a conditional expression. If it's too long for one line, leave it as an if...else statement. > How about this: > > excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) > if total > P.BASE else > None) If you insist on using the conditional expression, my preference would be: excessblk = ( Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None ) -- Steven From jjposner at optimum.net Tue Aug 18 10:58:05 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 18 Aug 2009 10:58:05 -0400 Subject: Code formatting question: conditional expression In-Reply-To: References: Message-ID: <4A8AC17D.5080602@optimum.net> > > My choice would be > > excessblk = None > if total > P.BASE: > excessblk = ... > Diez and Jean-Michel, Ha! Your suggestion above was my *original* coding. It looks like I'm evolving backwards! But doesn't it violate the DRY principle? The token "excessblk" appears twice instead of once. Thanks again, John From dmitrey.kroshko at scipy.org Tue Aug 18 11:19:12 2009 From: dmitrey.kroshko at scipy.org (dmitrey) Date: Tue, 18 Aug 2009 08:19:12 -0700 (PDT) Subject: simplest way to visit 3 subdirectories with a command? Message-ID: <487d46f0-db01-4134-b9a8-8360f5dc82f6@w41g2000yqb.googlegroups.com> hi all, could you inform how to compose a py-file (for soft installation), that will visit 3 subdirectories (eg subdir1, subdir2, subdir3) and invoke a command "python setup.py install" in each subdirectory? I know there should be a simple solution available in Python documentation, but I have an awful lots of other things to be done, so could someone write these several lines of code? Thank you in advance, D. From R.Brodie at rl.ac.uk Tue Aug 18 11:27:52 2009 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 18 Aug 2009 16:27:52 +0100 Subject: Code formatting question: conditional expression References: Message-ID: "John Posner" wrote in message news:mailman.26.1250604346.2854.python-list at python.org... > if total > P.BASE: > excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) > else: > excessblk = None I wonder if it is appropriate to replace the None sentinel with one that is an instance of Block() e.g. size = total - P.BASE excessblk = Block(size, srccol, carry_button_suppress=True, empty_block=(size <= 0) ) From holdenweb at gmail.com Tue Aug 18 11:55:54 2009 From: holdenweb at gmail.com (Steve Holden) Date: Tue, 18 Aug 2009 08:55:54 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> > > Robert Dailey: [...] > > It's a figure of speech. And besides, why would I want programming > advice from a woman? lol. Thanks for the help. Sorry, Robert, simply not acceptable. Whether designed to be funny or not it's the kind of inane remark I would be really happy never to see again. The problem is that we can't just "let these things go by" all the time (even though we aren't discussing a major crime here). If we do that it encourages (at best) an atmosphere of complacency and a feeling that it's OK to demean people in Python forums. I'd really like to see those *not* get a hold. regards Steve From jeanmichel at sequans.com Tue Aug 18 11:57:01 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 18 Aug 2009 17:57:01 +0200 Subject: Code formatting question: conditional expression In-Reply-To: <4A8AC17D.5080602@optimum.net> References: <4A8AC17D.5080602@optimum.net> Message-ID: <4A8ACF4D.2080805@sequans.com> John Posner wrote: >> >> My choice would be >> >> excessblk = None >> if total > P.BASE: >> excessblk = ... >> > > Diez and Jean-Michel, > > Ha! Your suggestion above was my *original* coding. It looks like I'm > evolving backwards! > > But doesn't it violate the DRY principle? The token "excessblk" > appears twice instead of once. > > Thanks again, > John > I don't see any problem in that. You are hunting poor readability, not redundancy, it's up to you to decide of you priorities. I would still advise that readability should rule your world. JM From deets at nospam.web.de Tue Aug 18 11:57:28 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 17:57:28 +0200 Subject: Start-up program References: Message-ID: <7f01b8F2hfu8qU1@mid.uni-berlin.de> Virgil Stokes wrote: > How difficult is to create a program that will be executed when Windows > Vista is started? As Windows Calendar does, for example. > > I am actually more interested in the Python tools that might be used for > this task. I hope that this question is not inappropriate for the list. There are many discussions here about creating an exe (py2exe) that you could start in autostart, and how to run scripts as windows services, which is the other option. Just google a bit. Diez From jeanmichel at sequans.com Tue Aug 18 12:00:09 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 18 Aug 2009 18:00:09 +0200 Subject: Start-up program In-Reply-To: <4A8ABA78.8050605@it.uu.se> References: <4A8ABA78.8050605@it.uu.se> Message-ID: <4A8AD009.5050005@sequans.com> Virgil Stokes wrote: > How difficult is to create a program that will be executed when > Windows Vista is started? As Windows Calendar does, for example. > > I am actually more interested in the Python tools that might be used > for this task. I hope that this question is not inappropriate for the > list. :-\ > > --V > Well put your program in your startup folder or configure it as a service in the service manager of windows. Now your problem becomes "How difficult is to create a program" for which there is no easy answer as it really depends on the kind of program. JM From madzientist at gmail.com Tue Aug 18 12:04:54 2009 From: madzientist at gmail.com (madzientist) Date: Tue, 18 Aug 2009 09:04:54 -0700 (PDT) Subject: Mac OS 9.2 Message-ID: <96ab6db4-55c5-4142-8ef8-d7fbe97e4c4d@f37g2000yqn.googlegroups.com> hi, i have to work with mac OS 9.2 for legacy reasons...is there a compiled version of python for this os ? i need to get input about variable values from the user and then print out some text files that make use of this input. a gui would be nice, but keyboard based input would be ok too... thanks much, suresh ps. if there isn't a version of pythn that will work, perhaps you could suggest some other scripting language for 0S 9.2 ? From python at mrabarnett.plus.com Tue Aug 18 12:09:24 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 18 Aug 2009 17:09:24 +0100 Subject: Start-up program In-Reply-To: <4A8ABA78.8050605@it.uu.se> References: <4A8ABA78.8050605@it.uu.se> Message-ID: <4A8AD234.7050205@mrabarnett.plus.com> Virgil Stokes wrote: > How difficult is to create a program that will be executed when Windows > Vista is started? As Windows Calendar does, for example. > > I am actually more interested in the Python tools that might be used for > this task. I hope that this question is not inappropriate for the list. :-\ > Look for the Windows Startup folder. A quick search with Google found: http://www.bleepingcomputer.com/forums/topic85142.html From nirvana117 at gmail.com Tue Aug 18 12:49:55 2009 From: nirvana117 at gmail.com (dou dou) Date: Wed, 19 Aug 2009 00:49:55 +0800 Subject: problem with interface of operator.itemgetter In-Reply-To: <50f98a4c0908161132o4bf73e80lf306f89108c1e669@mail.gmail.com> References: <19b355330908132016y49f2679u631c3123fcfc920a@mail.gmail.com> <50f98a4c0908161132o4bf73e80lf306f89108c1e669@mail.gmail.com> Message-ID: <19b355330908180949x2f8635dfk39ae892a9f6943b2@mail.gmail.com> 2009/8/17 Simon Forman > You can use a little helper function to create your itemgetter like this: > > def makeItemGetter(indexes): > I = itemgetter(*indexes) > if len(indexes) > 1: > return I > return lambda thing: (I(thing),) > > If indexes contains only one index the itemgetter is wrapped in a > lambda that turns its output into a tuple. Thanks. I just thought if the stdlib could support some function like item*s *getter would be better, it always returns tuple instead of a item or a tuple of items. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jeanmichel at sequans.com Tue Aug 18 13:05:49 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 18 Aug 2009 19:05:49 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> Message-ID: <4A8ADF6D.2030405@sequans.com> Steve Holden wrote: >>> Robert Dailey: >>> > [...] > >> It's a figure of speech. And besides, why would I want programming >> advice from a woman? lol. Thanks for the help. >> > > Sorry, Robert, simply not acceptable. Whether designed to be funny or > not it's the kind of inane remark I would be really happy never to see > again. > > The problem is that we can't just "let these things go by" all the > time (even though we aren't discussing a major crime here). If we do > that it encourages (at best) an atmosphere of complacency and a > feeling that it's OK to demean people in Python forums. I'd really > like to see those *not* get a hold. > > regards > Steve > Did you read the original post (this is an old one) ? Because quoting a joke out of its context is totally unfair. Anyway the hysteria that is surrounding this thread is just amazing. I'm waiting for more. JM From james.harris.1 at googlemail.com Tue Aug 18 13:09:29 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Tue, 18 Aug 2009 10:09:29 -0700 (PDT) Subject: Identifying a class type - bad practice? Message-ID: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> I am writing some code to form a tree of nodes of different types. The idea is to define one class per node type such as class node_type_1(node): class node_type_2(node): etc (Class "node" would hold any common properties). When walking the tree I need to know what type of node I'm dealing with so polymorphism isn't generally useful. The action to be taken depends on the node type. Two options appear to be useful: __class__ and isinstance. I know the latter will match the instance against any superclass and the former will match one class only. My question is: is this the Pythonic way to deal with such a tree? Is there a better way? In C I would use structs where one field was a tag indicating the kind of struct. James From python.list at tim.thechases.com Tue Aug 18 13:11:54 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 18 Aug 2009 12:11:54 -0500 Subject: simplest way to visit 3 subdirectories with a command? In-Reply-To: <487d46f0-db01-4134-b9a8-8360f5dc82f6@w41g2000yqb.googlegroups.com> References: <487d46f0-db01-4134-b9a8-8360f5dc82f6@w41g2000yqb.googlegroups.com> Message-ID: <4A8AE0DA.1080909@tim.thechases.com> > could you inform how to compose a py-file (for soft installation), > that will visit 3 subdirectories (eg subdir1, subdir2, subdir3) and > invoke a command "python setup.py install" in each subdirectory? > I know there should be a simple solution available in Python If you're executing "python setup.py install", that sounds like you're operating at the shell level, not within python. In which case, I'd just use my shell's iteration capabilities: # running bash on a *nix-like OS bash$ for dir in subdir1 subdir2 subdir3; do pushd $dir; python setup.py install; popd; done # running within Win32's cmd.exe c:\temp\> for %f in (subdir1 subdir2 subdir3) do pushd %f & python setup.py install & popd or something of the sort. Remember in Win32 that the variables have to be escaped if you put them in a batch file ("%%f" instead of "%f") -tkc From seldan24 at gmail.com Tue Aug 18 13:18:42 2009 From: seldan24 at gmail.com (seldan24) Date: Tue, 18 Aug 2009 10:18:42 -0700 (PDT) Subject: Using a Callback Function - ftplib References: <76875cdd-30c4-4a3b-8a16-d0e2061765d7@v2g2000vbb.googlegroups.com> <1euafoc8zeh0q.91hedjv5ueuh$.dlg@40tude.net> Message-ID: On Aug 18, 6:02?am, Nitebirdz wrote: > On Mon, Aug 17, 2009 at 11:10:25AM -0700, seldan24 wrote: > > > I didn't even notice the higher level methods. ?I changed the > > retrieval line to: > > > ftp.nlst("testfile*.txt") > > > This works great. ?The result is even captured in an array. ?I really > > have no idea what the difference between a LIST and NLST is within > > FTP. ?Never delved that deep into it. ?I did notice that an NLST will > > return a specific FTP code if a file doesn't exist, whereas a LIST > > doesn't. ?So, I ended up using NLST as that'll generate an > > ftplib.error_perm exception. ?Based on if the job cares if a file is > > not available or not (some do, some don't), I'll either exit, or > > continue on with the file loop. > > The following thread from a NetBSD mailing list may help clarify this > issue: > > http://mail-index.netbsd.org/netbsd-users/2001/01/30/0016.html > > NLST returns a machine-readable list of names, while LIST returns a > human-readable list. ?Hene the presence of the FTP code in the case of > NLST. ? Nitebirdz, Thanks for the information. I knew it stood for 'named list' but had no idea how that differed from the standard. I appreciate the link. From madzientist at gmail.com Tue Aug 18 13:19:10 2009 From: madzientist at gmail.com (madzientist) Date: Tue, 18 Aug 2009 10:19:10 -0700 (PDT) Subject: Mac OS 9.2 References: <96ab6db4-55c5-4142-8ef8-d7fbe97e4c4d@f37g2000yqn.googlegroups.com> Message-ID: <5ed2205e-9542-44c3-a8b7-70f52b0d09cb@r38g2000yqn.googlegroups.com> ok, i found macpython 2.3 at this site: http://homepages.cwi.nl/~jack/macpython/macpython-older.html is this the best option for me in terms of using python on os 9.2 ? thanks much !! suresh On Aug 18, 6:04?pm, madzientist wrote: > hi, > > i have to work with mac OS 9.2 for legacy reasons...is there a > compiled version of python for this os ? i need to get input about > variable values from the user and then print out some text files that > make use of this input. a gui would be nice, but keyboard based input > would be ok too... > > thanks much, > > suresh > > ps. if there isn't a version of pythn that will work, perhaps you > could suggest some other scripting language for 0S 9.2 ? From jjposner at optimum.net Tue Aug 18 13:25:46 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 18 Aug 2009 13:25:46 -0400 Subject: Code formatting question: conditional expression In-Reply-To: References: Message-ID: <4A8AE41A.3060107@optimum.net> > I wonder if it is appropriate to replace the None sentinel with one that is an instance > of Block() e.g. > > size = total - P.BASE > excessblk = Block(size, srccol, carry_button_suppress=True, empty_block=(size <= 0) ) > In this particular case, Richard, I don't think so. The Block class is an application-level wrapper for a graphical object. I don't want to worry about zero-size objects. ("Is this column really empty, or does it contain one or more zero-size blocks?") If you're interested, take a look at "BlockHead" at www.jjposner.net. BTW, from the (admittedly few) responses to my original post, it seems there's some sentiment that "conditional expressions" are a non-Pythonic misfeature. Interesting ... -John From chris at simplistix.co.uk Tue Aug 18 13:39:10 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 18 Aug 2009 18:39:10 +0100 Subject: xlutils 1.4.0 released! Message-ID: <4A8AE73E.9030504@simplistix.co.uk> Hi All, I'm pleased to announce a new release of xlutils. This is a small collection of utilities that make use of both xlrd and xlwt to process Microsoft Excel files. The changes for this release are as follows: - Add sheet density information and onesheet option to xlutils.margins. - Reduced the memory footprint of xlutils.filter.ColumnTrimmer at the expense of speed. - Fixed incorrect warnings about boolean cells in xlutils.filter.ErrorFilter. xlwt has always supported boolean cells. - xlutils.filter.BaseReader now opens workbooks with on_demand = True - Added support for xlrd Books opened with on_demand as True passed to open_workbook. - Fixed bug when copying error cells. - Requires the latest versions of xlrd (0.7.1) and xlwt (0.7.2). To find out more, please read here: http://www.simplistix.co.uk/software/python/xlutils In case you're not aware, xlrd and xlwt are two excellent pure-python libraries for reading and writing Excel files. They run on any platform and, likely, any implementation of Python without the need for horrific things like binding to Excel via COM and so needing a Windows machine. If you use any of xlrd, xlwt or xlutils, the following google group will be of use: http://groups.google.com.au/group/python-excel Hope some of this is of interest, I'd love to hear from anyone who ends up using it! cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From rcdailey at gmail.com Tue Aug 18 14:19:28 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 11:19:28 -0700 (PDT) Subject: Parallelization in Python 2.6 Message-ID: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> I'm looking for a way to parallelize my python script without using typical threading primitives. For example, C++ has pthreads and TBB to break things into "tasks". I would like to see something like this for python. So, if I have a very linear script: doStuff1() doStuff2() I can parallelize it easily like so: create_task( doStuff1 ) create_task( doStuff2 ) Both of these functions would be called from new threads, and once execution ends the threads would die. I realize this is a simple example and I could create my own classes for this functionality, but I do not want to bother if a solution already exists. Thanks in advance. From stefan_ml at behnel.de Tue Aug 18 14:41:18 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 18 Aug 2009 20:41:18 +0200 Subject: Parallelization in Python 2.6 In-Reply-To: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> Message-ID: <4a8af5ce$0$30224$9b4e6d93@newsspool1.arcor-online.net> Robert Dailey wrote: > I'm looking for a way to parallelize my python script without using > typical threading primitives. For example, C++ has pthreads and TBB to > break things into "tasks". I would like to see something like this for > python. So, if I have a very linear script: > > doStuff1() > doStuff2() > > > I can parallelize it easily like so: > > create_task( doStuff1 ) > create_task( doStuff2 ) > > Both of these functions would be called from new threads, and once > execution ends the threads would die. I realize this is a simple > example and I could create my own classes for this functionality, but > I do not want to bother if a solution already exists. I think the canonical answer is to use the threading module or (preferably) the multiprocessing module, which is new in Py2.6. http://docs.python.org/library/threading.html http://docs.python.org/library/multiprocessing.html Both share a (mostly) common interface and are simple enough to use. They are pretty close to the above interface already. Stefan From ethan at stoneleaf.us Tue Aug 18 14:43:36 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 Aug 2009 11:43:36 -0700 Subject: Code formatting question: conditional expression In-Reply-To: <4A8AE41A.3060107@optimum.net> References: <4A8AE41A.3060107@optimum.net> Message-ID: <4A8AF658.4090400@stoneleaf.us> John Posner wrote: > > BTW, from the (admittedly few) responses to my original post, it seems > there's some sentiment that "conditional expressions" are a non-Pythonic > misfeature. Interesting ... > > -John > > > I didn't read it that way. One of the (to me) core points of Pythonic is readability. A conditional expression on one line is fine -- a conditional expression on more than one line is less readable than the standard if-else structure. ~Ethan~ From ethan at stoneleaf.us Tue Aug 18 15:08:42 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Tue, 18 Aug 2009 12:08:42 -0700 Subject: Identifying a class type - bad practice? In-Reply-To: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> References: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> Message-ID: <4A8AFC3A.4000608@stoneleaf.us> James Harris wrote: > I am writing some code to form a tree of nodes of different types. The > idea is to define one class per node type such as > > class node_type_1(node): > > class node_type_2(node): > > etc > > (Class "node" would hold any common properties). > > When walking the tree I need to know what type of node I'm dealing > with so polymorphism isn't generally useful. The action to be taken > depends on the node type. Two options appear to be useful: __class__ > and isinstance. I know the latter will match the instance against any > superclass and the former will match one class only. > > My question is: is this the Pythonic way to deal with such a tree? Is > there a better way? In C I would use structs where one field was a tag > indicating the kind of struct. > > James I would recommend going with isinstance. An instance of node_type_2 will not be an instance node_type_1, so no worries there, and it leaves open the option of subclassing further if you need to later on. ~Ethan~ From andre.roberge at gmail.com Tue Aug 18 15:24:18 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Tue, 18 Aug 2009 12:24:18 -0700 (PDT) Subject: Identifying a class type - bad practice? References: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> Message-ID: <0aab1195-8ae5-4550-993f-bec9aca7e27e@p23g2000vbl.googlegroups.com> On Aug 18, 2:09?pm, James Harris wrote: > I am writing some code to form a tree of nodes of different types. The > idea is to define one class per node type such as > > class node_type_1(node): > ? > class node_type_2(node): > ? > etc > > (Class "node" would hold any common properties). > > When walking the tree I need to know what type of node I'm dealing > with so polymorphism isn't generally useful. The action to be taken > depends on the node type. Two options appear to be useful: __class__ > and isinstance. I know the latter will match the instance against any > superclass and the former will match one class only. > > My question is: is this the Pythonic way to deal with such a tree? Is > there a better way? In C I would use structs where one field was a tag > indicating the kind of struct. > > James I would probably go with hasattr(instance, 'what_I_want') Andr? From sajmikins at gmail.com Tue Aug 18 15:42:10 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 15:42:10 -0400 Subject: comparing XML files to eachother In-Reply-To: <9583ed900908171251k50fafaefrd626439bf1bd9a3c@mail.gmail.com> References: <9583ed900908171251k50fafaefrd626439bf1bd9a3c@mail.gmail.com> Message-ID: <50f98a4c0908181242w734a3b64k68b8928bdef0c88d@mail.gmail.com> On Mon, Aug 17, 2009 at 3:51 PM, David Brochu wrote: > I need to compare one xml document to another to see if the content matches. > Unfortunately, the formatting (spacing) and order of elements may change > between files from run to run. I have looked into xml dom minidom but can't > seem to find how to accomplish this. Does anyone know how I can do a compare > between two XML documents using the STL? It seems to me that you're going to have to "normalize" the documents to be able to compare them. (I.e. strip or ignore spacing differences, sort the elements to be in the same order, etc..) From pavpanchekha at gmail.com Tue Aug 18 15:44:55 2009 From: pavpanchekha at gmail.com (Pavel Panchekha) Date: Tue, 18 Aug 2009 12:44:55 -0700 (PDT) Subject: Inheriting dictionary Message-ID: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> I want a dictionary that will transparently "inherit" from a parent dictionary. So, for example: """ a = InheritDict({1: "one", 2: "two", 4: "four"}) b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) a[1] # "one" a[4] # "four" b[1] # "one" b[3] # "three" b[4] # "foobar" """ I've written something like this in Python already, but I'm wondering if something like this already exists, preferably written in C, for speed. From zuo at chopin.edu.pl Tue Aug 18 15:48:58 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 21:48:58 +0200 Subject: Code formatting question: conditional expression In-Reply-To: <0014440c$0$2963$c3e8da3@news.astraweb.com> References: <0014440c$0$2963$c3e8da3@news.astraweb.com> Message-ID: 18-08-2009 Steven D'Aprano wrote: > On Tue, 18 Aug 2009 10:04:36 -0400, John Posner wrote: > [snip] >> How about this: >> >> excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) >> if total > P.BASE else >> None) > > If you insist on using the conditional expression, my preference would > be: > > excessblk = ( > Block(total - P.BASE, srccol, carry_button_suppress=True) > if total > P.BASE else None > ) Generally I'd prefer: excessblk = (Block(........) if total > P.BASE else None) But it this case first line would be too long, then I'd try using: excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None) or excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None) I'd use conditional expression only (rather) in situation when the first expression-part was 'common' and the other (after else) was 'rare'. Cheers, *j -- Jan Kaliszewski (zuo) From code at pizzashack.org Tue Aug 18 16:10:15 2009 From: code at pizzashack.org (Derek Martin) Date: Tue, 18 Aug 2009 15:10:15 -0500 Subject: basic thread question Message-ID: <20090818201015.GP20434@dragontoe.org> I have some simple threaded code... If I run this with an arg of 1 (start one thread), it pegs one cpu, as I would expect. If I run it with an arg of 2 (start 2 threads), it uses both CPUs, but utilization of both is less than 50%. Can anyone explain why? I do not pretend it's impeccable code, and I'm not looking for a critiqe of the code per se, excepting the case where what I've written is actually *wrong*. I hacked this together in a couple of minutes, with the intent of pegging my CPUs. Performance with two threads is actually *worse* than with one, which is highly unintuitive. I can accomplish my goal very easily with bash, but I still want to understand what's going on here... The OS is Linux 2.6.24, on a Ubuntu base. Here's the code: Thanks -=-=-=-=- #!/usr/bin/python import thread, sys, time def busy(thread): x=0 while True: x+=1 if __name__ == '__main__': try: cpus = int(sys.argv[1]) except ValueError: cpus = 1 print "cpus = %d, argv[1] = %s\n" % (cpus, sys.argv[1]) i=0 thread_list = [] while i < cpus: x = thread.start_new_thread(busy, (i,)) thread_list.append(x) i+=1 while True: pass -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From zuo at chopin.edu.pl Tue Aug 18 16:23:09 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 22:23:09 +0200 Subject: Inheriting dictionary In-Reply-To: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: 18-08-2009 o 21:44:55 Pavel Panchekha wrote: > I want a dictionary that will transparently "inherit" from a parent > dictionary. So, for example: > > """ > a = InheritDict({1: "one", 2: "two", 4: "four"}) > b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) > > a[1] # "one" > a[4] # "four" > b[1] # "one" > b[3] # "three" > b[4] # "foobar" > """ > > I've written something like this in Python already, but I'm wondering > if something like this already exists, preferably written in C, for > speed. AFAIN -- no. But you can easily implement it in Python with rather small loss of speed... class InheritDict(dict): class NoParent(object): def __getitem__(self, key): raise KeyError('There is no %r key in the hierarchy' % key) def __nonzero__(self): return False noparent = NoParent() def __init__(self, *args, **kwargs): parent = kwargs.pop('inherit_from', self.noparent) dict.__init__(self, *args, **kwargs) self.parent = parent def __getitem__(self, key): try: return dict.__getitem__(self, key) except KeyError: return self.parent[key] Did you do it in similar way? (just curiosity) :-) Regards, *j -- Jan Kaliszewski (zuo) From nat.williams at gmail.com Tue Aug 18 16:27:41 2009 From: nat.williams at gmail.com (Nat Williams) Date: Tue, 18 Aug 2009 15:27:41 -0500 Subject: Inheriting dictionary In-Reply-To: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: On Tue, Aug 18, 2009 at 2:44 PM, Pavel Panchekha wrote: > I want a dictionary that will transparently "inherit" from a parent > dictionary. So, for example: > > """ > a = InheritDict({1: "one", 2: "two", 4: "four"}) > b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) > > a[1] # "one" > a[4] # "four" > b[1] # "one" > b[3] # "three" > b[4] # "foobar" > """ > > I've written something like this in Python already, but I'm wondering > if something like this already exists, preferably written in C, for > speed. Why complicate this with a custom object? Just use regular dicts and make b a copy of a. a = {1: 'one', 2: 'two', 4: 'four'} b = dict(a) b[3] = 'three' b[4] = 'foobar' -------------- next part -------------- An HTML attachment was scrubbed... URL: From rcdailey at gmail.com Tue Aug 18 16:27:49 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:27:49 -0700 (PDT) Subject: How to create functors? Message-ID: Hello, I want to simply wrap a function up into an object so it can be called with no parameters. The parameters that it would otherwise have taken are already filled in. Like so: print1 = lambda: print( "Foobar" ) print1() However, the above code fails with: File "C:\IT\work\distro_test\distribute_radix.py", line 286 print1 = lambda: print( "Foobar" ) ^ SyntaxError: invalid syntax How can I get this working? From duncan.booth at invalid.invalid Tue Aug 18 16:31:51 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Aug 2009 20:31:51 GMT Subject: How to create functors? References: Message-ID: Robert Dailey wrote: > Hello, > > I want to simply wrap a function up into an object so it can be called > with no parameters. The parameters that it would otherwise have taken > are already filled in. Like so: > > > print1 = lambda: print( "Foobar" ) > print1() > > However, the above code fails with: > > File "C:\IT\work\distro_test\distribute_radix.py", line 286 > print1 = lambda: print( "Foobar" ) > ^ > SyntaxError: invalid syntax > > How can I get this working? def print1(): print "Foobar" It looks like in your version of Python "print" isn't a function. It always helps if you say the exact version you are using in your question as the exact answer you need may vary. From rcdailey at gmail.com Tue Aug 18 16:32:55 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:32:55 -0700 (PDT) Subject: How to create functors? References: Message-ID: On Aug 18, 3:31?pm, Duncan Booth wrote: > Robert Dailey wrote: > > Hello, > > > I want to simply wrap a function up into an object so it can be called > > with no parameters. The parameters that it would otherwise have taken > > are already filled in. Like so: > > > ? ? ? print1 = lambda: print( "Foobar" ) > > ? ? ? print1() > > > However, the above code fails with: > > > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 > > ? ? print1 = lambda: print( "Foobar" ) > > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > > SyntaxError: invalid syntax > > > How can I get this working? > > def print1(): > ? ? print "Foobar" > > It looks like in your version of Python "print" isn't a function. It always > helps if you say the exact version you are using in your question as the > exact answer you need may vary. I'm using Python 2.6. And using the legacy syntax in the lambda does not work either. I want to avoid using a def if possible. Thanks. From pavpanchekha at gmail.com Tue Aug 18 16:32:58 2009 From: pavpanchekha at gmail.com (Pavel Panchekha) Date: Tue, 18 Aug 2009 13:32:58 -0700 (PDT) Subject: Inheriting dictionary References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: <54699ee8-9c14-4aea-be86-06ef49be86c5@d21g2000vbm.googlegroups.com> On Aug 18, 4:23?pm, "Jan Kaliszewski" wrote: > 18-08-2009 o 21:44:55 Pavel Panchekha wrote: > > > > > I want a dictionary that will transparently "inherit" from a parent > > dictionary. So, for example: > > > """ > > a = InheritDict({1: "one", 2: "two", 4: "four"}) > > b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) > > > a[1] # "one" > > a[4] # "four" > > b[1] # "one" > > b[3] # "three" > > b[4] # "foobar" > > """ > > > I've written something like this in Python already, but I'm wondering > > if something like this already exists, preferably written in C, for > > speed. > > AFAIN -- no. But you can easily implement it in Python with rather > small loss of speed... > > ? class InheritDict(dict): > > ? ? ? class NoParent(object): > ? ? ? ? ? def __getitem__(self, key): > ? ? ? ? ? ? ? raise KeyError('There is no %r key in the hierarchy' % key) > ? ? ? ? ? def __nonzero__(self): > ? ? ? ? ? ? ? return False > > ? ? ? noparent = NoParent() > > ? ? ? def __init__(self, *args, **kwargs): > ? ? ? ? ? parent = kwargs.pop('inherit_from', self.noparent) > ? ? ? ? ? dict.__init__(self, *args, **kwargs) > ? ? ? ? ? self.parent = parent > > ? ? ? def __getitem__(self, key): > ? ? ? ? ? try: > ? ? ? ? ? ? ? return dict.__getitem__(self, key) > ? ? ? ? ? except KeyError: > ? ? ? ? ? ? ? return self.parent[key] > > Did you do it in similar way? (just curiosity) :-) > > Regards, > *j > > -- > Jan Kaliszewski (zuo) I implemented it in a similar way (instead of a try block, an if block, which works a tiny bit faster; also have a multiple-parents case, but its rare, and I could do that in Python without much loss of speed). Pity that there's no C version; this InheritDict is kind of the core of my application (in a very basic test, I have 329901 calls to __getitem__). Oh well; I'll see if I can optimize the __getattr__ function with minor tweaking. Thanks for your help. From rcdailey at gmail.com Tue Aug 18 16:36:07 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:36:07 -0700 (PDT) Subject: How to create functors? References: Message-ID: On Aug 18, 3:31?pm, Duncan Booth wrote: > Robert Dailey wrote: > > Hello, > > > I want to simply wrap a function up into an object so it can be called > > with no parameters. The parameters that it would otherwise have taken > > are already filled in. Like so: > > > ? ? ? print1 = lambda: print( "Foobar" ) > > ? ? ? print1() > > > However, the above code fails with: > > > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 > > ? ? print1 = lambda: print( "Foobar" ) > > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > > SyntaxError: invalid syntax > > > How can I get this working? > > def print1(): > ? ? print "Foobar" > > It looks like in your version of Python "print" isn't a function. It always > helps if you say the exact version you are using in your question as the > exact answer you need may vary. Seems like it works fine on everything else except for print(). For example: print1 = lambda: MyFunction( "FooBar" ) The syntax above is accepted by the interpreter. From sajmikins at gmail.com Tue Aug 18 16:37:21 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 16:37:21 -0400 Subject: define class over 2 files In-Reply-To: References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> Message-ID: <50f98a4c0908181337q6295f977ubcf8edab02fef5cb@mail.gmail.com> On Tue, Aug 18, 2009 at 1:57 AM, Steven D'Aprano wrote: > On Mon, 17 Aug 2009 21:45:57 -0700, naveen wrote: > >> Is it possible to split up a class definition over multiple files? > > Not exactly, but you can do variations of this: > > > In file A.py, create: > > class Parent: > ? ?def method(self): > ? ? ? ?return "Method" > > > In file B.py, do this: > > import A > class Child(B.parent): class Child(A.Parent): From clp2 at rebertia.com Tue Aug 18 16:40:37 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 13:40:37 -0700 Subject: How to create functors? In-Reply-To: References: Message-ID: <50697b2c0908181340n48f510cdx79ee9ceeb416d4a5@mail.gmail.com> On Tue, Aug 18, 2009 at 1:32 PM, Robert Dailey wrote: > On Aug 18, 3:31?pm, Duncan Booth wrote: >> Robert Dailey wrote: >> > Hello, >> >> > I want to simply wrap a function up into an object so it can be called >> > with no parameters. The parameters that it would otherwise have taken >> > are already filled in. Like so: >> >> > ? ? ? print1 = lambda: print( "Foobar" ) >> > ? ? ? print1() >> >> > However, the above code fails with: >> >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 >> > ? ? print1 = lambda: print( "Foobar" ) >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ >> > SyntaxError: invalid syntax >> >> > How can I get this working? >> >> def print1(): >> ? ? print "Foobar" >> >> It looks like in your version of Python "print" isn't a function. It always >> helps if you say the exact version you are using in your question as the >> exact answer you need may vary. > > I'm using Python 2.6. And using the legacy syntax in the lambda does > not work either. I want to avoid using a def if possible. Thanks. chris at morpheus ~ $ python Python 2.6.2 (r262:71600, May 14 2009, 16:34:51) [GCC 4.0.1 (Apple Inc. build 5484)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> print1 = lambda: print( "Foobar" ) File "", line 1 print1 = lambda: print( "Foobar" ) ^ SyntaxError: invalid syntax >>> from __future__ import print_function >>> print1 = lambda: print( "Foobar" ) >>> print1() Foobar Cheers, Chris -- http://blog.rebertia.com From jgardner at jonathangardner.net Tue Aug 18 16:41:16 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Tue, 18 Aug 2009 13:41:16 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> Message-ID: <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> On Aug 18, 11:19?am, Robert Dailey wrote: > I'm looking for a way to parallelize my python script without using > typical threading primitives. For example, C++ has pthreads and TBB to > break things into "tasks". I would like to see something like this for > python. So, if I have a very linear script: > > doStuff1() > doStuff2() > > I can parallelize it easily like so: > > create_task( doStuff1 ) > create_task( doStuff2 ) > > Both of these functions would be called from new threads, and once > execution ends the threads would die. I realize this is a simple > example and I could create my own classes for this functionality, but > I do not want to bother if a solution already exists. > If you haven't heard of the Python GIL, you'll want to find out sooner rather than later. Short summary: Python doesn't do threading very well. There are quite a few parallelization solutions out there for Python, however. (I don't know what they are off the top of my head, however.) The way they work is they have worker processes that can be spread across machines. When you want to parallelize a task, you send off a function to those worker threads. There are some serious caveats and problems, not the least of which is sharing code between the worker threads and the director, so this isn't a great solution. If you're looking for highly parallelized code, Python may not be the right answer. Try something like Erlang or Haskell. From zuo at chopin.edu.pl Tue Aug 18 16:42:46 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 22:42:46 +0200 Subject: define class over 2 files In-Reply-To: <2d56febf0908172158l760256rc703d7d87f04e509@mail.gmail.com> References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> <2d56febf0908172158l760256rc703d7d87f04e509@mail.gmail.com> Message-ID: 18-08-2009 o 06:58:58 Xavier Ho wrote: > On Tue, Aug 18, 2009 at 2:45 PM, naveen wrote: > >> Is it possible to split up a class definition over multiple files? >> - > Answer in short, I don't think so. Why not? --------- File a.py: class MyClass: def foo(self, x): return x * 6 --------- File b.py: import a def bar(self): print 'bar' def baz(self, a): print self.foooo(a) # adding methods by hand: a.MyClass.bar = bar a.MyClass.baz = baz --------- File c.py import a def foooo(self, a): return a * self.foo(4) def baaar(self): print self.baz('tralala') def bazzz(self): print 'bzzzzzzzzzz' # adding methods more automaticly: for name, obj in globals().values(): setattr(a.MyClass, name, obj) > Now why would you want to do that? It's a good question. As others said it's very probable that some other solution would be better (e.g. inheritance). Cheers, *j -- Jan Kaliszewski (zuo) From rcdailey at gmail.com Tue Aug 18 16:42:59 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:42:59 -0700 (PDT) Subject: How to create functors? References: Message-ID: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> On Aug 18, 3:40?pm, Chris Rebert wrote: > On Tue, Aug 18, 2009 at 1:32 PM, Robert Dailey wrote: > > On Aug 18, 3:31?pm, Duncan Booth wrote: > >> Robert Dailey wrote: > >> > Hello, > > >> > I want to simply wrap a function up into an object so it can be called > >> > with no parameters. The parameters that it would otherwise have taken > >> > are already filled in. Like so: > > >> > ? ? ? print1 = lambda: print( "Foobar" ) > >> > ? ? ? print1() > > >> > However, the above code fails with: > > >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 > >> > ? ? print1 = lambda: print( "Foobar" ) > >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > >> > SyntaxError: invalid syntax > > >> > How can I get this working? > > >> def print1(): > >> ? ? print "Foobar" > > >> It looks like in your version of Python "print" isn't a function. It always > >> helps if you say the exact version you are using in your question as the > >> exact answer you need may vary. > > > I'm using Python 2.6. And using the legacy syntax in the lambda does > > not work either. I want to avoid using a def if possible. Thanks. > > chris at morpheus ~ $ python > Python 2.6.2 (r262:71600, May 14 2009, 16:34:51) > [GCC 4.0.1 (Apple Inc. build 5484)] on darwin > Type "help", "copyright", "credits" or "license" for more information.>>> print1 = lambda: print( "Foobar" ) > > ? File "", line 1 > ? ? print1 = lambda: print( "Foobar" ) > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > SyntaxError: invalid syntax>>> from __future__ import print_function > >>> print1 = lambda: print( "Foobar" ) > >>> print1() > > Foobar > > Cheers, > Chris > --http://blog.rebertia.com I see what you're saying now. However, why am I able to use print as a function in general-purpose code in my Python 2.6 script, like so: def SomeFunction(): print( "Hello World" ) But, I am not able to do this: SomeFunction = lambda: print( "Hello World" ) ?????? Doesn't make sense. From rcdailey at gmail.com Tue Aug 18 16:45:38 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:45:38 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> Message-ID: <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> On Aug 18, 3:41?pm, Jonathan Gardner wrote: > On Aug 18, 11:19?am, Robert Dailey wrote: > > > > > > > I'm looking for a way to parallelize my python script without using > > typical threading primitives. For example, C++ has pthreads and TBB to > > break things into "tasks". I would like to see something like this for > > python. So, if I have a very linear script: > > > doStuff1() > > doStuff2() > > > I can parallelize it easily like so: > > > create_task( doStuff1 ) > > create_task( doStuff2 ) > > > Both of these functions would be called from new threads, and once > > execution ends the threads would die. I realize this is a simple > > example and I could create my own classes for this functionality, but > > I do not want to bother if a solution already exists. > > If you haven't heard of the Python GIL, you'll want to find out sooner > rather than later. Short summary: Python doesn't do threading very > well. > > There are quite a few parallelization solutions out there for Python, > however. (I don't know what they are off the top of my head, however.) > The way they work is they have worker processes that can be spread > across machines. When you want to parallelize a task, you send off a > function to those worker threads. > > There are some serious caveats and problems, not the least of which is > sharing code between the worker threads and the director, so this > isn't a great solution. > > If you're looking for highly parallelized code, Python may not be the > right answer. Try something like Erlang or Haskell. Really, all I'm trying to do is the most trivial type of parallelization. Take two functions, execute them in parallel. This type of parallelization is called "embarrassingly parallel", and is the simplest form. There are no dependencies between the two functions. They do requires read-only access to shared data, though. And if they are being spawned as sub-processes this could cause problems, unless the multiprocess module creates pipelines or other means to handle this situation. From rami.chowdhury at gmail.com Tue Aug 18 16:45:50 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 18 Aug 2009 13:45:50 -0700 Subject: How to create functors? In-Reply-To: References: Message-ID: Lambda expressions are, I believe, syntactically limited to a single expression -- no statements, like 'print' is in Python 2.x. If you are strongly against just defining a function, you might have to use a trick to get around it -- this page (http://p-nand-q.com/python/stupid_lambda_tricks.html) has some suggestions. On Tue, 18 Aug 2009 13:32:55 -0700, Robert Dailey wrote: > On Aug 18, 3:31?pm, Duncan Booth wrote: >> Robert Dailey wrote: >> > Hello, >> >> > I want to simply wrap a function up into an object so it can be called >> > with no parameters. The parameters that it would otherwise have taken >> > are already filled in. Like so: >> >> > ? ? ? print1 = lambda: print( "Foobar" ) >> > ? ? ? print1() >> >> > However, the above code fails with: >> >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 >> > ? ? print1 = lambda: print( "Foobar" ) >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ >> > SyntaxError: invalid syntax >> >> > How can I get this working? >> >> def print1(): >> ? ? print "Foobar" >> >> It looks like in your version of Python "print" isn't a function. It >> always >> helps if you say the exact version you are using in your question as the >> exact answer you need may vary. > > I'm using Python 2.6. And using the legacy syntax in the lambda does > not work either. I want to avoid using a def if possible. Thanks. -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From nad at acm.org Tue Aug 18 16:46:57 2009 From: nad at acm.org (Ned Deily) Date: Tue, 18 Aug 2009 13:46:57 -0700 Subject: How to create functors? References: Message-ID: In article , Robert Dailey wrote: > On Aug 18, 3:31?pm, Duncan Booth wrote: > > Robert Dailey wrote: > > > Hello, > > > > > I want to simply wrap a function up into an object so it can be called > > > with no parameters. The parameters that it would otherwise have taken > > > are already filled in. Like so: > > > > > ? ? ? print1 = lambda: print( "Foobar" ) > > > ? ? ? print1() > > > > > However, the above code fails with: > > > > > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 > > > ? ? print1 = lambda: print( "Foobar" ) > > > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > > > SyntaxError: invalid syntax > > > > > How can I get this working? > > > > def print1(): > > ? ? print "Foobar" > > > > It looks like in your version of Python "print" isn't a function. It always > > helps if you say the exact version you are using in your question as the > > exact answer you need may vary. > > I'm using Python 2.6. And using the legacy syntax in the lambda does > not work either. I want to avoid using a def if possible. Thanks. The problem is that in Python 2 print is a statement, not a function. That should work fine in Python 3 where print *is* a function. In 2.x, you can wrap print in a function or use something like: >>> import sys >>> print1 = lambda: sys.stdout.write("Foobar\n") >>> print1() Foobar or the pprint library module or various other solutions. -- Ned Deily, nad at acm.org From malaclypse2 at gmail.com Tue Aug 18 16:49:34 2009 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 18 Aug 2009 16:49:34 -0400 Subject: How to create functors? In-Reply-To: References: Message-ID: <16651e80908181349l20efec3do7148c7ef1f2657cb@mail.gmail.com> On Tue, Aug 18, 2009 at 4:27 PM, Robert Dailey wrote: > Hello, > > I want to simply wrap a function up into an object so it can be called > with no parameters. The parameters that it would otherwise have taken > are already filled in. Like so: > > > ? ? ?print1 = lambda: print( "Foobar" ) > ? ? ?print1() > > However, the above code fails with: > > ?File "C:\IT\work\distro_test\distribute_radix.py", line 286 > ? ?print1 = lambda: print( "Foobar" ) > ? ? ? ? ? ? ? ? ? ? ? ? ^ > SyntaxError: invalid syntax > > How can I get this working? You can't, at least not with that example. Lambdas are restricted to a single expression[1]. Print is not an expression, it's a statement[2]. I'm guessing that your use case is not really in wrapping a print statement in an anonymous function. Given the first part of your message, you might find something of use in the functools module, particularly functools.partial [3]. 1: http://docs.python.org/tutorial/controlflow.html#lambda-forms 2: http://docs.python.org/reference/simple_stmts.html 3: http://docs.python.org/library/functools.html#functools.partial -- Jerry From clp2 at rebertia.com Tue Aug 18 16:50:27 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 13:50:27 -0700 Subject: Identifying a class type - bad practice? In-Reply-To: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> References: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> Message-ID: <50697b2c0908181350x5bbfd8e9qe1b7e1d3c13bf49e@mail.gmail.com> On Tue, Aug 18, 2009 at 10:09 AM, James Harris wrote: > I am writing some code to form a tree of nodes of different types. The > idea is to define one class per node type such as > > class node_type_1(node): > ? > class node_type_2(node): > ? > etc > > (Class "node" would hold any common properties). > > When walking the tree I need to know what type of node I'm dealing > with so polymorphism isn't generally useful. The action to be taken > depends on the node type. I'm sure it relates to the exact type of tree you're walking and the calculation you're doing on it, but what is the reason why your code, which in the abstract sounds like it will vaguely resemble this: def walk_tree(tree): if isinstance(tree, node_type_1): #code walk_tree(subtree) elif isinstance(tree, node_type_2): #code walk_tree(subtree) #etc... can't be written instead as: class node_type_1: def walk_tree(self): #code self.subtree.walk() class node_type_2: def walk_tree(self): #code self.subtree.walk() #etc ? Cheers, Chris -- http://blog.rebertia.com From rcdailey at gmail.com Tue Aug 18 16:51:19 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:51:19 -0700 (PDT) Subject: How to create functors? References: Message-ID: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> On Aug 18, 3:45?pm, "Rami Chowdhury" wrote: > Lambda expressions are, I believe, syntactically limited to a single ? > expression -- no statements, like 'print' is in Python 2.x. > > If you are strongly against just defining a function, you might have to ? > use a trick to get around it -- this page ? > (http://p-nand-q.com/python/stupid_lambda_tricks.html) has some ? > suggestions. > > On Tue, 18 Aug 2009 13:32:55 -0700, Robert Dailey ? > wrote: > > > > > > > On Aug 18, 3:31?pm, Duncan Booth wrote: > >> Robert Dailey wrote: > >> > Hello, > > >> > I want to simply wrap a function up into an object so it can be called > >> > with no parameters. The parameters that it would otherwise have taken > >> > are already filled in. Like so: > > >> > ? ? ? print1 = lambda: print( "Foobar" ) > >> > ? ? ? print1() > > >> > However, the above code fails with: > > >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 > >> > ? ? print1 = lambda: print( "Foobar" ) > >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > >> > SyntaxError: invalid syntax > > >> > How can I get this working? > > >> def print1(): > >> ? ? print "Foobar" > > >> It looks like in your version of Python "print" isn't a function. It ? > >> always > >> helps if you say the exact version you are using in your question as the > >> exact answer you need may vary. > > > I'm using Python 2.6. And using the legacy syntax in the lambda does > > not work either. I want to avoid using a def if possible. Thanks. > > -- > Rami Chowdhury > "Never attribute to malice that which can be attributed to stupidity" -- ? > Hanlon's Razor > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) The example I gave earlier is a bit contrived, the real example fundamentally requires a lambda since I am actually passing in local variables into the functions the lambda is wrapping. Example: def MyFunction(): localVariable = 20 CreateTask( lambda: SomeOtherFunction( localVariable ) ) # CreateTask () executes the functor internally This is more or less like the real scenario I'm working with. There are other (more personal) reasons why I prefer to avoid 'def' in this case. I want to keep the functor as central to the code that needs it as possible to improve code readability. Thanks for the help everyone. I guess in Python 3.0 the print() function will not require the import from __future__ to work in this particular case? From zuo at chopin.edu.pl Tue Aug 18 16:51:26 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 22:51:26 +0200 Subject: How to create functors? In-Reply-To: References: Message-ID: 18-08-2009 o 22:32:55 Robert Dailey wrote: > On Aug 18, 3:31?pm, Duncan Booth wrote: >> Robert Dailey wrote: >> > Hello, >> >> > I want to simply wrap a function up into an object so it can be called >> > with no parameters. The parameters that it would otherwise have taken >> > are already filled in. Like so: >> >> > ? ? ? print1 = lambda: print( "Foobar" ) >> > ? ? ? print1() >> >> > However, the above code fails with: >> >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 >> > ? ? print1 = lambda: print( "Foobar" ) >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ >> > SyntaxError: invalid syntax >> >> > How can I get this working? >> >> def print1(): >> ? ? print "Foobar" >> >> It looks like in your version of Python "print" isn't a function. It >> always >> helps if you say the exact version you are using in your question as the >> exact answer you need may vary. > > I'm using Python 2.6. And using the legacy syntax in the lambda does > not work either. In Python 1.x/2.x 'print' is a keyword-based statement, not a function -- then you cannot use it in lambda (which in Python is limited to single expressions, and statements are not allowed in it). You can try using sys.stdout.write() instead. > I want to avoid using a def if possible. But what for? Usualy def is more readable than lambda and it's not worth to lose readibility just to save a few keystrokes. Cheers, *j -- Jan Kaliszewski (zuo) From rcdailey at gmail.com Tue Aug 18 16:52:21 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 13:52:21 -0700 (PDT) Subject: How to create functors? References: Message-ID: <315f52d5-1e0c-48ab-85fb-e5857aedd3ce@s15g2000yqs.googlegroups.com> On Aug 18, 3:51?pm, "Jan Kaliszewski" wrote: > 18-08-2009 o 22:32:55 Robert Dailey wrote: > > > > > > > On Aug 18, 3:31?pm, Duncan Booth wrote: > >> Robert Dailey wrote: > >> > Hello, > > >> > I want to simply wrap a function up into an object so it can be called > >> > with no parameters. The parameters that it would otherwise have taken > >> > are already filled in. Like so: > > >> > ? ? ? print1 = lambda: print( "Foobar" ) > >> > ? ? ? print1() > > >> > However, the above code fails with: > > >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 > >> > ? ? print1 = lambda: print( "Foobar" ) > >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ > >> > SyntaxError: invalid syntax > > >> > How can I get this working? > > >> def print1(): > >> ? ? print "Foobar" > > >> It looks like in your version of Python "print" isn't a function. It ? > >> always > >> helps if you say the exact version you are using in your question as the > >> exact answer you need may vary. > > > I'm using Python 2.6. And using the legacy syntax in the lambda does > > not work either. > > In Python 1.x/2.x 'print' is a keyword-based statement, not a function > -- then you cannot use it in lambda (which in Python is limited to > single expressions, and statements are not allowed in it). > > You can try using sys.stdout.write() instead. > > > I want to avoid using a def if possible. > > But what for? Usualy def is more readable than lambda and it's not worth > to lose readibility just to save a few keystrokes. > > Cheers, > *j > > -- > Jan Kaliszewski (zuo) I posted a bit earlier than you did. See my previous post. Thanks for the help. From invalid at invalid Tue Aug 18 16:55:19 2009 From: invalid at invalid (Grant Edwards) Date: Tue, 18 Aug 2009 15:55:19 -0500 Subject: How to create functors? References: Message-ID: On 2009-08-18, Robert Dailey wrote: > Hello, > > I want to simply wrap a function up into an object so it can be called > with no parameters. The parameters that it would otherwise have taken > are already filled in. Like so: > > > print1 = lambda: print( "Foobar" ) > print1() > > However, the above code fails with: > > File "C:\IT\work\distro_test\distribute_radix.py", line 286 > print1 = lambda: print( "Foobar" ) > ^ > SyntaxError: invalid syntax > > How can I get this working? Doesn't this do what you want? def print1(): return print(" Foobar" ) -- Grant Edwards grante Yow! I want my nose in at lights! visi.com From rami.chowdhury at gmail.com Tue Aug 18 16:57:54 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 18 Aug 2009 13:57:54 -0700 Subject: How to create functors? In-Reply-To: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> References: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> Message-ID: > why am I able to use print as a > function in general-purpose code in my Python 2.6 script I believe it's because that is parsed as the print statement followed by a parenthesized expression. On Tue, 18 Aug 2009 13:42:59 -0700, Robert Dailey wrote: > On Aug 18, 3:40?pm, Chris Rebert wrote: >> On Tue, Aug 18, 2009 at 1:32 PM, Robert Dailey >> wrote: >> > On Aug 18, 3:31?pm, Duncan Booth wrote: >> >> Robert Dailey wrote: >> >> > Hello, >> >> >> > I want to simply wrap a function up into an object so it can be >> called >> >> > with no parameters. The parameters that it would otherwise have >> taken >> >> > are already filled in. Like so: >> >> >> > ? ? ? print1 = lambda: print( "Foobar" ) >> >> > ? ? ? print1() >> >> >> > However, the above code fails with: >> >> >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 >> >> > ? ? print1 = lambda: print( "Foobar" ) >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ >> >> > SyntaxError: invalid syntax >> >> >> > How can I get this working? >> >> >> def print1(): >> >> ? ? print "Foobar" >> >> >> It looks like in your version of Python "print" isn't a function. It >> always >> >> helps if you say the exact version you are using in your question as >> the >> >> exact answer you need may vary. >> >> > I'm using Python 2.6. And using the legacy syntax in the lambda does >> > not work either. I want to avoid using a def if possible. Thanks. >> >> chris at morpheus ~ $ python >> Python 2.6.2 (r262:71600, May 14 2009, 16:34:51) >> [GCC 4.0.1 (Apple Inc. build 5484)] on darwin >> Type "help", "copyright", "credits" or "license" for more >> information.>>> print1 = lambda: print( "Foobar" ) >> >> ? File "", line 1 >> ? ? print1 = lambda: print( "Foobar" ) >> ? ? ? ? ? ? ? ? ? ? ? ? ?^ >> SyntaxError: invalid syntax>>> from __future__ import print_function >> >>> print1 = lambda: print( "Foobar" ) >> >>> print1() >> >> Foobar >> >> Cheers, >> Chris >> --http://blog.rebertia.com > > I see what you're saying now. However, why am I able to use print as a > function in general-purpose code in my Python 2.6 script, like so: > > def SomeFunction(): > print( "Hello World" ) > > But, I am not able to do this: > > SomeFunction = lambda: print( "Hello World" ) > > ?????? > > Doesn't make sense. -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From nad at acm.org Tue Aug 18 17:00:04 2009 From: nad at acm.org (Ned Deily) Date: Tue, 18 Aug 2009 14:00:04 -0700 Subject: How to create functors? References: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> Message-ID: In article <5834f36f-b172-4e76-ad90-7056e7097cdd at o6g2000yqj.googlegroups.com>, Robert Dailey wrote: > I see what you're saying now. However, why am I able to use print as a > function in general-purpose code in my Python 2.6 script, like so: > > def SomeFunction(): > print( "Hello World" ) For the same reason you can do this: >>> x = ( "Hello World" ) >>> type(x) -- Ned Deily, nad at acm.org From zuo at chopin.edu.pl Tue Aug 18 17:01:26 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 23:01:26 +0200 Subject: How to create functors? In-Reply-To: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> References: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> Message-ID: Dnia 18-08-2009 o 22:42:59 Robert Dailey napisa?(a): > I see what you're saying now. However, why am I able to use print as a > function in general-purpose code in my Python 2.6 script, like so: > > def SomeFunction(): > print( "Hello World" ) > > But, I am not able to do this: > > SomeFunction = lambda: print( "Hello World" ) > > ?????? Because (unless you do 'from __future__ import print_function' in Py2.6) it's statement, not a functions. In Python you can put any expression in parentheses -- it's useful for wraping long lines but changes nothing semantically (unless you add a comma -- then you create a tuple, even without parentheses, but it'a another story...). *j -- Jan Kaliszewski (zuo) From gu.yakahughes at gmail.com Tue Aug 18 17:02:16 2009 From: gu.yakahughes at gmail.com (KillSwitch) Date: Tue, 18 Aug 2009 14:02:16 -0700 (PDT) Subject: Editing a wiki Message-ID: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> Hey guys, Is it possible to edit a wiki page with python, including logging in to edit the page, and inserting text into the edit box, etc. I was thinking maybe python would be the language to do this in, because I have to iterate through every line in a text file and gather info about what to enter in the wiki that way, then put that text in a wiki page. It's sort of a program-documenting program. If it's possible to do this, I would make a special way of entering comments in the source files, like maybe --[[##title code here]] and then --[[@@code example here]] with the two symbols at the beginning of the comment dictating what to enter where. Thanks for any input. From rcdailey at gmail.com Tue Aug 18 17:03:51 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 14:03:51 -0700 (PDT) Subject: How to create functors? References: <5834f36f-b172-4e76-ad90-7056e7097cdd@o6g2000yqj.googlegroups.com> Message-ID: On Aug 18, 4:01?pm, "Jan Kaliszewski" wrote: > Dnia 18-08-2009 o 22:42:59 Robert Dailey napisa?(a): > > > I see what you're saying now. However, why am I able to use print as a > > function in general-purpose code in my Python 2.6 script, like so: > > > def SomeFunction(): > > ? ?print( "Hello World" ) > > > But, I am not able to do this: > > > SomeFunction = lambda: print( "Hello World" ) > > > ?????? > > Because (unless you do 'from __future__ import print_function' in Py2.6) > it's statement, not a functions. In Python you can put any expression > in parentheses -- it's useful for wraping long lines but changes nothing > semantically (unless you add a comma -- then you create a tuple, even > without parentheses, but it'a another story...). > > *j > > -- > Jan Kaliszewski (zuo) Ah, I see now. I completely fooled myself. This whole time I thought Python 2.6 was updated to work with both forms of print by default as a convenience, but still maintain the backwards compatibility. I understand the situation now. Thanks to everyone for the help. From lkcl at lkcl.net Tue Aug 18 17:05:54 2009 From: lkcl at lkcl.net (Luke Kenneth Casson Leighton) Date: Tue, 18 Aug 2009 21:05:54 +0000 Subject: [ANN] Pyjamas 0.6 Web Widget Set and python-to-javascript Compiler released Message-ID: Pyjamas 0.6 is finally out: many thanks to everyone who has contributed. Special thanks to Kees Bos; Bernd, Bernd and Jurgen from LovelySystems.com; the people who showed an interest in Pyjamas at EuroPython 2009; and especially to everyone who has helped during the pre-releases, with testing and bugreports over the past few weeks. For a full list of contributors, see CREDITS. Downloads: --------- http://code.google.com/p/pyjamas/downloads http://pypi.python.org/pypi/Pyjamas http://sf.net/projects/pyjamas Pyjamas ------- Pyjamas is a port of Google Web Toolkit to Python, and thus enables the development of Rich Media AJAX applications in Python, with no need for special browser plugins. Pyjamas contains a stand-alone python-to-javascript compiler, and also a Widget Set API that looks very similar to Desktop Widget Set APIs (such as PyQT4 or PyGTK2). For more information, see: http://pyjs.org http://pyjs.org/FAQ.html http://pyjs.org/features.html Known bugs: http://code.google.com/p/pyjamas/issues #227, #228, #229, #230 and #232 Pyjamas-Desktop --------------- Pyjamas runs your application in a Web Browser (as javascript); Pyjamas-Desktop runs exactly the same python application on the Desktop (as python) http://pyjd.org Release 0.6 of Pyjamas also incorporates Pyjamas-Desktop directly into the Pyjamas Distribution. To use Pyjamas-Desktop there are three choices, with more planned [MacOSX PyObjC; KDE's PyKHTML]. 1) - XULRunner install hulahop and python-xpcom. hulahop is distributed with both Debian and Ubuntu; python-xpcom is part of XULRunner and is also distributed with both Debian and Ubuntu. Other users should investigate the installation instructions for python-xpcom and hulahop for the operating system of their choice on the appropriate web sites. GNU/Linux, FreeBSD and other POSIX systems are strongly advised to use XULRunner for Pyjamas-Desktop: it is the most stable of the PyJD ports. 2) - PyWebKitGtk you will need a patched version of pywebkitgtk: http://code.google.com/p/pywebkitgtk/issues/detail?id=13 you will need a patched version of webkit: http://github.com/lkcl/webkit/16401.master Detailed build instructions are available here: http://wiki.github.com/lkcl/webkit/helping-with-16401master 3) - MSHTML (experimental!) For Windows users, all that's required, other than installing python and Internet Explorer, is one further package: Win32 "comtypes". Win32 "comtypes" can be downloaded here: * http://sourceforge.net/projects/comtypes/ The MSHTML version primarily works. Reports using IE8's MSHTML engine would be appreciated. Known bugs: the use of Tab to cycle through Keyboard Focus elements is ineffective; onkeyup and onkeydown events are unresponsive, but oddly onkeypress event handling works. From rami.chowdhury at gmail.com Tue Aug 18 17:11:23 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 18 Aug 2009 14:11:23 -0700 Subject: How to create functors? In-Reply-To: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> References: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> Message-ID: > The example I gave earlier is a bit contrived, the real example > fundamentally requires a lambda since I am actually passing in local > variables into the functions the lambda is wrapping. Example: > > def MyFunction(): > localVariable = 20 > CreateTask( lambda: SomeOtherFunction( localVariable ) ) # CreateTask > () executes the functor internally > > This is more or less like the real scenario I'm working with. You could define a local function ('closure') inside the function: def MyFunction(): localVariable = 20 def UseLocalVariable(): SomeOtherFunction(localVariable) CreateTask(UseLocalVariable) I would suggest this is much better for readability. On Tue, 18 Aug 2009 13:51:19 -0700, Robert Dailey wrote: > On Aug 18, 3:45?pm, "Rami Chowdhury" wrote: >> Lambda expressions are, I believe, syntactically limited to a single ? >> expression -- no statements, like 'print' is in Python 2.x. >> >> If you are strongly against just defining a function, you might have to >> ? >> use a trick to get around it -- this page ? >> (http://p-nand-q.com/python/stupid_lambda_tricks.html) has some ? >> suggestions. >> >> On Tue, 18 Aug 2009 13:32:55 -0700, Robert Dailey ? >> wrote: >> >> >> >> >> >> > On Aug 18, 3:31?pm, Duncan Booth wrote: >> >> Robert Dailey wrote: >> >> > Hello, >> >> >> > I want to simply wrap a function up into an object so it can be >> called >> >> > with no parameters. The parameters that it would otherwise have >> taken >> >> > are already filled in. Like so: >> >> >> > ? ? ? print1 = lambda: print( "Foobar" ) >> >> > ? ? ? print1() >> >> >> > However, the above code fails with: >> >> >> > ? File "C:\IT\work\distro_test\distribute_radix.py", line 286 >> >> > ? ? print1 = lambda: print( "Foobar" ) >> >> > ? ? ? ? ? ? ? ? ? ? ? ? ?^ >> >> > SyntaxError: invalid syntax >> >> >> > How can I get this working? >> >> >> def print1(): >> >> ? ? print "Foobar" >> >> >> It looks like in your version of Python "print" isn't a function. It >> ? >> >> always >> >> helps if you say the exact version you are using in your question as >> the >> >> exact answer you need may vary. >> >> > I'm using Python 2.6. And using the legacy syntax in the lambda does >> > not work either. I want to avoid using a def if possible. Thanks. >> >> -- >> Rami Chowdhury >> "Never attribute to malice that which can be attributed to stupidity" >> -- ? >> Hanlon's Razor >> 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > > The example I gave earlier is a bit contrived, the real example > fundamentally requires a lambda since I am actually passing in local > variables into the functions the lambda is wrapping. Example: > > def MyFunction(): > localVariable = 20 > CreateTask( lambda: SomeOtherFunction( localVariable ) ) # CreateTask > () executes the functor internally > > This is more or less like the real scenario I'm working with. There > are other (more personal) reasons why I prefer to avoid 'def' in this > case. I want to keep the functor as central to the code that needs it > as possible to improve code readability. > > Thanks for the help everyone. I guess in Python 3.0 the print() > function will not require the import from __future__ to work in this > particular case? -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From david.birdsong at gmail.com Tue Aug 18 17:11:25 2009 From: david.birdsong at gmail.com (birdsong) Date: Tue, 18 Aug 2009 14:11:25 -0700 (PDT) Subject: basic thread question References: Message-ID: <07fb2a97-d720-4dcd-9155-9237c1802091@i8g2000pro.googlegroups.com> On Aug 18, 1:10?pm, Derek Martin wrote: > I have some simple threaded code... ?If I run this > with an arg of 1 (start one thread), it pegs one cpu, as I would > expect. ?If I run it with an arg of 2 (start 2 threads), it uses both > CPUs, but utilization of both is less than 50%. ?Can anyone explain > why? ? > > I do not pretend it's impeccable code, and I'm not looking for a > critiqe of the code per se, excepting the case where what I've written > is actually *wrong*. I hacked this together in a couple of minutes, > with the intent of pegging my CPUs. ?Performance with two threads is > actually *worse* than with one, which is highly unintuitive. ?I can > accomplish my goal very easily with bash, but I still want to > understand what's going on here... > > The OS is Linux 2.6.24, on a Ubuntu base. ?Here's the code: > > Thanks > > -=-=-=-=- > > #!/usr/bin/python > > import thread, sys, time > > def busy(thread): > ? ? x=0 > ? ? while True: > ? ? ? ? x+=1 > > if __name__ == '__main__': > ? ? try: > ? ? ? ? cpus = int(sys.argv[1]) > ? ? except ValueError: > ? ? ? ? cpus = 1 > ? ? print "cpus = %d, argv[1] = %s\n" % (cpus, sys.argv[1]) > ? ? i=0 > ? ? thread_list = [] > ? ? while i < cpus: > ? ? ? ? x = thread.start_new_thread(busy, (i,)) > ? ? ? ? thread_list.append(x) > ? ? ? ? i+=1 > ? ? while True: > ? ? ? ? pass > > -- > Derek D. Martinhttp://www.pizzashack.org/ > GPG Key ID: 0x81CFE75D > > ?application_pgp-signature_part > < 1KViewDownload watch this and all your findings will be explained: http://blip.tv/file/2232410 this talk marked a pivotal moment in my understanding of python threads and signal handling in threaded programs. From zuo at chopin.edu.pl Tue Aug 18 17:11:34 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 23:11:34 +0200 Subject: Inheriting dictionary In-Reply-To: References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: 18-08-2009 o 22:27:41 Nat Williams wrote: > On Tue, Aug 18, 2009 at 2:44 PM, Pavel Panchekha > wrote: > >> I want a dictionary that will transparently "inherit" from a parent >> dictionary. So, for example: >> >> """ >> a = InheritDict({1: "one", 2: "two", 4: "four"}) >> b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) >> >> a[1] # "one" >> a[4] # "four" >> b[1] # "one" >> b[3] # "three" >> b[4] # "foobar" >> """ >> >> I've written something like this in Python already, but I'm wondering >> if something like this already exists, preferably written in C, for >> speed. > > > Why complicate this with a custom object? Just use regular dicts and > make b a copy of a. > > a = {1: 'one', 2: 'two', 4: 'four'} > b = dict(a) > b[3] = 'three' > b[4] = 'foobar' Because, as I understand Pavel's intent, it has to work dynamically (e.g. changes in 'a' reflect in behaviour of 'b'), and obviously not only for such trivial examples like above. *j -- Jan Kaliszewski (zuo) From sajmikins at gmail.com Tue Aug 18 17:13:02 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 17:13:02 -0400 Subject: Need cleanup advice for multiline string In-Reply-To: <4A8ADF6D.2030405@sequans.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: <50f98a4c0908181413s69648332i6dea4f927e605f6@mail.gmail.com> On Tue, Aug 18, 2009 at 1:05 PM, Jean-Michel Pichavant wrote: > Steve Holden wrote: >>>> >>>> Robert Dailey: >>>> >> >> [...] >> >>> >>> It's a figure of speech. And besides, why would I want programming >>> advice from a woman? lol. Thanks for the help. >>> >> >> Sorry, Robert, simply not acceptable. Whether designed to be funny or >> not it's the kind of inane remark I would be really happy never to see >> again. >> >> The problem is that we can't just "let these things go by" all the >> time (even though we aren't discussing a major crime here). If we do >> that it encourages (at best) an atmosphere of complacency and a >> feeling that it's OK to demean people in Python forums. I'd really >> like to see those *not* get a hold. >> >> regards >> ?Steve >> > > Did you read the original post (this is an old one) ? Because quoting a joke > out of its context is totally unfair. Unfair to whom? In any event, the context here seems to be a mixture of Guy Fawkes trivia and general disapproval of sexist remarks on c.l.p, so I don't see this comment as "out of context". (For the record, I use "guys" to refer to groups of people regardless of their gender. I also use "dude" to refer to people regardless of their gender. The only person who has taken offense to this is my mom. "I am not a dude." But she means she's not a cowboy, not not a male.) (Uh, she is, in fact, female.) > Anyway the hysteria that is surrounding this thread is just amazing. I'm > waiting for more. I don't feel hysterical, only appalled. The OP used a common slang term, someone mentioned that the term implies a group of males when in fact the group being addressed is mixed gender, and the OP replied that it was "just a figure of speech". So far, so good. But then the OP made a sexist "joke". He was called on it and issued a rather gracious apology, but then he dropped another sexist turd right in the middle of his otherwise model apology. I won't speak for anyone else, but I was appalled. Sexism, racism, homophobia, religious intolerance, etc., all stem from a fundamental forgetfulness of our Unity in God (as I would put it) and this is perhaps the single greatest cause of human misery. We are one family. From deets at nospam.web.de Tue Aug 18 17:18:36 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 23:18:36 +0200 Subject: Editing a wiki In-Reply-To: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> References: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> Message-ID: <7f0k5cF2i58otU1@mid.uni-berlin.de> KillSwitch schrieb: > Hey guys, > Is it possible to edit a wiki page with python, including logging in > to edit the page, and inserting text into the edit box, etc. I was > thinking maybe python would be the language to do this in, because I > have to iterate through every line in a text file and gather info > about what to enter in the wiki that way, then put that text in a wiki > page. It's sort of a program-documenting program. If it's possible to > do this, I would make a special way of entering comments in the source > files, like maybe --[[##title code here]] and then --[[@@code example > here]] with the two symbols at the beginning of the comment dictating > what to enter where. Thanks for any input. Take a look at mechanize, which is a python web-client impostor thingy - it should be easy to use for this purpose. Diez From pavpanchekha at gmail.com Tue Aug 18 17:19:05 2009 From: pavpanchekha at gmail.com (Pavel Panchekha) Date: Tue, 18 Aug 2009 14:19:05 -0700 (PDT) Subject: Inheriting dictionary References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: <30490e9b-7f8d-4adc-afc6-0c1d5e04cbac@f33g2000vbm.googlegroups.com> On Aug 18, 5:11?pm, "Jan Kaliszewski" wrote: > 18-08-2009 o 22:27:41 Nat Williams wrote: > > > > > On Tue, Aug 18, 2009 at 2:44 PM, Pavel Panchekha ? > > wrote: > > >> I want a dictionary that will transparently "inherit" from a parent > >> dictionary. So, for example: > > >> """ > >> a = InheritDict({1: "one", 2: "two", 4: "four"}) > >> b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) > > >> a[1] # "one" > >> a[4] # "four" > >> b[1] # "one" > >> b[3] # "three" > >> b[4] # "foobar" > >> """ > > >> I've written something like this in Python already, but I'm wondering > >> if something like this already exists, preferably written in C, for > >> speed. > > > Why complicate this with a custom object? ?Just use regular dicts and ? > > make b a copy of a. > > > a = {1: 'one', 2: 'two', 4: 'four'} > > b = dict(a) > > b[3] = 'three' > > b[4] = 'foobar' > > Because, as I understand Pavel's intent, it has to work dynamically > (e.g. changes in 'a' reflect in behaviour of 'b'), and obviously not > only for such trivial examples like above. > > *j > > -- > Jan Kaliszewski (zuo) That is indeed the point. From leonhard.vogt at gmx.ch Tue Aug 18 17:19:26 2009 From: leonhard.vogt at gmx.ch (Leonhard Vogt) Date: Tue, 18 Aug 2009 23:19:26 +0200 Subject: How to create functors? In-Reply-To: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> References: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> Message-ID: <36b62$4a8b1adf$544b15b8$17140@news.hispeed.ch> > The example I gave earlier is a bit contrived, the real example > fundamentally requires a lambda since I am actually passing in local > variables into the functions the lambda is wrapping. Example: > > def MyFunction(): > localVariable = 20 > CreateTask( lambda: SomeOtherFunction( localVariable ) ) # CreateTask > () executes the functor internally > > This is more or less like the real scenario I'm working with. There > are other (more personal) reasons why I prefer to avoid 'def' in this > case. I want to keep the functor as central to the code that needs it > as possible to improve code readability. > what about def MyFunction(): localVariable = 20 def wrapper(): return SomeOtherFunction( localVariable ) CreateTask( wrapper ) the wrapper is only visible inside MyFunction. Leonhard From ben+python at benfinney.id.au Tue Aug 18 17:19:39 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 07:19:39 +1000 Subject: Code formatting question: conditional expression References: Message-ID: <87skfohlas.fsf@benfinney.id.au> John Posner writes: > Is there any consensus on how to format a conditional expression that > is too long for one line? How about this: > > excessblk = (Block(total - P.BASE, srccol, carry_button_suppress=True) > if total > P.BASE else > None) > > The above format separates the values from the if-then-else machinery. > Too many lines? Too much indentation, and worse, indentation that changes based on a distractingly irrelevant quantity: the length of the first line. I prefer:: excessblk = ( Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None) > Would it be better to line up "if" and "else" vertically? ... If the expression assigned in the ?else? branch were also quite long, I'd say yes:: excessblk = ( Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else Block(total, srccol, carry_button_suppress=False)) -- \ ?Friendship is born at that moment when one person says to | `\ another, ?What! You too? I thought I was the only one!?? ?C.S. | _o__) Lewis | Ben Finney From ben+python at benfinney.id.au Tue Aug 18 17:24:35 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 07:24:35 +1000 Subject: Code formatting question: conditional expression References: <7evr1pF2i4mouU1@mid.uni-berlin.de> Message-ID: <87ocqchl2k.fsf@benfinney.id.au> "Diez B. Roggisch" writes: > excessblk = None > if total > P.BASE: > excessblk = ... > > You don't lose any vertical space, I don't see vertical space as such a scarce resource; we don't have an imminent newline shortage, to my knowledge. I value it far lower than, say, local readability. > and it's much more readable IMHO. On the basis of local readability, then, I agree that a multi-line conditional expression is far less quickly comprehensible than a normal multi-line ?if? statement. Assigning the default value of ?None? first (if that's the default) is also good style IMO. -- \ ?Pinky, are you pondering what I'm pondering?? ?Wuh, I think | `\ so, Brain, but wouldn't anything lose its flavor on the bedpost | _o__) overnight?? ?_Pinky and The Brain_ | Ben Finney From deets at nospam.web.de Tue Aug 18 17:24:38 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 18 Aug 2009 23:24:38 +0200 Subject: How to create functors? In-Reply-To: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> References: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> Message-ID: <7f0kgmF2iioslU1@mid.uni-berlin.de> > The example I gave earlier is a bit contrived, the real example > fundamentally requires a lambda since I am actually passing in local > variables into the functions the lambda is wrapping. Example: funcs = [] for i in xrange(10): def f(i=i): print i funcs.append(f) for f in funcs: f() > This is more or less like the real scenario I'm working with. There > are other (more personal) reasons why I prefer to avoid 'def' in this > case. I want to keep the functor as central to the code that needs it > as possible to improve code readability. Didn't you say the other day you came from C++? Given the galactic amount of hoops to jump through that language has to offer, typing def f instead of the even longe lambda strikes me as rather peculiar. Diez From zuo at chopin.edu.pl Tue Aug 18 17:30:19 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 23:30:19 +0200 Subject: How to create functors? In-Reply-To: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> References: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> Message-ID: Dnia 18-08-2009 o 22:51:19 Robert Dailey napisa?(a): > The example I gave earlier is a bit contrived, the real example > fundamentally requires a lambda since I am actually passing in local > variables into the functions the lambda is wrapping. Example: > > def MyFunction(): > localVariable = 20 > CreateTask( lambda: SomeOtherFunction( localVariable ) ) # CreateTask > () executes the functor internally Lambda in Python is a sintactic sugar for some simple situations. But you *always* can replace it with def, e.g.: def MyFunction(): localVariable = 20 def TaskFunction(): SomeOtherFunction(localVariable) CreateTask(TaskFunction) If we say about You can also use functools.partial: import functools def MyFunction(): localVariable = 20 CreateTask(functools.partial(SomeOtherFunction, localVariable) ...which (especially) makes sense if passed function is supposed to be callend many times. > This is more or less like the real scenario I'm working with. There > are other (more personal) reasons why I prefer to avoid 'def' in this > case. I want to keep the functor as central to the code that needs it > as possible to improve code readability. IMHO def is mostly more readable (see my previous mail...). > Thanks for the help everyone. I guess in Python 3.0 the print() > function will not require the import from __future__ to work in this > particular case? Print as a function is a standard feature of Py 3.x so it doesn't require it (see: http://docs.python.org/3.1/whatsnew/3.0.html ). Regards, *j -- Jan Kaliszewski (zuo) From clp2 at rebertia.com Tue Aug 18 17:30:22 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 14:30:22 -0700 Subject: Editing a wiki In-Reply-To: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> References: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> Message-ID: <50697b2c0908181430k7b36ec3fv4248865dbd0ae954@mail.gmail.com> On Tue, Aug 18, 2009 at 2:02 PM, KillSwitch wrote: > Hey guys, > Is it possible to edit a wiki page with python, including logging in > to edit the page, and inserting text into the edit box, etc. Depends on the wiki. For Mediawiki, yes: http://pywikipediabot.sourceforge.net/ Cheers, Chris -- http://blog.rebertia.com From invalid at invalid Tue Aug 18 17:31:58 2009 From: invalid at invalid (Grant Edwards) Date: Tue, 18 Aug 2009 16:31:58 -0500 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: On 2009-08-18, Simon Forman wrote: > Sexism, racism, homophobia, religious intolerance, etc., all > stem from a fundamental forgetfulness of our Unity in God (as > I would put it) and this is perhaps the single greatest cause > of human misery. You mean the single greatest cause of human misery isn't Microsoft Windows? -- Grant Edwards grante Yow! What I want to find at out is -- do parrots know visi.com much about Astro-Turf? From paul at boddie.org.uk Tue Aug 18 17:32:11 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 18 Aug 2009 14:32:11 -0700 (PDT) Subject: Editing a wiki References: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> Message-ID: On 18 Aug, 23:02, KillSwitch wrote: > Hey guys, > Is it possible to edit a wiki page with python, including logging in > to edit the page, and inserting text into the edit box, etc. I was > thinking maybe python would be the language to do this in, because I > have to iterate through every line in a text file and gather info > about what to enter in the wiki that way, then put that text in a wiki > page. What you seem to want is a way of interacting with Web forms, and there are various Python client libraries which do this: http://wiki.python.org/moin/WebClientProgramming However, see below. > It's sort of a program-documenting program. If it's possible to > do this, I would make a special way of entering comments in the source > files, like maybe --[[##title code here]] and then --[[@@code example > here]] with the two symbols at the beginning of the comment dictating > what to enter where. Thanks for any input. Generally, you have to be careful interacting with Web sites in an automated fashion: Wiki sites in particular often have measures in place to deter "robots" and behaviour which looks like spamming. If the Wiki is under your control, you'd be better off uploading content via the data store (such as the filesystem for MoinMoin and some other Wiki solutions) or via specific mechanisms provided for administration of the Wiki. Paul From ben+python at benfinney.id.au Tue Aug 18 17:39:13 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 07:39:13 +1000 Subject: Code formatting question: conditional expression References: Message-ID: <87k510hke6.fsf@benfinney.id.au> John Posner writes: > > excessblk = None > > if total > P.BASE: > > excessblk = ... > > [?] > But doesn't it violate the DRY principle? The token "excessblk" > appears twice instead of once. No, the DRY principle doesn't speak against assigning two *different* values in two *different* circumstances. That's not duplication, and doesn't risk contradiction. DRY speaks against repeating the same *meaning* in two different places. Because this concept is expressed in natural language and not a programming language, and because we don't speak in a language under the same principles we espouse for programming, there are multiple terms used for this concept :-) Another term which makes the point slightly more sharply is SPOT: there should be a Single Point Of Truth for each fact in the overall system. -- \ ?What I have to do is see, at any rate, that I do not lend | `\ myself to the wrong which I condemn.? ?Henry Thoreau, _Civil | _o__) Disobedience_ | Ben Finney From zuo at chopin.edu.pl Tue Aug 18 17:41:02 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Tue, 18 Aug 2009 23:41:02 +0200 Subject: basic thread question In-Reply-To: <20090818201015.GP20434@dragontoe.org> References: <20090818201015.GP20434@dragontoe.org> Message-ID: 18-08-2009 o 22:10:15 Derek Martin wrote: > I have some simple threaded code... If I run this > with an arg of 1 (start one thread), it pegs one cpu, as I would > expect. If I run it with an arg of 2 (start 2 threads), it uses both > CPUs, but utilization of both is less than 50%. Can anyone explain > why? > > I do not pretend it's impeccable code, and I'm not looking for a > critiqe of the code per se, excepting the case where what I've written > is actually *wrong*. I hacked this together in a couple of minutes, > with the intent of pegging my CPUs. Performance with two threads is > actually *worse* than with one, which is highly unintuitive. I can > accomplish my goal very easily with bash, but I still want to > understand what's going on here... > > The OS is Linux 2.6.24, on a Ubuntu base. Here's the code: Python threads can't benefit from multiple processors (because of GIL, see: http://docs.python.org/glossary.html#term-global-interpreter-lock). 'multiprocessing' module is what you need: http://docs.python.org/library/multiprocessing.html Cheers, *j -- Jan Kaliszewski (zuo) From ben+python at benfinney.id.au Tue Aug 18 17:42:40 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 07:42:40 +1000 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> Message-ID: <87fxbohk8f.fsf@benfinney.id.au> Jean-Michel Pichavant writes: > Anyway the hysteria that is surrounding this thread is just amazing. If the calm reproach that has been the maximum response so far seems like ?hysteria? to you, I can only conclude you have only been using the internet for a few hours. -- \ ?The fact that I have no remedy for all the sorrows of the | `\ world is no reason for my accepting yours. It simply supports | _o__) the strong probability that yours is a fake.? ?Henry L. Mencken | Ben Finney From rcdailey at gmail.com Tue Aug 18 17:50:22 2009 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 18 Aug 2009 14:50:22 -0700 (PDT) Subject: How to create functors? References: <0866bb91-ce18-46f5-a62b-8c6cb14e13d7@24g2000yqm.googlegroups.com> Message-ID: On Aug 18, 4:30?pm, "Jan Kaliszewski" wrote: > Lambda in Python is a sintactic sugar for some simple situations. But you > *always* can replace it with def, e.g.: > > ? def MyFunction(): > > ? ? ? localVariable = 20 > ? ? ? def TaskFunction(): > ? ? ? ? ? SomeOtherFunction(localVariable) > > ? ? ? CreateTask(TaskFunction) > > If we say about You can also use functools.partial: > > ? import functools > > ? def MyFunction(): > > ? ? ? localVariable = 20 > ? ? ? CreateTask(functools.partial(SomeOtherFunction, localVariable) > > ...which (especially) makes sense if passed function is supposed to be > callend many times. Good point, I'm too used to C++ (Can't define functions in local scope). I never thought of that. In C++ I use boost::bind() fairly extensively and I carry over those habits to python. > > IMHO def is mostly more readable (see my previous mail...). > > Print as a function is a standard feature of Py 3.x so it doesn't > require it (see:http://docs.python.org/3.1/whatsnew/3.0.html). Thanks for the info. From erik1vandamme at gmail.com Tue Aug 18 18:06:50 2009 From: erik1vandamme at gmail.com (Erik Vandamme) Date: Tue, 18 Aug 2009 15:06:50 -0700 (PDT) Subject: Setuptools - help! References: Message-ID: <77a95cac-a059-4501-917a-e87157511912@p36g2000prn.googlegroups.com> On Aug 7, 9:17?am, Robert Kern wrote: > On 2009-08-06 18:04, Peter Chant wrote: > > > > > Chaps, > > > any ideas, I'm floundering - I don't quite get it. ?I have the following > > files, setup.py and main.py in a directory pphoto: > > > # more setup.py > > from setuptools import setup, find_packages > > setup( > > ? ? ?name = "Pphoto", > > ? ? ?version = "0.1", > > ? ? ?packages = find_packages(), > > > ? ? ?# other arguments here... > > ? ? ?entry_points = {'console_scripts': ['foo = pphoto.main:HelloWorld',]} > > > ) > > > bash-3.1# more main.py > > > def HelloWorld(): > > ? ? ?print "Hello World!" > > > print "Odd world" > > >> From various websites that should produce a script foo that runs HelloWorld. > > It does produce a script that simply crashes. > > > bash-3.1# foo > > Traceback (most recent call last): > > ? ?File "/usr/bin/foo", line 8, in > > ? ? ?load_entry_point('Pphoto==0.1', 'console_scripts', 'foo')() > > ? ?File "build/bdist.linux-i686/egg/pkg_resources.py", line 277, in > > load_entry_point > > ? ?File "build/bdist.linux-i686/egg/pkg_resources.py", line 2098, in > > load_entry_point > > ? ?File "build/bdist.linux-i686/egg/pkg_resources.py", line 1831, in load > > ImportError: No module named pphoto.main > > bash-3.1# > > > Note, doing this as root as it seems not to do anything usefull at all if I > > run python setup develop as a user. > > > Any ideas? ?I must be missing something fundamental? > > You need to put main.py into the pphoto package. > > $ mkdir pphoto/ > $ mv main.py pphoto/ > $ touch pphoto/__init__.py > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco erik at erik-d2c:~/calibre-0.6.7$ mv main.py pphoto/ mv: cannot stat `main.py': No such file or directory ------------------------------------- there is no main.py in the main calibre folder and there is 5 of them in the subfolders????? From sajmikins at gmail.com Tue Aug 18 18:08:11 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 15:08:11 -0700 (PDT) Subject: Inheriting dictionary References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: <2fe6d216-1e8f-4de1-8c36-d4ee11bb7233@26g2000yqk.googlegroups.com> On Aug 18, 3:44?pm, Pavel Panchekha wrote: > I want a dictionary that will transparently "inherit" from a parent > dictionary. So, for example: > > """ > a = InheritDict({1: "one", 2: "two", 4: "four"}) > b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) > > a[1] # "one" > a[4] # "four" > b[1] # "one" > b[3] # "three" > b[4] # "foobar" > """ > > I've written something like this in Python already, but I'm wondering > if something like this already exists, preferably written in C, for > speed. I would consider something like the following: a = {1: "one", 2: "two", 4: "four"} b = {3: "three", 4: "foobar"} from functools import partial def getter(first, second, key): try: return first(key) except KeyError: return second(key) f = partial(getter, b.__getitem__, a.__getitem__) # Or, if you know you'll be getting a lot of KeyErrors, you # can use get() instead of __getitem__(). def getter1(first, second, key, sentinel=None): item = first(key, sentinel) if item is sentinel: item = second(key) return item g = partial(getter1, b.get, a.__getitem__) HTH, ~Simon From robert.kern at gmail.com Tue Aug 18 18:14:42 2009 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 18 Aug 2009 15:14:42 -0700 Subject: Setuptools - help! In-Reply-To: <77a95cac-a059-4501-917a-e87157511912@p36g2000prn.googlegroups.com> References: <77a95cac-a059-4501-917a-e87157511912@p36g2000prn.googlegroups.com> Message-ID: On 2009-08-18 15:06 PM, Erik Vandamme wrote: > On Aug 7, 9:17 am, Robert Kern wrote: >> On 2009-08-06 18:04, Peter Chant wrote: >> >> >> >>> Chaps, >> >>> any ideas, I'm floundering - I don't quite get it. I have the following >>> files, setup.py and main.py in a directory pphoto: >> >>> # more setup.py >>> from setuptools import setup, find_packages >>> setup( >>> name = "Pphoto", >>> version = "0.1", >>> packages = find_packages(), >> >>> # other arguments here... >>> entry_points = {'console_scripts': ['foo = pphoto.main:HelloWorld',]} >> >>> ) >> >>> bash-3.1# more main.py >> >>> def HelloWorld(): >>> print "Hello World!" >> >>> print "Odd world" >> >>>> From various websites that should produce a script foo that runs HelloWorld. >>> It does produce a script that simply crashes. >> >>> bash-3.1# foo >>> Traceback (most recent call last): >>> File "/usr/bin/foo", line 8, in >>> load_entry_point('Pphoto==0.1', 'console_scripts', 'foo')() >>> File "build/bdist.linux-i686/egg/pkg_resources.py", line 277, in >>> load_entry_point >>> File "build/bdist.linux-i686/egg/pkg_resources.py", line 2098, in >>> load_entry_point >>> File "build/bdist.linux-i686/egg/pkg_resources.py", line 1831, in load >>> ImportError: No module named pphoto.main >>> bash-3.1# >> >>> Note, doing this as root as it seems not to do anything usefull at all if I >>> run python setup develop as a user. >> >>> Any ideas? I must be missing something fundamental? >> >> You need to put main.py into the pphoto package. >> >> $ mkdir pphoto/ >> $ mv main.py pphoto/ >> $ touch pphoto/__init__.py >> >> -- >> Robert Kern >> >> "I have come to believe that the whole world is an enigma, a harmless enigma >> that is made terrible by our own mad attempt to interpret it as though it had >> an underlying truth." >> -- Umberto Eco > erik at erik-d2c:~/calibre-0.6.7$ mv main.py pphoto/ > mv: cannot stat `main.py': No such file or directory > ------------------------------------- > there is no main.py in the main calibre folder and there is 5 of them > in the subfolders????? I was helping Peter Chant with his problem. You have a different problem. Why are you trying to follow my advice verbatim for a completely different package? What problem are you seeing? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From code at pizzashack.org Tue Aug 18 18:18:54 2009 From: code at pizzashack.org (Derek Martin) Date: Tue, 18 Aug 2009 17:18:54 -0500 Subject: basic thread question In-Reply-To: <20090818201015.GP20434@dragontoe.org> References: <20090818201015.GP20434@dragontoe.org> Message-ID: <20090818221854.GQ20434@dragontoe.org> On Tue, Aug 18, 2009 at 03:10:15PM -0500, Derek Martin wrote: > I have some simple threaded code... If I run this > with an arg of 1 (start one thread), it pegs one cpu, as I would > expect. If I run it with an arg of 2 (start 2 threads), it uses both > CPUs, but utilization of both is less than 50%. Can anyone explain > why? Ah, searching while waiting for an answer (the e-mail gateway is a bit slow, it seems...) I discovered that the GIL is the culprate. Evidently this question comes up a lot. It would probably save a lot of time on the part of those who answer questions here, as well as those implementing solutions in Python, if whoever is maintaining the docs these days would put a blurb about this in the docs in big bold letters... Concurrency being perhaps the primary reason to use threading, essentially it means that Python is not useful for the sorts of problems that one would be inclined to solve they way my code works (or rather, was meant to). It would be very helpful to know that *before* one tried to implement a solution that way... especially for solutions significantly less trivial than mine. ;-) Thanks -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From digitalxero at gmail.com Tue Aug 18 18:21:26 2009 From: digitalxero at gmail.com (Dj Gilcrease) Date: Tue, 18 Aug 2009 16:21:26 -0600 Subject: [Python-Dev] Mercurial migration: help needed In-Reply-To: <4A8A6256.1030009@v.loewis.de> References: <4A8A6256.1030009@v.loewis.de> Message-ID: On Tue, Aug 18, 2009 at 2:12 AM, "Martin v. L?wis" wrote: > The second item is line conversion hooks. Dj Gilcrease has posted a > solution which he considers a hack himself. Mark Hammond has also > volunteered, but it seems some volunteer needs to be "in charge", > keeping track of a proposed solution until everybody agrees that it > is a good solution. It may be that two solutions are necessary: a > short-term one, that operates as a hook and has limitations, and > a long-term one, that improves the hook system of Mercurial to > implement the proper functionality (which then might get shipped > with Mercurial in a cross-platform manner). My solution is a hack because the hooks in Mercurial need to be modified to support it properly, I would be happy to help work on this as it is a situation I run into all the time in my own projects. I can never seem to get all the developers to enable the hooks, and one of them always commits with improper line endings =P From markscottwright at gmail.com Tue Aug 18 18:24:20 2009 From: markscottwright at gmail.com (markscottwright) Date: Tue, 18 Aug 2009 15:24:20 -0700 (PDT) Subject: How do I convert an iterator over bytes into a str? Message-ID: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> This does what I expected: In [6]: list(iter([1,2,3,4,5])) Out[6]: [1, 2, 3, 4, 5] But this appears to be doing a __repr__ rather than making me a nice string: In [7]: str(iter("four score and seven years ago")) Out[7]: '' What's the correct way to turn an iterator over bytes into a string? This works, but, ewww: In [8]: "".join(iter("four score and seven years ago")) Out[8]: 'four score and seven years ago' From emile at fenx.com Tue Aug 18 18:39:27 2009 From: emile at fenx.com (Emile van Sebille) Date: Tue, 18 Aug 2009 15:39:27 -0700 Subject: Need cleanup advice for multiline string In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: On 8/18/2009 2:31 PM Unknown said... > You mean the single greatest cause of human misery isn't > Microsoft Windows? Either that or users... Sick-of-both-today-ly y'rs, Emile From davidshais at googlemail.com Tue Aug 18 18:47:09 2009 From: davidshais at googlemail.com (David) Date: Tue, 18 Aug 2009 15:47:09 -0700 (PDT) Subject: Scope and classes Message-ID: Hi all, I'm trying to understand how scopes work within a class definition. I'll quickly illustrate with an example. Say I had the following class definition: class Abc: message = 'Hello World' def print_message(self): print message >>> instance = Abc() >>> instance.print_message() NameError: global name 'message' not defined My question is, why? message is not defined in print_message, but it is defined in the enclosing scope (the class)? Thanks! From breamoreboy at yahoo.co.uk Tue Aug 18 18:54:13 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Tue, 18 Aug 2009 23:54:13 +0100 Subject: How do I convert an iterator over bytes into a str? In-Reply-To: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> Message-ID: markscottwright wrote: > This does what I expected: > In [6]: list(iter([1,2,3,4,5])) > Out[6]: [1, 2, 3, 4, 5] > > But this appears to be doing a __repr__ rather than making me a nice > string: > In [7]: str(iter("four score and seven years ago")) > Out[7]: '' > > What's the correct way to turn an iterator over bytes into a string? > This works, but, ewww: > In [8]: "".join(iter("four score and seven years ago")) > Out[8]: 'four score and seven years ago' You've started with a string. >>> type("four score and seven years ago") -- Kindest regards. Mark Lawrence. From olivier.anospamrnospamnnospamanospamenospamz at affaires.net Tue Aug 18 19:03:30 2009 From: olivier.anospamrnospamnnospamanospamenospamz at affaires.net (Ludo) Date: Wed, 19 Aug 2009 01:03:30 +0200 Subject: Read C++ enum in python Message-ID: <4a8b3342$0$25403$426a34cc@news.free.fr> Hello, I work in a very large project where we have C++ packages and pieces of python code. I've been googleing for days but what I find seems really too complicated for what I want to do. My business is, in python, to read enum definitions provided by the header file of an c++ package. Of course I could open the .h file, read the enum and transcode it by hand into a .py file but the package is regularly updated and thus is the enum. My question is then simple : do we have : - either a simple way in python to read the .h file, retrieve the c++ enum and provide an access to it in my python script - either a simple tool (in a long-term it would be automatically run when the c++ package is compiled) generating from the .h file a .py file containing the python definition of the enums ? Thank you for any suggestion. From atulskulkarni at gmail.com Tue Aug 18 19:06:12 2009 From: atulskulkarni at gmail.com (Atul.) Date: Tue, 18 Aug 2009 16:06:12 -0700 (PDT) Subject: Python on the web, how to? Message-ID: Hello All, Needless to say I am new to python and web programming. I am looking for a quick Python-101 course / tutorial for "using python to implement dynamic content on web" under some web server. Any pointers what should I be reading? Regards, Atul. From clp2 at rebertia.com Tue Aug 18 19:16:07 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 16:16:07 -0700 Subject: Scope and classes In-Reply-To: References: Message-ID: <50697b2c0908181616y41cab4eah13769e75d59a505d@mail.gmail.com> On Tue, Aug 18, 2009 at 3:47 PM, David wrote: > Hi all, > > I'm trying to understand how scopes work within a class definition. > I'll quickly illustrate with an example. Say I had the following class > definition: > > class Abc: > ? ?message = 'Hello World' > > ? ?def print_message(self): > ? ? ? ?print message > >>>> instance = Abc() >>>> instance.print_message() > NameError: global name 'message' not defined > > My question is, why? message is not defined in print_message, but it > is defined in the enclosing scope (the class)? A class' scope is never consulted when resolving variable names in its methods. The scopes consulted are roughly (and in this order): 1. Local variable scope (i.e. of the current function/method) 2. Enclosing functions (if you have functions nested inside other functions) 3. Globals (i.e. module-level variables) 3. Builtins (i.e. the built-in functions and methods, such as len()) To access class-level variables from within instance methods of the class, you have 2 options: A. Use the class name, i.e. Abc.message B. Reference the class indirectly, i.e. self.__class__.message Cheers, Chris -- http://blog.rebertia.com From wwn1 at sfu.ca Tue Aug 18 19:16:33 2009 From: wwn1 at sfu.ca (WilsonOfCanada) Date: Tue, 18 Aug 2009 16:16:33 -0700 (PDT) Subject: Raw Strings with Variables Message-ID: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Hellos, I know that if you have: happy = r"C:\moo" print happy you get C:\moo instead of C:\\moo The thing is that I want to do this a variable instead. ex. testline = fileName.readline() rawtestline = r testline Thanks From clp2 at rebertia.com Tue Aug 18 19:18:57 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 16:18:57 -0700 Subject: Python on the web, how to? In-Reply-To: References: Message-ID: <50697b2c0908181618r6be34f68ma7702b8358788602@mail.gmail.com> On Tue, Aug 18, 2009 at 4:06 PM, Atul. wrote: > Hello All, > > Needless to say I am new to python and web programming. I am looking > for a quick Python-101 course / tutorial for "using python to > implement dynamic content on web" under some web server. Any pointers > what should I be reading? Google for "Python web framework" and take your pick. Some popular choices: - Django: http://www.djangoproject.com/ -- associated online book: http://djangobook.com/ - TurboGears: http://turbogears.org/ Cheers, Chris -- http://blog.rebertia.com From af2012 at gmail.com Tue Aug 18 19:33:00 2009 From: af2012 at gmail.com (Allan) Date: Tue, 18 Aug 2009 16:33:00 -0700 (PDT) Subject: recording input from USB port and write to text file Message-ID: Hi! I'm fairly new to Python. I understand the basics basics but I'm been trying to write a simple python code that will let me read input data (such as mouse movement) from my USB port and write it in a text file and I am so lost. Can anyone help or direct me to some resources? Thank you! From davidshais at googlemail.com Tue Aug 18 19:38:15 2009 From: davidshais at googlemail.com (David) Date: Tue, 18 Aug 2009 16:38:15 -0700 (PDT) Subject: Scope and classes References: Message-ID: <07746be7-368e-4222-82a1-fecb5c2c5da3@s31g2000yqs.googlegroups.com> On Aug 19, 12:16?am, Chris Rebert wrote: > On Tue, Aug 18, 2009 at 3:47 PM, David wrote: > > Hi all, > > > I'm trying to understand how scopes work within a class definition. > > I'll quickly illustrate with an example. Say I had the following class > > definition: > > > class Abc: > > ? ?message = 'Hello World' > > > ? ?def print_message(self): > > ? ? ? ?print message > > >>>> instance = Abc() > >>>> instance.print_message() > > NameError: global name 'message' not defined > > > My question is, why? message is not defined in print_message, but it > > is defined in the enclosing scope (the class)? > > A class' scope is never consulted when resolving variable names in its methods. > > The scopes consulted are roughly (and in this order): > 1. Local variable scope (i.e. of the current function/method) > 2. Enclosing functions (if you have functions nested inside other functions) > 3. Globals (i.e. module-level variables) > 3. Builtins (i.e. the built-in functions and methods, such as len()) > > To access class-level variables from within instance methods of the > class, you have 2 options: > A. Use the class name, i.e. Abc.message > B. Reference the class indirectly, i.e. self.__class__.message > > Cheers, > Chris > --http://blog.rebertia.com Ah, thanks! From steve at REMOVE-THIS-cybersource.com.au Tue Aug 18 19:39:38 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 18 Aug 2009 23:39:38 GMT Subject: Scope and classes References: Message-ID: <0014bf1a$0$2963$c3e8da3@news.astraweb.com> On Tue, 18 Aug 2009 15:47:09 -0700, David wrote: > Hi all, > > I'm trying to understand how scopes work within a class definition. I'll > quickly illustrate with an example. Say I had the following class > definition: > > class Abc: > message = 'Hello World' > > def print_message(self): > print message > >>>> instance = Abc() >>>> instance.print_message() > NameError: global name 'message' not defined > > My question is, why? message is not defined in print_message, but it is > defined in the enclosing scope (the class)? It's a deliberate design decision. I don't recall the reasons for it, but the class namespace is deliberately excluded from the method scope. The correct way of writing the above is: class Abc: message = 'Hello World' def print_message(self): print self.message self.message will first search the instance namespace for an attribute `message`, then search the class, then any superclasses. If you specifically want the class attribute, even if the instance masks it with an instance attribute of the same name, you do this instead: print self.__class__.message -- Steven From marduk at letterboxes.org Tue Aug 18 19:39:54 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Tue, 18 Aug 2009 19:39:54 -0400 Subject: Raw Strings with Variables In-Reply-To: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: <1250638794.5388.3.camel@centar.nbk> On Tue, 2009-08-18 at 16:16 -0700, WilsonOfCanada wrote: > Hellos, > > I know that if you have: > > happy = r"C:\moo" > print happy > > you get C:\moo instead of C:\\moo > > The thing is that I want to do this a variable instead. > > ex. testline = fileName.readline() > rawtestline = r testline I'm not sure what you are hoping for... Raw strings apply to string literals. If you are reading from a file, as above, you need not worry about it: $ cat test.txt C:\moo $ python -c 'r = open("test.txt").readline() ; print r' C:\moo From python at mrabarnett.plus.com Tue Aug 18 19:50:05 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 19 Aug 2009 00:50:05 +0100 Subject: Read C++ enum in python In-Reply-To: <4a8b3342$0$25403$426a34cc@news.free.fr> References: <4a8b3342$0$25403$426a34cc@news.free.fr> Message-ID: <4A8B3E2D.7040702@mrabarnett.plus.com> Ludo wrote: > Hello, > > I work in a very large project where we have C++ packages and pieces of > python code. > > I've been googleing for days but what I find seems really too > complicated for what I want to do. > > My business is, in python, to read enum definitions provided by the > header file of an c++ package. > Of course I could open the .h file, read the enum and transcode it by > hand into a .py file but the package is regularly updated and thus is > the enum. > > My question is then simple : do we have : > - either a simple way in python to read the .h file, retrieve the > c++ enum and provide an access to it in my python script > - either a simple tool (in a long-term it would be automatically run > when the c++ package is compiled) generating from the .h file a .py file > containing the python definition of the enums ? > > Thank you for any suggestion. Speaking personally, I'd parse the .h file using a regular expression (re module) and generate a .py file. Compilers typically have a way of letting you run external scripts (eg batch files in Windows or, in this case, a Python script) when an application is compiled. From zuo at chopin.edu.pl Tue Aug 18 19:52:42 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 19 Aug 2009 01:52:42 +0200 Subject: How do I convert an iterator over bytes into a str? In-Reply-To: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> Message-ID: 19-08-2009 o 00:24:20 markscottwright wrote: > What's the correct way to turn an iterator over bytes into a string? > This works, but, ewww: > In [8]: "".join(iter("four score and seven years ago")) > Out[8]: 'four score and seven years ago' But it is the correct way (and even recommended over s=s+t or s+=t, when applicable -- see: http://docs.python.org/library/stdtypes.html#sequence-types-str-unicode-list-tuple-buffer-xrange). Cheers, *j -- Jan Kaliszewski (zuo) From david.birdsong at gmail.com Tue Aug 18 19:58:28 2009 From: david.birdsong at gmail.com (birdsong) Date: Tue, 18 Aug 2009 16:58:28 -0700 (PDT) Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> Message-ID: <92338aa1-0913-483a-b950-c73f0fdb0b1f@v37g2000prg.googlegroups.com> On Aug 18, 3:18?pm, Derek Martin wrote: > On Tue, Aug 18, 2009 at 03:10:15PM -0500, Derek Martin wrote: > > I have some simple threaded code... ?If I run this > > with an arg of 1 (start one thread), it pegs one cpu, as I would > > expect. ?If I run it with an arg of 2 (start 2 threads), it uses both > > CPUs, but utilization of both is less than 50%. ?Can anyone explain > > why? ? > > Ah, searching while waiting for an answer (the e-mail gateway is a bit > slow, it seems...) I discovered that the GIL is the culprate. > Evidently this question comes up a lot. ?It would probably save a lot > of time on the part of those who answer questions here, as well as > those implementing solutions in Python, if whoever is maintaining the > docs these days would put a blurb about this in the docs in big bold > letters... ?Concurrency being perhaps the primary reason to use > threading, essentially it means that Python is not useful for the > sorts of problems that one would be inclined to solve they way my code > works (or rather, was meant to). ?It would be very helpful to know > that *before* one tried to implement a solution that way... especially > for solutions significantly less trivial than mine. ;-) > > Thanks > > -- > Derek D. Martinhttp://www.pizzashack.org/ > GPG Key ID: 0x81CFE75D > > ?application_pgp-signature_part > < 1KViewDownload I would still watch that video which will explain a bit more about the GIL. From steve at REMOVE-THIS-cybersource.com.au Tue Aug 18 20:03:44 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 19 Aug 2009 00:03:44 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: <0014c4c0$0$2963$c3e8da3@news.astraweb.com> On Tue, 18 Aug 2009 17:13:02 -0400, Simon Forman wrote: > Sexism, racism, homophobia, religious intolerance, etc., all stem from a > fundamental forgetfulness of our Unity in God (as I would put it) and Of the tens of thousands of Gods that people have invented, which is the one we're supposed to believe in? I always forget which ones we're supposed to dismiss as nonsense, and which one we're not. > this is perhaps the single greatest cause of human misery. Okay, we're Unified in God. Great. What does that actually mean, really? In the struggle to survive in a world of shortages, disease, natural disasters and disputes between well-meaning but incompatible viewpoints (to say nothing of the selfish and greedy), what practical difference does it make? -- Steven From cmpython at gmail.com Tue Aug 18 20:04:08 2009 From: cmpython at gmail.com (Che M) Date: Tue, 18 Aug 2009 17:04:08 -0700 (PDT) Subject: GUI interface builder for python References: <21bca3cf-b2c7-47d7-9142-26c9fd015f92@r27g2000vbn.googlegroups.com> <02ec7cd9-e749-46d3-8b25-75d85794f292@o35g2000vbi.googlegroups.com> Message-ID: <02bf2081-4f4a-4219-8441-1d48f09af338@c14g2000yqm.googlegroups.com> On Aug 18, 10:54?am, sturlamolden wrote: > On 17 Aug, 17:19, Che M wrote: > > > Boa (Boa Constructor) is really nice for wxPython GUI > > work, but it has some bugs when using Linux that might > > be dealbreakers for the user. ?At least I have had > > problems on Ubuntu 8.10 64 bit (but none or very few > > I prefer wxFormBuilder over Boa. Why? From tjreedy at udel.edu Tue Aug 18 20:08:20 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Aug 2009 09:08:20 +0900 Subject: sub-list extraction, logical indexation In-Reply-To: References: Message-ID: Pierre wrote: > Hello Everyone, > > I would like to know if it is possible to extract a sub-list from a > list ? > > typically if : > > L =[[1, 2, 3],[4, 5, 6],[3] ] > > How to extract easily the elements 0 and 2 of L in order to get : > > L2 =[[1, 2, 3],[3] ] L2 = [L[0],L[2]] > > Moreover, I would like to know if it is possible to use logical > indexation such that : > > index = [ True, False, True] > L2 = L use zip(index,L) in a for loop > > or usual indexation, something like > index=[0, 2] > L2 = L #untried L2=[] for i in index L2.append(L[i]) tjr From wwn1 at sfu.ca Tue Aug 18 20:09:29 2009 From: wwn1 at sfu.ca (WilsonOfCanada) Date: Tue, 18 Aug 2009 17:09:29 -0700 (PDT) Subject: Raw Strings with Variables References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: You're right, but the moment I append it onto a list, it would become C:\\moo. arrPlaces = [] intPoint =0 while (len(testline)): testline = fileName.readline() print testline arrPlaces[intPoint].append(testline) intPoint += 1 print arrPlaces > C:\moo > C:\supermoo > ['C:\\moo', 'C:\\supermoo'] Is there a way to stop that when appending to the dictionary? Thanks From zuo at chopin.edu.pl Tue Aug 18 20:10:58 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 19 Aug 2009 02:10:58 +0200 Subject: Scope and classes In-Reply-To: References: Message-ID: 19-08-2009 o 00:47:09 David wrote: > Hi all, > > I'm trying to understand how scopes work within a class definition. > I'll quickly illustrate with an example. Say I had the following class > definition: > > class Abc: > message = 'Hello World' > > def print_message(self): > print message > >>>> instance = Abc() >>>> instance.print_message() > NameError: global name 'message' not defined > > My question is, why? message is not defined in print_message, but it > is defined in the enclosing scope (the class)? Note that when *running* the code that is *inside* print_message() method called within the global scope, the outer (enclosing) scope is indeed the global scope (the scope in which e.g. 'instance' name exists; note that e.g. 'print instance' in that method would be ok). As Chris wrote, class' scope (contrary to outer function scope) is not considered as the 'enclosing' scope. The only ways to reach Abc's attribute 'message' from that method are: * 'Abc.message' * 'self.__class__.message' * 'self.message' (unless there is an instance attribute 'message' which overrides the class attribute). Cheers, *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Tue Aug 18 20:17:22 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 19 Aug 2009 02:17:22 +0200 Subject: Scope and classes In-Reply-To: References: Message-ID: 19-08-2009 o 02:10:58 Jan Kaliszewski wrote: > The only ways to reach Abc's attribute 'message' from that method are: > * 'Abc.message' > * 'self.__class__.message' > * 'self.message' (unless there is an instance attribute 'message' which > overrides the class attribute). And of course getattr(Abc), getattr(self.__class__) etc. :-) -- Jan Kaliszewski (zuo) From clp2 at rebertia.com Tue Aug 18 20:18:13 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 17:18:13 -0700 Subject: Raw Strings with Variables In-Reply-To: References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: <50697b2c0908181718w6eb8befbp876e8cd831ec3c8e@mail.gmail.com> On Tue, Aug 18, 2009 at 5:09 PM, WilsonOfCanada wrote: > You're right, but the moment I append it onto a list, it would become > C:\\moo. > > arrPlaces = [] > intPoint =0 > > while (len(testline)): > ? ? ? ?testline = fileName.readline() > ? ? ? ?print testline > ? ? ? ?arrPlaces[intPoint].append(testline) > ? ? ? ?intPoint += 1 > > print arrPlaces > >> C:\moo >> C:\supermoo >> ['C:\\moo', 'C:\\supermoo'] That's because the list uses repr() rather than str() to stringify its items when it is output. repr() shows escape sequences rather than the literal characters and adds the surrounding quote marks, but the string is not modified upon placement in the container. Study this interpreter session: >>> a = r"C:\supermoo" >>> b = "\t" #a tab character >>> c = [a, b] >>> print a #note the lack of quotes in the output C:\supermoo >>> print repr(a) #note the quotes and \\ 'C:\\supermoo' >>> print b #we see the literal tab >>> print repr(b) #we see the escape sequence '\t' >>> print c #note how this matches the repr() output from earlier ['C:\\supermoo', '\t'] >>> print c[0], c[1], "end" #but the actual strings are the same as before C:\supermoo end Cheers, Chris -- http://blog.rebertia.com From zuo at chopin.edu.pl Tue Aug 18 20:30:36 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 19 Aug 2009 02:30:36 +0200 Subject: Raw Strings with Variables In-Reply-To: References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: Dnia 19-08-2009 o 02:09:29 WilsonOfCanada napisa?(a): > You're right, but the moment I append it onto a list, it would become > C:\\moo. No, it would not. Really! > C:\moo > C:\supermoo > ['C:\\moo', 'C:\\supermoo'] It is not the matter of content of the string but only of a way of *presentation* of it by print: print arrPlaces in the example is roughly equivalent to: print '[' + repr(a_list[0]) + ', ' + repr(a_list[1]) + ']' So try: print a_list[0] Output: C:\moo print a_list[1] Output: C:\supermoo print ', '.join(arrPlaces) Output: C:\moo, C:\supermoo print ', '.join("'%s'" % item for item in arrPlaces) Output: 'C:\moo', 'C:\supermoo' Cheers, *j -- Jan Kaliszewski (zuo) From ben+python at benfinney.id.au Tue Aug 18 20:42:13 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 10:42:13 +1000 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: <87hbw4fxcq.fsf@benfinney.id.au> Simon Forman writes: > Sexism, racism, homophobia, religious intolerance, etc., all stem from > a fundamental forgetfulness of our Unity in God (as I would put it) It seems odd, for someone who cites religious intolerance as a problem, to then assert an extremely divisive religious idea. We're all unified by our humanity. Bringing any god into the picture is surely counter to any goals of unity. > We are one family. Agreed. -- \ ?Are you thinking what I'm thinking, Pinky?? ?Uh... yeah, | `\ Brain, but where are we going to find rubber pants our size?? | _o__) ?_Pinky and The Brain_ | Ben Finney From mauriceling at gmail.com Tue Aug 18 20:49:56 2009 From: mauriceling at gmail.com (mauriceling@acm.org) Date: Tue, 18 Aug 2009 17:49:56 -0700 (PDT) Subject: Call for Papers - PyCon Asia Pacific 2010 Message-ID: <04687d05-2017-4002-ba11-6d50f684b2f3@y28g2000prd.googlegroups.com> Dear fellow friends and colleagues, I apologize if you had received multiple copies of this Call for Papers. Maurice ================================================================== ------------------------------------------------------------ Call for Papers - PyCon Asia Pacific 2010 ------------------------------------------------------------ PyCon Asia Pacific 2010 represents a major development for the Python community in the Asia Pacific region. In Asia Pacific, we are encouraged by the country-level initiatives of Python conferences in India and New Zealand. We fully expect that PyCon Asia Pacific will be hosted by different APAC countries as the momentum of Python develops in the region. Quote : ??Python development in the Asia Pacific region is proceeding rapidly? I would very much like to highlight the special nature of this conference?. I hope that my presence will help to further international cooperation on Python development? Steven Holden, Chairman, Python Software Foundation (PSF) Keynote, PyCon Asia Pacific 2010 PyCon Asia Pacific 2010?s is looking for proposals from the Python community to fill its formal presentation tracks. The Conference Days will be June 10-11, 2010 in Singapore, preceded by a Tutorial Day (June 9). (http://apac.pycon.org) Important Dates ----------------------- ? Call for Papers: August 15, 2009 ? Deadline for Paper Submissions: February 1, 2010 ? Notification of Paper Acceptance: March 15, 2010 ? Conference Registration Open: March 15, 2010 ? Submission of Camera-Ready Paper: April 15, 2010 ? Conference Days: June 10 - 11, 2010 (preceded by tutorials on the June 9, 2010) PyCon Topics -------------------- PyCon conferences worldwide have had a broad range of presentations, ranging from reports on academic and commercial projects to tutorials and case studies. We hope to continue that tradition here at PyCon Asia Pacific in Singapore. As long as the presentation is interesting and potentially useful to the Python community, it will be considered for inclusion in the program. We are especially interested in short presentations that will teach conference-goers something new and useful. Suitable topics for PyCon Asia Pacific 2010 presentations include, but are not limited to: ? Core Python and other implementations: IronPython, Jython, PyPy and Stackless. ? Python libraries and extensions ? Business Applications ? Databases ? Embedding and Extending Python ? Game Programming ? GUI Programming ? Network Programming ? Python in IT Security ? Open Source Python projects ? Packaging Issues ? Programming Tools ? Project Best Practices ? Python in Education, Science and Math ? System Administration ? Web Programming (Django, Zope, TurboGears, WSGI) Talk Format ----------------- The preferred length for talks is 30 minutes. Session lengths include time for audience questions. You should budget at least five minutes for questions; for example, a 30-minute talk will be 25 minutes of presentation and 5 minutes of questions. Open Space rooms will also be available for follow-up sessions. Proposal Submission ------------------------------- The primary author should submit a proposal, after which additional authors can be added. This is to help us make arrangements for reviewers and draft the conference programme. The proposal must include the following: ? Talk title. ? Choice of one or more category tag. ? Level. Indicate the intended audience difficulty level i.e. beginner, intermediate or advanced. ? Summary (max 100 words) for the website. ? Description : Detailed outline for review; notes for reviewers and permission for your talk to be recorded. Your proposal will be reviewed by the programme committee. If your proposal is accepted, you should thereafter include: ? a companion paper (up to 30 pages) OR ? an extended abstract (up to 3 pages) along with your presentation. Go to http://us.pycon.org/2008/conference/proposals/ example1/ for an example of a conference talk proposal. Please send your proposal (and any questions) to conference at pugs.org.sg. Companion Paper or Extended Abstract Submission ---------------------------------------------------------------------------- All presenters should submit a paper by the deadline above, with or without prior proposal submission. This submission is to be your full paper (companion paper or extended abstract), not a draft. It should contain all of the usual aspects of a paper such as an abstract, introduction, body and conclusion. Please ensure that this submission has had its grammar and spelling corrected and that code snippets work. Your paper will be peer-reviewed by the programme committee and a notice of paper acceptance with review comments will be sent to the author(s) on March 15, 2010. Accepted papers can be amended by the author(s), taking into account of reviewers' comments and submit for publication by April 15, 2010. ? All papers will be published in The Python Papers Monograph series (www.pythonpapers.org). We suggest, but do not require, all authors to place their papers under the Creative Commons license. ? Please see http://www.pythonpapers.org/instAuthor.html for the preferred formats of submission. ? Please submit your papers at http://ojs.pythonpapers.org/index.php/tppm/author. Your paper allows attendees who attended your talk a chance to refresh their memories about your presentation, and gives attendees who missed your talk a chance to learn from you anyway. Make sure your paper includes - at the very least - a brief introduction to your subject material and a list of further resources. Assistance ---------------- PyCon Asia Pacific 2010 in Singapore cannot offer payment or free registration to all conference speakers. However, financial aid will be available were possible, and giving a talk is a great rationale. If you require financial aid in order to attend PyCon Asia Pacific 2010 in Singapore, please note it in your proposal. If you have any questions, contact conference at pugs.org.sg. From wwn1 at sfu.ca Tue Aug 18 20:51:31 2009 From: wwn1 at sfu.ca (WilsonOfCanada) Date: Tue, 18 Aug 2009 17:51:31 -0700 (PDT) Subject: Raw Strings with Variables References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: However, when I send the list over as a dictionary for HTML: d["places"] = arrPlaces return render_to_response('rentSearch.html', d) the HTML using Django has: {{ places }} but returns ['C:\\moo', 'C:\\supermoo'] From clp2 at rebertia.com Tue Aug 18 21:00:56 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 18 Aug 2009 18:00:56 -0700 Subject: Raw Strings with Variables In-Reply-To: References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: <50697b2c0908181800r62abeb00t9632b3f336e2e0c1@mail.gmail.com> On Tue, Aug 18, 2009 at 5:51 PM, WilsonOfCanada wrote: > However, when I send the list over as a dictionary for HTML: > > d["places"] = arrPlaces > > return render_to_response('rentSearch.html', d) > > the HTML using Django has: > > {{ places }} but returns ['C:\\moo', 'C:\\supermoo'] As we've explained already, containers (such as dictionaries and lists) use repr() to display their elements, and repr() for strings shows the escape sequences (e.g. \\ \t \n) and adds surrounding quotes. Hence the output you're getting. If you don't like the way it looks, then either send the list through a filter that outputs it like you want by accessing the elements individually, or iterate over the contents of the list in your template and output it like you want. Cheers, Chris -- http://blog.rebertia.com From http Tue Aug 18 21:07:25 2009 From: http (Paul Rubin) Date: 18 Aug 2009 18:07:25 -0700 Subject: Editing a wiki References: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> Message-ID: <7x1vn8har6.fsf@ruckus.brouhaha.com> KillSwitch writes: > Is it possible to edit a wiki page with python, including logging in > to edit the page, and inserting text into the edit box, etc. If you are talking about MediaWiki (the software behind Wikipedia), it already has an API for which there are several Python clients. See: http://www.mediawiki.org/wiki/API http://www.mediawiki.org/wiki/API:Client_Code If you are looking to use Python (or any other language) to automatically edit Wikipedia itself, you need approval for that. See: http://en.wikipedia.org/wiki/Wikipedia:Bot_policy From davea at ieee.org Tue Aug 18 21:07:27 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 18 Aug 2009 21:07:27 -0400 Subject: Start-up program In-Reply-To: <4A8ABA78.8050605@it.uu.se> References: <4A8ABA78.8050605@it.uu.se> Message-ID: <4A8B504F.8010307@ieee.org> Virgil Stokes wrote: >
How > difficult is to create a program that will be executed when Windows > Vista is started? As Windows Calendar does, for example. > > I am actually more interested in the Python tools that might be used > for this task. I hope that this question is not inappropriate for the > list. :-\ > > --V > > >
> The three responses I've seen probably aren't what you're asking. You have to make a distinction between when Windows starts, and when a user logs in. If you're interested in the point when the user logs in, all you need to do is make a shortcut for the script, no special executable is needed. Just put the shortcut in the Startup folder. But if you're really interested in the point when Windows starts, you have three options. Most painful is making a service. But that's unnecessary. Second way involves the system policy: HKLM\SOFTWARE\Policies\Microsoft|Windows\System\Scripts\ but anything started that way has a 10 minute time limit before it's automatically killed. Third, and easiest way is the task scheduler: Start Menu/All Programs/Accessories/System Tools/ScheduledTasks Add your program in with the scheduled task wizard. There are various scheduling choices, and one of them is called something like "boot". Again, you needn't make a separate EXE file, since Python.exe is already a perfectly valid one. It's likely that Vista has some security oddities, and I don't have any pointers for that. But even in XP, one thing you might need to do is "Fast Logon Optimization". It's enabled by default, but if somebody has turned it off, then logon might be blocked till your special script finishes. DaveA From davidshais at googlemail.com Tue Aug 18 21:12:39 2009 From: davidshais at googlemail.com (David) Date: Tue, 18 Aug 2009 18:12:39 -0700 (PDT) Subject: Scope and classes References: Message-ID: On Aug 19, 1:17?am, "Jan Kaliszewski" wrote: > 19-08-2009 o 02:10:58 Jan Kaliszewski wrote: > > > The only ways to reach Abc's attribute 'message' from that method are: > > * 'Abc.message' > > * 'self.__class__.message' > > * 'self.message' (unless there is an instance attribute 'message' which > > overrides the class attribute). > > And of course getattr(Abc), getattr(self.__class__) etc. :-) > > -- > Jan Kaliszewski (zuo) Out of 'Abc.message' and 'self.message', which is the favoured convention? It would be very easy to accidentally override 'self.messages' with an instance attribute! From ben+python at benfinney.id.au Tue Aug 18 21:22:32 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 11:22:32 +1000 Subject: Scope and classes References: Message-ID: <878whgfvhj.fsf@benfinney.id.au> David writes: > Out of 'Abc.message' and 'self.message', which is the favoured > convention? It's not a matter of convention. They mean different things, so you use each depending on what you mean. > It would be very easy to accidentally override 'self.messages' with an > instance attribute! Right. So you use ?Abc.message? when you specifically want a class independent of any instance, and you use ?self.message? when you want the attribute of this instance (with fallback to the usual resolution order). -- \ ?Any intelligent fool can make things bigger and more complex? | `\ It takes a touch of genius ? and a lot of courage ? to move in | _o__) the opposite direction.? ?Albert Einstein | Ben Finney From ben+python at benfinney.id.au Tue Aug 18 22:01:29 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 12:01:29 +1000 Subject: Scope and classes References: <878whgfvhj.fsf@benfinney.id.au> Message-ID: <874os4ftom.fsf@benfinney.id.au> Ben Finney writes: > Right. So you use ?Abc.message? when you specifically want a class > independent of any instance That's ?a class attribute independent of any instance?, of course. -- \ ?Humanity has advanced, when it has advanced, not because it | `\ has been sober, responsible, and cautious, but because it has | _o__) been playful, rebellious, and immature.? ?Tom Robbins | Ben Finney From gu.yakahughes at gmail.com Tue Aug 18 22:25:07 2009 From: gu.yakahughes at gmail.com (yaka) Date: Tue, 18 Aug 2009 19:25:07 -0700 (PDT) Subject: Editing a wiki References: <62993053-871d-4dd6-96b0-10548ca4ed29@c14g2000yqm.googlegroups.com> <7x1vn8har6.fsf@ruckus.brouhaha.com> Message-ID: <85b24ce4-2cbb-402d-8027-f3025c795db0@r18g2000yqd.googlegroups.com> On Aug 18, 6:07?pm, Paul Rubin wrote: > KillSwitch writes: > > Is it possible to edit a wiki page with python, including logging in > > to edit the page, and inserting text into the edit box, etc. > > If you are talking about MediaWiki (the software behind Wikipedia), > it already has an API for which there are several Python clients. > See: > > ? ?http://www.mediawiki.org/wiki/API > ? ?http://www.mediawiki.org/wiki/API:Client_Code > > If you are looking to use Python (or any other language) to > automatically edit Wikipedia itself, you need approval for that. > See: > > ?http://en.wikipedia.org/wiki/Wikipedia:Bot_policy It's actually a wiki owned by a friend. From sjmachin at lexicon.net Tue Aug 18 22:32:14 2009 From: sjmachin at lexicon.net (John Machin) Date: Tue, 18 Aug 2009 19:32:14 -0700 (PDT) Subject: How do I convert an iterator over bytes into a str? References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> Message-ID: <9e60a01a-46e3-4aab-bbb0-845e4a08fb15@i8g2000pro.googlegroups.com> On Aug 19, 8:24?am, markscottwright wrote: > This does what I expected: > ? ? In [6]: list(iter([1,2,3,4,5])) > ? ? Out[6]: [1, 2, 3, 4, 5] > > But this appears to be doing a __repr__ rather than making me a nice > string: > ? ?In [7]: str(iter("four score and seven years ago")) > ? ?Out[7]: '' > > What's the correct way to turn an iterator over bytes into a string? > This works, but, ewww: > ? ? In [8]: "".join(iter("four score and seven years ago")) > ? ? Out[8]: 'four score and seven years ago' There is no such thing as an "iterator over bytes" in Python 2.x. There is no such concept as "convert an iterator over into a str" object. What you have is an iterator over str objects of length 1. To do what you appear to actually want to do (concatenate a bunch of strings), it is recomemnded to use ''.join(str_iterable). From pavlovevidence at gmail.com Tue Aug 18 23:02:34 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 18 Aug 2009 20:02:34 -0700 (PDT) Subject: How do I convert an iterator over bytes into a str? References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> Message-ID: On Aug 18, 3:24?pm, markscottwright wrote: > This does what I expected: > ? ? In [6]: list(iter([1,2,3,4,5])) > ? ? Out[6]: [1, 2, 3, 4, 5] > > But this appears to be doing a __repr__ rather than making me a nice > string: > ? ?In [7]: str(iter("four score and seven years ago")) > ? ?Out[7]: '' Unfortunately, str() is overloaded in that it tries to be both a sorta- pretty-printer and a constructor. You're trying to use it as a constructor, but it wants to be a sorta-pretty-printer here. Anyway, str is different from other container objects since, unlike other containers, strings can't contain arbitrary Python objects. > What's the correct way to turn an iterator over bytes into a string? > This works, but, ewww: > ? ? In [8]: "".join(iter("four score and seven years ago")) > ? ? Out[8]: 'four score and seven years ago' This is the correct way. If the syntax bothers you can always do this: str.join("",iter("four score")) I think "".join is ugly as hell but in this case convenience beats beauty for me. Carl Banks From grante at visi.com Tue Aug 18 23:23:34 2009 From: grante at visi.com (Grant Edwards) Date: Tue, 18 Aug 2009 22:23:34 -0500 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> Message-ID: On 2009-08-19, Ben Finney wrote: > Simon Forman writes: >> We are one family. > > Agreed. That's not much comfort if you've seen the way many families get along with each other. -- Grant From sajmikins at gmail.com Tue Aug 18 23:27:39 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 23:27:39 -0400 Subject: Inheriting dictionary In-Reply-To: <2fe6d216-1e8f-4de1-8c36-d4ee11bb7233@26g2000yqk.googlegroups.com> References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> <2fe6d216-1e8f-4de1-8c36-d4ee11bb7233@26g2000yqk.googlegroups.com> Message-ID: <50f98a4c0908182027j214c922dx3f82d6114c6eda3a@mail.gmail.com> On Tue, Aug 18, 2009 at 6:08 PM, Simon Forman wrote: > On Aug 18, 3:44?pm, Pavel Panchekha wrote: >> I want a dictionary that will transparently "inherit" from a parent >> dictionary. So, for example: >> >> """ >> a = InheritDict({1: "one", 2: "two", 4: "four"}) >> b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) >> >> a[1] # "one" >> a[4] # "four" >> b[1] # "one" >> b[3] # "three" >> b[4] # "foobar" >> """ >> >> I've written something like this in Python already, but I'm wondering >> if something like this already exists, preferably written in C, for >> speed. > > > I would consider something like the following: > > > a = {1: "one", 2: "two", 4: "four"} > b = {3: "three", 4: "foobar"} > > > from functools import partial > > > def getter(first, second, key): > ? ?try: > ? ? ? ?return first(key) > ? ?except KeyError: > ? ? ? ?return second(key) > > > f = partial(getter, b.__getitem__, a.__getitem__) > > > # Or, if you know you'll be getting a lot of KeyErrors, you > # can use get() instead of __getitem__(). > > def getter1(first, second, key, sentinel=None): > ? ?item = first(key, sentinel) > ? ?if item is sentinel: > ? ? ? ?item = second(key) > ? ?return item > > g = partial(getter1, b.get, a.__getitem__) > > > HTH, > ~Simon > -- > http://mail.python.org/mailman/listinfo/python-list > Since you're going for speed the overhead of using partial (which creates a wrapper object around the getter function) can be replaced by something like this: def makeGetter(first, second): def getter(key): try: return first(key) except KeyError: return second(key) return getter f = makeGetter(b.__getitem__, a.__getitem__) From sajmikins at gmail.com Tue Aug 18 23:43:48 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 23:43:48 -0400 Subject: Need cleanup advice for multiline string In-Reply-To: <0014c4c0$0$2963$c3e8da3@news.astraweb.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <0014c4c0$0$2963$c3e8da3@news.astraweb.com> Message-ID: <50f98a4c0908182043i8a619fdydb9311eadf7cef9@mail.gmail.com> On Tue, Aug 18, 2009 at 8:03 PM, Steven D'Aprano wrote: > On Tue, 18 Aug 2009 17:13:02 -0400, Simon Forman wrote: > >> Sexism, racism, homophobia, religious intolerance, etc., all stem from a >> fundamental forgetfulness of our Unity in God (as I would put it) and > > Of the tens of thousands of Gods that people have invented, which is the > one we're supposed to believe in? I always forget which ones we're > supposed to dismiss as nonsense, and which one we're not. Why the heck are you asking me? (I'd say "/you/ are the God you should believe in.") >> this is perhaps the single greatest cause of human misery. > > Okay, we're Unified in God. Great. What does that actually mean, really? > In the struggle to survive in a world of shortages, disease, natural > disasters and disputes between well-meaning but incompatible viewpoints > (to say nothing of the selfish and greedy), what practical difference > does it make? It means (to me, at least) that underlying all the BS and misery there's a reason to hope, a reality the transcends this squalid mud-ball Earth, and can overcome it completely if tapped. It's more than a symbol with meaning, Unity is a phenomenon that can be lived, experienced. It can be practiced and deepened. Done well, the practical difference it makes defies measurement. (That's why calling folks on sexist behavior is important enough to butt in on a thread on usenet with an OT reprimand. IMHO) Regards, ~Simon From ben+python at benfinney.id.au Tue Aug 18 23:49:12 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 13:49:12 +1000 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> Message-ID: <87vdkkea4n.fsf@benfinney.id.au> Grant Edwards writes: > On 2009-08-19, Ben Finney wrote: > > Simon Forman writes: > >> We are one family. > > > > Agreed. > > That's not much comfort if you've seen the way many families get along > with each other. Demonstrable facts, by nature of being independently verifiable, are a better point of unification than comforting illusions, however confidently asserted. -- \ ?Life does not cease to be funny when people die any more than | `\ it ceases to be serious when people laugh.? ?George Bernard Shaw | _o__) | Ben Finney From sajmikins at gmail.com Tue Aug 18 23:49:45 2009 From: sajmikins at gmail.com (Simon Forman) Date: Tue, 18 Aug 2009 23:49:45 -0400 Subject: Need cleanup advice for multiline string In-Reply-To: <87hbw4fxcq.fsf@benfinney.id.au> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> Message-ID: <50f98a4c0908182049t63322bbiebf53065562cb2@mail.gmail.com> On Tue, Aug 18, 2009 at 8:42 PM, Ben Finney wrote: > Simon Forman writes: > >> Sexism, racism, homophobia, religious intolerance, etc., all stem from >> a fundamental forgetfulness of our Unity in God (as I would put it) > > It seems odd, for someone who cites religious intolerance as a problem, > to then assert an extremely divisive religious idea. Well, I did say, "(as I would put it)" to try to cushion the blow. > We're all unified by our humanity. Bringing any god into the picture is > surely counter to any goals of unity. Unity "in humanity" is, to my way of thinking, the same as Unity "in God". I think Unity, like None, is a built-in singleton, so to speak. >> We are one family. > > Agreed. <3 From ben+python at benfinney.id.au Wed Aug 19 00:05:53 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 19 Aug 2009 14:05:53 +1000 Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> Message-ID: <87r5v8e9cu.fsf@benfinney.id.au> Simon Forman writes: > On Tue, Aug 18, 2009 at 8:42 PM, Ben Finney wrote: > > We're all unified by our humanity. Bringing any god into the picture > > is surely counter to any goals of unity. > > Unity "in humanity" is, to my way of thinking, the same as Unity "in > God". Then you're playing Humpty-Dumpty games with words. You know very well that ?God? has established meanings entirely different from ?humanity?, and those meanings played a part in your choice of that word. I maintain that you can't consistently make a declaration in favour of human unity and unfounded religious assertions. > I think Unity, like None, is a built-in singleton, so to speak. This is white noise. > >> We are one family. > > > > Agreed. > > <3 I think we can peaceably leave it at that. -- \ ?Spam will be a thing of the past in two years' time.? ?Bill | `\ Gates, 2004-01-24 | _o__) | Ben Finney From pavlovevidence at gmail.com Wed Aug 19 00:14:05 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Tue, 18 Aug 2009 21:14:05 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> <87vdkkea4n.fsf@benfinney.id.au> Message-ID: On Aug 18, 8:49?pm, Ben Finney wrote: > Grant Edwards writes: > > On 2009-08-19, Ben Finney wrote: > > > Simon Forman writes: > > >> We are one family. > > > > Agreed. > > > That's not much comfort if you've seen the way many families get along > > with each other. > > Demonstrable facts, by nature of being independently verifiable, are a > better point of unification than comforting illusions, however > confidently asserted. You know, if you're going to escalate a budding flame war the least you could do is to choose to do it some other way than by following up to an obvious joke, probably one designed to diffuse the ill-feeling. Carl Banks From mensanator at aol.com Wed Aug 19 00:37:04 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 18 Aug 2009 21:37:04 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <4A89CEA2.10400@mrabarnett.plus.com> <0014291d$0$2963$c3e8da3@news.astraweb.com> Message-ID: <58ea46ae-0ad0-4d63-b3ba-7ed693a2b381@d32g2000yqh.googlegroups.com> On Aug 18, 7:59?am, Steven D'Aprano wrote: > On Tue, 18 Aug 2009 13:36:49 +0200, Jean-Michel Pichavant wrote: > > MRAB wrote: > >> Carl Banks wrote: > >>> On Aug 17, 10:03 am, Jean-Michel Pichavant > >>> wrote: > >>>> I'm no English native, but I already heard women/men referring to a > >>>> group as "guys", no matter that group gender configuration. It's even > >>>> used for group composed exclusively of women. Moreover it looks like > >>>> a *very* friendly form, so there is really nothing to worry about it. > > >>> I like how being very friendly means calling people after a guy who > >>> tried to blow up the English Parliament. > > >> Guy Fawkes adopted the name Guido while fighting for the Spanish in the > >> Low Countries: > > >>http://en.wikipedia.org/wiki/Guy_Fawkes > > > I didn't get Carl's reference. The only thing I know about blowing the > > parliament is from the movie V for Vendetta (no comment please !). Now > > thanks to your link: > > "In 18th-century England, the term "guy" was used to refer to an effigy > > of Fawkes, which would be paraded > > around town by children on the anniversary of the conspiracy" > > > Well, my knowledge is much too low to get this kind of reference from > > the start. :-/ > > "Guy" is an old English name, related to the old French name "Gy" and > Italian "Guido". It's originally derived from the Old German for "wood" > or "warrior". > > After Guy Fawkes tried to blow up the English Parliament house, and was > executed, the British government encouraged people to burn effigies of > him. These became known as "guys", which eventually became slang for an > ugly man, which later became slang for any man, and in recent years, any > person. > > So the irony is that the friendly term "guys", referring to a group of > people, is derived from the name of an 18th century You're off by at least a century. > religious terrorist. As were all members of parliament including the king. > > One can only wonder whether in 200 years time people will walk into the > office and say "Hey you osamas, they're giving away free donuts down > stairs, anyone want some?" Q: What's white and flies across the ocean? A: Lord Mountbatten's tennis shoes. Ain't so fuckin' funny, is it? (Unless you're Irish, in which case it's hysterical). > > -- > Steven From gallium.arsenide at gmail.com Wed Aug 19 00:44:01 2009 From: gallium.arsenide at gmail.com (John Yeung) Date: Tue, 18 Aug 2009 21:44:01 -0700 (PDT) Subject: Code formatting question: conditional expression References: Message-ID: On Aug 18, 1:25?pm, John Posner wrote: > BTW, from the (admittedly few) responses to my original > post, it seems there's some sentiment that "conditional > expressions" are a non-Pythonic misfeature. Interesting ... Well, it's not like Guido was especially eager to add it in the first place. I personally wouldn't call it a misfeature, but it shares with lambda the property that it's best used when what you need to say with it is very short. John Y. From mensanator at aol.com Wed Aug 19 00:52:43 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 18 Aug 2009 21:52:43 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> <86bb893a-344a-4c7b-9fc6-67d9f42c7607@q14g2000vbi.googlegroups.com> Message-ID: <62dbf088-4510-40d0-af3e-3feeb291d6e4@t13g2000yqt.googlegroups.com> On Aug 17, 11:35?pm, Carl Banks wrote: > On Aug 17, 8:49?pm, Mensanator wrote: > > > > > > > On Aug 17, 8:04 pm, Carl Banks wrote: > > > > On Aug 17, 5:40 pm, Mensanator wrote: > > > > > On Aug 17, 4:06 pm, Carl Banks wrote: > > > > > > On Aug 17, 10:03 am, Jean-Michel Pichavant > > > > > wrote: > > > > > > > I'm no English native, but I already heard women/men referring to a > > > > > > group as "guys", no matter that group gender configuration. It's even > > > > > > used for group composed exclusively of women. Moreover it looks like a > > > > > > *very* friendly form, so there is really nothing to worry about it. > > > > > > I like how being very friendly means calling people after a guy who > > > > > tried to blow up the English Parliament. > > > > > So? > > > > I also like how making an amusing pointless observation > > > Pointless, yes, but what was amusing abot the observation? > > The irony that in being friendly that you're calling someone a > terrorist. ? People of Irish Catholic heritage find that extremely offensive, like asking how many Jews you can fit into a Volswagen. > I guess I shouldn't have expected you to get it. Oh, I got it alright, moreso than you could possibly imagine. > > > > gets people all huffy. > > > That wasn't huffy. You want to see huffy, make a wisecrack > > comparing mothballs to Zyklon B, you'll REALLY get a load > > of huffy replies. > > > > (BTW, lest anyone is not aware, that is the origin of the word "guy", > > > It most certainly is not. > > My dictionary disagrees with you. hen yor dictionary is wrong. Or, more likely, you have comprehension problems. People have been named "Guy" for centuries prior to Mr. Fawkes. Try reading my whole post before shouting your mouth off. > > > Maybe the origin of that > > word's useage as a genric reference to a male, but > > you didn't say that. > > > > this was not some random association.) > > > Penny for the guy? > > Probably that phrase was part of the word's gradual common adoption. Kinda why I mentioned it. Duh. > > Carl Banks From mensanator at aol.com Wed Aug 19 01:07:09 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 18 Aug 2009 22:07:09 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <4A89CEA2.10400@mrabarnett.plus.com> Message-ID: On Aug 18, 6:36?am, Jean-Michel Pichavant wrote: > MRAB wrote: > > Carl Banks wrote: > >> On Aug 17, 10:03 am, Jean-Michel Pichavant > >> wrote: > >>> I'm no English native, but I already heard women/men referring to a > >>> group as "guys", no matter that group gender configuration. It's even > >>> used for group composed exclusively of women. Moreover it looks like a > >>> *very* friendly form, so there is really nothing to worry about it. > > >> I like how being very friendly means calling people after a guy who > >> tried to blow up the English Parliament. > > > Guy Fawkes adopted the name Guido while fighting for the Spanish in the > > Low Countries: > > >http://en.wikipedia.org/wiki/Guy_Fawkes > > I didn't get Carl's reference. The only thing I know about blowing the > parliament is from the movie V for Vendetta (no comment please !). > Now thanks to your link: > "In 18th-century England, the term "guy" was used to refer to an effigy > of Fawkes, which would be paraded > around town by children on the anniversary of the conspiracy" > > Well, my knowledge is much too low to get this kind of reference from > the start. :-/ So I guess you have no clue WHY Mr. Fawkes would want to blow up the parliment and assassinate the king. Read up a bit on how just how the Church of England came to be and it will be quite obvious. On some TV show, someone did a re-creation of that event to see what would have happened had he not gotten caught. They built a life-size mockuup of the room under which the gunpowder kegs were stashed and filled the room with dummys. The blast was spectacular. They eventually found the head of the dummy representing king James a couple miles away. Or maybe it was kilometers. Either way, the conclusion was it was very lucky to have worked out the way it did. > > JM From greg at cosc.canterbury.ac.nz Wed Aug 19 02:07:13 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 19 Aug 2009 18:07:13 +1200 Subject: Changing Python Opcodes In-Reply-To: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> References: <1e3f4885-f908-4a45-8f7a-1a45e9d91b27@n11g2000yqb.googlegroups.com> Message-ID: <7f1j3gF2hsc2hU1@mid.individual.net> Sreejith K wrote: > I know this is not the best way to do it. But I have to do it at least > to make it *hard* to decompile the python bytecode. > So I compiled Python from source changing some opcode values It probably wouldn't be all that hard for someone to figure this out. A possible avenue of attack would be to use your python to compile a known piece of code that exercises all the opcodes, and compare the result with that from a standard python. -- Greg From sakib.iqbal at gmail.com Wed Aug 19 02:08:49 2009 From: sakib.iqbal at gmail.com (Sakib) Date: Tue, 18 Aug 2009 23:08:49 -0700 (PDT) Subject: can't retrieve data from pyxml Message-ID: <64baa6b4-2cd7-451e-a749-9fdca8c62d2c@k19g2000yqn.googlegroups.com> well, i need to retrive data from the following line of xml. i need the Caption and the type data. is any one out there help me doing that? thanks, Sakib From greg at cosc.canterbury.ac.nz Wed Aug 19 02:11:43 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 19 Aug 2009 18:11:43 +1200 Subject: define class over 2 files In-Reply-To: <6a490ec8-3536-4508-afd4-90a5cf9317b5@g10g2000yqh.googlegroups.com> References: <7de550a5-64af-4f40-a7fc-e3c449d0dce9@h21g2000yqa.googlegroups.com> <6a490ec8-3536-4508-afd4-90a5cf9317b5@g10g2000yqh.googlegroups.com> Message-ID: <7f1jbuF2ifjr1U1@mid.individual.net> naveen wrote: >>>Is it possible to split up a class definition over multiple files? >> >>Not exactly, but you can do variations of this: > > ... [subclass a class] Multiple inheritance can also be useful: # A_Part1.py class A_Part1: ... # A_Part2.py class A_Part2: ... # A.py from A_Part1 import A_Part1 from A_Part2 import A_Part2 class A(A_Part1, A_Part2): ... -- Greg From danb_83 at yahoo.com Wed Aug 19 02:17:55 2009 From: danb_83 at yahoo.com (AggieDan04) Date: Tue, 18 Aug 2009 23:17:55 -0700 (PDT) Subject: Read C++ enum in python References: <4a8b3342$0$25403$426a34cc@news.free.fr> Message-ID: On Aug 18, 6:03?pm, Ludo wrote: > Hello, > > I work in a very large project where we have C++ packages and pieces of > python code. > > I've been googleing for days but what I find seems really too > complicated for what I want to do. > > My business is, in python, to read enum definitions provided by the > header file of an c++ package. > Of course I could open the .h file, read the enum and transcode it by > hand into a .py file but the package is regularly updated and thus is > the enum. > > My question is then simple : do we have : > ? ? ? ? - either a simple way in python to read the .h file, retrieve the c++ > enum and provide an access to it in my python script Try something like this: file_data = open(filename).read() # Remove comments and preprocessor directives file_data = ' '.join(line.split('//')[0].split('#')[0] for line in file_data.splitlines()) file_data = ' '.join(re.split(r'\/\*.*\*\/', file_data)) # Look for enums: In the first { } block after the keyword "enum" enums = [text.split('{')[1].split('}')[0] for text in re.split(r'\benum \b', file_data)[1:]] for enum in enums: last_value = -1 for enum_name in enum.split(','): if '=' in enum_name: enum_name, enum_value = enum_name.split('=') enum_value = int(enum_value, 0) else: enum_value = last_value + 1 last_value = enum_value enum_name = enum_name.strip() print '%s = %d' % (enum_name, enum_value) print From stefan_ml at behnel.de Wed Aug 19 02:42:59 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Wed, 19 Aug 2009 08:42:59 +0200 Subject: Parallelization in Python 2.6 In-Reply-To: References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> Message-ID: <4a8b9ef4$0$31865$9b4e6d93@newsspool3.arcor-online.net> Dennis Lee Bieber wrote: > On Tue, 18 Aug 2009 13:45:38 -0700 (PDT), Robert Dailey wrote: >> Really, all I'm trying to do is the most trivial type of >> parallelization. Take two functions, execute them in parallel. This >> type of parallelization is called "embarrassingly parallel", and is >> the simplest form. There are no dependencies between the two >> functions. They do requires read-only access to shared data, though. >> And if they are being spawned as sub-processes this could cause >> problems, unless the multiprocess module creates pipelines or other >> means to handle this situation. It wouldn't be much worth if it didn't, as the subprocess module handles everything else nicely. See the Queue classes. > If they are number crunchers (CPU-bound) and don't make use of > binary extension libraries that release the GIL (for the most common > Python implementation), they'll run faster being called in sequence > since you won't have the overhead of task switching. ... unless, obviously, the hardware is somewhat up to date (which is not that uncommon for number crunching environments) and can execute more than one thing at once. Stefan From deets at nospam.web.de Wed Aug 19 02:56:11 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 08:56:11 +0200 Subject: recording input from USB port and write to text file In-Reply-To: References: Message-ID: <7f1m0bF2iv0uuU1@mid.uni-berlin.de> Allan schrieb: > Hi! I'm fairly new to Python. I understand the basics basics but I'm > been trying to write a simple python code that will let me read input > data (such as mouse movement) from my USB port and write it in a text > file and I am so lost. Can anyone help or direct me to some > resources? Thank you! This isn't as easy as you think. And dependend on your operating-system. Diez From deets at nospam.web.de Wed Aug 19 03:01:45 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 09:01:45 +0200 Subject: can't retrieve data from pyxml In-Reply-To: <64baa6b4-2cd7-451e-a749-9fdca8c62d2c@k19g2000yqn.googlegroups.com> References: <64baa6b4-2cd7-451e-a749-9fdca8c62d2c@k19g2000yqn.googlegroups.com> Message-ID: <7f1mapF2iv0uuU2@mid.uni-berlin.de> Sakib schrieb: > well, i need to retrive data from the following line of xml. > > msdata:Caption="Microtia" type="xs:string" minOccurs="0" /> > > i need the Caption and the type data. > > is any one out there help me doing that? That's not XML. It lacks namespace-declarations. So no XML-parser will (or should) grok it. Also, to get help here it's better to show what you already tried, instead of simply asking others to do your work for you. Diez From hendrik at microcorp.co.za Wed Aug 19 03:03:49 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 19 Aug 2009 09:03:49 +0200 Subject: Diversity in Python In-Reply-To: <8763cliez7.fsf@benfinney.id.au> References: <8763cliez7.fsf@benfinney.id.au> Message-ID: <200908190903.49977.hendrik@microcorp.co.za> On Tuesday 18 August 2009 12:38:36 Ben Finney wrote: > Hendrik van Rooyen writes: > > On Tuesday 18 August 2009 06:45:39 Aahz wrote: > > > Mainly an opportunity to flog the new diversity list. > > > > Here my English fails me - flog as in "whip", or flog as in "sell"? > > Yes :-) Thank you that clears it up. :-) - Hendrik From hendrik at microcorp.co.za Wed Aug 19 03:24:13 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 19 Aug 2009 09:24:13 +0200 Subject: Inheriting dictionary In-Reply-To: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> References: <95736695-29b5-4185-8764-8eca140b76d2@e18g2000vbe.googlegroups.com> Message-ID: <200908190924.13792.hendrik@microcorp.co.za> On Tuesday 18 August 2009 21:44:55 Pavel Panchekha wrote: > I want a dictionary that will transparently "inherit" from a parent > dictionary. So, for example: > > """ > a = InheritDict({1: "one", 2: "two", 4: "four"}) > b = InheritDict({3: "three", 4: "foobar"}, inherit_from=a) > > a[1] # "one" > a[4] # "four" > b[1] # "one" > b[3] # "three" > b[4] # "foobar" > """ > > I've written something like this in Python already, but I'm wondering > if something like this already exists, preferably written in C, for > speed. Its not inheritance, but have you looked at the update method? -Hendrik From metolone+gmane at gmail.com Wed Aug 19 03:28:15 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Wed, 19 Aug 2009 00:28:15 -0700 Subject: Read C++ enum in python References: <4a8b3342$0$25403$426a34cc@news.free.fr> <4A8B3E2D.7040702@mrabarnett.plus.com> Message-ID: "MRAB" wrote in message news:4A8B3E2D.7040702 at mrabarnett.plus.com... > Ludo wrote: >> Hello, >> >> I work in a very large project where we have C++ packages and pieces of >> python code. >> >> I've been googleing for days but what I find seems really too complicated >> for what I want to do. >> >> My business is, in python, to read enum definitions provided by the >> header file of an c++ package. >> Of course I could open the .h file, read the enum and transcode it by >> hand into a .py file but the package is regularly updated and thus is the >> enum. >> >> My question is then simple : do we have : >> - either a simple way in python to read the .h file, retrieve the c++ >> enum and provide an access to it in my python script >> - either a simple tool (in a long-term it would be automatically run >> when the c++ package is compiled) generating from the .h file a .py file >> containing the python definition of the enums ? >> >> Thank you for any suggestion. > > Speaking personally, I'd parse the .h file using a regular expression > (re module) and generate a .py file. Compilers typically have a way of > letting you run external scripts (eg batch files in Windows or, in this > case, a Python script) when an application is compiled. This is what 3rd party library pyparsing is great for: --------begin code---------- from pyparsing import * # sample string with enums and other stuff sample = ''' stuff before enum hello { Zero, One, Two, Three, Five=5, Six, Ten=10 } in the middle enum blah { alpha, beta, gamma = 10 , zeta = 50 } at the end ''' # syntax we don't want to see in the final parse tree _lcurl = Suppress('{') _rcurl = Suppress('}') _equal = Suppress('=') _comma = Suppress(',') _enum = Suppress('enum') identifier = Word(alphas,alphanums+'_') integer = Word(nums) enumValue = Group(identifier('name') + Optional(_equal + integer('value'))) enumList = Group(enumValue + ZeroOrMore(_comma + enumValue)) enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl # find instances of enums ignoring other syntax for item,start,stop in enum.scanString(sample): id = 0 for entry in item.list: if entry.value != '': id = int(entry.value) print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id) id += 1 --------------end code------------ Output: HELLO_ZERO = 0 HELLO_ONE = 1 HELLO_TWO = 2 HELLO_THREE = 3 HELLO_FIVE = 5 HELLO_SIX = 6 HELLO_TEN = 10 BLAH_ALPHA = 0 BLAH_BETA = 1 BLAH_GAMMA = 10 BLAH_ZETA = 50 -Mark From hendrik at microcorp.co.za Wed Aug 19 03:31:18 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 19 Aug 2009 09:31:18 +0200 Subject: Parallelization in Python 2.6 In-Reply-To: <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> Message-ID: <200908190931.18297.hendrik@microcorp.co.za> On Tuesday 18 August 2009 22:45:38 Robert Dailey wrote: > Really, all I'm trying to do is the most trivial type of > parallelization. Take two functions, execute them in parallel. This > type of parallelization is called "embarrassingly parallel", and is > the simplest form. There are no dependencies between the two > functions. They do requires read-only access to shared data, though. > And if they are being spawned as sub-processes this could cause > problems, unless the multiprocess module creates pipelines or other > means to handle this situation. Just use thread then and thread.start_new_thread. It just works. - Hendrik From gabriel.rossetti at arimaz.com Wed Aug 19 03:34:52 2009 From: gabriel.rossetti at arimaz.com (Gabriel Rossetti) Date: Wed, 19 Aug 2009 09:34:52 +0200 Subject: socket bug or not? Message-ID: <4A8BAB1C.7090700@arimaz.com> Hello everyone, I found what was not working in my code (see Twisted mailing list topics "self.socket.accept() in doRead() in tcp.py has (11, 'Resource temporarily unavailable') error", "Twisted, PushProducer, Words & big msgs, any limit?" and Python mailing list topic "socket.send : (11, 'Resource temporarily unavailable')"). I was just wondering if this was a bug or not, so here it is, I wrote aserver using twisted words' xmlstream class. When a client connects, it sends "" and the server also sends it, so a bi-directional xmlstream communication is established. This works fine, I at some point wrote a webservice to send msgs to my system, not using any twisted code, that sends a message to my server in this format : ".....". This worked fine as long as the messages were small, but if it send larger msgs (I tried +128k msgs) the server only received part of the msg and then the parser died because of this, so my msg appeared to be dropped. I discovered that it was because my webservice did not read the "" element sent by the server when it connected (since I was not interested in having a bidirectional xml stream communication with it), when I added the code to read it, everything worked as expected. I tested the webservice to without the server to see if it had a problem, using netcat, and it does, so I wonder if there is a bug in the socket code or not. Here is the test code : ###################### Listing 1 Start ###################### import socket, time STREAM_START = "" STREAM_END = "" def sendTestMessage(host, port): msg = "" + ('a' * 175177) + "" burstSize = 4096 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.send(STREAM_START) time.sleep(5) while msg: sent = sock.send(msg[:burstSize]) print "Sending %d bytes..." % sent if sent == 0: raise RuntimeError, "socket connection broken" msg = msg[burstSize:] sock.send(STREAM_END) sock.close() ###################### Listing 1 End ###################### To test it: 1) open a python interpretor, copy-past the code above 2) open another terminal and run netcat using the following command : nc -v -l -p 4444 3) call the above function using : sendTestMessage("localhost", 4444), it will wait 5 seconds after having sent the , for the first test, just wait. The message will be completely send and received by the netcat "server", now let's test the case I have, where the server sends a , to do that, repeat the above steps (you have to re-run netcat as it exits when the client disconnects), except in step 3 instead of just waiting, type and press enter in the netcat terminal after having received the element from the sending code. This time you will see that the message is incomplete. If you send a smaller message, like by replacing the following line : msg = "" + ('a' * 175177) + "" with : msg = "" + ('a' * (175177/4)) + "" it works in both cases. Now test the "fixed" code : ###################### Listing 2 Start ###################### import socket STREAM_START = "" STREAM_END = "" def sendTestMessage(host, port): msg = "" + ('a' * 175177) + "" burstSize = 4096 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((host, port)) sock.send(STREAM_START) sock.recv(len(STREAM_START)+1) while msg: sent = sock.send(msg[:burstSize]) print "Sending %d bytes..." % sent if sent == 0: raise RuntimeError, "socket connection broken" msg = msg[burstSize:] sock.send(STREAM_END) sock.close() ###################### Listing 2 End ###################### This time the code reads for the element after sending the element so it works, just try the steps described above, the ones where you have to type and press enter in the netcat terminal and this time it works. Is this a bug in the sockets code, or is this normal? If it's normal I think it should be mentioned somewhere. Oh, by the way, I use linux and this code was tested only on linux, I don't know if the problem also occurs on other platforms. Gabriel From digisatori at gmail.com Wed Aug 19 03:57:44 2009 From: digisatori at gmail.com (digisatori at gmail.com) Date: Wed, 19 Aug 2009 00:57:44 -0700 (PDT) Subject: expandtabs acts unexpectedly Message-ID: <7e598693-c248-4304-bc46-ac79a8a3969b@t11g2000prh.googlegroups.com> Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> ' test\ttest'.expandtabs(4) ' test test' >>> 'test \ttest'.expandtabs(4) 'test test' 1st example: expect returning 4 spaces between 'test', 3 spaces returned 2nd example: expect returning 5 spaces between 'test', 4 spaces returned Is it a bug or something, please advice. From contact at xavierho.com Wed Aug 19 04:10:49 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 19 Aug 2009 18:10:49 +1000 Subject: expandtabs acts unexpectedly In-Reply-To: <7e598693-c248-4304-bc46-ac79a8a3969b@t11g2000prh.googlegroups.com> References: <7e598693-c248-4304-bc46-ac79a8a3969b@t11g2000prh.googlegroups.com> Message-ID: <2d56febf0908190110o57d6b345xc2010dd14f5d503a@mail.gmail.com> On Wed, Aug 19, 2009 at 5:57 PM, digisatori at gmail.com wrote: > Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> ' test\ttest'.expandtabs(4) > ' test test' > >>> 'test \ttest'.expandtabs(4) > 'test test' > > Is it a bug or something, please advice. > -- It is completely working as intended. What were you expecting instead? Regards, -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From nyamatongwe+thunder at gmail.com Wed Aug 19 04:12:48 2009 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Wed, 19 Aug 2009 08:12:48 GMT Subject: Read C++ enum in python In-Reply-To: References: <4a8b3342$0$25403$426a34cc@news.free.fr> Message-ID: <4uOim.12753$ze1.6481@news-server.bigpond.net.au> AggieDan04: > file_data = open(filename).read() > # Remove comments and preprocessor directives > file_data = ' '.join(line.split('//')[0].split('#')[0] for line in > file_data.splitlines()) > file_data = ' '.join(re.split(r'\/\*.*\*\/', file_data)) For some headers I tried it didn't work until the .* was changed to a non-greedy .*? to avoid removing from the start of the first comment to the end of the last comment. file_data = ' '.join(re.split(r'\/\*.*?\*\/', file_data)) Neil From http Wed Aug 19 04:13:41 2009 From: http (Paul Rubin) Date: 19 Aug 2009 01:13:41 -0700 Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> Message-ID: <7xbpmcnruy.fsf@ruckus.brouhaha.com> Hendrik van Rooyen writes: > Just use thread then and thread.start_new_thread. > It just works. The GIL doesn't apply to threads made like that?! From peter at peter-b.co.uk Wed Aug 19 04:16:35 2009 From: peter at peter-b.co.uk (Peter Brett) Date: Wed, 19 Aug 2009 09:16:35 +0100 Subject: expandtabs acts unexpectedly References: <7e598693-c248-4304-bc46-ac79a8a3969b@t11g2000prh.googlegroups.com> Message-ID: "digisatori at gmail.com" writes: > Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> ' test\ttest'.expandtabs(4) > ' test test' >>>> 'test \ttest'.expandtabs(4) > 'test test' > > 1st example: expect returning 4 spaces between 'test', 3 spaces > returned > 2nd example: expect returning 5 spaces between 'test', 4 spaces > returned > > Is it a bug or something, please advice. Consider where the 4-space tabstops are relative to those strings: test test test test ^ ^ ^ So no, it's not a bug. If you just want to replace the tab characters by spaces, use: >>> " test\ttest".replace("\t", " ") ' test test' >>> "test \ttest".replace("\t", " ") 'test test' HTH, Peter -- Peter Brett Remote Sensing Research Group Surrey Space Centre From user at example.net Wed Aug 19 04:40:28 2009 From: user at example.net (superpollo) Date: Wed, 19 Aug 2009 10:40:28 +0200 Subject: reading a text file Message-ID: <4a8bba7d$0$40004$4fafbaef@reader3.news.tin.it> hi clp what's the difference between: while True: input_line = sys.stdin.readline() if input_line: sys.stdout.write(input_line.upper()) else: break and: while True: try: sys.stdout.write(sys.stdin.next().upper()) except StopIteration: break ??? From http Wed Aug 19 04:46:16 2009 From: http (Paul Rubin) Date: 19 Aug 2009 01:46:16 -0700 Subject: reading a text file References: <4a8bba7d$0$40004$4fafbaef@reader3.news.tin.it> Message-ID: <7xocqci42v.fsf@ruckus.brouhaha.com> superpollo writes: > while True: > try: > sys.stdout.write(sys.stdin.next().upper()) > except StopIteration: > break Maybe there is some subtle difference, but it looks like you really mean for line in sys.stdin: sys.stdout.write(line.upper()) From pierre.gaillard at gmail.com Wed Aug 19 04:48:43 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Wed, 19 Aug 2009 01:48:43 -0700 (PDT) Subject: difference between 2 arrays Message-ID: Hello, I would like to know how to find the difference (set operation) between 2 arrays : a = array([1,2, 3,2,5,2]) b = array([1,2]) I want a - b = [3,5] Well, the equivalence of setdiff in matlab... I thought a.difference(b) could work, but no : AttributeError: 'numpy.ndarray' object has no attribute 'difference' Thanks ! From deets at nospam.web.de Wed Aug 19 04:52:13 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 10:52:13 +0200 Subject: Code formatting question: conditional expression References: Message-ID: <7f1sptF2gcfgnU1@mid.uni-berlin.de> > BTW, from the (admittedly few) responses to my original post, it seems > there's some sentiment that "conditional expressions" are a non-Pythonic > misfeature. Interesting ... No. I love them. But not if they are so large that they stretch over several lines (or to many columns). foo = bar if cond else baz is more than fine for me. But foo = I_need_to_do_something_really_complicated_here() if cond else baz isn't, because one doesn't grasp as easily in one look that we're talking a ternary operator here. Diez From james.harris.1 at googlemail.com Wed Aug 19 04:52:22 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Wed, 19 Aug 2009 01:52:22 -0700 (PDT) Subject: Identifying a class type - bad practice? References: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> Message-ID: <520f55a6-38ac-432b-97e7-ec327740645a@o6g2000yqj.googlegroups.com> On 18 Aug, 21:50, Chris Rebert wrote: > On Tue, Aug 18, 2009 at 10:09 AM, James > > Harris wrote: > > I am writing some code to form a tree of nodes of different types. The > > idea is to define one class per node type such as > > > class node_type_1(node): > > ? > > class node_type_2(node): > > ? > > etc > > > (Class "node" would hold any common properties). > > > When walking the tree I need to know what type of node I'm dealing > > with so polymorphism isn't generally useful. The action to be taken > > depends on the node type. > > I'm sure it relates to the exact type of tree you're walking and the > calculation you're doing on it, but what is the reason why your code, > which in the abstract sounds like it will vaguely resemble this: > > def walk_tree(tree): > ? ? if isinstance(tree, node_type_1): > ? ? ? ? #code > ? ? ? ? walk_tree(subtree) > ? ? elif isinstance(tree, node_type_2): > ? ? ? ? #code > ? ? ? ? walk_tree(subtree) > ? ? #etc... > > can't be written instead as: > > class node_type_1: > ? ? def walk_tree(self): > ? ? ? ? #code > ? ? ? ? self.subtree.walk() > > class node_type_2: > ? ? def walk_tree(self): > ? ? ? ? #code > ? ? ? ? self.subtree.walk() > > #etc Interesting idea. This may be a better and a more OO solution than what I had in mind. I'm not sure if I can use this but I'll see how it fits in as the work progresses. The tree is for a compiler. Initially the tree is for parsing of source code. Then it will need to be processed and changed as further compiler phases are written. I don't know yet whether it will be easier to modify the tree or to create a new one for each phase. So I guess whether I use the idea depends on the commonality of operations. James From deets at nospam.web.de Wed Aug 19 04:54:16 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 10:54:16 +0200 Subject: difference between 2 arrays References: Message-ID: <7f1stoF2gcfgnU2@mid.uni-berlin.de> Pierre wrote: > Hello, > > I would like to know how to find the difference (set operation) > between 2 arrays : > > a = array([1,2, 3,2,5,2]) > b = array([1,2]) > I want a - b = [3,5] > > Well, the equivalence of setdiff in matlab... > > I thought a.difference(b) could work, but no : AttributeError: > 'numpy.ndarray' object has no attribute 'difference' Not sure if this works with numpy-arrays, but set(a) - set(b) might just work if the arrays are iterable. Diez From enleverLesX_XXmcX at XmclavXeauX.com Wed Aug 19 04:56:20 2009 From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP) Date: Wed, 19 Aug 2009 10:56:20 +0200 Subject: difference between 2 arrays References: Message-ID: <4a8bbe36$0$12654$ba4acef3@news.orange.fr> (envoy? via news:\\news.wanadoo.fr\comp.lang.python) Hi! See the module "sets" @-salutations -- Michel Claveau From enleverLesX_XXmcX at XmclavXeauX.com Wed Aug 19 04:58:53 2009 From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP) Date: Wed, 19 Aug 2009 10:58:53 +0200 Subject: difference between 2 arrays References: Message-ID: <4a8bbecf$0$12634$ba4acef3@news.orange.fr> Re ! Juste pour signaler qu'il existe un newsgroup en fran?ais sur Python, qui permet de recevoir des r?ponses en fran?ais (donc plus compl?tes/d?taill?es). @-salutations -- Michel Claveau From h.jaeger at medienkonzepte.de Wed Aug 19 05:00:52 2009 From: h.jaeger at medienkonzepte.de (=?ISO-8859-1?Q?Horst_J=E4ger?=) Date: Wed, 19 Aug 2009 11:00:52 +0200 Subject: How to create ones own lib Message-ID: Hi, I would like to create my own lib "hotte.py" which I can import like import string,hotte . How do I do that? I'm working on MacOS 10.5.6 . Thanks in advance From __peter__ at web.de Wed Aug 19 05:08:06 2009 From: __peter__ at web.de (Peter Otten) Date: Wed, 19 Aug 2009 11:08:06 +0200 Subject: reading a text file References: <4a8bba7d$0$40004$4fafbaef@reader3.news.tin.it> Message-ID: superpollo wrote: > hi clp > > what's the difference between: > > while True: > input_line = sys.stdin.readline() > if input_line: > sys.stdout.write(input_line.upper()) > else: > break > > and: > > > while True: > try: > sys.stdout.write(sys.stdin.next().upper()) > except StopIteration: > break You should write the latter as for line in sys.stdin: sys.stdout.write(line.upper()) or sys.stdout.writelines(line.upper() for line in sys.stdin) You seem to know already that next() and readline() use different ways to signal "I'm done with the file". Also, after the first StopIteration subsequent next() calls are guaranteed to raise a StopIteration. But the main difference is that file.next() uses an internal buffer, file.readline() doesn't. That means you would lose data if you tried to replace the readline() call below with next() first_line = f.readline() read_of_the_file = f.read() In newer Python versions you will get a ValueError when mixing next() and read()/readline() but in older Pythons (before 2.5 I think) you are in for a surprise. As for line in file: ... is both the fastest and most readable approach if you want to access a file one line at a time I recommend that you use it unless there is a specific reason not to. Peter From gforgx at lavabit.com Wed Aug 19 05:18:37 2009 From: gforgx at lavabit.com (Sergey Simonenko) Date: Wed, 19 Aug 2009 03:18:37 -0600 Subject: Subclass dynamically In-Reply-To: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com> References: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com> Message-ID: On Sat, 08 Aug 2009 11:12:30 -0600, Robert Dailey wrote: How can you subclass a class from an object?.. > Hey, > > I have a class that I want to have a different base class depending on > a parameter that I pass to its __init__method. For example > (pseudocode): > > class MyDerived( self.base ): > def __init__( self, base ): > self.base = base > > > Something like that... and then I would do this: > > foo = MyDerived( MyBase() ) > > Note I'm using Python 3.1 on Windows. Thanks in advance. -- Kind regards, Sergey Simonenko. From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 19 05:18:59 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 19 Aug 2009 11:18:59 +0200 Subject: Scope and classes In-Reply-To: References: Message-ID: <4a8bc383$0$1556$426a34cc@news.free.fr> Chris Rebert a ?crit : (snip) > To access class-level variables from within instance methods of the > class, you have 2 options: > A. Use the class name, i.e. Abc.message > B. Reference the class indirectly, i.e. self.__class__.message Or even simpler - *if* there's no synonym instance attribute: => self.message Attribute lookup will try to resolve the attribute name on the class (and it's parent classes) if it's not found on the instance. From contact at xavierho.com Wed Aug 19 05:28:50 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 19 Aug 2009 19:28:50 +1000 Subject: How to create ones own lib In-Reply-To: References: Message-ID: <2d56febf0908190228q72edb74fr43274d9f253cf014@mail.gmail.com> On Wed, Aug 19, 2009 at 7:00 PM, Horst J?ger wrote: > Hi, > > I would like to create my own lib "hotte.py" which I can import like > > > import string,hotte > > . How do I do that? > 1) Have the hotte.py in the same directory of any of your other Python code that imports it, or 2) Put the hotte.py file in the Python import directive, whose location I do not know in Mac.. someone else will know, I'm sure =] All in all, I'm pretty sure you don't have to compile it or anything, but it can be an option. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From bieffe62 at gmail.com Wed Aug 19 05:30:10 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Wed, 19 Aug 2009 02:30:10 -0700 (PDT) Subject: How to create ones own lib References: Message-ID: On 19 Ago, 11:00, Horst J?ger wrote: > Hi, > > I would like to create my own lib "hotte.py" which I can import like > > ? ? ? ? import string,hotte > > . How do I do that? > > I'm working on MacOS 10.5.6 . > > Thanks in advance Just create the file 'hotte.py' and place it somewhere python can find it, that is: - in the same directory of the code using it (which is most probablyt what you want to do ) - in a directory listed in sys.path variable (which you can extend using sys.path.append("full_path_of_my_library_directory") before doing import hotte There are other options, but these should cover your needs. Ciao ----- FB From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 19 05:31:55 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 19 Aug 2009 11:31:55 +0200 Subject: Scope and classes In-Reply-To: References: Message-ID: <4a8bc68b$0$4054$426a74cc@news.free.fr> David a ?crit : (snip) > Out of 'Abc.message' and 'self.message', which is the favoured > convention? It would be very easy to accidentally override > 'self.messages' with an instance attribute! Only use 'Abc.message' if you want to make sure you get the Abc class 'message' attribute - that is, if you want to skip possible overrides in subclasses. As far as I'm concerned, I'd tend to consider this bad style unless it's a very very specific implementation point of an abstract class (in which case it would probably be named '__message' to prevent accidental override) - but YMMV of course. Use 'self.__class__.message' (or 'type(self).message') if you want to make sure you get the class 'message' attribute - that is, if you want to honor possible overrides in subclasses, but not per-instance override. But then - at least in your example code - I'd use a classmethod: class Abc: message = 'Hello World' @classmethod def print_message(cls): print cls.message Now the most common idiom - that is, outside classmethods - is to just use 'self.message'. Someone (even you) might have a very valid reason to override the 'message' attribute on a per-instance basis. FWIW, if you start to worry about possible accidental overrides here, then Python might not be the right language for you - nothing prevents "accidental" overrides of method and even the class (the '__class__' attribute) itself - yes, they are all attributes, and you can dynamically override them !-) From Bill at SynectixLtd.com Wed Aug 19 05:34:11 2009 From: Bill at SynectixLtd.com (Bill Davy) Date: Wed, 19 Aug 2009 10:34:11 +0100 Subject: Read C++ enum in python References: <4a8b3342$0$25403$426a34cc@news.free.fr><4A8B3E2D.7040702@mrabarnett.plus.com> Message-ID: <7f1v8eF2i0es3U1@mid.individual.net> "Mark Tolonen" wrote in message news:mailman.89.1250666942.2854.python-list at python.org... > > "MRAB" wrote in message > news:4A8B3E2D.7040702 at mrabarnett.plus.com... >> Ludo wrote: >>> Hello, >>> >>> I work in a very large project where we have C++ packages and pieces of >>> python code. >>> >>> I've been googleing for days but what I find seems really too >>> complicated for what I want to do. >>> >>> My business is, in python, to read enum definitions provided by the >>> header file of an c++ package. >>> Of course I could open the .h file, read the enum and transcode it by >>> hand into a .py file but the package is regularly updated and thus is >>> the enum. >>> >>> My question is then simple : do we have : >>> - either a simple way in python to read the .h file, retrieve the >>> c++ enum and provide an access to it in my python script >>> - either a simple tool (in a long-term it would be automatically run >>> when the c++ package is compiled) generating from the .h file a .py file >>> containing the python definition of the enums ? >>> >>> Thank you for any suggestion. >> >> Speaking personally, I'd parse the .h file using a regular expression >> (re module) and generate a .py file. Compilers typically have a way of >> letting you run external scripts (eg batch files in Windows or, in this >> case, a Python script) when an application is compiled. > > This is what 3rd party library pyparsing is great for: > > --------begin code---------- > from pyparsing import * > > # sample string with enums and other stuff > sample = ''' > stuff before > > enum hello { > Zero, > One, > Two, > Three, > Five=5, > Six, > Ten=10 > } > > in the middle > > enum blah > { > alpha, > beta, > gamma = 10 , > zeta = 50 > } > > at the end > ''' > > # syntax we don't want to see in the final parse tree > _lcurl = Suppress('{') > _rcurl = Suppress('}') > _equal = Suppress('=') > _comma = Suppress(',') > _enum = Suppress('enum') > > identifier = Word(alphas,alphanums+'_') > integer = Word(nums) > > enumValue = Group(identifier('name') + Optional(_equal + > integer('value'))) > enumList = Group(enumValue + ZeroOrMore(_comma + enumValue)) > enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl > > # find instances of enums ignoring other syntax > for item,start,stop in enum.scanString(sample): > id = 0 > for entry in item.list: > if entry.value != '': > id = int(entry.value) > print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id) > id += 1 > --------------end code------------ > > Output: > HELLO_ZERO = 0 > HELLO_ONE = 1 > HELLO_TWO = 2 > HELLO_THREE = 3 > HELLO_FIVE = 5 > HELLO_SIX = 6 > HELLO_TEN = 10 > BLAH_ALPHA = 0 > BLAH_BETA = 1 > BLAH_GAMMA = 10 > BLAH_ZETA = 50 > > -Mark > > Python and pythoneers are amazing! From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 19 05:39:07 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 19 Aug 2009 11:39:07 +0200 Subject: Identifying a class type - bad practice? In-Reply-To: <520f55a6-38ac-432b-97e7-ec327740645a@o6g2000yqj.googlegroups.com> References: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> <520f55a6-38ac-432b-97e7-ec327740645a@o6g2000yqj.googlegroups.com> Message-ID: <4a8bc83b$0$24683$426a74cc@news.free.fr> James Harris a ?crit : > On 18 Aug, 21:50, Chris Rebert wrote: (snip) >> class node_type_1: >> def walk_tree(self): >> #code >> self.subtree.walk() >> >> class node_type_2: >> def walk_tree(self): >> #code >> self.subtree.walk() >> >> #etc > > Interesting idea. Basic OO stuff, really. I'd say it's even the whole point of OO. (snip) > The tree is for a compiler. Initially the tree is for parsing of > source code. Then it will need to be processed and changed as further > compiler phases are written. I don't know yet whether it will be > easier to modify the tree or to create a new one for each phase. > > So I guess whether I use the idea depends on the commonality of > operations. You may want to have a look at the "composite" and "visitor" design patterns. AST are canonical use case for these patterns. HTH From jeanmichel at sequans.com Wed Aug 19 05:47:36 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 19 Aug 2009 11:47:36 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: <4A8BCA38.5030308@sequans.com> Grant Edwards wrote: > On 2009-08-18, Simon Forman wrote: > > >> Sexism, racism, homophobia, religious intolerance, etc., all >> stem from a fundamental forgetfulness of our Unity in God (as >> I would put it) and this is perhaps the single greatest cause >> of human misery. >> > > You mean the single greatest cause of human misery isn't > Microsoft Windows? > > No, emacs is responsible ! Hail to Vi ! JM From jeanmichel at sequans.com Wed Aug 19 06:05:29 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Wed, 19 Aug 2009 12:05:29 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <50f98a4c0908182043i8a619fdydb9311eadf7cef9@mail.gmail.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <0014c4c0$0$2963$c3e8da3@news.astraweb.com> <50f98a4c0908182043i8a619fdydb9311eadf7cef9@mail.gmail.com> Message-ID: <4A8BCE69.6030508@sequans.com> Simon Forman wrote: > On Tue, Aug 18, 2009 at 8:03 PM, Steven > D'Aprano wrote: > >> On Tue, 18 Aug 2009 17:13:02 -0400, Simon Forman wrote: >> >> >>> Sexism, racism, homophobia, religious intolerance, etc., all stem from a >>> fundamental forgetfulness of our Unity in God (as I would put it) and >>> >> Of the tens of thousands of Gods that people have invented, which is the >> one we're supposed to believe in? I always forget which ones we're >> supposed to dismiss as nonsense, and which one we're not. >> > > Why the heck are you asking me? (I'd say "/you/ are the God you > should believe in.") > Steven, a God... funny :o) No the only God we should surely worship is Guido, our BDFL :bow:. That is not questionable, and those who dare will be hung by the balls. (In order to be fairly cruel we should find an appropriate torture for our ladies, I don't want to be tagged as sexist). JM From nick at craig-wood.com Wed Aug 19 06:29:53 2009 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 19 Aug 2009 05:29:53 -0500 Subject: How to create ones own lib References: Message-ID: Horst J?ger wrote: > I would like to create my own lib "hotte.py" which I can import like > > import string,hotte > > . How do I do that? One of the nice things about python is that you don't need to do anything special to define a library. Just define your classes / functions in hotte.py then use them like import hotte hotte.MyClass() hotte.my_function() See here for the relevant bit of the tutorial http://docs.python.org/tutorial/modules.html -- Nick Craig-Wood -- http://www.craig-wood.com/nick From digisatori at gmail.com Wed Aug 19 06:40:44 2009 From: digisatori at gmail.com (digisatori at gmail.com) Date: Wed, 19 Aug 2009 03:40:44 -0700 (PDT) Subject: expandtabs acts unexpectedly References: <7e598693-c248-4304-bc46-ac79a8a3969b@t11g2000prh.googlegroups.com> Message-ID: <12da5573-4cc0-47ca-837c-b2d75a786eb1@p10g2000prm.googlegroups.com> On Aug 19, 4:16?pm, Peter Brett wrote: > "digisat... at gmail.com" writes: > > Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) > > [GCC 4.3.3] on linux2 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> ' test\ttest'.expandtabs(4) > > ' test ? test' > >>>> 'test \ttest'.expandtabs(4) > > 'test ? ?test' > > > 1st example: expect returning 4 spaces between 'test', 3 spaces > > returned > > 2nd example: expect returning 5 spaces between 'test', 4 spaces > > returned > > > Is it a bug or something, please advice. > > Consider where the 4-space tabstops are relative to those strings: > > ?test ? test > test ? ?test > ^ ? ^ ? ^ > > So no, it's not a bug. > > If you just want to replace the tab characters by spaces, use: > > ? >>> " test\ttest".replace("\t", " ? ?") > ? ' test ? ?test' > ? >>> "test \ttest".replace("\t", " ? ?") > ? 'test ? ? test' > > HTH, > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?Peter > > -- > Peter Brett > Remote Sensing Research Group > Surrey Space Centre You corrected me for the understanding of tab stop. Great explanation. Thank you so much. From tjreedy at udel.edu Wed Aug 19 06:48:13 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Aug 2009 19:48:13 +0900 Subject: How to create functors? In-Reply-To: References: Message-ID: Robert Dailey wrote: > I'm using Python 2.6. And using the legacy syntax in the lambda does > not work either. I want to avoid using a def if possible. Thanks. In Python, writing name = lambda arg: expr instead of def name(arg): return expr is all negative and no positive and should be avoided. Your experience illustrates one reason why. tjr From tjreedy at udel.edu Wed Aug 19 06:52:14 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 19 Aug 2009 19:52:14 +0900 Subject: Raw Strings with Variables In-Reply-To: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> References: <0d176354-bb6c-4da5-b9b8-b444f6a946e6@a39g2000pre.googlegroups.com> Message-ID: WilsonOfCanada wrote: > Hellos, > > I know that if you have: > > happy = r"C:\moo" > print happy > > you get C:\moo instead of C:\\moo > > The thing is that I want to do this a variable instead. > > ex. testline = fileName.readline() > rawtestline = r testline Python does not have 'raw strings'. It only has 'raw string literals', which is to say, string literals with 'r' prepended to signal less processing (cooking) of the literal in the process of turning it into a string object. tjr From sleepy at cabbage.co.uk Wed Aug 19 07:06:41 2009 From: sleepy at cabbage.co.uk (Sleepy Cabbage) Date: Wed, 19 Aug 2009 11:06:41 GMT Subject: urlopen errors in script References: <3Gxim.148238$XK2.30441@newsfe15.ams2> Message-ID: <51Rim.226342$e11.13364@newsfe14.ams2> On Tue, 18 Aug 2009 13:05:03 +0000, Sleepy Cabbage wrote: > Thanks for the time you've spent anyway Peter. I have superkaramba > installed and the rest of the script is running fine, it's only when I > put the urlopen part in that it comes back with errors. The quotes are > just to make it readable on here as my first attempt at posting muted > the text. This has been solved by upgrading to kde 4.3 From tino at wildenhain.de Wed Aug 19 07:09:28 2009 From: tino at wildenhain.de (Tino Wildenhain) Date: Wed, 19 Aug 2009 13:09:28 +0200 Subject: reading a text file In-Reply-To: <4a8bba7d$0$40004$4fafbaef@reader3.news.tin.it> References: <4a8bba7d$0$40004$4fafbaef@reader3.news.tin.it> Message-ID: <4A8BDD68.4050108@wildenhain.de> superpollo wrote: > hi clp > > what's the difference between: > > while True: > input_line = sys.stdin.readline() > if input_line: > sys.stdout.write(input_line.upper()) > else: > break > > and: > > > while True: > try: > sys.stdout.write(sys.stdin.next().upper()) > except StopIteration: > break > More useless code, under the hood its working similar. But why not use it in the way intended? for input_line in sys.stdin: sys.stdout.write(input_line.upper()) ? Regards Tino -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/x-pkcs7-signature Size: 3241 bytes Desc: S/MIME Cryptographic Signature URL: From nuno.hespanhol at gmail.com Wed Aug 19 07:55:02 2009 From: nuno.hespanhol at gmail.com (Nuno Santos) Date: Wed, 19 Aug 2009 12:55:02 +0100 Subject: Help with libxml2dom Message-ID: <4A8BE816.9050901@gmail.com> I have just started using libxml2dom to read html files and I have some questions I hope you guys can answer me. The page I am working on (teste.htm): Title
8/15/2009
>>> import libxml2dom >>> foo = open('teste.htm', 'r') >>> str1 = foo.read() >>> doc = libxml2dom.parseString(str1, html=1) >>> html = doc.firstChild >>> html.nodeName u'html' >>> head = html.firstChild >>> head.nodeName u'head' >>> title = head.firstChild >>> title.nodeName u'title' >>> body = head.nextSibling >>> body.nodeName u'body' >>> table = body.firstChild >>> table.nodeName u'text' #?! Why!? Shouldn't it be a table? (1) >>> table = body.firstChild.nextSibling #why this works? is there a text element hidden? (2) >>> table.nodeName u'table' >>> tr = table.firstChild >>> tr.nodeName u'tr' >>> td = tr.firstChild >>> td.nodeName u'td' >>> font = td.firstChild >>> font.nodeName u'text' # (1) >>> font = td.firstChild.nextSibling # (2) >>> font.nodeName u'font' >>> a = font.firstChild >>> a.nodeName u'text' #(1) >>> a = font.firstChild.nextSibling #(2) >>> a.nodeName u'a' It seems like sometimes there are some text elements 'hidden'. This is probably a standard in DOM I simply am not familiar with this and I would very much appreciate if anyone had the kindness to explain me this. Thanks. From kannan4k at gmail.com Wed Aug 19 08:09:16 2009 From: kannan4k at gmail.com (Kannan) Date: Wed, 19 Aug 2009 17:39:16 +0530 Subject: About Python Symbian 60 Message-ID: Hi friends.... I want a Python SDK like Netbeans to work with the Symbian 60 python. I don't have the Symbian 60 mobile.I create some Apps for S60 Platform.To execute that i want this.... Help me.. With regards, Kannan. R. P, -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Wed Aug 19 08:16:17 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 05:16:17 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> Message-ID: On 18 Aug, 11:19, Robert Dailey wrote: > I'm looking for a way to parallelize my python script without using > typical threading primitives. For example, C++ has pthreads and TBB to > break things into "tasks". In C++, parallelization without "typical threading primitives" usually means one of three things: - OpenMP pragmas - the posix function fork(), unless you are using Windows - MPI In Python, you find the function os.fork and wrappers for MPI, and they are used as in C++. With os.fork, I like to use a context manager, putting the calls to fork in __enter__ and the calls to sys.exit in __exit__. Then I can just write code like this: with parallel(): # parallel block here You can also program in the same style as OpenMP using closures. Just wrap whatever loop or block you want to execute in parallel in a closure. It requires minimal edition of the serial code. Instead of def foobar(): for i in iterable: #whatever you can add a closure (internal function) and do this: def foobar(): def section(): # add a closure for i in sheduled(iterable): # balance load #whatever parallel(section) # spawn off threads Programs written in C++ are much more difficult to parallelize with threads because C++ do not have closures. This is why pragma-based parallelization (OpenMP) was invented: #pragma omp parallel for private(i) for (i=0; i Hi, Is there any package to edit the existing excel cell data using python or to create excel charts using python.... please help. Thanks, From davea at ieee.org Wed Aug 19 08:27:43 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 19 Aug 2009 08:27:43 -0400 Subject: Parallelization in Python 2.6 In-Reply-To: <200908190931.18297.hendrik@microcorp.co.za> References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> <200908190931.18297.hendrik@microcorp.co.za> Message-ID: <4A8BEFBF.4010905@ieee.org> Hendrik van Rooyen wrote: > On Tuesday 18 August 2009 22:45:38 Robert Dailey wrote: > > >> Really, all I'm trying to do is the most trivial type of >> parallelization. Take two functions, execute them in parallel. This >> type of parallelization is called "embarrassingly parallel", and is >> the simplest form. There are no dependencies between the two >> functions. They do requires read-only access to shared data, though. >> And if they are being spawned as sub-processes this could cause >> problems, unless the multiprocess module creates pipelines or other >> means to handle this situation. >> > > Just use thread then and thread.start_new_thread. > It just works. > > - Hendrik > > But if you do it that way, it's slower than sequential. And if you have a multi-core processor, or two processors, or ... then it gets much slower yet, and slows down other tasks as well. With the current GIL implementation, for two CPU-bound tasks, you either do them sequentially, or make a separate process. Now, you can share data between separate processes, and if the data is truly going to be readonly, you shouldn't have any locking issues. Naturally you should do your own timings. Maybe your particular CPU and OS will have different results. DaveA From sturlamolden at yahoo.no Wed Aug 19 08:31:37 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 05:31:37 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> Message-ID: <250fb031-d955-45a7-8089-a3973f9af307@g10g2000yqh.googlegroups.com> On 18 Aug, 13:45, Robert Dailey wrote: > Really, all I'm trying to do is the most trivial type of > parallelization. Take two functions, execute them in parallel. This > type of parallelization is called "embarrassingly parallel", and is > the simplest form. There are no dependencies between the two > functions. If you are using Linux or Mac, just call os.fork for this. You should also know that you function "create_task" is simply from threading import Thread def create_task(task): Thread(target=task).start() If your task releases the GIL, this will work fine. > They do requires read-only access to shared data, though. > And if they are being spawned as sub-processes this could cause > problems, unless the multiprocess module creates pipelines or other > means to handle this situation. With forking or multiprocessing, you have to use IPC. That is, usually pipes, unix sockets / named pipes, or shared memory. Multiprocessing helps you with this. Multiprocessing also has a convinient Queue object for serialised read/write access to a pipe. You can also create shared memory with mmap.mmap, using fd 0 with Windows or -1 with Linux. From hendrik at microcorp.co.za Wed Aug 19 08:34:17 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 19 Aug 2009 14:34:17 +0200 Subject: Parallelization in Python 2.6 In-Reply-To: <7xbpmcnruy.fsf@ruckus.brouhaha.com> References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <7xbpmcnruy.fsf@ruckus.brouhaha.com> Message-ID: <200908191434.17399.hendrik@microcorp.co.za> On Wednesday 19 August 2009 10:13:41 Paul Rubin wrote: > Hendrik van Rooyen writes: > > Just use thread then and thread.start_new_thread. > > It just works. > > The GIL doesn't apply to threads made like that?! The GIL does apply - I was talking nonsense again. Misread the OP's intention. - Hendrik From tim.wintle at teamrubber.com Wed Aug 19 08:36:40 2009 From: tim.wintle at teamrubber.com (Tim Wintle) Date: Wed, 19 Aug 2009 13:36:40 +0100 Subject: Excel edit using python In-Reply-To: <405ea65b-434b-4b93-914f-c0ddbf92077f@2g2000prl.googlegroups.com> References: <405ea65b-434b-4b93-914f-c0ddbf92077f@2g2000prl.googlegroups.com> Message-ID: <1250685400.4676.8.camel@tim-laptop> On Wed, 2009-08-19 at 05:25 -0700, suman wrote: > > Is there any package to edit the existing excel cell data using python > or > to create excel charts using python.... Chris, Chris, where are you? http://www.python-excel.org/ Site provided by Chris Withers: http://mail.python.org/pipermail/python-list/2009-June/716845.html Tim Wintle From sturlamolden at yahoo.no Wed Aug 19 08:39:15 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 05:39:15 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> <200908190931.18297.hendrik@microcorp.co.za> Message-ID: On 19 Aug, 05:27, Dave Angel wrote: > But if you do it that way, it's slower than sequential. ?And if you have > a multi-core processor, or two processors, or ... ? then it gets much > slower yet, and slows down other tasks as well. > > With the current GIL implementation, for two CPU-bound tasks, you either > do them sequentially, or make a separate process. For CPU bound tasks, one should put the bottleneck in C/Fortran/Cython and release the GIL. There is a speed penalty of 200x from using Python instead of C. With a quadcore processor you can gain less than 4x speed-up by parallelizing. If you really care enough about speed to write parallel code, the first thing you should do is migrate the bottleneck to C. From martin.hellwig at dcuktec.org Wed Aug 19 08:40:59 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 19 Aug 2009 13:40:59 +0100 Subject: Parallelization in Python 2.6 In-Reply-To: References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> Message-ID: sturlamolden wrote: > The human brain is bad at detecting > computational bottlenecks though. So it almost always pays off to > write everything in Python first, and use the profiler to locate the > worst offenders. +1 QOTW -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From deets at nospam.web.de Wed Aug 19 08:45:13 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 14:45:13 +0200 Subject: Help with libxml2dom References: Message-ID: <7f2aepF2i8bttU1@mid.uni-berlin.de> Nuno Santos wrote: > I have just started using libxml2dom to read html files and I have some > questions I hope you guys can answer me. > > The page I am working on (teste.htm): > > > > Title > > > > > > > > >
> > > > 8/15/2009 >
> > > > >>> import libxml2dom > >>> foo = open('teste.htm', 'r') > >>> str1 = foo.read() > >>> doc = libxml2dom.parseString(str1, html=1) > >>> html = doc.firstChild > >>> html.nodeName > u'html' > >>> head = html.firstChild > >>> head.nodeName > u'head' > >>> title = head.firstChild > >>> title.nodeName > u'title' > >>> body = head.nextSibling > >>> body.nodeName > u'body' > >>> table = body.firstChild > >>> table.nodeName > u'text' #?! Why!? Shouldn't it be a table? (1) > >>> table = body.firstChild.nextSibling #why this works? is there a > text element hidden? (2) > >>> table.nodeName > u'table' > >>> tr = table.firstChild > >>> tr.nodeName > u'tr' > >>> td = tr.firstChild > >>> td.nodeName > u'td' > >>> font = td.firstChild > >>> font.nodeName > u'text' # (1) > >>> font = td.firstChild.nextSibling # (2) > >>> font.nodeName > u'font' > >>> a = font.firstChild > >>> a.nodeName > u'text' #(1) > >>> a = font.firstChild.nextSibling #(2) > >>> a.nodeName > u'a' > > > It seems like sometimes there are some text elements 'hidden'. This is > probably a standard in DOM I simply am not familiar with this and I > would very much appreciate if anyone had the kindness to explain me this. Without a schema or something similar, a parser can't tell if whitespace is significant or not. So if you have you will have not 2, but 4 nodes - root, text containing a newline + 2 spaces, child, and again a text with a newline. You have to skip over those that you are not interested in, or use a different XML-library such as ElementTree (e.g. in the form of lxml) that has a different approach about text-nodes. Diez From piet at cs.uu.nl Wed Aug 19 08:51:48 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 19 Aug 2009 14:51:48 +0200 Subject: recording input from USB port and write to text file References: Message-ID: >>>>> Allan (A) wrote: >A> Hi! I'm fairly new to Python. I understand the basics basics but I'm >A> been trying to write a simple python code that will let me read input >A> data (such as mouse movement) from my USB port and write it in a text >A> file and I am so lost. Can anyone help or direct me to some >A> resources? Thank you! You could try http://sourceforge.net/projects/pyusb/ -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From sturlamolden at yahoo.no Wed Aug 19 08:56:21 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 05:56:21 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> Message-ID: <4575acc6-6045-4b5e-9a60-6dbde6b6d5db@k19g2000yqn.googlegroups.com> On 19 Aug, 05:16, sturlamolden wrote: > You should know about the GIL. It prevents multiple threads form using > the Python interpreter simultaneously. For parallel computing, this is > a blessing and a curse. Only C extensions can release the GIL; this > includes I/0 routines in Python's standard library. If the GIL is not > released, the C library call are guaranteed to be thread-safe. > However, the Python interpreter will be blocked while waiting for the > library call to return. If the GIL is released, parallelization works > as expected; you can also utilise multi-core CPUs (it is a common > misbelief that Python cannot do this). Since I am at it, this is how the GIL can be released: - Many functions in Python's standard library, particularly all blocking i/o functions, release the GIL. - In C or C++ extensions, use the macros Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS. - With ctypes, functions called from a cdll release the GIL, whereas functions called from a pydll do not. - In f2py, declaring a Fortran function threadsafe in a .pyf file or cf2py comment releases the GIL. - In Cython or Pyrex, use a "with nogil:" block to execute code without holding the GIL. Regards, Sturla Molden From piet at cs.uu.nl Wed Aug 19 08:59:43 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 19 Aug 2009 14:59:43 +0200 Subject: Subclass dynamically References: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com> Message-ID: >>>>> Robert Dailey (RD) wrote: >RD> Hey, >RD> I have a class that I want to have a different base class depending on >RD> a parameter that I pass to its __init__method. For example >RD> (pseudocode): >RD> class MyDerived( self.base ): >RD> def __init__( self, base ): >RD> self.base = base >RD> Something like that... and then I would do this: >RD> foo = MyDerived( MyBase() ) What do you want? As you write it now foo would be an instance of MyDerived, but you say you want to have a class with a different base class... So does this mean that foo should become that class or that foo should become an instance of a new anonymous class that has a specified base class? And on the other hand is MyBase the required base class. But you pass an instance of MyBase, not MyBase itself. As you have it above MyBase() should be a class, therefore MyBase should be a metaclass. Or is that not what you want? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From deets at nospam.web.de Wed Aug 19 09:12:55 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 15:12:55 +0200 Subject: recording input from USB port and write to text file References: Message-ID: <7f2c2nF2i8qovU1@mid.uni-berlin.de> Piet van Oostrum wrote: >>>>>> Allan (A) wrote: > >>A> Hi! I'm fairly new to Python. I understand the basics basics but I'm >>A> been trying to write a simple python code that will let me read input >>A> data (such as mouse movement) from my USB port and write it in a text >>A> file and I am so lost. Can anyone help or direct me to some >>A> resources? Thank you! > > You could try http://sourceforge.net/projects/pyusb/ As I said - this is more complicated as it appears. HID-devices will be captured by the OS and can't be accessed by libusb then (with good reason - otherwise writing a keylogger is something not even kernel-space is needed anymore) Diez From sturlamolden at yahoo.no Wed Aug 19 09:14:01 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 06:14:01 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> <200908190931.18297.hendrik@microcorp.co.za> Message-ID: On 19 Aug, 05:27, Dave Angel wrote: > With the current GIL implementation, for two CPU-bound tasks, you either > do them sequentially, or make a separate process. I'd also like to add that most compute-bound code should be delegated to specialized C libraries, many of which are prewritten. For example, FFTW, Intel MKL, ATLAS, LAPACK, NAG. When you do this, the GIL has no consequence unless it is kept locked. So even for scientific programs, writing parallel compute-bound code mostly involves calling into a C or Fortran library with the GIL released. I have yet to see compute- bound code that could not be easily migrated to C or Fortran, either using existing libraries (the common case) or specialised code. From sturlamolden at yahoo.no Wed Aug 19 09:18:16 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 06:18:16 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <7xbpmcnruy.fsf@ruckus.brouhaha.com> Message-ID: On 19 Aug, 05:34, Hendrik van Rooyen wrote: > The GIL does apply - I was talking nonsense again. ?Misread the OP's > intention. It depends on what the OP's functions "doStuff1" and "doStuff2" actually do. If they release the GIL (e.g. make I/O calls) it does not apply. The GIL only serialize access to the interpreter. From sturlamolden at yahoo.no Wed Aug 19 09:31:20 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 06:31:20 -0700 (PDT) Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <4a8af5ce$0$30224$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <9d96a617-75b2-413f-bb8a-81d51e42197c@f37g2000yqn.googlegroups.com> On 18 Aug, 11:41, Stefan Behnel wrote: > I think the canonical answer is to use the threading module or (preferably) > the multiprocessing module, which is new in Py2.6. > > http://docs.python.org/library/threading.htmlhttp://docs.python.org/library/multiprocessing.html > > Both share a (mostly) common interface and are simple enough to use. They > are pretty close to the above interface already. There is a big difference between them, which is that multiprocessing do not work with closures. This means that the threading module is simpler to use than multiprocessing if you want to parallelize serial code. You just wrap a closure around whatever block of code you want to run in a thread. For the same reason, programming with OpenMP is easier than using pthreads directly in C/C++. C does not have closures, which is the raison d'etre for OpenMP. Multiprocessing has the same limitation as abstraction for parallel programming as pthreads in C. Python's threading module do not, but the GIL can be a limitation. From ndbecker2 at gmail.com Wed Aug 19 09:41:58 2009 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 19 Aug 2009 09:41:58 -0400 Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <4a8af5ce$0$30224$9b4e6d93@newsspool1.arcor-online.net> <9d96a617-75b2-413f-bb8a-81d51e42197c@f37g2000yqn.googlegroups.com> Message-ID: sturlamolden wrote: > On 18 Aug, 11:41, Stefan Behnel wrote: > >> I think the canonical answer is to use the threading module or >> (preferably) the multiprocessing module, which is new in Py2.6. >> >> http://docs.python.org/library/threading.htmlhttp://docs.python.org/library/multiprocessing.html >> >> Both share a (mostly) common interface and are simple enough to use. They >> are pretty close to the above interface already. > > There is a big difference between them, which is that multiprocessing > do not work with closures. This means that the threading module is > simpler to use than multiprocessing if you want to parallelize serial > code. You just wrap a closure around whatever block of code you want > to run in a thread. Do you have an example of this technique? From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 19 09:43:38 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 19 Aug 2009 15:43:38 +0200 Subject: Subclass dynamically In-Reply-To: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com> References: <69df1b9a-fbc2-4a04-bc43-713eeee23e1a@g23g2000vbr.googlegroups.com> Message-ID: <4a8c0189$0$9983$426a34cc@news.free.fr> Robert Dailey a ?crit : > Hey, > > I have a class that I want to have a different base class depending on > a parameter that I pass to its __init__method. For example > (pseudocode): > > class MyDerived( self.base ): > def __init__( self, base ): > self.base = base > > > Something like that... and then I would do this: > > foo = MyDerived( MyBase() ) What is your real use case ? I mean, what problem are you actually trying to solve this way ? From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 19 09:48:48 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 19 Aug 2009 15:48:48 +0200 Subject: Code formatting question: conditional expression In-Reply-To: References: Message-ID: <4a8c02bf$0$716$426a74cc@news.free.fr> Richard Brodie a ?crit : > "John Posner" wrote in message > news:mailman.26.1250604346.2854.python-list at python.org... > >> if total > P.BASE: >> excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) >> else: >> excessblk = None > > I wonder if it is appropriate to replace the None sentinel with one that is an instance > of Block() e.g. > > size = total - P.BASE > excessblk = Block(size, srccol, carry_button_suppress=True, empty_block=(size <= 0) ) In which case the last param is possibly redundant - the Block object knows its size, so it might be able to know by itself if it's empty. NB : please notice the 'possibly' and 'might' cautions !-) From mczwhiners at yahoo.com Wed Aug 19 09:50:44 2009 From: mczwhiners at yahoo.com (Smeagol) Date: Wed, 19 Aug 2009 06:50:44 -0700 (PDT) Subject: NOOB: Developing using python on two different computers Message-ID: <610dc365-476f-4c5d-a307-b7b4141244ba@q40g2000prh.googlegroups.com> Hi there, Occasionally I have to develop on two different computers, and I was wondering if there was a way to copy the python "environment" from one to the other? Access to the data is trivial (networked database) but various packages etc exist on one computer, and I want to ensure I have everything package-wise on the other. Both are "windows" machines (native windows box and a Macbook with VMWare running XP)... Is it as simple as copying the Python directory, or is there a script I can run that will tell me what packages are installed on the native windows box and then I can use easy_install to update the VM partition on the Macbook? Much obliged for any help. From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 19 09:56:08 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 19 Aug 2009 15:56:08 +0200 Subject: How to create functors? In-Reply-To: References: Message-ID: <4a8c0478$0$2752$426a74cc@news.free.fr> Terry Reedy a ?crit : > Robert Dailey wrote: > >> I'm using Python 2.6. And using the legacy syntax in the lambda does >> not work either. I want to avoid using a def if possible. Thanks. > > In Python, writing > > name = lambda arg: expr > > instead of > > def name(arg): return expr > > is all negative and no positive and should be avoided. Except that def is a statement, and as such can't be used as a named params when calling a function expecting a callback, ie: vroom = some_dead('parrot', name=lambda arg: exp) (notice the 'name = lambda arg: exp' ?-) Ok, nitpicking. Me --->[] From sjmachin at lexicon.net Wed Aug 19 10:06:28 2009 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Aug 2009 07:06:28 -0700 (PDT) Subject: difference between 2 arrays References: <4a8bbe36$0$12654$ba4acef3@news.orange.fr> Message-ID: On Aug 19, 6:56?pm, "Michel Claveau - MVP" wrote: > See the module "sets" See especially the notice at the front of the current sets doc which says "deprecated since 2.6" and the comparison down the end which explains why the built-in set() and frozenset() are better than the sets module. Starting now to use the sets module is not a good idea unless the OP is stuck on using Python 2.3 . From paul at boddie.org.uk Wed Aug 19 10:10:08 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 19 Aug 2009 07:10:08 -0700 (PDT) Subject: Help with libxml2dom References: Message-ID: <55183f22-2687-4426-b38d-054743b9f150@h21g2000yqa.googlegroups.com> On 19 Aug, 13:55, Nuno Santos wrote: > I have just started using libxml2dom to read html files and I have some > questions I hope you guys can answer me. [...] > ?>>> table = body.firstChild > ?>>> table.nodeName > u'text' #?! Why!? Shouldn't it be a table? (1) You answer this yourself just below. > ?>>> table = body.firstChild.nextSibling #why this works? is there a > text element hidden? (2) > ?>>> table.nodeName > u'table' Yes, in the DOM, the child nodes of elements include text nodes, and even though one might regard the whitespace before the first child element and that appearing after the last child element as unimportant, the DOM keeps it around in case it really is important. [...] > It seems like sometimes there are some text elements 'hidden'. This is > probably a standard in DOM I simply am not familiar with this and I > would very much appreciate if anyone had the kindness to explain me this. Well, the nodes are actually there: they're whitespace used to provide the indentation in your example. I recommend using XPath to get actual elements: table = body.xpath("*")[0] # get child elements and then select the first Although people make a big "song and dance" about the DOM being a nasty API, it's quite bearable if you use it together with XPath queries. Paul From invalid at invalid Wed Aug 19 10:14:11 2009 From: invalid at invalid (Grant Edwards) Date: Wed, 19 Aug 2009 09:14:11 -0500 Subject: Parallelization in Python 2.6 References: <9d9e7278-d855-4066-b090-46d5060dc051@j21g2000yqe.googlegroups.com> <17baaedc-2eeb-4ede-b416-afed3c2b0fc8@i18g2000pro.googlegroups.com> <54899d05-8e9b-4b91-b79d-9839cddfe2d7@o15g2000yqm.googlegroups.com> <4a8b9ef4$0$31865$9b4e6d93@newsspool3.arcor-online.net> Message-ID: On 2009-08-19, Stefan Behnel wrote: > Dennis Lee Bieber wrote: >> If they are number crunchers (CPU-bound) and don't make use of >> binary extension libraries that release the GIL (for the most common >> Python implementation), they'll run faster being called in sequence >> since you won't have the overhead of task switching. > > ... unless, obviously, the hardware is somewhat up to date > (which is not that uncommon for number crunching environments) > and can execute more than one thing at once. Even with multiple processors, it'll still be faster to call them sequentially in a single thread than run them sequentially in multiple threads with the GIL serializing them. -- Grant Edwards grante Yow! Gibble, Gobble, we at ACCEPT YOU ... visi.com From baaluaanand at gmail.com Wed Aug 19 10:20:05 2009 From: baaluaanand at gmail.com (baalu aanand) Date: Wed, 19 Aug 2009 07:20:05 -0700 (PDT) Subject: difference between 2 arrays References: Message-ID: <9a598f0b-f694-4011-b567-1d089f4062e7@v36g2000yqv.googlegroups.com> On Aug 19, 1:48?pm, Pierre wrote: > Hello, > > I would like to know how to find the difference (set operation) > between 2 arrays : > > a = array([1,2, 3,2,5,2]) > b = array([1,2]) > I want a - b = [3,5] > > Well, the equivalence of setdiff in matlab... > > I thought a.difference(b) could work, but no : AttributeError: > 'numpy.ndarray' object has no attribute 'difference' > > Thanks ! Hi, Here I have given my logic, check whether it helps for you a = [1,2, 3,2,5,2] b = [1,2] j = 0 dif = [] for i in range(len(a)) : if a[i] not in b: dif.append(a[i]) j += 1 print dif[k] Thanks Baalu From baaluaanand at gmail.com Wed Aug 19 10:25:55 2009 From: baaluaanand at gmail.com (baalu aanand) Date: Wed, 19 Aug 2009 07:25:55 -0700 (PDT) Subject: difference between 2 arrays References: Message-ID: <1da8e2d5-7a43-4b8c-b447-07f4f8e2f249@z24g2000yqb.googlegroups.com> On Aug 19, 1:48?pm, Pierre wrote: > Hello, > > I would like to know how to find the difference (set operation) > between 2 arrays : > > a = array([1,2, 3,2,5,2]) > b = array([1,2]) > I want a - b = [3,5] > > Well, the equivalence of setdiff in matlab... > > I thought a.difference(b) could work, but no : AttributeError: > 'numpy.ndarray' object has no attribute 'difference' > > Thanks ! Hi, Here I have given my logic, check whether it helps for you a = [1,2, 3,2,5,2] b = [1,2] j = 0 dif = [] for i in range(len(a)) : if a[i] not in b: dif.append(a[i]) j += 1 print dif Thanks Baalu From mhuening at zedat.fu-berlin.de Wed Aug 19 10:44:48 2009 From: mhuening at zedat.fu-berlin.de (Matthias Huening) Date: Wed, 19 Aug 2009 16:44:48 +0200 Subject: difference between 2 arrays In-Reply-To: References: Message-ID: <7f2heuF2hnhj3U1@mid.uni-berlin.de> Pierre (19.08.2009 10:48): > Hello, > > I would like to know how to find the difference (set operation) > between 2 arrays : > > a = array([1,2, 3,2,5,2]) > b = array([1,2]) > I want a - b = [3,5] > What about set()? >>> a = set([1,2, 3,2,5,2]) >>> b = set([1,2]) >>> a.difference(b) set([3, 5]) Matthias From jhnhndly at aol.com Wed Aug 19 10:52:56 2009 From: jhnhndly at aol.com (La Vie Spirituelle) Date: Wed, 19 Aug 2009 16:52:56 +0200 Subject: New message Message-ID: Test -------------- next part -------------- An HTML attachment was scrubbed... URL: From drobinow at gmail.com Wed Aug 19 11:15:07 2009 From: drobinow at gmail.com (David Robinow) Date: Wed, 19 Aug 2009 11:15:07 -0400 Subject: difference between 2 arrays In-Reply-To: References: Message-ID: <4eb0089f0908190815h867d13ci23494b54d1e06947@mail.gmail.com> On Wed, Aug 19, 2009 at 4:48 AM, Pierre wrote: > Hello, > > I would like to know how to find the difference (set operation) > between 2 arrays : > > a = array([1,2, 3,2,5,2]) > b = array([1,2]) > I want a - b = [3,5] > > Well, the equivalence of setdiff in matlab... > > I thought a.difference(b) could work, but no : AttributeError: > 'numpy.ndarray' object has no attribute 'difference' > > Thanks ! > -- > http://mail.python.org/mailman/listinfo/python-list > import numpy a = numpy.array([1,2,3,2,5,2]) b = numpy.array([1,2]) c = list(set(a)-set(b)) # or c = numpy.array(list(set(a)-set(b))) if you want to continue w/ arrays print c From olivier.anospamrnospamnnospamanospamenospamz at affaires.net Wed Aug 19 11:37:56 2009 From: olivier.anospamrnospamnnospamanospamenospamz at affaires.net (Ludo) Date: Wed, 19 Aug 2009 17:37:56 +0200 Subject: Read C++ enum in python In-Reply-To: <4uOim.12753$ze1.6481@news-server.bigpond.net.au> References: <4a8b3342$0$25403$426a34cc@news.free.fr> <4uOim.12753$ze1.6481@news-server.bigpond.net.au> Message-ID: <4a8c1c55$0$420$426a74cc@news.free.fr> Neil Hodgson a ?crit : > > For some headers I tried it didn't work until the .* was changed to a > non-greedy .*? to avoid removing from the start of the first comment to > the end of the last comment. > > file_data = ' '.join(re.split(r'\/\*.*?\*\/', file_data)) Thank you ! I adopt it ! Cheers. From gunterhenriksen at gmail.com Wed Aug 19 11:43:55 2009 From: gunterhenriksen at gmail.com (Gunter Henriksen) Date: Wed, 19 Aug 2009 08:43:55 -0700 Subject: warnings.warn vs logging.warning Message-ID: When I want to issue a warning, I am uncertain about the distinction between warnings.warn() and logging.warning(). My naive thought is to presume "warning" means the same thing in both cases, and so if I call logging.warning(), it should take care of making sure something equivalent to my calling warnings.warn() will happen... more than just having a message go to wherever a message to warnings.warn() would go. If I want to utilize the capabilities of both mechanisms (like having an exception raised), should I call both functions? From deets at nospam.web.de Wed Aug 19 11:52:29 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 17:52:29 +0200 Subject: difference between 2 arrays References: <9a598f0b-f694-4011-b567-1d089f4062e7@v36g2000yqv.googlegroups.com> Message-ID: <7f2ldtF2gd9ttU1@mid.uni-berlin.de> baalu aanand wrote: > On Aug 19, 1:48?pm, Pierre wrote: >> Hello, >> >> I would like to know how to find the difference (set operation) >> between 2 arrays : >> >> a = array([1,2, 3,2,5,2]) >> b = array([1,2]) >> I want a - b = [3,5] >> >> Well, the equivalence of setdiff in matlab... >> >> I thought a.difference(b) could work, but no : AttributeError: >> 'numpy.ndarray' object has no attribute 'difference' >> >> Thanks ! > > > > Hi, > > Here I have given my logic, check whether it helps for you > > a = [1,2, 3,2,5,2] > b = [1,2] > j = 0 > dif = [] > for i in range(len(a)) : > if a[i] not in b: > dif.append(a[i]) > j += 1 > > print dif[k] EEEK, quadratic behavior!! Diez From robert.kern at gmail.com Wed Aug 19 12:17:16 2009 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 19 Aug 2009 09:17:16 -0700 Subject: difference between 2 arrays In-Reply-To: References: Message-ID: On 2009-08-19 01:48 AM, Pierre wrote: > Hello, > > I would like to know how to find the difference (set operation) > between 2 arrays : > > a = array([1,2, 3,2,5,2]) > b = array([1,2]) > I want a - b = [3,5] > > Well, the equivalence of setdiff in matlab... You will want to ask numpy questions on the numpy mailing list. http://www.scipy.org/Mailing_Lists Using set() is frequently a good option, but for large arrays, you will want to avoid the overhead of converting to and from sets and use numpy.setdiff1d(a, b): In [2]: a = array([1,2, 3,2,5,2]) In [3]: b = array([1,2]) In [4]: numpy.setdiff1d(a, b) Out[4]: array([3, 5]) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From markscottwright at gmail.com Wed Aug 19 12:49:07 2009 From: markscottwright at gmail.com (markscottwright) Date: Wed, 19 Aug 2009 09:49:07 -0700 (PDT) Subject: How do I convert an iterator over bytes into a str? References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> Message-ID: <2c212222-0dac-4bd3-8130-5bd302d12dd5@c2g2000yqi.googlegroups.com> On Aug 18, 6:52?pm, "Jan Kaliszewski" wrote: > 19-08-2009 o 00:24:20 markscottwright wrote: > > > What's the correct way to turn an iterator over bytes into a string? > > This works, but, ewww: > > ? ? In [8]: "".join(iter("four score and seven years ago")) > > ? ? Out[8]: 'four score and seven years ago' > > But it is the correct way (and even recommended over s=s+t or s+=t, when > applicable > -- see: ?http://docs.python.org/library/stdtypes.html#sequence-types-str-unico...). > > Cheers, > *j > > -- > Jan Kaliszewski (zuo) Thanks Jan (and all other responders). I suppose I shouldn't be surprised - it's a known wart (http://wiki.python.org/moin/ PythonWarts), but it just looks so darn wrong. It is, as you point out, much faster than "better looking" alternatives, though - http://www.skymind.com/~ocrow/python_string/ From aahz at pythoncraft.com Wed Aug 19 13:08:56 2009 From: aahz at pythoncraft.com (Aahz) Date: 19 Aug 2009 10:08:56 -0700 Subject: Need cleanup advice for multiline string References: <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <4A89CEA2.10400@mrabarnett.plus.com> Message-ID: In article , Jean-Michel Pichavant wrote: >MRAB wrote: >> Carl Banks wrote: >>> On Aug 17, 10:03 am, Jean-Michel Pichavant >>> wrote: >>>> >>>> I'm no English native, but I already heard women/men referring to a >>>> group as "guys", no matter that group gender configuration. It's even >>>> used for group composed exclusively of women. Moreover it looks like a >>>> *very* friendly form, so there is really nothing to worry about it. >>> >>> I like how being very friendly means calling people after a guy who >>> tried to blow up the English Parliament. >> >> Guy Fawkes adopted the name Guido while fighting for the Spanish in the >> Low Countries: >> >> http://en.wikipedia.org/wiki/Guy_Fawkes > >I didn't get Carl's reference. The only thing I know about blowing the >parliament is from the movie V for Vendetta (no comment please !). You should read the original comic book, it's much more interesting (and clearly mentions the Guy Fawkes connection). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From sturlamolden at yahoo.no Wed Aug 19 13:09:46 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 19 Aug 2009 10:09:46 -0700 (PDT) Subject: difference between 2 arrays References: Message-ID: <7470d887-6c9c-4013-8dc5-ffa7ef344f3f@j21g2000yqe.googlegroups.com> On 19 Aug, 01:48, Pierre wrote: > Well, the equivalence of setdiff in matlab... That would be numpy.setdiff1d. From sajmikins at gmail.com Wed Aug 19 13:35:59 2009 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 19 Aug 2009 10:35:59 -0700 (PDT) Subject: recording input from USB port and write to text file References: Message-ID: On Aug 18, 7:33?pm, Allan wrote: > Hi! I'm fairly new to Python. ?I understand the basics basics but I'm > been trying to write a simple python code that will let me read input > data (such as mouse movement) from my USB port and write it in a text > file and I am so lost. ?Can anyone help or direct me to some > resources? ?Thank you! This isn't exactly what you were looking for, but maybe it will give you some ideas: from Tkinter import * def printMotionEvents(event): print "mouse coords: %i x %i" % (event.x, event.y) t = Tk() t.bind('', printMotionEvents) t.mainloop() This script creates a little Tkinter window and then makes it so that when you move the mouse over the window the mouse coordinates are printed to stdout. From rui.vapps at gmail.com Wed Aug 19 13:44:56 2009 From: rui.vapps at gmail.com (Ray) Date: Wed, 19 Aug 2009 10:44:56 -0700 (PDT) Subject: generate keyboard/mouse event under windows Message-ID: <96047669-1bfd-4dbe-bed8-fafea07bbc5a@z34g2000vbl.googlegroups.com> Hi, Anyone can give some help on how to generate keyboard mouse event under windows? (python 2.5) I tried pyhook, I only know how to monitor the keyboard/mouse events. but don't know how to generate/send the the event. thanks for any help. -Ray From aahz at pythoncraft.com Wed Aug 19 13:49:09 2009 From: aahz at pythoncraft.com (Aahz) Date: 19 Aug 2009 10:49:09 -0700 Subject: Database query execution times in Python? References: <24870050.post@talk.nabble.com> Message-ID: In article , pwnedd wrote: > >> Look up EXPLAIN > >Thanks for the suggestion. I don't see any option to have EXPLAIN display >the query time though? My suggestion was partly a gentle push toward a database forum to get more information -- this isn't really a Python question. Unless all you want to do is get the wall-clock time, in which case just use time.time(). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith From sajmikins at gmail.com Wed Aug 19 13:51:08 2009 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 19 Aug 2009 10:51:08 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> <87r5v8e9cu.fsf@benfinney.id.au> Message-ID: On Aug 19, 12:05?am, Ben Finney wrote: > Simon Forman writes: > > On Tue, Aug 18, 2009 at 8:42 PM, Ben Finney wrote: > > > We're all unified by our humanity. Bringing any god into the picture > > > is surely counter to any goals of unity. > > > Unity "in humanity" is, to my way of thinking, the same as Unity "in > > God". > > Then you're playing Humpty-Dumpty games with words. You know very well > that ?God? has established meanings entirely different from ?humanity?, > and those meanings played a part in your choice of that word. > > I maintain that you can't consistently make a declaration in favour of > human unity and unfounded religious assertions. > > > I think Unity, like None, is a built-in singleton, so to speak. > > This is white noise. > > > >> We are one family. > > > > Agreed. > > > <3 > > I think we can peaceably leave it at that. Hear hear! (FWIW, I've always admired Humpty Dumpty's attitude to words. Have you ever read R.A. Wilson's "Quantum Psychology"?) Regards, ~Simon From gu.yakahughes at gmail.com Wed Aug 19 14:07:16 2009 From: gu.yakahughes at gmail.com (yaka) Date: Wed, 19 Aug 2009 11:07:16 -0700 (PDT) Subject: generate keyboard/mouse event under windows References: <96047669-1bfd-4dbe-bed8-fafea07bbc5a@z34g2000vbl.googlegroups.com> Message-ID: Read this and see if it helps: http://kvance.livejournal.com/985732.html From aahz at pythoncraft.com Wed Aug 19 14:20:22 2009 From: aahz at pythoncraft.com (Aahz) Date: 19 Aug 2009 11:20:22 -0700 Subject: httplib incredibly slow :-( References: Message-ID: In article , Chris Withers wrote: >Aahz wrote: >> >> What do you need to know for a decent example? > >Simple download of a file from a url with some auth headers added would >do me. Well, I've hacked up some sample code from my company's codebase: # !!! UNTESTED !!! c = pycurl.Curl() c.setopt(pycurl.URL, url) c.setopt(pycurl.USERPWD, "%s:%s" % (user, pwd)) c.setopt(pycurl.FOLLOWLOCATION, 1) c.setopt(pycurl.MAXREDIRS, 5) c.setopt(pycurl.CONNECTTIMEOUT, 30) f = StringIO() c.setopt(pycurl.WRITEDATA, f) c.perform() c.close() -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith From rui.vapps at gmail.com Wed Aug 19 14:55:25 2009 From: rui.vapps at gmail.com (Ray) Date: Wed, 19 Aug 2009 11:55:25 -0700 (PDT) Subject: generate keyboard/mouse event under windows References: <96047669-1bfd-4dbe-bed8-fafea07bbc5a@z34g2000vbl.googlegroups.com> Message-ID: <9f107280-5d5c-4e6e-b47b-779e8012fdbc@h30g2000vbr.googlegroups.com> On Aug 19, 2:07?pm, yaka wrote: > Read this and see if it helps: > > http://kvance.livejournal.com/985732.html is there a way to generate a 'true' keyboard event? (works like user pressed a key on keyboard) not send the 'send keyboard event to application' ? From jcn-france1972 at pobox.com Wed Aug 19 15:01:25 2009 From: jcn-france1972 at pobox.com (Jean-Claude Neveu) Date: Wed, 19 Aug 2009 12:01:25 -0700 Subject: Python and PHP encryption/decryption Message-ID: I'm looking for a recommendation about encryption/decryption packages for Python. I'm working on a project that will require me to store some values in a database in encrypted format. I'll be storing them from a PHP script and retrieving them (decrypting them) using Python. I'm currently using PHP's mcrypt package to encrypt the values, and I'm using AES for encryption, so something AES-compatible would be ideal. However, the project is at the development stage so I can easily change how I'm encrypting things in PHP if there is a compelling reason on the Python side of things to do so. Many Thanks, Jean-Claude From aahz at pythoncraft.com Wed Aug 19 15:43:00 2009 From: aahz at pythoncraft.com (Aahz) Date: 19 Aug 2009 12:43:00 -0700 Subject: Any way to adjust difflib algorithm? References: Message-ID: In article , Grant Edwards wrote: >On 2009-08-14, Grant Edwards wrote: >> >> In my particular usage, no lines have ever been >> inserted/deleted, so perhaps I should be running diffs on >> individual lines instead? If I do that, I can't figure out >> how to generate HTML output. > >I ended up using the SequenceMatcher on individual pairs of >lines and generating my own HTML based on the results of >get_matching_blocks(). > >That produced the desired results. Good work! Note that IME most diff software shows changed lines as a delete-and-add. For example, diff -u -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith From jgardner at jonathangardner.net Wed Aug 19 16:10:17 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Wed, 19 Aug 2009 13:10:17 -0700 (PDT) Subject: NOOB: Developing using python on two different computers References: <610dc365-476f-4c5d-a307-b7b4141244ba@q40g2000prh.googlegroups.com> Message-ID: <75f2e1e8-49c4-4564-9fab-b0a6b96adaa4@p36g2000prn.googlegroups.com> On Aug 19, 6:50?am, Smeagol wrote: > Hi there, > > Occasionally I have to develop on two different computers, and I was > wondering if there was a way to copy the python "environment" from one > to the other? > > Access to the data is trivial (networked database) but various > packages etc exist on one computer, and I want to ensure I have > everything package-wise on the other. > > Both are "windows" machines (native windows box and a Macbook with > VMWare running XP)... > > Is it as simple as copying the Python directory, or is there a script > I can run that will tell me what packages are installed on the native > windows box and then I can use easy_install to update the VM partition > on the Macbook? > Simple copy won't do it. Check out virtualenv (http://pypi.python.org/pypi/virtualenv). Reinstalling each env from scratch is usually the best bet. List your dependencies in your packages and all you have to do is easy_install your packages. From invalid at invalid Wed Aug 19 16:16:22 2009 From: invalid at invalid (Grant Edwards) Date: Wed, 19 Aug 2009 15:16:22 -0500 Subject: Any way to adjust difflib algorithm? References: Message-ID: On 2009-08-19, Aahz wrote: > In article , > Grant Edwards wrote: >>On 2009-08-14, Grant Edwards wrote: >>> >>> In my particular usage, no lines have ever been >>> inserted/deleted, so perhaps I should be running diffs on >>> individual lines instead? If I do that, I can't figure out >>> how to generate HTML output. >> >>I ended up using the SequenceMatcher on individual pairs of >>lines and generating my own HTML based on the results of >>get_matching_blocks(). >> >>That produced the desired results. > > Good work! Note that IME most diff software shows changed > lines as a delete-and-add. For example, diff -u Right -- though difflib did show _some_ lines as changed rather than deleted/added, it wasn't obvious how it decided between the two. I suspect it used some sort of percentage-changed threshold. For this application both files had all the same lines (by definition), so what I was interested in was what parts of each line changed. -- Grant Edwards grante Yow! I just heard the at SEVENTIES were over!! And visi.com I was just getting in touch with my LEISURE SUIT!! From politza at googlemail.com Wed Aug 19 16:17:19 2009 From: politza at googlemail.com (A.Politz) Date: Wed, 19 Aug 2009 13:17:19 -0700 (PDT) Subject: python doc available in emacs info format? References: Message-ID: On Aug 17, 6:43?am, Xah Lee wrote: > btw, is there still [no] info format for python doc? > > i feel kinda sad [...] > Part of this is due to [other peoples fault] Someone started a rst2info project (google it), maybe you want to help this guy out. Though, he might be a techgeeker, so watch out ! -ap From israelu at elbit.co.il Wed Aug 19 16:31:17 2009 From: israelu at elbit.co.il (iu2) Date: Wed, 19 Aug 2009 13:31:17 -0700 (PDT) Subject: Dictionary from a list Message-ID: Hi all, I need to create a dictionary out of a list. Given the list [1, 2, 3, 4, 5, 6] I need the dictionary: {1:2, 3:4, 5:6} I'll appreciate your help Thanks iu2 From jjposner at optimum.net Wed Aug 19 16:36:20 2009 From: jjposner at optimum.net (John Posner) Date: Wed, 19 Aug 2009 16:36:20 -0400 Subject: Code formatting question: conditional expression In-Reply-To: References: Message-ID: <4A8C6244.40706@optimum.net> Diez wrote: > No. I love them. But not if they are so large that they stretch over several > lines (or to many columns). > > foo = bar if cond else baz > > is more than fine for me. But > > foo = I_need_to_do_something_really_complicated_here() if cond else baz > > isn't, because one doesn't grasp as easily in one look that we're talking a > ternary operator here. > But the right side of my brain (see Peter Keller's discussion in the recent "importance of syntax" thread) finds it quite easy to recognize this as a ternary op: foo = (I_need_to_do_something_really_complicated_here() if cond else baz) The whitespace below "foo" provides a visual hint, which is confirmed by the nearby appearance of "if" on the second line. De gustibus non est disputandum! (or not) Many thanks to all responders! -John From deets at nospam.web.de Wed Aug 19 16:39:47 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 22:39:47 +0200 Subject: Dictionary from a list In-Reply-To: References: Message-ID: <7f368jF2it5a5U1@mid.uni-berlin.de> iu2 schrieb: > Hi all, > > I need to create a dictionary out of a list. > > Given the list [1, 2, 3, 4, 5, 6] > > I need the dictionary: {1:2, 3:4, 5:6} dict(zip(l[::2], l[1::2])) Diez From deets at nospam.web.de Wed Aug 19 16:42:43 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 22:42:43 +0200 Subject: Python and PHP encryption/decryption In-Reply-To: References: Message-ID: <7f36e3F2it5a5U2@mid.uni-berlin.de> Jean-Claude Neveu schrieb: > I'm looking for a recommendation about encryption/decryption packages > for Python. > > I'm working on a project that will require me to store some values in a > database in encrypted format. I'll be storing them from a PHP script and > retrieving them (decrypting them) using Python. I'm currently using > PHP's mcrypt package to encrypt the values, and I'm using AES for > encryption, so something AES-compatible would be ideal. However, the > project is at the development stage so I can easily change how I'm > encrypting things in PHP if there is a compelling reason on the Python > side of things to do so. With PyCrypto[1] you have a wide range of choices, amongst others AES. If that's the best algorithm, or even the best python-package to implement it, I don't know. [1] http://www.dlitz.net/software/pycrypto/ Diez From deets at nospam.web.de Wed Aug 19 16:46:43 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 22:46:43 +0200 Subject: recording input from USB port and write to text file In-Reply-To: References: Message-ID: <7f36ljF2hd2f3U1@mid.uni-berlin.de> Simon Forman schrieb: > On Aug 18, 7:33 pm, Allan wrote: >> Hi! I'm fairly new to Python. I understand the basics basics but I'm >> been trying to write a simple python code that will let me read input >> data (such as mouse movement) from my USB port and write it in a text >> file and I am so lost. Can anyone help or direct me to some >> resources? Thank you! > > This isn't exactly what you were looking for, but maybe it will give > you some ideas: > > > from Tkinter import * > > def printMotionEvents(event): > print "mouse coords: %i x %i" % (event.x, event.y) > > t = Tk() > t.bind('', printMotionEvents) > t.mainloop() > > > This script creates a little Tkinter window and then makes it so that > when you move the mouse over the window the mouse coordinates are > printed to stdout. If it has focus. The overall problem is hard - see e.g. this: http://www.wintellect.com/CS/blogs/jrobbins/archive/2008/08/30/so-you-want-to-set-a-windows-journal-recording-hook-on-vista-it-s-not-nearly-as-easy-as-you-think.aspx Diez From israelu at elbit.co.il Wed Aug 19 16:52:54 2009 From: israelu at elbit.co.il (iu2) Date: Wed, 19 Aug 2009 13:52:54 -0700 (PDT) Subject: Dictionary from a list References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: On Aug 19, 11:39?pm, "Diez B. Roggisch" wrote: > iu2 schrieb: > > > Hi all, > > > I need to create a dictionary out of a list. > > > Given the list [1, 2, 3, 4, 5, 6] > > > I need the dictionary: {1:2, 3:4, 5:6} > > dict(zip(l[::2], l[1::2])) > > Diez Wow, this is cool! thanks iu2 From deets at nospam.web.de Wed Aug 19 17:16:32 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 19 Aug 2009 23:16:32 +0200 Subject: recording input from USB port and write to text file In-Reply-To: <7f36ljF2hd2f3U1@mid.uni-berlin.de> References: <7f36ljF2hd2f3U1@mid.uni-berlin.de> Message-ID: <7f38dgF2i8dt7U1@mid.uni-berlin.de> Diez B. Roggisch schrieb: > Simon Forman schrieb: >> On Aug 18, 7:33 pm, Allan wrote: >>> Hi! I'm fairly new to Python. I understand the basics basics but I'm >>> been trying to write a simple python code that will let me read input >>> data (such as mouse movement) from my USB port and write it in a text >>> file and I am so lost. Can anyone help or direct me to some >>> resources? Thank you! >> >> This isn't exactly what you were looking for, but maybe it will give >> you some ideas: >> >> >> from Tkinter import * >> >> def printMotionEvents(event): >> print "mouse coords: %i x %i" % (event.x, event.y) >> >> t = Tk() >> t.bind('', printMotionEvents) >> t.mainloop() >> >> >> This script creates a little Tkinter window and then makes it so that >> when you move the mouse over the window the mouse coordinates are >> printed to stdout. > > If it has focus. > > The overall problem is hard - see e.g. this: > > http://www.wintellect.com/CS/blogs/jrobbins/archive/2008/08/30/so-you-want-to-set-a-windows-journal-recording-hook-on-vista-it-s-not-nearly-as-easy-as-you-think.aspx But then, there is a solution :) http://pypi.python.org/pypi/pyHook/1.4/ Diez From shearichard at gmail.com Wed Aug 19 18:55:49 2009 From: shearichard at gmail.com (northof40) Date: Wed, 19 Aug 2009 15:55:49 -0700 (PDT) Subject: What file is foo in package bar in ? Message-ID: Hi - I think this is a pretty basic question but it's never worried me before. To improve my skills I'm reading the source code of a library written by someone else. I've come across a problem doing that. Commonly a function is called like this: thepackage.theclass.foo The problem is that 'theclass' is implemented in a file called nothingliketheclass.py so finding the implemention of foo is a bit boring. Now I can grep for foo and depending on how common the method name is that helps ... or not but I'm sure there must be a better way. Given an arbitary package is there some programmatic way to 'ask' what file the method/function is implemented in ? thanks R. From jcd at sdf.lonestar.org Wed Aug 19 19:01:16 2009 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Wed, 19 Aug 2009 19:01:16 -0400 Subject: How to create functors? In-Reply-To: <4a8c0478$0$2752$426a74cc@news.free.fr> References: <4a8c0478$0$2752$426a74cc@news.free.fr> Message-ID: <1250722876.5792.3.camel@webb> On Wed, 2009-08-19 at 15:56 +0200, Bruno Desthuilliers wrote: > Terry Reedy a ?crit : > > Robert Dailey wrote: > > > >> I'm using Python 2.6. And using the legacy syntax in the lambda does > >> not work either. I want to avoid using a def if possible. Thanks. > > > > In Python, writing > > > > name = lambda arg: expr > > > > instead of > > > > def name(arg): return expr > > > > is all negative and no positive and should be avoided. > > Except that def is a statement, and as such can't be used as a named > params when calling a function expecting a callback, ie: > > vroom = some_dead('parrot', name=lambda arg: exp) > > (notice the 'name = lambda arg: exp' ?-) > Which offers no added functionality over: def name_func(arg): return exp vroom = some_dead('parrot', name=name_func) except for confusion in debugging. :) (See other excessively long threads on lambda for further discussion of the debugging headaches caused by lambdas. > Ok, nitpicking. Me --->[] > > From lists at cheimes.de Wed Aug 19 19:06:00 2009 From: lists at cheimes.de (Christian Heimes) Date: Thu, 20 Aug 2009 01:06:00 +0200 Subject: What file is foo in package bar in ? In-Reply-To: References: Message-ID: northof40 wrote: > Given an arbitary package is there some programmatic way to 'ask' what > file the method/function is implemented in ? Indeed, the inspect module contains several useful functions for the job, for example http://docs.python.org/library/inspect.html#inspect.getfile Christian From ndbecker2 at gmail.com Wed Aug 19 19:19:24 2009 From: ndbecker2 at gmail.com (Neal Becker) Date: Wed, 19 Aug 2009 19:19:24 -0400 Subject: #elements of seq A in seq B Message-ID: What would be a time efficient way to count the number of occurrences of elements of sequence A in sequence B? (in this particular case, these sequences are strings, if that matters). From zuo at chopin.edu.pl Wed Aug 19 19:36:19 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 20 Aug 2009 01:36:19 +0200 Subject: difference between 2 arrays In-Reply-To: <4a8bbe36$0$12654$ba4acef3@news.orange.fr> References: <4a8bbe36$0$12654$ba4acef3@news.orange.fr> Message-ID: 19-08-2009 o 10:56:20 <""Michel Claveau - MVP"> wrote: > (envoy? via news:\\news.wanadoo.fr\comp.lang.python) > > Hi! > > See the module "sets" No, see the builtin set type. Module sets is deprecated (removed in Py 3.x) -- Jan Kaliszewski (zuo) From shearichard at gmail.com Wed Aug 19 19:42:16 2009 From: shearichard at gmail.com (northof40) Date: Wed, 19 Aug 2009 16:42:16 -0700 (PDT) Subject: What file is foo in package bar in ? References: Message-ID: <48a9837b-eb37-47ba-9032-5c5ff7d42223@x25g2000prf.googlegroups.com> On Aug 20, 11:06?am, Christian Heimes wrote: > northof40 wrote: > > Given an arbitary package is there some programmatic way to 'ask' what > > file the method/function is implemented in ? > > Indeed, the inspect module contains several useful functions for the > job, for examplehttp://docs.python.org/library/inspect.html#inspect.getfile > > Christian That's really great thanks - just what I was after. regards R. From ronn.ross at gmail.com Wed Aug 19 19:55:06 2009 From: ronn.ross at gmail.com (Ronn Ross) Date: Wed, 19 Aug 2009 19:55:06 -0400 Subject: Barcodes In-Reply-To: <9c8c445f0908190619v5f50de1bvbbfbd8c0557f9783@mail.gmail.com> References: <9c8c445f0908171318x2d9d862bi35ccb398376aceca@mail.gmail.com> <4A89C3BB.2030605@tim.thechases.com> <9c8c445f0908190619v5f50de1bvbbfbd8c0557f9783@mail.gmail.com> Message-ID: <9c8c445f0908191655i42ec8f86p8f699f2b35cbf6f7@mail.gmail.com> On Wed, Aug 19, 2009 at 9:19 AM, Ronn Ross wrote: > I was hoping that python would have a library to help me print my own bar > codes? We will need labels in all sizes and most label printer just work > with 1 or 2 sizes. I would like to just print a grid of different sizes on > standard paper. Does python have a bar code printing library? > > > > On Mon, Aug 17, 2009 at 4:55 PM, Tim Chase wrote: > >> My company needs a small inventory management app. Does >>>> python have any libraries to help with reading and writing >>>> bar codes? >>>> >>> >>> I've written bar code apps and python really doesn't enter >>> into that part of things. Printers generally have bar code >>> printing capabilities so you just send the right escape >>> sequences and you get the bar codes. To read them, bar code >>> readers scan and translate before sending the values through >>> typically a keyboard wedge or serial port. >>> >> >> To add to what Emile mentions, most barcode readers present a >> keyboard-wedge interface, so that scanning a barcode merely appears as if >> you typed it at the keyboard (USB readers show up as a HID profile). Often >> they'll have configuration barcodes that you can scan to tweak the profile >> (such as pressing , or an arrow-key after sending the barcode; >> controlling beep tone & volume, etc). >> >> For printing barcodes, you can use any number of solutions -- the most >> popular usually just involves installing a "barcode font" and then rendering >> text in that font to your desired output canvas. I believe there are some >> native rendering solutions as well, but I've not investigated since the font >> method was more than sufficient for my wants. >> >> -tkc >> >> >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > I found this library, but no documentation( https://cybernetics.hudora.biz/projects/wiki/huBarcode). Has anyone used this or know of a similar library with better documentation? -------------- next part -------------- An HTML attachment was scrubbed... URL: From zuo at chopin.edu.pl Wed Aug 19 20:05:57 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 20 Aug 2009 02:05:57 +0200 Subject: Dictionary from a list In-Reply-To: References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: 19-08-2009 o 22:52:54 iu2 wrote: > On Aug 19, 11:39?pm, "Diez B. Roggisch" wrote: >> iu2 schrieb: >> >> > Hi all, >> >> > I need to create a dictionary out of a list. >> >> > Given the list [1, 2, 3, 4, 5, 6] >> >> > I need the dictionary: {1:2, 3:4, 5:6} >> >> dict(zip(l[::2], l[1::2])) Or (for long lists, when memory becomes expensive): dict(li[i:i+2] for i in xrange(0, len(li), 2)) Or probably better: from itertools import islice, izip dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2))) Cheers, *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Wed Aug 19 20:17:47 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 20 Aug 2009 02:17:47 +0200 Subject: #elements of seq A in seq B In-Reply-To: References: Message-ID: 20-08-2009 o 01:19:24 Neal Becker wrote: > What would be a time efficient way to count the number of occurrences of > elements of sequence A in sequence B? (in this particular case, these > sequences are strings, if that matters). If you mean: to count occurences of each element of A (separately) in B... Hm, maybe something like this: # result as a dict {: , ...} dict((element, B.count(element)) for element in A) If you mean: to count non overlaping occurences of string A in B -- simply: B.count(A) Regards, *j -- Jan Kaliszewski (zuo) From mhanuel at ieee.org Wed Aug 19 20:27:07 2009 From: mhanuel at ieee.org (Manuel A. Iglesias Abbatemarco) Date: Thu, 20 Aug 2009 00:27:07 +0000 Subject: grokproject and zope.security==3.4.1 error Message-ID: I will apprreciate if someone could help me with the following error. I a trying to create a grokproject application in my debian 5.0 box, the following is the output after executing # grokproject Sample command. debian-box:/home/manuel-debian# grokproject Sample Enter user (Name of an initial administrator user): grok Enter passwd (Password for the initial administrator user): Downloading info about versions... Creating directory ./Sample Downloading zc.buildout... Invoking zc.buildout... Develop: '/home/manuel-debian/Sample/.' Installing eggbasket. Couldn't find index page for 'zope.security' (maybe misspelled?) Getting distribution for 'zope.security==3.4.1'. eggbasket: Distributions are not installed. A tarball will be downloaded. eggbasket: Distributions are not installed. A tarball will be downloaded. eggbasket: Downloading http://grok.zope.org/releaseinfo/grok-eggs-1.0a4.tgz ... eggbasket: Downloading http://grok.zope.org/releaseinfo/grok-eggs-1.0a4.tgz ... eggbasket: Finished downloading. eggbasket: Finished downloading. eggbasket: Extracting tarball contents... eggbasket: Extracting tarball contents... eggbasket: Installing eggs to /root/.buildout/eggs which will take a while... eggbasket: Installing eggs to /root/.buildout/eggs which will take a while... Getting distribution for 'zope.security==3.4.1'. src/zope/security/_proxy.c:19:20: error: Python.h: No such file or directory In file included from src/zope/security/_proxy.c:20: include/zope.proxy/proxy.h:8: error: expected ?)? before ?*? token include/zope.proxy/proxy.h:9: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token include/zope.proxy/proxy.h:10: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token include/zope.proxy/proxy.h:11: error: expected ?)? before ?*? token include/zope.proxy/proxy.h:12: error: expected ?)? before ?*? token include/zope.proxy/proxy.h:16: error: expected specifier-qualifier-list before ?PyObject_HEAD? include/zope.proxy/proxy.h:23: error: expected specifier-qualifier-list before ?PyTypeObject? include/zope.proxy/proxy.h:37: error: ?NULL? undeclared here (not in a function) include/zope.proxy/proxy.h: In function ?Proxy_Import?: include/zope.proxy/proxy.h:43: error: ?PyObject? undeclared (first use in this function) include/zope.proxy/proxy.h:43: error: (Each undeclared identifier is reported only once include/zope.proxy/proxy.h:43: error: for each function it appears in.) include/zope.proxy/proxy.h:43: error: ?m? undeclared (first use in this function) include/zope.proxy/proxy.h:43: warning: implicit declaration of function ?PyImport_ImportModule? include/zope.proxy/proxy.h:45: error: ?tmp? undeclared (first use in this function) include/zope.proxy/proxy.h:45: warning: implicit declaration of function ?PyObject_GetAttrString? include/zope.proxy/proxy.h:47: warning: implicit declaration of function ?PyCObject_Check? include/zope.proxy/proxy.h:49: warning: implicit declaration of function ?PyCObject_AsVoidPtr? include/zope.proxy/proxy.h:50: warning: implicit declaration of function ?Py_DECREF? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:22: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:26: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:27: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:28: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:29: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:30: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:31: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:32: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:33: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:34: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:35: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:36: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:37: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:38: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:39: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:40: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:41: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:42: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:43: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:44: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:45: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:46: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:47: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:48: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:49: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:50: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:51: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:52: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:53: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:54: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:55: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:56: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:57: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:58: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:59: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:60: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:61: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:62: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:63: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:64: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:65: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:66: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:67: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:68: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:69: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:70: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:71: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:72: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:73: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:74: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:75: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:76: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:77: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:78: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:79: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:80: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:81: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:82: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:83: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:84: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:85: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:86: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:87: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:88: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:89: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:90: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:91: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:92: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:93: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:94: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:95: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:96: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:100: error: expected specifier-qualifier-list before ?PyObject? src/zope/security/_proxy.c:109: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?SecurityProxyType? src/zope/security/_proxy.c:116: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c:116: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?check?: src/zope/security/_proxy.c:118: error: ?PyObject? undeclared (first use in this function) src/zope/security/_proxy.c:118: error: ?r? undeclared (first use in this function) src/zope/security/_proxy.c:126: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:127: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:128: error: ?meth? undeclared (first use in this function) src/zope/security/_proxy.c:128: error: ?str_check_setattr? undeclared (first use in this function) src/zope/security/_proxy.c:129: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:130: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:130: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:130: error: ?name? undeclared (first use in this function) src/zope/security/_proxy.c:132: warning: implicit declaration of function ?PyObject_CallMethodObjArgs? src/zope/security/_proxy.c:132: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:133: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:162: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:164: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:176: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:210: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:250: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:282: error: expected ?)? before ?*? token src/zope/security/_proxy.c: In function ?proxy_clear?: src/zope/security/_proxy.c:290: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:290: error: ?PyObject? undeclared (first use in this function) src/zope/security/_proxy.c:290: error: ?t? undeclared (first use in this function) src/zope/security/_proxy.c:290: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:290: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c:291: error: ?SecurityProxyType? undeclared (first use in this function) src/zope/security/_proxy.c:291: error: expected expression before ?)? token src/zope/security/_proxy.c: In function ?proxy_dealloc?: src/zope/security/_proxy.c:299: error: ?SecurityProxyType? undeclared (first use in this function) src/zope/security/_proxy.c:299: error: ?PyObject? undeclared (first use in this function) src/zope/security/_proxy.c:299: error: expected expression before ?)? token src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:303: error: expected declaration specifiers or ?...? before ?visitproc? src/zope/security/_proxy.c: In function ?proxy_traverse?: src/zope/security/_proxy.c:305: warning: implicit declaration of function ?visit? src/zope/security/_proxy.c:305: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:307: error: ?SecurityProxy? has no member named ?proxy_checker? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:312: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:324: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:337: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:350: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:364: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c:364: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?proxy_setattro?: src/zope/security/_proxy.c:366: error: ?str_check_setattr? undeclared (first use in this function) src/zope/security/_proxy.c:366: error: ?name? undeclared (first use in this function) src/zope/security/_proxy.c:366: error: too many arguments to function ?check? src/zope/security/_proxy.c:367: warning: implicit declaration of function ?PyObject_SetAttr? src/zope/security/_proxy.c:367: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:367: error: ?value? undeclared (first use in this function) src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:371: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:410: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:427: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:443: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?proxy_compare?: src/zope/security/_proxy.c:445: warning: implicit declaration of function ?PyObject_Compare? src/zope/security/_proxy.c:445: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:445: error: ?other? undeclared (first use in this function) src/zope/security/_proxy.c: In function ?proxy_hash?: src/zope/security/_proxy.c:451: warning: implicit declaration of function ?PyObject_Hash? src/zope/security/_proxy.c:451: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:454: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:484: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:485: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:486: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:487: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:488: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:490: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:497: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:498: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:499: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:500: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:501: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:502: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:504: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:544: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:545: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:546: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:547: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:548: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:551: error: expected ?)? before ?*? token src/zope/security/_proxy.c:596: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:597: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:598: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:601: error: expected ?)? before ?*? token src/zope/security/_proxy.c:606: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:607: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:608: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:609: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:610: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:611: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:613: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:614: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:615: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:616: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:617: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:618: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:619: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:620: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:621: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:622: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:623: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:625: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:626: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:627: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:628: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c: In function ?proxy_length?: src/zope/security/_proxy.c:637: error: ?str_check? undeclared (first use in this function) src/zope/security/_proxy.c:637: error: ?str___len__? undeclared (first use in this function) src/zope/security/_proxy.c:637: error: too many arguments to function ?check? src/zope/security/_proxy.c:638: warning: implicit declaration of function ?PyObject_Length? src/zope/security/_proxy.c:638: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:643: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:644: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c:644: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c:646: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:661: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?proxy_isetitem?: src/zope/security/_proxy.c:663: error: ?PyObject? undeclared (first use in this function) src/zope/security/_proxy.c:663: error: ?key? undeclared (first use in this function) src/zope/security/_proxy.c:663: warning: implicit declaration of function ?PyInt_FromLong? src/zope/security/_proxy.c:667: error: ?value? undeclared (first use in this function) src/zope/security/_proxy.c:667: error: too many arguments to function ?proxy_setitem? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:673: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:686: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?proxy_ass_slice?: src/zope/security/_proxy.c:688: error: ?str_check? undeclared (first use in this function) src/zope/security/_proxy.c:688: error: ?str___setslice__? undeclared (first use in this function) src/zope/security/_proxy.c:688: error: too many arguments to function ?check? src/zope/security/_proxy.c:689: warning: implicit declaration of function ?PySequence_SetSlice? src/zope/security/_proxy.c:689: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:689: error: ?value? undeclared (first use in this function) src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:694: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?proxy_contains?: src/zope/security/_proxy.c:696: error: ?str_check? undeclared (first use in this function) src/zope/security/_proxy.c:696: error: ?str___contains__? undeclared (first use in this function) src/zope/security/_proxy.c:696: error: too many arguments to function ?check? src/zope/security/_proxy.c:697: warning: implicit declaration of function ?PySequence_Contains? src/zope/security/_proxy.c:697: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:697: error: ?value? undeclared (first use in this function) src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:705: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:719: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c:719: error: expected declaration specifiers or ?...? before ?PyObject? src/zope/security/_proxy.c: In function ?proxy_setitem?: src/zope/security/_proxy.c:721: error: ?value? undeclared (first use in this function) src/zope/security/_proxy.c:722: error: ?str_check? undeclared (first use in this function) src/zope/security/_proxy.c:722: error: ?str___delitem__? undeclared (first use in this function) src/zope/security/_proxy.c:722: error: too many arguments to function ?check? src/zope/security/_proxy.c:723: warning: implicit declaration of function ?PyObject_DelItem? src/zope/security/_proxy.c:723: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c:723: error: ?key? undeclared (first use in this function) src/zope/security/_proxy.c:726: error: ?str___setitem__? undeclared (first use in this function) src/zope/security/_proxy.c:726: error: too many arguments to function ?check? src/zope/security/_proxy.c:727: warning: implicit declaration of function ?PyObject_SetItem? src/zope/security/_proxy.c:727: error: ?ProxyObject? has no member named ?proxy_object? src/zope/security/_proxy.c: At top level: src/zope/security/_proxy.c:737: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?proxy_as_number? src/zope/security/_proxy.c:785: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?proxy_as_sequence? src/zope/security/_proxy.c:797: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?proxy_as_mapping? src/zope/security/_proxy.c:817: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?PyTypeObject? src/zope/security/_proxy.c:862: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:877: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?*? token src/zope/security/_proxy.c:892: error: expected ?=?, ?,?, ?;?, ?asm? or ?__attribute__? before ?module_functions? src/zope/security/_proxy.c: In function ?init_proxy?: src/zope/security/_proxy.c:905: error: ?PyObject? undeclared (first use in this function) src/zope/security/_proxy.c:905: error: ?m? undeclared (first use in this function) src/zope/security/_proxy.c:915: error: ?str___3pow__? undeclared (first use in this function) src/zope/security/_proxy.c:915: warning: implicit declaration of function ?PyString_InternFromString? src/zope/security/_proxy.c:916: error: ?str___call__? undeclared (first use in this function) src/zope/security/_proxy.c:917: error: ?str_check? undeclared (first use in this function) src/zope/security/_proxy.c:918: error: ?str_check_getattr? undeclared (first use in this function) src/zope/security/_proxy.c:919: error: ?str_check_setattr? undeclared (first use in this function) src/zope/security/_proxy.c:920: error: ?str___cmp__? undeclared (first use in this function) src/zope/security/_proxy.c:921: error: ?str___coerce__? undeclared (first use in this function) src/zope/security/_proxy.c:922: error: ?str___contains__? undeclared (first use in this function) src/zope/security/_proxy.c:923: error: ?str___delitem__? undeclared (first use in this function) src/zope/security/_proxy.c:924: error: ?str___getitem__? undeclared (first use in this function) src/zope/security/_proxy.c:925: error: ?str___getslice__? undeclared (first use in this function) src/zope/security/_proxy.c:926: error: ?str___hash__? undeclared (first use in this function) src/zope/security/_proxy.c:927: error: ?str___iter__? undeclared (first use in this function) src/zope/security/_proxy.c:928: error: ?str___len__? undeclared (first use in this function) src/zope/security/_proxy.c:929: error: ?str_next? undeclared (first use in this function) src/zope/security/_proxy.c:930: error: ?str___nonzero__? undeclared (first use in this function) src/zope/security/_proxy.c:931: error: ?str_op_abs? undeclared (first use in this function) src/zope/security/_proxy.c:932: error: ?str_op_add? undeclared (first use in this function) src/zope/security/_proxy.c:933: error: ?str_op_and? undeclared (first use in this function) src/zope/security/_proxy.c:934: error: ?str_op_div? undeclared (first use in this function) src/zope/security/_proxy.c:935: error: ?str_op_divmod? undeclared (first use in this function) src/zope/security/_proxy.c:936: error: ?str_op_float? undeclared (first use in this function) src/zope/security/_proxy.c:937: error: ?str_op_floordiv? undeclared (first use in this function) src/zope/security/_proxy.c:938: error: ?str_op_hex? undeclared (first use in this function) src/zope/security/_proxy.c:939: error: ?str_op_iadd? undeclared (first use in this function) src/zope/security/_proxy.c:940: error: ?str_op_iand? undeclared (first use in this function) src/zope/security/_proxy.c:941: error: ?str_op_idiv? undeclared (first use in this function) src/zope/security/_proxy.c:942: error: ?str_op_ifloordiv? undeclared (first use in this function) src/zope/security/_proxy.c:943: error: ?str_op_ilshift? undeclared (first use in this function) src/zope/security/_proxy.c:944: error: ?str_op_imod? undeclared (first use in this function) src/zope/security/_proxy.c:945: error: ?str_op_imul? undeclared (first use in this function) src/zope/security/_proxy.c:946: error: ?str_op_int? undeclared (first use in this function) src/zope/security/_proxy.c:947: error: ?str_op_invert? undeclared (first use in this function) src/zope/security/_proxy.c:948: error: ?str_op_ior? undeclared (first use in this function) src/zope/security/_proxy.c:949: error: ?str_op_ipow? undeclared (first use in this function) src/zope/security/_proxy.c:950: error: ?str_op_irshift? undeclared (first use in this function) src/zope/security/_proxy.c:951: error: ?str_op_isub? undeclared (first use in this function) src/zope/security/_proxy.c:952: error: ?str_op_itruediv? undeclared (first use in this function) src/zope/security/_proxy.c:953: error: ?str_op_ixor? undeclared (first use in this function) src/zope/security/_proxy.c:954: error: ?str_op_long? undeclared (first use in this function) src/zope/security/_proxy.c:955: error: ?str_op_lshift? undeclared (first use in this function) src/zope/security/_proxy.c:956: error: ?str_op_mod? undeclared (first use in this function) src/zope/security/_proxy.c:957: error: ?str_op_mul? undeclared (first use in this function) src/zope/security/_proxy.c:958: error: ?str_op_neg? undeclared (first use in this function) src/zope/security/_proxy.c:959: error: ?str_op_oct? undeclared (first use in this function) src/zope/security/_proxy.c:960: error: ?str_op_or? undeclared (first use in this function) src/zope/security/_proxy.c:961: error: ?str_op_pos? undeclared (first use in this function) src/zope/security/_proxy.c:962: error: ?str_op_radd? undeclared (first use in this function) src/zope/security/_proxy.c:963: error: ?str_op_rand? undeclared (first use in this function) src/zope/security/_proxy.c:964: error: ?str_op_rdiv? undeclared (first use in this function) src/zope/security/_proxy.c:965: error: ?str_op_rdivmod? undeclared (first use in this function) src/zope/security/_proxy.c:966: error: ?str_op_rfloordiv? undeclared (first use in this function) src/zope/security/_proxy.c:967: error: ?str_op_rlshift? undeclared (first use in this function) src/zope/security/_proxy.c:968: error: ?str_op_rmod? undeclared (first use in this function) src/zope/security/_proxy.c:969: error: ?str_op_rmul? undeclared (first use in this function) src/zope/security/_proxy.c:970: error: ?str_op_ror? undeclared (first use in this function) src/zope/security/_proxy.c:971: error: ?str_op_rrshift? undeclared (first use in this function) src/zope/security/_proxy.c:972: error: ?str_op_rshift? undeclared (first use in this function) src/zope/security/_proxy.c:973: error: ?str_op_rsub? undeclared (first use in this function) src/zope/security/_proxy.c:974: error: ?str_op_rtruediv? undeclared (first use in this function) src/zope/security/_proxy.c:975: error: ?str_op_rxor? undeclared (first use in this function) src/zope/security/_proxy.c:976: error: ?str_op_sub? undeclared (first use in this function) src/zope/security/_proxy.c:977: error: ?str_op_truediv? undeclared (first use in this function) src/zope/security/_proxy.c:978: error: ?str_op_xor? undeclared (first use in this function) src/zope/security/_proxy.c:979: error: ?str___pow__? undeclared (first use in this function) src/zope/security/_proxy.c:980: error: ?str_proxy? undeclared (first use in this function) src/zope/security/_proxy.c:981: error: ?str___repr__? undeclared (first use in this function) src/zope/security/_proxy.c:982: error: ?str___rpow__? undeclared (first use in this function) src/zope/security/_proxy.c:983: error: ?str___setitem__? undeclared (first use in this function) src/zope/security/_proxy.c:984: error: ?str___setslice__? undeclared (first use in this function) src/zope/security/_proxy.c:985: error: ?str___str__? undeclared (first use in this function) src/zope/security/_proxy.c:988: error: ?__class__str? undeclared (first use in this function) src/zope/security/_proxy.c:988: warning: implicit declaration of function ?PyString_FromString? src/zope/security/_proxy.c:991: error: ?__name__str? undeclared (first use in this function) src/zope/security/_proxy.c:994: error: ?__module__str? undeclared (first use in this function) src/zope/security/_proxy.c:997: error: ?SecurityProxyType? undeclared (first use in this function) src/zope/security/_proxy.c:997: error: ?PyType_Type? undeclared (first use in this function) src/zope/security/_proxy.c:998: error: ?PyType_GenericAlloc? undeclared (first use in this function) src/zope/security/_proxy.c:999: error: ?_PyObject_GC_Del? undeclared (first use in this function) src/zope/security/_proxy.c:1000: error: ?ProxyInterface? has no member named ?proxytype? src/zope/security/_proxy.c:1001: warning: implicit declaration of function ?PyType_Ready? src/zope/security/_proxy.c:1004: warning: implicit declaration of function ?Py_InitModule3? src/zope/security/_proxy.c:1004: error: ?module_functions? undeclared (first use in this function) src/zope/security/_proxy.c:1008: warning: implicit declaration of function ?Py_INCREF? src/zope/security/_proxy.c:1009: warning: implicit declaration of function ?PyModule_AddObject? src/zope/security/_proxy.c:1009: error: expected expression before ?)? token error: Setup script exited with error: command 'gcc' failed with exit status 1 An error occured when trying to install zope.security 3.4.1.Look above this message for any errors thatwere output by easy_install. While: Installing eggbasket. Getting distribution for 'zope.security==3.4.1'. Error: Couldn't install: zope.security 3.4.1 Thank you in advance. Manuel _________________________________________________________________ With Windows Live, you can organize, edit, and share your photos. http://www.windowslive.com/Desktop/PhotoGallery -------------- next part -------------- An HTML attachment was scrubbed... URL: From zuo at chopin.edu.pl Wed Aug 19 20:29:32 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 20 Aug 2009 02:29:32 +0200 Subject: Dictionary from a list In-Reply-To: References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: 20-08-2009 o 02:05:57 Jan Kaliszewski wrote: > Or probably better: > > from itertools import islice, izip > dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2))) Or similarly, perhaps more readable: iterator = iter(li) dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2)) -- Jan Kaliszewski (zuo) From greg at cosc.canterbury.ac.nz Wed Aug 19 20:51:36 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 20 Aug 2009 12:51:36 +1200 Subject: Identifying a class type - bad practice? In-Reply-To: <520f55a6-38ac-432b-97e7-ec327740645a@o6g2000yqj.googlegroups.com> References: <5a6e91f5-83c1-42a3-ab8a-082c4d8e840c@c14g2000yqm.googlegroups.com> <520f55a6-38ac-432b-97e7-ec327740645a@o6g2000yqj.googlegroups.com> Message-ID: <7f3kvpF2in935U1@mid.individual.net> James Harris wrote: > I don't know yet whether it will be > easier to modify the tree or to create a new one for each phase. You can create a new tree using this style as well. Just have each method create and return a new node instead of modifying the existing one. -- Greg From nat.k at gm.ml Wed Aug 19 20:58:15 2009 From: nat.k at gm.ml (Nathan Keel) Date: Wed, 19 Aug 2009 17:58:15 -0700 Subject: python doc available in emacs info format? References: Message-ID: A.Politz wrote: > On Aug 17, 6:43?am, Xah Lee wrote: >> btw, is there still [no] info format for python doc? >> >> i feel kinda sad [...] >> Part of this is due to [other peoples fault] > > Someone started a rst2info project (google it), maybe you want to help > this guy out. > > Though, he might be a techgeeker, so watch out ! > > -ap Don't bother with this Xah Lee clown. He posts random crap because he thinks everyone wants to hear what he has to say about unrelated subject material and thinks he looks smart for doing it. Unfortunately, he usually lacks a clue about any topic he brings up (and he always starts a new thread like he's some authority). His goals are nothing more than to post arrogant, clueless rants thinking he's showing off. this is why he ALWAYS cross posts to the same groups (Emacs, Python,, Perl, etc.), even when the topic or content has nothing to do with those things. He thinks people in these groups automatically respect him, when most have killfiled him. From http Wed Aug 19 21:42:32 2009 From: http (Paul Rubin) Date: 19 Aug 2009 18:42:32 -0700 Subject: How to create functors? References: Message-ID: <7xab1vl0qf.fsf@ruckus.brouhaha.com> Robert Dailey writes: > I want to simply wrap a function up into an object so it can be called > with no parameters. Nitpick: what you are asking for is called a closure. "Functor" means something completely different. As a few other people have explained, "print" in python 2.x is a statement rather than a function. You could use sys.stdout.write instead of print. From http Wed Aug 19 21:45:53 2009 From: http (Paul Rubin) Date: 19 Aug 2009 18:45:53 -0700 Subject: Python and PHP encryption/decryption References: Message-ID: <7x63cjl0ku.fsf@ruckus.brouhaha.com> Jean-Claude Neveu writes: > I'm working on a project that will require me to store some values in > a database in encrypted format. I'll be storing them from a PHP script > and retrieving them (decrypting them) using Python. I'm currently > using PHP's mcrypt package to encrypt the values, and I'm using AES > for encryption, so something AES-compatible would be ideal. There are several python libraries that support AES in the standard operating modes. If you are doing something sensible on the PHP side, you should be able to get Python to interoperate with it. Be careful that you are doing the right things algorithmically in terms of modes, IV's, etc. If you don't know what you're doing in this area, it's best to (at minimum) seek more specific advice. From sajmikins at gmail.com Wed Aug 19 22:12:14 2009 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 19 Aug 2009 19:12:14 -0700 (PDT) Subject: #elements of seq A in seq B References: Message-ID: <7c16abe1-7502-432a-acff-aff95c22a8ac@q14g2000vbi.googlegroups.com> On Aug 19, 8:17?pm, "Jan Kaliszewski" wrote: > 20-08-2009 o 01:19:24 Neal Becker wrote: > > > What would be a time efficient way to count the number of occurrences of > > elements of sequence A in sequence B? ?(in this particular case, these > > sequences are strings, if that matters). > > If you mean: to count occurences of each element of A (separately) in B... > > Hm, maybe something like this: > > ? ?# result as a dict {: , ...} > ? ?dict((element, B.count(element)) for element in A) > > If you mean: to count non overlaping occurences of string A in B > -- simply: > > ? ?B.count(A) > > Regards, > *j > > -- > Jan Kaliszewski (zuo) You don't want to use count() in a case like this because it iterates through B len(A) times, i.e. this algorithm is O(A x B). If all you want is the total you can do it like this: def f(a, b): a = set(a) return sum(item in a for item in b) A = 'some string' B = 'another string' print f(A, B) # prints 12 If you want to know the count for each element you can use this: from collections import defaultdict def g(a, b): a = set(a) d = defaultdict(int) for item in b: if item in a: d[item] += 1 return d print g(A, B) # prints defaultdict(, {' ': 1, 'e': 1, 'g': 1, 'i': 1, 'o': 1, 'n': 2, 's': 1, 'r': 2, 't': 2}) HTH, ~Simon From rtomek at ceti.com.pl Wed Aug 19 22:45:46 2009 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Thu, 20 Aug 2009 04:45:46 +0200 (CEST) Subject: #elements of seq A in seq B In-Reply-To: References: Message-ID: On Wed, 19 Aug 2009, Neal Becker wrote: > What would be a time efficient way to count the number of occurrences of > elements of sequence A in sequence B? (in this particular case, these > sequences are strings, if that matters). If A and B are rather lengthy, then maybe build a tree from elements of A and use it to count elements of B. I.e., tree nodes would be counters. Building trees in Python, however, I guess it is a little bit tricky. Of course it is possible. But maybe you would rather have this tree maintained in C. Regards Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From wuwei23 at gmail.com Wed Aug 19 23:04:12 2009 From: wuwei23 at gmail.com (alex23) Date: Wed, 19 Aug 2009 20:04:12 -0700 (PDT) Subject: How do I convert an iterator over bytes into a str? References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> <2c212222-0dac-4bd3-8130-5bd302d12dd5@c2g2000yqi.googlegroups.com> Message-ID: markscottwright wrote: > Thanks Jan (and all other responders). ?I suppose I shouldn't be > surprised - it's a known wart (http://wiki.python.org/moin/ > PythonWarts), but it just looks so darn wrong. Don't forget that it's exceptionally easy to create your own mechanism for doing this: def join(seq, sep): return sep.join(map(str, seq)) From laser.yuan at gmail.com Wed Aug 19 23:22:55 2009 From: laser.yuan at gmail.com (laser) Date: Wed, 19 Aug 2009 20:22:55 -0700 (PDT) Subject: IDLE is not as interactive as Maple Message-ID: <7aa51a98-965c-4c74-a3b5-650140f1d589@v23g2000pro.googlegroups.com> In the future, will Python provide programe enviroment like Maple does? In Maple, you can remove anything unneeded in the editor. And the code execution order are not necessary in one direction. You can run any command line on the screen by push Enter key. These functions gave a lot of flaxibility for users to start with programming something. From sjmachin at lexicon.net Wed Aug 19 23:34:51 2009 From: sjmachin at lexicon.net (John Machin) Date: Wed, 19 Aug 2009 20:34:51 -0700 (PDT) Subject: #elements of seq A in seq B References: <7c16abe1-7502-432a-acff-aff95c22a8ac@q14g2000vbi.googlegroups.com> Message-ID: <285422cf-9a8d-43ef-a5ac-a04a3ce9a002@a39g2000pre.googlegroups.com> On Aug 20, 12:12?pm, Simon Forman wrote: > On Aug 19, 8:17?pm, "Jan Kaliszewski" wrote: > > If you mean: to count non overlaping occurences of string A in B > > -- simply: > > > ? ?B.count(A) > > You don't want to use count() in a case like this because it iterates > through B len(A) times, i.e. this algorithm is O(A x B). There's seems to be multiple confusion here. Jan was talking about counting non-overlapping occurrences of string A in [string] B. In that case B.count(A) is nowhere near O(A*B)... in fact in reasonable cases it is sub-linear i.e. O(B/A) See http://svn.python.org/view/python/trunk/Objects/stringlib/fastsearch.h?revision=68811&view=markup And even a naive implementation of str.count() would not "iterate through B len(A) times". and list.count() can't be used on its own to solve Neal's problem; its arg is a single element so it would have to be wrapped in a loop: sum (B.count(a) for a in A) which would of course be O(A*B) From metolone+gmane at gmail.com Thu Aug 20 00:01:23 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Wed, 19 Aug 2009 21:01:23 -0700 Subject: Read C++ enum in python References: <4a8b3342$0$25403$426a34cc@news.free.fr><4A8B3E2D.7040702@mrabarnett.plus.com> Message-ID: "Mark Tolonen" wrote in message news:h6g9ig$vh0$1 at ger.gmane.org... [snip] > > This is what 3rd party library pyparsing is great for: > > --------begin code---------- > from pyparsing import * > > # sample string with enums and other stuff > sample = ''' > stuff before > > enum hello { > Zero, > One, > Two, > Three, > Five=5, > Six, > Ten=10 > } > > in the middle > > enum blah > { > alpha, > beta, > gamma = 10 , > zeta = 50 > } > > at the end > ''' > > # syntax we don't want to see in the final parse tree > _lcurl = Suppress('{') > _rcurl = Suppress('}') > _equal = Suppress('=') > _comma = Suppress(',') > _enum = Suppress('enum') > > identifier = Word(alphas,alphanums+'_') > integer = Word(nums) > > enumValue = Group(identifier('name') + Optional(_equal + > integer('value'))) > enumList = Group(enumValue + ZeroOrMore(_comma + enumValue)) > enum = _enum + identifier('enum') + _lcurl + enumList('list') + _rcurl > > # find instances of enums ignoring other syntax > for item,start,stop in enum.scanString(sample): > id = 0 > for entry in item.list: > if entry.value != '': > id = int(entry.value) > print '%s_%s = %d' % (item.enum.upper(),entry.name.upper(),id) > id += 1 > --------------end code------------ > > Output: > HELLO_ZERO = 0 > HELLO_ONE = 1 > HELLO_TWO = 2 > HELLO_THREE = 3 > HELLO_FIVE = 5 > HELLO_SIX = 6 > HELLO_TEN = 10 > BLAH_ALPHA = 0 > BLAH_BETA = 1 > BLAH_GAMMA = 10 > BLAH_ZETA = 50 Paul McGuire (pyparsing author) reminded me that: enum.ignore(cppStyleComment) before scanString will skip commented out sections as well. -Mark From half.italian at gmail.com Thu Aug 20 00:04:47 2009 From: half.italian at gmail.com (Sean DiZazzo) Date: Wed, 19 Aug 2009 21:04:47 -0700 (PDT) Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <92338aa1-0913-483a-b950-c73f0fdb0b1f@v37g2000prg.googlegroups.com> Message-ID: <4213ecf5-4981-48b4-a038-229cc330db32@p36g2000prn.googlegroups.com> On Aug 18, 4:58?pm, birdsong wrote: > On Aug 18, 3:18?pm, Derek Martin wrote: > > > > > On Tue, Aug 18, 2009 at 03:10:15PM -0500, Derek Martin wrote: > > > I have some simple threaded code... ?If I run this > > > with an arg of 1 (start one thread), it pegs one cpu, as I would > > > expect. ?If I run it with an arg of 2 (start 2 threads), it uses both > > > CPUs, but utilization of both is less than 50%. ?Can anyone explain > > > why? ? > > > Ah, searching while waiting for an answer (the e-mail gateway is a bit > > slow, it seems...) I discovered that the GIL is the culprate. > > Evidently this question comes up a lot. ?It would probably save a lot > > of time on the part of those who answer questions here, as well as > > those implementing solutions in Python, if whoever is maintaining the > > docs these days would put a blurb about this in the docs in big bold > > letters... ?Concurrency being perhaps the primary reason to use > > threading, essentially it means that Python is not useful for the > > sorts of problems that one would be inclined to solve they way my code > > works (or rather, was meant to). ?It would be very helpful to know > > that *before* one tried to implement a solution that way... especially > > for solutions significantly less trivial than mine. ;-) > > > Thanks > > > -- > > Derek D. Martinhttp://www.pizzashack.org/ > > GPG Key ID: 0x81CFE75D > > > ?application_pgp-signature_part > > < 1KViewDownload > > I would still watch that video which will explain a bit more about the > GIL. Thank you for the video! It's good to know, but it raises lots of other questions in my mind. Lots of examples would have helped. ~Sean From Brian.Mingus at colorado.edu Thu Aug 20 00:08:46 2009 From: Brian.Mingus at colorado.edu (Brian) Date: Wed, 19 Aug 2009 22:08:46 -0600 Subject: Read C++ enum in python In-Reply-To: <4a8b3342$0$25403$426a34cc@news.free.fr> References: <4a8b3342$0$25403$426a34cc@news.free.fr> Message-ID: <9839a05c0908192108w32148026r8112f1683010620a@mail.gmail.com> pygccxml http://www.language-binding.net/pygccxml/pygccxml.html It uses gccxml to compile your source code into xml, and then makes all of your source code available to you via a high level and convenient query interface in python. On Tue, Aug 18, 2009 at 5:03 PM, Ludo < olivier.anospamrnospamnnospamanospamenospamz at affaires.net> wrote: > Hello, > > I work in a very large project where we have C++ packages and pieces of > python code. > > I've been googleing for days but what I find seems really too complicated > for what I want to do. > > My business is, in python, to read enum definitions provided by the header > file of an c++ package. > Of course I could open the .h file, read the enum and transcode it by hand > into a .py file but the package is regularly updated and thus is the enum. > > My question is then simple : do we have : > - either a simple way in python to read the .h file, retrieve the > c++ enum and provide an access to it in my python script > - either a simple tool (in a long-term it would be automatically run > when the c++ package is compiled) generating from the .h file a .py file > containing the python definition of the enums ? > > Thank you for any suggestion. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 00:11:32 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 04:11:32 GMT Subject: How to create functors? References: <7xab1vl0qf.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 19 Aug 2009 18:42:32 -0700, Paul Rubin wrote: > Robert Dailey writes: >> I want to simply wrap a function up into an object so it can be called >> with no parameters. > > Nitpick: what you are asking for is called a closure. "Functor" means > something completely different. I'm glad somebody else noticed this. I would have said something about it myself, except I wasn't entirely sure my understanding of functor is correct. As near as I can tell, a functor is just an object which is callable like a function without actually being implemented as a function, e.g.: class Functor: def __call__(self): return None f = Functor() result = f() -- Steven From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 00:13:50 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 04:13:50 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> <87hbw4fxcq.fsf@benfinney.id.au> <87r5v8e9cu.fsf@benfinney.id.au> Message-ID: On Wed, 19 Aug 2009 10:51:08 -0700, Simon Forman wrote: > (FWIW, I've always admired Humpty Dumpty's attitude to words. "When I use a word," Humpty Dumpty said in rather a scornful tone, "it means just what I choose it to mean -- neither more nor less." When you say "admired", do you mean what the rest of us understand by "admired", or something completely different? How about "always", "attitude", "to" and "words"? For all I know, you're talking about baking a birthday cake for your cat, by which I mean shaving off all your hair, and by "hair" I mean "lunch" and by "shaving off" I mean "eating". > Have you > ever read R.A. Wilson's "Quantum Psychology"?) Perhaps I have, perhaps I haven't, it depends on who asks first. -- Steven From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 00:20:09 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 04:20:09 GMT Subject: How do I convert an iterator over bytes into a str? References: <3e3d2ebd-df8a-42a8-9420-0439a965a0d5@v2g2000vbb.googlegroups.com> <2c212222-0dac-4bd3-8130-5bd302d12dd5@c2g2000yqi.googlegroups.com> Message-ID: On Wed, 19 Aug 2009 20:04:12 -0700, alex23 wrote: > markscottwright wrote: >> Thanks Jan (and all other responders). ?I suppose I shouldn't be >> surprised - it's a known wart (http://wiki.python.org/moin/ >> PythonWarts), but it just looks so darn wrong. > > Don't forget that it's exceptionally easy to create your own mechanism > for doing this: > > def join(seq, sep): > return sep.join(map(str, seq)) Oh oh oh my brain hurts!!! Neither "seq" nor "sep" are real words, both are abbreviations, they differ by a single letter, and the two letters are mirror images of each other!!! This is a recipe for confusion when people get the order of sep and seq mixed up. Hopefully in real life code, you'd use a less easily confused function signature -- even just spelling out sequence and separator in full would reduce confusion to essentially zero. -- Steven From jsrat10 at gmail.com Thu Aug 20 00:34:22 2009 From: jsrat10 at gmail.com (jo) Date: Wed, 19 Aug 2009 21:34:22 -0700 (PDT) Subject: starting selenium rc server from python code Message-ID: Hi, Is there anyway to start the selenium rc server within python code? Thank you Jo From metolone+gmane at gmail.com Thu Aug 20 00:52:36 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Wed, 19 Aug 2009 21:52:36 -0700 Subject: Converting DD MM YYYY into YYYY-MM-DD? References: Message-ID: "Gilles Ganault" wrote in message news:rtqk859vm3rkdfor0gd2u2pq5sftl8mccm at 4ax.com... >I find it odd that the regex library can't handle European characters It can. Read the documentation about the re.LOCALE flag. -Mark From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 01:17:21 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 05:17:21 GMT Subject: starting selenium rc server from python code References: Message-ID: On Wed, 19 Aug 2009 21:34:22 -0700, jo wrote: > Hi, > Is there anyway to start the selenium rc server within python code? How would you start the selenium rc server outside of Python code? -- Steven From narkewoody at gmail.com Thu Aug 20 01:31:14 2009 From: narkewoody at gmail.com (Steven Woody) Date: Thu, 20 Aug 2009 13:31:14 +0800 Subject: Blank Line at Program Exit Message-ID: Hi, Any python program, even that does absolutely nothing in the code, will cause a blank line printed out when the program exit. What's the reason? Thanks. -- Life is the only flaw in an otherwise perfect nonexistence -- Schopenhauer narke public key at http://subkeys.pgp.net:11371 (narkewoody at gmail.com) -------------- next part -------------- An HTML attachment was scrubbed... URL: From sajmikins at gmail.com Thu Aug 20 01:44:02 2009 From: sajmikins at gmail.com (Simon Forman) Date: Wed, 19 Aug 2009 22:44:02 -0700 (PDT) Subject: #elements of seq A in seq B References: <7c16abe1-7502-432a-acff-aff95c22a8ac@q14g2000vbi.googlegroups.com> <285422cf-9a8d-43ef-a5ac-a04a3ce9a002@a39g2000pre.googlegroups.com> Message-ID: <02165547-8143-4f46-a74e-babe9145c033@s6g2000vbp.googlegroups.com> On Aug 19, 11:34?pm, John Machin wrote: > On Aug 20, 12:12?pm, Simon Forman wrote: > > > On Aug 19, 8:17?pm, "Jan Kaliszewski" wrote: > > > If you mean: to count non overlaping occurences of string A in B > > > -- simply: > > > > ? ?B.count(A) > > > You don't want to use count() in a case like this because it iterates > > through B len(A) times, i.e. this algorithm is O(A x B). > > There's seems to be multiple confusion here. Jan was talking about > counting non-overlapping occurrences of string A in [string] B. In > that case B.count(A) is nowhere near O(A*B)... in fact in reasonable > cases it is sub-linear i.e. O(B/A) > > Seehttp://svn.python.org/view/python/trunk/Objects/stringlib/fastsearch.... > > And even a naive implementation of str.count() would not "iterate > through B len(A) times". > > and list.count() can't be used on its own to solve Neal's problem; its > arg is a single element so it would have to be wrapped in a loop: sum > (B.count(a) for a in A) which would of course be O(A*B) First, thanks for pointing out str.count(). I didn't know of it and I didn't notice that that was what was being used in Jan's code. (It's blindingly obvious-- now that you've pointed it out. :] ) Second, I was referring to this: dict((element, B.count(element)) for element in A) not B.count(A). Sorry for not interspersing my comment better. Regards, ~Simon From rylesny at gmail.com Thu Aug 20 01:46:17 2009 From: rylesny at gmail.com (ryles) Date: Wed, 19 Aug 2009 22:46:17 -0700 (PDT) Subject: Setuptools - help! References: <9fauk6-t24.ln1@phoenix.fire> Message-ID: <9b2b4500-3670-40b7-8148-57448500c074@p15g2000vbl.googlegroups.com> On Aug 7, 3:04?pm, Peter Chant wrote: > Robert Kern wrote: > > You need to put main.py into the pphoto package. > > > $ mkdir pphoto/ > > $ mv main.py pphoto/ > > $ touch pphoto/__init__.py > > Thanks, it worked. ?Any ideas how to run the resulting scripts without > installing or running as root? > > Pete > > --http://www.petezilla.co.uk If you are using Python 2.6+ you have your own site-packages directory, e.g. ~/.local/lib/python2.6/site-packages. So, if this package is only for your own use, you can use easy_install's --install- dir option to have setuptools install it there, and can also set -- script-dir to ~/bin, where your console script will go. This, and other options are discussed here: http://peak.telecommunity.com/DevCenter/EasyInstall#custom-installation-locations From __peter__ at web.de Thu Aug 20 02:10:28 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Aug 2009 08:10:28 +0200 Subject: Dictionary from a list References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: Jan Kaliszewski wrote: > 20-08-2009 o 02:05:57 Jan Kaliszewski wrote: > >> Or probably better: >> >> from itertools import islice, izip >> dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2))) > > Or similarly, perhaps more readable: > > iterator = iter(li) > dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2)) I just can't stop posting this one: >>> from itertools import izip >>> it = iter([1,2,3,4,5,6]) >>> dict(izip(it, it)) {1: 2, 3: 4, 5: 6} I really tried, but yours drove me over the edge. Peter From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 03:05:41 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 07:05:41 GMT Subject: Dictionary from a list References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: On Thu, 20 Aug 2009 08:10:28 +0200, Peter Otten wrote: > I just can't stop posting this one: > >>>> from itertools import izip >>>> it = iter([1,2,3,4,5,6]) >>>> dict(izip(it, it)) > {1: 2, 3: 4, 5: 6} > > I really tried, but yours drove me over the edge. If you want something to drive you over the edge: >>> alist = [1, 2, 3, 4, 5, 6] >>> dict(apply(zip, map(lambda n: map(lambda t: t[1], filter(lambda t: ((not (t[0]%2)) == 1) == n, enumerate(alist))), range(1, -1, -1)))) {1: 2, 3: 4, 5: 6} Enjoy :) -- Steven From pierre.gaillard at gmail.com Thu Aug 20 03:18:23 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Thu, 20 Aug 2009 00:18:23 -0700 (PDT) Subject: regular expression Message-ID: Hello, I would like to change the string "(1 and (2 or 3))" by "(x[1] & (x [2] || x[3]))" using regular expression... Anyone can help me ? Thanks. From rami.chowdhury at gmail.com Thu Aug 20 03:34:38 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 20 Aug 2009 00:34:38 -0700 Subject: How to create functors? In-Reply-To: References: <7xab1vl0qf.fsf@ruckus.brouhaha.com> Message-ID: <223ACEB9-09FE-4BBB-8B1D-25C66ABB46E3@gmail.com> > As near as I can tell, a functor is just an object which is > callable like a function I believe that's how they're defined in the C++ world, in which, of course, functions aren't first-class objects... ------------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Aug 19, 2009, at 21:11 , Steven D'Aprano wrote: > On Wed, 19 Aug 2009 18:42:32 -0700, Paul Rubin wrote: > >> Robert Dailey writes: >>> I want to simply wrap a function up into an object so it can be >>> called >>> with no parameters. >> >> Nitpick: what you are asking for is called a closure. "Functor" >> means >> something completely different. > > > I'm glad somebody else noticed this. I would have said something > about it > myself, except I wasn't entirely sure my understanding of functor is > correct. As near as I can tell, a functor is just an object which is > callable like a function without actually being implemented as a > function, e.g.: > > class Functor: > def __call__(self): > return None > > f = Functor() > result = f() > > > > -- > Steven > -- > http://mail.python.org/mailman/listinfo/python-list From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 03:40:06 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 07:40:06 GMT Subject: regular expression References: Message-ID: On Thu, 20 Aug 2009 00:18:23 -0700, Pierre wrote: > Hello, > > I would like to change the string "(1 and (2 or 3))" by "(x[1] & (x > [2] || x[3]))" using regular expression... Anyone can help me ? Do you mean you want to change the string into "(x[1] & (x[2] || x[3]))" ? Does it have to be using regular expressions? Would this be good enough? >>> s = "(1 and (2 or 3))" >>> for c in '123': ... s = s.replace(c, 'x[%s]'%c) ... >>> s = s.replace('or', '||') >>> s = s.replace('and', '&') >>> s '(x[1] & (x[2] || x[3]))' -- Steven From __peter__ at web.de Thu Aug 20 03:45:37 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Aug 2009 09:45:37 +0200 Subject: Dictionary from a list References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: Steven D'Aprano wrote: > On Thu, 20 Aug 2009 08:10:28 +0200, Peter Otten wrote: > > >> I just can't stop posting this one: >> >>>>> from itertools import izip >>>>> it = iter([1,2,3,4,5,6]) >>>>> dict(izip(it, it)) >> {1: 2, 3: 4, 5: 6} >> >> I really tried, but yours drove me over the edge. > > If you want something to drive you over the edge: I meant that figuratively... >>>> alist = [1, 2, 3, 4, 5, 6] >>>> dict(apply(zip, map(lambda n: map(lambda t: t[1], filter(lambda t: > ((not (t[0]%2)) == 1) == n, enumerate(alist))), range(1, -1, -1)))) > {1: 2, 3: 4, 5: 6} ...originally. > Enjoy :) Not ;) From python.list at tim.thechases.com Thu Aug 20 03:47:25 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 20 Aug 2009 02:47:25 -0500 Subject: Dictionary from a list In-Reply-To: References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: <4A8CFF8D.9080405@tim.thechases.com> Peter Otten wrote: >>>> it = iter([1,2,3,4,5,6]) >>>> dict(izip(it, it)) > {1: 2, 3: 4, 5: 6} Zip(it). Zip(it) good. it's-3:00am-and-i-seriously-need-to-sleep'ly yers... -tkc From __peter__ at web.de Thu Aug 20 03:56:07 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Aug 2009 09:56:07 +0200 Subject: regular expression References: Message-ID: Pierre wrote: > I would like to change the string "(1 and (2 or 3))" by "(x[1] & (x > [2] || x[3]))" using regular expression... > Anyone can help me ? >>> re.compile(r"(\d+)").sub(r"x[\1]", "(1 and (2 or 3))") '(x[1] and (x[2] or x[3]))' >>> re.compile("and|or").sub(lambda m, d={"and":"&", "or":"||"}: d[m.group()], _) '(x[1] & (x[2] || x[3]))' Peter From catalinfest at gmail.com Thu Aug 20 04:23:39 2009 From: catalinfest at gmail.com (catafest) Date: Thu, 20 Aug 2009 01:23:39 -0700 (PDT) Subject: PIL and Python References: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> Message-ID: On my photo jpg i have this : Image Type: jpeg (The JPEG image format) Width: 1224 pixels Height: 1632 pixels Camera Brand: Sony Ericsson Camera Model: W810i Date Taken: 2009:07:09 08:16:21 Exposure Time: 1/19 sec. ISO Speed Rating: 320 Flash Fired: Flash did not fire, compulsory flash mode. Metering Mode: Center-Weighted Average Software: R4EA031 prgCXC1250321_ORANGE_HN 4.5 This is the data i want edit it to make some copyright for my site. From http Thu Aug 20 04:36:14 2009 From: http (Paul Rubin) Date: 20 Aug 2009 01:36:14 -0700 Subject: How to create functors? References: <7xab1vl0qf.fsf@ruckus.brouhaha.com> Message-ID: <7xmy5uanlt.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > As near as I can tell, a functor is just an object which is > callable like a function without actually being implemented as a > function, e.g.: No it's not anything like that either, at least as I'm used to the term in programming or in mathematics. Maybe it's used other ways though. As I'm used to it, it's a feature of certain static type systems. The notion isn't that useful in Python but you could translate it something like this: imagine that the "list" datatype has a couple extra operations: # lift_value turns a normal value from a base type to a 1-element list list.lift_value(x) = [x] # lift_function turns a function on a base type to a higher order # function that operates on a whole list list.lift_function(f) = partial(map, f) Then given a function like def square(x): return x*x you could say lifted_square = list.lifted_function(square) print lifted_square([1,2,3,4,5]) and get [1,4,9,16,25]. Similarly if you had some other type (like a tree data structure), that type could also support a map-like operation so you could lift functions to it (lifting a function and applying it to a tree like [1,[2,3],4] would result in [1,[4,9],16] or whatever). If I remember properly, for type t to be a functor it needs the above two lifting operations, with the property that for a given function f, t.lifted_value(f(x)) = (t.lifted_function(f))(t.lifted_value(x)) I guess this explanation isn't going that well but basically in a statically typed language you'd use functors to convert the signatures of functions to versions that operate on higher types. The idea comes from ML and is used explicitly in Haskell, and I think some of the C++ standard template library can be explained in terms of functors. For the mathematical concept of functors and how they relate to programming (at least Haskell's version), see: http://en.wikibooks.org/Haskell/Category_theory From steven at REMOVE.THIS.cybersource.com.au Thu Aug 20 05:25:48 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 09:25:48 GMT Subject: How to create functors? References: <7xab1vl0qf.fsf@ruckus.brouhaha.com> <7xmy5uanlt.fsf@ruckus.brouhaha.com> Message-ID: On Thu, 20 Aug 2009 01:36:14 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> As near as I can tell, a functor is just an object which is callable >> like a function without actually being implemented as a function, e.g.: > > No it's not anything like that either, at least as I'm used to the term > in programming or in mathematics. Maybe it's used other ways though. According to Wikipedia, functor can be used as a synonym for "function object": http://en.wikipedia.org/wiki/Function_object which is what I was thinking of. So it seems there are at least two meanings for the word, neither of which seems to apply to this thread :) > As I'm used to it, it's a feature of certain static type systems. The > notion isn't that useful in Python I find the Haskell page entirely opaque and unintelligible. Well, perhaps not *entirely* opaque, but pretty close: it assumes a mathematical sophistication that I don't think I even had when I was getting my maths degree, let alone can remember two decades later. (Pity the poor VB coders wondering what Haskell is good for...) The Wikipedia page is a little better, but it's section on Examples is laughable -- the examples are as unintelligible to this reader as the description before them. But let me try an example to see if I've got it right: class Int2StrFunctor: def map1(self, n): if type(n) is not int: raise TypeError('argument must be an int') return "-"*n def map2(self, f): if type(f) is not type(lambda: None): raise TypeError('argument must be a function') # assume f takes an int, and returns another int def inner(n): return self.map1(f(n)) return inner The functor can take an int and return a string: >>> F = Int2StrFunctor() # F is a functor >>> F.map1(3) '---' It can also take a function (of int -> int) and return a new function (int -> str): >>> def myfunc(n): ... return n+2 ... >>> f = F.map2(myfunc) >>> f(3) '-----' >>> f(4) '------' There's nothing special about the methods map1() and map2(), I could call them anything I like, or even do this: >>> def __call__(self, arg): ... if type(arg) is int: ... return self.map1(arg) ... else: ... return self.map2(arg) ... >>> Int2StrFunctor.__call__ = __call__ >>> >>> F(2) '--' >>> F(myfunc)(0) '--' There are some technical restrictions on functors, relating to the sorts of functions and types (strictly "categories") they can accept, presumably to make them mathematically well-behaved. Have I got it correct? -- Steven From nitebirdz at sacredchaos.com Thu Aug 20 05:46:34 2009 From: nitebirdz at sacredchaos.com (Nitebirdz) Date: Thu, 20 Aug 2009 11:46:34 +0200 Subject: What file is foo in package bar in ? In-Reply-To: References: Message-ID: <20090820094633.GD7136@sevilla.sacredchaos.com> On Thu, Aug 20, 2009 at 01:06:00AM +0200, Christian Heimes wrote: > northof40 wrote: >> Given an arbitary package is there some programmatic way to 'ask' what >> file the method/function is implemented in ? > > Indeed, the inspect module contains several useful functions for the > job, for example > http://docs.python.org/library/inspect.html#inspect.getfile > Stupid question from someone who ignores it all: since the OP is reading code from an existing tree in order to learn from it, wouldn't it make more sense to use something like Cscope? Assuming it works with Python, of course. If it doesn't, is there a similar tool that can be used? A related question too is whether any of these tools actually help in an object-oriented environment. http://cscope.sourceforge.net/ http://www.linux.com/archive/feature/114237 From enleverLesX_XXmcX at XmclavXeauX.com Thu Aug 20 05:54:05 2009 From: enleverLesX_XXmcX at XmclavXeauX.com (Michel Claveau - MVP) Date: Thu, 20 Aug 2009 11:54:05 +0200 Subject: difference between 2 arrays References: Message-ID: <4a8d1d3f$0$23447$ba4acef3@news.orange.fr> (envoy? via news:\\news.wanadoo.fr\comp.lang.python) Hi! Yes, the module sets is written, in doc, like "deprecated". But: - sets exist in Python 2.6 (& 2.5 or 2.4) - documentation of sets (module) is better tha, documentation of set (builtin) The best: read the documentaion of the module, and use the builtin... @-salutations -- MCI From ashwin.u.rao at nokia.com Thu Aug 20 06:02:26 2009 From: ashwin.u.rao at nokia.com (ashwin.u.rao at nokia.com) Date: Thu, 20 Aug 2009 12:02:26 +0200 Subject: Zipimport leaks memory? Message-ID: <6CC019B5D220A147932441E798B252B910B0193FEF@NOK-EUMSG-05.mgdnok.nokia.com> Hi, We are currently trying to identify and fix all the memory leaks by just doing Py_Initialize-PyRun_SimpleFile(some simple script)-Py_Finalize and found that there are around 70 malloc-ed blocks which are not freed. One of the significant contributor to this number is the 'files' object in ZipImporter. I am not able to identify the reason for this leak and was wondering if anyone on this list would help me out here. So, here goes : Since we have a zip file in our sys.path, this object is initialized and added to the zip_directory_cache dict during Py_Initialize. One point to note here is that there is no DECREF on the 'files' object after adding it to the zip_directory_cache dict. When a module in a directory is imported(encoding.alias) then the reference count of 'files' is increased. When this module is unloaded during Py_Finalize-PyImport_Cleanup, the ref count of files object is decremented properly. So at the end of Py_Finalize the files object still has one reference count which is a result of it being an entry in the zip_directory_cache. To summarize : ZipImporter->files - zipimporter_init function: Py_Initialize - Read files from zip - ref_count -1 Add files to zip_directory_cache - ref count - 2 Import some modules from different directory in zip - ref count - 3 Py_Finalze - PyImport_Cleanup - sub-directory - ref-count - 2 PyImport_Cleanup - main directory - ref-count - 1 So the reference count of 'files' is still 1 after Py_Finalize. The zip_directory_cache is the dict that has this 'files' object and this dict is added to the module during zipimport module initialization. This dict is destroyed during _PyModule_Clear(called by PyImport_Cleanup) but the 'files' object's reference count is not decremented. Please excuse me if I have misinterpreted the whole logic. Any pointers towards solving this would be great. Thank you. ~Ashwin From iain at kandaba.com Thu Aug 20 06:19:56 2009 From: iain at kandaba.com (Iain) Date: Thu, 20 Aug 2009 03:19:56 -0700 (PDT) Subject: Polling a net address Message-ID: <99ddf4e1-d327-4fb1-aee4-aa881de3b3af@d23g2000vbm.googlegroups.com> Hi All, I'm writing a system tray application for windows, and the app needs to poll a remote site at a pre-defined interval, and then process any data returned. The GUI needs to remain responsive as this goes on, so the polling needs to be done in the background. I've been looking into Twisted as a way of achieving this, but can't seem to get anything to loop successfully. Does anyone have any pointers that they might be able to give me? TIA. From baaluaanand at gmail.com Thu Aug 20 06:24:15 2009 From: baaluaanand at gmail.com (baalu aanand) Date: Thu, 20 Aug 2009 03:24:15 -0700 (PDT) Subject: difference between raw_input() and input() Message-ID: <3c91915d-bcb1-4ea9-9b37-6b30ea0588a0@e34g2000vbm.googlegroups.com> Hi, I have used both raw_input() and input() for a same input value. But these gives different output. I have listed below what actually I have done >>> a = raw_input("===>") ===> 023 >>> a '023' I have given the same value for the input() but it gives 19 as result >>> a = input("===>") ===> 023 >>> a 19 Is there anything hide within this. Please illustrate the difference between raw_input() and input() Thanks in advance Baalu From clp2 at rebertia.com Thu Aug 20 06:49:42 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 20 Aug 2009 03:49:42 -0700 Subject: difference between raw_input() and input() In-Reply-To: <3c91915d-bcb1-4ea9-9b37-6b30ea0588a0@e34g2000vbm.googlegroups.com> References: <3c91915d-bcb1-4ea9-9b37-6b30ea0588a0@e34g2000vbm.googlegroups.com> Message-ID: <50697b2c0908200349i5e0a13aeq63252c162fbfe492@mail.gmail.com> On Thu, Aug 20, 2009 at 3:24 AM, baalu aanand wrote: > Hi, > > ? ? I have used both raw_input() and input() for a same input value. > But these gives different output. > > ? ? I have listed below what actually I have done > > ? ? ? ? ? ?>>> a = raw_input("===>") > ? ? ? ? ? ? ? ? ? ===> 023 > ? ? ? ? ? ?>>> a > ? ? ? ? ? ? ? ? ? ?'023' > > ? ? I have given the same value for the input() but it gives 19 as > result > ? ? ? ? ? ?>>> a = input("===>") > ? ? ? ? ? ? ? ? ? ===> ?023 > ? ? ? ? ? ?>>> a > ? ? ? ? ? ? ? ? ? ?19 > > ?Is there anything hide within this. Please illustrate the difference > between raw_input() and input() input() === eval(raw_input()) eval("023") --> int("23", 8) --> 19 [an integer, not a string] raw_input() /always/ returns a string. Never use input() in Python 2.x. In Python 3, raw_input() was renamed to input() because it's a better name and the old input() was hardly ever used (correctly). Cheers, Chris -- http://blog.rebertia.com From ashagow at gmail.com Thu Aug 20 06:50:27 2009 From: ashagow at gmail.com (Asha Gowda) Date: Thu, 20 Aug 2009 16:20:27 +0530 Subject: pexpect on QNX platform Message-ID: <375470f50908200350n57ce3e7csccd83ddad08e7de9@mail.gmail.com> Hi, I found that pexpect is available only for linux. But we need to port to QNX, Is pexpect is available? If yes, where can I find it. Thanks, -------------- next part -------------- An HTML attachment was scrubbed... URL: From maxthemouse at googlemail.com Thu Aug 20 07:01:20 2009 From: maxthemouse at googlemail.com (MaxTheMouse) Date: Thu, 20 Aug 2009 04:01:20 -0700 (PDT) Subject: PIL and Python References: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> Message-ID: On Aug 20, 10:23?am, catafest wrote: > On my photo jpg i have this : > > Image Type: jpeg (The JPEG image format) > Width: 1224 pixels > Height: 1632 pixels > Camera Brand: Sony Ericsson > Camera Model: W810i > Date Taken: 2009:07:09 08:16:21 > Exposure Time: 1/19 sec. > ISO Speed Rating: 320 > Flash Fired: Flash did not fire, compulsory flash mode. > Metering Mode: Center-Weighted Average > Software: R4EA031 ? ? prgCXC1250321_ORANGE_HN 4.5 > > This is the data i want edit it to make some copyright for my site. I don't know about PIL but you might want to try exif.py. http://sourceforge.net/projects/exif-py/ From ndbecker2 at gmail.com Thu Aug 20 07:01:29 2009 From: ndbecker2 at gmail.com (Neal Becker) Date: Thu, 20 Aug 2009 07:01:29 -0400 Subject: #elements of seq A in seq B References: Message-ID: Jan Kaliszewski wrote: > 20-08-2009 o 01:19:24 Neal Becker wrote: > >> What would be a time efficient way to count the number of occurrences of >> elements of sequence A in sequence B? (in this particular case, these >> sequences are strings, if that matters). > > If you mean: to count occurences of each element of A (separately) in B... > > Hm, maybe something like this: > > # result as a dict {: , ...} > dict((element, B.count(element)) for element in A) > > > If you mean: to count non overlaping occurences of string A in B > -- simply: > > B.count(A) > > > Regards, > *j > I meant #occurrences of characters from the set A in string B From muhammadsalman712 at gmail.com Thu Aug 20 07:17:41 2009 From: muhammadsalman712 at gmail.com (Muhammad Salman) Date: Thu, 20 Aug 2009 04:17:41 -0700 (PDT) Subject: New Windows Mobile Smartphones from I-mate Message-ID: Windows Mobile smart phone device manufacturer, i-mate has shown off its latest models -the Ultimate 9502 and the Ultimate 8502.for other details http://infomobilepk.blogspot.com From __peter__ at web.de Thu Aug 20 08:05:12 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 20 Aug 2009 14:05:12 +0200 Subject: #elements of seq A in seq B References: Message-ID: Neal Becker wrote: > I meant #occurrences of characters from the set A in string B If a contains "few" characters: n = sum(b.count(c) for c in a) If a contains "many" characters: identity = "".join(map(chr, range(256))) n = len(b) - len(b.translate(identity, a)) Peter From ballacky13 at gmail.com Thu Aug 20 08:07:31 2009 From: ballacky13 at gmail.com (Yan Jian) Date: Thu, 20 Aug 2009 20:07:31 +0800 Subject: Hi everyone, I get a problem when using binhex module Message-ID: Below is what I copy from the Internet: import binhex import sys infile = "in.txt" binhex.binhex(infile, sys.stdout) Every time I try to run this script, I get a message saying Traceback (most recent call last): File "D:\eclipse_workspace\encode\src\binhex.sample.py", line 6, in import binhex File "C:\Python25\lib\binhex.py", line 12, in # easy interface should work "as expected" on any platform. TypeError: 'module' object is not callable Does anyone encounter similar situation. Thank you for your help? -------------- next part -------------- An HTML attachment was scrubbed... URL: From jelleferinga at gmail.com Thu Aug 20 08:19:42 2009 From: jelleferinga at gmail.com (jelle) Date: Thu, 20 Aug 2009 05:19:42 -0700 (PDT) Subject: pypi category Message-ID: Hi, Would someone be able to inform me how a category can be added to the pypy list of categories? I'd like to add a CAD & Geometry category. ( I develop PythonOCC, wrappers for the OpenCASCADE CAD kernel, which is why ) Thanks! -jelle From contact at xavierho.com Thu Aug 20 08:20:32 2009 From: contact at xavierho.com (Xavier Ho) Date: Thu, 20 Aug 2009 22:20:32 +1000 Subject: Hi everyone, I get a problem when using binhex module In-Reply-To: References: Message-ID: <2d56febf0908200520n697ae725v4e0a2abcc3a10c11@mail.gmail.com> On Thu, Aug 20, 2009 at 10:07 PM, Yan Jian wrote: > > Does anyone encounter similar situation. Thank you for your help? > Yeah, in Python 3.1 I get this: Traceback (most recent call last): File "test.py", line 6, in binhex.binhex(file, sys.stdout) File "c:\Python31\lib\binhex.py", line 228, in binhex ofp = BinHex(finfo, out) File "c:\Python31\lib\binhex.py", line 149, in __init__ ofp.write(b'(This file must be converted with BinHex 4.0)\r\r:') TypeError: write() argument 1 must be str, not bytes Python 2.6.2 runs fine though: :"QPZ,R4iG!"849K82j!%!*!&&3#3"1#$6A*bB@%Z$3T0FR*KB5iJ6A*bB@%ZY@% !!!: I never used binhex however, so someone else might have a better insight. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From aaron.watters at gmail.com Thu Aug 20 08:21:54 2009 From: aaron.watters at gmail.com (Aaron Watters) Date: Thu, 20 Aug 2009 05:21:54 -0700 (PDT) Subject: Data visualization in Python References: Message-ID: <15325820-dae0-4ba4-b25a-d33e17908fde@p15g2000vbl.googlegroups.com> On Aug 17, 3:10?pm, kj wrote: > I'm looking for a good Python package for visualizing > scientific/statistical data. ?(FWIW, the OS I'm interested in is > Mac OS X). Please take a look at the amcharts embedding in WHIFF http://aaron.oirt.rutgers.edu/myapp/amcharts/doc WHIFF is a collection of support services for WSGI applications which allows applications to be composed by "dropping" dynamic pages into container directories. http://aaron.oirt.rutgers.edu/myapp/docs/W.intro thanks, -- Aaron Watters === Sisyphus got ripped. From andre.roberge at gmail.com Thu Aug 20 09:11:30 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Thu, 20 Aug 2009 06:11:30 -0700 (PDT) Subject: IDLE is not as interactive as Maple References: <7aa51a98-965c-4c74-a3b5-650140f1d589@v23g2000pro.googlegroups.com> Message-ID: <399082f9-3765-46dc-b71e-618e75256cf9@d34g2000vbm.googlegroups.com> On Aug 20, 12:22?am, laser wrote: > In the future, will Python provide programe enviroment like Maple > does? A quick, flip answer: perhaps if you design one? Tools for Python are designed by people scratching an itch. That being said, have a look at reinteract: http://www.reinteract.org/trac/wiki/Tutorial/Introduction > In Maple, you can remove anything unneeded in the editor. And > the code execution order are not necessary in one direction. You can > run any command line on the screen by > push Enter key. These functions gave a lot of flaxibility for users to > start with programming something. Andr? From benjamin.kaplan at case.edu Thu Aug 20 09:29:45 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 20 Aug 2009 09:29:45 -0400 Subject: IDLE is not as interactive as Maple In-Reply-To: <7aa51a98-965c-4c74-a3b5-650140f1d589@v23g2000pro.googlegroups.com> References: <7aa51a98-965c-4c74-a3b5-650140f1d589@v23g2000pro.googlegroups.com> Message-ID: On Wed, Aug 19, 2009 at 11:22 PM, laser wrote: > In the future, will Python provide programe enviroment like Maple > does? In Maple, you can remove anything unneeded in the editor. And > the code execution order are not necessary in one direction. You can > run any command line on the screen by > push Enter key. These functions gave a lot of flaxibility for users to > start with programming something. > -- > http://mail.python.org/mailman/listinfo/python-list > Maple is a very expensive IDE that happens to have a language that goes with it. Python is a language that happens to come with a free text editor/integrated shell. For languages like Mathematica and Maple, the IDE is everything- you almost never use the language without the integrated IDE. Python focuses more on language features. IDLE is not supposed to be a great editor on the level of Visual Studio or Maple, it's supposed to be a convenient way to run your code for people who are scared of the command line. I would venture a guess that very few people on this list use IDLE for their coding. Based on previous answers to questions, most people use Eclipse/PyDev, Netbeans, Wing, Komodo, emacs, and vim. Wing and Komodo are the only Python-specific IDEs on that list and neither of them are free (though the have stripped-down free versions). If you want a better editor, use one of those. From haricibi83 at gmail.com Thu Aug 20 09:44:52 2009 From: haricibi83 at gmail.com (hari) Date: Thu, 20 Aug 2009 06:44:52 -0700 (PDT) Subject: Python libexpat and EXPAT are same/Different? Message-ID: Hi all, Am very new to XML, I have a query, Does Python libexpat and EXPAT are same or they are diffrent? Thanks in advance. Regards, Hari From stefan_ml at behnel.de Thu Aug 20 10:05:21 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 20 Aug 2009 16:05:21 +0200 Subject: Python libexpat and EXPAT are same/Different? In-Reply-To: References: Message-ID: <4a8d5821$0$30236$9b4e6d93@newsspool1.arcor-online.net> hari wrote: > Am very new to XML, I have a query, Does Python libexpat and EXPAT > are same or they are diffrent? Depends on what you mean with "EXPAT". Python's expat module that you can find in the standard library is the well known non-validating XML parser originally written by James Clark. BTW, if you are new to XML and want to use it in Python, you might want to start with the xml.etree package. Stefan From jelleferinga at gmail.com Thu Aug 20 10:10:26 2009 From: jelleferinga at gmail.com (jelle) Date: Thu, 20 Aug 2009 07:10:26 -0700 (PDT) Subject: pypi category References: Message-ID: The pypi list of categories, sorry... From sturlamolden at yahoo.no Thu Aug 20 10:25:59 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Thu, 20 Aug 2009 07:25:59 -0700 (PDT) Subject: IDLE is not as interactive as Maple References: <7aa51a98-965c-4c74-a3b5-650140f1d589@v23g2000pro.googlegroups.com> Message-ID: On 19 Aug, 20:22, laser wrote: > In the future, will Python provide programe enviroment like Maple > does? You might be looking for SAGE. http://www.sagemath.org/ From steve at REMOVE-THIS-cybersource.com.au Thu Aug 20 10:54:04 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 14:54:04 GMT Subject: difference between raw_input() and input() References: <3c91915d-bcb1-4ea9-9b37-6b30ea0588a0@e34g2000vbm.googlegroups.com> Message-ID: <029d53bb$0$25987$c3e8da3@news.astraweb.com> On Thu, 20 Aug 2009 03:24:15 -0700, baalu aanand wrote: > Hi, > > I have used both raw_input() and input() for a same input value. > But these gives different output. > > I have listed below what actually I have done > > >>> a = raw_input("===>") > ===> 023 > >>> a > '023' > > I have given the same value for the input() but it gives 19 as > result > >>> a = input("===>") > ===> 023 > >>> a > 19 > > Is there anything hide within this. Please illustrate the difference > between raw_input() and input() Did you look them up in the documentation? Did you try the interactive help? help(input) help(raw_input) Perhaps you could try some further experiments: >>> raw_input() hello world 'hello world' >>> input() hello world Traceback (most recent call last): File "", line 1, in File "", line 1 hello world ^ SyntaxError: unexpected EOF while parsing Does that give you a hint as to what is happening? How about this? >>> 07 7 >>> 08 File "", line 1 08 ^ SyntaxError: invalid token >>> 010 8 >>> oct(8) 010 -- Steven From davea at ieee.org Thu Aug 20 11:08:07 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 20 Aug 2009 11:08:07 -0400 Subject: Hi everyone, I get a problem when using binhex module In-Reply-To: References: Message-ID: <4A8D66D7.4070006@ieee.org> Yan Jian wrote: > Below is what I copy from the Internet: > > import binhex > import sys > > infile = "in.txt" > > binhex.binhex(infile, sys.stdout) > > Every time I try to run this script, I get a message saying > > Traceback (most recent call last): > File "D:\eclipse_workspace\encode\src\binhex.sample.py", line 6, in > > import binhex > File "C:\Python25\lib\binhex.py", line 12, in > # easy interface should work "as expected" on any platform. > TypeError: 'module' object is not callable > > Does anyone encounter similar situation. Thank you for your help? > > First question: Are you running Python2.5 ? And do you actually have it installed in c:\Python25 directory? Do you in fact have 5 blank lines in front of the "import binhex" line? Assuming yes for all of those, the only cause I can figure for that particular error string is that binhex.pyc is out of synch with binhex.py. To test that theory, try deleting it (in general that means renaming it temporarily, so you could restore it if I'm wrong), and running again. I would also add the lines: import sys print sys.version in front of the import, just to make sure you're running what you think you are. And then I'd get a console prompt, change directory to D:\eclipse_workspace\encode\src\binhex and run sample.py from that command prompt. Compare the two version strings, and see if anything's different in the two error messages. DaveA From manu3d at gmail.com Thu Aug 20 11:16:51 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 20 Aug 2009 08:16:51 -0700 (PDT) Subject: Executing untrusted code References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com> Message-ID: Sorry for digging this back from the grave. I've had to chew on it for a little while. On Aug 8, 1:40?am, Nobody wrote: > If you want to support restricted execution within a language, it > has to be built into the language from day one. Trying to bolt it > on later is a fool's errand. Fair enough. In this context, let's say I do this: import __builtin__ import imp originalBuiltins = imp.new_module("OriginalBuiltins") def readOnlyOpen(filename): return originalBuiltins.open(filename, "r") __builtin__.open = readOnlyOpen exec(anUntrustedString, {}) In what ways would the untrusted string be able to obtain the original, built-in open function and open a file for writing? Manu From lists at cheimes.de Thu Aug 20 11:26:33 2009 From: lists at cheimes.de (Christian Heimes) Date: Thu, 20 Aug 2009 17:26:33 +0200 Subject: Executing untrusted code In-Reply-To: References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com> Message-ID: <4A8D6B29.3040800@cheimes.de> Emanuele D'Arrigo write: > In what ways would the untrusted string be able to obtain the > original, built-in open function and open a file for writing? Yes, if you know some tricks: >>> [cls for cls in object.__subclasses__() if cls.__name__ == 'file'][0] Christian From rami.chowdhury at gmail.com Thu Aug 20 11:27:24 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 20 Aug 2009 08:27:24 -0700 Subject: Executing untrusted code In-Reply-To: References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com> Message-ID: They could, of course, use the file object constructor directly, e.g.: f = file("/etc/passwd", "w") On Thu, 20 Aug 2009 08:16:51 -0700, Emanuele D'Arrigo wrote: > Sorry for digging this back from the grave. > I've had to chew on it for a little while. > > On Aug 8, 1:40?am, Nobody wrote: >> If you want to support restricted execution within a language, it >> has to be built into the language from day one. Trying to bolt it > on >> later is a fool's errand. > > Fair enough. In this context, let's say I do this: > > import __builtin__ > import imp > originalBuiltins = imp.new_module("OriginalBuiltins") > > def readOnlyOpen(filename): > return originalBuiltins.open(filename, "r") > > __builtin__.open = readOnlyOpen > > exec(anUntrustedString, {}) > > In what ways would the untrusted string be able to obtain the > original, built-in open function and open a file for writing? > > Manu > -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From narkewoody at gmail.com Thu Aug 20 12:06:55 2009 From: narkewoody at gmail.com (Steven Woody) Date: Fri, 21 Aug 2009 00:06:55 +0800 Subject: line completion Message-ID: Hi, I wrote a program that takes some user input. Many inputs are quit often used by user, so when a user launch the program, and type in "The Sha", he wants to get "wshank Redemption" displayed automatically in reversed color (black text on white background) along his cursor. When he decided to use "The Shawshank Redemption", he just press the enter key, otherwise, he type in other words anyway. My question is, is there any module that can easy the implementation of this feature? Thanks. -- Life is the only flaw in an otherwise perfect nonexistence -- Schopenhauer narke public key at http://subkeys.pgp.net:11371 (narkewoody at gmail.com) -------------- next part -------------- An HTML attachment was scrubbed... URL: From inigoserna at gmail.com Thu Aug 20 12:36:05 2009 From: inigoserna at gmail.com (=?UTF-8?B?ScOxaWdvIFNlcm5h?=) Date: Thu, 20 Aug 2009 18:36:05 +0200 Subject: ncurses getch & unicode (was: decoding keyboard input when using curses) Message-ID: <65a1d6f80908200936g18b235fcw49d0047168cf9548@mail.gmail.com> Hello, I have the same problem mentioned in http://groups.google.com/group/comp.lang.python/browse_thread/thread/c70c80cd9bc7bac6?pli=1some months ago. Python 2.6 program which uses ncurses module in a terminal configured to use UTF-8 encoding. When trying to get input from keyboard, a non-ascii character (like ?) is returned as 2 integers < 255, needing 2 calls to getch method to get both. These two integers \xc3 \xa7 forms the utf-8 encoded representation of ? character. ncurses get_wch documentation states the function should return an unique integer > 255 with the ordinal representation of that unicode char encoded in UTF-8, \xc3a7. [Please, read the link above, it explains the issue much better that what I could do.] Any idea or update on this? Thanks, I?igo Serna PS: my system is a Linux Fedora 11 x86_64. Same happens on console, gnome-terminal or xterm. -------------- next part -------------- An HTML attachment was scrubbed... URL: From israelu at elbit.co.il Thu Aug 20 12:41:14 2009 From: israelu at elbit.co.il (iu2) Date: Thu, 20 Aug 2009 09:41:14 -0700 (PDT) Subject: Dictionary from a list References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: <04452fa5-b76f-4e5d-93f3-6348ca466bc8@b15g2000yqd.googlegroups.com> On Aug 20, 9:10?am, Peter Otten <__pete... at web.de> wrote: > Jan Kaliszewski wrote: > > 20-08-2009 o 02:05:57 Jan Kaliszewski wrote: > > >> Or probably better: > > >> ? ? ?from itertools import islice, izip > >> ? ? ?dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2))) > > > Or similarly, perhaps more readable: > > > ? ? ?iterator = iter(li) > > ? ? ?dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2)) > > I just can't stop posting this one: > > >>> from itertools import izip > >>> it = iter([1,2,3,4,5,6]) > >>> dict(izip(it, it)) > > {1: 2, 3: 4, 5: 6} > > I really tried, but yours drove me over the edge. > > Peter Nice. (but looks like stepping towards the dark side ... :-) I also liked this one: iterator = iter(li) dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2)) which inspired me to do something quite similar: a=range(1, 11) >>> a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> dict([[a.pop(0), a.pop(0)] for i in range(len(a)/2)]) {1: 2, 3: 4, 9: 10, 5: 6, 7: 8} Thanks From tim.arnold at sas.com Thu Aug 20 13:21:34 2009 From: tim.arnold at sas.com (Tim Arnold) Date: Thu, 20 Aug 2009 13:21:34 -0400 Subject: 2.6 windows install Message-ID: Hi, I installed python2.6 to a netapp device. I can use it from my local windows machine (XP). But others cannot use it from their pcs. They get this response "The system cannot execute the specified program.". If they double click on python.exe, they get a window with: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. When I installed it I didn't see any mention of an 'administrators' install, it just installed. The permissions on the directories where it installed are set wide-open for everyone. Any ideas on what I'm missing here? thanks, --Tim Arnold From dullrich at sprynet.com Thu Aug 20 14:13:35 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Thu, 20 Aug 2009 13:13:35 -0500 Subject: Silly question Message-ID: I just noticed that sequence[i:j:k] syntax in a post here. When did this happen? (I'm just curious whether it existed in 1.5.x or not. If so I'm stupid - otoh if it was introduced in 2.x I'm just slow...) From benjamin.kaplan at case.edu Thu Aug 20 14:36:35 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 20 Aug 2009 14:36:35 -0400 Subject: Silly question In-Reply-To: References: Message-ID: On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrich wrote: > I just noticed that > > ?sequence[i:j:k] > > syntax in a post here. When did this happen? > > (I'm just curious whether it existed in 1.5.x or not. > If so I'm stupid - otoh if it was introduced in 2.x > I'm just slow...) > Well, I got some good news and some bad news. According to the docs, it existed in 1.4 but the built-in sequences didn't support it until 2.3. It's not used that often anyway so you haven't been missing much. http://www.python.org/doc/2.3.5/whatsnew/section-slices.html From steve at REMOVE-THIS-cybersource.com.au Thu Aug 20 14:38:09 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 18:38:09 GMT Subject: Executing untrusted code References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com> Message-ID: <029d8840$0$25987$c3e8da3@news.astraweb.com> On Thu, 20 Aug 2009 08:16:51 -0700, Emanuele D'Arrigo wrote: > Fair enough. In this context, let's say I do this: > > import __builtin__ > import imp > originalBuiltins = imp.new_module("OriginalBuiltins") > > def readOnlyOpen(filename): > return originalBuiltins.open(filename, "r") > > __builtin__.open = readOnlyOpen Have you actually tested this? I don't think it works the way you think it does. >>> import __builtin__ >>> import imp >>> originalBuiltins = imp.new_module("OriginalBuiltins") >>> originalBuiltins.open Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'open' So your strategy fails to provide read-only file access. But moving on... > In what ways would the untrusted string be able to obtain the original, > built-in open function and open a file for writing? That's hardly even a challenge. >>> __builtin__.open = readOnlyOpen >>> anUntrustedString = """import __builtin__ ... reload(__builtin__) ... open('junk', 'w').write('a') ... """ >>> exec(anUntrustedString, {}) >>> open('junk').read() 'a' Not only have I broken your "read only" open within the call to exec, but I've broken it outside as well. With a little bit more effort, I could probably save and restore the open, so that my untrusted string could write to files inside the exec(), but code outside of the exec() would still see the readOnlyOpen. -- Steven From duncan.booth at invalid.invalid Thu Aug 20 14:41:34 2009 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 20 Aug 2009 18:41:34 GMT Subject: Silly question References: Message-ID: David C Ullrich wrote: > I just noticed that > > sequence[i:j:k] > > syntax in a post here. When did this happen? > > (I'm just curious whether it existed in 1.5.x or not. > If so I'm stupid - otoh if it was introduced in 2.x > I'm just slow...) > > Googling for 'python extended slice' returns this as the first hit: http://www.python.org/doc/2.3.5/whatsnew/section-slices.html > 15 Extended Slices > > Ever since Python 1.4, the slicing syntax has supported an optional > third ``step'' or ``stride'' argument. For example, these are all > legal Python syntax: L[1:10:2], L[:-1:1], L[::-1]. This was added to > Python at the request of the developers of Numerical Python, which > uses the third argument extensively. However, Python's built-in list, > tuple, and string sequence types have never supported this feature, > raising a TypeError if you tried it. Michael Hudson contributed a > patch to fix this shortcoming. So extended slices have existed since Python 1.4, but builtin types only started to support them from 2.3. From steve at REMOVE-THIS-cybersource.com.au Thu Aug 20 14:42:24 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 20 Aug 2009 18:42:24 GMT Subject: Executing untrusted code References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com> Message-ID: <029d893f$0$25987$c3e8da3@news.astraweb.com> On Thu, 20 Aug 2009 08:16:51 -0700, Emanuele D'Arrigo wrote: > In what ways would the untrusted string be able to obtain the original, > built-in open function and open a file for writing? On a related topic, you should read this post here: http://tav.espians.com/a-challenge-to-break-python-security.html -- Steven From 71david at libero.it Thu Aug 20 15:06:43 2009 From: 71david at libero.it (David) Date: Thu, 20 Aug 2009 21:06:43 +0200 Subject: Annoying octal notation Message-ID: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Hi all, Is there some magic to make the 2.x CPython interpreter to ignore the annoying octal notation? I'd really like 012 to be "12" and not "10". If I want an octal I'll use oct()! "Explicit is better than implicit..." TIA David From info at wingware.com Thu Aug 20 15:21:42 2009 From: info at wingware.com (Wingware) Date: Thu, 20 Aug 2009 15:21:42 -0400 Subject: ANN: Wing IDE 3.2 released Message-ID: <4A8DA246.9030908@wingware.com> Hi, Wingware has released version 3.2.0 final of Wing IDE, our integrated development environment for the Python programming language. *Release Highlights* This release includes the following new features: * Support for Python 3.0 and 3.1 * Rewritten version control integration with support for Subversion, CVS, Bazaar, git, Mercurial, and Perforce (*) * Added 64-bit Debian, RPM, and tar file installers for Linux * File management in Project view (**) * Auto-completion in the editor obtains completion data from live runtime when the debugger is active (**) * Perspectives: Create and save named GUI layouts and optionally automatically transition when debugging is started (*) * Improved support for Cython and Pyrex (*.pyx files) * Added key binding documentation to the manual * Added Restart Debugging item in Debug menu and tool bar (**) (*)'d items are available in Wing IDE Professional only. (**)'d items are available in Wing IDE Personal and Professional only. The release also contains many other minor features and bug fixes; see the change log for details: http://wingware.com/pub/wingide/3.2.0/CHANGELOG.txt *Downloads* Wing IDE Professional and Wing IDE Personal are commercial software and require a license to run. A free trial license can be obtained directly from the product when launched. Wing IDE 101 can be used free of charge. Wing IDE Pro 3.2.0 http://wingware.com/downloads/wingide/3.2 Wing IDE Personal 3.2.0 http://wingware.com/downloads/wingide-personal/3.2 Wing IDE 101 3.2.0 http://wingware.com/downloads/wingide-101/3.2 *About Wing IDE* Wing IDE is an integrated development environment for the Python programming language. It provides powerful debugging, editing, code intelligence, testing, version control, and search capabilities that reduce development and debugging time, cut down on coding errors, and make it easier to understand and navigate Python code. Wing IDE is available in three product levels: Wing IDE Professional is the full-featured Python IDE, Wing IDE Personal offers a reduced feature set at a low price, and Wing IDE 101 is a free simplified version designed for teaching entry level programming courses with Python. System requirements are Windows 2000 or later, OS X 10.3.9 or later for PPC or Intel (requires X11 Server), or a recent Linux system (either 32 or 64 bit). Wing IDE 3.2 supports Python versions 2.0.x through 3.1.x. *Purchasing and Upgrading* Wing 3.2 is a free upgrade for all Wing IDE 3.0 and 3.1 users. Any 2.x license sold after May 2nd 2006 is free to upgrade; others cost 1/2 the normal price to upgrade. Upgrade a 2.x license: https://wingware.com/store/upgrade Purchase a 3.x license: https://wingware.com/store/purchase -- The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From rui.vapps at gmail.com Thu Aug 20 15:23:40 2009 From: rui.vapps at gmail.com (Ray) Date: Thu, 20 Aug 2009 12:23:40 -0700 (PDT) Subject: thread and win32com.client problem Message-ID: <970c1cee-71ac-4b01-91ce-8ca2014570f8@p9g2000vbl.googlegroups.com> Hi, I have a problem with thread and win32com.client running python 2.5 on vista (activestate python) import win32com.client, thread def child(test): problem=win32com.client.Dispatch("WScript.Shell") print 'hello from thread', test def parent(): i=0 while 1: i+=1 thread.start_new(child,('abc',)) if raw_input()=='q': break parent() above codes will give me error when I run it. but if without the line problem=win32com.client.Dispatch("WScript.Shell") it just works fine. errors are: Unhandled exception in thread started by Traceback (most recent call last): File "C:\Users\Test\Desktop\Test\test_thread.py", line 3, in child problem=win32com.client.Dispatch("WScript.Shell") File "C:\Python25\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName (dispatch,userName,clsctx) File "C:\Python25\lib\site-packages\win32com\client\dynamic.py", line 98, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python25\lib\site-packages\win32com\client\dynamic.py", line 78, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) pywintypes.com_error: (-2147221008, 'CoInitialize has not been called.', None, None) Traceback (most recent call last): File "C:\Users\Test\Desktop\Test\test_thread.py", line 11, in parent() File "C:\Users\Test\Desktop\Test\test_thread.py", line 10, in parent if raw_input()=='q': break Thanks for any help. From dullrich at sprynet.com Thu Aug 20 15:31:30 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Thu, 20 Aug 2009 14:31:30 -0500 Subject: Silly question References: Message-ID: On Thu, 20 Aug 2009 18:41:34 +0000, Duncan Booth wrote: > David C Ullrich wrote: > >> I just noticed that >> >> sequence[i:j:k] >> >> syntax in a post here. When did this happen? >> >> (I'm just curious whether it existed in 1.5.x or not. If so I'm stupid >> - otoh if it was introduced in 2.x I'm just slow...) >> >> > Googling for 'python extended slice' returns this as the first hit: > > http://www.python.org/doc/2.3.5/whatsnew/section-slices.html > >> 15 Extended Slices >> >> Ever since Python 1.4, the slicing syntax has supported an optional >> third ``step'' or ``stride'' argument. For example, these are all legal >> Python syntax: L[1:10:2], L[:-1:1], L[::-1]. This was added to Python >> at the request of the developers of Numerical Python, which uses the >> third argument extensively. However, Python's built-in list, tuple, and >> string sequence types have never supported this feature, raising a >> TypeError if you tried it. Michael Hudson contributed a patch to fix >> this shortcoming. > > So extended slices have existed since Python 1.4, but builtin types only > started to support them from 2.3. Fine (I knew they existed in Numerical Python way back when...) From dullrich at sprynet.com Thu Aug 20 15:33:05 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Thu, 20 Aug 2009 14:33:05 -0500 Subject: Silly question References: Message-ID: On Thu, 20 Aug 2009 14:36:35 -0400, Benjamin Kaplan wrote: > On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrich > wrote: >> I just noticed that >> >> ?sequence[i:j:k] >> >> syntax in a post here. When did this happen? >> >> (I'm just curious whether it existed in 1.5.x or not. If so I'm stupid >> - otoh if it was introduced in 2.x I'm just slow...) >> >> > Well, I got some good news and some bad news. According to the docs, it > existed in 1.4 but the built-in sequences didn't support it until 2.3. > It's not used that often anyway so you haven't been missing much. So I'm slow, fine. (There were several times when I was using 1.5.3 and wished they were there - transposing matrices, etc.) > > http://www.python.org/doc/2.3.5/whatsnew/section-slices.html From rui.vapps at gmail.com Thu Aug 20 15:53:39 2009 From: rui.vapps at gmail.com (Ray) Date: Thu, 20 Aug 2009 12:53:39 -0700 (PDT) Subject: thread and win32com.client problem References: <970c1cee-71ac-4b01-91ce-8ca2014570f8@p9g2000vbl.googlegroups.com> Message-ID: <319b2ae1-276b-41af-9fd9-7086353ed193@p23g2000vbl.googlegroups.com> I already find the way to fix it. :-) From fuzzyman at gmail.com Thu Aug 20 15:55:47 2009 From: fuzzyman at gmail.com (Fuzzyman) Date: Thu, 20 Aug 2009 12:55:47 -0700 (PDT) Subject: ANN: discover 0.3.0 released, automatic test discovery for unittest Message-ID: <096a6bb5-9b09-4d5c-86cf-ba826cf3a39a@f37g2000yqn.googlegroups.com> The discover module is a backport of the automatic test discovery from the unittest module in Python-trunk (what will become Python 2.7 and 3.2). The discover module should work on versions of Python 2.4 upwards: * discover module on PyPI: http://pypi.python.org/pypi/discover The discover module can be used to run all, or a subset, of your unittest based tests automatically from the command line. See the PyPI page for details. Version 0.3.0 has two new features: * Failing to import a file (e.g. due to a syntax error) no longer halts discovery but is reported as an error. * Discovery will not attempt to import test files whose names are not valid Python identifiers, even if they match the pattern. From aaron.hildebrandt at gmail.com Thu Aug 20 16:02:57 2009 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Thu, 20 Aug 2009 13:02:57 -0700 (PDT) Subject: Problem with arrays in a recursive class function Message-ID: <190378bc-f095-46fa-9104-cb94fa09698f@g10g2000yqh.googlegroups.com> I have a list of nodes, and I need to find a path from one node to another. The nodes each have a list of nodes they are connected to, set up like this: class Node(object): def __init__(self, connectedNodes): self.connectedNodes = connectedNodes nodes = { 1: Node([4]), 2: Node([3]), 3: Node([2, 4, 5]), 4: Node([1, 6, 3]), 5: Node([3, 7]), 6: Node([4, 9]), 7: Node([5, 8]), 8: Node([7, 9]), 9: Node([6, 8]) } I made a quick brute-force pathfinder to solve it (in this case, a path from node 1 to node 9). Here it is: class PathFind(object): def __init__(self, source, destination): self.source = source self.destination = destination self.solved = [] def Search(self): self.PathFind([self.source]) if self.solved: print "Solutions: " for i in self.solved: print "\t" + str(i) else: print "Couldn't solve." def PathFind(self, trail): location = trail[-1] if location == self.destination: self.solved.append(trail) print "Solution found: " + str(trail) else: possibilities = [] for i in nodes[location].connectedNodes: if not i in trail: possibilities.append(i) for i in possibilities: trail.append(i) self.PathFind(trail[:]) if not possibilities: print "Dead end: " + str(trail) finder = PathFind(1, 9) finder.Search() Unfortunately, it doesn't seem to be giving me the result I was after. This is the output: Solution found: [1, 4, 6, 9] Dead end: [1, 4, 6, 3, 2] Solution found: [1, 4, 6, 3, 2, 5, 7, 8, 9] Solutions: [1, 4, 6, 9] [1, 4, 6, 3, 2, 5, 7, 8, 9] The problem is the array trail[], which seems to survive from instance to instance of PathFind(). I thought that by calling self.PathFind (trail[:]), I was creating a new copy of trail[], but obviously something isn't running like I expected. Is there something I'm misunderstanding here, or is there just a stupid bug in my code I haven't caught? From dfnsonfsduifb at gmx.de Thu Aug 20 16:24:24 2009 From: dfnsonfsduifb at gmx.de (Johannes Bauer) Date: Thu, 20 Aug 2009 22:24:24 +0200 Subject: Annoying octal notation In-Reply-To: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: <7f5pohF2k259vU1@mid.dfncis.de> David schrieb: > If I want an octal I'll use oct()! > > "Explicit is better than implicit..." A leading "0" *is* explicit. Implicit would be when some functions would interpret a "0" prefix as octal and others wouldn't. Regards, Johannes -- "Meine Gegenklage gegen dich lautet dann auf bewusste Verlogenheit, verl?sterung von Gott, Bibel und mir und bewusster Blasphemie." -- Prophet und Vision?r Hans Joss aka HJP in de.sci.physik <48d8bf1d$0$7510$5402220f at news.sunrise.ch> From lists at cheimes.de Thu Aug 20 16:35:48 2009 From: lists at cheimes.de (Christian Heimes) Date: Thu, 20 Aug 2009 22:35:48 +0200 Subject: thread and win32com.client problem In-Reply-To: <319b2ae1-276b-41af-9fd9-7086353ed193@p23g2000vbl.googlegroups.com> References: <970c1cee-71ac-4b01-91ce-8ca2014570f8@p9g2000vbl.googlegroups.com> <319b2ae1-276b-41af-9fd9-7086353ed193@p23g2000vbl.googlegroups.com> Message-ID: <4A8DB3A4.4030800@cheimes.de> Ray wrote: > I already find the way to fix it. :-) I consider it good style when people describe their solution to a problem, too. Other Python users may run into the same issue someday. :) Christian From sajmikins at gmail.com Thu Aug 20 16:37:33 2009 From: sajmikins at gmail.com (Simon Forman) Date: Thu, 20 Aug 2009 13:37:33 -0700 (PDT) Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: <6a523329-3287-4271-ba37-7be450cfc5f6@d32g2000yqh.googlegroups.com> On Aug 20, 3:06?pm, David <71da... at libero.it> wrote: > Hi all, > > Is there some magic to make the 2.x CPython interpreter to ignore the > annoying octal notation? No. You would have to modify and recompile the interpreter. This is not exactly trivial, see "How to Change Python's Grammar" http://www.python.org/dev/peps/pep-0306/ However, see "Integer Literal Support and Syntax" http://www.python.org/dev/peps/pep-3127/ (Basically in 2.6 and onwards you can use 0oNNN notation.) > I'd really like 012 to be "12" and not "10". > > If I want an octal I'll use oct()! But that gives you a string, you're asking about literals. From luk.art.q1 at gmail.com Thu Aug 20 16:43:37 2009 From: luk.art.q1 at gmail.com (artur lukowicz) Date: Thu, 20 Aug 2009 22:43:37 +0200 Subject: No subject Message-ID: 6344a24de14243c76060bedd42f79bc302679dad -------------- next part -------------- An HTML attachment was scrubbed... URL: From aaron.hildebrandt at gmail.com Thu Aug 20 16:57:07 2009 From: aaron.hildebrandt at gmail.com (Aaron Scott) Date: Thu, 20 Aug 2009 13:57:07 -0700 (PDT) Subject: Problem with arrays in a recursive class function References: <190378bc-f095-46fa-9104-cb94fa09698f@g10g2000yqh.googlegroups.com> Message-ID: <5f185928-131e-4718-bbb2-a775157d966c@c34g2000yqi.googlegroups.com> Never mind -- ditched the attempt and implemented Dijkstra. From MatzeGuentert at gmx.de Thu Aug 20 17:08:34 2009 From: MatzeGuentert at gmx.de (Matthias =?ISO-8859-1?Q?G=FCntert?=) Date: Thu, 20 Aug 2009 23:08:34 +0200 Subject: incrementing string/hex value from file and write back Message-ID: <1250802514.3331.0.camel@celsius> Hello guys I would like to read a hex number from an ASCII file, increment it and write it back. How can this be performed? I have tried several approaches: my file serial.txt contains: 0C ---------------------------------- f = open('serial.txt', 'r') val = f.read() val = val.encode('hex') print val ---------------------------------- --> 3043 ---------------------------------- f = open('serial.txt', 'r') val = f.read() print val val = val+1 ---------------------------------- --> TypeError: cannot concatenate 'str' and 'int' objects ---------------------------------- f = open('serial.txt', 'rb') val = f.read() val = val + 1 ---------------------------------- --> TypeError: cannot concatenate 'str' and 'int' objects hm.... From rami.chowdhury at gmail.com Thu Aug 20 17:18:28 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 20 Aug 2009 14:18:28 -0700 Subject: incrementing string/hex value from file and write back In-Reply-To: <1250802514.3331.0.camel@celsius> References: <1250802514.3331.0.camel@celsius> Message-ID: > val = val.encode('hex') That's the crucial line -- it's returning a new integer, which you are re-binding to val. If you then did: val = val + 1 you'd be fine, and could then write val back to your file :-) On Thu, 20 Aug 2009 14:08:34 -0700, Matthias G?ntert wrote: > Hello guys > > I would like to read a hex number from an ASCII file, increment it and > write it back. > How can this be performed? > > I have tried several approaches: > > my file serial.txt contains: 0C > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > val = val.encode('hex') > print val > ---------------------------------- > --> 3043 > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > print val > val = val+1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > ---------------------------------- > f = open('serial.txt', 'rb') > val = f.read() > val = val + 1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > > hm.... > -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From sajmikins at gmail.com Thu Aug 20 17:35:12 2009 From: sajmikins at gmail.com (Simon Forman) Date: Thu, 20 Aug 2009 14:35:12 -0700 (PDT) Subject: incrementing string/hex value from file and write back References: Message-ID: <6d707639-7d1b-44a3-b4a5-3a0cbf1240fc@j21g2000yqe.googlegroups.com> On Aug 20, 5:08?pm, Matthias G?ntert wrote: > Hello guys > > I would like to read a hex number from an ASCII file, increment it and > write it back. > How can this be performed? > > I have tried several approaches: > > my file serial.txt contains: 0C > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > val = val.encode('hex') > print val > ---------------------------------- > --> 3043 > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() ? > print val > val = val+1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > ---------------------------------- > f = open('serial.txt', 'rb') > val = f.read() > val = val + 1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > hm.... Check this out: In [1]: val = '0C' In [2]: val.encode('hex') Out[2]: '3043' That's not what you want. Try this: In [3]: int(val, 16) Out[3]: 12 And to convert an int to a hex string. In [4]: '%x' % 13 Out[4]: 'd' The interpreter has a help() function that gives you quick access to information about python objects: >>> help(str.encode) Help on method_descriptor: encode(...) S.encode([encoding[,errors]]) -> object Encodes S using the codec registered for encoding. encoding defaults to the default encoding. errors may be given to set a different error handling scheme. Default is 'strict' meaning that encoding errors raise a UnicodeEncodeError. Other possible values are 'ignore', 'replace' and 'xmlcharrefreplace' as well as any other name registered with codecs.register_error that is able to handle UnicodeEncodeErrors. >>> help(int) Help on class int in module __builtin__: class int(object) | int(x[, base]) -> integer | | Convert a string or number to an integer, if possible. A floating point | argument will be truncated towards zero (this does not include a string | representation of a floating point number!) When converting a string, use | the optional base. It is an error to supply a base when converting a | non-string. If the argument is outside the integer range a long object | will be returned instead. | | Methods defined here: | ... Unfortunately you can't use it on the '%' string formatting operator... >>> help(%) SyntaxError: invalid syntax So here's a link to the docs: http://docs.python.org/library/stdtypes.html#string-formatting-operations HTH, ~Simon From breamoreboy at yahoo.co.uk Thu Aug 20 17:36:37 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 20 Aug 2009 22:36:37 +0100 Subject: incrementing string/hex value from file and write back In-Reply-To: <1250802514.3331.0.camel@celsius> References: <1250802514.3331.0.camel@celsius> Message-ID: Matthias G?ntert wrote: > Hello guys > > I would like to read a hex number from an ASCII file, increment it and > write it back. > How can this be performed? > > I have tried several approaches: > > my file serial.txt contains: 0C > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > val = val.encode('hex') val = int(val, 16) + 1 f.write('%02X' % val) > print val > ---------------------------------- > --> 3043 > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > print val > val = val+1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > ---------------------------------- > f = open('serial.txt', 'rb') > val = f.read() > val = val + 1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > > hm.... > -- Kindest regards. Mark Lawrence. From ethan at stoneleaf.us Thu Aug 20 17:36:41 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 20 Aug 2009 14:36:41 -0700 Subject: incrementing string/hex value from file and write back In-Reply-To: References: <1250802514.3331.0.camel@celsius> Message-ID: <4A8DC1E9.30504@stoneleaf.us> [fixed top-posting] Rami Chowdhury wrote: > On Thu, 20 Aug 2009 14:08:34 -0700, Matthias G?ntert > wrote: > >> Hello guys >> >> I would like to read a hex number from an ASCII file, increment it and >> write it back. >> How can this be performed? >> >> I have tried several approaches: >> >> my file serial.txt contains: 0C >> >> ---------------------------------- >> f = open('serial.txt', 'r') >> val = f.read() >> val = val.encode('hex') > > That's the crucial line -- it's returning a new integer, which you are > re-binding to val. If you then did: > > val = val + 1 > > you'd be fine, and could then write val back to your file :-) > .encode('hex') is returning a string -- attempting to add one to it will raise the same error the OP is getting below. To get a number you can do (after reading val from the file): val = int(val, '16') # convert from base 16 val += 1 # increment val = "%X" % val # back to heg digits and then write it back out again. Don't forget to close and reopen the file for writing. :) ~Ethan~ >> print val >> ---------------------------------- >> --> 3043 >> >> ---------------------------------- >> f = open('serial.txt', 'r') >> val = f.read() >> print val >> val = val+1 >> ---------------------------------- >> --> TypeError: cannot concatenate 'str' and 'int' objects >> >> ---------------------------------- >> f = open('serial.txt', 'rb') >> val = f.read() >> val = val + 1 >> ---------------------------------- >> --> TypeError: cannot concatenate 'str' and 'int' objects >> >> >> hm.... From sajmikins at gmail.com Thu Aug 20 17:38:08 2009 From: sajmikins at gmail.com (Simon Forman) Date: Thu, 20 Aug 2009 14:38:08 -0700 (PDT) Subject: incrementing string/hex value from file and write back References: <1250802514.3331.0.camel@celsius> Message-ID: On Aug 20, 5:18?pm, "Rami Chowdhury" wrote: > > val = val.encode('hex') > > That's the crucial line -- it's returning a new integer, which you are ? > re-binding to val. If you then did: No, it returns another string, which still isn't the decimal representation of the hex string. hex C => decimal 12 In [1]: '0C'.encode('hex') Out[1]: '3043' From rami.chowdhury at gmail.com Thu Aug 20 17:44:57 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 20 Aug 2009 14:44:57 -0700 Subject: incrementing string/hex value from file and write back In-Reply-To: References: <1250802514.3331.0.camel@celsius> Message-ID: Of course - my apologies, I was being an idiot. On Thu, 20 Aug 2009 14:38:08 -0700, Simon Forman wrote: > On Aug 20, 5:18?pm, "Rami Chowdhury" wrote: >> > val = val.encode('hex') >> >> That's the crucial line -- it's returning a new integer, which you are ? >> re-binding to val. If you then did: > > No, it returns another string, which still isn't the decimal > representation of the hex string. hex C => decimal 12 > > In [1]: '0C'.encode('hex') > Out[1]: '3043' -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From manu3d at gmail.com Thu Aug 20 17:46:19 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 20 Aug 2009 14:46:19 -0700 (PDT) Subject: Executing untrusted code References: <137d4d96-c481-4806-a8cf-2904e89c78ae@l35g2000vba.googlegroups.com> <029d893f$0$25987$c3e8da3@news.astraweb.com> Message-ID: <4a5db5ed-4413-46a6-bc2b-6e9200b26ea3@s31g2000yqs.googlegroups.com> Christian, Rami and Steven, thank you all for your help. It wasn't meant to be a challenge, I knew it ought to be easily breakable. I'm no hacker and it just helps to have some examples to better understand the issue. On Aug 20, 7:42?pm, Steven D'Aprano On a related topic, you should read this post here: > http://tav.espians.com/a-challenge-to-break-python-security.html Indeed I did read the post and my minimalistic test was inspired by some of the code in it (I didn't know you could replace the builtins!). Tav's effort kinda of ended nowhere though. My understanding of it is that it hasn't been broken and that Tav has submitted a patch to secure some of python's innards. But Steven, you are perfectly right, I didn't test it and I missed the crucial part in which I store the __builtins__ dictionary in the dictionary of the new originalBuiltins module. My bad. Still, you did understand my intentions and did give me a simple example of how it could be broken. Thank you. -However- I would suggest that conceptually the "award" goes to Christian. ;) In the same way the open builtin function can be replaced or removed, also reload, file, __import__, exec, execfile and any other potentially "unsafe" builtin can be replaced with safer versions. Or not? Christian's solution though, seems to be much trickier to evade. Can the object class be replaced at runtime with a version that does not provide a way to reach its subclasses? Manu From inigoserna at gmail.com Thu Aug 20 18:12:07 2009 From: inigoserna at gmail.com (=?UTF-8?B?ScOxaWdvIFNlcm5h?=) Date: Fri, 21 Aug 2009 00:12:07 +0200 Subject: ncurses getch & unicode (was: decoding keyboard input when using curses) In-Reply-To: <65a1d6f80908200936g18b235fcw49d0047168cf9548@mail.gmail.com> References: <65a1d6f80908200936g18b235fcw49d0047168cf9548@mail.gmail.com> Message-ID: <65a1d6f80908201512w4b90c646r315e699ed78a525a@mail.gmail.com> Hi again, 2009/8/20 I?igo Serna > > I have the same problem mentioned in http://groups.google.com/group/comp.lang.python/browse_thread/thread/c70c80cd9bc7bac6?pli=1 some months ago. > > Python 2.6 program which uses ncurses module in a terminal configured to use UTF-8 encoding. > > When trying to get input from keyboard, a non-ascii character (like ?) is returned as 2 integers < 255, needing 2 calls to getch method to get both. > These two integers \xc3 \xa7 forms the utf-8 encoded representation of ? character. > > ncurses get_wch documentation states the function should return an unique integer > 255 with the ordinal representation of that unicode char encoded in UTF-8, \xc3a7. Answering myself, I've copied at the bottom of this email a working solution, but the question still remains: why win.getch() doesn't return the correct value? Kind regards, I?igo Serna ###################################################################### # test.py import curses import locale locale.setlocale(locale.LC_ALL, '') print locale.getpreferredencoding() def get_char(win): ??? def get_check_next_byte(): ??????? c = win.getch() ??????? if 128 <= c <= 191: ??????????? return c ??????? else: ??????????? raise UnicodeError ??? bytes = [] ??? c = win.getch() ??? if c <= 127: ??????? # 1 bytes ??????? bytes.append(c) ??? elif 194 <= c <= 223: ??????? # 2 bytes ??????? bytes.append(c) ??????? bytes.append(get_check_next_byte()) ??? elif 224 <= c <= 239: ??????? # 3 bytes ??????? bytes.append(c) ??????? bytes.append(get_check_next_byte()) ??????? bytes.append(get_check_next_byte()) ??? elif 240 <= c <= 244: ??????? # 4 bytes ??????? bytes.append(c) ??????? bytes.append(get_check_next_byte()) ??????? bytes.append(get_check_next_byte()) ??????? bytes.append(get_check_next_byte()) ??? buf = ''.join([chr(b) for b in bytes]) ??? buf = buf.decode('utf-8') ??? return buf def getcodes(win): ??? codes = [] ??? while True: ??????? try: ??????????? ch = get_char(win) ??????? except KeyboardInterrupt: ??????????? return codes ??????? codes.append(ch) lst = curses.wrapper(getcodes) print lst for c in lst: ??? print c.encode('utf-8'), print ###################################################################### From mensanator at aol.com Thu Aug 20 18:18:35 2009 From: mensanator at aol.com (Mensanator) Date: Thu, 20 Aug 2009 15:18:35 -0700 (PDT) Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: On Aug 20, 2:06?pm, David <71da... at libero.it> wrote: > Hi all, > > Is there some magic to make the 2.x CPython interpreter to ignore the > annoying octal notation? > I'd really like 012 to be "12" and not "10". Use 3.1: >>> int('012') 12 (Just kidding! That works in 2.5 also. How are you using it where it's coming out wrong? I can see you pulling '012' out of a text file and want to calculate with it, but how would you use a string without using int()? Passing it to functions that allow string representations of numbers?) > > If I want an octal I'll use oct()! > > "Explicit is better than implicit..." > > TIA > David From davea at ieee.org Thu Aug 20 19:05:17 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 20 Aug 2009 19:05:17 -0400 Subject: incrementing string/hex value from file and write back In-Reply-To: <1250802514.3331.0.camel@celsius> References: <1250802514.3331.0.camel@celsius> Message-ID: <4A8DD6AD.5080108@ieee.org> Matthias G?ntert wrote: > Hello guys > > I would like to read a hex number from an ASCII file, increment it and > write it back. > How can this be performed? > > I have tried several approaches: > > my file serial.txt contains: 0C > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > val = val.encode('hex') > print val > ---------------------------------- > --> 3043 > > ---------------------------------- > f = open('serial.txt', 'r') > val = f.read() > print val > val = val+1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > ---------------------------------- > f = open('serial.txt', 'rb') > val = f.read() > val = val + 1 > ---------------------------------- > --> TypeError: cannot concatenate 'str' and 'int' objects > > > hm.... > > > You don't say much to constrain the file. Is it always two characters (nibbles) long? Or might it have a newline at the end? If it could be multiple lines, is each line limited to 2 columns? or to 8 columns? or no limit? To interpret val as an integer, try new = int(val, 16) Then to convert back to hex digits, try line = "%x" % (val+1) For fancier conversions, look at binascii.unhexlify() and hexlify(). Look also at chr() and ord(). and str.format() DaveA From martin.hellwig at dcuktec.org Thu Aug 20 19:06:10 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 21 Aug 2009 00:06:10 +0100 Subject: thread and win32com.client problem In-Reply-To: References: <970c1cee-71ac-4b01-91ce-8ca2014570f8@p9g2000vbl.googlegroups.com> <319b2ae1-276b-41af-9fd9-7086353ed193@p23g2000vbl.googlegroups.com> Message-ID: Christian Heimes wrote: > Ray wrote: >> I already find the way to fix it. :-) > > I consider it good style when people describe their solution to a > problem, too. Other Python users may run into the same issue someday. :) > > Christian He probably used: pythoncom.CoInitialize() -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From farberow at wisc.edu Thu Aug 20 19:21:50 2009 From: farberow at wisc.edu (Carrie Farberow) Date: Thu, 20 Aug 2009 18:21:50 -0500 Subject: Python on Crays Message-ID: <6fb0f9aeb382.4a8d943e@wiscmail.wisc.edu> I am trying to build a statically-linked Python based on directions at: http://yt.enzotools.org/wiki/CrayXT5Installation I have tried this on multiple systems. The first time I attempt to build python, 'make' runs fine but 'make install' fails with the following error: Sorry: UnicodeError: ("\\N escapes not supported (can't load unicodedata module)",) Any help regarding the source of this error and possible fixes would be appreciated. Carrie From zuo at chopin.edu.pl Thu Aug 20 19:25:38 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Fri, 21 Aug 2009 01:25:38 +0200 Subject: #elements of seq A in seq B In-Reply-To: <7c16abe1-7502-432a-acff-aff95c22a8ac@q14g2000vbi.googlegroups.com> References: <7c16abe1-7502-432a-acff-aff95c22a8ac@q14g2000vbi.googlegroups.com> Message-ID: 20-08-2009 o 04:12:14 Simon Forman wrote: > If you want to know the count for each element you can use this: > > from collections import defaultdict > > def g(a, b): > a = set(a) > d = defaultdict(int) > for item in b: > if item in a: > d[item] += 1 > return d > > print g(A, B) > > # prints defaultdict(, {' ': 1, 'e': 1, 'g': 1, 'i': 1, > 'o': 1, 'n': 2, 's': 1, 'r': 2, 't': 2}) Yeah, your sollution is better (and more interesting :-)). Thanks! *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Thu Aug 20 19:44:43 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Fri, 21 Aug 2009 01:44:43 +0200 Subject: #elements of seq A in seq B In-Reply-To: References: Message-ID: 20-08-2009 o 13:01:29 Neal Becker wrote: > I meant #occurrences of characters from the set A in string B But: 1) separately for each element of A? (see Simon's sollution with defaultdict) 2) or total number of all occurrences of elements of A? (see below) 20-08-2009 o 14:05:12 Peter Otten <__peter__ at web.de> wrote: > identity = "".join(map(chr, range(256))) > n = len(b) - len(b.translate(identity, a)) Nice, though I'd prefer Simon's sollution: a = set(a) n = sum(item in a for item in b) Regards, *j -- Jan Kaliszewski (zuo) From aahz at pythoncraft.com Thu Aug 20 19:51:00 2009 From: aahz at pythoncraft.com (Aahz) Date: 20 Aug 2009 16:51:00 -0700 Subject: Silly question References: Message-ID: In article , Benjamin Kaplan wrote: >On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrich wrot= >e: >> >> I just noticed that >> sequence[i:j:k] > >Well, I got some good news and some bad news. According to the docs, >it existed in 1.4 but the built-in sequences didn't support it until >2.3. It's not used that often anyway so you haven't been missing much. Except that it's canonical for one specific operation: 'reverseme'[::-1] -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith From james.harris.1 at googlemail.com Thu Aug 20 19:59:14 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Thu, 20 Aug 2009 16:59:14 -0700 (PDT) Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: On 20 Aug, 20:06, David <71da... at libero.it> wrote: > Hi all, > > Is there some magic to make the 2.x CPython interpreter to ignore the > annoying octal notation? > I'd really like 012 to be "12" and not "10". This is (IMHO) a sad hangover from C (which took it from B but not from BCPL which used # and #x) and it appears in many places. It sounds like you want to use leading zeroes in literals - perhaps for spacing. I don't think there's an easy way. You just have to be aware of it. Note that it seems to apply to integers and not floating point literals >>> 012 10 >>> int("012") 12 >>> 012.5 12.5 >>> This daft notation is recognised in some surprising places to catch the unwary. For example, the place I first came across it was in a windows command prompt: s:\>ping 192.168.1.012 Pinging 192.168.1.10 with 32 bytes of data: On B's use of the leading zero see http://cm.bell-labs.com/cm/cs/who/dmr/kbman.html and note the comment: "An octal constant is the same as a decimal constant except that it begins with a zero. It is then interpreted in base 8. Note that 09 (base 8) is legal and equal to 011." It maybe made sense once but this relic of the past should have been consigned to the waste bin of history long ago. James From sjmachin at lexicon.net Thu Aug 20 20:45:11 2009 From: sjmachin at lexicon.net (John Machin) Date: Thu, 20 Aug 2009 17:45:11 -0700 (PDT) Subject: Silly question References: Message-ID: <97ae0d22-7eaa-4ad6-8603-69699703d508@u16g2000pru.googlegroups.com> On Aug 21, 5:33?am, David C Ullrich wrote: > So I'm slow, fine. (There were several times when I was using 1.5.3 > and wished they were there - transposing matrices, etc.) 1.5.THREE ?? From sflennik at comcast.net Thu Aug 20 20:57:53 2009 From: sflennik at comcast.net (Steve1234) Date: Thu, 20 Aug 2009 17:57:53 -0700 (PDT) Subject: install package in a particular python version Message-ID: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> I installed the boto module in my Ubuntu system using "python setup.py install" and it installs in my python2.6 version and works great. Now I want to install boto into my python2.5 version because my hosting services supports 2.5 but not 2.6. and I want to test my code locally, "sting".format() is not in 2.5. How do I install a package in a particular version of python? I tried several different install switches without any luck. From aahz at pythoncraft.com Thu Aug 20 20:58:53 2009 From: aahz at pythoncraft.com (Aahz) Date: 20 Aug 2009 17:58:53 -0700 Subject: platform-specific overrides of functions and class methods (expanding on imputils demo code) References: <77715735-2668-43e7-95da-c91d175b35c9@z31g2000yqd.googlegroups.com> Message-ID: In article <77715735-2668-43e7-95da-c91d175b35c9 at z31g2000yqd.googlegroups.com>, lkcl wrote: > >if somebody would like to add this to the python bugtracker, as a >contribution, that would be great. alternatively, you might like to >have a word with the python developers to get them to remove the >censorship on my contributions. Excuse me? What censorship? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Given that C++ has pointers and typecasts, it's really hard to have a serious conversation about type safety with a C++ programmer and keep a straight face. It's kind of like having a guy who juggles chainsaws wearing body armor arguing with a guy who juggles rubber chickens wearing a T-shirt about who's in more danger." --Roy Smith From benjamin.kaplan at case.edu Thu Aug 20 21:05:34 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 20 Aug 2009 21:05:34 -0400 Subject: install package in a particular python version In-Reply-To: References: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> Message-ID: whoops, sent it to you instead of the list On Thu, Aug 20, 2009 at 9:05 PM, Benjamin Kaplan wrote: > On Thu, Aug 20, 2009 at 8:57 PM, Steve1234 wrote: >> >> I installed the boto module in my Ubuntu system using "python setup.py >> install" and it installs in my python2.6 version and works great. ?Now >> I want to install boto into my python2.5 version because my hosting >> services supports 2.5 but not 2.6. and I want to test my code locally, >> "sting".format() is not in 2.5. >> >> How do I install a package in a particular version of python? >> >> I tried several different install switches without any luck. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > It's not an install switch- it's the version of python you use to > install it. If you want to install it to Python 2.5, run python2.5 > setup.py install > From david.lyon at preisshare.net Thu Aug 20 21:34:08 2009 From: david.lyon at preisshare.net (David Lyon) Date: Thu, 20 Aug 2009 21:34:08 -0400 Subject: install package in a particular python version In-Reply-To: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> References: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> Message-ID: <85a5395c9a481e1dfc74f5a76a62e85a@preisshare.net> On Thu, 20 Aug 2009 17:57:53 -0700 (PDT), Steve1234 wrote: > I installed the boto module in my Ubuntu system using "python setup.py > install" and it installs in my python2.6 version and works great. Now > I want to install boto into my python2.5 version because my hosting > services supports 2.5 but not 2.6. and I want to test my code locally, > "sting".format() is not in 2.5. > > How do I install a package in a particular version of python? > > I tried several different install switches without any luck. If you wish to do it in a gui rather than at the commandline then you could try the python package manager at : http://sourceforge.net/projects/pythonpkgmgr/ You will need to download it from source. In the Options Dialog, there is a dropdown list that allow you to easily change from one version of python to another. Regards David From zuo at chopin.edu.pl Thu Aug 20 21:42:42 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Fri, 21 Aug 2009 03:42:42 +0200 Subject: #elements of seq A in seq B In-Reply-To: <200908202009.59909.ndbecker2@gmail.com> References: <200908202009.59909.ndbecker2@gmail.com> Message-ID: >> a = set(a) >> n = sum(item in a for item in b) > Why set? Does it matter if I say that items in A are already unique? Sets are hash-based, so it's (most probably) far more efficient for sets than for sequences (especially if we say about big/long ones). Regards, *j -- Jan Kaliszewski (zuo) From charles at declareSub.com Thu Aug 20 22:12:32 2009 From: charles at declareSub.com (Charles Yeomans) Date: Thu, 20 Aug 2009 22:12:32 -0400 Subject: How to create functors? In-Reply-To: References: <7xab1vl0qf.fsf@ruckus.brouhaha.com> <7xmy5uanlt.fsf@ruckus.brouhaha.com> Message-ID: <33BB3F81-177F-4A02-9F09-44520F4823C4@declareSub.com> On Aug 20, 2009, at 5:25 AM, Steven D'Aprano wrote: > On Thu, 20 Aug 2009 01:36:14 -0700, Paul Rubin wrote: > >> Steven D'Aprano writes: >>> As near as I can tell, a functor is just an object which is callable >>> like a function without actually being implemented as a function, >>> e.g.: >> >> No it's not anything like that either, at least as I'm used to the >> term >> in programming or in mathematics. Maybe it's used other ways though. > > According to Wikipedia, functor can be used as a synonym for "function > object": > > http://en.wikipedia.org/wiki/Function_object > > which is what I was thinking of. So it seems there are at least two > meanings for the word, neither of which seems to apply to this > thread :) > > > >> As I'm used to it, it's a feature of certain static type systems. >> The >> notion isn't that useful in Python > > I find the Haskell page entirely opaque and unintelligible. Well, > perhaps > not *entirely* opaque, but pretty close: it assumes a mathematical > sophistication that I don't think I even had when I was getting my > maths > degree, let alone can remember two decades later. (Pity the poor VB > coders wondering what Haskell is good for...) The Wikipedia page is a > little better, but it's section on Examples is laughable -- the > examples > are as unintelligible to this reader as the description before them. > To this reader -- an Rb coder -- the examples were pretty clear. > > But let me try an example to see if I've got it right: > > > class Int2StrFunctor: > def map1(self, n): > if type(n) is not int: > raise TypeError('argument must be an int') > return "-"*n > def map2(self, f): > if type(f) is not type(lambda: None): > raise TypeError('argument must be a function') > # assume f takes an int, and returns another int > def inner(n): > return self.map1(f(n)) > return inner > > > The functor can take an int and return a string: > >>>> F = Int2StrFunctor() # F is a functor >>>> F.map1(3) > '---' > > It can also take a function (of int -> int) and return a new function > (int -> str): > >>>> def myfunc(n): > ... return n+2 > ... >>>> f = F.map2(myfunc) >>>> f(3) > '-----' >>>> f(4) > '------' > > > There's nothing special about the methods map1() and map2(), I could > call > them anything I like, or even do this: > > >>>> def __call__(self, arg): > ... if type(arg) is int: > ... return self.map1(arg) > ... else: > ... return self.map2(arg) > ... >>>> Int2StrFunctor.__call__ = __call__ >>>> >>>> F(2) > '--' >>>> F(myfunc)(0) > '--' > > > There are some technical restrictions on functors, relating to the > sorts > of functions and types (strictly "categories") they can accept, > presumably to make them mathematically well-behaved. > > > Have I got it correct? > I don't think so. Paul Rubin's square example was, I thought, particularly instructive. Charles Yeomans -------------- next part -------------- An HTML attachment was scrubbed... URL: From laser.yuan at gmail.com Thu Aug 20 23:34:20 2009 From: laser.yuan at gmail.com (laser) Date: Thu, 20 Aug 2009 20:34:20 -0700 (PDT) Subject: IDLE is not as interactive as Maple References: <7aa51a98-965c-4c74-a3b5-650140f1d589@v23g2000pro.googlegroups.com> <399082f9-3765-46dc-b71e-618e75256cf9@d34g2000vbm.googlegroups.com> Message-ID: <80f61e9c-9c0d-4fc9-a16a-9ef9f90b928c@o9g2000prg.googlegroups.com> Thanks very much for your information. Reinteract looks like exactly what I want. It give me the similary feeling of using Maple. I like this kind of programming style. People who did not have this experience really should take a try. On 8?20?, ??9?11?, Andr? wrote: > On Aug 20, 12:22 am, laser wrote: > > > In the future, will Python provide programe enviroment like Maple > > does? > > A quick, flip answer: perhaps if you design one? Tools for Python are > designed by people scratching an itch. > > That being said, have a look at reinteract:http://www.reinteract.org/trac/wiki/Tutorial/Introduction > > > In Maple, you can remove anything unneeded in the editor. And > > the code execution order are not necessary in one direction. You can > > run any command line on the screen by > > push Enter key. These functions gave a lot of flaxibility for users to > > start with programming something. > > Andr? From sflennik at comcast.net Thu Aug 20 23:53:18 2009 From: sflennik at comcast.net (Steve1234) Date: Thu, 20 Aug 2009 20:53:18 -0700 (PDT) Subject: install package in a particular python version References: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> Message-ID: <99822c4d-74ef-4a28-b133-42144c7fd25a@f20g2000prn.googlegroups.com> Benjamin suggested: sudo python2.5 setup.py install and it works. This makes sense, thanks. I downloaded pythonpkgmgr from source and installed it. I got the error that reguired wx package was missing. I couldn't find this package for Linux or source. From ben+python at benfinney.id.au Fri Aug 21 01:13:56 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 15:13:56 +1000 Subject: Waiting for a subprocess to exit Message-ID: <873a7l21gr.fsf@benfinney.id.au> Howdy all, I'm looking to replace some usages of ?os.system? with the more secure ?subprocess.Popen? methods. The module documentation has a section on replacing ?os.system? , which says to use:: process = subprocess.Popen("mycmd" + " myarg", shell=True) status = os.waitpid(process.pid, 0) But a ?Popen? instance has its own ?wait? method, which waits for exit . Why would I use ?os.waitpid? instead of:: process = subprocess.Popen("mycmd" + " myarg", shell=True) process.wait() status = process.returncode -- \ ?The best is the enemy of the good.? ?Voltaire, _Dictionnaire | `\ Philosophique_ | _o__) | Ben Finney From wuwei23 at gmail.com Fri Aug 21 01:17:29 2009 From: wuwei23 at gmail.com (alex23) Date: Thu, 20 Aug 2009 22:17:29 -0700 (PDT) Subject: 2.6 windows install References: Message-ID: <1e18d400-03ec-48ae-b59d-72aa6f5d9f64@l5g2000pra.googlegroups.com> "Tim Arnold" wrote: > Any ideas on what I'm missing here? Most likely the required configuration of the local environments. Did you install Python to the network device from your XP box? That would explain why you can run it: the required registry settings & environment variables are added by the installer, none of which is occurring on any computer other than the one from which you installed. To be honest, I've never seen a single-point-of-access network installation of Python for a Windows environment. If it was possible, I'd expect ActiveState's ActivePython to support it but there's no mention of it in the list of acceptable installer switches[1]. [1]: http://docs.activestate.com/activepython/2.6/installnotes.html#msi From ben+python at benfinney.id.au Fri Aug 21 01:18:09 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 15:18:09 +1000 Subject: install package in a particular python version References: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> Message-ID: <87y6pdzqwe.fsf@benfinney.id.au> Steve1234 writes: > I installed the boto module in my Ubuntu system using "python setup.py > install" and it installs in my python2.6 version and works great. That's because your ?python? command is doing the same thing as if you'd typed:: $ python2.6 setup.py install The Python 2.6 interpreter knows where its ?site-packages? path is, and so ?setup.py? in turn knows where to put files. > Now I want to install boto into my python2.5 version Invoke the specific Python interpreter you want:: $ python2.5 setup.py install -- \ ?Don't worry about people stealing your ideas. If your ideas | `\ are any good, you'll have to ram them down people's throats.? | _o__) ?Howard Aiken | Ben Finney From josefg at gmail.com Fri Aug 21 02:07:18 2009 From: josefg at gmail.com (josef) Date: Thu, 20 Aug 2009 23:07:18 -0700 (PDT) Subject: Object Reference question Message-ID: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> To begin, I'm new with python. I've read a few discussions about object references and I think I understand them. To be clear, Python uses a "Pass By Object Reference" model. x = 1 x becomes the object reference, while an object is created with the type 'int', value 1, and identifier (id(x)). Doing this with a class, x = myclass(), does the same thing, but with more or less object attributes. Every object has a type and an identifier (id()), according to the Python Language Reference for 2.6.2 section 3.1. x in both cases is the object reference. I would like to use the object to refer to the object reference. If I have a gross misunderstanding, please correct me. The following is what I would like to do: I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d is an object reference. Entering dk gives me the object: [MyClass0 instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at 0x0010 ... ] I need the object reference name (a,b,c,d) from dk to use as input for a file. Where do I find the memory location of the object reference and the object reference name memory location? I am unconcerned with the fact that the memory location will change the next time I run a python session. I will be using the object reference name for processing right away. My main focus of this post is: "How do I find and use object reference memory locations?" Thoughts? Thanks, Josef From milesck at umich.edu Fri Aug 21 02:18:35 2009 From: milesck at umich.edu (Miles Kaufmann) Date: Thu, 20 Aug 2009 23:18:35 -0700 Subject: Waiting for a subprocess to exit In-Reply-To: <873a7l21gr.fsf@benfinney.id.au> References: <873a7l21gr.fsf@benfinney.id.au> Message-ID: On Aug 20, 2009, at 10:13 PM, Ben Finney wrote: > The module documentation has a section on replacing ?os.system? > , which > says to use:: > > process = subprocess.Popen("mycmd" + " myarg", shell=True) > status = os.waitpid(process.pid, 0) > > But a ?Popen? instance has its own ?wait? method, which waits for exit > . > Why would I use ?os.waitpid? instead of:: > > process = subprocess.Popen("mycmd" + " myarg", shell=True) > process.wait() > status = process.returncode Really, you can just use: process = subprocess.Popen("mycmd" + " myarg", shell=True) status = process.wait() I'm not sure why the documentation suggests using os.waitpid. I would recommend avoiding shell=True whenever possible. It's used in the examples, I suspect, to ease the transition from the functions being replaced, but all it takes is for a filename or some other input to unexpectedly contain whitespace or a metacharacter and your script will stop working--or worse, do damage (cf. the iTunes 2 installer debacle[1]). Leaving shell=False makes scripts more secure and robust; besides, when I'm putting together a command and its arguments, it's as convenient to build a list (['mycmd', 'myarg']) as it is a string (if not more so). -Miles [1]: http://apple.slashdot.org/article.pl?sid=01/11/04/0412209#comment_2518563 From milesck at umich.edu Fri Aug 21 02:34:13 2009 From: milesck at umich.edu (Miles Kaufmann) Date: Thu, 20 Aug 2009 23:34:13 -0700 Subject: Object Reference question In-Reply-To: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <502C2E44-39EE-42E5-A9EA-3110CAEFF99D@umich.edu> On Aug 20, 2009, at 11:07 PM, josef wrote: > To begin, I'm new with python. I've read a few discussions about > object references and I think I understand them. > > To be clear, Python uses a "Pass By Object Reference" model. > x = 1 > x becomes the object reference, while an object is created with the > type 'int', value 1, and identifier (id(x)). Doing this with a class, > x = myclass(), does the same thing, but with more or less object > attributes. Every object has a type and an identifier (id()), > according to the Python Language Reference for 2.6.2 section 3.1. > > x in both cases is the object reference. I would like to use the > object to refer to the object reference. Stop right there. 'x' is not *the* object reference. It is *an* object reference (or in my preferred terminology, a label). Suppose you do: x = myclass() y = x The labels 'x' and 'y' both refer to the same object with equal precedence. There is no mapping from object back to label; it is a one-way pointer. Also importantly, labels themselves are not objects, and cannot be accessed or referred to. (This is a slight oversimplification; thanks to Python's reflection and introspection capabilities, it is possible to access labels to some extent, and in some limited situations it is possible to use stack inspection to obtain a label for an object. But this is hackish and error-prone, and should never be used when a more Pythonic method is available.) > The following is what I would like to do: > I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d > is an object reference. Entering dk gives me the object: [MyClass0 > instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at > 0x0010 ... ] > > I need the object reference name (a,b,c,d) from dk to use as input for > a file. It sounds like you should either be storing that name as an attribute of the object, or using a dictionary ({'a': a, 'b': b, ...}). -Miles From clp2 at rebertia.com Fri Aug 21 02:39:41 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 20 Aug 2009 23:39:41 -0700 Subject: Object Reference question In-Reply-To: <502C2E44-39EE-42E5-A9EA-3110CAEFF99D@umich.edu> References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <502C2E44-39EE-42E5-A9EA-3110CAEFF99D@umich.edu> Message-ID: <50697b2c0908202339w46e11252xc1fb86f770423f19@mail.gmail.com> On Thu, Aug 20, 2009 at 11:34 PM, Miles Kaufmann wrote: > On Aug 20, 2009, at 11:07 PM, josef wrote: >> The following is what I would like to do: >> I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d >> is an object reference. Entering dk gives me the object: [MyClass0 >> instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at >> 0x0010 ... ] >> >> I need the object reference name (a,b,c,d) from dk to use as input for >> a file. > > It sounds like you should either be storing that name as an attribute of the > object, or using a dictionary ({'a': a, 'b': b, ...}). Shorter way to produce the same dictionary: dict(a=a, b=b, ...) Cheers, Chris -- http://blog.rebertia.com From python at rcn.com Fri Aug 21 02:42:34 2009 From: python at rcn.com (Raymond Hettinger) Date: Thu, 20 Aug 2009 23:42:34 -0700 (PDT) Subject: #elements of seq A in seq B References: Message-ID: On Aug 19, 4:19?pm, Neal Becker wrote: > What would be a time efficient way to count the number of occurrences of > elements of sequence A in sequence B? ?(in this particular case, these > sequences are strings, if that matters). Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import collections >>> A = 'abc' >>> B = 'abracadabra' >>> collections.Counter(filter(A.__contains__, B)) Counter({'a': 5, 'b': 2, 'c': 1}) Raymond From python at rcn.com Fri Aug 21 02:44:29 2009 From: python at rcn.com (Raymond Hettinger) Date: Thu, 20 Aug 2009 23:44:29 -0700 (PDT) Subject: #elements of seq A in seq B References: Message-ID: <3f0fe16b-19df-4e48-94a6-96ea303c6ff2@g1g2000pra.googlegroups.com> On Aug 19, 4:19?pm, Neal Becker wrote: > What would be a time efficient way to count the number of occurrences of > elements of sequence A in sequence B? ?(in this particular case, these > sequences are strings, if that matters). Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import collections >>> A = 'abc' >>> B = 'abracadabra' >>> collections.Counter(filter(set(A).__contains__, B)) Counter({'a': 5, 'b': 2, 'c': 1}) Raymond From hendrik at microcorp.co.za Fri Aug 21 02:50:13 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 21 Aug 2009 08:50:13 +0200 Subject: Object Reference question In-Reply-To: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <200908210850.14075.hendrik@microcorp.co.za> On Friday 21 August 2009 08:07:18 josef wrote: > My main focus of this post is: "How do I find and use object reference > memory locations?" >>> a = [1,2,3,4] >>> id(a) 8347088 >>> - Hendrik From josefg at gmail.com Fri Aug 21 02:56:57 2009 From: josefg at gmail.com (josef) Date: Thu, 20 Aug 2009 23:56:57 -0700 (PDT) Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <627db5cc-7758-4d09-9ca4-78bc501c2626@d4g2000yqa.googlegroups.com> On Aug 21, 1:34?am, Miles Kaufmann wrote: > On Aug 20, 2009, at 11:07 PM, josef wrote: > > > To begin, I'm new with python. I've read a few discussions about > > object references and I think I understand them. > > > To be clear, Python uses a "Pass By Object Reference" model. > > x = 1 > > x becomes the object reference, while an object is created with the > > type 'int', value 1, and identifier (id(x)). Doing this with a class, > > x = myclass(), does the same thing, but with more or less object > > attributes. Every object has a type and an identifier (id()), > > according to the Python Language Reference for 2.6.2 section 3.1. > > > x in both cases is the object reference. I would like to use the > > object to refer to the object reference. > > Stop right there. ?'x' is not *the* object reference. ?It is *an* ? > object reference (or in my preferred terminology, a label). ?Suppose ? > you do: > > x = myclass() > y = x It would not make sense to do that in the context of the software I am writing. The documentation will specifically state not to do that. If the user does do that, then the user will be disappointed and possibly angry. > > The labels 'x' and 'y' both refer to the same object with equal ? > precedence. ?There is no mapping from object back to label; it is a ? > one-way pointer. ?Also importantly, labels themselves are not objects, ? > and cannot be accessed or referred to. I would just like to store the name of the one way pointer. > > (This is a slight oversimplification; thanks to Python's reflection ? > and introspection capabilities, it is possible to access labels to ? > some extent, and in some limited situations it is possible to use ? > stack inspection to obtain a label for an object. ?But this is hackish ? > and error-prone, and should never be used when a more Pythonic method ? > is available.) Hackish is fine. How error-prone is this method? > > > The following is what I would like to do: > > I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d > > is an object reference. Entering dk gives me the object: [MyClass0 > > instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at > > 0x0010 ... ] > > > I need the object reference name (a,b,c,d) from dk to use as input for > > a file. > > It sounds like you should either be storing that name as an attribute ? > of the object, or using a dictionary ({'a': a, 'b': b, ...}). That solution was mentioned in some of the discussions I read, but I would like to stay away from something like: a = MyClass (name='a', ...). Is it possible to assign an object reference name in a class __init__ defintion? From __peter__ at web.de Fri Aug 21 03:43:51 2009 From: __peter__ at web.de (Peter Otten) Date: Fri, 21 Aug 2009 09:43:51 +0200 Subject: #elements of seq A in seq B References: Message-ID: Jan Kaliszewski wrote: > 20-08-2009 o 13:01:29 Neal Becker wrote: > >> I meant #occurrences of characters from the set A in string B > > But: > > 1) separately for each element of A? (see Simon's sollution with > defaultdict) > > 2) or total number of all occurrences of elements of A? (see below) > > > 20-08-2009 o 14:05:12 Peter Otten <__peter__ at web.de> wrote: > >> identity = "".join(map(chr, range(256))) >> n = len(b) - len(b.translate(identity, a)) > > Nice, though I'd prefer Simon's sollution: > > a = set(a) > n = sum(item in a for item in b) Just to give you an idea why I posted the former: $ python -m timeit -s"a = set('abc'); b = 'abcdefg'*10**5" 'sum(item in a for item in b)' 10 loops, best of 3: 195 msec per loop $ python -m timeit -s"a = 'abc'; b = 'abcdefg'*10**5; id=''.join(map(chr, range(256)))" 'len(b) - len(b.translate(id, a))' 100 loops, best of 3: 4.97 msec per loop Peter From davea at ieee.org Fri Aug 21 03:56:57 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 21 Aug 2009 03:56:57 -0400 Subject: Object Reference question In-Reply-To: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <4A8E5349.80104@ieee.org> josef wrote: > To begin, I'm new with python. I've read a few discussions about > object references and I think I understand them. > > To be clear, Python uses a "Pass By Object Reference" model. > x = 1 > x becomes the object reference, while an object is created with the > type 'int', value 1, and identifier (id(x)). Doing this with a class, > x = myclass(), does the same thing, but with more or less object > attributes. Every object has a type and an identifier (id()), > according to the Python Language Reference for 2.6.2 section 3.1. > > x in both cases is the object reference. I would like to use the > object to refer to the object reference. If I have a gross > misunderstanding, please correct me. > > The following is what I would like to do: > I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d > is an object reference. Entering dk gives me the object: [MyClass0 > instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at > 0x0010 ... ] > > I need the object reference name (a,b,c,d) from dk to use as input for > a file. Where do I find the memory location of the object reference > and the object reference name memory location? I am unconcerned with > the fact that the memory location will change the next time I run a > python session. I will be using the object reference name for > processing right away. > > My main focus of this post is: "How do I find and use object reference > memory locations?" > > Thoughts? > Thanks, > > Josef > > There was a similar query here within the last couple of months, and lots of interesting discussion. But I never saw a use case convincing enough for me to want to remember how the various suggestions worked. Just how are you planning to use this? Are you planning to write a debugger? Or are you trying to keep mnemonic names for all instances of a particular class? Is this for a particular program's use, or are you trying to create a library to be used to reverse engineer some software you con't control? Several of your phrasings imply you don't understand Python yet. "memory location" - invisible to python use. And although id() will give you a hash-code that's actually a memory address, there's no direct way to use it. And names (attributes) don't necessarily have an address. "the object reference name (a,b,c,d) from dk" What is this? There's nothing that even conceptually looks like that when you assign dk = [a, b, c, d] A given object may have one to many references, and some of these may have names. If you constrain those names to be in a particular context, it may be possible to search for which name(s) currently happen(s) to point to the given object. For example, if you have the following at top level in a module: a = MyClass0() b = MyClass1() c = MyClass2() dk = [a, b, c] then, given the id() of dk[2], you could search the particular modules global name dictionary, and find c. But for the following fragment, you could not: a = MyClass0() b = MyClass1() c = MyClass2() dk = [a, b, c] c = 42 dk remains the same, but the dk[2] item no longer has any name referencing it. At any given instant of time, most objects in a typical program have no name associated with them. Many of them never did have a name. What would you want if dk had been created as: dk = [MyClass0(), MyClass1(), MyClass2()] or if a, b, and/or c were local variables in a function that's long since quit running, or that has run many times, each time creating new objects? DaveA From catalinfest at gmail.com Fri Aug 21 04:09:09 2009 From: catalinfest at gmail.com (catafest) Date: Fri, 21 Aug 2009 01:09:09 -0700 (PDT) Subject: PIL and Python References: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> Message-ID: <5df342cf-c742-42d6-bc8c-97a3c44a0816@h21g2000yqa.googlegroups.com> I don't extract data from jpegs. I wanna put some data in this (copyright of my site) ... On Aug 20, 2:01?pm, MaxTheMouse wrote: > On Aug 20, 10:23?am, catafest wrote: > > > On my photo jpg i have this : > > > Image Type: jpeg (The JPEG image format) > > Width: 1224 pixels > > Height: 1632 pixels > > Camera Brand: Sony Ericsson > > Camera Model: W810i > > Date Taken: 2009:07:09 08:16:21 > > Exposure Time: 1/19 sec. > > ISO Speed Rating: 320 > > Flash Fired: Flash did not fire, compulsory flash mode. > > Metering Mode: Center-Weighted Average > > Software: R4EA031 ? ? prgCXC1250321_ORANGE_HN 4.5 > > > This is the data i want edit it to make some copyright for my site. > > I don't know about PIL but you might want to try exif.py.http://sourceforge.net/projects/exif-py/ From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 21 04:34:09 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 21 Aug 2009 10:34:09 +0200 Subject: Object Reference question In-Reply-To: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <4a8e5bf6$0$15180$426a74cc@news.free.fr> josef a ?crit : > To begin, I'm new with python. I've read a few discussions about > object references and I think I understand them. > > To be clear, Python uses a "Pass By Object Reference" model. > x = 1 > x becomes the object reference, while an object is created with the > type 'int', value 1, and identifier (id(x)). Doing this with a class, > x = myclass(), does the same thing, but with more or less object > attributes. Every object has a type and an identifier (id()), > according to the Python Language Reference for 2.6.2 section 3.1. > > x in both cases is the object reference. Nope. It's *a* reference to the object - or, more exactly, a key in a mapping (the current namespace), which is associatied with a reference to the object. You can translate: x = 1 to: current_namespace['x'] = int(1) > I would like to use the > object to refer to the object reference. If I have a gross > misunderstanding, please correct me. > > The following is what I would like to do: > I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d > is an object reference. Entering dk gives me the object: [MyClass0 > instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at > 0x0010 ... ] > > I need the object reference name (a,b,c,d) from dk to use as input for > a file. ??? Could you elaborate, please ? > Where do I find the memory location of the object reference > and the object reference name memory location? short answer : you don't. Python is a high level language, 'memory location' is an implementation detail (and highly implementation-dependant), and *not* exposed (at least not in any usable way). > I am unconcerned with > the fact that the memory location will change the next time I run a > python session. I will be using the object reference name for > processing right away. > > My main focus of this post is: "How do I find and use object reference > memory locations?" > > Thoughts? Yes : please explain the problem you're trying to solve. I mean, the *real* problem - what you want to achieve -, not what you think is the solution !-) From gagsl-py2 at yahoo.com.ar Fri Aug 21 04:36:38 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Aug 2009 05:36:38 -0300 Subject: difference between 2 arrays References: <4a8d1d3f$0$23447$ba4acef3@news.orange.fr> Message-ID: En Thu, 20 Aug 2009 06:54:05 -0300, <""Michel Claveau - MVP"> escribi?: > Yes, the module sets is written, in doc, like "deprecated". > But: > - sets exist in Python 2.6 (& 2.5 or 2.4) > - documentation of sets (module) is better tha, documentation of set > (builtin) > > The best: read the documentaion of the module, and use the builtin... Any suggestion to improve the builtin set documentation? In what ways do you see one is better than the other? -- Gabriel Genellina From dickey at his.com Fri Aug 21 04:47:42 2009 From: dickey at his.com (Thomas Dickey) Date: Fri, 21 Aug 2009 01:47:42 -0700 (PDT) Subject: ncurses getch & unicode (was: decoding keyboard input when using curses) References: <65a1d6f80908200936g18b235fcw49d0047168cf9548@mail.gmail.com> Message-ID: <0a683d75-ac07-40a6-8374-2a2e900ac0ba@j21g2000yqe.googlegroups.com> On Aug 20, 6:12?pm, I?igo Serna wrote: > Hi again, > > 2009/8/20 I?igo Serna > > I have the same problem mentioned inhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/...some months ago. > > > Python 2.6 program which usesncursesmodule in a terminal configured to use UTF-8 encoding. > > > When trying to get input from keyboard, a non-ascii character (like ?) is returned as 2 integers < 255, needing 2 calls to getch method to get both. > > These two integers \xc3 \xa7 forms the utf-8 encoded representation of ? character. > > >ncursesget_wch documentation states the function should return an unique integer > 255 with the ordinal representation of that unicode char encoded in UTF-8, \xc3a7. > > Answering myself, I've copied at the bottom of this email a working > solution, but the question still remains: why win.getch() doesn't > return the correct value? The code looks consistent with the curses functions... > Kind regards, > I?igo Serna > > ###################################################################### > # test.py > import curses > > import locale > locale.setlocale(locale.LC_ALL, '') > print locale.getpreferredencoding() > > def get_char(win): > ??? def get_check_next_byte(): > ??????? c = win.getch() You're using "getch", not "get_wch" (Python's ncurses binding may/may not have the latter). curses getch returns 8-bit values, get_wch would return wider values. From ben+python at benfinney.id.au Fri Aug 21 04:49:19 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 18:49:19 +1000 Subject: Waiting for a subprocess to exit References: <873a7l21gr.fsf@benfinney.id.au> Message-ID: <87fxbllfg0.fsf@benfinney.id.au> Miles Kaufmann writes: > On Aug 20, 2009, at 10:13 PM, Ben Finney wrote: > > Why would I use ?os.waitpid? instead of:: > > > > process = subprocess.Popen("mycmd" + " myarg", shell=True) > > process.wait() > > status = process.returncode > > Really, you can just use: > > process = subprocess.Popen("mycmd" + " myarg", shell=True) > status = process.wait() Ah thanks, that's even better. > I'm not sure why the documentation suggests using os.waitpid. Could someone who knows how to drive the Python BTS please report that against the ?subprocess? documentation? -- \ ?I am amazed, O Wall, that you have not collapsed and fallen, | `\ since you must bear the tedious stupidities of so many | _o__) scrawlers.? ?anonymous graffiti, Pompeii, 79 CE | Ben Finney From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 21 04:52:05 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 21 Aug 2009 10:52:05 +0200 Subject: Problem with arrays in a recursive class function In-Reply-To: <190378bc-f095-46fa-9104-cb94fa09698f@g10g2000yqh.googlegroups.com> References: <190378bc-f095-46fa-9104-cb94fa09698f@g10g2000yqh.googlegroups.com> Message-ID: <4a8e6029$0$20864$426a34cc@news.free.fr> Aaron Scott a ?crit : > I have a list of nodes, and I need to find a path from one node to > another. The nodes each have a list of nodes they are connected to, > set up like this: > > > > class Node(object): > def __init__(self, connectedNodes): > self.connectedNodes = connectedNodes > > nodes = { > 1: Node([4]), > 2: Node([3]), > 3: Node([2, 4, 5]), > 4: Node([1, 6, 3]), > 5: Node([3, 7]), > 6: Node([4, 9]), > 7: Node([5, 8]), > 8: Node([7, 9]), > 9: Node([6, 8]) > } > > > > I made a quick brute-force pathfinder to solve it (in this case, a > path from node 1 to node 9). Here it is: > > > > class PathFind(object): > def __init__(self, source, destination): > self.source = source > self.destination = destination > self.solved = [] > def Search(self): > self.PathFind([self.source]) > > if self.solved: > print "Solutions: " > for i in self.solved: > print "\t" + str(i) print "\t%s" % i > else: > print "Couldn't solve." > def PathFind(self, trail): > location = trail[-1] > if location == self.destination: > self.solved.append(trail) I think you want self.solved.append(trail[:]) Hint : Python doesn't use "pass by value". > The problem is the array trail[], which seems to survive from instance > to instance of PathFind(). I thought that by calling self.PathFind > (trail[:]), I was creating a new copy of trail[], Yes. But on the 'not solved' branch, you do mutate trail !-) From ben+python at benfinney.id.au Fri Aug 21 05:08:08 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 19:08:08 +1000 Subject: Sanitising arguments to shell commands (was: Waiting for a subprocess to exit) References: <873a7l21gr.fsf@benfinney.id.au> Message-ID: <87ab1tlekn.fsf_-_@benfinney.id.au> Miles Kaufmann writes: > I would recommend avoiding shell=True whenever possible. It's used in > the examples, I suspect, to ease the transition from the functions > being replaced, but all it takes is for a filename or some other input > to unexpectedly contain whitespace or a metacharacter and your script > will stop working--or worse, do damage (cf. the iTunes 2 installer > debacle[1]). Agreed, and that's my motivation for learning about ?subprocess.Popen?. > Leaving shell=False makes scripts more secure and robust; besides, > when I'm putting together a command and its arguments, it's as > convenient to build a list (['mycmd', 'myarg']) as it is a string (if > not more so). Which leads to another issue: I'm modifying a program that gets its child process command arguments from three places: * hard-coded text within the program (e.g. the command name, and context-specific arguments for the specific operation to be performed) * user-customised options to be added to the command line * filenames from the program's own command line For the hard-coded argument text, obviously they can simply be hard-coded as list elements:: command_args = ["foo", "--bar"] The filenames to be processed can also be appended one item per filename. However, the user-customised options are specified by the user in a configuration file, as a single string argument:: [fooprogram] additional_args = --baz 'crunch cronch' --wobble This works fine if the command line is constructed by dumb string concatenation; but obviously it fails when I try to construct a list of command line arguments. It's quite reasonable for the user to expect to be able to put any partial shell command-line in that string option and expect it will be processed by the shell, including any quoting or other escaping. How can I take a string that is intended to be part of a command line, representing multiple arguments and the shell's own escape characters as in the above example, and end up with a sane command argument list for ?subprocess.Popen?? E.g.:: parser = optparse.OptionParser() (options_args) = parser.parse_args(argv[1:]) filenames = args config = configparser.ConfigParser() config.read([system_config_file_path, user_config_file_path]) user_configured_args = config.get('fooprogram', 'additional_args') command_args = ["foo", "--bar"] somehow_append_each_argument(command_args, user_configured_args) command_args.extend(filenames) command_process = subprocess.Popen(command_args, shell=False) The resulting ?command_args? list should be:: ["foo", "--bar", "--baz", "crunch cronch", "--wobble", "spam.txt", "beans.txt"] How can I write the ?somehow_append_each_argument? step to get that result? -- \ ?Every sentence I utter must be understood not as an | `\ affirmation, but as a question.? ?Niels Bohr | _o__) | Ben Finney From clp2 at rebertia.com Fri Aug 21 05:19:13 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 Aug 2009 02:19:13 -0700 Subject: Sanitising arguments to shell commands (was: Waiting for a subprocess to exit) In-Reply-To: <87ab1tlekn.fsf_-_@benfinney.id.au> References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> Message-ID: <50697b2c0908210219i5e02c0cbq2d63bff891624ef4@mail.gmail.com> On Fri, Aug 21, 2009 at 2:08 AM, Ben Finney wrote: > How can I take a string that is intended to be part of a command line, > representing multiple arguments and the shell's own escape characters as > in the above example, and end up with a sane command argument list for > ?subprocess.Popen?? http://docs.python.org/library/shlex.html module shlex ? Simple lexical analysis New in version 1.5.2. "The shlex class makes it easy to write lexical analyzers for simple syntaxes resembling that of the Unix shell." Cheers, Chris -- http://blog.rebertia.com From jeanmichel at sequans.com Fri Aug 21 05:22:03 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 21 Aug 2009 11:22:03 +0200 Subject: Sanitising arguments to shell commands In-Reply-To: <87ab1tlekn.fsf_-_@benfinney.id.au> References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> Message-ID: <4A8E673B.3060606@sequans.com> Ben Finney wrote: > Miles Kaufmann writes: > > >> I would recommend avoiding shell=True whenever possible. It's used in >> the examples, I suspect, to ease the transition from the functions >> being replaced, but all it takes is for a filename or some other input >> to unexpectedly contain whitespace or a metacharacter and your script >> will stop working--or worse, do damage (cf. the iTunes 2 installer >> debacle[1]). >> > > Agreed, and that's my motivation for learning about ?subprocess.Popen?. > Can someone explain the difference with the shell argument ? giving for instance an example of what True will do that False won't. I mean, I've read the doc, and to be honest, I didn't get it. I'm concerned because I'm using subprocess, but I guess my shell arg has been filled a little bit random.. JM From ben+python at benfinney.id.au Fri Aug 21 05:26:54 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 19:26:54 +1000 Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <8763chldpd.fsf@benfinney.id.au> josef writes: > To be clear, Python uses a "Pass By Object Reference" model. Yes. (I'm glad this concept has propagated to newcomers so well :-) > x = 1 > x becomes the object reference It becomes *a* reference to that object, independent of any other references to that same object. > while an object is created with the type 'int', value 1, and > identifier (id(x)). Not really ?while?. The object creation happens first, then the assignment statement binds a reference to that object. > Doing this with a class, x = myclass(), does the same thing, but with > more or less object attributes. Every object has a type and an > identifier (id()), according to the Python Language Reference for > 2.6.2 section 3.1. Any expression can be on the right side of the assignment operator. The expression will evaluate to some object, which the assignment will then bind to the reference on the left side of the assignment operator. > x in both cases is the object reference. It is *an* object reference; that is, it's an identifier which refers to an object. There's nothing about that identifier that makes it ?the (one and only) object reference?. > I would like to use the object to refer to the object reference. If I > have a gross misunderstanding, please correct me. Yes, it's a simple misunderstanding: objects do not, in general, know any of the references there may be to them. > The following is what I would like to do: I have a list of class > instances dk = [ a, b, c, d ], where a, b, c, d is an object > reference. Note that, after that list is created, each item in that list is *also* a reference to the corresponding object. That is, ?a? is a reference to an object, and ?dk[0]? is a *different* reference to the *same* object. The object has no knowledge about those references. > Entering dk gives me the object: [MyClass0 instance at 0x0000, > MyClass1 instance at 0x0008, MyClass2 instance at 0x0010 ... ] This is a hint that, when asked for a string representation, each of the objects in that list can say little more than that they are of a particular type, and are located at a particular memory address. They do not know any of the references to themselves. > I need the object reference name (a,b,c,d) from dk to use as input for > a file. You'll have to track that yourself. A good way to keep track of name-to-object mappings is with Python's built-in mapping type, ?dict?:: dk = {'a': a, 'b': b, 'c': c, 'd': d} (There are more efficient ways to create a dictionary without such repetition, of course, but this is more illustrative of the point.) You can then get a list (assembled in arbitrary sequence) of just the keys, or just the values, or the key-value pairs, from the dict with its ?keys?, ?values?, and ?items? methods respectively:: >>> dk = {'a': a, 'b': b, 'c': c, 'd': d} >>> dk.keys() ['a', 'c', 'd', 'b'] >>> dk.values() [, , , ] >>> dk.items() [('b', ), ('c', ), ('a', ), ('d', )] Each of these is even better used as the iterable for a ?for? loop:: >>> for (key, value) in dk.items(): ... print "Here is item named", key ... print value > My main focus of this post is: "How do I find and use object reference > memory locations?" You don't. Use the references in your code, forget about the memory addresses, and remember that container objects themselves contain references, so use them for organising your objects. -- \ ?Demagogue: One who preaches doctrines he knows to be untrue to | `\ men he knows to be idiots.? ?Henry L. Mencken | _o__) | Ben Finney From ben+python at benfinney.id.au Fri Aug 21 06:18:29 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 20:18:29 +1000 Subject: Sanitising arguments to shell commands References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> Message-ID: <87ws4xjwqy.fsf@benfinney.id.au> Jean-Michel Pichavant writes: > Can someone explain the difference with the shell argument ? giving > for instance an example of what True will do that False won't. The ?shell? argument to the ?subprocess.Popen? constructor specifies whether the command-line should be invoked directly (?shell=False?) or indirectly through invoking a shell (?shell=True?). If ?shell=False?, the command-line arguments are used as direct arguments to the kernel's ?run this program for me?. If ?shell=True? the command-line arguments are themselves passed to a new instance of the user's current shell, as a command line that *it* should invoke on the program's behalf. This allows the command line to be manipulated and interpolated etc., the way it would be if typed at a new shell prompt. Then, that shell will in turn ask the kernel ?run this program for me? as it normally does after processing the arguments. > I mean, I've read the doc, and to be honest, I didn't get it. I'm > concerned because I'm using subprocess, but I guess my shell arg has > been filled a little bit random.. Use ?shell=False? by default (which, since that's the default for ?subprocess.Popen?, means you can omit it entirely), and specify exactly the command line arguments you want the kernel to execute. Only if you know you want a shell process to be involved should you use ?shell=True?. -- \ ?Welchen Teil von ?Gestalt? verstehen Sie nicht? [What part of | `\ ?gestalt? don't you understand?]? ?Karsten M. Self | _o__) | Ben Finney From ben+python at benfinney.id.au Fri Aug 21 06:26:02 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 21 Aug 2009 20:26:02 +1000 Subject: Sanitising arguments to shell commands References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> Message-ID: <87skfljwed.fsf@benfinney.id.au> Chris Rebert writes: > module shlex ? Simple lexical analysis > New in version 1.5.2. > "The shlex class makes it easy to write lexical analyzers for simple > syntaxes resembling that of the Unix shell." Exactly what I needed: >>> import shlex >>> user_configured_args = "--baz 'crunch cronch' --wobble" >>> filenames = ["spam.txt", "beans.txt"] >>> command_args = ["foo", "--bar"] >>> command_args.extend(shlex.split(user_configured_args)) >>> command_args.extend(filenames) >>> command_args ['foo', '--bar', '--baz', 'crunch cronch', '--wobble', 'spam.txt', 'beans.txt'] -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but if we get Sam Spade, we'll never have any puppies.? | _o__) ?_Pinky and The Brain_ | Ben Finney From gagsl-py2 at yahoo.com.ar Fri Aug 21 06:31:33 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 21 Aug 2009 07:31:33 -0300 Subject: Zipimport leaks memory? References: <6CC019B5D220A147932441E798B252B910B0193FEF@NOK-EUMSG-05.mgdnok.nokia.com> Message-ID: En Thu, 20 Aug 2009 07:02:26 -0300, ashwin.u.rao at nokia.com escribi?: > We are currently trying to identify and fix all the memory leaks by just > doing Py_Initialize-PyRun_SimpleFile(some simple script)-Py_Finalize and > found that there are around 70 malloc-ed blocks which are not freed. One > of the significant contributor to this number is the 'files' object in > ZipImporter. I am not able to identify the reason for this leak and was > wondering if anyone on this list would help me out here. > > So, here goes : > > Since we have a zip file in our sys.path, this object is initialized and > added to the zip_directory_cache dict during Py_Initialize. One point to > note here is that there is no DECREF on the 'files' object after adding > it to the zip_directory_cache dict. > > When a module in a directory is imported(encoding.alias) then the > reference count of 'files' is increased. When this module is unloaded > during Py_Finalize-PyImport_Cleanup, the ref count of files object is > decremented properly. So at the end of Py_Finalize the files object > still has one reference count which is a result of it being an entry in > the zip_directory_cache. I didn't read the source, but isn't that the expected behavior? If the module is still referenced by zip_directory_cache, the reference count must be 1 or more. Maybe zip_directory_cache should be cleared at interpreter shutdown? -- Gabriel Genellina From inigoserna at gmail.com Fri Aug 21 07:58:38 2009 From: inigoserna at gmail.com (=?UTF-8?B?ScOxaWdvIFNlcm5h?=) Date: Fri, 21 Aug 2009 13:58:38 +0200 Subject: ncurses getch & unicode (was: decoding keyboard input when using curses) In-Reply-To: <0a683d75-ac07-40a6-8374-2a2e900ac0ba@j21g2000yqe.googlegroups.com> References: <65a1d6f80908200936g18b235fcw49d0047168cf9548@mail.gmail.com> <0a683d75-ac07-40a6-8374-2a2e900ac0ba@j21g2000yqe.googlegroups.com> Message-ID: <65a1d6f80908210458hfa33699m398d9af6eab67674@mail.gmail.com> 2009/8/21 Thomas Dickey : > On Aug 20, 6:12?pm, I?igo Serna wrote: >> ??????? c = win.getch() > > You're using "getch", not "get_wch" (Python's ncurses binding may/may > not have the latter). > curses getch returns 8-bit values, get_wch would return wider values. you are right, ncurses binding does not have get_wch, only getch, and this last is the only one called in ncurses library bindings. Anyway, I've written a patch to include the get_wch method in the bindings. See http://bugs.python.org/issue6755 Thanks for the clarification, I?igo From georavel at yahoo.com Fri Aug 21 08:46:07 2009 From: georavel at yahoo.com (Justin) Date: Fri, 21 Aug 2009 05:46:07 -0700 (PDT) Subject: list 'results' from maps.google then crawl Message-ID: <81b5a7ba-49c7-4750-ad1d-5564973b6b8c@v36g2000yqv.googlegroups.com> list 'results' from maps.google then crawl through the (engine of some sort) space to the 'results' website and look at it html to find the contact From jeanmichel at sequans.com Fri Aug 21 08:55:33 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Fri, 21 Aug 2009 14:55:33 +0200 Subject: Sanitising arguments to shell commands In-Reply-To: <87ws4xjwqy.fsf@benfinney.id.au> References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> <87ws4xjwqy.fsf@benfinney.id.au> Message-ID: <4A8E9945.40906@sequans.com> Ben Finney wrote: > Jean-Michel Pichavant writes: > > >> Can someone explain the difference with the shell argument ? giving >> for instance an example of what True will do that False won't. >> > > The ?shell? argument to the ?subprocess.Popen? constructor specifies > whether the command-line should be invoked directly (?shell=False?) or > indirectly through invoking a shell (?shell=True?). > > If ?shell=False?, the command-line arguments are used as direct > arguments to the kernel's ?run this program for me?. > > If ?shell=True? the command-line arguments are themselves passed to a > new instance of the user's current shell, as a command line that *it* > should invoke on the program's behalf. This allows the command line to > be manipulated and interpolated etc., the way it would be if typed at a > new shell prompt. Then, that shell will in turn ask the kernel ?run this > program for me? as it normally does after processing the arguments. > > >> I mean, I've read the doc, and to be honest, I didn't get it. I'm >> concerned because I'm using subprocess, but I guess my shell arg has >> been filled a little bit random.. >> > > Use ?shell=False? by default (which, since that's the default for > ?subprocess.Popen?, means you can omit it entirely), and specify exactly > the command line arguments you want the kernel to execute. Only if you > know you want a shell process to be involved should you use > ?shell=True?. > > Thank you Ben for the update. It's clear for me now, I've checked and I use it with no shell arg, except at one place, but I don't think it's intended and it happens to work anyway. I've added a small comment just in case it fails in the future. JM From rickbking at comcast.net Fri Aug 21 09:07:04 2009 From: rickbking at comcast.net (Rick King) Date: Fri, 21 Aug 2009 09:07:04 -0400 Subject: Sanitising arguments to shell commands In-Reply-To: <50697b2c0908210219i5e02c0cbq2d63bff891624ef4@mail.gmail.com> References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> <50697b2c0908210219i5e02c0cbq2d63bff891624ef4@mail.gmail.com> Message-ID: <4A8E9BF8.8040206@comcast.net> shlex doesn't handle unicode input though, so, in general, it's not a good solution. Rick King Southfield MI > http://docs.python.org/library/shlex.html > > module shlex ? Simple lexical analysis > New in version 1.5.2. > "The shlex class makes it easy to write lexical analyzers for simple > syntaxes resembling that of the Unix shell." > From countryone77 at yahoo.com Fri Aug 21 09:34:04 2009 From: countryone77 at yahoo.com (Bev in TX) Date: Fri, 21 Aug 2009 06:34:04 -0700 (PDT) Subject: Logging with SMTP Error on Mac Message-ID: Hi, I've done some Python programming, but I still consider myself a Python newbie. I have a Mac Pro OS X 10.5.8 system and I installed Python 2.6.2 (the latest package available for the Mac) yesterday. I was working through Matt Wilson's article on using the logging module: http://blog.tplus1.com/index.php/2007/09/28/the-python-logging-module-is-much-better-than-print-statements/ (If that does not work, then try: http://tinyurl.com/5v2lcy ) Everything worked great until his last example. My ISP does not provide e-mail, so I tried using gmail in the line that sets h2. I substituted "mailid" for my actual e-mail address in the following examples; in my test I used my actual e-mail ID. Also, I used the full path to the newly installed Python 2.6.2; otherwise it picked up the older Python 2.5: #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python First attempt: h2 = logging.handlers.SMTPHandler('smtp.gmail.com', 'mailid at gmail.com', ['mailid at gmail.com'],'ERROR log') However, that caused the following error to be issued: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/logging/handlers.py", line 868, in emit smtp.sendmail(self.fromaddr, self.toaddrs, msg) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/smtplib.py", line 698, in sendmail raise SMTPSenderRefused(code, resp, from_addr) SMTPSenderRefused: (530, '5.7.0 Must issue a STARTTLS command first. 7sm3867994qwf.47', 'mailid at gmail.com') I also tried providing my gmail userid/password, I tried adding a 5th, credential, argument, which is a tupple, (username,password) (new in 2.6). Second attempt: h2 = logging.handlers.SMTPHandler('smtp.gmail.com', 'mailid at gmail.com', ['mailid at gmail.com'],'ERROR log',('mailid at gmail.com','gmail- password')) However, that caused the following error message: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/logging/handlers.py", line 867, in emit smtp.login(self.username, self.password) File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ python2.6/smtplib.py", line 552, in login raise SMTPException("SMTP AUTH extension not supported by server.") SMTPException: SMTP AUTH extension not supported by server. I am able access gmail via Mac's Mail, in which it says that outgoing mail is going to: smtp.gmail.com:mailid I tried using that as the server in the Python script, but it could not find that server. Is this possible? If I am doing something incorrectly, would someone please indicate what it is? Thanks, Bev in TX From fabio at aptana.com Fri Aug 21 09:36:34 2009 From: fabio at aptana.com (Fabio Zadrozny) Date: Fri, 21 Aug 2009 10:36:34 -0300 Subject: Pydev 1.4.8 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.4.8 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Created public API for starting/finishing debug server * Import based on unresolved variables works correctly when the document is changed * Ignore error works correctly when the document is changed * No longer showing the replace button for the search Release Highlights in Pydev: ---------------------------------------------- * Debugger can jump to line * Reloading module when code changes in the editor if inside debug session * Usability improvement on the preferences pages (editor, code-formatter, comment block and code-style showing examples) * Pythonpath reported in the main tab was not correct for ironpython launch configs * Main module tab in launch configuration was not appearing for jython * Multiline block comments considering the current indentation (and working with tabs) * Hover works correctly when the document is changed * The interactive console no longer uses the UI thread (so, it doesn't make eclipse halt anymore on slow requests to the shell) * The interactive console save history now saves the contents in the same way they're written * When creating a python run, the classpath was being set (and overridden), which should only happen in jython runs * Fixed issue where a line with only tabs and a close parenthesis would have additional tabs entered on code-formatting * A Pydev (Jython) project can coexist with a JDT project (and properly use its info -- only project references worked previously) * Many small usability improvements (editors improved) * Verbosity option added to run as unit-test * No longer using respectJavaAccessibility=False for jython * When there are too many items to show in the debugger, handle it gracefully What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python, Jython and Iron Python development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer Aptana http://aptana.com/python Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Environment for Eclipse http://pydev.sf.net http://pydev.blogspot.com From jfine at pytex.org Fri Aug 21 09:36:35 2009 From: jfine at pytex.org (Jonathan Fine) Date: Fri, 21 Aug 2009 14:36:35 +0100 Subject: Using 'apply' as a decorator, to define constants Message-ID: Hi It might seem odd to use 'apply' as a decorator, but it can make sense. I want to write: # Top level in module. tags = where the list is most easily constructed using a function. And so I write: @apply def tags(): value = [] # complicated code return value And now 'tags' has the result of running the complicated code. Without using 'apply' as a decorator one alternative is def tmp(): value = [] # complicated code return value tags = tmp() del tmp Like all uses of decorators, it is simply syntactic sugar. It allows you to see, up front, what is going to happen. I think, once I get used to it, I'll get to like it. The way to read @apply def name(): # code is that we are defining 'name' to be the return value of the effectively anonymous function that follows. -- Jonathan From stefan_ml at behnel.de Fri Aug 21 09:37:44 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 21 Aug 2009 15:37:44 +0200 Subject: list 'results' from maps.google then crawl In-Reply-To: <81b5a7ba-49c7-4750-ad1d-5564973b6b8c@v36g2000yqv.googlegroups.com> References: <81b5a7ba-49c7-4750-ad1d-5564973b6b8c@v36g2000yqv.googlegroups.com> Message-ID: <4a8ea328$0$31861$9b4e6d93@newsspool3.arcor-online.net> Justin wrote: > list 'results' from maps.google then crawl through the (engine of some > sort) space to the 'results' website and look at it html to find the > contact Good idea. How do you know how to recognise the contact? He/she might come disguised. Stefan From sajmikins at gmail.com Fri Aug 21 10:23:30 2009 From: sajmikins at gmail.com (Simon Forman) Date: Fri, 21 Aug 2009 07:23:30 -0700 (PDT) Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: On Aug 21, 2:07?am, josef wrote: > To begin, I'm new with python. I've read a few discussions about > object references and I think I understand them. > > To be clear, Python uses a "Pass By Object Reference" model. > x = 1 > x becomes the object reference, while an object is created with the > type 'int', value 1, and identifier (id(x)). Doing this with a class, > x = myclass(), does the same thing, but with more or less object > attributes. Every object has a type and an identifier (id()), > according to the Python Language Reference for 2.6.2 section 3.1. > > x in both cases is the object reference. I would like to use the > object to refer to the object reference. If I have a gross > misunderstanding, please correct me. x is not the object reference, it's just a string used as a key in a dict (the value is the object reference): |>>> globals() |{'__builtins__': , '__name__': '__main__', '__doc__': None} |>>> x = 1 |>>> globals() |{'__builtins__': , '__name__': '__main__', '__doc__': None, 'x': 1} I don't understand what you're trying to do, but give up the idea of "object reference memory locations". Any name binding in python just associates a string with a object in one of various namespace dictionaries. HTH, ~Simon From tsuraan at gmail.com Fri Aug 21 10:50:01 2009 From: tsuraan at gmail.com (tsuraan) Date: Fri, 21 Aug 2009 09:50:01 -0500 Subject: Conditionally skipping the contents of a with-statement Message-ID: <84fb38e30908210750v212339c2x2c87df33c2fcf069@mail.gmail.com> I'd like to write a Fork class to wrap os.fork that allows something like this: with Fork(): # to child stuff, end of block will automatically os._exit() # parent stuff goes here This would require (I think) that the __enter__ method of my Fork class to be able to return a value or raise an exception indicating that the block should not be run. It looks like, from PEP343, any exception thrown in the __enter__ isn't handled by with, and my basic tests confirm this. I could have __enter__ raise a custom exception and wrap the entire with statement in a try/except block, but that sort of defeats the purpose of the with statement. Is there a clean way for the context manager to signal that the execution of the block should be skipped altogether? From deets at nospam.web.de Fri Aug 21 11:02:08 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 21 Aug 2009 17:02:08 +0200 Subject: Conditionally skipping the contents of a with-statement In-Reply-To: References: Message-ID: <7f7r7hF2i7ba6U1@mid.uni-berlin.de> tsuraan schrieb: > I'd like to write a Fork class to wrap os.fork that allows something like this: > > with Fork(): > # to child stuff, end of block will automatically os._exit() > # parent stuff goes here > > This would require (I think) that the __enter__ method of my Fork > class to be able to return a value or raise an exception indicating > that the block should not be run. It looks like, from PEP343, any > exception thrown in the __enter__ isn't handled by with, and my basic > tests confirm this. I could have __enter__ raise a custom exception > and wrap the entire with statement in a try/except block, but that > sort of defeats the purpose of the with statement. Is there a clean > way for the context manager to signal that the execution of the block > should be skipped altogether? No. The only way would be something like this: with Fork() as is_child: if is_child: ... Diez From mhecht2909 at instant-mail.de Fri Aug 21 11:31:34 2009 From: mhecht2909 at instant-mail.de (M. Hecht) Date: Fri, 21 Aug 2009 08:31:34 -0700 (PDT) Subject: Three-Phase-Diagrams with matplotlib Message-ID: <25082083.post@talk.nabble.com> Hello, does anyone know whether it is possible to draw three-phase-diagrams with matplotlib? A three-phase-diagram is a triangular diagram applied in chemistry e.g. for slags where one has three main components of a chemical substance at the corners and points or lines within the triangle marking different compositions of the substances in percent, e.g. in metallurgy 20% Al2O3, 45% CaO and 35% SiO2. -- View this message in context: http://www.nabble.com/Three-Phase-Diagrams-with-matplotlib-tp25082083p25082083.html Sent from the Python - python-list mailing list archive at Nabble.com. From martin at v.loewis.de Fri Aug 21 11:36:53 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Aug 2009 17:36:53 +0200 Subject: pypi category In-Reply-To: References: Message-ID: <4A8EBF15.2090006@v.loewis.de> > Would someone be able to inform me how a category can be added to the > pypy list of categories? > I'd like to add a CAD & Geometry category. > ( I develop PythonOCC, wrappers for the OpenCASCADE CAD kernel, which > is why ) Make a specific proposal to catalog-sig at lists.python.org, along with a list of packages that are already on PyPI that could use that classifier. Having a classifier that classifies zero or one package is pointless. Regards, Martin From martin at v.loewis.de Fri Aug 21 11:39:09 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Aug 2009 17:39:09 +0200 Subject: 2.6 windows install In-Reply-To: <1e18d400-03ec-48ae-b59d-72aa6f5d9f64@l5g2000pra.googlegroups.com> References: <1e18d400-03ec-48ae-b59d-72aa6f5d9f64@l5g2000pra.googlegroups.com> Message-ID: <4A8EBF9D.6020306@v.loewis.de> > Did you install Python to the network device from your XP box? That > would explain why you can run it: the required registry settings & > environment variables are added by the installer, none of which is > occurring on any computer other than the one from which you installed. In principle, Python doesn't need any registry settings or environment variables in order to run. Regards, Martin From wuwei23 at gmail.com Fri Aug 21 12:09:02 2009 From: wuwei23 at gmail.com (alex23) Date: Fri, 21 Aug 2009 09:09:02 -0700 (PDT) Subject: Using 'apply' as a decorator, to define constants References: Message-ID: On Aug 21, 11:36?pm, Jonathan Fine wrote: > It might seem odd to use 'apply' as a decorator, but it can make sense. Yes, it's an idiom I've used myself for property declarations, but one I find myself using less often: class ColourThing(object): @apply def rgb(): def fset(self, rgb): self.r, self.g, self.b = rgb def fget(self): return (self.r, self.g, self.b) return property(**locals()) Unfortunately, apply() has been removed as a built-in in 3.x. I'm not sure if it has been relocated to a module somewhere, there's no mention of such in the docs. > Without using 'apply' as a decorator one alternative is > ? ? ?def tmp(): > ? ? ? ? ?value = [] > ? ? ? ? ?# complicated code > ? ? ? ? ?return value > ? ? ?tags = tmp() > ? ? ?del tmp You can save yourself the tidy up by using the same name for the function & the label: def tags(): value = [] # ... return value tags = tags() > Like all uses of decorators, it is simply syntactic sugar. ?It allows > you to see, up front, what is going to happen. ?I think, once I get used > to it, I'll get to like it. The question is, is it really that useful, or is it just a slight aesthetic variation? Given that apply(f, args, kwargs) is identical to f(*args, **kwargs), it's understandable that's apply() isn't seen as worth keeping in the language. Why I've personally stopped using it: I've always had the impression that decorators were intended to provide a convenient and obvious way of augmenting functions. Having one that automatically executes the function at definition just runs counter to the behaviour I expect from a decorator. Especially when direct assignment... foo = foo () ...is a far more direct and clear way of expressing exactly what is happening. But that's all IMO, if you feel it makes your code cleaner and don't plan on moving to 3.x any time soon (come on in! the water's great!), go for it :) From josefg at gmail.com Fri Aug 21 12:12:36 2009 From: josefg at gmail.com (josef) Date: Fri, 21 Aug 2009 09:12:36 -0700 (PDT) Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <8763chldpd.fsf@benfinney.id.au> Message-ID: On Aug 21, 4:26?am, Ben Finney wrote: > josef writes: > > To be clear, Python uses a "Pass By Object Reference" model. > > Yes. (I'm glad this concept has propagated to newcomers so well :-) I found one really good discussion on python semantics versus other languages. It gave me this gem of a quote: "When I turn on the TV and see Chuck Norris, though, I know it's only a reference to Chuck Norris, or I would be blinded. The only case he needs is "Pass By Roundhouse Kick"." -Chuckk > > > x = 1 > > x becomes the object reference > > It becomes *a* reference to that object, independent of any other > references to that same object. > > > while an object is created with the type 'int', value 1, and > > identifier (id(x)). > > Not really ?while?. The object creation happens first, then the > assignment statement binds a reference to that object. > > > Doing this with a class, x = myclass(), does the same thing, but with > > more or less object attributes. Every object has a type and an > > identifier (id()), according to the Python Language Reference for > > 2.6.2 section 3.1. > > Any expression can be on the right side of the assignment operator. The > expression will evaluate to some object, which the assignment will then > bind to the reference on the left side of the assignment operator. > > > x in both cases is the object reference. > > It is *an* object reference; that is, it's an identifier which refers to > an object. There's nothing about that identifier that makes it ?the (one > and only) object reference?. > > > I would like to use the object to refer to the object reference. If I > > have a gross misunderstanding, please correct me. > > Yes, it's a simple misunderstanding: objects do not, in general, know > any of the references there may be to them. > > > The following is what I would like to do: I have a list of class > > instances dk = [ a, b, c, d ], where a, b, c, d is an object > > reference. > > Note that, after that list is created, each item in that list is *also* > a reference to the corresponding object. That is, ?a? is a reference to > an object, and ?dk[0]? is a *different* reference to the *same* object. > The object has no knowledge about those references. This is surprising. My initial thought is that dk[0] hold the object reference 'a,' but that wouldn't be true "pass by object reference." When defining the object reference dk[0], python takes the object reference 'a,' finds the object MyClass0(), and then assigns the object identity to dk[0]? Or something close to that. > > > Entering dk gives me the object: [MyClass0 instance at 0x0000, > > MyClass1 instance at 0x0008, MyClass2 instance at 0x0010 ... ] > > This is a hint that, when asked for a string representation, each of the > objects in that list can say little more than that they are of a > particular type, and are located at a particular memory address. They do > not know any of the references to themselves. > > > I need the object reference name (a,b,c,d) from dk to use as input for > > a file. > > You'll have to track that yourself. I'm a bit shocked that there isn't a method for catching object reference names. I think that something like a = MyClass0(name = 'a', ...) is a bit redundant. Are definitions treated the same way? How would one print or pass function names? > > A good way to keep track of name-to-object mappings is with Python's > built-in mapping type, ?dict?:: > > ? ? dk = {'a': a, 'b': b, 'c': c, 'd': d} > > (There are more efficient ways to create a dictionary without such > repetition, of course, but this is more illustrative of the point.) > > You can then get a list (assembled in arbitrary sequence) of just the > keys, or just the values, or the key-value pairs, from the dict with its > ?keys?, ?values?, and ?items? methods respectively:: > > ? ? >>> dk = {'a': a, 'b': b, 'c': c, 'd': d} > ? ? >>> dk.keys() > ? ? ['a', 'c', 'd', 'b'] > ? ? >>> dk.values() > ? ? [, , , ] > ? ? >>> dk.items() > ? ? [('b', ), ('c', ), ('a', ?), ('d', ?)] > > Each of these is even better used as the iterable for a ?for? loop:: > > ? ? >>> for (key, value) in dk.items(): > ? ? ... ? ? print "Here is item named", key > ? ? ... ? ? print value I think I'll just add a 'name' to the classes' init defintion. > > > My main focus of this post is: "How do I find and use object reference > > memory locations?" > > You don't. Use the references in your code, forget about the memory > addresses, and remember that container objects themselves contain > references, so use them for organising your objects. > > -- > ?\ ? ? ?Demagogue: One who preaches doctrines he knows to be untrue to | > ? `\ ? ? ? ? ? ? ? ? ? ? men he knows to be idiots.? ?Henry L. Mencken | > _o__) ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| > Ben Finney Thanks, Josef From jamie.ivanov at gmail.com Fri Aug 21 12:33:57 2009 From: jamie.ivanov at gmail.com (Jamie) Date: Fri, 21 Aug 2009 09:33:57 -0700 (PDT) Subject: Problem with winreg - The object is not a PyHKEY object Message-ID: My goal is to remotely remove the registry keys for McAfee. I don't know how winreg handles an exception if a key doesn't exist, but I setup my script to skip the exception. But it doesn't seem to work right.. I think the script should be self explanitory, please help! Please forgive me, but I'm a python newbie. ## SCRIPT ## import _winreg print "Removing McAfee registry entries" hkey = _winreg.ConnectRegistry(r'\ \000000439140PC',_winreg.HKEY_LOCAL_MACHINE) try: _winreg.DeleteKey('SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFEAPFK') except: pass #try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFEAVFK') #except: # pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFEBOPK') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFEHIDK') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFEHIDK01') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFERKDK') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFETDIK') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_NAIAVFILTER1') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_NAIAVFILTER101') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MCSHIELD') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','MCTASKMANAGER') except: pass try: _winreg.DeleteKey('\SOFTWARE','McAfee') except: pass try: _winreg.DeleteKey('\SOFTWARE','Network Associates') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','AlertManager') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet \Services','McAfeeFramework') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','McShield') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet \Services','McTaskManager') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfeapfk') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfeavfk') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfebopk') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfehidk') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfehidk01') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mferkdk') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','mfetdik') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Services','NaiAvFilter1') except: pass try: _winreg.DeleteKey('\SYSTEM\CurrentControlSet \Services','NaiAvFilter101') except: pass ## END SCRIPT ## ## OUTPUT ## Removing McAfee registry entries Traceback (most recent call last): File "uninstallMcafee.py", line 11, in _winreg.DeleteKey('\SYSTEM\CurrentControlSet\Enum \Root','LEGACY_MFEAVFK') TypeError: The object is not a PyHKEY object ## END OUTPUT ## From 71david at libero.it Fri Aug 21 12:35:07 2009 From: 71david at libero.it (David) Date: Fri, 21 Aug 2009 18:35:07 +0200 Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <7f5pohF2k259vU1@mid.dfncis.de> Message-ID: <12e1y7snryy06$.1r84z897tmw7u$.dlg@40tude.net> Il Thu, 20 Aug 2009 22:24:24 +0200, Johannes Bauer ha scritto: > David schrieb: > >> If I want an octal I'll use oct()! >> >> "Explicit is better than implicit..." > > A leading "0" *is* explicit. It isn't explicit enough, at least IMO. regards David From 71david at libero.it Fri Aug 21 12:40:55 2009 From: 71david at libero.it (David) Date: Fri, 21 Aug 2009 18:40:55 +0200 Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: <14hj3v50qg77e$.1pk6i6w7h7q6s.dlg@40tude.net> Il Thu, 20 Aug 2009 15:18:35 -0700 (PDT), Mensanator ha scritto: > (Just kidding! That works in 2.5 also. How are you using it where > it's coming out wrong? I can see you pulling '012' out of a text > file and want to calculate with it, but how would you use a > string without using int()? Passing it to functions that allow > string representations of numbers?) Obviously it's not a progamming issue, just a hassle using the interpreter on command line. David From Kevin.Smith at sixquickrun.com Fri Aug 21 12:43:31 2009 From: Kevin.Smith at sixquickrun.com (Kevin D. Smith) Date: Fri, 21 Aug 2009 11:43:31 -0500 Subject: 2.6 windows install References: <4A8EBF9D.6020306@v.loewis.de> Message-ID: On 2009-08-21 10:39:09 -0500, "Martin v. L?wis" said: >> Did you install Python to the network device from your XP box? That >> would explain why you can run it: the required registry settings & >> environment variables are added by the installer, none of which is >> occurring on any computer other than the one from which you installed. > > In principle, Python doesn't need any registry settings or environment > variables in order to run. That may be true, but it doesn't explain why python won't run. I'm guessing that it has something to do with the msvc*90.dll files not getting installed. If those dlls haven't been previously installed, they won't be on the client machine in order for python to use them. However, I haven't had any luck installing these files manually and getting python to work that way. -- Kevin D. Smith From 71david at libero.it Fri Aug 21 12:46:09 2009 From: 71david at libero.it (David) Date: Fri, 21 Aug 2009 18:46:09 +0200 Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: <1bzp9xkx7u4a4$.hp3xb39tz5vv.dlg@40tude.net> Il Thu, 20 Aug 2009 16:59:14 -0700 (PDT), James Harris ha scritto: > > It maybe made sense once but this relic of the past should have been > consigned to the waste bin of history long ago. I perfectly agree with you! David. From python at mrabarnett.plus.com Fri Aug 21 12:58:25 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 21 Aug 2009 17:58:25 +0100 Subject: Annoying octal notation In-Reply-To: <12e1y7snryy06$.1r84z897tmw7u$.dlg@40tude.net> References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <7f5pohF2k259vU1@mid.dfncis.de> <12e1y7snryy06$.1r84z897tmw7u$.dlg@40tude.net> Message-ID: <4A8ED231.3010409@mrabarnett.plus.com> David wrote: > Il Thu, 20 Aug 2009 22:24:24 +0200, Johannes Bauer ha scritto: > >> David schrieb: >> >>> If I want an octal I'll use oct()! >>> >>> "Explicit is better than implicit..." >> A leading "0" *is* explicit. > > It isn't explicit enough, at least IMO. > Is this better? Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> 010 File "", line 1 010 ^ I would've preferred it to be decimal unless there's a prefix: Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> 0x10 16 >>> 0o10 8 Ah well, something for Python 4. :-) From michele.petrazz at REMOTEME_unipex.it Fri Aug 21 13:14:07 2009 From: michele.petrazz at REMOTEME_unipex.it (Michele Petrazzo) Date: Fri, 21 Aug 2009 19:14:07 +0200 Subject: PIL and Python In-Reply-To: <5df342cf-c742-42d6-bc8c-97a3c44a0816@h21g2000yqa.googlegroups.com> References: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> <5df342cf-c742-42d6-bc8c-97a3c44a0816@h21g2000yqa.googlegroups.com> Message-ID: catafest wrote: > I don't extract data from jpegs. I wanna put some data in this > (copyright of my site) ... > My wrap for freeimage, called freeimagepy :) can't, as now, wrote exif information on the image, but since freeimage can do it, I think that it's not so difficult to add this type of feature. If you have some time for investigate and create a patch, I'll be happy to include it into the mainline! Contact me directly if you want to talk of need some help on how do it. Michele From apt.shansen at gmail.com Fri Aug 21 13:22:04 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Fri, 21 Aug 2009 10:22:04 -0700 Subject: Problem with winreg - The object is not a PyHKEY object In-Reply-To: References: Message-ID: <7a9c25c20908211022l751a2df8r5476887515272f1f@mail.gmail.com> On Fri, Aug 21, 2009 at 9:33 AM, Jamie wrote: > My goal is to remotely remove the registry keys for McAfee. I don't > know how winreg handles an exception if a key doesn't exist, but I > setup my script to skip the exception. But it doesn't seem to work > right.. I think the script should be self explanitory, please help! > Please forgive me, but I'm a python newbie. > > ## SCRIPT ## > > import _winreg > > print "Removing McAfee registry entries" > hkey = _winreg.ConnectRegistry(r'\ > \000000439140PC',_winreg.HKEY_LOCAL_MACHINE) > try: > _winreg.DeleteKey('SYSTEM\CurrentControlSet\Enum\Root','LEGACY_MFEAPFK') > except: > pass > You have to "open" the key first-- the first argument to .DeleteKey is not a string. E.g., do: key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, r'SYSTEM\CurrentControlSet\Enum\Root') _winreg.DeleteKey(key, 'LEGACY_MFEAPFK' _winreg.CloseKey(key) The above is an example off the top of my head, not actually tested-- But that's sorta your problem, I believe: .DeleteKey operates on a key /handle/ in its first argument, not a string. The second argument is a string. HTH, --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From ryniek90 at gmail.com Fri Aug 21 13:33:29 2009 From: ryniek90 at gmail.com (ryniek90) Date: Fri, 21 Aug 2009 19:33:29 +0200 Subject: TypeError while checking for permissions with os.access() on windows xp In-Reply-To: References: Message-ID: <4A8EDA69.6030103@gmail.com> I've got some code that checks priviliges on two paths: First - chosen by user Second - hardcoded home directory represented by **os.getenv('HOME')** - (os.getenv('HOME') works both on Linux and Windows) Here's the code: " def __check_set_perm(self, rd_obj_path, backup_dest): try: if os.path.exists(rd_obj_path): if os.access(rd_obj_path, os.R_OK) != True: print "Have no permissions on [%s] for reading operation.\nTrying to set them..." % os.path.split(rd_obj_path)[1] if not os.path.isdir(rd_obj_path): os.chmod(rd_obj_path, stat.S_IREAD) else: for root, dirs, files in os.walk(rd_obj_path): for f in files: os.chmod(os.path.join(root, f), stat.S_IREAD) print "Get permissions for reading on [%s] successfully." % os.path.split(rd_obj_path)[1] else: print "Have permissions on [%s] for reading." % os.path.split(rd_obj_path)[1] if os.access(backup_dest, os.W_OK) != True: print "Have no permissions on [%s] for writing operation.\nTrying to set them..." % os.path.split(backup_dest)[1] os.chmod(backup_dest, stat.S_IWRITE) print "Get permissions for reading on [%s] successfully." % os.path.split(backup_dest)[1] else: print "Have permissions on [%s] for writing." % os.path.split(backup_dest)[1] else: return "Can't find specified path - [%s]." % rd_obj_path sys.exit(0) except (Except), ex: return ex " This code is part of my backup script. When script checks for reading permission on 'user chosen path' it seems ok, but when it checks for writing permissions on 'home directory', (this line: **if os.access(backup_dest, os.W_OK) != True**), i get error: **TypeError: coercing to Unicode: need string or buffer, NoneType found** The second os.access check fails, but don't know why. When i turned os.W_OK to integer, i get the same error. But when changed os.W_OK or that int to string, i get error that integer is required. I'm launching this code on WinXP Prof+SP3, on Administrator account. Is it bug in os.acces() or my code is written wrong? Btw. i kow that os.chmod in windows can set only read-olny flag, so later i'll change the line with **os.chmod(path, stat.S_IWRITE)** Thanks and cheers. From piet at cs.uu.nl Fri Aug 21 13:36:00 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 21 Aug 2009 19:36:00 +0200 Subject: Python and PHP encryption/decryption References: <7f36e3F2it5a5U2@mid.uni-berlin.de> Message-ID: >>>>> "Diez B. Roggisch" (DBR) wrote: >DBR> Jean-Claude Neveu schrieb: >>> I'm looking for a recommendation about encryption/decryption packages for >>> Python. >>> >>> I'm working on a project that will require me to store some values in a >>> database in encrypted format. I'll be storing them from a PHP script and >>> retrieving them (decrypting them) using Python. I'm currently using PHP's >>> mcrypt package to encrypt the values, and I'm using AES for encryption, >>> so something AES-compatible would be ideal. However, the project is at >>> the development stage so I can easily change how I'm encrypting things in >>> PHP if there is a compelling reason on the Python side of things to do >>> so. >DBR> With PyCrypto[1] you have a wide range of choices, amongst others AES. >DBR> If that's the best algorithm, or even the best python-package to implement >DBR> it, I don't know. >DBR> [1] http://www.dlitz.net/software/pycrypto/ Pycrypto had been stalled in development. The latest release was in 2005. There is now a new developer and that it were the link above goes, but he has not yet released anything. so you will have to do with the 2005 release. There is an alternative library: m2crypto (http://chandlerproject.org/Projects/MeTooCrypto). It is built on top of OpenSSL which is available for most platforms that have Python whereas Pycrypto has its own C implementations of crypto algorithms. M2crypto has a recent release. Also I think because OpenSSL is widely used, its vulnerabilities are easier detected and corrected, whereas I don't think that is the case for Pycrypto. M2crypto is much bigger than you need for this project, however. If that doesn't bother you I would recommend it. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From mensanator at aol.com Fri Aug 21 13:36:35 2009 From: mensanator at aol.com (Mensanator) Date: Fri, 21 Aug 2009 10:36:35 -0700 (PDT) Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <14hj3v50qg77e$.1pk6i6w7h7q6s.dlg@40tude.net> Message-ID: On Aug 21, 11:40?am, David <71da... at libero.it> wrote: > Il Thu, 20 Aug 2009 15:18:35 -0700 (PDT), Mensanator ha scritto: > > > (Just kidding! That works in 2.5 also. How are you using it where > > it's coming out wrong? I can see you pulling '012' out of a text > > file and want to calculate with it, but how would you use a > > string without using int()? Passing it to functions that allow > > string representations of numbers?) > > Obviously it's not a progamming issue, just a hassle using the interpreter > on command line. Aha! Then I WAS right after all. Switch to 3.1 and you'll soon be cured of that bad habit: >>> 012 + 012 SyntaxError: invalid token (, line 1) > > David From nagle at animats.com Fri Aug 21 13:45:51 2009 From: nagle at animats.com (John Nagle) Date: Fri, 21 Aug 2009 10:45:51 -0700 Subject: Annoying octal notation In-Reply-To: <6a523329-3287-4271-ba37-7be450cfc5f6@d32g2000yqh.googlegroups.com> References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <6a523329-3287-4271-ba37-7be450cfc5f6@d32g2000yqh.googlegroups.com> Message-ID: <4a8edc29$0$1599$742ec2ed@news.sonic.net> Simon Forman wrote: > On Aug 20, 3:06 pm, David <71da... at libero.it> wrote: >> Hi all, >> >> Is there some magic to make the 2.x CPython interpreter to ignore the >> annoying octal notation? > > No. You would have to modify and recompile the interpreter. This is > not exactly trivial, see "How to Change Python's Grammar" > http://www.python.org/dev/peps/pep-0306/ > > However, see "Integer Literal Support and Syntax" http://www.python.org/dev/peps/pep-3127/ > > (Basically in 2.6 and onwards you can use 0oNNN notation.) Yes, and making lead zeros an error as suggested in PEP 3127 is a good idea. It will be interesting to see what bugs that flushes out. In 2009, Unisys finally exited the mainframe hardware business, and the last of the 36-bit machines, the ClearPath servers, are being phased out. That line of machines goes back to the UNIVAC 2200 series, and the UNIVAC 1100 series, all the way back to the vacuum-tube UNIVAC 1103 from 1952. It's the longest running series of computers in history, and code for all those machines used octal heavily. And it's over. We can finally dispense with octal by default. John Nagle From dickinsm at gmail.com Fri Aug 21 13:49:20 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Fri, 21 Aug 2009 10:49:20 -0700 (PDT) Subject: Python on Crays References: Message-ID: <1f5c81d8-4f79-4eea-b1bd-af48ab9ddc82@c2g2000yqi.googlegroups.com> On Aug 21, 12:21?am, Carrie Farberow wrote: > I am trying to build a statically-linked Python based on directions at: > > http://yt.enzotools.org/wiki/CrayXT5Installation > > I have tried this on multiple systems. ?The first time I attempt to build python, 'make' runs fine but 'make install' fails with the following error: > > Sorry: UnicodeError: ("\\N escapes not supported (can't load unicodedata module)",) > > Any help regarding the source of this error and possible fixes would be appreciated. Hmm. There's not a lot of information to go on here. What version of Python is this? Python 2.6.2? Have you tried Googling for that exact error message? The following issue looks as though it might be relevant: http://bugs.python.org/issue1594809 especially since it looks as though the directions you linked to involve messing with the PYTHONPATH environment variable. If you could post a log somewhere[*] showing the exact commands that you executed, along with all the output (and especially all the output from 'make' and 'make install'), that might help someone diagnose the problem further. Mark [*] I'm not sure where, though. Posting all that output directly in a newsgroup message might not be considered very friendly. From sajmikins at gmail.com Fri Aug 21 13:54:13 2009 From: sajmikins at gmail.com (Simon Forman) Date: Fri, 21 Aug 2009 10:54:13 -0700 (PDT) Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <8763chldpd.fsf@benfinney.id.au> Message-ID: On Aug 21, 12:12?pm, josef wrote: > > > I need the object reference name (a,b,c,d) from dk to use as input for > > > a file. > > > You'll have to track that yourself. > > I'm a bit shocked that there isn't a method for catching object > reference names. I think that something like a = MyClass0(name = > 'a', ...) is a bit redundant. Are definitions treated the same way? > How would one print or pass function names? There's no such thing as "object reference names". Object references do not have names. When you run a piece of code like "a = object()" a string "a" is used as a key in a dictionary and the value is the "object reference". Consider: [None][0] = object() (Create an anonymous list object with one item in it and immediately replace that item with an anonymous object instance.) There's no name to catch. Objects know nothing about their "enclosing" namespace. So if you want them to have names you have to explicitly give them name attributes. (However, this won't affect their enclosing namespaces.) As Bruno said, think of "foo = something" as shorthand for "some_namespace_dictionary['foo'] = something". The two exceptions to this are 'def' and 'class' statements which both create name->object (key, value) pairs in their current namespace AND give the objects they create '__name__' attributes (pretty much just as an aid to debugging.) In [1]: def foo(): pass ...: In [2]: foo.__name__ Out[2]: 'foo' In [3]: class foo(): pass ...: In [4]: foo.__name__ Out[4]: 'foo' > > A good way to keep track of name-to-object mappings is with Python's > > built-in mapping type, ?dict?:: > > > ? ? dk = {'a': a, 'b': b, 'c': c, 'd': d} > > > (There are more efficient ways to create a dictionary without such > > repetition, of course, but this is more illustrative of the point.) > > > You can then get a list (assembled in arbitrary sequence) of just the > > keys, or just the values, or the key-value pairs, from the dict with its > > ?keys?, ?values?, and ?items? methods respectively:: > > > ? ? >>> dk = {'a': a, 'b': b, 'c': c, 'd': d} > > ? ? >>> dk.keys() > > ? ? ['a', 'c', 'd', 'b'] > > ? ? >>> dk.values() > > ? ? [, , , ] > > ? ? >>> dk.items() > > ? ? [('b', ), ('c', ), ('a', ?), ('d', ?)] > > > Each of these is even better used as the iterable for a ?for? loop:: > > > ? ? >>> for (key, value) in dk.items(): > > ? ? ... ? ? print "Here is item named", key > > ? ? ... ? ? print value > > I think I'll just add a 'name' to the classes' init defintion. That's the way to do it. :] From ronn.ross at gmail.com Fri Aug 21 14:14:32 2009 From: ronn.ross at gmail.com (Ronn Ross) Date: Fri, 21 Aug 2009 14:14:32 -0400 Subject: convert date time Message-ID: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> I'm new to python and I'm getting a date time from a field in the database that looks like this: 8/2/2009 8:36:16 AM (UTC) I want to split it into two fields one with the date formatted like this: YYYY-MM-DD 2009-08-02 and the time to be 24 hour or military time. How every you call it. Similar to this: 15:22:00 I found it easy to truncate off the (UTC), but having trouble converting the date. Can someone point me in the right direction? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sajmikins at gmail.com Fri Aug 21 14:20:53 2009 From: sajmikins at gmail.com (Simon Forman) Date: Fri, 21 Aug 2009 11:20:53 -0700 (PDT) Subject: TypeError while checking for permissions with os.access() on windows xp References: Message-ID: On Aug 21, 1:33?pm, ryniek90 wrote: > I've got some code that checks priviliges on two paths: > First - chosen by user > Second - hardcoded home directory represented by **os.getenv('HOME')** - > (os.getenv('HOME') works both on Linux and Windows) > > Here's the code: > " > def __check_set_perm(self, rd_obj_path, backup_dest): > > ? ? ? ? try: > > ? ? ? ? ? ? if os.path.exists(rd_obj_path): > ? ? ? ? ? ? ? ? if os.access(rd_obj_path, os.R_OK) != True: > ? ? ? ? ? ? ? ? ? ? print "Have no permissions on [%s] for reading > operation.\nTrying to set them..." % os.path.split(rd_obj_path)[1] > ? ? ? ? ? ? ? ? ? ? if not os.path.isdir(rd_obj_path): > ? ? ? ? ? ? ? ? ? ? ? ? os.chmod(rd_obj_path, stat.S_IREAD) > ? ? ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? ? ? for root, dirs, files in os.walk(rd_obj_path): > ? ? ? ? ? ? ? ? ? ? ? ? ? ? for f in files: > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? os.chmod(os.path.join(root, f), > stat.S_IREAD) > ? ? ? ? ? ? ? ? ? ? print "Get permissions for reading on [%s] > successfully." % os.path.split(rd_obj_path)[1] > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? print "Have permissions on [%s] for reading." % > os.path.split(rd_obj_path)[1] > > ? ? ? ? ? ? ? ? if os.access(backup_dest, os.W_OK) != True: > ? ? ? ? ? ? ? ? ? ? print "Have no permissions on [%s] for writing > operation.\nTrying to set them..." % os.path.split(backup_dest)[1] > ? ? ? ? ? ? ? ? ? ? os.chmod(backup_dest, stat.S_IWRITE) > ? ? ? ? ? ? ? ? ? ? print "Get permissions for reading on [%s] > successfully." % os.path.split(backup_dest)[1] > ? ? ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? ? ? print "Have permissions on [%s] for writing." % > os.path.split(backup_dest)[1] > ? ? ? ? ? ? else: > ? ? ? ? ? ? ? ? return "Can't find specified path - [%s]." % rd_obj_path > ? ? ? ? ? ? ? ? sys.exit(0) > > ? ? ? ? except (Except), ex: > ? ? ? ? ? ? return ex > " > > This code is part of my backup script. When script checks for reading > permission on 'user chosen path' it seems ok, but when it checks for > writing permissions on 'home directory', (this line: **if > os.access(backup_dest, os.W_OK) != True**), i get error: > **TypeError: coercing to Unicode: need string or buffer, NoneType found** > The second os.access check fails, but don't know why. When i turned > os.W_OK to integer, i get the same error. > But when changed os.W_OK or that int to string, i get error that integer > is required. I'm launching this code on WinXP Prof+SP3, on Administrator > account. Is it bug in os.acces() or my code is written wrong? > Btw. i kow that os.chmod in windows can set only read-olny flag, so > later i'll change the line with **os.chmod(path, stat.S_IWRITE)** > > Thanks and cheers. First, some nitpicking: Include the whole traceback when posting about errors please. Don't write "if some_boolean_expression != True:" instead prefer "if not some_boolean_expression:". Also, in your code "except (Except), ex: return ex" the parentheses are redundant, there's no "Except" Exception (unless you created one yourself) and why are you catching and returning the Exception object? (Also, what's that "sys.exit(0)" doing in there? And why exit with 0 if there was a problem? Exit code 0 means "no problem".) Second, from what you've said backup_dest must be None: >>> import os >>> os.access(None, os.W_OK) Traceback (most recent call last): File "", line 1, in os.access(None, os.W_OK) TypeError: coercing to Unicode: need string or buffer, NoneType found From darcy at druid.net Fri Aug 21 14:26:38 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 21 Aug 2009 14:26:38 -0400 Subject: convert date time In-Reply-To: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> References: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> Message-ID: <20090821142638.92d91382.darcy@druid.net> On Fri, 21 Aug 2009 14:14:32 -0400 Ronn Ross wrote: > I want to split it into two fields one with the date formatted like this: > YYYY-MM-DD 2009-08-02 > > and the time to be 24 hour or military time. How every you call it. Similar > to this: > 15:22:00 > > I found it easy to truncate off the (UTC), but having trouble converting the > date. Can someone point me in the right direction? You don't say what database you are using but you may find it simpler to do the conversion in your SELECT statement. For example, see http://www.postgresql.org/docs/8.3/static/functions-formatting.html for PostgreSQL formatting functions. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From tommy.nordgren at comhem.se Fri Aug 21 14:29:08 2009 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Fri, 21 Aug 2009 20:29:08 +0200 Subject: Mac OS 9.2 In-Reply-To: <96ab6db4-55c5-4142-8ef8-d7fbe97e4c4d@f37g2000yqn.googlegroups.com> References: <96ab6db4-55c5-4142-8ef8-d7fbe97e4c4d@f37g2000yqn.googlegroups.com> Message-ID: <8683E1B6-367C-4A05-B6FA-667F0D4FC7DF@comhem.se> On Aug 18, 2009, at 6:04 PM, madzientist wrote: > hi, > > i have to work with mac OS 9.2 for legacy reasons...is there a > compiled version of python for this os ? i need to get input about > variable values from the user and then print out some text files that > make use of this input. a gui would be nice, but keyboard based input > would be ok too... > > thanks much, > > suresh > > ps. if there isn't a version of pythn that will work, perhaps you > could suggest some other scripting language for 0S 9.2 ? > -- > http://mail.python.org/mailman/listinfo/python-list There was a port (MacPython) of versions 2.3 and 2.3 that worked on MacOS 9 Maybe Google will help you locate a copy. ------ What is a woman that you forsake her, and the hearth fire and the home acre, to go with the old grey Widow Maker. --Kipling, harp song of the Dane women Tommy Nordgren tommy.nordgren at comhem.se From dullrich at sprynet.com Fri Aug 21 14:36:02 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Fri, 21 Aug 2009 13:36:02 -0500 Subject: Silly question References: <97ae0d22-7eaa-4ad6-8603-69699703d508@u16g2000pru.googlegroups.com> Message-ID: On Thu, 20 Aug 2009 17:45:11 -0700, John Machin wrote: > On Aug 21, 5:33?am, David C Ullrich wrote: > >> So I'm slow, fine. (There were several times when I was using 1.5.3 and >> wished they were there - transposing matrices, etc.) > > 1.5.THREE ?? Not sure. 1.SOMETHING. Sorry about the CONFUSION... From ronn.ross at gmail.com Fri Aug 21 14:43:55 2009 From: ronn.ross at gmail.com (Ronn Ross) Date: Fri, 21 Aug 2009 14:43:55 -0400 Subject: convert date time In-Reply-To: <20090821142638.92d91382.darcy@druid.net> References: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> <20090821142638.92d91382.darcy@druid.net> Message-ID: <9c8c445f0908211143g38382e7aocbee20155e525573@mail.gmail.com> On Fri, Aug 21, 2009 at 2:26 PM, D'Arcy J.M. Cain wrote: > On Fri, 21 Aug 2009 14:14:32 -0400 > Ronn Ross wrote: > > I want to split it into two fields one with the date formatted like this: > > YYYY-MM-DD 2009-08-02 > > > > and the time to be 24 hour or military time. How every you call it. > Similar > > to this: > > 15:22:00 > > > > I found it easy to truncate off the (UTC), but having trouble converting > the > > date. Can someone point me in the right direction? > > You don't say what database you are using but you may find it simpler > to do the conversion in your SELECT statement. For example, see > http://www.postgresql.org/docs/8.3/static/functions-formatting.html for > PostgreSQL formatting functions. > > -- > D'Arcy J.M. Cain | Democracy is three wolves > http://www.druid.net/darcy/ | and a sheep voting on > +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. > I apologize I should have made it clear that this date is stored in the db as a string/varchar. The reason it is stored that way is before it's being read in from a text file where it is formatted that way. -------------- next part -------------- An HTML attachment was scrubbed... URL: From jfine at pytex.org Fri Aug 21 15:23:51 2009 From: jfine at pytex.org (Jonathan Fine) Date: Fri, 21 Aug 2009 20:23:51 +0100 Subject: Using 'apply' as a decorator, to define constants In-Reply-To: References: Message-ID: <_L2dne59TJ3baRPXnZ2dnUVZ8gCdnZ2d@brightview.co.uk> alex23 wrote: > Unfortunately, apply() has been removed as a built-in in 3.x. I'm not > sure if it has been relocated to a module somewhere, there's no > mention of such in the docs. The old use of apply() > You can save yourself the tidy up by using the same name for the > function & the label: > > def tags(): > value = [] > # ... > return value > tags = tags() I don't like that because there's no hint at def tags(): that this is /not/ the value of tags. >> Like all uses of decorators, it is simply syntactic sugar. It allows >> you to see, up front, what is going to happen. I think, once I get used >> to it, I'll get to like it. > > The question is, is it really that useful, or is it just a slight > aesthetic variation? Given that apply(f, args, kwargs) is identical to > f(*args, **kwargs), it's understandable that's apply() isn't seen as > worth keeping in the language. Yes, I agree with that, completely. > Why I've personally stopped using it: I've always had the impression > that decorators were intended to provide a convenient and obvious way > of augmenting functions. Yes, that was the intended use case. > Having one that automatically executes the > function at definition just runs counter to the behaviour I expect > from a decorator. I'd expect the name of the decorator to explain what is going on. If apply() were a well known part of the language, that would be fine. > Especially when direct assignment... foo = foo > () ...is a far more direct and clear way of expressing exactly what is > happening. Actually, I think the decorator approach is clearer. But that's just my opinion, and not with the benefit of a lot of experience. > But that's all IMO, if you feel it makes your code cleaner and don't > plan on moving to 3.x any time soon (come on in! the water's great!), > go for it :) Thank you for your comments, Alex. And particularly for telling me that apply() is no longer a builtin for Python 3. -- Jonathan From dullrich at sprynet.com Fri Aug 21 15:40:30 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Fri, 21 Aug 2009 14:40:30 -0500 Subject: Silly question References: Message-ID: On Thu, 20 Aug 2009 16:51:00 -0700, Aahz wrote: > In article , > Benjamin Kaplan wrote: >>On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrich >>wrot= e: >>> >>> I just noticed that >>> sequence[i:j:k] >> >>Well, I got some good news and some bad news. According to the docs, it >>existed in 1.4 but the built-in sequences didn't support it until 2.3. >>It's not used that often anyway so you haven't been missing much. > > Except that it's canonical for one specific operation: > > 'reverseme'[::-1] It's like you guys are a bunch of programmers or something: from math import sqrt def Primes(n): """Return a list of the primes < n""" sieve = range(n) for k in range(2,int(sqrt(n))+2): sieve[::k] = [1]*((n+k-1)/k) return [p for p in sieve if p > 1] From darcy at druid.net Fri Aug 21 15:42:27 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 21 Aug 2009 15:42:27 -0400 Subject: convert date time In-Reply-To: <9c8c445f0908211143g38382e7aocbee20155e525573@mail.gmail.com> References: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> <20090821142638.92d91382.darcy@druid.net> <9c8c445f0908211143g38382e7aocbee20155e525573@mail.gmail.com> Message-ID: <20090821154227.b9fe0bdd.darcy@druid.net> On Fri, 21 Aug 2009 14:43:55 -0400 Ronn Ross wrote: > On Fri, Aug 21, 2009 at 2:26 PM, D'Arcy J.M. Cain wrote: > > You don't say what database you are using but you may find it simpler > > to do the conversion in your SELECT statement. For example, see > > http://www.postgresql.org/docs/8.3/static/functions-formatting.html for > > PostgreSQL formatting functions. > > > I apologize I should have made it clear that this date is stored in the db > as a string/varchar. The reason it is stored that way is before it's being > read in from a text file where it is formatted that way. You can still save it as a timestamp: SELECT '8/2/2009 8:36:16 AM (UTC)'::timestamp(0); timestamp --------------------- 2009-08-02 08:36:16 (1 row) Your input format is read into PostgreSQL time types directly. Same may be true of other databases. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From dullrich at sprynet.com Fri Aug 21 15:45:55 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Fri, 21 Aug 2009 14:45:55 -0500 Subject: Silly question References: Message-ID: On Fri, 21 Aug 2009 14:40:30 -0500, David C Ullrich wrote: > On Thu, 20 Aug 2009 16:51:00 -0700, Aahz wrote: > >> In article , >> Benjamin Kaplan wrote: >>>On Thu, Aug 20, 2009 at 2:13 PM, David C Ullrich >>>wrot= e: >>>> >>>> I just noticed that >>>> sequence[i:j:k] >>> >>>Well, I got some good news and some bad news. According to the docs, it >>>existed in 1.4 but the built-in sequences didn't support it until 2.3. >>>It's not used that often anyway so you haven't been missing much. >> >> Except that it's canonical for one specific operation: >> >> 'reverseme'[::-1] > > It's like you guys are a bunch of programmers or something: > > from math import sqrt > > def Primes(n): > """Return a list of the primes < n""" sieve = range(n) > for k in range(2,int(sqrt(n))+2): > sieve[::k] = [1]*((n+k-1)/k) > return [p for p in sieve if p > 1] Oops. Should have tested that a little more carefully before posting. No time to fix it right now, customer just got here. Let's just say we're looking for the primes between sqrt(n) and n... From code at pizzashack.org Fri Aug 21 15:48:57 2009 From: code at pizzashack.org (Derek Martin) Date: Fri, 21 Aug 2009 14:48:57 -0500 Subject: Annoying octal notation Message-ID: <20090821194857.GU20434@dragontoe.org> John Nagle wrote: > Yes, and making lead zeros an error as suggested in PEP 3127 is a > good idea. It will be interesting to see what bugs that flushes > out. James Harris wrote: > It maybe made sense once but this relic of the past should have been > consigned to the waste bin of history long ago. Sigh. Nonsense. I use octal notation *every day*, for two extremely prevalent purposes: file creation umask, and Unix file permissions (i.e. the chmod() function/command). I fail to see how 0O012, or even 0o012 is more intelligible than 012. The latter reads like a typo, and the former is virtually indistinguishable from 00012, O0012, or many other combinations that someone might accidentally type (or intentionally type, having to do this in dozens of other programming languages). I can see how 012 can be confusing to new programmers, but at least it's legible, and the great thing about humans is that they can be taught (usually). I for one think this change is completely misguided. More than flushing out bugs, it will *cause* them in ubiquity, requiring likely terabytes of code to be poured over and fixed. Changing decades-old behaviors common throughout a community for the sake of avoiding a minor inconvenience of the n00b is DUMB. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From dickey at his.com Fri Aug 21 15:53:17 2009 From: dickey at his.com (Thomas Dickey) Date: Fri, 21 Aug 2009 15:53:17 -0400 (EDT) Subject: ncurses getch & unicode (was: decoding keyboard input when using curses) In-Reply-To: <65a1d6f80908210458hfa33699m398d9af6eab67674@mail.gmail.com> References: <65a1d6f80908200936g18b235fcw49d0047168cf9548@mail.gmail.com> <0a683d75-ac07-40a6-8374-2a2e900ac0ba@j21g2000yqe.googlegroups.com> <65a1d6f80908210458hfa33699m398d9af6eab67674@mail.gmail.com> Message-ID: <20090821155306.K929@mail101.his.com> On Fri, 21 Aug 2009, I?igo Serna wrote: > 2009/8/21 Thomas Dickey : >> On Aug 20, 6:12?pm, I?igo Serna wrote: >>> ??????? c = win.getch() >> >> You're using "getch", not "get_wch" (Python's ncurses binding may/may >> not have the latter). >> curses getch returns 8-bit values, get_wch would return wider values. > > you are right, ncurses binding does not have get_wch, only getch, and > this last is the only one called in ncurses library bindings. > > > Anyway, I've written a patch to include the get_wch method in the bindings. > See http://bugs.python.org/issue6755 > > > Thanks for the clarification, no problem (report bugs) > I?igo > -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net From Kevin.Smith at sixquickrun.com Fri Aug 21 15:58:50 2009 From: Kevin.Smith at sixquickrun.com (Kevin D. Smith) Date: Fri, 21 Aug 2009 14:58:50 -0500 Subject: 2.6 windows install References: <4A8EBF9D.6020306@v.loewis.de> Message-ID: On 2009-08-21 11:43:31 -0500, Kevin D. Smith said: > On 2009-08-21 10:39:09 -0500, "Martin v. L?wis" said: > >>> Did you install Python to the network device from your XP box? That >>> would explain why you can run it: the required registry settings & >>> environment variables are added by the installer, none of which is >>> occurring on any computer other than the one from which you installed. >> >> In principle, Python doesn't need any registry settings or environment >> variables in order to run. > > That may be true, but it doesn't explain why python won't run. I'm > guessing that it has something to do with the msvc*90.dll files not > getting installed. If those dlls haven't been previously installed, > they won't be on the client machine in order for python to use them. > However, I haven't had any luck installing these files manually and > getting python to work that way. Installing those files from does seem to help, but python still gives an error of "The application failed to initialize properly (0xc00000022)." I'm not really sure where to go from here. -- Kevin D. Smith From travis+ml-python at subspacefield.org Fri Aug 21 16:09:08 2009 From: travis+ml-python at subspacefield.org (Travis) Date: Fri, 21 Aug 2009 15:09:08 -0500 Subject: zlib interface semi-broken In-Reply-To: <20090212172619.GG6522@subspacefield.org> References: <20090210205739.GT6522@subspacefield.org> <20090212172619.GG6522@subspacefield.org> Message-ID: <20090821200908.GI1215@subspacefield.org> I've come up with a good test for issue5210 and uploaded it to the bug tracker. This patch should be ready for inclusion now. -- Obama Nation | My emails do not have attachments; it's a digital signature that your mail program doesn't understand. | http://www.subspacefield.org/~travis/ If you are a spammer, please email john at subspacefield.org to get blacklisted. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 850 bytes Desc: not available URL: From travis at subspacefield.org Fri Aug 21 16:13:12 2009 From: travis at subspacefield.org (travis at subspacefield.org) Date: Fri, 21 Aug 2009 15:13:12 -0500 Subject: proposal: add setresuid() system call to python In-Reply-To: <20090717205953.2543.1223422516.divmod.quotient.3129@henry.divmod.com> References: <20090717200141.GI6065@subspacefield.org> <20090717205953.2543.1223422516.divmod.quotient.3129@henry.divmod.com> Message-ID: <20090821201312.GJ1215@subspacefield.org> On Fri, Jul 17, 2009 at 04:59:53PM -0400, Jean-Paul Calderone wrote: > On Fri, 17 Jul 2009 15:01:41 -0500, travis+ml-python at subspacefield.org wrote: >> I am suggesting that the setresuid function be added to python, >> perhaps in the OS module, because it has the clearest semantics for >> manipulating user ids. The reason why is best described in the >> following paper: > > Yes, it'd be good for Python to expose setresuid. The best course of > action is to file a ticket in the issue tracker. Things will be sped > along if you also attach a patch implementing the change. :) I'm now working on this as issue6758 in the tracker. Adding the calls to the os module doesn't seem like a good idea to me, because the calls are not POSIX, and it appears that os maps to posixmodule.c. Since the authors of the paper (Wagner et. al.) are proposing a new set of APIs to make all of this clearer, I'm thinking that I will create a module specifically for dropping permissions. -- Obama Nation | My emails do not have attachments; it's a digital signature that your mail program doesn't understand. | http://www.subspacefield.org/~travis/ If you are a spammer, please email john at subspacefield.org to get blacklisted. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 850 bytes Desc: not available URL: From mccredie at gmail.com Fri Aug 21 16:20:11 2009 From: mccredie at gmail.com (Matimus) Date: Fri, 21 Aug 2009 13:20:11 -0700 (PDT) Subject: 2.6 windows install References: Message-ID: On Aug 20, 10:21?am, "Tim Arnold" wrote: > Hi, > I installed python2.6 to a netapp device. I can use it from my local windows > machine (XP). But others cannot use it from their pcs. > > They get this response > "The system cannot execute the specified program.". > > If they double click on python.exe, they get a window > > with: This application has failed to start because the application > > configuration is incorrect. ?Reinstalling the application may fix this > > problem. > > When I installed it I didn't see any mention of an 'administrators' install, > it just installed. The permissions on the directories where it installed are > set wide-open for everyone. > > Any ideas on what I'm missing here? > > thanks, > --Tim Arnold The default windows install puts Python26.dll in \windows\system32. I haven't tried this, but you could probably fix your install by moving Python26.dll into the Python26 directory. That being said, the usual thing to do would be to install it on each machine. Matt From benjamin at python.org Fri Aug 21 16:22:47 2009 From: benjamin at python.org (Benjamin Peterson) Date: Fri, 21 Aug 2009 20:22:47 +0000 (UTC) Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <6a523329-3287-4271-ba37-7be450cfc5f6@d32g2000yqh.googlegroups.com> Message-ID: Simon Forman gmail.com> writes: > No. You would have to modify and recompile the interpreter. This is > not exactly trivial, see "How to Change Python's Grammar" > http://www.python.org/dev/peps/pep-0306/ And even that's incorrect. You'd have to modify the tokenizer. From benjamin at python.org Fri Aug 21 16:25:45 2009 From: benjamin at python.org (Benjamin Peterson) Date: Fri, 21 Aug 2009 20:25:45 +0000 (UTC) Subject: Annoying octal notation References: <20090821194857.GU20434@dragontoe.org> Message-ID: Derek Martin pizzashack.org> writes: > More than flushing out > bugs, it will *cause* them in ubiquity, requiring likely terabytes of > code to be poured over and fixed. 2to3, however, can fix it for you extreme easily. From code at pizzashack.org Fri Aug 21 16:44:14 2009 From: code at pizzashack.org (Derek Martin) Date: Fri, 21 Aug 2009 15:44:14 -0500 Subject: Annoying octal notation In-Reply-To: References: <20090821194857.GU20434@dragontoe.org> Message-ID: <20090821204414.GV20434@dragontoe.org> On Fri, Aug 21, 2009 at 08:25:45PM +0000, Benjamin Peterson wrote: > > More than flushing out bugs, it will *cause* them in ubiquity, > > requiring likely terabytes of code to be poured over and fixed. > > 2to3, however, can fix it for you extreme easily. Sure, but that won't stop people who've been writing code for 20 years from continuing to type octal that way... Humans can learn fairly easily, but UN-learning is often much harder, especially when the behavior to be unlearned is still very commonly in use. Anyway, whatever. This change (along with a few of the other seemingly arbitrary changes in 3.x) is annoying, but Python is still one of the best languages to code in for any multitude of problems. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From piet at cs.uu.nl Fri Aug 21 16:44:41 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 21 Aug 2009 22:44:41 +0200 Subject: Annoying octal notation References: Message-ID: >>>>> Derek Martin (DM) wrote: >DM> I fail to see how 0O012, or even 0o012 is more intelligible than 012. >DM> The latter reads like a typo, and the former is virtually >DM> indistinguishable from 00012, O0012, or many other combinations that >DM> someone might accidentally type (or intentionally type, having to do >DM> this in dozens of other programming languages). You're right. Either hexadecimal should have been 0h or octal should have been 0t :=) -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From martin at v.loewis.de Fri Aug 21 16:45:41 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 21 Aug 2009 22:45:41 +0200 Subject: 2.6 windows install In-Reply-To: References: Message-ID: <4A8F0775.1000208@v.loewis.de> > The default windows install puts Python26.dll in \windows\system32. I > haven't tried this, but you could probably fix your install by moving > Python26.dll into the Python26 directory. Only the admin installation should do that (for all users). The "just for me" installation won't. Regards, Martin From travis+ml-python at subspacefield.org Fri Aug 21 16:50:40 2009 From: travis+ml-python at subspacefield.org (travis+ml-python at subspacefield.org) Date: Fri, 21 Aug 2009 15:50:40 -0500 Subject: proposal: add setresuid() system call to python In-Reply-To: <877hy38mxw.fsf@busola.homelinux.net> References: <20090717200141.GI6065@subspacefield.org> <148918f0907171315i4ed5b274v77581a43c4464f8f@mail.gmail.com> <7cj89qF27mfrjU1@mid.uni-berlin.de> <877hy38mxw.fsf@busola.homelinux.net> Message-ID: <20090821205040.GK1215@subspacefield.org> On Mon, Jul 20, 2009 at 04:10:35PM +0200, Hrvoje Niksic wrote: > To emulate the os-module-type calls, it's better to raise exceptions > than return negative values: > > > def setresuid(ruid, euid, suid): > > return _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid)) > > def setresuid(ruid, euid, suid): > res = _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid)) > if res < 0: > raise OSError('[Errno %d] %s' % (os.errno, errno.strerror(os.errno))) I am working on a module to implement all of this, but that raise command won't work in Python 2.6.1; it turns out that os.errno is a module, not an integer. Does anyone know how to do what I want (that is, how to access the errno set in C functions)? -- Obama Nation | My emails do not have attachments; it's a digital signature that your mail program doesn't understand. | http://www.subspacefield.org/~travis/ If you are a spammer, please email john at subspacefield.org to get blacklisted. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 850 bytes Desc: not available URL: From seanm.py at gmail.com Fri Aug 21 16:55:51 2009 From: seanm.py at gmail.com (newb.py) Date: Fri, 21 Aug 2009 13:55:51 -0700 (PDT) Subject: IDLE file saving problem Message-ID: <70222640-1990-4fae-bbca-8451d252a1ab@13g2000prl.googlegroups.com> I am learning Python and need to use use IDLE, but I am having a problem. When I open a new window in IDLE and write my code, all is well. The coloring works and is very helpful. However, when I save the file I am working on, all the color disappears. And what is more frustrating is that when I open the saved file, it opens in TextEdit, so I have to copy it back into a new IDLE window to work on the code. If someone could clear up this seemingly simple problem for me, I would really appreciate it. Much thanks, Sean From python at mrabarnett.plus.com Fri Aug 21 17:10:49 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 21 Aug 2009 22:10:49 +0100 Subject: IDLE file saving problem In-Reply-To: <70222640-1990-4fae-bbca-8451d252a1ab@13g2000prl.googlegroups.com> References: <70222640-1990-4fae-bbca-8451d252a1ab@13g2000prl.googlegroups.com> Message-ID: <4A8F0D59.9010508@mrabarnett.plus.com> newb.py wrote: > I am learning Python and need to use use IDLE, but I am having a > problem. When I open a new window in IDLE and write my code, all is > well. The coloring works and is very helpful. However, when I save the > file I am working on, all the color disappears. And what is more > frustrating is that when I open the saved file, it opens in TextEdit, > so I have to copy it back into a new IDLE window to work on the code. > > If someone could clear up this seemingly simple problem for me, I > would really appreciate it. > That happens if you don't provide the extension, eg you save as "my_script" instead of "my_script.py". (Perhaps IDLE should add the extension if the user doesn't.) From python at mrabarnett.plus.com Fri Aug 21 17:18:41 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 21 Aug 2009 22:18:41 +0100 Subject: Annoying octal notation In-Reply-To: References: Message-ID: <4A8F0F31.4080107@mrabarnett.plus.com> Piet van Oostrum wrote: >>>>>> Derek Martin (DM) wrote: > >> DM> I fail to see how 0O012, or even 0o012 is more intelligible than 012. >> DM> The latter reads like a typo, and the former is virtually >> DM> indistinguishable from 00012, O0012, or many other combinations that >> DM> someone might accidentally type (or intentionally type, having to do >> DM> this in dozens of other programming languages). > > You're right. Either hexadecimal should have been 0h or octal should > have been 0t :=) I have seen the use of Q/q instead in order to make it clearer. I still prefer Smalltalk's 16rFF and 8r377. From breamoreboy at yahoo.co.uk Fri Aug 21 17:20:20 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 21 Aug 2009 22:20:20 +0100 Subject: Three-Phase-Diagrams with matplotlib In-Reply-To: <25082083.post@talk.nabble.com> References: <25082083.post@talk.nabble.com> Message-ID: M. Hecht wrote: > Hello, > > does anyone know whether it is possible to draw three-phase-diagrams with > matplotlib? > > A three-phase-diagram is a triangular diagram applied in chemistry e.g. for > slags where > one has three main components of a chemical substance at the corners and > points or lines > within the triangle marking different compositions of the substances in > percent, e.g. > in metallurgy 20% Al2O3, 45% CaO and 35% SiO2. > > As noone else has responded try the matplotlib users' mailing list, see http://sourceforge.net/mail/?group_id=80706 -- Kindest regards. Mark Lawrence. From rt8396 at gmail.com Fri Aug 21 17:48:56 2009 From: rt8396 at gmail.com (r) Date: Fri, 21 Aug 2009 14:48:56 -0700 (PDT) Subject: IDLE file saving problem References: <70222640-1990-4fae-bbca-8451d252a1ab@13g2000prl.googlegroups.com> Message-ID: On Aug 21, 4:10?pm, MRAB wrote: [snip] > That happens if you don't provide the extension, eg you save as > "my_script" instead of "my_script.py". (Perhaps IDLE should add the > extension if the user doesn't.) Yes, and much more needs improvement! I have made many changes already and i am polishing an "IDLE 3000" for the good people of Pythonia, stay tuned more to come.... From jgardner at jonathangardner.net Fri Aug 21 17:53:55 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 21 Aug 2009 14:53:55 -0700 (PDT) Subject: Using 'apply' as a decorator, to define constants References: Message-ID: On Aug 21, 6:36?am, Jonathan Fine wrote: > ? ? ?@apply > ? ? ?def tags(): > ? ? ? ? ?value = [] > ? ? ? ? ?# complicated code > ? ? ? ? ?return value > Is this different from: tags = [] # complicated code I can see the argument that you are cleaning up a lot of intermediary variables upon return, though. From jgardner at jonathangardner.net Fri Aug 21 18:17:40 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Fri, 21 Aug 2009 15:17:40 -0700 (PDT) Subject: Using 'apply' as a decorator, to define constants References: Message-ID: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> On Aug 21, 9:09?am, alex23 wrote: > On Aug 21, 11:36?pm, Jonathan Fine wrote: > > class ColourThing(object): > ? ? @apply > ? ? def rgb(): > ? ? ? ? def fset(self, rgb): > ? ? ? ? ? ? self.r, self.g, self.b = rgb > ? ? ? ? def fget(self): > ? ? ? ? ? ? return (self.r, self.g, self.b) > ? ? ? ? return property(**locals()) > This is brilliant. I am going to use this more often. I've all but given up on property() since defining "get_foo", "get_bar", etc... has been a pain and polluted the namespace. > Unfortunately, apply() has been removed as a built-in in 3.x. I'm not > sure if it has been relocated to a module somewhere, there's no > mention of such in the docs. apply = lambda f: f() It's one of those functions that is easier to define than import. > Why I've personally stopped using it: I've always had the impression > that decorators were intended to provide a convenient and obvious way > of augmenting functions. Having one that automatically executes the > function at definition just runs counter to the behaviour I expect > from a decorator. Especially when direct assignment... foo = foo > () ...is a far more direct and clear way of expressing exactly what is > happening. > If anyone reads the decorator and doesn't think "this thing below is defined as the result of this decorator function" then they don't understand decorators at all. From sean.marimpietri at gmail.com Fri Aug 21 18:21:52 2009 From: sean.marimpietri at gmail.com (seanm) Date: Fri, 21 Aug 2009 15:21:52 -0700 (PDT) Subject: Reading, writing files Message-ID: In the book I am using, they give the following function as an example: def copyFile(oldFile, newFile): f1 = open(oldFile, 'r') f2 = open(newFile, 'w') while True: text = f1.read(50) if text == "": break f2.write(text) f1.close() f2.close() return My question is why does this function successfully copy a 200 character file, oldFile, to newFile? The line of code that reads, text = f1.read(50), does not seem to be iterative in any way to me. How is this fuction succeding in adding each additional set up 50 characters to the previous set of 50 characters read from oldFile? How does it even succeed in copying a 25 character file? If oldFile contains 25 characters, how does the program ever break out of the 'while True:' loop? I just don't see it. Again, much thanks to anyone who can clear this up. -Sean From seanm.py at gmail.com Fri Aug 21 18:25:17 2009 From: seanm.py at gmail.com (newb.py) Date: Fri, 21 Aug 2009 15:25:17 -0700 (PDT) Subject: Help Please Message-ID: <75c475fc-5f93-4e41-98f3-9bde17859343@d4g2000prc.googlegroups.com> In the book I am using, they give the following function as an example: def copyFile(oldFile, newFile): f1 = open(oldFile, 'r') f2 = open(newFile, 'w') while True: text = f1.read(50) if text == "": break f2.write(text) f1.close() f2.close() return My question is why does this function successfully copy a 200 character file, oldFile, to newFile? The line of code that reads, text = f1.read(50), does not seem to be iterative in any way to me. How is this fuction succeding in adding each additional set up 50 characters to the previous set of 50 characters read from oldFile? How does it even succeed in copying a 25 character file? If oldFile contains 25 characters, how does the program ever break out of the 'while True:' loop? I just don't see it. Again, much thanks to anyone who can clear this up. -Sean From marduk at letterboxes.org Fri Aug 21 18:42:56 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Fri, 21 Aug 2009 18:42:56 -0400 Subject: Reading, writing files In-Reply-To: References: Message-ID: <1250894576.5655.5.camel@centar.nbk> On Fri, 2009-08-21 at 15:21 -0700, seanm wrote: > In the book I am using, they give the following function as an > example: > > def copyFile(oldFile, newFile): > f1 = open(oldFile, 'r') > f2 = open(newFile, 'w') > while True: > text = f1.read(50) > if text == "": > break > f2.write(text) > f1.close() > f2.close() > return > > My question is why does this function successfully copy a 200 > character file, oldFile, to newFile? The line of code that reads, text > = f1.read(50), does not seem to be iterative in any way to me. How is > this fuction succeding in adding each additional set up 50 characters > to the previous set of 50 characters read from oldFile? The body of the loop will execute forever (unless cut short by the "break" statement. What the loop is essentially doing is reading 50 bytes at a time from f1 and writing it into f2. When f1 reaches end of file it will stop returning bytes (if text == "":) the loop is broken and both files are closed. > How does it even succeed in copying a 25 character file? If oldFile > contains 25 characters, how does the program ever break out of the > 'while True:' loop? > > I just don't see it. Have you read the documentation for file objects? During the first iteration of the loop 25 bytes are read from f1. Then they are written to f2. During the next iteration there is nothing else to be read from f1 so f1.read(50) returns "", which causes the loop to break. > Again, much thanks to anyone who can clear this up. > From marduk at letterboxes.org Fri Aug 21 18:43:54 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Fri, 21 Aug 2009 18:43:54 -0400 Subject: Help Please In-Reply-To: <75c475fc-5f93-4e41-98f3-9bde17859343@d4g2000prc.googlegroups.com> References: <75c475fc-5f93-4e41-98f3-9bde17859343@d4g2000prc.googlegroups.com> Message-ID: <1250894634.5655.6.camel@centar.nbk> Why do you post the same question twice within 5 minutes of each other? From python at mrabarnett.plus.com Fri Aug 21 18:52:17 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 21 Aug 2009 23:52:17 +0100 Subject: Reading, writing files In-Reply-To: References: Message-ID: <4A8F2521.2040406@mrabarnett.plus.com> seanm wrote: > In the book I am using, they give the following function as an > example: > > def copyFile(oldFile, newFile): > f1 = open(oldFile, 'r') > f2 = open(newFile, 'w') > while True: > text = f1.read(50) This will read up to 50 characters from the input file. At the end of the file it'll return an empty string (""). In fact, the only time it'll return an empty string is at the end of the file. > if text == "": > break > f2.write(text) > f1.close() > f2.close() > return > > My question is why does this function successfully copy a 200 > character file, oldFile, to newFile? The line of code that reads, text > = f1.read(50), does not seem to be iterative in any way to me. How is > this fuction succeding in adding each additional set up 50 characters > to the previous set of 50 characters read from oldFile? > > How does it even succeed in copying a 25 character file? If oldFile > contains 25 characters, how does the program ever break out of the > 'while True:' loop? > > I just don't see it. > > Again, much thanks to anyone who can clear this up. > It reads some characters from the input file and then writes then to the output file, and because of the 'while' loop it'll repeat action that until the read returns an empty string, which will be when it has read all the way to the end of file and tries to read some more. From ben+python at benfinney.id.au Fri Aug 21 18:52:21 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 22 Aug 2009 08:52:21 +1000 Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <8763chldpd.fsf@benfinney.id.au> Message-ID: <87ocq8kcey.fsf@benfinney.id.au> josef writes: > On Aug 21, 4:26?am, Ben Finney wrote: > > Note that, after that list is created, each item in that list is > > *also* a reference to the corresponding object. That is, ?a? is a > > reference to an object, and ?dk[0]? is a *different* reference to > > the *same* object. The object has no knowledge about those > > references. > > This is surprising. Perhaps so, depending on your initial assumptions. But it's quite consistent: every time you use an object, you do so via some kind of reference to that object. Those references are the way you get at the same object again later. > My initial thought is that dk[0] hold the object reference 'a,' but > that wouldn't be true "pass by object reference." Right. It stores an entirely *separate* reference to that object. The reference ?dk[0]?, a list item, and the reference ?a?, a name, both refer to the same object. Neither of those references knows anything about the other. > When defining the object reference dk[0] Not ?defining?. You're binding (?assigning?, if you like) a reference. > python takes the object reference 'a,' More accurately, it takes the object referred to by ?a?. (Also, please don't put the comma inside the quotes; it's syntactically significant, and changes the meaning of what you're writing in code.) > finds the object MyClass0() No. ?MyClass0()? is syntax for ?call MyClass0 and get its return value?. The return value will be a new instance of the class ? a *new* object every time you use that syntax. Rather, the object referred to by ?a? will be the result of evaluating the identifier ?a?. As a shortcut for discussion, you can talk about ?the object ?a??, but remember that the only things you're using in the syntax of your Python code is object *references*, be they identifiers (names) or some other kind of reference. > and then assigns the object identity to dk[0]? Or something close to > that. You'd do well to read for a good, simple coverage of the Python object model. > I'm a bit shocked that there isn't a method for catching object > reference names. Don't be; there is no such thing as an ?object reference name?. A name is an object reference. So is every other way of getting at a Python object in your code. > I think that something like a = MyClass0(name = 'a', ...) is a bit > redundant. It usually is, yes. Why do you think you need it? The natural way to handle objects and names together in Python is with a mapping; a ?dict? instance. > Are definitions treated the same way? How would one print or pass > function names? Functions are objects like any other, but since they're more likely to want to know their own name, the name is stored as an attribute:: >>> def frobnicate_nodule(spam): ... """ Frobnicate the spam nodule. """ ... >>> type(frobnicate_nodule) >>> frobnicate_nodule.__name__ 'frobnicate_nodule' The fact that the function name is stored in one of those funky double-underscore names is a big clue that the attribute is special (in this case, because it gets assigned automatically by the Python interpreter). That's not the case for most types, though. > I think I'll just add a 'name' to the classes' init defintion. What is the larger problem you're trying to solve, and why do you think it will be helped by instances knowing a name for themselves? (Note: an object can never know *all* names for itself, let alone all the other references to itself; and you must write your program in the knowledge that no reference to an object has any intrinsic special status against any of the other references to that object.) -- \ ?I spent a lot of money on wine and women, and like a fool I | `\ squandered the rest.? ?Benny Hill | _o__) | Ben Finney From ben+python at benfinney.id.au Fri Aug 21 18:55:11 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 22 Aug 2009 08:55:11 +1000 Subject: Sanitising arguments to shell commands References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> <50697b2c0908210219i5e02c0cbq2d63bff891624ef4@mail.gmail.com> Message-ID: <87k50wkca8.fsf@benfinney.id.au> Rick King writes: > shlex doesn't handle unicode input though, so, in general, it's not a > good solution. Argh. Is there a Python bug tracker number for fixing that? Or is there a better solution? -- \ ?Pinky, are you pondering what I'm pondering?? ?I think so, | `\ Brain, but if we have nothing to fear but fear itself, why does | _o__) Elanore Roosevelt wear that spooky mask?? ?_Pinky and The Brain_ | Ben Finney From pavlovevidence at gmail.com Fri Aug 21 19:23:29 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 21 Aug 2009 16:23:29 -0700 (PDT) Subject: proposal: add setresuid() system call to python References: <20090717200141.GI6065@subspacefield.org> <148918f0907171315i4ed5b274v77581a43c4464f8f@mail.gmail.com> <7cj89qF27mfrjU1@mid.uni-berlin.de> <877hy38mxw.fsf@busola.homelinux.net> Message-ID: On Aug 21, 1:50?pm, travis+ml-pyt... at subspacefield.org wrote: > On Mon, Jul 20, 2009 at 04:10:35PM +0200, Hrvoje Niksic wrote: > > To emulate the os-module-type calls, it's better to raise exceptions > > than return negative values: > > > > def setresuid(ruid, euid, suid): > > > ? ? return _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid)) > > > def setresuid(ruid, euid, suid): > > ? ? res = _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid)) > > ? ? if res < 0: > > ? ? ? ? raise OSError('[Errno %d] %s' % (os.errno, errno.strerror(os.errno))) > > I am working on a module to implement all of this, but that raise command > won't work in Python 2.6.1; it turns out that os.errno is a module, not > an integer. ?Does anyone know how to do what I want (that is, how to access > the errno set in C functions)? You are using ctypes, I presume? Try replacing raise OSError with this: ctypes.pythonapi.PyErr_SetFromErrno(ctypes.py_object(OSError)) Not entirely sure it'll work with Python built with a static library, but I think it will. Carl Banks From james.harris.1 at googlemail.com Fri Aug 21 19:23:57 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Fri, 21 Aug 2009 16:23:57 -0700 (PDT) Subject: Annoying octal notation References: Message-ID: On 21 Aug, 20:48, Derek Martin wrote: ... > James Harris wrote: > > It maybe made sense once but this relic of the past should have been > > consigned to the waste bin of history long ago. > > Sigh. ?Nonsense. ?I use octal notation *every day*, for two extremely > prevalent purposes: file creation umask, and Unix file permissions > (i.e. the chmod() function/command). ? You misunderstand. I was saying that taking a leading zero as indicating octal is archaic. Octal itself is fine where appropriate. The chmod command doesn't require a leading zero. James From dullrich at sprynet.com Fri Aug 21 19:32:41 2009 From: dullrich at sprynet.com (David C. Ullrich) Date: Fri, 21 Aug 2009 18:32:41 -0500 Subject: Silly question References: Message-ID: <5jbu85dvva20ntj9iai1rhp9a51ipan989@4ax.com> On Fri, 21 Aug 2009 14:45:55 -0500, David C Ullrich wrote: >[...] > >Oops. Should have tested that a little more carefully >before posting. No time to fix it right now, customer just >got here. Let's just say we're looking for the primes >between sqrt(n) and n... from math import sqrt def Primes(n): """Return a list of the primes < n""" sieve = range(n) for k in range(2,int(sqrt(n))+2): sieve[2*k::k] = [1]*((n-k-1)/k) return [p for p in sieve if p > 1] David C. Ullrich "Understanding Godel isn't about following his formal proof. That would make a mockery of everything Godel was up to." (John Jones, "My talk about Godel to the post-grads." in sci.logic.) From aahz at pythoncraft.com Fri Aug 21 19:38:42 2009 From: aahz at pythoncraft.com (Aahz) Date: 21 Aug 2009 16:38:42 -0700 Subject: Code formatting question: conditional expression References: <7evr1pF2i4mouU1@mid.uni-berlin.de> <87ocqchl2k.fsf@benfinney.id.au> Message-ID: In article <87ocqchl2k.fsf at benfinney.id.au>, Ben Finney wrote: >"Diez B. Roggisch" writes: >> >> excessblk = None >> if total > P.BASE: >> excessblk = ... >> >> You don't lose any vertical space, > >I don't see vertical space as such a scarce resource; we don't have an >imminent newline shortage, to my knowledge. I value it far lower than, >say, local readability. We don't have a newline shortage, but we do have a pixel shortage. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From james.harris.1 at googlemail.com Fri Aug 21 19:52:29 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Fri, 21 Aug 2009 16:52:29 -0700 (PDT) Subject: Annoying octal notation References: Message-ID: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> On 21 Aug, 22:18, MRAB wrote: > Piet van Oostrum wrote: > >>>>>> Derek Martin (DM) wrote: > > >> DM> I fail to see how 0O012, or even 0o012 is more intelligible than 012. > >> DM> The latter reads like a typo, and the former is virtually > >> DM> indistinguishable from 00012, O0012, or many other combinations that > >> DM> someone might accidentally type (or intentionally type, having to do > >> DM> this in dozens of other programming languages). ? > > > You're right. Either hexadecimal should have been 0h or octal should > > have been 0t :=) > > I have seen the use of Q/q instead in order to make it clearer. I still > prefer Smalltalk's 16rFF and 8r377. Two interesting options. In a project I have on I have also considered using 0q as indicating octal. I maybe saw it used once somewhere else but I have no idea where. 0t was a second choice and 0c third choice (the other letters of oct). 0o should NOT be used for obvious reasons. So you are saying that Smalltalk has r where r is presumably for radix? That's maybe best of all. It preserves the syntactic requirement of starting a number with a digit and seems to have greatest flexibility. Not sure how good it looks but it's certainly not bad. 0xff & 0x0e | 0b1101 16rff & 16r0e | 2r1101 Hmm. Maybe a symbol would be better than a letter. James From wgheath at gmail.com Fri Aug 21 19:58:50 2009 From: wgheath at gmail.com (Tim Heath) Date: Fri, 21 Aug 2009 16:58:50 -0700 (PDT) Subject: Invitation to connect on LinkedIn Message-ID: <485663771.786023.1250899130772.JavaMail.app@ech3-cdn10.prod> LinkedIn ------------ Tim Heath requested to add you as a connection on LinkedIn: ------------------------------------------ Jaime, I'd like to add you to my professional network on LinkedIn. - Tim View invitation from Tim Heath http://www.linkedin.com/e/I2LlXdLlWUhFABKmxVOlgGLlWUhFAfhMPPF/blk/I287618177_3/0PnPsTcjwNdzsUcAALqnpPbOYWrSlI/svi/ ------------------------------------------ DID YOU KNOW you can be the first to know when a trusted member of your network changes jobs? With Network Updates on your LinkedIn home page, you'll be notified as members of your network change their current position. Be the first to know and reach out! http://www.linkedin.com/ ------ (c) 2009, LinkedIn Corporation -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Fri Aug 21 20:02:14 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 21 Aug 2009 17:02:14 -0700 Subject: Sanitising arguments to shell commands In-Reply-To: <87k50wkca8.fsf@benfinney.id.au> References: <873a7l21gr.fsf@benfinney.id.au> <87ab1tlekn.fsf_-_@benfinney.id.au> <50697b2c0908210219i5e02c0cbq2d63bff891624ef4@mail.gmail.com> <87k50wkca8.fsf@benfinney.id.au> Message-ID: <50697b2c0908211702h2a2017f8r18f9a7b4b56d87fa@mail.gmail.com> On Fri, Aug 21, 2009 at 3:55 PM, Ben Finney wrote: > Rick King writes: > >> shlex doesn't handle unicode input though, so, in general, it's not a >> good solution. > > Argh. Is there a Python bug tracker number for fixing that? Indeed there is: http://bugs.python.org/issue1170 It even has a patch. I wonder why it's unapplied. Cheers, Chris -- http://blog.rebertia.com From ben+python at benfinney.id.au Fri Aug 21 20:03:35 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 22 Aug 2009 10:03:35 +1000 Subject: Annoying octal notation References: Message-ID: <87d46ok948.fsf@benfinney.id.au> Derek Martin writes: > James Harris wrote: > > It maybe made sense once but this relic of the past should have been > > consigned to the waste bin of history long ago. > > Sigh. Nonsense. I use octal notation *every day*, for two extremely > prevalent purposes: file creation umask, and Unix file permissions > (i.e. the chmod() function/command). Right. Until Unix stops using these (and whatever replaces it would have to be pretty compelling, given the prevalence of these in octal notation), or until people stop using Unix, these will be with us and require octal notation. That doesn't mean, of course, that we need to elevate it above hexadecimal in our language syntax; ?0o012? will allow octal notation for literals just fine. > I fail to see how 0O012, or even 0o012 is more intelligible than 012. > The latter reads like a typo No, it reads like a very common notation for decimal numbers in natural usage. It's very frequently not a typo, but an expression of a three-digit decimal number that happens to be less than 100. > and the former is virtually indistinguishable from 00012, O0012, or > many other combinations that someone might accidentally type (or > intentionally type, having to do this in dozens of other programming > languages). Only if you type the letter in uppercase. The lower-case ?o? is much easier to distinguish. Whether or not you find ?0o012? easily distinguishable as a non-decimal notation, it's undoubtedly easier to distinguish than ?012?. > I can see how 012 can be confusing to new programmers, but at least > it's legible, and the great thing about humans is that they can be > taught (usually). I for one think this change is completely misguided. These human programmers, whether newbies or long-experienced, also deal with decimal numbers every day, many of which are presented as a sequence of digits with leading zeros ? and we continue to think of them as decimal numbers regardless. Having the language syntax opposed to that is a wart, a cognitive overhead with little benefit, and I'll be glad to see it go in favour of a clearer syntax. -- \ ?? one of the main causes of the fall of the Roman Empire was | `\ that, lacking zero, they had no way to indicate successful | _o__) termination of their C programs.? ?Robert Firth | Ben Finney -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 202 bytes Desc: not available URL: From ben+python at benfinney.id.au Fri Aug 21 20:09:29 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sat, 22 Aug 2009 10:09:29 +1000 Subject: Annoying octal notation References: <20090821194857.GU20434@dragontoe.org> Message-ID: <878whck8ue.fsf@benfinney.id.au> Derek Martin writes: > Sure, but that won't stop people who've been writing code for 20 years > from continuing to type octal that way... Humans can learn fairly > easily, but UN-learning is often much harder, especially when the > behavior to be unlearned is still very commonly in use. This is exactly the argument for removing ?012? octal notation: humans (and programmers who have far less need for octal numbers than for decimal numbers) are *already* trained, and reinforced many times daily, to think of that notation as a decimal number. They should not need to un-learn that association in order to understand octal literals in code. > Anyway, whatever. This change (along with a few of the other seemingly > arbitrary changes in 3.x) is annoying, but Python is still one of the > best languages to code in for any multitude of problems. Hear hear. -- \ ?I wrote a song, but I can't read music so I don't know what it | `\ is. Every once in a while I'll be listening to the radio and I | _o__) say, ?I think I might have written that.?? ?Steven Wright | Ben Finney -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 202 bytes Desc: not available URL: From smono927 at gmail.com Fri Aug 21 21:15:35 2009 From: smono927 at gmail.com (SeanMon) Date: Fri, 21 Aug 2009 18:15:35 -0700 (PDT) Subject: Decompressing gzip over FTP Message-ID: Is there a way to decompress a large (2GB) gzipped file being retrieved over FTP on the fly? I'm using ftplib.FTP to open a connection to a remote server, and I have had no success connecting retrbinary to gzip without using an intermediate file. Is there any way to get a file-like object describing the remote file, or a way to utilize gzip's decompression without providing it a file- like object? Thanks, Sean From lists at cheimes.de Fri Aug 21 21:40:58 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 Aug 2009 03:40:58 +0200 Subject: Decompressing gzip over FTP In-Reply-To: References: Message-ID: <4A8F4CAA.7040903@cheimes.de> SeanMon schrieb: > Is there a way to decompress a large (2GB) gzipped file being > retrieved over FTP on the fly? > > I'm using ftplib.FTP to open a connection to a remote server, and I > have had no success connecting retrbinary to gzip without using an > intermediate file. > > Is there any way to get a file-like object describing the remote file, > or a way to utilize gzip's decompression without providing it a file- > like object? gzip is really just a file format. In order to work with compressed streams you should use the low level zlib module. http://docs.python.org/library/zlib.html#module-zlib Have fun! Christian From smono927 at gmail.com Fri Aug 21 21:51:47 2009 From: smono927 at gmail.com (SeanMon) Date: Fri, 21 Aug 2009 18:51:47 -0700 (PDT) Subject: Decompressing gzip over FTP References: Message-ID: <0bf17e27-408c-4d67-90cc-74f28789f524@32g2000yqj.googlegroups.com> On Aug 21, 9:40?pm, Christian Heimes wrote: > SeanMon schrieb: > > > Is there a way to decompress a large (2GB) gzipped file being > > retrieved over FTP on the fly? > > > I'm using ftplib.FTP to open a connection to a remote server, and I > > have had no success connecting retrbinary to gzip without using an > > intermediate file. > > > Is there any way to get a file-like object describing the remote file, > > or a way to utilize gzip's decompression without providing it a file- > > like object? > > gzip is really just a file format. In order to work with compressed > streams you should use the low level zlib module. > > http://docs.python.org/library/zlib.html#module-zlib > > Have fun! > > Christian Unfortunately, the file on the server is a gzip file, so I cannot simply pipe the contents into a zlib.decompressobj (which does have the ability to decompress in chunks, as I wish gzip did!). Thanks, Sean From subhakolkata1234 at gmail.com Fri Aug 21 22:15:31 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Fri, 21 Aug 2009 19:15:31 -0700 (PDT) Subject: Questions on XML Message-ID: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Dear Group, I like to convert some simple strings of natural language to XML. May I use Python to do this? If any one can help me, on this. I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I use Python to help me in this regard? How can I learn good XML aspects of Python. If any one can kindly name me a book or URL. I am using Python2.6 on Windows XP with IDLE as GUI. Best Regards, Subhabrata. From wuwei23 at gmail.com Fri Aug 21 22:35:38 2009 From: wuwei23 at gmail.com (alex23) Date: Fri, 21 Aug 2009 19:35:38 -0700 (PDT) Subject: Using 'apply' as a decorator, to define constants References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> Message-ID: Jonathan Gardner wrote: > This is brilliant. I am going to use this more often. I've all but > given up on property() since defining "get_foo", "get_bar", etc... has > been a pain and polluted the namespace. Unfortunately I can't remember who I first learned it from - it was definitely in a post to this group - otherwise all credit would be their's. > It's one of those functions that is easier to define than import. And so obvious now :) > If anyone reads the decorator and doesn't think "this thing below is > defined as the result of this decorator function" then they don't > understand decorators at all. Well, it's not so much a question of the reader's intelligence as that Python already has a readily identifiable assignment operator. Having a second mechanism for assignment with no real similarity to the first just adds cognitive friction to reading the code...not because the reader doesn't understand what is happening, but because it's not obvious _why_ this second form would have been chosen. Nothing that couldn't be mitigated with a comment, I guess. # @apply used to prevent having to repeat references That would work for me. From steve at REMOVE-THIS-cybersource.com.au Fri Aug 21 22:54:27 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 02:54:27 GMT Subject: Using 'apply' as a decorator, to define constants References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> Message-ID: <0018e14c$0$2938$c3e8da3@news.astraweb.com> On Fri, 21 Aug 2009 15:17:40 -0700, Jonathan Gardner wrote: >> Unfortunately, apply() has been removed as a built-in in 3.x. I'm not >> sure if it has been relocated to a module somewhere, there's no mention >> of such in the docs. > > apply = lambda f: f() > > It's one of those functions that is easier to define than import. >>> apply = lambda f: f() >>> __builtin__.apply(len, 'a') 1 >>> apply(len, 'a') Traceback (most recent call last): File "", line 1, in TypeError: () takes exactly 1 argument (2 given) It's a little bit more difficult to define it *correctly*. Here's a working version of apply: def apply(object, *args, **kwargs): """apply(object[, args[, kwargs]]) -> value Call a callable object with positional and keyword arguments. >>> apply(max, 'one', 'two', 'three', 'four', key=len) 'three' """ return object(*args, **kwargs) Note that this: * actually does what apply() is supposed to do; * defines the function name, useful for tracebacks; * has a docstring, useful for interactive use and documentation; * includes an example suitable for automated testing with doctest. -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 21 22:55:51 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 02:55:51 GMT Subject: Annoying octal notation References: Message-ID: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> On Fri, 21 Aug 2009 14:48:57 -0500, Derek Martin wrote: >> It maybe made sense once but this relic of the past should have been >> consigned to the waste bin of history long ago. > > Sigh. Nonsense. I use octal notation *every day*, for two extremely > prevalent purposes: file creation umask, and Unix file permissions (i.e. > the chmod() function/command). And you will still be able to, by explicitly using octal notation. > I fail to see how 0O012, or even 0o012 is more intelligible than 012. The first is wrong, bad, wicked, and if I catch anyone using it, they will be soundly slapped with a halibut. *wink* Using O instead of o for octal is so unreadable that I think it should be prohibited by the language, no matter that hex notation accepts both x and X. > The latter reads like a typo, *Everything* reads like a typo if you're unaware of the syntax being used. > and the former is virtually > indistinguishable from 00012, O0012, or many other combinations that > someone might accidentally type (or intentionally type, having to do > this in dozens of other programming languages). Agreed. > I can see how 012 can > be confusing to new programmers, but at least it's legible, and the > great thing about humans is that they can be taught (usually). And the great thing is that now you get to teach yourself to stop writing octal numbers implicitly and be write them explicitly with a leading 0o instead :) It's not just new programmers -- it's any programmer who is unaware of the notation (possibly derived from C) that a leading 0 means "octal". That's a strange and bizarre notation to use, because 012 is a perfectly valid notation for decimal 12, as are 0012, 00012, 000012 and so forth. Anyone who has learnt any mathematics beyond the age of six will almost certainly expect 012 to equal 12. Having 012 equal 10 comes as a surprise even to people who are familiar with octal. > I for > one think this change is completely misguided. More than flushing out > bugs, it will *cause* them in ubiquity, requiring likely terabytes of > code to be poured over and fixed. Changing decades-old behaviors common > throughout a community for the sake of avoiding a minor inconvenience of > the n00b is DUMB. Use of octal isn't common. You've given two cases were octal notation is useful, but for every coder who frequently writes umasks on Unix systems, there are a thousand who don't. It's no hardship to write 0o12 instead of 012. -- Steven From dns4 at cornell.edu Fri Aug 21 22:57:16 2009 From: dns4 at cornell.edu (David Smith) Date: Fri, 21 Aug 2009 22:57:16 -0400 Subject: Questions on XML In-Reply-To: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Message-ID: joy99 wrote: > Dear Group, > > I like to convert some simple strings of natural language to XML. May > I use Python to do this? If any one can help me, on this. > > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > use Python to help me in this regard? > > How can I learn good XML aspects of Python. If any one can kindly name > me a book or URL. > > I am using Python2.6 on Windows XP with IDLE as GUI. > > Best Regards, > Subhabrata. Take a look at xml.etree.ElementTree package and it's contents. It's included in the binary distributions of Python 2.6. There are lot's of books out covering XML and UTF-8 is exactly where you want to be w/ XML. --David From rami.chowdhury at gmail.com Sat Aug 22 00:18:13 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Fri, 21 Aug 2009 21:18:13 -0700 Subject: Questions on XML In-Reply-To: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Message-ID: > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > use Python to help me in this regard? I can say from experience that Python on Windows (at least, Python 2.5 on 32-bit Vista) works perfectly well with UTF-8 files containing Bangla. I have had trouble with working with the data in IDLE, however, which seems to prefer ASCII by default. ------------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Aug 21, 2009, at 19:15 , joy99 wrote: > Dear Group, > > I like to convert some simple strings of natural language to XML. May > I use Python to do this? If any one can help me, on this. > > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > use Python to help me in this regard? > > How can I learn good XML aspects of Python. If any one can kindly name > me a book or URL. > > I am using Python2.6 on Windows XP with IDLE as GUI. > > Best Regards, > Subhabrata. > -- > http://mail.python.org/mailman/listinfo/python-list From stefan_ml at behnel.de Sat Aug 22 01:53:31 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 22 Aug 2009 07:53:31 +0200 Subject: Questions on XML In-Reply-To: References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Message-ID: <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> Rami Chowdhury wrote: >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I >> use Python to help me in this regard? > > I can say from experience that Python on Windows (at least, Python 2.5 > on 32-bit Vista) works perfectly well with UTF-8 files containing > Bangla. I have had trouble with working with the data in IDLE, however, > which seems to prefer ASCII by default. Defaults almost never work for encodings. You have to be explicit: add an encoding declaration to the top of your source file if you use encoded literal strings in your code; use the codecs module with a suitable encoding to read encoded text files, and use an XML parser when reading XML. Stefan From kee at kagi.com Sat Aug 22 02:09:36 2009 From: kee at kagi.com (Kee Nethery) Date: Fri, 21 Aug 2009 23:09:36 -0700 Subject: Questions on XML In-Reply-To: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Message-ID: On Aug 21, 2009, at 7:15 PM, joy99 wrote: > Dear Group, > > I like to convert some simple strings of natural language to XML. May > I use Python to do this? If any one can help me, on this. > > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > use Python to help me in this regard? As a newbie, the thing that caused me trouble was importing a string into the XML parser. The parser seemed to want to open a file and I had a string. The solution was one of these: from xml.etree import ElementTree as et theXmlDataTree = et.parse(StringIO.StringIO(theXmlString)) from xml.etree import ElementTree as et theXmlDataTree = et.ElementTree(et.XML(theXmlString)) Not sure which you would use nor what the differences are. I have the first set commented out in my code so for some reason I switched to the second set of code to take a string and pull it into the XML parser. Once the string is in the parser, all the examples worked. It was getting it into the parser that had me stumped because none of the examples showed this situation, it appears to be obvious to someone who has used Python for a while. Kee From subhakolkata1234 at gmail.com Sat Aug 22 02:13:33 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Fri, 21 Aug 2009 23:13:33 -0700 (PDT) Subject: Questions on XML References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <575587f9-b2d2-498f-a907-0a90c260aa60@i4g2000prm.googlegroups.com> On Aug 22, 10:53?am, Stefan Behnel wrote: > Rami Chowdhury wrote: > >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > >> use Python to help me in this regard? > > > I can say from experience that Python on Windows (at least, Python 2.5 > > on 32-bit Vista) works perfectly well with UTF-8 files containing > > Bangla. I have had trouble with working with the data in IDLE, however, > > which seems to prefer ASCII by default. > > Defaults almost never work for encodings. You have to be explicit: add an > encoding declaration to the top of your source file if you use encoded > literal strings in your code; use the codecs module with a suitable > encoding to read encoded text files, and use an XML parser when reading XML. > > Stefan Dear Group, Thanx for your reply. Python works perfectly for Hindi and Bangla with Win XP. I never had a trouble. Best Regards, Subhabrata. From emmanuel.surleau at gmail.com Sat Aug 22 02:55:17 2009 From: emmanuel.surleau at gmail.com (Emmanuel Surleau) Date: Sat, 22 Aug 2009 08:55:17 +0200 Subject: Questions on XML In-Reply-To: <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <200908220855.17815.emmanuel.surleau@gmail.com> > >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > >> use Python to help me in this regard? > > > > I can say from experience that Python on Windows (at least, Python 2.5 > > on 32-bit Vista) works perfectly well with UTF-8 files containing > > Bangla. I have had trouble with working with the data in IDLE, however, > > which seems to prefer ASCII by default. > > Defaults almost never work for encodings. You have to be explicit: add an > encoding declaration to the top of your source file if you use encoded > literal strings in your code; use the codecs module with a suitable > encoding to read encoded text files, and use an XML parser when reading > XML. Actually, default *should* work for XML. The default encoding for an XML file is UTF-8 (AFAIK). Cheers, Emm From emmanuel.surleau at gmail.com Sat Aug 22 02:59:56 2009 From: emmanuel.surleau at gmail.com (Emmanuel Surleau) Date: Sat, 22 Aug 2009 08:59:56 +0200 Subject: Questions on XML In-Reply-To: <575587f9-b2d2-498f-a907-0a90c260aa60@i4g2000prm.googlegroups.com> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> <575587f9-b2d2-498f-a907-0a90c260aa60@i4g2000prm.googlegroups.com> Message-ID: <200908220859.56127.emmanuel.surleau@gmail.com> On Saturday 22 August 2009 08:13:33 joy99 wrote: > On Aug 22, 10:53 am, Stefan Behnel wrote: > > Rami Chowdhury wrote: > > >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > > >> use Python to help me in this regard? > > > > > > I can say from experience that Python on Windows (at least, Python 2.5 > > > on 32-bit Vista) works perfectly well with UTF-8 files containing > > > Bangla. I have had trouble with working with the data in IDLE, however, > > > which seems to prefer ASCII by default. > > > > Defaults almost never work for encodings. You have to be explicit: add an > > encoding declaration to the top of your source file if you use encoded > > literal strings in your code; use the codecs module with a suitable > > encoding to read encoded text files, and use an XML parser when reading > > XML. > > > > Stefan > > Dear Group, > Thanx for your reply. Python works perfectly for Hindi and Bangla with > Win XP. I never had a trouble. > Best Regards, > Subhabrata. You might also want to have a look at lxml. It can much more than the XML module in the default distribution, uses ElementTree as well, and is backed by the kickass, fast libxml library (http://codespeak.net/lxml/). It will allow you to use XSLs, for instance. Regardless of whether you use lxml or not, have a look at etree.iterparse, it is invaluable when processing huge XML documents. Cheers, Emm From jfine at pytex.org Sat Aug 22 03:09:52 2009 From: jfine at pytex.org (Jonathan Fine) Date: Sat, 22 Aug 2009 08:09:52 +0100 Subject: Using 'apply' as a decorator, to define constants In-Reply-To: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> Message-ID: Jonathan Gardner wrote: > On Aug 21, 9:09 am, alex23 wrote: >> On Aug 21, 11:36 pm, Jonathan Fine wrote: >> >> class ColourThing(object): >> @apply >> def rgb(): >> def fset(self, rgb): >> self.r, self.g, self.b = rgb >> def fget(self): >> return (self.r, self.g, self.b) >> return property(**locals()) >> > > This is brilliant. I am going to use this more often. I've all but > given up on property() since defining "get_foo", "get_bar", etc... has > been a pain and polluted the namespace. I think we can do better, with a little work. And also solve the problem that 'apply' is no longer a builtin in Python3. Here's my suggestion: === import wibble # Informs reader we're doing something special here. class ColourThing(object): @wibble.property def rgb(): '''This is the docstring for the property.''' def fset(self, rgb): self.r, self.g, self.b = rgb def fget(self): return (self.r, self.g, self.b) return locals() === And here's wibble.property() === _property = property # Avoid collision. def property(fn): return _property(doc=fn.__doc__, **fn()) === We can add apply() to the wibble module. By the way, 'wibble' is a placeholder to the real name. Any suggestions? -- Jonathan From kushal.kumaran+python at gmail.com Sat Aug 22 03:11:49 2009 From: kushal.kumaran+python at gmail.com (Kushal Kumaran) Date: Sat, 22 Aug 2009 12:41:49 +0530 Subject: convert date time In-Reply-To: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> References: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> Message-ID: <1e364c4e0908220011qd99b59ek973060fd767d1dc0@mail.gmail.com> On Fri, Aug 21, 2009 at 11:44 PM, Ronn Ross wrote: > I'm new to python and I'm getting a date time from a field in the database > that looks like this: > 8/2/2009 8:36:16 AM (UTC) > > I want to split it into two fields one with the date formatted like this: > YYYY-MM-DD? 2009-08-02 > > and the time to be 24 hour or military time. How every you call it. Similar > to this: > 15:22:00 > > I found it easy to truncate off the (UTC), but having trouble converting the > date. Can someone point me in the right direction? > datetime.datetime.strptime() will give you a datetime object, which you can then format in a wide variety of ways using its strftime() method. Doesn't work with dates earlier than 1900, I believe. -- kushal From rami.chowdhury at gmail.com Sat Aug 22 03:16:29 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Sat, 22 Aug 2009 00:16:29 -0700 Subject: Questions on XML In-Reply-To: <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <89952E85-0E6C-4B62-A638-E742E67030CF@gmail.com> > encoding declaration to the top of your source file if you use encoded > literal strings in your code Any tips for how to set the encoding in IDLE? printing the Unicode strings works -- trying to repr() the variable chokes with a UnicodeDecodeError, and trying to enter the literals inside IDLE just gets me '?' characters instead. (this is Python 2.5 + IDLE installed from the Python-2.5.msi on python.org) ------------- Rami Chowdhury "Never assume malice when stupidity will suffice." -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Aug 21, 2009, at 22:53 , Stefan Behnel wrote: > Rami Chowdhury wrote: >>> I am using primarily UTF-8 based strings, like Hindi or Bengali. >>> Can I >>> use Python to help me in this regard? >> >> I can say from experience that Python on Windows (at least, Python >> 2.5 >> on 32-bit Vista) works perfectly well with UTF-8 files containing >> Bangla. I have had trouble with working with the data in IDLE, >> however, >> which seems to prefer ASCII by default. > > Defaults almost never work for encodings. You have to be explicit: > add an > encoding declaration to the top of your source file if you use encoded > literal strings in your code; use the codecs module with a suitable > encoding to read encoded text files, and use an XML parser when > reading XML. > > Stefan > -- > http://mail.python.org/mailman/listinfo/python-list From ray.belanger at gmail.com Sat Aug 22 04:17:49 2009 From: ray.belanger at gmail.com (flagmino) Date: Sat, 22 Aug 2009 01:17:49 -0700 (PDT) Subject: debugger Message-ID: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> To get familiar with the debugger, I have loaded this program: import math def s1(x, y): a = (x + y) print("Answer from s1"), a return def s2(x, y): b = (x - y) print("This comes from s2"), b #print z print("call from s2: "), s1(x, y) return I am trying to debug: I press shift-F9 and F7. I end up in the interpreter where I enter s2 (1, 2). >From that point if I press F7, the program restart all over. If I press Enter, the program gets out of debug mode. Please help me figuring out how I can use the dbugger. You are welcome to send a sound file if this is easier for you. Thanks ray From ak at nothere.com Sat Aug 22 04:20:23 2009 From: ak at nothere.com (AK) Date: Sat, 22 Aug 2009 04:20:23 -0400 Subject: How to 'de-slashify' a string? Message-ID: <4a8faa47$0$31283$607ed4bc@cv.net> Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' in a general way? The problem I'm running into is that I'm connecting with pygresql to a postgres database and when I get fields that are of 'char' type, I get them in unicode, but when I get fields of 'byte' type, I get the text with quoted slashes, e.g. '\303' becomes '\\303' and so on. I saw posts online to do cursor.execute("set client-encoding to unicode") before running queries but this command causes an error. So I think I need a way to de-quote the slashes or alternatively some way to tell pygresql not to quote slashes for 'byte' fields. Any help, hints, etc appreciated.. -- AK From contact at xavierho.com Sat Aug 22 04:53:59 2009 From: contact at xavierho.com (Xavier Ho) Date: Sat, 22 Aug 2009 18:53:59 +1000 Subject: debugger In-Reply-To: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> Message-ID: <2d56febf0908220153r6455323al4610f453443bc175@mail.gmail.com> On Sat, Aug 22, 2009 at 6:17 PM, flagmino wrote: > To get familiar with the debugger, I have loaded this program: > > import math > > def s1(x, y): > a = (x + y) > print("Answer from s1"), a > return > > def s2(x, y): > b = (x - y) > print("This comes from s2"), b > #print z > print("call from s2: "), s1(x, y) > return > > I am trying to debug: > I press shift-F9 and F7. I end up in the interpreter where I enter s2 > (1, 2). > > >From that point if I press F7, the program restart all over. > If I press Enter, the program gets out of debug mode. > > Please help me figuring out how I can use the dbugger. You are welcome > to send a sound file if this is easier for you. > > Thanks > > ray > -- > http://mail.python.org/mailman/listinfo/python-list Sorry, but which debugger are you referring to? Also, note that you're printing s1(x,y) which is returning nothing. Not sure why you want to do that, but just mentioning it. -------------- next part -------------- An HTML attachment was scrubbed... URL: From leonhard.vogt at gmx.ch Sat Aug 22 04:58:47 2009 From: leonhard.vogt at gmx.ch (Leonhard Vogt) Date: Sat, 22 Aug 2009 10:58:47 +0200 Subject: Using 'apply' as a decorator, to define constants In-Reply-To: References: Message-ID: <86f8e$4a8fb348$544b15b8$5398@news.hispeed.ch> > Why I've personally stopped using it: I've always had the impression > that decorators were intended to provide a convenient and obvious way > of augmenting functions. Having one that automatically executes the > function at definition just runs counter to the behaviour I expect > from a decorator. Especially when direct assignment... foo = foo > () ...is a far more direct and clear way of expressing exactly what is > happening. if you have to define it yourself, you could call it store_result or something else instead of apply. @store_result def tags(): return result Leonhard From steve at REMOVE-THIS-cybersource.com.au Sat Aug 22 05:03:39 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 09:03:39 GMT Subject: Using 'apply' as a decorator, to define constants References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> Message-ID: <001937d5$0$2938$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 08:09:52 +0100, Jonathan Fine wrote: > Jonathan Gardner wrote: >> On Aug 21, 9:09 am, alex23 wrote: >>> On Aug 21, 11:36 pm, Jonathan Fine wrote: >>> >>> class ColourThing(object): >>> @apply >>> def rgb(): >>> def fset(self, rgb): >>> self.r, self.g, self.b = rgb >>> def fget(self): >>> return (self.r, self.g, self.b) >>> return property(**locals()) >>> >>> >> This is brilliant. I am going to use this more often. I've all but >> given up on property() since defining "get_foo", "get_bar", etc... has >> been a pain and polluted the namespace. > > > I think we can do better, with a little work. And also solve the > problem that 'apply' is no longer a builtin in Python3. There's a standard idiom for that, using the property() built-in, for Python 2.6 or better. Here's an example including a getter, setter, deleter and doc string, with no namespace pollution, imports, or helper functions or deprecated built-ins: class ColourThing(object): @property def rgb(self): """Get and set the (red, green, blue) colours.""" return (self.r, self.g, self.b) @rgb.setter def rgb(self, rgb): self.r, self.g, self.b = rgb @rgb.deleter def rgb(self): del self.r, self.g, self.b -- Steven From 71david at libero.it Sat Aug 22 05:15:16 2009 From: 71david at libero.it (David) Date: Sat, 22 Aug 2009 11:15:16 +0200 Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <14hj3v50qg77e$.1pk6i6w7h7q6s.dlg@40tude.net> Message-ID: <8aeik0nwe7l6$.znpheg2zqrj3.dlg@40tude.net> Il Fri, 21 Aug 2009 10:36:35 -0700 (PDT), Mensanator ha scritto: > Aha! Then I WAS right after all. Switch to 3.1 and you'll > soon be cured of that bad habit: > >>>> 012 + 012 > SyntaxError: invalid token (, line 1) I have tre (four) problems: 1) I am forced to use 2.5 since the production server has 2.5 installed. 2) Quite often I have to enter many zero-leading numbers and now my fingers put a leading zero almost everywhere 3) I don't understand why useless but *harmless* things like algebrically insignificant leading zeros should be *forbidden* and promoted to errors. 4) I still don't like the '0o..' notation because 0 (zero) and o (lowercase O) glyphs appear very similar in many character sets. I'd prefer something like '0c..' so it resembles the word 'oc' for 'octal'. David From steve at REMOVE-THIS-cybersource.com.au Sat Aug 22 05:18:52 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 09:18:52 GMT Subject: How to 'de-slashify' a string? References: <4a8faa47$0$31283$607ed4bc@cv.net> Message-ID: <00193b65$0$2938$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 04:20:23 -0400, AK wrote: > Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' > in a general way? It's not clear what you mean. Do you mean you have a string '\\303\\266', that is: backslash backslash three zero three backslash backslash two six six If so, then the simplest way is: >>> s = r'\\303\\266' # note the raw string >>> len(s) 10 >>> print s \\303\\266 >>> print s.replace('\\\\', '\\') \303\266 Another possibility: >>> s = '\\303\\266' # this is not a raw string >>> len(s) 8 >>> print s \303\266 So s is: backslash three zero three backslash two six six and you don't need to do any more. > The problem I'm running into is that I'm connecting with pygresql to a > postgres database and when I get fields that are of 'char' type, I get > them in unicode, but when I get fields of 'byte' type, I get the text > with quoted slashes, e.g. '\303' becomes '\\303' and so on. Is pygresql quoting the backslash, or do you just think it is quoting the backslashes? How do you know? E.g. if you have '\\303', what is the length of that? 4 or 5? -- Steven From 71david at libero.it Sat Aug 22 05:27:32 2009 From: 71david at libero.it (David) Date: Sat, 22 Aug 2009 11:27:32 +0200 Subject: Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> Message-ID: <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Il Fri, 21 Aug 2009 16:52:29 -0700 (PDT), James Harris ha scritto: > > 0xff & 0x0e | 0b1101 > 16rff & 16r0e | 2r1101 > > Hmm. Maybe a symbol would be better than a letter. What about 2_1011, 8_7621, 16_c26h or 2;1011, 8;7621, 16;c26h ? David From sjmachin at lexicon.net Sat Aug 22 05:29:53 2009 From: sjmachin at lexicon.net (John Machin) Date: Sat, 22 Aug 2009 02:29:53 -0700 (PDT) Subject: convert date time References: <9c8c445f0908211114x52989399m9dff884ccdd43ad0@mail.gmail.com> Message-ID: On Aug 22, 5:11?pm, Kushal Kumaran wrote: > On Fri, Aug 21, 2009 at 11:44 PM, Ronn Ross wrote: > > I'm new to python and I'm getting a date time from a field in the database > > that looks like this: > > 8/2/2009 8:36:16 AM (UTC) > datetime.datetime.strptime() will give you a datetime object, which > you can then format in a wide variety of ways using its strftime() > method. ?Doesn't work with dates earlier than 1900, I believe. The datetime module works from 0001-01-01 onwards; see http://docs.python.org/library/datetime.html#datetime.MINYEAR Other things worth mentioning: (1) datetime.datetime.strptime() was introduced in Python 2.5; for Python 2.3 and 2.4, use time.strptime() [which may not like years before 1970] followed by datetime.datetime() (2) as the input has 12-hour clock plus AM/PM, ensure that you use %I instead of %H for the hour component; %H won't do what you expect if your expectation is not based on reading the docs :-) From jfine at pytex.org Sat Aug 22 05:51:27 2009 From: jfine at pytex.org (Jonathan Fine) Date: Sat, 22 Aug 2009 10:51:27 +0100 Subject: Using 'apply' as a decorator, to define constants In-Reply-To: <001937d5$0$2938$c3e8da3@news.astraweb.com> References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> <001937d5$0$2938$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > There's a standard idiom for that, using the property() built-in, for > Python 2.6 or better. > > Here's an example including a getter, setter, deleter and doc string, > with no namespace pollution, imports, or helper functions or deprecated > built-ins: > > class ColourThing(object): > @property > def rgb(self): > """Get and set the (red, green, blue) colours.""" > return (self.r, self.g, self.b) > @rgb.setter > def rgb(self, rgb): > self.r, self.g, self.b = rgb > @rgb.deleter > def rgb(self): > del self.r, self.g, self.b Sorry, Steve, but I don't understand this. In fact, I don't even see how it can be made to work. Unless an exception is raised, @wibble def wobble(): pass will make an assignment to wobble, namely the return value of wibble. So in your example above, there will be /three/ assignments to rgb. Unless you do some complicated introspection (and perhaps not even then) surely they will clobber each other. I still prefer: @wibble.property def rgb(): '''Red Green Blue color settings (property)''' def fset(rgb): self.r, self.g, self.b = rgb return locals() -- Jonathan From steve at REMOVE-THIS-cybersource.com.au Sat Aug 22 05:57:32 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 09:57:32 GMT Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <14hj3v50qg77e$.1pk6i6w7h7q6s.dlg@40tude.net> <8aeik0nwe7l6$.znpheg2zqrj3.dlg@40tude.net> Message-ID: <00194475$0$2938$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 11:15:16 +0200, David wrote: > 3) I don't understand why useless but *harmless* things like > algebrically insignificant leading zeros should be *forbidden* and > promoted to errors. The PEP covering this change says: "There are still some strong feelings that '0123' should be allowed as a literal decimal in Python 3.0. If this is the right thing to do, this can easily be covered in an additional PEP. This proposal only takes the first step of making '0123' not be a valid octal number, for reasons covered in the rationale." http://www.python.org/dev/peps/pep-3127/ -- Steven From ekayxu at gmail.com Sat Aug 22 06:03:27 2009 From: ekayxu at gmail.com (EK) Date: Sat, 22 Aug 2009 03:03:27 -0700 (PDT) Subject: Dictionary from a list References: <7f368jF2it5a5U1@mid.uni-berlin.de> Message-ID: On Aug 20, 2:10?pm, Peter Otten <__pete... at web.de> wrote: > Jan Kaliszewski wrote: > > 20-08-2009 o 02:05:57 Jan Kaliszewski wrote: > > >> Or probably better: > > >> ? ? ?from itertools import islice, izip > >> ? ? ?dict(izip(islice(li, 0, None, 2), islice(li, 1, None, 2))) > > > Or similarly, perhaps more readable: > > > ? ? ?iterator = iter(li) > > ? ? ?dict((iterator.next(), iterator.next()) for i in xrange(len(li)/2)) > > I just can't stop posting this one: > > >>> from itertools import izip > >>> it = iter([1,2,3,4,5,6]) > >>> dict(izip(it, it)) > > {1: 2, 3: 4, 5: 6} > > I really tried, but yours drove me over the edge. > > Peter dict(zip(*[iter(l)]*2)) From ak at nothere.com Sat Aug 22 06:09:20 2009 From: ak at nothere.com (AK) Date: Sat, 22 Aug 2009 06:09:20 -0400 Subject: How to 'de-slashify' a string? In-Reply-To: <00193b65$0$2938$c3e8da3@news.astraweb.com> References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> Message-ID: <4a8fc3d1$0$22535$607ed4bc@cv.net> Steven D'Aprano wrote: > On Sat, 22 Aug 2009 04:20:23 -0400, AK wrote: > >> Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' >> in a general way? > > It's not clear what you mean. > > Do you mean you have a string '\\303\\266', that is: > > backslash backslash three zero three backslash backslash two six six > > If so, then the simplest way is: > >>>> s = r'\\303\\266' # note the raw string >>>> len(s) > 10 >>>> print s > \\303\\266 >>>> print s.replace('\\\\', '\\') > \303\266 > > > Another possibility: > >>>> s = '\\303\\266' # this is not a raw string >>>> len(s) > 8 >>>> print s > \303\266 > > So s is: > backslash three zero three backslash two six six > > and you don't need to do any more. Well, I need the string itself to become '\303\266', not to print that way. In other words, when I do 'print s', it should display unicode characters if my term is set to show them, instead of showing \303\266. > > >> The problem I'm running into is that I'm connecting with pygresql to a >> postgres database and when I get fields that are of 'char' type, I get >> them in unicode, but when I get fields of 'byte' type, I get the text >> with quoted slashes, e.g. '\303' becomes '\\303' and so on. > > Is pygresql quoting the backslash, or do you just think it is quoting the > backslashes? How do you know? E.g. if you have '\\303', what is the > length of that? 4 or 5? Length is 4, and I need it to be length of 1. E.g.: >>> s = '\303' >>> s '\xc3' >>> x = '\\303' >>> x '\\303' >>> len(x) 4 >>> len(s) 1 What I get from pygresql is x, what I need is s. Either by asking pygresql to do this or convert it afterwards. I can't do replace('\\303', '\303') because it can be any unicode character. > > -- AK From stefan_ml at behnel.de Sat Aug 22 06:32:52 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sat, 22 Aug 2009 12:32:52 +0200 Subject: Questions on XML In-Reply-To: References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Message-ID: <4a8fc954$0$31331$9b4e6d93@newsspool4.arcor-online.net> Kee Nethery wrote: > As a newbie, the thing that caused me trouble was importing a string > into the XML parser. That would be root_element = et.fromstring(some_string) The parse() function is meant to parse from a file. > from xml.etree import ElementTree as et > theXmlDataTree = et.parse(StringIO.StringIO(theXmlString)) > > from xml.etree import ElementTree as et > theXmlDataTree = et.ElementTree(et.XML(theXmlString)) You can use both, but I suspect parsing from StringIO to be slower than parsing from the string directly. That's the case for lxml, at least. Note that fromstring() behaves the same as XML(), but it reads better when parsing from a string variable. XML() reads better when parsing from a literal string. Stefan From vlastimil.brom at gmail.com Sat Aug 22 06:33:32 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 22 Aug 2009 12:33:32 +0200 Subject: How to 'de-slashify' a string? In-Reply-To: <4a8fc3d1$0$22535$607ed4bc@cv.net> References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> <4a8fc3d1$0$22535$607ed4bc@cv.net> Message-ID: <9fdb569a0908220333u41a662f0j7a898500df50a324@mail.gmail.com> 2009/8/22 AK : > Steven D'Aprano wrote: >> >> On Sat, 22 Aug 2009 04:20:23 -0400, AK wrote: >> >>> Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' >>> in a general way? >> >> It's not clear what you mean. >> >> Do you mean you have a string '\\303\\266', that is: >> >> backslash backslash three zero three backslash backslash two six six >> >> If so, then the simplest way is: >> >>>>> s = r'\\303\\266' ?# note the raw string >>>>> len(s) >> >> 10 >>>>> >>>>> print s >> >> \\303\\266 >>>>> >>>>> print s.replace('\\\\', '\\') >> >> \303\266 >> >> >> Another possibility: >> >>>>> s = '\\303\\266' ?# this is not a raw string >>>>> len(s) >> >> 8 >>>>> >>>>> print s >> >> \303\266 >> >> So s is: >> backslash three zero three backslash two six six >> >> and you don't need to do any more. > > Well, I need the string itself to become '\303\266', not to print > that way. In other words, when I do 'print s', it should display > unicode characters if my term is set to show them, instead of > showing \303\266. > >> >> >>> The problem I'm running into is that I'm connecting with pygresql to a >>> postgres database and when I get fields that are of 'char' type, I get >>> them in unicode, but when I get fields of 'byte' type, I get the text >>> with quoted slashes, e.g. '\303' becomes '\\303' and so on. >> >> Is pygresql quoting the backslash, or do you just think it is quoting the >> backslashes? How do you know? E.g. if you have '\\303', what is the length >> of that? 4 or 5? > > Length is 4, and I need it to be length of 1. E.g.: > >>>> s = '\303' >>>> s > '\xc3' >>>> x = '\\303' >>>> x > '\\303' >>>> len(x) > 4 >>>> len(s) > 1 > > > What I get from pygresql is x, what I need is s. Either by asking pygresql > to do this or convert it afterwards. I can't do replace('\\303', '\303') > because it can be any unicode character. > >> >> > > > -- > AK > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, do you mean something like >>> u"\u0303" u'\u0303' >>> print u"\u0303" ? ? (dec.: 771) (hex.: 0x303) ? COMBINING TILDE (Mark, Nonspacing) ? vbr From steve at REMOVE-THIS-cybersource.com.au Sat Aug 22 06:45:13 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 10:45:13 GMT Subject: Using 'apply' as a decorator, to define constants References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> <001937d5$0$2938$c3e8da3@news.astraweb.com> Message-ID: <00194fa2$0$2938$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 10:51:27 +0100, Jonathan Fine wrote: > Steven D'Aprano wrote: > >> There's a standard idiom for that, using the property() built-in, for >> Python 2.6 or better. >> >> Here's an example including a getter, setter, deleter and doc string, >> with no namespace pollution, imports, or helper functions or deprecated >> built-ins: >> >> class ColourThing(object): >> @property >> def rgb(self): >> """Get and set the (red, green, blue) colours.""" return >> (self.r, self.g, self.b) >> @rgb.setter >> def rgb(self, rgb): >> self.r, self.g, self.b = rgb >> @rgb.deleter >> def rgb(self): >> del self.r, self.g, self.b > > > Sorry, Steve, but I don't understand this. In fact, I don't even see > how it can be made to work. Nevertheless, it does work, and it's not even magic. It's described (very briefly) in the docstring for property: help(property) will show it to you. More detail is here: http://docs.python.org/library/functions.html#property As for how it can work, it's not that difficult. All you need is for the setter and deleter methods to add an appropriate fset and fdel method to the property, then return it. Here's a toy example which may demonstrate the process (although unlike property, fget, fset and fdel don't have any special meanings): class ToyProperty(object): def __init__(self, fget, fset=None, fdel=None, fdoc=None): if fdoc is None: fdoc = fget.__doc__ self.fget = fget self.fset = fset self.fdel = fdel def getter(self, fget): self.fget = fget return self def setter(self, fset): self.fset = fset return self def deleter(self, fdel): self.fdel = fdel return self > Unless an exception is raised, > @wibble > def wobble(): > pass > will make an assignment to wobble, namely the return value of wibble. So > in your example above, there will be /three/ assignments to rgb. Yes. A tiny inefficiency, which only occurs when the class is created. If you care about that, then (1) use the full form of property() where you supply the fget, fset and fdel arguments all at once, and (2) you really need to get out into the fresh air more *wink* > Unless > you do some complicated introspection (and perhaps not even then) surely > they will clobber each other. So what? The process is no weirder than: x = ['fget'] x = x + ['fset'] x = x + ['fdel'] -- Steven From ak at nothere.com Sat Aug 22 06:52:53 2009 From: ak at nothere.com (AK) Date: Sat, 22 Aug 2009 06:52:53 -0400 Subject: How to 'de-slashify' a string? In-Reply-To: References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> <4a8fc3d1$0$22535$607ed4bc@cv.net> Message-ID: <4a8fce05$0$31285$607ed4bc@cv.net> Vlastimil Brom wrote: > 2009/8/22 AK : >> Steven D'Aprano wrote: >>> On Sat, 22 Aug 2009 04:20:23 -0400, AK wrote: >>> >>>> Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' >>>> in a general way? >>> It's not clear what you mean. >>> >>> Do you mean you have a string '\\303\\266', that is: >>> >>> backslash backslash three zero three backslash backslash two six six >>> >>> If so, then the simplest way is: >>> >>>>>> s = r'\\303\\266' # note the raw string >>>>>> len(s) >>> 10 >>>>>> print s >>> \\303\\266 >>>>>> print s.replace('\\\\', '\\') >>> \303\266 >>> >>> >>> Another possibility: >>> >>>>>> s = '\\303\\266' # this is not a raw string >>>>>> len(s) >>> 8 >>>>>> print s >>> \303\266 >>> >>> So s is: >>> backslash three zero three backslash two six six >>> >>> and you don't need to do any more. >> Well, I need the string itself to become '\303\266', not to print >> that way. In other words, when I do 'print s', it should display >> unicode characters if my term is set to show them, instead of >> showing \303\266. >> >>> >>>> The problem I'm running into is that I'm connecting with pygresql to a >>>> postgres database and when I get fields that are of 'char' type, I get >>>> them in unicode, but when I get fields of 'byte' type, I get the text >>>> with quoted slashes, e.g. '\303' becomes '\\303' and so on. >>> Is pygresql quoting the backslash, or do you just think it is quoting the >>> backslashes? How do you know? E.g. if you have '\\303', what is the length >>> of that? 4 or 5? >> Length is 4, and I need it to be length of 1. E.g.: >> >>>>> s = '\303' >>>>> s >> '\xc3' >>>>> x = '\\303' >>>>> x >> '\\303' >>>>> len(x) >> 4 >>>>> len(s) >> 1 >> >> >> What I get from pygresql is x, what I need is s. Either by asking pygresql >> to do this or convert it afterwards. I can't do replace('\\303', '\303') >> because it can be any unicode character. >> >>> >> >> -- >> AK >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > Hi, > do you mean something like > >>>> u"\u0303" > u'\u0303' >>>> print u"\u0303" > ? > ? (dec.: 771) (hex.: 0x303) ? COMBINING TILDE (Mark, Nonspacing) > ? > > vbr Yes, something like that except that it starts out as '\\303\\266', and it's good enough for me if it turns into '\303\266', in fact that's rendered as one unicode char. In other words, when you do: >>> print "\\303\\266" '\303\266' I need that result to become a python string, i.e. the slashes need to be converted from literal slashes to escape slashes. -- AK From marduk at letterboxes.org Sat Aug 22 07:34:17 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sat, 22 Aug 2009 07:34:17 -0400 Subject: debugger In-Reply-To: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> Message-ID: <1250940857.28537.0.camel@centar.nbk> On Sat, 2009-08-22 at 01:17 -0700, flagmino wrote: [...] > I am trying to debug: > I press shift-F9 and F7. I end up in the interpreter where I enter s2 > (1, 2). > > >From that point if I press F7, the program restart all over. > If I press Enter, the program gets out of debug mode. Umm.. which debugger is that? My debugger doesn't have shift-F9... -a From steve at REMOVE-THIS-cybersource.com.au Sat Aug 22 07:40:33 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 22 Aug 2009 11:40:33 GMT Subject: How to 'de-slashify' a string? References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> <4a8fc3d1$0$22535$607ed4bc@cv.net> Message-ID: <00195c9b$0$2938$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 06:09:20 -0400, AK wrote: >> Is pygresql quoting the backslash, or do you just think it is quoting >> the backslashes? How do you know? E.g. if you have '\\303', what is the >> length of that? 4 or 5? > > Length is 4, and I need it to be length of 1. E.g.: > > >>> s = '\303' > >>> s > '\xc3' > >>> x = '\\303' > >>> x > '\\303' > >>> len(x) > 4 > >>> len(s) > 1 > > > What I get from pygresql is x, what I need is s. Either by asking > pygresql to do this or convert it afterwards. I can't do > replace('\\303', '\303') because it can be any unicode character. Use the 'unicode-escape' codec to decode the byte-string to Unicode. >>> s = '\\303\\266' >>> print s \303\266 >>> s '\\303\\266' >>> len(s) 8 >>> u = s.decode('unicode-escape') >>> print u ?? >>> u u'\xc3\xb6' >>> len(u) 2 -- Steven From vlastimil.brom at gmail.com Sat Aug 22 07:43:22 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 22 Aug 2009 13:43:22 +0200 Subject: How to 'de-slashify' a string? In-Reply-To: <4a8fce05$0$31285$607ed4bc@cv.net> References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> <4a8fc3d1$0$22535$607ed4bc@cv.net> <4a8fce05$0$31285$607ed4bc@cv.net> Message-ID: <9fdb569a0908220443i47998230o115e6109835e3b67@mail.gmail.com> 2009/8/22 AK : > Vlastimil Brom wrote: >> >> 2009/8/22 AK : >>> >>> Steven D'Aprano wrote: >>>> >>>> On Sat, 22 Aug 2009 04:20:23 -0400, AK wrote: >>>> >>>>> Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' >>>>> in a general way? >>>> >>>> It's not clear what you mean. >>>> >>>> Do you mean you have a string '\\303\\266', that is: >>>> >>>> backslash backslash three zero three backslash backslash two six six >>>> >>>> If so, then the simplest way is: >>>> >>>>>>> s = r'\\303\\266' ?# note the raw string >>>>>>> len(s) >>>> >>>> 10 >>>>>>> >>>>>>> print s >>>> >>>> \\303\\266 >>>>>>> >>>>>>> print s.replace('\\\\', '\\') >>>> >>>> \303\266 >>>> >>>> >>>> Another possibility: >>>> >>>>>>> s = '\\303\\266' ?# this is not a raw string >>>>>>> len(s) >>>> >>>> 8 >>>>>>> >>>>>>> print s >>>> >>>> \303\266 >>>> >>>> So s is: >>>> backslash three zero three backslash two six six >>>> >>>> and you don't need to do any more. >>> >>> Well, I need the string itself to become '\303\266', not to print >>> that way. In other words, when I do 'print s', it should display >>> unicode characters if my term is set to show them, instead of >>> showing \303\266. >>> >>>> >>>>> The problem I'm running into is that I'm connecting with pygresql to a >>>>> postgres database and when I get fields that are of 'char' type, I get >>>>> them in unicode, but when I get fields of 'byte' type, I get the text >>>>> with quoted slashes, e.g. '\303' becomes '\\303' and so on. >>>> >>>> Is pygresql quoting the backslash, or do you just think it is quoting >>>> the >>>> backslashes? How do you know? E.g. if you have '\\303', what is the >>>> length >>>> of that? 4 or 5? >>> >>> Length is 4, and I need it to be length of 1. E.g.: >>> >>>>>> s = '\303' >>>>>> s >>> >>> '\xc3' >>>>>> >>>>>> x = '\\303' >>>>>> x >>> >>> '\\303' >>>>>> >>>>>> len(x) >>> >>> 4 >>>>>> >>>>>> len(s) >>> >>> 1 >>> >>> >>> What I get from pygresql is x, what I need is s. Either by asking >>> pygresql >>> to do this or convert it afterwards. I can't do replace('\\303', '\303') >>> because it can be any unicode character. >>> >>>> >>> >>> -- >>> AK >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> >> >> Hi, >> do you mean something like >> >>>>> u"\u0303" >> >> u'\u0303' >>>>> >>>>> print u"\u0303" >> >> ? >> ? ?? (dec.: 771) ?(hex.: 0x303) ? ? COMBINING TILDE (Mark, Nonspacing) >> ? >> >> vbr > > Yes, something like that except that it starts out as '\\303\\266', and it's > good enough for me if it turns into '\303\266', in fact that's rendered as > one unicode char. In other words, when you do: > >>>> print "\\303\\266" > '\303\266' > > I need that result to become a python string, i.e. the slashes need to > be converted from literal slashes to escape slashes. > > > > > -- > AK > -- > http://mail.python.org/mailman/listinfo/python-list > Not sure, whether it is the right way of handling the such text data, but maybe: >>> decoded = '\\303\\266'.decode("string_escape") >>> decoded '\xc3\xb6' >>> print decoded ?? >>> print '\303\266' ?? >>> It might be an IDLE issue, but it still isn't one unicode glyph. I guess, you have to ensure, that the input data is valid and the right encoding is used. hth vbr From jfine at pytex.org Sat Aug 22 08:04:02 2009 From: jfine at pytex.org (Jonathan Fine) Date: Sat, 22 Aug 2009 13:04:02 +0100 Subject: Using 'apply' as a decorator, to define constants In-Reply-To: <00194fa2$0$2938$c3e8da3@news.astraweb.com> References: <3c82e522-e879-473b-b814-d9bcd9d905de@u20g2000prg.googlegroups.com> <001937d5$0$2938$c3e8da3@news.astraweb.com> <00194fa2$0$2938$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Sat, 22 Aug 2009 10:51:27 +0100, Jonathan Fine wrote: > >> Steven D'Aprano wrote: >> >>> There's a standard idiom for that, using the property() built-in, for >>> Python 2.6 or better. >>> >>> Here's an example including a getter, setter, deleter and doc string, >>> with no namespace pollution, imports, or helper functions or deprecated >>> built-ins: >>> >>> class ColourThing(object): >>> @property >>> def rgb(self): >>> """Get and set the (red, green, blue) colours.""" return >>> (self.r, self.g, self.b) >>> @rgb.setter >>> def rgb(self, rgb): >>> self.r, self.g, self.b = rgb >>> @rgb.deleter >>> def rgb(self): >>> del self.r, self.g, self.b >> >> Sorry, Steve, but I don't understand this. In fact, I don't even see >> how it can be made to work. > > Nevertheless, it does work, and it's not even magic. It's described (very > briefly) in the docstring for property: help(property) will show it to > you. More detail is here: > > http://docs.python.org/library/functions.html#property My apologies. I wasn't up to date with my Python versions: | Changed in version 2.6: The getter, setter, and deleter | attributes were added. I was still thinking Python2.5 (or perhaps earlier?). I still don't like it. All those repetitions of 'rgb'. -- Jonathan From lists at cheimes.de Sat Aug 22 08:35:21 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 22 Aug 2009 14:35:21 +0200 Subject: grokproject and zope.security==3.4.1 error In-Reply-To: References: Message-ID: Manuel A. Iglesias Abbatemarco schrieb: > I will apprreciate if someone could help me with the following error. > > I a trying to create a grokproject application in my debian 5.0 box, > the following is the output after executing # grokproject Sample > command. > > Getting distribution for 'zope.security==3.4.1'. > > src/zope/security/_proxy.c:19:20: error: Python.h: No such file or directory sudo apt-get install python2.4-dev Have fun :) Christian From python at mrabarnett.plus.com Sat Aug 22 08:55:39 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 22 Aug 2009 13:55:39 +0100 Subject: Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> Message-ID: <4A8FEACB.7030202@mrabarnett.plus.com> Dennis Lee Bieber wrote: > On Fri, 21 Aug 2009 16:52:29 -0700 (PDT), James Harris > declaimed the following in > gmane.comp.python.general: > >> So you are saying that Smalltalk has r where >> r is presumably for radix? That's maybe best of all. It preserves the >> syntactic requirement of starting a number with a digit and seems to >> have greatest flexibility. Not sure how good it looks but it's >> certainly not bad. >> >> 0xff & 0x0e | 0b1101 >> 16rff & 16r0e | 2r1101 >> >> Hmm. Maybe a symbol would be better than a letter. >> > Or Ada's 16#FF#, 8#377#... > '#' starts a comment, so that's right out! :-) > I forget if DEC/VMS FORTRAN or Xerox Sigma FORTRAN used x'FF' or > 'FF'x, and o'377' or '377'o From python at mrabarnett.plus.com Sat Aug 22 08:55:42 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 22 Aug 2009 13:55:42 +0100 Subject: Annoying octal notation In-Reply-To: <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <4A8FEACE.9060503@mrabarnett.plus.com> David wrote: > Il Fri, 21 Aug 2009 16:52:29 -0700 (PDT), James Harris ha scritto: > > >> 0xff & 0x0e | 0b1101 >> 16rff & 16r0e | 2r1101 >> >> Hmm. Maybe a symbol would be better than a letter. > > What about 2_1011, 8_7621, 16_c26h or 2;1011, 8;7621, 16;c26h ? > '_': what if in the future we want to allow them in numbers for clarity? ';': used to separate multiple statements on a line (but not used that often). From catalinfest at gmail.com Sat Aug 22 09:14:25 2009 From: catalinfest at gmail.com (catafest) Date: Sat, 22 Aug 2009 06:14:25 -0700 (PDT) Subject: PIL and Python References: <9683190f-3c99-49d6-93d1-d8966d38d7a6@j21g2000yqe.googlegroups.com> <5df342cf-c742-42d6-bc8c-97a3c44a0816@h21g2000yqa.googlegroups.com> Message-ID: If I make it work, i will send the solution. Thank you ! From stef.mientki at gmail.com Sat Aug 22 09:40:51 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 22 Aug 2009 15:40:51 +0200 Subject: debugger In-Reply-To: <1250940857.28537.0.camel@centar.nbk> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> <1250940857.28537.0.camel@centar.nbk> Message-ID: <4A8FF563.5070003@gmail.com> Albert Hopkins wrote: > On Sat, 2009-08-22 at 01:17 -0700, flagmino wrote: > [...] > >> I am trying to debug: >> I press shift-F9 and F7. I end up in the interpreter where I enter s2 >> (1, 2). >> >> >From that point if I press F7, the program restart all over. >> If I press Enter, the program gets out of debug mode. >> > > Umm.. which debugger is that? My debugger doesn't have shift-F9... > then you probably not working under windows ... Stef From piet at cs.uu.nl Sat Aug 22 09:52:44 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 22 Aug 2009 15:52:44 +0200 Subject: How to 'de-slashify' a string? References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> <4a8fc3d1$0$22535$607ed4bc@cv.net> <4a8fce05$0$31285$607ed4bc@cv.net> Message-ID: >>>>> Vlastimil Brom (VB) wrote: >>>>> decoded = '\\303\\266'.decode("string_escape") >>>>> decoded >VB> '\xc3\xb6' >>>>> print decoded >VB> ?? >>>>> print '\303\266' >VB> ?? >>>>> >VB> It might be an IDLE issue, but it still isn't one unicode glyph. >VB> I guess, you have to ensure, that the input data is valid and the >VB> right encoding is used. >>> decoded = '\\303\\266'.decode("string_escape").decode('utf-8') >>> decoded u'\xf6' >>> print decoded ? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From python.list at tim.thechases.com Sat Aug 22 10:07:52 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 22 Aug 2009 09:07:52 -0500 Subject: debugger In-Reply-To: <4A8FF563.5070003@gmail.com> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> <1250940857.28537.0.camel@centar.nbk> <4A8FF563.5070003@gmail.com> Message-ID: <4A8FFBB8.4070706@tim.thechases.com> Stef Mientki wrote: > Albert Hopkins wrote: >> On Sat, 2009-08-22 at 01:17 -0700, flagmino wrote: >> [...] >> >>> I am trying to debug: >>> I press shift-F9 and F7. I end up in the interpreter where I enter s2 >>> (1, 2). >>> >>> >From that point if I press F7, the program restart all over. >>> If I press Enter, the program gets out of debug mode. >>> >> Umm.. which debugger is that? My debugger doesn't have shift-F9... >> > then you probably not working under windows ... Even under Windows, you still have to specify your environment. In both Win32 and *nix I use pdb as my debugger and shift+F9 does nothing ;-) So the question is what is the debugger the OP is using? Because it's not pdb. :) -tkc From grante at visi.com Sat Aug 22 10:08:09 2009 From: grante at visi.com (Grant Edwards) Date: Sat, 22 Aug 2009 09:08:09 -0500 Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> <6a523329-3287-4271-ba37-7be450cfc5f6@d32g2000yqh.googlegroups.com> <4a8edc29$0$1599$742ec2ed@news.sonic.net> Message-ID: On 2009-08-22, Dennis Lee Bieber wrote: > On Fri, 21 Aug 2009 10:45:51 -0700, John Nagle > declaimed the following in gmane.comp.python.general: > >> >> And it's over. We can finally dispense with octal by default. >> > I've not looked at modern Intel processor format, but if there are > folks still using variants of 8080 (8051?) and Z-80, Octal still works > nice for op-codes... I don't recall the exact values, but the MOV > instruction was something like '1SD'o, where S and D are three bit > register specifications (A, B, C, D, E, H, L, and Memory as I recall) The Heathkit's terminal I have uses a Z80, and IIRC, the assembly listings were in split-octal [a 16 bit word ranges from 000 000 to 377 377]. Stuff for the PDP-11 (which also had instruction fields 3 bits wide) was always in octal as well. The PDP-11 is pretty much dead, but I think there are embedded Z80 derivitives still in use. -- Grant From ebonak at hotmail.com Sat Aug 22 10:25:37 2009 From: ebonak at hotmail.com (Esmail) Date: Sat, 22 Aug 2009 10:25:37 -0400 Subject: your favorite debugging tool? Message-ID: Hi all, What is your favorite tool to help you debug your code? I've been getting along with 'print' statements but that is getting old and somewhat cumbersome. I'm primarily interested in utilities for Linux (but if you have recommendations for Windows, I'll take them too :) I use emacs as my primary development environment, FWIW. Someone mentioned winpdb .. anyone have experience/comments on this? Others? Thanks, Esmail From Scott.Daniels at Acm.Org Sat Aug 22 10:37:08 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sat, 22 Aug 2009 07:37:08 -0700 Subject: debugger In-Reply-To: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> Message-ID: flagmino wrote: > To get familiar with the debugger, I have loaded this program: > > import math > > def s1(x, y): > a = (x + y) > print("Answer from s1"), a > return > > def s2(x, y): > b = (x - y) > print("This comes from s2"), b > #print z > print("call from s2: "), s1(x, y) > return > > I am trying to debug: > I press shift-F9 and F7. I end up in the interpreter where I enter s2 > (1, 2). > > From that point if I press F7, the program restart all over. > If I press Enter, the program gets out of debug mode. > > Please help me figuring out how I can use the dbugger. You are welcome > to send a sound file if this is easier for you. > > Thanks > > ray You need to tell us: Which Python version (e.g. 2.6.2) Which "platform" (hardware & OS) (e.g. 64-bit AMD FreeBSD) Which debugger (e.g. Idle) What you expected to happen that did not, and why you expected it. or What happened and why you did not expect it. Often you can lots of this information by going to your debugger window and doing Help // About, and go to your Python environment and type: import sys print sys.version # cut the results and paste in your message as "sys.version says, "'2.6.2 (r262:71605, ...'" [don't do dots yourself] To understand more of why we need this on every question, see: http://www.mikeash.com/getting_answers.html or google for "smart questions". --Scott David Daniels Scott.Daniels at Acm.Org From aahz at pythoncraft.com Sat Aug 22 10:49:22 2009 From: aahz at pythoncraft.com (Aahz) Date: 22 Aug 2009 07:49:22 -0700 Subject: your favorite debugging tool? References: Message-ID: In article , Esmail wrote: > >What is your favorite tool to help you debug your code? I've been >getting along with 'print' statements but that is getting old and >somewhat cumbersome. Despite the fact that I've been using Python for more than a decade, print is still my mainstay (or possibly logging to a file). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From davea at ieee.org Sat Aug 22 10:51:08 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 22 Aug 2009 10:51:08 -0400 Subject: Blank Line at Program Exit In-Reply-To: References: Message-ID: <4A9005DC.1050906@ieee.org> Steven Woody wrote: > Hi, > Any python program, even that does absolutely nothing in the code, will > cause a blank line printed out when the program exit. What's the reason? > Thanks. > > > I think the "blank line" is coming from your shell. In Windows, I believe the shell emits a newline after running a program, probably to make sure the prompt starts in column 0. Note that if your python program writes a partial line to stdout, this will "finish" the line before giving you the next prompt. So the line isn't necessarily blank. DaveA From marduk at letterboxes.org Sat Aug 22 10:59:55 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sat, 22 Aug 2009 10:59:55 -0400 Subject: Decompressing gzip over FTP In-Reply-To: References: Message-ID: <1250953195.7115.5.camel@centar.nbk> On Fri, 2009-08-21 at 18:15 -0700, SeanMon wrote: > Is there a way to decompress a large (2GB) gzipped file being > retrieved over FTP on the fly? > > I'm using ftplib.FTP to open a connection to a remote server, and I > have had no success connecting retrbinary to gzip without using an > intermediate file. > > Is there any way to get a file-like object describing the remote file, > or a way to utilize gzip's decompression without providing it a file- > like object? I tried to solve your problem with StringIO and .truncate(). I also tried to solve it with us.pipe(), but was unsuccessful with either. The problem is the gzip module uses .seek() which you can't do with pipes... You could probably get away with just using the compress module (as zlib does) but you will have to deal with handling the headers, footers, CRC checks, etc. on your own. The cheap alternative is to just have your script open a pipe to "gunzip -c" and read/write from that pipe. hth, -a From ryniek90 at gmail.com Sat Aug 22 11:00:41 2009 From: ryniek90 at gmail.com (ryniek90) Date: Sat, 22 Aug 2009 17:00:41 +0200 Subject: TypeError while checking for permissions with os.access() on windows xp In-Reply-To: References: Message-ID: <4A900819.8010702@gmail.com> > First, some nitpicking: Include the whole traceback when posting about > errors please. Don't write "if some_boolean_expression != True:" > instead prefer "if not some_boolean_expression:". Also, in your code > "except (Except), ex: return ex" the parentheses are redundant, > there's no "Except" Exception (unless you created one yourself) and > why are you catching and returning the Exception object? (Also, > what's that "sys.exit(0)" doing in there? And why exit with 0 if there > was a problem? Exit code 0 means "no problem".) > > > Second, from what you've said backup_dest must be None: > > >>>> import os >>>> os.access(None, os.W_OK) >>>> > > Traceback (most recent call last): > File "", line 1, in > os.access(None, os.W_OK) > TypeError: coercing to Unicode: need string or buffer, NoneType found > > No, backup_dest is destination for backup. It's this variable: *backup_dest = self.__backup_dest* . *self.__backup_dest = os.getenv('HOME')* - as you can see, self.__backup_dest is a reference to the home directory which is a string. Then backup_dest is a reference to the variable self.__backup_dest. But that second reference seems to be recognised as a NoneType ?? I'm using optparse in my script (that code for checking for permission is a part of my backup script). Maybe i post my complete code: " #!/usr/bin/env python #-*- coding: utf-8 -*- #MyBackUper import os, sys, tarfile import datetime from optparse import OptionParser class Except(Exception): pass class Packer(Except): def __init__(self): self.__backup_dest = os.getenv('HOME') __current_time = datetime.datetime.today().strftime('%Y-%m-%d %H:%M:%S') Except.__init__(self) def doc_note(self): print """ DOCUMENTATION 'Backuper' is a script for doing backups. You can backup with it single files or whole directories. For available commands type 'backuper.py -h' or 'backuper.py --help'. Using it is simple: - to backup single file, type: 'backuper.py -f FILE_PATH BCKP_NAME [DEST_PATH]', where 'FILE_PATH' is exact path to prefered file which you want to backup and 'BCKP_NAME' is the name for backup output file. Default 'DEST_PATH' is placed in home directory, it can't be changed. 'BCKP_NAME' must be given; - to backup whole directory, type: 'backuper.py -d DIR_PATH BCKP_NAME [DEST_PATH]', where 'DIR_PATH' is exact path to prefered directory, which you want to backup and 'BCKP_NAME' is the name for backup output file. Default 'DEST_PATH' is placed in home directory, it can't be changed. 'BCKP_NAME' must be given; """ def __check_set_perm(self, rd_obj_path, backup_dest): try: if os.path.exists(rd_obj_path): if not os.access(rd_obj_path, os.R_OK): print "Have no permissions on [%s] for reading operation.\nTrying to set them..." % os.path.split(rd_obj_path)[1] if not os.path.isdir(rd_obj_path): os.chmod(rd_obj_path, stat.S_IREAD) else: for root, dirs, files in os.walk(rd_obj_path): for f in files: os.chmod(os.path.join(root, f), stat.S_IREAD) print "Get permissions for reading on [%s] successfully." % os.path.split(rd_obj_path)[1] else: print "Have permissions on [%s] for reading." % os.path.split(rd_obj_path)[1] if not os.access(backup_dest, os.W_OK): print "Have no permissions on [%s] for writing operation.\nTrying to set them..." % os.path.split(backup_dest)[1] os.chmod(backup_dest, stat.S_IWRITE) print "Get permissions for reading on [%s] successfully." % os.path.split(backup_dest)[1] else: print "Have permissions on [%s] for writing." % os.path.split(backup_dest)[1] else: return "Can't find specified path - [%s]." % rd_obj_path sys.exit(1) except (Except), ex: return ex def backup_file(self, rd_obj_path, bkp_obj_name): try: if os.name == "nt": rd_obj_path = rd_obj_path.replace('~/', '%s\\' % os.getenv('HOME')).replace('\\', '\\\\') backup_dest = self.__backup_dest print "Checking permissions for reading and writing..." self.__check_set_perm(rd_obj_path, backup_dest) backup_obj = tarfile.open("%s\\%s(%s).tar.bz2" % (backup_dest, bkp_obj_name, __current_time), 'w:bz2') else: rd_obj_path = rd_obj_path.replace('~/', '%s/' % os.getenv('HOME')) backup_dest = self.__backup_dest print "Checking permissions for reading and writing..." self.__check_set_perm(rd_obj_path, backup_dest) backup_obj = tarfile.open("%s/%s(%s).tar.bz2" % (backup_dest, bkp_obj_name, __current_time), 'w:bz2') print "Preparing for backup [%s]..." % os.path.split(rd_obj_path)[1] print "Starting backup..." read_obj = open(rd_obj_path, 'rb') print "Now adding [%s]..." % os.path.split(rd_obj_path)[1] backup_obj.add(read_obj.read()) read_obj.close(), backup_obj.close() print "Backup [%s] made successfully. :-)" % os.path.split(backup_dest)[1] except (Except), ex: return ex def backup_dir(self, rd_obj_path, bkp_obj_name): try: if os.name == "nt": rd_obj_path = rd_obj_path.replace('~/', '%s\\' % os.getenv('HOME')).replace('\\', '\\\\') backup_dest = self.__backup_dest print "Checking permissions for reading and writing..." self.__check_set_perm(rd_obj_path, backup_dest) backup_obj = tarfile.open("%s\\%s(%s).tar.bz2" % (backup_dest, bkp_obj_name, __current_time), 'w:bz2') else: rd_obj_path = rd_obj_path.replace('~/', '%s/' % os.getenv('HOME')) backup_dest = self.__backup_dest print "Checking permissions for reading and writing..." self.__check_set_perm(rd_obj_path, backup_dest) backup_obj = tarfile.open("%s/%s(%s).tar.bz2" % (backup_dest, bkp_obj_name, __current_time), 'w:bz2') print "Preparing for backup '%s'..." % os.path.split(rd_obj_path)[1] print "Gathering files for backup..." path_list = [] for root, dirs, files in os.walk(rd_obj_path): for f in files: path_list.append(os.path.join(root, f)) print "Starting backup..." for p in path_list: fl = open(p, 'rb') print "Now adding [%s] from [%s] directory" % (os.path.split(p)[1], os.path.split(p)[0]) backup_obj.add(fl.read()) fl.close() print "Added [%s] successfully" % os.path.split(p)[1] backup_obj.close() print "Backup [%s] made successfully. :-)" % os.path.split(backup_dest)[1] except (Except), ex: return ex class ParseIt(object): def __init__(self): self.__initial = True _usage = "usage: %prog [options] Arg1 Arg2" parser = OptionParser(_usage) parser.add_option("-f", "--file", action="store", type="string", dest="filename", help="Make backup of a single file", metavar="FILE_PATH CKP_NAME", nargs=2) parser.add_option("-d", "--dir", action="store", type="string", dest="dirname", help="Recursively backup a whole directory", metavar="DIR_PATH BCKP_NAME", nargs=2) parser.add_option("-i", "--info", dest="info_note", action="store_true", help="Show script's documentation") (options, args) = parser.parse_args() def main_meth(): paq = Packer() pars = ParseIt() if pars.options.filename: paq.backup_file(pars.options.filename[0], pars.options.filename[1]) elif pars.options.dirname: paq.backup_dir(pars.options.dirname[0], pars.options.dirname[1]) elif pars.options.info_note: paq.doc_note() if __name__ == "__main__": main_meth() " From davea at ieee.org Sat Aug 22 11:15:32 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 22 Aug 2009 11:15:32 -0400 Subject: debugger In-Reply-To: <4A8FF563.5070003@gmail.com> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> <1250940857.28537.0.camel@centar.nbk> <4A8FF563.5070003@gmail.com> Message-ID: <4A900B94.6060607@ieee.org> Stef Mientki wrote: >
Albert > Hopkins wrote: >> On Sat, 2009-08-22 at 01:17 -0700, flagmino wrote: >> [...] >> >>> I am trying to debug: >>> I press shift-F9 and F7. I end up in the interpreter where I enter s2 >>> (1, 2). >>> >>> >From that point if I press F7, the program restart all over. >>> If I press Enter, the program gets out of debug mode. >>> >> >> Umm.. which debugger is that? My debugger doesn't have shift-F9... >> > then you probably not working under windows ... > > Stef > >
> That doesn't help. If you want help, describe the environment. Python version, OS, and what command you did to start this "debugger." Or at least its name. The Windows debugger is called Debug.exe, and it doesn't accept Shift-F9. But I doubt the OP was talking about that one. Komodo doesn't seem to do anything with Shift-F9 either. PythonWin doesn't seem to, nor does Idle. Most of these could be customized, but that's besides the point. In version: 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)], running under XPsp3, with win32 extensions loaded, there are a bunch of files called debug or debugger. Which one might be meant here? Or perhaps the debugger was part of NetBeans, or Eclipse, or some other IDE? DaveA From nitebirdz at sacredchaos.com Sat Aug 22 11:25:16 2009 From: nitebirdz at sacredchaos.com (Nitebirdz) Date: Sat, 22 Aug 2009 17:25:16 +0200 Subject: Blank Line at Program Exit In-Reply-To: References: Message-ID: <20090822152515.GC10584@sevilla.sacredchaos.com> On Thu, Aug 20, 2009 at 01:31:14PM +0800, Steven Woody wrote: > Hi, > Any python program, even that does absolutely nothing in the code, will > cause a blank line printed out when the program exit. What's the reason? > Thanks. > Chances are it is related to whichever operating system and/or shell you are using. For instance, this is taken from a system running Ubuntu Linux 8.04: ------------------------------------------------- laptop:$ cat hello.py #!/usr/bin/env python print "Hello, there!" laptop:$ ./hello.py Hello, there! laptop:$ cat nothing.py #!/usr/bin/env python laptop:$ ./nothing.py laptop:$ ------------------------------------------------- As you can see, no blank line was printed out. From python at mrabarnett.plus.com Sat Aug 22 11:49:30 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 22 Aug 2009 16:49:30 +0100 Subject: debugger In-Reply-To: <4A900B94.6060607@ieee.org> References: <71854089-ba76-40c8-8a81-e224711cf7c0@i8g2000pro.googlegroups.com> <1250940857.28537.0.camel@centar.nbk> <4A8FF563.5070003@gmail.com> <4A900B94.6060607@ieee.org> Message-ID: <4A90138A.4000905@mrabarnett.plus.com> Dave Angel wrote: > Stef Mientki wrote: >>
Albert >> Hopkins wrote: >>> On Sat, 2009-08-22 at 01:17 -0700, flagmino wrote: >>> [...] >>> >>>> I am trying to debug: >>>> I press shift-F9 and F7. I end up in the interpreter where I enter s2 >>>> (1, 2). >>>> >>>> >From that point if I press F7, the program restart all over. >>>> If I press Enter, the program gets out of debug mode. >>>> >>> >>> Umm.. which debugger is that? My debugger doesn't have shift-F9... >>> >> then you probably not working under windows ... >> >> Stef >> >>
>> > That doesn't help. If you want help, describe the environment. Python > version, OS, and what command you did to start this "debugger." Or at > least its name. > > The Windows debugger is called Debug.exe, and it doesn't accept > Shift-F9. But I doubt the OP was talking about that one. Komodo > doesn't seem to do anything with Shift-F9 either. > > PythonWin doesn't seem to, nor does Idle. Most of these could be > customized, but that's besides the point. > > In version: 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 > bit (Intel)], running under XPsp3, with win32 extensions loaded, there > are a bunch of files called debug or debugger. Which one might be meant > here? > > Or perhaps the debugger was part of NetBeans, or Eclipse, or some other > IDE? > It might be winpdb, although I haven't been able to confirm it. From davea at ieee.org Sat Aug 22 13:36:12 2009 From: davea at ieee.org (Dave Angel) Date: Sat, 22 Aug 2009 13:36:12 -0400 Subject: TypeError while checking for permissions with os.access() on windows xp In-Reply-To: <4A900819.8010702@gmail.com> References: <4A900819.8010702@gmail.com> Message-ID: <4A902C8C.4070108@ieee.org> ryniek90 wrote: >
>> First, some nitpicking: Include the whole traceback when posting about >> errors please. Don't write "if some_boolean_expression != True:" >> instead prefer "if not some_boolean_expression:". Also, in your code >> "except (Except), ex: return ex" the parentheses are redundant, >> there's no "Except" Exception (unless you created one yourself) and >> why are you catching and returning the Exception object? (Also, >> what's that "sys.exit(0)" doing in there? And why exit with 0 if there >> was a problem? Exit code 0 means "no problem".) >> >> >> Second, from what you've said backup_dest must be None: >> >> >>>>> import os >>>>> os.access(None, os.W_OK) >>>>> >> >> Traceback (most recent call last): >> File "", line 1, in >> os.access(None, os.W_OK) >> TypeError: coercing to Unicode: need string or buffer, NoneType found >> >> > > No, backup_dest is destination for backup. It's this variable: > *backup_dest = self.__backup_dest* . > *self.__backup_dest = os.getenv('HOME')* - as you can see, > self.__backup_dest is a reference to the home directory which is a > string. Then backup_dest is a reference to the variable > self.__backup_dest. But that second reference seems to be recognised > as a NoneType ?? > > I'm using optparse in my script (that code for checking for permission > is a part of my backup script). > > Maybe i post my complete code: > " > #!/usr/bin/env python > #-*- coding: utf-8 -*- > #MyBackUper > > import os, sys, tarfile > import datetime > from optparse import OptionParser > > > class Except(Exception): > pass > > > class Packer(Except): > > def __init__(self): > self.__backup_dest = os.getenv('HOME') > __current_time = datetime.datetime.today().strftime('%Y-%m-%d > %H:%M:%S') > Except.__init__(self) > > def doc_note(self): > > print """ > > DOCUMENTATION > > 'Backuper' is a script for doing backups. > You can backup with it single files or whole directories. > For available commands type 'backuper.py -h' or 'backuper.py > --help'. > > Using it is simple: > > - to backup single file, type: > 'backuper.py -f FILE_PATH BCKP_NAME [DEST_PATH]', > where 'FILE_PATH' is exact path to prefered file which you want > to backup and 'BCKP_NAME' is the name for backup output file. Default > 'DEST_PATH' is placed in home directory, it can't be changed. > 'BCKP_NAME' must be given; > > - to backup whole directory, type: > 'backuper.py -d DIR_PATH BCKP_NAME [DEST_PATH]', where > 'DIR_PATH' is exact path to prefered directory, which you want to > backup and 'BCKP_NAME' is the name for backup output file. Default > 'DEST_PATH' is placed in home directory, it can't be changed. > 'BCKP_NAME' must be given; > > """ > > def __check_set_perm(self, rd_obj_path, backup_dest): > > try: > > if os.path.exists(rd_obj_path): > if not os.access(rd_obj_path, os.R_OK): > print "Have no permissions on [%s] for reading > operation.\nTrying to set them..." % os.path.split(rd_obj_path)[1] > if not os.path.isdir(rd_obj_path): > os.chmod(rd_obj_path, stat.S_IREAD) > else: > for root, dirs, files in os.walk(rd_obj_path): > for f in files: > os.chmod(os.path.join(root, f), > stat.S_IREAD) > print "Get permissions for reading on [%s] > successfully." % os.path.split(rd_obj_path)[1] > else: > print "Have permissions on [%s] for reading." % > os.path.split(rd_obj_path)[1] > > if not os.access(backup_dest, os.W_OK): > print "Have no permissions on [%s] for writing > operation.\nTrying to set them..." % os.path.split(backup_dest)[1] > os.chmod(backup_dest, stat.S_IWRITE) > print "Get permissions for reading on [%s] > successfully." % os.path.split(backup_dest)[1] > else: > print "Have permissions on [%s] for writing." % > os.path.split(backup_dest)[1] > else: > return "Can't find specified path - [%s]." % rd_obj_path > sys.exit(1) > > except (Except), ex: > return ex > > > def backup_file(self, rd_obj_path, bkp_obj_name): > > try: > > if os.name == "nt": > rd_obj_path = rd_obj_path.replace('~/', '%s\\' % > os.getenv('HOME')).replace('\\', '\\\\') > backup_dest = self.__backup_dest > print "Checking permissions for reading and writing..." > self.__check_set_perm(rd_obj_path, backup_dest) > backup_obj = tarfile.open("%s\\%s(%s).tar.bz2" % > (backup_dest, bkp_obj_name, __current_time), 'w:bz2') > > else: > rd_obj_path = rd_obj_path.replace('~/', '%s/' % > os.getenv('HOME')) > backup_dest = self.__backup_dest > print "Checking permissions for reading and writing..." > self.__check_set_perm(rd_obj_path, backup_dest) > backup_obj = tarfile.open("%s/%s(%s).tar.bz2" % > (backup_dest, bkp_obj_name, __current_time), 'w:bz2') > > print "Preparing for backup [%s]..." % > os.path.split(rd_obj_path)[1] > print "Starting backup..." > read_obj = open(rd_obj_path, 'rb') > print "Now adding [%s]..." % os.path.split(rd_obj_path)[1] > backup_obj.add(read_obj.read()) > read_obj.close(), backup_obj.close() > print "Backup [%s] made successfully. :-)" % > os.path.split(backup_dest)[1] > > except (Except), ex: > return ex > > def backup_dir(self, rd_obj_path, bkp_obj_name): > > try: > > if os.name == "nt": > rd_obj_path = rd_obj_path.replace('~/', '%s\\' % > os.getenv('HOME')).replace('\\', '\\\\') > backup_dest = self.__backup_dest > print "Checking permissions for reading and writing..." > self.__check_set_perm(rd_obj_path, backup_dest) > backup_obj = tarfile.open("%s\\%s(%s).tar.bz2" % > (backup_dest, bkp_obj_name, __current_time), 'w:bz2') > > else: > rd_obj_path = rd_obj_path.replace('~/', '%s/' % > os.getenv('HOME')) > backup_dest = self.__backup_dest > print "Checking permissions for reading and writing..." > self.__check_set_perm(rd_obj_path, backup_dest) > backup_obj = tarfile.open("%s/%s(%s).tar.bz2" % > (backup_dest, bkp_obj_name, __current_time), 'w:bz2') > > print "Preparing for backup '%s'..." % > os.path.split(rd_obj_path)[1] > print "Gathering files for backup..." > path_list = [] > for root, dirs, files in os.walk(rd_obj_path): > for f in files: > path_list.append(os.path.join(root, f)) > print "Starting backup..." > for p in path_list: > fl = open(p, 'rb') > print "Now adding [%s] from [%s] directory" % > (os.path.split(p)[1], os.path.split(p)[0]) > backup_obj.add(fl.read()) > fl.close() > print "Added [%s] successfully" % os.path.split(p)[1] > backup_obj.close() > print "Backup [%s] made successfully. :-)" % > os.path.split(backup_dest)[1] > > except (Except), ex: > return ex > > > class ParseIt(object): > > def __init__(self): > self.__initial = True > > _usage = "usage: %prog [options] Arg1 Arg2" > parser = OptionParser(_usage) > parser.add_option("-f", "--file", action="store", type="string", > dest="filename", help="Make backup of a single file", > metavar="FILE_PATH CKP_NAME", nargs=2) > parser.add_option("-d", "--dir", action="store", type="string", > dest="dirname", help="Recursively backup a whole directory", > metavar="DIR_PATH BCKP_NAME", nargs=2) > parser.add_option("-i", "--info", dest="info_note", > action="store_true", help="Show script's documentation") > > (options, args) = parser.parse_args() > > def main_meth(): > paq = Packer() > pars = ParseIt() > if pars.options.filename: > paq.backup_file(pars.options.filename[0], > pars.options.filename[1]) > elif pars.options.dirname: > paq.backup_dir(pars.options.dirname[0], pars.options.dirname[1]) > elif pars.options.info_note: > paq.doc_note() > > > if __name__ == "__main__": > main_meth() > > " > > > >
> I don't know why you didn't immediately add a print statement just before the failing os.access(), once you saw the error message. You could have printed out both the formal parameter and the instance attribute. Simple explanation: you probably don't have an environment variable named "HOME". I don't either, on Windows. You need to test for that, and put some error handling, so the lack of an environment variable won't crash your program. > Then backup_dest is a reference to the variable self.__backup_dest. But that second reference seems to be recognised as a NoneType ?? backup_dest is a local variable which is a reference to whatever object self.__backup_dest referenced. That could be a very different thing. But in this case the subtlety isn't important -- they're both referencing None, which is the object returned by os.getenv() when the requested environment variable doesn't exist. DaveA From kee at kagi.com Sat Aug 22 13:46:51 2009 From: kee at kagi.com (Kee Nethery) Date: Sat, 22 Aug 2009 10:46:51 -0700 Subject: string literal vs string variable In-Reply-To: <4a8fc954$0$31331$9b4e6d93@newsspool4.arcor-online.net> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8fc954$0$31331$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On Aug 22, 2009, at 3:32 AM, Stefan Behnel wrote: > > You can use both, but I suspect parsing from StringIO to be slower > than > parsing from the string directly. That's the case for lxml, at least. > > Note that fromstring() behaves the same as XML(), but it reads > better when > parsing from a string variable. XML() reads better when parsing from a > literal string. I'm not sure I know the difference between a string variable and a literal string. Is the difference as simple as: somestring = u'hello world' fromstring(somestring) <-- string variable vs XML(u'hello world') <-- literal string Kee From gnuist006 at gmail.com Sat Aug 22 14:11:32 2009 From: gnuist006 at gmail.com (bolega) Date: Sat, 22 Aug 2009 11:11:32 -0700 (PDT) Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? Message-ID: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? I really prefer a sed one liner. Example Input : This is my book. It is too thick to read. The author gets little royalty but the publisher makes a lot. Output: This_is_my_book._It_is_too__thick_to read. The author gets little royalty but the publisher makes a lot. We replaced all the spaces with underscores before the first occurence of the string "to ". Thanks Gnuist From carlosfabianramirez at gmail.com Sat Aug 22 14:12:50 2009 From: carlosfabianramirez at gmail.com (Carlos Fabian Ramirez) Date: Sat, 22 Aug 2009 14:12:50 -0400 Subject: Urllib2 not working Message-ID: <51303220908221112w79ccb746i900c22d45fff07c7@mail.gmail.com> Hello, When I try to open a URL using urllib2.urlopen it returns Name or service not known. It is not a problem with my Internet I believe, since I have Internet access on my computer, and I have verified it is not a syntax, or spelling, error on my part. I have also tried accessing the site (google.com) by IP like so: urllib2.urlopen('http://74.125.67.100/') but this does not work either. This is a traceback of an attempt to access it through its URL ( http://www.google.com/) http://dpaste.com/84016/ Any help would be very appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From w_a_x_man at yahoo.com Sat Aug 22 14:24:56 2009 From: w_a_x_man at yahoo.com (w_a_x_man) Date: Sat, 22 Aug 2009 11:24:56 -0700 (PDT) Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> Message-ID: <1bc82397-1e91-4055-879a-c178534e1c17@z24g2000yqb.googlegroups.com> On Aug 22, 1:11?pm, bolega wrote: > sed/awk/perl: > > How to replace all spaces each with an underscore that occur before a > specific string ? > > I really prefer a sed one liner. > > Example > Input : ?This is my book. It is too ?thick to read. The author gets > little royalty but the publisher makes a lot. > Output: This_is_my_book._It_is_too__thick_to read. The author gets > little royalty but the publisher makes a lot. > > We replaced all the spaces with underscores before the first occurence > of the string "to ". > > Thanks > Gnuist awk 'BEGIN{FS=OFS="to "}{gsub(/ /,"_",$1);print}' myfile From MacRules at nome.com Sat Aug 22 14:25:25 2009 From: MacRules at nome.com (MacRules) Date: Sat, 22 Aug 2009 14:25:25 -0400 Subject: Python - insert image / pdf / blob files to MySQL, MSSQL Message-ID: <4a903814$0$10311$607ed4bc@cv.net> Where to find code examples? Or someone can post sample codes here. Thanks From code at pizzashack.org Sat Aug 22 15:04:17 2009 From: code at pizzashack.org (Derek Martin) Date: Sat, 22 Aug 2009 14:04:17 -0500 Subject: Annoying octal notation In-Reply-To: <87d46ok948.fsf@benfinney.id.au> References: <87d46ok948.fsf@benfinney.id.au> Message-ID: <20090822190417.GW20434@dragontoe.org> On Sat, Aug 22, 2009 at 10:03:35AM +1000, Ben Finney wrote: > > and the former is virtually indistinguishable from 00012, O0012, or > > many other combinations that someone might accidentally type (or > > intentionally type, having to do this in dozens of other programming > > languages). > > Only if you type the letter in uppercase. The lower-case ?o? is much > easier to distinguish. It is easier, but I dispute that it is much easier. > Whether or not you find ?0o012? easily distinguishable as a non-decimal > notation, it's undoubtedly easier to distinguish than ?012?. 012 has meant decimal 10 in octal to me for so long, from its use in MANY other programming languages, that I disagree completely. > > I can see how 012 can be confusing to new programmers, but at least > > it's legible, and the great thing about humans is that they can be > > taught (usually). I for one think this change is completely misguided. > > These human programmers, whether newbies or long-experienced, also deal > with decimal numbers every day, many of which are presented as a > sequence of digits with leading zeros ? and we continue to think of them > as decimal numbers regardless. Having the language syntax opposed to > that is ...consistent with virtually every other popular programming language. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ryniek90 at gmail.com Sat Aug 22 15:16:11 2009 From: ryniek90 at gmail.com (ryniek90) Date: Sat, 22 Aug 2009 21:16:11 +0200 Subject: TypeError while checking for permissions with os.access() on windows xp In-Reply-To: References: Message-ID: <4A9043FB.7070108@gmail.com> > >>> First, some nitpicking: Include the whole traceback when posting about >>> errors please. Don't write "if some_boolean_expression != True:" >>> instead prefer "if not some_boolean_expression:". Also, in your code >>> "except (Except), ex: return ex" the parentheses are redundant, >>> there's no "Except" Exception (unless you created one yourself) and >>> why are you catching and returning the Exception object? (Also, >>> what's that "sys.exit(0)" doing in there? And why exit with 0 if there >>> was a problem? Exit code 0 means "no problem".) >>> >>> >>> Second, from what you've said backup_dest must be None: >>> >>> >>>>>> import os >>>>>> os.access(None, os.W_OK) >>>>>> >>> >>> Traceback (most recent call last): >>> File "", line 1, in >>> os.access(None, os.W_OK) >>> TypeError: coercing to Unicode: need string or buffer, NoneType found >>> >>> >> >> No, backup_dest is destination for backup. It's this variable: >> *backup_dest = self.__backup_dest* . >> *self.__backup_dest = os.getenv('HOME')* - as you can see, >> self.__backup_dest is a reference to the home directory which is a >> string. Then backup_dest is a reference to the variable >> self.__backup_dest. But that second reference seems to be recognised >> as a NoneType ?? >> >> I'm using optparse in my script (that code for checking for >> permission is a part of my backup script). >> >> Maybe i post my complete code: >> " >> #!/usr/bin/env python >> #-*- coding: utf-8 -*- >> #MyBackUper >> >> import os, sys, tarfile >> import datetime >> from optparse import OptionParser >> >> >> class Except(Exception): >> pass >> >> >> class Packer(Except): >> >> def __init__(self): >> self.__backup_dest = os.getenv('HOME') >> __current_time = datetime.datetime.today().strftime('%Y-%m-%d >> %H:%M:%S') >> Except.__init__(self) >> >> def doc_note(self): >> >> print """ >> >> DOCUMENTATION >> >> 'Backuper' is a script for doing backups. >> You can backup with it single files or whole directories. >> For available commands type 'backuper.py -h' or 'backuper.py >> --help'. >> >> Using it is simple: >> >> - to backup single file, type: >> 'backuper.py -f FILE_PATH BCKP_NAME [DEST_PATH]', >> where 'FILE_PATH' is exact path to prefered file which you >> want to backup and 'BCKP_NAME' is the name for backup output file. >> Default 'DEST_PATH' is placed in home directory, it can't be changed. >> 'BCKP_NAME' must be given; >> >> - to backup whole directory, type: >> 'backuper.py -d DIR_PATH BCKP_NAME [DEST_PATH]', where >> 'DIR_PATH' is exact path to prefered directory, which you want to >> backup and 'BCKP_NAME' is the name for backup output file. Default >> 'DEST_PATH' is placed in home directory, it can't be changed. >> 'BCKP_NAME' must be given; >> >> """ >> >> def __check_set_perm(self, rd_obj_path, backup_dest): >> >> try: >> >> if os.path.exists(rd_obj_path): >> if not os.access(rd_obj_path, os.R_OK): >> print "Have no permissions on [%s] for reading >> operation.\nTrying to set them..." % os.path.split(rd_obj_path)[1] >> if not os.path.isdir(rd_obj_path): >> os.chmod(rd_obj_path, stat.S_IREAD) >> else: >> for root, dirs, files in os.walk(rd_obj_path): >> for f in files: >> os.chmod(os.path.join(root, f), >> stat.S_IREAD) >> print "Get permissions for reading on [%s] >> successfully." % os.path.split(rd_obj_path)[1] >> else: >> print "Have permissions on [%s] for reading." % >> os.path.split(rd_obj_path)[1] >> >> if not os.access(backup_dest, os.W_OK): >> print "Have no permissions on [%s] for writing >> operation.\nTrying to set them..." % os.path.split(backup_dest)[1] >> os.chmod(backup_dest, stat.S_IWRITE) >> print "Get permissions for reading on [%s] >> successfully." % os.path.split(backup_dest)[1] >> else: >> print "Have permissions on [%s] for writing." % >> os.path.split(backup_dest)[1] >> else: >> return "Can't find specified path - [%s]." % rd_obj_path >> sys.exit(1) >> >> except (Except), ex: >> return ex >> >> >> def backup_file(self, rd_obj_path, bkp_obj_name): >> >> try: >> >> if os.name == "nt": >> rd_obj_path = rd_obj_path.replace('~/', '%s\\' % >> os.getenv('HOME')).replace('\\', '\\\\') >> backup_dest = self.__backup_dest >> print "Checking permissions for reading and writing..." >> self.__check_set_perm(rd_obj_path, backup_dest) >> backup_obj = tarfile.open("%s\\%s(%s).tar.bz2" % >> (backup_dest, bkp_obj_name, __current_time), 'w:bz2') >> >> else: >> rd_obj_path = rd_obj_path.replace('~/', '%s/' % >> os.getenv('HOME')) >> backup_dest = self.__backup_dest >> print "Checking permissions for reading and writing..." >> self.__check_set_perm(rd_obj_path, backup_dest) >> backup_obj = tarfile.open("%s/%s(%s).tar.bz2" % >> (backup_dest, bkp_obj_name, __current_time), 'w:bz2') >> >> print "Preparing for backup [%s]..." % >> os.path.split(rd_obj_path)[1] >> print "Starting backup..." >> read_obj = open(rd_obj_path, 'rb') >> print "Now adding [%s]..." % os.path.split(rd_obj_path)[1] >> backup_obj.add(read_obj.read()) >> read_obj.close(), backup_obj.close() >> print "Backup [%s] made successfully. :-)" % >> os.path.split(backup_dest)[1] >> >> except (Except), ex: >> return ex >> >> def backup_dir(self, rd_obj_path, bkp_obj_name): >> >> try: >> >> if os.name == "nt": >> rd_obj_path = rd_obj_path.replace('~/', '%s\\' % >> os.getenv('HOME')).replace('\\', '\\\\') >> backup_dest = self.__backup_dest >> print "Checking permissions for reading and writing..." >> self.__check_set_perm(rd_obj_path, backup_dest) >> backup_obj = tarfile.open("%s\\%s(%s).tar.bz2" % >> (backup_dest, bkp_obj_name, __current_time), 'w:bz2') >> >> else: >> rd_obj_path = rd_obj_path.replace('~/', '%s/' % >> os.getenv('HOME')) >> backup_dest = self.__backup_dest >> print "Checking permissions for reading and writing..." >> self.__check_set_perm(rd_obj_path, backup_dest) >> backup_obj = tarfile.open("%s/%s(%s).tar.bz2" % >> (backup_dest, bkp_obj_name, __current_time), 'w:bz2') >> >> print "Preparing for backup '%s'..." % >> os.path.split(rd_obj_path)[1] >> print "Gathering files for backup..." >> path_list = [] >> for root, dirs, files in os.walk(rd_obj_path): >> for f in files: >> path_list.append(os.path.join(root, f)) >> print "Starting backup..." >> for p in path_list: >> fl = open(p, 'rb') >> print "Now adding [%s] from [%s] directory" % >> (os.path.split(p)[1], os.path.split(p)[0]) >> backup_obj.add(fl.read()) >> fl.close() >> print "Added [%s] successfully" % os.path.split(p)[1] >> backup_obj.close() >> print "Backup [%s] made successfully. :-)" % >> os.path.split(backup_dest)[1] >> >> except (Except), ex: >> return ex >> >> >> class ParseIt(object): >> >> def __init__(self): >> self.__initial = True >> >> _usage = "usage: %prog [options] Arg1 Arg2" >> parser = OptionParser(_usage) >> parser.add_option("-f", "--file", action="store", type="string", >> dest="filename", help="Make backup of a single file", >> metavar="FILE_PATH CKP_NAME", nargs=2) >> parser.add_option("-d", "--dir", action="store", type="string", >> dest="dirname", help="Recursively backup a whole directory", >> metavar="DIR_PATH BCKP_NAME", nargs=2) >> parser.add_option("-i", "--info", dest="info_note", >> action="store_true", help="Show script's documentation") >> >> (options, args) = parser.parse_args() >> >> def main_meth(): >> paq = Packer() >> pars = ParseIt() >> if pars.options.filename: >> paq.backup_file(pars.options.filename[0], >> pars.options.filename[1]) >> elif pars.options.dirname: >> paq.backup_dir(pars.options.dirname[0], pars.options.dirname[1]) >> elif pars.options.info_note: >> paq.doc_note() >> >> >> if __name__ == "__main__": >> main_meth() >> >> " >> >> >> >>
>> > I don't know why you didn't immediately add a print statement just > before the failing os.access(), once you saw the error message. You > could have printed out both the formal parameter and the instance > attribute. > > Simple explanation: you probably don't have an environment variable > named "HOME". I don't either, on Windows. You need to test for that, > and put some error handling, so the lack of an environment variable > won't crash your program. > > > Then backup_dest is a reference to the variable self.__backup_dest. > But that second reference seems to be recognised as a NoneType ?? > > backup_dest is a local variable which is a reference to whatever > object self.__backup_dest referenced. That could be a very different > thing. But in this case the subtlety isn't important -- they're both > referencing None, which is the object returned by os.getenv() when the > requested environment variable doesn't exist. > > DaveA Yes, You have right Dave. This reference don't exist in windows's cmd.exe, but in IDLE does. Check this out: " Microsoft Windows XP [Wersja 5.1.2600] (C) Copyright 1985-2001 Microsoft Corp. C:\Documents and Settings\Adrian-Admin>python ActivePython 2.6.2.2 (ActiveState Software Inc.) based on Python 2.6.2 (r262:71600, Apr 21 2009, 15:05:37) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.getenv('HOME') >>> print os.getenv('HOME') None >>> " And now output from IDLE: " Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [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.4 >>> import os >>> os.getenv('HOME') 'C:\\Documents and Settings\\Adrian-Admin' >>> " WTF?? Why on IDLE it works, but when i run this script in cmd.exe, the os.getenv('HOME') goes NoneType? I'm to newbie yet to understand this :/ That's the example with Traceback: " C:\Documents and Settings\Adrian-Admin\Moje dokumenty\My Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python backuper.py -f E:\ISO\archlinux-2009.02-core-i686.img ArchLinBackup Checking permissions for reading and writing... Have permissions on [archlinux-2009.02-core-i686.img] for reading. Traceback (most recent call last): File "backuper.py", line 200, in main_meth() File "backuper.py", line 190, in main_meth paq.backup_file(pars.options.filename[0], pars.options.filename[1]) File "backuper.py", line 111, in backup_file self.__check_set_perm(rd_obj_path, self._backup_dest) File "backuper.py", line 90, in __check_set_perm if not os.access(self._backup_dest, os.W_OK): TypeError: coercing to Unicode: need string or buffer, NoneType found C:\Documents and Settings\Adrian-Admin\Moje dokumenty\My Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty> " So....it's cmd.exe fault? From sajmikins at gmail.com Sat Aug 22 15:27:52 2009 From: sajmikins at gmail.com (Simon Forman) Date: Sat, 22 Aug 2009 15:27:52 -0400 Subject: Urllib2 not working In-Reply-To: <51303220908221112w79ccb746i900c22d45fff07c7@mail.gmail.com> References: <51303220908221112w79ccb746i900c22d45fff07c7@mail.gmail.com> Message-ID: <50f98a4c0908221227k4cfe3387t205c91ba20d5e514@mail.gmail.com> On Sat, Aug 22, 2009 at 2:12 PM, Carlos Fabian Ramirez wrote: > Hello, > When I try to open a URL using urllib2.urlopen it returns Name or service > not known. It is not a problem with my Internet I believe, since I have > Internet access on my computer, and I have verified it is not a syntax, or > spelling, error on my part. I have also tried accessing the site > (google.com) by IP like so: > urllib2.urlopen('http://74.125.67.100/') > but this does not work either. > This is a traceback of an attempt to access it through its URL > (http://www.google.com/) > http://dpaste.com/84016/ > Any help would be very appreciated. > Try googling the error message "Name or service not known" and urllib2. HTH From apt.shansen at gmail.com Sat Aug 22 15:30:16 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sat, 22 Aug 2009 12:30:16 -0700 Subject: TypeError while checking for permissions with os.access() on windows xp In-Reply-To: <4A9043FB.7070108@gmail.com> References: <4A9043FB.7070108@gmail.com> Message-ID: <7a9c25c20908221230p673bffdane36b67482ab4621f@mail.gmail.com> > > > WTF?? > Why on IDLE it works, but when i run this script in cmd.exe, the > os.getenv('HOME') goes NoneType? > I'm to newbie yet to understand this :/ > HOME is simply not a standard environment variable that Windows provides. Any program can set/add environment variables as it deems fit; in this case it seems IDLE is setting one, but you can't rely on it outside of IDLE. If you do os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] it may be what you want. Start up cmd.exe, type 'set' -- that's the default/standard environment variables you have to work with. That's it. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From jurajg at gmail.com Sat Aug 22 15:49:52 2009 From: jurajg at gmail.com (Juraj G.) Date: Sat, 22 Aug 2009 21:49:52 +0200 Subject: difference between raw_input() and input() In-Reply-To: <029d53bb$0$25987$c3e8da3@news.astraweb.com> References: <3c91915d-bcb1-4ea9-9b37-6b30ea0588a0@e34g2000vbm.googlegroups.com> <029d53bb$0$25987$c3e8da3@news.astraweb.com> Message-ID: <3cdfc0a80908221249t7b7042b8reab3b0202ef3b2a3@mail.gmail.com> if you prefix number with zero, it will turn into octal number... I too wasn't aware of it... at least in python :/ http://en.wikipedia.org/wiki/Octal It seems like bad practice to put zeroes before any decimal number in any language :) Juraj From python.list at tim.thechases.com Sat Aug 22 15:49:55 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 22 Aug 2009 14:49:55 -0500 Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? In-Reply-To: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> Message-ID: <4A904BE3.6030507@tim.thechases.com> bolega wrote: > sed/awk/perl: Better to post in the "sed" or "perl" mailing lists rather than a Python list. I saw an awk solution flew by. > How to replace all spaces each with an underscore that occur > before a specific string ? > > I really prefer a sed one liner. Here's a one-liner sed solution: sed '/to /{s//\n&/;h;s/.*\n//;x;s/\n.*//;s/ /_/g;G;s/\n//}' There's a reason I prefer Python for these sorts of things: readability! You win 5 free internets (as a stand-in for the "real life" you clearly don't have) if you can decipher that in under 20 seconds ;-) expecting-to-see-NO CARRIER-after-typing-that'ly yers, -tkc +++ATH0 From zuo at chopin.edu.pl Sat Aug 22 16:11:20 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 22 Aug 2009 22:11:20 +0200 Subject: Using 'apply' as a decorator, to define constants In-Reply-To: References: Message-ID: 21-08-2009 o 18:09:02 alex23 wrote: > Unfortunately, apply() has been removed as a built-in in 3.x. You can always implement it yourself :) def apply(function, args=(), keywords={}): return function(*args, **keywords) -- Jan Kaliszewski (zuo) From subhakolkata1234 at gmail.com Sat Aug 22 16:27:02 2009 From: subhakolkata1234 at gmail.com (SUBHABRATA BANERJEE) Date: Sun, 23 Aug 2009 01:57:02 +0530 Subject: Questions on XML In-Reply-To: References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> Message-ID: <97c638a50908221327ge57818ahc1bb4c9ad3eb186b@mail.gmail.com> Should I help you? If you answered my questions I am differing from your view I do not get any problem in processing Hindi or Bangla or any Indian language in Python it is perfectly fine. Best Regards, Subhabrata. On Sat, Aug 22, 2009 at 9:48 AM, Rami Chowdhury wrote: > > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I >> use Python to help me in this regard? >> > > I can say from experience that Python on Windows (at least, Python 2.5 on > 32-bit Vista) works perfectly well with UTF-8 files containing Bangla. I > have had trouble with working with the data in IDLE, however, which seems to > prefer ASCII by default. > > ------------- > Rami Chowdhury > "Never assume malice when stupidity will suffice." -- Hanlon's Razor > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > > > > > > On Aug 21, 2009, at 19:15 , joy99 wrote: > > Dear Group, >> >> I like to convert some simple strings of natural language to XML. May >> I use Python to do this? If any one can help me, on this. >> >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I >> use Python to help me in this regard? >> >> How can I learn good XML aspects of Python. If any one can kindly name >> me a book or URL. >> >> I am using Python2.6 on Windows XP with IDLE as GUI. >> >> Best Regards, >> Subhabrata. >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at cs.uu.nl Sat Aug 22 16:43:13 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 22 Aug 2009 22:43:13 +0200 Subject: string literal vs string variable References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8fc954$0$31331$9b4e6d93@newsspool4.arcor-online.net> Message-ID: >>>>> Kee Nethery (KN) wrote: >KN> On Aug 22, 2009, at 3:32 AM, Stefan Behnel wrote: >>> >>> You can use both, but I suspect parsing from StringIO to be slower than >>> parsing from the string directly. That's the case for lxml, at least. >>> >>> Note that fromstring() behaves the same as XML(), but it reads better >>> when >>> parsing from a string variable. XML() reads better when parsing from a >>> literal string. >KN> I'm not sure I know the difference between a string variable and a literal >KN> string. Is the difference as simple as: >KN> somestring = u'hello world' >KN> fromstring(somestring) <-- string variable >KN> vs >KN> XML(u'hello world') <-- literal string Yes. Stefan probably means `looks better for the human reader' when he says `reads better'. XML and fromstring are just different names for the same function. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From zuo at chopin.edu.pl Sat Aug 22 16:44:35 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 22 Aug 2009 22:44:35 +0200 Subject: Annoying octal notation In-Reply-To: <20090822190417.GW20434@dragontoe.org> References: <87d46ok948.fsf@benfinney.id.au> <20090822190417.GW20434@dragontoe.org> Message-ID: 22-08-2009 o 21:04:17 Derek Martin wrote: > On Sat, Aug 22, 2009 at 10:03:35AM +1000, Ben Finney wrote: >> These human programmers, whether newbies or long-experienced, also deal >> with decimal numbers every day, many of which are presented as a >> sequence of digits with leading zeros ? and we continue to think of them >> as decimal numbers regardless. Having the language syntax opposed to >> that is > ...consistent with virtually every other popular programming language. Probably not every other... Anyway -- being (as it was said) inconsistent with every-day-convention -- it'd be also inconsistent with *Python* conventions, i.e.: 0x <- hex prefix 0b <- bin prefix Cheers, *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Sat Aug 22 16:51:44 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 22 Aug 2009 22:51:44 +0200 Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? In-Reply-To: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> Message-ID: 22-08-2009 o 20:11:32 bolega wrote: > sed/awk/perl: > > How to replace all spaces each with an underscore that occur before a > specific string ? $ rm -rf /home/bolega ; python -c 'for i in xrange(1000): print "I will never crosspost senselessly."' ;~] -- Jan Kaliszewski (zuo) From subhakolkata1234 at gmail.com Sat Aug 22 16:53:16 2009 From: subhakolkata1234 at gmail.com (joy99) Date: Sat, 22 Aug 2009 13:53:16 -0700 (PDT) Subject: Questions on XML References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8f87db$0$30221$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <11b8af5c-de10-4583-979c-64109c8fe698@g1g2000pra.googlegroups.com> On Aug 22, 12:16?pm, Rami Chowdhury wrote: > > encoding declaration to the top of your source file if you use encoded > > literal strings in your code > > Any tips for how to set the encoding in IDLE? printing the Unicode ? > strings works -- trying to repr() the variable chokes with a ? > UnicodeDecodeError, and trying to enter the literals inside IDLE just ? > gets me '?' characters instead. > > (this is Python 2.5 + IDLE installed from the Python-2.5.msi on ? > python.org) > > ------------- > Rami Chowdhury > "Never assume malice when stupidity will suffice." -- Hanlon's Razor > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > > On Aug 21, 2009, at 22:53 , Stefan Behnel wrote: > > > > > Rami Chowdhury wrote: > >>> I am using primarily UTF-8 based strings, like Hindi or Bengali. ? > >>> Can I > >>> use Python to help me in this regard? > > >> I can say from experience that Python on Windows (at least, Python ? > >> 2.5 > >> on 32-bit Vista) works perfectly well with UTF-8 files containing > >> Bangla. I have had trouble with working with the data in IDLE, ? > >> however, > >> which seems to prefer ASCII by default. > > > Defaults almost never work for encodings. You have to be explicit: ? > > add an > > encoding declaration to the top of your source file if you use encoded > > literal strings in your code; use the codecs module with a suitable > > encoding to read encoded text files, and use an XML parser when ? > > reading XML. > > > Stefan > > -- > >http://mail.python.org/mailman/listinfo/python-list- Hide quoted text - > > - Show quoted text - Dear Sir, There is no big issue for this. I simply downloaded Python2.5 and using IDLE on Windows XP with service pack 2. I used Python 2.5 earlier and presently using Python 2.6 and it is also perfectly fine. I am not using it for small programs but machine learning programs, where code itself runs few million lines over some terabytes of Hindi and Bengali data, and I never found any problem. What is the exact nature of problem you are getting? If you can kindly specify. If possible, with some sample codes. And printing is also never been a problem, all good printers like HP,Epson,Xerox,Canon are printing Hindi or Bengali data finely. If you can kindly specify the problem. Best Regards, Subhabrata. From zuo at chopin.edu.pl Sat Aug 22 17:06:57 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sat, 22 Aug 2009 23:06:57 +0200 Subject: string literal vs string variable In-Reply-To: References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <4a8fc954$0$31331$9b4e6d93@newsspool4.arcor-online.net> Message-ID: 22-08-2009 o 19:46:51 Kee Nethery wrote: > I'm not sure I know the difference between a string variable and a > literal string. Is the difference as simple as: > > somestring = u'hello world' > fromstring(somestring) <-- string variable > vs > XML(u'hello world') <-- literal string Yes, simply: s = 'hello world' # ^ # it is a *string literal* s # <- it is a *string object* # (or rather a name referring to it :-)) (In Python we have rather 'names' than 'variables', though -- as a mental leap -- they are commonly referred to as 'variables', regarding other languages' terminology). Cheers, *j -- Jan Kaliszewski (zuo) From fuzzyman at gmail.com Sat Aug 22 17:25:08 2009 From: fuzzyman at gmail.com (Fuzzyman) Date: Sat, 22 Aug 2009 14:25:08 -0700 (PDT) Subject: ANN: mock 0.6.0, Python mocking and testing library Message-ID: <5a8c8a3a-8bf0-40ad-bf21-89b6fc6a3c9f@z31g2000yqd.googlegroups.com> mock is a Python mock object library for testing, with additional support for runtime monkey patching. Most mocking libraries follow the ?record -> replay? pattern of mocking. I prefer the ?action -> assertion? pattern, which is more readable and intuitive; particularly when working with the Python unittest module. This release, version 0.6.0, is a minor release but with a few new features: * mock homepage http://www.voidspace.org.uk/python/mock/ * download http://www.voidspace.org.uk/downloads/mock-0.6.0.zip * PDF documentation http://www.voidspace.org.uk/downloads/mock.pdf * Google code project and SVN repository http://code.google.com/p/mock/ New in 0.6.0: * New test layout compatible with test discovery * Descriptors (static methods / class methods etc) can now be patched and restored correctly * Mocks can raise exceptions when called by setting side_effect to an exception class or instance * Mocks that wrap objects will not pass on calls to the underlying object if an explicit return_value is set From countryone77 at yahoo.com Sat Aug 22 17:26:16 2009 From: countryone77 at yahoo.com (Bev in TX) Date: Sat, 22 Aug 2009 14:26:16 -0700 (PDT) Subject: logging SMTPhandler Error References: Message-ID: On Aug 21, 8:34?am, Bev in TX wrote: > Hi, > > I've done some Python programming, but I still consider myself a > Python newbie. ?I have a Mac Pro OS X 10.5.8 system and I installed > Python 2.6.2 (the latest package available for the Mac) yesterday. > > I was working through Matt Wilson's article on using the logging > module:http://blog.tplus1.com/index.php/2007/09/28/the-python-logging-module... > (If that does not work, then try:http://tinyurl.com/5v2lcy) > > Everything worked great until his last example. ?My ISP does not > provide e-mail, so I tried using gmail in the line that sets h2. ?I > substituted "mailid" for my actual e-mail address in the following > examples; in my test I used my actual e-mail ID. ?Also, I used the > full path to the newly installed Python 2.6.2; otherwise it picked up > the older Python 2.5: > #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python > > First attempt: > h2 = logging.handlers.SMTPHandler('smtp.gmail.com', 'mai... at gmail.com', > ['mai... at gmail.com'],'ERROR log') > However, that caused the following error to be issued: > > Traceback (most recent call last): > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/logging/handlers.py", line 868, in emit > ? ? smtp.sendmail(self.fromaddr, self.toaddrs, msg) > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/smtplib.py", line 698, in sendmail > ? ? raise SMTPSenderRefused(code, resp, from_addr) > SMTPSenderRefused: (530, '5.7.0 Must issue a STARTTLS command first. > 7sm3867994qwf.47', 'mai... at gmail.com') > > I also tried providing my gmail userid/password, I tried adding a 5th, > credential, argument, which is a tupple, (username,password) (new in > 2.6). > > Second attempt: > h2 = logging.handlers.SMTPHandler('smtp.gmail.com', 'mai... at gmail.com', > ['mai... at gmail.com'],'ERROR log',('mai... at gmail.com','gmail- > password')) > However, that caused the following error message: > > Traceback (most recent call last): > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/logging/handlers.py", line 867, in emit > ? ? smtp.login(self.username, self.password) > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > python2.6/smtplib.py", line 552, in login > ? ? raise SMTPException("SMTP AUTH extension not supported by > server.") > SMTPException: SMTP AUTH extension not supported by server. > > I am able access gmail via Mac's Mail, in which it says that outgoing > mail is going to: > ? ? ? smtp.gmail.com:mailid > I tried using that as the server in the Python script, but it could > not find that server. > > Is this possible? ?If I am doing something incorrectly, would someone > please indicate what it is? > > Thanks, > Bev in TX Today I tried this with both Python 2.6.2 and 3.1.1 on an XP system, with the same error. For the 3.1.1 test, I had to change the syntax of the exception from "except exc, var" to "except exc as var". Here is the modified script, with my email ID changed to "mailid": import logging import logging.handlers #Make a global logging object x = logging.getLogger("logfun") x.setLevel(logging.DEBUG) #This handler writes out everything to stdout h1 = logging.StreamHandler() f = logging.Formatter("%(levelname)s %(asctime)s %(funcName)s %(lineno) d %(message)s") h1.setFormatter(f) h1.setLevel(logging.DEBUG) x.addHandler(h1) #This handler emails me anything that is an error or worse h2 = logging.handlers.SMTPHandler('smtp.gmail.com', 'mailid at gmail.com', ['mailid at gmail.com'],'ERROR log') f = logging.Formatter("%(levelname)s %(asctime)s %(funcName)s %(lineno) d %(message)s") h2.setLevel(logging.ERROR) h2.setFormatter(f) x.addHandler(h2) def g(): 1 / 0 def f(): logfun = logging.getLogger("logfun") logfun.debug("inside f!") try: g() except Exception as ex: logfun.exception("Something awful happened!") logfun.debug("Finishing f!") if __name__ == "__main__": f() Thanks, Bev in TX From ryniek90 at gmail.com Sat Aug 22 17:37:22 2009 From: ryniek90 at gmail.com (ryniek90) Date: Sat, 22 Aug 2009 23:37:22 +0200 Subject: TypeError while checking for permissions with os.access() on windows xp In-Reply-To: References: Message-ID: <4A906512.1060606@gmail.com> > > > > WTF?? > Why on IDLE it works, but when i run this script in cmd.exe, the > os.getenv('HOME') goes NoneType? > I'm to newbie yet to understand this :/ > > > HOME is simply not a standard environment variable that Windows > provides. Any program can set/add environment variables as it deems > fit; in this case it seems IDLE is setting one, but you can't rely on > it outside of IDLE. > > If you do os.environ["HOMEDRIVE"] + os.environ["HOMEPATH"] it may be > what you want. > > Start up cmd.exe, type 'set' -- that's the default/standard > environment variables you have to work with. That's it. > > --S Yep, now that variable works fine. Thanks. From james.harris.1 at googlemail.com Sat Aug 22 17:54:41 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Sat, 22 Aug 2009 14:54:41 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: On 22 Aug, 10:27, David <71da... at libero.it> wrote: ... (snipped a discussion on languages and other systems interpreting numbers with a leading zero as octal) > > Either hexadecimal should have been 0h or octal should > > have been 0t :=) > > > I have seen the use of Q/q instead in order to make it clearer. I still > prefer Smalltalk's 16rFF and 8r377. > > > Two interesting options. In a project I have on I have also considered > using 0q as indicating octal. I maybe saw it used once somewhere else > but I have no idea where. 0t was a second choice and 0c third choice > (the other letters of oct). 0o should NOT be used for obvious reasons. > > So you are saying that Smalltalk has r where > r is presumably for radix? That's maybe best of all. It preserves the > syntactic requirement of starting a number with a digit and seems to > have greatest flexibility. Not sure how good it looks but it's > certainly not bad. > > > > ? 0xff & 0x0e | 0b1101 > > ? 16rff & 16r0e | 2r1101 > > > Hmm. Maybe a symbol would be better than a letter. ... > > Or Ada's 16#FF#, 8#377#... > > I forget if DEC/VMS FORTRAN or Xerox Sigma FORTRAN used x'FF' or > > 'FF'x, and o'377' or '377'o ... > > What about 2_1011, 8_7621, 16_c26h or 2;1011, 8;7621, 16;c26h ? They look good - which is important. The trouble (for me) is that I want the notation for a new programming language and already use these characters. I have underscore as an optional separator for groups of digits - 123000 and 123_000 mean the same. The semicolon terminates a statement. Based on your second idea, though, maybe a colon could be used instead as in 2:1011, 8:7621, 16:c26b I don't (yet) use it as a range operator. I could also use a hash sign as although I allow hash to begin comments it cannot be preceded by anything other than whitespace so these would be usable 2#1011, 8#7621, 16#c26b I have no idea why Ada which uses the # also apparently uses it to end a number 2#1011#, 8#7621#, 16#c26b# Copying this post also to comp.lang.misc. Folks there may either be interested in the discussion or have comments to add. James From kkumerNOTTHIS at thatfamoussearchenginesmail.com Sat Aug 22 18:49:22 2009 From: kkumerNOTTHIS at thatfamoussearchenginesmail.com (Kreso) Date: Sat, 22 Aug 2009 22:49:22 +0000 (UTC) Subject: Items inheriting attributes from its container? Message-ID: I would like to create a list-like container class so that, additionally to usual list methods, I could attach attributes to the container instances. However, I would like it so that the items contained in the particular instance of container somehow 'inherit' those attributes i.e. cont = Container() cont.color = 'blue' cont.append(item) print item.color 'blue' The example appended below does that, but with the restriction that container attributes must be set in the instantiation phase. This is actually fine for me at the moment because my objects are "read only", but I would like to hear about better solutions, with more flexibility, please. #-----8<---------------------------- class Player: """Class for items""" def __init__(self, playerdata, team): self.data = playerdata for key in team.__dict__: setattr(self, key, team.__dict__[key]) return class Team(list): """Class for containers""" def __init__(self, teamdata, playerdata): for key in teamdata: setattr(self, key, teamdata[key]) for item in playerdata: self.append(Player(item, self)) return lakersdata = {'name' : 'Lakers', 'kitcolor' : 'yellow'} lakersplayers = [['Kobe', 'PG', 12, 123], ['Kareem', 'FW', 23, 345]] lakers = Team(lakersdata, lakersplayers) # This is fine: p1 = lakers[1] print p1.kitcolor # However the following doesn't work: lakers.kitcolor = 'blue' print p1.kitcolor #-----8<---------------------------- From clp2 at rebertia.com Sat Aug 22 18:52:29 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 22 Aug 2009 15:52:29 -0700 Subject: line completion In-Reply-To: References: Message-ID: <50697b2c0908221552k3a44156ek509a35ad0764dd2b@mail.gmail.com> On Thu, Aug 20, 2009 at 9:06 AM, Steven Woody wrote: > Hi, > I wrote a program that takes some user input. ?Many inputs are quit often > used by user, so when a user launch the program, and type in "The Sha", ?he > wants to get "wshank Redemption" displayed automatically in reversed color > (black text on white background) along his cursor. ?When he decided to use > "The Shawshank Redemption", he just press the enter key, otherwise, he type > in other words anyway. > My question is, is there any module that can easy the implementation of this > feature? ?Thanks. The `readline` module in the standard library: http://docs.python.org/library/readline.html Although I don't know how to get it to colorize the interface. Cheers, Chris -- http://blog.rebertia.com From mortonspam at gmail.com Sat Aug 22 19:02:27 2009 From: mortonspam at gmail.com (Ed Morton) Date: Sat, 22 Aug 2009 16:02:27 -0700 (PDT) Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> Message-ID: On Aug 22, 1:11?pm, bolega wrote: > sed/awk/perl: > > How to replace all spaces each with an underscore that occur before a > specific string ? > > I really prefer a sed one liner. Why? > Example > Input : ?This is my book. It is too ?thick to read. The author gets > little royalty but the publisher makes a lot. > Output: This_is_my_book._It_is_too__thick_to read. The author gets > little royalty but the publisher makes a lot. > > We replaced all the spaces with underscores before the first occurence > of the string "to ". No, you replaced all ... the string "to " (note the space). awk '{idx=index($0,"to "); tgt=substr($0,1,idx-1); gsub(/ /,"_",tgt); print tgt substr($0,idx)}' file Ed. From lists at cheimes.de Sat Aug 22 19:14:03 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 23 Aug 2009 01:14:03 +0200 Subject: Items inheriting attributes from its container? In-Reply-To: References: Message-ID: Kreso schrieb: > I would like to create a list-like container class so that, additionally > to usual list methods, I could attach attributes to the container instances. > However, I would like it so that the items contained in the particular > instance of container somehow 'inherit' those attributes i.e. The Python web application framework Zope implements the feature under the name "acquisition". Happy Googling! Christian From mwilson at the-wire.com Sat Aug 22 19:16:39 2009 From: mwilson at the-wire.com (Mel) Date: Sat, 22 Aug 2009 19:16:39 -0400 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: James Harris wrote: > I have no idea why Ada which uses the # also apparently uses it to end > a number > > 2#1011#, 8#7621#, 16#c26b# Interesting. They do it because of this example from : 2#1#E8 -- an integer literal of value 256 where the E prefixes a power-of-2 exponent, and can't be taken as a digit of the radix. That is to say 16#1#E2 would also equal 256, since it's 1*16**2 . Mel. From pavlovevidence at gmail.com Sat Aug 22 19:45:20 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 22 Aug 2009 16:45:20 -0700 (PDT) Subject: Annoying octal notation References: <87d46ok948.fsf@benfinney.id.au> Message-ID: On Aug 22, 12:04?pm, Derek Martin wrote: > On Sat, Aug 22, 2009 at 10:03:35AM +1000, Ben Finney wrote: > > These human programmers, whether newbies or long-experienced, also deal > > with decimal numbers every day, many of which are presented as a > > sequence of digits with leading zeros ? and we continue to think of them > > as decimal numbers regardless. Having the language syntax opposed to > > that is > > ...consistent with virtually every other popular programming language. If you know anything about Python, you should know that "consistent with virtually every other programming langauge" is, at most, a polite suggestion for how Python should do it. Carl Banks From somebody at somewhere.com Sat Aug 22 19:46:26 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Sun, 23 Aug 2009 00:46:26 +0100 Subject: Items inheriting attributes from its container? References: Message-ID: <_MSdnWJk2KnPHg3XnZ2dnUVZ8hmdnZ2d@giganews.com> Kreso wrote: > I would like to create a list-like container class so that, additionally > to usual list methods, I could attach attributes to the container > instances. However, I would like it so that the items contained in the > particular instance of container somehow 'inherit' those attributes i.e. > > cont = Container() > cont.color = 'blue' > cont.append(item) > print item.color > 'blue' > > The example appended below does that, but with the restriction that > container attributes must be set in the instantiation phase. This is > actually fine for me at the moment because my objects are "read only", but > I would like to hear about better solutions, with more flexibility, > please. > > > #-----8<---------------------------- > class Player: > """Class for items""" > > def __init__(self, playerdata, team): > self.data = playerdata > for key in team.__dict__: > setattr(self, key, team.__dict__[key]) > return > > > class Team(list): > """Class for containers""" > > def __init__(self, teamdata, playerdata): > for key in teamdata: > setattr(self, key, teamdata[key]) > for item in playerdata: > self.append(Player(item, self)) > return > > > lakersdata = {'name' : 'Lakers', 'kitcolor' : 'yellow'} > lakersplayers = [['Kobe', 'PG', 12, 123], ['Kareem', 'FW', 23, 345]] > > lakers = Team(lakersdata, lakersplayers) > > # This is fine: > p1 = lakers[1] > print p1.kitcolor > > # However the following doesn't work: > lakers.kitcolor = 'blue' > print p1.kitcolor > > #-----8<---------------------------- I hope this gives you some good ideas. http://en.wikipedia.org/wiki/Join_(SQL) I suspect you will be finding a use for the special __getattr__ method, which is called when an attribute is not found. This can be used to search on your set of joined objects. Your list of joined objects should be a set() to prevent duplicates. -- Stephen Fairchild From pavlovevidence at gmail.com Sat Aug 22 19:49:40 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 22 Aug 2009 16:49:40 -0700 (PDT) Subject: Annoying octal notation References: Message-ID: On Aug 21, 12:48?pm, Derek Martin wrote: > John Nagle wrote: > > Yes, and making lead zeros an error as suggested in PEP 3127 is a > > good idea. ?It will be interesting to see what bugs that flushes > > out. > James Harris wrote: > > It maybe made sense once but this relic of the past should have been > > consigned to the waste bin of history long ago. > > Sigh. ?Nonsense. ?I use octal notation *every day*, for two extremely > prevalent purposes: file creation umask, and Unix file permissions > (i.e. the chmod() function/command). Unix file permissions maybe made sense once but this relic of the past should have been consigned to the waste bin of history long ago. :) Carl Banks From nad at acm.org Sat Aug 22 20:07:29 2009 From: nad at acm.org (Ned Deily) Date: Sat, 22 Aug 2009 17:07:29 -0700 Subject: logging SMTPhandler Error References: Message-ID: In article , Bev in TX wrote: > On Aug 21, 8:34?am, Bev in TX wrote: > > Hi, > > > > I've done some Python programming, but I still consider myself a > > Python newbie. ?I have a Mac Pro OS X 10.5.8 system and I installed > > Python 2.6.2 (the latest package available for the Mac) yesterday. > > > > I was working through Matt Wilson's article on using the logging > > module:http://blog.tplus1.com/index.php/2007/09/28/the-python-logging-module > > ... > > (If that does not work, then try:http://tinyurl.com/5v2lcy) > > > > Everything worked great until his last example. ?My ISP does not > > provide e-mail, so I tried using gmail in the line that sets h2. ?I > > substituted "mailid" for my actual e-mail address in the following > > examples; in my test I used my actual e-mail ID. ?Also, I used the > > full path to the newly installed Python 2.6.2; otherwise it picked up > > the older Python 2.5: > > #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python > > > > First attempt: > > h2 = logging.handlers.SMTPHandler('smtp.gmail.com', 'mai... at gmail.com', > > ['mai... at gmail.com'],'ERROR log') > > However, that caused the following error to be issued: > > > > Traceback (most recent call last): > > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > > python2.6/logging/handlers.py", line 868, in emit > > ? ? smtp.sendmail(self.fromaddr, self.toaddrs, msg) > > ? File "/Library/Frameworks/Python.framework/Versions/2.6/lib/ > > python2.6/smtplib.py", line 698, in sendmail > > ? ? raise SMTPSenderRefused(code, resp, from_addr) > > SMTPSenderRefused: (530, '5.7.0 Must issue a STARTTLS command first. > > 7sm3867994qwf.47', 'mai... at gmail.com') The problem here is that gmail, like most modern mail services, requires the use of an encrypted (SSL or TLS) connection for mail relaying so that the required user name and password are not sent in the clear. The logging SMTP handler uses the smtplib module from the standard module to send mail and, when built properly, smtplib does support TLS. However, the caller of smtplib does need to do some extra work in that case, i.e. it needs to call the server object's starttls method at the right point in the protocol handshaking. It's currently not done automatically in smtplib and, unfortunately, there is no code in the logging smtp handler to detect the need for and to call starttls (in response to a 250-STARTTLS response to an EHLO). To make this work, either the logging module or, perhaps better, the smptlib module needs to be smarter about this case. I didn't see an open issue on the Python bug tracker about this; you might want to open one. In the meantime, some options would be to find an SMTP mail host that doesn't require TLS. Or write a custom logger. Or on OS X it's not *too* difficult to set up a local host mailer using the Apple-supplied prefix that would accept mail locally and forward it to a more sophisticated remote mailer. -- Ned Deily, nad at acm.org From someone at example.com Sat Aug 22 20:14:29 2009 From: someone at example.com (John W. Krahn) Date: Sat, 22 Aug 2009 17:14:29 -0700 Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? In-Reply-To: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> Message-ID: bolega wrote: > sed/awk/perl: > > How to replace all spaces each with an underscore that occur before a > specific string ? > > I really prefer a sed one liner. > > Example > Input : This is my book. It is too thick to read. The author gets > little royalty but the publisher makes a lot. > Output: This_is_my_book._It_is_too__thick_to read. The author gets > little royalty but the publisher makes a lot. > > We replaced all the spaces with underscores before the first occurence > of the string "to ". $ perl -le' $x = "This is my book. It is too thick to read. The author gets little royalty but the publisher makes a lot."; print $x; $x =~ /to / && substr( $x, 0, $-[0] ) =~ tr/ /_/; print $x; ' This is my book. It is too thick to read. The author gets little royalty but the publisher makes a lot. This_is_my_book._It_is_too__thick_to read. The author gets little royalty but the publisher makes a lot. John -- Those people who think they know everything are a great annoyance to those of us who do. -- Isaac Asimov From python at mrabarnett.plus.com Sat Aug 22 20:45:18 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 23 Aug 2009 01:45:18 +0100 Subject: sed/awk/perl: How to replace all spaces each with an underscore that occur before a specific string ? In-Reply-To: References: <1380cb14-6462-4585-b2d1-c59c99ff9b56@b15g2000yqd.googlegroups.com> Message-ID: <4A90911E.3000402@mrabarnett.plus.com> John W. Krahn wrote: > bolega wrote: >> sed/awk/perl: >> >> How to replace all spaces each with an underscore that occur before a >> specific string ? >> >> I really prefer a sed one liner. >> >> Example >> Input : This is my book. It is too thick to read. The author gets >> little royalty but the publisher makes a lot. >> Output: This_is_my_book._It_is_too__thick_to read. The author gets >> little royalty but the publisher makes a lot. >> >> We replaced all the spaces with underscores before the first occurence >> of the string "to ". > > $ perl -le' > $x = "This is my book. It is too thick to read. The author gets little > royalty but the publisher makes a lot."; > print $x; > $x =~ /to / && substr( $x, 0, $-[0] ) =~ tr/ /_/; > print $x; > ' > This is my book. It is too thick to read. The author gets little > royalty but the publisher makes a lot. > This_is_my_book._It_is_too__thick_to read. The author gets little > royalty but the publisher makes a lot. > If you're interested in a Python regex solution: s = "This is my book. It is too thick to read. The author gets little royalty but the publisher makes a lot." s = re.sub(".*?(?=to )", lambda m: m.group().replace(" ", "_"), s) From countryone77 at yahoo.com Sat Aug 22 20:45:52 2009 From: countryone77 at yahoo.com (Bev in TX) Date: Sat, 22 Aug 2009 17:45:52 -0700 (PDT) Subject: logging SMTPhandler Error References: Message-ID: <87236fb1-c09f-46e8-8492-514ba000c74a@24g2000yqm.googlegroups.com> On Aug 22, 7:07?pm, Ned Deily wrote: > > The problem here is that gmail, like most modern mail services, requires > the use of an encrypted (SSL or TLS) connection for mail relaying so > that the required user name and password are not sent in the clear. ?The > logging SMTP handler uses the smtplib module from the standard module to > send mail and, when built properly, smtplib does support TLS. ?However, > the caller of smtplib does need to do some extra work in that case, i.e. > it needs to call the server object's starttls method at the right point > in the protocol handshaking. It's currently not done automatically in > smtplib and, unfortunately, there is no code in the logging smtp handler > to detect the need for and to call starttls (in response to a > 250-STARTTLS response to an EHLO). > > To make this work, either the logging module or, perhaps better, the > smptlib module needs to be smarter about this case. ?I didn't see an > open issue on the Python bug tracker about this; you might want to open > one. ?In the meantime, some options would be to find an SMTP mail host > that doesn't require TLS. ?Or write a custom logger. ?Or on OS X it's > not *too* difficult to set up a local host mailer using the > Apple-supplied prefix that would accept mail locally and forward it to a > more sophisticated remote mailer. > > -- > ?Ned Deily, > ?n... at acm.org- Hide quoted text - > > - Show quoted text - Thanks for the excellent and informative response :-). I'll investigate further, as you suggested, now that I understand what is happening. Bev in TX From zuo at chopin.edu.pl Sat Aug 22 20:56:08 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sun, 23 Aug 2009 02:56:08 +0200 Subject: Items inheriting attributes from its container? In-Reply-To: References: Message-ID: 23-08-2009 Kreso wrote: > I would like to create a list-like container class so that, additionally > to usual list methods, I could attach attributes to the container > instances. > However, I would like it so that the items contained in the particular > instance of container somehow 'inherit' those attributes i.e. > > cont = Container() > cont.color = 'blue' > cont.append(item) > print item.color > 'blue' [snip] > class Player: > """Class for items""" > > def __init__(self, playerdata, team): > self.data = playerdata > for key in team.__dict__: > setattr(self, key, team.__dict__[key]) > return > > > class Team(list): > """Class for containers""" > def __init__(self, teamdata, playerdata): > for key in teamdata: > setattr(self, key, teamdata[key]) > for item in playerdata: > self.append(Player(item, self)) > return > > lakersdata = {'name' : 'Lakers', 'kitcolor' : 'yellow'} > lakersplayers = [['Kobe', 'PG', 12, 123], ['Kareem', 'FW', 23, 345]] > > lakers = Team(lakersdata, lakersplayers) [snip] > p1 = lakers[1] > print p1.kitcolor [snip] > lakers.kitcolor = 'blue' > print p1.kitcolor [Not tested. I believe that the idea is clear] class RecruitmentError(ValueError): """Raised when a player cannot be recruited.""" class Player(object): """A potential item of a Team() instance.""" def __init__(self, playerdata, team=None): self.data = playerdata self.team = None if team: team.append(self) # (called when the usual attribute lookup didn't succeed) def __getattr__(self, name): return getattr(self.team, name) # ^ the last method may not be necessary -- you can always # access to team data via 'team' attribute # (and 'explicit is better than implicit') class Team(list): """A container for Player() instances.""" def __init__(self, teamdata, playerdata=None): for key in teamdata: setattr(self, key, teamdata[key]) for data in playerdata: self.append(Player(data)) def _validate_and_get(self, index=None, player=None): if player is not None and not isinstance(player, Player): raise TypeError('A Player instance is required') if index is not None: if isinstance(index, slice): raise TypeError('Slicing is not allowed') return self[index] # (raise IndexError for bad index) _validate = _validate_and_get def _recruit(self, player): if player.team is None: player.team = self else: raise RecruitmentError('Player %s has already recruited') def _dismiss(self, player): player.team = None def __setitem__(self, index, player): current = self._validate_and_get(index, player) if player is not current: self._recruit(player) self._dismiss(current) list.__setitem__(self, index, player) def __delitem__(self, index): player = self._validate_and_get(index) self._dismiss(player) list.__delitem__(self, index) def append(self, player): self._validate(player=player) self._recruit(player) list.append(self, player) # and similarly: # * def extend... # * def insert... # * def pop... # * def remove... ...if you really need ordered container (reflecting functions/hierarchy of players in a team?). Otherwise, as Stephen noted, you should subclass set rather than list. Cheers, *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Sat Aug 22 21:08:37 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sun, 23 Aug 2009 03:08:37 +0200 Subject: Items inheriting attributes from its container? In-Reply-To: References: Message-ID: PS. Erratum: > class Team(list): > """A container for Player() instances.""" > > def __init__(self, teamdata, playerdata=None): *** Here should be added: list.__init__(self) *** > for key in teamdata: > setattr(self, key, teamdata[key]) > for data in playerdata: > self.append(Player(data)) -- Jan Kaliszewski (zuo) From ben+python at benfinney.id.au Sat Aug 22 21:27:25 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 23 Aug 2009 11:27:25 +1000 Subject: your favorite debugging tool? References: Message-ID: <87vdkfiaki.fsf@benfinney.id.au> Esmail writes: > What is your favorite tool to help you debug your code? A ?print? statement (or equivalent, like logging output). > I've been getting along with 'print' statements but that is getting > old and somewhat cumbersome. Whenever a simple output statement is too cumbersome for debugging, I take it as a sign that the program is too cumbersome to follow. My debugging questions at that point are best taken to the unit test suite: record the questions and the expected answers, so that in the future anyone can get the benefit of them in a repeatable and automated fashion. -- \ ?The power of accurate observation is frequently called | `\ cynicism by those who don't have it.? ?George Bernard Shaw | _o__) | Ben Finney From nad at acm.org Sat Aug 22 22:05:51 2009 From: nad at acm.org (Ned Deily) Date: Sat, 22 Aug 2009 19:05:51 -0700 Subject: logging SMTPhandler Error References: <87236fb1-c09f-46e8-8492-514ba000c74a@24g2000yqm.googlegroups.com> Message-ID: In article <87236fb1-c09f-46e8-8492-514ba000c74a at 24g2000yqm.googlegroups.com>, Bev in TX wrote: > On Aug 22, 7:07?pm, Ned Deily wrote: > > [...] Or on OS X it's > > not *too* difficult to set up a local host mailer using the > > Apple-supplied prefix that would accept mail locally and forward it to a > > more sophisticated remote mailer. Um, notation fail: s/prefix/Postfix/ -- Ned Deily, nad at acm.org From code at pizzashack.org Sat Aug 22 23:19:01 2009 From: code at pizzashack.org (Derek Martin) Date: Sat, 22 Aug 2009 22:19:01 -0500 Subject: Annoying octal notation In-Reply-To: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> Message-ID: <20090823031901.GX20434@dragontoe.org> On Sat, Aug 22, 2009 at 02:55:51AM +0000, Steven D'Aprano wrote: > > I can see how 012 can > > be confusing to new programmers, but at least it's legible, and the > > great thing about humans is that they can be taught (usually). > > And the great thing is that now you get to teach yourself to stop writing > octal numbers implicitly and be write them explicitly with a leading 0o > instead :) Sorry, I don't write them implicitly. A leading zero explicitly states that the numeric constant that follows is octal. It is so in 6 out of 7 computer languages I have more than a passing familiarity with (the 7th being scheme, which is a thing unto itself), including Python. It's that way on Bourne-compatible and POSIX-compatible Unix shells (though it requires a leading backslash before the leading zero there). I'm quite certain it can not be the case on only those 6 languages that I happen to be familiar with... While it may be true that people commonly write decimal numbers with leading zeros (I dispute even this, having to my recollection only recently seen it as part of some serial number, which in practice is really more of a string identifier than a number, often containing characters other than numbers), it's also true that in the context of computer programming languages, for the last 40+ years, a number represented with a leading zero is most often an octal number. This has been true even in Python for nearly *twenty years*. Why the sudden need to change it? So no, I don't get to teach myself to stop writing octal numbers with a leading zero. Instead, I have to remember an exception to the rule. Also I don't think it's exactly uncommon for computer languages to do things differently than they are done in non-CS circles. A couple of easy examples: we do not write x+=y except in computer languages. The POSIX system call to create a file is called creat(). If you think about it, I'm sure you can come up with lots of examples where even Python takes liberties. Is this a bad thing? Not inherently, no. Will it be confusing to people who aren't familiar with the usage? Quite possibly, but that is not inherently bad either. It's all about context. > Use of octal isn't common. It's common enough. Peruse the include files for your C libraries, or the source for your operating system's kernel, or system libraries, and I bet you'll find plenty of octal. I did. [Note that it is irrelevant that these are C/C++ files; here we are only concerned with whether they use octal, not how it is represented therein.] I'd guess there's a fair chance that any math or scientific software package uses octal. Octal is a convenient way to represent bit fields that naturally occur in groups of 3, of which there are potentially limitless cases. > You've given two cases were octal notation is useful, but for every > coder who frequently writes umasks on Unix systems, there are a > thousand who don't. I gave two cases that I use *daily*, or very nearly daily. My hats currently include system admin, SQA, and software development, and I find it convenient to use octal in each of those. But those are hardly the only places where octal is useful. Have a look at the ncurses library, for example. Given that Python has an ncurses interface, I'm guessing it's used there too. In fact if the Python source had no octal in it, I would find that very surprising. > It's no hardship to write 0o12 instead of 012. Computer languages are not write-only, excepting maybe Perl. ;-) Writing 0o12 presents no hardship; but I assert, with at least some support from others here, that *reading* it does. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From code at pizzashack.org Sat Aug 22 23:32:03 2009 From: code at pizzashack.org (Derek Martin) Date: Sat, 22 Aug 2009 22:32:03 -0500 Subject: Annoying octal notation In-Reply-To: References: Message-ID: <20090823033203.GY20434@dragontoe.org> On Fri, Aug 21, 2009 at 04:23:57PM -0700, James Harris wrote: > You misunderstand. I was saying that taking a leading zero as > indicating octal is archaic. Octal itself is fine where appropriate. I don't see that the leading zero is any more archaic than the use of octal itself... Both originate from around the same time period, and are used in the same cases. We should just prohibit octal entirely then. But I suppose it depends on which definition of "archaic" you use. In the other common sense of the word, the leading zero is no more archaic than the C programming language. Let's ban the use of all three. :) (I believe C is still the language in which the largest number of lines of new code are written, but if not, it's way up there.) > The chmod command doesn't require a leading zero. No, but it doesn't need any indicator that the number given to it is in octal; in the case of the command line tool, octal is *required*, and the argument is *text*. However, the chmod() system call, and the interfaces to it in every language I'm familiar with that has one, do require the leading zero (because that's how you represent octal). Including Python, for some 20 years or so. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From cri at tiac.net Sat Aug 22 23:38:59 2009 From: cri at tiac.net (Richard Harter) Date: Sun, 23 Aug 2009 03:38:59 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <4a90b50e.154654859@text.giganews.com> On Sat, 22 Aug 2009 14:54:41 -0700 (PDT), James Harris wrote: >On 22 Aug, 10:27, David <71da... at libero.it> wrote: > >... (snipped a discussion on languages and other systems interpreting >numbers with a leading zero as octal) > >> > Either hexadecimal should have been 0h or octal should >> > have been 0t :=3D) >> >> >> I have seen the use of Q/q instead in order to make it clearer. I still >> prefer Smalltalk's 16rFF and 8r377. >> >> >> Two interesting options. In a project I have on I have also considered >> using 0q as indicating octal. I maybe saw it used once somewhere else >> but I have no idea where. 0t was a second choice and 0c third choice >> (the other letters of oct). 0o should NOT be used for obvious reasons. >> >> So you are saying that Smalltalk has r where >> r is presumably for radix? That's maybe best of all. It preserves the >> syntactic requirement of starting a number with a digit and seems to >> have greatest flexibility. Not sure how good it looks but it's >> certainly not bad. I opine that a letter is better; special characters are a valuable piece of real estate. However for floating point you need at least three letters because a floating point number has three parts: the fixed point point, the exponent base, and the exponent. Now we can represent the radices of the individual parts with the 'r'scheme, e.g., 2r101001, but we need separate letters to designate the exponent base and the exponent. B and E are the obvious choices, though we want to be careful about a confusion with 'b' in hex. For example, using 'R', 3R20.1B2E16Rac is 20.1 in trinary (6 1/3) times 2**172 (hex ac). I grant that this example looks a bit gobbledegookish, but normal usage would be much simpler. The notation doesn't handle balanced trinary; however I opine that balanced trinary requires special notation. Richard Harter, cri at tiac.net http://home.tiac.net/~cri, http://www.varinoma.com No one asks if a tree falls in the forest if there is no one there to see it fall. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 23 00:07:05 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Aug 2009 04:07:05 GMT Subject: Annoying octal notation References: <87d46ok948.fsf@benfinney.id.au> Message-ID: <02a0b085$0$30337$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 14:04:17 -0500, Derek Martin wrote: >> These human programmers, whether newbies or long-experienced, also deal >> with decimal numbers every day, many of which are presented as a >> sequence of digits with leading zeros ? and we continue to think of >> them as decimal numbers regardless. Having the language syntax opposed >> to that is > > ...consistent with virtually every other popular programming language. A mistake is still a mistake even if it shared with others. Treating its with a lead zero as octal was a design error when it was first thought up (possibly in C?) and it remains a design error no matter how many languages copy it. I feel your pain of having to unlearn something you have learned, but just because you have been lead astray by the languages you use doesn't mean we should compound the error by leading the next generation of coders astray too. Octal is of little importance today, as near as I can tell it only has two common uses in high level languages: file umasks and permissions on Unix systems. It simply isn't special enough to justify implicit notation that surprises people, leads to silent errors, and is inconsistent with standard mathematical notation and treatment of floats: >>> 123.2000 # insignificant trailing zeroes don't matter 123.2 >>> 000123.2 # neither do insignificant leading zeroes 123.2 >>> 001.23e0023 # not even if it is an integer 1.23e+23 >>> 000123 # but here is matters 83 -- Steven From goldtech at worldpost.com Sun Aug 23 00:47:52 2009 From: goldtech at worldpost.com (goldtech) Date: Sat, 22 Aug 2009 21:47:52 -0700 (PDT) Subject: Idle does not recognize PYTHONPATH Message-ID: <1eaa9d66-b1ff-4d2d-961f-ee40054a0953@r38g2000yqn.googlegroups.com> Hi, Idle does not recognize PYTHONPATH set in .bashrc. Starting Python shell in the terminal sys.path shows the PYTHONPATH, but again not shown in IDLE. This is a common problem but I could not find a fix. Using Ubuntu 9.04. Python 2.6. Thanks From ak at nothere.com Sun Aug 23 01:01:46 2009 From: ak at nothere.com (AK) Date: Sun, 23 Aug 2009 01:01:46 -0400 Subject: How to 'de-slashify' a string? In-Reply-To: References: <4a8faa47$0$31283$607ed4bc@cv.net> <00193b65$0$2938$c3e8da3@news.astraweb.com> <4a8fc3d1$0$22535$607ed4bc@cv.net> <4a8fce05$0$31285$607ed4bc@cv.net> Message-ID: <4a90cd3a$0$22525$607ed4bc@cv.net> Vlastimil Brom wrote: > 2009/8/22 AK : >> Vlastimil Brom wrote: >>> 2009/8/22 AK : >>>> Steven D'Aprano wrote: >>>>> On Sat, 22 Aug 2009 04:20:23 -0400, AK wrote: >>>>> >>>>>> Hi, if I have a string '\\303\\266', how can I convert it to '\303\266' >>>>>> in a general way? >>>>> It's not clear what you mean. >>>>> >>>>> Do you mean you have a string '\\303\\266', that is: >>>>> >>>>> backslash backslash three zero three backslash backslash two six six >>>>> >>>>> If so, then the simplest way is: >>>>> >>>>>>>> s = r'\\303\\266' # note the raw string >>>>>>>> len(s) >>>>> 10 >>>>>>>> print s >>>>> \\303\\266 >>>>>>>> print s.replace('\\\\', '\\') >>>>> \303\266 >>>>> >>>>> >>>>> Another possibility: >>>>> >>>>>>>> s = '\\303\\266' # this is not a raw string >>>>>>>> len(s) >>>>> 8 >>>>>>>> print s >>>>> \303\266 >>>>> >>>>> So s is: >>>>> backslash three zero three backslash two six six >>>>> >>>>> and you don't need to do any more. >>>> Well, I need the string itself to become '\303\266', not to print >>>> that way. In other words, when I do 'print s', it should display >>>> unicode characters if my term is set to show them, instead of >>>> showing \303\266. >>>> >>>>>> The problem I'm running into is that I'm connecting with pygresql to a >>>>>> postgres database and when I get fields that are of 'char' type, I get >>>>>> them in unicode, but when I get fields of 'byte' type, I get the text >>>>>> with quoted slashes, e.g. '\303' becomes '\\303' and so on. >>>>> Is pygresql quoting the backslash, or do you just think it is quoting >>>>> the >>>>> backslashes? How do you know? E.g. if you have '\\303', what is the >>>>> length >>>>> of that? 4 or 5? >>>> Length is 4, and I need it to be length of 1. E.g.: >>>> >>>>>>> s = '\303' >>>>>>> s >>>> '\xc3' >>>>>>> x = '\\303' >>>>>>> x >>>> '\\303' >>>>>>> len(x) >>>> 4 >>>>>>> len(s) >>>> 1 >>>> >>>> >>>> What I get from pygresql is x, what I need is s. Either by asking >>>> pygresql >>>> to do this or convert it afterwards. I can't do replace('\\303', '\303') >>>> because it can be any unicode character. >>>> >>>> -- >>>> AK >>>> -- >>>> http://mail.python.org/mailman/listinfo/python-list >>>> >>> >>> Hi, >>> do you mean something like >>> >>>>>> u"\u0303" >>> u'\u0303' >>>>>> print u"\u0303" >>> ? >>> ? (dec.: 771) (hex.: 0x303) ? COMBINING TILDE (Mark, Nonspacing) >>> ? >>> >>> vbr >> Yes, something like that except that it starts out as '\\303\\266', and it's >> good enough for me if it turns into '\303\266', in fact that's rendered as >> one unicode char. In other words, when you do: >> >>>>> print "\\303\\266" >> '\303\266' >> >> I need that result to become a python string, i.e. the slashes need to >> be converted from literal slashes to escape slashes. >> >> >> >> >> -- >> AK >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > Not sure, whether it is the right way of handling the such text data, but maybe: > >>>> decoded = '\\303\\266'.decode("string_escape") >>>> decoded > '\xc3\xb6' >>>> print decoded > ?? >>>> print '\303\266' > ?? > > It might be an IDLE issue, but it still isn't one unicode glyph. > > I guess, you have to ensure, that the input data is valid and the > right encoding is used. > > hth > vbr Actually, this works perfectly for me. It prints out as one character in gnome-terminal and also when I write it to a text file, and open it as utf-8 format in gnumeric, it also shows up properly. Thanks to all who helped! -AK From http Sun Aug 23 01:27:57 2009 From: http (Paul Rubin) Date: 22 Aug 2009 22:27:57 -0700 Subject: How to create functors? References: <7xab1vl0qf.fsf@ruckus.brouhaha.com> <7xmy5uanlt.fsf@ruckus.brouhaha.com> Message-ID: <7xljlbf6aq.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > According to Wikipedia, functor can be used as a synonym for "function > object": ... http://en.wikipedia.org/wiki/Function_object Hmm, I hadn't seen that usage before. I guess there's no law against it, but it seems a bit bogus to me. > I find the Haskell page entirely opaque and unintelligible... The > Wikipedia page is a little better I thought it was the other way around, but I've been banging my head against Haskell on and off for the past year or so, so it could be that the Haskell page is more intelligible if the reader already has some familiarity with Haskell and its type system. Here's another attempt of my own, from the mathematical perspective: "categories" generalize the concept of structured collections of objects. For example, groups, rings, and sets are each a type of structured collection, so there is a category of groups (called "Grp" since for some reason categorists like to use capitalized, abbreviated names), a category of rings ("Rng"), and a category of sets ("Set"). Each category has a collection of objects and a collection of "arrows" (sometimes called morphisms) which are associative relations between objects in the category. So in the category of sets, the objects are sets and the arrows are functions mapping one set to another. In the category of groups, the objects are groups and the arrows are the homeomorphisms between groups. Functors are mappings from one category to another, that map both the objects and the arrows. That is they are arrows on the categories of categories. The concepts of categories and functors came from the loftier reaches of algebraic geometry (further in math than I ever got) in the 1950's or so. These days they turn out to be useful in studying type systems of programming languages, which is where most of my exposure to them has come from. > But let me try an example to see if I've got it right: > class Int2StrFunctor: > def map1(self, n): > if type(n) is not int: > raise TypeError('argument must be an int') I don't think this is right. A functor (in the PL sense that I've been describing) acts on types, not on members of types. That is, your example turns "3" into "---", i.e. it turns a member of type "int" into a member of type "str". A functor would be something that acts on arbitrary types, e.g. one might turn "int" into "array of int", and "str" into "array of str" and so forth. Another might turn "int" into "red-black tree containing a pair of ints at each node" and doing something similar with str. The map1 and map2 functions (I guess it is ok to call them that) are supposed to be generic. I guess you could have a "String" functor whose map1 function is repr and whose map2 functor is (lambda f: lambda x,f=f: repr(f(x))) or something like that. It would transport every type to the str type. > There are some technical restrictions on functors, relating to the sorts > of functions and types (strictly "categories") they can accept, > presumably to make them mathematically well-behaved. Right. From aahz at pythoncraft.com Sun Aug 23 01:48:34 2009 From: aahz at pythoncraft.com (Aahz) Date: 22 Aug 2009 22:48:34 -0700 Subject: logging SMTPhandler Error References: Message-ID: In article , Ned Deily wrote: > >Or on OS X it's not *too* difficult to set up a local host mailer using >the Apple-supplied prefix that would accept mail locally and forward it >to a more sophisticated remote mailer. It's also not too difficult to do the moral equivalent with dnspython and find the MX host for the domain you're trying to send e-mail to; that usually does not require an encrypted connection. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From steve at REMOVE-THIS-cybersource.com.au Sun Aug 23 02:13:31 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 23 Aug 2009 06:13:31 GMT Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> Message-ID: <02a0ce27$0$30337$c3e8da3@news.astraweb.com> On Sat, 22 Aug 2009 22:19:01 -0500, Derek Martin wrote: > On Sat, Aug 22, 2009 at 02:55:51AM +0000, Steven D'Aprano wrote: >> > I can see how 012 can >> > be confusing to new programmers, but at least it's legible, and the >> > great thing about humans is that they can be taught (usually). >> >> And the great thing is that now you get to teach yourself to stop >> writing octal numbers implicitly and be write them explicitly with a >> leading 0o instead :) > > Sorry, I don't write them implicitly. A leading zero explicitly states > that the numeric constant that follows is octal. That is incorrect. Decimal numbers implicitly use base 10, because there's nothing in the literal 12340 (say) to indicate the base is ten, rather than 16 or 9 or 23. Although implicit is usually bad, when it's as common and expected as decimal notation, it's acceptable. Hex decimals explicitly use base 16, because the leading 0x is defined to mean "base 16". 0x is otherwise not a legal decimal number, or hex number for that matter. (It would be legal in base 34 or greater, but that's rare enough that we can ignore this.) For the bases we care about, a leading 0x can't have any other meaning -- there's no ambiguity, so we can treat it as a synonym for "base 16". (Explicitness isn't a binary state, and it would be even more explicit if the base was stated in full, as in e.g. Ada where 16#FF# = decimal 255.) However, octal numbers are defined implicitly: 012 is a legal base 10 number, or base 3, or base 9, or base 16. There's nothing about a leading zero that says "base 8" apart from familiarity. We can see the difference between leading 0x and leading 0 if you repeat it: repeating an explicit 0x, as in 0x0xFF, is a syntax error, while repeating an implicit 0 silently does nothing different: >>> 0x0xFF File "", line 1 0x0xFF ^ SyntaxError: invalid syntax >>> 0077 63 > It is so in 6 out of 7 > computer languages I have more than a passing familiarity with (the 7th > being scheme, which is a thing unto itself), including Python. It's > that way on Bourne-compatible and POSIX-compatible Unix shells (though > it requires a leading backslash before the leading zero there). I'm > quite certain it can not be the case on only those 6 languages that I > happen to be familiar with... No, of course not. There are a bunch of languages, pretty much all heavily influenced by C, which treat integer literals with leading 0s as oct: C++, Javascript, Python 2.x, Ruby, Perl, Java. As so often is the case, C's design mistakes become common practice. Sigh. However, there are many, many languages that don't, or otherwise do things differently to C. Even some modern C-derived languages reject the convention: C# doesn't have octal literals at all. As far as I can tell, Objective-C and Cocoa requires you to explicitly enable support for octal literals before you use them. In D, at least some people want to follow Python's lead and either drop support for oct literals completely, or require a 0o prefix: http://d.puremagic.com/issues/show_bug.cgi?id=2656 E makes a leading 0 a syntax error. As far as other, non-C languages go, leading 0 = octal seems to be rare or non-existent: Basic and VB use a leading &O for octal. FORTRAN 90 uses a leading O (uppercase o) for octal, and surrounds the literal in quotation marks: O"12" would be ten in octal. 012 would be decimal 12. As far as I can tell, COBOL also ignores leading zeroes. Forth interprets literals according to the current value of BASE (which defaults to 10). There's no special syntax for it.To enter ten in octal, you might say: 8 BASE ! 12 or if your system provides it: OCT 12 Standard Pascal ignores leading 0s in integers, and doesn't support octal at all. A leading $ is used for hex. At least one non-standard Pascal uses leading zero for octal. Haskell requires an explicit 0o: http://www.haskell.org/onlinereport/lexemes.html#lexemes-numeric So does OCaml. Ada uses decimal unless you explicitly give the base: http://archive.adaic.com/standards/83lrm/html/lrm-02-04.html Leading zeroes are insignificant in bc: [steve at sylar ~]$ bc bc 1.06 Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. 012 + 011 23 Leading zeroes are also insignificant in Hewlett-Packard RPN language (e.g. HP-48GX calculators), Hypertalk and languages derived from it. I'm not sure, but it looks to me like Boo doesn't support octal literals, although it supports hex with 0x and binary with 0b. Algol uses an explicit base: 8r12 to indicate octal 10. Common Lisp and Scheme use a #o prefix. As far as *languages* go, 0-based octal literals are in the tiny minority. As far as *programmers* go, it may be in a plurality, perhaps even a small minority, but remember there are still millions of VB programmers out there who are just as unfamiliar with C conventions. > While it may be true that people commonly write decimal numbers with > leading zeros (I dispute even this [...] Leading zeroes in decimal numbers are *very* common in dates and times. [...] > Given that Python has an ncurses interface, I'm > guessing it's used there too. In fact if the Python source had no octal > in it, I would find that very surprising. I can't see any oct literals in the standard library, not even in the ncurses interface, but then my grep-foo is weak and I may have made a mistake. I encourage you to look for yourself. >> It's no hardship to write 0o12 instead of 012. > > Computer languages are not write-only, excepting maybe Perl. ;-) Writing > 0o12 presents no hardship; but I assert, with at least some support from > others here, that *reading* it does. No more so than 0x or 0b literals. If anything, 0o12 stands out as "not twelve" far more than 012 does. -- Steven From hendrik at microcorp.co.za Sun Aug 23 03:10:22 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 23 Aug 2009 09:10:22 +0200 Subject: Blank Line at Program Exit In-Reply-To: References: Message-ID: <200908230910.22246.hendrik@microcorp.co.za> On Thursday 20 August 2009 07:31:14 Steven Woody wrote: > Hi, > Any python program, even that does absolutely nothing in the code, will > cause a blank line printed out when the program exit. What's the reason? not for me: hvr at Linuxbox:~/Sasol/lib> cat blank.py hvr at Linuxbox:~/Sasol/lib> python blank.py hvr at Linuxbox:~/Sasol/lib> - Hendrik From hendrik at microcorp.co.za Sun Aug 23 03:21:54 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 23 Aug 2009 09:21:54 +0200 Subject: your favorite debugging tool? In-Reply-To: References: Message-ID: <200908230921.54199.hendrik@microcorp.co.za> On Saturday 22 August 2009 16:49:22 Aahz wrote: > In article , > > Esmail wrote: > >What is your favorite tool to help you debug your code? I've been > >getting along with 'print' statements but that is getting old and > >somewhat cumbersome. > > Despite the fact that I've been using Python for more than a decade, > print is still my mainstay (or possibly logging to a file). Same here, although I have not been abusing python for as long as Aahz has been using it. I find that python pretty much does more or less what I expect it to, and where it does not, a print quickly gets me to RTFM when I have been rolling along under intuition. And the final arbiter is of course the interactive prompt. - Hendrik From ben+python at benfinney.id.au Sun Aug 23 03:40:47 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Sun, 23 Aug 2009 17:40:47 +1000 Subject: your favorite debugging tool? References: Message-ID: <873a7jhta8.fsf@benfinney.id.au> Hendrik van Rooyen writes: > And the final arbiter is of course the interactive prompt. Oh yes, of course I forget to mention that! Write your code so it can be imported, and write your functionality so it has narrow interfaces, and you can do whatever inspection is needed from the interactive prompt. -- \ ?We have to go forth and crush every world view that doesn't | `\ believe in tolerance and free speech.? ?David Brin | _o__) | Ben Finney From robert.kern at gmail.com Sun Aug 23 03:54:31 2009 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 23 Aug 2009 00:54:31 -0700 Subject: your favorite debugging tool? In-Reply-To: References: Message-ID: On 2009-08-22 07:25 AM, Esmail wrote: > Hi all, > > What is your favorite tool to help you debug your > code? I've been getting along with 'print' statements > but that is getting old and somewhat cumbersome. > > I'm primarily interested in utilities for Linux (but > if you have recommendations for Windows, I'll take > them too :) > > I use emacs as my primary development environment, FWIW. > Someone mentioned winpdb .. anyone have experience/comments > on this? Others? I am frequently in the IPython interactive prompt for testing out stuff and even as the main way of running my code. It has a nice feature that when you get a traceback, you can open up pdb post-mortem. In [8]: def f(x): ...: y = 1 / x ...: return y ...: In [9]: f(1) Out[9]: 1 In [10]: f(0) --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) /Users/rkern/ in () /Users/rkern/ in f(x) ZeroDivisionError: integer division or modulo by zero In [11]: %debug > (2)f() ipdb> print x 0 I have a little function that I've been using recently to print out the function I am currently in along with the arguments: def whereami(): """ Print the current function call. import kerntrace;kerntrace.whereami() """ import inspect frame = inspect.currentframe(1) args, varargs, varkw, f_locals = inspect.getargvalues(frame) if args[:1] == ['self']: del args[0] print '%s%s' % (frame.f_code.co_name, inspect.formatargvalues(args, varargs, varkw, f_locals)) I think pdb is okay, but I am looking forward to pydbgr's completion. http://code.google.com/p/pydbgr/ -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sdementen at gmail.com Sun Aug 23 04:09:04 2009 From: sdementen at gmail.com (seb) Date: Sun, 23 Aug 2009 01:09:04 -0700 (PDT) Subject: conditional for-statement Message-ID: Hi, i was wondering if there is a syntax alike: for i in range(10) if i > 5: print i equivalent to for i in (for i in range(10) if i>5): print i sebastien From benjamin at python.org Sun Aug 23 04:12:40 2009 From: benjamin at python.org (Benjamin Peterson) Date: Sun, 23 Aug 2009 08:12:40 +0000 (UTC) Subject: conditional for-statement References: Message-ID: seb gmail.com> writes: > > Hi, > > i was wondering if there is a syntax alike: > > for i in range(10) if i > 5: > print i for i in range(10): if i > 5: print i From bieffe62 at gmail.com Sun Aug 23 04:12:52 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Sun, 23 Aug 2009 01:12:52 -0700 (PDT) Subject: your favorite debugging tool? References: Message-ID: <7694a678-fb08-4cd4-a1f7-de71e0a26cb2@o6g2000yqj.googlegroups.com> On Aug 22, 4:25?pm, Esmail wrote: > Hi all, > > What is your favorite tool to help you debug your > code? I've been getting along with 'print' statements > but that is getting old and somewhat cumbersome. > > I'm primarily interested in utilities for Linux (but > if you have recommendations for Windows, I'll take > them too :) > > I use emacs as my primary development environment, FWIW. > Someone mentioned winpdb .. anyone have experience/comments > on this? Others? > > Thanks, > Esmail Although like the others I mostly use print statements, in a few occasions I have found useful to resort to a full-blown debugger. Of the ones I have used, the one provided by eclipse+pydev is the one I liked most. The one in pywin32 IDE is basic but can be useful. With emacs, one should be able to use pydb, but I never used that, although emacs is my most used programming environment on most platforms. About print cumbersomeness, I agree. As I posted elsewhere, I'd like a 'trace mechanism' with the following characteristics: 1. Can be enabled/disabled easily, and when it is dsabled it has no runtime costs ( i.e. disabled 'trace' statements do not generate any code) 2. Can be enabled/disabled on a class/function/method base (e.g. enable only the trace in a method ), to only get the trace output from the code you are debugging 3. Make it easy to report the context (i.e. generate messages which starts with 'class.method:', without hanving to hardcode class name and method name). I know about the 'trace' and 'logging' modules, but neither seem to satisfy the above requirements. Probably using python introspection and metaprogramming features it is possible to do somethinmg that covers at least 2 and 3. Not sure about one (using if __debug__ you can reduce the runtime cost when compiling in optimized mode, but probably not nullify it). Ciao ----- FB From mailbox at dmitry-kazakov.de Sun Aug 23 04:21:52 2009 From: mailbox at dmitry-kazakov.de (Dmitry A. Kazakov) Date: Sun, 23 Aug 2009 10:21:52 +0200 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <1gl24ajxu6dsk.1btjdkwwj6m.dlg@40tude.net> On Sat, 22 Aug 2009 14:54:41 -0700 (PDT), James Harris wrote: > They look good - which is important. The trouble (for me) is that I > want the notation for a new programming language and already use these > characters. I have underscore as an optional separator for groups of > digits - 123000 and 123_000 mean the same. The semicolon terminates a > statement. Based on your second idea, though, maybe a colon could be > used instead as in > > 2:1011, 8:7621, 16:c26b > > I don't (yet) use it as a range operator. > > I could also use a hash sign as although I allow hash to begin > comments it cannot be preceded by anything other than whitespace so > these would be usable > > 2#1011, 8#7621, 16#c26b > > I have no idea why Ada which uses the # also apparently uses it to end > a number > > 2#1011#, 8#7621#, 16#c26b# If you are going Unicode, you could use the mathematical notation, which is 10112, 76218, c26b16 (subscript specification of the base). Yes, it might be difficult to type (:-)), and would require some look-ahead in the parser. One of the advantages of Ada notation, is that a numeric literal always starts with decimal digit. That makes things simple for a descent recursive parser. I guess this choice was intentional, back in 1983 a complex parser would eat too much resources... -- Regards, Dmitry A. Kazakov http://www.dmitry-kazakov.de From bieffe62 at gmail.com Sun Aug 23 04:30:16 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Sun, 23 Aug 2009 01:30:16 -0700 (PDT) Subject: conditional for-statement References: Message-ID: On Aug 23, 10:09?am, seb wrote: > Hi, > > i was wondering if there is a syntax alike: > > for i in range(10) if i > 5: > ? ? print i > > equivalent to > > for i in (for i in range(10) if i>5): > ? ? print i > > sebastien AFAIK, no syntax fo that. But the standard syntax is not too different: for i in range(0): if i > 5 : print i Or you can use itertools.ifilter: for i in itertools.ifilter( lambda x: x > 5, range(10) ): print i Or, if you define a function corresponding to the loop body, you could do something like: map( print, (i for i in range(10) if i> 5 )) # only works if print is a function Ciao ---- FB From bearophileHUGS at lycos.com Sun Aug 23 05:09:20 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Sun, 23 Aug 2009 02:09:20 -0700 (PDT) Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <02a0ce27$0$30337$c3e8da3@news.astraweb.com> Message-ID: <6b5ea596-d1e3-483d-ba79-7b139d3c7a47@z24g2000yqb.googlegroups.com> MRAB: >'_': what if in the future we want to allow them in numbers for clarity? Hettinger says it's hard (= requires too many changes) to do that and Python programs don't have big integer constants often enough, so probably that improvement will not see the light. In the meantime in a Python program of mine I have put a small bug, writing 1000000 instead of 10000000. Now in Python I write 10*1000*1000, because I try to learn from my bugs. In D I enjoy writing 10_000_000. ------------------------------- Steven D'Aprano: > In D, at least some people want to follow Python's lead and either drop > support for oct literals completely, or require a 0o prefix:http://d.puremagic.com/issues/show_bug.cgi?id=2656 Yes, people in the D community are trying to improve things, but it's a slow and painful process, and often it goes nowhere. There's lot of politics. Bye, bearophile From harald.luessen at gmx.de Sun Aug 23 05:12:43 2009 From: harald.luessen at gmx.de (Harald Luessen) Date: Sun, 23 Aug 2009 11:12:43 +0200 Subject: IDLE file saving problem References: <70222640-1990-4fae-bbca-8451d252a1ab@13g2000prl.googlegroups.com> Message-ID: <9d12959olkh5l3oamr9lfhedcrqd5nt7v7@4ax.com> On Fri, 21 Aug 2009 14:48:56 -0700 (PDT), r wrote: >On Aug 21, 4:10?pm, MRAB wrote: > >Yes, and much more needs improvement! I have made many changes already >and i am polishing an "IDLE 3000" for the good people of Pythonia, >stay tuned more to come.... There is a small little detail that nags me when I use IDLE: When the cursor is somewhere in the white space at the beginning of the lines and I use Ctrl-rightArrow [ctrl]-[->] to go to the first word in the line then IDLE skips the position with the first non-whitespace letter and places the cursor after the first word in the line. This is not consistent because moving backwards works. [ctrl]-[<-] Similar things happen at the end of a line. I suggest that these movements should consider 'before the first' and 'after the last' text in the line as stop positions. I think other editors do that, at least MS Visual Studio. (The [pos1] alternating between first column and first text in line does not help much.) Harald From 71david at libero.it Sun Aug 23 05:50:30 2009 From: 71david at libero.it (David) Date: Sun, 23 Aug 2009 11:50:30 +0200 Subject: conditional for-statement References: Message-ID: Il Sun, 23 Aug 2009 01:09:04 -0700 (PDT), seb ha scritto: > Hi, > > i was wondering if there is a syntax alike: > > for i in range(10) if i > 5: > print i You can write for i in filter(lambda i: i > 5, range(10)): print i but for i in range(10): if i > 5: print i it' better readable, and for i in range(6,10): print i it's event better. From garabik-news-2005-05 at kassiopeia.juls.savba.sk Sun Aug 23 06:08:43 2009 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Sun, 23 Aug 2009 10:08:43 +0000 (UTC) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: In comp.lang.python James Harris wrote: > On 22 Aug, 10:27, David <71da... at libero.it> wrote: ... >> >> What about 2_1011, 8_7621, 16_c26h or 2;1011, 8;7621, 16;c26h ? > > They look good - which is important. The trouble (for me) is that I > want the notation for a new programming language and already use these > characters. I have underscore as an optional separator for groups of > digits - 123000 and 123_000 mean the same. Why not just use the space? 123 000 looks better than 123_000, and is not syntactically ambiguous (at least in python). And as it already works for string literals, it could be applied to numbers, too? -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From nmm1 at cam.ac.uk Sun Aug 23 06:35:10 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Sun, 23 Aug 2009 11:35:10 +0100 (BST) Subject: Python/Fortran interoperability Message-ID: I am interested in surveying people who want to interoperate between Fortran and Python to find out what they would like to be able to do more conveniently, especially with regard to types not supported for C interoperability by the current Fortran standard. Any suggestions as to other ways that I could survey such people (Usenet is no longer as ubiquitous as it used to be) would be welcomed. My Email address is real, so direct messages will be received. Specifically, I should like to know the answers to the following questions: 1) Do you want to use character strings of arbitrary length? 2) Do you want to use Python classes with list members, where the length of the list is not necessarily fixed for all instances of the class? Or, equivalently, Fortran derived types containing allocatable or pointer arrays? 2) Do you want to use Fortran derived types or Python classes that contain type-bound procedures (including finalizers)? Please answer "yes" whether or nor you would like to call those type-bound procedures from the other language. 4) Do you want to call functions where the called language allocates or deallocates arrays/lists/strings for use by the calling language? Note that this is specifically Fortran->Python and Python->Fortran. Regards, Nick Maclaren. From countryone77 at yahoo.com Sun Aug 23 06:57:49 2009 From: countryone77 at yahoo.com (Bev in TX) Date: Sun, 23 Aug 2009 03:57:49 -0700 (PDT) Subject: logging SMTPhandler Error References: Message-ID: <60de8d40-61f4-4ffd-bcef-749bf06675d0@k19g2000yqn.googlegroups.com> On Aug 23, 12:48?am, a... at pythoncraft.com (Aahz) wrote: > It's also not too difficult to do the moral equivalent with dnspython and > find the MX host for the domain you're trying to send e-mail to; that > usually does not require an encrypted connection. > -- > Aahz (a... at pythoncraft.com) ? ? ? ? ? <*> ? ? ? ?http://www.pythoncraft.com/ > > "I support family values -- Addams family values" --www.nancybuttons.com Thanks :-). I'm not sure that I understand exactly what needs to be done, but I'll read the documentation and see what I can come up with. Bev in TX From sp.bylc at gmail.com Sun Aug 23 07:26:35 2009 From: sp.bylc at gmail.com (newbie) Date: Sun, 23 Aug 2009 04:26:35 -0700 (PDT) Subject: Is Python what I need? Message-ID: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Hi all I'm interested in developing computer based, interactive programs for students in a special school who have an aversion to pen and paper. I've searched the net to find ready made software that will meet my needs but it is either written to a level much higher than these students can cope with or priced beyond our school budget. I came across a blog of someone singing the praises of Python. My question is therefore aimed at those that know what they are talking about (ie users in this group). Is Python the language I need to learn to develop these programs? From contact at xavierho.com Sun Aug 23 07:42:30 2009 From: contact at xavierho.com (Xavier Ho) Date: Sun, 23 Aug 2009 21:42:30 +1000 Subject: Is Python what I need? In-Reply-To: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: <2d56febf0908230442r32088956gb504b0149d2808a7@mail.gmail.com> On Sun, Aug 23, 2009 at 9:26 PM, newbie wrote: > Hi all > I'm interested in developing computer based, interactive programs for > students in a special school who have an aversion to pen and paper. What sort of interactive program? Would it be educational, for example? > I've searched the net to find ready made software that will meet my > needs but it is either written to a level much higher than these > students can cope with or priced beyond our school budget. Could you give us the details of which software you've encountered that were either too expensive or did not meet your needs? > I came across a blog of someone singing the praises of Python. My question > is > therefore aimed at those that know what they are talking about (ie > users in this group). Is Python the language I need to learn to > develop these programs? Any language can do the job. What a program does depends on the design, and specification. Different languages simply have different behaviours, and perhaps platform dependence and requirements. So, in some way, yes, Python can do what you need, but you need to tell us in exact details what you were really looking for. Good luck, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From 71david at libero.it Sun Aug 23 08:01:41 2009 From: 71david at libero.it (David) Date: Sun, 23 Aug 2009 14:01:41 +0200 Subject: your favorite debugging tool? References: Message-ID: <142n6tb9nof0p$.1f2kw0c0vhj8u.dlg@40tude.net> Il Sat, 22 Aug 2009 10:25:37 -0400, Esmail ha scritto: > > I use emacs as my primary development environment, FWIW. > Someone mentioned winpdb .. anyone have experience/comments > on this? Others? I use Winpdb on Windows and I feel quite comfortable. The interface is not so clever as more advanced (and expensive, winpdb is free) debuggers but there is all yuo need for deep-source debugging. It is especially suited for multi threaded programs and GUI debugging, where command line debugging is a pain. It supports remote debugging over encrypted connection also. regards David From pengyu.ut at gmail.com Sun Aug 23 08:37:24 2009 From: pengyu.ut at gmail.com (Peng Yu) Date: Sun, 23 Aug 2009 05:37:24 -0700 (PDT) Subject: Combining python and perl Message-ID: <743337bf-487f-434d-b15c-4b675b6487f4@d21g2000vbm.googlegroups.com> Hi, According to http://www.python.org/doc/essays/comparisons.html, it says "Python and Perl come from a similar background (Unix scripting, which both have long outgrown), and sport many similar features, but have a different philosophy. Perl emphasizes support for common application- oriented tasks, e.g. by having built-in regular expressions, file scanning and report generating features. Python emphasizes support for common programming methodologies such as data structure design and object-oriented programming, and encourages programmers to write readable (and thus maintainable) code by providing an elegant but not overly cryptic notation. As a consequence, Python comes close to Perl but rarely beats it in its original application domain; however Python has an applicability well beyond Perl's niche." My question is that how to combine both python and perl to take advantages of both their strong aspects. Of course, I want to primarily use python---that is why I send this message to this group. I see a module 'perlmodule'. But I would like to know whether there are other tips besides using 'perlmodule' to take perl's advantage in python. Regards, Peng From marduk at letterboxes.org Sun Aug 23 09:00:00 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 23 Aug 2009 09:00:00 -0400 Subject: Combining python and perl In-Reply-To: <743337bf-487f-434d-b15c-4b675b6487f4@d21g2000vbm.googlegroups.com> References: <743337bf-487f-434d-b15c-4b675b6487f4@d21g2000vbm.googlegroups.com> Message-ID: <1251032400.19411.17.camel@centar.nbk> On Sun, 2009-08-23 at 05:37 -0700, Peng Yu wrote: > Hi, > > According to http://www.python.org/doc/essays/comparisons.html, it > says > > "Python and Perl come from a similar background (Unix scripting, which > both have long outgrown), and sport many similar features, but have a > different philosophy. Perl emphasizes support for common application- > oriented tasks, e.g. by having built-in regular expressions, file > scanning and report generating features. Python emphasizes support for > common programming methodologies such as data structure design and > object-oriented programming, and encourages programmers to write > readable (and thus maintainable) code by providing an elegant but not > overly cryptic notation. As a consequence, Python comes close to Perl > but rarely beats it in its original application domain; however Python > has an applicability well beyond Perl's niche." > > My question is that how to combine both python and perl to take > advantages of both their strong aspects. Of course, I want to > primarily use python---that is why I send this message to this group. I'm not sure why you'd want to "combine" them. You can pretty much do the same things with both language, it's just that one may emphasize one thing or make it easier for the user than the other. For example, regular expressions in Perl. It's built into the language, but that doesn't mean Python doesn't have regular expressions, just that Python is less "centered" around them. If you want to use regular expressions with Python just "import re". -a From motoom at xs4all.nl Sun Aug 23 09:05:51 2009 From: motoom at xs4all.nl (Michiel Overtoom) Date: Sun, 23 Aug 2009 15:05:51 +0200 Subject: your favorite debugging tool? In-Reply-To: References: Message-ID: <4A913EAF.8050703@xs4all.nl> Esmail wrote: > What is your favorite tool to help you debug your > code? import pdb pdb.set_trace() pdb has commands to inspect code, variables, set breakpoints, watches, walk up and down stack frames, single-step through the program, run the rest of the function, run until return, etc... http://www.ferg.org/papers/debugging_in_python.html http://onlamp.com/pub/a/python/2005/09/01/debugger.html http://plone.org/documentation/how-to/using-pdb http://docs.python.org/library/pdb.html Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Valloppillil http://www.catb.org/~esr/halloween/halloween4.html From narkewoody at gmail.com Sun Aug 23 09:07:53 2009 From: narkewoody at gmail.com (Steven Woody) Date: Sun, 23 Aug 2009 21:07:53 +0800 Subject: Blank Line at Program Exit In-Reply-To: <20090822152515.GC10584@sevilla.sacredchaos.com> References: <20090822152515.GC10584@sevilla.sacredchaos.com> Message-ID: On Sat, Aug 22, 2009 at 11:25 PM, Nitebirdz wrote: > On Thu, Aug 20, 2009 at 01:31:14PM +0800, Steven Woody wrote: > > Hi, > > Any python program, even that does absolutely nothing in the code, will > > cause a blank line printed out when the program exit. What's the reason? > > Thanks. > > > > Chances are it is related to whichever operating system and/or shell you > are using. For instance, this is taken from a system running Ubuntu > Linux 8.04: > > ------------------------------------------------- > laptop:$ cat hello.py > #!/usr/bin/env python > > print "Hello, there!" > laptop:$ ./hello.py > Hello, there! > laptop:$ cat nothing.py > #!/usr/bin/env python > > laptop:$ ./nothing.py > laptop:$ > ------------------------------------------------- > > > As you can see, no blank line was printed out. > > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, I am using cywin on XP. -- Life is the only flaw in an otherwise perfect nonexistence -- Schopenhauer narke public key at http://subkeys.pgp.net:11371 (narkewoody at gmail.com) -------------- next part -------------- An HTML attachment was scrubbed... URL: From visionat at mail.infochan.com Sun Aug 23 09:08:52 2009 From: visionat at mail.infochan.com (viper-2) Date: Sun, 23 Aug 2009 06:08:52 -0700 (PDT) Subject: Python/Fortran interoperability References: Message-ID: <1f39d176-28e4-4e4f-a4d1-b3168349510b@34g2000yqi.googlegroups.com> On Aug 23, 6:35 am, n... at cam.ac.uk wrote: > I am interested in surveying people who want to interoperate between > Fortran and Python to find out what they would like to be able to do > more conveniently, especially with regard to types not supported for C > interoperability by the current Fortran standard. Python is still on my "to do" list, but I know I'll be interested in the following: > 1) Do you want to use character strings of arbitrary length? > Yes > 2) Do you want to use Python classes with list members, where the > length of the list is not necessarily fixed for all instances of the > class? Or, equivalently, Fortran derived types containing allocatable > or pointer arrays? > Yes > 2) Do you want to use Fortran derived types or Python classes that > contain type-bound procedures (including finalizers)? Please answer > "yes" whether or nor you would like to call those type-bound procedures > from the other language. > Don't know yet > 4) Do you want to call functions where the called language allocates > or deallocates arrays/lists/strings for use by the calling language? > Note that this is specifically Fortran->Python and Python->Fortran. > Yes agt -- Freedom - no pane, all gaiGN! Code Art Now http://codeartnow.com Email: agt at codeartnow.com From narkewoody at gmail.com Sun Aug 23 09:09:24 2009 From: narkewoody at gmail.com (Steven Woody) Date: Sun, 23 Aug 2009 21:09:24 +0800 Subject: How to distribute an application Message-ID: Hi, My application contains a main python source file as well as a set of modules (also .py files). Now, I am considering distribute my application to others. But the distutils seems made for distributing packages not for main applications. Am I right? Thanks. -- Life is the only flaw in an otherwise perfect nonexistence -- Schopenhauer narke public key at http://subkeys.pgp.net:11371 (narkewoody at gmail.com) -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Sun Aug 23 09:11:05 2009 From: aahz at pythoncraft.com (Aahz) Date: 23 Aug 2009 06:11:05 -0700 Subject: Dictionary from a list References: Message-ID: In article , EK wrote: >On Aug 20, 2:10=A0pm, Peter Otten <__pete... at web.de> wrote: >> >> >>> from itertools import izip >> >>> it =3D iter([1,2,3,4,5,6]) >> >>> dict(izip(it, it)) >> >> {1: 2, 3: 4, 5: 6} > >dict(zip(*[iter(l)]*2)) No, that's not a good solution. For starters, it's less readable than Peter's version. More importantly, it has poor memory use because it needs to construct both the intermediate tuple and the zip() list. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From matthew at woodcraft.me.uk Sun Aug 23 09:13:32 2009 From: matthew at woodcraft.me.uk (Matthew Woodcraft) Date: Sun, 23 Aug 2009 13:13:32 GMT Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> Message-ID: <87fxbifzb7.fsf@golux.woodcraft.me.uk> Dennis Lee Bieber writes: > About the only place one commonly sees leading zeros on decimal > numbers, in my experience, is zero-filled COBOL data decks (and since > classic COBOL stores in BCD anyway... binary (usage is > computational/comp-1) was a later add-on to the data specification model > as I recall...) A more common case is dates. I've seen people trip over this writing things like xxx = [ date(2009, 10, 12), date(2009, 12, 26), date(2010, 02, 09), ] -M- From aahz at pythoncraft.com Sun Aug 23 09:14:00 2009 From: aahz at pythoncraft.com (Aahz) Date: 23 Aug 2009 06:14:00 -0700 Subject: logging SMTPhandler Error References: <60de8d40-61f4-4ffd-bcef-749bf06675d0@k19g2000yqn.googlegroups.com> Message-ID: In article <60de8d40-61f4-4ffd-bcef-749bf06675d0 at k19g2000yqn.googlegroups.com>, Bev in TX wrote: >On Aug 23, 12:48=A0am, a... at pythoncraft.com (Aahz) wrote: >> >> It's also not too difficult to do the moral equivalent with dnspython and >> find the MX host for the domain you're trying to send e-mail to; that >> usually does not require an encrypted connection. > >Thanks :-). I'm not sure that I understand exactly what needs to be >done, but I'll read the documentation and see what I can come up with. Slightly expanded: most mail servers accept connections from any other mail server for addresses that are hosted by them. The MX address for a domain tells you what mail server hosts that address. By connecting directly to the MX, your script is essentially acting as a mail server itself. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From ben+python at benfinney.id.au Sun Aug 23 10:01:46 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 24 Aug 2009 00:01:46 +1000 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <87ljlahbn9.fsf@benfinney.id.au> garabik-news-2005-05 at kassiopeia.juls.savba.sk writes: > Why not just use the space? 123 000 looks better than 123_000, and is > not syntactically ambiguous (at least in python). And as it already > works for string literals, it could be applied to numbers, too? +1 to all this. I think this discussion was had many months ago, but can't recall how it ended back then. -- \ ?Only the educated are free.? ?Epictetus, _Discourses_ | `\ | _o__) | Ben Finney From stefan_ml at behnel.de Sun Aug 23 10:21:27 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Aug 2009 16:21:27 +0200 Subject: Python/Fortran interoperability In-Reply-To: References: Message-ID: <4a915067$0$31339$9b4e6d93@newsspool4.arcor-online.net> nmm1 at cam.ac.uk wrote: > I am interested in surveying people who want to interoperate between > Fortran and Python to find out what they would like to be able to do > more conveniently, especially with regard to types not supported for C > interoperability by the current Fortran standard. Any suggestions as to > other ways that I could survey such people (Usenet is no longer as > ubiquitous as it used to be) would be welcomed. You might want to ask also on the Cython, NumPy and SciPy mailing lists. NumPy and SciPy have a rather large audience of scientific developers, and Cython has a running sub-project on providing better Fortran integration (which might be of interest to you anyway). Stefan From jcd at sdf.lonestar.org Sun Aug 23 10:35:22 2009 From: jcd at sdf.lonestar.org (J. Cliff Dyer) Date: Sun, 23 Aug 2009 10:35:22 -0400 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: <87ljlahbn9.fsf@benfinney.id.au> References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> Message-ID: <1251038122.7067.29.camel@webb> I had an objection to using spaces in numeric literals last time around and it still stands, and it still stands in the new one. What happens if you use a literal like 0x10f 304? Is 304 treated as decimal or hexadecimal? It's not clear how you would begin to combine it The way string concatenation works, it takes two independent string literals, and combines them. If you specify r'\n' 'abc\n', the first half is treated independently as a raw string, and the second half is treated as a normal string. The result is '\\nabc\n'. With numeric literals, this behavior doesn't even make sense. How do you concatenate hex 10f with decimal 304? I suppose you could multiply 0x10f by 1000, and add them, but this probably wouldn't fit any practical usecase. Alternatively, you could raise an exception, and require the user to use numeric literals of the same type, like 0x10f 0x304, but then you lose any readability benefit you might have gained by dropping the _ to begin with. If, on the other hand, you want to combine the tokens before processing their independent meanings, which makes the most intuitive sense, well, in that case we're no longer talking about an operation analogous to string contcatenation. We're talking about integers no longer being simple tokens that can be assigned a value. I'm not familiar with the code that makes all this happen in C Python (or any other implementation for that matter), but it seems like it extends the complexity of the parser unnecessarily. I'm concerned that the benefit in readability will be outweighed by the burden it places on the parser, and the cognitive burden on the programmer of knowing what to expect when using non-decimal numeric literals. For that reason, I'm a -1 on using a space in numeric literals, but +1 on using some other separator, and an _, in spite of its slight awkwardness in typing, seems like a good idea. If someone with a solid understanding of the python parser could chime in that this wouldn't cause as much friction as I think, and explain a clean, elegant implementation for this, many of my concerns would be alleviated, and I would change my -1 to a -0. Cheers, Cliff On Mon, 2009-08-24 at 00:01 +1000, Ben Finney wrote: > garabik-news-2005-05 at kassiopeia.juls.savba.sk writes: > > Why not just use the space? 123 000 looks better than 123_000, and is > > not syntactically ambiguous (at least in python). And as it already > > works for string literals, it could be applied to numbers, too? > > +1 to all this. I think this discussion was had many months ago, but > can't recall how it ended back then. > > -- > \ ?Only the educated are free.? ?Epictetus, _Discourses_ | > `\ | > _o__) | > Ben Finney From ryniek90 at gmail.com Sun Aug 23 10:39:42 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Sun, 23 Aug 2009 16:39:42 +0200 Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: References: Message-ID: <4A9154AE.1000609@gmail.com> Hi I've got my backup script which opens tarfile for add chosen file to it. But while setting it up, i've got Traceback: here's the url: -->http://paste.ubuntu.com/258081/<-- I have searched among google's result but didn't found anything useful. Only found info that it may be the backslashes fault in path, but i have written proper the path. Here's link to my script paste: http://paste.ubuntu.com/258087/ Is its the '|\U' literal fault in path '|C:\\Users\\Ryniek's WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2|' ? Sorry if i'm annoying but i'm still learning. | From phillip.oldham at gmail.com Sun Aug 23 11:02:34 2009 From: phillip.oldham at gmail.com (Phillip B Oldham) Date: Sun, 23 Aug 2009 08:02:34 -0700 (PDT) Subject: Most "active" coroutine library project? Message-ID: <64183b73-9cb0-4ce1-98d0-f47e13a818e4@f37g2000yqn.googlegroups.com> I've been taking a look at the multitude of coroutine libraries available for Python, but from the looks of the projects they all seem to be rather "quiet". I'd like to pick one up to use on a current project but can't deduce which is the most popular/has the largest community. Libraries I looked at include: cogen, weightless, eventlet and circuits (which isn't exactly coroutine-based but it's event-driven model was intriguing). Firstly, are there any others I've missed? And what would the consensus be on the which has the most active community behind it? From victorsubervi at gmail.com Sun Aug 23 11:04:57 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 23 Aug 2009 10:04:57 -0500 Subject: Trying To Catch Invalid User Input Message-ID: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> Hi; I have the following: style = raw_input('What style is this? (1 = short, 2 = long): ') flag = 0 while flag == 0: if (style != 1) or (style != 2): style = raw_input('There was a mistake. What style is this? (1 = short, 2 = long): ') else: flag = 1 I would think this would catch errors and permit valid values, but it doesn't. If I enter an erroneous value the first time, and the second time a good value, it doesn't break the loop. Why? TIA, Victor -------------- next part -------------- An HTML attachment was scrubbed... URL: From doctoresam at gmail.com Sun Aug 23 11:12:26 2009 From: doctoresam at gmail.com (Deep_Feelings) Date: Sun, 23 Aug 2009 08:12:26 -0700 (PDT) Subject: can python make web applications? Message-ID: can python make powerfull database web applications that can replace desktop database applications? e.g: entrprise accounting programs,enterprise human resource management programs ...etc From sturlamolden at yahoo.no Sun Aug 23 11:17:56 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 08:17:56 -0700 (PDT) Subject: Python/Fortran interoperability References: Message-ID: <1032c78d-d4dd-41c0-a877-b85ca000d871@g31g2000yqc.googlegroups.com> On 23 Aug, 12:35, n... at cam.ac.uk wrote: > I am interested in surveying people who want to interoperate between > Fortran and Python to find out what they would like to be able to do > more conveniently, especially with regard to types not supported for C > interoperability by the current Fortran standard. ?Any suggestions as to > other ways that I could survey such people (Usenet is no longer as > ubiquitous as it used to be) would be welcomed. I think you will find that 99.9% of Python and Fortran programmers are scientists and engineers that also use NumPy and f2py. Go to scipy.org and ask your question on the numpy mailing list. Regards, Sturla Molden From __peter__ at web.de Sun Aug 23 11:31:47 2009 From: __peter__ at web.de (Peter Otten) Date: Sun, 23 Aug 2009 17:31:47 +0200 Subject: Is Python what I need? References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: newbie wrote: > I'm interested in developing computer based, interactive programs for > students in a special school who have an aversion to pen and paper. > I've searched the net to find ready made software that will meet my > needs but it is either written to a level much higher than these > students can cope with or priced beyond our school budget. I came > across a blog of someone singing the praises of Python. My question is > therefore aimed at those that know what they are talking about (ie > users in this group). Is Python the language I need to learn to > develop these programs? >From the distance it looks like these children need a good teacher rather than a bad (or just starting) programmer. They need goals they can understand and share, not yet another tool. But it's interactive? Yeah, three canned answers instead of just one... That said, Python is a good language for the casual developer. You can whack together something pretty quickly. It may not be perfect, but you don't waste time on administrative overhead either. Peter From python at mrabarnett.plus.com Sun Aug 23 11:36:10 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 23 Aug 2009 16:36:10 +0100 Subject: Trying To Catch Invalid User Input In-Reply-To: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> References: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> Message-ID: <4A9161EA.5050602@mrabarnett.plus.com> Victor Subervi wrote: > Hi; > I have the following: > > style = raw_input('What style is this? (1 = short, 2 = long): ') > flag = 0 > while flag == 0: > if (style != 1) or (style != 2): > style = raw_input('There was a mistake. What style is this? (1 = > short, 2 = long): ') > else: > flag = 1 > > I would think this would catch errors and permit valid values, but it > doesn't. If I enter an erroneous value the first time, and the second > time a good value, it doesn't break the loop. Why? > This is wrong: (style != 1) or (style != 2) For example, if style is 1 (which should be a valid value): (style != 1) or (style != 2) => (1 != 1) or (1 != 2) => False or True => True What you mean is: (style != 1) and (style != 2) From rtomek at ceti.com.pl Sun Aug 23 11:36:32 2009 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Sun, 23 Aug 2009 17:36:32 +0200 Subject: Is Python what I need? In-Reply-To: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: On Sun, 23 Aug 2009, newbie wrote: > Hi all > I'm interested in developing computer based, interactive programs for > students in a special school who have an aversion to pen and paper. > I've searched the net to find ready made software that will meet my > needs but it is either written to a level much higher than these > students can cope with or priced beyond our school budget. I came > across a blog of someone singing the praises of Python. My question is > therefore aimed at those that know what they are talking about (ie > users in this group). Is Python the language I need to learn to > develop these programs? Perhaps, maybe, yes. Python has simple syntax and it can be grasped quite fast. It is also quite easy IMHO to go from easy interactive, calculator-like stuff to bigger things. It also has quite big library of specialized functions, to be used in bigger programs. So if this is what you are looking for, it seems you are in the right place. You may also have a look at Squeak. It is an implementation of Smalltalk language. As far as I can tell, it is targeted for kid users or young students, who are interested in programming. http://en.wikipedia.org/wiki/Smalltalk http://www.squeak.org/ http://en.wikipedia.org/wiki/Squeak Or, I mean, Smalltalk is a general purpose language, just as Python. It is not a "kid language". Squeak, however, seems to be a bit easier for new users. After tinkering with it a little, I think it has few batteries not only included (like Python has) but connected to few toys as well. This makes it more playable than Python after unpacking the box. Wrt languages, their "goodness" or differences between them - I am pretty much sure a number of people will start pointing them out to you. But I don't think this is really that much important. All languages are more or less similar because they serve the same purpose. Just try and do not use (Visual) Basic :-) and you should be ok. Well, maybe this is just me, but I consider VB to be a dead-end. Besides, if this is going to be "let's show them how interesting it is", you should stay away from languages more complicated, like Java. Those who are going to learn Java, will learn it anyway. Knowing something different and cool first should not kill them. Quite the contrary, it can be an eye opener. Regards Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From gherron at islandtraining.com Sun Aug 23 11:37:26 2009 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 23 Aug 2009 08:37:26 -0700 Subject: Trying To Catch Invalid User Input In-Reply-To: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> References: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> Message-ID: <4A916236.6070007@islandtraining.com> Victor Subervi wrote: > Hi; > I have the following: > > style = raw_input('What style is this? (1 = short, 2 = long): ') > flag = 0 > while flag == 0: > if (style != 1) or (style != 2): > style = raw_input('There was a mistake. What style is this? (1 = > short, 2 = long): ') > else: > flag = 1 > > I would think this would catch errors and permit valid values, but it > doesn't. If I enter an erroneous value the first time, and the second > time a good value, it doesn't break the loop. Why? > TIA, > Victor First, raw_input will not return an integer, but rather characters, so the value of style will never be 1 or 2, but rather '1', or '2'. But even if you make your comparisons against '1' and '2', this will not work since you've also made a simple logic error. The conditional if (style != '1') or (style != '2'): will always be True no matter what value style has. For instance if style is '1', then the conditional evaluates like (False) or (True) which evaluates to True. You want one of the following: if (style != '1') and (style != '2'): or if not (style == '1' or style == '2'): or if style == '1' or style == '2': flag = 1 ... or if style in ['1','2']: flag = 1 ... or better yet dispense with flag altogether while style not in ['1','2']: style = raw_input('There was a mistake ... Gary Herron From python-url at phaseit.net Sun Aug 23 11:54:40 2009 From: python-url at phaseit.net (Gabriel Genellina) Date: Sun, 23 Aug 2009 15:54:40 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Aug 23) Message-ID: QOTW: "... [O]nce you accept that text is best handled in Unicode, there's little sense in making an exception for the limited subset that happens to be representable in ASCII." - Ben Finney http://groups.google.com/group/comp.lang.python/msg/accc8c2ae9d7ed15 Python 3.1.1 released: http://groups.google.com/group/comp.lang.python/t/f34c4b07a61f4414/ Parallelization in Python 2.6: http://groups.google.com/group/comp.lang.python/t/c8169c393e58a5d5/ 012=3D=3D10, a relic from ancient times, is finally gone: http://groups.google.com/group/comp.lang.python/t/3bc42fffb012635b/ How to ensure a method is actually implemented in a derived class: http://groups.google.com/group/comp.lang.python/t/42d0ec54b7683f23/ Is this community sexist? (Also, etymology of the word "guy" < "Guy" ~ "Guido") http://groups.google.com/group/comp.lang.python/t/7a190c24d8025bb4/ A "for" loop using range() is inefficient, but other Python variants are able to optimize it: http://groups.google.com/group/comp.lang.python/t/27df793be6f5675/ The scope of names inside a "class" statement: http://groups.google.com/group/comp.lang.python/t/4a244346dc9a5f15/ Counting how many times items from a set appear on a given list: http://groups.google.com/group/comp.lang.python/t/fb0580cefff96682/ Construct a dictionary from a list [key,value,key,value,...] (many recipes!): http://groups.google.com/group/comp.lang.python/t/e16e180b5f61f748/ And more recipes: format a number with thousand separators: http://groups.google.com/group/comp.lang.python/t/2eb729797f162a6e/ Code style: how to write a long conditional expression: http://groups.google.com/group/comp.lang.python/t/6876917a4d579d59/ On the concept of "functor" and how it may be applied to Python: http://groups.google.com/group/comp.lang.python/t/8fbc7ad2ec11841c/ ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Just beginning with Python? This page is a great place to start: http://wiki.python.org/moin/BeginnersGuide/Programmers The Python Papers aims to publish "the efforts of Python enthusiasts": http://pythonpapers.org/ The Python Magazine is a technical monthly devoted to Python: http://pythonmagazine.com Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/group/comp.lang.python.announce/topics Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html The Python Package Index catalogues packages. http://www.python.org/pypi/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donations/ The Summary of Python Tracker Issues is an automatically generated report summarizing new bugs, closed ones, and patch submissions. http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://code.activestate.com/recipes/langs/python/ Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available, see: http://www.python.org/channews.rdf For more, see: http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python Enjoy the *Python Magazine*. http://pymag.phparch.com/ *Py: the Journal of the Python Language* http://www.pyzine.com Dr.Dobb's Portal is another source of Python news and articles: http://www.ddj.com/TechSearch/searchResults.jhtml?queryText=python and Python articles regularly appear at IBM DeveloperWorks: http://www.ibm.com/developerworks/search/searchResults.jsp?searchSite=dW&searchScope=dW&encodedQuery=python&rankprofile=8 Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://search.gmane.org/?query=python+URL+weekly+news+links&group=gmane.comp.python.general&sort=date http://groups.google.com/groups/search?q=Python-URL!+group%3Acomp.lang.python&start=0&scoring=d& http://lwn.net/Search/DoSearch?words=python-url&ctype3=yes&cat_25=yes There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From claird at lairds.us Sun Aug 23 11:55:11 2009 From: claird at lairds.us (Cameron Laird) Date: Sun, 23 Aug 2009 15:55:11 +0000 Subject: [Diversity] Language note References: <20090807143826.GA19246@panix.com> <12470af00908080943g1e559273sdd5e4fc92336a5eb@mail.gmail.com> Message-ID: In article , Rami Chowdhury wrote: > >> Most indian languages have a different >> grammer (compared to English). So i'm curious to see how that would be >> implemented in a parser > >+1 -- I'd be interested in seeing this too, although we have drifted >OT here and perhaps this conversation would be better had on Python- >list. The closest I've seen to a language being able to support >different grammatical structures is Perligata (http:// >www.csse.monash.edu.au/~damian/papers/HTML/Perligata.html), does >Python have anything similar? . . . Yes and no. There's considerably more to say on the subject than my own patience permits for now. Highlights, though: I regard it as a big deal whether a language permits Unicode in spelling variable names (Python 3 does, despite , and presumably you know the situation in Perl); languages like Lisp, Forth, and Tcl have minimal syntax, and rich traditions of construction of problem-specific "little languages", so it's common in them to see, for example, object orientation modeled with a variety of lexical orders; and my own favorite "little-language" work in Python has generally modeled VSO human languages. From bartc at freeuk.com Sun Aug 23 11:57:57 2009 From: bartc at freeuk.com (bartc) Date: Sun, 23 Aug 2009 15:57:57 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <9Gdkm.71135$OO7.46868@text.news.virginmedia.com> wrote in message news:h6r4fb$18a$1 at aioe.org... > In comp.lang.python James Harris wrote: >> On 22 Aug, 10:27, David <71da... at libero.it> wrote: > > ... >>> >>> What about 2_1011, 8_7621, 16_c26h or 2;1011, 8;7621, 16;c26h ? >> >> They look good - which is important. The trouble (for me) is that I >> want the notation for a new programming language and already use these >> characters. I have underscore as an optional separator for groups of >> digits - 123000 and 123_000 mean the same. > > Why not just use the space? 123 000 looks better than 123_000, and > is not syntactically ambiguous (at least in python). If the purpose is to allow "_" to introduce a non-base ten literal, using this to enter a hexadecimal number might result in: 16_1234 ABCD I'd say that that was ambiguous (depending on whether a name can follow a number; if you have a operator called ABCD, then that would be a problem). Unless each block of digits used it's own base: 16_1234 16_ABCD > And as it > already works for string literals, it could be applied to numbers, too? String literals are conveniently surround by quotes, so they're a bit easier to recognise. -- Bart From marduk at letterboxes.org Sun Aug 23 12:08:02 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 23 Aug 2009 12:08:02 -0400 Subject: Trying To Catch Invalid User Input In-Reply-To: <4A9161EA.5050602@mrabarnett.plus.com> References: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> <4A9161EA.5050602@mrabarnett.plus.com> Message-ID: <1251043682.19411.38.camel@centar.nbk> On Sun, 2009-08-23 at 16:36 +0100, MRAB wrote: > Victor Subervi wrote: > > Hi; > > I have the following: > > > > style = raw_input('What style is this? (1 = short, 2 = long): ') > > flag = 0 > > while flag == 0: > > if (style != 1) or (style != 2): > > style = raw_input('There was a mistake. What style is this? (1 = > > short, 2 = long): ') > > else: > > flag = 1 > > > > I would think this would catch errors and permit valid values, but it > > doesn't. If I enter an erroneous value the first time, and the second > > time a good value, it doesn't break the loop. Why? > > > This is wrong: > > (style != 1) or (style != 2) > > For example, if style is 1 (which should be a valid value): > > (style != 1) or (style != 2) > => (1 != 1) or (1 != 2) > => False or True > => True > > What you mean is: > > (style != 1) and (style != 2) Or (perhaps) better: VALID_STYLES = {1: 'short', 2: 'long'} style = None while style not in VALID_STYLES: style = raw_input('What style is this? %s: ' % str(VALID_STYLES).replace(':', ' =')) # also, raw_input() returns a string try: style = int(style) except ValueError: pass From Scott.Daniels at Acm.Org Sun Aug 23 12:12:50 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 23 Aug 2009 09:12:50 -0700 Subject: generate keyboard/mouse event under windows In-Reply-To: <9f107280-5d5c-4e6e-b47b-779e8012fdbc@h30g2000vbr.googlegroups.com> References: <96047669-1bfd-4dbe-bed8-fafea07bbc5a@z34g2000vbl.googlegroups.com> <9f107280-5d5c-4e6e-b47b-779e8012fdbc@h30g2000vbr.googlegroups.com> Message-ID: Ray wrote: > On Aug 19, 2:07 pm, yaka wrote: >> Read this and see if it helps: >> >> http://kvance.livejournal.com/985732.html > > is there a way to generate a 'true' keyboard event? (works like user > pressed a key on keyboard) > not send the 'send keyboard event to application' ? If there is such a spot, it is a major security weakness. You'd be able to automate password attacks. --Scott David Daniels Scott.Daniels at Acm.Org From jjposner at optimum.net Sun Aug 23 12:18:43 2009 From: jjposner at optimum.net (John Posner) Date: Sun, 23 Aug 2009 12:18:43 -0400 Subject: conditional for-statement In-Reply-To: References: Message-ID: <4A916BE3.5010804@optimum.net> >> Hi, >> >> i was wondering if there is a syntax alike: >> >> for i in range(10) if i > 5: >> print i >> > > You can write > > for i in filter(lambda i: i > 5, range(10)): > print i > > but > > for i in range(10): > if i > 5: > print i > > it' better readable, and > > for i in range(6,10): > print i > > it's event better. > > How about using a generator expression instead of a list? for i in (x for x in range(10) if x > 5): print i -John From koranthala at gmail.com Sun Aug 23 12:25:48 2009 From: koranthala at gmail.com (koranthala) Date: Sun, 23 Aug 2009 09:25:48 -0700 (PDT) Subject: can python make web applications? References: Message-ID: <7f0cc793-c4ae-4f7d-87a4-9471f640db89@y4g2000prf.googlegroups.com> On Aug 23, 8:12?pm, Deep_Feelings wrote: > can python make powerfull database web applications that can replace > desktop database applications? e.g: entrprise accounting > programs,enterprise human resource management programs ...etc Very much so. The web frameworks, Django & TurboGears are quite powerful and can be used to do what you just now mentioned. Check out Django - esp if the application is database centric. It has very good documentation and a free online book - djangobook. From victorsubervi at gmail.com Sun Aug 23 12:27:48 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Sun, 23 Aug 2009 11:27:48 -0500 Subject: Trying To Catch Invalid User Input In-Reply-To: <1251043682.19411.38.camel@centar.nbk> References: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> <4A9161EA.5050602@mrabarnett.plus.com> <1251043682.19411.38.camel@centar.nbk> Message-ID: <4dc0cfea0908230927m45420f3dxbae2c42c95540c59@mail.gmail.com> Really slick! Thanks! V On Sun, Aug 23, 2009 at 11:08 AM, Albert Hopkins wrote: > On Sun, 2009-08-23 at 16:36 +0100, MRAB wrote: > > Victor Subervi wrote: > > > Hi; > > > I have the following: > > > > > > style = raw_input('What style is this? (1 = short, 2 = long): ') > > > flag = 0 > > > while flag == 0: > > > if (style != 1) or (style != 2): > > > style = raw_input('There was a mistake. What style is this? (1 = > > > short, 2 = long): ') > > > else: > > > flag = 1 > > > > > > I would think this would catch errors and permit valid values, but it > > > doesn't. If I enter an erroneous value the first time, and the second > > > time a good value, it doesn't break the loop. Why? > > > > > This is wrong: > > > > (style != 1) or (style != 2) > > > > For example, if style is 1 (which should be a valid value): > > > > (style != 1) or (style != 2) > > => (1 != 1) or (1 != 2) > > => False or True > > => True > > > > What you mean is: > > > > (style != 1) and (style != 2) > > Or (perhaps) better: > > VALID_STYLES = {1: 'short', 2: 'long'} > > style = None > while style not in VALID_STYLES: > style = raw_input('What style is this? %s: ' % > str(VALID_STYLES).replace(':', ' =')) > > # also, raw_input() returns a string > try: > style = int(style) > except ValueError: > pass > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nmm1 at cam.ac.uk Sun Aug 23 12:34:16 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Sun, 23 Aug 2009 17:34:16 +0100 (BST) Subject: Python/Fortran interoperability References: <1032c78d-d4dd-41c0-a877-b85ca000d871@g31g2000yqc.googlegroups.com> Message-ID: In article <1032c78d-d4dd-41c0-a877-b85ca000d871 at g31g2000yqc.googlegroups.com>, sturlamolden wrote: >On 23 Aug, 12:35, n... at cam.ac.uk wrote: > >> I am interested in surveying people who want to interoperate between >> Fortran and Python to find out what they would like to be able to do >> more conveniently, especially with regard to types not supported for C >> interoperability by the current Fortran standard. =A0Any suggestions as t= >o >> other ways that I could survey such people (Usenet is no longer as >> ubiquitous as it used to be) would be welcomed. > >I think you will find that 99.9% of Python and Fortran programmers are >scientists and engineers that also use NumPy and f2py. Go to scipy.org >and ask your question on the numpy mailing list. > >Regards, >Sturla Molden > > > Thanks. I had forgotten they had a mailing list. Nick. From dmw at coder.cl Sun Aug 23 12:35:33 2009 From: dmw at coder.cl (Daniel Molina Wegener) Date: Sun, 23 Aug 2009 12:35:33 -0400 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module Message-ID: <2571343.k9db9GJWqV@coder.cl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Hello, I'm pleased to announce pyxser-1.2r, a Python-Object to XML serializer and deserializer. This module package it's completely written in C and licensed under LGPLv3. The tested Python versions are 2.5.X and 2.7.X. * home page: ? http://coder.cl/software/pyxser * hosted at: ? http://sourceforge.net/projects/pyxser/ * pypi entry: ? http://pypi.python.org/pypi?:action=display&name=pyxser&version=1.2r The current ChangeLog is as follows: - -----8<----------8<----------8<----------8<----- 1.2r (2009.08.23): ? ? ? ? Daniel Molina Wegener ? ? ? ? * Added encoded serialization of Unicode strings by using ? ? ? ? the user defined encoding as is passed to the serialization ? ? ? ? functions as enc parameter ? ? ? ? * Refactored some functions to allow more ordered code. - -----8<----------8<----------8<----------8<----- As you see, now Unicode strings are serialized as encoded byte string by using the encoding that the user pass as enc parameter to the serialization function. This means that Unicode strings are serialized in a human readable form, regarding a better interoperability with other platforms. Best regards... - -- ?.O. | Daniel Molina Wegener ? | FreeBSD & Linux ?..O | dmw [at] coder [dot] cl | Open Standards ?OOO | http://coder.cl/ ? ? ? ?| FOSS Developer -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (FreeBSD) iQIcBAEBCgAGBQJKkW/VAAoJEHxqfq6Y4O5N36oP/3iV+D9YUgLStFoZiJvb5b7x +UyrfyWpg6oxqeH4oOUVmyrWYlIaM3IStOtCayYEIrRJeg7FfHM8rvUV89FhDgVy xb/4R9UyqSOqcev/edmXvhbUKfOjUDu/kaKNjK4HiI3Ewh6BBjxbythZSQ/BcvGc OzAsZU9bACbuTuiYLumoum/KjRg/13Tzc8R+xhugJ7fjqH94kWGmUN8l8E/DU7O1 IULm4da4y4mPzhdyIxIGzncOGEZmQLLcv7jYcMVBvkuXe8Ar0WlGQ6YjyvQMLVlz KBn5JiNC1/gzImQXXDfT2u454gyH86i7BRtOCk0RbUmTVFsQ32wjnF0u4bngrtm7 3dD0WVIWV/n/27UZtYte3YlVoHzYu+M6TsX9vwhxvg4SHvg74XigXuXgD8vWQxGE FP6YENbHOND3oSNJIRO9368irvCbYrcpndtYBLyyDlfwdN5YTAME+Z5eEGvl4j4P D7aPryOKCzklxv33qtA1si6f//4JPqdKHGXnl8ysPC7QWh6u+ImmYFYj2kAu7l/N PfUvf8hfQqWOz53W4AuFGg5u+L29TIMUUvxc4r446SFdLUZEaHueJ5GQ0G8uNF/B QoWUnwynLlasyeo+JTcrG9NBgm85QfT3jDd+z4Zba9yWCqojymOpVCQ5duKifMb3 x9fc1ulI44AGNAv+UhnB =4C1g -----END PGP SIGNATURE----- From foo at bar.invalid Sun Aug 23 13:06:48 2009 From: foo at bar.invalid (JB) Date: Sun, 23 Aug 2009 20:06:48 +0300 (EEST) Subject: Python/Fortran interoperability References: Message-ID: ["Followup-To:" header set to comp.lang.fortran.] On 2009-08-23, nmm1 at cam.ac.uk wrote: > > I am interested in surveying people who want to interoperate between > Fortran and Python to find out what they would like to be able to do > more conveniently, especially with regard to types not supported for C > interoperability by the current Fortran standard. Any suggestions as to > other ways that I could survey such people (Usenet is no longer as > ubiquitous as it used to be) would be welcomed. > > My Email address is real, so direct messages will be received. > > Specifically, I should like to know the answers to the following > questions: > > 1) Do you want to use character strings of arbitrary length? As in, a signed C int (that most Fortran implementations use to keep track of string lengths) may not be sufficient? No, I'm not particularly interested in that. > 2) Do you want to use Python classes with list members, where the > length of the list is not necessarily fixed for all instances of the > class? Or, equivalently, Fortran derived types containing allocatable > or pointer arrays? Yes. > 2) Do you want to use Fortran derived types or Python classes that > contain type-bound procedures (including finalizers)? Please answer > "yes" whether or nor you would like to call those type-bound procedures > from the other language. In python I use it all the time, haven't used any F2003 OOP features yet. > 4) Do you want to call functions where the called language allocates > or deallocates arrays/lists/strings for use by the calling language? > Note that this is specifically Fortran->Python and Python->Fortran. Yes. Generally speaking, f2py today is not that bad, though it's getting long in the tooth. There is a project called fwrap that aims to create an improved python/Fortran bridge: http://conference.scipy.org/static/wiki/smith_fwrap.pdf This project uses ISO_C_BINDING, and I think that this is the correct approach rather than trying to keep up with whatever ABI's all those Fortran compilers use. So from the Fortran side of the fence, I suppose the path forward would be to improve on the C binding functionality (this would also of course benefit other language bindings than just python). Whether TR 29113 is the right path forward or not I have no strong opinion on. Specifically what's needed is some way to portably access the array descriptor data, and maybe also how to access the OOP functionality in a standardized way. The experience with C++ ABI's suggests that this might not be as straightforward as it sounds. -- JB From matthew at woodcraft.me.uk Sun Aug 23 13:23:06 2009 From: matthew at woodcraft.me.uk (Matthew Woodcraft) Date: Sun, 23 Aug 2009 17:23:06 GMT Subject: Most "active" coroutine library project? References: <64183b73-9cb0-4ce1-98d0-f47e13a818e4@f37g2000yqn.googlegroups.com> Message-ID: <87ab1qfnr9.fsf@golux.woodcraft.me.uk> Phillip B Oldham writes: > I've been taking a look at the multitude of coroutine libraries > available for Python, but from the looks of the projects they all seem > to be rather "quiet". I'd like to pick one up to use on a current > project but can't deduce which is the most popular/has the largest > community. > > Libraries I looked at include: cogen, weightless, eventlet and > circuits (which isn't exactly coroutine-based but it's event-driven > model was intriguing). > > Firstly, are there any others I've missed? There's greenlets http://pypi.python.org/pypi/greenlet which I think is also fairly described as "quiet". -M- From james.harris.1 at googlemail.com Sun Aug 23 14:11:36 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Sun, 23 Aug 2009 11:11:36 -0700 (PDT) Subject: Annoying octal notation References: <2h2hwo918umw.1ihpdwjimzge8$.dlg@40tude.net> Message-ID: <583bb6bd-9723-4ff7-bc0e-d58782cf9296@k30g2000yqf.googlegroups.com> On 21 Aug, 00:59, James Harris wrote: ... > > Is there some magic to make the 2.x CPython interpreter to ignore the > > annoying octal notation? > > I'd really like 012 to be "12" and not "10". > > This is (IMHO) a sad hangover from C (which took it from B ... This seemed worth writing up so I've taken the snipped comments and posted them at http://sundry.wikispaces.com/octal-zero-prefix The idea is that the page can be pointed to any time the issue comes up again. I've also fleshed the comments out a bit. James From aahz at pythoncraft.com Sun Aug 23 14:12:00 2009 From: aahz at pythoncraft.com (Aahz) Date: 23 Aug 2009 11:12:00 -0700 Subject: Polling a net address References: <99ddf4e1-d327-4fb1-aee4-aa881de3b3af@d23g2000vbm.googlegroups.com> Message-ID: In article <99ddf4e1-d327-4fb1-aee4-aa881de3b3af at d23g2000vbm.googlegroups.com>, Iain wrote: > >I'm writing a system tray application for windows, and the app needs >to poll a remote site at a pre-defined interval, and then process any >data returned. > >The GUI needs to remain responsive as this goes on, so the polling >needs to be done in the background. I've been looking into Twisted as >a way of achieving this, but can't seem to get anything to loop >successfully. > >Does anyone have any pointers that they might be able to give me? You might prefer trying out threads instead; there's a simple Tkinter example in http://www.pythoncraft.com/OSCON2001/index.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From stefaan.himpe at gmail.com Sun Aug 23 14:32:04 2009 From: stefaan.himpe at gmail.com (Stefaan Himpe) Date: Sun, 23 Aug 2009 20:32:04 +0200 Subject: can python make web applications? In-Reply-To: References: Message-ID: Deep_Feelings wrote: > can python make powerfull database web applications that can replace > desktop database applications? e.g: entrprise accounting > programs,enterprise human resource management programs ...etc In addition to the recommendations by other people, I'd like to recommend the very easy to learn and use web2py. (www.web2py.com). From nmm1 at cam.ac.uk Sun Aug 23 14:42:51 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Sun, 23 Aug 2009 19:42:51 +0100 (BST) Subject: Python/Fortran interoperability References: Message-ID: In article , JB wrote: >["Followup-To:" header set to comp.lang.fortran.] Sorry - set back again, because you don't provide an Email address, and there's a significant issue. Thanks for the response. >> 1) Do you want to use character strings of arbitrary length? > >As in, a signed C int (that most Fortran implementations use to keep >track of string lengths) may not be sufficient? No, I'm not >particularly interested in that. No, I mean things like 'Kilroy was here'. Currently, Fortran's C interoperability supports only strings of length 1, and you have to kludge them up as arrays. That doesn't work very well, especially for things like function results. >Generally speaking, f2py today is not that bad, though it's getting >long in the tooth. There is a project called fwrap that aims to create >an improved python/Fortran bridge: Thanks. I will look at that. >This project uses ISO_C_BINDING, and I think that this is the correct >approach rather than trying to keep up with whatever ABI's all those >Fortran compilers use. So from the Fortran side of the fence, I >suppose the path forward would be to improve on the C binding >functionality (this would also of course benefit other language >bindings than just python). Whether TR 29113 is the right path forward >or not I have no strong opinion on. Specifically what's needed is some >way to portably access the array descriptor data, and maybe also how >to access the OOP functionality in a standardized way. The experience >with C++ ABI's suggests that this might not be as straightforward as >it sounds. That is precisely what I am investigating. TR 29113 falls a LONG way before it gets to any of the OOP data - indeed, you can't even pass OOP derived types as pure data (without even the functionality) in its model. Nor most of what else Python would expect. Regards, Nick Maclaren. From rami.chowdhury at gmail.com Sun Aug 23 14:48:50 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Sun, 23 Aug 2009 11:48:50 -0700 Subject: Questions on XML In-Reply-To: <97c638a50908221327ge57818ahc1bb4c9ad3eb186b@mail.gmail.com> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <97c638a50908221327ge57818ahc1bb4c9ad3eb186b@mail.gmail.com> Message-ID: <200908231148.51151.rami.chowdhury@gmail.com> My problem is with IDLE on Windows. When I try to type Bangla directly into the IDLE window I only get '?' characters, and repr() fails with a UnicodeDecodeError. I expect, though, that that's because of my specific installation / Windows issues, as it works fine on Fedora 10... > I do not get any problem in processing Hindi or Bangla or any Indian > language in Python it is perfectly fine. I have no problems either -- my issues are with IDLE, and only on Windows. ---- Rami Chowdhury "Strangers are just friends who haven't had enough gin." -- Howdle's Saying 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) On Saturday 22 August 2009 13:27:02 SUBHABRATA BANERJEE wrote: > Should I help you? If you answered my questions I am differing from your > view I do not get any problem in processing Hindi or Bangla or any Indian > language in Python it is perfectly fine. > Best Regards, > Subhabrata. > > On Sat, Aug 22, 2009 at 9:48 AM, Rami Chowdhury wrote: > > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > > > >> use Python to help me in this regard? > > > > I can say from experience that Python on Windows (at least, Python 2.5 on > > 32-bit Vista) works perfectly well with UTF-8 files containing Bangla. I > > have had trouble with working with the data in IDLE, however, which seems > > to prefer ASCII by default. > > > > ------------- > > Rami Chowdhury > > "Never assume malice when stupidity will suffice." -- Hanlon's Razor > > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > > > > > > > > > > > > On Aug 21, 2009, at 19:15 , joy99 wrote: > > > > Dear Group, > > > >> I like to convert some simple strings of natural language to XML. May > >> I use Python to do this? If any one can help me, on this. > >> > >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > >> use Python to help me in this regard? > >> > >> How can I learn good XML aspects of Python. If any one can kindly name > >> me a book or URL. > >> > >> I am using Python2.6 on Windows XP with IDLE as GUI. > >> > >> Best Regards, > >> Subhabrata. > >> -- > >> http://mail.python.org/mailman/listinfo/python-list From stefan_ml at behnel.de Sun Aug 23 14:52:16 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Aug 2009 20:52:16 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> Message-ID: <4a918fe0$0$30226$9b4e6d93@newsspool1.arcor-online.net> Simon Brunning wrote: > 2009/8/11 Robert Dailey: >> On Aug 11, 3:40 pm, Bearophile wrote: >>> There are gals too here. >> It's a figure of speech. And besides, why would I want programming >> advice from a woman? lol. Thanks for the help. > > Give the attitudes still prevalent in our industry (cf > and many more), I'm sorry to say that I > don't think this is funny. Me neither. I used to reply with comments like "you just missed more than half of the world's population" to people who started their postings with "hi guys!", and I stopped doing that as a) it became too tiring, especially on a potentially-for-newbees group like c.l.py, and b) to many people it actually *is* a figure of speech. But reading statements like the above really makes me feel that it's best to comment even on simple things like "hi guys!". Stefan From stefan_ml at behnel.de Sun Aug 23 15:11:57 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Aug 2009 21:11:57 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <90cd2c33-5f2d-4a29-b267-67f233ae2946@r24g2000vbn.googlegroups.com> <4A8ADF6D.2030405@sequans.com> Message-ID: <4a91947d$0$30226$9b4e6d93@newsspool1.arcor-online.net> Jean-Michel Pichavant wrote: > Grant Edwards wrote: >> On 2009-08-18, Simon Forman wrote: >>> Sexism, racism, homophobia, religious intolerance, etc., all >>> stem from a fundamental forgetfulness of our Unity in God (as >>> I would put it) and this is perhaps the single greatest cause >>> of human misery. >> >> You mean the single greatest cause of human misery isn't >> Microsoft Windows? >> > No, emacs is responsible ! Hail to Vi ! Heck, where's Godwin's law when you need it? Stefan From stefan_ml at behnel.de Sun Aug 23 15:25:51 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Aug 2009 21:25:51 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <62dbf088-4510-40d0-af3e-3feeb291d6e4@t13g2000yqt.googlegroups.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> <86bb893a-344a-4c7b-9fc6-67d9f42c7607@q14g2000vbi.googlegroups.com> <62dbf088-4510-40d0-af3e-3feeb291d6e4@t13g2000yqt.googlegroups.com> Message-ID: <4a9197c0$0$30226$9b4e6d93@newsspool1.arcor-online.net> Mensanator wrote: > asking how many Jews you can fit into a Volswagen. None, because it's already full. (or "voll" as those who design Volkswagens would put it...) Stefan From voodoorai2000 at gmail.com Sun Aug 23 15:47:21 2009 From: voodoorai2000 at gmail.com (Raimond Garcia) Date: Sun, 23 Aug 2009 21:47:21 +0200 Subject: Is python faster than java? Message-ID: I'm building a large application, kind of fancy python but I'm concerned about speed. Cheers Peter -------------- next part -------------- An HTML attachment was scrubbed... URL: From pengyu.ut at gmail.com Sun Aug 23 15:54:15 2009 From: pengyu.ut at gmail.com (Peng Yu) Date: Sun, 23 Aug 2009 12:54:15 -0700 (PDT) Subject: Combining python and perl References: <743337bf-487f-434d-b15c-4b675b6487f4@d21g2000vbm.googlegroups.com> Message-ID: On Aug 23, 8:00?am, Albert Hopkins wrote: > On Sun, 2009-08-23 at 05:37 -0700, Peng Yu wrote: > > Hi, > > > According tohttp://www.python.org/doc/essays/comparisons.html, it > > says > > > "Python and Perl come from a similar background (Unix scripting, which > > both have long outgrown), and sport many similar features, but have a > > different philosophy. Perl emphasizes support for common application- > > oriented tasks, e.g. by having built-in regular expressions, file > > scanning and report generating features. Python emphasizes support for > > common programming methodologies such as data structure design and > > object-oriented programming, and encourages programmers to write > > readable (and thus maintainable) code by providing an elegant but not > > overly cryptic notation. As a consequence, Python comes close to Perl > > but rarely beats it in its original application domain; however Python > > has an applicability well beyond Perl's niche." > > > My question is that how to combine both python and perl to take > > advantages of both their strong aspects. Of course, I want to > > primarily use python---that is why I send this message to this group. > > I'm not sure why you'd want to "combine" them. ?You can pretty much do > the same things with both language, it's just that one may emphasize one > thing or make it easier for the user than the other. ?For example, > regular expressions in Perl. ?It's built into the language, but that > doesn't mean Python doesn't have regular expressions, just that Python > is less "centered" around them. ?If you want to use regular expressions > with Python just "import re". I understand that the sames things can be done with both language. But I do think that certain applications can be done faster (in term of the coding & debugging time, I don't care runtime here) with one language than with another. Therefore, for any give problem, it is meaningful to decide, based on the time to write and debug the code, which part should be programmed with perl and which part should be programed with python. However, when I split the code in perl and python, the problem of the integration is introduced, which incur additional coding and maintenance cost. I am sure that somebody must has already encounter the similar situation like I described above. I am wondering whether there are any advices on how to take advantages of both languages to speed up the code development time and reduce maintenance cost. Regards, Peng From emile at fenx.com Sun Aug 23 15:59:37 2009 From: emile at fenx.com (Emile van Sebille) Date: Sun, 23 Aug 2009 12:59:37 -0700 Subject: Is python faster than java? In-Reply-To: References: Message-ID: On 8/23/2009 12:47 PM Raimond Garcia said... > I'm building a large application, What kind of application? > kind of fancy python but I'm concerned > about speed. Speed of what? Development? User interaction? Responsiveness to queries? Mostly, you should worry about speed later. Writing it in python is probably faster than java. Then optimize the slow bits once you've identified where its needed. Emile From brannerchinese at gmail.com Sun Aug 23 16:13:16 2009 From: brannerchinese at gmail.com (David Prager Branner) Date: Sun, 23 Aug 2009 13:13:16 -0700 (PDT) Subject: web frameworks that support Python 3 Message-ID: I use Chinese and therefore Unicode very heavily, and so Python 3 is an unavoidable choice for me. But I'm frustrated by the fact that Django, Pylons, and TurboGears do not support Python 3 yet and (according to their development websites) will not for a very long time to come. So I am asking for recommendations for web frameworks that support Python 3. I am running Ubuntu 9.04 (Jaunty). Thanks! From max at alcyone.com Sun Aug 23 16:14:41 2009 From: max at alcyone.com (Erik Max Francis) Date: Sun, 23 Aug 2009 13:14:41 -0700 Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: References: Message-ID: Ryniek90 wrote: > I've got my backup script which opens tarfile for add chosen file to it. > But while setting it up, i've got Traceback: > here's the url: -->http://paste.ubuntu.com/258081/<-- > > I have searched among google's result but didn't found anything useful. > Only found info that it may be the backslashes fault in path, but i have > written proper the path. > > Here's link to my script paste: http://paste.ubuntu.com/258087/ > > Is its the '|\U' literal fault in path '|C:\\Users\\Ryniek's > WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2|' ? > > Sorry if i'm annoying but i'm still learning. It's probably a misleading error from the OS; I would guess the problem is that the filename contains colons, which I believe is a no-no on Windows. You want to make sure to always escape your backslashes (or use raw strings), too, or that's going to bite you sometime later (but it's not your main problem here). -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Every human being is a problem in search of a solution. -- Ashley Montague From marduk at letterboxes.org Sun Aug 23 16:32:09 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 23 Aug 2009 16:32:09 -0400 Subject: web frameworks that support Python 3 In-Reply-To: References: Message-ID: <1251059529.12426.23.camel@centar.nbk> On Sun, 2009-08-23 at 13:13 -0700, David Prager Branner wrote: > I use Chinese and therefore Unicode very heavily, and so Python 3 is > an unavoidable choice for me. But I'm frustrated by the fact that > Django, Pylons, and TurboGears do not support Python 3 yet and > (according to their development websites) will not for a very long > time to come. > > So I am asking for recommendations for web frameworks that support > Python 3. I am running Ubuntu 9.04 (Jaunty). Python 2.x has Unicode. In fact Django and the like use unicode heavily. What's different about Python 3 is that there is only unicode strings, whereas Python 2 has a string type and a unicode type. So it's not true that Python 3 is an unavoidable choice for using unicode. From basti.wiesner at gmx.net Sun Aug 23 16:34:50 2009 From: basti.wiesner at gmx.net (Sebastian Wiesner) Date: Sun, 23 Aug 2009 22:34:50 +0200 Subject: web frameworks that support Python 3 In-Reply-To: References: Message-ID: <200908232234.58373.basti.wiesner@gmx.net> At Sunday 23 August 2009 22:13:16 you wrote: > I use Chinese and therefore Unicode very heavily, and so Python 3 is > an unavoidable choice for me. Python 2.x supports Unicode just as well as Python 3. Every common web framework works perfectly with unicode. In any case, there is bottle [1], which provides a *very minimal* framework for WSGI web development. Don't expect too much, it is really small, and doesn't do much more than routing and minimal templating. However, it is the only Python-3-compatible web framework I know of. [1] http://bottle.paws.de/page/start -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 205 bytes Desc: This is a digitally signed message part. URL: From marduk at letterboxes.org Sun Aug 23 16:34:55 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 23 Aug 2009 16:34:55 -0400 Subject: Combining python and perl In-Reply-To: References: <743337bf-487f-434d-b15c-4b675b6487f4@d21g2000vbm.googlegroups.com> Message-ID: <1251059695.12426.27.camel@centar.nbk> On Sun, 2009-08-23 at 12:54 -0700, Peng Yu wrote: > I understand that the sames things can be done with both language. > > But I do think that certain applications can be done faster (in term > of the coding & debugging time, I don't care runtime here) with one > language than with another. Yes, and usually that application is written in that language *or* the other. > Therefore, for any give problem, it is > meaningful to decide, based on the time to write and debug the code, > which part should be programmed with perl and which part should be > programed with python. However, when I split the code in perl and > python, the problem of the integration is introduced, which incur > additional coding and maintenance cost. > Couldn't agree more. > I am sure that somebody must has already encounter the similar > situation like I described above. I am wondering whether there are any > advices on how to take advantages of both languages to speed up the > code development time and reduce maintenance cost. Perhaps you need to give more specific criteria. I've worked on a few projects where different languages are used, but in different "domains". For example, the client may be written in Python but the server written in Java or PHP. Or different subsystems written in different languages. For example, the workflow engine may be written in Python but the batch processor written in C. However in these cases, for the most part, the systems themselves are monolingual though they communicate with each other using well-defined, common interfaces (e.g. TCP/IP, XMLRPC, HL7, etc.). If, however, you are thinking of writing a sub-system in multiple languages (ala permodule, for example), you are in for a world of hurt. Not only will the code be difficult to maintain yourself, it will be difficult for others to maintain/understand it. Most people don't say things like "Well I'm going to write all the 'object' stuff in Python but all the string processing in Perl. What usually motivates people to write systems in multiple languages are: * Availability of third-party libraries in a certain language. * Combining separate systems written in different languages. * Developer's capabilities in one language or the other * External dependencies (e.g. need to to have a plugin system for people to program in Python). * Performance. * Other types of "glue" (e.g. installation scripts need to be written in Perl, test system is Java based so CI scripts need to be in Java). permodule is nice for "simple" or "one-off" kind of stuff (or for any of the above reasons). But any reasonably-sized application using something like that throughout is going to be a maintenance nightmare. From sdementen at gmail.com Sun Aug 23 16:36:10 2009 From: sdementen at gmail.com (seb) Date: Sun, 23 Aug 2009 13:36:10 -0700 (PDT) Subject: conditional for-statement References: Message-ID: On Aug 23, 6:18?pm, John Posner wrote: > >> Hi, > > >> i was wondering if there is a syntax alike: > > >> for i in range(10) if i > 5: > >> ? ? print i > > > You can write > > > for i in filter(lambda i: i > 5, range(10)): > > ? ? print i > > > but > > > for i in range(10): > > ? ? if i > 5: > > ? ? ? ? print i > > > it' better readable, and > > > for i in range(6,10): > > ? ? print i > > > it's event better. > > How about using a generator expression instead of a list? > > ? for i in (x for x in range(10) if x > 5): > ? ? ? print i > > -John Indeed, but we could have the same syntax than for generators but directly in the for statement as in for variable in generator if condition: body Is there a special reason for not doing so ? A rejected PEP ? From stefan_ml at behnel.de Sun Aug 23 16:43:20 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Sun, 23 Aug 2009 22:43:20 +0200 Subject: web frameworks that support Python 3 In-Reply-To: References: Message-ID: <4a91a9e8$0$30226$9b4e6d93@newsspool1.arcor-online.net> David Prager Branner wrote: > I use Chinese and therefore Unicode very heavily, and so Python 3 is > an unavoidable choice for me. As others noted before, this statement is not true by itself. > But I'm frustrated by the fact that > Django, Pylons, and TurboGears do not support Python 3 yet and > (according to their development websites) will not for a very long > time to come. http://wiki.python.org/moin/PortingDjangoTo3k Stefan From pyklass at gmail.com Sun Aug 23 16:45:17 2009 From: pyklass at gmail.com (Goke Aruna) Date: Sun, 23 Aug 2009 21:45:17 +0100 Subject: can python make web applications? In-Reply-To: References: Message-ID: <30ef32480908231345l1d3f96eqb59825fdd2d2e1cd@mail.gmail.com> A lot check this fantastic open source application, http://www.openerp.com, all done is python. On 8/23/09, Stefaan Himpe wrote: > Deep_Feelings wrote: >> can python make powerfull database web applications that can replace >> desktop database applications? e.g: entrprise accounting >> programs,enterprise human resource management programs ...etc > > In addition to the recommendations by other people, I'd like to > recommend the very easy to learn and use web2py. (www.web2py.com). > -- > http://mail.python.org/mailman/listinfo/python-list > -- Sent from my mobile device From voodoorai2000 at gmail.com Sun Aug 23 16:49:32 2009 From: voodoorai2000 at gmail.com (Raimond Garcia) Date: Sun, 23 Aug 2009 22:49:32 +0200 Subject: Is python faster than java? In-Reply-To: References: Message-ID: Makes sense. +1 Cheers Peter On Sun, Aug 23, 2009 at 9:59 PM, Emile van Sebille wrote: > On 8/23/2009 12:47 PM Raimond Garcia said... > >> I'm building a large application, >> > > What kind of application? > > kind of fancy python but I'm concerned about speed. >> > > Speed of what? Development? User interaction? Responsiveness to queries? > Mostly, you should worry about speed later. Writing it in python is > probably faster than java. Then optimize the slow bits once you've > identified where its needed. > > Emile > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From james.harris.1 at googlemail.com Sun Aug 23 16:55:19 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Sun, 23 Aug 2009 13:55:19 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <4a90b50e.154654859@text.giganews.com> Message-ID: <9411f79a-934f-494c-93bc-dc020646f281@z24g2000yqb.googlegroups.com> On 23 Aug, 04:38, c... at tiac.net (Richard Harter) wrote: > On Sat, 22 Aug 2009 14:54:41 -0700 (PDT), James Harris > > > > > > wrote: > >On 22 Aug, 10:27, David <71da... at libero.it> wrote: > > >... (snipped a discussion on languages and other systems interpreting > >numbers with a leading zero as octal) > > >> > Either hexadecimal should have been 0h or octal should > >> > have been 0t :=3D) > > >> I have seen the use of Q/q instead in order to make it clearer. I still > >> prefer Smalltalk's 16rFF and 8r377. > > >> Two interesting options. In a project I have on I have also considered > >> using 0q as indicating octal. I maybe saw it used once somewhere else > >> but I have no idea where. 0t was a second choice and 0c third choice > >> (the other letters of oct). 0o should NOT be used for obvious reasons. > > >> So you are saying that Smalltalk has r where > >> r is presumably for radix? That's maybe best of all. It preserves the > >> syntactic requirement of starting a number with a digit and seems to > >> have greatest flexibility. Not sure how good it looks but it's > >> certainly not bad. > > I opine that a letter is better; special characters are a > valuable piece of real estate. Very very true. > ?However for floating point you > need at least three letters because a floating point number has > three parts: the fixed point point, the exponent base, and the > exponent. ?Now we can represent the radices of the individual > parts with the 'r'scheme, e.g., 2r101001, but we need separate > letters to designate the exponent base and the exponent. ?B and E > are the obvious choices, though we want to be careful about a > confusion with 'b' in hex. ?For example, using 'R', > > 3R20.1B2E16Rac Ooh err! > is 20.1 in trinary (6 1/3) times 2**172 (hex ac). > > I grant that this example looks a bit gobbledegookish, You think? :-) > but normal > usage would be much simpler. ?The notation doesn't handle > balanced trinary; however I opine that balanced trinary requires > special notation. When the programmer needs to construct such values how about allowing him or her to specify something like (20.1 in base 3) times 2 to the power of 0xac Leaving out how to specify (20.1 in base 3) for now this could be (20.1 in base 3) * 2 ** 0xac The compiler could convert this to a constant. James From sdementen at gmail.com Sun Aug 23 16:58:01 2009 From: sdementen at gmail.com (seb) Date: Sun, 23 Aug 2009 13:58:01 -0700 (PDT) Subject: conditional for-statement References: Message-ID: <9571ca2a-8559-403a-8ba5-aa6626f13ee6@32g2000yqj.googlegroups.com> On Aug 23, 10:36?pm, seb wrote: > On Aug 23, 6:18?pm, John Posner wrote: > > > > > > > >> Hi, > > > >> i was wondering if there is a syntax alike: > > > >> for i in range(10) if i > 5: > > >> ? ? print i > > > > You can write > > > > for i in filter(lambda i: i > 5, range(10)): > > > ? ? print i > > > > but > > > > for i in range(10): > > > ? ? if i > 5: > > > ? ? ? ? print i > > > > it' better readable, and > > > > for i in range(6,10): > > > ? ? print i > > > > it's event better. > > > How about using a generator expression instead of a list? > > > ? for i in (x for x in range(10) if x > 5): > > ? ? ? print i > > > -John > > Indeed, but we could have the same syntax than for generators but > directly in the for statement as in > for variable in generator if condition: > ? ? body > > Is there a special reason for not doing so ? A rejected PEP ?- Hide quoted text - > > - Show quoted text - I just found the same thread on the python ideas group at http://mail.python.org/pipermail/python-ideas/2009-April/004278.html sorry for reposting From clp2 at rebertia.com Sun Aug 23 17:02:16 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Aug 2009 14:02:16 -0700 Subject: conditional for-statement In-Reply-To: References: Message-ID: <50697b2c0908231402p1ff54041jba173c3e23ffab12@mail.gmail.com> On Sun, Aug 23, 2009 at 1:36 PM, seb wrote: > On Aug 23, 6:18?pm, John Posner wrote: >> >> Hi, >> >> >> i was wondering if there is a syntax alike: >> >> >> for i in range(10) if i > 5: >> >> ? ? print i >> >> > You can write >> >> > for i in filter(lambda i: i > 5, range(10)): >> > ? ? print i >> >> > but >> >> > for i in range(10): >> > ? ? if i > 5: >> > ? ? ? ? print i >> >> > it' better readable, and >> >> > for i in range(6,10): >> > ? ? print i >> >> > it's event better. >> >> How about using a generator expression instead of a list? >> >> ? for i in (x for x in range(10) if x > 5): >> ? ? ? print i >> >> -John > > Indeed, but we could have the same syntax than for generators but > directly in the for statement as in > for variable in generator if condition: > ? ?body > > Is there a special reason for not doing so ? A rejected PEP ? It's not been added since it's completely unnecessary (see the several alternatives already presented by others). There have been a few other mailinglist threads on adding essentially the same syntax. None have proved fruitful. Cheers, Chris -- http://blog.rebertia.com From james.harris.1 at googlemail.com Sun Aug 23 17:42:16 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Sun, 23 Aug 2009 14:42:16 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: On 23 Aug, 00:16, Mel wrote: > James Harris wrote: > > I have no idea why Ada which uses the # also apparently uses it to end > > a number > > > ? 2#1011#, 8#7621#, 16#c26b# > > Interesting. ?They do it because of this example from > : Thanks for providing an explanation. > > 2#1#E8 ? ? ? ? ? ? ? ? ? ?-- an integer literal of value 256 > > where the E prefixes a power-of-2 exponent, and can't be taken as a digit of > the radix. ?That is to say > > 16#1#E2 > > would also equal 256, since it's 1*16**2 . Here's another suggested number literal format. First, keep the familar 0x and 0b of C and others and to add 0t for octal. (T is the third letter of octal as X is the third letter of hex.) The numbers above would be 0b1011, 0t7621, 0xc26b Second, allow an arbitrary number base by putting base and number in quotes after a zero as in 0"2:1011", 0"8:7621", 0"16:c26b" This would work for arbitrary bases and allows an exponent to be tagged on the end. It only depends on zero followed by a quote mark not being used elsewhere. Finally, although it uses a colon it doesn't take it away from being used elsewhere in the language. Another option: 0.(2:1011), 0.(8:7621), 0.(16:c26b) where the three characters "0.(" begin the sequence. Comments? Improvements? James From james.harris.1 at googlemail.com Sun Aug 23 17:45:39 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Sun, 23 Aug 2009 14:45:39 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <4a90b50e.154654859@text.giganews.com> <9411f79a-934f-494c-93bc-dc020646f281@z24g2000yqb.googlegroups.com> Message-ID: On 23 Aug, 21:55, James Harris wrote: ... > > ?However for floating point you > > need at least three letters because a floating point number has > > three parts: the fixed point point, the exponent base, and the > > exponent. ?Now we can represent the radices of the individual > > parts with the 'r'scheme, e.g., 2r101001, but we need separate > > letters to designate the exponent base and the exponent. ?B and E > > are the obvious choices, though we want to be careful about a > > confusion with 'b' in hex. ?For example, using 'R', > > > 3R20.1B2E16Rac > > Ooh err! > > > is 20.1 in trinary (6 1/3) times 2**172 (hex ac). > > > I grant that this example looks a bit gobbledegookish, > > You think? :-) > > > but normal > > usage would be much simpler. ?The notation doesn't handle > > balanced trinary; however I opine that balanced trinary requires > > special notation. > > When the programmer needs to construct such values how about allowing > him or her to specify something like > > ? (20.1 in base 3) times 2 to the power of 0xac > > Leaving out how to specify (20.1 in base 3) for now this could be > > ? (20.1 in base 3) * 2 ** 0xac Using the suggestion from another post would convert this to 0.(3:20.1) * 2 ** 0xac > > The compiler could convert this to a constant. From phily05 at gmail.com Sun Aug 23 17:51:32 2009 From: phily05 at gmail.com (Phil) Date: Sun, 23 Aug 2009 14:51:32 -0700 (PDT) Subject: __import__(x) VS __import__(x, {}, {}, ['']) Message-ID: I am trying to understand the difference between __import__(x) and __import__(x, {}, {}, ['']). The documentations wording was a bit weird for me to understand: "The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement." Does that mean it passes in the globals by default, or does the above statement stand true only if globals() is passed in? From mwilson at the-wire.com Sun Aug 23 18:05:44 2009 From: mwilson at the-wire.com (Mel) Date: Sun, 23 Aug 2009 18:05:44 -0400 Subject: conditional for-statement References: Message-ID: seb wrote: > On Aug 23, 6:18 pm, John Posner wrote: [ ... ] >> How about using a generator expression instead of a list? >> >> for i in (x for x in range(10) if x > 5): >> print i >> >> -John > > Indeed, but we could have the same syntax than for generators but > directly in the for statement as in > for variable in generator if condition: > body > > Is there a special reason for not doing so ? A rejected PEP ? Well, the Zen of Python does say There should be one-- and preferably only one --obvious way to do it. Beyond that, I refer you to Gerald M. Weinberg's _The Psychology of Computer Programming_, specifically chapters 11 and 12, about Programming Languages, and their design. The proposal creates an case where one particular pair of syntactic constructs can be mooshed together. OK for them, but everything else becomes an exception; what about while a==c if b != d: why not if b != d while a==c: or for a in range(7) if os.name == 'posix': It winds up burdening the programmers with remembering which constructs are and which are not mooshable. Weinberg gave an example: FORTRAN had some stringent rules for what expressions were and were not allowed as array subscripts. The result was that many programmers couldn't remember all the rules, and often avoided using legal forms, having forgotten they were legal. Maybe the line was already crossed when list comprehensions came into being, still, the damage is localized in a particular context: building a list. It isn't out creating wild options in the program control flow at large. Mel. From voodoorai2000 at gmail.com Sun Aug 23 18:07:31 2009 From: voodoorai2000 at gmail.com (Raimond Garcia) Date: Mon, 24 Aug 2009 00:07:31 +0200 Subject: What is the recommended library for xml parsing? Message-ID: Is there a good build in library or should I use a third party one? Cheers, Peter -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Sun Aug 23 18:15:55 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sun, 23 Aug 2009 23:15:55 +0100 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <4A91BF9B.9080100@mrabarnett.plus.com> James Harris wrote: > On 23 Aug, 00:16, Mel wrote: >> James Harris wrote: >>> I have no idea why Ada which uses the # also apparently uses it to end >>> a number >>> 2#1011#, 8#7621#, 16#c26b# >> Interesting. They do it because of this example from >> : > > Thanks for providing an explanation. > >> 2#1#E8 -- an integer literal of value 256 >> >> where the E prefixes a power-of-2 exponent, and can't be taken as a digit of >> the radix. That is to say >> >> 16#1#E2 >> >> would also equal 256, since it's 1*16**2 . > > Here's another suggested number literal format. First, keep the > familar 0x and 0b of C and others and to add 0t for octal. (T is the > third letter of octal as X is the third letter of hex.) The numbers > above would be > > 0b1011, 0t7621, 0xc26b > > Second, allow an arbitrary number base by putting base and number in > quotes after a zero as in > > 0"2:1011", 0"8:7621", 0"16:c26b" > Why not just put the base first, followed by the value in quotes: 2"1011", 8"7621", 16"c26b" > This would work for arbitrary bases and allows an exponent to be > tagged on the end. It only depends on zero followed by a quote mark > not being used elsewhere. Finally, although it uses a colon it doesn't > take it away from being used elsewhere in the language. > > Another option: > > 0.(2:1011), 0.(8:7621), 0.(16:c26b) > > where the three characters "0.(" begin the sequence. > > Comments? Improvements? > From aahz at pythoncraft.com Sun Aug 23 18:44:01 2009 From: aahz at pythoncraft.com (Aahz) Date: 23 Aug 2009 15:44:01 -0700 Subject: logging SMTPhandler Error References: <60de8d40-61f4-4ffd-bcef-749bf06675d0@k19g2000yqn.googlegroups.com> Message-ID: In article , Dennis Lee Bieber wrote: >On 23 Aug 2009 06:14:00 -0700, aahz at pythoncraft.com (Aahz) declaimed the >following in gmane.comp.python.general: >> >> Slightly expanded: most mail servers accept connections from any other >> mail server for addresses that are hosted by them. The MX address for a >> domain tells you what mail server hosts that address. By connecting >> directly to the MX, your script is essentially acting as a mail server >> itself. > > But is not possible if one's ISP blocks pass-through SMTP >connections. Correct, but the OP said that zir ISP did not have a mailserver; AFAIK all ISPs that block SMTP have their own mailserver that you can point at instead. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From Scott.Daniels at Acm.Org Sun Aug 23 18:50:29 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Sun, 23 Aug 2009 15:50:29 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: James Harris wrote:... > Another option: > > 0.(2:1011), 0.(8:7621), 0.(16:c26b) > > where the three characters "0.(" begin the sequence. > > Comments? Improvements? I did a little interpreter where non-base 10 numbers (up to base 36) were: .7.100 == 64 (octal) .9.100 == 100 (decimal) .F.100 == 256 (hexadecimal) .1.100 == 4 (binary) .3.100 == 9 (trinary) .Z.100 == 46656 (base 36) Advantages: Tokenizer can recognize chunks easily. Not visually too confusing, No issue of what base the base indicator is expressed in. --Scott David Daniels Scott.Daniels at Acm.Org From clp2 at rebertia.com Sun Aug 23 18:59:35 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Aug 2009 15:59:35 -0700 Subject: What is the recommended library for xml parsing? In-Reply-To: References: Message-ID: <50697b2c0908231559vf6c42dcn321296edd7d033b7@mail.gmail.com> On Sun, Aug 23, 2009 at 3:07 PM, Raimond Garcia wrote: > Is there a good build in library or should I use a third party one? xml.etree.ElementTree: http://docs.python.org/library/xml.etree.elementtree.html Cheers, Chris -- http://blog.rebertia.com From bartc at freeuk.com Sun Aug 23 19:04:37 2009 From: bartc at freeuk.com (bartc) Date: Sun, 23 Aug 2009 23:04:37 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> "Scott David Daniels" wrote in message news:kN2dnSZR5b0BWAzXnZ2dnUVZ_s-dnZ2d at pdx.net... > James Harris wrote:... >> Another option: >> >> 0.(2:1011), 0.(8:7621), 0.(16:c26b) >> >> where the three characters "0.(" begin the sequence. >> >> Comments? Improvements? > > I did a little interpreter where non-base 10 numbers > (up to base 36) were: > > .7.100 == 64 (octal) > .9.100 == 100 (decimal) > .F.100 == 256 (hexadecimal) > .1.100 == 4 (binary) > .3.100 == 9 (trinary) > .Z.100 == 46656 (base 36) > Advantages: > Tokenizer can recognize chunks easily. > Not visually too confusing, > No issue of what base the base indicator is expressed in. It can be assumed however that .9. isn't in binary? That's a neat idea. But an even simpler scheme might be: .octal.100 .decimal.100 .hex.100 .binary.100 .trinary.100 until it gets to this anyway: .thiryseximal.100 -- Bartc From sjmachin at lexicon.net Sun Aug 23 19:04:55 2009 From: sjmachin at lexicon.net (John Machin) Date: Sun, 23 Aug 2009 23:04:55 +0000 (UTC) Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in =?utf-8?b?d2luZG93cwl4cA==?= while making tarfile References: Message-ID: Erik Max Francis alcyone.com> writes: > > Ryniek90 wrote: > > Is its the '|\U' literal fault in path '|C:\\Users\\Ryniek's > > WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2|' ? What is "the '|\U' literal fault" ??? > > It's probably a misleading error from the OS; I would guess the problem > is that the filename contains colons, which I believe is a no-no on Windows. The colons are the problem. The error message is not from the OS; it is concocted by Python (see fileobject.c) as what appears to be the best possible text given vague error reporting by Windows. I don't understand "probably a misleading error [message]" -- invalid mode (actual value) or filename -> invalid something-obviously-not-invalid or filename -> invalid filename From sturlamolden at yahoo.no Sun Aug 23 19:17:19 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 16:17:19 -0700 (PDT) Subject: Python/Fortran interoperability References: Message-ID: On 23 Aug, 20:42, n... at cam.ac.uk wrote: > That is precisely what I am investigating. ?TR 29113 falls a LONG > way before it gets to any of the OOP data - indeed, you can't even > pass OOP derived types as pure data (without even the functionality) > in its model. ?Nor most of what else Python would expect. I am note sure what you mean. This has the same ABI: typedef struct { int m, n; float r; } myctype; use iso_c_binding type, bind(c) :: myftype integer(c_int) :: m, n real(c_float) :: s end type You thus can pass derived types between C and Fortran. From mattaman at gmail.com Sun Aug 23 19:27:21 2009 From: mattaman at gmail.com (mm) Date: Sun, 23 Aug 2009 16:27:21 -0700 (PDT) Subject: Newbie: list comprehension troubles.. Message-ID: Hi, I'm trying to replace this... # this works but there must be a more pythonic way, right? tlist = [] for obj in self.objs: t = obj.intersect(ray) if (t != None): tlist.append((obj,t)) with a list comprehension- can it be done? What I need to do is iterate over a list of graphics primitives and call their intersect method. If the returned t value is not None then I want to store the obj refernence and its t value in a list of tuples for further processing. I've tried stuff like ... tlist = [(obj,t) for obj,t in (self.objs, obj.intersect(ray)) if (t != None)] tlist = [(obj,t) for obj in self.objs for t in obj.intersect (ray) ] print ">>> ",len(tlist), tlist but they don't work. Any help greatly appreciated. matt From clp2 at rebertia.com Sun Aug 23 19:36:02 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Aug 2009 16:36:02 -0700 Subject: Newbie: list comprehension troubles.. In-Reply-To: References: Message-ID: <50697b2c0908231636l77357d21icca87edf2248f15d@mail.gmail.com> On Sun, Aug 23, 2009 at 4:27 PM, mm wrote: > Hi, I'm trying to replace this... > > ? ? ? ?# this works but there must be a more pythonic way, right? > ? ? ? ?tlist = [] > ? ? ? ?for obj in self.objs: > ? ? ? ? ? ?t = obj.intersect(ray) > ? ? ? ? ? ?if (t != None): > ? ? ? ? ? ? ? ?tlist.append((obj,t)) > > with a list comprehension- can it be done? Yes: tlist = [pair for pair in ((obj, obj.intersect(ray)) for obj in self.objs) if pair[1] is not None] Should it be done? Probably not. It's less readable and less efficient. Cheers, Chris -- http://blog.rebertia.com From sturlamolden at yahoo.no Sun Aug 23 19:59:34 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 16:59:34 -0700 (PDT) Subject: Python/Fortran interoperability References: Message-ID: <277abf44-d218-45de-90c8-9bed0f1c8abf@k30g2000yqf.googlegroups.com> On 24 Aug, 00:02, Dennis Lee Bieber wrote: > ? ? ? ? That's a C language problem -- since a string in C is just an array > of character. The last FORTRAN dialect (and implementation) I used > passed strings On 24 Aug, 00:02, Dennis Lee Bieber wrote: > values -- FORTRAN strings were typically static, the called function > could not reallocate to fit in longer data and update the descriptor to > match) It is possible to pass an arbitrary length. You have to convert a pointer from C to Fortran: subroutine foobar(cstr) bind(c, name='foobar') use, intrinsic :: iso_c_binding type(c_ptr) :: cstr character(*), pointer :: fstr call c_f_pointer(cptr, fptr) If you need the length, call strlen from libc. I think the OP has misunderstood how the Fortran 2003 C bindings work. They don't convert C pointers to Fortran strings or Fortran arryas. They convert C pointers to Fortran pointers. Sturla From tjreedy at udel.edu Sun Aug 23 20:05:38 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 24 Aug 2009 09:05:38 +0900 Subject: Newbie: list comprehension troubles.. In-Reply-To: <50697b2c0908231636l77357d21icca87edf2248f15d@mail.gmail.com> References: <50697b2c0908231636l77357d21icca87edf2248f15d@mail.gmail.com> Message-ID: Chris Rebert wrote: > On Sun, Aug 23, 2009 at 4:27 PM, mm wrote: >> Hi, I'm trying to replace this... >> >> # this works but there must be a more pythonic way, right? 'Pythonic' is readable, if nothing else >> tlist = [] >> for obj in self.objs: >> t = obj.intersect(ray) >> if (t != None): >> tlist.append((obj,t)) This, to me, is more readable than the lc replacement. >> >> with a list comprehension- can it be done? > > Yes: > tlist = [pair for pair in ((obj, obj.intersect(ray)) for obj in > self.objs) if pair[1] is not None] > > Should it be done? Probably not. It's less readable and less efficient. I agree. tjr From sturlamolden at yahoo.no Sun Aug 23 20:06:43 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 17:06:43 -0700 (PDT) Subject: Python/Fortran interoperability References: <277abf44-d218-45de-90c8-9bed0f1c8abf@k30g2000yqf.googlegroups.com> Message-ID: On 24 Aug, 01:59, sturlamolden wrote: > subroutine foobar(cstr) bind(c, name='foobar') > ? ? use, intrinsic :: iso_c_binding > ? ? type(c_ptr) :: cstr > ? ? character(*), pointer :: fstr > ? ? call c_f_pointer(cptr, fptr) > Which means that you can write a wrapper in Fortran callable from C, that calls a Fortran routine you want to expose: subroutine wrap_foobar(cstr) bind(c, name='foobar') use, intrinsic :: iso_c_binding type(c_ptr) :: cstr character(*), pointer :: fstr call c_f_pointer(cptr, fptr) call foobar(fstr) end subroutine subroutine foobar(fstr) character(*) :: fstr ! whatever end subroutine This by the way is how wrap exposes Fortran functions to Cython. From ben+python at benfinney.id.au Sun Aug 23 20:09:29 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 24 Aug 2009 10:09:29 +1000 Subject: Newbie: list comprehension troubles.. References: Message-ID: <87ab1qgjie.fsf@benfinney.id.au> Chris Rebert writes: > tlist = [pair for pair in ((obj, obj.intersect(ray)) for obj in > self.objs) if pair[1] is not None] > > Should it be done? Probably not. [Compared to a ?for? suite with an > ?if? suite, it's] less readable and less efficient. I disagree on the ?less efficient?, unless you've measured it. The Python compiler and machine make list comprehensions and generator expressions turn into quite efficient code. I also disagree on ?less readable?, if you show the structure and choose meaningful names (I can only guess at the meaning from the OP's code):: tribbles = [ (obj, tribble) for (obj, tribble) in ( (obj, obj.intersect(ray)) for obj in self.objs) if tribble is not None] -- \ ?I must say that I find television very educational. The minute | `\ somebody turns it on, I go to the library and read a book.? | _o__) ?Groucho Marx | Ben Finney From find.mig at paa.google Sun Aug 23 20:14:24 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Mon, 24 Aug 2009 02:14:24 +0200 Subject: Protecting against callbacks queuing up? Message-ID: <4a91db65$0$305$14726298@news.sunsite.dk> Hello I'm using Python for S60 1.9.7 on my Nokia phone. I've made a program that gets input from an accelerometer sensor, and then calculates some stuff and displays the result. The sensor framework API does a callback to a function defined by me, every time new data is available. The problem is, that sometimes, the calculations may take longer than others, but if the callback is called before the first calculation is done, it seems like it's queuing up all the callbacks, and execute them sequentially, afterwards. What I need, is to simply ignore the callback, if the previous call hasn't finished it's operations before it's called again. I thought that this code would do the trick, but it obviously doesn't help at all, and i can't understand why... def doCallback(self): if self.process_busy==False: self.process_busy=True self.data_callback() self.process_busy=False doCallback is defined as a callback function for the accelerometer instance, and data_callback does some calculations and show them on the display of the phone. What to do? Thanks... From steve at REMOVE-THIS-cybersource.com.au Sun Aug 23 20:17:11 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2009 00:17:11 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <4a918fe0$0$30226$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <02a1cc1d$0$30337$c3e8da3@news.astraweb.com> On Sun, 23 Aug 2009 20:52:16 +0200, Stefan Behnel wrote: > Simon Brunning wrote: >> 2009/8/11 Robert Dailey: >>> On Aug 11, 3:40 pm, Bearophile wrote: >>>> There are gals too here. >>> It's a figure of speech. And besides, why would I want programming >>> advice from a woman? lol. Thanks for the help. >> >> Give the attitudes still prevalent in our industry (cf >> and many more), I'm sorry to say that I >> don't think this is funny. > > Me neither. > > I used to reply with comments like "you just missed more than half of > the world's population" to people who started their postings with "hi > guys!", If you start your post with "Hi guys", you've missed more than EIGHTY percent of the world's population, namely the 5.5 to 6 billion people who speak no English. To say nothing of the 99.9% of the world's population who couldn't help you with your query, even if they spoke English, and even if they were on the Internet. In that case, missing out on the small percentage of English-speaking women who don't know that "guys" has become sexless probably doesn't matter. (I'm amused and somewhat perplexed that somebody with the non-English name of Stefan, writing from a .de email address, seems to be assuming that (1) everybody is on the Internet, and (2) everybody on the Internet speaks English. Awareness of sexism is a good thing, but so is awareness of cultural chauvinism.) > and I stopped doing that as a) it became too tiring, especially > on a potentially-for-newbees group like c.l.py, and b) to many people it > actually *is* a figure of speech. > > But reading statements like the above really makes me feel that it's > best to comment even on simple things like "hi guys!". Or you could enter the 21 century and understand that "guys" has become a generic term for people of any sex. -- Steven From nospam at see.signature Sun Aug 23 20:26:31 2009 From: nospam at see.signature (Richard Maine) Date: Sun, 23 Aug 2009 17:26:31 -0700 Subject: Python/Fortran interoperability References: Message-ID: <1j4ww90.pvvxweehycu0N%nospam@see.signature> sturlamolden wrote: > On 23 Aug, 20:42, n... at cam.ac.uk wrote: > > > That is precisely what I am investigating. TR 29113 falls a LONG > > way before it gets to any of the OOP data - indeed, you can't even > > pass OOP derived types as pure data (without even the functionality) > > in its model. Nor most of what else Python would expect. > > I am note sure what you mean. ... > You thus can pass derived types between C and Fortran. You missed the word "OOP", which seemed like the whole point. Not that the particular word is used in the Fortran standard, but it isn't hard to guess that he means a derived type that uses some of the OOP features. Inheritance, polymorphism, and type-bound procedure (aka methods in some other languages) come to mind. Since you say that you haven't used any of the F2003 OOP features, it isn't too surprising that you'd miss the allusion. -- Richard Maine | Good judgment comes from experience; email: last name at domain . net | experience comes from bad judgment. domain: summertriangle | -- Mark Twain From python at mrabarnett.plus.com Sun Aug 23 20:34:41 2009 From: python at mrabarnett.plus.com (MRAB) Date: Mon, 24 Aug 2009 01:34:41 +0100 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a91db65$0$305$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> Message-ID: <4A91E021.1040502@mrabarnett.plus.com> Esben von Buchwald wrote: > Hello > > I'm using Python for S60 1.9.7 on my Nokia phone. > > I've made a program that gets input from an accelerometer sensor, and > then calculates some stuff and displays the result. > > The sensor framework API does a callback to a function defined by me, > every time new data is available. > > The problem is, that sometimes, the calculations may take longer than > others, but if the callback is called before the first calculation is > done, it seems like it's queuing up all the callbacks, and execute them > sequentially, afterwards. > > What I need, is to simply ignore the callback, if the previous call > hasn't finished it's operations before it's called again. > > I thought that this code would do the trick, but it obviously doesn't > help at all, and i can't understand why... > > def doCallback(self): > if self.process_busy==False: > self.process_busy=True > self.data_callback() > self.process_busy=False > > > doCallback is defined as a callback function for the accelerometer > instance, and data_callback does some calculations and show them on the > display of the phone. > If it is, in fact, queuing the callbacks then that means that it's just recording that the callback needs to be called, but doesn't actually do it while a previous one is in effect, ie it'll wait for the current call to return before doing the next one. > What to do? Thanks... If you want to try multithreading you could make the callback just trigger the actual action in another thread. The other thread could wait for an event, perform the calculation, then clear any pending events before waiting again. From sturlamolden at yahoo.no Sun Aug 23 20:39:34 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 17:39:34 -0700 (PDT) Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> Message-ID: <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> On 24 Aug, 02:26, nos... at see.signature (Richard Maine) wrote: > You missed the word "OOP", which seemed like the whole point. Not that > the particular word is used in the Fortran standard, but it isn't hard > to guess that he means a derived type that uses some of the OOP > features. Inheritance, polymorphism, and type-bound procedure (aka > methods in some other languages) come to mind. But C is not OOP. The ISO C bindings in Fortran are not ISO C++ bindings. This is for a reason: C++ does not have a standard ABI like ISO C. From david.lyon at preisshare.net Sun Aug 23 20:46:12 2009 From: david.lyon at preisshare.net (David Lyon) Date: Sun, 23 Aug 2009 20:46:12 -0400 Subject: install package in a particular python version In-Reply-To: <99822c4d-74ef-4a28-b133-42144c7fd25a@f20g2000prn.googlegroups.com> References: <4ae493d4-4669-4e54-a385-6d79d539a778@v23g2000pro.googlegroups.com> <99822c4d-74ef-4a28-b133-42144c7fd25a@f20g2000prn.googlegroups.com> Message-ID: <0e4f0ed1c46760d844a603fae3ebc3a3@preisshare.net> On Thu, 20 Aug 2009 20:53:18 -0700 (PDT), Steve1234 wrote: > Benjamin suggested: > sudo python2.5 setup.py install > and it works. This makes sense, thanks. > > I downloaded pythonpkgmgr from source and installed it. I got the > error that reguired wx package was missing. I couldn't find this > package for Linux or source. That's wxpython. You'll need to look at http://www.wxpython.org/download.php#binaries David From clp2 at rebertia.com Sun Aug 23 20:52:47 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 23 Aug 2009 17:52:47 -0700 Subject: Newbie: list comprehension troubles.. In-Reply-To: <87ab1qgjie.fsf@benfinney.id.au> References: <87ab1qgjie.fsf@benfinney.id.au> Message-ID: <50697b2c0908231752h2ec893fal92a9dc2d8a8d6aba@mail.gmail.com> On Sun, Aug 23, 2009 at 5:09 PM, Ben Finney wrote: > Chris Rebert writes: > >> tlist = [pair for pair in ((obj, obj.intersect(ray)) for obj in >> self.objs) if pair[1] is not None] >> >> Should it be done? Probably not. [Compared to a ?for? suite with an >> ?if? suite, it's] less readable and less efficient. > > I disagree on the ?less efficient?, unless you've measured it. The > Python compiler and machine make list comprehensions and generator > expressions turn into quite efficient code. Well, I hadn't benchmarked it originally, but since you bring it up: class Foo(object): def __init__(self, n): self.n = n def intersect(self, ray): return ray + self.n objs = [Foo(n) for n in range(300)] ray = 42 def listcomp(objs, ray): tlist = [pair for pair in ((obj, obj.intersect(ray)) for obj in objs) if pair[1] is not None] def naive(objs, ray): tlist = [] for obj in objs: t = obj.intersect(ray) if t is not None: tlist.append((obj,t)) chris at morpheus Desktop $ python Python 2.6.2 (r262:71600, May 14 2009, 16:34:51) [GCC 4.0.1 (Apple Inc. build 5484)] on darwin chris at morpheus Desktop $ python -m timeit -n 10000 -s 'from tmp import naive, ray, objs' 'naive(objs, ray)' 10000 loops, best of 3: 227 usec per loop chris at morpheus Desktop $ python -m timeit -n 10000 -s 'from tmp import listcomp, ray, objs' 'listcomp(objs, ray)' 10000 loops, best of 3: 254 usec per loop The numbers for each test stayed within a few usec of each other over a few runs. I thus conclude that the list comprehension method is indeed slower (which makes sense looking at the 2 algorithms). > I also disagree on ?less readable?, if you show the structure and choose > meaningful names (I can only guess at the meaning from the OP's code):: > > ? ?tribbles = [ > ? ? ? ?(obj, tribble) for (obj, tribble) in ( > ? ? ? ? ? ?(obj, obj.intersect(ray)) > ? ? ? ? ? ?for obj in self.objs) > ? ? ? ?if tribble is not None] I do concede it becomes somewhat more readable if split over multiple lines: pairs = ((obj, obj.intersect(ray)) for obj in self.objs) tlist = [pair for pair in pairs if pair[1] is not None] Cheers, Chris -- http://blog.rebertia.com From nospam at see.signature Sun Aug 23 20:57:52 2009 From: nospam at see.signature (Richard Maine) Date: Sun, 23 Aug 2009 17:57:52 -0700 Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> Message-ID: <1j4wx7d.18cr6dvw3j79yN%nospam@see.signature> sturlamolden wrote: > On 24 Aug, 02:26, nos... at see.signature (Richard Maine) wrote: > > > You missed the word "OOP", which seemed like the whole point. Not that > > the particular word is used in the Fortran standard, but it isn't hard > > to guess that he means a derived type that uses some of the OOP > > features. Inheritance, polymorphism, and type-bound procedure (aka > > methods in some other languages) come to mind. > > But C is not OOP. The ISO C bindings in Fortran are not ISO C++ > bindings. This is for a reason: C++ does not have a standard ABI like > ISO C. That seems irrelevant to the question originally asked, which was >>> Do you want to use Fortran derived types or Python classes that >>> contain type-bound procedures (including finalizers)? Yes, it is no surprise that the C interop stuff fails to address this, since it isn't in C. Something different/extra would be needed, which is exactly what Nick said. I'm going to jump out of the middle of this now. The only reason I jumped in was to point out the gap in communication, where Nick said that the TR doesn't handle "OOP derived types" and you replied that it does so do derived types, omitting the OOP part, which was clearly (to me) Nick's whole point. However, I don't seem to be facilitating the communication, as the replies just seem to be wandering farther afield, or maybe it is around in a circle. I think you just explained that the ISO C bindings in Fortran don't handle what Nick is asking about... but that somehow this makes it puzzling that Nick also says that they don't handle it. Well, I'll leave it to Nick and you, I guess. I'm lost. -- Richard Maine | Good judgment comes from experience; email: last name at domain . net | experience comes from bad judgment. domain: summertriangle | -- Mark Twain From maxerickson at gmail.com Sun Aug 23 21:19:53 2009 From: maxerickson at gmail.com (Max Erickson) Date: Mon, 24 Aug 2009 01:19:53 +0000 (UTC) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: "bartc" wrote: > > "Scott David Daniels" wrote in message > news:kN2dnSZR5b0BWAzXnZ2dnUVZ_s-dnZ2d at pdx.net... >> James Harris wrote:... >>> Another option: > > It can be assumed however that .9. isn't in binary? > > That's a neat idea. But an even simpler scheme might be: > > .octal.100 > .decimal.100 > .hex.100 > .binary.100 > .trinary.100 > > until it gets to this anyway: > > .thiryseximal.100 > At some point, abandoning direct support for literals and just having a function that can handle different bases starts to make a lot of sense to me: >>> int('100', 8) 64 >>> int('100', 10) 100 >>> int('100', 16) 256 >>> int('100', 2) 4 >>> int('100', 3) 9 >>> int('100', 36) 1296 max From voodoorai2000 at gmail.com Sun Aug 23 21:25:11 2009 From: voodoorai2000 at gmail.com (Raimond Garcia) Date: Mon, 24 Aug 2009 03:25:11 +0200 Subject: What is the recommended library for xml parsing? In-Reply-To: <50697b2c0908231559vf6c42dcn321296edd7d033b7@mail.gmail.com> References: <50697b2c0908231559vf6c42dcn321296edd7d033b7@mail.gmail.com> Message-ID: +1 ::results:: Cheers, Peter Petrelli On Mon, Aug 24, 2009 at 12:59 AM, Chris Rebert wrote: > On Sun, Aug 23, 2009 at 3:07 PM, Raimond Garcia > wrote: > > Is there a good build in library or should I use a third party one? > > xml.etree.ElementTree: > http://docs.python.org/library/xml.etree.elementtree.html > > Cheers, > Chris > -- > http://blog.rebertia.com > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bot at letsdecide.us Sun Aug 23 21:27:04 2009 From: bot at letsdecide.us (bot at letsdecide.us) Date: Mon, 24 Aug 2009 01:27:04 +0000 Subject: What is the recommended library for xml parsing? Message-ID: <4a91ec68908f7_7144..fdbe3c0dc13e@li86-209.tmail> voodoorai2000 on gmail.com has asked me for the current status of our votation.. so here you go: +1 => 1 vote -1 => 0 votes Time Line: ---------- (2009-08-24 01:25:11) Raimond Garcia: +1 Visit the fancy votation page: * http://letsdecide.us/4130bc4e0051016cb377d3436f4e8e683ed820ed From sturlamolden at yahoo.no Sun Aug 23 21:28:24 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 18:28:24 -0700 (PDT) Subject: Python/Fortran interoperability References: <277abf44-d218-45de-90c8-9bed0f1c8abf@k30g2000yqf.googlegroups.com> Message-ID: <310696bd-f51e-42bc-80cf-89a2a9e04c0c@v20g2000yqm.googlegroups.com> On 24 Aug, 01:59, sturlamolden wrote: > subroutine foobar(cstr) bind(c, name='foobar') > ? ? use, intrinsic :: iso_c_binding > ? ? type(c_ptr) :: cstr > ? ? character(*), pointer :: fstr > ? ? call c_f_pointer(cptr, fptr) Actually, this does not work, as it is illegal to create a pointer to a character(*). However, we can create a pointer to a huge string (say 2 GB or whatever maximum the system allows), and slice that down to a substring using strlen to obtain the length. So here is how to pass a variable-length string from C to Fortran, tested with gcc and gfortran 4.1.1. In foobar.f03: subroutine wrap_foobar(cstr) bind(c, name='foobar') ! a wrapper for foobar we expose to C use, intrinsic :: iso_c_binding interface function strlen(cstr) bind(c, name='strlen') use, intrinsic :: iso_c_binding integer(c_int) :: strlen type(c_ptr), value :: cstr end function strlen end interface type(c_ptr), value :: cstr character(2147483647), pointer :: p_fstr integer :: n n = strlen(cstr) call c_f_pointer(cstr, p_fstr) call foobar(p_fstr(1:n)) end subroutine subroutine foobar(fstr) ! this is the Fortran function we want to call from C ! it takes a variable length string as argument and print its length character(*) :: fstr write (*,*) len(fstr) end subroutine In main.c: extern void foobar(char *); int main(int argc, char *argv[]) { foobar(argv[1]); return 0; } Sturla at STURLA-PC /d/fortrantest $ gfortran -c foobar.f03 Sturla at STURLA-PC /d/fortrantest $ gcc -c main.c Sturla at STURLA-PC /d/fortrantest $ gcc -o test.exe main.o foobar.o -lgfortran Sturla at STURLA-PC /d/fortrantest $ ./test 1234 4 Sturla at STURLA-PC /d/fortrantest $ ./test 0123456789 10 So it works... Regards, Sturla Molden From davea at ieee.org Sun Aug 23 21:32:13 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 23 Aug 2009 21:32:13 -0400 Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: References: Message-ID: <4A91ED9D.4090803@ieee.org> John Machin wrote: > Erik Max Francis alcyone.com> writes: > > >> Ryniek90 wrote: >> > > >>> Is its the '|\U' literal fault in path '|C:\\Users\\Ryniek's >>> WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2|' ? >>> > > What is "the '|\U' literal fault" ??? > > >> It's probably a misleading error from the OS; I would guess the problem >> is that the filename contains colons, which I believe is a no-no on Windows. >> > > The colons are the problem. The error message is not from the OS; it is > concocted by Python (see fileobject.c) as what appears to be the best possible > text given vague error reporting by Windows. I don't understand "probably a > misleading error [message]" -- invalid mode (actual value) or filename -> > invalid something-obviously-not-invalid or filename -> invalid filename > > > I also suspect the "pipe" symbol. I don't know if it's an invalid character to Windows, but it's certainly a bad idea. The '|' character means something special to the shell. DaveA From sturlamolden at yahoo.no Sun Aug 23 21:40:06 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 18:40:06 -0700 (PDT) Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> <1j4wx7d.18cr6dvw3j79yN%nospam@see.signature> Message-ID: <800c6f66-7074-451f-8c1b-47c93d07c5a4@s13g2000yql.googlegroups.com> On 24 Aug, 02:57, nos... at see.signature (Richard Maine) wrote: > Yes, it is no surprise that the C interop stuff fails to address this, > since it isn't in C. Something different/extra would be needed, which is > exactly what Nick said. I'm going to jump out of the middle of this now. > The only reason I jumped in was to point out the gap in communication, > where Nick said that the TR doesn't handle "OOP derived types" and you > replied that it does so do derived types, omitting the OOP part, which > was clearly (to me) Nick's whole point. You are right, I missed th OOP part. It might be interesting in teh future to say inherit a Python class from a Fortran 2003 derived type. I have no idea how to do this (I don't know Fortran 2003 that well). But possibly one could do some magic with the ISO C bindings, exposing the Fortran 2003 derived type as a C etxtension class to Python. Does anyone use OOP in Fortran anyway? I sure do not. And Fortran 2003 compilers are not ubiquitous. Fortran compilers tend to support a subset for Fortran 2003, usually ISO C bindings but not OOP. Sturla From greg at cosc.canterbury.ac.nz Sun Aug 23 21:46:18 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 24 Aug 2009 13:46:18 +1200 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> Message-ID: <7fe9mbF2l83bmU1@mid.individual.net> J. Cliff Dyer wrote: > What happens if you use a literal like 0x10f 304? To me the obvious thing to do is concatenate them textually and then treat the whole thing as a single numeric literal. Anything else wouldn't be sane, IMO. -- Greg From nospam at see.signature Sun Aug 23 21:58:40 2009 From: nospam at see.signature (Richard Maine) Date: Sun, 23 Aug 2009 18:58:40 -0700 Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> <1j4wx7d.18cr6dvw3j79yN%nospam@see.signature> <800c6f66-7074-451f-8c1b-47c93d07c5a4@s13g2000yql.googlegroups.com> Message-ID: <1j4x00p.nyarf2ce8dxcN%nospam@see.signature> sturlamolden wrote: > Does anyone use OOP in Fortran anyway? Presumably not many people yet because... > And Fortran 2003 compilers are not ubiquitous. I'd not only agree, I'd say that was quite a bit understated. Last time I checked, the number of Fortran 2003 compilers available on the most widely used platforms was zero, which is quite a bit short of ubiquitous. No I don't have an IBM workstation handy; or a Cray. Nor do most people. I did try playing with the Fortran OOP stuff quite a few years ago, when NAG first added some of the OOP features to their f95 compiler. But alas, although they added some of the OOP features, there were critical parts that were not included. Play with it a little is all I could do. I couldn't write any serious code, or even "play" very extensively. (Lack of allocatable scalars was a show stopper; it seems so simple and isn't even normally identified as an OOP feature per se, but you need it to do much with OOP in F2003). I'm told that NAG's 5.2 finally has the needed stuff, but it has been an awful long time in coming... and still isn't yet here for anything but Linux (I'm told "soon"). Some other compilers are also getting there. But there is just no way that most people have spent much time developing with compilers that adequately supported the f2003 OOP features. (I'd cite my formal comment on f2008, and maybe David Muxworthy's recent article as well, but we've already been down that path.) -- Richard Maine | Good judgment comes from experience; email: last name at domain . net | experience comes from bad judgment. domain: summertriangle | -- Mark Twain From davea at ieee.org Sun Aug 23 22:05:42 2009 From: davea at ieee.org (Dave Angel) Date: Sun, 23 Aug 2009 22:05:42 -0400 Subject: Is Python what I need? In-Reply-To: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: <4A91F576.30707@ieee.org> newbie wrote: > Hi all > I'm interested in developing computer based, interactive programs for > students in a special school who have an aversion to pen and paper. > I've searched the net to find ready made software that will meet my > needs but it is either written to a level much higher than these > students can cope with or priced beyond our school budget. I came > across a blog of someone singing the praises of Python. My question is > therefore aimed at those that know what they are talking about (ie > users in this group). Is Python the language I need to learn to > develop these programs? > > I think I'm a bit confused as to just what you're intending, and what your background is. So if this response doesn't fit, please don't be offended. I'm guessing you don't want these special students to do any programming, but instead you just want to find/develop inexpensive applications for their use. You have some specific ideas, but haven't found anything already available within your budget. I'm also guessing that you're a total beginner at programming. If so, I claim that most programs are much, much harder to write than you can imagine. Python is one of the easiest languages to learn and to write things in, but even so, most GUI programs take hundreds of hours to develop. And I've been doing it for forty years, in about 30 languages. DaveA From sjmachin at lexicon.net Sun Aug 23 22:10:12 2009 From: sjmachin at lexicon.net (John Machin) Date: Mon, 24 Aug 2009 02:10:12 +0000 (UTC) Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in =?utf-8?b?d2luZG93cwl4cA==?= while making tarfile References: <4A91ED9D.4090803@ieee.org> Message-ID: Dave Angel ieee.org> writes: > John Machin wrote: > > Erik Max Francis alcyone.com> writes: > I also suspect the "pipe" symbol. I don't know if it's an invalid > character to Windows, but it's certainly a bad idea. The '|' character > means something special to the shell. The "pipe" character is not a valid character in a Windows file. Despite the OP's message wrapping the filename in "pipes", there are no pipes in the filename in the traceback to which he posted a link. Wrapping the filename in "pipes" and the cryptic reference to "the '|\U' literal fault" appear to be side-issue bogglements. >>> open('boggle|txt', 'wb') Traceback (most recent call last): File "", line 1, in IOError: [Errno 22] invalid mode ('wb') or filename: 'boggle|txt' >>> open('|boggle.txt|', 'wb') Traceback (most recent call last): File "", line 1, in IOError: [Errno 22] invalid mode ('wb') or filename: '|boggle.txt|' From sturlamolden at yahoo.no Sun Aug 23 22:28:10 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 23 Aug 2009 19:28:10 -0700 (PDT) Subject: Is python faster than java? References: Message-ID: On 23 Aug, 21:59, Emile van Sebille wrote: > Speed of what? Development? User interaction? Responsiveness to queries? My personal view on the 'Is Python faster than Java' question: - Coding? Yes, if you program 'pythonic'. - String handling? Often. - I/O and networking? Often. - Iteration? No. - Function calls and recursion? No. - Arithmetics with elemental types? No. - Numerics? Yes, if you use NumPy. Is never interesting which language generates the most efficient code. If that were the case, we would be writing everything in assembly. If the code is fast enough, it is fast enough. Fast enough is sufficient. If some part of the code turn out to be too slow, we have two options: Either we use faster hardware, which is often the cheapest solution. Or we can alternatively try to move that part to something less high- level (Cython, C, C++, Fortran, assembly). Unlike Java, Python integrates easily with C. Also beware that Python is not Java: There is an old saying that you can write FORTRAN in any language. You can also write Java in Python. It will be just as slow to program as Java, and it will run a lot slower than Java. Most of the complaints about 'Python being slow' stems from people writing Java in Python. From ben+python at benfinney.id.au Sun Aug 23 22:29:20 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 24 Aug 2009 12:29:20 +1000 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: <8763cegd1b.fsf@benfinney.id.au> Max Erickson writes: > At some point, abandoning direct support for literals and just > having a function that can handle different bases starts to make a > lot of sense to me: > > >>> int('100', 8) > 64 > >>> int('100', 10) > 100 > >>> int('100', 16) > 256 > >>> int('100', 2) > 4 > >>> int('100', 3) > 9 > >>> int('100', 36) > 1296 Hah! You don't get me that easily, nobody would make something so simple and obvious. Right, guys? -- \ ?When a well-packaged web of lies has been sold to the masses | `\ over generations, the truth will seem utterly preposterous and | _o__) its speaker a raving lunatic.? ?Dresden James | Ben Finney From greg at cosc.canterbury.ac.nz Sun Aug 23 22:34:41 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Mon, 24 Aug 2009 14:34:41 +1200 Subject: __import__(x) VS __import__(x, {}, {}, ['']) In-Reply-To: References: Message-ID: <7fech5F2kofoqU1@mid.individual.net> Phil wrote: > I am trying to understand the difference between __import__(x) and > __import__(x, {}, {}, ['']). > > The documentations wording was a bit weird for me to understand: > "The standard implementation does not use its locals argument at all, > and uses its globals only to determine the package context of the > import statement." > > Does that mean it passes in the globals by default, or does the above > statement stand true only if globals() is passed in? Not sure what you mean by "it" in that question. This is talking about the built-in implementation of the __import__ function, and what it does with the 'globals' and 'locals' arguments that get passed to it (by whatever means). If you call it without a value for 'globals', it uses the current value of globals(). The bytecode generated for the 'import' statement always calls it with the current globals() and locals(). If you pass an empty dict for 'globals', I think the effect will be to cause the module name to always be interpreted as a top-level module (i.e. no relative import). But I'm not sure. -- Greg From ben+python at benfinney.id.au Sun Aug 23 22:45:25 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Mon, 24 Aug 2009 12:45:25 +1000 Subject: Literal concatenation, strings vs. numbers (was: Numeric literals in other than base 10 - was Annoying octal notation) References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> <7fe9mbF2l83bmU1@mid.individual.net> Message-ID: <871vn2gcai.fsf_-_@benfinney.id.au> greg writes: > J. Cliff Dyer wrote: > > > What happens if you use a literal like 0x10f 304? > > To me the obvious thing to do is concatenate them textually and then > treat the whole thing as a single numeric literal. Anything else > wouldn't be sane, IMO. Yet, as was pointed out, that behaviour would be inconsistent with the concatenation of string literals:: >>> "abc" r'def' u"ghi" 'jkl' u'abcdefghijkl' So, different representations of literals are parsed as separate literals, then concatenated. To have the behaviour you describe, the case needs to be made separately that digit concatenation should not be consistent with the established string literal parsing behaviour. -- \ ?What if the Hokey Pokey IS what it's all about?? ?anonymous | `\ | _o__) | Ben Finney From phily05 at gmail.com Sun Aug 23 22:58:42 2009 From: phily05 at gmail.com (Phil) Date: Sun, 23 Aug 2009 19:58:42 -0700 (PDT) Subject: __import__(x) VS __import__(x, {}, {}, ['']) References: <7fech5F2kofoqU1@mid.individual.net> Message-ID: <7d34f960-39a2-4447-9879-77a2794266a0@a26g2000yqn.googlegroups.com> "If you call it without a value for 'globals', it uses the current value of globals()." Thanks, this is what I was trying to ask. I typed my question up way too fast before dinner. You've been great help. From kerensaelise at hotmail.com Sun Aug 23 23:51:00 2009 From: kerensaelise at hotmail.com (elsa) Date: Sun, 23 Aug 2009 20:51:00 -0700 (PDT) Subject: sgmllib.py Message-ID: Hi all, I'm new to both this forum and Python, and I've got a bit stuck trying to learn how to parse HTML.... here is my problem I'm using a textbook that uses sgmllib.py for all its examples. I'm aware that sgmllib is not in the current release, however I want to get it to work, as I have python 2.5, and the text book uses it. So, the first example says to type something like (to test the sgmllib): python sgmllib.py "path/to/my/file.html" .... example (1) this doesn't work for me. I think I have figured out the problem - the error says "/System/Library/Frameworks/Python.framework/Versions/2.5/Resources/ Python.app/Contents/MacOS/Python: can't open file 'sgmllib.py': [Errno 2] No such file or directory" the problem is that this path is wrong. My sgmllib.py is in: "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/sgmllib.py" if I substitute this path for sgmllib.py in example (1), everything works fine. However, I don't want to do all that typing everytime I want to use sgmllib.py. So, I thought maybe the problem was with PYTHONPATH. I executed the following command: export PYTHONPATH=/System/Library/Frameworks/Python.framework/Versions/ 2.5/li/python2.5:$PYTHONPATH this seemed to work - no errors raised. However, when I retyped example (1), I got the same original error. Any assistance would be much appreciated. I'm working on max os x leopard. Thanks, elsa From doron.tal.list at gmail.com Sun Aug 23 23:51:05 2009 From: doron.tal.list at gmail.com (Doron Tal) Date: Mon, 24 Aug 2009 06:51:05 +0300 Subject: Most "active" coroutine library project? In-Reply-To: <64183b73-9cb0-4ce1-98d0-f47e13a818e4@f37g2000yqn.googlegroups.com> References: <64183b73-9cb0-4ce1-98d0-f47e13a818e4@f37g2000yqn.googlegroups.com> Message-ID: <2a8674c60908232051p71e743d0g9136ff2672e846f9@mail.gmail.com> On Sun, Aug 23, 2009 at 6:02 PM, Phillip B Oldham wrote: > I've been taking a look at the multitude of coroutine libraries > available for Python, but from the looks of the projects they all seem > to be rather "quiet". I'd like to pick one up to use on a current > project but can't deduce which is the most popular/has the largest > community. > > Libraries I looked at include: cogen, weightless, eventlet and > circuits (which isn't exactly coroutine-based but it's event-driven > model was intriguing). > > Firstly, are there any others I've missed? And what would the > consensus be on the which has the most active community behind it? > -- > http://mail.python.org/mailman/listinfo/python-list > If you seek also event-driven libraries: Twisted - http://twistedmatrix.com/trac/ --doron -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Mon Aug 24 00:36:19 2009 From: mensanator at aol.com (Mensanator) Date: Sun, 23 Aug 2009 21:36:19 -0700 (PDT) Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> <86bb893a-344a-4c7b-9fc6-67d9f42c7607@q14g2000vbi.googlegroups.com> <62dbf088-4510-40d0-af3e-3feeb291d6e4@t13g2000yqt.googlegroups.com> <4a9197c0$0$30226$9b4e6d93@newsspool1.arcor-online.net> Message-ID: On Aug 23, 2:25?pm, Stefan Behnel wrote: > Mensanator wrote: > > asking how many Jews you can fit into a Volswagen. > > None, because it's already full. A spelling error does not make it any less offensive. > > (or "voll" as those who design Volkswagens would put it...) > > Stefan From chaelon at gmail.com Mon Aug 24 01:09:45 2009 From: chaelon at gmail.com (c) Date: Sun, 23 Aug 2009 22:09:45 -0700 (PDT) Subject: Is Python what I need? References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: <22af46a4-91d1-4941-b914-ce78f136a151@p15g2000vbl.googlegroups.com> > I'm interested in developing computer based, interactive programs That is so open-ended it could mean anything. If you give a much more specified idea of what you are imagining creating, people could be helpful. > for students in a special school who have an aversion to pen and paper. Aversion? Why? Is it that they have such bad penmanship that writing is too frustrating? I've taught such students in college, and suspect (but do not know) that what would be good is to get them young and really put in the remedial time to train their penmanship up to sustained legibility and speed. Eventually society might go 100% electronic; for now, being able to write notes on paper is very helpful, and paper is still such a great technology aside from renewable concerns, but they can be greatly improved. (I even suspect rigorous and successful penmanship training might pay off in "general intelligence" gains) > I've searched the net to find ready made software that will meet my > needs but it is either written to a level much higher than these > students can cope with or priced beyond our school budget. I came > across a blog of someone singing the praises of Python. My question is > therefore aimed at those that know what they are talking about (ie > users in this group). Is Python the language I need to learn to > develop these programs? I agree with Dave A that writing a useful program is often far harder than a beginner might imagine. That said, much would depend on what you would need the program to do. Python, in my limited experience as a hobbyist, strikes me as fairly easy to get started with in programming, and yet can do a great deal, too. So, as I said, more details about the intended program would help people guide your choice. Che From nagle at animats.com Mon Aug 24 01:14:17 2009 From: nagle at animats.com (John Nagle) Date: Sun, 23 Aug 2009 22:14:17 -0700 Subject: basic thread question In-Reply-To: References: <20090818201015.GP20434@dragontoe.org> Message-ID: <4a922086$0$1619$742ec2ed@news.sonic.net> Jan Kaliszewski wrote: > 18-08-2009 o 22:10:15 Derek Martin wrote: > >> I have some simple threaded code... If I run this >> with an arg of 1 (start one thread), it pegs one cpu, as I would >> expect. If I run it with an arg of 2 (start 2 threads), it uses both >> CPUs, but utilization of both is less than 50%. Can anyone explain >> why? >> >> I do not pretend it's impeccable code, and I'm not looking for a >> critiqe of the code per se, excepting the case where what I've written >> is actually *wrong*. I hacked this together in a couple of minutes, >> with the intent of pegging my CPUs. Performance with two threads is >> actually *worse* than with one, which is highly unintuitive. I can >> accomplish my goal very easily with bash, but I still want to >> understand what's going on here... >> >> The OS is Linux 2.6.24, on a Ubuntu base. Here's the code: > > Python threads can't benefit from multiple processors (because of GIL, > see: http://docs.python.org/glossary.html#term-global-interpreter-lock). This is a CPython implementation restriction. It's not inherent in the language. Multiple threads make overall performance worse because Python's approach to thread locking produces a large number of context switches. The interpreter unlocks the "Global Interpreter Lock" every N interpreter cycles and on any system call that can block, which, if there is a thread waiting, causes a context switch. Multiple Python processes can run concurrently, but each process has a copy of the entire Python system, so the memory and cache footprints are far larger than for multiple threads. John Nagle From graham.dumpleton at gmail.com Mon Aug 24 02:51:33 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 23 Aug 2009 23:51:33 -0700 (PDT) Subject: web frameworks that support Python 3 References: Message-ID: On Aug 24, 6:34?am, Sebastian Wiesner wrote: > At Sunday 23 August 2009 22:13:16 you wrote:> I use Chinese and therefore Unicode very heavily, and so Python 3 is > > an unavoidable choice for me. > > Python 2.x supports Unicode just as well as Python 3. ?Every common web > framework works perfectly with unicode. > > In any case, there is bottle [1], which provides a *very minimal* framework > for WSGI web development. ?Don't expect too much, it is really small, and > doesn't do much more than routing and minimal templating. > > However, it is the only Python-3-compatible web framework I know of. > > [1]http://bottle.paws.de/page/start There is one big flaw with your claim. That is the there is no WSGI specification for Python 3.0 as yet. Anything that claims to work with WSGI and Python 3.0 is just a big guess as far as how WSGI for Python 3.0 may work. I would therefore be a bit cautious with your claim. Graham From kerensaelise at hotmail.com Mon Aug 24 03:04:57 2009 From: kerensaelise at hotmail.com (elsa) Date: Mon, 24 Aug 2009 00:04:57 -0700 (PDT) Subject: elementtree Message-ID: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> I have a question about elementtree: I know how to turn HTML into an ElementTree object, but I don't know how to then view the structure of this object. Is there a method or module that you can give an ElementTree object to, and it returns some kind of graphical or printed representation of the tree? Otherwise, if you can't see you're tree's structure, how do you know what is a sensible way of iterating over the tree to access the info you need? Thanks! From stefan_ml at behnel.de Mon Aug 24 03:08:07 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 09:08:07 +0200 Subject: sgmllib.py In-Reply-To: References: Message-ID: <4a923c57$0$32664$9b4e6d93@newsspool2.arcor-online.net> elsa wrote: > I'm new to both this forum and Python, and I've got a bit stuck trying > to learn how to parse HTML... If what you want to do is *parse* the HTML instead of trying to *learn* how to parse it, you might want to give the existing (external) HTML parser libraries a try. There's lxml.html (extremely fast and fixes up broken HTML), html5lib (very slow, but very browser-like parse results) and BeautifulSoup (slow, but good encoding detection if you need that). Here are a couple of (only slightly biased) comparisons: http://blog.ianbicking.org/2008/03/30/python-html-parser-performance/ http://blog.ianbicking.org/2008/12/10/lxml-an-underappreciated-web-scraping-library/ > python sgmllib.py "path/to/my/file.html" .... example (1) > > this doesn't work for me. I think I have figured out the problem - > the error says > > "/System/Library/Frameworks/Python.framework/Versions/2.5/Resources/ > Python.app/Contents/MacOS/Python: can't open file 'sgmllib.py': [Errno > 2] No such file or directory" > > the problem is that this path is wrong. My sgmllib.py is in: > > "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/sgmllib.py" You can use "python -m sgmllib" to call a module from the stdlib (or the PYTHONPATH, to be more accurate). But note that sgmllib is a particularly cumbersome way to deal with HTML. Stefan From stefan_ml at behnel.de Mon Aug 24 03:13:14 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 09:13:14 +0200 Subject: elementtree In-Reply-To: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> References: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> Message-ID: <4a923d8b$0$32664$9b4e6d93@newsspool2.arcor-online.net> Hi, elsa wrote: > I know how to turn HTML into an ElementTree object I don't. ;) ElementTree doesn't have an HTML parser, so what do you use for parsing? > but I don't know > how to then view the structure of this object. Is there a method or > module that you can give an ElementTree object to, and it returns some > kind of graphical or printed representation of the tree? Otherwise, if > you can't see you're tree's structure, how do you know what is a > sensible way of iterating over the tree to access the info you need? ElementTree has a tostring() method that returns a string. To get a pretty printed representation, you can use the indent() function from this recipe: http://effbot.org/zone/element-lib.htm#prettyprint Stefan From stefan_ml at behnel.de Mon Aug 24 03:16:32 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 09:16:32 +0200 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module In-Reply-To: <2571343.k9db9GJWqV@coder.cl> References: <2571343.k9db9GJWqV@coder.cl> Message-ID: <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> Daniel Molina Wegener wrote: > * Added encoded serialization of Unicode strings by using > the user defined encoding as is passed to the serialization > functions as enc parameter > > As you see, now Unicode strings are serialized as encoded byte string > by using the encoding that the user pass as enc parameter to the > serialization function. This means that Unicode strings are serialized > in a human readable form, regarding a better interoperability with > other platforms. You mean, the whole XML document is serialised with that encoding, right? Stefan From osky50 at gmail.com Mon Aug 24 03:25:44 2009 From: osky50 at gmail.com (osky) Date: Mon, 24 Aug 2009 00:25:44 -0700 (PDT) Subject: Python and JMS Message-ID: <679a2898-abf1-4938-a456-59e0bf5ba666@k6g2000yqn.googlegroups.com> Hi all, I would like to make a JMS client connection from Python to Progress Sonic ESB (JMS message provider similar to WebSphere MQ or Active MQ). What would be the best way to implement that within Python 2.6 ? Any ideas ? Thanks Oscar From ajoys123 at gmail.com Mon Aug 24 03:39:21 2009 From: ajoys123 at gmail.com (devaru) Date: Mon, 24 Aug 2009 00:39:21 -0700 (PDT) Subject: Simple IRC library Message-ID: <752884c5-c6fb-4974-a21a-bf3017fa4145@y4g2000prf.googlegroups.com> Hi all, I am new to Python language. I want to capture(either in database or a file) the conversation in IRC. Please suggest me some simple IRC library or code snippet for this. From stefan_ml at behnel.de Mon Aug 24 03:40:03 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 09:40:03 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <02a1cc1d$0$30337$c3e8da3@news.astraweb.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <4a918fe0$0$30226$9b4e6d93@newsspool1.arcor-online.net> <02a1cc1d$0$30337$c3e8da3@news.astraweb.com> Message-ID: <4a9243d3$0$32677$9b4e6d93@newsspool2.arcor-online.net> Steven D'Aprano wrote: > I'm amused and somewhat perplexed that somebody with the non-English > name of Stefan, writing from a .de email address, seems to be assuming > that (1) everybody is on the Internet, and (2) everybody on the Internet > speaks English. Oh, I totally don't. But most people who read c.l.py do at least understand it to a certain extent. I don't commonly read /that/ many non-english-speaking Python forums thoroughly enough to assume that the OP posted the question only in English and only in c.l.py. I don't even assume that he only posted that question to an Internet newsgroup. You know, there's real-life, too. >> But reading statements like the above really makes me feel that it's >> best to comment even on simple things like "hi guys!". > > Or you could enter the 21 century and understand that "guys" has become a > generic term for people of any sex. Is that true for everyone who understands and/or writes English? In that case, I'm fine with your above statement. Otherwise, I'd wonder who you meant with the term "cultural chauvinism". So far, I only learned that most North-American English native speakers use that term in the way you refer to. That doesn't even get you close to the majority of English speakers. Stefan From stefan_ml at behnel.de Mon Aug 24 03:43:49 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 09:43:49 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <1fa1663b-a1cb-42d4-890b-0617b73e8816@k6g2000yqn.googlegroups.com> <9b8c48a3-b050-4a13-83f5-bc4185c62bdc@t13g2000yqt.googlegroups.com> <86bb893a-344a-4c7b-9fc6-67d9f42c7607@q14g2000vbi.googlegroups.com> <62dbf088-4510-40d0-af3e-3feeb291d6e4@t13g2000yqt.googlegroups.com> <4a9197c0$0$30226$9b4e6d93@newsspool1.arcor-online.net> Message-ID: <4a9244b5$0$32671$9b4e6d93@newsspool2.arcor-online.net> Mensanator wrote: > On Aug 23, 2:25?pm, Stefan Behnel wrote: >> Mensanator wrote: >>> asking how many Jews you can fit into a Volswagen. >> None, because it's already full. > > A spelling error does not make it any less offensive. As it stands, I find the joke above perfectly acceptable. Using the word "Jew" in a joke doesn't make it anti-semitic by default. Stefan From piet at cs.uu.nl Mon Aug 24 03:51:37 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 24 Aug 2009 09:51:37 +0200 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: >>>>> Scott David Daniels (SDD) wrote: >SDD> James Harris wrote:... >>> Another option: >>> >>> 0.(2:1011), 0.(8:7621), 0.(16:c26b) >>> >>> where the three characters "0.(" begin the sequence. >>> >>> Comments? Improvements? >SDD> I did a little interpreter where non-base 10 numbers >SDD> (up to base 36) were: >SDD> .7.100 == 64 (octal) >SDD> .9.100 == 100 (decimal) >SDD> .F.100 == 256 (hexadecimal) >SDD> .1.100 == 4 (binary) >SDD> .3.100 == 9 (trinary) >SDD> .Z.100 == 46656 (base 36) I wonder how you wrote that interpreter, given that some answers are wrong. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From max at alcyone.com Mon Aug 24 04:05:40 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 01:05:40 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: MRAB wrote: > James Harris wrote: >> On 23 Aug, 00:16, Mel wrote: >>> James Harris wrote: >>>> I have no idea why Ada which uses the # also apparently uses it to end >>>> a number >>>> 2#1011#, 8#7621#, 16#c26b# >>> Interesting. They do it because of this example from >>> : >> >> Thanks for providing an explanation. >> >>> 2#1#E8 -- an integer literal of value 256 >>> >>> where the E prefixes a power-of-2 exponent, and can't be taken as a >>> digit of >>> the radix. That is to say >>> >>> 16#1#E2 >>> >>> would also equal 256, since it's 1*16**2 . >> >> Here's another suggested number literal format. First, keep the >> familar 0x and 0b of C and others and to add 0t for octal. (T is the >> third letter of octal as X is the third letter of hex.) The numbers >> above would be >> >> 0b1011, 0t7621, 0xc26b >> >> Second, allow an arbitrary number base by putting base and number in >> quotes after a zero as in >> >> 0"2:1011", 0"8:7621", 0"16:c26b" >> > Why not just put the base first, followed by the value in quotes: > > 2"1011", 8"7621", 16"c26b" It's always a bit impressive how syntax suggestions get more and more involved and, if you'll forgive me for saying, ridiculous as the conversation continues. This is starting to get truly nutty. What I've done in my projects is simply extend the pattern of 0x... for hexadecimal literals in C to 0b... for binary, 0o... for octal, 0d... for decimal (though redundant as that's the default), and so on. (Go crazy and add 0t... for trinary and 0q... for quaternary if you feel like it.) To me this always seemed elegant, simple, and understandable. If arbitrary radix values is what's desirable, then some syntax like r (e.g., 8r024222570 for an octal number which represents a very lame joke) would work, but seems to me like huge overkill. A normal string literal coupled with a "constructor" type function would seem far more appropriate -- and we already have that with `int`. As for large literals, I'd go with having spaces indicate automatic concatenation (though only the first in the series can indicate the radix, whichever method you choose above). It's the same as for strings, and it's the common SI recommendation for thousands separators anyway. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis The little I know, I owe to my ignorance. -- Sacha Guitry From max at alcyone.com Mon Aug 24 04:12:22 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 01:12:22 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> Message-ID: J. Cliff Dyer wrote: > I had an objection to using spaces in numeric literals last time around > and it still stands, and it still stands in the new one. > > What happens if you use a literal like 0x10f 304? Is 304 treated as > decimal or hexadecimal? It's not clear how you would begin to combine > it. Well, you can't combine them in any meaningful mathematical or computational sense if they're of different bases, so the answer lies therein: You shouldn't be allowed to do that. > The way string concatenation works, it takes two independent string > literals, and combines them. If you specify r'\n' 'abc\n', the first > half is treated independently as a raw string, and the second half is > treated as a normal string. The result is '\\nabc\n'. > > With numeric literals, this behavior doesn't even make sense. How do > you concatenate hex 10f with decimal 304? You can't, and the operation makes no sense, which is what makes the syntax unambiguous. An extended numeric literal continues the radix of wherever it started. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Do not seek death. Death will find you. -- Dag Hammarskjold From james.harris.1 at googlemail.com Mon Aug 24 04:16:07 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Mon, 24 Aug 2009 01:16:07 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: On 24 Aug, 02:19, Max Erickson wrote: ... > > It can be assumed however that .9. isn't in binary? > > > That's a neat idea. But an even simpler scheme might be: > > > .octal.100 > > .decimal.100 > > .hex.100 > > .binary.100 > > .trinary.100 > > > until it gets to this anyway: > > > .thiryseximal.100 > > At some point, abandoning direct support for literals and just > having a function that can handle different bases starts to make a > lot of sense to me: > > >>> int('100', 8) > 64 > >>> int('100', 10) > 100 > >>> int('100', 16) > 256 > >>> int('100', 2) > 4 > >>> int('100', 3) > 9 > >>> int('100', 36) > 1296 This is fine typed into the language directly but couldn't be entered by the user or read-in from or written to a file. James From max at alcyone.com Mon Aug 24 04:20:02 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 01:20:02 -0700 Subject: Literal concatenation, strings vs. numbers In-Reply-To: <871vn2gcai.fsf_-_@benfinney.id.au> References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> <7fe9mbF2l83bmU1@mid.individual.net> <871vn2gcai.fsf_-_@benfinney.id.au> Message-ID: Ben Finney wrote: > Yet, as was pointed out, that behaviour would be inconsistent with the > concatenation of string literals:: > > >>> "abc" r'def' u"ghi" 'jkl' > u'abcdefghijkl' > > So, different representations of literals are parsed as separate > literals, then concatenated. To have the behaviour you describe, the > case needs to be made separately that digit concatenation should not be > consistent with the established string literal parsing behaviour. Since digit concatenation can't possibly be useful any other way, it makes perfect sense. Why is the operator ** right-to-left associative? The same basic reason: Because it would be dumb for it not to be. Does that make it confusing and inconsistent compared to most of the other binary operators? In some sense, yes, it does. But it also makes it sane. Is anyone so upset by this that it didn't make it into the language, or cause huge confusion on a regular basis that upsets a lot of users? Nope. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Do not seek death. Death will find you. -- Dag Hammarskjold From nmm1 at cam.ac.uk Mon Aug 24 04:24:50 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Mon, 24 Aug 2009 09:24:50 +0100 (BST) Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> Message-ID: In article <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e at w6g2000yqw.googlegroups.com>, sturlamolden wrote: >On 24 Aug, 02:26, nos... at see.signature (Richard Maine) wrote: > >> You missed the word "OOP", which seemed like the whole point. Not that >> the particular word is used in the Fortran standard, but it isn't hard >> to guess that he means a derived type that uses some of the OOP >> features. Inheritance, polymorphism, and type-bound procedure (aka >> methods in some other languages) come to mind. > >But C is not OOP. The ISO C bindings in Fortran are not ISO C++ >bindings. This is for a reason: C++ does not have a standard ABI like >ISO C. Nor does C. Almost everything that most people believe about C is wrong, because C is not well-defined at any level, so there are many twisty little C languages, all different. Richard is perfectly correct that my point was OOP. C interoperability does not apply to any derived type with type-bound procedures, which include finalizers. Note that this ALSO forbids them from being passed as data, even if the other language never uses the OOP features of the type. Regards, Nick Maclaren. From james.harris.1 at googlemail.com Mon Aug 24 04:25:35 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Mon, 24 Aug 2009 01:25:35 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: On 24 Aug, 09:05, Erik Max Francis wrote: ... > >> Here's another suggested number literal format. First, keep the > >> familar 0x and 0b of C and others and to add 0t for octal. (T is the > >> third letter of octal as X is the third letter of hex.) The numbers > >> above would be > > >> ? 0b1011, 0t7621, 0xc26b > > >> Second, allow an arbitrary number base by putting base and number in > >> quotes after a zero as in > > >> ? 0"2:1011", 0"8:7621", 0"16:c26b" > > > Why not just put the base first, followed by the value in quotes: > > > ? ? 2"1011", 8"7621", 16"c26b" > > It's always a bit impressive how syntax suggestions get more and more > involved and, if you'll forgive me for saying, ridiculous as the > conversation continues. ?This is starting to get truly nutty. Why do you say that here? MRAB's suggestion is one of the clearest there has been. And it incorporates the other requirements: starts with a digit, allows an appropriate alphabet, has no issues with spacing digit groups, shows clearly where the number ends and could take an exponent suffix. James From hendrik at microcorp.co.za Mon Aug 24 04:29:20 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 24 Aug 2009 10:29:20 +0200 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: <200908241029.20487.hendrik@microcorp.co.za> On Monday 24 August 2009 01:04:37 bartc wrote: > That's a neat idea. But an even simpler scheme might be: > > .octal.100 > .decimal.100 > .hex.100 > .binary.100 > .trinary.100 > > until it gets to this anyway: > > .thiryseximal.100 Yeah right. So now I first have to type a string, which probably has a strict spelling, before a number. It is only marginally less stupid than this: 1.0 - Unary 11.0101 - Binary 111. 012012 - Trinary 11111111.01234567 - Octal 1111111111.0123456789 - Decimal 1111111111111111.0123456789abcdef - Hex Any parser that can count will immediately know what to do. I also tried to include an example of a literal with a base of a Googol but I ran out of both ink and symbols. :-) - Hendrik From max at alcyone.com Mon Aug 24 04:30:11 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 01:30:11 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: <_oidnbiiYrgJ0g_XnZ2dnUVZ_uVi4p2d@giganews.com> James Harris wrote: > On 24 Aug, 09:05, Erik Max Francis wrote: >>>> Here's another suggested number literal format. First, keep the >>>> familar 0x and 0b of C and others and to add 0t for octal. (T is the >>>> third letter of octal as X is the third letter of hex.) The numbers >>>> above would be >>>> 0b1011, 0t7621, 0xc26b >>>> Second, allow an arbitrary number base by putting base and number in >>>> quotes after a zero as in >>>> 0"2:1011", 0"8:7621", 0"16:c26b" >>> Why not just put the base first, followed by the value in quotes: >>> 2"1011", 8"7621", 16"c26b" >> It's always a bit impressive how syntax suggestions get more and more >> involved and, if you'll forgive me for saying, ridiculous as the >> conversation continues. This is starting to get truly nutty. > > Why do you say that here? MRAB's suggestion is one of the clearest > there has been. And it incorporates the other requirements: starts > with a digit, allows an appropriate alphabet, has no issues with > spacing digit groups, shows clearly where the number ends and could > take an exponent suffix. In your opinion. Obviously not in others. Which is pretty obviously what I meant, so the rhetorical question is a bit weird here. There's a reason that languages designed by committee end up horrific nightmares. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Do not seek death. Death will find you. -- Dag Hammarskjold From max at alcyone.com Mon Aug 24 04:35:47 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 01:35:47 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: James Harris wrote: > On 24 Aug, 02:19, Max Erickson wrote: >>> It can be assumed however that .9. isn't in binary? >>> That's a neat idea. But an even simpler scheme might be: >>> .octal.100 >>> .decimal.100 >>> .hex.100 >>> .binary.100 >>> .trinary.100 >>> until it gets to this anyway: >>> .thiryseximal.100 >> At some point, abandoning direct support for literals and just >> having a function that can handle different bases starts to make a >> lot of sense to me: >> >>>>> int('100', 8) >> 64 >>>>> int('100', 10) >> 100 >>>>> int('100', 16) >> 256 >>>>> int('100', 2) >> 4 >>>>> int('100', 3) >> 9 >>>>> int('100', 36) >> 1296 > > This is fine typed into the language directly but couldn't be entered > by the user or read-in from or written to a file. Why would a programmer be expecting an arbitrary-radix numeric literal typed in by a user or read from a file? If you're reading it from a file, you've already got it in some satisfactory form, binary or otherwise. If you're taking it as input from a user, they're not going to know the Python syntax anyway, and would type in the radix and then the literal (in the unlikely case this would ever be required, which is still hard to imagine). Either way, conversion is, as Max showed, one line of code. It's hard to see the explicit need for truly arbitrary-radix literals in any language -- and I'm the guy who's put quaternary literals in syntaxes he's had to develop just for fun. Binary, octal, decimal, hexadecimal, sure. Beyond that it's a solution begging for problems. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Do not seek death. Death will find you. -- Dag Hammarskjold From hendrik at microcorp.co.za Mon Aug 24 04:40:06 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 24 Aug 2009 10:40:06 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a91db65$0$305$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> Message-ID: <200908241040.06613.hendrik@microcorp.co.za> On Monday 24 August 2009 02:14:24 Esben von Buchwald wrote: > Hello > > I'm using Python for S60 1.9.7 on my Nokia phone. > > I've made a program that gets input from an accelerometer sensor, and > then calculates some stuff and displays the result. > > The sensor framework API does a callback to a function defined by me, > every time new data is available. > > The problem is, that sometimes, the calculations may take longer than > others, but if the callback is called before the first calculation is > done, it seems like it's queuing up all the callbacks, and execute them > sequentially, afterwards. > > What I need, is to simply ignore the callback, if the previous call > hasn't finished it's operations before it's called again. > > I thought that this code would do the trick, but it obviously doesn't > help at all, and i can't understand why... > > def doCallback(self): > if self.process_busy==False: > self.process_busy=True > self.data_callback() > self.process_busy=False > see if there is an "after" method somewhere. What you have to do is to "break the link" between the callback and the processing. Your code above is all in the callback "thread", despite the fact that you call another function to do the processing. So if you replace the data_callback() with an after call, it should work as you expect. HTH - Hendrik From max at alcyone.com Mon Aug 24 04:41:14 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 01:41:14 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: Hendrik van Rooyen wrote: > I also tried to include an example of a literal with a base of a Googol but I > ran out of both ink and symbols. > :-) ... or particles in the observable Universe, for that matter. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis Do not seek death. Death will find you. -- Dag Hammarskjold From piet at cs.uu.nl Mon Aug 24 04:41:58 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 24 Aug 2009 10:41:58 +0200 Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> Message-ID: >>>>> Dennis Lee Bieber (DLB) wrote: >DLB> On Sun, 23 Aug 2009 22:14:17 -0700, John Nagle >DLB> declaimed the following in gmane.comp.python.general: >>> Multiple Python processes can run concurrently, but each process >>> has a copy of the entire Python system, so the memory and cache footprints are >>> far larger than for multiple threads. >>> >DLB> One would think a smart enough OS would be able to share the >DLB> executable (interpreter) code, and only create a new stack/heap >DLB> allocation for data. Of course they do, but a significant portion of a Python system consists of imported modules and these are data as far as the OS is concerned. Only the modules written in C which are loaded as DLL's (shared libs) and of course the interpreter executable will be shared. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 24 04:44:21 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 24 Aug 2009 10:44:21 +0200 Subject: Items inheriting attributes from its container? In-Reply-To: References: Message-ID: <4a9252e5$0$17143$426a74cc@news.free.fr> Kreso a ?crit : > I would like to create a list-like container class so that, additionally > to usual list methods, I could attach attributes to the container instances. > However, I would like it so that the items contained in the particular > instance of container somehow 'inherit' those attributes i.e. > > cont = Container() > cont.color = 'blue' > cont.append(item) > print item.color > 'blue' > This is named "environmental aquisition" (or simply "aquisition") and is one of the base mechanisms in Zope 2. While an interesting idea, from experience, it can rapidly turn into a total maintainance nightmare if not used with care :-/ From james.harris.1 at googlemail.com Mon Aug 24 04:47:44 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Mon, 24 Aug 2009 01:47:44 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <_oidnbiiYrgJ0g_XnZ2dnUVZ_uVi4p2d@giganews.com> Message-ID: On 24 Aug, 09:30, Erik Max Francis wrote: > James Harris wrote: > > On 24 Aug, 09:05, Erik Max Francis wrote: > >>>> Here's another suggested number literal format. First, keep the > >>>> familar 0x and 0b of C and others and to add 0t for octal. (T is the > >>>> third letter of octal as X is the third letter of hex.) The numbers > >>>> above would be > >>>> ? 0b1011, 0t7621, 0xc26b > >>>> Second, allow an arbitrary number base by putting base and number in > >>>> quotes after a zero as in > >>>> ? 0"2:1011", 0"8:7621", 0"16:c26b" > >>> Why not just put the base first, followed by the value in quotes: > >>> ? ? 2"1011", 8"7621", 16"c26b" > >> It's always a bit impressive how syntax suggestions get more and more > >> involved and, if you'll forgive me for saying, ridiculous as the > >> conversation continues. ?This is starting to get truly nutty. > > > Why do you say that here? MRAB's suggestion is one of the clearest > > there has been. And it incorporates the other requirements: starts > > with a digit, allows an appropriate alphabet, has no issues with > > spacing digit groups, shows clearly where the number ends and could > > take an exponent suffix. > > In your opinion. ?Obviously not in others. ?Which is pretty obviously > what I meant, so the rhetorical question is a bit weird here. Don't get defensive.... Yes, in my opinion, if you like, but you can't say "obviously not in others" as no one else but you has commented on MRAB's suggestion. Also, when you say "This is starting to get truly nutty" would you accept that that's in your opinion? > There's a reason that languages designed by committee end up horrific > nightmares. True but I would suggest that mistakes are also made by designers who do not seek the opinions of others. There's a balance to be struck between a committee and an ivory tower. James From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 24 04:54:31 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 24 Aug 2009 10:54:31 +0200 Subject: Newbie: list comprehension troubles.. In-Reply-To: References: Message-ID: <4a925547$0$22644$426a74cc@news.free.fr> mm a ?crit : > Hi, I'm trying to replace this... > > # this works but there must be a more pythonic way, right? > tlist = [] > for obj in self.objs: > t = obj.intersect(ray) > if (t != None): hint 1 : this is Python, you don't need parens around conditionals. hint 2 : None is a singleton, so the usual idiom is to test for identity ('is') instead of equality ('==') IOW, make this line: if t is not None: > tlist.append((obj,t)) > > with a list comprehension- can it be done? See other answers here. As far as I'm concerned, while being a great fan of list comps etc, I'd stick with the plain old for loop here - much more readable if nothing else. From davea at ieee.org Mon Aug 24 05:04:19 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 24 Aug 2009 05:04:19 -0400 Subject: sgmllib.py In-Reply-To: References: Message-ID: <4A925793.9030305@ieee.org> elsa wrote: > Hi all, > > I'm new to both this forum and Python, and I've got a bit stuck trying > to learn how to parse HTML.... here is my problem > > I'm using a textbook that uses sgmllib.py for all its examples. I'm > aware that sgmllib is not in the current release, however I want to > get it to work, as I have python 2.5, and the text book uses it. > > So, the first example says to type something like (to test the > sgmllib): > > python sgmllib.py "path/to/my/file.html" .... example (1) > > this doesn't work for me. I think I have figured out the problem - > the error says > > "/System/Library/Frameworks/Python.framework/Versions/2.5/Resources/ > Python.app/Contents/MacOS/Python: can't open file 'sgmllib.py': [Errno > 2] No such file or directory" > > the problem is that this path is wrong. My sgmllib.py is in: > > "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/sgmllib.py" > > if I substitute this path for sgmllib.py in example (1), everything > works fine. However, I don't want to do all that typing everytime I > want to use sgmllib.py. So, I thought maybe the problem was with > PYTHONPATH. I executed the following command: > > export PYTHONPATH=/System/Library/Frameworks/Python.framework/Versions/ > 2.5/li/python2.5:$PYTHONPATH > > this seemed to work - no errors raised. However, when I retyped > example (1), I got the same original error. > > Any assistance would be much appreciated. I'm working on max os x > leopard. > > Thanks, > > elsa > > The path in the error message simply refers to the full path string to your Python interpreter, and reflects %0 in your shell. So I'd assume you've got a script called 'python' on your path, which spells out the full path name. That has nothing to do with your problem. Your problem, as you correctly surmised, is that Python's search path doesn't include the directory containing sgmllib.py Unfortunately, I haven't used Unix for over 15 years, so I don't recall the specifics of the shell 'export' operation. But you should be able to check the workings by inspecting the PYTHONPATH variable after trying to change it. There are a number of places that Python looks for a .py file. My choice, for a standard library like this that you don't plan to modify, would be to put it in the site-packages directory. You can see exactly where that is by doing the following in a simple script, and examining the output. import sys print sys.path From deets at nospam.web.de Mon Aug 24 05:06:00 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Aug 2009 11:06:00 +0200 Subject: Python and JMS References: <679a2898-abf1-4938-a456-59e0bf5ba666@k6g2000yqn.googlegroups.com> Message-ID: <7ff3foF2kcl0rU1@mid.uni-berlin.de> osky wrote: > Hi all, > > I would like to make a JMS client connection from Python to Progress > Sonic ESB (JMS message provider similar to WebSphere MQ or Active > MQ). > > What would be the best way to implement that within Python 2.6 ? > Any ideas ? I just recently learned about JCC - a Java-wrapper-compiler for python that is used by pylucene to embed (!) the JVM into python. This might be one viable option. I don't know much more, though. Diez From stefan_ml at behnel.de Mon Aug 24 05:16:38 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 11:16:38 +0200 Subject: sgmllib.py In-Reply-To: References: Message-ID: <4a925a76$0$32668$9b4e6d93@newsspool2.arcor-online.net> Dave Angel schrieb: > elsa wrote: >> python sgmllib.py "path/to/my/file.html" .... example (1) > > The path in the error message simply refers to the full path string to > your Python interpreter, and reflects %0 in your shell. So I'd assume > you've got a script called 'python' on your path, which spells out the > full path name. No, the problem is that "sgmllib.py" simply isn't in the directory where the Python interpreter is run. When you say python sgmllib.py you are instructing the Python interpreter to run the script "sgmllib.py" *in the current directory*. According to the original post, that's clearly not the intention of the OP. Stefan From davea at ieee.org Mon Aug 24 05:23:24 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 24 Aug 2009 05:23:24 -0400 Subject: basic thread question In-Reply-To: References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> Message-ID: <4A925C0C.4090906@ieee.org> Dennis Lee Bieber wrote: > On Sun, 23 Aug 2009 22:14:17 -0700, John Nagle > declaimed the following in gmane.comp.python.general: > > >> Multiple Python processes can run concurrently, but each process >> has a copy of the entire Python system, so the memory and cache footprints are >> far larger than for multiple threads. >> >> > One would think a smart enough OS would be able to share the > executable (interpreter) code, and only create a new stack/heap > allocation for data. > That's what fork is all about. (See os.fork(), available on most Unix/Linux) The two processes start out sharing their state, and only the things subsequently written need separate swap space. In Windows (and probably Unix/Linux), the swapspace taken by the executable and DLLs(shared libraries) is minimal. Each DLL may have a "preferred location" and if that part of the address space is available, it takes no swapspace at all, except for static variables, which are usually allocated together. I don't know whether the standard build of CPython (python.exe and the pyo libraries) uses such a linker option, but I'd bet they do. It also speeds startup time. On my system, a minimal python program uses about 50k of swapspace. But I'm sure that goes way up with lots of imports. DaveA From davea at ieee.org Mon Aug 24 05:29:43 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 24 Aug 2009 05:29:43 -0400 Subject: elementtree In-Reply-To: <4a923d8b$0$32664$9b4e6d93@newsspool2.arcor-online.net> References: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> <4a923d8b$0$32664$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4A925D87.5010905@ieee.org> Stefan Behnel wrote: > Hi, > > elsa wrote: > >> I know how to turn HTML into an ElementTree object >> > > I don't. ;) > > ElementTree doesn't have an HTML parser, so what do you use for parsing? > > > >> but I don't know >> how to then view the structure of this object. Is there a method or >> module that you can give an ElementTree object to, and it returns some >> kind of graphical or printed representation of the tree? Otherwise, if >> you can't see you're tree's structure, how do you know what is a >> sensible way of iterating over the tree to access the info you need? >> > > ElementTree has a tostring() method that returns a string. To get a pretty > printed representation, you can use the indent() function from this recipe: > > http://effbot.org/zone/element-lib.htm#prettyprint > > Stefan > > Perhaps the OP was referring to XHTML, which should be eligible for ElementTree. But could you tell me whether ElementTree is at all tolerant of malformed XML? Most HTML and XHTML I encounter in the wild is so buggy it's amazing it all works at all. DaveA From stefan_ml at behnel.de Mon Aug 24 05:54:39 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 11:54:39 +0200 Subject: elementtree In-Reply-To: References: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> <4a923d8b$0$32664$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <4a92635f$0$32678$9b4e6d93@newsspool2.arcor-online.net> Dave Angel wrote: > Stefan Behnel wrote: >> elsa wrote: >>> I know how to turn HTML into an ElementTree object >> >> I don't. ;) >> >> ElementTree doesn't have an HTML parser, so what do you use for parsing? >> > Perhaps the OP was referring to XHTML, which should be eligible for > ElementTree. But could you tell me whether ElementTree is at all > tolerant of malformed XML? Most HTML and XHTML I encounter in the wild > is so buggy it's amazing it all works at all. Well, if the XHTML is "buggy", it's not XHTML at all. XHTML is XML, which is defined as being well-formed. Any XHTML parser is required to reject malformed input, and the expat parser that ElementTree uses is (luckily) no exception. Regarding malformed HTML: that's not directly supported by ElementTree, hence my question. You can use ElementSoup to interface with BeautifulSoup, or elementtidy to interface with tidy, or html5lib with ElementTree as backend, or you can use lxml instead, which handles malformed HTML (and is all fast and shiny and ... ;). Stefan From stefan_ml at behnel.de Mon Aug 24 06:12:19 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 12:12:19 +0200 Subject: Python and JMS In-Reply-To: <679a2898-abf1-4938-a456-59e0bf5ba666@k6g2000yqn.googlegroups.com> References: <679a2898-abf1-4938-a456-59e0bf5ba666@k6g2000yqn.googlegroups.com> Message-ID: <4a926783$0$32673$9b4e6d93@newsspool2.arcor-online.net> osky wrote: > I would like to make a JMS client connection from Python to Progress > Sonic ESB (JMS message provider similar to WebSphere MQ or Active > MQ). Never needed this, but Google gives me this as first hit http://hjb.python-hosting.com/ and this c.l.py thread reference a little further down: http://mail.python.org/pipermail/python-list/2006-July/567400.html Stefan From pavlovevidence at gmail.com Mon Aug 24 06:56:08 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 24 Aug 2009 03:56:08 -0700 (PDT) Subject: Literal concatenation, strings vs. numbers (was: Numeric literals in other than base 10 - was Annoying octal notation) References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> <7fe9mbF2l83bmU1@mid.individual.net> <871vn2gcai.fsf_-_@benfinney.id.au> Message-ID: <3353e3ec-384a-4786-bd33-b26ab26df129@l5g2000yqo.googlegroups.com> On Aug 23, 7:45?pm, Ben Finney wrote: > greg writes: > > J. Cliff Dyer wrote: > > > > What happens if you use a literal like 0x10f 304? > > > To me the obvious thing to do is concatenate them textually and then > > treat the whole thing as a single numeric literal. Anything else > > wouldn't be sane, IMO. > > Yet, as was pointed out, that behaviour would be inconsistent with the > concatenation of string literals:: > > ? ? >>> "abc" r'def' u"ghi" 'jkl' > ? ? u'abcdefghijkl' Well my take on it is that this would not be the same as string concatenation, the series of digits would be parsed as a single token with spaces automatically removed. That does make a difference to the users (it's not just under the covers). For instance, string concatenation works across lines: "abc" "def" but if the numbers were parsed as a single token it wouldn't necessarily be allowed, and would be unwise, so this is out: 100 200 You might want to also enforce rules such as only a single space can separate digits, no tabs, not multiple spaces, so this 100 200 would also be right out. You might even want to enforce that spaces be at regular intervals. I don't think it would matter too much that digit separation can superficially resemble string concatenation if you don't break the strings across lines, it's not too difficult to explain what the difference is, and there's really not much chance anyone would be confused by their meanings. Having said all that, I would favor _ as a digit separator in Python any day of the week, and I don't think it's all that important to have one at all. HOWEVER, I once proposed that if I were designing a new language I'd consider allowing spaces in identifiers. (That didn't stop people from arguing why it would be confusing in Python, but never mind that.) If spaces were allowed in identifiers, then I'd be also in favor of spaces in numeric literals. > So, different representations of literals are parsed as separate > literals, then concatenated. To have the behaviour you describe, the > case needs to be made separately that digit concatenation should not be > consistent with the established string literal parsing behaviour. Well, one doesn't really *need* to make that case, they just might not care about consistency. But if they did I think Erik's case is a good one: very little chance of confusion because there's really only one reasonable interpretation. The point of consistency is to help understand things by analogy, but if analogy doesn't help understanding--and it wouldn't in this case--there's no point. Carl Banks From pavlovevidence at gmail.com Mon Aug 24 07:00:46 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 24 Aug 2009 04:00:46 -0700 (PDT) Subject: elementtree References: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> <4a923d8b$0$32664$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <446e340c-82cc-4533-ae64-53d45ce765a2@24g2000yqm.googlegroups.com> On Aug 24, 12:13?am, Stefan Behnel wrote: > Hi, > > elsa wrote: > > I know how to turn HTML into an ElementTree object > > I don't. ;) > > ElementTree doesn't have an HTML parser, so what do you use for parsing? The OP could be feeding the HTML through tidy, or it could be XHTML. > > but I don't know > > how to then view the structure of this object. Is there a method or > > module that you can give an ElementTree object to, and it returns some > > kind of graphical or printed representation of the tree? Otherwise, if > > you can't see you're tree's structure, how do you know what is a > > sensible way of iterating over the tree to access the info you need? > > ElementTree has a tostring() method that returns a string. To get a pretty > printed representation, you can use the indent() function from this recipe: > > http://effbot.org/zone/element-lib.htm#prettyprint Another possibility is to write out the ElementTree object as XML with an .xml extension, and view it in a modern web browser (Firefox, IE, others maybe) that can show XML structure. Carl Banks From martin.hellwig at dcuktec.org Mon Aug 24 07:06:30 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Mon, 24 Aug 2009 12:06:30 +0100 Subject: can python make web applications? In-Reply-To: References: Message-ID: Deep_Feelings wrote: > can python make powerfull database web applications that can replace > desktop database applications? e.g: entrprise accounting > programs,enterprise human resource management programs ...etc As the other replies already mentioned that these already exists, I would like to add that with Pyjamas you can write 'webgui' programs relatively easily: http://pyjs.org/ -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From piet at cs.uu.nl Mon Aug 24 07:21:03 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 24 Aug 2009 13:21:03 +0200 Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> Message-ID: >>>>> Dave Angel (DA) wrote: >DA> Dennis Lee Bieber wrote: >>> On Sun, 23 Aug 2009 22:14:17 -0700, John Nagle >>> declaimed the following in gmane.comp.python.general: >>> >>> >>>> Multiple Python processes can run concurrently, but each process >>>> has a copy of the entire Python system, so the memory and cache footprints are >>>> far larger than for multiple threads. >>>> >>>> >>> One would think a smart enough OS would be able to share the >>> executable (interpreter) code, and only create a new stack/heap >>> allocation for data. >>> >DA> That's what fork is all about. (See os.fork(), available on most >DA> Unix/Linux) The two processes start out sharing their state, and only the >DA> things subsequently written need separate swap space. But os.fork() is not available on Windows. And I guess refcounts et al. will soon destroy the sharing. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From jeanmichel at sequans.com Mon Aug 24 07:33:07 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 Aug 2009 13:33:07 +0200 Subject: your favorite debugging tool? In-Reply-To: References: Message-ID: <4A927A73.5080207@sequans.com> Esmail wrote: > Hi all, > > What is your favorite tool to help you debug your > code? I've been getting along with 'print' statements > but that is getting old and somewhat cumbersome. > > I'm primarily interested in utilities for Linux (but > if you have recommendations for Windows, I'll take > them too :) > > I use emacs as my primary development environment, FWIW. > Someone mentioned winpdb .. anyone have experience/comments > on this? Others? > > Thanks, > Esmail > I execute the program within IPython. >>> run test.py I usually write a CTRL+C except clause that will spawn an Ipython shell so I can inspect the namespace at that time. I'm also using the ipdb to spawn the debugger. import IPython ipdb = IPython.Debugger.Pdb(color_scheme='Linux') ipdb.set_trace() it spawns the IPython debugger, allowing step by step execution, code inspection, changing the namespace. You get all the IPython benefits (espacially the TAB completion, history ...) I used to proceed with print statements, but they are some situations where it won't just make it. Sometimes the code is so complex you can't anticipate all the required prints to catch a bug. JM From bieffe62 at gmail.com Mon Aug 24 07:42:29 2009 From: bieffe62 at gmail.com (Francesco Bochicchio) Date: Mon, 24 Aug 2009 04:42:29 -0700 (PDT) Subject: Newbie: list comprehension troubles.. References: Message-ID: <86e872ed-eb86-4def-ad55-49ee60f61cf0@a26g2000yqn.googlegroups.com> On 24 Ago, 01:27, mm wrote: > Hi, I'm trying to replace this... > > ? ? ? ? # this works but there must be a more pythonic way, right? > ? ? ? ? tlist = [] > ? ? ? ? for obj in self.objs: > ? ? ? ? ? ? t = obj.intersect(ray) > ? ? ? ? ? ? if (t != None): > ? ? ? ? ? ? ? ? tlist.append((obj,t)) > > with a list comprehension- can it be done? > > What I need to do is iterate over a list of graphics primitives and > call their intersect method. If the returned t value is not None then > I want to store the obj refernence and its t value in a list of tuples > for further processing. I've tried stuff like ... > > ? ? ? ? tlist = [(obj,t) for obj,t in (self.objs, obj.intersect(ray)) > if (t != None)] > ? ? ? ? tlist = [(obj,t) for obj in self.objs for t in obj.intersect > (ray) ] > ? ? ? ? print ">>> ",len(tlist), tlist > > but they don't work. Any help greatly appreciated. matt What about this: def intersections(objlist, ray): for obj in objlist: yield obj, obj.intersect(ray) tlist = [(obj, t) in intersections(self.objs, ray) if t != None ] It is still quite readable but a bit more compact. More efficient? Maybe. Ciao ---- FB From nospam at nospam.com Mon Aug 24 08:08:40 2009 From: nospam at nospam.com (Gilles Ganault) Date: Mon, 24 Aug 2009 14:08:40 +0200 Subject: Python for professsional Windows GUI apps? Message-ID: Hello I was wondering if some people in this ng use Python and some GUI toolkit (PyWin32, wxWidgets, QT, etc.) to build professional applications, and if yes, what it's like, the pros and cons, etc. I'm especially concerned about the lack of controls, the lack of updates (lots of controls in wxWidgets are 1.0 deadware), and problems linked to how to update users' PC remotely when I build a new version using eg. Py2exe. I need controls for business apps like access to databases, good data grid, printing reports (with or without barcodes), etc. Thank you. From jeanmichel at sequans.com Mon Aug 24 08:08:47 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Mon, 24 Aug 2009 14:08:47 +0200 Subject: Is Python what I need? In-Reply-To: References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: <4A9282CF.3000204@sequans.com> Peter Otten wrote: > newbie wrote: > > >> I'm interested in developing computer based, interactive programs for >> students in a special school who have an aversion to pen and paper. >> I've searched the net to find ready made software that will meet my >> needs but it is either written to a level much higher than these >> students can cope with or priced beyond our school budget. I came >> across a blog of someone singing the praises of Python. My question is >> therefore aimed at those that know what they are talking about (ie >> users in this group). Is Python the language I need to learn to >> develop these programs? >> > > >From the distance it looks like these children need a good teacher rather > than a bad (or just starting) programmer. Wow, that is rude. Let's keep this list friendly, won't we ? JM From nevillednz at gmail.com Mon Aug 24 08:22:42 2009 From: nevillednz at gmail.com (NevilleDNZ) Date: Mon, 24 Aug 2009 05:22:42 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: On Aug 23, 9:42 pm, James Harris wrote: > The numbers above would be > > 0b1011, 0t7621, 0xc26b Algol68 has the type BITS, that is converted to INT with the ABS operator. The numbers above would be: > 2r1011, 8r7621, 16rc26b "r" is for radix: http://en.wikipedia.org/wiki/Radix The standard supports 2r, 4r, 8r & 16r only. The standard supports LONG BITS, LONG LONG BITS etc, but does not include UNSIGNED. Compare gcc's: bash$ cat num_lit.c #include main(){ printf("%d %d %d %d\n",0xffff,07777,9999,0b1111); } bash$ ./num_lit 65535 4095 9999 15 With Algol68's: https://sourceforge.net/projects/algol68/ bash$ cat num_lit.a68 main:( printf(($g$,ABS 16rffff,ABS 8r7777,9999,ABS 2r1111,$l$)) ) bash$ algol68g ./num_lit.a68 +65535 +4095 +9999 +15 Enjoy N From dmw at coder.cl Mon Aug 24 08:29:48 2009 From: dmw at coder.cl (Daniel Molina Wegener) Date: Mon, 24 Aug 2009 08:29:48 -0400 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module References: <2571343.k9db9GJWqV@coder.cl> <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <2665032.o6QR52tnKS@coder.cl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Stefan Behnel on Monday 24 August 2009 03:16 wrote in comp.lang.python: > Daniel Molina Wegener wrote: >> * Added encoded serialization of Unicode strings by using >> the user defined encoding as is passed to the serialization >> functions as enc parameter >> >> As you see, now Unicode strings are serialized as encoded byte string >> by using the encoding that the user pass as enc parameter to the >> serialization function. This means that Unicode strings are serialized >> in a human readable form, regarding a better interoperability with >> other platforms. > > You mean, the whole XML document is serialised with that encoding, right? Well, if you call pyxser with: xmldocstr = pyxser.serialize(obj = someobj, enc = "utf-8", depth = 3) pyxser will serialize someobj into XML document (xmldocstr) using the utf-8 encoding with a depth of three levels in the object tree. If the object tree has unicode objects, those objects will be encoded into utf-8 too. And yes, it means that unicode objects are encoded into the encoding that the XML document encoding has, and as you say, the whole XML document has one encoding. There is no mixing of byte encoded strings with different encodings in the outout document. When the object is restored, by using pyxser.unserialize: pyobj = pyxser.unserialize(obj = xmldocstr, enc = "utf-8") Unicode objects are restored as unicode objects, by decoding the utf-8 strings on the document. Byte string objects are restored as byte string objects. And the other types of objects are restored as their original type. Another issue is the fact that if you have mixed some encodings in byte strings objects in your object tree, such as iso-8859-1 and utf-8, and you try to serialize that object, pyxser will output to stdout the serialization errors by trying to handle those mixed encodings which are not regarding the document encoding. There are some restrictions, if the class of the object is declared on the __main__ module, pyxser can not handle it... This is a bug but I'm expecting to solve it in near future. A depth level of zero (depth = 0) will serialize the complete object tree with a fixed limit of 50 levels, pyxser can handle cross referenced objects and circular references. Sorry if don't answer more questions until we reach the night --- here in Chile --- the night, I must go to my job right now, and there I don't have access to usenet or google groups. > > Stefan Best regards, - -- .O. | Daniel Molina Wegener | FreeBSD & Linux ..O | dmw [at] coder [dot] cl | Open Standards OOO | http://coder.cl/ | FOSS Developer -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (FreeBSD) iQIcBAEBCgAGBQJKkoe8AAoJEHxqfq6Y4O5Na3gP/R2BTdmZpUPn8PrsPhMPaKLf dmAUAyQ2Ukj1461eiYGAa1zly5bz/rKV8UJXq6zp0cFIIimBHWCYkFlbtCIdCl5k qclT6y3d5N9/VggZi92ICK4xFe4CCOzLeJCaYkBcVgvbpks9oRJwlS9LrTZAMdOw WdnaUdNadj2lRcXHwqV7uk5D5CwBdNujgpp+7vJXZbEnPD9diXEbPDUeHznn7cEa 2zwtGK3+kyPEkLpS5F+zE2iPUQK+HOw4r1s7kow9mSUU0n3p+gJj9J0NtBKDa92d hXGQ6M52jtoyZlv0bWJl8R1YQLnezvNDMu9F/NqB79wmLhJqIZm3Py57rtIaD96J 2a7BN/LcM8fhs+dgTlt6538EKoM5Jj+gv+birSIUwxKFChRpGsj7229cmTzjQc7q mcXlXPa6aknOWxVlhPSpGDSbZ+HpqGH7s9cOHAAuUt+WRcaafeRpy7K3BXJ+AaJ6 Rz69j2nsOgqGufLlBiDf9aRIrX3A47eE0DGZLwVuolValgmBhgedn43T4XH85wrE BfXERoIrIlMS8hmcxs6Ao6TayLHmaZjSVaLmP+qsN9qHCs8hCbQBNBfaU1vrsM2u nppo/+yGepLGZSW35yA8ha7m3RAX1HTyHcKrPcrbTmK5IVjVWjHRbTz4XcqNt1v6 5prWXP8WUIfIr4E2112J =JjU5 -----END PGP SIGNATURE----- From ryniek90 at gmail.com Mon Aug 24 08:44:59 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Mon, 24 Aug 2009 14:44:59 +0200 Subject: Temat:,Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: References: Message-ID: <4A928B4B.9030502@gmail.com> >> John Machin wrote: >> >>> Erik Max Francis alcyone.com> writes: >>> > > >> I also suspect the "pipe" symbol. I don't know if it's an invalid >> character to Windows, but it's certainly a bad idea. The '|' character >> means something special to the shell. >> > > The "pipe" character is not a valid character in a Windows file. > Despite the OP's message wrapping the filename in "pipes", > there are no pipes in the filename in the traceback to > which he posted a link. Wrapping the filename in "pipes" > and the cryptic reference to "the '|\U' literal fault" > appear to be side-issue bogglements. > > >>> open('boggle|txt', 'wb') > Traceback (most recent call last): > File "", line 1, in > IOError: [Errno 22] invalid mode ('wb') or filename: 'boggle|txt' > >>> open('|boggle.txt|', 'wb') > Traceback (most recent call last): > File "", line 1, in > IOError: [Errno 22] invalid mode ('wb') or filename: '|boggle.txt|' > > > > Sorry, but i don't know where those pipes came from : P The proper path is "C:\\Users\\Ryniek's WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2" and that string literal is "\U", without any pipes :) The truth is that script works on linux (ubuntu) but not on windows (neither Win7 nor WinXP). Maybe it's good idea to use raw string for specifing those paths? As i mentioned later, some python users had the same problem with this IOError ( like here: http://www.daniweb.com/forums/thread174552.html or here: http://groups.google.com/group/sympy/browse_thread/thread/c42aca3eb532928c ). From stefan_ml at behnel.de Mon Aug 24 09:00:06 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 15:00:06 +0200 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module In-Reply-To: <2665032.o6QR52tnKS@coder.cl> References: <2571343.k9db9GJWqV@coder.cl> <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> <2665032.o6QR52tnKS@coder.cl> Message-ID: <4a928ed7$0$32666$9b4e6d93@newsspool2.arcor-online.net> Daniel Molina Wegener wrote: > unicode objects are encoded into the > encoding that the XML document encoding has, and as you say, the whole > XML document has one encoding. There is no mixing of byte encoded strings > with different encodings in the outout document. Ok, that's what I hoped anyway. It just wasn't clear from your description. > When the object is restored, by using pyxser.unserialize: > > pyobj = pyxser.unserialize(obj = xmldocstr, enc = "utf-8") But this is XML, right? What do you need to pass the encoding for at this point? > Another issue is the fact that if you have mixed some encodings in byte > strings objects in your object tree, such as iso-8859-1 and utf-8, and > you try to serialize that object, pyxser will output to stdout the > serialization errors by trying to handle those mixed encodings which are > not regarding the document encoding. There shouldn't be any serialisation errors (unless you try to recode byte strings on the way out, which is a no-no for arbitrary user input). All you have to do is properly escape the byte string so that it passes the XML encoding step. One trick to do that is to decode the byte string as ISO-8859-1 and serialise the result as a normal Unicode string. Then you can re-encode the unicode string on input back to ISO-8859-1. I choose ISO-8859-1 here because it has the well-defined side-effect of mapping byte values directly to Unicode characters with an identical code point value. So you do not risk any failures or data loss. Stefan From mwilson at the-wire.com Mon Aug 24 09:05:24 2009 From: mwilson at the-wire.com (Mel) Date: Mon, 24 Aug 2009 09:05:24 -0400 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: James Harris wrote: > On 24 Aug, 02:19, Max Erickson wrote: [ ... ] >> >>> int('100', 3) >> 9 >> >>> int('100', 36) >> 1296 > > This is fine typed into the language directly but couldn't be entered > by the user or read-in from or written to a file. That's rather beside the point. Literals don't essentially come from files or user input. Essentially literals are a subset of expressions, just like function calls are, and they have to be evaluated by Python to yield a value. I'm not averse to 32'rst', but we already have Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> int ('rst', 32) 28573 Mel. > > James From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 24 09:07:58 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 24 Aug 2009 15:07:58 +0200 Subject: conditional for-statement In-Reply-To: References: Message-ID: <4a9290ad$0$406$426a34cc@news.free.fr> seb a ?crit : > Hi, > > i was wondering if there is a syntax alike: > > for i in range(10) if i > 5: > print i > > equivalent to > > for i in (for i in range(10) if i>5): > print i what about : for i in range(6, 10): print i More seriously: for i in range(10): if i > 5: print i From jjalocha at gmail.com Mon Aug 24 09:13:40 2009 From: jjalocha at gmail.com (Jerzy Jalocha N) Date: Mon, 24 Aug 2009 09:13:40 -0400 Subject: P3 weird sys.stdout.write() Message-ID: <9b72f9a90908240613i513597bbk83a30946ab0b04ae@mail.gmail.com> I've stumbled upon the following in Python 3: Python 3.0.1+ (r301:69556, Apr 15 2009, 15:59:22) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdout.write("") 0 >>> sys.stdout.write("something") something9 >>> write() is appending the length of the string to it's output. That's not how it worked in 2.6. What's the reason for this? Is this intended? I couldn't find a bug report for this. From deets at nospam.web.de Mon Aug 24 09:21:31 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Aug 2009 15:21:31 +0200 Subject: P3 weird sys.stdout.write() References: Message-ID: <7ffierF2ken49U1@mid.uni-berlin.de> Jerzy Jalocha N wrote: > I've stumbled upon the following in Python 3: > > Python 3.0.1+ (r301:69556, Apr 15 2009, 15:59:22) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import sys >>>> sys.stdout.write("") > 0 >>>> sys.stdout.write("something") > something9 >>>> > > write() is appending the length of the string to it's output. That's > not how it worked in 2.6. > > What's the reason for this? Is this intended? I couldn't find a bug > report for this. Write returns the number of bytes written. And because you don't capture that output into a variable, the interpreter puts it out as well. If you do >>> n = sys.stdout.write("") instead, you won't see the behavior. Diez From andre.roberge at gmail.com Mon Aug 24 09:22:36 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 24 Aug 2009 06:22:36 -0700 (PDT) Subject: P3 weird sys.stdout.write() References: Message-ID: <9ad77db9-08a7-474d-b6a3-588e82cd8b85@b15g2000yqd.googlegroups.com> On Aug 24, 10:13?am, Jerzy Jalocha N wrote: > I've stumbled upon the following in Python 3: > > Python 3.0.1+ (r301:69556, Apr 15 2009, 15:59:22) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > > >>> import sys > >>> sys.stdout.write("") > 0 > >>> sys.stdout.write("something") > something9 > > write() is appending the length of the string to it's output. Not quite right, see below. > That's > not how it worked in 2.6. > > What's the reason for this? Is this intended? I couldn't find a bug > report for this. I don't know what the reason for the change, but try the following: >>> out = sys.stdout.write("test\n") test >>> out 5 What you are seeing is the concatenation of the return value of the write() method with its output. Andr? From __peter__ at web.de Mon Aug 24 09:32:48 2009 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Aug 2009 15:32:48 +0200 Subject: Is Python what I need? References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: Jean-Michel Pichavant wrote: >> >From the distance it looks like these children need a good teacher >> >rather than a bad (or just starting) programmer. > Wow, that is rude. Let's keep this list friendly, won't we ? I may have been too blunt, and if my message has come across as an insult I apologize for that. Let me try again: If you are trying to teach children that are unwilling to use pen and paper putting them in front of a computer doesn't help you and them one bit. As a starting programmer you'll have to spend a lot of time in front of your computer that may be better spent with your students. Better? Peter From code at pizzashack.org Mon Aug 24 09:42:31 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 08:42:31 -0500 Subject: Annoying octal notation In-Reply-To: <02a0ce27$0$30337$c3e8da3@news.astraweb.com> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <02a0ce27$0$30337$c3e8da3@news.astraweb.com> Message-ID: <20090824134231.GZ20434@dragontoe.org> On Sun, Aug 23, 2009 at 06:13:31AM +0000, Steven D'Aprano wrote: > On Sat, 22 Aug 2009 22:19:01 -0500, Derek Martin wrote: > > On Sat, Aug 22, 2009 at 02:55:51AM +0000, Steven D'Aprano wrote: > >> And the great thing is that now you get to teach yourself to stop > >> writing octal numbers implicitly and be write them explicitly with a > >> leading 0o instead :) > > > > Sorry, I don't write them implicitly. A leading zero explicitly states > > that the numeric constant that follows is octal. > > That is incorrect. No, it simply isn't. It is a stated specification in most popular programming languages that an integer preceded by a leading zero is an octal number. That makes it explicit, when used by a programmer to write an octal literal. By definition. End of discussion. > (Explicitness isn't a binary state Of course it is. Something can be either stated or implied... there are no shades in between. Perhaps you mean "obvious and intutitive" where you are using the word "explicit" above (and that would be a matter of subjective opinion). The leading zero, however, is undoubtedly explicit. It is an explicitly written token which, in that context, has the meaning that the digits that follow are an octal number. One simply needs to be aware of that aspect of the specification of the programming language, and one will clearly know that it is octal. My point in mentioning that many other programming languages, by the way, was NOT to suggest that, "See, look here, all these other folks do it that way too, so it must be right." It was to refute the notion that the leading zero as octal was in some way unusual. It is, in fact, ubiquitous in computing, taught roughly in the first week of any beginning computing course using nearly any modern popular programming language, and discussed within the first full page of text in the section on numerical literals in _Learning Python_ (and undoubtedly many other books on Python). It may be a surprise the first time you run into it, but you typically won't forget that detail after you run into it the first time. > However, octal numbers are defined implicitly: 012 is a legal base 10 > number, or base 3, or base 9, or base 16. Not in any programming language I use today, it's not. In all of those, 012 is an octal integer literal, per the language spec. > There's nothing about a leading zero that says "base 8" apart from > familiarity. That is simply untrue. What says base 8 about a leading zero is the formal specification of the programming language. The only way using octal could be implicit in the code is if you wrote something like: x = 12 in your code, and then had to pass a flag to your compiler or interpreter to tell it that you meant to use octal integer literals instead of decimal ones. That, of course, would be insane. But specifying a leading zero to represent an octal number zero is very much explicit, by definition. > We can see the difference between leading 0x and leading 0 if you > repeat it: repeating an explicit 0x, as in 0x0xFF, is a syntax > error, while repeating an implicit 0 silently does nothing > different: No, we can't. Just as you can type 0012, you can also type 0x0FF. It's not different AT ALL. In both cases, the marker designated by the programming language as the base indicator can be followed by an arbitrary number of zeros which do not impact the magnitude of the integer so specified. Identical behavior. The key is simply to understand that the first 0 is not a digit -- it's a syntactic marker, an operator if you will (though Python may not technically think of it that way). The definition of '0' is overloaded, just as other language tokens often are. This, too, is hardly unusual. > There are a bunch of languages, pretty much all heavily influenced > by C, which treat integer literals with leading 0s as oct: C++, > Javascript, Python 2.x, Ruby, Perl, Java. As so often is the case, > C's design mistakes become common practice. Sigh. That it is a design mistake is a matter of opinion. Obviously the people who designed it didn't think it was a mistake, and neither do I. If you search the web for this topic (I did), you will find no shortage of people who think the recent movement to irradicate the leading zero to be frustrating, annoying, and/or stupid. And by the way, this representation predates C. It was at least present in B. > FORTRAN 90 uses a leading O (uppercase o) for octal That clearly IS a design mistake, because O is virtually indistinguishable from 0, especially considering varying fonts and people's variable eye sight quality. > Algol uses an explicit base: 8r12 to indicate octal 10. This is far better than 0o01. I maintain that 0o1 is only marginally better than O01 (from your fortran example) or 0O1, allowed by Python. The string 8r12 has the nicety that it can easily be used to represent integers of any radix in a consistent fashion. But I maintain that the leading zero is just fine, and changing it after 20 years of Python seems more than a little arbitrary and brain-damaged to me. > > Computer languages are not write-only, excepting maybe Perl. ;-) Writing > > 0o12 presents no hardship; but I assert, with at least some support from > > others here, that *reading* it does. > > No more so than 0x or 0b literals. If anything, 0o12 stands out as "not > twelve" far more than 012 does. Obviously, I don't agree. Moving on... I've wasted enough time arguing about this. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From jjalocha at gmail.com Mon Aug 24 09:44:47 2009 From: jjalocha at gmail.com (Jerzy Jalocha N) Date: Mon, 24 Aug 2009 09:44:47 -0400 Subject: P3 weird sys.stdout.write() In-Reply-To: <9b72f9a90908240613i513597bbk83a30946ab0b04ae@mail.gmail.com> References: <9b72f9a90908240613i513597bbk83a30946ab0b04ae@mail.gmail.com> Message-ID: <9b72f9a90908240644i77caaa0avb3c305925be86092@mail.gmail.com> >>> import sys >>> n = sys.stdout.write('something') something>>> n 9 >>> Yes, that works as expected, now, similar to 2.6. Thank you both, Diez and Andr?! -Jerzy From sturlamolden at yahoo.no Mon Aug 24 09:46:02 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 06:46:02 -0700 (PDT) Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> Message-ID: On 24 Aug, 10:24, n... at cam.ac.uk wrote: > In article <5134d9f1-0e23-4e05-a817-bf0cc9e85... at w6g2000yqw.googlegroups.com>, > > sturlamolden ? wrote: > >On 24 Aug, 02:26, nos... at see.signature (Richard Maine) wrote: > > >> You missed the word "OOP", which seemed like the whole point. Not that > >> the particular word is used in the Fortran standard, but it isn't hard > >> to guess that he means a derived type that uses some of the OOP > >> features. Inheritance, polymorphism, and type-bound procedure (aka > >> methods in some other languages) come to mind. > > >But C is not OOP. The ISO C bindings in Fortran are not ISO C++ > >bindings. This is for a reason: C++ does not have a standard ABI like > >ISO C. > > Nor does C. ?Almost everything that most people believe about C is > wrong, because C is not well-defined at any level, so there are > many twisty little C languages, all different. > > Richard is perfectly correct that my point was OOP. ?C interoperability > does not apply to any derived type with type-bound procedures, which > include finalizers. ?Note that this ALSO forbids them from being > passed as data, even if the other language never uses the OOP features > of the type. You also made this claim regarding Fortran's C interop with strings: "No, I mean things like 'Kilroy was here'. Currently, Fortran's C interoperability supports only strings of length 1, and you have to kludge them up as arrays. That doesn't work very well, especially for things like function results." This obviosuly proves you wrong: subroutine foobar(fstr) ! this is the Fortran function we want to call from C ! it takes a variable length string as argument and ! print its length character(*) :: fstr write (*,*) len(fstr) end subroutine subroutine wrap_foobar(cstr) bind(c, name='foobar') ! a wrapper for foobar which we expose to C use, intrinsic :: iso_c_binding interface function strlen(cstr) bind(c, name='strlen') use, intrinsic :: iso_c_binding integer(c_int) :: strlen type(c_ptr), value :: cstr end function strlen end interface type(c_ptr), value :: cstr character(2147483647), pointer :: p_fstr integer :: n n = strlen(cstr) call c_f_pointer(cstr, p_fstr) call foobar(p_fstr(1:n)) end subroutine I am not saying you are wrong regarding OOP derives types, but I'm not taking your word for it. However, I am not wasting my time on Fortran 2003 OOP now, as it lacks compiler support. So I'll leave your claim uncontested. By the way, I am more than happy using Python for OOP and Fortran 95 for speed. As for numerical computing, I'd rather see better support for array and matrix types in Cython than OOP in Fortran. Regards, Sturla Molden From paul.vandelst at noaa.gov Mon Aug 24 09:46:49 2009 From: paul.vandelst at noaa.gov (Paul van Delst) Date: Mon, 24 Aug 2009 09:46:49 -0400 Subject: Python/Fortran interoperability In-Reply-To: <800c6f66-7074-451f-8c1b-47c93d07c5a4@s13g2000yql.googlegroups.com> References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> <1j4wx7d.18cr6dvw3j79yN%nospam@see.signature> <800c6f66-7074-451f-8c1b-47c93d07c5a4@s13g2000yql.googlegroups.com> Message-ID: sturlamolden wrote: > On 24 Aug, 02:57, nos... at see.signature (Richard Maine) wrote: > > Does anyone use OOP in Fortran anyway? I do - currently for learning (and eventually training) purposes so I don't distribute any of the code. But, the fact that... > Fortran 2003 compilers are not ubiquitous. ...is a major sticking point towards a fully engaged f2003 programme (not program :o) > Fortran compilers tend to support a > subset for Fortran 2003, usually ISO C bindings but not OOP. Yeah, I'm starting to find it a little bit tiresome that vendors now appear convinced that implementing some of the more note-worthy features of f2008 is of greater importance that wrapping up the f2003 implementations. But, it's their business for their customers so c'est la vie I guess If I ignore parameterised derived types then my f2003 platform/compiler of "choice", IBM AIX xlf2003, works well for OOP stuff. cheers, paulv From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 24 09:55:16 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 24 Aug 2009 15:55:16 +0200 Subject: Object Reference question In-Reply-To: References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <8763chldpd.fsf@benfinney.id.au> Message-ID: <4a929bc3$0$22636$426a74cc@news.free.fr> josef a ?crit : (snip) > I think that something like a = MyClass0(name = > 'a', ...) is a bit redundant. Are definitions treated the same way? > How would one print or pass function names? In Python, classes and functions are objects too. The class and def statements are mostly syntactic sugar that *both* instanciate the (resp) class of function objet *and* bind it in the local namespace. FWIW, while class and function objects do (usually) have a __name__ attribute (usually the one used in the class or def statement...), this doesn't mean they're still bound to this name, nor that they are not bound to any other name: bruno at bruno:~$ python Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. pythonrc start pythonrc done >>> def foo(): print "function foo ???" ... >>> foo >>> foo.__name__ 'foo' >>> bar = foo >>> bar.__name__ 'foo' >>> bar() function foo ??? >>> import sys >>> foo = lambda: sys.stdout.write("pick a boo !\n") >>> foo.__name__ '' >>> foo() pick a boo ! >>> funcs = [foo, bar] >>> del foo >>> funcs[0] at 0x8563ed4> >>> funcs[0]() pick a boo ! >>> funcs[1] >>> funcs[1]() function foo ??? >>> funcs[1].__name__ 'foo' >>> del bar >>> funcs[1]() function foo ??? >>> funcs[1].__name__ = "yadda" >>> funcs[1]() function foo ??? >>> funcs[1].__name__ 'yadda' >>> HTH From code at pizzashack.org Mon Aug 24 09:56:48 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 08:56:48 -0500 Subject: Annoying octal notation In-Reply-To: <87fxbifzb7.fsf@golux.woodcraft.me.uk> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> Message-ID: <20090824135648.GA20434@dragontoe.org> On Sun, Aug 23, 2009 at 01:13:32PM +0000, Matthew Woodcraft wrote: > Dennis Lee Bieber writes: > > About the only place one commonly sees leading zeros on decimal > > numbers, in my experience, is zero-filled COBOL data decks (and since > > classic COBOL stores in BCD anyway... binary (usage is > > computational/comp-1) was a later add-on to the data specification model > > as I recall...) > > A more common case is dates. I suppose this is true, but I can't remember the last time I hard-coded a date in a program, or worked on someone else's code with hard-coded dates. I'm fairly certain I've never done it, and if I had, I obviously would not have used leading zeros. I think hard-coding dates is more uncommon than using octal. ;-) [It unquestionably is, for me personally.] I tend to also discount this example, because when we write dates with leading zeros, usually it's in some variation of the form 08/09/2009, which, containing slashes, is a string, not a number, and can not be used as a date literal in any language I know. We do it for reasons of format, which again implies that it has more the characteristics of a string than of a number. To use such a thing in any programming language I can think of would require translation from a string. > I've seen people trip over this writing things like > > xxx = [ > date(2009, 10, 12), > date(2009, 12, 26), > date(2010, 02, 09), > ] I've never seen anyone do this (no doubt because it would be an error), but as I said, I don't think I've ever seen hard-coded dates in any programs I've worked on. I've never encountered anyone having problems with octals who was not a total noob at programming. The changing of this syntax seems like much ado about nothing to me, and as such is annoying, consider that I use it very often. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From ryniek90 at gmail.com Mon Aug 24 10:04:07 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Mon, 24 Aug 2009 16:04:07 +0200 Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile Message-ID: <4A929DD7.4070507@gmail.com> >> John Machin wrote: >>> Erik Max Francis alcyone.com> writes: >> I also suspect the "pipe" symbol. I don't know if it's an invalid >> character to Windows, but it's certainly a bad idea. The '|' character >> means something special to the shell. > The "pipe" character is not a valid character in a Windows file. > Despite the OP's message wrapping the filename in "pipes", > there are no pipes in the filename in the traceback to > which he posted a link. Wrapping the filename in "pipes" > and the cryptic reference to "the '|\U' literal fault" > appear to be side-issue bogglements. > >>> open('boggle|txt', 'wb') > Traceback (most recent call last): > File "", line 1, in > IOError: [Errno 22] invalid mode ('wb') or filename: 'boggle|txt' > >>> open('|boggle.txt|', 'wb') > Traceback (most recent call last): > File "", line 1, in > IOError: [Errno 22] invalid mode ('wb') or filename: '|boggle.txt|' Sorry, but i don't know where those pipes came from : P The proper path is "C:\\Users\\Ryniek's WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2" and that string literal is "\U", without any pipes :) The truth is that script works on linux (ubuntu) but not on windows (neither Win7 nor WinXP). Maybe it's good idea to use raw string for specifing those paths? As i mentioned later, some python users had the same problem with this IOError ( like here: http://www.daniweb.com/forums/thread174552.html or here: http://groups.google.com/group/sympy/browse_thread/thread/c42aca3eb53... ). From code at pizzashack.org Mon Aug 24 10:14:25 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 09:14:25 -0500 Subject: Annoying octal notation In-Reply-To: <20090824135648.GA20434@dragontoe.org> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <20090824135648.GA20434@dragontoe.org> Message-ID: <20090824141425.GB20434@dragontoe.org> On Mon, Aug 24, 2009 at 08:56:48AM -0500, Derek Martin wrote: > On Sun, Aug 23, 2009 at 01:13:32PM +0000, Matthew Woodcraft wrote: > > A more common case is dates. > > I suppose this is true, but [...] > I tend to also discount this example, because when we write dates > with leading zeros, usually it's in some variation of the form > 08/09/2009, which, containing slashes, is a string, not a number In fact, now that I think of it... I just looked at some old school papers I had tucked away in a family album. I'm quite sure that in grammar school, I was tought to use a date format of 8/9/79, without leading zeros. I can't prove it, of course, but feel fairly sure that the prevalence of leading zeros in dates occured only in the mid to late 1980's as computers became more prevalent in our society (no doubt because thousands of cobol programmers writing business apps needed a way to convert dates as strings to numbers that was easy and fit in small memory). Assuming I'm right about that, then the use of a leading 0 to represent octal actually predates the prevalence of using 0 in dates by almost two decades. And while using leading zeros in other contexts is "familiar" to me, I would certainly not consider it "common" by any means. Thus I think it's fair to say that when this syntax was selected, it was a rather good choice. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From victorsubervi at gmail.com Mon Aug 24 10:17:04 2009 From: victorsubervi at gmail.com (Victor Subervi) Date: Mon, 24 Aug 2009 09:17:04 -0500 Subject: Trying To Catch Invalid User Input In-Reply-To: References: <4dc0cfea0908230804o29a328ecmdb99af2ef790f5ac@mail.gmail.com> Message-ID: <4dc0cfea0908240717y562d89dcqb84bef146fcd08f4@mail.gmail.com> That's nice. Thanks! V On Sun, Aug 23, 2009 at 5:02 PM, Dennis Lee Bieber wrote: > On Sun, 23 Aug 2009 10:04:57 -0500, Victor Subervi > declaimed the following in > gmane.comp.python.general: > > > Hi; > > I have the following: > > > > style = raw_input('What style is this? (1 = short, 2 = long): ') > > flag = 0 > > while flag == 0: > > if (style != 1) or (style != 2): > > style = raw_input('There was a mistake. What style is this? (1 = > short, > > 2 = long): ') > > else: > > flag = 1 > > > Ugh... Unless you are using an archaic version of Python, the > language has support for booleans... > > done = False > while not done: > ... > done = True > > > You fail to convert the character input from raw_input into an > integer for comparison... Oh, and you say the input is wrong if it is > NOT 1 OR NOT 2... 1 is not 2, and 2 is not 1, so... even if you did > convert to an integer, it would be rejected. > > Consider: > > -=-=-=-=-=-=-=- > while True: > charin = raw_input("What style is this? (1: short, 2: long): ") > try: > style = int(charin) > except: #I know, should not use naked except clause > print ("The input '%s' is not a valid integer value; try again" > % charin) > else: > if style in (1, 2): break > print ("The input value '%s' is not in the valid range; try > again" > % style) > -=-=-=-=-=-=-=- > {Watch out for line wraps} > Works in Python 2.5 > > E:\UserData\Dennis Lee Bieber\My Documents>python Script1.py > What style is this? (1: short, 2: long): ab1 > The input 'ab1' is not a valid integer value; try again > What style is this? (1: short, 2: long): 1a > The input '1a' is not a valid integer value; try again > What style is this? (1: short, 2: long): 12 > The input value '12' is not in the valid range; try again > What style is this? (1: short, 2: long): 2 > > E:\UserData\Dennis Lee Bieber\My Documents> > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com HTTP://wlfraed.home.netcom.com/ > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Mon Aug 24 10:20:32 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 07:20:32 -0700 (PDT) Subject: basic thread question References: Message-ID: <4ddd2bd2-de39-487f-95ad-64c670a9b710@t13g2000yqt.googlegroups.com> On 18 Aug, 22:10, Derek Martin wrote: > I have some simple threaded code... ?If I run this > with an arg of 1 (start one thread), it pegs one cpu, as I would > expect. ?If I run it with an arg of 2 (start 2 threads), it uses both > CPUs, but utilization of both is less than 50%. ?Can anyone explain > why? ? Access to the Python interpreter is serialized by the global interpreter lock (GIL). You created two threads the OS could schedule, but they competed for access to the Python interpreter. If you want to utilize more than one CPU, you have to release the GIL or use multiple processes instead (os.fork since you are using Linux). This is how the GIL can be released: * Many functions in Python's standard library, particularly all blocking i/o functions, release the GIL. This covers the by far most common use of threads. * In C or C++ extensions, use the macros Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS. * With ctypes, functions called from a cdll release the GIL, whereas functions called from a pydll do not. * In f2py, declaring a Fortran function threadsafe in a .pyf file or cf2py comment releases the GIL. * In Cython or Pyrex extensions, use a "with nogil:" block to execute code without holding the GIL. Sturla Molden From sturlamolden at yahoo.no Mon Aug 24 10:31:57 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 07:31:57 -0700 (PDT) Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> Message-ID: <4224e772-5b67-4eea-9bdf-a7d2bf7cc128@c14g2000yqm.googlegroups.com> On 24 Aug, 13:21, Piet van Oostrum wrote: > But os.fork() is not available on Windows. And I guess refcounts et al. > will soon destroy the sharing. Well, there is os.fork in Cygwin and SUA (SUA is the Unix subsytem in Windows Vista Professional). Cygwin's fork is a bit sluggish. Multiprocessing works on Windows and Linux alike. Apart from that, how are you going to use threads? The GIL will not be a problem if it can be released. Mostly, the GIL is a hypothetical problem. It is only a problem for compute-bound code written in pure Python. But very few use Python for that. However, if you do and can afford the 200x speed penalty from using Python (instead of C, C++, Fortran, Cython), you can just as well accept that only one CPU is used. Sturla Molden From drobinow at gmail.com Mon Aug 24 10:33:45 2009 From: drobinow at gmail.com (David Robinow) Date: Mon, 24 Aug 2009 10:33:45 -0400 Subject: Is Python what I need? In-Reply-To: References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: <4eb0089f0908240733h17f02cbte4154bf552404509@mail.gmail.com> On Mon, Aug 24, 2009 at 9:32 AM, Peter Otten<__peter__ at web.de> wrote: > If you are trying to teach children that are unwilling to use pen and paper > putting them in front of a computer doesn't help you and them one bit. As a > starting programmer you'll have to spend a lot of time in front of your > computer that may be better spent with your students. I don't think you were rude at all, but I like your second answer even more than the first. Nevertheless, I'd still like to hear from the Original Poster. What are you trying to accomplish? What software have you found that is too expensive? Given more information, somebody might be able to help. From ronn.ross at gmail.com Mon Aug 24 10:35:09 2009 From: ronn.ross at gmail.com (Ronn Ross) Date: Mon, 24 Aug 2009 10:35:09 -0400 Subject: Reading binary files Message-ID: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> I need to read a binary file. When I open it up in a text editor it is just junk. Does Python have a class to help with this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From garabik-news-2005-05 at kassiopeia.juls.savba.sk Mon Aug 24 10:35:56 2009 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Mon, 24 Aug 2009 14:35:56 +0000 (UTC) Subject: Numeric literals in other than base 10 - was Annoying octal?notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> Message-ID: J. Cliff Dyer wrote: > I had an objection to using spaces in numeric literals last time around > and it still stands, and it still stands in the new one. > Or, we can use U+00A0 NO-BREAK SPACE, once we already have unicode variable names :-) (probably some people would find it difficult to type, though with my keyboard layout it is COMPOSE + SPACE + SPACE, not more difficult than _). Well, reading code listings could be a bit confusing. Thinking about it, U+2005 FOUR-PER-EM SPACE makes more sense. Aesthetically, too :-) -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From davea at dejaviewphoto.com Mon Aug 24 10:36:42 2009 From: davea at dejaviewphoto.com (Dave Angel) Date: Mon, 24 Aug 2009 10:36:42 -0400 Subject: Temat:,Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: <4A928B4B.9030502@gmail.com> References: <4A928B4B.9030502@gmail.com> Message-ID: <4A92A57A.5010105@dejaviewphoto.com> Ryniek90 wrote: >
>>> John Machin wrote: >>> >>>> Erik Max Francis alcyone.com> writes: >>>> >> >>> I also suspect the "pipe" symbol. I don't know if it's an invalid >>> character to Windows, but it's certainly a bad idea. The '|' >>> character means something special to the shell. >>> >> >> The "pipe" character is not a valid character in a Windows file. >> Despite the OP's message wrapping the filename in "pipes", >> there are no pipes in the filename in the traceback to >> which he posted a link. Wrapping the filename in "pipes" >> and the cryptic reference to "the '|\U' literal fault" >> appear to be side-issue bogglements. >> >> >>> open('boggle|txt', 'wb') >> Traceback (most recent call last): >> File "", line 1, in >> IOError: [Errno 22] invalid mode ('wb') or filename: 'boggle|txt' >> >>> open('|boggle.txt|', 'wb') >> Traceback (most recent call last): >> File "", line 1, in >> IOError: [Errno 22] invalid mode ('wb') or filename: '|boggle.txt|' >> >> >> >> > > Sorry, but i don't know where those pipes came from : P > > The proper path is "C:\\Users\\Ryniek's > WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2" > and that string literal is "\U", without any pipes :) > > The truth is that script works on linux (ubuntu) but not on windows > (neither Win7 nor WinXP). > Maybe it's good idea to use raw string for specifing those paths? > > As i mentioned later, some python users had the same problem with this > IOError ( like here: http://www.daniweb.com/forums/thread174552.html > or here: > http://groups.google.com/group/sympy/browse_thread/thread/c42aca3eb532928c > ). > > > >
> You still haven't gotten rid of those illegal colons in the filename. They're not legal in Windows, as has been pointed out a couple of times in this thread. DaveA From aotto1968 at users.sourceforge.net Mon Aug 24 10:40:21 2009 From: aotto1968 at users.sourceforge.net (Andreas Otto) Date: Mon, 24 Aug 2009 16:40:21 +0200 Subject: problem to write a THREAD enabled python extension Message-ID: Hi, the following scenario: 1. using GIL 2. a pthread is created in a library and have to be "announced" to python 3. the thread is created in a "PyObject_CallObject" function call from extension c code using a other extension c-code function called from python code python CRASH with invalid thread-state object http://www.linuxjournal.com/article/3641 has information that GIL is NOT able to keep thread state information for cross thread operation. workaround -> ...... PyGILState_STATE gilState = PyGILState_Ensure(); // PyEval_RestoreThread // Call Python/C API... PyGILState_Release(gilState); // PyEval_SaveThread ...... // Create new thread... ...... PyGILState_STATE gilState = PyGILState_Ensure(); // PyEval_RestoreThread // Call Python/C API... PyGILState_Release(gilState); // PyEval_SaveThread ...... the problem is that PyGILState_Release have to be done in the call of "PyObject_CallObject" and not in the extension c-code -> for now i call it impossible to provide thread support if thread is created in extension code -> more info by valgrind ==29105== ==29105== Invalid read of size 4 ==29105== at 0x4F099AB: PyEval_EvalFrameEx (ceval.c:3728) ==29105== by 0x4F0B476: PyEval_EvalCodeEx (ceval.c:3180) ==29105== by 0x4E9DE50: function_call (funcobject.c:630) ==29105== by 0x4E7610C: PyObject_Call (abstract.c:2160) ==29105== by 0x4E8BEFB: method_call (classobject.c:323) ==29105== by 0x4E7610C: PyObject_Call (abstract.c:2160) ==29105== by 0x4F04975: PyEval_CallObjectWithKeywords (ceval.c:3624) ==29105== by 0x72132DF: pymsgque_ProcCall (misc_python.c:48) ==29105== by 0x742A23E: pTokenInvoke (token.c:327) ==29105== by 0x742E7E2: sMqEventStart (msgque.c:908) ==29105== by 0x7425365: pEventStart (event.c:360) ==29105== by 0x742ECBF: MqProcessEvent (msgque.c:1081) ==29105== by 0x7215F24: pymsgque_ProcessEvent (context_python.c:176) ==29105== by 0x4F09BFA: PyEval_EvalFrameEx (ceval.c:3961) ==29105== by 0x4F0B476: PyEval_EvalCodeEx (ceval.c:3180) ==29105== by 0x4F0B58A: PyEval_EvalCode (ceval.c:650) ==29105== by 0x4F2EE29: PyRun_FileExFlags (pythonrun.c:1697) ==29105== by 0x4F2F134: PyRun_SimpleFileExFlags (pythonrun.c:1182) ==29105== by 0x4F43CFB: Py_Main (main.c:625) ==29105== by 0x400D11: main (python.c:152) ==29105== Address 0x24 is not stack'd, malloc'd or (recently) free'd -> extension code ... (including some debugging output) M0 PyGILState_STATE gstate = PyGILState_Ensure(); PyObject *result; PyObject * const self = (PyObject*) CONTEXT->self; PyObject * const callable = (PyObject*) dataP; enum MqErrorE ret = MQ_OK; // clean Python and libmsgque error PyErr_Clear(); MqErrorReset(msgque->error); // call the function M1 printP(PyThreadState_Get()) if (PyMethod_Check(callable) && PyMethod_Self(callable) == self) { //PyGILState_Release(gstate); result = PyObject_CallObject(callable, NULL); //gstate = PyGILState_Ensure(); } else { //PyGILState_Release(gstate); result = PyObject_CallFunctionObjArgs(callable, self, NULL); //gstate = PyGILState_Ensure(); } M2 printP(PyThreadState_Get()) Py_XDECREF(result); // no error return OK if (PyErr_Occurred() != NULL) { NS(ErrorSet) (self); ret = MqErrorGetCode(msgque->error); } PyGILState_Release(gstate); return ret; } with GIL wrapper 'PyGILState_Release' and 'PyGILState_Ensure' enabled for 'PyObject_CallObject' the following SEG happen if (PyMethod_Check(callable) && PyMethod_Self(callable) == self) { PyGILState_Release(gstate); result = PyObject_CallObject(callable, NULL); gstate = PyGILState_Ensure(); } else { PyGILState_Release(gstate); result = PyObject_CallFunctionObjArgs(callable, self, NULL); gstate = PyGILState_Ensure(); } pymsgque_ProcCall(misc_python.c:32) -> 00000000000000000 pymsgque_ProcCall(misc_python.c:44) -> 11111111111111111 pymsgque_ProcCall(misc_python.c:45) -> PyThreadState_Get()<0x68c2ad8> ==29223== ==29223== Thread 2: ==29223== Invalid read of size 4 ==29223== at 0x4E760EA: PyObject_Call (abstract.c:2158) ==29223== by 0x4F04975: PyEval_CallObjectWithKeywords (ceval.c:3624) ==29223== by 0x72132F7: pymsgque_ProcCall (misc_python.c:48) ==29223== by 0x7430092: MqLinkCreate (msgque.c:644) ==29223== by 0x7430AB0: MqDefaultLinkCreate (msgque.c:681) ==29223== by 0x742F73B: MqLinkCreate (msgque.c:346) ==29223== by 0x7432C3D: sSysServerThreadCreate (sys.c:502) ==29223== by 0x521606F: start_thread (in /lib64/libpthread-2.9.so) ==29223== by 0x5B5B10C: clone (in /lib64/libc-2.9.so) ==29223== Address 0x18 is not stack'd, malloc'd or (recently) free'd ==29223== ==29223== Process terminating with default action of signal 11 (SIGSEGV) mfg aotto1968 From rami.chowdhury at gmail.com Mon Aug 24 10:41:09 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Mon, 24 Aug 2009 07:41:09 -0700 Subject: Reading binary files In-Reply-To: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> References: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> Message-ID: The built-in file type deals with this just fine. You can simply specify when opening the file that it is to be opened as binary: http://docs.python.org/library/functions.html#open On Mon, 24 Aug 2009 07:35:09 -0700, Ronn Ross wrote: > I need to read a binary file. When I open it up in a text editor it is > just > junk. Does Python have a class to help with this? -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From marduk at letterboxes.org Mon Aug 24 10:43:59 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Mon, 24 Aug 2009 10:43:59 -0400 Subject: Reading binary files In-Reply-To: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> References: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> Message-ID: <1251125039.23757.0.camel@brotherus.corp.redhat.com> On Mon, 2009-08-24 at 10:35 -0400, Ronn Ross wrote: > I need to read a binary file. When I open it up in a text editor it is > just junk. Does Python have a class to help with this? Yes, the "file" class. >>> myfile = open('/path/to/binary/file', 'rb') -a From sturlamolden at yahoo.no Mon Aug 24 10:45:44 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 07:45:44 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: On 24 Aug, 14:08, Gilles Ganault wrote: > I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. There is pywin32 if you like to work with MFC and ActiveX. Apart from that, lack of controls is not what I associate with GTK, Qt or wxWidgets. > I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. Why do you want GUI controls for this? If you think you do, Visual Basic has crippled your mind. Python has packages for database connectivity. There is ReportLab for reports, matplotlib for graphs, pyagg or pycairo for whatever you want to draw, etc. You can find Python packages for anything you can imagine. Sturla From mail at timgolden.me.uk Mon Aug 24 10:46:46 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 24 Aug 2009 15:46:46 +0100 Subject: Temat:,Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: <4A92A57A.5010105@dejaviewphoto.com> References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> Message-ID: <4A92A7D6.4050903@timgolden.me.uk> Dave Angel wrote: > You still haven't gotten rid of those illegal colons in the filename. > They're not legal in Windows, as has been pointed out a couple of times > in this thread. Ummm.. Colons are of course legal in Windows filenames as designating the Alternate Data Streams: with open ("c:/temp/test.txt", "w") as f: f.write ("base text") with open ("c:/temp/test.txt:blah", "w") as f: f.write ("ADS text") print open ("c:/temp/test.txt:blah").read () On the other hand, though, you can't have more than one of them: with open ("c:/temp/test.txt:blah:blah2", "w") as f: f.write ("ADS text2") should raise an error. TJG From kwmsmith at gmail.com Mon Aug 24 10:49:56 2009 From: kwmsmith at gmail.com (Kurt Smith) Date: Mon, 24 Aug 2009 09:49:56 -0500 Subject: Python/Fortran interoperability In-Reply-To: <4a915067$0$31339$9b4e6d93@newsspool4.arcor-online.net> References: <4a915067$0$31339$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On Sun, Aug 23, 2009 at 9:21 AM, Stefan Behnel wrote: > nmm1 at cam.ac.uk wrote: >> I am interested in surveying people who want to interoperate between >> Fortran and Python to find out what they would like to be able to do >> more conveniently, especially with regard to types not supported for C >> interoperability by the current Fortran standard. ?Any suggestions as to >> other ways that I could survey such people (Usenet is no longer as >> ubiquitous as it used to be) would be welcomed. > > You might want to ask also on the Cython, NumPy and SciPy mailing lists. > NumPy and SciPy have a rather large audience of scientific developers, and > Cython has a running sub-project on providing better Fortran integration > (which might be of interest to you anyway). Thanks for the mention, Stefan. For those who are interested, here's my blog summarizing the status of 'fwrap,' a Fortran wrapper utility for the C, Cython & Python languages. http://fortrancython.wordpress.com/ Linked there are my talk slides & presentation at last week's SciPy 2009 conference, which gives a good overview. Kurt From davea at ieee.org Mon Aug 24 10:52:16 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 24 Aug 2009 10:52:16 -0400 Subject: P3 weird sys.stdout.write() In-Reply-To: <9b72f9a90908240613i513597bbk83a30946ab0b04ae@mail.gmail.com> References: <9b72f9a90908240613i513597bbk83a30946ab0b04ae@mail.gmail.com> Message-ID: <4A92A920.70703@ieee.org> Jerzy Jalocha N wrote: > I've stumbled upon the following in Python 3: > > Python 3.0.1+ (r301:69556, Apr 15 2009, 15:59:22) > [GCC 4.3.3] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>> import sys >>>> sys.stdout.write("") >>>> > 0 > >>>> sys.stdout.write("something") >>>> > something9 > > > write() is appending the length of the string to it's output. That's > not how it worked in 2.6. > > What's the reason for this? Is this intended? I couldn't find a bug > report for this. > > (You probably should be using 3.1, but that's not your particular problem here.) The write() function changed in 3.0, but not in the way you're describing. It now (usually) has a return value, the count of the number of characters written. See the 3.1 docs: file.write(/str/) Write a string to the file. Due to buffering, the string may not actually show up in the file until the flush() or close() method is called. The meaning of the return value is not defined for every file-like object. Some (mostly low-level) file-like objects may return the number of bytes actually written, others return None. But because you're running from the interpreter, you're seeing the return value(9), which is suppressed if it's None, which it was in 2.x. This has nothing to do with how the language behaves in normal use. DaveA From sjmachin at lexicon.net Mon Aug 24 10:56:24 2009 From: sjmachin at lexicon.net (John Machin) Date: Mon, 24 Aug 2009 07:56:24 -0700 (PDT) Subject: Temat:, Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> Message-ID: <4ec18c68-b8b5-401e-b910-802b7662dced@i18g2000pro.googlegroups.com> On Aug 25, 12:46?am, Tim Golden wrote: > Dave Angel wrote: > > You still haven't gotten rid of those illegal colons in the filename. ? > > They're not legal in Windows, as has been pointed out a couple of times > > in this thread. > > Ummm.. Colons are of course legal in Windows filenames as designating That is the most inappropriate "of course" I've seen for quite a while. > the Alternate Data Streams: OK, so s/illegal/evil/ From apt.shansen at gmail.com Mon Aug 24 11:03:56 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Mon, 24 Aug 2009 08:03:56 -0700 Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: <4A929DD7.4070507@gmail.com> References: <4A929DD7.4070507@gmail.com> Message-ID: <7a9c25c20908240803v53cabd08la78e08163fae1aa7@mail.gmail.com> > > The proper path is "C:\\Users\\Ryniek's > WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2" > and that string literal is "\U", without any pipes :) > > The truth is that script works on linux (ubuntu) but not on windows > (neither Win7 nor WinXP). > Maybe it's good idea to use raw string for specifing those paths? > Colons are not valid in filenames on Windows. You won't get that filename to work. The error may be somewhat cryptic. Depending on the version of Windows and the particulars of your filesystem, *attempting* to read/write a filename with a colon may lead to very surprising results-- 0 sized files with names up to the colon... as you may actually be writing to an alternate named data stream (like a resource fork on the mac). Basically, the error is just cryptic. The problem is your filename isn't a valid windows filename :) --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From gtaylor at l11solutions.com Mon Aug 24 11:04:34 2009 From: gtaylor at l11solutions.com (Greg Taylor) Date: Mon, 24 Aug 2009 08:04:34 -0700 (PDT) Subject: Fedex + SOAP Message-ID: <55f5539e-2cb7-4e51-b897-da42e673ff57@r42g2000yqj.googlegroups.com> Fedex has recently started the process to transition from their XML- based Web Services to the new SOAP-based equivalent. I've been trying unsuccessfully to get an example SOAP transaction working with their new service, but am running into validation problems. I was wondering if anyone has already started tinkering with a Fedex +SOAP module before I potentially re-invent the wheel. If there's nothing in the works yet, would anyone be interested in working with me on such a module? Thanks, Greg From sturlamolden at yahoo.no Mon Aug 24 11:08:07 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 08:08:07 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: On 24 Aug, 14:08, Gilles Ganault wrote: > and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. Remote update is a problem regardless of language. It typically involves the following steps: 1. Download the update from a server using a background thread. 2. When the program starts, look for downloaded updates. Install updates, then launch the Python app. The problem is that a program's DLLs etc. become write-protected when the program runs. So you nees two programs that cooperate to install updates. But regardless of language you will run into this problem - it is not Python specific. With py2exe, you can solve this using two executables. The first py2exe launch a script that installs updates, then spawns the second py2exe executable. The second py2exe lauch a script that installs updates in the first, then launch the Python app. The Python app then run a background thread that downloads new updates. Sturla Molden From ebonak at hotmail.com Mon Aug 24 11:17:37 2009 From: ebonak at hotmail.com (Esmail) Date: Mon, 24 Aug 2009 11:17:37 -0400 Subject: your favorite debugging tool? In-Reply-To: References: Message-ID: Hello, thank you all for your suggestions/comments. While I do believe in a minimalist approach (part of the reason I find Python so appealing), using print statements sometimes only goes so far (for me). I probably should look into using iPython in the context of debugging (I already use this shell). For now I ended up giving winpdb a whirl and it did help me find the bug that had been elusive to my print statement approach :-) Thanks again .. and if there are additional postings, I'll be reading them too with great interest. Esmail From stefan_ml at behnel.de Mon Aug 24 11:18:40 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 17:18:40 +0200 Subject: problem to write a THREAD enabled python extension In-Reply-To: References: Message-ID: <4a92af50$0$32675$9b4e6d93@newsspool2.arcor-online.net> Andreas Otto wrote: > Hi, > > the following scenario: > > 1. using GIL > 2. a pthread is created in a library and have to be "announced" to python > 3. the thread is created in a "PyObject_CallObject" function call from > extension c code using a other extension c-code function called > from python code > > python CRASH with invalid thread-state object You forgot to create a thread state for the new thread. See the PyThreadState_New() function. Stefan From hendrik at microcorp.co.za Mon Aug 24 11:22:39 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 24 Aug 2009 17:22:39 +0200 Subject: Annoying octal notation In-Reply-To: <20090824141425.GB20434@dragontoe.org> References: <20090824135648.GA20434@dragontoe.org> <20090824141425.GB20434@dragontoe.org> Message-ID: <200908241722.39942.hendrik@microcorp.co.za> On Monday 24 August 2009 16:14:25 Derek Martin wrote: > In fact, now that I think of it... > > I just looked at some old school papers I had tucked away in a family > album. I'm quite sure that in grammar school, I was tought to use a > date format of 8/9/79, without leading zeros. I can't prove it, of > course, but feel fairly sure that the prevalence of leading zeros in > dates occured only in the mid to late 1980's as computers became more > prevalent in our society (no doubt because thousands of cobol I was one of those COBOL programmers, and the time was around the end of the sixties, running into the seventies. And the reason for leading zeroes on dates was the punched card, and its handmaiden, the data entry form, with a nice little block for every character. > programmers writing business apps needed a way to convert dates as > strings to numbers that was easy and fit in small memory). > > Assuming I'm right about that, then the use of a leading 0 to > represent octal actually predates the prevalence of using 0 in dates > by almost two decades. Not quite - at the time I started, punch cards and data entry forms were already well established practice, and at least on the English machines, (ICL 1500/1900 series) octal was prevalent, but I don't know when the leading zero octal notation started, and where. I only met it much later in life, and learned it through hard won irritation, because it is a stupid convention, when viewed dispassionately. > And while using leading zeros in other > contexts is "familiar" to me, I would certainly not consider it > "common" by any means. Thus I think it's fair to say that when this > syntax was selected, it was a rather good choice. I think you give it credence for far more depth of design thinking than what actually happened in those days - some team working on a compiler made a decision (based on gut feel or experience, or precedent, or whim ) and that was that - lo! - a standard is born! -- We have always done it this way, here at company x. And besides, we cannot ask our main guru to spend any of his precious time mucking around with trivia - the man may leave us for the opposition if we irritate him, and systems people do not grow on trees, you know. - Hendrik From jjalocha at gmail.com Mon Aug 24 11:25:15 2009 From: jjalocha at gmail.com (Jerzy Jalocha N) Date: Mon, 24 Aug 2009 11:25:15 -0400 Subject: P3 weird sys.stdout.write() In-Reply-To: <4A92A920.70703@ieee.org> References: <9b72f9a90908240613i513597bbk83a30946ab0b04ae@mail.gmail.com> <4A92A920.70703@ieee.org> Message-ID: <9b72f9a90908240825m5d04cdb9m74f28e9eac1ab02f@mail.gmail.com> On Mon, Aug 24, 2009 at 10:52 AM, Dave Angel wrote: > The write() function changed in 3.0, but not in the way you're describing. > ?It now (usually) has a return value, the count of the number of characters > written. [...] > But because you're running from the interpreter, you're seeing the return > value(9), which is suppressed if it's None, which it was in 2.x. ? This has > nothing to do with how the language behaves in normal use. This makes it much clearer! You are right, output in a shell script is "normal", without the return value. Thank you, Dave. -Jerzy From bbxx789_05ss at yahoo.com Mon Aug 24 11:29:39 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 24 Aug 2009 08:29:39 -0700 (PDT) Subject: print() and unicode strings (python 3.1) Message-ID: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> ======python 2.6 ====== import sys print sys.getdefaultencoding() s = u"\u20ac" print s.encode("utf-8") $ python2.6 1test.py ascii ? =====python 3.1 ======= import sys print(sys.getdefaultencoding()) s = "?" print(s.encode("utf-8")) print(s) $ python3.1 1test.py utf-8 b'\xe2\x82\xac' Traceback (most recent call last): File "1test.py", line 7, in print(s) UnicodeEncodeError: 'ascii' codec can't encode character '\u20ac' in position 0: ordinal not in range(12 I don't understand why I'm getting an encode error in python 3.1. From pavlovevidence at gmail.com Mon Aug 24 11:31:13 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 24 Aug 2009 08:31:13 -0700 (PDT) Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> Message-ID: <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> On Aug 24, 6:56?am, Derek Martin wrote: >?I think > hard-coding dates is more uncommon than using octal. ;-) ?[It > unquestionably is, for me personally.] You just don't get it, do you? Do you really think this is a contest over what's more common and the winner gets to choose the syntax? You really think that's the issue? It is not. The issue is that C's arcane octal notation is MIND- BOGGLINGLY RETARDED. So, even if Unix file permissions were a hundred times more common than padding integer constants with zero, it still wouldn't be a good idea to have it in Python because the notation is retarded. Even if 99.999% of other languages use the notation, it still wouldn't be a good idea to have it in Python because the notation is retarded. The vast majority of people reading this will understand intuitively why the arcane octal notation is retarded. I was going to explain it, but I decided it's not worth a serious argument. Carl Banks From find.mig at paa.google Mon Aug 24 11:32:23 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Mon, 24 Aug 2009 17:32:23 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: References: <4a91db65$0$305$14726298@news.sunsite.dk> Message-ID: <4a92b290$0$305$14726298@news.sunsite.dk> Hendrik van Rooyen wrote: > see if there is an "after" method somewhere. > > What you have to do is to "break the link" between the callback > and the processing. Your code above is all in the callback "thread", despite > the fact that you call another function to do the processing. > > So if you replace the data_callback() with an after call, it should work as > you expect. > > HTH - Hendrik > Thanks I'm new to python, what is an after function and an after call? Couldn't find excact answer on google...? Do you have a link to some docs? From steve at REMOVE-THIS-cybersource.com.au Mon Aug 24 11:36:24 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2009 15:36:24 GMT Subject: Literal concatenation, strings vs. numbers (was: Numeric literals in other than base 10 - was Annoying octal notation) References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> <7fe9mbF2l83bmU1@mid.individual.net> <871vn2gcai.fsf_-_@benfinney.id.au> Message-ID: <02a2a388$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 12:45:25 +1000, Ben Finney wrote: > greg writes: > >> J. Cliff Dyer wrote: >> >> > What happens if you use a literal like 0x10f 304? >> >> To me the obvious thing to do is concatenate them textually and then >> treat the whole thing as a single numeric literal. Anything else >> wouldn't be sane, IMO. Agreed. It's the only sane way to deal with concatenating numeric literals. It makes it simple and easy to understand: remove the whitespace from inside the literal, and parse as normal. 123 4567 => 1234567 # legal 0xff 123 => 0xff123 # legal 123 0xff => 1230xff # illegal The first two examples would be legal, the last would raise a syntax error, for obvious reasons. This would also work for floats: 1.23 4e5 => 1.234e5 # legal 1.23 4.5 => 1.234.5 # illegal 1e23 4e5 => 1e234e5 # illegal > Yet, as was pointed out, that behaviour would be inconsistent with the > concatenation of string literals:: > > >>> "abc" r'def' u"ghi" 'jkl' > u'abcdefghijkl' Unicode/byte conversion is obviously a special case, and arguably should have been prohibited, although "practicality beats purity" suggests that a single unicode string in the sequence should make the lot unicode. (What else could it mean?) In any case, numeric concatenation and string concatenation are very different beasts. With strings, you have to interpret each piece as either bytes or characters, you have to treat escapes specially, you have to deal with matching delimiters. For numeric concatenation, none of those complications is relevant: there is no equivalent to the byte/ character dichotomy, there are no escape sequences, there are no delimiters. Numeric literals are much simpler than string literals, consequently the concatenation rule can be correspondingly simpler too. There's no need to complicate it by *adding* complexity: you can't have mixed bases in a single numeric literal without spaces, why would you expect to have mixed bases in one with spaces? -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Aug 24 11:40:24 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2009 15:40:24 GMT Subject: Need cleanup advice for multiline string References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <4a918fe0$0$30226$9b4e6d93@newsspool1.arcor-online.net> <02a1cc1d$0$30337$c3e8da3@news.astraweb.com> <4a9243d3$0$32677$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <02a2a478$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 09:40:03 +0200, Stefan Behnel wrote: >> Or you could enter the 21 century and understand that "guys" has become >> a generic term for people of any sex. > > Is that true for everyone who understands and/or writes English? In that > case, I'm fine with your above statement. Otherwise, I'd wonder who you > meant with the term "cultural chauvinism". So far, I only learned that > most North-American English native speakers use that term in the way you > refer to. That doesn't even get you close to the majority of English > speakers. If you read the entire thread, you'd see that we've already discussed the issue of "guys" for mixed sex groups and females. In fact, as I'd already said, I'm one of those old fashioned guys who still gets surprised when women refer to themselves as guys, but I'm learning to keep up with the times. I'm Australian, not North American, and the British author Michael Quinion, one of the researchers for the Oxford Dictionary, also states that "guys" now refers to both men and women: http://www.worldwidewords.org/weirdwords/ww-guy1.htm When "guys" can refer to either sex in English, American, Canadian and Australian English, I think it should be pretty uncontroversial to treat it as standard now. -- Steven From apt.shansen at gmail.com Mon Aug 24 11:49:36 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Mon, 24 Aug 2009 08:49:36 -0700 Subject: Python for professsional Windows GUI apps? In-Reply-To: References: Message-ID: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> > > I was wondering if some people in this ng use Python and some GUI > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > applications, and if yes, what it's like, the pros and cons, etc. My company does. A few years ago we decided to re-write our entire aging product line in Python using wxPython as the GUI layer (PyWin32 was out because we wanted Mac compatibility, and at that time between QT's commercial license and my own familiarity with wx meant we just used that by default.) It took some time to get solid; there's a learning curve involved in doing things "the pythonic way", and wxPython is -- not really pythonic(and no powerful GUI library is, though there are some simpler libraries out there which are), so you're learning in two directions at once. It's been a pretty interesting experience, and I'd consider it a complete success, honestly. It took some time to get the full suite going from "functional" to "mature", mostly because of certain complexities to our system which have nothing to do with Python. But, Python and wxPython as the foundation for the system has allowed some pretty remarkable flexibility in getting something usable to the customer quickly, getting early feedback and rapidly responding to their needs and growing the application as we did so. It's been a very iterative process, but I don't know if you want to create a long-term project or get something out that works Just Fine, Right Now. For us we started out with a basic re-implementation of the legacy system which just 'worked', and have over the last few years probably rewritten most of the original code at least twice (a piece at a time)-- re-factoring and redesigning both the insides and UI as new controls and technologies (and our own knowledge!) improve over time. For us that's good, because we like maintenance contracts :) But we've had a continually evolving product line-- getting faster with every new release, slicker, with new features and evolving continually. Sure, every program /should/ do that -- but using Python+wxPython IMHO has been invaluable to the process of evolving /efficiently/. It takes very little effort to /maintain/ the system, very little effort going back to some deep dark place in the codebase and figuring out what the heck was done by someone else three years ago... and very little effort to pull the whole thing apart and piece it back together with a new heart when it's discovered the original didn't quite do things as well as it should. I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), I find this comment -- frankly bizarre. There's a plethora if controls in wxWidgets, and it's not terribly hard once you learn the system how to make your own. Check out Andrea Gavana's excellent suite of custom widgets (which continually get migrated into the core wxPython) and the AUI, and the sublime ObjectListView for Python. Now, if you're talking about "lack of the latest Microsoft-specialized controls", that's true. wxWidgets is cross-platform so doesn't readily adopt the latest and newest way that Microsoft does things with each new iteration of Office and Windows pumping out a new UI paradigm. But you can still create very native and impressively functional looking apps. With wxWidgets at least (I have no idea about QT), you also don't have a series of data-aware controls that you may be used to, but it's *really* not that hard to write that layer yourself. You may also want to look into Dabo, which builds on top of wxPython and I believe solves some of its limitations with regards to data-integration if you do things in a way that are Dabo-esque. I'm only vaguely familiar with it, though. Depending on your needs, you can use various dialog builders to create XRC/XML "descriptions" of your interface and load them up-- but personally I hand-code all the controls and interfaces, and doing so once you learn the system is really quite rapid. I can dummy up a very functional interface for testing/dummying much faster in Python/wxPython then I can in Visual Studio. It doesn't have as many bells and whistles, but I really can't imagine why anyone would find themselves control-starved. > and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. > What problems? Yes, you have to learn py2exe, but once you have your program packaged together, it's no different then any other program on windows. Build a MSI, and have the IT guy push that MSI out via an active directory group policy. Isn't that the standard way you install and update /any/ group of users' software on a windows network? Regardless of in what language you write it in? I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. Data access is easy and well supported to a wide-variety of databases, depending on just how you want to do it. I've recently fallen in love with SQLAlchemy, though previously I did mostly simple DB-API based access and home-grown model objects representing data models. The wxWidgets "data grid" is somewhat somewhat lacking at present in that it doesn't really connect "to" the database-- but it is not significantly hard to write a table implementation to serve as your 'backend' to connect to the database, which the grid can then uses to define what it shows. Dabo's grid implementation solves that, I believe, so may be good for you. Reports, I have no idea-- in my company's domain the reporting needs are very limited, and we've found it sufficient to write out a HTML file and toss up IE to print out the table. But there is reportlab which is an excellent library for PDF generation -- and making reports in particular, of course. It has support for barcodes, I believe. Dabo also has some links to a report generator they include -- never really looked in beyond glancing and going 'Oh, neat.' --S P.S. I have no idea why I'm pumping Dabo so much in this though I've never used it! -------------- next part -------------- An HTML attachment was scrubbed... URL: From john.haxby at oracle.com Mon Aug 24 11:50:11 2009 From: john.haxby at oracle.com (John Haxby) Date: Mon, 24 Aug 2009 16:50:11 +0100 Subject: Bash-like brace expansion In-Reply-To: References: Message-ID: <4A92B6B3.9020509@oracle.com> Peter Waller wrote: > Okay, I got fed up with there not being any (obvious) good examples of > how to do bash-like brace expansion in Python, so I wrote it myself. > Here it is for all to enjoy! > > If anyone has any better solutions or any other examples of how to do > this, I'd be glad to hear from them. > That was a little while ago and while I found Peter's BraceExpand was a good start it wasn't quite what I wanted. It's not quite the same as bash: for example, BraceExpand("{1,3..5}") gives "1 3 4 5" but bash gives "1 3..5" (use "{1,{3..5}}") and bash turns all of "{a..z}", "{z..a}, "{10..-10}" into sequences. My version is a little shorter, mostly because it's heavily recursive so it may fail spectacularly on some pathological cases :-) jch -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: bp.py URL: From code at pizzashack.org Mon Aug 24 11:50:28 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 10:50:28 -0500 Subject: Annoying octal notation In-Reply-To: <200908241722.39942.hendrik@microcorp.co.za> References: <20090824135648.GA20434@dragontoe.org> <20090824141425.GB20434@dragontoe.org> <200908241722.39942.hendrik@microcorp.co.za> Message-ID: <20090824155028.GC20434@dragontoe.org> On Mon, Aug 24, 2009 at 05:22:39PM +0200, Hendrik van Rooyen wrote: > > Assuming I'm right about that, then the use of a leading 0 to > > represent octal actually predates the prevalence of using 0 in dates > > by almost two decades. > > Not quite - at the time I started, punch cards and data entry forms were > already well established practice, and at least on the English machines, (ICL > 1500/1900 series) octal was prevalent, but I don't know when the leading zero > octal notation started, and where. I said "prevalence." The key is that the average person did not start using leading zeros in dates until (I think) much, much later, and that's what's relevant to this discussion. If it were not commonplace for people to use decimal numbers with leading zeros, this whole thread would be a moot point, the python devs likely never would have considered changing the syntax, and we would not be having this discussion. Most people did not work as data entry clerks on ICL computers... :) Those participating in this thread have pretty much all seem to agree that the only places where decimal numbers with leading zeros really are common are either in rather specialized applications, such as computer-oriented data or serial numbers (which typically behave more like strings, from a computer science perspective), or the rather common one of dates. The latter case is perhaps what's significant, if any of those cases are. I tend to think that within the computer science arena, the history and prevalence of the leading 0 indicating octal far outweighs all of those cases combined. > I think you give it credence for far more depth of design thinking than what > actually happened in those days - some team working on a compiler made a > decision (based on gut feel or experience, or precedent, or whim ) and that > was that - lo! - a standard is born! Rather, I think you give the folks at Bell Labs way too little credit. They designed a programming language and an operating system that, while certainly not exactly the same as their original incarnations, even then contained a lot of features and design principles that remain state-of-the-art (though perhaps their specific implementation details have since been improved) and in many ways superior to a lot of what has come since (e.g. virtually anything that came out of Microsoft). [That's just my opinion, of course... but shared by many. :)] I don't think that happened by mere accident. That's not to say they were perfect, but those guys had their proverbial $#!t together. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From martin at v.loewis.de Mon Aug 24 11:56:43 2009 From: martin at v.loewis.de (=?windows-1252?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 24 Aug 2009 17:56:43 +0200 Subject: print() and unicode strings (python 3.1) In-Reply-To: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> Message-ID: <4a92b83b$0$27209$9b622d9e@news.freenet.de> > I don't understand why I'm getting an encode error in python 3.1. The default encoding is not relevant here at all. Look at sys.stdout.encoding. Regards, Martin From chris at simplistix.co.uk Mon Aug 24 12:08:15 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 24 Aug 2009 17:08:15 +0100 Subject: Python 2.6 still not giving memory back to the OS... In-Reply-To: <4A88406C.3060609@v.loewis.de> References: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> <762603ba-0a4c-4504-94d9-34a8b1e3f9c3@s15g2000yqs.googlegroups.com> <4A88406C.3060609@v.loewis.de> Message-ID: <4A92BAEF.2010303@simplistix.co.uk> Martin v. L?wis wrote: > Today, there are two cases when malloc returns memory on a typical > Unix system (in particular, in Linux malloc): > a) if the malloc block block is small (below page size), it is allocated > from the brk heap, where it can only be returned if the last page of > that heap is completely free, and > b) if the block is large (multiple pages), it gets returned to the > system right away. > > Case b) can only happen if the C malloc uses mmap to allocate large > blocks. I believe (and John will correct me if I'm wrong) that xlrd uses mmap, so why am I not seeing the memory being returned? Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From stefan_ml at behnel.de Mon Aug 24 12:12:11 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 18:12:11 +0200 Subject: Need cleanup advice for multiline string In-Reply-To: <02a2a478$0$20629$c3e8da3@news.astraweb.com> References: <5cd0cdaa-db32-45df-ac65-3bd434c1f7e9@s31g2000yqs.googlegroups.com> <461cc6f1-fc23-4bc7-a719-6f29babf8bcd@o15g2000yqm.googlegroups.com> <4a918fe0$0$30226$9b4e6d93@newsspool1.arcor-online.net> <02a1cc1d$0$30337$c3e8da3@news.astraweb.com> <4a9243d3$0$32677$9b4e6d93@newsspool2.arcor-online.net> <02a2a478$0$20629$c3e8da3@news.astraweb.com> Message-ID: <4a92bbdb$0$32676$9b4e6d93@newsspool2.arcor-online.net> Steven D'Aprano wrote: > On Mon, 24 Aug 2009 09:40:03 +0200, Stefan Behnel wrote: > >>> Or you could enter the 21 century and understand that "guys" has become >>> a generic term for people of any sex. >> Is that true for everyone who understands and/or writes English? In that >> case, I'm fine with your above statement. Otherwise, I'd wonder who you >> meant with the term "cultural chauvinism". So far, I only learned that >> most North-American English native speakers use that term in the way you >> refer to. That doesn't even get you close to the majority of English >> speakers. > > If you read the entire thread, you'd see that we've already discussed the > issue of "guys" for mixed sex groups and females. In fact, as I'd already > said, I'm one of those old fashioned guys who still gets surprised when > women refer to themselves as guys, but I'm learning to keep up with the > times. I'm Australian, not North American, and the British author Michael > Quinion, one of the researchers for the Oxford Dictionary, also states > that "guys" now refers to both men and women: > > http://www.worldwidewords.org/weirdwords/ww-guy1.htm > > When "guys" can refer to either sex in English, American, Canadian and > Australian English, I think it should be pretty uncontroversial to treat > it as standard now. Ok, then I guess I just misread "after being adopted in the USA it started to change meaning" in one of the cited articles as "it changed meaning in the USA". I didn't expect Australians (and Oxford dictionary writers, and potentially others) to be /that/ influenced by shifts in US juvenile word semantics... I for one wouldn't start calling my leg "foot", even though the Austrians kept insisting for ages now. Stefan From chris at simplistix.co.uk Mon Aug 24 12:13:45 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Mon, 24 Aug 2009 17:13:45 +0100 Subject: Barcodes In-Reply-To: <9c8c445f0908191655i42ec8f86p8f699f2b35cbf6f7@mail.gmail.com> References: <9c8c445f0908171318x2d9d862bi35ccb398376aceca@mail.gmail.com> <4A89C3BB.2030605@tim.thechases.com> <9c8c445f0908190619v5f50de1bvbbfbd8c0557f9783@mail.gmail.com> <9c8c445f0908191655i42ec8f86p8f699f2b35cbf6f7@mail.gmail.com> Message-ID: <4A92BC39.3010007@simplistix.co.uk> Ronn Ross wrote: > > I found this library, but no > documentation(https://cybernetics.hudora.biz/projects/wiki/huBarcode). > Has anyone used this or know of a similar library with better > documentation? Yup, reportlab has really good barcode generation stuff. I use it to generate labels with barcodes on for asset tracking :-) http://the-gay-bar.com/index.php?/archives/221-Howto-generate-barcodes-in-Python-with-reportlab/ Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From Scott.Daniels at Acm.Org Mon Aug 24 12:18:20 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Mon, 24 Aug 2009 09:18:20 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: Piet van Oostrum wrote: >>>>>> Scott David Daniels (SDD) wrote: > >> SDD> James Harris wrote:... >>>> Another option: >>>> >>>> 0.(2:1011), 0.(8:7621), 0.(16:c26b) >>>> >>>> where the three characters "0.(" begin the sequence. >>>> >>>> Comments? Improvements? > >> SDD> I did a little interpreter where non-base 10 numbers >> SDD> (up to base 36) were: > >> SDD> .7.100 == 64 (octal) >> SDD> .9.100 == 100 (decimal) >> SDD> .F.100 == 256 (hexadecimal) >> SDD> .1.100 == 4 (binary) >> SDD> .3.100 == 9 (trinary) >> SDD> .Z.100 == 46656 (base 36) > > I wonder how you wrote that interpreter, given that some answers are wrong. Obviously I started with a different set of examples and edited after starting to make a table that could be interpretted in each base. After doing that, I forgot to double check, and lo and behold .F.1000 = 46656, while .F.100 = 1296. Since it has been decades since I've had access to that interpreter, this is all from memory. --Scott David Daniels Scott.Daniels at Acm.Org From nmm1 at cam.ac.uk Mon Aug 24 12:20:23 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Mon, 24 Aug 2009 17:20:23 +0100 (BST) Subject: Python/Fortran interoperability References: <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> Message-ID: In article , sturlamolden wrote: > >You also made this claim regarding Fortran's C interop with strings: > >"No, I mean things like 'Kilroy was here'. Currently, Fortran's C >interoperability supports only strings of length 1, and you have >to kludge them up as arrays. That doesn't work very well, especially >for things like function results." > >This obviosuly proves you wrong: Er, no, it doesn't. I suggest that you read what I said more carefully - and the Fortran standard. As I said, you can kludge them up, and that is precisely one such kludge - but, as I also said, it doesn't work very well. However, I shall take your answer as a "yes, I want to do that". Regards, Nick Maclaren. From code at pizzashack.org Mon Aug 24 12:21:46 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 11:21:46 -0500 Subject: Annoying octal notation In-Reply-To: <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> Message-ID: <20090824162146.GD20434@dragontoe.org> On Mon, Aug 24, 2009 at 08:31:13AM -0700, Carl Banks wrote: > On Aug 24, 6:56?am, Derek Martin wrote: > >?I think hard-coding dates is more uncommon than using octal. ;-) > >?[It unquestionably is, for me personally.] > > You just don't get it, do you? I think I get it just fine, thanks. > Do you really think this is a contest over what's more common and > the winner gets to choose the syntax? You really think that's the > issue? No, I think it's about egos. Someone got the idea that 0o1 was better than 01, and had to be Right. And had the power to make it happen, or at least (sadly) convince the people with the power. I'm simply presenting an argument that the need for the change is not so clear. You say the old syntax is retarded. I say the new syntax, and the very act of making the change itself is retarded. I think my argument is very solid and persuasive; but of course some minds are invulnerable to persuasion. I might not even disagree that the old syntax could be improved upon, except that it already is what it is, and the new syntax is NOT better; I personally believe it's not only not better, but that it's actually worse. Others have agreed. > It is not. The issue is that C's arcane octal notation is MIND- > BOGGLINGLY RETARDED. As I said, I searched the web on this topic before I bothered to post. I did a bit of research. One of the things that my search turned up: A lot of smart people disagree with you. If the use of the leading zero boggles your mind, then perhaps your mind is too easily boggled, and perhaps you should seek a different way to occupy your time. This is yet another case where some Pythonista has gotten it in his head that "There is One Truth, and the Old Way be Damned, my way is The Way, and Thus Shall It Be Evermore." And worse yet, managed to convince others. Well, there's no such thing as One Truth, and there are different perspectives that are just as valid as yours. I'm expressing one now. This change sucks. I already know that my rant won't change the syntax. The only reason I bothered to post is because I do actually quite like Python -- something I can say of only one other programming language -- and I think the powers that be are (in some cases) making it worse, not better. I hoped to open a few minds with a different perspective, but of course I should have known better. 0o1 is not better than 01. On my terminal it's hard to see the difference between 0 and o. YMMV. But since YMMV, and since the old syntax is prevalent both within and without the Python community, making the change is, was, and always will be a bad idea. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve at REMOVE-THIS-cybersource.com.au Mon Aug 24 12:47:43 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2009 16:47:43 GMT Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <20090824135648.GA20434@dragontoe.org> Message-ID: <02a2b43f$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 09:14:25 -0500, Derek Martin wrote: > Assuming I'm right about that, then the use of a leading 0 to represent > octal actually predates the prevalence of using 0 in dates by almost two > decades. And while using leading zeros in other contexts is "familiar" > to me, I would certainly not consider it "common" by any means. Thus I > think it's fair to say that when this syntax was selected, it was a > rather good choice. Except of course to anyone familiar with mathematics in the last, oh, five hundred years or so. Mathematics has used a positional system for numbers for centuries now: leading zeroes have been insignificant, just like trailing zeroes after the decimal point: 9 = 09 = 009 = 9.0 = 9.00 = 0009.000 etc. -- Steven From ronn.ross at gmail.com Mon Aug 24 12:50:37 2009 From: ronn.ross at gmail.com (Ronn Ross) Date: Mon, 24 Aug 2009 12:50:37 -0400 Subject: Reading binary files In-Reply-To: <9c8c445f0908240818k1ae301acr49c65ccb21435cd7@mail.gmail.com> References: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> <1251125039.23757.0.camel@brotherus.corp.redhat.com> <9c8c445f0908240818k1ae301acr49c65ccb21435cd7@mail.gmail.com> Message-ID: <9c8c445f0908240950h24e5bfccoc9ae809c1048be5d@mail.gmail.com> On Mon, Aug 24, 2009 at 11:18 AM, Ronn Ross wrote: > > > On Mon, Aug 24, 2009 at 10:43 AM, Albert Hopkins wrote: > >> On Mon, 2009-08-24 at 10:35 -0400, Ronn Ross wrote: >> > I need to read a binary file. When I open it up in a text editor it is >> > just junk. Does Python have a class to help with this? >> >> Yes, the "file" class. >> >> >>> myfile = open('/path/to/binary/file', 'rb') >> >> -a >> > This works for a simple binary file, but the actual file I'm trying to read > is give throwing an error that the file cannot be found. Here is the name of > the my file: > 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars > > Should python have trouble reading this file name or extension? > I'm having trouble with the filename: 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars It throws an error with that file name, When I change it to something like sample.txt it runs, but the data is still garbled. Is there any reason why I can't use the above file name? If I'm using 'rb' to read the binary file why is it still garbled? -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Mon Aug 24 12:54:03 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 24 Aug 2009 09:54:03 -0700 (PDT) Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> Message-ID: On Aug 24, 9:56?am, "Martin v. L?wis" wrote: > > I don't understand why I'm getting an encode error in python 3.1. > > The default encoding is not relevant here at all. Look at > sys.stdout.encoding. > > Regards, > Martin Hi, Thanks for the response. I get US-ASCII for both 2.6 and 3.1: ===python 3.1====== import sys print(sys.stdout.encoding) $ python3.1 1test.py US-ASCII I can't figure out a way to programatically set the encoding for sys.stdout. So where does that leave me? python 3.1 won't let me explicitly encode my unicode string, and python 3.1 implicitly does the encoding with the wrong codec. And why would any programmer rely on python 3.1's implicit encoding of unicode strings anyway? Presumably, different systems will have different encodings for sys.stdout, some encodings might cause encode errors. From rurpy at yahoo.com Mon Aug 24 12:56:47 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Mon, 24 Aug 2009 09:56:47 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: <8e65beea-eb8e-45cf-b286-36055be5eb2e@c2g2000yqi.googlegroups.com> On 08/24/2009 06:08 AM, Gilles Ganault wrote: > I was wondering if some people in this ng use Python and some GUI > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > applications, and if yes, what it's like, the pros and cons, etc. > > I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. > > I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. I sure you'll get plenty of GUI-x is really great and you'll is just as good as anything commercial out there, so I thought a minority opinion, even if unpopular, might be useful. Won't comment on the control choices or packaging issues, but I am at the moment doing a little database-connected app that presents editable data in a spreadsheet like (grid) form using wxPython. It has been a very painful process. I have not found any simple pre-written code to connect a wxPython grid to a database so that the result is something like a Microsoft Access datasheet.[*1] It is probably taking me 10 times as long to develop this app in WxPython/Postgresql as it did to develop something similar in MS Access/VBA/SQL Server. I haven't needed for printing yet, but I've read wxpython maillist posts about the difficultly of getting printing to work so you may want to check that out as well before commiting to wxpython. A meta-issue that applies (I think) to both wxPython and PyQt is that both projects seem to be highly dependent on a single person leading one to worry about the "bus" scenario. I am not a fan of Microsoft (in fact I despise their commercial behavior and many aspects of thier products) but I am reporting the reality as I've experienced it. [*1] There are ORMs like Sqlalchemy but they introduce a additional problems like inefficient database operations, dependency on a large external package, etc. It is hard to tell for sure since the Sqlalchemy docs are lousy, which of course means even more development time. From code at pizzashack.org Mon Aug 24 13:02:39 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 12:02:39 -0500 Subject: Annoying octal notation In-Reply-To: <02a2b43f$0$20629$c3e8da3@news.astraweb.com> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <20090824135648.GA20434@dragontoe.org> <02a2b43f$0$20629$c3e8da3@news.astraweb.com> Message-ID: <20090824170239.GE20434@dragontoe.org> On Mon, Aug 24, 2009 at 04:47:43PM +0000, Steven D'Aprano wrote: > Except of course to anyone familiar with mathematics in the last, oh, > five hundred years or so. Mathematics has used a positional system for > numbers for centuries now: leading zeroes have been insignificant, just > like trailing zeroes after the decimal point: > > 9 = 09 = 009 = 9.0 = 9.00 = 0009.000 etc. Dude, seriously. No one ever *uses* leading zeros in the context of mathematics except in 2nd grade math class. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From steve at REMOVE-THIS-cybersource.com.au Mon Aug 24 13:03:28 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 24 Aug 2009 17:03:28 GMT Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> Message-ID: <02a2b7f1$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 11:21:46 -0500, Derek Martin wrote: > since the old > syntax is prevalent both within and without the Python community, making > the change is, was, and always will be a bad idea. Octal syntax isn't prevalent *at all*, except in a small number of niche areas. You've said that this change is a hardship for you, because on your terminal 0 and o are hard to distinguish. Personally, I'd say that's a good sign that your terminal is crappy and you should use a better one, but putting that aside, let's accept that. To you, for whatever reason, 0o looks just like 00. Okay then. Under the current 2.x syntax, 0012 would be interpreted as octal. Under the new 3.x syntax, 0o12 which looks just like 0012 also would be interpreted as octal. You have argued that it might not be any harder to type the extra 'o' to get an octal literal, but that it will hurt readability. I quote: "Writing 0o12 presents no hardship; but I assert, with at least some support from others here, that *reading* it does." But according to you, reading 0o12 is just like reading 0012. 0o12 under the new syntax gives decimal ten, and it looks just like 0012 in the old syntax, which also gives ten. So there's no difference in reading, and you've already accepted that the extra effort in writing it "presents no hardship". A whole lot of noise over a change which is more or less invisible. -- Steven From harald.luessen at gmx.de Mon Aug 24 13:18:16 2009 From: harald.luessen at gmx.de (Harald Luessen) Date: Mon, 24 Aug 2009 19:18:16 +0200 Subject: Annoying octal notation References: <20090824135648.GA20434@dragontoe.org> <20090824141425.GB20434@dragontoe.org> <200908241722.39942.hendrik@microcorp.co.za> Message-ID: On Mon, 24 Aug 2009 Derek Martin wrote: >Those participating in this thread have pretty much all seem to agree >that the only places where decimal numbers with leading zeros really >are common are either in rather specialized applications, such as >computer-oriented data or serial numbers (which typically behave more >like strings, from a computer science perspective), or the rather >common one of dates. The latter case is perhaps what's significant, >if any of those cases are. I don't like the 'leading 0 is octal'-syntax. I typically think of numbers as decimal and bytes as hexadecimal. I would even write something like this: # iterate over bits 3 to 5 for i in range(0x00, 0x40, 0x08): ... print "0x%02x\n" % i 0x00 0x08 0x10 0x18 0x20 0x28 0x30 0x38 For me it is easier to see where the bits are in the hex notation. And it is very common to use numbers with leading zeroes that are hexadecimal. Like this: # print address and data for i in range(0x10000): print "%04x: %d\n" % i, data[i] 0000: ... 0001: ... ... 000f: ... 0010: ... ... When you are looking for examples of numbers where leading zeroes do not mean octal then consider decimal AND hexadecimal. >I tend to think that within the computer >science arena, the history and prevalence of the leading 0 indicating >octal far outweighs all of those cases combined. I disagree. Harald From robert.kern at gmail.com Mon Aug 24 13:19:27 2009 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 24 Aug 2009 12:19:27 -0500 Subject: Is Python what I need? In-Reply-To: References: <224ed882-b78e-4b75-afa8-35c907096469@13g2000prl.googlegroups.com> Message-ID: On 2009-08-24 08:32 AM, Peter Otten wrote: > Jean-Michel Pichavant wrote: > >>> > From the distance it looks like these children need a good teacher >>>> rather than a bad (or just starting) programmer. > >> Wow, that is rude. Let's keep this list friendly, won't we ? > > I may have been too blunt, and if my message has come across as an insult I > apologize for that. Let me try again: > > If you are trying to teach children that are unwilling to use pen and paper > putting them in front of a computer doesn't help you and them one bit. As a > starting programmer you'll have to spend a lot of time in front of your > computer that may be better spent with your students. I suspect everyone is reading too much into the word "aversion". There may be physical or mental handicaps involved, not the personal preference of the students. In such a case, the OP's word choice is not ideal, but the readers here should give a little more thought before assuming the most ludicrous interpretation. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sturlamolden at yahoo.no Mon Aug 24 13:23:55 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 10:23:55 -0700 (PDT) Subject: Python/Fortran interoperability References: <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> Message-ID: <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> On 24 Aug, 18:20, n... at cam.ac.uk wrote: >This obviosuly proves you wrong: > > Er, no, it doesn't. ?I suggest that you read what I said more > carefully - and the Fortran standard. ?As I said, you can kludge > them up, and that is precisely one such kludge - You said we have to kludge them up as arrays. I did not. I kludged up the C string as a pointer to a Fortran string, and called strlen to get the length of the C string. You also said we can only interop with length-1 character strings. My kludge was valid Fortran and works with strings of any length up to some sane limit that you can specify. You cannot expect a C pointer to carry information about the length of the string. C strings are nul terminated, which is precisely why we have strlen. When C has to use strlen to get the length of a C string, so does Fortran. You cannot use the Fortran standard to change the behaviour of C. > but, as I also > said, it doesn't work very well. Only if you have an incredibly stupid compiler. Sturla From dirkmoors at gmail.com Mon Aug 24 13:30:09 2009 From: dirkmoors at gmail.com (gravityzoo-dmo) Date: Mon, 24 Aug 2009 10:30:09 -0700 (PDT) Subject: Python memory management <-> virtualized server environments Message-ID: Hello everyone, I was wondering if anyone here has had any experience in running Python in a virtualized server environment? The reason I'm asking is the recent thing I noticed when running my server application (written in Python + Twisted); The memory of the server application seems to only grow, and not give back memory space to the OS. I realize that this won't be a problem on a single physical server, but I'm curious of the effect this behaviour has on a virtualized environment. Could anyone provide me with a little more insight please? Thanks in advance! Dirk From jkpeck at gmail.com Mon Aug 24 13:30:23 2009 From: jkpeck at gmail.com (JKPeck) Date: Mon, 24 Aug 2009 10:30:23 -0700 (PDT) Subject: csv module and None values Message-ID: I'm trying to get the csv module (Python 2.6) to write data records like Excel. The excel dialect isn't doing it. The problem is in writing None values. I want them to result in just sequential commas - ,, but csv treats None specially, as the doc says, "To make it as easy as possible to interface with modules which implement the DB API, the value None is written as the empty string." I need strings to be quoted but not None values. Is there any way to get around this special None treatment? TIA, Jon Peck From code at pizzashack.org Mon Aug 24 13:40:24 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 12:40:24 -0500 Subject: Annoying octal notation In-Reply-To: <02a2b7f1$0$20629$c3e8da3@news.astraweb.com> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> <02a2b7f1$0$20629$c3e8da3@news.astraweb.com> Message-ID: <20090824174024.GF20434@dragontoe.org> On Mon, Aug 24, 2009 at 05:03:28PM +0000, Steven D'Aprano wrote: > On Mon, 24 Aug 2009 11:21:46 -0500, Derek Martin wrote: > > since the old syntax is prevalent both within and without the > > Python community, making the change is, was, and always will be a > > bad idea. > > Octal syntax isn't prevalent *at all*, except in a small number of > niche areas. Steven, don't be obtuse. Where octal is used in programming, the leading zero is prevalent. > You've said that this change is a hardship for you, because on your > terminal 0 and o are hard to distinguish. Personally, I'd say that's a > good sign that your terminal is crappy and you should use a better one, The terminal I use is just fine. Stringing together similar characters always has the possibility of confusing the reader. The human mind tends to see what it expects, and fills in the gaps when it does not. It wouldn't matter much if I changed my terminal font, unless I made the font big enough to be not especially useful, except for the rather exceptional case of detecting 0o1 and similar patterns in python code. The suggestion is asinine, and you know it. > but putting that aside, let's accept that. To you, for whatever reason, > 0o looks just like 00. It doesn't look "just like" 00, but similar enough that you have to pay close attention. > Okay then. Under the current 2.x syntax, 0012 would be interpreted as > octal. Under the new 3.x syntax, 0o12 which looks just like 0012 also > would be interpreted as octal. You have argued that it might not be any > harder to type the extra 'o' to get an octal literal, but that it will > hurt readability. I quote: > > "Writing 0o12 presents no hardship; but I assert, with at least some > support from others here, that *reading* it does." Let me clarify my statement. Writing 0o12 is easy -- there is no hardship to type the characters 0o12 (well, actually it feels a bit cumbersome, to be honest). Remembering to do so, however, when virtually everwhere else one uses octal writes it 012, is not easy. Then I stand corrected: There is indeed hardship. > But according to you, reading 0o12 is just like reading 0012. 0o12 under > the new syntax gives decimal ten, and it looks just like 0012 in the old > syntax, which also gives ten. So there's no difference in reading, But there *IS* a difference in reading, because 0o12 is not the same as 0012, and which one you use *matters*. In particular, it will matter with the adoption of Python 3.x, where the latter will be an error. But it matters even in 2.6 because right now, you can write it either way, and that is (I think) even more confusing... There is also still discussion (mentioned in the relevant PEP) about making 0012 *valid decimal*. That should never, ever, ever happen. Why is it so hard for you to accept that intelligent people can disagree with you, and that what's right for you might be bad for others? -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From manu3d at gmail.com Mon Aug 24 13:43:24 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Mon, 24 Aug 2009 10:43:24 -0700 (PDT) Subject: List iterator thread safety Message-ID: Let's say I have a list accessed by two threads, one removing list items via "del myList[index]" statement the other iterating through the list and printing out the items via "for item in myList:" statement. Am I right to say this -won't- generate exceptions because the list iterator is not concerned with the list changing in size under its nose? Or are there pitfalls I should be aware of? Manu From nospam at see.signature Mon Aug 24 14:04:56 2009 From: nospam at see.signature (Richard Maine) Date: Mon, 24 Aug 2009 11:04:56 -0700 Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> Message-ID: <1j4y84p.v5docbtueccmN%nospam@see.signature> sturlamolden wrote: > You also said we can only interop with > length-1 character strings. My kludge was valid Fortran and works with > strings of any length up to some sane limit that you can specify. There might be a confusion here (and I'm not even sure on whose part) on a picky but important detail of wording. I have seen multiple people confused by this one before. In fact, some potential confusion was forseen, which is why there are notes specifically about it in the Fortran standard (see below). Those notes do tend to get overlooked though. Only character strings of length 1 are interoperable, as the term "interoperable" is defined in the Fortran standard. However, that does not mean that only character strings of length 1 will work with C. The distinction might be picky, but it is important. See Note 15.19 (which in turn cites an example in Note 15.23) of f2003. You can pass a Fortran string of length n as an actual argument corrseponding to a dummy argument that is an array of n character*1 elements. This isn't considered a question of "interoperability", as it is a feature purely within Fortran, but it does impact on what kinds of things work. One might plausibly regard this as a kludge, but it is a kludge that is part of the Fortran standard and is guaranteed to work with all Fortran compilers. I almost said all f2003-compliant compilers (admittedly a limited set), but then I recalled that the feature actually dates back to f77 when character type was introduced; f2003 just extends it to the C character kind for the obscure case where the C character kind might be different from the default character kind (I don't know of any compilers where this is so, but the standard allows for it). -- Richard Maine | Good judgment comes from experience; email: last name at domain . net | experience comes from bad judgment. domain: summertriangle | -- Mark Twain From stefan_ml at behnel.de Mon Aug 24 14:19:28 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Mon, 24 Aug 2009 20:19:28 +0200 Subject: print() and unicode strings (python 3.1) In-Reply-To: References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> Message-ID: <4a92d9b0$0$32667$9b4e6d93@newsspool2.arcor-online.net> 7stud wrote: > python 3.1 won't let me > explicitly encode my unicode string Sure it does. But encoding a non-ASCII string to ASCII will necessarily fail. > and python 3.1 implicitly does > the encoding with the wrong codec. That's not a Python problem, though. Your terminal is configured for US-ASCII, so you can't output anything but US-ASCII characters. Change your terminal setup to e.g. UTF-8 and see how things start working. Stefan From davea at ieee.org Mon Aug 24 14:35:21 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 24 Aug 2009 14:35:21 -0400 Subject: Reading binary files In-Reply-To: <9c8c445f0908240950h24e5bfccoc9ae809c1048be5d@mail.gmail.com> References: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> <1251125039.23757.0.camel@brotherus.corp.redhat.com> <9c8c445f0908240818k1ae301acr49c65ccb21435cd7@mail.gmail.com> <9c8c445f0908240950h24e5bfccoc9ae809c1048be5d@mail.gmail.com> Message-ID: <4A92DD69.7090007@ieee.org> Ronn Ross wrote: > On Mon, Aug 24, 2009 at 11:18 AM, Ronn Ross wrote: > > >> On Mon, Aug 24, 2009 at 10:43 AM, Albert Hopkins wrote: >> >> >>> On Mon, 2009-08-24 at 10:35 -0400, Ronn Ross wrote: >>> >>>> I need to read a binary file. When I open it up in a text editor it is >>>> just junk. Does Python have a class to help with this? >>>> >>> Yes, the "file" class. >>> >>> >>>>>> myfile = open('/path/to/binary/file', 'rb') >>>>>> >>> -a >>> >>> >> This works for a simple binary file, but the actual file I'm trying to read >> is give throwing an error that the file cannot be found. Here is the name of >> the my file: >> 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars >> >> Should python have trouble reading this file name or extension? >> >> > I'm having trouble with the filename: > 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars > > It throws an error with that file name, When I change it to something like > sample.txt it runs, but the data is still garbled. Is there any reason why I > can't use the above file name? If I'm using 'rb' to read the binary file why > is it still garbled? > > > You're describing two separate problems here. One is an error in the open statement, and the other is "something is garbled." If you hand a relative path name to the open() function, it'll have to get the absolute path from somewhere else, presumably the current directory. Do you know for sure what the current directory is, and is that file located there? Try printing os.path.abspath(os.curdir). Or pass a complete (absolute) path to open(). As for garbled... Just what do you expect? A binary file is a completely arbitrary sequence of bytes. So if you're trying to print it, you may see "garbled." Just what is the file's purpose anyway? You can't do much with it without knowing something about it. DaveA From martin.hellwig at dcuktec.org Mon Aug 24 14:35:45 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Mon, 24 Aug 2009 19:35:45 +0100 Subject: Python memory management <-> virtualized server environments In-Reply-To: References: Message-ID: gravityzoo-dmo wrote: > Hello everyone, > > I was wondering if anyone here has had any experience in running > Python in a virtualized server environment? > The reason I'm asking is the recent thing I noticed when running my > server application (written in Python + Twisted); > The memory of the server application seems to only grow, and not give > back memory space to the OS. I realize that this won't be a problem on > a single physical server, but I'm curious of the effect this behaviour > has on a virtualized environment. > Could anyone provide me with a little more insight please? > Thanks in advance! > > Dirk Might help if you say which version of Python you are running, although I'm not a memory expert I do know there have been some changes between the versions. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From bbxx789_05ss at yahoo.com Mon Aug 24 14:45:17 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 24 Aug 2009 11:45:17 -0700 (PDT) Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92d9b0$0$32667$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <00daf8f6-ee6a-47ab-8d92-1676a473d7cc@y4g2000prf.googlegroups.com> On Aug 24, 12:19?pm, Stefan Behnel wrote: > 7stud wrote: > > python 3.1 won't let me > > explicitly encode my unicode string > > Sure it does. But encoding a non-ASCII string to ASCII will necessarily fail. > As you should be able to see in the python 3.1 example I posted, I did not encode the string using the ascii codec. I encoded it with the utf-8 codec, and unfortunately in python 3.1 that creates a "bytes string", and print()'ing a bytes string does not produce human readable text. > > and python 3.1 implicitly does > > the encoding with the wrong codec. > > That's not a Python problem, though. Your terminal is configured for > US-ASCII, so you can't output anything but US-ASCII characters. > My terminal is configured for utf-8, and from the output of the python 2.6 example I posted, it should be apparent that my terminal is capable of rendering the euro character. From gert.cuykens at gmail.com Mon Aug 24 14:50:55 2009 From: gert.cuykens at gmail.com (gert) Date: Mon, 24 Aug 2009 11:50:55 -0700 (PDT) Subject: How does the file.seek() work ? Message-ID: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> I want the file pointer set to 100 and overwrite everything from there curl -C 100 -T upload2.wsgi http://192.168.2.17/appwsgi/wsgi/upload2.wsgi -v w+ overwrites my file completely r+ overwrites nothing a+ only makes my file bigger import os def application(environ, response): query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') range=environ.get('HTTP_RANGE','bytes=0-').replace ('bytes=','').split(',') offset=[] for r in range: offset.append(r.split('-')) with open(query,'w+') as f: f.seek(int(offset[0][0])) while True: chunk=environ['wsgi.input'].read(8192).decode('latin1') if not chunk: break f.write(chunk) f=open(query) l=str(os.fstat(f.fileno()).st_size) response('200 OK', [('Content-Type', 'text/plain'), ('Content- Length', str(len(l)))]) return [l] also why must I open the file a second time to know how big it is ? From nmm1 at cam.ac.uk Mon Aug 24 14:55:38 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Mon, 24 Aug 2009 19:55:38 +0100 (BST) Subject: Python/Fortran interoperability References: <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> <1j4y84p.v5docbtueccmN%nospam@see.signature> Message-ID: In article <1j4y84p.v5docbtueccmN%nospam at see.signature>, Richard Maine wrote: > >Only character strings of length 1 are interoperable, as the term >"interoperable" is defined in the Fortran standard. However, that does >not mean that only character strings of length 1 will work with C. The >distinction might be picky, but it is important. Precisely. And the kludge does NOT work under all circumstances, which is why I said that it doesn't work very well. Consider, for example: SUBROUTINE Fred (X) BIND(C) CHARACTER*(*) :: X END SUBROUTINE Fred CHARACTER(LEN=100) :: string CALL Fred(string(40:60)) CALL Fred(string(5:50)) This is not currently allowed and raises all sorts of 'interesting' implementation and portability questions. For example, I defy anyone to write Fred portably in C :-) It gets really hairy if you have functions that have assumed length results, but those are obsolescent. Even when Fred has an explicit length, there are some problematic cases, which could catch out programmers in one language that don't know the other fairly well. But those are much less of a problem than the common need for assumed length CHARACTER arguments. Regards, Nick Maclaren. From sturlamolden at yahoo.no Mon Aug 24 15:14:26 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 12:14:26 -0700 (PDT) Subject: Python/Fortran interoperability References: <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> <1j4y84p.v5docbtueccmN%nospam@see.signature> Message-ID: <7abee4bb-b18a-4680-817b-7e76aed40194@c2g2000yqi.googlegroups.com> On 24 Aug, 20:55, n... at cam.ac.uk wrote: > Precisely. ?And the kludge does NOT work under all circumstances, > which is why I said that it doesn't work very well. Do you have an example? > Consider, for example: > > ? ? SUBROUTINE Fred (X) BIND(C) > ? ? CHARACTER*(*) :: X > ? ? END SUBROUTINE Fred Obviously that is not allowed, because C does not know anything about Fortran strings. How should a C compiler pass the correct data structure to Fred? The C bindings in Fortran 2003 has functions to convert C pointers to Fortran pointers (c_f_pointer, c_f_procpointer), because C does not know the ABI of a particular Fortran implementation. From http Mon Aug 24 15:17:39 2009 From: http (Paul Rubin) Date: 24 Aug 2009 12:17:39 -0700 Subject: your favorite debugging tool? References: Message-ID: <7xocq5vx64.fsf@ruckus.brouhaha.com> Esmail writes: > What is your favorite tool to help you debug your > code? I've been getting along with 'print' statements > but that is getting old and somewhat cumbersome. Beyond print statements, I use pdb a lot. Winpdb (www.winpdb.org) is even better, but is kind of cumbersome to get working. From gah at ugcs.caltech.edu Mon Aug 24 15:23:53 2009 From: gah at ugcs.caltech.edu (glen herrmannsfeldt) Date: Mon, 24 Aug 2009 19:23:53 +0000 (UTC) Subject: Python/Fortran interoperability References: <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> <1j4y84p.v5docbtueccmN%nospam@see.signature> Message-ID: In comp.lang.fortran nmm1 at cam.ac.uk wrote: (snip) < Precisely. And the kludge does NOT work under all circumstances, < which is why I said that it doesn't work very well. < Consider, for example: < SUBROUTINE Fred (X) BIND(C) < CHARACTER*(*) :: X < END SUBROUTINE Fred < CHARACTER(LEN=100) :: string < CALL Fred(string(40:60)) < CALL Fred(string(5:50)) < This is not currently allowed and raises all sorts of 'interesting' < implementation and portability questions. For example, I defy anyone < to write Fred portably in C :-) You mean, how does FRED know the length? It seems to me the usual question for Fortran assumed size arrays. Assuming that FRED can tell from the passed string, it seems fine to me. If not, it is a problem. Null terminated strings are a C convention, supported by the library and compiler (string constants). Others are legal C, though you have to be careful which library routines you use. < It gets really hairy if you have functions that have assumed length < results, but those are obsolescent. < Even when Fred has an explicit length, there are some problematic < cases, which could catch out programmers in one language that don't < know the other fairly well. But those are much less of a problem < than the common need for assumed length CHARACTER arguments. Maybe Fortran programmers who started in Fortran 66 will not have so much problem with this. The usual way would be to pass the length, as with assumed size arrays. I believe terminating strings with unusual (likely not null) characters was also done. -- glen From nmm1 at cam.ac.uk Mon Aug 24 15:24:35 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Mon, 24 Aug 2009 20:24:35 +0100 (BST) Subject: Python/Fortran interoperability References: <1j4y84p.v5docbtueccmN%nospam@see.signature> <7abee4bb-b18a-4680-817b-7e76aed40194@c2g2000yqi.googlegroups.com> Message-ID: In article <7abee4bb-b18a-4680-817b-7e76aed40194 at c2g2000yqi.googlegroups.com>, sturlamolden wrote: > >> Precisely. =A0And the kludge does NOT work under all circumstances, >> which is why I said that it doesn't work very well. > >Do you have an example? I gave you one. Also see below. >> Consider, for example: >> >> =A0 =A0 SUBROUTINE Fred (X) BIND(C) >> =A0 =A0 CHARACTER*(*) :: X >> =A0 =A0 END SUBROUTINE Fred > >Obviously that is not allowed, because C does not know anything about >Fortran strings. How should a C compiler pass the correct data >structure to Fred? Precisely. The reason I asked that question is that it would be possible to extend the standard to make it possible in a portable fashion. You might also like to consider the converse problem: how to write a Fortran function that takes a C string of arbitrary length and uses it. Regards, Nick Maclaren. From python.list at tim.thechases.com Mon Aug 24 15:37:00 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 24 Aug 2009 14:37:00 -0500 Subject: How does the file.seek() work ? In-Reply-To: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> References: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> Message-ID: <4A92EBDC.8010901@tim.thechases.com> > I want the file pointer set to 100 and overwrite everything from there [snip] > def application(environ, response): > query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') > range=environ.get('HTTP_RANGE','bytes=0-').replace > ('bytes=','').split(',') > offset=[] > for r in range: offset.append(r.split('-')) > with open(query,'w+') as f: > f.seek(int(offset[0][0])) > while True: > chunk=environ['wsgi.input'].read(8192).decode('latin1') > if not chunk: break > f.write(chunk) > f=open(query) > l=str(os.fstat(f.fileno()).st_size) > response('200 OK', [('Content-Type', 'text/plain'), ('Content- > Length', str(len(l)))]) > return [l] A couple items of note: - you don't open the file in binary mode -- seek is more reliable in binary mode :) - if you want to lop off the rest of the file, use f.truncate() An example: # create the initial file >>> f = file('zzz.zzz', 'wb+') >>> f.write('abcdefghijklmnop') >>> f.close() >>> f = file('zzz.zzz', 'ab+') >>> f.read() # show the existing content 'abcdefghijklmnop' >>> f.seek(5) # seek to the desired offset >>> f.truncate() # throw away everything after here >>> f.write('zyx') # write the new data at pos=5 >>> f.close() # demonstrate that it worked >>> f = file('zzz.zzz', 'rb') >>> f.read() 'abcdezyx' >>> f.close() > also why must I open the file a second time to know how big it is ? Likely the output has been buffered. You can try using f.flush() # write all the data to the disk first size = os.fstat(f.fileno()).st_size which seems to do the trick for me. -tkc From gagsl-py2 at yahoo.com.ar Mon Aug 24 15:40:14 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 24 Aug 2009 16:40:14 -0300 Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> <02a2b7f1$0$20629$c3e8da3@news.astraweb.com> <20090824174024.GF20434@dragontoe.org> Message-ID: En Mon, 24 Aug 2009 14:40:24 -0300, Derek Martin escribi?: > Why is it so hard for you to accept that intelligent people can > disagree with you, and that what's right for you might be bad for > others? Ask the same question yourself please. -- Gabriel Genellina From gordon at panix.com Mon Aug 24 15:41:17 2009 From: gordon at panix.com (John Gordon) Date: Mon, 24 Aug 2009 19:41:17 +0000 (UTC) Subject: Web Services examples using "raw" xml? Message-ID: I'm developing a program that will use web services, which I have never used before. There are several tutorials out there that advise you to get the WSDL and then call a method (such as wsdl2py) that inspects the wsdl and automagically generates the python classes and methods you need for interacting with that web service. I've tried this, and have run into a number of roadblocks that have left me frustrated. For example I tried wsdl2py() from the ZSI package, and got this error: Error loading services.xml: namespace of schema and import match I tried WSDL.Proxy() from the SOAPpy package and eventually end up with this error: xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 6 I tried Client() from the suds package, and got this error: File "/usr/lib/python2.3/site-packages/suds/client.py", line 59 @classmethod ^ SyntaxError: invalid syntax I'm not an expert; I have no idea what any of these errors mean, and I have no idea how to go about resolving them. So I decided to take a step back and see if I could bypass all the fancy automagic methods and just create my own SOAP xml message from scratch and then send it to the web server. That would work, surely. But I'm having a tough time finding some good examples of that, because all the tutorials I've found just tell you to use the aforementioned magic methods, which unfortunately don;t seem to be working for me. Does anyone have some good examples of code that builds a "raw" xml SOAP message and sends it to a webserver, then reads the response? I think that would be a good place for me to start. Thanks for any replies. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From gert.cuykens at gmail.com Mon Aug 24 15:41:59 2009 From: gert.cuykens at gmail.com (gert) Date: Mon, 24 Aug 2009 12:41:59 -0700 (PDT) Subject: How does the file.seek() work ? References: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> Message-ID: <6a22c4d5-1f6b-4ebf-9f4e-3f039d213a49@r42g2000yqj.googlegroups.com> On Aug 24, 9:37?pm, Tim Chase wrote: > > I want the file pointer set to 100 and overwrite everything from there > [snip] > > def application(environ, response): > > ? ? query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') > > ? ? range=environ.get('HTTP_RANGE','bytes=0-').replace > > ('bytes=','').split(',') > > ? ? offset=[] > > ? ? for r in range: offset.append(r.split('-')) > > ? ? with open(query,'w+') as f: > > ? ? ? ? ?f.seek(int(offset[0][0])) > > ? ? ? ? ?while True: > > ? ? ? ? ? ? ?chunk=environ['wsgi.input'].read(8192).decode('latin1') > > ? ? ? ? ? ? ?if not chunk: break > > ? ? ? ? ? ? ?f.write(chunk) > > ? ? f=open(query) > > ? ? l=str(os.fstat(f.fileno()).st_size) > > ? ? response('200 OK', [('Content-Type', 'text/plain'), ('Content- > > Length', str(len(l)))]) > > ? ? return [l] > > A couple items of note: > > - you don't open the file in binary mode -- seek is more reliable > in binary mode :) > > - if you want to lop off the rest of the file, use f.truncate() > > An example: > > # create the initial file > ?>>> f = file('zzz.zzz', 'wb+') > ?>>> f.write('abcdefghijklmnop') > ?>>> f.close() > > ?>>> f = file('zzz.zzz', 'ab+') > ?>>> f.read() # show the existing content > 'abcdefghijklmnop' > ?>>> f.seek(5) # seek to the desired offset > ?>>> f.truncate() # throw away everything after here > ?>>> f.write('zyx') # write the new data at pos=5 > ?>>> f.close() > > # demonstrate that it worked > ?>>> f = file('zzz.zzz', 'rb') > ?>>> f.read() > 'abcdezyx' > ?>>> f.close() > > > also why must I open the file a second time to know how big it is ? > > Likely the output has been buffered. ?You can try using > > ? ?f.flush() # write all the data to the disk first > ? ?size = os.fstat(f.fileno()).st_size > > which seems to do the trick for me. > > -tkc Doh! my curl was wrong, thanks :) curl -C 100 upload2.wsgi http://192.168.2.17/appwsgi/wsgi/upload2.wsgi -v From nagle at animats.com Mon Aug 24 15:51:55 2009 From: nagle at animats.com (John Nagle) Date: Mon, 24 Aug 2009 12:51:55 -0700 Subject: Web Services examples using "raw" xml? In-Reply-To: References: Message-ID: <4a92ee38$0$1627$742ec2ed@news.sonic.net> John Gordon wrote: > I'm developing a program that will use web services, which I have never > used before. Web services in general, or some Microsoft interface? John Nagle From nmm1 at cam.ac.uk Mon Aug 24 15:54:38 2009 From: nmm1 at cam.ac.uk (nmm1 at cam.ac.uk) Date: Mon, 24 Aug 2009 20:54:38 +0100 (BST) Subject: Python/Fortran interoperability References: <1j4y84p.v5docbtueccmN%nospam@see.signature> Message-ID: In article , glen herrmannsfeldt wrote: > >< Consider, for example: > >< SUBROUTINE Fred (X) BIND(C) >< CHARACTER*(*) :: X >< END SUBROUTINE Fred > >< CHARACTER(LEN=100) :: string >< CALL Fred(string(40:60)) >< CALL Fred(string(5:50)) > >< This is not currently allowed and raises all sorts of 'interesting' >< implementation and portability questions. For example, I defy anyone >< to write Fred portably in C :-) > >You mean, how does FRED know the length? It seems to me the >usual question for Fortran assumed size arrays. Assuming that >FRED can tell from the passed string, it seems fine to me. >If not, it is a problem. Precisely. And the whole point of my question is how many people WANT to do it, from the point of view of extending BIND(C). >< Even when Fred has an explicit length, there are some problematic >< cases, which could catch out programmers in one language that don't >< know the other fairly well. But those are much less of a problem >< than the common need for assumed length CHARACTER arguments. > >Maybe Fortran programmers who started in Fortran 66 will not >have so much problem with this. The usual way would be to >pass the length, as with assumed size arrays. I believe terminating >strings with unusual (likely not null) characters was also done. Yeah. But there are a decreasing number of us left :-) Prefix length strings were also used. Regards, Nick Maclaren. From jkpeck at gmail.com Mon Aug 24 15:55:31 2009 From: jkpeck at gmail.com (JKPeck) Date: Mon, 24 Aug 2009 12:55:31 -0700 (PDT) Subject: csv module and None values References: Message-ID: <040ec55a-5b14-41c4-8099-683a6d3a0a45@n11g2000yqb.googlegroups.com> On Aug 24, 11:30?am, JKPeck wrote: > I'm trying to get the csv module (Python 2.6) to write data records > like Excel. ?The excel dialect isn't doing it. ?The problem is in > writing None values. ?I want them to result in just sequential commas > - ,, but csv treats None specially, as the doc says, > > "To make it as easy as possible to interface with modules which > implement the DB API, the value None is written as the empty string." > > I need strings to be quoted but not None values. ?Is there any way to > get around this special None treatment? > > TIA, > Jon Peck Solved the problem myself by giving a writer class to csv.writer that looks for sentinel markers inserted in place of None and wipes them out before writing to a file. Pretty ugly, but it works. Regards, Jon Peck From gordon at panix.com Mon Aug 24 15:57:06 2009 From: gordon at panix.com (John Gordon) Date: Mon, 24 Aug 2009 19:57:06 +0000 (UTC) Subject: Web Services examples using "raw" xml? References: <4a92ee38$0$1627$742ec2ed@news.sonic.net> Message-ID: In <4a92ee38$0$1627$742ec2ed at news.sonic.net> John Nagle writes: > John Gordon wrote: > > I'm developing a program that will use web services, which I have never > > used before. > Web services in general, or some Microsoft interface? Microsoft. Exchange Web Services, specifically. -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From sturlamolden at yahoo.no Mon Aug 24 16:03:06 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 13:03:06 -0700 (PDT) Subject: Python/Fortran interoperability References: <1j4y84p.v5docbtueccmN%nospam@see.signature> <7abee4bb-b18a-4680-817b-7e76aed40194@c2g2000yqi.googlegroups.com> Message-ID: On 24 Aug, 21:24, n... at cam.ac.uk wrote: > You might also like to consider the converse problem: how to write > a Fortran function that takes a C string of arbitrary length and > uses it. That's what the code I showed you does. From code at pizzashack.org Mon Aug 24 16:14:24 2009 From: code at pizzashack.org (Derek Martin) Date: Mon, 24 Aug 2009 15:14:24 -0500 Subject: Annoying octal notation In-Reply-To: References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> <02a2b7f1$0$20629$c3e8da3@news.astraweb.com> <20090824174024.GF20434@dragontoe.org> Message-ID: <20090824201424.GG20434@dragontoe.org> On Mon, Aug 24, 2009 at 04:40:14PM -0300, Gabriel Genellina wrote: > En Mon, 24 Aug 2009 14:40:24 -0300, Derek Martin > escribi?: > > >Why is it so hard for you to accept that intelligent people can > >disagree with you, and that what's right for you might be bad for > >others? > > Ask the same question yourself please. I accept it. But I reserve the right to voice my dissent, and am doing so. The Usual Suspects in this forum seem to suggest that the change is some silver bullet that makes Python suddenly Right With The World, and I say it just ain't so. I happen to opine that the old behavior was better, and I will not be dissuaded from that opinion just because a few prominent posters in this forum suggest that I'm an idiot for disagreeing with them. My original post in this thread, if you weren't paying attention, was in opposition to several people trying to cram the idea down the throats of other posters that leading zeros to represent octal numbers is inherently evil, and that anyone who suggests otherwise is an Apostate to be damned for all eternity. Alright, I exaggerate. Slightly. :) -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From vorticitywolfe at gmail.com Mon Aug 24 16:29:07 2009 From: vorticitywolfe at gmail.com (J Wolfe) Date: Mon, 24 Aug 2009 13:29:07 -0700 (PDT) Subject: Pmw optionmenu color Message-ID: <0faab022-2ad1-4579-a5b9-54f93591c953@26g2000yqk.googlegroups.com> Hello, It seems like this should be easy to do... change the background color of the Pmw optionmenu. I have not been able to find this. Anyone have a hint or know how to do this? Thanks, Jonathan From ryniek90 at gmail.com Mon Aug 24 16:34:51 2009 From: ryniek90 at gmail.com (ryniek) Date: Mon, 24 Aug 2009 13:34:51 -0700 (PDT) Subject: Temat:, Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> <4ec18c68-b8b5-401e-b910-802b7662dced@i18g2000pro.googlegroups.com> Message-ID: <321b8396-0806-4a1a-9a32-efbb147e6b4b@c2g2000yqi.googlegroups.com> On 24 Sie, 16:56, John Machin wrote: > On Aug 25, 12:46?am, Tim Golden wrote: > > > Dave Angel wrote: > > > You still haven't gotten rid of those illegal colons in the filename. ? > > > They're not legal in Windows, as has been pointed out a couple of times > > > in this thread. > > > Ummm.. Colons are of course legal in Windows filenames as designating > > That is the most inappropriate "of course" I've seen for quite a > while. > > > the Alternate Data Streams: > > OK, so s/illegal/evil/ Ok, but how to get rid of those colons? Is it necessary? From deets at nospam.web.de Mon Aug 24 16:36:54 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 24 Aug 2009 22:36:54 +0200 Subject: Web Services examples using "raw" xml? In-Reply-To: References: Message-ID: <7fgbv7F2l9u4oU1@mid.uni-berlin.de> John Gordon schrieb: > I'm developing a program that will use web services, which I have never > used before. > > There are several tutorials out there that advise you to get the WSDL > and then call a method (such as wsdl2py) that inspects the wsdl and > automagically generates the python classes and methods you need for > interacting with that web service. > > I've tried this, and have run into a number of roadblocks that have left > me frustrated. Welcome to the wonderful world of SOAP. If you didn't know - the S stands for simple [1]. I don't want to go into a rant about the why and how SOAP sucks, and why it's support in Python is lacking - to say the least. What we did in a similar situation was this: - got hold of a client that was able to speak with the server. In your case, a .NET-client shouldn't be hard to get working. - monitor the traffic that went on between the client and server using some HTTP-proxy or WireShark. - mimicked the server-side protocol by dynamising the sniffed traffic through an XML-templating tool, genshi in our case. Sounds archaic, and complicated? Yes. Blame SOAP (and Microsoft, it's biggest proponent) Diez [1] http://72.249.21.88/nonintersecting/2006/11/15/the-s-stands-for-simple/ From martin at v.loewis.de Mon Aug 24 16:41:37 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 24 Aug 2009 22:41:37 +0200 Subject: print() and unicode strings (python 3.1) In-Reply-To: References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> Message-ID: <4a92fb02$0$2582$9b622d9e@news.freenet.de> > I can't figure out a way to programatically set the encoding for > sys.stdout. So where does that leave me? You should be setting the terminal encoding administratively, not programmatically. Regards, Martin From not_valid at comcast.net Mon Aug 24 16:55:19 2009 From: not_valid at comcast.net (James Van Buskirk) Date: Mon, 24 Aug 2009 14:55:19 -0600 Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> <1j4y84p.v5docbtueccmN%nospam@see.signature> Message-ID: "Richard Maine" wrote in message news:1j4y84p.v5docbtueccmN%nospam at see.signature... > There might be a confusion here (and I'm not even sure on whose part) on > a picky but important detail of wording. I have seen multiple people > confused by this one before. In fact, some potential confusion was > forseen, which is why there are notes specifically about it in the > Fortran standard (see below). Those notes do tend to get overlooked > though. > Only character strings of length 1 are interoperable, as the term > "interoperable" is defined in the Fortran standard. However, that does > not mean that only character strings of length 1 will work with C. The > distinction might be picky, but it is important. > See Note 15.19 (which in turn cites an example in Note 15.23) of f2003. > You can pass a Fortran string of length n as an actual argument > corrseponding to a dummy argument that is an array of n character*1 > elements. This isn't considered a question of "interoperability", as it > is a feature purely within Fortran, but it does impact on what kinds of > things work. > One might plausibly regard this as a kludge, but it is a kludge that is > part of the Fortran standard and is guaranteed to work with all Fortran > compilers. I almost said all f2003-compliant compilers (admittedly a > limited set), but then I recalled that the feature actually dates back > to f77 when character type was introduced; f2003 just extends it to the > C character kind for the obscure case where the C character kind might > be different from the default character kind (I don't know of any > compilers where this is so, but the standard allows for it). No, this is a tricky point. It was allowed in f77 to pass an array actual argument to a scalar character dummy argument, but the ability to pass a scalar character actual argument to an array dummy argument is new to the sequence association rules of f2003. So your first impression was more accurate than the result of thoughtful reflection :) -- write(*,*) transfer((/17.392111325966148d0,6.5794487871554595D-85, & 6.0134700243160014d-154/),(/'x'/)); end From __peter__ at web.de Mon Aug 24 17:00:44 2009 From: __peter__ at web.de (Peter Otten) Date: Mon, 24 Aug 2009 23:00:44 +0200 Subject: csv module and None values References: Message-ID: JKPeck wrote: > I'm trying to get the csv module (Python 2.6) to write data records > like Excel. The excel dialect isn't doing it. The problem is in > writing None values. I want them to result in just sequential commas > - ,, but csv treats None specially, as the doc says, > > "To make it as easy as possible to interface with modules which > implement the DB API, the value None is written as the empty string." > > I need strings to be quoted but not None values. Is there any way to > get around this special None treatment? If I understand you correctly the csv.writer already does what you want: Python 2.6.2 (release26-maint, Apr 19 2009, 01:58:18) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import csv, sys >>> w = csv.writer(sys.stdout) >>> w.writerow([1,None,2]) 1,,2 just sequential commas, but that is the special treatment. Without it the the None value would be converted to a string and the line would look like this one: >>> class LooksLikeNone: ... def __str__(self): return "None" ... >>> w.writerow([1,LooksLikeNone(),2]) 1,None,2 Peter From ryniek90 at gmail.com Mon Aug 24 17:23:41 2009 From: ryniek90 at gmail.com (ryniek) Date: Mon, 24 Aug 2009 14:23:41 -0700 (PDT) Subject: Temat:, Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> <4ec18c68-b8b5-401e-b910-802b7662dced@i18g2000pro.googlegroups.com> <321b8396-0806-4a1a-9a32-efbb147e6b4b@c2g2000yqi.googlegroups.com> Message-ID: On 24 Sie, 22:34, ryniek wrote: > On 24 Sie, 16:56, John Machin wrote: > > > On Aug 25, 12:46?am, Tim Golden wrote: > > > > Dave Angel wrote: > > > > You still haven't gotten rid of those illegal colons in the filename. ? > > > > They're not legal in Windows, as has been pointed out a couple of times > > > > in this thread. > > > > Ummm.. Colons are of course legal in Windows filenames as designating > > > That is the most inappropriate "of course" I've seen for quite a > > while. > > > > the Alternate Data Streams: > > > OK, so s/illegal/evil/ > > Ok, but how to get rid of those colons? > Is it necessary? I dealt with it. Had to change 'w:bz2' into 'w|bz2'. But now have another problem: " C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje \Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba ckuper.py -f E:\APLIKACJE\nowegg.exe E:\ MyGG Checking permissions for reading and writing... Traceback (most recent call last): File "backuper.py", line 194, in main_meth() File "backuper.py", line 186, in main_meth paq.backup_file(pars.options.filename[0], pars.options.filename [1], pars.options.filename[2]) File "backuper.py", line 114, in backup_file backup_obj = tarfile.open(dest, 'w|bz2') File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib \tarfile.py", line 1675, in open _Stream(name, filemode, comptype, fileobj, bufsize), File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib \tarfile.py", line 400, in __init__ fileobj = _LowLevelFile(name, mode) File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib \tarfile.py", line 373, in __init__ self.fd = os.open(name, mode) OSError: [Errno 22] Invalid argument: 'E:\\MyGG(2009-08-24 23:18:25).tar.bz2' " When i type path with foreward slashes, Python converts them to double backslashes :P " C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje \Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python backuper.py -f E:/ APLIKACJE/nowegg.exe E:/ MyGG Checking permissions for reading and writing... Traceback (most recent call last): File "backuper.py", line 194, in main_meth() File "backuper.py", line 186, in main_meth paq.backup_file(pars.options.filename[0], pars.options.filename [1], pars.options.filename[2]) File "backuper.py", line 114, in backup_file backup_obj = tarfile.open(dest, 'w|bz2') File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib \tarfile.py", line 1675, in open _Stream(name, filemode, comptype, fileobj, bufsize), File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib \tarfile.py", line 400, in __init__ fileobj = _LowLevelFile(name, mode) File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib \tarfile.py", line 373, in __init__ self.fd = os.open(name, mode) OSError: [Errno 22] Invalid argument: 'E:\\MyGG(2009-08-24 23:20:19).tar.bz2' " I tried raw string also, but nothing helps. :-/ From van.lindberg at gmail.com Mon Aug 24 17:37:34 2009 From: van.lindberg at gmail.com (VanL) Date: Mon, 24 Aug 2009 16:37:34 -0500 Subject: Graph library recommendations for large graphs Message-ID: I am working on a project that will require building and querying large graph objects (initially 8M nodes, 30-40M edges; eventually 40M nodes, 100M edges). NetworkX seems to be the most popular, but I am concerned that a dict representation for nodes would use too much memory -- my initial tests suggest that a graph with 3M nodes and 12M edges creates substantial memory pressure on my machine. Can anybody who has worked with large graphs before give a recommendation? Thanks, Van From nospam at see.signature Mon Aug 24 17:39:32 2009 From: nospam at see.signature (Richard Maine) Date: Mon, 24 Aug 2009 14:39:32 -0700 Subject: Python/Fortran interoperability References: <1j4ww90.pvvxweehycu0N%nospam@see.signature> <5134d9f1-0e23-4e05-a817-bf0cc9e85d3e@w6g2000yqw.googlegroups.com> <760c8bce-c634-4af1-a829-efa8c2d5ed29@t13g2000yqt.googlegroups.com> <1j4y84p.v5docbtueccmN%nospam@see.signature> Message-ID: <1j4yiym.1jxu2ko10c7zucN%nospam@see.signature> James Van Buskirk wrote: > "Richard Maine" wrote in message > news:1j4y84p.v5docbtueccmN%nospam at see.signature... > > > One might plausibly regard this as a kludge, but it is a kludge that is > > part of the Fortran standard and is guaranteed to work with all Fortran > > compilers. I almost said all f2003-compliant compilers (admittedly a > > limited set), but then I recalled that the feature actually dates back > > to f77 when character type was introduced; f2003 just extends it to the > > C character kind for the obscure case where the C character kind might > > be different from the default character kind (I don't know of any > > compilers where this is so, but the standard allows for it). > > No, this is a tricky point. It was allowed in f77 to pass an array > actual argument to a scalar character dummy argument, but the ability > to pass a scalar character actual argument to an array dummy argument > is new to the sequence association rules of f2003. So your first > impression was more accurate than the result of thoughtful reflection :) Ah. You might be right - probably you are. I know there is some closely related stuff that goes back a ways and was just extended to the C character kind in f2003, but it might not have been that exact bit. I'm probably thinking of the rule for sequence association that allows the character length parameter to differ between the actual and dummy... as long as you are doing sequence association. But it might be a new rule that puts the scalar case under sequence association; that's probably it. Not worth dragging out the standards to check, but I bet that's it. -- Richard Maine | Good judgment comes from experience; email: last name at domain . net | experience comes from bad judgment. domain: summertriangle | -- Mark Twain From drobinow at gmail.com Mon Aug 24 17:43:41 2009 From: drobinow at gmail.com (David Robinow) Date: Mon, 24 Aug 2009 17:43:41 -0400 Subject: Reading binary files In-Reply-To: <9c8c445f0908240950h24e5bfccoc9ae809c1048be5d@mail.gmail.com> References: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> <1251125039.23757.0.camel@brotherus.corp.redhat.com> <9c8c445f0908240818k1ae301acr49c65ccb21435cd7@mail.gmail.com> <9c8c445f0908240950h24e5bfccoc9ae809c1048be5d@mail.gmail.com> Message-ID: <4eb0089f0908241443p348eea3dxd57581e37f94d0bd@mail.gmail.com> >> This works for a simple binary file, but the actual file I'm trying to >> read is give throwing an error that the file cannot be found. Here is the >> name of the my file: >> 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars >> >> Should python have trouble reading this file name or extension? > > I'm having trouble with the filename: > 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars > > It throws an error with that file name, When I change it to something like > sample.txt it runs, but the data is still garbled. Is there any reason why I > can't use the above file name? If I'm using 'rb' to read the binary file why > is it still garbled? I don't think it's garbled. It's a binary file. What do you expect? It's been over ten years since I've worked with any JSTARS stuff so I can't give you any details but you almost certainly have some sort of imagery. The military has a lot of bizarre formats and whoever sent you the data should have included a data sheet describing the format (or a pointer to such). Ideally, you'll also get a pointer to code to read the thing, but sometimes you just have to bite the bullet and write a program to process the file. (If all else fails, look at a dump of the first 512 bytes or so; often the image size is included at the beginning; maybe in ASCII, 16 bit ints, 32 bit ints, floating point -- who knows) There've been times when I had to just display the thing at 512 or 1024 bytes (or ints) per row and try to surmise the info from that. So, look for the file description. ... Googling a bit: I see there's a package at http://www.mbari.org/data/mbsystem/index.html which purports to handle some JSTARS stuff. I've no idea if that will help you. From pavpanchekha at gmail.com Mon Aug 24 18:07:54 2009 From: pavpanchekha at gmail.com (Pavel Panchekha) Date: Mon, 24 Aug 2009 15:07:54 -0700 (PDT) Subject: Distutils evil voodoo: install into a package Message-ID: <824505df-5534-423e-b72c-06d0f62b376b@p15g2000vbl.googlegroups.com> Before you flame me, I know that what I'm trying to do is beyond evil. But I nonetheless want to do it. Feel free to rant if you must. :) I have a package that I want to install into another package. For example, I have the packages pya and pyb. pya is guaranteed to be installed before pyb is, so that's not an issue. pya is installed as the module `pya`. I want to install pyb into the module `pya.pyb`. Is there any way to do this beyond figuring out what the path is and installing the entire pyb directory as data_files? From deets at nospam.web.de Mon Aug 24 18:21:05 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 00:21:05 +0200 Subject: Graph library recommendations for large graphs In-Reply-To: References: Message-ID: <7fgi2iF2juk72U1@mid.uni-berlin.de> VanL schrieb: > I am working on a project that will require building and querying large > graph objects (initially 8M nodes, 30-40M edges; eventually 40M nodes, > 100M edges). NetworkX seems to be the most popular, but I am concerned > that a dict representation for nodes would use too much memory -- my > initial tests suggest that a graph with 3M nodes and 12M edges creates > substantial memory pressure on my machine. > > Can anybody who has worked with large graphs before give a recommendation? My initial tests show otherwise. The below test-script creates 3 million nodes with 12 million adjacencies, on my 2GB Notebook. The theoretical limit for this (if we assume pointer-based adjacency-references which makes sense if we have sparse graphs as your numbers indicate) is (32 bits assumed): - 8 bytes per node (4 byte pointer to adjacency list, 4 byte int for counting the number of adjacencies in that list) - 4 bytes per adjacency This is 60.000.000 for your example - roughly 60MB. On my machine, the process has 320.000.000MB - (roughly) a factor five. Given the much richer properties a Python-object (and python-lists) have thas is pretty good I'd say. So for your eventual size of 40M nodes, 100M edges, we have a theoretical amount of 560MB, times 5 makes 2.5 GB. Not exactly a low memory profile, but manageable on modern hardware. I don't know anything about NetworkX - it still might be the better solution, given the underlying C-based algorithms. But if all you need is to represent a graph of that size, it appears to be working. ---- test.py ---- import random import gc import time class Node(object): __slots__ = ["adjacencies", "value", "id"] def __init__(self, id): id = id value = random.random() self.adjacencies = [] nodes = [] gc.disable() nc = 3000000 for i in xrange(nc): nodes.append(Node(i)) if (i % 1000) == 0: print i for i in xrange(12000000): a = random.randint(0, nc - 1) b = random.randint(0, nc - 1) while a == b: b = random.randint(0, nc) nodes[a].adjacencies.append(nodes[b]) if (i % 1000) == 0: print "e", i gc.enable() while True: time.sleep(1) traversed = set() def depth_search(node, depth=0): traversed.add(node) if depth == 4: return for child in node.adjacencies: if child not in traversed: depth_search(child, depth+1) depth_search(nodes[random.randint(0, nc - 1)]) ------ Diez From deets at nospam.web.de Mon Aug 24 18:22:48 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 00:22:48 +0200 Subject: Distutils evil voodoo: install into a package In-Reply-To: <824505df-5534-423e-b72c-06d0f62b376b@p15g2000vbl.googlegroups.com> References: <824505df-5534-423e-b72c-06d0f62b376b@p15g2000vbl.googlegroups.com> Message-ID: <7fgi5oF2juk72U2@mid.uni-berlin.de> Pavel Panchekha schrieb: > Before you flame me, I know that what I'm trying to do is beyond evil. > But I nonetheless want to do it. Feel free to rant if you must. :) > > I have a package that I want to install into another package. For > example, I have the packages pya and pyb. > pya is guaranteed to be installed before pyb is, so that's not an > issue. pya is installed as the module `pya`. I want to install pyb > into the module `pya.pyb`. > > Is there any way to do this beyond figuring out what the path is and > installing the entire pyb directory as data_files? This is what whe world has created namespace-packages for. At least if you can live with the namespace "pya" being otherwise empty. Pray tell - what is your usecase? Diez From bearophileHUGS at lycos.com Mon Aug 24 18:46:25 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Mon, 24 Aug 2009 15:46:25 -0700 (PDT) Subject: Graph library recommendations for large graphs References: Message-ID: You may try the Python bindings for the Boost Graph Library, the graph you talk about may fit in 2GB of a 32 bit OS too (this is the first link I have found, it's a lot of time I don't use those graph bindings): http://banyan.usc.edu/log/c_cpp/boost-graph-library-python-bindings Bye, bearophile From james.harris.1 at googlemail.com Mon Aug 24 19:23:06 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Mon, 24 Aug 2009 16:23:06 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: On 24 Aug, 14:05, Mel wrote: > James Harris wrote: > > On 24 Aug, 02:19, Max Erickson wrote: > [ ... ] > >> >>> int('100', 3) > >> 9 > >> >>> int('100', 36) > >> 1296 > > > This is fine typed into the language directly but couldn't be entered > > by the user or read-in from or written to a file. > > That's rather beside the point. ?Literals don't essentially come from files > or user input. ?Essentially literals are a subset of expressions, just like > function calls are, and they have to be evaluated by Python to yield a > value. ?I'm not averse to 32'rst', but we already have ... > >>> int ('rst', 32) > > 28573 Sure but while I wouldn't normally want to type something as obscure as 32"rst" into a file of data I might want to type 0xff00 or similar. That is far clearer than 65280 in some cases. My point was that int('ff00', 16) is OK for the programmer but cannot be used generally as it includes a function call. James From piet at cs.uu.nl Mon Aug 24 19:26:38 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 25 Aug 2009 01:26:38 +0200 Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> <4224e772-5b67-4eea-9bdf-a7d2bf7cc128@c14g2000yqm.googlegroups.com> Message-ID: >>>>> sturlamolden (s) wrote: >s> On 24 Aug, 13:21, Piet van Oostrum wrote: >>> But os.fork() is not available on Windows. And I guess refcounts et al. >>> will soon destroy the sharing. >s> Well, there is os.fork in Cygwin and SUA (SUA is the Unix subsytem in >s> Windows Vista Professional). Cygwin's fork is a bit sluggish. That's because it doesn't use copy-on-write. Thereby losing most of its advantages. I don't know SUA, but I have vaguely heard about it. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From istvan.albert at gmail.com Mon Aug 24 19:54:43 2009 From: istvan.albert at gmail.com (Istvan Albert) Date: Mon, 24 Aug 2009 16:54:43 -0700 (PDT) Subject: Graph library recommendations for large graphs References: Message-ID: <1ea9e905-e758-4c83-917b-862b63fdc8fb@p36g2000vbn.googlegroups.com> On Aug 24, 5:37?pm, VanL wrote: > > Can anybody who has worked with large graphs before give a recommendation? > when using large graphs another limitation may come from the various graph algorithm run times. Most likely you will need to squeeze out as much as possible and a python implementation has a lot of overhead. I've used the LEDA graph library with great success. This is a C++ library with substantial syntax sugar that looks a bit like python (and I made some python bindings for it via SWIG and thus got the best of both worlds, lost the code I'm afraid). http://www.algorithmic-solutions.info/leda_guide/Graphs.html i. From davea at ieee.org Mon Aug 24 20:09:10 2009 From: davea at ieee.org (Dave Angel) Date: Mon, 24 Aug 2009 20:09:10 -0400 Subject: Temat:, Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> <4ec18c68-b8b5-401e-b910-802b7662dced@i18g2000pro.googlegroups.com> <321b8396-0806-4a1a-9a32-efbb147e6b4b@c2g2000yqi.googlegroups.com> Message-ID: <4A932BA6.3090801@ieee.org> You shouldn't want either a colon or a pipe symbol in the filename string (not counting the drive letter prefix). A single colon gives you surprising behavior, and two will give you Invalid Argument. See inline responses. ryniek wrote: > On 24 Sie, 22:34, ryniek wrote: > >>> >>> >> Ok, but how to get rid of those colons? >> Is it necessary? >> > > I dealt with it. Had to change 'w:bz2' into 'w|bz2'. > > Looks to me like you're putting a pipe in again (unless that's just an artifact of the mail system) > But now have another problem: > " > C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje > \Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba > ckuper.py -f E:\APLIKACJE\nowegg.exe E:\ MyGG > Checking permissions for reading and writing... > Traceback (most recent call last): > File "backuper.py", line 194, in > main_meth() > File "backuper.py", line 186, in main_meth > paq.backup_file(pars.options.filename[0], pars.options.filename > [1], pars.options.filename[2]) > File "backuper.py", line 114, in backup_file > backup_obj =arfile.open(dest, 'w|bz2') > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib > \tarfile.py", line 1675, in open > _Stream(name, filemode, comptype, fileobj, bufsize), > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib > \tarfile.py", line 400, in __init__ > fileobj =LowLevelFile(name, mode) > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib > \tarfile.py", line 373, in __init__ > self.fd =s.open(name, mode) > OSError: [Errno 22] Invalid argument: 'E:\\MyGG(2009-08-24 > 23:18:25).tar.bz2' > " > > Still have two erroneous colons in that string. The one after the E is okay. > When i type path with foreward slashes, Python converts them to double > backslashes :P > " > C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje > \Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python backuper.py -f E:/ > APLIKACJE/nowegg.exe E:/ MyGG > Checking permissions for reading and writing... > Traceback (most recent call last): > File "backuper.py", line 194, in > main_meth() > File "backuper.py", line 186, in main_meth > paq.backup_file(pars.options.filename[0], pars.options.filename > [1], pars.options.filename[2]) > File "backuper.py", line 114, in backup_file > backup_obj =arfile.open(dest, 'w|bz2') > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib > \tarfile.py", line 1675, in open > _Stream(name, filemode, comptype, fileobj, bufsize), > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib > \tarfile.py", line 400, in __init__ > fileobj =LowLevelFile(name, mode) > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib > \tarfile.py", line 373, in __init__ > self.fd =s.open(name, mode) > OSError: [Errno 22] Invalid argument: 'E:\\MyGG(2009-08-24 > 23:20:19).tar.bz2' > " > > I tried raw string also, but nothing helps. :-/ > > If a string has a backslash in it, and it is printed, you see a single backslash. But if it is output with repr(), then you see it doubled, just as you would do if you were typing it in as a literal. That does NOT mean that it has a double backslash, it just means that particular display formatting shows you that. Try the following to see what I mean: >>> st = r"e:\testing\again.txt" >>> st 'e:\\testing\\again.txt' >>> print st e:\testing\again.txt >>> print [st, st] ['e:\\testing\\again.txt', 'e:\\testing\\again.txt'] >>> Since you don't know how a particular error message was constructed, you don't know for sure which way to interpret the results. That comes with practice. In the meantime, if you print a simple string with simple print, you should be able to see it fine. Incidentally, in nearly every case, Windows ignores extra backslashes. So that's not likely to be your problem. Get rid of those colons, without replacing them with pipes. DaveA From sturlamolden at yahoo.no Mon Aug 24 20:16:33 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 17:16:33 -0700 (PDT) Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> <4224e772-5b67-4eea-9bdf-a7d2bf7cc128@c14g2000yqm.googlegroups.com> Message-ID: <864e2d5f-0855-4f35-a78c-b09054e75f0d@w41g2000yqb.googlegroups.com> On 25 Aug, 01:26, Piet van Oostrum wrote: > That's because it doesn't use copy-on-write. Thereby losing most of its > advantages. I don't know SUA, but I have vaguely heard about it. SUA is a version of UNIX hidden inside Windows Vista and Windows 7 (except in Home and Home Premium), but very few seem to know of it. SUA (Subsystem for Unix based Applications) is formerly known as Interix, which is a certified version of UNIX based on OpenBSD. If you go to http://www.interopsystems.com (a website run by Interop Systems Inc., a company owned by Microsoft), you will find a lot of common unix tools prebuilt for SUA, including Python 2.6.2. The NT-kernel supports copy-on-write fork with a special system call (ZwCreateProcess in ntdll.dll), which is what SUA's implementation of fork() uses. From steve at REMOVE-THIS-cybersource.com.au Mon Aug 24 20:25:39 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Aug 2009 00:25:39 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> Message-ID: <02a31f91$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 16:23:06 -0700, James Harris wrote: > Sure but while I wouldn't normally want to type something as obscure as > 32"rst" into a file of data I might want to type 0xff00 or similar. That > is far clearer than 65280 in some cases. > > My point was that int('ff00', 16) is OK for the programmer but cannot be > used generally as it includes a function call. No, it's the other way around. If you have *data*, whether entered at run time by the user or read from a file, you can easily pass it to a function to convert to an int. (In fact you have to do this anyway, because the data will be a string and you need an int.) If you want your data file to have values entered in hex, or oct, or even unary (1=one, 11=two, 111=three, 1111=four...) you can. There's no need to have the user enter int('ff00', 16) to get hex, just have them enter ff00. But when writing *code*, you want syntax which will accept integers in the most common bases (decimal, a distant second hex, an even more distant third octal, and way out on the horizon binary) without the runtime cost of a function call. -- Steven From steve at REMOVE-THIS-cybersource.com.au Mon Aug 24 20:37:36 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Aug 2009 00:37:36 GMT Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <0b380152-efb5-4cee-b75e-28ff59e095fd@v20g2000yqm.googlegroups.com> <02a2b7f1$0$20629$c3e8da3@news.astraweb.com> Message-ID: <02a3225f$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 12:40:24 -0500, Derek Martin wrote: > On Mon, Aug 24, 2009 at 05:03:28PM +0000, Steven D'Aprano wrote: >> On Mon, 24 Aug 2009 11:21:46 -0500, Derek Martin wrote: >> > since the old syntax is prevalent both within and without the Python >> > community, making the change is, was, and always will be a bad idea. >> >> Octal syntax isn't prevalent *at all*, except in a small number of >> niche areas. > > Steven, don't be obtuse. Where octal is used in programming, the > leading zero is prevalent. Now who is being obtuse? If you take *any* feature at all, no matter how rare, you can say "Where it is used, it is prevalent". Among people who program in Whitespace, all three of them, the use of spaces and tabs as significant programming tokens is prevalent. This whole argument is over whether or not a "feature" desired by a tiny proportion of the programming community -- the intersection of those who use octal frequently enough that using an extra 'o' is a hardship, and those who use C-based languages -- should hold *everyone else* hostage to their badly thought out notation. [...] > Why is it so hard for you to accept that intelligent people can disagree > with you, and that what's right for you might be bad for others? I can accept that intelligent people can disagree with me. I even sympathise with you, that you're one of the minority who don't find octal archaic and unnecessary, and you'll need to learn a new syntax for octal literals in Python 3.x. But your argument is fundamentally "but we've always done it this way, and other languages do it, so why should we change?". We should change because the desire to prevent silent errors caused by (e.g.) 012 being interpreted as 10, and the desire to be consistent with both mathematical notation and floating point syntax outweighs the need to be backward compatible. This change was not a spur of the moment thing, it went through the entire PEP process with due concern for backward compatibility, which Python does *not* change without good reason. You lost, get over it. I'm sorry that you personally find this change a hardship, but HTFU. If and when you move to Python 3.x, you'll get used to it. If you can get used to putting braces around code blocks in C and braces around dicts in Python, you're more than capable of getting used to writing 012 in C and 0o12 in Python. -- Steven From greg at cosc.canterbury.ac.nz Mon Aug 24 20:54:13 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 25 Aug 2009 12:54:13 +1200 Subject: Literal concatenation, strings vs. numbers In-Reply-To: <871vn2gcai.fsf_-_@benfinney.id.au> References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <87ljlahbn9.fsf@benfinney.id.au> <7fe9mbF2l83bmU1@mid.individual.net> <871vn2gcai.fsf_-_@benfinney.id.au> Message-ID: <7fgr0nF2l3st0U1@mid.individual.net> Ben Finney wrote: > So, different representations of literals are parsed as separate > literals, then concatenated. To have the behaviour you describe, the > case needs to be made separately that digit concatenation should not be > consistent with the established string literal parsing behaviour. I think it's a pretty easy case to make, since there is no obvious way of "concatenating" numbers written in different bases. So if it's to be allowed at all, it pretty much has to be restricted to a single base. However, I'd be just as happy with underscores. I don't see how there could be any great difficulty with implementing that -- it only affects the scanner. -- Greg From mensanator at aol.com Mon Aug 24 21:01:38 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 24 Aug 2009 18:01:38 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> Message-ID: <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> On Aug 24, 7:25?pm, Steven D'Aprano wrote: > On Mon, 24 Aug 2009 16:23:06 -0700, James Harris wrote: > > Sure but while I wouldn't normally want to type something as obscure as > > 32"rst" into a file of data I might want to type 0xff00 or similar. That > > is far clearer than 65280 in some cases. > > > My point was that int('ff00', 16) is OK for the programmer but cannot be > > used generally as it includes a function call. > > No, it's the other way around. If you have *data*, whether entered at run > time by the user or read from a file, you can easily pass it to a > function to convert to an int. (In fact you have to do this anyway, > because the data will be a string and you need an int.) > > If you want your data file to have values entered in hex, or oct, or even > unary (1=one, 11=two, 111=three, 1111=four...) you can. Unary? I think you'll find that Standard Positional Number Systems are not defined for radix 1. > There's no need > to have the user enter int('ff00', 16) to get hex, just have them enter > ff00. > > But when writing *code*, you want syntax which will accept integers in > the most common bases (decimal, a distant second hex, an even more > distant third octal, and way out on the horizon binary) without the > runtime cost of a function call. > > -- > Steven From mwilson at the-wire.com Mon Aug 24 21:21:32 2009 From: mwilson at the-wire.com (Mel) Date: Mon, 24 Aug 2009 21:21:32 -0400 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> Message-ID: Mensanator wrote: [ ... ] >> If you want your data file to have values entered in hex, or oct, or even >> unary (1=one, 11=two, 111=three, 1111=four...) you can. > > Unary? I think you'll find that Standard Positional Number > Systems are not defined for radix 1. It has to be tweaked. If the only digit you have is 0 then your numbers take the form 0*1 + 0*1**2 + 0*1**3 ... and every number has an infinitely long representation. If you cheat and take a 1 digit instead then it becomes workable. Mel. From pydecker at gmail.com Mon Aug 24 21:51:42 2009 From: pydecker at gmail.com (Peter Decker) Date: Mon, 24 Aug 2009 21:51:42 -0400 Subject: Python for professsional Windows GUI apps? In-Reply-To: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> Message-ID: On Mon, Aug 24, 2009 at 11:49 AM, Stephen Hansen wrote: > P.S. I have no idea why I'm pumping Dabo so much in this though I've never > used it! I've used in fairly regularly for about 2 years now. I haven't had to write that ugly wxPython code for so long that every time I see examples on their mail list I wanna barf. Dabo is powerful, Pythonic, and strongly supported by its developers. Check it out at http://dabodev.com -- # p.d. From samwyse at gmail.com Mon Aug 24 21:53:00 2009 From: samwyse at gmail.com (samwyse) Date: Mon, 24 Aug 2009 18:53:00 -0700 (PDT) Subject: best way to display photos Message-ID: <96e9b045-d591-485e-b831-ba1462345df9@z31g2000yqd.googlegroups.com> I have several thousand photographs that I need to quickly classify, all by myself. After extensive searches, I have been unable to find anything to my liking, so desire to write something myself. I'm thinking about displaying a photo and waiting for keystrokes to tag it; 'i' for interior, 'e' for exterior, etc., while hitting space or enter will advance to the next photo. My big question is, what's the best way to display the photos. I've used PIL in the past, but IIRC it uses an external program. Pygame is the next obvious choice, but like PIL it requires an add-in. That leaves Tkinter. Has anyone used it to display .JPG files, perhaps with rescaling to fit my screen? How is its performance? Is there any other possibilities that I've missed? Thanks. From http Mon Aug 24 22:01:49 2009 From: http (Paul Rubin) Date: 24 Aug 2009 19:01:49 -0700 Subject: best way to display photos References: <96e9b045-d591-485e-b831-ba1462345df9@z31g2000yqd.googlegroups.com> Message-ID: <7x3a7gmz1u.fsf@ruckus.brouhaha.com> samwyse writes: > My big question is, what's the > best way to display the photos. I've used PIL in the past, but IIRC > it uses an external program. Pygame is the next obvious choice, but > like PIL it requires an add-in. That leaves Tkinter. Has anyone used > it to display .JPG files, perhaps with rescaling to fit my screen? I've displayed images with tkinter -- I remember there is some kind of trick you have to do to prevent them from being gc'd prematurely but I've forgotten the specifics. However, for the kind of thing you're doing, a one-off app that you don't have to impress anyone with by making it slick, the simplest thing to do is just slam together an HTML page and view it with a browser, with an entry field next to each picture, and a "submit" button. Then run a near-trivial http server that collects the form submissions and saves them to a file. From sturlamolden at yahoo.no Mon Aug 24 22:26:40 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 19:26:40 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> Message-ID: <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> On 25 Aug, 03:51, Peter Decker wrote: > I've used in fairly regularly for about 2 years now. I haven't had to > write that ugly wxPython code for so long that every time I see > examples on their mail list I wanna barf. I prefer wxFormBuilder. GUIs should be designed visually whenever possible. From afriere at yahoo.co.uk Mon Aug 24 22:29:24 2009 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 24 Aug 2009 19:29:24 -0700 (PDT) Subject: Web Services examples using "raw" xml? References: Message-ID: <115acae5-b3cb-4879-b464-80301d817018@p36g2000prn.googlegroups.com> On Aug 25, 5:41?am, John Gordon wrote: > > ? File "/usr/lib/python2.3/site-packages/suds/client.py", line 59 > ? ? @classmethod > ? ? ^ > SyntaxError: invalid syntax > If memory serves me correctly, decorators were introduced in python2.4. That would account for your SyntaxError. From rodrigodocarmo at gmail.com Mon Aug 24 22:29:57 2009 From: rodrigodocarmo at gmail.com (Rodrigo do Carmo) Date: Mon, 24 Aug 2009 23:29:57 -0300 Subject: Any Softphone wrote in Python? Message-ID: Hi python-community, I would like to ask you if someone know any open source softphone wrote entirely in Python. The thing is that I want to write a honeyphone but starting from a softphone. Sorry if you think that I haven't "googled" enough. Regards, Rodrigo. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mbezovnik at freenet.si Mon Aug 24 22:30:52 2009 From: mbezovnik at freenet.si (Matjaz Bezovnik) Date: Tue, 25 Aug 2009 04:30:52 +0200 Subject: Putting together a larger matrix from smaller matrices Message-ID: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> Dear all, I'm but a layman so do not take offence at this maybe over simple question. This is something which is done often in FEM methods, and the alike. I have matrix A of 3x3 elements, and B, of the same number of elements, 3x3. What would be the most obvious way to assemble a matrix which: a11 a12 a13 a21 a22 a23 a31 a32 a33+b11 b12 b13 b21 b22 b23 b31 b32 b33 (the missing elements = zero) (you see the pattern - if there was a third matrix C, it would "connect" to b33 on the main diagonal) Matjaz From bbxx789_05ss at yahoo.com Mon Aug 24 22:42:36 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 24 Aug 2009 19:42:36 -0700 (PDT) Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> Message-ID: On Aug 24, 2:41?pm, "Martin v. L?wis" wrote: > > I can't figure out a way to programatically set the encoding for > > sys.stdout. ?So where does that leave me? > > You should be setting the terminal encoding administratively, not > programmatically. > The terminal encoding has always been utf-8. It was not set programmatically. It seems to me that python 3.1's string handling is broken. Apparently, in python 3.1 I am unable to explicitly set the encoding of a string and print() it out with the result being human readable text. On the other hand, if I let python do the encoding implicitly, python uses a codec I don't want it to. From rylesny at gmail.com Mon Aug 24 22:48:20 2009 From: rylesny at gmail.com (ryles) Date: Mon, 24 Aug 2009 19:48:20 -0700 (PDT) Subject: Protecting against callbacks queuing up? References: <4a91db65$0$305$14726298@news.sunsite.dk> Message-ID: <18241686-02a5-4433-bd45-ba280d5705a1@r33g2000vbp.googlegroups.com> On Aug 23, 8:14?pm, Esben von Buchwald wrote: > I thought that this code would do the trick, but it obviously doesn't > help at all, and i can't understand why... > > ? ? ?def doCallback(self): > ? ? ? ? ?if self.process_busy==False: > ? ? ? ? ? ? ?self.process_busy=True > ? ? ? ? ? ? ?self.data_callback() > ? ? ? ? ? ? ?self.process_busy=False > > doCallback is defined as a callback function for the accelerometer > instance, and data_callback does some calculations and show them on the > display of the phone. > > What to do? Thanks... As Dennis pointed out, it sounds like doCallback() is called serially. That is, you can think of doCallback() as being called in a loop, rather than entered multiple times simultaneously. Your 'busy' flag is never actually checked until after it has already been reset to False. If the data accessed by the callback as a unique copy and has a timestamp then a simple approach which avoids multithreading would be to have your callback ensure that any 'old' data is simply ignored. This will allow it to quickly catch up to a 'new' event. From r1chardj0n3s at gmail.com Mon Aug 24 23:20:19 2009 From: r1chardj0n3s at gmail.com (Richard Jones) Date: Tue, 25 Aug 2009 13:20:19 +1000 Subject: Next week: the 9th PyWeek game programming challenge! Message-ID: The ninth PyWeek challenge starts this weekend, running between Sunday 30th August to Sunday 6th September (00:00UTC to 00:00UTC) The PyWeek challenge invites entrants to write a game in one week from scratch either as an individual or in a team. Entries must be developed in Python, during the challenge, and must incorporate some theme chosen at the start of the challenge. REGISTRATION IS NOW OPEN -- Visit the challenge website to sign up, join discussions in the message board or read the timetable and rules: http://www.pyweek.org/9/ PLANNING FOR THE CHALLENGE -- Make sure you have working versions of the libraries you're going to use. The rules page has a list of libraries and other resources. Make sure you can build packages to submit as your final submission (if you're going to use py2exe, make sure you know how to use it and that it works). If you don't have access to Linux, Windows or a Mac to test on, contact friends, family or other competitors to find someone who is able to test for you. From max at alcyone.com Mon Aug 24 23:20:21 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 20:20:21 -0700 Subject: Annoying octal notation In-Reply-To: <02a2b43f$0$20629$c3e8da3@news.astraweb.com> References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <20090824135648.GA20434@dragontoe.org> <02a2b43f$0$20629$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Mon, 24 Aug 2009 09:14:25 -0500, Derek Martin wrote: > >> Assuming I'm right about that, then the use of a leading 0 to represent >> octal actually predates the prevalence of using 0 in dates by almost two >> decades. And while using leading zeros in other contexts is "familiar" >> to me, I would certainly not consider it "common" by any means. Thus I >> think it's fair to say that when this syntax was selected, it was a >> rather good choice. > > Except of course to anyone familiar with mathematics in the last, oh, > five hundred years or so. Mathematics has used a positional system for > numbers for centuries now: leading zeroes have been insignificant, just > like trailing zeroes after the decimal point: > > 9 = 09 = 009 = 9.0 = 9.00 = 0009.000 etc. Trailing zeroes are quite important when you're indicating the significance of a figure. 9 is not the same as 9.0 or 9.000. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis If the sky should fall, hold up your hands. -- (a Spanish proverb) From max at alcyone.com Mon Aug 24 23:23:34 2009 From: max at alcyone.com (Erik Max Francis) Date: Mon, 24 Aug 2009 20:23:34 -0700 Subject: Temat:,Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile In-Reply-To: References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> <4ec18c68-b8b5-401e-b910-802b7662dced@i18g2000pro.googlegroups.com> <321b8396-0806-4a1a-9a32-efbb147e6b4b@c2g2000yqi.googlegroups.com> Message-ID: ryniek wrote: > On 24 Sie, 22:34, ryniek wrote: >> On 24 Sie, 16:56, John Machin wrote: >> >>> On Aug 25, 12:46 am, Tim Golden wrote: >>>> Dave Angel wrote: >>>>> You still haven't gotten rid of those illegal colons in the filename. >>>>> They're not legal in Windows, as has been pointed out a couple of times >>>>> in this thread. >>>> Ummm.. Colons are of course legal in Windows filenames as designating >>> That is the most inappropriate "of course" I've seen for quite a >>> while. >>>> the Alternate Data Streams: >>> OK, so s/illegal/evil/ >> Ok, but how to get rid of those colons? >> Is it necessary? > > I dealt with it. Had to change 'w:bz2' into 'w|bz2'. > > But now have another problem: It's the same problem, asked and answered. Why not read the replies of the people telling you what the problem is? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis If the sky should fall, hold up your hands. -- (a Spanish proverb) From apt.shansen at gmail.com Mon Aug 24 23:37:11 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Mon, 24 Aug 2009 20:37:11 -0700 Subject: print() and unicode strings (python 3.1) In-Reply-To: References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> Message-ID: <7a9c25c20908242037n41dde072h7eec82c78cd8f864@mail.gmail.com> > > > You should be setting the terminal encoding administratively, not > > programmatically. > > > > The terminal encoding has always been utf-8. It was not set > programmatically. > > It seems to me that python 3.1's string handling is broken. > Apparently, in python 3.1 I am unable to explicitly set the encoding > of a string and print() it out with the result being human readable > text. On the other hand, if I let python do the encoding implicitly, > python uses a codec I don't want it to. This isn't Python's string handling-- its the streams. The string handling is behaving precisely as it should, and you can explicitly set the encoding of any string to anything you want (as long as the data can translate). sys.stdout is a text stream: so has an explicit encoding. You can set your string to any encoding, but if you try to pass it through a text-stream which has an incompatible encoding, of course it will error out. That's the correct behavior. The problem seems to be that Python appears to be auto-detecting an encoding for your terminal (and assigning it to sys.stdout) that you think is incorrect; and it appears that this detection routine has changed (though I don't know if its the routine itself or sys.stdout being a "byte string" based object in 2.6 and a "unicode string" based object in 3.x that has caused this difference in behavior-- this is probably the case, really). How are you 'setting' your terminal encoding? Is your LC_CTYPE environment variable set to "en_US.UTF-8"? That's how Python (on nix'ses, at least, I believe) determines the encoding of the terminal and thus the sys.std(out|err) streams. If for some reason Python's detecting it wrong, the only way I know to change it would be to: import io, sys sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') HTH, --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From stephen.mc at gmail.com Mon Aug 24 23:37:19 2009 From: stephen.mc at gmail.com (Steve) Date: Mon, 24 Aug 2009 20:37:19 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: You can also use Windows Forms with IronPython http://www.ironpython.info/index.php/Contents#Windows_Forms From cmpython at gmail.com Mon Aug 24 23:37:23 2009 From: cmpython at gmail.com (Che M) Date: Mon, 24 Aug 2009 20:37:23 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: > I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), I use wxPython. No lack of controls there, and most are up to date. Which "lots" in wxWidgets are you thinking of? > I need controls for business apps like access to databases, good data > grid, Should be fine with wxPython. > printing reports (with or without barcodes), etc. Maybe ReportManager? (haven't used) or other options. -cm From pydecker at gmail.com Mon Aug 24 23:56:23 2009 From: pydecker at gmail.com (Peter Decker) Date: Mon, 24 Aug 2009 23:56:23 -0400 Subject: Python for professsional Windows GUI apps? In-Reply-To: <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: On Mon, Aug 24, 2009 at 10:26 PM, sturlamolden wrote: > On 25 Aug, 03:51, Peter Decker wrote: > >> I've used in fairly regularly for about 2 years now. I haven't had to >> write that ugly wxPython code for so long that every time I see >> examples on their mail list I wanna barf. > > I prefer wxFormBuilder. GUIs should be designed visually whenever > possible. I use the Dabo Class Designer to visually design my forms. So what's you're point? :) -- # p.d. From timr at probo.com Tue Aug 25 00:02:05 2009 From: timr at probo.com (Tim Roberts) Date: Mon, 24 Aug 2009 21:02:05 -0700 Subject: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile References: Message-ID: Ryniek90 wrote: > >Sorry, but i don't know where those pipes came from : P > >The proper path is "C:\\Users\\Ryniek's >WinSe7en\\MyNewGGBackup(2009-08-23 14:59:02).tar.bz2" >and that string literal is "\U", without any pipes :) > >The truth is that script works on linux (ubuntu) but not on windows >(neither Win7 nor WinXP). Right, and it' not going to work as long as you have a colon (:) in the file name. Colons are not valid in a Windows file name. Colons are used to separate the drive letter and the "stream" name. It's just that simple. >Maybe it's good idea to use raw string for specifing those paths? Doesn't matter. Get rid of the colons, and your file name will work. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From dmw at coder.cl Tue Aug 25 00:03:55 2009 From: dmw at coder.cl (Daniel Molina Wegener) Date: Tue, 25 Aug 2009 00:03:55 -0400 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module References: <2571343.k9db9GJWqV@coder.cl> <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> <2665032.o6QR52tnKS@coder.cl> <4a928ed7$0$32666$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1685404.FXBiJzzPRc@coder.cl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Stefan Behnel on Monday 24 August 2009 09:00 wrote in comp.lang.python: > Daniel Molina Wegener wrote: >> unicode objects are encoded into the >> encoding that the XML document encoding has, and as you say, the whole >> XML document has one encoding. There is no mixing of byte encoded strings >> with different encodings in the outout document. > > Ok, that's what I hoped anyway. It just wasn't clear from your > description. > > >> When the object is restored, by using pyxser.unserialize: >> >> pyobj = pyxser.unserialize(obj = xmldocstr, enc = "utf-8") > > But this is XML, right? What do you need to pass the encoding for at this > point? The user may want a different encoding, other than utf-8, it can be any encoding supported by libxml2. > > >> Another issue is the fact that if you have mixed some encodings in byte >> strings objects in your object tree, such as iso-8859-1 and utf-8, and >> you try to serialize that object, pyxser will output to stdout the >> serialization errors by trying to handle those mixed encodings which are >> not regarding the document encoding. > > There shouldn't be any serialisation errors (unless you try to recode byte > strings on the way out, which is a no-no for arbitrary user input). All > you have to do is properly escape the byte string so that it passes the > XML encoding step. Yup, but if the encodings are mixed inside Python byte strings, I think that there is no way to know which encoding are using them. This may cause XML serialization errors, by having a different encoding that the user have set as the document encoding. > > One trick to do that is to decode the byte string as ISO-8859-1 and > serialise the result as a normal Unicode string. Then you can re-encode > the unicode string on input back to ISO-8859-1. > > I choose ISO-8859-1 here because it has the well-defined side-effect of > mapping byte values directly to Unicode characters with an identical code > point value. So you do not risk any failures or data loss. Sure, but if there are Python byte strings (not Unicode strings), ones encoded in big5 and others in iso-8859-1 inside the object tree, the XML serialization would throw errors on the encoding conversion, by setting those bytes inside the document... > > Stefan Thanks for commenting, and sorry for the late answer. This day was busy... Best regards, - -- .O. | Daniel Molina Wegener | FreeBSD & Linux ..O | dmw [at] coder [dot] cl | Open Standards OOO | http://coder.cl/ | FOSS Developer -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (FreeBSD) iQIcBAEBCgAGBQJKk2KrAAoJEHxqfq6Y4O5N6mAQAK6a121n6ZeTl/Xm/UqlFw3S YyN0ZLY7qEgBPOz4NO3PC9DxQbo1F5/V4ZOLS86Tdc4OgRjq1dRHG2EoxzV7wQFJ yBzGTWbgyOOX1lNlnBSVLvlPooz/pBBYa0WMejUG2Sa4xDVXSXDEA5aPFy3xrYHy gj7zkWcBg3on0U+OC2l7Xdy4vIXmtTKSXMLQc01C2/yJdsNKGm2vOm8SG/gsEHo4 XYaOje3fI9WE9HUbeGrFMEnmPXpXTvodkdHY6mzRBqXws9K/ot5pz03R94boALKz MAgc/eZbPTkxViy8N98G0d4aXutNWy3cEr4B9kk6c5ZjIhmGzpSers/MrqJS+LiY t8O8d/1sT6uHQKKYOoFWCojagsDG3HFXClQyvNlqoZyj9IdN2fHNrrjmgCyeNdr3 njJNhfu7IVuZTtjwHQWscG2TVgh5slsTjEpzB/LR3V4Kt+x6Ptiy636LF7L4dqmm 7lL9dXhWRnZK7W8FzzzZDnk0qtJdsYRXsXdZ8opOqQwTnx47+HdwFClp88vbpASH YvNVn76m/Jx37WfXUXVoPDVuiQHsWDPNn3anZ60d6pDOCK9x7A065f7OCtyjq12k 2sDR1RUMBbJ0u11m7+JxIqTdcut/cJS7piiSE95vqviob4jKOQgF9y5i5eUget60 uWmCsGjI65Naxq+BWFrb =BJOF -----END PGP SIGNATURE----- From nad at acm.org Tue Aug 25 00:09:53 2009 From: nad at acm.org (Ned Deily) Date: Mon, 24 Aug 2009 21:09:53 -0700 Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> Message-ID: In article , 7stud wrote: > On Aug 24, 2:41?pm, "Martin v. L?wis" wrote: > > > I can't figure out a way to programatically set the encoding for > > > sys.stdout. ?So where does that leave me? > > > > You should be setting the terminal encoding administratively, not > > programmatically. > > > > The terminal encoding has always been utf-8. It was not set > programmatically. > > It seems to me that python 3.1's string handling is broken. > Apparently, in python 3.1 I am unable to explicitly set the encoding > of a string and print() it out with the result being human readable > text. On the other hand, if I let python do the encoding implicitly, > python uses a codec I don't want it to. If you are running on a Unix-y system, check your locale settings (LANG, LC.*, et al). I think you'll likely find that your locale is really not UTF-8. The following was on Python 3.1 on OS X 10.5, similar results on Debian Linux: $ cat t3.py import sys print(sys.stdout.encoding) s = "?" print(s.encode("utf-8")) print(s) $ export LANG=en_US.UTF-8 $ python3.1 t3.py UTF-8 b'\xe2\x82\xac' ? $ export LANG=C $ python3.1 t3.py US-ASCII b'\xe2\x82\xac' Traceback (most recent call last): File "t3.py", line 7, in print(s) UnicodeEncodeError: 'ascii' codec can't encode character '\u20ac' in position 0: ordinal not in range(128) -- Ned Deily, nad at acm.org From bbxx789_05ss at yahoo.com Tue Aug 25 00:14:44 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 24 Aug 2009 21:14:44 -0700 (PDT) Subject: best way to display photos References: <96e9b045-d591-485e-b831-ba1462345df9@z31g2000yqd.googlegroups.com> <7x3a7gmz1u.fsf@ruckus.brouhaha.com> Message-ID: <3c6c5a60-c969-4db8-8787-fb01a174249d@p10g2000prm.googlegroups.com> On Aug 24, 8:01?pm, Paul Rubin wrote: > samwyse writes: > > My big question is, what's the > > best way to display the photos. ?I've used PIL in the past, but IIRC > > it uses an external program. ?Pygame is the next obvious choice, but > > like PIL it requires an add-in. ?That leaves Tkinter. ?Has anyone used > > it to display .JPG files, perhaps with rescaling to fit my screen? > > I've displayed images with tkinter -- I remember there is some kind of > trick you have to do to prevent them from being gc'd prematurely but > I've forgotten the specifics. ? > You store the images in a list or dictionary. From gallium.arsenide at gmail.com Tue Aug 25 00:34:57 2009 From: gallium.arsenide at gmail.com (John Yeung) Date: Mon, 24 Aug 2009 21:34:57 -0700 (PDT) Subject: csv module and None values References: Message-ID: <54b4b6f9-38d5-4a8e-8ec2-fbca4a0fe1f4@r27g2000vbn.googlegroups.com> On Aug 24, 1:30?pm, JKPeck wrote: > I'm trying to get the csv module (Python 2.6) to write data > records like Excel. ?The excel dialect isn't doing it. ?The > problem is in writing None values. ?I want them to result > in just sequential commas - ,, but csv treats None specially, > as the doc says, > > "To make it as easy as possible to interface with modules > which implement the DB API, the value None is written as > the empty string." > > I need strings to be quoted but not None values. ?Is there > any way to get around this special None treatment? If you need all nonempty strings to be quoted unconditionally, then you are not writing CSV records the way Excel writes CSV records. The csv module is surprisingly good at behaving like Excel, and by default writes strings with quotes only when needed (that is, when the string itself contains commas, quotes, or newlines). If you truly want Excel-style CSVs, just let the csv module do its thing, as pointed out by Peter Otten. >From the sounds of it, you have specified QUOTE_NONNUMERIC or perhaps QUOTE_ALL as the quoting property of the dialect you are using. If so, and if this is really what you need except for *your* special None treatment, then using a sentinel is in my opinion as good a way as any to achieve that. John From wuwei23 at gmail.com Tue Aug 25 00:40:42 2009 From: wuwei23 at gmail.com (alex23) Date: Mon, 24 Aug 2009 21:40:42 -0700 (PDT) Subject: Simple IRC library References: <752884c5-c6fb-4974-a21a-bf3017fa4145@y4g2000prf.googlegroups.com> Message-ID: devaru wrote: > I am new to Python language. I want to capture(either in database or a > file) the conversation in IRC. > Please suggest me some simple IRC library or code snippet for this. I recommend the circuits[1] library, which contains a sample irc bot [2]. You'll want to override the message method to do something with the data captured. #!/usr/bin/env python from circuits import Component, Debugger from circuits.net.sockets import TCPClient, Connect from circuits.net.protocols.irc import IRC, Message, User, Nick class Bot(Component): def __init__(self, host, port=6667, channel=None): super(Bot, self).__init__(channel=channel) self += TCPClient(channel=channel) + IRC(channel=channel) self.push(Connect(host, port), "connect") def connected(self, host, port): self.push(User("test", host, host, "Test Bot"), "USER") self.push(Nick("test"), "NICK") def numeric(self, source, target, numeric, args, message): if numeric == 433: self.push(Nick("%s_" % self("getNick")), "NICK") def message(self, source, target, message): self.push(Message(source[0], message), "PRIVMSG") bot = Bot("irc.freenode.net", channel="bot") + Debugger() bot.run() [1]: http://pypi.python.org/pypi/circuits [2]: http://trac.softcircuit.com.au/circuits/browser/examples/ircbot.py From gallium.arsenide at gmail.com Tue Aug 25 00:43:57 2009 From: gallium.arsenide at gmail.com (John Yeung) Date: Mon, 24 Aug 2009 21:43:57 -0700 (PDT) Subject: csv module and None values References: Message-ID: <23c02daf-dc5a-4676-8d73-9dc63791825f@o36g2000vbl.googlegroups.com> On Aug 24, 5:00?pm, Peter Otten <__pete... at web.de> wrote: > If I understand you correctly the csv.writer already does > what you want: > > >>> w.writerow([1,None,2]) > 1,,2 > > just sequential commas, but that is the special treatment. > Without it the None value would be converted to a string > and the line would look like this one: > > 1,None,2 No, I think he means he is getting >>> w.writerow([1,None,2]) 1,"",2 He evidently wants to quote "all" strings, but doesn't want None to be considered a string. John From denis.bilenko at gmail.com Tue Aug 25 00:51:52 2009 From: denis.bilenko at gmail.com (Denis) Date: Mon, 24 Aug 2009 21:51:52 -0700 (PDT) Subject: Most "active" coroutine library project? References: <64183b73-9cb0-4ce1-98d0-f47e13a818e4@f37g2000yqn.googlegroups.com> Message-ID: You can also at gevent http://pypi.python.org/pypi/gevent On Aug 23, 10:02?pm, Phillip B Oldham wrote: > I've been taking a look at the multitude of coroutine libraries > available for Python, but from the looks of the projects they all seem > to be rather "quiet". I'd like to pick one up to use on a current > project but can't deduce which is the most popular/has the largest > community. > > Libraries I looked at include: cogen, weightless, eventlet and > circuits (which isn't exactly coroutine-based but it's event-driven > model was intriguing). > > Firstly, are there any others I've missed? And what would the > consensus be on the which has the most active community behind it? From stefan_ml at behnel.de Tue Aug 25 00:54:28 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 25 Aug 2009 06:54:28 +0200 Subject: Web Services examples using "raw" xml? In-Reply-To: References: Message-ID: <4a936e84$0$31337$9b4e6d93@newsspool4.arcor-online.net> John Gordon wrote: > I'm developing a program that will use web services, which I have never > used before. > > There are several tutorials out there that advise you to get the WSDL > and then call a method (such as wsdl2py) that inspects the wsdl and > automagically generates the python classes and methods you need for > interacting with that web service. There are a number of tools that help in building WS clients. One is soaplib. It's pretty easy to use and was recently ported (V0.8) to the lxml XML library. I actually still use a 0.7.x, also fixed to work with Py2.3. It doesn't do any code generation. Instead, you have to write up a short code snippet that describes the WS interface. Works pretty well. > I tried WSDL.Proxy() from the SOAPpy package and eventually end up > with this error: > > xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 6 Is that while parsing the WSDL file? Have you tried pushing it through an XML parser yourself (or opening it with an XML editor) to see if it really is XML? Or does this happen while communicating with the remote side? (in which case I'd trap the wire and look at the transferred XML messages) > I tried Client() from the suds package, and got this error: > > File "/usr/lib/python2.3/site-packages/suds/client.py", line 59 > @classmethod > ^ > SyntaxError: invalid syntax That's a Py2.4-ism. You can make the code backwards compatible by replacing all @classmethod def some_function(): ... lines with def some_function(): ... some_function = classmethod(some_function) That's how I fixed up soaplib, BTW. > So I decided to take a step back and see if I could bypass all the fancy > automagic methods and just create my own SOAP xml message from scratch > and then send it to the web server. That would work, surely. Yes, that's a good way also. And it avoids an additional dependency on a convoluted SOAP library. > But I'm having a tough time finding some good examples of that, because > all the tutorials I've found just tell you to use the aforementioned > magic methods, which unfortunately don;t seem to be working for me. http://effbot.org/zone/element-soap.htm Stefan From stefan_ml at behnel.de Tue Aug 25 01:11:01 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 25 Aug 2009 07:11:01 +0200 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module In-Reply-To: <1685404.FXBiJzzPRc@coder.cl> References: <2571343.k9db9GJWqV@coder.cl> <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> <2665032.o6QR52tnKS@coder.cl> <4a928ed7$0$32666$9b4e6d93@newsspool2.arcor-online.net> <1685404.FXBiJzzPRc@coder.cl> Message-ID: <4a937266$0$31337$9b4e6d93@newsspool4.arcor-online.net> Daniel Molina Wegener wrote: > Stefan Behnel wrote: >> Daniel Molina Wegener wrote: >>> When the object is restored, by using pyxser.unserialize: >>> >>> pyobj = pyxser.unserialize(obj = xmldocstr, enc = "utf-8") >> But this is XML, right? What do you need to pass the encoding for at this >> point? > > The user may want a different encoding, other than utf-8, it can > be any encoding supported by libxml2. I really meant what I wrote: this is XML. The encoding is well defined in the XML declaration at the start of the document (and will default to UTF-8 if not provided). Passing it externally will allow users to override that, which doesn't make any sense at all. > if the encodings are mixed inside Python byte strings, I think > that there is no way to know which encoding are using them. Correct. > This may cause XML serialization errors Yes, but only if you try to recode the strings (which, as I said, is a no-no). >> One trick to do that is to decode the byte string as ISO-8859-1 and >> serialise the result as a normal Unicode string. Then you can re-encode >> the unicode string on input back to ISO-8859-1. > >> I choose ISO-8859-1 here because it has the well-defined side-effect of >> mapping byte values directly to Unicode characters with an identical code >> point value. So you do not risk any failures or data loss. > > Sure, but if there are Python byte strings (not Unicode strings), ones > encoded in big5 and others in iso-8859-1 inside the object tree, the > XML serialization would throw errors on the encoding conversion, by > setting those bytes inside the document... No, I really meant: decoding from ISO-8859-1 to Unicode, for all byte strings, regardless of their encoding (since you can't even know if they represent encoded text at all). So you get a unicode string that you can serialise to the target encoding, although it may result in character references (&#xyz;) being output. But you won't get any errors, at least. On the way in, you get a unicode string again, which you can encode to ISO-8859-1 to get the original byte string back. Stefan From sturlamolden at yahoo.no Tue Aug 25 01:22:20 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Mon, 24 Aug 2009 22:22:20 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: On 25 Aug, 05:56, Peter Decker wrote: > I use the Dabo Class Designer to visually design my forms. So what's > you're point? ?:) Nothing, except lobbying for wxFormBuilder for anyone who still doesn't know of it. :) From stefan_ml at behnel.de Tue Aug 25 01:23:18 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 25 Aug 2009 07:23:18 +0200 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module In-Reply-To: <4a937266$0$31337$9b4e6d93@newsspool4.arcor-online.net> References: <2571343.k9db9GJWqV@coder.cl> <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> <2665032.o6QR52tnKS@coder.cl> <4a928ed7$0$32666$9b4e6d93@newsspool2.arcor-online.net> <1685404.FXBiJzzPRc@coder.cl> <4a937266$0$31337$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <4a937546$0$31332$9b4e6d93@newsspool4.arcor-online.net> Stefan Behnel wrote: > for all byte > strings, regardless of their encoding (since you can't even know if they > represent encoded text at all). Hmm, having written that, I guess it's actually best to encode byte strings as base64 instead. Otherwise, null bytes and other special byte values won't pass. I also think that if the user wants readable output for text strings, it's reasonable to require Unicode input instead of byte strings. Handling text in byte strings is just too error prone. Still, you may have to sanitize text input to make sure it doesn't contain special characters either. Take a look at the way lxml does it in the apihelpers.pxi source file, or read the XML spec on character content. Stefan From mensanator at aol.com Tue Aug 25 01:27:51 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 24 Aug 2009 22:27:51 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> Message-ID: <4468c5f5-435f-48aa-a259-7ab51069d1f7@24g2000yqm.googlegroups.com> On Aug 24, 8:21?pm, Mel wrote: > Mensanator wrote: > > [ ... ] > > >> If you want your data file to have values entered in hex, or oct, or even > >> unary (1=one, 11=two, 111=three, 1111=four...) you can. > > > Unary? I think you'll find that Standard Positional Number > > Systems are not defined for radix 1. > > It has to be tweaked. ?If the only digit you have is 0 then your numbers > take the form > > 0*1 + 0*1**2 + 0*1**3 ... > > and every number has an infinitely long representation. ?If you cheat and > take a 1 digit instead then it becomes workable. Not really. If your single digit is one, you still have an infinitely long representation only instead of every position being zero, every position is one. So either the only number that can be represented is 0, or the only number that can be represented is infinity. No amount of tweaking can fix this. So, to use radix 1, you have to abandon the concept of "Standard" (contains a 0) AND abandon "Positional" (infinitely long representation). It's all in TAOCP by Knuth if you want to get it straight. You can have a radix 1 number system, but is meaningless to speak of "unary" in the same context as hex, decimal, octal & binary. > > ? ? ? ? Mel. From spam at chezmarshall.freeserve.co.uk Tue Aug 25 01:44:28 2009 From: spam at chezmarshall.freeserve.co.uk (Robert Marshall) Date: Tue, 25 Aug 2009 06:44:28 +0100 Subject: your favorite debugging tool? References: <7xocq5vx64.fsf@ruckus.brouhaha.com> Message-ID: On 24 Aug 2009, Paul Rubin wrote: > Esmail writes: >> What is your favorite tool to help you debug your >> code? I've been getting along with 'print' statements >> but that is getting old and somewhat cumbersome. > > Beyond print statements, I use pdb a lot. Winpdb (www.winpdb.org) is > even better, but is kind of cumbersome to get working. And you can run it (pdb) within emacs - though I find a little roughness in working out the exact interactions keeps ending up (ie the source buffer displayed) in the wrong stack frame - afaict Robert -- La grenouille songe..dans son ch?teau d'eau Links and things http://rmstar.blogspot.com/ From mensanator at aol.com Tue Aug 25 02:01:30 2009 From: mensanator at aol.com (Mensanator) Date: Mon, 24 Aug 2009 23:01:30 -0700 (PDT) Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <20090823031901.GX20434@dragontoe.org> <87fxbifzb7.fsf@golux.woodcraft.me.uk> <20090824135648.GA20434@dragontoe.org> <02a2b43f$0$20629$c3e8da3@news.astraweb.com> Message-ID: On Aug 24, 10:20?pm, Erik Max Francis wrote: > Steven D'Aprano wrote: > > On Mon, 24 Aug 2009 09:14:25 -0500, Derek Martin wrote: > > >> Assuming I'm right about that, then the use of a leading 0 to represent > >> octal actually predates the prevalence of using 0 in dates by almost two > >> decades. ?And while using leading zeros in other contexts is "familiar" > >> to me, I would certainly not consider it "common" by any means. ?Thus I > >> think it's fair to say that when this syntax was selected, it was a > >> rather good choice. > > > Except of course to anyone familiar with mathematics in the last, oh, > > five hundred years or so. Mathematics has used a positional system for > > numbers for centuries now: leading zeroes have been insignificant, just > > like trailing zeroes after the decimal point: > > > 9 = 09 = 009 = 9.0 = 9.00 = 0009.000 etc. > > Trailing zeroes are quite important when you're indicating the > significance of a figure. ?9 is not the same as 9.0 or 9.000. Tell me about it. Unfortunnately, Microsoft doesn't understand the difference between precision and significance. Makes my job a nightmare when I have to convert ug/kg to mg/kg. > > -- > Erik Max Francis && m... at alcyone.com &&http://www.alcyone.com/max/ > ? San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis > ? ?If the sky should fall, hold up your hands. > ? ? -- (a Spanish proverb)- Hide quoted text - > > - Show quoted text - From hv at tbz-pariv.de Tue Aug 25 02:40:56 2009 From: hv at tbz-pariv.de (Thomas Guettler) Date: Tue, 25 Aug 2009 08:40:56 +0200 Subject: best way to display photos In-Reply-To: <96e9b045-d591-485e-b831-ba1462345df9@z31g2000yqd.googlegroups.com> References: <96e9b045-d591-485e-b831-ba1462345df9@z31g2000yqd.googlegroups.com> Message-ID: <7fhfboF2ksfhiU1@mid.individual.net> Some years ago I had the same problem. I wrote a simple app with pygtk. You get get it from here: http://guettli.sourceforge.net/gthumpy/src/README.html The next pictures get loaded in background. Switching from one image to the next is faster then in some other apps. But somehow it is not ready for the public. I guess I am the only one who uses it. Flags are symlinks in the home directory .local/share/app/gthumpy. This means you should not move your images, otherwise the flags get lost. I don't think it will work on ms-windows, but it could be ported. Or you use mirage: http://mirageiv.berlios.de/index.html It is a pygtk image viewer. You can define shortcuts that execute user defined commands. Thomas samwyse schrieb: > I have several thousand photographs that I need to quickly classify, > all by myself. After extensive searches, I have been unable to find > anything to my liking, so desire to write something myself. I'm > thinking about displaying a photo and waiting for keystrokes to tag > it; 'i' for interior, 'e' for exterior, etc., while hitting space or > enter will advance to the next photo. My big question is, what's the > best way to display the photos. I've used PIL in the past, but IIRC > it uses an external program. Pygame is the next obvious choice, but > like PIL it requires an add-in. That leaves Tkinter. Has anyone used > it to display .JPG files, perhaps with rescaling to fit my screen? > How is its performance? Is there any other possibilities that I've > missed? Thanks. -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From sjmachin at lexicon.net Tue Aug 25 02:54:36 2009 From: sjmachin at lexicon.net (John Machin) Date: Mon, 24 Aug 2009 23:54:36 -0700 (PDT) Subject: Python 2.6 still not giving memory back to the OS... References: <38581c40-b7ed-4dbf-a3af-33e1761ba7b0@r7g2000yqj.googlegroups.com> <762603ba-0a4c-4504-94d9-34a8b1e3f9c3@s15g2000yqs.googlegroups.com> <4A88406C.3060609@v.loewis.de> Message-ID: <64ac5a03-ebf2-4a78-8ada-9e2dc46c86ac@d9g2000prh.googlegroups.com> On Aug 25, 2:08?am, Chris Withers wrote: > Martin v. L?wis wrote: > > Today, there are two cases when malloc returns memory on a typical > > Unix system (in particular, in Linux malloc): > > a) if the malloc block block is small (below page size), it is allocated > > ? ?from the brk heap, where it can only be returned if the last page of > > ? ?that heap is completely free, and > > b) if the block is large (multiple pages), it gets returned to the > > ? ?system right away. > > > Case b) can only happen if the C malloc uses mmap to allocate large > > blocks. > > I believe (and John will correct me if I'm wrong) that xlrd uses mmap, > so why am I not seeing the memory being returned? xlrd uses mmap to access the input file; this seems to have zero correlation with "the C malloc uses mmap to allocate large blocks". From nadia.helen.johnson at gmail.com Tue Aug 25 03:12:57 2009 From: nadia.helen.johnson at gmail.com (Nadia Johnson) Date: Tue, 25 Aug 2009 00:12:57 -0700 (PDT) Subject: elementtree References: <3037e686-d552-4373-a822-75a43b274cca@t11g2000prh.googlegroups.com> <4a923d8b$0$32664$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <2b3279b4-ed91-4d46-823a-1bf89acf33fb@j9g2000prh.googlegroups.com> On Aug 24, 7:29?pm, Dave Angel wrote: > Stefan Behnel wrote: > > Hi, > > > elsa wrote: > > >> I know how to turn HTML into an ElementTree object > > > I don't. ;) > > > ElementTree doesn't have an HTML parser, so what do you use for parsing? > > >> but I don't know > >> how to then view the structure of this object. Is there a method or > >> module that you can give an ElementTree object to, and it returns some > >> kind of graphical or printed representation of the tree? Otherwise, if > >> you can't see you're tree's structure, how do you know what is a > >> sensible way of iterating over the tree to access the info you need? > > > ElementTree has a tostring() method that returns a string. To get a pretty > > printed representation, you can use the indent() function from this recipe: > > >http://effbot.org/zone/element-lib.htm#prettyprint > > > Stefan > > Perhaps the OP was referring to XHTML, which should be eligible for > ElementTree. ?But could you tell me whether ElementTree is at all > tolerant of malformed XML? ? Most HTML and XHTML I encounter in the wild > is so ?buggy it's amazing it all works at all. > > DaveA I used elementtidy, also available from effbot From dirkmoors at gmail.com Tue Aug 25 03:54:34 2009 From: dirkmoors at gmail.com (gravityzoo-dmo) Date: Tue, 25 Aug 2009 00:54:34 -0700 (PDT) Subject: Python memory management <-> virtualized server environments References: Message-ID: <5773f2ee-5654-4f82-82c5-7668eb419f36@w41g2000yqb.googlegroups.com> On 24 aug, 20:35, "Martin P. Hellwig" wrote: > gravityzoo-dmo wrote: > > Hello everyone, > > > I was wondering if anyone here has had any experience in running > > Python in a virtualized server environment? > > The reason I'm asking is the recent thing I noticed when running my > > server application (written in Python + Twisted); > > The memory of the server application seems to only grow, and not give > > back memory space to the OS. I realize that this won't be a problem on > > a single physical server, but I'm curious of the effect this behaviour > > has on a virtualized environment. > > Could anyone provide me with a little more insight please? > > Thanks in advance! > > > Dirk > > Might help if you say which version of Python you are running, although > I'm not a memory expert I do know there have been some changes between > the versions. > > -- > MPHhttp://blog.dcuktec.com > 'If consumed, best digested with added seasoning to own preference.' Hi, I'm sorry, I forgot to post the version indeed. The Python version I'm running is 2.5.2 (r252:60911, January 4 2009) The Twisted version I'm running is 8.2.0, and I'm using the EPOLL- Reactor (don't know if that matters) The OS I'm running on is Debian version 2.6.26-2-686 (i686 GNU/Linux) Is that enough info? Best regards, Dirk From __peter__ at web.de Tue Aug 25 04:03:57 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Aug 2009 10:03:57 +0200 Subject: Putting together a larger matrix from smaller matrices References: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> Message-ID: Matjaz Bezovnik wrote: > This is something which is done often in FEM methods, and the alike. > > I have matrix A of 3x3 elements, and B, of the same number of > elements, 3x3. > > What would be the most obvious way to assemble a matrix which: > a11 a12 a13 > a21 a22 a23 > a31 a32 a33+b11 b12 b13 > b21 b22 b23 > b31 b32 b33 > > (the missing elements = zero) > > (you see the pattern - if there was a third matrix C, it would > "connect" to b33 on the main diagonal) Unless there is a dedicated function: partial = [...] # list of matrices of shape NxN N = partial[0].shape[0] width = N*len(partial) b = numpy.zeros((width, width)) off = 0 for m in partial: b[off:off+N, off:off+N] = m off += N print b Peter From martin.hellwig at dcuktec.org Tue Aug 25 04:09:06 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 25 Aug 2009 09:09:06 +0100 Subject: Python memory management <-> virtualized server environments In-Reply-To: <5773f2ee-5654-4f82-82c5-7668eb419f36@w41g2000yqb.googlegroups.com> References: <5773f2ee-5654-4f82-82c5-7668eb419f36@w41g2000yqb.googlegroups.com> Message-ID: <3oSdnePt4Mu_AQ7XnZ2dnUVZ8j9i4p2d@bt.com> gravityzoo-dmo wrote: > On 24 aug, 20:35, "Martin P. Hellwig" > wrote: >> gravityzoo-dmo wrote: >>> Hello everyone, >>> I was wondering if anyone here has had any experience in running >>> Python in a virtualized server environment? >>> The reason I'm asking is the recent thing I noticed when running my >>> server application (written in Python + Twisted); >>> The memory of the server application seems to only grow, and not give >>> back memory space to the OS. I realize that this won't be a problem on >>> a single physical server, but I'm curious of the effect this behaviour >>> has on a virtualized environment. >>> Could anyone provide me with a little more insight please? >>> Thanks in advance! >>> Dirk >> Might help if you say which version of Python you are running, although >> I'm not a memory expert I do know there have been some changes between >> the versions. >> >> -- >> MPHhttp://blog.dcuktec.com >> 'If consumed, best digested with added seasoning to own preference.' > > Hi, I'm sorry, I forgot to post the version indeed. > > The Python version I'm running is 2.5.2 (r252:60911, January 4 2009) > The Twisted version I'm running is 8.2.0, and I'm using the EPOLL- > Reactor (don't know if that matters) > The OS I'm running on is Debian version 2.6.26-2-686 (i686 GNU/Linux) > > Is that enough info? > > Best regards, > Dirk According to Python 2.6 release document: "To reduce memory usage, the garbage collector will now clear internal free lists when garbage-collecting the highest generation of objects. This may return memory to the operating system sooner." Which might apply to your situation, but to be really sure you can only try it out :-) -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From pierre.gaillard at gmail.com Tue Aug 25 04:12:51 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Tue, 25 Aug 2009 01:12:51 -0700 (PDT) Subject: matplotlib / backend Message-ID: <5c24850b-462f-4d2e-9d75-e9317c093e5e@z31g2000yqd.googlegroups.com> Hello, I'm to plot some results but it doesn't work. I got this error : /usr/local/libre_rep/python-2.6.1/RHEL_5__x86_64/lib/python2.6/site- packages/matplotlib/backends/__init__.py:41: UserWarning: Your currently selected backend, 'agg' does not support show(). Please select a GUI backend in your matplotlibrc file ('/usr/local/ libre_rep/python-2.6.1/RHEL_5__x86_64/lib/python2.6/site-packages/ matplotlib/mpldata/matplotlibrc') or with matplotlib.use() Any idea to fix it ? Thanks From james.harris.1 at googlemail.com Tue Aug 25 04:22:29 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Tue, 25 Aug 2009 01:22:29 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> Message-ID: <68540205-9970-41a2-b0b0-7b66a9865c9b@s15g2000yqs.googlegroups.com> On 25 Aug, 01:25, Steven D'Aprano wrote: > On Mon, 24 Aug 2009 16:23:06 -0700, James Harris wrote: > > Sure but while I wouldn't normally want to type something as obscure as > > 32"rst" into a file of data I might want to type 0xff00 or similar. That > > is far clearer than 65280 in some cases. > > > My point was that int('ff00', 16) is OK for the programmer but cannot be > > used generally as it includes a function call. > > No, it's the other way around. If you have *data*, whether entered at run > time by the user or read from a file, you can easily pass it to a > function to convert to an int. (In fact you have to do this anyway, > because the data will be a string and you need an int.) > > If you want your data file to have values entered in hex, or oct, or even You are looking at this the other way round from me and I'll explain why I think this is important. I'm not talking about the *programmer* prescribing how the user should enter the data but the *user* being able to choose to prepare the data in a certain format - the format which makes sense for the data being entered. Your way only works if those fields in every row have the same format. That may be the case sometimes but is not general. > unary (1=one, 11=two, 111=three, 1111=four...) you can. There's no need > to have the user enter int('ff00', 16) to get hex, just have them enter > ff00. > > But when writing *code*, you want syntax which will accept integers in > the most common bases (decimal, a distant second hex, an even more > distant third octal, and way out on the horizon binary) without the > runtime cost of a function call. Be careful! When designing a language feature don't be too ready to *tell* the users of that language what restrictions they want. Just because the designer wants features with a certain frequency does not mean that all users will have the same priorities. (If it is impossible or unreasonable to support a feature then by all means don't support it. But don't decide up-front before examining the options that something in not personally appealing.) James From hendrik at microcorp.co.za Tue Aug 25 04:28:11 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 25 Aug 2009 10:28:11 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a92b290$0$305$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a92b290$0$305$14726298@news.sunsite.dk> Message-ID: <200908251028.12047.hendrik@microcorp.co.za> On Monday 24 August 2009 17:32:23 Esben von Buchwald wrote: > Hendrik van Rooyen wrote: 8< -------------- some stuff about an "after" call -------------------------- > > I'm new to python, what is an after function and an after call? Couldn't > find excact answer on google...? Do you have a link to some docs? The after call is common in GUI stuff. Here is a link to nice Tkinter manual - it is the first link if you google for: tkinter "new mexico tech" shipman www.nmt.edu/tcc/help/pubs/tkinter/ What after does is that it is like a normal call, except that it is not done immediately, but after some settable time, hence the "after". - Hendrik From thebiggestbangtheory at gmail.com Tue Aug 25 04:36:08 2009 From: thebiggestbangtheory at gmail.com (nickname) Date: Tue, 25 Aug 2009 01:36:08 -0700 (PDT) Subject: os.popen output different from native shell output Message-ID: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Hi all, I am a relative newbie to python, I am using os.popen to run an ls command. The output that I get using the read() function is different in look and feel from when I run the ls command natively from the shell (not via python). I display the ouput via python by using the print function on the variable that accepts the os.popen ().read() function. For example: output from native shell (as seen on the bash shell) file1 file2 dir1(highlighted in blue color) file3longnamewhichwillcausenextfiletoappearonnextline file 4 output from python (as seen on the bash shell) file1 file2 dir1 (no blue color) file3longnamewhichwillcausenextfiletoappearonnextline file4 Is there an easy way to "mirror" the output. When python displays the output, how can it tell the bash shell that some of the entries are directories and they should appear blue on the bash shell, and that everything should not be appearing on 1 column only. Thanks for any pointers. From clp2 at rebertia.com Tue Aug 25 04:52:55 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 25 Aug 2009 01:52:55 -0700 Subject: os.popen output different from native shell output In-Reply-To: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Message-ID: <50697b2c0908250152y4e6a7fb8ke20f9aae28193b40@mail.gmail.com> On Tue, Aug 25, 2009 at 1:36 AM, nickname wrote: > Hi all, > ? ? ? I am a relative newbie to python, I am using os.popen to run an > ls command. The output that I get using the read() function is > different in look and feel from when I run the ls command natively > from the shell (not via python). I display the ouput via python by > using the print function on the variable that accepts the os.popen > ().read() function. > > For example: > > output from native shell (as seen on the bash shell) > > file1 file2 dir1(highlighted in blue color) > file3longnamewhichwillcausenextfiletoappearonnextline > > file 4 > > output from python (as seen on the bash shell) > > file1 > file2 > dir1 (no blue color) > file3longnamewhichwillcausenextfiletoappearonnextline > file4 > > Is there an easy way to "mirror" the output. When python displays the > output, how can it tell the bash shell that some of the entries are > directories and they should appear blue on the bash shell, and that > everything should not be appearing on 1 column only. I would assume the difference is caused by `ls` changing behavior (for example, enabling/disabling colorization) based on whether its output is going to a terminal or a pipe. Is there a reason you can't use os.listdir() instead of running ls?: http://docs.python.org/library/os.html#os.listdir For the colorization, google for "ANSI color escape sequences" Cheers, Chris -- http://blog.rebertia.com From subhakolkata1234 at gmail.com Tue Aug 25 05:08:31 2009 From: subhakolkata1234 at gmail.com (SUBHABRATA BANERJEE) Date: Tue, 25 Aug 2009 14:38:31 +0530 Subject: Questions on XML In-Reply-To: <200908231148.51151.rami.chowdhury@gmail.com> References: <51b22a8c-54de-484e-9b3c-9baeb4498f69@q40g2000prh.googlegroups.com> <97c638a50908221327ge57818ahc1bb4c9ad3eb186b@mail.gmail.com> <200908231148.51151.rami.chowdhury@gmail.com> Message-ID: <97c638a50908250208n3a81007n92b7507ca8515bf2@mail.gmail.com> I was trying this. Looks perfectly fine. There must be something really wrong. If you can reinstall Python 2.5. >>> a1=raw_input("String") String?? On Mon, Aug 24, 2009 at 12:18 AM, Rami Chowdhury wrote: > My problem is with IDLE on Windows. When I try to type Bangla directly into > the IDLE window I only get '?' characters, and repr() fails with a > UnicodeDecodeError. I expect, though, that that's because of my specific > installation / Windows issues, as it works fine on Fedora 10... > > > I do not get any problem in processing Hindi or Bangla or any Indian > > language in Python it is perfectly fine. > I have no problems either -- my issues are with IDLE, and only on Windows. > > ---- > Rami Chowdhury > "Strangers are just friends who haven't had enough gin." -- Howdle's Saying > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > > On Saturday 22 August 2009 13:27:02 SUBHABRATA BANERJEE wrote: > > Should I help you? If you answered my questions I am differing from your > > view I do not get any problem in processing Hindi or Bangla or any Indian > > language in Python it is perfectly fine. > > Best Regards, > > Subhabrata. > > > > On Sat, Aug 22, 2009 at 9:48 AM, Rami Chowdhury > wrote: > > > I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > > > > > >> use Python to help me in this regard? > > > > > > I can say from experience that Python on Windows (at least, Python 2.5 > on > > > 32-bit Vista) works perfectly well with UTF-8 files containing Bangla. > I > > > have had trouble with working with the data in IDLE, however, which > seems > > > to prefer ASCII by default. > > > > > > ------------- > > > Rami Chowdhury > > > "Never assume malice when stupidity will suffice." -- Hanlon's Razor > > > 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) > > > > > > > > > > > > > > > > > > On Aug 21, 2009, at 19:15 , joy99 wrote: > > > > > > Dear Group, > > > > > >> I like to convert some simple strings of natural language to XML. May > > >> I use Python to do this? If any one can help me, on this. > > >> > > >> I am using primarily UTF-8 based strings, like Hindi or Bengali. Can I > > >> use Python to help me in this regard? > > >> > > >> How can I learn good XML aspects of Python. If any one can kindly name > > >> me a book or URL. > > >> > > >> I am using Python2.6 on Windows XP with IDLE as GUI. > > >> > > >> Best Regards, > > >> Subhabrata. > > >> -- > > >> http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From baloand at googlemail.com Tue Aug 25 05:52:45 2009 From: baloand at googlemail.com (baloan) Date: Tue, 25 Aug 2009 02:52:45 -0700 (PDT) Subject: matplotlib / backend References: <5c24850b-462f-4d2e-9d75-e9317c093e5e@z31g2000yqd.googlegroups.com> Message-ID: <5480dbe7-d9cc-44fb-a6cb-b866c01cd545@o6g2000yqj.googlegroups.com> On Aug 25, 10:12?am, Pierre wrote: > Hello, > > I'm to plot some results but it doesn't work. > I got this error : > > /usr/local/libre_rep/python-2.6.1/RHEL_5__x86_64/lib/python2.6/site- > packages/matplotlib/backends/__init__.py:41: UserWarning: > Your currently selected backend, 'agg' does not support show(). > Please select a GUI backend in your matplotlibrc file ('/usr/local/ > libre_rep/python-2.6.1/RHEL_5__x86_64/lib/python2.6/site-packages/ > matplotlib/mpldata/matplotlibrc') > or with matplotlib.use() > > Any idea to fix it ? > > Thanks Try: import matplotlib matplotlib.use('TkAgg') before coding anything else from the examples section of the matplotlib documentation http://matplotlib.sourceforge.net/examples/user_interfaces/embedding_in_tk.html From hv at tbz-pariv.de Tue Aug 25 06:18:59 2009 From: hv at tbz-pariv.de (Thomas Guettler) Date: Tue, 25 Aug 2009 12:18:59 +0200 Subject: os.popen output different from native shell output In-Reply-To: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Message-ID: <7fhs4jF2b5i5pU1@mid.individual.net> hi, you get the popen output like this: user at unixhost> ls | cat nickname schrieb: > Hi all, > I am a relative newbie to python, I am using os.popen to run an > ls command. The output that I get using the read() function is > different in look and feel from when I run the ls command natively > from the shell (not via python). I display the ouput via python by > using the print function on the variable that accepts the os.popen > ().read() function. ... Thomas -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From michele.simionato at gmail.com Tue Aug 25 06:28:44 2009 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 25 Aug 2009 03:28:44 -0700 (PDT) Subject: your favorite debugging tool? References: Message-ID: <57d65219-8134-4c2e-9739-825a5ef450d0@s15g2000yqs.googlegroups.com> On Aug 22, 4:25?pm, Esmail wrote: > Hi all, > > What is your favorite tool to help you debug your > code? The times when I would just use 'print' are long past. Nowadays I spend lots of my time with code written by others than myself. I use pdb all the time, and now also ipdb (ipdb is very cool if you are used to ipython). M.S. From bbxx789_05ss at yahoo.com Tue Aug 25 06:41:54 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 25 Aug 2009 03:41:54 -0700 (PDT) Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> Message-ID: <84154e6e-c425-4b71-89e3-7d2877a19418@m7g2000prd.googlegroups.com> On Aug 24, 10:09 pm, Ned Deily wrote: > In article > , > > > > 7stud wrote: > > On Aug 24, 2:41 pm, "Martin v. L?wis" wrote: > > > > I can't figure out a way to programatically set the encoding for > > > > sys.stdout. So where does that leave me? > > > > You should be setting the terminal encoding administratively, not > > > programmatically. > > > The terminal encoding has always been utf-8. It was not set > > programmatically. > > > It seems to me that python 3.1's string handling is broken. > > Apparently, in python 3.1 I am unable to explicitly set the encoding > > of a string and print() it out with the result being human readable > > text. On the other hand, if I let python do the encoding implicitly, > > python uses a codec I don't want it to. > > If you are running on a Unix-y system, check your locale settings (LANG, > LC.*, et al). I think you'll likely find that your locale is really not > UTF-8. The following was on Python 3.1 on OS X 10.5, similar results > on Debian Linux: > > $ cat t3.py > import sys > print(sys.stdout.encoding) > s = "?" > print(s.encode("utf-8")) > print(s) > > $ export LANG=en_US.UTF-8 > $ python3.1 t3.py > UTF-8 > b'\xe2\x82\xac' > ? > > $ export LANG=C > $ python3.1 t3.py > US-ASCII > b'\xe2\x82\xac' > Traceback (most recent call last): > File "t3.py", line 7, in > print(s) > UnicodeEncodeError: 'ascii' codec can't encode character '\u20ac' in > position 0: ordinal not in range(128) > > -- > Ned Deily, > n... at acm.org Hi, Thanks for the response. My OS is mac osx 10.4.11. I'm not really sure how to check my locale settings. Here is some stuff I tried: $ echo $LANG $ echo $LC_ALL $ echo $LC_CTYPE $ locale LANG= LC_COLLATE="C" LC_CTYPE="C" LC_MESSAGES="C" LC_MONETARY="C" LC_NUMERIC="C" LC_TIME="C" LC_ALL="C" $man locale ... ... ... ENVIRONMENT: LANG Used as a substitute for any unset LC_* variable. If LANG is unset it will act as if set to "C". If any of LANG or LC_* are set to invalide values locale acts as if they are all unset. =========== As in your last example, my 'C' settings mean that an ascii codec is used somewhere to encode() the unicode string. -- The locale C or POSIX is a portable locale; its LC_CTYPE part corresponds to the 7-bit ASCII character set. http://linux.about.com/library/cmd/blcmdl3_setlocale.htm -- Is this the way it works: 1) python sets the codec for sys.stdout to the LANG environment variable. 2) It doesn't matter that my terminal's encoding is set to utf-8 because output has to pass through sys.stdout first. So: a) My terminal's environment is telling python(and all other programs running in the terminal) that output sent to sys.stdout must be encoded in ascii. b) The solution is to set a LANG environment variable. Why does echoing $LC_ALL or $LC_CTYPE just give me a blank string? Previously, I've set environment variables that I want to be permanent, e.g PATH, in ~/.bash_profile, so I did this: ~/.bash_profile: -------------- ... ... LANG="en_US.UTF-8" export LANG and now python 3.1 acts like I expect it to: ------- import locale import sys print(locale.getlocale(locale.LC_CTYPE)) print(sys.stdout.encoding) s = "?" print(s) print(s.encode("utf-8")) --output:-- ('en_US', 'UTF8') UTF-8 ? b'\xe2\x82\xac' ---------- In conclusion, as far as I can tell, if your python 3.1 program tries to output a unicode string, and the unicode string cannot be encoded by the codec specified in the user's LANG environment variable**, then the user will get an encode error. Just because the programmer's system can handle the output doesn't mean that another user's system can. I guess that's the way it goes: if a user's environment is telling all programs that it only wants ascii output to go to the screen(sys.stdout), you can't(or shouldn't) do anything about it. **Or if the LANG environment variable is not present, then the codec corresponding to the locale settings(C' corresponds to ascii). some good locale info: http://www.chemie.fu-berlin.de/chemnet/use/info/libc/libc_19.html From bbarbero at inescporto.pt Tue Aug 25 06:57:07 2009 From: bbarbero at inescporto.pt (bbarbero at inescporto.pt) Date: Tue, 25 Aug 2009 12:57:07 +0200 Subject: unexpected token `;' Message-ID: <20090825125707.96162cpxx4xdaglf@horde.inescporto.pt> Hello to all! I am struggling with a script in python for a while now, and decided to look for some help. I am running a code that takes commands from Marsyas(open source for Music analysis). #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 #!/bin/bashimport math import re import numpy import string import os.path import sys import commands l = "/Users/bmorab/Audio_Projecto/Data/Palco/PP3_44_distance_matrix/PP3_44_5.mf" Col = open(l, 'r') colist= [] songlist = [] for line in Col: #print line song = os.path.split(line)[1] #print song songlist.append(song) colist.append(line) cmd = "sfplay " + colist[2] print cmd fileout = commands.getoutput(cmd) print fileout It basically reads song files from the .mf file, stores them in a list and play one of the songs from the list. It does work with some music but mostly it gives an error like this: sfplay /Volumes/HAL/Datasets/Audio/PalcoPrincipal/mp3_resampled_44100/10005.mp3 sh: -c: line 1: syntax error near unexpected token `;' sh: -c: line 1: `; } 2>&1' Ive been searching for the meaning of the error, and It really depends on the script, but I would conclude that I am missing a punctuation mark?? Thank you very much for taking your time reading my request. Looking forward to hearing from you. Regards, Bea ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From mmelchert03 at yahoo.com Tue Aug 25 07:24:37 2009 From: mmelchert03 at yahoo.com (mmelchert) Date: Tue, 25 Aug 2009 13:24:37 +0200 Subject: unexpected token `;' References: Message-ID: <4a93c9f6$0$2370$9b622d9e@news.freenet.de> bbarbero at inescporto.pt wrote: > Hello to all! > > I am struggling with a script in python for a while now, and decided > to look for some help. I am running a code that takes commands from > Marsyas(open source for Music analysis). > > #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 > #!/bin/bashimport math <<== > import re > import numpy have a close look at the <<== line: I think you wanted it to read import math rather than #!/bin/bashimport math? From aotto1968 at users.sourceforge.net Tue Aug 25 07:24:37 2009 From: aotto1968 at users.sourceforge.net (Andreas Otto) Date: Tue, 25 Aug 2009 13:24:37 +0200 Subject: problem to write a THREAD enabled python extension References: <4a92af50$0$32675$9b4e6d93@newsspool2.arcor-online.net> Message-ID: Stefan Behnel wrote: > > You forgot to create a thread state for the new thread. See the > PyThreadState_New() function. > this does not really solve the problem even if the original error does no happen anymore ... but a bucket of other error happen >>> sometimes <<< and this mean that time and (I call it so) internal state stuff has influence on the problem and create errors like: 1. http://mail.python.org/pipermail/python-list/2004-January/242740.html 2. various PyThreadState_Get -> PyThreadState_Get: no current thread 3. sometimes ThreadState has NULL sometimes not and NULL create an CORE for "tstate" pointer access operations 4. ... a lot of other problems too all problems together I come to the conclusion: 1. I spend ~ 1week for a job done in C# or java in a day - and have no usable solution 2. python need a couple of 100+ C API function for the same job java need 10+ 3. the design on the C-API is amateurish -> significant parts are implemented as GLOBAL variables 4. the thread support is not more than a joke -> go to 3 5. after pay a lot of effort to get something working the final solution is significant slower than C# or JAVA 6. you can not truss any-thing in python because you never know if under some circumstance you get a CORE the resulting PYTHON code is usable but not significant more readable as JAVA, C* or even C++ code mfg aotto1968 From feliphil at gmx.net Tue Aug 25 07:24:39 2009 From: feliphil at gmx.net (Wolfgang Keller) Date: Tue, 25 Aug 2009 13:24:39 +0200 Subject: Python for professsional Windows GUI apps? References: Message-ID: <20090825132439.d6cb18ca.feliphil@gmx.net> > I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. The area of _desktop_ database application development indeed looks like a vast and very hostile desert in the Python landscape. The only framework that seems to be worth trying is Dabo. Unfortunately there's little documentation, and that's mostly outdated. There's also Kiwi, but that's even less well documented. And GNU Enterprise essentially seems to be dead. Sincerely, Wolfgang -- NO "Courtesy Copies" PLEASE! From deets at nospam.web.de Tue Aug 25 07:25:04 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 13:25:04 +0200 Subject: unexpected token `;' References: Message-ID: <7fi00gF2kr205U1@mid.uni-berlin.de> bbarbero at inescporto.pt wrote: > Hello to all! > > I am struggling with a script in python for a while now, and decided > to look for some help. I am running a code that takes commands from > Marsyas(open source for Music analysis). > > #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 > #!/bin/bashimport math This is bogus. Replace it with #!/usr/bin/python and put the "import math" on the next line. Diez From markonlinux at internode.on.net Tue Aug 25 07:26:40 2009 From: markonlinux at internode.on.net (Mark) Date: 25 Aug 2009 11:26:40 GMT Subject: can python make web applications? References: Message-ID: <02a3ba7c$0$18215$c3e8da3@news.astraweb.com> On Sun, 23 Aug 2009 21:45:17 +0100, Goke Aruna wrote: > A lot check this fantastic open source application, > http://www.openerp.com, all done is python. That does look impressive. Is that Django or Turbogears? -- Mark From gslindstrom at gmail.com Tue Aug 25 07:28:40 2009 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Tue, 25 Aug 2009 06:28:40 -0500 Subject: PyCon 2010 - Call for Tutorials Message-ID: The period to submit proposals for PyCon 2010 in Atlanta, Georgia (USA) is now open and will close on October 18. Tutorials are 3-hour long classes on a specific Python technique, package or technology and are taught by members of the Python community. If you have knowledge in a particular topic and would like to be considered to teach a class we invite you to submit a proposal outlining the material you would like to cover. Once we receive your proposal, we will "score" it based on content and then select 24 classes (subject to change) for presentation. Class instructors will be paid $1000.00 per class. If a class has more than one teacher, the fee will be split between them. Interested? Click on over to the Tutorial Proposal Pageto see more details, examples of classes that have been requested in the past (though you are free to submit a proposal on anything Python), an example proposal and an empty template to help you prepare your own proposal. Once complete, email your proposal to pycon-tutorials at python.orgso we can get it out to the evaluation committee and get you on your way to being a PyCon Questions? You can contact us at the PyCon Email Listand we will get back with you. We look forward to hearing from you! Greg Lindstrom Tutorial Coordinator PyCon 2010 (Atlanta) -------------- next part -------------- An HTML attachment was scrubbed... URL: From piet at cs.uu.nl Tue Aug 25 07:33:02 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 25 Aug 2009 13:33:02 +0200 Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> <4224e772-5b67-4eea-9bdf-a7d2bf7cc128@c14g2000yqm.googlegroups.com> <864e2d5f-0855-4f35-a78c-b09054e75f0d@w41g2000yqb.googlegroups.com> Message-ID: >>>>> sturlamolden (s) wrote: >s> On 25 Aug, 01:26, Piet van Oostrum wrote: >>> That's because it doesn't use copy-on-write. Thereby losing most of its >>> advantages. I don't know SUA, but I have vaguely heard about it. >s> SUA is a version of UNIX hidden inside Windows Vista and Windows 7 >s> (except in Home and Home Premium), but very few seem to know of it. >s> SUA (Subsystem for Unix based Applications) is formerly known as >s> Interix, which is a certified version of UNIX based on OpenBSD. If you >s> go to http://www.interopsystems.com (a website run by Interop Systems >s> Inc., a company owned by Microsoft), you will find a lot of common >s> unix tools prebuilt for SUA, including Python 2.6.2. >s> The NT-kernel supports copy-on-write fork with a special system call >s> (ZwCreateProcess in ntdll.dll), which is what SUA's implementation of >s> fork() uses. I have heard about that also, but is there a Python implementation that uses this? (Just curious, I am not using Windows.) -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From nobody at nowhere.com Tue Aug 25 07:34:59 2009 From: nobody at nowhere.com (Nobody) Date: Tue, 25 Aug 2009 12:34:59 +0100 Subject: web frameworks that support Python 3 References: Message-ID: On Sun, 23 Aug 2009 16:32:09 -0400, Albert Hopkins wrote: > What's different about Python 3 is that there is only unicode strings, > whereas Python 2 has a string type and a unicode type. Python 2 has "str" (char) and "unicode" (wchar) types. Python 3 has "bytes" (char) and "str" (wchar) types. The main difference is that Python 3 uses unicode "by default", i.e. string literals are unicode rather than byte strings, variables such as sys.argv and os.environ contain unicode strings, etc. There are other differences, e.g.: + Passing a "bytes" object where "str" is expected will raise an exception rather than using an automatic conversion + Subscripting a "bytes" object returns an integer between 0 and 255 + upper(), isalpha(), etc assume ASCII rather than the system encoding From nobody at nowhere.com Tue Aug 25 07:47:54 2009 From: nobody at nowhere.com (Nobody) Date: Tue, 25 Aug 2009 12:47:54 +0100 Subject: sgmllib.py References: <4a923c57$0$32664$9b4e6d93@newsspool2.arcor-online.net> Message-ID: On Mon, 24 Aug 2009 09:08:07 +0200, Stefan Behnel wrote: > But note that sgmllib is a particularly cumbersome way to deal with HTML. Mostly because it only provides a tokeniser, not a parser. Whoever wrote it doesn't appear to understand the difference. From benjamin.kaplan at case.edu Tue Aug 25 07:50:59 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Tue, 25 Aug 2009 07:50:59 -0400 Subject: unexpected token `;' In-Reply-To: <7fi00gF2kr205U1@mid.uni-berlin.de> References: <7fi00gF2kr205U1@mid.uni-berlin.de> Message-ID: On Tue, Aug 25, 2009 at 7:25 AM, Diez B. Roggisch wrote: > > > Hello to all! > > > > I am struggling with a script in python for a while now, and decided > > to look for some help. I am running a code that takes commands from > > Marsyas(open source for Music analysis). > > > > #!/Library/Frameworks/Python.framework/Versions/2.6/bin/python2.6 > > #!/bin/bashimport math > > This is bogus. Replace it with > > #!/usr/bin/python > > and put the "import math" on the next line. > > Diez It's not bogus. That is perfectly legitimate for using the user-installed Python2.6 on OS X. /usr/bin/ is reserved for system programs on that platform so it will always point to the system python install, which is 2.5.1 on Leopard and 2.3.5 on Tiger. That being said, the #!/bin/bash line is what's screwing it up. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Aug 25 07:51:24 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Aug 2009 13:51:24 +0200 Subject: unexpected token `;' References: Message-ID: bbarbero at inescporto.pt wrote: > I am struggling with a script in python for a while now, and decided > to look for some help. I am running a code that takes commands from > Marsyas(open source for Music analysis). > cmd = "sfplay " + colist[2] > print cmd > fileout = commands.getoutput(cmd) You have to ensure here that characters that have a special meaning for the shell are escaped correctly. The best approach is probably to use subprocess instead of commands: fileoutput = subprocess.Popen(["sfplay", colist[2]], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0] Peter From ebonak at hotmail.com Tue Aug 25 07:55:22 2009 From: ebonak at hotmail.com (Esmail) Date: Tue, 25 Aug 2009 07:55:22 -0400 Subject: your favorite debugging tool? In-Reply-To: <7xocq5vx64.fsf@ruckus.brouhaha.com> References: <7xocq5vx64.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Esmail writes: >> What is your favorite tool to help you debug your >> code? I've been getting along with 'print' statements >> but that is getting old and somewhat cumbersome. > > Beyond print statements, I use pdb a lot. Winpdb (www.winpdb.org) is > even better, but is kind of cumbersome to get working. Hi, 2 quick questions. Re pdb, if you have a 'pointer' (ie reference) to an object, is there an easy way to dump out its contents, ie all of its members short of writing a method that does that and then calling it? Anyone know what is going on with the winpdb site? I haven't been able to get to it in the last few days. Thanks, Esmail From ebonak at hotmail.com Tue Aug 25 07:55:56 2009 From: ebonak at hotmail.com (Esmail) Date: Tue, 25 Aug 2009 07:55:56 -0400 Subject: your favorite debugging tool? In-Reply-To: References: <7xocq5vx64.fsf@ruckus.brouhaha.com> Message-ID: Robert Marshall wrote: > On 24 Aug 2009, Paul Rubin wrote: > >> Esmail writes: >>> What is your favorite tool to help you debug your >>> code? I've been getting along with 'print' statements >>> but that is getting old and somewhat cumbersome. >> Beyond print statements, I use pdb a lot. Winpdb (www.winpdb.org) is >> even better, but is kind of cumbersome to get working. > > And you can run it (pdb) within emacs - though I find a little roughness > in working out the exact interactions keeps ending up (ie the source > buffer displayed) in the wrong stack frame - afaict Thanks Robert, I'll have to give that a try. Esmail From ebonak at hotmail.com Tue Aug 25 07:57:26 2009 From: ebonak at hotmail.com (Esmail) Date: Tue, 25 Aug 2009 07:57:26 -0400 Subject: your favorite debugging tool? In-Reply-To: <57d65219-8134-4c2e-9739-825a5ef450d0@s15g2000yqs.googlegroups.com> References: <57d65219-8134-4c2e-9739-825a5ef450d0@s15g2000yqs.googlegroups.com> Message-ID: Michele Simionato wrote: > On Aug 22, 4:25 pm, Esmail wrote: >> Hi all, >> >> What is your favorite tool to help you debug your >> code? > > The times when I would just use 'print' are long past. Nowadays I > spend lots of my time > with code written by others than myself. I use pdb all the time, and > now also ipdb > (ipdb is very cool if you are used to ipython). Never heard of ipdb, I'll have to check it out. Thanks, Esmail From dmw at coder.cl Tue Aug 25 08:08:02 2009 From: dmw at coder.cl (Daniel Molina Wegener) Date: Tue, 25 Aug 2009 08:08:02 -0400 Subject: [ANN] pyxser-1.2r --- Python-Object to XML serialization module References: <2571343.k9db9GJWqV@coder.cl> <4a923e50$0$32664$9b4e6d93@newsspool2.arcor-online.net> <2665032.o6QR52tnKS@coder.cl> <4a928ed7$0$32666$9b4e6d93@newsspool2.arcor-online.net> <1685404.FXBiJzzPRc@coder.cl> <4a937266$0$31337$9b4e6d93@newsspool4.arcor-online.net> <4a937546$0$31332$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <1731852.i11Z6b9PKs@coder.cl> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA512 Stefan Behnel on Tuesday 25 August 2009 01:23 wrote in comp.lang.python: > Stefan Behnel wrote: >> for all byte >> strings, regardless of their encoding (since you can't even know if they >> represent encoded text at all). > > Hmm, having written that, I guess it's actually best to encode byte > strings as base64 instead. Otherwise, null bytes and other special byte > values won't pass. Sure, base64 is a good option for byte string input. > > I also think that if the user wants readable output for text strings, it's > reasonable to require Unicode input instead of byte strings. Handling text > in byte strings is just too error prone. > > Still, you may have to sanitize text input to make sure it doesn't contain > special characters either. Take a look at the way lxml does it in the > apihelpers.pxi source file, or read the XML spec on character content. Thanks, I will look for that. I must to do a better implementation on handling byte strings, since would be many cases on where encoded strings are mixed. For example different database inputs with different encodings --- if those byte strings are not readed as Unicode strings. Both sanitizing and base64 encoding are good options, and also, both are readable from other platforms. The problem with later implementations of pyxser was that it was using *RawUnicodeEscape* which is not readable from other platforms. > > Stefan Best regards, - -- .O. | Daniel Molina Wegener | FreeBSD & Linux ..O | dmw [at] coder [dot] cl | Open Standards OOO | http://coder.cl/ | FOSS Developer -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (FreeBSD) iQIcBAEBCgAGBQJKk9QiAAoJEHxqfq6Y4O5NvxcP/1plIdop5ghbwAKwavU8PSSe 05Lx/3AqThiQTJgG1qIrUXqA70KKGbgnyRAyOb8lTo3E1EcYnrEyM3pIg9xKbEr1 aRbpMVPIUPv//ckJxIwJlszjWoxjpSWKpRFqOkHnBjL6NcAqD7r3LxMLaDKMHNXl Ka07clukcarEeU5f93mcOpCXMg1XFxfQFr126wbEkC5M2WxwpSJrsX6NIXL34peU 37sjuYOQGEgifw7KKVDNCmt3JNTmojCeRL+xzUiFDXRmm2B9A2Q7fGKKudNC2+u7 d5vUdWUhsK8a2P7o3c8ka/N9hcZ7ESjhlLDjtXEAb45yGUOXkpoOSLznObhGM3H9 MpPbmprvFL8sUX8F8+EOHOAbfaTtTRO384hwY2e7tVaaf6CNutK00Z5nBM7UPdWW nclS7owNOVsrR62ZGwEcjDwjeYqXp3kIixbbSM9kALu1iKYxaueauIXct6oPQwl7 A3rEmultt7pjfbaDw+kYCouP4YnbPQn84H7Qgle/TMATPgnlD+93OnbCgWhpkx0h 21l4STWHNIZ2yi538lDDnkxKXS9reJQOYiiB9ImueIJJBZhqTwCDiCZDJg7QBVH0 7zsKH70Pbl3ENpTjBmPsxTUbOjzMwaFCbJ/h9+JCLV98TRfwa4KOAsRDC+mThnrY k6Pj1jxY4uYmAn+xK+x+ =5B9H -----END PGP SIGNATURE----- From walterbyrd at iname.com Tue Aug 25 08:28:31 2009 From: walterbyrd at iname.com (walterbyrd) Date: Tue, 25 Aug 2009 05:28:31 -0700 (PDT) Subject: Would there be work for a sysadmin who specializes in python? Message-ID: If I took the time to really learn to use python for sysadmin work, would I be able to find jobs, or even contract jobs? >From what I am seeing on the job boards etc., I would have to say no. It looks to me as though I could possibly do that with perl, but not python. Of course, I could be missing something. Job board ads can be deceptive. From ryniek90 at gmail.com Tue Aug 25 08:29:27 2009 From: ryniek90 at gmail.com (ryniek) Date: Tue, 25 Aug 2009 05:29:27 -0700 (PDT) Subject: Temat:, Re: IOError: [Errno 22] invalid mode ('wb') or filename: in windows xp while making tarfile References: <4A928B4B.9030502@gmail.com> <4A92A57A.5010105@dejaviewphoto.com> <4ec18c68-b8b5-401e-b910-802b7662dced@i18g2000pro.googlegroups.com> <321b8396-0806-4a1a-9a32-efbb147e6b4b@c2g2000yqi.googlegroups.com> Message-ID: <62ee06b6-4d8b-4033-828a-bad0bd6ea329@r42g2000yqj.googlegroups.com> On 25 Sie, 07:33, Dennis Lee Bieber wrote: > On Mon, 24 Aug 2009 14:23:41 -0700 (PDT), ryniek > declaimed the following in gmane.comp.python.general: > > > C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje > > \Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba > > ckuper.py -f E:\APLIKACJE\nowegg.exe E:\ MyGG > > ? ? ? ? > > > OSError: [Errno 22] Invalid argument: 'E:\\MyGG(2009-08-24 > > 23:18:25).tar.bz2' > > " > > ? ? ? ? WHERE in your program are you creating that file name? Based upon > the invocation line, all you are supplying is the E:\MyGG part... > Somewhere you are creating a timestamp and attaching that to the prefix. > > ? ? ? ? THAT is where you need to get rid of the colons -- the ones in the > timestamp. Instead of 23:18:25 (or whatever the next run generates) you > want something like 23_18_25... > -- > ? ? ? ? Wulfraed ? ? ? ? Dennis Lee Bieber ? ? ? ? ? ? ? KD6MOG > ? ? ? ? wlfr... at ix.netcom.com ? ? ?HTTP://wlfraed.home.netcom.com/ Yep, i realized that it were THOSE colons. Thanks very much. I think i must work on my perceptivity : P Thanks again. From nobody at nowhere.com Tue Aug 25 08:34:33 2009 From: nobody at nowhere.com (Nobody) Date: Tue, 25 Aug 2009 13:34:33 +0100 Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> <84154e6e-c425-4b71-89e3-7d2877a19418@m7g2000prd.googlegroups.com> Message-ID: On Tue, 25 Aug 2009 03:41:54 -0700, 7stud wrote: > Why does echoing $LC_ALL or $LC_CTYPE just give me a blank string? Because the variables aren't set. The default locale for a particular category (e.g. LC_CTYPE) is taken from $LC_ALL if that is set, otherwise $LC_CTYPE, otherwise $LANG, otherwise "C" is used. Normally, you would either set LANG (and possibly some individual LC_* variables), or LC_ALL. There's no point in setting all of them. > In conclusion, as far as I can tell, if your python 3.1 program tries > to output a unicode string, and the unicode string cannot be encoded > by the codec specified in the user's LANG environment variable**, then > the user will get an encode error. Just because the programmer's > system can handle the output doesn't mean that another user's system > can. I guess that's the way it goes: if a user's environment is > telling all programs that it only wants ascii output to go to the > screen(sys.stdout), you can't(or shouldn't) do anything about it. > > **Or if the LANG environment variable is not present, then the codec > corresponding to the locale settings(C' corresponds to ascii). The underlying OS primitive can only handle bytes. If you read or write a (unicode) string, Python needs to know which encoding is used. For Python file objects created by the user (via open() etc), you can specify the encoding; for those created by the runtime (e.g. sys.stdin), Python uses the locale's LC_CTYPE category to select an encoding. Data written to or read from text streams is encoded or decoded using the stream's encoding. Filenames are encoded and decoded using the filesystem encoding (sys.getfilesystemencoding()). Anything else uses the default encoding (sys.getdefaultencoding()). In Python 3, text streams are handled using io.TextIOWrapper: http://docs.python.org/3.1/library/io.html#text-i-o This implements a stream which can read and/or write text data on top of one which can read and/or write binary data. The sys.std{in,out,err} streams are instances of TextIOWrapper. You can get the underlying binary stream from the "buffer" attribute, e.g.: sys.stdout.buffer.write(b'hello world\n') If you need to force a specific encoding (e.g. if the user has specified an encoding via a command-line option), you can detach the existing wrapper and create a new one, e.g.: sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = new_encoding) From ebonak at hotmail.com Tue Aug 25 08:40:24 2009 From: ebonak at hotmail.com (Esmail) Date: Tue, 25 Aug 2009 08:40:24 -0400 Subject: Would there be work for a sysadmin who specializes in python? In-Reply-To: References: Message-ID: walterbyrd wrote: > If I took the time to really learn to use python for sysadmin work, > would I be able to find jobs, or even contract jobs? > FWIW, I think one of the qualities of a good system admin would be the ability to work with a variety of tools and languages and not focus on one particular language. Though Perl (not a favorite of mine at all :) seems to be quite popular for admin type work, and of course knowing some sort of shell programming etc would come in handy. From ben+python at benfinney.id.au Tue Aug 25 08:44:47 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Tue, 25 Aug 2009 22:44:47 +1000 Subject: your favorite debugging tool? References: Message-ID: <87ws4sf4g0.fsf@benfinney.id.au> Esmail writes: > While I do believe in a minimalist approach (part of the reason I find > Python so appealing), using print statements sometimes only goes so > far (for me). Right, which is where the Python interactive interpreter (which I failed to mention in my initial response) comes in as my favourite debugging tool. -- \ ?When I was a kid I used to pray every night for a new bicycle. | `\ Then I realised that the Lord doesn't work that way so I stole | _o__) one and asked Him to forgive me.? ?Emo Philips | Ben Finney From ebonak at hotmail.com Tue Aug 25 08:51:06 2009 From: ebonak at hotmail.com (Esmail) Date: Tue, 25 Aug 2009 08:51:06 -0400 Subject: your favorite debugging tool? In-Reply-To: <87vdkfiaki.fsf@benfinney.id.au> References: <87vdkfiaki.fsf@benfinney.id.au> Message-ID: Hi Ben, Ben Finney wrote: > > Whenever a simple output statement is too cumbersome for debugging, I > take it as a sign that the program is too cumbersome to follow. I'll have to think about this .. though my gut says this is true :-) re your other point about the interactive shell, I agree it's useful, but to me still doesn't quite do what a full-fledged debugger can - but perhaps that is a reflection of my skill with the shell at this point. Always more to learn. Esmail From hniksic at xemacs.org Tue Aug 25 09:03:12 2009 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 25 Aug 2009 15:03:12 +0200 Subject: proposal: add setresuid() system call to python In-Reply-To: <20090821205040.GK1215@subspacefield.org> (travis's message of "Fri, 21 Aug 2009 15:50:40 -0500") References: <20090717200141.GI6065@subspacefield.org> <148918f0907171315i4ed5b274v77581a43c4464f8f@mail.gmail.com> <7cj89qF27mfrjU1@mid.uni-berlin.de> <877hy38mxw.fsf@busola.homelinux.net> <20090821205040.GK1215@subspacefield.org> Message-ID: <87d46kdp0v.fsf@busola.homelinux.net> travis+ml-python at subspacefield.org writes: > On Mon, Jul 20, 2009 at 04:10:35PM +0200, Hrvoje Niksic wrote: >> To emulate the os-module-type calls, it's better to raise exceptions >> than return negative values: >> >> > def setresuid(ruid, euid, suid): >> > return _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid)) >> >> def setresuid(ruid, euid, suid): >> res = _setresuid(__uid_t(ruid), __uid_t(euid), __uid_t(suid)) >> if res < 0: >> raise OSError('[Errno %d] %s' % (os.errno, errno.strerror(os.errno))) > > I am working on a module to implement all of this, but that raise command > won't work in Python 2.6.1; it turns out that os.errno is a module, not > an integer. Does anyone know how to do what I want (that is, how to access > the errno set in C functions)? You should use ctypes.get_errno() instead of os.errno; sorry about that. Also, when raising OSError, you should set the 'errno' attribute to the appropriate code. From nobody at nowhere.com Tue Aug 25 09:16:23 2009 From: nobody at nowhere.com (Nobody) Date: Tue, 25 Aug 2009 14:16:23 +0100 Subject: os.popen output different from native shell output References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Message-ID: On Tue, 25 Aug 2009 01:36:08 -0700, nickname wrote: > I am a relative newbie to python, I am using os.popen to run an > ls command. The output that I get using the read() function is > different in look and feel from when I run the ls command natively > from the shell (not via python). As others have pointed out, the default behaviour of ls is different if its output is a terminal. > Is there an easy way to "mirror" the output. When python displays the > output, how can it tell the bash shell that some of the entries are > directories and they should appear blue on the bash shell, and that > everything should not be appearing on 1 column only. You can get the terminal-style behaviour even when using a pipe with: ls -x --color But why are you reading this information into Python then writing it back out to the terminal? If you're planning on processing the output within Python, both the multi-column format and the escape sequences used for colour will make such processing awkward. If you want to enumerate the contents of a directory within Python, use os.listdir(). If you want to generate coloured output, use the curses module, e.g.: #!/usr/bin/env python import sys import curses curses.setupterm() setaf = curses.tigetstr('setaf') or "" setab = curses.tigetstr('setab') or "" origp = curses.tigetstr('op') or "" def fg(c): sys.stdout.write(curses.tparm(setaf, c)) def bg(c): sys.stdout.write(curses.tparm(setab, c)) def orig(): sys.stdout.write(origp) # example bg(curses.COLOR_BLUE) fg(curses.COLOR_YELLOW) print "hello, world" orig() From find.mig at paa.google Tue Aug 25 09:21:16 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Tue, 25 Aug 2009 15:21:16 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a92b290$0$305$14726298@news.sunsite.dk> Message-ID: <4a93e575$0$298$14726298@news.sunsite.dk> Dennis Lee Bieber wrote: > On Mon, 24 Aug 2009 17:32:23 +0200, Esben von Buchwald > declaimed the following in > gmane.comp.python.general: > >> I'm new to python, what is an after function and an after call? Couldn't >> find excact answer on google...? Do you have a link to some docs? > > They would be particular to whatever GUI/event library is in use. > They aren't part of Python itself. This is how the accelerometer is accessed http://pys60.garage.maemo.org/doc/s60/node59.html I found this called "after"... http://pys60.garage.maemo.org/doc/s60/node12.html would that be usable? If so, how? From kkuNOTHISmer at thatsearchenginesmail.com Tue Aug 25 09:30:28 2009 From: kkuNOTHISmer at thatsearchenginesmail.com (Kreso) Date: Tue, 25 Aug 2009 13:30:28 +0000 (UTC) Subject: Items inheriting attributes from its container? References: Message-ID: Jan Kaliszewski wrote: [...] Great! Thanks to all of you for advices and code. K. From brentb at beanfield.com Tue Aug 25 09:42:00 2009 From: brentb at beanfield.com (Brent Bloxam) Date: Tue, 25 Aug 2009 09:42:00 -0400 Subject: Would there be work for a sysadmin who specializes in python? In-Reply-To: References: Message-ID: <4A93EA28.8060703@beanfield.com> walterbyrd wrote: > If I took the time to really learn to use python for sysadmin work, > would I be able to find jobs, or even contract jobs? > >>From what I am seeing on the job boards etc., I would have to say no. > It looks to me as though I could possibly do that with perl, but not > python. > > Of course, I could be missing something. Job board ads can be > deceptive. Being a system admin is about being able to handle to many different situations, and your tasks can often include automating various things and writing tools. Depending on the sort of place you're working in and the size of the IT department, you could find yourself doing a lot of work that lies outside of the standard job description for a system administrator. If you're looking to start out in the field, it would be better to have general knowledge, and as you gain experience you can begin to specialize. Being adaptable is key, so specializing in python probably won't gain you any ground as a system administrator. That being said, knowing python will mean you have another tool in your chest, which is definitely a good thing. If there's one thing I'd recommend, if you're not going to focus on a windows environment, would be to at least get perl under your belt as well. From jkpeck at gmail.com Tue Aug 25 10:02:36 2009 From: jkpeck at gmail.com (JKPeck) Date: Tue, 25 Aug 2009 07:02:36 -0700 (PDT) Subject: csv module and None values References: <23c02daf-dc5a-4676-8d73-9dc63791825f@o36g2000vbl.googlegroups.com> Message-ID: <4006702e-14c5-4917-b76f-906233cad71e@k30g2000yqf.googlegroups.com> On Aug 24, 10:43?pm, John Yeung wrote: > On Aug 24, 5:00?pm, Peter Otten <__pete... at web.de> wrote: > > > If I understand you correctly the csv.writer already does > > what you want: > > > >>> w.writerow([1,None,2]) > > 1,,2 > > > just sequential commas, but that is the special treatment. > > Without it the None value would be converted to a string > > and the line would look like this one: > > > 1,None,2 > > No, I think he means he is getting > > >>> w.writerow([1,None,2]) > > 1,"",2 > > He evidently wants to quote "all" strings, but doesn't want None to be > considered a string. > > John Exactly so. The requirement of the receiving program, which is out of my control, is that all strings be quoted but a None in a numeric field result in the ,, output rather than "". Excel quotes strings conditionally, which doesn't do what is needed in this case. For QUOTE_NONNUMERIC to quote None values makes some sense, but it gets in the way of representing missing values in a numeric field. It would be nice to have a choice here in the dialects. I thought of replacing the None values with float(nan), since that has a numeric type, but unfortunately that results in writing the string (unquoted) nan for the value. So the sentinel approach seems to be the best I can do. Thanks, Jon From chris0wj at gmail.com Tue Aug 25 10:14:12 2009 From: chris0wj at gmail.com (Chris) Date: Tue, 25 Aug 2009 07:14:12 -0700 (PDT) Subject: multiprocessing managers and socket connection. Message-ID: <722664f1-81af-45da-ae40-070bca8f3ee0@k6g2000yqn.googlegroups.com> I've been using multiprocessing managers and I really like the functionality. I have a question about reconnecting to a manager. I have a situation where I start on one machine (A) a manager that is listening and then on another machine (B) connects to that manager and uses its proxy object to call functions on the manager's computer; this all works as expected. But, if the manager from A shuts down, B's application won't notice because in the MP code it ignores socket error errno.ECONNREFUSED. If A becomes available again or is restarted, B doesn't automatically reconnect either and continue its operation. It's function is basically stopped. Here is the code from connection.py: while 1: try: s.connect(address) except socket.error, e: if e.args[0] != errno.ECONNREFUSED: # connection refused debug('failed to connect to address %s', address) raise time.sleep(0.01) else: break How can I have B automatically reconnect to A and continue its work once A is available again? From steve at REMOVE-THIS-cybersource.com.au Tue Aug 25 10:14:49 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Aug 2009 14:14:49 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> Message-ID: <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> On Mon, 24 Aug 2009 18:01:38 -0700, Mensanator wrote: >> If you want your data file to have values entered in hex, or oct, or >> even unary (1=one, 11=two, 111=three, 1111=four...) you can. > > Unary? I think you'll find that Standard Positional Number Systems are > not defined for radix 1. Of course not. But unary isn't a positional number system. It's a tally system, like my example above shows. Roman numerals are another tally system. Like Roman numerals, the disadvantages of unary are that you can't represent negative numbers, zero, or fractions, and anything but addition and subtraction is difficult. But if you want to use it, perhaps out of a sense of sadism towards your users, it's easy: def int2unary(n): return '1'*n def unary2int(s): n = 0 for c in s: if c == '1': n+=1 else: raise ValueError('invalid unary string') return n -- Steven From jeanmichel at sequans.com Tue Aug 25 10:27:40 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 25 Aug 2009 16:27:40 +0200 Subject: your favorite debugging tool? In-Reply-To: References: <87vdkfiaki.fsf@benfinney.id.au> Message-ID: <4A93F4DC.3090708@sequans.com> Esmail wrote: > Hi Ben, > > Ben Finney wrote: >> >> Whenever a simple output statement is too cumbersome for debugging, I >> take it as a sign that the program is too cumbersome to follow. > > I'll have to think about this .. though my gut says this is true :-) > That is not always true. When it comes to implement complex tasks, you can't always avoid writing complex code. Python does not get your code more complex than your algorithm, but it cannot always simplify it. Ben is right when he says that code can often be written in a more simpler manner, but they are some occasions when you have to write complex code, that the print debug statement won't be efficient enough to sort things out. I personally develop/maintain a full application written in python (and quite complex for some parts), using the ipdb debugger just saved my hours (days) of headache about some very difficult bug to spot > re your other point about the interactive shell, I agree it's useful, but > to me still doesn't quite do what a full-fledged debugger can - but > perhaps > that is a reflection of my skill with the shell at this point. > > Always more to learn. > > Esmail > 90% of the time, print statements + ipython shell will do the trick. The post mortem debugging is also very useful. Execute your python file in ipython, then when it exits upon exception, execute >>> import pdb ; pdb.pm() You can then inspect the symbols easily. JM From ryniek90 at gmail.com Tue Aug 25 10:37:21 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Tue, 25 Aug 2009 16:37:21 +0200 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile Message-ID: <4A93F721.10104@gmail.com> Referring to my earlier posts: http://groups.google.pl/group/comp.lang.python/browse_thread/thread/4e34f995800f5352?hl=pl and http://groups.google.pl/group/comp.lang.python/browse_thread/thread/abf5573b8fceb37e?hl=pl# I've dealt with those errors. but now have another. When my backup scripts starts to backup chosen file, python gave me Traceback: " C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba ckuper.py -f F:\APLIKACJE\nowegg.exe F:\ MyGGBackup Checking permissions for reading and writing... Have permissions on [F:\APLIKACJE\nowegg.exe] for reading. Have permissions on [F:\] for writing. Preparing for backup [nowegg.exe]... Starting backup... Now adding [nowegg.exe]... Traceback (most recent call last): File "backuper.py", line 197, in main_meth() File "backuper.py", line 189, in main_meth paq.backup_file(pars.options.filename[0], pars.options.filename[1], pars.options.filename[2]) File "backuper.py", line 127, in backup_file backup_obj.add(read_bin_obj) File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\tarfile.py", line 1948, in add if self.name is not None and os.path.abspath(name) == self.name: File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\ntpath.py", line 458, in abspath path = _getfullpathname(path) TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str " I've searched over google, but found only that is bug in Python ( http://bugs.python.org/issue4071 - in that issue bug is inside Python 2.5.2 - i've got ActiveState Active Python with core Python 2.6.2), and another info: *http://tinyurl.com/lvyn7o and **http://tinyurl.com/kn49vk * Here's my script code: *http://paste.ubuntu.com/259310/ *Shouldn't that bug be patched already :-? From chris at simplistix.co.uk Tue Aug 25 10:45:53 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 25 Aug 2009 15:45:53 +0100 Subject: inconsistent sitecustomize.py importing... Message-ID: <4A93F921.9080904@simplistix.co.uk> Hi All, Give this sitecustomize.py: print "ping" ...and this script: #!/usr/local/bin/python2.5 print "pong!" ...both in ~/folder, I would expect the output from: ~$./folder/script ...to be: ping pong ...but sitecustomize.py is not imported :-( If I do: ~$/usr/local/bin/python2.5 folder/script ...still no import. However, if I do: ~/folder$/usr/local/bin/python2.5 script ...sitecustomize.py IS imported! What gives?! Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From __peter__ at web.de Tue Aug 25 10:49:07 2009 From: __peter__ at web.de (Peter Otten) Date: Tue, 25 Aug 2009 16:49:07 +0200 Subject: csv module and None values References: <23c02daf-dc5a-4676-8d73-9dc63791825f@o36g2000vbl.googlegroups.com> <4006702e-14c5-4917-b76f-906233cad71e@k30g2000yqf.googlegroups.com> Message-ID: JKPeck wrote: > On Aug 24, 10:43 pm, John Yeung wrote: >> On Aug 24, 5:00 pm, Peter Otten <__pete... at web.de> wrote: >> >> > If I understand you correctly the csv.writer already does >> > what you want: >> >> > >>> w.writerow([1,None,2]) >> > 1,,2 >> >> > just sequential commas, but that is the special treatment. >> > Without it the None value would be converted to a string >> > and the line would look like this one: >> >> > 1,None,2 >> >> No, I think he means he is getting >> >> >>> w.writerow([1,None,2]) >> >> 1,"",2 >> >> He evidently wants to quote "all" strings, but doesn't want None to be >> considered a string. >> >> John > > Exactly so. The requirement of the receiving program, which is out of > my control, is that all strings be quoted but a None in a numeric > field result in the ,, output rather than "". Excel quotes strings > conditionally, which doesn't do what is needed in this case. For > QUOTE_NONNUMERIC to quote None values makes some sense, but it gets in > the way of representing missing values in a numeric field. It would > be nice to have a choice here in the dialects. > > I thought of replacing the None values with float(nan), since that has > a numeric type, but unfortunately that results in writing the string > (unquoted) nan for the value. So the sentinel approach seems to be > the best I can do. How about: >>> import csv, sys >>> class N(int): ... def __str__(self): return "" ... >>> pseudo_none = N() >>> w = csv.writer(sys.stdout, quoting=csv.QUOTE_NONNUMERIC) >>> w.writerow([1, "foo", pseudo_none, "bar"]) 1,"foo",,"bar" Peter From ben+python at benfinney.id.au Tue Aug 25 10:49:56 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 26 Aug 2009 00:49:56 +1000 Subject: your favorite debugging tool? References: <87vdkfiaki.fsf@benfinney.id.au> Message-ID: <87skfgeynf.fsf@benfinney.id.au> Esmail writes: > Hi Ben, > > Ben Finney wrote: > > > > Whenever a simple output statement is too cumbersome for debugging, I > > take it as a sign that the program is too cumbersome to follow. > > I'll have to think about this .. though my gut says this is true :-) Note that it's only a sign, *not* an ironclad guarantee. But it's the right way to bet, IME. > re your other point about the interactive shell, I agree it's useful, > but to me still doesn't quite do what a full-fledged debugger can - > but perhaps that is a reflection of my skill with the shell at this > point. This, on the other hand, I find even more consistent: if the code can't be effectively inspected from the interactive interpreter, that's a sure sign that its external interfaces are poor or its internal dependencies too tightly coupled; or more likely both. Fixing that set of problems is both useful for debugging *and* good design. -- \ ?Alternative explanations are always welcome in science, if | `\ they are better and explain more. Alternative explanations that | _o__) explain nothing are not welcome.? ?Victor J. Stenger, 2001-11-05 | Ben Finney From chris at simplistix.co.uk Tue Aug 25 10:53:03 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 25 Aug 2009 15:53:03 +0100 Subject: Even more inconsistent sitecustomize.py importing with PYTHONPATH rolled in... In-Reply-To: <4A93F921.9080904@simplistix.co.uk> References: <4A93F921.9080904@simplistix.co.uk> Message-ID: <4A93FACF.9000608@simplistix.co.uk> Chris Withers wrote: > However, if I do: > > ~/folder$/usr/local/bin/python2.5 script > > ...sitecustomize.py IS imported! However, the following doesn't import sitecustomize.py: ~/folder$ ./script While the following DOES import sitecustomize.py: ~/folder$ export PYTHONPATH= ~/folder$ ./script Bizarrely, none of the following import sitecustomize.py: ~$ export PYTHONPATH=~/folder ~$ ./script ~$ export PYTHONPATH=~/folder/ ~$ ./script ~$ export PYTHONPATH=~/folder ~/folder$ ./script ~$ export PYTHONPATH=~/folder/ ~/folder$ ./script Does anyone have any clue why there's such a huge level of inconsistency here?! Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From chris at simplistix.co.uk Tue Aug 25 11:05:14 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 25 Aug 2009 16:05:14 +0100 Subject: Even more inconsistent sitecustomize.py importing with PYTHONPATH rolled in... In-Reply-To: <4A93FACF.9000608@simplistix.co.uk> References: <4A93F921.9080904@simplistix.co.uk> <4A93FACF.9000608@simplistix.co.uk> Message-ID: <4A93FDAA.2050206@simplistix.co.uk> Chris Withers wrote: > Bizarrely, none of the following import sitecustomize.py: > > ~$ export PYTHONPATH=~/folder > ~$ ./script > > ~$ export PYTHONPATH=~/folder/ > ~$ ./script > > ~$ export PYTHONPATH=~/folder > ~/folder$ ./script > > ~$ export PYTHONPATH=~/folder/ > ~/folder$ ./script Okay, brain fail on my part, these do work, the others are still as described though... Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From Scott.Daniels at Acm.Org Tue Aug 25 11:26:44 2009 From: Scott.Daniels at Acm.Org (Scott David Daniels) Date: Tue, 25 Aug 2009 08:26:44 -0700 Subject: Putting together a larger matrix from smaller matrices In-Reply-To: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> References: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> Message-ID: <95-dnVK31vsFnQnXnZ2dnUVZ_qmdnZ2d@pdx.net> Matjaz Bezovnik wrote: If you are using numpy (which it sounds like you are): IDLE 2.6.2 >>> import numpy as np >>> v = np.array([[0,1,2],[3,4,5],[6,7,8]], dtype=float) >>> v array([[ 0., 1., 2.], [ 3., 4., 5.], [ 6., 7., 8.]]) >>> w = np.array([[10,11,12],[13,14,15],[16,17,18]], dtype=float) >>> w array([[ 10., 11., 12.], [ 13., 14., 15.], [ 16., 17., 18.]]) >>> r = np.zeros((6,6)) >>> r array([[ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.]]) >>> r[:3,:3] = v >>> r array([[ 0., 1., 2., 0., 0., 0.], [ 3., 4., 5., 0., 0., 0.], [ 6., 7., 8., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.]]) >>> r[3:,3:] = w >>> r array([[ 0., 1., 2., 0., 0., 0.], [ 3., 4., 5., 0., 0., 0.], [ 6., 7., 8., 0., 0., 0.], [ 0., 0., 0., 10., 11., 12.], [ 0., 0., 0., 13., 14., 15.], [ 0., 0., 0., 16., 17., 18.]]) >>> In general, make the right-sized array of zeros, and at various points: and you can ssign to subranges of the result array: N = 3 result = np.zeros((len(parts) * N, len(parts) * N), dtype=float) for n, chunk in enumerate(parts): base = n * 3 result[base : base + 3, base : base + 3] = chunk --Scott David Daniels Scott.Daniels at Acm.Org From steve at REMOVE-THIS-cybersource.com.au Tue Aug 25 11:28:31 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 25 Aug 2009 15:28:31 GMT Subject: inconsistent sitecustomize.py importing... References: Message-ID: <02a3f329$0$20629$c3e8da3@news.astraweb.com> On Tue, 25 Aug 2009 15:45:53 +0100, Chris Withers wrote: > Hi All, > > Give this sitecustomize.py: [...] > What gives?! Perhaps this? http://bugs.python.org/issue1734860 -- Steven From no.email at please.post Tue Aug 25 11:33:26 2009 From: no.email at please.post (kj) Date: Tue, 25 Aug 2009 15:33:26 +0000 (UTC) Subject: Need help with Python scoping rules Message-ID: I have many years of programming experience, and a few languages, under my belt, but still Python scoping rules remain mysterious to me. (In fact, Python's scoping behavior is the main reason I gave up several earlier attempts to learn Python.) Here's a toy example illustrating what I mean. It's a simplification of a real-life coding situation, in which I need to initialize a "private" class variable by using a recursive helper function. class Demo(object): def fact(n): if n < 2: return 1 else: return n * fact(n - 1) _classvar = fact(5) This code fails to compile, with the error "global name 'fact' not defined". Scanning the Python Language Reference page I see nothing that would suggest to me a discussion of Python's scoping rules, let alone anything that would help me solve the specific problem above. I'm sure it's in there, *somewhere*, but it's anyone's guess where. Likewise, my book, Beazley's "Python: Essential Reference" is of no help. I don't doubt that the answer to my question "is in there, *somewhere*", but finding it (without reading the book sequentially from page 1) is a tall order. All that's left is trial-and-error, the worst kind of programming. And still I can't find the right way to do this... I've tried every variant of this code that I can imagine, including decorating fact with @staticmethod or @classmethod, etc., etc. (In the latter case, I get cryptic errors saying that the staticmethod or classmethod object is not callable. Or something like that.) Needless to say, I'm pretty beat by this point. Any help would be appreciated. Thanks, kynn From mbezovnik at freenet.si Tue Aug 25 11:37:09 2009 From: mbezovnik at freenet.si (Matjaz Bezovnik) Date: Tue, 25 Aug 2009 17:37:09 +0200 Subject: Putting together a larger matrix from smaller matrices References: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> <95-dnVK31vsFnQnXnZ2dnUVZ_qmdnZ2d@pdx.net> Message-ID: On Tue, 25 Aug 2009 08:26:44 -0700, Scott David Daniels wrote: >Matjaz Bezovnik wrote: > >If you are using numpy (which it sounds like you are): > >IDLE 2.6.2 > >>> import numpy as np > >>> v = np.array([[0,1,2],[3,4,5],[6,7,8]], dtype=float) > >>> v >array([[ 0., 1., 2.], > [ 3., 4., 5.], > [ 6., 7., 8.]]) > >>> w = np.array([[10,11,12],[13,14,15],[16,17,18]], dtype=float) > >>> w >array([[ 10., 11., 12.], > [ 13., 14., 15.], > [ 16., 17., 18.]]) > >>> r = np.zeros((6,6)) > >>> r >array([[ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.]]) > >>> r[:3,:3] = v > >>> r >array([[ 0., 1., 2., 0., 0., 0.], > [ 3., 4., 5., 0., 0., 0.], > [ 6., 7., 8., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.], > [ 0., 0., 0., 0., 0., 0.]]) > >>> r[3:,3:] = w > >>> r >array([[ 0., 1., 2., 0., 0., 0.], > [ 3., 4., 5., 0., 0., 0.], > [ 6., 7., 8., 0., 0., 0.], > [ 0., 0., 0., 10., 11., 12.], > [ 0., 0., 0., 13., 14., 15.], > [ 0., 0., 0., 16., 17., 18.]]) > >>> > >In general, make the right-sized array of zeros, and at various points: >and you can ssign to subranges of the result array: > > N = 3 > result = np.zeros((len(parts) * N, len(parts) * N), dtype=float) > for n, chunk in enumerate(parts): > base = n * 3 > result[base : base + 3, base : base + 3] = chunk > >--Scott David Daniels >Scott.Daniels at Acm.Org Scott, thank you very much for the snippet. It is exactly what I looked for; simple to read and obvious as to what it does even a month later to a non-pythonist! Matjaz From ndbecker2 at gmail.com Tue Aug 25 11:49:03 2009 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 25 Aug 2009 11:49:03 -0400 Subject: Graph library recommendations for large graphs References: Message-ID: VanL wrote: > I am working on a project that will require building and querying large > graph objects (initially 8M nodes, 30-40M edges; eventually 40M nodes, > 100M edges). NetworkX seems to be the most popular, but I am concerned > that a dict representation for nodes would use too much memory -- my > initial tests suggest that a graph with 3M nodes and 12M edges creates > substantial memory pressure on my machine. > > Can anybody who has worked with large graphs before give a recommendation? > > Thanks, > > Van > How about python-igraph? From python at mrabarnett.plus.com Tue Aug 25 12:00:35 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 25 Aug 2009 17:00:35 +0100 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile In-Reply-To: <4A93F721.10104@gmail.com> References: <4A93F721.10104@gmail.com> Message-ID: <4A940AA3.8080003@mrabarnett.plus.com> Ryniek90 wrote: > Referring to my earlier posts: > http://groups.google.pl/group/comp.lang.python/browse_thread/thread/4e34f995800f5352?hl=pl > > > and > > http://groups.google.pl/group/comp.lang.python/browse_thread/thread/abf5573b8fceb37e?hl=pl# > > > I've dealt with those errors. but now have another. > When my backup scripts starts to backup chosen file, python gave me > Traceback: > > " > C:\Users\Ryniek's WinSe7en\Documents\My > Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba > ckuper.py -f F:\APLIKACJE\nowegg.exe F:\ MyGGBackup > Checking permissions for reading and writing... > Have permissions on [F:\APLIKACJE\nowegg.exe] for reading. > Have permissions on [F:\] for writing. > Preparing for backup [nowegg.exe]... > Starting backup... > Now adding [nowegg.exe]... > Traceback (most recent call last): > File "backuper.py", line 197, in > main_meth() > File "backuper.py", line 189, in main_meth > paq.backup_file(pars.options.filename[0], pars.options.filename[1], > pars.options.filename[2]) > File "backuper.py", line 127, in backup_file > backup_obj.add(read_bin_obj) > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python > 2.6\lib\tarfile.py", line 1948, in add > if self.name is not None and os.path.abspath(name) == self.name: > File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\ntpath.py", > line 458, in abspath > path = _getfullpathname(path) > TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str > " > > I've searched over google, but found only that is bug in Python ( > http://bugs.python.org/issue4071 - in that issue bug is inside Python > 2.5.2 - i've got ActiveState Active Python with core Python 2.6.2), and > another info: *http://tinyurl.com/lvyn7o and > **http://tinyurl.com/kn49vk > * > > Here's my script code: > *http://paste.ubuntu.com/259310/ > > *Shouldn't that bug be patched already :-? Are you giving it the contents of the file when it's actually expecting the filename? From hendrik at microcorp.co.za Tue Aug 25 12:02:31 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 25 Aug 2009 18:02:31 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a93e575$0$298$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a93e575$0$298$14726298@news.sunsite.dk> Message-ID: <200908251802.31556.hendrik@microcorp.co.za> On Tuesday 25 August 2009 15:21:16 Esben von Buchwald wrote: > Dennis Lee Bieber wrote: > > On Mon, 24 Aug 2009 17:32:23 +0200, Esben von Buchwald > > declaimed the following in > > > > gmane.comp.python.general: > >> I'm new to python, what is an after function and an after call? Couldn't > >> find excact answer on google...? Do you have a link to some docs? > > > > They would be particular to whatever GUI/event library is in use. > > They aren't part of Python itself. > > This is how the accelerometer is accessed > http://pys60.garage.maemo.org/doc/s60/node59.html > > I found this called "after"... > http://pys60.garage.maemo.org/doc/s60/node12.html > > would that be usable? Probably > > If so, how? This is a guess, for your device, but I suspect something along these lines: t = Ao_timer() cb = t.after(100,thing_that_does_the_work(with_its_arguments)) Lots of assumptions here - the 100 should give you a tenth of a second... Don't know what the arguments look like, and if you need to pass an instance (like self) - that would depend on where you are calling it from. Play and see :-) You should also be able to cancel the callback like this: t.cancel(cb) If you do it before the time out - Hendrik From nicola.larosa at gmail.com Tue Aug 25 12:06:37 2009 From: nicola.larosa at gmail.com (Nicola Larosa (tekNico)) Date: Tue, 25 Aug 2009 09:06:37 -0700 (PDT) Subject: Code formatting question: conditional expression References: Message-ID: <421c8c9d-efb5-4e70-9321-51736b42bc9a@g10g2000yqh.googlegroups.com> John Posner wrote: > Is there any consensus on how to format a conditional expression > that is too long for one line? Here's my take: excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True ) if total > P.BASE else None -- Nicola Larosa - http://www.tekNico.net/ Nobody knows everything, and nobody is expected to be perfect in the Ubuntu community (except of course the SABDFL). - https://launchpad.net/codeofconduct/1.0 From martin.hellwig at dcuktec.org Tue Aug 25 12:09:09 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Tue, 25 Aug 2009 17:09:09 +0100 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <9t2dnVFZo-g4kQnXnZ2dnUVZ8uidnZ2d@bt.com> kj wrote: > > Here's a toy example illustrating what I mean. It's a simplification > of a real-life coding situation, in which I need to initialize a > "private" class variable by using a recursive helper function. eh? > > class Demo(object): > def fact(n): > if n < 2: > return 1 > else: > return n * fact(n - 1) > > _classvar = fact(5) > Sorry still doesn't make sense, I'll give it a try though: class Demo(object): """Apparently a 'real-life coding situation'""" def __init__(self): # Look at http://docs.python.org/tutorial/classes.html # for init explanation. self.__class_var = self.fact(5) def fact(self, number): """Look at http://docs.python.org/tutorial/classes.html why you need self.""" if number < 2: return(1) else: return_value = number * self.fact(number -1) return(return_value) TEST = Demo() # Print the 'private' class variable print(TEST._Demo__class_var) -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From garrickp at gmail.com Tue Aug 25 12:11:47 2009 From: garrickp at gmail.com (Falcolas) Date: Tue, 25 Aug 2009 09:11:47 -0700 (PDT) Subject: your favorite debugging tool? References: Message-ID: <97f6dd5f-ffa7-4d73-8545-378301a5f6e1@13g2000prl.googlegroups.com> On Aug 23, 1:21?am, Hendrik van Rooyen wrote: > On Saturday 22 August 2009 16:49:22 Aahz wrote: > > > In article , > > > Esmail ? wrote: > > >What is your favorite tool to help you debug your code? I've been > > >getting along with 'print' statements but that is getting old and > > >somewhat cumbersome. > > > Despite the fact that I've been using Python for more than a decade, > > print is still my mainstay (or possibly logging to a file). > > Same here, although I have not been abusing python for as long as Aahz has > been using it. > > ... > > And the final arbiter is of course the interactive prompt. > > - Hendrik The only thing I would add to these comments is the fact that writing helper functions for using print with complicated routines is very simple, though perhaps not obvious. For example, consider the following for unrolling list comprehensions or generators without having to re-write them: def trace(iterable): for x in iterable: print x yield x ~G From deets at nospam.web.de Tue Aug 25 12:14:26 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 18:14:26 +0200 Subject: Need help with Python scoping rules References: Message-ID: <7figv3F2m3p0dU1@mid.uni-berlin.de> kj wrote: > > > > I have many years of programming experience, and a few languages, > under my belt, but still Python scoping rules remain mysterious to > me. (In fact, Python's scoping behavior is the main reason I gave > up several earlier attempts to learn Python.) > > Here's a toy example illustrating what I mean. It's a simplification > of a real-life coding situation, in which I need to initialize a > "private" class variable by using a recursive helper function. > > class Demo(object): > def fact(n): > if n < 2: > return 1 > else: > return n * fact(n - 1) > > _classvar = fact(5) > > This code fails to compile, with the error "global name 'fact' not > defined". > > Scanning the Python Language Reference page I see nothing that > would suggest to me a discussion of Python's scoping rules, let > alone anything that would help me solve the specific problem above. > I'm sure it's in there, *somewhere*, but it's anyone's guess where. > > Likewise, my book, Beazley's "Python: Essential Reference" is of > no help. I don't doubt that the answer to my question "is in there, > *somewhere*", but finding it (without reading the book sequentially > from page 1) is a tall order. > > All that's left is trial-and-error, the worst kind of programming. > And still I can't find the right way to do this... I've tried > every variant of this code that I can imagine, including decorating > fact with @staticmethod or @classmethod, etc., etc. (In the latter > case, I get cryptic errors saying that the staticmethod or classmethod > object is not callable. Or something like that.) Classes are not scopes. So the above doesn't work because name resolution inside functions/methods looks for local variables first, then for the *global* scope. There is no class-scope-lookup. If you want anything else, you need to qualify it with a full name, Demo.fact. Which isn't working for your example because "Demo" isn't available yet. But if you insist on the above methodology, you can do this: class Demo(object): def fact(n): def inner(n): if n < 2: return 1 else: return n * inner(n - 1) return inner(n) _classvar = fact(5) This makes inner a *local* variable, which is found. Diez From gordon at panix.com Tue Aug 25 12:19:33 2009 From: gordon at panix.com (John Gordon) Date: Tue, 25 Aug 2009 16:19:33 +0000 (UTC) Subject: Web Services examples using "raw" xml? References: <4a936e84$0$31337$9b4e6d93@newsspool4.arcor-online.net> Message-ID: In <4a936e84$0$31337$9b4e6d93 at newsspool4.arcor-online.net> Stefan Behnel writes: > > I tried WSDL.Proxy() from the SOAPpy package and eventually end up > > with this error: > > > > xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 6 > Is that while parsing the WSDL file? Have you tried pushing it through an > XML parser yourself (or opening it with an XML editor) to see if it really > is XML? The 'invalid token' error happens if the argument to WSDL.Proxy() is a string containing a URL beginning with https. (It doesn't happen with a http URL, but I'm stuck with https.) As a next step, I grabbed the content from the https url in a browser, saved it to a file, inserted it into the python code as a large string, and passed that string to WSDL.Proxy(). That produced a KeyError 'targetNamespace' from this snippet of XML: I looked at the code and it apparently requires that the parent tag of have a targetNamespace attribute. So I made one up and added it, like so: I have no idea if this was the right thing to do, but it did let me advance to the next error: Traceback (most recent call last): File "soappytest.py", line 1020, in ? server = jrgWSDL.Proxy(wsdlFile) File "/home/gordonj/wsdl/jrgSOAPpy/jrgWSDL.py", line 75, in __init__ service = self.wsdl.services[0] File "/home/gordonj/wsdl/jrgwstools/Utility.py", line 631, in __getitem__ return self.list[key] IndexError: list index out of range After poking around in the code a bit more, I think that self.wsdl.services is supposed to be a collection of all the services offered by the wsdl, but it's actually empty, which is why it throws an error when it tries to access the first element. So that's where I'm stuck at the moment. I have no idea why self.wsdl.services isn't getting populated correctly -- or even if that's the real problem! Any suggestions? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From jeanmichel at sequans.com Tue Aug 25 12:36:28 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 25 Aug 2009 18:36:28 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A94130C.9050809@sequans.com> kj wrote: > > I have many years of programming experience, and a few languages, > under my belt, but still Python scoping rules remain mysterious to > me. (In fact, Python's scoping behavior is the main reason I gave > up several earlier attempts to learn Python.) > > Here's a toy example illustrating what I mean. It's a simplification > of a real-life coding situation, in which I need to initialize a > "private" class variable by using a recursive helper function. > > class Demo(object): > def fact(n): > if n < 2: > return 1 > else: > return n * fact(n - 1) > > _classvar = fact(5) > > This code fails to compile, with the error "global name 'fact' not > defined". > [snip] fact is defined within the Demo class, so to access it, you'll need to prefix it with Demo: _classvar = Demo.fact(5). The problem is, Demo will raise a NameError exception. The solution is pretty simple, cause your fact function seems to be unrelated to the Demo class : def _fact(n): # some code class Demo(object): _classvar = _fact(5) It may happen that you *want* your fact within the Demo, in you example it's not that obvious, but I think Java would allow such following patern: class Color: def __init__(self, r, g,b): pass BLACK = Color(0,0,0) It make sens from a design point of view to put BLACK in the Color namespace. But I don't think it's possible with python. You could trick the system using inheritance: class Chrome: def __init__(self, r,g,b) pass Putting all your code in the Chrome class then: class Color(Chrome): BLACK = Chrome(0,0,0) I'm not sure this is satisfying. JM From jeanmichel at sequans.com Tue Aug 25 12:47:20 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Tue, 25 Aug 2009 18:47:20 +0200 Subject: Need help with Python scoping rules In-Reply-To: <7figv3F2m3p0dU1@mid.uni-berlin.de> References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <4A941598.3000207@sequans.com> Diez B. Roggisch wrote > Classes are not scopes. > > Too bad, could have been handy. JM From contact at xavierho.com Tue Aug 25 12:55:41 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 26 Aug 2009 02:55:41 +1000 Subject: Need help with Python scoping rules In-Reply-To: <4A94130C.9050809@sequans.com> References: <4A94130C.9050809@sequans.com> Message-ID: <2d56febf0908250955h6aedb3efp52168a719bfaf5e5@mail.gmail.com> I'm not really quite sure what voodoo I did here, but my code seems to work in Python 3.1.1 in the following way: class Demo(object): def func(self, n): return n * 5 _f = func(None, 5) d = Demo() print(d._f) print(d.func(5)) # OUTPUT 25 25 So, hmm? Regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Aug 25 12:55:41 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 18:55:41 +0200 Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <7fijcdF2kheecU1@mid.uni-berlin.de> Jean-Michel Pichavant wrote: > Diez B. Roggisch wrote >> Classes are not scopes. >> >> > Too bad, could have been handy. Nope. Because then a lot of people would write something like this: class Foo(object): def bar(self): bar() # note the missing self. And this would lead to errors because self was missing from the call to "bar". And you'd need a disambiguation for methodname/global-name-clashes. The global-statement would work, but then code could break when all of a sudden a subclass defines a method that hitherto was only known as global. So via subclassing, you introduce *arbitray* and hard to debug errors. No. I'm certain, not a good idea. Diez From contact at xavierho.com Tue Aug 25 12:58:58 2009 From: contact at xavierho.com (Xavier Ho) Date: Wed, 26 Aug 2009 02:58:58 +1000 Subject: Need help with Python scoping rules In-Reply-To: <7figv3F2m3p0dU1@mid.uni-berlin.de> References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <2d56febf0908250958q96905caw4185c20b9e12cd33@mail.gmail.com> On Wed, Aug 26, 2009 at 2:14 AM, Diez B. Roggisch wrote: > > Classes are not scopes. > > So the above doesn't work because name resolution inside functions/methods > looks for local variables first, then for the *global* scope. There is no > class-scope-lookup. Sorry, I'm coming here with sincere ignorance. If local variables and global variables are not "scopes", then what would it be? Cheers, -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From sdementen at gmail.com Tue Aug 25 13:25:27 2009 From: sdementen at gmail.com (seb) Date: Tue, 25 Aug 2009 10:25:27 -0700 (PDT) Subject: conditional for-statement References: Message-ID: On Aug 23, 11:02?pm, Chris Rebert wrote: > On Sun, Aug 23, 2009 at 1:36 PM, seb wrote: > > On Aug 23, 6:18?pm, John Posner wrote: > >> >> Hi, > > >> >> i was wondering if there is a syntax alike: > > >> >> for i in range(10) if i > 5: > >> >> ? ? print i > > >> > You can write > > >> > for i in filter(lambda i: i > 5, range(10)): > >> > ? ? print i > > >> > but > > >> > for i in range(10): > >> > ? ? if i > 5: > >> > ? ? ? ? print i > > >> > it' better readable, and > > >> > for i in range(6,10): > >> > ? ? print i > > >> > it's event better. > > >> How about using a generator expression instead of a list? > > >> ? for i in (x for x in range(10) if x > 5): > >> ? ? ? print i > > >> -John > > > Indeed, but we could have the same syntax than for generators but > > directly in the for statement as in > > for variable in generator if condition: > > ? ?body > > > Is there a special reason for not doing so ? A rejected PEP ? > > It's not been added since it's completely unnecessary (see the several > alternatives already presented by others). > There have been a few other mailinglist threads on adding essentially > the same syntax. None have proved fruitful. > > Cheers, > Chris > --http://blog.rebertia.com- Hide quoted text - > > - Show quoted text - On Aug 23, 11:02 pm, Chris Rebert wrote: > On Sun, Aug 23, 2009 at 1:36 PM, seb wrote: > > On Aug 23, 6:18 pm, John Posner wrote: > >> >> Hi, > > >> >> i was wondering if there is a syntax alike: > > >> >> for i in range(10) if i > 5: > >> >> print i > > >> > You can write > > >> > for i in filter(lambda i: i > 5, range(10)): > >> > print i > > >> > but > > >> > for i in range(10): > >> > if i > 5: > >> > print i > > >> > it' better readable, and > > >> > for i in range(6,10): > >> > print i > > >> > it's event better. > > >> How about using a generator expression instead of a list? > > >> for i in (x for x in range(10) if x > 5): > >> print i > > >> -John > > > Indeed, but we could have the same syntax than for generators but > > directly in the for statement as in > > for variable in generator if condition: > > body > > > Is there a special reason for not doing so ? A rejected PEP ? > > It's not been added since it's completely unnecessary (see the several > alternatives already presented by others). > There have been a few other mailinglist threads on adding essentially > the same syntax. None have proved fruitful. > > Cheers, > Chris > --http://blog.rebertia.com- Hide quoted text - > > - Show quoted text - Tx Chris for your reply ! i am still a bit puzzle by the following. I read in http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generators """Python 3.0 unifies all collection types by introducing dict and set comprehensions, similar to list comprehensions: >>> [ n*n for n in range(5) ] # regular list comprehension [0, 1, 4, 9, 16] >>> >>> { n*n for n in range(5) } # set comprehension {0, 1, 4, 16, 9} >>> >>> { n: n*n for n in range(5) } # dict comprehension {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} """ and we can add to this list the quite similar syntax for generator expressions. On all these loop constructs, one can consistenly add filtering on a condition by adding an "if ..." after the "for ... in ..." part (and it looks to me difficult to argue, for instance, that we should not allow filtering for dict comprehesion because we could get the same result by some other construct) If the "if ..." part after the "for ... in ..." is so much used in all these list/dict/set comprehensions and in the generator expressions, it makes sense to me to have it also for the "for as a statement" syntax : [ n*n for n in range(10) if n%3 == 0] { n*n for n in range(10) if n%3 == 0} { n: n*n for n in range(10) if n%3 == 0} ( n*n for n in range(10) if n%3 == 0) for n in range(10) if n%3 == 0: print n*n In fact, we often see the list comprehension [ n*n for n in range(10) if n%3 == 0] explained as being equivalent to l = [] for n in range(10): if n%3 == 0: l.append(n) We could as consistenly explain that the syntax for n in range(10) if n%3==0: body means for n in range(10): if n%3==0: body This syntax has also the benefit of avoiding an extra level of indentation (the one for the if) that bears no real meaning on a structural level. Maybe a PEP could do the job... S?bastien From sdementen at gmail.com Tue Aug 25 13:30:15 2009 From: sdementen at gmail.com (seb) Date: Tue, 25 Aug 2009 10:30:15 -0700 (PDT) Subject: conditional for-statement References: Message-ID: <40ae96a4-6f86-4daa-a06b-5556339cb032@c2g2000yqi.googlegroups.com> On Aug 24, 12:05?am, Mel wrote: > seb wrote: > > On Aug 23, 6:18 pm, John Posner wrote: > [ ... ] > >> How about using a generator expression instead of a list? > > >> for i in (x for x in range(10) if x > 5): > >> print i > > >> -John > > > Indeed, but we could have the same syntax than for generators but > > directly in the for statement as in > > for variable in generator if condition: > > ? ? body > > > Is there a special reason for not doing so ? A rejected PEP ? > > Well, the Zen of Python does say > > There should be one-- and preferably only one --obvious way to do it. > > Beyond that, I refer you to Gerald M. Weinberg's _The Psychology of Computer > Programming_, specifically chapters 11 and 12, about Programming Languages, > and their design. > > The proposal creates an case where one particular pair of syntactic > constructs can be mooshed together. ?OK for them, but everything else > becomes an exception; what about > > while a==c if b != d: > > why not > > if b != d while a==c: > what would be the unambiguous meaning of any of these forms ? they could be interesting but I do not understand them (yet!). > or > > for a in range(7) if os.name == 'posix': > > It winds up burdening the programmers with remembering which constructs are > and which are not mooshable. ?Weinberg gave an example: FORTRAN had some > stringent rules for what expressions were and were not allowed as array > subscripts. ?The result was that many programmers couldn't remember all the > rules, and often avoided using legal forms, having forgotten they were > legal. indeed, the language features should stay as orthogonal as possible (at least as a general rule) > > Maybe the line was already crossed when list comprehensions came into being, > still, the damage is localized in a particular context: building a list. ?It > isn't out creating wild options in the program control flow at large. > indeed and it proved to be very useful & successful. one cannot recommend to mix all features together as a general rule but using common sense and practice, we can have some exceptions that are definitely worth. > ? ? ? ? Mel.- Hide quoted text - > > - Show quoted text - From stefan_ml at behnel.de Tue Aug 25 13:53:46 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Tue, 25 Aug 2009 19:53:46 +0200 Subject: Web Services examples using "raw" xml? In-Reply-To: References: <4a936e84$0$31337$9b4e6d93@newsspool4.arcor-online.net> Message-ID: <4a94252a$0$31870$9b4e6d93@newsspool3.arcor-online.net> John Gordon wrote: > Any suggestions? Well, yes, see the link I posted. http://effbot.org/zone/element-soap.htm That might actually be the easiest way to get your stuff done, and it avoids external dependencies (well, except for ElementTree, if you continue to use Python <= 2.4). Stefan From jjposner at optimum.net Tue Aug 25 14:11:32 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 25 Aug 2009 14:11:32 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A942954.7070702@optimum.net> Diez said: > > Classes are not scopes. > > So the above doesn't work because name resolution inside functions/methods > looks for local variables first, then for the *global* scope. There is no > class-scope-lookup. But http://docs.python.org/tutorial/classes.html says, in Section 9.3 "A First Look at Classes": When a class definition is entered, a new namespace is created, and used as the local scope ? thus, all assignments to local variables go into this new namespace. In particular, function definitions bind the name of the new function here. The following example confirms this: class Spam(object): clsvar_1 = 555 clsvar_2 = clsvar_1 + 222 def __init__(self): print "Spam instance initialized" sp = Spam() print sp.clsvar_1, sp.clsvar_2 output: Spam instance initialized 555 777 Does the OP (kj) have a legitimate gripe, though? I confess that I know nothing about Python's implementation -- I'm strictly a user. So it's just a suspicion of mine that something special enables a recursive function definition to refer to the function's own name before the definition has been completed. It works at the module-namespace (i.e. global) level, and Diez's "toy example" shows that it works at function-namespace level: class Demo(object): def fact(n): def inner(n): if n < 2: return 1 else: return n * inner(n - 1) return inner(n) _classvar = fact(5) So why can't it work at the class-namespace level, too? (BTW, Diez, your toy example is another demonstration that there *is* a class-scope-lookup: the "def" statement binds the name "fact" in the class scope, and the assignment statement looks up the name "fact" in that scope.) -John From rami.chowdhury at gmail.com Tue Aug 25 14:17:49 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Tue, 25 Aug 2009 11:17:49 -0700 Subject: conditional for-statement In-Reply-To: References: Message-ID: > We could as consistenly explain that the syntax > > for n in range(10) if n%3==0: > body > > means > > for n in range(10): > if n%3==0: > body > > This syntax has also the benefit of avoiding an extra level of > indentation (the one for the if) that bears no real meaning on a > structural level. > I'm sorry, I don't see what you mean about avoiding the extra level of indentation? I can see a very real structural and logical distinction that the if-block makes, and IMO it's a good thing that that needs to be set apart. On Tue, 25 Aug 2009 10:25:27 -0700, seb wrote: > > Tx Chris for your reply ! > > i am still a bit puzzle by the following. > > I read in > http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generators > > """Python 3.0 unifies all collection types by introducing dict and set > comprehensions, similar to list comprehensions: > >>>> [ n*n for n in range(5) ] # regular list comprehension > [0, 1, 4, 9, 16] >>>> >>>> { n*n for n in range(5) } # set comprehension > {0, 1, 4, 16, 9} >>>> >>>> { n: n*n for n in range(5) } # dict comprehension > {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} > """ > and we can add to this list the quite similar syntax for generator > expressions. > > On all these loop constructs, one can consistenly add filtering on a > condition by adding an "if ..." after the "for ... in ..." part (and > it looks to me difficult to argue, for instance, that we should not > allow filtering for dict comprehesion because we could get the same > result by some other construct) > > If the "if ..." part after the "for ... in ..." is so much used in all > these list/dict/set comprehensions and in the generator expressions, > it makes sense to me to have it also for the "for as a statement" > syntax : > [ n*n for n in range(10) if n%3 == 0] > { n*n for n in range(10) if n%3 == 0} > { n: n*n for n in range(10) if n%3 == 0} > ( n*n for n in range(10) if n%3 == 0) > for n in range(10) if n%3 == 0: > print n*n > > In fact, we often see the list comprehension [ n*n for n in range(10) > if n%3 == 0] explained as being equivalent to > l = [] > for n in range(10): > if n%3 == 0: > l.append(n) > > We could as consistenly explain that the syntax > > for n in range(10) if n%3==0: > body > > means > > for n in range(10): > if n%3==0: > body > > This syntax has also the benefit of avoiding an extra level of > indentation (the one for the if) that bears no real meaning on a > structural level. > > Maybe a PEP could do the job... > > S?bastien -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From sturlamolden at yahoo.no Tue Aug 25 14:25:19 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 25 Aug 2009 11:25:19 -0700 (PDT) Subject: basic thread question References: <20090818201015.GP20434@dragontoe.org> <4a922086$0$1619$742ec2ed@news.sonic.net> <4224e772-5b67-4eea-9bdf-a7d2bf7cc128@c14g2000yqm.googlegroups.com> <864e2d5f-0855-4f35-a78c-b09054e75f0d@w41g2000yqb.googlegroups.com> Message-ID: On 25 Aug, 13:33, Piet van Oostrum wrote: > I have heard about that also, but is there a Python implementation that > uses this? (Just curious, I am not using Windows.) On Windows we have three different versions of Python 2.6: * Python 2.6 for Win32/64 (from python.org) does not have os.fork. * Python 2.6 for Cygwin has os.fork, but it is non-COW and sluggish. * Python 2.6 for SUA has a fast os.fork with copy-on-write. You get Python 2.6.2 for SUA prebuilt by Microsoft from http://www.interopsystems.com. Using Python 2.6 for SUA is not without surprices: For example, the process is not executed from the Win32 subsystem, hence the Windows API is inaccessible. That means we cannot use native Windows GUI. Instead we must run an X11 server on the Windows subsystem (e.g. X- Win32), and use the Xlib SUA has installed. You can compare SUA to a stripped down Linux distro, on which you have to build and install most of the software you want to use. I do not recommend using Python for SUA instead of Python for Windows unless you absolutely need a fast os.fork or have a program that otherwise requires Unix. But for running Unix apps on Windows, SUA is clearly superior to Cygwin. Licencing is also better: Programs compiled against Cygwin libraries are GPL (unless you buy a commercial license). Program compiled against SUA libraries are not. Sturla Molden From nospam at nospam.com Tue Aug 25 14:30:27 2009 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 25 Aug 2009 20:30:27 +0200 Subject: Python for professsional Windows GUI apps? References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: On Tue, 25 Aug 2009 13:24:39 +0200, Wolfgang Keller wrote: >The area of _desktop_ database application development indeed looks like a vast and very hostile desert in the Python landscape. > >The only framework that seems to be worth trying is Dabo. Unfortunately there's little documentation, and that's mostly outdated. > >There's also Kiwi, but that's even less well documented. > >And GNU Enterprise essentially seems to be dead. Combined with the comment above about issues with printing, it looks like Python for GUI apps isn't a very good idea :-/ I'd be interested in checking out commercial applications written in Python for the Windows OS, if there are any. Thank you. From bbxx789_05ss at yahoo.com Tue Aug 25 14:36:46 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 25 Aug 2009 11:36:46 -0700 (PDT) Subject: Need help with Python scoping rules References: Message-ID: <62d4c548-c45f-4345-b9b2-42a7ba7a309a@g1g2000pra.googlegroups.com> On Aug 25, 12:11?pm, John Posner wrote: > Diez said: > > > > > Classes are not scopes. > > > So the above doesn't work because name resolution inside functions/methods > > looks for local variables first, then for the *global* scope. There is no > > class-scope-lookup. > > Buthttp://docs.python.org/tutorial/classes.htmlsays, in Section 9.3 "A > First Look at Classes": > > When a class definition is entered, a new namespace is created, > and used as the local scope ? thus, all assignments to local variables > go into this new namespace. In particular, function definitions bind > the name of the new function here. > > The following example confirms this: > > class Spam(object): > clsvar_1 = 555 > clsvar_2 = clsvar_1 + 222 > > def __init__(self): > print "Spam instance initialized" > > sp = Spam() > print sp.clsvar_1, sp.clsvar_2 > > output: > Spam instance initialized > 555 777 > > Does the OP (kj) have a legitimate gripe, though? I confess that I know I guess a counter example would be something like this: y = "hello" class Demo(object): y = "goodbye" def __init__(self): self.x = 10 print y Demo() --output:-- hello > > nothing about Python's implementation -- I'm strictly a user. So it's > just a suspicion of mine that > something special enables a recursive function definition to refer to > the function's own name before the definition has been completed. > python ignores the names inside a function when it creates the function. This "program" will not produce an error: def f(): print x python parses the file and creates the function object and assigns the function object to the variable f. It's not until you execute the function that python will raise an error. The same thing happens with the recursive function. From david at boddie.org.uk Tue Aug 25 14:37:35 2009 From: david at boddie.org.uk (David Boddie) Date: Tue, 25 Aug 2009 20:37:35 +0200 Subject: Python for professsional Windows GUI apps? References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: On Tuesday 25 August 2009 13:24, Wolfgang Keller wrote: > The area of _desktop_ database application development indeed looks like a > vast and very hostile desert in the Python landscape. > > The only framework that seems to be worth trying is Dabo. Unfortunately > there's little documentation, and that's mostly outdated. > > There's also Kiwi, but that's even less well documented. > > And GNU Enterprise essentially seems to be dead. There's also Camelot, if that's the kind of thing you're after: http://www.conceptive.be/projects/camelot David From sturlamolden at yahoo.no Tue Aug 25 14:39:14 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 25 Aug 2009 11:39:14 -0700 (PDT) Subject: Putting together a larger matrix from smaller matrices References: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> <95-dnVK31vsFnQnXnZ2dnUVZ_qmdnZ2d@pdx.net> Message-ID: <7df5f26b-5f31-4e93-b873-946c99d9a5e4@w41g2000yqb.googlegroups.com> On 25 Aug, 17:37, Matjaz Bezovnik wrote: > Scott, thank you very much for the snippet. > > It is exactly what I looked for; simple to read and obvious as to what > it does even a month later to a non-pythonist! Since you were talking about matrices, observe that numpy has a matrix subclass of ndarray, which e.g. changes the meaning of the * operator mean indicate matrix multiplication. Thus, >>> import numpy as np >>> np.eye(4) array([[ 1., 0., 0., 0.], [ 0., 1., 0., 0.], [ 0., 0., 1., 0.], [ 0., 0., 0., 1.]]) >>> np.matrix(np.eye(4)) matrix([[ 1., 0., 0., 0.], [ 0., 1., 0., 0.], [ 0., 0., 1., 0.], [ 0., 0., 0., 1.]]) >>> a = np.ones((4,4)) >>> a*a array([[ 1., 1., 1., 1.], [ 1., 1., 1., 1.], [ 1., 1., 1., 1.], [ 1., 1., 1., 1.]]) >>> b = np.matrix(a) >>> b*b matrix([[ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.]]) >>> b**2 matrix([[ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.], [ 4., 4., 4., 4.]]) >>> b**4 matrix([[ 64., 64., 64., 64.], [ 64., 64., 64., 64.], [ 64., 64., 64., 64.], [ 64., 64., 64., 64.]]) In Matlab, you use .* vs. * and .^ vs. ^ to obtain the same effect. In NumPy we use different classes for arrays and matrices. Sturla Molden From robert.kern at gmail.com Tue Aug 25 14:42:31 2009 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 25 Aug 2009 13:42:31 -0500 Subject: Putting together a larger matrix from smaller matrices In-Reply-To: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> References: <0si695db7bm7rfelo9iud89d8vda32176r@4ax.com> Message-ID: On 2009-08-24 21:30 PM, Matjaz Bezovnik wrote: > Dear all, > > I'm but a layman so do not take offence at this maybe over simple > question. > > This is something which is done often in FEM methods, and the alike. > > I have matrix A of 3x3 elements, and B, of the same number of > elements, 3x3. > > What would be the most obvious way to assemble a matrix which: > a11 a12 a13 > a21 a22 a23 > a31 a32 a33+b11 b12 b13 > b21 b22 b23 > b31 b32 b33 > > (the missing elements = zero) > > (you see the pattern - if there was a third matrix C, it would > "connect" to b33 on the main diagonal) You will certainly want to use numpy for this and ask questions on the numpy mailing list. http://www.scipy.org/Mailing_Lists I believe that someone recently posted a recipe for constructing such "block diagonal" arrays. I think it will be included in a future release of numpy. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From thebiggestbangtheory at gmail.com Tue Aug 25 14:42:31 2009 From: thebiggestbangtheory at gmail.com (nickname) Date: Tue, 25 Aug 2009 11:42:31 -0700 (PDT) Subject: os.popen output different from native shell output References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Message-ID: On Aug 25, 6:16?am, Nobody wrote: > On Tue, 25 Aug 2009 01:36:08 -0700, nickname wrote: > > ? ? ? ?I am a relative newbie to python, I am using os.popen to run an > > ls command. The output that I get using the read() function is > > different in look and feel from when I run the ls command natively > > from the shell (not via python). > > As others have pointed out, the default behaviour of ls is different if > its output is a terminal. > > > Is there an easy way to "mirror" the output. When python displays the > > output, how can it tell the bash shell that some of the entries are > > directories and they should appear blue on the bash shell, and that > > everything should not be appearing on 1 column only. > > You can get the terminal-style behaviour even when using a pipe with: > > ? ? ? ? ls -x --color > > But why are you reading this information into Python then writing it > back out to the terminal? > > If you're planning on processing the output within Python, both the > multi-column format and the escape sequences used for colour will make > such processing awkward. > > If you want to enumerate the contents of a directory within Python, use > os.listdir(). > > If you want to generate coloured output, use the curses module, e.g.: > > #!/usr/bin/env python > > import sys > import curses > > curses.setupterm() > setaf = curses.tigetstr('setaf') or "" > setab = curses.tigetstr('setab') or "" > origp = curses.tigetstr('op') or "" > > def fg(c): > ? ? sys.stdout.write(curses.tparm(setaf, c)) > > def bg(c): > ? ? sys.stdout.write(curses.tparm(setab, c)) > > def orig(): > ? ? sys.stdout.write(origp) > > # example > bg(curses.COLOR_BLUE) > fg(curses.COLOR_YELLOW) > print "hello, world" > orig() wow guys! thanks for all the great leads! this is awesome! The reason why I want to do this is because I am going to do a little project. I will write a python script called ls which will log the time and username and then will show the actual ls output. I want this to be transparent and so want to throw the ls output (via python) exactly as it will be in native shell execution. I know there's history files I can look up, but I just am exploring my own intermediate-logging-layer the functionality for which is executed right before the actual command is executed. Thanks, -A From sturlamolden at yahoo.no Tue Aug 25 14:44:11 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 25 Aug 2009 11:44:11 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: On 25 Aug, 20:30, Gilles Ganault wrote: > Combined with the comment above about issues with printing, it looks > like Python for GUI apps isn't a very good idea :-/ With pywin32, printing is the same as for any other Windows app (you get MFC for Python). From mensanator at aol.com Tue Aug 25 14:45:28 2009 From: mensanator at aol.com (Mensanator) Date: Tue, 25 Aug 2009 11:45:28 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> Message-ID: On Aug 25, 9:14?am, Steven D'Aprano wrote: > On Mon, 24 Aug 2009 18:01:38 -0700, Mensanator wrote: > >> If you want your data file to have values entered in hex, or oct, or > >> even unary (1=one, 11=two, 111=three, 1111=four...) you can. > > > Unary? I think you'll find that Standard Positional Number Systems are > > not defined for radix 1. > > Of course not. But unary isn't a positional number system. It's a tally > system, like my example above shows. Roman numerals are another tally > system. Like Roman numerals, the disadvantages of unary are that you > can't represent negative numbers, zero, or fractions, and anything but > addition and subtraction is difficult. But if you want to use it, perhaps > out of a sense of sadism towards your users, it's easy: > > def int2unary(n): > ? ? return '1'*n > > def unary2int(s): > ? ? n = 0 > ? ? for c in s: > ? ? ? ? if c == '1': n+=1 > ? ? ? ? else: raise ValueError('invalid unary string') > ? ? return n But without insignificant leading 0's, I fail to see the relevance of unary to this discussion. And what would you call a tally system of radix 2? Certainly not binary. > > -- > Steven From robert.kern at gmail.com Tue Aug 25 14:54:10 2009 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 25 Aug 2009 13:54:10 -0500 Subject: your favorite debugging tool? In-Reply-To: <87skfgeynf.fsf@benfinney.id.au> References: <87vdkfiaki.fsf@benfinney.id.au> <87skfgeynf.fsf@benfinney.id.au> Message-ID: On 2009-08-25 09:49 AM, Ben Finney wrote: > Esmail writes: > >> Hi Ben, >> >> Ben Finney wrote: >>> >>> Whenever a simple output statement is too cumbersome for debugging, I >>> take it as a sign that the program is too cumbersome to follow. >> >> I'll have to think about this .. though my gut says this is true :-) > > Note that it's only a sign, *not* an ironclad guarantee. But it's the > right way to bet, IME. > >> re your other point about the interactive shell, I agree it's useful, >> but to me still doesn't quite do what a full-fledged debugger can - >> but perhaps that is a reflection of my skill with the shell at this >> point. > > This, on the other hand, I find even more consistent: if the code can't > be effectively inspected from the interactive interpreter, that's a sure > sign that its external interfaces are poor or its internal dependencies > too tightly coupled; or more likely both. And a debugger is a great tool to help you figure out exactly why your code doesn't actually have the wonderful decoupling that you thought you designed into it so you can fix it. :-) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sturlamolden at yahoo.no Tue Aug 25 14:54:21 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 25 Aug 2009 11:54:21 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: <7d48a1c7-b406-499e-a0e1-3c7d3b91d8a0@k30g2000yqf.googlegroups.com> On 25 Aug, 13:24, Wolfgang Keller wrote: > The area of _desktop_ database application development indeed looks like a vast and very hostile desert in the Python landscape. Yes, you don't have drag-and-drop database tools like MS Access or FoxPro. You actually have to use a database API (such as pyodbc or pymssql) with GUI (tkinter, wxPython, PyGTK, PyQt, MFC) manually. If you need a framework for this, you should not be developing software anyway. From robert.kern at gmail.com Tue Aug 25 14:55:28 2009 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 25 Aug 2009 13:55:28 -0500 Subject: your favorite debugging tool? In-Reply-To: References: <57d65219-8134-4c2e-9739-825a5ef450d0@s15g2000yqs.googlegroups.com> Message-ID: On 2009-08-25 06:57 AM, Esmail wrote: > Michele Simionato wrote: >> On Aug 22, 4:25 pm, Esmail wrote: >>> Hi all, >>> >>> What is your favorite tool to help you debug your >>> code? >> >> The times when I would just use 'print' are long past. Nowadays I >> spend lots of my time >> with code written by others than myself. I use pdb all the time, and >> now also ipdb >> (ipdb is very cool if you are used to ipython). > > Never heard of ipdb, I'll have to check it out. It's not really a separate thing, just the pdb integration into the IPython interactive shell (which I highly recommend that you check out). -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From guettli at thomas-guettler.de Tue Aug 25 14:57:59 2009 From: guettli at thomas-guettler.de (Thomas Guettler) Date: Tue, 25 Aug 2009 20:57:59 +0200 Subject: os.popen output different from native shell output In-Reply-To: References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Message-ID: <7fiqhnF2l2bs6U1@mid.individual.net> In one of the first chapters of "Advanced programming in the unix environment (second edition)" there is explained how a unix shell works. You could write you own shell using python. This way the python interpreter gets stared only once, and not for every call to "ls". Have fun, Thomas nickname schrieb: > wow guys! thanks for all the great leads! this is awesome! > > The reason why I want to do this is because I am going to do a little > project. I will write a python script called ls which will log the > time and username and then will show the actual ls output. I want this > to be transparent and so want to throw the ls output (via python) > exactly as it will be in native shell execution. From travis at subspacefield.org Tue Aug 25 15:16:59 2009 From: travis at subspacefield.org (travis at subspacefield.org) Date: Tue, 25 Aug 2009 14:16:59 -0500 Subject: proposal: add setresuid() system call to python In-Reply-To: <87d46kdp0v.fsf@busola.homelinux.net> References: <20090717200141.GI6065@subspacefield.org> <148918f0907171315i4ed5b274v77581a43c4464f8f@mail.gmail.com> <7cj89qF27mfrjU1@mid.uni-berlin.de> <877hy38mxw.fsf@busola.homelinux.net> <20090821205040.GK1215@subspacefield.org> <87d46kdp0v.fsf@busola.homelinux.net> Message-ID: <20090825191659.GL1215@subspacefield.org> On Tue, Aug 25, 2009 at 03:03:12PM +0200, Hrvoje Niksic wrote: > You should use ctypes.get_errno() instead of os.errno; sorry about that. > > Also, when raising OSError, you should set the 'errno' attribute to the > appropriate code. How does that compare to: raise pythonapi.PyErr_SetFromErrno(py_object(OSError)) ? -- Obama Nation | My emails do not have attachments; it's a digital signature that your mail program doesn't understand. | http://www.subspacefield.org/~travis/ If you are a spammer, please email john at subspacefield.org to get blacklisted. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 850 bytes Desc: not available URL: From aahz at pythoncraft.com Tue Aug 25 15:19:33 2009 From: aahz at pythoncraft.com (Aahz) Date: 25 Aug 2009 12:19:33 -0700 Subject: Waiting for a subprocess to exit References: <873a7l21gr.fsf@benfinney.id.au> Message-ID: In article , Miles Kaufmann wrote: > >debacle[1]). Leaving shell=3DFalse makes scripts more secure and =20 >robust; besides, when I'm putting together a command and its =20 >arguments, it's as convenient to build a list (['mycmd', 'myarg']) as =20= > >it is a string (if not more so). ....unless you want to use "~" on Mac or Unix. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From jason at nospam.org Tue Aug 25 15:21:25 2009 From: jason at nospam.org (jason) Date: Tue, 25 Aug 2009 13:21:25 -0600 Subject: Simple IRC library References: <752884c5-c6fb-4974-a21a-bf3017fa4145@y4g2000prf.googlegroups.com> Message-ID: <2009082513212516807-jason@nospamorg> On 2009-08-24 01:39:21 -0600, devaru said: > Hi all, > I am new to Python language. I want to capture(either in database or a > file) the conversation in IRC. Fed. > Please suggest me some simple IRC library or code snippet for this. I have used the oyoyo library with success. It's pretty nice and has a framework for bots which you might be interested in looking at. http://code.google.com/p/oyoyo/ From jjposner at optimum.net Tue Aug 25 15:31:48 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 25 Aug 2009 15:31:48 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A943C24.6090209@optimum.net> 7stud said: > python ignores the names inside a function when it creates the > function. This "program" will not produce an error: > > > def f(): > print x > > python parses the file and creates the function object and assigns the > function object to the variable f. It's not until you execute the > function that python will raise an error. The same thing happens with > the recursive function. > Thanks for that explanation. So in the OP's example: Class Demo(object): def fact(n): if n < 2: return 1 else: return n * fact(n - 1) _classvar = fact(5) ... no failure occurs when "fact(5)" is invoked, because the lookup of "fact" in the local scope is a class-scope-lookup, which succeeds. The failure occurs on the first recursive invocation of fact() in the statement "return n * fact(n - 1)": the function-scope-lookup of "fact" fails, and then the interpreter falls back to a global-scope-lookup of "fact", which also fails. From aahz at pythoncraft.com Tue Aug 25 15:32:09 2009 From: aahz at pythoncraft.com (Aahz) Date: 25 Aug 2009 12:32:09 -0700 Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: In article , Hendrik van Rooyen wrote: >On Friday 21 August 2009 08:07:18 josef wrote: >> >> My main focus of this post is: "How do I find and use object reference >> memory locations?" > >>>> a = [1,2,3,4] >>>> id(a) >8347088 >>>> Of course, that doesn't actually allow you to do anything... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From evaned at gmail.com Tue Aug 25 15:33:51 2009 From: evaned at gmail.com (Evan Driscoll) Date: Tue, 25 Aug 2009 12:33:51 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] Message-ID: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> (If you don't want to read the following, note that you can answer my question by writing a swap function.) I want to make a context manager that will temporarily change the value of a variable within the scope of a 'with' that uses it. This is inspired by a C++ RAII object I've used in a few projects. Ideally, what I want is something like the following: x = 5 print x # prints 5 with changed_value(x, 10): print x # prints 10 print x # prints 5 This is similar to PEP 343's example 5 ("Redirect stdout temporarily"; see http://www.python.org/dev/peps/pep-0343/), except that the variable that I want to temporarily change isn't hard-coded in the stdout_redirected function. What I want to write is something like this: @contextmanager def changed_value(variable, temp_value): old_value = variable variable = temp_value try: yield None finally: variable = old_value with maybe a check in 'finally' to make sure that the value hasn't changed during the execution of the 'with'. Of course this doesn't work since it only changes the binding of 'variable', not whatever was passed in, and I kind of doubt I can stick a "&" and "*" in a couple places to make it do what I want. :-) So my question is: is what I want possible to do in Python? How? I think it might be possible to rig something up by passing in the variable that i want to change as a *string* and looking up that string in a dictionary somewhere, but I think what I need is the locals () dictionary of the calling function, and I'm not sure how to get that. Thanks, Evan Driscoll From garrickp at gmail.com Tue Aug 25 15:42:34 2009 From: garrickp at gmail.com (Falcolas) Date: Tue, 25 Aug 2009 12:42:34 -0700 (PDT) Subject: conditional for-statement References: Message-ID: On Aug 25, 11:25?am, seb wrote: > We could as consistenly explain that the syntax > > for n in range(10) if n%3==0: > ? body > > means > > for n in range(10): > ? if n%3==0: > ? ? body > > This syntax has also the benefit of avoiding an extra level of > indentation (the one for the if) that bears no real meaning on a > structural level. > > Maybe a PEP could do the job... > > S?bastien So, what part of the statement does the "if" statement belong to; particularly a concern considering this is valid python: for x in y if y else z: body You can always do the following at the cost of 6 symbols, and the gain of clarity: for n in (x for x in y if y%3==0): body ~G From tjreedy at udel.edu Tue Aug 25 15:45:09 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 25 Aug 2009 15:45:09 -0400 Subject: Python, qt, and lgpl Message-ID: " New LGPL Python bindings for Qt slither into the light A new set of LGPL-licensed Python bindings for Qt has been announced. The project, which is backed by Nokia, will make it easier for commercial software developers to adopt Python and Qt for rapid application development." http://arstechnica.com/open-source/news/2009/08/openbossa-announces-new-lgpl-python-bindings-for-qt.ars Will be good news if realized. From rurpy at yahoo.com Tue Aug 25 15:45:49 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Tue, 25 Aug 2009 12:45:49 -0700 (PDT) Subject: break unichr instead of fix ord? Message-ID: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> In Python 2.5 on Windows I could do [*1]: # Create a unicode character outside of the BMP. >>> a = u'\U00010040' # On Windows it is represented as a surogate pair. >>> len(a) 2 >>> a[0],a[1] (u'\ud800', u'\udc40') # Create the same character with the unichr() function. >>> a = unichr (65600) >>> a[0],a[1] (u'\ud800', u'\udc40') # Although the unichr() function works fine, its # inverse, ord(), doesn't. >>> ord (a) TypeError: ord() expected a character, but string of length 2 found On Python 2.6, unichr() was "fixed" (using the word loosely) so that it too now fails with characters outside the BMP. >>> a = unichr (65600) ValueError: unichr() arg not in range(0x10000) (narrow Python build) Why was this done rather than changing ord() to accept a surrogate pair? Does not this effectively make unichr() and ord() useless on Windows for all but a subset of unicode characters? From emile at fenx.com Tue Aug 25 15:48:41 2009 From: emile at fenx.com (Emile van Sebille) Date: Tue, 25 Aug 2009 12:48:41 -0700 Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] In-Reply-To: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> Message-ID: On 8/25/2009 12:33 PM Evan Driscoll said... > So my question is: is what I want possible to do in Python? Probably not with immutables (as in your example) -- maybe otherwise. Emile From sdementen at gmail.com Tue Aug 25 15:58:38 2009 From: sdementen at gmail.com (seb) Date: Tue, 25 Aug 2009 12:58:38 -0700 (PDT) Subject: conditional for-statement References: Message-ID: <14afbe5a-62e7-4944-ab9d-42b86530ac41@s31g2000yqs.googlegroups.com> On Aug 25, 9:42?pm, Falcolas wrote: > On Aug 25, 11:25?am, seb wrote: > > > > > We could as consistenly explain that the syntax > > > for n in range(10) if n%3==0: > > ? body > > > means > > > for n in range(10): > > ? if n%3==0: > > ? ? body > > > This syntax has also the benefit of avoiding an extra level of > > indentation (the one for the if) that bears no real meaning on a > > structural level. > > > Maybe a PEP could do the job... > > > S?bastien > > So, what part of the statement does the "if" statement belong to; > particularly a concern considering this is valid python: > > for x in y if y else z: > ? ? body > can this be done in list/set/dict comprehensions/generator expressions ? > You can always do the following at the cost of 6 symbols, and the gain > of clarity: > > for n in (x for x in y if y%3==0): > ? ? body it is in fact precisely to avoid this sort of line: for n in (x for x in y if x%3==0): and have instead the (more readable IMO) line for n in y if n%3==0: with: - 1 "for ... in ..." instead of 2 (where one is the repetition of the other) - no parentheses - no extra technical variable with local binding to the expression generator ('x') it looks more pythonic to me but it is a personal taste. > > ~G From evaned at gmail.com Tue Aug 25 16:07:13 2009 From: evaned at gmail.com (Evan Driscoll) Date: Tue, 25 Aug 2009 13:07:13 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> Message-ID: <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> On Aug 25, 2:33?pm, Evan Driscoll wrote: > I want to make a context manager that will temporarily change the > value of a variable within the scope of a 'with' that uses it. This is > inspired by a C++ RAII object I've used in a few projects. Ideally, > what I want is something like the following: Okay, so I think I actually got this with some consultation with a friend. Critiques? from contextlib import contextmanager import inspect def get_parents_var(offset, var): f = inspect.stack()[offset][0] if var in f.f_locals: return f.f_locals[var] else: return f.f_globals[var] def set_parents_var(offset, var, val): f = inspect.stack()[offset][0] if var in f.f_locals: f.f_locals[var] = val elif var in f_globals: f.f_globals[var] = val else: assert False @contextmanager def changed_value_tb(var_name, temp_value): # 1 is here, 2 will be the implicit next() function, 3 is the real caller offset = 3 old_value = get_parents_var(offset, var_name) set_parents_var(offset, var_name, temp_value) try: yield None finally: set_parents_var(offset, var_name, old_value) x = 5 print x # prints 5 with changed_value_tb("x", 10): print x # prints 10 print x # prints 5 From deets at nospam.web.de Tue Aug 25 16:10:00 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 22:10:00 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <7fiuooF2l2oogU1@mid.uni-berlin.de> John Posner schrieb: > Diez said: >> >> Classes are not scopes. >> So the above doesn't work because name resolution inside >> functions/methods >> looks for local variables first, then for the *global* scope. There is no >> class-scope-lookup. > > But http://docs.python.org/tutorial/classes.html says, in Section 9.3 "A > First Look at Classes": > > When a class definition is entered, a new namespace is created, > and used as the local scope ? thus, all assignments to local variables > go into this new namespace. In particular, function definitions bind > the name of the new function here. > > > The following example confirms this: > > class Spam(object): > clsvar_1 = 555 > clsvar_2 = clsvar_1 + 222 > > def __init__(self): > print "Spam instance initialized" > > sp = Spam() > print sp.clsvar_1, sp.clsvar_2 > > output: > Spam instance initialized > 555 777 > > > Does the OP (kj) have a legitimate gripe, though? I confess that I know > nothing about Python's implementation -- I'm strictly a user. So it's > just a suspicion of mine that > something special enables a recursive function definition to refer to > the function's own name before the definition has been completed. It > works at the module-namespace (i.e. global) level, and Diez's "toy > example" shows that it works at function-namespace level: > > class Demo(object): > > def fact(n): > def inner(n): > if n < 2: > return 1 > else: > return n * inner(n - 1) > return inner(n) > > _classvar = fact(5) > > > So why can't it work at the class-namespace level, too? See my other post on what name lookup with class-scope *inside* functions would mean. Diez From deets at nospam.web.de Tue Aug 25 16:14:48 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 22:14:48 +0200 Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] In-Reply-To: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> Message-ID: <7fiv1oF2l2ejnU1@mid.uni-berlin.de> Evan Driscoll schrieb: > (If you don't want to read the following, note that you can answer my > question by writing a swap function.) > > I want to make a context manager that will temporarily change the > value of a variable within the scope of a 'with' that uses it. This is > inspired by a C++ RAII object I've used in a few projects. Ideally, > what I want is something like the following: > > x = 5 > print x # prints 5 > with changed_value(x, 10): > print x # prints 10 > print x # prints 5 > > This is similar to PEP 343's example 5 ("Redirect stdout temporarily"; > see http://www.python.org/dev/peps/pep-0343/), except that the > variable that I want to temporarily change isn't hard-coded in the > stdout_redirected function. > > What I want to write is something like this: > @contextmanager > def changed_value(variable, temp_value): > old_value = variable > variable = temp_value > try: > yield None > finally: > variable = old_value > with maybe a check in 'finally' to make sure that the value hasn't > changed during the execution of the 'with'. > > Of course this doesn't work since it only changes the binding of > 'variable', not whatever was passed in, and I kind of doubt I can > stick a "&" and "*" in a couple places to make it do what I want. :-) > > So my question is: is what I want possible to do in Python? How? No. And unfortunately, the with-statement (as the for-statement and others) leaks it's name, so you can't even use it like this: with changed_value(variable, temp_value) as new_name: ... The new_name will be defined afterwards. Diez From travis+ml-python at subspacefield.org Tue Aug 25 16:15:35 2009 From: travis+ml-python at subspacefield.org (travis+ml-python at subspacefield.org) Date: Tue, 25 Aug 2009 15:15:35 -0500 Subject: proposal: add setresuid() system call to python In-Reply-To: <20090821201312.GJ1215@subspacefield.org> References: <20090717200141.GI6065@subspacefield.org> <20090717205953.2543.1223422516.divmod.quotient.3129@henry.divmod.com> <20090821201312.GJ1215@subspacefield.org> Message-ID: <20090825201535.GM1215@subspacefield.org> On Fri, Aug 21, 2009 at 03:13:12PM -0500, travis at subspacefield.org wrote: > Since the authors of the paper (Wagner et. al.) are proposing a new > set of APIs to make all of this clearer, I'm thinking that I will > create a module specifically for dropping permissions. I've created the module here: http://www.subspacefield.org/~travis/python/privilege/ I could sure use any comments people had on my python style. PyPi link: http://pypi.python.org/pypi/privilege/1.0 -- Obama Nation | My emails do not have attachments; it's a digital signature that your mail program doesn't understand. | http://www.subspacefield.org/~travis/ If you are a spammer, please email john at subspacefield.org to get blacklisted. -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 850 bytes Desc: not available URL: From apt.shansen at gmail.com Tue Aug 25 16:16:24 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Tue, 25 Aug 2009 13:16:24 -0700 Subject: Need help with Python scoping rules In-Reply-To: <4A942954.7070702@optimum.net> References: <4A942954.7070702@optimum.net> Message-ID: <7a9c25c20908251316k2ebc304fk1422c96ddb4158c4@mail.gmail.com> > > > But http://docs.python.org/tutorial/classes.html says, in Section 9.3 "A > First Look at Classes": > > When a class definition is entered, a new namespace is created, > and used as the local scope ? thus, all assignments to local variables > go into this new namespace. In particular, function definitions bind > the name of the new function here. > > [snip] > > (BTW, Diez, your toy example is another demonstration that there *is* a > class-scope-lookup: the "def" statement binds the name "fact" in the class > scope, and the assignment statement looks up the name "fact" in that scope.) > This sounds like a fundamental confusion -- a namespace is not equivalent to a scope, really, I think. The def statement creates a function object, and assigns it to the given name, in its /local scope/ which is the class's namespace -- but that is not a new scope. Its just, during class creation, the local scope. When you enter a class definition, a new namespace is created, and that is used as the local scope during the class's definition. Under "class Foo", the local scope is this class's namespace-- and the global scope is the module's namespace. Any lookup operation checks first in the local scope, then in the global scope... When the "def fact(...)" is executed (note that class bodies are executed on load, function bodies aren't), a new namespace is created as well-- the function's namespace-- and its used as the local scope. During execution of the code, it looks up in the local scope first-- and then it looks up in the global scope if it doesn't find anything. There /is/ no class-lookup-scope... but there IS a class namespace. There's just those two scopes: but the namespace bound to those scopes changes as you enter different parts of the code. For a long time that's all there was, just the local and global scope: to access any other namespace required you to explicitly address it. The class namespace remains accessible only via explicit addressing, but PEP 227 in Python 2.1/2.2 introduced static nested scopes. But that applies only to enclosing functions: embedding one function into another. You can only call recursive functions if the function is able to refer to itself according to the same lookup rules: is the function's name in the local scope? No it's not... is it in the global scope? No? Then it can't call itself recursively... well, unless its a method, and it addresses itself specifically-- with "self.". The OP's probably is that during the execution of the class body, the class doesn't exist... so the 'def fact' -can't- use Classname.fact to address itself explicitly, and within fact the locals don't contain a reference to the function itself, and its globals don't either. You just can't do that. The right way, IMHO, is to move 'fact' up and out of the class into a _fact global variable. Alternatively, you can use a metaclass. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From evaned at gmail.com Tue Aug 25 16:24:08 2009 From: evaned at gmail.com (Evan Driscoll) Date: Tue, 25 Aug 2009 13:24:08 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> Message-ID: On Aug 25, 3:07?pm, Evan Driscoll wrote: > Okay, so I think I actually got this with some consultation with a > friend. Critiques? This is wrong; it's not quite working right. It does with the example I posted, but not in a more thorough test. I'm still ignoring the "you can't do this" answers for a little while more and continuing to try to hack on it. :-) Evan From deets at nospam.web.de Tue Aug 25 16:25:31 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 25 Aug 2009 22:25:31 +0200 Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] In-Reply-To: <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> Message-ID: <7fivlrF2lsrsuU1@mid.uni-berlin.de> Evan Driscoll schrieb: > On Aug 25, 2:33 pm, Evan Driscoll wrote: >> I want to make a context manager that will temporarily change the >> value of a variable within the scope of a 'with' that uses it. This is >> inspired by a C++ RAII object I've used in a few projects. Ideally, >> what I want is something like the following: > > Okay, so I think I actually got this with some consultation with a > friend. Critiques? Modifying locals isn't really allowed - it might stop working with certain implementations of python. And to be honest - I don't really see a use-case for your whole approache. Why don't you want to introduce a new name? Diez From thebiggestbangtheory at gmail.com Tue Aug 25 16:32:57 2009 From: thebiggestbangtheory at gmail.com (nickname) Date: Tue, 25 Aug 2009 13:32:57 -0700 (PDT) Subject: os.popen output different from native shell output References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> <7fiqhnF2l2bs6U1@mid.individual.net> Message-ID: On Aug 25, 11:57?am, Thomas Guettler wrote: > In one of the first chapters of "Advanced programming in the unix > environment (second edition)" there is explained how a unix shell works. > > You could write you own shell using python. This way the python > interpreter gets stared only once, and not for every call to "ls". > > Have fun, > ? Thomas > > nickname schrieb: > > > wow guys! thanks for all the great leads! this is awesome! > > > The reason why I want to do this is because I am going to do a little > > project. I will write a python script called ls which will log the > > time and username and then will show the actual ls output. I want this > > to be transparent and so want to throw the ls output (via python) > > exactly as it will be in native shell execution. > > very good point, I will look it up :-) From ebonak at hotmail.com Tue Aug 25 16:33:53 2009 From: ebonak at hotmail.com (Esmail) Date: Tue, 25 Aug 2009 16:33:53 -0400 Subject: your favorite debugging tool? In-Reply-To: <87skfgeynf.fsf@benfinney.id.au> References: <87vdkfiaki.fsf@benfinney.id.au> <87skfgeynf.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Esmail writes: > >> Hi Ben, >> >> Ben Finney wrote: >>> Whenever a simple output statement is too cumbersome for debugging, I >>> take it as a sign that the program is too cumbersome to follow. >> I'll have to think about this .. though my gut says this is true :-) > > Note that it's only a sign, *not* an ironclad guarantee. But it's the > right way to bet, IME. :-) .. I took it as a rule of thumb too .. I didn't meant to imply anything more serious. These design guidelines help though. Thanks, Esmail From garrickp at gmail.com Tue Aug 25 16:46:19 2009 From: garrickp at gmail.com (Falcolas) Date: Tue, 25 Aug 2009 13:46:19 -0700 (PDT) Subject: conditional for-statement References: <14afbe5a-62e7-4944-ab9d-42b86530ac41@s31g2000yqs.googlegroups.com> Message-ID: <4720bbf4-1be7-4f02-9869-df8e0cd9e221@y10g2000prf.googlegroups.com> On Aug 25, 1:58?pm, seb wrote: > On Aug 25, 9:42?pm, Falcolas wrote: > > On Aug 25, 11:25?am, seb wrote: > > So, what part of the statement does the "if" statement belong to; > > particularly a concern considering this is valid python: > > > for x in y if y else z: > > ? ? body > > can this be done in list/set/dict comprehensions/generator > expressions ? It's a statement, so anywhere you use a statement (such as in generators and list comprehensions), it can exist. for ... in ... only requires that the statement return an iterable, it doesn't matter what statement you use to get there. For example, the following is perfectly valid (if nonsensical - I don't use ternary operators very often in my programming, so I don't have many good examples of their use) list = [x if x else y for x, y in iterable] > it is in fact precisely to avoid this sort of line: > ? for n in (x for x in y if x%3==0): > and have instead the (more readable IMO) line > ? for n in y if n%3==0: > with: > ?- 1 "for ... in ..." instead of 2 (where one is the repetition of the > other) > ?- no parentheses > ?- no extra technical variable with local binding to the expression > generator ('x') > it looks more pythonic to me but it is a personal taste. > It doesn't feel clear to me, which is why I would have to disagree. IIRC, these very filters are the main reason that list comprehensions, and later one-line generators and dictionary comprehensions were originally created: so you can filter the stream before acting on it. One statement performs one action - very precise and understandable. It's just my two cents, but I would not agree that adding a filter keyword to for loops is required. Not when we have the filter function, various types of comprehensions, and if statements which all provide that very functionality. ~G From evaned at gmail.com Tue Aug 25 16:47:17 2009 From: evaned at gmail.com (Evan Driscoll) Date: Tue, 25 Aug 2009 13:47:17 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> <7fivlrF2lsrsuU1@mid.uni-berlin.de> Message-ID: On Aug 25, 3:25?pm, "Diez B. Roggisch" wrote: > Modifying locals isn't really allowed - it might stop working with > certain implementations of python. > > And to be honest - I don't really see a use-case for your whole > approache. Why don't you want to introduce a new name? Wow, this actually was very helpful, because it forced me to clarify what I'm doing to myself, and I *am* making it rather too complicated. The reason that I can't introduce a new name is that I want to call another function that refers to the old name. (Specifically, I'm using this in a testing framework, and I want to mock out some things like file I/O so want to replace 'open' and others temporarily. I don't really want to make said function take an extra parameter which is "the open function to use" or something like that.) But then I don't need to modify locals. In fact, the references that I want to affect are used in a function that isn't even on the stack when the "with" statement is entered! So I only need to modify a global, which is much easier than what I was mucking about with. So here is my simplified version that only works for globals: from contextlib import contextmanager @contextmanager def changed_value(var_name, temp_value): old_value = globals()[var_name] globals()[var_name] = temp_value try: yield None finally: globals()[var_name] = old_value x = 5 print "5:", x with changed_value("x", 10): print "10:", x print "5:", x y = 7 def test(): print "5:", x with changed_value("x", 20): print "20:", x print "7:", y print "5:", x test() print "5:", x How does that look? And thanks for making me think about what I'm doing. :-) Evan From gbelov at gmail.com Tue Aug 25 16:51:14 2009 From: gbelov at gmail.com (Gleb Belov) Date: Tue, 25 Aug 2009 13:51:14 -0700 (PDT) Subject: Is it a bug? Message-ID: <87b7ce88-1f2f-43ff-8096-6a95a89b6e27@e27g2000yqm.googlegroups.com> Hey everyone! I'm quite new to Python and equally new to newsgroups in general, so apologies if this makes no sense. Basically, I was just exploring Python "arrays" on my own, since I come from C++. What I did was: >>> words = ["Hi!", "What's up?", "Bye!"] >>> print words ['Hi!', "What's up?", 'Bye!'] I have two questions: 1) Is it possible and if so, how do I access each individual element? Are there any indexes and what is the syntax? 2) I just noticed that the first and the last words in the output are enclosed in single quotes, and the middle one is enclosed in double quotes. Is it a bug? If not, why does the output work that way? Alright, thanks in advance for any replies and I hope I'll manage to actually find this topic... From somebody at somewhere.com Tue Aug 25 16:59:00 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Tue, 25 Aug 2009 21:59:00 +0100 Subject: Is it a bug? References: <87b7ce88-1f2f-43ff-8096-6a95a89b6e27@e27g2000yqm.googlegroups.com> Message-ID: Gleb Belov wrote: > Hey everyone! I'm quite new to Python and equally new to newsgroups in > general, so apologies if this makes no sense. > > Basically, I was just exploring Python "arrays" on my own, since I > come from C++. What I did was: >>>> words = ["Hi!", "What's up?", "Bye!"] >>>> print words > ['Hi!', "What's up?", 'Bye!'] > > I have two questions: > 1) Is it possible and if so, how do I access each individual element? > Are there any indexes and what is the syntax? For the first element: >>> words[0] > 2) I just noticed that the first and the last words in the output are > enclosed in single quotes, and the middle one is enclosed in double > quotes. Is it a bug? If not, why does the output work that way? The output is valid python code. To represent with single quotes for the second item, there would have to be a \ escape character for the apostrophe. -- Stephen Fairchild From gbelov at gmail.com Tue Aug 25 17:12:47 2009 From: gbelov at gmail.com (Gleb Belov) Date: Tue, 25 Aug 2009 14:12:47 -0700 (PDT) Subject: Is it a bug? References: <87b7ce88-1f2f-43ff-8096-6a95a89b6e27@e27g2000yqm.googlegroups.com> Message-ID: On Aug 26, 12:59?am, Stephen Fairchild wrote: > Gleb Belov wrote: > > Hey everyone! I'm quite new to Python and equally new to newsgroups in > > general, so apologies if this makes no sense. > > > Basically, I was just exploring Python "arrays" on my own, since I > > come from C++. What I did was: > >>>> words = ["Hi!", "What's up?", "Bye!"] > >>>> print words > > ['Hi!', "What's up?", 'Bye!'] > > > I have two questions: > > 1) Is it possible and if so, how do I access each individual element? > > Are there any indexes and what is the syntax? > > For the first element: > > >>> words[0] > > 2) I just noticed that the first and the last words in the output are > > enclosed in single quotes, and the middle one is enclosed in double > > quotes. Is it a bug? If not, why does the output work that way? > > The output is valid python code. To represent with single quotes for the > second item, there would have to be a \ escape character for the > apostrophe. > -- > Stephen Fairchild Oh, thank you! That makes sense! Should have thought of the escape character issue... From sdementen at gmail.com Tue Aug 25 17:19:31 2009 From: sdementen at gmail.com (seb) Date: Tue, 25 Aug 2009 14:19:31 -0700 (PDT) Subject: conditional for-statement References: <14afbe5a-62e7-4944-ab9d-42b86530ac41@s31g2000yqs.googlegroups.com> <4720bbf4-1be7-4f02-9869-df8e0cd9e221@y10g2000prf.googlegroups.com> Message-ID: On Aug 25, 10:46?pm, Falcolas wrote: > On Aug 25, 1:58?pm, seb wrote: > > > On Aug 25, 9:42?pm, Falcolas wrote: > > > On Aug 25, 11:25?am, seb wrote: > > > So, what part of the statement does the "if" statement belong to; > > > particularly a concern considering this is valid python: > > > > for x in y if y else z: > > > ? ? body > > > can this be done in list/set/dict comprehensions/generator > > expressions ? > > It's a statement, so anywhere you use a statement (such as in > generators and list comprehensions), it can exist. for ... in ... only > requires that the statement return an iterable, it doesn't matter what > statement you use to get there. > I never thought about this case... Testing that in python 3.0, i see that >>> [x for x in range(5) if False else range(10)] SyntaxError: invalid syntax (, line 1) >>> [x for x in (range(5) if False else range(10))] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] hence, to avoid the ambiguity you mentionned (that already exists with list comprehensions), one can use the parenthesis. This minor incompatibility is referenced in http://www.python.org/dev/peps/pep-0308/ > It doesn't feel clear to me, which is why I would have to disagree. > IIRC, these very filters are the main reason that list comprehensions, > and later one-line generators and dictionary comprehensions were > originally created: so you can filter the stream before acting on it. > One statement performs one action - very precise and understandable. in my mind, I am thinking as you are but with 'loop' instead of 'stream' """so you can filter the 'loop' before acting on it. One statement performs one action - very precise and understandable.""" and it doesn't look that dissimilar to your own reasoning. > > It's just my two cents, but I would not agree that adding a filter > keyword to for loops is required. Not when we have the filter > function, various types of comprehensions, and if statements which all > provide that very functionality. > before having list comprehensions, we could also have said that """ I would not agree that adding a 'list comprehension' feature is required. Not when we have the filter function, and the 'for+if' statements which all provide that very functionality.""" How can unifying the "for ... in ..." statement with the "for ... in ... if ..." syntax be detrimental ? It would be an inconsistence less to remember, wouldn't it ? cheers, sebastien From ryniek90 at gmail.com Tue Aug 25 17:22:13 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Tue, 25 Aug 2009 23:22:13 +0200 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile In-Reply-To: References: Message-ID: <4A945605.1050105@gmail.com> > > Ryniek90 wrote: >> Referring to my earlier posts: >> http://groups.google.pl/group/comp.lang.python/browse_thread/thread/4e34f995800f5352?hl=pl >> >> >> and >> >> http://groups.google.pl/group/comp.lang.python/browse_thread/thread/abf5573b8fceb37e?hl=pl# >> >> >> I've dealt with those errors. but now have another. >> When my backup scripts starts to backup chosen file, python gave me >> Traceback: >> >> " >> C:\Users\Ryniek's WinSe7en\Documents\My >> Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba >> ckuper.py -f F:\APLIKACJE\nowegg.exe F:\ MyGGBackup >> Checking permissions for reading and writing... >> Have permissions on [F:\APLIKACJE\nowegg.exe] for reading. >> Have permissions on [F:\] for writing. >> Preparing for backup [nowegg.exe]... >> Starting backup... >> Now adding [nowegg.exe]... >> Traceback (most recent call last): >> File "backuper.py", line 197, in >> main_meth() >> File "backuper.py", line 189, in main_meth >> paq.backup_file(pars.options.filename[0], >> pars.options.filename[1], pars.options.filename[2]) >> File "backuper.py", line 127, in backup_file >> backup_obj.add(read_bin_obj) >> File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python >> 2.6\lib\tarfile.py", line 1948, in add >> if self.name is not None and os.path.abspath(name) == self.name: >> File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python >> 2.6\lib\ntpath.py", line 458, in abspath >> path = _getfullpathname(path) >> TypeError: _getfullpathname() argument 1 must be (buffer overflow), >> not str >> " >> >> I've searched over google, but found only that is bug in Python ( >> http://bugs.python.org/issue4071 - in that issue bug is inside >> Python 2.5.2 - i've got ActiveState Active Python with core Python >> 2.6.2), and another info: *http://tinyurl.com/lvyn7o and >> **http://tinyurl.com/kn49vk >> * >> >> Here's my script code: >> *http://paste.ubuntu.com/259310/ >> >> *Shouldn't that bug be patched already :-? > Are you giving it the contents of the file when it's actually expecting > the filename? > > Of course the content of the file: " C:\Users\Ryniek's WinSe7en\Documents\My Dropbox\Aplikacje\Moje_aplikacje\Pythonowe_aplikacje\Skrypty>python ba ckuper.py -f F:\APLIKACJE\nowegg.exe F:\ MyGGBackup Checking permissions for reading and writing... Have permissions on [F:\APLIKACJE\nowegg.exe] for reading. Have permissions on [F:\] for writing. Preparing for backup [nowegg.exe]... Starting backup... Now adding [nowegg.exe]... Traceback (most recent call last): File "backuper.py", line 196, in main_meth() File "backuper.py", line 188, in main_meth paq.backup_file(pars.options.filename[0], pars.options.filename[1], pars.options.filename[2]) File "backuper.py", line 126, in backup_file backup_obj.add(read_obj.read()) File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\tarfile.py", line 1948, in add if self.name is not None and os.path.abspath(name) == self.name: File "E:\WinSe7en Apps\APLIKACJE\ActiveState Python 2.6\lib\ntpath.py", line 458, in abspath path = _getfullpathname(path) TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str " See? *backup_obj.add(read_obj.read())* In previous pasted Traceback you can see *backup_obj.add(read_bin_obj)* - read_obj_bin was a reference to the *read_obj.read()* . Do only I have this problem or Python programming under Windows is nightmare? From james.harris.1 at googlemail.com Tue Aug 25 17:26:05 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Tue, 25 Aug 2009 14:26:05 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: On 24 Aug, 03:49, Dennis Lee Bieber wrote: ... > > Here's another suggested number literal format. First, keep the > > familar 0x and 0b of C and others and to add 0t for octal. (T is the > >thirdletter of octal as X is thethirdletter of hex.) The numbers > > above would be > > ? ? ? ? The thing is -- "x" and "hex" have similar pronunciations: (h)ecks; > the name of the radix is its own reminder for the character to use > without thinking such conventions as "thirdletter of the radix name". > > ? ? ? ? But "t" (tee) has no pronunciation resemblance to "oct" (o'kt) > whereas the unlovely "o" at least if taken as a short vowel sound is > similar to the "o" of "oct" given the short stop between it and the > "ct". > > > ? 0b1011, 0t7621, 0xc26b > > ? ? ? ? And "b" for binary breaks the "thirdletter of radix name" > convention... You should be using "n" for that (and "c" for decimal ) I wasn't proposing a convention of using the third character of the base name. I was saying that t is not too unreasonable given that we use x for hex (rather than h). > > ? ? ? ? Or we use b, o, d, h (as the HP calculator) and drop the "x" > version. > > > > > where the three characters "0.(" begin the sequence. > > ? ? ? ? Ugly... > > > Comments? Improvements? > > ? ? ? ? Retaining which ever character is finally decided, I'd make all > radix specified literals follow a quoted format: > > ? ? ? ? "digits"radix > > ? ? ? ? "01110"b > ? ? ? ? "123"d (of course, just 123 would be allowed for simplicity) > ? ? ? ? "7C"x > ? ? ? ? "327"o The quoting is good. For hex, decimal, octal and binary, however, I can't see a good reason to change away from the conventional prefix form. And, in general, it's easier for a human to parse if the base is specified first. > > ? ? ? ? Probably wouldn't need that much change to the parser as it would, > left to right, see a string, and then when the string is not followed by > one white space character, find a radix marker -- the parser would then > parse the string using the specified radix, and emit the appropriate > numeric value instead of a string value. Maybe. I think, though, that having the base as prefix would make the parser's job easier as well as the job of humans. It's easier if we know what we are parsing before we parse it rather than afterwards. > ? ? ? ?It only adds one extra > character (instead of leading 0r, one has ""r), and the leading " serves > as a warning to a reader that this is not directly readable as a number. > > ? ? ? ? The alternative syntax of radix"digits" is the same length, but adds > to the parsing as it initially looks like a name entity, then hits the > quote, and has to back up to interpret the result as a radix marker. True. The beginning of a number should be numeric. Using your scheme, though, instead of radix"digits" you could have 0radix"digits". > 0r > format starts as a number, hits a radix marker while the > "conversion/accumulator" is still a 0 value (0 is 0 in all radix) and > switches the converter to accept the digits in the specified radix. Sounds like you are suggesting 0radix"digits" but I'm not sure. > > ? ? ? ? Whereas all prefix versions that don't start with a 0r tend to > require more complex parsing: > > ? ? ? ? 0.( > > starts out looking like a number (the 0)... a floating point number (the > .)... a function/method call on a floating point 0... WAIT? floating > point numbers aren't callables (yet! I'm sure someone is going to show a > way to define a variable bound to a number as a callable, though not to > a literal number)... throw away this parse tree branch, back up and > reparse as special numeric radix prefix... You've laid it on thick but I agree in principle. What about radix"digits" where radix is numeric: So 2"1101" or 3"122"? (Not to replace 0b1101 etc but to supplement it for arbitrary bases.) > > ? ? ? ? Of course, one still has to consider what will be used for \ > character encoding... \x0F vs \013 vs \b0001111? The plans I had did not allow for the suggestions above so I have no comments on character encoding yet but it's good that you mentioned it. James From pydecker at gmail.com Tue Aug 25 17:31:55 2009 From: pydecker at gmail.com (Peter Decker) Date: Tue, 25 Aug 2009 17:31:55 -0400 Subject: Python for professsional Windows GUI apps? In-Reply-To: <20090825132439.d6cb18ca.feliphil@gmx.net> References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: On Tue, Aug 25, 2009 at 7:24 AM, Wolfgang Keller wrote: > The only framework that seems to be worth trying is Dabo. Unfortunately there's little documentation, and that's mostly outdated. To be honest, that was my biggest concern when I tried Dabo. However, after as small a learning curve as one could expect for any non-trivial tool, it seemed that if I wasn't sure what a particular way to do something was, the most obvious guess was almost always correct. Contrast that with developing in wxPython, which has quite a bit of documentation, which I constantly had to refer to, because the confusing and inconsistent design. There is a step by step guide on Google docs written by one of the authors that is a very helpful approach to using Dabo. The authors are also very active on the dabo-users list, and any questions are quickly answered. So I guess if you need a desktop framework in Python, I would strongly urge you to check out Dabo and not let the volume of documentation scare you off. -- # p.d. From jjposner at optimum.net Tue Aug 25 17:56:51 2009 From: jjposner at optimum.net (John Posner) Date: Tue, 25 Aug 2009 17:56:51 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A945E23.2060802@optimum.net> Stephen Hansen said: > > > But http://docs.python.org/tutorial/classes.html says, in Section > 9.3 "A First Look at Classes": > > When a class definition is entered, a new namespace is created, > and used as the local scope ? thus, all assignments to local variables > go into this new namespace. In particular, function definitions bind > the name of the new function here. > > [snip] > > > (BTW, Diez, your toy example is another demonstration that there > *is* a class-scope-lookup: the "def" statement binds the name > "fact" in the class scope, and the assignment statement looks up > the name "fact" in that scope.) > > > This sounds like a fundamental confusion -- a namespace is not > equivalent to a scope, really, I think. My apologies if I was being too loose with the terms "namespace" and "scope". I was trying to use Diez's terminology (e.g. "class-scope-lookup"). But I think you agree with me in *almost* everything you say below. > > The def statement creates a function object, and assigns it to the > given name, in its /local scope/ which is the class's namespace -- but > that is not a new scope. Its just, during class creation, the local scope. > > When you enter a class definition, a new namespace is created, and > that is used as the local scope during the class's definition. Under > "class Foo", the local scope is this class's namespace-- and the > global scope is the module's namespace. Any lookup operation checks > first in the local scope, then in the global scope... > > When the "def fact(...)" is executed (note that class bodies are > executed on load, function bodies aren't), a new namespace is created > as well-- the function's namespace-- and its used as the local scope. > During execution of the code, it looks up in the local scope first-- > and then it looks up in the global scope if it doesn't find anything. > There /is/ no class-lookup-scope... but there IS a class namespace. > > There's just those two scopes: but the namespace bound to those scopes > changes as you enter different parts of the code. > > For a long time that's all there was, just the local and global scope: > to access any other namespace required you to explicitly address it. > The class namespace remains accessible only via explicit addressing, > but PEP 227 in Python 2.1/2.2 introduced static nested scopes. But > that applies only to enclosing functions: embedding one function into > another. > > You can only call recursive functions if the function is able to refer > to itself according to the same lookup rules: is the function's name > in the local scope? No it's not... is it in the global scope? No? Then > it can't call itself recursively... well, unless its a method, and it > addresses itself specifically-- with "self.". All of the above is consistent with my previous post. > > The OP's probably is that during the execution of the class body, the > class doesn't exist... so the 'def fact' -can't- use Classname.fact to > address itself explicitly, and within fact the locals don't contain a > reference to the function itself, and its globals don't either. You > just can't do that. Here's where we disagree, and I'm sticking to my guns. The fact that the class definition has not been completely processed is irrelevant. The OP's problem was attempting to implement a recursive function. A non-recursive implementation of fact() works fine: class ThisWorks(object): def fact(n): answer = 1 i = 1 while i <= n: answer *= i i += 1 return answer clsvar = fact(4) print ThisWorks.clsvar # output: 24 > The right way, IMHO, is to move 'fact' up and out of the class ... We're back to agreement on this point! -John From piet at cs.uu.nl Tue Aug 25 17:57:21 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Tue, 25 Aug 2009 23:57:21 +0200 Subject: conditional for-statement References: Message-ID: >>>>> seb (s) wrote: >s> i am still a bit puzzle by the following. >s> I read in http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generators >s> """Python 3.0 unifies all collection types by introducing dict and set >s> comprehensions, similar to list comprehensions: >>>>> [ n*n for n in range(5) ] # regular list comprehension >s> [0, 1, 4, 9, 16] >>>>> >>>>> { n*n for n in range(5) } # set comprehension >s> {0, 1, 4, 16, 9} >>>>> >>>>> { n: n*n for n in range(5) } # dict comprehension >s> {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} >s> """ >s> and we can add to this list the quite similar syntax for generator >s> expressions. >s> On all these loop constructs, one can consistenly add filtering on a >s> condition by adding an "if ..." after the "for ... in ..." part (and >s> it looks to me difficult to argue, for instance, that we should not >s> allow filtering for dict comprehesion because we could get the same >s> result by some other construct) You can also say: [x+y for x in range(3) for y in range(4) if x < y] If you want to write this as a loop you have to put the for's on separate lines separated by colons, so why not the if also? Or would you also like to have the for's on one line? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From python at mrabarnett.plus.com Tue Aug 25 18:05:01 2009 From: python at mrabarnett.plus.com (MRAB) Date: Tue, 25 Aug 2009 23:05:01 +0100 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile In-Reply-To: <4A945605.1050105@gmail.com> References: <4A945605.1050105@gmail.com> Message-ID: <4A94600D.60409@mrabarnett.plus.com> Ryniek90 wrote: >> >> Ryniek90 wrote: [snip] >>> Here's my script code: >>> *http://paste.ubuntu.com/259310/ >>> >>> *Shouldn't that bug be patched already :-? >> Are you giving it the contents of the file when it's actually expecting >> the filename? >> > > Of course the content of the file: [snip] > See? *backup_obj.add(read_obj.read())* > In previous pasted Traceback you can see *backup_obj.add(read_bin_obj)* > - read_obj_bin was a reference to the *read_obj.read()* . > The documentation lists the methods "add" and "addfile". Pick one and provide the values it's expecting. For example, if you choose "add" then provide the filename, not the contents of the file. > Do only I have this problem or Python programming under Windows is > nightmare? It's only a nightmare if you don't follow the documentation. :-) From gbelov at gmail.com Tue Aug 25 18:14:26 2009 From: gbelov at gmail.com (Gleb Belov) Date: Tue, 25 Aug 2009 15:14:26 -0700 (PDT) Subject: Help with arrays Message-ID: Hello! I'm working on an exercise wherein I have to write a Guess The Number game, but it's the computer who's guessing MY number. I can get it to work, but there's one obvious problem: the computer generates random numbers until one of them corresponds to my number, but it will often generate one number (eg. 4) numerous times, meaning it doesn't know that this number is invalid. What I mean is, it will sometimes use 37 tries to guess a number out of 1 - 9, which makes no sense, since it should only take 9 tries, at most. I was trying to find a way to make a dynamic list of all the numbers the computer generates in the loop and then make it re-generate the number if the previous number is present in the list, so it doesn't keep on generating 4 (as an example). I don't know if that makes sense... Basically, we humans know that once something is incorrect, there's no point in trying to use it as the answer next time, because we already know it's incorrect. How do I go about coding this in Python? I'm still quite new to the language so any help will be appreciated... From philip at semanchuk.com Tue Aug 25 18:21:46 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Tue, 25 Aug 2009 18:21:46 -0400 Subject: Help with arrays In-Reply-To: References: Message-ID: <9AE5AB62-5991-4A6E-81EC-2AEE8BFE71F3@semanchuk.com> On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: > Hello! I'm working on an exercise wherein I have to write a Guess The > Number game, but it's the computer who's guessing MY number. I can get > it to work, but there's one obvious problem: the computer generates > random numbers until one of them corresponds to my number, but it will > often generate one number (eg. 4) numerous times, meaning it doesn't > know that this number is invalid. What I mean is, it will sometimes > use 37 tries to guess a number out of 1 - 9, which makes no sense, > since it should only take 9 tries, at most. I was trying to find a way > to make a dynamic list of all the numbers the computer generates in > the loop and then make it re-generate the number if the previous > number is present in the list, so it doesn't keep on generating 4 (as > an example). I don't know if that makes sense... Basically, we humans > know that once something is incorrect, there's no point in trying to > use it as the answer next time, because we already know it's > incorrect. How do I go about coding this in Python? I'm still quite > new to the language so any help will be appreciated... One cheap way to do it (not necessarily efficient) is to make a list of your possible guesses (e.g. range(1,10)), use random.shuffle() to put them in random order and then run through the guesses one at a time. HTH Philip From farberow at wisc.edu Tue Aug 25 18:34:10 2009 From: farberow at wisc.edu (Carrie Farberow) Date: Tue, 25 Aug 2009 17:34:10 -0500 Subject: Python on Crays In-Reply-To: <1f5c81d8-4f79-4eea-b1bd-af48ab9ddc82@c2g2000yqi.googlegroups.com> References: <1f5c81d8-4f79-4eea-b1bd-af48ab9ddc82@c2g2000yqi.googlegroups.com> Message-ID: <6e80874a13151.4a942092@wiscmail.wisc.edu> Ok, here are links to word documents outlining the commands I executed as well as the make.log file and the make_install.log file instructions/commands: https://mywebspace.wisc.edu/xythoswfs/webui/_xy-29018965_1-t_dSnfEm5b make.log: https://mywebspace.wisc.edu/xythoswfs/webui/_xy-29018966_1-t_zjqLuV5v javascript:parent.send('smtp') make_install.log: https://mywebspace.wisc.edu/xythoswfs/webui/_xy-29018967_1-t_n8aqH2P The issue referred to in the previous message (http://bugs.python.org/issue1594809) sounds similar - however I do not think that I can just build the shared unicodedata module and have it work properly, as I am trying to statically link the necessary modules. I am very new with this, so if I am completely misunderstanding, please feel free to let me know. Thanks! Carrie ----- Original Message ----- From: Mark Dickinson Date: Friday, August 21, 2009 12:50 pm Subject: Re: Python on Crays To: python-list at python.org > On Aug 21, 12:21?am, Carrie Farberow wrote: > > I am trying to build a statically-linked Python based on directions > at: > > > > http://yt.enzotools.org/wiki/CrayXT5Installation > > > > I have tried this on multiple systems. ?The first time I attempt to > build python, 'make' runs fine but 'make install' fails with the > following error: > > > > Sorry: UnicodeError: ("\\N escapes not supported (can't load > unicodedata module)",) > > > > Any help regarding the source of this error and possible fixes would > be appreciated. > > Hmm. There's not a lot of information to go on here. > What version of Python is this? Python 2.6.2? > Have you tried Googling for that exact error message? > > The following issue looks as though it might be relevant: > > http://bugs.python.org/issue1594809 > > especially since it looks as though the directions you linked > to involve messing with the PYTHONPATH environment variable. > > If you could post a log somewhere[*] showing the exact commands > that you executed, along with all the output (and especially > all the output from 'make' and 'make install'), that might help > someone diagnose the problem further. > > Mark > > [*] I'm not sure where, though. Posting all that output directly > in a newsgroup message might not be considered very friendly. > -- > http://mail.python.org/mailman/listinfo/python-list From samwyse at gmail.com Tue Aug 25 18:35:55 2009 From: samwyse at gmail.com (samwyse) Date: Tue, 25 Aug 2009 15:35:55 -0700 (PDT) Subject: best way to display photos References: <96e9b045-d591-485e-b831-ba1462345df9@z31g2000yqd.googlegroups.com> <7fhfboF2ksfhiU1@mid.individual.net> Message-ID: On Aug 25, 1:40?am, Thomas Guettler wrote: > Some years ago I had the same problem. > > I wrote a simple app with pygtk. You get get it from here: > ? ?http://guettli.sourceforge.net/gthumpy/src/README.html > The next pictures get loaded in background. Switching from > one image to the next is faster then in some other apps. But > somehow it is not ready for the public. I guess I am the only > one who uses it. > > Flags are symlinks in the home directory .local/share/app/gthumpy. This > means you should not move your images, otherwise the flags get lost. > > I don't think it will work on ms-windows, but it could be ported. > > Or you use mirage:http://mirageiv.berlios.de/index.html > > It is a pygtk image viewer. You can define shortcuts that execute user defined > commands. > > ? Thomas > > samwyse schrieb: > > > I have several thousand photographs that I need to quickly classify, > > all by myself. ?After extensive searches, I have been unable to find > > anything to my liking, so desire to write something myself. ?I'm > > thinking about displaying a photo and waiting for keystrokes to tag > > it; 'i' for interior, 'e' for exterior, etc., while hitting space or > > enter will advance to the next photo. ?My big question is, what's the > > best way to display the photos. ?I've used PIL in the past, but IIRC > > it uses an external program. ?Pygame is the next obvious choice, but > > like PIL it requires an add-in. ?That leaves Tkinter. ?Has anyone used > > it to display .JPG files, perhaps with rescaling to fit my screen? > > How is its performance? ?Is there any other possibilities that I've > > missed? ?Thanks. > > -- > Thomas Guettler,http://www.thomas-guettler.de/ > E-Mail: guettli (*) thomas-guettler + de Thanks! Both of these look very similar to what I need. I will investigate further. From wwy58 at yahoo.com Tue Aug 25 18:43:28 2009 From: wwy58 at yahoo.com (David) Date: Tue, 25 Aug 2009 15:43:28 -0700 (PDT) Subject: mod_python: Permission denied Message-ID: <0fb0ed29-82bb-4bdf-aa24-071c158eea2a@k13g2000prh.googlegroups.com> Hello, I googled online however I did not find a clue my question. So I post it here. I created a mod_python CGI to upload a file and saves it in folder "/ var/www/keyword-query/files/". My code runs in root. fileitem = req.form['file'] # Test if the file was uploaded if fileitem.filename: # strip leading path from file name to avoid directory traversal attacks fname = os.path.basename(fileitem.filename) # build absolute path to files directory dir_path = os.path.join(os.path.dirname(req.filename), 'files') f = open(os.path.join(dir_path, fname), 'wb', 10000) # Read the file in chunks for chunk in fbuffer(fileitem.file): f.write(chunk) f.close() message = 'The file "%s" was uploaded successfully' % fname I got: File "/var/www/keyword-query/upload.py", line 30, in upload f = open(os.path.join(dir_path, fname), 'wb', 10000) IOError: [Errno 13] Permission denied: '/var/www/keyword-query/files/ Defrosting.rtf' "Defrosting.rtf" is a file on the desktop of my Windows XP computer. Anybody knows what the problem is? Thanks for your replies. From graham.dumpleton at gmail.com Tue Aug 25 18:46:07 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Aug 2009 15:46:07 -0700 (PDT) Subject: How does the file.seek() work ? References: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> Message-ID: <1532ff09-f892-44c8-8206-10b3c2d16050@13g2000prl.googlegroups.com> On Aug 25, 5:37?am, Tim Chase wrote: > > I want the file pointer set to 100 and overwrite everything from there > [snip] > > def application(environ, response): > > ? ? query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') > > ? ? range=environ.get('HTTP_RANGE','bytes=0-').replace > > ('bytes=','').split(',') > > ? ? offset=[] > > ? ? for r in range: offset.append(r.split('-')) > > ? ? with open(query,'w+') as f: > > ? ? ? ? ?f.seek(int(offset[0][0])) > > ? ? ? ? ?while True: > > ? ? ? ? ? ? ?chunk=environ['wsgi.input'].read(8192).decode('latin1') > > ? ? ? ? ? ? ?if not chunk: break > > ? ? ? ? ? ? ?f.write(chunk) > > ? ? f=open(query) > > ? ? l=str(os.fstat(f.fileno()).st_size) > > ? ? response('200 OK', [('Content-Type', 'text/plain'), ('Content- > > Length', str(len(l)))]) > > ? ? return [l] > > A couple items of note: > > - you don't open the file in binary mode -- seek is more reliable > in binary mode :) If my memory is right, if file is opened in binary mode, also wouldn't need to be decoding the WSGI input stream as latin-1 to get a string. Instead can just deal with bytes and write bytes to file. Graham > - if you want to lop off the rest of the file, use f.truncate() > > An example: > > # create the initial file > ?>>> f = file('zzz.zzz', 'wb+') > ?>>> f.write('abcdefghijklmnop') > ?>>> f.close() > > ?>>> f = file('zzz.zzz', 'ab+') > ?>>> f.read() # show the existing content > 'abcdefghijklmnop' > ?>>> f.seek(5) # seek to the desired offset > ?>>> f.truncate() # throw away everything after here > ?>>> f.write('zyx') # write the new data at pos=5 > ?>>> f.close() > > # demonstrate that it worked > ?>>> f = file('zzz.zzz', 'rb') > ?>>> f.read() > 'abcdezyx' > ?>>> f.close() > > > also why must I open the file a second time to know how big it is ? > > Likely the output has been buffered. ?You can try using > > ? ?f.flush() # write all the data to the disk first > ? ?size = os.fstat(f.fileno()).st_size > > which seems to do the trick for me. > > -tkc From graham.dumpleton at gmail.com Tue Aug 25 18:48:38 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Aug 2009 15:48:38 -0700 (PDT) Subject: mod_python: Permission denied References: <0fb0ed29-82bb-4bdf-aa24-071c158eea2a@k13g2000prh.googlegroups.com> Message-ID: <09e25701-5d85-4aed-a4bb-4fa94df74f5c@v37g2000prg.googlegroups.com> On Aug 26, 8:43?am, David wrote: > Hello, > > I googled online however I did not find a clue my question. So I post > it here. > > I created a mod_python CGI to upload a file and saves it in folder "/ > var/www/keyword-query/files/". ?My code runs in root. > > ? ? ?fileitem = req.form['file'] > > ? ?# Test if the file was uploaded > ? ?if fileitem.filename: > > ? ? ? # strip leading path from file name to avoid directory traversal > attacks > ? ? ? fname = os.path.basename(fileitem.filename) > ? ? ? # build absolute path to files directory > ? ? ? dir_path = os.path.join(os.path.dirname(req.filename), 'files') > ? ? ? f = open(os.path.join(dir_path, fname), 'wb', 10000) > > ? ? ? # Read the file in chunks > ? ? ? for chunk in fbuffer(fileitem.file): > ? ? ? ? ?f.write(chunk) > ? ? ? f.close() > ? ? ? message = 'The file "%s" was uploaded successfully' % fname > > I got: > > ?File "/var/www/keyword-query/upload.py", line 30, in upload > ? ? f = open(os.path.join(dir_path, fname), 'wb', 10000) > > IOError: [Errno 13] Permission denied: '/var/www/keyword-query/files/ > Defrosting.rtf' > > "Defrosting.rtf" is a file on the desktop of my Windows XP computer. > > Anybody knows what the problem is? > > Thanks for your replies. Apache service likely running as a special user which doesn't have write permission to your directory. Graham From wwy58 at yahoo.com Tue Aug 25 18:48:47 2009 From: wwy58 at yahoo.com (David) Date: Tue, 25 Aug 2009 15:48:47 -0700 (PDT) Subject: mod_python: Permission denied References: <0fb0ed29-82bb-4bdf-aa24-071c158eea2a@k13g2000prh.googlegroups.com> Message-ID: <5fc7570c-8f77-429d-8c9d-5ba74573e440@k13g2000prh.googlegroups.com> A little more info: "Defrosting.rtf" is a file that I wanted to upload. This file was supposed to upload to folder '/var/www/keyword- query/files/'. My code runs in root. From somebody at somewhere.com Tue Aug 25 18:50:17 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Tue, 25 Aug 2009 23:50:17 +0100 Subject: Help with arrays References: Message-ID: Philip Semanchuk wrote: > > On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: > >> Hello! I'm working on an exercise wherein I have to write a Guess The >> Number game, but it's the computer who's guessing MY number. I can get >> it to work, but there's one obvious problem: the computer generates >> random numbers until one of them corresponds to my number, but it will >> often generate one number (eg. 4) numerous times, meaning it doesn't >> know that this number is invalid. What I mean is, it will sometimes >> use 37 tries to guess a number out of 1 - 9, which makes no sense, >> since it should only take 9 tries, at most. I was trying to find a way >> to make a dynamic list of all the numbers the computer generates in >> the loop and then make it re-generate the number if the previous >> number is present in the list, so it doesn't keep on generating 4 (as >> an example). I don't know if that makes sense... Basically, we humans >> know that once something is incorrect, there's no point in trying to >> use it as the answer next time, because we already know it's >> incorrect. How do I go about coding this in Python? I'm still quite >> new to the language so any help will be appreciated... > > One cheap way to do it (not necessarily efficient) is to make a list > of your possible guesses (e.g. range(1,10)), use random.shuffle() to > put them in random order and then run through the guesses one at a time. import random import time l = range(1, 10) while l: print l.pop(random.randint(0, len(l) - 1)) time.sleep(2) -- Stephen Fairchild From wwy58 at yahoo.com Tue Aug 25 18:58:54 2009 From: wwy58 at yahoo.com (David) Date: Tue, 25 Aug 2009 15:58:54 -0700 (PDT) Subject: mod_python: Permission denied References: <0fb0ed29-82bb-4bdf-aa24-071c158eea2a@k13g2000prh.googlegroups.com> <5fc7570c-8f77-429d-8c9d-5ba74573e440@k13g2000prh.googlegroups.com> Message-ID: <0ec8929f-eab8-4655-8661-40142ae8c908@j9g2000prh.googlegroups.com> disclaimer: i did not write this code. i copied it and inserted into my cgi code. it is from http://webpython.codepoint.net/mod_python_publisher_big_file_upload. From wwy58 at yahoo.com Tue Aug 25 19:00:46 2009 From: wwy58 at yahoo.com (David) Date: Tue, 25 Aug 2009 16:00:46 -0700 (PDT) Subject: mod_python: Permission denied References: <0fb0ed29-82bb-4bdf-aa24-071c158eea2a@k13g2000prh.googlegroups.com> <5fc7570c-8f77-429d-8c9d-5ba74573e440@k13g2000prh.googlegroups.com> <0ec8929f-eab8-4655-8661-40142ae8c908@j9g2000prh.googlegroups.com> Message-ID: <0c73d5bf-3f5d-4308-a7f0-276e4d6d9fa9@x25g2000prf.googlegroups.com> Thanks Graham. Let me contact Admin. From geekworking at gmail.com Tue Aug 25 19:04:01 2009 From: geekworking at gmail.com (geekworking) Date: Tue, 25 Aug 2009 16:04:01 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: <63bb7834-80ac-4894-9ef5-2598ecac72cc@k19g2000yqn.googlegroups.com> If you are planning a database driven app, you should first settle on a DB server. Any real enterprise DB system will put all of the business logic in the database server. The choice of a front end should be secondary. Wikipedia's list of Python apps: http://en.wikipedia.org/wiki/List_of_Python_software From wwy58 at yahoo.com Tue Aug 25 19:07:34 2009 From: wwy58 at yahoo.com (David) Date: Tue, 25 Aug 2009 16:07:34 -0700 (PDT) Subject: mod_python: Permission denied References: <0fb0ed29-82bb-4bdf-aa24-071c158eea2a@k13g2000prh.googlegroups.com> <5fc7570c-8f77-429d-8c9d-5ba74573e440@k13g2000prh.googlegroups.com> <0ec8929f-eab8-4655-8661-40142ae8c908@j9g2000prh.googlegroups.com> <0c73d5bf-3f5d-4308-a7f0-276e4d6d9fa9@x25g2000prf.googlegroups.com> Message-ID: <134a6022-f7d5-4871-bb7c-e38af0cd7679@x6g2000prc.googlegroups.com> On Aug 25, 4:00?pm, David wrote: > Thanks Graham. Let me contact Admin. Hi Graham: you are right. it's fixed now. Thanks again. From mdekauwe at gmail.com Tue Aug 25 19:48:35 2009 From: mdekauwe at gmail.com (Mart.) Date: Tue, 25 Aug 2009 16:48:35 -0700 (PDT) Subject: Help with arrays References: Message-ID: <9be8986b-95c8-48fa-a298-3b97fa598081@s15g2000yqs.googlegroups.com> On Aug 25, 11:50?pm, Stephen Fairchild wrote: > Philip Semanchuk wrote: > > > On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: > > >> Hello! I'm working on an exercise wherein I have to write a Guess The > >> Number game, but it's the computer who's guessing MY number. I can get > >> it to work, but there's one obvious problem: the computer generates > >> random numbers until one of them corresponds to my number, but it will > >> often generate one number (eg. 4) numerous times, meaning it doesn't > >> know that this number is invalid. What I mean is, it will sometimes > >> use 37 tries to guess a number out of 1 - 9, which makes no sense, > >> since it should only take 9 tries, at most. I was trying to find a way > >> to make a dynamic list of all the numbers the computer generates in > >> the loop and then make it re-generate the number if the previous > >> number is present in the list, so it doesn't keep on generating 4 (as > >> an example). I don't know if that makes sense... Basically, we humans > >> know that once something is incorrect, there's no point in trying to > >> use it as the answer next time, because we already know it's > >> incorrect. How do I go about coding this in Python? I'm still quite > >> new to the language so any help will be appreciated... > > > One cheap way to do it (not necessarily efficient) is to make a list > > of your possible guesses (e.g. range(1,10)), use random.shuffle() to > > put them in random order and then run through the guesses one at a time. > > import random > import time > > l = range(1, 10) > > while l: > ? ? print l.pop(random.randint(0, len(l) - 1)) > ? ? time.sleep(2) > > -- > Stephen Fairchild Perhaps generate all of the possible moves at the outset in some form of lookup table that you can refer to? I think it is a similar thing to how computers play chess, I think it is called "hash tables" From cevomed at gmail.com Tue Aug 25 19:48:52 2009 From: cevomed at gmail.com (=?ISO-8859-9?Q?Cevahir_Demirk=FDran?=) Date: Wed, 26 Aug 2009 01:48:52 +0200 Subject: Division and right shift in python Message-ID: <3f74e020908251648k7b391a09g78b155507b2f23c4@mail.gmail.com> Hi, I would like to do a floor division by a power of 2 in python to make it faster than / (modular division in 2.x). However, it is slower. What is the reason of that? I checked them via: def f2(x,n): t1 = clock() r = x/pow(2,n) t2 = clock() print (t2-t1) print r t2 = clock() r = x>>n t3 = clock() print (t3-t2) print r -------------- next part -------------- An HTML attachment was scrubbed... URL: From evaned at gmail.com Tue Aug 25 19:51:42 2009 From: evaned at gmail.com (Evan Driscoll) Date: Tue, 25 Aug 2009 16:51:42 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> <7fivlrF2lsrsuU1@mid.uni-berlin.de> Message-ID: <3da50b33-d79e-4579-9240-ef430ea7c697@m38g2000yqh.googlegroups.com> On Aug 25, 3:47?pm, Evan Driscoll wrote: > So here is my simplified version that only works for globals: So I think this works if (1) you only use changed_value in the same module as it's defined in (otherwise it picks up the globals from the module it's defined in, which is almost certainly not what you want), and (2) the value you want to change is just a simple variable and not either something like "os.path" or a builtin. I have worked on this a bit more and have something that addresses these issues in at least the cases I've tested. I'm not going to post the code here, but it is up at http://pages.cs.wisc.edu/~driscoll/python/utils.py and there are a few unit tests at http://pages.cs.wisc.edu/~driscoll/python/utils_test.py I solved issue (1) by reintroducing the use of inspect to walk back up the stack a couple frames, but I pulled out the f_globals member instead of f_locals. Issue (2a) I fixed by splitting the variable name at periods and walking through successive dictionaries with each component. Issue (2b) I fixed by looking for a '__builtins__' entry if the name I'm looking up doesn't exist. Right now it's sort of hackish... it probably doesn't respond particularly well if things go unexpectedly (e.g. a bad variable name is given) and I should probably verify that the value is unchanged during the with statement and throw an exception otherwise, but it probably works well enough for my purposes for now. Comments are appreciated... a couple of the things in there it seems like there could very well be reimplementations of things that are already done. Evan From sturlamolden at yahoo.no Tue Aug 25 20:04:51 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 25 Aug 2009 17:04:51 -0700 (PDT) Subject: Python, qt, and lgpl References: Message-ID: <1e7a9056-db73-4c4f-be8a-f1b65a91daec@v20g2000yqm.googlegroups.com> On 25 Aug, 21:45, Terry Reedy wrote: > Will be good news if realized. Good news for everyone except Riverbank. From zuo at chopin.edu.pl Tue Aug 25 20:34:11 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 26 Aug 2009 02:34:11 +0200 Subject: Need help with Python scoping rules In-Reply-To: <7a9c25c20908251316k2ebc304fk1422c96ddb4158c4@mail.gmail.com> References: <4A942954.7070702@optimum.net> <7a9c25c20908251316k2ebc304fk1422c96ddb4158c4@mail.gmail.com> Message-ID: 25-08-2009 o 22:16:24 Stephen Hansen wrote: > The OP's probably is that during the execution of the class body, the > class > doesn't exist... so the 'def fact' -can't- use Classname.fact to address > itself explicitly, and within fact the locals don't contain a reference > to > the function itself, and its globals don't either. You just can't do > that. > The right way, IMHO, is to move 'fact' up and out of the class into a > _fact global variable. Alternatively, you can use a metaclass. Note that you can also pass a function to the function itself, and then it works: >>> class Foo: ... def func(foo=None): ... if foo: ... return foo() ... else: ... return '2nd step' ... x = func(func) ... >>> Foo.x '2nd step' Note that when called from class definition body, func is an ordinary function, not a method. It become a method *when it's called as a method* (what is possible *after* creating the class => outside the definition). Cheers, *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Tue Aug 25 20:45:32 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 26 Aug 2009 02:45:32 +0200 Subject: Is it a bug? In-Reply-To: <87b7ce88-1f2f-43ff-8096-6a95a89b6e27@e27g2000yqm.googlegroups.com> References: <87b7ce88-1f2f-43ff-8096-6a95a89b6e27@e27g2000yqm.googlegroups.com> Message-ID: 25-08-2009 o 22:51:14 Gleb Belov wrote: > I have two questions: > 1) Is it possible and if so, how do I access each individual element? > Are there any indexes and what is the syntax? It's a 'Read-The-Friendly-Manual' question. (hint: library reference - Built-in Types - ...) -- Jan Kaliszewski (zuo) From somebody at somewhere.com Tue Aug 25 20:59:45 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Wed, 26 Aug 2009 01:59:45 +0100 Subject: Need help with Python scoping rules References: Message-ID: You are trying to run code in a class that does not exist yet. def Demo(): def fact(n): if n < 2: return 1 else: return n * fact(n - 1) return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar": fact(5)}) Demo = Demo() d = Demo() print d._classvar # prints 120 print d.fact(7) # prints 5040 print Demo # prints -- Stephen Fairchild From zuo at chopin.edu.pl Tue Aug 25 21:02:11 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 26 Aug 2009 03:02:11 +0200 Subject: break unichr instead of fix ord? In-Reply-To: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: 25-08-2009 o 21:45:49 wrote: > In Python 2.5 on Windows I could do [*1]: > > # Create a unicode character outside of the BMP. > >>> a = u'\U00010040' > > # On Windows it is represented as a surogate pair. [snip] > On Python 2.6, unichr() was "fixed" (using the word > loosely) so that it too now fails with characters outside > the BMP. [snip] > Does not this effectively make unichr() and ord() useless > on Windows for all but a subset of unicode characters? Are you sure, you couldn't have UCS-4-compiled Python distro for Windows?? :-O *j -- Jan Kaliszewski (zuo) From phily05 at gmail.com Tue Aug 25 21:09:28 2009 From: phily05 at gmail.com (Phil) Date: Tue, 25 Aug 2009 18:09:28 -0700 (PDT) Subject: Python on the Web Message-ID: I've seen lots of web sites explaining everything, but for whatever reason I seem to not be picking something up. I am a graphical person, which is probably the reason I haven't found my answer. May somebody please confirm if my diagram accurately represents the stack, generally speaking. http://i26.tinypic.com/1fe82x.png Even if that is the case, I'm having a hard time understanding the differences. I guess wsgiref has absolutely nothing to do with FCGI/ SCGI/CGI and simply receives and responds to HTTP requests following the WSGI specification? Does it just spawn a new thread for each request? If so, then how is this any different than a production server with FCGI? The way I am understanding the 'Production' side of that picture is that the web server (eg. lighttpd) creates a single FCGI process. The FCGI process is actually the entry point of the Framework/Application which sets up Flup's WSGIServer, being the interface between FCGI and the Framework/Application? What I mean is, it is just the code that the web server loads to start with, example... from flup.server.fcgi import WSGIServer from app import application WSGIServer(application).run() ... Then for each HTTP request, Flup's WSGIServer creates a new thread to handle the request? As I've read elsewhere, "These days, FastCGI is never used directly. Just like mod_python it is only used for the deployment of WSGI applications." As far as I understand, the main (or only?) reasoning for this is because WSGI makes Python applications easier to deploy without having to worry about whether using FCGI/SCGI/CGI. What would be involved to run Python on the web using FCGI without WSGI? I can feel the flames already. This isn't the only reason I want to know, but one reason is that I want to use Python 3.1 and as I understand, this will have to wait for the WSGI 2.0 specification to ensure time isn't wasted. I apologize if the questions are ridiculous. I've just recently got into web programming and it seems that in order for me to use Python, I need a deep understanding of web servers, HTTP, FCGI, etc. I have more questions but they go more off topic, so I will save it for another thread, another day. I realize there is a large number of questions, so thanks for any help. From terry.yinzhe at gmail.com Tue Aug 25 21:11:53 2009 From: terry.yinzhe at gmail.com (Terry) Date: Tue, 25 Aug 2009 18:11:53 -0700 (PDT) Subject: multiprocessing managers and socket connection. References: <722664f1-81af-45da-ae40-070bca8f3ee0@k6g2000yqn.googlegroups.com> Message-ID: <0af6687a-e36d-47c3-af5e-7e66eacbb3ce@v23g2000pro.googlegroups.com> On Aug 25, 10:14?pm, Chris wrote: > I've been using multiprocessing managers and I really like the > functionality. > > I have a question about reconnecting to a manager. I have a situation > where I start on one machine (A) a manager that is listening and then > on another machine (B) connects to that manager and uses its proxy > object to call functions on the manager's computer; this all works as > expected. But, if the manager from A shuts down, B's application won't > notice because in the MP code it ignores socket error > errno.ECONNREFUSED. If A becomes available again or is restarted, B > doesn't automatically reconnect either and continue its operation. > It's function is basically stopped. > > Here is the code from connection.py: > while 1: > ? ? ? ? try: > ? ? ? ? ? ? s.connect(address) > ? ? ? ? except socket.error, e: > ? ? ? ? ? ? if e.args[0] != errno.ECONNREFUSED: # connection refused > ? ? ? ? ? ? ? ? debug('failed to connect to address %s', address) > ? ? ? ? ? ? ? ? raise > ? ? ? ? ? ? time.sleep(0.01) > ? ? ? ? else: > ? ? ? ? ? ? break > > How can I have B automatically reconnect to A and continue its work > once A is available again? I think you need to retry repeatedly until successfully connected. br, Terry From wuwei23 at gmail.com Tue Aug 25 21:13:11 2009 From: wuwei23 at gmail.com (alex23) Date: Tue, 25 Aug 2009 18:13:11 -0700 (PDT) Subject: can python make web applications? References: <02a3ba7c$0$18215$c3e8da3@news.astraweb.com> Message-ID: <1e23a271-785b-4600-892f-32c85d717f2e@f18g2000prf.googlegroups.com> Mark wrote: > On Sun, 23 Aug 2009 21:45:17 +0100, Goke Aruna wrote: > >http://www.openerp.com, all done is python. > > That does look impressive. Is that Django or Turbogears? Turbogears, according to the product's wikipedia page. From terry.yinzhe at gmail.com Tue Aug 25 21:22:02 2009 From: terry.yinzhe at gmail.com (Terry) Date: Tue, 25 Aug 2009 18:22:02 -0700 (PDT) Subject: Return value of multiprocessing manager registerred function Message-ID: <4337084f-cf9b-4b9c-a0cc-ba8f0821f31a@v15g2000prn.googlegroups.com> Hi, I'm using the multiprocessing.manager to run procedures remotely. It all worked fine except I hope to have a different return value type. The remote function calls always return a proxy, which when I need to get the value it need to connect to the manager again to fetch it. But I just need the value, not the proxy. Can I just return the value instead of a proxy from a manager? br, Terry From davea at ieee.org Tue Aug 25 21:26:12 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 25 Aug 2009 21:26:12 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A948F34.3030703@ieee.org> Stephen Fairchild wrote: > You are trying to run code in a class that does not exist yet. > > > def Demo(): > def fact(n): > if n < 2: > return 1 > else: > return n * fact(n - 1) > return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar": > fact(5)}) > Demo = Demo() > > d = Demo() > print d._classvar # prints 120 > print d.fact(7) # prints 5040 > print Demo # prints > > In all these messages, something I haven't seen pointed out is that fact() has no self argument. Seems to me that makes it a staticmethod, so it should be declared that way. But you can't call a static method from the class scope, since the class hasn't been completed yet. That's the part I consider a problem, not all the rest. I've seen the same problem in Forth, where 'smudge' is used to prevent a definition from accidentally calling itself. But I don't recall whether that was in the standard, or just vendor's helpful additions. Anyway, my first choice is to move the static method out of the class. Second choice workaround follows, moving the initialization of the class variable to after the class, when it can properly use the class name.: class Demo(object): @staticmethod def fact(n): if n < 2: return 1 else: return n * Demo.fact(n - 1) Demo._classvar = Demo.fact(5) print Demo._classvar xx = Demo() print xx.fact(6) DaveA From aahz at pythoncraft.com Tue Aug 25 21:41:55 2009 From: aahz at pythoncraft.com (Aahz) Date: 25 Aug 2009 18:41:55 -0700 Subject: web frameworks that support Python 3 References: Message-ID: In article , Graham Dumpleton wrote: >On Aug 24, 6:34=A0am, Sebastian Wiesner wrote: >> >> In any case, there is bottle [1], which provides a *very minimal* framewo= >rk >> for WSGI web development. =A0Don't expect too much, it is really small, a= >nd >> doesn't do much more than routing and minimal templating. >> >> However, it is the only Python-3-compatible web framework I know of. >> >> [1]http://bottle.paws.de/page/start > >There is one big flaw with your claim. That is the there is no WSGI >specification for Python 3.0 as yet. Anything that claims to work with >WSGI and Python 3.0 is just a big guess as far as how WSGI for Python >3.0 may work. Perhaps you meant "library" instead of "specification"? I don't understand how a language can be missing a specification. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From robert.kern at gmail.com Tue Aug 25 21:47:22 2009 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 25 Aug 2009 20:47:22 -0500 Subject: Python on the Web In-Reply-To: References: Message-ID: On 2009-08-25 20:09 PM, Phil wrote: > I've seen lots of web sites explaining everything, but for whatever > reason I seem to not be picking something up. > I am a graphical person, which is probably the reason I haven't found > my answer. > May somebody please confirm if my diagram accurately represents the > stack, generally speaking. > > http://i26.tinypic.com/1fe82x.png > > Even if that is the case, I'm having a hard time understanding the > differences. I guess wsgiref has absolutely nothing to do with FCGI/ > SCGI/CGI and simply receives and responds to HTTP requests following > the WSGI specification? Correct. > Does it just spawn a new thread for each > request? No, it is single-threaded. > If so, then how is this any different than a production > server with FCGI? > > The way I am understanding the 'Production' side of that picture is > that the web server (eg. lighttpd) creates a single FCGI process. The > FCGI process is actually the entry point of the Framework/Application > which sets up Flup's WSGIServer, being the interface between FCGI and > the Framework/Application? What I mean is, it is just the code that > the web server loads to start with, example... > from flup.server.fcgi import WSGIServer > from app import application > WSGIServer(application).run() > ... Then for each HTTP request, Flup's WSGIServer creates a new thread > to handle the request? Something like that, yes. > As I've read elsewhere, "These days, FastCGI is never used directly. > Just like mod_python it is only used for the deployment of WSGI > applications." As far as I understand, the main (or only?) reasoning > for this is because WSGI makes Python applications easier to deploy > without having to worry about whether using FCGI/SCGI/CGI. Yes, that is the primary reason for WSGI, in my mind. There are other things like the composability of applications, but the decoupling of application authoring from deployment is the sine qua non, in my opinion. > What would be involved to run Python on the web using FCGI without > WSGI? I can feel the flames already. This isn't the only reason I want > to know, but one reason is that I want to use Python 3.1 and as I > understand, this will have to wait for the WSGI 2.0 specification to > ensure time isn't wasted. I am willing to bet that the FCGI libraries haven't been upgraded to Python 3.x, either. I suspect that the most 3.x-updating work will be going into WSGI and the adapters. E.g. http://www.saddi.com/software/news/archives/64-Dabbling-in-Python-3.0.html You may want to rethink the Python 3.x requirement, though. It will probably be much less a waste of your time to write your app using a framework like Django or Pylons on Python 2.x and then upgrade to Python 3.x when they do. > I apologize if the questions are ridiculous. I've just recently got > into web programming and it seems that in order for me to use Python, > I need a deep understanding of web servers, HTTP, FCGI, etc. I have > more questions but they go more off topic, so I will save it for > another thread, another day. Knowing something about HTTP will certainly help get into the right mindset to know what limitations and capabilities web apps can have. Typically, though, you use a framework that abstracts most of this stuff away from you. You usually only need to delve into the details in very specific circumstances. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From lists at cheimes.de Tue Aug 25 21:49:42 2009 From: lists at cheimes.de (Christian Heimes) Date: Wed, 26 Aug 2009 03:49:42 +0200 Subject: break unichr instead of fix ord? In-Reply-To: References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: Jan Kaliszewski wrote: > Are you sure, you couldn't have UCS-4-compiled Python distro > for Windows?? :-O Nope, Windows require UCS-2 builds. Christian From davea at ieee.org Tue Aug 25 22:02:56 2009 From: davea at ieee.org (Dave Angel) Date: Tue, 25 Aug 2009 22:02:56 -0400 Subject: Help with arrays In-Reply-To: References: Message-ID: <4A9497D0.3010203@ieee.org> Stephen Fairchild wrote: > Philip Semanchuk wrote: > > >> On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: >> >> >>> Hello! I'm working on an exercise wherein I have to write a Guess The >>> Number game, but it's the computer who's guessing MY number. I can get >>> it to work, but there's one obvious problem: the computer generates >>> random numbers until one of them corresponds to my number, but it will >>> often generate one number (eg. 4) numerous times, meaning it doesn't >>> know that this number is invalid. What I mean is, it will sometimes >>> use 37 tries to guess a number out of 1 - 9, which makes no sense, >>> since it should only take 9 tries, at most. I was trying to find a way >>> to make a dynamic list of all the numbers the computer generates in >>> the loop and then make it re-generate the number if the previous >>> number is present in the list, so it doesn't keep on generating 4 (as >>> an example). I don't know if that makes sense... Basically, we humans >>> know that once something is incorrect, there's no point in trying to >>> use it as the answer next time, because we already know it's >>> incorrect. How do I go about coding this in Python? I'm still quite >>> new to the language so any help will be appreciated... >>> >> One cheap way to do it (not necessarily efficient) is to make a list >> of your possible guesses (e.g. range(1,10)), use random.shuffle() to >> put them in random order and then run through the guesses one at a time. >> > > import random > import time > > l = range(1, 10) > > while l: > print l.pop(random.randint(0, len(l) - 1)) > time.sleep(2) > > While both of these will work well, I'd point out that a direct translation of your question is to use a set. Define an empty set, and each time you try a number unsuccessfully, add it to the set. Then just use while x in myset: x = newguess() to find the next guess. This approach isn't as efficient, but it's a useful paradigm to understand. A separate question is whether the human is supposed to tell the computer whether the guess is high or low. If so, you can eliminate many numbers on each guess. For example, suppose the solution is 8. A guess of 5 would say "too low." Then you'd cross off now only 5 but 1-4 as well. With this change the best solution changes from a random shuffle to a binary search. DaveA From exarkun at twistedmatrix.com Tue Aug 25 22:19:59 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Wed, 26 Aug 2009 02:19:59 -0000 Subject: web frameworks that support Python 3 In-Reply-To: References: Message-ID: <20090826021959.7027.186838236.divmod.xquotient.13@localhost.localdomain> On 01:41 am, aahz at pythoncraft.com wrote: >In article >, >Graham Dumpleton wrote: >>On Aug 24, 6:34=A0am, Sebastian Wiesner wrote: >>> >>>In any case, there is bottle [1], which provides a *very minimal* >>>framewo= >>rk >>>for WSGI web development. =A0Don't expect too much, it is really >>>small, a= >>nd >>>doesn't do much more than routing and minimal templating. >>> >>>However, it is the only Python-3-compatible web framework I know of. >>> >>>[1]http://bottle.paws.de/page/start >> >>There is one big flaw with your claim. That is the there is no WSGI >>specification for Python 3.0 as yet. Anything that claims to work with >>WSGI and Python 3.0 is just a big guess as far as how WSGI for Python >>3.0 may work. > >Perhaps you meant "library" instead of "specification"? He meant specification. Python 3.x is different enough from any Python 2.x release that PEP 333 no longer completely makes sense. It needs to be modified to be applicable to Python 3.x. So, in the sense that there is no written down, generally agreed upon specification for what WSGI on Python 3.x means, there is no... specification. There is, however, apparently, a library. ;) Jean-Paul From phily05 at gmail.com Tue Aug 25 22:27:53 2009 From: phily05 at gmail.com (Phil) Date: Tue, 25 Aug 2009 19:27:53 -0700 (PDT) Subject: Python on the Web References: Message-ID: Thank you for the helpful and timely response. My interest in Python 3.1 was actually to develop a framework. Again, I can feel the flames. :) I understand there are enough frameworks but I actually have no applications that I wish to develop. I enjoy developing these kinds of things from scratch as a learning experience. I've been doing fine with 2.x and WSGI, even without understanding half of this stuff. It is actually my first Python project. Haha. I just have my own design philosophies that I wish to experiment with. Python 3.x just makes everything nicer with UNICODE, etc. Although you've been helpful with almost all of the mentioned concerns, I am still looking for more details on some of the questions I've asked. So, if others stumble upon this post, feel free to contribute further. Thanks again. From graham.dumpleton at gmail.com Tue Aug 25 22:52:16 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Aug 2009 19:52:16 -0700 (PDT) Subject: web frameworks that support Python 3 References: Message-ID: <7c16aca3-05c2-4aad-a645-f1e8ca37a097@2g2000prl.googlegroups.com> On Aug 26, 12:19?pm, exar... at twistedmatrix.com wrote: > On 01:41 am, a... at pythoncraft.com wrote: > > > > > > >In article > >, > >Graham Dumpleton ? wrote: > >>On Aug 24, 6:34=A0am, Sebastian Wiesner wrote: > > >>>In any case, there is bottle [1], which provides a *very minimal* > >>>framewo= > >>rk > >>>for WSGI web development. =A0Don't expect too much, it is really > >>>small, a= > >>nd > >>>doesn't do much more than routing and minimal templating. > > >>>However, it is the only Python-3-compatible web framework I know of. > > >>>[1]http://bottle.paws.de/page/start > > >>There is one big flaw with your claim. That is the there is no WSGI > >>specification for Python 3.0 as yet. Anything that claims to work with > >>WSGI and Python 3.0 is just a big guess as far as how WSGI for Python > >>3.0 may work. > > >Perhaps you meant "library" instead of "specification"? > > He meant specification. > > Python 3.x is different enough from any Python 2.x release that PEP 333 > no longer completely makes sense. ?It needs to be modified to be > applicable to Python 3.x. > > So, in the sense that there is no written down, generally agreed upon > specification for what WSGI on Python 3.x means, there is no... > specification. > > There is, however, apparently, a library. ;) If you are talking about wsgiref then that was somewhat broken in Python 3.0. In Python 3.1 it works for some definition of works. The problem again being that since WSGI specification hasn't been updated for Python 3.X, that how it works will likely not match what the specification may eventually say. This will become more and more of a problem if WSGI specification isn't updated. At the moment the discussion is going around in circles, although, if I put my optimistic face on, I would say it is a slow inward spiral. Not quite a death spiral at least. Graham From wuwei23 at gmail.com Tue Aug 25 23:17:15 2009 From: wuwei23 at gmail.com (alex23) Date: Tue, 25 Aug 2009 20:17:15 -0700 (PDT) Subject: Python on the Web References: Message-ID: <5ee192da-c56a-4adf-9572-6e5b72bafead@y4g2000prf.googlegroups.com> Phil wrote: > My interest in Python 3.1 was actually to develop a framework. Again, > I can feel the flames. :) I understand there are enough frameworks but > I actually have no applications that I wish to develop. No offense intended, but that's probably the worst approach to take. Frameworks created for the sake of creating a framework, as opposed to those written to meet a defined need, tend to be the worst examples of masturbatory coding. From phily05 at gmail.com Tue Aug 25 23:25:31 2009 From: phily05 at gmail.com (Phil) Date: Tue, 25 Aug 2009 20:25:31 -0700 (PDT) Subject: Python on the Web References: <5ee192da-c56a-4adf-9572-6e5b72bafead@y4g2000prf.googlegroups.com> Message-ID: On Aug 25, 11:17?pm, alex23 wrote: > Phil wrote: > > My interest in Python 3.1 was actually to develop a framework. Again, > > I can feel the flames. :) I understand there are enough frameworks but > > I actually have no applications that I wish to develop. > > No offense intended, but that's probably the worst approach to take. > > Frameworks created for the sake of creating a framework, as opposed to > those written to meet a defined need, tend to be the worst examples of > masturbatory coding. No offense taken. I understand your concern. I actually do have some important design decisions I wish to meet. It has sort of been a process of evaluating the things I love and hate most from existing frameworks. From metolone+gmane at gmail.com Tue Aug 25 23:40:46 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 25 Aug 2009 20:40:46 -0700 Subject: Division and right shift in python References: <3f74e020908251648k7b391a09g78b155507b2f23c4@mail.gmail.com> Message-ID: "Cevahir Demirkiran" wrote in message news:3f74e020908251648k7b391a09g78b155507b2f23c4 at mail.gmail.com... > Hi, > > I would like to do a floor division by a power of 2 in python to make it > faster than / (modular division in 2.x). > However, it is slower. > What is the reason of that? > I checked them via: > > def f2(x,n): > t1 = clock() > r = x/pow(2,n) > t2 = clock() > print (t2-t1) > print r > t2 = clock() > r = x>>n > t3 = clock() > print (t3-t2) > print r > It's not slower on my system, but note the inconsistent results also: >>> f2(1024,5) 3.47396033483e-06 32 2.19077375482e-06 32 >>> f2(1024,5) 4.84135603429e-06 32 3.08499440393e-06 32 >>> f2(1024,5) 4.6782844052e-06 32 3.77604384028e-06 32 Time it with timeit... C:\>python -m timeit -n 10000000 -s x=1024 "x>>5" 10000000 loops, best of 3: 0.113 usec per loop C:\>python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" 10000000 loops, best of 3: 0.468 usec per loop Right-shift is over 4x faster. -Mark From graham.dumpleton at gmail.com Tue Aug 25 23:45:26 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Aug 2009 20:45:26 -0700 (PDT) Subject: Python on the Web References: <5ee192da-c56a-4adf-9572-6e5b72bafead@y4g2000prf.googlegroups.com> Message-ID: On Aug 26, 1:17?pm, alex23 wrote: > Phil wrote: > > My interest in Python 3.1 was actually to develop a framework. Again, > > I can feel the flames. :) I understand there are enough frameworks but > > I actually have no applications that I wish to develop. > > No offense intended, but that's probably the worst approach to take. > > Frameworks created for the sake of creating a framework, as opposed to > those written to meet a defined need, tend to be the worst examples of > masturbatory coding. I would in part actually disagree with that. The problem with people creating frameworks to meet some defined need is that they often implement only just enough of that framework to meet that need and nothing more. End result is that the framework is more often than not ever fleshed out enough to be of much use to anyone else. Its existence though just pollutes the Internet with more crap that one has to wade through. Since there is already a plethora of good frameworks out there, if writing an application, you are better of using one of the existing frameworks. If interested in working at the framework level, you would still be much better off looking at the existing frameworks, first learn how they work and then consider contributing to them, rather than implementing your own. For some related reading, see: http://lucumr.pocoo.org/2009/7/30/nih-in-the-wsgi-world As far as low level framework (or anti frameworks), suggest looking at Werkzeug, Paste/Pylons and bobo. I'll comment more on original message later. Graham From clp2 at rebertia.com Tue Aug 25 23:51:30 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Tue, 25 Aug 2009 20:51:30 -0700 Subject: Division and right shift in python In-Reply-To: References: <3f74e020908251648k7b391a09g78b155507b2f23c4@mail.gmail.com> Message-ID: <50697b2c0908252051w2c0ad860t46a7651b2ccabcf1@mail.gmail.com> On Tue, Aug 25, 2009 at 8:40 PM, Mark Tolonen wrote: > > "Cevahir Demirkiran" wrote in message > news:3f74e020908251648k7b391a09g78b155507b2f23c4 at mail.gmail.com... >> >> Hi, >> >> I would like to do a floor division by a power of 2 in python to make it >> faster than / (modular division in 2.x). >> However, it is slower. >> What is the reason of that? >> I checked them via: >> >> def f2(x,n): >> ? t1 = clock() >> ? r = x/pow(2,n) >> ? t2 = clock() >> ? print (t2-t1) >> ? print r >> ? t2 = clock() >> ? r = x>>n >> ? t3 = clock() >> ? print (t3-t2) >> ? print r >> > > It's not slower on my system, but note the inconsistent results also: > >>>> f2(1024,5) > > 3.47396033483e-06 > 32 > 2.19077375482e-06 > 32 >>>> >>>> f2(1024,5) > > 4.84135603429e-06 > 32 > 3.08499440393e-06 > 32 >>>> >>>> f2(1024,5) > > 4.6782844052e-06 > 32 > 3.77604384028e-06 > 32 > > Time it with timeit... > > C:\>python -m timeit -n 10000000 -s x=1024 "x>>5" > 10000000 loops, best of 3: 0.113 usec per loop > > C:\>python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" > 10000000 loops, best of 3: 0.468 usec per loop > > Right-shift is over 4x faster. Adjusting for not having to lookup the name "pow", right shift is still faster, but only slightly. chris at morpheus ~ $ python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" 10000000 loops, best of 3: 0.318 usec per loop chris at morpheus ~ $ python -m timeit -n 10000000 -s x=1024 "x/(2**5)" 10000000 loops, best of 3: 0.0973 usec per loop chris at morpheus ~ $ python -m timeit -n 10000000 -s x=1024 "x>>5" 10000000 loops, best of 3: 0.0885 usec per loop Cheers, Chris -- http://blog.rebertia.com From metolone+gmane at gmail.com Tue Aug 25 23:53:52 2009 From: metolone+gmane at gmail.com (Mark Tolonen) Date: Tue, 25 Aug 2009 20:53:52 -0700 Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: wrote in message news:2ad21a79-4a6c-42a7-8923-beb304bb5e99 at v20g2000yqm.googlegroups.com... > In Python 2.5 on Windows I could do [*1]: > > # Create a unicode character outside of the BMP. > >>> a = u'\U00010040' > > # On Windows it is represented as a surogate pair. > >>> len(a) > 2 > >>> a[0],a[1] > (u'\ud800', u'\udc40') > > # Create the same character with the unichr() function. > >>> a = unichr (65600) > >>> a[0],a[1] > (u'\ud800', u'\udc40') > > # Although the unichr() function works fine, its > # inverse, ord(), doesn't. > >>> ord (a) > TypeError: ord() expected a character, but string of length 2 found > > On Python 2.6, unichr() was "fixed" (using the word > loosely) so that it too now fails with characters outside > the BMP. > > >>> a = unichr (65600) > ValueError: unichr() arg not in range(0x10000) (narrow Python build) > > Why was this done rather than changing ord() to accept a > surrogate pair? > > Does not this effectively make unichr() and ord() useless > on Windows for all but a subset of unicode characters? Switch to Python 3? >>> x='\U00010040' >>> import unicodedata >>> unicodedata.name(x) 'LINEAR B SYLLABLE B025 A2' >>> ord(x) 65600 >>> hex(ord(x)) '0x10040' >>> unicodedata.name(chr(0x10040)) 'LINEAR B SYLLABLE B025 A2' >>> ord(chr(0x10040)) 65600 >>> print(ascii(chr(0x10040))) '\ud800\udc40' -Mark From christopher.nebergall at gmail.com Wed Aug 26 00:32:28 2009 From: christopher.nebergall at gmail.com (Christopher Nebergall) Date: Tue, 25 Aug 2009 22:32:28 -0600 Subject: PyObject_CallFunction and writable memory Message-ID: I'm working a patch to a hex editor (frhed) written in c++ so it can load python scripts. Internally the c++ code has a unsigned char * of possibly serveral hundred megs which I want to send into the python code to modify. What is the best way to send the unsigned char * as writable memory into the python code, so I don't have to duplicate the memory in order to return a modified copy? I'm currently using "PyObject_CallFunction(pFunc, "(s#)",p->lpbMemory, p->dwSize);" to send an immutable string but I haven't seen what I need to set in the format string which makes the data writable to python. The solution can be for either python 2.6 or 3.1. Thanks, Christopher From graham.dumpleton at gmail.com Wed Aug 26 00:34:23 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Tue, 25 Aug 2009 21:34:23 -0700 (PDT) Subject: Python on the Web References: Message-ID: <08ac740a-de74-4b5d-94af-35ab4dbe6ecc@m3g2000pri.googlegroups.com> A few additional comments on top of what others have said. On Aug 26, 11:09?am, Phil wrote: > I've seen lots of web sites explaining everything, but for whatever > reason I seem to not be picking something up. > I am a graphical person, which is probably the reason I haven't found > my answer. > May somebody please confirm if my diagram accurately represents the > stack, generally speaking. > > http://i26.tinypic.com/1fe82x.png > > Even if that is the case, I'm having a hard time understanding the > differences. I guess wsgiref has absolutely nothing to do with FCGI/ > SCGI/CGI and simply receives and responds to HTTP requests following > the WSGI specification? Technically it receives and responses to request based on HTTP specification, not WSGI specification. The underlying HTTP server translates to and communicates with a Python web application using the WSGI interface. > Does it just spawn a new thread for each > request? If so, then how is this any different than a production > server with FCGI? I would describe there as being four major ways that WSGI can be hosted. These are: 1. Custom build HTTP/WSGI server written in Python. Production quality examples are CherryPy WSGI server and Paste HTTP server. You shouldn't use wsgiref for anything but very simple stuff. 2. Per request process execution by way of CGI and a CGI/WSGI adapter. This could be under Apache or any other web server which supports CGI. 3. Module that embeds Python interpreter into a C based web server. Example are mod_wsgi and mod_python for Apache. Note that mod_python would infrequently be used to host WSGI and doesn't include its own WSGI adapter. These days mod_wsgi for Apache would be used. Processes in this would be persistent. 4. Module in a web server that allows one to communicate using a custom protocol with a separate persistent web application process hosting the web application through a WSGI interface. This convers FASTCGI, SCGI and AJP. The mod_wsgi module for Apache has a hybrid mode which work in a similar way but uses an internal protocol. Amongst these, there are many variations as far as number of process and threads. For a bit of discussion about this in relation to mod_wsgi read: http://code.google.com/p/modwsgi/wiki/ProcessesAndThreading > The way I am understanding the 'Production' side of that picture is > that the web server (eg. lighttpd) creates a single FCGI process. FASTCGI isn't restricted to a single process, nor single threading. Whether a particular implementation allows for the variations depends on the implementation. > The > FCGI process is actually the entry point of the Framework/Application > which sets up Flup's WSGIServer, being the interface between FCGI and > the Framework/Application? What I mean is, it is just the code that > the web server loads to start with, example... > ? ? from flup.server.fcgi import WSGIServer > ? ? from app import application > ? ? WSGIServer(application).run() > ... Then for each HTTP request, Flup's WSGIServer creates a new thread > to handle the request? > > As I've read elsewhere, "These days, FastCGI is never used directly. Even back in time, I don't think it was really ever used as a generic interface that people worked with directly, there was always a more usable layer built on top of it. > Just like mod_python it is only used for the deployment of WSGI > applications. The mod_python module isn't used just for WSGI applications and is probably rarely used for them. This is because mod_python has its own interface for building web applications. It also has abilities to hook into Apache request handling phases, meaning it can do more than host a a content handler/web application. > As far as I understand, the main (or only?) reasoning > for this is because WSGI makes Python applications easier to deploy > without having to worry about whether using FCGI/SCGI/CGI. WSGI provides for portability, it isn't necessarily easier to use than mod_python. > What would be involved to run Python on the web using FCGI without > WSGI? I can feel the flames already. No, you really don't want to do that. > This isn't the only reason I want > to know, but one reason is that I want to use Python 3.1 and as I > understand, this will have to wait for the WSGI 2.0 specification to > ensure time isn't wasted. Then look at mod_wsgi. It already has support for Python 3.X. Some aspects of how it implements WSGI 1.0 may change, but will not be too much and details are being sorted out in the back rooms as we speak. See: http://code.google.com/p/modwsgi/wiki/ChangesInVersion0300 The other option is CherryPy WSGI server as that is close to a Python 3.X release as well, as I perceive it. I wouldn't bother waiting for WSGI 2.0. That is more of a pipe dream. There will be an updated WSGI 1.0 for Python 3.0. Graham > I apologize if the questions are ridiculous. I've just recently got > into web programming and it seems that in order for me to use Python, > I need a deep understanding of web servers, HTTP, FCGI, etc. I have > more questions but they go more off topic, so I will save it for > another thread, another day. > > I realize there is a large number of questions, so thanks for any help. From nicola.larosa at gmail.com Wed Aug 26 01:54:59 2009 From: nicola.larosa at gmail.com (Nicola Larosa (tekNico)) Date: Tue, 25 Aug 2009 22:54:59 -0700 (PDT) Subject: Code formatting question: conditional expression References: <421c8c9d-efb5-4e70-9321-51736b42bc9a@g10g2000yqh.googlegroups.com> Message-ID: <46c5c882-c38b-4439-a3cf-62783309cc08@t13g2000yqt.googlegroups.com> Nicola Larosa wrote: > Here's my take: > > ? ? excessblk = Block(total - P.BASE, srccol, > carry_button_suppress=True > ? ? ? ? ) if total > P.BASE else None Oops, it got shortened out: line longer than 72 chars, acceptable in code, but not in email. I'll try again. If the first line is too long, I would write it like this: excessblk = Block(total - P.BASE, srccol, carry_button_suppress=True) if total > P.BASE else None If not, like this: excessblk = Block(total - P.BASE, srccol, cbs=True ) if total > P.BASE else None If the condition or the last value were too long to make it all fit on two lines, then it would probably best to revert to a plain "if" statement. -- Nicola Larosa - http://www.tekNico.net/ From http Wed Aug 26 02:19:25 2009 From: http (Paul Rubin) Date: 25 Aug 2009 23:19:25 -0700 Subject: your favorite debugging tool? References: Message-ID: <7xpraj5c7m.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > My normal debug technique is wolf fencing* (eg; print statements) That method was formerly completely automated on the web: http://www.st.cs.uni-saarland.de/askigor/faq.php It was amazing. Further info is here: http://www.st.cs.uni-saarland.de/dd/ From hendrik at microcorp.co.za Wed Aug 26 02:44:50 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 26 Aug 2009 08:44:50 +0200 Subject: Object Reference question In-Reply-To: References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <200908260844.50220.hendrik@microcorp.co.za> On Tuesday 25 August 2009 21:32:09 Aahz wrote: > In article , > > Hendrik van Rooyen wrote: > >On Friday 21 August 2009 08:07:18 josef wrote: > >> My main focus of this post is: "How do I find and use object reference > >> memory locations?" > >> > >>>> a = [1,2,3,4] > >>>> id(a) > > > >8347088 > > Of course, that doesn't actually allow you to do anything... Well - if the OP is the sort of person who likes juggling with running chainsaws, then he can look up a thread I started about a thing I called a "can", which enabled you to get the object back from a string representation of the ID. I did not want to open that "can" of worms again, and I thought that answering half a question was better than nothing... *weg* - Hendrik From ben+python at benfinney.id.au Wed Aug 26 02:47:33 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 26 Aug 2009 16:47:33 +1000 Subject: Code formatting question: conditional expression References: <421c8c9d-efb5-4e70-9321-51736b42bc9a@g10g2000yqh.googlegroups.com> <46c5c882-c38b-4439-a3cf-62783309cc08@t13g2000yqt.googlegroups.com> Message-ID: <877hwrf4vu.fsf@benfinney.id.au> "Nicola Larosa (tekNico)" writes: > Nicola Larosa wrote: > > Here's my take: > > > > ? ? excessblk = Block(total - P.BASE, srccol, > > carry_button_suppress=True > > ? ? ? ? ) if total > P.BASE else None > > Oops, it got shortened out: line longer than 72 chars, acceptable in > code, but not in email. I'll try again. Fine in email; just munged on your behalf (and probably without your knowledge) by your email service provider. If you don't want that happening, it's probably best to avoid Google Mail. -- \ ?I wish a robot would get elected president. That way, when he | `\ came to town, we could all take a shot at him and not feel too | _o__) bad.? ?Jack Handey | Ben Finney From eckhardt at satorlaser.com Wed Aug 26 03:03:27 2009 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 26 Aug 2009 09:03:27 +0200 Subject: Need help with Python scoping rules References: Message-ID: Jean-Michel Pichavant wrote: > class Color: > def __init__(self, r, g,b): > pass > BLACK = Color(0,0,0) > > It make sens from a design point of view to put BLACK in the Color > namespace. But I don't think it's possible with python. class Color: ... setattrib(Color, "BLACK", Color(0,0,0)) Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From deets at nospam.web.de Wed Aug 26 03:33:26 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Aug 2009 09:33:26 +0200 Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] In-Reply-To: <3da50b33-d79e-4579-9240-ef430ea7c697@m38g2000yqh.googlegroups.com> References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> <7fivlrF2lsrsuU1@mid.uni-berlin.de> <3da50b33-d79e-4579-9240-ef430ea7c697@m38g2000yqh.googlegroups.com> Message-ID: <7fk6q6F2jq5otU1@mid.uni-berlin.de> Evan Driscoll schrieb: > On Aug 25, 3:47 pm, Evan Driscoll wrote: >> So here is my simplified version that only works for globals: > > So I think this works if (1) you only use changed_value in the same > module as it's defined in (otherwise it picks up the globals from the > module it's defined in, which is almost certainly not what you want), > and (2) the value you want to change is just a simple variable and not > either something like "os.path" or a builtin. > > I have worked on this a bit more and have something that addresses > these issues in at least the cases I've tested. I'm not going to post > the code here, but it is up at > http://pages.cs.wisc.edu/~driscoll/python/utils.py > and there are a few unit tests at > http://pages.cs.wisc.edu/~driscoll/python/utils_test.py > > I solved issue (1) by reintroducing the use of inspect to walk back up > the stack a couple frames, but I pulled out the f_globals member > instead of f_locals. > > Issue (2a) I fixed by splitting the variable name at periods and > walking through successive dictionaries with each component. Issue > (2b) I fixed by looking for a '__builtins__' entry if the name I'm > looking up doesn't exist. > > Right now it's sort of hackish... it probably doesn't respond > particularly well if things go unexpectedly (e.g. a bad variable name > is given) and I should probably verify that the value is unchanged > during the with statement and throw an exception otherwise, but it > probably works well enough for my purposes for now. > > Comments are appreciated... a couple of the things in there it seems > like there could very well be reimplementations of things that are > already done. I'd still won't use it :) instead, something like this might be something I'd use, if I need a local "rebound". Or, again, just use a different *name* alltogether. foo = "bar" @apply def f(foo="baz"): ... Other than that, for your original use-case, I have a context-manager I call "safe modifier" that - takes an object, key and value - stores the old value of the key on the object - sets the new value - on exit, restores the old value This is for e.g. temporary config-changes in tests. Diez From deets at nospam.web.de Wed Aug 26 03:34:31 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Aug 2009 09:34:31 +0200 Subject: PyObject_CallFunction and writable memory In-Reply-To: References: Message-ID: <7fk6s7F2jq5otU2@mid.uni-berlin.de> Christopher Nebergall schrieb: > I'm working a patch to a hex editor (frhed) written in c++ so it can > load python scripts. Internally the c++ code has a unsigned char * of > possibly serveral hundred megs which I want to send into the python > code to modify. What is the best way to send the unsigned char * as > writable memory into the python code, so I don't have to duplicate the > memory in order to return a modified copy? I'm currently using > "PyObject_CallFunction(pFunc, "(s#)",p->lpbMemory, p->dwSize);" to > send an immutable string but I haven't seen what I need to set in the > format string which makes the data writable to python. The solution > can be for either python 2.6 or 3.1. Take a look at the buffer-protocol. Diez From deets at nospam.web.de Wed Aug 26 03:36:21 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Aug 2009 09:36:21 +0200 Subject: Python, qt, and lgpl In-Reply-To: <1e7a9056-db73-4c4f-be8a-f1b65a91daec@v20g2000yqm.googlegroups.com> References: <1e7a9056-db73-4c4f-be8a-f1b65a91daec@v20g2000yqm.googlegroups.com> Message-ID: <7fk6vlF2jq5otU3@mid.uni-berlin.de> sturlamolden schrieb: > On 25 Aug, 21:45, Terry Reedy wrote: > >> Will be good news if realized. > > Good news for everyone except Riverbank. And only if LGPL is something you can live with. Some projects require more liberal licenses. Or is there a commercial license available, too? Diez From benjamin at python.org Wed Aug 26 03:37:40 2009 From: benjamin at python.org (Benjamin Peterson) Date: Wed, 26 Aug 2009 07:37:40 +0000 (UTC) Subject: =?utf-8?b?UHlPYmplY3RfQ2FsbEZ1bmN0aW9u?= and writable memory References: Message-ID: Christopher Nebergall gmail.com> writes: > > I'm currently using > "PyObject_CallFunction(pFunc, "(s#)",p->lpbMemory, p->dwSize);" to > send an immutable string but I haven't seen what I need to set in the > format string which makes the data writable to python. The solution > can be for either python 2.6 or 3.1. Have a look at the buffer interface: http://docs.python.org/3.1/c-api/buffer.html From sdementen at gmail.com Wed Aug 26 03:50:17 2009 From: sdementen at gmail.com (seb) Date: Wed, 26 Aug 2009 00:50:17 -0700 (PDT) Subject: conditional for-statement References: Message-ID: <0fce5130-3057-4393-94a2-320568ddc072@n11g2000yqb.googlegroups.com> On Aug 25, 11:57?pm, Piet van Oostrum wrote: > You can also say: > [x+y for x in range(3) for y in range(4) if x < y] > If you want to write this as a loop you have to put the for's on > separate lines separated by colons, so why not the if also? Or would you > also like to have the for's on one line? indeed, we could have the for's on one line too. In fact, if you have a double loop without any body that is specific to the outer loop, you can merge the two lines. Similarly, if you have a loop with a if (ie filter) without any body having to be executed outside the if, having them on the same line is also clearer. | for x in range(3): | for x in range(3) for y in range(4): | for y in range(4): could be written as | body | body and | for x in range(3): | for x in range(3) if cond(x): | if cond(x): could be written as | body | body Such loops are in fact mentally just one loop over the cartesian product (product set) of the two iterators or over the filter set of the iterator respectively in these examples. Moreover, for 'body' longer than a couple of lines, it is quite useful to see immediately that there is no additional code that could be only specific to the outher loop ie, when writing all in one line, we can be sure that we do not have this situation | for x in range(3): | for y in range(4): | long body | ... | long body | body related to outer loop The naturalness of iteration in the various comprehensions and the generator expressions can be smoothly extended to the standard code iteration. BTW, I noticed this inconsistency when, coming back to python after a couple of weeks of no python programming, I started coding loops like for obj in list_obj if obj.Size > 100: print(obj) and got an error message about syntax. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org- Hide quoted text - > > - Show quoted text - From vlastimil.brom at gmail.com Wed Aug 26 04:05:17 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Wed, 26 Aug 2009 10:05:17 +0200 Subject: break unichr instead of fix ord? In-Reply-To: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: <9fdb569a0908260105s7858b648of081d439bb73e3ae@mail.gmail.com> 2009/8/25 : > In Python 2.5 on Windows I could do [*1]: > > ?# Create a unicode character outside of the BMP. > ?>>> a = u'\U00010040' > > ?# On Windows it is represented as a surogate pair. > ?>>> len(a) > ?2 > ?>>> a[0],a[1] > ?(u'\ud800', u'\udc40') > > ?# Create the same character with the unichr() function. > ?>>> a = unichr (65600) > ?>>> a[0],a[1] > ?(u'\ud800', u'\udc40') > > ?# Although the unichr() function works fine, its > ?# inverse, ord(), doesn't. > ?>>> ord (a) > ?TypeError: ord() expected a character, but string of length 2 found > > On Python 2.6, unichr() was "fixed" (using the word > loosely) so that it too now fails with characters outside > the BMP. > > ?>>> a = unichr (65600) > ?ValueError: unichr() arg not in range(0x10000) (narrow Python build) > > Why was this done rather than changing ord() to accept a > surrogate pair? > > Does not this effectively make unichr() and ord() useless > on Windows for all but a subset of unicode characters? > -- > http://mail.python.org/mailman/listinfo/python-list > Hi, I'm not sure about the exact reasons for this behaviour on narrow builds either (maybe the consistency of the input/ output data to exactly one character?). However, if I need these functions for higher unicode planes, the following rather hackish replacements seem to work. I presume, there might be smarter ways of dealing with this, but anyway... hth, vbr #### not (systematically) tested ##################################### import sys def wide_ord(char): try: return ord(char) except TypeError: if len(char) == 2 and 0xD800 <= ord(char[0]) <= 0xDBFF and 0xDC00 <= ord(char[1]) <= 0xDFFF: return (ord(char[0]) - 0xD800) * 0x400 + (ord(char[1]) - 0xDC00) + 0x10000 else: raise TypeError("invalid character input") def wide_unichr(i): if i <= sys.maxunicode: return unichr(i) else: return ("\U"+str(hex(i))[2:].zfill(8)).decode("unicode-escape") From lib_team at yahoo.fr Wed Aug 26 04:08:48 2009 From: lib_team at yahoo.fr (=?iso-8859-1?Q?Pr=E9mon_Nom?=) Date: Wed, 26 Aug 2009 08:08:48 +0000 (GMT) Subject: Getting the current PyCFunction while in a python function Message-ID: <526667.17255.qm@web24301.mail.ird.yahoo.com> Hi I would like to get the PyCFunction object which corresponds to the current function which is executed. I call PyFrameObject* frame = PyEval_GetFrame() I try to parse frame->f_valuestack, but I don't know how to get the index of the function in the stack or event the size of the stack to be able to parse it (from end to begin and to stop on the first PyCFunctionObject). There is a member call stack size (frame->f_valuestack->f_code->co_stacksize) but it doesn't correspond to the frame->f_valuestack size :-( In fact i know that when i call "print(myFunctionPrintNumber(123)) There is PyCfunctionObject corresponding to myFunctionPrintNumber but i don't know how to acces it :/ because i don't know how to get/compute frame->f_valuestack size or to get/compute directly the index where the current executed function is. Please help me!!! Regards -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon at brunningonline.net Wed Aug 26 04:14:33 2009 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 26 Aug 2009 09:14:33 +0100 Subject: Python for professsional Windows GUI apps? In-Reply-To: <63bb7834-80ac-4894-9ef5-2598ecac72cc@k19g2000yqn.googlegroups.com> References: <20090825132439.d6cb18ca.feliphil@gmx.net> <63bb7834-80ac-4894-9ef5-2598ecac72cc@k19g2000yqn.googlegroups.com> Message-ID: <8c7f10c60908260114q45ac2ae0i91fba0ed56808d6a@mail.gmail.com> 2009/8/26 geekworking : > If you are planning a database driven app, you should first settle on > a DB server. Any real enterprise DB system will put all of the > business logic in the database server. The choice of a front end > should be secondary. The trend for some years now has been to get behavior out of the database and into the application, where it belongs. True, we tend to keep the presentation tier separate too, but we really don't "put all of the business logic in the database server". Going back to the OP's question, it would be worth taking a look at what the resolver boys are up to: . -- Cheers, Simon B. From bruno.42.desthuilliers at websiteburo.invalid Wed Aug 26 04:16:13 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Wed, 26 Aug 2009 10:16:13 +0200 Subject: Python on the Web In-Reply-To: References: Message-ID: <4a94ef42$0$27774$426a74cc@news.free.fr> Phil a ?crit : > I've seen lots of web sites explaining everything, but for whatever > reason I seem to not be picking something up. > I am a graphical person, which is probably the reason I haven't found > my answer. > May somebody please confirm if my diagram accurately represents the > stack, generally speaking. > > http://i26.tinypic.com/1fe82x.png Seems correct. > Even if that is the case, I'm having a hard time understanding the > differences. I guess wsgiref has absolutely nothing to do with FCGI/ > SCGI/CGI and simply receives and responds to HTTP requests following > the WSGI specification? Yeps. > Does it just spawn a new thread for each > request? Not AFAICT. > The way I am understanding the 'Production' side of that picture is > that the web server (eg. lighttpd) creates a single FCGI process. The > FCGI process is actually the entry point of the Framework/Application > which sets up Flup's WSGIServer, being the interface between FCGI and > the Framework/Application? What I mean is, it is just the code that > the web server loads to start with, example... > from flup.server.fcgi import WSGIServer > from app import application > WSGIServer(application).run() > ... Then for each HTTP request, Flup's WSGIServer creates a new thread > to handle the request? I didn't bother reading Flup's source code, but I suppose this might be the case. > As I've read elsewhere, "These days, FastCGI is never used directly. > Just like mod_python it is only used for the deployment of WSGI > applications." As far as I understand, the main (or only?) reasoning > for this is because WSGI makes Python applications easier to deploy > without having to worry about whether using FCGI/SCGI/CGI. Nor about which web server you use (Apache, lighthttpd, whatever). > What would be involved to run Python on the web using FCGI without > WSGI? I can feel the flames already. This isn't the only reason I want > to know, but one reason is that I want to use Python 3.1 and as I > understand, this will have to wait for the WSGI 2.0 specification to > ensure time isn't wasted. My humble opinion (based on years of experience in both Python and web programming) is that you're taking the wrong approach. I can only second Robert Kern here: use an existing, well maintained wsgi-compliant framework like Django, Pylons etc, and wait for the framework to be ported to python 3.x. Any other solution will almost certainly end up needing a complete rewrite anytime soon. > I apologize if the questions are ridiculous. I've just recently got > into web programming and it seems that in order for me to use Python, > I need a deep understanding of web servers, HTTP, FCGI, etc. Programming for the web - whatever the language & techno - indeed require a deep (or at least correct) understanding of HTTP and web servers, yes. Even with the abstraction layers provided by frameworks, you still need to understand how the whole damn thing works, what's an HTTP resquest & response and quite a few other things as well. From frank at chagford.com Wed Aug 26 04:22:41 2009 From: frank at chagford.com (Frank Millman) Date: Wed, 26 Aug 2009 10:22:41 +0200 Subject: Move dictionary from instance to class level Message-ID: Hi all I have a class that uses a dictionary to map message numbers to methods. Here is a simple example - class MyClass(object): def __init__(self): self.method_dict = {} self.method_dict[0] = self.method_0 self.method_dict[1] = self.method_1 def on_message_received(self, msg): self.method_dict[msg]() def method_0(self): print 'in method_0' def method_1(self): print 'in method_1' I have quite a few methods, so the dictionary is growing - up to 28 methods so far. To avoid having to recreate the dictionary every time I create an instance of the class, I tried to move it up to the class level. Unfortunately it does not work. This is what I tried - class MyClass(object): method_dict = {} method_dict[0] = method_0 # this gives an error method_dict[1] = method_1 def on_message_received(self, msg): self.method_dict[msg]() def method_0(self): print 'in method_0' def method_1(self): print 'in method_1' As written above, I get the following error - NameError: name 'method_0' is not defined If I try self.method_0, I get 'self' is not defined. If I try __class__.method_0, I get '__class__' is not defined. If I try MyClass.method_0, I get 'MyClass' is not defined. Is there any variation on this theme that will work? #---------------------------------------------------- Ok, I found a variation that seems to work. Is this the preferred way, or is there a better alternative? class MyClass(object): def on_message_received(self, msg): #self.method_dict[msg]() # had to change this to get it to work self.method_dict[msg](self) def method_0(self): print 'in method_0' def method_1(self): print 'in method_1' MyClass.method_dict = {} MyClass.method_dict[0] = MyClass.method_0 MyClass.method_dict[1] = MyClass.method_1 As you can see, I had to add 'self' to the method arguments when calling the method. Any comments? Thanks Frank Millman From tw55413 at gmail.com Wed Aug 26 04:29:52 2009 From: tw55413 at gmail.com (erikj) Date: Wed, 26 Aug 2009 01:29:52 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: <7f519c34-2d6e-4fff-9489-dae43c6b2df1@r42g2000yqj.googlegroups.com> Hi, You could have a look at Camelot, to see if it fits your needs : http://www.conceptive.be/projects/camelot/ it was developed with cross platform business apps in mind. when developing Camelot, we tried to build it using wxWidgets first (because of the licensing at that time), but it turned out that developing with QT proved to be much more straightforward. QT is documented very well and you seldom encounter 'strange' issues that cost hours of time to pinpoint and fix. the datagrid was developed to be able to handle millions of database records without glitches and is flexible thanks to QT's model-view-delegate framework. we do print barcodes with this app (even directly to zebra printers) if you have questions regarding Camelot, please feel free to post on our mailing list : http://groups.google.com/group/project-camelot Regards, Erik On Aug 24, 2:08?pm, Gilles Ganault wrote: > Hello > > ? ? ? ? I was wondering if some people in this ng use Python and some GUI > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > applications, and if yes, what it's like, the pros and cons, etc. > > I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. > > I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. > > Thank you. From pierre.gaillard at gmail.com Wed Aug 26 04:30:32 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Wed, 26 Aug 2009 01:30:32 -0700 (PDT) Subject: quantiles of a student distribution Message-ID: Hello... Do you know how I can calculate the quantiles of a student distribution in pyhton ? Thanks From piet at cs.uu.nl Wed Aug 26 04:41:56 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 26 Aug 2009 10:41:56 +0200 Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> <84154e6e-c425-4b71-89e3-7d2877a19418@m7g2000prd.googlegroups.com> Message-ID: >>>>> 7stud (7) wrote: >7> Thanks for the response. My OS is mac osx 10.4.11. I'm not really >7> sure how to check my locale settings. Here is some stuff I tried: >7> $ echo $LANG >7> $ echo $LC_ALL >7> $ echo $LC_CTYPE >7> $ locale >7> LANG= >7> LC_COLLATE="C" >7> LC_CTYPE="C" >7> LC_MESSAGES="C" >7> LC_MONETARY="C" >7> LC_NUMERIC="C" >7> LC_TIME="C" >7> LC_ALL="C" IIRC, Mac OS X 10.4 does not set LANG or LC_* automatically. In 10.5 Terminal has an option in the preferences to set LANG according to the encoding chosen (and presumably the language of the user). -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From clp2 at rebertia.com Wed Aug 26 04:54:05 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 26 Aug 2009 01:54:05 -0700 Subject: Move dictionary from instance to class level In-Reply-To: References: Message-ID: <50697b2c0908260154y2f4f6852ga3d6a3c41bd768de@mail.gmail.com> On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote: > Hi all > > I have a class that uses a dictionary to map message numbers to methods. > > Here is a simple example - > > ? ?class MyClass(object): > ? ? ? ?def __init__(self): > ? ? ? ? ? ?self.method_dict = {} > ? ? ? ? ? ?self.method_dict[0] = self.method_0 > ? ? ? ? ? ?self.method_dict[1] = self.method_1 > > ? ? ? ?def on_message_received(self, msg): > ? ? ? ? ? ?self.method_dict[msg]() > > ? ? ? ?def method_0(self): > ? ? ? ? ? ?print 'in method_0' > > ? ? ? ?def method_1(self): > ? ? ? ? ? ?print 'in method_1' > > I have quite a few methods, so the dictionary is growing - up to 28 methods > so far. To avoid > having to recreate the dictionary every time I create an instance of the > class, I tried to move it > up to the class level. Unfortunately it does not work. This is what I > tried - > > ? ?class MyClass(object): > ? ? ? ?method_dict = {} > ? ? ? ?method_dict[0] = method_0 ?# this gives an error > ? ? ? ?method_dict[1] = method_1 > > ? ? ? ?def on_message_received(self, msg): > ? ? ? ? ? ?self.method_dict[msg]() > > ? ? ? ?def method_0(self): > ? ? ? ? ? ?print 'in method_0' > > ? ? ? ?def method_1(self): > ? ? ? ? ? ?print 'in method_1' > > As written above, I get the following error - > ? ?NameError: name 'method_0' is not defined > > If I try self.method_0, I get 'self' is not defined. Right, because you're in the *class* body; there's no "current instance" to be "self"; in fact, there's not even any class for there to be instances of yet. > If I try __class__.method_0, I get '__class__' is not defined. Right, because the class isn't created until its body has finished executing > If I try MyClass.method_0, I get 'MyClass' is not defined. See previous note. The class name can't be bound to anything until the class itself has been created. > Is there any variation on this theme that will work? > > #---------------------------------------------------- > > Ok, I found a variation that seems to work. > > Is this the preferred way, or is there a better alternative? A class MyClass(object): def on_message_received(self, msg): self.method_dict[msg](self) def method_0(self): print 'in method_0' def method_1(self): print 'in method_1' method_dict method_dict = {0: method_0, 1: method_1} #note this comes *after* the methods in question have been defined Is there some reason you aren't using a list instead of a dict? e.g. method_dict = [method_0, method_1, method_2, etc] For that matter, why are you associating methods with integers in the first place? Cheers, Chris -- http://blog.rebertia.com From mriedel at inova-semiconductors.de Wed Aug 26 04:56:28 2009 From: mriedel at inova-semiconductors.de (Michael Riedel) Date: Wed, 26 Aug 2009 10:56:28 +0200 Subject: Q: multiprocessing.Queue size limitations or bug... Message-ID: <4A94F8BC.8050304@inova-semiconductors.de> Sorry for being not more specific but I'm not absolutely certain whether I encountered a bug or did anything wrong: The (stupid) code below results in a stall forever or not at 'p0.join()' depending on the value of TROUBLE_MAKER. Any help, thoughts, comments? Thank you for your time. Michael # ---------------------------------------------------------------------- from multiprocessing import Process, Queue # bit vector size BVS=8 # TROUBLE_MAKER=12 # for greater values p0.join() is never satisfied... def evaluate(q, id, start=0, stop=2**BVS): cmin = {0: []} for mask0 in range(start, stop): for mask1 in range(0, 2**BVS): for mask2 in range(mask1, TROUBLE_MAKER): cmin[0].append((mask0, mask1, mask2)) print 'process %d finished (dict layout: %d/%d)...' % (id, len(cmin), len(cmin[0])) q.put(cmin.copy()) q.close() if __name__ == '__main__': q0 = Queue() q1 = Queue() q2 = Queue() q3 = Queue() part = 2**BVS/4 p0 = Process(target=evaluate, args=(q0, 0, 0*part, 1*part), name='worker_0') p1 = Process(target=evaluate, args=(q1, 1, 1*part, 2*part), name='worker_1') p2 = Process(target=evaluate, args=(q2, 2, 2*part, 3*part), name='worker_2') p3 = Process(target=evaluate, args=(q3, 3, 3*part, 4*part), name='worker_3') p0.start() print 'process 0 started...' p1.start() print 'process 1 started...' p2.start() print 'process 2 started...' p3.start() print 'process 3 started...' # main process stalls at p0.join() for bigger TROUBLE_MAKER p0.join() p1.join() p2.join() p3.join() res0 = q0.get() res1 = q1.get() res2 = q2.get() res3 = q3.get() print 'results fetched...' # ---------------------------------------------------------------------- -- From eckhardt at satorlaser.com Wed Aug 26 05:04:43 2009 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 26 Aug 2009 11:04:43 +0200 Subject: Need help with Python scoping rules References: Message-ID: Ulrich Eckhardt wrote: > Jean-Michel Pichavant wrote: >> class Color: >> def __init__(self, r, g,b): >> pass >> BLACK = Color(0,0,0) >> >> It make sens from a design point of view to put BLACK in the Color >> namespace. But I don't think it's possible with python. > > class Color: > ... > > setattrib(Color, "BLACK", Color(0,0,0)) Apart from it being "setattr" and not "setattrib", a simple Color.BLACK = Color(0,0,0) should have done the job here. However, what I had in mind was this: class Color: _colors = [ ("BLACK", (0,0,0)), ("WHITE", (1,1,1)) ] def __str__(self): # try to locate a name for name, rgb in Color._colors: if self.rgb==rgb: return name # no name found, just format as a triplet return "(%s, %s, %s)" % self.rgb # add symbolic names for name, rgb in Color._colors: setattr(Colors, name, Color(rgb)) ...which I got as suggestion on my question how to model C enumeration lookalikes. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From frank at chagford.com Wed Aug 26 05:21:03 2009 From: frank at chagford.com (Frank Millman) Date: Wed, 26 Aug 2009 11:21:03 +0200 Subject: Move dictionary from instance to class level References: Message-ID: On Aug 26, 10:54 am, Chris Rebert wrote: > On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote: > > A > > class MyClass(object): > def on_message_received(self, msg): > self.method_dict[msg](self) > > def method_0(self): > print 'in method_0' > > def method_1(self): > print 'in method_1' > method_dict > > method_dict = {0: method_0, 1: method_1} > #note this comes *after* the methods in question have been defined > Thanks, Chris. This is much better. > Is there some reason you aren't using a list instead of a dict? > e.g. method_dict = [method_0, method_1, method_2, etc] > > For that matter, why are you associating methods with integers in the > first place? > I actually use constants to define my messages, like this - (MESSAGE_ONE ,MESSAGE_TWO ,MESSAGE_THREE ) = xrange(3) I can then refer to the messages by their description, but internally it uses integers. Frank From frank at chagford.com Wed Aug 26 05:22:21 2009 From: frank at chagford.com (Frank Millman) Date: Wed, 26 Aug 2009 11:22:21 +0200 Subject: Move dictionary from instance to class level References: Message-ID: <6ZKdnagdF6mZnwjXnZ2dnUVZ8jKdnZ2d@saix.net> On Aug 26, 10:54 am, Chris Rebert wrote: > On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote: > > A > > class MyClass(object): > def on_message_received(self, msg): > self.method_dict[msg](self) > > def method_0(self): > print 'in method_0' > > def method_1(self): > print 'in method_1' > method_dict > > method_dict = {0: method_0, 1: method_1} > #note this comes *after* the methods in question have been defined > Thanks, Chris. This is much better. > Is there some reason you aren't using a list instead of a dict? > e.g. method_dict = [method_0, method_1, method_2, etc] > > For that matter, why are you associating methods with integers in the > first place? > I actually use constants to define my messages, like this - (MESSAGE_ONE ,MESSAGE_TWO ,MESSAGE_THREE ) = xrange(3) I can then refer to the messages by their description, but internally it uses integers. Frank From frank at chagford.com Wed Aug 26 05:22:21 2009 From: frank at chagford.com (Frank Millman) Date: Wed, 26 Aug 2009 11:22:21 +0200 Subject: Move dictionary from instance to class level References: Message-ID: On Aug 26, 10:54 am, Chris Rebert wrote: > On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote: > > A > > class MyClass(object): > def on_message_received(self, msg): > self.method_dict[msg](self) > > def method_0(self): > print 'in method_0' > > def method_1(self): > print 'in method_1' > method_dict > > method_dict = {0: method_0, 1: method_1} > #note this comes *after* the methods in question have been defined > Thanks, Chris. This is much better. > Is there some reason you aren't using a list instead of a dict? > e.g. method_dict = [method_0, method_1, method_2, etc] > > For that matter, why are you associating methods with integers in the > first place? > I actually use constants to define my messages, like this - (MESSAGE_ONE ,MESSAGE_TWO ,MESSAGE_THREE ) = xrange(3) I can then refer to the messages by their description, but internally it uses integers. Frank From frank at chagford.com Wed Aug 26 05:48:38 2009 From: frank at chagford.com (Frank Millman) Date: Wed, 26 Aug 2009 11:48:38 +0200 Subject: Move dictionary from instance to class level References: Message-ID: "Frank Millman" wrote: Apologies for the triple-post. I use google-groups for reading c.l.py, but I know that some people reject messages from there due to the volume of spam, so on the odd occasion when I want to send something I fire up Outlook Express and send it from there. It seems to be misbehaving today. Sorry about that. Frank From somebody at somewhere.com Wed Aug 26 05:52:09 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Wed, 26 Aug 2009 10:52:09 +0100 Subject: Help with arrays References: Message-ID: Dave Angel wrote: > With this change the best solution changes from a random shuffle to a > binary search. Which is not what the OP asked for. Anyway, I think whatever solution is chosen it's probably best written as a generator. The new pushback syntax may prove useful. -- Stephen Fairchild From dksreddy at gmail.com Wed Aug 26 06:05:41 2009 From: dksreddy at gmail.com (Sandy) Date: Wed, 26 Aug 2009 03:05:41 -0700 (PDT) Subject: all possible matchings of elements of two lists Message-ID: Hi all, I basically want all possible matchings of elements from two lists, Ex: [1,2] [a,b,c] Required: [ [(1,a),(2,b)] [(1,b),(2,c)] [(1,c),(2,b)] [(1,b),(2,a)] [(1,c),(2,a)] [(1,a),(2,c)] ] My thought is to get all possible permutations of two lists given and select any combination and use zip to get the tuples. Repeat this for all possible combinations. Any other ideas? Sandy From no.email at please.post Wed Aug 26 06:08:38 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 10:08:38 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: In John Posner writes: >Stephen Hansen said: >> This sounds like a fundamental confusion -- a namespace is not >> equivalent to a scope, really, I think. >> ... Hmm. I can't find Stephen Hansen's original post anywhere. Where did you come across it? Is there an *official* write-up where these issues are discussed? To put it differently, where exactly in the Python docs would someone learning Python go to answer my original query? TIA! kynn From pavlovevidence at gmail.com Wed Aug 26 06:16:32 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Aug 2009 03:16:32 -0700 (PDT) Subject: Python, qt, and lgpl References: <1e7a9056-db73-4c4f-be8a-f1b65a91daec@v20g2000yqm.googlegroups.com> Message-ID: On Aug 25, 5:04?pm, sturlamolden wrote: > On 25 Aug, 21:45, Terry Reedy wrote: > > > Will be good news if realized. > > Good news for everyone except Riverbank. Oh well, Riverbank could have played ball but they didn't, so I guess I don't care if it's bad news for them. Carl Banks From manish.paradkar at gmail.com Wed Aug 26 06:28:01 2009 From: manish.paradkar at gmail.com (manish) Date: Wed, 26 Aug 2009 18:28:01 +0800 Subject: Python Processor Message-ID: <7670c8130908260328l6982ef4etad802a755b85a44f@mail.gmail.com> Hi, I am also wondering about how to implement a soft core reconfigurable processor in a FPGA which would directly execute the compiled python bytecode. I am trying to understand the bytecode format but apart from http://docs.python.org/library/dis.html there is hardly any documentation on the python bytecodes. Before going through the one of the existing VM implementations, i want to know if there is there any informaition available which elaborates on the structure of the bytecodes. Like details regarding co_names, co_cellvars, co_freevars, the concept of frames, global, local, objects, functions etc with respect to the bytecode. Thanks Manish -------------- next part -------------- An HTML attachment was scrubbed... URL: From robin at reportlab.com Wed Aug 26 06:30:22 2009 From: robin at reportlab.com (Robin Becker) Date: Wed, 26 Aug 2009 11:30:22 +0100 Subject: ubuntu dist-packages Message-ID: <4A950EBE.1090707@chamonix.reportlab.co.uk> I was surprised a couple of days ago when trying to assist a colleage with his python setup on a ubuntu 9.04 system. We built our c-extensions and manually copied them into place, but site-packages wasn't there. It seems that ubuntu now wants stuff to go into lib/python2.6/dist-packages. What is the relation between dist-packages/site-packages if any? Is this just a name change or is there some other problem being addressed? For developers is it best just to create one's own private installations from the original tarballs? -- Robin Becker From dksreddy at gmail.com Wed Aug 26 06:32:35 2009 From: dksreddy at gmail.com (dksr) Date: Wed, 26 Aug 2009 03:32:35 -0700 (PDT) Subject: all possible matchings of elements of two lists References: Message-ID: <2eb06442-7369-4c9f-83ad-b8f9d3d08c07@d4g2000yqa.googlegroups.com> Ok this is how I do it: l1 = [1,2] l2= ['a','b','c'] res = [] l2 = permute(l2) for i in l2: lis = [l1,l2] res.append(zip(*lis)) # or use map depending on what u want res.append(map(None,*lis)) print res On Aug 26, 11:05?am, Sandy wrote: > Hi all, > I basically want all possible matchings of elements from two lists, > Ex: [1,2] [a,b,c] > > Required: > ? ?[ [(1,a),(2,b)] > ? ? ?[(1,b),(2,c)] > ? ? ?[(1,c),(2,b)] > ? ? ?[(1,b),(2,a)] > ? ? ?[(1,c),(2,a)] > ? ? ?[(1,a),(2,c)] > ? ?] > > My thought is to get all possible permutations of two lists given and > select any combination and use zip to get the tuples. Repeat this for > all possible combinations. > > Any other ideas? > Sandy From ryniek90 at gmail.com Wed Aug 26 06:44:07 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Wed, 26 Aug 2009 12:44:07 +0200 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile In-Reply-To: References: Message-ID: <4A9511F7.7030909@gmail.com> > [snip] >>>> Here's my script code: >>>> *http://paste.ubuntu.com/259310/ >>>> >>>> *Shouldn't that bug be patched already :-? >>> Are you giving it the contents of the file when it's actually expecting >>> the filename? >>> >> >> Of course the content of the file: > [snip] >> See? *backup_obj.add(read_obj.read())* >> In previous pasted Traceback you can see >> *backup_obj.add(read_bin_obj)* - read_obj_bin was a reference to the >> *read_obj.read()* . >> > The documentation lists the methods "add" and "addfile". Pick one and > provide the values it's expecting. For example, if you choose "add" then > provide the filename, not the contents of the file. > >> Do only I have this problem or Python programming under Windows is >> nightmare? > > It's only a nightmare if you don't follow the documentation. :-) > Hahah right. My fault. Must remember to read documentation so many times until I find the solution. Thanks, now works fine. :-) From deets at nospam.web.de Wed Aug 26 06:46:13 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Aug 2009 12:46:13 +0200 Subject: ubuntu dist-packages References: Message-ID: <7fki3lF2kirnkU1@mid.uni-berlin.de> Robin Becker wrote: > I was surprised a couple of days ago when trying to assist a colleage with > his python setup on a ubuntu 9.04 system. > > We built our c-extensions and manually copied them into place, but > site-packages wasn't there. It seems that ubuntu now wants stuff to go > into lib/python2.6/dist-packages. > > What is the relation between dist-packages/site-packages if any? Is this > just a name change or is there some other problem being addressed? > > For developers is it best just to create one's own private installations > from the original tarballs? I don't know much about the atrocities distributions commit to python-installations (ripping out distutils "because it's a developer-only thing", trying to save a few bytes here and there by unifying install-locations between interpreter versions and whatnot), but I think the main problem is that you don't use distutils - or setuptools (that gets often a bad rap even if for most cases it works flawless) If you'd use that to build & install your extension, it would figure out where to place the resulting package (or egg) by itself. Diez From dickinsm at gmail.com Wed Aug 26 06:52:22 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Wed, 26 Aug 2009 03:52:22 -0700 (PDT) Subject: all possible matchings of elements of two lists References: Message-ID: On Aug 26, 11:05?am, Sandy wrote: > Hi all, > I basically want all possible matchings of elements from two lists, > Ex: [1,2] [a,b,c] > > Required: > ? ?[ [(1,a),(2,b)] > ? ? ?[(1,b),(2,c)] > ? ? ?[(1,c),(2,b)] > ? ? ?[(1,b),(2,a)] > ? ? ?[(1,c),(2,a)] > ? ? ?[(1,a),(2,c)] > ? ?] If you're using Python 2.6 (or 3.1), you might find the itertools module helpful: Python 2.6.2 (r262:71600, Aug 26 2009, 09:40:44) [GCC 4.2.1 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import itertools >>> for p in itertools.permutations('abc', 2): print zip([1,2], p) ... [(1, 'a'), (2, 'b')] [(1, 'a'), (2, 'c')] [(1, 'b'), (2, 'a')] [(1, 'b'), (2, 'c')] [(1, 'c'), (2, 'a')] [(1, 'c'), (2, 'b')] -- Mark From no.email at please.post Wed Aug 26 06:57:32 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 10:57:32 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: In <7figv3F2m3p0dU1 at mid.uni-berlin.de> "Diez B. Roggisch" writes: >Classes are not scopes. This looks to me like a major wart, on two counts. First, one of the goals of OO is encapsulation, not only at the level of instances, but also at the level of classes. Your comment suggests that Python does not fully support class-level encapsulation. Second, my example shows that Python puts some peculiar restrictions on recursion. Recursion! One of the central concepts in the theory of functions! This is shown most clearly by the following elaboration of my original example: class Demo(object): def fact_rec(n): if n < 2: return 1 else: return n * fact_rec(n - 1) def fact_iter(n): ret = 1 for i in range(1, n + 1): ret *= i return ret classvar1 = fact_iter(5) classvar2 = fact_rec(5) This code won't compile as shown, but it does compile if the last line (the call to the recursive fact_rec) is commented out. There is no justification for discriminating against recursive functions in this context. Recursive functions should be OK wherever functions are OK. I can't think of any other language that allows recursion but not anywhere. Is there any good reason (from the point of view of Python's overall design) for not fixing this? kynn From chris0wj at gmail.com Wed Aug 26 07:25:13 2009 From: chris0wj at gmail.com (Chris) Date: Wed, 26 Aug 2009 04:25:13 -0700 (PDT) Subject: multiprocessing managers and socket connection. References: <722664f1-81af-45da-ae40-070bca8f3ee0@k6g2000yqn.googlegroups.com> <0af6687a-e36d-47c3-af5e-7e66eacbb3ce@v23g2000pro.googlegroups.com> Message-ID: <7d8f3f17-3cd7-4eb1-b049-2990d638cc46@o6g2000yqj.googlegroups.com> On Aug 25, 9:11?pm, Terry wrote: > On Aug 25, 10:14?pm, Chris wrote: > > > > > I've been using multiprocessing managers and I really like the > > functionality. > > > I have a question about reconnecting to a manager. I have a situation > > where I start on one machine (A) a manager that is listening and then > > on another machine (B) connects to that manager and uses its proxy > > object to call functions on the manager's computer; this all works as > > expected. But, if the manager from A shuts down, B's application won't > > notice because in the MP code it ignores socket error > > errno.ECONNREFUSED. If A becomes available again or is restarted, B > > doesn't automatically reconnect either and continue its operation. > > It's function is basically stopped. > > > Here is the code from connection.py: > > while 1: > > ? ? ? ? try: > > ? ? ? ? ? ? s.connect(address) > > ? ? ? ? except socket.error, e: > > ? ? ? ? ? ? if e.args[0] != errno.ECONNREFUSED: # connection refused > > ? ? ? ? ? ? ? ? debug('failed to connect to address %s', address) > > ? ? ? ? ? ? ? ? raise > > ? ? ? ? ? ? time.sleep(0.01) > > ? ? ? ? else: > > ? ? ? ? ? ? break > > > How can I have B automatically reconnect to A and continue its work > > once A is available again? > > I think you need to retry repeatedly until successfully connected. > > br, Terry I'm having issue after once connected. If the server goes down during a long-running connection. I would want to be notified so I could try to reconnect. I'm doing more experimenting now and will try to post an example. From tibor.beck at hotmail.com Wed Aug 26 07:44:25 2009 From: tibor.beck at hotmail.com (gentlestone) Date: Wed, 26 Aug 2009 04:44:25 -0700 (PDT) Subject: Usefull python tutorial Message-ID: <0bd7592d-d705-4938-b13d-61157d7fbc7a@c2g2000yqi.googlegroups.com> Can somebody give me an advise where I can found a really good online tutorial? All I found are useless. For example no tutorial I found explains this piece of code: someList = [element for element in otherList if element is not None] or this example: a = a or [] There are only stupid elementary examples in the tutorials I found. From pavlovevidence at gmail.com Wed Aug 26 07:52:43 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Aug 2009 04:52:43 -0700 (PDT) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> On Aug 26, 3:57?am, kj wrote: > In <7figv3F2m3p0... at mid.uni-berlin.de> "Diez B. Roggisch" writes: > > >Classes are not scopes. > > This looks to me like a major wart, on two counts. Class statements *are* scopes, they are just not accessible from scopes nested within them. > First, one of the goals of OO is encapsulation, not only at the > level of instances, but also at the level of classes. ?Your comment > suggests that Python does not fully support class-level encapsulation. I can't answer this, I don't even know what you are talking about. The OO notion of encapsulation that I'm familar means that an object can seal off access to private data. This has nothing to do with class statement scoping. > Second, my example shows that Python puts some peculiar restrictions > on recursion. ?Recursion! ?One of the central concepts in the theory > of functions! ?This is shown most clearly by the following elaboration > of my original example: > > class Demo(object): > ? ? def fact_rec(n): > ? ? ? ? if n < 2: > ? ? ? ? ? ? return 1 > ? ? ? ? else: > ? ? ? ? ? ? return n * fact_rec(n - 1) > > ? ? def fact_iter(n): > ? ? ? ? ret = 1 > ? ? ? ? for i in range(1, n + 1): > ? ? ? ? ? ? ret *= i > ? ? ? ? return ret > > ? ? classvar1 = fact_iter(5) > ? ? classvar2 = fact_rec(5) > > This code won't compile as shown, but it does compile if the last > line (the call to the recursive fact_rec) is commented out. ?There > is no justification for discriminating against recursive functions > in this context. ?Recursive functions should be OK wherever functions > are OK. ?I can't think of any other language that allows recursion > but not anywhere. Inside class statements are not the place for this kind of thing. Define functions like fact_rec outside the class statement. > Is there any good reason (from the point of view of Python's overall > design) for not fixing this? I suspect that no reason, however profound, would satisfy you. Therefore I will merely answer your question without fanfare, and you can take it as you will. 1. One of the key aspects of Python's design is that attributes must be accessed explicitly with dot notation. Accessing class scopes from nested functions would (seemingly) allow access to class attributes without the dotted notation. Therefore it is not allowed. 2. This is considered more important that your ability to define recursive functions in the class statement. Carl Banks From cevomed at gmail.com Wed Aug 26 07:53:01 2009 From: cevomed at gmail.com (=?ISO-8859-9?Q?Cevahir_Demirk=FDran?=) Date: Wed, 26 Aug 2009 13:53:01 +0200 Subject: Division and right shift in python In-Reply-To: References: <3f74e020908251648k7b391a09g78b155507b2f23c4@mail.gmail.com> Message-ID: <3f74e020908260453p181d8134va4047019b60831b1@mail.gmail.com> Thanks for the answer. Run it with a big number: f2(9230821908403878236537264867326482638462035732098490238409328947638257462745672354627356427356742563256745362772537532756732673275732,9) I had this result: 8.1015883211e-06 1.06158743591e-05 512 2009/8/26 Mark Tolonen > > > "Cevahir Demirkiran" wrote in message > news:3f74e020908251648k7b391a09g78b155507b2f23c4 at mail.gmail.com... > > Hi, >> >> I would like to do a floor division by a power of 2 in python to make it >> faster than / (modular division in 2.x). >> However, it is slower. >> What is the reason of that? >> I checked them via: >> >> def f2(x,n): >> t1 = clock() >> r = x/pow(2,n) >> t2 = clock() >> print (t2-t1) >> print r >> t2 = clock() >> r = x>>n >> t3 = clock() >> print (t3-t2) >> print r >> >> > It's not slower on my system, but note the inconsistent results also: > > f2(1024,5) >>>> >>> 3.47396033483e-06 > 32 > 2.19077375482e-06 > 32 > >> f2(1024,5) >>>> >>> 4.84135603429e-06 > 32 > 3.08499440393e-06 > 32 > >> f2(1024,5) >>>> >>> 4.6782844052e-06 > 32 > 3.77604384028e-06 > 32 > > Time it with timeit... > > C:\>python -m timeit -n 10000000 -s x=1024 "x>>5" > 10000000 loops, best of 3: 0.113 usec per loop > > C:\>python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" > 10000000 loops, best of 3: 0.468 usec per loop > > Right-shift is over 4x faster. > > -Mark > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Cevahir Demirkiran -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Wed Aug 26 08:11:25 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 26 Aug 2009 05:11:25 -0700 Subject: Usefull python tutorial In-Reply-To: <0bd7592d-d705-4938-b13d-61157d7fbc7a@c2g2000yqi.googlegroups.com> References: <0bd7592d-d705-4938-b13d-61157d7fbc7a@c2g2000yqi.googlegroups.com> Message-ID: <50697b2c0908260511u7445f434x6fc8481c2bb5c305@mail.gmail.com> On Wed, Aug 26, 2009 at 4:44 AM, gentlestone wrote: > Can somebody give me an advise where I can found a really good online > tutorial? All I found are useless. For example no tutorial I found > explains this piece of code: > > ? ?someList = [element for element in otherList if element is not > None] See http://docs.python.org/tutorial/datastructures.html#list-comprehensions > or this example: > > ? ?a = a or [] That's a bit more obscure, and I'm not entirely surprised it's not in a tutorial: http://docs.python.org/reference/expressions.html#boolean-operations You might want to try the official tutorial (unless it's the one you're complaining about): http://docs.python.org/tutorial/index.html I've also heard good things about Dive Into Python: http://diveintopython.org/ Cheers, Chris -- http://blog.rebertia.com From cevomed at gmail.com Wed Aug 26 08:17:48 2009 From: cevomed at gmail.com (=?ISO-8859-9?Q?Cevahir_Demirk=FDran?=) Date: Wed, 26 Aug 2009 14:17:48 +0200 Subject: Division and right shift in python In-Reply-To: <3f74e020908260453p181d8134va4047019b60831b1@mail.gmail.com> References: <3f74e020908251648k7b391a09g78b155507b2f23c4@mail.gmail.com> <3f74e020908260453p181d8134va4047019b60831b1@mail.gmail.com> Message-ID: <3f74e020908260517y77d6824esa9813b64031f5bf8@mail.gmail.com> The previous one was slower but now it is faster. How can I make this more consistent? Why cannot I control it? Where can I find the algorithms implemented under for example pow, /, %, etc.? I could not see them in python documentation? f2(281367918279371279712863756486284619792197836426862028028824908239084023984967328564836783686836834628136791827937127971286375648628461979219783642686202802882490823908402398496732856483678368683683462813679182793712797128637564862846197921978364268620280288249082390840239849673285648367836868368346,9) 8.3809534317e-06 6.70476276809e-06 512 Thanks in advance, 26 A?ustos 2009 13:53 tarihinde Cevahir Demirk?ran yazd?: > Thanks for the answer. > Run it with a big number: > > f2(9230821908403878236537264867326482638462035732098490238409328947638257462745672354627356427356742563256745362772537532756732673275732,9) > > I had this result: > > 8.1015883211e-06 > 1.06158743591e-05 > 512 > > 2009/8/26 Mark Tolonen > > > > >> "Cevahir Demirkiran" wrote in message >> news:3f74e020908251648k7b391a09g78b155507b2f23c4 at mail.gmail.com... >> >> Hi, >>> >>> I would like to do a floor division by a power of 2 in python to make it >>> faster than / (modular division in 2.x). >>> However, it is slower. >>> What is the reason of that? >>> I checked them via: >>> >>> def f2(x,n): >>> t1 = clock() >>> r = x/pow(2,n) >>> t2 = clock() >>> print (t2-t1) >>> print r >>> t2 = clock() >>> r = x>>n >>> t3 = clock() >>> print (t3-t2) >>> print r >>> >>> >> It's not slower on my system, but note the inconsistent results also: >> >> f2(1024,5) >>>>> >>>> 3.47396033483e-06 >> 32 >> 2.19077375482e-06 >> 32 >> >>> f2(1024,5) >>>>> >>>> 4.84135603429e-06 >> 32 >> 3.08499440393e-06 >> 32 >> >>> f2(1024,5) >>>>> >>>> 4.6782844052e-06 >> 32 >> 3.77604384028e-06 >> 32 >> >> Time it with timeit... >> >> C:\>python -m timeit -n 10000000 -s x=1024 "x>>5" >> 10000000 loops, best of 3: 0.113 usec per loop >> >> C:\>python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" >> 10000000 loops, best of 3: 0.468 usec per loop >> >> Right-shift is over 4x faster. >> >> -Mark >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > > > -- > Cevahir Demirkiran > -- Cevahir Demirkiran -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon at brunningonline.net Wed Aug 26 08:17:57 2009 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 26 Aug 2009 13:17:57 +0100 Subject: Usefull python tutorial In-Reply-To: <0bd7592d-d705-4938-b13d-61157d7fbc7a@c2g2000yqi.googlegroups.com> References: <0bd7592d-d705-4938-b13d-61157d7fbc7a@c2g2000yqi.googlegroups.com> Message-ID: <8c7f10c60908260517q6819c17qd5bd6070b02eace9@mail.gmail.com> 2009/8/26 gentlestone : > Can somebody give me an advise where I can found a really good online > tutorial? All I found are useless. is really good, as I remember, as is . For example no tutorial I found > explains this piece of code: > > ? ?someList = [element for element in otherList if element is not > None] or > or this example: > > ? ?a = a or [] Strangely not in the tutorial: . -- Cheers, Simon B. From davea at ieee.org Wed Aug 26 08:18:15 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 08:18:15 -0400 Subject: Division and right shift in python In-Reply-To: References: <3f74e020908251648k7b391a09g78b155507b2f23c4@mail.gmail.com> Message-ID: <4A952807.5090608@ieee.org> Mark Tolonen wrote: >
> "Cevahir Demirkiran" wrote in message > news:3f74e020908251648k7b391a09g78b155507b2f23c4 at mail.gmail.com... >> Hi, >> >> I would like to do a floor division by a power of 2 in python to make it >> faster than / (modular division in 2.x). >> However, it is slower. >> What is the reason of that? >> I checked them via: >> >> def f2(x,n): >> t1 = clock() >> r = x/pow(2,n) >> t2 = clock() >> print (t2-t1) >> print r >> t2 = clock() >> r = x>>n >> t3 = clock() >> print (t3-t2) >> print r >> > > It's not slower on my system, but note the inconsistent results also: > >>>> f2(1024,5) > 3.47396033483e-06 > 32 > 2.19077375482e-06 > 32 >>>> f2(1024,5) > 4.84135603429e-06 > 32 > 3.08499440393e-06 > 32 >>>> f2(1024,5) > 4.6782844052e-06 > 32 > 3.77604384028e-06 > 32 > > Time it with timeit... > > C:\>python -m timeit -n 10000000 -s x=1024 "x>>5" > 10000000 loops, best of 3: 0.113 usec per loop > > C:\>python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" > 10000000 loops, best of 3: 0.468 usec per loop > > Right-shift is over 4x faster. > > -Mark > > > >
> There have been languages and processors in which right shift has been notably faster than divide. But with Python on a Pentium, you're both just measuring overhead. The actual divide or shift is probably less than 5% of the time measured. And that overhead will vary between versions of the interpreter. I measured with Python 2.6.2 on Windows XP, and got C:\>python -m timeit -n 10000000 -s x=1024 "x>>5" 10000000 loops, best of 3: 0.112 usec per loop C:\>python -m timeit -n 10000000 -s x=1024 "x/pow(2,5)" 10000000 loops, best of 3: 0.384 usec per loop But the real overhead is in the function call to pow(). If that had been precalculated, then the time for divide is nearly as fast as for right shift. C:\>python -m timeit -n 10000000 -s x=1024 "x/32" 10000000 loops, best of 3: 0.135 usec per loop And I suspect that some other implementation might well show this quicker than the right shift. I would use whichever code most clearly represents the problem being solved. There are undoubtedly other ways to speed up the code, without trying to micro-optimize one expression. DaveA From davea at ieee.org Wed Aug 26 08:34:26 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 08:34:26 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A952BD2.8010608@ieee.org> Ulrich Eckhardt wrote: > Jean-Michel Pichavant wrote: > >> class Color: >> def __init__(self, r, g,b): >> pass >> BLACK = Color(0,0,0) >> >> It make sens from a design point of view to put BLACK in the Color >> namespace. But I don't think it's possible with python. >> > > class Color: > ... > > setattrib(Color, "BLACK", Color(0,0,0)) > > Uli > > Or instead of setattrib, Color.BLACK = Color(0,0,0) DaveA From IDOL at il.ibm.com Wed Aug 26 08:38:50 2009 From: IDOL at il.ibm.com (Ido Levy) Date: Wed, 26 Aug 2009 15:38:50 +0300 Subject: pygtk - What is the best way to change the mouse pointer Message-ID: Hello All, I am writing a dialog which one of its widget is a gtk.ComboBoxEntry ( let's assume widget in the example below is its instance ) When the user select one of the values from the gtk.ComboBoxEntry I need to run some calculations that takes a few seconds. In order to reflect calculation time to the user I want to switch the mouse pointer to an hour glass and back to arrow what it finish the calculation. I use the following code but it doesn't seems to work in a deterministic way. From time to time it skips the last line and keep the mouse pointer as an hour glass. watch = gtk.gdk.Cursor(gtk.gdk.WATCH) widget.window.set_cursor(watch) calculation code widget.window.set_cursor(None) I would appreciate your advice on the right way to implement this. Thanks Ido -------------- next part -------------- An HTML attachment was scrubbed... URL: From python at mrabarnett.plus.com Wed Aug 26 08:40:56 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 26 Aug 2009 13:40:56 +0100 Subject: Move dictionary from instance to class level In-Reply-To: References: Message-ID: <4A952D58.2050807@mrabarnett.plus.com> Frank Millman wrote: > On Aug 26, 10:54 am, Chris Rebert wrote: >> On Wed, Aug 26, 2009 at 1:22 AM, Frank Millman wrote: >> >> A >> >> class MyClass(object): >> def on_message_received(self, msg): >> self.method_dict[msg](self) >> >> def method_0(self): >> print 'in method_0' >> >> def method_1(self): >> print 'in method_1' >> method_dict >> >> method_dict = {0: method_0, 1: method_1} >> #note this comes *after* the methods in question have been defined >> > > Thanks, Chris. This is much better. > >> Is there some reason you aren't using a list instead of a dict? >> e.g. method_dict = [method_0, method_1, method_2, etc] >> >> For that matter, why are you associating methods with integers in the >> first place? >> > > I actually use constants to define my messages, like this - > > (MESSAGE_ONE > ,MESSAGE_TWO > ,MESSAGE_THREE > ) = xrange(3) > > I can then refer to the messages by their description, but internally it > uses integers. > An alternative is: >>> class MyClass(object): ... def on_message_received(self, msg): ... try: ... getattr(self, "method_%d" % msg)() ... except AttributeError: ... raise Exception("Unknown message") ... def method_0(self): ... print 'in method_0' ... def method_1(self): ... print 'in method_1' ... >>> my_obj = MyClass() >>> my_obj.on_message_received(0) in method_0 >>> my_obj.on_message_received(1) in method_1 >>> my_obj.on_message_received(2) Traceback (most recent call last): File "", line 1, in File "", line 6, in on_message_received Exception: Unknown message >>> From ben+python at benfinney.id.au Wed Aug 26 08:45:23 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Wed, 26 Aug 2009 22:45:23 +1000 Subject: ubuntu dist-packages References: Message-ID: <87tyzueobg.fsf@benfinney.id.au> Robin Becker writes: > What is the relation between dist-packages/site-packages if any? Is > this just a name change or is there some other problem being > addressed? The problem being addressed is to maintain the distinction between OS-vendor-managed files versus sysadmin-managed files. That is, the distinction between: * Python packages installed by the operating system package manager (the OS ?distribution?, as distinct from the Python-specific meaning of that term); versus * Python packages installed by the site administrator, outside the purview of the OS package manager. This distinction is important in operating systems with a functioning package manager. > For developers is it best just to create one's own private > installations from the original tarballs? Developers should be making changes as neither the system administrator nor the OS package manager, but as a regular user of the system. So installing to a user-specific package location seems best. -- \ ?Holy rising hemlines, Batman!? ?Robin | `\ | _o__) | Ben Finney From szport at gmail.com Wed Aug 26 08:51:20 2009 From: szport at gmail.com (zaur) Date: Wed, 26 Aug 2009 05:51:20 -0700 (PDT) Subject: Object's nesting scope Message-ID: Hi folk! What do you think about idea of "object's nesting scope" in python? Let's imaging this feature, for example, in this syntax: obj=: or : That's means that result object of evaluation is used as nested scope for evaluation. So is this idea useful? Zaur From martin.hellwig at dcuktec.org Wed Aug 26 09:02:04 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 26 Aug 2009 14:02:04 +0100 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: kj wrote: > First, one of the goals of OO is encapsulation, not only at the > level of instances, but also at the level of classes. Who says? Anyway, you could be right (I am not capable to judge it) and Python should change on this issue but from what I gathered, Pythons OO is inspired by the following: - Don't repeat yourself - Containing code into logical units makes it easier to understand and maintain. Note the absence of 'OO is defined as X so we are going to do X without thinking if X is actually the best way to do it' > Your comment suggests that Python does not fully support > class-level encapsulation. Probably right too, but being intrigued, why is that necessary, and given an example is that the best way to do it? > Second, my example shows that Python puts some peculiar restrictions > on recursion. Recursion! One of the central concepts in the theory > of functions! It is also one of the best ways to shoot yourself in the foot, but I ask you again, is the reason why you encountered this 'limitation' actually the best way to solve your problem? Please forgive my incompetence if this reply sounds harsh and patronizing. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From grahn+nntp at snipabacken.se Wed Aug 26 09:09:15 2009 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 26 Aug 2009 13:09:15 GMT Subject: Code formatting question: conditional expression References: <421c8c9d-efb5-4e70-9321-51736b42bc9a@g10g2000yqh.googlegroups.com> <46c5c882-c38b-4439-a3cf-62783309cc08@t13g2000yqt.googlegroups.com> <877hwrf4vu.fsf@benfinney.id.au> Message-ID: On Wed, 26 Aug 2009 16:47:33 +1000, Ben Finney wrote: > "Nicola Larosa (tekNico)" writes: > >> Nicola Larosa wrote: >> > Here's my take: >> > >> > ? ? excessblk = Block(total - P.BASE, srccol, >> > carry_button_suppress=True >> > ? ? ? ? ) if total > P.BASE else None >> >> Oops, it got shortened out: line longer than 72 chars, acceptable in >> code, but not in email. I'll try again. > > Fine in email; just munged on your behalf (and probably without your > knowledge) by your email service provider. If you don't want that > happening, it's probably best to avoid Google Mail. But this is Usenet (or at least it gets gatewayed there) and there are such limits here (either by common agreement or by RFC). Probably not Google's fault. /Jorgen -- // Jorgen Grahn O o . From deets at nospam.web.de Wed Aug 26 09:13:49 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 26 Aug 2009 15:13:49 +0200 Subject: Object's nesting scope References: Message-ID: <7fkqodF2llnghU1@mid.uni-berlin.de> zaur wrote: > Hi folk! > > What do you think about idea of "object's nesting scope" in python? > > Let's imaging this feature, for example, in this syntax: > > obj=: > > > or > > : > > > That's means that result object of evaluation is used as > nested scope for evaluation. > > So is this idea useful? Whom am we to judge? Sure if you propose this, you have some usecases in mind - how about you present these? Diez From bbxx789_05ss at yahoo.com Wed Aug 26 09:28:28 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Wed, 26 Aug 2009 06:28:28 -0700 (PDT) Subject: Need help with Python scoping rules References: Message-ID: <8219d86d-cf0b-457f-b823-550dcf7cbf71@p36g2000prn.googlegroups.com> On Aug 25, 7:26?pm, Dave Angel wrote: > Stephen Fairchild wrote: > > You are trying to run code in a class that does not exist yet. > > > def Demo(): > > ? ? def fact(n): > > ? ? ? ? if n < 2: > > ? ? ? ? ? ? return 1 > > ? ? ? ? else: > > ? ? ? ? ? ? return n * fact(n - 1) > > ? ? return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar": > > fact(5)}) > > Demo = Demo() > > > d = Demo() > > print d._classvar ? ?# prints 120 > > print d.fact(7) ? ? ?# prints 5040 > > print Demo ? ? ? ? ? # prints > > > > In all these messages, something I haven't seen pointed out is that > fact() has no self argument. ? > An "argument" is something that is specified in the the function call. I assume you are trying to state something like, "fact() is not defined with a parameter variable named self". However, that has never been a requirement in python: class A(object): def fact(n): print n fact("hello") a = A() a.fact() --output:-- hello <__main__.A object at 0x7faf0> From jawad.karachi2010 at gmail.com Wed Aug 26 09:29:31 2009 From: jawad.karachi2010 at gmail.com (Jawad Alam) Date: Wed, 26 Aug 2009 06:29:31 -0700 (PDT) Subject: "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ Message-ID: "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ "JOBS IN ALASKA IT" "JOBS IN ALASKA" "JOBS IN ALASKA IT" "JOBS IN ALASKA" "jobs in alaska anchorage" "jobs in alaska oil" "jobs in alaska usa" "jobs in alaska mines" ON http://jobs-in-alaska.blogspot.com/ V From bbxx789_05ss at yahoo.com Wed Aug 26 09:31:48 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Wed, 26 Aug 2009 06:31:48 -0700 (PDT) Subject: print() and unicode strings (python 3.1) References: <4eda8137-7db9-4c39-a2c1-3477b071f7f6@x5g2000prf.googlegroups.com> <4a92b83b$0$27209$9b622d9e@news.freenet.de> <4a92fb02$0$2582$9b622d9e@news.freenet.de> <84154e6e-c425-4b71-89e3-7d2877a19418@m7g2000prd.googlegroups.com> Message-ID: <811decac-b086-4ca1-af03-84c33819a710@a37g2000prf.googlegroups.com> On Aug 25, 6:34?am, Nobody wrote: > The underlying OS primitive can only handle bytes. If you read or write a > (unicode) string, Python needs to know which encoding is used. For Python > file objects created by the user (via open() etc), you can specify the > encoding; for those created by the runtime (e.g. sys.stdin), Python uses > the locale's LC_CTYPE category to select an encoding. > > Data written to or read from text streams is encoded or decoded using the > stream's encoding. Filenames are encoded and decoded using the > filesystem encoding (sys.getfilesystemencoding()). Anything else uses the > default encoding (sys.getdefaultencoding()). > > In Python 3, text streams are handled using io.TextIOWrapper: > > ? ? ? ?http://docs.python.org/3.1/library/io.html#text-i-o > > This implements a stream which can read and/or write text data on top of > one which can read and/or write binary data. The sys.std{in,out,err} > streams are instances of TextIOWrapper. You can get the underlying > binary stream from the "buffer" attribute, e.g.: > > ? ? ? ? sys.stdout.buffer.write(b'hello world\n') > > If you need to force a specific encoding (e.g. if the user has specified > an encoding via a command-line option), you can detach the existing > wrapper and create a new one, e.g.: > > ? ? ? ? sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = new_encoding) Thanks for the details. From mdekauwe at gmail.com Wed Aug 26 09:34:59 2009 From: mdekauwe at gmail.com (Mart.) Date: Wed, 26 Aug 2009 06:34:59 -0700 (PDT) Subject: Help with arrays References: Message-ID: <391bbc0f-08ea-4840-a2da-cb36b5632669@m38g2000yqh.googlegroups.com> On Aug 26, 3:02 am, Dave Angel wrote: > Stephen Fairchild wrote: > > Philip Semanchuk wrote: > > >> On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: > > >>> Hello! I'm working on an exercise wherein I have to write a Guess The > >>> Number game, but it's the computer who's guessing MY number. I can get > >>> it to work, but there's one obvious problem: the computer generates > >>> random numbers until one of them corresponds to my number, but it will > >>> often generate one number (eg. 4) numerous times, meaning it doesn't > >>> know that this number is invalid. What I mean is, it will sometimes > >>> use 37 tries to guess a number out of 1 - 9, which makes no sense, > >>> since it should only take 9 tries, at most. I was trying to find a way > >>> to make a dynamic list of all the numbers the computer generates in > >>> the loop and then make it re-generate the number if the previous > >>> number is present in the list, so it doesn't keep on generating 4 (as > >>> an example). I don't know if that makes sense... Basically, we humans > >>> know that once something is incorrect, there's no point in trying to > >>> use it as the answer next time, because we already know it's > >>> incorrect. How do I go about coding this in Python? I'm still quite > >>> new to the language so any help will be appreciated... > > >> One cheap way to do it (not necessarily efficient) is to make a list > >> of your possible guesses (e.g. range(1,10)), use random.shuffle() to > >> put them in random order and then run through the guesses one at a time. > > > import random > > import time > > > l = range(1, 10) > > > while l: > > print l.pop(random.randint(0, len(l) - 1)) > > time.sleep(2) > > While both of these will work well, I'd point out that a direct > translation of your question is to use a set. Define an empty set, and > each time you try a number unsuccessfully, add it to the set. Then just use > while x in myset: > x = newguess() > > to find the next guess. This approach isn't as efficient, but it's a > useful paradigm to understand. > > A separate question is whether the human is supposed to tell the > computer whether the guess is high or low. If so, you can eliminate > many numbers on each guess. For example, suppose the solution is 8. A > guess of 5 would say "too low." Then you'd cross off now only 5 but 1-4 > as well. > > With this change the best solution changes from a random shuffle to a > binary search. > > DaveA That's a good point if you can define whether the computer has guessed too low/high, then you could use the previous guess to set a bounds and rescale the next random guess. min + (random_number * max) although I think random.randomint does this for you! From no.email at please.post Wed Aug 26 09:57:23 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 13:57:23 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: In "Martin P. Hellwig" writes: >kj wrote: > >> First, one of the goals of OO is encapsulation, not only at the >> level of instances, but also at the level of classes. >Who says? Python itself: it already offers a limited form of class encapsulation (e.g. class variables). It would be nice if it went all the way and gave classes their own bona fide scope. (But I hasten to add: I *still* don't understand the Python scope model, and not for lack of trying. I've only succeeded in finding fragments of this model explained here and there, like pottery shards: a bit lost in a tutorial, or some comment in a newsgroup thread, etc. Maybe the full, authoritative documentation of Python's scope model got lost somewhere, and will be found by archaeologists in the 25th century...) >Anyway, you could be right (I am not capable to judge it) and Python >should change on this issue but from what I gathered, Pythons OO is >inspired by the following: >- Don't repeat yourself >- Containing code into logical units makes it easier to understand and >maintain. ...except, apparently, when that code is a recursive function, in which case one's out of luck. >> Second, my example shows that Python puts some peculiar restrictions >> on recursion. Recursion! One of the central concepts in the theory >> of functions! > >It is also one of the best ways to shoot yourself in the foot... If recursion is so evil, and Python so intent in saving us from shooting ourselves in the foot, why does it allow recursion at all? kynn From no.email at please.post Wed Aug 26 10:09:57 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 14:09:57 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> Message-ID: In <16b72319-8023-471c-ba40-8025aa6d462e at a26g2000yqn.googlegroups.com> Carl Banks writes: >> First, one of the goals of OO is encapsulation, not only at the >> level of instances, but also at the level of classes. =A0Your comment >> suggests that Python does not fully support class-level encapsulation. >I can't answer this, I don't even know what you are talking about. Yes, you do. As I said in another post, Python offers some degree of class-level encapsulation (e.g. class variables). But it is limited by the fact that these class-encapsulated elements can't always be accessed from within the class itself, which is kind of silly. >1. One of the key aspects of Python's design is that attributes must >be accessed explicitly with dot notation. Accessing class scopes from >nested functions would (seemingly) allow access to class attributes >without the dotted notation. Therefore it is not allowed. It would be trivial to define a keyword (e.g. this, or if you prefer, __this__), valid only within a class statement, and that the interpreter would recognize as "the current class", even before this class is full defined. kynn From nobody at nowhere.com Wed Aug 26 10:18:28 2009 From: nobody at nowhere.com (Nobody) Date: Wed, 26 Aug 2009 15:18:28 +0100 Subject: os.popen output different from native shell output References: <8119e546-b54d-4e72-b8b7-d1f3d104670f@v23g2000pro.googlegroups.com> Message-ID: On Tue, 25 Aug 2009 11:42:31 -0700, nickname wrote: > The reason why I want to do this is because I am going to do a little > project. I will write a python script called ls which will log the > time and username and then will show the actual ls output. I want this > to be transparent and so want to throw the ls output (via python) > exactly as it will be in native shell execution. If your script doesn't need the "ls" output for its own purposes, just run "ls" with its output to the terminal, rather than into a pipe. I.e. don't use os.popen(), but use os.spawnvp(), os.execvp() or subprocess.call(). If running "ls" is the very last thing which your script does, use os.execvp(). This causes the program to be executed in the existing process, rather than spawning a child process and waiting for it to exit. Because they replace the existing program (the Python interpreter), the various os.exec* functions don't return (unless there's an error). If you need to perform any action after the command completes (e.g. log the execution time), you need to use one of the other functions instead. From andre.cohen at gmail.com Wed Aug 26 10:19:42 2009 From: andre.cohen at gmail.com (Andre) Date: Wed, 26 Aug 2009 07:19:42 -0700 (PDT) Subject: Zlib: correct checksum but error decompressing Message-ID: <99c381ef-a146-4545-9344-7b15d60441de@y20g2000vbk.googlegroups.com> I have been trying to solve this issue for a while now. I receive data from a TCP connection which is compressed. I know the correct checksum for the data and both the client and server generate the same checksum. However, in Python when it comes to decompressing the data I get the exception: "Error -5 while decompressing data"! I would assume that if the string in python is equivalent to the correct checksum than the decompress function should also work on the same string, but that's clearly not the case. # convert data to a byte array data = array('b', raw_data) # print checksum for visual inspection print zlib.crc32(data.tostring()) # try to decompress, but fails! str = zlib.decompress(data.tostring()) Does anyone know what's going on? From davea at ieee.org Wed Aug 26 10:31:31 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 10:31:31 -0400 Subject: Need help with Python scoping rules In-Reply-To: <8219d86d-cf0b-457f-b823-550dcf7cbf71@p36g2000prn.googlegroups.com> References: <8219d86d-cf0b-457f-b823-550dcf7cbf71@p36g2000prn.googlegroups.com> Message-ID: <4A954743.4070804@ieee.org> 7stud wrote: > On Aug 25, 7:26 pm, Dave Angel wrote: > >> Stephen Fairchild wrote: >> >>> You are trying to run code in a class that does not exist yet. >>> >>> def Demo(): >>> def fact(n): >>> if n < 2: >>> return 1 >>> else: >>> return n * fact(n - 1) >>> return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar": >>> fact(5)}) >>> Demo =emo() >>> >>> d =emo() >>> print d._classvar # prints 120 >>> print d.fact(7) # prints 5040 >>> print Demo # prints >>> >> >> In all these messages, something I haven't seen pointed out is that >> fact() has no self argument. >> >> > > An "argument" is something that is specified in the the function > call. I assume you are trying to state something like, "fact() is not > defined with a parameter variable named self". However, that has > never been a requirement in python: > > > class A(object): > > def fact(n): > print n > > fact("hello") > > > a =() > a.fact() > > --output:-- > hello > <__main__.A object at 0x7faf0> > > > > You're good at nitpicking. I concede the distinction between argument and formal parameter. And self is a convention, not a requirement. But the fact is that the method as written would never have worked, when called from outside the class, since you'd have to call it with either the class name or an instance, and in either case, the method was then trying to do arithmetic on one of those. Thanks for diluting my point. The OP is chasing the wrong problem. Who cares whether a class initializer can call a method, if the method doesn't meet its original requirements, to be callable outside the class? And the arguments about how recursion is restricted are ridiculous. Nothing wrong with a method calling itself, once it's got a proper signature. You just have to make the call agree with the signature. The problem is only that the method may not be actually called until the class definition is complete. DaveA From mwilson at the-wire.com Wed Aug 26 10:38:50 2009 From: mwilson at the-wire.com (Mel) Date: Wed, 26 Aug 2009 10:38:50 -0400 Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: kj wrote: > Is there any good reason (from the point of view of Python's overall > design) for not fixing this? Python is not a compiled language, in the sense that a compiler can go back and forth over the program, filling in the details that make the program runnable. Python is an interpreted language in a sense that makes a `class` statement an executable statement, with a start time and an end time. Before the start time, the affected class doesn't exist. After the start time, the class does exist. In between, while the `class` statement is executing, it's best to make no promises so as not to constrain present and future implementations. Mel. From frank at chagford.com Wed Aug 26 10:54:32 2009 From: frank at chagford.com (Frank Millman) Date: Wed, 26 Aug 2009 16:54:32 +0200 Subject: Move dictionary from instance to class level References: Message-ID: "MRAB" wrote in message news:mailman.444.1251290454.2854.python-list at python.org... > An alternative is: > > >>> class MyClass(object): > ... def on_message_received(self, msg): > ... try: > ... getattr(self, "method_%d" % msg)() > ... except AttributeError: > ... raise Exception("Unknown message") > ... def method_0(self): > ... print 'in method_0' > ... def method_1(self): > ... print 'in method_1' > ... > >>> my_obj = MyClass() > >>> my_obj.on_message_received(0) > in method_0 > >>> my_obj.on_message_received(1) > in method_1 > >>> my_obj.on_message_received(2) > Traceback (most recent call last): > File "", line 1, in > File "", line 6, in on_message_received > Exception: Unknown message I like the idea. Unfortunately my real-world situation is a little more complex than my simple example implied. This is a more typical example - (EVT_GETLOGIN ,EVT_LOGOUT ,EVT_GETMENUOPT ,EVT_GOTFOCUS ,EVT_LOSTFOCUS ,EVT_BUTTONCLICKED ,EVT_CHECKBOX ... ) = xrange(28) method_dict = {} method_dict[EVT_GETLOGIN] = onGetLogin method_dict[EVT_LOGOUT] = onLogout method_dict[EVT_GETMENUOPT] = onGetMenuOpt method_dict[EVT_GOTFOCUS] = onGotFocus method_dict[EVT_LOSTFOCUS] = onLostFocus method_dict[EVT_BUTTONCLICKED] = onButtonClicked method_dict[EVT_CHECKBOX] = onCheckBox You can probably figure out from my method names what I am doing here - the messages are sent by a thin client (wxPython), and processed by a server.I am anticipating some "don't do that" responses, but I like the concept, and so far it is very fast and responsive, so I will pursue it for now. Thanks for the input. Frank From pavlovevidence at gmail.com Wed Aug 26 10:58:04 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Aug 2009 07:58:04 -0700 (PDT) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> Message-ID: <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> On Aug 26, 7:09?am, kj wrote: > In <16b72319-8023-471c-ba40-8025aa6d4... at a26g2000yqn.googlegroups.com> Carl Banks writes: > > >> First, one of the goals of OO is encapsulation, not only at the > >> level of instances, but also at the level of classes. =A0Your comment > >> suggests that Python does not fully support class-level encapsulation. > >I can't answer this, I don't even know what you are talking about. > > Yes, you do. ?As I said in another post, Python offers some degree > of class-level encapsulation (e.g. class variables). ?But it is > limited by the fact that these class-encapsulated elements can't > always be accessed from within the class itself, which is kind of > silly. Nope, you're wrong. Class variables are accessible wherever a class exists. The apparent silliness of this is because you are confusing classes with class statements. You know that the class isn't created until the class statement exits, don't you? Yeah, it's a little surprising that you can't access class scope from a function, but that has nothing to do with encapsulation. > >1. One of the key aspects of Python's design is that attributes must > >be accessed explicitly with dot notation. ?Accessing class scopes from > >nested functions would (seemingly) allow access to class attributes > >without the dotted notation. ?Therefore it is not allowed. > > It would be trivial to define a keyword (e.g. this, or if you > prefer, __this__), valid only within a class statement, and that > the interpreter would recognize as "the current class", even before > this class is full defined. Your solution to this "problem" is to add a keyword to Python. Laughable. (BTW, it's not trivial.) Carl Banks From no.email at please.post Wed Aug 26 10:58:10 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 14:58:10 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: In Dave Angel writes: >Stephen Fairchild wrote: >> You are trying to run code in a class that does not exist yet. >> >> def Demo(): >> def fact(n): >> if n < 2: >> return 1 >> else: >> return n * fact(n - 1) >> return type("Demo", (object,), {"fact": staticmethod(fact), "_classvar": >> fact(5)}) >> Demo = Demo() >> >> d = Demo() >> print d._classvar # prints 120 >> print d.fact(7) # prints 5040 >> print Demo # prints >> >> >In all these messages, something I haven't seen pointed out is that >fact() has no self argument. Seems to me that makes it a staticmethod, >so it should be declared that way. No, the fact() function here represents an internal "helper" function. It is meant to be called only once to help initialize a class variable that would be inconvenient to initialize otherwise; this helper function is not meant to be called from outside the class statement. Granted, in the example I gave, the "helper" function (factorial) is a bit silly, but that was just intended as a simple and familiar example of a recursive function. The actual function that motivated this post would be considerably more difficult to explain and would have obscured the point of the post. kynn From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 10:58:15 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Aug 2009 14:58:15 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> Message-ID: <02a53d89$0$20629$c3e8da3@news.astraweb.com> On Tue, 25 Aug 2009 11:45:28 -0700, Mensanator wrote: > On Aug 25, 9:14?am, Steven D'Aprano cybersource.com.au> wrote: >> On Mon, 24 Aug 2009 18:01:38 -0700, Mensanator wrote: >> >> If you want your data file to have values entered in hex, or oct, or >> >> even unary (1=one, 11=two, 111=three, 1111=four...) you can. >> >> > Unary? I think you'll find that Standard Positional Number Systems >> > are not defined for radix 1. >> >> Of course not. But unary isn't a positional number system. It's a tally >> system, like my example above shows. Roman numerals are another tally >> system. Like Roman numerals, the disadvantages of unary are that you >> can't represent negative numbers, zero, or fractions, and anything but >> addition and subtraction is difficult. But if you want to use it, >> perhaps out of a sense of sadism towards your users, it's easy: [...] > But without insignificant leading 0's, I fail to see the relevance of > unary to this discussion. It was just an example of how you can use numeric data in any format, no matter how obscure, weird or difficult, you can use it by passing it through an appropriate converter. You don't need compiler support for user-supplied data, you just write your own function. As for insignificant leading zeroes, such a thing is meaningless in a base-1 tally system. Zero is the absence of a tally mark. > And what would you call a tally system of > radix 2? Certainly not binary. "Radix" isn't the correct term, because radix doesn't apply to tally counting systems. I'd accept "base 2", in the sense that the tally is based on two different marks. We do something similar when we mark four tally lines, then for five we mark a diagonal line through the previous four. So by analogy a base-2 tally could go: / one X two X/ three XX four XX/ five XXX six XXX/ seven But I certainly wouldn't call it "binary", for fear of confusion with radix-2 binary. Possibly binary-tally, for lack of a better term. -- Steven From patrol at invisibleroads.com Wed Aug 26 11:01:37 2009 From: patrol at invisibleroads.com (InvisibleRoads Patrol) Date: Wed, 26 Aug 2009 10:01:37 -0500 Subject: Zlib: correct checksum but error decompressing In-Reply-To: <99c381ef-a146-4545-9344-7b15d60441de@y20g2000vbk.googlegroups.com> References: <99c381ef-a146-4545-9344-7b15d60441de@y20g2000vbk.googlegroups.com> Message-ID: <1e55aa13bc60afb4835118cd3f027008@mail.webfaction.com> On Wed, 26 Aug 2009 07:19:42 -0700 (PDT), Andre wrote: > I have been trying to solve this issue for a while now. I receive data > from a TCP connection which is compressed. I know the correct checksum > for the data and both the client and server generate the same > checksum. However, in Python when it comes to decompressing the data I > get the exception: "Error -5 while decompressing data"! I would assume > that if the string in python is equivalent to the correct checksum > than the decompress function should also work on the same string, but > that's clearly not the case. > > # convert data to a byte array > data = array('b', raw_data) > # print checksum for visual inspection > print zlib.crc32(data.tostring()) > # try to decompress, but fails! > str = zlib.decompress(data.tostring()) > > Does anyone know what's going on? Hi Andre, Hmm. Can you decompress the string on the server before it was sent? Maybe the zipfile or gzip module will work. Reference: http://bytes.com/topic/python/answers/42131-zlib-decompress-cannot-gunzip-can from cStringIO import StringIO from gzip import GzipFile body = GzipFile('', 'r', 0, StringIO(raw_data)).read() You might want to try experimenting with the wbits parameter of zlib.decompress() Reference: http://mail.python.org/pipermail/python-list/2008-December/691694.html zlib.decompress(data, -15) The zlib module seems to work fine with both strings and byte arrays. import array, zlib dataAsString = zlib.compress('example string') dataAsArray = array.array('b', dataAsString) zlib.decompress(dataAsString) == zlib.decompress(dataAsArray) zlib.decompress(dataAsString) == zlib.decompress(dataAsArray.tostring()) -- http://invisibleroads.com We train ordinary people into Python software developers and connect them with jobs and projects for local businesses. From davea at ieee.org Wed Aug 26 11:13:14 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 11:13:14 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <4A95510A.2060704@ieee.org> kj wrote: > In <7figv3F2m3p0dU1 at mid.uni-berlin.de> "Diez B. Roggisch" writes: > > >> Classes are not scopes. >> > > This looks to me like a major wart, on two counts. > > First, one of the goals of OO is encapsulation, not only at the > level of instances, but also at the level of classes. Your comment > suggests that Python does not fully support class-level encapsulation. > > Second, my example shows that Python puts some peculiar restrictions > on recursion. Recursion! One of the central concepts in the theory > of functions! This is shown most clearly by the following elaboration > of my original example: > > class Demo(object): > def fact_rec(n): > if n < 2: > return 1 > else: > return n * fact_rec(n - 1) > > Why not fix the call? The correct way to call a method is with either the class name or an instance object, depending on whether it's a instance method or not. By default, a method is unbound, and its first argument is by convention called self. If you want to recurse, then add self in the appropriate places. As you have it, neither of the methods can be called outside the class: class Demo(object): def fact_rec(n): if n < 2: return 1 else: return n * fact_rec(n - 1) .... obj = Demo() print obj.fact_rec(5) gives error: Traceback (most recent call last): File "M:\Programming\Python\sources\dummy\stuff2.py", line 20, in print obj.fact_rec(5) TypeError: fact_rec() takes exactly 1 argument (2 given) To fix it, you need to either change the signature (add in 'self' argument before the n argument) or do some form of decorator to the function. If I assume you never intended this method to use 'self' (ie. it's a static method), then declare it so. And call it accordingly. class Demo(object): @staticmethod def fact(n): if n < 2: return 1 else: return n * Demo.fact(n - 1) print Demo.fact(6) On the other hand, if I assume you're just giving a simple example of what's really intended to be a normal method (called with an instance, that it uses), then you'd change it this way. class Demo2(object): def fact(self, n): if n<2: return 1 else: return n * self.fact(n-1) obj = Demo2() print obj.fact(5) Now the only real restriction, as opposed to all these red-herrings, is that the class may not be used before it's complete. That only comes to play when class attributes (non-instance "variables") are defined in terms of class methods. So if you have such attributes to define, move them outside of the class, perhaps immediately after it. class Demo(object): @staticmethod def fact(n): if n < 2: return 1 else: return n * Demo.fact(n - 1) Demo._classvar = Demo.fact(5) > def fact_iter(n): > ret = 1 > for i in range(1, n + 1): > ret *= i > return ret > > classvar1 = fact_iter(5) > classvar2 = fact_rec(5) > > This code won't compile as shown, Sure it will compile. It just won't run. You get the error after compiling the function when *calling* it from the classvar* line. But at that time the class is not defined, and not everything is ready for use. You can probably work around this by replacing the staticmethod decorator with an equivalent function call:. class Demo9(object): def fact(n): if n < 2: return 1 else: return n * Demo.fact(n - 1) _classvar = fact(5) fact = staticmethod(fact) print Demo9._classvar xx = Demo9() print xx.fact(6) print Demo9.fact(8) > but it does compile if the last > line (the call to the recursive fact_rec) is commented out. There > is no justification for discriminating against recursive functions > in this context. Recursive functions should be OK wherever functions > are OK. I can't think of any other language that allows recursion > but not anywhere. > > Is there any good reason (from the point of view of Python's overall > design) for not fixing this? > > kynn > > > From no.email at please.post Wed Aug 26 11:14:27 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 15:14:27 +0000 (UTC) Subject: Need help with Python scoping rules References: <8219d86d-cf0b-457f-b823-550dcf7cbf71@p36g2000prn.googlegroups.com> Message-ID: In Dave Angel writes: >Thanks for diluting my point. The OP is chasing the wrong problem. Who >cares whether a class initializer can call a method, if the method >doesn't meet its original requirements, to be callable outside the class? >And the arguments about how recursion is restricted are ridiculous. >Nothing wrong with a method calling itself, once it's got a proper >signature. You just have to make the call agree with the signature. >The problem is only that the method may not be actually called until the >class definition is complete. As I described at length in another reply, the function in question is not intended to be "callable outside the class". And yes, recursive functions in Python *are* restricted in ways that non-recursive functions aren't. The examples I've posted prove this point unambiguously. At this point the only defense for this restriction is to claim that it is somehow negligible. But I disagree. It's easy to come up with equally negligible, and equally indefensible, restrictions to the language would be found quite unacceptable by most users. E.g. suppose that Python's specification prohibited the use of upper case X in an identifier. That's certainly a negligible restriction: it is not harder at all to write great software without the services of the letter X than with them. Still, I think most users would find this restriction infuriatingly idiotic. Which pretty much captures what I feel about Python's prohibition of recursive functions within class statements. kynn From pavlovevidence at gmail.com Wed Aug 26 11:15:53 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Aug 2009 08:15:53 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> Message-ID: <42b95155-db9d-4865-9039-c11ba556f3b4@z31g2000yqd.googlegroups.com> On Aug 25, 1:07?pm, Evan Driscoll wrote: > On Aug 25, 2:33?pm, Evan Driscoll wrote: > > > I want to make a context manager that will temporarily change the > > value of a variable within the scope of a 'with' that uses it. This is > > inspired by a C++ RAII object I've used in a few projects. Ideally, > > what I want is something like the following: > > Okay, so I think I actually got this with some consultation with a > friend. Critiques? > > ? ? from contextlib import contextmanager > ? ? import inspect > > ? ? def get_parents_var(offset, var): > ? ? ? ? f = inspect.stack()[offset][0] > ? ? ? ? if var in f.f_locals: > ? ? ? ? ? ? ? ? return f.f_locals[var] > ? ? ? ? else: > ? ? ? ? ? ? ? ? return f.f_globals[var] > > ? ? def set_parents_var(offset, var, val): > ? ? ? ? f = inspect.stack()[offset][0] > ? ? ? ? if var in f.f_locals: > ? ? ? ? ? ? f.f_locals[var] = val > ? ? ? ? elif var in f_globals: > ? ? ? ? ? ? f.f_globals[var] = val > ? ? ? ? else: > ? ? ? ? ? ? assert False > > ? ? @contextmanager > ? ? def changed_value_tb(var_name, temp_value): > ? ? ? ? # 1 is here, 2 will be the implicit next() function, 3 is the > real caller > ? ? ? ? offset = 3 > ? ? ? ? old_value = get_parents_var(offset, var_name) > ? ? ? ? set_parents_var(offset, var_name, temp_value) > ? ? ? ? try: > ? ? ? ? ? ? yield None > ? ? ? ? finally: > ? ? ? ? ? ? set_parents_var(offset, var_name, old_value) > > ? ? x = 5 > ? ? print x ? # prints 5 > ? ? with changed_value_tb("x", 10): > ? ? ? ? print x ?# prints 10 > ? ? print x ?# prints 5 Well, it wouldn't be a "can I rebind a variable using a with- statement" thread if someone didn't post a solution that they thought worked, but didn't test it on local variables. Carl Banks From la.foma at gmail.com Wed Aug 26 11:18:23 2009 From: la.foma at gmail.com (Maggie) Date: Wed, 26 Aug 2009 08:18:23 -0700 (PDT) Subject: Raw data extraction question Message-ID: <250bf47b-6307-435a-b991-caee359c4ccf@n11g2000yqb.googlegroups.com> i have event timing stretch of code i need to alter. here is code below: -------------- # we start each run with one full silent trial # creating a "stub" with the duration of a full block # less the discarded acquisitions stub = block_dur - (distax * tr) feed = sys.stdin.readlines() sess = -1 for line in feed: if re.search(line != rest): time = (line + line (-1)) + (distax * tr) print time elif (line(-1) = rest): # block onsets are determined by # block number, block duration, # and the stub; 3dDeconvolve # takes care of making these # "global" time = (line) + (distax * tr) print time ----- my concern is that it is extracting line number and not data contained on a given line. I need it to extract data from each line (excluding lines with spaces and/or lines that contain the word "pause" or "silence"). Basically i need ONLY raw data extracted from line 1 - onward. Please let me know if you have any suggestions. Thanks! From no.email at please.post Wed Aug 26 11:27:06 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 15:27:06 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> Message-ID: In <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71 at j21g2000yqe.googlegroups.com> Carl Banks writes: >On Aug 26, 7:09=A0am, kj wrote: >> In <16b72319-8023-471c-ba40-8025aa6d4... at a26g2000yqn.googlegroups.com> Ca= >rl Banks writes: >> >> >> First, one of the goals of OO is encapsulation, not only at the >> >> level of instances, but also at the level of classes. =3DA0Your commen= >t >> >> suggests that Python does not fully support class-level encapsulation. >> >I can't answer this, I don't even know what you are talking about. >> >> Yes, you do. =A0As I said in another post, Python offers some degree >> of class-level encapsulation (e.g. class variables). =A0But it is >> limited by the fact that these class-encapsulated elements can't >> always be accessed from within the class itself, which is kind of >> silly. >Nope, you're wrong. Class variables are accessible wherever a class >exists. The apparent silliness of this is because you are confusing >classes with class statements. Repeating an earlier example (though I've switched the order of the two internal functions): class Demo(object): def fact_iter(n): ret = 1 for i in range(1, n + 1): ret *= i return ret def fact_rec(n): if n < 2: return 1 else: return n * fact_rec(n - 1) classvar1 = fact_iter(5) classvar2 = fact_rec(5) In the initialization of classvar1, fact_iter is invoked without any problem even though the class is not yet created: no need to qualify it with the name of the class. This is completely inconsistent with the requirement that fact_rec be so qualified when invoked within fact_rec. kynn From pavlovevidence at gmail.com Wed Aug 26 11:27:24 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Aug 2009 08:27:24 -0700 (PDT) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <90b1ff07-19cf-4eeb-abc5-80445da9f790@h21g2000yqa.googlegroups.com> On Aug 26, 8:13?am, Dave Angel wrote: > You can probably work around this by replacing the staticmethod > decorator with an equivalent function call:. > > class Demo9(object): > ? ? def fact(n): > ? ? ? ? if n < 2: > ? ? ? ? ? ? return 1 > ? ? ? ? else: > ? ? ? ? ? ? return n * Demo.fact(n - 1) > > ? ? _classvar = fact(5) > ? ? fact = staticmethod(fact) > > print Demo9._classvar > xx = Demo9() > print xx.fact(6) > print Demo9.fact(8) This won't work normally. It only worked for you because you made a typo. Carl Banks From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 11:32:38 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Aug 2009 15:32:38 GMT Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <02a54597$0$20629$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 10:57:32 +0000, kj wrote: > In <7figv3F2m3p0dU1 at mid.uni-berlin.de> "Diez B. Roggisch" > writes: > >>Classes are not scopes. > > This looks to me like a major wart, on two counts. > > First, one of the goals of OO is encapsulation, not only at the level of > instances, but also at the level of classes. Your comment suggests that > Python does not fully support class-level encapsulation. I don't even know what that is supposed to mean. If anything, your problem could be because Python has TOO MUCH "class-level encapsulation" compared to what you are expecting: functions inside a class don't see the class attributes you expect them too. Actually, I think your problem is that you are interpreting what you're seeing in terms of C++ or Java, and assuming that whatever they do is the One True Definition of OO. That's hardly valid -- if any language deserves the label of the One True OO Design, it might be Smalltalk, on the basis that it was the first OO language. But even that is silly -- just because something was the first, that doesn't make it the best example of something. > Second, my example shows that Python puts some peculiar restrictions on > recursion. Incorrect. Recursive calls are just like any other function call in Python: when you call *any* function from the body of a function, it must be in scope at runtime. def fact(n): print g() # g must be in scope when fact is called if n < 2: return 1 return n*fact(n-1) # fact must be in scope when fact is called Python doesn't treat recursive functions specially in any way. It is *classes*, not functions, that are special. This is explained in the docs: http://docs.python.org/reference/executionmodel.html It is also discussed in the PEP introducing nested scopes to Python: http://www.python.org/dev/peps/pep-0227/ It's even eluded to in the tutorial: http://docs.python.org/tutorial/classes.html > Recursion! One of the central concepts in the theory of > functions! This is shown most clearly by the following elaboration of > my original example: > > class Demo(object): > def fact_rec(n): > if n < 2: > return 1 > else: > return n * fact_rec(n - 1) Why are you defining a method without a self parameter? In any case, the problem has nothing to do with recursion: >>> class Broken: ... def f(): ... return g() ... def g(): ... return "gee" ... x = f() ... Traceback (most recent call last): File "", line 1, in File "", line 6, in Broken File "", line 3, in f NameError: global name 'g' is not defined > def fact_iter(n): > ret = 1 > for i in range(1, n + 1): > ret *= i > return ret > > classvar1 = fact_iter(5) > classvar2 = fact_rec(5) > > This code won't compile as shown, That's nonsense. It compiles, and then it suffers a runtime error when you *execute* it. (NameError occurs at runtime, not at compile time.) You can prove this for yourself by putting that above class definition inside a string, s: >>> x = compile(s, '', 'exec') >>> exec(x) Traceback (most recent call last): File "", line 1, in File "", line 1, in File "", line 15, in Demo File "", line 6, in fact_rec NameError: global name 'fact_rec' is not defined If you expect us to take your criticisms seriously, at least get your basic facts right. [...] > Is there any good reason (from the point of view of Python's overall > design) for not fixing this? It doesn't need to be "fixed" because it's not broken. The question is, should it be *changed* to match C++ programmers' expectations? -- Steven From no.email at please.post Wed Aug 26 11:36:35 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 15:36:35 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> Message-ID: In <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71 at j21g2000yqe.googlegroups.com> Carl Banks writes: >Yeah, it's a little surprising that you can't access class scope from >a function, but that has nothing to do with encapsulation. It does: it thwarts encapsulation. The helper function in my example is one that clearly rightfully belongs nowhere else than the class itself, i.e. encapsulated within the class. It is only this silly prohibition against recursive functions in a class statement that forces one to put it outside the class statement. kynn From davea at ieee.org Wed Aug 26 11:37:52 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 11:37:52 -0400 Subject: Help with arrays In-Reply-To: <391bbc0f-08ea-4840-a2da-cb36b5632669@m38g2000yqh.googlegroups.com> References: <391bbc0f-08ea-4840-a2da-cb36b5632669@m38g2000yqh.googlegroups.com> Message-ID: <4A9556D0.1060508@ieee.org> Mart. wrote: > On Aug 26, 3:02 am, Dave Angel wrote: > >> Stephen Fairchild wrote: >> >>> Philip Semanchuk wrote: >>> >>>> On Aug 25, 2009, at 6:14 PM, Gleb Belov wrote: >>>> >>>>> Hello! I'm working on an exercise wherein I have to write a Guess The >>>>> Number game, but it's the computer who's guessing MY number. I can get >>>>> it to work, but there's one obvious problem: the computer generates >>>>> random numbers until one of them corresponds to my number, but it will >>>>> often generate one number (eg. 4) numerous times, meaning it doesn't >>>>> know that this number is invalid. What I mean is, it will sometimes >>>>> use 37 tries to guess a number out of 1 - 9, which makes no sense, >>>>> since it should only take 9 tries, at most. I was trying to find a way >>>>> to make a dynamic list of all the numbers the computer generates in >>>>> the loop and then make it re-generate the number if the previous >>>>> number is present in the list, so it doesn't keep on generating 4 (as >>>>> an example). I don't know if that makes sense... Basically, we humans >>>>> know that once something is incorrect, there's no point in trying to >>>>> use it as the answer next time, because we already know it's >>>>> incorrect. How do I go about coding this in Python? I'm still quite >>>>> new to the language so any help will be appreciated... >>>>> >>>> One cheap way to do it (not necessarily efficient) is to make a list >>>> of your possible guesses (e.g. range(1,10)), use random.shuffle() to >>>> put them in random order and then run through the guesses one at a time. >>>> >>> import random >>> import time >>> >>> l = range(1, 10) >>> >>> while l: >>> print l.pop(random.randint(0, len(l) - 1)) >>> time.sleep(2) >>> >> While both of these will work well, I'd point out that a direct >> translation of your question is to use a set. Define an empty set, and >> each time you try a number unsuccessfully, add it to the set. Then just use >> while x in myset: >> x = newguess() >> >> to find the next guess. This approach isn't as efficient, but it's a >> useful paradigm to understand. >> >> A separate question is whether the human is supposed to tell the >> computer whether the guess is high or low. If so, you can eliminate >> many numbers on each guess. For example, suppose the solution is 8. A >> guess of 5 would say "too low." Then you'd cross off now only 5 but 1-4 >> as well. >> >> With this change the best solution changes from a random shuffle to a >> binary search. >> >> DaveA >> > > That's a good point if you can define whether the computer has guessed > too low/high, then you could use the previous guess to set a bounds > and rescale the next random guess. > > min + (random_number * max) > > although I think random.randomint does this for you! > > Actually, if you change the specs this way, you don't need random at all. Just guess halfway through the remaining range. To guess a number between 1 and 100 this way takes 7 guesses, worst case. (plus/minus 1, I haven't checked) Same problem as searching a sorted list. This code (from: http://stackoverflow.com/questions/212358/binary-search-in-python) appears to search a sorted list |def binary_search(a, x, lo=0, hi=None): if hi is None: hi = len(a) while lo < hi: mid = (lo+hi)//2 midval = a[mid] if midval < x: lo = mid+1 elif midval > x: hi = mid else: return mid return -1 | DaveA From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 11:40:35 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Aug 2009 15:40:35 GMT Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <02a54775$0$20629$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 13:57:23 +0000, kj wrote: > In "Martin P. Hellwig" > writes: > >>kj wrote: >> >>> First, one of the goals of OO is encapsulation, not only at the level >>> of instances, but also at the level of classes. >>Who says? > > Python itself: it already offers a limited form of class encapsulation > (e.g. class variables). An int variable is an int. A string variable is a string. A bool variable is a bool. A class variable is a class. Perhaps you mean a class attribute? > It would be nice if it went all the way and > gave classes their own bona fide scope. Classes have their own bona fide scope. It just doesn't work the way you expect it to. > (But I hasten to add: I *still* > don't understand the Python scope model, and not for lack of trying. > I've only succeeded in finding fragments of this model explained here > and there, like pottery shards: a bit lost in a tutorial, or some > comment in a newsgroup thread, etc. Maybe the full, authoritative > documentation of Python's scope model got lost somewhere, and will be > found by archaeologists in the 25th century...) It's all in the Fine Manual: http://docs.python.org/reference/executionmodel.html >>Anyway, you could be right (I am not capable to judge it) and Python >>should change on this issue but from what I gathered, Pythons OO is >>inspired by the following: >>- Don't repeat yourself >>- Containing code into logical units makes it easier to understand and >>maintain. > > ...except, apparently, when that code is a recursive function, in which > case one's out of luck. Incorrect. As I showed in my previous post, your problem has nothing to do with recursion. >>> Second, my example shows that Python puts some peculiar restrictions >>> on recursion. Recursion! One of the central concepts in the theory >>> of functions! >> >>It is also one of the best ways to shoot yourself in the foot... > > If recursion is so evil, and Python so intent in saving us from shooting > ourselves in the foot, why does it allow recursion at all? Recursion isn't evil, and Python isn't intent on preventing foot-shooting. -- Steven From no.email at please.post Wed Aug 26 11:45:54 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 15:45:54 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano writes: >On Wed, 26 Aug 2009 10:57:32 +0000, kj wrote: >> Recursion! One of the central concepts in the theory of >> functions! This is shown most clearly by the following elaboration of >> my original example: >> >> class Demo(object): >> def fact_rec(n): >> if n < 2: >> return 1 >> else: >> return n * fact_rec(n - 1) >Why are you defining a method without a self parameter? Because, as I've explained elsewhere, it is not a method: it's a "helper" function, meant to be called only once, within the class statement itself. Well, this is not strictly true, because the function is recursive, so it will also call itself a few times. But still, all these calls happen (loosely speaking) "within the class statement". In fact the only reason to use a function for such initialization work is when one needs recursion; otherwise there's no point in defining a function that will only be invoked exactly once. kynn From grahn+nntp at snipabacken.se Wed Aug 26 11:48:53 2009 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 26 Aug 2009 15:48:53 GMT Subject: ubuntu dist-packages References: <7fki3lF2kirnkU1@mid.uni-berlin.de> Message-ID: On Wed, 26 Aug 2009 12:46:13 +0200, Diez B. Roggisch wrote: > Robin Becker wrote: > >> I was surprised a couple of days ago when trying to assist a colleage with >> his python setup on a ubuntu 9.04 system. >> >> We built our c-extensions and manually copied them into place, but >> site-packages wasn't there. It seems that ubuntu now wants stuff to go >> into lib/python2.6/dist-packages. ... > I don't know much about the atrocities distributions commit to > python-installations (ripping out distutils "because it's a developer-only > thing", Well, if you are thinking about Debian Linux, it's not as much "ripping out" as "splitting into a separate package with a non-obvious name". Annoying at times, but hardly an atrocity. /Jorgen -- // Jorgen Grahn O o . From wiggly at wiggly.org Wed Aug 26 11:49:10 2009 From: wiggly at wiggly.org (Nigel Rantor) Date: Wed, 26 Aug 2009 16:49:10 +0100 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A955976.6000303@wiggly.org> kj wrote: > > Needless to say, I'm pretty beat by this point. Any help would be > appreciated. > > Thanks, Based on your statement above, and the fact that multiple people have now explained *exactly* why your attempt at recursion hasn't worked, it might be a good idea to step back, accept the advice and walk away instead of trying to convince people that the language forbids recursion and doesn't provide decent OO ecapsulation. Otherwise I'd wager you'll soon be appearing in multiple kill-files. n From davea at ieee.org Wed Aug 26 11:54:13 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 11:54:13 -0400 Subject: Move dictionary from instance to class level In-Reply-To: References: Message-ID: <4A955AA5.6000200@ieee.org> Frank Millman wrote: > "MRAB" wrote in message > news:mailman.444.1251290454.2854.python-list at python.org... > >> An alternative is: >> >> >>>>> class MyClass(object): >>>>> >> ... def on_message_received(self, msg): >> ... try: >> ... getattr(self, "method_%d" % msg)() >> ... except AttributeError: >> ... raise Exception("Unknown message") >> ... def method_0(self): >> ... print 'in method_0' >> ... def method_1(self): >> ... print 'in method_1' >> ... >> >>>>> my_obj = MyClass() >>>>> my_obj.on_message_received(0) >>>>> >> in method_0 >> >>>>> my_obj.on_message_received(1) >>>>> >> in method_1 >> >>>>> my_obj.on_message_received(2) >>>>> >> Traceback (most recent call last): >> File "", line 1, in >> File "", line 6, in on_message_received >> Exception: Unknown message >> > > I like the idea. Unfortunately my real-world situation is a little more > complex than my simple example implied. > > This is a more typical example - > > (EVT_GETLOGIN > ,EVT_LOGOUT > ,EVT_GETMENUOPT > ,EVT_GOTFOCUS > ,EVT_LOSTFOCUS > ,EVT_BUTTONCLICKED > ,EVT_CHECKBOX > ... > ) = xrange(28) > > method_dict = {} > method_dict[EVT_GETLOGIN] = onGetLogin > method_dict[EVT_LOGOUT] = onLogout > method_dict[EVT_GETMENUOPT] = onGetMenuOpt > method_dict[EVT_GOTFOCUS] = onGotFocus > method_dict[EVT_LOSTFOCUS] = onLostFocus > method_dict[EVT_BUTTONCLICKED] = onButtonClicked > method_dict[EVT_CHECKBOX] = onCheckBox > > You can probably figure out from my method names what I am doing here - the > messages are sent by a thin client (wxPython), and processed by a server.I > am anticipating some "don't do that" responses, but I like the concept, and > so far it is very fast and responsive, so I will pursue it for now. > > Thanks for the input. > > Frank > > > Any time I see multiple lists like that which have to stay in synch, I think code-smell. Why not let the EVT's be passed as strings, and avoid the whole mapping to integers and mapping back detail? And name the methods involved in a way that you can directly translate the string to the method name? Barring that, make a single "structure" which lists the event names and method names in matched pairs, and derive whatever lists and dictionaries you actually need from that one structure. And that structure should be shared between client and server code, perhaps as a text file that they both parse. Or as a stream that's passed from one to the other during startup. That way, consistency between them can be regulated (with version string in the file, for example) DaveA From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 11:55:08 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Aug 2009 15:55:08 GMT Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> Message-ID: <02a54ade$0$20629$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 14:09:57 +0000, kj wrote: >>1. One of the key aspects of Python's design is that attributes must be >>accessed explicitly with dot notation. Accessing class scopes from >>nested functions would (seemingly) allow access to class attributes >>without the dotted notation. Therefore it is not allowed. > > It would be trivial to define a keyword (e.g. this, or if you prefer, > __this__), valid only within a class statement, and that the interpreter > would recognize as "the current class", even before this class is full > defined. Python doesn't treat the addition of new keywords, and the corresponding breakage of code which used that word as a normal name, as "trivial" -- the Python dev team takes their responsibilities to not casually break people's code seriously. That pretty much rules out "this", although it would allow "__this__". However, what's your use-case? class Demo(object): def f(n): return n+1 x = f(10) is a poorly written class, because the user will expect to do this: instance = Demo() assert instance.c == 11 # suceeds instance.f(10) == 11 # fails Since the function f doesn't refer to a Demo instance, or the Demo class, why do you put it inside the Demo class? It doesn't belong there, it belongs in the global (module) scope. Move it out, and your problem goes away. The only use-case I can think of for __this__ is the following: class Example(object): @staticmethod def rec(n): if n < 2: return "x" return "x" + __this__.rec(n/2) Example.rec(15) but again, why include rec() in the class if it doesn't actually have anything to do with the class or the instance? Or why make it a staticmethod? Just make it a class method: class Example(object): @classmethod def rec(cls, n): if n < 2: return "x" return "x" + cls.rec(n/2) -- Steven From marcandre at abppers.com Wed Aug 26 12:10:34 2009 From: marcandre at abppers.com (=?iso-8859-1?Q?Marc-Andr=E9_Ouellette?=) Date: Wed, 26 Aug 2009 12:10:34 -0400 Subject: WEB PROGRAMMER ANALYST (with Python knowledge) for Laval, Quebec needed. Message-ID: <7116C98A7E6E4F8785817A4A92A545D7@abppers.local> To whom it may concern, ABP Personnel Consultants is a recruiting firm established in Montreal. We presently have a need for a web programmer with knowledge of Python. Below is the job description : Our client offers much more than simple Internet advertising and website design. They are a full-service automotive industry consulting company that develops integrated sales and CRM solutions, focussing on showing clients how to make the most of online communications. Their digital marketing services are geared towards measurable results attained with the help of rigorous online methodology. Du to the expansion of the company nationally, they are seeking talented individuals to fill full-time software development positions at their offices in Laval. The candidate will be responsible for analyzing client requests and/or specifications. Determine the functionality demanded by the system and resources/requirements, using the most appropriate development technology to produce the required application, and/or modification. Additionally, the candidate will work with Quality Assurance department to validate newly developed applications, and/or modifications. Software Developers will also be required to troubleshoot applications when problems arise. The working environment is flexible, easy going and encourages teamwork. EXPERIENCE (not required to know all): Candidates should have commercial programming experience (Python, SQL and Javascript). Knowledge in one or more of the following technologies is desirable: Languages: Python, SQL, JavaScript, C/C++, Delphi Servers: Apache, Sybase, PostgreSQL Markups: HTML, XML, CSS, XUL Frameworks/Toolkits: Django, Twisted Matrix, wxWidgets Protocols: TCP/UDP IP, XMLRPC/SOAP, AJAX, FTP, HTTP, POP/SMTP OSes: Linux, Windows, MacOSX Other: Client/server architectures, version control systems Mercurial SALARY: Based on level of experience, from 50000$ to 75000$ + benefits. If your interested to know more, please contact me. Regards, Marc-Andr? Ouellette marcandre at abppers.com Marc-Andr? Ouellette Consultant en recrutement Recruitment consultant T. 514-939-3399 poste 105 F. 514-939-0241 Courriel : marcandre at abppers.com Consultez nos offres d'emplois au www.abppers.com Visit us online at www.abppers.com Ce message, ainsi que tout fichier qui y est joint, est destin? exclusivement aux personnes ? qui il est adress?. Il peut contenir des renseignements ou des informations de nature confidentielle qui ne doivent ?tre divulgu?s en vertu des lois applicables. Si vous n'?tes pas le destinataire de ce message ou un mandataire autoris? de celui-ci, par la pr?sente vous ?tes avis? que toute impression, diffusion, distribution ou reproduction de ce message et de tout fichier qui y est joint est strictement interdite. L'int?grit? de ce message n'?tant pas assur?e sur Internet, ABP Consultants en Personnel inc. ne peut ?tre tenue responsable de son contenu s'il a ?t? alt?r?, d?form? ou falsifi?. Si ce message vous a ?t? transmis par erreur, veuillez en aviser sans d?lai l'exp?diteur et l'effacer ainsi que tout fichier joint sans en conserver de copie. This message, and any attachments, is intended only for the use of the addressee or his authorized representative. It may contain information that is privileged, confidential and exempt from disclosure under applicable law. If the reader of this message is not the intended recipient,or his authorized representative, you are hereby notified that any dissemination, distribution or copying of this message and any attachments isstrictly prohibited. The integrity of this message cannot be guaranteed on the Internet, ABP Personnel Consultants inc. shall not be liable for its content if altered, changed or falsified. If you have received this message in error, please contact right away with the sender and delete this message andany attachments from your system. -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.jpg Type: image/jpeg Size: 10281 bytes Desc: not available URL: From pavlovevidence at gmail.com Wed Aug 26 12:13:40 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Wed, 26 Aug 2009 09:13:40 -0700 (PDT) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> Message-ID: On Aug 26, 8:36?am, kj wrote: > In <1bf83a7e-f9eb-46ff-84fe-cf42d9608... at j21g2000yqe.googlegroups.com> Carl Banks writes: > > >Yeah, it's a little surprising that you can't access class scope from > >a function, but that has nothing to do with encapsulation. > > It does: it thwarts encapsulation. ?The helper function in my > example is one that clearly rightfully belongs nowhere else than > the class itself, i.e. encapsulated within the class. It is only > this silly prohibition against recursive functions in a class > statement that forces one to put it outside the class statement. Oh well, I guess that sucks for you. Carl Banks From robin at reportlab.com Wed Aug 26 12:20:35 2009 From: robin at reportlab.com (Robin Becker) Date: Wed, 26 Aug 2009 17:20:35 +0100 Subject: ubuntu dist-packages In-Reply-To: References: <7fki3lF2kirnkU1@mid.uni-berlin.de> Message-ID: <4A9560D3.4000009@chamonix.reportlab.co.uk> Jorgen Grahn wrote: > On Wed, 26 Aug 2009 12:46:13 +0200, Diez B. Roggisch ........ > Well, if you are thinking about Debian Linux, it's not as much > "ripping out" as "splitting into a separate package with a non-obvious > name". Annoying at times, but hardly an atrocity. so where is the official place for user installed stuff on ubuntu/debian ie will there be dist-packages and site-packages. -- Robin Becker From robin at reportlab.com Wed Aug 26 12:20:35 2009 From: robin at reportlab.com (Robin Becker) Date: Wed, 26 Aug 2009 17:20:35 +0100 Subject: ubuntu dist-packages In-Reply-To: References: <7fki3lF2kirnkU1@mid.uni-berlin.de> Message-ID: <4A9560D3.4000009@chamonix.reportlab.co.uk> Jorgen Grahn wrote: > On Wed, 26 Aug 2009 12:46:13 +0200, Diez B. Roggisch ........ > Well, if you are thinking about Debian Linux, it's not as much > "ripping out" as "splitting into a separate package with a non-obvious > name". Annoying at times, but hardly an atrocity. so where is the official place for user installed stuff on ubuntu/debian ie will there be dist-packages and site-packages. -- Robin Becker From tjreedy at udel.edu Wed Aug 26 12:21:45 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Aug 2009 12:21:45 -0400 Subject: Python Processor In-Reply-To: <7670c8130908260328l6982ef4etad802a755b85a44f@mail.gmail.com> References: <7670c8130908260328l6982ef4etad802a755b85a44f@mail.gmail.com> Message-ID: manish wrote: > Hi, > > I am also wondering about how to implement a soft core reconfigurable > processor in a FPGA > which would directly execute the compiled python bytecode. > > I am trying to understand the bytecode format but apart from > http://docs.python.org/library/dis.html > there is hardly any documentation on the python bytecodes. Contrary to the ancient and, I believe, obsolete text in the documentation, there is no 'python bytecode'. Dis is based on CPython bytecode. Jython uses Java bytecode. IronPython uses, I believe, Microsoft clr bytecode. Object code compilers do not use bytecode. > Before going through the one of the existing VM implementations, i want > to know if there is there any informaition > available which elaborates on the structure of the bytecodes. Like > details regarding co_names, co_cellvars, > co_freevars, the concept of frames, global, local, objects, functions > etc with respect to the bytecode. These are mostly version-specific Cpython implementation details. tjr From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 12:42:24 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 26 Aug 2009 16:42:24 GMT Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> Message-ID: <02a555f2$0$20629$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 15:36:35 +0000, kj wrote: > In <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71 at j21g2000yqe.googlegroups.com> > Carl Banks writes: > >>Yeah, it's a little surprising that you can't access class scope from a >>function, but that has nothing to do with encapsulation. > > It does: it thwarts encapsulation. The helper function in my example is > one that clearly rightfully belongs nowhere else than the class itself, > i.e. encapsulated within the class. There's nothing "clearly" about it. This helper function doesn't reference the class, or any instance of the class. Why should it be encapsulated in the class? It's not *part* of the class, it shouldn't be *inside* the class. Look at it this way: classes are made from building blocks. Just because a building block ends up in a class, doesn't mean the function that makes the building block has to be inside the class too. It's an accident of Python's execution model that a single function call *sometimes* works as you expect inside the class statement: class Demo: def f(): return 2 def g(): return f()+1 x = f() # works y = g() # fails As you can see, the problem is not because of recursion, but because the class scope is not inserted into the function scope. As I said earlier, your problem isn't too little class encapsulation, but too much: the class scope doesn't leak into the function scope. Python could, of course, behave the way you want, but it would lead to some odd interactions: class Weird(object): x = 1 def __init__(self): self.y = 2 def test(self): print self.x # refers to attribute x with value 1 print x # refers to attribute x with value 1 print self.y # refers to attribute y with value 2 print y # refers to global y In existing Python, both x and y will refer to globals, because it's considered more important for all attribute access to be consistently explicit than to insert the class scope into the function scope. This isn't a design flaw, or a bug, it's a feature. Yes, it makes it hard for you to solve your problem the way you want to solve it, but it doesn't stop you from solving your problem. The module is encapsulation enough. -- Steven From cjw at ncf.ca Wed Aug 26 12:49:18 2009 From: cjw at ncf.ca (Colin J. Williams) Date: Wed, 26 Aug 2009 12:49:18 -0400 Subject: quantiles of a student distribution In-Reply-To: References: Message-ID: Pierre wrote: > Hello... > > Do you know how I can calculate the quantiles of a student > distribution in pyhton ? > > Thanks You might look at: http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/python/special.html Colin W. From szport at gmail.com Wed Aug 26 12:49:48 2009 From: szport at gmail.com (zaur) Date: Wed, 26 Aug 2009 09:49:48 -0700 (PDT) Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> Message-ID: <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> On 26 ???, 17:13, "Diez B. Roggisch" wrote: > Whom am we to judge? Sure if you propose this, you have some usecases in > mind - how about you present these Ok. Here is a use case: object initialization. For example, person = Person(): name = "john" age = 30 address = Address(): street = "Green Street" no = 12 vs. person = Person() person.name = "john" person.age = 30 address = person.address = Address() address.street = "Green Street" address.no = 12 In this example any assignment is an equivalence of setting attribute's address of the parent object. From phily05 at gmail.com Wed Aug 26 12:54:55 2009 From: phily05 at gmail.com (Phil) Date: Wed, 26 Aug 2009 09:54:55 -0700 (PDT) Subject: Python on the Web References: <4a94ef42$0$27774$426a74cc@news.free.fr> Message-ID: Thanks to everybody. I believe I am understanding things better. I have looked at the links that have been provided, although I have seen most of them in the past month or so that I've been looking into this stuff. I do agree with most of the things Armin stated in that NIH post. I agree with everybody in this thread so far. If I wanted to write an application, I would use an existing framework and wait for it to be ported to 3.x. However, I do not have the need to write a web application at this time, and creating blogs or other applications I do not need for fun is getting old. My reasoning for working on my own instead of following the 'NIH' concept or contributing to an existing framework is because I have experimented with many existing frameworks and I have figured out what I like/dislike, and have envisioned my own design that I feel would work potentially better for others, or at least newcomers. Things like this are fun for me, and I do not mind the challenge. I don't want to pollute the web with (sigh) 'another framework', but it would be fun for me to write it and get some feedback. I would love for people like you, Armin, and others who take a look at the various frameworks that pop up seemingly every day, to look at my (hypothetical) framework and just rip it apart with (constructive) criticism. That is just the way I do things, whether the community agrees with it or not. The reason I was asking about Python 3 on the web was just because I like some of the changes that have been made, and would like to use it for my framework. That is when I realized that I was absolutely clueless about the details of how Python, or any language, works on the web. Graham, regarding number 3 in your list of ways to host WSGI: I haven't really looked into mod_wsgi at all, but basically it sounds like the web server would be running this embedded module. That module would then serve the function of both FCGI and the 'WSGI Server' in my diagram? That actually sounds really neat. Unfortunately I missed this because I've been hooked on lighttpd, as the minimalist I am. Here are the things I am still confused with: 1) Why do I not want to consider running Python on the web with FCGI, without WSGI? You said 'no' straight up, no questions asked. I would imagine that there is a good reason of course, as you've been in this field for a long time. I just feel more comfortable understanding why. >From my understanding, the only real purpose of WSGI is to remain independent of FCGI/SCGI/CGI/AJP (whatever that is) and the web server it is run on. However, 99.9% of the discussion I see with Python on the web is around FCGI. So for example, lets say everybody used FCGI. All that would be left to deal with is web server independence. Now this is what I don't get, I thought that FCGI itself was supposed to be the protocol that deals with web server independence. Maybe I just need to re-read entire WSGI specification to understand, along with all the details of FCGI. There are just so many details regarding web servers, FCGI, and WSGI that it is hard to absorb it all and see how it works together. That is why I tried to create the diagram, but it doesn't provide enough details. And those are the details I am missing. I've been trying to find a simple diagram or explaination of the process a request takes to make a response, from HTTP all the way up to the application, to the the user. 2) In the development stack, the 'WSGI Server' seems to take on the role of the web server (dealing with HTTP specification), skips FCGI, and deals with the WSGI specification. Then, the 'WSGI Server' in the production stack (eg. Flup, CherryPy, etc) only deals with FCGI and WSGI specification, because the HTTP is already taken care of by the web server? From rami.chowdhury at gmail.com Wed Aug 26 13:11:15 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Wed, 26 Aug 2009 10:11:15 -0700 Subject: Object's nesting scope In-Reply-To: <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> Message-ID: > person = Person(): > name = "john" > age = 30 > address = Address(): > street = "Green Street" > no = 12 > Can you clarify what you mean? Would that define a Person class, and an Address class? If you are expecting those classes to be already defined, please bear in mind that if you want, you can do this: > > > class Person(object): def __init__(self, name='Nemo', age=0, address=None): self.name = name self.age = age self.address = address > > > class Address(object): def __init__(self, street=None, no=None): self.street = street self.no = no > > > otherperson = Person( name = 'Bob', age = 26, address = Address( street = 'Blue Street', no = 1 ) ) On Wed, 26 Aug 2009 09:49:48 -0700, zaur wrote: > On 26 ???, 17:13, "Diez B. Roggisch" wrote: >> Whom am we to judge? Sure if you propose this, you have some usecases in >> mind - how about you present these > > Ok. Here is a use case: object initialization. > > For example, > > person = Person(): > name = "john" > age = 30 > address = Address(): > street = "Green Street" > no = 12 > > vs. > > person = Person() > person.name = "john" > person.age = 30 > address = person.address = Address() > address.street = "Green Street" > address.no = 12 > > In this example any assignment is an equivalence of setting > attribute's address of the parent object. -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From eckhardt at satorlaser.com Wed Aug 26 13:17:22 2009 From: eckhardt at satorlaser.com (Ulrich Eckhardt) Date: Wed, 26 Aug 2009 19:17:22 +0200 Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> Message-ID: <2a7gm6-9h.ln1@satorlaser.homedns.org> kj wrote: > class Demo(object): > def fact_iter(n): > ret = 1 > for i in range(1, n + 1): > ret *= i > return ret > > def fact_rec(n): > if n < 2: > return 1 > else: > return n * fact_rec(n - 1) > > classvar1 = fact_iter(5) > classvar2 = fact_rec(5) > > > In the initialization of classvar1, fact_iter is invoked without > any problem even though the class is not yet created: no need to > qualify it with the name of the class. This is completely inconsistent > with the requirement that fact_rec be so qualified when invoked > within fact_rec. Let me take a shot at explaining this, maybe it helps that I'm mostly a C++ guy.... Firstly, if Python sees a name, it looks up that name first in the local scope and then in the global scope. This is very simple (especially compared to C++ when adding ADL there...), but it is something most people can live with. So, even inside a class function (static or member), you have to qualify a function call like 'ClassName.function_name', because neither is 'function_name' a local nor is it a global. Secondly, and that is due to the very dynamic nature of Python's types, the class doesn't exist until its definition is finished. Therefore, any attempt (directly or indirectly) to access a class member will usually fail before that time. The exception is that inside the class definition you can access the members directly, because they are in the same scope (access to locals). Note that the scope already seems to exist but that it is not yet available under any name! Looking at your example, you can not write 'classvar1 = Demo.fact_iter(42)', because the lookup of 'Demo' will fail. Now, what actually causes problems is that 'fact_rec' is not universally accessible until class 'Demo' is fully defined, but you need this in order to fully define it. Here comes a drawback of the dynamic nature of Python, that the declaration phase (compiling) is not separate from the execution. I fully agree that this case is rather vexing to my (and obviously your) biased brain. I wouldn't call this a bug before fully understanding why e.g. you can not access a class before its definition is finished. I think someone mentioned one or two PEPs, which are the design documents that explain Python including the rationale, I'd use that as a starting point. Suggestion: someone mentioned that you should make the function a normal function. You can mark it as private using an underscore as prefix. If you want to make it foolproof, you could even delete ("del fact_rec") the function after use. Other alternatives would be to put it into a separate baseclass, use a local function as implementation or to add the class attributes after defining the class. Neither of these provide the 'perfect' encapsulation of things in a class that you might be used to from e.g. Java, but they have proven to be very useful nonetheless. Uli -- Sator Laser GmbH Gesch?ftsf?hrer: Thorsten F?cking, Amtsgericht Hamburg HR B62 932 From gert.cuykens at gmail.com Wed Aug 26 13:28:23 2009 From: gert.cuykens at gmail.com (gert) Date: Wed, 26 Aug 2009 10:28:23 -0700 (PDT) Subject: How does the file.seek() work ? References: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> <1532ff09-f892-44c8-8206-10b3c2d16050@13g2000prl.googlegroups.com> Message-ID: <40093737-2ff1-4527-a2ea-a016ee526463@k30g2000yqf.googlegroups.com> On Aug 26, 12:46?am, Graham Dumpleton wrote: > On Aug 25, 5:37?am, Tim Chase wrote: > > > > I want the file pointer set to 100 and overwrite everything from there > > [snip] > > > def application(environ, response): > > > ? ? query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') > > > ? ? range=environ.get('HTTP_RANGE','bytes=0-').replace > > > ('bytes=','').split(',') > > > ? ? offset=[] > > > ? ? for r in range: offset.append(r.split('-')) > > > ? ? with open(query,'w+') as f: > > > ? ? ? ? ?f.seek(int(offset[0][0])) > > > ? ? ? ? ?while True: > > > ? ? ? ? ? ? ?chunk=environ['wsgi.input'].read(8192).decode('latin1') > > > ? ? ? ? ? ? ?if not chunk: break > > > ? ? ? ? ? ? ?f.write(chunk) > > > ? ? f=open(query) > > > ? ? l=str(os.fstat(f.fileno()).st_size) > > > ? ? response('200 OK', [('Content-Type', 'text/plain'), ('Content- > > > Length', str(len(l)))]) > > > ? ? return [l] > > > A couple items of note: > > > - you don't open the file in binary mode -- seek is more reliable > > in binary mode :) > > If my memory is right, if file is opened in binary mode, also wouldn't > need to be decoding the WSGI input stream as latin-1 to get a string. > Instead can just deal with bytes and write bytes to file. > > Graham > > > - if you want to lop off the rest of the file, use f.truncate() > > > An example: > > > # create the initial file > > ?>>> f = file('zzz.zzz', 'wb+') > > ?>>> f.write('abcdefghijklmnop') > > ?>>> f.close() > > > ?>>> f = file('zzz.zzz', 'ab+') > > ?>>> f.read() # show the existing content > > 'abcdefghijklmnop' > > ?>>> f.seek(5) # seek to the desired offset > > ?>>> f.truncate() # throw away everything after here > > ?>>> f.write('zyx') # write the new data at pos=5 > > ?>>> f.close() > > > # demonstrate that it worked > > ?>>> f = file('zzz.zzz', 'rb') > > ?>>> f.read() > > 'abcdezyx' > > ?>>> f.close() > > > > also why must I open the file a second time to know how big it is ? > > > Likely the output has been buffered. ?You can try using > > > ? ?f.flush() # write all the data to the disk first > > ? ?size = os.fstat(f.fileno()).st_size > > > which seems to do the trick for me. > > -tkc > Works thanks curl -C 10 -T upload2.wsgi http://192.168.2.17/appwsgi/wsgi/upload2.wsgi --header "Transfer-Encoding: chunked" -v import os def application(environ, response): #query=environ.get['QUERY_STRING'] #print (query, file=environ['wsgi.errors']) query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') range=environ.get('HTTP_CONTENT_RANGE','bytes 0-').replace('bytes ','').split('/')[0].split(',') offset=[] for r in range: offset.append(r.split('-')) with open(query,'rb+') as f: f.seek(int(offset[0][0])) if environ['REQUEST_METHOD']=='PUT': f.truncate() while True: chunk=environ['wsgi.input'].read(8192) if not chunk: break f.write(chunk) f.flush() l=str(os.fstat(f.fileno()).st_size) response('200 OK', [('Content-Type', 'text/plain'), ('Content- Length', str(len(l)))]) return [l] From tjreedy at udel.edu Wed Aug 26 13:52:36 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 26 Aug 2009 13:52:36 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: kj wrote: > In <7figv3F2m3p0dU1 at mid.uni-berlin.de> "Diez B. Roggisch" writes: > >> Classes are not scopes. Classes are objects. In particular, they are (by default) instances of class 'type'. Unless 'scopes' were instances of some other metaclass, the statement has to be true. I understand 'scope' as referring to a section of code, as opposed to a runtime object. Class statements introduce a new local namespace used to define the class. Whether one considers that as introducing a new 'scope' depends, I suppose, on one's exact definition of scope. > This looks to me like a major wart, on two counts. It is a 'wart' that a Python object is not a 'scope', whatever that is to you? I have trouble comprehending that claim. > First, one of the goals of OO is encapsulation, not only at the > level of instances, but also at the level of classes. Your comment > suggests that Python does not fully support class-level encapsulation. I really do not see how your claim follows from the comment. The irony of your 'two counts' is that the example of 'count 2' fails precisely because of the encapsulation that you claim does not exist as 'count 1'. > Second, my example shows that Python puts some peculiar restrictions > on recursion. I claim it does not. Name-based recursion inherently requires that a function be able to access itself by name at the time it is called. This can be a bit tricky, especially in a language with dynamic rather than static name binding and resolution, as it requires that code within the function be able to access a scope outside itself in which the function name is defined. In other words, it requires that function code *not* be completely encapsulated. It also require that the appropriate name be used when there is one. Neither of these is a 'peculiar restriction' imposed by Python. > class Demo(object): > def fact_rec(n): > if n < 2: > return 1 > else: > return n * fact_rec(n - 1) This function is just a function. It is not an instance method. It is not even a class method. It does not belong here and should not be here. If you insist on putting it where it does not belong, then you have to call it by a name that works. If you only call it after the class statement has finished, then 'Demo.fact_rec' works, as I believe someone else pointed out. If you want to call the function during class creation, before (in this case) Demo exists, then binding it to a local name works. With 3.1 class Demo: def f1(n): if n < 2: return 1 else: return n * Demo.f1(n - 1) def f2(n,f): if n < 2: return 1 else: return n * f(n - 1, f) cvar = f2(5, f2) print(Demo.f1(5), Demo.cvar, Demo.f2(5,Demo.f2)) # prints >>> 120 120 120 > Recursive functions should be OK wherever functions are OK. Iteration can and has been viewed as within-frame recursion. When iterative rather than recursive syntax is used, the naming issue is avoided. > Is there any good reason (from the point of view of Python's overall > design) for not fixing this? After reading the above, what, if anything, do you think still needs to be fixed? Before 2.2, Python functions were more encapsulated than they are today in that they could only access local and global namespaces but not outer function namespaces. It would be possible to further de-encapsulate them by giving them direct access to lexically surrounding class namespaces, but this would increase the problem of name clashes without solving any real problems in proper Python code. It could also break the intentional design principle that function code should mean the same thing whether placed within or without a class statement. This principle allows functions to be added to existing classes as attributes and work as methods that same as if they had been defined with the class. Terry Jan Reedy From mensanator at aol.com Wed Aug 26 13:58:12 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 26 Aug 2009 10:58:12 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> Message-ID: <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> On Aug 26, 9:58?am, Steven D'Aprano wrote: > On Tue, 25 Aug 2009 11:45:28 -0700, Mensanator wrote: > > On Aug 25, 9:14?am, Steven D'Aprano > cybersource.com.au> wrote: > >> On Mon, 24 Aug 2009 18:01:38 -0700, Mensanator wrote: > >> >> If you want your data file to have values entered in hex, or oct, or > >> >> even unary (1=one, 11=two, 111=three, 1111=four...) you can. > > >> > Unary? I think you'll find that Standard Positional Number Systems > >> > are not defined for radix 1. > > >> Of course not. But unary isn't a positional number system. It's a tally > >> system, like my example above shows. Roman numerals are another tally > >> system. Like Roman numerals, the disadvantages of unary are that you > >> can't represent negative numbers, zero, or fractions, and anything but > >> addition and subtraction is difficult. But if you want to use it, > >> perhaps out of a sense of sadism towards your users, it's easy: > [...] > > But without insignificant leading 0's, I fail to see the relevance of > > unary to this discussion. > > It was just an example of how you can use numeric data in any format, no > matter how obscure, weird or difficult, you can use it by passing it > through an appropriate converter. You don't need compiler support for > user-supplied data, you just write your own function. Ok, no problem with that. > > As for insignificant leading zeroes, such a thing is meaningless in a > base-1 tally system. Zero is the absence of a tally mark. > > > And what would you call a tally system of > > radix 2? Certainly not binary. > > "Radix" isn't the correct term, because radix doesn't apply to tally > counting systems. I'd accept "base 2", in the sense that the tally is > based on two different marks. I thought the two were equivalent, but maybe I'm wrong. Anyway, that's a minor quibble. > We do something similar when we mark four > tally lines, then for five we mark a diagonal line through the previous > four. So by analogy a base-2 tally could go: > > / ? ? one > X ? ? two > X/ ? ?three > XX ? ?four > XX/ ? five > XXX ? six > XXX/ ?seven Sure, as long as you're consistent, there's no problem. > > But I certainly wouldn't call it "binary", for fear of confusion with > radix-2 binary. That's my point. Since the common usage of "binary" is for Standard Positional Number System of Radix 2, it follows that "unary" is the common usage for Standard Positional Number System of Radix 1. That's VERY confusing since such a system is undefined. Remember, common usage does not necessarily properly define things. Saying simply "unary" sounds like you're extending common usage beyond its proper boundaries. > Possibly binary-tally, for lack of a better term. Then possibly unary-tally would be better than unary. Tally systems being much less common require a less common terminology to avoid confusion. > > -- > Steven From begin.middle.end at gmail.com Wed Aug 26 14:10:27 2009 From: begin.middle.end at gmail.com (Mahi Haile) Date: Wed, 26 Aug 2009 14:10:27 -0400 Subject: SimpleXMLRPCServer timeout issue Message-ID: <83d424980908261110m1f70b326ua4b7668c8bd173a4@mail.gmail.com> Hi all, I have an XML-RPC server running that is using SimpleXMLRPCServer, and I am trying to send a relatively large file on a poor connection [simulated low bandwidth, high latency]. The file is simply the return value of a function call available on the server. However, sometime in to the transfer, I get a timeout, seemingly regardless of what I do. The server is initiated as follows: s = SimpleXMLRPCServer((HOST, PORT), requestHandler = RequestHandler) s.timeout = 100000 #I tried setting this to None, and also a higher number And the exception I get is: Traceback (most recent call last): File "/python2.5/SocketServer.py", line 464, in process_request_thread self.finish_request(request, client_address) File "/python2.5/SocketServer.py", line 254, in finish_request self.RequestHandlerClass(request, client_address, self) File "/python2.5/SocketServer.py", line 522, in __init__ self.handle() File "/python2.5/BaseHTTPServer.py", line 316, in handle self.handle_one_request() File "python2.5/BaseHTTPServer.py", line 310, in handle_one_request method() File "/python2.5/SimpleXMLRPCServer.py", line 481, in do_POST self.wfile.write(response) File "/python2.5/socket.py", line 262, in write self.flush() File "/python2.5/socket.py", line 249, in flush self._sock.sendall(buffer) timeout: timed out Googling resulted in similar questions asked in the CherryPy forums, and the general suggestions seem to be to use a streaming transfer, using yield rather than return. Do you know how I go about solving when using the SimpleXMLRPCServer? For what it is worth, I am running the server on Mac OS X. Thank you, -------------- next part -------------- An HTML attachment was scrubbed... URL: From diesch at spamfence.net Wed Aug 26 14:37:30 2009 From: diesch at spamfence.net (Florian Diesch) Date: Wed, 26 Aug 2009 20:37:30 +0200 Subject: ubuntu dist-packages References: Message-ID: Robin Becker writes: > I was surprised a couple of days ago when trying to assist a colleage > with his python setup on a ubuntu 9.04 system. > > We built our c-extensions and manually copied them into place, but > site-packages wasn't there. It seems that ubuntu now wants stuff to go > into lib/python2.6/dist-packages. > > What is the relation between dist-packages/site-packages if any? Is > this just a name change or is there some other problem being > addressed? > > For developers is it best just to create one's own private > installations from the original tarballs? >From /usr/lib/python2.6/site.py: ,---- | For Debian and derivatives, this sys.path is augmented with directories | for packages distributed within the distribution. Local addons go | into /usr/local/lib/python/dist-packages, Debian addons | install into /usr/{lib,share}/python/dist-packages. | /usr/lib/python/site-packages is not used. `---- Florian -- From szport at gmail.com Wed Aug 26 14:57:54 2009 From: szport at gmail.com (zaur) Date: Wed, 26 Aug 2009 11:57:54 -0700 (PDT) Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> Message-ID: On 26 ???, 21:11, "Rami Chowdhury" wrote: > > person = Person(): > > ? name = "john" > > ? age = 30 > > ? address = Address(): > > ? ? ?street = "Green Street" > > ? ? ?no = 12 > > Can you clarify what you mean? Would that define a Person class, and an ? > Address class? I suppose that someone already define classes Person ans Address. For example, in this stupid way in a foreign module: class Person(object): pass class Address(object): pass and the following statements person = Person(): name = "john" age = 30 address = Address(): street = "Green Street" no = 12 are constructing an instance as follows: person = Person() person.name = "john" person.age = 30 address = person.address = Address() address.street = "Green Street" address.no = 12 > If you are expecting those classes to be already defined, please bear in ? > mind that if you want, you can do this: > > > > > class Person(object): > > ? ? ? ? def __init__(self, name='Nemo', age=0, address=None): > ? ? ? ? ? ? ? ? self.name = name > ? ? ? ? ? ? ? ? self.age = age > ? ? ? ? ? ? ? ? self.address = address > > > > > class Address(object): > > ? ? ? ? def __init__(self, street=None, no=None): > ? ? ? ? ? ? ? ? self.street = street > ? ? ? ? ? ? ? ? self.no = no > > > > > otherperson = Person( > > ? ? ? ? ? ? ? ? ? ? ?name = 'Bob', > ? ? ? ? ? ? ? ? ? ? ?age = 26, > ? ? ? ? ? ? ? ? ? ? ?address = Address( > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?street = 'Blue Street', > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?no = 1 > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?) > ? ? ? ? ? ? ? ? ? ? ?) > Yes, that's right. I aware about this way of instance initialization. From ethan at stoneleaf.us Wed Aug 26 15:00:02 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 26 Aug 2009 12:00:02 -0700 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A958632.9020301@stoneleaf.us> kj wrote: > > > I have many years of programming experience, and a few languages, > under my belt, but still Python scoping rules remain mysterious to > me. (In fact, Python's scoping behavior is the main reason I gave > up several earlier attempts to learn Python.) > > Here's a toy example illustrating what I mean. It's a simplification > of a real-life coding situation, in which I need to initialize a > "private" class variable by using a recursive helper function. > > class Demo(object): > def fact(n): > if n < 2: > return 1 > else: > return n * fact(n - 1) > > _classvar = fact(5) As has been pretty thoroughly discussed, the issue here is not recursion, but name lookup. Going back through the archives I found Arnaud's post with this decorator: def bindfunc(f): def boundf(*args, **kwargs): return f(boundf, *args, **kwargs) return boundf If you use it on your fact function like so... class Demo(object): @bindfunc def fact(recurse, n) # recurse can be any name you like if n < 2: return 1 else: return n * recurse(n-1) _classvar = fact(5) del fact # no longer needed, and won't work # once class is created This should do as you want. As a side note, if you're going to bother asking questions on this list, you really should try to understand the answers. I won't gripe at you too much, though, 'cause I learned a lot from the many responses given due to your refusal to do so. ;-) ~Ethan~ From evaned at gmail.com Wed Aug 26 15:12:59 2009 From: evaned at gmail.com (Evan Driscoll) Date: Wed, 26 Aug 2009 12:12:59 -0700 (PDT) Subject: Context manager to temporarily change the variable of a register [aka write swap(a,b)] References: <7c171ce3-56a7-482f-addd-c6c86441cba7@w6g2000yqw.googlegroups.com> <7c2c560f-d54c-492c-a847-e8ab079faea0@a26g2000yqn.googlegroups.com> <42b95155-db9d-4865-9039-c11ba556f3b4@z31g2000yqd.googlegroups.com> Message-ID: On Aug 26, 10:15?am, Carl Banks wrote: > Well, it wouldn't be a "can I rebind a variable using a with- > statement" thread if someone didn't post a solution that they thought > worked, but didn't test it on local variables. I'm not going to deny it was pretty stupid... though in my defense, I'm new at more that trivial Python coding and don't have the Python scoping rules and such ingrained in my mind yet. :-) Evan From no.email at please.post Wed Aug 26 15:20:24 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 19:20:24 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano writes: >http://docs.python.org/reference/executionmodel.html >It is also discussed in the PEP introducing nested scopes to Python: >http://www.python.org/dev/peps/pep-0227/ >It's even eluded to in the tutorial: >http://docs.python.org/tutorial/classes.html Thanks! kynn From nagle at animats.com Wed Aug 26 15:30:05 2009 From: nagle at animats.com (John Nagle) Date: Wed, 26 Aug 2009 12:30:05 -0700 Subject: Python Processor In-Reply-To: References: <7670c8130908260328l6982ef4etad802a755b85a44f@mail.gmail.com> Message-ID: <4a958c1b$0$1600$742ec2ed@news.sonic.net> Terry Reedy wrote: > manish wrote: >> Hi, >> >> I am also wondering about how to implement a soft core reconfigurable >> processor in a FPGA >> which would directly execute the compiled python bytecode. It probably wouldn't help much. CPython's performance problems come from excessive dictionary lookups, not from instruction decode. John Nagle From robert.kern at gmail.com Wed Aug 26 15:30:08 2009 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 26 Aug 2009 14:30:08 -0500 Subject: quantiles of a student distribution In-Reply-To: References: Message-ID: On 2009-08-26 11:49 AM, Colin J. Williams wrote: > Pierre wrote: >> Hello... >> >> Do you know how I can calculate the quantiles of a student >> distribution in pyhton ? >> >> Thanks > You might look at: > http://bonsai.ims.u-tokyo.ac.jp/~mdehoon/software/python/special.html [Please pardon the piggybacking. I have not gotten the original, yet.] Using scipy: In [1]: from scipy import stats In [2]: import numpy as np In [3]: x = np.linspace(-1.0, 1.0, 21) In [4]: x Out[4]: array([-1. , -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]) In [5]: ndof = 10 In [6]: stats.t.cdf(x, ndof) Out[6]: array([ 0.17044657, 0.19463963, 0.22115021, 0.24994379, 0.28092759, 0.3139468 , 0.3487837 , 0.3851603 , 0.4227446 , 0.46116036, 0.5 , 0.53883964, 0.5772554 , 0.6148397 , 0.6512163 , 0.6860532 , 0.71907241, 0.75005621, 0.77884979, 0.80536037, 0.82955343]) -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sridharr at activestate.com Wed Aug 26 15:35:00 2009 From: sridharr at activestate.com (Sridhar Ratnakumar) Date: Wed, 26 Aug 2009 12:35:00 -0700 Subject: ANN: ActivePython 3.1.1.2 is now available Message-ID: I'm happy to announce that ActivePython 3.1.1.2 is now available for download from: http://www.activestate.com/activepython/python3/ This is a patch release that updates ActivePython to core Python 3.1.1 We recommend that you try 2.6 version first. See the release notes for full details: http://docs.activestate.com/activepython/3.1/relnotes.html What is ActivePython? --------------------- ActivePython is ActiveState's binary distribution of Python. Builds for Windows, Mac OS X, Linux, HP-UX and AIX are made freely available. ActivePython includes the Python core and the many core extensions: zlib and bzip2 for data compression, the Berkeley DB (bsddb) and SQLite (sqlite3) database libraries, OpenSSL bindings for HTTPS support, the Tix GUI widgets for Tkinter, ElementTree for XML processing, ctypes (on supported platforms) for low-level library access, and others. The Windows distribution ships with PyWin32 -- a suite of Windows tools developed by Mark Hammond, including bindings to the Win32 API and Windows COM. See this page for full details: http://docs.activestate.com/activepython/3.1/whatsincluded.html As well, ActivePython ships with a wealth of documentation for both new and experienced Python programmers. In addition to the core Python docs, ActivePython includes the "What's New in Python" series, "Dive into Python", the Python FAQs & HOWTOs, and the Python Enhancement Proposals (PEPs). An online version of the docs can be found here: http://docs.activestate.com/activepython/ We would welcome any and all feedback to: ActivePython-feedback at activestate.com Please file bugs against ActivePython at: http://bugs.activestate.com/query.cgi?set_product=ActivePython On what platforms does ActivePython run? ---------------------------------------- ActivePython includes installers for the following platforms: - Windows/x86 - Windows/x64 (aka "AMD64") - Mac OS X - Linux/x86 - Linux/x86_64 (aka "AMD64") - Solaris/SPARC - Solaris/x86 - HP-UX/PA-RISC - AIX/PowerPC - AIX/PowerPC64 Extra Bits ---------- ActivePython releases also include the following: - ActivePythonXY.chm: An MS compiled help collection of the full ActivePython documentation set. Linux users of applications such as xCHM might find this useful. This package is installed by default on Windows. Extra bits are available from: http://downloads.activestate.com/ActivePython/etc/ Thanks, and enjoy! The Python Team -- Sridhar Ratnakumar sridharr at activestate.com From davea at ieee.org Wed Aug 26 15:50:46 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 15:50:46 -0400 Subject: Need help with Python scoping rules In-Reply-To: <90b1ff07-19cf-4eeb-abc5-80445da9f790@h21g2000yqa.googlegroups.com> References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <90b1ff07-19cf-4eeb-abc5-80445da9f790@h21g2000yqa.googlegroups.com> Message-ID: <4A959216.3080507@ieee.org> Carl Banks wrote: > On Aug 26, 8:13 am, Dave Angel wrote: > >> You can probably work around this by replacing the staticmethod >> decorator with an equivalent function call:. >> >> class Demo9(object): >> def fact(n): >> if n < 2: >> return 1 >> else: >> return n * Demo.fact(n - 1) >> >> _classvar =act(5) >> fact =taticmethod(fact) >> >> print Demo9._classvar >> xx =emo9() >> print xx.fact(6) >> print Demo9.fact(8) >> > > This won't work normally. It only worked for you because you made a > typo. > > > Carl Banks > > Sorry about the typo. I was trying out several different versions of the class in the same module, and forgot to include to change Demo to Demo9 in the recursive call. I didn't like that approach anyway, as it smacked of taking advantage of some implementation accident. The other approaches are more straightforward. DaveA From python at mrabarnett.plus.com Wed Aug 26 15:56:54 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 26 Aug 2009 20:56:54 +0100 Subject: Object's nesting scope In-Reply-To: References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> Message-ID: <4A959386.6060809@mrabarnett.plus.com> zaur wrote: > On 26 ???, 21:11, "Rami Chowdhury" wrote: >>> person = Person(): >>> name = "john" >>> age = 30 >>> address = Address(): >>> street = "Green Street" >>> no = 12 >> Can you clarify what you mean? Would that define a Person class, and an >> Address class? > I suppose that someone already define classes Person ans Address. > For example, in this stupid way in a foreign module: > > class Person(object): > pass > > class Address(object): > pass > > and the following statements > > person = Person(): > name = "john" > age = 30 > address = Address(): > street = "Green Street" > no = 12 > > are constructing an instance as follows: > > person = Person() > person.name = "john" > person.age = 30 > address = person.address = Address() > address.street = "Green Street" > address.no = 12 > [snip] Create factory functions: def new_address(**kwargs): address = Address() address.__dict__.update(kwargs) return address def new_person(**kwargs): person = Person() person.__dict__.update(kwargs) return person person = new_person(name="john", age=30, address=new_address(street="Green Street", no=12)) From python at mrabarnett.plus.com Wed Aug 26 16:03:45 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 26 Aug 2009 21:03:45 +0100 Subject: pygtk - What is the best way to change the mouse pointer In-Reply-To: References: Message-ID: <4A959521.8020505@mrabarnett.plus.com> Ido Levy wrote: > Hello All, > > I am writing a dialog which one of its widget is a gtk.ComboBoxEntry ( > let's assume widget in the example below is its instance ) > When the user select one of the values from the gtk.ComboBoxEntry I need > to run some calculations that takes a few seconds. > In order to reflect calculation time to the user I want to switch the > mouse pointer to an hour glass and back to arrow what it finish the > calculation. > > I use the following code but it doesn't seems to work in a deterministic > way. From time to time it skips the last line and keep the mouse pointer > as an hour glass. > > watch = gtk.gdk.Cursor(gtk.gdk.WATCH) > widget.window.set_cursor(watch) > > calculation code > > widget.window.set_cursor(None) > > I would appreciate your advice on the right way to implement this. > Could the calculation code be raising an exception? Try adding some logging to see whether the last lien is actually being called. You could also use a try...finally... block to ensure that the last line is called: watch = gtk.gdk.Cursor(gtk.gdk.WATCH) widget.window.set_cursor(watch) try: calculation code finally: widget.window.set_cursor(None) From find.mig at paa.google Wed Aug 26 16:06:01 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Wed, 26 Aug 2009 22:06:01 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a93e575$0$298$14726298@news.sunsite.dk> Message-ID: <4a9595ca$0$300$14726298@news.sunsite.dk> Hendrik van Rooyen wrote: >> would that be usable? > Probably >> If so, how? > > This is a guess, for your device, but I suspect > something along these lines: > > t = Ao_timer() > > cb = t.after(100,thing_that_does_the_work(with_its_arguments)) > > Lots of assumptions here - the 100 should give you a tenth of a second... > Don't know what the arguments look like, and if you need to pass an instance > (like self) - that would depend on where you are calling it from. > > Play and see :-) > > You should also be able to cancel the callback like this: > > t.cancel(cb) > > If you do it before the time out > > - Hendrik > I don't really get it... I can see that I should put a t.after(...) around the function that does the work, when calling it. That delays each call for the given period. I just tried it out, the console keeps saying ------------------------------------------------------------------------- Traceback (most recent call last): File "c:\resource\python25\python25.zip\sensorfw.py", line 499, in data_cb File "c:\resource\python25\python25.zip\sensorfw.py", line 160, in custom_cb File "e:\python\r3s_contextdata.py", line 79, in acc_filter self.acc_callback() File "e:\python\r3s_contextdata.py", line 85, in acc_callback self.doCallback() File "e:\python\r3s_contextdata.py", line 47, in doCallback self.at.after(0.05,self.data_callback) RuntimeError: Timer pending - cancel first ------------------------------------------------------------------------- It seems like i should cancel the current counting timer, when a new call comes in - but how to determine when to cancel etc? I'm kind of new to all this async python stuff. From find.mig at paa.google Wed Aug 26 16:07:25 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Wed, 26 Aug 2009 22:07:25 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a92b290$0$305$14726298@news.sunsite.dk> <4a93e575$0$298$14726298@news.sunsite.dk> Message-ID: <4a95961d$0$300$14726298@news.sunsite.dk> Dennis Lee Bieber wrote: > On Tue, 25 Aug 2009 15:21:16 +0200, Esben von Buchwald > declaimed the following in > gmane.comp.python.general: > >> This is how the accelerometer is accessed >> http://pys60.garage.maemo.org/doc/s60/node59.html >> >> I found this called "after"... >> http://pys60.garage.maemo.org/doc/s60/node12.html >> >> would that be usable? > > Based on the documentation... I'd suggest... > > def doCallback(self): > self.accelerometer.stop_listening() > self.data_callback() > self.accelerometer.start_listening() > > with appropriate changes to whatever reference you use for the > accelerometer would solve the problem... IE, when the callback is > triggered, you STOP the accelerometer action, compute results, and then > restart the accelerometer.. I just tried that - it made the application lock up, leaving the sensors unusable until next reboot of the phone. I don't think these start/stop calls are supposed to be called as often as it does the callback... From no.email at please.post Wed Aug 26 16:11:02 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 20:11:02 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: In Ethan Furman writes: >Going back through the archives I found Arnaud's post with this decorator: >def bindfunc(f): > def boundf(*args, **kwargs): > return f(boundf, *args, **kwargs) > return boundf >If you use it on your fact function like so... >class Demo(object): > @bindfunc > def fact(recurse, n) # recurse can be any name you like > if n < 2: > return 1 > else: > return n * recurse(n-1) > _classvar = fact(5) > del fact # no longer needed, and won't work > # once class is created >This should do as you want. Thanks, this is instructive. >As a side note, if you're going to bother asking questions on this list, >you really should try to understand the answers. I think I understand the answers well enough. What I *really* don't understand is why this particular "feature" of Python (i.e. that functions defined within a class statement are forbidden from "seeing" other identifiers defined within the class statement) is generally considered to be perfectly OK. IMO it's a bizarre, inexplicable blindspot (which, among other things, gives rise to a certain worry about what other similar craziness lurks under Python's image of rationality). I have never seen even a half-hearted justification, from a language design point of view, for why this particular "feature" is worth having. Maybe some day the BDFL will deign to give one. kynn From no.email at please.post Wed Aug 26 16:16:54 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 20:16:54 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: In <7figv3F2m3p0dU1 at mid.uni-berlin.de> "Diez B. Roggisch" writes: >But if you insist on the above methodology, you can do this: >class Demo(object): > def fact(n): > def inner(n): > if n < 2: > return 1 > else: > return n * inner(n - 1) > return inner(n) > _classvar = fact(5) >This makes inner a *local* variable, which is found. Thanks for this. I think this is the most straightforward workaround. kynn From no.email at please.post Wed Aug 26 16:35:28 2009 From: no.email at please.post (kj) Date: Wed, 26 Aug 2009 20:35:28 +0000 (UTC) Subject: Need help with Python scoping rules References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> <2a7gm6-9h.ln1@satorlaser.homedns.org> Message-ID: In <2a7gm6-9h.ln1 at satorlaser.homedns.org> Ulrich Eckhardt writes: >kj wrote: >> class Demo(object): >> def fact_iter(n): >> ret = 1 >> for i in range(1, n + 1): >> ret *= i >> return ret >> >> def fact_rec(n): >> if n < 2: >> return 1 >> else: >> return n * fact_rec(n - 1) >> >> classvar1 = fact_iter(5) >> classvar2 = fact_rec(5) >> >> >> In the initialization of classvar1, fact_iter is invoked without >> any problem even though the class is not yet created: no need to >> qualify it with the name of the class. This is completely inconsistent >> with the requirement that fact_rec be so qualified when invoked >> within fact_rec. >Let me take a shot at explaining this, maybe it helps that I'm mostly a C++ >guy.... Thanks for your reply. >I fully agree that this case is rather vexing to my (and obviously your) >biased brain. I wouldn't call this a bug before fully understanding why >e.g. you can not access a class before its definition is finished. I understand this, what I don't understand is why do it this way. I've been trying to understand this particular design point for *literally* years. >I think >someone mentioned one or two PEPs, which are the design documents that >explain Python including the rationale, I'd use that as a starting point. I'm reading PEP 227 now, suggested by Steven D'Aprano. In it I find statements like the following alert: (Note: If a region is contained within a class definition, the name bindings that occur in the class block are not visible to enclosed functions.) I've seen this before, but never an explanation for why having this restriction. It's just one of life's mysteries. (Incidentally, the fact that the author of PEP 227 felt it necessary to add that parenthetical remark suggests that the expectation it warns against is not so crazy after all.) But I'm still not done with PEP 227. Maybe I'll see the light by the time I'm done. kynn From grahn+nntp at snipabacken.se Wed Aug 26 16:38:15 2009 From: grahn+nntp at snipabacken.se (Jorgen Grahn) Date: 26 Aug 2009 20:38:15 GMT Subject: ubuntu dist-packages References: <7fki3lF2kirnkU1@mid.uni-berlin.de> Message-ID: On Wed, 26 Aug 2009 17:20:35 +0100, Robin Becker wrote: > Jorgen Grahn wrote: >> On Wed, 26 Aug 2009 12:46:13 +0200, Diez B. Roggisch > ........ >> Well, if you are thinking about Debian Linux, it's not as much >> "ripping out" as "splitting into a separate package with a non-obvious >> name". Annoying at times, but hardly an atrocity. > so where is the official place for user installed stuff on > ubuntu/debian ie will > there be dist-packages and site-packages. I don't know, but I know Debian has a group of people working out how to package Python and software written in Python. Those guys have a home page somewhere at debian.org -- there should be information there, and/or under /usr/share/doc/python* on your system. Another answer is "let distutils do its job and do not worry", but sometimes you need to know the rules and the reasons ... /Jorgen -- // Jorgen Grahn O o . From dullrich at sprynet.com Wed Aug 26 16:47:23 2009 From: dullrich at sprynet.com (David C Ullrich) Date: Wed, 26 Aug 2009 15:47:23 -0500 Subject: Python for professsional Windows GUI apps? References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: On Mon, 24 Aug 2009 22:22:20 -0700, sturlamolden wrote: > On 25 Aug, 05:56, Peter Decker wrote: > >> I use the Dabo Class Designer to visually design my forms. So what's >> you're point? ?:) > > Nothing, except lobbying for wxFormBuilder for anyone who still doesn't > know of it. :) That's great. But do you know of anything I can use as a visual form design tool in wxPython? From zuo at chopin.edu.pl Wed Aug 26 16:48:01 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 26 Aug 2009 22:48:01 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: 26-08-2009 o 09:03:27 Ulrich Eckhardt wrote: > Jean-Michel Pichavant wrote: >> class Color: >> def __init__(self, r, g,b): >> pass >> BLACK = Color(0,0,0) >> >> It make sens from a design point of view to put BLACK in the Color >> namespace. But I don't think it's possible with python. > > class Color: > ... > > setattrib(Color, "BLACK", Color(0,0,0)) Or simpler: class Color: ... Color.BLACK = Color(...) Then (Color.BLACK is Color.BLACK.BLACK.BLACK.BLACK) == True :-) *j PS. Obviously, that's nothing special (there is no problem with creating such "recursive" references in Python). -- Jan Kaliszewski (zuo) From cripto at ecn.org Wed Aug 26 16:56:16 2009 From: cripto at ecn.org (Anonymous) Date: Wed, 26 Aug 2009 22:56:16 +0200 (CEST) Subject: print() and unicode strings (python 3.1) Message-ID: <20090826205616.2B9231A7B03@www.ecn.org> Have you considered including an encoding line at the top of your file, as described in PEP 0263: http://www.python.org/dev/peps/pep-0263/ I just ran into a similar error, but it went away when I included # coding: utf-8 as the first line in my file. From kyrie at uh.cu Wed Aug 26 17:00:11 2009 From: kyrie at uh.cu (Luis Zarrabeitia) Date: Wed, 26 Aug 2009 17:00:11 -0400 Subject: Confessions of a Python fanboy In-Reply-To: References: <200907301757.48761.kyrie@uh.cu> Message-ID: <200908261700.12060.kyrie@uh.cu> On Friday 31 July 2009 04:08:33 am Masklinn wrote: > On 30 Jul 2009, at 23:57 , Luis Zarrabeitia wrote: > > I'd like to ask, what "container.each" is, exactly? It looks like a > > function > > call (as I've learned a few posts ago), but, what are its arguments? > > How the > > looping "works"? Does it receive a "code" object that it has to > > execute? > > Is .each some kind of magic keyword? (This has little to do with > > python or > > the current thread, so feel free to reply off-list if you want to...) > > #each is simply a method that takes a function (called blocks in > ruby). One could call it a higher-order method I guess. > > It's an implementation of the concept of internal iteration: instead > of collections yielding iterator objects, and programmers using those > through specially-built iteration constructs (e.g. `for?in`), > collections control iteration over themselves (the iteration is > performed "inside" the collection, thus the "internal" part) and the > programmer provides the operations to perform at each iterative step > through (usually) a function. Interesting. I know what internal iteration is, and I suspected it was along these lines when I saw the syntax and that .each was a function and not a keyword. But if it is internal iteration and the .each method is receiving an anonymous function, I wonder what is the scope of the variables in that function. In pseudo-python terms (using your example), x = 5 some_list.each((def (item): do_something(item, x) x = do_something_else(item) )) (or something like that). In python, the inner function would be invalid (the 'x' is local). For that construct to be equivalent to a for loop, the anonymous function shouldn't create a new scope. Is that what is happening? (If it is, this would be a big difference between anonymous and non-anonymous functions). Anyway, this is OT. Thank you for your reply. (ah, sorry for taking so long... I was out of town) -- Luis Zarrabeitia (aka Kyrie) Fac. de Matem?tica y Computaci?n, UH. http://profesores.matcom.uh.cu/~kyrie From paul at boddie.org.uk Wed Aug 26 17:00:26 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 26 Aug 2009 14:00:26 -0700 (PDT) Subject: ubuntu dist-packages References: <7fki3lF2kirnkU1@mid.uni-berlin.de> Message-ID: <71f5986e-6aae-46b0-8325-d67051c60a30@a13g2000yqc.googlegroups.com> On 26 Aug, 17:48, Jorgen Grahn wrote: > > Well, if you are thinking about Debian Linux, it's not as much > "ripping out" as "splitting into a separate package with a non-obvious > name". Annoying at times, but hardly an atrocity. Indeed. Having seen two packages today which insisted on setuptools, neither really needing it, and with one actively trying to download stuff from the Internet (fifteen seconds warning - how generous!) when running setup.py, it seems to me that it isn't the distribution packagers who need to be re-thinking how they install Python software. Generally, distributions have to manage huge amounts of software and uphold reasonable policies without creating unnecessary maintenance. Sadly, until very recently (and I'm still not entirely sure if there's really been an attitude change) the Pythonic packaging brigade has refused to even consider the needs of one of the biggest groups of consumers of the upstream code. Consequently, distributions will always devise different ways of storing installed Python software, documentation and resources, mostly because the Pythonic tools have been deficient, particularly in the management of the latter categories. Paul From zuo at chopin.edu.pl Wed Aug 26 17:02:42 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 26 Aug 2009 23:02:42 +0200 Subject: all possible matchings of elements of two lists In-Reply-To: References: Message-ID: 26-08-2009 o 12:05:41 Sandy wrote: > Hi all, > I basically want all possible matchings of elements from two lists, > Ex: [1,2] [a,b,c] > > Required: > [ [(1,a),(2,b)] > [(1,b),(2,c)] > [(1,c),(2,b)] > [(1,b),(2,a)] > [(1,c),(2,a)] > [(1,a),(2,c)] > ] > > My thought is to get all possible permutations of two lists given and > select any combination and use zip to get the tuples. Repeat this for > all possible combinations. > > Any other ideas? See: module itertools -- there are (OOTB) some combinatoric generators that may be useful for you. *j -- Jan Kaliszewski (zuo) From martin at v.loewis.de Wed Aug 26 17:10:41 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 26 Aug 2009 23:10:41 +0200 Subject: break unichr instead of fix ord? In-Reply-To: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: <4A95A4D1.9060008@v.loewis.de> > In Python 2.5 on Windows I could do [*1]: > > >>> a = unichr (65600) > >>> a[0],a[1] > (u'\ud800', u'\udc40') I can't reproduce that. My copy of Python on Windows gives Traceback (most recent call last): File "", line 1, in unichr(65600) ValueError: unichr() arg not in range(0x10000) (narrow Python build) This is Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32 Regards, Martin From martin.hellwig at dcuktec.org Wed Aug 26 17:19:05 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Wed, 26 Aug 2009 22:19:05 +0100 Subject: Python Processor In-Reply-To: <4a958c1b$0$1600$742ec2ed@news.sonic.net> References: <7670c8130908260328l6982ef4etad802a755b85a44f@mail.gmail.com> <4a958c1b$0$1600$742ec2ed@news.sonic.net> Message-ID: John Nagle wrote: > CPython's performance problems > come from excessive dictionary lookups, not from instruction decode. > > John Nagle Could you please suggest some background information/links to this? I tried to Google for it but unsurprisingly any combination with 'cpython' and 'performance' results (to me that is) in a haystack of rants. I did find http://www.python.org/dev/peps/pep-0339/ but I would ideally like to read something more in depth but still in reasonable easy language. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From ethan at stoneleaf.us Wed Aug 26 17:23:47 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Wed, 26 Aug 2009 14:23:47 -0700 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A95A7E3.7040900@stoneleaf.us> kj wrote: > I think I understand the answers well enough. What I *really* > don't understand is why this particular "feature" of Python (i.e. > that functions defined within a class statement are forbidden from > "seeing" other identifiers defined within the class statement) is > generally considered to be perfectly OK. IMO it's a bizarre, > inexplicable blindspot (which, among other things, gives rise to > a certain worry about what other similar craziness lurks under > Python's image of rationality). I have never seen even a half-hearted > justification, from a language design point of view, for why this > particular "feature" is worth having. Maybe some day the BDFL will > deign to give one. > > kynn You keep using that word. I do not think it means what you think it means. :) Keep studying. Listen. Learn how it *is*. Understanding may come later. ~Ethan~ From piet at cs.uu.nl Wed Aug 26 17:24:32 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 26 Aug 2009 23:24:32 +0200 Subject: Web Services examples using "raw" xml? References: <7fgbv7F2l9u4oU1@mid.uni-berlin.de> Message-ID: >>>>> "Diez B. Roggisch" (DBR) wrote: >DBR> John Gordon schrieb: >>> I'm developing a program that will use web services, which I have never >>> used before. >>> >>> There are several tutorials out there that advise you to get the WSDL >>> and then call a method (such as wsdl2py) that inspects the wsdl and >>> automagically generates the python classes and methods you need for >>> interacting with that web service. >>> >>> I've tried this, and have run into a number of roadblocks that have left >>> me frustrated. >DBR> Welcome to the wonderful world of SOAP. If you didn't know - the S stands >DBR> for simple [1]. Stood. Like the O was supposed to stand for Object. Now out of shame they tend to talk more about `Service Oriented Architecture Protocol'. Whichever is a greater abomination you may choose (that almost sounds like Yoda-speak). -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From ignace.danneels at gmail.com Wed Aug 26 17:40:24 2009 From: ignace.danneels at gmail.com (BlueFlash) Date: Wed, 26 Aug 2009 14:40:24 -0700 (PDT) Subject: How do I insert a menu item in an existing menu. Message-ID: <73dd8da1-7b1e-4065-9c2f-2cee554093e2@j21g2000yqe.googlegroups.com> Idea: Use of a RecentFileList, update element 0 with new file opened. Appending a menu is easy menu.Append(-1, "Menu Name") when I try to insert a new menu item menu.Insert(-1, position, "Menu Name") does not work. full code: def addnew(self, position, path): path = path.strip() try: self.filelist.index(path) # index() throws ValueError if path does not exist. except: # ValueError, path is not in list, so add it: if position >= len(self.filelist): self.filelist.append(path) item = self.menu.Append(-1, path) #this does return a menu item self.window.Bind(wx.EVT_MENU, self.event, item) else: self.filelist.insert(position, path) item = self.menu.InsertItem(-1, position, path) # does Not return a menu item. throws some exception. print item #self.window.Bind(wx.EVT_MENU, self.event, item) How do I remove a menu item from a menu? The RecentUsedList is eg: 4 element long. When opening a new file, this should be added at the top, and the 4th element must be dropped. From zuo at chopin.edu.pl Wed Aug 26 17:54:16 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Wed, 26 Aug 2009 23:54:16 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: 26-08-2009 o 17:45:54 kj wrote: > In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano > writes: > >> On Wed, 26 Aug 2009 10:57:32 +0000, kj wrote: > >>> Recursion! One of the central concepts in the theory of >>> functions! This is shown most clearly by the following elaboration of >>> my original example: >>> >>> class Demo(object): >>> def fact_rec(n): >>> if n < 2: >>> return 1 >>> else: >>> return n * fact_rec(n - 1) > >> Why are you defining a method without a self parameter? > > Because, as I've explained elsewhere, it is not a method: it's a > "helper" function, meant to be called only once, within the class > statement itself. > > Well, this is not strictly true, because the function is recursive, > so it will also call itself a few times. But still, all these > calls happen (loosely speaking) "within the class statement". > > In fact the only reason to use a function for such initialization > work is when one needs recursion; otherwise there's no point in > defining a function that will only be invoked exactly once. 1. I don't understand then... Why do you desire to both define and run it *within* that class statement as if it was this class's method? 2. Could you please show me how it could be done in C++ or Java? (Or you want to say that that languages also are not fully valuable OO languages?) 3. Python makes function bodies "agnostic" about the context of their definition -- generally any non-global information must be passed explicitly to their interior. *It has nothing to do with recursion.* If you really must both define and use such a function within the class definition, pass function object to itself explicitly, and everybody will be happy: class Demo(object): def fact(fact, n): if n < 2: return 1 else: return n * fact(fact, n - 1) fact(fact, 3) *j -- Jan Kaliszewski (zuo) From http Wed Aug 26 17:57:25 2009 From: http (Paul Rubin) Date: 26 Aug 2009 14:57:25 -0700 Subject: Zlib: correct checksum but error decompressing References: <99c381ef-a146-4545-9344-7b15d60441de@y20g2000vbk.googlegroups.com> Message-ID: <7xk50qz1a2.fsf@ruckus.brouhaha.com> Andre writes: > I have been trying to solve this issue for a while now. I receive data > from a TCP connection which is compressed. Are you sure it is compressed with zlib? If yes, does it include the standard zlib header? Some applications save a few bytes by stripping the header. See the zlib doc page for how to deal with that, there is a flag that causes the header check to be skipped on decompression if you pass a negative number. That's the first thing I would try. From piet at cs.uu.nl Wed Aug 26 17:59:57 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 26 Aug 2009 23:59:57 +0200 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> Message-ID: >>>>> Mensanator (M) wrote: >M> That's my point. Since the common usage of "binary" is for >M> Standard Positional Number System of Radix 2, it follows >M> that "unary" is the common usage for Standard Positional >M> Number System of Radix 1. That's VERY confusing since such >M> a system is undefined. Remember, common usage does not >M> necessarily properly define things. Saying simply "unary" >M> sounds like you're extending common usage beyond its proper >M> boundaries. But the customary meaning of `unary' is the tally system, as a radix system wouldn't make sense. I don't know when this term came into use but I have known it for a long time. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From python at mrabarnett.plus.com Wed Aug 26 18:12:58 2009 From: python at mrabarnett.plus.com (MRAB) Date: Wed, 26 Aug 2009 23:12:58 +0100 Subject: How do I insert a menu item in an existing menu. In-Reply-To: <73dd8da1-7b1e-4065-9c2f-2cee554093e2@j21g2000yqe.googlegroups.com> References: <73dd8da1-7b1e-4065-9c2f-2cee554093e2@j21g2000yqe.googlegroups.com> Message-ID: <4A95B36A.9070109@mrabarnett.plus.com> BlueFlash wrote: > Idea: Use of a RecentFileList, update element 0 with new file opened. > > Appending a menu is easy > menu.Append(-1, "Menu Name") > > when I try to insert a new menu item > menu.Insert(-1, position, "Menu Name") > > does not work. > The following comments are the result of a brief search of the web, so I'm not sure whether they're correct, but they might be worth a try. > full code: > def addnew(self, position, path): > path = path.strip() > try: > self.filelist.index(path) # index() throws ValueError > if path does not exist. > except: > # ValueError, path is not in list, so add it: > if position >= len(self.filelist): > self.filelist.append(path) > item = self.menu.Append(-1, path) #this does return a > menu item > self.window.Bind(wx.EVT_MENU, self.event, item) > else: > self.filelist.insert(position, path) > item = self.menu.InsertItem(-1, position, path) # does > Not return a menu item. throws some exception. I think it should be: item = self.menu.InsertItem(position, -1, path) > print item > #self.window.Bind(wx.EVT_MENU, self.event, item) > > > How do I remove a menu item from a menu? The RecentUsedList is eg: 4 > element long. When opening a new file, this should be added at the > top, and the 4th element must be dropped. I think you need the 'Remove' method. From ubershmekel at gmail.com Wed Aug 26 18:16:20 2009 From: ubershmekel at gmail.com (RunThePun) Date: Wed, 26 Aug 2009 15:16:20 -0700 (PDT) Subject: Overriding iadd for dictionary like objects Message-ID: I'd like to build a database wrapper using DictMixin and allow items to be appended by my own code. The problem is += is always understood as setitem and getitem plainly. d = MyDict() d['a'] = 1 # this is the problem code that's I'd like to override. It's always setitem('a', getitem('a') + 3) d['a'] += 3 # i wanted to do something like my own 'appenditem' function which for example could be useful if getitem is an expensive operation which can be avoided. I hope that was clear enough of a request, it's really late at night here... thanks, RunPun From stef.mientki at gmail.com Wed Aug 26 18:24:34 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 27 Aug 2009 00:24:34 +0200 Subject: Python for professsional Windows GUI apps? In-Reply-To: References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: <4A95B622.50705@gmail.com> David C Ullrich wrote: > On Mon, 24 Aug 2009 22:22:20 -0700, sturlamolden wrote: > > >> On 25 Aug, 05:56, Peter Decker wrote: >> >> >>> I use the Dabo Class Designer to visually design my forms. So what's >>> you're point? :) >>> >> Nothing, except lobbying for wxFormBuilder for anyone who still doesn't >> know of it. :) >> > > That's great. But do you know of anything I can use as a > visual form design tool in wxPython? > > Not a real form designer, but very convenient is XRC or GUI-support http://mientki.ruhosting.nl/data_www/pylab_works/pw_gui_support.html cheers, Stef From john_ladasky at sbcglobal.net Wed Aug 26 18:26:13 2009 From: john_ladasky at sbcglobal.net (John Ladasky) Date: Wed, 26 Aug 2009 15:26:13 -0700 (PDT) Subject: How do I insert a menu item in an existing menu. References: <73dd8da1-7b1e-4065-9c2f-2cee554093e2@j21g2000yqe.googlegroups.com> Message-ID: You might want to direct your wxPython questions to the dedicated wxPython newsgroup. It's Google-only, and thus not part of the Usenet hierarchy. But it's the most on-topic newsgroup you will find. http://groups.google.com/group/wxpython-users I attempted to crosspost this article to wx-python users, but that doesn't work for non-Usenet groups... Good luck! From matthew.bellis at gmail.com Wed Aug 26 18:27:55 2009 From: matthew.bellis at gmail.com (Matt Bellis) Date: Wed, 26 Aug 2009 15:27:55 -0700 (PDT) Subject: How to exclude "import"s from PyDoc Message-ID: Hi all, I tried PyDoc today for documentation for a small project on which I'm working. I have a class, foo, in foo.py. However, at the beginning of the file I "from math import *". When I use PyDoc, it's pulling in all the math functions.... ---snip--- . . . FUNCTIONS acos(...) acos(x) Return the arc cosine (measured in radians) of x. asin(...) asin(x) Return the arc sine (measured in radians) of x. . . . ----snip---- Anyone know the best way to get PyDoc to ignore this (or other) imported module(s)? Thanks in advance. Matt From robert.kern at gmail.com Wed Aug 26 18:48:33 2009 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 26 Aug 2009 17:48:33 -0500 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: Message-ID: On 2009-08-26 17:16 PM, RunThePun wrote: > I'd like to build a database wrapper using DictMixin and allow items > to be appended by my own code. The problem is += is always understood > as setitem and getitem plainly. > > d = MyDict() > d['a'] = 1 > > # this is the problem code that's I'd like to override. It's always > setitem('a', getitem('a') + 3) > d['a'] += 3 > # i wanted to do something like my own 'appenditem' function which for > example could be useful if getitem is an expensive operation which can > be avoided. > > I hope that was clear enough of a request, it's really late at night > here... I'm sorry, this is just part of the syntax of Python. You cannot override it. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From mensanator at aol.com Wed Aug 26 18:58:43 2009 From: mensanator at aol.com (Mensanator) Date: Wed, 26 Aug 2009 15:58:43 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> Message-ID: On Aug 26, 4:59?pm, Piet van Oostrum wrote: > >>>>> Mensanator (M) wrote: > >M> That's my point. Since the common usage of "binary" is for > >M> Standard Positional Number System of Radix 2, it follows > >M> that "unary" is the common usage for Standard Positional > >M> Number System of Radix 1. That's VERY confusing since such > >M> a system is undefined. Remember, common usage does not > >M> necessarily properly define things. Saying simply "unary" > >M> sounds like you're extending common usage beyond its proper > >M> boundaries. > > But the customary meaning of `unary' is the tally system, as a radix > system wouldn't make sense. I don't know when this term came into use > but I have known it for a long time. Ok, I'll accept that and in the same breath say such common usage is stupid. I, for one, have never heard such usage and would never use "unary" in the same breath as "decimal, octal, binary" even if I had. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org From deets at nospam.web.de Wed Aug 26 19:01:26 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Aug 2009 01:01:26 +0200 Subject: How to exclude "import"s from PyDoc In-Reply-To: References: Message-ID: <7flt66F2lho6lU1@mid.uni-berlin.de> Matt Bellis schrieb: > Hi all, > > I tried PyDoc today for documentation for a small project on which > I'm working. I have a class, foo, in foo.py. However, at the beginning > of the file I "from math import *". > > When I use PyDoc, it's pulling in all the math functions.... > > ---snip--- > . > . > . > FUNCTIONS > acos(...) > acos(x) > > Return the arc cosine (measured in radians) of x. > > asin(...) > asin(x) > > Return the arc sine (measured in radians) of x. > > . > . > . > ----snip---- > > > Anyone know the best way to get PyDoc to ignore this (or other) > imported module(s)? Don't know about pydoc, but epydoc (which generates much nicer docs imho) can be forced to only include certain packages. Diez From sturlamolden at yahoo.no Wed Aug 26 19:08:53 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Wed, 26 Aug 2009 16:08:53 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: <843fa78f-da92-4714-bac5-8807bf11e35a@f37g2000yqn.googlegroups.com> On 26 Aug, 22:47, David C Ullrich wrote: > > Nothing, except lobbying for wxFormBuilder for anyone who still doesn't > > know of it. :) > > That's great. But do you know of anything I can use as a > visual form design tool in wxPython? Right... I don't know if you are trying to be funny, but as I said there is wxFormBuilder... 3.0 generates XRC that you can use with wxPython. 3.1 beta generates wxPython classes you can subclass. Honestly, it's the best GUI builder for wxPython I know of. From cmpython at gmail.com Wed Aug 26 19:12:41 2009 From: cmpython at gmail.com (Che M) Date: Wed, 26 Aug 2009 16:12:41 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: <3a52c99d-6046-4e58-bed3-65d3e98980bb@r36g2000vbn.googlegroups.com> > Combined with the comment above about issues with printing, it looks > like Python for GUI apps isn't a very good idea :-/ I don't have that feeling at all. I don't have that much of a basis of comparison, but my experience with wxPython for making GUI apps has been pretty good. Does anyone know of a wxPython "gallery" of apps using it? That'd be the quickest way to prove its usefulness. Che From cmpython at gmail.com Wed Aug 26 19:27:07 2009 From: cmpython at gmail.com (Che M) Date: Wed, 26 Aug 2009 16:27:07 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: On Aug 26, 4:47?pm, David C Ullrich wrote: > On Mon, 24 Aug 2009 22:22:20 -0700, sturlamolden wrote: > > On 25 Aug, 05:56, Peter Decker wrote: > > >> I use the Dabo Class Designer to visually design my forms. So what's > >> you're point? ?:) > > > Nothing, except lobbying for wxFormBuilder for anyone who still doesn't > > know of it. :) > > That's great. But do you know of anything I can use as a > visual form design tool in wxPython? If in your mind GUI-builder = form builder (or close enough) there's Boa Constructor (my choice) and wxGlade. From rurpy at yahoo.com Wed Aug 26 19:27:33 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Wed, 26 Aug 2009 16:27:33 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> Message-ID: On 08/26/2009 03:10 PM, "Martin v. L?wis" wrote: >> >> In Python 2.5 on Windows I could do [*1]: >> >> >> >> >>> a = unichr (65600) >> >> >>> a[0],a[1] >> >> (u'\ud800', u'\udc40') > > > > I can't reproduce that. My copy of Python on Windows gives > > > > Traceback (most recent call last): > > File "", line 1, in > > unichr(65600) > > ValueError: unichr() arg not in range(0x10000) (narrow Python build) > > > > This is > > > > Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit > > (Intel)] on win32 My apologies for the red herring. I was working from a comment in my replacement ord() function. I dug up an old copy of Python 2.4.3 and could not reproduce it there either so I have no explanation for the comment (which I wrote). Python 2.3 maybe? But regardless, the significant question is, what is the reason for having ord() (and unichr) not work for surrogate pairs and thus not usable with a large number of unicode characters that Python otherwise supports? From rurpy at yahoo.com Wed Aug 26 19:29:34 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Wed, 26 Aug 2009 16:29:34 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: <5f561ea6-95bb-4ccc-9922-decf4e554331@q5g2000yqh.googlegroups.com> On Aug 25, 9:53?pm, "Mark Tolonen" wrote: > wrote in message > > news:2ad21a79-4a6c-42a7-8923-beb304bb5e99 at v20g2000yqm.googlegroups.com... > > > > > In Python 2.5 on Windows I could do [*1]: > > > ?# Create a unicode character outside of the BMP. > > ?>>> a = u'\U00010040' > > > ?# On Windows it is represented as a surogate pair. > > ?>>> len(a) > > ?2 > > ?>>> a[0],a[1] > > ?(u'\ud800', u'\udc40') > > > ?# Create the same character with the unichr() function. > > ?>>> a = unichr (65600) > > ?>>> a[0],a[1] > > ?(u'\ud800', u'\udc40') > > > ?# Although the unichr() function works fine, its > > ?# inverse, ord(), doesn't. > > ?>>> ord (a) > > ?TypeError: ord() expected a character, but string of length 2 found > > > On Python 2.6, unichr() was "fixed" (using the word > > loosely) so that it too now fails with characters outside > > the BMP. > > > ?>>> a = unichr (65600) > > ?ValueError: unichr() arg not in range(0x10000) (narrow Python build) > > > Why was this done rather than changing ord() to accept a > > surrogate pair? > > > Does not this effectively make unichr() and ord() useless > > on Windows for all but a subset of unicode characters? > > Switch to Python 3? > > >>> x='\U00010040' > >>> import unicodedata > >>> unicodedata.name(x) > > 'LINEAR B SYLLABLE B025 A2'>>> ord(x) > 65600 > >>> hex(ord(x)) > '0x10040' > >>> unicodedata.name(chr(0x10040)) > > 'LINEAR B SYLLABLE B025 A2'>>> ord(chr(0x10040)) > 65600 > >>> print(ascii(chr(0x10040))) > > '\ud800\udc40' > > -Mark I am still a long way away from moving to Python 3 but I am looking forward to hopefully more rational unicode handling there. Thanks for the info. From rurpy at yahoo.com Wed Aug 26 19:35:51 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Wed, 26 Aug 2009 16:35:51 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: On Aug 26, 2:05?am, Vlastimil Brom wrote: >[...] > Hi, > I'm not sure about the exact reasons for this behaviour on narrow > builds either (maybe the consistency of the input/ output data to > exactly one character?). > > However, if I need these functions for higher unicode planes, the > following rather hackish replacements seem to work. I presume, there > might be smarter ways of dealing with this, but anyway... > > hth, > ? ?vbr > >[...code snipped...] Thanks, I wrote a replacement ord function nearly identical to yours but will steal your unichr function if that's ok. :-) But I still wonder why all this is neccessary. From robert.kern at gmail.com Wed Aug 26 19:40:19 2009 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 26 Aug 2009 18:40:19 -0500 Subject: Python for professsional Windows GUI apps? In-Reply-To: <843fa78f-da92-4714-bac5-8807bf11e35a@f37g2000yqn.googlegroups.com> References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> <843fa78f-da92-4714-bac5-8807bf11e35a@f37g2000yqn.googlegroups.com> Message-ID: On 2009-08-26 18:08 PM, sturlamolden wrote: > On 26 Aug, 22:47, David C Ullrich wrote: > >>> Nothing, except lobbying for wxFormBuilder for anyone who still doesn't >>> know of it. :) >> >> That's great. But do you know of anything I can use as a >> visual form design tool in wxPython? > > Right... I don't know if you are trying to be funny, but as I said > there is wxFormBuilder... > > 3.0 generates XRC that you can use with wxPython. > 3.1 beta generates wxPython classes you can subclass. > > Honestly, it's the best GUI builder for wxPython I know of. It's possible that he is not asking for a visual form designer tool *for* building a wxPython app, but one that can be used *inside* a wxPython app like an IDE or something similar. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From stef.mientki at gmail.com Wed Aug 26 19:42:47 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Thu, 27 Aug 2009 01:42:47 +0200 Subject: Python for professsional Windows GUI apps? In-Reply-To: References: <20090825132439.d6cb18ca.feliphil@gmx.net> Message-ID: <4A95C877.7020401@gmail.com> Gilles Ganault wrote: > On Tue, 25 Aug 2009 13:24:39 +0200, Wolfgang Keller > wrote: > >> The area of _desktop_ database application development indeed looks like a vast and very hostile desert in the Python landscape. >> >> The only framework that seems to be worth trying is Dabo. Unfortunately there's little documentation, and that's mostly outdated. >> >> There's also Kiwi, but that's even less well documented. >> >> And GNU Enterprise essentially seems to be dead. >> > > Combined with the comment above about issues with printing, it looks > like Python for GUI apps isn't a very good idea :-/ > > I'd be interested in checking out commercial applications written in > Python for the Windows OS, if there are any. > I've been grown up with (and still using) Delphi, known as having th? best GUI-builder. I now use wxPython (with GUI-support), with more comfort and more easy than Delphi ! cheers, Stef > Thank you. > From sjmachin at lexicon.net Wed Aug 26 19:53:28 2009 From: sjmachin at lexicon.net (John Machin) Date: Wed, 26 Aug 2009 23:53:28 +0000 (UTC) Subject: Zlib: correct checksum but error decompressing References: <99c381ef-a146-4545-9344-7b15d60441de@y20g2000vbk.googlegroups.com> <7xk50qz1a2.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin writes: > > Andre gmail.com> writes: > > I have been trying to solve this issue for a while now. I receive data > > from a TCP connection which is compressed. > > Are you sure it is compressed with zlib? If yes, does it include the > standard zlib header? Some applications save a few bytes by stripping > the header. See the zlib doc page for how to deal with that, there is > a flag that causes the header check to be skipped on decompression if > you pass a negative number. That's the first thing I would try. Short answer: Try this: zlib.decompress(incoming_data, -15) If that doesn't work: print repr(incoming_data[:30]) # post the results here Longer answer: A zlib stream consists of a deflate stream preceded by a 2-byte header and followed by a 4-byte Adler32 checksum of the original data. The problem occurs not out of a desire to save 6 bytes but through compounding of 2 mistakes: Mistake (1) is in the HTTP protocol. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html The "deflate" content coding should have been called "zlib". Read this and weep: """deflate The "zlib" format defined in RFC 1950 [31] in combination with the "deflate" compression mechanism described in RFC 1951 [29].""" Mistake (2) happens when software implementers read only the first word of the above quote and provide only a deflate stream. A reader can handle both possibilities by checking for a (usual, default) zlib header: data[0] == '\x78' and (ord(data[1]) + 0x7800) % 31 == 0 HTH, John From contact at xavierho.com Wed Aug 26 20:20:59 2009 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 Aug 2009 10:20:59 +1000 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: Message-ID: <2d56febf0908261720i70dd92cds13c0139f25646c70@mail.gmail.com> I haven't tested it, but did you encounter a problem defining __iadd__ in the class definition? See: http://docs.python.org/reference/datamodel.html#object.__iadd__ Cheers, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ On Thu, Aug 27, 2009 at 8:48 AM, Robert Kern wrote: > On 2009-08-26 17:16 PM, RunThePun wrote: > >> I'd like to build a database wrapper using DictMixin and allow items >> to be appended by my own code. The problem is += is always understood >> as setitem and getitem plainly. >> >> d = MyDict() >> d['a'] = 1 >> >> # this is the problem code that's I'd like to override. It's always >> setitem('a', getitem('a') + 3) >> d['a'] += 3 >> # i wanted to do something like my own 'appenditem' function which for >> example could be useful if getitem is an expensive operation which can >> be avoided. >> >> I hope that was clear enough of a request, it's really late at night >> here... >> > > I'm sorry, this is just part of the syntax of Python. You cannot override > it. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless > enigma > that is made terrible by our own mad attempt to interpret it as though it > had > an underlying truth." > -- Umberto Eco > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vlastimil.brom at gmail.com Wed Aug 26 20:26:28 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Thu, 27 Aug 2009 02:26:28 +0200 Subject: break unichr instead of fix ord? In-Reply-To: References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> Message-ID: <9fdb569a0908261726t23d19f82pa590b57a4297d662@mail.gmail.com> 2009/8/27 : > On Aug 26, 2:05?am, Vlastimil Brom wrote: >>[...] >>... >> However, if I need these functions for higher unicode planes, the >> following rather hackish replacements seem to work. I presume, there >> might be smarter ways of dealing with this, but anyway... >> >> hth, >> ? ?vbr >> >>[...code snipped...] > > Thanks, I wrote a replacement ord function nearly identical > to yours but will steal your unichr function if that's ok. :-) > > But I still wonder why all this is neccessary. > -- You are welcome :-), but make sure to test it, if you are going to use it for something more complex; as I said, it's only vaguely tested ... vbr From zuo at chopin.edu.pl Wed Aug 26 21:00:10 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 27 Aug 2009 03:00:10 +0200 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: Message-ID: 27-08-2009 o 00:48:33 Robert Kern wrote: > On 2009-08-26 17:16 PM, RunThePun wrote: >> I'd like to build a database wrapper using DictMixin and allow items >> to be appended by my own code. The problem is += is always understood >> as setitem and getitem plainly. >> >> d = MyDict() >> d['a'] = 1 >> >> # this is the problem code that's I'd like to override. It's always >> setitem('a', getitem('a') + 3) >> d['a'] += 3 >> # i wanted to do something like my own 'appenditem' function which for >> example could be useful if getitem is an expensive operation which can >> be avoided. >> >> I hope that was clear enough of a request, it's really late at night >> here... > > I'm sorry, this is just part of the syntax of Python. You cannot > override it. Though d['a'] = 3 is equivalent to: d.__setitem__('a', 3) The d['a'] += 3 *is not* equivalent to: d.__setitem__('a', d.__getitem__('a') + 3) *but is* equivalent to: d.__getitem__('a').__iadd__(3) Then you can override __getitem__() of MyDict in such a way that it returns prepared (wrapped) object with overriden __iadd__() as you want to. How could I now it: 1 import collections 2 import functools 3 import itertools 4 5 6 def verbose_func(func): 7 'Function decorator that makes a function "verbose"' 8 9 @functools.wraps(func, assigned=('__name__', '__doc__')) 10 def func_wrapper(*args, **kwargs): 11 iargs = (map(str, args)) 12 ikwargs = ('{0}={1}'.format(key, value) 13 for key, value in kwargs.items()) 14 func_args = ', '.join(itertools.chain(iargs, ikwargs)) 15 print('{0}({1})'.format(func.__name__, func_args)) 16 return func(*args, **kwargs) 17 18 return func_wrapper 19 20 21 def verbose_cls(base): 22 'Class decorator that makes callable attributes "verbose"' 23 24 quiet = ('__new__', '__repr__', '__str__') 25 26 def cls_wrapper(cls): 27 for name in vars(base): 28 attr = getattr(cls, name) 29 if isinstance(attr, collections.Callable) and name not in quiet: 30 setattr(cls, name, verbose_func(attr)) 31 return cls 32 33 return cls_wrapper 34 35 36 @verbose_cls(dict) 37 class VerboseDict(dict): 38 pass 39 40 41 @verbose_cls(int) 42 class MyInt(int): 43 44 @verbose_func 45 def __iadd__(self, other): 46 int.__add__(self, other) # can do something more interesting 47 48 49 if __name__ == '__main__': 50 d = VerboseDict() 51 52 print("d['a'] = 3") 53 d['a'] = MyInt(3) 54 55 print("d['a'] += 3") 56 d['a'] += MyInt(3) *j -- Jan Kaliszewski (zuo) From aahz at pythoncraft.com Wed Aug 26 21:01:35 2009 From: aahz at pythoncraft.com (Aahz) Date: 26 Aug 2009 18:01:35 -0700 Subject: List iterator thread safety References: Message-ID: In article , Emanuele D'Arrigo wrote: > >Let's say I have a list accessed by two threads, one removing list >items via "del myList[index]" statement the other iterating through >the list and printing out the items via "for item in myList:" >statement. Am I right to say this -won't- generate exceptions because >the list iterator is not concerned with the list changing in size >under its nose? Or are there pitfalls I should be aware of? Well, I'm not sure about exceptions, but you almost certainly won't get the results you want. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From zuo at chopin.edu.pl Wed Aug 26 21:02:19 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 27 Aug 2009 03:02:19 +0200 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: Message-ID: 27-08-2009 o 00:48:33 Robert Kern wrote: > On 2009-08-26 17:16 PM, RunThePun wrote: >> I'd like to build a database wrapper using DictMixin and allow items >> to be appended by my own code. The problem is += is always understood >> as setitem and getitem plainly. >> >> d = MyDict() >> d['a'] = 1 >> >> # this is the problem code that's I'd like to override. It's always >> setitem('a', getitem('a') + 3) >> d['a'] += 3 >> # i wanted to do something like my own 'appenditem' function which for >> example could be useful if getitem is an expensive operation which can >> be avoided. >> >> I hope that was clear enough of a request, it's really late at night >> here... > > I'm sorry, this is just part of the syntax of Python. You cannot > override it. Though d['a'] = 3 is equivalent to: d.__setitem__('a', 3) The d['a'] += 3 *is not* equivalent to: d.__setitem__('a', d.__getitem__('a') + 3) *but is* equivalent to: d.__setitem__('a', d.__getitem__('a').__iadd__(3)) Then you can override __getitem__() of MyDict in such a way that it returns prepared (wrapped) object with overriden __iadd__() as you want to. How could I now it: 1 import collections 2 import functools 3 import itertools 4 5 6 def verbose_func(func): 7 'Function decorator that makes a function "verbose"' 8 9 @functools.wraps(func, assigned=('__name__', '__doc__')) 10 def func_wrapper(*args, **kwargs): 11 iargs = (map(str, args)) 12 ikwargs = ('{0}={1}'.format(key, value) 13 for key, value in kwargs.items()) 14 func_args = ', '.join(itertools.chain(iargs, ikwargs)) 15 print('{0}({1})'.format(func.__name__, func_args)) 16 return func(*args, **kwargs) 17 18 return func_wrapper 19 20 21 def verbose_cls(base): 22 'Class decorator that makes callable attributes "verbose"' 23 24 quiet = ('__new__', '__repr__', '__str__') 25 26 def cls_wrapper(cls): 27 for name in vars(base): 28 attr = getattr(cls, name) 29 if isinstance(attr, collections.Callable) and name not in quiet: 30 setattr(cls, name, verbose_func(attr)) 31 return cls 32 33 return cls_wrapper 34 35 36 @verbose_cls(dict) 37 class VerboseDict(dict): 38 pass 39 40 41 @verbose_cls(int) 42 class MyInt(int): 43 44 @verbose_func 45 def __iadd__(self, other): 46 int.__add__(self, other) # can do something more interesting 47 48 49 if __name__ == '__main__': 50 d = VerboseDict() 51 52 print("d['a'] = 3") 53 d['a'] = MyInt(3) 54 55 print("d['a'] += 3") 56 d['a'] += MyInt(3) *j -- Jan Kaliszewski (zuo) From zuo at chopin.edu.pl Wed Aug 26 21:06:16 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 27 Aug 2009 03:06:16 +0200 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: Message-ID: PS. Sorry for sending 2 posts -- the latter is the correct one. Cheers, *j From davea at ieee.org Wed Aug 26 21:19:37 2009 From: davea at ieee.org (Dave Angel) Date: Wed, 26 Aug 2009 21:19:37 -0400 Subject: [Tutor] Declaration order of classes... why it is important? In-Reply-To: <1251323517.23132.6.camel@jabbar> References: <1251303952.20327.46.camel@jabbar> <1c2a2c590908261040r1e70348v8d31d0bf628e7c80@mail.gmail.com> <4A959114.8010703@ieee.org> <1251323517.23132.6.camel@jabbar> Message-ID: <4A95DF29.5070803@ieee.org> (Looks like you posted privately to me; should use Reply-all. I'm copying entire message here so others can add to my comments) Mac Ryan wrote: > On Wed, 2009-08-26 at 15:46 -0400, Dave Angel wrote: > >> So define a classmethod to finish the job, and invoke it later >> >> class Employee(object): >> @classmethod >> def finish(cls): >> cls.__storm_table__ = "employee" >> cls.company_id = [] >> cls.company = Company.id #where Company is a forward >> reference >> del cls.finish #remove this method so it won't be called a >> second time >> >> class Company: >> id = 42 >> >> Employee.finish() #This finishes initializing the class >> >> >> help(Employee) >> print Employee.company_id >> > > First things first, thank you Wayne, Kent and Dave for your extensive > and complementary explanations. As many things in python, what it seemed > obscure at first now - with your help - seems perfectly obvious. > > Second thing: the example that Dave gave me and that I left quoted above > makes use of decorators, but this is something that I still do not > understand. I believe I got a grasp of the concept of metaclasses, to > which the concept of decorator seems to be related, but the official > documentation is a a bit obscure for me. > > I don't want to steal your time asking for an explanation that probably > is already somewhere out there, but my google searches did not return > anything useful (I assume I am using the wrong keywords here), so if you > have a good pointer for me, I would be very grateful. :) > > Mac. > > > Decorators are syntactic sugar to save typing; what they accomplish can always be done another way, but generally not as readable. #somebody (eg., Python library) defines a function that takes a function as parameter, and returns a function, generally a different one related to the first def mydecorator(funct): .... return newfunct class myclass(object): @mydecorator def mymethod(self, arg1, arg2): ... Instead of the @syntax, we could also have written: class myclass(object): def mymethod(self, arg1, arg2) .... mymethod = mydecorator(mymethod) #this call happens when the class is being created Now there are a couple of decorators that are in the standard library that everyone should know about: classmethod() and staticmethod(). They wrap a method in a new one (which ends up having the same name), such that the first argument is either eaten (staticmethod), or changed to a class (classmethod). Hope that was sufficient detail. DaveA From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 21:34:10 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 01:34:10 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> Message-ID: <02a5d290$0$15633$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 10:58:12 -0700, Mensanator wrote: >> But I certainly wouldn't call it "binary", for fear of confusion with >> radix-2 binary. > > That's my point. Since the common usage of "binary" is for Standard > Positional Number System of Radix 2, it follows that "unary" is the > common usage for Standard Positional Number System of Radix 1. Er, no, that doesn't follow. There is no such thing as a radix-1 positional number system -- it just doesn't work. In any case, unary is the standard term for what I'm discussing: http://en.wikipedia.org/wiki/Unary_numeral_system although Mathworld doesn't seem to know it. > That's VERY confusing since such a system is undefined. Base-1 positional system is defined, it just doesn't work. You would have to write a number by the sum of 0*(1**i), which clearly doesn't get you very far. Positional unary is only capable of representing zero, and no other numbers, which is even less useful than unary, which at least can be used for counting positive numbers, addition and subtraction, and even has a use in Elias gamma coding. > Remember, common usage > does not necessarily properly define things. Saying simply "unary" > sounds like you're extending common usage beyond its proper boundaries. You're reasoning by analogy: "binary" means "positional number system with radix 2", "decimal" => radix 10, etc, so "unary" => radix 1. That's a reasonable heuristic to follow, but it can fail, because even in mathematics, names for things don't necessarily follow such patterns perfectly. Because the radix 1 positional system can't work and therefore doesn't exist, the name "unary" is available, and has been taken to describe a number system which counts by tally marks. -- Steven From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 21:52:27 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 01:52:27 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> <02a5d290$0$15633$c3e8da3@news.astraweb.com> Message-ID: <02a5d6da$0$15633$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 01:34:10 +0000, Steven D'Aprano wrote: > On Wed, 26 Aug 2009 10:58:12 -0700, Mensanator wrote: > >>> But I certainly wouldn't call it "binary", for fear of confusion with >>> radix-2 binary. >> >> That's my point. Since the common usage of "binary" is for Standard >> Positional Number System of Radix 2, it follows that "unary" is the >> common usage for Standard Positional Number System of Radix 1. > > Er, no, that doesn't follow. There is no such thing as a radix-1 > positional number system -- it just doesn't work. Sorry, this is clumsy writing... of course radix-1 positional number system is defined, it's just pointless -- it is only capable of representing 0 = 00 = 000 = 0000 ... -- Steven From max at alcyone.com Wed Aug 26 21:53:04 2009 From: max at alcyone.com (Erik Max Francis) Date: Wed, 26 Aug 2009 18:53:04 -0700 Subject: Numeric literals in other than base 10 - was Annoying octal notation In-Reply-To: <02a5d290$0$15633$c3e8da3@news.astraweb.com> References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> <02a5d290$0$15633$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > On Wed, 26 Aug 2009 10:58:12 -0700, Mensanator wrote: > >>> But I certainly wouldn't call it "binary", for fear of confusion with >>> radix-2 binary. >> That's my point. Since the common usage of "binary" is for Standard >> Positional Number System of Radix 2, it follows that "unary" is the >> common usage for Standard Positional Number System of Radix 1. > > Er, no, that doesn't follow. There is no such thing as a radix-1 > positional number system -- it just doesn't work. > > In any case, unary is the standard term for what I'm discussing: > > http://en.wikipedia.org/wiki/Unary_numeral_system > > although Mathworld doesn't seem to know it. Psst. That's a hint. Googling for "unary number system" ("unary numeral system" just comes up with endless mirrors of Wikipedia) gives Wikipedia as hit #1. Hit #2 is from the Institute of Druidic Technology, another hint. The remaining hits are pretty much people pontificating in discussion groups just as they are in this one. Yes, you can define something that works. But it's not the usual mathematical definition of radix, so if you want to talk about it you have to disclaim that it's not a proper base and that's you're making up as you go. But you can't pretend like it's the "obvious" mathematical meaning just because the usual mathematical meaning doesn't apply, which is what you seem to be doing. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 18 N 121 57 W && AIM/Y!M/Skype erikmaxfrancis And I've seen the promised land. I may not get there with you. -- Dr. Martin Luther King, Jr. From graham.dumpleton at gmail.com Wed Aug 26 22:09:49 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Wed, 26 Aug 2009 19:09:49 -0700 (PDT) Subject: Python on the Web References: <4a94ef42$0$27774$426a74cc@news.free.fr> Message-ID: On Aug 27, 2:54?am, Phil wrote: > Thanks to everybody. I believe I am understanding things better. > > I have looked at the links that have been provided, although I have > seen most of them in the past month or so that I've been looking into > this stuff. I do agree with most of the things Armin stated in that > NIH post. I agree with everybody in this thread so far. If I wanted to > write an application, I would use an existing framework and wait for > it to be ported to 3.x. However, I do not have the need to write a web > application at this time, and creating blogs or other applications I > do not need for fun is getting old. > > My reasoning for working on my own instead of following the 'NIH' > concept or contributing to an existing framework is because I have > experimented with many existing frameworks and I have figured out what > I like/dislike, and have envisioned my own design that I feel would > work potentially better for others, or at least newcomers. Things like > this are fun for me, and I do not mind the challenge. I don't want to > pollute the web with (sigh) 'another framework', but it would be fun > for me to write it and get some feedback. I would love for people like > you, Armin, and others who take a look at the various frameworks that > pop up seemingly every day, to look at my (hypothetical) framework and > just rip it apart with (constructive) criticism. That is just the way > I do things, whether the community agrees with it or not. The reason I > was asking about Python 3 on the web was just because I like some of > the changes that have been made, and would like to use it for my > framework. That is when I realized that I was absolutely clueless > about the details of how Python, or any language, works on the web. > > Graham, regarding number 3 in your list of ways to host WSGI: I > haven't really looked into mod_wsgi at all, but basically it sounds > like the web server would be running this embedded module. That module > would then serve the function of both FCGI and the 'WSGI Server' in my > diagram? That actually sounds really neat. Unfortunately I missed this > because I've been hooked on lighttpd, as the minimalist I am. > > Here are the things I am still confused with: > > 1) Why do I not want to consider running Python on the web with FCGI, > without WSGI? You said 'no' straight up, no questions asked. I would > imagine that there is a good reason of course, as you've been in this > field for a long time. Because FASTCGI is a wire protocol for socket communications and not a programming interface. As such, you would only be creating much more work for your self as you would need to implement a whole lot of code to handle the protocol and then still put a usable interface on top of it. You would also have to come up with what that usable interface should be as well. WSGI already provides that low level interface. > I just feel more comfortable understanding why. > From my understanding, the only real purpose of WSGI is to remain > independent of FCGI/SCGI/CGI/AJP (whatever that is) and the web server > it is run on. However, 99.9% of the discussion I see with Python on > the web is around FCGI. 99.9% of the discussion about Python on the web is not around FASTCGI. Even if there is quite a bit of discussion, it is because documentation on hosting Python on FASTCGI via flup is virtually non existent and so many people have a lot of trouble getting it to work due to peculiarities of different FASTCGI implementations. The dicusssion is therefore because people have problems with it, or feel the need to blog about how they finally got it to work. So, FASTCGI may be the only way for commodity web hosting, but it certainly isn't for self managed servers where mod_wsgi, mod_python and mod_proxy type solutions are going to be preferred. The latter are better documented or easier to setup and so why you possibly don't see as much discussion. In other words, people who get things working easily don't need to ask questions. > So for example, lets say everybody used FCGI. > All that would be left to deal with is web server independence. Now > this is what I don't get, I thought that FCGI itself was supposed to > be the protocol that deals with web server independence. Maybe I just > need to re-read entire WSGI specification to understand, along with > all the details of FCGI. There are just so many details regarding web > servers, FCGI, and WSGI that it is hard to absorb it all and see how > it works together. That is why I tried to create the diagram, but it > doesn't provide enough details. And those are the details I am > missing. I've been trying to find a simple diagram or explaination of > the process a request takes to make a response, from HTTP all the way > up to the application, to the the user. FASTCGI fills a role, but is not essential. Personally I feel that whole concept of FASTCGI/SCGI/AJP needs a refresh and modernised with better hosting support for it. > 2) In the development stack, the 'WSGI Server' seems to take on the > role of the web server (dealing with HTTP specification), It doesn't have to. Some servers may have a clear line between the two with WSGI being a properly distinct layer on top. > skips FCGI, > and deals with the WSGI specification. Then, the 'WSGI Server' in the > production stack (eg. Flup, CherryPy, etc) only deals with FCGI and > WSGI specification, because the HTTP is already taken care of by the > web server? Graham From manish.paradkar at gmail.com Wed Aug 26 22:39:21 2009 From: manish.paradkar at gmail.com (manish) Date: Thu, 27 Aug 2009 10:39:21 +0800 Subject: Python Processor Message-ID: <7670c8130908261939p7ef1726bodbae14d836d33ea5@mail.gmail.com> Hi, Contrary to the ancient and, I believe, obsolete text in the documentation, there is no 'python bytecode'. Dis is based on CPython bytecode. Jython uses Java bytecode. IronPython uses, I believe, Microsoft clr bytecode. Object code compilers do not use bytecode. Before going through the one of the existing VM implementations, i want to know if there is there any informaition available which elaborates on the structure of the bytecodes. Like details regarding co_names, co_cellvars, co_freevars, the concept of frames, global, local, objects, functions etc with respect to the bytecode. These are mostly version-specific Cpython implementation details. tjr I agree, i am looking at a version-specific CPython implementation, or can be PyPy even . I need some information on the implementation of these interpreters which would help me visualize how they can be mapped to hardware. It probably wouldn't help much. CPython's performance problems come from excessive dictionary lookups, not from instruction decode. John Nagle This is just for my personal interest so currently i am not looking at performance - just be able to implement a basic core at first. The idea is to then extend it and develop a self contained unit of computation which can be reconfigured on the fly. So given enough memory and I/Os the same module can behave differently depending on the script loaded. One can either have a large monolithic cpu running an OS of some sorts or smaller processors each executing their own little scripts and communicating with each other. Manish -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet at enigmacurry.com Wed Aug 26 22:52:19 2009 From: usenet at enigmacurry.com (Ryan McGuire) Date: Wed, 26 Aug 2009 19:52:19 -0700 (PDT) Subject: codecs.open on Win32 -- converting my newlines to CR+LF Message-ID: <8fbc2c4a-c347-43df-8830-3b4e86d95792@t13g2000yqt.googlegroups.com> I've got a UTF-8 encoded text file from Linux with standard newlines ("\n"). I'm reading this file on Win32 with Python 2.6: codecs.open("whatever.txt","r","utf-8").read() Inexplicably, all the newlines ("\n") are replaced with CR+LF ("\r \n") ... Why? As a workaround I'm having to do this: open("whatever.txt","r").read().decode("utf-8") which appropriately does not alter my newlines. What really gets me confused though is the Python docs for codecs.open: "Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8- bit values. This means that no automatic conversion of '\n' is done on reading and writing." The way I read that, codecs.open should not touch my newlines. What am I doing wrong? Is this a bug in Python, or in the docs, or both? From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 22:52:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 02:52:41 GMT Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> Message-ID: <02a5e4f7$0$15633$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 16:27:33 -0700, rurpy wrote: > But regardless, the significant question is, what is the reason for > having ord() (and unichr) not work for surrogate pairs and thus not > usable with a large number of unicode characters that Python otherwise > supports? I'm no expert on Unicode, but my guess is that the reason is out of a desire for simplicity: unichr() should always return a single char, not a pair of chars, and similarly ord() should take as input a single char, not two, and return a single number. Otherwise it would be ambiguous whether ord(surrogate_pair) should return a pair of ints representing the codes for each item in the pair, or a single int representing the code point for the whole pair. E.g. given your earlier example: >>> a = u'\U00010040' >>> len(a) 2 >>> a[0] u'\ud800' >>> a[1] u'\udc40' would you expect ord(a) to return (0xd800, 0xdc40) or 0x10040? If the latter, what about ord(u'ab')? Remember that a unicode string can contain code points that aren't valid characters: >>> ord(u'\ud800') # reserved for surrogates, not a character 55296 so if ord() sees a surrogate pair, it can't assume it's meant to be treated as a surrogate pair rather than a pair of code points that just happens to match a surrogate pair. None of this means you can't deal with surrogate pairs, it just means you can't deal with them using ord() and unichr(). The above is just my guess, I'd be interested to hear what others say. -- Steven From phily05 at gmail.com Wed Aug 26 23:02:55 2009 From: phily05 at gmail.com (Phil) Date: Wed, 26 Aug 2009 20:02:55 -0700 (PDT) Subject: Python on the Web References: <4a94ef42$0$27774$426a74cc@news.free.fr> Message-ID: <835a57b2-9a08-4f10-b2d4-78c96f22f3ee@n11g2000yqb.googlegroups.com> Thanks a lot for another response. I've never posted in groups like this before but the results are amazing. I will definitely consider trying mod_wsgi when I get a chance. I like the approach taken with it. It is unfortunate that I completely missed all Apache related material because I was using lighttpd. Is there no mod_wsgi for lighttpd? I guess I could always just Google that myself. Thanks again for the help. From philip at semanchuk.com Wed Aug 26 23:04:31 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Wed, 26 Aug 2009 23:04:31 -0400 Subject: codecs.open on Win32 -- converting my newlines to CR+LF In-Reply-To: <8fbc2c4a-c347-43df-8830-3b4e86d95792@t13g2000yqt.googlegroups.com> References: <8fbc2c4a-c347-43df-8830-3b4e86d95792@t13g2000yqt.googlegroups.com> Message-ID: <2E7FD302-C77A-48DD-B03D-B1959945BBA4@semanchuk.com> On Aug 26, 2009, at 10:52 PM, Ryan McGuire wrote: > I've got a UTF-8 encoded text file from Linux with standard newlines > ("\n"). > > I'm reading this file on Win32 with Python 2.6: > > codecs.open("whatever.txt","r","utf-8").read() > > Inexplicably, all the newlines ("\n") are replaced with CR+LF ("\r > \n") ... Why? Try using "rb" instead of "r" for the mode in the call to open(). HTH Philip From steve at REMOVE-THIS-cybersource.com.au Wed Aug 26 23:27:05 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 03:27:05 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> <02a5d290$0$15633$c3e8da3@news.astraweb.com> Message-ID: <02a5ed07$0$15633$c3e8da3@news.astraweb.com> On Wed, 26 Aug 2009 18:53:04 -0700, Erik Max Francis wrote: >> In any case, unary is the standard term for what I'm discussing: >> >> http://en.wikipedia.org/wiki/Unary_numeral_system >> >> although Mathworld doesn't seem to know it. > > Psst. That's a hint. > > Googling for "unary number system" ("unary numeral system" just comes up > with endless mirrors of Wikipedia) gives Wikipedia as hit #1. Hit #2 is > from the Institute of Druidic Technology, another hint. The remaining > hits are pretty much people pontificating in discussion groups just as > they are in this one. Perhaps you should FOLLOW THE REFERENCES from the Wikipedia article, instead of relying on Google. http://www.research.att.com/~njas/sequences/A000042 which in turn points to primary references: K. G. Kroeber, Mathematik der Palindrome; p. 348; 2003; ISBN 3 499 615762; Rowohlt Verlag; Germany D. Olivastro, Ancient Puzzles. Bantam Books, NY, 1993, p. 276. Amarnath Murthy, On the divisors of the unary sequence, Smarandache Notions Journal Vol. - 11, 2000. Amarnath Murthy and Charles Ashbacher, Generalized Partitions and Some New Ideas on Number Theory and Smarandache Sequences, Hexis, Phoenix; USA 2005. See Section 2.12. > Yes, you can define something that works. But it's not the usual > mathematical definition of radix, It's not a radix. I never said it is a radix. Only you and Mensator are confusing it with a radix system, which is *your* problem, not mine. > so if you want to talk about it you > have to disclaim that it's not a proper base and that's you're making up > as you go. But you can't pretend like it's the "obvious" mathematical > meaning just because the usual mathematical meaning doesn't apply, which > is what you seem to be doing. I explicitly gave an example, showing what I meant by unary, because I knew it would be unfamiliar terminology for most people. When my example was ignored completely, I explained further, and showed that it's fairly standard terminology. It is *uncommon* terminology, since most mathematicians don't concern themselves with non-positional number representations, which is why Goggle doesn't find many references to it apart from Wikipedia and copies of Wikipedia. David Wheeler also discusses "base 1", and describes it as "cheating a bit". It's only cheating if you assume you're working with a positional radix system, which tallies aren't. Here's another example, from American Scientist: https://www.americanscientist.org/issues/pub/third-base/2 although that site seems to be having problems now and you're best off with the Google cache: http://74.125.153.132/search?q=cache:7hlZ33y4uCAJ:https:// www.americanscientist.org/issues/pub/third-base/2+%22base+1%22 +numbers&cd=18&hl=en&ct=clnk&gl=uk&ie=UTF-8 [quote] How do you measure the cost of a numeric representation? If you simply count digits, then the biggest base will always win; for example, base 1,000,000 can represent any number between 0 and decimal 999,999 in a single digit. The trouble is, that single digit can be any of a million different symbols, all of which you must somehow recognize. At the opposite pole are unary, or base-1, numbers. The unary representation of decimal 1,000,000 needs only one type of symbol, but that symbol is repeated a million times. (Unary notation is in a category apart from other bases?it's not really a positional number system?but in the present context it serves as a useful limiting case.) [end quote] This really isn't anywhere near as controversial as you guys are making it. Words sometimes have meanings different from what you expect from reasoning by analogy. Get over it. -- Steven From usenet at enigmacurry.com Wed Aug 26 23:40:36 2009 From: usenet at enigmacurry.com (Ryan McGuire) Date: Wed, 26 Aug 2009 20:40:36 -0700 (PDT) Subject: codecs.open on Win32 -- converting my newlines to CR+LF References: <8fbc2c4a-c347-43df-8830-3b4e86d95792@t13g2000yqt.googlegroups.com> Message-ID: <6085bece-97c6-4400-9571-7cd288da1578@g31g2000yqc.googlegroups.com> On Aug 26, 11:04?pm, Philip Semanchuk wrote: > Try using "rb" instead of "r" for the mode in the call to open(). > > HTH > Philip That does indeed fix the problem, thanks! Still seems like the docs are wrong though. From robert.kern at gmail.com Wed Aug 26 23:58:05 2009 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 26 Aug 2009 22:58:05 -0500 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: Message-ID: On 2009-08-26 20:00 PM, Jan Kaliszewski wrote: > 27-08-2009 o 00:48:33 Robert Kern wrote: > >> On 2009-08-26 17:16 PM, RunThePun wrote: >>> I'd like to build a database wrapper using DictMixin and allow items >>> to be appended by my own code. The problem is += is always understood >>> as setitem and getitem plainly. >>> >>> d = MyDict() >>> d['a'] = 1 >>> >>> # this is the problem code that's I'd like to override. It's always >>> setitem('a', getitem('a') + 3) >>> d['a'] += 3 >>> # i wanted to do something like my own 'appenditem' function which for >>> example could be useful if getitem is an expensive operation which can >>> be avoided. >>> >>> I hope that was clear enough of a request, it's really late at night >>> here... >> >> I'm sorry, this is just part of the syntax of Python. You cannot >> override it. > > Though > d['a'] = 3 > is equivalent to: > d.__setitem__('a', 3) > > The > d['a'] += 3 > *is not* equivalent to: > d.__setitem__('a', d.__getitem__('a') + 3) > *but is* equivalent to: > d.__getitem__('a').__iadd__(3) > > Then you can override __getitem__() of MyDict in such a way that it > returns prepared (wrapped) object with overriden __iadd__() as you > want to. You could, but then you will almost certainly run into problems using the wrapped object in places that really expect the true object. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From rylesny at gmail.com Thu Aug 27 00:44:43 2009 From: rylesny at gmail.com (ryles) Date: Wed, 26 Aug 2009 21:44:43 -0700 (PDT) Subject: Object's nesting scope References: Message-ID: On Aug 26, 8:51?am, zaur wrote: > Hi folk! > > What do you think about idea of "object's nesting scope" in python? > > Let's imaging this feature, for example, in this syntax: > > obj=: > ? ? ? > > or > > : > ? ? > > That's means that result object of evaluation is used as > nested scope for evaluation. > > So is this idea useful? > > Zaur FYI, there was recently a similar idea being discussed on the python- ideas list: http://groups.google.com/group/python-ideas/browse_thread/thread/1a13cd9a5189b01c?hl=en From rurpy at yahoo.com Thu Aug 27 01:36:12 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Wed, 26 Aug 2009 22:36:12 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <02a5e4f7$0$15633$c3e8da3@news.astraweb.com> Message-ID: <144510f3-3cc4-4b3f-bdcc-98e810d6ee35@2g2000prl.googlegroups.com> On 08/26/2009 08:52 PM, Steven D'Aprano wrote: > On Wed, 26 Aug 2009 16:27:33 -0700, rurpy wrote: > >> But regardless, the significant question is, what is the reason for >> having ord() (and unichr) not work for surrogate pairs and thus not >> usable with a large number of unicode characters that Python otherwise >> supports? > > > I'm no expert on Unicode, but my guess is that the reason is out of a > desire for simplicity: unichr() should always return a single char, not a > pair of chars, and similarly ord() should take as input a single char, > not two, and return a single number. > > Otherwise it would be ambiguous whether ord(surrogate_pair) should return > a pair of ints representing the codes for each item in the pair, or a > single int representing the code point for the whole pair. > > E.g. given your earlier example: > >>>> a = u'\U00010040' >>>> len(a) > 2 >>>> a[0] > u'\ud800' >>>> a[1] > u'\udc40' > > would you expect ord(a) to return (0xd800, 0xdc40) or 0x10040? The latter. > If the > latter, what about ord(u'ab')? I would expect a TypeError* (as ord() currently raises) because the string length is not 1 and 'ab' is not a surrogate pair. *Actually I would have expected ValueError but I'm not going to lose sleep over it. > Remember that a unicode string can contain code points that aren't valid > characters: > >>>> ord(u'\ud800') # reserved for surrogates, not a character > 55296 > > so if ord() sees a surrogate pair, it can't assume it's meant to be > treated as a surrogate pair rather than a pair of code points that just > happens to match a surrogate pair. Well, actually, yes it can. :-) Python has already made a strong statement that such a pair the representation of a character: >>> a = ''.join([u'\ud800',u'\udc40']) >>> a u'\U00010040' That is, Python prints, and treats in nearly all other contexts, that combination as a character. This is related to the practicality argument: what is the ratio of need treat a surrogate pair as character consistent with with the rest of Python, vs the need to treat it as a string of two separate (and invalid in the unicode sense?) characters? And if you want to treat each half of the pair separately it's not exactly hard: ord(a[0]), ord(a[1]). > None of this means you can't deal with surrogate pairs, it just means you > can't deal with them using ord() and unichr(). Kind of like saying, it doesn't mean you can't deal with integers larger that 2**32, you just can't multiply and divide them. > The above is just my guess, I'd be interested to hear what others say. From martin at v.loewis.de Thu Aug 27 01:51:29 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 27 Aug 2009 07:51:29 +0200 Subject: break unichr instead of fix ord? In-Reply-To: References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> Message-ID: <4A961EE1.9010103@v.loewis.de> > My apologies for the red herring. I was working from > a comment in my replacement ord() function. I dug up > an old copy of Python 2.4.3 and could not reproduce it > there either so I have no explanation for the comment > (which I wrote). Python 2.3 maybe? No. The behavior you observed would only happen on a wide Unicode build (e.g. on Unix). > But regardless, the significant question is, what is > the reason for having ord() (and unichr) not work for > surrogate pairs and thus not usable with a large number > of unicode characters that Python otherwise supports? See PEP 261, http://www.python.org/dev/peps/pep-0261/ It specifies all this. Regards, Martin From clp2 at rebertia.com Thu Aug 27 02:06:07 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 26 Aug 2009 23:06:07 -0700 Subject: codecs.open on Win32 -- converting my newlines to CR+LF In-Reply-To: <6085bece-97c6-4400-9571-7cd288da1578@g31g2000yqc.googlegroups.com> References: <8fbc2c4a-c347-43df-8830-3b4e86d95792@t13g2000yqt.googlegroups.com> <6085bece-97c6-4400-9571-7cd288da1578@g31g2000yqc.googlegroups.com> Message-ID: <50697b2c0908262306t223cc991o5564bac623d9697a@mail.gmail.com> On Wed, Aug 26, 2009 at 8:40 PM, Ryan McGuire wrote: > On Aug 26, 11:04?pm, Philip Semanchuk wrote: >> Try using "rb" instead of "r" for the mode in the call to open(). >> >> HTH >> Philip > > That does indeed fix the problem, thanks! Still seems like the docs > are wrong though. Yeah, the need to specify "b" does seem rather incongruous: codecs.open(filename, mode[, encoding[, errors[, buffering]]]) [...] Note: Files are always opened in binary mode, even if no binary mode was specified. This is done to avoid data loss due to encodings using 8-bit values. This means that no automatic conversion of b'\n' is done on reading and writing. File a bug perhaps?: http://bugs.python.org/ Cheers, Chris -- http://blog.rebertia.com From clp2 at rebertia.com Thu Aug 27 02:11:22 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Wed, 26 Aug 2009 23:11:22 -0700 Subject: codecs.open on Win32 -- converting my newlines to CR+LF In-Reply-To: <50697b2c0908262306t223cc991o5564bac623d9697a@mail.gmail.com> References: <8fbc2c4a-c347-43df-8830-3b4e86d95792@t13g2000yqt.googlegroups.com> <6085bece-97c6-4400-9571-7cd288da1578@g31g2000yqc.googlegroups.com> <50697b2c0908262306t223cc991o5564bac623d9697a@mail.gmail.com> Message-ID: <50697b2c0908262311w55faa8afh91eef611ca99f6b5@mail.gmail.com> On Wed, Aug 26, 2009 at 11:06 PM, Chris Rebert wrote: > On Wed, Aug 26, 2009 at 8:40 PM, Ryan McGuire wrote: >> On Aug 26, 11:04?pm, Philip Semanchuk wrote: >>> Try using "rb" instead of "r" for the mode in the call to open(). >>> >>> HTH >>> Philip >> >> That does indeed fix the problem, thanks! Still seems like the docs >> are wrong though. > > Yeah, the need to specify "b" does seem rather incongruous: > > codecs.open(filename, mode[, encoding[, errors[, buffering]]]) > ? ?[...] > ? ?Note: Files are always opened in binary mode, even if no binary > mode was specified. This is done to avoid data loss due to encodings > using 8-bit values. This means that no automatic conversion of b'\n' > is done on reading and writing. > > File a bug perhaps?: http://bugs.python.org/ Ah, I see you already did: http://bugs.python.org/issue6788 - Chris From hendrik at microcorp.co.za Thu Aug 27 02:38:29 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 08:38:29 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <200908270838.29673.hendrik@microcorp.co.za> On Wednesday 26 August 2009 17:14:27 kj wrote: > As I described at length in another reply, the function in question > is not intended to be "callable outside the class". And yes, I think this might go to nub of your problem - It might help you to think as follows: A Python class, even after it has been executed, does not really exist except as a kind of template or pattern - it is mostly useless until an instance of the class is made by calling it with whatever it needs to set up the instance. And once you have an instance, you can do stuff with that particular instance. Before that time, the class is mostly just a promise of things to come. > recursive functions in Python *are* restricted in ways that > non-recursive functions aren't. The examples I've posted prove > this point unambiguously. Yes and no - mostly no - your examples just illustrate the point I tried to make above. Pythons object model, and its classes, are different from what you are used to. A bare class is mostly useless without an instance, which is ultimately why accessing a function in a class from itself like you are doing, without reference to an instance, does not work - the function does not exist yet to a degree that it can be referenced. It is kind of subtle, and different from other languages. 8<------------- rant against the way things are ----------------------- Welcome to python, and the newsgroup, by the way. - Hendrik From ubershmekel at gmail.com Thu Aug 27 02:49:10 2009 From: ubershmekel at gmail.com (RunThePun) Date: Wed, 26 Aug 2009 23:49:10 -0700 (PDT) Subject: Overriding iadd for dictionary like objects References: Message-ID: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> On Aug 27, 6:58?am, Robert Kern wrote: > On 2009-08-26 20:00 PM, Jan Kaliszewski wrote: > > > > > > > 27-08-2009 o 00:48:33 Robert Kern wrote: > > >> On 2009-08-26 17:16 PM, RunThePun wrote: > >>> I'd like to build a database wrapper using DictMixin and allow items > >>> to be appended by my own code. The problem is += is always understood > >>> as setitem and getitem plainly. > > >>> d = MyDict() > >>> d['a'] = 1 > > >>> # this is the problem code that's I'd like to override. It's always > >>> setitem('a', getitem('a') + 3) > >>> d['a'] += 3 > >>> # i wanted to do something like my own 'appenditem' function which for > >>> example could be useful if getitem is an expensive operation which can > >>> be avoided. > > >>> I hope that was clear enough of a request, it's really late at night > >>> here... > > >> I'm sorry, this is just part of the syntax of Python. You cannot > >> override it. > > > Though > > d['a'] = 3 > > is equivalent to: > > d.__setitem__('a', 3) > > > The > > d['a'] += 3 > > *is not* equivalent to: > > d.__setitem__('a', d.__getitem__('a') + 3) > > *but is* equivalent to: > > d.__getitem__('a').__iadd__(3) > > > Then you can override __getitem__() of MyDict in such a way that it > > returns prepared (wrapped) object with overriden __iadd__() as you > > want to. > > You could, but then you will almost certainly run into problems using the > wrapped object in places that really expect the true object. > > -- > Robert Kern > > "I have come to believe that the whole world is an enigma, a harmless enigma > ? that is made terrible by our own mad attempt to interpret it as though it had > ? an underlying truth." > ? ?-- Umberto Eco Exactly my problem Robert. I'm actually going to be using this dict for storing and retrieving strings so wrapping str and replacing the iadd would cause alot of craziness. Anybody have any more ideas? I think python should/could havev a syntax for overriding this behaviour, i mean, obviously the complexity of supporting all operators with the getitem syntax could introduce alot of clutter. But maybe there's an elegant solution out there... ---RP From rylesny at gmail.com Thu Aug 27 02:56:49 2009 From: rylesny at gmail.com (ryles) Date: Wed, 26 Aug 2009 23:56:49 -0700 (PDT) Subject: Q: multiprocessing.Queue size limitations or bug... References: Message-ID: <9a338a3f-33a8-416c-af42-36f596c7cb71@r27g2000vbn.googlegroups.com> On Aug 26, 4:56?am, Michael Riedel wrote: > Sorry for being not more specific but I'm not absolutely certain whether > I encountered a bug or did anything wrong: > > The (stupid) code below results in a stall forever or not at 'p0.join()' > depending on the value of TROUBLE_MAKER. > > Any help, thoughts, comments? > > Thank you for your time. > > Michael > > # ---------------------------------------------------------------------- > > from multiprocessing import Process, Queue > > # bit vector size > BVS=8 > > # > TROUBLE_MAKER=12 ?# for greater values p0.join() is never satisfied... > > def evaluate(q, id, start=0, stop=2**BVS): > > ? ? cmin = {0: []} > > ? ? for mask0 in range(start, stop): > ? ? ? ? for mask1 in range(0, 2**BVS): > ? ? ? ? ? ? for mask2 in range(mask1, TROUBLE_MAKER): > ? ? ? ? ? ? ? ? cmin[0].append((mask0, mask1, mask2)) > > ? ? print 'process %d finished (dict layout: %d/%d)...' % (id, > len(cmin), len(cmin[0])) > ? ? q.put(cmin.copy()) > ? ? q.close() > > if __name__ == '__main__': > > ? ? q0 = Queue() > ? ? q1 = Queue() > ? ? q2 = Queue() > ? ? q3 = Queue() > > ? ? part = 2**BVS/4 > ? ? p0 = Process(target=evaluate, args=(q0, 0, 0*part, 1*part), > name='worker_0') > ? ? p1 = Process(target=evaluate, args=(q1, 1, 1*part, 2*part), > name='worker_1') > ? ? p2 = Process(target=evaluate, args=(q2, 2, 2*part, 3*part), > name='worker_2') > ? ? p3 = Process(target=evaluate, args=(q3, 3, 3*part, 4*part), > name='worker_3') > ? ? p0.start() > ? ? print 'process 0 started...' > ? ? p1.start() > ? ? print 'process 1 started...' > ? ? p2.start() > ? ? print 'process 2 started...' > ? ? p3.start() > ? ? print 'process 3 started...' > ? ? # main process stalls at p0.join() for bigger TROUBLE_MAKER > ? ? p0.join() > ? ? p1.join() > ? ? p2.join() > ? ? p3.join() > ? ? res0 = q0.get() > ? ? res1 = q1.get() > ? ? res2 = q2.get() > ? ? res3 = q3.get() > ? ? print 'results fetched...' > > # ---------------------------------------------------------------------- > > -- There is a warning related to this in the documentation: http://docs.python.org/library/multiprocessing.html#pipes-and-queues Basically, you should reverse the order of the get() and join() calls. multiprocessing does a pretty nice job of abstracting away the low- level details of IPC, but there are still some gotchas. As you've noticed, your program will deadlock when there is a large enough amount of data being put into the queue. This is related to a hidden thread that exists inside each of your child processes. The thread is responsible for taking your queue items from an internal buffer and then writing them into a pipe that your parent process will read from when get() is called. The pipe mechanism is what allows the two processes to pass information, and is supported directly by the Operating System. However, the pipe has a limited capacity, and when it is full, the writer thread is stuck waiting for the reader to read enough from the pipe so that it can finish its write. The problem is that your parent process (reader) is not actually calling get() to drain the pipe. Instead it's stuck in join() waiting for the writer to complete. From hendrik at microcorp.co.za Thu Aug 27 03:09:21 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 09:09:21 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: <200908270909.21886.hendrik@microcorp.co.za> On Wednesday 26 August 2009 17:45:54 kj wrote: > In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano writes: > >Why are you defining a method without a self parameter? > > Because, as I've explained elsewhere, it is not a method: it's a > "helper" function, meant to be called only once, within the class > statement itself. If the sole purpose of the function is to be used to define what will become a constant, why do you not just calculate the constant on your calculator, or at the interactive prompt, and assign it to the attribute, and be done with it? Why waste run time recalculating every time the programme is called? > > Well, this is not strictly true, because the function is recursive, > so it will also call itself a few times. But still, all these > calls happen (loosely speaking) "within the class statement". Why *must* it be there? > > In fact the only reason to use a function for such initialization > work is when one needs recursion; otherwise there's no point in > defining a function that will only be invoked exactly once. Seems no point to me even when there is recursion - a number is a number is a number. If you know the arguments when you write it, and if the function is known at time of writing, storing a literal is the best solution. Conversely, if the arguments are not known at time of writing, then they should be passed at run time, when an instance is created, and assigned as part of the __init__ method. And the same is true if the function is not known at time of writing - then it must be passed to the constructor of the instance. Storm in a teacup. - Hendrik From frank at chagford.com Thu Aug 27 03:10:02 2009 From: frank at chagford.com (Frank Millman) Date: Thu, 27 Aug 2009 09:10:02 +0200 Subject: Move dictionary from instance to class level In-Reply-To: <4A955AA5.6000200@ieee.org> Message-ID: <20090827071016.E9A7F8A3D@ctb-mesg-1-1.saix.net> Dave Angel wrote: > Any time I see multiple lists like that which have to stay in > synch, I think code-smell. > I don't think it is that bad, but I agree there is always room for improvement. > Why not let the EVT's be passed as strings, and avoid the whole mapping > to integers and mapping back detail? And name the methods involved in a > way that you can directly translate the string to the method name? > There is some merit in this. At present I am writing the server and the client, and copy/paste the list of constants, so they are guaranteed to stay in sync. (Maybe I should import it instead - even more fool-proof [the fool being me, of course]). However, it may happen that I want to open it up to 3rd-party clients in the future, in which case I would have to publish some sort of API. It would make more sense to identify the messages by a meaningful name rather than an integer. And yes, I could then use 'getattr' to retrieve the corresponding method on the server side. > Barring that, make a single "structure" which lists the event > names and > method names in matched pairs, and derive whatever lists and > dictionaries you actually need from that one structure. And that > structure should be shared between client and server code, > perhaps as a > text file that they both parse. Or as a stream that's passed > from one > to the other during startup. That way, consistency between > them can be > regulated (with version string in the file, for example) > I'm not sure how that would work. On the client side, I need to respond to a 'button-clicked' event from the gui system by sending an EVT_BUTTON_CLICKED message to the server. In other words it is hard-coded into the client program. I don't know how that would work if I read in a list of message-types at startup. > DaveA > Thanks for the input - it is always good to have some fresh ideas. Frank From tjreedy at udel.edu Thu Aug 27 03:26:31 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Aug 2009 03:26:31 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: kj wrote: > I think I understand the answers well enough. What I *really* > don't understand is why this particular "feature" of Python (i.e. > that functions defined within a class statement are forbidden from > "seeing" other identifiers defined within the class statement) is > generally considered to be perfectly OK. IMO it's a bizarre, > inexplicable blindspot (which, among other things, gives rise to > a certain worry about what other similar craziness lurks under > Python's image of rationality). I have never seen even a half-hearted > justification, from a language design point of view, for why this > particular "feature" is worth having. Maybe some day the BDFL will > deign to give one. I attempted to give an explanation in my previous post. From frank at chagford.com Thu Aug 27 03:31:01 2009 From: frank at chagford.com (Frank Millman) Date: Thu, 27 Aug 2009 09:31:01 +0200 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org Message-ID: <20090827073102.293C91DF2@ctb-mesg8.saix.net> Hi all I mentioned yesterday that I had a problem sending a message to the newsgroup via the Outlook Express news reader. Today I received an email from DaveA, which was sent to me via python-list at python.org. I tried simply replying to the email, to see if it behaved better than Outlook Express. I hit 'Reply to all', so it 'replied' to the sender and cc'ed to python-list at python.org. I have just checked in google-groups and my message does appear, in the correct thread, but not in its correct thread position. Is there a proper way to do this, or is it better to stick to a news reader like Outlook Express? Thanks Frank Millman P.S. I am sending this message via email to python-list at python.org - let's see what happens. From hendrik at microcorp.co.za Thu Aug 27 03:44:06 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 09:44:06 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a9595ca$0$300$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a9595ca$0$300$14726298@news.sunsite.dk> Message-ID: <200908270944.06268.hendrik@microcorp.co.za> On Wednesday 26 August 2009 22:06:01 Esben von Buchwald wrote: > > I don't really get it... > > I can see that I should put a t.after(...) around the function that does > the work, when calling it. That delays each call for the given period. I > just tried it out, the console keeps saying > ------------------------------------------------------------------------- > Traceback (most recent call last): > File "c:\resource\python25\python25.zip\sensorfw.py", line 499, in > data_cb > File "c:\resource\python25\python25.zip\sensorfw.py", line 160, in > custom_cb > File "e:\python\r3s_contextdata.py", line 79, in acc_filter > self.acc_callback() > File "e:\python\r3s_contextdata.py", line 85, in acc_callback > self.doCallback() > File "e:\python\r3s_contextdata.py", line 47, in doCallback > self.at.after(0.05,self.data_callback) > RuntimeError: Timer pending - cancel first > > ------------------------------------------------------------------------- > > It seems like i should cancel the current counting timer, when a new > call comes in - but how to determine when to cancel etc? Hmm - now I am really starting to fly by the seat of my pants - but it looks as if your problem is that your routine is basically being called faster than what it can do the processing. So what I would try is to define a global (you should really acquire a lock, but forget that for the moment) So lets call this thing running_calculation. Then you set this in the routine just before the after call, and reset it just before exiting the calculation routine, and if it is set when you get into the first routine, then you just exit, without doing the after. This should have the effect of skipping some calls, to make it all manageable. Then you should (hopefully) not have the duplication that it looks to me like you are now having. Bye the way, make the time short - like 1 - it could also be that the time is now so long before you start calculating, that you do not have a snowball's hope in hell to be finished before the next value comes in. - Hendrik From hendrik at microcorp.co.za Thu Aug 27 03:47:05 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 09:47:05 +0200 Subject: Python for professsional Windows GUI apps? In-Reply-To: References: Message-ID: <200908270947.05723.hendrik@microcorp.co.za> On Wednesday 26 August 2009 22:47:23 David C Ullrich wrote: > That's great. But do you know of anything I can use as a > visual form design tool in wxPython? Boa Constructor - Hendrik From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 04:07:46 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 10:07:46 +0200 Subject: Need help with Python scoping rules In-Reply-To: <2a7gm6-9h.ln1@satorlaser.homedns.org> References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> <2a7gm6-9h.ln1@satorlaser.homedns.org> Message-ID: <4a963ec1$0$20889$426a74cc@news.free.fr> Ulrich Eckhardt a ?crit : (snip) > Now, what actually causes problems is that 'fact_rec' is not universally > accessible until class 'Demo' is fully defined, but you need this in order > to fully define it. Here comes a drawback of the dynamic nature of Python, > that the declaration phase (compiling) is not separate from the execution. It is. You can manually compile a module, remove the source .py and still import (or execute) the compiled .pyc. The "problem" here is not with compilation, but with the fact that 'class' (and 'def') statements are *executable* statements. IOW, the class statement is executed when encountered, that is, usually (most class statements being top-level statements), when the module is first loaded. > I fully agree that this case is rather vexing to my (and obviously your) > biased brain. I wouldn't call this a bug before fully understanding why > e.g. you can not access a class before its definition is finished. Nor why it's a GoodThing(tm) for quite a lot of use case - while the OP's problem is in the splitting-hairs category - only a problem if yo?u insist in imposing your views on the language instead of learning how to use it. > Suggestion: someone mentioned that you should make the function a normal > function. (snip) Someone (Diez Roggisch IIRC) also mentionned a simple solution that mostly fulfills the OP's desires: use a nested function. From somebody at somewhere.com Thu Aug 27 04:10:46 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Thu, 27 Aug 2009 09:10:46 +0100 Subject: Need help with Python scoping rules References: <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: kj wrote: > Because, as I've explained elsewhere, it is not a method: it's a > "helper" function, meant to be called only once, within the class > statement itself. So why didn't you delete it after you were done with it? Class Demo(object): def fact(x): ... _classvar = fact(5) del fact() -- Stephen Fairchild From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 04:18:59 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 10:18:59 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> <2a7gm6-9h.ln1@satorlaser.homedns.org> Message-ID: <4a964162$0$7806$426a74cc@news.free.fr> kj a ?crit : (snip) > >> I fully agree that this case is rather vexing to my (and obviously your) >> biased brain. I wouldn't call this a bug before fully understanding why >> e.g. you can not access a class before its definition is finished. > > I understand this, what I don't understand is why do it this way. > I've been trying to understand this particular design point for > *literally* years. It's quitye simple: 'class' is an executable statement that creates a class object (yes, all this happens at runtime) and bind it in the current namespace. So until the class statement is executed, the class object doesn't exist and it's name is not bound. Now if you don't understand why it's a GoodThing(tm) that all this happens at runtime, have a look at metaclasses, how they are used in most major Python frameworks, and how this allows to vastly reduce the amount of needed boring and erreor-prone boilerplate code one cand find elsewhere. >> I think >> someone mentioned one or two PEPs, which are the design documents that >> explain Python including the rationale, I'd use that as a starting point. > > I'm reading PEP 227 now, suggested by Steven D'Aprano. In it I > find statements like the following alert: > > (Note: If a region is contained within a class definition, the > name bindings that occur in the class block are not visible to > enclosed functions.) > > I've seen this before, but never an explanation for why having this > restriction. You should re-read Carl Bank's answers more carefully then. > It's just one of life's mysteries. (Incidentally, > the fact that the author of PEP 227 felt it necessary to add that > parenthetical remark suggests that the expectation it warns against > is not so crazy after all.) It's not so crazy for someone coming from a more static language. Python's object model is indeed a bit peculiar, and it can take some times getting the big picture, but be sure it has been carefully designed, and is incredibly powerfull once you start understanding the whole thing. > But I'm still not done with PEP 227. Maybe I'll see the light by > the time I'm done. My 2 cents : learn about metaclasses, attributes lookup rules, and the descriptor protocol (and some practical applications of these features). Then you might decide that the few resulting restrictions are really worth the price. From david.westlund at hp.com Thu Aug 27 04:19:26 2009 From: david.westlund at hp.com (Westlund, David) Date: Thu, 27 Aug 2009 08:19:26 +0000 Subject: Python on HP-UX Message-ID: <2A1DB3DEDE43A7479FB4692CB732771A3CB9E9BF44@GVW1086EXB.americas.hpqcorp.net> Hi I'm trying to compile Python on an HP-UX v11.23 running on an Itanium. I have tried with both gcc and cc, and python versions 2.5.4, 2.6.2 as well as an SVN checkout. In all cases, alloca.h needs to be included. On most systems I'm guessing it is already included from stdlib.h, but not on HP-UX. The following code in the right header file solves that problem: #ifdef __hpux #include #endif My problem is that ctypes keeps seg faulting: ./python -v Lib/ctypes/test/runtests.py [...] # Python-2.5.4/Lib/encodings/ascii.pyc matches /Python-2.5.4/Lib/encodings/ascii.py import encodings.ascii # precompiled from Python-2.5.4/Lib/encodings/ascii.pyc ....Segmentation fault (core dumped) ./python -v ./Lib/ctypes/test/runtests.py [...] # Python-2.6.2/Lib/ctypes/test/test_numbers.pyc matches Python-2.6.2/Lib/ctypes/test/test_numbers.py import ctypes.test.test_numbers # precompiled from Python-2.6.2/Lib/ctypes/test/test_numbers.pyc ....Segmentation fault Have people managed to get a working ctypes installation on HP-UX? BR, David Westlund From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 04:35:51 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 10:35:51 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> <16b72319-8023-471c-ba40-8025aa6d462e@a26g2000yqn.googlegroups.com> <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71@j21g2000yqe.googlegroups.com> Message-ID: <4a964556$0$748$426a74cc@news.free.fr> kj a ?crit : > In <1bf83a7e-f9eb-46ff-84fe-cf42d9608e71 at j21g2000yqe.googlegroups.com> Carl Banks writes: > >> Yeah, it's a little surprising that you can't access class scope from >> a function, but that has nothing to do with encapsulation. > > It does: it thwarts encapsulation. The helper function in my > example is one that clearly rightfully belongs nowhere else than > the class itself, i.e. encapsulated within the class. I don't see what's wrong with having this function at the top-level. Sorry to have to say it this way, but IMHO you're border on cargo-cult thinking here. Python is an all-object language (ie : everything is an object, including functions, classes and modules), but it's by no mean 'pure-object', and module level functions are perfectly ok (and quite often the right thing). Now if you really want to "encapsulate" the function and the class together, you do have simple and and working solutions : using a nested recursive function (as explained by Diez), or nesting both the class and function in a factory function, ie: def Demo(): def fact(n): if n < 2: return 1 else: return n * fact(n - 1) class Demo(object): _classvar = fact(5) return Demo Demo = Demo() But anyway: this is really a WTF. Python's notion of encapsulation is very weak (by design), and you're really wasting time trying to fight the language instead of learning it. Just put that f... helper function at the top level (prefixing it's name with a '_' to mark it as implementation detail), and move on to something else !-) > It is only > this silly prohibition against recursive functions in a class > statement that forces one to put it outside the class statement. The "prohibition" only happens for recursive functions defined *and* called in the class statement. And once you get the big picture, it's certainly not "silly". From davea at ieee.org Thu Aug 27 04:36:34 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 27 Aug 2009 04:36:34 -0400 Subject: Move dictionary from instance to class level In-Reply-To: <20090827071016.E9A7F8A3D@ctb-mesg-1-1.saix.net> References: <20090827071016.E9A7F8A3D@ctb-mesg-1-1.saix.net> Message-ID: <4A964592.30100@ieee.org> Frank Millman wrote: > Dave Angel wrote: > > >> Any time I see multiple lists like that which have to stay in >> synch, I think code-smell. >> >> > > I don't think it is that bad, but I agree there is always room for > improvement. > > >> Why not let the EVT's be passed as strings, and avoid the whole mapping >> to integers and mapping back detail? And name the methods involved in a >> way that you can directly translate the string to the method name? >> >> > > There is some merit in this. At present I am writing the server and the > client, and copy/paste the list of constants, so they are guaranteed to stay > in sync. (Maybe I should import it instead - even more fool-proof [the fool > being me, of course]). > > However, it may happen that I want to open it up to 3rd-party clients in the > future, in which case I would have to publish some sort of API. It would > make more sense to identify the messages by a meaningful name rather than an > integer. > > And yes, I could then use 'getattr' to retrieve the corresponding method on > the server side. > > I've built such pairs of programs (not in Python), and studied the tradeoffs of various methods of coupling. Cut & Paste is probably the worst way to do it. Manual error is easy to creep in, where one copy is updated, and somebody neglects to update the other. It's especially bad if the item order matters, as it does for enums and for your xlist() example. Shared code works okay (have a module that both ends import). But it assumes both ends are built and ship and install on a consistent basis. Not too hard when it's a single product on a single machine. But if the two ends are on separate machines, especially separated by the Internet, you have to deal with version consistency problems. If there's a time shift as well (file format), then you're stuck at that level. Check the version, and either insist on exact match, or have a way to adapt to whichever end reports the earlier version. Make no mistake, there will be new versions, and you'll have to deal with it. Shared data is about the same, but can sometimes be more flexibly interpreted. It also can have the advantage of being able to have multiple simultaneous versions on the same machine. For the Internet case, picture a server that has to be able to serve several clients, each running different versions. And it's tougher for corruption (accidental or malicious) to do serious damage. I wouldn't want to do an import over the Internet live connection. Best is if the necessary data is passed between the two ends during initialization, and both ends know how to make that data describe the protocol they'll use. That can work as long as there's a notion of a session, and preferably if the session is two-way. In the case of file formats, it means you have this data in the header of the file. Sometimes for bandwidth reasons, you just want to transmit a version string, and not the entire table implied by that string. Just realize the increased risks involved. Probably the easiest way to stay in synch is if each message is self-describing. To me that screams "text" for the id's. It makes the message a bit larger, and you have to decide if it's worth it. The overhead could very well be lost in the noise of packeting, in any tcp/ip protocol. Note that all these have very gray boundaries. And that underneath it all, it's all just data. >> Barring that, make a single "structure" which lists the event >> names and >> method names in matched pairs, and derive whatever lists and >> dictionaries you actually need from that one structure. And that >> structure should be shared between client and server code, >> perhaps as a >> text file that they both parse. Or as a stream that's passed >> from one >> to the other during startup. That way, consistency between >> them can be >> regulated (with version string in the file, for example) >> >> > > I'm not sure how that would work. On the client side, I need to respond to a > 'button-clicked' event from the gui system by sending an EVT_BUTTON_CLICKED > message to the server. In other words it is hard-coded into the client > program. I don't know how that would work if I read in a list of > message-types at startup. > > > Show me a sample client event handler, and maybe I can suggest how to encode it. For example in wxPython, events are encoded with an event object. You could have the event send the object's type-string as an event ID. No lookup at all. And in fact, one event handler then might handle several of the events for a given widget, or even for multiple ones. I guess it's not that simple, since you frequently have to pass other information, such as the state of the Ctrl-key, or the mouse position on the screen, which is not directly encoded in the event type. >> DaveA >> >> > > Thanks for the input - it is always good to have some fresh ideas. > > Frank > > > From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 04:49:24 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 10:49:24 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: <7figv3F2m3p0dU1@mid.uni-berlin.de> Message-ID: <4a964883$0$18484$426a74cc@news.free.fr> kj a ?crit : > In "Martin P. Hellwig" writes: > >> kj wrote: >> >>> First, one of the goals of OO is encapsulation, not only at the >>> level of instances, but also at the level of classes. >> Who says? > > Python itself: it already offers a limited form of class encapsulation > (e.g. class variables). "class variables" - which FWIW include the "methods" - are just attributes of the class *object* (reminder : Python's classes and functions *are* objects too). Any name bound at the top level of the class statement scope becomes an attribute of the class object. IOW, this "limited form of class encapsulation" is just the ordinary "form of encapsulation" you'll get with Python objects. > It would be nice if it went all the way > and gave classes their own bona fide scope. (But I hasten to add: > I *still* don't understand the Python scope model, I think that what you should first understand are Python's execution and object models. >> Anyway, you could be right (I am not capable to judge it) and Python >> should change on this issue but from what I gathered, Pythons OO is >> inspired by the following: >> - Don't repeat yourself >> - Containing code into logical units makes it easier to understand and >> maintain. > > ...except, apparently, when that code is a recursive function, in > which case one's out of luck. I wrote quite a few recursive functions in Python and never had any problem. >>> Second, my example shows that Python puts some peculiar restrictions >>> on recursion. It's not a restriction on recursion, it's a scoping rule that apply to any other name. You can't access the class statement's scope from within a function, period. >>> Recursion! One of the central concepts in the theory >>> of functions! >> >> It is also one of the best ways to shoot yourself in the foot... > > If recursion is so evil, and Python so intent in saving us from > shooting ourselves in the foot, why does it allow recursion at all? Recursion is not evil, and Python doesn't try to prevent anyone from doing stupid things anyway. FWIW, do you know that you can add / replace / remove attributes (including methods) at runtime, both on a per-instance or per-class basis ? And even dynamically change the class of an object ?-) From jldunn2000 at googlemail.com Thu Aug 27 04:56:22 2009 From: jldunn2000 at googlemail.com (loial) Date: Thu, 27 Aug 2009 01:56:22 -0700 (PDT) Subject: Parse xml file Message-ID: Is there a quick way to retrieve data from an xml file in python 2.4, rather than read the whole file? From frank at chagford.com Thu Aug 27 04:56:47 2009 From: frank at chagford.com (Frank Millman) Date: Thu, 27 Aug 2009 10:56:47 +0200 Subject: Move dictionary from instance to class level In-Reply-To: <4A964592.30100@ieee.org> Message-ID: <20090827085652.E1339AE22@ctb-mesg-1-3.saix.net> Dave Angel wrote: > > Show me a sample client event handler, and maybe I can suggest how to > encode it. For example in wxPython, events are encoded with > an event > object. You could have the event send the object's type-string as an > event ID. No lookup at all. And in fact, one event handler > then might > handle several of the events for a given widget, or even for multiple > ones. I guess it's not that simple, since you frequently > have to pass > other information, such as the state of the Ctrl-key, or the mouse > position on the screen, which is not directly encoded in the > event type. That is definitely *not* what I want to do. I want to make the server as generic as possible, so that it can handle any type of client, hopefully even including a browser eventually. Therefore the server has no knowledge of wxPython event types. I have abstracted all the event types I am interested in (the list is fairly stable now). My protocol requires that the client maps a specific gui event type to a message identifier, and the server maps the message identifier to a method that handles the message. Hope that makes sense. Frank From davea at ieee.org Thu Aug 27 05:04:59 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 27 Aug 2009 05:04:59 -0400 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <20090827073102.293C91DF2@ctb-mesg8.saix.net> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> Message-ID: <4A964C3B.8090206@ieee.org> Frank Millman wrote: > Hi all > > I mentioned yesterday that I had a problem sending a message to the > newsgroup via the Outlook Express news reader. > > Today I received an email from DaveA, which was sent to me via > python-list at python.org. > > I tried simply replying to the email, to see if it behaved better than > Outlook Express. I hit 'Reply to all', so it 'replied' to the sender and > cc'ed to python-list at python.org. > > I have just checked in google-groups and my message does appear, in the > correct thread, but not in its correct thread position. > > Is there a proper way to do this, or is it better to stick to a news reader > like Outlook Express? > > Thanks > > Frank Millman > > P.S. I am sending this message via email to python-list at python.org - let's > see what happens. > > > I use Thunderbird, and treat the list as ordinary mail. I use reply-all, and it seems to do the right thing. Or at least if I'm breaking threads, nobody has pointed it out to me yet. I'm not sure how the list-server decides what thread a particular message belongs to. It's more than just the subject line, since when people change the subject, it stays in the same thread. I'm guessing it's somewhere in the boilerplate that's built by a normal mail program when it builds a reply message. And since I don't see threads this way, I wouldn't know if I broke things. I'd love to see an FAQ on how to handle these python.org mailing lists, with recommendations on settings to use both when you sign up for the list, and within various mail applications. For example, I see a single message containing typically around 10 attachments. I do the reply-all to one of these attachments, and it handles the message body okay, the To/CC fields okay, usually adds an extra RE: on the subject (so it becomes RE: RE: subject). But it defaults to the wrong From: address, so I have to change that by hand. I don't have that problem if I reply directly to a message, say from my in-box. The FAQ could also cover conventions and other techniques, such as whether to use html or plain-text for messages, how to use ** to mark a word as bold, top-posting suggestions.... DaveA From balamurugan.sekar at gmail.com Thu Aug 27 05:10:55 2009 From: balamurugan.sekar at gmail.com (Balamurugan S) Date: Thu, 27 Aug 2009 14:40:55 +0530 Subject: Parse xml file In-Reply-To: References: Message-ID: On Thu, Aug 27, 2009 at 2:26 PM, loial wrote: > Is there a quick way to retrieve data from an xml file in python 2.4, > rather than read the whole file? Universal Feed parser can do the job for you. This can be imported and used in your python programs. For more information, http://www.feedparser.org/ -- Regards, S.Balamurugan Free the code, Free the User From steve at REMOVE-THIS-cybersource.com.au Thu Aug 27 05:14:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 09:14:41 GMT Subject: Need help with Python scoping rules References: Message-ID: <02a63e7d$0$15633$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 08:38:29 +0200, Hendrik van Rooyen wrote: > On Wednesday 26 August 2009 17:14:27 kj wrote: > >> As I described at length in another reply, the function in question is >> not intended to be "callable outside the class". And yes, > > I think this might go to nub of your problem - It might help you to > think as follows: > > A Python class, even after it has been executed, does not really exist > except as a kind of template or pattern - it is mostly useless until an > instance of the class is made by calling it with whatever it needs to > set up the instance. And once you have an instance, you can do stuff > with that particular instance. Before that time, the class is mostly > just a promise of things to come. Oh my! I couldn't disagree more strongly! I think the above is totally incorrect. Classes and types are first class objects, you can treat them like anything else in Python. In fact, classes themselves are instances of type, so you can say: >>> class C(object): # must inherit from object ... pass ... >>> issubclass(C, object) True >>> isinstance(C, type) True Classes are themselves instances of their metaclass. By default, classes have a metaclass of type, but you can easily change that. Metaclass programming is advanced but very powerful. Because classes are themselves objects, you can (with a bit of metaclass jiggery-pokery) make them do all sorts of interesting things. For instance, huge amounts of effort are often put into creating a Singleton class, a class that has a single instance. Well, okay... but why not just use the class object itself, instead of an instance? There's already one of those, and you can't (easily) make a copy of it, and even if you did, it would be an independent class. Instead of this: singleton = SingletonClass(args) do_something_with(singleton) just do this: do_something_with(SingletonClass) Of course SingletonClass needs to be designed to work that way, which will probably need some metaclass magic. It would be interesting to see which requires less effort. When it comes to built-in classes (types), I often use the class object itself as an object. E.g. I might do something like this: def convert(seq): t = type(seq) # remember the original type result = process(seq) # always produces a list if t is list: return result # don't bother making a copy of the result elif t is str or t is unicode: empty = t() return empty.join(result) else: return t(result) # return the original type >> recursive functions in Python *are* restricted in ways that >> non-recursive functions aren't. The examples I've posted prove this >> point unambiguously. > > Yes and no - mostly no - your examples just illustrate the point I > tried to make above. Completely no. You may have missed the examples I've given, but the problems the Original Poster were having had nothing to do with recursion. > Pythons object model, and its classes, are different from what you are > used to. A bare class is mostly useless without an instance, which is > ultimately why accessing a function in a class from itself like you are > doing, without reference to an instance, does not work - the function > does not exist yet to a degree that it can be referenced. That is incorrect. What's going on is more subtle. >>> class Demo: ... def function(x): ... print "Calling function with argument %s" % x ... function(None) ... function(1) ... function(function) ... Calling function with argument None Calling function with argument 1 Calling function with argument >>> Demo -- Steven From davea at ieee.org Thu Aug 27 05:24:14 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 27 Aug 2009 05:24:14 -0400 Subject: Move dictionary from instance to class level In-Reply-To: <20090827085652.E1339AE22@ctb-mesg-1-3.saix.net> References: <20090827085652.E1339AE22@ctb-mesg-1-3.saix.net> Message-ID: <4A9650BE.9030909@ieee.org> Frank Millman wrote: > Dave Angel wrote: > >> Show me a sample client event handler, and maybe I can suggest how to >> encode it. For example in wxPython, events are encoded with >> an event >> object. You could have the event send the object's type-string as an >> event ID. No lookup at all. And in fact, one event handler >> then might >> handle several of the events for a given widget, or even for multiple >> ones. I guess it's not that simple, since you frequently >> have to pass >> other information, such as the state of the Ctrl-key, or the mouse >> position on the screen, which is not directly encoded in the >> event type. >> > > That is definitely *not* what I want to do. > > I want to make the server as generic as possible, so that it can handle any > type of client, hopefully even including a browser eventually. Therefore the > server has no knowledge of wxPython event types. > > I have abstracted all the event types I am interested in (the list is fairly > stable now). My protocol requires that the client maps a specific gui event > type to a message identifier, and the server maps the message identifier to > a method that handles the message. > > Hope that makes sense. > > Frank > > > Yes, it makes sense. Sorry for heading down that particular dead-end. But the more I think about it, the more likely I think it is that you'll be adding new message types, even if they're just variants of ones already defined. So it might behoove you to have a shared "data structure" that describes the whole message, not just equates a name to an integer. Or consider pickling. I don't know the tradeoffs, but the idea is that an object is constructed at the other end that has all the same data members as the object you had at this end. Perhaps with a flexible enough class definition, you could represent all or at least several of your messages with the same object. I am curious about your topology. You're sending events from the client (which presumably has a mouse and keyboard) to a server. But what does the server do with those? Does it have its own screen, or what? DaveA From steve at REMOVE-THIS-cybersource.com.au Thu Aug 27 05:31:41 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 09:31:41 GMT Subject: Need help with Python scoping rules References: <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: <02a6427a$0$15633$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 09:09:21 +0200, Hendrik van Rooyen wrote: > On Wednesday 26 August 2009 17:45:54 kj wrote: >> In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano > writes: > >> >Why are you defining a method without a self parameter? >> >> Because, as I've explained elsewhere, it is not a method: it's a >> "helper" function, meant to be called only once, within the class >> statement itself. > > If the sole purpose of the function is to be used to define what will > become a constant, why do you not just calculate the constant on your > calculator, or at the interactive prompt, and assign it to the > attribute, and be done with it? > > Why waste run time recalculating every time the programme is called? What you are calculating might actually be quite complicated to enter as a literal. You might have something like: class C(object): TABLE = [] for i in xrange(100): row = [] for j in xrange(100): row.append((i**3 + 2*i**2 - i*j + 7*j**2 + 9*i*j**2 - j)/3) TABLE.append(row) It's a little hard to type out C.TABLE as a literal. And even if you could, which would you rather see if you were debugging this class? The above, or: class C(object): TABLE = [ [0.0, 2.0, 8.6666666666666661, 20.0, 36.0, ... ], [1.0, 5.666666666666667, 21.0, 47.0, 83.666666666666671, ...], [5.333333333333333, 12.666666666666666, 36.666666666666664, ...], ... [... , 3143161.0, 3201497.6666666665, 3260433.0] ] For obvious reasons I haven't typed the whole thing out! And imagine trying to check it for typos! Clearly this is a made-up example, but the principle is sound. If Python can calculate values for you, why not let it do so? It is easier for you, easier to check that you've calculated them correctly, easier to debug and read, it makes the algorithm clearer (fewer "magic constants"). Yes, there is a run-time cost, but you only pay it once, when you import the module, and it's likely to be not that much more expensive than parsing the literals anyway. Of course, for something as big and complicated as the above table, I'd almost certainly put the code to calculate it in a function outside of the class, but that's a matter of style, and it will work to put it inside the class. -- Steven From tjreedy at udel.edu Thu Aug 27 05:47:50 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Aug 2009 05:47:50 -0400 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <4A964C3B.8090206@ieee.org> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: Dave Angel wrote: > Frank Millman wrote: > I use Thunderbird, and treat the list as ordinary mail. I use > reply-all, and it seems to do the right thing. Or at least if I'm > breaking threads, nobody has pointed it out to me yet. reply-all may send duplicate messages to the author. Not sure of this list. I use Thunderbird and access python-list as a newsgroup via news.gmane.org as gmane.comp.python.general. About 200 other python mailing lists are accessible as g.c.p.xxx. The first time one posts to a particular mailint list, the post is held until one replies to a email sent to the 'from:' address. This cuts spam tremendously. Otherwise, no signup seems to be needed. tjr From catalinfest at gmail.com Thu Aug 27 06:20:31 2009 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Thu, 27 Aug 2009 03:20:31 -0700 (PDT) Subject: About diagram and python Message-ID: <030422b7-a4f8-4ea6-8708-4486da4cf595@w6g2000yqw.googlegroups.com> Hello! I see on my Diagram Editor software this : File -> Export... -> (on Export option is : PyDia Code Generation ... .py) What python is in this file ? How help me with python code ? Thank you ! From frank at chagford.com Thu Aug 27 06:21:10 2009 From: frank at chagford.com (Frank Millman) Date: Thu, 27 Aug 2009 12:21:10 +0200 Subject: Move dictionary from instance to class level In-Reply-To: <4A9650BE.9030909@ieee.org> Message-ID: <20090827102111.ABC3B1F93@ctb-mesg4.saix.net> Dave Angel wrote: > > Frank Millman wrote: > > > > That is definitely *not* what I want to do. > > > > I want to make the server as generic as possible, so that > it can handle any > > type of client, hopefully even including a browser > eventually. Therefore the > > server has no knowledge of wxPython event types. > > > > I have abstracted all the event types I am interested in > (the list is fairly > > stable now). My protocol requires that the client maps a > specific gui event > > type to a message identifier, and the server maps the > message identifier to > > a method that handles the message. > > > > Hope that makes sense. > > > > Frank > > > > > > > Yes, it makes sense. Sorry for heading down that particular > dead-end. > But the more I think about it, the more likely I think it is > that you'll > be adding new message types, even if they're just variants of ones > already defined. So it might behoove you to have a shared "data > structure" that describes the whole message, not just equates > a name to > an integer. > > Or consider pickling. I don't know the tradeoffs, but the > idea is that > an object is constructed at the other end that has all the same data > members as the object you had at this end. Perhaps with a flexible > enough class definition, you could represent all or at least > several of > your messages with the same object. > > I am curious about your topology. You're sending events from > the client > (which presumably has a mouse and keyboard) to a server. But > what does > the server do with those? Does it have its own screen, or what? > I'll try to explain. I am writing a fairly standard business/accounting application. (I am now adding Business Process Management to it, which is complicating matters, but that is another story.) Most of the gui stuff is basic forms processing - screens with static data, text fields for display and input of data, and buttons for signifying certain actions to be taken. My original attempt had both the gui and the business logic running on the client, with a connection to a database running on a server. It worked, but then I realised it was very insecure - it would be easy to hack the python code, bypass the business logic, and allow any update to the database. So my second attempt took all the business logic out of the client and put it onto the server. To execute a form, the server builds a form definition by creating objects to represent each of the widgets, creates a list of the components with sufficient information for the client to render them , then sends a json'd copy of the list to the client, which interprets it and displays the required form. The client informs the server of each event, and the server handles the event in much the same way as it did before when the business logic was on the client. For example, clicking a button triggers a response which could involve updating the database, displaying another window with additional data, etc, etc. Previously there would have been a method on the client designed to handle the response, and the method would be added to the button constructor so that it would be called when the button was clicked. Now the method is on the server, and is stored as an attribute of the button object on the server. When the user clicks the button, the message is passed up to the server (each widget has its own id, which is part of the message), the server is notified that the button was clicked, and it calls the associated method. There is a lot more to it than that, but hopefully that will give you an idea. If I ever get this to a workable state (it is taking far longer than I anticipated) I will release it as open source, and will then welcome as much feedback as possible. Frank From contact at xavierho.com Thu Aug 27 06:26:19 2009 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 Aug 2009 20:26:19 +1000 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <4A964C3B.8090206@ieee.org> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: <2d56febf0908270326p58adda54w306eb823710bb952@mail.gmail.com> On Thu, Aug 27, 2009 at 7:04 PM, Dave Angel wrote: > I'm not sure how the list-server decides what thread a particular message > belongs to. It's more than just the subject line, since when people change > the subject, it stays in the same thread. > I'm just using gmail because it saves me the trouble of reconfiguring the mail server every time I use a new computer (which I do at uni quite a lot). When someone changes the Subject with (was: XXX), it opens as a new "thread" on gmail. also, when someone puts "Re:" in the subject it also puts it on a new thread. The magical thing about gmail is that it seems to ingnore the first "Re:" on the subject line, and make them the same thread. I rarely have threading issues, but occasionally I do see "Re:" messages in a separate place, maybe once a month. I'd love to see an FAQ on how to handle these python.org mailing lists, with > recommendations on settings to use both when you sign up for the list, and > within various mail applications. Google found me these: http://www.gnu.org/software/mailman/faq.html http://www.gnu.org/software/mailman/docs.html Maybe they're helpful, since that's what the python-list uses. I've only scanned for a bit and it seems comprehensive. > For example, I see a single message containing typically around 10 > attachments. I do the reply-all to one of these attachments, and it handles > the message body okay, the To/CC fields okay, What do you mean 10 attachments? O_o. I know some people like to attach a company logo in their signature. (The Aussie DLF list people do that heaps. Although some people post a hand-written sig in the attachment ... I'm not sure how smart that is, but I've seen it done.) Where are you getting these "attachments"? I haven't tried reply-all yet. May give that a try next time and see what pops up in the To: address. > usually adds an extra RE: on the subject (so it becomes RE: RE: subject). Gmail doesn't do that. Yay! (Re: is dumb anyway, and you can't prepend Re: forever. Fwd: is reasonable.) > But it defaults to the wrong From: address, so I have to change that by > hand. I don't have that problem if I reply directly to a message, say from > my in-box. Weird. I have a different problem: the "To:" Address is usually the sender I'm replying to. It's really annoying, because I always have to hand-change the To: address to python-list. I've sent two messages onto the list mentioning about adding a "Reply-to" attribute by the mailing list server, which would fix this problem. To-date everyone has seemed to ignore me. =/ > The FAQ could also cover conventions and other techniques, such as whether > to use html or plain-text for messages, how to use ** to mark a word as > bold, top-posting suggestions.... I didn't know ** marks bold. Does __ mark underline? Those are cool things I never hear about. Thanks! On another tangent, I only found out the Python Wiki on the official site today (http://wiki.python.org/moin/) Does anyone actually use it, and what for? - Kind regards, Ching-Yun "Xavier" Ho, Technical Artist Contact Information Mobile: (+61) 04 3335 4748 Skype ID: SpaXe85 Email: contact at xavierho.com Website: http://xavierho.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Thu Aug 27 06:46:57 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 10:46:57 GMT Subject: About diagram and python References: <030422b7-a4f8-4ea6-8708-4486da4cf595@w6g2000yqw.googlegroups.com> Message-ID: <02a6541d$0$15633$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 03:20:31 -0700, catalinfest at gmail.com wrote: > Hello! > I see on my Diagram Editor software this : File -> Export... -> (on > Export option is : PyDia Code Generation ... .py) > What python is in this file ? Why don't you look for yourself? Just open the file in a text editor and read it. -- Steven From greg at cosc.canterbury.ac.nz Thu Aug 27 06:50:41 2009 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 27 Aug 2009 22:50:41 +1200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <7fn6n4F2m1582U1@mid.individual.net> kj wrote: > No, the fact() function here represents an internal "helper" > function. It is meant to be called only once to help initialize > a class variable that would be inconvenient to initialize otherwise; > this helper function is not meant to be called from outside the > class statement. That, to me, is an excellent indication that the function does *not* belong inside the class! The only things that belong inside the class are things that users of the class will need to use, or that instances of the class will need to do their job. Your helper function belongs outside the class, in the module where the class is defined. -- Greg From IDOL at il.ibm.com Thu Aug 27 06:57:49 2009 From: IDOL at il.ibm.com (Ido Levy) Date: Thu, 27 Aug 2009 13:57:49 +0300 Subject: pygtk - What is the best way to change the mouse pointer In-Reply-To: <4A959521.8020505@mrabarnett.plus.com> References: <4A959521.8020505@mrabarnett.plus.com> Message-ID: > From: > > MRAB > > To: > > python-list at python.org > > Date: > > 26/08/2009 11:04 PM > > Subject: > > Re: pygtk - What is the best way to change the mouse pointer > > Ido Levy wrote: > > Hello All, > > > > I am writing a dialog which one of its widget is a gtk.ComboBoxEntry ( > > let's assume widget in the example below is its instance ) > > When the user select one of the values from the gtk.ComboBoxEntry I need > > to run some calculations that takes a few seconds. > > In order to reflect calculation time to the user I want to switch the > > mouse pointer to an hour glass and back to arrow what it finish the > > calculation. > > > > I use the following code but it doesn't seems to work in a deterministic > > way. From time to time it skips the last line and keep the mouse pointer > > as an hour glass. > > > > watch = gtk.gdk.Cursor(gtk.gdk.WATCH) > > widget.window.set_cursor(watch) > > > > calculation code > > > > widget.window.set_cursor(None) > > > > I would appreciate your advice on the right way to implement this. > > > Could the calculation code be raising an exception? Try adding some > logging to see whether the last lien is actually being called. You could > also use a try...finally... block to ensure that the last line is > called: > > watch = gtk.gdk.Cursor(gtk.gdk.WATCH) > widget.window.set_cursor(watch) > try: > calculation code > finally: > widget.window.set_cursor(None) > Thank you for your input. I used logging and it seems that the last line is called. I also used try...finally... block but it didn't solve the issue. Then I have noticed that the line before the last one is widget.connect() I insert time.sleep() in between the lines and it seems to solve the issue. I assume it's not suppose to work this way but it can be considered as a workaround -------------- next part -------------- An HTML attachment was scrubbed... URL: From graham.dumpleton at gmail.com Thu Aug 27 07:01:05 2009 From: graham.dumpleton at gmail.com (Graham Dumpleton) Date: Thu, 27 Aug 2009 04:01:05 -0700 (PDT) Subject: Python on the Web References: <4a94ef42$0$27774$426a74cc@news.free.fr> <835a57b2-9a08-4f10-b2d4-78c96f22f3ee@n11g2000yqb.googlegroups.com> Message-ID: <77a1add8-3b36-4b69-b21e-a7a496c30205@l35g2000pra.googlegroups.com> On Aug 27, 1:02?pm, Phil wrote: > Thanks a lot for another response. I've never posted in groups like > this before but the results are amazing. > > I will definitely consider trying mod_wsgi when I get a chance. I like > the approach taken with it. It is unfortunate that I completely missed > all Apache related material because I was using lighttpd. Is there no > mod_wsgi for lighttpd? I guess I could always just Google that myself. There is no mod_wsgi for lighttpd and suggest there never will be. WSGI doesn't lend itself to working on top of an event driven system. Someone did get a mod_wsgi going on nginx, which is also event driven, but it has limitations due to possibility of blocking other traffic to web server. See: http://blog.dscpl.com.au/2009/05/blocking-requests-and-nginx-version-of.html Graham From jeanmichel at sequans.com Thu Aug 27 07:17:32 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 27 Aug 2009 13:17:32 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A966B4C.7030307@sequans.com> Ulrich Eckhardt wrote: > Ulrich Eckhardt wrote: > >> Jean-Michel Pichavant wrote: >> >>> class Color: >>> def __init__(self, r, g,b): >>> pass >>> BLACK = Color(0,0,0) >>> >>> It make sens from a design point of view to put BLACK in the Color >>> namespace. But I don't think it's possible with python. >>> >> class Color: >> ... >> >> setattrib(Color, "BLACK", Color(0,0,0)) >> > > Apart from it being "setattr" and not "setattrib", a simple > > Color.BLACK = Color(0,0,0) > > Obviously ... I'll remember that. JM From jeanmichel at sequans.com Thu Aug 27 07:45:00 2009 From: jeanmichel at sequans.com (Jean-Michel Pichavant) Date: Thu, 27 Aug 2009 13:45:00 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A9671BC.7030600@sequans.com> kj wrote: > I think I understand the answers well enough. What I *really* > don't understand is why this particular "feature" of Python (i.e. > that functions defined within a class statement are forbidden from > "seeing" other identifiers defined within the class statement) is > generally considered to be perfectly OK. IMO it's a bizarre, > inexplicable blindspot (which, among other things, gives rise to > a certain worry about what other similar craziness lurks under > Python's image of rationality). I have never seen even a half-hearted > justification, from a language design point of view, for why this > particular "feature" is worth having. Maybe some day the BDFL will > deign to give one. > > kynn > I think I got your point. I guess many people may not be receptive to your question, cause guess what, we're all python fans :o) in foo.py: a = 5 b = a # works fine class A: c = 5 d = c # broken d = A.c # broken either def foo(self): e = 5 f = e #works fine We should all acknowledge that any newcomer to python will not expect such behavior. There are plenty of good answers to that thread explaining why the fact that classes are not scopes is much better. Still this design fails at one point : insight. It may be solved by creating the class upon the "class" statement. If the class A object is created, then c is added as a property of that object, there's no problem accession one object property with A.c. JM From manu3d at gmail.com Thu Aug 27 08:03:07 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 27 Aug 2009 05:03:07 -0700 (PDT) Subject: List iterator thread safety References: Message-ID: <14e1469e-bcfe-4922-b135-3f0bd7e17a42@r42g2000yqj.googlegroups.com> On Aug 27, 2:01?am, a... at pythoncraft.com (Aahz) wrote: > Well, I'm not sure about exceptions, but you almost certainly won't get > the results you want. What I'd like in this context is to iterate through the items in the list without processing the same item twice and without skipping item that are in front of the current iterator position. Somehow I can't quite prove to myself if this is possible or not over multiple threads. I.e. a dictionary will throw an exception about the object changing size while iterating through it. A list doesn't, hence the question. Manu From no.email at please.post Thu Aug 27 08:09:44 2009 From: no.email at please.post (kj) Date: Thu, 27 Aug 2009 12:09:44 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: In Jean-Michel Pichavant writes: >kj wrote: >> I think I understand the answers well enough. What I *really* >> don't understand is why this particular "feature" of Python (i.e. >> that functions defined within a class statement are forbidden from >> "seeing" other identifiers defined within the class statement) is >> generally considered to be perfectly OK. IMO it's a bizarre, >> inexplicable blindspot (which, among other things, gives rise to >> a certain worry about what other similar craziness lurks under >> Python's image of rationality). I have never seen even a half-hearted >> justification, from a language design point of view, for why this >> particular "feature" is worth having. Maybe some day the BDFL will >> deign to give one. >> >> kynn >> >I think I got your point. >I guess many people may not be receptive to your question, cause guess >what, we're all python fans :o) >in foo.py: >a = 5 >b = a # works fine >class A: > c = 5 > d = c # broken > d = A.c # broken either > > def foo(self): > e = 5 > f = e #works fine >We should all acknowledge that any newcomer to python will not expect >such behavior. There are plenty of good answers to that thread >explaining why the fact that classes are not scopes is much better. >Still this design fails at one point : insight. >It may be solved by creating the class upon the "class" statement. If >the class A object is created, then c is added as a property of that >object, there's no problem accession one object property with A.c. Thanks! I was beginning to think I'd gone crazy. kynn From jvpic at free.fr Thu Aug 27 08:13:21 2009 From: jvpic at free.fr (jvpic) Date: Thu, 27 Aug 2009 14:13:21 +0200 Subject: Learning Python advanced features Message-ID: <4a967864$0$15193$426a74cc@news.free.fr> Hi, Learning Python, I understand the mechanism of : closure, __new__, descriptors, decorators and __metaclass__, but I interrogate myself on the interest of those technics ? May somebody explain me the interest ? Many thanks ! Jackes Bihan From steve at REMOVE-THIS-cybersource.com.au Thu Aug 27 08:17:15 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 27 Aug 2009 12:17:15 GMT Subject: Need help with Python scoping rules References: Message-ID: <02a66947$0$15633$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 13:45:00 +0200, Jean-Michel Pichavant wrote: > in foo.py: > > a = 5 > b = a # works fine > > class A: > c = 5 > d = c # broken Incorrect. That works fine. >>> class A: ... c = 5 ... d = c # not actually broken ... >>> A.c 5 >>> A.d 5 The class is a scope, and inside the class scope, you can access local names. What you can't do is access the class scope from inside nested functions. -- Steven From no.email at please.post Thu Aug 27 08:20:13 2009 From: no.email at please.post (kj) Date: Thu, 27 Aug 2009 12:20:13 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: In Jean-Michel Pichavant writes: >in foo.py: >a = 5 >b = a # works fine > > def foo(self): > e = 5 > f = e #works fine >It may be solved by creating the class upon the "class" statement. If >the class A object is created, then c is added as a property of that >object, there's no problem accession one object property with A.c. I thought one could implement something like class A: c = 5 d = __thisclass__.c But apparently this is a *huge* deal. I'm not sure if the reason it is a huge deal is that it is technically difficult to implement, or that there is an implicit "lie" in having something (__thisclass__) standing for something else that doesn't yet exist (and the potential errors that may arise from this "lie" in sufficiently unfortunate code). Or maybe something else beyond my noobish ken altogether. kynn From no.email at please.post Thu Aug 27 08:21:38 2009 From: no.email at please.post (kj) Date: Thu, 27 Aug 2009 12:21:38 +0000 (UTC) Subject: Need help with Python scoping rules References: <02a54597$0$20629$c3e8da3@news.astraweb.com> <02a6427a$0$15633$c3e8da3@news.astraweb.com> Message-ID: In <02a6427a$0$15633$c3e8da3 at news.astraweb.com> Steven D'Aprano writes: >On Thu, 27 Aug 2009 09:09:21 +0200, Hendrik van Rooyen wrote: >> On Wednesday 26 August 2009 17:45:54 kj wrote: >>> In <02a54597$0$20629$c3e8da3 at news.astraweb.com> Steven D'Aprano >> writes: >> >>> >Why are you defining a method without a self parameter? >>> >>> Because, as I've explained elsewhere, it is not a method: it's a >>> "helper" function, meant to be called only once, within the class >>> statement itself. >> >> If the sole purpose of the function is to be used to define what will >> become a constant, why do you not just calculate the constant on your >> calculator, or at the interactive prompt, and assign it to the >> attribute, and be done with it? >> >> Why waste run time recalculating every time the programme is called? >What you are calculating might actually be quite complicated to enter as >a literal. Thank you! kynn From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 08:25:36 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 14:25:36 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4a967b2f$0$19301$426a74cc@news.free.fr> Jean-Michel Pichavant a ?crit : > kj wrote: >> I think I understand the answers well enough. What I *really* >> don't understand is why this particular "feature" of Python (i.e. >> that functions defined within a class statement are forbidden from >> "seeing" other identifiers defined within the class statement) is >> generally considered to be perfectly OK. IMO it's a bizarre, >> inexplicable blindspot (which, among other things, gives rise to >> a certain worry about what other similar craziness lurks under >> Python's image of rationality). I have never seen even a half-hearted >> justification, from a language design point of view, for why this >> particular "feature" is worth having. Maybe some day the BDFL will >> deign to give one. >> >> kynn >> > > I think I got your point. > I guess many people may not be receptive to your question, cause guess > what, we're all python fans :o) > > in foo.py: > > a = 5 > b = a # works fine > > class A: > c = 5 > d = c # broken Err... Did you actually tried this ? >>> class A: ... c = 5 ... d = c ... >>> A.c 5 >>> A.d 5 >>> > d = A.c # broken either Not "broken" : the class doesn't yet exists, nor is it bound to global name 'A'. FWIW, *this* works (for some definitions of 'works') juts fine: >>> class Foo(object): ... c = 42 ... >>> A = Foo() >>> class A(object): ... d = A.c ... >>> A.d 42 > > We should all acknowledge that any newcomer to python will not expect > such behavior. Any newcomer to any language should aknowledge that her expectations based on previous experience with any other language should be kept aside or just plain abandoned, and start by learning the new language. The only thing one is entitled to expect when learning a new language is that the language's implementation follows the language specs. > There are plenty of good answers to that thread > explaining why the fact that classes are not scopes is much better. > Still this design fails at one point : insight. Oh, really ? > It may be solved by creating the class upon the "class" statement. If > the class A object is created, then c is added as a property of that > object, there's no problem accession one object property with A.c. Please, write a pep... From robin at reportlab.com Thu Aug 27 08:26:47 2009 From: robin at reportlab.com (Robin Becker) Date: Thu, 27 Aug 2009 13:26:47 +0100 Subject: ubuntu dist-packages In-Reply-To: References: Message-ID: <4A967B87.9040100@chamonix.reportlab.co.uk> Florian Diesch wrote: ......... > >>From /usr/lib/python2.6/site.py: > > ,---- > | For Debian and derivatives, this sys.path is augmented with directories > | for packages distributed within the distribution. Local addons go > | into /usr/local/lib/python/dist-packages, Debian addons > | install into /usr/{lib,share}/python/dist-packages. > | /usr/lib/python/site-packages is not used. > `---- the above is not present in my windows documentation (or indeed site.py) at all so it seems they just decided to change the name. Anyone trying to debug why their distutils or setuptools or whichever python packager is going wrong will have yet another detail to remember. In addition, as any one who has done such trivial changes will already know, they forgot to do it globally eg my 0.4.1.0 version of the "Debian Python Policy" document explicitly mentions site-packages. -- Robin Becker From robin at reportlab.com Thu Aug 27 08:26:47 2009 From: robin at reportlab.com (Robin Becker) Date: Thu, 27 Aug 2009 13:26:47 +0100 Subject: ubuntu dist-packages In-Reply-To: References: Message-ID: <4A967B87.9040100@chamonix.reportlab.co.uk> Florian Diesch wrote: ......... > >>From /usr/lib/python2.6/site.py: > > ,---- > | For Debian and derivatives, this sys.path is augmented with directories > | for packages distributed within the distribution. Local addons go > | into /usr/local/lib/python/dist-packages, Debian addons > | install into /usr/{lib,share}/python/dist-packages. > | /usr/lib/python/site-packages is not used. > `---- the above is not present in my windows documentation (or indeed site.py) at all so it seems they just decided to change the name. Anyone trying to debug why their distutils or setuptools or whichever python packager is going wrong will have yet another detail to remember. In addition, as any one who has done such trivial changes will already know, they forgot to do it globally eg my 0.4.1.0 version of the "Debian Python Policy" document explicitly mentions site-packages. -- Robin Becker From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 08:28:24 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 14:28:24 +0200 Subject: Learning Python advanced features In-Reply-To: <4a967864$0$15193$426a74cc@news.free.fr> References: <4a967864$0$15193$426a74cc@news.free.fr> Message-ID: <4a967bd6$0$19301$426a74cc@news.free.fr> jvpic a ?crit : > Hi, > > Learning Python, I understand the mechanism of : closure, __new__, > descriptors, decorators and __metaclass__, but I interrogate myself on > the interest of those technics ? > > May somebody explain me the interest ? Didn't like my answers on f.c.l.py ?-) From luismgz at gmail.com Thu Aug 27 08:31:30 2009 From: luismgz at gmail.com (Neuruss) Date: Thu, 27 Aug 2009 05:31:30 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <7f519c34-2d6e-4fff-9489-dae43c6b2df1@r42g2000yqj.googlegroups.com> Message-ID: <6b961048-782a-428c-9c0a-4fb17e87b57f@s13g2000yql.googlegroups.com> On 26 ago, 05:29, erikj wrote: > Hi, > > You could have a look at Camelot, to see if it fits > your needs :http://www.conceptive.be/projects/camelot/ > > it was developed with cross platform business apps in > mind. ?when developing Camelot, we tried to build it using > wxWidgets first (because of the licensing at that time), > but it turned out that developing with QT proved to be > much more straightforward. ?QT is documented very well > and you seldom encounter 'strange' issues that cost hours > of time to pinpoint and fix. > > the datagrid was developed to be able to handle millions > of database records without glitches and is flexible thanks > to QT's model-view-delegate framework. > > we do print barcodes with this app (even directly to > zebra printers) > > if you have questions regarding Camelot, please feel free > to post on our mailing list :http://groups.google.com/group/project-camelot > > Regards, > > Erik > > On Aug 24, 2:08?pm, Gilles Ganault wrote: > > > > > Hello > > > ? ? ? ? I was wondering if some people in this ng use Python and someGUI > > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > > applications, and if yes, what it's like, the pros and cons, etc. > > > I'm especially concerned about the lack of controls, the lack of > > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > > linked to how to update users' PC remotely when I build a new version > > using eg. Py2exe. > > > I need controls for business apps like access to databases, good data > > grid, printing reports (with or without barcodes), etc. > > > Thank you. Looks interesting, but I wonder if I can use Camelot without its ORM. I feel that ORMs make easy things easier, but complex things much harder... Can I use it with plain old sql? Luis From __peter__ at web.de Thu Aug 27 08:41:07 2009 From: __peter__ at web.de (Peter Otten) Date: Thu, 27 Aug 2009 14:41:07 +0200 Subject: List iterator thread safety References: <14e1469e-bcfe-4922-b135-3f0bd7e17a42@r42g2000yqj.googlegroups.com> Message-ID: Emanuele D'Arrigo wrote: > On Aug 27, 2:01 am, a... at pythoncraft.com (Aahz) wrote: >> Well, I'm not sure about exceptions, but you almost certainly won't get >> the results you want. > > What I'd like in this context is to iterate through the items in the > list without processing the same item twice and without skipping item > that are in front of the current iterator position. Somehow I can't > quite prove to myself if this is possible or not over multiple > threads. I.e. a dictionary will throw an exception about the object > changing size while iterating through it. A list doesn't, hence the > question. This is not even possible in a single thread: >>> items = [1, 2, 3] >>> for i in items: ... print i ... if 1 in items: items.remove(1) ... 1 3 Basically a list iterator is just a list reference and an index into that list. No effort is made to keep track of added or removed items. Peter From dmhouse at gmail.com Thu Aug 27 08:41:08 2009 From: dmhouse at gmail.com (David House) Date: Thu, 27 Aug 2009 13:41:08 +0100 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: 2009/8/27 Terry Reedy : > reply-all may send duplicate messages to the author. Not sure of this list. I'm fairly sure Mailman deals with that. -- -David From darcy at druid.net Thu Aug 27 08:55:40 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Thu, 27 Aug 2009 08:55:40 -0400 Subject: Need help with Python scoping rules In-Reply-To: References: <02a54597$0$20629$c3e8da3@news.astraweb.com> Message-ID: <20090827085540.de12c38d.darcy@druid.net> On Thu, 27 Aug 2009 09:10:46 +0100 Stephen Fairchild wrote: > So why didn't you delete it after you were done with it? > > Class Demo(object): That should be "class". > _classvar = fact(5) > del fact() I suppose you mean "del fact". -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From contact at xavierho.com Thu Aug 27 08:59:51 2009 From: contact at xavierho.com (Xavier Ho) Date: Thu, 27 Aug 2009 22:59:51 +1000 Subject: List iterator thread safety In-Reply-To: References: Message-ID: <2d56febf0908270559h58809a2na75e382c6638e7ac@mail.gmail.com> On Tue, Aug 25, 2009 at 3:43 AM, Emanuele D'Arrigo wrote: > Let's say I have a list accessed by two threads, one removing list > items via "del myList[index]" statement the other iterating through > the list and printing out the items via "for item in myList:" > statement. I tried something similar to that before. Gave me an error. I *think* it was in compile-time, too, but I might be wrong. The message was something like that the list size cannot be changed. > Am I right to say this -won't- generate exceptions because > the list iterator is not concerned with the list changing in size > under its nose? It kind of concerns about the size, I think. If it just checked the "next" item, that would have been so awesome. > Or are there pitfalls I should be aware of? The pitfall is that I don't think it will work at all. At least I haven't succeeded in doing this in the past. If you make it work, be sure to share your thoughts =] Good luck, -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From manu3d at gmail.com Thu Aug 27 09:16:14 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 27 Aug 2009 06:16:14 -0700 (PDT) Subject: Does Class implements Interface? Message-ID: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> Greetings everybody, let's say I have a Class C and I'd like to verify if it implements Interface I. If I is available to me as a class object I can use issubclass(C, I) and I can at least verify that I is a superclass of C. There are a couple of issues with this approach however: 1) C might override not just I's methods code but also I's methods signatures, effectively changing the interface. 2) What if I is -not- available to me as the superclass of C but as a description of the interface, i.e. as an IDL(*) file? Are there resources such as tools, recipes, documents or strategies that could help me deal with these issues? I've already looked into the ABC module and the zope.interface. I'm just fishing for more things to look at. Manu (*) http://en.wikipedia.org/wiki/Interface_description_language From bruno.42.desthuilliers at websiteburo.invalid Thu Aug 27 09:21:33 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Thu, 27 Aug 2009 15:21:33 +0200 Subject: Python on the Web In-Reply-To: References: <4a94ef42$0$27774$426a74cc@news.free.fr> Message-ID: <4a96884b$0$22855$426a74cc@news.free.fr> Phil a ?crit : (snip) > However, 99.9% of the discussion I see with Python on > the web is around FCGI. May I suggest you spend some time reading django-users and django-dev on google groups ? (and that's only *one* of the way-too-many Python web frameworks). From pavlovevidence at gmail.com Thu Aug 27 09:26:04 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 27 Aug 2009 06:26:04 -0700 (PDT) Subject: List iterator thread safety References: <14e1469e-bcfe-4922-b135-3f0bd7e17a42@r42g2000yqj.googlegroups.com> Message-ID: On Aug 27, 5:03?am, "Emanuele D'Arrigo" wrote: > On Aug 27, 2:01?am, a... at pythoncraft.com (Aahz) wrote: > > > Well, I'm not sure about exceptions, but you almost certainly won't get > > the results you want. > > What I'd like in this context is to iterate through the items in the > list without processing the same item twice and without skipping item > that are in front of the current iterator position. Somehow I can't > quite prove to myself if this is possible or not over multiple > threads. I.e. a dictionary will throw an exception about the object > changing size while iterating through it. A list doesn't, hence the > question. Deleting items from a list while iterating over it is a bad idea, exceptions or not. Hmm, this sounds like something someone might do for a game. You have a list of objects, and in a given time step you have to iterate through the list and update each object. Problem is, one of the enemies is kill before you get to it, so you would like to remove the object from the list while iterating. Not an easy problem. For this simple appeoach, I would suggest writing a custom container (with an underlying list) with state to keep track of the current iterating position. Whenever an item is removed the index is modified (so as to prevent skipping objects), and because you are keeping track of the index yourself there is an iterator that might throw an exception. With threads, you would need to use a Condition or something to sychronize access to the object. Carl Banks From deets at nospam.web.de Thu Aug 27 09:27:16 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 27 Aug 2009 15:27:16 +0200 Subject: ubuntu dist-packages References: <7fki3lF2kirnkU1@mid.uni-berlin.de> <71f5986e-6aae-46b0-8325-d67051c60a30@a13g2000yqc.googlegroups.com> Message-ID: <7fnftkF2m6bvdU1@mid.uni-berlin.de> Paul Boddie wrote: > On 26 Aug, 17:48, Jorgen Grahn wrote: >> >> Well, if you are thinking about Debian Linux, it's not as much >> "ripping out" as "splitting into a separate package with a non-obvious >> name". Annoying at times, but hardly an atrocity. > > Indeed. Having seen two packages today which insisted on setuptools, > neither really needing it, and with one actively trying to download > stuff from the Internet (fifteen seconds warning - how generous!) when > running setup.py, it seems to me that it isn't the distribution > packagers who need to be re-thinking how they install Python software. > > Generally, distributions have to manage huge amounts of software and > uphold reasonable policies without creating unnecessary maintenance. > Sadly, until very recently (and I'm still not entirely sure if there's > really been an attitude change) the Pythonic packaging brigade has > refused to even consider the needs of one of the biggest groups of > consumers of the upstream code. Consequently, distributions will > always devise different ways of storing installed Python software, > documentation and resources, mostly because the Pythonic tools have > been deficient, particularly in the management of the latter > categories. You mean it's the problem of the python packaging that it can't deal with RPMs, debs, tgzs, OSX bundles, MSIs and ? Multiplied by the various packaging philosophies the respective distros build based on these have? I'm a Python-developer. I develop libraries and tools for Python, and want others to be able to install these - as I want to install things *other* python developers created. Setuptools let's me do that (most of the time. And I mean most). If somebody thinks he wants to include these in whatever form he prefers - fine with me. But it's hardly *my* problem, or that of the Python world in general, to fulfill the requirements some other people come up with. Diez From hendrik at microcorp.co.za Thu Aug 27 09:27:59 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 15:27:59 +0200 Subject: Need help with Python scoping rules In-Reply-To: <02a63e7d$0$15633$c3e8da3@news.astraweb.com> References: <02a63e7d$0$15633$c3e8da3@news.astraweb.com> Message-ID: <200908271527.59982.hendrik@microcorp.co.za> On Thursday 27 August 2009 11:14:41 Steven D'Aprano wrote: > On Thu, 27 Aug 2009 08:38:29 +0200, Hendrik van Rooyen wrote: > > On Wednesday 26 August 2009 17:14:27 kj wrote: > >> As I described at length in another reply, the function in question is > >> not intended to be "callable outside the class". And yes, > > > > I think this might go to nub of your problem - It might help you to > > think as follows: > > > > A Python class, even after it has been executed, does not really exist > > except as a kind of template or pattern - it is mostly useless until an > > instance of the class is made by calling it with whatever it needs to > > set up the instance. And once you have an instance, you can do stuff > > with that particular instance. Before that time, the class is mostly > > just a promise of things to come. > > Oh my! I couldn't disagree more strongly! I think the above is totally > incorrect. It was intended to help the OP out of the mental hole he finds himself in. Most of the classes I use fall directly into such a classification - they are useless until an instance is created. And I would be so bold as to say that _all_ gui classes are like that. This is the pattern I am talking about: class thing(object): def __init__(self,foo,bar): stuff to do things with foo and bar, creating or modifying attributes of the instance. def somemethod(self,baz,bling): instance method to do further operations on the attributes of the instance Now kindly explain to me how a class like that is usefull before an instance of it is created, and I might agree with you that what I said is "totally incorrect" 8< --trivial examples showing that there is something there ------------ > Classes are themselves instances of their metaclass. By default, classes > have a metaclass of type, but you can easily change that. Metaclass > programming is advanced but very powerful. > > Because classes are themselves objects, you can (with a bit of metaclass > jiggery-pokery) make them do all sorts of interesting things. For > instance, huge amounts of effort are often put into creating a Singleton > class, a class that has a single instance. Well, okay... but why not just > use the class object itself, instead of an instance? There's already one > of those, and you can't (easily) make a copy of it, and even if you did, > it would be an independent class. Instead of this: > > singleton = SingletonClass(args) > do_something_with(singleton) > > just do this: > > do_something_with(SingletonClass) > > Of course SingletonClass needs to be designed to work that way, which > will probably need some metaclass magic. It would be interesting to see > which requires less effort. *nods* yes this would make sense - but it is not quite what either the OP or I was on about. > > When it comes to built-in classes (types), I often use the class object > itself as an object. E.g. I might do something like this: > > def convert(seq): > t = type(seq) # remember the original type > result = process(seq) # always produces a list > if t is list: > return result # don't bother making a copy of the result > elif t is str or t is unicode: > empty = t() > return empty.join(result) > else: > return t(result) # return the original type nice. now try doing it with object: thing = object() After that, thing will exist, but it is a bit like write only memory - completely useless, until you have done some more work with it. > > >> recursive functions in Python *are* restricted in ways that > >> non-recursive functions aren't. The examples I've posted prove this > >> point unambiguously. > > > > Yes and no - mostly no - your examples just illustrate the point I > > tried to make above. > > Completely no. You may have missed the examples I've given, but the > problems the Original Poster were having had nothing to do with recursion. The yes was in there to make the man feel a bit better, and because from where he stood, it _was_ the recursion that did him in. : - ) > > > Pythons object model, and its classes, are different from what you are > > used to. A bare class is mostly useless without an instance, which is > > ultimately why accessing a function in a class from itself like you are > > doing, without reference to an instance, does not work - the function > > does not exist yet to a degree that it can be referenced. > > That is incorrect. What's going on is more subtle. > Right - I can see that you are reading that to mean that there must be an instance. That is not what I intended to bring across. I was talking about the lack of a reference that is his original problem, which he only encountered with recursion. > >>> class Demo: > > ... def function(x): > ... print "Calling function with argument %s" % x > ... function(None) > ... function(1) > ... function(function) > ... > Calling function with argument None > Calling function with argument 1 > Calling function with argument > > >>> Demo > > two points: Of what earthly use is a bare class like that - except possibly as a container for all the good stuff those functions produced out of nothing? - You might as well use a list, or better a dict, to keep the results of such functions, unless the functions are procedures, doing things by side effect - and if that is the case, why bother putting them in a class? Secondly: Now what you have done is carefully avoided the OP's original problem, which arises when the function in the class is called, and tries to call itself at the time of execution of the class suite, and fails, for the reasons so nicely explained by a lot of people. So the OP had a point when he complained that python does not like recursion, because, until he understands what is happening, the simplest theory that fits his observed facts is that the failure is caused by the recursion. - a completely rational conclusion based on Occam's razor. It just happens to be wrong in this case. This was the source for my "Yes" above. This should also work for the OP - I cannot recall if it has been shown: class Demo(object): def fact(x,f): if x < 2: return 1 else: return x*f(x-1,f) thing = fact(42,fact) I still think it is stupid, though - thing should simply be set to 1405006117752879898543142606244511569936384000000000L and that would be the end of it for this use case, without the bother of a function and the concomitant waste of time. - Hendrik From benjamin.kaplan at case.edu Thu Aug 27 09:28:20 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 27 Aug 2009 09:28:20 -0400 Subject: Does Class implements Interface? In-Reply-To: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> Message-ID: On Thu, Aug 27, 2009 at 9:16 AM, Emanuele D'Arrigo wrote: > Greetings everybody, > > let's say I have a Class C and I'd like to verify if it implements > Interface I. If I is available to me as a class object I can use > issubclass(C, I) and I can at least verify that I is a superclass of > C. There are a couple of issues with this approach however: > > 1) C might override not just I's methods code but also I's methods > signatures, effectively changing the interface. > 2) What if I is -not- available to me as the superclass of C but as a > description of the interface, i.e. as an IDL(*) file? > > Are there resources such as tools, recipes, documents or strategies > that could help me deal with these issues? I've already looked into > the ABC module and the zope.interface. I'm just fishing for more > things to look at. > > Manu > > (*) http://en.wikipedia.org/wiki/Interface_description_language Python's general philosophy is that it's Easier to Ask Forgiveness than Permission. Don't check the interface, just assume it's true and wrap the code block in a try/except in case it isn't. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From anthony.tolle at gmail.com Thu Aug 27 09:36:25 2009 From: anthony.tolle at gmail.com (Anthony Tolle) Date: Thu, 27 Aug 2009 06:36:25 -0700 (PDT) Subject: Move dictionary from instance to class level References: Message-ID: <705c21b0-2858-46c2-8230-3cea64f5be3a@a26g2000yqn.googlegroups.com> To take things one step further, I would recommend using decorators to allow symbolic association of functions with the message identifiers, as follows: ====================================== (MESSAGE_ONE ,MESSAGE_TWO ,MESSAGE_THREE ) = xrange(3) class MyClass(object): method_dict = {} # create helper decorator register_method = lambda msg, method_dict=method_dict: lambda function: method_dict.setdefault(msg, function) @register_method(MESSAGE_ONE) def handle_one(self): print 'handling MESSAGE_ONE' @register_method(MESSAGE_TWO) def handle_two(self): print 'handling MESSAGE_TWO' @register_method(MESSAGE_THREE) def handle_three(self): print 'handling MESSAGE_THREE' # no longer need helper decorator del register_method # function to dispatch messages def on_message_received(self, msg): MyClass.method_dict[msg](self) x = MyClass() x.on_message_received(MESSAGE_ONE) x.on_message_received(MESSAGE_TWO) x.on_message_received(MESSAGE_THREE) ====================================== Note: the line containing the lambda definition is all one line. From hendrik at microcorp.co.za Thu Aug 27 09:44:35 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 15:44:35 +0200 Subject: Need help with Python scoping rules In-Reply-To: <02a6427a$0$15633$c3e8da3@news.astraweb.com> References: <02a6427a$0$15633$c3e8da3@news.astraweb.com> Message-ID: <200908271544.35328.hendrik@microcorp.co.za> On Thursday 27 August 2009 11:31:41 Steven D'Aprano wrote: > > What you are calculating might actually be quite complicated to enter as > a literal. You might have something like: 8< ---------- Complicated Table Example ------------------------------- Me? - never! I am just an assembler programmer. I would not touch a thing like that with a barge pole. Unless of course, I have to. > Clearly this is a made-up example, but the principle is sound. If Python > can calculate values for you, why not let it do so? It is easier for you, > easier to check that you've calculated them correctly, easier to debug > and read, it makes the algorithm clearer (fewer "magic constants"). Yes, > there is a run-time cost, but you only pay it once, when you import the > module, and it's likely to be not that much more expensive than parsing > the literals anyway. > > Of course, for something as big and complicated as the above table, I'd > almost certainly put the code to calculate it in a function outside of > the class, but that's a matter of style, and it will work to put it > inside the class. It is a hell of a thing if it needs recursion to calculate - If it was really that complex, I would calculate it, check it (if I can), document it and put it in a module of its own, with "This side up", "Fragile", and other warning stickers all over it. - Hendrik From knurxs at gmx.de Thu Aug 27 09:49:21 2009 From: knurxs at gmx.de (Michael) Date: Thu, 27 Aug 2009 06:49:21 -0700 (PDT) Subject: Q: multiprocessing.Queue size limitations or bug... References: <9a338a3f-33a8-416c-af42-36f596c7cb71@r27g2000vbn.googlegroups.com> Message-ID: <24428363-dd55-40de-8fc0-45441c1aab22@a13g2000yqc.googlegroups.com> On Aug 27, 8:56?am, ryles wrote: > On Aug 26, 4:56?am, Michael Riedel > wrote: > > > > > Sorry for being not more specific but I'm not absolutely certain whether > > I encountered a bug or did anything wrong: > > > The (stupid) code below results in a stall forever or not at 'p0.join()' > > depending on the value of TROUBLE_MAKER. > > > Any help, thoughts, comments? > > > Thank you for your time. > > > Michael > > > # ---------------------------------------------------------------------- > > > from multiprocessing import Process, Queue > > > # bit vector size > > BVS=8 > > > # > > TROUBLE_MAKER=12 ?# for greater values p0.join() is never satisfied... > > > def evaluate(q, id, start=0, stop=2**BVS): > > > ? ? cmin = {0: []} > > > ? ? for mask0 in range(start, stop): > > ? ? ? ? for mask1 in range(0, 2**BVS): > > ? ? ? ? ? ? for mask2 in range(mask1, TROUBLE_MAKER): > > ? ? ? ? ? ? ? ? cmin[0].append((mask0, mask1, mask2)) > > > ? ? print 'process %d finished (dict layout: %d/%d)...' % (id, > > len(cmin), len(cmin[0])) > > ? ? q.put(cmin.copy()) > > ? ? q.close() > > > if __name__ == '__main__': > > > ? ? q0 = Queue() > > ? ? q1 = Queue() > > ? ? q2 = Queue() > > ? ? q3 = Queue() > > > ? ? part = 2**BVS/4 > > ? ? p0 = Process(target=evaluate, args=(q0, 0, 0*part, 1*part), > > name='worker_0') > > ? ? p1 = Process(target=evaluate, args=(q1, 1, 1*part, 2*part), > > name='worker_1') > > ? ? p2 = Process(target=evaluate, args=(q2, 2, 2*part, 3*part), > > name='worker_2') > > ? ? p3 = Process(target=evaluate, args=(q3, 3, 3*part, 4*part), > > name='worker_3') > > ? ? p0.start() > > ? ? print 'process 0 started...' > > ? ? p1.start() > > ? ? print 'process 1 started...' > > ? ? p2.start() > > ? ? print 'process 2 started...' > > ? ? p3.start() > > ? ? print 'process 3 started...' > > ? ? # main process stalls at p0.join() for bigger TROUBLE_MAKER > > ? ? p0.join() > > ? ? p1.join() > > ? ? p2.join() > > ? ? p3.join() > > ? ? res0 = q0.get() > > ? ? res1 = q1.get() > > ? ? res2 = q2.get() > > ? ? res3 = q3.get() > > ? ? print 'results fetched...' > > > # ---------------------------------------------------------------------- > > > -- > > There is a warning related to this in the documentation: > > http://docs.python.org/library/multiprocessing.html#pipes-and-queues > > Basically, you should reverse the order of the get() and join() calls. > > multiprocessing does a pretty nice job of abstracting away the low- > level details of IPC, but there are still some gotchas. As you've > noticed, your program will deadlock when there is a large enough > amount of data being put into the queue. This is related to a hidden > thread that exists inside each of your child processes. The thread is > responsible for taking your queue items from an internal buffer and > then writing them into a pipe that your parent process will read from > when get() is called. The pipe mechanism is what allows the two > processes to pass information, and is supported directly by the > Operating System. However, the pipe has a limited capacity, and when > it is full, the writer thread is stuck waiting for the reader to read > enough from the pipe so that it can finish its write. The problem is > that your parent process (reader) is not actually calling get() to > drain the pipe. Instead it's stuck in join() waiting for the writer to > complete. I see. I really appreciate your valuable feedback. From no.email at please.post Thu Aug 27 09:53:07 2009 From: no.email at please.post (kj) Date: Thu, 27 Aug 2009 13:53:07 +0000 (UTC) Subject: Need help with Python scoping rules References: <4a967b2f$0$19301$426a74cc@news.free.fr> Message-ID: In <4a967b2f$0$19301$426a74cc at news.free.fr> Bruno Desthuilliers writes: >The only thing one is entitled to expect when learning a new language is >that the language's implementation follows the language specs. In fact, the official docs, when they discuss scopes, are off to a bad start: Names refer to objects. Names are introduced by name binding operations. Each occurrence of a name in the program text refers to the binding of that name established in the innermost function block containing the use. The first paragraph implies that binding can only occur within functions, which is either incorrect, or presupposes a definition of "function" that is not what most programmers would recognize. In general, I found the docs very unclear on the subject of scoping. PEP 227 is much better, but I wouldn't have thought of it as "the specs". kynn From szport at gmail.com Thu Aug 27 10:00:57 2009 From: szport at gmail.com (zaur) Date: Thu, 27 Aug 2009 07:00:57 -0700 (PDT) Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> Message-ID: On 26 ???, 23:56, MRAB wrote: > zaur wrote: > > On 26 ???, 21:11, "Rami Chowdhury" wrote: > >>> person = Person(): > >>> ? name = "john" > >>> ? age = 30 > >>> ? address = Address(): > >>> ? ? ?street = "Green Street" > >>> ? ? ?no = 12 > >> Can you clarify what you mean? Would that define a Person class, and an ? > >> Address class? > > I suppose that someone already define classes Person ans Address. > > For example, in this stupid way in a foreign module: > > > class Person(object): > > ? ?pass > > > class Address(object): > > ? ?pass > > > and the following statements > > > person = Person(): > > ? ?name = "john" > > ? ?age = 30 > > ? ?address = Address(): > > ? ? ? street = "Green Street" > > ? ? ? no = 12 > > > are constructing an instance as follows: > > > person = Person() > > person.name = "john" > > person.age = 30 > > address = person.address = Address() > > address.street = "Green Street" > > address.no = 12 > > [snip] > > Create factory functions: > > def new_address(**kwargs): > ? ? ?address = Address() > ? ? ?address.__dict__.update(kwargs) > ? ? ?return address > > def new_person(**kwargs): > ? ? ?person = Person() > ? ? ?person.__dict__.update(kwargs) > ? ? ?return person > > person = new_person(name="john", age=30, > address=new_address(street="Green Street", no=12)) Original idea isn't about how to organize my code in order to initialize these custom objects. The idea is about to use object's dictionary as nested scope. From paul at boddie.org.uk Thu Aug 27 10:05:51 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 27 Aug 2009 07:05:51 -0700 (PDT) Subject: ubuntu dist-packages References: <7fki3lF2kirnkU1@mid.uni-berlin.de> <71f5986e-6aae-46b0-8325-d67051c60a30@a13g2000yqc.googlegroups.com> <7fnftkF2m6bvdU1@mid.uni-berlin.de> Message-ID: <0298b834-78b4-4501-a09b-9b8da5e796c1@s15g2000yqs.googlegroups.com> On 27 Aug, 15:27, "Diez B. Roggisch" wrote: > > You mean it's the problem of the python packaging that it can't deal with > RPMs, debs, tgzs, OSX bundles, MSIs and > ? No, it's the problem of the Pythonic packaging brigade that package retrieval, building and installing is combined into one unsatisfactory whole. Certainly, it's annoying to discover when building some extension that the Python headers are missing, but the rhetorical vehicle used in the Python community is to frame the distributions as people who like to move stuff around unnecessarily and to corrupt other people's work. In fact, the distributions have proven themselves to be quite competent at managing huge numbers of software packages in a semi-automated fashion, so it's baffling that people doing work on Pythonic packaging tools wouldn't want to learn as much as they can about how those people manage it. For me, when making Debian packages, it has become easier to use the debhelper stuff to install things like documentation and resources than it is to figure out which special options have to be passed to the particular distutils incarnation of the setup function in order to get such stuff put in the right place, especially since distutils probably still employs an ad-hoc 1990s proprietary UNIX "oh just dump that stuff in some directory or other and forget about it" mentality. Really, distutils should be all about *dist*ribution and even then get out of the way as much as possible - the hard stuff is extracting the appropriate knowledge about the built Python interpreter in order to build extensions. Installation should be left to something which has an opinion about where things should be placed on a particular system, and which has the capability to know how to uninstall stuff - a capability which never seems to get any closer in the distutils scene. Paul From hendrik at microcorp.co.za Thu Aug 27 10:25:54 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 27 Aug 2009 16:25:54 +0200 Subject: List iterator thread safety In-Reply-To: References: <14e1469e-bcfe-4922-b135-3f0bd7e17a42@r42g2000yqj.googlegroups.com> Message-ID: <200908271625.54609.hendrik@microcorp.co.za> On Thursday 27 August 2009 15:26:04 Carl Banks wrote: > Deleting items from a list while iterating over it is a bad idea, > exceptions or not. > > Hmm, this sounds like something someone might do for a game. You have > a list of objects, and in a given time step you have to iterate > through the list and update each object. Problem is, one of the > enemies is kill before you get to it, so you would like to remove the > object from the list while iterating. Not an easy problem. Its not too bad - if you crook a bit - the trick is that you iterate over the list backwards when you are removing stuff based on index, so that the remainder does not get jumbled up by losing their positions, as happens when you do it going forwards. - Hendrik From pavlovevidence at gmail.com Thu Aug 27 10:34:17 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 27 Aug 2009 07:34:17 -0700 (PDT) Subject: Object's nesting scope References: Message-ID: <2751e263-ace0-4649-997c-1302d0f3b320@m20g2000vbp.googlegroups.com> On Aug 26, 5:51?am, zaur wrote: > Hi folk! > > What do you think about idea of "object's nesting scope" in python? > > Let's imaging this feature, for example, in this syntax: > > obj=: > ? ? ? > > or > > : > ? ? > > That's means that result object of evaluation is used as > nested scope for evaluation. > > So is this idea useful? It might be marginally useful to save typing. The idea has been discussed in various forms here quite a bit over the years. I doubt there's any chance it'll be accepted into Python, because it goes against one of the main design points of Python: that attributes should always be accessed explicitly. Having said that, the syntax you propose is awful. :) Normally when this is proposed they use a keyword such as "using": p = Person() using p: name = "Carl Banks" location = "Los Angeles" or, perhaps to save a line (even though it'd be a minor syntax abuse): using Person() as p: name = "Carl Banks" location = "Los Angeles" Carl Banks From stefan_ml at behnel.de Thu Aug 27 10:39:24 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Thu, 27 Aug 2009 16:39:24 +0200 Subject: Parse xml file In-Reply-To: References: Message-ID: <4a969a9c$0$32665$9b4e6d93@newsspool2.arcor-online.net> loial wrote: > Is there a quick way to retrieve data from an xml file in python 2.4, > rather than read the whole file? ElementTree is available as an external package for Py2.4 (and it's in the stdlib xml.etree package since 2.5). It's pretty much the easiest way to get data out of XML files. If your statement "rather than read the whole file" was referring to the file size, note that the C implementation "cElementTree" of ElementTree is very memory efficient, so you might still get away with just reading the whole file into memory. There's also the iterparse() function which supports iterative parsing of an XML file and thus allows intermediate cleanup of used data. Stefan From pavlovevidence at gmail.com Thu Aug 27 10:50:16 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 27 Aug 2009 07:50:16 -0700 (PDT) Subject: List iterator thread safety References: <14e1469e-bcfe-4922-b135-3f0bd7e17a42@r42g2000yqj.googlegroups.com> Message-ID: <6bf89e55-2ddd-435f-925d-7cc3827c0f9a@24g2000yqm.googlegroups.com> On Aug 27, 7:25?am, Hendrik van Rooyen wrote: > On Thursday 27 August 2009 15:26:04 Carl Banks wrote: > > > Deleting items from a list while iterating over it is a bad idea, > > exceptions or not. > > > Hmm, this sounds like something someone might do for a game. ?You have > > a list of objects, and in a given time step you have to iterate > > through the list and update each object. ?Problem is, one of the > > enemies is kill before you get to it, so you would like to remove the > > object from the list while iterating. ?Not an easy problem. > > Its not too bad - if you crook a bit - the trick is that you iterate over the > list backwards when you are removing stuff based on index, so that the > remainder does not get jumbled up by losing their positions, as happens when > you do it going forwards. That's only if you remove the "current item". The OP has different threads accessing the list at the same time, so I have to assume that item being remove is not necessarily the current iteration. Getting back to the game example, suppose your "list of objects in the scene" looks like this: [ HandsomeHero, Enemy1, Bullet1, Enemy2, Bullet2, Enemy3] It might happen that Bullet1.update() detects a collision with Enemy2, thus killing Enemy2, which means Enemy2 would have to be removed before the next iteration. Otherwise you're updating a zombie. (Which, parenthetically, is another approach.) Conversely, suppose Bullet2.update() detects a collision with Enemy1, and Enemy1 is removed from the list. Then Enemy3 is going to be skipped. In order to handle both cases (where an item could be removed ahead of or before the current item), you have to keep track of the current index and adjust it. A list iterator won't work. For the record, I use a more sophisticated system that explicitly resolves cause and effect in my games. That's probably beyond the scope of this thread, though. Carl Banks From zuo at chopin.edu.pl Thu Aug 27 10:59:47 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Thu, 27 Aug 2009 16:59:47 +0200 Subject: Need help with Python scoping rules In-Reply-To: <02a66947$0$15633$c3e8da3@news.astraweb.com> References: <02a66947$0$15633$c3e8da3@news.astraweb.com> Message-ID: 14:17:15 Steven D'Aprano wrote: > The class is a scope, and inside the class scope, you can access local > names. What you can't do is access the class scope from inside nested > functions. s/from inside nested functions/from inside nested scopes Besides that detail, I fully agree. *j -- Jan Kaliszewski (zuo) From szport at gmail.com Thu Aug 27 11:01:14 2009 From: szport at gmail.com (zaur) Date: Thu, 27 Aug 2009 08:01:14 -0700 (PDT) Subject: Object's nesting scope References: <2751e263-ace0-4649-997c-1302d0f3b320@m20g2000vbp.googlegroups.com> Message-ID: On 27 ???, 18:34, Carl Banks wrote: > On Aug 26, 5:51?am, zaur wrote: > > > > > Hi folk! > > > What do you think about idea of "object's nesting scope" in python? > > > Let's imaging this feature, for example, in this syntax: > > > obj=: > > ? ? ? > > > or > > > : > > ? ? > > > That's means that result object of evaluation is used as > > nested scope for evaluation. > > > So is this idea useful? > > It might be marginally useful to save typing. It also allow to structure the code. > The idea has been > discussed in various forms here quite a bit over the years. ?I doubt > there's any chance it'll be accepted into Python, because it goes > against one of the main design points of Python: that attributes > should always be accessed explicitly. I don't in general consider this idea as a way for implicit access to object's attributes. Idea is about to use in some way object's dictionary as nested scope in a code block. I agree though that using this only for saving typing or implicit attribute access isn't a good idea. > Having said that, the syntax you propose is awful. :) Normally when > this is proposed they use a keyword such as "using": > > p = Person() > using p: > ? ? name = "Carl Banks" > ? ? location = "Los Angeles" > > or, perhaps to save a line (even though it'd be a minor syntax abuse): > > using Person() as p: > ? ? name = "Carl Banks" > ? ? location = "Los Angeles" I don't propose concrete syntax for using object's dictionary as nested scope. I used current only to explain the idea. From pavlovevidence at gmail.com Thu Aug 27 11:19:04 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Thu, 27 Aug 2009 08:19:04 -0700 (PDT) Subject: Object's nesting scope References: <2751e263-ace0-4649-997c-1302d0f3b320@m20g2000vbp.googlegroups.com> Message-ID: <03269cff-acd9-401a-b98d-0b1136b0d2e0@s13g2000yql.googlegroups.com> On Aug 27, 8:01?am, zaur wrote: > On 27 ???, 18:34, Carl Banks wrote: > > The idea has been > > discussed in various forms here quite a bit over the years. ?I doubt > > there's any chance it'll be accepted into Python, because it goes > > against one of the main design points of Python: that attributes > > should always be accessed explicitly. > > I don't in general consider this idea as a way for implicit access to > object's attributes. That's what is it regardless of what you consider it. > Idea is about to use in some way object's dictionary as nested scope > in a code block. Which is implicitly accessing the object's attributes. Carl Banks From davea at ieee.org Thu Aug 27 11:43:22 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 27 Aug 2009 11:43:22 -0400 Subject: Move dictionary from instance to class level In-Reply-To: <20090827102111.ABC3B1F93@ctb-mesg4.saix.net> References: <20090827102111.ABC3B1F93@ctb-mesg4.saix.net> Message-ID: <4A96A99A.1090100@ieee.org> Frank Millman wrote: > Dave Angel wrote: > >> Frank Millman wrote: >> >>> That is definitely *not* what I want to do. >>> >>> I want to make the server as generic as possible, so that >>> >> it can handle any >> >>> type of client, hopefully even including a browser >>> >> eventually. Therefore the >> >>> server has no knowledge of wxPython event types. >>> >>> I have abstracted all the event types I am interested in >>> >> (the list is fairly >> >>> stable now). My protocol requires that the client maps a >>> >> specific gui event >> >>> type to a message identifier, and the server maps the >>> >> message identifier to >> >>> a method that handles the message. >>> >>> Hope that makes sense. >>> >>> Frank >>> >>> >>> >>> >> Yes, it makes sense. Sorry for heading down that particular >> dead-end. >> But the more I think about it, the more likely I think it is >> that you'll >> be adding new message types, even if they're just variants of ones >> already defined. So it might behoove you to have a shared "data >> structure" that describes the whole message, not just equates >> a name to >> an integer. >> >> Or consider pickling. I don't know the tradeoffs, but the >> idea is that >> an object is constructed at the other end that has all the same data >> members as the object you had at this end. Perhaps with a flexible >> enough class definition, you could represent all or at least >> several of >> your messages with the same object. >> >> I am curious about your topology. You're sending events from >> the client >> (which presumably has a mouse and keyboard) to a server. But >> what does >> the server do with those? Does it have its own screen, or what? >> >> > > I'll try to explain. > > I am writing a fairly standard business/accounting application. (I am now > adding Business Process Management to it, which is complicating matters, but > that is another story.) > > Most of the gui stuff is basic forms processing - screens with static data, > text fields for display and input of data, and buttons for signifying > certain actions to be taken. > > My original attempt had both the gui and the business logic running on the > client, with a connection to a database running on a server. It worked, but > then I realised it was very insecure - it would be easy to hack the python > code, bypass the business logic, and allow any update to the database. > > So my second attempt took all the business logic out of the client and put > it onto the server. To execute a form, the server builds a form definition > by creating objects to represent each of the widgets, creates a list of the > components with sufficient information for the client to render them , then > sends a json'd copy of the list to the client, which interprets it and > displays the required form. The client informs the server of each event, and > the server handles the event in much the same way as it did before when the > business logic was on the client. > > For example, clicking a button triggers a response which could involve > updating the database, displaying another window with additional data, etc, > etc. Previously there would have been a method on the client designed to > handle the response, and the method would be added to the button constructor > so that it would be called when the button was clicked. > > Now the method is on the server, and is stored as an attribute of the button > object on the server. When the user clicks the button, the message is passed > up to the server (each widget has its own id, which is part of the message), > the server is notified that the button was clicked, and it calls the > associated method. > > There is a lot more to it than that, but hopefully that will give you an > idea. > > If I ever get this to a workable state (it is taking far longer than I > anticipated) I will release it as open source, and will then welcome as much > feedback as possible. > > Frank > > > OK, that makes good sense. And I withdraw any suggestion to use pickling, since that could be subject to hacking. It now appears that the messages are only incidentally GUI events. And that you would be well advised to make every possible event a separate message, so that if the server state and the client state get out of synch, you can readily check and reject such operations. For example, you'd have a message for pressing the SUBMIT button on a particular form, but you'd have different message types for other buttons on the same form, or for SUBMIT on other forms. DaveA From szport at gmail.com Thu Aug 27 11:43:55 2009 From: szport at gmail.com (zaur) Date: Thu, 27 Aug 2009 08:43:55 -0700 (PDT) Subject: Object's nesting scope References: <2751e263-ace0-4649-997c-1302d0f3b320@m20g2000vbp.googlegroups.com> <03269cff-acd9-401a-b98d-0b1136b0d2e0@s13g2000yql.googlegroups.com> Message-ID: <2c78ef30-3af6-45bd-b772-e09d895b0cd8@o15g2000yqm.googlegroups.com> On 27 ???, 19:19, Carl Banks wrote: > On Aug 27, 8:01?am, zaur wrote: > > > On 27 ???, 18:34, Carl Banks wrote: > > > The idea has been > > > discussed in various forms here quite a bit over the years. ?I doubt > > > there's any chance it'll be accepted into Python, because it goes > > > against one of the main design points of Python: that attributes > > > should always be accessed explicitly. > > > I don't in general consider this idea as a way for implicit access to > > object's attributes. > > That's what is it regardless of what you consider it. > > > Idea is about to use in some way object's dictionary as nested scope > > in a code block. > > Which is implicitly accessing the object's attributes. > > Carl Banks In my opinion idea of using object's dictionary as nested scope is more about structuring code blocks rather than just saving typing and implicit attribute access. From cournape at gmail.com Thu Aug 27 11:45:01 2009 From: cournape at gmail.com (David Cournapeau) Date: Thu, 27 Aug 2009 10:45:01 -0500 Subject: ubuntu dist-packages In-Reply-To: <7fnftkF2m6bvdU1@mid.uni-berlin.de> References: <7fki3lF2kirnkU1@mid.uni-berlin.de> <71f5986e-6aae-46b0-8325-d67051c60a30@a13g2000yqc.googlegroups.com> <7fnftkF2m6bvdU1@mid.uni-berlin.de> Message-ID: <5b8d13220908270845g67bb8d05w1dda70f433e29914@mail.gmail.com> On Thu, Aug 27, 2009 at 8:27 AM, Diez B. Roggisch wrote: > Paul Boddie wrote: > >> On 26 Aug, 17:48, Jorgen Grahn wrote: >>> >>> Well, if you are thinking about Debian Linux, it's not as much >>> "ripping out" as "splitting into a separate package with a non-obvious >>> name". Annoying at times, but hardly an atrocity. >> >> Indeed. Having seen two packages today which insisted on setuptools, >> neither really needing it, and with one actively trying to download >> stuff from the Internet (fifteen seconds warning - how generous!) when >> running setup.py, it seems to me that it isn't the distribution >> packagers who need to be re-thinking how they install Python software. >> >> Generally, distributions have to manage huge amounts of software and >> uphold reasonable policies without creating unnecessary maintenance. >> Sadly, until very recently (and I'm still not entirely sure if there's >> really been an attitude change) the Pythonic packaging brigade has >> refused to even consider the needs of one of the biggest groups of >> consumers of the upstream code. Consequently, distributions will >> always devise different ways of storing installed Python software, >> documentation and resources, mostly because the Pythonic tools have >> been deficient, particularly in the management of the latter >> categories. > > You mean it's the problem of the python packaging that it can't deal with > RPMs, debs, tgzs, OSX bundles, MSIs and > ? Of course it is - not because distutils should know about them but on the contrary because it should be possible to tweak the installation parameters to accomodate the various packaging solutions. Autotools, cmake, etc... do not need anything about rpm, debian, msi, and yet, they can be used to that purpose. cheers, David From diesch at spamfence.net Thu Aug 27 11:54:03 2009 From: diesch at spamfence.net (Florian Diesch) Date: Thu, 27 Aug 2009 17:54:03 +0200 Subject: ubuntu dist-packages References: Message-ID: Robin Becker writes: > Florian Diesch wrote: > ......... >> >>>From /usr/lib/python2.6/site.py: >> >> ,---- >> | For Debian and derivatives, this sys.path is augmented with directories >> | for packages distributed within the distribution. Local addons go >> | into /usr/local/lib/python/dist-packages, Debian addons >> | install into /usr/{lib,share}/python/dist-packages. >> | /usr/lib/python/site-packages is not used. >> `---- > > the above is not present in my windows documentation (or indeed > site.py) at all so it seems they just decided to change the > name. Anyone trying to debug why their distutils or setuptools or > whichever python packager is going wrong will have yet another detail > to remember. setuptools works fine for me in Ubuntu 9.04; eggs go to /usr/local/lib/python2.6/dist-packages/ like they should according to site.py > In addition, as any one who has done such trivial changes > will already know, they forgot to do it globally eg my 0.4.1.0 version > of the "Debian Python Policy" document explicitly mentions > site-packages. It's a change for the Python 2.6 package, see and /usr/lib/python2.5/site.py Python 2.6 is only in Debian experimental, I guess there is a new version of the Debian Python Policy coming. Florian -- From phily05 at gmail.com Thu Aug 27 11:58:19 2009 From: phily05 at gmail.com (Phil) Date: Thu, 27 Aug 2009 08:58:19 -0700 (PDT) Subject: Python on the Web References: <4a94ef42$0$27774$426a74cc@news.free.fr> <4a96884b$0$22855$426a74cc@news.free.fr> Message-ID: <1b7a2f45-dd10-4722-a9d8-8c6d2464e4d6@e27g2000yqm.googlegroups.com> Thanks Graham. I actually ended up reading that blog post from a Google search last night before I saw your response. It was very informative. Bruno, I will take a look at those groups to expand my knowledge. When I gave that arbitrary percentage, I was basing it off of the information I had seen with regards to launching applications built with existing frameworks using lighttpd. I do realize I was missing a lot of information by looking up something that specific. I also understand that there are enough frameworks. That still won't change my mind. I do not want to write a web application, otherwise I would use an existing framework as suggested. I just wanted to experiment and see what kind of framework I could develop with some ideas I had in mind. The original post was mostly just because I was having a difficulty understanding some lower level concepts as a result of trying to get Python 3 on the web before figuring out that it wasn't quite ready for that. I just really like some of the new features of Python 3, and most importantly, unicode compliance is just that much straight forward in my opinion. From robin_v at bigpond.com Thu Aug 27 12:07:20 2009 From: robin_v at bigpond.com (robin) Date: Thu, 27 Aug 2009 16:07:20 GMT Subject: Numeric literals in other than base 10 References: <6031ba08-08c8-416b-91db-ce8ff57ae8e5@w6g2000yqw.googlegroups.com> <1ituygwxqe7p$.scuioqblznea.dlg@40tude.net> Message-ID: "James Harris" wrote in message news:bc3607b3-7fdd-43fd-8ede-66ac3f597403 at 32g2000yqj.googlegroups.com... On 22 Aug, 10:27, David <71da... at libero.it> wrote: >They look good - which is important. The trouble (for me) is that I >want the notation for a new programming language and already use these >characters. I have underscore as an optional separator for groups of >digits - 123000 and 123_000 mean the same. The semicolon terminates a >statement. Based on your second idea, though, maybe a colon could be >used instead as in XPL uses "(2)1011" for base 4, "(3)03212" for octal, "(4)0741" for base 16. PL/I uses 8FXN for numeric hex and X suffix for a hex character constant. From sylvain.thenault at logilab.fr Thu Aug 27 12:10:22 2009 From: sylvain.thenault at logilab.fr (Sylvain =?utf-8?B?VGjDqW5hdWx0?=) Date: Thu, 27 Aug 2009 18:10:22 +0200 Subject: [ANN] pylint 0.18.1 / astng 0.19.1 Message-ID: <20090827161022.GF4791@lupus.logilab.fr> Hi there, I'm pleased to announce a new bug fixes release of pylint and astng. To see what have been fixed and to download it (unless your using debian, ubuntu or easy_install of course :), check: http://www.logilab.org/project/pylint/0.18.1 http://www.logilab.org/project/logilab-astng/0.19.1 -- Sylvain Th?nault LOGILAB, Paris (France) Formations Python, Debian, M?th. Agiles: http://www.logilab.fr/formations D?veloppement logiciel sur mesure: http://www.logilab.fr/services CubicWeb, the semantic web framework: http://www.cubicweb.org From robert.kern at gmail.com Thu Aug 27 12:16:41 2009 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 27 Aug 2009 11:16:41 -0500 Subject: Overriding iadd for dictionary like objects In-Reply-To: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: On 2009-08-27 01:49 AM, RunThePun wrote: > Anybody have any more ideas? I think python should/could havev a > syntax for overriding this behaviour, i mean, obviously the complexity > of supporting all operators with the getitem syntax could introduce > alot of clutter. But maybe there's an elegant solution out there... I would recommend just adding a method to MyDict that does exactly what you want. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From robert.kern at gmail.com Thu Aug 27 12:26:31 2009 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 27 Aug 2009 11:26:31 -0500 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: On 2009-08-27 07:41 AM, David House wrote: > 2009/8/27 Terry Reedy: >> reply-all may send duplicate messages to the author. Not sure of this list. > > I'm fairly sure Mailman deals with that. Many of us read from comp.lang.python for gmane.comp.python.general. I do not appreciate getting reply emails to my inbox. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From shashank.sunny.singh at gmail.com Thu Aug 27 12:39:06 2009 From: shashank.sunny.singh at gmail.com (Shashank Singh) Date: Thu, 27 Aug 2009 22:09:06 +0530 Subject: (Simple?) Unicode Question Message-ID: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> Hi All! I have a very simple (and probably stupid) question eluding me. When exactly is the char-set information needed? To make my question clear consider reading a file. While reading a file, all I get is basically an array of bytes. Now suppose a file has 10 bytes in it (all is data, no metadata, forget the BOM and stuff for a little while). I read it into an array of 10 bytes, replace, say, 2nd bytes and write all the bytes back to a new file. Do i need the character encoding mumbo jumbo anywhere in this? Further, does anything, except a printing device need to know the encoding of a piece of "text"? I mean, as long as we are not trying to get a symbolic representation of a "text" or get "i"th character of it, all we need to do is to carry the intended encoding as an auxiliary information to the data stored as byte array. Right? --shashank -------------- next part -------------- An HTML attachment was scrubbed... URL: From davea at ieee.org Thu Aug 27 12:42:10 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 27 Aug 2009 12:42:10 -0400 Subject: About diagram and python In-Reply-To: <030422b7-a4f8-4ea6-8708-4486da4cf595@w6g2000yqw.googlegroups.com> References: <030422b7-a4f8-4ea6-8708-4486da4cf595@w6g2000yqw.googlegroups.com> Message-ID: <4A96B762.7030209@ieee.org> catalinfest at gmail.com wrote: > Hello! > I see on my Diagram Editor software this : > File -> Export... -> (on Export option is : PyDia Code > Generation ... .py) > What python is in this file ? > How help me with python code ? > Thank you ! > > And when I start my car the radio is tuned to the wrong station. Could somebody tell me how to change the tubes on it? Or maybe I have a flat tire? When asking a question, give enough information that somebody has a chance of answering it. Otherwise you're wasting your time and ours. There are hundreds of "diagram editors" out there. Brand, version, maybe the URL to a website to download it. DaveA From rami.chowdhury at gmail.com Thu Aug 27 12:44:41 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Thu, 27 Aug 2009 09:44:41 -0700 Subject: (Simple?) Unicode Question In-Reply-To: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> Message-ID: > Further, does anything, except a printing device need to know the > encoding of a piece of "text"? I may be wrong, but I believe that's part of the idea between separation of string and bytes types in Python 3.x. I believe, if you are using Python 3.x, you don't need the character encoding mumbo jumbo at all ;-) If you're using Python 2.x, though, I believe if you simply set the file opening mode to binary then data you read() should still be treated as an array of bytes, although you may encounter issues trying to access the n'th character. Please do correct me if I'm wrong, anyone. On Thu, 27 Aug 2009 09:39:06 -0700, Shashank Singh wrote: > Hi All! > > I have a very simple (and probably stupid) question eluding me. > When exactly is the char-set information needed? > > To make my question clear consider reading a file. > While reading a file, all I get is basically an array of bytes. > > Now suppose a file has 10 bytes in it (all is data, no metadata, > forget the BOM and stuff for a little while). I read it into an array of > 10 > bytes, replace, say, 2nd bytes and write all the bytes back to a new > file. > > Do i need the character encoding mumbo jumbo anywhere in this? > > Further, does anything, except a printing device need to know the > encoding of a piece of "text"? I mean, as long as we are not trying > to get a symbolic representation of a "text" or get "i"th character > of it, all we need to do is to carry the intended encoding as > an auxiliary information to the data stored as byte array. > > Right? > > --shashank -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From invalid at invalid Thu Aug 27 12:47:41 2009 From: invalid at invalid (Grant Edwards) Date: Thu, 27 Aug 2009 11:47:41 -0500 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: On 2009-08-27, Robert Kern wrote: > On 2009-08-27 07:41 AM, David House wrote: >> 2009/8/27 Terry Reedy: >>> reply-all may send duplicate messages to the author. Not sure of this list. >> >> I'm fairly sure Mailman deals with that. > > Many of us read from comp.lang.python or gmane.comp.python.general. > I do not appreciate getting reply emails to my inbox. Same here. I haven't noticed it happening much for c.l.p, but on some other lists it seems to be a common (and annoying) practice. For those lists, I usually set up e-mail filters for those lists to route such replys to /dev/null. I haven't yet done so for c.l.p... -- Grant Edwards grante Yow! I just forgot my whole at philosophy of life!!! visi.com From marduk at letterboxes.org Thu Aug 27 12:49:36 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Thu, 27 Aug 2009 12:49:36 -0400 Subject: (Simple?) Unicode Question In-Reply-To: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> Message-ID: <1251391776.79209.5.camel@centar.nbk> On Thu, 2009-08-27 at 22:09 +0530, Shashank Singh wrote: > Hi All! > > I have a very simple (and probably stupid) question eluding me. > When exactly is the char-set information needed? > > To make my question clear consider reading a file. > While reading a file, all I get is basically an array of bytes. > > Now suppose a file has 10 bytes in it (all is data, no metadata, > forget the BOM and stuff for a little while). I read it into an array > of 10 > bytes, replace, say, 2nd bytes and write all the bytes back to a new > file. > > Do i need the character encoding mumbo jumbo anywhere in this? > > Further, does anything, except a printing device need to know the > encoding of a piece of "text"? I mean, as long as we are not trying > to get a symbolic representation of a "text" or get "i"th character > of it, all we need to do is to carry the intended encoding as > an auxiliary information to the data stored as byte array. If you are just reading and writing bytes then you are just reading and writing bytes. Where you need to worry about unicode, etc. is when you start treating a series of bytes as TEXT (e.g. how many *characters* are in this byte array).* This is no different, IMO, than treating a byte stream vs a image file. You don't, need to worry about resolution, palette, bit-depth, etc. if you are only treating as a stream of bytes. The only difference between the two is that in Python "unicode" is a built-in type and "image" isn't ;) * Just make sure that if you are manipulating byte streams independent of it's textual representation that you open files, e.g., in binary mode. -a From davea at ieee.org Thu Aug 27 12:52:53 2009 From: davea at ieee.org (Dave Angel) Date: Thu, 27 Aug 2009 12:52:53 -0400 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <2d56febf0908270326p58adda54w306eb823710bb952@mail.gmail.com> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> <2d56febf0908270326p58adda54w306eb823710bb952@mail.gmail.com> Message-ID: <4A96B9E5.3030709@ieee.org> Xavier Ho wrote: > On Thu, Aug 27, 2009 at 7:04 PM, Dave Angel wrote: > > > > Thanks for those pointers. >> For example, I see a single message containing typically around 10 >> attachments. I do the reply-all to one of these attachments, and it handles >> the message body okay, the To/CC fields okay, >> > > > What do you mean 10 attachments? O_o. I know some people like to attach a > company logo in their signature. (The Aussie DLF list people do that heaps. > Although some people post a hand-written sig in the attachment ... I'm not > sure how smart that is, but I've seen it done.) Where are you getting these > "attachments"? > > The message is a "digest" containing between 1 and 20 messages. The "index" is in the main message, and all the actual messages are encoded as attachments. I also see actual attachments, and sometimes signatures as attachments. But the ones I'm talking about have extension .eml. > I haven't tried reply-all yet. May give that a try next time and see what > pops up in the To: address. > > > >> usually adds an extra RE: on the subject (so it becomes RE: RE: subject). >> > > > Gmail doesn't do that. Yay! (Re: is dumb anyway, and you can't prepend Re: > forever. Fwd: is reasonable.) > > > If I have a direct message with a Re: at the beginning, Thunderbird does not add an extra one to my reply subject. Only when I'm doing it on one of these attachments. > > I didn't know ** marks bold. Does __ mark underline? Those are cool things > I never hear about. Thanks! > > I don't know about any others other than *bold* text. And I don't know if it shows up in everyone's viewer that way, or just some. DaveA From josefg at gmail.com Thu Aug 27 13:04:38 2009 From: josefg at gmail.com (josef) Date: Thu, 27 Aug 2009 10:04:38 -0700 (PDT) Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> Message-ID: <9feee13c-117e-4806-b238-e4152a68adfb@18g2000yqa.googlegroups.com> Thanks to everyone who responded. I will be going with some sort of a = MyClass(name = 'a') format. It's the Python way. For me, it was very hard to accept that EVERYTHING is an object reference. And that there are no object reference names, just string entries in dictionaries. But I think it all makes sense now. Thanks again, Josef On Aug 21, 1:07?am, josef wrote: > To begin, I'm new with python. I've read a few discussions about > object references and I think I understand them. > > To be clear, Python uses a "Pass By Object Reference" model. > x = 1 > x becomes the object reference, while an object is created with the > type 'int', value 1, and identifier (id(x)). Doing this with a class, > x = myclass(), does the same thing, but with more or less object > attributes. Every object has a type and an identifier (id()), > according to the Python Language Reference for 2.6.2 section 3.1. > > x in both cases is the object reference. I would like to use the > object to refer to the object reference. If I have a gross > misunderstanding, please correct me. > > The following is what I would like to do: > I have a list of class instances dk = [ a, b, c, d ], where a, b, c, d > is an object reference. Entering dk gives me the object: [MyClass0 > instance at 0x0000, MyClass1 instance at 0x0008, MyClass2 instance at > 0x0010 ... ] > > I need the object reference name (a,b,c,d) from dk to use as input for > a file. Where do I find the memory location of the object reference > and the object reference name memory location? I am unconcerned with > the fact that the memory location will change the next time I run a > python session. I will be using the object reference name for > processing right away. > > My main focus of this post is: "How do I find and use object reference > memory locations?" > > Thoughts? > Thanks, > > Josef From milesck at umich.edu Thu Aug 27 13:27:40 2009 From: milesck at umich.edu (Miles Kaufmann) Date: Thu, 27 Aug 2009 10:27:40 -0700 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <13DD6BD6-A688-4870-AA57-8FCF1A122C5A@umich.edu> On Aug 26, 2009, at 1:11 PM, kj wrote: > I think I understand the answers well enough. What I *really* > don't understand is why this particular "feature" of Python (i.e. > that functions defined within a class statement are forbidden from > "seeing" other identifiers defined within the class statement) is > generally considered to be perfectly OK. IMO it's a bizarre, > inexplicable blindspot (which, among other things, gives rise to > a certain worry about what other similar craziness lurks under > Python's image of rationality). I have never seen even a half-hearted > justification, from a language design point of view, for why this > particular "feature" is worth having. Guido's design justifications: http://mail.python.org/pipermail/python-dev/2000-November/010598.html -- My personal justification: Python has used the same basic method of class creation since the very beginning: create a new local namespace, execute the class suite in that namespace, and then create a class, using the contents of the namespace as the class attributes. The important thing to note here is that there are really *two* namespaces--the local namespace that exists while the class suite is being executed (what I call the "suite namespace"), and the namespace of the class itself--and the first ceases to exist when the second is created. The two namespaces generally contain the same names at the point that the transfer occurs, but they don't have to; the metaclass (which constructs the class) is free to mess with the dictionary of attributes before creating the class. Suppose for a moment that the suite namespace *were* visible to nested scopes. The simplest and most consistent implementation would be to have a closure generated by a class statement be similar to that generated by a function--i.e., the closure would be over the suite namespace. This hardly seems desirable, though, because the suite namespace and the class namespace would get out of sync when different objects were assigned to the class namespace: class C: x = 1 def foo(self): print x print self.x >>> o = C() >>> o.foo() 1 1 >>> o.x = 2 >>> o.foo() 1 2 Surely such an implementation would be considered an even larger Python wart then not having the suite namespace visible to nested scopes at all. But it's better than the alternative of trying to unify the class suite namespace and the class namespace, which would be a nightmare of special cases (adding/deleting class attributes? descriptors? __getattr__?) and require an implementation completely separate from that of normal nested scopes. -Miles P.S. Just for fun: import types def make_class(*bases): """Decorator to allow you to (ab)use a function as a class definition. The function must take no arguments and end with 'return locals()'; bases are (optionally) specified as arguments to make_class; metaclasses other than 'type' are not supported. >>> @make_class ... def C(): ... greeting = 'Hello' ... target = 'world' ... def greet(self): ... print '%s, %s' % (self.greeting, target) ... return locals() ... >>> C().greet() Hello, world """ def decorator(func): return type(func.func_name, bases, func()) if len(bases) == 1 and isinstance(bases[0], types.FunctionType): func = bases[0] bases = (object,) return decorator(func) if not bases: bases = (object,) return decorator From ethan at stoneleaf.us Thu Aug 27 13:31:04 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 Aug 2009 10:31:04 -0700 Subject: Annoying octal notation In-Reply-To: <02a0b085$0$30337$c3e8da3@news.astraweb.com> References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> Message-ID: <4A96C2D8.5040002@stoneleaf.us> Steven D'Aprano wrote: > A mistake is still a mistake even if it shared with others. > > Treating its with a lead zero as octal was a design error when it was > first thought up [snippage] I have to disagree with you on this one. The computing world was vastly different when that design decision was made. Space was at a premium, programmers were not touch-typists, every character had to count, and why in the world would somebody who had to use papertape or punch cards add a lead zero without a *real* good reason? I submit that that real good reason was to specify an octal literal, and not a decimal literal. Now many many years have passed, much has changed, and a leading zero (like so much else) no longer makes the sense in once did -- especially in a very wide-spread and general purpose language like Python. That does not mean it was not a very good decision at the time. ~Ethan~ From python at mrabarnett.plus.com Thu Aug 27 13:42:58 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 Aug 2009 18:42:58 +0100 Subject: Annoying octal notation In-Reply-To: <4A96C2D8.5040002@stoneleaf.us> References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> <4A96C2D8.5040002@stoneleaf.us> Message-ID: <4A96C5A2.4020307@mrabarnett.plus.com> Ethan Furman wrote: > Steven D'Aprano wrote: >> A mistake is still a mistake even if it shared with others. >> >> Treating its with a lead zero as octal was a design error when it was >> first thought up > > [snippage] > > I have to disagree with you on this one. The computing world was vastly > different when that design decision was made. Space was at a premium, > programmers were not touch-typists, every character had to count, and > why in the world would somebody who had to use papertape or punch cards > add a lead zero without a *real* good reason? I submit that that real > good reason was to specify an octal literal, and not a decimal literal. > > Now many many years have passed, much has changed, and a leading zero > (like so much else) no longer makes the sense in once did -- especially > in a very wide-spread and general purpose language like Python. That > does not mean it was not a very good decision at the time. > I think that it although it might have been reasonable when C was invented, it wasn't a good idea when Python was invented. From mensanator at aol.com Thu Aug 27 13:49:27 2009 From: mensanator at aol.com (Mensanator) Date: Thu, 27 Aug 2009 10:49:27 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> <02a5d290$0$15633$c3e8da3@news.astraweb.com> <02a5ed07$0$15633$c3e8da3@news.astraweb.com> Message-ID: <9f392780-cb72-4bdb-a571-b1c218f3cbf8@k19g2000yqn.googlegroups.com> On Aug 26, 10:27?pm, Steven D'Aprano wrote: > On Wed, 26 Aug 2009 18:53:04 -0700, Erik Max Francis wrote: > >> In any case, unary is the standard term for what I'm discussing: > > >>http://en.wikipedia.org/wiki/Unary_numeral_system > This really isn't anywhere near as controversial as you guys are making > it. Words sometimes have meanings different from what you expect from > reasoning by analogy. Get over it. Fine. I'm over it. Point is, I HAVE encountered plenty of people who DON'T properly understand it, Marilyn Vos Savant, for example. You can't blame me for thinking you don't understand it either when unary is brought up in a discussion of how to interpret insignificant leading 0's. > > -- > Steven From ethan at stoneleaf.us Thu Aug 27 13:51:16 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 Aug 2009 10:51:16 -0700 Subject: Annoying octal notation In-Reply-To: <4A96C5A2.4020307@mrabarnett.plus.com> References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> <4A96C2D8.5040002@stoneleaf.us> <4A96C5A2.4020307@mrabarnett.plus.com> Message-ID: <4A96C794.9090209@stoneleaf.us> MRAB wrote: > Ethan Furman wrote: > >> Steven D'Aprano wrote: >> >>> A mistake is still a mistake even if it shared with others. >>> >>> Treating its with a lead zero as octal was a design error when it was >>> first thought up >> >> >> [snippage] >> >> I have to disagree with you on this one. The computing world was >> vastly different when that design decision was made. Space was at a >> premium, programmers were not touch-typists, every character had to >> count, and why in the world would somebody who had to use papertape or >> punch cards add a lead zero without a *real* good reason? I submit >> that that real good reason was to specify an octal literal, and not a >> decimal literal. >> >> Now many many years have passed, much has changed, and a leading zero >> (like so much else) no longer makes the sense in once did -- >> especially in a very wide-spread and general purpose language like >> Python. That does not mean it was not a very good decision at the time. >> > I think that it although it might have been reasonable when C was > invented, it wasn't a good idea when Python was invented. Very good point. I was thinking Steven was talking about the earliest case, as opposed to the earliest Python case. My apologies if I misunderstood. ~Ethan~ From bakes at ymail.com Thu Aug 27 14:15:59 2009 From: bakes at ymail.com (Bakes) Date: Thu, 27 Aug 2009 11:15:59 -0700 (PDT) Subject: regexp help Message-ID: <4e548d26-f3c9-46b8-a82a-c012607e2ff8@o6g2000yqj.googlegroups.com> If I were using the code: (?P[0-9]+) to get an integer between 0 and 9, how would I allow it to register negative integers as well? From iurisilvio at gmail.com Thu Aug 27 14:28:09 2009 From: iurisilvio at gmail.com (Iuri) Date: Thu, 27 Aug 2009 15:28:09 -0300 Subject: regexp help In-Reply-To: <4e548d26-f3c9-46b8-a82a-c012607e2ff8@o6g2000yqj.googlegroups.com> References: <4e548d26-f3c9-46b8-a82a-c012607e2ff8@o6g2000yqj.googlegroups.com> Message-ID: <789aac5a0908271128j43b5cf93se3afe2a7477ecc5e@mail.gmail.com> You can use r"[+-]?\d+" to get positive and negative integers. It returns true to these strings: "+123", "-123", "123" On Thu, Aug 27, 2009 at 3:15 PM, Bakes wrote: > If I were using the code: > > (?P[0-9]+) > > to get an integer between 0 and 9, how would I allow it to register > negative integers as well? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ethan at stoneleaf.us Thu Aug 27 14:35:22 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 Aug 2009 11:35:22 -0700 Subject: Object Reference question In-Reply-To: <9feee13c-117e-4806-b238-e4152a68adfb@18g2000yqa.googlegroups.com> References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <9feee13c-117e-4806-b238-e4152a68adfb@18g2000yqa.googlegroups.com> Message-ID: <4A96D1EA.7030002@stoneleaf.us> josef wrote: > Thanks to everyone who responded. > > I will be going with some sort of a = MyClass(name = 'a') format. It's > the Python way. > > For me, it was very hard to accept that EVERYTHING is an object > reference. And that there are no object reference names, just string > entries in dictionaries. But I think it all makes sense now. > > Thanks again, > > Josef My apologies if I missed it, but what *exactly* are you planning on doing with your 'name' attribute? From the posts I've seen so far, I think you are only setting yourself up for failure. ~Ethan~ From dickinsm at gmail.com Thu Aug 27 14:48:11 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Thu, 27 Aug 2009 11:48:11 -0700 (PDT) Subject: Python on Crays References: <1f5c81d8-4f79-4eea-b1bd-af48ab9ddc82@c2g2000yqi.googlegroups.com> Message-ID: <9e853de8-3183-402f-ab11-c0fad2a2fb9b@d4g2000yqa.googlegroups.com> On Aug 25, 11:34?pm, Carrie Farberow wrote: > Ok, here are links to word documents outlining the commands I executed as well as the make.log file and the make_install.log file > [links snipped] So from the output of make, it looks as though none of the modules specified in the Modules/Setup file is being built at all on your system. So not just unicodedata, but the math, cmath, array, itertools modules and more are missing from your build. You can check this by running Python: after the make step finishes, you should have a working Python executable called 'python' in the current directory; if you start it up and then type 'import math' at the '>>>' prompt, I'm guessing you'll get an error message that looks something like: ImportError: No module named math I don't have much idea why those modules aren't being built; I tried imitating the relevant parts of your instructions (to the degree that they make sense on my non-Cray system) without any problems. Anyway, I agree that issue1594809 doesn't look so relevant; the only common factor is that in both cases Python is failing to find the unicodedata module; but in that issue the unicodedata module is present but doesn't get found because the paths are messed up, while in your case the unicodedata module isn't being built at all. Suggestions: (1) double check that you've uncommented the appropriate lines in the Modules/Setup file. E.g., after the configure step, there's a line in Modules/Setup that looks like: #unicodedata unicodedata.c # static Unicode character database that leading '#' should be removed so that it looks like: unicodedata unicodedata.c # static Unicode character database and similarly for the other modules in that section. Make sure that you're editing the Modules/Setup file *after* the configure step and *before* the make step. (2) Find a local Unix/Python guru and ask him/her to help out. These sorts of problems are generally much easier to figure out when you've got direct access to the machine. Sorry I can't be more help than this. -- Mark From enleverLesX_XXmcX at XmclavXeauX.com.invalid Thu Aug 27 14:57:38 2009 From: enleverLesX_XXmcX at XmclavXeauX.com.invalid (Michel Claveau - MVP) Date: Thu, 27 Aug 2009 20:57:38 +0200 Subject: Learning Python advanced features References: <4a967bd6$0$19301$426a74cc@news.free.fr> Message-ID: <4a96d723$0$12655$ba4acef3@news.orange.fr> Bonsoir ! Tu aurais peut-?tre d? r?pondre en anglais (pour certains, "advanced features", c'est mieux que "concepts sophistiqu?s"). @+ MCI From james.harris.1 at googlemail.com Thu Aug 27 15:06:19 2009 From: james.harris.1 at googlemail.com (James Harris) Date: Thu, 27 Aug 2009 12:06:19 -0700 (PDT) Subject: Annoying octal notation References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> Message-ID: On 27 Aug, 18:31, Ethan Furman wrote: > Steven D'Aprano wrote: > > A mistake is still a mistake even if it shared with others. > > > Treating its with a lead zero as octal was a design error when it was > > first thought up > > [snippage] > > I have to disagree with you on this one. ?The computing world was vastly > different when that design decision was made. ?Space was at a premium, > programmers were not touch-typists, every character had to count, and > why in the world would somebody who had to use papertape or punch cards > add a lead zero without a *real* good reason? ?I submit that that real > good reason was to specify an octal literal, and not a decimal literal. Nice idea. Characters were expensive but not that expensive - even then. One extra character to make the octal prefix 0t or 0q or something could have been used. Check out the History heading at http://sundry.wikispaces.com/octal-zero-prefix Note how B migrated away from both BCPL's octal and its hex notation. # and #x in BCPL became 0 and 0x in B James From vicente.soler at gmail.com Thu Aug 27 15:06:53 2009 From: vicente.soler at gmail.com (vsoler) Date: Thu, 27 Aug 2009 12:06:53 -0700 (PDT) Subject: Question on the "csv" library Message-ID: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> I am trying to read a csv file generated by excel. Although I succeed in reading the file, the format that I get is not suitable for me. I've done: >>> import csv >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) >>> print spamReader <_csv.reader object at 0x01022E70> >>> for row in spamReader: print row ['codigo;nombre;cantidad'] ['a;qwe;1'] ['b;asd;2'] ['c;zxc;3'] My questions are: 1- Why using "print spamReader" I cannot see the data? I expected to see a list of lists, a kind of a matrix, but I get nothing 2- Why are the rows in a single string? I expected a list of fields that, when text, would be delimited by " To tell the truth, the file generated by excel does not contain the strings delimited by ". Isn't it weird? 3- Is there anything I can do to have my data in a list of lists structure? would another kind of data suit better my needs? Thank you for your help Vicente Soler From fasteliteprogrammer at yahoo.com Thu Aug 27 15:15:00 2009 From: fasteliteprogrammer at yahoo.com (Craig) Date: Thu, 27 Aug 2009 12:15:00 -0700 (PDT) Subject: Python on Crays In-Reply-To: <9e853de8-3183-402f-ab11-c0fad2a2fb9b@d4g2000yqa.googlegroups.com> Message-ID: <645368.38785.qm@web36503.mail.mud.yahoo.com> Who the one from wisconsin and did you try the python group in madison maybe they can help. Well i from madison are and i just a newbie with python.What OS you useing? --- On Thu, 8/27/09, Mark Dickinson wrote: > From: Mark Dickinson > Subject: Re: Python on Crays > To: python-list at python.org > Date: Thursday, August 27, 2009, 1:48 PM > On Aug 25, 11:34?pm, Carrie Farberow > > wrote: > > Ok, here are links to word documents outlining the > commands I executed as well as the make.log file and the > make_install.log file > > [links snipped] > > So from the output of make, it looks as though none of the > modules specified in the Modules/Setup file is being built > at all on your system.? So not just unicodedata, but > the > math, cmath, array, itertools modules and more are > missing from your build. > > You can check this by running Python:? after the make > step > finishes, you should have a working Python executable > called > 'python' in the current directory;? if you start it up > and > then type 'import math' at the '>>>' prompt, I'm > guessing > you'll get an error message that looks something like: > > ImportError: No module named math > > I don't have much idea why those modules aren't being > built; > I tried imitating the relevant parts of your instructions > (to the degree that they make sense on my non-Cray system) > without any problems. > > Anyway, I agree that issue1594809 doesn't look so > relevant; > the only common factor is that in both cases Python is > failing to find the unicodedata module;? but in that > issue > the unicodedata module is present but doesn't get found > because the paths are messed up, while in your case the > unicodedata module isn't being built at all. > > Suggestions: > > (1) double check that you've uncommented the appropriate > lines > in the Modules/Setup file.? E.g., after the configure > step, there's > a line in Modules/Setup that looks like: > > #unicodedata unicodedata.c? ? # static Unicode > character database > > that leading '#' should be removed so that it looks like: > > unicodedata unicodedata.c? ? # static Unicode > character database > > and similarly for the other modules in that section. > Make sure that you're editing the Modules/Setup file > *after* the configure step and *before* the make step. > > (2) Find a local Unix/Python guru and ask him/her to > help out.? These sorts of problems are generally much > easier to figure out when you've got direct access to > the machine. > > Sorry I can't be more help than this. > > -- > Mark > -- > http://mail.python.org/mailman/listinfo/python-list > From gert.cuykens at gmail.com Thu Aug 27 15:18:28 2009 From: gert.cuykens at gmail.com (gert) Date: Thu, 27 Aug 2009 12:18:28 -0700 (PDT) Subject: How does the file.seek() work ? References: <2feaaf6c-d723-4843-a9e5-271d00187180@c2g2000yqi.googlegroups.com> <1532ff09-f892-44c8-8206-10b3c2d16050@13g2000prl.googlegroups.com> <40093737-2ff1-4527-a2ea-a016ee526463@k30g2000yqf.googlegroups.com> Message-ID: On Aug 26, 7:28?pm, gert wrote: > On Aug 26, 12:46?am, Graham Dumpleton > wrote: > > > > > On Aug 25, 5:37?am, Tim Chase wrote: > > > > > I want the file pointer set to 100 and overwrite everything from there > > > [snip] > > > > def application(environ, response): > > > > ? ? query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') > > > > ? ? range=environ.get('HTTP_RANGE','bytes=0-').replace > > > > ('bytes=','').split(',') > > > > ? ? offset=[] > > > > ? ? for r in range: offset.append(r.split('-')) > > > > ? ? with open(query,'w+') as f: > > > > ? ? ? ? ?f.seek(int(offset[0][0])) > > > > ? ? ? ? ?while True: > > > > ? ? ? ? ? ? ?chunk=environ['wsgi.input'].read(8192).decode('latin1') > > > > ? ? ? ? ? ? ?if not chunk: break > > > > ? ? ? ? ? ? ?f.write(chunk) > > > > ? ? f=open(query) > > > > ? ? l=str(os.fstat(f.fileno()).st_size) > > > > ? ? response('200 OK', [('Content-Type', 'text/plain'), ('Content- > > > > Length', str(len(l)))]) > > > > ? ? return [l] > > > > A couple items of note: > > > > - you don't open the file in binary mode -- seek is more reliable > > > in binary mode :) > > > If my memory is right, if file is opened in binary mode, also wouldn't > > need to be decoding the WSGI input stream as latin-1 to get a string. > > Instead can just deal with bytes and write bytes to file. > > > Graham > > > > - if you want to lop off the rest of the file, use f.truncate() > > > > An example: > > > > # create the initial file > > > ?>>> f = file('zzz.zzz', 'wb+') > > > ?>>> f.write('abcdefghijklmnop') > > > ?>>> f.close() > > > > ?>>> f = file('zzz.zzz', 'ab+') > > > ?>>> f.read() # show the existing content > > > 'abcdefghijklmnop' > > > ?>>> f.seek(5) # seek to the desired offset > > > ?>>> f.truncate() # throw away everything after here > > > ?>>> f.write('zyx') # write the new data at pos=5 > > > ?>>> f.close() > > > > # demonstrate that it worked > > > ?>>> f = file('zzz.zzz', 'rb') > > > ?>>> f.read() > > > 'abcdezyx' > > > ?>>> f.close() > > > > > also why must I open the file a second time to know how big it is ? > > > > Likely the output has been buffered. ?You can try using > > > > ? ?f.flush() # write all the data to the disk first > > > ? ?size = os.fstat(f.fileno()).st_size > > > > which seems to do the trick for me. > > > -tkc > > Works thanks > > curl -C 10 -T upload2.wsgihttp://192.168.2.17/appwsgi/wsgi/upload2.wsgi > --header "Transfer-Encoding: chunked" -v > > import os > > def application(environ, response): > ? ? #query=environ.get['QUERY_STRING'] > ? ? #print (query, file=environ['wsgi.errors']) > ? ? query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') > ? ? range=environ.get('HTTP_CONTENT_RANGE','bytes 0-').replace('bytes > ','').split('/')[0].split(',') > ? ? offset=[] > ? ? for r in range: offset.append(r.split('-')) > ? ? with open(query,'rb+') as f: > ? ? ? ? ?f.seek(int(offset[0][0])) > ? ? ? ? ?if environ['REQUEST_METHOD']=='PUT': > ? ? ? ? ? ? ?f.truncate() > ? ? ? ? ? ? ?while True: > ? ? ? ? ? ? ? ? ?chunk=environ['wsgi.input'].read(8192) > ? ? ? ? ? ? ? ? ?if not chunk: break > ? ? ? ? ? ? ? ? ?f.write(chunk) > ? ? ? ? ?f.flush() > ? ? ? ? ?l=str(os.fstat(f.fileno()).st_size) > ? ? response('200 OK', [('Content-Type', 'text/plain'), ('Content- > Length', str(len(l)))]) > ? ? return [l] Update it works on mod_wsgi but not on wsgiref.simple_server C:\Users\gert\Desktop\hg\appwsgi\wsgi>curl -T upload2.wsgi http://localhost/appwsgi/wsgi/upload2.wsg i -v * About to connect() to localhost port 80 (#0) * Trying 127.0.0.1... connected * Connected to localhost (127.0.0.1) port 80 (#0) > PUT /appwsgi/wsgi/upload2.wsgi HTTP/1.1 > User-Agent: curl/7.19.4 (amd64-pc-win32) libcurl/7.19.4 OpenSSL/0.9.8j zlib/1.2.3 > Host: localhost > Accept: */* > Content-Length: 869 > Expect: 100-continue > * Done waiting for 100-continue I not getting 100-continues ? From ethan at stoneleaf.us Thu Aug 27 15:22:45 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Thu, 27 Aug 2009 12:22:45 -0700 Subject: Annoying octal notation In-Reply-To: References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> Message-ID: <4A96DD05.8020603@stoneleaf.us> James Harris wrote: > On 27 Aug, 18:31, Ethan Furman wrote: > > >>Steven D'Aprano wrote: > > >>>A mistake is still a mistake even if it shared with others. >> >>>Treating its with a lead zero as octal was a design error when it was >>>first thought up >> >>[snippage] >> >>I have to disagree with you on this one. The computing world was vastly >>different when that design decision was made. Space was at a premium, >>programmers were not touch-typists, every character had to count, and >>why in the world would somebody who had to use papertape or punch cards >>add a lead zero without a *real* good reason? I submit that that real >>good reason was to specify an octal literal, and not a decimal literal. > > > Nice idea. Characters were expensive but not that expensive - even > then. One extra character to make the octal prefix 0t or 0q or > something could have been used. Check out the History heading at > > http://sundry.wikispaces.com/octal-zero-prefix > > Note how B migrated away from both BCPL's octal and its hex notation. > > # and #x in BCPL became > 0 and 0x in B > > James Nice link. I suspect that as much as anything is was abbreviate as much as possible. In unix we have copy as cp, list as ls move as mv, etc, etc. Different mind-set also when designing for yourself or a small group, versus thousands and thousands. I am in agreement that Python should not have a leading 0 for octal, as there are big inconsistencies with how it's treated. Visually, I would have preferred a prefix of 0c, but I understand it should be consistent with the string specifier of o. Oh well, win some, lose some. ~Ethan~ From piet at cs.uu.nl Thu Aug 27 15:26:04 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 27 Aug 2009 21:26:04 +0200 Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> Message-ID: >>>>> Mensanator (M) wrote: >M> On Aug 26, 4:59?pm, Piet van Oostrum wrote: >>> >>>>> Mensanator (M) wrote: >>> >M> That's my point. Since the common usage of "binary" is for >>> >M> Standard Positional Number System of Radix 2, it follows >>> >M> that "unary" is the common usage for Standard Positional >>> >M> Number System of Radix 1. That's VERY confusing since such >>> >M> a system is undefined. Remember, common usage does not >>> >M> necessarily properly define things. Saying simply "unary" >>> >M> sounds like you're extending common usage beyond its proper >>> >M> boundaries. >>> >>> But the customary meaning of `unary' is the tally system, as a radix >>> system wouldn't make sense. I don't know when this term came into use >>> but I have known it for a long time. >M> Ok, I'll accept that and in the same breath say such common usage >M> is stupid. I, for one, have never heard such usage and would never >M> use "unary" in the same breath as "decimal, octal, binary" even if >M> I had. As I see it, unary just means that there is one symbol. Binary just means that there are two symbols, etc. With unary, the only sensible numerical interpretation is to count the number of occurrences of that symbol, or if you also want to have the number 0, the number of occurrences - 1. With binary and higher you can come up with more numerical interpretations but the most efficient one is the radix interpretation (for different values of `efficient'). I doubt that there are many other interpretations that you can call sensible. Therefore we immediately think of a radix system when we talk about binary, octal, decimal etc. But the word `binary' itself doesn't imply that. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From benjamin.kaplan at case.edu Thu Aug 27 15:29:15 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 27 Aug 2009 15:29:15 -0400 Subject: Question on the "csv" library In-Reply-To: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> Message-ID: On Thu, Aug 27, 2009 at 3:06 PM, vsoler wrote: > > I am trying to read a csv file generated by excel. > > Although I succeed in reading the file, the format that I get is not > suitable for me. > > I've done: > > >>> import csv > >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) > > >>> print spamReader > <_csv.reader object at 0x01022E70> > > >>> for row in spamReader: > ? ? ? ?print row > > > ['codigo;nombre;cantidad'] > ['a;qwe;1'] > ['b;asd;2'] > ['c;zxc;3'] > > My questions are: > > 1- Why using "print spamReader" I cannot see the data? > ? ?I expected to see a list of lists, a kind of a matrix, but I get > nothing It's because csv.reader does the same thing open does. It returns an iterable, not a list. The file is opened but not processed until you iterate through it. You cannot see the data when you do print spamReader because of this and because the csv reader object does define a __str__ method. > > 2- Why are the rows in a single string? > ? I expected a list of fields that, when text, would be delimited by > " > ?To tell the truth, the file generated by excel does not contain the > strings delimited by ". Isn't it weird? CSV stands for comma separated variables. It actually has nothing to do with the quotes- they're just used in case an element has a comma in it, so the reader knows it's a string literal and not a separate column. Your comma separated variable worksheet seems to be semicolon separated. That's why the reader isn't splitting it. > > 3- Is there anything I can do to have my data in a list of lists > structure? would another kind of data suit better my needs? > just do a list comprehension sheet = [row for row in spamReader] > Thank you for your help > > Vicente Soler > -- > http://mail.python.org/mailman/listinfo/python-list From piet at cs.uu.nl Thu Aug 27 15:40:28 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 27 Aug 2009 21:40:28 +0200 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile References: Message-ID: >>>>> Ryniek90 (R) wrote: >R> Hahah right. My fault. Must remember to read documentation so many times >R> until I find the solution. Thanks, now works fine. :-) And, by the way, how come the traceback refers to File "backuper.py", line 197, in while the posted code has only 188 lines? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From usenot at geekmail.INVALID Thu Aug 27 15:42:40 2009 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Thu, 27 Aug 2009 21:42:40 +0200 Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> Message-ID: <20090827214240.70aeb792@geekmail.INVALID> On Thu, 27 Aug 2009 21:36:28 +0200 Andreas Waldenburger wrote: > [snip] > > Might I humbly suggest > > >>> sheet = list(spamReader) # ? > Oh, and while I'm humbly suggesting: spam_reader instead of spamReader or SpamReader or SpamrEadeR or suchlike. Caps are "reserved" for classes. Not a necessity, of course. But it's the dialect around these parts. /W -- INVALID? DE! From farberow at wisc.edu Thu Aug 27 15:53:53 2009 From: farberow at wisc.edu (Carrie Farberow) Date: Thu, 27 Aug 2009 14:53:53 -0500 Subject: Python on Crays In-Reply-To: <645368.38785.qm@web36503.mail.mud.yahoo.com> References: <9e853de8-3183-402f-ab11-c0fad2a2fb9b@d4g2000yqa.googlegroups.com> <645368.38785.qm@web36503.mail.mud.yahoo.com> Message-ID: <6f30fc8f1d449.4a969e01@wiscmail.wisc.edu> I am from Wisconsin -- is there a python group here? Do you have any contact info.? The compute node operating system is Compute Node Linux (CNL). Carrie ----- Original Message ----- From: Craig Date: Thursday, August 27, 2009 2:15 pm Subject: Re: Python on Crays To: python-list at python.org, Mark Dickinson > Who the one from wisconsin and did you try the python group in madison > maybe they can help. > > Well i from madison are and i just a newbie with python.What OS you useing? > > --- On Thu, 8/27/09, Mark Dickinson wrote: > > > From: Mark Dickinson > > Subject: Re: Python on Crays > > To: python-list at python.org > > Date: Thursday, August 27, 2009, 1:48 PM > > On Aug 25, 11:34?pm, Carrie Farberow > > > > wrote: > > > Ok, here are links to word documents outlining the > > commands I executed as well as the make.log file and the > > make_install.log file > > > [links snipped] > > > > So from the output of make, it looks as though none of the > > modules specified in the Modules/Setup file is being built > > at all on your system.? So not just unicodedata, but > > the > > math, cmath, array, itertools modules and more are > > missing from your build. > > > > You can check this by running Python:? after the make > > step > > finishes, you should have a working Python executable > > called > > 'python' in the current directory;? if you start it up > > and > > then type 'import math' at the '>>>' prompt, I'm > > guessing > > you'll get an error message that looks something like: > > > > ImportError: No module named math > > > > I don't have much idea why those modules aren't being > > built; > > I tried imitating the relevant parts of your instructions > > (to the degree that they make sense on my non-Cray system) > > without any problems. > > > > Anyway, I agree that issue1594809 doesn't look so > > relevant; > > the only common factor is that in both cases Python is > > failing to find the unicodedata module;? but in that > > issue > > the unicodedata module is present but doesn't get found > > because the paths are messed up, while in your case the > > unicodedata module isn't being built at all. > > > > Suggestions: > > > > (1) double check that you've uncommented the appropriate > > lines > > in the Modules/Setup file.? E.g., after the configure > > step, there's > > a line in Modules/Setup that looks like: > > > > #unicodedata unicodedata.c? ? # static Unicode > > character database > > > > that leading '#' should be removed so that it looks like: > > > > unicodedata unicodedata.c? ? # static Unicode > > character database > > > > and similarly for the other modules in that section. > > Make sure that you're editing the Modules/Setup file > > *after* the configure step and *before* the make step. > > > > (2) Find a local Unix/Python guru and ask him/her to > > help out.? These sorts of problems are generally much > > easier to figure out when you've got direct access to > > the machine. > > > > Sorry I can't be more help than this. > > > > -- > > Mark > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From piet at cs.uu.nl Thu Aug 27 16:07:51 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 27 Aug 2009 22:07:51 +0200 Subject: Need help with Python scoping rules References: Message-ID: >>>>> kj (k) wrote: >k> No, the fact() function here represents an internal "helper" >k> function. It is meant to be called only once to help initialize >k> a class variable that would be inconvenient to initialize otherwise; >k> this helper function is not meant to be called from outside the >k> class statement. Granted, in the example I gave, the "helper" >k> function (factorial) is a bit silly, but that was just intended as >k> a simple and familiar example of a recursive function. The actual >k> function that motivated this post would be considerably more >k> difficult to explain and would have obscured the point of the post. Classes don't have helper functions; they have methods. Instance methods, static methods or class methods. Your's isn't either of these. Methods are to be called like `something.method(...)'. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From vicente.soler at gmail.com Thu Aug 27 16:12:07 2009 From: vicente.soler at gmail.com (vsoler) Date: Thu, 27 Aug 2009 13:12:07 -0700 (PDT) Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> Message-ID: <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> On Aug 27, 9:42?pm, Andreas Waldenburger wrote: > On Thu, 27 Aug 2009 21:36:28 +0200 Andreas Waldenburger > > wrote: > > [snip] > > > Might I humbly suggest > > > >>> sheet = list(spamReader) ?# ? > > Oh, and while I'm humbly suggesting: > > spam_reader instead of spamReader or SpamReader or SpamrEadeR or > suchlike. Caps are "reserved" for classes. > > Not a necessity, of course. But it's the dialect around these parts. > > /W > > -- > INVALID? DE! Thank you for your answers. Let me however make some comments: 1- the csv file was generated with Excel 2007; no prompts for what the separator should be; Excel has used ";" by default, without asking anything 2- about capitalisation, I used the var "spamReader" because I just copy/pasted from the official python site: http://docs.python.org/library/csv.html 3- when I try >>> sheet = [row for row in spamReader] >>> print sheet [] all I get is an empty list; something seems not to be working properly Same result list: I get an empty list sheet = list(spamReader) Thank you again for your help, which is highly appreciated. Vicente Soler From tjreedy at udel.edu Thu Aug 27 16:22:31 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Aug 2009 16:22:31 -0400 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: David House wrote: > 2009/8/27 Terry Reedy : >> reply-all may send duplicate messages to the author. Not sure of this list. > > I'm fairly sure Mailman deals with that. Nope. I got a duplicate sent to my mailbox, which I hate. From ppearson at nowhere.invalid Thu Aug 27 16:31:01 2009 From: ppearson at nowhere.invalid (Peter Pearson) Date: 27 Aug 2009 20:31:01 GMT Subject: regexp help References: <4e548d26-f3c9-46b8-a82a-c012607e2ff8@o6g2000yqj.googlegroups.com> Message-ID: <7fo8o5F2i2o8tU1@mid.individual.net> On Thu, 27 Aug 2009 11:15:59 -0700 (PDT), Bakes wrote: > If I were using the code: > > (?P[0-9]+) > > to get an integer between 0 and 9, how would I allow it to register > negative integers as well? (?P-?[0-9]+) -- To email me, substitute nowhere->spamcop, invalid->net. From usenot at geekmail.INVALID Thu Aug 27 16:37:26 2009 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Thu, 27 Aug 2009 22:37:26 +0200 Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> Message-ID: <20090827223726.23f99ef6@geekmail.INVALID> On Thu, 27 Aug 2009 13:12:07 -0700 (PDT) vsoler wrote: > On Aug 27, 9:42?pm, Andreas Waldenburger > wrote: > > [snip what I wrote] > > Thank you for your answers. Let me however make some comments: > > 1- the csv file was generated with Excel 2007; no prompts for what the > separator should be; Excel has used ";" by default, without asking > anything > Apparently it's possible, but it's a kludge http://astrochimp.com/2005/12/20/export-csv-with-any-delimiter/comment-page-1/ Anyways, ... > 2- about capitalisation, I used the var "spamReader" because I just > copy/pasted from the official python site: > > http://docs.python.org/library/csv.html > Oh, switcheroo! Well, those hypocrites! > 3- when I try > > >>> sheet = [row for row in spamReader] > >>> print sheet > [] > > all I get is an empty list; something seems not to be working properly > > Same result list: I get an empty list > > sheet = list(spamReader) > > Thank you again for your help, which is highly appreciated. > I'm assuming you do that after you've iterated over the file before? Because it did work in a previous post of yours. Here's the deal: When you iterate over a file (or read from it in any other manner) you "advance" in the file. After iteration, you're at the end, of course. So iterating again yields silch. Hmm ... don't know how that translates to a CSVReader. But I postulate that it'l work on a fresh run. /W -- INVALID? DE! From jgardner at jonathangardner.net Thu Aug 27 16:42:18 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 27 Aug 2009 13:42:18 -0700 (PDT) Subject: Does Class implements Interface? References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> Message-ID: <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> On Aug 27, 6:16?am, "Emanuele D'Arrigo" wrote: > Greetings everybody, > > let's say I have a Class C and I'd like to verify if it implements > Interface I. If I is available to me as a class object I can use > issubclass(C, I) and I can at least verify that I is a superclass of > C. There are a couple of issues with this approach however: > > 1) C might override not just I's methods code but also I's methods > signatures, effectively changing the interface. > 2) What if I is -not- available to me as the superclass of C but as a > description of the interface, i.e. as an IDL(*) file? > > Are there resources such as tools, recipes, documents or strategies > that could help me deal with these issues? I've already looked into > the ABC module and the zope.interface. I'm just fishing for more > things to look at. > Have you heard of duck typing? Ignore all those things and rely on human (aka natural language) documentation. That is, if you want to see if a class will work for an interface, go read the docs on the interface (or rather, what the function expects the interface to be) and what the class provides and see if they fit. From breamoreboy at yahoo.co.uk Thu Aug 27 16:44:17 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Thu, 27 Aug 2009 21:44:17 +0100 Subject: Question on the "csv" library In-Reply-To: <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> Message-ID: vsoler wrote: > On Aug 27, 9:42 pm, Andreas Waldenburger > wrote: >> On Thu, 27 Aug 2009 21:36:28 +0200 Andreas Waldenburger >> >> wrote: >>> [snip] >>> Might I humbly suggest >>>>>> sheet = list(spamReader) # ? >> Oh, and while I'm humbly suggesting: >> >> spam_reader instead of spamReader or SpamReader or SpamrEadeR or >> suchlike. Caps are "reserved" for classes. >> >> Not a necessity, of course. But it's the dialect around these parts. >> >> /W >> >> -- >> INVALID? DE! > > Thank you for your answers. Let me however make some comments: > > 1- the csv file was generated with Excel 2007; no prompts for what the > separator should be; Excel has used ";" by default, without asking > anything I find this difficult to believe, but assuming that you are correct then use the delimiter=';' argument in the call to csv.reader. See the csv module documentation section "Dialects and Formatting Parameters" for more information. > > 2- about capitalisation, I used the var "spamReader" because I just > copy/pasted from the official python site: > > http://docs.python.org/library/csv.html > > 3- when I try > >>>> sheet = [row for row in spamReader] >>>> print sheet > [] > > all I get is an empty list; something seems not to be working properly > > Same result list: I get an empty list > > sheet = list(spamReader) > > Thank you again for your help, which is highly appreciated. > > Vicente Soler -- Kindest regards. Mark Lawrence. From jgardner at jonathangardner.net Thu Aug 27 16:44:27 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 27 Aug 2009 13:44:27 -0700 (PDT) Subject: Learning Python advanced features References: <4a967864$0$15193$426a74cc@news.free.fr> Message-ID: <6b1a2aae-fd3d-40a8-9350-89a8661a6d4a@a37g2000prf.googlegroups.com> On Aug 27, 5:13?am, jvpic wrote: > Hi, > > Learning Python, I understand the mechanism of : closure, __new__, > descriptors, decorators and __metaclass__, but I interrogate myself on > the interest of those technics ? > > May somebody explain me the interest ? > I assume you are asking, "Why do these features exist? What makes them useful? When would I use them?" For that, you should re-read the documentation and discussion surrounding them. The short answer is that the above makes your job, as a programmer easier. It's easier because you have to write less code, read less code, and your code has fewer bugs. From tjreedy at udel.edu Thu Aug 27 16:57:44 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 27 Aug 2009 16:57:44 -0400 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: Terry Reedy wrote: > David House wrote: >> 2009/8/27 Terry Reedy : >>> reply-all may send duplicate messages to the author. Not sure of this >>> list. >> >> I'm fairly sure Mailman deals with that. > > Nope. I got a duplicate sent to my mailbox, which I hate. In particular, because there is no indication that it is an exact duplicate of what I will also find on the list itself. Please use reply instead of reply-all. From aahz at pythoncraft.com Thu Aug 27 17:05:05 2009 From: aahz at pythoncraft.com (Aahz) Date: 27 Aug 2009 14:05:05 -0700 Subject: Python on the Web References: Message-ID: In article , Phil wrote: > >My interest in Python 3.1 was actually to develop a framework. Again, >I can feel the flames. :) I understand there are enough frameworks but >I actually have no applications that I wish to develop. I enjoy >developing these kinds of things from scratch as a learning >experience. Well, there's a standard joke that just as people learning Scheme write a new language (following SICP), people learning Python write a new web framework. That's why there are so many of them. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From nbdarvin at gmail.com Thu Aug 27 17:06:19 2009 From: nbdarvin at gmail.com (Darvin) Date: Thu, 27 Aug 2009 14:06:19 -0700 (PDT) Subject: Python Telnet client Message-ID: <09ac1e4e-2c17-4174-9ff3-f07576532960@t13g2000yqt.googlegroups.com> Is there telnet client in python? i want to write NetHack telnet GUI app) From jakecjacobson at gmail.com Thu Aug 27 17:10:22 2009 From: jakecjacobson at gmail.com (jakecjacobson) Date: Thu, 27 Aug 2009 14:10:22 -0700 (PDT) Subject: How to unencode a string Message-ID: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> This seems like a real simple newbie question but how can a person unencode a string? In Perl I use something like: "$part=~ s/\%([A-Fa- f0-9]{2})/pack('C', hex($1))/seg;" If I have a string like Word1%20Word2%20Word3 I want to get Word1 Word2 Word3. Would also like to handle special characters like '",(){} [] etc/ From clp2 at rebertia.com Thu Aug 27 17:14:24 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Aug 2009 14:14:24 -0700 Subject: Python Telnet client In-Reply-To: <09ac1e4e-2c17-4174-9ff3-f07576532960@t13g2000yqt.googlegroups.com> References: <09ac1e4e-2c17-4174-9ff3-f07576532960@t13g2000yqt.googlegroups.com> Message-ID: <50697b2c0908271414l78a79b4dm14de9d6ba359804e@mail.gmail.com> On Thu, Aug 27, 2009 at 2:06 PM, Darvin wrote: > Is there telnet client in python? > i want to write NetHack telnet GUI app) http://docs.python.org/library/telnetlib.html Cheers, Chris -- http://blog.rebertia.com From aahz at pythoncraft.com Thu Aug 27 17:16:28 2009 From: aahz at pythoncraft.com (Aahz) Date: 27 Aug 2009 14:16:28 -0700 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> Message-ID: In article , Terry Reedy wrote: >David House wrote: >> 2009/8/27 Terry Reedy : >>> >>> reply-all may send duplicate messages to the author. Not sure of >>> this list. >> >> I'm fairly sure Mailman deals with that. > >Nope. I got a duplicate sent to my mailbox, which I hate. More precisely, there is a Mailman option per-list to suppress list sending of posts for which you are cc'd. I don't remember where, you should be able to find it by poking around the Mailman interface (or searching the docs). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From exarkun at twistedmatrix.com Thu Aug 27 17:18:41 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Thu, 27 Aug 2009 21:18:41 -0000 Subject: Python Telnet client In-Reply-To: <09ac1e4e-2c17-4174-9ff3-f07576532960@t13g2000yqt.googlegroups.com> References: <09ac1e4e-2c17-4174-9ff3-f07576532960@t13g2000yqt.googlegroups.com> Message-ID: <20090827211841.7475.756920895.divmod.xquotient.59@localhost.localdomain> On 09:06 pm, nbdarvin at gmail.com wrote: >Is there telnet client in python? >i want to write NetHack telnet GUI app) The Python stdlib has a module named telnetlib which offers rudamentary telnet support. Twisted includes twisted.conch.telnet which implements a much more complete telnet library. Twisted also includes twisted.conch.insults which provides basic terminal control functionality (so you can tell what nethack is trying to do over your telnet connection). Jean-Paul From ryniek90 at gmail.com Thu Aug 27 17:21:25 2009 From: ryniek90 at gmail.com (Ryniek90) Date: Thu, 27 Aug 2009 23:21:25 +0200 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile In-Reply-To: References: Message-ID: <4A96F8D5.5080709@gmail.com> > >>>>>> Ryniek90 (R) wrote: >>>>>> > > >> R> Hahah right. My fault. Must remember to read documentation so many times >> R> until I find the solution. Thanks, now works fine. :-) >> > > And, by the way, how come the traceback refers to > File "backuper.py", line 197, in > while the posted code has only 188 lines? > Cuz my original code is bit longer - i've got some bookkeepings like __author__, __version__ etc., just after module imports. From rt8396 at gmail.com Thu Aug 27 17:22:52 2009 From: rt8396 at gmail.com (r) Date: Thu, 27 Aug 2009 14:22:52 -0700 (PDT) Subject: An assessment of Tkinter and IDLE Message-ID: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> --------------------------------------------- Tkinter and IDLE Shortfalls --------------------------------------------- *The following is an assessment of Tkinter as i have experienced it. Even with all the problems i list below i strongly believe Tkinter is a great starter GUI toolkit and we (the Python Community), must keep and maintain this module for the foreseeable future. *However, as my assessment will reveal, much needs to be done to "freshen" up Tkinter and IDLE, and I am not just asking for someone to fix these problems. I have already coded solutions for most of them however, some of course still need work, and i would like to hear from others on this subject too. So buckle your seat belts folks, cause here we go... --------------------------------------------- Python offical docs and Tkinter --------------------------------------------- *The Python docs barely cover anything related to actual Tkinter coding. At the minimum the Tkinter doc page should have a subpage for all the widgets available --which is very small(approx 15) and each subpage should list the available methods on that wiget. Here are two great resources that really like from Fredrik Lundh and John Shipman... http://www.pythonware.com/library/tkinter/introduction/index.htm http://infohost.nmt.edu/tcc/help/pubs/tkinter/ ...I must say that I prefer the latter written by John Shipman because of the way he lists each widgets options in a nice table structure, and then lists the methods below. And intersestingly enough, his manual only weighs in at about 800kb completely uncommpressed and unedited. I'll bet you a wooden nickel i can reduce it to around 500kb for the official Python docs *wink* *Sadly however neither of these great works is mentioned or linked in the official docs Why?. *I think a short-and-to-the-point reference, like the afore mentioned along with a few links to full featured tuts would be a great addition to the Tkinter section of the official docs and i would be happy to help make this happen. --------------------------------------------- from Tkinter import * --------------------------------------------- *Too many noobs start out with the "from Tkinter import *" idiom, unknowing that they are horribly polluting their namespace. I feel that all (tkinter) code should follow the "import Tkinter as tk" policy and never use "from Tkinter import *". To push this agenda i propose all docs be modified so that no one should see such global import blasphemy again. We should at least keep all example code in the latter non-polluting form and frown heavily upon global imports in Tkinter code or any code for that matter. --------------------------------------------- Tkinter Constants --------------------------------------------- *The Tkconstants module needs to be removed *yesterday* because i think it reinforces sloppy coding styles. The main problem is with subtle bugs that are created when someone rebinds one or more of the constants, for example "W=20". At first i thought the constants were great but I quickly found out the shortfalls of such a Utopian approach . Since Tkinter allows strings to be passed-into widget constructors, we should remove the TkConstants immediately and force everyone to use strings instead... #-- instead of this --# w.pack(side=LEFT,fill=BOTH,anchor=W) #-- do this --# w.pack(side='left',fill='both',anchor='w') The few extra keystrokes are well worth the effort! --------------------------------------------- IDLE Shell --------------------------------------------- *IDLE and Pyshell are great but have major flaws in design. One of my biggest complaints is the shell's eight space indention which completely bloats your screen! Another annoying fact is that the prompt (>>>) is actually inside the text widget. This design is all wrong! The prompt should be in another widget to the left of the text so it never gets copied or pasted. Or at-least have the copy/paste action remove the initial four spaces and the prompt, but i think a full separation of "prompt" and "text" are the best solution. The following ASCII art won't win me any awards, but it may covey my idea. "W1" holds the prompt and "W2" is the actual text editor. <-------- W2 -----------> >>> | for x in range(10): | ... | print x | ... | for y in range(x): | ... | print y | |1 |2 And don't tell me about Geany or Pythonwin or emacs or vim or whatever editor happens to float your boat. I know there are tons of great editors out there but IDLE is most likely the first one a Pynoob will use so it must be usable! IDLE and Tkinter are what make Python a stater language -- after the beautiful syntax of course :) --------------------------------------------- IDLE Editor --------------------------------------------- *On M$ windows pressing the MMB without a motion causes the selected text to be pasted at the insertion cursor, and holding it repeats the action very quickly! Since IDLE has no horizontal scroll bar you must use MMB to scroll left-right. I am quite happy that there is no horizontal scrollbar since using MMB is much quicker, but the text pasting action always ruins my day :(. This pasting action is a real PITA and a waste of good processor time. I know how to override it with a hack in IDLE, but many newcomers won't and will probably get frustrated by it so this must be either fixed by hard coding IDLE or allowing a user to turn is off in the config options dialog. *Something that always gets a Python IDLE noob is "open-bracket-syntax- errors" in IDLE. When Python throws this type of error normally the only clue you will get from IDLE is to see the last line highlighted. However, the missing or misplaced bracket is usually no where near the end of the script. IDLE can be easily fixed to show a much closer or even exact location of the last open bracket. *The Find dialog forgets the regexp string after finding a match, this can be a real time waster especially if you typed in a long expression and need to tweak it just a bit for a second search! if the "regexp" check box is selected the dialog should not replace the contents of the Dialog.entry with the texts' selection. (easy fix) *The replace dialog seems buggy when doing a "replace+find". Sometimes it will highlight the next match but sometimes the highlight will immediately disappear so you can't be for sure what you may be replacing with the next push of the button? (could be a conflict with the colorizer) Real aggravating! This seems to always happen when a string is selected. *One of my all time pet peeves with all text editors. Everybody repeat after me... """NO TEXT EDITOR SHOULD EVER COPY AN EMPTY STRING TO THE CLIPBOARD!!""" ...I can't tell you how many times I've had to re-copy some text because i accidentally pressed instead of , arggh! This bug needs to be fixed yesterday! Pressing with no active selection should sound the error bell, not copy "". *Using the goto-line command should highlight the requested line. Currently all that IDLE does is place the insertion cursor at the start of the requested line which is completely useless. One more line of code in the goto method would make this action more useful --------------------------------------------- Tkinter Canvas --------------------------------------------- *The Tkinter Canvas widget should return (X,Y) pairs when calling canvas.coords(obj). The current implementation returns a flat array that is pretty much useless outside of canvas calls. Of course one could zip the coords into pairs, but it seems clumsy to call zip() on 2 LC's when Tkinter could, and should, do it for you. *Canvas needs a canvas.rotate() method for polygons, lines -- (easy). --------------------------------------------- Tkinter ComboBox -- where's Waldo? --------------------------------------------- *As much as i hate to support anything related to M$, Tkinter needs an M$ stlye combobox. Yes, I know Tix has combobox (*puke*), however using it is like pulling teeth. I have coded up an far more elegant/ simple solution -- and yes, i know about the OptionMenu widget which serves a useful purpose but is NOT a good replacement for a REAL M$ style combobox ;). *For instance, ComboBoxes need values that the user can select from, this is as universal as humans and oxygen. But sometimes you want to give the user a detailed set of values in the dropdown listbox and then insert an abbrieation of the value once selected, such as the case with state names... New Mexico -> MN California -> CA Florida -> FL ...instead of the laborious and wasteful convention of overriding a method to insert this value from a mapping each time why not just pass a pointer to the mapping into the constructor and create a combobox that actually knows how to walk and chew gum! [Warning: puesdo code ahead!] class ComboBox(master, values, etc..) def __init__(blahblahblah) self.values = values if type(values) == dict: self.values = values.keys()) listbox.load(self.values) def onUserPick(self, arg): if type(self.values) == dict: self.entry.set(self.values[arg]) return self.entry.set(arg) --------------------------------------------- Tix In General --------------------------------------------- *I am not a big fan of the Tix Module. The idea behind the widgets is great, but using most of them is a nightmare on elm street with Jason Voorhees in hot pursuit. I have hacked my own far more elegant versions of the more useful Tix Widgets and i feel mine are less buggy and more user friendly. So i say lose Tix and go with my fix, or get stuck with the Tix! *Python is missing good docs for Tix. The only thing i can find is the Tcl docs which are riddled with horribly cryptic tcl code. --------------------------------------------- Tix NoteBook --------------------------------------------- *The Tix.NoteBook widget has a bug. If you subclass Frame for your toplevel window you can't create a notebook widget as a descendant of the frame because it just blows chunks. The only way i have successfully used the widget is by the noobish style... >>> import Tix >>> root = Tix.Tk() >>> notebook = Tix.NoteBook...blah >>> root.mainloop() *Overall however i feel the IDLE "TabbedWidget" out-performs the Tix.NoteBook by miles and is easier to use, although it does have a few design problems that i have fixed. One of the most predominate being the inability to see the tabs clearly. The selected tab should "stand-out" from the others so a user can spot it quickly. Also there is no reason to export TabSet class and this can clean up the code a bit. --------------------------------------------- Tix ComboBox --------------------------------------------- *What is with that big ugly arrow? This widget is an exercise in cruelty to humans, and thats all i will say about it! --------------------------------------------- Final Thoughts --------------------------------------------- Well, that is all i can remember for now. If you've made it this far without losing your temper or your lunch well i am very surprised ;). Anyway, give me some feedback on these ideas so maybe i can get motivated to submit some patches/enhancements. psst... help is welcome too ya'know :) From kccnospam at glenevin.com Thu Aug 27 17:37:54 2009 From: kccnospam at glenevin.com (seanacais) Date: Thu, 27 Aug 2009 14:37:54 -0700 (PDT) Subject: variables of the class are not available as default values? Message-ID: I'm working on a program where I wish to define the default value of a method as a value that was set in __init__. I get a compilation error saying that self is undefined. As always a code snippet helps :-) class foo: def __init__(self, maxvalue): self.maxvalue = maxvalue self.value = 0 def put(self, value=self.maxvalue): self.value = value So if I call foo.put() the value is set to maxvalue but maxvalue can be specified when I instantiate foo. Explanations and/or workarounds much appreciated. python test.py Traceback (most recent call last): File "test.py", line 1, in class foo: File "test.py", line 6, in foo def put(self, value=self.maxvalue): NameError: name 'self' is not defined From clp2 at rebertia.com Thu Aug 27 17:44:53 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Aug 2009 14:44:53 -0700 Subject: variables of the class are not available as default values? In-Reply-To: References: Message-ID: <50697b2c0908271444t67b2c820pbcd0f6c82acaa832@mail.gmail.com> On Thu, Aug 27, 2009 at 2:37 PM, seanacais wrote: > I'm working on a program where I wish to define the default value of a > method as a value that was set in __init__. ?I get a compilation error > saying that self is undefined. > > As always a code snippet helps :-) > > class foo: > ? ?def __init__(self, maxvalue): > ? ? ? ?self.maxvalue = maxvalue > ? ? ? ?self.value = 0 > > ? ?def put(self, value=self.maxvalue): > ? ? ? ?self.value = value > > So if I call foo.put() the value is set to maxvalue but maxvalue can > be specified when I instantiate foo. > python test.py > Traceback (most recent call last): > File "test.py", line 1, in > class foo: > File "test.py", line 6, in foo > def put(self, value=self.maxvalue): > NameError: name 'self' is not defined > Explanations and/or workarounds much appreciated. Workaround: class foo: def __init__(self, maxvalue): self.maxvalue = maxvalue self.value = 0 def put(self, value=None): self.value = self.value if value is None else value Explanation: Default values are only evaluated once, when the class is defined, thus "self" is not defined at that point since the class is still being defined when the method definition is executed and thus there can be no instances yet anyway. Cheers, Chris -- http://blog.rebertia.com From andreengels at gmail.com Thu Aug 27 17:49:42 2009 From: andreengels at gmail.com (Andre Engels) Date: Thu, 27 Aug 2009 23:49:42 +0200 Subject: variables of the class are not available as default values? In-Reply-To: References: Message-ID: <6faf39c90908271449ic980813n56a9873913ee2af9@mail.gmail.com> On Thu, Aug 27, 2009 at 11:37 PM, seanacais wrote: > I'm working on a program where I wish to define the default value of a > method as a value that was set in __init__. ?I get a compilation error > saying that self is undefined. > > As always a code snippet helps :-) > > class foo: > ? ?def __init__(self, maxvalue): > ? ? ? ?self.maxvalue = maxvalue > ? ? ? ?self.value = 0 > > ? ?def put(self, value=self.maxvalue): > ? ? ? ?self.value = value > > So if I call foo.put() the value is set to maxvalue but maxvalue can > be specified when I instantiate foo. > > Explanations and/or workarounds much appreciated. Explanation: The default value is calculated at the time the function is defined, not at the time it is called. And at that time there is no instance for "self" to refer to. Workaround: class foo: def __init__(self, maxvalue): self.maxvalue = maxvalue self.value = 0 def put(self, value=None): if value is None: self.value = self.maxvalue else: self.value = value -- Andr? Engels, andreengels at gmail.com From clp2 at rebertia.com Thu Aug 27 17:49:50 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Aug 2009 14:49:50 -0700 Subject: How to unencode a string In-Reply-To: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> References: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> Message-ID: <50697b2c0908271449x1854d875ncdde2280b46ecdcc@mail.gmail.com> On Thu, Aug 27, 2009 at 2:10 PM, jakecjacobson wrote: > This seems like a real simple newbie question but how can a person > unencode a string? ?In Perl I use something like: "$part=~ s/\%([A-Fa- > f0-9]{2})/pack('C', hex($1))/seg;" > > If I have a string like Word1%20Word2%20Word3 I want to get Word1 > Word2 Word3. ?Would also like to handle special characters like '",(){} > [] etc/ Use the `uu` module together with the `stringio` module: http://docs.python.org/library/uu.html http://docs.python.org/library/stringio.html Not sure about special character handling though. Cheers, Chris -- http://blog.rebertia.com From mdekauwe at gmail.com Thu Aug 27 17:51:08 2009 From: mdekauwe at gmail.com (Mart.) Date: Thu, 27 Aug 2009 14:51:08 -0700 (PDT) Subject: regexp help References: <4e548d26-f3c9-46b8-a82a-c012607e2ff8@o6g2000yqj.googlegroups.com> Message-ID: <93ec85b5-907e-4504-968d-b14f1577debf@z38g2000yqh.googlegroups.com> On Aug 27, 7:15?pm, Bakes wrote: > If I were using the code: > > (?P[0-9]+) > > to get an integer between 0 and 9, how would I allow it to register > negative integers as well? -? From phily05 at gmail.com Thu Aug 27 18:02:41 2009 From: phily05 at gmail.com (Phil) Date: Thu, 27 Aug 2009 15:02:41 -0700 (PDT) Subject: Python on the Web References: Message-ID: <633c57f3-fb46-4d11-93c7-64a07ecd0844@32g2000yqj.googlegroups.com> Haha. While I don't disagree with you, I seem to be under the impression that you think I haven't been reading the web where nearly every blog post complains about the abundance of Python frameworks. The thing is, most of the frameworks being commented on in such a way are 'microframeworks' that provide next to nothing. I'm do not mean to say anything negative about them, but I strongly feel that my approach will be much more functional without having to include, or at least a good starting point for newcomers to both Python and web programming. The ideas I had for mine lied somewhere in between a full stack framework and a minimalist approach like said microframeworks. From python at mrabarnett.plus.com Thu Aug 27 18:05:03 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 Aug 2009 23:05:03 +0100 Subject: How to unencode a string In-Reply-To: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> References: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> Message-ID: <4A97030F.9000805@mrabarnett.plus.com> jakecjacobson wrote: > This seems like a real simple newbie question but how can a person > unencode a string? In Perl I use something like: "$part=~ s/\%([A-Fa- > f0-9]{2})/pack('C', hex($1))/seg;" > > If I have a string like Word1%20Word2%20Word3 I want to get Word1 > Word2 Word3. Would also like to handle special characters like '",(){} > [] etc/ The Python equivalent of your regular expression code is: >>> import re >>> s = "Word1%20Word2%20Word3" >>> re.sub(r"%([A-Fa-f0-9]{2})", lambda m: chr(int(m.group(1), 16)), s) 'Word1 Word2 Word3' The replacement is a lambda expression (an anonymous function), which is called for each match with the match object and it works like this: m # m is the match object m.group(1) # get group 1 (the 2 hex digits) int(m.group(1), 16) # convert to an integer chr(int(m.group(1), 16)) # convert to a character From manu3d at gmail.com Thu Aug 27 18:09:18 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Thu, 27 Aug 2009 15:09:18 -0700 (PDT) Subject: Does Class implements Interface? References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> Message-ID: On Aug 27, 9:42?pm, Jonathan Gardner wrote: > Have you heard of duck typing? Yes. > Ignore all those things and rely on human (aka natural language) > documentation. That is, if you want to see if a class will work for an > interface, go read the docs on the interface (or rather, what the > function expects the interface to be) and what the class provides and > see if they fit. Apologies, my fault, I didn't explain that humans are out of the loop entirely. It's only at runtime that the program obtains the class object that might or might not conform to an expected interface. In fact the program might obtain multiple objects and have to decide which one conforms best to the expected interface. Of course I could use hasattr() and the inspect module (anything else?) to find out if existing attributes and method signatures are those expected. Or I could just deal with the exceptions as they are raised. However, if I could somehow rely that the object I'm getting has the right methods and signatures I could avoid peppering the code with try/except constructs. I was just wondering then if this has been somewhat dealt with and has been wrapped in a neat package, set of functions, recipe or pattern. Manu From somebody at somewhere.com Thu Aug 27 18:16:14 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Thu, 27 Aug 2009 23:16:14 +0100 Subject: How to unencode a string References: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> Message-ID: jakecjacobson wrote: > This seems like a real simple newbie question but how can a person > unencode a string? In Perl I use something like: "$part=~ s/\%([A-Fa- > f0-9]{2})/pack('C', hex($1))/seg;" > > If I have a string like Word1%20Word2%20Word3 I want to get Word1 > Word2 Word3. Would also like to handle special characters like '",(){} > [] etc/ import urllib print urllib.unquote("Word1%20Word2%20Word3") -- Stephen Fairchild From jgardner at jonathangardner.net Thu Aug 27 18:22:33 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 27 Aug 2009 15:22:33 -0700 (PDT) Subject: Does Class implements Interface? References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> Message-ID: On Aug 27, 3:09?pm, "Emanuele D'Arrigo" wrote: > > Apologies, my fault, No apology is necessary. > I didn't explain that humans are out of the loop > entirely. It's only at runtime that the program obtains the class > object that might or might not conform to an expected interface. In > fact the program might obtain multiple objects and have to decide > which one conforms best to the expected interface. Of course I could > use hasattr() and the inspect module (anything else?) to find out if > existing attributes and method signatures are those expected. Or I > could just deal with the exceptions as they are raised. However, if I > could somehow rely that the object I'm getting has the right methods > and signatures I could avoid peppering the code with try/except > constructs. > > I was just wondering then if this has been somewhat dealt with and has > been wrapped in a neat package, set of functions, recipe or pattern. > Don't bother with introspection using hasattr() and such. Use exceptions. If the object that is instantiated at run-time doesn't provide the right interface, throw an exception and direct it to the responsible party. This isn't much different than what you'd do if you're writing an app that expects a string of digits but is instead given a string of non- digits. Rather than inspecting the string before converting it (introspection), just try to convert it and catch the exception. Then handle the exception such that you tell the person who entered the data, "I wanted numbers, not letters" and allow them to try again. When you stop asking "Did I get something I expect?" except only when it is absolutely necessary, then you can get back to writing your program. From jgardner at jonathangardner.net Thu Aug 27 18:25:09 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Thu, 27 Aug 2009 15:25:09 -0700 (PDT) Subject: Does Class implements Interface? References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> Message-ID: <83dc3cba-a6f5-46ef-8a43-119b78be622d@v15g2000prn.googlegroups.com> On Aug 27, 3:09?pm, "Emanuele D'Arrigo" wrote: > On Aug 27, 9:42?pm, Jonathan Gardner > wrote: > > > Have you heard of duck typing? > > Yes. > > I was just wondering then if this has been somewhat dealt with and has > been wrapped in a neat package, set of functions, recipe or pattern. > As a joke (but only partly), here's the python code you'd use to check to see if a value conforms with expectations: As you can see, the above code is not only easy to write, but easy to write unit tests for, compile, run, and debug. It simply doesn't get better than this. From kccnospam at glenevin.com Thu Aug 27 18:29:53 2009 From: kccnospam at glenevin.com (seanacais) Date: Thu, 27 Aug 2009 15:29:53 -0700 (PDT) Subject: variables of the class are not available as default values? References: Message-ID: On Aug 27, 5:44?pm, Chris Rebert wrote: > On Thu, Aug 27, 2009 at 2:37 PM, seanacais wrote: > > I'm working on a program where I wish to define the default value of a > > method as a value that was set in __init__. ?I get a compilation error > > saying that self is undefined. > > > As always a code snippet helps :-) > > > class foo: > > ? ?def __init__(self, maxvalue): > > ? ? ? ?self.maxvalue = maxvalue > > ? ? ? ?self.value = 0 > > > ? ?def put(self, value=self.maxvalue): > > ? ? ? ?self.value = value > > > So if I call foo.put() the value is set to maxvalue but maxvalue can > > be specified when I instantiate foo. > > python test.py > > Traceback (most recent call last): > > ?File "test.py", line 1, in > > ? ?class foo: > > ?File "test.py", line 6, in foo > > ? ?def put(self, value=self.maxvalue): > > NameError: name 'self' is not defined > > Explanations and/or workarounds much appreciated. > > Workaround: > > class foo: > ? ? def __init__(self, maxvalue): > ? ? ? ? self.maxvalue = maxvalue > ? ? ? ? self.value = 0 > > ? ? def put(self, value=None): > ? ? ? ? self.value = self.value if value is None else value > > Explanation: > > Default values are only evaluated once, when the class is defined, > thus "self" is not defined at that point since the class is still > being defined when the method definition is executed and thus there > can be no instances yet anyway. > > Cheers, > Chris > --http://blog.rebertia.com That clears that up for me. Thank you! From find.mig at paa.google Thu Aug 27 18:31:15 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Fri, 28 Aug 2009 00:31:15 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a92b290$0$305$14726298@news.sunsite.dk> <4a93e575$0$298$14726298@news.sunsite.dk> <4a95961d$0$300$14726298@news.sunsite.dk> Message-ID: <4a970942$0$334$14726298@news.sunsite.dk> Dennis Lee Bieber wrote: > > The only other thing I could suggest is exactly what is done on: > http://pys60.garage.maemo.org/doc/s60/node59.html > > Initialize a counter value to 0, then increment it in the callback, > only doing REAL work every n calls. > > > def doCallback(self): > if self.count % 35 == 0: #doc says 35 hits/second, so this > self.data_callback() #will run one once per second > self.count += 1 > > You'll still get that slew of backlogged callbacks that built up > while doing the real processing, but unless self.data_callback() takes > more time than the "35" covers, most of the callbacks will just come in > and exit with an increment. Of course I can do that. But it'll only make a noticable delay EVERY time the user moves, and not prevent the build up of calls if it doesn't finish within the 35 callbacks. The point is that I don't know in advance, how long the call will take. It depends on the amount of data i load and process during the call. I only know when the calculations have finished, and when they are called, and think there might be some way to block further callbacks until the first one returns? From find.mig at paa.google Thu Aug 27 18:42:16 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Fri, 28 Aug 2009 00:42:16 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a9595ca$0$300$14726298@news.sunsite.dk> Message-ID: <4a970bd7$0$333$14726298@news.sunsite.dk> Hendrik van Rooyen wrote: > > Hmm - now I am really starting to fly by the seat of my pants - but it looks > as if your problem is that your routine is basically being called faster than > what it can do the processing. > > So what I would try is to define a global (you should really acquire a lock, > but forget that for the moment) So lets call this thing running_calculation. > > Then you set this in the routine just before the after call, and reset it just > before exiting the calculation routine, and if it is set when you get into > the first routine, then you just exit, without doing the after. This should > have the effect of skipping some calls, to make it all manageable. Then you > should (hopefully) not have the duplication that it looks to me like you are > now having. > > Bye the way, make the time short - like 1 - it could also be that the time is > now so long before you start calculating, that you do not have a snowball's > hope in hell to be finished before the next value comes in. > OK, now things starts to make sense. You tell me to do something like this? def doCallback(self): if self.process_busy==False: self.process_busy=True self.at.after(0.01,self.data_callback) def doneCallback(self): self.process_busy=False And the after command will cause python to spawn a new thread, which runs self.data_callback, which measn that the doCallback will return immediately, so the next callback from accelerometer can be processed? And when the self.data_callback() finishes, i'd make it call the doneCallback() to release my busy flag, right? I'm gonna try this tomorrow :) From somebody at somewhere.com Thu Aug 27 18:43:30 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Thu, 27 Aug 2009 23:43:30 +0100 Subject: Does Class implements Interface? References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> Message-ID: <6fidnfxppNqOkQrXnZ2dnUVZ8uydnZ2d@giganews.com> Emanuele D'Arrigo wrote: > Apologies, my fault, I didn't explain that humans are out of the loop > entirely. It's only at runtime that the program obtains the class > object that might or might not conform to an expected interface. In > fact the program might obtain multiple objects and have to decide > which one conforms best to the expected interface. Of course I could > use hasattr() and the inspect module (anything else?) to find out if > existing attributes and method signatures are those expected. Or I > could just deal with the exceptions as they are raised. However, if I > could somehow rely that the object I'm getting has the right methods > and signatures I could avoid peppering the code with try/except > constructs. > > I was just wondering then if this has been somewhat dealt with and has > been wrapped in a neat package, set of functions, recipe or pattern. http://docs.python.org/library/abc.html In particular, pay attention to the term virtual subclass and also note in the second code example the use of __subclasshook__ to define virtual subclass membership by the presence (or not) of class attributes. -- Stephen Fairchild From piet at cs.uu.nl Thu Aug 27 18:45:13 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 28 Aug 2009 00:45:13 +0200 Subject: TypeError: _getfullpathname() argument 1 must be (buffer overflow), not str in windows xp, while making tarfile References: Message-ID: >>>>> Ryniek90 (R) wrote: >>> >>>>>>>> Ryniek90 (R) wrote: >>>>>>>> >>> >>> >R> Hahah right. My fault. Must remember to read documentation so many times >R> until I find the solution. Thanks, now works fine. :-) >>>> >>> >>> And, by the way, how come the traceback refers to >>> File "backuper.py", line 197, in >>> while the posted code has only 188 lines? >>> >R> Cuz my original code is bit longer - i've got some bookkeepings like >R> __author__, __version__ etc., just after module imports. That can be very confusing for people that want to help you. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From piet at cs.uu.nl Thu Aug 27 18:51:55 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 28 Aug 2009 00:51:55 +0200 Subject: How to unencode a string References: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> Message-ID: >>>>> jakecjacobson (j) wrote: >j> This seems like a real simple newbie question but how can a person >j> unencode a string? In Perl I use something like: "$part=~ s/\%([A-Fa- >j> f0-9]{2})/pack('C', hex($1))/seg;" >j> If I have a string like Word1%20Word2%20Word3 I want to get Word1 >j> Word2 Word3. urllib.unquote(string) >j> Would also like to handle special characters like '",(){} >j> [] etc/ What would you like to do with them? Or do you mean to replace %27 by ' etc? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From python at mrabarnett.plus.com Thu Aug 27 18:58:06 2009 From: python at mrabarnett.plus.com (MRAB) Date: Thu, 27 Aug 2009 23:58:06 +0100 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a970942$0$334$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a92b290$0$305$14726298@news.sunsite.dk> <4a93e575$0$298$14726298@news.sunsite.dk> <4a95961d$0$300$14726298@news.sunsite.dk> <4a970942$0$334$14726298@news.sunsite.dk> Message-ID: <4A970F7E.9070006@mrabarnett.plus.com> Esben von Buchwald wrote: > Dennis Lee Bieber wrote: >> >> The only other thing I could suggest is exactly what is done on: >> http://pys60.garage.maemo.org/doc/s60/node59.html >> >> Initialize a counter value to 0, then increment it in the callback, >> only doing REAL work every n calls. >> >> >> def doCallback(self): >> if self.count % 35 == 0: #doc says 35 hits/second, so this >> self.data_callback() #will run one once per second >> self.count += 1 >> >> You'll still get that slew of backlogged callbacks that built up >> while doing the real processing, but unless self.data_callback() takes >> more time than the "35" covers, most of the callbacks will just come in >> and exit with an increment. > > Of course I can do that. > > > But it'll only make a noticable delay EVERY time the user moves, and not > prevent the build up of calls if it doesn't finish within the 35 callbacks. > > The point is that I don't know in advance, how long the call will take. > It depends on the amount of data i load and process during the call. > I only know when the calculations have finished, and when they are > called, and think there might be some way to block further callbacks > until the first one returns? You could record when your callback finishes (is about to return) and then ignore any callback that happens too soon after that: def doCallback(self): now = time.time() if now - self.last_call >= MIN_TIME: self.data_callback() now = time.time() self.last_call = now From clp2 at rebertia.com Thu Aug 27 19:05:04 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Aug 2009 16:05:04 -0700 Subject: How to unencode a string In-Reply-To: <50697b2c0908271449x1854d875ncdde2280b46ecdcc@mail.gmail.com> References: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> <50697b2c0908271449x1854d875ncdde2280b46ecdcc@mail.gmail.com> Message-ID: <50697b2c0908271605h1055dfd7qc786a7e0e067f4a5@mail.gmail.com> On Thu, Aug 27, 2009 at 2:49 PM, Chris Rebert wrote: > On Thu, Aug 27, 2009 at 2:10 PM, jakecjacobson wrote: >> This seems like a real simple newbie question but how can a person >> unencode a string? ?In Perl I use something like: "$part=~ s/\%([A-Fa- >> f0-9]{2})/pack('C', hex($1))/seg;" >> >> If I have a string like Word1%20Word2%20Word3 I want to get Word1 >> Word2 Word3. ?Would also like to handle special characters like '",(){} >> [] etc/ > > Use the `uu` module together with the `stringio` module: > http://docs.python.org/library/uu.html > http://docs.python.org/library/stringio.html > > Not sure about special character handling though. Ah, I misread our post in haste. Please disregard my reply. - Chris From python at mrabarnett.plus.com Thu Aug 27 19:05:37 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 28 Aug 2009 00:05:37 +0100 Subject: Protecting against callbacks queuing up? In-Reply-To: <4A970F7E.9070006@mrabarnett.plus.com> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a92b290$0$305$14726298@news.sunsite.dk> <4a93e575$0$298$14726298@news.sunsite.dk> <4a95961d$0$300$14726298@news.sunsite.dk> <4a970942$0$334$14726298@news.sunsite.dk> <4A970F7E.9070006@mrabarnett.plus.com> Message-ID: <4A971141.6050402@mrabarnett.plus.com> MRAB wrote: > Esben von Buchwald wrote: >> Dennis Lee Bieber wrote: >>> >>> The only other thing I could suggest is exactly what is done on: >>> http://pys60.garage.maemo.org/doc/s60/node59.html >>> >>> Initialize a counter value to 0, then increment it in the callback, >>> only doing REAL work every n calls. >>> >>> >>> def doCallback(self): >>> if self.count % 35 == 0: #doc says 35 hits/second, so this >>> self.data_callback() #will run one once per second >>> self.count += 1 >>> >>> You'll still get that slew of backlogged callbacks that built up >>> while doing the real processing, but unless self.data_callback() takes >>> more time than the "35" covers, most of the callbacks will just come in >>> and exit with an increment. >> >> Of course I can do that. >> >> >> But it'll only make a noticable delay EVERY time the user moves, and >> not prevent the build up of calls if it doesn't finish within the 35 >> callbacks. >> >> The point is that I don't know in advance, how long the call will >> take. It depends on the amount of data i load and process during the >> call. >> I only know when the calculations have finished, and when they are >> called, and think there might be some way to block further callbacks >> until the first one returns? > > You could record when your callback finishes (is about to return) and > then ignore any callback that happens too soon after that: > > def doCallback(self): > now = time.time() > if now - self.last_call >= MIN_TIME: > self.data_callback() > now = time.time() > self.last_call = now After a little more thought, I think that should be: def doCallback(self): if time.time() - self.last_call >= MIN_TIME: self.data_callback() self.last_call = time.time() From kkumNOTTHISer at thatsearchenginesguglsemail.com Thu Aug 27 19:05:41 2009 From: kkumNOTTHISer at thatsearchenginesguglsemail.com (Kreso) Date: Thu, 27 Aug 2009 23:05:41 +0000 (UTC) Subject: Algorithms as objects? Message-ID: I am writing an application that essentially calculates set of numbers, say N1, N2, ..., where they can be calculated by several different algorithms. (One should be able to choose the algorithm at run time.) In each algorithm one starts from a set of functions, say f1, f2, ..., which are then transformed into some other functions g1(f1, f2, ..), g2(f1, f2, ...), ... , then maybe transformed once more and result is obtained by evaluating final functions. I can naturally think about this as a collection of transformation blocks, which have functions as input and output, and which can be put together to get the final results. However, I am not sure how to program this, especially since one cannot subclass function type. To be clear let me give simplified example of what is needed: f(x) has unknown shape, so one would like to try, say f1(x) = ax - b x**2 or f2(x) = a sin(b*x), where a and b are variable parameters. Then, one would like to create, with known k(x,y), function g(x) in one of two ways: g1(x) = k(x, x)*f(x) or g2(x) = integrate(k(x, y) * f(y), y=0..1), and finally evaluate N=g(1) as result. In this simple example there are 4 different algorithms for f(x) -> g(x) -> N, and one should be able to simply choose between them, e.g. by calling N(g1, f2, (a,b)). In practice algorithm is not necessary so linear, but is generally tree-lika: (a,b) -> f1(x) --->g1(x)---+ |--> h(x) --> N (c,d) ---+--> g2(x)--------+ | f2(x) --+ It would be nice to have some class of function-objects, that f1(x), .., g1(x), ... could be members/instances of so that common operations on these functions could be possible (checking that they satisfy some necessary properties, plotting them, ...), and then second "class" of transformations/methods operating on these objects. I seem to be confused by the fact that I would like to somehow treat algorithms as objects (so that one can experiment with different algorithm systems) but I don't have clear picture how to do it. I am just brainstorming for ideas. Any advice is welcome. From clp2 at rebertia.com Thu Aug 27 19:14:35 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Aug 2009 16:14:35 -0700 Subject: Algorithms as objects? In-Reply-To: References: Message-ID: <50697b2c0908271614q6609884aw36de8ef27b97d930@mail.gmail.com> On Thu, Aug 27, 2009 at 4:05 PM, Kreso wrote: > > I am writing an application that essentially calculates set of numbers, > say N1, N2, ..., where they can be calculated by several different > algorithms. (One should be able to choose the algorithm at run time.) > In each algorithm one starts from a set of functions, say f1, f2, ..., > which are then transformed into some other functions g1(f1, f2, ..), > g2(f1, f2, ...), ... , then maybe transformed once more and result is > obtained by evaluating final functions. > ?I can naturally think about this as a collection of transformation > blocks, which have functions as input and output, and which can be > put together to get the final results. However, I am not sure > how to program this, especially since one cannot subclass function > type. To be clear let me give simplified example of what is needed: > > f(x) has unknown shape, so one would like to try, say > > f1(x) = ax - b x**2 ? or ? ?f2(x) = a sin(b*x), > > where a and b are variable parameters. > > Then, one would like to create, with known k(x,y), function g(x) > in one of two ways: > > g1(x) = k(x, x)*f(x) ?or ? g2(x) = integrate(k(x, y) * f(y), y=0..1), > > and finally evaluate N=g(1) as result. In this simple example > there are 4 different algorithms ?for f(x) -> g(x) -> N, and one > should be able to simply choose between them, e.g. by calling > N(g1, f2, (a,b)). > > In practice algorithm is not necessary so linear, ?but is > generally tree-lika: > > (a,b) -> f1(x) --->g1(x)---+ > ? ? ? ? ? ? ? ? ? ? ? ? ? |--> h(x) --> N > (c,d) ---+--> g2(x)--------+ > ? ? ? ? | > ?f2(x) --+ > > > It would be nice to have some class of function-objects, > that f1(x), .., g1(x), ... could be members/instances of so that common > operations on these functions could be possible (checking > that they satisfy some necessary properties, plotting them, ...), > and then second "class" of transformations/methods operating on > these objects. > I seem to be confused by the fact that I would like to somehow treat > algorithms as objects (so that one can experiment with different > algorithm systems) but I don't have clear picture how to do it. > I am just brainstorming for ideas. Any advice is welcome. It sounds like you're describing the Strategy Pattern (http://en.wikipedia.org/wiki/Strategy_pattern). To have objects callable like functions, just implement the __call__ special method in your class(es): http://docs.python.org/reference/datamodel.html#object.__call__ Cheers, Chris -- http://blog.rebertia.com From mensanator at aol.com Thu Aug 27 19:19:26 2009 From: mensanator at aol.com (Mensanator) Date: Thu, 27 Aug 2009 16:19:26 -0700 (PDT) Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> Message-ID: <4ee81a75-e22d-4bf7-8b40-b883cc6e69c6@k30g2000yqf.googlegroups.com> On Aug 27, 2:26?pm, Piet van Oostrum wrote: > >>>>> Mensanator (M) wrote: > >M> On Aug 26, 4:59?pm, Piet van Oostrum wrote: > >>> >>>>> Mensanator (M) wrote: > >>> >M> That's my point. Since the common usage of "binary" is for > >>> >M> Standard Positional Number System of Radix 2, it follows > >>> >M> that "unary" is the common usage for Standard Positional > >>> >M> Number System of Radix 1. That's VERY confusing since such > >>> >M> a system is undefined. Remember, common usage does not > >>> >M> necessarily properly define things. Saying simply "unary" > >>> >M> sounds like you're extending common usage beyond its proper > >>> >M> boundaries. > > >>> But the customary meaning of `unary' is the tally system, as a radix > >>> system wouldn't make sense. I don't know when this term came into use > >>> but I have known it for a long time. > >M> Ok, I'll accept that and in the same breath say such common usage > >M> is stupid. I, for one, have never heard such usage and would never > >M> use "unary" in the same breath as "decimal, octal, binary" even if > >M> I had. > > As I see it, unary just means that there is one symbol. Binary just > means that there are two symbols, etc. Right, and neither word, by itself, gives the full meaning. > > With unary, the only sensible numerical interpretation is to count the > number of occurrences of that symbol, or if you also want to have the > number 0, the number of occurrences - 1. Trouble is, nothing's stopping you from making a non-sensible interpretation. > > With binary and higher you can come up with more numerical > interpretations but the most efficient one is the radix interpretation > (for different values of `efficient'). I doubt that there are many other > interpretations that you can call sensible. But not impossible. You could have a base-3 tally system for ticking off how many cars on a three lane road pass a given point. And you can have mixed radix systems (pounds, shillings, pence or degrees, minutes seconds). > Therefore we immediately > think of a radix system when we talk about binary, octal, decimal etc. > But the word `binary' itself doesn't imply that. Just as unary doesn't imply that it's an extension of binary made by simply changing the base because there's more to it than that. Yet, I constantly run into people who get confused by this. As a result, I will never use the word "unary" even if it is considered acceptable. If I'm trying to imply some sort of base-1 system, I'll explain what I'm talking about and not assume the listener will fully understand what is meant by "unary". > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org From barcaroller at music.net Thu Aug 27 19:20:00 2009 From: barcaroller at music.net (barcaroller) Date: Thu, 27 Aug 2009 19:20:00 -0400 Subject: PyGTK problems after Linux update... Message-ID: I use a python-based program called 'meld' which worked fine until my latest Fedora11/KDE4.3 update; it now gives me the following error: prompt> meld /usr/lib/python2.6/site-packages/gtk-2.0/glib/_glib.so: undefined symbol: PyUnicodeUCS4_DecodeUTF8 Meld requires pygtk 2.8.0 or higher. If I run another GTK-based utility, I also get errors: prompt> gedit ** (gedit:28289): WARNING **: Error initializing Python interpreter: could not import pygtk. I have installed the latest PyGTK (pygtk-2.14.1), to no avail. Googling these messages have also produced no major results. When I run 'pygtk-demo', I get the following errors: prompt> python /usr/lib/pygtk/2.0/pygtk-demo.py Traceback (most recent call last): File "/usr/lib/pygtk/2.0/pygtk-demo.py", line 18, in import gobject File "/usr/lib/python2.6/site-packages/gtk-2.0/gobject/__init__.py", line 33, in from glib import spawn_async, idle_add, timeout_add, timeout_add_seconds, \ File "/usr/lib/python2.6/site-packages/gtk-2.0/glib/__init__.py", line 30, in from glib._glib import * ImportError: /usr/lib/python2.6/site-packages/gtk-2.0/glib/_glib.so: undefined symbol: PyUnicodeUCS4_DecodeUTF8 Does anyone know what needs to be done to resolve this? Using Python 2.6.2 on Fedora11/KDE4.3 32-bit i386/i586/i686. From upton at virginia.edu Thu Aug 27 19:35:04 2009 From: upton at virginia.edu (Dan Upton) Date: Thu, 27 Aug 2009 16:35:04 -0700 Subject: printing from child process in Tkinter window Message-ID: <5504f9ac0908271635j1926850y45c048f41c1ef0e@mail.gmail.com> Hi all, I've been messing with this for a couple hours now but can't make it work. Basically I have a Tkinter GUI that creates a child process via subprocess.Popen, and I would like to capture the child process's output to display it in a Text widget in the GUI. Relevant snippets: def click_start: #launch from clicking a button in the gui ... self.apppipe = Popen(cmdString, shell=True, stdout=PIPE, stderr=PIPE) self.master.after(200, self.readAppStdout) ... def readAppStdout(self): readers, writers, exceptionals = select.select( [self.apppipe.stdout], [], [], 0.001) if readers != []: pipetext = self.apppipe.stdout.readline() self.appoutput.insert(END, pipetext) #self.appoutput is the Text widget (same for apppipe.stderr) self.master.after(200, self.readAppStdout) I don't ever get any output in my window, even though I've waited long enough that the application would otherwise have printed to the console (based on its graphical outputs). Any suggestions for what I'm doing wrong? -dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From hjtoi-better-remove-before-reply at comcast.net Thu Aug 27 19:43:40 2009 From: hjtoi-better-remove-before-reply at comcast.net (Heikki Toivonen) Date: Thu, 27 Aug 2009 16:43:40 -0700 Subject: ANN: M2Crypto 0.20.1 Message-ID: M2Crypto is the most complete Python wrapper for OpenSSL featuring RSA, DSA, DH, HMACs, message digests, symmetric ciphers (including AES); SSL functionality to implement clients and servers; HTTPS extensions to Python's httplib, urllib, and xmlrpclib; unforgeable HMAC'ing AuthCookies for web session management; FTP/TLS client and server; S/MIME; ZServerSSL: A HTTPS server for Zope and ZSmime: An S/MIME messenger for Zope. Smartcards supported with the Engine interface. This is the 0.20.1 release. Download links and bug filing instructions on the homepage at http://chandlerproject.org/Projects/MeTooCrypto. Changelog: - Fix regression in httpslib.ProxyHTTPSConnection, by Miloslav Trmac -- Heikki Toivonen - http://heikkitoivonen.net From no.email at please.post Thu Aug 27 19:49:27 2009 From: no.email at please.post (kj) Date: Thu, 27 Aug 2009 23:49:27 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: Miles Kaufmann writes: >On Aug 26, 2009, at 1:11 PM, kj wrote: >> I think I understand the answers well enough. What I *really* >> don't understand is why this particular "feature" of Python (i.e. >> that functions defined within a class statement are forbidden from >> "seeing" other identifiers defined within the class statement) is >> generally considered to be perfectly OK. IMO it's a bizarre, >> inexplicable blindspot (which, among other things, gives rise to >> a certain worry about what other similar craziness lurks under >> Python's image of rationality). I have never seen even a half-hearted >> justification, from a language design point of view, for why this >> particular "feature" is worth having. >Guido's design justifications: >http://mail.python.org/pipermail/python-dev/2000-November/010598.html Ah! Clarity! Thanks! How did you find this? Did you know of this post already? Or is there some special way to search Guido's "design justifications"? >...because the suite >namespace and the class namespace would get out of sync when different >objects were assigned to the class namespace: >class C: > x = 1 > def foo(self): > print x > print self.x > >>> o = C() > >>> o.foo() >1 >1 > >>> o.x = 2 > >>> o.foo() >1 >2 But this unfortunate situation is already possible, because one can already define class C: x = 1 def foo(self): print C.x print self.x which would lead to exactly the same thing. I need to learn more about metaclasses, though, to fully understand your post. Many thanks! kynn From bearophileHUGS at lycos.com Thu Aug 27 20:00:36 2009 From: bearophileHUGS at lycos.com (Bearophile) Date: Thu, 27 Aug 2009 17:00:36 -0700 (PDT) Subject: Algorithms as objects? References: Message-ID: <9bd48179-a356-4d7f-8057-f68db29d6cad@a13g2000yqc.googlegroups.com> Chris Rebert: > It sounds like you're describing the Strategy Pattern > (http://en.wikipedia.org/wiki/Strategy_pattern). > > To have objects callable like functions, just implement the ?__call__ > special method in your class(es): Please, can't you just use a bit of functional-style programming? Like creating nested functions on the fly, etc. Bye, bearophile From doctoresam at gmail.com Thu Aug 27 20:34:17 2009 From: doctoresam at gmail.com (Deep_Feelings) Date: Thu, 27 Aug 2009 17:34:17 -0700 (PDT) Subject: why python got less developers ? Message-ID: python got relatively fewer numbers of developers than other high level languages like .NET , java .. etc why ? From mwilson at the-wire.com Thu Aug 27 20:39:56 2009 From: mwilson at the-wire.com (Mel) Date: Thu, 27 Aug 2009 20:39:56 -0400 Subject: Annoying octal notation References: <0018e1a0$0$2938$c3e8da3@news.astraweb.com> <02a0ce27$0$30337$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano wrote: > Leading zeroes in decimal numbers are *very* common in dates and times. In banking too, according to someone at work today. Mel. From clp2 at rebertia.com Thu Aug 27 20:46:36 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Thu, 27 Aug 2009 17:46:36 -0700 Subject: why python got less developers ? In-Reply-To: References: Message-ID: <50697b2c0908271746v7116a1ffo62d5dced879a2c6a@mail.gmail.com> On Thu, Aug 27, 2009 at 5:34 PM, Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc ?why ? We lack Sun and Microsoft's massive marketing departments. :) Cheers, Chris -- http://blog.rebertia.com From python at mrabarnett.plus.com Thu Aug 27 20:47:51 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 28 Aug 2009 01:47:51 +0100 Subject: why python got less developers ? In-Reply-To: References: Message-ID: <4A972937.9070405@mrabarnett.plus.com> Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc why ? Fewer needed? From gherron at islandtraining.com Thu Aug 27 20:49:02 2009 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 27 Aug 2009 17:49:02 -0700 Subject: why python got less developers ? In-Reply-To: References: Message-ID: <4A97297E.9020607@islandtraining.com> Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc why ? > Perhaps because we value QUALITY over QUANTITY ... Gary Herron From rurpy at yahoo.com Thu Aug 27 20:49:26 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Thu, 27 Aug 2009 17:49:26 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> Message-ID: <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> On 08/26/2009 11:51 PM, "Martin v. L?wis" wrote: >[...] >> But regardless, the significant question is, what is >> the reason for having ord() (and unichr) not work for >> surrogate pairs and thus not usable with a large number >> of unicode characters that Python otherwise supports? > > See PEP 261, http://www.python.org/dev/peps/pep-0261/ > It specifies all this. The PEP (AFAICT) says only what we already know... that on narrow builds unichr() will raise an exception with an argument >= 0x10000, and ord() is unichr()'s inverse. I have read the PEP twice now and still see no justification for that decision, it appears to have been made by fiat.[*1] Could you or someone please point me to specific justification for having unichr and ord work only for a subset of unicode characters on narrow builds, as opposed to the more general and IMO useful behavior proposed earlier in this thread? ---------------------------------------------------------- [*1] The PEP says: * unichr(i) for 0 <= i < 2**16 (0x10000) always returns a length-one string. * unichr(i) for 2**16 <= i <= TOPCHAR will return a length-one string on wide Python builds. On narrow builds it will raise ValueError. and * ord() is always the inverse of unichr() which of course we know; that is the current behavior. But there is no reason given for that behavior. Under the second *unicode bullet point, there are two issues raised: 1) Should surrogate pairs be disallowed on narrow builds? That appears to have been answered in the negative and is not relevant to my question. 2) Should access to code points above TOPCHAR be allowed? Not relevant to my question. * every Python Unicode character represents exactly one Unicode code point (i.e. Python Unicode Character = Abstract Unicode character) I'm not sure what this means (what's an abstract unicode character?). If it mandates that u'\ud800\udc40' be treated as a len() 2 string, that is that current case but does not say anything about how unichr and ord should behave. If it mandates that that string must always be treated as two separate code points then Python itself violates by printing that string as u'\U00010040' rather than u'\ud800\udc40'. Finally we read: * There is a convention in the Unicode world for encoding a 32-bit code point in terms of two 16-bit code points. These are known as "surrogate pairs". Python's codecs will adopt this convention. Is a distinction made between Python and Python codecs with only the latter having any knowledge of surrogate pairs? I guess that would explain why Python prints a surrogate pair as a single character. But this seems arbitrary and counter-useful if applied to ord() and unichr(). What possible use-case is there for *not* recognizing surrogate pairs in those two functions? Nothing else in the PEP seems remotely relevant. From ben+python at benfinney.id.au Thu Aug 27 20:55:35 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 28 Aug 2009 10:55:35 +1000 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: <87bpm0daew.fsf@benfinney.id.au> Terry Reedy writes: > In particular, because there is no indication that it is an exact > duplicate of what I will also find on the list itself. Please use > reply instead of reply-all. Better: If you don't want to reply to the author directly, and you don't want to reply to everyone, don't use ?reply to author? or ?reply to all?. When replying to the list, use the ?reply to list? command of your mail client. This will, in a standards-compliant mail client, reply to the posting address for the list (declared in the message header via the RFC 2369 ?List-Post? field, added automatically by every common mailing list system), without a copy to the sender. Thunderbird has a long-outstanding bug report requesting this feature , which is apparently fixed in recent versions. Before that bug was fixed, an add-on was developed to add it in a different way. If you're using a different mail client, look for the ?reply to list? command, and if it's not there (or doesn't work correctly), report it to the vendor as a bug and/or switch to one of the many alternative MUAs that get it right. -- \ ?I think it would be a good idea.? ?Mahatma Gandhi (when asked | `\ what he thought of Western civilization) | _o__) | Ben Finney From contact at xavierho.com Thu Aug 27 21:16:41 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 11:16:41 +1000 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <2d56febf0908271816m68b761deq778f5105c2957baa@mail.gmail.com> On Fri, Aug 28, 2009 at 9:49 AM, kj wrote: > > Miles Kaufmann writes: > > >...because the suite > >namespace and the class namespace would get out of sync when different > >objects were assigned to the class namespace: > > >class C: > > x = 1 > > def foo(self): > > print x > > print self.x > > > >>> o = C() > > >>> o.foo() > >1 > >1 > > >>> o.x = 2 > > >>> o.foo() > >1 > >2 > I haven't tested either codes, but that isn't "out of sync". Your x = 1 is a static variable, and shared between all isntances of class C. > But this unfortunate situation is already possible, because one > can already define > > class C: > x = 1 > def foo(self): > print C.x > print self.x > > which would lead to exactly the same thing. > It works because you're simply explicitly referring to the class's local scope, which leads to the same result. Again, that's just my understanding of the implementation. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Thu Aug 27 21:48:08 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 27 Aug 2009 18:48:08 -0700 (PDT) Subject: regexp help References: <4e548d26-f3c9-46b8-a82a-c012607e2ff8@o6g2000yqj.googlegroups.com> Message-ID: On Aug 27, 1:15?pm, Bakes wrote: > If I were using the code: > > (?P[0-9]+) > > to get an integer between 0 and 9, how would I allow it to register > negative integers as well? With that + sign in there, you will actually get an integer from 0 to 99999999999999999... -- Paul From pydecker at gmail.com Thu Aug 27 21:48:40 2009 From: pydecker at gmail.com (Peter Decker) Date: Thu, 27 Aug 2009 21:48:40 -0400 Subject: Python for professsional Windows GUI apps? In-Reply-To: References: <7a9c25c20908240849p283cb70o50f374a4f8c867b@mail.gmail.com> <81ac68ae-c7fc-4caa-a04f-f358ffb78864@s15g2000yqs.googlegroups.com> Message-ID: On Wed, Aug 26, 2009 at 4:47 PM, David C Ullrich wrote: > On Mon, 24 Aug 2009 22:22:20 -0700, sturlamolden wrote: > >> On 25 Aug, 05:56, Peter Decker wrote: >> >>> I use the Dabo Class Designer to visually design my forms. So what's >>> you're point? :) >> >> Nothing, except lobbying for wxFormBuilder for anyone who still doesn't >> know of it. :) > > That's great. But do you know of anything I can use as a > visual form design tool in wxPython? You mean you prefer the wxPython style of coding? No, I don't know what's available. Once I discovered that Dabo is the smart way to get all the benefits of wxPython without the ugly C++ style of coding, I haven't used raw wxPython. -- # p.d. From doctoresam at gmail.com Thu Aug 27 22:12:57 2009 From: doctoresam at gmail.com (Esam Qanadeely) Date: Thu, 27 Aug 2009 19:12:57 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: On Aug 28, 3:46?am, Chris Rebert wrote: > On Thu, Aug 27, 2009 at 5:34 PM, Deep_Feelings wrote: > > python got relatively fewer numbers of developers than other high > > level languages like .NET , java .. etc ?why ? > > We lack Sun and Microsoft's massive marketing departments. :) > > Cheers, > Chris > --http://blog.rebertia.com any technical reasons ?? From somebody at somewhere.com Thu Aug 27 22:23:00 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Fri, 28 Aug 2009 03:23:00 +0100 Subject: Need help with Python scoping rules References: Message-ID: kj wrote: > But this unfortunate situation is already possible, because one > can already define > > class C: > x = 1 > def foo(self): > print C.x > print self.x How is this a problem? There is no ambiguity between the global scope and the local from within foo. >From within foo C is accessed from the global scope having not found it as a local. Once you have C C.x is just one step away. Variable self is local to function foo since it was passed in as a parameter from the method which wraps it. Variable self refers to a class instance which contains a dictionary. Variable x is absent from the instance dictionary so the class self.__class__ is referenced, again from local scope to find x. If it wasn't found there the superclasses would have been searched before throwing an attribute error. It seems to me, you are confusing instance creation with class creation. -- Stephen Fairchild From benjamin.kaplan at case.edu Thu Aug 27 22:33:57 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Thu, 27 Aug 2009 22:33:57 -0400 Subject: why python got less developers ? In-Reply-To: References: Message-ID: On Thu, Aug 27, 2009 at 10:12 PM, Esam Qanadeely wrote: > On Aug 28, 3:46?am, Chris Rebert wrote: >> On Thu, Aug 27, 2009 at 5:34 PM, Deep_Feelings wrote: >> > python got relatively fewer numbers of developers than other high >> > level languages like .NET , java .. etc ?why ? >> >> We lack Sun and Microsoft's massive marketing departments. :) >> >> Cheers, >> Chris >> --http://blog.rebertia.com > > any technical reasons ?? > -- Not really. It's mostly because of the lack of marketing departments and pieces of paper to placate business majors (what Microsoft and Sun call "certification") > http://mail.python.org/mailman/listinfo/python-list > From milesck at umich.edu Thu Aug 27 23:27:23 2009 From: milesck at umich.edu (Miles Kaufmann) Date: Thu, 27 Aug 2009 20:27:23 -0700 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: On Aug 27, 2009, at 4:49 PM, kj wrote: > Miles Kaufmann writes: >> Guido's design justifications: >> http://mail.python.org/pipermail/python-dev/2000-November/010598.html > > Ah! Clarity! Thanks! How did you find this? Did you know of > this post already? Or is there some special way to search Guido's > "design justifications"? I just checked the python-dev archives around the time that PEP 227 was written. >> ...because the suite >> namespace and the class namespace would get out of sync when >> different >> objects were assigned to the class namespace: > >> class C: >> x = 1 >> def foo(self): >> print x >> print self.x > >>>>> o = C() >>>>> o.foo() >> 1 >> 1 >>>>> o.x = 2 >>>>> o.foo() >> 1 >> 2 > > But this unfortunate situation is already possible, because one > can already define > > class C: > x = 1 > def foo(self): > print C.x > print self.x > > which would lead to exactly the same thing. You're right, of course. If I had been thinking properly, I would have posted this: ... the suite namespace and the class namespace would get out of sync when different objects were assigned to the class namespace: # In a hypothetical Python with nested class suite scoping: class C: x = 1 @classmethod def foo(cls): print x print cls.x >>> C.foo() 1 1 >>> C.x = 2 >>> C.foo() 1 2 With your example, the result is at least easily explainable: self.x is originally 1 because the object namespace inherits from the class namespace, but running 'o.x = 2' rebinds 'x' in the object namespace (without affecting the class namespace). It's a distinction that sometimes trips up newbies (and me, apparently ;) ), but it's straightforward to comprehend once explained. But the distinction between the class suite namespace and the class namespace is far more subtle; extending the lifetime of the first so that it still exists after the second is created is, IMO, asking for trouble (and trying to unify the two double so). -Miles From rt8396 at gmail.com Thu Aug 27 23:41:47 2009 From: rt8396 at gmail.com (r) Date: Thu, 27 Aug 2009 20:41:47 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> On Aug 27, 7:34?pm, Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc ?why ? Ugh? Well maybe if you put some deep_thoughts into this conundrum you may reveal the answer to your self. Python is an interpreted "scripting", "glue", and "sys administation" language. As long as Java can be complied strait to machine code and constantly run light years faster than Python Java will always win in this area. But who cares, Python is not meant for writing OS's or 3D games of the year, and i am quite happy it is made to be that way. Python will never be as popular as C, Java, etc for all these reasons. And since your chances of making a living writing Java code verses Python code are absolute, then of course that is where the pros will go. From contact at xavierho.com Thu Aug 27 23:48:31 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 13:48:31 +1000 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <2d56febf0908272048m656cecb9nc68f1fd3bfdf02bb@mail.gmail.com> On Fri, Aug 28, 2009 at 1:27 PM, Miles Kaufmann wrote: > You're right, of course. If I had been thinking properly, I would have > posted this: > > ... the suite namespace and the class namespace would get out of sync when > different objects were assigned to the class namespace: I'm not an expert on Python, but could you define "out of sync" for me? When you call the class as a new instance and assign it to a new variable, the class attributes (self.x) are independent for each instance. The static variables in the class (x, or C.x in this case) is shared between all instances of this class. > # In a hypothetical Python with nested class suite scoping: Class already provides some kind of scoping/namespace, that is the locals() method for the class. What is pypothetical about this, if you could elaborate? With your example, the result is at least easily explainable: self.x is > originally 1 Incorrect. "self.x" (or cls.x in your sample code) doesn't exist until you called o.x = 2, which sets "cls.x = 2". Don't be confused between static variables that are initialised at class creation, and the class attributes which usually is declared inside the __init__ method. > because the object namespace inherits from the class namespace, but running > 'o.x = 2' rebinds 'x' in the object namespace (without affecting the class > namespace). See above comment. > It's a distinction that sometimes trips up newbies (and me, apparently ;) > ), but it's straightforward to comprehend once explained. But the > distinction between the class suite namespace and the class namespace is far > more subtle; extending the lifetime of the first so that it still exists > after the second is created is, IMO, asking for trouble (and trying to unify > the two double so). It is. I had trouble getting it also, but once I think of all the variables outside of the __init__() method as "static", and the ones within as "class attributes", everything clears out just fine. =] Any corrections appreciated. I'm merely posting my understanding of Python. Cheers, - Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From contact at xavierho.com Thu Aug 27 23:51:56 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 13:51:56 +1000 Subject: Need help with Python scoping rules In-Reply-To: <2d56febf0908272048m656cecb9nc68f1fd3bfdf02bb@mail.gmail.com> References: <2d56febf0908272048m656cecb9nc68f1fd3bfdf02bb@mail.gmail.com> Message-ID: <2d56febf0908272051h26f84ad9t218f39e86e74b2@mail.gmail.com> On Fri, Aug 28, 2009 at 1:48 PM, Xavier Ho wrote: > > Class already provides some kind of scoping/namespace, that is the locals() > method for the class. What is pypothetical about this, if you could > elaborate? > Obviously that was supposed to be "hypothetical". Oops. -------------- next part -------------- An HTML attachment was scrubbed... URL: From dukeofperl at ml1.net Thu Aug 27 23:52:56 2009 From: dukeofperl at ml1.net (Duke Normandin) Date: Fri, 28 Aug 2009 03:52:56 GMT Subject: Transforming a str to an operator Message-ID: Hey.... I'm a Python noob.... So far so good! I've written the following: num1 = raw_input('Enter the first number: ') num2 = raw_input('Enter the second number: ') op = raw_input('Select one of the following [+-*/]: ') print 'The answer is: ', int(num1), eval(op), int(num2) ^^^^^^^^ How do I convert the contents of "op" from a string to an actual arithmetic operator? eval() does not seem to be the answer. TIA! -- duke From contact at xavierho.com Fri Aug 28 00:01:16 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 14:01:16 +1000 Subject: Transforming a str to an operator In-Reply-To: References: Message-ID: <2d56febf0908272101y3f237951o32c04f30bd42a69e@mail.gmail.com> On Fri, Aug 28, 2009 at 1:52 PM, Duke Normandin wrote: > How do I convert the contents of "op" from a string to an actual > arithmetic operator? eval() does not seem to be the answer. TIA! Maybe you were looking for print eval(num1 + op + num2) # it's a little ugly string concatenation. Hm? (untested, but it works in my head.) Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Fri Aug 28 00:08:54 2009 From: rt8396 at gmail.com (r) Date: Thu, 27 Aug 2009 21:08:54 -0700 (PDT) Subject: Transforming a str to an operator References: Message-ID: <6ee483f7-e92c-49e0-be27-125f3389b1f2@33g2000vbe.googlegroups.com> On Aug 27, 10:52?pm, Duke Normandin wrote: > How do I convert the contents of "op" from a string to an actual > arithmetic operator? eval() does not seem to be the answer. TIA! Try this.. >>> op = '+' >>> one = '1' >>> two = '2' >>> one+op+two '1+2' >>> eval(one+op+two) 3 you could also use string formatting. From sjmachin at lexicon.net Fri Aug 28 00:30:48 2009 From: sjmachin at lexicon.net (John Machin) Date: Thu, 27 Aug 2009 21:30:48 -0700 (PDT) Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> Message-ID: <9f3083b4-4886-41c3-9404-d7eac300964b@l35g2000pra.googlegroups.com> On Aug 28, 6:44?am, Mark Lawrence wrote: > vsoler wrote: > > On Aug 27, 9:42 pm, Andreas Waldenburger > > > 1- the csv file was generated with Excel 2007; no prompts for what the > > separator should be; Excel has used ";" by default, without asking > > anything > > I find this difficult to believe, Mark, there exist parallel universes the denizens of which use strange notation e.g. 1.234,56 instead of 1,234.56 and would you believe they use ';' instead of ',' as a list separator ... Excel perfidiously gives them what they expect rather than forcing them to comply with The One True Way. From apt.shansen at gmail.com Fri Aug 28 00:32:55 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Thu, 27 Aug 2009 21:32:55 -0700 Subject: Transforming a str to an operator In-Reply-To: References: Message-ID: <7a9c25c20908272132p737fe070w5a3c7b0a4970a2c9@mail.gmail.com> > > num1 = raw_input('Enter the first number: ') > num2 = raw_input('Enter the second number: ') > op = raw_input('Select one of the following [+-*/]: ') > print 'The answer is: ', int(num1), eval(op), int(num2) > ^^^^^^^^ > > How do I convert the contents of "op" from a string to an actual > arithmetic operator? eval() does not seem to be the answer. TIA! > You could eval(num1+op+num2), but it'd be safer to do: import operator operators = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div} fn = operators[op] print "The answer is:", fn(int(num1), int(num2)) Its best to avoid eval when possible :) --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From ben+python at benfinney.id.au Fri Aug 28 00:35:24 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 28 Aug 2009 14:35:24 +1000 Subject: Transforming a str to an operator References: Message-ID: <87skfcblo3.fsf@benfinney.id.au> Duke Normandin writes: > Hey.... > > I'm a Python noob.... > > So far so good! > > I've written the following: > > num1 = raw_input('Enter the first number: ') > num2 = raw_input('Enter the second number: ') > op = raw_input('Select one of the following [+-*/]: ') > print 'The answer is: ', int(num1), eval(op), int(num2) > ^^^^^^^^ > > How do I convert the contents of "op" from a string to an actual > arithmetic operator? eval() does not seem to be the answer. TIA! In general, ?eval? on unsanitised input is not the answer. I would use the following approach: import operator op_funcs = { '+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.div, } num_1 = int(raw_input('Enter the first number: ')) num_2 = int(raw_input('Enter the second number: ')) op_prompt = ( "Select an operator " + "[" + "".join(s for s in op_funcs.keys()) + "]" + ": ") op_symbol = raw_input(op_prompt) op_func = op_funcs[op_symbol] print 'The answer is: ', op_func(num_1, num_2) This has several advantages: * The input isn't evaluated directly as code. * The operator symbols are specified in one place, the ?op_funcs? mapping; if you want to change the set of possible operators, you just change it there. * If the input results in an operator that's not defined, it won't attempt to perform it; instead, a simple KeyError will result when trying to find the corresponding operator function. -- \ ?I do not believe in immortality of the individual, and I | `\ consider ethics to be an exclusively human concern with no | _o__) superhuman authority behind it.? ?Albert Einstein, letter, 1953 | Ben Finney From stefan_ml at behnel.de Fri Aug 28 00:49:45 2009 From: stefan_ml at behnel.de (Stefan Behnel) Date: Fri, 28 Aug 2009 06:49:45 +0200 Subject: why python got less developers ? In-Reply-To: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> References: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> Message-ID: <4a9761e8$0$31876$9b4e6d93@newsspool3.arcor-online.net> r wrote: > As long as Java > can be complied strait to machine code I think you meant "compared" here. Stefan From contact at xavierho.com Fri Aug 28 00:50:37 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 14:50:37 +1000 Subject: Transforming a str to an operator In-Reply-To: <87skfcblo3.fsf@benfinney.id.au> References: <87skfcblo3.fsf@benfinney.id.au> Message-ID: <2d56febf0908272150y59e5d458hab1fc6aa9c14187e@mail.gmail.com> On Fri, Aug 28, 2009 at 2:35 PM, Ben Finney > wrote: > import operator > > op_funcs = { > '+': operator.add, > '-': operator.sub, > '*': operator.mul, > '/': operator.div, > } > > num_1 = int(raw_input('Enter the first number: ')) > num_2 = int(raw_input('Enter the second number: ')) > op_prompt = "Select an operator ({}):".format(','.join(op for op in > op_funcs)) > op_symbol = raw_input(op_prompt) > op_func = op_funcs[op_symbol] > print 'The answer is: ', op_func(num_1, num_2) Just fixing the code a little to be more "Pythonic" ;). Might also want to do exception handling, but with a program this small, meh. -------------- next part -------------- An HTML attachment was scrubbed... URL: From doctoresam at gmail.com Fri Aug 28 01:03:54 2009 From: doctoresam at gmail.com (Esam Qanadeely) Date: Thu, 27 Aug 2009 22:03:54 -0700 (PDT) Subject: why python got less developers ? References: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> Message-ID: who cares if a language is compiled or interpreted as long as it runs and perform the function. second thing is : even if java is faster than python , unless you are making performance critical operations : who cares? computers are getting faster all the time and languages like python or ruby are fast enough. any comment ? From doctoresam at gmail.com Fri Aug 28 01:05:29 2009 From: doctoresam at gmail.com (Esam Qanadeely) Date: Thu, 27 Aug 2009 22:05:29 -0700 (PDT) Subject: why python got less developers ? References: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> Message-ID: <42a1c81d-b2ec-46b7-9cf2-6e099bd260a3@j21g2000yqe.googlegroups.com> i meant fast enough for most (but not all) applications From rt8396 at gmail.com Fri Aug 28 01:08:01 2009 From: rt8396 at gmail.com (r) Date: Thu, 27 Aug 2009 22:08:01 -0700 (PDT) Subject: Transforming a str to an operator References: <87skfcblo3.fsf@benfinney.id.au> Message-ID: <91126ac3-e7fe-4b7a-a37d-d1e60beaa278@w41g2000yqb.googlegroups.com> On Aug 27, 11:35?pm, Ben Finney wrote: > In general, ?eval? on unsanitised input is not the answer. Yes i agree. > I would use the following approach: Abviously the OP is a python baby noob and casting your irrational fear (and many others irrational fears) of eval at him is akin to tales of Chupacabras running a muck in the jungle sucking the blood from live goats in the twilight hours. I use eval all the time and quite love it. This is nothing more than a throw away academic exercise that will serve no useful purpose for him in the future, but serves the very useful purpose now of establishing an IO between the student and Python interpretor. I'll bet most your example (albeit a good example) flew miles above his head into la-la land. The OP has plenty of time to learn about malicious input and protecting against it, right now the fundamentals are well... fundamental :) From timr at probo.com Fri Aug 28 01:27:45 2009 From: timr at probo.com (Tim Roberts) Date: Thu, 27 Aug 2009 22:27:45 -0700 Subject: why python got less developers ? References: Message-ID: Deep_Feelings wrote: > >python got relatively fewer numbers of developers than other high >level languages like .NET , java .. etc why ? How do you know, and why does it matter? By the way, .NET is not a language. I assume you meant C#. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From max at landaeus.com Fri Aug 28 01:36:33 2009 From: max at landaeus.com (Max Landaeus) Date: Fri, 28 Aug 2009 13:36:33 +0800 Subject: Does Class implements Interface? In-Reply-To: References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> Message-ID: <4A976CE1.2050506@landaeus.com> Emanuele D'Arrigo wrote: > On Aug 27, 9:42 pm, Jonathan Gardner > wrote: > >> Have you heard of duck typing? >> > > Yes. > > >> Ignore all those things and rely on human (aka natural language) >> documentation. That is, if you want to see if a class will work for an >> interface, go read the docs on the interface (or rather, what the >> function expects the interface to be) and what the class provides and >> see if they fit. >> > > Apologies, my fault, I didn't explain that humans are out of the loop > entirely. It's only at runtime that the program obtains the class > object that might or might not conform to an expected interface. In > fact the program might obtain multiple objects and have to decide > which one conforms best to the expected interface. Of course I could > use hasattr() and the inspect module (anything else?) to find out if > existing attributes and method signatures are those expected. Or I > could just deal with the exceptions as they are raised. However, if I > could somehow rely that the object I'm getting has the right methods > and signatures I could avoid peppering the code with try/except > constructs. > > I was just wondering then if this has been somewhat dealt with and has > been wrapped in a neat package, set of functions, recipe or pattern. > > Manu > Check out Alex Martelli's recipe 'Checking wheter an object has necessary attributes' in the Python Cookbook: http://books.google.co.uk/books?id=Q0s6Vgb98CQC&printsec=frontcover&dq=python+cookbook#v=onepage&q=&f=false Max From doctoresam at gmail.com Fri Aug 28 01:44:59 2009 From: doctoresam at gmail.com (Esam Qanadeely) Date: Thu, 27 Aug 2009 22:44:59 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: <1ccf54f5-b1f5-4c4a-b782-fde1a1648cf6@l5g2000yqo.googlegroups.com> On Aug 28, 8:27?am, Tim Roberts wrote: > Deep_Feelings wrote: > > >python got relatively fewer numbers of developers than other high > >level languages like .NET , java .. etc ?why ? > > How do you know, and why does it matter? > > By the way, .NET is not a language. ?I assume you meant C#. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. you know when you go to forums and compare the number of posts and topics ,and you know when you google and compare the number of results .NET= i meant all .NET languages From rt8396 at gmail.com Fri Aug 28 01:52:11 2009 From: rt8396 at gmail.com (r) Date: Thu, 27 Aug 2009 22:52:11 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: On Aug 27, 7:34?pm, Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc ?why ? Oh, and why on god's green would you ever compare Java (*puke*) and Python in the same breath? You say Python is a "high-level-language"? Well sir, i say Python is a "super-high-level-language" that approaches pseudo code simplicity *but* stays far enough away from it so as not to be scorched by it's asinine synonymous quirks. From frank at chagford.com Fri Aug 28 02:01:01 2009 From: frank at chagford.com (Frank Millman) Date: Fri, 28 Aug 2009 08:01:01 +0200 Subject: Move dictionary from instance to class level References: <705c21b0-2858-46c2-8230-3cea64f5be3a@a26g2000yqn.googlegroups.com> Message-ID: Anthony Tolle wrote: > To take things one step further, I would recommend using decorators to > allow symbolic association of functions with the message identifiers, > as follows: > [...] That's neat. Thanks. Frank From apt.shansen at gmail.com Fri Aug 28 02:01:29 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Thu, 27 Aug 2009 23:01:29 -0700 Subject: Transforming a str to an operator In-Reply-To: <91126ac3-e7fe-4b7a-a37d-d1e60beaa278@w41g2000yqb.googlegroups.com> References: <87skfcblo3.fsf@benfinney.id.au> <91126ac3-e7fe-4b7a-a37d-d1e60beaa278@w41g2000yqb.googlegroups.com> Message-ID: <7a9c25c20908272301p7675c8f4q91dbb5ea4b790210@mail.gmail.com> > > > I would use the following approach: > > Abviously the OP is a python baby noob and casting your irrational > fear (and many others irrational fears) of eval at him is akin to > tales of Chupacabras running a muck in the jungle sucking the blood > from live goats in the twilight hours. I use eval all the time and > quite love it. > Yes, the OP is clearly a newbie to the language and probably programming in general, but that response is nonsense. It's a perfect example of a false analogy. Chupacabras are superstition, baseless fear-mongering. eval() is a very real dangerous construct. There is absolutely nothing irrational about the unsafe nature of eval. It is a tool: it is a useful tool if one knows how to use it, but is a tool that you'll slam into your thumb and break it if you don't know how. When there are tools available which address the same problem without those dangers, newbies should be exposed to THOSE first. > This is nothing more than a throw away academic exercise that will > serve no useful purpose for him in the future, but serves the very > useful purpose now of establishing an IO between the student and > Python interpretor. I'll bet most your example (albeit a good example) > flew miles above his head into la-la land. > I prefer not to assume newbies are stupid; if they don't understand a part of a correct explanation that's given, they can ask for clarification and further details can be given. True, this is a very Python-specific "correct" example to this basic problem, with dictionary dispatch which is a very Pythonic idiom that might be a bit too much for a newbie to programming in general: if that's the case, the correct thing to show the newbie would be: if op == "+": print "The result is:", int(num1) + int(num2) elif op == "-": print "The result is:", int(num1) - int(num2) ..etc. Exposing newbies to eval() is simply irresponsible. It is not an irrational fear: eval has a purpose and it is useful and it's fine to use, IF you understand the language and implications enough to use it. If you don't, if you're a newbie to programming entirely, it is good sense and a benefit to the newbie to steer the person away from something that will get them in trouble down the road. If they're not ready to deal with input sanitization, that's fine... but exposing them to dangerous practices when there's clear and logical alternate approaches is fool-hearty. The OP has plenty of time to learn about malicious input and > protecting against it, right now the fundamentals are well... > fundamental :) eval is simply NOT a fundamental. It should be considered an advanced feature, for advanced usage; that it seems simple is all the more dangerous. No one should be taught from an early stage that 'this is how to address a problem', only to then teach them later, 'Oh, by the way, that thing I taught you? It's bad in most cases and you shouldn't do it again'. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From frank at chagford.com Fri Aug 28 02:06:14 2009 From: frank at chagford.com (Frank Millman) Date: Fri, 28 Aug 2009 08:06:14 +0200 Subject: Move dictionary from instance to class level References: <20090827102111.ABC3B1F93@ctb-mesg4.saix.net> Message-ID: Dave Angel wrote: > OK, that makes good sense. And I withdraw any suggestion to use pickling, > since that could be subject to hacking. > > It now appears that the messages are only incidentally GUI events. And > that you would be well advised to make every possible event a separate > message, so that if the server state and the client state get out of > synch, you can readily check and reject such operations. For example, > you'd have a message for pressing the SUBMIT button on a particular form, > but you'd have different message types for other buttons on the same form, > or for SUBMIT on other forms. > I use the same message type for all SUBMITs, but the body of the message contains a unique id for each button. When the server constructs the form, it assigns a unique id to each widget, and includes this id in the form definition it sends to the client. Therefore the server and client can unambiguously reference specific widgets, and there is no real danger of getting out of sync. Frank From chris at simplistix.co.uk Fri Aug 28 02:26:45 2009 From: chris at simplistix.co.uk (Chris Withers) Date: Fri, 28 Aug 2009 07:26:45 +0100 Subject: why python got less developers ? In-Reply-To: <1ccf54f5-b1f5-4c4a-b782-fde1a1648cf6@l5g2000yqo.googlegroups.com> References: <1ccf54f5-b1f5-4c4a-b782-fde1a1648cf6@l5g2000yqo.googlegroups.com> Message-ID: <4A9778A5.1060105@simplistix.co.uk> Esam Qanadeely wrote: > .NET= i meant all .NET languages What? You mean like Python? ;-) Google IronPython ya troll... Chris -- Simplistix - Content Management, Batch Processing & Python Consulting - http://www.simplistix.co.uk From jvpic at free.fr Fri Aug 28 02:37:16 2009 From: jvpic at free.fr (jvpic) Date: Fri, 28 Aug 2009 08:37:16 +0200 Subject: Learning Python advanced features In-Reply-To: <4a967bd6$0$19301$426a74cc@news.free.fr> References: <4a967864$0$15193$426a74cc@news.free.fr> <4a967bd6$0$19301$426a74cc@news.free.fr> Message-ID: <4a977b20$0$740$426a34cc@news.free.fr> Bruno Desthuilliers a ?crit : > jvpic a ?crit : >> Hi, >> >> Learning Python, I understand the mechanism of : closure, __new__, >> descriptors, decorators and __metaclass__, but I interrogate myself on >> the interest of those technics ? >> >> May somebody explain me the interest ? > > Didn't like my answers on f.c.l.py ?-) Si, mais je voulais savoir ce qu'on en pense sur un autre forum ! Merci encore... From simon at brunningonline.net Fri Aug 28 02:42:29 2009 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 28 Aug 2009 07:42:29 +0100 Subject: Question on the "csv" library In-Reply-To: <9f3083b4-4886-41c3-9404-d7eac300964b@l35g2000pra.googlegroups.com> References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> <9f3083b4-4886-41c3-9404-d7eac300964b@l35g2000pra.googlegroups.com> Message-ID: <8c7f10c60908272342o4fc91195m27b56e3b506eb540@mail.gmail.com> 2009/8/28 John Machin : > > Mark, there exist parallel universes the denizens of which use strange > notation e.g. 1.234,56 instead of 1,234.56 When displaying data, sure. > and would you believe they > use ';' instead of ',' as a list separator ... CSV is a data transfer format, not a display format. Locale specific stuff like this has no place in it. Dates, IMHO, should be in the ugly but unambiguous ISO 8601 format in a CSV. It's for import and export, not for looking pretty. Besides - CSV; the clue's in the name. ;-) > Excel perfidiously > gives them what they expect rather than forcing them to comply with > The One True Way. When people export to a comma separated value file, they are almost certainly expecting a file containing values separated by comas. If Excel isn't giving them this by default, it's broken. -- Cheers, Simon B. From beorn at seznam.cz Fri Aug 28 03:45:58 2009 From: beorn at seznam.cz (hoffik) Date: Fri, 28 Aug 2009 00:45:58 -0700 (PDT) Subject: Select column from a list Message-ID: <25185508.post@talk.nabble.com> Hello, I'm quite new in Python and I have one question. I have a 2D matrix of values stored in list (3 columns, many rows). I wonder if I can select one column without having to go through the list with 'for' command. For example I have list called 'values'. When I write 'values[0]' or 'values[0][:]' I'll get the first row. But when I write 'values[:][0]' I won't get the first column, but the first row again! I can't see why. Thanks Hoffik -- View this message in context: http://www.nabble.com/Select-column-from-a-list-tp25185508p25185508.html Sent from the Python - python-list mailing list archive at Nabble.com. From hendrik at microcorp.co.za Fri Aug 28 03:54:51 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 28 Aug 2009 09:54:51 +0200 Subject: List iterator thread safety In-Reply-To: <6bf89e55-2ddd-435f-925d-7cc3827c0f9a@24g2000yqm.googlegroups.com> References: <6bf89e55-2ddd-435f-925d-7cc3827c0f9a@24g2000yqm.googlegroups.com> Message-ID: <200908280954.51423.hendrik@microcorp.co.za> On Thursday 27 August 2009 16:50:16 Carl Banks wrote: > On Aug 27, 7:25?am, Hendrik van Rooyen > wrote: > > Its not too bad - if you crook a bit - the trick is that you iterate over > > the list backwards when you are removing stuff based on index, so that > > the remainder does not get jumbled up by losing their positions, as > > happens when you do it going forwards. > > That's only if you remove the "current item". The OP has different > threads accessing the list at the same time, so I have to assume that > item being remove is not necessarily the current iteration. Sorry - I did not pick that up - The threading screws the simple scheme up. In such a situation I would have a thread to run the list - almost like a mini data base - and link the lot together using queues. It is still a bugger, though, as one thread could try to kill something that is "checked out" to another one. Then you have to take hard decisions, and a list is the wrong structure, because you have to remember state. Better to use a dict, so you can at least mark a thing as "dead", and check for that before you update. 8<-------- example -------- > For the record, I use a more sophisticated system that explicitly > resolves cause and effect in my games. That's probably beyond the > scope of this thread, though. Yes - it is hairy - and there are probably as many different solutions as there are programmers, and then some. :-) - Hendrik From eric.brunel at pragmadev.com Fri Aug 28 03:55:22 2009 From: eric.brunel at pragmadev.com (eb303) Date: Fri, 28 Aug 2009 00:55:22 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> Message-ID: On Aug 27, 11:22 pm, r wrote: > --------------------------------------------- > Python offical docs and Tkinter > --------------------------------------------- > *The Python docs barely cover anything related to actual Tkinter > coding. At the minimum the Tkinter doc page should have a subpage for > all the widgets available --which is very small(approx 15) and each > subpage should list the available methods on that wiget. I think the general idea behind the 'lack' of documentation is that it would only double tcl/tk's own documentation. I've always used Tkinter using the tcl/tk docs here: http://www.tcl.tk/man/tcl8.5/TkCmd/contents.htm and once you get used to how you transform tcl syntax to Python syntax, it works pretty well. Maintaining a documentation for Tkinter in the official Python docs would force people to run after tcl. I understand why they don't want to do that, even if I'd love to see a better Tkinter documentation too. > --------------------------------------------- > from Tkinter import * > --------------------------------------------- > *Too many noobs start out with the "from Tkinter import *" idiom, > unknowing that they are horribly polluting their namespace. I feel > that all (tkinter) code should follow the "import Tkinter as tk" > policy and never use "from Tkinter import *". To push this agenda i > propose all docs be modified so that no one should see such global > import blasphemy again. We should at least keep all example code in > the latter non-polluting form and frown heavily upon global imports in > Tkinter code or any code for that matter. Well, I just don't agree with you on this one. AFAIK, Tkinter has been made to make the 'from Tkinter import *' idiom work without too much namespace pollution. I've always used it, still use it today, and never seen any problem with it. I do agree that this might lead newbies to think it's ok for all modules, and end up doing 'from os import *' and wonder why opening a file with 'open' no more works. But this is the only problem I can see. > --------------------------------------------- > Tkinter Constants > --------------------------------------------- > *The Tkconstants module needs to be removed *yesterday* because i > think it reinforces sloppy coding styles. The main problem is with > subtle bugs that are created when someone rebinds one or more of the > constants, for example "W=20". At first i thought the constants were > great but I quickly found out the shortfalls of such a Utopian > approach . Since Tkinter allows strings to be passed-into widget > constructors, we should remove the TkConstants immediately and force > everyone to use strings instead... > > #-- instead of this --# > w.pack(side=LEFT,fill=BOTH,anchor=W) > > #-- do this --# > w.pack(side='left',fill='both',anchor='w') > > The few extra keystrokes are well worth the effort! Well, again, I don't agree. I prefer having well defined constants than having to type strings. If the values for the fill option could be anything, well, OK. But they can't: they have to be either 'x' or 'y' or 'both'. So I prefer to have them defined in constants. [snip comments on IDLE, which I don't use] > --------------------------------------------- > Tkinter Canvas > --------------------------------------------- > *The Tkinter Canvas widget should return (X,Y) pairs when calling > canvas.coords(obj). The current implementation returns a flat array > that is pretty much useless outside of canvas calls. Of course one > could zip the coords into pairs, but it seems clumsy to call zip() on > 2 LC's when Tkinter could, and should, do it for you. We agree on this one, but it's a minor flaw. > *Canvas needs a canvas.rotate() method for polygons, lines -- (easy). All Canvas methods are actually forwarded to the underlying tcl interpreter. So you might want to suggest that to the tcl guys. > --------------------------------------------- > Tkinter ComboBox -- where's Waldo? > --------------------------------------------- > *As much as i hate to support anything related to M$, Tkinter needs an > M$ stlye combobox. Yes, I know Tix has combobox (*puke*), however > using it is like pulling teeth. I have coded up an far more elegant/ > simple solution -- and yes, i know about the OptionMenu widget which > serves a useful purpose but is NOT a good replacement for a REAL M$ > style combobox ;). You don't seem to be aware of the new widgets in tk, which do include a combo-box (and a lot of others BTW). See the ttk:: commands in the tcl/tk documentation (link above). These widgets already have a Python wrapper (see http://pypi.python.org/pypi/pyttk/0.3). > *For instance, ComboBoxes need values that the user can select from, > this is as universal as humans and oxygen. But sometimes you want to > give the user a detailed set of values in the dropdown listbox and > then insert an abbrieation of the value once selected, such as the > case with state names... > > New Mexico -> MN > California -> CA > Florida -> FL > > ...instead of the laborious and wasteful convention of overriding a > method to insert this value from a mapping each time why not just pass > a pointer to the mapping into the constructor and create a combobox > that actually knows how to walk and chew gum! Again, you might want to forward that to the tcl guys. And I do agree it would be nice. [snip code] [snip Tix comments...] Tix is more or less dead, since nearly all the widgets it provided have now way better alternatives which have been included in the tcl/ tk core in the ttk package, including comboboxes and notebooks. You might want to have a look at these. From contact at xavierho.com Fri Aug 28 03:55:50 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 17:55:50 +1000 Subject: Select column from a list In-Reply-To: <25185508.post@talk.nabble.com> References: <25185508.post@talk.nabble.com> Message-ID: <2d56febf0908280055g3b38bec9j1f1e812dc8bab11f@mail.gmail.com> On Fri, Aug 28, 2009 at 5:45 PM, hoffik wrote: > Hello, > > I'm quite new in Python and I have one question. I have a 2D matrix of > values stored in list (3 columns, many rows). I wonder if I can select one > column without having to go through the list with 'for' command. As far as I know though, you will have to loop through this if you built your matrix with nested lists. i.e.: li = [[1,2],[3,4]] result = [] for row in li: result.append(row[0]) # result == [1, 3] > For example I have list called 'values'. > When I write 'values[0]' or 'values[0][:]' I'll get the first row. > But when I write 'values[:][0]' I won't get the first column, but the first > row again! I can't see why. Let's say values = [[1,2][3,4]]. values[:] returns the entire values list, from beginning to end. So you end up what you started with. And, of course, values[:][0] is the same as values[0]. In fact: >>> li[:][:][:][0] is li[0] True It's... a very interesting behaviour, to say the least. You might be able to get a proper matrix behaviour using NumPy, (which I never used, so I'm just throwing it out there as a guess) or you might have to write your own iterator for later reuse. Cheers, Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From breamoreboy at yahoo.co.uk Fri Aug 28 04:03:49 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Aug 2009 09:03:49 +0100 Subject: Question on the "csv" library In-Reply-To: <9f3083b4-4886-41c3-9404-d7eac300964b@l35g2000pra.googlegroups.com> References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> <9f3083b4-4886-41c3-9404-d7eac300964b@l35g2000pra.googlegroups.com> Message-ID: John Machin wrote: > On Aug 28, 6:44 am, Mark Lawrence wrote: >> vsoler wrote: >>> On Aug 27, 9:42 pm, Andreas Waldenburger >>> 1- the csv file was generated with Excel 2007; no prompts for what the >>> separator should be; Excel has used ";" by default, without asking >>> anything >> I find this difficult to believe, > > Mark, there exist parallel universes the denizens of which use strange > notation e.g. 1.234,56 instead of 1,234.56 and would you believe they > use ';' instead of ',' as a list separator ... Excel perfidiously > gives them what they expect rather than forcing them to comply with > The One True Way. I suggest a new file type csvewtlsinac i.e. comma seperated value except when the list seperator is not a comma.:) Does this cover everything? p.s. is it "separator" or "seperator", after 50+ years I still can't remember? -- Kindest regards. Mark Lawrence. From martin at v.loewis.de Fri Aug 28 04:12:34 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 28 Aug 2009 10:12:34 +0200 Subject: break unichr instead of fix ord? In-Reply-To: <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> Message-ID: <4a979172$0$11759$9b622d9e@news.freenet.de> > The PEP says: > * unichr(i) for 0 <= i < 2**16 (0x10000) always returns a > length-one string. > > * unichr(i) for 2**16 <= i <= TOPCHAR will return a > length-one string on wide Python builds. On narrow > builds it will raise ValueError. > and > * ord() is always the inverse of unichr() > > which of course we know; that is the current behavior. But > there is no reason given for that behavior. Sure there is, right above the list: "Most things will behave identically in the wide and narrow worlds." That's the reason: scripts should work the same as much as possible in wide and narrow builds. What you propose would break the property "unichr(i) always returns a string of length one, if it returns anything at all". > 1) Should surrogate pairs be disallowed on narrow builds? > That appears to have been answered in the negative and is > not relevant to my question. It is, as it does lead to inconsistencies between wide and narrow builds. OTOH, it also allows the same source code to work on both versions, so it also preserves the uniformity in a different way. > * every Python Unicode character represents exactly > one Unicode code point (i.e. Python Unicode > Character = Abstract Unicode character) > > I'm not sure what this means (what's an abstract unicode > character?). I don't think this is actually the case, but I may be confusing Unicode terminology here - "abstract character" is a term from the Unicode standard. > Finally we read: > > * There is a convention in the Unicode world for > encoding a 32-bit code point in terms of two > 16-bit code points. These are known as > "surrogate pairs". Python's codecs will adopt > this convention. > > Is a distinction made between Python and Python > codecs with only the latter having any knowledge of > surrogate pairs? No. In the end, the Unicode type represents code units, not code points, i.e. half surrogates are individually addressable. Codecs need to adjust to that; in particular the UTF-8 and the UTF-32 codec in narrow builds, and the UTF-16 codec in wide builds (which didn't exist when the PEP was written). > Nothing else in the PEP seems remotely relevant. Except for the motivation, of course :-) In addition: your original question was "why has this been changed", to which the answer is "it hasn't". Then, the next question is "why is it implemented that way", to which the answer is "because the PEP says so". Only *then* the question is "what is the rationale for the PEP specifying things the way it does". The PEP is relevant so that we can both agree that Python behaves correctly (in the sense of behaving as specified). Regards, Martin From deets at nospam.web.de Fri Aug 28 04:14:59 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Aug 2009 10:14:59 +0200 Subject: Algorithms as objects? In-Reply-To: References: Message-ID: <7fpi03F2lmnccU1@mid.uni-berlin.de> Kreso schrieb: > I am writing an application that essentially calculates set of numbers, > say N1, N2, ..., where they can be calculated by several different > algorithms. (One should be able to choose the algorithm at run time.) > In each algorithm one starts from a set of functions, say f1, f2, ..., > which are then transformed into some other functions g1(f1, f2, ..), > g2(f1, f2, ...), ... , then maybe transformed once more and result is > obtained by evaluating final functions. > I can naturally think about this as a collection of transformation > blocks, which have functions as input and output, and which can be > put together to get the final results. However, I am not sure > how to program this, especially since one cannot subclass function > type. To be clear let me give simplified example of what is needed: > > f(x) has unknown shape, so one would like to try, say > > f1(x) = ax - b x**2 or f2(x) = a sin(b*x), > > where a and b are variable parameters. > > Then, one would like to create, with known k(x,y), function g(x) > in one of two ways: > > g1(x) = k(x, x)*f(x) or g2(x) = integrate(k(x, y) * f(y), y=0..1), > > and finally evaluate N=g(1) as result. In this simple example > there are 4 different algorithms for f(x) -> g(x) -> N, and one > should be able to simply choose between them, e.g. by calling > N(g1, f2, (a,b)). > > In practice algorithm is not necessary so linear, but is > generally tree-lika: > > (a,b) -> f1(x) --->g1(x)---+ > |--> h(x) --> N > (c,d) ---+--> g2(x)--------+ > | > f2(x) --+ > > > It would be nice to have some class of function-objects, > that f1(x), .., g1(x), ... could be members/instances of so that common > operations on these functions could be possible (checking > that they satisfy some necessary properties, plotting them, ...), > and then second "class" of transformations/methods operating on > these objects. > I seem to be confused by the fact that I would like to somehow treat > algorithms as objects (so that one can experiment with different > algorithm systems) but I don't have clear picture how to do it. > I am just brainstorming for ideas. Any advice is welcome. > Sound like simple function combinators to me. Like this: import inspect def combine(f, g): if len(inspect.getargspec(g)[0]) > 1: def h(*args): return g(*f(*args)) return h else: def h(*args): return g(f(*args)) return h def a(x): return 10 + x def b(x): return x ** 2 print combine(a, b)(20) def c(x): return x, x * 2 def d(x, y): return x + y print combine(c, d)(10) But to be honest - I don't think you win much with this whole thing. Spelling out the function-calls the way they are made is in the end as efficient and clear as it can get. And for *real* algorithms, you need non-strict constructs, control-structures and the like, and in the end of the day, you create a programming language on top of a programming language. Diez From hendrik at microcorp.co.za Fri Aug 28 04:18:01 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 28 Aug 2009 10:18:01 +0200 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> Message-ID: <200908281018.01750.hendrik@microcorp.co.za> On Thursday 27 August 2009 22:57:44 Terry Reedy wrote: > > Nope. I got a duplicate sent to my mailbox, which I hate. > > In particular, because there is no indication that it is an exact > duplicate of what I will also find on the list itself. Please use reply > instead of reply-all. If I do that, then the mail would go just to you, and not to the list at all, which is not what I suspect you want, in view of what you have just said. I have to do a "reply all", followed by deletion of the author, and sometimes addition of the list as a "to" too. Its a mess, and if I muck it up, the author gets a copy in his email, if he has not fudged his "reply to" It would really be nice if the "reply" would go to the list, but for the digest versions, at least, it does not. And different mail clients do not seem to make a difference. - Hendrik From contact at xavierho.com Fri Aug 28 04:31:59 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 18:31:59 +1000 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <200908281018.01750.hendrik@microcorp.co.za> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <200908281018.01750.hendrik@microcorp.co.za> Message-ID: <2d56febf0908280131p1599de21i62add26fc4e96ab4@mail.gmail.com> On Fri, Aug 28, 2009 at 6:18 PM, Hendrik van Rooyen wrote: > It would really be nice if the "reply" would go to the list, but for the > digest versions, at least, it does not. I'm on a few other lists. The Python ones are the only ones that I have to manually change. The Nuke-user mailing list automatically changes the To: to the correct address, and I *think* they also use mail-man. The DLF list I mentioned before also doesn't have this problem. When will this be fixed? It'll take someone like 5 minutes to do a setting . . . -Just my rambling again Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From no.i.dont at want.mail.from.spammers.com Fri Aug 28 04:37:15 2009 From: no.i.dont at want.mail.from.spammers.com (Fencer) Date: Fri, 28 Aug 2009 10:37:15 +0200 Subject: Sending email Message-ID: <7fpj9tF2clhemU1@mid.individual.net> Hello, I'm using Python version 2.6.2 and I discovered it has built-in libraries for sending email (imports smtplib and email). On the web I discovered how to send mail through smtp.gmail.com: mail_server = smtplib.SMTP() mail_server.connect('smtp.gmail.com') mail_server.ehlo() mail_server.starttls() mail_server.ehlo() mail_server.login('username', 'password') msg = MIMEText('Some message text') msg['Subject'] = 'Some subject' msg['From'] = 'Mr Underhill' msg['To'] = 'someemailaddress' me = 'myemailaddress' mail_server.sendmail(me, ['someemailaddress'], msg.as_string()) That seems to work just fine but for the messages I will be sending I don't want to use my private GMail account. We have an SMTP server at work, and I checked its settings in the Thunderbird mail client and it's using SSL over port 465, so a bit different from how GMail's SMTP server is configured in Thunderbird. I altered my code slightly to account for this: mail_server = smtplib.SMTP_SSL() mail_server.connect('mysmtpserver.at.work', 465) Everything I left untouched. However, it doesn't work: Traceback (most recent call last): File "C:\Users\fencer\workspace\Send Email\src\send_email.py", line 16, in mail_server.ehlo() File "C:\Python26\lib\smtplib.py", line 382, in ehlo self.putcmd(self.ehlo_msg, name or self.local_hostname) File "C:\Python26\lib\smtplib.py", line 318, in putcmd self.send(str) File "C:\Python26\lib\smtplib.py", line 310, in send raise SMTPServerDisconnected('please run connect() first') smtplib.SMTPServerDisconnected: please run connect() first As you can see, I'm on Windows Vista. What do I need to change in my code to fix this problem? Thunderbird manages to do it! :) Ideally, I would like send an email that the recipient can't reply to, but if doesn't work, it's fine too. I want to use this to send automated emails to students with account information for a course. - Fencer From manu3d at gmail.com Fri Aug 28 04:40:28 2009 From: manu3d at gmail.com (Emanuele D'Arrigo) Date: Fri, 28 Aug 2009 01:40:28 -0700 (PDT) Subject: Does Class implements Interface? References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> <3e18a803-4445-4dcf-8d8f-7661fd46ab93@y4g2000prf.googlegroups.com> Message-ID: <55a99698-49ae-4af9-a254-d4e1a429b3d5@k30g2000yqf.googlegroups.com> Jonathan, Stephen and Max, thank you all for the tips and tricks. Much appreciated. Manu From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 04:41:51 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 10:41:51 +0200 Subject: Need help with Python scoping rules In-Reply-To: References: <4a967b2f$0$19301$426a74cc@news.free.fr> Message-ID: <4a979838$0$13005$426a34cc@news.free.fr> kj a ?crit : > In <4a967b2f$0$19301$426a74cc at news.free.fr> Bruno Desthuilliers writes: > >> The only thing one is entitled to expect when learning a new language is >> that the language's implementation follows the language specs. > > In fact, the official docs, when they discuss scopes, are off to > a bad start: > > Names refer to objects. Names are introduced by name binding > operations. Each occurrence of a name in the program text refers > to the binding of that name established in the innermost function > block containing the use. > > The first paragraph implies that binding can only occur within > functions, which is either incorrect, or presupposes a definition > of "function" that is not what most programmers would recognize. Indeed, and you're right to point it. I strongly suggest you submit a ticket to the doc maintainers. > In general, I found the docs very unclear on the subject of scoping. > PEP 227 is much better, but I wouldn't have thought of it as "the > specs". Well, here again, it sure would help to make clear that peps (and release specific "what's new") *are* part of the doc. But for sure, what used to be a simple and clear reference is now a bit of a mess, despite the hard work of the doc team. Side-effect of the rapid growth of the language I guess... From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 04:48:03 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 10:48:03 +0200 Subject: Algorithms as objects? In-Reply-To: References: Message-ID: <4a9799ac$0$8042$426a74cc@news.free.fr> Kreso a ?crit : > I am writing an application that essentially calculates set of numbers, > say N1, N2, ..., where they can be calculated by several different > algorithms. (One should be able to choose the algorithm at run time.) > In each algorithm one starts from a set of functions, say f1, f2, ..., > which are then transformed into some other functions g1(f1, f2, ..), > g2(f1, f2, ...), ... , then maybe transformed once more and result is > obtained by evaluating final functions. > I can naturally think about this as a collection of transformation > blocks, which have functions as input and output, and which can be > put together to get the final results. However, I am not sure > how to program this, especially since one cannot subclass function > type. Nope, but you can write your own callable types: class functor(object): def __call__(self): print "%s called" % self (snip) > I seem to be confused by the fact that I would like to somehow treat > algorithms as objects Strategy pattern anyone ? From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 04:51:43 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 10:51:43 +0200 Subject: variables of the class are not available as default values? In-Reply-To: References: Message-ID: <4a979a88$0$8042$426a74cc@news.free.fr> Chris Rebert a ?crit : (snip) > Default values are only evaluated once, when the class is defined, s/class/function/ The function objects (defined in a class statement body...) are created before the class object itself. > thus "self" is not defined at that point since the class is still > being defined when the method definition is executed and thus there > can be no instances yet anyway. From hendrik at microcorp.co.za Fri Aug 28 04:52:01 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 28 Aug 2009 10:52:01 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a970bd7$0$333$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a970bd7$0$333$14726298@news.sunsite.dk> Message-ID: <200908281052.01436.hendrik@microcorp.co.za> On Friday 28 August 2009 00:42:16 Esben von Buchwald wrote: > OK, now things starts to make sense. > > You tell me to do something like this? > > > def doCallback(self): > if self.process_busy==False: > self.process_busy=True > self.at.after(0.01,self.data_callback) This bit is allmost right - try to make the time a millisecond or less, if you can. (however that is specified - I do not know) The spelling is probably: self.at.after(1,self.data_callback, (other_stuff)) where "other stuff" comes from the event and is what is needed to do the calculation. - the event should be an argument to the doCallback thinghy too, somehow, so that you can get at what you need to do the calculation. > def doneCallback(self): > self.process_busy=False > you do not need this separate. just do this: def data_callback(self,other_stuff): calculate what must be calculated self.process_busy=False > > And the after command will cause python to spawn a new thread, which > runs self.data_callback, which measn that the doCallback will return > immediately, so the next callback from accelerometer can be processed? Yes and skipped if the calculation is not done yet. Obviously you will have to do whatever it takes to make sure the events keep coming (if anything), so it may end up a little more complex, but you basically have the idea now. The thing that happens as a result of the after is not really a new thread, it is a piece of the main loop that gets diverted for a while to do the calculation. if, in that routine, you go: while True: pass You will completely freeze up the whole bang shoot.. > > And when the self.data_callback() finishes, i'd make it call the > doneCallback() to release my busy flag, right? see above - just clear it from the called routine. > > I'm gonna try this tomorrow :) Good luck! - Hendrik From ben+python at benfinney.id.au Fri Aug 28 04:54:30 2009 From: ben+python at benfinney.id.au (Ben Finney) Date: Fri, 28 Aug 2009 18:54:30 +1000 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> Message-ID: <87k50ob9o9.fsf@benfinney.id.au> Hendrik van Rooyen writes: > If I [use the ?reply to author? command], then the mail would go just > to you, and not to the list at all, which is not what I suspect you > want, in view of what you have just said. Right. The common ?reply? command in most mail clients means ?reply to author?, and as you say, it requests to compose a reply addressed to the author. > It would really be nice if the "reply" would go to the list, but for > the digest versions, at least, it does not. No, it really wouldn't; because if you're asking to compose a message address to the *author*, and it instead gets addressed to the whole *list*, that's a recipe for disastrous communication errors. Instead, it would be nice if people had a ?reply to list? command, and used that when they choose to send a message to the list. > And different mail clients do not seem to make a difference. Fortunately, the messages that come from the list enable any mail client to know the correct address for ?reply to list?. It only remains to choose a mail client that knows how to use it. -- \ ?? one of the main causes of the fall of the Roman Empire was | `\ that, lacking zero, they had no way to indicate successful | _o__) termination of their C programs.? ?Robert Firth | Ben Finney From contact at xavierho.com Fri Aug 28 05:04:57 2009 From: contact at xavierho.com (Xavier Ho) Date: Fri, 28 Aug 2009 19:04:57 +1000 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <87k50ob9o9.fsf@benfinney.id.au> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <87k50ob9o9.fsf@benfinney.id.au> Message-ID: <2d56febf0908280204k73a41cc0j63717c8ca258ff33@mail.gmail.com> On Fri, Aug 28, 2009 at 6:54 PM, Ben Finney > wrote: > Fortunately, the messages that come from the list enable any mail client > to know the correct address for ?reply to list?. It only remains to > choose a mail client that knows how to use it. Would you be so kind and share with us for such a client that knows how to use the mailing list attribute? Thanks! -Xav -------------- next part -------------- An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 05:06:31 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 11:06:31 +0200 Subject: Select column from a list In-Reply-To: References: Message-ID: <4a979e00$0$3608$426a34cc@news.free.fr> hoffik a ?crit : > Hello, > > I'm quite new in Python and I have one question. I have a 2D matrix of > values stored in list (3 columns, many rows). I wonder if I can select one > column without having to go through the list with 'for' command. Lists don't have columns. What you have is a list of lists (and FWIW, in your case, it should be a list of tuples since obviously these are fixed-size items where position is meaningfull). > For example I have list called 'values'. > When I write 'values[0]' or 'values[0][:]' I'll get the first row. Not exactly. In the first case, you have a reference to values[0], in the second case a _copy_ of values[0] >>> alist = [[1, 2, 3], [4, 5, 6]] >>> ref = alist[0] >>> copy = alist[0][:] >>> ref is alist[0] True >>> copy is alist[0] False >>> copy[0] = 999 >>> copy [999, 2, 3] >>> alist [[1, 2, 3], [4, 5, 6]] >>> ref [1, 2, 3] >>> ref[0] = 888 >>> alist [[888, 2, 3], [4, 5, 6]] >>> > But when I write 'values[:][0]' I won't get the first column, but the first > row again! I can't see why. alist[:] returns a copy the whole list. As I said, lists don't have "columns". So yes, given your data structure, you do have to iterate over the outer list to collect items at specific positions of the inner lists (or tuples). Depending on the size of your dataset, the frequency of such operation in your code, and required perfs, you can either * just do the simplest thing, ie: first_column_items = [row[0] for row in values] * try to find a more suited datastructure * of just use the most appropriate tool for set operations, which is a relational database. FWIW, sqlite doesn't require any server setup, and can even be used with in-memory databases if you don't need persistance. HTH From vlastimil.brom at gmail.com Fri Aug 28 05:28:38 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Fri, 28 Aug 2009 11:28:38 +0200 Subject: Select column from a list In-Reply-To: <25185508.post@talk.nabble.com> References: <25185508.post@talk.nabble.com> Message-ID: <9fdb569a0908280228g59038ba1u30d6d5ef9d6a80ca@mail.gmail.com> 2009/8/28 hoffik : > > Hello, > > I'm quite new in Python and I have one question. I have a 2D matrix of > values stored in list (3 columns, many rows). I wonder if I can select one > column without having to go through the list with 'for' command. > ... I guess, it won't be possible without an explicit or implicit loop; you may try: >>> from operator import itemgetter >>> nested_list = [[1, 2, 3], [10, 20, 30], [100, 200, 300]] >>> map(itemgetter(1), nested_list) [2, 20, 200] >>> vbr From anthra.norell at bluewin.ch Fri Aug 28 05:59:17 2009 From: anthra.norell at bluewin.ch (Anthra Norell) Date: Fri, 28 Aug 2009 11:59:17 +0200 Subject: Select column from a list In-Reply-To: <9fdb569a0908280228g59038ba1u30d6d5ef9d6a80ca@mail.gmail.com> References: <25185508.post@talk.nabble.com> <9fdb569a0908280228g59038ba1u30d6d5ef9d6a80ca@mail.gmail.com> Message-ID: <4A97AA75.3040101@bluewin.ch> Vlastimil Brom wrote: > 2009/8/28 hoffik : > >> Hello, >> >> I'm quite new in Python and I have one question. I have a 2D matrix of >> values stored in list (3 columns, many rows). I wonder if I can select one >> column without having to go through the list with 'for' command. >> ... >> > > I guess, it won't be possible without an explicit or implicit loop; > you may try: > > >>>> from operator import itemgetter >>>> nested_list = [[1, 2, 3], [10, 20, 30], [100, 200, 300]] >>>> map(itemgetter(1), nested_list) >>>> > [2, 20, 200] > > > vbr > How about rotating the list with zip? >>> zip (*nested_list)[1] (2, 20, 200) Frederic From marduk at letterboxes.org Fri Aug 28 06:19:18 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Fri, 28 Aug 2009 06:19:18 -0400 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <2d56febf0908280204k73a41cc0j63717c8ca258ff33@mail.gmail.com> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <87k50ob9o9.fsf@benfinney.id.au> <2d56febf0908280204k73a41cc0j63717c8ca258ff33@mail.gmail.com> Message-ID: <1251454758.12823.1.camel@blackwidow.nbk> On Fri, 2009-08-28 at 19:04 +1000, Xavier Ho wrote: > On Fri, Aug 28, 2009 at 6:54 PM, Ben Finney +python at benfinney.id.au> wrote: > Fortunately, the messages that come from the list enable any > mail client > to know the correct address for ?reply to list?. It only > remains to > choose a mail client that knows how to use it. > > Would you be so kind and share with us for such a client that knows > how to use the mailing list attribute? Evolution at least is mailing-list aware. I usually "Reply to List" (CTRL-L) and fugetaboutit. From olivier.darge at gmail.com Fri Aug 28 06:53:03 2009 From: olivier.darge at gmail.com (OdarR) Date: Fri, 28 Aug 2009 03:53:03 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: <2aab5093-5381-42e3-a3dd-1d2e88e36004@32g2000yqj.googlegroups.com> On 28 ao?t, 02:47, MRAB wrote: > Deep_Feelings wrote: > > python got relatively fewer numbers of developers than other high > > level languages like .NET , java .. etc ?why ? > > Fewer needed? excellent answer. LOL. Olivier From usenot at geekmail.INVALID Fri Aug 28 07:13:22 2009 From: usenot at geekmail.INVALID (Andreas Waldenburger) Date: Fri, 28 Aug 2009 13:13:22 +0200 Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <20090827213628.180142f6@geekmail.INVALID> <20090827214240.70aeb792@geekmail.INVALID> <4587853e-5aaa-4be0-af87-d758481c6077@r42g2000yqj.googlegroups.com> <9f3083b4-4886-41c3-9404-d7eac300964b@l35g2000pra.googlegroups.com> Message-ID: <20090828131322.6173ade1@geekmail.INVALID> On Fri, 28 Aug 2009 09:03:49 +0100 Mark Lawrence wrote: > p.s. is it "separator" or "seperator", after 50+ years I still can't > remember? The former. It's cognate to English "part" if that helps any. /W -- INVALID? DE! From find.mig at paa.google Fri Aug 28 07:15:50 2009 From: find.mig at paa.google (Esben von Buchwald) Date: Fri, 28 Aug 2009 13:15:50 +0200 Subject: Protecting against callbacks queuing up? In-Reply-To: <4a970bd7$0$333$14726298@news.sunsite.dk> References: <4a91db65$0$305$14726298@news.sunsite.dk> <4a9595ca$0$300$14726298@news.sunsite.dk> <4a970bd7$0$333$14726298@news.sunsite.dk> Message-ID: <4a97bc7e$0$339$14726298@news.sunsite.dk> It seems to solve the problem. What I did: def contextDataHandler(self): self.contextdata.process_busy=True self.services.findServices() self.drawDisplay() self.contextdata.process_busy=False def doCallback(self): self.at.cancel() if self.process_busy==False: self.at.after(0.01,self.data_callback) The app works awesomely stable now data_callback refers to contextDataHandler in parent class Thanks guys, good job From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 07:40:28 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 13:40:28 +0200 Subject: Python on the Web In-Reply-To: <1b7a2f45-dd10-4722-a9d8-8c6d2464e4d6@e27g2000yqm.googlegroups.com> References: <4a94ef42$0$27774$426a74cc@news.free.fr> <4a96884b$0$22855$426a74cc@news.free.fr> <1b7a2f45-dd10-4722-a9d8-8c6d2464e4d6@e27g2000yqm.googlegroups.com> Message-ID: <4a97c215$0$16809$426a74cc@news.free.fr> Phil a ?crit : > When > I gave that arbitrary percentage, I was basing it off of the > information I had seen with regards to launching applications built > with existing frameworks using lighttpd. I do realize I was missing a > lot of information by looking up something that specific. Indeed !-) > I also > understand that there are enough frameworks. That still won't change > my mind. I do not want to write a web application, otherwise I would > use an existing framework as suggested. I just wanted to experiment > and see what kind of framework I could develop with some ideas I had > in mind. I wrote quite a couple web and non web frameworks myself - all ending up in the trash can FWIW, but it certainly has been a very educative experience by itself. > I just really like some of the new features of > Python 3, and most importantly, unicode compliance is just that much > straight forward in my opinion. If you're only writing your framework for learning purposes, you could as well go with Python 3, and implement everything from the ground up (not a trivial task FWIW). From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 07:45:13 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 13:45:13 +0200 Subject: Learning Python advanced features In-Reply-To: <4a977b20$0$740$426a34cc@news.free.fr> References: <4a967864$0$15193$426a74cc@news.free.fr> <4a967bd6$0$19301$426a74cc@news.free.fr> <4a977b20$0$740$426a34cc@news.free.fr> Message-ID: <4a97c331$0$16809$426a74cc@news.free.fr> jvpic a ?crit : > Bruno Desthuilliers a ?crit : >> jvpic a ?crit : >>> Hi, >>> >>> Learning Python, I understand the mechanism of : closure, __new__, >>> descriptors, decorators and __metaclass__, but I interrogate myself >>> on the interest of those technics ? >>> >>> May somebody explain me the interest ? >> >> Didn't like my answers on f.c.l.py ?-) > Si, mais je voulais savoir ce qu'on en pense sur un autre forum ! > Merci encore... Hum... I guess the smiley was not big enough !-) From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 07:48:07 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 13:48:07 +0200 Subject: Learning Python advanced features In-Reply-To: <6b1a2aae-fd3d-40a8-9350-89a8661a6d4a@a37g2000prf.googlegroups.com> References: <4a967864$0$15193$426a74cc@news.free.fr> <6b1a2aae-fd3d-40a8-9350-89a8661a6d4a@a37g2000prf.googlegroups.com> Message-ID: <4a97c3df$0$16809$426a74cc@news.free.fr> Jonathan Gardner a ?crit : > On Aug 27, 5:13 am, jvpic wrote: >> Hi, >> >> Learning Python, I understand the mechanism of : closure, __new__, >> descriptors, decorators and __metaclass__, but I interrogate myself on >> the interest of those technics ? >> >> May somebody explain me the interest ? >> > > I assume you are asking, "Why do these features exist? What makes them > useful? When would I use them?" > > For that, you should re-read the documentation and discussion > surrounding them. The short answer is that the above makes your job, > as a programmer easier. It's easier because you have to write less > code, read less code, and your code has fewer bugs. I think the OP is mostly looking for practical use cases. FWIW, when I discovered Python's "lambda" (I only knew a couple low-level imperative languages by that time), I really wondered what an anonymous function could be used for !-) From martin.hellwig at dcuktec.org Fri Aug 28 07:56:08 2009 From: martin.hellwig at dcuktec.org (Martin P. Hellwig) Date: Fri, 28 Aug 2009 12:56:08 +0100 Subject: why python got less developers ? In-Reply-To: References: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> Message-ID: Esam Qanadeely wrote: > who cares if a language is compiled or interpreted as long as it runs > and perform the function. > > second thing is : even if java is faster than python , unless you are > making performance critical operations : who cares? computers are > getting faster all the time and languages like python or ruby are fast > enough. > > any comment ? I like to second that, if performance is *that* important you wouldn't go with Java either, you be better of with C or even assembly. Doesn't mean you should write everything in C, just the parts that are performance critical, preferably with a 'slow' fall back if there isn't an optimized routine available yet for a specific platform. -- MPH http://blog.dcuktec.com 'If consumed, best digested with added seasoning to own preference.' From bruno.42.desthuilliers at websiteburo.invalid Fri Aug 28 08:07:05 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 14:07:05 +0200 Subject: Object's nesting scope In-Reply-To: <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> Message-ID: <4a97c851$0$307$426a74cc@news.free.fr> zaur a ?crit : > On 26 ???, 17:13, "Diez B. Roggisch" wrote: >> Whom am we to judge? Sure if you propose this, you have some usecases in >> mind - how about you present these > > Ok. Here is a use case: object initialization. > > For example, > > person = Person(): > name = "john" > age = 30 > address = Address(): > street = "Green Street" > no = 12 > > vs. > > person = Person() > person.name = "john" > person.age = 30 > address = person.address = Address() > address.street = "Green Street" > address.no = 12 Err... Looks like you really should read the FineManual(tm) - specifically, the parts on the __init__ method. class Person(object): def __init__(self, name, age, address): self.name = name self.age = age self.address = address class Address(object): def __init__(self, street, no): self.no = no self.street = street person = Person( name="john", age=30, address = Address( street="Green Street", no=12 ) ) From dukeofperl at ml1.net Fri Aug 28 08:34:08 2009 From: dukeofperl at ml1.net (Duke Normandin) Date: Fri, 28 Aug 2009 06:34:08 -0600 (MDT) Subject: Transforming a str to an operator In-Reply-To: <7a9c25c20908272132p737fe070w5a3c7b0a4970a2c9@mail.gmail.com> References: <7a9c25c20908272132p737fe070w5a3c7b0a4970a2c9@mail.gmail.com> Message-ID: On Thu, 27 Aug 2009, Stephen Hansen wrote: > > > > num1 = raw_input('Enter the first number: ') > > num2 = raw_input('Enter the second number: ') > > op = raw_input('Select one of the following [+-*/]: ') > > print 'The answer is: ', int(num1), eval(op), int(num2) > > ^^^^^^^^ > > > > How do I convert the contents of "op" from a string to an actual > > arithmetic operator? eval() does not seem to be the answer. TIA! > > > > You could eval(num1+op+num2), but it'd be safer to do: > > import operator > operators = {"+": operator.add, "-": operator.sub, "*": operator.mul, "/": > operator.div} > fn = operators[op] > print "The answer is:", fn(int(num1), int(num2)) > > Its best to avoid eval when possible :) > > --S > In *any* language "eval" is dangerous, so your second example would also be my choice. Thanks for the clue. BTW, I hunted hi-n-lo for something that would address my question at http://docs.python.org. I obviously didn't have much luck. Something about those docs that is confusing.... -- duke From bbxx789_05ss at yahoo.com Fri Aug 28 08:40:46 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 28 Aug 2009 05:40:46 -0700 (PDT) Subject: Sending email References: <7fpj9tF2clhemU1@mid.individual.net> Message-ID: <2b3621fd-53fc-4f20-a048-3608894e52af@o9g2000prg.googlegroups.com> On Aug 28, 2:37?am, Fencer wrote: > Hello, I'm using Python version 2.6.2 and I discovered it has built-in > libraries for sending email (imports smtplib and email). On the web I > discovered how to send mail through smtp.gmail.com: > > mail_server = smtplib.SMTP() > > mail_server.connect('smtp.gmail.com') > mail_server.ehlo() > mail_server.starttls() > mail_server.ehlo() > mail_server.login('username', 'password') > > msg = MIMEText('Some message text') > msg['Subject'] = 'Some subject' > msg['From'] = 'Mr Underhill' > msg['To'] = 'someemailaddress' > > me = 'myemailaddress' > mail_server.sendmail(me, ['someemailaddress'], msg.as_string()) > > That seems to work just fine but for the messages I will be sending I > don't want to use my private GMail account. > We have an SMTP server at work, and I checked its settings in the > Thunderbird mail client and it's using SSL over port 465, so a bit > different from how GMail's SMTP server is configured in Thunderbird. > > I altered my code slightly to account for this: > mail_server = smtplib.SMTP_SSL() > mail_server.connect('mysmtpserver.at.work', 465) > > Everything I left untouched. However, it doesn't work: > Traceback (most recent call last): > ? ?File "C:\Users\fencer\workspace\Send Email\src\send_email.py", line > 16, in > ? ? ?mail_server.ehlo() > ? ?File "C:\Python26\lib\smtplib.py", line 382, in ehlo > ? ? ?self.putcmd(self.ehlo_msg, name or self.local_hostname) > ? ?File "C:\Python26\lib\smtplib.py", line 318, in putcmd > ? ? ?self.send(str) > ? ?File "C:\Python26\lib\smtplib.py", line 310, in send > ? ? ?raise SMTPServerDisconnected('please run connect() first') > smtplib.SMTPServerDisconnected: please run connect() first > > As you can see, I'm on Windows Vista. > > What do I need to change in my code to fix this problem? Thunderbird > manages to do it! :) Ideally, I would like send an email that the > recipient can't reply to, but if doesn't work, it's fine too. I want to > use this to send automated emails to students with account information > for a course. > > - Fencer The docs say: --- class smtplib.SMTP_SSL([host[, port[, local_hostname[, keyfile[, certfile[, timeout]]]]]]) A SMTP_SSL instance behaves exactly the same as instances of SMTP. SMTP_SSL should be used for situations where SSL is required from the beginning of the connection and using starttls() is not appropriate. --- So try getting ride of these two lines: > mail_server.starttls() > mail_server.ehlo() There's also some info on google about a bug in this regard, so check to see when you installed python 2.6.2. From zvezdan at zope.com Fri Aug 28 09:12:29 2009 From: zvezdan at zope.com (Zvezdan Petkovic) Date: Fri, 28 Aug 2009 09:12:29 -0400 Subject: Does Class implements Interface? In-Reply-To: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> References: <800d9226-6bbc-447e-a171-83777a9634b8@c34g2000yqi.googlegroups.com> Message-ID: On Aug 27, 2009, at 9:16 AM, Emanuele D'Arrigo wrote: > Are there resources such as tools, recipes, documents or strategies > that could help me deal with these issues? I've already looked into > the ABC module and the zope.interface. I'm just fishing for more > things to look at. You say above that you looked at zope.interface. Did you look at zope.interface.verify? Specifically, verify.txt doctests state that: "An object provides an interface if - either its class declares that it implements the interfaces, or the object declares that it directly provides the interface - the object defines all the methods required by the interface - all the methods have the correct signature - the object defines all non-method attributes required by the interface" zope.interface.verify.verifyObject(I, obj) will check all of the above. Similarly, zope.interface.verify.verifyClass(I, C) will check the class. It is a good practice to call these functions in the regression tests. If this is not what you are looking for, sorry for the noise. Zvezdan From piet at cs.uu.nl Fri Aug 28 09:23:47 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 28 Aug 2009 15:23:47 +0200 Subject: Select column from a list References: Message-ID: >>>>> hoffik (h) wrote: >h> Hello, >h> I'm quite new in Python and I have one question. I have a 2D matrix of >h> values stored in list (3 columns, many rows). I wonder if I can select one >h> column without having to go through the list with 'for' command. >h> For example I have list called 'values'. >h> When I write 'values[0]' or 'values[0][:]' I'll get the first row. >h> But when I write 'values[:][0]' I won't get the first column, but the first >h> row again! I can't see why. If you work with matrices, numpy may be interesting for you. It does have the required functionality: M[:,0] will give you the first column. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From lucafbb at gmail.com Fri Aug 28 09:33:39 2009 From: lucafbb at gmail.com (Luca) Date: Fri, 28 Aug 2009 15:33:39 +0200 Subject: Read a content file from a P7M In-Reply-To: <20090320141244.GA31004@galliera.it> References: <27308d500903110905j336da086ya39300c876aa95a5@mail.gmail.com> <20090320141244.GA31004@galliera.it> Message-ID: <27308d500908280633u310ed4ffu8fe753d69a575265@mail.gmail.com> On Fri, Mar 20, 2009 at 4:12 PM, Emanuele Rocca wrote: > On 11/03/09 - 05:05, Luca wrote: >> There is standard or sugested way in python to read the content of a P7M file? >> >> I don't need no feature like verify sign, or sign using a certificate. >> I only need to extract the content file of the p7m (a doc, a pdf, ...) > > For PDF files you can just remove the P7M content before %PDF and after > %%EOF. > > The following snippet converts /tmp/test.p7m into PDF, saving the > resulting document into /tmp/test.pdf: > > import re > from gzip import GzipFile > > contents = GzipFile('/tmp/test.p7m').read() > > contents_re = re.compile('%PDF-.*%%EOF', re.MULTILINE | re.DOTALL) > contents = contents_re.search(contents).group() > > open('/tmp/test.pdf', 'w').write(contents) > After all those days... only to say THANKS! The example of the PDF file is perfect, I only needed to not execute the GzipFile call (it seems that our PDF are not GZipped). Unluckily now seems that we need the same feature for non-pdf files... -- -- luca From hv at tbz-pariv.de Fri Aug 28 09:42:36 2009 From: hv at tbz-pariv.de (Thomas Guettler) Date: Fri, 28 Aug 2009 15:42:36 +0200 Subject: PyGTK problems after Linux update... In-Reply-To: References: Message-ID: <7fq56dF2m6qlbU1@mid.individual.net> Looks like your pygtk package does not fit to the installed python package. > from glib._glib import * > ImportError: /usr/lib/python2.6/site-packages/gtk-2.0/glib/_glib.so: > undefined symbol: PyUnicodeUCS4_DecodeUTF8 -- Thomas Guettler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de From steve at REMOVE-THIS-cybersource.com.au Fri Aug 28 09:43:05 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2009 13:43:05 GMT Subject: Numeric literals in other than base 10 - was Annoying octal notation References: <9Wjkm.71294$OO7.22863@text.news.virginmedia.com> <02a31f91$0$20629$c3e8da3@news.astraweb.com> <44bcb727-0885-4d4f-9c11-ca60a39b0d91@w6g2000yqw.googlegroups.com> <02a3e1e2$0$20629$c3e8da3@news.astraweb.com> <02a53d89$0$20629$c3e8da3@news.astraweb.com> <8d25833e-8008-42e9-ad24-10ddd4f6cbef@k6g2000yqn.googlegroups.com> <02a5d290$0$15633$c3e8da3@news.astraweb.com> <02a5ed07$0$15633$c3e8da3@news.astraweb.com> <9f392780-cb72-4bdb-a571-b1c218f3cbf8@k19g2000yqn.googlegroups.com> Message-ID: <00216264$0$2930$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 10:49:27 -0700, Mensanator wrote: > Fine. I'm over it. Point is, I HAVE encountered plenty of people who > DON'T properly understand it, Marilyn Vos Savant, for example. I'm curious -- please explain. Links please? > You can't > blame me for thinking you don't understand it either when unary is > brought up in a discussion of how to interpret insignificant leading > 0's. Er, when I show an example of what I'm calling unary, and then later on explain in detail and link to a detailed discussion of it, who exactly should I blame for your confusion? -- Steven From steve at REMOVE-THIS-cybersource.com.au Fri Aug 28 09:51:08 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2009 13:51:08 GMT Subject: Annoying octal notation References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> Message-ID: <00216447$0$2930$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 10:31:04 -0700, Ethan Furman wrote: > Steven D'Aprano wrote: >> A mistake is still a mistake even if it shared with others. >> >> Treating its with a lead zero as octal was a design error when it was >> first thought up > > [snippage] > > I have to disagree with you on this one. The computing world was vastly > different when that design decision was made. Space was at a premium, > programmers were not touch-typists, every character had to count, and > why in the world would somebody who had to use papertape or punch cards > add a lead zero without a *real* good reason? I submit that that real > good reason was to specify an octal literal, and not a decimal literal. Octal with a leading 0 comes from B, which influenced C, which influenced many languages. B was designed in 1969, the same year as Pascal, not the 1950s -- six years *after* Basic, ten years after Lisp and Cobol, eleven years after Algol, and thirteen years after Fortran. *None* of these other languages use a leading 0 for Octal, and none of them are particularly terse. Obviously I can't speak for Ken Thompson's motivation in creating this feature, but I'm pretty sure it wasn't to save typing or space on punchcards. Even in 1969, hex was more common than octal, and yet hex values are written with 0x. My guess is that he wanted all numbers to start with a digit, to simplify parsing, and beyond that, it was just his programming style -- why call the copy command `copy` when you could call it `cp`? (Thompson was the co-inventor of Unix.) -- Steven From bernhard.voigt at gmail.com Fri Aug 28 09:53:49 2009 From: bernhard.voigt at gmail.com (Bernhard Voigt) Date: Fri, 28 Aug 2009 06:53:49 -0700 (PDT) Subject: Select column from a list References: <25185508.post@talk.nabble.com> <9fdb569a0908280228g59038ba1u30d6d5ef9d6a80ca@mail.gmail.com> Message-ID: <708f2333-43d7-4091-8f73-67ef5ef4752a@c2g2000yqi.googlegroups.com> > >> I'm quite new in Python and I have one question. I have a 2D matrix of > >> values stored in list (3 columns, many rows). I wonder if I can select one > >> column without having to go through the list with 'for' command. In case you want to due numerical calculations take a look at numpy it has an extended slicing notation to select columns directly. See http://www.scipy.org # create 10x10 numpy array filled with 1 data = numpy.ones((10,10)) column = data[:,0] Best wishes! Bernhard From sturlamolden at yahoo.no Fri Aug 28 09:55:55 2009 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 28 Aug 2009 06:55:55 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: On 28 Aug, 02:34, Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc ?why ? Because we are better, so fewer are needed. From jakecjacobson at gmail.com Fri Aug 28 09:57:59 2009 From: jakecjacobson at gmail.com (jakecjacobson) Date: Fri, 28 Aug 2009 06:57:59 -0700 (PDT) Subject: How to unencode a string References: <55f8f373-8e0a-4ca5-8deb-53c02e4d1137@b14g2000yqd.googlegroups.com> Message-ID: <31799652-b530-4877-8e2d-c5e7e3477ff0@d38g2000yqi.googlegroups.com> On Aug 27, 6:51?pm, Piet van Oostrum wrote: > >>>>> jakecjacobson (j) wrote: > >j> This seems like a real simple newbie question but how can a person > >j> unencode a string? ?In Perl I use something like: "$part=~ s/\%([A-Fa- > >j> f0-9]{2})/pack('C', hex($1))/seg;" > >j> If I have a string like Word1%20Word2%20Word3 I want to get Word1 > >j> Word2 Word3. ? > > urllib.unquote(string) > > >j> Would also like to handle special characters like '",(){} > >j> [] etc/ > > What would you like to do with them? Or do you mean to replace %27 by ' etc? > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: p... at vanoostrum.org Yes, take '%27' and replace with ', etc. From hamdori at gmail.com Fri Aug 28 10:11:58 2009 From: hamdori at gmail.com (Jinha Jung) Date: Fri, 28 Aug 2009 07:11:58 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: On Aug 28, 9:55?am, sturlamolden wrote: > On 28 Aug, 02:34, Deep_Feelings wrote: > > > python got relatively fewer numbers of developers than other high > > level languages like .NET , java .. etc ?why ? > > Because we are better, so fewer are needed. That makes sense!! :-) From python at mrabarnett.plus.com Fri Aug 28 10:13:00 2009 From: python at mrabarnett.plus.com (MRAB) Date: Fri, 28 Aug 2009 15:13:00 +0100 Subject: Annoying octal notation In-Reply-To: <00216447$0$2930$c3e8da3@news.astraweb.com> References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> <00216447$0$2930$c3e8da3@news.astraweb.com> Message-ID: <4A97E5EC.5010007@mrabarnett.plus.com> Steven D'Aprano wrote: > On Thu, 27 Aug 2009 10:31:04 -0700, Ethan Furman wrote: > >> Steven D'Aprano wrote: >>> A mistake is still a mistake even if it shared with others. >>> >>> Treating its with a lead zero as octal was a design error when it was >>> first thought up >> [snippage] >> >> I have to disagree with you on this one. The computing world was vastly >> different when that design decision was made. Space was at a premium, >> programmers were not touch-typists, every character had to count, and >> why in the world would somebody who had to use papertape or punch cards >> add a lead zero without a *real* good reason? I submit that that real >> good reason was to specify an octal literal, and not a decimal literal. > > Octal with a leading 0 comes from B, which influenced C, which influenced > many languages. B was designed in 1969, the same year as Pascal, not the > 1950s -- six years *after* Basic, ten years after Lisp and Cobol, eleven > years after Algol, and thirteen years after Fortran. *None* of these > other languages use a leading 0 for Octal, and none of them are > particularly terse. > > Obviously I can't speak for Ken Thompson's motivation in creating this > feature, but I'm pretty sure it wasn't to save typing or space on > punchcards. Even in 1969, hex was more common than octal, and yet hex > values are written with 0x. My guess is that he wanted all numbers to > start with a digit, to simplify parsing, and beyond that, it was just his > programming style -- why call the copy command `copy` when you could call > it `cp`? (Thompson was the co-inventor of Unix.) > Maybe it was because they were working on minicomputers, not mainframes, so there was less processing power and storage available. From steve at REMOVE-THIS-cybersource.com.au Fri Aug 28 10:14:07 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2009 14:14:07 GMT Subject: why python got less developers ? References: Message-ID: <002169aa$0$2930$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 17:34:17 -0700, Deep_Feelings wrote: > python got relatively fewer numbers of developers than other high level > languages like .NET , java .. etc why ? Python programmers are the elite. The elite are always fewer than the masses. -- Steven who is three quarters joking From dukeofperl at ml1.net Fri Aug 28 10:18:48 2009 From: dukeofperl at ml1.net (Duke Normandin) Date: Fri, 28 Aug 2009 14:18:48 GMT Subject: Transforming a str to an operator In-Reply-To: <6ee483f7-e92c-49e0-be27-125f3389b1f2@33g2000vbe.googlegroups.com> References: <6ee483f7-e92c-49e0-be27-125f3389b1f2@33g2000vbe.googlegroups.com> Message-ID: On Thu, 27 Aug 2009, r wrote: > On Aug 27, 10:52?pm, Duke Normandin wrote: > > How do I convert the contents of "op" from a string to an actual > > arithmetic operator? eval() does not seem to be the answer. TIA! > > > Try this.. > > >>> op = '+' > >>> one = '1' > >>> two = '2' > >>> one+op+two > '1+2' > >>> eval(one+op+two) > 3 > > > you could also use string formatting. I see! Concatenate the strings within the "eval()" function. Of course, it's prudent not to expose "eval" to the outside world. But for learning purposes .... Thanks for the input! -- duke From no.i.dont at want.mail.from.spammers.com Fri Aug 28 10:18:57 2009 From: no.i.dont at want.mail.from.spammers.com (Fencer) Date: Fri, 28 Aug 2009 16:18:57 +0200 Subject: Sending email In-Reply-To: <2b3621fd-53fc-4f20-a048-3608894e52af@o9g2000prg.googlegroups.com> References: <7fpj9tF2clhemU1@mid.individual.net> <2b3621fd-53fc-4f20-a048-3608894e52af@o9g2000prg.googlegroups.com> Message-ID: <7fq7aiF2mp83gU1@mid.individual.net> 7stud wrote: [snip] Thanks for your reply. After consulting the sysadmins here I was able to get it to work. - Fencer From dukeofperl at ml1.net Fri Aug 28 10:23:16 2009 From: dukeofperl at ml1.net (Duke Normandin) Date: Fri, 28 Aug 2009 14:23:16 GMT Subject: Transforming a str to an operator In-Reply-To: <87skfcblo3.fsf@benfinney.id.au> References: <87skfcblo3.fsf@benfinney.id.au> Message-ID: On Fri, 28 Aug 2009, Ben Finney wrote: > Duke Normandin writes: > > > Hey.... > > > > I'm a Python noob.... > > > > So far so good! > > > > I've written the following: > > > > num1 = raw_input('Enter the first number: ') > > num2 = raw_input('Enter the second number: ') > > op = raw_input('Select one of the following [+-*/]: ') > > print 'The answer is: ', int(num1), eval(op), int(num2) > > ^^^^^^^^ > > > > How do I convert the contents of "op" from a string to an actual > > arithmetic operator? eval() does not seem to be the answer. TIA! > > In general, ?eval? on unsanitised input is not the answer. Agreed! If I were to expose "eval" to the 'net, I would have some input error checking and "type" checks to insure that only integers and valid operators were being input. > > I would use the following approach: > > import operator > > op_funcs = { > '+': operator.add, > '-': operator.sub, > '*': operator.mul, > '/': operator.div, > } > > num_1 = int(raw_input('Enter the first number: ')) > num_2 = int(raw_input('Enter the second number: ')) > op_prompt = ( > "Select an operator " > + "[" + "".join(s for s in op_funcs.keys()) + "]" > + ": ") > op_symbol = raw_input(op_prompt) > op_func = op_funcs[op_symbol] > print 'The answer is: ', op_func(num_1, num_2) > > This has several advantages: > > * The input isn't evaluated directly as code. > > * The operator symbols are specified in one place, the ?op_funcs? > mapping; if you want to change the set of possible operators, you just > change it there. > > * If the input results in an operator that's not defined, it won't > attempt to perform it; instead, a simple KeyError will result when > trying to find the corresponding operator function. Cool! Something useful to study... Thanks for the input! -- duke From steve at REMOVE-THIS-cybersource.com.au Fri Aug 28 10:30:00 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 28 Aug 2009 14:30:00 GMT Subject: Algorithms as objects? References: Message-ID: <00216d63$0$2930$c3e8da3@news.astraweb.com> On Thu, 27 Aug 2009 23:05:41 +0000, Kreso wrote: > I am writing an application that essentially calculates set of numbers, > say N1, N2, ..., where they can be calculated by several different > algorithms. (One should be able to choose the algorithm at run time.) In > each algorithm one starts from a set of functions, say f1, f2, ..., > which are then transformed into some other functions g1(f1, f2, ..), > g2(f1, f2, ...), ... , then maybe transformed once more and result is > obtained by evaluating final functions. Sounds like you're doing functional programming. There's a rich set of functional tools in languages like Haskell, but in Python there's only a few, such as partial(). (See the functools module.) However, you can make your own, using the following general technique. Suppose you want to compose two functions, f and g. Then with a helper function: def compose(f, g): def composed_function(*args): return f(g(*args)) return composed_function you can do this: >>> def add1(x): ... return x+1 ... >>> def double(y): ... return 2*y ... >>> double_plus_one = compose(add1, double) >>> double_plus_one(3.5) 8.0 Unfortunately, about the only thing you can't do is check the return type of functions without actually calling them. > I can naturally think about this as a collection of transformation > blocks, which have functions as input and output, and which can be put > together to get the final results. However, I am not sure how to program > this, especially since one cannot subclass function type. To be clear > let me give simplified example of what is needed: > > f(x) has unknown shape, so one would like to try, say > > f1(x) = ax - b x**2 or f2(x) = a sin(b*x), > > where a and b are variable parameters. You need factory functions! def axbx2_factory(a, b): # Return a function that returns a*x-b*x**2 def inner(x): return a*x -b*x**2 return inner And in use: >>> f1 = axbx2_factory(1, 2) >>> f2 = axbx2_factory(1, 0) >>> f1(2.5) -10.0 >>> f1(3.5) -21.0 >>> f2(2.5) 2.5 >>> f2(3.5) 3.5 Hope this helps. -- Steven From rt8396 at gmail.com Fri Aug 28 10:41:27 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 07:41:27 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> Message-ID: Thanks eb303 for the wonderful post I have looked over the new ttk widgets and everything looks nice. I am very glad to see the death of Tix as i never much liked it anyhow and always believed these widgets should have been in the main Tkinter module to start with. The tree widget has been needed for some time. However, i am not sure about the new "style" separation. Previously a simple command like root.option_add('*Label.Font'...) accomplished the same thing with less typing, but there may be a future method to this current madness that i am unaware of...??? From rknop at pobox.com Fri Aug 28 10:51:09 2009 From: rknop at pobox.com (Rob Knop) Date: Fri, 28 Aug 2009 09:51:09 -0500 Subject: write Unicode to sys.out.write without access to sitecustomize.py Message-ID: <871vmw56w2.fsf@pobox.com> I would like to tell the system that it's OK to write Unicode to sys.out and sys.err. However, I'm doing this in a CGI script where I don't have access to the system directories, and as such can't use sys.setdefaultencoding in sitecustomize.py. Is there a way to make this happen? -- --Rob Knop E-mail: rknop at pobox.com Home Page: http://www.pobox.com/~rknop/ Blog: http://www.sonic.net/~rknop/blog/ From gb345 at invalid.com Fri Aug 28 10:58:11 2009 From: gb345 at invalid.com (gb345) Date: Fri, 28 Aug 2009 14:58:11 +0000 (UTC) Subject: Modules/packages by GvR? Message-ID: Are there any Python-only modules or packages in the latest releases of Python 2.x or Python 3.x that were largely written by Guido van Rossum? What's the best way to find this out? I know that some modules mention the author(s) in the source code, but this does not seem to be true most of the time, as far as I can tell. I'm interested in reading this code as prime examplars of "Pythonicity". (I'm sure that many other programmers could serve as models of the Pythonic ideal, but I doubt that there would be a *less debatable* choice in this category than GvR.) Many thanks in advance, Gabe From gagsl-py2 at yahoo.com.ar Fri Aug 28 10:58:13 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Aug 2009 11:58:13 -0300 Subject: Transforming a str to an operator References: <87skfcblo3.fsf@benfinney.id.au> <2d56febf0908272150y59e5d458hab1fc6aa9c14187e@mail.gmail.com> Message-ID: En Fri, 28 Aug 2009 01:50:37 -0300, Xavier Ho escribi?: > On Fri, Aug 28, 2009 at 2:35 PM, Ben Finney > >> wrote: > >> op_funcs = { >> '+': operator.add, >> '-': operator.sub, >> '*': operator.mul, >> '/': operator.div, >> } >> op_prompt = "Select an operator ({}):".format(','.join(op for op in >> op_funcs)) op_prompt = "Select an operator ({}):".format(','.join(op_funcs)) > Just fixing the code a little to be more "Pythonic" ;). Even more ;) -- Gabriel Genellina From breamoreboy at yahoo.co.uk Fri Aug 28 11:12:50 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Aug 2009 16:12:50 +0100 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org In-Reply-To: <2d56febf0908280204k73a41cc0j63717c8ca258ff33@mail.gmail.com> References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <87k50ob9o9.fsf@benfinney.id.au> <2d56febf0908280204k73a41cc0j63717c8ca258ff33@mail.gmail.com> Message-ID: Xavier Ho wrote: > On Fri, Aug 28, 2009 at 6:54 PM, Ben Finney > >> wrote: > >> Fortunately, the messages that come from the list enable any mail client >> to know the correct address for ?reply to list?. It only remains to >> choose a mail client that knows how to use it. > > > Would you be so kind and share with us for such a client that knows how to > use the mailing list attribute? > > Thanks! > -Xav > > Further to the earlier reply from Albert Hopkins, I use Thunderbird on Windows and just hit reply. The message I reply to is "from Xavier Ho " and "to python-list at python.org". I think this sums it up. -- Kindest regards. Mark Lawrence. From bouncyinc at gmail.com Fri Aug 28 11:18:06 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Fri, 28 Aug 2009 09:18:06 -0600 Subject: Modules/packages by GvR? In-Reply-To: References: Message-ID: How is writing code like a language maintainer going to go towards a philosophic ideal? And more principally why would this be of a benefit. In the philosophic world dressing and acting like Socrates isn't necessarily the same as following his ideals and isn't necessarily being Socratic. On Fri, Aug 28, 2009 at 8:58 AM, gb345 wrote: > > > > > Are there any Python-only modules or packages in the latest releases > of Python 2.x or Python 3.x that were largely written by Guido van > Rossum? What's the best way to find this out? I know that some > modules mention the author(s) in the source code, but this does > not seem to be true most of the time, as far as I can tell. > > I'm interested in reading this code as prime examplars of "Pythonicity". > (I'm sure that many other programmers could serve as models of the > Pythonic ideal, but I doubt that there would be a *less debatable* > choice in this category than GvR.) > > Many thanks in advance, > > Gabe > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at twistedmatrix.com Fri Aug 28 11:22:49 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Fri, 28 Aug 2009 15:22:49 -0000 Subject: write Unicode to sys.out.write without access to sitecustomize.py In-Reply-To: <871vmw56w2.fsf@pobox.com> References: <871vmw56w2.fsf@pobox.com> Message-ID: <20090828152249.7507.1150495477.divmod.xquotient.5@localhost.localdomain> On 02:51 pm, rknop at pobox.com wrote: > >I would like to tell the system that it's OK to write Unicode to >sys.out >and sys.err. However, I'm doing this in a CGI script where I don't >have >access to the system directories, and as such can't use >sys.setdefaultencoding in sitecustomize.py. > >Is there a way to make this happen? Sure, just replace the two files with versions that know how to encode the unicode using the correct encoding: import sys, codecs info = codecs.lookup('utf-8') # for example sys.stdout = info.streamwriter(sys.stdout) sys.stderr = info.streamwriter(sys.stderr) Jean-Paul From mccredie at gmail.com Fri Aug 28 11:28:02 2009 From: mccredie at gmail.com (Matimus) Date: Fri, 28 Aug 2009 08:28:02 -0700 (PDT) Subject: Modules/packages by GvR? References: Message-ID: <789935e7-1952-49bb-8ae1-90b7787d5ff2@r24g2000prf.googlegroups.com> On Aug 28, 7:58?am, gb345 wrote: > Are there any Python-only modules or packages in the latest releases > of Python 2.x or Python 3.x that were largely written by Guido van > Rossum? ?What's the best way to find this out? ?I know that some > modules mention the author(s) in the source code, but this does > not seem to be true most of the time, as far as I can tell. > > I'm interested in reading this code as prime examplars of "Pythonicity". > (I'm sure that many other programmers could serve as models of the > Pythonic ideal, but I doubt that there would be a *less debatable* > choice in this category than GvR.) > > Many thanks in advance, > > Gabe I'm sure there are. You might be able to figure that out by browsing the source repository: http://hg.python.org. But, I wouldn't necessarily say that any code written by Guido would make a good example of 'Pythonic' code. Not that he doesn't create good code, but the language and standards have evolved over time. There may be code that he wrote from the 2.0 days that may have been perfectly 'Pythonic' then but is just out-of-date now. In general though, browsing the standard modules is a good way to find examples, no matter who wrote it. Just keep in mind when it was written more than who wrote it. Matt From jfabiani at yolo.com Fri Aug 28 11:36:24 2009 From: jfabiani at yolo.com (jfabiani at yolo.com) Date: Fri, 28 Aug 2009 08:36:24 -0700 Subject: why python got less developers ? References: Message-ID: Chris Rebert wrote: > On Thu, Aug 27, 2009 at 5:34 PM, Deep_Feelings > wrote: >> python got relatively fewer numbers of developers than other high >> level languages like .NET , java .. etc ?why ? > > We lack Sun and Microsoft's massive marketing departments. :) I'm inclined to agreed. But in recent years we lost a number of developers to Ruby. I don't know but I doubt Ruby has a marketing budget. So in my mind it is difficult for me to blame just the lack of marketing dollars for the lost. I do take heart in a recent article (on Linux today). that less than 5% of open source is using C#. Which tells me that .Net in the open source world is not doing well. So in my opinion the OP is wrong when he includes .Net in his assessment of developers. As far as what the OP is suggesting I'm not to sure it matters how many total developers are using Python. Python is always in the top ten of the languages in use. And therefore is very popular. I use it daily. But it does not mean I don't use other languages too. Johnf From ethan at stoneleaf.us Fri Aug 28 11:42:26 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Fri, 28 Aug 2009 08:42:26 -0700 Subject: Need help with Python scoping rules In-Reply-To: References: Message-ID: <4A97FAE2.4060108@stoneleaf.us> kj wrote: > Miles Kaufmann writes: >>...because the suite >>namespace and the class namespace would get out of sync when different >>objects were assigned to the class namespace: > > >>class C: >> x = 1 >> def foo(self): >> print x >> print self.x > > >>>>>o = C() >>>>>o.foo() >> >>1 >>1 >> >>>>>o.x = 2 >>>>>o.foo() >> >>1 >>2 > > > But this unfortunate situation is already possible, because one > can already define > > class C: > x = 1 > def foo(self): > print C.x > print self.x > > which would lead to exactly the same thing. > This is not the same thing, and definitely not exactly the same thing. In your example you are explicitly stating whether you want the original class variable, or the current, and possibly different, instance variable. Further, the instance variable will not be different from the class variable, even after C.x = whatever, unless the instance has had that variable set specifically for it. In [1]: class C(object): ...: x = 9 ...: def doit(self): ...: print C.x ...: print self.x ...: In [2]: test = C() In [3]: test.doit() 9 9 In [4]: C.x = 10 In [5]: test.doit() 10 10 In [6]: test.x = 7 In [7]: test.doit() 10 7 ~Ethan~ From googleaccount at rumbalski.com Fri Aug 28 11:43:42 2009 From: googleaccount at rumbalski.com (Steven Rumbalski) Date: Fri, 28 Aug 2009 08:43:42 -0700 (PDT) Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> Message-ID: <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> On Aug 27, 3:06?pm, vsoler wrote: > I am trying to read a csv file generated by excel. > > Although I succeed in reading the file, the format that I get is not > suitable for me. > > I've done: > > >>> import csv > >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) > >>> print spamReader > > <_csv.reader object at 0x01022E70> > > >>> for row in spamReader: > > ? ? ? ? print row > > ['codigo;nombre;cantidad'] > ['a;qwe;1'] > ['b;asd;2'] > ['c;zxc;3'] > > My questions are: > > 1- Why using "print spamReader" I cannot see the data? > ? ? I expected to see a list of lists, a kind of a matrix, but I get > nothing > > 2- Why are the rows in a single string? > ? ?I expected a list of fields that, when text, would be delimited by > " > ? To tell the truth, the file generated by excel does not contain the > strings delimited by ". Isn't it weird? > > 3- Is there anything I can do to have my data in a list of lists > structure? would another kind of data suit better my needs? > > Thank you for your help > > Vicente Soler the csv module can handle any delimiter. change this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) to this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r'), delimiter=';') hope this helps, Steven Rumbalski From bbxx789_05ss at yahoo.com Fri Aug 28 11:49:12 2009 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 28 Aug 2009 08:49:12 -0700 (PDT) Subject: Sending email References: <7fpj9tF2clhemU1@mid.individual.net> <2b3621fd-53fc-4f20-a048-3608894e52af@o9g2000prg.googlegroups.com> <7fq7aiF2mp83gU1@mid.individual.net> Message-ID: On Aug 28, 8:18?am, Fencer wrote: > 7stud wrote: > > [snip] > > Thanks for your reply. After consulting the sysadmins here I was able to > get it to work. > > - Fencer Ok, but how about posting your code so that a future searcher will not be left screaming, "WHAT THE EFF WAS THE SOLUTION!!" From pavpanchekha at gmail.com Fri Aug 28 11:50:14 2009 From: pavpanchekha at gmail.com (Pavel Panchekha) Date: Fri, 28 Aug 2009 08:50:14 -0700 (PDT) Subject: Distutils evil voodoo: install into a package References: <824505df-5534-423e-b72c-06d0f62b376b@p15g2000vbl.googlegroups.com> <7fgi5oF2juk72U2@mid.uni-berlin.de> Message-ID: <08f192f0-fdcd-420d-9152-3873f5b77e59@j19g2000vbp.googlegroups.com> > This is what whe world has created namespace-packages for. At least if > you can live with the namespace "pya" being otherwise empty. That seems like a good solution. Thanks! From breamoreboy at yahoo.co.uk Fri Aug 28 11:56:38 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Aug 2009 16:56:38 +0100 Subject: Modules/packages by GvR? In-Reply-To: References: Message-ID: [fix top posting] > On Fri, Aug 28, 2009 at 8:58 AM, gb345 wrote: > >> >> >> >> Are there any Python-only modules or packages in the latest releases >> of Python 2.x or Python 3.x that were largely written by Guido van >> Rossum? What's the best way to find this out? I know that some >> modules mention the author(s) in the source code, but this does >> not seem to be true most of the time, as far as I can tell. >> >> I'm interested in reading this code as prime examplars of "Pythonicity". >> (I'm sure that many other programmers could serve as models of the >> Pythonic ideal, but I doubt that there would be a *less debatable* >> choice in this category than GvR.) >> >> Many thanks in advance, >> >> Gabe >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > John Haggerty wrote: > How is writing code like a language maintainer going to go towards a > philosophic ideal? And more principally why would this be of a benefit. In > the philosophic world dressing and acting like Socrates isn't necessarily > the same as following his ideals and isn't necessarily being Socratic. > So the poor old BDFL has been reduced to the rank of language maintainer. Is it safe to assume that somebody is organising a whip round for him? Any and all currencies accepted? -- Kindest regards. Mark Lawrence. From tjreedy at udel.edu Fri Aug 28 12:09:39 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Aug 2009 12:09:39 -0400 Subject: Modules/packages by GvR? In-Reply-To: <789935e7-1952-49bb-8ae1-90b7787d5ff2@r24g2000prf.googlegroups.com> References: <789935e7-1952-49bb-8ae1-90b7787d5ff2@r24g2000prf.googlegroups.com> Message-ID: Matimus wrote: > On Aug 28, 7:58 am, gb345 wrote: >> Are there any Python-only modules or packages in the latest releases >> of Python 2.x or Python 3.x that were largely written by Guido van >> Rossum? What's the best way to find this out? I know that some >> modules mention the author(s) in the source code, but this does >> not seem to be true most of the time, as far as I can tell. >> >> I'm interested in reading this code as prime examplars of "Pythonicity". >> (I'm sure that many other programmers could serve as models of the >> Pythonic ideal, but I doubt that there would be a *less debatable* >> choice in this category than GvR.) >> >> Many thanks in advance, >> >> Gabe > > I'm sure there are. You might be able to figure that out by browsing > the source repository: http://hg.python.org. But, I wouldn't > necessarily say that any code written by Guido would make a good > example of 'Pythonic' code. Not that he doesn't create good code, but > the language and standards have evolved over time. There may be code > that he wrote from the 2.0 days that may have been perfectly > 'Pythonic' then but is just out-of-date now. I am not aware of any recent stdlib modules written by Guido. I suspect most older ones have been updated at least once by someone else. > In general though, browsing the standard modules is a good way to find > examples, no matter who wrote it. Just keep in mind when it was > written more than who wrote it. The itertools module is relatively recent and has been recommended as one to read. From mark at markroseman.com Fri Aug 28 12:12:32 2009 From: mark at markroseman.com (Mark Roseman) Date: Fri, 28 Aug 2009 10:12:32 -0600 Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> Message-ID: With regard to Tkinter documentation, and in particular the newer, more modern aspects thereof (e.g. ttk, styles, etc.) please have a look at the tutorial at http://www.tkdocs.com Would it be useful to link to this from the main Python Tkinter documentation? Mark From nagle at animats.com Fri Aug 28 12:18:11 2009 From: nagle at animats.com (John Nagle) Date: Fri, 28 Aug 2009 09:18:11 -0700 Subject: Python on the Web In-Reply-To: <08ac740a-de74-4b5d-94af-35ab4dbe6ecc@m3g2000pri.googlegroups.com> References: <08ac740a-de74-4b5d-94af-35ab4dbe6ecc@m3g2000pri.googlegroups.com> Message-ID: <4a9801fa$0$1651$742ec2ed@news.sonic.net> Graham Dumpleton wrote: > A few additional comments on top of what others have said. > > On Aug 26, 11:09 am, Phil wrote: >> As I've read elsewhere, "These days, FastCGI is never used directly. Actually, FCGI works quite well. Sitetruth's AdRater (http://www.sitetruth.com/downloads/adrater.html) uses FCGI and Python on the server. FCGI is basically CGI with process reusability. Each app gets its own process in its own address space with its own global interpreter lock. mod_fcgi in Apache keeps a supply of such processes around, launching additional ones if there's heavy request traffic and shutting down existing ones when there isn't. Each process handles one transaction after another, so, unlike CGI, you're not spending all your time loading Python and its modules. Here's the main loop of a real FCGI application. This uses a small WSGI library on the Python side. No "framework" is involved. #!/usr/local/bin/python ... from fcgi import WSGIServer import MySQLdb db = None # database connection, held open for life of FCGI # # The application # def QuickSitetruthQuery(environ, start_response): global db # static global - active database handle try: if db : # if previously attached try : db.ping() # test whether connection is still up # handle loss of database connection except MySQLdb.OperationalError, message: db = None # we lost database connection if db is None : # if no valid database handle db = miscutils.dbattach(kdbfile) # connect to database status = '200 OK' # normal status headers = [('Content-type','text/xml'), ('charset','utf-8')] reqlist = cgi.parse_qsl(environ['QUERY_STRING']) # Parse params priority = 1 # priority of request sourceip = environ['REMOTE_ADDR'] # get IP address of client urls = [] # list of URLs to check for item in reqlist : # for all items (key, value) = item # extract item if key.lower() == 'url' : # want all "url" items urls.append(value) elif key.lower() == 'priority' : # if priority priority = int(value) # get priority value # Make request; no waiting, no details outstr = InfoDisplay.getratingXMLquick(db, kdbfile, urls, priority, sourceip) # get the rating XML, never wait start_response(status, headers) # compose result s = kprefixxml + outstr + ksuffixxml # construct output XML return [s.encode('utf8')] # encode as UTF8 except Exception, message: # if trouble, report to user # Error handling status = "500 Internal Error on Server" response_headers = [("Content-type","text/html")] start_response(status, response_headers) s = "

Internal error - request not processed.

\n\n" + traceback.format_exc() s = s.replace("\n","
") # convert to HTML return [s] # # Main FCGI program # WSGIServer(QuickSitetruthQuery).run() From bdesth.quelquechose at free.quelquepart.fr Fri Aug 28 12:32:36 2009 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 28 Aug 2009 18:32:36 +0200 Subject: Python on the Web In-Reply-To: <4a9812d9$0$1617$742ec2ed@news.sonic.net> References: <4a94ef42$0$27774$426a74cc@news.free.fr> <4a96884b$0$22855$426a74cc@news.free.fr> <1b7a2f45-dd10-4722-a9d8-8c6d2464e4d6@e27g2000yqm.googlegroups.com> <4a97c215$0$16809$426a74cc@news.free.fr> <4a9812d9$0$1617$742ec2ed@news.sonic.net> Message-ID: <4a98224c$0$437$426a34cc@news.free.fr> John Nagle a ?crit : > Bruno Desthuilliers wrote: >> If you're only writing your framework for learning purposes, you could >> as well go with Python 3, and implement everything from the ground up >> (not a trivial task FWIW). > > Python 3 isn't ready for prime time on web servers. Too many major > modules, > haven't been ported yet. Which ones (sorry, still using 2.5 at work so I didn't bother that much with 2.6 so far) ? > MySQLdb is available only up to Python 2.5. So the basics > for web work aren't > ready yet. I wouldn't label MySQLdb as "a basic for web work" - I mean, something you just can't do without !-) From vicente.soler at gmail.com Fri Aug 28 12:35:19 2009 From: vicente.soler at gmail.com (vsoler) Date: Fri, 28 Aug 2009 09:35:19 -0700 (PDT) Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> Message-ID: On Aug 28, 5:43?pm, Steven Rumbalski wrote: > On Aug 27, 3:06?pm, vsoler wrote: > > > > > I am trying to read a csv file generated by excel. > > > Although I succeed in reading the file, the format that I get is not > > suitable for me. > > > I've done: > > > >>> import csv > > >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) > > >>> print spamReader > > > <_csv.reader object at 0x01022E70> > > > >>> for row in spamReader: > > > ? ? ? ? print row > > > ['codigo;nombre;cantidad'] > > ['a;qwe;1'] > > ['b;asd;2'] > > ['c;zxc;3'] > > > My questions are: > > > 1- Why using "print spamReader" I cannot see the data? > > ? ? I expected to see a list of lists, a kind of a matrix, but I get > > nothing > > > 2- Why are the rows in a single string? > > ? ?I expected a list of fields that, when text, would be delimited by > > " > > ? To tell the truth, the file generated by excel does not contain the > > strings delimited by ". Isn't it weird? > > > 3- Is there anything I can do to have my data in a list of lists > > structure? would another kind of data suit better my needs? > > > Thank you for your help > > > Vicente Soler > > the csv module can handle any delimiter. > > change this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) > to this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r'), > delimiter=';') > > hope this helps, > Steven Rumbalski Thank you very much for all your comments. After reading them I can conclude that: 1- the CSV format is not standardized; each piece of software uses it differently 2- the "C" in "CSV" does not mean "comma" for Microsoft Excel; the ";" comes from my regional Spanish settings 3- Excel does not even put quotes around litteral texts, not even when the text contains a blank But, perhaps, there is no standard alternative to CSV !!! From benjamin at python.org Fri Aug 28 12:35:40 2009 From: benjamin at python.org (Benjamin Peterson) Date: Fri, 28 Aug 2009 16:35:40 +0000 (UTC) Subject: Modules/packages by GvR? References: <789935e7-1952-49bb-8ae1-90b7787d5ff2@r24g2000prf.googlegroups.com> Message-ID: Terry Reedy udel.edu> writes > > I am not aware of any recent stdlib modules written by Guido. I suspect > most older ones have been updated at least once by someone else. Guido wrote a good deal of the new Python 3 code. However, maintence has now turned over to over Python developers. For example, I now maintain 2to3 and the io library, both of which were originally written by Guido. > > > In general though, browsing the standard modules is a good way to find > > examples, no matter who wrote it. Just keep in mind when it was > > written more than who wrote it. > > The itertools module is relatively recent and has been recommended as > one to read. That probably don't do much good for your sense of Pythonicity, since it's written in C. :) From gagsl-py2 at yahoo.com.ar Fri Aug 28 12:41:35 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Aug 2009 13:41:35 -0300 Subject: Object's nesting scope References: <2751e263-ace0-4649-997c-1302d0f3b320@m20g2000vbp.googlegroups.com> <03269cff-acd9-401a-b98d-0b1136b0d2e0@s13g2000yql.googlegroups.com> <2c78ef30-3af6-45bd-b772-e09d895b0cd8@o15g2000yqm.googlegroups.com> Message-ID: En Thu, 27 Aug 2009 12:43:55 -0300, zaur escribi?: > On 27 ???, 19:19, Carl Banks wrote: >> On Aug 27, 8:01?am, zaur wrote: >> > On 27 ???, 18:34, Carl Banks wrote: >> > > The idea has been >> > > discussed in various forms here quite a bit over the years. ?I doubt >> > > there's any chance it'll be accepted into Python, because it goes >> > > against one of the main design points of Python: that attributes >> > > should always be accessed explicitly. >> > In my opinion idea of using object's dictionary as nested scope is > more about structuring code blocks rather than just saving typing and > implicit attribute access. But you *are* doing implicit attribute access. Anyway, the topic was raised and rejected several times in the past; see this recent thread in the python-ideas list: http://comments.gmane.org/gmane.comp.python.ideas/5518 -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Aug 28 13:02:32 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Aug 2009 14:02:32 -0300 Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> Message-ID: En Fri, 28 Aug 2009 13:35:19 -0300, vsoler escribi?: > On Aug 28, 5:43?pm, Steven Rumbalski > wrote: >> On Aug 27, 3:06?pm, vsoler wrote: >> > I am trying to read a csv file generated by excel. >> > ['a;qwe;1'] >> > ['b;asd;2'] >> > ['c;zxc;3'] > > Thank you very much for all your comments. After reading them I can > conclude that: > > 1- the CSV format is not standardized; each piece of software uses it > differently Yes! And that's part of the pain of working with 'csv' files. > 2- the "C" in "CSV" does not mean "comma" for Microsoft Excel; the ";" > comes from my regional Spanish settings Yes - but not just Excel, other programs do call "CSV" files that are TAB-separated, by example. > 3- Excel does not even put quotes around litteral texts, not even when > the text contains a blank I guess you'll get quotes around text containing ';' characters > But, perhaps, there is no standard alternative to CSV !!! Of course there are! You may use SYLK, DIFF, XML, XDR... "The nice thing about standards is that there are so many to choose from." (Andrew S. Tanenbaum) But look for the xlrd package, it lets you read Excel files directly from Python. -- Gabriel Genellina From dns4 at cornell.edu Fri Aug 28 13:06:09 2009 From: dns4 at cornell.edu (David Smith) Date: Fri, 28 Aug 2009 13:06:09 -0400 Subject: Question on the "csv" library In-Reply-To: References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> Message-ID: vsoler wrote: > > Thank you very much for all your comments. After reading them I can > conclude that: > > 1- the CSV format is not standardized; each piece of software uses it > differently True, but there are commonalities. See http://en.wikipedia.org/wiki/Comma-separated_values > > 2- the "C" in "CSV" does not mean "comma" for Microsoft Excel; the ";" > comes from my regional Spanish settings The C really does stand for comma. I've never seen MS spit out semi-colon separated text on a CSV format. > > 3- Excel does not even put quotes around litteral texts, not even when > the text contains a blank There is no need to quote text literals with whitespace in them. There is a need when a newline exists or when the separator character is embedded in the field. --David From gagsl-py2 at yahoo.com.ar Fri Aug 28 13:09:52 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 28 Aug 2009 14:09:52 -0300 Subject: Raw data extraction question References: <250bf47b-6307-435a-b991-caee359c4ccf@n11g2000yqb.googlegroups.com> Message-ID: En Wed, 26 Aug 2009 12:18:23 -0300, Maggie escribi?: > i have event timing stretch of code i need to alter. here is code > below: > -------------- > # we start each run with one full silent trial > # creating a "stub" with the duration of a full block > # less the discarded acquisitions > stub = block_dur - (distax * tr) > > feed = sys.stdin.readlines() > sess = -1 > for line in feed: > if re.search(line != rest): > time = (line + line (-1)) + (distax * tr) > print time > > elif (line(-1) = rest): > # block onsets are determined by > # block number, block duration, > # and the stub; 3dDeconvolve > # takes care of making these > # "global" > time = (line) + (distax * tr) > print time > ----- When you post some piece of code, copy & paste it from the original source; don't retype. The code above don't even compile. > my concern is that it is extracting line number and not data contained > on a given line. I need it to extract data from each line (excluding > lines with spaces and/or lines that contain the word "pause" or > "silence"). Basically i need ONLY raw data extracted from line 1 - > onward. How does a line look like? Post some sample lines. -- Gabriel Genellina From breamoreboy at yahoo.co.uk Fri Aug 28 13:14:36 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Aug 2009 18:14:36 +0100 Subject: Question on the "csv" library In-Reply-To: References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> Message-ID: vsoler wrote: > On Aug 28, 5:43 pm, Steven Rumbalski > wrote: >> On Aug 27, 3:06 pm, vsoler wrote: >> >> >> >>> I am trying to read a csv file generated by excel. >>> Although I succeed in reading the file, the format that I get is not >>> suitable for me. >>> I've done: >>>>>> import csv >>>>>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) >>>>>> print spamReader >>> <_csv.reader object at 0x01022E70> >>>>>> for row in spamReader: >>> print row >>> ['codigo;nombre;cantidad'] >>> ['a;qwe;1'] >>> ['b;asd;2'] >>> ['c;zxc;3'] >>> My questions are: >>> 1- Why using "print spamReader" I cannot see the data? >>> I expected to see a list of lists, a kind of a matrix, but I get >>> nothing >>> 2- Why are the rows in a single string? >>> I expected a list of fields that, when text, would be delimited by >>> " >>> To tell the truth, the file generated by excel does not contain the >>> strings delimited by ". Isn't it weird? >>> 3- Is there anything I can do to have my data in a list of lists >>> structure? would another kind of data suit better my needs? >>> Thank you for your help >>> Vicente Soler >> the csv module can handle any delimiter. >> >> change this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r')) >> to this >>> spamReader = csv.reader(open('C:\\abc.csv', 'r'), >> delimiter=';') >> >> hope this helps, >> Steven Rumbalski > > Thank you very much for all your comments. After reading them I can > conclude that: > > 1- the CSV format is not standardized; each piece of software uses it > differently > > 2- the "C" in "CSV" does not mean "comma" for Microsoft Excel; the ";" > comes from my regional Spanish settings > > 3- Excel does not even put quotes around litteral texts, not even when > the text contains a blank > > But, perhaps, there is no standard alternative to CSV !!! This depends on the use case of yourself or your users. If you could give more detail on what you are trying to achieve then I'm sure that more help will be forthcoming. For example, could the file be saved in Excel 97-2003 xls format and then processed with the excellent xlrd/xlwt/xlutils? They are available here:- http://pypi.python.org/pypi/xlutils/1.4.0 -- Kindest regards. Mark Lawrence. From hniksic at xemacs.org Fri Aug 28 13:19:44 2009 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 28 Aug 2009 19:19:44 +0200 Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> Message-ID: <87ocpzdff3.fsf@busola.homelinux.net> David Smith writes: >> 2- the "C" in "CSV" does not mean "comma" for Microsoft Excel; the ";" >> comes from my regional Spanish settings > > The C really does stand for comma. I've never seen MS spit out > semi-colon separated text on a CSV format. That's because you're running MS Office in a US language environment. In almost all of Europe MS products use comma as the decimal separator, and semicolon for CSV field separation. From no.email at please.post Fri Aug 28 13:23:37 2009 From: no.email at please.post (kj) Date: Fri, 28 Aug 2009 17:23:37 +0000 (UTC) Subject: Need help with Python scoping rules References: Message-ID: In Ethan Furman writes: >kj wrote: >> Miles Kaufmann writes: >>>...because the suite >>>namespace and the class namespace would get out of sync when different >>>objects were assigned to the class namespace: >> >> >>>class C: >>> x = 1 >>> def foo(self): >>> print x >>> print self.x >> >> >>>>>>o = C() >>>>>>o.foo() >>> >>>1 >>>1 >>> >>>>>>o.x = 2 >>>>>>o.foo() >>> >>>1 >>>2 >> >> >> But this unfortunate situation is already possible, because one >> can already define >> >> class C: >> x = 1 >> def foo(self): >> print C.x >> print self.x >> >> which would lead to exactly the same thing. >> >This is not the same thing, and definitely not exactly the same thing. Thanks for the clarification! kynn From rt8396 at gmail.com Fri Aug 28 13:27:15 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 10:27:15 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> Message-ID: <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> On Aug 28, 11:12?am, Mark Roseman wrote: > Would it be useful to link to this from the main Python Tkinter > documentation? > > Mark Thanks Mark, but i would hate to see more links to TCL code in the python docs. Whats the use of Tkinter if the docs are in TCL. Just learn TCL and skip the Python middleman. But i don;t want to code in TCL (*puke*) i much prefer Python even if i am calling wrapped TCL. Not to mention this link is not a complete coverage of all the widgets anyway. We desperately need a complete reference for tkinter written with only Python code that covers all widgets, all widget options, and all widget methods. And this would be a minimal effort if someone would just do it. Most of the information is already out there in various locations around the net. We just need to compile, compress, and edit it into one short and to the point reference material. I will happily volunteer to create on my own or contribute to the docs if i can get a guarantee from the tkinter maintainer that my work would not be in vain. From nagle at animats.com Fri Aug 28 13:30:09 2009 From: nagle at animats.com (John Nagle) Date: Fri, 28 Aug 2009 10:30:09 -0700 Subject: Python on the Web In-Reply-To: <4a97c215$0$16809$426a74cc@news.free.fr> References: <4a94ef42$0$27774$426a74cc@news.free.fr> <4a96884b$0$22855$426a74cc@news.free.fr> <1b7a2f45-dd10-4722-a9d8-8c6d2464e4d6@e27g2000yqm.googlegroups.com> <4a97c215$0$16809$426a74cc@news.free.fr> Message-ID: <4a9812d9$0$1617$742ec2ed@news.sonic.net> Bruno Desthuilliers wrote: > If you're only writing your framework for learning purposes, you could > as well go with Python 3, and implement everything from the ground up > (not a trivial task FWIW). Python 3 isn't ready for prime time on web servers. Too many major modules, haven't been ported yet. Twisted and Django are now available up to Python 2.6; MySQLdb is available only up to Python 2.5. So the basics for web work aren't ready yet. Python 2.5 is more or less the "stable" version of Python for production use at the moment. 2.6 is a transition version to 3.0. John Nagle From breamoreboy at yahoo.co.uk Fri Aug 28 13:44:22 2009 From: breamoreboy at yahoo.co.uk (Mark Lawrence) Date: Fri, 28 Aug 2009 18:44:22 +0100 Subject: An assessment of Tkinter and IDLE In-Reply-To: <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> Message-ID: r wrote: > On Aug 28, 11:12 am, Mark Roseman wrote: >> Would it be useful to link to this from the main Python Tkinter >> documentation? >> >> Mark > > Thanks Mark, but i would hate to see more links to TCL code in the > python docs. Whats the use of Tkinter if the docs are in TCL. Just > learn TCL and skip the Python middleman. But i don;t want to code in > TCL (*puke*) i much prefer Python even if i am calling wrapped TCL. > Not to mention this link is not a complete coverage of all the widgets > anyway. > > We desperately need a complete reference for tkinter written with only > Python code that covers all widgets, all widget options, and all > widget methods. And this would be a minimal effort if someone would > just do it. Most of the information is already out there in various > locations around the net. We just need to compile, compress, and edit > it into one short and to the point reference material. > > I will happily volunteer to create on my own or contribute to the docs > if i can get a guarantee from the tkinter maintainer that my work > would not be in vain. Please go ahead and try it. Having read the "Summary of Python tracker Issues" on the python-dev mailing list, and followed from there to the bug tracker, it seems that all input is greatly appreciated. For the small issues the reply is often "Thanks, done". Some things get rejected, and usually rightly so from what I can see. Others the issue is closed with the half way house committed/rejected. Work that out for yourself if you can.:) -- Kindest regards. Mark Lawrence. From warpcat at sbcglobal.net Fri Aug 28 14:13:06 2009 From: warpcat at sbcglobal.net (AK Eric) Date: Fri, 28 Aug 2009 11:13:06 -0700 (PDT) Subject: Query screen resolution? Message-ID: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> Thought this would be easy, maybe I'm missing something :) Trying to query the x,y resolution of my screen. I've seen this available through http://python.net/crew/mhammond/win32/ : from win32api import GetSystemMetrics print "width =", GetSystemMetrics (0) print "height =",GetSystemMetrics (1) But I was hoping for something built-in, and something non-OS specific. Is that available? Would be nice to detect for multiple monitors as well, but I'm probably asking too much :) Thanks! From szport at gmail.com Fri Aug 28 14:25:55 2009 From: szport at gmail.com (zaur) Date: Fri, 28 Aug 2009 11:25:55 -0700 (PDT) Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> Message-ID: <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> On 28 ???, 16:07, Bruno Desthuilliers wrote: > zaur a ?crit : > > > > > On 26 ???, 17:13, "Diez B. Roggisch" wrote: > >> Whom am we to judge? Sure if you propose this, you have some usecases in > >> mind - how about you present these > > > Ok. Here is a use case: object initialization. > > > For example, > > > person = Person(): > > ? name = "john" > > ? age = 30 > > ? address = Address(): > > ? ? ?street = "Green Street" > > ? ? ?no = 12 > > > vs. > > > person = Person() > > person.name = "john" > > person.age = 30 > > address = person.address = Address() > > address.street = "Green Street" > > address.no = 12 > > Err... Looks like you really should read the FineManual(tm) - > specifically, the parts on the __init__ method. > > class Person(object): > ? ? def __init__(self, name, age, address): > ? ? ? ? self.name = name > ? ? ? ? self.age = age > ? ? ? ? self.address = address > > class Address(object): > ? ? def __init__(self, street, no): > ? ? ? ? self.no = no > ? ? ? ? self.street = street > > person = Person( > ? ? name="john", > ? ? age=30, > ? ? address = Address( > ? ? ? ? street="Green Street", > ? ? ? ? no=12 > ? ? ) > ) What are you doing if 1) classes Person and Address imported from foreign module 2) __init__ method is not defined as you want? From rami.chowdhury at gmail.com Fri Aug 28 14:27:15 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Fri, 28 Aug 2009 11:27:15 -0700 Subject: Query screen resolution? In-Reply-To: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> References: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> Message-ID: > But I was hoping for something built-in, and something non-OS > specific. I don't know about built-ins, but I do believe that pygame (which *is* cross-platform) will let you get at that information: http://www.pygame.org/docs/ref/display.html#pygame.display.Info On Fri, 28 Aug 2009 11:13:06 -0700, AK Eric wrote: > Thought this would be easy, maybe I'm missing something :) Trying to > query the x,y resolution of my screen. I've seen this available > through http://python.net/crew/mhammond/win32/ : > > from win32api import GetSystemMetrics > print "width =", GetSystemMetrics (0) > print "height =",GetSystemMetrics (1) > > But I was hoping for something built-in, and something non-OS > specific. Is that available? Would be nice to detect for multiple > monitors as well, but I'm probably asking too much :) > > Thanks! -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From gert.cuykens at gmail.com Fri Aug 28 14:31:31 2009 From: gert.cuykens at gmail.com (gert) Date: Fri, 28 Aug 2009 11:31:31 -0700 (PDT) Subject: how to edit .wsgi file extebtions with IDLE on windows Message-ID: I can't figure out how to enable the .py shell and syntax highlighting for .wsgi file extensions using IDLE for windows ? From davea at ieee.org Fri Aug 28 14:35:35 2009 From: davea at ieee.org (Dave Angel) Date: Fri, 28 Aug 2009 14:35:35 -0400 Subject: Select column from a list In-Reply-To: <25185508.post@talk.nabble.com> References: <25185508.post@talk.nabble.com> Message-ID: <4A982377.7020402@ieee.org> hoffik wrote: > Hello, > > I'm quite new in Python and I have one question. I have a 2D matrix of > values stored in list (3 columns, many rows). I wonder if I can select one > column without having to go through the list with 'for' command. > > For example I have list called 'values'. > When I write 'values[0]' or 'values[0][:]' I'll get the first row. > But when I write 'values[:][0]' I won't get the first column, but the first > row again! I can't see why. > > Thanks > Hoffik > Python doesn't have 2d matrices as a native type. Others have already suggested Numpy. But I'll assume you really want to stick with what's included in base Python, because you're still learning. (Aren't we all?) The real question to me is how this data is related to each other. If it's uniform data, organized in a 3x20 rectangle, or whatever, then maybe you want to use a single list, and just use slicing to extract particular rows and columns. You were actually using slicing in your example above; that's what the colon does. But in your case, you used defaults for the 3 arguments, so you got a *copy* of the entire list. Slicing to get one row would be simply values[row*3:(row+1)*3], and one column would be print values[column: -1: 3] Notice that I hardcoded the width of our "matrix," since list doesn't know anything about it. And notice it's easy to add more rows, but not easy to change row size, because that's not part of the structure, but part of the code to access it. Next possibility is to make a class to describe the data structure. You can make methods that mimic the behavior you want. But I suspect that the row is 3 specific values, maybe not even the same type as each other. So they might be name, address, and phone number. Each row represents a family, and each column represents a type of data. In this case, I'd suggest making each row an instance of a new class you define, and making a list of those objects. Now, you might be representing a row by an object of your class. And representing a column by two things: your list & an accessor method that knows how to extract that particular field. DaveA From matthew.bellis at gmail.com Fri Aug 28 14:36:51 2009 From: matthew.bellis at gmail.com (Matt Bellis) Date: Fri, 28 Aug 2009 11:36:51 -0700 (PDT) Subject: How to exclude "import"s from PyDoc References: <7flt66F2lho6lU1@mid.uni-berlin.de> Message-ID: <613fc599-609a-4df3-b46b-8bba6297da55@i8g2000pro.googlegroups.com> Hi Diez, Thanks for the heads up. I'll give epydoc a shot. Matt > > > ? ?Anyone know the best way to getPyDocto ignore this (or other) > > imported module(s)? > > Don't know aboutpydoc, but epydoc (which generates much nicer docs > imho) can be forced to only include certain packages. > > Diez From xiaosongxia at yahoo.com Fri Aug 28 14:38:30 2009 From: xiaosongxia at yahoo.com (xiaosong xia) Date: Fri, 28 Aug 2009 11:38:30 -0700 (PDT) Subject: copy construtor question Message-ID: <613204.64791.qm@web53105.mail.re2.yahoo.com> Hi all, ? I am trying to define a class with copy constructor as following: ? class test: ???? def __init__(self, s=None): ????????? self=s ? x=[1,2] ? y=test(x) ? print y.__dict__ ? it gives {} ? The above code doesn't work. ? Questions are: ? 1. Can 'self ' be a class attribute? 2. How to make a copy constructor? ? Thanks for any help. ? Eric -------------- next part -------------- An HTML attachment was scrubbed... URL: From warpcat at sbcglobal.net Fri Aug 28 14:49:16 2009 From: warpcat at sbcglobal.net (Warpcat) Date: Fri, 28 Aug 2009 11:49:16 -0700 (PDT) Subject: Query screen resolution? References: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> Message-ID: <04a85dc7-d1e7-4566-9ee9-fa9090b45543@v15g2000prn.googlegroups.com> On Aug 28, 11:27?am, "Rami Chowdhury" wrote: > > But I was hoping for something built-in, and something non-OS > > specific. > > I don't know about built-ins, but I do believe that pygame (which *is* ? > cross-platform) will let you get at that information: > ? ? ? ?http://www.pygame.org/docs/ref/display.html#pygame.display.Info Actually, I just came up with another hack using PyGame as well like so: screen = pygame.display.set_mode((0,0)) WIDTH, HEIGHT = screen.get_size() If you pass zero values into the resolution, it will pop to the current screen resolution. And since I'm making a PyGame app, this actually works out ok. However, querying the current_w & current_h attrs from the Info object is a lot cleaner (I was unaware of that, thanks!) But I'd sure like to know if there is built-in way. From somebody at somewhere.com Fri Aug 28 14:57:28 2009 From: somebody at somewhere.com (Stephen Fairchild) Date: Fri, 28 Aug 2009 19:57:28 +0100 Subject: Select column from a list References: Message-ID: hoffik wrote: > > Hello, > > I'm quite new in Python and I have one question. I have a 2D matrix of > values stored in list (3 columns, many rows). I wonder if I can select one > column without having to go through the list with 'for' command. > > For example I have list called 'values'. > When I write 'values[0]' or 'values[0][:]' I'll get the first row. > But when I write 'values[:][0]' I won't get the first column, but the > first row again! I can't see why. rows = [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] cols = zip(*rows) To just get the second column: zip(*rows)[1] -- Stephen Fairchild From vicente.soler at gmail.com Fri Aug 28 14:58:48 2009 From: vicente.soler at gmail.com (vsoler) Date: Fri, 28 Aug 2009 11:58:48 -0700 (PDT) Subject: Colors on IDLE Message-ID: Everything that I see in IDLE is in black. I have tried to add colors, without success. I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic From vicente.soler at gmail.com Fri Aug 28 15:00:21 2009 From: vicente.soler at gmail.com (vsoler) Date: Fri, 28 Aug 2009 12:00:21 -0700 (PDT) Subject: Colors on IDLE References: Message-ID: On Aug 28, 8:58?pm, vsoler wrote: > Everything that I see in IDLE is in black. > > I have tried to add colors, without success. > > I've tried: ?/Options/Configure IDLE/Highlighting/IDLE Classic Couldn't finish writing... sorry ----------------------------------- Everything that I see in IDLE is in black. I have tried to add colors, without success. I've tried: /Options/Configure IDLE/Highlighting/IDLE Classic However, everything remains black. Any help is highly appreciated Vicente Soler From pfeldman at verizon.net Fri Aug 28 15:00:31 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Fri, 28 Aug 2009 12:00:31 -0700 (PDT) Subject: comparison on list yields surprising result Message-ID: <25195170.post@talk.nabble.com> In [21]: x Out[21]: [1, 2, 3, 5] In [22]: x>6 Out[22]: True Is this a bug? -- View this message in context: http://www.nabble.com/comparison-on-list-yields-surprising-result-tp25195170p25195170.html Sent from the Python - python-list mailing list archive at Nabble.com. From sjmachin at lexicon.net Fri Aug 28 15:00:36 2009 From: sjmachin at lexicon.net (John Machin) Date: Fri, 28 Aug 2009 12:00:36 -0700 (PDT) Subject: Question on the "csv" library References: <055885e5-b2ee-4ca7-84d9-238034b8f21d@c2g2000yqi.googlegroups.com> <183eb772-dda3-45be-82e3-9160091e066b@v2g2000vbb.googlegroups.com> Message-ID: On Aug 29, 2:35?am, vsoler wrote: > 3- Excel does not even put quotes around litteral texts, not even when > the text contains a blank Correct. Quoting is necessary only if a text field contains a delimiter (semicolon/comma), a newline, or the quote character. You can read Excel CSV output using the Python csv module by specifying delimiter=";" If you need to feed a CSV file to some software that demands that text fields be quoted unconditionally, you have at least two options: (1) If you know which fields should be text fields, you can read the Excel-output file with Python csv, convert your non-text fields to float, and write it back out with quoting=csv.QUOTE_NONNUMERIC. (2) If you want precise control (and thus precise knowledge), use xlrd (http://pypi.python.org/pypi/xlrd) to read Excel 97-2003 .xls files -- it will tell you cell by cell (NOT column by column (the user has control of the type at the cell level)) whether the cell contains text (reported as a unicode object), a number (float), a Boolean (int, 1 or 0), a date (float, days since ? (read the docs)), or an error code e.g. #DIV/0! (int, read the docs) ... then you can write it out however you like. HTH, John From sjmachin at lexicon.net Fri Aug 28 15:16:59 2009 From: sjmachin at lexicon.net (John Machin) Date: Fri, 28 Aug 2009 12:16:59 -0700 (PDT) Subject: comparison on list yields surprising result References: Message-ID: On Aug 29, 5:00?am, "Dr. Phillip M. Feldman" wrote: > In [21]: x > Out[21]: [1, 2, 3, 5] > > In [22]: x>6 > Out[22]: True > > Is this a bug? No. http://docs.python.org/reference/expressions.html#notin From deets at nospam.web.de Fri Aug 28 15:19:43 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Aug 2009 21:19:43 +0200 Subject: comparison on list yields surprising result In-Reply-To: References: Message-ID: <4A982DCF.2060201@nospam.web.de> Dr. Phillip M. Feldman schrieb: > In [21]: x > Out[21]: [1, 2, 3, 5] > > In [22]: x>6 > Out[22]: True > > Is this a bug? In python2.x, it's the defined behavior - all types are somhow comparable. The comparison is stable (all lists compare larger to all ints), but of course this by no means well-defined. This debatable design-decision has been remedied in Python3: Python 3.1 (r31:73578, Jun 27 2009, 21:49:46) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> list(range(10)) < 10 Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: list() < int() >>> Diez From deets at nospam.web.de Fri Aug 28 15:19:58 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 28 Aug 2009 21:19:58 +0200 Subject: comparison on list yields surprising result In-Reply-To: References: Message-ID: <7fqouuF2mlupvU2@mid.uni-berlin.de> Dr. Phillip M. Feldman schrieb: > In [21]: x > Out[21]: [1, 2, 3, 5] > > In [22]: x>6 > Out[22]: True > > Is this a bug? In python2.x, it's the defined behavior - all types are somhow comparable. The comparison is stable (all lists compare larger to all ints), but of course this by no means well-defined. This debatable design-decision has been remedied in Python3: Python 3.1 (r31:73578, Jun 27 2009, 21:49:46) [GCC 4.0.1 (Apple Inc. build 5493)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> list(range(10)) < 10 Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: list() < int() >>> Diez From motoom at xs4all.nl Fri Aug 28 15:23:12 2009 From: motoom at xs4all.nl (Michiel Overtoom) Date: Fri, 28 Aug 2009 21:23:12 +0200 Subject: An assessment of Tkinter and IDLE In-Reply-To: <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> Message-ID: <4A982EA0.10808@xs4all.nl> r wrote: > Whats the use of Tkinter if the docs are in TCL. Just > learn TCL and skip the Python middleman. But Mark's tutorial at http://www.tkdocs.com/tutorial/index.html allows you to select 'Python' as one of the languages you want to see the example code in. Too bad that the 'ttk' widgets are not mainstream yet. Greetings, -- "The ability of the OSS process to collect and harness the collective IQ of thousands of individuals across the Internet is simply amazing." - Vinod Valloppillil http://www.catb.org/~esr/halloween/halloween4.html From gert.cuykens at gmail.com Fri Aug 28 15:24:25 2009 From: gert.cuykens at gmail.com (gert) Date: Fri, 28 Aug 2009 12:24:25 -0700 (PDT) Subject: how to send 100 continues in wsgi application ? Message-ID: how do you send 100 continues in a wsgi applications ? when using curl -T file http://localhost/upload.wsgi on the wsgiref.simple_server it get stuck waiting for a 100 continue import os def application(environ, response): query=os.path.join(os.path.dirname(__file__),'teeeeeeeeeemp') range=environ.get('HTTP_CONTENT_RANGE','bytes 0-').replace('bytes ','').split('/')[0].split(',') offset=[] for r in range: offset.append(r.split('-')) with open(query,'ab+') as f: if environ['REQUEST_METHOD']=='PUT': f.seek(int(offset[0][0])) f.truncate() while True: chunk=environ['wsgi.input'].read(8192) if not chunk: break f.write(chunk) f.flush() l=str(os.fstat(f.fileno()).st_size) response('200 OK', [('Content-Type', 'text/plain'), ('Content- Length', str(len(l)))]) return [l] From aahz at pythoncraft.com Fri Aug 28 15:29:09 2009 From: aahz at pythoncraft.com (Aahz) Date: 28 Aug 2009 12:29:09 -0700 Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: In article <21e57363-4e92-41cb-9907-5aef96ad0a6e at o15g2000yqm.googlegroups.com>, RunThePun wrote: > >Anybody have any more ideas? I think python should/could havev a >syntax for overriding this behaviour, i mean, obviously the complexity >of supporting all operators with the getitem syntax could introduce >alot of clutter. But maybe there's an elegant solution out there... Any solution you create must support this: >>> L = [3] >>> L[0] += 7 >>> L [10] -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From pfeldman at verizon.net Fri Aug 28 15:47:13 2009 From: pfeldman at verizon.net (Dr. Phillip M. Feldman) Date: Fri, 28 Aug 2009 12:47:13 -0700 (PDT) Subject: comparison on list yields surprising result In-Reply-To: <4A982DCF.2060201@nospam.web.de> References: <25195170.post@talk.nabble.com> <4A982DCF.2060201@nospam.web.de> Message-ID: <25195893.post@talk.nabble.com> It looks as though what I should have done is the following: In [23]: array(x) > 6 Out[23]: array([False, False, False, False], dtype=bool) -- View this message in context: http://www.nabble.com/comparison-on-list-yields-surprising-result-tp25195170p25195893.html Sent from the Python - python-list mailing list archive at Nabble.com. From clp2 at rebertia.com Fri Aug 28 15:55:11 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 28 Aug 2009 12:55:11 -0700 Subject: Colors on IDLE In-Reply-To: References: Message-ID: <50697b2c0908281255n1f17d4c9l335c39a3acd5c7c4@mail.gmail.com> On Fri, Aug 28, 2009 at 12:00 PM, vsoler wrote: > On Aug 28, 8:58?pm, vsoler wrote: >> Everything that I see in IDLE is in black. >> >> I have tried to add colors, without success. >> >> I've tried: ?/Options/Configure IDLE/Highlighting/IDLE Classic > > Couldn't finish writing... ? sorry > ----------------------------------- > > Everything that I see in IDLE is in black. > > I have tried to add colors, without success. > > I've tried: ?/Options/Configure IDLE/Highlighting/IDLE Classic > > However, everything remains black. Any help is highly appreciated What OS are you on? - Chris From pavlovevidence at gmail.com Fri Aug 28 16:03:40 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 28 Aug 2009 13:03:40 -0700 (PDT) Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: On Aug 26, 11:49?pm, RunThePun wrote: > Anybody have any more ideas? I think python should/could havev a > syntax for overriding this behaviour, i mean, obviously the complexity > of supporting all operators with the getitem syntax could introduce > alot of clutter. But maybe there's an elegant solution out there... I don't think it needs a syntax for that, but I'm not so sure a method to modify a value in place with a single key lookup wouldn't occasioanally be useful. For instance: def increment(value): return value+1 d = { 'a': 1 } d.apply_to_value('a',increment) print d and d['a'] would be 2. The difference is that only one lookup occurs. (The dictionary would be locked to modifications while the callback function is called, same as if it were being iterated over.) Thing is, there's no way to get that ability except subclass dict in C; can't be done from Python. Which is why even though it'd be a pretty rare need it at least deserves a bit of consideration before being tabled. As a workaround, if lookups are expensive, you can add an indirection to the dict. For example, you could let each value in the dict be a singleton list which is permanently bound to the key. Then you only have look up the key once to modify the value. d = { 'a': [1] } ston = d['a'] ston[0] += 3 and now d['a'][0] is 4, and there was only one dict lookup. Downside is that you have the [0] to carry around, but that is the price of indirection. A wrapper class might help. Carl Banks From mwilson at the-wire.com Fri Aug 28 16:38:55 2009 From: mwilson at the-wire.com (Mel) Date: Fri, 28 Aug 2009 16:38:55 -0400 Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> Message-ID: zaur wrote: > On 28 ???, 16:07, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> zaur a ?crit : >> >> >> >> > On 26 ???, 17:13, "Diez B. Roggisch" wrote: >> >> Whom am we to judge? Sure if you propose this, you have some usecases >> >> in mind - how about you present these >> >> > Ok. Here is a use case: object initialization. >> >> > For example, >> >> > person = Person(): >> > name = "john" >> > age = 30 >> > address = Address(): >> > street = "Green Street" >> > no = 12 >> >> > vs. >> >> > person = Person() >> > person.name = "john" >> > person.age = 30 >> > address = person.address = Address() >> > address.street = "Green Street" >> > address.no = 12 >> >> Err... Looks like you really should read the FineManual(tm) - >> specifically, the parts on the __init__ method. >> >> class Person(object): >> def __init__(self, name, age, address): >> self.name = name >> self.age = age >> self.address = address >> >> class Address(object): >> def __init__(self, street, no): >> self.no = no >> self.street = street >> >> person = Person( >> name="john", >> age=30, >> address = Address( >> street="Green Street", >> no=12 >> ) >> ) > > What are you doing if 1) classes Person and Address imported from > foreign module 2) __init__ method is not defined as you want? My work-around would be: p = person = Person() p.name = "john" p.age = age # assuming, for a moment, that the age I wanted to set # happened to be in another variable a = p.address = Address() a.street = "Green Street" a.no = 12 del a, p # optional, for a tidier namespace Slightly verbose, but, saying what it means, it avoids having to guess which age of several ages might have to be used in various places; the same would go for other input variables. Actually, I probably wouldn't use p as a stand-in for person unless person were a global name and p could be local. Mel. From charles at declareSub.com Fri Aug 28 16:40:54 2009 From: charles at declareSub.com (Charles Yeomans) Date: Fri, 28 Aug 2009 16:40:54 -0400 Subject: why python got less developers ? In-Reply-To: References: <71fc40ff-cf0e-4b15-b60c-dd42deaac49d@r27g2000vbn.googlegroups.com> Message-ID: On Aug 28, 2009, at 1:03 AM, Esam Qanadeely wrote: > who cares if a language is compiled or interpreted as long as it runs > and perform the function. > > second thing is : even if java is faster than python , unless you are > making performance critical operations : who cares? computers are > getting faster all the time and languages like python or ruby are fast > enough. > > any comment ? Many developers suffer from performance anxiety. Charles Yeomans From ken at seehart.com Fri Aug 28 16:59:57 2009 From: ken at seehart.com (Ken Seehart) Date: Fri, 28 Aug 2009 13:59:57 -0700 Subject: cgi and POST Message-ID: <4A98454D.6050006@seehart.com> I can't seem to find an answer to this simple question on the web, and the documentation doesn't seem to indicate how to do this... On the client I have: urllib.urlopen(uri, data) This does a POST, but it's not obvious to me how this maps onto the various cgi examples which assume that the POST operation came from an html form with a file field. In my case, there is no html form, and there is no file field, so please do not refer me to a page that just gives examples where the data is coming from a file transfer form. I have already visited those pages. My question is this: Using cgi, how do I get the /data /(not the uri arguments) originating from a POST that did not originate from a form. Thanks. From vicente.soler at gmail.com Fri Aug 28 17:34:07 2009 From: vicente.soler at gmail.com (vsoler) Date: Fri, 28 Aug 2009 14:34:07 -0700 (PDT) Subject: Colors on IDLE References: Message-ID: <59922ab5-f8c9-429f-b1ea-9b1418aa6b71@t13g2000yqt.googlegroups.com> On Aug 28, 9:55?pm, Chris Rebert wrote: > On Fri, Aug 28, 2009 at 12:00 PM, vsoler wrote: > > On Aug 28, 8:58?pm, vsoler wrote: > >> Everything that I see in IDLE is in black. > > >> I have tried to add colors, without success. > > >> I've tried: ?/Options/Configure IDLE/Highlighting/IDLE Classic > > > Couldn't finish writing... ? sorry > > ----------------------------------- > > > Everything that I see in IDLE is in black. > > > I have tried to add colors, without success. > > > I've tried: ?/Options/Configure IDLE/Highlighting/IDLE Classic > > > However, everything remains black. Any help is highly appreciated > > What OS are you on? > > - Chris Windows XP From tjreedy at udel.edu Fri Aug 28 17:42:04 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 28 Aug 2009 17:42:04 -0400 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: Carl Banks wrote: > I don't think it needs a syntax for that, but I'm not so sure a method > to modify a value in place with a single key lookup wouldn't > occasioanally be useful. Augmented assignment does that. > > For instance: > > def increment(value): > return value+1 > d = { 'a': 1 } > d.apply_to_value('a',increment) > print d > > and d['a'] would be 2. The difference is that only one lookup > occurs. Like this? >>> d={'a': 2} >>> d['a'] += 2 >>> d['a'] 4 This does not cover all replacements, but certainly the most common. [snip] > As a workaround, if lookups are expensive, But they are not. Because (C)Python is heavily based on dict name lookup for builtins and global names and attributes, as well as overt dict lookup, must effort has gone into optimizing dict lookup. > you can add something even slower ;-). In particular, a method lookup + method call, as you suggest above. One can always avoid calculating the key object twice if that is expensive. Terry Jan Reedy From darcy at druid.net Fri Aug 28 17:48:57 2009 From: darcy at druid.net (D'Arcy J.M. Cain) Date: Fri, 28 Aug 2009 17:48:57 -0400 Subject: cgi and POST In-Reply-To: <4A98454D.6050006@seehart.com> References: <4A98454D.6050006@seehart.com> Message-ID: <20090828174857.843a4da2.darcy@druid.net> On Fri, 28 Aug 2009 13:59:57 -0700 Ken Seehart wrote: > Using cgi, how do I get the /data /(not the uri arguments) originating > from a POST that did not originate from a form. You don't care where it came from. Just treat it exactly as if it came from a form. -- D'Arcy J.M. Cain | Democracy is three wolves http://www.druid.net/darcy/ | and a sheep voting on +1 416 425 1212 (DoD#0082) (eNTP) | what's for dinner. From saimapk81 at gmail.com Fri Aug 28 17:49:58 2009 From: saimapk81 at gmail.com (saima81) Date: Fri, 28 Aug 2009 14:49:58 -0700 (PDT) Subject: "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options Message-ID: <83e09538-4098-4f19-8164-f3a4c4702e32@u20g2000prg.googlegroups.com> "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options "BOLLYWOOD GIRLS" ON www.e-indiangirls.blogspot.com "BOLLYWOOD ROMANTIC SCENES" www.e-indiangirls.blogspot.com "BOLLYWOOD WALLPAPERS" www.e-indiangirls.blogspot.com "BOLLYWOOD PICTURES" www.e-indiangirls.blogspot.com "BOLLYWOOD SCENES" Options From robert.kern at gmail.com Fri Aug 28 18:13:19 2009 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 28 Aug 2009 17:13:19 -0500 Subject: Overriding iadd for dictionary like objects In-Reply-To: References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: On 2009-08-28 16:42 PM, Terry Reedy wrote: > Carl Banks wrote: > >> I don't think it needs a syntax for that, but I'm not so sure a method >> to modify a value in place with a single key lookup wouldn't >> occasioanally be useful. > > Augmented assignment does that. No, it uses one __getitem__ and one __setitem__ thus two key lookups. >> For instance: >> >> def increment(value): >> return value+1 >> d = { 'a': 1 } >> d.apply_to_value('a',increment) >> print d >> >> and d['a'] would be 2. The difference is that only one lookup >> occurs. > > Like this? > >>> d={'a': 2} > >>> d['a'] += 2 > >>> d['a'] > 4 > > This does not cover all replacements, but certainly the most common. Take look farther up in the thread for the actual point at issue. The OP knows that augmented assignment works for the common cases. He wants to override the behavior on the container to handle some uncommon cases, and this is not possible because Python breaks up the operation into three orthogonal actions. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From hkh00001 at gmail.com Fri Aug 28 18:19:35 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 15:19:35 -0700 (PDT) Subject: IDE for python similar to visual basic Message-ID: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> i have been searching for am IDE for python that is similar to Visual Basic but had no luck.shall you help me please? From fasteliteprogrammer at yahoo.com Fri Aug 28 18:22:47 2009 From: fasteliteprogrammer at yahoo.com (Craig) Date: Fri, 28 Aug 2009 15:22:47 -0700 (PDT) Subject: IDE for python similar to visual basic In-Reply-To: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> Message-ID: <504063.99893.qm@web36502.mail.mud.yahoo.com> Try wingware i have it and i like it. --- On Fri, 8/28/09, qwe rty wrote: > From: qwe rty > Subject: IDE for python similar to visual basic > To: python-list at python.org > Date: Friday, August 28, 2009, 5:19 PM > i have been searching for am IDE for > python that is similar to Visual > Basic but had no luck.shall you help me please? > -- > http://mail.python.org/mailman/listinfo/python-list > From josefg at gmail.com Fri Aug 28 18:25:13 2009 From: josefg at gmail.com (josef) Date: Fri, 28 Aug 2009 15:25:13 -0700 (PDT) Subject: Object Reference question References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <9feee13c-117e-4806-b238-e4152a68adfb@18g2000yqa.googlegroups.com> Message-ID: On Aug 27, 1:35?pm, Ethan Furman wrote: > josef wrote: > > Thanks to everyone who responded. > > > I will be going with some sort of a = MyClass(name = 'a') format. It's > > the Python way. > > > For me, it was very hard to accept that EVERYTHING is an object > > reference. And that there are no object reference names, just string > > entries in dictionaries. But I think it all makes sense now. > > > Thanks again, > > > Josef > > My apologies if I missed it, but what *exactly* are you planning on > doing with your 'name' attribute? ?From the posts I've seen so far, I > think you are only setting yourself up for failure. > > ~Ethan~ I'm going to use it for printing purposes. dk = MyClass(name='dk') When I need a name dk.name. There will only ever be one dk defined. Does that read like I'm setting myself up for failure? From hkh00001 at gmail.com Fri Aug 28 18:37:46 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 15:37:46 -0700 (PDT) Subject: What python can NOT do? Message-ID: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> i know that an interpreted language like python can't be used to make an operating system or system drivers. what else can NOT be done in python? what are the limitations of the language? From thudfoo at opensuse.us Fri Aug 28 18:39:28 2009 From: thudfoo at opensuse.us (member thudfoo) Date: Fri, 28 Aug 2009 15:39:28 -0700 Subject: [Tutor] Sending an email alert In-Reply-To: <000001ca2811$cb320b10$61962130$@org> References: <000001ca2811$cb320b10$61962130$@org> Message-ID: <3d881a310908281539k42b92449p804575eac3cd6e7@mail.gmail.com> On Fri, Aug 28, 2009 at 12:00 PM, Marc wrote: [...] > ??? s = smtplib.SMTP('smtp.marcd.org') > > AttributeError: 'module' object has no attribute 'SMTP' > > > > The code I am trying to use is: > > > > import smtplib > [...] Make sure you do not have a file called "smtplib.py" on the your python path: put this statement after "import smtplib": print smtplib.__file__ in order to find out what "smtplib" is being imported. HTH > _______________________________________________ > Tutor maillist ?- ?Tutor at python.org > http://mail.python.org/mailman/listinfo/tutor > From hkh00001 at gmail.com Fri Aug 28 18:43:51 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 15:43:51 -0700 (PDT) Subject: IDE for python similar to visual basic References: Message-ID: On Aug 29, 1:22?am, Craig wrote: > Try wingware i have it and i like it. > > --- On Fri, 8/28/09, qwe rty wrote: > > > From: qwe rty > > Subject: IDE for python similar to visual basic > > To: python-l... at python.org > > Date: Friday, August 28, 2009, 5:19 PM > > i have been searching for am IDE for > > python that is similar to Visual > > Basic but had no luck.shall you help me please? > > -- > >http://mail.python.org/mailman/listinfo/python-list > > OMG, it has no visual designer !! From mark at markroseman.com Fri Aug 28 18:48:35 2009 From: mark at markroseman.com (Mark Roseman) Date: Fri, 28 Aug 2009 16:48:35 -0600 Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> Message-ID: r wrote: > On Aug 28, 11:12?am, Mark Roseman wrote: > > Would it be useful to link to this from the main Python Tkinter > > documentation? > > Thanks Mark, but i would hate to see more links to TCL code in the > python docs. Whats the use of Tkinter if the docs are in TCL. The www.tkdocs.com site is 'language neutral' - currently the tutorial covers Tcl, Perl, Ruby and yes Python, and allows you to switch between any of those languages (or show all of them). From abecedarian314159 at yahoo.com Fri Aug 28 18:51:10 2009 From: abecedarian314159 at yahoo.com (William) Date: Fri, 28 Aug 2009 15:51:10 -0700 (PDT) Subject: IDE for python similar to visual basic In-Reply-To: Message-ID: <846470.11833.qm@web110601.mail.gq1.yahoo.com> For visual designers, you may try: QTDesigner with PyQt or WxForms or WxGlade or BoaConstructor with WxPython It's not like VB.NET where you can put in callbacks write after doing layout, but some prefer the above designers to hand coding guis.? Good luck, William --- On Fri, 8/28/09, qwe rty wrote: From: qwe rty Subject: Re: IDE for python similar to visual basic To: python-list at python.org Date: Friday, August 28, 2009, 6:43 PM On Aug 29, 1:22?am, Craig wrote: > Try wingware i have it and i like it. > > --- On Fri, 8/28/09, qwe rty wrote: > > > From: qwe rty > > Subject: IDE for python similar to visual basic > > To: python-l... at python.org > > Date: Friday, August 28, 2009, 5:19 PM > > i have been searching for am IDE for > > python that is similar to Visual > > Basic but had no luck.shall you help me please? > > -- > >http://mail.python.org/mailman/listinfo/python-list > > OMG, it has no visual designer !! -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From stef.mientki at gmail.com Fri Aug 28 18:51:12 2009 From: stef.mientki at gmail.com (Stef Mientki) Date: Sat, 29 Aug 2009 00:51:12 +0200 Subject: IDE for python similar to visual basic In-Reply-To: References: Message-ID: <4A985F60.5060301@gmail.com> qwe rty wrote: > On Aug 29, 1:22 am, Craig wrote: > >> Try wingware i have it and i like it. >> >> --- On Fri, 8/28/09, qwe rty wrote: >> >> >>> From: qwe rty >>> Subject: IDE for python similar to visual basic >>> To: python-l... at python.org >>> Date: Friday, August 28, 2009, 5:19 PM >>> i have been searching for am IDE for >>> python that is similar to Visual >>> Basic but had no luck.shall you help me please? >>> -- >>> http://mail.python.org/mailman/listinfo/python-list >>> >> > > OMG, it has no visual designer !! > That was my first reaction too. and I was even used to a better visual designer: Delphi ;-) I'm now very happy and design faster in wxPython (with GUI-support) than in Delphi ;-) cheers, Stef From pavlovevidence at gmail.com Fri Aug 28 19:02:00 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Fri, 28 Aug 2009 16:02:00 -0700 (PDT) Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: <58e91734-d03f-417c-89b1-f2717c3a9181@l5g2000yqo.googlegroups.com> On Aug 28, 2:42?pm, Terry Reedy wrote: > Carl Banks wrote: > > I don't think it needs a syntax for that, but I'm not so sure a method > > to modify a value in place with a single key lookup wouldn't > > occasioanally be useful. > > Augmented assignment does that. Internally uses two lookups, one for getting, and one for setting. I think this is an unavoidable given Python's semantics. Look at the traceback: >>> def x(): ... d['a'] += 1 ... >>> dis.dis(x) 2 0 LOAD_GLOBAL 0 (d) 3 LOAD_CONST 1 ('a') 6 DUP_TOPX 2 9 BINARY_SUBSCR 10 LOAD_CONST 2 (1) 13 INPLACE_ADD 14 ROT_THREE 15 STORE_SUBSCR 16 LOAD_CONST 0 (None) 19 RETURN_VALUE > > As a workaround, if lookups are expensive, > > But they are not. Because (C)Python is heavily based on dict name lookup > for builtins and global names and attributes, as well as overt dict > lookup, must effort has gone into optimizing dict lookup. The actual lookup algorithm Python dicts use is well-optimized, yes, but the dict could contain keys that have expensive comparison and hash-code calculation, in which case lookup is going to be slow. Carl Banks From nyamatongwe+thunder at gmail.com Fri Aug 28 19:02:33 2009 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 28 Aug 2009 23:02:33 GMT Subject: Annoying octal notation In-Reply-To: <00216447$0$2930$c3e8da3@news.astraweb.com> References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> <00216447$0$2930$c3e8da3@news.astraweb.com> Message-ID: Steven D'Aprano: > Obviously I can't speak for Ken Thompson's motivation in creating this > feature, but I'm pretty sure it wasn't to save typing or space on > punchcards. The original implementation of UNIX was on a PDP-7 which was an 18-bit machine. Octal = 3 bits at a a time which evenly divides an 18-bit word whereas the 4 bits of hexadecimal do not. Early implementations of B were (according to Wikipedia) on the PDP-7, PDP-11 (a 16-bit machine) and Honeywell 36-bit mainframes. Octal was widely used on the PDP-11. DEC's PDP-11 Assembler defaulted to octal and didn't even support hexadecimal. The prefixes used in MACRO-11 for explicit radixes were ^D, ^O, and ^B. http://computer-refuge.org/bitsavers/pdf/dec/pdp11/rsx11/RSX11M_V2/DEC-11-OIMRA-A-D_MACRO_75.pdf Neil From ken at seehart.com Fri Aug 28 19:11:20 2009 From: ken at seehart.com (Ken Seehart) Date: Fri, 28 Aug 2009 16:11:20 -0700 Subject: cgi and POST In-Reply-To: <20090828174857.843a4da2.darcy@druid.net> References: <4A98454D.6050006@seehart.com> <20090828174857.843a4da2.darcy@druid.net> Message-ID: <4A986418.6000600@seehart.com> D'Arcy J.M. Cain wrote: > On Fri, 28 Aug 2009 13:59:57 -0700 > Ken Seehart wrote: > >> Using cgi, how do I get the /data /(not the uri arguments) originating >> from a POST that did not originate from a form. >> > > You don't care where it came from. Just treat it exactly as if it came > from a form. > Thanks. Anyway, the issue was that I made a mistake the urllib side of things. Problem solved. Ken From lists at cheimes.de Fri Aug 28 19:21:32 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 29 Aug 2009 01:21:32 +0200 Subject: What python can NOT do? In-Reply-To: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: qwe rty wrote: > i know that an interpreted language like python can't be used to make > an operating system or system drivers. > > what else can NOT be done in python? what are the limitations of the > language? Python is a high level language. It's not designed for low level stuff like bit operations or direct hardware access. However it can be used as a glue language for low level code written in C or ASM. Christian From rt8396 at gmail.com Fri Aug 28 19:27:27 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 16:27:27 -0700 (PDT) Subject: Colors on IDLE References: <59922ab5-f8c9-429f-b1ea-9b1418aa6b71@t13g2000yqt.googlegroups.com> Message-ID: <8d5d283f-b0bd-4e16-97c7-d2de1a148cae@l35g2000vba.googlegroups.com> Have you tried saving the files as MYScriptName.py? notice the py extension, very important ;) From rt8396 at gmail.com Fri Aug 28 19:33:38 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 16:33:38 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: <1b6492ae-ee59-4a09-a35a-b0db79b5db81@s13g2000yql.googlegroups.com> On Aug 28, 10:36?am, jfabi... at yolo.com wrote: (snip) > I'm inclined to agreed. ?But in recent years we lost a number of developers > to Ruby. ?I don't know but I doubt Ruby has a marketing budget. ?So in my > mind it is difficult for me to blame just the lack of marketing dollars for > the lost. ? Yes probably have since you can write Ruby code that almost mimics Python code, well except for that annoying "end" statement ;). But i think Ruby attracts more perl-heads and lispers anyhow. And i really doubt we want to caterer to that bunch *wink*. I shudder when i imagine a world without Python's simplistic beauty, it is a very scary thought... From rt8396 at gmail.com Fri Aug 28 19:56:44 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 16:56:44 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <8b9073d6-b539-4f0c-b26b-ecf9fd014a87@k6g2000yqn.googlegroups.com> On Aug 28, 5:37?pm, qwe rty wrote: > what else can NOT be done in python? what are the limitations of the > language? Why would you even want to know what can't be done? What is it that you would like to do with Python? If you want a one size fits all language you may be looking for a very long time... From python.list at tim.thechases.com Fri Aug 28 20:05:40 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 28 Aug 2009 19:05:40 -0500 Subject: What python can NOT do? In-Reply-To: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <4A9870D4.8070800@tim.thechases.com> qwe rty wrote: > i know that an interpreted language like python can't be used to make > an operating system or system drivers. As long as you are willing to write the OS hooks in C, you can write the userspace device drivers in Python: https://www.linuxquestions.org/questions/programming-9/how-to-write-device-driver-program-using-python-in-linux-687277/ Since Python is Turing-complete, there's no reason a whole OS couldn't be authored in Python. > what else can NOT be done in python? what are the limitations of the > language? I understand there's a little trouble getting Python to prove that P=NP You'll also find that it only comes close to solving the unrestricted three-body problem and the Traveling Salesman problem is still limited to fallible heuristics and searching the entire solution set in better than O(2**n) time. -tkc From aahz at pythoncraft.com Fri Aug 28 20:06:54 2009 From: aahz at pythoncraft.com (Aahz) Date: 28 Aug 2009 17:06:54 -0700 Subject: why python got less developers ? References: Message-ID: In article , wrote: >Chris Rebert wrote: >> On Thu, Aug 27, 2009 at 5:34 PM, Deep_Feelings >> wrote: >>> >>> python got relatively fewer numbers of developers than other high >>> level languages like .NET , java .. etc ??why ? >> >> We lack Sun and Microsoft's massive marketing departments. :) > >I'm inclined to agreed. But in recent years we lost a number of developers >to Ruby. Cite? I mean, I'm sure it's not zero, but "a number" implies quite a bit more than zero, which I'm inclined to doubt without good evidence. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From rt8396 at gmail.com Fri Aug 28 20:11:08 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 17:11:08 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> Message-ID: <827effaa-d0f7-4142-b4b9-6f9f8e0e7963@e34g2000vbm.googlegroups.com> On Aug 28, 5:48?pm, Mark Roseman wrote: (snip) > Thewww.tkdocs.comsite is 'language neutral' - currently the tutorial > covers Tcl, Perl, Ruby and yes Python, and allows you to switch between > any of those languages (or show all of them). True, however the coverage is incomplete. I would back this site if we can get a complete coverage of all widgets in the Python language. +0.1 From python.list at tim.thechases.com Fri Aug 28 20:14:39 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 28 Aug 2009 19:14:39 -0500 Subject: What python can NOT do? In-Reply-To: <4A9870D4.8070800@tim.thechases.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: <4A9872EF.2000708@tim.thechases.com> >> what else can NOT be done in python? what are the limitations of the >> language? > > I understand there's a little trouble getting Python to prove > that P=NP You'll also find that it only comes close to solving > the unrestricted three-body problem and the Traveling Salesman > problem is still limited to fallible heuristics and searching the > entire solution set in better than O(2**n) time. I forgot about solving the Spam problem entirely. And answering poorly worded/thought-out questions on the internet... I've also been sorely disappointed by Python's ability to make a good chocolate cream silk pie. -tkc From hkh00001 at gmail.com Fri Aug 28 20:26:06 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 17:26:06 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: On Aug 29, 3:14?am, Tim Chase wrote: > >> what else can NOT be done in python? what are the limitations of the > >> language? > > > I understand there's a little trouble getting Python to prove > > that P=NP ?You'll also find that it only comes close to solving > > the unrestricted three-body problem and the Traveling Salesman > > problem is still limited to fallible heuristics and searching the > > entire solution set in better than O(2**n) time. > > I forgot about solving the Spam problem entirely. ?And answering > poorly worded/thought-out questions on the internet... > > I've also been sorely disappointed by Python's ability to make a > good chocolate cream silk pie. > > -tkc if you don't know the answer please don't reply From rt8396 at gmail.com Fri Aug 28 20:31:22 2009 From: rt8396 at gmail.com (r) Date: Fri, 28 Aug 2009 17:31:22 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: On Aug 28, 7:05?pm, Tim Chase wrote: (snip) > Since Python is Turing-complete, there's no reason a whole OS > couldn't be authored in Python. Yes, and one could go from NY to LA on a unicycle but would one really want to? Talk about some redass and blueballs! *yikes* Yes, if i have learned anything in my life, i can say there are absolutely no boundaries to what humans can achieve short the limit of their own imagination and the ever fading remainder of ones life. From clp2 at rebertia.com Fri Aug 28 20:47:51 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Fri, 28 Aug 2009 17:47:51 -0700 Subject: copy construtor question In-Reply-To: <613204.64791.qm@web53105.mail.re2.yahoo.com> References: <613204.64791.qm@web53105.mail.re2.yahoo.com> Message-ID: <50697b2c0908281747q347d849cx3e8abe2ebe94a120@mail.gmail.com> On Fri, Aug 28, 2009 at 11:38 AM, xiaosong xia wrote: > Hi all, > > I am trying to define a class with copy constructor as following: > > class test: > > ???? def __init__(self, s=None): > > ????????? self=s Python uses call-by-object (http://effbot.org/zone/call-by-object.htm), so reassigning `self` does not affect the object outside of the body of the method. It is (practically) impossible to reassign `self` in the way and with the effect you're trying to do; that is, you never change what `self` points to from the outside world's perspective, you can only modify the object it already points at. > 1. Can 'self ' be a class attribute? Doing this would make no sense. > 2. How to make a copy constructor? Since Python lacks overloading based on parameter types, generally one does it the other way around and instead provides a method that produces a copy of the object. For example: class Point(object): def __init__(self, x, y): self. x = x self.y = y def copy(self): return Point(self.x, self.y) Cheers, Chris -- http://blog.rebertia.com From steve at REMOVE-THIS-cybersource.com.au Fri Aug 28 21:17:35 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 01:17:35 GMT Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <0022052b$0$2930$c3e8da3@news.astraweb.com> On Fri, 28 Aug 2009 15:37:46 -0700, qwe rty wrote: > i know that an interpreted language like python Languages are neither interpreted nor compiled. *Implementations* are interpreted or compiled. Perl has only one implementation, which is interpreted (as far as I know); Java has a number of implementations, some of which compile to byte-code, some compile to machine-code. There are C interpreters as well as C compilers. And languages like Forth have an unusual programming model which doesn't easily match the conventional interpreted/compiled distinction. Python has a number of implementations, all of which are compiled to byte- code, like early Java. None are purely interpreted; none are compiled to machine-code, although there are add-ons to CPython which will compile most Python code to machine-code. Some day, Python may include implementations which compile directly to machine-code. > can't be used to make an operating system or system drivers. With existing Python implementations, it would be difficult to write an OS, because the implementations assume there is already an operating system available to handle things like memory and disk IO. So before you could write an OS in Python, you would need to write a new Python implementation. However, you could easily write a "virtual OS" in Python which sat on top of the regular OS. Device drivers would be less difficult, but performance may be slow compared to drivers written in (say) C. Boot loaders are another type of software which would be impractical to write in existing Python implementations. > what else can NOT be done in python? what are the limitations of the > language? As a language, Python has no theoretical limits -- it is Turing Complete, which means anything you can do in C, Java, Lisp, or any other Turing Complete language, you could do in Python -- with sufficient effort, and provided you don't care about efficiency. In practice, though, we *do* care about efficiency, and about the effort required to write the program in the first case. In practical terms, Python the language makes most things easy to write but slower to run, so there are very few applications which couldn't be written in Python. A few things are more difficult than others. One of the hardest things to do is to "sandbox" some arbitrary Python code from an untrusted source and execute it in a restricted environment. In practical terms, Python will let you write nearly any sort of program you want, provided absolute performance isn't your provided. (To put it another way, Python code is rarely "the fastest", but it is usually "fast enough".) If performance is too slow, Python is an excellent "glue" language, letting you write the bulk of your program in Python for ease, the performance-critical parts in C for speed. Some practical restrictions... if you are writing a web app, some hosting providers don't provide access to Python on their webserver, so you're limited to using whatever languages they provide, or finding another provider. All existing Python implementations require a minimum amount of memory to operate. This is relatively high, so you probably couldn't use Python on a device where you only had (say) 64K of memory. There's no Python implementation for your ancient Mac Plus or Commodore 64, and there probably never will be. Python the language is based on an execution model with relatively high overhead, so even if you wrote an implementation for such ancient machines, you probably couldn't do much with it. Existing Python implementations don't give you direct access to hardware, and bit-manipulation has a lot of overhead in Python. Numerical calculations (e.g. scientific array calculations) also suffer from overhead, which is barely noticeable if you're doing a few thousand calculations, but if you're doing a few tens of millions may be a little slow. For these, you should use Python as an interface to numeric libraries written in C, like Scipy and Numpy. -- Steven From aahz at pythoncraft.com Fri Aug 28 21:25:57 2009 From: aahz at pythoncraft.com (Aahz) Date: 28 Aug 2009 18:25:57 -0700 Subject: variables of the class are not available as default values? References: Message-ID: In article , Chris Rebert wrote: > >class foo: > def __init__(self, maxvalue): > self.maxvalue =3D maxvalue > self.value =3D 0 > > def put(self, value=3DNone): > self.value =3D self.value if value is None else value Stylistic nit: I'd make that self.value = value if value is not None else self.value The reason is that the "primary" value should go first. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From bcb at undisclosedlocation.net Fri Aug 28 21:29:31 2009 From: bcb at undisclosedlocation.net (Bruce C. Baker) Date: Fri, 28 Aug 2009 20:29:31 -0500 Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <1v%lm.174048$zq1.37846@newsfe22.iad> "qwe rty" wrote in message news:00a36f89-52dd-4d90-a455-cee6a0c9d10f at q5g2000yqh.googlegroups.com... >i know that an interpreted language like python can't be used to make > an operating system or system drivers. > > what else can NOT be done in python? what are the limitations of the > language? It's a floor wax and a dessert topping too! :-) From python.list at tim.thechases.com Fri Aug 28 21:32:17 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 28 Aug 2009 20:32:17 -0500 Subject: What python can NOT do? In-Reply-To: References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: <4A988521.7070005@tim.thechases.com> qwe rty wrote: > On Aug 29, 3:14 am, Tim Chase wrote: >>>> what else can NOT be done in python? what are the limitations of the >>>> language? >>> I understand there's a little trouble getting Python to prove >>> that P=NP You'll also find that it only comes close to solving >>> the unrestricted three-body problem and the Traveling Salesman >>> problem is still limited to fallible heuristics and searching the >>> entire solution set in better than O(2**n) time. >> I forgot about solving the Spam problem entirely. And answering >> poorly worded/thought-out questions on the internet... >> >> I've also been sorely disappointed by Python's ability to make a >> good chocolate cream silk pie. > > if you don't know the answer please don't reply I'm not sure you understand -- Being a Turing complete language, anything you can do in any other language, you can do in Python. As "r" observed, it might not be a pleasant experience (though there are a lot of things I'd rather do in Python than in C or Assembly) but certainly doable. So clearly the issue resides in your nonsensical question. You asked for things you can't do with Python so I listed some. The things you can't do in Python are things you can't do in any other language either. To turn your snark on end, "If you can't post a sensible question, please don't post in the first place". But this is usenet, and Python can't solve the problem of nonsensical questions posted on usenet. :-/ -tkc From b1540457 at tyldd.com Fri Aug 28 21:43:23 2009 From: b1540457 at tyldd.com (Anny Mous) Date: Sat, 29 Aug 2009 11:43:23 +1000 Subject: Transforming a str to an operator References: <87skfcblo3.fsf@benfinney.id.au> <91126ac3-e7fe-4b7a-a37d-d1e60beaa278@w41g2000yqb.googlegroups.com> Message-ID: r wrote: > Abviously the OP is a python baby noob and casting your irrational > fear (and many others irrational fears) of eval It isn't irrational to have a healthy caution towards eval. Apart from the security issues, running code in eval takes a massive performance hit. Its about ten times slower to run eval("x+1") than to run x+1 directly. > at him is akin to > tales of Chupacabras running a muck in the jungle sucking the blood > from live goats in the twilight hours. I use eval all the time and > quite love it. LOL I'm not surprised. > This is nothing more than a throw away academic exercise that will > serve no useful purpose for him in the future, What makes you think that learning to program well in Python is a throw-away exercise of no useful purpose? I'm sure the code itself will be thrown away and forgotten, but it has a very important purpose: for the OP to learn good programming skills. Looks like you want him to learn bad skills, then spend the rest of his life trying to unlearn them. > but serves the very > useful purpose now of establishing an IO between the student and > Python interpretor. I'll bet most your example (albeit a good example) > flew miles above his head into la-la land. How insulting. Is there anything that gave you the impression the OP was stupid? > The OP has plenty of time to learn about malicious input and > protecting against it, right now the fundamentals are well... > fundamental :) When would you recommend he learns? When his web app is hijacked by gangsters in Russia and the personal details and financial records of fifty thousand people stolen? Protecting against malicious input *IS* fundamental. From nobody at nowhere.com Fri Aug 28 21:50:20 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 29 Aug 2009 02:50:20 +0100 Subject: [OT] How do I reply to a thread by sending a message to python-list@python.org References: <20090827073102.293C91DF2@ctb-mesg8.saix.net> <4A964C3B.8090206@ieee.org> Message-ID: On Thu, 27 Aug 2009 05:47:50 -0400, Terry Reedy wrote: >> I use Thunderbird, and treat the list as ordinary mail. I use >> reply-all, and it seems to do the right thing. Or at least if I'm >> breaking threads, nobody has pointed it out to me yet. > > reply-all may send duplicate messages to the author. Not sure of this list. If the author doesn't want duplicate replies, they would normally set a Reply-To header which points to the list. Some listservs provide an option to suppress duplicates, i.e. a message isn't sent if the recipient is listed in the To/CC headers. Enabling this option is a bad idea if you're stuck behind an aggressive spam filter: the listserv only knows whether you're listed as a recipient; it can't know whether you actually got the message. From nobody at nowhere.com Fri Aug 28 22:06:03 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 29 Aug 2009 03:06:03 +0100 Subject: Query screen resolution? References: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> Message-ID: On Fri, 28 Aug 2009 11:13:06 -0700, AK Eric wrote: > Thought this would be easy, maybe I'm missing something :) Trying to > query the x,y resolution of my screen. I've seen this available > through http://python.net/crew/mhammond/win32/ : > > from win32api import GetSystemMetrics > print "width =", GetSystemMetrics (0) > print "height =",GetSystemMetrics (1) > > But I was hoping for something built-in, and something non-OS > specific. Is that available? Would be nice to detect for multiple > monitors as well, but I'm probably asking too much :) Your question is based upon the notion that "the screen" is a meaningful concept. Once you move away from Windows (and systems which intentionally try to be like Windows), that's no longer true. E.g. if the program is being run on a terminal, the screen size is measured in characters, not pixels (80x25 would be a reasonable size). If the program is being run as a cron job or CGI script, there is no screen. OTOH, if the system has the X libraries installed, there are a practically unlimited number of X displays which you could connect to, provided that you have the appropriate authentication credentials. From nobody at nowhere.com Fri Aug 28 22:10:18 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 29 Aug 2009 03:10:18 +0100 Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: On Fri, 28 Aug 2009 17:31:22 -0700, r wrote: >> Since Python is Turing-complete, there's no reason a whole OS >> couldn't be authored in Python. > > Yes, and one could go from NY to LA on a unicycle but would one really > want to? Talk about some redass and blueballs! *yikes* > > Yes, if i have learned anything in my life, i can say there are > absolutely no boundaries to what humans can achieve short the limit of > their own imagination and the ever fading remainder of ones life. Well, other than writing a program to determine whether a program in a Turing-complete language will terminate on some input, or devising a formal system which is sound, complete, and able to express its own metatheory, or ... Some things are actually impossible. From hkh00001 at gmail.com Fri Aug 28 22:10:30 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 19:10:30 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: > > if you don't know the answer please don't reply > > I'm not sure you understand -- Being a Turing complete language, > anything you can do in any other language, you can do in Python. > ? As "r" observed, it might not be a pleasant experience (though > there are a lot of things I'd rather do in Python than in C or > Assembly) but certainly doable. > > So clearly the issue resides in your nonsensical question. ?You > asked for things you can't do with Python so I listed some. ?The > things you can't do in Python are things you can't do in any > other language either. ?To turn your snark on end, "If you can't > post a sensible question, please don't post in the first place". > > But this is usenet, and Python can't solve the problem of > nonsensical questions posted on usenet. :-/ > > -tkc i am free to post , you are free to ignore From hkh00001 at gmail.com Fri Aug 28 22:11:24 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 19:11:24 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <0022052b$0$2930$c3e8da3@news.astraweb.com> Message-ID: <380e1617-cd42-4b9d-820a-90d226751915@b18g2000vbl.googlegroups.com> On Aug 29, 4:17?am, Steven D'Aprano wrote: > On Fri, 28 Aug 2009 15:37:46 -0700, qwe rty wrote: > > i know that an interpreted language like python > > Languages are neither interpreted nor compiled. *Implementations* are > interpreted or compiled. > > Perl has only one implementation, which is interpreted (as far as I > know); Java has a number of implementations, some of which compile to > byte-code, some compile to machine-code. There are C interpreters as well > as C compilers. And languages like Forth have an unusual programming > model which doesn't easily match the conventional interpreted/compiled > distinction. > > Python has a number of implementations, all of which are compiled to byte- > code, like early Java. None are purely interpreted; none are compiled to > machine-code, although there are add-ons to CPython which will compile > most Python code to machine-code. Some day, Python may include > implementations which compile directly to machine-code. > > > can't be used to make an operating system or system drivers. > > With existing Python implementations, it would be difficult to write an > OS, because the implementations assume there is already an operating > system available to handle things like memory and disk IO. So before you > could write an OS in Python, you would need to write a new Python > implementation. However, you could easily write a "virtual OS" in Python > which sat on top of the regular OS. > > Device drivers would be less difficult, but performance may be slow > compared to drivers written in (say) C. > > Boot loaders are another type of software which would be impractical to > write in existing Python implementations. > > > what else can NOT be done in python? what are the limitations of the > > language? > > As a language, Python has no theoretical limits -- it is Turing Complete, > which means anything you can do in C, Java, Lisp, or any other Turing > Complete language, you could do in Python -- with sufficient effort, and > provided you don't care about efficiency. > > In practice, though, we *do* care about efficiency, and about the effort > required to write the program in the first case. In practical terms, > Python the language makes most things easy to write but slower to run, so > there are very few applications which couldn't be written in Python. > > A few things are more difficult than others. One of the hardest things to > do is to "sandbox" some arbitrary Python code from an untrusted source > and execute it in a restricted environment. > > In practical terms, Python will let you write nearly any sort of program > you want, provided absolute performance isn't your provided. (To put it > another way, Python code is rarely "the fastest", but it is usually "fast > enough".) If performance is too slow, Python is an excellent "glue" > language, letting you write the bulk of your program in Python for ease, > the performance-critical parts in C for speed. > > Some practical restrictions... if you are writing a web app, some hosting > providers don't provide access to Python on their webserver, so you're > limited to using whatever languages they provide, or finding another > provider. > > All existing Python implementations require a minimum amount of memory to > operate. This is relatively high, so you probably couldn't use Python on > a device where you only had (say) 64K of memory. There's no Python > implementation for your ancient Mac Plus or Commodore 64, and there > probably never will be. Python the language is based on an execution > model with relatively high overhead, so even if you wrote an > implementation for such ancient machines, you probably couldn't do much > with it. > > Existing Python implementations don't give you direct access to hardware, > and bit-manipulation has a lot of overhead in Python. Numerical > calculations (e.g. scientific array calculations) also suffer from > overhead, which is barely noticeable if you're doing a few thousand > calculations, but if you're doing a few tens of millions may be a little > slow. For these, you should use Python as an interface to numeric > libraries written in C, like Scipy and Numpy. > > -- > Steven thank you very much ,THIS is the sort of answer i wanted From nobody at nowhere.com Fri Aug 28 22:11:48 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 29 Aug 2009 03:11:48 +0100 Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: On Fri, 28 Aug 2009 17:26:06 -0700, qwe rty wrote: > if you don't know the answer please don't reply If you don't understand the question, don't post it in the first place. From hkh00001 at gmail.com Fri Aug 28 22:37:23 2009 From: hkh00001 at gmail.com (qwe rty) Date: Fri, 28 Aug 2009 19:37:23 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: On Aug 29, 5:11?am, Nobody wrote: > On Fri, 28 Aug 2009 17:26:06 -0700, qwe rty wrote: > > if you don't know the answer please don't reply > > If you don't understand the question, don't post it in the first place. don't be so angry ,not good for your health From warpcat at sbcglobal.net Fri Aug 28 23:15:57 2009 From: warpcat at sbcglobal.net (Warpcat) Date: Fri, 28 Aug 2009 20:15:57 -0700 (PDT) Subject: Query screen resolution? References: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> Message-ID: <409bf880-4e4b-48f4-8cfc-ecacf262d782@v15g2000prn.googlegroups.com> > Your question is based upon the notion that "the screen" is a meaningful > concept. Once you move away from Windows (and systems which intentionally > try to be like Windows), that's no longer true. Good points. Always something I haven't thought of. Ok so... let's *presume* the user has a measurable screen on win\mac\linux\etc since on any other OS they wouldn't be running the app.... From alan.isaac at gmail.com Fri Aug 28 23:36:12 2009 From: alan.isaac at gmail.com (Alan G Isaac) Date: Sat, 29 Aug 2009 03:36:12 GMT Subject: Select column from a list In-Reply-To: References: Message-ID: On 8/28/2009 3:45 AM hoffik wrote: > I'm quite new in Python and I have one question. I have a 2D matrix of > values stored in list (3 columns, many rows). I wonder if I can select one > column without having to go through the list with 'for' command. Not quite what you asked but ... >>> rows = [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)] >>> cols = map(None,*rows) >>> cols [(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12)] Now you can have any "column" you want. Alan Isaac PS You can also use imap if you prefer not to create the list. From rtomek at ceti.com.pl Fri Aug 28 23:37:34 2009 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Sat, 29 Aug 2009 05:37:34 +0200 Subject: What python can NOT do? In-Reply-To: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: On Fri, 28 Aug 2009, qwe rty wrote: > i know that an interpreted language like python can't be used to make > an operating system or system drivers. > > what else can NOT be done in python? what are the limitations of the > language? Oh, my. And now everybody points at you this Turing-completeness. The issue, in my opinion, is not that something cannot be done. The truth about Turing-completeness is, I would say, you can do whatever but sometimes you will not because it would be too ugly. My private list of things that when implemented in Python would be ugly to the point of calling it difficult: 1. AMB operator - my very favourite. In one sentence, either language allows one to do it easily or one would not want to do it (in an ugly way). http://www.randomhacks.net/articles/2005/10/11/amb-operator After quite some googling I was finally able to locate sample implementation, but I cannot say ATM how well it works and if it is practical enough to use it in any of my programs. If time permits, I will try it, hopefully. http://www.c2.com/cgi/wiki?AmbInPython 2. Changing the language from the inside. Everybody can change the interpreter, right? But how about doing some bigger, maybe even fundamental change to the language by means offered by the language itself? Example: If Python had no object system, or if I wanted to implement one in different way (say, I would like to experiment or I would not want to wait for a new release). In some languages that interest me now, it is possible and practical, more or less. So it can sometimes backfire - what OO system should I choose for my next Scheme program, etc. Because there are few of them :-), all (? - I believe) implemented as a code library. Just install it and off you go, now you have OO programming. Actually, I don't use OO all that much recently (maybe I feel disapointed a bit, or something). Also, I have read (but not checked it myself) that for some time Common Lisp had it's now-official CLOS distributed and tested in a form of library. Say, have they adopted OO with single inheritance as a part of CL ANSI standard - I would still be able to have OO with multiple inheritance. I would just have to download and install CLOS. No change to interpreter or compiler. From their point of view, CLOS would be just another library. http://en.wikipedia.org/wiki/Common_Lisp_Object_System Judging by this code, introducing OO to the language is relatively easy: http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme-Z-H-14.html It is not possible to alter Python in a minor way, I think. Something simpler than OO, like a new keyword or structures: http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme-Z-H-10.html http://www.ccs.neu.edu/home/dorai/t-y-scheme/t-y-scheme-Z-H-11.html Some readers could oppose the above by saying that Lisp's syntax is so primitive that it can be used to implement just any programming paradigm, so having it as a loadable code is not a big achievement. Well, it seems to me that Python has even simpler syntax or on par with Lisp family, so... Some (perhaps other) readers could also say, that there is no need to extend Python. It already has sets and "yield" and... But some time ago it did not. As far as I can tell, it can be a bit too hard to go into "experimenting mode" with Python. Something like adding "yield" all but myself. It only takes few kilos of code for a working OO in another language, so how hard could such "yield" be? Well, in Python I probably wouldn't dare. BTW I hope nobody's feeling have been hurt. This was meant to be informative, not offensive. BTW2. As I said, these are _possible_ things (Turing complete language, and so on). But adding them would require some hard work and would produce ugly and/or fragile code, so I decided it could be easier to learn another language... Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From aahz at pythoncraft.com Fri Aug 28 23:41:12 2009 From: aahz at pythoncraft.com (Aahz) Date: 28 Aug 2009 20:41:12 -0700 Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: In article , qwe rty wrote: > >> > if you don't know the answer please don't reply >> >> I'm not sure you understand -- Being a Turing complete language, >> anything you can do in any other language, you can do in Python. >> =A0 As "r" observed, it might not be a pleasant experience (though >> there are a lot of things I'd rather do in Python than in C or >> Assembly) but certainly doable. >> >> So clearly the issue resides in your nonsensical question. =A0You >> asked for things you can't do with Python so I listed some. =A0The >> things you can't do in Python are things you can't do in any >> other language either. =A0To turn your snark on end, "If you can't >> post a sensible question, please don't post in the first place". >> >> But this is usenet, and Python can't solve the problem of >> nonsensical questions posted on usenet. :-/ >> >> -tkc > >i am free to post , you are free to ignore Well -- don't you think the same applies in reverse? Remember that Python is named after the comedy group Monty Python, and jokes are a frequent occurrence on this group. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From sebouel at gmail.com Sat Aug 29 00:28:17 2009 From: sebouel at gmail.com (=?ISO-8859-1?Q?S=E9bastien_Ouellet?=) Date: Fri, 28 Aug 2009 21:28:17 -0700 (PDT) Subject: A lot of problem with pygame.mixer module! References: Message-ID: I had the same problem and struggled through every solution posted on the web. None actually helped but I discovered bbfreeze : http://pypi.python.org/pypi/bbfreeze/ It works as well as py2exe and there are no problems with pygame.mixer. It's easy to install and the example script at the end of the page does the trick. On 20 juil, 08:28, Alex wrote: > hi at all, > As email object I 'm not be able to run my program when compiled with > py2exe. > Everythink ?works fine until I try to make an exe. > After that, it crash and in the log: > > C:\dist\sponge.exe:97: RuntimeWarning: use mixer: DLL load failed: The > specified module could not be found. > Traceback (most recent call last): > ? File "sponge.py", line 97, in > ? File "pygame\__init__.pyo", line 70, in __getattr__ > NotImplementedError: mixer module not available > > The code about pygame.mixer is only: > > pygame.mixer.init() > music = pygame.mixer.Sound("popcorn.ogg") > music.play() > > in the dist folder there is SDL_mixer.dll so...HOW can I solve this > problem ?? > thanks in advance > Alex > Below my setup.py > > # py2exe setup program > from distutils.core import setup > import py2exe > import pygame > from modulefinder import Module > #from pygame import mixer > import ImageGrab > import sys > import os > import Tkinter > import glob, shutil > sys.argv.append("py2exe") > > VERSION = '1.0' > AUTHOR_NAME = 'Your Name' > AUTHOR_EMAIL = 'your_em... at somewhere.com' > AUTHOR_URL = "http://www.urlofyourgamesite.com/" > PRODUCT_NAME = "Sponge" > SCRIPT_MAIN = 'sponge.py' > VERSIONSTRING = PRODUCT_NAME + " ALPHA " + VERSION > ICONFILE = 'icon.ico' > > # Remove the build tree on exit automatically > REMOVE_BUILD_ON_EXIT = True > > if os.path.exists('dist/'): shutil.rmtree('dist/') > > extra_files = [ ("",[ICONFILE,'WinLockDll.dll','popcorn.ogg']), > ? ? ? ? ? ? ? ? ? ?#("data",glob.glob(os.path.join('data','*.dat'))), > ? ? ? ? ? ? ? ? ? ?#("gfx",glob.glob(os.path.join('gfx','*.jpg'))), > ? ? ? ? ? ? ? ? ? ?#("gfx",glob.glob(os.path.join('gfx','*.png'))), > ? ? ? ? ? ? ? ? ? ?("fonts",glob.glob(os.path.join('fonts','*.ttf'))), > ? ? ? ? ? ? ? ? ? ?("music",glob.glob(os.path.join('music','*.ogg')))] > ? ? ? ? ? ? ? ? ? ?#("snd",glob.glob(os.path.join('snd','*.wav')))] > > # List of all modules to automatically exclude from distribution build > # This gets rid of extra modules that aren't necessary for proper > functioning of app > # You should only put things in this list if you know exactly what you > DON'T need > # This has the benefit of drastically reducing the size of your dist > > MODULE_EXCLUDES =[ > 'email', > 'AppKit', > 'Foundation', > 'bdb', > 'difflib', > 'tcl', > #'Tkinter', > #'Tkconstants', > 'curses', > 'distutils', > 'setuptools', > 'urllib', > 'urllib2', > 'urlparse', > 'BaseHTTPServer', > '_LWPCookieJar', > '_MozillaCookieJar', > 'ftplib', > 'gopherlib', > '_ssl', > 'htmllib', > 'httplib', > 'mimetools', > 'mimetypes', > 'rfc822', > 'tty', > 'webbrowser', > 'socket', > 'hashlib', > #'base64', > 'compiler', > 'pydoc' > ] > > INCLUDE_STUFF = ['encodings',"encodings.latin_1"] > > setup(windows=[ > ? ? ? ? ? ? ?{'script': SCRIPT_MAIN, > ? ? ? ? ? ? ? ?'other_resources': [(u"VERSIONTAG",1,VERSIONSTRING)], > ? ? ? ? ? ? ? ?'icon_resources': [(1,ICONFILE)]}], > ? ? ? ? ?options = {"py2exe": { > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"optimize": 2, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"includes": INCLUDE_STUFF, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"compressed": 1, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"ascii": 1, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?#"bundle_files": 1, > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"ignores": > ['tcl','AppKit','Numeric','Foundation'], > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?"excludes": MODULE_EXCLUDES} }, > ? ? ? ? ? name = PRODUCT_NAME, > ? ? ? ? ? version = VERSION, > ? ? ? ? ? data_files = extra_files, > ? ? ? ? ? #zipfile = None, > ? ? ? ? ? author = AUTHOR_NAME, > ? ? ? ? ? author_email = AUTHOR_EMAIL, > ? ? ? ? ? url = AUTHOR_URL) > > # Create the /save folder for inclusion with the installer > #shutil.copytree('save','dist/save') > > #if os.path.exists('dist/tcl'): shutil.rmtree('dist/tcl') > > # Remove the build tree > if REMOVE_BUILD_ON_EXIT: > ? ? ?shutil.rmtree('build/') > > if os.path.exists('dist/tcl84.dll'): os.unlink('dist/tcl84.dll') > if os.path.exists('dist/tk84.dll'): os.unlink('dist/tk84.dll') From gagsl-py2 at yahoo.com.ar Sat Aug 29 00:37:37 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Aug 2009 01:37:37 -0300 Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> Message-ID: En Fri, 28 Aug 2009 15:25:55 -0300, zaur escribi?: > On 28 ???, 16:07, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> zaur a ?crit : >> >> > Ok. Here is a use case: object initialization. >> >> > For example, >> >> > person = Person(): >> > ? name = "john" >> > ? age = 30 >> > ? address = Address(): >> > ? ? ?street = "Green Street" >> > ? ? ?no = 12 >> >> > vs. >> >> > person = Person() >> > person.name = "john" >> > person.age = 30 >> > address = person.address = Address() >> > address.street = "Green Street" >> > address.no = 12 >> >> Err... Looks like you really should read the FineManual(tm) - >> specifically, the parts on the __init__ method. >> >> class Person(object): >> ? ? def __init__(self, name, age, address): >> ? ? ? ? self.name = name >> ? ? ? ? self.age = age >> ? ? ? ? self.address = address >> >> class Address(object): >> ? ? def __init__(self, street, no): >> ? ? ? ? self.no = no >> ? ? ? ? self.street = street >> >> person = Person( >> ? ? name="john", >> ? ? age=30, >> ? ? address = Address( >> ? ? ? ? street="Green Street", >> ? ? ? ? no=12 >> ? ? ) >> ) > > What are you doing if 1) classes Person and Address imported from > foreign module 2) __init__ method is not defined as you want? Welcome to dynamic languages! It doesn't matter *where* the class was defined. You may add new attributes to the instance (even methods to the class) at any time. 1) person = Person() vars(person).update(name="john",age=30,address=Address()) vars(person.Address).update(street="Green Street",no=12) 2) def the_initializer_i_would_like(person, name, age): person.name = name person.age = age person = Person() the_initializer_i_would_like(person, name="john", age=30) 3) def the_initializer_i_would_like(self, name, age): self.name = name self.age = age Person.init = the_initializer_i_would_like person = Person() person.init(name="john", age=30) 4) def a_generic_updater(obj, **kw): try: ns = vars(obj) except Exception: ns = None if ns is not None: ns.update(kw) else: for name in kw: setattr(obj, name, kw[name]) person = Person() a_generic_updater(person, name="john", age=30) -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sat Aug 29 00:43:09 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Aug 2009 01:43:09 -0300 Subject: how to edit .wsgi file extebtions with IDLE on windows References: Message-ID: En Fri, 28 Aug 2009 15:31:31 -0300, gert escribi?: > I can't figure out how to enable the .py shell and syntax highlighting > for .wsgi file extensions using IDLE for windows ? That's a Windows question, not a Python one. You have to associate the .wsgi extension with the Python.File file type (the one used for .py files): D:\USERDATA\Gabriel>assoc .py .py=Python.File D:\USERDATA\Gabriel>assoc .wsgi=Python.File .wsgi=Python.File -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sat Aug 29 00:48:36 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Aug 2009 01:48:36 -0300 Subject: copy construtor question References: <613204.64791.qm@web53105.mail.re2.yahoo.com> <50697b2c0908281747q347d849cx3e8abe2ebe94a120@mail.gmail.com> Message-ID: En Fri, 28 Aug 2009 21:47:51 -0300, Chris Rebert escribi?: > On Fri, Aug 28, 2009 at 11:38 AM, xiaosong xia > wrote: >> >> 2. How to make a copy constructor? > > Since Python lacks overloading based on parameter types, generally one > does it the other way around and instead provides a method that > produces a copy of the object. For example: > > class Point(object): > def __init__(self, x, y): > self. x = x > self.y = y > > def copy(self): > return Point(self.x, self.y) For simple enough cases, the copy and deepcopy functions in the copy module are just fine: http://docs.python.org/library/copy.html -- Gabriel Genellina From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 01:21:08 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 05:21:08 GMT Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <00223e3f$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 05:37:34 +0200, Tomasz Rola wrote: > My private list of > things that when implemented in Python would be ugly to the point of > calling it difficult: > > 1. AMB operator - my very favourite. In one sentence, either language > allows one to do it easily or one would not want to do it (in an ugly > way). > > http://www.randomhacks.net/articles/2005/10/11/amb-operator Fascinating, but I don't exactly see how that's actually *useful*. It strikes me of combining all the benefits of COME FROM with the potential performance of Bogosort, but maybe I'm being harsh. On the other hand, it sounds rather like Prolog-like declarative programming. I fear that, like Prolog, it risks massive performance degradation if you don't apply the constraints in the right order. > 2. Changing the language from the inside. > > Everybody can change the interpreter, right? But how about doing some > bigger, maybe even fundamental change to the language by means offered > by the language itself? Like Forth. You need it in Forth, because it has a very sparse set of language features, and everything is bootstrapped from a small set of commands, so the ability to re-define the language as you go is (1) necessary and (2) free. But for Python, I don't know... it sounds cool, but in practice? It sounds like the sort of thing that allows programmers to spend three hours writing a new control structure which will save them three minutes. And of course, for all but the tiniest, one-man-band applications, readability is important. Sure, you've created a gee-whizz control structure which combines try, while and if into one keyword, and it automatically does logging and threading, fantastic. But how will anyone else be able to maintain it when you're gone? The ability to change the language is one step into a tarpit, where everything is possible but nothing is easy, and where you spend all your time writing language features and none of your time building the useful functionality you actually want. It sounds like something you want in a language you use for designing languages, rather than writing applications. -- Steven From rozzin at geekspace.com Sat Aug 29 01:23:59 2009 From: rozzin at geekspace.com (Joshua Judson Rosen) Date: Sat, 29 Aug 2009 01:23:59 -0400 Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> Message-ID: <87vdk76vm8.fsf@slice.rozzin.com> Robert Kern writes: > > On 2009-08-28 16:42 PM, Terry Reedy wrote: > > Carl Banks wrote: > > > > > I don't think it needs a syntax for that, but I'm not so sure a > > > method to modify a value in place with a single key lookup > > > wouldn't occasioanally be useful. > > > > Augmented assignment does that. > > No, it uses one __getitem__ and one __setitem__ thus two key lookups. Apparently you're defining "key lookup" some other way than as `what __getitem__ does'. What exactly does "key lookup" mean to you? I've always understood it as `retrieving the value associated with a key', which obviously isn't required for assignment--otherwise it wouldn't be possible to add new keys to a mapping. -- Don't be afraid to ask (Lf.((Lx.xx) (Lr.f(rr)))). From rozzin at geekspace.com Sat Aug 29 01:37:21 2009 From: rozzin at geekspace.com (Joshua Judson Rosen) Date: Sat, 29 Aug 2009 01:37:21 -0400 Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> <58e91734-d03f-417c-89b1-f2717c3a9181@l5g2000yqo.googlegroups.com> Message-ID: <87ws4n5gfi.fsf@slice.rozzin.com> Carl Banks writes: > > On Aug 28, 2:42?pm, Terry Reedy wrote: > > > Carl Banks wrote: > > > I don't think it needs a syntax for that, but I'm not so sure a method > > > to modify a value in place with a single key lookup wouldn't > > > occasioanally be useful. > > > > Augmented assignment does that. > > Internally uses two lookups, one for getting, and one for setting. > > I think this is an unavoidable given Python's semantics. Look at > the traceback: > > > >>> def x(): > ... d['a'] += 1 > ... > >>> dis.dis(x) > 2 0 LOAD_GLOBAL 0 (d) > 3 LOAD_CONST 1 ('a') > 6 DUP_TOPX 2 > 9 BINARY_SUBSCR OK, there's one lookup, but... > 10 LOAD_CONST 2 (1) > 13 INPLACE_ADD > 14 ROT_THREE > 15 STORE_SUBSCR > 16 LOAD_CONST 0 (None) > 19 RETURN_VALUE ... I don't see anything in there that retrieves the value a second time.... > > > As a workaround, if lookups are expensive, > > > > But they are not. Because (C)Python is heavily based on dict name lookup > > for builtins and global names and attributes, as well as overt dict > > lookup, must effort has gone into optimizing dict lookup. > > The actual lookup algorithm Python dicts use is well-optimized, yes, > but the dict could contain keys that have expensive comparison and > hash-code calculation, in which case lookup is going to be slow. I'll like the originator correct me if I've made a mistake, but I read "lookup" as actually meaning "lookup", not "value-comparison". At least in part because the question, as it was posed, specifically related to a wrapper-class (providing a mapping ("dict like") interface) around a database of some sort other than Python's dict class per se. How do the details of Python's native dict-type's internal (hashtable) algorithm matter when they're explicitly /not/ being used? -- Don't be afraid to ask (Lf.((Lx.xx) (Lr.f(rr)))). From icevi.icevi at gmail.com Sat Aug 29 02:09:45 2009 From: icevi.icevi at gmail.com (Vivian Wang) Date: Fri, 28 Aug 2009 23:09:45 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: Message-ID: On Aug 24, 8:08?pm, Gilles Ganault wrote: > Hello > > ? ? ? ? I was wondering if some people in this ng use Python and some GUI > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > applications, and if yes, what it's like, the pros and cons, etc. > > I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. > > I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. > > Thank you. On Aug 24, 8:08 pm, Gilles Ganault wrote: > Hello > > I was wondering if some people in this ng use Python and some GUI > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > applications, and if yes, what it's like, the pros and cons, etc. > > I'm especially concerned about the lack of controls, the lack of > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > linked to how to update users' PC remotely when I build a new version > using eg. Py2exe. > > I need controls for business apps like access to databases, good data > grid, printing reports (with or without barcodes), etc. > > Thank you. You can try biform: http://www.bilive.com/download/Setup_BiForm_V2.1_en.msi.zip Demo: http://www.bilive.com/demo/BiForm_EN_demo.htm More demo:(Chinese version) http://www.bilive.com/demo/ BiForm is a form designer,one designed form will deploy as a PFF file. BiReader is a runtime PFF file process engine for end-users. Setup file above include BiForm and BiReader. Main features: *Python as script language,base on QT GUI library *Visible form designer *Internal database access framework *Auto connect database,auto create tables *Supports SQLite/Mssql2000/Sybase ASE,not need write diffrent script for diffrent database at most time *Simple deploy,simple upgrade *Different forms can share same tables, they will auto cooperation with other forms at runtime.If you want to deploy a new function , not need uninstall other forms,deploy the new PFF file is enough . From ivanko.rus at gmail.com Sat Aug 29 02:28:26 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 06:28:26 +0000 Subject: Monitoring stdout in (more or less) real time Message-ID: <000e0cd148be848541047241e842@google.com> Hello to everyone! I am making a program that will be a GTK+ frontend to ffmpeg. Naturally, one of the main functions is parsing ffmpeg's output. It's pretty simple when I, for example, retrieve information about a file (the program finishes and I read the output). But it also needs to parse working ffmpeg's output (in order to retrieve the percentage, remaining time, etc.). So, actually what I do is Popen ffmpeg, and connect to its stdout. And as stdout is represented by a file object, it needs to be read(). The problem is that read() reads until EOF is reached, which doesn't exist while the program is running (the same goes with communicate()). So my question is: is there a way to retrieve the stdout without waiting the program to finish? PS. I think it might be redirected to a "normal", existing file, but may be there are more optimal ways. I will be grateful for any answer! And sorry for my English =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From icevi.icevi at gmail.com Sat Aug 29 02:32:16 2009 From: icevi.icevi at gmail.com (Vivian Wang) Date: Fri, 28 Aug 2009 23:32:16 -0700 (PDT) Subject: IDE for python similar to visual basic References: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> Message-ID: <2127e0be-3b93-406f-99a7-5fe02e643b40@a39g2000pre.googlegroups.com> On Aug 29, 6:19?am, qwe rty wrote: > i have been searching for am IDE for python that is similar to Visual > Basic but had no luck.shall you help me please? You can try biform: http://www.bilive.com/download/Setup_BiForm_V2.1_en.msi.zip Demo: http://www.bilive.com/demo/BiForm_EN_demo.htm More demo:(Chinese version) http://www.bilive.com/demo/ BiForm is a form designer,one designed form will deploy as a PFF file. BiReader is a runtime PFF file process engine for end-users. Setup file above include BiForm and BiReader. Main features: *Python as script language,base on QT GUI library *Visible form designer *Internal database access framework *Auto connect database,auto create tables *Supports SQLite/Mssql2000/Sybase ASE,not need write diffrent script for diffrent database at most time *Simple deploy,simple upgrade *Different forms can share same tables,they will auto cooperation with other forms at runtime.If you want to deploy a new function , not need uninstall other forms,deploy the new PFF file is enough . From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 03:10:11 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 07:10:11 GMT Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> <87vdk76vm8.fsf@slice.rozzin.com> Message-ID: <002257cf$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 01:23:59 -0400, Joshua Judson Rosen wrote: > Robert Kern writes: >> >> On 2009-08-28 16:42 PM, Terry Reedy wrote: >> > Carl Banks wrote: >> > >> > > I don't think it needs a syntax for that, but I'm not so sure a >> > > method to modify a value in place with a single key lookup wouldn't >> > > occasioanally be useful. >> > >> > Augmented assignment does that. >> >> No, it uses one __getitem__ and one __setitem__ thus two key lookups. > > Apparently you're defining "key lookup" some other way than as `what > __getitem__ does'. > > What exactly does "key lookup" mean to you? > > I've always understood it as `retrieving the value associated with a > key', which obviously isn't required for assignment--otherwise it > wouldn't be possible to add new keys to a mapping. When you retrieve a value from a dictionary using __getitem__, e.g.: dict["K"] the dict has to search the hash table for the record with key "K". This a key lookup. (I use the term "search", but of course for hash tables this is usually very fast. For Python dicts, you can assume it will usually be a constant time, independent of the key or the size of the dict.) When you store a value in a dictionary using __setitem__, e.g.: dict["K"] = 42 the dict has to search the hash table for the correct place to store a record with key "K". It obviously can't place the record in some arbitrary place, it has to be in the correct place for future lookups to find it. This is also a key lookup. -- Steven From erik.reppen at gmail.com Sat Aug 29 03:20:59 2009 From: erik.reppen at gmail.com (Pherdnut) Date: Sat, 29 Aug 2009 00:20:59 -0700 (PDT) Subject: Python Noob - gui module, book, annoying questions Message-ID: <92cc4ca1-0e0d-4355-8d9a-b4928390e619@q35g2000vbi.googlegroups.com> I want to write cross-platform stuff. Any opinions on the best GUI module for that? I like a good juicy, but concise book for reading on my commute downtown. I was thinking of checking Python in a Nutshell. Good? Bad? Better? Is 3.0+ more object based? I'm actually an FED and one of the things I love about JS is the consistency of the language. I love Python 2.6 so far so I'm not knocking it. But I'm not really taking advantage of the non-core libraries as much right now anyway since I'm learning it. What do you guys like in Reg Ex books/sites? I'd like to become more fluent in some of the less commonly used stuff. From gagsl-py2 at yahoo.com.ar Sat Aug 29 03:21:20 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Aug 2009 04:21:20 -0300 Subject: Monitoring stdout in (more or less) real time References: <000e0cd148be848541047241e842@google.com> Message-ID: En Sat, 29 Aug 2009 03:28:26 -0300, escribi?: > Hello to everyone! I am making a program that will be a GTK+ frontend to > ffmpeg. Naturally, one of the main functions is parsing ffmpeg's output. > It's pretty simple when I, for example, retrieve information about a file > (the program finishes and I read the output). But it also needs to parse > working ffmpeg's output (in order to retrieve the percentage, remaining > time, etc.). So, actually what I do is Popen ffmpeg, and connect to its > stdout. And as stdout is represented by a file object, it needs to be > read(). The problem is that read() reads until EOF is reached, which > doesn't exist while the program is running (the same goes with > communicate()). > So my question is: is there a way to retrieve the stdout without waiting > the program to finish? You don't have to read the complete output at once - you may process it line by line, I presume. I'd use a second thread to read the pipe and put the lines onto a Queue object; the main thread gets lines from the Queue when available. -- Gabriel Genellina From thorsten at thorstenkampe.de Sat Aug 29 03:34:43 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 29 Aug 2009 09:34:43 +0200 Subject: (Simple?) Unicode Question References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> Message-ID: * Rami Chowdhury (Thu, 27 Aug 2009 09:44:41 -0700) > > Further, does anything, except a printing device need to know the > > encoding of a piece of "text"? Python needs to know if you are processing the text. > I may be wrong, but I believe that's part of the idea between separation > of string and bytes types in Python 3.x. I believe, if you are using > Python 3.x, you don't need the character encoding mumbo jumbo at all ;-) Nothing has changed in that regard. You still need to decode and encode text and for that you have to know the encoding. Thorsten From szport at gmail.com Sat Aug 29 03:34:48 2009 From: szport at gmail.com (zaur) Date: Sat, 29 Aug 2009 00:34:48 -0700 (PDT) Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> Message-ID: <9205fd44-90ec-4ce6-be2a-2f82dd99e13e@r27g2000vbn.googlegroups.com> On 29 ???, 08:37, "Gabriel Genellina" wrote: > En Fri, 28 Aug 2009 15:25:55 -0300, zaur escribi?: > > > > > On 28 ???, 16:07, Bruno Desthuilliers > 42.desthuilli... at websiteburo.invalid> wrote: > >> zaur a ?crit : > > >> > Ok. Here is a use case: object initialization. > > >> > For example, > > >> > person = Person(): > >> > ? name = "john" > >> > ? age = 30 > >> > ? address = Address(): > >> > ? ? ?street = "Green Street" > >> > ? ? ?no = 12 > > >> > vs. > > >> > person = Person() > >> > person.name = "john" > >> > person.age = 30 > >> > address = person.address = Address() > >> > address.street = "Green Street" > >> > address.no = 12 > > >> Err... Looks like you really should read the FineManual(tm) - > >> specifically, the parts on the __init__ method. > > >> class Person(object): > >> ? ? def __init__(self, name, age, address): > >> ? ? ? ? self.name = name > >> ? ? ? ? self.age = age > >> ? ? ? ? self.address = address > > >> class Address(object): > >> ? ? def __init__(self, street, no): > >> ? ? ? ? self.no = no > >> ? ? ? ? self.street = street > > >> person = Person( > >> ? ? name="john", > >> ? ? age=30, > >> ? ? address = Address( > >> ? ? ? ? street="Green Street", > >> ? ? ? ? no=12 > >> ? ? ) > >> ) > > > What are you doing if 1) classes Person and Address imported from > > foreign module 2) __init__ method is not defined as you want? > > Welcome to dynamic languages! It doesn't matter *where* the class was ? > defined. You may add new attributes to the instance (even methods to the ? > class) at any time. > > 1) > person = Person() > vars(person).update(name="john",age=30,address=Address()) > vars(person.Address).update(street="Green Street",no=12) > > 2) > def the_initializer_i_would_like(person, name, age): > ? ?person.name = name > ? ?person.age = age > > person = Person() > the_initializer_i_would_like(person, name="john", age=30) > > 3) > def the_initializer_i_would_like(self, name, age): > ? ?self.name = name > ? ?self.age = age > > Person.init = the_initializer_i_would_like > person = Person() > person.init(name="john", age=30) > > 4) > def a_generic_updater(obj, **kw): > ? ?try: ns = vars(obj) > ? ?except Exception: ns = None > ? ?if ns is not None: > ? ? ?ns.update(kw) > ? ?else: > ? ? ?for name in kw: > ? ? ? ?setattr(obj, name, kw[name]) > > person = Person() > a_generic_updater(person, name="john", age=30) > > -- > Gabriel Genellina I know about these ways of object initializing. What I said is about using object's dictionary as nested scope in code block. Object initialization is just one use case. So we say about different things. From hendrik at microcorp.co.za Sat Aug 29 03:36:38 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 29 Aug 2009 09:36:38 +0200 Subject: comparison on list yields surprising result In-Reply-To: <25195170.post@talk.nabble.com> References: <25195170.post@talk.nabble.com> Message-ID: <200908290936.38375.hendrik@microcorp.co.za> On Friday 28 August 2009 21:00:31 Dr. Phillip M. Feldman wrote: > In [21]: x > Out[21]: [1, 2, 3, 5] > > In [22]: x>6 > Out[22]: True > > Is this a bug? No, it is a feature, so that you can use sorted on this: [[1,2,3,4,5],6] - Hendrik From hendrik at microcorp.co.za Sat Aug 29 03:50:43 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 29 Aug 2009 09:50:43 +0200 Subject: What python can NOT do? In-Reply-To: <4A9872EF.2000708@tim.thechases.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> <4A9872EF.2000708@tim.thechases.com> Message-ID: <200908290950.43216.hendrik@microcorp.co.za> On Saturday 29 August 2009 02:14:39 Tim Chase wrote: > I've also been sorely disappointed by Python's ability to make a > good chocolate cream silk pie. This is not pythons fault - it is yours, for failing to collaborate with a good hardware designer for the robotics. - Hendrik From nomail at nomail.com Sat Aug 29 03:54:15 2009 From: nomail at nomail.com (Sortie) Date: Sat, 29 Aug 2009 07:54:15 +0000 (UTC) Subject: Combining C and Python programs Message-ID: I want to write a program that will use ode for the physics simulation, whose python bindings are outdated. So I'm writing the physics engine in C and want to write the drawing code in Python. What will be the best way of making those two programs work together? THe physics engine won't have to run concurrently with the drawing code. It will only return some position data so they can be drawn. From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 04:16:21 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 08:16:21 GMT Subject: comparison on list yields surprising result References: <25195170.post@talk.nabble.com> Message-ID: <00226752$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 09:36:38 +0200, Hendrik van Rooyen wrote: > On Friday 28 August 2009 21:00:31 Dr. Phillip M. Feldman wrote: >> In [21]: x >> Out[21]: [1, 2, 3, 5] >> >> In [22]: x>6 >> Out[22]: True >> >> Is this a bug? > > No, it is a feature, so that you can use sorted on this: > > [[1,2,3,4,5],6] If it's a feature, it has gone away in Python 3. Python 3.0.1 (r301:69556, Apr 2 2009, 00:41:38) [GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> [[1,2,3], 5].sort() Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: int() < list() -- Steven From hendrik at microcorp.co.za Sat Aug 29 04:24:52 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 29 Aug 2009 10:24:52 +0200 Subject: Combining C and Python programs In-Reply-To: References: Message-ID: <200908291024.52629.hendrik@microcorp.co.za> On Saturday 29 August 2009 09:54:15 Sortie wrote: > I want to write a program that will use ode for the physics > simulation, whose python bindings are outdated. So I'm writing > the physics engine in C and want to write the drawing code in > Python. What will be the best way of making those two programs > work together? THe physics engine won't have to run concurrently > with the drawing code. It will only return some position data so > they can be drawn. Have you looked at ctypes? - Hendrik From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 04:26:54 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 08:26:54 GMT Subject: (Simple?) Unicode Question References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> Message-ID: <002269cb$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 09:34:43 +0200, Thorsten Kampe wrote: > * Rami Chowdhury (Thu, 27 Aug 2009 09:44:41 -0700) >> > Further, does anything, except a printing device need to know the >> > encoding of a piece of "text"? > > Python needs to know if you are processing the text. Python only needs to know when you convert the text to or from bytes. I can do this: >>> s = "hello" >>> t = "world" >>> print(' '.join([s, t])) hello world and not need to care anything about encodings. So long as your terminal has a sensible encoding, and you have a good quality font, you should be able to print any string you can create. >> I may be wrong, but I believe that's part of the idea between >> separation of string and bytes types in Python 3.x. I believe, if you >> are using Python 3.x, you don't need the character encoding mumbo jumbo >> at all ;-) > > Nothing has changed in that regard. You still need to decode and encode > text and for that you have to know the encoding. You only need to worry about encoding when you convert from bytes to text, and visa versa. Admittedly, the most common time you need to do that is when reading input from files, but if all your text strings are generated by Python, and not output anywhere, you shouldn't need to care about encodings. If all your text contains nothing but ASCII characters, you should never need to worry about encodings at all. -- Steven From bilawal.samoon at gmail.com Sat Aug 29 04:46:15 2009 From: bilawal.samoon at gmail.com (bilawal samoon) Date: Sat, 29 Aug 2009 01:46:15 -0700 (PDT) Subject: SEI Job Opening Message-ID: SEI is seeking a FT, YR Photovoltaic Technical Manager. If you are a team player with a minimum of 4 years PV installation, curriculum and education development, management experience, the ability to multitask, strong verbal and written communication skills, and a sense of humor, SEI invites you to apply to join our team in Paonia, Colorado. For more details www.technicaledu.blogspot.com From thangappan143 at gmail.com Sat Aug 29 05:12:36 2009 From: thangappan143 at gmail.com (Thangappan.M) Date: Sat, 29 Aug 2009 14:42:36 +0530 Subject: Suggestion Message-ID: <7aa29e790908290212h17d27593u52d1a90b3e785386@mail.gmail.com> Dear all, I am in the process of learning Python programming language. I know Perl,PHP. Compare to both the language Python impressed me because here there is no lexical variables and all.Now I need suggestion saying that , What online book can I follow? I have not yet learnt any advanced programming stuffs in Python. Please suggest some book? or tutorial. net net my goal is that I will be able to do the project in any languages(Python,Perl,PHP).So I need to learn more depth knowledge of Python. So Please help me? -- Regards, Thangappan.M -------------- next part -------------- An HTML attachment was scrubbed... URL: From thangappan143 at gmail.com Sat Aug 29 05:14:00 2009 From: thangappan143 at gmail.com (Thangappan.M) Date: Sat, 29 Aug 2009 14:44:00 +0530 Subject: IDE for Python Message-ID: <7aa29e790908290214ode909c8od898918e86759daf@mail.gmail.com> Dear all, Please suggest some good IDE for python.I am working in linux platform. -- Regards, Thangappan.M -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sat Aug 29 06:58:10 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 29 Aug 2009 03:58:10 -0700 (PDT) Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> <58e91734-d03f-417c-89b1-f2717c3a9181@l5g2000yqo.googlegroups.com> <87ws4n5gfi.fsf@slice.rozzin.com> Message-ID: On Aug 28, 10:37?pm, Joshua Judson Rosen wrote: > Carl Banks writes: > > > On Aug 28, 2:42?pm, Terry Reedy wrote: > > > > Carl Banks wrote: > > > > I don't think it needs a syntax for that, but I'm not so sure a method > > > > to modify a value in place with a single key lookup wouldn't > > > > occasioanally be useful. > > > > Augmented assignment does that. > > > Internally uses two lookups, one for getting, and one for setting. > > > I think this is an unavoidable given Python's semantics. ?Look at > > the traceback: > > > >>> def x(): > > ... ? ? d['a'] += 1 > > ... > > >>> dis.dis(x) > > ? 2 ? ? ? ? ? 0 LOAD_GLOBAL ? ? ? ? ? ? ?0 (d) > > ? ? ? ? ? ? ? 3 LOAD_CONST ? ? ? ? ? ? ? 1 ('a') > > ? ? ? ? ? ? ? 6 DUP_TOPX ? ? ? ? ? ? ? ? 2 > > ? ? ? ? ? ? ? 9 BINARY_SUBSCR > > OK, there's one lookup, but... > > > ? ? ? ? ? ? ?10 LOAD_CONST ? ? ? ? ? ? ? 2 (1) > > ? ? ? ? ? ? ?13 INPLACE_ADD > > ? ? ? ? ? ? ?14 ROT_THREE > > ? ? ? ? ? ? ?15 STORE_SUBSCR > > ? ? ? ? ? ? ?16 LOAD_CONST ? ? ? ? ? ? ? 0 (None) > > ? ? ? ? ? ? ?19 RETURN_VALUE > > ... I don't see anything in there that retrieves the value a second time.... STORE_SUBSCR has to look up the position in the hash table to store the value, hence the second lookup. > > > > As a workaround, if lookups are expensive, > > > > But they are not. Because (C)Python is heavily based on dict name lookup > > > for builtins and global names and attributes, as well as overt dict > > > lookup, must effort has gone into optimizing dict lookup. > > > The actual lookup algorithm Python dicts use is well-optimized, yes, > > but the dict could contain keys that have expensive comparison and > > hash-code calculation, in which case lookup is going to be slow. > > I'll like the originator correct me if I've made a mistake, but I read > "lookup" as actually meaning "lookup", not "value-comparison". This has nothing to do with value comparison. I was talking about key comparison, which happens when looking up a position in a hash table. I was the first person to use the word "lookup" in this thread and I specifically meant hash-table position lookup. > At least in part because the question, as it was posed, specifically > related to a wrapper-class (providing a mapping ("dict like") interface) > around a database of some sort other than Python's dict class per se. > > How do the details of Python's native dict-type's internal (hashtable) > algorithm matter when they're explicitly /not/ being used? Well it doesn't apply specifically to the OP's problem. I changed the topic a bit by making it specific to dicts. Is that ok with you? Was that not allowed? The OP can add a method like apply_to_value to his own class, but one can't do that for dicts. Ergo why something like apply_to_value() would be useful enough in rare circumstances where lookup is very slow to merit a moments consideration before being rejected. (If dict did have a method like that, the OP would at least know which method to override.) Carl Banks From vicente.soler at gmail.com Sat Aug 29 07:01:46 2009 From: vicente.soler at gmail.com (vsoler) Date: Sat, 29 Aug 2009 04:01:46 -0700 (PDT) Subject: Colors on IDLE References: <59922ab5-f8c9-429f-b1ea-9b1418aa6b71@t13g2000yqt.googlegroups.com> <8d5d283f-b0bd-4e16-97c7-d2de1a148cae@l35g2000vba.googlegroups.com> Message-ID: <311ec593-4050-4a6a-adbd-2325698a4b61@h30g2000vbr.googlegroups.com> On Aug 29, 1:27?am, r wrote: > Have you tried saving the files as MYScriptName.py? notice the py > extension, very important ;) That was it!!! I see the colors again. Thank you. From paul at subsignal.org Sat Aug 29 07:16:00 2009 From: paul at subsignal.org (paul) Date: Sat, 29 Aug 2009 13:16:00 +0200 Subject: why python got less developers ? In-Reply-To: References: Message-ID: Deep_Feelings schrieb: > python got relatively fewer numbers of developers than other high > level languages like .NET , java .. etc why ? Besides the marketing argument, python never had a "hype". Both PHP and ruby(Rails to be precise) got widespread because they could at one point do "one" thing better than the competition. From there on, they had more ressources (developer time) and grew fast and beyond the original problem domain. Now you can write GUI apps in PHP, great! cheers Paul From thorsten at thorstenkampe.de Sat Aug 29 07:34:18 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sat, 29 Aug 2009 13:34:18 +0200 Subject: Colors on IDLE References: <59922ab5-f8c9-429f-b1ea-9b1418aa6b71@t13g2000yqt.googlegroups.com> <8d5d283f-b0bd-4e16-97c7-d2de1a148cae@l35g2000vba.googlegroups.com> <311ec593-4050-4a6a-adbd-2325698a4b61@h30g2000vbr.googlegroups.com> Message-ID: * vsoler (Sat, 29 Aug 2009 04:01:46 -0700 (PDT)) > On Aug 29, 1:27?am, r wrote: > > Have you tried saving the files as MYScriptName.py? notice the py > > extension, very important ;) > > That was it!!! > > I see the colors again. Thank you. I suggest you start using familiar technical terms. Like "syntax highlighting" instead of "see colours". That would increase the number of useful answers you get - at least it will stop people from thinking you talk about controlled substances. Thorsten From mwawrzyczek at gmail.com Sat Aug 29 08:14:34 2009 From: mwawrzyczek at gmail.com (Marek Wawrzyczek) Date: Sat, 29 Aug 2009 05:14:34 -0700 (PDT) Subject: gettext translate problem Message-ID: Hi, I've got the following code in main.py file: import gettext import os t = gettext.translation(__file__.split('.')[0], os.getcwd()) _ = t.lgettext if __name__=='__main__': print _("Hello") then I call: xgettext main.py and after that I call: msgfmt messages.po wchich produces the following message: messages.po: warning: Charset "CHARSET" is not a portable encoding name. Message conversion to user's charset might not work. then after calling: python main.py the following output is print: Traceback (most recent call last): File "main.py", line 4, in t = gettext.translation(__file__.split('.')[0], os.getcwd()) File "/usr/lib/python2.5/gettext.py", line 484, in translation raise IOError(ENOENT, 'No translation file found for domain', domain) IOError: [Errno 2] No translation file found for domain: 'main' How to use gettext translation method properly? Regards, Marek From invalid at invalid Sat Aug 29 08:21:11 2009 From: invalid at invalid (Grant Edwards) Date: Sat, 29 Aug 2009 07:21:11 -0500 Subject: Annoying octal notation References: <87d46ok948.fsf@benfinney.id.au> <02a0b085$0$30337$c3e8da3@news.astraweb.com> <00216447$0$2930$c3e8da3@news.astraweb.com> Message-ID: On 2009-08-28, Neil Hodgson wrote: > Steven D'Aprano: > >> Obviously I can't speak for Ken Thompson's motivation in creating this >> feature, but I'm pretty sure it wasn't to save typing or space on >> punchcards. > > The original implementation of UNIX was on a PDP-7 which was an > 18-bit machine. Octal = 3 bits at a a time which evenly divides an > 18-bit word whereas the 4 bits of hexadecimal do not. Early > implementations of B were (according to Wikipedia) on the PDP-7, PDP-11 > (a 16-bit machine) and Honeywell 36-bit mainframes. > > Octal was widely used on the PDP-11. The PDP-11's 16-bit instruction word consisted mainly of 3-bit fields for destiation-mode, destination-register, source-mode, source-register. So, it was quite easy for the progammer to read/write machine code in octal. -- Grant Edwards grante Yow! I've read SEVEN at MILLION books!! visi.com From gert.cuykens at gmail.com Sat Aug 29 08:40:29 2009 From: gert.cuykens at gmail.com (gert) Date: Sat, 29 Aug 2009 05:40:29 -0700 (PDT) Subject: how to edit .wsgi file extebtions with IDLE on windows References: Message-ID: <58a021ce-3058-483d-b429-6ba4855807ac@o36g2000vbl.googlegroups.com> On Aug 29, 6:43?am, "Gabriel Genellina" wrote: > En Fri, 28 Aug 2009 15:31:31 -0300, gert escribi?: > > > I can't figure out how to enable the .py shell and syntax highlighting > > for .wsgi file extensions using IDLE for windows ? > > That's a Windows question, not a Python one. You have to associate the ? > .wsgi extension with the Python.File file type (the one used for .py ? > files): > > D:\USERDATA\Gabriel>assoc .py > .py=Python.File > > D:\USERDATA\Gabriel>assoc .wsgi=Python.File > .wsgi=Python.File > Thanks that does make it open exactly like a .py file, expect that there is no syntax highlighting. Don't know if this is also a windows issue or a IDLE issue ? From szport at gmail.com Sat Aug 29 08:45:54 2009 From: szport at gmail.com (zaur) Date: Sat, 29 Aug 2009 05:45:54 -0700 (PDT) Subject: Is behavior of += intentional for int? Message-ID: Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "copyright", "credits" or "license()" for more information. >>> a=1 >>> x=[a] >>> id(a)==id(x[0]) True >>> a+=1 >>> a 2 >>> x[0] 1 I thought that += should only change the value of the int object. But += create new. Is this intentional? From ptmcg at austin.rr.com Sat Aug 29 09:08:49 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 29 Aug 2009 06:08:49 -0700 (PDT) Subject: Is behavior of += intentional for int? References: Message-ID: On Aug 29, 7:45?am, zaur wrote: > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin > Type "copyright", "credits" or "license()" for more information.>>> a=1 > >>> x=[a] > >>> id(a)==id(x[0]) > True > >>> a+=1 > >>> a > 2 > >>> x[0] > > 1 > > I thought that += should only change the value of the int object. But > += create new. > Is this intentional? ints are immutable. But your logic works fine with a mutable object, like a list: >>> a = [1] >>> x = [a] >>> print id(a) == id(x[0]) True >>> a += [1] >>> print a [1, 1] >>> print x[0] [1, 1] What exactly are you trying to do? -- Paul From gd_usenet at spamfence.net Sat Aug 29 09:23:20 2009 From: gd_usenet at spamfence.net (=?UTF-8?Q?G=C3=BCnther?= Dietrich) Date: Sat, 29 Aug 2009 15:23:20 +0200 Subject: Is behavior of += intentional for int? References: Message-ID: <8nmnm6-g6g.ln1@spamfence.net> zaur wrote: >Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) >[GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin >Type "copyright", "credits" or "license()" for more information. >>>> a=1 >>>> x=[a] >>>> id(a)==id(x[0]) >True >>>> a+=1 >>>> a >2 >>>> x[0] >1 > >I thought that += should only change the value of the int object. But >+= create new. >Is this intentional? An integer variable contains the reference (ID) to an (immutable) integer object; it doesn't contain the value itself. So, when you assign a new value to an integer variable, it will contain the reference to the object containing the new value, afterwards. If you assign an integer variable to a list element, this reference will be written into the list. The assignment of a new value to the integer variable will create a new integer object, containing the new value, and put the reference to it into the integer variable. The reference to the object with the old value, that is stored in the list, won't be touched. In fact, it is a result of integers in python being immutable. Best regards, G?nther From nitebirdz at sacredchaos.com Sat Aug 29 09:33:38 2009 From: nitebirdz at sacredchaos.com (Nitebirdz) Date: Sat, 29 Aug 2009 15:33:38 +0200 Subject: Blank Line at Program Exit In-Reply-To: References: <20090822152515.GC10584@sevilla.sacredchaos.com> Message-ID: <20090829133337.GA6751@sevilla.sacredchaos.com> On Sun, Aug 23, 2009 at 09:07:53PM +0800, Steven Woody wrote: > > Hi, > I am using cywin on XP. > Sorry for the late reply. I've been too busy with some personal matters. It'd seem to me that you're better off taking this issue to the Cygwin mailing lists, since it doesn't seem to be related to Python itself. From jkpeck at gmail.com Sat Aug 29 10:12:33 2009 From: jkpeck at gmail.com (JKPeck) Date: Sat, 29 Aug 2009 07:12:33 -0700 (PDT) Subject: csv module and None values References: <23c02daf-dc5a-4676-8d73-9dc63791825f@o36g2000vbl.googlegroups.com> <4006702e-14c5-4917-b76f-906233cad71e@k30g2000yqf.googlegroups.com> Message-ID: On Aug 25, 8:49?am, Peter Otten <__pete... at web.de> wrote: > JKPeck wrote: > > On Aug 24, 10:43 pm, John Yeung wrote: > >> On Aug 24, 5:00 pm, Peter Otten <__pete... at web.de> wrote: > > >> > If I understand you correctly the csv.writer already does > >> > what you want: > > >> > >>> w.writerow([1,None,2]) > >> > 1,,2 > > >> > just sequential commas, but that is the special treatment. > >> > Without it the None value would be converted to a string > >> > and the line would look like this one: > > >> > 1,None,2 > > >> No, I think he means he is getting > > >> >>> w.writerow([1,None,2]) > > >> 1,"",2 > > >> He evidently wants to quote "all" strings, but doesn't want None to be > >> considered a string. > > >> John > > > Exactly so. ?The requirement of the receiving program, which is out of > > my control, is that all strings be quoted but a None in a numeric > > field result in the ,, output rather than "". ?Excel quotes strings > > conditionally, which doesn't do what is needed in this case. ?For > > QUOTE_NONNUMERIC to quote None values makes some sense, but it gets in > > the way of representing missing values in a numeric field. ?It would > > be nice to have a choice here in the dialects. > > > I thought of replacing the None values with float(nan), since that has > > a numeric type, but unfortunately that results in writing the string > > (unquoted) nan for the value. ?So the sentinel approach seems to be > > the best I can do. > > How about: > > >>> import csv, sys > >>> class N(int): > > ... ? ? def __str__(self): return "" > ...>>> pseudo_none = N() > >>> w = csv.writer(sys.stdout, quoting=csv.QUOTE_NONNUMERIC) > >>> w.writerow([1, "foo", pseudo_none, "bar"]) > > 1,"foo",,"bar" > > Peter Clever. Thanks, Jon From forzamila2004 at hotmail.com Sat Aug 29 10:12:54 2009 From: forzamila2004 at hotmail.com (Momen) Date: Sat, 29 Aug 2009 16:12:54 +0200 Subject: the best book for learning python !? Message-ID: -------------- next part -------------- An HTML attachment was scrubbed... URL: From rurpy at yahoo.com Sat Aug 29 10:38:51 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sat, 29 Aug 2009 07:38:51 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: On 08/28/2009 02:12 AM, "Martin v. L?wis" wrote: [I reordered the quotes from your previous post to try and get the responses in a more coherent order. No intent to take anything out of context...] >> Nothing else in the PEP seems remotely relevant. [to providing justification for the behavior of unichr/ord] > > Except for the motivation, of course :-) > > In addition: your original question was "why has this > been changed", to which the answer is "it hasn't". My original interest was two-fold: can unichr/ord be changed to work in a more general and helpful way? That seemed remotely possible until it was pointed out that the two behave consistently, and that behavior is accurately documented. Second, why would they work the way they do when they could have been generalized to cover the full unicode space? An inadequate answer to this would have provided support for the first point but remains interesting to me for the reason below. > Then, the next question is "why is it implemented that > way", to which the answer is "because the PEP says so". Not at all a satisfying answer unless one believes in PEPal infallibility. :-) > Only *then* the question is "what is the rationale for > the PEP specifying things the way it does". The PEP is > relevant so that we can both agree that Python behaves > correctly (in the sense of behaving as specified). But my question had become: why that behavior, when a slightly different behavior would be more general with little apparent downside? To clarify, my interest in the justification for the current behavior is this: I think the best feature of python is not, as commonly stated, the clean syntax, but rather the pretty complete and orthogonal libraries. I often find, after I have written some code, that due to the right library functions being available, it turns out much shorter and concise than I expected. Nevertheless, every now and then, perhaps more than in some other languages (I'm not sure), I run into something that requires what seems to be excessive coding -- I have to do something it seems to me that a library function should have done for me. Sometimes this is because I don't under- stand the reason the library function needs to works the way it does. Other times it is one of the countless trade- off made in the design of the language, which didn't happen to go the way that would have been beneficial to me in a particular coding situation. But sometimes (and it feels too often) it seems as though, zen not withstanding, that purity -- adherence to some philosophic ideal -- beat practicality. unichr/ord seems such as case to me, But I want to be sure I am not missing something. The reasons for the current behavior so far: 1. > What you propose would break the property "unichr(i) always returns > a string of length one, if it returns anything at all". Yes. And i don't see the problem with that. Why is that property more desirable than the non-existent property that a Unicode literal always produces one python character? It would only occur on a narrow build with a unicode character outside of the bmp, exactly the condition a unicode literal can "behave differently" by producing two python characters. 2. > > But there is no reason given [in the PEP] for that behavior. > Sure there is, right above the list: > "Most things will behave identically in the wide and narrow worlds." > That's the reason: scripts should work the same as much as possible > in wide and narrow builds. So what else would work "differently"? My point was that extending unichr/ord to work with all unicode characters reduces differences far more often than it increase them. 3. >> * There is a convention in the Unicode world for >> encoding a 32-bit code point in terms of two >> 16-bit code points. These are known as >> "surrogate pairs". Python's codecs will adopt >> this convention. >> >> Is a distinction made between Python and Python >> codecs with only the latter having any knowledge of >> surrogate pairs? > > No. In the end, the Unicode type represents code units, > not code points, i.e. half surrogates are individually > addressable. Codecs need to adjust to that; in particular > the UTF-8 and the UTF-32 codec in narrow builds, and the > UTF-16 codec in wide builds (which didn't exist when the > PEP was written). OK, so that is not a reason either. 4. I'll speculate a little. If surrogate handling was added to ord/unichr, it would be the top of a slippery slope leading to demands that other string functions also handle surrogates. But this is not true -- there is a strong distinction between ord/unichr and other string methods. The latter deal with strings of multiple characters. But the former deals only with single characters (taking a surrogate pair as a single unicode character.) The behavior of ord/unichr is independent of the other string methods -- if they were changed with regard to surrogate handling they would all have to be changed to maintain consistent behavior. Unichr/str affect only each other. The functions of ord/unichr -- to map characters to numbers -- are fundamental string operations, akin to indexing or extracting a substring. So why would one want to limit them to a subset of characters if not absolutely necessary? To reiterate, I am not advocating for any change. I simply want to understand if there is a good reason for limiting the use of unchr/ord on narrow builds to a subset of the unicode characters that Python otherwise supports. So far, it seems not and that unichr/ord is a poster child for "purity beats practicality". From tw55413 at gmail.com Sat Aug 29 10:49:22 2009 From: tw55413 at gmail.com (erikj) Date: Sat, 29 Aug 2009 07:49:22 -0700 (PDT) Subject: Python for professsional Windows GUI apps? References: <7f519c34-2d6e-4fff-9489-dae43c6b2df1@r42g2000yqj.googlegroups.com> <6b961048-782a-428c-9c0a-4fb17e87b57f@s13g2000yql.googlegroups.com> Message-ID: On Aug 27, 2:31?pm, Neuruss wrote: > On 26 ago, 05:29, erikj wrote: > > > > > Hi, > > > You could have a look at Camelot, to see if it fits > > your needs :http://www.conceptive.be/projects/camelot/ > > > it was developed with cross platform business apps in > > mind. ?when developing Camelot, we tried to build it using > > wxWidgets first (because of the licensing at that time), > > but it turned out that developing with QT proved to be > > much more straightforward. ?QT is documented very well > > and you seldom encounter 'strange' issues that cost hours > > of time to pinpoint and fix. > > > the datagrid was developed to be able to handle millions > > of database records without glitches and is flexible thanks > > to QT's model-view-delegate framework. > > > we do print barcodes with this app (even directly to > > zebra printers) > > > if you have questions regarding Camelot, please feel free > > to post on our mailing list :http://groups.google.com/group/project-camelot > > > Regards, > > > Erik > > > On Aug 24, 2:08?pm, Gilles Ganault wrote: > > > > Hello > > > > ? ? ? ? I was wondering if some people in this ng use Python and someGUI > > > toolkit (PyWin32, wxWidgets, QT, etc.) to build professional > > > applications, and if yes, what it's like, the pros and cons, etc. > > > > I'm especially concerned about the lack of controls, the lack of > > > updates (lots of controls in wxWidgets are 1.0 deadware), and problems > > > linked to how to update users' PC remotely when I build a new version > > > using eg. Py2exe. > > > > I need controls for business apps like access to databases, good data > > > grid, printing reports (with or without barcodes), etc. > > > > Thank you. > > Looks interesting, but I wonder if I can use Camelot without its ORM. > I feel that ORMs make easy things easier, but complex things much > harder... > Can I use it with plain old sql? > > Luis Yes and no :) It uses sqlalchemy as it's orm, which is quite flexible and allows the use of plain old sql, but you still have to map the result to objects for the GUI to to handle them. You are right that the ORM makes easy things easier, eg. what we do a lot is to create our core model using the ORM, and then create the different summaries directly as views in the database (since these are usually very complex queries, and those tend to be easier to write/debug in plain old sql). Then we use the ORM again to map those views back to objects and have them visualized. Cheers, Erik From timothy.tsvetkov at gmail.com Sat Aug 29 10:52:03 2009 From: timothy.tsvetkov at gmail.com (Timothy N. Tsvetkov) Date: Sat, 29 Aug 2009 07:52:03 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: On Aug 29, 4:26?am, qwe rty wrote: > On Aug 29, 3:14?am, Tim Chase wrote: > > > > > > > >> what else can NOT be done in python? what are the limitations of the > > >> language? > > > > I understand there's a little trouble getting Python to prove > > > that P=NP ?You'll also find that it only comes close to solving > > > the unrestricted three-body problem and the Traveling Salesman > > > problem is still limited to fallible heuristics and searching the > > > entire solution set in better than O(2**n) time. > > > I forgot about solving the Spam problem entirely. ?And answering > > poorly worded/thought-out questions on the internet... > > > I've also been sorely disappointed by Python's ability to make a > > good chocolate cream silk pie. > > > -tkc > > if you don't know the answer please don't reply If you want to ask a silly question don't ask it. From deets at nospam.web.de Sat Aug 29 11:22:29 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 29 Aug 2009 17:22:29 +0200 Subject: Combining C and Python programs In-Reply-To: References: Message-ID: <7fsvdlF2lo7cgU1@mid.uni-berlin.de> Sortie schrieb: > I want to write a program that will use ode for the physics > simulation, whose python bindings are outdated. So I'm writing > the physics engine in C and want to write the drawing code in > Python. What will be the best way of making those two programs > work together? THe physics engine won't have to run concurrently > with the drawing code. It will only return some position data so > they can be drawn. How about you update the ODE-bindings? They shouldn't be hard to enhance to cover the latest features. Diez From rtomek at ceti.com.pl Sat Aug 29 11:51:30 2009 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Sat, 29 Aug 2009 17:51:30 +0200 Subject: What python can NOT do? In-Reply-To: References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: On Sat, 29 Aug 2009, Timothy N. Tsvetkov wrote: > On Aug 29, 4:26?am, qwe rty wrote: > > On Aug 29, 3:14?am, Tim Chase wrote: > > > > > >> what else can NOT be done in python? what are the limitations of the > > > >> language? > > [...] > > > I forgot about solving the Spam problem entirely. ?And answering > > > poorly worded/thought-out questions on the internet... > > > > > I've also been sorely disappointed by Python's ability to make a > > > good chocolate cream silk pie. > > > > > -tkc > > > > if you don't know the answer please don't reply > > If you want to ask a silly question don't ask it. The question the OP asked was not silly. Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From gherron at islandtraining.com Sat Aug 29 12:12:29 2009 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 29 Aug 2009 09:12:29 -0700 Subject: Is behavior of += intentional for int? In-Reply-To: References: Message-ID: <4A99536D.6080002@islandtraining.com> zaur wrote: > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin > Type "copyright", "credits" or "license()" for more information. > >>>> a=1 >>>> x=[a] >>>> id(a)==id(x[0]) >>>> > True > >>>> a+=1 >>>> a >>>> > 2 > >>>> x[0] >>>> > 1 > > I thought that += should only change the value of the int object. But > += create new. > Is this intentional? > > You don't need the (slight) complexity of += to see this. Straight assignment shows the same behavior. Try this: a=1 print id(a) a=2 print id(a) The different results from the two prints happens because Python stores integers 1 and 2 in different locations and the assignments causes a to refer to one and then the other. Gary Herron -------------- next part -------------- An HTML attachment was scrubbed... URL: From vicente.soler at gmail.com Sat Aug 29 12:25:48 2009 From: vicente.soler at gmail.com (vsoler) Date: Sat, 29 Aug 2009 09:25:48 -0700 (PDT) Subject: Colors on IDLE References: <59922ab5-f8c9-429f-b1ea-9b1418aa6b71@t13g2000yqt.googlegroups.com> <8d5d283f-b0bd-4e16-97c7-d2de1a148cae@l35g2000vba.googlegroups.com> <311ec593-4050-4a6a-adbd-2325698a4b61@h30g2000vbr.googlegroups.com> Message-ID: On Aug 29, 1:34?pm, Thorsten Kampe wrote: > * vsoler (Sat, 29 Aug 2009 04:01:46 -0700 (PDT)) > > > On Aug 29, 1:27?am, r wrote: > > > Have you tried saving the files as MYScriptName.py? notice the py > > > extension, very important ;) > > > That was it!!! > > > I see the colors again. Thank you. > > I suggest you start using familiar technical terms. Like "syntax > highlighting" instead of "see colours". That would increase the number > of useful answers you get - at least it will stop people from thinking > you talk about controlled substances. > > Thorsten I'll keep it in mind for next time. Thank you Vicente Soler From gd_usenet at spamfence.net Sat Aug 29 12:25:54 2009 From: gd_usenet at spamfence.net (=?UTF-8?Q?G=C3=BCnther?= Dietrich) Date: Sat, 29 Aug 2009 18:25:54 +0200 Subject: Is behavior of += intentional for int? References: Message-ID: Paul McGuire wrote: >What exactly are you trying to do? I think, he wants to kind of dereference the list element. So that he can write >>> a += 1 instead of >>> long_name_of_a_list_which_contains_data[mnemonic_pointer_name] += 1 Regards, G?nther From cryzed at googlemail.com Sat Aug 29 12:28:24 2009 From: cryzed at googlemail.com (cryzed) Date: Sat, 29 Aug 2009 18:28:24 +0200 Subject: AutoIt/Autohotkey Python library for Linux Message-ID: Hey, maybe some of you are familiar with the tools "AutoIt" () and "Autohotkey" () for Windows - I was wondering if you knew about Python libraries which provide similiar functionality for Python programs under Linux. That said, those libraries would have to rely on X11 internally to provide their functionality. Also, yes, I know that there are X11-bindings for Python - but I honestly think that they aren't remotely useable and they are also incomplete. It would be great if you guys had some tips for me. From rt8396 at gmail.com Sat Aug 29 13:17:38 2009 From: rt8396 at gmail.com (r) Date: Sat, 29 Aug 2009 10:17:38 -0700 (PDT) Subject: Transforming a str to an operator References: <87skfcblo3.fsf@benfinney.id.au> <91126ac3-e7fe-4b7a-a37d-d1e60beaa278@w41g2000yqb.googlegroups.com> Message-ID: <38877ac9-cc2d-4293-b682-cfaf5cd3c861@o13g2000vbl.googlegroups.com> On Aug 28, 8:43?pm, Anny Mous wrote: > It isn't irrational to have a healthy caution towards eval. Ignorance is never an excuse for stupidity. No caution is needed if you know how to properly use eval. You can't shoot yourself in the foot without first pulling the trigger. > Apart from the security issues, running code in eval takes a massive > performance hit. Its about ten times slower to run eval("x+1") than to run > x+1 directly. And the point is...? eval is only for corner cases. Nobody is suggesting he eval entire scripts. Performance is the last of my worries. Optimizations can come later. First understand the problem at hand, code up a working solution, then tweak and optimize the code to perfection. > What makes you think that learning to program well in Python is a throw-away > exercise of no useful purpose? I'm sure the code itself will be thrown away > and forgotten, but it has a very important purpose: for the OP to learn > good programming skills. Looks like you want him to learn bad skills, then > spend the rest of his life trying to unlearn them. No i want him to use eval properly .If you think eval is scary well thats just your opinion. I showed the OP how to successfully pass the arguments into eval the way he was unsuccesfully struggling to pass them. Ben's approach is the professional/proper way to handle such input in the real world (there are other ways too), however the OP also must know that you don't *have* to go by the book all the time (python is not Java ya know?). > > but serves the very > > useful purpose now of establishing an IO between the student and > > Python interpretor. I'll bet most your example (albeit a good example) > > flew miles above his head into la-la land. > > How insulting. Is there anything that gave you the impression the OP was > stupid? Please quote the line from my post were i called the OP stupid or used otherwise derogatory comments? And if you can i'll buy you a beer. Obviously anyone who shows example code as the OP did is a noob and needs proper training on how to use it and there is nothing wrong with that. We have all been there, remember? > > The OP has plenty of time to learn about malicious input and > > protecting against it, right now the fundamentals are well... > > fundamental :) > > When would you recommend he learns? When his web app is hijacked by > gangsters in Russia and the personal details and financial records of fifty > thousand people stolen? Protecting against malicious input *IS* > fundamental. If the OP uses eval without inderstanding it and then shoots himself in the foot, well then i can't think of a better learning experience for him. I'll bet the next time he will read the docs first or ask on this list before he goes off on a turkey hunt ;). Fear is a product of ignorance. Educate yourself and your irrational fears shall bother you no more. From cryzed at googlemail.com Sat Aug 29 13:37:56 2009 From: cryzed at googlemail.com (cryzed) Date: Sat, 29 Aug 2009 19:37:56 +0200 Subject: AutoIt/Autohotkey-like library for Linux Message-ID: Hey, maybe some of you are familiar with the tools "AutoIt" (http://www.autoitscript.com/autoit3/) and "Autohotkey" (http://www.autohotkey.com/) for Windows - I was wondering if you knew about Python libraries which provide similiar functionality for Python programs under Linux. That said, those libraries would have to rely on X11 internally to provide their functionality. Also, yes, I know that there are X11-bindings for Python - but I honestly think that they aren't remotely useable and they are also incomplete. It would be great if you guys had some tips for me. From python at mrabarnett.plus.com Sat Aug 29 13:39:11 2009 From: python at mrabarnett.plus.com (MRAB) Date: Sat, 29 Aug 2009 18:39:11 +0100 Subject: Transforming a str to an operator In-Reply-To: <38877ac9-cc2d-4293-b682-cfaf5cd3c861@o13g2000vbl.googlegroups.com> References: <87skfcblo3.fsf@benfinney.id.au> <91126ac3-e7fe-4b7a-a37d-d1e60beaa278@w41g2000yqb.googlegroups.com> <38877ac9-cc2d-4293-b682-cfaf5cd3c861@o13g2000vbl.googlegroups.com> Message-ID: <4A9967BF.6000700@mrabarnett.plus.com> r wrote: > On Aug 28, 8:43 pm, Anny Mous wrote: >> It isn't irrational to have a healthy caution towards eval. > > Ignorance is never an excuse for stupidity. No caution is needed if > you know how to properly use eval. You can't shoot yourself in the > foot without first pulling the trigger. > >> Apart from the security issues, running code in eval takes a massive >> performance hit. Its about ten times slower to run eval("x+1") than to run >> x+1 directly. > > And the point is...? > eval is only for corner cases. Nobody is suggesting he eval entire > scripts. Performance is the last of my worries. Optimizations can come > later. First understand the problem at hand, code up a working > solution, then tweak and optimize the code to perfection. > >> What makes you think that learning to program well in Python is a throw-away >> exercise of no useful purpose? I'm sure the code itself will be thrown away >> and forgotten, but it has a very important purpose: for the OP to learn >> good programming skills. Looks like you want him to learn bad skills, then >> spend the rest of his life trying to unlearn them. > > No i want him to use eval properly .If you think eval is scary well > thats just your opinion. I showed the OP how to successfully pass the > arguments into eval the way he was unsuccesfully struggling to pass > them. Ben's approach is the professional/proper way to handle such > input in the real world (there are other ways too), however the OP > also must know that you don't *have* to go by the book all the time > (python is not Java ya know?). > >>> but serves the very >>> useful purpose now of establishing an IO between the student and >>> Python interpretor. I'll bet most your example (albeit a good example) >>> flew miles above his head into la-la land. >> How insulting. Is there anything that gave you the impression the OP was >> stupid? > > Please quote the line from my post were i called the OP stupid or used > otherwise derogatory comments? And if you can i'll buy you a beer. > Obviously anyone who shows example code as the OP did is a noob and > needs proper training on how to use it and there is nothing wrong with > that. We have all been there, remember? > >>> The OP has plenty of time to learn about malicious input and >>> protecting against it, right now the fundamentals are well... >>> fundamental :) >> When would you recommend he learns? When his web app is hijacked by >> gangsters in Russia and the personal details and financial records of fifty >> thousand people stolen? Protecting against malicious input *IS* >> fundamental. > > If the OP uses eval without inderstanding it and then shoots himself > in the foot, well then i can't think of a better learning experience > for him. I'll bet the next time he will read the docs first or ask on > this list before he goes off on a turkey hunt ;). > > Fear is a product of ignorance. Educate yourself and your irrational > fears shall bother you no more. > I think it's a good idea to warn the OP about the dangers of eval. If he still wants to use it, then that's his choice (and his problem). From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 14:06:34 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 18:06:34 GMT Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: <0022f1a7$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 07:38:51 -0700, rurpy wrote: > > Then, the next question is "why is it implemented that way", to which > > the answer is "because the PEP says so". > > Not at all a satisfying answer unless one believes in PEPal > infallibility. :-) Not at all. You don't have to believe that PEPs are infallible to accept the answer, you just have to understand that major changes to Python aren't made arbitrarily, they have to go through a PEP first. Even Guido himself has to write a PEP before making any major changes to the language. But PEPs aren't infallible, they can be challenged, rejected, withdrawn or made obsolete by new PEPs. > The reasons for the current behavior so far: > > 1. >> What you propose would break the property "unichr(i) always returns a >> string of length one, if it returns anything at all". > > Yes. And i don't see the problem with that. Why is that property more > desirable than the non-existent property that a Unicode literal always > produces one python character? What do you mean? Unicode literals don't always produce one character, e.g. u'abcd' is a Unicode literal with four characters. I think it's fairly self-evident that a function called uniCHR [emphasis added] should return a single character (technically a single code point). But even if you can come up with a reason for unichr() to return two or more characters, this would break code that relies on the documented promise that the length of the output of unichr() is always one. > It would only occur on a narrow build > with a unicode character outside of the bmp, exactly the condition a > unicode literal can "behave differently" by producing two python > characters. > 2. >> > But there is no reason given [in the PEP] for that behavior. >> Sure there is, right above the list: >> "Most things will behave identically in the wide and narrow worlds." >> That's the reason: scripts should work the same as much as possible in >> wide and narrow builds. > > So what else would work "differently"? unichr(n) sometimes would return one character and sometimes two; ord(c) would sometimes accept two characters and sometimes raise an exception. That's a fairly major difference. > My point was that extending > unichr/ord to work with all unicode characters reduces differences far > more often than it increase them. I don't see that at all. What differences do you think it would reduce? > 3. >>> * There is a convention in the Unicode world for >>> encoding a 32-bit code point in terms of two 16-bit code >>> points. These are known as "surrogate pairs". Python's codecs >>> will adopt this convention. >>> >>> Is a distinction made between Python and Python codecs with only the >>> latter having any knowledge of surrogate pairs? >> >> No. In the end, the Unicode type represents code units, not code >> points, i.e. half surrogates are individually addressable. Codecs need >> to adjust to that; in particular the UTF-8 and the UTF-32 codec in >> narrow builds, and the UTF-16 codec in wide builds (which didn't exist >> when the PEP was written). > > OK, so that is not a reason either. I think it is a very important reason. Python supports code points, so it has to support surrogate codes individually. Python can't tell if the pair of code points u'\ud800\udc40' represents the single character \U00010040 or a pair of code points \ud800 and \udc40. > 4. > I'll speculate a little. > If surrogate handling was added to ord/unichr, it would be the top of a > slippery slope leading to demands that other string functions also > handle surrogates. > > But this is not true -- there is a strong distinction between ord/unichr > and other string methods. The latter deal with strings of multiple > characters. But the former deals only with single characters (taking a > surrogate pair as a single unicode character.) Strictly speaking, unichr() deals with code points, not characters, although the distinction is very fine. >>> c = unichr(56384) >>> len(c) 1 >>> import unicodedata >>> unicodedata.category(c) 'Cs' Cs is the general category for "Other, Surrogate", so \udc40 is not strictly speaking a character. Nevertheless, Python treats it as one. > To reiterate, I am not advocating for any change. I simply want to > understand if there is a good reason for limiting the use of unchr/ord > on narrow builds to a subset of the unicode characters that Python > otherwise supports. So far, it seems not and that unichr/ord is a > poster child for "purity beats practicality". On the contrary, it seems pretty impractical to me for ord() to sometimes successfully accept strings of length two and sometimes to raise an exception. I would much rather see a pair of new functions, wideord() and widechr() used for converting between surrogate pairs and numbers. -- Steven From ivanko.rus at gmail.com Sat Aug 29 14:08:56 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 18:08:56 +0000 Subject: IDE for Python In-Reply-To: <7aa29e790908290214ode909c8od898918e86759daf@mail.gmail.com> Message-ID: <000e0cd20f80b36a6104724bb134@google.com> 29.08.2009 4:14 ???????????? "Thangappan.M" ???????: > Dear all, > Please suggest some good IDE for python.I am working in linux platform. > -- > Regards, > Thangappan.M You can use Eclipse + PyDev or Emacs+PythonMode . Also there are Anjuta and Code:Blocks, but they are designed mainly for C++ (but still can be used). -------------- next part -------------- An HTML attachment was scrubbed... URL: From szport at gmail.com Sat Aug 29 14:11:43 2009 From: szport at gmail.com (zaur) Date: Sat, 29 Aug 2009 11:11:43 -0700 (PDT) Subject: Is behavior of += intentional for int? References: Message-ID: On 29 ???, 20:25, "G?nther Dietrich" wrote: > Paul McGuire wrote: > >What exactly are you trying to do? > > I think, he wants to kind of dereference the list element. So that he > can write > > >>> a += 1 > > instead of > > >>> long_name_of_a_list_which_contains_data[mnemonic_pointer_name] += 1 > > Regards, > > G?nther That's right. I thought that int as object will stay the same object after += but with another integer value. My intuition said me that int object which represent integer value should behave this way. But by design python's integer behave differently. I fond that NumPy's 1-d types behaves as objects with mutable values. >>> from numpy import * >>> a=array([1]) >>> id(a) 10912544 >>> a += 1 >>> id(a) 10912544 >>> a array([2]) From rtomek at ceti.com.pl Sat Aug 29 14:18:07 2009 From: rtomek at ceti.com.pl (Tomasz Rola) Date: Sat, 29 Aug 2009 20:18:07 +0200 Subject: What python can NOT do? In-Reply-To: <00223e3f$0$2930$c3e8da3@news.astraweb.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <00223e3f$0$2930$c3e8da3@news.astraweb.com> Message-ID: On Sat, 29 Aug 2009, Steven D'Aprano wrote: > On Sat, 29 Aug 2009 05:37:34 +0200, Tomasz Rola wrote: > > > My private list of > > things that when implemented in Python would be ugly to the point of > > calling it difficult: > > > > 1. AMB operator - my very favourite. In one sentence, either language > > allows one to do it easily or one would not want to do it (in an ugly > > way). > > > > http://www.randomhacks.net/articles/2005/10/11/amb-operator > > > Fascinating, but I don't exactly see how that's actually *useful*. It > strikes me of combining all the benefits of COME FROM with the potential > performance of Bogosort, but maybe I'm being harsh. Usefullness is totally different thing, I agree. However, amb could still find some following. I guess it is more about personal taste and willingness to look for better idioms in programming. I can imagine when they introduced for and while loops, people were pointing at conditional goto as more practical (I think every control structure can be modeled with it). Id doesn't mean amb is better idiom, but it is something that could be tried - or not. One could write like this: (partially stol####copied from the above link) a = amb 1, 2, 3 b = amb 4, 5, 6 c = amb 7, 8, 9 if a*b + c != 27 : amb print a,b,c or one could write like this: for a in [1, 2, 3]: for b in [4, 5, 6]: for c in [7, 8, 9]: if a*b+c == 27 : print a,b,c break Which one would I choose? Well, amb of course. I consider it to be more readable which is, for me at least, useful. Now, try to imagine the same with ten variables. And longer lists. And some problems do not fit well into numpy (they could be non-numerical in nature). > On the other hand, it sounds rather like Prolog-like declarative > programming. I fear that, like Prolog, it risks massive performance > degradation if you don't apply the constraints in the right order. Of course, but this can be optimised. Either by hand or by a good compiler (whatever this means). Performance degradation is connected with abuse of every other programming technique, too. And besides, I believe one would sometimes trade performance for the ability to clearly express the idea behind the algorithm. Just as is the case with choosing Python rather than Java. For things I use Python for, I wouldn't use Java or C. Even though C is one of my beloved languages. If I ever used Prolog for anything, I wouldn't like to rewrite it in C or Python. I mean, languages should (in theory) be chosen and used with some consideration. > > 2. Changing the language from the inside. > > > > Everybody can change the interpreter, right? But how about doing some > > bigger, maybe even fundamental change to the language by means offered > > by the language itself? > > Like Forth. You need it in Forth, because it has a very sparse set of > language features, and everything is bootstrapped from a small set of > commands, so the ability to re-define the language as you go is (1) > necessary and (2) free. It also leads to writing code in an incredibly expressive manner. I've never done anything big in Forth. I only had a two weeks long exposure to it in times, when you loaded such things from casette recorder ;-/... But from time to time I find some interesting pieces, like a disk driver whose source would fit into a comment of one Python function :-). > But for Python, I don't know... it sounds cool, but in practice? It > sounds like the sort of thing that allows programmers to spend three > hours writing a new control structure which will save them three minutes. It really is not so. Writing something for three hours and using it only once sounds more like programming excercise, less like real life work. To write a function I need to know at least two places in my code where it would be used (well, I am oversimplifying, ok? sometimes one place is sufficient). I think reasonable people would judge language extension by similar criteria. They would possibly stay away from this as long as possible (I have such possibility from some time but I just don't touch macros, which by my own words makes me reasonable, wow :-)... or a coward...). > And of course, for all but the tiniest, one-man-band applications, > readability is important. Sure, you've created a gee-whizz control > structure which combines try, while and if into one keyword, and it > automatically does logging and threading, fantastic. But how will anyone > else be able to maintain it when you're gone? This is comparable to me creating a gee-whizz function library and using it. I cannot see a problem as long as I document (with use cases, tests etc). There is something better in this idea. Suppose I would have invented a better control structure and posted the source code here? Some would have found it amusing, others would have tried it, posted their comments, leading to improvements and further spreading. Finally - who knows - it could have found a way in to a standard. And even if not, it should still remain as a loadable extension for quite some time. > The ability to change the language is one step into a tarpit, where > everything is possible but nothing is easy, and where you spend all your > time writing language features and none of your time building the useful > functionality you actually want. I don't think this is much different from the situation when I would write string processing library (that would be used further in the program) rather than "building useful functionality" - which would be what, programming buttons :-)? For me, it looks like language elements should not be protected from my tinkering. Think about operators in Python. I can define my own "+" for some objects, which has been decided on Python's upper levels :-). In fact, as far as I remember, I have never used this feature. But knowing there is some possibility, space to grow, is good. > It sounds like something you want in a > language you use for designing languages, rather than writing > applications. Yes indeed, Lisps have been used to prototype some other languages. However, I am not sure if the boundary between a language and an app could be strictly defined. If adding new words to the language dictionary by writing a library is considered a good programming practice, then why adding a new keyword and syntax should not be considered as such? Ok, since I myself have written above I didn't use those features from very upper shelve, one could ask what is my point. The point is, if I wanted to, I could have used them. Click and go. Do anything that by my own judgement is good for code progress rather than murmuring about my code being less elegant and expressive that it could have been. I mean, if my job was beheading people, I would rather do it with sharp axe because it is more expressive and elegant than sawing their necks with piece of wood. And besides the job is better done and less boring for parties involved. So, my going after elegance is not so much whimsical, at least not from my point of view. I believe there is something more to it than just esthetics. Just in case - I am not voting for changes in Python. Quite far from this. Only expressing my opinions etc. As I have already mentioned in some other posts of mine, Python is good for few things I do and for other things I use other tools. That's it. Regards, Tomasz Rola -- ** A C programmer asked whether computer had Buddha's nature. ** ** As the answer, master did "rm -rif" on the programmer's home ** ** directory. And then the C programmer became enlightened... ** ** ** ** Tomasz Rola mailto:tomasz_rola at bigfoot.com ** From bouncyinc at gmail.com Sat Aug 29 14:38:20 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sat, 29 Aug 2009 12:38:20 -0600 Subject: What python can NOT do? In-Reply-To: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: Theoretically a microkernel could be used to do the stuff python directly couldn't do and the rest could be done once an interpreter was loaded in theory. On Fri, Aug 28, 2009 at 4:37 PM, qwe rty wrote: > i know that an interpreted language like python can't be used to make > an operating system or system drivers. > > what else can NOT be done in python? what are the limitations of the > language? > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From philip at semanchuk.com Sat Aug 29 14:46:15 2009 From: philip at semanchuk.com (Philip Semanchuk) Date: Sat, 29 Aug 2009 14:46:15 -0400 Subject: Combining C and Python programs In-Reply-To: References: Message-ID: <0BBCF0D2-789B-4FD2-B5E6-AE81C07A6273@semanchuk.com> On Aug 29, 2009, at 3:54 AM, Sortie wrote: > I want to write a program that will use ode for the physics > simulation, whose python bindings are outdated. So I'm writing > the physics engine in C and want to write the drawing code in > Python. What will be the best way of making those two programs > work together? THe physics engine won't have to run concurrently > with the drawing code. It will only return some position data so > they can be drawn. I'd look at ctypes first, as Hendrik suggested. It's pretty simple and part of the standard library. If that doesn't work for you for some reason and you're willing to use something outside of the standard library, you might find Cython useful. Good luck Philip From diogo.neves at gmail.com Sat Aug 29 14:54:09 2009 From: diogo.neves at gmail.com (Diogo Neves) Date: Sat, 29 Aug 2009 19:54:09 +0100 Subject: IDE for Python In-Reply-To: <000e0cd20f80b36a6104724bb134@google.com> References: <7aa29e790908290214ode909c8od898918e86759daf@mail.gmail.com> <000e0cd20f80b36a6104724bb134@google.com> Message-ID: Is IDLE (the editor that comes with Python) good? I'm just starting now, but it looks ok. 2009/8/29 > 29.08.2009 4:14 ???????????? "Thangappan.M" > ???????: > > Dear all, > > > > > > Please suggest some good IDE for python.I am working in linux > platform. > > > > -- > > Regards, > > Thangappan.M > > > > You can use Eclipse + PyDev or Emacs+PythonMode . Also there are Anjuta and > Code:Blocks, but they are designed mainly for C++ (but still can be used). > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 15:03:23 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 29 Aug 2009 19:03:23 GMT Subject: Is behavior of += intentional for int? References: Message-ID: <0022fef9$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: > I thought that int as object will stay the same object after += but with > another integer value. My intuition said me that int object which > represent integer value should behave this way. If it did, then you would have this behaviour: >>> n = 3 # bind the name n to the object 3 >>> saved_id = id(n) # get the id of the object >>> n += 1 # add one to the object 3 >>> assert n == 4 # confirm that it has value four >>> assert id(n) == saved_id # confirm that it is the same object >>> m = 3 # bind the name m to the object 3 >>> print m + 1 # but object 3 has been modified 5 This would be pretty disturbing behaviour, and anything but intuitive. Fortunately, Python avoids this behaviour by making ints immutable. You can't change the object 3 to have any other value, it will always have value three, and consequently n+=1 assigns a new object to n. -- Steven From nobody at nowhere.com Sat Aug 29 15:09:12 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 29 Aug 2009 20:09:12 +0100 Subject: (Simple?) Unicode Question References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> <002269cb$0$2930$c3e8da3@news.astraweb.com> Message-ID: On Sat, 29 Aug 2009 08:26:54 +0000, Steven D'Aprano wrote: > Python only needs to know when you convert the text to or from bytes. I > can do this: > >>>> s = "hello" >>>> t = "world" >>>> print(' '.join([s, t])) > hello world > > and not need to care anything about encodings. > > So long as your terminal has a sensible encoding, and you have a good > quality font, you should be able to print any string you can create. UTF-8 isn't a particularly sensible encoding for terminals. And "Unicode font" is an oxymoron. You can merge a whole bunch of fonts together and stuff them into a TTF file; that doesn't make them "a font", though. >>> I may be wrong, but I believe that's part of the idea between >>> separation of string and bytes types in Python 3.x. I believe, if you >>> are using Python 3.x, you don't need the character encoding mumbo jumbo >>> at all ;-) >> >> Nothing has changed in that regard. You still need to decode and encode >> text and for that you have to know the encoding. > > You only need to worry about encoding when you convert from bytes to > text, and visa versa. Admittedly, the most common time you need to do > that is when reading input from files, but if all your text strings are > generated by Python, and not output anywhere, you shouldn't need to care > about encodings. Why would you generate text strings and not output them anywhere? The main advantage of using Unicode internally is that you can associate encodings with the specific points where data needs to be converted to/from bytes, rather than having to carry the encoding details around the program. From nobody at nowhere.com Sat Aug 29 15:19:36 2009 From: nobody at nowhere.com (Nobody) Date: Sat, 29 Aug 2009 20:19:36 +0100 Subject: Query screen resolution? References: <7d57e7c2-39bf-4515-8642-6bcbeba0492c@u16g2000pru.googlegroups.com> <409bf880-4e4b-48f4-8cfc-ecacf262d782@v15g2000prn.googlegroups.com> Message-ID: On Fri, 28 Aug 2009 20:15:57 -0700, Warpcat wrote: >> Your question is based upon the notion that "the screen" is a meaningful >> concept. Once you move away from Windows (and systems which intentionally >> try to be like Windows), that's no longer true. > > Good points. Always something I haven't thought of. Ok so... let's > *presume* the user has a measurable screen on win\mac\linux\etc since > on any other OS they wouldn't be running the app.... If it's a GUI app, you ask the GUI toolkit which you're using. [And if it isn't a GUI app, why would the screen resolution be relevant?] From clp2 at rebertia.com Sat Aug 29 15:31:39 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sat, 29 Aug 2009 12:31:39 -0700 Subject: how to edit .wsgi file extebtions with IDLE on windows In-Reply-To: <58a021ce-3058-483d-b429-6ba4855807ac@o36g2000vbl.googlegroups.com> References: <58a021ce-3058-483d-b429-6ba4855807ac@o36g2000vbl.googlegroups.com> Message-ID: <50697b2c0908291231l75e91893lffe18bc9d46f617a@mail.gmail.com> On Sat, Aug 29, 2009 at 5:40 AM, gert wrote: > On Aug 29, 6:43?am, "Gabriel Genellina" > wrote: >> En Fri, 28 Aug 2009 15:31:31 -0300, gert escribi?: >> >> > I can't figure out how to enable the .py shell and syntax highlighting >> > for .wsgi file extensions using IDLE for windows ? >> >> That's a Windows question, not a Python one. You have to associate the >> .wsgi extension with the Python.File file type (the one used for .py >> files): >> >> D:\USERDATA\Gabriel>assoc .py >> .py=Python.File >> >> D:\USERDATA\Gabriel>assoc .wsgi=Python.File >> .wsgi=Python.File >> > > Thanks that does make it open exactly like a .py file, expect that > there is no syntax highlighting. Don't know if this is also a windows > issue or a IDLE issue ? That's an IDLE issue; it only highlights files with .py (and possibly .pyw) extensions. Cheers, Chris -- http://blog.rebertia.com From aahz at pythoncraft.com Sat Aug 29 15:33:45 2009 From: aahz at pythoncraft.com (Aahz) Date: 29 Aug 2009 12:33:45 -0700 Subject: Select column from a list References: <25185508.post@talk.nabble.com> <9fdb569a0908280228g59038ba1u30d6d5ef9d6a80ca@mail.gmail.com> Message-ID: In article , Anthra Norell wrote: >Vlastimil Brom wrote: >> 2009/8/28 hoffik : >>> >>> I'm quite new in Python and I have one question. I have a 2D matrix of >>> values stored in list (3 columns, many rows). I wonder if I can select one >>> column without having to go through the list with 'for' command. >> >> I guess, it won't be possible without an explicit or implicit loop; >> you may try: >> >>>>> from operator import itemgetter >>>>> nested_list = [[1, 2, 3], [10, 20, 30], [100, 200, 300]] >>>>> map(itemgetter(1), nested_list) >> >> [2, 20, 200] > >How about rotating the list with zip? > >>> zip (*nested_list)[1] >(2, 20, 200) That's an implicit loop, plus it consumes an O(M*N) chunk of memory for the intermediate list. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From vlastimil.brom at gmail.com Sat Aug 29 15:43:58 2009 From: vlastimil.brom at gmail.com (Vlastimil Brom) Date: Sat, 29 Aug 2009 21:43:58 +0200 Subject: break unichr instead of fix ord? In-Reply-To: References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: <9fdb569a0908291243l9c33dbeu61debb104d2c13fc@mail.gmail.com> 2009/8/29 : > On 08/28/2009 02:12 AM, "Martin v. L?wis" wrote: > > So far, it seems not and that unichr/ord > is a poster child for "purity beats practicality". > -- > http://mail.python.org/mailman/listinfo/python-list > As Mark Tolonen pointed out earlier in this thread, in Python 3 the practicality apparently beat purity in this aspect: Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> goth_urus_1 = '\U0001033f' >>> list(goth_urus_1) ['\ud800', '\udf3f'] >>> len(goth_urus_1) 2 >>> ord(goth_urus_1) 66367 >>> goth_urus_2 = chr(66367) >>> len(goth_urus_2) 2 >>> import unicodedata >>> unicodedata.name(goth_urus_1) 'GOTHIC LETTER URUS' >>> goth_urus_3 = unicodedata.lookup("GOTHIC LETTER URUS") >>> goth_urus_4 = "\N{GOTHIC LETTER URUS}" >>> goth_urus_1 == goth_urus_2 == goth_urus_3 == goth_urus_4 True >>> As for the behaviour in python 2.x, it's probably good enough, that the surrogates aren't prohibited and the eventually needed behaviour can be easily added via custom functions. vbr From nagle at animats.com Sat Aug 29 15:46:52 2009 From: nagle at animats.com (John Nagle) Date: Sat, 29 Aug 2009 12:46:52 -0700 Subject: What python can NOT do? In-Reply-To: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <4a998465$0$1637$742ec2ed@news.sonic.net> qwe rty wrote: > i know that an interpreted language like python can't be used to make > an operating system or system drivers. > > what else can NOT be done in python? what are the limitations of the > language? Speed, basically. CPython is on the slow side. This is not inherent in the language; it's an implementation problem. The Shed Skin compiler is approaching C speeds, but you have to accept some modest restrictions on run-time dynamism. Also, CPython does not use multiple processors well. In fact, multiple cores make CPython performance worse. (There's a long analysis of this that's been discussed here recently.) Personally, I consider Python to be a good language held back by too-close ties to a naive interpreter implementation and the lack of a formal standard for the language. John Nagle From ivanko.rus at gmail.com Sat Aug 29 16:08:51 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 20:08:51 +0000 Subject: Python Noob - gui module, book, annoying questions In-Reply-To: <92cc4ca1-0e0d-4355-8d9a-b4928390e619@q35g2000vbi.googlegroups.com> Message-ID: <000e0cd117da963eed04724d5ea6@google.com> 29.08.2009 2:20 ???????????? Pherdnut ???????: > I want to write cross-platform stuff. Any opinions on the best GUI > module for that? There are many options for this. For example GTK+ (pygtk), tkinter, QT. GTK+ is a little bit complicated, but you can use glade to make the GUIs. Tkinter is built-in and pretty simple (although not so feature-rich). QT - ok, I haven't used it. Personally I prefer GTK+ (using pygtk module) -------------- next part -------------- An HTML attachment was scrubbed... URL: From webcokies at yahoo.com Sat Aug 29 16:13:12 2009 From: webcokies at yahoo.com (Joni Lee) Date: Sat, 29 Aug 2009 13:13:12 -0700 (PDT) Subject: a popen command line question Message-ID: <964997.10840.qm@web36907.mail.mud.yahoo.com> Hi all, I write a small script status = os.popen('top').readlines() print status It calls the command line "top" and will print out the status. But I have to press the keyboard "q" to quit "top", then the status will be printed, otherwise it just stands by with blank. Question is. Do you know how to give "q" into my python script so that "top" is automatically quit immediately or maybe after 1s (for gathering information) Sorry the question is weird. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gert.cuykens at gmail.com Sat Aug 29 16:14:14 2009 From: gert.cuykens at gmail.com (gert) Date: Sat, 29 Aug 2009 13:14:14 -0700 (PDT) Subject: how to edit .wsgi file extebtions with IDLE on windows References: <58a021ce-3058-483d-b429-6ba4855807ac@o36g2000vbl.googlegroups.com> Message-ID: <00795942-19ae-4d0e-9259-79ae00c34fc5@f10g2000vbf.googlegroups.com> On Aug 29, 9:31?pm, Chris Rebert wrote: > On Sat, Aug 29, 2009 at 5:40 AM, gert wrote: > > On Aug 29, 6:43?am, "Gabriel Genellina" > > wrote: > >> En Fri, 28 Aug 2009 15:31:31 -0300, gert escribi?: > > >> > I can't figure out how to enable the .py shell and syntax highlighting > >> > for .wsgi file extensions using IDLE for windows ? > > >> That's a Windows question, not a Python one. You have to associate the > >> .wsgi extension with the Python.File file type (the one used for .py > >> files): > > >> D:\USERDATA\Gabriel>assoc .py > >> .py=Python.File > > >> D:\USERDATA\Gabriel>assoc .wsgi=Python.File > >> .wsgi=Python.File > > > Thanks that does make it open exactly like a .py file, expect that > > there is no syntax highlighting. Don't know if this is also a windows > > issue or a IDLE issue ? > > That's an IDLE issue; it only highlights files with .py (and possibly > .pyw) extensions. > Any chance they would make a highlight option in the menu ? From danb_83 at yahoo.com Sat Aug 29 16:25:35 2009 From: danb_83 at yahoo.com (AggieDan04) Date: Sat, 29 Aug 2009 13:25:35 -0700 (PDT) Subject: Is behavior of += intentional for int? References: Message-ID: On Aug 29, 8:08?am, Paul McGuire wrote: > On Aug 29, 7:45?am, zaur wrote: > > > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) > > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin > > Type "copyright", "credits" or "license()" for more information.>>> a=1 > > >>> x=[a] > > >>> id(a)==id(x[0]) > > True > > >>> a+=1 > > >>> a > > 2 > > >>> x[0] > > > 1 > > > I thought that += should only change the value of the int object. But > > += create new. > > Is this intentional? > > ints are immutable. ?But your logic works fine with a mutable object, > like a list: Technically, mutability isn't the issue: There's nothing enforcing that a mutable object HAS to have an __iadd__ method that returns the same object. From pogonyshev at gmx.net Sat Aug 29 16:27:03 2009 From: pogonyshev at gmx.net (Paul Pogonyshev) Date: Sat, 29 Aug 2009 23:27:03 +0300 Subject: weak reference callback Message-ID: <200908292327.03416.pogonyshev@gmx.net> Hi, Is weak reference callback called immediately after the referenced object is deleted or at arbitrary point in time after that? I.e. is it possible to see a dead reference before the callback is called? More formally, will this ever raise? callback_called = False def note_deletion (ref): callback_called = True x = ... ref = weakref.ref (x, note_deletion) ... if ref () is None and not callback_called: raise RuntimeError ("reference is dead, yet callback hasn't been called yet") Paul From sergiocharpinel at gmail.com Sat Aug 29 16:27:45 2009 From: sergiocharpinel at gmail.com (Sergio Charpinel Jr.) Date: Sat, 29 Aug 2009 17:27:45 -0300 Subject: Sqlite format string Message-ID: Hi, I have this statement cursor.execute("SELECT * from session_attribute WHERE sid=%s", ( user )) and I'm receiving this error : TypeError: not all arguments converted during string formatting What is wrong ? -- Sergio Roberto Charpinel Jr. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivanko.rus at gmail.com Sat Aug 29 16:28:26 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 20:28:26 +0000 Subject: Monitoring stdout in (more or less) real time In-Reply-To: Message-ID: <000e0cd2175497123704724da485@google.com> 29.08.2009 2:21 ???????????? Gabriel Genellina ???????: > En Sat, 29 Aug 2009 03:28:26 -0300, ivanko.rus at gmail.com> escribi?: > Hello to everyone! I am making a program that will be a GTK+ frontend to > ffmpeg. Naturally, one of the main functions is parsing ffmpeg's output. > It's pretty simple when I, for example, retrieve information about a file > (the program finishes and I read the output). But it also needs to parse > working ffmpeg's output (in order to retrieve the percentage, remaining > time, etc.). So, actually what I do is Popen ffmpeg, and connect to its > stdout. And as stdout is represented by a file object, it needs to be > read(). The problem is that read() reads until EOF is reached, which > doesn't exist while the program is running (the same goes with > communicate()). > So my question is: is there a way to retrieve the stdout without waiting > the program to finish? > You don't have to read the complete output at once - you may process it > line by line, I presume. I'd use a second thread to read the pipe and put > the lines onto a Queue object; the main thread gets lines from the Queue > when available. > -- > Gabriel Genellina > -- > http://mail.python.org/mailman/listinfo/python-list Thanks, Gabriel, but I resolved that problem in another way. thrashold in irc.freenode.net gave me the solution. What i do now is: p = Popen(["cmd","arg"],stdout=PIPE,stderr=STDOUT) fcntl.fcntl(p.stdout.fileno(), fcntl.F_SETFL, os.O_NONBLOCK) p.stdout.read() And in that way p.stdout.read() doesn't wait the program to finish, but gives me instant response. But anyway, thanks! =) -------------- next part -------------- An HTML attachment was scrubbed... URL: From ivanko.rus at gmail.com Sat Aug 29 16:31:38 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 20:31:38 +0000 Subject: IDE for python similar to visual basic In-Reply-To: <2127e0be-3b93-406f-99a7-5fe02e643b40@a39g2000pre.googlegroups.com> Message-ID: <000e0cd170f00a493904724db0ec@google.com> 29.08.2009 1:32 ???????????? Vivian Wang ???????: > On Aug 29, 6:19 am, qwe rty hkh00... at gmail.com> wrote: > > i have been searching for am IDE for python that is similar to Visual > > Basic but had no luck.shall you help me please? > You can try biform: > http://www.bilive.com/download/Setup_BiForm_V2.1_en.msi.zip > Demo: > http://www.bilive.com/demo/BiForm_EN_demo.htm > More demo:(Chinese version) > http://www.bilive.com/demo/ > BiForm is a form designer,one designed form will deploy as a PFF file. > BiReader is a runtime PFF file process engine for end-users. > Setup file above include BiForm and BiReader. > Main features: > *Python as script language,base on QT GUI library > *Visible form designer > *Internal database access framework > *Auto connect database,auto create tables > *Supports SQLite/Mssql2000/Sybase ASE,not need write diffrent script > for diffrent database at most time > *Simple deploy,simple upgrade > *Different forms can share same tables,they will auto cooperation with > other forms at runtime.If you want to deploy a new function , not need > uninstall other forms,deploy the new PFF file is enough . > -- > http://mail.python.org/mailman/listinfo/python-list You can also try Eclipse + PyDev. It's not the same as Visual Studio, and I am not sure about the GUI builder, but I think it's what you want. -------------- next part -------------- An HTML attachment was scrubbed... URL: From python.list at tim.thechases.com Sat Aug 29 17:12:06 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 29 Aug 2009 16:12:06 -0500 Subject: Sqlite format string In-Reply-To: References: Message-ID: <4A9999A6.4030804@tim.thechases.com> > I have this statement cursor.execute("SELECT * from session_attribute WHERE > sid=%s", ( user )) > and I'm receiving this error : > > TypeError: not all arguments converted during string formatting Two possibilities occur to me: 1) the 2nd parameter to execute() usually needs to be a tuple (or maybe a list), so try cursor.execute("select ...", (user, )) with the extra comma after "user". 2) More likely, check your sqlite3.paramstyle to see what sqlite is expecting (it's defined at the module-level): import sqlite3 print sqlite3.paramstyle Mine here is set to "qmark" which means that sqlite is expecting cursor.execute("... WHERE sid=?", (user,)) instead of the "format" style you're using: cursor.execute("... WHERE sid=%s", (user,)) as defined in http://www.python.org/dev/peps/pep-0249/ Hope this helps, -tkc From lists at cheimes.de Sat Aug 29 17:14:17 2009 From: lists at cheimes.de (Christian Heimes) Date: Sat, 29 Aug 2009 23:14:17 +0200 Subject: weak reference callback In-Reply-To: <200908292327.03416.pogonyshev@gmx.net> References: <200908292327.03416.pogonyshev@gmx.net> Message-ID: <4A999A29.4050108@cheimes.de> Paul Pogonyshev wrote: > Hi, > > Is weak reference callback called immediately after the referenced > object is deleted or at arbitrary point in time after that? I.e. is > it possible to see a dead reference before the callback is called? > > More formally, will this ever raise? > > callback_called = False > def note_deletion (ref): > callback_called = True > > x = ... > ref = weakref.ref (x, note_deletion) > > ... > > if ref () is None and not callback_called: > raise RuntimeError ("reference is dead, yet callback hasn't been called yet") Yes, you'll definitely see a RuntimeError because you forgot to declare callback_called as a global variable. :) Christian From pogonyshev at gmx.net Sat Aug 29 17:14:38 2009 From: pogonyshev at gmx.net (Paul Pogonyshev) Date: Sun, 30 Aug 2009 00:14:38 +0300 Subject: weak reference callback In-Reply-To: <4A999A29.4050108@cheimes.de> References: <200908292327.03416.pogonyshev@gmx.net> <4A999A29.4050108@cheimes.de> Message-ID: <200908300014.38644.pogonyshev@gmx.net> Christian Heimes wrote: > Paul Pogonyshev wrote: > > Hi, > > > > Is weak reference callback called immediately after the referenced > > object is deleted or at arbitrary point in time after that? I.e. is > > it possible to see a dead reference before the callback is called? > > > > More formally, will this ever raise? > > > > callback_called = False > > def note_deletion (ref): > > callback_called = True > > > > x = ... > > ref = weakref.ref (x, note_deletion) > > > > ... > > > > if ref () is None and not callback_called: > > raise RuntimeError ("reference is dead, yet callback hasn't been called yet") > > Yes, you'll definitely see a RuntimeError because you forgot to declare > callback_called as a global variable. :) Thanks. Any useful answers though? callback_called = False def note_deletion (ref): global callback_called callback_called = True x = ... ref = weakref.ref (x, note_deletion) ... if ref () is None and not callback_called: raise RuntimeError ("reference is dead, yet callback hasn't been called yet") Paul From gagsl-py2 at yahoo.com.ar Sat Aug 29 17:16:02 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Aug 2009 18:16:02 -0300 Subject: how to edit .wsgi file extebtions with IDLE on windows References: <58a021ce-3058-483d-b429-6ba4855807ac@o36g2000vbl.googlegroups.com> <00795942-19ae-4d0e-9259-79ae00c34fc5@f10g2000vbf.googlegroups.com> Message-ID: En Sat, 29 Aug 2009 17:14:14 -0300, gert escribi?: > On Aug 29, 9:31?pm, Chris Rebert wrote: >> On Sat, Aug 29, 2009 at 5:40 AM, gert wrote: >> > On Aug 29, 6:43?am, "Gabriel Genellina" >> > wrote: >> >> En Fri, 28 Aug 2009 15:31:31 -0300, gert >> escribi?: >> >> >> > I can't figure out how to enable the .py shell and syntax >> highlighting >> >> > for .wsgi file extensions using IDLE for windows ? >> >> >> That's a Windows question, not a Python one. You have to associate >> the >> >> .wsgi extension with the Python.File file type (the one used for .py >> >> files): >> >> >> D:\USERDATA\Gabriel>assoc .py >> >> .py=Python.File >> >> >> D:\USERDATA\Gabriel>assoc .wsgi=Python.File >> >> .wsgi=Python.File >> >> > Thanks that does make it open exactly like a .py file, expect that >> > there is no syntax highlighting. Don't know if this is also a windows >> > issue or a IDLE issue ? >> >> That's an IDLE issue; it only highlights files with .py (and possibly >> .pyw) extensions. >> > > Any chance they would make a highlight option in the menu ? Two alternatives: a) Ensure your scripts contain a shebang - no purpose on Windows, but IDLE recognizes the file as a Python file. That is, make sure the very first line is like this: #!c:\python26\python.exe (it must start with #! and contain the word "python" somewhere) b) Edit IDLE sources: - Locate the file EditorWindow.py in the idlelib package. - Add this line near the top: import _winreg - Modify function ispythonsource near line 580 as follows: def ispythonsource(self, filename): if not filename or os.path.isdir(filename): return True base, ext = os.path.splitext(os.path.basename(filename)) if os.path.normcase(ext) in (".py", ".pyw"): return True ### add these 4 lines ### with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, ext) as key: ftype = _winreg.QueryValueEx(key, None)[0] if ftype.lower() in ("python.file","python.noconfile"): return True ### end ### try: f = open(filename) line = f.readline() f.close() except IOError: return False return line.startswith('#!') and line.find('python') >= 0 -- Gabriel Genellina From ivanko.rus at gmail.com Sat Aug 29 17:44:10 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 21:44:10 +0000 Subject: Sqlite format string In-Reply-To: Message-ID: <000e0cd2142c6f325d04724eb3c7@google.com> 29.08.2009 15:40 ???????????? "Sergio Charpinel Jr." ???????: > Thanks. > Do you know if both of them works for mysql too? > 2009/8/29 ivanko.rus at gmail.com> > 29.08.2009 15:27 ???????????? "Sergio Charpinel Jr." > sergiocharpinel at gmail.com> ???????: Actually, this works for any string (it doesn't depend on anything else). So you can pass "somestring {0}".format(foo) to any function because the string will be formatted _first_ and then passed as an argument. The same goes with "somestring %s" % "foo". Both will work -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Sat Aug 29 18:23:38 2009 From: aahz at pythoncraft.com (Aahz) Date: 29 Aug 2009 15:23:38 -0700 Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4a998465$0$1637$742ec2ed@news.sonic.net> Message-ID: In article <4a998465$0$1637$742ec2ed at news.sonic.net>, John Nagle wrote: > > Personally, I consider Python to be a good language held back by >too-close ties to a naive interpreter implementation and the lack >of a formal standard for the language. Name one language under active development that has not been harmed by a formal standard. (I think C doesn't count -- there was relatively little development of C after the standards process started.) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From python.list at tim.thechases.com Sat Aug 29 18:26:38 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 29 Aug 2009 17:26:38 -0500 Subject: Sqlite format string In-Reply-To: <000e0cd2142c6f325d04724eb3c7@google.com> References: <000e0cd2142c6f325d04724eb3c7@google.com> Message-ID: <4A99AB1E.5040600@tim.thechases.com> ivanko.rus at gmail.com wrote: > 29.08.2009 15:40 ???????????? "Sergio Charpinel Jr." > ???????: >> Thanks. >> Do you know if both of them works for mysql too? > >> 2009/8/29 ivanko.rus at gmail.com> > >> 29.08.2009 15:27 ???????????? "Sergio Charpinel Jr." >> sergiocharpinel at gmail.com> ???????: > > Actually, this works for any string (it doesn't depend on anything else). > So you can pass "somestring {0}".format(foo) to any function because the > string will be formatted _first_ and then passed as an argument. The same > goes with "somestring %s" % "foo". Both will work Bad idea when assembling SQL, unless you _like_ SQL-injection attacks: sql = "select * from users where name='%s' and password='%s'" # get some values from an untrusted user: name = "administrator" password = "' or 1=1; drop table users; --" cursor.execute(sql % (name, password)) # uh-oh! This is why it's so important to use the DB API's own escaping functions. -tkc From ivanko.rus at gmail.com Sat Aug 29 18:40:46 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sat, 29 Aug 2009 22:40:46 +0000 Subject: Sqlite format string In-Reply-To: <4A99AB1E.5040600@tim.thechases.com> Message-ID: <000e0cd2142ce07bf104724f7d3b@google.com> 29.08.2009 17:26 ???????????? Tim Chase ???????: > ivanko.rus at gmail.com wrote: > 29.08.2009 15:40 ???????????? "Sergio Charpinel Jr." > sergiocharpinel at gmail.com> ???????: > Thanks. > Do you know if both of them works for mysql too? > 2009/8/29 ivanko.rus at gmail.com> > 29.08.2009 15:27 ???????????? "Sergio Charpinel Jr." > sergiocharpinel at gmail.com> ???????: > Actually, this works for any string (it doesn't depend on anything else). > So you can pass "somestring {0}".format(foo) to any function because the > string will be formatted _first_ and then passed as an argument. The same > goes with "somestring %s" % "foo". Both will work > Bad idea when assembling SQL, unless you _like_ SQL-injection attacks: > sql = "select * from users where name='%s' and password='%s'" > # get some values from an untrusted user: > name = "administrator" > password = "' or 1=1; drop table users; --" > cursor.execute(sql % (name, password)) > # uh-oh! > This is why it's so important to use the DB API's own escaping functions. > -tkc Sergio, Tim Chase is absolutely right! What you can do here is check every field separately OR you can modify the format() method to automatically do that. In the second case, you need to create your method first and then assign it to the str.format method like that: str.format = your_format_method . Note that there are NO parenthesis. For more details, look at this recipe: http://code.activestate.com/recipes/92823/ . I think it will simplify the things for you later, as every time you will call the str.format method, the values will be checked automatically. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Sat Aug 29 18:46:31 2009 From: rt8396 at gmail.com (r) Date: Sat, 29 Aug 2009 15:46:31 -0700 (PDT) Subject: An assessment of the Unicode standard Message-ID: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> I was reading the thread here... http://groups.google.com/group/comp.lang.python/browse_thread/thread/db90a9629b92aab0/b0385050b4c6c84e?hl=en&lnk=raot#b0385050b4c6c84e and it raised some fundamental philophosical questions to me about natural languages and Unicode. Which IMO * Unicode* is simply a monkey patch for this soup of multiple languages we have to deal with in programming and communication. Unicode (*puke*) seems nothing more than a brain fart of morons. And sadly it was created by CS majors who i assumed used logic and deductive reasoning but i must be wrong. Why should the larger world keep supporting such antiquated languages and character sets through Unicode? What purpose does this serve? Are we merely trying to make everyone happy? A sort of Utopian free-language-love-fest-kinda- thing? But there is a larger problem that is at the heart of Unicode itself, and it has to do with this multi-language/multi-culture world we live in. Even today in 2009 AD with all our technology and advancements we still live in a dark ages of societal communication. Of the many things that divide us such as race, color, religion, geography, blah, the most perplexing and devastating seems to be why have we not accepted a single global language for all to speak. Take for instance the Chinese language with it's thousands of characters and BS, it's more of an art than a language. Why do we need such complicated languages in this day and time. Many languages have been perfected, (although not perfect) far beyond that of Chinese language. The A-Z char set is flawless! Some may say well how can we possibly force countries/people to speak/ code in a uniform manner? Well that's simple, you just stop supporting their cryptic languages by dumping Unicode and returning to the beautiful ASCII and adopting English as the universal world language. Why English? Well because it is so widely spoken. But whatever we choose just choose one language and stick with it, perfect it, and maintain it. IMO Multiple languages are barriers to communication, collaboration, and the continuation of our future evolution as intelligent Human beings and this language multiplicity will comprise our future until it is reigned in and utterly destroyed. And i think most of you are missing how important this really is to our future. And so these problems bring me to the main subject of this thread "Unicode Sucks" Now you may say to yourself "I am not a sociologist i am a programmer, so why should i give a flying fig about natural languages or Unicode, i just accept things as they are". Well yes you could just go on accepting the status quo that is surely the easy route, but your life would be so much easier if you crusaded for change. BUT STOP!, before i go any further i want to respond to what i know will be condemnation from the sociology nuts out there. Yes multiculturalism is great, yes art is great, but if you can't see how the ability to communicate is severely damperd by multi-languages then you only *feel* with your heart but you apparently have no ability to reason with your mind intelligently. [nested thoughts] A few months ago i was watching some tear-jerking documentary called something like "Save the Languages" or "The dying languages" blah! In the documentary these two bleeding-heart-ivy-leaguers were running all over the world to document some obscure languages that were on the verge of extinction. And at one utterly amazing point in the episode they start crying and moaning for the loss of these languages like their own mother had died a horrible death. I watched all this in much horror and disbelief with jaw-dropped and i am still scared by the thought that people actually buy into this BS! Has the world gone mad? [back on track] The death of a language is as natural as the death of a flower, or a fish, or even the ever long oxidation of aluminum coke can. When a life form dies it brings life to the next generation. With languages, each death compiles upon the last and we are one step closer to the unifying language that we all so disparately need. We should herald the death of the languages like the jazz funerals of New Orleans with much happiness and fanfare for there is no reason to be sad. It's called evolution people! Ever heard of science? So ditch the useless Unicode and save us all a few keystrokes and bottles of aspirin for the persistent headaches! Simplicity is beautiful!! From exarkun at twistedmatrix.com Sat Aug 29 19:07:17 2009 From: exarkun at twistedmatrix.com (exarkun at twistedmatrix.com) Date: Sat, 29 Aug 2009 23:07:17 -0000 Subject: What python can NOT do? In-Reply-To: References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4a998465$0$1637$742ec2ed@news.sonic.net> Message-ID: <20090829230717.14429.2004501285.divmod.xquotient.10@localhost.localdomain> On 10:23 pm, aahz at pythoncraft.com wrote: >In article <4a998465$0$1637$742ec2ed at news.sonic.net>, >John Nagle wrote: >> >> Personally, I consider Python to be a good language held back by >>too-close ties to a naive interpreter implementation and the lack >>of a formal standard for the language. > >Name one language under active development that has not been harmed by >a >formal standard. (I think C doesn't count -- there was relatively >little >development of C after the standards process started.) I think you must mean "harmed by a formal standard more than it has been helped", since that's clearly the interesting thing. And it's a pretty difficult question to answer. How do you quantify the harm done to a language by a standarization process? How do you quantify the help? These are extremely difficult things to measure objectively. For my part, I will agree with John. I feel like Python's big shortcomings stem from the areas he mentioned. They're related to each other as well - the lack of a standard hampers the development of a less naive interpreter (either one based on CPython or another one). It doesn't completely prevent such development (obviously, as CPython continues to undergo development, and there are a number of alternate runtimes for Python-like languages), but there's clearly a cost associated with the fact that in order to do this development, a lot of time has to be spent figuring out what Python *is*. This is the kind of thing that a standard would help with. Jean-Paul From apt.shansen at gmail.com Sat Aug 29 19:12:26 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sat, 29 Aug 2009 16:12:26 -0700 Subject: An assessment of the Unicode standard In-Reply-To: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <7a9c25c20908291612o4f134743h84753572dd71026@mail.gmail.com> > > Unicode (*puke*) seems nothing more than a brain fart of morons. And > sadly it was created by CS majors who i assumed used logic and > deductive reasoning but i must be wrong. Why should the larger world > keep supporting such antiquated languages and character sets through > Unicode? What purpose does this serve? Are we merely trying to make > everyone happy? A sort of Utopian free-language-love-fest-kinda- > thing? > One really shouldn't consider Xah Lee a role model and seek to imitate (poorly) his rants. The Real World isn't going away just because you think we should stick our heads in the sand and pretend it's not there. There are billions of people out there who are quite happy with their language, and I'd rather keep them as a customer, thanks. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sat Aug 29 19:22:03 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 29 Aug 2009 20:22:03 -0300 Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> <9205fd44-90ec-4ce6-be2a-2f82dd99e13e@r27g2000vbn.googlegroups.com> Message-ID: En Sat, 29 Aug 2009 04:34:48 -0300, zaur escribi?: > On 29 ???, 08:37, "Gabriel Genellina" wrote: >> En Fri, 28 Aug 2009 15:25:55 -0300, zaur escribi?: >> > On 28 ???, 16:07, Bruno Desthuilliers > > 42.desthuilli... at websiteburo.invalid> wrote: >> >> zaur a ?crit : >> >> >> > Ok. Here is a use case: object initialization. >> >> >> Err... Looks like you really should read the FineManual(tm) - >> >> specifically, the parts on the __init__ method. >> >> > What are you doing if 1) classes Person and Address imported from >> > foreign module 2) __init__ method is not defined as you want? >> >> Welcome to dynamic languages! It doesn't matter *where* the class was ? >> defined. You may add new attributes to the instance (even methods to >> the class) at any time. [...4 examples...] > > I know about these ways of object initializing. What I said is about > using object's dictionary as nested scope in code block. Object > initialization is just one use case. > So we say about different things. Well, you asked how to proceed in certain cases and I showed several ways it can be done right now, without requiring a new scope. You'll have to think of another use case. Attribute lookup is explicit in Python, and that's a very good thing. If you follow the python-ideas thread posted earlier, you'll see the kind of problems an implicit attribute lookup would cause. The "with" statement is necesary (and a good thing) in Pascal, but not in Python. Zope2 departs from this explicitness: it has a construct (similar to what you propose), and I hate it profoundly every time I have to edit a DTML file - I can never tell *where* an attribute comes from. Another related "feature" is acquisition, a stack of namespaces where objects "inherit" attributes from their containers. Same thing, a complete waste of time every time I have to track a bug. Unless you can find a very compeling use case, I don't think this feature will become part of the language anytime soon... -- Gabriel Genellina From gert.cuykens at gmail.com Sat Aug 29 19:29:43 2009 From: gert.cuykens at gmail.com (gert) Date: Sat, 29 Aug 2009 16:29:43 -0700 (PDT) Subject: how to edit .wsgi file extebtions with IDLE on windows References: <58a021ce-3058-483d-b429-6ba4855807ac@o36g2000vbl.googlegroups.com> <00795942-19ae-4d0e-9259-79ae00c34fc5@f10g2000vbf.googlegroups.com> Message-ID: <00cc1c86-0100-44d2-af4b-5a5652e934c2@e18g2000vbe.googlegroups.com> On Aug 29, 11:16?pm, "Gabriel Genellina" wrote: > En Sat, 29 Aug 2009 17:14:14 -0300, gert escribi?: > > > On Aug 29, 9:31?pm, Chris Rebert wrote: > >> On Sat, Aug 29, 2009 at 5:40 AM, gert wrote: > >> > On Aug 29, 6:43?am, "Gabriel Genellina" > >> > wrote: > >> >> En Fri, 28 Aug 2009 15:31:31 -0300, gert ? > >> escribi?: > > >> >> > I can't figure out how to enable the .py shell and syntax ? > >> highlighting > >> >> > for .wsgi file extensions using IDLE for windows ? > > >> >> That's a Windows question, not a Python one. You have to associate ? > >> the > >> >> .wsgi extension with the Python.File file type (the one used for .py > >> >> files): > > >> >> D:\USERDATA\Gabriel>assoc .py > >> >> .py=Python.File > > >> >> D:\USERDATA\Gabriel>assoc .wsgi=Python.File > >> >> .wsgi=Python.File > > >> > Thanks that does make it open exactly like a .py file, expect that > >> > there is no syntax highlighting. Don't know if this is also a windows > >> > issue or a IDLE issue ? > > >> That's an IDLE issue; it only highlights files with .py (and possibly > >> .pyw) extensions. > > > Any chance they would make a highlight option in the menu ? > > Two alternatives: > > a) Ensure your scripts contain a shebang - no purpose on Windows, but IDLE ? > recognizes the file as a Python file. That is, make sure the very first ? > line is like this: > > #!c:\python26\python.exe > > (it must start with #! and contain the word "python" somewhere) > > b) Edit IDLE sources: > > - Locate the file EditorWindow.py in the idlelib package. > > - Add this line near the top: > ? ?import _winreg > > - Modify function ispythonsource near line 580 as follows: > > ? ? ?def ispythonsource(self, filename): > ? ? ? ? ?if not filename or os.path.isdir(filename): > ? ? ? ? ? ? ?return True > ? ? ? ? ?base, ext = os.path.splitext(os.path.basename(filename)) > ? ? ? ? ?if os.path.normcase(ext) in (".py", ".pyw"): > ? ? ? ? ? ? ?return True > ? ? ? ? ?### add these 4 lines ### > ? ? ? ? ?with _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, ext) as key: > ? ? ? ? ? ? ?ftype = _winreg.QueryValueEx(key, None)[0] > ? ? ? ? ? ? ?if ftype.lower() in ("python.file","python.noconfile"): > ? ? ? ? ? ? ? ? ?return True > ? ? ? ? ?### end ### > ? ? ? ? ?try: > ? ? ? ? ? ? ?f = open(filename) > ? ? ? ? ? ? ?line = f.readline() > ? ? ? ? ? ? ?f.close() > ? ? ? ? ?except IOError: > ? ? ? ? ? ? ?return False > ? ? ? ? ?return line.startswith('#!') and line.find('python') >= 0 > Thanks. Can you make a ispythonsource menu option in the next python3.x release? There are many examples of txt, xml or wsgi files having python parts in them. From cjns1989 at gmail.com Sat Aug 29 20:07:19 2009 From: cjns1989 at gmail.com (Chris Jones) Date: Sat, 29 Aug 2009 20:07:19 -0400 Subject: An assessment of the Unicode standard In-Reply-To: <7a9c25c20908291612o4f134743h84753572dd71026@mail.gmail.com> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <7a9c25c20908291612o4f134743h84753572dd71026@mail.gmail.com> Message-ID: <20090830000719.GA30241@turki.gavron.org> On Sat, Aug 29, 2009 at 07:12:26PM EDT, Stephen Hansen wrote: > > > > Unicode (*puke*) seems nothing more than a brain fart of morons. And > > sadly it was created by CS majors who i assumed used logic and > > deductive reasoning but i must be wrong. Why should the larger world > > keep supporting such antiquated languages and character sets through > > Unicode? What purpose does this serve? Are we merely trying to make > > everyone happy? A sort of Utopian free-language-love-fest-kinda- > > thing? > > > > One really shouldn't consider Xah Lee a role model and seek to imitate > (poorly) his rants. :-) CJ From rurpy at yahoo.com Sat Aug 29 20:12:24 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sat, 29 Aug 2009 17:12:24 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> <0022f1a7$0$2930$c3e8da3@news.astraweb.com> Message-ID: On 08/29/2009 12:06 PM, Steven D'Aprano wrote: [...] >> The reasons for the current behavior so far: >> >> 1. >>> What you propose would break the property "unichr(i) always returns a >>> string of length one, if it returns anything at all". >> >> Yes. And i don't see the problem with that. Why is that property more >> desirable than the non-existent property that a Unicode literal always >> produces one python character? > > What do you mean? Unicode literals don't always produce one character, > e.g. u'abcd' is a Unicode literal with four characters. I'm sorry, I should have been clearer. I meant the literal representation of a *single* unicode character. u'\u4000' which results in a string of length 1, vs u'\U00010040' which results in a string of length 2. In both case the literal represents a single unicode code point. > I think it's fairly self-evident that a function called uniCHR [emphasis > added] should return a single character (technically a single code > point). There are two concepts of characters here, the 16-bit things that encodes a character in a Python unicode string (in a narrow build Python), and a character in the sense of one of the ~2**10 unicode characters. Python has chosen to represent the latter (when outside the BMP) as a pair of surrogate characters from the former. I don't see why one would assume that CHR would mean the python 16-bit character concept rather than the full unicode character concept. In fact, rather the opposite. > But even if you can come up with a reason for unichr() to return > two or more characters, I've given a number of reasons why it should return a two character representation of a non-BMP character, one of which is that that is how Python has chosen to represent such characters internally. I won't repeat the other reasons again. I'm not sure why you think more than two characters would ever be possible. > this would break code that relies on the > documented promise that the length of the output of unichr() is always > one. Ah, OK. This is the good reason I was looking for. I did not realize (until prompted by your remark to go back and look at the early docs) that unichr had been documented to return a single character since 2.0 and that wide character support was added in 2.2. Martin v. Loewis also implied that, I now see, although the implication was too deep for me to pick up. So although it leads to a suboptimal situation, I agree that maintaining the documented behavior was necessary. [...] > I would much rather see a pair of new functions, wideord() and > widechr() used for converting between surrogate pairs and numbers. I guess if it were still 2001 and Python 2.2 was coming out I would be in favor of this too. :-) From walkraft at gmail.com Sat Aug 29 20:12:45 2009 From: walkraft at gmail.com (casebash) Date: Sat, 29 Aug 2009 17:12:45 -0700 (PDT) Subject: Determining the metaclass Message-ID: <6f69f304-3cf1-45c8-b86d-f57751bcc2ed@d15g2000prc.googlegroups.com> Hi all, I cannot determine if a class is an instance of a particular metaclass. Here is my best attempt >>> class tmp(type): ... pass ... >>> def c(metaclass=tmp): ... pass ... >>> isinstance(c, tmp) False >>> isinstance(c.__class__, tmp) False Can anyone explain why this fails? Thanks very much, Chris From rurpy at yahoo.com Sat Aug 29 20:16:30 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sat, 29 Aug 2009 17:16:30 -0700 (PDT) Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: <55a533a7-20ab-42ed-b2c7-74706d7d5451@p36g2000vbn.googlegroups.com> On 08/29/2009 01:43 PM, Vlastimil Brom wrote: > > 2009/8/29: >> >> On 08/28/2009 02:12 AM, "Martin v. L?wis" wrote: >> >> >> >> So far, it seems not and that unichr/ord >> >> is a poster child for "purity beats practicality". >> >> -- >> >> http://mail.python.org/mailman/listinfo/python-list >> >> > > > > As Mark Tolonen pointed out earlier in this thread, in Python 3 the > > practicality apparently beat purity in this aspect: > > > > Python 3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit > > (Intel)] on win32 > > Type "copyright", "credits" or "license()" for more information. > > >>>> >>>> goth_urus_1 = '\U0001033f' >>>> >>>> list(goth_urus_1) > > ['\ud800', '\udf3f'] >>>> >>>> len(goth_urus_1) > > 2 >>>> >>>> ord(goth_urus_1) > > 66367 >>>> >>>> goth_urus_2 = chr(66367) >>>> >>>> len(goth_urus_2) > > 2 >>>> >>>> import unicodedata >>>> >>>> unicodedata.name(goth_urus_1) > > 'GOTHIC LETTER URUS' >>>> >>>> goth_urus_3 = unicodedata.lookup("GOTHIC LETTER URUS") >>>> >>>> goth_urus_4 = "\N{GOTHIC LETTER URUS}" >>>> >>>> goth_urus_1 == goth_urus_2 == goth_urus_3 == goth_urus_4 > > True >>>> >>>> Yes, that certainly seems like much more sensible behavior. > > As for the behaviour in python 2.x, it's probably good enough, that > > the surrogates aren't prohibited and the eventually needed behaviour > > can be easily added via custom functions. Yes, I agree that given the current behavior is well documented and further, is fixed in python 3, it can't be changed. I would a nit though with "can be easily added via custom functions." I don't think that is a good criterion for rejection of functionality from the library because it is not sufficient; their are many functions in the library that fail that test. I think the criterion should be more like a ratio: (how often needed) / (ease of writing). [where "ease" is not just the line count but also the obviousness to someone who is not a python expert yet.] And I would also dispute that the generalized unichr/ord functions are "easily" added. When I ran into the TypeError in ord(), I thought "surrogate pairs" were something used in sex therapy. :-) It took a lot of reading and research before I was able to write a generalized ord() function. From walkraft at gmail.com Sat Aug 29 20:18:46 2009 From: walkraft at gmail.com (casebash) Date: Sat, 29 Aug 2009 17:18:46 -0700 (PDT) Subject: Why does this group have so much spam? Message-ID: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> So much of it could be removed even by simple keyword filtering. From sjmachin at lexicon.net Sat Aug 29 20:20:47 2009 From: sjmachin at lexicon.net (John Machin) Date: Sat, 29 Aug 2009 17:20:47 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: On Aug 30, 8:46?am, r wrote: > > Take for instance the Chinese language with it's thousands of > characters and BS, it's more of an art than a language. ?Why do we > need such complicated languages in this day and time. Many languages > have been perfected, (although not perfect) far beyond that of Chinese > language. The Chinese language is more widely spoken than English, is quite capable of expression in ASCII ("r tongzhi shi sha gua") and doesn't have those pesky it's/its problems. > The A-Z char set is flawless! ... for expressing the sounds of a very limited number of languages, and English is *NOT* one of those. From nyamatongwe+thunder at gmail.com Sat Aug 29 20:22:26 2009 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 30 Aug 2009 00:22:26 GMT Subject: An assessment of the Unicode standard In-Reply-To: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> r: > Unicode (*puke*) seems nothing more than a brain fart of morons. And > sadly it was created by CS majors who i assumed used logic and > deductive reasoning but i must be wrong. Why should the larger world > keep supporting such antiquated languages and character sets through > Unicode? What purpose does this serve? Are we merely trying to make > everyone happy? A sort of Utopian free-language-love-fest-kinda- > thing? Wow, I like this world you live in: all that altruism! Unicode was developed by corporations from the US left coast in order to sell their products in foreign markets at minimal cost. Neil From pavlovevidence at gmail.com Sat Aug 29 20:31:19 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sat, 29 Aug 2009 17:31:19 -0700 (PDT) Subject: Determining the metaclass References: <6f69f304-3cf1-45c8-b86d-f57751bcc2ed@d15g2000prc.googlegroups.com> Message-ID: <3e1b7e0b-e44c-4b34-9866-33aa7b33a3af@v37g2000prg.googlegroups.com> On Aug 29, 5:12?pm, casebash wrote: > Hi all, > > I cannot determine if a class is an instance of a particular > metaclass. Here is my best attempt > > >>> class tmp(type): > > ... ? ? pass > ...>>> def c(metaclass=tmp): > > ... ? ? pass > ...>>> isinstance(c, tmp) > False > >>> isinstance(c.__class__, tmp) > > False > > Can anyone explain why this fails? You're gonna kick yourself. It's because you used "def" and not "class" to define c. If you'd used "class" then then first test would have worked. Carl Banks From sccolbert at gmail.com Sat Aug 29 20:39:31 2009 From: sccolbert at gmail.com (Chris Colbert) Date: Sat, 29 Aug 2009 20:39:31 -0400 Subject: Permanently adding to the Python path in Ubuntu Message-ID: <7f014ea60908291739r70f724fbw626c32265198b5ae@mail.gmail.com> I'm having an issue with sys.path on Ubuntu. I want some of my home built packages to overshadow the system packages. Namely, I have built numpy 1.3.0 from source with atlas support, and I need it to overshadow the system numpy 1.2.1 which I had to drag along as a dependency for other stuff. I have numpy 1.3.0 installed into /usr/local/lib/python2.6/dist-packages/. The issue is that this directory is added to the path after the /usr/lib/python2.6/dist-packages/ is added, so python doesnt see my version of numpy. I have been combating this with a line in my .bashrc file: export PYTHONPATH=/usr/local/lib/python2.6/dist-packages So when I start python from the shell, everything works fine. Problems show up when python is not executed from the shell, and thus the path variable is never exported. This can occur when I have launcher in the gnome panel or i'm executing from within wing-ide. Is there a way to fix this so that the local dist-packages is added to sys.path before the system directory ALWAYS? I can do this by editing site.py but I think it's kind of bad form to do it this way. I feel there has to be a way to do this without root privileges. Any ideas? Cheers, Chris From rt8396 at gmail.com Sat Aug 29 20:40:42 2009 From: rt8396 at gmail.com (r) Date: Sat, 29 Aug 2009 17:40:42 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <1c10c974-beb6-4e71-90dd-4f23aa6c70a9@g23g2000vbr.googlegroups.com> On Aug 29, 7:20?pm, John Machin wrote: > On Aug 30, 8:46?am, r wrote: > The Chinese language is more widely spoken than English, is quite > capable of expression in ASCII ("r tongzhi shi sha gua") and doesn't > have those pesky it's/its problems. Oh yes of course it is the most widely spoken amongst Chinese people since one in every five people on this earth are Chinese. What i meant to say was that English language is more widespread outside of "normal" English speaking countries -- of course as a result of colonialism, and arguably, imperialism. ;) From rt8396 at gmail.com Sat Aug 29 21:03:12 2009 From: rt8396 at gmail.com (r) Date: Sat, 29 Aug 2009 18:03:12 -0700 (PDT) Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> Message-ID: On Aug 29, 7:18?pm, casebash wrote: > So much of it could be removed even by simple keyword filtering. A more interesting question is what morons are responding to this spam and enticing the spammers to proliferate their garbage? Do people actually see a spam like "Phallus enlargement pills" and say to themself "Alright!, just what i been looking for!". I guess i just can't understand foolishness... Yes i agree, far to much spam is getting through. From rt8396 at gmail.com Sat Aug 29 21:30:34 2009 From: rt8396 at gmail.com (r) Date: Sat, 29 Aug 2009 18:30:34 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: On Aug 29, 7:22?pm, Neil Hodgson wrote: > ? ?Wow, I like this world you live in: all that altruism! Well if i don't who will? *shrugs* > Unicode was > developed by corporations from the US left coast in order to sell their > products in foreign markets at minimal cost. So why the heck are we supporting such capitalistic implementations as Unicode. Sure we must support a winders installer but Unicode, dump it! We don't support a Python group in Chinese or French, so why this? Makes no sense to me really. Let M$ deal with it. From benjamin at python.org Sat Aug 29 21:38:50 2009 From: benjamin at python.org (Benjamin Peterson) Date: Sun, 30 Aug 2009 01:38:50 +0000 (UTC) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: Neil Hodgson gmail.com> writes: \\ > > Unicode was > developed by corporations from the US left coast in order to sell their > products in foreign markets at minimal cost. Like Sanskrit or Snowman language? From danb_83 at yahoo.com Sat Aug 29 21:40:36 2009 From: danb_83 at yahoo.com (AggieDan04) Date: Sat, 29 Aug 2009 18:40:36 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: On Aug 28, 7:05?pm, Tim Chase wrote: > qwe rty wrote: > > i know that an interpreted language like python can't be used to make > > an operating system or system drivers. > > As long as you are willing to write the OS hooks in C, you can > write the userspace device drivers in Python: Writing your OS hooks in C isn't a problem because you could write a C compiler in Python ;-) From zuo at chopin.edu.pl Sat Aug 29 22:25:45 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sun, 30 Aug 2009 04:25:45 +0200 Subject: copy construtor question In-Reply-To: <613204.64791.qm@web53105.mail.re2.yahoo.com> References: <613204.64791.qm@web53105.mail.re2.yahoo.com> Message-ID: 28-08-2009 o 20:38:30 xiaosong xia wrote: > I am trying to define a class with copy constructor as following: > ? > class test: > ???? def __init__(self, s=None): > ????????? self=s > ? > x=[1,2] > ? > y=test(x) > ? > print y.__dict__ > ? > it gives > {} > ? > The above code doesn't work. And cannot, as Chris has already written. But it is possible to customize construction of objects of your class -- using __new__(): [see: http://docs.python.org/reference/datamodel.html#object.__new__ ] import copy # in Python 2.x you must explicitly inherit from 'object' type class Test(object): "Not tested" def __new__(cls, s, way=None): if s is None: # a new object of 'Test' class return super(currentclass, cls).__new__(cls, *args) else: if way == 'alias': return s elif way == 'shallow': return copy.copy(s) elif way == 'deep': return copy.deepcopy(s) else: raise ValueError("'way' must be 'alias', " "'shallow' or 'deepcopy'") ...but in such cases as copying existing objects it is usualy better (though less romantic :-)) to use an ordinary function (e.g. simply copy.copy() or copy.deepcopy(), as Gabriel has pointed). Regards, *j -- Jan Kaliszewski (zuo) From steve at REMOVE-THIS-cybersource.com.au Sat Aug 29 22:36:49 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 02:36:49 GMT Subject: (Simple?) Unicode Question References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> <002269cb$0$2930$c3e8da3@news.astraweb.com> Message-ID: <0023693f$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 20:09:12 +0100, Nobody wrote: > On Sat, 29 Aug 2009 08:26:54 +0000, Steven D'Aprano wrote: > >> Python only needs to know when you convert the text to or from bytes. I >> can do this: >> >>>>> s = "hello" >>>>> t = "world" >>>>> print(' '.join([s, t])) >> hello world >> >> and not need to care anything about encodings. >> >> So long as your terminal has a sensible encoding, and you have a good >> quality font, you should be able to print any string you can create. > > UTF-8 isn't a particularly sensible encoding for terminals. Did I mention UTF-8? Out of curiosity, why do you say that UTF-8 isn't sensible for terminals? > And "Unicode font" is an oxymoron. You can merge a whole bunch of fonts > together and stuff them into a TTF file; that doesn't make them "a > font", though. I never mentioned "Unicode font" either. In any case, there's no reason why a skillful designer can't make a single font which covers the entire Unicode range in a consistent style. >>>> I may be wrong, but I believe that's part of the idea between >>>> separation of string and bytes types in Python 3.x. I believe, if you >>>> are using Python 3.x, you don't need the character encoding mumbo >>>> jumbo at all ;-) >>> >>> Nothing has changed in that regard. You still need to decode and >>> encode text and for that you have to know the encoding. >> >> You only need to worry about encoding when you convert from bytes to >> text, and visa versa. Admittedly, the most common time you need to do >> that is when reading input from files, but if all your text strings are >> generated by Python, and not output anywhere, you shouldn't need to >> care about encodings. > > Why would you generate text strings and not output them anywhere? Who knows? It doesn't matter -- the point is that you can if you want to. You only need to worry about encodings at input and output, therefore logically if you don't do I/O you can process strings all day long and never worry about encodings at all. > The main advantage of using Unicode internally is that you can associate > encodings with the specific points where data needs to be converted > to/from bytes, rather than having to carry the encoding details around > the program. Surely the main advantage of Unicode is that it gives you a full and consistent range of characters not limited to the 128 characters provided by ASCII? -- Steven From nyamatongwe+thunder at gmail.com Sat Aug 29 23:07:17 2009 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 30 Aug 2009 03:07:17 GMT Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: Benjamin Peterson: > Like Sanskrit or Snowman language? Sanskrit is mostly written in Devanagari these days which is also useful for selling things to people who speak Hindi and other Indian languages. Not sure if you are referring to the ? snowman character or Arctic region languages like Canadian Aboriginal syllabic writing like ????? which were added to Unicode 8 years after the initial version. I'd guess that was added from political rather than marketing motives. ? was required since it was present in Japanese character sets. Neil From cs at zip.com.au Sat Aug 29 23:24:22 2009 From: cs at zip.com.au (Cameron Simpson) Date: Sun, 30 Aug 2009 13:24:22 +1000 Subject: Sqlite format string In-Reply-To: Message-ID: <20090830032422.GA23090@cskk.homeip.net> On 29Aug2009 17:27, Sergio Charpinel Jr. wrote: | Hi, | I have this statement cursor.execute("SELECT * from session_attribute WHERE | sid=%s", ( user )) | and I'm receiving this error : | | TypeError: not all arguments converted during string formatting | | What is wrong ? This: ( user ) is not a tuple containing the element user. It's just user. This: ( user, ) is what you want. -- Cameron Simpson DoD#743 http://www.cskk.ezoshosting.com/cs/ [Alain] had been looking at his dashboard, and had not seen me, so I ran into him. - Jean Alesi on his qualifying prang at Imola '93 From half.italian at gmail.com Sat Aug 29 23:51:16 2009 From: half.italian at gmail.com (Sean DiZazzo) Date: Sat, 29 Aug 2009 20:51:16 -0700 (PDT) Subject: Permanently adding to the Python path in Ubuntu References: Message-ID: On Aug 29, 5:39?pm, Chris Colbert wrote: > I'm having an issue with sys.path on Ubuntu. I want some of my home > built packages to overshadow the system packages. Namely, I have built > numpy 1.3.0 from source with atlas support, and I need it to > overshadow the system numpy 1.2.1 which I had to drag along as a > dependency for other stuff. I have numpy 1.3.0 installed into > /usr/local/lib/python2.6/dist-packages/. The issue is that this > directory is added to the path after the > /usr/lib/python2.6/dist-packages/ is added, so python doesnt see my > version of numpy. > > I have been combating this with a line in my .bashrc file: > > export PYTHONPATH=/usr/local/lib/python2.6/dist-packages > > So when I start python from the shell, everything works fine. > > Problems show up when python is not executed from the shell, and thus > the path variable is never exported. This can occur when I have > launcher in the gnome panel or i'm executing from within wing-ide. > > Is there a way to fix this so that the local dist-packages is added to > sys.path before the system directory ALWAYS? I can do this by editing > site.py but I think it's kind of bad form to do it this way. I feel > there has to be a way to do this without root privileges. > > Any ideas? > > Cheers, > > Chris I think you can modify sys.path inside your application. Maybe this will work (at the top of your script): import sys sys.path[0] = "/usr/local/lib/python2.6/dist-packages" import numpy PS. Say hi to Steven for me! ~Sean From b1540457 at tyldd.com Sun Aug 30 00:05:24 2009 From: b1540457 at tyldd.com (Anny Mous) Date: Sun, 30 Aug 2009 14:05:24 +1000 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: r wrote: > Of the many > things that divide us such as race, color, religion, geography, blah, > the most perplexing and devastating seems to be why have we not > accepted a single global language for all to speak. I agree 1000% and obviously we should make Klingon that global language. Or possibly the Black Tongue of the Mordor Orcs, which is much better for cursing. I haven't decided yet. > Take for instance the Chinese language with it's thousands of > characters and BS, it's more of an art than a language. Why do we > need such complicated languages in this day and time. Many languages > have been perfected, (although not perfect) far beyond that of Chinese > language. The A-Z char set is flawless! How do we distinguish resume from r?sum? without accents? Even when we succeed in banning all languages that can't be written using A-Z, what do we do about the vast number of legacy documents? How do we write about obsolete English letters like ? and ? without Unicode? How do we write mathematical and scientific documents without characters like ? ? ? ? and ? ? What do we use to replace typographic symbols and dingbats like ? without Unicode? > Some may say well how can we possibly force countries/people to speak/ > code in a uniform manner? Well that's simple, you just stop supporting > their cryptic languages by dumping Unicode and returning to the > beautiful ASCII and adopting English as the universal world language. > Why English? Well because it is so widely spoken. World population: 6.7 billion Number of native Mandarin speakers: 873 million Number of native Hindi speakers: 370 million Number of native Spanish speakers: 350 million Number of native English speakers: 340 million Total number of Mandarin speakers: 1051 million Total number of English speakers: 510 million http://www.vistawide.com/languages/top_30_languages.htm Whichever way you look at it, we should all convert to Mandarin, not English. Looks like we still need Unicode. Besides, given that the US would be bankrupt if not for Chinese loans, do you really want to upset them by suggesting their language sucks? > But whatever we > choose just choose one language and stick with it, perfect it, and > maintain it. Just ask the Academie Francaise how well that works! Why stop with A-Z? We can improve on 26 letters. In the first year we should replace the soft 'c' with 's'. Any sivilized language will sertainly be better off with this change. The hard 'c' will be dropped in favour of 'k', which will klear up much konfusion and allow one key less on keyboards. In the sekond year I expect publik enthusiasm to grow, allowing us to replace the troublesome 'ph' with 'f', which will make words like 'fotograf' twenty persent shorter. In the third year, publik akseptanse of the new spelling kan be expekted to permit more komplikated changes. We will enkourage the removal of double leters which have always ben a deterent to akurate speling. Also, al wil agre that the horible mes of the silent 'e' is disgrasful. By the fourth yer, peopl wil be reseptiv to replasing 'th' with 'z' and 'w' with 'v'. Zis vil be a grat improvment. During ze fifz yer, ze unesesary 'o' kan be dropd from vords kontaining 'ou' and similar changes vud of kors be aplid to ozer kombinations of leters. After zis fifz yer, ve vil hav a reli sensibl riten styl. Zer vil be no mor trubls or difikultis and everivun vil find it ezi to understand ech ozer. ZE DREM VIL FINALI COM TRU! > IMO Multiple languages are barriers to communication, collaboration, > and the continuation of our future evolution as intelligent Human > beings and this language multiplicity will comprise our future until > it is reigned in and utterly destroyed. Yes, because language differences have utterly destroyed us so many times in the past! Have you thought about the difference between China, with one culture and one spoken language for thousands of years, and Europe, with dozens of competing cultures, competing governments, and alternate languages for just as long? If multiple languages are so harmful, why was it the British, French, Japanese, Russians, Germans, Italians, Austrians, Hungarians and Americans who were occupying China during the Opium Wars and the Boxer Rebellion, instead of the other way around? Strength comes from diversity, not monoculture. From kennyken747 at gmail.com Sun Aug 30 00:14:59 2009 From: kennyken747 at gmail.com (kennyken747) Date: Sat, 29 Aug 2009 21:14:59 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: <604b21ef-a3ad-4da8-92f5-c1d22345b4d7@p15g2000vbl.googlegroups.com> On Aug 29, 6:16?am, paul wrote: > Deep_Feelings schrieb:> python got relatively fewer numbers of developers than other high > > level languages like .NET , java .. etc ?why ? > > Besides the marketing argument, python never had a "hype". > > Both PHP and ruby(Rails to be precise) got widespread because they could > ? at one point do "one" thing better than the competition. From there > on, they had more ressources (developer time) and grew fast and beyond > the original problem domain. Now you can write GUI apps in PHP, great! > > cheers > ? Paul You guys can say anything you'd like it to be in this thread, but the actual reason comes down to 1. No marketing. Seriously, if Microsoft was pushing Python it would obviously be a lot bigger in terms of developers. 2. No certification. Millions go to college to get degrees in computer related study. Do the math. Also, really guys? This crap about speed? People have been saying this for years, and yet they still don't realize that there are plenty solutions to take care of that one problem. Just be happy that you've stumbled upon Python, just because it's not the most widespread language in the world certainly doesn't mean it's not a worthy language. Quite the opposite. From cjns1989 at gmail.com Sun Aug 30 00:22:00 2009 From: cjns1989 at gmail.com (Chris Jones) Date: Sun, 30 Aug 2009 00:22:00 -0400 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: <20090830042200.GC30241@turki.gavron.org> On Sat, Aug 29, 2009 at 11:07:17PM EDT, Neil Hodgson wrote: > Benjamin Peterson: > > Like Sanskrit or Snowman language? > Sanskrit is mostly written in Devanagari these days which is also > useful for selling things to people who speak Hindi and other Indian > languages. Is the implication that the principal usefulness of such languages as Hindi and "other Indian languages" is us selling "things" to them..? I am not from these climes but all the same, I do find you tone of voice rather offensive, considering that you are referring to a culture that's about 3000 years older and 3000 richer than ours and certainly deserves our respect. Maybe you didn't notice, but our plants shut down many years ago.. They are selling _us_ their wares. > Not sure if you are referring to the snowman character or Arctic > region languages like Canadian Aboriginal syllabic writing like ????? > which were added to Unicode 8 years after the initial version. I'd > guess that was added from political rather than marketing motives. ? > was required since it was present in Japanese character sets. Oh.. so.. now Unicode is not only about marketing.. there is also a political "aspect".. polytonic Greek, Runic, Shavian, Glagolitic, Carian, Phoenician, Lydian, Cuneiform, not to mention Mathematical symbols, Braille, Domino Tiles, the IPA..? What was I thinking..? Nothing personal, I assure you.. maybe I misunderstood what you were saying. In any event, you shouldn't feed the troll, even if he's teething. CJ From cmpython at gmail.com Sun Aug 30 00:45:19 2009 From: cmpython at gmail.com (Che M) Date: Sat, 29 Aug 2009 21:45:19 -0700 (PDT) Subject: IDE for python similar to visual basic References: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> Message-ID: <3d91c968-bd36-45b9-8ae0-3af8e855605e@o35g2000vbi.googlegroups.com> On Aug 28, 6:19?pm, qwe rty wrote: > i have been searching for am IDE for python that is similar to Visual > Basic but had no luck.shall you help me please? Boa Constructor. IDE/visual GUI-builder/sizer support, lots of other goodies. Not actively maintained, though, and some issues on Linux, in my experience. But I like it a lot. From cmpython at gmail.com Sun Aug 30 00:47:10 2009 From: cmpython at gmail.com (Che M) Date: Sat, 29 Aug 2009 21:47:10 -0700 (PDT) Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> Message-ID: <62177729-0079-4cfc-bdf6-e31ebd3e883b@z28g2000vbl.googlegroups.com> On Aug 28, 6:37?pm, qwe rty wrote: > i know that an interpreted language like python can't be used to make > an operating system or system drivers. > > what else can NOT be done in python? what are the limitations of the > language? Now that you have some good answers, may I ask what what your reason was for posting this question? From cmpython at gmail.com Sun Aug 30 00:51:13 2009 From: cmpython at gmail.com (Che M) Date: Sat, 29 Aug 2009 21:51:13 -0700 (PDT) Subject: Python Noob - gui module, book, annoying questions References: <92cc4ca1-0e0d-4355-8d9a-b4928390e619@q35g2000vbi.googlegroups.com> Message-ID: On Aug 29, 3:20?am, Pherdnut wrote: > I want to write cross-platform stuff. Any opinions on the best GUI > module for that? > > I like a good juicy, but concise book for reading on my commute > downtown. I was thinking of checking Python in a Nutshell. Good? Bad? > Better? > > Is 3.0+ more object based? I'm actually an FED and one of the things I > love about JS is the consistency of the language. I love Python 2.6 so > far so I'm not knocking it. But I'm not really taking advantage of the > non-core libraries as much right now anyway since I'm learning it. > > What do you guys like in Reg Ex books/sites? I'd like to become more > fluent in some of the less commonly used stuff. Also wxPython. It's cross platform, but it does require occasional platform-dependent tweaks, since it mostly uses native controls and sometimes the native controls' requirements are different. You might want to consider that it's going to be some time before the 3rd party libraries catch up to Python 3. I'd recommend 2.5 or 2.6 for learning now if you plan on using them. From torriem at gmail.com Sun Aug 30 00:52:54 2009 From: torriem at gmail.com (Michael Torrie) Date: Sat, 29 Aug 2009 22:52:54 -0600 Subject: What python can NOT do? In-Reply-To: References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4A9870D4.8070800@tim.thechases.com> Message-ID: <4A9A05A6.4080803@gmail.com> qwe rty wrote: > On Aug 29, 5:11 am, Nobody wrote: >> On Fri, 28 Aug 2009 17:26:06 -0700, qwe rty wrote: >>> if you don't know the answer please don't reply >> If you don't understand the question, don't post it in the first place. > > don't be so angry ,not good for your health You forgot your smiley emoticon! Since everyone else is posting in a light-hearted manner (not "angry" as you say), I choose to read your post in this light as well. What Nobody was really trying to say, is ask your question in a better way and you'll get a better answer. From dieter at handshake.de Sun Aug 30 00:54:21 2009 From: dieter at handshake.de (Dieter Maurer) Date: 30 Aug 2009 06:54:21 +0200 Subject: break unichr instead of fix ord? In-Reply-To: <4a979172$0$11759$9b622d9e@news.freenet.de> References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: "Martin v. L?wis" writes on Fri, 28 Aug 2009 10:12:34 +0200: > > The PEP says: > > * unichr(i) for 0 <= i < 2**16 (0x10000) always returns a > > length-one string. > > > > * unichr(i) for 2**16 <= i <= TOPCHAR will return a > > length-one string on wide Python builds. On narrow > > builds it will raise ValueError. > > and > > * ord() is always the inverse of unichr() > > > > which of course we know; that is the current behavior. But > > there is no reason given for that behavior. > > Sure there is, right above the list: > > "Most things will behave identically in the wide and narrow worlds." > > That's the reason: scripts should work the same as much as possible > in wide and narrow builds. > > What you propose would break the property "unichr(i) always returns > a string of length one, if it returns anything at all". But getting a "ValueError" in some builds (and not in others) is rather worse than getting unicode strings of different length.... > > 1) Should surrogate pairs be disallowed on narrow builds? > > That appears to have been answered in the negative and is > > not relevant to my question. > > It is, as it does lead to inconsistencies between wide and narrow > builds. OTOH, it also allows the same source code to work on both > versions, so it also preserves the uniformity in a different way. Do you not have the inconsistencies in any case? ... "ValueError" in some builds and not in others ... From bcb at undisclosedlocation.net Sun Aug 30 01:00:54 2009 From: bcb at undisclosedlocation.net (Bruce C. Baker) Date: Sun, 30 Aug 2009 00:00:54 -0500 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> Message-ID: <7Hnmm.176524$zq1.39243@newsfe22.iad> "casebash" wrote in message news:7294bf8b-9819-4b6d-92b2-afc1c8042a06 at x6g2000prc.googlegroups.com... > So much of it could be removed even by simple keyword filtering. Assuming this is a serious question: 1. comp.lang.python has relatively little spam, compared to others. 2. The spam posters aren't looking for responses within the individual NGs, they're just hoping you'll click through to the link within the post. It's a version of "fire and forget" 3. Simple keyword filtering /by whom/? There is no central NG governing authority. The best response is to ignore[1] the spam posts; they'll eventually expire and disappear from your newsreader. [1] Although if they're egregiously stupid, you may find yourself mocking the OP. Realize that as witty and urbane as your response may be, the OP ain't listening. :-) From nagle at animats.com Sun Aug 30 01:14:55 2009 From: nagle at animats.com (John Nagle) Date: Sat, 29 Aug 2009 22:14:55 -0700 Subject: An assessment of the Unicode standard In-Reply-To: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <4a9a0988$0$1669$742ec2ed@news.sonic.net> r wrote: > I was reading the thread here... > http://groups.google.com/group/comp.lang.python/browse_thread/thread/db90a9629b92aab0/b0385050b4c6c84e?hl=en&lnk=raot#b0385050b4c6c84e > > and it raised some fundamental philophosical questions Rant ignored. Actually, Python 3.x seems finally to have character sets right. There's "bytes", for uninterpreted binary data, Unicode, and proper ASCII, 0..127. Within Python, we finally got rid of "upper code pages". (I wish the HTML standards people would do the same. HTML 5 should have been ASCII only (with the "&" escapes if desired) or Unicode. No "Latin-1", no upper code pages, no JIS, etc.) > > [nested thoughts] > A few months ago i was watching some tear-jerking documentary called > something like "Save the Languages" or "The dying languages" blah! It may be a bit much that Unicode supports Cretan Linear B. John Nagle From tjreedy at udel.edu Sun Aug 30 01:26:55 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Aug 2009 01:26:55 -0400 Subject: An assessment of the Unicode standard In-Reply-To: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: r wrote: > natural languages and Unicode. Which IMO * Unicode* is simply a monkey > patch for this soup of multiple languages we have to deal with in > programming and communication. A somewhat fair charactierization. [snip] > everyone happy? A sort of Utopian free-language-love-fest-kinda- > thing? Not utopian, but pragmatically political. Before unicode, and still today, we had and have multiple codes. Multiple ascii extenstions for European languages and even multiple codes just for Japanese. To get people in the major computing countries, including Japan, to agree to eventually replace their national codes with one worldwide code, some kludgy compromises were made. > language. The A-Z char set is flawless! Hardly. There are too few characters. A basic set should have at least 50. The international phonetic alphabet (IPA) has about 150. Here is a true Utopian proposal for you (from a non-CS major ;-): develop an extended IPA 256-character set with just a few control chars (rather than 32) and punctuation and other markers. Then develop dictionaries to translate texts in every languange and char set into and back out of this universal character set. Fat chance of approval, even if techical issues were resolved. > Some may say well how can we possibly force countries/people to speak/ > code in a uniform manner? Well that's simple, you just stop supporting > their cryptic languages by dumping Unicode and returning to the > beautiful ASCII But most everyone outside the US was not using ascii precisely because it did not support their language. Get over the imperfections of unicode. It improves on the prior status quo. Terry Jan Reedy From steve at lonetwin.net Sun Aug 30 01:28:50 2009 From: steve at lonetwin.net (steve) Date: Sun, 30 Aug 2009 10:58:50 +0530 Subject: An assessment of the Unicode standard In-Reply-To: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <4A9A0E12.9040308@lonetwin.net> On 08/30/2009 04:16 AM, r wrote: > I was reading the thread here... > http://groups.google.com/group/comp.lang.python/browse_thread/thread/db90a9629b92aab0/b0385050b4c6c84e?hl=en&lnk=raot#b0385050b4c6c84e > ... > ... > It's called evolution people! Ever heard of science? So ditch the > useless Unicode and save us all a few keystrokes and bottles of > aspirin for the persistent headaches! Simplicity is beautiful!! You are right ! In the same vein, we should all also standardize on using the Java language for programming, after all /everybody/ writes code in Java. cheers, - steve -- random non tech spiel: http://lonetwin.blogspot.com/ tech randomness: http://lonehacks.blogspot.com/ what i'm stumbling into: http://lonetwin.stumbleupon.com/ From tjreedy at udel.edu Sun Aug 30 01:37:37 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Aug 2009 01:37:37 -0400 Subject: What python can NOT do? In-Reply-To: <20090829230717.14429.2004501285.divmod.xquotient.10@localhost.localdomain> References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4a998465$0$1637$742ec2ed@news.sonic.net> <20090829230717.14429.2004501285.divmod.xquotient.10@localhost.localdomain> Message-ID: exarkun at twistedmatrix.com wrote: > For my part, I will agree with John. I feel like Python's big > shortcomings stem from the areas he mentioned. They're related to each > other as well - the lack of a standard hampers the development of a less > naive interpreter (either one based on CPython or another one). The reference manual is *intended* to define the 'standard' Python language. > It > doesn't completely prevent such development (obviously, as CPython > continues to undergo development, and there are a number of alternate > runtimes for Python-like languages), but there's clearly a cost > associated with the fact that in order to do this development, a lot of > time has to be spent figuring out what Python *is*. This is the kind of > thing that a standard would help with. Such developers occasionally raise questions about ambiguities in the ref manual on the pydev list. This is part of the editing process. There is an effort underway to separate the CPython test suite into two parts: test of standard Python behavior, which all implementations should pass, and tests of the CPython implementation, which other implementations need not pass. It will move as fast as volunteer effort moves it. tjr From steve at REMOVE-THIS-cybersource.com.au Sun Aug 30 01:46:12 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 05:46:12 GMT Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: <002395a3$0$2930$c3e8da3@news.astraweb.com> On Sun, 30 Aug 2009 03:07:17 +0000, Neil Hodgson wrote: > Not sure if you are referring to the ? snowman character or Arctic > region languages like Canadian Aboriginal syllabic writing like ????? > which were added to Unicode 8 years after the initial version. I'd guess > that was added from political rather than marketing motives. ? was > required since it was present in Japanese character sets. If I recall correctly, the snowman was specifically added at the request of Japanese television producers, because it is a standard glyph used for representing snow when showing the weather on TV. Unicode's stated aim is to have a single universal standard for all characters needed for communication. From the Unicode Consortium: [quote] What is Unicode? Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language. ... Even for a single language like English no single encoding was adequate for all the letters, punctuation, and technical symbols in common use. These encoding systems also conflict with one another. That is, two encodings can use the same number for two different characters, or use different numbers for the same character. Any given computer (especially servers) needs to support many different encodings; yet whenever data is passed between different encodings or platforms, that data always runs the risk of corruption. Unicode is changing all that! Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language. [end quote] And from the FAQs: [quote] Unicode covers all the characters for all the writing systems of the world, modern and ancient. It also includes technical symbols, punctuations, and many other characters used in writing text. [end quote] It's not just about supporting languages used by foreigners too stupid to speak English (sarcasm!). It's about supporting business users who want a standard way of referring to dingbats and pictographs, historians who need to deal with ancient writings and obsolete characters, scientists and mathematicians who want to use mathematical symbols, editors and book publishers who want to use their own typographic symbols, including Braille, musical symbols, and even TV producers who want to include snowmen on their weather charts. The Unicode system replaces dozens of incompatible, clashing systems with a single universal, extensible system. Why would anyone want to go back to the Bad Old Days where you couldn't transfer data from one OS to another, or even from one application to another, without quote marks turning into mathematical symbols or boxes? -- Steven From steve at REMOVE-THIS-cybersource.com.au Sun Aug 30 01:52:48 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 05:52:48 GMT Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <4a9a0988$0$1669$742ec2ed@news.sonic.net> Message-ID: <0023972f$0$2930$c3e8da3@news.astraweb.com> On Sat, 29 Aug 2009 22:14:55 -0700, John Nagle wrote: > It may be a bit much that Unicode supports Cretan Linear B. Thousands of historians who need to discuss Linear B would disagree. Well, hundreds. There are tens of thousands of characters available. If there's room for chess pieces, dingbats with drop shadows and numbers inside circles, there's room for actual characters from real (if extinct) languages. -- Steven From martin at v.loewis.de Sun Aug 30 01:58:39 2009 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 30 Aug 2009 07:58:39 +0200 Subject: break unichr instead of fix ord? In-Reply-To: References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: <4A9A150F.6010503@v.loewis.de> > To reiterate, I am not advocating for any change. I > simply want to understand if there is a good reason > for limiting the use of unchr/ord on narrow builds to > a subset of the unicode characters that Python otherwise > supports. So far, it seems not and that unichr/ord > is a poster child for "purity beats practicality". I think that's actually the case. I went back to the discussions, and found that early 2.2 alpha releases did return two-byte strings from unichr, and that this was changed because Marc-Andre Lemburg insisted. Here are a few relevant messages from the archives (search for unichr) http://mail.python.org/pipermail/python-dev/2001-June/015649.html http://mail.python.org/pipermail/python-dev/2001-July/015662.html http://mail.python.org/pipermail/python-dev/2001-July/016110.html http://mail.python.org/pipermail/python-dev/2001-July/016153.html http://mail.python.org/pipermail/python-dev/2001-July/016155.html http://mail.python.org/pipermail/python-dev/2001-July/016186.html Eventually, in r28142, MAL changed it to give it its current state. Regards, Martin From nyamatongwe+thunder at gmail.com Sun Aug 30 02:17:14 2009 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 30 Aug 2009 06:17:14 GMT Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: Chris Jones: > Is the implication that the principal usefulness of such languages as > Hindi and "other Indian languages" is us selling "things" to them..? Unicode was developed by a group of US corporations: Xerox, Apple, Sun, Microsoft, ... The main motivation was to avoid dealing with multiple character set encodings since this was difficult, time consuming and expensive. > I > am not from these climes but all the same, I do find you tone of voice > rather offensive, considering that you are referring to a culture that's > about 3000 years older and 3000 richer than ours and certainly deserves > our respect. Eh? Was Unicode developed in India? China? What precisely is direspectful here? Is there a significant population that regards Unicode as their 'holy patrimony' that will suffer distress due to my post? > Maybe you didn't notice, but our plants shut down many years ago.. They > are selling _us_ their wares. Maybe your plants shut down but some of the plants I have worked at (such as the steelworks at Port Kembla) are still successfully exporting to Asia. Neil From steve at REMOVE-THIS-cybersource.com.au Sun Aug 30 02:27:32 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 06:27:32 GMT Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: <00239f52$0$2930$c3e8da3@news.astraweb.com> On Sun, 30 Aug 2009 00:22:00 -0400, Chris Jones wrote: > On Sat, Aug 29, 2009 at 11:07:17PM EDT, Neil Hodgson wrote: >> Benjamin Peterson: > >> > Like Sanskrit or Snowman language? > >> Sanskrit is mostly written in Devanagari these days which is also >> useful for selling things to people who speak Hindi and other Indian >> languages. > > Is the implication that the principal usefulness of such languages as > Hindi and "other Indian languages" is us selling "things" to them..? I > am not from these climes but all the same, I do find you tone of voice > rather offensive, I think Neil's point is that Unicode has succeeded in the wider world, outside of academic circles, because of the commercial need to communicate between cultures using different character sets. I suppose he could have worded it better, but fundamentally he's right: without the commercial need to trade across the world (information as well as physical goods) I doubt Unicode would be anything more than an interesting curiosity of use only to a few academics and linguists. > considering that you are referring to a culture that's > about 3000 years older and 3000 richer than ours and certainly deserves > our respect. Older, certainly, but richer? There's a reason that Indians come to the West rather than Westerners going to India. As Terry Pratchet has written, age is not linked to wisdom -- just because somebody is old, doesn't mean they're wise, perhaps they've just been stupid for a very long time. The same goes for cultures: old doesn't mean better. Indian culture has been responsible for many wonderful things over the millennia, but the cast system is not one of them, and any culture which glorified sati (suttee) as an act of piety is not one we should look up to. Sati was probably rare even at the height of it's popularity, and vanishingly rare now, and arguably could even be defended as the right of an adult to end their own life when they see fit, but dowry-burning is outright murder and is sadly very common across the Indian sub-continent: some estimates suggest that in the mid-1990s there were nearly 6000 such murders a year in India. If we are to be truly non-racist, we must recognise that the West does not have a monopoly on wickedness, ignorance, spite and sheer awfulness. In any case, I'm not sure we should be talking about Indian culture in the singular -- India is about as large as Western Europe, significantly more varied, and the culture has changed over time. The India which treated the Karma Sutra as a holy book is hardly the same India where people literally rioted in the street because Richard Gere gave the actress Shilpa Shetty a couple of rather theatrical and silly kisses on the cheek. -- Steven From szport at gmail.com Sun Aug 30 03:15:41 2009 From: szport at gmail.com (zaur) Date: Sun, 30 Aug 2009 00:15:41 -0700 (PDT) Subject: Object's nesting scope References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> <9205fd44-90ec-4ce6-be2a-2f82dd99e13e@r27g2000vbn.googlegroups.com> Message-ID: <109d0956-0675-4c12-94c4-1cd54d6016b3@33g2000vbe.googlegroups.com> On 30 ???, 03:22, "Gabriel Genellina" wrote: > En Sat, 29 Aug 2009 04:34:48 -0300, zaur escribi?: > > > > > On 29 ???, 08:37, "Gabriel Genellina" wrote: > >> En Fri, 28 Aug 2009 15:25:55 -0300, zaur escribi?: > >> > On 28 ???, 16:07, Bruno Desthuilliers >> > 42.desthuilli... at websiteburo.invalid> wrote: > >> >> zaur a ?crit : > > >> >> > Ok. Here is a use case: object initialization. > > >> >> Err... Looks like you really should read the FineManual(tm) - > >> >> specifically, the parts on the __init__ method. > > >> > What are you doing if 1) classes Person and Address imported from > >> > foreign module 2) __init__ method is not defined as you want? > > >> Welcome to dynamic languages! It doesn't matter *where* the class was ? > >> defined. You may add new attributes to the instance (even methods to ? > >> the class) at any time. [...4 examples...] > > > I know about these ways of object initializing. What I said is about > > using object's dictionary as nested scope in code block. Object > > initialization is just one use case. > > So we say about different things. > > Well, you asked how to proceed in certain cases and I showed several ways ? > it can be done right now, without requiring a new scope. You'll have to ? > think of another use case. > > Attribute lookup is explicit in Python, and that's a very good thing. If ? > you follow the python-ideas thread posted earlier, you'll see the kind of ? > problems an implicit attribute lookup would cause. The "with" statement is ? > necesary (and a good thing) in Pascal, but not in Python. > > Zope2 departs from this explicitness: it has a construct ? > (similar to what you propose), and I hate it profoundly every time I have ? > to edit a DTML file - I can never tell *where* an attribute comes from. ? > Another related "feature" is acquisition, a stack of namespaces where ? > objects "inherit" attributes from their containers. Same thing, a complete ? > waste of time every time I have to track a bug. > > Unless you can find a very compeling use case, I don't think this feature ? > will become part of the language anytime soon... > > -- > Gabriel Genellina The same can be said about multiple inheritance. However, multiple inheritance is a powerful tool in the hands of someone who can properly and effectively use it. From code at pizzashack.org Sun Aug 30 03:33:05 2009 From: code at pizzashack.org (Derek Martin) Date: Sun, 30 Aug 2009 02:33:05 -0500 Subject: Is behavior of += intentional for int? In-Reply-To: <0022fef9$0$2930$c3e8da3@news.astraweb.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: <20090830073305.GN20434@dragontoe.org> On Sat, Aug 29, 2009 at 07:03:23PM +0000, Steven D'Aprano wrote: > On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: > > > I thought that int as object will stay the same object after += but with > > another integer value. My intuition said me that int object which > > represent integer value should behave this way. > > If it did, then you would have this behaviour: No, you wouldn't; the behavior you described is completely different from, and incompatible with, what zaur wrote. He's saying that instead of thinking the integer value of 3 itself being the object, he expected Python's object model would behave as though the entity m is the object, and that object exists to contain an integer value. In that case, m is always m, but it has whatever integer value it is told to hold at any point in time. The self-referential addition would access the value of m, add the operand, and store the result back in the same object as the object's value. This is not the way Python works, but he's saying this is the intuitive behavior. I happen to agree, and argued at length with you and others about that very thing months ago, when some other third party posted with that exact same confusion. By contrast, your description maintains the concept of numerical value as object that Python uses, and completely misses the point. I did find the description you gave to be highly enlightening though... It highlighted perfectly, I think, exactly why it is that Python's behavior regarding numerical values as objects is *not* intuitive. Of course, intuition is highly subjective. I believe it boils down to this: People expect that objects they create are mutable. At least, unless they specify otherwise. It is so in some other programming languages which people may be likely to be familiar with (if they are not taking their first forray into the world of computing by learning Python), and even "real world" objects are essentially always mutable. If you have a 2002 Buick LeSabre, it has a number of attributes, including its length, which might be 8.5 feet, for instance. However, this is not fixed: by adding modified body parts, or as an extreme example by sawing off the trunk of the car, the length and indeed the object itself has been changed. However, despite having been modified, it is at least in some sense still the same object: it is still a 2002 Buick LeSabre, and it still has the same *identity* (the same VIN number). It's the same object, but its value(s) changed. [Not that it matters, but I do not own such a car. :)] Numbers are fundamentally different from objects. The number 3 is a symbol of the idea of the existence of three countable objects. It can not be changed (though it can be renamed, if you so choose -- just don't expect most people to know what you're talking about). It is unintuitive that 3 is an object; it is rather what we use to describe objects -- the value of the object. It is an abstract concept, and as such it is not an object at all. You cannot hear 3, taste 3, nor smell 3. You can neither see nor touch 3, though you can certainly see 3 *objects* if they are present, and you can certainly see the symbol '3' that we use to represent that idea... but you can not see three itself, because there is no such object. The only way to see three is to envision 3 of some object. The number 3 does not have a value; it IS a value (it is the symbolic representation of the value of three). To say that 3 is an object that has a value is a bit like saying the length of a car is an object that itself has a length. It just doesn't compute. THAT is why Python's behavior with regard to numerical objects is not intuitive, and frankly bizzare to me, and I dare say to others who find it so. Yes, that's right. BIZZARE. Of course, none of this is real. In the end, it's all just a bunch of wires that either have current or don't. It's only how *WE* organize and think about that current that gives it any meaning. So you're free to think about it any way you like. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From milesck at umich.edu Sun Aug 30 03:38:20 2009 From: milesck at umich.edu (Miles Kaufmann) Date: Sun, 30 Aug 2009 00:38:20 -0700 Subject: Why does this group have so much spam? In-Reply-To: <7Hnmm.176524$zq1.39243@newsfe22.iad> References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7Hnmm.176524$zq1.39243@newsfe22.iad> Message-ID: <5C6A9174-FE24-433F-8508-03FE8A4DE9D9@umich.edu> > "casebash" wrote in message > news:7294bf8b-9819-4b6d-92b2- > afc1c8042a06 at x6g2000prc.googlegroups.com... >> So much of it could be removed even by simple keyword filtering. Funny, I was just thinking recently about how *little* spam this list gets--on the other hand, I'm following it via the python-list@ mailing list. The list owners do a great job of keeping the level of spam at a minimum, though there are occasional false positives (like your post, apparently, since I'm only seeing the replies). -Miles From detlev at die-offenbachs.de Sun Aug 30 03:53:03 2009 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sun, 30 Aug 2009 09:53:03 +0200 Subject: IDE for python similar to visual basic References: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> Message-ID: qwe rty wrote: > i have been searching for am IDE for python that is similar to Visual > Basic but had no luck.shall you help me please? eric4 should be a good candidate. http://eric-ide.python-projects.org Detlev -- Detlev Offenbach detlev at die-offenbachs.de From ubershmekel at gmail.com Sun Aug 30 03:56:31 2009 From: ubershmekel at gmail.com (RunThePun) Date: Sun, 30 Aug 2009 00:56:31 -0700 (PDT) Subject: Overriding iadd for dictionary like objects References: <21e57363-4e92-41cb-9907-5aef96ad0a6e@o15g2000yqm.googlegroups.com> <58e91734-d03f-417c-89b1-f2717c3a9181@l5g2000yqo.googlegroups.com> <87ws4n5gfi.fsf@slice.rozzin.com> Message-ID: On Aug 29, 1:58?pm, Carl Banks wrote: > On Aug 28, 10:37?pm, Joshua Judson Rosen wrote: > > > > > > > Carl Banks writes: > > > > On Aug 28, 2:42?pm, Terry Reedy wrote: > > > > > Carl Banks wrote: > > > > > I don't think it needs a syntax for that, but I'm not so sure a method > > > > > to modify a value in place with a single key lookup wouldn't > > > > > occasioanally be useful. > > > > > Augmented assignment does that. > > > > Internally uses two lookups, one for getting, and one for setting. > > > > I think this is an unavoidable given Python's semantics. ?Look at > > > the traceback: > > > > >>> def x(): > > > ... ? ? d['a'] += 1 > > > ... > > > >>> dis.dis(x) > > > ? 2 ? ? ? ? ? 0 LOAD_GLOBAL ? ? ? ? ? ? ?0 (d) > > > ? ? ? ? ? ? ? 3 LOAD_CONST ? ? ? ? ? ? ? 1 ('a') > > > ? ? ? ? ? ? ? 6 DUP_TOPX ? ? ? ? ? ? ? ? 2 > > > ? ? ? ? ? ? ? 9 BINARY_SUBSCR > > > OK, there's one lookup, but... > > > > ? ? ? ? ? ? ?10 LOAD_CONST ? ? ? ? ? ? ? 2 (1) > > > ? ? ? ? ? ? ?13 INPLACE_ADD > > > ? ? ? ? ? ? ?14 ROT_THREE > > > ? ? ? ? ? ? ?15 STORE_SUBSCR > > > ? ? ? ? ? ? ?16 LOAD_CONST ? ? ? ? ? ? ? 0 (None) > > > ? ? ? ? ? ? ?19 RETURN_VALUE > > > ... I don't see anything in there that retrieves the value a second time.... > > STORE_SUBSCR has to look up the position in the hash table to store > the value, hence the second lookup. > > > > > > As a workaround, if lookups are expensive, > > > > > But they are not. Because (C)Python is heavily based on dict name lookup > > > > for builtins and global names and attributes, as well as overt dict > > > > lookup, must effort has gone into optimizing dict lookup. > > > > The actual lookup algorithm Python dicts use is well-optimized, yes, > > > but the dict could contain keys that have expensive comparison and > > > hash-code calculation, in which case lookup is going to be slow. > > > I'll like the originator correct me if I've made a mistake, but I read > > "lookup" as actually meaning "lookup", not "value-comparison". > > This has nothing to do with value comparison. ?I was talking about key > comparison, which happens when looking up a position in a hash table. > I was the first person to use the word "lookup" in this thread and I > specifically meant hash-table position lookup. > > > At least in part because the question, as it was posed, specifically > > related to a wrapper-class (providing a mapping ("dict like") interface) > > around a database of some sort other than Python's dict class per se. > > > How do the details of Python's native dict-type's internal (hashtable) > > algorithm matter when they're explicitly /not/ being used? > > Well it doesn't apply specifically to the OP's problem. ?I changed the > topic a bit by making it specific to dicts. ?Is that ok with you? ?Was > that not allowed? > > The OP can add a method like apply_to_value to his own class, but one > can't do that for dicts. ?Ergo why something like apply_to_value() > would be useful enough in rare circumstances where lookup is very slow > to merit a moments consideration before being rejected. > > (If dict did have a method like that, the OP would at least know which > method to override.) > > Carl Banks First of all I'd like to say thanks for this discussion, you guys are awesome. I probably should have explained my problem better to begin with and I apologize for that. So now I'll start from the top: I made a DictMixin where the keys are filenames and the values are the file contents. It was very simple and easy to do thanks to DictMixin. For example this code writes "abc" in a file named "temp.txt" and prints the contents of the file named "swallow", these files are looked up/created/deleted in the directory "spam": >>> d = FilesDict('spam') >>> d['temp.txt'] = 'abc' >>> print(d['swallow']) This was very convenient for me because I wanted to use a simple DB which could be read and edited by shell scripts and non-pythonistas, without the heavy ORM. Also, if in the future an online full featured DB would be needed, I could easily convert the DictMixin methods. So up to here I had a good solution. My problem arose when I wanted to append a string to a file which using open(..., 'ab') would have been miles more efficient because I wouldn't have to read the entire file (__getitem__) and then write the entire file back (__setitem__). The files are expected to be as big as 600 KB which will be appended 30 bytes at a time about 3 times a second. Performance-wise the system would probably work without open (..., 'ab') but it would be a real thrashing so the current solution uses a method "AddTo" as Robert suggested, sacrificing the neat getitem/setitem syntax. Just so I don't leave out any information, I actually also made a DirectoryDict for having multiple 'tables'. In this DictMixin, keys are directory names and values are FilesDict instances. So to write "European or African" to the file "/root/tmp/velocity" one would be just: >>> d = DirectoryDict("/root") >>> d["tmp"]["velocity"] = "European or African" So now I hope it's clearer why and how I wanted a special __item_iadd__ for the dictionary syntax, RunThePun From dickinsm at gmail.com Sun Aug 30 04:01:37 2009 From: dickinsm at gmail.com (Mark Dickinson) Date: Sun, 30 Aug 2009 01:01:37 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: On Aug 29, 8:03?pm, Steven D'Aprano wrote: > On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: > > I thought that int as object will stay the same object after += but with > > another integer value. My intuition said me that int object which > > represent integer value should behave this way. > > If it did, then you would have this behaviour: > > >>> n = 3 ? ? ? ? ? ? ? ? ? ? # bind the name n to the object 3 > >>> saved_id = id(n) ? ? ? ? ?# get the id of the object > >>> n += 1 ? ? ? ? ? ? ? ? ? ?# add one to the object 3 > >>> assert n == 4 ? ? ? ? ? ? # confirm that it has value four > >>> assert id(n) == saved_id ?# confirm that it is the same object > >>> m = 3 ? ? ? ? ? ? ? ? ? ? # bind the name m to the object 3 > >>> print m + 1 ? ? ? ? ? ? ? # but object 3 has been modified > > 5 I don't see how that follows. In an alternative interpretation, the int literals would all be thought of as distinct objects: that is, the line 'n = 3' creates an integer object with value 3 and binds the name n to it; the later line 'm = 3' then creates another *new* integer object with value 3 and binds the name m to it. In other words, it could work in exactly the same way as the following works in Python: >>> n = {} >>> n[1729] = 10585 >>> m = {} >>> m {} The modification to n doesn't affect m, since the two occurrences of {} give distinct dictionary objects. -- Mark From garabik-news-2005-05 at kassiopeia.juls.savba.sk Sun Aug 30 04:17:54 2009 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Sun, 30 Aug 2009 08:17:54 +0000 (UTC) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: r wrote: > Some may say well how can we possibly force countries/people to speak/ > code in a uniform manner? Well that's simple, you just stop supporting > their cryptic languages by dumping Unicode and returning to the > beautiful ASCII and adopting English as the universal world language. v> Why English? Well because it is so widely spoken. But whatever we > choose just choose one language and stick with it, perfect it, and > maintain it. > Y?know, it is na?ve to think that the ?beautiful? ASCII is sufficient for English? Besides, there is the APL... (though, you are right, we should dump those crappy old languages and use Python exclusively) -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From catalinfest at gmail.com Sun Aug 30 04:20:15 2009 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Sun, 30 Aug 2009 01:20:15 -0700 (PDT) Subject: How i follow tree folders from url Message-ID: <9f163791-417a-49e1-903b-54154ed3bc2b@p9g2000vbl.googlegroups.com> Hello ! I wanna use python to follow the tree folders from one url. Example : If url is "www.site.com/first/ and " "first" is first folder with next subfolders "01","02","03" The result of script should be : www.site.com/first/01/ www.site.com/first/02/ www.site.com/first/03/ Maybe urllib has some functions , but i don't know them. Please help me ! Thank you ! From thorsten at thorstenkampe.de Sun Aug 30 04:33:43 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 30 Aug 2009 10:33:43 +0200 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: * r (Sat, 29 Aug 2009 18:30:34 -0700 (PDT)) > We don't support a Python group in Chinese or French, so why this? "We" do - you don't (or to be more realistic, you simply didn't know it). > Makes no sense to me really. Like probably 99.99999% of all things you hear, read, see and encounter during the day. By the way: the dumbness of your "Unicode rant" would have even ashamed the great XL himself. Thorsten From thorsten at thorstenkampe.de Sun Aug 30 04:38:03 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 30 Aug 2009 10:38:03 +0200 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: * Neil Hodgson (Sun, 30 Aug 2009 06:17:14 GMT) > Chris Jones: > > > I am not from these climes but all the same, I do find you tone of > > voice rather offensive, considering that you are referring to a > > culture that's about 3000 years older and 3000 richer than ours and > > certainly deserves our respect. > > Eh? Was Unicode developed in India? China? Chris was obviously talking about Sanskrit... Thorsten From clp2 at rebertia.com Sun Aug 30 04:39:19 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 30 Aug 2009 01:39:19 -0700 Subject: How i follow tree folders from url In-Reply-To: <9f163791-417a-49e1-903b-54154ed3bc2b@p9g2000vbl.googlegroups.com> References: <9f163791-417a-49e1-903b-54154ed3bc2b@p9g2000vbl.googlegroups.com> Message-ID: <50697b2c0908300139o3247d2e3g8ef9039fd3f6f301@mail.gmail.com> On Sun, Aug 30, 2009 at 1:20 AM, catalinfest at gmail.com wrote: > Hello ! > > I wanna use python to follow the tree folders from one url. > Example : > If url is "www.site.com/first/ and " > "first" is first folder with next subfolders "01","02","03" > The result of script should be : > > www.site.com/first/01/ > www.site.com/first/02/ > www.site.com/first/03/ > Maybe urllib has some functions , but i don't know them. HTTP has no equivalent to "ls". You have to either know the format the of URLs yourself or spider the links on a given page. To generate the URLs if you know the scheme, use range() and str.zfill(). Cheers, Chris -- http://blog.rebertia.com From thorsten at thorstenkampe.de Sun Aug 30 04:43:24 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 30 Aug 2009 10:43:24 +0200 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: * Chris Jones (Sun, 30 Aug 2009 00:22:00 -0400) > On Sat, Aug 29, 2009 at 11:07:17PM EDT, Neil Hodgson wrote: > > Sanskrit is mostly written in Devanagari these days which is also > > useful for selling things to people who speak Hindi and other Indian > > languages. > > Is the implication that the principal usefulness of such languages as > Hindi and "other Indian languages" is us selling "things" to them..? I > am not from these climes but all the same, I do find you tone of voice > rather offensive, considering that you are referring to a culture that's > about 3000 years older and 3000 richer than ours and certainly deserves > our respect. Neil was obviously talking about Devanagari. Please also mind the principal difference between Neil's "also useful" and your "principal useful(ness)". Thorsten From solipsis at pitrou.net Sun Aug 30 04:48:43 2009 From: solipsis at pitrou.net (Antoine Pitrou) Date: Sun, 30 Aug 2009 08:48:43 +0000 (UTC) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: r gmail.com> writes: > > Why should the larger world > keep supporting such antiquated languages and character sets through > Unicode? What purpose does this serve? Are we merely trying to make > everyone happy? A sort of Utopian free-language-love-fest-kinda- > thing? Can you go and troll somewhere else? Thanks. Antoine. From thorsten at thorstenkampe.de Sun Aug 30 04:53:04 2009 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 30 Aug 2009 10:53:04 +0200 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: * John Machin (Sat, 29 Aug 2009 17:20:47 -0700 (PDT)) > On Aug 30, 8:46?am, r wrote: > > > > Take for instance the Chinese language with it's thousands of > > characters and BS, it's more of an art than a language. ?Why do we > > need such complicated languages in this day and time. Many languages > > have been perfected, (although not perfect) far beyond that of > > Chinese language. > > The Chinese language is more widely spoken than English, is quite > capable of expression in ASCII ("r tongzhi shi sha gua") and doesn't > have those pesky it's/its problems. You could also put it differently: the Chinese language (like any other language) doesn't even have "characters". It's really funny to see how someone who rants about Unicode doesn't event knows the most basic facts. Thorsten From 71david at libero.it Sun Aug 30 05:18:35 2009 From: 71david at libero.it (David) Date: Sun, 30 Aug 2009 11:18:35 +0200 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> Message-ID: <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> Il Sat, 29 Aug 2009 17:18:46 -0700 (PDT), casebash ha scritto: > So much of it could be removed even by simple keyword filtering. I think there is only one final solution to the spam pestilence: a tiny tax on email and posts. Spammers send hundreds of thousands of emails/posts a day and a tax of 0.0001$ each does not harm normal users but discurages spammers. This tax should be applied when a message is routed by a ISP server, this saves mails/posts internal to a LAN. Direct costs of this tax would be compensated by the simplified management of network traffic (70-90% of mail traffic is spam) and the reduced risk of virus infections. David From larudwer at freenet.de Sun Aug 30 05:21:46 2009 From: larudwer at freenet.de (larudwer) Date: Sun, 30 Aug 2009 11:21:46 +0200 Subject: weak reference callback References: Message-ID: "Paul Pogonyshev" schrieb im Newsbeitrag news:mailman.658.1251577954.2854.python-list at python.org... > Hi, > > Is weak reference callback called immediately after the referenced > object is deleted or at arbitrary point in time after that? I.e. is > it possible to see a dead reference before the callback is called? > > More formally, will this ever raise? > > callback_called = False > def note_deletion (ref): > callback_called = True > ref = weakref.ref (x, note_deletion) > if ref () is None and not callback_called: > raise RuntimeError ("reference is dead, yet callback hasn't been > called yet") The Manual says: "If callback is provided and not None, and the returned weakref object is still alive, the callback will be called when the object is about to be finalized; the weak reference object will be passed as the only parameter to the callback; the referent will no longer be available." This says that the Object is deleted first, and the callback functions will be called after that. Since after 'after that' IS an arbitrary point in time your example SHOULD raise. I think it is save to assume that this will never raise in an single threaded cpython application because the GIL and reference counting scheme etc. will prevent this. However, this is an implementation specific detail of the cpython runtime and it is not save to rely on this behavior. It may be completely different in an multi threaded environment or any other implementation of Python. From steve at REMOVE-THIS-cybersource.com.au Sun Aug 30 06:34:17 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 10:34:17 GMT Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: <0023d927$0$2930$c3e8da3@news.astraweb.com> On Sun, 30 Aug 2009 02:33:05 -0500, Derek Martin wrote: > On Sat, Aug 29, 2009 at 07:03:23PM +0000, Steven D'Aprano wrote: >> On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: >> >> > I thought that int as object will stay the same object after += but >> > with another integer value. My intuition said me that int object >> > which represent integer value should behave this way. >> >> If it did, then you would have this behaviour: > > No, you wouldn't; the behavior you described is completely different > from, and incompatible with, what zaur wrote. > > He's saying that instead of thinking the integer value of 3 itself being > the object, he expected Python's object model would behave as though the > entity m is the object, and that object exists to contain an integer > value. What is "the entity m"? Is it the name m, as follows? >>> m = 3 # bind the object 3 to the name m Or is it the literal "3" (without quotes)? Or an object holding the value three? Or something else? > In that case, m is always m, > but it has whatever integer value > it is told to hold at any point in time. The self-referential addition > would access the value of m, add the operand, and store the result back > in the same object as the object's value. Ah wait, I think I get it... is m a memory location? So when you say: m = 3 the memory location that m represents is set to the value 3, and when you say: m += 1 the memory location that m represents is set to the value 4? That would be how Pascal and C (and presumably other languages) work, but not Python or Ruby or even VB (so I'm told) and similar languages. Java has a hybrid model, where a few data types (such as ints) are handled like C, and everything else is handled like Python. Consistency was never Java's strong suit. > This is not the way Python > works, but he's saying this is the intuitive behavior. It isn't intuitive if you've never been exposed to Pascal- or C-like languages. If your only programming language was Haskell, the very idea of mutating values would be alien. So I guess when you say "the intuitive behaviour", what you actually mean is "familiar". > I happen to > agree, and argued at length with you and others about that very thing > months ago, when some other third party posted with that exact same > confusion. > > By contrast, your description maintains the concept of numerical value > as object that Python uses, and completely misses the point. I did find > the description you gave to be highly enlightening though... It > highlighted perfectly, I think, exactly why it is that Python's behavior > regarding numerical values as objects is *not* intuitive. Of course, > intuition is highly subjective. What exactly is it about Python's behaviour regarding numbers that is not intuitive? That you can't do this? >>> anum = 2 >>> alist = [anum] >>> anum += 1 >>> print alist # this doesn't work [3] That won't work in any language that I know of -- as far as I am aware, the above is impossible in just about every common programming language. (My C and VB are nearly non-existent, so I may be wrong about them.) Here is Ruby's behaviour: irb(main):001:0> anum = 2 => 2 irb(main):002:0> alist = [anum] => [2] irb(main):003:0> anum += 1 => 3 irb(main):004:0> puts alist 2 => nil Just like Python. > I believe it boils down to this: People expect that objects they create > are mutable. Why would they expect that? Is there any evidence apart from the anecdotal complaints of a few people that they expect this? People complain equally when they use a mutable default value and it mutates, or that they can't use mutable objects as dict keys, so this suggests that people expect objects should be immutable and are surprised when they change. If you're going to argue by analogy with the real world (as you do further on), I think it's fair to argue that some objects are mutable (pieces of rubber that expand into a balloon when you blow into them), and some are immutable unless you expend extraordinary effort (rocks). I would be gobsmacked if my desk turned pink or changed into an armchair, I expect it to be essentially unchanging and immutable. But I fully expect a banana to turn black, then squishy, and finally white and fuzzy if I leave it long enough. > At least, unless they specify otherwise. It is so in some > other programming languages which people may be likely to be familiar > with (if they are not taking their first forray into the world of > computing by learning Python), and even "real world" objects are > essentially always mutable. [snip example of a 2002 Buick LeSabre] Be careful bringing real-world examples into this. People have been arguing about identity in the real-world for millennia. See, for example, the paradox of my great-grandfather's axe. My great-grandfather's axe is still in my family after 80 years, as good as new, although the handle has been replaced four times and the head twice. But it's still the same axe. An even older example is the paradox of the Ship of Theseus. > Numbers are fundamentally different from objects. The number 3 is a > symbol of the idea of the existence of three countable objects. It can > not be changed Doesn't this contradict your claim that people expect to be able to mutate numbers? That you should be able to do this? >>> x = 3 >>> id(x) 123456 >>> x += 1 >>> assert x == 4 >>> id(x) 123456 You can't have it both ways -- if people think of objects as mutable, and think of numbers as not-objects and unchanging, then why oh why would they find Python's numeric behaviour to be unintuitive? > (though it can be renamed, if you so choose -- just don't > expect most people to know what you're talking about). It is > unintuitive that 3 is an object; Says you. People have considered numbers to be eternal, unchanging, immutable entities going back to at least Plato. If people are comfortable thinking that there are Platonic ideal numbers, why wouldn't they think of them represented in computers as immutable objects? What I think is that some people, such as you and Zaur, have *learned* from C-like languages that numbers are mutable not-objects, and you've learned it so well that you've forgotten that you ever needed to learn it. Consequently what you actually mean when you say Python is unintuitive is that Python is not like some other language (and is like yet other languages). > it is rather what we use to describe > objects -- the value of the object. It is an abstract concept, and as > such it is not an object at all. You cannot hear 3, taste 3, nor smell > 3. You can neither see nor touch 3, though you can certainly see 3 > *objects* if they are present, and you can certainly see the symbol '3' > that we use to represent that idea... but you can not see three itself, > because there is no such object. Human beings are excellent at reifying abstract things into (imaginary) objects. We talk about letting in the cold (we actually let out the heat); we talk about souls and life-force as if they are things; we treat justice and love and mercy and hate as palpable things instead of emotions and abstract entities. Plato imagined that everything has a pure, abstract form, an ideal, and people find that intuitive: we expect that there is an archetypal "chair" that embodies everything that is chair-like and nothing which is not, if only we could find it. Numbers are no different. Reifying them into objects comes easy to people who haven't learned differently. > The only way to see three is to > envision 3 of some object. The number 3 does not have a value; it IS a > value (it is the symbolic representation of the value of three). To say > that 3 is an object that has a value is a bit like saying the length of > a car is an object that itself has a length. No, the length of a car is an object which *is* a length, it doesn't *have* a length. > It just doesn't compute. None of this explains why you would expect to be able to mutate the value three and turn it into four. I don't think your argument makes sense -- I think your explanation is tangled up in knots. Everything you say about numbers being unchangeable, immutable entities supports Python's behaviour to make numbers immutable, and yet you argue that since people expect numbers to be unchanging, they therefore expect Python ints to be mutable! This makes no sense. > THAT is why Python's behavior with regard to numerical objects is not > intuitive, and frankly bizzare to me, and I dare say to others who find > it so. > > Yes, that's right. BIZZARE. I think you have confused yourself. If the number three cannot change, and you have a label "m" associated with three, then if you add one to it, you *can't* have the three mutate into a four, because numbers cannot change. Obviously the label has to detach itself off the three and onto the four -- precisely the behaviour Python uses. Plato would surely have found this commonsensical, and I would say that it's only those who have become used to Pascal-like languages that don't. -- Steven From ptmcg at austin.rr.com Sun Aug 30 06:42:06 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 30 Aug 2009 03:42:06 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> On Aug 30, 2:33?am, Derek Martin wrote: > THAT is why Python's behavior with regard to numerical objects is > not intuitive, and frankly bizzare to me, and I dare say to others who > find it so. > > Yes, that's right. ?BIZZARE. > Can't we all just get along? I think the question boils down to "where is the object?". In this statement: a = 3 which is the object, a or 3? There exist languages (such as C++) that allow you to override the '=' assignment as a class operator. So that I could create a class where I decided that assigning an integer value to it applies some application logic, probably the setting of some fundamental attribute. In that language, 'a' is the object, and 3 is a value being assigned to it. This can cause some consternation when a reader (or worse, maintainer) isn't familiar with my code, sees this simple assignment, and figures that they can use 'a' elsewhere as a simple integer, with some surprising or disturbing results. Python just doesn't work that way. Python binds values to names. Always. In Python, "=" is not and never could be a class operator. In Python, any expression of LHS = RHS, LHS is always a name, and in this statement it is being bound to some object found by evaluating the right hand side, RHS. The bit of confusion here is that the in-place operators like +=, -=, etc. are something of a misnomer - obviously a *name* can't be incremented or decremented (unlike a pointer in C or C++). One has to see that these are really shortcuts for LHS = LHS + RHS, and once again, our LHS is just a name getting bound to the result of LHS + RHS. Is this confusing, or non-intuitive? Maybe. Do you want to write code in Python? Get used to it. It is surprising how many times we think things are "intuitive" when we really mean they are "familiar". For long-time C and Java developers, it is intuitive that variables are memory locations, and switching to Python's name model for them is non-intuitive. As for your quibble about "3 is not an object", I'm afraid that may be your own personal set of blinders. Integer constants as objects is not unique to Python, you can see it in other languages - Smalltalk and Ruby are two that I know personally. Ruby implements a loop using this interesting notation: 3.times do ...do something... end Of course, it is a core idiom of the language, and if I adopted Ruby, I would adopt its idioms and object model. Is it any odder that 3 is an object than that the string literal "Hello, World!" is an object? Perhaps we are just not reminded of it so often, because Python's int class defines no methods that are not "__" special methods (type in "dir(3)" at the Python prompt). So we never see any Python code referencing a numeric literal and immediately calling a method on it, as in Ruby's simple loop construct. But we do see methods implemented on str like split(), and so "about above across after against".split() gives me a list of the English prepositions that begin with "a". We see this kind of thing often enough, we get accustomed to the objectness of string literals. It gets to be so familiar, it eventually seems "intuitive". You yourself mentioned that intuition is subjective - unfortunately, the "intuitiveness" of a feature is often tied to its value as a coding concept, and so statements of non-intuitiveness can be interpreted as a slant against the virtue of that concept, or even against the language itself. Once we accept that 3 is an object, we clearly have to stipulate that there can be no changes allowed to it. 3 must *always* have the value of the integer between 2 and 4. So our language invokes the concept that some classes create instances that are immutable. For a Python long-timer like Mr. D'Aprano, I don't think he even consciously thinks about this kind of thing any more; his intuition has aligned with the Python stars, so he extrapolates from the OP's suggestion to the resulting aberrant behavior, as he posted it. You can dispute and rail at this core language concept if you like, but I think the more entrenched you become in the position that "'3 is an object' is bizarre", the less enjoyable your Python work will be. -- Paul From steve at REMOVE-THIS-cybersource.com.au Sun Aug 30 06:44:48 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 10:44:48 GMT Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: <0023db9f$0$2930$c3e8da3@news.astraweb.com> On Sun, 30 Aug 2009 01:01:37 -0700, Mark Dickinson wrote: > On Aug 29, 8:03?pm, Steven D'Aprano cybersource.com.au> wrote: >> On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: >> > I thought that int as object will stay the same object after += but >> > with another integer value. My intuition said me that int object >> > which represent integer value should behave this way. >> >> If it did, then you would have this behaviour: >> >> >>> n = 3 ? ? ? ? ? ? ? ? ? ? # bind the name n to the object 3 >> >>> saved_id = id(n) ? ? ? ? ?# get the id of the object n += 1 ? ? ? ? >> >>> ? ? ? ? ? ?# add one to the object 3 assert n == 4 ? ? ? ? ? ? # >> >>> confirm that it has value four assert id(n) == saved_id ?# confirm >> >>> that it is the same object m = 3 ? ? ? ? ? ? ? ? ? ? # bind the >> >>> name m to the object 3 print m + 1 ? ? ? ? ? ? ? # but object 3 has >> >>> been modified >> >> 5 > > I don't see how that follows. Okay, it follows given Python's caching of small integer objects. It also follows from the idea that there is one abstract entity which English speakers call "three" and write as 3. There's not two identical entities with value 3, or four, or a million of them, only one. But of course your alternative implementation (where every time the Python VM sees the literal 3 it creates a new integer object with that value) would also be a valid, albeit inefficient, implementation. To be honest, I didn't even think of that. -- Steven From ptmcg at austin.rr.com Sun Aug 30 06:52:36 2009 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 30 Aug 2009 03:52:36 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> Message-ID: <71e92f9c-4094-409d-95d7-9836737d4dc2@d34g2000vbm.googlegroups.com> On Aug 30, 5:42?am, Paul McGuire wrote: > Python binds values to names. Always. In Python, "=" is not and never > could be a class operator. ?In Python, any expression of LHS = RHS, > LHS is always a name, and in this statement it is being bound to some > object found by evaluating the right hand side, RHS. > An interesting side note, and one that could be granted to the OP, is that Python *does* support the definition of class operator overrides for in-place assignment operators like += (by defining a method __iadd__). This is how numpy's values accomplish their mutability. > It is surprising how many times we > think things are "intuitive" when we really mean they are "familiar". Of course, just as I was typing my response, Steve D'Aprano beat me to the punch. Maybe it's time we added a new acronym to this group's ongoing discussions: PDWTW, or "Python doesn't work that way". -- Paul From marduk at letterboxes.org Sun Aug 30 07:09:46 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 30 Aug 2009 07:09:46 -0400 Subject: Is behavior of += intentional for int? In-Reply-To: <0023db9f$0$2930$c3e8da3@news.astraweb.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0023db9f$0$2930$c3e8da3@news.astraweb.com> Message-ID: <1251630586.9674.0.camel@centar.nbk> On Sun, 2009-08-30 at 10:44 +0000, Steven D'Aprano wrote: > It also follows from the idea that there is one abstract entity which > English speakers call "three" and write as 3. There's not two > identical > entities with value 3, or four, or a million of them, only one. That's not true. There are many different 3s in all the parallel universes. ;) -a From webcokies at yahoo.com Sun Aug 30 07:19:10 2009 From: webcokies at yahoo.com (Joni Lee) Date: Sun, 30 Aug 2009 04:19:10 -0700 (PDT) Subject: a popen question. Please help Message-ID: <473423.84282.qm@web36903.mail.mud.yahoo.com> Hi all, I write a small script texts = os.popen('top').readlines() print texts It calls the command line "top" and will print out some texts. But first I have to press the keyboard "q" to quit the subprocess "top", then the texts will be printed, otherwise it just stands by with blank. Question is. Do you know how to give "q" into my python script so that "top" is automatically quit immediately or maybe after 1s and print out the texts. Thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From pavlovevidence at gmail.com Sun Aug 30 07:26:54 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 30 Aug 2009 04:26:54 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: <0221274c-994d-4130-93bb-a5fb528e7b83@x6g2000prc.googlegroups.com> On Aug 30, 12:33?am, Derek Martin wrote: [snip rant] > THAT is why Python's behavior with regard to numerical objects is > not intuitive, and frankly bizzare to me, and I dare say to others who > find it so. > > Yes, that's right. ?BIZZARE. You mean it's different from how you first learned it. Carl Banks From rolfpw at online.de Sun Aug 30 07:34:46 2009 From: rolfpw at online.de (Rolf) Date: Sun, 30 Aug 2009 13:34:46 +0200 Subject: How to install setuptools...egg? Message-ID: Hi, I would like to install setuptools for Python2.6 on Windows. Unfortunately I could only find setuptools-0.6c9-py2.6.egg but no *.exe for Python2.6. And as far as I understand I need setuptools to install a Python egg. I would be very appreciative for any help. Regards Rolf From python.list at tim.thechases.com Sun Aug 30 07:43:19 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 30 Aug 2009 06:43:19 -0500 Subject: a popen question. Please help In-Reply-To: <473423.84282.qm@web36903.mail.mud.yahoo.com> References: <473423.84282.qm@web36903.mail.mud.yahoo.com> Message-ID: <4A9A65D7.4020308@tim.thechases.com> > texts = os.popen('top').readlines() > print texts > > It calls the command line "top" and will print out some texts. > But first I have to press the keyboard "q" to quit the subprocess "top", then the texts will be printed, otherwise it just stands by with blank. > > Question > is. Do you know how to give "q" into my python script so that "top" is > automatically quit immediately or maybe after 1s and print out the texts. Well as a workaround, my version of top (on Debian) supports a "-n" parameter so you can tell it how many iterations you want it to perform before quitting. So you should be able to just use os.popen('top -n1').readlines() -tkc From clp2 at rebertia.com Sun Aug 30 07:49:17 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 30 Aug 2009 04:49:17 -0700 Subject: a popen question. Please help In-Reply-To: <4A9A65D7.4020308@tim.thechases.com> References: <473423.84282.qm@web36903.mail.mud.yahoo.com> <4A9A65D7.4020308@tim.thechases.com> Message-ID: <50697b2c0908300449i65d22994ra6d63b0bbdb1d201@mail.gmail.com> On Sun, Aug 30, 2009 at 4:43 AM, Tim Chase wrote: >> texts = os.popen('top').readlines() >> print texts >> >> It calls the command line "top" and will print out some texts. >> But first I have to press the keyboard "q" to quit the subprocess "top", >> then the texts will be printed, otherwise it just stands by with blank. >> >> Question >> is. Do you know how to give "q" into my python script so that "top" is >> automatically quit immediately or maybe after 1s and print out the texts. > > Well as a workaround, my version of top (on Debian) supports a "-n" > parameter so you can tell it how many iterations you want it to perform > before quitting. ?So you should be able to just use > > ?os.popen('top -n1').readlines() Hm, interesting. On Mac OS X's (and BSD's?) top, -n instead specifies the number of processes to list at a time (i.e. list only the top N processes), which is entirely different. Cheers, Chris From pavlovevidence at gmail.com Sun Aug 30 07:49:51 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 30 Aug 2009 04:49:51 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0023d927$0$2930$c3e8da3@news.astraweb.com> Message-ID: <051da35f-efc2-4c4a-9b87-6d7db59c4529@t11g2000prh.googlegroups.com> On Aug 30, 3:34?am, Steven D'Aprano wrote: > On Sun, 30 Aug 2009 02:33:05 -0500, Derek Martin wrote: > > On Sat, Aug 29, 2009 at 07:03:23PM +0000, Steven D'Aprano wrote: > >> On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: > > >> > I thought that int as object will stay the same object after += but > >> > with another integer value. My intuition said me that int object > >> > which represent integer value should behave this way. > > >> If it did, then you would have this behaviour: > > > No, you wouldn't; the behavior you described is completely different > > from, and incompatible with, what zaur wrote. > > > He's saying that instead of thinking the integer value of 3 itself being > > the object, he expected Python's object model would behave as though the > > entity m is the object, and that object exists to contain an integer > > value. > > What is "the entity m"? I think they (Derek and zaur) expect integer objects to be mutable. It's pretty common for people coming from "name is a location in memory" languages to have this conception of integers as an intermediate stage of learning Python's object system. Even once they've understood "everything is an object" and "names are references to objects" they won't have learned all the nuances of the system, and might still (not unreasonably) think integer objects could be mutable. However, it'd be nice if all these people didn't post here whining about how surprising and unintuitive it is and instead just said, "ah, integers are immutable, got it", quietly to themselves. Carl Banks From deets at nospam.web.de Sun Aug 30 07:51:21 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: 30 Aug 2009 11:51:21 GMT Subject: How to install setuptools...egg? References: Message-ID: <36484556273325783.562061deets-nospam.web.de@news.hansenet.de> Rolf wrote: > Hi, > > I would like to install setuptools for Python2.6 on Windows. > Unfortunately I could only find setuptools-0.6c9-py2.6.egg but no > *.exe > for Python2.6. And as far as I understand I need setuptools to install > a > Python egg. I would be very appreciative for any help. You bootstrap setuptools by downloading & executing ez_setup.py. Diez From cjw at ncf.ca Sun Aug 30 08:08:20 2009 From: cjw at ncf.ca (Colin J. Williams) Date: Sun, 30 Aug 2009 08:08:20 -0400 Subject: How to install setuptools...egg? In-Reply-To: <36484556273325783.562061deets-nospam.web.de@news.hansenet.de> References: <36484556273325783.562061deets-nospam.web.de@news.hansenet.de> Message-ID: Diez B. Roggisch wrote: > Rolf wrote: >> Hi, >> >> I would like to install setuptools for Python2.6 on Windows. >> Unfortunately I could only find setuptools-0.6c9-py2.6.egg but no >> *.exe >> for Python2.6. And as far as I understand I need setuptools to install >> a >> Python egg. I would be very appreciative for any help. > > > You bootstrap setuptools by downloading & executing ez_setup.py. > > > Diez You might try, at the command line: easy_install setuptools Colin W. From abecedarian314159 at yahoo.com Sun Aug 30 08:10:20 2009 From: abecedarian314159 at yahoo.com (William) Date: Sun, 30 Aug 2009 05:10:20 -0700 (PDT) Subject: Python for professsional Windows GUI apps? In-Reply-To: Message-ID: <669926.22777.qm@web110604.mail.gq1.yahoo.com> For wxFormbuilder, does it also support AUI (dockable windows,etc.)? Thanks, William --- On Wed, 8/26/09, Robert Kern wrote: From: Robert Kern Subject: Re: Python for professsional Windows GUI apps? To: python-list at python.org Date: Wednesday, August 26, 2009, 7:40 PM On 2009-08-26 18:08 PM, sturlamolden wrote: > On 26 Aug, 22:47, David C Ullrich? wrote: > >>> Nothing, except lobbying for wxFormBuilder for anyone who still doesn't >>> know of it. :) >> >> That's great. But do you know of anything I can use as a >> visual form design tool in wxPython? > > Right... I don't know if you are trying to be funny, but as I said > there is wxFormBuilder... > > 3.0 generates XRC that you can use with wxPython. > 3.1 beta generates wxPython classes you can subclass. > > Honestly, it's the best GUI builder for wxPython I know of. It's possible that he is not asking for a visual form designer tool *for* building a wxPython app, but one that can be used *inside* a wxPython app like an IDE or something similar. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." ? -- Umberto Eco -- http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- An HTML attachment was scrubbed... URL: From hendrik at microcorp.co.za Sun Aug 30 08:11:15 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 30 Aug 2009 14:11:15 +0200 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <200908301411.15680.hendrik@microcorp.co.za> On Sunday 30 August 2009 02:20:47 John Machin wrote: > On Aug 30, 8:46?am, r wrote: > > Take for instance the Chinese language with it's thousands of > > characters and BS, it's more of an art than a language. ?Why do we > > need such complicated languages in this day and time. Many languages > > have been perfected, (although not perfect) far beyond that of Chinese > > language. > > The Chinese language is more widely spoken than English, is quite > capable of expression in ASCII ("r tongzhi shi sha gua") and doesn't > have those pesky it's/its problems. > > > The A-Z char set is flawless! > > ... for expressing the sounds of a very limited number of languages, > and English is *NOT* one of those. I suspect that the alphabet is not ideal for representing the sounds of _any_ language, and I would look for my proof in the plethora of things that we use when writing, other than the bare A-Z. - Punctuation, diacritics... But what really started me thinking, after reading this post of John's, read with Dennis'. - on the dissimilarity of the spoken and written Chinese - was the basic dichotomy of the two systems - a symbol for a sound vs a symbol for a word or an idea. I know that when I read, I do not actually read the characters, I recognize words, and only fall back to messing with characters when I hit something unfamiliar. So It would seem to me that r's "utopia" could sooner be realized if the former system were abandoned in favour of the latter. - and Horrors! The language of choice would not be English! Not that I agree that it would be a Utopia, whatever the language - more like a nightmare of Orwellian proportions - because the language you get taught first, moulds the way you think. And I know from personal experience that there are concepts that can be succinctly expressed in one language, that takes a lot of wordy handwaving to get across in another. So diversity would be less, creativity would suffer due to lack of cross pollination, and progress would slow or stop. - Hendrik From python.list at tim.thechases.com Sun Aug 30 08:17:08 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 30 Aug 2009 07:17:08 -0500 Subject: a popen question. Please help In-Reply-To: <50697b2c0908300449i65d22994ra6d63b0bbdb1d201@mail.gmail.com> References: <473423.84282.qm@web36903.mail.mud.yahoo.com> <4A9A65D7.4020308@tim.thechases.com> <50697b2c0908300449i65d22994ra6d63b0bbdb1d201@mail.gmail.com> Message-ID: <4A9A6DC4.5060804@tim.thechases.com> >> os.popen('top -n1').readlines() > > Hm, interesting. On Mac OS X's (and BSD's?) top, -n instead specifies > the number of processes to list at a time (i.e. list only the top N > processes), which is entirely different. [reaching over to my Mac] Looks like "top" there supports a -l parameter which does something similar. Darn "standards" :-/ -tkc From rt8396 at gmail.com Sun Aug 30 08:19:45 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 05:19:45 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <3e9ddb9b-8f61-4d8d-a25c-7e95e8a25c06@g1g2000vbr.googlegroups.com> On Aug 29, 11:05?pm, Anny Mous wrote: (snip) > How do we distinguish resume from r?sum? without accents? This is another quirk of some languages that befuddles me. What is with the ongoing language pronunciation tutorial some languages have turned into -- French is a good example (*puke*). Do you *really* need those squiggly lines and cues above letters so you won't forget how to pronounce a word. Pure ridiculousness! > Even when we succeed in banning all languages that can't be written using > A-Z, what do we do about the vast number of legacy documents? How do we > write about obsolete English letters like ? and ? without Unicode? Who gives a fig about obsolete languages, thank god they are dead and let's move on!! > > Some may say well how can we possibly force countries/people to speak/ > > code in a uniform manner? Well that's simple, you just stop supporting > > their cryptic languages by dumping Unicode and returning to the > > beautiful ASCII and adopting English as the universal world language. > > Why English? Well because it is so widely spoken. > > World population: 6.7 billion > > Number of native Mandarin speakers: 873 million > Number of native Hindi speakers: 370 million > Number of native Spanish speakers: 350 million > Number of native English speakers: 340 million > > Total number of Mandarin speakers: 1051 million > Total number of English speakers: 510 million > > http://www.vistawide.com/languages/top_30_languages.htm I was actually referring to countries where the majority of people *actually* know what a computer is and how to use it... If there culture has not caught up with western technology yet they are doomed to the fate of native American Indians. > Whichever way you look at it, we should all convert to Mandarin, not > English. Looks like we still need Unicode. see my last comment (snip entertaining assumptions) > Yes, because language differences have utterly destroyed us so many times in > the past! > > Have you thought about the difference between China, with one culture and > one spoken language for thousands of years, and Europe, with dozens of > competing cultures, competing governments, and alternate languages for just > as long? If multiple languages are so harmful, why was it the British, > French, Japanese, Russians, Germans, Italians, Austrians, Hungarians and > Americans who were occupying China during the Opium Wars and the Boxer > Rebellion, instead of the other way around? > > Strength comes from diversity, not monoculture. No strength comes from superior firepower. The Chinese culture stop evolving thousands of years ago. Who invented gun powder? Yes the Chinese and all they could do with it was create fireworks. Europeans took gun powered and started a revolution that changes the world forever -- for better and for worse, but that is how advancements work. It wasn't until western influence came along and finally nudged china into the 21st century. Europeans seek out technology and aren't dragged down by an antiquated culture which is good for innovation. If China with it's huge population thought like a European, they would rule the earth for 10,000 years. From rt8396 at gmail.com Sun Aug 30 08:25:58 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 05:25:58 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: <9077a084-bf0c-4480-b6e4-59f62558f3f4@p23g2000vbl.googlegroups.com> On Aug 30, 3:33?am, Thorsten Kampe wrote: [snip ridiculous trolling] > Thorsten Hmm, I wonder who's sock puppet you are Thorsten? From lists at cheimes.de Sun Aug 30 08:27:06 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 30 Aug 2009 14:27:06 +0200 Subject: How to install setuptools...egg? In-Reply-To: References: <36484556273325783.562061deets-nospam.web.de@news.hansenet.de> Message-ID: Colin J. Williams wrote: > You might try, at the command line: > easy_install setuptools That's not going to work. setuptools provides the easy_install command. If you have the easy_install command than setuptools is already installed. Christian From sjmachin at lexicon.net Sun Aug 30 08:41:23 2009 From: sjmachin at lexicon.net (John Machin) Date: Sun, 30 Aug 2009 05:41:23 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: On Aug 30, 4:47?pm, Dennis Lee Bieber wrote: > On Sun, 30 Aug 2009 14:05:24 +1000, Anny Mous > declaimed the following in gmane.comp.python.general: > > > Have you thought about the difference between China, with one culture and > > one spoken language for thousands of years, and Europe, with dozens of > > ? ? ? ? China has one WRITTEN language -- It has multiple SPOKEN languages ... hence Chinese movies have subtitles in Chinese. And it can't really be called one written language. For a start there are the Traditional characters and the Simplified characters. Then there are regional variations and add-ons e.g. the Hong Kong Special Character Set (now added into Unicode): not academic-only stuff, includes surnames, the "Hang" in Hang Seng Index and Hang Seng Bank, and the 5th character of the Chinese name of The Hongkong and Shanghai Banking Corporation Limited on the banknotes it issues. > (the main two being mandarin and cantonese -- with enough differences > between them that they might as well be spanish vs italian) Mandarin and Cantonese are groups of languages/dialects. Rough figures (millions): Mandarin 850, Wu 90, Min and Cantonese about 70 each. The intelligibility comparison is more like Romanian vs Portuguese, or Icelandic vs Dutch. I've heard that the PLA used Shanghainese (Wu group) as code talkers just like the USMC used Navajos. From rt8396 at gmail.com Sun Aug 30 08:49:19 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 05:49:19 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: On Aug 30, 7:11?am, Hendrik van Rooyen wrote: (snip) > I suspect that the alphabet is not ideal for representing the sounds of _any_ > language, and I would look for my proof in the plethora of things that we use > when writing, other than the bare A-Z. ? - Punctuation, diacritics... It can be made better and if that means add/removing letters or redefining what a letter represents i am fine with that. I know first hand the hypocrisy of the English language. I am thinking more on the lines of English redux! > Not that I agree that it would be a Utopia, whatever the language ?- more like > a nightmare of Orwellian proportions - because the language you get taught > first, moulds the way you think. ?And I know from personal experience that > there are concepts that can be succinctly expressed in one language, that > takes a lot of wordy handwaving to get across in another. ?So diversity would > be less, creativity would suffer due to lack of cross pollination, and > progress would slow or stop. We already live in a Orwellian language nightmare. Have you seen much change to the English language in your lifetime? i haven't. A language must constantly evolve and trim the excess cruft that pollutes it. And English has a mountain of cruft! After all our years on this planet i think it's high time to perfect a simplified language for world-wide usage. From bh at izb.knu.ac.kr Sun Aug 30 09:23:33 2009 From: bh at izb.knu.ac.kr (Byung-Hee HWANG) Date: Sun, 30 Aug 2009 22:23:33 +0900 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> Message-ID: <86vdk5o2p6.fsf@betla.izb.knu.ac.kr> casebash writes: > So much of it could be removed even by simple keyword filtering. Use python-list at python.org [1], instead. [1] http://mail.python.org/mailman/listinfo/python-list -- "He's a responsible man in his own way." -- Michael Corleone, "Chapter 25", page 363 From szport at gmail.com Sun Aug 30 09:32:22 2009 From: szport at gmail.com (zaur) Date: Sun, 30 Aug 2009 06:32:22 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> Message-ID: On 29 ???, 23:03, Steven D'Aprano wrote: > On Sat, 29 Aug 2009 11:11:43 -0700, zaur wrote: > > I thought that int as object will stay the same object after += but with > > another integer value. My intuition said me that int object which > > represent integer value should behave this way. > > If it did, then you would have this behaviour: > > >>> n = 3 ? ? ? ? ? ? ? ? ? ? # bind the name n to the object 3 > >>> saved_id = id(n) ? ? ? ? ?# get the id of the object > >>> n += 1 ? ? ? ? ? ? ? ? ? ?# add one to the object 3 > >>> assert n == 4 ? ? ? ? ? ? # confirm that it has value four > >>> assert id(n) == saved_id ?# confirm that it is the same object > >>> m = 3 ? ? ? ? ? ? ? ? ? ? # bind the name m to the object 3 > >>> print m + 1 ? ? ? ? ? ? ? # but object 3 has been modified > > 5 > > This would be pretty disturbing behaviour, and anything but intuitive. > > Fortunately, Python avoids this behaviour by making ints immutable. You > can't change the object 3 to have any other value, it will always have > value three, and consequently n+=1 assigns a new object to n. > > -- > Steven This behavior is because small integers are cached internally. See Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> a=1 >>> c=1 >>> d=10000 >>> e=10000 >>> id(a),id(c),id(d),id(e) (16793992, 16793992, 17067336, 17067276) From rt8396 at gmail.com Sun Aug 30 09:37:19 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 06:37:19 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: On Aug 30, 7:11?am, Hendrik van Rooyen wrote: (snip) > Not that I agree that it would be a Utopia, whatever the language ?- more like > a nightmare of Orwellian proportions - because the language you get taught > first, moulds the way you think. ?And I know from personal experience that > there are concepts that can be succinctly expressed in one language, that > takes a lot of wordy handwaving to get across in another. ?So diversity would > be less, creativity would suffer due to lack of cross pollination, and > progress would slow or stop. > > - Hendrik What makes you think that diversity is lost with a single language? I say more pollination will occur and the seed will be more potent since all parties will contribute to the same pool. Sure there will be idioms of different regions but that is to be expected. But at least then i could make international crank calls without the language barrier ;-) From sergiocharpinel at gmail.com Sun Aug 30 09:51:04 2009 From: sergiocharpinel at gmail.com (Sergio Charpinel Jr.) Date: Sun, 30 Aug 2009 10:51:04 -0300 Subject: Sqlite format string In-Reply-To: <20090830032422.GA23090@cskk.homeip.net> References: <20090830032422.GA23090@cskk.homeip.net> Message-ID: Thank you very much. 2009/8/30 Cameron Simpson > On 29Aug2009 17:27, Sergio Charpinel Jr. > wrote: > | Hi, > | I have this statement cursor.execute("SELECT * from session_attribute > WHERE > | sid=%s", ( user )) > | and I'm receiving this error : > | > | TypeError: not all arguments converted during string formatting > | > | What is wrong ? > > This: > > ( user ) > > is not a tuple containing the element user. It's just user. > > This: > > ( user, ) > > is what you want. > -- > Cameron Simpson DoD#743 > http://www.cskk.ezoshosting.com/cs/ > > [Alain] had been looking at his dashboard, and had not seen me, so I > ran into him. - Jean Alesi on his qualifying prang at Imola '93 > -- Sergio Roberto Charpinel Jr. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rt8396 at gmail.com Sun Aug 30 09:55:34 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 06:55:34 -0700 (PDT) Subject: How to install setuptools...egg? References: <36484556273325783.562061deets-nospam.web.de@news.hansenet.de> Message-ID: <2062b940-d248-47e3-adaf-2aaecd83e18c@g23g2000vbr.googlegroups.com> On Aug 30, 7:08?am, "Colin J. Williams" wrote: > You might try, at the command line: > ? ?easy_install setuptools Wait maybe you should try this command >>> help(setuptools) :-) From marduk at letterboxes.org Sun Aug 30 10:12:26 2009 From: marduk at letterboxes.org (Albert Hopkins) Date: Sun, 30 Aug 2009 10:12:26 -0400 Subject: Is behavior of += intentional for int? In-Reply-To: <051da35f-efc2-4c4a-9b87-6d7db59c4529@t11g2000prh.googlegroups.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0023d927$0$2930$c3e8da3@news.astraweb.com> <051da35f-efc2-4c4a-9b87-6d7db59c4529@t11g2000prh.googlegroups.com> Message-ID: <1251641546.14626.17.camel@centar.nbk> On Sun, 2009-08-30 at 04:49 -0700, Carl Banks wrote: > It's pretty common for people coming from "name is a location in > memory" languages to have this conception of integers as an > intermediate stage of learning Python's object system. Even once > they've understood "everything is an object" and "names are references > to objects" they won't have learned all the nuances of the system, and > might still (not unreasonably) think integer objects could be mutable. > I agree. Python (and other similar languages?) are different in that. 'x' does not point to an area in memory, where you can do anything with that area. But in Python there are objects, and they are "references" in memory that some magical "reference counter" keeps track of for us (and that's a wonderful thing). And what is 'x'? Well 'x' is just some "label" that just so happens to have the privelage of being associated with this "unnamed" object. 'x' could just as easily associate itself with another object. I think that the Blue programming language, which I have been looking at lately, makes this distinction even clearer. For example, functions are not defined by names at all. Instead of def funcname(): ... You have func{...}; If you actually want to be able to reference the function later (as you probably would) then it's just a simple assignment just like any other assignment: funcname = func{...}; But i think it makes it more clear that "funcname" just so happens to reference this object that's a function. It's the same basic philosophy when applied to methods: MyClass = sys.class(); MyClass.my_method = func{...}; Blue also has interesting, simple rules wrt scopes. It's a surprisingly small, simple language (yet in a very early stage of development. > However, it'd be nice if all these people didn't post here whining > about how surprising and unintuitive it is and instead just said, "ah, > integers are immutable, got it", quietly to themselves. Yes, when I was first learning Python, at least the book I used made it very clear when introducing a new type to specify that type as mutable or immutable. It's a very core concept to Python. If you choose to ignore it or refuse to understand it then you are asking for trouble. -a From catalinfest at gmail.com Sun Aug 30 10:27:10 2009 From: catalinfest at gmail.com (catafest) Date: Sun, 30 Aug 2009 07:27:10 -0700 (PDT) Subject: About diagram and python References: <030422b7-a4f8-4ea6-8708-4486da4cf595@w6g2000yqw.googlegroups.com> Message-ID: This is the software : http://projects.gnome.org/dia/ From magawake at gmail.com Sun Aug 30 10:27:10 2009 From: magawake at gmail.com (Mag Gam) Date: Sun, 30 Aug 2009 10:27:10 -0400 Subject: Parse xml file In-Reply-To: <4a969a9c$0$32665$9b4e6d93@newsspool2.arcor-online.net> References: <4a969a9c$0$32665$9b4e6d93@newsspool2.arcor-online.net> Message-ID: <1cbd6f830908300727lf4281f2wca2f5778dff181f@mail.gmail.com> XML is a structured file. I never knew you can read it line by line and process. iterparse() More info on iterparse(): http://effbot.org/zone/element-iterparse.htm On Thu, Aug 27, 2009 at 10:39 AM, Stefan Behnel wrote: > loial wrote: >> Is there a quick way to retrieve data from an xml file in python 2.4, >> rather than read the whole file? > > ElementTree is available as an external package for Py2.4 (and it's in the > stdlib xml.etree package since 2.5). > > It's pretty much the easiest way to get data out of XML files. > > If your statement "rather than read the whole file" was referring to the > file size, note that the C implementation "cElementTree" of ElementTree is > very memory efficient, so you might still get away with just reading the > whole file into memory. There's also the iterparse() function which > supports iterative parsing of an XML file and thus allows intermediate > cleanup of used data. > > Stefan > -- > http://mail.python.org/mailman/listinfo/python-list > From catalinfest at gmail.com Sun Aug 30 10:49:52 2009 From: catalinfest at gmail.com (catalinfest at gmail.com) Date: Sun, 30 Aug 2009 07:49:52 -0700 (PDT) Subject: How i follow tree folders from url Message-ID: <27fb7927-d3cd-446f-93b5-68bd2125c2ce@h30g2000vbr.googlegroups.com> Hello ! I wanna use python to follow the tree folders from one url to get data about dirs and folders. Example : If url is "www.site.com/first/ and " "first" is first folder with next subfolders "01","02","03" The result of script should be : www.site.com/first/01/ www.site.com/first/02/ www.site.com/first/03/ What is a easy way to make this ? From zuo at chopin.edu.pl Sun Aug 30 10:51:23 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Sun, 30 Aug 2009 16:51:23 +0200 Subject: An assessment of the Unicode standard In-Reply-To: <200908301411.15680.hendrik@microcorp.co.za> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <200908301411.15680.hendrik@microcorp.co.za> Message-ID: 30-08-2009 o 14:11:15 Hendrik van Rooyen wrote: > a nightmare of Orwellian proportions - because the language you get > taught first, moulds the way you think. And I know from personal > experience that > there are concepts that can be succinctly expressed in one language, that > takes a lot of wordy handwaving to get across in another. So diversity > would be less, creativity would suffer due to lack of cross pollination, > and progress would slow or stop. That's the point! Even in the case of programming languages we say about 'culture' and 'way of thinking' connected with each of them, though after all they are only formal constructs. In case of natural languages it's incomparably richer and more complex. Each natural language has richness of culture and ages of history -- behind that language and recorded in it in many ways. Most probably such an unification would mean terrible impoverishment of our (humans') culture and, as a result, terrible squandering of our intelectual, emotional, cognitive etc. potential -- especially if such unification were a result of intentional policy (and not of a slow and 'patient' process of synthesis). *j -- Jan Kaliszewski (zuo) From paul at boddie.org.uk Sun Aug 30 11:09:40 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 30 Aug 2009 08:09:40 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: On 30 Aug, 14:49, r wrote: > > It can be made better and if that means add/removing letters or > redefining what a letter represents i am fine with that. I know first > hand the hypocrisy of the English language. I am thinking more on the > lines of English redux! Elsewhere in this thread you've written... "This is another quirk of some languages that befuddles me. What is with the ongoing language pronunciation tutorial some languages have turned into -- French is a good example (*puke*). Do you *really* need those squiggly lines and cues above letters so you won't forget how to pronounce a word. Pure ridiculousness!" And, in fact, there have been schemes to simplify written English such as Initial Teaching Alphabet: http://en.wikipedia.org/wiki/Initial_Teaching_Alphabet I imagine that this is the first time you've heard of it, though. [...] > We already live in a Orwellian language nightmare. Have you seen much > change to the English language in your lifetime? i haven't. Then you aren't paying attention. Especially in places where English isn't the first language, there is a lot of modification of English that is then considered an acceptable version of the language - this is one way in which languages change. Elsewhere, you wrote this... "What makes you think that diversity is lost with a single language? I say more pollination will occur and the seed will be more potent since all parties will contribute to the same pool." Parties are contributing to the same language already. It's just not the only language that they contribute to. >From what you've written, I get the impression that you don't really know any other languages, don't have much experience with non-native users of your own language, are oblivious to how languages change, and are oblivious to the existence of various attempts to "improve" the English language in the past in ways similar to those you appear to advocate, albeit incoherently: do you want to know how to pronounce a word from its spelling or not? Add to that a complete lack of appreciation for the relationship between language and culture, along with a perverted application of evolutionary models to such things, and you come across as a lazy cultural supremacist who regards everyone else's language as superfluous apart from his own. If you're just having problems with UnicodeDecodeError, at least have the honesty to say so instead of parading something not too short of bigotry in a public forum. Paul From mike at mhuffman.com Sun Aug 30 11:39:37 2009 From: mike at mhuffman.com (Mike) Date: Sun, 30 Aug 2009 08:39:37 -0700 (PDT) Subject: How to install setuptools...egg? References: Message-ID: <6ee4ad7f-7e78-42cb-8f0b-198f32c08b6d@i18g2000pro.googlegroups.com> > I would like to install setuptools for Python2.6 on Windows. 1. Download setuptools-0.6c9-py2.6.egg 2. Download setuptools-0.6c9.tar.gz 3. Use 7-zip from http://www.7-zip.org/ to extract ez_setup.py from setuptools-0.6c9.tar.gz 4. In a directory that contains setuptools-0.6c9-py2.6.egg and ez_setup.py run the command python ez_setup.py 5. Add C:\Python26\Scripts to your path to run easy_install Mike From rt8396 at gmail.com Sun Aug 30 12:00:07 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 09:00:07 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: On Aug 30, 10:09 am, Paul Boddie wrote: > On 30 Aug, 14:49, r wrote: Then you aren't paying attention. ...(snip: defamation of character) Hold the phone Paul you are calling me a retarded bigot and i don't much appreciate that. I think you are completely misinterpreting my post. i and i ask you read it again especially this part... [quote] BUT STOP!, before i go any further i want to respond to what i know will be condemnation from the sociology nuts out there. Yes multiculturalism is great, yes art is great, but if you can't see how the ability to communicate is severely damperd by multi-languages then you only *feel* with your heart but you apparently have no ability to reason with your mind intelligently. [/quote] I don't really care what language we adopt as long as we choose *only* one and then seek to perfect it to perfection. And also that this *one* language use simplicity as it's model. English sucks, but compared to traditional Chinese and Egyptian Hieroglyphs it's a god send. I think a good language would combine the best of the popular world languages into one super language for all. The same thing Python did for programming. But of course programming is not as evolved as natural language so we will need multiple programming languages for quite some time... And just as the internet enabled worldwide instant communication, the unification of all languages will cause a Renaissance of sorts for coloaboration which in turn will beget innovation of enormous proportions. The ability to communicate unhampered is in everyones best interest. --------------------------------------- History Lesson and the laws of Nature --------------------------------------- Look history is great but i am more concerned with the future. Learn the lessons of the past, move on, and live for the future. If you want to study the hair styles of Neanderthal women be my guest. Anybody with half a brain knows the one world government and language is coming. Why stop evolution, it is our destiny and it will improve the human experience. [Warning: facts of life ahead!!] I'll bet you weep and moan for the native Americans who where slaughtered don't you? Yes they suffered a tragic death as have many poor souls throughout history and yes they also contributed to human history and experience, but their time had come and they can only blame themselfs for it. They stopped evolving, and when you stop evolving you get left behind. We can't win wars with bows and arrows in the 21st century, we can't fly to the moon on horse back, And you damn sure can smoke a peace pipe and make all the bad things disappear. Nature can be cruel and unjust at times, but progress is absolute and that is all mother nature (and myself to some extent) really cares about. Without the survival of the fittest nothing you see, feel, touch, or experience would be. The universe would collapse upon itself and cease to exist. The system works because it is perfect. Don't knock that which you do not understand, or, you refuse to understand.. We are but pawns in an ever evolving higher order entity. And when this entity no longer has a use for us, we will be history... From sccolbert at gmail.com Sun Aug 30 12:07:58 2009 From: sccolbert at gmail.com (Chris Colbert) Date: Sun, 30 Aug 2009 12:07:58 -0400 Subject: Permanently adding to the Python path in Ubuntu In-Reply-To: References: Message-ID: <7f014ea60908300907l3d21fcb6v9ed0c51180161338@mail.gmail.com> I don't want to have to modify the path in each and every application. There has to be a way to do this... Personally, I don't agree with the Debian maintainers in the order they import anyway; it should be simple for me to overshadow system packagers. But that's another story. P.S. my first name is Steven! Cheers, Chris On Sat, Aug 29, 2009 at 11:51 PM, Sean DiZazzo wrote: > On Aug 29, 5:39?pm, Chris Colbert wrote: >> I'm having an issue with sys.path on Ubuntu. I want some of my home >> built packages to overshadow the system packages. Namely, I have built >> numpy 1.3.0 from source with atlas support, and I need it to >> overshadow the system numpy 1.2.1 which I had to drag along as a >> dependency for other stuff. I have numpy 1.3.0 installed into >> /usr/local/lib/python2.6/dist-packages/. The issue is that this >> directory is added to the path after the >> /usr/lib/python2.6/dist-packages/ is added, so python doesnt see my >> version of numpy. >> >> I have been combating this with a line in my .bashrc file: >> >> export PYTHONPATH=/usr/local/lib/python2.6/dist-packages >> >> So when I start python from the shell, everything works fine. >> >> Problems show up when python is not executed from the shell, and thus >> the path variable is never exported. This can occur when I have >> launcher in the gnome panel or i'm executing from within wing-ide. >> >> Is there a way to fix this so that the local dist-packages is added to >> sys.path before the system directory ALWAYS? I can do this by editing >> site.py but I think it's kind of bad form to do it this way. I feel >> there has to be a way to do this without root privileges. >> >> Any ideas? >> >> Cheers, >> >> Chris > > I think you can modify sys.path inside your application. > > Maybe this will work (at the top of your script): > > > import sys > sys.path[0] = "/usr/local/lib/python2.6/dist-packages" > > import numpy > > > PS. ?Say hi to Steven for me! > > ~Sean > -- > http://mail.python.org/mailman/listinfo/python-list > From lists at cheimes.de Sun Aug 30 12:29:22 2009 From: lists at cheimes.de (Christian Heimes) Date: Sun, 30 Aug 2009 18:29:22 +0200 Subject: Permanently adding to the Python path in Ubuntu In-Reply-To: <7f014ea60908291739r70f724fbw626c32265198b5ae@mail.gmail.com> References: <7f014ea60908291739r70f724fbw626c32265198b5ae@mail.gmail.com> Message-ID: <4A9AA8E2.50201@cheimes.de> Chris Colbert wrote: > Is there a way to fix this so that the local dist-packages is added to > sys.path before the system directory ALWAYS? I can do this by editing > site.py but I think it's kind of bad form to do it this way. I feel > there has to be a way to do this without root privileges. > > Any ideas? Have you read my blog entry about my PEP 370? http://lipyrary.blogspot.com/2009/08/how-to-add-new-module-search-path.html Christian From szport at gmail.com Sun Aug 30 12:37:49 2009 From: szport at gmail.com (zaur) Date: Sun, 30 Aug 2009 09:37:49 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0023d927$0$2930$c3e8da3@news.astraweb.com> <051da35f-efc2-4c4a-9b87-6d7db59c4529@t11g2000prh.googlegroups.com> Message-ID: <1345f68a-9f1f-4314-8b5d-dbd60a1b37a9@p23g2000vbl.googlegroups.com> On 30 ???, 15:49, Carl Banks wrote: > I think they (Derek and zaur) expect integer objects to be mutable. > > It's pretty common for people coming from "name is a location in > memory" languages to have this conception of integers as an > intermediate stage of learning Python's object system. ?Even once > they've understood "everything is an object" and "names are references > to objects" they won't have learned all the nuances of the system, and > might still (not unreasonably) think integer objects could be mutable. > > However, it'd be nice if all these people didn't post here whining > about how surprising and unintuitive it is and instead just said, "ah, > integers are immutable, got it", quietly to themselves. > > Carl Banks Very expressive. I use python many years. And many years I just took python int as they are. I am also not think about names as reference to objects and so on. So this isn't the case. From hendrik at microcorp.co.za Sun Aug 30 12:40:31 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 30 Aug 2009 18:40:31 +0200 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <200908301840.31248.hendrik@microcorp.co.za> On Sunday 30 August 2009 15:37:19 r wrote: > What makes you think that diversity is lost with a single language? I am quite sure of this - it goes deeper than mere regional differences - your first language forms the way you think - and if we all get taught the same language, then on a very fundamental level we will all think in a similar way, and that loss will outweigh the normal regional or cultural differences on which you would have to rely for your diversity. Philip Larkin has explained the effect better than I can: "They f*ck you up, your mom and dad, They do not mean to, but they do. They fill you with the faults they had, And add some extra, just for you." > I > say more pollination will occur and the seed will be more potent since > all parties will contribute to the same pool. I think this effect, while it might be real, would be swamped by the loss of the real diversity. > Sure there will be > idioms of different regions but that is to be expected. But at least > then i could make international crank calls without the language > barrier ;-) You can make crank calls _now_ without a language barrier - heavy breathing is a universally understood idiom. :-) - Hendrik From code at pizzashack.org Sun Aug 30 12:40:51 2009 From: code at pizzashack.org (Derek Martin) Date: Sun, 30 Aug 2009 11:40:51 -0500 Subject: Is behavior of += intentional for int? In-Reply-To: <0023d927$0$2930$c3e8da3@news.astraweb.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0023d927$0$2930$c3e8da3@news.astraweb.com> Message-ID: <20090830164050.GO20434@dragontoe.org> On Sun, Aug 30, 2009 at 10:34:17AM +0000, Steven D'Aprano wrote: > > He's saying that instead of thinking the integer value of 3 itself being > > the object, he expected Python's object model would behave as though the > > entity m is the object, and that object exists to contain an integer > > value. > What is "the entity m"? The entity m is an object. Objects, in computer science, are abstractions created by humans to make solving a large class of problems easier to think about. An object is a piece of data, upon which you can perform programmatic actions, which are grouped together with the values contained in that data. It's an abstraction which translates, in the physical sense, to a group of memory locations with a reference in a symbol table. > Ah wait, I think I get it... is m a memory location? No, it isn't. It is an abstraction in the programmer's mind that sits on top of some memory. For that matter, the memory location is itself an abstraction. It is not a memory location, but a particular series of circuits which either have current or don't. It is simply convenient for us to think of it as a memory location. > That would be how Pascal and C (and presumably other languages) > work, but not Python or Ruby or even VB (so I'm told) and similar > languages. Well, except that, in fact, they do work that way. They simply present a different abstraction to the programmer than C or other languages. They have to work that way, at the lowest level, because that is how the hardware works. > > Numbers are fundamentally different from objects. The number 3 is a > > symbol of the idea of the existence of three countable objects. It can > > not be changed > > Doesn't this contradict your claim that people expect to be able to > mutate numbers? That you should be able to do this? This is where you continually fail. There is no contradiction at all. What I'm saying is that in my view, numbers CAN'T mutate; they are not objects! They are values, which are a means of describing objects. Only the objects which hold the values can mutate. However in Python they don't, and can't, but they EASILY could with a different design. You, however, seem to be completely stuck on Python's behavior with regard to numeric objects, and fail to see past that. Python's model is only one abstraction, among multiple possibilities. > You can't have it both ways -- if people think of objects as > mutable, and think of numbers as not-objects and unchanging, then > why oh why would they find Python's numeric behaviour to be > unintuitive? Because in Python, they ARE objects, which they think should be mutable, but in Python when they try to change the *value* of the object, they don't get the same object with a different value; they get a completely different object. This is counter to their experience. If you don't like the Buick example, then use algebra. We've been down this road before, so I'm probably wasting my time... In algebra, you don't assign a name to a value, you assign a value to a variable. You can, in a different problem, assign a different value to that variable, but the variable didn't change; only its value did. In Python, it's the opposite. > What I think is that some people, such as you and Zaur, have *learned* > from C-like languages that numbers are mutable not-objects, and you've > learned it so well that you've forgotten that you ever needed to learn > it. No, this is precisely why I provided the real-world examples -- to illustrate to you that there was no need to learn it in computer science, because the concept applies in the real world quite intuitively in every-day situations. I think rather it is YOU who have learned the concept in Python, and since then fail to imagine any other possible interpretation of an object, and somehow have completely forgotten the examples you encountered before Python, from algebra and from the real world. > Human beings are excellent at reifying abstract things into (imaginary) > objects. I don't know what the word "reifying" means, but irrelevant. Such things are abstract, and in fact not objects. > No, the length of a car is an object which *is* a length, it doesn't > *have* a length. It is not an object. It is an abstract idea used as a description of an object. > None of this explains why you would expect to be able to mutate the > value three and turn it into four. Again, you fail. I *DO NOT* expect that. I expect to be able to mutate the object m, changing its value from 3 to 4. > I think you have confused yourself. No Steven, on this topic, it is only you who have been confused, perpetually. Although, it could be said that Python's idea of what an object is also is itself confused... Python (or at least the docs) actually refrains from formally defining an object. The docs only say that an object has an identity, a name, and a value. Well, OK... so 3 is an object. You can bind a name to it... except that's not exactly correct. You can bind many names to it, and every time you write something like: m = 3 You are binding another name to the same object. That's intuitive? So you say. But what is the value of 3? Is it 3? How can the value of an object be the object itself? If that were true, then the value of the object is an object, which has a value... you have an infinite recursion. It's a paradox. How could you get any more unintuitive than that?! In practice it's not a paradox, because the values inside numeric objects are *not* objects. They're numerical constants, as used by the hardware (excepting that they are just an abstraction on top of current, as noted before). Python's model breaks down at that point; it is not so with most other types of objects... their values remain objects. And *that* is inconsistent. The same is true of character data as for numeric data. And that, I believe, is why Java treats these as atomic data types, rather than as objects. Because they are, in fact. They are types of data that the hardware knows how to deal with, directly. Everything else is not. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From nobody at nowhere.com Sun Aug 30 12:42:40 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 30 Aug 2009 17:42:40 +0100 Subject: break unichr instead of fix ord? References: <2ad21a79-4a6c-42a7-8923-beb304bb5e99@v20g2000yqm.googlegroups.com> <4A95A4D1.9060008@v.loewis.de> <4A961EE1.9010103@v.loewis.de> <65e6c430-9dc4-4a90-8448-f8f587d19750@v20g2000yqm.googlegroups.com> <4a979172$0$11759$9b622d9e@news.freenet.de> Message-ID: On Sun, 30 Aug 2009 06:54:21 +0200, Dieter Maurer wrote: >> What you propose would break the property "unichr(i) always returns >> a string of length one, if it returns anything at all". > > But getting a "ValueError" in some builds (and not in others) > is rather worse than getting unicode strings of different length.... Not necessarily. If the code assumes that unichr() always returns a single-character string, it will silently produce bogus results when unichr() returns a pair of surrogates. An exception is usually preferable to silently producing bad data. If unichr() returns a surrogate pair, what is e.g. unichr(i).isalpha() supposed to do? Using surrogates is fine in an external representation (UTF-16), but it doesn't make sense as an internal representation. Think: why do people use wchar_t[] rather than a char[] encoded in UTF-8? Because a wchar_t[] allows you to index *characters*, which you can't do with a multi-byte encoding. You can't do it with a multi-*word* encoding either. UCS-2 and UTF-16 are superficially so similar that people forget that they're completely different beasts. UCS-2 is fixed-length, UTF-16 is variable-length. This makes UTF-16 semantically much closer to UTF-8 than to UCS-2 or UCS-4. If your wchar_t is 16 bits, the only sane solution is to forego support for characters outside of the BMP. The alternative is to process wide strings in exactly the same way that you process narrow (mbcs) strings; e.g. extracting character N requires iterating over the string from the beginning until you have counted N-1 characters. This provides no benefit over using narrow strings except for a slight performance gain from halving the number of iterations. You still end up with indexing being O(n) rather than O(1). From vbabiy86 at gmail.com Sun Aug 30 12:56:07 2009 From: vbabiy86 at gmail.com (Vitaly Babiy) Date: Sun, 30 Aug 2009 12:56:07 -0400 Subject: Thread Pool Message-ID: <8abf49ac0908300956x30d41685xfa1a383adb466aea@mail.gmail.com> Hey, Any one know of a good thread pool library. I have tried a few but they don't seem to clean up after them selfs well. Thanks, Vitaly Babiy -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhodri at wildebst.demon.co.uk Sun Aug 30 12:57:23 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Sun, 30 Aug 2009 17:57:23 +0100 Subject: Is behavior of += intentional for int? In-Reply-To: <1345f68a-9f1f-4314-8b5d-dbd60a1b37a9@p23g2000vbl.googlegroups.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0023d927$0$2930$c3e8da3@news.astraweb.com> <051da35f-efc2-4c4a-9b87-6d7db59c4529@t11g2000prh.googlegroups.com> <1345f68a-9f1f-4314-8b5d-dbd60a1b37a9@p23g2000vbl.googlegroups.com> Message-ID: On Sun, 30 Aug 2009 17:37:49 +0100, zaur wrote: > On 30 ???, 15:49, Carl Banks wrote: >> I think they (Derek and zaur) expect integer objects to be mutable. >> >> It's pretty common for people coming from "name is a location in >> memory" languages to have this conception of integers as an >> intermediate stage of learning Python's object system. ?Even once >> they've understood "everything is an object" and "names are references >> to objects" they won't have learned all the nuances of the system, and >> might still (not unreasonably) think integer objects could be mutable. >> >> However, it'd be nice if all these people didn't post here whining >> about how surprising and unintuitive it is and instead just said, "ah, >> integers are immutable, got it", quietly to themselves. >> >> Carl Banks > > Very expressive. > > I use python many years. And many years I just took python int as they > are. > I am also not think about names as reference to objects and so on. Then you are doomed to surprises such as this. -- Rhodri James *-* Wildebeest Herder to the Masses From sccolbert at gmail.com Sun Aug 30 13:03:19 2009 From: sccolbert at gmail.com (Chris Colbert) Date: Sun, 30 Aug 2009 13:03:19 -0400 Subject: Permanently adding to the Python path in Ubuntu In-Reply-To: <4A9AA8E2.50201@cheimes.de> References: <7f014ea60908291739r70f724fbw626c32265198b5ae@mail.gmail.com> <4A9AA8E2.50201@cheimes.de> Message-ID: <7f014ea60908301003q5f28776q88f5603a5f885358@mail.gmail.com> Great! That was the solution I was looking for. Thanks! Chris On Sun, Aug 30, 2009 at 12:29 PM, Christian Heimes wrote: > Chris Colbert wrote: >> Is there a way to fix this so that the local dist-packages is added to >> sys.path before the system directory ALWAYS? I can do this by editing >> site.py but I think it's kind of bad form to do it this way. I feel >> there has to be a way to do this without root privileges. >> >> Any ideas? > > Have you read my blog entry about my PEP 370? > http://lipyrary.blogspot.com/2009/08/how-to-add-new-module-search-path.html > > Christian > From code at pizzashack.org Sun Aug 30 13:04:45 2009 From: code at pizzashack.org (Derek Martin) Date: Sun, 30 Aug 2009 12:04:45 -0500 Subject: Is behavior of += intentional for int? In-Reply-To: <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> Message-ID: <20090830170445.GP20434@dragontoe.org> On Sun, Aug 30, 2009 at 03:42:06AM -0700, Paul McGuire wrote: > Python binds values to names. Always. No, actually, it doesn't. It binds *objects* to names. This distinction is subtle, but important, as it is the crux of why this is confusing to people. If Python is to say that objects have values, then the object can not *be* the value that it has, because that is a paradoxical self-reference. It's an object, not a value. > Is it any odder that 3 is an object than that the string literal > "Hello, World!" is an object? Yes. Because 3 is a fundamental bit of data that the hardware knows how to deal with, requiring no higher level abstractions for the programmer to use it (though certainly, a programming language can provide them, if it is convenient). "Hello, World!" is not. They are fundamentally different in that way. > For a Python long-timer like Mr. D'Aprano, I don't think he even > consciously thinks about this kind of thing any more; his intuition > has aligned with the Python stars, so he extrapolates from the OP's > suggestion to the resulting aberrant behavior, as he posted it. I'm sure that's the case. But it's been explained to him before, and yet he still can't seem to comprehend that not everyone immediately gets this behavior, and that this is not without good reason. So, since it *has* been explained to him before, it's somewhat astonishing that he would reply to zaur's post, saying that the behavior zaur described would necessarily lead to the insane behavior that Steven described. When he makes such statements, it's tantamount to calling the OP an idiot. I find that offensive, especially considering that Steven's post displayed an overwhelming lack of understanding of what the OP was trying to say. > You can dispute and rail at this core language concept if you like, > but I think the more entrenched you become in the position that "'3 is > an object' is bizarre", the less enjoyable your Python work will be. While I did genuinely find the behavior bizarre when I encountered it, and honestly still do, I learned it quickly and moved past it. I'm not suggesting that it be changed, and I don't feel particularly strongly that it even should change. It's not so much the language I'm railing against, but the humans... -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From code at pizzashack.org Sun Aug 30 13:27:57 2009 From: code at pizzashack.org (Derek Martin) Date: Sun, 30 Aug 2009 12:27:57 -0500 Subject: Is behavior of += intentional for int? In-Reply-To: <71e92f9c-4094-409d-95d7-9836737d4dc2@d34g2000vbm.googlegroups.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> <71e92f9c-4094-409d-95d7-9836737d4dc2@d34g2000vbm.googlegroups.com> Message-ID: <20090830172757.GQ20434@dragontoe.org> On Sun, Aug 30, 2009 at 03:52:36AM -0700, Paul McGuire wrote: > > It is surprising how many times we > > think things are "intuitive" when we really mean they are "familiar". > > Of course, just as I was typing my response, Steve D'Aprano beat me to > the punch. Intuition means "The power or faculty of attaining to direct knowledge or cognition without evident rational thought and inference." Very naturally, things which behave in a familiar manner are intuitive. Familiar and intuitive are very closely tied. Correspondingly, when things look like something familiar, but behave differently, they are naturally unintuitive. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From nobody at nowhere.com Sun Aug 30 13:30:48 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 30 Aug 2009 18:30:48 +0100 Subject: (Simple?) Unicode Question References: <332972a20908270939m57be4e51tc5785b880ec642b3@mail.gmail.com> <002269cb$0$2930$c3e8da3@news.astraweb.com> <0023693f$0$2930$c3e8da3@news.astraweb.com> Message-ID: On Sun, 30 Aug 2009 02:36:49 +0000, Steven D'Aprano wrote: >>> So long as your terminal has a sensible encoding, and you have a good >>> quality font, you should be able to print any string you can create. >> >> UTF-8 isn't a particularly sensible encoding for terminals. > > Did I mention UTF-8? > > Out of curiosity, why do you say that UTF-8 isn't sensible for terminals? I don't think I've ever seen a terminal (whether an emulator running on a PC or a hardware terminal) which supports anything like the entire Unicode repertoire, along with right-to-left writing, complex scripts, etc. Even support for double-width characters is uncommon. If your terminal can't handle anything outside of ISO-8859-1, there isn't any advantage to using UTF-8, and some disadvantages; e.g. a typical Unix tty driver will delete the last *byte* from the input buffer when you press backspace (Linux 2.6.* has the IUTF8 flag, but this is non-standard). Historically, terminal I/O has tended to revolve around unibyte encodings, with everything except the endpoints being encoding-agnostic. Anything which falls outside of that is a dog's breakfast; it's no coincidence that the word for "messed-up text" (arising from an encoding mismatch) was borrowed from Japanese (mojibake). Life is simpler if you can use a unibyte encoding. Apart from anything else, the failure modes tend to be harmless. E.g. you get the wrong glyph rather than two glyphs where you expected one. On a 7-bit channel, you get the wrong printable character rather than a control character (this is why ISO-8859-* reserves \x80-\x9F as control codes rather than using them as printable characters). >> And "Unicode font" is an oxymoron. You can merge a whole bunch of fonts >> together and stuff them into a TTF file; that doesn't make them "a >> font", though. > > I never mentioned "Unicode font" either. In any case, there's no reason > why a skillful designer can't make a single font which covers the entire > Unicode range in a consistent style. Consistency between unrelated scripts is neither realistic nor desirable. E.g. Latin fonts tend to use uniform stroke widths unless they're specifically designed to look like handwriting, whereas Han fonts tend to prefer variable-width strokes which reflect the direction. >> The main advantage of using Unicode internally is that you can associate >> encodings with the specific points where data needs to be converted >> to/from bytes, rather than having to carry the encoding details around >> the program. > > Surely the main advantage of Unicode is that it gives you a full and > consistent range of characters not limited to the 128 characters provided > by ASCII? Nothing stops you from using other encodings, or from using multiple encodings. But using multiple encodings means keeping track of the encodings. This isn't impossible, and it may produce better results (e.g. no information loss from Han unification), but it can be a lot more work. From code at pizzashack.org Sun Aug 30 13:36:17 2009 From: code at pizzashack.org (Derek Martin) Date: Sun, 30 Aug 2009 12:36:17 -0500 Subject: Is behavior of += intentional for int? In-Reply-To: <0221274c-994d-4130-93bb-a5fb528e7b83@x6g2000prc.googlegroups.com> References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <0221274c-994d-4130-93bb-a5fb528e7b83@x6g2000prc.googlegroups.com> Message-ID: <20090830173617.GR20434@dragontoe.org> On Sun, Aug 30, 2009 at 04:26:54AM -0700, Carl Banks wrote: > On Aug 30, 12:33?am, Derek Martin wrote: > [snip rant] I was not ranting. I was explaining a perspective. > > THAT is why Python's behavior with regard to numerical objects is > > not intuitive, and frankly bizzare to me, and I dare say to others who > > find it so. > > > > Yes, that's right. ?BIZZARE. > > You mean it's different from how you first learned it. I mean exactly that I find it "strikingly out of the ordinary; odd, extravagant, or eccentric in style or mode" as Webster's defines the word. Whether it is so because it is different from how I first learned it, or for some other reason, it is so nonetheless. I have elsewhere gone into great detail about why I find it so. If you need it to be simple, then feel free to simplify it. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From brenNOSPAMbarn at NObrenSPAMbarn.net Sun Aug 30 13:43:42 2009 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Sun, 30 Aug 2009 17:43:42 GMT Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> Message-ID: Derek Martin wrote: > If Python is to say that objects have values, > then the object can not *be* the value that it has, because that is a > paradoxical self-reference. It's an object, not a value. But does it say that objects have values? I don't see where you get this idea. Consider this code: class A(object): pass class B(object): x = 0 a = A() b = B() b2 = B() b2.x = a What is the "value" of the object now bound to the name "a"? What about the "value" of the object bound to b, or b2? I would say that in Python, objects do not have values. Objects are values. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From rt8396 at gmail.com Sun Aug 30 13:48:24 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 10:48:24 -0700 (PDT) Subject: IDE for python similar to visual basic References: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> Message-ID: <6cb48259-3e42-4efe-b856-7b0f1a141024@o21g2000vbl.googlegroups.com> On Aug 28, 5:19?pm, qwe rty wrote: > i have been searching for am IDE for python that is similar to Visual > Basic but had no luck.shall you help me please? Hello qwe rty, I remember my first days with GUI programming and thinking to myself; how on earth can i write GUI code without a MS style GUI builder? Not to long after that i was coding up some pretty spectacular GUI's from nothing more than source code and loving it. [Warning: the following is only opinion!] I think a point and click GUI builder (although some may disagree) is actually detrimental to your programming skills. The ability to visualize the GUI only from the source code as you read it, is as important to a programmer as site reading sheet music is to a musician. And I like to program with the training wheels off. From rozzin at geekspace.com Sun Aug 30 13:54:17 2009 From: rozzin at geekspace.com (Joshua Judson Rosen) Date: Sun, 30 Aug 2009 13:54:17 -0400 Subject: Non-deterministic computing (was: What python can NOT do?) References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <00223e3f$0$2930$c3e8da3@news.astraweb.com> Message-ID: <87ab1h192u.fsf_-_@slice.rozzin.com> Steven D'Aprano writes: > > On Sat, 29 Aug 2009 05:37:34 +0200, Tomasz Rola wrote: > > > My private list of things that when implemented in Python would be > > ugly to the point of calling it difficult: > > > > 1. AMB operator - my very favourite. In one sentence, either language > > allows one to do it easily or one would not want to do it (in an ugly > > way). > > > > http://www.randomhacks.net/articles/2005/10/11/amb-operator > > > Fascinating, but I don't exactly see how that's actually *useful*. It > strikes me of combining all the benefits of COME FROM with the potential > performance of Bogosort, but maybe I'm being harsh. There's a chapter on this (non-deterministic computing in general, and `amb' in particular) in Abelson's & Sussman's book, `Structure and Interpretation of Computer Programs': http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-28.html#%_sec_4.3 It's an interesting read (the chapter, as well as the rest of the book). > On the other hand, it sounds rather like Prolog-like declarative > programming. I fear that, like Prolog, it risks massive performance > degradation if you don't apply the constraints in the right order. One of the classic arguments in the other direction is that imperative programming (as is common in Python ;)) risks massive *incorrect results* if you don't apply the side-effects in the right order :) -- Don't be afraid to ask (Lf.((Lx.xx) (Lr.f(rr)))). From nobody at nowhere.com Sun Aug 30 13:54:22 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 30 Aug 2009 18:54:22 +0100 Subject: What python can NOT do? References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4a998465$0$1637$742ec2ed@news.sonic.net> Message-ID: On Sat, 29 Aug 2009 23:07:17 +0000, exarkun wrote: >>> Personally, I consider Python to be a good language held back by >>>too-close ties to a naive interpreter implementation and the lack >>>of a formal standard for the language. >> >>Name one language under active development that has not been harmed by a >>formal standard. (I think C doesn't count -- there was relatively little >>development of C after the standards process started.) > > I think you must mean "harmed by a formal standard more than it has been > helped", since that's clearly the interesting thing. > > And it's a pretty difficult question to answer. How do you quantify the > harm done to a language by a standarization process? How do you > quantify the help? These are extremely difficult things to measure > objectively. For a start, you have to decide how to weight the different groups of users. For an application which is designed for end users and will be in a permanent state of flux, dealing with revisions to the language or its standard libraries are likely to be a small part of the ongoing development effort. For libraries or middleware which need to maintain a stable interface, or for code which needs extensive testing, documentation, audits, etc, even a minor update can incur significant costs. Users in the latter group will prefer languages with a stable and rigorous specification, and will tend to view any flexibility granted to the language implementors as an inconvenience. From rt8396 at gmail.com Sun Aug 30 14:01:21 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 11:01:21 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <8252056f-399d-4da5-a1da-d09468eaf149@l35g2000vba.googlegroups.com> Would someone please point me to one example where this sociology or anthropology crap has ever improved our day to day lives or moved use into the future with great innovation? A life spend studying this mumbo-jumbo is a complete waste of time when many other far more important and *real* problems need solving! To me this is nothing more than educated people going antiquing on a Saturday afternoon! All they are going to find is more useless, overpriced junk that clogs up the closets of society! From nobody at nowhere.com Sun Aug 30 14:08:34 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 30 Aug 2009 19:08:34 +0100 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <4a9a0988$0$1669$742ec2ed@news.sonic.net> Message-ID: On Sat, 29 Aug 2009 22:14:55 -0700, John Nagle wrote: > (I wish the HTML standards people would do the same. HTML 5 > should have been ASCII only (with the "&" escapes if desired) > or Unicode. No "Latin-1", no upper code pages, no JIS, etc.) IOW, you want the HTML standards to continue to be meaningless documents, and "HTML" to continue to mean "what browsers support". Because that would be the likely consequence of such a stance. Japanese websites will continue to use Shift-JIS, Japanese cellphones (or Scandanavian cellphones aimed at the Japanese market, for that matter) will continue to render websites which use Shift-JIS, and HTML 5 will be just as much a pure academic exercise as all of the other HTML standards. From ivanko.rus at gmail.com Sun Aug 30 14:13:12 2009 From: ivanko.rus at gmail.com (ivanko.rus at gmail.com) Date: Sun, 30 Aug 2009 18:13:12 +0000 Subject: a popen question. Please help In-Reply-To: <473423.84282.qm@web36903.mail.mud.yahoo.com> Message-ID: <000e0cd20f80cbfb7e04725fde8e@google.com> First, I think you should use subprocess.Popen (it's recommended by PEP-324) instead of os.popen. For example: p = subprocess.Popen(["top"], stdout = PIPE) p.stdout.readlines() And to write to stdin (in your case "q") you can use p.stdin.write("q"), or terminate the process with p.terminate(), or just specify the -n option (the number of iterations) to the value you desire. It's done in that way: subprocess.Popen(["top","-n 1"], stdout=PIPE) -------------- next part -------------- An HTML attachment was scrubbed... URL: From nobody at nowhere.com Sun Aug 30 14:13:38 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 30 Aug 2009 19:13:38 +0100 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> Message-ID: On Sun, 30 Aug 2009 11:18:35 +0200, David wrote: >> So much of it could be removed even by simple keyword filtering. > > I think there is only one final solution to the spam pestilence: a tiny tax > on email and posts. > Spammers send hundreds of thousands of emails/posts a day and a tax of > 0.0001$ each does not harm normal users but discurages spammers. Apart from the impossibility of implementing such a tax, it isn't going to discourage spammers when the tax will be paid by the owner of the compromised PC from which they're sending their spam. If you want to avoid usenet spam and don't want to filter it yourself, find a provider with more aggressive spam filter. Ultimately, it's up to the person running the news server as to which posts they will or will not accept. From code at pizzashack.org Sun Aug 30 14:21:09 2009 From: code at pizzashack.org (Derek Martin) Date: Sun, 30 Aug 2009 13:21:09 -0500 Subject: Is behavior of += intentional for int? In-Reply-To: References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> Message-ID: <20090830182109.GS20434@dragontoe.org> On Sun, Aug 30, 2009 at 05:43:42PM +0000, OKB (not okblacke) wrote: > Derek Martin wrote: > > > If Python is to say that objects have values, > > then the object can not *be* the value that it has, because that is a > > paradoxical self-reference. It's an object, not a value. > > But does it say that objects have values? I don't see where you > get this idea. Yes, it does say that. Read the docs. :) http://docs.python.org/reference/datamodel.html (paragraph 2) > class A(object): > pass > a = A() > > What is the "value" of the object now bound to the name "a" In Python, the value of objects depends on the context in which it is evaluated. But when you do that, you're not getting a value that is equivalent to object, but of some property of the object. The object has no intrinsic value until it is evaluated. In that sense, and as used by the python docs, I would say that the value of the object a is "true" -- you can use it in boolean expressions, and it will evaluate as such. > I would say that in Python, objects do not have values. > Objects are values. You can say that, but if you do you're using some definition of "value" that's only applicable in Python and programming languages which behave the same way. It would be more correct to say that an object is a collection of arbitrary data, which has a type and an identity, and that the data in that collection has a value that evaluates in context. An object is an abstract collection of data, and abstractions have no value. You can not measure them in any meaningful way. The data contained in the collection does, however, have a value. When you reference an object in an expression, what you get is not the value of the object, but the value of some peice of data about, or contained in, that object. It is this property of objects, that the value evaluated depends on the context, that I think demonstrates that an object is *not* a value. Values never change, as we've said in this thread: 3 is always 3. 'a' is always 'a'. But an object x can evaluate to many different values, depending on how it is used. The definition of the object would need to allow for it to do so, but Python allows that, and even encourages it. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From rolfpw at online.de Sun Aug 30 14:33:41 2009 From: rolfpw at online.de (Rolf) Date: Sun, 30 Aug 2009 20:33:41 +0200 Subject: How to install setuptools...egg? In-Reply-To: <6ee4ad7f-7e78-42cb-8f0b-198f32c08b6d@i18g2000pro.googlegroups.com> References: <6ee4ad7f-7e78-42cb-8f0b-198f32c08b6d@i18g2000pro.googlegroups.com> Message-ID: Mike schrieb: >> I would like to install setuptools for Python2.6 on Windows. > > 1. Download setuptools-0.6c9-py2.6.egg > 2. Download setuptools-0.6c9.tar.gz > 3. Use 7-zip from http://www.7-zip.org/ to extract ez_setup.py from > setuptools-0.6c9.tar.gz > 4. In a directory that contains setuptools-0.6c9-py2.6.egg and > ez_setup.py run the command python ez_setup.py > 5. Add C:\Python26\Scripts to your path to run easy_install > > Mike Thank you very much. Your recipe did the job. Rolf From steve at REMOVE-THIS-cybersource.com.au Sun Aug 30 14:37:38 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 30 Aug 2009 18:37:38 GMT Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> Message-ID: <00244a72$0$2930$c3e8da3@news.astraweb.com> On Sun, 30 Aug 2009 12:04:45 -0500, Derek Martin wrote: > On Sun, Aug 30, 2009 at 03:42:06AM -0700, Paul McGuire wrote: >> Python binds values to names. Always. > > No, actually, it doesn't. It binds *objects* to names. This > distinction is subtle, but important, as it is the crux of why this is > confusing to people. If Python is to say that objects have values, then > the object can not *be* the value that it has, because that is a > paradoxical self-reference. It's an object, not a value. You're thinking about this too hard and tying yourself in knots trying to philosophise about it. In context of OO programming, the distinction between objects and values is fuzzy, and it depends on the context: e.g. if I have this: class MyInt(int): pass five = MyInt(5) five.thingy = 23 is thingy part of the value of the object or not? For most objects, at least for built-ins, the object *is* the value. (For custom classes you create yourself, you are free to do anything you like.) There's no need to try to distinguish between the object 3 and the value of the object 3: you're looking for a distinction that simply doesn't matter. >> Is it any odder that 3 is an object than that the string literal >> "Hello, World!" is an object? > > Yes. Because 3 is a fundamental bit of data that the hardware knows how > to deal with, requiring no higher level abstractions for the programmer > to use it (though certainly, a programming language can provide them, if > it is convenient). "Hello, World!" is not. They are fundamentally > different in that way. Nonsense on two levels. Firstly, in Python, *both* 3 and "Hello World" are complex objects, and neither are even close to the fundamental bits of data that the hardware can deal with. Secondly, in low level languages, both are nothing but a sequence of bytes, and hardware knows how to deal with bytes regardless of whether they are interpreted by the human reader as 3 or "Hello World". The compiler might stop you from adding 2371 to "Hell" or "o Wor" but the hardware would be perfectly happy to do so if asked. >> For a Python long-timer like Mr. D'Aprano, I don't think he even >> consciously thinks about this kind of thing any more; his intuition has >> aligned with the Python stars, so he extrapolates from the OP's >> suggestion to the resulting aberrant behavior, as he posted it. > > I'm sure that's the case. But it's been explained to him before, and > yet he still can't seem to comprehend that not everyone immediately gets > this behavior, and that this is not without good reason. Oh, it's obvious that not everybody gets this behaviour. I understand full well that it's different to some other languages, but not all, and so some people have their expectations violated. > So, since it *has* been explained to him before, it's somewhat > astonishing that he would reply to zaur's post, saying that the behavior > zaur described would necessarily lead to the insane behavior that Steven > described. When he makes such statements, it's tantamount to calling > the OP an idiot. Given Python's programming model and implementation, the behaviour asked for *would* lead to the crazy behaviour I described. (For the record, some early implementations of Fortran allowed the user to redefine literals like that, and I'm told that Lisp will do so too.) So what Zaur presumably saw as a little tiny difference is in fact the tip of the iceberg of a fairly major difference. I don't know how smart he is, but I'd be willing to bet he hadn't thought through the full consequences of the behaviour he'd prefer, given Python's execution model. You could make a language that behaved as he wants, and I wouldn't be surprised if Java was it, but whatever it is, it isn't Python. > I find that offensive, It's moments like this that I am reminded of a quote from Stephen Fry: "You're offended? So f***ing what?" Taking offense at an intellectual disagreement over the consequences of changes to a programming model is a good sign that you've got no rational argument to make and so have to resort to (real or pretend) outrage to win points. > especially considering that > Steven's post displayed an overwhelming lack of understanding of what > the OP was trying to say. I'm pretty sure I do understand what the OP was trying to say. He actually managed to communicate it very well. I think he expects to be able to do this: >>> n = 1 >>> id(n) 123456 >>> n += 1 >>> assert n == 2 >>> id(n) 123456 Do you disagree? What do *you* think he wants? -- Steven From paul at boddie.org.uk Sun Aug 30 15:05:54 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Sun, 30 Aug 2009 12:05:54 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> Message-ID: <1ab2c088-bead-43fa-bf4a-3e7f4d84e871@g1g2000vbr.googlegroups.com> On 30 Aug, 18:00, r wrote: > > Hold the phone Paul you are calling me a retarded bigot and i don't > much appreciate that. I think you are completely misinterpreting my > post. i and i ask you read it again especially this part... I didn't call you a "retarded bigot", and yet I did read your post. [...] > I don't really care what language we adopt as long as we choose *only* > one and then seek to perfect it to perfection. And also that this > *one* language use simplicity as it's model. English sucks, but > compared to traditional Chinese and Egyptian Hieroglyphs it's a god > send. You don't care which language it is as long as it's the one you use. That's what this sounds like, layered on top of what you've already written (and what you write below). How about Esperanto? You have heard of Esperanto, right? Or take your pick from the other artificial languages - they're relatively popular in some places where English isn't the natural first-choice foreign language. [...] > Look history is great but i am more concerned with the future. Learn > the lessons of the past, move on, and live for the future. If you want > to study the hair styles of Neanderthal women be my guest. Anybody > with half a brain knows the one world government and language is > coming. Why stop evolution, it is our destiny and it will improve the > human experience. Again, we witness a distortion of scientific concepts through the use of political themes. > [Warning: facts of life ahead!!] Even Xah Lee's harshest critics must acknowledge that Xah delivers a less offensive, more entertaining rant than this. At least Xah has mastered the art of the expletive. > I'll bet you weep and moan for the native Americans who where > slaughtered don't you? Yes they suffered a tragic death as have many > poor souls throughout history and yes they also contributed to human > history and experience, but their time had come and they can only > blame themselfs for it. You're on a slippery slope when you claim that people deserve whatever mistreatment or misfortune comes their way through mere circumstances of birth. I suggest you step back and actually read your messages again and consider how others might interpret them. I also suggest that, unless you really wish to discuss deficiencies of Unicode with respect to Python, you don't use this list/group as a discussion forum for your ill-informed notions of "progress", but instead take them to a more appropriate forum where I'm sure people will be happy to scrutinise your ideas at their leisure. Paul From sebas0 at gmail.com Sun Aug 30 15:33:15 2009 From: sebas0 at gmail.com (Sebastian) Date: Sun, 30 Aug 2009 16:33:15 -0300 Subject: Popen question (redundant processes) Message-ID: Hello World! This is my first post on the list and I'm hoping it is the right forum and not OT, I've searched a bit on this, but, none-the-wiser! My question is on the Popen method, here is my snippet: p1 = Popen(["cat", "georgi_ddr7_allmag_kcor_in_test.dat"], stdout=PIPE ) > p2 = Popen(["fit_coeffs"], stdin=p1.stdout, stdout=PIPE) > p3 = Popen(["reconstruct_maggies"], stdin=p2.stdout,stdout=PIPE) > output_maggies_z=p3.communicate()[0] > > p1 = Popen(["cat", "georgi_ddr7_allmag_kcor_in_test.dat"], stdout=PIPE ) > p2 = Popen(["fit_coeffs"], stdin=p1.stdout, stdout=PIPE) > p4 = Popen(["reconstruct_maggies", "--band-shift", "0.1", "--redshift", > "0."], stdin=p2.stdout,stdout=PIPE) > output_maggies_z0=p4.communicate()[0] > > That is, p1 and p2 are the same, but p3 and p4 which they are passed to, are different. Is there a way to pass p1 and p2 to p3 AND p4 simultaneously, so as to not need to run p1 and p2 twice, as above? What arguments would I need to achieve this? NOTE: "georgi_ddr7_allmag_kcor_in_test.dat" is a very large file (~1E6 records) regards, - Sebastian -------------- next part -------------- An HTML attachment was scrubbed... URL: From aahz at pythoncraft.com Sun Aug 30 15:33:29 2009 From: aahz at pythoncraft.com (Aahz) Date: 30 Aug 2009 12:33:29 -0700 Subject: Overriding iadd for dictionary like objects References: <87ws4n5gfi.fsf@slice.rozzin.com> Message-ID: In article , RunThePun wrote: > >I made a DictMixin where the keys are filenames and the values are the >file contents. It was very simple and easy to do thanks to DictMixin. > >For example this code writes "abc" in a file named "temp.txt" and >prints the contents of the file named "swallow", these files are >looked up/created/deleted in the directory "spam": >>>> d =3D FilesDict('spam') >>>> d['temp.txt'] =3D 'abc' >>>> print(d['swallow']) > >My problem arose when I wanted to append a string to a file which >using open(..., 'ab') would have been miles more efficient because I >wouldn't have to read the entire file (__getitem__) and then write the >entire file back (__setitem__). The files are expected to be as big as >600 KB which will be appended 30 bytes at a time about 3 times a >second. Performance-wise the system would probably work without open >(..., 'ab') but it would be a real thrashing so the current solution >uses a method "AddTo" as Robert suggested, sacrificing the neat >getitem/setitem syntax. You can do mostly what you want, I think, by having __setitem__() convert string values into FileProxy() objects that have an appropriate __iadd__() method. That brings a whole new set of problems, of course. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From apt.shansen at gmail.com Sun Aug 30 15:43:44 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 30 Aug 2009 12:43:44 -0700 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: <7a9c25c20908301243r71fa3376uac02a0000e2ac27e@mail.gmail.com> > > So why the heck are we supporting such capitalistic implementations as > Unicode. Sure we must support a winders installer but Unicode, dump > it! We don't support a Python group in Chinese or French, so why this? > Makes no sense to me really. Let M$ deal with it. > Who, exactly, do you think "we" are? You're off talking about The Python Community again, aren't you. I thought we talked about that. "We" are a group of diverse people from diverse backgrounds-- national and linguistic-- and quite a few who either run our own business or are connected to businesses. A very huge chunk of folk around here quite like capitalistic implementations. Python's very business and closed-source friendly, remember? This "crusade change the world" crap is so strikingly stupid of a troll approach for this group, I'm startled that it's worked. But it has, so kudos to you! Can't you go try to get someone fired up who has some philosophical basis in the group's existence? Python's not the FSF*. It's not software-for-freedom to change the world. It's software to get things done, and keep things done down the road. ... sigh. I fed the troll. --S P.S. *And I mean no insult by this towards the FSFL. It's a political/philosophical for-the-good-of-humanity organization, is all. Good for them. -------------- next part -------------- An HTML attachment was scrubbed... URL: From apt.shansen at gmail.com Sun Aug 30 15:55:22 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 30 Aug 2009 12:55:22 -0700 Subject: Thread Pool In-Reply-To: <8abf49ac0908300956x30d41685xfa1a383adb466aea@mail.gmail.com> References: <8abf49ac0908300956x30d41685xfa1a383adb466aea@mail.gmail.com> Message-ID: <7a9c25c20908301255p13112f64q90a94a9e99fe125@mail.gmail.com> On Sun, Aug 30, 2009 at 9:56 AM, Vitaly Babiy wrote: > Hey, > Any one know of a good thread pool library. I have tried a few but they > don't seem to clean up after them selfs well. > > Thanks, > Vitaly Babiy > > As obscene as it seems, I actually use twisted's :) I mean, it's obscene not because it's badly done or anything, but because to use twisted to do threads sounds terribly wrong. But I have twisted installed anyway for a different purpose, so figured why not. It seems to work fine / scale well / clean up fine (assuming my code is correct). --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From bouncyinc at gmail.com Sun Aug 30 16:06:22 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sun, 30 Aug 2009 14:06:22 -0600 Subject: Thread Pool In-Reply-To: <7a9c25c20908301255p13112f64q90a94a9e99fe125@mail.gmail.com> References: <8abf49ac0908300956x30d41685xfa1a383adb466aea@mail.gmail.com> <7a9c25c20908301255p13112f64q90a94a9e99fe125@mail.gmail.com> Message-ID: twisted? I don't get it On Sun, Aug 30, 2009 at 1:55 PM, Stephen Hansen wrote: > > On Sun, Aug 30, 2009 at 9:56 AM, Vitaly Babiy wrote: > >> Hey, >> Any one know of a good thread pool library. I have tried a few but they >> don't seem to clean up after them selfs well. >> >> Thanks, >> Vitaly Babiy >> >> > As obscene as it seems, I actually use twisted's :) > > I mean, it's obscene not because it's badly done or anything, but because > to use twisted to do threads sounds terribly wrong. But I have twisted > installed anyway for a different purpose, so figured why not. It seems to > work fine / scale well / clean up fine (assuming my code is correct). > > --S > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From luke.leighton at googlemail.com Sun Aug 30 16:17:56 2009 From: luke.leighton at googlemail.com (lkcl) Date: Sun, 30 Aug 2009 13:17:56 -0700 (PDT) Subject: port of GWT GChart to python pyjamas Message-ID: the excellent GWT Chart Library, GChart: http://code.google.com/p/gchart/ is being ported to python, to run under the pyjamas [desktop / web] widget set: http://pyjamas.svn.sourceforge.net/viewvc/pyjamas/trunk/library/pyjamas/chart/ approximately 15 of the 30 examples and 1 of the 90 test charts have been ported already, enough to show that the libray is in a mostly useable state, even after only three days. pie-charts are proving slightly problematic (as GChartExample24, which is a pie chart editor, shows). on the TODO list is: * the rest of the examples and test charts * GWT's NumberFormat (a basic one is in place right now) * GWT's DateFormat (a basic one is in place right now) * a basic implementation of re.py (for use in pyjs) * a port of http://code.google.com/p/gwt-canvas/ (for GChart optimisation purposes) conversion of the examples from java to python is pretty straightfoward: pyjamas/contrib/java2py.py is a _very_ basic java to python converter which takes care of the majority of the global/search/ replace tricks, and also it converts all { } matched braces into the correct python indentation levels. when using java2py.py, it relies on well-formatted code (which 99.9% of GWT is, and 99.5% of GChart is). code MUST be converted to actually _have_ braces, so a single- line "if" statement will give a great deal of grief: pre-editing of the java code is therefore sometimes required. please note: no real experience of java programming is required to convert java into python with java2py.py. if anyone would like to help out with this porting project, feel free to check out the source code and submit patches to http://code.google.com/p/pyjamas/issues and contact http://groups.google.com/group/pyjamas-dev/ From apt.shansen at gmail.com Sun Aug 30 16:18:19 2009 From: apt.shansen at gmail.com (Stephen Hansen) Date: Sun, 30 Aug 2009 13:18:19 -0700 Subject: Thread Pool In-Reply-To: References: <8abf49ac0908300956x30d41685xfa1a383adb466aea@mail.gmail.com> <7a9c25c20908301255p13112f64q90a94a9e99fe125@mail.gmail.com> Message-ID: <7a9c25c20908301318n742de97bydb8c9f9e63219069@mail.gmail.com> On Sun, Aug 30, 2009 at 1:06 PM, John Haggerty wrote: > twisted? I don't get it > Twisted. Big library / framework for network'd applications. Specifically, asynchronous network'd applications, really. --S -------------- next part -------------- An HTML attachment was scrubbed... URL: From clp2 at rebertia.com Sun Aug 30 16:25:40 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 30 Aug 2009 13:25:40 -0700 Subject: Popen question (redundant processes) In-Reply-To: References: Message-ID: <50697b2c0908301325w67af40a0lfbde8418f4a89e5f@mail.gmail.com> On Sun, Aug 30, 2009 at 12:33 PM, Sebastian wrote: > Hello World! > This is my first post on the list and I'm hoping it is the right forum and > not OT, I've searched > a bit on this, but, none-the-wiser! > > My question is on the Popen method, here is my snippet: > >> p1 = Popen(["cat", "georgi_ddr7_allmag_kcor_in_test.dat"], stdout=PIPE ) >> p2 = Popen(["fit_coeffs"], stdin=p1.stdout, stdout=PIPE) >> p3 = Popen(["reconstruct_maggies"], stdin=p2.stdout,stdout=PIPE) >> output_maggies_z=p3.communicate()[0] >> >> p1 = Popen(["cat", "georgi_ddr7_allmag_kcor_in_test.dat"], stdout=PIPE ) >> p2 = Popen(["fit_coeffs"], stdin=p1.stdout, stdout=PIPE) >> p4 = Popen(["reconstruct_maggies", "--band-shift", "0.1", "--redshift", >> "0."], stdin=p2.stdout,stdout=PIPE) >> output_maggies_z0=p4.communicate()[0] >> > > That is, p1 and p2 are the same, but p3 and p4 which they are passed to, are > different. > Is there a way to pass p1 and p2 to p3 AND p4 simultaneously, so as to not > need to > run p1 and p2 twice, as above? > What arguments would I need to achieve this? > > NOTE: "georgi_ddr7_allmag_kcor_in_test.dat" is a very large file (~1E6 > records) Send the output of p2 through the unix command "tee" (http://unixhelp.ed.ac.uk/CGI/man-cgi?tee). Then put the output of tee into p3 and set p4's input to the file you specified to tee. Cheers, Chris -- http://blog.rebertia.com From exallion.long at gmail.com Sun Aug 30 16:33:45 2009 From: exallion.long at gmail.com (Mug) Date: Sun, 30 Aug 2009 13:33:45 -0700 (PDT) Subject: initilize a memory zone in python Message-ID: hello, i'm new in python, i used to program in C, i have a small problem, i tryed to do some serial port things manipulation with python. i have something like: import sys,termios fd = sys.stdin.fileno() term_conf=termios.tcgetattr(fd); now i want to modify the actuall values in term_conf zone to zero i don't see how to do it, in C we can do : bzero(&term_conf,sizeof(struct termios)); i want to know if it exist a similar function in python, thanks From pavlovevidence at gmail.com Sun Aug 30 16:52:29 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Sun, 30 Aug 2009 13:52:29 -0700 (PDT) Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> <71e92f9c-4094-409d-95d7-9836737d4dc2@d34g2000vbm.googlegroups.com> Message-ID: <8562f607-7bef-422b-b716-487af7c73abc@k13g2000prh.googlegroups.com> On Aug 30, 10:27?am, Derek Martin wrote: > On Sun, Aug 30, 2009 at 03:52:36AM -0700, Paul McGuire wrote: > > > It is surprising how many times we > > > think things are "intuitive" when we really mean they are "familiar". > > > Of course, just as I was typing my response, Steve D'Aprano beat me to > > the punch. > > Intuition means "The power or faculty of attaining to direct knowledge > or cognition without evident rational thought and inference." ?Very > naturally, things which behave in a familiar manner are intuitive. > Familiar and intuitive are very closely tied. ?Correspondingly, when > things look like something familiar, but behave differently, they are > naturally unintuitive. *You* find something unfamiliar, and by your logic that means it's unintuitive for everyone? Nice logic there, chief. Presumptuous much? Carl Banks From deets at nospam.web.de Sun Aug 30 16:58:54 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 30 Aug 2009 22:58:54 +0200 Subject: initilize a memory zone in python In-Reply-To: References: Message-ID: <7g07ghF2ngfq1U1@mid.uni-berlin.de> Mug schrieb: > hello, i'm new in python, i used to program in C, > i have a small problem, i tryed to do some serial port things > manipulation > with python. > i have something like: > > import sys,termios > > fd = sys.stdin.fileno() > term_conf=termios.tcgetattr(fd); > > now i want to modify the actuall values in term_conf zone to zero > i don't see how to do it, > in C we can do : bzero(&term_conf,sizeof(struct termios)); > i want to know if it exist a similar function in python, thanks In python you don't modify memory like that. For the above function, you pass a value as the one you got to tcgetattr, with values modified as you desire them. Diez From nobody at nowhere.com Sun Aug 30 17:12:49 2009 From: nobody at nowhere.com (Nobody) Date: Sun, 30 Aug 2009 22:12:49 +0100 Subject: IDE for python similar to visual basic References: <2a17396c-4d6d-4cb0-a314-208054a2f774@z31g2000yqd.googlegroups.com> <6cb48259-3e42-4efe-b856-7b0f1a141024@o21g2000vbl.googlegroups.com> Message-ID: On Sun, 30 Aug 2009 10:48:24 -0700, r wrote: > I think a point and click GUI builder (although some may disagree) is > actually detrimental to your programming skills. The ability to > visualize the GUI only from the source code as you read it, is as > important to a programmer as site reading sheet music is to a > musician. And I like to program with the training wheels off. The main advantage of a GUI builder is that it helps prevent you from hard-coding the GUI into the program. You could get the same effect by coding a UIL/XRC/etc file manually, but a GUI builder tends to force it. It also allows the GUI to be edited by without requiring any programming knowledge. This eliminates the need for the GUI designer to be familiar with the programming language used (or any programming language), and allows customisation by end users. Creating a GUI programmatically is almost always the wrong approach. It tends to be adopted due to a path of least resistance, rather than any affirmative reason. From 71david at libero.it Sun Aug 30 17:23:20 2009 From: 71david at libero.it (David) Date: Sun, 30 Aug 2009 23:23:20 +0200 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> Message-ID: Il Sun, 30 Aug 2009 19:13:38 +0100, Nobody ha scritto: > Apart from the impossibility of implementing such a tax, it isn't going to > discourage spammers when the tax will be paid by the owner of the > compromised PC from which they're sending their spam. I don't agree. Each computer connected to internet is phisically connected to a carrer's hub. Each carrier can easily count smtp packets of each user as they can detect, filter and in some nations prosecute, p2p users. The owner of compromised PC should be responsible of his computer like the owner of a car is responsible of damages caused by its car. That owner should keep his computer clean as he *must* keep his car functional and safe. Today most of the people consider cyber security an optional, but all of us pay for their negligence. Those people are externalizing to the rest of the world their costs in terms of SO updating, antivirus, firewall and knowledge. This is unfair. This is mainly a matter of sensibility and culture: in '50/60s active and passive car safety was an optional, today is a must. I think it's time to switch to responsible computing and the mail-tax would charge each person of its own costs and annoyances without affectig the rest of the world. > > If you want to avoid usenet spam and don't want to filter it yourself, > find a provider with more aggressive spam filter. This is not the solution. You are saying that if your neighbour makes loud noises you can not call police to impose him to cease but you can only make your home soundproof. > Ultimately, it's up to > the person running the news server as to which posts they will or will not > accept. Are you suggesting to moderate every news server and mail server all over the world? THIS is impossible! D. From bouncyinc at gmail.com Sun Aug 30 17:30:57 2009 From: bouncyinc at gmail.com (John Haggerty) Date: Sun, 30 Aug 2009 15:30:57 -0600 Subject: Sending email In-Reply-To: References: <7fpj9tF2clhemU1@mid.individual.net> <2b3621fd-53fc-4f20-a048-3608894e52af@o9g2000prg.googlegroups.com> <7fq7aiF2mp83gU1@mid.individual.net> Message-ID: I would concur On Fri, Aug 28, 2009 at 9:49 AM, 7stud wrote: > On Aug 28, 8:18 am, Fencer > wrote: > > 7stud wrote: > > > > [snip] > > > > Thanks for your reply. After consulting the sysadmins here I was able to > > get it to work. > > > > - Fencer > > > Ok, but how about posting your code so that a future searcher will not > be left screaming, "WHAT THE EFF WAS THE SOLUTION!!" > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From barcaroller at music.net Sun Aug 30 17:37:11 2009 From: barcaroller at music.net (barcaroller) Date: Sun, 30 Aug 2009 17:37:11 -0400 Subject: PyGTK problems after Linux update... References: <7fq56dF2m6qlbU1@mid.individual.net> Message-ID: "Thomas Guettler" wrote in message news:7fq56dF2m6qlbU1 at mid.individual.net... > Looks like your pygtk package does not fit to the installed python > package. Okay, I won't disagree, but I how do if fix this? From exallion.long at gmail.com Sun Aug 30 17:59:50 2009 From: exallion.long at gmail.com (Mug) Date: Sun, 30 Aug 2009 14:59:50 -0700 (PDT) Subject: initilize a memory zone in python References: <7g07ghF2ngfq1U1@mid.uni-berlin.de> Message-ID: <18627379-8056-4ee9-b3b8-d5fd4cd0590c@y20g2000vbk.googlegroups.com> On Aug 30, 8:58?pm, "Diez B. Roggisch" wrote: > Mug schrieb: > > > hello, i'm new in python, i used to program in C, > > i have a small problem, i tryed to do some serial port things > > manipulation > > with python. > > i have something like: > > > import sys,termios > > > fd = sys.stdin.fileno() > > term_conf=termios.tcgetattr(fd); > > > now i want to modify the actuall values in term_conf ?zone to zero > > i don't see how to do it, > > in C we can do : bzero(&term_conf,sizeof(struct termios)); > > i want to know if it exist a similar function in python, thanks > > In python you don't modify memory like that. > > For the above function, you pass a value as the one you got to > tcgetattr, with values modified as you desire them. i tryed print term_conf and i saw that the term_conf is actually represent with an array in python: zsh/3 4201 [1] % python test.py [27906, 5, 1215, 35387, 15, 15, ['\x03', '\x1c', '\x7f', '\x15', '\x04', '\x00', '\x01', '\xff', '\x11', '\x13', '\x1a', '\xff', '\x12', '\x0f', '\x17', '\x16', '\xff', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00']] it's a array of 7 elements, with the seventh element it self a array, so in order to initialize them to zero, there's no other way than modify them one by one in a loop? is there a fonction like "memset" or "bzero" in python? > > Diez From tjreedy at udel.edu Sun Aug 30 18:24:00 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Aug 2009 18:24:00 -0400 Subject: quantiles of a student distribution In-Reply-To: References: Message-ID: Pierre wrote: > Hello... > > Do you know how I can calculate the quantiles of a student > distribution in pyhton ? Try searching the net for 'Python student distribution quantiles' From rt8396 at gmail.com Sun Aug 30 18:28:55 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 15:28:55 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <1ab2c088-bead-43fa-bf4a-3e7f4d84e871@g1g2000vbr.googlegroups.com> Message-ID: <59cad1ba-1162-4227-9375-d132ef030a7b@d21g2000vbm.googlegroups.com> On Aug 30, 2:05?pm, Paul Boddie wrote: (snip) > You don't care which language it is as long as it's the one you use. > That's what this sounds like, layered on top of what you've already > written (and what you write below). I said it before and i will say it again. I DON"T CARE WHAT LANGUAGE WE USE AS LONG AS IT IS A MODERN LANGUAGE FOUNDED ON IDEALS OF SIMPLICITY!!!! > How about Esperanto? You have > heard of Esperanto, right? Or take your pick from the other artificial > languages - they're relatively popular in some places where English > isn't the natural first-choice foreign language. English is by far already the de-facto lingua franca throughout the world. However it has many shortcommings. The most prevalent being idiotic pronunciation. You can thank neo-nazi-linguist and your third grade language teachers for this brainwashing. Academias raping of languages has been going on for centuries. > > Look history is great but i am more concerned with the future. Learn > > the lessons of the past, move on, and live for the future. If you want > > to study the hair styles of Neanderthal women be my guest. Anybody > > with half a brain knows the one world government and language is > > coming. Why stop evolution, it is our destiny and it will improve the > > human experience. > > Again, we witness a distortion of scientific concepts through the use > of political themes. You can deny the holocaust all you want but it still happened and so too shall the great unity! Sadly because of cultural and social fanatics like yourself, it will probably take another great war to usher in the new order. > Even Xah Lee's harshest critics must acknowledge that Xah delivers a > less offensive, more entertaining rant than this. At least Xah has > mastered the art of the expletive. So you are advocating for me to use derogatory statements in my post, no thanks i need not resort to adolescent rants to argue my points. And why do you continue to compare me to XL. Has XL *ever* helped a python user in this forum? I have, many times. I am *actually* a python programmer who cares about Python and my posts bring much vigor and intelligence to an otherwise boring NG -- like me or not. > You're on a slippery slope when you claim that people deserve whatever > mistreatment or misfortune comes their way through mere circumstances > of birth. I suggest you step back and actually read your messages > again and consider how others might interpret them. Paul: civilizations rise and fall, this is beyond our control. Every great power will utter fail at some point. Some die out like a slow burning candle, others go quickly and painfully from defeating blows in war time. This is an eventuality you must face friend. This whole save the whales BS is really getting on my nerves! Stop trying to play God Paul, it is not your decision when and where the blade shall fall. When a people stop evolving and no longer have anything productive to give to evolution, evolution stamps them out. If the Indians had developed gun power and industrialized America they might be running more than merely a casino. Oh No! Was that out of line, you will probably think so. Stay in know and you shall endure... From tjreedy at udel.edu Sun Aug 30 18:31:42 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Aug 2009 18:31:42 -0400 Subject: Why does this group have so much spam? In-Reply-To: <86vdk5o2p6.fsf@betla.izb.knu.ac.kr> References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <86vdk5o2p6.fsf@betla.izb.knu.ac.kr> Message-ID: Byung-Hee HWANG wrote: > casebash writes: > >> So much of it could be removed even by simple keyword filtering. > > Use python-list at python.org [1], instead. > > [1] http://mail.python.org/mailman/listinfo/python-list Or read python-list as a newsgroup via news.gmane.org, which mirrors python-list, not c.l.p. From tjreedy at udel.edu Sun Aug 30 18:33:30 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 30 Aug 2009 18:33:30 -0400 Subject: Why does this group have so much spam? In-Reply-To: References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> Message-ID: Nobody wrote: > Apart from the impossibility of implementing such a tax, it isn't going to > discourage spammers when the tax will be paid by the owner of the > compromised PC from which they're sending their spam. It would encourge PC owners to not let their machine be used as a spambot. From cousinstanley at gmail.com Sun Aug 30 18:40:33 2009 From: cousinstanley at gmail.com (Cousin Stanley) Date: Sun, 30 Aug 2009 22:40:33 +0000 (UTC) Subject: Combining C and Python programs References: Message-ID: > I want to write a program that will use ode for the physics > simulation, whose python bindings are outdated. So I'm writing > the physics engine in C and want to write the drawing code in > Python. What will be the best way of making those two programs > work together? THe physics engine won't have to run concurrently > with the drawing code. It will only return some position data so > they can be drawn. You might find VPython useful .... http://www.vpython.org/ A VPython example using ode .... http://vpython.wikidot.com/forum/t-109218 -- Stanley C. Kitching Human Being Phoenix, Arizona From barcaroller at music.net Sun Aug 30 18:41:51 2009 From: barcaroller at music.net (barcaroller) Date: Sun, 30 Aug 2009 18:41:51 -0400 Subject: PyGTK problems after Linux update... References: <7fq56dF2m6qlbU1@mid.individual.net> Message-ID: "Thomas Guettler" wrote in message news:7fq56dF2m6qlbU1 at mid.individual.net... > Looks like your pygtk package does not fit to the installed python > package. Okay, I won't disagree, but how do I fix this? From rt8396 at gmail.com Sun Aug 30 19:08:46 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 16:08:46 -0700 (PDT) Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> Message-ID: On Aug 30, 4:23?pm, David <71da... at libero.it> wrote: (snip) > The owner of compromised PC should be responsible of his computer like the > owner of a car is responsible of damages caused by its car. > That owner should keep his computer clean as he *must* keep his car > functional and safe. Yes i agree but your logic is flawed. If someone cuts my brake lines and i cannot stop who is to blame? Or if someone throws nails on the highway and i crash, who is to blame? Obviously you cannot blame the car owner. However if i let my brake pads wear out until they are metal on metal and run over some poor old lady crossing the street -- well now you got me! ;) But you cannot apply this logic when a hacker compromises someones computer, it the same as cutting their brake lines. How can you honestly expect that Joe computer user will know of this infection? Do you even know where your brake lines are? Even hackers can be hacked without ever knowing it! The only sure fire way is VM's or system re- installs. > Today most of the people consider cyber security an optional, but all of us > pay for their negligence. Those people are externalizing to the rest of the > world their costs in terms of SO updating, antivirus, firewall and > knowledge. This is unfair. Yes, keeping a running AV and proper updating i agree with... > This is mainly a matter of sensibility and culture: in '50/60s active and > passive car safety was an optional, today is a must. > I think it's time to switch to responsible computing and the mail-tax would > charge each person of its own costs and annoyances without affectig the rest > of the world. What, this is madness! If you have terrorist terrorizing your country you don't tax the public when they blow up a shopping mall so you can rebuild it! No you kill the terrorist in a harsh and painful manner and make an example of them, then you seize there monies. You should direct your anger to the proper internet security authorities(and more importantly to the perpetrator's) and not the innocent victims of such attacks. I want you to sit back and think very deeply about your proposal here because it is horribly wrong. It is so easy to just slap a tax on something, yes that will solve everything. *sarcasm* > > If you want to avoid usenet spam and don't want to filter it yourself, > > find a provider with more aggressive spam filter. > > This is not the solution. You are saying that if your neighbour makes loud > noises you can not call police to impose him to cease but you can only make > your home soundproof. or you could go over and punch him in the nose, works every time for me ;-) From rt8396 at gmail.com Sun Aug 30 19:24:00 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 16:24:00 -0700 (PDT) Subject: Colors on IDLE References: <59922ab5-f8c9-429f-b1ea-9b1418aa6b71@t13g2000yqt.googlegroups.com> <8d5d283f-b0bd-4e16-97c7-d2de1a148cae@l35g2000vba.googlegroups.com> Message-ID: <45407662-a944-4e8c-922e-83095cd2ce9e@g23g2000vbr.googlegroups.com> On Aug 28, 6:27?pm, r wrote: > Have you tried saving the files as MYScriptName.py? notice the py > extension, very important ;) Just for fun try the .pyw extension and observe the result. From rt8396 at gmail.com Sun Aug 30 19:36:31 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 16:36:31 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <4a9a0988$0$1669$742ec2ed@news.sonic.net> Message-ID: On Aug 30, 1:08?pm, Nobody wrote: (snip) > Because that would be the likely consequence of such a stance. Japanese > websites will continue to use Shift-JIS, Japanese cellphones (or > Scandanavian cellphones aimed at the Japanese market, for that matter) > will continue to render websites which use Shift-JIS, and HTML 5 will be > just as much a pure academic exercise as all of the other HTML standards. Yes and this keep-everyone-happy crap will go on for centuries. Unicode will then turn into another elephant sized bloatware standard that only VB and MSDN, M$ Office, and Adobe PDF can hold a candle to. Who cares, hard drives can hold terabytes of useless junk, right? This is starting to border on OCD tendencies and i for one am getting very nervous. From david.lyon at preisshare.net Sun Aug 30 20:06:52 2009 From: david.lyon at preisshare.net (David Lyon) Date: Sun, 30 Aug 2009 20:06:52 -0400 Subject: ubuntu dist-packages In-Reply-To: <0298b834-78b4-4501-a09b-9b8da5e796c1@s15g2000yqs.googlegroups.com> References: <7fki3lF2kirnkU1@mid.uni-berlin.de> <71f5986e-6aae-46b0-8325-d67051c60a30@a13g2000yqc.googlegroups.com> <7fnftkF2m6bvdU1@mid.uni-berlin.de> <0298b834-78b4-4501-a09b-9b8da5e796c1@s15g2000yqs.googlegroups.com> Message-ID: On Thu, 27 Aug 2009 07:05:51 -0700 (PDT), Paul Boddie wrote: > No, it's the problem of the Pythonic packaging brigade that package > retrieval, building and installing is combined into one unsatisfactory > whole. Brigade? That implies a disciplined and systematic approach.. I would suggest a better term is just guerrilla fighters. There's no central planning.. no looking out for the greater good.. No sense of future.. forgive my pessimism.. > In fact, the distributions have proven themselves > to be quite competent at managing huge numbers of software packages in > a semi-automated fashion, so it's baffling that people doing work on > Pythonic packaging tools wouldn't want to learn as much as they can > about how those people manage it. That's a serious and true allegation. I think the answer is that the people that are running it aren't interested in cleaning things up for the linux or windows platform. Consensus seems to be just "remove" anything that relates to windows or linux as an approach to harmonising it. I believe that it should be harmonised. > For me, when making Debian packages, it has become easier to use the > debhelper stuff to install things like documentation and resources > than it is to figure out which special options have to be passed to > the particular distutils incarnation of the setup function in order to > get such stuff put in the right place, especially since distutils > probably still employs an ad-hoc 1990s proprietary UNIX "oh just dump > that stuff in some directory or other and forget about it" mentality. It doesn't. Actually, it can't even do that very well. 90's.... which '90s ? 1890's ? > Really, distutils should be all about *dist*ribution and even then get > out of the way as much as possible - the hard stuff is extracting the > appropriate knowledge about the built Python interpreter in order to > build extensions. Exactly. > Installation should be left to something which has > an opinion about where things should be placed on a particular system, > and which has the capability to know how to uninstall stuff - a > capability which never seems to get any closer in the distutils scene. (sigh) - it is true... David From grante at visi.com Sun Aug 30 20:25:45 2009 From: grante at visi.com (Grant Edwards) Date: Sun, 30 Aug 2009 19:25:45 -0500 Subject: initilize a memory zone in python References: Message-ID: On 2009-08-30, Mug wrote: > hello, i'm new in python, i used to program in C, i have a > small problem, i tryed to do some serial port things You're probably better off just using pyserial: http://pyserial.sourceforge.net/ If you really want to muck about with termios stuff, you can look at the posix serial module in pyserial to see how it's done. > import sys,termios > > fd = sys.stdin.fileno() > term_conf=termios.tcgetattr(fd); > > now i want to modify the actuall values in term_conf zone to > zero Have you looked at the documentation for termios.tcgettattr()? It returns a list of integers. If you want set them to zero, then just set them to zero. If you want a configuration that's all zeros, why bother calling tcgetattr() at all? Just set the configuration to zeros: term_conf = [0,0,0,0,0,0] -- Grant From grante at visi.com Sun Aug 30 20:37:15 2009 From: grante at visi.com (Grant Edwards) Date: Sun, 30 Aug 2009 19:37:15 -0500 Subject: initilize a memory zone in python References: Message-ID: On 2009-08-31, Grant Edwards wrote: > If you want a configuration that's all zeros, why bother > calling tcgetattr() at all? Just set the configuration to > zeros: > > term_conf = [0,0,0,0,0,0] Oops, I forgot about cc. That should be: term_conf = [0,0,0,0,0,0,['\x00']*32] That's why it's easier to just use pyserial ;) -- Grant From walkraft at gmail.com Sun Aug 30 20:49:52 2009 From: walkraft at gmail.com (casebash) Date: Sun, 30 Aug 2009 17:49:52 -0700 (PDT) Subject: Nice copy in interactive terminal References: <1250153823.228153@athprx03> <0dac8bc9-8f00-4f4e-bc29-b475bade7685@y10g2000prg.googlegroups.com> Message-ID: <67cb16ca-89a5-43f3-8074-990b491faa7d@a37g2000prf.googlegroups.com> I managed to get some more answers here: http://stackoverflow.com/questions/1352886/nice-copying-from-python-interpreter On Aug 14, 5:05?pm, casebash wrote: > I mainly develop on Linux these days, but if I ever end up doing > anything on windows I'll make sure to look at that. > > On Aug 13, 6:56?pm, "Elias Fotinis \(eliasf\)" > wrote: > > > "casebash" wrote: > > > I've been wondering for a while if there exists an interactive > > > terminal which has nice copy feature (ie. I can copy code without > > > getting the >>> in front of every line). > > > It would help if we knew what platform you're interested in -- your > > User-Agent is G2/1.0, but I don't know what that is. ?:o) > > > On Windows, PythonWin can copy from the interactive window without the > > prompts. > > From walkraft at gmail.com Sun Aug 30 20:50:45 2009 From: walkraft at gmail.com (casebash) Date: Sun, 30 Aug 2009 17:50:45 -0700 (PDT) Subject: Determining the metaclass References: <6f69f304-3cf1-45c8-b86d-f57751bcc2ed@d15g2000prc.googlegroups.com> <3e1b7e0b-e44c-4b34-9866-33aa7b33a3af@v37g2000prg.googlegroups.com> Message-ID: Thanks, I am silly > > > I cannot determine if a class is an instance of a particular > > metaclass. Here is my best attempt > > > >>> class tmp(type): > > > ... ? ? pass > > ...>>> def c(metaclass=tmp): > > > ... ? ? pass > > ...>>> isinstance(c, tmp) > > False > > >>> isinstance(c.__class__, tmp) > > > False > > > Can anyone explain why this fails? > > You're gonna kick yourself. > > It's because you used "def" and not "class" to define c. ?If you'd > used "class" then then first test would have worked. > > Carl Banks From rt8396 at gmail.com Sun Aug 30 20:51:28 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 17:51:28 -0700 (PDT) Subject: initilize a memory zone in python References: <7g07ghF2ngfq1U1@mid.uni-berlin.de> <18627379-8056-4ee9-b3b8-d5fd4cd0590c@y20g2000vbk.googlegroups.com> Message-ID: <2f4ad057-c88b-4fe7-8858-3511b2a10f27@y20g2000vbk.googlegroups.com> On Aug 30, 4:59?pm, Mug wrote: (snip) > is there a fonction like "memset" or "bzero" in python? Not that i know of ;). Try this link for a coverage of the Python built-in functions. You cannot write quality Python code without them. http://docs.python.org/3.1/library/functions.html What you refer to as an array is called a list round here, see this informative read http://docs.python.org/3.1/library/stdtypes.html#sequence-types-str-bytes-bytearray-list-tuple-range And be sure to check out list comprehentions too, just icing on the cake ;) python 3000 docs http://docs.python.org/3.1/ From gagsl-py2 at yahoo.com.ar Sun Aug 30 21:29:14 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 30 Aug 2009 22:29:14 -0300 Subject: Popen question (redundant processes) References: <50697b2c0908301325w67af40a0lfbde8418f4a89e5f@mail.gmail.com> Message-ID: En Sun, 30 Aug 2009 17:25:40 -0300, Chris Rebert escribi?: > On Sun, Aug 30, 2009 at 12:33 PM, Sebastian wrote: >> Hello World! >> This is my first post on the list and I'm hoping it is the right forum >> and >> not OT, I've searched >> a bit on this, but, none-the-wiser! >> >> My question is on the Popen method, here is my snippet: >> >>> p1 = Popen(["cat", "georgi_ddr7_allmag_kcor_in_test.dat"], stdout=PIPE >>> ) >>> p2 = Popen(["fit_coeffs"], stdin=p1.stdout, stdout=PIPE) >>> p3 = Popen(["reconstruct_maggies"], stdin=p2.stdout,stdout=PIPE) >>> output_maggies_z=p3.communicate()[0] >>> >>> p1 = Popen(["cat", "georgi_ddr7_allmag_kcor_in_test.dat"], stdout=PIPE >>> ) >>> p2 = Popen(["fit_coeffs"], stdin=p1.stdout, stdout=PIPE) >>> p4 = Popen(["reconstruct_maggies", "--band-shift", "0.1", "--redshift", >>> "0."], stdin=p2.stdout,stdout=PIPE) >>> output_maggies_z0=p4.communicate()[0] >>> >> >> That is, p1 and p2 are the same, but p3 and p4 which they are passed >> to, are >> different. >> Is there a way to pass p1 and p2 to p3 AND p4 simultaneously, so as to >> not >> need to >> run p1 and p2 twice, as above? >> What arguments would I need to achieve this? >> >> NOTE: "georgi_ddr7_allmag_kcor_in_test.dat" is a very large file (~1E6 >> records) > > Send the output of p2 through the unix command "tee" > (http://unixhelp.ed.ac.uk/CGI/man-cgi?tee). Then put the output of tee > into p3 and set p4's input to the file you specified to tee. In addition to that, you can avoid the cat command (and omit p1 completely), just pass the georgi file as p2 stdin: p2 = Popen(["fit_coeffs"], stdin=open("georgi..."), ... In other words, the original shell commands are: cat georgi.dat | fit | reconstruct cat georgi.dat | fit | reconstruct --otherargs and we suggest doing: fit < georgi.dat | tee /tmp/foo | reconstruct reconstruct --otherargs < /tmp/foo -- Gabriel Genellina From timr at probo.com Sun Aug 30 23:18:41 2009 From: timr at probo.com (Tim Roberts) Date: Sun, 30 Aug 2009 20:18:41 -0700 Subject: why python got less developers ? References: <1ccf54f5-b1f5-4c4a-b782-fde1a1648cf6@l5g2000yqo.googlegroups.com> Message-ID: <3bfm959q7f430caogglsctpoc6j917d7m6@4ax.com> Esam Qanadeely wrote: >On Aug 28, 8:27?am, Tim Roberts wrote: >> Deep_Feelings wrote: >> >> >python got relatively fewer numbers of developers than other high >> >level languages like .NET , java .. etc ?why ? >> >> How do you know, and why does it matter? >> >> By the way, .NET is not a language. ?I assume you meant C#. > >you know when you go to forums and compare the number of posts and >topics ,and you know when you google and compare the number of results > >.NET= i meant all .NET languages That's hardly a fair way to categorize things. "All .NET languages" includes C++, C#, Basic, Java (in J#), Ocaml (in F#), and Python. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From drsalists at gmail.com Sun Aug 30 23:27:55 2009 From: drsalists at gmail.com (Dan Stromberg) Date: Sun, 30 Aug 2009 20:27:55 -0700 Subject: Reading binary files In-Reply-To: <4eb0089f0908241443p348eea3dxd57581e37f94d0bd@mail.gmail.com> References: <9c8c445f0908240735k6599045dn5ecbd63fa76bfe6e@mail.gmail.com> <1251125039.23757.0.camel@brotherus.corp.redhat.com> <9c8c445f0908240818k1ae301acr49c65ccb21435cd7@mail.gmail.com> <9c8c445f0908240950h24e5bfccoc9ae809c1048be5d@mail.gmail.com> <4eb0089f0908241443p348eea3dxd57581e37f94d0bd@mail.gmail.com> Message-ID: <4A9B433B.8050203@gmail.com> David Robinow wrote: >>> This works for a simple binary file, but the actual file I'm trying to >>> read is give throwing an error that the file cannot be found. Here is the >>> name of the my file: >>> 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars >>> >>> Should python have trouble reading this file name or extension? >>> >> I'm having trouble with the filename: >> 2009.08.02_06.52.00_WA-1_0001_00_0662_0.jstars >> >> It throws an error with that file name, When I change it to something like >> sample.txt it runs, but the data is still garbled. Is there any reason why I >> can't use the above file name? If I'm using 'rb' to read the binary file why >> is it still garbled? >> > I don't think it's garbled. It's a binary file. What do you expect? > > It's been over ten years since I've worked with any JSTARS stuff so I > can't give you any details but you almost certainly have some sort of > imagery. The military has a lot of bizarre formats and whoever sent > you the data should have included a data sheet describing the format > (or a pointer to such). Ideally, you'll also get a pointer to code to > read the thing, but sometimes you just have to bite the bullet and > write a program to process the file. > (If all else fails, look at a dump of the first 512 bytes or so; > often the image size is included at the beginning; maybe in ASCII, 16 > bit ints, 32 bit ints, floating point -- who knows) > There've been times when I had to just display the thing at 512 or > 1024 bytes (or ints) per row and try to surmise the info from that. > So, look for the file description. > ... > Googling a bit: I see there's a package at > http://www.mbari.org/data/mbsystem/index.html > which purports to handle some JSTARS stuff. I've no idea if that will help you. > If you don't find anything preexisting for reading JSTARS format, this might help: http://stromberg.dnsalias.org/~strombrg/converting-binary.html From nagle at animats.com Mon Aug 31 00:29:38 2009 From: nagle at animats.com (John Nagle) Date: Sun, 30 Aug 2009 21:29:38 -0700 Subject: What python can NOT do? In-Reply-To: References: <00a36f89-52dd-4d90-a455-cee6a0c9d10f@q5g2000yqh.googlegroups.com> <4a998465$0$1637$742ec2ed@news.sonic.net> Message-ID: <4a9b506c$0$1675$742ec2ed@news.sonic.net> exarkun at twistedmatrix.com wrote: > On 10:23 pm, aahz at pythoncraft.com wrote: >> In article <4a998465$0$1637$742ec2ed at news.sonic.net>, >> John Nagle wrote: >>> >>> Personally, I consider Python to be a good language held back by >>> too-close ties to a naive interpreter implementation and the lack >>> of a formal standard for the language. ... > > For my part, I will agree with John. I feel like Python's big > shortcomings stem from the areas he mentioned. They're related to each > other as well - the lack of a standard hampers the development of a less > naive interpreter (either one based on CPython or another one). It > doesn't completely prevent such development (obviously, as CPython > continues to undergo development, and there are a number of alternate > runtimes for Python-like languages), but there's clearly a cost > associated with the fact that in order to do this development, a lot of > time has to be spent figuring out what Python *is*. This is the kind of > thing that a standard would help with. Right. Python is a moving target for developers of implementations other than CPython. IronPython's production version is at Python 2.5, with a beta at 2.6. Shed Skin is at 2.x and lacks the manpower to get to 3.x. Psyco I'm not sure about, but it's 2.x. PyPy is at Python 2.5, but PyPy is currently slower than CPython. A solid Python 3 standard would give everyone a target to shoot for that would be good for five years or so. John Nagle From rt8396 at gmail.com Mon Aug 31 00:31:29 2009 From: rt8396 at gmail.com (r) Date: Sun, 30 Aug 2009 21:31:29 -0700 (PDT) Subject: why python got less developers ? References: <604b21ef-a3ad-4da8-92f5-c1d22345b4d7@p15g2000vbl.googlegroups.com> Message-ID: <798eded3-b3fe-4995-9e63-bff718b18889@m20g2000vbp.googlegroups.com> On Aug 29, 11:14?pm, kennyken747 wrote: (snip) > You guys can say anything you'd like it to be in this thread, but the > actual reason comes down to > 1. No marketing. Seriously, if Microsoft was pushing Python it would > obviously be a lot bigger in terms of developers. I really don't care if 100 or 100 million are using Python as long as it will endure my lifetime so i can use it ;). But it would be interesting to see a good approx of this number... just for kicks > Also, really guys? This crap about speed? People have been saying this > for years, and yet they still don't realize that there are plenty > solutions to take care of that one problem. > > Just be happy that you've stumbled upon Python, just because it's not > the most widespread language in the world certainly doesn't mean it's > not a worthy language. Quite the opposite. Your post seems a contridiction of itself? i am confused :\ From kerensaelise at hotmail.com Mon Aug 31 00:55:52 2009 From: kerensaelise at hotmail.com (elsa) Date: Sun, 30 Aug 2009 21:55:52 -0700 (PDT) Subject: map Message-ID: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Hi, i have a question about the built in map function. Here 'tis: say I have a list, myList. Now say I have a function with more than one argument: myFunc(a, b='None') now, say I want to map myFunc onto myList, with always the same argument for b, but iterating over a: map(myFunc(b='booHoo'), myList) Why doesn't this work? is there a way to make it work? (Ultimately, I want to call myFunc(myList[0], 'booHoo'), myFunc(myList [1], 'booHoo'), myFunc(myList[2], 'booHoo') etc. However, I might want to call myFunc(myList[0], 'woo'), myFunc(myList[1], 'woo'), myFunc (myList[2], 'woo') some other time). Thanks, Elsa From mmm286 at gmail.com Mon Aug 31 01:08:39 2009 From: mmm286 at gmail.com (mierdatutis mi) Date: Sun, 30 Aug 2009 22:08:39 -0700 (PDT) Subject: connect to ms sql server with odbc Message-ID: Hi, I'm newbie in python. I try to connect to remote server with ms sql server from my ubuntu. I install pyodbc and I do: >>> conn = >>> Conn = pyodbc.connect("DRIVER= {FreeTDS};SERVER=defekas62;UID=emuser;PWD=temporal;DATABASE=em620") pyodbc.connect ( "DRIVER = () FreeTDS; SERVER = defekas62; UID = emuser; PWD = temporal; em620 DATABASE =") cursor = conn.cursor() cursor = conn.cursor () >>> for row in cursor.execute("select USERNAME from JOBACTIONS"): >>> Para la fila en cursor.execute ( "usuario seleccionar de JOBACTIONS"): ... ... print row.USERNAME row.USERNAME de impresi?n File "", line 2 Archivo "", l?nea 2 print row.USERNAME row.USERNAME de impresi?n ^ ^ IndentationError: expected an indented block Why this error? Many thanks and sorry for my english From clp2 at rebertia.com Mon Aug 31 01:17:30 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Sun, 30 Aug 2009 22:17:30 -0700 Subject: map In-Reply-To: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: <50697b2c0908302217o4d2f445m96bc713f93be961e@mail.gmail.com> On Sun, Aug 30, 2009 at 9:55 PM, elsa wrote: > Hi, > > i have a question about the built in map function. Here 'tis: > > say I have a list, myList. Now say I have a function with more than > one argument: > > myFunc(a, b='None') > > now, say I want to map myFunc onto myList, with always the same > argument for b, but iterating over a: > > map(myFunc(b='booHoo'), myList) > > Why doesn't this work? Because myFunc is executed before map() is ever called, and you didn't specify a value for the `a` parameter, hence you get an error about not giving a value for `a`. Another way of saying this: Python uses "eager evaluation" (http://en.wikipedia.org/wiki/Eager_evaluation) most of the time. > is there a way to make it work? Use functools.partial to fill in the `b` parameter: http://docs.python.org/library/functools.html#functools.partial #untested example: from functools import partial f = partial(myFunc, b='booHoo') map(f, myList) Cheers, Chris -- http://blog.rebertia.com From rurpy at yahoo.com Mon Aug 31 01:19:13 2009 From: rurpy at yahoo.com (rurpy at yahoo.com) Date: Sun, 30 Aug 2009 22:19:13 -0700 (PDT) Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: On 08/30/2009 10:55 PM, elsa wrote: > i have a question about the built in map function. Here 'tis: > > say I have a list, myList. Now say I have a function with more than > one argument: > > myFunc(a, b='None') > > now, say I want to map myFunc onto myList, with always the same > argument for b, but iterating over a: > > map(myFunc(b='booHoo'), myList) > > Why doesn't this work? is there a way to make it work? When you write "map(myFunc(b='booHoo'), myList)", you are telling Python to call myFunc before the map function is called, because an argument list, "(b='booHoo')", follows myFunc. You want to pass map a function object, not the results of calling a function object. A couple ways to do what you want: map(lambda a: myFunc(a, b='booHoo'), myList) The lamba expression creates a new function of one argument (which is needed by map) that, when executed, will call myFunc with the two arguments it needs. You can also just define an ordinary function that does the same thing as the lambda above: def tmpFunc (a) myFunc (a, b='booHoo') ... map (tmpFunc, myList) In the functools module there is a function called "partial" that does something similar to the lambda above. I'll leave it to you you look it up if interested. HTH From half.italian at gmail.com Mon Aug 31 01:24:22 2009 From: half.italian at gmail.com (Sean DiZazzo) Date: Sun, 30 Aug 2009 22:24:22 -0700 (PDT) Subject: connect to ms sql server with odbc References: Message-ID: On Aug 30, 10:08?pm, mierdatutis mi wrote: > Hi, > > I'm newbie in python. I try to connect to remote server with ms sql > server from my ubuntu. I install pyodbc and I do: > > ?>>> conn = >>> Conn = > ?pyodbc.connect("DRIVER= > {FreeTDS};SERVER=defekas62;UID=emuser;PWD=temporal;DATABASE=em620") > pyodbc.connect ( "DRIVER = () FreeTDS; SERVER = defekas62; UID = > emuser; PWD = temporal; em620 DATABASE =") > ?cursor = conn.cursor() cursor = conn.cursor () > ?>>> for row in cursor.execute("select USERNAME from JOBACTIONS"): >>> > Para la fila en cursor.execute ( "usuario seleccionar de > JOBACTIONS"): > ?... ... print row.USERNAME row.USERNAME de impresi?n > ? ?File "", line 2 Archivo "", l?nea 2 > ? ? ?print row.USERNAME row.USERNAME de impresi?n > ? ? ? ? ?^ ^ > ?IndentationError: expected an indented block > Why this error? > Many thanks and sorry for my english Welcome to python. The error is telling you exactly what it says. There is a block of code that is not indented properly. Perhaps your code was edited with two different editors? Tabs are not equal to spaces. Go thru your code and be sure that you are consistent with all of your spacing. I believe 4 spaces per indent (without tabs) is the current Python standard. ~Sean From news3 at mystrobl.de Mon Aug 31 01:34:28 2009 From: news3 at mystrobl.de (Wolfgang Strobl) Date: Mon, 31 Aug 2009 07:34:28 +0200 Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: <91om95pbqtcduss20iv37f44scr89fgudb@4ax.com> elsa : >now, say I want to map myFunc onto myList, with always the same >argument for b, but iterating over a: >>> from functools import partial >>> def g(x,y=1): return x+y ... >>> map(partial(g,y=2),[1,2]) [3, 4] >>> map(partial(g,y=42),[1,2]) [43, 44] -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From erik.reppen at gmail.com Mon Aug 31 02:10:07 2009 From: erik.reppen at gmail.com (Erik Reppen) Date: Sun, 30 Aug 2009 23:10:07 -0700 (PDT) Subject: why python got less developers ? References: Message-ID: It seems to be a language embraced by people who enjoy coding. Not so much by the time-spent-seeking-degree to paycheck ratio balancing crowd. Or maybe I just hate bloated IDEs and I've heard too many Java dev jokes to be impartial. From ubershmekel at gmail.com Mon Aug 31 02:26:59 2009 From: ubershmekel at gmail.com (RunThePun) Date: Sun, 30 Aug 2009 23:26:59 -0700 (PDT) Subject: Overriding iadd for dictionary like objects References: <87ws4n5gfi.fsf@slice.rozzin.com> Message-ID: On Aug 30, 10:33?pm, a... at pythoncraft.com (Aahz) wrote: > In article , > > > > > > RunThePun ? wrote: > > >I made a DictMixin where the keys are filenames and the values are the > >file contents. It was very simple and easy to do thanks to DictMixin. > > >For example this code writes "abc" in a file named "temp.txt" and > >prints the contents of the file named "swallow", these files are > >looked up/created/deleted in the directory "spam": > >>>> d =3D FilesDict('spam') > >>>> d['temp.txt'] =3D 'abc' > >>>> print(d['swallow']) > > >My problem arose when I wanted to append a string to a file which > >using open(..., 'ab') would have been miles more efficient because I > >wouldn't have to read the entire file (__getitem__) and then write the > >entire file back (__setitem__). The files are expected to be as big as > >600 KB which will be appended 30 bytes at a time about 3 times a > >second. Performance-wise the system would probably work without open > >(..., 'ab') but it would be a real thrashing so the current solution > >uses a method "AddTo" as Robert suggested, sacrificing the neat > >getitem/setitem syntax. > > You can do mostly what you want, I think, by having __setitem__() > convert string values into FileProxy() objects that have an appropriate > __iadd__() method. ?That brings a whole new set of problems, of course. > -- > Aahz (a... at pythoncraft.com) ? ? ? ? ? <*> ? ? ? ?http://www.pythoncraft.com/ > > "I support family values -- Addams family values" --www.nancybuttons.com I'm guessing you meant __getitem__, which is what Jan Kaliszewski suggested, but as you noted, would be a bit cumbersome in this case. From pierre.gaillard at gmail.com Mon Aug 31 03:41:57 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Mon, 31 Aug 2009 00:41:57 -0700 (PDT) Subject: lambda functions Message-ID: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> Hello, I would like to know if it is possible to define a loop in a lambda function.... How to manage the indents ? Example : s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s [index]-1 Thanks ! From eric.brunel at pragmadev.com Mon Aug 31 03:50:20 2009 From: eric.brunel at pragmadev.com (eb303) Date: Mon, 31 Aug 2009 00:50:20 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> Message-ID: <7b4f243d-ac69-4351-aed7-924afb0b3b11@e18g2000vbe.googlegroups.com> On Aug 28, 4:41 pm, r wrote: > Thanks eb303 for the wonderful post > > I have looked over the new ttk widgets and everything looks nice. I am > very glad to see the death of Tix as i never much liked it anyhow and > always believed these widgets should have been in the main Tkinter > module to start with. The tree widget has been needed for some time. > > However, i am not sure about the new "style" separation. Previously a > simple command like root.option_add('*Label.Font'...) accomplished the > same thing with less typing, but there may be a future method to this > current madness that i am unaware of...??? The new widgets have been made mainly to make tk look better by making it possible to use native widgets. The drawback is that it limits a lot the possibilities of configuration you can have: on many platforms, the looks of the widgets are decided by the user via a system preference, not by the application programmer. This is why ttk widgets are not configurable directly, because 'native' styles usually don't allow it at application level anyway. Keep in mind that the new ttk widgets are not replacements for former widgets, but an addition to them. 'Old' widgets are still here, and there is no plan I know of to remove them. If you want to do an application with a very specific look, you can still use these. From clp2 at rebertia.com Mon Aug 31 03:51:07 2009 From: clp2 at rebertia.com (Chris Rebert) Date: Mon, 31 Aug 2009 00:51:07 -0700 Subject: lambda functions In-Reply-To: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> References: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> Message-ID: <50697b2c0908310051n3bbe87d7n9929f90231062daa@mail.gmail.com> On Mon, Aug 31, 2009 at 12:41 AM, Pierre wrote: > Hello, > > I would like to know if it is possible to define a loop in a lambda > function.... Not possible. Lambdas can only contain a single expression. A loop is a block statement. Just use a named function instead. There's nothing that can be done with a lambda that can't be done with a named function instead. Cheers, Chris -- http://blog.rebertia.com From javier.collado at gmail.com Mon Aug 31 03:59:55 2009 From: javier.collado at gmail.com (Javier Collado) Date: Mon, 31 Aug 2009 09:59:55 +0200 Subject: lambda functions In-Reply-To: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> References: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> Message-ID: Hello, This page has some advice about how to avoid some of the lambda functions limitations: http://p-nand-q.com/python/stupid_lambda_tricks.html In particular, it suggests to use map function instead of for loops. Best regards, Javier 2009/8/31 Pierre : > Hello, > > I would like to know if it is possible to define a loop in a lambda > function.... > > How to manage the indents ? Example : > s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s > [index]-1 > > > Thanks ! > > -- > http://mail.python.org/mailman/listinfo/python-list > From deets at nospam.web.de Mon Aug 31 04:08:39 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 31 Aug 2009 10:08:39 +0200 Subject: initilize a memory zone in python In-Reply-To: <18627379-8056-4ee9-b3b8-d5fd4cd0590c@y20g2000vbk.googlegroups.com> References: <7g07ghF2ngfq1U1@mid.uni-berlin.de> <18627379-8056-4ee9-b3b8-d5fd4cd0590c@y20g2000vbk.googlegroups.com> Message-ID: <7g1eo9F2neh1fU1@mid.uni-berlin.de> Mug schrieb: > On Aug 30, 8:58 pm, "Diez B. Roggisch" wrote: >> Mug schrieb: >> >>> hello, i'm new in python, i used to program in C, >>> i have a small problem, i tryed to do some serial port things >>> manipulation >>> with python. >>> i have something like: >>> import sys,termios >>> fd = sys.stdin.fileno() >>> term_conf=termios.tcgetattr(fd); >>> now i want to modify the actuall values in term_conf zone to zero >>> i don't see how to do it, >>> in C we can do : bzero(&term_conf,sizeof(struct termios)); >>> i want to know if it exist a similar function in python, thanks >> In python you don't modify memory like that. >> >> For the above function, you pass a value as the one you got to >> tcgetattr, with values modified as you desire them. > i tryed > print term_conf > and i saw that the term_conf is actually represent with an array in > python: > > zsh/3 4201 [1] % python test.py > [27906, 5, 1215, 35387, 15, 15, ['\x03', '\x1c', '\x7f', '\x15', > '\x04', '\x00', '\x01', '\xff', '\x11', '\x13', '\x1a', '\xff', > '\x12', '\x0f', '\x17', '\x16', '\xff', '\x00', '\x00', '\x00', > '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', > '\x00', '\x00', '\x00', '\x00']] > > it's a array of 7 elements, with the seventh element it self a array, > so in order to initialize them to zero, there's no other way than > modify them > one by one in a loop? is there a fonction like "memset" or "bzero" in > python? Again: no, there is no such function. But for the above, you'd easily write: foo = [0] * 7 # only do this with immutables foo[-1] = ['\x00'] * 16 alternatively, you modify the result you got from tcgetattr in the places you want. Diez From gagsl-py2 at yahoo.com.ar Mon Aug 31 04:16:39 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Aug 2009 05:16:39 -0300 Subject: lambda functions References: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> Message-ID: En Mon, 31 Aug 2009 04:41:57 -0300, Pierre escribi?: > I would like to know if it is possible to define a loop in a lambda > function.... > > How to manage the indents ? Example : > s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s > [index]-1 You can't. lambda is just a way to define a short, inline, anonymous function, and its body can only contain expressions, not statements. Even if what you want were legal, giving a name to the resulting expression kind of defeats the purpose of lambda - use a normal function instead: def s_minus_1(s): "document usage here" for index,item in enumerate(s): s[index] -= 1 -- Gabriel Genellina From hendrik at microcorp.co.za Mon Aug 31 04:19:57 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 31 Aug 2009 10:19:57 +0200 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <3e9ddb9b-8f61-4d8d-a25c-7e95e8a25c06@g1g2000vbr.googlegroups.com> Message-ID: <200908311019.58029.hendrik@microcorp.co.za> On Sunday 30 August 2009 22:46:49 Dennis Lee Bieber wrote: > Rather elitist viewpoint... Why don't we just drop nukes on some 60% > of populated landmasses that don't have a "western" culture and avoid > the whole problem? Now yer talking, boyo! It will surely help with the basic problem which is the heavy infestation of people on the planet! :-) - Hendrik From hendrik at microcorp.co.za Mon Aug 31 04:43:07 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 31 Aug 2009 10:43:07 +0200 Subject: map In-Reply-To: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: <200908311043.07827.hendrik@microcorp.co.za> On Monday 31 August 2009 06:55:52 elsa wrote: 8< --------- map question ---------------------------- > > (Ultimately, I want to call myFunc(myList[0], 'booHoo'), myFunc(myList > [1], 'booHoo'), myFunc(myList[2], 'booHoo') etc. However, I might want > to call myFunc(myList[0], 'woo'), myFunc(myList[1], 'woo'), myFunc > (myList[2], 'woo') some other time). Here is some heretical advice: Do not use stuff like map and reduce unless they fit what you want to do perfectly, and "JustWorks" the first time. You have a very clear idea of what you want to do, so why do you not just simply write something to do it? something like this (untested): def woofer(thefunc,thelist,thething): theanswers = [] for x in thelist: theanswers.append(thefunc(x,thething)) return theanswers And the advantage is that you do not have to remember what map does... *ducks away from the inevitable flames* - Hendrik From pierre.gaillard at gmail.com Mon Aug 31 05:02:45 2009 From: pierre.gaillard at gmail.com (Pierre) Date: Mon, 31 Aug 2009 02:02:45 -0700 (PDT) Subject: rcond in numpy : Message-ID: Hello, Anyone knows the numpy equivalent of the matlab function : rcond (Matrix reciprocal condition number estimate) ? Thanks. From gagsl-py2 at yahoo.com.ar Mon Aug 31 05:05:17 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Aug 2009 06:05:17 -0300 Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> <200908311043.07827.hendrik@microcorp.co.za> Message-ID: En Mon, 31 Aug 2009 05:43:07 -0300, Hendrik van Rooyen escribi?: > On Monday 31 August 2009 06:55:52 elsa wrote: > >> (Ultimately, I want to call myFunc(myList[0], 'booHoo'), myFunc(myList >> [1], 'booHoo'), myFunc(myList[2], 'booHoo') etc. However, I might want >> to call myFunc(myList[0], 'woo'), myFunc(myList[1], 'woo'), myFunc >> (myList[2], 'woo') some other time). > > Here is some heretical advice: > > Do not use stuff like map and reduce unless they fit what you want to do > perfectly, and "JustWorks" the first time. I think of that advice as "orthodox", not "heretical"! (functional guys are minority here...) > You have a very clear idea of what you want to do, so why do you not just > simply write something to do it? > > something like this (untested): > > def woofer(thefunc,thelist,thething): > theanswers = [] > for x in thelist: > theanswers.append(thefunc(x,thething)) > return theanswers > > And the advantage is that you do not have to remember what map does... This block: theanswers = [] for x in thelist: theanswers.append(thefunc(x,thething)) is formally the same as this one: theanswers = [thefunc(x,thething) for x in thelist] but the list comprehension is faster. So the function becomes: def woofer(thefunc,thelist,thething): return [thefunc(x,thething) for x in thelist] and may be inlined (it's usually easier to read). > *ducks away from the inevitable flames* *fights back to back with you against heretics* -- Gabriel Genellina From piet at cs.uu.nl Mon Aug 31 05:31:34 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 31 Aug 2009 11:31:34 +0200 Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: >>>>> Hendrik van Rooyen (HvR) wrote: >HvR> On Monday 31 August 2009 06:55:52 elsa wrote: >HvR> 8< --------- map question ---------------------------- >>> >>> (Ultimately, I want to call myFunc(myList[0], 'booHoo'), myFunc(myList >>> [1], 'booHoo'), myFunc(myList[2], 'booHoo') etc. However, I might want >>> to call myFunc(myList[0], 'woo'), myFunc(myList[1], 'woo'), myFunc >>> (myList[2], 'woo') some other time). >HvR> Here is some heretical advice: >HvR> Do not use stuff like map and reduce unless they fit what you want to do >HvR> perfectly, and "JustWorks" the first time. >HvR> You have a very clear idea of what you want to do, so why do you not just >HvR> simply write something to do it? >HvR> something like this (untested): >HvR> def woofer(thefunc,thelist,thething): >HvR> theanswers = [] >HvR> for x in thelist: >HvR> theanswers.append(thefunc(x,thething)) >HvR> return theanswers >HvR> And the advantage is that you do not have to remember what map does... Map should be in every good programmer's toolbox. So (s)he presumably knows already what map does. In order to follow your advise (s)he must first forget what map does :=) Agreed on the part that map shouldn't be used indiscriminately. Neither should loops. Your woofer is much harder to follow than map, I think. [myFunc(elt, 'booHoo') for elt in myList] is also a good candidate and in this case I think it is preferable to both the loop and the map with a partial or lambda in terms of clarity. On the other hand when you just want to call a function on each element of a list and you don't need to collect the result a simple loop is often preferable. But ultimately it is also very much a matter of taste, preference and habit. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From jacopo.pecci at gmail.com Mon Aug 31 05:44:23 2009 From: jacopo.pecci at gmail.com (jacopo) Date: Mon, 31 Aug 2009 02:44:23 -0700 (PDT) Subject: starting a client remotely Message-ID: <7013f2ee-3076-4abf-b609-18c023d3e28a@f33g2000vbm.googlegroups.com> I am playing with multiprocessing and I would like to have a python script on one machine which initialize my whole system, in other words, this script should start the server (a python script) on my local machine and the clients (python scripts) on the other machines in my local network. Would you have any suggestion? regards, jacopo From deets at nospam.web.de Mon Aug 31 05:47:44 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 31 Aug 2009 11:47:44 +0200 Subject: starting a client remotely References: <7013f2ee-3076-4abf-b609-18c023d3e28a@f33g2000vbm.googlegroups.com> Message-ID: <7g1ki0F2nifhkU1@mid.uni-berlin.de> jacopo wrote: > I am playing with multiprocessing and I would like to have a python > script on one machine which initialize my whole system, in other > words, this script should start the server (a python script) on my > local machine and the clients (python scripts) on the other machines > in my local network. > > Would you have any suggestion? This isn't possible witout some kind of service running on the remote machine. You don't write what OS you are using, on unix'ish machines this can be easily accomplished using SSH to invoke a remote-command that starts your server. I've used that + Pyro in the past to create distributed systems. Diez From jacopo.pecci at gmail.com Mon Aug 31 05:58:34 2009 From: jacopo.pecci at gmail.com (jacopo) Date: Mon, 31 Aug 2009 02:58:34 -0700 (PDT) Subject: Return value of multiprocessing manager registerred function References: <4337084f-cf9b-4b9c-a0cc-ba8f0821f31a@v15g2000prn.googlegroups.com> Message-ID: Hi Terry, I have just started working on similar things and I am strugling to find examples or documentations. So far I have found only the official documentation of the multiprocessing package. Would you be able to recommend me some good reference or a book. I dont want to overwhelm this newsgroup with questions... yet :) Regards, Jacopo On Aug 26, 4:22?am, Terry wrote: > Hi, > > I'm using the multiprocessing.manager to run proceduresremotely. It > all worked fine except I hope to have a different return value type. > > The remote function calls always return a proxy, which when I need to > get the value it need to connect to the manager again to fetch it. But > I just need the value, not the proxy. > > Can I just return the value instead of a proxy from a manager? > > br, Terry From paul at boddie.org.uk Mon Aug 31 06:00:58 2009 From: paul at boddie.org.uk (Paul Boddie) Date: Mon, 31 Aug 2009 03:00:58 -0700 (PDT) Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <1ab2c088-bead-43fa-bf4a-3e7f4d84e871@g1g2000vbr.googlegroups.com> <59cad1ba-1162-4227-9375-d132ef030a7b@d21g2000vbm.googlegroups.com> Message-ID: <5a3acf8a-0f5f-4743-a477-f5dc2978d4ed@r36g2000vbn.googlegroups.com> On 31 Aug, 00:28, r wrote: > > I said it before and i will say it again. I DON"T CARE WHAT LANGUAGE > WE USE AS LONG AS IT IS A MODERN LANGUAGE FOUNDED ON IDEALS OF > SIMPLICITY!!!! [Esperanto] > English is by far already the de-facto lingua franca throughout the > world. You don't care, but here it comes: English! And is it a language "founded on ideals of simplicity"? I suggest you familiarise yourself with the history of the English language. [...] > You can deny the holocaust all you want but it still happened and so > too shall the great unity! Sadly because of cultural and social > fanatics like yourself, it will probably take another great war to > usher in the new order. Now you are just being offensive. [...] > So you are advocating for me to use derogatory statements in my post, > no thanks i need not resort to adolescent rants to argue my points. So what was the bulk of your opening message in this thread or the kind of gutter remarks made above if not "adolescent rants"? > And why do you continue to compare me to XL. Has XL *ever* helped a > python user in this forum? I have, many times. I am *actually* a > python programmer who cares about Python and my posts bring much vigor > and intelligence to an otherwise boring NG -- like me or not. Whether you actually care about Python or not, I repeat my suggestion that you take rants of this nature out of this forum and to a more appropriate place. At the very time the community seeks to increase diversity, such material is not only insensitive towards those who do not share your own cultural and political background, it also demonstrates a total lack of awareness of the kind of community people are trying to build and sustain. And don't give us the "livening up the newsgroup" excuse. The only reason people use newsgroups like this for their political posturing is analogous to a football player bursting into a chess club and claiming superiority in his own sport over those whose pastime has been interrupted: he knows that in a more suitable venue, his inadequacy would quickly be revealed by active practitioners of the discipline. Take your material elsewhere - maybe then the historians, linguists and sociologists will give you the tuition you so richly deserve! Paul From piet at cs.uu.nl Mon Aug 31 06:04:01 2009 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 31 Aug 2009 12:04:01 +0200 Subject: Is behavior of += intentional for int? References: <0022fef9$0$2930$c3e8da3@news.astraweb.com> <725bcd4c-01ed-489d-baa4-288a5c492831@m20g2000vbp.googlegroups.com> Message-ID: >>>>> Derek Martin (DM) wrote: >DM> On Sun, Aug 30, 2009 at 03:42:06AM -0700, Paul McGuire wrote: >>> Is it any odder that 3 is an object than that the string literal >>> "Hello, World!" is an object? >DM> Yes. Because 3 is a fundamental bit of data that the hardware knows >DM> how to deal with, requiring no higher level abstractions for the >DM> programmer to use it (though certainly, a programming language can >DM> provide them, if it is convenient). "Hello, World!" is not. They are >DM> fundamentally different in that way. How the semantics of Python is defined is not dependent of the hardware. You could imagine a computer where strings are as much built into the hardware as ints are. On the other hand you could also imagine a computer that only knows about bits and where int arithmetic has to be done in software. In fact early microprocessors only could operate directly on bytes and arithmetic of larger ints was in software. And even nowadays there are processors in use that don't have built-in floating point hardware. Would you say that considering whether 3.14 is an object in Python or whether that is to be considered strange should depend on the availability of a floating point unit in the hardware where the program runs? Would that make floating point numbers "fundamentally different" from ints in the sense described above? -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From jacopo.pecci at gmail.com Mon Aug 31 06:08:04 2009 From: jacopo.pecci at gmail.com (jacopo) Date: Mon, 31 Aug 2009 03:08:04 -0700 (PDT) Subject: starting a client remotely References: <7013f2ee-3076-4abf-b609-18c023d3e28a@f33g2000vbm.googlegroups.com> <7g1ki0F2nifhkU1@mid.uni-berlin.de> Message-ID: <7a3cbeba-7338-45b3-aff8-7840a322b185@r33g2000vbp.googlegroups.com> thank you Diez, unfortunatelly I am on Windows NT. Did you use SSH in a python script? Isn't multiprocessing.managers already doing something like Pyro? thanks Jacopo On Aug 31, 12:47?pm, "Diez B. Roggisch" wrote: > jacopo wrote: > > I am playing with multiprocessing and I would like to have a python > > script on one machine which initialize my whole system, in other > > words, this script should start the server (a python script) on my > > local machine and the clients (python scripts) on the other machines > > in my local network. > > > Would you have any suggestion? > > This isn't possible witout some kind of service running on the remote > machine. You don't write what OS you are using, on unix'ish machines this > can be easily accomplished using SSH to invoke a remote-command that starts > your server. I've used that + Pyro in the past to create distributed > systems. > > Diez From xi at gamma.dn.ua Mon Aug 31 06:14:18 2009 From: xi at gamma.dn.ua (Kirill Simonov) Date: Mon, 31 Aug 2009 13:14:18 +0300 Subject: [ANN] PyYAML-3.09: YAML parser and emitter for Python Message-ID: <4A9BA27A.10507@gamma.dn.ua> ======================== Announcing PyYAML-3.09 ======================== A new bug fix release of PyYAML is now available: http://pyyaml.org/wiki/PyYAML Note that PyYAML supports both Python 2 and Python 3. For compatibility notes, please see http://pyyaml.org/wiki/PyYAMLDocumentation#Python3support Changes ======= * Fixed compatibility issues with Python 3.1. * Fixed use of uninitialized memory when emitting anchors with LibYAML bindings (Thank to cegner(at)yahoo-inc(dot)com). * Fixed emitting incorrect BOM characters for UTF-16 (Thank to Valentin Nechayev) * Fixed the emitter for folded scalars not respecting the preferred line width (Thank to Ingy). * Fixed a subtle ordering issue with emitting '%TAG' directives (Thank to Andrey Somov). * Fixed performance regression with LibYAML bindings. Resources ========= PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.09.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.09.zip Windows installers: http://pyyaml.org/download/pyyaml/PyYAML-3.09.win32-py2.3.exe http://pyyaml.org/download/pyyaml/PyYAML-3.09.win32-py2.4.exe http://pyyaml.org/download/pyyaml/PyYAML-3.09.win32-py2.5.exe http://pyyaml.org/download/pyyaml/PyYAML-3.09.win32-py2.6.exe http://pyyaml.org/download/pyyaml/PyYAML-3.09.win32-py3.0.exe http://pyyaml.org/download/pyyaml/PyYAML-3.09.win32-py3.1.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core About PyYAML ============ YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. Example ======= >>> import yaml >>> yaml.load(""" ... name: PyYAML ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... """) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} >>> print yaml.dump(_) name: PyYAML homepage: http://pyyaml.org/wiki/PyYAML description: YAML parser and emitter for Python keywords: [YAML, serialization, configuration, persistance, pickle] Copyright ========= The PyYAML module is written by Kirill Simonov . PyYAML is released under the MIT license. From deets at nospam.web.de Mon Aug 31 06:35:44 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 31 Aug 2009 12:35:44 +0200 Subject: starting a client remotely References: <7013f2ee-3076-4abf-b609-18c023d3e28a@f33g2000vbm.googlegroups.com> <7g1ki0F2nifhkU1@mid.uni-berlin.de> <7a3cbeba-7338-45b3-aff8-7840a322b185@r33g2000vbp.googlegroups.com> Message-ID: <7g1nc0F2mjpocU1@mid.uni-berlin.de> jacopo wrote: > thank you Diez, > unfortunatelly I am on Windows NT. > Did you use SSH in a python script? Via subprocess, yes. Paramiko would be a way, too. > Isn't multiprocessing.managers already doing something like Pyro? I never used it, so I don't know - but it appears to be, yes. Doesn't change the overall problem though - without an inroad to another server, you can't spawn processes on remote machines. Diez From gagsl-py2 at yahoo.com.ar Mon Aug 31 06:46:06 2009 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 31 Aug 2009 07:46:06 -0300 Subject: starting a client remotely References: <7013f2ee-3076-4abf-b609-18c023d3e28a@f33g2000vbm.googlegroups.com> <7g1ki0F2nifhkU1@mid.uni-berlin.de> <7a3cbeba-7338-45b3-aff8-7840a322b185@r33g2000vbp.googlegroups.com> Message-ID: > On Aug 31, 12:47?pm, "Diez B. Roggisch" wrote: >> jacopo wrote: >> > I am playing with multiprocessing and I would like to have a python >> > script on one machine which initialize my whole system, in other >> > words, this script should start the server (a python script) on my >> > local machine and the clients (python scripts) on the other machines >> > in my local network. En Mon, 31 Aug 2009 07:08:04 -0300, jacopo escribi?: > thank you Diez, > unfortunatelly I am on Windows NT. NT 4.0??? I was going to say "use the rexec command" but I think it's posterior to the Triasic-Jurasic extinction event :) -- Gabriel Genellina From bruno.42.desthuilliers at websiteburo.invalid Mon Aug 31 07:25:12 2009 From: bruno.42.desthuilliers at websiteburo.invalid (Bruno Desthuilliers) Date: Mon, 31 Aug 2009 13:25:12 +0200 Subject: Object's nesting scope In-Reply-To: <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> References: <7fkqodF2llnghU1@mid.uni-berlin.de> <1ea2a98f-4035-4ec6-b5a9-06b21dd6f584@c14g2000yqm.googlegroups.com> <4a97c851$0$307$426a74cc@news.free.fr> <440b8caf-27f9-49d4-8d1b-94f93c75eb23@b14g2000yqd.googlegroups.com> Message-ID: <4a9bb2ee$0$10244$426a74cc@news.free.fr> zaur a ?crit : > On 28 ???, 16:07, Bruno Desthuilliers 42.desthuilli... at websiteburo.invalid> wrote: >> zaur a ?crit : >> >> >> >>> On 26 ???, 17:13, "Diez B. Roggisch" wrote: >>>> Whom am we to judge? Sure if you propose this, you have some usecases in >>>> mind - how about you present these >>> Ok. Here is a use case: object initialization. >>> For example, >>> person = Person(): >>> name = "john" >>> age = 30 >>> address = Address(): >>> street = "Green Street" >>> no = 12 >>> vs. >>> person = Person() >>> person.name = "john" >>> person.age = 30 >>> address = person.address = Address() >>> address.street = "Green Street" >>> address.no = 12 >> Err... Looks like you really should read the FineManual(tm) - >> specifically, the parts on the __init__ method. >> >> class Person(object): >> def __init__(self, name, age, address): >> self.name = name >> self.age = age >> self.address = address >> >> class Address(object): >> def __init__(self, street, no): >> self.no = no >> self.street = street >> >> person = Person( >> name="john", >> age=30, >> address = Address( >> street="Green Street", >> no=12 >> ) >> ) > > What are you doing if 1) classes Person and Address imported from > foreign module 2) __init__ method is not defined as you want? Either 1/write an alternate initializer and bind it to the appropriate classes or 2/write factory functions: 1/ from foreign_module import Person, Address def my_init(self, **kw): for k, v in kw.items(): setattr(self, k, v) return self Person.init = my_init Address.init = my_init person = Person().init( name="john", age=30, address = Address().init( street="Green Street", no=12 ) ) 2/ from functools import partial import foreign_module def my_factory(cls, **kw): obj = cls() for k, v in kw.items(): setattr(obj, k, v) return obj Person = partial(my_factory, foreign_module.Person) Address = partial(my_factory, foreign_module.Address) person = Person( name="john", age=30, address = Address( street="Green Street", no=12 ) ) From steve at REMOVE-THIS-cybersource.com.au Mon Aug 31 08:16:57 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Aug 2009 12:16:57 GMT Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: <002542bb$0$2930$c3e8da3@news.astraweb.com> On Mon, 31 Aug 2009 10:43:07 +0200, Hendrik van Rooyen wrote: > Here is some heretical advice: > > Do not use stuff like map and reduce unless they fit what you want to do > perfectly, and "JustWorks" the first time. > > You have a very clear idea of what you want to do, so why do you not > just simply write something to do it? That's not heretical advice -- that's pretty standard, vanilla, boring advice. It's probably good advice, if you care more about Getting the Job Done than about learning the language. > And the advantage is that you do not have to remember what map does... map() is probably the simplest, most straightforward of the functional tools in Python. It's harder for me to remember it's name than to remember what it does: it applies a function to each element of a list, instead of two the entire list as a single argument. Easy-peasy. > *ducks away from the inevitable flames* You'll have to try harder than that to get flamed :) -- Steven From hendrik at microcorp.co.za Mon Aug 31 09:44:30 2009 From: hendrik at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 31 Aug 2009 15:44:30 +0200 Subject: map In-Reply-To: References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: <200908311544.30746.hendrik@microcorp.co.za> On Monday 31 August 2009 11:31:34 Piet van Oostrum wrote: > But ultimately it is also very much a matter of taste, preference and > habit. This is true, but there is another reason that I posted - I have noticed that there seems to be a tendency amongst newcomers to the group to go to great lengths to find something that will do exactly what they want, irrespective of the inherent complexity or lack thereof of that which they are trying to do. Now I cannot understand why this is - one could say that it is caused by an eagerness to understand all the corners of the tool that is python, but somehow it does not feel like that to me - I see it almost as a crisis of confidence - as if the newbie lacks the self confidence to believe that he or she is capable of doing anything independently. So whenever I can, I try to encourage people to just do it their way, and to see what happens, and to hack using the interactive interpreter, to build confidence by experimenting and making mistakes, and realizing that when you have made a mistake, it is not the end of the world, - you can fix it and move on. Don't know if this rant makes any sense... - Hendrik From kw at codebykevin.com Mon Aug 31 09:52:13 2009 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 31 Aug 2009 09:52:13 -0400 Subject: An assessment of Tkinter and IDLE In-Reply-To: <827effaa-d0f7-4142-b4b9-6f9f8e0e7963@e34g2000vbm.googlegroups.com> References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> <827effaa-d0f7-4142-b4b9-6f9f8e0e7963@e34g2000vbm.googlegroups.com> Message-ID: <4A9BD58D.3060808@codebykevin.com> On 8/28/09 8:11 PM, r wrote: > On Aug 28, 5:48 pm, Mark Roseman wrote: > (snip) >> Thewww.tkdocs.comsite is 'language neutral' - currently the tutorial >> covers Tcl, Perl, Ruby and yes Python, and allows you to switch between >> any of those languages (or show all of them). > > True, however the coverage is incomplete. I would back this site if we > can get a complete coverage of all widgets in the Python language. > > +0.1 Are you certain the site is incomplete? Its coverage of the basic Tk and Ttk widgets is spectacular. . Its coverage of layout techinques and best practices for organizing complex interfaces with Tk is also extremely valuable. I wish this site had been around when I was learning Tk five years ago. I've looked at just about every Tk and Tkinter tutorial site out there, and this one surpasses them all. Mark Roseman--a professional, independent software developer whose commercial products almost all incorporate Tk into their GUI's--has spent a couple of years putting together this site with input from various users and developers (myself included). It's now an absolutely indispensible resource for beginners and more experienced developers. The reason the site does not cover 'all widgets in the Python language' is threefold: 1. It's a site about Tk, a tookit that has Python bindings and bindings to other languages also (Ruby, Perl, Tcl, etc.). 2. It omits additional Python-specific, Tkinter-based widget sets such as PMW, Tix, etc. because once you understand the basics of Tk, then grokking these other megawidget sets (which all build on top of Tk) should be pretty straightforward. 3. Finally, 'all widgets in the Python language' gets into other tookits as well, which is obviously unfeasible for a website. If the site by itself isn't enough for you, or is a bit too basic in its coverage of Python techniques, then there are other options. Couple the TkDocs site with effbot's more advanced walk through the various Tkinter classes, and perhaps one or two of the other Tkinter-specific tutorials, and you'll have learned a lot. But I think the TkDocs site is essential, especially in its more advanced discussion of how to put together an attractive, polished user interface with Tk. Tk has a long-standing reputation of being the toolkit of choice for quick, simple, ugly interfaces, and the other resources I've mentioned do nothing to to change this. The practices that Mark Roseman discusses will allow one to eventually put together a UI that matches anything that the other big toolkits (wxPython, PyQt, PyObjC, PyGtk, etc.) can do. Hope this helps, Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From xahlee at gmail.com Mon Aug 31 10:00:43 2009 From: xahlee at gmail.com (Xah Lee) Date: Mon, 31 Aug 2009 07:00:43 -0700 (PDT) Subject: =?windows-1252?Q?Math_Notations=2C_Computer_Languages=2C_and_the_=93Form?= =?windows-1252?Q?=94_in_Formalism?= Message-ID: <8f621b1f-a259-44dd-a6c4-231fa708ace7@j9g2000prh.googlegroups.com> ? Math Notations, Computer Languages, and the ?Form? in Formalism http://xahlee.org/cmaci/notation/index.html plain text version follows. (lacks links) ----------------------------- Math Notations, Computer Languages, and the ?Form? in Formalism Xah Lee, 2009-08-31 This page is a collection of essays and expositions on the subjects of nomenclature and notations in math and computer languages, in the context of facilitating human communication and theorem proving systems. Most of these essays here are originally from email, blogs, or rants. They are not of publication quality, and they are not a coherent exposition the subject. Here's a very brief summary of of these essays's central thesis: ? Traditional math notations are very inconsistent. Edsger Dijkstra is a leader in a movement of what's called Calculational Proofs. That is, using a notation that is consistent and facilitates the calculation aspects when doing math by humans. ? Today, especially since 1990s, tremendous advances are made in computer algebra systems and theorem proving systems. In these languages, a coherent syntax, grammar, are needed for math expressions. ? In computer algebra or theorem proving systems, they are intimately tied to the math philosophies of formalism and logicism. In a sense, formalism and logicism today are tied together as a single subject, and using computer languages as foundation. ? Math expressions/syntax in computer languages are intimately tied to math notations for human reading. (e.g. Mathematical, MathML are technologies that combine the two.) ? The syntax and grammar of today's computer languages, such as Java, C, Python, SQL, Lisp, are ad-hoc and their communities have little understanding of the knowledge gained in math related fields such as computer algebra or theorem proving languages. (This applies to functional langs such as Haskell as well, but to a lesser degree.) On the other hand, mathematicians in general are illiterate about programing or using computer languages. All of the above considered together, computer language designers and mathematicians, should be made aware of these issues, so that when they design or use computer languages, may it be math oriented or not, the language's syntax and grammar can move towards a consistent syntax system with solid foundation (as opposed to ad-hoc), and such language should have build-in markup or simple mapping to 2-dimensional notations for human reading (such as done with Mathematica or Semantic MathML), and this computer language should be in fact as a basis of theorem prover or computer algebra system (as in OCaml, Haskell, Mathematica). The languages of computer algebra and theorem prover would in fact merge together into one single subject if it is not already slowly happening today. Progress in the above issues are made in different fields but there are little unification going on. For example, there's Edsger Dijkstra's Calculational Proofs movement. It improves math notations towards consistency and formalism. However, people in Calculational Proofs movement are mostly math pedagogy community i think. They are not programers interested in computer languages, nor logicians interested in math formalism, or industrial and commercial organizations interested in math notation representation systems. There's the computer algebra community, such as Mathematica, Maple, Matlab, which requires a syntax and grammar for mathematical concepts. There's the theorem proving community, such as OCaml, Coq, HOL, which not only requires a syntax for math concepts, but also made major understanding about math as a system of forms, i.e. formal systems. Both computer algebra and theorem proving systems require math notations and computer language syntax that are consistent and can represent math concepts. However, the 2 camps are largely separate communities. For example, there is as far as i know no tool that is both a practical computer algebra system as well as a theorem proving language. Common computer languages, such as C, Java, Python, requires a good syntax, parsers, and compilers, but their community, including computer scientists and programers, are usually illiterate in typical topics of of mathematics proper. Functional languages, such as Scheme Lisp, APL, OCaml, Haskell, are more based on logic foundations (lambda calculus) but their syntax and grammar has little to do with the math notations as a logic or formal system. (these languages do not have a formal spec in the sense of Formlism, i.e. transformation of forms. In fact, almost no languages has a formal spec, formalism or not.) There's math notation representation needs, such as TeX, MathCAD, MathML, Mathematica. These are typically commercial organizations in the computing industry. They can render math notations. In the case of MathML and Mathematica, the language also represent the semantic content of math notations. These two made major understanding about the relation of math notations and computer languages, but they in general have little to do with formalism or theorem proving. (with some exception of Mathematica) Calculational proof notational system, Computer algebra systems, theorem prover languages, formalism and logicism as foundation of mathematics, functional languages, and computer languages in general, mathematics and its notations, all are in fact can be considered as a single subject with a unified goal. All the technologies and movements exist, but today they have mostly not come together. For example, Microsoft Equaton Editor, TeX, and various other tools does well with math notation rendering. MathML has both representational and semantic aspects (OpenMath is a new group that focus on semantic aspects), for the purpose of rendering as well semantic representation. Mathematica is a computer algebra system for solving arbitrary math equations, that is also able to represent math notation as a computer language, so that computation can be done with math notation directly. However, the system lacks a foundation as a theorem prover. Theorem provers such as OCaml (HOL, Coq), Mizar does math formalism as a foundation, also function as a generic computer language, but lacks abilities as a computer algebra system or math notation representation. Notations * The Codification of Mathematics * State Of Theorem Proving Systems 2008 * The Problems of Traditional Math Notation * A Notation for Plane Geometry * the Moronicity of the Expositions of Common Mathematicians (rant) * Fundamental Problems of Lisp (see section 1, on the importance for regularity of syntax) * The Concepts and Confusions of Prefix, Infix, Postfix and Fully Functional Notations * The Moronicities of Typography Jargons Math * Math Terminology and Naming of Things * Math Jargons Explained * Politics and the English Language, 1946, by George Orwell. Harm Of Bad Terminologies In Computing Languages * The Importance of Terminology's Quality In A Computer Language * What are OOP's Jargons and Complexities? * Java's Abuse of the Jargon ?Interface? and API * Jargons of Info Tech Industry * The Term Currying In Computer Science * Function Application is not Currying * Why You should Not Use The Jargon Lisp1 and Lisp2 * The Jargon ?Tail Recursion? * What Is Closure In A Programing Language * Jargons And High Level Languages (unpolished essay) * Why You Should Avoid The Jargon ?Tail Recursion? * I Can Not Find A Word Better Than ?CAR? Harm of Mixing Concept of Syntax and Formatting * The TeX Pestilence * The Harm of hard-wrapping Lines (harm of confusing syntax with formatting) * Tabs versus Spaces in Source Code (harm of treating syntax as formatting instead of syntax) Applications of Regular Syntax * A Text Editor Feature: Syntax Tree Walk (application of syntax) * A Simple Lisp Code Formatter (application of syntax regularity) References * ?Mathematica Notation: Past and Future? (2000-10-20), by Stephen Wolfram, at http://www.stephenwolfram.com/publications/recent/mathml/index.html. * Functional Mathematics, by Raymond Boute, 2006. http://www.funmath.be/ * Formalized Mathematics, by John Harrison, 1996-08-13. http://www.rbjones.com/rbjpub/logic/jrh0100.htm * ?How Computing Science created a new mathematical style?. (1990) By Edsger W Dijkstra. EWD1073 * ?Under the spell of Leibniz's dream? (2000) By Edsger W Dijkstra. EWD1298 * Abuse of notation * Formal system From nitebirdz at sacredchaos.com Mon Aug 31 10:21:11 2009 From: nitebirdz at sacredchaos.com (Nitebirdz) Date: Mon, 31 Aug 2009 16:21:11 +0200 Subject: Suggestion In-Reply-To: <7aa29e790908290212h17d27593u52d1a90b3e785386@mail.gmail.com> References: <7aa29e790908290212h17d27593u52d1a90b3e785386@mail.gmail.com> Message-ID: <20090831142109.GA7611@sevilla.sacredchaos.com> On Sat, Aug 29, 2009 at 02:42:36PM +0530, Thangappan.M wrote: > Dear all, > > I am in the process of learning Python programming language. I know > Perl,PHP. Compare to both the language Python impressed me because here > there is no lexical variables and all.Now I need suggestion saying that , > What online book can I follow? > > I have not yet learnt any advanced programming stuffs in Python. > Please suggest some book? or tutorial. net net my goal is that I will be > able to do the project in any languages(Python,Perl,PHP).So I need to learn > more depth knowledge of Python. > > So Please help me? > Thangappan, I'm no expert, but perhaps the following book will be of some help: http://diveintopython.org/ There are plenty of tutorials on the web too. Just do a quick search for something like "python tutorial". From wiggly at wiggly.org Mon Aug 31 10:36:46 2009 From: wiggly at wiggly.org (Nigel Rantor) Date: Mon, 31 Aug 2009 15:36:46 +0100 Subject: An assessment of the Unicode standard In-Reply-To: <200908311019.58029.hendrik@microcorp.co.za> References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <3e9ddb9b-8f61-4d8d-a25c-7e95e8a25c06@g1g2000vbr.googlegroups.com> <200908311019.58029.hendrik@microcorp.co.za> Message-ID: <4A9BDFFE.2040402@wiggly.org> Hendrik van Rooyen wrote: > On Sunday 30 August 2009 22:46:49 Dennis Lee Bieber wrote: > >> Rather elitist viewpoint... Why don't we just drop nukes on some 60% >> of populated landmasses that don't have a "western" culture and avoid >> the whole problem? > > Now yer talking, boyo! It will surely help with the basic problem which is > the heavy infestation of people on the planet! > :-) On two conditions: 1) We drop some "test" bombs on Slough to satisfy Betjeman. 2) We strap both Xah and r to aforementioned bombs. Also, I'm surprised no-one has mentioned Esperanto yet. Sounds like something r and Xah would *love*. Slightly off-topic - does anyone have a good recipe for getting thunderbird to kill whole threads for good? Either based on a rule or just some extension I can use? The Xah/r threads are like car crashes, I can't help but watch but my time could be better spent and I don't want to unsub the whole list. Cheers, n From nitebirdz at sacredchaos.com Mon Aug 31 10:40:50 2009 From: nitebirdz at sacredchaos.com (Nitebirdz) Date: Mon, 31 Aug 2009 16:40:50 +0200 Subject: a popen command line question In-Reply-To: <964997.10840.qm@web36907.mail.mud.yahoo.com> References: <964997.10840.qm@web36907.mail.mud.yahoo.com> Message-ID: <20090831144049.GB7611@sevilla.sacredchaos.com> On Sat, Aug 29, 2009 at 01:13:12PM -0700, Joni Lee wrote: > Hi all, > > I write a small script > > status = os.popen('top').readlines() > print status > > It calls the command line "top" and will print out the status. > But I have to press the keyboard "q" to quit "top", then the status > will be printed, otherwise it just stands by with blank. > > Question is. Do you know how to give "q" into my python script so that > "top" is automatically quit immediately or maybe after 1s (for > gathering information) > Why not run the actual 'top' command in batch mode with only one iteration? It's in the man page. I'm referring to this: status = os.popen('top -b -n 1').readlines() Also, the following approach seems to display a nicer output: ------------------------------------------------- #!/usr/bin/env python import os status=os.popen('top -b -n 1') for i in status.readlines(): print i ------------------------------------------------- Or how about the following? ------------------------------------------------- #!/usr/bin/env python import commands status=commands.getoutput('top -b -n 1') print status ------------------------------------------------- Mind you, I'm just suggesting different approaches. I'm new to Python and don't necessarily know what I'm doing. Other more experienced people may be able to suggest something better. From kyosohma at gmail.com Mon Aug 31 10:53:27 2009 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Aug 2009 07:53:27 -0700 (PDT) Subject: IDE for Python References: Message-ID: On Aug 29, 1:08?pm, ivanko.... at gmail.com wrote: > 29.08.2009 4:14 ???????????? "Thangappan.M" ? > ???????: > > > Dear all, > > Please suggest some good IDE for python.I am working in linux platform. > > -- > > Regards, > > Thangappan.M > > You can use Eclipse + PyDev or Emacs+PythonMode . Also there are Anjuta and ? > Code:Blocks, but they are designed mainly for C++ (but still can be used). Don't forget Wingware IDE. Admittedly, it's not free (except for a limited version), but it's pretty good. There's also SPE (Stani's Python Editor). If you want a nigh-complete list, check the Python wiki: http://wiki.python.org/moin/PythonEditors ------------------- Mike Driscoll Blog: http://blog.pythonlibrary.org From cmpython at gmail.com Mon Aug 31 11:32:19 2009 From: cmpython at gmail.com (Che M) Date: Mon, 31 Aug 2009 08:32:19 -0700 (PDT) Subject: IDE for Python References: Message-ID: <0f5f01d3-220e-4ef8-b55b-0f88f58a0afd@b18g2000vbl.googlegroups.com> On Aug 31, 10:53?am, Mike Driscoll wrote: > On Aug 29, 1:08?pm, ivanko.... at gmail.com wrote: > > > 29.08.2009 4:14 ???????????? "Thangappan.M" ? > > ???????: > > > > Dear all, > > > Please suggest some good IDE for python.I am working in linux platform. > > > -- > > > Regards, > > > Thangappan.M > > > You can use Eclipse + PyDev or Emacs+PythonMode . Also there are Anjuta and ? > > Code:Blocks, but they are designed mainly for C++ (but still can be used). > > Don't forget Wingware IDE. Admittedly, it's not free (except for a > limited version), but it's pretty good. There's also SPE (Stani's > Python Editor). If you want a nigh-complete list, check the Python > wiki: > > http://wiki.python.org/moin/PythonEditors Not sure when an editor gets to be called an IDE, but while on the site that OP should check out this related page: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments From tjreedy at udel.edu Mon Aug 31 11:36:03 2009 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 31 Aug 2009 11:36:03 -0400 Subject: An assessment of Tkinter and IDLE In-Reply-To: <4A9BD58D.3060808@codebykevin.com> References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> <827effaa-d0f7-4142-b4b9-6f9f8e0e7963@e34g2000vbm.googlegroups.com> <4A9BD58D.3060808@codebykevin.com> Message-ID: Kevin Walzer wrote: www.tkdocs.com [snip] > and you'll have learned a lot. But I think the TkDocs site is essential, > especially in its more advanced discussion of how to put together an > attractive, polished user interface with Tk. Tk has a long-standing > reputation of being the toolkit of choice for quick, simple, ugly > interfaces, and the other resources I've mentioned do nothing to to > change this. The practices that Mark Roseman discusses will allow one to > eventually put together a UI that matches anything that the other big > toolkits (wxPython, PyQt, PyObjC, PyGtk, etc.) can do. > > Hope this helps, It persuaded me to go and start reading. A couple of things of interest. "It would be a great help if you could have a look around, provide any comments, corrections or suggestions, or even help fill in some of the missing pieces. " so no pretense of completeness yet. "In the near future, the plan is to continue refining the tutorial, mainly finishing up the rest of the Perl and Python examples." And from the linked blog "July 09, 2009 Python material in progress. While not yet complete, I've managed to add a very hefty chunk of Python material to the tutorial. I should be able to complete the rest over the next week or so. Would definitely appreciate feedback from any Pythonistas on the existing material. While I hadn't used it before, I think Tkinter may very well be the nicest interface to Tk next to Tcl's (for which Tk was originally designed of course, so you'd expect a bit of an advantage). For people unfamiliar with either language, I think Python's more conventional use of parentheses for functions, the "option=value" syntax, plus other language features it takes advantage of are very attractive and win out over Tcl. The two main parts that I think Tcl does in a nicer way are event bindings and the fact you can create and geometry manage a widget in one statement, while still keeping a handle to a widget around. UPDATE July 17/2009: Most of the rest of the Python examples and code snippets have been added. " tjr From http Mon Aug 31 11:46:42 2009 From: http (Paul Rubin) Date: 31 Aug 2009 08:46:42 -0700 Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: <7xzl9gkmu5.fsf@ruckus.brouhaha.com> elsa writes: > map(myFunc(b='booHoo'), myList) > > Why doesn't this work? is there a way to make it work? You can use functools.partial but a listcomp might be simpler: list(myfunc(a, b='booHoo') for a in myList) There is another listcomp syntax with square brackets, but I try to avoid it because it has broken behavior (leaks the index variable) in Python 2.x. From http Mon Aug 31 11:48:14 2009 From: http (Paul Rubin) Date: 31 Aug 2009 08:48:14 -0700 Subject: lambda functions References: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> Message-ID: <7xvdk4kmrl.fsf@ruckus.brouhaha.com> Pierre writes: > s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s > [index]-1 What are you trying to do here anyway? That looks broken. Maybe you want the list.insert method. From koranthala at gmail.com Mon Aug 31 12:03:13 2009 From: koranthala at gmail.com (koranthala) Date: Mon, 31 Aug 2009 09:03:13 -0700 (PDT) Subject: executable path finding Message-ID: <9d71d0bd-5109-45b6-bce7-114607386063@y10g2000prf.googlegroups.com> Hi, I am creating a python application using py2exe. I am facing a problem which I am not sure how to solve. The application contains many other files associated with it - like icons, config files etc. The executable can be in any directory. If the user creates a shortcut to the executable to run in desktop, the program fails - saying that the icon image cannot be found. But I can run the application properly, if I run it from application directory - where all the other icons, config files etc are kept. How is such issues usually solved? I do not want to hardcode the paths of icons and store the icons in those paths. I guess, we can change the directory to the application directory before running the application. (in __init__.py ???) But how do we find the current directory in that case? I am completely at sea in solving this. This looks to be a very common issue. How is this usually solved? From deets at nospam.web.de Mon Aug 31 12:07:20 2009 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 31 Aug 2009 18:07:20 +0200 Subject: executable path finding References: <9d71d0bd-5109-45b6-bce7-114607386063@y10g2000prf.googlegroups.com> Message-ID: <7g2apoF2nipofU2@mid.uni-berlin.de> koranthala wrote: > Hi, > I am creating a python application using py2exe. I am facing a > problem which I am not sure how to solve. > The application contains many other files associated with it - > like icons, config files etc. The executable can be in any directory. > If the user creates a shortcut to the executable to run in desktop, > the program fails - saying that the icon image cannot be found. But I > can run the application properly, if I run it from application > directory - where all the other icons, config files etc are kept. > How is such issues usually solved? I do not want to hardcode the > paths of icons and store the icons in those paths. I guess, we can > change the directory to the application directory before running the > application. (in __init__.py ???) But how do we find the current > directory in that case? I am completely at sea in solving this. > This looks to be a very common issue. How is this usually solved? You can get the location of a module via module.__file__ This can be used to find a file relative to e.g. the toplevel module/package of your application. The pkg_resources-module of setuptools encapsulates that even into a stream and file-name api. Diez From daniel.watrous at gmail.com Mon Aug 31 12:11:46 2009 From: daniel.watrous at gmail.com (Daniel) Date: Mon, 31 Aug 2009 09:11:46 -0700 (PDT) Subject: find free hard disk space remote windows host Message-ID: <6070a0b2-23db-4824-851b-4920a31bd38e@q14g2000vbi.googlegroups.com> Hello, I'm trying to determine the amount of free hard disk space on a remote windows host. Seems like this should be simple, but it's giving me grief. Here's what I've tried: >>> mystat = os.stat('//remotehost/share/') >>> mystat (16895, 0L, 0, 0, 0, 0, 0L, 1251731920, 1251731289, 1249399952) For some reason it doesn't show the details about space on the remote path. Next I tried this: subprocess.call('dir //remotehost/share/ | find "bytes free"', shell=True) But this only returns the status, not the output, which is what I need. How can I determine the amount of free hard drive space on a remote windows host using python? Thanks From vicente.soler at gmail.com Mon Aug 31 12:19:28 2009 From: vicente.soler at gmail.com (vsoler) Date: Mon, 31 Aug 2009 09:19:28 -0700 (PDT) Subject: Efficient way to sum a product of numbers... Message-ID: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> Hi, After simplifying my problem, I can say that I want to get the sum of the product of two culumns: Say m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] r={'a':4, 'b':5, 'c':6} What I need is the calculation 1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 That is, for each row list in variable 'm' look for its first element in variable 'r' and multiply the value found by the second element in row 'm'. After that, sum all the products. What's an efficient way to do it? I have thousands of these calculations to make on a big data file. Thank you. From python.list at tim.thechases.com Mon Aug 31 12:30:27 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 31 Aug 2009 11:30:27 -0500 Subject: Efficient way to sum a product of numbers... In-Reply-To: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> Message-ID: <4A9BFAA3.3000308@tim.thechases.com> > After simplifying my problem, I can say that I want to get the sum of > the product of two culumns: > > Say > m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] assuming you meant ['c', 3] here... ^ > r={'a':4, 'b':5, 'c':6} > > What I need is the calculation > > 1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 and you mean "3*6" here instead of "3*4", which is 18 instead of 12, making the whole sum 4+10+18=32 Then it sounds like you could do something like result = sum(v * r[k] for k,v in m) where "m" is any arbitrary iterable of tuples. If the keys (the letters) aren't guaranteed to be in "r", then you can use defaults (in this case "0", but could just as likely be "1" depending on your intent): result = sum(v * r.get(k,0) for k,v in m) If the conditions above don't hold, you'll have to introduce me to your new math. ;-) -tkc From rami.chowdhury at gmail.com Mon Aug 31 12:31:25 2009 From: rami.chowdhury at gmail.com (Rami Chowdhury) Date: Mon, 31 Aug 2009 09:31:25 -0700 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <6Djmm.14757$ze1.10295@news-server.bigpond.net.au> Message-ID: No need to feed the troll by actually trying to engage in the discussion, but just FYI: > Sanskrit is mostly written in Devanagari these days which is also > useful for selling things to people who speak Hindi and other Indian > languages. Devanagari is what's used for Hindi and a handful of other languages, yes, but most Indian languages (Gujarati, Punjabi, Bengali, and Tamil just to name a few) use different scripts. On Sat, 29 Aug 2009 20:07:17 -0700, Neil Hodgson wrote: > Benjamin Peterson: > >> Like Sanskrit or Snowman language? > > Sanskrit is mostly written in Devanagari these days which is also > useful for selling things to people who speak Hindi and other Indian > languages. > > Not sure if you are referring to the ? snowman character or Arctic > region languages like Canadian Aboriginal syllabic writing like ????? > which were added to Unicode 8 years after the initial version. I'd guess > that was added from political rather than marketing motives. ? was > required since it was present in Japanese character sets. > > Neil -- Rami Chowdhury "Never attribute to malice that which can be attributed to stupidity" -- Hanlon's Razor 408-597-7068 (US) / 07875-841-046 (UK) / 0189-245544 (BD) From koranthala at gmail.com Mon Aug 31 12:37:24 2009 From: koranthala at gmail.com (koranthala) Date: Mon, 31 Aug 2009 09:37:24 -0700 (PDT) Subject: executable path finding References: <9d71d0bd-5109-45b6-bce7-114607386063@y10g2000prf.googlegroups.com> <7g2apoF2nipofU2@mid.uni-berlin.de> Message-ID: <40dd30b5-c65c-4fb2-9a3a-c9264f333018@m7g2000prd.googlegroups.com> On Aug 31, 9:07?pm, "Diez B. Roggisch" wrote: > koranthala wrote: > > Hi, > > ? ? I am creating a python application using py2exe. I am facing a > > problem which I am not sure how to solve. > > ? ? The application contains many other files associated with it - > > like icons, config files etc. The executable can be in any directory. > > If the user creates a shortcut to the executable to run in desktop, > > the program fails - saying that the icon image cannot be found. But I > > can run the application properly, if I run it from application > > directory - where all the other icons, config files etc are kept. > > ? ? How is such issues usually solved? I do not want to hardcode the > > paths of icons and store the icons in those paths. I guess, we can > > change the directory to the application directory before running the > > application. (in __init__.py ???) But how do we find the current > > directory in that case? I am completely at sea in solving this. > > ? ? This looks to be a very common issue. How is this usually solved? > > You can get the location of a module via > > ?module.__file__ > > This can be used to find a file relative to e.g. the toplevel module/package > of your application. > > The pkg_resources-module of setuptools encapsulates that even into a stream > and file-name api. > > Diez Thank you Diez. It was what I was looking for. From robert.kern at gmail.com Mon Aug 31 12:43:30 2009 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 31 Aug 2009 11:43:30 -0500 Subject: rcond in numpy : In-Reply-To: References: Message-ID: On 2009-08-31 04:02 AM, Pierre wrote: > > Hello, > > Anyone knows the numpy equivalent of the matlab function : rcond > (Matrix reciprocal condition number estimate) ? You will want to ask numpy questions on the numpy mailing list: http://www.scipy.org/Mailing_Lists numpy.linalg.cond() will give you the condition number of the matrix. Invert it to get the reciprocal. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From vicente.soler at gmail.com Mon Aug 31 12:43:45 2009 From: vicente.soler at gmail.com (vsoler) Date: Mon, 31 Aug 2009 09:43:45 -0700 (PDT) Subject: Efficient way to sum a product of numbers... References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> Message-ID: <26d7f803-ec2d-4195-a48b-d34c0cbedc84@h30g2000vbr.googlegroups.com> On Aug 31, 6:30?pm, Tim Chase wrote: > > After simplifying my problem, I can say that I want to get the sum of > > the product of two culumns: > > > Say > > ? ? ? ? ?m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] > > assuming you meant ['c', 3] here... ? ?^> ? ? ? ? ?r={'a':4, 'b':5, 'c':6} > > > What I need is the calculation > > > ? ? ? ? ?1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 > > and you mean "3*6" here instead of "3*4", which is 18 instead of > 12, making the whole sum 4+10+18=32 > > Then it sounds like you could do something like > > ? result = sum(v * r[k] for k,v in m) > > where "m" is any arbitrary iterable of tuples. ?If the keys (the > letters) aren't guaranteed to be in "r", then you can use > defaults (in this case "0", but could just as likely be "1" > depending on your intent): > > ? result = sum(v * r.get(k,0) for k,v in m) > > If the conditions above don't hold, you'll have to introduce me > to your new math. ;-) > > -tkc Hello Tim, There is no mistake in my original post, so I really meant [ 'a', 3] Imagine that m contains time sheets of suppliers supplier 'a' has worked for you 1 hour supplier 'b' has worked for you 2 hour supplier 'a' has worked for you 3 hour Now supplier 'a' charges $4 per hour supplier 'b' charges $5 per hour supplier 'c' charges $6 per hour I want to know how much I will be charged this month by my pannel of suppliers. 1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 This is what I am after. I expect all my suppliers to have handed me in advance the per hour fee. If at least one hasn't, I must know that the result is undefined. Hope this helps Vicente Soler From python.list at tim.thechases.com Mon Aug 31 12:59:01 2009 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 31 Aug 2009 11:59:01 -0500 Subject: Efficient way to sum a product of numbers... In-Reply-To: <26d7f803-ec2d-4195-a48b-d34c0cbedc84@h30g2000vbr.googlegroups.com> References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> <26d7f803-ec2d-4195-a48b-d34c0cbedc84@h30g2000vbr.googlegroups.com> Message-ID: <4A9C0155.2090505@tim.thechases.com> vsoler wrote: > On Aug 31, 6:30 pm, Tim Chase wrote: >>> After simplifying my problem, I can say that I want to get the sum of >>> the product of two culumns: >>> Say >>> m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] >> assuming you meant ['c', 3] here... ^> r={'a':4, 'b':5, 'c':6} >> >>> What I need is the calculation >>> 1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 >> and you mean "3*6" here instead of "3*4", which is 18 instead of >> 12, making the whole sum 4+10+18=32 >> >> Then it sounds like you could do something like >> >> result = sum(v * r[k] for k,v in m) >> >> where "m" is any arbitrary iterable of tuples. If the keys (the >> letters) aren't guaranteed to be in "r", then you can use >> defaults (in this case "0", but could just as likely be "1" >> depending on your intent): >> >> result = sum(v * r.get(k,0) for k,v in m) >> >> If the conditions above don't hold, you'll have to introduce me >> to your new math. ;-) > There is no mistake in my original post, so I really meant [ 'a', 3] Ah...that makes more sense of the data. My answer still holds then. Use the r[k] version instead of the r.get(...) version, and it will throw an exception if the rate doesn't exist in your mapping. (a KeyError if you want to catch it) -tkc From rt8396 at gmail.com Mon Aug 31 13:00:01 2009 From: rt8396 at gmail.com (r) Date: Mon, 31 Aug 2009 10:00:01 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> <1010dd16-fa92-46b6-8391-b8a701704472@s31g2000yqs.googlegroups.com> <827effaa-d0f7-4142-b4b9-6f9f8e0e7963@e34g2000vbm.googlegroups.com> <4A9BD58D.3060808@codebykevin.com> Message-ID: Kevin and Terry, Kevin. I respectfully disagree that the site is ready for prime time *However* i do not wish to undermine the great work that Mark Roseman has done here and i thank him for his contribution. He has put much work into covering all the major languages and i think this site *could* turn out to be the best one-stop-shop for Tk coding no matter what language you come use. And Actually of all the sites that i know of, his is by far the most professional/modern looking of all! My only beef with Mark's site is lack of detailed information OR a reference manual of sorts in the Python language. We have too many places around the net one must go to get this information when starting the road to Tkinter. The Effbot site is great with much detail but is not a good reference. John's NMT site is a great reference but lacks the extensive tutorial style details of effbot. Mark's site is the shiny new corvette, however the engine is on back order? We need to compile this info into one beautiful orgy of Tkinter learning material. Here are the three sites that i mentioned above, they would compress well into one... http://effbot.org/tkinterbook/ http://infohost.nmt.edu/tcc/help/pubs/tkinter/ http://www.tkdocs.com/ [TERRY SAID..] While I hadn't used it before, I think Tkinter may very well be the nicest interface to Tk next to Tcl's (for which Tk was originally designed of course, so you'd expect a bit of an advantage). For people unfamiliar with either language, I think Python's more conventional use of parentheses for functions, the "option=value" syntax, plus other language features it takes advantage of are very attractive and win out over Tcl. [/TERRY] Well put Terry! I could not agree more with this assessment! Pythons wrapping of Tk is so beautiful next to the other languages i can bet a lot of Ruby, Tcl, and Perl guys are going to feel like ugly ducklings at a Ms america pageant! (but i may be partial to Python code... just a little) ;-) When it comes to using Tkinter I think a lot of people let ego get in the way. Yes the name may sound synonymous with "Tinker Toys" however, TEE-KAY-ENTER is a great (albeit simple) GUI toolkit. I use it quite often and reach for the power of wx only when i need the extra functionality -- which the gap is starting to close. Anyhow, welcome to Tkinter Terry, i only wished you would had dropped by sooner...??? :) psst: maybe you can use your influence and convince others that Tk is not so bad? From vicente.soler at gmail.com Mon Aug 31 13:13:34 2009 From: vicente.soler at gmail.com (vsoler) Date: Mon, 31 Aug 2009 10:13:34 -0700 (PDT) Subject: Efficient way to sum a product of numbers... References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> <26d7f803-ec2d-4195-a48b-d34c0cbedc84@h30g2000vbr.googlegroups.com> Message-ID: On Aug 31, 6:59?pm, Tim Chase wrote: > vsoler wrote: > > On Aug 31, 6:30 pm, Tim Chase wrote: > >>> After simplifying my problem, I can say that I want to get the sum of > >>> the product of two culumns: > >>> Say > >>> ? ? ? ? ?m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] > >> assuming you meant ['c', 3] here... ? ?^> ? ? ? ? ?r={'a':4, 'b':5, 'c':6} > > >>> What I need is the calculation > >>> ? ? ? ? ?1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 > >> and you mean "3*6" here instead of "3*4", which is 18 instead of > >> 12, making the whole sum 4+10+18=32 > > >> Then it sounds like you could do something like > > >> ? result = sum(v * r[k] for k,v in m) > > >> where "m" is any arbitrary iterable of tuples. ?If the keys (the > >> letters) aren't guaranteed to be in "r", then you can use > >> defaults (in this case "0", but could just as likely be "1" > >> depending on your intent): > > >> ? result = sum(v * r.get(k,0) for k,v in m) > > >> If the conditions above don't hold, you'll have to introduce me > >> to your new math. ;-) > > There is no mistake in my original post, so I really meant [ 'a', 3] > > Ah...that makes more sense of the data. ?My answer still holds > then. ?Use the r[k] version instead of the r.get(...) version, > and it will throw an exception if the rate doesn't exist in your > mapping. ?(a KeyError if you want to catch it) > > -tkc It works!!! Thank you From szport at gmail.com Mon Aug 31 13:21:22 2009 From: szport at gmail.com (zaur) Date: Mon, 31 Aug 2009 10:21:22 -0700 (PDT) Subject: Is behavior of += intentional for int? References: Message-ID: On 29 ???, 16:45, zaur wrote: > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin > Type "copyright", "credits" or "license()" for more information.>>> a=1 > >>> x=[a] > >>> id(a)==id(x[0]) > True > >>> a+=1 > >>> a > 2 > >>> x[0] > > 1 > > I thought that += should only change the value of the int object. But > += create new. > Is this intentional? As a result of this debate is not whether we should conclude that there should be two types of integers in python: 1) immutable numbers, which behave as constant value; 2) mutable numbers, which behave as variable value? From ajoys123 at gmail.com Mon Aug 31 13:23:48 2009 From: ajoys123 at gmail.com (devaru) Date: Mon, 31 Aug 2009 10:23:48 -0700 (PDT) Subject: Logging contents of IRC channel Message-ID: I am new to Python. I want to log the activities in an IRC channel. Any pointers regarding this would be of great help. From rt8396 at gmail.com Mon Aug 31 13:29:22 2009 From: rt8396 at gmail.com (r) Date: Mon, 31 Aug 2009 10:29:22 -0700 (PDT) Subject: An assessment of Tkinter and IDLE References: <55a0833d-3f1f-402a-8eb7-cb4b7861cce5@q5g2000yqh.googlegroups.com> Message-ID: <799b8346-dc43-48be-aee0-bc5b1b235e1e@e34g2000vbm.googlegroups.com> On Aug 28, 11:12?am, Mark Roseman wrote: > Would it be useful to link to this from the main Python Tkinter > documentation? > > Mark Sorry Mark, i did not realize when i replied to you that YOU are the Mark of tkdoc.com. For some reason i only saw Tcl code when i visted the site, and that prompted my slightly grumpy rant. After looking a second time (and actually reading more) i see this site has much promise. I hope my post did not seem condescending of your efforts. I think your site is beautiful and just wish we could add MORE Python specific info to it like i covered in my last post. And also I would like to see a complete coverage of all the widgets. We more experienced guys already know how and where to find the thousand or so sites for this or that Python info, but the new users are going to be lost in the wilderness. I love that Python has so much info out there, i just hate that is so spread out! We must do something about this in a way that all doc/tut creators can be happy. PS: and i would like to contribute to your site. From pavlovevidence at gmail.com Mon Aug 31 13:59:41 2009 From: pavlovevidence at gmail.com (Carl Banks) Date: Mon, 31 Aug 2009 10:59:41 -0700 (PDT) Subject: Is behavior of += intentional for int? References: Message-ID: On Aug 31, 10:21?am, zaur wrote: > On 29 ???, 16:45, zaur wrote: > > > > > > > Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) > > [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin > > Type "copyright", "credits" or "license()" for more information.>>> a=1 > > >>> x=[a] > > >>> id(a)==id(x[0]) > > True > > >>> a+=1 > > >>> a > > 2 > > >>> x[0] > > > 1 > > > I thought that += should only change the value of the int object. But > > += create new. > > Is this intentional? > > As a result of this debate is not whether we should conclude that > there should be two types of integers in python: 1) immutable numbers, > which behave as constant value; 2) mutable numbers, which behave as > variable value? You are free to use third-party modules (such as numpy) which provide mutable numbers. I see no reason to include any mutable number type standard library, as not many people will require the performance benefits and/or indirection of mutable numbers, and those who do are free to use third- party modules that provide them. Carl Banks From sccolbert at gmail.com Mon Aug 31 14:15:20 2009 From: sccolbert at gmail.com (Chris Colbert) Date: Mon, 31 Aug 2009 14:15:20 -0400 Subject: IDE for Python In-Reply-To: <0f5f01d3-220e-4ef8-b55b-0f88f58a0afd@b18g2000vbl.googlegroups.com> References: <0f5f01d3-220e-4ef8-b55b-0f88f58a0afd@b18g2000vbl.googlegroups.com> Message-ID: <7f014ea60908311115s33f32d63v39706acba8fad9b3@mail.gmail.com> I'm a big fan of wing. Pay for the non-free version and you get all the goodies, plus PHENOMENAL support. Really. They answer support emails within a few minutes. Its has the best code completion i've seen in any python editor/ide and is also the most stable, fastest (for ide's), and customizable. I am not affiliated with Wingware or their parent company in any way. On Mon, Aug 31, 2009 at 11:32 AM, Che M wrote: > On Aug 31, 10:53?am, Mike Driscoll wrote: >> On Aug 29, 1:08?pm, ivanko.... at gmail.com wrote: >> >> > 29.08.2009 4:14 ???????????? "Thangappan.M" ? >> > ???????: >> >> > > Dear all, >> > > Please suggest some good IDE for python.I am working in linux platform. >> > > -- >> > > Regards, >> > > Thangappan.M >> >> > You can use Eclipse + PyDev or Emacs+PythonMode . Also there are Anjuta and ? >> > Code:Blocks, but they are designed mainly for C++ (but still can be used). >> >> Don't forget Wingware IDE. Admittedly, it's not free (except for a >> limited version), but it's pretty good. There's also SPE (Stani's >> Python Editor). If you want a nigh-complete list, check the Python >> wiki: >> >> http://wiki.python.org/moin/PythonEditors > > Not sure when an editor gets to be called an IDE, but while on the > site > that OP should check out this related page: > > http://wiki.python.org/moin/IntegratedDevelopmentEnvironments > > -- > http://mail.python.org/mailman/listinfo/python-list > From http Mon Aug 31 14:27:03 2009 From: http (Paul Rubin) Date: 31 Aug 2009 11:27:03 -0700 Subject: Efficient way to sum a product of numbers... References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> Message-ID: <7xab1f2614.fsf@ruckus.brouhaha.com> vsoler writes: > m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] > r={'a':4, 'b':5, 'c':6} > > What I need is the calculation > > 1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 sum(r[k]*w for k,w in m) From http Mon Aug 31 14:30:13 2009 From: http (Paul Rubin) Date: 31 Aug 2009 11:30:13 -0700 Subject: Logging contents of IRC channel References: Message-ID: <7x63c325vu.fsf@ruckus.brouhaha.com> devaru writes: > I am new to Python. I want to log the activities in an IRC channel. > Any pointers regarding this would be of great help. http://science.slashdot.org/science/04/04/13/1356216.shtml From mail at timgolden.me.uk Mon Aug 31 14:39:56 2009 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 31 Aug 2009 19:39:56 +0100 Subject: find free hard disk space remote windows host In-Reply-To: <6070a0b2-23db-4824-851b-4920a31bd38e@q14g2000vbi.googlegroups.com> References: <6070a0b2-23db-4824-851b-4920a31bd38e@q14g2000vbi.googlegroups.com> Message-ID: <4A9C18FC.2050702@timgolden.me.uk> Daniel wrote: > Hello, > > I'm trying to determine the amount of free hard disk space on a remote > windows host. Seems like this should be simple, but it's giving me > grief. Here's what I've tried: > >>>> mystat = os.stat('//remotehost/share/') >>>> mystat > (16895, 0L, 0, 0, 0, 0, 0L, 1251731920, 1251731289, 1249399952) Assuming you have the necessary security levels, WMI's quite good at this kind of thing. See this example: http://timgolden.me.uk/python/wmi_cookbook.html#percentage_free and just add "remotehost" as the first parameter to the wmi.WMI () call. (And I recommend find_classes=False) for speed. TJG From jgardner at jonathangardner.net Mon Aug 31 14:56:29 2009 From: jgardner at jonathangardner.net (Jonathan Gardner) Date: Mon, 31 Aug 2009 11:56:29 -0700 (PDT) Subject: Logging contents of IRC channel References: Message-ID: <395c130e-3269-453f-b8e5-379aea2de7d8@i18g2000pro.googlegroups.com> On Aug 31, 10:23?am, devaru wrote: > I am new to Python. I want to log the activities in an IRC channel. > Any pointers regarding this would be of great help. How are you going to plug into the chat server to obtain the data? How will you store the data? The in between parts are really easy. From 71david at libero.it Mon Aug 31 15:04:27 2009 From: 71david at libero.it (David) Date: Mon, 31 Aug 2009 21:04:27 +0200 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> Message-ID: <171zfm8mhuokq.1e4ltdmqqfp01.dlg@40tude.net> Il Sun, 30 Aug 2009 16:08:46 -0700 (PDT), r ha scritto: > Yes i agree but your logic is flawed. If someone cuts my brake lines > and i cannot stop who is to blame? Or if someone throws nails on the > highway and i crash, who is to blame? Obviously you cannot blame the > car owner. However if i let my brake pads wear out until they are > metal on metal and run over some poor old lady crossing the street -- > well now you got me! ;) > > But you cannot apply this logic when a hacker compromises someones > computer, it the same as cutting their brake lines. How can you > honestly expect that Joe computer user will know of this infection? I expect that user makes periodical and hopefully frequent checks to his computer. Today most of the people simply does absolutely nothing. Obvioulsy there is a vulnerability time between two check, but Perfection does not belongs to human beings so we must accept the risk of being cracked and being aware that we will charged for our computer actions, even if we are not directly responsible. It's a question of point of view: in italy if a thief steals a car and causes an accident the car's owner's assurance (having a car assurance is mandatory) must refund the victims. That's because protections of victims is first priority. Obviously the owner can not be charged >Do > you even know where your brake lines are? Even hackers can be hacked > without ever knowing it! The only sure fire way is VM's or system re- > installs. That's a problem of the computer owner. Why should the rest of the world be charged of *his* problem while keeping him safe from suffering any consequence? >[...] >> I think it's time to switch to responsible computing and the mail-tax would >> charge each person of its own costs and annoyances without affectig the rest >> of the world. > > What, this is madness! If you have terrorist terrorizing your country > you don't tax the public when they blow up a shopping mall so you can > rebuild it! No you kill the terrorist in a harsh and painful manner > and make an example of them, then you seize there monies. You should > direct your anger to the proper internet security authorities(and more > importantly to the perpetrator's) and not the innocent victims of such > attacks. I want you to sit back and think very deeply about your > proposal here because it is horribly wrong. Madness, you say? Let's examine the situation a bit moore deeply. First, the mail-tax would is not for rebuilding the destroyed building after the attack but, at the opposite, to prevent the attack. Wouldn't you pay a small tax to prevent terrorist's attacks? The mail-tax would be really small, if you send 1000 mails at month (a real huge traffic, for a non spammer!) the bill would be about 10 cents. Do you really think this is too much to get rid of most of the spam? Second, today we *are* paying that tax to repair building destroyed by terrorists. We are paying and hidden tax in terms of HW and human resources needed by ISPs to manage that huge (~90%) useless/malicius traffic. (I don't mention const related to dalays, denial of services, theft of informations...) Those costs are obviously charged by ISPs on our montly subscription bill. By the mail-tax we achive 3 results: 1. stopping forever direct spammers. 2. make each owner aware that his computer is compromised when the montly bill is higher than usual. 3. make that owner aware that *he* must pay for *his* problem and the rest of the world (included, I hope, you) is no more willing to be charged for this. The mail-tax may not be Final Solution against spam, but helps a lot. > > It is so easy to just slap a tax on something, yes that will solve > everything. *sarcasm* You should reconsider your position because you are actually blaming the present situation, not my proposal. Finally a little criticims: spam and related malware is a problem growing day by day. I am proposing a solution and if somebody doest't like it, well, he should propose a better one. Just saying "NO!" and turning head aside hoping that the problem will solve by itsef is no more acceptable. > >>> If you want to avoid usenet spam and don't want to filter it yourself, >>> find a provider with more aggressive spam filter. >> >> This is not the solution. You are saying that if your neighbour makes loud >> noises you can not call police to impose him to cease but you can only make >> your home soundproof. > > or you could go over and punch him in the nose, works every time for > me ;-) In italy we say: "preventing is better than treating" (a disease). Regards David From zuo at chopin.edu.pl Mon Aug 31 15:22:20 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Mon, 31 Aug 2009 21:22:20 +0200 Subject: map In-Reply-To: <7xzl9gkmu5.fsf@ruckus.brouhaha.com> References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> <7xzl9gkmu5.fsf@ruckus.brouhaha.com> Message-ID: Another possibilities, if you really *desire* to use map() and not list-comprehension (I'd prefer the latter), are: # Python 2.x: map(func, mylist, itertools.repeat('booHoo', len(mylist))) # Python 3.x, where map() works like Py2.x's itertools.imap(): list(map(func, mylist, itertools.repeat('booHoo'))) Cheers, *j -- Jan Kaliszewski (zuo) From mcravitz at att.net Mon Aug 31 15:43:04 2009 From: mcravitz at att.net (MikeC) Date: Mon, 31 Aug 2009 12:43:04 -0700 (PDT) Subject: win32ui DLL Load Failed Message-ID: I have a python executable that's failing to load on a user's machine running Windows XP. My developer machine is also running Windows XP. I have determined that it is failing when it attempts to load win32ui. I have Python 2.6 on my developer machine and am using the pywin support (Mark Hammonds???) for Python 2.6. In order to make the problem smaller and more managable I created an executable (with pytoexe) of a 1 one-line python script which does the following: import win32ui Running the one-line script on my machine from python source as well as from the executable created from the one-line source works fine on my machine. But when I attempt to run the executable on a target Windows/XP user machine (without Python) it fails with the following traceback Traceback (most recent call last): File "CheckScan.py", line 7, in File "PrintImage.pyc", line 1, in File "win32ui.pyc", line 12, in File "win32ui.pyc", line 10, in __load ImportError: DLL load failed: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. The only thing I can think of regarding the difference between my machine and the target machine is that I have the .NET framework on my machine. Is it possible that that is the problem? Running Depends didn't get me anywhere. I would appreciate any help you can offer. From gordon at panix.com Mon Aug 31 15:44:03 2009 From: gordon at panix.com (John Gordon) Date: Mon, 31 Aug 2009 19:44:03 +0000 (UTC) Subject: Unexpected 411 error response using httplib Message-ID: I'm writing some code that queries a Microsoft Exchange Web Services server. The server is responding with a 411 Length Required error, which is strange because I am definitely sending a Content-Length header. Here's the code: ----------------------------------------------------- import httplib import base64 SoapMessage = """\ Default \ """ host = "some.host.com" username = "myUsername" password = "myPassword" auth = base64.encodestring(username + ":" + password) conn = httplib.HTTPSConnection(host) conn.set_debuglevel(5) conn.putrequest("POST", "/EWS/Exchange.asmx") conn.putheader("Content-type", "text/xml; charset=\"UTF-8\"") conn.putheader("Proxy-Authorization", "Basic %s" % auth) conn.putheader("Content-Length", "%d" % len(SoapMessage)) conn.putheader("User-Agent", "Python post") conn.endheaders() conn.send(SoapMessage) resp = conn.getresponse() body = resp.read() headers = resp.msg version = resp.version status = resp.status reason = resp.reason conn.close() print "Response: ", status, reason print "Headers: ", headers print body ----------------------------------------------------- As you can see, I am including the call to putheader() for Content-Length, and the debugging output confirms that the header is present in the outgoing message. So why am I getting a 411 Length Required error? -- John Gordon A is for Amy, who fell down the stairs gordon at panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" From no.email at please.post Mon Aug 31 15:46:37 2009 From: no.email at please.post (kj) Date: Mon, 31 Aug 2009 19:46:37 +0000 (UTC) Subject: pyjamas in action? Message-ID: At work we want to implement a webapp using Google's GWT, and we're debating whether to use the standard GWT approach with Java, or to try Pyjamas. There's no great love here for Java, but there's the concern that Pyjamas will not be able to deliver the full power and/or convenience of standard Java-based GWT. (Why-oh-why did Google pick Java for this? Couldn't Guido twist some arms? Just kidding.) Are there any examples of real production websites implemented with Pyjamas? TIA! kynn From emile at fenx.com Mon Aug 31 15:48:08 2009 From: emile at fenx.com (Emile van Sebille) Date: Mon, 31 Aug 2009 12:48:08 -0700 Subject: An assessment of the Unicode standard In-Reply-To: References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <3e9ddb9b-8f61-4d8d-a25c-7e95e8a25c06@g1g2000vbr.googlegroups.com> <200908311019.58029.hendrik@microcorp.co.za> <4A9BDFFE.2040402@wiggly.org> Message-ID: On 8/31/2009 10:41 AM Dennis Lee Bieber said... > On Mon, 31 Aug 2009 15:36:46 +0100, Nigel Rantor >> Also, I'm surprised no-one has mentioned Esperanto yet. Sounds like >> something r and Xah would *love*. >> > Hmmm, thought I had mentioned Esperanto (and Klingon) Just curious -- has anyone mentioned autocoding? :) Emile From kyosohma at gmail.com Mon Aug 31 15:48:37 2009 From: kyosohma at gmail.com (Mike Driscoll) Date: Mon, 31 Aug 2009 12:48:37 -0700 (PDT) Subject: win32ui DLL Load Failed References: Message-ID: <591c8c0d-8134-4bd6-923f-7b05066c92ad@m20g2000vbp.googlegroups.com> On Aug 31, 2:43?pm, MikeC wrote: > I have a python executable that's failing to load on a user's machine > running Windows XP. My developer machine is also running Windows XP. I > have determined that it is failing when it attempts to load win32ui. > > I have Python 2.6 on my developer machine and am using the pywin > support (Mark Hammonds???) for Python 2.6. > > In order to make the problem smaller and more managable I created an > executable (with pytoexe) of a 1 one-line python script which does the > following: > > import win32ui > > Running the one-line script on my machine from python source as well > as from the executable created from the one-line source works fine on > my machine. But when I attempt to run the executable on a target > Windows/XP user machine (without Python) it fails with the following > traceback > > Traceback (most recent call last): > ? File "CheckScan.py", line 7, in > ? File "PrintImage.pyc", line 1, in > ? File "win32ui.pyc", line 12, in > ? File "win32ui.pyc", line 10, in __load > ImportError: DLL load failed: This application has failed to start > because the application configuration is incorrect. Reinstalling the > application may fix this problem. > > The only thing I can think of regarding the difference between my > machine and the target machine is that I have the .NET framework on my > machine. Is it possible that that is the problem? Running Depends > didn't get me anywhere. I would appreciate any help you can offer. Did you install PyWin32? If so, which version? Here's a link: http://sourceforge.net/projects/pywin32/ - Mike From ckaynor at zindagigames.com Mon Aug 31 15:51:59 2009 From: ckaynor at zindagigames.com (Chris Kaynor) Date: Mon, 31 Aug 2009 12:51:59 -0700 Subject: win32ui DLL Load Failed In-Reply-To: References: Message-ID: You likely need to install the Microsoft Visual C++ 2008 SP1 Redistributable Package on the target machine. If you search Google for this, you should find it (make sure to grab the correct version of x86 or x64 depending upon the Python version). Chris On Mon, Aug 31, 2009 at 12:43 PM, MikeC wrote: > I have a python executable that's failing to load on a user's machine > running Windows XP. My developer machine is also running Windows XP. I > have determined that it is failing when it attempts to load win32ui. > > I have Python 2.6 on my developer machine and am using the pywin > support (Mark Hammonds???) for Python 2.6. > > In order to make the problem smaller and more managable I created an > executable (with pytoexe) of a 1 one-line python script which does the > following: > > import win32ui > > Running the one-line script on my machine from python source as well > as from the executable created from the one-line source works fine on > my machine. But when I attempt to run the executable on a target > Windows/XP user machine (without Python) it fails with the following > traceback > > Traceback (most recent call last): > File "CheckScan.py", line 7, in > File "PrintImage.pyc", line 1, in > File "win32ui.pyc", line 12, in > File "win32ui.pyc", line 10, in __load > ImportError: DLL load failed: This application has failed to start > because the application configuration is incorrect. Reinstalling the > application may fix this problem. > > The only thing I can think of regarding the difference between my > machine and the target machine is that I have the .NET framework on my > machine. Is it possible that that is the problem? Running Depends > didn't get me anywhere. I would appreciate any help you can offer. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From nobody at nowhere.com Mon Aug 31 16:20:55 2009 From: nobody at nowhere.com (Nobody) Date: Mon, 31 Aug 2009 21:20:55 +0100 Subject: map References: <777de4d8-e591-4d21-bbd0-b286105895bc@i18g2000pro.googlegroups.com> Message-ID: On Sun, 30 Aug 2009 21:55:52 -0700, elsa wrote: > say I have a list, myList. Now say I have a function with more than > one argument: > > myFunc(a, b='None') > > now, say I want to map myFunc onto myList, with always the same > argument for b, but iterating over a: > > map(myFunc(b='booHoo'), myList) > > Why doesn't this work? You're passing the result of (incorrectly) calling myFunc to map(), but you need to pass a function. > is there a way to make it work? If you need to construct a simple function on-the-fly, you can use a lambda form: map(lambda x: myFunc(x, b='booHoo'), myList) Or you could use a list comprehension: [myFunc(x, b='booHoo') for x in myList] From zuo at chopin.edu.pl Mon Aug 31 16:28:56 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Mon, 31 Aug 2009 22:28:56 +0200 Subject: Efficient way to sum a product of numbers... In-Reply-To: <4A9BFAA3.3000308@tim.thechases.com> References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> <4A9BFAA3.3000308@tim.thechases.com> Message-ID: 31-08-2009 o 18:19:28 vsoler wrote: > Say > m= [[ 'a', 1], [ 'b', 2],[ 'a', 3]] > r={'a':4, 'b':5, 'c':6} > > What I need is the calculation > > 1*4 + 2*5 + 3*4 = 4 + 10 + 12 = 26 > > That is, for each row list in variable 'm' look for its first element > in variable 'r' and multiply the value found by the second element in > row 'm'. After that, sum all the products. > > What's an efficient way to do it? I have thousands of these > calculations to make on a big data file. 31-08-2009 o 18:30:27 Tim Chase wrote: > result = sum(v * r[k] for k,v in m) You can also check if this isn't more efficient: from itertools import starmap from operator import mul result = sum(starmap(mul, ((r[name], hour) for name, hour in m))) Or, if you had m in form of two lists: names = ['a', 'b', 'a'] hours = [1, 2, 3] ...then you could do: from itertools import imap as map # <- remove if you use Py3.x from operator import mul result = sum(map(mul, map(r.__getitem__, names), hours)) Cheers, *j PS. I've done a quick test on my computer (Pentium 4, 2.4Ghz, Linux): >>> setup = "from itertools import starmap, imap ; from operator import >>> mul; import random, string; names = >>> [rndom.choice(string.ascii_letters) for x in xrange(10000)]; hours = >>> [random.randint(1, 12) for x in xrange(1000)]; m = zip(names, hours); >>> workers = set(names); r = dict(zip(workers, (random.randint(1, 10) for >>> x in xrange(en(workers)))))" >>> tests = ( ... 'sum(v * r[k] for k,v in m)', ... 'sum(starmap(mul, ((r[name], hour) for name, hour in m)))', ... 'sum(imap(mul, imap(r.__getitem__, names), hours))', ... ) >>> for t in tests: ... print t ... timeit.repeat(t, setup, number=1000) ... print ... sum(v * r[k] for k,v in m) [6.2493009567260742, 6.1892399787902832, 6.2634339332580566] sum(starmap(mul, ((r[name], hour) for name, hour in m))) [9.3293819427490234, 10.280816078186035, 9.2766909599304199] sum(imap(mul, imap(r.__getitem__, names), hours)) [5.7341709136962891, 5.5898380279541016, 5.7318859100341797] -- Jan Kaliszewski (zuo) From andre.roberge at gmail.com Mon Aug 31 16:35:25 2009 From: andre.roberge at gmail.com (=?ISO-8859-1?Q?Andr=E9?=) Date: Mon, 31 Aug 2009 13:35:25 -0700 (PDT) Subject: pyjamas in action? References: Message-ID: <09fc970b-febe-4c73-9443-e10550bca916@j19g2000vbp.googlegroups.com> On Aug 31, 4:46?pm, kj wrote: > At work we want to implement a webapp using Google's GWT, and we're > debating whether to use the standard GWT approach with Java, or to > try Pyjamas. ?There's no great love here for Java, but there's the > concern that Pyjamas will not be able to deliver the full power > and/or convenience of standard Java-based GWT. ?(Why-oh-why did > Google pick Java for this? ?Couldn't Guido twist some arms? ?Just > kidding.) > > Are there any examples of real production websites implemented with > Pyjamas? > > TIA! > > kynn Perhaps you might get answers faster if you posted to the pyjamas group: http://groups.google.com/group/pyjamas-dev Andr? From mcravitz at att.net Mon Aug 31 16:36:25 2009 From: mcravitz at att.net (MikeC) Date: Mon, 31 Aug 2009 13:36:25 -0700 (PDT) Subject: win32ui DLL Load Failed References: Message-ID: <19449021-bcd4-4917-867f-882b9b586467@p36g2000prn.googlegroups.com> On Aug 31, 12:43?pm, MikeC wrote: > I have a python executable that's failing to load on a user's machine > running Windows XP. My developer machine is also running Windows XP. I > have determined that it is failing when it attempts to load win32ui. > > I have Python 2.6 on my developer machine and am using the pywin > support (Mark Hammonds???) for Python 2.6. > > In order to make the problem smaller and more managable I created an > executable (with pytoexe) of a 1 one-line python script which does the > following: > > import win32ui > > Running the one-line script on my machine from python source as well > as from the executable created from the one-line source works fine on > my machine. But when I attempt to run the executable on a target > Windows/XP user machine (without Python) it fails with the following > traceback > > Traceback (most recent call last): > ? File "CheckScan.py", line 7, in > ? File "PrintImage.pyc", line 1, in > ? File "win32ui.pyc", line 12, in > ? File "win32ui.pyc", line 10, in __load > ImportError: DLL load failed: This application has failed to start > because the application configuration is incorrect. Reinstalling the > application may fix this problem. > > The only thing I can think of regarding the difference between my > machine and the target machine is that I have the .NET framework on my > machine. Is it possible that that is the problem? Running Depends > didn't get me anywhere. I would appreciate any help you can offer. I assume you're asking about my development machine. Yes I have it installed. When I bring up PythonWin.exe, here is what is displayed at the top of the main dialog. PythonWin 2.6.1 (r261:67517, Dec 4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. From zuo at chopin.edu.pl Mon Aug 31 16:40:51 2009 From: zuo at chopin.edu.pl (Jan Kaliszewski) Date: Mon, 31 Aug 2009 22:40:51 +0200 Subject: Efficient way to sum a product of numbers... In-Reply-To: References: <73c1558e-8103-431a-9830-dead8024200b@p23g2000vbl.googlegroups.com> <4A9BFAA3.3000308@tim.thechases.com> Message-ID: 31-08-2009 o 22:28:56 Jan Kaliszewski wrote: > >>> setup = "from itertools import starmap, imap ; from operator > import mul; import random, string; names = [rndom.choice(string. > ascii_letters) for x in xrange(10000)]; hours = [random.randint( > 1, 12) for x in xrange(1000)]; m = zip(names, hours); workers = > set(names); r = dict(zip(workers, (random.randint(1, 10) for x i > n xrange(en(workers)))))" Erratum -- should be: >>> setup = ( ... 'from itertools import starmap, imap;' ... 'from operator import mul;' ... 'import random, string; names' ... ' = [random.choice(string.ascii_letters)' ... ' for x in xrange(10000)];' ... 'hours = [random.randint(1, 12)' ... for x in xrange(10000)];' ... 'm = zip(names, hours);' ... 'workers = set(names);' ... 'r = dict(zip(workers, (random.randint(1, 10)' ... ' for x in xrange(len(workers)))))' ... ) -- Jan Kaliszewski (zuo) From ethan at stoneleaf.us Mon Aug 31 18:07:02 2009 From: ethan at stoneleaf.us (Ethan Furman) Date: Mon, 31 Aug 2009 15:07:02 -0700 Subject: Object Reference question In-Reply-To: References: <2dcf41c3-6623-48d9-bb74-97f753088479@c34g2000yqi.googlegroups.com> <9feee13c-117e-4806-b238-e4152a68adfb@18g2000yqa.googlegroups.com> Message-ID: <4A9C4986.3010405@stoneleaf.us> josef wrote: > On Aug 27, 1:35 pm, Ethan Furman wrote: > >>josef wrote: >> >>>Thanks to everyone who responded. >> >>>I will be going with some sort of a = MyClass(name = 'a') format. It's >>>the Python way. >> >>>For me, it was very hard to accept that EVERYTHING is an object >>>reference. And that there are no object reference names, just string >>>entries in dictionaries. But I think it all makes sense now. >> >>>Thanks again, >> >>>Josef >> >>My apologies if I missed it, but what *exactly* are you planning on >>doing with your 'name' attribute? From the posts I've seen so far, I >>think you are only setting yourself up for failure. >> >>~Ethan~ > > > I'm going to use it for printing purposes. dk = MyClass(name='dk') > When I need a name dk.name. There will only ever be one dk defined. > > Does that read like I'm setting myself up for failure? I was hoping someone with more expertise than myself would answer that. :) Oh well. The best answer I can give is that you do not want to use 'name' to reference the object itself, but only for printing/debugging purposes. 'name' is just a label for your object, and not necessarily the only label; that particular label may also be lost... Consider: In [5]: class MyClass(object): ...: def __init__(self, name): ...: self.name = name ...: def __repr__(self): ...: return "MyClass(name='%s')" % self.name ...: In [6]: dk = MyClass(name='dk') In [7]: dk Out[7]: MyClass(name='dk') In [8]: se = dk In [9]: del dk In [10]: se Out[10]: MyClass(name='dk') In [11]: dk ------------------------------------------------------------------- NameError Traceback (most recent call last) C:\pythonlib\ in () NameError: name 'dk' is not defined As you can see, just because you have saved the original name does not gaurantee that same name will always reference that same object, or any object. Hope this helps! ~Ethan~ From rhodri at wildebst.demon.co.uk Mon Aug 31 18:40:12 2009 From: rhodri at wildebst.demon.co.uk (Rhodri James) Date: Mon, 31 Aug 2009 23:40:12 +0100 Subject: lambda functions In-Reply-To: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> References: <5369eaa8-bcda-44e0-90c3-8972f2b1eb91@g23g2000vbr.googlegroups.com> Message-ID: On Mon, 31 Aug 2009 08:41:57 +0100, Pierre wrote: > Hello, > > I would like to know if it is possible to define a loop in a lambda > function.... > > How to manage the indents ? Example : > s_minus_1 = lambda s : for index in range(0, len(s)) : s[index] = s > [index]-1 You can't use commands in a lambda function, only expressions. The nearest thing I can think of to what you want here is to use a list comprehension: s_minus_1 = lambda s : [i-1 for i in s] my_list = s_minus_1(my_list) On the other hand, giving a name to an anonymous function rather defeats the point of it being an *anonymous* function! What are you actually trying to do here? There's almost certainly a better way to do it than this. -- Rhodri James *-* Wildebeest Herder to the Masses From bh at izb.knu.ac.kr Mon Aug 31 19:15:53 2009 From: bh at izb.knu.ac.kr (Byung-Hee HWANG) Date: Tue, 01 Sep 2009 08:15:53 +0900 Subject: An assessment of the Unicode standard References: <2ad2272a-e016-4c07-92cf-39f7823acf05@o35g2000vbi.googlegroups.com> <3e9ddb9b-8f61-4d8d-a25c-7e95e8a25c06@g1g2000vbr.googlegroups.com> <200908311019.58029.hendrik@microcorp.co.za> Message-ID: <86tyzninh2.fsf@betla.izb.knu.ac.kr> Nigel Rantor writes: > Hendrik van Rooyen wrote: >> On Sunday 30 August 2009 22:46:49 Dennis Lee Bieber wrote: >> >>> Rather elitist viewpoint... Why don't we just drop nukes on some 60% >>> of populated landmasses that don't have a "western" culture and avoid >>> the whole problem? >> >> Now yer talking, boyo! It will surely help with the basic problem >> which is the heavy infestation of people on the planet! >> :-) > > > On two conditions: > > 1) We drop some "test" bombs on Slough to satisfy Betjeman. > > 2) We strap both Xah and r to aforementioned bombs. > > > > Also, I'm surprised no-one has mentioned Esperanto yet. Sounds like > something r and Xah would *love*. > > Slightly off-topic - does anyone have a good recipe for getting > thunderbird to kill whole threads for good? Either based on a rule or > just some extension I can use? > > The Xah/r threads are like car crashes, I can't help but watch but my > time could be better spent and I don't want to unsub the whole list. > Please do not insult Xah. He spoke nothing in this threads. -- "After the divorce I gave Ginny and the kids more than the courts said I should." -- Johnny Fontane, "Chapter 1", page 36 From ecir.hana at gmail.com Mon Aug 31 19:29:45 2009 From: ecir.hana at gmail.com (Ecir Hana) Date: Mon, 31 Aug 2009 16:29:45 -0700 (PDT) Subject: Executing python script stored as a string Message-ID: <720b423c-7058-4605-96a0-b62f56aec791@s6g2000vbp.googlegroups.com> Hello, please, how to execute a python script stored as a string? But let me impose several limitations, so simple "exec" wont work: - if I understood it correctly defining a function in the string and exec-ing it created the function in current scope. This is something I really don't want - simple exec also blocks the rest of the program - I also would like the string to be able to use and return some parts of the caller So to give an example what I try to achieve: result = [] def up(s): result.append(s.upper()) code = ''' up("abc") print 'hello' i = i + 3 def x(s): up(s) x('def') print i ''' somehow_execute(code) Couple of points: - the script in string should behave just like any other ordinary python script executed in separate process, except it should also know about a function caller "up". Nothing else. (I read that something similar is possible while embedding python into your C project - that you could invoke the VM and provide some default "imports") - if the other script runs in separate process how should it call the remote function? And how to pass its arguments? I really hope I don't have to serialize every communication, maybe I should use threading instead of process? All I want is that running it wont block the caller and that it cannot modify callers code/variables/scope (apart from calling the predefined callers' functions). Or maybe even better, let it block the caller but provide a way to stop its execution? - how to know that the script finished? I was thinking about atexit() - could it work here? Think of it as a text editor with a special ability to execute its content, while providing access of some of its functionality to the script. The reason I *think* I cannot just simple import the "editor" module into the script is that the"editor" is GUI application and script should have access to just this instance of editor. Anyway, I hope I was not too confusing. Thanks for any help! From steve at REMOVE-THIS-cybersource.com.au Mon Aug 31 19:31:14 2009 From: steve at REMOVE-THIS-cybersource.com.au (Steven D'Aprano) Date: 31 Aug 2009 23:31:14 GMT Subject: Is behavior of += intentional for int? References: Message-ID: <0025e0c6$0$2930$c3e8da3@news.astraweb.com> On Mon, 31 Aug 2009 10:21:22 -0700, zaur wrote: > As a result of this debate is not whether we should conclude that there > should be two types of integers in python: 1) immutable numbers, which > behave as constant value; 2) mutable numbers, which behave as variable > value? What can you do with mutable numbers that you can't do with immutable ones, and why do you want to do it? -- Steven From aahz at pythoncraft.com Mon Aug 31 19:52:35 2009 From: aahz at pythoncraft.com (Aahz) Date: 31 Aug 2009 16:52:35 -0700 Subject: a popen question. Please help References: <473423.84282.qm@web36903.mail.mud.yahoo.com> <4A9A65D7.4020308@tim.thechases.com> <50697b2c0908300449i65d22994ra6d63b0bbdb1d201@mail.gmail.com> Message-ID: In article , Tim Chase wrote: > >Darn "standards" :-/ The wonderful thing about standards is that there are so many to choose from. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From aahz at pythoncraft.com Mon Aug 31 20:00:31 2009 From: aahz at pythoncraft.com (Aahz) Date: 31 Aug 2009 17:00:31 -0700 Subject: Overriding iadd for dictionary like objects References: Message-ID: In article , RunThePun wrote: >On Aug 30, 10:33=A0pm, a... at pythoncraft.com (Aahz) wrote: >> In article .com>, >> RunThePun =A0 wrote: >>> >>>I made a DictMixin where the keys are filenames and the values are the >>>file contents. It was very simple and easy to do thanks to DictMixin. >>> >>>For example this code writes "abc" in a file named "temp.txt" and >>>prints the contents of the file named "swallow", these files are >>>looked up/created/deleted in the directory "spam": >>>>>> d =3D3D FilesDict('spam') >>>>>> d['temp.txt'] =3D3D 'abc' >>>>>> print(d['swallow']) >>> >>>My problem arose when I wanted to append a string to a file which >>>using open(..., 'ab') would have been miles more efficient because I >>>wouldn't have to read the entire file (__getitem__) and then write the >>>entire file back (__setitem__). The files are expected to be as big as >>>600 KB which will be appended 30 bytes at a time about 3 times a >>>second. Performance-wise the system would probably work without open >>>(..., 'ab') but it would be a real thrashing so the current solution >>>uses a method "AddTo" as Robert suggested, sacrificing the neat >>>getitem/setitem syntax. >> >> You can do mostly what you want, I think, by having __setitem__() >> convert string values into FileProxy() objects that have an appropriate >> __iadd__() method. =A0That brings a whole new set of problems, of course. > >I'm guessing you meant __getitem__, which is what Jan Kaliszewski >suggested, but as you noted, would be a bit cumbersome in this case. Actually, what I meant was __setitem__. The idea is that you create the proxy item when you add the data to the dict (wrapping the original data), and the proxy has an __iadd__ method, which would allow you to do the file append. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I support family values -- Addams family values" --www.nancybuttons.com From trinh.vo at jpl.nasa.gov Mon Aug 31 21:32:26 2009 From: trinh.vo at jpl.nasa.gov (Vo, Trinh (388C)) Date: Mon, 31 Aug 2009 18:32:26 -0700 Subject: Python installation Message-ID: <63E24D720DCE7246ABAA722B52D23CDF0153D3073233@ALTPHYEMBEVSP10.RES.AD.JPL> Hello Python Users, I am new to Python. I have errors message when I installed Python. I appreciate if you can help. I download Python-2.6-2. I then did the following steps: ./configure make In the second step "make", I had the following message: Failed to find the necessary bits to build these modules: _bsddb _curses _curses_panel _hashlib _sqlite3 _ssl _tkinter bsddb185 bz2 dbm dl gdbm imageop readline sunaudiodev To find the necessary bits, look in setup.py in detect_modules() for the module's name. I however still saw the binary python was installed in /usr/local/Python-2.6.2. I tested, and it till run OK. However, I am worried if the above message can cause any problem in the future. I have on my cluster: X86_64 GCC version 4.1.2 (Red Hat 4.1.2-42) Thank you, Trinh Vo -------------- next part -------------- An HTML attachment was scrubbed... URL: From benjamin.kaplan at case.edu Mon Aug 31 22:26:26 2009 From: benjamin.kaplan at case.edu (Benjamin Kaplan) Date: Mon, 31 Aug 2009 22:26:26 -0400 Subject: Python installation In-Reply-To: <63E24D720DCE7246ABAA722B52D23CDF0153D3073233@ALTPHYEMBEVSP10.RES.AD.JPL> References: <63E24D720DCE7246ABAA722B52D23CDF0153D3073233@ALTPHYEMBEVSP10.RES.AD.JPL> Message-ID: On Mon, Aug 31, 2009 at 9:32 PM, Vo, Trinh (388C) wrote: > Hello Python Users, > > > > I am new to Python.? I have errors message when I installed Python.? I > appreciate if you can help. > > > > I download Python-2.6-2.? I then did the following steps: > > ./configure > > make > > > > In the second step ?make?, I had the following message: > > > > > > Failed to find the necessary bits to build these modules: > > _bsddb???????????? _curses??????????? _curses_panel > > _hashlib?????????? _sqlite3?????????? _ssl > > _tkinter?????????? bsddb185?????????? bz2 > > dbm??????????????? dl???????????????? gdbm > > imageop??????????? readline?????????? sunaudiodev > > To find the necessary bits, look in setup.py in detect_modules() for the > module's name. > > I however still saw the binary python was installed in > /usr/local/Python-2.6.2.? I tested, and it till run OK.? However, I am > worried if the above message can cause any problem in ?the future.? I have > on my cluster: > > X86_64 > > GCC version 4.1.2 ?(Red Hat 4.1.2-42) > It's only a problem if you want to use those modules. Personally, I would rebuild it with some more of those (just install those libraries and the dev versions if red hat keeps them separate) but Python can run fine without them. > > > Thank you, > > > > Trinh Vo > > -- > http://mail.python.org/mailman/listinfo/python-list > > From terry.yinzhe at gmail.com Mon Aug 31 22:37:10 2009 From: terry.yinzhe at gmail.com (Terry) Date: Mon, 31 Aug 2009 19:37:10 -0700 (PDT) Subject: Return value of multiprocessing manager registerred function References: <4337084f-cf9b-4b9c-a0cc-ba8f0821f31a@v15g2000prn.googlegroups.com> Message-ID: <69078aec-d556-4a7b-963e-373fe0b39c9e@b18g2000vbl.googlegroups.com> On Aug 31, 5:58?pm, jacopo wrote: > Hi Terry, > I have just started working on similar things and I am strugling to > find examples or documentations. So far I have found only the official > documentation of the multiprocessing package. Would you be able to > recommend me some good reference or a book. I dont want to overwhelm > this newsgroup with questions... yet :) > Regards, Jacopo > > On Aug 26, 4:22?am, Terry wrote: > > > > > Hi, > > > I'm using the multiprocessing.manager to run proceduresremotely. It > > all worked fine except I hope to have a different return value type. > > > The remote function calls always return a proxy, which when I need to > > get the value it need to connect to the manager again to fetch it. But > > I just need the value, not the proxy. > > > Can I just return the value instead of a proxy from a manager? > > > br, Terry Hi Jacopo, Well, I also have had a hard time to find any examples or document except the official document. I had to read the multiprocessing source code (they are all in python except the network connection parts). And I found I need to hack it a little to get it work. You can share your questions, and maybe it's common to most of us. br, Terry From terry.yinzhe at gmail.com Mon Aug 31 22:41:26 2009 From: terry.yinzhe at gmail.com (Terry) Date: Mon, 31 Aug 2009 19:41:26 -0700 (PDT) Subject: multiprocessing managers and socket connection. References: <722664f1-81af-45da-ae40-070bca8f3ee0@k6g2000yqn.googlegroups.com> <0af6687a-e36d-47c3-af5e-7e66eacbb3ce@v23g2000pro.googlegroups.com> <7d8f3f17-3cd7-4eb1-b049-2990d638cc46@o6g2000yqj.googlegroups.com> Message-ID: <6be90391-085f-4ba1-9ed4-88f77ad11c2d@e18g2000vbe.googlegroups.com> On Aug 26, 7:25?pm, Chris wrote: > On Aug 25, 9:11?pm, Terry wrote: > > > > > > > On Aug 25, 10:14?pm, Chris wrote: > > > > I've been using multiprocessing managers and I really like the > > > functionality. > > > > I have a question about reconnecting to a manager. I have a situation > > > where I start on one machine (A) a manager that is listening and then > > > on another machine (B) connects to that manager and uses its proxy > > > object to call functions on the manager's computer; this all works as > > > expected. But, if the manager from A shuts down, B's application won't > > > notice because in the MP code it ignores socket error > > > errno.ECONNREFUSED. If A becomes available again or is restarted, B > > > doesn't automatically reconnect either and continue its operation. > > > It's function is basically stopped. > > > > Here is the code from connection.py: > > > while 1: > > > ? ? ? ? try: > > > ? ? ? ? ? ? s.connect(address) > > > ? ? ? ? except socket.error, e: > > > ? ? ? ? ? ? if e.args[0] != errno.ECONNREFUSED: # connection refused > > > ? ? ? ? ? ? ? ? debug('failed to connect to address %s', address) > > > ? ? ? ? ? ? ? ? raise > > > ? ? ? ? ? ? time.sleep(0.01) > > > ? ? ? ? else: > > > ? ? ? ? ? ? break > > > > How can I have B automatically reconnect to A and continue its work > > > once A is available again? > > > I think you need to retry repeatedly until successfully connected. > > > br, Terry > > I'm having issue after once connected. If the server goes down during > a long-running connection. I would want to be notified so I could try > to reconnect. I'm doing more experimenting now and will try to post an > example. Hi Chris, Are you sure that the proxy object keeps a permanent connection to the server? br, Terry From 71david at libero.it Mon Aug 31 23:06:14 2009 From: 71david at libero.it (David) Date: Tue, 1 Sep 2009 05:06:14 +0200 Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> <171zfm8mhuokq.1e4ltdmqqfp01.dlg@40tude.net> Message-ID: <121ziuuxjq6wq$.1vey8y61a3y3s$.dlg@40tude.net> Il Mon, 31 Aug 2009 21:04:27 +0200, David ha scritto: > Obviously the owner can not be charged I mean: can not be jailed for crimes made by the thief using his car. D. From rt8396 at gmail.com Mon Aug 31 23:06:54 2009 From: rt8396 at gmail.com (r) Date: Mon, 31 Aug 2009 20:06:54 -0700 (PDT) Subject: Why does this group have so much spam? References: <7294bf8b-9819-4b6d-92b2-afc1c8042a06@x6g2000prc.googlegroups.com> <7l1wem586nhf.c8spq9wpqg99.dlg@40tude.net> <171zfm8mhuokq.1e4ltdmqqfp01.dlg@40tude.net> Message-ID: On Aug 31, 2:04?pm, David <71da... at libero.it> wrote: (snip) > It's a question of point of view: in italy if a thief steals a car and > causes an accident the car's owner's assurance (having a car assurance is > mandatory) must refund the victims. That's because protections of victims is > first priority. > Obviously the owner can not be charged Is the car owner not a victim too? :). i am ok with the filthy insurance company paying as long as the owners rates don't increase. But why can't we force the criminal into hard labor to pay back the lost monies? Seems like that would serve justice to all parties... > That's a problem of the computer owner. Why should the rest of the world be > charged of *his* problem while keeping him safe from suffering any > consequence? No, why should spammers feel safe while doing their crimes? I say put the pressure on criminals, and NOT the victims. I really doubt much is being done to fight spam now that is why it is so prevalent. Two FBI hackers can't keep up with billions of spams. > Madness, you say? Let's examine the situation a bit moore deeply. > > First, the mail-tax would is not for rebuilding the destroyed building after > the attack but, at the opposite, to prevent the attack. Wouldn't you pay a > small tax to prevent terrorist's attacks? Only if that tax was given to highly trained US Marines who where given a green light to use any and all methods to brutally kill the enemy and make an example of him with no worry of prosecution by their own government. > The mail-tax would be really small, if you send 1000 mails at month (a real > huge traffic, for a non spammer!) the bill would be about 10 cents. > Do you really think this is too much to get rid of most of the spam? I don't think that will stop most spammers since they must be making more that a 10c a month profit or they would starve to death! I say why not put a 1000.00 fine on any idiot that responds to a spam! What about that? > We are paying and hidden tax in terms of HW and human resources needed by > ISPs to manage that huge (~90%) useless/malicius traffic. (I don't mention > const related to dalays, denial of services, theft of informations...) (...snip) The system is definitely flawed. I am no internet expert so i don't really know what we could do to fix it. I do fear goverment or corporations taking over of the internet and robbing use of our freedom of speech under the pretense that they will *somehow* save us from the spammers. Something must be done however. I *do* know however that M$ windows ships with its back doors wide open and you could put a lot of blame of M$ for this stupidity! And since their product is meant for computing morons why do they still ship it in such a vulnerable state... complete madness! > Finally a little criticims: spam and related malware is a problem growing > day by day. I am proposing a solution and if somebody doest't like it, well, > he should propose a better one. Just saying "NO!" and turning head aside > hoping that the problem will solve by itsef is no more acceptable. (snip) I agree with you, we must do something... From steven at REMOVE.THIS.cybersource.com.au Mon Aug 31 23:31:35 2009 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 01 Sep 2009 03:31:35 GMT Subject: Executing python script stored as a string References: <720b423c-7058-4605-96a0-b62f56aec791@s6g2000vbp.googlegroups.com> Message-ID: On Mon, 31 Aug 2009 16:29:45 -0700, Ecir Hana wrote: > Hello, > > please, how to execute a python script stored as a string? But let me > impose several limitations, so simple "exec" wont work: > > - if I understood it correctly defining a function in the string and > exec-ing it created the function in current scope. This is something I > really don't want You can pass in a global and local namespaces to exec as arguments: >>> x = 4 >>> ns = {'x': 4} >>> exec "x += 1" in ns >>> x 4 >>> ns['x'] 5 See the docs for details. > - simple exec also blocks the rest of the program Run it in a thread. > - I also would like the string to be able to use and return some parts > of the caller You can copy the parts of the current scope into the namespace you pass to exec, then later copy the revised values out again. But are you sure you really want to take this approach? exec is up to ten times slower than just executing the code directly. And if the string is coming from an untrusted source, it is a *huge* security risk. > Couple of points: > > - the script in string should behave just like any other ordinary python > script executed in separate process, except it should also know about a > function caller "up". Nothing else. (I read that something similar is > possible while embedding python into your C project - that you could > invoke the VM and provide some default "imports") If you want it to execute in a separate *process*, that's a whole different question. If you do that, you get separation of code for free, as well as separate namespaces. My approach would be to have a special module "common" which subprocesses can import, to get access to the shared functions. You will probably need to create some sort of message passing infrastructure to get results out of the subprocess into the parent process. > - if the other script runs in separate process how should it call the > remote function? And how to pass its arguments? I really hope I don't > have to serialize every communication, maybe I should use threading > instead of process? If you want separate processes, they're *separate*. Threads are not. > All I want is that running it wont block the caller > and that it cannot modify callers code/variables/scope (apart from > calling the predefined callers' functions). Or maybe even better, let it > block the caller but provide a way to stop its execution? As far as I know, you can't kill threads, you can only ask them to kill themselves. > - how to know that the script finished? I was thinking about atexit() - > could it work here? I doubt it. You would need to poll each thread to see if it has completed. > Think of it as a text editor with a special ability to execute its > content, while providing access of some of its functionality to the > script. Something like this? In the text editor, you have contents: text goes here and more text # Python script starts here x = 'a' up(x) print "foo" # Python script stops here more text again and the user selects lines 4 and 5 and chooses the command "Execute". The script executes, and its output (foo) is appended to the end of the file: text goes here and more text # Python script starts here x = 'a' up(x) print "foo" # Python script stops here more text again foo Is this what you mean? If so, I think you are making this much too complicated for such a simple use-case. Just publish an API which the script can use, and have the main text editor application specify a "script" namespace containing only that API. That could be a module: >>> import math # pretend this is your API shared module >>> exec "myvalue = 42" in math.__dict__ >>> math.myvalue 42 Then execute the text using exec, but don't bother about putting it into a thread or subprocess. That just makes it harder to implement, and you have to worry about concurrency issues. -- Steven